diff --git a/.gitea/workflows/pr-checks.yml b/.gitea/workflows/pr-checks.yml
index 45bd89954..50afae728 100644
--- a/.gitea/workflows/pr-checks.yml
+++ b/.gitea/workflows/pr-checks.yml
@@ -159,6 +159,36 @@ jobs:
echo "Parity-doc reminder: nothing to flag."
fi
+ # ersatztv#784 — ADVISORY nudge for `docs.no-session-narrative`. Deliberately NON-BLOCKING and
+ # deliberately in this job rather than a gate of its own: it is a string predicate over prose,
+ # and `docs/defect-shapes-773.md` §4 argues that class must not be load-bearing. The script
+ # exits 0 on every path (asserted per argument shape in scripts/tests/test_check_doc_narrative.py,
+ # not only in prose), so this step cannot redden the run even on a hit; if you find yourself
+ # wanting it to fail, read the decision record first — it says no in as many words.
+ # `python3` is not guaranteed on the bare `small` lane (docs/ci-cd.md), and every other
+ # python-using job on it declares this. Without it a missing interpreter is exit 127 — a RED
+ # advisory job joining the combined status, which is the one thing this step must never be.
+ #
+ # Both steps carry `continue-on-error` because the SCRIPT exiting 0 is not the whole invariant:
+ # a setup-python download failure reddens the job just as effectively as a hit would, and an
+ # advisory red still joins the combined status the merge gate reads (ersatztv#598). Scope,
+ # stated rather than implied: this covers the two steps that exist to run the check. A failed
+ # `Checkout` is NOT covered and deliberately so — with no tree there is nothing to check, and
+ # a job that cannot run is a different failure from an advisory one that ran and disagreed.
+ # Measured on this runner (PR#811, run 2179): the job reports `success` and the commit status
+ # context is `success` with both steps green under `continue-on-error`.
+ - name: Set up Python
+ uses: actions/setup-python@v5
+ continue-on-error: true
+ with:
+ python-version: '3.x'
+ - name: Warn when a doc narrates its own revision history
+ continue-on-error: true
+ run: |
+ base_ref="${{ github.base_ref }}"
+ git fetch --no-tags --depth=100 origin "$base_ref" || true
+ python3 scripts/check-doc-narrative.py --diff "origin/${base_ref}"
+
# BLOCKING (ersatztv#521, supersedes the ersatztv#303 H9 append-only mechanic): validates decision-
# record lifecycle invariants (metadata schema, one active record per key, reciprocal
# supersedes/superseded-by links, no rationale-prose rewrite without a Decisions-Edit: yes git
diff --git a/docs/README.md b/docs/README.md
index f9a933a97..2c398b022 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -27,6 +27,7 @@ doc below, or that changes which sections a task signal points to.**
| Proposing a new guard / CI check / regression test convention | `docs/defect-shapes-773.md` §4 (detector menu + the classes where no detector is plausible), then the two rules every guard must satisfy: `docs/decisions/records/testing/guard-derives-population-from-source.md` and `…/guard-ships-with-mutation-proof.md` |
| Testing a surface gated by config / an env var / a credential | `docs/decisions/records/testing/deny-path-at-production-config-value.md` — cover the setting absent, at its production value, and each opt-out, and assert the DENY branch |
| Touching a full-replace write path or a hand-built request object | `docs/decisions/records/testing/full-replace-asserts-field-list.md` — derive the field list from the DTO and assert set equality; reconcile by id where child state exists |
+| Writing or editing any doc, or answering a review finding in prose | `docs/decisions/records/docs/no-session-narrative.md` — the doc records the END STATE; the path to it goes in the commit message. Apply the who-benefits test, and read the carve-out before you cut (dated measurements, stated snapshot boundaries and tested-and-rejected results stay) |
| Adding / changing / deleting a guard file | `docs/guard-inventory.md` — every guard's row is machine-checked by `scripts/tests/test_guard_inventory.py`, so a new guard must acquire a row before the suite goes green |
| Writing code that reads live Gitea/remote state and then acts on it | `docs/decisions/records/process/check-and-use-pins-a-version.md`, then `docs/remote-state-inventory.md` — a new executable under `scripts/` (**excluding `scripts/tests/`**), `.claude/hooks/`, `.husky/` or `.gitea/workflows/` must acquire a row there before `scripts/tests/test_remote_state_inventory.py` goes green |
| Finding every site that references a symbol (multi-site fix/sweep) | `docs/local-lsp-tooling.md` — which surface answers, and why a delegated agent must be pointed at the `csharp-lsp` MCP tools rather than the `LSP` tool |
diff --git a/docs/ci-cd.md b/docs/ci-cd.md
index 5ce0c456d..6def410e3 100644
--- a/docs/ci-cd.md
+++ b/docs/ci-cd.md
@@ -838,12 +838,36 @@ Full rationale: `docs/decisions/records/ci/required-job-step-execution-markers.m
### `docs-reminder` job (non-blocking, PR-only — in `pr-checks.yml`)
-A lightweight nudge that enforces the CLAUDE.md "docs-update is part of done" rule for the
+Two lightweight nudges, both `::warning::`-only. Neither can fail the build — they are reminders,
+not gates; prose-doc gates get gamed with token edits.
+
+**1. The parity-doc reminder** enforces the CLAUDE.md "docs-update is part of done" rule for the
one case that's easy to forget and easy to detect: a PR that touches a SPA screen
(`web/src/screens/*.tsx`) or `ErsatzTV/LegacyUiRedirects.cs` but **does not** update
`docs/blazor-route-parity.md`. It diffs the PR against its base branch and emits a
-`::warning::` annotation (never fails the build — it's a reminder, not a gate; prose-doc
-gates get gamed with token edits). Deliberately has **no** `setup-dotnet`/`setup-node` (and
+`::warning::` annotation.
+
+**2. The session-narrative reminder** (ersatztv#784) runs `scripts/check-doc-narrative.py --diff`
+over the lines this PR **adds** to `docs/**/*.md` (minus `docs/decisions/**`, exempt wholesale) and
+root-level `*.md`, flagging text that narrates the document's own revision history —
+`docs.no-session-narrative`. It is advisory **by design and permanently**: a narrative detector is a
+string predicate over prose, the class `docs/defect-shapes-773.md` §4 argues must never be
+load-bearing, so the script exits 0 on every path including a bad argument or an unresolvable base
+ref. It does NOT rest on prose alone, and it does not rest wholly on tests either: the record's
+COVERAGE BOUNDARY names which clauses carry a mutation proof and which are defensive and unproven
+(the unhandled-exception arm among them). Every argument shape is asserted per shape in
+`scripts/tests/test_check_doc_narrative.py` rather than only in prose. When it cannot resolve the
+base it prints `SCANNED NOTHING` instead of a clean-looking line, because a silent zero-file scan is
+indistinguishable from a clean one — the same failure `ci.required-job-step-execution-markers`
+exists for.
+
+Because this step needs an interpreter, the job DOES carry `actions/setup-python` — the one
+exception to the no-setup-actions note below, since `python3` is not guaranteed on the bare `small`
+lane. Both it and the script step carry `continue-on-error: true`: a script that exits 0 does not by
+itself keep the JOB green, and a setup-action download failure would redden an advisory check just
+as effectively as a hit would.
+
+The job deliberately has **no** `setup-dotnet`/`setup-node` (and
thus no `actions/cache`), so it can't hit the cache-save hangs seen on the VM-127 runner
(server-management#570). It does not cover the remaining doc obligations in the CLAUDE.md table
(domain-model, spa-conventions) — those stay on the author. (The API contract is mechanized by the
diff --git a/docs/decisions/README.md b/docs/decisions/README.md
index 4af092e6e..1aedeab2f 100644
--- a/docs/decisions/README.md
+++ b/docs/decisions/README.md
@@ -80,6 +80,7 @@ the link for rationale. Superseded/retired history lives in `archive/`. Regenera
| `docs.decision-one-file-per-record` | Each decision record is its own file at `docs/decisions/records//.md` (archived ones at `docs/decisions/archive//.md`) with YAML frontmatter; the filename IS the key, so one-active-record-per-key is a filesystem property rather than a validator check, and supersession is a `git mv`. | 2026-07-25 | [link](records/docs/decision-one-file-per-record.md) |
| `docs.decision-optional-provenance` | Decision records gain two OPTIONAL fields — `stale-after: YYYY-MM-DD` on the metadata line and a `**Sources:**` line in the metadata block; the Open Knowledge Format (OKF) itself is NOT adopted as the record format. | 2026-07-25 | [link](records/docs/decision-optional-provenance.md) |
| `docs.frontmatter-pyyaml-crosscheck` | `decisions_validate.py` runs `pyyaml_frontmatter_faults()` over every record-wing file: it loads the frontmatter with PyYAML and reports an ERROR when PyYAML rejects the document OR when any key's value differs from what the dependency-free `dl._read_frontmatter` read. PyYAML is the WRITER of these files (`migrate_decisions_split.render_record` emits them with `yaml.safe_dump`), so on any disagreement PyYAML is authoritative and the defect is in the FILE, not in either parser. The check is strictly additive: when PyYAML is not importable it is SKIPPED and `main()` says so with a `::notice::`, never silently — the read path stays dependency-free because `decisions-guard`, the Husky hooks and contributor machines install nothing. The comparison has exactly ONE implementation, called by both the validator and `test_frontmatter_reader_matches_pyyaml_on_every_real_record`, so the suite and the tool cannot drift on what "matches PyYAML" means. | 2026-08-04 | [link](records/docs/frontmatter-pyyaml-crosscheck.md) |
+| `docs.no-session-narrative` | Every durable artifact — an in-repo `docs/` page, a skill, a README, a code comment, an Obsidian vault page — records the END STATE. The path to that end state goes in the commit message, the Gitea issue, or the issue's `## Closing record`; it does not go in the artifact. Concretely: **a review finding is answered in the commit message, and only the corrected claim enters the doc.** Naming the destination is load-bearing — "do not write it in the doc" with no home loses the knowledge, and this repo has the inverse failure on record too (#542, where a pruned narrative turned out to be the only copy). THE TEST IS WHO BENEFITS: if only the author's timeline explains why a sentence is there, it is narrative and belongs in the commit; if a reader who never saw the session would act differently knowing it, it is a finding and stays. Session narrative reads as: first person or session chronology ("I initially thought", "an earlier draft counted", "my first attempt returned 0"), a correction of a belief the reader never held ("this was wrong, actually X" where only X matters), relative time ("earlier today", "currently investigating"), or a blow-by-blow diagnosis standing in place of the conclusion. THE CARVE-OUT, which must be stated or the rule gets over-applied — reader-facing history that must survive: a decision record's `supersedes`/`superseded-by`; a dated measurement or an explicitly stated snapshot boundary; a TESTED-AND-REJECTED negative result, kept so nobody re-proposes it on plausibility; the *why* behind a non-obvious choice; and a trap together with its consequence. `docs/decisions/records/**` and `docs/decisions/archive/**` are exempt WHOLESALE: a record narrating how a rule was got wrong is carrying the rationale it exists to carry. ENFORCEMENT IS ADVISORY ONLY — `scripts/check-doc-narrative.py`, run non-blocking from the `docs-reminder` job over ADDED lines. It is a string predicate over prose and may never become a blocking gate. | 2026-08-21 | [link](records/docs/no-session-narrative.md) |
| `docs.record-wing-parse-guard` | `decisions_validate.py` asserts, per PATH, that every `*.md` under `docs/decisions/records/**` and `docs/decisions/archive/**` parses to exactly one record carrying a `key` — an ERROR, not a warning, since a file in the record wings that is not a record is a mistake by definition. A file sitting DIRECTLY in `archive/` is exempt only when it actually looks like a #610 stripped index — exactly one keyless record with a known generated heading — never merely by living there. The one other exemption, `archive/README.md`, is by exact RELATIVE PATH; nothing is ever exempt by BASENAME, since that would exempt the same filename in the active wing too. `_read_frontmatter` is deliberately NOT extended to accept YAML block scalars: every record value goes on ONE line, and the structural check is what makes that limitation loud instead of silent. | 2026-07-26 | [link](records/docs/record-wing-parse-guard.md) |
| `docs.tracker-comment-retrofit` | When the knowledge exporter flags an over-cap tracker issue and excludes it from ingestion, triage its comments instead of assuming a retrofit is owed — and for each decision-shaped item check the **worked issue first**, because a tracker session comment is by construction a précis of the fuller closing record posted on the issue it narrates. Applied to #237 (111 comments) this yielded **zero** records, so server-management#642's "a fact found only in a #237 comment" retrieval row has no valid subject and its interim target (an already-migrated record) is permanent. | 2026-07-21 | [link](records/docs/tracker-comment-retrofit.md) |
| `ffmpeg.external-logo-graphics-engine` | External-URL channel logos pass through to the graphics engine like any other watermark source; `WatermarkSelector` must never gate them on `File.Exists` (always false for a URL) and never route them through the ffmpeg-native overlay shortcut. | 2026-07-20 | [link](records/ffmpeg/external-logo-graphics-engine.md) |
diff --git a/docs/decisions/records/docs/no-session-narrative.md b/docs/decisions/records/docs/no-session-narrative.md
new file mode 100644
index 000000000..df8cb9f83
--- /dev/null
+++ b/docs/decisions/records/docs/no-session-narrative.md
@@ -0,0 +1,56 @@
+---
+key: docs.no-session-narrative
+title: '2026-08-21 — a doc records the end state; the path to it goes in the commit message, not the artifact (#784)'
+status: active
+since: '2026-08-21'
+supersedes: none
+superseded-by: none
+rule: 'Every durable artifact — an in-repo `docs/` page, a skill, a README, a code comment, an Obsidian vault page — records the END STATE. The path to that end state goes in the commit message, the Gitea issue, or the issue''s `## Closing record`; it does not go in the artifact. Concretely: **a review finding is answered in the commit message, and only the corrected claim enters the doc.** Naming the destination is load-bearing — "do not write it in the doc" with no home loses the knowledge, and this repo has the inverse failure on record too (#542, where a pruned narrative turned out to be the only copy). THE TEST IS WHO BENEFITS: if only the author''s timeline explains why a sentence is there, it is narrative and belongs in the commit; if a reader who never saw the session would act differently knowing it, it is a finding and stays. Session narrative reads as: first person or session chronology ("I initially thought", "an earlier draft counted", "my first attempt returned 0"), a correction of a belief the reader never held ("this was wrong, actually X" where only X matters), relative time ("earlier today", "currently investigating"), or a blow-by-blow diagnosis standing in place of the conclusion. THE CARVE-OUT, which must be stated or the rule gets over-applied — reader-facing history that must survive: a decision record''s `supersedes`/`superseded-by`; a dated measurement or an explicitly stated snapshot boundary; a TESTED-AND-REJECTED negative result, kept so nobody re-proposes it on plausibility; the *why* behind a non-obvious choice; and a trap together with its consequence. `docs/decisions/records/**` and `docs/decisions/archive/**` are exempt WHOLESALE: a record narrating how a rule was got wrong is carrying the rationale it exists to carry. ENFORCEMENT IS ADVISORY ONLY — `scripts/check-doc-narrative.py`, run non-blocking from the `docs-reminder` job over ADDED lines. It is a string predicate over prose and may never become a blocking gate.'
+signals: 'no session narrative in docs · the reader never saw the earlier draft · who-benefits test · answer a review finding in the commit message not the doc · end state versus path to it · earlier draft · first version of this table · my first attempt · relative time in a doc · carve-out for dated measurement and snapshot boundary · tested-and-rejected negative result · decision records are exempt on purpose · advisory not blocking · string predicate over prose · paths: `scripts/check-doc-narrative.py`, `.gitea/workflows/pr-checks.yml`, `docs/handoffs/chicorytv-issue-queue.md`, `docs/defect-shapes-773.md` · issues: #784, #773, #767, #743, #542'
+mechanics: 'The RULE is about every durable artifact; the DETECTOR''s population is narrower and is stated here so a row in it never reads as coverage it does not have. `scripts/check-doc-narrative.py` scans `docs/**/*.md` minus `docs/decisions/**` (exempt wholesale, in both modes), plus root-level `*.md`. Skills under `.claude/`, `web/`, and every other nested markdown file outside `docs/` are OUT of its scope and stay a human judgement. It warns and exits 0 on every path — bad argument, unresolvable ref, unreadable file, unhandled exception — asserted per argument shape in `scripts/tests/test_check_doc_narrative.py`, not only in prose, EXCEPT the unhandled-exception arm, which is a bare `except` no test exercises and is recorded as unproven rather than implied. The invariant is held at the JOB level too (`continue-on-error` on both steps): a script that returns 0 does not keep a job green if a setup action fails. Every knob DEMONSTRATED to break the parse has a row in `FORMAT_KNOBS` in the test file; the user and system config files are removed from the picture entirely so an unnamed one cannot reach it. Three separate review rounds each found ONE more knob turning a real hit into a clean-looking `scanned 0 file(s)`, so the third fix removed the surface rather than naming a fourth knob — a completeness claim over the knob space would be exactly the enumeration that failed three times. COVERAGE BOUNDARY, written once so it is not rediscovered one clause at a time, and naming the clauses rather than a category because a category is where the last mis-sort hid. MUTATION-PROVEN: the parse path (hunk state, the `\` marker, the `diff --git` reset, `splitlines`, the population count, `re.IGNORECASE`, the SCANNED-NOTHING return) and five pins — `core.quotePath=false`, `--find-renames`, `--dst-prefix`, `--no-ext-diff`, `--no-color`. UNPROVEN and defensive, recorded as such rather than implied to be covered: `-U0` (the context arm handles any `-U`, so removing it reddens nothing), the `GIT_CONFIG_GLOBAL`/`SYSTEM`/`NOSYSTEM` overrides (which exist for the UNNAMED knob and therefore cannot be witnessed — the script says so itself), `--src-prefix`, the `+++ /dev/null` deletion arm, the malformed-`@@` arm, the stderr relay, `git()`''s `OSError` return, `run_all`''s failure sentinel, `open(errors=)` and the top-level `except`. Both lists ENUMERATE; neither is a universal over the file, and a clause on neither list has simply not been measured. `--diff` scans only lines ADDED in the PR (with rename detection, so a `git mv` does not re-flag a file''s pre-existing content) and reports `SCANNED NOTHING` rather than a clean-looking line when it cannot resolve the base. `--all` sweeps the tracked corpus from `git ls-files`, never a filesystem walk (#778). Two consequences of added-lines-only are deliberate and stated so they are not mistaken for coverage: a file MOVED into the population (`web/x.md` to `docs/x.md`) is never scanned by any PR, and neither is anything already in the corpus. `--all` is the only thing that sees either, which is why the sweep is a task a person runs rather than a job.'
+---
+
+The rule already existed, correctly stated, and scoped to exactly one file. The kickoff handoff said
+a paragraph of narrative there is a tax paid by every future session, *because that file is pasted
+into every session*. That reason is file-specific. The general reason is broader and applies to
+every doc in the repo: **a reader coming to a doc cold never saw the earlier draft**, so "we
+previously got this wrong" carries nothing they can act on.
+
+This is the recurring shape `#773` measures — a rule established where it was first noticed and
+never extended to its class. It is the same shape as #743, where a control defended the merge path
+while the push path stayed open, and as #767's record puts it: *"'the ban is enforced' and 'the ban
+is enforced **where it matters**' were never separated."* The generalisation is the fix; the six
+stripped instances in `docs/defect-shapes-773.md` were the symptom.
+
+**Why it leaks — a mechanism, not a discipline problem.** A review finding creates pressure to
+answer *in the artifact*. The correction and the justification-for-the-correction get written in the
+same keystroke, and the artifact is the file already open, so the justification lands there too.
+Every one of the six instances came out of a review round. That is why the rule names a destination
+rather than only a prohibition: the commit message is written at the same moment, is permanent, and
+is where provenance is actually looked for.
+
+**Why the carve-out is half the rule.** Over-stripping is the more common failure. A doc cut to bare
+facts reads as arbitrary and the next reader "fixes" it back — which is how a rejected approach gets
+re-proposed and a trap gets re-sprung. `docs/defect-shapes-773.md` carries both a dated measurement
+and a struck-through `shellcheck` row recording a *tested* negative result; both are reader-facing
+history and both must survive. The who-benefits test is what separates them from narrative, and it
+is stated as a question rather than a word list because a word list is exactly what the mechanised
+half of this cannot be trusted to be.
+
+**Why enforcement is advisory and stays that way.** A narrative detector is a string predicate over
+prose. `docs/defect-shapes-773.md` §4 and `testing.guard-derives-population-from-source` both argue
+that a weak string-matching detector is the symptom-keyed mistake, and the withdrawn
+`test_review_verdict_vocabulary_parity.py` — six cold-review rounds, then deleted — is the empirical
+case: every round's fix was locally correct and the sequence never converged. As a blocking gate
+this is a bad bet. As a non-blocking nudge it is nearly free, and the repo already runs that exact
+pattern in `docs-reminder` for the parity doc. So the detector warns; it never fails a run. Budget
+for it being wrong sometimes, and make that acceptable by not letting it block.
+
+**It is Python, not shell, and that is the same argument one level down.** A detector over diff output has to decide what each line IS, and deciding that from its prefix alone — without hunk state — is a string predicate too. Four distinct defects fell out of one bash implementation of it: the no-trailing-newline marker counted as content, an added line whose own text began `++ ` eaten by the `+++ ` header arm, `core.quotePath` hiding non-ASCII paths, and a final unterminated line dropped by `read`. Those are four sites of one mistake, so the mechanism was replaced rather than the sites patched one at a time. Anything that parses a diff here should parse it with hunk state or not at all.
+
+**If this ever becomes a hook, it belongs at USER scope, not in this repo.** The rule is not
+ersatztv-specific — it is true of every repo — and an ersatztv-only hook would enforce it exactly
+where it was first noticed and nowhere else, which is the shape this record exists to close.
+Mechanically that means `~/.claude/hooks/` plus the user `settings.json`. Worth stating because
+`~/.claude/hooks/` holds only cosmetic hooks today (terminal title, statusline), so there is no
+precedent there for a content rule and someone would have to decide that deliberately.
diff --git a/docs/guard-inventory.md b/docs/guard-inventory.md
index 908270137..f9a0ce2aa 100644
--- a/docs/guard-inventory.md
+++ b/docs/guard-inventory.md
@@ -90,6 +90,7 @@ all.
| `.husky/pre-commit` | a commit failing lint-staged, decisions, root-PNG or format | GUARD | NONE | — |
| `.husky/pre-push` | a push failing any pre-push hook or the SPA gate | GUARD | MUTATION | `test_prepush_unsets_git_env.py::test_MUTATION_DELETING_the_unset_lets_drift_through_silently` |
| `scripts/build_decisions_catalog.py` | the `decisions-guard` job, on a stale catalog | GUARD | MUTATION | `test_build_catalog_check_path.py::test_MUTATION_disarming_the_stale_comparison_stops_detection` |
+| `scripts/check-doc-narrative.py` | nothing, by design (advisory `::warning::` only, exits 0 on every path (the error/degradation arms are defensive and unproven — see the record) — `docs.no-session-narrative` says a string predicate over prose may not be load-bearing) | TOOLING | NONE | — |
| `scripts/check-kickoff-guard.sh` | the `decisions-guard` job, on a revived #237 reference | GUARD | NONE | — |
| `scripts/check-review-verdict.sh` | the merge-consent hook's verdict classification | GUARD | BEHAVIOUR-ONLY | `test_check_review_verdict.py::test_falseopen_token_must_be_a_whole_word` |
| `scripts/ci-detect-already-validated.sh` | nothing directly (feeds the skip gate) | GUARD | NONE | — |
@@ -111,6 +112,7 @@ all.
| `scripts/tests/test_build_catalog.py` | the `script-tests` job | PROOF | NONE | — |
| `scripts/tests/test_build_catalog_check_path.py` | the `script-tests` job | PROOF | NONE | — |
| `scripts/tests/test_check_review_verdict.py` | the `script-tests` job | PROOF | NONE | — |
+| `scripts/tests/test_check_doc_narrative.py` | the `script-tests` job | PROOF | NONE | — |
| `scripts/tests/test_ci_dropped_step_guard.py` | the `script-tests` job | PROOF | NONE | — |
| `scripts/tests/test_ci_image_pin_population.py` | the `script-tests` job, when a container job loses its pin | GUARD | MUTATION | `test_ci_image_pin_population.py::test_a_single_job_losing_its_pin_is_DETECTED` |
| `scripts/tests/test_ci_release_path_scan_job.py` | the `script-tests` job, on a weakened release-path scan job | GUARD | NONE | — |
@@ -133,7 +135,7 @@ all.
## What the numbers say
-34 guards, 5 tooling scripts, 18 proof files. **12 guards carry a mutation proof; 6 are
+34 guards, 6 tooling scripts, 19 proof files. **12 guards carry a mutation proof; 6 are
behaviour-only; 16 have none.** These figures are asserted against the table by
`test_the_summary_counts_match_the_table` — they were wrong in the first draft (28/4/6/3/19 against
a table holding 27/5/6/3/18), because a hand-maintained summary of a table is a second copy of it,
diff --git a/docs/handoffs/chicorytv-issue-queue.md b/docs/handoffs/chicorytv-issue-queue.md
index 5d2d2ba5d..7a795374d 100644
--- a/docs/handoffs/chicorytv-issue-queue.md
+++ b/docs/handoffs/chicorytv-issue-queue.md
@@ -346,8 +346,10 @@ HARD CONSTRAINTS:
> **Scope**: *how we work* — orchestration, CI triage, review routing, cross-session hygiene. Each rule
> below is one or two lines plus its decision `key:`; the evidence, the incident that produced it and the
> full rationale live in that record (`docs/decisions/workflow-process.md` for most of them). **Keep it
-> that way** — this file is pasted into every session's kickoff, so a paragraph of narrative here is a tax
-> paid by every future session, while a record is retrieved only when it is needed (#542).
+> that way** — `docs.no-session-narrative` is the general rule (a doc records the end state; the path to
+> it goes in the commit message), and it binds here with one extra cost on top: this file is pasted into
+> every session's kickoff, so a paragraph here is a tax paid by every future session, while a record is
+> retrieved only when it is needed (#542).
>
> Editing: prune covered and stale bullets rather than appending — this is not append-only and git keeps
> the history. If you add a rule, write the record first and cite it here.
diff --git a/docs/remote-state-inventory.md b/docs/remote-state-inventory.md
index e2fb528af..c5c0107cf 100644
--- a/docs/remote-state-inventory.md
+++ b/docs/remote-state-inventory.md
@@ -120,6 +120,7 @@ classifications differ; otherwise the strictest applies and the Note names the e
| `scripts/decisions_lib.py` | `N/A` | Reads no live remote state — pure parser over local decision-record files. |
| `scripts/migrate_decisions_split.py` | `N/A` | Reads no live remote state — one-shot local file migration over `docs/decisions/`. |
| `scripts/generate-endpoint-index.py` | `N/A` | Reads no live remote state — reads local `v1.json` and writes a local markdown index. |
+| `scripts/check-doc-narrative.py` | `N/A` | Reads no live remote state. Both modes are local: `--diff` reads `git diff` against a ref the CALLER fetched, `--all` reads `git ls-files`. The `docs-reminder` fetch that supplies the ref carries its own row below. |
| `scripts/check-kickoff-guard.sh` | `N/A` | Reads no live remote state — scans a fixed local file list for forbidden phrasing. |
| `scripts/check-local-lsp.sh` | `N/A` | Reads no live remote state — probes local PATH binaries and spawns a local MCP server over stdio. |
| `scripts/mcp_smoke.py` | `N/A` | Reads no live remote state — spawns a local subprocess and speaks JSON-RPC over stdio pipes, no network socket. |
@@ -147,7 +148,7 @@ classifications differ; otherwise the strictest applies and the Note names the e
| `.gitea/workflows/ci-image.yml` — verify the pushed image | `UNSAFE-KNOWN` | Pulls back the `:` tag it pushed in the immediately preceding step. Same demotion and same reason as the two rows above: a registry tag is not a digest, and anything able to write to the registry can repoint it between the push and the verify, which would make the verification confirm an image other than the one built. Accepted on the same terms — the exposure requires registry write access, i.e. an actor already inside the trust boundary — and the same fix applies. |
| `.gitea/workflows/pr-checks.yml` — `prove-fix` | `PINNED` | `base`/`head` are full shas from the event payload, immune to later PR mutation. |
| `.gitea/workflows/pr-checks.yml` — `ci-image-pin` | `N/A` | A purely local comparison — `git log` over the checked-out tree against a literal in `docker-build.yml`. It never queries the registry, which is exactly why it cannot bound the retagging the image rows above describe. |
-| `.gitea/workflows/pr-checks.yml` — `docs-reminder` base fetch | `N/A` | Fetches the live base tip, but the result only selects the text of a non-blocking warning. The rationale has to be narrower than the first draft's "the job cannot fail and never reaches the combined status", which is false — any job's status joins the combined state, and runner or checkout failure can redden it. What is true, and is what earns the `N/A`: the fetch and diff are failure-swallowed, so the remote read cannot change this job's outcome, only the warning's wording. It draws no authorization from what it reads, this file's second `N/A` clause. Grouping it with `decisions-guard` over-demoted it, and the two have different classifications, so per the rule above they get separate rows. |
+| `.gitea/workflows/pr-checks.yml` — `docs-reminder` base fetch | `N/A` | Fetches the live base tip, but the result only selects the text of a non-blocking warning. The rationale has to be narrower than the first draft's "the job cannot fail and never reaches the combined status", which is false — any job's status joins the combined state, and runner or checkout failure can redden it. What is true, and is what earns the `N/A`: the fetch and diff are failure-swallowed, so the remote read cannot change this job's outcome, only the warning's wording. It draws no authorization from what it reads, this file's second `N/A` clause. Grouping it with `decisions-guard` over-demoted it, and the two have different classifications, so per the rule above they get separate rows. Since ersatztv#784 the job runs TWO advisory checks off this fetch (the parity-doc reminder and `scripts/check-doc-narrative.py`); the classification is unchanged because the second is advisory on the same terms — it exits 0 on every path, so a moved base still only changes warning text (its unproven arms are enumerated in `docs.no-session-narrative`). |
| `.gitea/workflows/pr-checks.yml` — `decisions-guard` base fetch | `UNSAFE-KNOWN` | Fetches the live base tip and diffs against it, unpinned, and unlike `docs-reminder` this job CAN fail — so its answer reaches the combined status the merge hook reads and therefore participates in consent. Accepted on the same grounds as the `api-docs`/`format` row: a base that moved mid-job produces a spurious FAILURE and a re-run, never a spurious pass, and it re-fetches fresh on every trigger with no state carried between runs. |
| `.gitea/workflows/renovate.yml` — `renovate/renovate:43` | `N/A` | Out of this class, in scope for a different one — see the limits below. |
| `.gitea/workflows/dependency-scan.yml` — NuGet advisory query | `N/A` | `dotnet list package --vulnerable` queries a live advisory database and fails the job on the report marker in the same step, so there is no check-then-act split. Worth one line anyway: a green here means "no advisories **as of this run**", which is a dated claim about mutable remote data rather than a property of the tree — which is why the scan runs on a weekly schedule instead of only on PRs. |
diff --git a/scripts/check-doc-narrative.py b/scripts/check-doc-narrative.py
new file mode 100755
index 000000000..3b98188ef
--- /dev/null
+++ b/scripts/check-doc-narrative.py
@@ -0,0 +1,259 @@
+#!/usr/bin/env python3
+"""ersatztv#784 — ADVISORY nudge for `docs.no-session-narrative`.
+
+A doc records the END STATE; the path to it belongs in the commit message, not the artifact.
+
+THIS NEVER FAILS. Every path returns exit 0 — including a bad argument, an unresolvable base ref,
+an unreadable file and an unhandled exception. That is a design constraint, not an oversight: a
+narrative detector is a string predicate over prose, and `docs/defect-shapes-773.md` §4 plus
+`testing.guard-derives-population-from-source` both argue that class must not be load-bearing (the
+withdrawn `test_review_verdict_vocabulary_parity.py` — six review rounds, then deleted — is the
+empirical case). Do not convert this into a gate; the decision record says no in as many words.
+
+WHY PYTHON AND NOT SHELL. The first implementation hand-parsed `git diff -U0` output in bash by
+matching line prefixes, and cold review demonstrated four separate defects in that one parser: the
+`\\ No newline at end of file` marker was counted as content, an added line whose own text began
+`++ ` was eaten by the `+++ ` header arm, `core.quotePath` hid non-ASCII paths, and `read` dropped a
+final unterminated line. Those are four instances of one mistake — deciding what a diff line IS from
+its prefix alone, with no hunk state. Patching them one at a time is the shape this repo has
+recorded as never converging, so the mechanism was replaced rather than the sites.
+
+ check-doc-narrative.py --diff scan lines ADDED against (the CI mode)
+ check-doc-narrative.py --all scan the whole tracked corpus (deliberate sweep)
+
+Scanning only ADDED lines in CI is what keeps the existing corpus of legitimate history out of the
+output; `--all` deliberately reports all of it, for a human to apply the who-benefits test to.
+"""
+
+from __future__ import annotations
+
+import os
+import re
+import subprocess
+import sys
+
+# The never-fails invariant must not depend on the ambient locale. Both the summary line and the
+# last-resort handler below carry non-ASCII text, so under ascii/latin-1 stdio the very code meant to
+# guarantee exit 0 is what raises. Degrade unencodable characters instead of failing on them.
+try:
+ sys.stdout.reconfigure(errors="replace") # type: ignore[union-attr]
+ sys.stderr.reconfigure(errors="replace") # type: ignore[union-attr]
+except Exception: # noqa: BLE001, S110 — a stdout that cannot be reconfigured is not a reason to fail
+ pass # deliberate: this is the never-fails invariant's own setup, so it cannot itself raise
+
+# `docs/decisions/**` is exempt WHOLESALE — a decision record narrating how a rule was got wrong is
+# carrying the rationale it exists to carry, so a detector that flagged it would fight the
+# convention it serves.
+EXEMPT_PREFIXES = ("docs/decisions/",)
+
+# Session-narrative phrasings. Deliberately narrow: each is first person or names a revision of THIS
+# artifact. Broad words that also appear in legitimate dated history ("previously", "was wrong") are
+# absent on purpose — a false positive on a carved-out case is what makes an advisory check stop
+# being read.
+PATTERNS = re.compile(
+ r"an earlier draft"
+ r"|earlier drafts"
+ r"|the (?:first|previous|original) (?:version|draft) of (?:this|the)"
+ r"|my first attempt"
+ r"|I (?:initially|first|originally|then) (?:thought|assumed|tried|wrote|found)"
+ r"|we (?:then|initially) (?:found|thought|realis|realiz)"
+ r"|it turned out that"
+ r"|earlier today"
+ r"|as of just now"
+ r"|currently investigating",
+ re.IGNORECASE,
+)
+
+WARNING = (
+ "{path}:{line} reads as session narrative — a reader coming cold never saw the earlier draft. "
+ "Answer the review finding in the COMMIT MESSAGE and let only the corrected claim enter the "
+ "doc (docs.no-session-narrative). Keep it only if a reader would ACT differently knowing it "
+ "(dated measurement, stated snapshot boundary, tested-and-rejected result, a trap and its "
+ "consequence). Line: {text}"
+)
+
+
+def is_scanned_path(path: str) -> bool:
+ """The population: `docs/**/*.md` minus `docs/decisions/**`, plus root-level `*.md`.
+
+ Stated positively and in one place so the record's `mechanics:` can quote it exactly. Skills,
+ `web/`, and other nested markdown outside `docs/` are deliberately NOT in scope.
+ """
+ if not path.endswith(".md"):
+ return False
+ if any(path.startswith(p) for p in EXEMPT_PREFIXES):
+ return False
+ return path.startswith("docs/") or "/" not in path
+
+
+# Git's OUTPUT FORMAT is configurable, and this script reads paths and line numbers out of that
+# format. Three separate knobs were each demonstrated turning a real hit into `scanned 0 file(s)` —
+# `core.quotePath` hiding non-ASCII paths, `diff.dstPrefix` rewriting the header, `color.diff=always`
+# injecting ANSI escapes. Pinning them one at a time is refuting variants, not clearing the channel,
+# so the channel is closed at both ends: the user's and the system's config files are taken out of
+# the picture entirely (which also covers knobs nobody has thought of yet), and the handful that a
+# REPO-local config could still set are pinned explicitly on the command line, where they win.
+GIT_ENV_OVERRIDES = {
+ "GIT_CONFIG_GLOBAL": os.devnull,
+ "GIT_CONFIG_SYSTEM": os.devnull,
+ "GIT_CONFIG_NOSYSTEM": "1",
+}
+# `core.quotePath=false` is witnessed by a test. The env overrides above are NOT, and cannot be: they
+# exist for the knob nobody has named yet, which is exactly what three rounds of naming one knob at a
+# time argued for. Every knob that IS named is pinned on the command line, where it also beats a
+# repo-local config, and has a row in FORMAT_KNOBS in the test file.
+GIT_CONFIG_PINS = ("-c", "core.quotePath=false")
+
+
+def git(*args: str) -> tuple[int, str]:
+ """Run git with its output format pinned. Returns (returncode, stdout) and never raises."""
+ try:
+ p = subprocess.run(
+ ["git", *GIT_CONFIG_PINS, *args],
+ capture_output=True,
+ text=True,
+ errors="replace",
+ env={**os.environ, **GIT_ENV_OVERRIDES},
+ )
+ except OSError as exc: # git missing, or not a repo we can exec in
+ return 1, f"{exc}"
+ if p.returncode != 0:
+ sys.stderr.write(p.stderr)
+ return p.returncode, p.stdout
+
+
+def scan_line(path: str, lineno: int, text: str, out: list[str]) -> None:
+ if PATTERNS.search(text):
+ detail = WARNING.format(path=path, line=lineno, text=text[:160])
+ out.append(f"::warning file={path}::{detail}")
+
+
+def added_lines(diff: str):
+ """Yield (path, lineno, text) for every ADDED line in a unified diff.
+
+ A line's meaning comes from HUNK STATE, not from its prefix: `+++ ` is a header only before the
+ first `@@` of a file, and inside a hunk it is content whose own text starts `++ `. That
+ distinction is the whole reason this is not a prefix match.
+ """
+ path = None
+ in_hunk = False
+ lineno = 0
+ for raw in diff.split("\n"):
+ if raw.startswith("diff --git "):
+ path, in_hunk = None, False
+ elif raw.startswith("@@"):
+ m = re.match(r"@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@", raw)
+ if not m:
+ in_hunk = False
+ continue
+ in_hunk = True
+ lineno = int(m.group(1)) - 1
+ elif not in_hunk:
+ if raw.startswith("+++ "):
+ p = raw[4:]
+ # `/dev/null` on the new side means the file was DELETED. Stated honestly: this arm
+ # is DEFENSIVE, not load-bearing — a deletion contributes no `+` lines, so nothing is
+ # yielded for it either way, and removing this arm reddens no test. It is kept because
+ # `path` should never name a file the added lines do not belong to. A
+ # `--diff-filter=d` on the git call was removed rather than kept beside it: a second
+ # mechanism nobody can witness failing is how a duplicate guard hides its twin.
+ path = None if p == "/dev/null" else (p[2:] if p.startswith("b/") else p)
+ elif raw.startswith("+"):
+ lineno += 1
+ if path is not None:
+ yield path, lineno, raw[1:]
+ elif raw.startswith("-") or raw.startswith("\\"):
+ pass # a removed line, or the no-trailing-newline marker: neither advances the new file
+ else:
+ lineno += 1 # context (absent at -U0, but harmless and correct if -U grows)
+
+
+def run_diff(base: str, out: list[str]) -> int:
+ rc, diff = git(
+ "diff",
+ "-U0",
+ # Pinned, not decorative: `diff.renames=false` in a developer's gitconfig turns a `git mv`
+ # into a whole-file add and re-flags every pre-existing line. Same channel as the prefixes.
+ "--find-renames",
+ # Pin the header shape the path is parsed out of. `diff.noprefix`, `diff.srcPrefix` and
+ # `diff.dstPrefix` each rewrite it from a developer's gitconfig, and `diff.external` replaces
+ # the output entirely — a configured prefix silently produced a scanned-0-files clean run.
+ "--src-prefix=a/",
+ "--dst-prefix=b/",
+ "--no-ext-diff",
+ "--no-color",
+ f"{base}...HEAD",
+ )
+ if rc != 0:
+ print(
+ f"doc-narrative: could not diff against '{base}' — SCANNED NOTHING. "
+ "This is reported rather than swallowed: a silent zero-file scan is indistinguishable "
+ "from a clean one, which is the failure `ci.required-job-step-execution-markers` exists for."
+ )
+ return -1
+ scanned = set()
+ for path, lineno, text in added_lines(diff):
+ if not is_scanned_path(path):
+ continue
+ scanned.add(path)
+ scan_line(path, lineno, text, out)
+ return len(scanned)
+
+
+def run_all(out: list[str]) -> int:
+ # Population from `git ls-files`, never a filesystem walk — an untracked scratch file is not
+ # part of the corpus (#778).
+ rc, listing = git("ls-files", "-z", "--", "*.md")
+ if rc != 0:
+ print("doc-narrative: could not list tracked files — SCANNED NOTHING.")
+ return -1
+ scanned = 0
+ for path in listing.split("\0"):
+ if not path or not is_scanned_path(path):
+ continue
+ try:
+ with open(path, encoding="utf-8", errors="replace") as fh:
+ text = fh.read()
+ except OSError as exc:
+ # A tracked-but-deleted doc is an ordinary working state, not a reason to fail.
+ print(f"doc-narrative: skipped {path} ({exc.strerror}).")
+ continue
+ scanned += 1
+ # splitlines() keeps a final unterminated line, which `read`-per-line dropped.
+ for i, line in enumerate(text.splitlines(), start=1):
+ scan_line(path, i, line, out)
+ return scanned
+
+
+def main(argv: list[str]) -> int:
+ mode = argv[1] if len(argv) > 1 else "--all"
+ out: list[str] = []
+
+ if mode == "--diff":
+ if len(argv) < 3 or not argv[2]:
+ print("doc-narrative: --diff needs a base ref — SCANNED NOTHING. (advisory; not a failure)")
+ return 0
+ scanned = run_diff(argv[2], out)
+ elif mode == "--all":
+ scanned = run_all(out)
+ else:
+ print(f"doc-narrative: unknown mode '{mode}'. usage: {argv[0]} [--all | --diff ]")
+ return 0
+
+ for line in out:
+ print(line)
+ if scanned < 0:
+ return 0
+ print(
+ f"doc-narrative: scanned {scanned} file(s); {len(out)} advisory warning(s). "
+ "NON-BLOCKING — this check never fails a run."
+ )
+ return 0
+
+
+if __name__ == "__main__":
+ try:
+ sys.exit(main(sys.argv))
+ except Exception as exc: # noqa: BLE001 — the never-fails constraint outranks a clean traceback
+ print(f"doc-narrative: internal error ({exc!r}) — SCANNED NOTHING. Advisory; not a failure.")
+ sys.exit(0)
diff --git a/scripts/tests/test_check_doc_narrative.py b/scripts/tests/test_check_doc_narrative.py
new file mode 100644
index 000000000..0650e0b67
--- /dev/null
+++ b/scripts/tests/test_check_doc_narrative.py
@@ -0,0 +1,360 @@
+"""Proofs for `scripts/check-doc-narrative.py` (ersatztv#784).
+
+Every case below is a defect a cold review DEMONSTRATED in the first, shell implementation. They are
+here because the never-fails invariant and the reported line numbers are both asserted in prose in
+four places (the script header, the workflow comment, `docs/guard-inventory.md` and
+`docs/remote-state-inventory.md`), and an invariant asserted only in prose is the shape this repo
+keeps getting wrong.
+
+The line-number cases all compare against the TRUTH computed from the file on disk, never against a
+number written into the test — a hand-written expectation is a second copy of the parser.
+"""
+
+from __future__ import annotations
+
+import re
+import subprocess
+import sys
+from pathlib import Path
+
+import pytest
+
+REPO = Path(__file__).resolve().parents[2]
+SCRIPT = REPO / "scripts" / "check-doc-narrative.py"
+
+NARRATIVE = "I initially thought otherwise"
+HIT = re.compile(r"^::warning file=(?P[^:]+)::(?P=path):(?P\d+) ", re.MULTILINE)
+
+
+def run(cwd: Path, *args: str) -> subprocess.CompletedProcess:
+ return subprocess.run(
+ [sys.executable, str(SCRIPT), *args], cwd=cwd, capture_output=True, text=True
+ )
+
+
+def hits(out: str) -> set[tuple[str, int]]:
+ return {(m.group("path"), int(m.group("line"))) for m in HIT.finditer(out)}
+
+
+def truth(root: Path, rel: str) -> set[tuple[str, int]]:
+ """Where the narrative marker ACTUALLY is, read back off disk."""
+ text = (root / rel).read_text(encoding="utf-8")
+ return {
+ (rel, i)
+ for i, line in enumerate(text.splitlines(), start=1)
+ if "initially thought" in line or "an earlier draft" in line.lower()
+ }
+
+
+def git(repo: Path, *args: str) -> None:
+ subprocess.run(["git", *args], cwd=repo, check=True, capture_output=True)
+
+
+@pytest.fixture()
+def repo(tmp_path: Path) -> Path:
+ r = tmp_path / "r"
+ (r / "docs").mkdir(parents=True)
+ git(r.parent, "init", "-q", "r")
+ git(r, "config", "user.email", "t@example.com")
+ git(r, "config", "user.name", "t")
+ (r / "docs" / "seed.md").write_text("seed\n", encoding="utf-8")
+ git(r, "add", "-A")
+ git(r, "commit", "-qm", "base")
+ return r
+
+
+def commit(r: Path, msg: str = "c") -> None:
+ git(r, "add", "-A")
+ git(r, "commit", "-qm", msg)
+
+
+# --- the never-fails invariant -------------------------------------------------------------------
+
+
+@pytest.mark.parametrize(
+ ("args", "expected"),
+ [
+ ((), "scanned "),
+ (("--all",), "scanned "),
+ (("--diff",), "--diff needs a base ref"), # no base ref at all
+ (("--diff", ""), "--diff needs a base ref"), # `origin/` with base_ref unset
+ (("--diff", "no-such-ref-xyz"), "SCANNED NOTHING"), # an unresolvable ref
+ (("--diff", "origin/"), "SCANNED NOTHING"),
+ (("--nonsense",), "unknown mode"),
+ ],
+)
+def test_every_argument_shape_exits_zero_HAVING_HANDLED_IT(repo: Path, args, expected: str) -> None:
+ """The header, the workflow comment and both inventories state exit 0 absolutely.
+
+ The expected message is asserted alongside the exit code on purpose: the script ends with a bare
+ `except` that returns 0, so an exit-code-only assertion is satisfied by an unhandled crash and
+ would pass against a script that handles none of these shapes.
+ """
+ p = run(repo, *args)
+ assert p.returncode == 0, f"args={args} exited {p.returncode}: {p.stderr}"
+ assert expected in p.stdout, f"args={args} exited 0 but did not HANDLE it: {p.stdout!r}"
+ assert "internal error" not in p.stdout, f"args={args} reached the last-resort handler: {p.stdout!r}"
+
+
+def test_an_unknown_mode_prints_usage_and_scans_nothing(repo: Path) -> None:
+ """Stated as the observable behaviour it actually pins. It is NOT a proof that the else-branch
+ cannot reach `run_all`: the branch returns before the warnings are printed, so a mutant calling
+ `run_all` there is silent and no black-box test can see it."""
+ (repo / "docs" / "u.md").write_text(f"x\n{NARRATIVE}\n", encoding="utf-8")
+ commit(repo)
+ p = run(repo, "--nonsense")
+ assert hits(p.stdout) == set()
+ assert "scanned" not in p.stdout
+
+
+def test_a_DELETED_doc_is_not_reported_as_added_content(repo: Path) -> None:
+ """A deletion contributes no added lines.
+
+ Stated exactly: this pins the BEHAVIOUR, and it is NOT a proof of the `+++ /dev/null` arm, which
+ is defensive — removing that arm reddens nothing, because a deletion yields no `+` lines either
+ way. The script comment says the same. A docstring claiming a proof it does not have is worse
+ than no docstring: it is the thing a later reader trusts instead of re-checking."""
+ (repo / "docs" / "del.md").write_text(f"x\n{NARRATIVE}\n", encoding="utf-8")
+ commit(repo)
+ (repo / "docs" / "del.md").unlink()
+ commit(repo)
+ assert hits(run(repo, "--diff", "HEAD~1").stdout) == set()
+
+
+# Every knob DEMONSTRATED to break the parse — not every knob that reshapes diff output, which is a
+# universal nobody can check and which is the enumeration that failed three rounds running.
+# (`diff.mnemonicPrefix` is a live example of one that reshapes the header and has no row: it emits
+# `+++ w/f.md`. It is inert HERE for a reason worth stating exactly, because the obvious explanation
+# is the wrong one — not because `--dst-prefix=b/` beats it, though it does, but because git only
+# uses mnemonic prefixes when a diff side is the worktree or the index, and `run_diff` issues the
+# three-dot `base...HEAD` form, where git emits plain `a/`…`b/` either way. Measured, not reasoned.)
+# Three of these were each demonstrated turning
+# a real hit into `scanned 0 file(s)`, one at a time, in three separate rounds — which is why the fix
+# stopped pinning variants and removed the surface. The table is here so the next knob someone finds
+# gets a row instead of a round.
+FORMAT_KNOBS = [
+ ("core.quotePath", "true"), # quotes non-ASCII paths out of the population
+ ("diff.dstPrefix", "dst/"), # rewrites the header the path is read from
+ ("diff.srcPrefix", "src/"),
+ ("diff.noprefix", "true"),
+ ("color.diff", "always"), # injects ANSI escapes into every line
+ ("color.ui", "always"),
+ ("diff.renames", "false"), # turns a `git mv` into a whole-file add
+ ("diff.context", "9"), # a configured context must not beat the -U0 on the CLI
+ ("diff.external", "/bin/echo"), # replaces the output wholesale
+]
+
+
+@pytest.mark.parametrize(("key", "value"), FORMAT_KNOBS)
+def test_no_git_FORMAT_CONFIG_can_produce_a_false_clean(repo: Path, key: str, value: str) -> None:
+ """A false clean is the worst outcome available to an advisory check: it is indistinguishable
+ from a real one and nobody looks twice."""
+ (repo / "docs" / "pfx.md").write_text("x\n", encoding="utf-8")
+ commit(repo)
+ (repo / "docs" / "pfx.md").write_text(f"x\n{NARRATIVE}\n", encoding="utf-8")
+ commit(repo)
+ git(repo, "config", key, value)
+ assert hits(run(repo, "--diff", "HEAD~1").stdout) == truth(repo, "docs/pfx.md"), f"{key}={value}"
+
+
+# Only PYTHONIOENCODING is listed. `LC_ALL=C` was here too and was VACUOUS — PEP 540 UTF-8 mode
+# means the pre-fix script passed it as well, so it read as a second witness where there was one.
+@pytest.mark.parametrize("env_name,env_value", [("PYTHONIOENCODING", "ascii")])
+def test_a_NON_UTF8_stdio_does_not_break_the_never_fails_invariant(repo: Path, env_name, env_value) -> None:
+ """Both the summary line and the last-resort handler carry U+2014, so under ascii stdio the code
+ guaranteeing exit 0 was itself what raised."""
+ import os
+
+ env = dict(os.environ, **{env_name: env_value})
+ env.pop("PYTHONUTF8", None)
+ p = subprocess.run(
+ [sys.executable, str(SCRIPT), "--all"], cwd=repo, capture_output=True, text=True, env=env
+ )
+ assert p.returncode == 0, f"{env_name}={env_value} exited {p.returncode}: {p.stderr}"
+
+
+def test_a_tracked_but_DELETED_doc_does_not_kill_the_run(repo: Path) -> None:
+ """`git ls-files` lists index entries; deleting a doc before committing is ordinary."""
+ (repo / "docs" / "gone.md").write_text("x\n", encoding="utf-8")
+ commit(repo)
+ (repo / "docs" / "gone.md").unlink()
+ p = run(repo, "--all")
+ assert p.returncode == 0
+ assert "skipped docs/gone.md" in p.stdout
+
+
+def test_an_unresolvable_base_REPORTS_that_it_scanned_nothing(repo: Path) -> None:
+ """A silent zero-file scan is indistinguishable from a clean one — the whole point of #751."""
+ p = run(repo, "--diff", "no-such-ref-xyz")
+ assert p.returncode == 0
+ assert "SCANNED NOTHING" in p.stdout
+ # The guard names the line this branch must NOT also print. It previously named "nothing to
+ # flag", a string that occurs nowhere in this script (it belongs to the sibling parity step), so
+ # it could never fail — a negative assertion over a literal that does not exist is not a guard.
+ assert "scanned 0 file(s)" not in p.stdout, "printed a clean-looking summary after scanning nothing"
+
+
+def test_a_genuine_clean_scan_REPORTS_its_population(repo: Path) -> None:
+ p = run(repo, "--all")
+ assert "scanned 1 file(s); 0 advisory warning(s)" in p.stdout
+
+
+# --- line numbers, against truth read off disk ---------------------------------------------------
+
+
+def test_a_file_with_NO_trailing_newline_does_not_shift_later_lines(repo: Path) -> None:
+ """`\\ No newline at end of file` is a marker, not a line of the new file."""
+ (repo / "docs" / "n.md").write_text("a\nb\nc", encoding="utf-8") # no trailing newline
+ commit(repo)
+ (repo / "docs" / "n.md").write_text(f"a\nb\nZ\n{NARRATIVE}\n", encoding="utf-8")
+ commit(repo)
+ assert hits(run(repo, "--diff", "HEAD~1").stdout) == truth(repo, "docs/n.md")
+
+
+def test_an_added_line_whose_TEXT_starts_with_plus_plus_is_content_not_a_header(repo: Path) -> None:
+ """Docs here embed diff output in fenced blocks, so `++ ` at column 0 is real."""
+ (repo / "docs" / "p.md").write_text("p\n", encoding="utf-8")
+ commit(repo)
+ (repo / "docs" / "p.md").write_text(f"p\n++ a fenced diff line\n{NARRATIVE}\n", encoding="utf-8")
+ commit(repo)
+ assert hits(run(repo, "--diff", "HEAD~1").stdout) == truth(repo, "docs/p.md")
+
+
+def test_a_multi_hunk_file_numbers_every_hunk_from_its_own_header(repo: Path) -> None:
+ body = [f"l{i}" for i in range(1, 31)]
+ (repo / "docs" / "m.md").write_text("\n".join(body) + "\n", encoding="utf-8")
+ commit(repo)
+ body[4] = NARRATIVE # replace, early hunk
+ body.insert(15, NARRATIVE) # pure insert, middle hunk
+ body[-1] = NARRATIVE # replace, last hunk
+ (repo / "docs" / "m.md").write_text("\n".join(body) + "\n", encoding="utf-8")
+ commit(repo)
+ assert hits(run(repo, "--diff", "HEAD~1").stdout) == truth(repo, "docs/m.md")
+
+
+def test_a_NON_ASCII_path_is_scanned_rather_than_silently_skipped(repo: Path) -> None:
+ """`core.quotePath` quotes the path, and a quoted path matches no scope rule — it vanishes."""
+ (repo / "docs" / "café.md").write_text(f"x\n{NARRATIVE}\n", encoding="utf-8")
+ commit(repo)
+ assert hits(run(repo, "--all").stdout) == truth(repo, "docs/café.md")
+ assert hits(run(repo, "--diff", "HEAD~1").stdout) == truth(repo, "docs/café.md")
+
+
+def test_a_final_UNTERMINATED_line_is_still_scanned_in_all_mode(repo: Path) -> None:
+ (repo / "docs" / "t.md").write_text(f"ok\n{NARRATIVE}", encoding="utf-8") # no trailing newline
+ commit(repo)
+ assert hits(run(repo, "--all").stdout) == truth(repo, "docs/t.md")
+
+
+def test_a_RENAME_does_not_re_flag_the_whole_pre_existing_file(repo: Path) -> None:
+ """Without rename detection a `git mv` reports every line of the file as newly added."""
+ (repo / "docs" / "r1.md").write_text("a\n" + f"{NARRATIVE}\n" + "b\n", encoding="utf-8")
+ commit(repo)
+ git(repo, "mv", "docs/r1.md", "docs/r2.md")
+ commit(repo)
+ assert hits(run(repo, "--diff", "HEAD~1").stdout) == set()
+
+ # `diff.renames` defaults to true, so the assertion above passes with or without the explicit
+ # `--find-renames`. Turning the config off is what makes that flag load-bearing and this test a
+ # real proof of it rather than a restatement of a git default.
+ git(repo, "config", "diff.renames", "false")
+ assert hits(run(repo, "--diff", "HEAD~1").stdout) == set(), "the --find-renames pin is not doing its job"
+
+
+# --- the population ------------------------------------------------------------------------------
+
+
+@pytest.mark.parametrize("mode", ["--all", "--diff"])
+def test_decision_records_are_exempt_in_BOTH_modes(repo: Path, mode: str) -> None:
+ for rel in ("docs/decisions/records/x/y.md", "docs/decisions/archive/x/y.md"):
+ p = repo / rel
+ p.parent.mkdir(parents=True, exist_ok=True)
+ p.write_text(f"x\n{NARRATIVE}\n", encoding="utf-8")
+ commit(repo)
+ out = run(repo, mode, "HEAD~1").stdout if mode == "--diff" else run(repo, mode).stdout
+ assert hits(out) == set()
+
+
+def test_markdown_outside_the_stated_population_is_not_scanned(repo: Path) -> None:
+ """The population is `docs/**/*.md` minus `docs/decisions/**`, plus root-level `*.md`. A skill
+ under `.claude/` is out of scope, and the record's `mechanics:` says so."""
+ (repo / ".claude" / "skills" / "s").mkdir(parents=True)
+ (repo / ".claude" / "skills" / "s" / "SKILL.md").write_text(f"{NARRATIVE}\n", encoding="utf-8")
+ (repo / "README.md").write_text(f"{NARRATIVE}\n", encoding="utf-8")
+ commit(repo)
+ assert hits(run(repo, "--all").stdout) == {("README.md", 1)}
+
+
+# --- the detector actually detects ---------------------------------------------------------------
+
+
+def test_a_MULTI_FILE_diff_scans_every_file_not_just_the_first(repo: Path) -> None:
+ """Every real CI run is multi-file. Without the `in_hunk` reset on `diff --git`, the parser stays
+ inside the previous file's hunk and silently drops every file after the first."""
+ for name in ("a", "b", "c"):
+ (repo / "docs" / f"{name}.md").write_text("x\n", encoding="utf-8")
+ commit(repo)
+ for name in ("a", "b", "c"):
+ (repo / "docs" / f"{name}.md").write_text(f"x\n{NARRATIVE}\n", encoding="utf-8")
+ commit(repo)
+ p = run(repo, "--diff", "HEAD~1")
+ assert hits(p.stdout) == {(f"docs/{n}.md", 2) for n in ("a", "b", "c")}
+ assert "scanned 3 file(s); 3 advisory warning(s)" in p.stdout
+
+
+def test_the_reported_POPULATION_COUNT_matches_the_files_actually_scanned(repo: Path) -> None:
+ """The count is the observable that made every false clean in this file's history visible. A
+ mutant that never populated the scanned set reported `scanned 0 file(s); 3 warning(s)` — green,
+ and self-contradictory."""
+ (repo / "docs" / "one.md").write_text("x\n", encoding="utf-8")
+ (repo / "docs" / "two.md").write_text("x\n", encoding="utf-8")
+ commit(repo)
+ (repo / "docs" / "one.md").write_text(f"x\n{NARRATIVE}\n", encoding="utf-8")
+ (repo / "docs" / "two.md").write_text("x\nharmless\n", encoding="utf-8")
+ commit(repo)
+ assert "scanned 2 file(s); 1 advisory warning(s)" in run(repo, "--diff", "HEAD~1").stdout
+
+
+def test_a_NON_UTF8_LOCALE_does_not_silently_empty_the_scan(repo: Path) -> None:
+ """`subprocess.run(errors="replace")` is the other half of the locale channel: without it a
+ UTF-8 doc under an ascii locale raises inside `git()`, the bare `except` catches it, and the
+ whole scan degrades to nothing while still exiting 0."""
+ import os
+
+ (repo / "docs" / "u8.md").write_text(f"héllo — em dash\n{NARRATIVE}\n", encoding="utf-8")
+ commit(repo)
+ env = dict(os.environ, LC_ALL="C", PYTHONUTF8="0", PYTHONIOENCODING="utf-8")
+ p = subprocess.run(
+ [sys.executable, str(SCRIPT), "--diff", "HEAD~1"],
+ cwd=repo, capture_output=True, text=True, env=env,
+ )
+ assert p.returncode == 0, p.stderr
+ assert "internal error" not in p.stdout, p.stdout
+ assert hits(p.stdout) == {("docs/u8.md", 2)}
+
+
+def test_the_pattern_is_case_insensitive(repo: Path) -> None:
+ (repo / "docs" / "case.md").write_text("AN EARLIER DRAFT of this said otherwise\n", encoding="utf-8")
+ commit(repo)
+ assert hits(run(repo, "--all").stdout) == {("docs/case.md", 1)}
+
+
+def test_MUTATION_neutering_the_pattern_makes_a_known_hit_go_quiet(repo: Path, tmp_path: Path) -> None:
+ """The clause-level disarm: with PATTERNS unable to match, a file that IS flagged stops being
+ flagged. Without this, every assertion above is satisfied by a detector that finds nothing."""
+ (repo / "docs" / "d.md").write_text(f"x\n{NARRATIVE}\n", encoding="utf-8")
+ commit(repo)
+ assert hits(run(repo, "--all").stdout) == truth(repo, "docs/d.md")
+
+ disarmed = tmp_path / "disarmed.py"
+ src = SCRIPT.read_text(encoding="utf-8")
+ marker = 'PATTERNS = re.compile('
+ assert src.count(marker) == 1
+ disarmed.write_text(
+ src.replace(marker, 'PATTERNS = re.compile(r"(?!x)x" # disarmed\n or ', 1), encoding="utf-8"
+ )
+ p = subprocess.run(
+ [sys.executable, str(disarmed), "--all"], cwd=repo, capture_output=True, text=True
+ )
+ assert p.returncode == 0, p.stderr
+ assert hits(p.stdout) == set(), "the disarmed detector still flagged something — the mutation did not take"