agents-reverse-engineer / src
AGENTS.md21 starsChanged 10 months agoMITView on GitHub
Root source directory for agents-reverse-engineer — exports programmatic API via core/index.ts, implements CLI commands via cli/, orchestrates AI-powered documentation generation via generation/ and orchestration/, provides quality validation via quality/, and supplies installer/integration tooling for AI coding assistants (Claude, OpenCode, Codex, Gemini). version.ts — Exports getVersion() to read package version from package.json. ai/ — AIService orchestrator and backend registry for spawning AI CLI subprocesses with exponential backoff retry, timeout enforcement, rate limit detection, and per-run telemetry logging. Implements multi-backend abstraction (Claude,…
Where files are headingNew AGENTS.md files have more rules about keeping secrets out of the code, and fewer about checking a change actually works.
Of the AGENTS.md files we read, the 11,736 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.
In this repository20 other files it gives its agents.
- AGENTS.mdAGENTS.md
- .github/workflows/AGENTS.mdAGENTS.md
- hooks/AGENTS.mdAGENTS.md
- scripts/AGENTS.mdAGENTS.md
- CLAUDE.mdCLAUDE.md
- .github/workflows/CLAUDE.mdCLAUDE.md
- hooks/CLAUDE.mdCLAUDE.md
- scripts/CLAUDE.mdCLAUDE.md
- src/CLAUDE.mdCLAUDE.md
- bumpSkill
- are-cleanSkill
- are-dashboardSkill
- are-discoverSkill
- are-generateSkill
- are-helpSkill
- are-implementSkill
- are-planSkill
- are-rebuildSkill
- are-specifySkill
- are-updateSkill
The file
We split this AGENTS.md into the rules it gives an agent
2 rules. About 0 are common, 0 are distinctive, and 2 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈0
Distinctive · estimate
This author's own choices. Worth a look.
2
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 137
Subprocess CWD Override: When spawning AI CLI subprocesses, set CWD to os.tmpdir() via AIService.setSubprocessCwd() to prevent AI CLIs …
- Very specific: line 141
Dry-Run Mode: All commands support --dry-run, which prints plan/preview without executing AI calls or file writes.
≈ “Common” is an estimate: at least 1 in 5 of the 16,597 AGENTS.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
<!-- Generated by agents-reverse-engineer v1.2.12 -->src
Root source directory for agents-reverse-engineer — exports programmatic API via core/index.ts, implements CLI commands via cli/, orchestrates AI-powered documentation generation via generation/ and orchestration/, provides quality validation via quality/, and supplies installer/integration tooling for AI coding assistants (Claude, OpenCode, Codex, Gemini).
Contents
version.ts — Exports getVersion() to read package version from package.json.
Subdirectories
ai/ — AIService orchestrator and backend registry for spawning AI CLI subprocesses with exponential backoff retry, timeout enforcement, rate limit detection, and per-run telemetry logging. Implements multi-backend abstraction (Claude, Codex, Gemini, OpenCode) with unified AIProvider/AIBackend interface, subprocess lifecycle management (SIGTERM→SIGKILL escalation), retry strategy (rate limits only, never timeouts), CWD override to prevent AI CLIs from discovering project context files that waste cache tokens.
change-detection/ — Provides git-based change detection and SHA-256 content hashing for incremental documentation updates. Uses simple-git for repository operations and Node.js crypto for file fingerprinting.
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. Commands: init, discover, generate, update, clean, specify, rebuild, plan, implement, dashboard.
config/ — Defines schemas, defaults, and loading logic for .agents-reverse-engineer/config.yaml, providing all configuration primitives (exclude patterns, concurrency, compression, backend selection) consumed by the orchestration and generation layers.
core/ — Core programmatic API barrel (index.ts) and logger abstraction (logger.ts) for agents-reverse-engineer engine — exports all reusable modules (AI, discovery, generation, orchestration, quality, change detection, config, imports) with @beta stability and zero forced console output for library consumers.
dashboard/ — Terminal-based telemetry dashboard for LLM API usage analytics: cost breakdowns, token metrics, execution timelines, and trend analysis from .agents-reverse-engineer/logs/ run logs and .agents-reverse-engineer/traces/ NDJSON files.
discovery/ — File discovery orchestration using fast-glob traversal and filter chain processing (gitignore, vendor, binary, custom patterns).
generation/ — Orchestrates AI-powered documentation generation by transforming file/directory discovery plans into dependency-ordered execution tasks that produce .sum file summaries and AGENTS.md aggregations via Claude prompts enforcing density, behavioral contract preservation, and incremental update semantics.
implement/ — Executes AI-driven code changes in isolated worktrees with and without ARE documentation, evaluates quality via blind comparison (randomized plan A/plan B presentation with five weighted criteria), persists metrics (git stats, test/build/lint results, cost/latency deltas, quality scores) to .agents-reverse-engineer/implementations/.
imports/ — Extracts and classifies TypeScript/JavaScript import statements from source files, producing structured import graphs for LLM context generation.
installer/ — Interactive TTY wizard and non-interactive CLI for installing agents-reverse-engineer command templates, hooks, and runtime integrations into global/local config directories, managing .gitignore/.vscode/settings.json entries, and uninstalling all artifacts with surgical precision.
integration/ — Orchestrates AI coding assistant integration by detecting environments (Claude Code, OpenCode, Aider, Gemini), generating runtime-specific command files from shared definitions, and installing hooks into config directories.
orchestration/ — Orchestrates two-phase AI-driven documentation generation (file analysis → directory aggregation) with concurrency pooling, progress tracking, quality validation, and NDJSON tracing for multi-worker task coordination.
output/ — Typed CLI logging with conditional ANSI formatting per CONTEXT.md human-readable output specification.
plan/ — A/B testing framework for AI planning quality: compares implementation plans generated with and without ARE documentation using parallel Git worktrees, quantitative metrics, and optional qualitative evaluation by a third AI judge.
quality/ — Detects documentation drift, code duplication, and phantom path references across the project by comparing TypeScript/JavaScript exports against .sum file documentation, identifying duplicate symbols across files, and validating AGENTS.md path references.
rebuild/ — Reconstructs project source code from specification documents through AI-driven code generation with ordered-phase execution, checkpoint-based resume, and context accumulation.
specify/ — Exports three-function specification generation pipeline: buildSpecPrompt constructs AI prompts from AGENTS.md docs + optional annex files → LLM produces spec markdown → writeSpec persists to single file or splits into slugified heading-based sections with SpecExistsError on collision.
types/ — TypeScript type definitions shared across discovery, file traversal, and exclusion reporting modules.
update/ — Incremental documentation synchronization: detects file changes, regenerates stale .sum files, removes orphaned documentation artifacts, and updates affected AGENTS.md files.
Architecture
Three-tier command execution model:
- CLI Layer (
cli/) — argument parsing, config loading, backend resolution, AI service provisioning, trace/log setup, workflow invocation, exit code management - Orchestration Layer (
orchestration/) — concurrency pooling via shared-iterator pattern, two-phase pipeline (file analysis → directory aggregation), quality validation (code-vs-doc, code-vs-code, phantom-paths), progress reporting, telemetry - Generation Layer (
generation/) — prompt construction (file/directory templates), .sum serialization (YAML frontmatter + summary), AGENTS.md aggregation, annex overflow handling, incremental update preservation
Discovery pipeline: discovery/walker.ts (fast-glob traversal) → discovery/filters/ (gitignore/vendor/binary/custom) → generation/executor.ts (execution plan) → orchestration/runner.ts (two-phase execution).
Quality pipeline: quality/inconsistency/code-vs-doc.ts (export-vs-.sum comparison) → quality/inconsistency/code-vs-code.ts (duplicate symbol detection) → quality/phantom-paths/validator.ts (AGENTS.md path validation) → quality/inconsistency/reporter.ts (aggregation, CLI/markdown formatting).
Telemetry pipeline: ai/telemetry/logger.ts (per-call entry accumulation) → ai/telemetry/run-log.ts (run log persistence) → orchestration/trace.ts (NDJSON event streaming) → dashboard/ (cost/token/trend visualization).
Stack
- Runtime: Node.js with TypeScript (tsconfig.json)
- AI Backends: Claude CLI, OpenAI Codex, Google Gemini, OpenCode (subprocess adapters in
ai/backends/) - File Traversal: fast-glob (walker.ts)
- Git Operations: simple-git (change-detection, plan worktrees, implement worktrees)
- YAML Parsing: Custom frontmatter regex in
generation/writers/sum.ts - JSONC Editing: jsonc-parser (installer settings.json merging)
- Markdown Rendering: Custom formatters in dashboard/views/, quality/inconsistency/reporter.ts
- NDJSON Streaming: readline for trace parsing (dashboard/trace-reader.ts)
- Chart.js: CDN-loaded for HTML reports (dashboard/html-report.ts)
API Surface
Programmatic API (via core/index.ts):
- Logger:
nullLogger,consoleLogger,Logger - AI:
AIService,AIProvider,AIBackend,SubprocessProvider,withRetry,DEFAULT_RETRY_OPTIONS - Discovery:
discoverFiles,walkDirectory,applyFilters,FileFilter,FilterResult - Generation Prompts:
buildFilePrompt,buildDirectoryPrompt,detectLanguage - Generation Writers:
writeSumFile,readSumFile,writeAgentsMd,writeAgentsMdHub,writeClaudeMdPointer - Orchestration:
DocumentationOrchestrator,buildExecutionPlan,formatExecutionPlanAsMarkdown,runPool - Quality:
extractExports,checkCodeVsDoc,checkCodeVsCode,checkPhantomPaths,buildInconsistencyReport - Change Detection:
computeContentHash,isGitRepo,getChangedFiles - Config:
loadConfig,findProjectRoot,Config - Imports:
extractImports,extractDirectoryImports,formatImportMap
CLI Commands (via cli/index.ts):
are init— create config, update .gitignore/.vscode/settings.jsonare discover— walk directory, generate GENERATION-PLAN.mdare generate— full two-phase documentation generationare update— incremental regeneration for changed filesare clean— delete .sum/AGENTS.md/CLAUDE.md artifactsare specify— synthesize spec from AGENTS.md docsare rebuild— reconstruct project from specare plan— A/B test planning with/without docsare implement— A/B test implementation with/without docsare dashboard— telemetry visualization (table/JSON/HTML/trends/timeline)
Behavioral Contracts
Exit Codes:
- 0 — all operations succeeded
- 1 — partial failure (some files/tasks failed)
- 2 — total failure (CLI not found, no files processed, conflict detection)
Retry Strategy: AIService retries only RATE_LIMIT errors (never TIMEOUT), uses exponential backoff with jitter, emits {type:'retry', attempt, taskLabel, errorCode} trace events.
Timeout Enforcement: runSubprocess() enforces timeoutMs with SIGTERM→SIGKILL escalation after 5s grace period, attempts process group kill before falling back to single process.
Concurrency Model: runPool() uses shared-iterator pattern (workers pull from tasks.entries() iterator), starts new task immediately when prior completes, avoiding batch-idle anti-pattern.
Checkpoint Resume: rebuild/checkpoint.ts tracks per-module status (pending/done/failed) with spec hash validation, supports resume from partial runs.
Progress Monitoring: Commands write logs to .agents-reverse-engineer/logs/{command}-{backend}-{model}-{timestamp}.log for tail -f monitoring, telemetry to .agents-reverse-engineer/logs/run-{command}-{backend}-{model}-{timestamp}.json.
Trace Output: Commands with --trace flag write NDJSON events to .agents-reverse-engineer/traces/trace-{timestamp}.ndjson, subprocess logs to .agents-reverse-engineer/subprocess-logs/{timestamp}/.
Variant Routing: variant parameter writes .${variant}.sum and AGENTS.${variant}.md, hub files import @AGENTS.${activeVariant}.md, variant files bypass user-preservation logic.
File Relationships
cli/index.tsroutes commands tocli/{command}.tscli/{command}.tsimports orchestrators fromorchestration/,generation/,plan/,implement/,specify/,rebuild/,update/orchestration/runner.tsimportsbuildFilePrompt/buildDirectoryPromptfromgeneration/prompts/,writeSumFile/writeAgentsMdfromgeneration/writers/, quality checks fromquality/generation/prompts/builder.tsimportsextractImports/formatImportMapfromimports/,detectLanguagefromgeneration/prompts/ai/service.tswrapsai/backends/inai/providers/subprocess.ts, usesai/retry.tsfor exponential backoffdashboard/index.tsimports cost calculators fromdashboard/cost-calculator.ts, log readers fromdashboard/log-reader.ts/dashboard/trace-reader.ts, view renderers fromdashboard/views/
Workflow & Conventions
Subprocess CWD Override: When spawning AI CLI subprocesses, set CWD to os.tmpdir() via AIService.setSubprocessCwd() to prevent AI CLIs (especially Claude) from discovering project context files (CLAUDE.md, package.json, CLAUDE_CONTEXT.md) that waste cache tokens on automatic ingestion.
User Content Preservation: User-authored AGENTS.md/CLAUDE.md detected by absence of GENERATED_MARKER_PREFIX, renamed to .local.md on first generation, preserved via @{filename}.local.md import directive.
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.
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 for long-running operations.
Worktree Management: plan.ts and implement.ts create temporary git worktrees with branch naming are/{plan|implement}/{with-docs|without-docs}/{taskSlug}. Cleanup: SIGINT/SIGTERM handlers call worktrees.cleanup() to remove worktrees (branches preserved).
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

