agentleFS
GeoloeG-IsTGeoloeG-IsT/agents-reverse-engineer/AGENTS.md

agents-reverse-engineer

AGENTS.md21 starsChanged 10 months agoMITView on GitHub

npx-installable CLI toolkit for AI coding assistants that generates AI-optimized .sum file summaries, AGENTS.md hierarchical documentation, and runtime integration hooks for Claude Code, OpenCode, Gemini CLI, and Codex, with A/B testing framework for measuring AI planning and implementation quality impact. Runtime: Node.js 18+ with TypeScript (ES2022 modules via tsconfig.json) AI Backends: Claude CLI, OpenAI Codex, Google Gemini, OpenCode (subprocess adapters) File Discovery: fast-glob with ignore/isbinaryfile filters Git Operations: simple-git (change detection, worktree isolation) Schema Validation: zod (config.yaml schema) Output Formats:…

The file

We split this AGENTS.md into the rules it gives an agent

5 rules. About 0 are common, 0 are distinctive, and 5 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.

  • 5

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Telemetry: All runs log to .agents-reverse-engineer/telemetry/ (costs, tokens, latency).

    line 167
  2. Very specific:

    Dry-Run Mode: All commands support --dry-run for cost estimation and workflow validation without AI calls or file writes.

    line 177
  3. Very specific:

    Subprocess CWD Override: When spawning AI CLI subprocesses, set CWD to os.tmpdir() via AIService.setSubprocessCwd() to prevent AI CLIs …

    line 181
  4. Very specific:

    Run scripts/analyze-sum-ratios.sh to validate .sum compression (target: <25%)

    line 194
  5. Very specific:

    Run scripts/analyze-agents-compression.sh to measure AGENTS.md aggregation efficiency

    line 195

≈ “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.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
AGENTS.md
<!-- Generated by agents-reverse-engineer v1.2.12 -->

agents-reverse-engineer

npx-installable CLI toolkit for AI coding assistants that generates AI-optimized .sum file summaries, AGENTS.md hierarchical documentation, and runtime integration hooks for Claude Code, OpenCode, Gemini CLI, and Codex, with A/B testing framework for measuring AI planning and implementation quality impact.

Stack

Runtime: Node.js 18+ with TypeScript (ES2022 modules via tsconfig.json)
AI Backends: Claude CLI, OpenAI Codex, Google Gemini, OpenCode (subprocess adapters)
File Discovery: fast-glob with ignore/isbinaryfile filters
Git Operations: simple-git (change detection, worktree isolation)
Schema Validation: zod (config.yaml schema)
Output Formats: YAML frontmatter (.sum files), NDJSON (telemetry traces), HTML (dashboard reports via Chart.js CDN)
Entry Points: bin.agents-reverse-engineer and bin.are → dist/cli/index.js
Core API: exports["./core"] → dist/core/index.js with types at dist/core/index.d.ts (@beta stability)

Contents

Configuration & Licensing

  • CONTRIBUTING.md — Developer workflow: npm install (dependencies), npm run build (tsc → dist/), npm run dev (tsx watch live reload). Project structure: src/cli/ (CLI entry + commands), src/config/ (schema + loading), src/discovery/ (file discovery + plan gen), src/generation/ (AI-driven doc gen), src/orchestration/ (concurrency pool + tracing + process mgmt), src/ai/ (AI service abstraction + subprocess mgmt), src/plan/ (A/B plan comparison), src/implement/ (A/B implementation comparison). Fork-branch-PR contribution workflow. Bug reports require repro steps + environment. Feature requests use enhancement label. MIT licensed.
  • LANGUAGES-MANIFEST.md — Mapping of 24 languages to package manifest files: JavaScript/TypeScript (package.json), Python (requirements.txt, pyproject.toml, setup.py, Pipfile), Go (go.mod), Rust (Cargo.toml) marked supported (✓); Ruby (Gemfile), Java (pom.xml, build.gradle), and 17 others currently unsupported. Used by src/generation/prompts/builder.ts for import map construction.
  • LICENSE — MIT license granting unrestricted use/modification/distribution with copyright notice requirement. AS IS warranty disclaimer. Copyright holder: GeoloeG-IsT (2026).
  • package.json — npm package metadata v1.2.17. Entry points: bin.agents-reverse-engineer/bin.are → dist/cli/index.js, exports["."] → dist/cli/index.js, exports["./core"] → dist/core/index.js with type definitions at dist/core/index.d.ts. Build scripts: build (tsc), build:hooks (scripts/build-hooks.js), prepublishOnly (sequential builds), prepack (removes LICENSE.sum/README.md.sum), dev (tsx watch). Dependencies: fast-glob, ignore, isbinaryfile, jsonc-parser, simple-git, yaml, zod, picocolors. Node >=18.0.0 required.
  • tsconfig.json — TypeScript compiler config: target ES2022, module/moduleResolution NodeNext, outDir dist/, rootDir src/, declaration/declarationMap/sourceMap true, strict true, forceConsistentCasingInFileNames true, isolatedModules true, resolveJsonModule true. Include src/**/*, exclude node_modules/dist.

