{
  "markdown": "# 🛡️ DocGuard\n\n**English** · [Português (BR)](README.pt-BR.md) · [Español](README.es.md)\n\n> **The enforcement layer for Spec-Driven Development.**\n> Validate. Score. Enforce. Ship documentation that AI agents can actually use.\n\n[![CI](https://github.com/raccioly/docguard/actions/workflows/ci.yml/badge.svg)](https://github.com/raccioly/docguard/actions/workflows/ci.yml)\n[![npm](https://img.shields.io/npm/v/docguard-cli)](https://www.npmjs.com/package/docguard-cli)\n[![npm downloads](https://img.shields.io/npm/dw/docguard-cli)](https://www.npmjs.com/package/docguard-cli)\n[![PyPI](https://img.shields.io/pypi/v/docguard-cli)](https://pypi.org/project/docguard-cli/)\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)\n[![Node.js](https://img.shields.io/badge/Node.js-18%2B-green)](https://nodejs.org)\n[![Runtime deps](https://img.shields.io/badge/runtime_deps-1_(pinned)-green)](package.json)\n[![Spec Kit Extension](https://img.shields.io/badge/Spec_Kit-Extension-blueviolet)](https://github.com/github/spec-kit)\n[![Glama](https://glama.ai/mcp/servers/raccioly/docguard/badges/score.svg)](https://glama.ai/mcp/servers/raccioly/docguard)\n[![MCP Registry](https://img.shields.io/badge/MCP_Registry-listed-0a7ea4)](https://registry.modelcontextprotocol.io/)\n\n---\n\n> **✨ See what DocGuard catches in 30 seconds — no install, no setup:**\n> ```bash\n> npx docguard-cli demo\n> ```\n> Runs against a baked-in sample project with intentional drift and shows you the findings + a clear path to fixing them.\n\n![DocGuard demo](assets/demo.gif)\n\n---\n\n## Table of Contents\n\n- [What is DocGuard?](#what-is-docguard)\n- [Why DocGuard?](#why-docguard)\n- [Quick Start](#-quick-start)\n- [Spec Kit Integration](#-spec-kit-integration)\n- [Usage](#usage)\n- [Validators](#-validators)\n- [Templates](#-templates)\n- [AI Agent Support](#-ai-agent-support)\n- [Slash Commands](#-slash-commands)\n- [Examples](#-examples)\n- [Testing](#-testing)\n- [Enterprise Adoption](#-enterprise-adoption)\n- [CI/CD Integration](#%EF%B8%8F-cicd-integration)\n- [What's New](#-whats-new)\n- [File Structure](#-file-structure)\n- [Configuration](#%EF%B8%8F-configuration)\n- [Research Credits](#-research-credits)\n\n---\n\n## What is DocGuard?\n\nDocGuard enforces **Canonical-Driven Development (CDD)** — a methodology where documentation is the source of truth, not an afterthought. AI writes the docs, DocGuard validates them.\n\n| Traditional Development | Canonical-Driven Development |\n|:----|:----|\n| Code first, docs maybe | Docs first, code conforms |\n| Docs rot silently | Drift is tracked and enforced |\n| Docs are optional | Docs are required and validated |\n| One AI agent, one context | Any agent, shared context via canonical docs |\n\nDocGuard is an official [GitHub Spec Kit](https://github.com/github/spec-kit) community extension. It validates the artifacts that Spec Kit creates, ensuring your specs stay high-quality throughout the development lifecycle.\n\n📖 **[Philosophy](PHILOSOPHY.md)** · 📋 **[CDD Standard](STANDARD.md)** · ⚖️ **[Comparisons](COMPARISONS.md)** · 🔬 **[Validation](VALIDATION.md)** · 🗺️ **[Roadmap](ROADMAP.md)**\n\n### Architecture\n\n```mermaid\ngraph TD\n    CLI[\"CLI Entry<br/>docguard.mjs\"] --> Commands[\"Commands (20)\"]\n    Commands --> guard[\"guard\"]\n    Commands --> generate[\"generate\"]\n    Commands --> score[\"score\"]\n    Commands --> diagnose[\"diagnose\"]\n    Commands --> setup[\"setup wizard\"]\n    Commands --> other[\"diff · init · fix · trace · impact · sync<br/>explain · memory · upgrade · agents · hooks · badge · ci · watch\"]\n\n    guard --> Validators[\"Validators (27)\"]\n    generate --> Scanners[\"Scanners (4)<br/>routes · schemas · doc-tools · speckit\"]\n    score --> Scoring[\"Weighted Scoring<br/>8 categories\"]\n    diagnose --> Validators\n    diagnose --> AIPrompts[\"AI-Ready<br/>Fix Prompts\"]\n\n    Validators --> Output[\"Output\"]\n    Scanners --> Output\n    Scoring --> Output\n    Output --> Terminal[\"Terminal\"]\n    Output --> JSON[\"JSON\"]\n    Output --> Badge[\"Badge\"]\n\n    style CLI fill:#2d5016,color:#fff\n    style Validators fill:#1a3a5c,color:#fff\n    style Scanners fill:#1a3a5c,color:#fff\n    style Output fill:#5c3a1a,color:#fff\n```\n\n> **Distribution**: Node.js core (npm) · Python wrapper (PyPI) · GitHub Action (`action.yml`) · Spec Kit Extension (ZIP)\n\n---\n\n## Why DocGuard?\n\nDocumentation that drifts from code is worse than no documentation — it\nconfidently misleads humans and AI agents alike. DocGuard treats your canonical\ndocs as an enforced contract: deterministic validators diff what the docs claim\nagainst what the code does, on every commit, with no LLM required. The full\nthesis (and the research behind it) lives in [PHILOSOPHY.md](PHILOSOPHY.md);\nrecent feature highlights moved [below](#-whats-new).\n\nThe field data backs the enforcement-over-instructions bet: an ETH Zurich\nstudy across 138 repos / 5,694 agent PRs found the most popular style of\nagent-instruction file *hurts* agent performance, and practitioners keep\nconverging on the same lesson — written rules are routinely ignored;\nprogrammatic checks are what agents (and humans) actually respect. That is\nexactly the layer DocGuard provides: not another instructions file, but the\nvalidator suite that makes the instructions and docs verifiably true.\n\n---\n\n## ⚡ Quick Start\n\n> **Package naming:** this repo is `raccioly/docguard`; the published package is **`docguard-cli`** on both [npm](https://www.npmjs.com/package/docguard-cli) and [PyPI](https://pypi.org/project/docguard-cli/); the installed command is `docguard`. Same project — the `-cli` suffix is just the registry name. The package runs **no install scripts**, so `npm i -g docguard-cli --ignore-scripts` is equivalent.\n\n### Node.js (npm)\n\n```bash\n# No install needed — run directly\nnpx docguard-cli diagnose\n\n# Or install globally\nnpm i -g docguard-cli\ndocguard diagnose\n```\n\n### Python (PyPI)\n\n```bash\npip install docguard-cli\ndocguard diagnose\n```\n\n> **Note:** The Python package is a thin wrapper that delegates to `npx`. Node.js 18+ is required on the system.\n\n### More ways to integrate\n\n- **pre-commit** — changed-only guard on every commit:\n  ```yaml\n  repos:\n    - repo: https://github.com/raccioly/docguard\n      rev: v0.29.0\n      hooks: [{ id: docguard-guard }]   # docguard-guard-full for pre-push\n  ```\n- **MCP** (Claude, Cursor, any MCP client) — `claude mcp add docguard -- npx -y docguard-cli mcp`; 5 read-only tools (guard, score, explain, verify-claims, diagnose). Registry manifest ships in-repo (`server.json`, Smithery-ready).\n- **GitLab CI** — component staged at [`templates/ci/gitlab-component.yml`](templates/ci/gitlab-component.yml) (guard/score/ci job with a SARIF artifact).\n- **Homebrew** — `brew install raccioly/tap/docguard` (formula in [`packaging/homebrew/`](packaging/homebrew/)).\n\n### Core Workflow\n\n```bash\n# 1. Initialize docs for your project\nnpx docguard-cli init\n\n# 2. Or reverse-engineer docs from existing code\nnpx docguard-cli generate\n\n# 3. AI diagnoses issues and generates fix prompts\nnpx docguard-cli diagnose\n\n# 4. Validate — use as CI gate\nnpx docguard-cli guard\n\n# 5. Check maturity score\nnpx docguard-cli score\n```\n\n### The AI Loop\n\n```\ndiagnose  →  AI reads prompts  →  AI fixes docs  →  guard verifies\n   ↑                                                       ↓\n   └───────────────── issues found? ←──────────────────────┘\n```\n\n`diagnose` is the primary command. It runs all validators, maps every failure to an AI-actionable fix prompt, and outputs a remediation plan. Your AI agent runs it, fixes the docs, and runs `guard` to verify.\n\n### Mechanical vs. agent fixes\n\nDocGuard splits drift into two kinds and is explicit about which is which:\n\n| Kind | Example | How it's fixed |\n|------|---------|----------------|\n| **Mechanical** (deterministic) | An endpoint documented in `API-REFERENCE.md` that the OpenAPI spec confirms is gone | `docguard fix --write` deletes the row + detail block itself — **no AI** |\n| **Agent** (needs judgment) | Rewriting an X-Ray prose section as CloudWatch; writing a new endpoint's request/response | Routed to an AI agent via `diagnose` / `fix --doc` prompts |\n\n`docguard fix --write` only touches docs marked `<!-- docguard:generated true -->` (override with `--force`), is idempotent, and prints exactly what changed. It never rewrites prose — that stays with the agent.\n\n### Hands-off loop (set and forget)\n\n```\nguard ──▶ fix --write (mechanical, auto) ──▶ guard ──▶ diagnose (agent prompts for the rest)\n```\n\n- **CI / pre-commit:** `docguard hooks --type pre-commit --auto-fix` installs a hook that applies mechanical fixes, re-stages the docs, then runs `guard`; anything left is surfaced as agent prompts.\n- **Agent-driven:** `docguard diagnose --auto` scaffolds missing docs **and** applies mechanical fixes, then emits prompts for the content rewrites that remain.\n- **JSON for automation:** `guard`/`diagnose --format json` include a `mechanicalFixes` array and tag each issue `mechanical` vs `agent`, so an agent can apply or delegate precisely.\n\n---\n\n## 🌱 Spec Kit Integration\n\nDocGuard is a [community extension](https://github.com/github/spec-kit/blob/main/extensions/README.md) for GitHub's **Spec Kit** framework. While Spec Kit focuses on **creating** specifications (via AI slash commands like `/speckit.specify` and `/speckit.plan`), DocGuard focuses on **validating** their quality.\n\n### How They Work Together\n\n```\n┌─────────────────┐          ┌──────────────────┐\n│    Spec Kit      │          │    DocGuard       │\n│                  │          │                   │\n│  /speckit.specify│ ──────→  │  docguard guard   │\n│  Creates specs   │          │  Validates specs  │\n│  (AI-driven)     │          │  (automated)      │\n└─────────────────┘          └──────────────────┘\n```\n\n| Phase | Tool | What happens |\n|:------|:-----|:-------------|\n| 1. Initialize | `specify init` | Creates `.specify/` directory and templates |\n| 2. Write specs | `/speckit.specify` | AI creates `spec.md` with FR-IDs, user stories |\n| 3. **Validate** | **`docguard guard`** | Checks spec quality (mandatory sections, FR/SC IDs) |\n| 4. Plan | `/speckit.plan` | AI creates `plan.md` with technical context |\n| 5. **Validate** | **`docguard guard`** | Checks plan quality (sections, structure) |\n| 6. Tasks | `/speckit.tasks` | AI creates `tasks.md` with phased breakdown |\n| 7. **Validate** | **`docguard guard`** | Checks task quality (phases, T-IDs) |\n| 8. Implement | `/speckit.implement` | AI writes code |\n| 9. **Enforce** | **`docguard guard`** | Final quality gate — CI/CD |\n\n### What DocGuard Validates in Spec Kit Projects\n\n- **spec.md** — Mandatory sections (User Scenarios, Requirements, Success Criteria), FR-xxx IDs, SC-xxx IDs\n- **plan.md** — Summary, Technical Context, Project Structure sections\n- **tasks.md** — Phased task breakdown (Phase 1, 2, 3+), T-xxx task IDs\n- **constitution.md** — Detected at `.specify/memory/constitution.md` or project root\n- **Requirement traceability** — FR, SC, NFR, US, AC, UC, SYS, ARCH, MOD, T IDs\n\n### Installing as a Spec Kit Extension\n\n```bash\nspecify extension add docguard\n```\n\nThis installs DocGuard's slash commands (`/docguard.init`, `/docguard.guard`, `/docguard.review`, `/docguard.fix`, `/docguard.update`) into your AI agent's command palette.\n\n---\n\n## Usage\n\nDocGuard ships **20 commands** (the \"Daily 5\" + 15 situational tools, including the zero-install `demo`, the `mcp` server, and the `ci` pipeline gate). Six additional one-shot scaffolders are accessed via `docguard init --with <name>`. Seven v0.19 commands continue to work as deprecation aliases through v0.20.x — see [MIGRATION-v0.20.md](docs-implementation/MIGRATION-v0.20.md).\n\n**The Daily 5** — what you'll reach for 95% of the time:\n\n| Command | What It Does |\n|:--------|:-------------|\n| `init`  | Bootstrap a project (`--wizard` for interactive · `--with <name>` for scaffolders) |\n| `guard` | Validate against canonical docs — 27 validators |\n| `diff`  | Show gaps between docs and code (`--since <ref>` for impact mode) |\n| `sync`  | Refresh code-truth doc sections — keeps memory always up to date |\n| `score` | CDD maturity score (0-100; `--diff` for delta between refs) |\n\n**Tools (situational, but day-to-day useful):**\n\n| Command | Purpose |\n|:--------|:--------|\n| `demo` | Zero-install showcase — runs guard against a baked-in drifting fixture (`npx docguard-cli demo`) |\n| `diagnose` | AI orchestrator — guard → emit fix prompts in one command |\n| `fix` | Generate AI fix instructions for specific docs (`--doc <name> --format prompt`) |\n| `fix --write` | Apply deterministic fixes (no AI — version bumps, counts, anchors, sections) |\n| `fix --history` | Audit log of every mechanical fix applied (from `.docguard/fixed.json`) |\n| `generate` | Reverse-engineer docs from existing codebase (`--plan` for AI scan) — includes auto-generated Mermaid ER diagrams from your detected schemas (Prisma/Drizzle/TypeORM/Sequelize/Django/Rails) in DATA-MODEL.md |\n| `agent` | One-shot agent task graph — ordered, pre-filled code-truth, per-task verify (`--format json`) |\n| `explain <warning\\|CODE>` | Paste any warning — or a finding code like `SEC001` — to get the validator's docstring, fix path, and how to suppress |\n| `verify --semantic` | Extract documented numbers/limits/enums (retention days, rate limits, GSI/role counts, status enums) as a task list for an agent to check against code — the semantic-drift class regex/AST can't see |\n| `verify --instructions` | Audit AGENTS.md/CLAUDE.md themselves for drift: duplicate rules, never-vs-always contradictions, stale file pointers, unknown commands — plus clustered rule pairs as agent judgment tasks |\n| `feedback` | Report likely false positives back to DocGuard — local-first record + a 1-click prefilled, redacted GitHub issue (zero typing) |\n| `mcp` | MCP server — exposes guard/score/explain/verify/report/diagnose as native tools for Claude, Cursor, and any MCP client. Stdio: `claude mcp add docguard -- npx docguard-cli mcp`. Team-shared HTTP: `docguard mcp --transport http --port 8585` (loopback by default; non-loopback binds require `--api-key`) |\n| `report` | Compliance-evidence bundle for audits — guard verdict + CDD score + ALCOA+ attributes + fix history, stamped with git commit and a tamper-evident sha256 integrity hash (`--format json`, `--out <file>`). Evidence, not a gate: always exits 0 |\n| `ci` | Pipeline gate: guard + score in one command — never scaffolds or touches source; its only write is its own `.docguard/history.jsonl` (opt out: `--no-history`). `--threshold <n>` fails below a score, `--fail-on-warning` for strict mode, `--format json` for parsers |\n| `score --trend` | Score trajectory from recorded `ci` runs — sparkline, delta, and the last 10 runs with commit stamps |\n| `memory` | Per-domain accuracy headline (endpoints / entities / env / tech) |\n| `memory --diff` | Drill into which specific claims don't match code |\n| `memory --pack` | Write `.docguard/context-pack.md` — compact, code-truth-stamped session-start context for AI agents |\n| `score --diff` | Drill into which checks pulled each category down |\n| `trace` / `trace --reverse <file>` | Requirements traceability — forward AND reverse |\n| `trace --features` | Per-feature spec-adherence scores (requirement coverage, task completion, task evidence, artifacts) — worst-first with fix hints |\n| `upgrade [--apply] [--pr]` | Check + migrate `.docguard.json` schema; `--pr` opens a PR |\n| `watch` | Live mode: re-run guard on file changes |\n\n**`init --with <name>` scaffolders** — picked at init time:\n\n| Scaffolder | What It Generates |\n|:-----------|:------------------|\n| `agents` | `AGENTS.md`, `CLAUDE.md`, `.cursor/rules/`, `.github/copilot-instructions.md` |\n| `hooks` | Git pre-commit / pre-push hooks |\n| `ci` | GitHub Actions / pipeline YAML |\n| `badge` | Shields.io score badges for README |\n| `llms` | `llms.txt` (AI-friendly summary) |\n| `publish` | External doc-site config (Mintlify) — experimental |\n\nRun them solo (`docguard init --with hooks`) or stacked (`docguard init --with agents,hooks,badge,ci`).\n\n**Deprecation aliases** — `setup` · `agents` · `hooks` · `ci` · `badge` · `llms` · `publish` · `impact` keep working in v0.20.x with a yellow stderr warning. `audit → guard` is permanent (no warning). See [MIGRATION-v0.20.md](docs-implementation/MIGRATION-v0.20.md).\n\n### CLI Flags\n\n| Flag | Description | Commands |\n|:-----|:------------|:---------|\n| `--dir <path>` | Project directory (default: `.`) | All |\n| `--verbose` | Show detailed output | All |\n| `--quiet` / `-q` | Suppress banner — for hooks, CI loops, scripts | All |\n| `--format json` | Machine-readable output (clean JSON, no ANSI bleed) | guard, score, diff, trace, diagnose, memory, impact, explain |\n| `--format sarif` | SARIF 2.1.0 output — findings as rules/results for GitHub Code Scanning and SARIF dashboards | guard |\n| `--format junit` | JUnit XML output — one testcase per validator, for GitLab CI (`artifacts:reports:junit`), Jenkins, Azure DevOps, CircleCI | guard |\n| `--update-baseline` | Adopt DocGuard on a legacy repo without a red day one: freeze today's findings into a committed `.docguard.baseline.json`; guard/ci then gate only NEW drift. Suppression is always visible (\"N pre-existing finding(s) suppressed\"), and `--no-baseline` shows the full picture | guard |\n| `--full` | Generate `llms-full.txt` (full doc bodies inlined) instead of the `llms.txt` link index | llms |\n| `--pack` | Write `.docguard/context-pack.md` — agent session-start context | memory |\n| `--sync` | Regenerate the agent-file family (CLAUDE.md, Copilot, Cursor, …) from AGENTS.md; hash-marked, never touches hand-written files without `--force` | agents |\n| `--check` | CI gate for the synced agent-file family — exit 2 when a variant is stale | agents |\n| `--force` | Overwrite existing files (creates `.bak` backups) | generate, agents, init |\n| `--force-redo` | Bypass ping-pong suppression in `.docguard/fixed.json` | fix --write |\n| `--profile <name>` | Starter / standard / enterprise | init |\n| `--no-spec-kit` | Skip auto-init of `.specify/` / `.agent/` scaffolding | init |\n| `--changed-only [--since <ref>]` | Pre-commit lite mode (5 fast validators on changed files only) | guard |\n| `--timings` | Per-validator wall-time profile (slowest first) | guard |\n| `--show-failing` | Show warnings/errors even when status is PASS | guard |\n| `--pin` | Record running CLI version into `.docguard.json` (reproducibility) | guard |\n| `--diff` | Per-category drill-down | score, memory |\n| `--check-only` | Exit 1 if behind (for CI) | upgrade |\n| `--apply` | Actually run the migration | upgrade |\n| `--pr` | Open a PR with the migration | upgrade |\n| `--reverse <file>` | Reverse traceability (code → docs) | trace |\n| `--no-indirect` | Skip the reverse-import-graph analysis (docs about modules that import a changed file) | impact, diff --since |\n| `--prs` | Open-PR doc-conflict analysis — two PRs impacting the same canonical doc = merge-order risk (needs the `gh` CLI) | impact |\n| `--transport http` `--port` `--host` `--api-key` `--path` | Serve MCP over Streamable HTTP instead of stdio (team-shared server; loopback-only unless an api-key is set) | mcp |\n| `--history` | Show fix audit log | fix |\n\n### Example Output\n\n```\n$ npx docguard-cli generate\n\n🔮 DocGuard Generate — my-project\n   Scanning codebase to generate canonical documentation...\n\n  Detected Stack:\n    language: TypeScript ^5.0\n    framework: Next.js ^14.0\n    database: PostgreSQL\n    orm: Drizzle 0.33\n    testing: Vitest\n    hosting: AWS Amplify\n\n  ✅ ARCHITECTURE.md (4 components, 6 tech)\n  ✅ DATA-MODEL.md (12 entities detected)\n  ✅ ENVIRONMENT.md (18 env vars detected)\n  ✅ TEST-SPEC.md (45 tests, 8/10 services mapped)\n  ✅ SECURITY.md (auth: NextAuth.js)\n  ✅ REQUIREMENTS.md (spec-kit aligned)\n  ✅ AGENTS.md\n  ✅ CHANGELOG.md\n  ✅ DRIFT-LOG.md\n\n  Generated: 9  Skipped: 0\n```\n\n---\n\n## 🔍 Validators\n\nDocGuard runs **27 automated validators** on every `guard` check. Every one is **language-aware** as of v0.16 — patterns for Python (`test_*.py`), Rust (`tests/*.rs`), Go (`*_test.go`), Java (`*Test.java`), Ruby (`*_spec.rb`), PHP, and JS/TS all match.\n\n| # | Validator | What It Checks | Default |\n|:--|:----------|:--------------|:--------|\n| 1 | **Structure** | Required CDD files exist | ✅ On |\n| 2 | **Doc Sections** | Canonical docs have required sections (or N/A markers) | ✅ On |\n| 3 | **Docs-Sync** | Routes/services referenced in docs + OpenAPI cross-check | ✅ On |\n| 4 | **Drift-Comments** | `// DRIFT:` comments logged in DRIFT-LOG.md (skips test files by default) | ✅ On |\n| 5 | **Changelog** | CHANGELOG.md has [Unreleased] section | ✅ On |\n| 6 | **Test-Spec** | Tests exist per TEST-SPEC.md rules | ✅ On |\n| 7 | **Environment** | Env vars documented, `.env.example` exists | ✅ On |\n| 8 | **Security** | No hardcoded secrets in source code | ✅ On |\n| 9 | **Architecture** | Imports follow layer boundaries (honors `config.ignore`) | ✅ On |\n| 10 | **Freshness** | Docs not stale relative to code changes (rename-aware via `git log --follow`) | ✅ On |\n| 11 | **Traceability** | Requirement IDs (FR, SC, NFR, US, AC, T) trace to tests | ✅ On |\n| 12 | **Docs-Diff** | Code artifacts match documented entities | ✅ On |\n| 13 | **API-Surface** | API-REFERENCE.md endpoints match real routes (OpenAPI cross-check) | ✅ On |\n| 14 | **Metadata-Sync** | Version refs consistent across docs | ✅ On |\n| 15 | **Docs-Coverage** | Code features referenced in documentation | ✅ On |\n| 16 | **Doc-Quality** | Writing quality (readability, passive voice, atomicity, IEEE 830) | ✅ On |\n| 17 | **TODO-Tracking** | Untracked TODOs/FIXMEs and skipped tests (skips test files by default) | ✅ On |\n| 18 | **Schema-Sync** | Database models documented in DATA-MODEL.md | ✅ On |\n| 19 | **Spec-Kit** | Spec quality validation (FR-IDs, mandatory sections, phased tasks) | ✅ On |\n| 20 | **Cross-Reference** | Internal markdown links + anchors resolve (with \"did you mean?\" hints); Obsidian wikilinks validated when the repo uses them as file links (`.obsidian` present or a target resolves) | ✅ On |\n| 21 | **Generated-Staleness** | `source=code` sections match scanner output; `status: draft` doc age | ✅ On |\n| 22 | **Canonical-Sync** | DocGuard's own README count claims match code-truth (DocGuard repo only — N/A elsewhere) | ✅ On |\n| 23 | **Metrics-Consistency** | Hardcoded numbers match actual counts | ✅ On |\n| 24 | **Surface-Sync** | Item-level enumerable drift — names in doc tables/lists (commands, checks, etc.) match code-truth (opt-in via `surfaceSync.surfaces`; N/A unless configured) | ✅ On |\n| 25 | **Diff-Suspicion** | Change-driven: a doc/agent-instruction file that references code changed since the ref AND shares removed domain symbols is flagged for review (arXiv 2010.01625, F1 74.7) | ✅ On |\n| 26 | **Reference-Existence** | Two-revision check: a backticked code symbol present when the doc was last updated but gone at HEAD is flagged as outdated (arXiv 2212.01479) | ✅ On |\n| 27 | **API-Doc-Smells** | Bloated (≥300 words) / Lazy (≤6 prose words) API documentation units, keyed on signature-headed sections (F1 0.90/0.95) | ✅ On |\n\n**Per-validator controls** (in `.docguard.json`):\n```json\n{\n  \"validators\": {\n    \"test-spec\": false,                 // disable (kebab-case OR camelCase both accepted)\n    \"freshness\": true\n  },\n  \"severity\": {\n    \"todoTracking\": \"high\",             // warnings fail CI\n    \"freshness\": \"low\"                  // warnings ignored for exit code\n  }\n}\n```\n\n---\n\n## 📄 Templates\n\nDocGuard ships **18 professional templates** with metadata, badges, and revision history:\n\n| Template | Type | Purpose |\n|:---------|:-----|:--------|\n| ARCHITECTURE.md | Canonical | System design, components, layer boundaries |\n| DATA-MODEL.md | Canonical | Schemas, entities, relationships |\n| SECURITY.md | Canonical | Auth, permissions, secrets management |\n| TEST-SPEC.md | Canonical | Test strategy, coverage requirements |\n| ENVIRONMENT.md | Canonical | Environment variables, deployment config |\n| REQUIREMENTS.md | Canonical | Spec-kit aligned FR/SC IDs, user stories |\n| DEPLOYMENT.md | Canonical | Infrastructure, CI/CD, DNS |\n| ADR.md | Canonical | Architecture Decision Records |\n| ROADMAP.md | Canonical | Project phases, feature tracking |\n| KNOWN-GOTCHAS.md | Implementation | Symptom → gotcha → fix entries |\n| TROUBLESHOOTING.md | Implementation | Error diagnosis guides |\n| RUNBOOKS.md | Implementation | Operational procedures |\n| VENDOR-BUGS.md | Implementation | Third-party issue tracker |\n| CURRENT-STATE.md | Implementation | Deployment status, tech debt |\n| AGENTS.md | Agent | AI agent behavior rules |\n| CHANGELOG.md | Tracking | Change log |\n| DRIFT-LOG.md | Tracking | Deviation tracking |\n| llms.txt | Generated | AI-friendly project summary (llmstxt.org) |\n\n---\n\n## 🤖 AI Agent Support\n\n### One-click MCP install\n\n[![Add to Cursor](https://img.shields.io/badge/Cursor-Add_MCP_Server-000000?logo=cursor)](cursor://anysphere.cursor-deeplink/mcp/install?name=docguard&config=eyJjb21tYW5kIjogIm5weCIsICJhcmdzIjogWyIteSIsICJkb2NndWFyZC1jbGkiLCAibWNwIl19)\n[![Install in VS Code](https://img.shields.io/badge/VS_Code-Install_MCP_Server-0098FF?logo=githubcopilot)](vscode:mcp/install?%7B%22name%22%3A%22docguard%22%2C%22command%22%3A%22npx%22%2C%22args%22%3A%5B%22-y%22%2C%22docguard-cli%22%2C%22mcp%22%5D%7D)\n\n- **Claude Code**: `claude mcp add docguard -- npx docguard-cli mcp`\n- **Claude Desktop**: download `docguard-v<version>.mcpb` from the [latest release](https://github.com/raccioly/docguard/releases/latest) and drag it into Settings → Extensions — you'll be asked which project folder to analyze. No npm, no JSON editing.\n- **Anything MCP**: DocGuard is a verified namespace on the [official MCP registry](https://registry.modelcontextprotocol.io/v0/servers?search=docguard) (`io.github.raccioly/docguard`).\n\nDocGuard works with **every major AI coding agent**. All canonical docs are plain markdown — no vendor lock-in.\n\n| Agent | Compatibility | Auto-Generate Config |\n|:------|:---:|:---:|\n| Google Antigravity | ✅ | `docguard agents --agent antigravity` |\n| Claude Code | ✅ | `docguard agents --agent claude` |\n| GitHub Copilot | ✅ | `docguard agents --agent copilot` |\n| Cursor | ✅ | `docguard agents --agent cursor` |\n| Windsurf | ✅ | `docguard agents --agent windsurf` |\n| Cline | ✅ | `docguard agents --agent cline` |\n| Google Gemini CLI | ✅ | `docguard agents --agent gemini` |\n| Kiro (AWS) | ✅ | — |\n\n### Always-on nudge hook (Claude Code)\n\n```bash\ndocguard hooks --claude            # install   (remove: docguard hooks --claude --remove)\n```\n\nRegisters a `PostToolUse` hook in the project's `.claude/settings.json`. After the\nagent edits a canonical doc it is nudged to run `docguard guard --changed-only`;\nafter it edits a code file the docs reference, it is nudged toward `docguard impact`.\nMerge-safe (only DocGuard's own entry is ever added/removed), throttled to one nudge\nper file per 30 minutes, and the hook runtime can never break a session (errors are\nsilent by contract). Explicit opt-in — `init` never installs it for you.\n\n---\n\n## ⚡ Slash Commands\n\nDocGuard provides AI agent slash commands for integrated workflows. Installed automatically via `docguard init` or `specify extension add docguard`:\n\n| Command | What It Does |\n|:--------|:-------------|\n| `/docguard.init` | Initialize Canonical-Driven Development in a new or existing project |\n| `/docguard.guard` | Run quality validation — check all 27 validators |\n| `/docguard.review` | Analyze doc quality and suggest improvements |\n| `/docguard.fix` | Generate targeted fix prompts for specific issues |\n| `/docguard.update` | Update canonical docs after code changes — detect drift and sync documentation |\n\nThese commands are installed into your AI agent's command directory:\n\n```\n.github/commands/     → GitHub Copilot\n.cursor/rules/        → Cursor\n.gemini/commands/     → Google Gemini\n.claude/commands/     → Claude Code\n.agents/workflows/    → Antigravity\n```\n\n---\n\n## 🧠 AI Skills (Enterprise)\n\nBeyond slash commands, DocGuard provides **4 enterprise-grade AI skills** — deep behavior protocols that tell AI agents not just *what* to run, but *how to think, validate, and iterate*. Skills are modeled after [Spec Kit's](https://github.com/github/spec-kit) skill architecture.\n\n| Skill | Lines | What It Does |\n|:------|:-----:|:-------------|\n| `docguard-guard` | 155 | 6-step quality gate with severity triage (CRITICAL→LOW), structured reporting, remediation |\n| `docguard-fix` | 195 | 7-step research workflow with per-document codebase research and 3-iteration validation loops |\n| `docguard-review` | 170 | Read-only semantic cross-document analysis with 6 analysis passes and quality scoring |\n| `docguard-score` | 165 | CDD maturity assessment with ROI-based improvement roadmap and grade progression |\n\n### Workflow Hooks\n\nDocGuard integrates into the spec-kit workflow as an automated quality gate:\n\n| Hook | When | Behavior |\n|:-----|:-----|:---------|\n| `after_implement` | After `/speckit.implement` | **Mandatory** — always runs DocGuard guard |\n| `before_tasks` | Before `/speckit.tasks` | Optional — reviews doc consistency |\n| `after_tasks` | After `/speckit.tasks` | Optional — shows CDD maturity score |\n\n### Orchestration Scripts\n\nFor advanced users and CI/CD pipelines, DocGuard includes bash scripts with `--json` output:\n\n| Script | Purpose |\n|:-------|:--------|\n| `docguard-check-docs.sh` | Discover project docs, return JSON inventory with metadata |\n| `docguard-suggest-fix.sh` | Run guard, parse results, output prioritized fixes |\n| `docguard-init-doc.sh` | Initialize canonical doc with metadata header |\n\n---\n\n## 📁 Examples\n\nThree real-world projects to see DocGuard in action:\n\n| Example | Scenario | What You'll See |\n|---------|----------|----------------|\n| [01-express-api](examples/01-express-api/) | Node.js API with **zero docs** | Cold-start: `generate` → instant coverage |\n| [02-python-flask](examples/02-python-flask/) | Python app with **drifted docs** | Drift detection: catch when docs lie |\n| [03-spec-kit-project](examples/03-spec-kit-project/) | Full CDD + Spec Kit | Gold standard: what maturity looks like |\n\nSee [examples/README.md](examples/README.md) for step-by-step instructions.\n\n---\n\n## 🧪 Testing\n\n### Test Suite\n\n```bash\nnpm test    # 33 tests across 18 describe blocks\n```\n\nCovers all 15 CLI commands, project type detection, compliance profiles, JSON output format, and help completeness.\n\n### CI Matrix\n\n| Node.js | OS | Status |\n|---------|-----|--------|\n| 18 | ubuntu-latest | ✅ |\n| 20 | ubuntu-latest | ✅ |\n| 22 | ubuntu-latest | ✅ |\n\n### Self-Validation (Dogfooding)\n\nDocGuard runs its own `guard`, `score`, `diff`, `diagnose`, and `badge` commands against itself in CI — ensuring the tool passes its own checks.\n\n---\n\n## 🏢 Enterprise Adoption\n\nEverything runs local or in your CI — no SaaS, no data leaving your infra.\nThe pieces that matter at company scale:\n\n| Need | DocGuard answer |\n|------|-----------------|\n| **Adopt on a legacy repo** without a red pipeline on day one | `guard --update-baseline` freezes existing findings into a committed `.docguard.baseline.json`; only NEW drift gates from then on (suppression always visible) |\n| **Audit trail** for compliance reviews | `docguard report` — commit-stamped evidence bundle (guard verdict, findings by code, CDD score, ALCOA+ data-integrity attributes, fix history) with a tamper-evident sha256 integrity hash |\n| **Every CI system**, not just GitHub | `guard --format sarif` (GitHub Code Scanning) · `--format junit` (GitLab, Jenkins, Azure DevOps, CircleCI) · `--format json` (anything else) |\n| **Trajectory, not snapshots** | `docguard ci` records every run to `.docguard/history.jsonl`; `score --trend` shows the sparkline + delta |\n| **AI agents on the team** | MCP server (stdio or team-shared HTTP) exposes guard/score/explain/verify/report/diagnose as read-only tools; `agents --sync` keeps the whole agent-file family drift-proof |\n| **Data-integrity framing auditors know** | ALCOA+ scoring (FDA 21 CFR Part 11 / EMA Annex 11 vocabulary) built into `score` and `report` |\n\n## ⚙️ CI/CD Integration\n\n> **Full recipes:** see [`docs-canonical/CI-RECIPES.md`](./docs-canonical/CI-RECIPES.md) for guard, auto-fix (commits mechanical fixes back to PRs), nightly sync, score-on-PR, and pre-commit configs.\n\n### GitHub Actions — Guard (most common)\n\n```yaml\nname: DocGuard Guard\non: [pull_request, push]\npermissions: { pull-requests: write }   # for the sticky PR comment (optional)\njobs:\n  docguard:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v4\n        with: { fetch-depth: 0 }\n      - uses: raccioly/docguard@v0.12.0\n        with:\n          command: guard\n```\n\nOn pull requests, guard mode also gives inline PR feedback (both default on):\n\n| Input | Default | Description |\n|-------|---------|-------------|\n| `annotations` | `true` | Inline `::error`/`::warning` annotations on the PR diff, one per guard finding (capped at 50; a final notice reports how many were elided) |\n| `pr-comment` | `true` | Sticky PR comment with the guard verdict, top findings (by code), and which canonical docs the PR's changed files impact (`diff --since origin/<base>`). Needs `permissions: pull-requests: write`; degrades to a log warning without it |\n\nBoth run even when guard fails — that's when the feedback matters. Prefer native\ncode-scanning integration? `docguard guard --format sarif` uploads straight to\nGitHub Code Scanning via `github/codeql-action/upload-sarif`.\n\n### GitHub Actions — Auto-Fix (commits mechanical fixes back)\n\n```yaml\nname: DocGuard Auto-Fix\non: { pull_request: { types: [opened, synchronize, reopened] } }\npermissions: { contents: write, pull-requests: write }\njobs:\n  autofix:\n    runs-on: ubuntu-latest\n    if: github.event.pull_request.head.repo.full_name == github.repository\n    steps:\n      - uses: actions/checkout@v4\n        with:\n          ref: ${{ github.event.pull_request.head.ref }}\n          token: ${{ secrets.GITHUB_TOKEN }}\n          fetch-depth: 0\n      - uses: raccioly/docguard@v0.12.0\n        with: { command: fix, auto-commit: 'true', comment-on-pr: 'true' }\n```\n\n### Pre-commit Hook\n\n```bash\nnpx docguard-cli hooks --type pre-commit\n```\n\n### Workflow starters (copy directly)\n\nTwo ready-to-use templates ship with the Spec Kit extension and as standalone files:\n- `extensions/spec-kit-docguard/templates/github-workflows/docguard-guard.yml` — mandatory CI gate\n- `extensions/spec-kit-docguard/templates/github-workflows/docguard-autofix.yml` — PR auto-fix\n\n---\n\n## ✨ What's New\n\nHighlights of the current line (v0.29 → v0.33):\n\n- **Adoption baseline** — `guard --update-baseline` freezes a legacy repo's existing findings\n  into a committed `.docguard.baseline.json`; guard/ci then gate only NEW drift, with suppression\n  always visible. Adopt today, burn down at your own pace.\n- **`docguard report`** — commit-stamped compliance-evidence bundle (guard verdict, findings by\n  code, CDD score, ALCOA+ attributes, fix history) with a tamper-evident sha256 integrity hash.\n  Also exposed as the `docguard_report` MCP tool.\n- **Score history + `score --trend`** — `docguard ci` records every run to\n  `.docguard/history.jsonl`; the trend view shows the sparkline and delta over time.\n- **Three machine formats for guard** — `--format json`, `--format sarif` (GitHub Code\n  Scanning), and `--format junit` (GitLab, Jenkins, Azure DevOps, CircleCI).\n- **MCP server, stdio + team HTTP** — guard/score/explain/verify/report/diagnose as read-only\n  agent tools: `claude mcp add docguard -- npx docguard-cli mcp`.\n- **Agent-file family sync** — `agents --sync` treats AGENTS.md as canonical and regenerates\n  CLAUDE.md / `.cursor/rules` / Copilot / Gemini variants with drift-proof source-hash markers.\n- **`verify --semantic` and `verify --instructions`** — extract documented numbers/limits/enums\n  as agent verification tasks; audit the agent-instruction files themselves for contradictions\n  and stale pointers.\n- **`docguard agent`** — one-shot ordered task graph with pre-filled code-truth, collapsing ~10\n  agent round-trips into one call.\n\nSee [CHANGELOG.md](CHANGELOG.md) for the full history.\n\n---\n\n## 📁 File Structure\n\n```\nyour-project/\n├── .specify/                        # Spec Kit (if using specify init)\n│   ├── specs/\n│   │   └── 001-feature/\n│   │       ├── spec.md              # Requirements (FR-IDs, user stories)\n│   │       ├── plan.md              # Implementation plan\n│   │       └── tasks.md             # Task breakdown\n│   ├── memory/\n│   │   └── constitution.md          # Project principles\n│   └── templates/\n│\n├── docs-canonical/                  # CDD canonical docs (the \"blueprint\")\n│   ├── ARCHITECTURE.md              # System design, components\n│   ├── DATA-MODEL.md                # Database schemas\n│   ├── SECURITY.md                  # Auth, permissions, secrets\n│   ├── TEST-SPEC.md                 # Required tests, coverage\n│   ├── ENVIRONMENT.md               # Environment variables\n│   └── REQUIREMENTS.md              # Spec-kit aligned FR/SC IDs\n│\n├── docs-implementation/             # Current state (optional)\n│   ├── KNOWN-GOTCHAS.md\n│   ├── TROUBLESHOOTING.md\n│   ├── RUNBOOKS.md\n│   └── CURRENT-STATE.md\n│\n├── AGENTS.md                        # AI agent behavior rules\n├── CHANGELOG.md                     # Change tracking\n├── DRIFT-LOG.md                     # Documented deviations\n├── llms.txt                         # AI-friendly summary\n└── .docguard.json                   # DocGuard configuration\n```\n\n---\n\n## ⚙️ Configuration\n\nCreate `.docguard.json` in your project root (auto-generated by `docguard init`):\n\n```json\n{\n  \"projectName\": \"my-project\",\n  \"version\": \"0.4\",\n  \"profile\": \"standard\",\n  \"projectType\": \"webapp\",\n  \"validators\": {\n    \"structure\": true,\n    \"docsSync\": true,\n    \"drift\": true,\n    \"changelog\": true,\n    \"testSpec\": true,\n    \"security\": true,\n    \"environment\": true,\n    \"docQuality\": true,\n    \"specKit\": true\n  }\n}\n```\n\nSee [Configuration Guide](docs/configuration.md) for all options.\n\n---\n\n## 🔬 Research Credits\n\nDocGuard's quality evaluation and documentation generation patterns are informed by peer-reviewed research from the University of Arizona and the Joint Interoperability Test Command (JITC), U.S. Department of Defense:\n\n- **AITPG** — AI-driven Test Plan Generator using Multi-Agent Debate and RAG ([Lopez et al., IEEE TSE 2026](Research/AITPG.pdf))\n- **TRACE** — Telecom Root Cause Analysis through Calibrated Explainability ([Lopez et al., IEEE TMLCN 2026](Research/TRACE.pdf))\n\nLead researcher: **[Martin Manuel Lopez](https://github.com/martinmanuel9)** · [ORCID 0009-0002-7652-2385](https://orcid.org/0009-0002-7652-2385)\n\nSee [CONTRIBUTING.md](CONTRIBUTING.md#research--academic-credits) for full citations.\n\n---\n\n## ⭐ Star History\n\n[![Star History Chart](https://api.star-history.com/svg?repos=raccioly/docguard&type=Date)](https://star-history.com/#raccioly/docguard&Date)\n\n---\n\n## 🔒 Privacy & Supply Chain\n\nDocGuard is local-first: no telemetry, no analytics, no phone-home — the full\n(short) policy is in [PRIVACY.md](PRIVACY.md). npm releases are published with\n[provenance attestation](https://docs.npmjs.com/generating-provenance-statements),\nso you can verify each tarball was built by GitHub Actions from this repository.\n\n## 📄 License\n\n[MIT](LICENSE) — Free to use, modify, and distribute.\n\n---\n\n**Made with ❤️ by [Ricardo Accioly](https://github.com/raccioly)**\n",
  "bytes": 39593,
  "sha": "c2c7afc01b6dbf86c35014d520a927dfd8afe067a3a44cf95dd3fbab757754e8",
  "repo_slug": "raccioly/docguard",
  "fonte": "repo",
  "truncated": false,
  "api": "https://agentalog.com/api/listings/mcp_io_github_raccioly_docguard_2658f7b0/readme"
}