Files
shannon/src/cli/command-handler.js
T
ajmallesh d372f87297 refactor: remove ~500 lines of dead code and consolidate duplicates
Comprehensive codebase cleanup based on parallel agent analysis and automated
dead code detection (knip, depcheck). Reduces codebase by ~10% with zero
functional changes.

## Phase 1: Obsolete MCP Setup Removal (~82 lines)
- Delete setupMCP() and cleanupMCP() functions from environment.js
- Remove all calls to cleanupMCP() (8 instances across 3 files)
- Migrate from claude CLI to SDK's mcpServers option
- Remove --log flag (obsolete logging system)

## Phase 2: Dead Code Removal (~317 lines)
- Delete src/utils/logger.js entirely (127 lines, superseded by audit system)
- Remove handleConfigError() and handleError() from error-handling.js
- Remove isToolAvailable() from tool-checker.js
- Remove 5 dead methods from audit-session.js (logSessionFailure, logMessage,
  markRolledBack, updateValidation, getValidation)
- Remove 6 wrapper methods from audit/logger.js (all callers use logEvent directly)
- Remove formatCost(), updateMessage(), compose() utilities (unused)

## Phase 3: Consolidation (~195 lines)
- Extract SessionMutex to src/utils/concurrency.js (was duplicated in 2 files)
- Consolidate formatDuration to src/audit/utils.js (was in 3 files)
- Extract readline prompts to src/cli/prompts.js (was duplicated in 2 files)
- Create validator factories in constants.js (reduce 72 lines to 30)

## Impact
- Total reduction: 488 lines (20 files modified, 2 created, 1 deleted)
- Codebase: ~4,900 → ~4,400 LOC (10% reduction)
- Zero functional changes, all tests pass
- Improved maintainability and DRY compliance

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-23 17:01:17 -07:00

137 lines
4.9 KiB
JavaScript

import chalk from 'chalk';
import {
selectSession, deleteSession, deleteAllSessions,
validateAgent, validatePhase, reconcileSession
} from '../session-manager.js';
import {
runPhase, runAll, rollbackTo, rerunAgent, displayStatus, listAgents
} from '../checkpoint-manager.js';
import { logError, PentestError } from '../error-handling.js';
import { promptConfirmation } from './prompts.js';
// Developer command handlers
export async function handleDeveloperCommand(command, args, pipelineTestingMode, runClaudePromptWithRetry, loadPrompt) {
try {
let session;
// Commands that don't require session selection
if (command === '--list-agents') {
listAgents();
return;
}
if (command === '--cleanup') {
// Handle cleanup without needing session selection first
if (args[0]) {
// Cleanup specific session by ID
const sessionId = args[0];
const deletedSession = await deleteSession(sessionId);
console.log(chalk.green(`✅ Deleted session ${sessionId} (${new URL(deletedSession.webUrl).hostname})`));
} else {
// Cleanup all sessions - require confirmation
const confirmed = await promptConfirmation(chalk.yellow('⚠️ This will delete all pentest sessions. Are you sure? (y/N):'));
if (confirmed) {
const deleted = await deleteAllSessions();
if (deleted) {
console.log(chalk.green('✅ All sessions deleted'));
} else {
console.log(chalk.yellow('⚠️ No sessions found to delete'));
}
} else {
console.log(chalk.gray('Cleanup cancelled'));
}
}
return;
}
// Early validation for commands with agent names (before session selection)
if (command === '--run-phase') {
if (!args[0]) {
console.log(chalk.red('❌ --run-phase requires a phase name'));
console.log(chalk.gray('Usage: ./shannon.mjs --run-phase <phase-name>'));
process.exit(1);
}
validatePhase(args[0]); // This will throw PentestError if invalid
}
if (command === '--rollback-to' || command === '--rerun') {
if (!args[0]) {
console.log(chalk.red(`❌ ${command} requires an agent name`));
console.log(chalk.gray(`Usage: ./shannon.mjs ${command} <agent-name>`));
process.exit(1);
}
validateAgent(args[0]); // This will throw PentestError if invalid
}
// Get session for other commands
try {
session = await selectSession();
} catch (error) {
console.log(chalk.red(`❌ ${error.message}`));
process.exit(1);
}
// Self-healing: Reconcile session with audit logs before executing command
// This ensures Shannon store is consistent with audit data, even after crash recovery
try {
const reconcileReport = await reconcileSession(session.id);
if (reconcileReport.promotions.length > 0) {
console.log(chalk.blue(`🔄 Reconciled: Added ${reconcileReport.promotions.length} completed agents from audit logs`));
}
if (reconcileReport.demotions.length > 0) {
console.log(chalk.yellow(`🔄 Reconciled: Removed ${reconcileReport.demotions.length} rolled-back agents`));
}
if (reconcileReport.failures.length > 0) {
console.log(chalk.yellow(`🔄 Reconciled: Marked ${reconcileReport.failures.length} failed agents`));
}
// Reload session after reconciliation to get fresh state
const { getSession } = await import('../session-manager.js');
session = await getSession(session.id);
} catch (error) {
// Reconciliation failure is non-critical, but log warning
console.log(chalk.yellow(`⚠️ Failed to reconcile session with audit logs: ${error.message}`));
}
switch (command) {
case '--run-phase':
await runPhase(args[0], session, pipelineTestingMode, runClaudePromptWithRetry, loadPrompt);
break;
case '--run-all':
await runAll(session, pipelineTestingMode, runClaudePromptWithRetry, loadPrompt);
break;
case '--rollback-to':
await rollbackTo(args[0], session);
break;
case '--rerun':
await rerunAgent(args[0], session, pipelineTestingMode, runClaudePromptWithRetry, loadPrompt);
break;
case '--status':
await displayStatus(session);
break;
default:
console.log(chalk.red(`❌ Unknown developer command: ${command}`));
console.log(chalk.gray('Use --help to see available commands'));
process.exit(1);
}
} catch (error) {
if (error instanceof PentestError) {
await logError(error, `Developer command ${command}`);
console.log(chalk.red.bold(`\n🚨 Command failed: ${error.message}`));
} else {
console.log(chalk.red.bold(`\n🚨 Unexpected error: ${error.message}`));
if (process.env.DEBUG) {
console.log(chalk.gray(error.stack));
}
}
process.exit(1);
}
}