Imported from GeoloeG-IsT/agents-reverse-engineer (
src/cli/AGENTS.md). Install upstream withnpx skills add GeoloeG-IsT/agents-reverse-engineer --skill cli. Copyright stays with the author.
src/cli
Command-line interface entry points for all agents-reverse-engineer operations. Each file exports a command function consumed by the CLI router in index.ts, handling argument parsing, option validation, workflow orchestration, and exit code management.
Contents
Core Commands
index.ts — CLI entry point and command router. Exports main(), which parses arguments via parseArgs(), handles --version/--help flags, routes commands to handlers, and catches errors. Supports command shortcuts: zero-arg invocation launches interactive installer, direct installer flags (-g, -l, --runtime, --force) invoke runInstaller(). Version banner suppressed for installer and dashboard HTML/JSON output modes.
init.ts — Exports initCommand(root, { force }), which creates .agents-reverse-engineer/config.yaml via writeDefaultConfig(), updates .gitignore and .vscode/settings.json via ensureGitignoreEntry() and ensureVscodeExclude() to exclude *.sum artifacts. Exits with code 1 on permission errors.
clean.ts — Exports cleanCommand(targetPath, { dryRun }), which deletes generated artifacts (*.sum, AGENTS.md, CLAUDE.md, GENERATION-PLAN.md), removes ARE worktrees (registered via git worktree list --porcelain and orphaned under /tmp/{are-plan-*,are-impl-*}), and restores .local.md overrides via rename(). Uses fast-glob with patterns **/*.sum, **/AGENTS.md, **/AGENTS.*.md, **/CLAUDE.md; checks marker presence via GENERATED_MARKER_PREFIX before deletion. Dry-run mode previews changes without executing. Exits with code 1 on directory access errors.
Documentation Generation
discover.ts — Exports discoverCommand(targetPath, { showExcluded, debug, tracer }), which walks directory tree via discoverFiles(), applies gitignore/vendor/binary/custom filters, logs included/excluded files, generates post-order execution plan via buildExecutionPlan(), writes to .agents-reverse-engineer/GENERATION-PLAN.md via formatExecutionPlanAsMarkdown(). Emits discovery:start and discovery:end trace events with file counts and duration. Writes progress to .agents-reverse-engineer/logs/discover_*.log for tail -f monitoring.
generate.ts — Exports generateCommand(targetPath, GenerateOptions), which orchestrates full documentation generation: discovers files via discoverFiles(), creates GenerationPlan via createOrchestrator().createPlan(), resolves AI backend via resolveBackend(), builds ExecutionPlan via buildExecutionPlan(), executes two-phase pipeline (file analysis → directory aggregation) via CommandRunner.executeGenerate(). Supports eval mode: --eval flag computes variant ${backend}.${model}, passes to orchestrator for namespaced output (file.ts.claude.sonnet.sum). Dry-run mode prints plan without AI calls. Exits with code 2 if CLI not found, 1 if partial failure, 0 if success.
update.ts — Exports updateCommand(targetPath, UpdateOptions), which performs incremental updates: detects git changes via createUpdateOrchestrator().preparePlan(), analyzes modified files via CommandRunner.executeUpdate(), regenerates AGENTS.md for affected directories via buildDirectoryPrompt() and writeAgentsMd(). Supports eval mode with variant namespacing. First-run detection: if no baseline commit, prints hint to run are generate. Exits with code 2 if all files failed, 1 if partial failure, 0 if success.
Experimental Features
specify.ts — Exports specifyCommand(targetPath, SpecifyOptions), which synthesizes project specifications from AGENTS.md files: collects docs via collectAgentsDocs() and collectAnnexFiles(), auto-generates missing docs via generateCommand(), builds prompt via buildSpecPrompt(), calls AI with 900s minimum timeout, writes single or multi-file output via writeSpec(). Model selection upgrades sonnet to opus for specification quality. Early conflict detection scans for existing spec files before AI call (single file via access(), multi-file via readdir() filtering *.md). Dry-run mode estimates tokens (totalChars / 4 / 1000), warns if input exceeds 150K. Exits with code 1 if conflicts detected or SpecExistsError thrown, 2 if CLI not found.
rebuild.ts — Exports rebuildCommand(targetPath, RebuildOptions), which reconstructs projects from specifications: reads specs from specs/ via readSpecFiles(), partitions into rebuild units via partitionSpec(), executes with checkpoint-based resume via executeRebuild() and CheckpointManager, writes output to rebuild/ or custom directory. Model selection upgrades sonnet to opus, timeout extends to 900s minimum. Dry-run mode prints plan with checkpoint resume status. Exits with code 2 if zero processed and failures exist, 1 if partial failure, 0 if success.
plan.ts — Exports planCommand(task, targetPath, PlanOptions), which compares AI planning with/without ARE docs: creates git worktree pairs via createWorktreePair() with branch naming are/plan/{with-docs|without-docs}/{taskSlug}, strips artifacts from without-docs variant via stripArtifacts(), executes planning via executePlanRun() (without-docs first), commits results via commitPlanToWorktree(), evaluates via evaluatePlans() if --eval flag set, computes deltas (costDelta, latencyDelta, specificityRatio, actionabilityRatio, qualityScoreDelta), saves via saveComparison() with ID startTime.replace(/[:.]/g, '-'), renders via renderComparison(). Supports --list and --show <id> modes for comparison history.
implement.ts — Exports implementCommand(task, targetPath, ImplementOptions), which executes implementation comparison: reuses worktree pairs via reuseWorktreePair() or creates fresh from HEAD if plan-less, strips artifacts from without-docs variant via stripArtifacts() in plan-less mode, captures per-worktree HEAD as baseRef via git rev-parse HEAD after artifact stripping (excludes strip commit from diff), executes implementation via executeImplementation() (without-docs first), evaluates via evaluateImplementations() if --eval flag set, computes deltas (costDelta, latencyDelta, filesCreatedRatio, testPassingRatio, qualityScoreDelta), saves via saveComparison() with ID startTime.replace(/[:.]/g, '-'), renders via renderComparison(). Supports --list, --show <id>, --plan-id, --task-slug, --run-tests, --run-build, --run-lint modes. Plan text read from committed PLAN.md or fallback to disk via loadPlanText().
Architecture
Commands follow a consistent pattern: (1) resolve project root via findProjectRoot(), (2) load config via loadConfig(), (3) create trace writer via createTraceWriter() if --trace flag set, (4) resolve AI backend via createBackendRegistry() and resolveBackend(), (5) provision backend resources via backend.ensureProjectConfig(), (6) compute effective model (CLI flag > config, with upgrades for specify/rebuild), (7) instantiate AIService with extended timeout and subprocess CWD os.tmpdir(), (8) create ProgressLog for tail monitoring, (9) execute workflow via orchestrator/runner, (10) finalize telemetry via aiService.finalize(), (11) clean up traces via cleanupOldTraces(), (12) set exit code (0=success, 1=partial failure, 2=total failure/CLI not found).
Workflow & Conventions
Exit Codes:
- 0: all operations succeeded
- 1: partial failure (some files/tasks failed) or conflict detection (specify.ts)
- 2: total failure (CLI not found, no files processed)
Dry-Run Mode: All commands support --dry-run, which prints plan/preview without executing AI calls or file writes. Used for cost estimation and workflow validation.
Eval Mode: Commands supporting --eval flag compute variant ${backend}.${model}, pass to orchestrator for namespaced output (e.g., file.ts.claude.sonnet.sum, AGENTS.claude.sonnet.md). Used for backend/model comparison experiments.
Progress Monitoring: Commands write logs to .agents-reverse-engineer/logs/{command}-{backend}-{model}-{timestamp}.log for tail -f monitoring. Header includes project path, file/directory counts, timestamp.
Trace Output: Commands with --trace flag write NDJSON events to .agents-reverse-engineer/traces/, subprocess logs to .agents-reverse-engineer/subprocess-logs/{timestamp}/. Events include phase:start, phase:end, task:start, task:done with worker IDs, durations, success flags.
Model Upgrades: specify.ts and rebuild.ts upgrade default sonnet to opus for quality. Command-line --model flag overrides upgrade logic.
Timeout Extensions: specify.ts and rebuild.ts extend AI timeout to 900s minimum (Math.max(config.ai.timeoutMs, 900_000)) for long-running operations.
Checkpoint Resume: rebuild.ts uses CheckpointManager to save/restore progress after each module. Dry-run mode reports completion percentage and remaining modules.
Worktree Management: plan.ts creates worktree pairs with branch naming are/plan/{with-docs|without-docs}/{taskSlug}. implement.ts reuses branches are/plan/with-docs/{taskSlug}, are/plan/without-docs/{taskSlug} if plan exists, creates fresh pair from HEAD if plan-less. clean.ts removes registered worktrees via git worktree remove --force and orphaned /tmp/{are-plan-*,are-impl-*} directories via rm().
Artifact Stripping: plan.ts strips artifacts from without-docs worktree after creation via stripArtifacts(). implement.ts strips artifacts only in plan-less mode (plan branches are frozen).
User-Authored File Preservation: clean.ts checks GENERATED_MARKER_PREFIX before deleting AGENTS.md/CLAUDE.md. Files without marker logged as "user-authored" and skipped.
Local Override Restoration: clean.ts restores AGENTS.local.md → AGENTS.md and CLAUDE.local.md → CLAUDE.md via rename() after cleaning generated artifacts.
Comparison Storage: plan.ts and implement.ts generate comparison IDs from startTime.replace(/[:.]/g, '-'), save records via saveComparison() with branches, results, evaluation, deltas.