Agentic AI codebase analysis for living documentation, architecture, and change-impact review.
Are you tired of fragmented, inconsistent, unstructured, or even missing documentation?! Codebase Analysis AI keeps documentation aligned with the codebase through bounded, evidence-based analysis and repeatable checks.
It maps changed source files to the documentation they affect, reviews direct relationships, validates links and metadata, and asks an AI agent to update only what requires interpretation. docs/index.md is the canonical navigation entry point and is verified on every documentation change. During a full bootstrap, Python collects a bounded structural inventory; the parent agent reads the relevant project files, derives source macro-areas and documentation topics, then proposes one of three delegation strategies before writing the documentation.
Git, Python, Git hooks, and GitHub Actions provide the deterministic foundation; the agent skill handles evidence collection, orchestration, validation, and writing.
The result is a documentation system that helps a new developer understand the project's purpose, technologies, startup instructions, architecture, active functionality, known TODOs, and related flows immediately after cloning the repository.
A provider-neutral Agent Skill for keeping code and documentation aligned. The visual assets in this README are illustrative; the text and examples remain the source of truth.
Codebase Analysis AI reduces documentation drift by:
- starting from Git changes instead of scanning the complete repository;
- mapping source files to directly affected documents;
- checking links, hashes, metadata, naming, document kinds, and documentation coverage;
- validating immutable decision records and their supersession chains;
- optionally bridging decisions to PlanVault execution plans without modifying them;
- reviewing bootstrap macro-areas through isolated, read-only subagents;
- preserving a consistent documentation structure and evidence-backed TODOs;
- supporting monoliths, full-stack applications, microservices, libraries, mobile applications, and infrastructure repositories.
- Git identifies changed or uncommitted source files.
- A deterministic Python checker resolves source-to-document mappings and direct first-level relationships.
- The agent reviews the impacted sources and documentation.
- The agent updates stale content only when the evidence requires it.
- The checker validates links and refreshed metadata.
The traversal stops after one relationship level. If source A maps to document B, and B links to C, the update checks B and C without traversing the rest of the documentation graph. SHA-256 hashes track processed source content even when changes are uncommitted, amended, or rebased.
- A deterministic inventory identifies structural evidence; the parent selectively reads it and derives source macro-areas and separate documentation topics without relying on a fixed technology catalog.
- It proposes
parent-only, mixedselective, orallsafely separable areas, gives a brief evidence-based motivation and per-area assignment, and asks for confirmation before creating or invoking analyzers. During bootstrap, at least two independent macro-areas with 15 or more relevant files each require analyzer creation and delegation unless the user explicitly selectsparent-only. - Approved analyzers review bounded source scopes and return JSON reports whose claims and findings include repository sources; small or overlapping areas may remain in the parent.
- The parent validates paths and evidence, preserves and prioritizes findings, maps reports to thematic documents, resolves cross-area flows, and alone writes the documentation. The same findings contract applies when the parent works without analyzers.
Profiles are created only during bootstrap or migrate, and only for areas approved for delegation. An explicit parent-only choice suppresses profile creation and delegation even above the threshold. Otherwise, when the two-area/15-file threshold is met, creation is mandatory; a missing native capability, profile creation failure, invocation failure, or bounded timeout triggers a recorded in-process fallback. update and audit reuse existing profiles only.
| Mode | Purpose | Scope | Explicit request |
|---|---|---|---|
setup |
Install agent rules, checker, hooks, and GitHub Action | Configuration files | Yes |
bootstrap |
Create a complete documentation system using macro-area analyzers | Full repository and active-host analyzer profiles | Yes |
update |
Synchronize existing documentation | Changed files and direct relationships | No |
audit |
Review accuracy without changing files | Selected or impacted documentation | No |
migrate |
Restructure and index existing documentation without a general content refresh | Existing docs and mapped sources | Yes when restructuring is required |
check |
Run deterministic documentation-drift checks | Changed files, mappings, and direct relationships | No |
checkdoes not use an AI model. It is the command used by local hooks and CI to detect possible documentation drift.
For requests to create documentation from zero, the default existingDocumentationPolicy: ask prevents silent rebuilding. When documentation exists, the agent proposes exactly two choices:
archive: reuse every useful fact in the new documentation and preserve the originals belowdocs/_archive/pre-bootstrap/;replace: reuse every useful fact in the new documentation and remove only confirmed superseded originals after generation and validation.
Canonical files that keep the same path, such as README.md, are rewritten in place; archive first preserves their original version. The archive is historical and excluded from the active index, documentation map, normal updates, and audits. migrate remains a separate structural operation, while update synchronizes impacted content with implementation evidence and preserves still-valid manual context.
The documentation map identifies documents managed by Codebase Analysis AI through document IDs, source mappings, and source hashes. It does not prove that a document was originally created by the skill rather than adopted from an existing repository. Archiving or replacing existing documentation must therefore remain an explicit user decision.
Document paths, source paths, and glob patterns in the map must be repository-relative and use forward slashes; absolute paths and .. segments are invalid.
A map is canonical as soon as one document declares documentKind; otherwise it is legacy. Canonical maps use the documented glob subset (* and ? never cross /, ** does, so nested files need src/**/*.ts) and treat missing, unregistered, or unindexed documents as blocking errors. Legacy maps keep the historical fnmatch semantics (* also crosses /) and report those document findings only as warnings, so existing repositories keep working until they migrate.
After an update, the agent validates the changed documentation, refreshes hashes only for reviewed changed source paths, and reruns check.
The core workflow remains provider-neutral. During bootstrap or migration when delegation is required, the skill detects the active host and creates project-level, read-only analyzer profiles only for areas approved for delegation. An explicit parent-only choice suppresses creation and delegation even above the threshold. Small or overlapping areas may remain in the parent. It never creates profiles for inactive hosts or at user scope.
| Agent | Skill location and invocation | Analyzer profile | Discovery or invocation |
|---|---|---|---|
| OpenAI Codex | .agents/skills/codebase-analysis-ai/; $codebase-analysis-ai |
.codex/agents/<area>-analyzer.toml |
Explicit spawn instruction |
| Claude Code | .claude/skills/codebase-analysis-ai/; /codebase-analysis-ai |
.claude/agents/<area>-analyzer.md |
Name or @-mention; restart only for a newly created agent directory |
| Gemini CLI | .agents/skills/codebase-analysis-ai/; activate codebase-analysis-ai |
.gemini/agents/<area>-analyzer.md |
/agents refresh, then @<area>-analyzer |
| GitHub Copilot | .agents/skills/codebase-analysis-ai/; ask Copilot to activate it |
.github/agents/<area>-analyzer.agent.md |
CLI restart or enabled agent/runSubagent tool in VS Code |
Analyzer profiles explicitly exclude write, shell, and recursive-agent tools where the host supports tool allowlists. Codex profiles set sandbox_mode = "read-only". Every invocation receives a self-contained JSON evidence contract; only the parent agent merges reports and writes documentation.
The generated profiles contain a managed marker and area paths. Bootstrap or migration may create missing profiles, but update and audit reuse existing profiles only. Existing profiles are not silently overwritten, stale profiles are not deleted, and inactive-host or user-scope profiles are never created.
These marks identify example host targets only. They are navigation aids and do not imply endorsement or partnership.
Clone this repository and run the installer from the target project:
The examples use python3; on Windows, use py -3 instead.
git clone https://github.com/MattiaF95/codebase-analysis-ai.git
python3 codebase-analysis-ai/install.py \
--project-root /path/to/project \
--agent all \
--scope projectInstall only the skill for a project or for the current user:
python3 install.py --project-root /path/to/project --agent codex --scope project
python3 install.py --agent codex --scope userPython 3.9 or newer is required. The installer validates its targets in a read-only preflight before writing, applies the selected components transactionally, and restores files, permissions, and local Git configuration if a later step fails. It rejects targets and parent directories whose symlinks resolve outside the project root, is idempotent, creates missing managed components, refreshes outdated managed ones, preserves extra files and unrelated manual content, and never replaces unmanaged files. If the installed runtime contains unexpected Python files below tools/codebase-analysis-ai/codebase_analysis_ai/, setup reports the runtime as outdated and install stops with a conflict instead of deleting the files. During bootstrap or delegated migration, one project-level analyzer is mandatory for each of at least two independent macro-areas containing 15 or more relevant files unless the user explicitly selects parent-only.
Use explicit requests for operations that create or restructure documentation:
Use codebase-analysis-ai in bootstrap mode and create the complete project documentation.
Detect the source macro-areas and documentation topics, recommend parent-only, selective, or all delegation with a brief motivation, include automation in the initial confirmation, and write the documentation in English.
Use codebase-analysis-ai to update the documentation affected by the current Git changes.
Use codebase-analysis-ai to audit the existing documentation without modifying files.
Use codebase-analysis-ai setup to install agent rules, Git hooks, and the GitHub Action.
After installation, run the deterministic checker directly with:
python3 tools/codebase-analysis-ai/check.py check --mode working-treecheck exits non-zero when it finds documentation drift. Add --json for a machine-readable report on stdout, or --warn-only to keep every check failure non-blocking while still reporting it, including map, Git, and I/O errors. Alongside hashes, links, and mappings, the report exposes warnings (non-blocking findings of legacy maps), sectionErrors, adrErrors, coverageErrors, navigationErrors, and planvaultErrors; document-kind violations are reported through map errors. The JSON output is always deserializable, including on early failures.
Report documentation coverage by kind and decision-record status, either as JSON or as a Markdown summary:
python3 tools/codebase-analysis-ai/check.py coverage
python3 tools/codebase-analysis-ai/check.py coverage --markdownThe Markdown output includes the managed scope markers and can be saved directly to docs/_meta/coverage.md. For a canonical documentation index, both check and validate-docs --strict require links to mapped area and kind indexes, including area README.md files. They also verify the coverage summary's three two-column tables against the map: document kinds, decision-record statuses, then index policies. Keep this table order and the technical row identifiers when translating headings or surrounding prose; stale, missing, or duplicate count rows are reported as coverage errors.
Detect optional PlanVault plans and validate plan-to-ADR links without modifying anything:
python3 tools/codebase-analysis-ai/check.py planvault
python3 tools/codebase-analysis-ai/check.py planvault --strictA repository without plans/ reports detected: false and no error; the bridge never makes PlanVault a prerequisite.
Inspect setup state with the current bundled skill before relying on a project-local runtime:
python3 skill/codebase-analysis-ai/scripts/codebase_analysis_ai.py \
--root /path/to/project \
setup-state \
--agents codexsetup-state reports runtime, agent adapters, hooks, the GitHub Action, and documentation-map coherence. Running it from the installed project runtime reports that runtime as unverified, because it has no independent bundled source to compare against; adapter, hook, and workflow entries are also reported as unverified when the installed runtime has no corresponding assets to compare. Missing components are setup work; managed-but-different components are outdated; unmanaged or unexpected runtime files require an explicit cleanup or reinstall decision before install continues.
Before a full bootstrap, run the non-content preflight to detect existing text, markup, PDF, Office, OpenDocument, and other common documentation formats:
python3 tools/codebase-analysis-ai/check.py docs-stateValidate generated or changed managed documents with:
python3 tools/codebase-analysis-ai/check.py validate-docs docs/index.md
python3 tools/codebase-analysis-ai/check.py validate-docs --strictvalidate-docs accepts repository-relative Markdown paths only. Absolute paths, including paths inside the repository, and any path containing a .. segment are rejected with path must be repository-relative; the validator does not read files outside the Git root. When the documentation map is present, it also validates declared document kinds and localized sections, decision records and supersession, index navigation, coverage, and PlanVault links. Without --strict these issues are reported but do not fail the command; the command never rewrites documents.
Hooks provide fast local feedback for commits, pushes, merges, rebases, and amended commits. They run only the deterministic checker; they do not invoke an AI agent or rewrite documentation. They are installed under .githooks/ and enabled with:
git config core.hooksPath .githooksThe pre-push hook blocks publication when the documentation check reports one or more errors, prints the JSON report details, and shows git push --no-verify as the explicit bypass command. Manually changed Markdown documents are recorded as changedDocuments; their links are still validated, while their content and source hashes are not changed automatically. Hooks can be bypassed, so they are not the shared enforcement layer.
The workflow is a warning-only audit, not a blocking gate. It checks pull request updates, merge queues through merge_group, direct pushes to the default branch, and manually requested audits. It runs the checker with --warn-only --json and emits an English ::warning annotation only when the report contains at least one inconsistency; a clean run produces no annotation. An unreadable report produces a warning without failing the job. It uses contents: read, requires no model secrets, and creates no commits. Enforce required checks separately in repository settings if a project wants a blocking policy.
The skill reads docs/index.md first when present and follows the repository's existing documentation-language policy. In bootstrap, update, audit, or migrate, if no reliable language evidence exists, it includes the language choice in the initial request. The selected language is recorded in docs/_meta/documentation-map.json; technical identifiers, commands, API fields, and library names remain unchanged.
Topic documents normally follow this order:
- Purpose and context
- Responsibilities and behavior
- Technologies and implementation details
- Active functionality and planned work
- Related documentation and sources
The skill never invents functionality, TODOs, commands, dependencies, or architectural relationships.
Beyond the source area and topic, every new document declares a documentKind in the documentation map. The runtime catalog in scripts/codebase_analysis_ai/document_kinds.py defines the supported kinds and their required sections: project-readme, documentation-index, area, topic, architecture, api-reference, data-model, runbook, test-strategy, backlog, kind-index, decision-record, reference, and analysis-report. The map stores the localized heading used for each canonical section key, so validation works in the project language instead of assuming English titles. Documents without documentKind or sections remain valid for backward compatibility and are reported as legacy, never rewritten automatically.
Durable architectural decisions become decision records under docs/decisions/ (or the recognized legacy alias docs/adr/) using ADR-NNNN-<slug>.md. An accepted ADR is immutable except for status and supersession links; a changed decision creates a new ADR and marks the old one superseded. ADRs have no source patterns or source hashes, so refresh never updates them, and the gate validates filename, number, status, date, required sections, index links, and supersession consistency; a record superseded by a newer ADR may itself be superseded later, so chains such as ADR-0001 → ADR-0002 → ADR-0003 are valid.
When PlanVault plans exist under plans/, the skill detects single-file and three-core (spec.md, plan.md, tasks.md) plans without requiring or modifying them. Tactical choices stay in a plan's decision log; architectural, durable, or migration-triggering decisions are promoted to ADRs. A plan may link an ADR and the ADR lists the plan in metadata.relatedPlans (for a three-core plan, listing any one of its files is enough); the gate validates both directions when both artifacts exist. Update and audit report decisions that are not yet promoted but never create ADRs or alter plans without explicit confirmation, and a completed plan never changes an ADR status. Analyzer reports must cite repository-relative paths and source lines, remain bounded, and expose uncertainties instead of unsupported claims. Sensitive files, credentials, certificates, environment files, dependency directories, and generated build directories (such as build, dist, target, out, and obj) are excluded from analysis; ordinary source folders such as bin/ are not.
The structure is adaptive: deterministic tooling inventories project evidence, while the parent agent interprets repository shape, technologies, deployment boundaries, and existing terminology and creates only useful areas. The approved taxonomy is persisted for later runs. After bootstrap, update and audit reuse existing read-only profiles only for affected or selected macro-areas through the active host's native delegation mechanism; unavailable or timed-out delegation falls back to the parent without skipping the area. They never create persistent profiles. migrate may create missing profiles when delegated ownership or mapping analysis requires them. Before and after delegation, the parent verifies profile restrictions and working-tree integrity. Empty standard folders are not added merely for symmetry.
project/
├── <active-host-agent-directory>/
│ └── <area>-analyzer.<host-format>
├── README.md
├── docs/
│ ├── index.md
│ ├── architecture/ cross-area components and flows
│ ├── backend/ area index plus topic documents
│ ├── frontend/
│ ├── decisions/ ADR-NNNN-<slug>.md and index.md
│ ├── reference/ stable lookup material
│ ├── runbooks/ operational procedures
│ ├── _meta/ documentation-map.json and coverage.md
│ ├── _analysis/ optional dated reports, not indexed
│ └── _archive/ optional historical material, excluded
└── tools/codebase-analysis-ai/
docs/index.md links to every area index, every active kind index, and _meta/coverage.md, and summarizes each destination. Agents read it before deeper documentation and update it whenever navigation, document paths, or document purposes change. Historical originals under docs/_archive/ are intentionally omitted, and docs/_analysis/ reports remain linkable evidence without appearing in active navigation or coverage. New directories are created only when they contain real content; a small repository may need only docs/index.md, _meta/, and one area index.
<active-host-agent-directory> resolves to .codex/agents/, .claude/agents/, .gemini/agents/, or .github/agents/. Mobile applications, infrastructure repositories, libraries, command-line tools, and other repository types receive a taxonomy appropriate to their evidence.
The diagrams are illustrative. Actual generated paths and responsibilities depend on the detected repository shape.
The installable skill lives under skill/codebase-analysis-ai/; the separate Python test suite under tests/ is not copied into target projects. The minimum supported Python version is 3.9. Run the test suite locally; this repository does not configure GitHub Actions workflows.
python3 -m unittest discover -s tests -p "test_*.py"The tests verify structural inventory, mappings, one-level impact resolution, link validation, installer preflight, idempotency and rollback, symlink containment, runtime conflict reporting, setup-state truthfulness, validate-docs repository-relative boundaries, language metadata, stale-source detection, hash refreshes, document-kind and localized-section contracts, canonical docs/ layout and navigation, coverage counts, ADR lifecycle and supersession, PlanVault detection and bidirectional links, legacy-map compatibility, and the warning-only automation assets. Skill validation checks its structure and metadata.
codebase-analysis-ai/
├── README.md
├── assets/ README illustrations and agent logos
├── LICENSE Apache License 2.0
├── install.py Cross-agent installer
├── skill/codebase-analysis-ai/
│ ├── SKILL.md Mode router and safety boundaries
│ ├── agents/openai.yaml Optional Codex UI metadata
│ ├── references/ Mode, evidence-contract, and host-specific instructions
│ ├── scripts/ Deterministic analysis and installation code
│ └── assets/ Hooks, workflows, adapters, and templates
└── tests/ Unit, integration, and fixture tests
Created by MattiaF95.
Licensed under the Apache License 2.0.




