Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.
Python agentic-aiai-securityalert-triageblue-teamcybersecuritydetection-engineeringincident-responselanggraphllm-agentsmcpmitre-attackmodel-context-protocolpurple-teamsecurity-operationsself-hostedsiemsoarsocthreat-detectionthreat-intelligence
docs(audit): the seventh lettered deferral nobody was tracking (#989)
Beenu Arorad7c1cf82ebb7
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex a6ae869c6..96b9c3479 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -1104,6 +1104,29 @@ jobs:# indistinguishable from a leak.run: python3 scripts/check_triage_context_freeze.py+ - name: Every lettered deferral has its scope in the committed tracker+ # Six sub-phases were "tracked in docs/audit/PROGRESS.md", which is+ # gitignored and was never committed, so six named commitments had+ # their scope recorded only by a filename pointing at nothing.+ # docs/audit/DEFERRED_SUBPHASES.md replaced it — and the audit that+ # wrote it read ROADMAP.md and stopped there, so two more deferrals+ # named elsewhere stayed invisible: 6b in an ADR and 8b in a module+ # docstring, both still pointing at the file that does not exist.+ #+ # The set of deferrals can therefore not live in a reader's memory.+ # This derives it from the whole tracked tree, in both directions — a+ # deferral named anywhere with no section, and a section for one+ # nothing references — and fails any tracked file still sending a+ # reader to the tracker that was never committed.+ #+ # Self-test first, and deliberately: it injects the ADR shape, the+ # docstring shape and a bare phase reference into scratch trees, so a+ # matcher that has quietly stopped matching cannot report the+ # repository clean.+ run: |+ python3 scripts/check_deferral_tracker.py --self-test+ python3 scripts/check_deferral_tracker.py+- name: Every check in the tree is reachable from a workflow# The gate on the gates. A conformance script with no workflow cannot# fail, which is indistinguishable from no gate at all — while itsdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 929fa5703..c2869e985 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -168,6 +168,23 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0failed at `mint_ws_ticket`. It was green on `main` only because the job ispath-filtered and had not run on a triggering commit since that release.+- **Two lettered deferrals were on no list of the lettered deferrals.**+ `docs/audit/DEFERRED_SUBPHASES.md` exists because six commitments had their+ scope recorded only by a filename pointing at a gitignored file — and the+ audit that wrote it read `ROADMAP.md` and stopped there. `6b` (wire the+ storage cost model into the sizing guide and the LLM-cost dashboard) was in+ `docs/decisions/0005-storage-consolidation.md` and `8b` (migrate the inline+ agent prompts onto the registry) in `services/agents/app/llm/prompt_registry.py`,+ both still pointing at the tracker that was never committed. Both are open,+ both now have a section, and both pointers now resolve. `11b` closed+ (`scripts/check_sdk_surface.py`), and re-verifying the rest against the tree+ corrected two statuses: `9b`'s durable approval-timer table landed in+ `062_approval_timers.sql`, leaving only console-raised approvals with+ nothing to expire them, and `10b`'s checkpoint durability landed with one+ adopter of 84 connectors. New `scripts/check_deferral_tracker.py` derives+ the set of deferrals from the tracked tree in both directions, so a ninth+ cannot go unrecorded.+## [12.0.0] - 2026-09-27### BREAKINGdiff --git a/docs/audit/DEFERRED_SUBPHASES.md b/docs/audit/DEFERRED_SUBPHASES.mdindex f631e54d1..80f6df345 100644--- a/docs/audit/DEFERRED_SUBPHASES.md+++ b/docs/audit/DEFERRED_SUBPHASES.md@@ -1,26 +1,38 @@# The lettered deferrals-**Last updated:** 2026-09-23 (v9.0)+**Last updated:** 2026-09-28 (v12.0.0)-Six sub-phases of the hardening program were deferred with a letter suffix —-3.5+, 5b, 7b+, 9b, 10b, 11b — and `ROADMAP.md` says each is "tracked in-`docs/audit/PROGRESS.md`".+Eight sub-phases of the hardening program were deferred with a letter suffix+— 3.5+, 5b, 6b, 7b+, 8b, 9b, 10b, 11b. Six of them were named in `ROADMAP.md`,+which said each was "tracked in `docs/audit/PROGRESS.md`".That file is in `.gitignore`. It was never committed, the local copy is gone,-and so **the only record of what these six commitments contain was a filename-pointing at nothing.** Six named pieces of work with no scope anywhere a-contributor could read.--This file replaces it, and is committed. A tracker that is not in the-repository is a tracker that does not exist — the same lesson-`docs/roadmap/v8-progress.md` already carries about staleness, one step-further along.--The scope below is **re-derived from the phase lines in `ROADMAP.md` and from-the tree**, not recovered. Where the original intent is genuinely unknowable-that is said rather than guessed at, because inventing a commitment and-attributing it to a previous decision is worse than admitting the record was-lost.+and so **the only record of what those six commitments contained was a+filename pointing at nothing.** Six named pieces of work with no scope+anywhere a contributor could read.++This file replaced it, and is committed; `ROADMAP.md` has since been+corrected to point here, and the sentence it used to carry survives only as+the history above. A tracker that is not in the repository is a tracker that+does not exist — the same lesson `docs/roadmap/v8-progress.md` already+carries about staleness, one step further along.++**The other two were found later, and how they were missed is the point.**+The audit that wrote this file read `ROADMAP.md` and stopped there, so a+deferral written down anywhere else was invisible to it by construction. `6b`+was in an ADR and `8b` in a module docstring, both still pointing at the+tracker that was never committed, and neither appeared in any list of these.+`scripts/check_deferral_tracker.py` now derives the set from the whole+tracked tree rather than from a reader's memory: it fails when a deferral is+named anywhere and has no section here, when a section here is for a deferral+nothing references, and when any tracked file still sends a reader to the+file that does not exist.++The scope below is **re-derived from the phase lines in `ROADMAP.md`, from+the two documents that named 6b and 8b, and from the tree** — not recovered.+Where the original intent is genuinely unknowable that is said rather than+guessed at, because inventing a commitment and attributing it to a previous+decision is worse than admitting the record was lost.---@@ -55,6 +67,34 @@ backlog and nothing consumes it.---+## 6b — the storage cost model next to the LLM cost++**From the ADR:** *"Follow-up (Phase 6b). Wire the model into the+managed-mode sizing guide and the LLM-cost dashboard so a tenant's storage+$/mo shows next to its LLM $/mo"* —+[`docs/decisions/0005-storage-consolidation.md`](../decisions/0005-storage-consolidation.md).++**Status: open, and it was on no list of these until now.** Phase 6 shipped+the model and its drift gate, and both are real: `scripts/storage_cost_model.py`+computes ≈$902/mo and ≈$30/raw-TB at 1 TB/day, `docs/decisions/storage-cost-model.json`+is the committed worked example, and `.github/workflows/perf.yml` fails when+the two diverge.++Neither half of the follow-up exists. `services/api/app/services/cost_dashboard.py`+and `apps/web/src/app/(admin)/costs/page.tsx` mention storage nowhere — the+dashboard reports LLM spend only — and the "Billing and cost transparency"+section of `apps/docs/docs/operations/managed-instance.md` points at that LLM+dashboard and says nothing about storage. Outside the ADR, the CHANGELOG and+the perf workflow, the model's only readers are two ClickHouse tiering files+citing it in a comment.++**Why it is worth doing:** the ADR's stated reason for computing the number+at all was sizing and the managed-mode pricing shape (ADR-0003). A cost model+whose only consumer is the gate that checks the cost model is a well-tested+constant.++---+## 7b+ — posture collection and the fusion-time context bundle**From the phase line:** *"7b+ (posture collection, effective-permissions@@ -71,24 +111,67 @@ So what remains of 7b is one thing: a connector-side posture snapshot.---+## 8b — the inline prompts the registry was built for++**From the module docstring:** *"Migration of the existing inline prompts is+tracked as 8b; this seeds the registry + gate with the canonical+triage/summary prompts"* — `services/agents/app/llm/prompt_registry.py`.++**Status: open, and the gap is countable.** Phase 8 shipped the registry, the+committed `prompts.lock.json` and `scripts/check_prompt_lock.py --check`,+which fails when a prompt's text changes without a version bump. That is the+mechanism making the `AGENTS.md` rule — a prompt change obliges an eval+re-grade — enforceable rather than aspirational.++It is enforceable over three prompts. One production module reads the+registry: `services/agents/app/hunt/agent.py` takes `hunt.system`.+`triage.system` and `summary.system` are registered, hash-pinned and gated,+and nothing under `services/agents/app/` asks for either — while ten modules+there still declare a module-level `_SYSTEM_PROMPT` of their own, the triage,+cloud, identity, insider-threat and phishing agents and the recon, forensic,+responder, report-writer and playbook-drafter among them.++**Why it is worth doing:** every prompt still inline can be edited without a+version bump, without a lock change, and therefore without the re-grade —+which is the exact hole the registry was written to close, left open for all+but one of them.++---+## 9b — live-router wiring and the durable approval-SLA timer**From the phase line:** *"live-router wiring + durable approval-SLA timertable tracked as 9b"*.-**Status: substantially closed in v9.0, and the rest is named.**+**Status: substantially closed, and what is left is narrower than this+section used to say.**The live-router half is done: `services/api/app/api/v1/endpoints/approvals.py`now carries a decision through to `services/actions` and records on the rowwhether it executed, and `POST /actions` consults the confidence × impact-matrix rather than blast radius alone.--Durable storage arrived with `055_action_records.sql`. What is still missing-is the **timer**: nothing expires an approval that nobody answers, so a-pending containment waits forever rather than escalating or timing out to its-declared safe default. The Slack bot has an in-process-`ApprovalTimeoutScheduler`; it does not survive a restart, which is the same-class of defect the action store had.+matrix rather than blast radius alone. Durable storage arrived with+`055_action_records.sql`.++**The timer table landed too, and this section was wrong about it.** It+recorded the Slack bot's `ApprovalTimeoutScheduler` as in-process only. A+Postgres-backed store had in fact existed since Phase B3+(`services/slack-bot/app/services/timer_store.py`) — and it genuinely was not+durable, for a reason worth keeping: it created `approval_timers` itself with+`CREATE TABLE IF NOT EXISTS`, outside every migration chain, so once+`061_runtime_app_role.sql` took `CREATE` on schema public away from the+runtime role that call raised at startup and `main.py` fell back to the+in-memory store. Durable approval timers silently stopped being durable.+`062_approval_timers.sql` brought the table into the chain with a `tenant_id`+and an RLS policy; the store now refuses to create it and names the migration+instead, and `recover()` re-arms surviving timers on start.++**What remains is every approval the bot never sees.** The expiry lives in+`services/slack-bot`, a `chatops`-profile service, and is armed per ChatOps+approval. The API's own `agent_approvals` row carries an `expires_at` and its+status vocabulary includes `expired`; nothing writes that status, and no+worker under `services/api/app/workers/` sweeps the column. An approval+raised in the console and never answered still waits forever rather than+timing out to its declared safe default.---@@ -97,36 +180,58 @@ class of defect the action store had.**From the phase line:** *"Live-vendor sandbox smoke + rate-limit/checkpointdurability tracked as 10b"*.-**Status: open, and one half is credential-blocked.**+**Status: one half is credential-blocked; the other has a mechanism and one+adopter.**Live-vendor smoke needs sandbox accounts with real vendors — an accountaction, the same class of blocker as the npm publish and the funded eval key,-not an engineering task.--Checkpoint durability is not blocked and is worth doing: connector poll state-is module-scoped and keyed by base URL plus saved search, so it does not-survive a restart. A connector that restarts re-reads its overlap window,-which is safe but means a long outage silently loses events older than the-window.+not an engineering task. It stays open and says so.++**Checkpoint durability is no longer absent, which this section used to say+it was.** `services/connectors/app/db/connector_repo.py::record_checkpoint`+persists a connector's ingest checkpoint into `connector_config.checkpoint`,+and `services/connectors/app/scheduler.py` seeds it back into the connector+before each poll and writes the advanced value only after the batch was+accepted, so a failed ingest never moves it forward.++What is missing is adoption. `splunk` is the only one of the 84 connectors+implementing `set_checkpoint`/`get_checkpoint`; the scheduler seeds through a+`getattr(connector, "set_checkpoint", None)` that is simply absent on the+other 83. For those, poll state still does not survive a restart — the+connector re-reads its overlap window, which is safe, and means a long outage+silently loses events older than that window.---## 11b — per-language generated-client contract drift**From the phase line:** *"per-language SDK generated-client contract-drift-tracked as 11b"*, and it is one of the nine `PARTIAL` rows in-`CLAIM_TO_GATE_MATRIX.md`.--**Status: open.** `openapi-breaking.yml` catches a spec change that would-break a generated client. What it does not catch is the *hand-written* client-drifting from the spec — which is exactly what v9.0 found in `packages/sdk-ts`:-`approvals`, `push`, `onCall` and `passkeys` were all in `docs/openapi.yaml`-and none had a namespace, so the generated types were complete and the-ergonomic surface was three releases behind.--**The gate that closes this** is therefore not "does the spec still generate"-but "does every path in the spec have a client surface, or an explicit-exemption". That is the shape to build.+tracked as 11b"*.++**Status: closed by `scripts/check_sdk_surface.py`.** `openapi-breaking.yml`+catches a spec change that would break a generated client. What it did not+catch was the *hand-written* client drifting from the spec — which is exactly+what v9.0 found in `packages/sdk-ts`: `approvals`, `push`, `onCall` and+`passkeys` were all in `docs/openapi.yaml` and none had a namespace, so the+generated types were complete and the ergonomic surface was three releases+behind.++The gate this section called "the shape to build" — not "does the spec still+generate" but "does every path in the spec have a client surface, or an+explicit exemption" — is what landed. It reads the request sites out of both+hand-written clients and fails when one calls an operation+`docs/openapi.yaml` does not declare; it holds all three languages to the+namespace manifest at `packages/sdk-surface.json` in both directions, so a+recorded gap that has since been filled fails as stale rather than becoming a+permanent licence; and it fails a `package.json` declaring a codegen output+that is not on disk. Writing it found four operations both clients called+that the API does not serve, two of them with a passing test pinning them.++**What it does not prove.** That an operation *exists* — not that the+response matches it. `packages/sdk-ts/src/types.ts` and the Python client's+models are still hand-kept, so a field renamed or retyped in a response+schema breaks both clients with every SDK job green. That is the next gate,+not this one.---diff --git a/docs/decisions/0005-storage-consolidation.md b/docs/decisions/0005-storage-consolidation.mdindex b9fda9cec..cb2afa0b6 100644--- a/docs/decisions/0005-storage-consolidation.md+++ b/docs/decisions/0005-storage-consolidation.md@@ -3,7 +3,7 @@- **Status:** accepted- **Date:** 2026-07-12- **Decision-makers:** AiSOC core team-- **Plan reference:** World-Class Hardening Program, Phase 6 (performance + cost) — [`ROADMAP.md`](../../ROADMAP.md), [`docs/audit/PROGRESS.md`](../audit/PROGRESS.md).+- **Plan reference:** World-Class Hardening Program, Phase 6 (performance + cost) — [`ROADMAP.md`](../../ROADMAP.md), [`docs/audit/DEFERRED_SUBPHASES.md`](../audit/DEFERRED_SUBPHASES.md).## Context@@ -71,9 +71,12 @@ below can therefore never silently drift.- **Negative.** Object-tier reads (warm/cold) are slower than ClickHouse; aninvestigation reaching past 30 days pays a latency cost. Accepted: >30-daylookbacks are rare and the cost saving is large (block is ~3.5× object).-- **Follow-up (Phase 6b, tracked in `docs/audit/PROGRESS.md`).** Wire the model- into the managed-mode sizing guide and the LLM-cost dashboard so a tenant's- storage $/mo shows next to its LLM $/mo.+- **Follow-up (Phase 6b, tracked in+ [`docs/audit/DEFERRED_SUBPHASES.md`](../audit/DEFERRED_SUBPHASES.md)).** Wire+ the model into the managed-mode sizing guide and the LLM-cost dashboard so a+ tenant's storage $/mo shows next to its LLM $/mo. Still open: the dashboard+ reports LLM spend only, and the managed-instance billing section does not+ mention storage.## Performance gatediff --git a/scripts/check_deferral_tracker.py b/scripts/check_deferral_tracker.pynew file mode 100644index 000000000..3162a0d02--- /dev/null+++ b/scripts/check_deferral_tracker.py@@ -0,0 +1,571 @@+#!/usr/bin/env python3+"""A named deferral must have its scope in the tracker, and the tracker must+not hold scope for a deferral nothing names.++Why this exists+---------------+Six sub-phases of the hardening program were deferred with a letter suffix —+3.5+, 5b, 7b+, 9b, 10b, 11b — and ``ROADMAP.md`` said each was "tracked in+``docs/audit/PROGRESS.md``". That file is in ``.gitignore``. It was never+committed, so six named commitments had their scope recorded only by a+filename pointing at nothing. ``docs/audit/DEFERRED_SUBPHASES.md`` was+written to replace it, and is committed.++Writing that replacement was itself an audit, and the audit read+``ROADMAP.md`` and stopped there. Two more lettered deferrals were named+elsewhere in the tree and appeared in no list of them:++``6b``+ ``docs/decisions/0005-storage-consolidation.md`` — "Follow-up (Phase 6b,+ tracked in ``docs/audit/PROGRESS.md``). Wire the model into the+ managed-mode sizing guide and the LLM-cost dashboard". The same dangling+ pointer, in a document nobody re-read when the pointer was corrected.++``8b``+ ``services/agents/app/llm/prompt_registry.py`` — "Migration of the+ existing inline prompts is tracked as 8b". One module reads the registry;+ seventeen still declare their prompts inline.++Neither was recoverable by looking harder at the roadmap, because neither was+in it. The failure is structural: the set of deferrals lived in a reader's+head, so a deferral written down anywhere else was invisible by construction.+That is what this derives instead.++What it checks, in both directions+----------------------------------++``untracked-deferral``+ A lettered sub-phase named in deferral language anywhere in the tracked+ tree, with no section in the tracker and no record that it landed. This+ is the direction that produced 6b and 8b.++``unreferenced-section``+ The same question asked backwards. A tracker section for a sub-phase+ nothing else mentions is a commitment that has been renamed, absorbed or+ quietly dropped, and a tracker carrying scope for work nobody refers to+ decays into the thing it replaced. A gate that only looks one way passes+ while drift accumulates in the other.++``dangling-tracker-pointer``+ A tracked file still sending a reader to ``docs/audit/PROGRESS.md`` for+ the scope of something. Prose describing it as the gitignored file it was+ is fine and must stay fine — the tracker's own preamble and ``ROADMAP.md``+ both explain the history — so a mention within three lines of a phrase+ placing it in the past is not a finding.++``stale-landed-record`` / ``stale-exclusion``+ The recorded lists below, read back. All are shrink-only and checked in+ both directions: an entry naming a sub-phase nothing mentions is stale,+ an entry for one the tracker has since given a section to is a+ contradiction, and an excluded path matching no tracked file is excusing+ a surface that is no longer there. Every exclusion is printed on every+ run, clean or not. Without both, an exemption list becomes the place a+ real orphan goes to hide.++What it reads+-------------+Every tracked text file, from ``git ls-files`` — the defect was a deferral+written in a source docstring and in an ADR, so restricting the corpus to the+roadmap would rebuild the blind spot this exists to remove. Four historical+surfaces are excluded by prefix and each says why, as are this gate and its+tests, which quote every shape they detect.++Two strictnesses, deliberately, because the two directions fail differently.+Deciding something *is* an untracked deferral fails a build on a heuristic,+so it takes explicit deferral language: ``tracked as 5b``, ``Follow-up (Phase+6b``, or a bare ``Phase 6b``. Deciding a tracker section *is* referenced only+credits a section that already exists, so it takes any occurrence of the+identifier on a line that also talks about phases, deferrals or tracking —+which is what finds ``7b+``, whose only live mention reads "7b+ (…) scoped+in". Both print what they matched, so a credit nobody would accept is visible+by reading rather than by trusting the exit code.++Identifiers match a lowercase letter only. The hardening program writes its+deferrals lowercase throughout (``5b``, ``7b+``); ``Phase 1A``, ``Phase 2C``+and ``Phase 4B`` belong to a different, completed plan, and folding the two+vocabularies together would make this gate demand tracker sections for+another plan's finished work.++Usage+-----++::++ python3 scripts/check_deferral_tracker.py # gate+ python3 scripts/check_deferral_tracker.py --list # every mention found+ python3 scripts/check_deferral_tracker.py --json+ python3 scripts/check_deferral_tracker.py --self-test++Exit codes: 0 clean, 1 findings, 2 the scan itself could not run.++Note that the corpus comes from ``git ls-files``, which does not list+untracked files. Run this with your changes staged.+"""++from __future__ import annotations++import argparse+import contextlib+import io+import json+import re+import subprocess+import sys+import tempfile+from pathlib import Path++# `scripts/` is on sys.path when this file is run as a program, but not when a+# test loads it by path with importlib. gate_toolkit sits beside it either way.+sys.path.insert(0, str(Path(__file__).resolve().parent))++from gate_toolkit import repo_root, self_test_main # noqa: E402++#: The committed tracker. Every open lettered deferral's scope lives here.+TRACKER = "docs/audit/DEFERRED_SUBPHASES.md"++#: The tracker that was never committed. A reader sent here finds nothing.+DEAD_TRACKER = "docs/audit/PROGRESS.md"++# --------------------------------------------------------------------------+# Recorded exceptions. Shrink-only, and checked in both directions: an entry+# that stops describing the tree fails the build rather than sitting here.+# --------------------------------------------------------------------------++#: Lettered sub-phases that shipped, so a mention of one is a reference to+#: finished work rather than an open commitment with nowhere to record it.+#: Each says where that can be confirmed, because a bare list of identifiers+#: is a second place for drift to hide.+LANDED_SUBPHASES: dict[str, str] = {+ "4a": "shipped — ROADMAP.md Phase 4 records '4a/4b/4c landed'; 4a is the de-circularised DAC candidate-rule gate",+ "4b": "shipped — ROADMAP.md Phase 4; the executable-vs-imported detection truth table",+ "4c": "shipped — ROADMAP.md Phase 4; what remains of Phase 4 is a funded provider key, an account action rather than a sub-phase",+ "9a": "shipped — ROADMAP.md Phase 9, the autonomy-safety policy layer; its wiring is 9b, which the tracker holds",+}++#: Surfaces excluded from the scan, with the reason. All four record what was+#: true when they were written; editing one so it names today's paths would+#: make it claim a history it does not have.+HISTORICAL: dict[str, str] = {+ "CHANGELOG.md": "append-only release history — an entry describes the tree at that release",+ "RELEASES.md": "published release notes, same reason",+ "docs/community-feedback/": "dated snapshots of feedback, kept as received",+ "plans/": "plan documents are kept as written; the tree records what was built from them",+}++#: This gate and its tests quote the two orphans and the dangling pointer they+#: exist to catch. Scanning them would make it flag itself, which is the same+#: exclusion ``check_attribution.py`` keeps for the same reason.+#:+#: Unlike ``HISTORICAL`` these are *not* checked for staleness. The gate is+#: routinely run as a copy of ``scripts/`` in a tree that has no tests — the+#: empty-tree probe and the pre-fix proof both do exactly that — and an+#: absent test file there is the normal case, not drift. It also fails in the+#: safe direction: rename the test file and this stops excusing it, so the+#: gate starts flagging its own fixtures loudly rather than going quiet.+SELF_REFERENTIAL: dict[str, str] = {+ "scripts/check_deferral_tracker.py": "the gate itself — its docstring quotes every shape it detects",+ "scripts/tests/test_check_deferral_tracker.py": "its tests, which inject those shapes deliberately",+}++# --------------------------------------------------------------------------+# Patterns+# --------------------------------------------------------------------------++#: ``5b``, ``10b``, ``7b+``, ``3.5+``. Lowercase letter only — see the module+#: docstring. The lookarounds keep the token off the tail of a hex digest+#: (``c8b9d670``), a model tag (``llama3.1:8b``) and a version (``v8.1.0``).+#: The trailing ``\.\w`` rather than a bare ``.`` is not a detail: half these+#: mentions end a sentence, and excluding every following full stop silently+#: lost "tracked as 8b." and "Phase 12c." — a gate blind to the most ordinary+#: way of writing the thing it looks for.+_ID = r"(?:\d{1,2}(?:\.\d{1,2})?[a-z]\+?|\d{1,2}\.\d{1,2}\+)"+_TOKEN = rf"(?<![\w.+:/-]){_ID}(?![\w+-]|\.\w)"++#: "tracked as 5b", "tracked as non-blocking 3.5+", "deferred to 12c".+_DEFERRED_AS = re.compile(rf"(?i:tracked\s+as|deferred\s+(?:as|to|until))\s+(?i:non-blocking\s+)?({_TOKEN})")++#: "Follow-up (Phase 6b, tracked in …)" — the shape the ADR used.+_FOLLOW_UP = re.compile(rf"(?i:follow-?up)\s*\(\s*(?i:phase)\s+({_TOKEN})")++#: A bare "Phase 6b". Weaker on its own, which is what LANDED_SUBPHASES is for.+_PHASE = re.compile(rf"\b(?i:phase)\s+({_TOKEN})")++_MARKERS = (_DEFERRED_AS, _FOLLOW_UP, _PHASE)++#: Any identifier, for the generous direction.+_ANY_ID = re.compile(f"({_TOKEN})")++#: What makes a line one that could be talking about a deferral at all.+_DEFERRAL_CONTEXT = re.compile(r"phase|defer|track|scoped|follow-?up", re.I)++#: ``## 5b — backfill and replay-from-offset``+_SECTION = re.compile(rf"^#{{1,3}}\s+({_TOKEN})\s*[—:-]")++#: Prose placing the dead tracker in the past rather than pointing at it.+_QUALIFIED = re.compile(+ r"gitignore|never committed|was never|previously|used to|no longer|historical|replaced by|replaces|is gone|does not exist",+ re.I,+)++#: How far from a mention of the dead tracker the qualifying phrase may sit.+#: The tracker's own preamble puts it in the next paragraph.+_QUALIFY_WINDOW = 3+++def _tracked_files(root: Path) -> list[str]:+ """Every tracked path, per git.++ git rather than ``Path.rglob`` so build output and ``node_modules`` cannot+ contribute a mention, and so the corpus is the set under review.+ """+ out = subprocess.run( # noqa: S603 - fixed argv, no shell+ ["git", "ls-files", "-z"],+ capture_output=True,+ text=True,+ check=False,+ cwd=root,+ )+ if out.returncode != 0:+ return []+ return [name for name in out.stdout.split("\0") if name]+++def sections(text: str) -> dict[str, int]:+ """``{identifier: line number}`` for every section the tracker declares."""+ found: dict[str, int] = {}+ for number, line in enumerate(text.splitlines(), 1):+ match = _SECTION.match(line)+ if match is not None:+ found.setdefault(match.group(1), number)+ return found+++def named_as_deferral(line: str) -> set[str]:+ """Identifiers this line names in deferral language."""+ return {match.group(1) for marker in _MARKERS for match in marker.finditer(line)}+++def mentioned(line: str) -> set[str]:+ """Identifiers on a line that is talking about phases or deferrals."""+ if _DEFERRAL_CONTEXT.search(line) is None:+ return set()+ return {match.group(1) for match in _ANY_ID.finditer(line)}+++def dead_tracker_pointers(lines: list[str]) -> list[int]:+ """Line numbers sending a reader to the dead tracker with no qualifier."""+ unqualified: list[int] = []+ for index, line in enumerate(lines):+ if DEAD_TRACKER not in line:+ continue+ window = lines[max(0, index - _QUALIFY_WINDOW) : index + _QUALIFY_WINDOW + 1]+ if _QUALIFIED.search("\n".join(window)) is None:+ unqualified.append(index + 1)+ return unqualified+++def scan(root: Path, *, historical: dict[str, str] | None = None) -> dict:+ """Read the tracker and the tree. No verdict here."""+ excluded = {**HISTORICAL, **SELF_REFERENTIAL} if historical is None else historical+ tracker_path = root / TRACKER+ if not tracker_path.is_file():+ return {"error": f"{TRACKER} is missing; there is no tracker to check the tree against"}++ declared = sections(tracker_path.read_text(encoding="utf-8"))++ deferrals: dict[str, list[str]] = {}+ references: dict[str, list[str]] = {}+ pointers: list[str] = []+ read = 0+ matched_exclusions: set[str] = set()++ for relative in _tracked_files(root):+ hit = next((prefix for prefix in excluded if relative == prefix or relative.startswith(prefix)), None)+ if hit is not None:+ matched_exclusions.add(hit)+ continue+ try:+ text = (root / relative).read_text(encoding="utf-8")+ except (OSError, UnicodeDecodeError):+ continue+ read += 1+ lines = text.splitlines()++ pointers.extend(f"{relative}:{number}" for number in dead_tracker_pointers(lines))++ for number, line in enumerate(lines, 1):+ where = f"{relative}:{number}"+ for identifier in named_as_deferral(line):+ deferrals.setdefault(identifier, []).append(where)+ if relative == TRACKER:+ # The tracker cannot be its own evidence that a section is+ # still referenced; that is how an entry outlives its work.+ continue+ for identifier in mentioned(line):+ references.setdefault(identifier, []).append(where)++ return {+ "root": root,+ "declared": declared,+ "deferrals": deferrals,+ "references": references,+ "pointers": pointers,+ "files_read": read,+ "excluded": excluded,+ "must_match": {prefix for prefix in excluded if prefix not in SELF_REFERENTIAL},+ "matched_exclusions": matched_exclusions,+ }+++def evaluate(scanned: dict, *, landed: dict[str, str] | None = None) -> tuple[list[str], list[str]]:+ """``(findings, credits)`` — what is wrong, and what the verdict rests on."""+ shipped = LANDED_SUBPHASES if landed is None else landed+ declared: dict[str, int] = scanned["declared"]+ deferrals: dict[str, list[str]] = scanned["deferrals"]+ references: dict[str, list[str]] = scanned["references"]+ findings: list[str] = []+ credits: list[str] = []++ # untracked-deferral — the direction that produced 6b and 8b.+ for identifier, where in sorted(deferrals.items()):+ if identifier in declared:+ continue+ if identifier in shipped:+ credits.append(f"{identifier}: recorded as landed — {shipped[identifier]}")+ continue+ findings.append(+ f"untracked-deferral: {identifier} is named as a deferral at {', '.join(where[:3])} and "+ f"{TRACKER} has no section for it. Either add one in the voice of the others, or record it "+ f"in LANDED_SUBPHASES with where that can be confirmed"+ )++ # unreferenced-section — the same question, backwards.+ for identifier, line in sorted(declared.items()):+ where = references.get(identifier) or []+ if not where:+ findings.append(+ f"unreferenced-section: {TRACKER}:{line} holds scope for {identifier} and nothing outside "+ f"the tracker mentions it. Either the work was renamed or absorbed and the section should "+ f"say so, or the reference it was written against has been deleted"+ )+ continue+ credits.append(f"{identifier}: section at {TRACKER}:{line}, referenced at {where[0]}")++ for where in scanned["pointers"]:+ findings.append(+ f"dangling-tracker-pointer: {where} sends a reader to {DEAD_TRACKER}, which is gitignored and "+ f"was never committed. Point at {TRACKER}, or say in the same breath that the file is gone"+ )++ # The exemption list, read back. An entry nothing names is describing a+ # tree that has moved; an entry the tracker now has a section for says two+ # contradictory things about one sub-phase.+ for identifier in sorted(shipped):+ if identifier in declared:+ findings.append(+ f"stale-landed-record: LANDED_SUBPHASES records {identifier} as shipped and {TRACKER} now "+ f"has a section for it. One of the two is wrong"+ )+ elif identifier not in deferrals and identifier not in references:+ findings.append(+ f"stale-landed-record: LANDED_SUBPHASES records {identifier} and nothing in the tree names "+ f"it. Remove the entry — an exemption nobody needs is where a real one goes to hide"+ )++ # The exclusion list, read back, for the same reason — and printed either+ # way, because an exclusion nobody reads is indistinguishable from a gate+ # that never looked.+ for prefix, reason in sorted(scanned["excluded"].items()):+ if prefix in scanned["matched_exclusions"]:+ credits.append(f"excluded: {prefix} — {reason}")+ elif prefix in scanned["must_match"]:+ findings.append(f"stale-exclusion: '{prefix}' is excluded ({reason}) and no tracked file matches it")++ return findings, credits+++def main(argv: list[str] | None = None, *, landed: dict[str, str] | None = None, historical: dict[str, str] | None = None) -> int:+ parser = argparse.ArgumentParser(description="Check every lettered deferral against the committed tracker.")+ parser.add_argument("--self-test", action="store_true", help="prove the gate fails closed and still detects each violation")+ parser.add_argument("--list", action="store_true", help="print every mention found, then the verdict")+ parser.add_argument("--json", dest="as_json", action="store_true", help="machine-readable scan output")+ parser.add_argument("--repo-root", type=Path, default=None, help="the tree to inspect")+ args = parser.parse_args(argv)++ if args.self_test:+ with tempfile.TemporaryDirectory(prefix="aisoc-deferral-tracker-") as scratch:+ extra = _injected_cases(Path(scratch))+ return self_test_main(Path(__file__).name, [], extra=extra)++ root = (args.repo_root or repo_root()).resolve()+ scanned = scan(root, historical=historical)+ if "error" in scanned:+ print(f"REFUSED: {scanned['error']}")+ return 2++ declared: dict[str, int] = scanned["declared"]++ print(f"root: {root}")+ print(f"tracker: {TRACKER} — {len(declared)} section(s): {', '.join(sorted(declared)) or 'none'}")+ print(f"corpus: {scanned['files_read']} tracked text file(s) read, {len(scanned['excluded'])} path(s) excluded and named below")++ # Non-vacuity. A tracker with no sections and a corpus of no files both+ # produce zero findings, and neither says anything about the tree.+ if not declared:+ print(f"REFUSED: {TRACKER} declares no sections; a clean verdict here would describe a tracker the gate never parsed")+ return 2+ if not scanned["files_read"]:+ print("REFUSED: no tracked text files were read; there is nothing to check the tracker against")+ return 2++ findings, credits = evaluate(scanned, landed=landed)++ if args.as_json:+ print(+ json.dumps(+ {"declared": declared, "deferrals": scanned["deferrals"], "pointers": scanned["pointers"], "findings": findings},+ indent=2,+ sort_keys=True,+ )+ )++ if args.list:+ for identifier, where in sorted(scanned["deferrals"].items()):+ for location in where:+ print(f" named as a deferral {identifier:6} {location}")++ for credit in credits:+ print(f" {credit}")++ if findings:+ print(f"\nFAIL: the deferral record and the tree disagree ({len(findings)} finding(s))")+ for finding in findings:+ print(f" - {finding}")+ return 1++ print(+ f"\nOK: {len(declared)} tracked deferral(s), each named somewhere and each named deferral tracked; "+ f"{len(LANDED_SUBPHASES)} recorded as landed; no tracked file points at {DEAD_TRACKER}"+ )+ return 0+++# ─── Self-test ───────────────────────────────────────────────────────────────+#+# The empty-tree refusal comes from the toolkit. These are the cases only this+# gate can express: a violation of each rule it enforces, plus the near misses+# that would make it a nuisance, injected into scratch trees — because a gate+# that has never failed is not known to work.+#+# The scratch trees carry their own exemption lists. The module-level ones+# describe this repository, and every entry would read as stale against a+# four-file tree, which would drown the case each probe is actually making.++_TRACKER_BODY = "# The lettered deferrals\n\n## 5b — backfill and replay-from-offset\n\n**Status: open.**\n"+_ROADMAP = "- [x] Phase 5 — Data spine (backfill/replay-from-offset tracked as 5b)\n"+_HISTORICAL = {"CHANGELOG.md": "append-only release history"}+++def _tree(root: Path, files: dict[str, str]) -> Path:+ root.mkdir(parents=True, exist_ok=True)+ subprocess.run(["git", "-C", str(root), "init", "-q"], check=True) # noqa: S603+ for relative, body in files.items():+ target = root / relative+ target.parent.mkdir(parents=True, exist_ok=True)+ target.write_text(body, encoding="utf-8")+ subprocess.run(["git", "-C", str(root), "add", "-A"], check=True) # noqa: S603+ return root+++def _files(**extra: str) -> dict[str, str]:+ """A minimal clean tree: one tracked section, one reference, one excluded+ surface so the exclusion list is not itself reported stale."""+ return {TRACKER: _TRACKER_BODY, "ROADMAP.md": _ROADMAP, "CHANGELOG.md": "## [Unreleased]\n", **extra}+++def _verdict(root: Path, landed: dict[str, str] | None = None) -> int:+ """``main`` over ``root`` with its output swallowed.++ The probes below care only about the exit status, and fifteen verdicts+ printed in full would bury the self-test's own result.+ """+ with contextlib.redirect_stdout(io.StringIO()):+ return main(["--repo-root", str(root)], landed=landed or {}, historical=_HISTORICAL)+++def _injected_cases(scratch: Path) -> list[tuple[str, bool]]:+ adr = f"- **Follow-up (Phase 6b, tracked in `{DEAD_TRACKER}`).** Wire the model in.\n"+ docstring = '"""Migration of the existing inline prompts is tracked as 8b."""\n'+ qualified = f"`{DEAD_TRACKER}` is in `.gitignore` and was never committed.\n"+ across_paragraph = f"See `{DEAD_TRACKER}`.\n\nThat file was never committed.\n"++ return [+ (+ "a tree whose every named deferral has a section passes",+ _verdict(_tree(scratch / "clean", _files())) == 0,+ ),+ (+ "untracked-deferral: the ADR shape, 'Follow-up (Phase 6b, …)' with no section, fails",+ _verdict(_tree(scratch / "orphan-adr", _files(**{"docs/decisions/0005.md": adr}))) == 1,+ ),+ (+ "untracked-deferral: the docstring shape, 'tracked as 8b' in source, fails",+ _verdict(_tree(scratch / "orphan-src", _files(**{"services/a/p.py": docstring}))) == 1,+ ),+ (+ "untracked-deferral: a bare 'Phase 12c' in a doc fails",+ _verdict(_tree(scratch / "orphan-bare", _files(**{"docs/x.md": "Deferred to Phase 12c.\n"}))) == 1,+ ),+ (+ "a sub-phase recorded as landed is not an untracked deferral",+ _verdict(_tree(scratch / "landed", _files(**{"docs/x.md": "Phase 4c closed the row.\n"})), landed={"4c": "shipped"}) == 0,+ ),+ (+ "stale-landed-record: an exemption nothing in the tree names fails",+ _verdict(_tree(scratch / "stale-landed", _files()), landed={"4c": "shipped"}) == 1,+ ),+ (+ "stale-landed-record: an exemption the tracker has a section for fails",+ _verdict(_tree(scratch / "contradiction", _files()), landed={"5b": "shipped"}) == 1,+ ),+ (+ "unreferenced-section: a section nothing outside the tracker mentions fails",+ _verdict(_tree(scratch / "unreferenced", {**_files(), "ROADMAP.md": "- [x] Phase 5 — Data spine\n"})) == 1,+ ),+ (+ "dangling-tracker-pointer: an unqualified pointer at the dead tracker fails",+ _verdict(_tree(scratch / "pointer", _files(**{"docs/y.md": f"Scope lives in `{DEAD_TRACKER}`.\n"}))) == 1,+ ),+ (+ "prose calling the dead tracker gitignored and never committed passes",+ _verdict(_tree(scratch / "qualified", _files(**{"docs/y.md": qualified}))) == 0,+ ),+ (+ "a qualifier in the next paragraph passes, as the tracker's own preamble has it",+ _verdict(_tree(scratch / "qualified-para", _files(**{"docs/y.md": across_paragraph}))) == 0,+ ),+ (+ "a historical surface naming a deferral and the dead tracker is not a finding",+ _verdict(_tree(scratch / "historical", _files(**{"CHANGELOG.md": f"tracked as 9b in `{DEAD_TRACKER}`\n"}))) == 0,+ ),+ (+ "stale-exclusion: an excluded path matching no tracked file fails",+ _verdict(_tree(scratch / "stale-exclusion", {TRACKER: _TRACKER_BODY, "ROADMAP.md": _ROADMAP})) == 1,+ ),+ (+ "the other plan's uppercase 'Phase 4B' is not a lettered deferral",+ _verdict(_tree(scratch / "uppercase", _files(**{"docs/z.md": "Phase 4B — mobile responder PWA.\n"}))) == 0,+ ),+ (+ "a model tag and a hex digest do not read as identifiers",+ _verdict(_tree(scratch / "nearmiss", _files(**{"docs/z.md": "Phase notes: llama3.1:8b tracked at c8b9d670.\n"}))) == 0,+ ),+ (+ "a tracker declaring no sections is refused rather than called clean",+ _verdict(_tree(scratch / "vacuous", {**_files(), TRACKER: "# The lettered deferrals\n"})) == 2,+ ),+ ]+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/scripts/tests/test_check_deferral_tracker.py b/scripts/tests/test_check_deferral_tracker.pynew file mode 100644index 000000000..4c955efac--- /dev/null+++ b/scripts/tests/test_check_deferral_tracker.py@@ -0,0 +1,288 @@+"""The deferral gate detects each orphan shape it claims to, and only those.++Proven against the two shapes that were live on `main` when the gate was+written — a follow-up in an ADR naming `Phase 6b`, and a module docstring+saying a migration is "tracked as 8b", neither with a section in the tracker+and both still pointing at a file that was never committed — plus the near+misses that would make the gate a nuisance: the other plan's uppercase+`Phase 4B`, a model tag ending in `8b`, a hex digest, and prose that names+the dead tracker only to say it is gone.+"""++from __future__ import annotations++import importlib.util+import subprocess+import sys+from pathlib import Path++REPO_ROOT = Path(__file__).resolve().parents[2]+GATE = REPO_ROOT / "scripts" / "check_deferral_tracker.py"++sys.path.insert(0, str(REPO_ROOT / "scripts"))++from gate_toolkit import refuses_an_empty_tree # noqa: E402++TRACKER = "docs/audit/DEFERRED_SUBPHASES.md"+DEAD = "docs/audit/PROGRESS.md"++TRACKER_BODY = """# The lettered deferrals++## 5b — backfill and replay-from-offset++**Status: open.**++## 7b+ — posture collection++**Status: partially closed.**+"""++#: One line naming both sections in deferral language, the way `ROADMAP.md`+#: does — `7b+` only ever appears next to "scoped in", never "tracked as",+#: which is why the reference direction is the generous one.+ROADMAP = "- [x] Phase 5 — Data spine (backfill/replay tracked as 5b)\n- [x] Phase 7 — 7b+ (posture) scoped in the tracker\n"++#: The excluded surface has to exist or the exclusion reads as stale, which+#: is a finding in its own right and would mask the one under test.+HISTORICAL = {"CHANGELOG.md": "append-only release history"}+++def _load():+ spec = importlib.util.spec_from_file_location("check_deferral_tracker", GATE)+ assert spec is not None and spec.loader is not None+ module = importlib.util.module_from_spec(spec)+ sys.modules[spec.name] = module+ spec.loader.exec_module(module)+ return module+++def _tree(tmp_path: Path, files: dict[str, str] | None = None, *, tracker: str | None = None) -> Path:+ """A staged git tree holding a tracker, a roadmap and whatever else is asked for.++ Staged, because the gate takes its corpus from `git ls-files` and an+ unstaged file is invisible to it — the same trap that makes a gate run+ before `git add` skip the files it is meant to judge.+ """+ root = tmp_path / "tree"+ root.mkdir(exist_ok=True)+ subprocess.run(["git", "-C", str(root), "init", "-q"], check=True)+ payload = {+ TRACKER: TRACKER_BODY if tracker is None else tracker,+ "ROADMAP.md": ROADMAP,+ "CHANGELOG.md": "## [Unreleased]\n",+ **(files or {}),+ }+ for rel, body in payload.items():+ path = root / rel+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(body, encoding="utf-8")+ subprocess.run(["git", "-C", str(root), "add", "-A"], check=True)+ return root+++def _run(root: Path, module, *, landed: dict[str, str] | None = None) -> int:+ return module.main(["--repo-root", str(root)], landed=landed or {}, historical=HISTORICAL)+++# ─── The extraction halves, read directly ────────────────────────────────────+++def test_the_section_parser_reads_the_real_tracker() -> None:+ """The eight identifiers this repository actually carries, from the file."""+ module = _load()+ declared = module.sections((REPO_ROOT / TRACKER).read_text(encoding="utf-8"))+ assert set(declared) == {"3.5+", "5b", "6b", "7b+", "8b", "9b", "10b", "11b"}+++def test_every_way_the_tree_writes_a_deferral_is_recognised() -> None:+ module = _load()+ assert module.named_as_deferral("backfill/replay-from-offset tracked as 5b)") == {"5b"}+ assert module.named_as_deferral("demo-timing gate tracked as non-blocking 3.5+)") == {"3.5+"}+ assert module.named_as_deferral("- **Follow-up (Phase 6b, tracked in x).**") == {"6b"}+ assert module.named_as_deferral("prompts is tracked as 8b; this seeds the registry") == {"8b"}+ # A sentence-ending full stop is the most ordinary way of writing it, and+ # an earlier lookahead excluded every following `.` — which lost both+ # real orphans at once.+ assert module.named_as_deferral("Deferred to Phase 12c.") == {"12c"}+++def test_the_other_plans_uppercase_phases_are_a_different_vocabulary() -> None:+ """`Phase 1A` / `Phase 4B` belong to the 90-day plan and all landed."""+ module = _load()+ assert module.named_as_deferral("ORM models for the Phase 4B mobile responder PWA.") == set()+ assert module.named_as_deferral("Persistent agent decision ledger (Phase 1A).") == set()+++def test_a_model_tag_a_digest_and_a_version_are_not_identifiers() -> None:+ module = _load()+ assert module.mentioned("phase notes: llama3.1:8b") == set()+ assert module.mentioned("tracked at commit c8b9d670") == set()+ assert module.mentioned("phase shipped in v8.1.0") == set()+++def test_a_reference_only_counts_on_a_line_that_is_talking_about_phases() -> None:+ """The generous direction is still not "any occurrence anywhere"."""+ module = _load()+ assert module.mentioned("- [x] Phase 7 — 7b+ (posture) scoped in the tracker") == {"7b+"}+ assert module.mentioned("if head -c 2 /tmp/a.enc | od -An -tx1 | grep -q '1f 8b'; then") == set()+++def test_prose_placing_the_dead_tracker_in_the_past_is_not_a_pointer() -> None:+ module = _load()+ assert module.dead_tracker_pointers([f"Scope lives in `{DEAD}`."]) == [1]+ assert module.dead_tracker_pointers([f"`{DEAD}` is in `.gitignore` and was never committed."]) == []+ # The tracker's own preamble puts the qualifier in the next paragraph.+ assert module.dead_tracker_pointers([f"See `{DEAD}`.", "", "That file was never committed."]) == []+++# ─── untracked-deferral ──────────────────────────────────────────────────────+++def test_the_adr_shape_that_was_live_on_main_fails(tmp_path, capsys) -> None:+ """`docs/decisions/0005-storage-consolidation.md`, verbatim in shape."""+ module = _load()+ adr = f"- **Follow-up (Phase 6b, tracked in `{DEAD}`).** Wire the model in.\n"+ root = _tree(tmp_path, {"docs/decisions/0005.md": adr})+ assert _run(root, module) == 1+ out = capsys.readouterr().out+ assert "untracked-deferral: 6b" in out+ assert "dangling-tracker-pointer" in out+++def test_the_docstring_shape_that_was_live_on_main_fails(tmp_path, capsys) -> None:+ """A deferral named in source, which is why the corpus is the whole tree."""+ module = _load()+ root = _tree(tmp_path, {"services/a/p.py": '"""Migration of the inline prompts is tracked as 8b."""\n'})+ assert _run(root, module) == 1+ out = capsys.readouterr().out+ assert "untracked-deferral: 8b" in out+ assert "services/a/p.py:1" in out+++def test_a_bare_phase_reference_with_no_section_fails(tmp_path, capsys) -> None:+ module = _load()+ root = _tree(tmp_path, {"docs/x.md": "The rest is deferred to Phase 12c.\n"})+ assert _run(root, module) == 1+ assert "untracked-deferral: 12c" in capsys.readouterr().out+++def test_a_sub_phase_recorded_as_landed_is_not_an_orphan(tmp_path, capsys) -> None:+ module = _load()+ root = _tree(tmp_path, {"docs/x.md": "Phase 4c closed that row.\n"})+ assert _run(root, module, landed={"4c": "shipped — ROADMAP.md Phase 4"}) == 0+ assert "4c: recorded as landed" in capsys.readouterr().out+++# ─── the exemption list, read back ───────────────────────────────────────────+++def test_a_landed_record_nothing_in_the_tree_names_fails(tmp_path, capsys) -> None:+ """An exemption nobody needs is where a real one goes to hide."""+ module = _load()+ root = _tree(tmp_path)+ assert _run(root, module, landed={"4c": "shipped"}) == 1+ assert "stale-landed-record" in capsys.readouterr().out+++def test_a_landed_record_the_tracker_also_holds_a_section_for_fails(tmp_path, capsys) -> None:+ module = _load()+ root = _tree(tmp_path)+ assert _run(root, module, landed={"5b": "shipped"}) == 1+ assert "stale-landed-record: LANDED_SUBPHASES records 5b" in capsys.readouterr().out+++def test_an_excluded_path_matching_no_tracked_file_fails(tmp_path, capsys) -> None:+ module = _load()+ root = tmp_path / "tree"+ root.mkdir()+ subprocess.run(["git", "-C", str(root), "init", "-q"], check=True)+ for rel, body in {TRACKER: TRACKER_BODY, "ROADMAP.md": ROADMAP}.items():+ (root / rel).parent.mkdir(parents=True, exist_ok=True)+ (root / rel).write_text(body, encoding="utf-8")+ subprocess.run(["git", "-C", str(root), "add", "-A"], check=True)+ assert _run(root, module) == 1+ assert "stale-exclusion: 'CHANGELOG.md'" in capsys.readouterr().out+++def test_every_exclusion_is_printed_even_on_a_clean_run(tmp_path, capsys) -> None:+ """An exclusion nobody reads is indistinguishable from a gate that did not look."""+ module = _load()+ assert _run(_tree(tmp_path), module) == 0+ assert "excluded: CHANGELOG.md" in capsys.readouterr().out+++# ─── unreferenced-section ────────────────────────────────────────────────────+++def test_a_section_nothing_outside_the_tracker_mentions_fails(tmp_path, capsys) -> None:+ module = _load()+ root = _tree(tmp_path, {"ROADMAP.md": "- [x] Phase 5 — Data spine (tracked as 5b)\n"})+ assert _run(root, module) == 1+ out = capsys.readouterr().out+ assert "unreferenced-section" in out+ assert "7b+" in out+++def test_the_tracker_is_not_its_own_evidence(tmp_path, capsys) -> None:+ """A section citing itself is how an entry outlives the work it describes."""+ module = _load()+ root = _tree(tmp_path, {"ROADMAP.md": "nothing here\n"})+ assert _run(root, module) == 1+ out = capsys.readouterr().out+ assert "unreferenced-section" in out and "5b" in out+++# ─── historical surfaces ─────────────────────────────────────────────────────+++def test_a_historical_surface_naming_a_deferral_is_not_a_finding(tmp_path) -> None:+ """Editing a shipped changelog entry to name a different path is revisionism."""+ module = _load()+ root = _tree(tmp_path, {"CHANGELOG.md": f"- tracked as 9b in `{DEAD}`\n"})+ assert _run(root, module) == 0+++# ─── non-vacuity ─────────────────────────────────────────────────────────────+++def test_a_tracker_with_no_sections_is_refused_rather_than_called_clean(tmp_path, capsys) -> None:+ module = _load()+ root = _tree(tmp_path, tracker="# The lettered deferrals\n")+ assert _run(root, module) == 2+ assert "REFUSED" in capsys.readouterr().out+++def test_a_missing_tracker_is_refused(tmp_path, capsys) -> None:+ module = _load()+ root = tmp_path / "bare"+ root.mkdir()+ subprocess.run(["git", "-C", str(root), "init", "-q"], check=True)+ assert _run(root, module) == 2+ assert f"{TRACKER} is missing" in capsys.readouterr().out+++def test_the_empty_tree_refusal_holds_for_a_copy_of_the_script() -> None:+ """The toolkit's probe: `scripts/` copied into a tree with no content."""+ refused, detail = refuses_an_empty_tree(GATE.name, [])+ assert refused, detail+++# ─── the gate, end to end ────────────────────────────────────────────────────+++def test_the_gate_answers_the_self_test_flag() -> None:+ result = subprocess.run([sys.executable, str(GATE), "--self-test"], capture_output=True, text=True)+ assert result.returncode == 0, result.stdout + result.stderr+++def test_the_live_repository_passes() -> None:+ """The regression this gate exists for, asserted against the real tree."""+ result = subprocess.run([sys.executable, str(GATE)], capture_output=True, text=True)+ assert result.returncode == 0, result.stdout + result.stderr+++def test_the_live_run_credits_a_reference_for_every_section() -> None:+ """A credit nobody reads is a verdict nobody can check."""+ result = subprocess.run([sys.executable, str(GATE)], capture_output=True, text=True)+ for identifier in ("3.5+", "5b", "6b", "7b+", "8b", "9b", "10b", "11b"):+ assert f"{identifier}: section at {TRACKER}:" in result.stdout, result.stdoutdiff --git a/services/agents/app/llm/prompt_registry.py b/services/agents/app/llm/prompt_registry.pyindex ab4c89047..6c23ab94a 100644--- a/services/agents/app/llm/prompt_registry.py+++ b/services/agents/app/llm/prompt_registry.py@@ -15,8 +15,8 @@ which is exactly the signal that should trigger the eval re-grade.The registry is the source of truth for prompt text; agents should read via`get(name)` rather than redeclaring constants. Migration of the existing inline-prompts is tracked as 8b; this seeds the registry + gate with the canonical-triage/summary prompts.+prompts is tracked as 8b in `docs/audit/DEFERRED_SUBPHASES.md`; this seeds the+registry + gate with the canonical triage/summary prompts."""from __future__ import annotations