Documentation

  • README.md — Project documentation and CLI reference. Installation: npx agents-reverse-engineer@latest (interactive installer with runtime selection: claude, codex, opencode, gemini, all), --runtime <rt> -g|-l (non-interactive flags). Commands: are init (creates .agents-reverse-engineer/config.yaml), are discover (scans codebase, writes GENERATION-PLAN.md), are generate (executes plan: .sum files + AGENTS.md per directory + pointer files), are update (git-aware incremental with --uncommitted flag), are specify (aggregates AGENTS.md → specs/SPEC.md with --multi-file/--dry-run flags), are rebuild (reconstructs project from spec), are plan "<task>" (A/B planning test with --eval/--eval-model/--task-slug/--list/--show flags), are implement "<task>" (A/B implementation test with --plan-id/--run-tests/--run-build/--run-lint/--eval/--list/--show flags), are clean (removes .sum/AGENTS.md/plan artifacts with --dry-run), are dashboard (telemetry with --run/--trace/--trends/--format flags). Global flags: --model, --backend, --concurrency, --dry-run, --force, --fail-fast, --show-excluded, --debug, --trace. Config schema (.agents-reverse-engineer/config.yaml): exclude.patterns/vendorDirs/binaryExtensions, options.followSymlinks/maxFileSize, output.colors, ai.backend/model/timeoutMs/maxRetries/concurrency, ai.telemetry.keepRuns. Artifacts: .sum (YAML frontmatter + Purpose/Public Interface/Dependencies/Implementation Notes), AGENTS.md (directory overviews), CLAUDE.md/GEMINI.md/OPENCODE.md (pointer files), GENERATION-PLAN.md (post-order traversal), specs/SPEC.md (unified spec). Workflow: install → init → discover → generate → update. Codex integration: local install writes ./AGENTS.override.md, global install writes ~/.codex/AGENTS.override.md. Telemetry dashboard: .agents-reverse-engineer/telemetry/ logs, are dashboard for costs/tokens/latency. Total session costs via ccusage: npx ccusage@latest, npx @ccusage/codex@latest, npx @ccusage/opencode@latest. Requirements: Node.js 18+, AI coding assistant (Claude Code, Gemini CLI, OpenCode, any AGENTS.md-compatible).

Subdirectories

hooks/ — Runtime integration hooks for Claude Desktop and OpenCode. SessionStart hooks spawn detached npm version checkers to ~/.claude/cache/are-update-check.json and ~/.config/opencode/cache/are-update-check.json. PostToolUse hook walks directory tree from tool_input.file_path to data.cwd, loads AGENTS.md files, injects as additionalContext with session-scoped deduplication via ${os.tmpdir()}/are-context-loader/${session_id}.json.

