Deterministic doc-drift detection and exact doc navigation as read-only MCP tools.
Model Context Protocol Server: DocGuard (io.github.raccioly/docguard)
This MCP server provides deterministic doc-drift detection. It focuses on guarding documentation that AI agents can use by validating, scoring, explaining, and verify-claims, then diagnosing MCP tools when drift is detected.
🛠️ Key Features
Deterministic doc-drift detection
Guard, score, explain, verify-claims
Diagnose MCP tools
🚀 Use Cases
Spec-Driven Development enforcement for documentation quality
Documentation workflows where drift detection is required
Governance and compliance-oriented documentation checks
⚡ Developer Benefits
CI integration referenced via a GitHub Actions workflow badge
Works within Model Context Protocol (MCP) tool ecosystems
Aligns documentation with spec-driven development practices
⚠️ Limitations
Description provides no details on deployment options, supported languages, or configuration beyond drift detection and claim verification.
DocGuard enforces Canonical-Driven Development (CDD) — a methodology where documentation is the source of truth, not an afterthought. AI writes the docs, DocGuard validates them.
Traditional Development
Canonical-Driven Development
Code first, docs maybe
Docs first, code conforms
Docs rot silently
Drift is tracked and enforced
Docs are optional
Docs are required and validated
One AI agent, one context
Any agent, shared context via canonical docs
DocGuard is an official GitHub Spec Kit community extension. It validates the artifacts that Spec Kit creates, ensuring your specs stay high-quality throughout the development lifecycle.
DocGuard checks declared documentation facts against repository evidence and gives agents structured repair tasks. Deterministic checks cover supported facts, references, and generated sections. Human-authored requirements and architectural decisions retain their authority when implementation diverges.
A guard result describes the checks performed. The CDD grade measures structural maturity. Exact declarations in .docguard-evidence.json can verify selected statements against current local evidence; every other statement remains unverified. Coverage and unresolved claims remain visible, so teams can choose an appropriate enforcement policy.
Research motivates evaluation of this approach. A 2026 study found that repository context files did not generally improve task success and increased inference cost in its evaluated settings. It also found agents generally followed the instructions. These results support testing concise, relevant context and measuring actual task outcomes; they do not establish DocGuard's effectiveness. Evaluating AGENTS.md, revised June 2026.
The current roadmap prioritizes accurate detection, reproducible evidence, document lifecycle management, and contributor-supplied regression cases. Released plans and superseded specifications are removed from active AI context and remain recoverable from Git.
⚡ Quick Start
Package naming: this repo is raccioly/docguard; the published package is docguard-cli on both npm and PyPI; 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.
Node.js (npm)
bash
# No install needed — run directly
npx docguard-cli diagnose
# Or install globally
npm i -g docguard-cli
docguard diagnose
Strict is the default.docguard guard exits 4 when a check that applies to your project examined nothing (for example no API reference although you have routes), and prints what to add. A check that does not apply is skipped, and a layout DocGuard cannot read is reported without failing the run. Upgrading and seeing a red build? Read Upgrading to Strict (also in docs/upgrading-to-strict.md). To stay on the earlier behavior, set "enforcement": "standard" in .docguard.json; under strict a "validators": { "<key>": false } entry no longer switches a check off.
Python (PyPI)
bash
pip install docguard-cli
docguard diagnose
Note: The Python package is a thin wrapper that delegates to npx. Node.js 18+ is required on the system.
Docker (MCP server)
The MCP server ships as a container image on GHCR — no Node.js install required. Public image, so no authentication is needed to pull it:
bash
# Run the MCP server against the current directory
docker run -i --rm -v "$PWD":/workspace ghcr.io/raccioly/docguard:latest
The entrypoint is the stdio MCP transport: stdout is the JSON-RPC channel, so keep every other output off it. Mount the project you want inspected at /workspace; tools inspect it by default, and a projectDir in a tool call must be /workspace or a directory inside it (add --root <dir> after the image name to serve another mounted tree).
Pin a version rather than tracking latest in CI:
bash
docker run -i --rm -v "$PWD":/workspace ghcr.io/raccioly/docguard:0.34.9
The server is read-only: it only reads the mounted project.
More ways to integrate
pre-commit — changed-only guard on every commit:
yaml
repos:-repo:https://github.com/raccioly/docguardrev:v0.48.0hooks: [{ id:docguard-guard }] # docguard-guard-full for pre-push
MCP (Claude, Cursor, any MCP client) — claude mcp add docguard -- npx -y docguard-cli mcp; read-only tools to check docs (guard, score, diagnose, …) and to navigate them one bounded section at a time — the full list is in docs/ai-integration.md. Registry manifest ships in-repo (server.json, Smithery-ready).
Homebrew — brew install raccioly/tap/docguard. The release workflow renders the formula template in packaging/homebrew/ from the published npm tarball and pushes it to the tap.
Core Workflow
bash
# 1. Initialize docs for your project
npx docguard-cli init
# 2. Or reverse-engineer docs from existing code
npx docguard-cli generate
# 3. AI diagnoses issues and generates fix prompts
npx docguard-cli diagnose
# 4. Validate — use as CI gate
npx docguard-cli guard
# 5. Check maturity score
npx docguard-cli score
The AI Loop
code
diagnose → AI reads prompts → AI fixes docs → guard verifies
↑ ↓
└───────────────── issues found? ←──────────────────────┘
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.
Mechanical vs. agent fixes
DocGuard splits drift into two kinds and is explicit about which is which:
Kind
Example
How it's fixed
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
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
docguard fix --write only touches docs marked <!-- docguard:generated true --> (override with --force), is idempotent, and prints exactly what changed. Prose stays with the agent.
Continuous documentation workflow
code
guard ──▶ fix --write (mechanical, auto) ──▶ guard ──▶ diagnose (agent prompts for the rest)
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.
Agent-driven:docguard diagnose --auto scaffolds missing docs and applies mechanical fixes, then emits prompts for the content rewrites that remain.
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.
☁️ AWS AI-DLC Integration
DocGuard reads AWS AI-DLC workspaces on its own: traceability targets that no longer exist, gaps left in completed stages, deliverables removed after a unit, and agent memory that names what is gone (AID001–AID004, MEM001–MEM002). It also ships as an AI-DLC plugin, whose docguard-guard sensor fails a construction gate when the stage introduced drift. See the AI-DLC guide.
🌱 Spec Kit Integration
DocGuard is a community extension 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.
docguard init does this for you: when the specify CLI (Spec Kit ≥ 0.11.2, the floor the
extension declares) is on your PATH, it initializes Spec Kit for the coding agent the repository
already uses, then registers the DocGuard extension shipped inside the installed package. Nothing
is downloaded for the registration. If a project's registered extension is from another DocGuard
release, init re-registers it when the versions differ (keeping its priority), and
docguard upgrade --apply does the same. init says the workflow hooks are active only after each mandatory hook
(speckit.docguard.brief before specify, speckit.docguard.preflight before tasks,
speckit.docguard.guard after implement) resolves to a command file your agent can run; otherwise
it names the missing one. Spec Kit registers no extension commands for its generic integration,
so for generic DocGuard writes them next to Spec Kit's own commands (.agent/commands/ by
default). Every failure is printed with Spec Kit's own error and the command to run by hand. Only
init and upgrade --apply touch Spec Kit; other commands print a one-line hint at most.
DocGuard's own skills go where your agent reads them: .claude/skills/ for Claude Code (or the
skills directory of another skills-based integration), .agent/ for the generic integration or
an agent DocGuard cannot place. A commands-only integration such as Gemini gets Spec Kit's
speckit.docguard.* commands and no extra copies. The command and skill files run docguard from
your PATH when it is installed, and otherwise npx --yes docguard-cli@<version>, pinned to the
release they shipped with; they never fetch @latest.
Suggestions DocGuard prints (Next: …, Fix: …) name a slash command only when its file exists
for your agent, in its form (/speckit-docguard-guard in Claude Code, /speckit.docguard.guard
for generic); otherwise they print the CLI command.
docguard init registers the copy of the extension inside the installed package. To register
it yourself, use a release ZIP or a local checkout. A bare specify extension add docguard does
not work on a default Spec Kit setup: DocGuard is in Spec Kit's community catalog, which Spec Kit
uses for discovery only.
See the Spec Kit guide for the hooks,
the spec lifecycle registry and an end-to-end flow.
This registers the speckit.docguard.* commands listed in
extension.yml (invoked as
/speckit-docguard-guard and so on in skills-based agents such as Claude Code) and the
workflow hooks that run them.
Usage
DocGuard ships 28 commands (the "Daily 5" + 23 situational tools, including lifecycle reconciliation, doc dependency review, requirement anchors, agent-rule resolution, the suppression listing, retirement and spec tracking, the zero-install demo, the mcp server, and the ci pipeline gate). Six additional one-shot scaffolders are accessed via docguard init --with <name>. Legacy command forms remain compatible until v1.0 and print their replacements.
The Daily 5 — what you'll reach for 95% of the time:
Command
What It Does
init
Bootstrap a project (--wizard for interactive · --with <name> for scaffolders)
guard
Validate against canonical docs — 36 validators
diff
Show gaps between docs and code (--since <ref> for impact mode)
sync
Refresh code-truth doc sections, including the module-graph and entity-diagram mermaid diagrams drawn from code — keeps memory always up to date
score
Structural CDD maturity score (0-100; not a guard verdict; --diff for delta between refs; --dora for DORA documentation-quality and AI-capability evidence)
Tools (situational, but day-to-day useful):
Command
Purpose
demo
Zero-install showcase — runs guard against a baked-in drifting fixture (npx docguard-cli demo)
diagnose
AI orchestrator — guard → emit fix prompts in one command
fix
Generate AI fix instructions for specific docs (--doc <name> --format prompt)
fix --write
Apply deterministic fixes (no AI — version bumps, counts, anchors, sections)
fix --history
Audit log of every mechanical fix applied (from .docguard/fixed.json)
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. --spec <area> writes an as-built Spec Kit spec for one code area: one requirement candidate per route, exported symbol, env var or entity found there (the agent writes every statement), registered as origin: as_built; guard then reports new or vanished facts (SPR007)
agent
One-shot agent task graph, or a bounded current-evidence packet for one task (--task <text>, --format json)
explain <warning|CODE>
Paste any warning — or a finding code like SEC001 — to get the validator's docstring, fix path, and how to suppress
verify --evidence
Evaluate strict statement-to-source declarations for typed JSON values, bounded collection counts, saved oasdiff JSON, and saved Buf JSON Lines. Results distinguish scoped verification, contradiction, stale inputs, inconclusive evidence, and unsupported formats.
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
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
feedback
Review any finding or a synthetic false-positive/false-negative/unsupported fixture; verify its opposite control, reduce it deterministically, search open and closed duplicates, and optionally emit a test-only contribution. Nothing is submitted automatically.
retire
Find completed or superseded planning material (--plan/--check; --fail-on-warning gates advisory candidates) and explicitly remove clean tracked documentation from active AI context. .docguard-archive.json records recovery metadata and retired requirement identities, and --retention-ref proves the source revision remains reachable. This is separate from the Spec Kit Archive extension, which consolidates feature documents.
reconcile
Build a read-only code↔spec review graph since a Git ref. Classifies mechanical facts, approved intent, decisions, unrelated changes, and unsupported evidence; --write applies only mechanical generated-section refreshes.
review
Doc sections whose covered code changed since their last review (--accept <doc>#<id> --reason, --prune, --suggest)
anchors
Every @implements/@req tag, the requirement it resolves to, and the symbol, statement, route or file it anchors to, with the tier that resolved it (--spec <id>, --file <path>, --format json)
ignore
Every suppression in the project (.docguardignore entries with their # reason and expires: date, .docguard.json ignore arrays, inline pragmas, N/A markers, the baseline) with its state; --format claimspec exports the reasoned .docguardignore entries as a claimspec ignore document and reports what it left out
rules
Which agent instruction files each harness (Codex, Claude Code, Cursor, Copilot, OpenHands) loads for a path, why, and how many bytes (--for <path>, --harness)
specs
Maintain the versioned spec registry, preflight new specs, and apply evidence-gated completion transactions with bounded outcomes and active-context regeneration. Verified living specs can record later reviewed maintenance without reopening or duplicating the specification. specs require is the spec-first gate: a change to governed paths must name its spec or declare Spec-Exempt: <kind> — <reason>.
specs --check / specs --write
Validate or refresh .docguard-specs.json, the byte-stable index of immutable spec IDs, reviewed lifecycle/lineage/scope, artifact digests, task state, explicitly scoped test evidence, and archive tombstones. Refreshes preserve the reviewed block.
specs preflight [--path <spec>]
Before specification, print current spec lifecycle and evidence. Before planning, check the generated draft for structural blockers and report semantic overlap as review-only evidence.
specs approve --id <spec-id>
Record a person's approval of a spec in the registry, and with --delivery its planned, in_progress or implemented state. Plans by default; --write records it. --persistence and a repeatable --canonical-doc record the reviewed scope. Verification stays with specs complete.
mcp
MCP server — exposes checking (guard, score, explain, verify, report, diagnose) and exact doc navigation (docs for a file, document outline, one section, task context) as native tools for Claude, Cursor, and any MCP client; docguard_guard returns each fact once unless called with detail: "full". 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)
report
Compliance-evidence bundle for audits — combined readiness, guard verdict, structural maturity, ALCOA+ attributes, and fix history, stamped with git commit and a tamper-evident sha256 integrity hash (--format json, --out <file>). Evidence, not a gate: always exits 0
ci
Pipeline gate: guard + structural maturity in one command with READY/ATTENTION/BLOCKED assessment — 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
score --trend
Score trajectory from recorded ci runs — sparkline, delta, and the last 10 runs with commit stamps
The enforcement ladder: which advisory finding codes CI history shows are ready to promote to warnings or errors
sensor --aidlc
AWS AI-DLC's sensor contract, one JSON line: passes when the work in progress introduced no drift since HEAD. The DocGuard AI-DLC plugin runs it at construction gates; not listed in --help, because it is meant for machines
memory --pack
Write .docguard/context-pack.md — compact, code-truth-stamped session-start context for AI agents
Check npm for a newer CLI (the one command that contacts a registry) + migrate .docguard.json schema; --pr opens a PR. When the installed release is over 14 days old, guard's text output, the MCP server and the context pack suggest running docguard upgrade; nothing upgrades on its own (DOCGUARD_NO_UPDATE_HINT=1 silences the note)
watch
Live mode: re-run guard on file changes
init --with <name> scaffolders — picked at init time:
Run them solo (docguard init --with hooks) or stacked (docguard init --with agents,hooks,badge,ci).
To declare an exact fact, copy templates/evidence-manifest.json to
.docguard-evidence.json, point its literal Markdown template at one unique
statement, and bind that value to a supported local source. Run
docguard verify --evidence --format json before enabling the guard in CI.
External compatibility declarations consume saved oasdiff or Buf output and
require current SHA-256 identities for every declared repository input.
Deprecation aliases — setup · agents · hooks · badge · llms · publish · impact remain compatible until v1.0 with a yellow stderr warning. audit → guard is permanent and silent; ci is a current first-class pipeline command.
claimspec v1 ignore document on stdout, validated against the vendored schema; what could not be exported goes to stderr
ignore
--format sarif
SARIF 2.1.0 output — findings as rules/results for GitHub Code Scanning and SARIF dashboards
guard
--format junit
JUnit XML output — one testcase per validator, for GitLab CI (artifacts:reports:junit), Jenkins, Azure DevOps, CircleCI
guard
--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
--full
Generate llms-full.txt (full doc bodies inlined) instead of the llms.txt link index
llms
--compact
With --format json: each fact once, the form the MCP guard tool returns by default
With --pack: add a symbol map (most central files and their exported names, within memory.symbolMap.maxBytes); opt-in: the frozen agent-context benchmark (protocol v3) found no regression and no benefit, so it is not on by default
memory
--sync
Regenerate the agent-file family (CLAUDE.md, Copilot, Cursor, …) from AGENTS.md; hash-marked, never touches hand-written files without --force
agents
--check
CI gate for the synced agent-file family — exit 2 when a variant is stale
agents
--force
Overwrite existing files (creates .bak backups)
generate, agents, init
--force-redo
Bypass ping-pong suppression in .docguard/fixed.json
fix --write
--profile <name>
Starter / standard / enterprise
init
--no-spec-kit
Skip Spec Kit: no specify call and no .specify/; DocGuard's own agent skills still install
init
--spec-kit
With --profile starter, initialize Spec Kit too (starter skips it by default)
init
--changed-only [--since <ref>]
Pre-commit lite mode: the fast validators (including covered-doc dependencies) on changed files only
guard
--timings
Per-validator wall-time profile (slowest first)
guard
--show-failing
Show warnings/errors even when status is PASS
guard
--pin
Record running CLI version into .docguard.json (reproducibility)
guard
--diff
Per-category drill-down
score, memory
--check-only
Exit 1 if behind (for CI)
upgrade
--apply
Actually run the migration
upgrade
--pr
Open a PR with the migration
upgrade
--reverse <file>
Reverse traceability (code → docs)
trace
--no-indirect
Skip the reverse-import-graph analysis (docs about modules that import a changed file)
impact, diff --since
--prs
Open-PR doc-conflict analysis — two PRs impacting the same canonical doc = merge-order risk (needs the gh CLI)
impact
--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
--root <dir>
Serve another directory tree: tool calls may pass a projectDir inside it (repeatable). Without it, projectDir must stay inside the served directory
mcp
--history
Show fix audit log
fix
When run from a nested package without --dir, DocGuard checks only that
selected directory. If a bounded ancestor scan finds a .docguard.json or an
npm/pnpm workspace declaration that owns the package, stderr shows an exact
repository-scope rerun command. DocGuard never changes scope automatically. JSON,
SARIF, and JUnit stdout remain valid; machine runs receive one typed
docguard.repository-root-guidance JSON diagnostic on stderr. A local config,
an explicit --dir, an unmatched workspace, or a nested Git boundary suppresses
the suggestion.
DocGuard runs 36 automated validators on every guard check. Source-facing validators are language-aware where their evidence model applies; repository and document validators operate independently of source language.
Counting note:guard prints one row per check. Structure emits a second
check (Doc Sections) under the same validator key, so the table below has one
row more than there are validators. The published number is the count of shipped
cli/validators/*.mjs modules, enforced by tests; count those modules rather
than output rows.
#
Validator
What It Checks
Default
1
Structure
Required CDD files exist; each AGENTS.md chain fits the agent's load limit (32 KiB default, per-chain allowances for existing debt)
✅ On
2
Doc Sections
Canonical docs have required sections (or N/A markers)
✅ On
3
Docs-Sync
Routes/services referenced in docs + OpenAPI cross-check
✅ On
4
Drift-Comments
// DRIFT: comments logged in DRIFT-LOG.md (skips test files by default)
Exact declared Markdown statements match current typed JSON, bounded collections, or saved compatibility reports; unsupported and missing evidence stays visible
✅ On
23
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
24
Generated-Staleness
source=code sections match scanner output; status: draft doc age
✅ On
25
Canonical-Sync
DocGuard's own README count claims match code-truth (DocGuard repo only — N/A elsewhere)
✅ On
26
Metrics-Consistency
Hardcoded numbers match actual counts, including runtime-dependency claims against package.json (the Spec Kit constitution is read too)
✅ On
27
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
28
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
29
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
30
API-Doc-Smells
Bloated (≥300 words) / Lazy (≤6 prose words) API documentation units, keyed on signature-headed sections (F1 0.90/0.95)
✅ On
31
Doc-Dependency
A doc section that declares covers= is reported when a covered symbol's code changes semantically since its last docguard review --accept (formatting, comments and line moves do not count); opt-in by declaration
✅ On
32
Path-Scoped-Rules
Agent instruction files per harness (nested AGENTS.md/CLAUDE.md, Claude Code rules and skills, Cursor .mdc, Copilot .instructions.md, OpenHands skills): scope globs that match no tracked file, pointers to missing paths (including routing tables), instructions loaded for one path over the byte budget, and scopes a harness cannot read
✅ On
33
Doc-Ownership
With an ownership map in .docguard.json: source directories no doc section owns, two equally specific owners, patterns that match nothing, entries naming missing docs; also lints a committed .devin/wiki.json against Devin's limits and for paths that are gone
✅ On
34
Suppressions
Suppressions of any kind whose expires: date has passed (they no longer suppress anything), whose expiry is not a calendar date, or, with suppressions.requireReason, that have no # reason
✅ On
35
Requirement-Anchors
With .docguard-anchor-lock.jsonl or anchors.enabled: reviewed code→requirement links whose code or requirement changed since review (ANC001/ANC002), reviewed links whose tag is gone (ANC003), tags citing an undeclared or retired requirement (ANC007/ANC008), an unreadable lock (ANC005) and files read below their exact tier (ANC010). docguard anchors lists every link; anchors accept records a review
✅ On
36
Decision-Records
ADR status, one-way or dangling supersession, index/record mismatches, and unanswered clarifications or [Answer]: tags (DEC001–DEC006). Informational by default
✅ On
37
AIDLC
AWS AI-DLC workspaces (aidlc/spaces/…, legacy aidlc-docs/): traceability targets that no longer exist (AID001), gaps left in completed stages (AID002), unit deliverables removed after the unit (AID003), unreadable records (AID004). Informational by default
✅ On
Per-validator controls (in .docguard.json):
json
{"validators":{"test-spec":false,// disable (kebab-case OR camelCase both accepted)"freshness":true},"severity":{"todoTracking":"high",// warnings fail CI"freshness":"low"// warnings ignored for exit code},"findingSeverity":{"TRC004":"low",// only this finding becomes informational"SEC001":"high"// this exact code always blocks}}
Exact findingSeverity entries take precedence over validator severity. Guard
JSON, SARIF, and JUnit retain the detector's intrinsic severity and add the
effective severity plus the policy source. Intrinsic errors stay blocking unless
their exact stable code is explicitly configured.
🎚️ Reading a Finding
A finding used to answer one question — "how worried should you be?" — with one
confidence field, which meant the field was doing three incompatible jobs at
once. DocGuard now separates them. These axes are independent: a blocking
error can be an escalation, and a high-confidence finding can still be one a
human must judge.
act — DocGuard asserts a defect and names the correction. Safe to apply,
including through docguard fix or an agent.
escalate — DocGuard observed a signal; the judgement is yours. Freshness
FRS002 ("13 code commits since the document was reviewed") is the canonical
case: the count comes from git log, so it is exact and confidence: high —
and it establishes only that a review is due, never that the document is
wrong. Editing a document until an escalation stops printing destroys the signal
and fixes nothing. A judged-and-left escalation is a correct outcome.
evidence.status tells you what a confidence label is worth. measured
quotes the reviewed precision corpus with n and a Wilson lower bound;
not-measured means the label is a maintainer's prior and nothing more. Most
codes are unmeasured — that does not make their findings wrong, only unverified,
and docguard feedback samples them for exactly that reason.
parserTier tells you what the detector could see. js-ast and py-ast
mean a syntax tree. regex-fallback means the language has one (JS/TS, Python)
but it was unavailable for that file. fallback-language means DocGuard has no
parser for the language at all — Go, Java, Kotlin, Ruby, Rust, PHP, C# — so
routes and env reads there are matched by pattern. Either way the absence of
a finding there is weak evidence, and the owning validator reports
applicability: partial with a reason that names the language and the file
count. Environment variables are matched by pattern in every supported
language; a source language with no env patterns (Swift, Scala, …) makes the
Environment check partial rather than a silent pass.
Every channel appears on every finding in guard --format json, in SARIF
result.properties, and per-issue in diagnose --format json (which also emits
a dispositionCounts summary). guard, diagnose, ci and report all print
the act/escalate split beside the verdict; report adds a column per channel to
its findings table. Run docguard explain <CODE> for one code's evidence.
📄 Templates
DocGuard ships 18 professional templates with metadata, badges, and revision history:
Template
Type
Purpose
ARCHITECTURE.md
Canonical
System design, components, layer boundaries
DATA-MODEL.md
Canonical
Schemas, entities, relationships
SECURITY.md
Canonical
Auth, permissions, secrets management
TEST-SPEC.md
Canonical
Test strategy, coverage requirements
ENVIRONMENT.md
Canonical
Environment variables, deployment config
REQUIREMENTS.md
Canonical
Spec-kit aligned FR/SC IDs, user stories
DEPLOYMENT.md
Canonical
Infrastructure, CI/CD, DNS
ADR.md
Canonical
Architecture Decision Records
ROADMAP.md
Canonical
Project phases, feature tracking
KNOWN-GOTCHAS.md
Implementation
Symptom → gotcha → fix entries
TROUBLESHOOTING.md
Implementation
Error diagnosis guides
RUNBOOKS.md
Implementation
Operational procedures
VENDOR-BUGS.md
Implementation
Third-party issue tracker
CURRENT-STATE.md
Implementation
Deployment status, tech debt
AGENTS.md
Agent
AI agent behavior rules
CHANGELOG.md
Tracking
Change log
DRIFT-LOG.md
Tracking
Deviation tracking
llms.txt
Generated
AI-friendly project summary (llmstxt.org)
🤖 AI Agent Support
One-click MCP install
Claude Code: claude mcp add docguard -- npx docguard-cli mcp
Claude Desktop: download docguard-v<version>.mcpb from the latest release and drag it into Settings → Extensions — you'll be asked which project folder to analyze. No npm, no JSON editing.
Anything MCP: DocGuard is a verified namespace on the official MCP registry (io.github.raccioly/docguard).
DocGuard works with every major AI coding agent. All canonical docs are plain markdown, portable across vendors.
Registers a PostToolUse hook in the project's .claude/settings.json. After the
agent edits a canonical doc it is nudged to run docguard guard --changed-only;
after it edits a code file the docs reference, it is nudged toward docguard impact.
Merge-safe (only DocGuard's own entry is ever added/removed), throttled to one nudge
per file per 30 minutes, and the hook runtime can never break a session (errors are
silent by contract). Explicit opt-in — init never installs it for you.
⚡ Slash Commands
DocGuard ships four slash commands (commands/ in this repository):
Command
What It Does
/docguard.guard
Run quality validation across every validator
/docguard.review
Analyze doc quality and suggest improvements
/docguard.fix
Generate targeted fix prompts for specific issues
/docguard.score
CDD maturity score with an improvement roadmap
Where they go depends on your agent. With a Spec Kit integration that uses skills (Claude Code,
Codex, Cursor, Copilot), DocGuard installs its skills instead, and Spec Kit installs the
speckit.docguard.* extension commands. The /docguard.* files are written to .agent/commands/
only for Spec Kit's generic integration, or when no Spec Kit integration is present. The
Coding Agents reference lists the
exact paths for each agent.
🧠 AI Skills (Enterprise)
Beyond slash commands, DocGuard provides 5 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 skill architecture.
Skill
What It Does
docguard-guard
6-step quality gate with severity triage (CRITICAL→LOW), structured reporting, remediation
docguard-fix
7-step research workflow with per-document codebase research and 3-iteration validation loops
docguard-review
Read-only semantic cross-document analysis with 6 analysis passes and quality scoring
docguard-score
CDD maturity assessment with ROI-based improvement roadmap and grade progression
docguard-sync
Refreshes code-truth doc sections in place and flags the prose sections to review when code changes
Workflow Hooks
DocGuard integrates into the spec-kit workflow as an automated quality gate:
Hook
When
Behavior
before_specify
Before /speckit.specify
Mandatory — briefs the agent on existing specs (speckit.docguard.brief)
before_tasks
Before /speckit.tasks
Mandatory — preflight check of the generated spec (speckit.docguard.preflight)
after_implement
After /speckit.implement
Mandatory — runs DocGuard guard; then optionally records completion
after_converge
After /speckit.converge
Optional — records spec completion (speckit.docguard.complete)
after_tasks
After /speckit.tasks
Optional — shows CDD maturity score
Orchestration Scripts
For advanced users and CI/CD pipelines, DocGuard includes bash scripts with --json output:
Script
Purpose
docguard-check-docs.sh
Discover project docs, return JSON inventory with metadata
docguard-suggest-fix.sh
Run guard, parse results, output prioritized fixes
docguard-init-doc.sh
Initialize canonical doc with metadata header
📁 Examples
Three real-world projects to see DocGuard in action:
npm test# 4,334 tests (node:test, zero test dependencies)
Covers all 28 commands, every validator, project type detection, compliance profiles, JSON/SARIF/JUnit output, the packed npm tarball, and downstream field reports replayed as regression cases. Static test-case declarations are a lower bound of that number: Metrics-Consistency flags this line if it ever falls below what the test files declare.
CI Matrix
Node.js
OS
Status
18
ubuntu-latest
✅
20
ubuntu-latest
✅
22
ubuntu-latest
✅
24
ubuntu-latest
✅
Self-Validation (Dogfooding)
DocGuard runs its own guard, score, diff, diagnose, and badge commands against itself in CI — ensuring the tool passes its own checks.
🏢 Enterprise Adoption
Everything runs locally or in your CI, and your data stays in your infrastructure.
The pieces that matter at company scale:
Need
DocGuard answer
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)
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
docguard ci records every run to .docguard/history.jsonl; score --trend shows the sparkline + delta
AI agents on the team
MCP server (stdio or team-shared HTTP) exposes guard, score, verify, report, doc navigation and task context as read-only tools; agents --sync keeps the whole agent-file family drift-proof
Data-integrity framing auditors know
ALCOA+ scoring (FDA 21 CFR Part 11 / EMA Annex 11 vocabulary) built into score and report
⚙️ CI/CD Integration
Full recipes: see docs-canonical/CI-RECIPES.md for guard, auto-fix (commits mechanical fixes back to PRs), nightly sync, score-on-PR, and pre-commit configs.
GitHub Actions — Guard (most common)
yaml
name:DocGuardGuardon: [pull_request, push]
permissions: { pull-requests:write } # for the sticky PR comment (optional)jobs:docguard:runs-on:ubuntu-lateststeps:-uses:actions/checkout@v4with: { fetch-depth:0 }
-uses:raccioly/docguard@v0.48.0with:command:guard
The action installs the docguard-cli version it was released with, so pinning
the action pins the CLI too. Set docguard-version: latest (or an exact
x.y.z) to override.
On pull requests, guard mode also gives inline PR feedback (both default on):
Input
Default
Description
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)
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
Both run even when guard fails — that's when the feedback matters. Prefer native
code-scanning integration? docguard guard --format sarif uploads straight to
GitHub Code Scanning via github/codeql-action/upload-sarif.
Calibrated finding channels — disposition, evidence.status and parserTier now sit
beside severity and confidence on every finding, so "does CI block", "who decides",
"how sure is the detector", "has this code ever been measured" and "which analyzer saw it"
stop being one overloaded field. See Reading a Finding.
Adoption baseline — guard --update-baseline freezes a legacy repo's existing findings
into a committed .docguard.baseline.json; guard/ci then gate only NEW drift, with suppression
always visible. Adopt today, burn down at your own pace.
docguard report — commit-stamped compliance-evidence bundle (guard verdict, findings by
code, CDD score, ALCOA+ attributes, fix history) with a tamper-evident sha256 integrity hash.
Also exposed as the docguard_report MCP tool.
Score history + score --trend — docguard ci records every run to
.docguard/history.jsonl; the trend view shows the sparkline and delta over time.
Three machine formats for guard — --format json, --format sarif (GitHub Code
Scanning), and --format junit (GitLab, Jenkins, Azure DevOps, CircleCI).
MCP server, stdio + team HTTP — guard, score, verify, report, doc navigation and task
context as read-only agent tools: claude mcp add docguard -- npx docguard-cli mcp.
Agent-file family sync — agents --sync treats AGENTS.md as canonical and regenerates
CLAUDE.md / .cursor/rules / Copilot / Gemini variants with drift-proof source-hash markers.
verify --evidence, verify --semantic, and verify --instructions — check exact local
evidence declarations first, extract remaining numbers/limits/enums as agent tasks, and audit
agent-instruction files for contradictions and stale pointers.
docguard agent — one-shot ordered task graph with pre-filled code-truth, collapsing ~10
agent round-trips into one call.
docguard agent --task <text> — opt-in task context from approved current
specs and canonical docs, with hashed excerpts, source/test pointers, strict
budgets, and honest abstention. The frozen 27-run evaluation preserved every
tested behavior and cut median steps by 50% and latency by 17% versus the
context pack, while using 80% more uncached input tokens.
DocGuard reads documentation written in any language, but a few labels it looks for are matched in English only. Support for other languages is tracked in issue #644.
Works today. Prose in any language, accents included, and requirement ids such as FR-001 inside sentences in any language.
Must stay in English today. Write these labels exactly as shown and keep everything else in your language:
Canonical document headings (case-insensitive; a leading section number is fine): ARCHITECTURE.md needs ## System Overview, ## Component Map and ## Tech Stack; DATA-MODEL.md needs ## Entities; SECURITY.md needs ## Authentication and ## Secrets Management; TEST-SPEC.md needs ## Test Categories and ## Coverage Rules; ENVIRONMENT.md needs ## Environment Variables and ## Setup Steps. A project profile can add more required headings.
Spec Kit section names: a spec.md needs a heading containing User Scenarios, Requirements and Success Criteria, plus ids such as FR-001 and SC-001; a plan.md needs Summary, Technical Context and Project Structure; a tasks.md needs a Phase 1 style heading and ids such as T001.
Changelog marker: CHANGELOG.md must contain [Unreleased].
Decision-record status: the first word of **Status:** must be Proposed, Accepted, Rejected, Deprecated or Superseded (also accepted: Approved, Draft, Proposal, Obsolete, Replaced).
A required section that does not apply to your project can be marked with <!-- docguard:section <slug> n/a — reason -->, where <slug> is the English heading in lowercase with hyphens (for example system-overview). The reason must begin with a letter or digit from A-Z, a-z or 0-9.
Ignore the text-quality numbers. Passive voice, negation, conditional load and the similar metrics rely on English word lists, so for documents in another language their numbers carry no meaning until DocGuard can say so itself.
⚙️ Configuration
Create .docguard.json in your project root (auto-generated by docguard init):
DocGuard'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:
What the labels measure. DocGuard borrows TRACE's HIGH/MEDIUM/LOW vocabulary as deterministic strata (a validator's check pass-ratio). Detector precision is the quantity DocGuard actually measures: on a labelled, deliberately balanced benchmark corpus, published with sample sizes and Wilson 95% bounds in benchmarks/baseline.json (contract: schemas/docguard-benchmark-baseline.schema.json). Every number there carries a caveat explaining that benchmark precision on a balanced corpus differs from the base rate of stale claims in your repository. See VALIDATION.md.
⭐ Star History
🔒 Privacy & Supply Chain
DocGuard is local-first: no telemetry, no analytics, no phone-home — the full
(short) policy is in PRIVACY.md. npm releases are published with
provenance attestation,
so you can verify each tarball was built by GitHub Actions from this repository.