<plugin-root>names the directory that holds this plugin's.codex-plugin/plugin.json. Resolve it once from where this file was loaded, then substitute it into every path below that starts with it. Arguments:<target path> [--critical] [--comments] [--docs-only] [--phase N] [--depth=lite|full] [--run-name <name>] [--update] [--no-update]. Wherever<arguments>appears below, substitute the text the user typed after the skill name.
Codebase X-Ray Analysis
CRITICAL RULES
- Execute phases in order. Unless
--phase Nskips to a specific phase. - Write output files. Each phase produces a file in the run directory for context passing.
- Run isolation. All writes go to
$RUN_DIRuntil the publish step. Never write phase files to the.codebase-xray/root during analysis: concurrent runs share that root. - Stop at checkpoints. Confirm scope before starting analysis and before applying changes.
- Never enter plan mode. Execute immediately.
- Code is ground truth. Document what the code actually does, not what you think it should do.
Tool Integration
The scripts in <plugin-root>/skills/xray-method/scripts/ are language-aware and support: Python, Java, JavaScript, TypeScript (incl. TSX/JSX), SQL, PL/SQL, Rust. You MUST use them instead of manual file reading whenever the target file matches one of those languages.
- Phase 1-2 (Structure): Use
ast_parser.pyfor class/function/import extraction andclassifier.pyfor file classification. Do NOT attempt to parse AST manually or count imports with grep. - Phase 5 (Risks): Use
usage_finder.pyto trace symbol usages across the codebase. Multi-language: matches Pythonfrom/import, Javaimport, JS/TSimport/require, Rustuse, etc. - Phase 6 (Docs): Use
doc_review.pyfor link validation and marker checks, andrewrite_comments.pyfor multi-language comment quality analysis (Python#/docstrings, Java/JS/TS////* *// Javadoc / JSDoc, SQL/PL-SQL--//* */, Rust/// rustdoc).
For unsupported languages, use the Read tool and Grep tool directly. Tree-sitter is optional (see Prerequisites in the codebase-xray:xray-method skill): when tree-sitter-language-pack is installed, Java/JS/TS/Rust use the tree-sitter parsers for higher fidelity; otherwise a regex fallback is used. Python always uses the stdlib ast module. SQL/PL-SQL use a regex-based DDL extractor.
Do NOT use raw bash commands (cat, grep, find) to extract structure when a dedicated script exists. The scripts use real parsers, which are faster, more accurate, and consume fewer tokens than reading files line by line.
Forbidden Files
NEVER read or include contents from:
.env,.env.*- environment variables with secretscredentials.*,secrets.*,*secret*,*credential**.pem,*.key,*.p12,*.pfx- certificates and private keysid_rsa*,id_ed25519*- SSH keys.npmrc,.pypirc,.netrc- auth tokens- Any file that appears to contain API keys, passwords, or tokens
If encountered: note file existence only (".env present - contains environment config"). NEVER quote contents.
Pre-flight
1. Resolve the run
Analyses are concurrent-safe: each invocation is an isolated run under .codebase-xray/runs/<run-id>/ (see ## Concurrent Runs Model in the codebase-xray:xray-method skill).
- Compute
run-id: value of--run-name(normalized to[a-z0-9-]) or<slug-of-target>-<YYYYMMDD-HHMMSS>. On collision with an existing run directory, append-2,-3, ... - Set
RUN_DIR = .codebase-xray/runs/<run-id>. - Read
.codebase-xray/runs.jsonif it exists:- Active runs listed: show them (run-id, target, mode, started_at) and ask: resume one of them, or start this new run alongside? Starting alongside is normal and safe; runs never share files.
- Legacy layout (root
state.jsonwith acurrent_phasefield and noruns.json): offer to migrate the old files into.codebase-xray/runs/legacy-<date>/before proceeding.
- Register the run: create/update
runs.jsonwith read-modify-write, appending{run_id, target, mode: "classic", started_at}toactive. Never drop entries you did not create.
1b. Detect an update base
An X-ray run is a set of claims about a tree. When that tree has barely moved since the last run, re-deriving every claim is the whole reading cost paid again for an answer already on disk. This step finds out mechanically whether that is the case. It spends no model tokens: snapshot.py does the work.
Skip this step entirely if --no-update was passed.
From
runs.json, takelatest_completed. The candidate parent is that run when its recordedtargetnormalizes to the same path as this invocation's target,.codebase-xray/runs/<id>/state.jsonrecordsmode: "classic", and.codebase-xray/runs/<id>/snapshot/manifest.jsonexists. A completed team run is never a usable parent here: its08-interconnect-map.mdis cross-partition output this workflow has no phase to regenerate, so carrying it forward would leave a stale marker nothing in## Execution Orderever revisits, and the check in step 8 would then refuse to publish. Treat alatest_completedteam run the same as no candidate parent at all.With a candidate, run the change set:
python <plugin-root>/skills/xray-method/scripts/snapshot.py diff \ .codebase-xray/runs/<parent-id> <target> --out $RUN_DIR --flags '<this run's flags as JSON>'Read
$RUN_DIR/changes.jsonand takerecommendationandtotals. They drive the checkpoint in step 3.
With --update and no candidate parent, stop and say which condition failed (no completed run for this target, the latest completed run for this target is a team run, or a parent with no manifest), and that a full run is the way to create one. Never fabricate a parent. With a candidate present, --update changes nothing else: the checkpoint in step 3 still presents both options and waits, exactly as CRITICAL RULE 4 requires.
A parent from before this feature has no manifest, and the change set says so with recommendation: full. That is reported, never guessed at.
2. Initialize state
Create $RUN_DIR/ and $RUN_DIR/state.json:
{
"run_id": "<run-id>",
"target": "<arguments>",
"mode": "classic",
"status": "in_progress",
"flags": {
"critical": false,
"comments": false,
"docs_only": false,
"phase": null,
"depth": "full"
},
"parent_run": null,
"base_snapshot_created_at": null,
"git": null,
"incremental": null,
"current_phase": 1,
"completed_phases": [],
"files_created": [],
"started_at": "ISO_TIMESTAMP"
}
Parse flags: --critical (prioritize high-risk code), --comments (comment quality mode), --docs-only (documentation health only, skip to Phase 6), --phase N (start at phase N), --depth=lite (lightweight analysis: skip flow tracing diagrams, state machine diagrams, and detailed dependency analysis for non-critical files, producing only structure + interfaces + risks + final summary), --run-name <name> (explicit run identity for concurrent or repeated analyses).
On an incremental run, step 1b's change set already exists by the time this file is written, so parent_run (the parent's run-id), base_snapshot_created_at (the parent manifest's created_at) and incremental's affected_files, files_in_snapshot and claims_affected (from the change set's totals) are written here with their real values, not left for later. extra_reads has no source in the change set: it counts reads outside the affected-files budget, which cannot happen before any phase has run, so it starts at 0 here and is updated once the ## Extra reads log is written, at step 9 of ### Incremental depth below. git cannot follow the at-creation rule either: the snapshot that supplies it is not written until ## Execution Order, so it starts null here and is copied in right after that step. A full run leaves parent_run and incremental as null and still records git and the snapshot: every run is a possible parent.
Register parent_run in the run's runs.json entry as well, null for a full run. The chain of parent_run values is the analysis history; nothing else is added to hold it.
3. Confirm scope
Scan the target and present the scope. With no candidate parent from step 1b, present the classic block below. With a candidate, present the variant that matches the change set's recommendation.
With recommendation: incremental:
X-ray target: [path]
Run: [run-id] parent: [parent-id] ([commit], [age])
Since parent: [N] modified, [N] added, [N] removed files; [N] symbols changed, [N] added, [N] removed
Blast radius: [N] importing files
Affected claims: [N] ([per-phase-file breakdown])
Files to read: [N] of [total]
1. Incremental update from [parent-id] (reads [N] files)
2. Full analysis (reads [total] files)
3. Cancel
[commit] and [age] describe the parent run, not this one: read [commit] from .codebase-xray/runs/<parent-id>/state.json -> git.commit (copied into that run's own state right after it wrote its snapshot) and derive [age] from that run's started_at. changes.json's own git field describes the current worktree instead, and is never the source for this line.
With recommendation: full, present the same figures with the options reversed, and print every entry of reasons under the figures so the user sees why (ratio over threshold, parent without a manifest, parent not complete, flags differing from the parent's). The incremental option stays selectable: the recommendation is advice, and the user decides.
With recommendation: none, say that nothing in the target has changed since the parent run, name the parent's published output, and offer a full analysis or exit. Do not run an incremental update that would re-derive nothing.
With no candidate parent:
X-ray target: [path]
Run: [run-id] (concurrent active runs: [count or "none"])
Files to analyze: [count] ([language breakdown])
Flags: [active flags]
Analysis phases:
0. Project Knowledge Discovery (always runs)
1. Structure Extraction -- file inventory, dependency graph
2. Interface Analysis -- public APIs, contracts, exports
3. Flow Tracing -- data flow, control flow, critical paths
4. Semantic Understanding -- WHY code exists, design decisions, ADRs
5. Pattern & Risk Detection -- anti-patterns, red flags, tech debt
6. Documentation Health -- existing docs accuracy, gaps
7. Final Report -- consolidated findings
1. Proceed with full analysis
2. Analyze specific phase only (--phase N)
3. Quick scan (phases 1-2 only)
4. Lite mode (--depth=lite: structure + interfaces + risks + summary, skip detailed flows/diagrams)
5. Cancel
Execution Order
After scope confirmation, every phase runs inline in this context, in order. Nothing is dispatched. The target a classic run is for (one package, under about 200 files, one language) fits one context, and one context that reads the code once costs less than three workers that each read it again. A target larger than that belongs to /codebase-xray:team-analyze, which partitions it and runs the same phases per partition in isolated workers; the scope confirmation above is where to say so and stop.
Every run writes a snapshot. Right after scope confirmation, before Phase 0:
python <plugin-root>/skills/xray-method/scripts/snapshot.py write \
<target> --out $RUN_DIR/snapshot/manifest.json
The snapshot records the tree this run is about to read: every file with its size, mtime and content hash, every symbol with its span and a hash of its body, and the git commit as metadata. It is what makes this run a possible parent for the next one. A full run writes it too.
Immediately after, copy the manifest's own git field into $RUN_DIR/state.json's git field. This is the only new state.json field this step fills: parent_run, base_snapshot_created_at and incremental were already written with their real values when state.json was created, in step 2, because step 1b's change set already existed by then.
Full depth (default)
- Phase 0, Project Knowledge Discovery. Writes
$RUN_DIR/knowledge/navigation.mdand$RUN_DIR/knowledge/documentation-leads.md. - Phases 1 and 2, Structure and Interfaces. Their output (dependency graph, entry points, module inventory) is what every later phase reads first.
- Phases 3 and 4, Flows and Semantics, then Phases 5 and 6, Risks and Documentation. Each phase re-reads
$RUN_DIR/01-structure.mdand$RUN_DIR/02-interfaces.mdfrom disk rather than relying on what is still in context. - Phase 7, Final Report, with the context-management strategy it describes.
Write each phase file the moment its phase completes. A phase file on disk is the context the next phase reads; nothing carried only in this context survives a long run.
Lite depth (--depth=lite)
Lightweight mode for smaller projects, MVPs, or quick assessments: Phase 0, then Phases 1 and 2, then Phase 5, then a condensed Phase 7.
Skip Phase 3 (Flow Tracing), Phase 4 (Semantic Understanding), and Phase 6 (Documentation Health). Phase 0 (Project Knowledge Discovery) is not skippable and runs in lite exactly as in full: it is the cheap discovery pass, while Phase 6 is the expensive audit. Conflating the two is what made lite mode blind to a project's own documentation. In Phase 5, skip detailed state machine diagrams and Mermaid flowcharts for non-critical files, focusing on anti-patterns, red flags, and tech debt items.
The condensed $RUN_DIR/07-final-report.md covers structure, interfaces, and risks only. It omits the "Critical Paths", "Design Insights", "Key Process Diagrams", and "Documentation vs Reality" sections.
Incremental depth (an update accepted at the checkpoint)
The phases and their numbering are unchanged. What changes is that most claims are already on disk and only the affected ones are re-derived.
Write the snapshot for this run, as above.
Carry the parent forward, mechanically:
python <plugin-root>/skills/xray-method/scripts/snapshot.py carry \ .codebase-xray/runs/<parent-id> $RUN_DIRThis copies the parent's
01to06andknowledge/into the run, renumbers every carriedfile:linecitation whose symbol survived the edit, and inserts an<!-- xray:stale reason=... cites=... -->marker above every claim the change set affects. Phase 7 is never carried: it is regenerated.Phase 0 runs in full, exactly as in a fresh run, overwriting the carried
knowledge/. It is the cheap discovery pass and what it finds shapes what the re-derivation looks for.Phases 1 to 6, in order, only where work exists. For each phase file: open it, and for every
xray:stalemarker re-derive that claim by reading the affected files it cites, then delete the marker. A marker whose reason issymbol-removedorfile-removedmeans the claim is retired: delete the claim with the marker. Then write claims for the symbols listed under## Added symbolsinchanges.mdthat belong to this phase file (01and02always,03to06at full depth). A phase file with no marker and no added symbol is not opened at all.Read only the affected files.
changes.jsonlists them underaffected_files. When re-deriving a flow or a contract genuinely requires a file outside that set, read it and log it under## Extra readsinchanges.md, naming the claim that needed it. That log is the evidence a future threshold gets tuned from.A flow that cites even one affected symbol is re-derived whole. Flows cite every step, and a step that changed can change the steps after it.
Phase 7 is regenerated from the phase files, as in a full run.
Gate publication:
python <plugin-root>/skills/xray-method/scripts/snapshot.py check $RUN_DIRExit
0means clean: proceed to publish. Exit1means a claim is still marked stale or an added symbol was never documented: do not publish, report what the check named, and finish the work. Exit2meanschanges.jsonis missing, which should not happen this late in an incremental run: do not publish, and treat it as a bug in the run rather than in the code under analysis. This gate is what makes an incremental run worth trusting.Write the completion sections of
changes.md:## Claims confirmed,## Claims revised(old and new text, one row each),## Claims retired,## Claims added,## Extra reads.Publish exactly as a full run does.
--phase N and --docs-only are full-run flags. They change this run's flags, so the change set already recommends a full run.
Overrides
If --phase N or --docs-only flags are set, run only the requested phase(s), after Phase 0.
Phase 0: Project Knowledge Discovery
Runs in every depth, including --depth=lite, and runs first, in the orchestrating context: reading project instructions and globbing for index files is cheap, and what it finds shapes what every later phase looks for.
Phases 1 through 7 keep their numbers. --phase N is a user-facing flag and renumbering would break every invocation that names a phase.
Phase 0 is a preamble, not a selectable analysis phase. It runs before every invocation, --phase 5 and --docs-only included, and it does not change the numbering semantics of phases 1 to 7. --phase 5 still means "run phase 5 and nothing else from the analysis set", with the preamble in front of it. --phase 0 runs the preamble alone, which is a legitimate way to ask only "how does this repository document itself".
This phase owns discovery of how the repository documents itself. It does not evaluate whether the documentation is accurate, which is Phase 6.
- Read
CLAUDE.md,AGENTS.mdand any equivalent project instruction file at the repository root and in the target's ancestors. Record any navigation instruction they give, especially a statement of the form "look here first to find where a concept lives". - Locate the canonical indexes the project actually uses. Glob for, at minimum:
**/SEARCH_INDEX.md,**/INDEX.md,docs/README.md,README.md,**/BY_DOMAIN.md,**/adr/**,**/decisions/**,**/architecture/**,**/domains/**,.codebase-map/INDEX.md. Record what exists, not what you expected to exist. - For each concept, symbol and subsystem in the analysis scope, search the located documents for an entry. Record the concept, the document, and the anchor or heading that matched.
- Write both output files. Every row is a lead with status
documentedorunverified. Nothing here isverified, because this phase reads no code.
Output file: $RUN_DIR/knowledge/navigation.md
# Project Knowledge Navigation
## Project instructions read
| File | Navigation rule it states |
|------|---------------------------|
## Canonical indexes found
| Index | Path | What it indexes |
|-------|------|-----------------|
## Conventions observed
[How this repository organizes its knowledge, in prose. Name the file the project treats as its semantic index, if it has one.]
## Not found
[Index kinds searched for and absent. An absent index is a fact worth recording.]
Output file: $RUN_DIR/knowledge/documentation-leads.md
# Documentation Leads
> Leads, not truth. Every row is a pointer to where the project claims a concept lives.
> Status is `documented` or `unverified`. No row here is `verified`: this phase reads no code.
| Concept / symbol | Document | Anchor | Status |
|------------------|----------|--------|--------|
## Concepts in scope with no lead
[Concepts the scope touches for which no document was found. This list is what a
downstream consumer must discover independently.]
The canonical copy of this section lives in ## Phase 0: Project Knowledge Discovery of the codebase-xray:xray-method skill, which the team-analyze workers read directly. The copy here keeps the command path self-contained, and it is the copy /senior-review:team-review reaches when it invokes this command. Edit both together.
Phase 1: Structure Extraction
Scan all files in the target and build a structural map.
For each file, extract:
- Module/file name and path
- Language and framework
- Imports and dependencies
- Exported symbols (functions, classes, constants)
- File size and complexity indicators (line count, function count)
Output file: $RUN_DIR/01-structure.md
# Phase 1: Structure Extraction
## File Inventory
| File | Language | Lines | Functions | Classes | Imports |
|------|----------|-------|-----------|---------|---------|
| ... | ... | ... | ... | ... | ... |
## Dependency Graph
[Mermaid diagram of module dependencies]
## Entry Points
[Main files, API routes, CLI handlers]
## Key Observations
[Notable structural patterns or concerns]
## Where to Add New Code
[For each major directory, describe what belongs there]
- New feature module: `[path]`
- New API endpoint: `[path]`
- New utility: `[path]`
- New tests: `[path]`
## Naming Conventions
[Prescriptive: "Use X" not "X is used"]
- Files: [pattern]
- Functions: [pattern]
- Classes: [pattern]
Update $RUN_DIR/state.json: add phase 1 to completed_phases.
Phase 2: Interface Analysis
For each module, document the public interface:
- Function signatures with parameter types and return types
- Class hierarchies and method signatures
- API endpoints with request/response shapes
- Configuration interfaces
- Event/signal contracts
Output file: $RUN_DIR/02-interfaces.md
# Phase 2: Interface Analysis
## Public APIs
[Organized by module]
## Contracts
[Interface definitions, type shapes, schemas]
## External Dependencies
[Third-party libraries and how they're used]
## How to Add a New Module
[Step-by-step guide based on existing patterns]
1. Create file at `[path]`
2. Follow interface pattern from `[example file]`
3. Register in `[registration point]`
4. Add tests at `[test path]`
Phase 3: Flow Tracing
Trace critical execution paths through the codebase:
- Request lifecycle (entry → processing → response)
- Data transformation pipeline (input → validation → processing → output)
- Error propagation paths (where errors originate, how they're handled)
- State mutation flows (what changes state, side effects)
If --critical flag is set, prioritize:
- Authentication/authorization flows
- Payment/transaction flows
- Data persistence flows
Output file: $RUN_DIR/03-flows.md
# Phase 3: Flow Tracing
## Critical Paths
[Step-by-step flow descriptions with file:line references]
## Data Flow
[How data transforms through the system]
## Error Handling Paths
[Where errors originate and how they propagate]
## Side Effects
[Functions with side effects and their blast radius]
## Process Diagrams
For each significant process discovered, generate a Mermaid flowchart diagram. Categorize each diagram as Technical, Functional, or End-to-End.
### Technical Processes
[Internal system mechanics - how components interact at code level]
[One Mermaid flowchart per process, e.g. request handling pipeline, database transaction flow, cache invalidation]
### Functional Processes
[Business logic flows - what the system does from a domain perspective]
[One Mermaid flowchart per process, e.g. user registration, order processing, notification dispatch]
### End-to-End Processes
[Full user journeys spanning multiple components and services]
[One Mermaid flowchart per process, e.g. complete purchase flow from cart to confirmation, onboarding flow from signup to first action]
Diagram guidelines:
- Limit to the 5 most critical/complex paths per category to avoid noise. Reference additional flows in prose.
- Use `flowchart TD` (top-down) for linear processes, `flowchart LR` (left-right) for pipelines
- Include decision nodes (`{condition}`) for branching logic
- Label edges with conditions, data passed, or HTTP methods
- Reference source files as comments: `%% src/auth/login.py::handle_request`
- Mark error/failure paths with dotted lines: `-->|error|`
- Keep each diagram under 30 nodes - split large processes into sub-diagrams
Phase 4: Semantic Understanding
This is the AI-powered phase -- understand the WHY behind the code:
- Business purpose of each module
- Design decisions and trade-offs (inferred from code patterns)
- Historical context (from git blame and commit messages)
- Assumptions embedded in the code
- Implicit contracts not documented anywhere
- Architecture Decision Records (ADRs) -- document rejected alternatives and WHY they were rejected, so future developers don't reintroduce failed approaches
Output file: $RUN_DIR/04-semantics.md
# Phase 4: Semantic Understanding
## Module Purposes
[WHY each module exists, not just WHAT it does]
## Design Decisions
[Inferred decisions and their trade-offs]
## Architecture Decision Records
[For each significant design choice discovered, document as an ADR:]
- **Decision:** [What was chosen]
- **Context:** [What problem it solves]
- **Alternatives rejected:** [What was NOT chosen and WHY]
- **Consequences:** [Trade-offs accepted]
ADRs bridge the gap between temporal purity (document only the present) and historical
knowledge (don't repeat past mistakes). The code shows WHAT was chosen; ADRs preserve
WHY alternatives were rejected.
## Embedded Assumptions
[Assumptions the code makes that aren't documented]
## Hidden Contracts
[Implicit agreements between modules]
## Conventions to Follow
[Prescriptive rules derived from observed patterns]
- Error handling: [pattern]
- Logging: [pattern]
- Configuration: [pattern]
Phase 5: Pattern & Risk Detection
Scan for anti-patterns, red flags, and technical debt:
- Anti-patterns: God objects, spaghetti code, shotgun surgery, feature envy
- Red flags: Swallowed exceptions, hardcoded credentials, race conditions, N+1 queries
- Technical debt: TODO/FIXME comments, deprecated APIs, outdated patterns
- Failure modes: What breaks under load, edge cases, missing error handling
Output file: $RUN_DIR/05-risks.md
# Phase 5: Pattern & Risk Detection
## Anti-Patterns Found
[Organized by severity]
## Red Flags
[Security, reliability, and performance risks]
## Technical Debt Inventory
[TODO/FIXME items, deprecated usage, modernization opportunities]
## Failure Mode Analysis
[What could break and under what conditions]
Phase 6: Documentation Health
Evaluate existing documentation against the code reality:
- Accuracy: Do docs match the actual code?
- Completeness: What's documented vs what should be?
- Freshness: When were docs last updated vs code?
- Broken links: References to files/functions that don't exist
- Comment quality: Using antirez standards (if
--commentsflag)
If --comments flag is set, also analyze comment quality:
- Identify trivial/debt/backup comments
- Score comment usefulness
- Suggest rewrites following antirez standards
Output file: $RUN_DIR/06-documentation.md
# Phase 6: Documentation Health
## Documentation vs Code Accuracy
[Mismatches between docs and reality]
## Coverage Gaps
[Undocumented public APIs, missing architecture docs]
## Broken References
[Dead links, non-existent file paths in docs]
## Comment Quality [if --comments]
[Comment audit with improvement suggestions]
Phase 7: Final Report
Synthesize all $RUN_DIR/*.md files (01 through 06) into a consolidated report.
Context management strategy (to avoid "lost in the middle" on large codebases):
- Read each phase file one at a time
- After reading each file, extract the key findings into a running summary (max 5 bullet points per phase)
- After processing all 6 files, write the final report from the extracted summaries
- For detailed sections, cross-reference the original phase files rather than duplicating content
Output file: $RUN_DIR/07-final-report.md
# Codebase X-Ray Analysis Report
## Target
[From scope]
## Executive Summary
[2-3 sentences on overall codebase health]
## Project at a Glance
[2-3 paragraph narrative explaining what this project does, who it's for, and how it works - written for someone who has never seen the codebase]
## Architecture Overview
[Mermaid diagram + narrative from Phases 1-2]
## Technology Decisions
[Key tech choices and why they were made - useful for presentations and onboarding]
## Critical Paths
[Key findings from Phase 3]
## Key Process Diagrams
[Include the most important Mermaid flowcharts from 03-flows.md - select 3-5 diagrams that best represent the system's core processes. Prioritize E2E and Functional diagrams over Technical ones. Reference 03-flows.md for the complete set.]
## Design Insights
[Key findings from Phase 4]
## Risk Assessment
| Category | Critical | High | Medium | Low |
|----------|----------|------|--------|-----|
| Anti-patterns | X | X | X | X |
| Security risks | X | X | X | X |
| Technical debt | X | X | X | X |
| Doc gaps | X | X | X | X |
## Documentation vs Reality
[Discrepancies found between existing docs and actual code behavior - useful for doc maintenance]
## Top Priority Actions
1. [Most important fix/improvement]
2. [Second priority]
3. [Third priority]
## Detailed Findings
[Cross-references to phase files for full details]
## Quick Reference: Which File to Consult
| Your Task | Start With | Also Check |
|-----------|-----------|------------|
| Onboarding / understanding the project | 07-final-report, 01-structure | 04-semantics |
| Writing new feature | 01-structure (Where to Add), 02-interfaces | 04-semantics |
| Fixing a bug | 03-flows, 05-risks | 01-structure |
| Refactoring | 01-structure, 04-semantics, 05-risks | 03-flows |
| Code review | 02-interfaces, 05-risks | 06-documentation |
| Updating documentation | 06-documentation, 04-semantics | 02-interfaces |
| Creating report/presentation | 07-final-report, 01-structure | 04-semantics |
| Finding doc vs code discrepancies | 06-documentation | 03-flows, 05-risks |
## Analysis Metadata
- Run: [run-id]
- Target: [path]
- Files analyzed: [count]
- Phases completed: [list]
- Date: [timestamp]
Update $RUN_DIR/state.json: set status to "complete".
Publish Step
After Phase 7 completes:
- Copy
$RUN_DIR/01-*.mdthrough$RUN_DIR/07-final-report.md(the ones that exist for the active flags) and$RUN_DIR/state.jsonto the.codebase-xray/root, overwriting the previous mirror.
changes.md, changes.json and snapshot/ stay in the run directory and are never mirrored: the root mirror is the latest-state contract, and history lives under runs/.
- Update
runs.jsonwith read-modify-write: remove this run fromactive, setlatest_completedto this run-id. - The root mirror is what downstream consumers (
/senior-review:team-review,/senior-review:code-review,/codebase-mapper:map-codebase,/project-setup:create-claude-md,/project-setup:maintain-claude-md) read. The run directory stays intact for history and comparison.
If the analysis is aborted or fails, remove the run from active in runs.json and leave the root mirror untouched.
Completion
Present the analysis summary and a proposed action plan derived from findings, then ask the user what they want to do.
Codebase X-ray complete for: <arguments>
Run: [run-id] (published to .codebase-xray/ root)
Parent: [parent-id or "none (full run)"]
Output Files:
- Structure: .codebase-xray/runs/[run-id]/01-structure.md
- Interfaces: .codebase-xray/runs/[run-id]/02-interfaces.md
- Flows: .codebase-xray/runs/[run-id]/03-flows.md
- Semantics: .codebase-xray/runs/[run-id]/04-semantics.md
- Risks: .codebase-xray/runs/[run-id]/05-risks.md
- Documentation: .codebase-xray/runs/[run-id]/06-documentation.md
- Final Report: .codebase-xray/runs/[run-id]/07-final-report.md
(mirrored to .codebase-xray/ root for downstream consumers)
Summary:
- Files analyzed: [count]
- Anti-patterns: [count] | Red flags: [count] | Tech debt items: [count]
- Documentation gaps: [count]
On an incremental run, add a fourth line after Parent: naming the same four buckets ### Incremental depth step 9 writes to changes.md: Claims: [N] confirmed, [N] revised, [N] retired, [N] added. Detail in .codebase-xray/runs/[run-id]/changes.md. A full run has no such line: there is no changes.md to point at, and "carried" is not a bucket anything writes, since counting it would mean reading every citation in the parent's phase files, the cost this whole mechanism exists to avoid.
Proposed Action Plan
After presenting the summary, generate a prioritized action plan based on the analysis findings. Group actions by urgency:
Proposed Action Plan
====================
CRITICAL (fix now):
1. [Action derived from 05-risks critical findings]
2. [Action derived from security red flags]
HIGH (fix soon):
3. [Action derived from anti-patterns or tech debt]
4. [Action derived from documentation gaps]
RECOMMENDED (improve when possible):
5. [Action derived from code quality observations]
6. [Action derived from naming/convention inconsistencies]
Each action must reference the specific finding and file from the analysis (e.g., "Fix missing input validation in src/auth/login.py:45 - see 05-risks.md").
Next Steps Menu
After presenting the action plan, ask the user:
What would you like to do next?
1. Start fixing - execute the action plan (all or selected items)
2. Apply quick fixes - fix stale comments, outdated references, type hints, and naming issues directly in code
3. Analyze further - run additional phases or re-analyze specific areas (a new run alongside this one is fine)
4. Generate documentation - the analysis output is now available as
technical ground truth for downstream documentation generators:
4a. CLAUDE.md - create or update the project's CLAUDE.md using this
analysis as the structure backbone
(suggests: /project-setup:create-claude-md if CLAUDE.md is absent,
otherwise /project-setup:maintain-claude-md)
4b. Codebase map - generate the full 10-document human-readable
narrative guide (suggests: /codebase-mapper:map-codebase)
4c. API / interface docs - generate documentation for one or more
formal interfaces (suggests: /codebase-mapper:docs-create with the
relevant flag, e.g. --interfaces, --architecture, --data-model)
5. Export report - save the final report in a different format
6. Nothing for now - end the session
Wait for the user's choice before proceeding. If the user picks option 1, confirm which actions to execute and in what order before starting.
If the user picks option 4 (any sub-option), the downstream command auto-detects the published .codebase-xray/ mirror on its pre-flight and offers to ingest it as the technical source. The user does not need to pass any flag manually -- detection is automatic. If the user picks 4a and CLAUDE.md already exists, route to /project-setup:maintain-claude-md (audit + improve); otherwise route to /project-setup:create-claude-md (fresh generation).
If the user picks option 2, use the dedicated scripts for safe, automated fixes:
- Comment cleanup: Run
rewrite_comments.py rewrite <file> --apply --backupfor each file flagged in Phase 6. The script handles backup, lexer-safe removal of trivial/backup comments, and auto-formatting. Works on Python, Java, JavaScript, TypeScript, SQL, PL/SQL, Rust. Do NOT manually edit comments with the Edit tool when the script supports the language. - Type hint / annotation fixes: Apply these with the Edit tool one file at a time, verifying syntax after each change.
- Stale references: Update outdated names/references in comments using targeted Edit tool replacements.
Present a summary of changes made after applying fixes. For languages outside the supported set (Python/Java/JS/TS/SQL/PL-SQL/Rust), fall back to targeted Edit tool changes with explicit before/after diffs shown to the user.
Quick Examples
/codebase-xray:analyze src/-- Full 7-phase analysis/codebase-xray:analyze src/ --depth=lite-- Lightweight: structure + interfaces + risks only/codebase-xray:analyze src/auth/ --critical-- Prioritize security-critical code/codebase-xray:analyze src/ --docs-only-- Documentation health check only/codebase-xray:analyze src/ --comments-- Include comment quality audit/codebase-xray:analyze src/ --phase 5-- Jump to pattern & risk detection/codebase-xray:analyze src/api --run-name api-- Named run; a second session can run/codebase-xray:analyze src/web --run-name webconcurrently/codebase-xray:analyze src/ --update-- require an update base; a missing or unusable parent run is a hard stop instead of a silent full run/codebase-xray:analyze src/ --no-update-- skip detection and run a full analysis
Integration with Code Review
Published analysis output in .codebase-xray/ is automatically picked up by /senior-review:code-review. /senior-review:team-review builds the same context itself: its Phase 1a invokes this command (--depth=lite by default). Run an X-ray first, then run a code review for the most thorough analysis possible.