scripts/ — VHS demo recorders (demo-install.tape → assets/demo-install.gif), build tooling (build-hooks.js copies hooks/*.js → hooks/dist/), circle frame generator (generate-circle-frames.js → 36 ASCII art frames with Gaussian falloff), analysis scripts (analyze-sum-ratios.sh: .sum/<25% target, analyze-agents-compression.sh: AGENTS.md/<50% excellent). Demo workflow: npm run build → ln -sf fake-npx.sh /tmp/are-demo-bin/npx → vhs scripts/demo-install.tape. Build hooks: npm run prepublishOnly → build-hooks.js → hooks/dist/ populated.

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). Three-tier architecture: CLI layer (argument parsing, config loading, backend resolution) → Orchestration layer (concurrency pooling, two-phase pipeline, progress reporting) → Generation layer (prompt construction, .sum serialization, AGENTS.md aggregation). Discovery pipeline: discovery/walker.ts (fast-glob) → discovery/filters/ (gitignore/vendor/binary/custom) → generation/executor.ts (execution plan) → orchestration/runner.ts. Quality pipeline: quality/inconsistency/code-vs-doc.ts → quality/inconsistency/code-vs-code.ts → quality/phantom-paths/validator.ts → quality/inconsistency/reporter.ts. Telemetry pipeline: ai/telemetry/logger.ts → ai/telemetry/run-log.ts → orchestration/trace.ts → dashboard/ (cost/token/trend visualization).

Architecture

Two-Phase Pipeline:

  1. File Analysis Phase: Concurrency pool processes files via buildFilePrompt() → AI subprocess → .sum serialization with YAML frontmatter (file_type, generated_at) + markdown sections (Purpose, Public Interface, Dependencies, Implementation Notes)
  2. Directory Aggregation Phase: Post-order traversal processes directories via buildDirectoryPrompt() (integrates file summaries, Import Map, Project Directory Structure, user notes) → AI subprocess → AGENTS.md generation with adaptive sections (Contents, Subdirectories, Architecture/Data Flow, Stack, Structure, Patterns, Configuration, API Surface, File Relationships, Behavioral Contracts, Reproduction-Critical Constants, Workflow & Conventions)

AI Subprocess Lifecycle:
AIService spawns backend CLIs (claude, codex, gemini, opencode) via SubprocessProvider with CWD override to os.tmpdir() (prevents context file discovery), enforces timeoutMs with SIGTERM→SIGKILL escalation (5s grace period), retries only RATE_LIMIT errors (exponential backoff with jitter, never timeouts), logs per-call telemetry to .agents-reverse-engineer/logs/.

Git-Aware Incremental Updates:
are update uses simple-git to detect modified/added/deleted files since last run, computes SHA-256 content hashes, regenerates stale .sum files, removes orphaned artifacts, updates affected AGENTS.md files. Flag: --uncommitted includes unstaged changes.

A/B Testing Worktrees:
are plan and are implement create isolated git worktrees with branches are/{plan|implement}/{with-docs|without-docs}/{taskSlug}, execute AI-driven tasks in parallel, extract quantitative metrics (detail level, file references, actionable steps, files created, lines changed, commits), optionally run blind AI quality evaluation (via third judge), persist results to .agents-reverse-engineer/comparisons/. Cleanup: SIGINT/SIGTERM handlers call worktrees.cleanup() to remove worktrees (branches preserved).

Quality Validation:

  • quality/inconsistency/code-vs-doc.ts: compares TypeScript/JavaScript exports against .sum Public Interface sections, detects missing/phantom symbols
  • quality/inconsistency/code-vs-code.ts: identifies duplicate symbols across files
  • quality/phantom-paths/validator.ts: validates AGENTS.md path references (file links, subdirectory links, markdown links) against actual directory structure
  • Failures exit with code 1 (partial failure) or 2 (total failure)

Concurrency Model:
runPool() implements shared-iterator pattern (workers pull from tasks.entries() iterator), starts new task immediately when prior completes, avoids batch-idle anti-pattern. Auto-detects concurrency from CPU cores and available memory, configurable via ai.concurrency (1-20) or --concurrency flag.

Variant Routing:
variant parameter writes .${variant}.sum and AGENTS.${variant}.md, hub files import @AGENTS.${activeVariant}.md, variant files bypass user-preservation logic.

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)

Subprocess Spawning:

spawn(process.execPath, ['-e', inlineScript], {stdio: 'ignore', detached: true, windowsHide: true})

Version Check Command:

execSync('npm view agents-reverse-engineer version', {timeout: 10000})

AGENTS.md Marker Detection:

content.includes("Generated by agents-reverse-engineer")

Timeout Enforcement: runSubprocess() enforces timeoutMs with SIGTERM→SIGKILL escalation after 5s grace period, attempts process group kill (-pid) before falling back to single process kill.

Retry Strategy: AIService retries only RATE_LIMIT errors (never TIMEOUT), uses exponential backoff with jitter, emits {type:'retry', attempt, taskLabel, errorCode} trace events.

Progress Monitoring: Commands write logs to .agents-reverse-engineer/logs/{command}-{backend}-{model}-{timestamp}.log, 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}/.

Compression Thresholds:

  • .sum target: 25% of source size (pass), 30% acceptable, status symbols: ✓, ~, ✗
  • AGENTS.md aggregation: EXCELLENT <50%, GOOD <70%, ACCEPTABLE <90%, MINIMAL ≥90%

VHS Demo Configuration:

  • Install demo dimensions: Set Width 1200, Set Height 400, Set Framerate 30
  • YT Shorts vertical: Set Width 1080, Set Height 1920, Set FontSize 22, Set Framerate 30
  • Theme: Catppuccin Mocha, 16pt font, 20px padding
  • Timing: Sleep 4s (banner), Sleep 7s (installation complete), Sleep 500ms (user input)

Circle Frame Generation:
36 frames (10° rotation), dimensions 16×6, density chars ' .·:;oO@' (8 levels), ring geometry ringInner=0.70/ringOuter=1.05, Gaussian falloff exp(-(dAngle²)/(2*0.8²)), base brightness 0.15, peak 1.0.

File Patterns:

  • Exclude from analysis: */node_modules/*, */.git/*, dot-directories (grep -v "^\./\.")
  • Hook source: hooks/*.js and hooks/*.mjs (excluding dist)
  • Frame output: src/installer/frames/frame_{1..36}.txt + index.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.json
  • are discover — walk directory, generate GENERATION-PLAN.md
  • are generate — full two-phase documentation generation
  • are update — incremental regeneration for changed files
  • are clean — delete .sum/AGENTS.md/CLAUDE.md artifacts
  • are specify — synthesize spec from AGENTS.md docs
  • are rebuild — reconstruct project from spec
  • are plan — A/B test planning with/without docs
  • are implement — A/B test implementation with/without docs
  • are dashboard — telemetry visualization (table/JSON/HTML/trends/timeline)

File Relationships

  • package.json defines entry points → dist/cli/index.js (CLI router) and dist/core/index.js (programmatic API)
  • tsconfig.json configures TypeScript compilation: src/ → dist/ with ES2022 modules
  • CONTRIBUTING.md documents developer workflow: npm run build (tsc), npm run dev (tsx watch)
  • README.md documents user-facing CLI commands, config schema, artifact formats
  • LANGUAGES-MANIFEST.md cross-references package manifest files used by generation/prompts/builder.ts for import map construction
  • LICENSE (MIT) applies to all source files
  • hooks/ provides runtime integration hooks installed by installer/ into ~/.claude/, ~/.config/opencode/
  • scripts/ provides build tooling (build-hooks.js copies hooks/*.js → hooks/dist/) and analysis tools
  • src/cli/index.ts routes commands to src/cli/{command}.ts modules
  • src/core/index.ts barrel-exports all programmatic APIs from subdirectories
  • src/orchestration/runner.ts imports buildFilePrompt/buildDirectoryPrompt from src/generation/prompts/, writers from src/generation/writers/, quality checks from src/quality/
  • src/generation/prompts/builder.ts imports extractImports/formatImportMap from src/imports/
  • src/ai/service.ts wraps backend CLIs via src/ai/providers/subprocess.ts, uses src/ai/retry.ts for exponential backoff
  • src/dashboard/index.ts imports cost calculators, log readers, view renderers

Workflow & Conventions

Installation Order:

  1. npx agents-reverse-engineer@latest (install commands, auto-create config)
  2. /are-discover (scan codebase)
  3. /are-generate (execute plan)

Update Strategy: Git-aware incremental via /are-update — only regenerates changed files. Use --uncommitted to include unstaged changes.

Codex Integration: Local install writes ./AGENTS.override.md; global install writes ~/.codex/AGENTS.override.md with lazy AGENTS hierarchy loading guidance.

Telemetry: All runs log to .agents-reverse-engineer/telemetry/ (costs, tokens, latency). View via are dashboard. For total session costs beyond ARE, use ccusage: npx ccusage@latest (Claude Code), npx @ccusage/codex@latest (Codex), npx @ccusage/opencode@latest (OpenCode).

Concurrency Tuning: ai.concurrency auto-detects from CPU cores and available memory. Lower values (1-5) for resource-constrained environments; higher values (10-20) for faster generation with more memory.

Timeout Tuning: ai.timeoutMs defaults to 5 minutes. Increase for very large files or slow connections. specify.ts and rebuild.ts upgrade to 900s minimum.

Model Upgrades: specify.ts and rebuild.ts upgrade default sonnet to opus for quality. Command-line --model flag overrides upgrade logic.

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 for cost estimation and workflow validation without AI calls or file writes.

Checkpoint Resume: rebuild/checkpoint.ts tracks per-module status (pending/done/failed) with spec hash validation, supports resume from partial runs.

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.

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).

Demo Recording Pipeline:

  1. npm run build
  2. mkdir -p /tmp/are-demo-bin && ln -sf $(pwd)/scripts/fake-npx.sh /tmp/are-demo-bin/npx
  3. export PATH="$HOME/.local/bin:$PATH"
  4. vhs scripts/demo-install.tape → assets/demo-install.gif

Build Hooks: npm run prepublishOnly → scripts/build-hooks.js → hooks/dist/ populated for package distribution.

Quality Checks:

  • Run scripts/analyze-sum-ratios.sh to validate .sum compression (target: <25%)
  • Run scripts/analyze-agents-compression.sh to measure AGENTS.md aggregation efficiency

Download now (ZIP)

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
What did you use it for? e.g. Reviewing pull requests in a Rails app

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.