audit-docs
Audit documentation indexes, frontmatter, and links. Apply safe additive repairs; request confirmation for destructive changes.
- License 许可
- MIT
- 最近更新
- 2026-11-12
- Stars
- ★ 0
- Forks
- 0
01 前言 Front Matter
- name
- audit-docs
- model
- opus
- context
- fork
- metadata
- { "tags": "audit, integrity, validation, drift-detection", "bundles": "crux-docs", "triggers": "audit docs | check docs | find drift | verify docs integrity", "risk_level": "low", "routing_note": "Full vault-walk; mostly read-only.", "requires_access": "write-tree" }
- description
- Audit documentation indexes, frontmatter, and links. Apply safe additive repairs; request confirmation for destructive changes.
02 资源文件 4
- 参考文档references/legacy-claude-adapter.md3.7 KB
- 参考文档references/migrate-mode.md8.8 KB
- 参考文档references/output-format.md2.1 KB
- 参考文档references/pitfalls.md3.7 KB
03 SKILL.md 正文
Audit Docs
Execution context: this skill runs in a forked subagent and returns a summary to the caller. The fork does not see the main-thread conversation, so pass any needed context explicitly at invocation.
<!-- BEGIN GENERATED: runtime-compat -->
Runtime compatibility
This skill is portable across Claude Code, Codex, OpenCode, and OMP (Oh My Pi). This section overrides platform-specific labels below.
- Before running a command that uses
CRUX_PLUGIN_ROOT, set it to the installed plugin root. In Claude Code, use the value ofCLAUDE_PLUGIN_ROOT. In Codex, OpenCode, and OMP, derive it from the absolute path of this selectedSKILL.md: the plugin root is the parent of itsskills/directory (in OMPbash,skill://<name>resolves to the skill directory). In a source checkout, use the checkoutcrux/directory. - For project-local skills, use
.claude/skillsin Claude Code,.agents/skillsin Codex,.opencode/skillsin OpenCode (which also reads the singular.opencode/skill), and.omp/skillsin OMP. SetCRUX_LOCAL_SKILLS_DIRto that path before following any command below that uses it. - Translate Claude Code tool labels such as
Agent,Read,Write,Bash,WebSearch, andWebFetchto the matching capability in the current session. Codex names its own capabilities; OpenCode uses the lowercase formssubagent,read,edit,shell,websearch, andwebfetch, whereeditcovers bothEditandWrite; OMP usestask,read,edit,write,bash,grep,glob,find,todo, andweb_search(wherereadalso handles URLs andskill://URIs). Do not attempt to invoke the Claude Code labels as literal commands on another host. - Install the generated role agents before delegating:
install-codex-agentsin Codex,install-opencode-agentsin OpenCode,install-omp-agentsin OMP. Codex names themcrux_architect,crux_brainstormer,crux_commander,crux_dev_lead,crux_developer,crux_historian,crux_librarian,crux_night_gardener,crux_reviewer, andcrux_wayfinder; OpenCode and OMP use the bare role namesarchitect,brainstormer,commander,dev-lead,developer,historian,librarian,night-gardener,reviewer, andwayfinder(in OMP,scoutmay also be used for reconnaissance alongsidewayfinder). If a required role or capability is unavailable, report that truthfully instead of claiming it ran. - Argument placeholders such as
$adrand$bookbind only in Claude Code. On a host without argument binding they are unset — take the value from the user's phrase. The "Fields OpenCode ignores" section ofOPENCODE_GUIDE.mdnames the invocation-control fields OpenCode ignores. <!-- END GENERATED: runtime-compat -->
Current cycle records
Validate new cycle records through cycle.py show and the cycle schema. Review
identity, phase/pass state, references, history, and evidence. Legacy CHK-CYCLE and
promptbook minimum/module checks below apply only to historical promptbooks; never
apply them to new cycle records or repair a cycle into a promptbook.
Overview
The integrity check for the entire docs/ tree. Mirrors the samples audit-vault pattern but spans seven concerns: code, research, ADRs, briefs, journal, promptbooks, and invariants — plus the derived arch spine. Detects every form of drift between docs/index.md, the per-concern indexes, the files on disk, and the cross-concern reference graph (ADR ↔ brief, ADR ↔ research, journal ↔ ADR/promptbook, promptbook ↔ run-snapshot). For the two other regenerated artifacts (docs/code/, the skill catalog) it detects drift and recommends the regenerator; for the arch spine it regenerates in place (CHK-ARCH-1) — arch's inputs are all committed in-tree, so a regenerate can never capture in-flight uncommitted source.
The audit is mostly read-only. Findings are applied in three phases: DRIFT auto-fixes happen with notification; safe-BROKEN fixes happen with notification; destructive-BROKEN fixes require explicit user confirmation. Never auto-deletes a file. Never auto-rewrites an ADR body, a synthesis page's prose, a run-snapshot body, or a journal entry. Never edits past operations-log entries.
Around 97 checks across eighteen concern groups plus the schema/inbox layer. Run on every ~10 writes per concern; proactively recommend after a refresh-research-sources batch updating >5 sources, after a mix docs-driving refactor, before any release, and after an init-docs --force or schema migration.
When to use
- User says: "audit", "audit docs", "audit the docs", "check docs", "verify integrity", "find drift", "is the docs tree clean?".
- Proactively after every ~10 writes per concern. Track in the operations log under
docs/log/— when the count since the last audit reaches ~10 for a concern, mention it. - Immediately after a
refresh-research-sourcesbatch updating >5 sources. - Before any release or external publication.
- After a tree-schema recovery with the tagged release; audit the upgraded copy with the current version.
Do not use this skill for:
- Routine per-write verification — each writing skill has its own checklist.
- Regenerating
docs/code/— that'sextract-code-docs. The audit only callsextract-code-docs --dry-runto detect drift. - Repairing destructive findings without user confirmation — surface them, don't act.
Severity tiers
| Tier | Definition | Default action |
|---|---|---|
| BROKEN | A schema or cross-reference contract is violated. Cannot be ignored. | Block clean-audit. Auto-fix if additive and safe; ask if destructive. |
| DRIFT | Counts, dates, indexes, or rollups out of sync with reality. Recoverable bookkeeping. | Auto-fix with notification. |
| WARNING | Informational. May or may not be a problem. | Report only. |
The pipeline
1. Decide walk strategy
Before recursive walking or configuration discovery, prune retained demonstration holdings: list the holdings once with uv run "${CRUX_PLUGIN_ROOT}/scripts/authority-view.py" retained-roots --repo-root <repo-root> and skip each listed root during recursive walks; test one path with uv run "${CRUX_PLUGIN_ROOT}/scripts/authority-view.py" retained --repo-root <repo-root> <path> (exit 0, retained true or false). Apply this exclusion before split-tree detection, record parsing, census and allocation counts. Never inspect held manifests or nested configuration during those checks. A layout refusal stops the walk before repairs. The holding contract is docs/AGENTS.md §3; direct concern globs need no recursive scan.
Before authority-dependent checks or a clean-audit conclusion, run uv run "${CRUX_PLUGIN_ROOT}/scripts/authority-view.py" state --repo-root <repo-root>. Exit 0 reports original (no clause migration was ever published, so every ADR clause governs as its record says; this is the normal state) or published (a migration publication was proved from full Git history, so the clauses it moved are historical evidence, not current constraints). Exit 1 prints {"authority": "none", "limit": "<code>"}: current authority is unknown. Never fall back to an older ADR body or resolver. The common code is history-unavailable, a shallow clone of a tree that published a migration; fetch full history with git fetch --unshallow. Exit 2 is an environment error. A refusal stops those checks; report it and preserve files. Do not infer publication from an applied flag, summaries, doctrine or an existing roster. Implementation Decisions preserve reviewed intent; results preserve delivery evidence; neither establishes current source state or enters ADR/observation governance through a filename, quotation or mapping. Preserve historical references and surviving architectural clauses within mixed records. Audit may report a genuine architectural conflict; replacing a conforming implementation alone is no revocation finding.
Count total .md files under docs/ after pruning holdings through the shared predicate. An unpruned recursive count includes retained records.
- Fewer than ~100 files: walk inline in the main session using Read/Glob/Grep.
- 100 or more: spawn an Explore agent with the walk prompt below. The agent returns a structured findings report; the main session applies fixes.
Also count per-concern files for the rollup numbers used in docs/index.md.
2. Walk and collect findings
The walk produces a categorized findings list across eleven concern groups (plus the 1.A schema/inbox layer). Each check is named so it can be reported individually.
Concern 0 — Per-repo configuration (the repo-root .crux file, per docs/AGENTS.md §14)
Runs FIRST — the resolved docs_dir is the docs root every later check walks. This is the repo-root .crux file (per-project config, designed to be committed so the team shares it — works identically untracked), not the user-home ~/.crux/ directory. All ADR-NNNN-* / PB-NNNN-* filename globs and id regexes throughout this skill accept an optional artifact prefix per docs/AGENTS.md §14.3 (dual-form: ([A-Z][A-Z0-9]{1,9}-)?(PB|ADR)-(\d{4})).
- CHK-CFG-1 Validate the repo-root layout config via the loader semantics: invoke
python3 "${CRUX_PLUGIN_ROOT}/scripts/bionic-config.py"(the retainedcrux-config.pyis a back-compat delegator to the same entrypoint; either works). Delegate — do NOT re-implement the textual/containment validation or read the YAML ad hoc. Per thedocs/AGENTS.md§14 config contract, the CLI resolves the precedence.bionic.yml> legacy.crux> content-validated bare-directory discovery > default, reporting which won viasource(".bionic.yml" | ".crux" | "discovery:<dir>", with combined forms like".bionic.yml+discovery:<dir>"when a keyless config falls through to discovery). Exit 0 → clean; hold the resolveddocs_dir/artifact_prefixfor the rest of the walk. Exit 1 → BROKEN, reporting the{"error": ...}message verbatim (a malformed/invalid config never falls back to defaults or to the lower-precedence file — per thedocs/AGENTS.md§14.1 fail-loud rule). Both files absent is clean (discovery resolves the tree;source: "discovery:<dir>"when no config exists —"defaults"is not emitted). A.bionic.ymlcoexisting with a legacy.cruxis EXPECTED during migration and is NOT a finding (the CLI just reportssource: ".bionic.yml"). The invariants concern and the tree relocation both shipped;docs_dirnames the tree and the check suite lives inside it (see §14/§15). - CHK-CFG-2 Prefix consistency. Dual-form scan of artifact ids across the tree with
([A-Z][A-Z0-9]{1,9}-)?(PB|ADR)-(\d{4}); collect the distinct prefix spellings (capture 1, with "bare" counting as one). More than one distinct prefix in the tree, OR the dominant prefix ≠ the current.cruxartifact_prefixvalue → WARNING (mixed trees are valid perdocs/AGENTS.md§14.3 — ids are immutable history — but one repo SHOULD converge on one prefix; this is where a typo'd prefix likeCRUX-vsCRX-surfaces). - CHK-CFG-3 Split-tree backstop. A crux-shaped docs tree (a directory containing a
manifest.ymlwith a readableschema_version) exists at any location other than the configureddocs_dir— including the default./docs/in a repo whose.cruxrelocates the tree (the silent second tree a pre-.cruxtoolchain creates by ignoring the file) → BROKEN. Surface both paths and recommend consolidation; never auto-delete or auto-merge. - CHK-CFG-4
(type, NNNN)uniqueness across spellings (thedocs/AGENTS.md§14.3 allocation invariant, asserted mechanically). Dual-form scan([A-Z][A-Z0-9]{1,9}-)?(PB|ADR)-(\d{4})over the tree's artifact filenames and ids; group by (capture 2, capture 3); any pair duplicated across bare/prefixed spellings (e.g. bothPB-0040andCRX-PB-0040, or two different prefixes on the same number) → BROKEN (numbers are never reused, including across prefixes; any max-derivation likewise takes the integer max over capture 3 across bare AND prefixed artifacts).
Concern 1 — Master index and log (mostly DRIFT)
- CHK-MI-1 Every concern enabled in
manifest.yml'sconcerns_enabledhas a corresponding section indocs/index.md. Missing section → DRIFT (auto-add header + rollup). Section for a concern NOT inconcerns_enabled→ WARNING (concern was probably disabled but section wasn't removed; ask).docs/inbox/is NOT a concern — it is cross-concern staging (perdocs/AGENTS.md§11 "inbox is staging") and is deliberately absent fromconcerns_enabled, so CHK-MI-1 must NOT demand a## Inboxsection indocs/index.md. The inbox is excluded from the concern-section walk exactly likedocs/AGENTS.md/docs/README.md(see the non-concern excluded-paths list); its only audit coverage is CHK-SCHEMA-1 + CHK-INBOX-1/2/3.archis a concern but is likewise exempt from this master-section requirement — it is derived and regenerated (perdocs/AGENTS.md§4 "arch"), its catalog is its own<docs_dir>/arch/index.mdplus the spine hash, and a dated master-index rollup row would violate arch's no-timestamp rule. So CHK-MI-1 must NOT demand or auto-add an## Archsection indocs/index.md; arch's coverage is CHK-ARCH-1/2 (Concern 8). - CHK-MI-2 Each concern section's file count in
docs/index.mdmatches the actual file count for that concern. Mismatch → DRIFT (auto-fix). The ADRs rollup has a vendored regenerator:${CRUX_PLUGIN_ROOT}/scripts/generate-index-rollup.pyrebuilds the## ADRs (N)section ofdocs/index.mdas a pure function of ADR frontmatter (--dry-runis its drift gate, exit 1 on drift). For that one section prefer running the regenerator over hand-fixing, and wire its--dry-runinto whatever suite this repo gates on. Every other concern rollup (research, briefs, journal, promptbooks, invariants, code) is prose-checked here only — a passing ADR-rollup gate says nothing about them. - CHK-MI-3
docs/index.mdhas a top-of-file_Last updated: YYYY-MM-DD_line. Missing or stale (older than today after a fix) → DRIFT (set to today on any audit fix; otherwise leave). - Operations-log checks (CHK-LOG-1 to CHK-LOG-7). Run
uv run "${CRUX_PLUGIN_ROOT}/scripts/operation-log.py" check --repo-root <repo-root>and report its JSON. It exits 0 clean, 1 with findings, 2 on an environment fault. The checks read the op-enum regexes from the tree's owndocs/AGENTS.md§6, which stays the single source of truth for them — do NOT restate the enum here. The historical-reader form accepts bothcleanup-campsiteand the legacycleanup(frozen history predating the rename).[^log-enum] A legacydocs/log.md, a stray and a staged file are all read, so each check covers every log file. - CHK-LOG-1 Every
##heading outside a fence in every detail filedocs/log/YYYY-MM.md, legacydocs/log.md, staged file and stray matches the §6 historical-reader regex and carries a real calendar date. It also reports an entry that ends inside an open fence and a detail file whose bytes outside its entries leave a fence open. Malformed → DRIFT-surface (do NOT auto-edit; surface for user review). - CHK-LOG-2 Each detail file's bytes outside its entries are exactly the detail header of §6. Otherwise → DRIFT (never auto-edited; the finding prints the expected header). No check orders heading dates within a file: a file holds entries in write order, so a merged stray block, a backdated write and a release heading dated in another zone each break date order legitimately.
- CHK-LOG-3 The log, every log file read together, holds the bootstrap
initentry frominit-docs. Missing → BROKEN (ask; never auto-regenerate). - CHK-LOG-4 Every operation logged with
<op>outside the enum → BROKEN (typo or unauthorized op; surface). A §6 with no historical-reader block adds a WARNING; one with no op-enum block is BROKEN. - CHK-LOG-5 A legacy
docs/log.md, a stray, a staged legacy file, a staged stray, a split transaction file, or no completion record → DRIFT; the auto-fix runsoperation-log.py repair, which is lossless, and surfaces its refusal. Three states are conflicts with no auto-fix, reported BROKEN: two distinct staged legacy files, a staged legacy file and a staged stray with equal bytes, and a staged legacy file beside the completion record. - CHK-LOG-6 A file in
docs/log/whose name §6 does not define, a log file that is a symlink or not a regular file, or adocs/log/that is not a directory → BROKEN. A leftover writer temporary.write-journal-<hex>→ WARNING. - CHK-LOG-7
generate-log-summary.py --dry-runreports a region failure → DRIFT, auto-fixed by runninggenerate-log-summary.py; a structure failure → DRIFT with no auto-fix (editdocs/log/summary.mdby hand, or runoperation-log.py repair); pending months alone → WARNING, cleared bycleanup-campsite.[^log-gate]
Concern 1.A — Schema version and inbox (see docs/AGENTS.md §7)
The supported-range predicate is the single-value check schema_version == "5". The current plugin operates only on that tree schema. It recognizes "2", "3", and "4" only to direct recovery through the pinned v3.23.2 release. A missing, earlier, newer, or unrecognized value has no promised migration route. Read manifest.yml with a real YAML parse. CHK-INBOX-1/2/3 apply only at schema 5.
- CHK-SCHEMA-1
manifest.ymlcarriesschema_version == "5"with no in-flight.migratingmarker. Any other value or marker → BROKEN. For"2","3", or"4", and for a valid partial marker, give the pinned recovery route inreferences/migrate-mode.md. An invalid marker or ambiguous pair of trees refuses without guessing. For every other schema value, report incompatibility without promising conversion. Never auto-bump the value or change a marker. - CHK-INBOX-1 At schema 5,
docs/inbox/exists. Missing → BROKEN. Inspect the tree and repair the missing directory without treating it as an older schema; do not auto-create it during a plain audit.
Concern 1.B — Repository instruction files (see docs/AGENTS.md §18)
AGENTS.md is the canonical file at every managed instruction scope. These rules
are report-only in a plain audit; --migrate applies the validated plan. Run
the vendored script rather than reimplementing discovery here — it owns the
scope boundary, the classification, and the set-aside:
uv run "${CRUX_PLUGIN_ROOT}/scripts/migrate-instructions.py" --repo-root . --dry-run
Two sets, and conflating them is the defect these rules exist to prevent. The MUTATION set is the entries and index paths of each touched scope of this one checkout: a directory holding a tracked instruction file. A vendored dependency cache and a linked worktree hold no file tracked here, so they are outside it by construction. The SUPPRESSION set is wider and includes untracked files, because a file crux must not touch can still silence the canonical one.
-
CHK-INSTR-1 No managed scope holds a committed
CLAUDE.md. One present → DRIFT, remediationaudit-docs --migrate. Never migrate during a plain audit. -
CHK-INSTR-2 No scope holds two names in one case-folded family (
CLAUDE.mdplusClaude.md), counted across the directory and the index → BROKEN.--migraterefuses the scope rather than guessing which name wins, and the report names both paths and the next step. -
CHK-INSTR-3 Every suppressor under the checkout is reported with its remedy: an untracked
CLAUDE.md, a.claude/CLAUDE.md, aCLAUDE.local.md, and a tracked legacyCLAUDE.mdthat has not yet migrated. A suppressor on the chain from the root to the working directory is WARNING, because under the host's default mode it silences the canonical file outright. One off that chain is INFO — it is reported, and it changes nothing about what this host loads now. Never delete a private override; report it. -
CHK-INSTR-4 A scope
--migraterefused, stopped, or migrated without staging, a scope whose index holds a path its directory no longer lists, and every set-aside entry (<name>.crux-set-aside-<hash>) → WARNING. Some set-asides hold content that no longer loads, and the report'sno_longer_loadedlist names them. Other set-asides hold a winner, or a loser the winner imported, and that content still loads. A set-aside row carries no next step. A refused or stopped scope names its blocking entry and a next step. A scope that stages nothing names its reasons instages_nothing_because, and its index-only blobs with a save command. Each blocks its own scope and no other. -
CHK-INSTR-5 The host loads what this tree publishes. Run
uv run "${CRUX_PLUGIN_ROOT}/scripts/check-claude-compat.py" --repo-root .; an unsupported verdict is a WARNING carrying the verdict's ownreasons. A version number alone never settles this, so never report compatibility from one. Three of the five host causes are repaired by a setting rather than a file; the remaining two route toreferences/legacy-claude-adapter.md, which is opt-in and never part of a normal install.managed-onlyis repaired by configuration alone and never by the adapter. A sixth cause is a missingAGENTS.md: noAGENTS.mdon the chain from the root to the working directory (and, underclaude-md-and-agents-md, noCLAUDE.md) means the host loads none of this tree's instructions. Its remedy is to create anAGENTS.mdspelled exactly so.init-docscreates one only while it initialises a tree in a root that holds noAGENTS.mdorCLAUDE.mdin any letter case. ACLAUDE.local.mddoes not block that create. The remedy is never the adapter, which derives from that file. -
CHK-INBOX-2 At schema 5,
docs/research/new/is absent. Present → DRIFT. Inspect its contents and move pending drops intodocs/inbox/without overwriting or deleting them; never auto-delete this directory during a plain audit. -
CHK-INBOX-3 When
schema_version == "5": count non-.gitkeepentries indocs/inbox/excluding the_dispatched/subtree (a partially-drainedurls.mdlegitimately counts). Non-empty → WARNING"N items pending in docs/inbox/"(NOT BROKEN — pending drops are normal; the user runsprocess-inboxto triage). Empty → no finding.
Concern 1.B — Invariants (per docs/AGENTS.md §15; conditional on schema_version == "5" AND invariants in concerns_enabled)
The invariants concern has a ledger under <docs_dir>/invariants/ (a walked concern, gets a docs/index.md section) AND an executable check suite at <docs_dir>/invariants/checks/ reconciled via the .bionic.yml-rooted manifest (NOT a docs concern section — the surface the rules below reconcile). All CHK-INV rules read the canonical schema in docs/AGENTS.md §15 (do NOT restate it here). When the concern is disabled (or the tree is pre-v4), these rules are silent. Pin-level last_result is the §15.4 aggregate (fail>stale>pass>none). The rules are reference-implemented and tested in ${CRUX_PLUGIN_ROOT}/scripts/check_invariants.py (exit 0 clean / 1 findings, JSON on stdout) — CHK-INV MAY delegate to it, the same pattern CHK-CFG-1 uses for crux-config.py and CHK-CAT-3 for validate-catalog.py.
- CHK-INV-BIJECTION pin↔ledger-page is 1:1: a ledger page with no parseable
id, a duplicateid, or a reconciliation entry naming a pin with no ledger page → BROKEN. - CHK-INV-ORPHAN-CHECK every check in
<docs_dir>/invariants/checks/resolves via the reconciliation to exactly one existing pin; a check tracing to no/missing pin, or acheck_idabsent from the suite → BROKEN. - CHK-INV-DECORATION a
ratifiedpin with no resolvable check OR aggregatelast_result: none→ BROKEN (a trusted pin nothing proves). Anobservedpin with zero checks is NOT flagged (expected known-unknown). - CHK-INV-FAILING a
ratifiedpin whose aggregatelast_resultisfail→ BROKEN;stale→ WARNING. - CHK-INV-DANGEROUS an
observedpin with aggregatelast_result: pass→ WARNING (a green check that may be cementing unratified behavior). Plus survey-debt: surface the count ofobservedpins (never as a coverage percentage).
Concern 1.C — Observations (per docs/AGENTS.md §17; conditional on observations in concerns_enabled)
The observations concern has a set of records under <docs_dir>/observations/ (a walked concern, gets a docs/index.md section) plus <docs_dir>/observations/index.md, which is hand-maintained by propose-observation / transition-observation — not a regenerated artifact. An index row naming a record with no file, or a file with no index row, is therefore a real finding, never something to silently rewrite. All CHK-OBS rules read the canonical schema in docs/AGENTS.md §17.1 (do NOT restate it here) and the lifecycle in §17.2. They are reference-implemented and tested in ${CRUX_PLUGIN_ROOT}/scripts/check_observations.py (exit 0 clean / 1 findings, JSON on stdout) — CHK-OBS MAY delegate to it, the same pattern CHK-INV uses for check_invariants.py. When the concern is disabled, these rules are silent, and so is the checker.
<docs_dir>/observations/_surveys/is EXCLUDED from every CHK-OBS record walk. It is the frozen holding area for signed review sheets and their receipts, on thedocs/promptbooks/legacy/model: present on disk, invisible to the concern walk, and carrying nodocs/index.mdsection. The record walk is*.md-scoped and the live sheet is<docs_dir>/observations/survey-SVY-NNNN.yml, so neither the live sheet nor anything under_surveys/is a record — a.ymlbeside the records is never a stray-file finding. Do not glob_surveys/for CHK-OBS-BIJECTION (record↔file), CHK-OBS-ANCHOR, CHK-OBS-EVIDENCE, CHK-OBS-DECIDED, or CHK-OBS-STALE. Its only coverage is the four CHK-OBS-SURVEY-* rules below, which read it as batch state rather than as records.
- CHK-OBS-BIJECTION record↔file is 1:1: a file under
<docs_dir>/observations/with no parseableid, a duplicateid, anidthat disagrees with its filename, an index row naming a record with no file, or a record file whoseidappears in no index row → BROKEN. The last direction is the reverse of the one before it, and both run only whenindex.mdexists. - CHK-OBS-ANCHOR
anchor_idis present on every record and matches^[0-9a-f]{16}$→ BROKEN when it is absent or malformed. No two records inobservedorratifiedstatus share ananchor_id→ BROKEN on a collision. This is what makes a re-mine recognize a fact already recorded (§17.2); a record missing the field is silently skipped by the re-mine, which then proposes a duplicate. - CHK-OBS-EVIDENCE every
evidenceentry matches thepath:line-rangegrammar, and aratifiedrecord resolves every path it cites → BROKEN on an unresolvable path, an unparseable entry, or an emptyevidencelist. A cited path must also resolve to a location inside the repository root: an absolute path, a~-prefixed path, a..traversal, or a path reaching outside the root through a symlink is the same finding. - CHK-OBS-DECIDED a
decidedrecord names adecided_byADR that exists → BROKEN when it does not. A non-decidedrecord carrying a non-nulldecided_by, or adecidedrecord carryingnull, is the same finding. - CHK-OBS-STALE an
observedrecord whoseobserved_dateis older thanobservation.stale_daysinmanifest.yml(absent falls back to 90) → WARNING. Report survey-debt as the count ofobservedrecords, never as a coverage percentage: the denominator would be the facts nobody has written down, which nobody knows.
Four more rules read the batch surfaces contracted in docs/AGENTS.md §17.5 (do NOT restate that protocol here). Each derives batch state through the one shared function §17.5 names, so a gate never disagrees with the writer.
- CHK-OBS-SURVEY-STUB a receipt under
<docs_dir>/observations/_surveys/SVY-NNNN/recording no completion → WARNING insideobservation.survey_stub_daysinmanifest.yml(absent falls back to 1), which is what a sign-off still in progress looks like, and BROKEN past that window. The remedy is re-running the sign-off, which finishes the publish. - CHK-OBS-SURVEY-VISIBLE a record visible under
<docs_dir>/observations/whose receipt records no completion → BROKEN at any age. No healthy in-flight state produces one, because §17.5 lands completion before visibility. - CHK-OBS-SURVEY-DIGEST a receipt whose recomputed digest no longer matches the sheet archived beside it → BROKEN.
- CHK-OBS-SURVEY-RECORD a
ratifiedrecord whoseanchor_idno receipt covers and behind which noobservationlog op stands → BROKEN. The rule is a disjunction and stays one: the single-record path writes no receipt, so a conjunction would report BROKEN on every record that path wrote. It detects an unrecorded batch and never a forgery, because an actor with write access can write every surface.
Concern 2 — Code (mostly BROKEN if wrong, DRIFT via dispatcher)
- CHK-CODE-1 If
codeis inconcerns_enabled,docs/code/_meta/manifest.jsonexists. Missing → BROKEN (recommendextract-code-docs, do not invent). - CHK-CODE-2 Every row in
_meta/manifest.jsonhas an existing.mdfile atdoc_path. Missing files → BROKEN (likely deleted hand or by a failed write; recommend re-extraction). - CHK-CODE-3 Every
.mdfile underdocs/code/(other thanindex.mdand_meta/manifest.json) is listed in the manifest. Orphan files → BROKEN (these are hand-edits that survived a regenerate, OR a stale file from before the prune step landed). Recommend re-runextract-code-docsto clean (it will delete them). - CHK-CODE-4 Drift detection: invoke
uv run --no-config "${CRUX_PLUGIN_ROOT}/scripts/extract-code-docs.py" --dry-run --config docs/manifest.ymlfrom the repo root.[^code-doc-uv] Parse stdout as JSON regardless of exit code, on three lanes, never conflated (the same exit-code semantics asverify-code-docs): exit 0 +drift: false= clean; exit 1 +drift: true= DRIFT (byte-level, against actual bytes on disk — surface thepageslists and theindex_drift/metadata_driftflags and recommend a real run; a freshunownedcount under a--lang-scoped tree is reported, not drift); exit 1 + avalidation_errorspayload and nodriftkey = BROKEN (tree-content is malformed — regenerating cannot fix it; name the path and cause); non-zero + empty/unparseable stdout = an environment failure (capability mismatch or auvresolution failure before the dispatcher starts), never a document finding. A metadata-only drift immediately after a plugin upgrade is expected and clears after one fullextract-code-docsrun. DO NOT auto-run a real extraction during the audit — that'sextract-code-docs's job, and is destructive enough to warrant explicit user invocation. - CHK-CODE-5
docs/code/index.mdexists and has one section per language namespace underdocs/code/. Missing → DRIFT (will regenerate on next extract; flag).
Concern 3 — Research (mirrors samples audit-vault)
- CHK-RES-1 Every
docs/research/sources/<slug>.mdhas required frontmatter:title,slug,type: source,source_url,source_date,author,captured_at,last_source_check,raw_path,previous_captures,static,tags(the canonical field list —ingest-researchwrites it, this check enforces it). Missing → BROKEN. - CHK-RES-2
slugin frontmatter matches the filename. Mismatch → BROKEN. - CHK-RES-3
raw_pathresolves to an existing directory underdocs/research/raw/. Broken path → BROKEN. - CHK-RES-4 Every entry in
previous_capturesresolves to an existing directory. Broken → BROKEN. - CHK-RES-5 Every directory
docs/research/raw/<YYYY-MM-DD>/<slug>/is referenced by exactly one source page viaraw_pathorprevious_captures. Orphan raws (no reference) → BROKEN. Shared raws (multiple references) → BROKEN. - CHK-RES-6 Every synthesis page under
docs/research/<category>/has required frontmatter:title,slug,type(matches dir),tags,sources,last_reviewed(the canonical synthesis field list —ingest-researchwrites it, this check enforces it). Missing → BROKEN. - CHK-RES-7 Every slug in any synthesis page's
sources:list exists indocs/research/sources/. Dangling → BROKEN. - CHK-RES-8
docs/research/sources.mdexists at the research root with 9 columns matching samples. Missing → BROKEN (do NOT auto-regenerate; ask). Wrong column set → BROKEN. Per-row column mismatches against frontmatter → DRIFT (auto-fix from frontmatter; frontmatter is source of truth). - CHK-RES-9
docs/research/updates.mdexists. Missing → DRIFT (create stub header only — no entries). Every##heading matches## \[\d{4}-\d{2}-\d{2}\] <slug>. Malformed → WARNING (surface, don't edit). - CHK-RES-10 Every
[[research/sources/<slug>]]and[[research/<category>/<slug>]]link resolves. Dangling → BROKEN. - CHK-RES-11 Count
> [contradiction],> [unresolved],> [source updated],> [refresh failed]markers and## Capture gapssections across research pages. → WARNING (report counts).
Concern 4 — ADRs and briefs
-
CHK-ADR-1 Every
docs/adrs/ADR-NNNN-*.mdhas the required frontmatter keyset defined canonically indocs/AGENTS.md§11.A "Canonical ADR frontmatter schema" (the single source of truth — do NOT restate the field list here; read §11.A). Any field §11.A marksrequiredthat is missing → BROKEN. Theamends:field isoptionalper §11.A (see CHK-ADR-6a for resolution semantics). -
CHK-ADR-1a The frontmatter keyset of
${CRUX_PLUGIN_ROOT}/templates/ADR-template.mdMUST equal the canonical keyset indocs/AGENTS.md§11.A. Mechanical comparison — set equality, order-independent (the template orders fields differently from §11.A; that is fine): (1) extract the backticked tokens from §11.A's first table column — every entry in that column uses backtick markup, so a row whose field is not backticked is itself a §11.A formatting bug and should be flagged; (2) parse the template's YAML frontmatter for its top-level keys (use a real YAML parse via Bashpython3 -c 'import yaml,sys; print("\n".join(yaml.safe_load(...)))'rather than a line-grep — a grep would miss a key whose value shares the line, e.g.amends: [] # ...); (3) compare the two SETS. Any key in one but not the other → WARNING ("ADR template and §11.A schema have drifted; reconcile against §11.A"). This closes the loop so the template itself cannot silently drift from the schema. A stdlib unit test (${CRUX_PLUGIN_ROOT}/scripts/tests/test_schema_invariants.py) enforces the same invariant in CI. -
CHK-ADR-2
idmatches filename prefix. Mismatch → BROKEN. -
CHK-ADR-3
status∈ {Proposed, Accepted, Deprecated, Superseded}. Invalid → BROKEN. -
CHK-ADR-4 ADR numbering is monotonic and contiguous from 0000 with no gaps and no duplicates. Gap → WARNING; Duplicate → BROKEN, detected by CHK-NUM-1. The "ask" on a gap is concrete — distinguish two dispositions by whether the deleted number is still referenced anywhere: scan the tree (ADR
supersedes:/superseded_by:/amends:frontmatter, anyadrs/ADR-NNNNwiki-link, and thedocs/adrs/index.mdrows) for the gap'sADR-NNNN. (1) Gap with NO surviving references → the number is almost certainly a deleted Proposed ADR that was never cited; it is renumberable — recommend the user either reuse the gap by renumbering the next allocation down to close it, or leave it as a permanent hole (numbers are never reused once cited, but an uncited deleted-Proposed hole may be reclaimed). (2) Gap WITH surviving references → some artifact still points at the missingADR-NNNN; it is NOT renumberable — surface every referencing path and recommend either restoring the ADR or fixing the dangling references; do not propose reusing the number. (This is a generic reference scan — crux has no separate id-validation machinery; do not cite one.) -
CHK-ADR-5 State-machine date consistency:
proposed_dateis non-null for every ADR (every ADR was proposed at some point).accepted_dateis non-null iffstatus∈ {Accepted, Deprecated, Superseded} AND the ADR ever passed through Accepted (Proposed → Deprecated is allowed; an ADR with status=Deprecated and accepted_date=null is the "abandoned proposal" case).deprecated_dateis non-null iffstatus == Deprecated.superseded_dateis non-null iffstatus == Superseded.- Any violation → BROKEN (surface; never auto-set a date).
-
CHK-ADR-6 Supersession bidirectionality: for every
superseded_by: ADR-X,ADR-X.supersedescontains this ADR. For every entry in anysupersedes: [...], the target hassuperseded_bypointing back. Mismatch → BROKEN (auto-fixable viatransition-adr --repairon user approval; never silent). -
CHK-ADR-6a Optional top-level
amends:field on an ADR is a YAML list of ADR ids (e.g.,[ADR-NNNN, ADR-MMMM]). When present: every entry must resolve to an existing ADR file underdocs/adrs/. Dangling → BROKEN. Unlikesuperseded_by:/supersedes:,amends:is one-way — the amending ADR records the relationship; the amended ADRs' frontmatter is NOT back-populated and noamended_by:field is enforced. It records narrow-scope decision refinements to predecessor ADRs without overwriting theirsuperseded_by:chain. Distinct fromsupersedes:(which IS bidirectional and replaces the predecessor'ssuperseded_by:). -
CHK-ADR-7
manifest.yml'sadr.next_number> max existing ADR number. Equal-or-less → BROKEN (next allocation would collide). Way greater than max+1 → WARNING (gaps suggest deletions; ask). -
CHK-ADR-8 Every entry in
related_briefs:corresponds to an existingdocs/briefs/BRIEF-<slug>.md. Dangling → BROKEN. -
CHK-ADR-9 Every entry in
related_research:resolves underdocs/research/, behind a fail-closed grammar gate (the entry is author-controlled frontmatter that gets path-joined, so it inherits the §14.2 containment posture — reject, never resolve, any entry with.., a leading/,~, or more than one/): a bare slug matching^[a-z0-9-]+$→docs/research/sources/<slug>.md(backward-compatible); a single-segment path matching^[a-z0-9-]+/[a-z0-9-]+$→docs/research/<category>/<slug>.md(a synthesis page; the explicitsources/<slug>form falls out for free). Any entry matching neither grammar (a traversing entry, or any other shape — trailing slash, uppercase, underscore, etc.) → BROKEN (malformed). No file at the grammar-valid resolved path → BROKEN (dangling). One-way: the target research page is NOT back-populated. -
CHK-ADR-10 Brief-side bidirectionality: every brief listed in any ADR's
related_briefs:has its slug in its ownrelated_adrs:frontmatter. Missing back-ref → DRIFT (auto-fix on briefs; briefs are draft material so back-population is safe). -
CHK-ADR-11 Briefs cited with
status: draft→ WARNING ("ADR-X references brief Y still in draft; decision may need a follow-up"). -
CHK-ADR-12
docs/adrs/index.mdexists with one row per ADR (columns: id, title, status, date, supersedes, superseded_by). Missing rows → DRIFT (auto-add from frontmatter). Orphan rows → BROKEN (ask). -
CHK-ADR-SPEC The ADR body content rule — an ADR body states requirements and postconditions rather than implementation recipe — is defined canonically in
docs/AGENTS.md§11.D "ADR body content rule" (the single source of truth — do NOT restate the rule or the budget's value here; read §11.D). This rule REPORTS ONLY. It never repairs, never proposes an edit, and never asks: an ADR body pastProposedis frozen, so there is nothing here to fix even when the finding is correct. Severity is WARNING on every finding, including a clear one.Cohort gate — evaluate this FIRST and skip the whole rule when it does not pass. Read
docs/manifest.ymladr.spec_rule_from— that key inside theadr:block, addressed by a real YAML parse and not by a line-grep, which would also match the same key name under a different block. Absent,null, or not an integer ADR number → the rule is inert: emit no findings and no warnings, and say so in the report's ADR section in one line. A tree that never adopted the rule must produce silence, not noise. Otherwise the cohort is every ADR whose number is ≥ that value, across both the active and archived tiers; every ADR below it is exempt permanently.Two findings, per §11.D:
- Over budget without a declaration. Measure the span from the body's
## Contextline through the last non-blank line before## References, per §11.D's rule 3 (## Referencesand any footnote block are outside the span). Over §11.D's stated budget → WARNING, unless the body carries §11.D's justification blockquote immediately under## Context, in which case it is not a finding. Also not a finding when the ADR is itself a source of truth for a shape (§11.D rule 4's exemption). Report the measured span and the budget, so the reader can see the margin. - Body content shaped like a recipe. Heuristic, and stated as one: a fenced code block outside
## References; a call signature or function definition in prose (name(arg=…),def,class); a command recipe with flags; a| field | type |shape table restating a schema the body could have named instead. Each hit → WARNING naming the line, phrased as a prompt to look rather than a verdict.
State the heuristic's error rate in the report, every run. This rule reports bodies that are fine and misses bodies that are not. A reader who mistakes a WARNING here for a defect will try to edit a frozen body, which is the one action the rule forbids.
- Over budget without a declaration. Measure the span from the body's
Concern 4.A — Objectives (per docs/AGENTS.md §5.B)
<docs_dir>/objectives.md is a top-level, hand-authored file: the mission and goals a decision review measures the decision set against. It belongs to no concern and has no docs/index.md section, so no concerns_enabled entry gates these rules. They run on every audit of a schema_version == "5" tree. A missing file is CHK-OBJ-1's own finding, never a skip. All five rules read the canonical contract in docs/AGENTS.md §5.B — the frontmatter keyset, the maturity ladder, the body shape, and the Shifts grammar (do NOT restate any of them here). The audit never edits the file. Humans own its content, and reviewed_at moves only after a human read.
- CHK-OBJ-1 the file exists; its frontmatter carries exactly the §5.B keyset;
maturityis in the §5.B enum;reviewed_atis an ISO date not in the future;review_every_daysis a positive integer → BROKEN on any miss. - CHK-OBJ-2 the body carries §5.B's three H2 headings, in §5.B's order, and no other H2 → BROKEN.
- CHK-OBJ-3 when
maturityis notplaceholder: the Mission holds no bracketed template text; at least one goal exists; every goal carries §5.B's four fields with in-enumkindandstatus; goal ids are contiguous from 1 and unique → BROKEN. Silent atplaceholder— an untouched template is thecleanup-campsiteCLN-OBJ-1nudge's concern, not this rule's. - CHK-OBJ-4 every Shifts row carries an ISO date and a
shiftedvalue that ismissionor an existingOBJ-N; everydroppedgoal has a Shifts row naming it → BROKEN. - CHK-OBJ-5
reviewed_atis older thanreview_every_days→ WARNING: the file is due for a human read. Report the age in days and the threshold.
An OBJ-N token in a review report, a brief, or an ADR is a reference to this file. Resolve it against the goals here; a dangling one → BROKEN.
Concern 5 — Promptbooks
docs/promptbooks/legacy/is EXCLUDED from every CHK-PB- walk.* It is the preserved-originals holding area populated by earlier migrations — a frozen archive of superseded pre-migration.mdsource files, not part of the live promptbook graph. Treat it likedocs/inbox//docs/AGENTS.md: present on disk, invisible to the concern walk. Do not glob it for CHK-PB-1 (book shape), CHK-PB-5/6 (run-dir walks — itsrun-*.mdare NOT orphan run dirs), CHK-PB-9/ABANDON/RADIUS/SCHEMA (immutable-history shape), CHK-PB-BIND (binding), or CHK-PB-11 (index rebuild — its books are NOT enumerated). Its only coverage is CHK-PB-LEGACY below.
- CHK-PB-1 Glob both
docs/promptbooks/active/PB-NNNN-*.yamlanddocs/promptbooks/{active,archive}/PB-NNNN-*.md(format coexistence). Route by (extension,format_version-present) — the two-key detection table:.yamlwith top-levelformat_version→ new-format. The JSON Schema (${CRUX_PLUGIN_ROOT}/schemas/promptbook.schema.json) is the SSOT for single-document shape (the same indirection CHK-ADR-1/CHK-PB-SCHEMA already use — reference the schema by name, don't restate it). Delegate the shape check: invoke${CRUX_PLUGIN_ROOT}/scripts/validate-promptbook.py --kind promptbook <path>. Same exit-code/JSON contract as CHK-CAT-3 (exit 0 = clean; exit 1 +{"errors":[…]}on stdout = invalid; non-zero + empty/unparseable stdout = crash, surface stderr). Non-zero exit → BROKEN, reporting the validator's JSONerrors(each carriesinstance_path/schema_path)..yamllackingformat_version→ BROKEN (a malformed new-format book; do NOT route to the legacy keyset check)..md→ legacy-markdown: keep the existing required-frontmatter-keyset check (the keyset stated here is canonical):id,title,status,created_at,total_prompts,current_run,current_prompt,forked_from,tags. Missing → BROKEN. (The new-format top-level keys are a superset of this keyset, so the schema enforces the same requirement on the.yamlside.)- Canonical valid example:
${CRUX_PLUGIN_ROOT}/scripts/tests/fixtures/promptbook-valid.yaml(round-trips clean through the validator).
- CHK-PB-2
idmatches filename prefix. Mismatch → BROKEN. - CHK-PB-3
total_promptsagreement, format-detected:- New-format
.yamlbook:total_prompts == len(prompts)(the structured array). Mismatch → DRIFT. Do NOT auto-fix by counting### Prompt Nheadings — a.yamlbook has none, so the heading-count source does not exist; counting it would auto-corrupttotal_promptsto 0. The safe auto-fix istotal_prompts := len(prompts). - Legacy
.mdbook (active):total_promptsmatches the count of### Prompt Nheadings in the body. Mismatch → DRIFT, report only. Missingtotal_prompts→ BROKEN under CHK-PB-1. The current distribution never rewrites a Markdown book, even to repair this counter; preserve its bytes and name the finding.
- New-format
- CHK-PB-4
current_prompt ≤ total_promptswhen non-null. Violation → BROKEN. - CHK-PB-5 If
current_runis non-null, the snapshotdocs/promptbooks/runs/<id>-<slug>/run-<current_run>.{yaml,md}exists (check BOTH extensions — a.yamlbook has a.yamlrun, a.mdbook a.mdrun; format symmetry). Neither present → BROKEN (dangling pointer). A non-nullcurrent_runwhose pointed-to run is TERMINAL (status: completedorstatus: abandoned) is EXPECTED — the pointer stays untilarchive-promptbooknulls it, so this is the normal delivered-but-unarchived state, NOT a dangling pointer. The BROKEN condition is unchanged: the pointed-to snapshot file does not exist. - CHK-PB-6 Every
docs/promptbooks/runs/<id>-<slug>/subdir has a parent book inactive/ORarchive/. Orphan run dir (no parent) → BROKEN (ask before deleting). - CHK-PB-7 Every run snapshot has the run-level keys
run_id,book_id,started_at,completed_at,status,current_prompt— for a.yamlrun these are top-level YAML keys (a.yamlrun also carriesformat_version+book_content_hash, covered by CHK-PB-SCHEMA/CHK-PB-BIND); for a.mdrun they are frontmatter.status∈ {in_progress, completed, abandoned}. Missing → BROKEN. - CHK-PB-8 For
status: completedruns:completed_atis non-null AND every prompt state is terminal per the state-enum notes indocs/AGENTS.md§11.B "Run-snapshot per-prompt shape" (the single source of truth — do NOT restate the enum here; read §11.B). Violation → BROKEN. - CHK-PB-9 Archived books (
docs/promptbooks/archive/) havestatus: archivedAND their FINAL run is archive-eligible by one of the two paths indocs/AGENTS.md§11.B: eitherstatus: completedwith every prompt terminal (done | skipped | blocked), orstatus: abandonedwithabandonment.kind: deliberate. Violation → BROKEN. (Eligibility is a run-level property; there is no per-prompt flag.) - CHK-PB-10
forked_from: PB-MMMMreferences an existing book (active or archive). Dangling → BROKEN. Note that nothing writes this field any more — it is an accepted, always-null vestige, and the mid-run fork it recorded is deleted (a plan change mid-run is an abandonment plus a successor book that cites its predecessor in prose). The check is retained for the historical corpus; a non-null value on a newly authored book is itself suspect. - CHK-PB-11
docs/promptbooks/index.mdexists with active table + recent-runs list + archive section. Stale counts / missing rows → DRIFT (rebuild from directory walk). One exemption: theprogresscell of an ACTIVE book whosecurrent_runis non-null — whether the pointed-to run isin_progressor already terminal. Advancing a prompt deliberately writes two surfaces and no third — the run snapshot and the book pointer, never this index (seedocs/AGENTS.md§6 under thepromptbookop). So theprogresscell lags its snapshot by design for the whole life of the run, and reporting that lag would emit a DRIFT finding on every audit run during every live run. The advance that COMPLETES a run writes those same two surfaces and no third, and the book'scurrent_runsurvives that completion. So the lag persists through the delivered-but-unarchived window too, exempt there for the same reason rather than a new one. A laggingprogresscell on any unarchived run is NOT a finding; the next boundary op (archive) rebuilds it. Every other cell, row, and count in the file is checked as stated. - CHK-NUM-1 No two promptbooks and no two ADRs share a number → BROKEN. Delegate it: run
uv run "${CRUX_PLUGIN_ROOT}/scripts/check-record-numbers.py" --repo-root .(exit 0 clean; exit 1 with JSONvalidation_errors, one per shared number, naming each file holding it; exit 2 crash, surface stderr). Three namespaces are checked apart: books inactive/andarchive/(any extension), run directories inruns/, and ADRs inadrs/andadrs/archive/. A book and its run directory carry one number and are one record.legacy/is excluded, as it is from every CHK-PB-* walk. The checker reports the records it scanned per namespace underchecked; a clean verdict that scanned none is not a pass. Never renumber or delete a file to clear the finding: numbers are never reused, so surface both paths and ask. - CHK-PB-12
manifest.yml'spromptbook.next_number> max existing PB number. Equal-or-less → BROKEN. - CHK-PB-ABANDON (replaces the retired CHK-PB-13, whose whole subject was the per-prompt archive-eligibility flag that
docs/AGENTS.md§11.B retired.) For an archived book whose final run hasstatus: abandoned: that run MUST carryabandonment.kind: deliberate. An archived book whose final run isabandonedwithkind: superseded, or with noabandonmentmapping at all, → BROKEN — it was archived on a signal that confers no eligibility (asupersededvalue marks a stale run that a later run's start rolled over). Adeliberateabandonment on a run underactive/is legitimate and unflagged: it means the book is eligible but not yet archived. - CHK-PB-RADIUS For an archived book with
cycle_kind: patch:blast_radiusis present and non-empty, every entry passes the declared-path grammar, and the book's final run carries a non-nullbase_commit. The grammar has one implementation —invalid_blast_radius_entryin${CRUX_PLUGIN_ROOT}/scripts/validate-promptbook.py, the same function the authoring validator and the archive check call, so all three agree by construction. Its rejections are not restated here; read the function. (Restating them produced a partial copy that read as complete and omitted one of them.) Violation → BROKEN. Audit does NOT re-run the git comparison. A historical diff is not reproducible from an archived tree — the base commit may be unreachable, and the working tree has moved on — so re-deriving it would produce a verdict the archive already settled. The mechanical containment check isarchive-promptbook's precondition (check-blast-radius.py), run once at archival against the live tree; this rule audits only that the declaration and its commit boundary are present and well-formed. Immutable-history demotion applies as for CHK-PB-SCHEMA. - CHK-PB-SCHEMA Run-snapshot per-prompt shape, format-detected. Route by (extension,
format_version-present), exactly as CHK-PB-1 does:- New-format
.yamlrun (format_versionpresent) → delegate to the run validator: invoke${CRUX_PLUGIN_ROOT}/scripts/validate-promptbook.py --kind run <path>(same engine, second schema${CRUX_PLUGIN_ROOT}/schemas/run.schema.json— the per-prompt-shape SSOT thatdocs/AGENTS.md§11.B references by name). Exit-code contract: exit 1 → finding(s) from the validator's JSONerrors; any other non-zero with empty stdout (e.g. the exit-2 YAML-capability error (PyYAML missing; seedocs/AGENTS.md§10.A)) = crash, surface stderr and NEVER report it as a document finding. The validator covers the per-prompt shape AND the contiguity (n == index+1) post-schema pass; the cross-field rules it cannot express stay in audit-docs (see §11.B-referencing rules + CHK-PB-BIND). A.yamlrun lackingformat_version→ BROKEN (malformed new-format run; do NOT route to the legacy regex path). Canonical valid example:${CRUX_PLUGIN_ROOT}/scripts/tests/fixtures/run-valid.yaml. - Legacy
.mdrun → keep today's regex-against-§11.B path. Validate per-prompt blocks against the canonical schema indocs/AGENTS.md§11.B (single source of truth — read §11.B for the field list +Stateenum; do NOT restate them here). Block scope: only blocks whose heading matches^## Prompt (\d+)are validated;## Notes/## Summary/## PR Draftand any nested###/####content are ignored, and field-looking lines inside nested subsections are NOT treated as per-prompt fields. Field parse: accept both the bulleted- **Field:**form and the bare**Field:**form. Findings: a §11.B-required field (State/Started/Completed/Result/Artifacts) missing from a block → DRIFT-surface (do NOT auto-edit a snapshot body);Statevalue ∉ the §11.B enum → BROKEN; an unknown**Field:**key → WARNING.blocked-confirmedis a RETIRED field (seedocs/AGENTS.md§11.B) and is IGNORED, not reported. A frozen.mdsnapshot may carry it; those bodies are immutable and cannot be cleanly retro-fixed, so flagging it as an unknown field would generate a finding nobody may act on. - Immutable-history demotion (applies to BOTH paths): for archived (
docs/promptbooks/archive/parent) ORstatus: completedsnapshots, demote every finding to WARNING (frozen history can't be cleanly retro-fixed) — this includes findings the run validator returns on a.yamlsnapshot.statuswins over path in both directions —status: completedunderactive/is demoted;status: in_progressunderarchive/keeps full severity. Full severity applies only to active/in-progress runs. CHK-PB-SCHEMA does NOT own duplicate-## Prompt Ndetection (that'scleanup-campsiteCLN-PB-4). A stdlib CI test (test_schema_invariants.py) guards the §11.B field-token extraction.
- New-format
- CHK-PB-BIND Run↔book binding integrity for new-format
.yamlruns only. For each.yamlrun snapshot (format_versionpresent,book_idresolvable to an active-or-archived.yamlbook), recompute the bound book's frozen-plan hash with the validator'scompute_book_hash(i.e."sha256:" + sha256(canonical_json(frozen_plan_subset(book)))— the canonical serialization of the book's plan-bearing fields only, excluding the mutable run-state fieldscurrent_run/current_prompt/status; reuse${CRUX_PLUGIN_ROOT}/scripts/validate-promptbook.py'scompute_book_hashso the bytes match the writer's) and compare to the run's storedbook_content_hash. Mismatch → DRIFT, NEVER auto-fixed — recomputing/overwriting the stored hash would erase the evidence that the run-freeze invariant broke. Remediation cites the §4 abandon rule indocs/AGENTS.md: the plan was edited in place instead of being changed the sanctioned way, which is to abandon the run and author a successor book that cites its predecessor in prose. Surface the mismatch (stored vs. recomputed) and recommend that path. Notes: (1) this is distinct fromCHK-SCHEMA-1(manifestschema_version == "5") — different rule, different concern. (2) An unresolvablebook_id(no active-or-archived book exists) is NOT CHK-PB-BIND — that is the existing CHK-PB-6 "run dir has a parent book" graph rule (a missing book, vs. CHK-PB-BIND's found-but-plan-hash-differs). (3) Legacy.mdruns have nobook_content_hashand are not subject to this rule. (4) Immutable-history note: a mismatch on an archived/completedrun still surfaces as evidence (it documents a past in-place edit) — it is never auto-fixed regardless of run status. - CHK-PB-CYCLE Cycle-coverage invariants for cycle-kind books — the machine-enforced replacement for
dev-cycle's formerly prose-only formula/invariant contract, covering all three cycle kinds —dev-cycle(adr),iterate(verify), andpatch-cycle(patch). Format two: aformat_version "2"book declares its kind (adr,implementation,verifyorpatch); the implementation kind has no ADR modules and follows4I+4D+3R+2, the architectural kind follows4(A+I)+4D+3R+2, and the validator refusescycle_grandfatheredandgrandfather_reasonon such a book. The paragraph below describes format one. Delegated, not restated: the invariants live invalidate-promptbook.py'scycle_coverage_pass, which runs inside the--kind promptbookdelegation CHK-PB-1 already performs — so for a new-format.yamlbook, CHK-PB-1's non-zero exit already surfaces any cycle-coverage finding (foradr/verify: the4N+4M+3K+2formula ⟷modules⟷module_tag-count agreement, the per-module prompt-count "ordinal contract",adr/verifymutual exclusion, the degenerate-cycle andcycle_kind↔shape cross-checks, and the ≥13 floor — all unchanged; forpatch: the constant count of 5, the fixedverify, plan, implement, review, summaryphase sequence, the absence ofmodule_tag/modules, and a non-empty repo-relativeblast_radius). Thepatchtier is a third branch, not a relaxation of the other two — seedocs/AGENTS.md§11.C. This rule exists to make that coverage explicit and to pin the two scope rules the validator encodes: (a) grandfathered books are skipped — a book withcycle_grandfathered: true(+grandfather_reason) is exempt from the pass (it remains schema-validated); grandfather only a book with no run in flight, or abandon the run first.cycle_grandfatheredandcycle_kindare bound at run start: adding or changing either while a run is in flight makesadvance-run.pyrefuse every--outcomeof that run and write nothing, so it is never a silent migration. A book grandfathered before its run starts has every promptunclassified, so none of its gates is checked.[^correct] That refusal holds when the run-start book can be read. When it cannot,advance-run.pyignores both fields and module-tagged gate prompts stay gates. (b) legacy.mdcycle books are NOT cycle-coverage-checked — the pass is.yaml-only (it runs only on the--kind promptbookpath); a legacy.mdcycle book keeps the CHK-PB-1 legacy-keyset path and is out of scope (it predates the structuredmodules/module_tagform). Immutable-history demotion (consistent with CHK-PB-SCHEMA): a cycle-coverage finding on an archived (docs/promptbooks/archive/parent) orstatus: completedbook demotes to WARNING (statuswins over path in both directions); full severity (BROKEN, via CHK-PB-1's exit) applies only to active/in-progress cycle books. No separate test fixture is needed here — the invariants are covered bytest_validate_promptbook.py's cycle-coverage cases (theCycleCoveragePassTestsclass); this rule is the audit-side pointer to that engine. - CHK-PB-LEGACY Preservation integrity for the migration holding area. When
docs/promptbooks/legacy/exists: every preserved original under it SHOULD correspond to a live migrated.yaml— i.e. forlegacy/archive/<id>-<slug>.mdthere isdocs/promptbooks/archive/<id>-<slug>.yaml, and forlegacy/runs/<id>-<slug>/run-<RUN-NNN>.mdthere is adocs/promptbooks/runs/<id>-<slug>/run-RUN-NNN.yaml. A preserved original with no corresponding live.yaml→ WARNING (a half-migration; the live.yamlwas reverted or never written — surface, do not auto-fix). The converse (a live.yamlwhose.mdoriginal is missing fromlegacy/) is also WARNING. This is the ONLY rule that reads underlegacy/; it never validates the preserved.mdagainst any schema (they are frozen pre-migration artifacts).
Concern 6 — Journal
- CHK-JR-1 Every entry in
docs/journal/YYYY-MM.mdfiles has a heading matching## \[\d{4}-\d{2}-\d{2} \d{2}:\d{2}\] (decision|implementation|bug|learning|blocker|refactor|meeting|review|misc|release) \|. Malformed → WARNING (surface; never auto-edit). - CHK-JR-2 Entry dates inside a
YYYY-MM.mdfall within that month. Outside-of-month → WARNING (likely a file-naming mistake; ask). - CHK-JR-3
docs/journal/index.mdexists with one row per month file (newest first) listing entry count and the top three category names. Invokegenerate-journal-index.py --dry-runand report its verdict — exit 0 with no drift payload is clean; exit 1 with a drift payload is DRIFT (recommendgenerate-journal-index.py, do not rebuild by hand); a non-emptyvalidation_errorspayload is BROKEN. - CHK-JR-4 Every wiki-link in any journal entry (
adrs/ADR-NNNN,promptbooks/...,research/...targets) resolves. Promptbook book-links resolve lifecycle-agnostically per the resolver defined indocs/AGENTS.md§11: thePB-NNNNid (§14.3 dual-form regex) is the sole authoritative match key — the slug AND theactive/|archive/path segment are non-authoritative hints — so[[promptbooks/(active|archive)/PB-NNNN-<slug>]],[[promptbooks/PB-NNNN-<slug>]], and[[promptbooks/PB-NNNN]]all resolve iff a book with that id exists underdocs/promptbooks/active/ORarchive/(legacy/excluded). Run-links (promptbooks/runs/<book>/run-RUN-NNN) keep exact-path resolution (runs/never moves). Dangling → WARNING (journal references are historical; user decides whether to update or leave). - CHK-JR-5 Entries are reverse-chronological within each
YYYY-MM.mdfile. Out-of-order → WARNING.
Concern 7 — Catalog
- CHK-CAT-1 Catalog inventory, in two limbs. An inventory alone is strictly weaker than the rule it replaces — a check that walks whatever is present cannot notice that something expected is absent — so the required-file floor rides with it.
- Limb (a) — inventory. Every entry in
${CRUX_PLUGIN_ROOT}/catalog/parses, by extension:json.loadfor.json, the shared minimal-YAML loader's strict catalog path for.yml. Malformed → BROKEN (recommend re-installing the plugin via the marketplace flow; do not auto-regenerate from inside the audit). - Limb (b) — floor. Every required catalog file exists. Absent → BROKEN. The floor is derived, not a third hand-maintained list, and both enumerations ship inside the plugin: the
.jsonfiles are named byvalidate-catalog.py's module-levelREQUIRED_CATALOG_JSONconstant, and the.ymlfiles by itsCATALOG_TARGETSconstant. Both exist for other reasons and are separately gated, so adding a fifth catalog file costs no edit here — it costs the validator target or roster entry it was always going to need. Both sources must travel with the plugin. An earlier version of this rule derived the.jsonhalf from the crux source repo's own regenerative-outputs roster — then in the repo-rootCLAUDE.md, now in the repo-rootAGENTS.md— which is that repo's roster and not the installed tree's, whatever the file is called: downstream the list resolved EMPTY and the floor silently checked nothing. A rule whose input is absent must not degrade to a pass — if neither constant can be read, report BROKEN rather than an empty floor. - Disposition of every other entry.
${CRUX_PLUGIN_ROOT}/catalog/holds regular files with suffix.jsonor.yml, and nothing else. A directory, a symlink, an extensionless file, or any other suffix is BROKEN under limb (a) — reported as a misfiled entry, never parsed and never followed. - Parser-safety mitigations. This rule points a parser at a directory listing rather than at named files, so the widening is bounded explicitly. Trust boundary first:
catalog/is a repo-controlled directory whose every change arrives through code review; it is not an upload target and takes no runtime input, so the bounds below are defense-in-depth against a hostile pull request and against accident, not a perimeter around untrusted data.- No unsafe construction. YAML is read only through the shared loader, whose real-parser path is pinned to safe loading. Arbitrary-object construction is out of contract on both parse paths, and neither path may be swapped for a loader that permits it.
- Forbidden constructs are refused, not merely unused. Safe loading means no arbitrary object construction; it does not mean no expansion, and a real parser expands an anchor happily. So the loader rejects five constructs before accepting a document: a leading
&anchor, a*aliasreference, a<<:merge key, an explicit!tagor%TAGdirective, and a second document in one file. That is what puts quadratic expansion out of reach — a grammar the loader enforces, not a convention the authors observe. The list is six, not five: a flow collection ({...}/[...]) is refused at the start of any key or value token as well. It was originally left out on the theory that it "fails loudly on the fallback path" — it does not.a: {b: &x 1, c: *x}was accepted by both paths, and the two then disagreed silently: the real parser expanded the alias, the fallback kept the literal string. So the flow form was simultaneously an expansion bypass around the other five refusals and a two-path divergence. The two EMPTY forms{}and[]remain legal, because the hazard is a flow collection's contents and an empty one has none — and block YAML has no other spelling for an empty list. - Regular files only; symlinks refused. The walk is non-recursive and tests
is_symlink()beforeis_file(). A symlinked entry is BROKEN and is never followed, so the rule cannot be turned into an arbitrary-file read by adding a link to the directory. - Size caps before read — two of them, at two different scopes. This rule's own ceiling is 1 MiB per entry, and it covers EVERY entry in
catalog/, the.jsonfiles included: an entry over 1 MiB is BROKEN atstat, without being parsed. The shared YAML loader enforces a second, tighter ceiling of 64 KiB (CATALOG_MAX_BYTESin${CRUX_PLUGIN_ROOT}/scripts/_yaml_min.py), checked before the construct scan and before any parse — but only on the.ymlread path, because the.jsonfiles never reach that loader. The two are not a contradiction and neither is redundant: 64 KiB is the binding limit for a hand-authored.yml, and 1 MiB is what stops a 200 MiBskills.jsonfrom being handed tojson.load. Today's largest entry isskills.jsonat roughly 44 KiB and the largest.ymlismodels.ymlat roughly 6 KiB, so both caps sit well clear of live growth. Both bound the source bytes only; neither bounds an expanded object graph, which is why the construct refusal above — not either cap — answers expansion attacks.
- Limb (a) — inventory. Every entry in
- CHK-CAT-2 Every skill listed in
${CRUX_PLUGIN_ROOT}/plugin.jsonskills[]has a corresponding entry incatalog/skills.json(matched by directory-nameid), and vice versa. Orphans in either direction → BROKEN. - CHK-CAT-3 Drift detection: invoke
${CRUX_PLUGIN_ROOT}/scripts/validate-catalog.py --dry-runfrom the repo root. Parse stdout as JSON regardless of exit code (same exit-code semantics asverify-code-docsand CHK-CODE-4: exit 0 + JSON = clean, exit 1 + JSON = drift, non-zero + empty/unparseable stdout = crash). A"surface_absent": truepayload is N/A, never clean — the catalog is the plugin's OWN derived output, so a run outside the plugin's authoring checkout validated the plugin against itself and established nothing about this project. Report it N/A with the payload'sreason, and recommend no regenerator: there is no output here for one to write. Exit 1 with non-emptyadded/changed/removed→ DRIFT (surface counts; recommend runningvalidate-catalog.pywithout--dry-runto regenerate). Validation errors (non-emptyvalidation_errors) → BROKEN. Read thewarningskey too: it is a separate top-level list of findings that deliberately do NOT affect the exit code (themodels.ymlverified:staleness clock is the current member, kept non-failing so a passing tree cannot turn red on the passage of time alone). Non-emptywarnings→ WARNING, surfaced with its findings; a run with exit 0 and non-emptywarningsis a pass worth reporting, not a clean run. DO NOT auto-run a real regeneration during the audit —validate-catalog.pyis destructive enough (it overwritesskills.json) to warrant explicit user invocation. - CHK-CAT-4 Every entry in
${CRUX_PLUGIN_ROOT}/catalog/bundles.yml'sskills:list resolves to an existingidincatalog/skills.json. Dangling skill references → BROKEN. - CHK-CAT-5 Total skill count under
${CRUX_PLUGIN_ROOT}/skills/*/SKILL.mdequals the length ofcatalog/skills.json. Mismatch → DRIFT (recommendvalidate-catalog.pyto reconcile). - CHK-CAT-6 Reverse bundle membership. For every entry in
catalog/skills.json, each value in itsbundles[]array names a bundleidpresent incatalog/bundles.yml, AND that bundle'sskills[]contains the skill'sid. Dangling bundle id or missing membership → BROKEN. This is the mirror of CHK-CAT-4: every skill declares its bundle membership twice, once inmetadata.bundlesand once in the bundle's list, and CHK-CAT-4 checks only the bundle→skill direction. Scoped to skills: all ten agents incatalog/agents.jsondeclarebundles: ["crux-agents"]and nocrux-agentsbundle object exists, so extending the reverse check to agents would need either a new bundle object or anagents[]key in the bundle schema — a schema change no decision has made.
Concern 8 — Arch (derived — drift + auto-regenerate)
Runs only when arch ∈ manifest.yml's concerns_enabled (which requires schema_version == "5"); otherwise silent. The arch tree is the derived architecture spine (per docs/AGENTS.md §4 "arch"): four spine files (data-model.md, api-surface.md, module-graph.md, decision-index.md) plus a synthesized overview.md, an index.md, and _meta/manifest.json, all regenerated wholesale by derive-arch.py. Unlike CHK-CODE-4 and CHK-CAT-3 — which flag drift and recommend the regenerator — CHK-ARCH-1 auto-regenerates in place. The divergence is deliberate: arch's every input (JSON Schemas, ADR frontmatter, the skill catalog, crux package imports) is already committed in the tree, so a regenerate cannot capture in-flight uncommitted source the way a code-doc extraction can; the output is deterministic and byte-stable; and hand-edits under arch/ are defined as disposable. This makes an arch regenerate a DRIFT-tier auto-fix, not a destructive act.
-
CHK-ARCH-1 Drift detection + auto-regenerate. Invoke
${CRUX_PLUGIN_ROOT}/scripts/derive-arch.py --dry-run --docs-dir <docs_dir>from the repo root (<docs_dir>is the CHK-CFG-1 resolved tree). Parse stdout as JSON regardless of exit code (sibling exit-code semantics of CHK-CODE-4 / CHK-CAT-3). Exit 1 means findings, and the payload names which of TWO channels found them —driftandstrict_failuresare independent, a run may carry both, and they take different remedies.cleananswers the drift question alone, so{"clean": true, "drift": []}at exit 1 is a legitimate shape and not a contradiction.- exit 0 +
{"clean": true, "drift": [], "strict_failures": []}= clean, no finding. - exit 1 with
driftnon-empty = drift (cleanisfalse). Auto-regenerate — run${CRUX_PLUGIN_ROOT}/scripts/derive-arch.py --docs-dir <docs_dir>(no--dry-run,{"written": [...]}) to rewrite the spine +overview.md+_meta/manifest.json, then report DRIFT (auto-fixed) listing the drifted paths from the dry-rundriftarray. Re-run--dry-runonce to confirm. Convergence is judged on thedriftarray, never on the exit code — a tree with a livearch.requirestill exits 1 through the other channel after a successful regenerate. A still-non-emptydrift→ BROKEN (the regenerator did not converge — surface the residualdrift+ any stderr, do not loop). - exit 1 with
strict_failuresnon-empty = a requirement finding, NOT drift, and NOT a failed regeneration. Each entry names a concern that<docs_dir>/manifest.yml'sarch.requiredeclares this tree needs and whose recorded verdict is notpopulated, with itsstub_reason,expectedandfound(the strict gate, perdocs/AGENTS.md§4 "arch"). → BROKEN, reported as<concern> is required by <required_by> and its recorded verdict is <verdict>. Do NOT auto-regenerate for this channel and never prescribe one: the committed tree already is what a regeneration produces, so re-deriving writes an identical tree and clears nothing. The two remedies are to establish the precondition the verdict names in the repository, or to amendarch.require. Both are user decisions — recommend, never apply. - exit 2, or any non-zero with empty/unparseable stdout, or exit 1 reporting findings in NEITHER channel = no verdict — surface stderr and NEVER report it as a document finding. Two lanes share exit 2, and stderr says which. A crash is an environment/extractor capability error. A deliberate refusal (
StaleProjectionInputon stderr) means a spine file that projects a gated artifact declined because that artifact is not what its own regenerator produces; nothing was written. On the refusal lane, do NOT auto-regenerate arch — regenerating the spine cannot fix a stale ADR index or catalog, and a re-derive reads the same stale input and refuses again. Report the capability failure, name the input from stderr, and recommend that input's own regenerator (generate-adr-index.py,validate-catalog.py) followed by a re-derive.
Do NOT auto-regenerate under
--migrate— a migration owns its own step ordering; the arch auto-fix belongs to a plain audit / explicit "audit docs". - exit 0 +
-
CHK-ARCH-2 Enablement recognition. When
arch∈concerns_enabled, the tree at<docs_dir>/arch/is present with the four spine files +overview.md+index.md+_meta/manifest.json; a missing tree or file is drift that CHK-ARCH-1's regenerate produces (derive-arch.pywrites all of them) — route it through CHK-ARCH-1, do not raise a separate BROKEN. When<docs_dir>/arch/exists butarchis NOT inconcerns_enabled→ WARNING (a stale derived tree from a disabled concern; recommend re-enabling the concern or removing the tree — never auto-delete). Arch carries no timestamps and gets no master-index section (see CHK-MI-1); its catalog is<docs_dir>/arch/index.md+ the spine hash.
Concern 9 — Regenerated-output drift and doctrine reconciliation
The repo-root AGENTS.md "regenerative outputs" table is the enrollment roster: every derived artifact owes a vendored regenerator and a --dry-run drift gate. Concerns 2, 7, 8, and 9 already run four of those gates individually — CHK-CODE-4 (uv run --no-config extract-code-docs.py --dry-run), CHK-CAT-3 (validate-catalog.py --dry-run, covering both skills.json and agents.json), CHK-ARCH-1 (derive-arch.py --dry-run), and CHK-ROUTE-1 (generate-routing-table.py --dry-run). CHK-DRIFT-1 covers the roster's remaining sixteen outputs. The split is explicit so no gate runs twice.
- CHK-ROUTE-1 §10 routing-table drift (recommend-only, same form as CHK-CAT-3). Invoke
${CRUX_PLUGIN_ROOT}/scripts/generate-routing-table.py --dry-runfrom the repo root. Parse stdout as JSON regardless of exit code (the shared CHK-CODE-4 / CHK-CAT-3 semantics): exit 0 +{"drift": false}= clean; exit 0 with"surface_absent": true= N/A, never clean — the routing table projects the plugin's own skill catalog into a marked region, and a tree carrying neither owns nothing that could have drifted; report the payload'sreasonand recommend no regenerator. Exit 1 +{"drift": true, "paths": [...]}→ DRIFT (surface the drifted target and recommend runninggenerate-routing-table.pyto regenerate; do NOT run it); exit 1 +{"error": ...}(a missing/duplicated/misordered marker or an unreadableskills.json) → BROKEN; non-zero + empty/unparseable stdout → surface stderr, never a document finding. The payload'sno_trigger_skillsarray is informational — skills whosedescriptioncarries no quoted trigger phrase before its first period; report it as a WARNING when non-empty so a routing gap is visible, never as drift. - CHK-DRIFT-1 Regenerated-output drift for the sixteen roster outputs the four individual gates do not cover. Invoke the
check-driftskill (its whole-tree contract runs every enrolled gate; inside the audit, skip the four already run —validate-catalog.py,extract-code-docs.py,derive-arch.py,generate-routing-table.py— so none runs twice). The sixteen CHK-DRIFT-1 covers:agents.json(already checked by the SAME CHK-CAT-3validate-catalog.py --dry-runrun — reported here, NOT re-invoked), the summaries projection (summarize-adrs.py --dry-run), the doctrine projection (compile-doctrine.py --dry-run),opencode/agents/(generate-opencode-agents.py --dry-run),adrs/lineage.md(generate-lineage.py --dry-run),adrs/index.md(generate-adr-index.py --dry-run), thedocs/index.md## ADRsrollup (generate-index-rollup.py --dry-run), theREADME.mdversion footer (generate-readme-footer.py --dry-run), the writing-rules block (generate-writing-rules.py --dry-run), the runtime-compatibility block across 52 skills (generate-runtime-compat.py --dry-run), the reviews index (generate-reviews-index.py --dry-run, whose"surface_absent": truepayload is verdict N/A and never a clean pass — a tree that has run no decision review has no derived index to drift), the journal index (generate-journal-index.py --dry-run, whose"surface_absent": truepayload is likewise N/A, the same treatment the reviews index gets), the operations-log summary (generate-log-summary.py --dry-run, whose"surface_absent": truepayload on a tree with nolog/is N/A, and whosepending_monthsbeside exit 0 is a clean verdict that namescleanup-campsiteas the remedy), the shipped-rules catalog (generate-rules-catalog.py --dry-run), the crux-mods reach tables (generate-mods-reach-tables.py --dry-run), and the micro-crux guide (generate-micro-crux.py --dry-run). The last three are plugin-authoring gates: outside the plugin's own checkout each reports"surface_absent": true, which is N/A, never a clean pass. Parse each stdout as JSON regardless of exit code (the shared CHK-CODE-4 / CHK-CAT-3 semantics): exit 1 + a drift payload → DRIFT (surface the drifted paths and recommend the named regenerator; do NOT run it); a non-emptyvalidation_errorspayload → BROKEN (the named input must be repaired — regenerating cannot fix a validation error); non-zero + empty/unparseable stdout → surface stderr, never a document finding. A top-levelwarningskey (e.g.validate-catalog.py'smodels.ymlstaleness clock) → WARNING beside the verdict, exit unchanged. Recommend-only, never auto-regenerate: unlike CHK-ARCH-1 (which auto-regenerates the arch spine in place), CHK-DRIFT-1 recommends the regenerator and stops — the arch spine is the ONE derived artifact this audit rewrites. One roster gate sharesderive-arch's two-lane exit 2 only for arch itself; the CHK-DRIFT-1 gates each return the plain 0/1/crash contract. - CHK-DOCTRINE-1 Doctrine reconciliation backlog. Runs only when
<docs_dir>/adrs/doctrine/exists. Count the pending reconciliation pairings — either by reading<docs_dir>/adrs/doctrine/index.mdfor domains whose heading ends— BROKENand, under their_Reconciliation against ratified invariants:_table, rows whose status isun-adjudicated,digest-stale, orcollision; or by running the consistency gate${CRUX_PLUGIN_ROOT}/scripts/check-doctrine-reconciliation.py(exit 1 +broken_domainsnames them; exit 0 = none pending; itswarningskey names any ratified invariant seeding no pairing). Non-zero pending → WARNING:N doctrine pairing(s) awaiting reconciliation — run reconcile-signoff. Surface the S1warningsas WARNING too. NEVER auto-sign a reconciliation from the audit —reconcile-signoffis a human gate that reads the two texts and takes the verdict from the user; the audit only reports the backlog.
Total: ~97 checks.
3. Walk prompt (when spawning Explore agent)
When docs/ has 100+ markdown files, spawn an Explore agent with this prompt verbatim. The agent returns a findings report; the main session categorizes and applies fixes.
MAINTENANCE — two copies of the check list, keep in sync. The numbered items below are a verbatim restatement of the §2
CHK-*checks, reworded for an Explore agent that cannot apply fixes. They duplicate §2 by design (the inline walker uses §2; the spawned walker uses this prompt). When adding, removing, or renumbering a check in §2, make the matching edit here in the same change — a check that exists in only one of the two paths is silently skipped on the other walk strategy. Each item below carries its(CHK-…)id precisely so this correspondence is mechanical to verify.
Walk the entire
docs/tree at the current working directory. The layout is described indocs/AGENTS.md(read it first). For each of the following eleven concern groups, list specific violations (file path + one-line description). Do not propose fixes — just report findings.Before walking, prune retained holdings: list the holdings once with
uv run "${CRUX_PLUGIN_ROOT}/scripts/authority-view.py" retained-roots --repo-root <repo-root>and skip each listed root during recursive walks; test one path withuv run "${CRUX_PLUGIN_ROOT}/scripts/authority-view.py" retained --repo-root <repo-root> <path>(exit 0,retainedtrue or false). Prune before nested configuration discovery, token matching, record parsing, split-tree detection, census or allocation counts. Never read held manifests or import held code. A layout refusal stops the walk. The holding contract isdocs/AGENTS.md§3.Concern 0 — per-repo configuration (the repo-root
.cruxfile, perdocs/AGENTS.md§14; do this FIRST): 0a. (CHK-CFG-1) Runpython3 "${CRUX_PLUGIN_ROOT}/scripts/bionic-config.py"from the repo root (the retainedcrux-config.pydelegates to it; either works). It resolves the precedence.bionic.yml> legacy.crux> content-validated bare-directory discovery > default (perdocs/AGENTS.md§14), reportingsource(".bionic.yml" | ".crux" | "discovery:<dir>", with combined forms for a keyless config). Exit 1 → report the JSONerrormessage verbatim. Exit 0 → note the resolveddocs_dirandartifact_prefixand use thatdocs_diras the docs root for every following item. A.bionic.ymlcoexisting with a legacy.cruxis expected during migration (not a finding). Do not read the config YAML directly. 0b. (CHK-CFG-2) Scan artifact filenames/ids with([A-Z][A-Z0-9]{1,9}-)?(PB|ADR)-(\d{4})and list the distinct prefix spellings in use (bare counts as one). Report when more than one exists, or when the dominant prefix differs from the resolvedartifact_prefix. 0c. (CHK-CFG-3) List any directory other than the configureddocs_dirthat looks like a crux docs tree (contains amanifest.ymlwith a readableschema_version) — including a stray default./docs/when.cruxrelocates the tree. 0d. (CHK-CFG-4) Group the dual-form scan's matches by (type token, 4-digit number); list any(type, NNNN)pair that appears under more than one spelling (bare and prefixed, or two different prefixes).Concern 1 — master index and log:
- List concerns in
manifest.yml'sconcerns_enabledthat have no section indocs/index.md, and vice versa.- For each concern section in
docs/index.md, compare its declared count against the actual file count for that concern. List mismatches.- Check that
docs/index.mdhas a_Last updated: YYYY-MM-DD_line near the top.- Run
uv run "${CRUX_PLUGIN_ROOT}/scripts/operation-log.py" check --repo-root <repo-root>and report each CHK-LOG-1 to CHK-LOG-7 finding from its JSON with its severity. The checks read the historical-reader op-enum regex fromdocs/AGENTS.md§6 (single source of truth — read §6 for the exact pattern; it accepts bothcleanup-campsiteand the legacycleanupfor frozen history), across every detail file underdocs/log/, a legacydocs/log.md, staged files and strays. List malformed entries, out-of-enum ops, a missinginitentry, unsplit or stray log files, undefined files underdocs/log/, and summary-gate failures or pending months.- Do not order heading dates within a detail file: entries sit in write order, so date order is no finding.
Concern 1.A — schema version and inbox (read
docs/AGENTS.md§7 + §11 "inbox is staging"): 5a. (CHK-SCHEMA-1) Readmanifest.yml'sschema_versionwith a real YAML parse. Report whether it equals"5". If it is"4","3", or"2", name the pinnedv3.23.2recovery route. Otherwise report incompatible tree schema without promising conversion. 5b. (CHK-INBOX-1) Only whenschema_version == "5": confirmdocs/inbox/exists. List it as missing if absent. 5c. (CHK-INBOX-2) Only whenschema_version == "5": confirmdocs/research/new/is ABSENT. List it if present (do not delete it). 5d. (CHK-INBOX-3) Only whenschema_version == "5": count non-.gitkeepentries indocs/inbox/excluding the_dispatched/subtree. Report the count (a partially-drainedurls.mdcounts). Do NOT treatdocs/inbox/as a concern — it gets nodocs/index.mdsection; exclude it from the per-concern walk likeAGENTS.md/README.md.Concern 1.B — invariants (only when
schema_version == "5"ANDinvariantsinconcerns_enabled; seedocs/AGENTS.md§15): 5e. (CHK-INV-BIJECTION) Every ledger page under<docs_dir>/invariants/has a parseable uniqueid; every reconciliation entry names a pin with a ledger page. List pinless pages, duplicate ids, and reconciliation entries with no ledger page. 5f. (CHK-INV-ORPHAN-CHECK) Every check in<docs_dir>/invariants/checks/resolves via the reconciliation to exactly one existing pin. List orphan checks (no/missing pin, orcheck_idabsent from the suite). 5g. (CHK-INV-DECORATION) Listratifiedpins with no resolvable check OR aggregatelast_result: none(BROKEN). Do NOT flagobservedpins with zero checks. 5h. (CHK-INV-FAILING) Listratifiedpins whose aggregatelast_resultisfail(BROKEN) orstale(WARNING). Aggregate perdocs/AGENTS.md§15.4 (fail>stale>pass>none). 5i. (CHK-INV-DANGEROUS) Listobservedpins with aggregatelast_result: pass(WARNING). Report survey-debt: the count ofobservedpins (not a percentage).Concern 1.C — observations (only when
observationsinconcerns_enabled; seedocs/AGENTS.md§17): 5j. (CHK-OBS-BIJECTION) Every record under<docs_dir>/observations/has a parseable uniqueidmatching its filename; whenindex.mdexists, every index row names a record with a file AND every record'sidappears in a row. List parse failures, duplicate ids, filename mismatches, index rows with no file, and records with no row. 5ja. (CHK-OBS-ANCHOR) Every record'sanchor_idis 16 lowercase hex digits, and no two records inobservedorratifiedshare one. List absent or malformed values and every anchor claimed by more than one live record. 5k. (CHK-OBS-EVIDENCE) Everyevidenceentry matches thepath:line-rangegrammar; aratifiedrecord's paths all resolve to a file inside the repository root, symlinks followed. List unparseable entries, unresolvable or escaping paths, and emptyevidencelists. 5l. (CHK-OBS-DECIDED) Adecidedrecord'sdecided_bynames an existing ADR;decided_byis non-null iffstatusisdecided. List violations. 5m. (CHK-OBS-STALE) Listobservedrecords whoseobserved_dateis older thanobservation.stale_daysinmanifest.yml(absent falls back to 90) (WARNING). Report survey-debt: the count ofobservedrecords (not a percentage). 5n. (CHK-OBS-SURVEY-STUB) List receipts under<docs_dir>/observations/_surveys/recording no completion: WARNING insideobservation.survey_stub_daysinmanifest.yml(absent falls back to 1), BROKEN past that window. 5o. (CHK-OBS-SURVEY-VISIBLE) List records visible under<docs_dir>/observations/whose receipt records no completion (BROKEN at any age). 5p. (CHK-OBS-SURVEY-DIGEST) List receipts whose recomputed digest no longer matches the sheet archived beside them (BROKEN). 5q. (CHK-OBS-SURVEY-RECORD) Listratifiedrecords whoseanchor_idno receipt covers AND behind which noobservationlog op stands (BROKEN).Concern 2 — code: 6. If
docs/code/exists, confirmdocs/code/_meta/manifest.jsonexists and is valid JSON. 7. For every row in_meta/manifest.json, confirm thedoc_pathfile exists. List missing files. 8. For every.mdfile underdocs/code/(excludingindex.mdand_meta/), confirm it's listed in the manifest. List orphans. 9. Confirmdocs/code/index.mdexists. (Do not run any extractor — that's destructive and outside the audit's scope.)Concern 3 — research: 10. Every
docs/research/sources/<slug>.mdhas required frontmatter (title, slug, type=source, source_url, source_date, author, captured_at, last_source_check, raw_path, previous_captures, static, tags). List pages with missing keys. 11. Every source page'sslugmatches its filename. List mismatches. 12. Every source page'sraw_pathand every entry inprevious_capturesresolves to an existing directory underdocs/research/raw/. List broken paths. 13. Every directorydocs/research/raw/<YYYY-MM-DD>/<slug>/is referenced by exactly one source page. List orphan and shared raws. 14. Every synthesis page underdocs/research/<category>/has required frontmatter (title, slug, type matching dir, tags, sources, last_reviewed). List pages with missing keys. 15. Every slug in any synthesissources:list exists indocs/research/sources/. List dangling slugs. 16. Confirmdocs/research/sources.mdexists with the 9 documented columns. Parse the table; for each row, list any column that disagrees with the corresponding source page's frontmatter. List orphan rows (slug has no source page) and missing rows (source page has no row). 17. Confirmdocs/research/updates.mdexists; list malformed##headings. 18. Every[[research/sources/<slug>]]and[[research/<category>/<slug>]]wiki-link acrossdocs/resolves. List dangling. 19. Count[contradiction],[unresolved],[source updated],[refresh failed]markers and## Capture gapssections.Concern 4 — ADRs and briefs: 20. Every
docs/adrs/ADR-NNNN-*.mdhas the required frontmatter keyset defined canonically indocs/AGENTS.md§11.A (single source of truth — read §11.A for the field list;amends:is optional). List pages missing any §11.A-required key. 20a. (CHK-ADR-1a) Compare${CRUX_PLUGIN_ROOT}/templates/ADR-template.md's frontmatter keyset against the backticked col-1 tokens indocs/AGENTS.md§11.A. WARN on any divergence (template and schema drifted). 21. Every ADR'sidmatches its filename prefix. List mismatches. 22. ADR numbering is contiguous from 0000. List gaps. List duplicates through CHK-NUM-1 (item 40e), which reads the same filenames. 23. State-machine consistency: for each ADR, check thataccepted_date/deprecated_date/superseded_dateare non-null iff status implies them. List violations. 24. Supersession bidirectionality: for everysuperseded_by: ADR-X, confirmADR-X.supersedescontains this ADR; and for every entry in anysupersedes, confirmsuperseded_bypoints back. List one-sided links. Separately, for every ADR with a top-levelamends:list, confirm each entry resolves to an existingdocs/adrs/ADR-*.md. List dangling. Theamends:relationship is one-way — do NOT report missingamended_by:back-refs on the amended ADRs. 25.manifest.yml'sadr.next_numbermust be strictly greater than the max existing ADR number. Report the values. 26. Everyrelated_briefs:entry resolves to an existingdocs/briefs/BRIEF-<slug>.md. List dangling. 27. Everyrelated_research:entry resolves underdocs/research/: a bare^[a-z0-9-]+$slug →sources/<slug>.md; a^[a-z0-9-]+/[a-z0-9-]+$path →docs/research/<category>/<slug>.md(orsources/<slug>). Reject any../leading-//~/multi-slash entry as malformed (containment). List dangling + malformed. 28. For every brief in any ADR'srelated_briefs:, confirm the brief's ownrelated_adrs:lists the ADR back. List missing back-refs. 29. List ADRs that reference a brief withstatus: draft. 30. Confirmdocs/adrs/index.mdexists with one row per ADR. List orphan rows and missing rows. 30a. (CHK-ADR-SPEC) Readdocs/manifest.ymladr.spec_rule_from. Absent/null/unparsable → report "body content rule not adopted in this tree" and DO NOTHING ELSE for this item. Otherwise, for every ADR numbered ≥ that value in either tier: measure the body span from## Contextthrough the last non-blank line before## Referencesand compare it againstdocs/AGENTS.md§11.D's stated budget, and scan the same span for recipe-shaped content (fenced block, call signature ordef/class, flagged command,| field | type |shape table). WARN only — never a repair, never a proposed body edit; the body is frozen. An over-budget body carrying §11.D's justification blockquote under## Context, and an ADR that is itself a shape's source of truth, are both NOT findings. Report the measured span beside the budget, and state that the recipe scan is a heuristic that both over- and under-reports.Concern 4.A — objectives (per
docs/AGENTS.md§5.B; noconcerns_enabledentry gates these — run them on everyschema_version == "5"tree): 4Aa. (CHK-OBJ-1) Confirm<docs_dir>/objectives.mdexists and its frontmatter carries exactly the §5.B keyset, withmaturityin the §5.B enum,reviewed_atan ISO date not in the future, andreview_every_daysa positive integer. Read §5.B for the keyset and the enum; do not restate either. A missing file is this item's own finding, never a skip. List every miss. 4Ab. (CHK-OBJ-2) Confirm the body carries §5.B's three H2 headings, in §5.B's order, and no other H2. List violations. 4Ac. (CHK-OBJ-3) Only whenmaturityis notplaceholder: list bracketed template text left in the Mission, an empty goal list, any goal missing one of §5.B's four fields or carrying an out-of-enumkindorstatus, and goal ids that are not contiguous from 1 and unique. Atplaceholderreport nothing for this item. 4Ad. (CHK-OBJ-4) List Shifts rows whose date is not an ISO date or whoseshiftedvalue is neithermissionnor an existingOBJ-N, and every goal withstatus: droppedthat no Shifts row names. 4Ae. (CHK-OBJ-5) Report areviewed_atolder thanreview_every_daysas a WARNING, naming the age in days and the threshold. Do NOT edit the file —reviewed_atmoves only after a human read. 4Af. Find everyOBJ-Ntoken in the review reports, briefs, and ADRs underdocs/. Resolve each against the goals in<docs_dir>/objectives.md. List every dangling token as BROKEN.Concern 5 — promptbooks (format coexistence — glob both
.yamland.md; route by extension +format_version): 31. (CHK-PB-1) Glob bothdocs/promptbooks/active/PB-NNNN-*.yamlanddocs/promptbooks/{active,archive}/PB-NNNN-*.md. For each.yamlbook with top-levelformat_version: validate shape by invoking${CRUX_PLUGIN_ROOT}/scripts/validate-promptbook.py --kind promptbook <path>(exit 0 = clean; exit 1 + JSONerrors= invalid → list them as BROKEN); other non-zero with empty stdout = crash — surface stderr, e.g. the exit-2 YAML-capability error (PyYAML missing; seedocs/AGENTS.md§10.A)). A.yamlbook LACKINGformat_version→ BROKEN (malformed). For each.mdbook: check the legacy required frontmatter keyset (id, title, status, created_at, total_prompts, current_run, current_prompt, forked_from, tags). List violations. 32. Every book'sidmatches its filename prefix. List mismatches. 33. (CHK-PB-3) For each book, format-detected:.yamlbook → confirmtotal_prompts == len(prompts)(the structured array; do NOT count### Prompt Nheadings — there are none, and counting would corrupt to 0)..mdbook (active) → count### Prompt Nheadings in the body; list mismatches againsttotal_prompts. Either way, confirmcurrent_prompt ≤ total_promptswhen non-null. 34. For every book withcurrent_run: RUN-NNN, confirmdocs/promptbooks/runs/<id>-<slug>/run-<RUN-NNN>.mdexists. List dangling pointers. Acurrent_runpointing at a TERMINAL run (completedorabandoned) is EXPECTED — the pointer stays until archival — and is not a dangling pointer; only a missing snapshot file is. 35. Listdocs/promptbooks/runs/<id>-<slug>/directories with no parent book inactive/orarchive/(orphan run dirs). 36. Every run snapshot (glob bothrun-*.yamlandrun-*.mdunderdocs/promptbooks/runs/<book>/) has the required top-level keys (run_id, book_id, started_at, completed_at, status, current_prompt) with status ∈ {in_progress, completed, abandoned}. For.yamlruns the run validator (item 40b) covers this shape; for.mdruns check the legacy frontmatter. List violations. 37. Forstatus: completedruns, confirmcompleted_atis non-null and every prompt's**State:**is terminal per the state-enum notes indocs/AGENTS.md§11.B (single source of truth — read §11.B for the terminal definition). List violations. 38. (CHK-PB-9) For archived books, confirm the FINAL run is archive-eligible by one of the two paths indocs/AGENTS.md§11.B:status: completedwith every prompt terminal (done | skipped | blocked), ORstatus: abandonedwithabandonment.kind: deliberate. List violations. Eligibility is a run-level property — there is no per-prompt flag. 39. Everyforked_from: PB-MMMMreferences an existing book. List dangling references. Nothing writes this field any more (it is an always-null vestige); the check is retained for the historical corpus. 40.manifest.yml'spromptbook.next_numbermust be strictly greater than the max existing PB number. Report values. 40a. (CHK-PB-ABANDON) For each ARCHIVED book whose final run hasstatus: abandoned: confirm it carriesabandonment.kind: deliberate.kind: superseded, or noabandonmentmapping at all, → BROKEN (archived on a signal that confers no eligibility). Adeliberateabandonment on a run underactive/is legitimate — ignore it (do NOT flag). 40a-bis. (CHK-PB-RADIUS) For each ARCHIVED book withcycle_kind: patch: confirmblast_radiusis present and non-empty, every entry passes the declared-path grammarinvalid_blast_radius_entryin${CRUX_PLUGIN_ROOT}/scripts/validate-promptbook.py(the single implementation — call it or read it; do NOT restate its rejections), and the final run has a non-nullbase_commit. Violation → BROKEN. Do NOT re-run the git comparison — a historical diff is not reproducible from an archived tree; containment was checked once at archival byarchive-promptbook. Demote to WARNING per the immutable-history rule. 40b. (CHK-PB-SCHEMA) Format-detected per-prompt shape..yamlrun withformat_version→ invoke${CRUX_PLUGIN_ROOT}/scripts/validate-promptbook.py --kind run <path>(exit 0 = clean; exit 1 + JSONerrors= list them) — other non-zero with empty stdout = crash (surface stderr, e.g. the exit-2 YAML-capability error (PyYAML missing; seedocs/AGENTS.md§10.A)); a.yamlrun lackingformat_version→ BROKEN (malformed)..mdrun → validate each^## Prompt Nblock againstdocs/AGENTS.md§11.B (read §11.B for fields + enum). Ignore## Notes/## Summary/## PR Draftand nested###/####content. Accept bulleted- **Field:**and bare**Field:**. Findings: missing §11.B-required field → DRIFT-surface;State∉ enum → BROKEN; unknown**Field:**→ WARNING.blocked-confirmedis a RETIRED field — IGNORE it entirely (do NOT report it as unknown; those.mdbodies are frozen). Demote ALL findings to WARNING (both paths) for archived orstatus: completedsnapshots (status wins over path). 40c. (CHK-PB-BIND) For each.yamlrun whosebook_idresolves to an active-or-archived.yamlbook: recompute the book's frozen-plan hash via${CRUX_PLUGIN_ROOT}/scripts/validate-promptbook.py'scompute_book_hash(canonical-JSON of the plan-bearing fields, excluding run-statecurrent_run/current_prompt/status) and compare to the run's storedbook_content_hash. List any mismatch (stored vs. recomputed) as DRIFT — NEVER auto-fix (recomputing erases the evidence; remediation is the §4 abandon rule — abandon the run, author a successor book). An unresolvablebook_idis NOT this rule — that's the orphan-run-dir / parent-book check (item 35). 40d. (CHK-PB-11)docs/promptbooks/index.mdcompleteness. Delegate it: invoke${CRUX_PLUGIN_ROOT}/scripts/check-promptbook-index.py --root <repo root>(exit 0 = clean; exit 1 + JSONvalidation_errors= list them; other non-zero with empty stdout = crash, surface stderr). It reports a book on disk with no index row, a duplicate row, a row naming a book that is not there, a heading whose count disagrees with the rows below it, and the tree index's promptbook rollup disagreeing with the directories. Membership is the DIRECTORY WALK (active/andarchive/, extension-agnostic,legacy/excluded) — never astatusfrontmatter filter, which yields a different set and would call an incomplete index consistent. This item exists because its absence was the defect. The inline rule list carried CHK-PB-11; this delegated enumeration did not. On a tree large enough to route the audit here, the index went uninspected, which is how 107 rows sat against 109 books. Missing rows → DRIFT (additive, auto-fixable); an orphan row → confirm before removing, per the destructive-repair rule.40e. (CHK-NUM-1) Duplicate record numbers. Delegate it: invoke
${CRUX_PLUGIN_ROOT}/scripts/check-record-numbers.py --repo-root <repo root>(exit 0 = clean; exit 1 + JSONvalidation_errors= list them, each naming the files that hold the shared number; other non-zero with empty stdout = crash, surface stderr). It covers promptbooks, promptbook run directories and ADRs across both lifecycle tiers, and excludeslegacy/. A shared number is BROKEN; report it and never renumber.Concern 6 — journal: 41. Every
##heading indocs/journal/YYYY-MM.mdmust match## \[\d{4}-\d{2}-\d{2} \d{2}:\d{2}\] (decision|implementation|bug|learning|blocker|refactor|meeting|review|misc|release) \|. List malformed. 42. List entries whose date is outside the file'sYYYY-MMscope. 43. (CHK-JR-3) Rungenerate-journal-index.py --dry-run. Parse stdout as JSON regardless of exit code and report its verdict — do not walkdocs/journal/and compare counts by hand. 44. List dangling wiki-links inside journal entries (adrs/,promptbooks/,research/targets). Promptbook book-links are lifecycle-agnostic (perdocs/AGENTS.md§11):[[promptbooks/(active|archive)/PB-NNNN-<slug>]],[[promptbooks/PB-NNNN-<slug>]],[[promptbooks/PB-NNNN]]resolve iff a book with that id exists underactive/ORarchive/(thePB-NNNNid is authoritative; ignore the segment;legacy/excluded).runs/links resolve by exact path. 45. Confirm entries are reverse-chronological within each month file.Concern 7 — catalog: 46. Catalog integrity: (CHK-CAT-1) list every entry in
${CRUX_PLUGIN_ROOT}/catalog/and confirm each is a regular file with suffix.jsonor.ymlthat parses by extension — report a directory, a symlink, or any other suffix as a misfiled entry and do NOT follow or parse it; report an entry over 1 MiB — this rule's per-entry ceiling, applied to.jsonand.ymlalike — as misfiled without parsing it (a.ymlalso faces the loader's tighter 64 KiBCATALOG_MAX_BYTESrefusal, which fires first and is the loader's to report, not yours). Confirm the required files exist: the.jsonfiles named invalidate-catalog.py'sREQUIRED_CATALOG_JSONconstant, and the.ymlfiles named in itsCATALOG_TARGETSconstant (both ship inside the plugin — do NOT derive either from the repo-rootAGENTS.md, which an installed tree may well have and which is NOT this plugin's roster; if a constant cannot be read, report BROKEN rather than an empty floor). (CHK-CAT-2) List skill ids present inplugin.jsonbut missing fromcatalog/skills.json, and vice versa. (CHK-CAT-4) List bundleskills:entries incatalog/bundles.ymlthat don't resolve to acatalog/skills.jsonid. (CHK-CAT-6) List the reverse: skills whosebundles[]names a bundle absent frombundles.yml, and skills absent from theskills[]of a bundle they declare. (CHK-CAT-5) Compare the count ofskills/*/SKILL.mddirectories against the length ofcatalog/skills.json. Do not runvalidate-catalog.py— just compare on-disk state.Concern 8 — arch (only when
archis inmanifest.yml'sconcerns_enabled; readdocs/AGENTS.md§4 "arch"): 47. (CHK-ARCH-1) Run${CRUX_PLUGIN_ROOT}/scripts/derive-arch.py --dry-run --docs-dir <docs_dir>from the repo root. Parse stdout as JSON regardless of exit code. Exit 1 means findings, and the payload names which of TWO independent channels found them; a run may carry both. exit 0 +{"clean": true, "drift": [], "strict_failures": []}= clean. exit 1 withdriftnon-empty = drift — report the drifted paths from thedriftarray as "arch spine drifted (main session will regenerate)". exit 1 withstrict_failuresnon-empty = a requirement finding, NOT drift and NOT a failed regeneration: each entry names a concernarch.requiredeclares this tree needs whose recorded verdict is notpopulated— report it as "arch requirement not met:<concern>is<verdict>(<stub_reason>)" and say that regenerating arch does not fix it, because the committed tree already is what a regeneration produces.cleananswers the drift question alone, so{"clean": true, "drift": []}at exit 1 is that second channel and not a contradiction. exit 2, non-zero with empty/unparseable stdout, or exit 1 reporting findings in neither channel = no verdict — report the stderr, NOT a document finding. Two lanes share exit 2: a crash (an environment error) and a deliberate refusal (StaleProjectionInputon stderr, meaning a projected input is not what its own regenerator produces). Report which lane stderr names; on the refusal lane name the stale input and its own regenerator, and say that regenerating arch does not fix it. Do NOT regenerate — the main session runsderive-arch.py(no--dry-run) to auto-fix, and only on the drift lane. 48. (CHK-ARCH-2) Confirm<docs_dir>/arch/has the four spine files (data-model.md,api-surface.md,module-graph.md,decision-index.md) plusoverview.md,index.md, and_meta/manifest.json; list any missing (the main session's regenerate produces them). Separately, if<docs_dir>/arch/exists butarchis NOT inconcerns_enabled, report it as a stale derived tree (WARNING). Do NOT expect an## Archsection indocs/index.md— arch is derived and carries no master-index rollup.Concern 9 — regenerated-output drift and doctrine reconciliation (read
docs/AGENTS.md§4 "doctrine" + the repo-rootAGENTS.mdregenerative-outputs roster): 49. (CHK-DRIFT-1) Run each remaining enrolled--dry-rundrift gate that Concerns 2/7/8 did NOT already run (they ranextract-code-docs.py,validate-catalog.py,derive-arch.py,generate-routing-table.py— do not re-run those). For the sixteen remaining roster outputs run:summarize-adrs.py --dry-run,compile-doctrine.py --dry-run,generate-opencode-agents.py --dry-run,generate-lineage.py --dry-run,generate-adr-index.py --dry-run,generate-index-rollup.py --dry-run,generate-readme-footer.py --dry-run,generate-writing-rules.py --dry-run,generate-runtime-compat.py --dry-run,generate-reviews-index.py --dry-run,generate-journal-index.py --dry-run,generate-log-summary.py --dry-run,generate-rules-catalog.py --dry-run,generate-mods-reach-tables.py --dry-run,generate-micro-crux.py --dry-run(agents.json is covered by the Concern-7validate-catalog.pyrun — do not re-invoke it; a"surface_absent": truepayload is N/A, not clean — the reviews index, the journal index and the operations-log summary carry this payload on a tree that has not populated that surface yet, and the rules catalog, the reach tables and the micro-crux guide carry it outside the plugin's own checkout). Parse each stdout as JSON regardless of exit code: exit 1 + a drift payload → report DRIFT with the drifted paths and the regenerator that fixes it (main session recommends, never regenerates); avalidation_errorspayload → BROKEN (name the input to repair); non-zero + empty stdout → report the stderr, not a document finding; awarningskey → WARNING beside the verdict. Do NOT regenerate anything. 50. (CHK-DOCTRINE-1) Only when<docs_dir>/adrs/doctrine/exists: count pending reconciliation pairings by reading<docs_dir>/adrs/doctrine/index.mdfor domains marked— BROKENwith reconciliation-table rows whose status isun-adjudicated,digest-stale, orcollision(or run${CRUX_PLUGIN_ROOT}/scripts/check-doctrine-reconciliation.py: exit 1 +broken_domains). Report the count as WARNING "N doctrine pairing(s) awaiting reconciliation — run reconcile-signoff", plus any S1warnings(a ratified invariant seeding no pairing). Do NOT auto-sign — reconcile-signoff is a human gate.Return a report grouped by concern with specific file paths and one-line descriptions. Keep findings terse — one line per violation.
4. Apply fixes
Categorize findings into BROKEN / DRIFT / WARNING.
Apply DRIFT auto-fixes in the main session, with notification:
- Update concern-section counts in
docs/index.md. - Refresh
_Last updated:_ondocs/index.md. - Rebuild
docs/adrs/index.md,docs/promptbooks/index.mdrollups from directory walks; fordocs/journal/index.md, recommendgenerate-journal-index.py. - Add missing
total_promptson active books (from### Prompt Ncount). - Set missing
last_reviewedon synthesis pages where the value can be inferred from the operations log (use the## [YYYY-MM-DD] ingest | <touching slug>entry with the latest heading date in any detail file underdocs/log/). - Fix
docs/research/sources.mdper-row column drift from frontmatter (frontmatter wins). - Create missing
docs/research/updates.mdstub (header only). - Back-populate brief
related_adrs:from ADRrelated_briefs:. - Regenerate a drifted
archspine (CHK-ARCH-1): run${CRUX_PLUGIN_ROOT}/scripts/derive-arch.py --docs-dir <docs_dir>, then confirm clean with one--dry-run. This is the one regenerated artifact the audit rewrites in place —docs/code/and the skill catalog are recommend-only (see the destructive-BROKEN list). Skip under--migrate.
Safe-to-fix-automatically BROKEN findings, with notification:
- Add missing optional frontmatter keys with sensible defaults (
previous_captures: [],static: false).
Requires user confirmation (destructive BROKEN):
- Removing orphan index rows.
- Deleting orphan raw folders.
- Deleting orphan run directories.
- Removing dangling slugs from any
sources:/related_briefs:/related_research:/supersedes:list. - Fixing supersession bidirectionality (the missing-link side might be the wrong side; ask).
- Regenerating
docs/research/sources.mdfrom scratch when missing. - Re-extracting
docs/code/to clear orphan pages (recommend runningextract-code-docsseparately).
WARNINGS: report only. Offer to address in a follow-up session.
5. Record the audit operation
Write the entry through the log writer, as docs/AGENTS.md §6 states: write the body to a file outside the tree, then run
uv run "${CRUX_PLUGIN_ROOT}/scripts/operation-log.py" append --repo-root <repo-root> \
--op audit --subject '<B broken / D drift fixed / W warnings>' --date <YYYY-MM-DD> --body-file <path>
It writes this heading at the top of the current month's detail file:
## [YYYY-MM-DD] audit | <B broken / D drift fixed / W warnings>
A refused append keeps the audit's other writes; fix the cause it names and rerun the append alone. Then run the commit step of §6 over the result's commit_paths and restore_paths.
Body, in three short sections:
- Fixed (drift + safe-broken): bulleted list per concern of what changed.
- Pending broken: list with file paths and the action the user needs to decide.
- Warnings: counts grouped by check id and concern.
6. Hand-off
Report to the user in this order:
- Summary line:
Audit complete: B broken, D drift, W warnings. Q auto-fixes applied. R pending your decision. - Pending BROKEN items requiring decisions, one per line with a recommended action.
- Notable warnings (e.g., "8 contradiction markers across 5 research pages — schedule
refresh-research-synthesis"). - Cross-concern observations: ADR drift > 2 → recommend a
transition-adr --repairpass; code drift detected → recommendextract-code-docs; arch spine drifted → note it was regenerated in place (name the drifted files); promptbook progress stalled → mention it. - If applicable: "It's been N writes since the last audit per concern — consider audits more/less often."
The --migrate mode
In the current release, audit-docs --migrate handles only repository
instruction files behind CHK-INSTR-1/2/4. It has no tree-schema ladder. A
schema-5 tree can still owe this instruction migration. When CHK-SCHEMA-1 finds
an older supported schema or a partial .migrating marker, use the pinned
recovery release first; references/migrate-mode.md
contains the route and the independent instruction procedure.
Run the current instruction migrator through its vendored script:
uv run "${CRUX_PLUGIN_ROOT}/scripts/migrate-instructions.py" --repo-root . --migrate
Exit 0 clean, 1 with findings JSON when a scope is refused, stopped, or
migrated without staging, 2 on a capability error. Where a scope holds both a
CLAUDE.md and an AGENTS.md, CLAUDE.md wins: its bytes become AGENTS.md,
with each line that imports the other file replaced by that file's bytes. A losing
AGENTS.md whose bytes differ is set aside under a reported name in its own
directory, never overwritten. Show the user every set-aside, refusal and next step
the report names. The migration plans every scope before it mutates anything, and a
rerun reaches the state an uninterrupted run reaches — it claims no multi-file
filesystem atomicity, and the receipt says so in as many words.
Red flags — STOP and reconsider
- About to delete a raw folder, run-snapshot directory, or any file under
docs/without explicit user confirmation. NEVER. Always ask. - About to rewrite ADR body content "to fix the alternatives section". The audit never touches ADR body — only status frontmatter and only via
transition-adr. - About to rewrite a research synthesis page during the audit. NEVER. That's
refresh-research-synthesis. - About to edit a past operations-log entry, in a detail file under
docs/log/or a legacydocs/log.md, to "fix the format". The log is append-only history. Mistakes are evidence; surface them, don't rewrite. - About to edit a past journal entry. Same rule — append-only.
- About to edit a past run snapshot's prompt body. Run snapshots' prompt bodies are immutable.
- About to merge two ADRs or two source pages to resolve a duplicate. Never auto-merge; ask which is canonical.
- About to "fix" supersession bidirectionality by editing both ends without user consent. The missing back-link might be the wrong direction — the user has to confirm which ADR really supersedes which.
- About to regenerate
docs/research/sources.mdfrom scratch because it's missing. Stop. Reconstructing from frontmatter loses any hand-edits. Ask first. - About to auto-run
extract-code-docsto fix code drift. The audit only runs--dry-run. The real extraction is the user's explicit call. - About to apply >20 auto-fixes silently. Show the user the list first — could be a systematic issue.
- About to invoke this skill recursively from inside another skill. The audit is end-of-cycle, not a hook.
Rationalization table and common mistakes
The Red flags list above is the primary stop-list. For the fuller
excuse→reality mapping and the recurring-mistake catalog (log-vs-journal
confusion, hidden-file counting, naive frontmatter parsing, orphan-vs-abandoned
runs), read references/pitfalls.md.
Output format example
For a worked example of the end-of-audit DRIFT / BROKEN / WARNINGS report the
hand-off produces, see references/output-format.md.
CHK-ADR-ARCHIVE (SP-4)
Tier invariant: active adrs/ holds {Proposed, Accepted}; cold adrs/archive/ holds {Superseded, Deprecated}. CHK-ADR-ARCHIVE flags every violation — a Proposed/Accepted ADR in archive/, a Superseded/Deprecated ADR still active, an unknown status, a duplicate id across tiers — and auto-repairs the one legitimate crash window (a terminal-status ADR still in adrs/ → complete the move). An active-status ADR found in archive/ is corruption: flagged BROKEN, never moved back. A raw-path guard flags any non-wiki-link ADR path reference (bionic/adrs/…, adrs/…, ./…, …/archive/…) in prose/prompts, with an allowlist for the ADR machinery (propose-adr, transition-adr, generate-index-rollup.py, generate-lineage.py, generate-adr-index.py, summarize-adrs.py). The counter-contiguity and supersedes/superseded_by bidirectional checks walk both tiers.
The summaries projection declares _meta.json schema "6"; doctrine declares schema "5". These are projection versions, independent of tree-layout schema "5", plugin schema "4" and book/run formats. Historical slug/handle and clause rosters resolve preserved evidence, not governing rows; current live replacements remain separate from original historical displacer provenance. A malformed historical map or failed activation is a refusal, never a reason to restore the old rule. Mutable governing references must resolve surviving architecture through lint-governs-references.py; excluded dated or frozen evidence retains historical retrieval semantics. Human-signed doctrine pairings require separate human disposition before a migration affects them. Report the dependency; never edit or sign the ledger, rewrite frozen bodies or repair a historical citation into current authority.
<docs_dir>/adrs/summaries/ is a REGENERATED artifact directory — the summaries rule table, resolver, and ADR↔run implementation map plus _meta.json, projected deterministically from ADR governs blocks (a regenerative output). It is NOT part of the ADR document graph: exclude it from every CHK-ADR-* walk (its files are not ADRs and carry no ADR frontmatter) and from the raw-path guard's prose scan (its ADR-NNNN references are machine-emitted data, not authored prose), exactly as promptbooks/legacy/ is excluded from every CHK-PB-* walk. Its drift is owned by summarize-adrs.py --dry-run (the regenerative-outputs roster gate + CI) and is now DETECTED by audit-docs through CHK-DRIFT-1 (which runs that same gate) — but audit-docs only recommends summarize-adrs.py; it does not regenerate the summaries projection here. The same recommend-only rule holds for the doctrine projection (<docs_dir>/adrs/doctrine/), a separate REGENERATED artifact directory (index + _meta.json, compiled from the summaries projection and reconciled against the ratified invariants): exclude it from every CHK-ADR-* walk and the raw-path guard's prose scan exactly like summaries/; its drift is detected by CHK-DRIFT-1's compile-doctrine.py --dry-run and recommended via compile-doctrine, never regenerated in the audit. <docs_dir>/adrs/doctrine/reconciliations.yml is likewise machine-owned (only reconcile-signoff writes it) — the audit reads it and never edits it.
<docs_dir>/adrs/reviews/ is excluded on a different ground (rule:reviews-surface-excluded-from-adr-walks). It holds the dated reports of the periodic decision review, one YYYY-MM-DD.md per pass, plus a derived index. Exclude it from every CHK-ADR-* walk and from the raw-path guard's prose scan, exactly as summaries/ and doctrine/ are excluded. The reason differs from that precedent's: summaries/ and doctrine/ are regenerated wholesale, while a review report is hand-kept and never regenerated. The only gate over the surface is the reviews index's own regenerator and its drift gate. Without the exclusion a dated report reads as a malformed ADR to every CHK-ADR-* rule — no ADR id, no §11.A frontmatter — and the ADR ids a report cites inline by contract would trip the raw-path guard. The audit neither reads a report as a record nor edits one. The index's drift belongs to CHK-DRIFT-1, whose regenerator is enrolled in the regenerative-outputs roster; the audit recommends that regenerator and never runs it.
[^code-doc-uv]: rule:code-doc-callers-invoke-through-uv [^correct]: rule:existing-books-are-corrected-at-execution [^log-enum]: rule:op-enum-applies-to-every-detail-file, rule:log-readers-read-every-log-file [^log-gate]: rule:pending-month-is-not-drift, rule:summary-gate-fails-on-a-changed-region
04 同仓库更多 Skills
whiteboarding
Explore an idea through docs-informed dialogue before committing to a design. Capture the exploration for later filing as a brief.
verify-code-docs
Check generated code documentation against source and report drift without regenerating it.
transition-observation
Apply a human disposition to an observation's lifecycle state without changing its claim or body.
transition-invariant
Ratify, reject, or retire an invariant on human direction. Update lifecycle metadata without changing the invariant's body.
transition-decision
Apply a human ratify, reject, or defer verdict to a recovered decision candidate; ratification creates a Proposed ADR or observation.
transition-brief
Publish or abandon a draft brief, updating lifecycle metadata and indexes without changing its body.