# Watchtower Contracts

Shared contracts for all watchtower components. Every ring, hook, and
skill that reads or writes watchtower state files must follow these.

## Atomic Writes

All shared files use temp+rename. No exceptions. Write to a `.tmp`
sibling, then `fs.renameSync()`. This prevents partial reads when a
ring is writing while a SessionStart hook is reading.

```javascript
const tmp = filePath + '.tmp';
fs.writeFileSync(tmp, content);
fs.renameSync(tmp, filePath);
```

## No-Index Convention

The inbox queue uses directory listing, not an index file. To list
pending items, read `queue/items/`, open each `.json`, filter by
status. No manifest, no index.json.

Rationale: one fewer file to keep consistent. Directory listing is
O(n) but n is small (inbox items rarely exceed 50 items). If
listing exceeds 2 seconds or 500 items, revisit via `act:2b638b02`.

## Schema Versioning

Every JSON file carries `schema_version`. Readers guard on version
and emit clear errors on unrecognized versions. Never silent wrong
behavior — if a reader sees `schema_version: 2` and only understands
`1`, it must fail loudly, not silently misparse.

```javascript
if (item.schema_version !== 1) {
  throw new Error(`Unsupported schema version ${item.schema_version} in ${filePath}`);
}
```

## Session-ID Join Key

Session IDs are the join key across queue items (via `transcript_ref`),
messages (Plan 8), and Ring 3 cursors (Plan 7). This is a load-bearing
assumption documented here so that if session IDs prove to be the wrong
unit (e.g., Claude Code changes ID semantics), the migration scope is
known: queue items, messages, and cursors all need updating.

Validate when Ring 3 first writes real data.

## Summary Hard Cap

`state/summary.md` must not exceed 30 lines. This is the SessionStart
injection payload — it competes with other context for the model's
attention window. If content exceeds 30 lines, truncation order:

1. Drop Health section detail (keep one-line summary)
2. Drop Portfolio Pulse detail for quiet projects
3. Never truncate "What Needs Attention" or "Where You Left Off"

## Project State Section Ownership

`state/projects/<slug>.md` is written by two rings. Every section has
exactly ONE owner; a ring must never rebuild a section the other ring
owns. The merge that enforces this is `preserveRing3LastSession()` in
`watchtower-lib.mjs`, applied by Ring 1 before each per-project write.

| Section              | Owner  | Notes                                  |
|----------------------|--------|----------------------------------------|
| `# <name>` header    | Ring 1 | Timestamp refreshed every run          |
| `## Active Plans`    | Ring 1 | Rebuilt from pib-db every run          |
| `## Last Session`    | Ring 3 | Once authored — see below              |
| `## Standing Issues` | Ring 1 | Rebuilt every run                      |
| `## Tech Stack`      | Ring 1 | Rebuilt every run                      |

Ring 3's sessionSummary writes the rich Last Session summary with an
`_<date> (<session-id>)_` attribution line directly under the header.
That attribution line IS the ownership marker: until Ring 3 has authored
the section, Ring 1 writes its own ephemeral fallback ("Active: …" /
last-commit line) and rebuilds it freely; once the marker is present,
Ring 1 must carry the existing section forward verbatim. Without this,
Ring 1's full-file rebuild deterministically clobbers Ring 3's summary
within one cron tick (~5 minutes). Rebuild writes must go through
`writeProjectStatePreservingRing3()` in `watchtower-lib.mjs` (re-read
verify with retry), never a raw read→merge→write — the raw form has a
read-then-write race that drops a Last Session Ring 3 authors mid-merge.

The inline `## Last Session` block holds the COMPLETE session bullet set
— byte-identical to the bullets in the per-session record at
`state/projects/<slug>/sessions/<date>-<session-id>.md`. It is NOT a
pointer, a digest, or a truncated subset. Both bodies derive from the
ONE model bullet string via `buildLastSessionBlock()`, and Ring 3 writes
the inline block UNCONDITIONALLY — creating `<slug>.md` if it does not
yet exist — so the inline section is never silently skipped (the prior
`existsSync` gate dropped it on fresh projects, leaving readers to render
Ring 1's truncated one-line fallback while the per-session file held the
full set; act:ac119994). `upsertLastSessionSection()` performs the
in-place splice/append with the same line-anchored header search
`preserveRing3LastSession()` reads with — one splice convention, not two.

### Thread File Durability (disk wins over model)

`state/threads/<slug>.json` carries the sibling rule: **disk wins over
model**. If the thread file exists, Ring 3 ALWAYS appends to
`cursor_history` — the LLM's `is_new` field is advisory naming metadata
only, never an authorization to fresh-write over an existing file. One
hallucinated `is_new: true` must not wipe an append-only history. The
canonical implementation is `updateThreadFile()` in `watchtower-lib.mjs`.

Corrupt thread files are never silently replaced: the corrupt file is
backed up aside as `<slug>.json.corrupt-<ts>`, a fresh file is written,
and the recovery is logged loudly. Per-thread writes are isolated — one
bad thread file must not abort writes for the remaining threads.

**Earned, bounded membership (act:e8793574).** A single session close writes
at most `MAX_THREADS_PER_SESSION` (5) threads, and each membership must carry
a DISTINCT contribution. `selectEarnedThreads()` (in `watchtower-ring3-close.mjs`)
enforces this in code, not just in the prompt: a blank/one-word contribution
is dropped, a contribution that restates an already-accepted one (spray) is
dropped, and the accepted set is capped. Overlap is healthy — a session
genuinely advancing several zoom levels earns each — but a focused session
can no longer be sprayed across 6-9 threads on loose topical match.

**Relationship fields (act:e8793574, additive at `schema_version: 2`).** Two
optional union-deduped arrays let a cold session trace a thread:

- `related_fids` — pib-db work-item fids (`act:<8hex>`) the sessions that
  advanced this thread referenced. Populated DETERMINISTICALLY by
  `extractRelatedFids()` scanning the transcript — never model-authored, so no
  hallucinated fid can enter. Unioned across sessions on disk.
- `lineage` — sibling threads CO-ADVANCED in the same session (the only thread
  relation cheap enough to assert as ground truth: co-occurrence in one
  capture). Entry shape `{ slug, relation: "co-occurrence", session_id, date }`,
  deduped by `slug`. Empty when the session earned only one thread.

Both default to `[]` when the 7th `updateThreadFile()` argument is omitted, so
older callers and the corrupt/create paths are unchanged.

**No silent success on systemic API failure (act:e8793574).** When the
Anthropic API rejects every call for an account-level reason (billing
exhausted, bad key, quota), every knowledge-extraction phase produces nothing.
`ring3-health.json` then reports `status: "degraded"` with an `api_error`
`{ type, message }` instead of `"success"` (`classifyApiError()` /
`buildHealth()`), and the run logs a loud `SYSTEMIC API FAILURE` line. This
exists because a credit-balance outage silently froze thread capture for a
week (2026-07-05 → 2026-07-12) while health kept reporting success.

## Enrichment Directory

Per-item enrichment lives in `queue/items/<id>/enrichment/`. Four
standard files:

| File | Written by | Content |
|------|-----------|---------|
| `code-context.md` | Ring 2 fast | Actual code being discussed |
| `related-decisions.md` | Ring 2 fast | Prior decisions bearing on this |
| `memory-refs.md` | Ring 2 fast | Relevant memory entries |
| `options-analysis.md` | Ring 2 fast | Pros/cons with evidence |

`/inbox` reads these when `enrichment_status` is `"complete"`.
Missing files degrade gracefully (null in the read result).

## Routine Dispatch (declared interactive routines)

Projects declare interactive customs as **routines** in `config.json`,
under their project entry:

```json
"projects": {
  "flow": {
    "path": "/Users/x/flow",
    "routines": [
      {
        "name": "morning-briefing",
        "description": "Walk the operator through the day's landscape",
        "trigger": { "type": "time-of-day", "at": "08:30" },
        "script": ".claude/routines/morning-briefing.md",
        "urgency": "normal",
        "stale_after_hours": 24
      }
    ]
  }
}
```

- `name` — kebab-case slug, unique within the project.
- `trigger.type` — `time-of-day` (`at: "HH:MM"`, local, fires once per
  day), `interval` (`minutes`, >= 5), `path-nonempty` (`path` relative
  to the project root or absolute; `cooldown_minutes` default 60), or
  `session-close` (fires when Ring 3 closes a session for the project;
  worktree sessions resolve to the main project; `cooldown_minutes`
  default 0).
- `script` — project-authored phase file (the established CC phase
  convention) holding the routine's conversation script. The receiving
  session reads it and runs it; watchtower never parses it.
- `stale_after_hours` (default 24) — how long a pending dispatch stays
  blocking before a fresh firing supersedes it.

Ownership: `watchtower-routines.mjs` owns trigger evaluation, firing
state (`state/routine-state.json`), and dispatch. Ring 1 ticks the
mechanical triggers; Ring 3 raises session-close events. Both are
feature-flagged by `defaults.routine_dispatch`. A firing files an inbox
item (category `routine` — the durable record) and pushes a descriptor
through `mux qa dispatch`, the SAME hardened desk-dispatch path as
qa-handoffs (act:796fe6dc) — never a parallel one. Terminal exits on
any dispatched-category item (qa-handoff, routine) clear the matching
mux descriptor; routine items resolve normally (no QA gate, normal
expiry — expiry also clears the descriptor). A pending routine item
blocks refiring of the same routine until resolved or stale.

**Moment expiry for `time-of-day` routines (act:ea23b3a5).** A daily
routine's value is bound to its day: a morning briefing delivered
tomorrow is not a briefing. `stale_after_hours` only supersedes at the
NEXT due firing, which for a daily routine is 24 hours later, so a
missed firing held a queue slot and a lit desk badge all day. Ring 1's
tick now supersedes a pending `time-of-day` item once the calendar day
it was FILED on has ended.

End of day, not a fixed number of hours, and the difference is
measured rather than tasteful: across six weeks the portfolio's one
time-of-day routine had ten real pickups — eight within four hours and
two after, at 4.4h and 8.6h. A four-hour window would have destroyed two
genuine pickups to clear one stale item. End-of-day preserves all ten,
needs no tuning constant, and matches what a daily routine means to a
person: you can still want your morning briefing at 4pm; you do not want
it tomorrow.

Three scoping rules, each load-bearing:

- **Ring 1's portfolio tick only.** Ring 3 also calls `runRoutinePass`,
  with a single-project `session-close` event. An unscoped sweep there
  would have every session close in any project superseding every OTHER
  project's routine items — and one portfolio sweep per replayed session
  during a `--reprocess-failed` drain.
- **Classify from the ITEM, not from config.** `dispatchRoutine`
  persists `evidence.trigger` at filing, so a routine whose declaration
  was later removed still classifies. A config lookup would find nothing
  and leave it pending forever.
- **An unparseable `filed_at` abstains, loudly.** The `stale_after_hours`
  path treats the same input as stale (NaN comparisons fall through to
  supersede); this one refuses and logs. Two mechanisms disagreeing
  silently is worse than one abstaining out loud.

Consequences, named rather than discovered later: for a `time-of-day`
trigger the moment sweep pre-empts the `stale_after_hours` supersede
(same outcome, more honest reason), a missed briefing is no longer
re-delivered by the SessionStart missed-routine section on a LATER day,
and the sweep has no in-flight awareness — a routine picked up by `mux
qa drain` very close to midnight could be superseded mid-run, which
end-of-day narrows to minutes where a fixed-hour window would have
opened it to hours. `interval`, `path-nonempty`, and `session-close`
routines have no moment and are untouched.

## Upstream-Friction Actionability (Phase 2g)

A friction report with no party who could act on it is not a report.
Five of the 2026-07-26 dismissals were observations like "Claude made
iterative browser tweaks without writing to file" — true, and addressed
to nobody, aging in the queue for weeks.

Phase 2g now classifies each finding into three arms (act:ea23b3a5),
copying Phase 2f's verification-gate shape (which files a methodology
capture only when the claimed artifact verifiably exists on disk, after
11 of 11 unverified captures were dismissed over three weeks):

1. **A named route** — `evidence.route.type` from the CLOSED vocabulary
   `cc-feedback | project-tracker | config-change`, plus a non-empty
   `detail` naming who acts and how ⇒ files `upstream-friction`, with the
   route rendered into the summary so the operator sees it without
   opening the evidence.
2. **Durable, no route** — a platform constraint or environment quirk
   nobody can fix, whose WORKAROUND is worth remembering ⇒ files
   `knowledge-extraction`. This arm is not theory: of the five friction
   items the operator KEPT, four exited as `captured-to-memory`. A
   two-arm gate would have discarded the useful half of the lens.
3. **Neither** — a transient incident or a general observation about
   Claude's behavior ⇒ files nothing, and is COUNTED. All three counts
   are logged every run; silence would be indistinguishable from a lens
   that never ran, and the drop count is the number this change exists to
   move.

An invented route type or an empty `detail` falls to arm 3. The
vocabulary is closed precisely so "someone should fix this" cannot
become an escape hatch.

## Session Advisor Pass (re-homed standing advisors)

The standing session advisors (historian, system-advocate,
user-advocate, anthropic-insider) hold two session-boundary seats, both
index-driven via `.claude/skills/_index.json` — the roster is whoever
declares the mandate, never a hardcoded list (act:aded4fc9):

- **Close side (automatic):** Ring 3's Phase 2m runs every member whose
  `standingMandate` includes `session-close` against the compressed
  session transcript, scoped by `directives.session-close`. Findings
  file as `advisor-finding` inbox items (max 2 per member per session,
  deduped against pending + resolved/dismissed corpora). Feature-flagged
  by `defaults.session_advisors`. Cost: reuses Ring 3's pinned-sonnet
  run — no Claude Code spawn.
- **Start side (pull, intent-aware):** `/briefing` full mode spawns
  every member whose `standingMandate` includes `briefing`, scoped by
  `directives.briefing`, with the briefing's gathered portfolio context.
  Observations route through the curator's Step 3b selection and Step 4
  close — never a permanent section (anti-accretion invariant).
- **Consultation side (skill-level):** the /orient and /debrief
  cabinet-consultations phases persist their members' ACTIONABLE
  findings through this same channel before the briefing/report
  renders (act:84daa7bc) — `advisor-finding` items with
  `filed_by: "manual"` and `evidence.directive_key: "orient"` or
  `"debrief"`, capped at 2 per member per session like Phase 2m.
  Same dedup-vs-pending discipline (an existing pending item is
  referenced, not re-filed), same /briefing re-surfacing — never a
  parallel path. Projects without watchtower fall back to a pib-db
  action; with neither available, the finding is marked UNTRACKED in
  the rendered output so the non-persistence is loud.

`advisor-finding` is ungated and undispatched: normal expiry applies
(findings decay naturally), and `/briefing` weighs fresh ones near the
top of the owning project's chunk — the re-surfacing the close pass
promises. A `session-close`/`briefing` mandate without the matching
directive key is a data error: consumers skip the member and log it.

## Session-Close Extraction Lenses — Phase 2n/2o/2p (act:4ff2cfb3)

Ring 3's session close runs three extraction lenses beyond the knowledge
pass (2d) and advisor pass (2m), each modeled on `advisorPass` with an
injectable `callFn` (testable; never folded into the hardened Phase 2d —
see `lesson_ring3_lens_injectable_phase_pattern`):

- **Phase 2n — Raised-but-unhandled.** Loose ends the session RAISED
  (promises, side-issues, open questions) but neither completed nor
  filed → an inbox item under the `raised-unhandled` category. Capped at
  `RAISED_UNHANDLED_MAX = 5` per session.
- **Phase 2o — Skill-candidate.** A manual procedure repeated by hand
  that a skill could absorb → a `skill-candidate` inbox item ("make a
  skill?"). Capped at `SKILL_CANDIDATE_MAX = 3` per session.
- **Phase 2p — Checklist-catch.** A surfaced change-impact check that
  caught a real bug → recorded to `checklist-stats.json` (the
  catch-recording side; consumed by `/debrief`'s checklist-feedback and
  the audit `checklist-pruning` phase). Not an inbox item — a stats write.

The two new inbox categories (`raised-unhandled`, `skill-candidate`)
follow the standard item schema and the same dedup-vs-corpora discipline
as the other Ring 3 extractions.

## Suppression Ledger (Ring 3 dedup observability)

The recall-fix program (audit act:7d6a4b3b) makes Ring 3's
knowledge-capture dedup **auditable**. Every time `isDuplicate`
suppresses an extraction, the suppression site appends one structured
record to a shared sidecar so over-suppression is visible instead of
vanishing into a write-only cron.

**File:** `state/suppression-ledger.jsonl` (under `WATCHTOWER_DIR`).
Append-only JSON-lines. NOT shipped as a template — generated at
runtime, like `checklist-stats.json` and `.memory-pressure.jsonl`.

**Producer:** `recordSuppression(record, opts)` in `watchtower-lib.mjs`
(shared home; reachable by every ring). Called from every Ring 3
suppression site — Phase 2d (extraction), Phase 2m (advisor close
pass), Phase 2n (raised-unhandled lens), Phase 2o (skill-candidate
lens). The human `log()` line stays beside it; the ledger is the
machine-readable twin, never a parse of the prose.

**Consumer:** the Ring 2 slow over-suppression canary (M5) — the ONLY
reader. It windows records by `ts`, computes a per-project
suppression-rate (suppressed / (suppressed + filed)) against a captured
post-M1a baseline, samples actual suppressed titles + what they matched
for human eyeball, tracks net-durably-saved (filed × approval-rate), and
writes `state/recall-canary.json`. The canary also prunes the ledger to
a retention window on each run (growth is bounded at canary cadence, not
on the suppression hot path). It is over-suppression-only and states so
in its own `note` field. Guards: `total===0 ⇒ no alert`; a minimum
denominator before a rate can fire; baseline captured on first run (else
it would alert on its own improvement).

**The surfacing path** (no write-only telemetry): the canary writes
`state/recall-canary.json` (per-project `{suppressed, filed, rate,
baseline, by_corpus, approval_rate, net_durably_saved, sample, alert}`);
**Ring 1** reads it and renders an alerting project's entry into that
project's **Standing Issues** (Ring 1 owns the per-project state file);
**/briefing**'s State-file-flags reader surfaces it. Three named hops,
each owning its tier. Flag: `defaults.recall_canary` (opt-out).

**Record shape (the contract):**

```json
{
  "ts": "ISO-8601 timestamp of the suppression",
  "project": "resolved project name (or null)",
  "corpus": "memory | thread-cursor | pending | resolved | dismissed | session-actions | rules",
  "suppressed_title": "the extraction title that was killed",
  "matched_against": "the corpus entry it collided with",
  "session_id": "the closing session's id (or null)"
}
```

**Invariants:**

- **Fail-open.** `recordSuppression` never throws. A failed append logs
  one line and continues — a dropped ledger record must NEVER block an
  extraction from filing. The ledger is observability, not the decision.
- **Additive.** New fields ride alongside; readers default missing
  fields. The `corpus` enum grows when a new dedup corpus lands (M1a
  added `thread-cursor` as a first-class corpus split off from
  `memory`).
- **Baseline before behavior.** The ledger lands BEFORE any matcher
  change so it records the OLD (pre-M1a) suppression behavior as the
  before-baseline the canary compares against.
- **Over-suppression only.** The ledger sees what dedup KILLED, not what
  extraction never proposed (M2 under-extraction). The canary states
  this blindness in its own output.

## New Dedup Corpora Ship OFF (act:a6bb5603, act:02e21a69)

`isDuplicate`'s trailing options object is the designated growth point
for new corpora. Two landed together as the sixth and seventh:

- **`session-actions`** — the `text` of actions the project filed inside
  the closing session's own day window. Kills the class where the
  session filed the bug as an action hours ago and Ring 3 then read the
  same transcript and drafted a lesson describing it.
- **`rules`** — HEADINGS plus the filename slug of `.claude/rules/*.md`,
  in BOTH the project's and the operator's global scope. Rule BODIES are
  never matched.

**Every new corpus ships behind a config flag that defaults to OFF.**
This is the standing rule, not a one-time caution. Adding a corpus can
only ever suppress MORE, and a wrong suppression destroys novel
knowledge silently and invisibly — the failure the whole M1/M2
recall-fix program exists to prevent. The flags are `=== true` opt-INs,
deliberately inverted from the `!== false` opt-out convention every
other `defaults.*` flag in the rings uses. Read the recall canary
against the new corpus's own ledger lines before proposing a flip.

**Four invariants a new corpus must satisfy:**

1. **A distinct ledger label.** The `corpus` value is the unit the
   canary measures precision by. A corpus folded into an existing label
   is unmeasurable.
2. **The short-title floor stays absolute.** An item that cannot muster
   `OVERLAP_THRESHOLD` meaningful tokens is never suppressed, by any
   corpus. Terseness must not lower the bar.
3. **A bounded scope, bounded at BOTH ends.** `session-actions` is
   scoped to `[session-start day, session-end day]`, the tightest window
   `actions.created` (a DATE, no time component) supports. The late
   bound is load-bearing: without it, reprocessing a three-week-old
   transcript would sweep every action filed since into the corpus.
   Cross-session duplication stays deliberately UNCOVERED, and an action
   filed by a different session on the same calendar day is the known,
   accepted residual imprecision.
4. **Fail OPEN at every step.** An unreadable db or rules dir yields an
   empty corpus, so the item files as a possible duplicate (one
   dismissal click) rather than being dropped (silent loss).

**Ordering.** New corpora are appended LAST in the match order, so
first-match attribution — and every historical ledger label — is
unchanged for the corpora that predate them.

**A measurement recorded against the rules corpus, because it did not
land as predicted.** Against every item this portfolio has ever filed
(2132 knowledge-extraction, 906 pattern-promotion, 23 raised-unhandled,
35 advisor-finding), 115 rule entries suppress THREE. All three are true
positives, so the corpus is precise — it is simply almost inert. The
reason is structural: an item that RESTATES a rule restates its CONTENT
in its own words and shares almost no long tokens with the rule's
HEADING. The 41-of-78 "restating an already-loaded rule" class is real,
but heading-and-slug matching is not the mechanism that catches it, and
matching rule bodies — the only thing that would — is the
over-suppression this contract forbids.

## The Pattern Shape Gate Must Check the Gap ASSERTS a Gap (act:02e21a69)

`patternHasRequiredShape` rejects document echoes by requiring the
`**Evidence:**` + `**Gap:**` blocks Phase 2e's prompt mandates. It
checked those blocks were PRESENT, not that the Gap block **asserts a
gap** — so a well-formed positive observation passed cleanly and shipped
as a promotion. The live specimen says so in its own body:
`**Gap:** No gap — this is positive practice worth reinforcing.`

The generation-side exclusions in `QUALITY_PATTERN_SYSTEM_PROMPT`
already name no-gap positives as never-patterns. This was never a prompt
problem: the prompt said the right thing and the mechanical gate did not
enforce it, and per `maintainability.md` §Prefer Structural Prevention
Over Detection, the gate is the correct layer.

`gapBlockAssertsGap` rejects a Gap block that is empty or whose OPENING
negates a gap (`no gap`, `none`, `n/a`, `not a gap`, `positive
practice`). Rejections fold into the existing
`rejected_malformed_total` / `last_scan_rejected` counters in
`state/pattern-detection.json` AND into their own
`rejected_gap_negating_total` / `last_scan_rejected_gap_negating` pair,
so the new arm's rate is measurable separately from the arm it extends.

Calibrated against the live 2432-section `audit-patterns.md` corpus
(2275 of which pass the older shape gate): 12 rejections, every one
reading "No gap …" / "Not a gap …" in its own words. `nothing` was
measured OUT of the negation list — it rejected a REAL gap whose block
opened on a quotation ("Nothing is actively running on my side"). Three
of the 12 read "No gap in this instance, but the pattern worth noting is
…" and are rejected deliberately: the promotion question is whether
there is a behavioral gap worth writing into a cabinet member, and a
body that opens by saying there isn't one has answered it.

Unlike the two dedup corpora it shipped beside, this arm is an
**opt-OUT** (`defaults.pattern_gap_assertion !== false`). It is a defect
fix to a gate that already rejects on shape; the flag exists so it can
be turned off if it over-rejects, not so it has to be turned on.

## Extraction Noise Immunity (act:471941c9)

Five coordinated rules, all grounded in one 105-item drain on 2026-07-30
where a fifth of what the system "kept" was duplicating git, pib-db, or a
project's own designated authority file.

- **Bookkeeping is never knowledge.** Ring 3 Phase 2d suppresses an
  extraction whose TITLE substance is a commit sha, a merge event, a
  version bump/release, a filed-as-`act:` record, or a queue-disposition
  record (`bookkeepingRule` in `watchtower-ring3-close.mjs`). Git and
  pib-db already hold those facts. Title-gated ON PURPOSE: a genuine
  lesson that merely mentions a sha in its body is not bookkeeping. Each
  suppression logs its RULE NAME and appends a ledger line under
  `bookkeeping:<rule>`, so the cause is attributable and the recall
  canary can see it. The extraction prompt carries the matching
  generation-side exclusion — mechanical gate plus prompt, the same
  two-sided shape as the pattern-promotion gate.
- **A declared authority beats memory.** A project may name one file as
  THE authority for a knowledge class, via `authority_paths` in
  watchtower config — per-project first, then `defaults`:
  `"authority_paths": { "constraint": "docs/cowork-capabilities.md" }`.
  A memory- or claude-md-bound extraction of that TYPE is filed with
  `home: 'authority-file'`, `evidence.authority_path`, and a first option
  naming the path. It is a ROUTING, never a suppression — the item is
  still filed, still drafted, still triaged — and nothing writes to the
  authority file automatically (a file with a validator behind it is not
  something a cron job should edit).
- **Duplicate flags are strictly pairwise; clusters are computed once.**
  `evidence.possible_duplicate_of` is a claim about ONE pair and MUST NOT
  be chained — similarity is not transitive, and a transitive closure of
  75 flags produced a single 70-item blob of unrelated drafts.
  `buildFoldClusters` (watchtower-queue) computes the group view once at
  detection time with a SIZE bound and a DENSITY bound, so a chain can
  never present as a cluster; consumers read
  `evidence.duplicate_cluster` (or its explicit `null` plus
  `duplicate_cluster_rejected: 'oversized' | 'chained'`).
- **Dedup sees memory FILES, not just the index — and proposes more than
  it suppresses.** `loadMemoryCorpus` reads every memory file's own
  descriptive title and description line, because a consolidated memory's
  MEMORY.md title is slug-derived and carries almost no content tokens
  (the reason one project re-learned eight themes for four days). The
  expansion feeds the M1b novelty PROMPT in full (`title — description`);
  the lexical SUPPRESSION half additionally requires NEAR IDENTITY
  (`MEMORY_FILE_MIN_RATIO`, the same 0.8-of-the-shorter bar
  `mergeChunkExtractions` uses). **This split is measured, not stylistic:**
  feeding the expanded corpus into the ordinary 3-token pass suppressed
  72% of one project's untriaged drafts (from 17%), and reading the
  matches showed ~2 in 14 were real. Raising the token threshold
  destroyed true positives faster than false ones; normalizing to a ratio
  did not separate the distributions at all (the presumed-novel set
  scored HIGHER on median). The house rule stands: **a lexical matcher
  over a large corpus may propose, never silently suppress.**
- **At scale, offer a classification pass.** When `/inbox`'s individual
  set reaches `INBOX_CLASSIFICATION_THRESHOLD` (30), the per-item walk
  stops being a real offer. `groupItemsByShape` groups by
  category/type/home/urgency, largest-first, and the skill walks ONE
  group decision at a time, applying each through a single `applyBatch`.

## Worktree Coverage Is Reported, and a Dismissal Is Suppression Input (act:6dcb8015)

Two field reports, one detector, two distinct root causes — both named from
the live queue and live git rather than inferred.

- **The re-fire was a PENDING-ONLY dedup, not an ancestry failure.**
  `hasUnmergedContent` already tests ancestry first and got the reported five
  RIGHT: every item carries `evidence.unmerged === false`, `ahead === 0`, and
  was filed for ONE uncommitted file. The dedup consulted `listPending()` only,
  so a dismissal left the corpus and the next tick refiled a byte-identical
  item (dec-1d7706dd dismissed 2026-07-29T23:05:39 → dec-59afb639 filed
  2026-07-30T13:16:46). That is Detector Symmetry §2's named failure.
  `fileOrphanedWorktreeItem` now also consults recently
  resolved/dismissed/expired/superseded items (`WORKTREE_DEDUP_DAYS = 14`,
  deliberately shorter than the 30-day expiry so an item can never leave every
  corpus at the moment it expires). **Suppression is conditional on UNCHANGED
  STATE**: a register escalation — a merged-but-dirty worktree that later gains
  real unmerged commits — files regardless of any dismissal, because a
  dismissal answers the question it was asked, not every future question about
  the same branch.
- **The coverage hole was the ACTIVE-WINDOW filter, and it was silent.** Every
  per-worktree skip was an uncounted `continue`, so an unscanned worktree and a
  clean one rendered identically. `scanWorktrees` now returns
  `{orphaned, coverage}`; the coverage counts what was listed, scanned, filed,
  and skipped by reason, and `renderWorktreeCoverage` puts "checked N of M
  worktrees" in Standing Issues — plus a loud "the scan did NOT run" line when
  it did not. Ambient state, so it lives in the state file, not the queue.
- **Real unmerged commits behind an open window are surfaced, never filed.** An
  active worktree is not orphaned and must not become an inbox item — nagging
  about work in progress is the noise the filter exists to prevent — but a
  six-commit branch sitting behind a window for days is exactly the reported
  miss. It now renders on its own Standing Issues line saying plainly that the
  branch is NOT merged.
- **Activity is detected by pane path first.** A tmux pane whose cwd is inside
  the worktree is unambiguous. The legacy window-name match is kept as a
  fallback but is global and prefix-stripped (`reflow-internal-notes` and
  `maginnis-internal-notes` both yield `internal-notes`), so a window open in
  ANY desk suppresses a same-named worktree in EVERY project — which is why the
  suppression must be counted rather than trusted.

## Completion Review Answers "Is It Finished", Not "Did It Change" (act:86226720)

Phase 2c sent the model `fid: text (status)` and nothing else — it had never
been shown an action's NOTES, so it had never been shown the action's own
definition of done. It could only answer "did something change here". Ten
items in one 2026-07-30 drain proved the cost: all ten open/in-progress with
`completed=0`, all ten blocked on the same external event, none closeable.

- **The action's notes are now in the prompt.** Each open action is presented
  with an `acceptanceCriteriaExcerpt` — the AC section when the notes have one,
  otherwise the head of the notes, bounded because every open action is sent.
- **The gate has two arms.** Mechanical: unchecked `- [ ]` boxes suppress.
  Model: `ac_status: met|unmet|unstated` suppresses on `unmet` **only with a
  VERBATIM cited criterion** (`ac_unmet`) — an uncited "unmet" is an assertion,
  not an answer, and is counted separately rather than silently downgraded.
- **"No acceptance criteria" is NEVER "unmet."** 150 of the 171 noise items in
  the measured corpus cite an action with no checklist at all; reading absence
  as failure would suppress the whole category.
- **Gating is safe here specifically** because "a missed completion is
  recoverable next session, a missed lesson is not" (this file's own
  transcript-budget rationale). Phase 2c re-runs against still-open actions, so
  an over-suppressed candidate comes back. That asymmetry is why quote
  verification ships as instrumentation and this ships as a gate.
- **Observability is the contract**, not a nicety: one log line per suppressed
  candidate naming WHICH arm fired, a per-session verdict tally
  (`met/unmet/unstated/unknown/unmet-uncited`) so "no suppressions" is
  distinguishable from "the model never answered", and `evidence.ac_status` +
  `ac_unmet` + `ac_boxes_present` stamped on every EMITTED item — the join key
  the next precision measurement needs.
- **The act:ea23b3a5 calibration fence is intact.** That measurement is fenced
  to "the Phase 2c confidence rubric AS WRITTEN". `ac_status` is an ADDITIONAL
  field; the four confidence lines are byte-identical and a test asserts it.

**Measured before shipping (the discipline this category already learned the
hard way), and the measurement REFUTED the proposed fix.** The report asked to
suppress on unchecked `- [ ]` boxes. Against the live queue: **zero** of the
reporting ten cite an action with an unchecked box — that project writes its
criteria as prose — and portfolio-wide only **8 of 247** completion-review
items ever filed cite one at all, of which 5 were noise and **3 were real
completions** (62% noise against a 73% baseline, i.e. mildly ANTI-predictive,
the same shape found for `confidence: high`). Every other mechanical signal
measured flat: confidence (20/32/26% against a 26% baseline), an explicit
`blocked` status (zero actions in the entire corpus use it), an
external-blocker phrase in the notes (23% vs 27%). The checkbox arm ships
because it is the literal acceptance criterion and costs ~1 blocked true
completion a month; the model arm is what actually addresses the reported
failure, and it ships instrumented precisely because it is unmeasured — the
model had never been asked this question, so no prior corpus could exist.

## Prospective Commitments (act:aa554774)

**The rule: can this wait in a queue for a week without cost?** Everything
`/close` delegates to the rings is retrospective — lessons, decisions,
knowledge — and losing a day costs nothing. A **prospective, time-bound
commitment made during the session** has a clock, and the inbox it would
land in has been 275 deep with a 26-day tail. Technically captured,
practically lost.

- **`/close` Step 6b files them forward.** Bounded to prospective, dated
  obligations ONLY — never an inventory, never a lesson sweep — and ONE
  AskUserQuestion naming each commitment concretely, so approval is of
  specific obligations rather than a count. `due` for a calendar deadline,
  `trigger_condition` for an event ("when the device arrives"). **Nothing
  qualifying means nothing is said**: the common path adds zero seconds.
- **Ring 3 declines to duplicate them.** Phase 2d loads the actions this
  project created on the session's date and suppresses a
  COMMITMENT-SHAPED extraction that one of them already covers, logging
  the covering fid and ledgering under `commitment-already-filed`. Scoped
  to commitment-shaped items on purpose — a general "does any action
  created today share words with this draft" test would eat ordinary
  knowledge. The window is the calendar DAY because `actions.created` is
  a date with no time component; the sweep files minutes before the ring
  runs, and midnight-crossing sessions are covered by taking everything
  created on or after the session-start date. Fails OPEN — a db hiccup
  costs one dismissable duplicate, where failing closed would silently
  drop a commitment.
- **One definition, both sides.** `watchtower-commitments.mjs` owns the
  screen (a temporal cue AND an obligation shape AND no settled marker)
  and the match (`findFiledCommitment`, overlap coefficient at 0.6 over
  the queue's fold tokenizer). The skill and the ring must never fork it.
- **Anti-pattern, stated in `/close` and `/session-handoff`:** never write
  a commitment into the notes of an action being marked completed. Closed
  items don't surface, so it reads as filing and functions as deletion. A
  commitment gets its own open action, or it does not exist.

## Reach 1 — Pending-Relation Proposals (act:5182beda, N3 of grp:retro-remeaning)

The first shippable instance of **retrospective temporality** (`act:ef5a3842`,
MANIFESTO principle 4): new understanding reaching BACK to recolor what came
before, at the earliest and safest reach — the still-pending inbox, where
nothing is believed yet. Every specimen that motivated the program had its
counterpart sitting pending at the moment the second one was written; Phase
2d's extraction call now sees that pending pile and can propose a relation.

**Mechanism.** `selectNearbyPendingItems` (ring3-close.mjs) shortlists the
pending inbox drafts most relevant to THIS session's transcript (same
relevance-scoring recipe as `selectNearbyMemoryTitles`, a SEPARATE corpus
with its OWN cap, `PENDING_RELATION_CAP` — never a shared budget with
memory's, or a large pending pile would evict memory titles and degrade the
M1b novelty gate). The extraction prompt's `PENDING IN INBOX` block is
injected as its OWN section, distinct from `ALREADY SAVED TO MEMORY`. For
each item, the model may set `relates_to` (the exact pending title) and
`relation` (`pairs_with` | `answers` | `contradicts`) — fields the model
outputs ALONGSIDE, never IN, `covered_by`. This separation is load-bearing:
`covered_by` stays scoped to memory titles and feeds `modelRescues`/
`isDuplicate` exactly as before; `relates_to`/`relation` are never read by
either — naming a pending title in `covered_by` instead would flip the
rescue gate into a suppressor (a filed-today item wrongly read as "covered
by," and suppressed, because it topically resembles a merely-PENDING draft
that isn't believed yet — the exact failure the Meta question/answer
specimen would have suffered).

**Filing.** A relation proposal is its own inbox item, category
`pending-relation`, filed via `fileRelationProposal` AFTER the newly-
extracted item's own `createItem` call succeeds (its id isn't known until
then). Deduped by `evidence.relation_key` (sorted ids + the relation verb) —
one pending item per (pair, verb), so the same relation proposed from either
side, or in a later session, never refiles. The proposal never changes
anything about the item that prompted it: no suppression, no home change, no
urgency change — it is strictly additive.

**The M5 suppression ledger is blind to this channel.** `recordSuppression`
(the Suppression Ledger above) only sees LEXICAL suppressions — the
deterministic `isDuplicate` corpus matches. The model's real per-item
inclusion/omission decision happens INSIDE the extraction call, in a channel
the ledger cannot observe at all: if the model chose to silently omit an
item from its output array (rather than including it with `relation: none`),
no suppression record is ever written, because nothing was suppressed BY A
CORPUS — it was never proposed. This is why the prompt carries an explicit,
load-bearing instruction that a pending item is grounds for a RELATION only,
never grounds to omit or demote anything — the instruction is the entire
defense, because the suppression ledger cannot audit it.

**Retraction.** Registered in `INBOX_DETECTOR_REGISTRY` with a reconciler:
`autoReconcilePendingRelations` (ring1.mjs, one global pass per tick — purely
queue-internal, no per-project pib-db access, unlike `completion-review`'s).
Retracts via `autoReconcileItem` when EITHER cited side (`evidence.from_id`
/ `evidence.to_id`) leaves pending — a relation between two open questions
no longer applies once one resolves. Fails toward KEEPING: an id that no
longer resolves via `getItem` (deleted/migrated) is ambiguous, not evidence
the relation resolved.

## Reach 2 — Significance-Change Proposals (act:bcb7edd4, L1 of grp:retro-remeaning)

The second reach of the retrospective-temporality motion (`act:ef5a3842`,
MANIFESTO principle 4), extending Reach 1's inbox-range reach-back to the
recently-absorbed thread trail. When Ring 3 closes a session, the new
understanding it captured reaches BACK into the prior cursor history of the
threads THIS session touched, and may PROPOSE that an earlier entry now
means something different: `reframes` (significance change — what looked
like friction was the seed of the architecture; the class a contradiction
scan is structurally blind to), `answers` (a real earlier uncertainty is
settled), or `contradicts`. Category: `significance-change`.

**Mechanism.** Inside Phase 2b2, AFTER the cursor appends land: the prior
trail of each earned thread is snapshotted from disk BEFORE this session's
entry is appended (last `PRIOR_HISTORY_CAP` entries), and one focused
follow-up model call (`significanceReachBack`) sees the new understanding
beside each prior trail. It fires only when at least one earned thread has
prior history — a routine or first-touch session costs nothing. It cannot
ride the capture call the way Reach 1 rode extraction: the reach-back
corpus (which threads matter) IS that call's output. EVENT-DRIVEN by
construction — never a periodic sweep (the shape the cabinet killed).

**Proposals are validated, then durably deduped.** A proposal must cite an
ACTUAL prior entry — session_id + date checked against the on-disk snapshot
(`validateRecolorProposals`); a hallucinated anchor drops, logged, never
filed. Filing (`fileSignificanceProposal`) dedups by
`evidence.relation_key` (`thread|prior_session|new_session|verb`) across
ALL queue statuses with NO time window: a dismissed or expired judgment
about a static corpus never re-nags — not after `RESOLUTION_CORPUS_DAYS`,
not ever — and a reprocess replay of the same session produces the same key
and files nothing. (The same unwindowed-exclusion discipline was backported
to Reach 1's `fileRelationProposal`, whose original pending-only dedup
left a post-dismissal refile hole.)

**The gate is real, not ceremonial.** Both relational categories
(`significance-change`, `pending-relation`) are in `GATED_CATEGORIES`:
`applyBatch` structurally refuses them, so each reinterpretation is
confirmed or dismissed individually — a rubber-stamped batch of re-meanings
is how a system gaslights its operator. On CONFIRM, /inbox applies the
recolor via `appendThreadRecolor` (watchtower-lib): an entry in the
thread's additive `recolor_log` array. The recolor ANNOTATES history — it
never rewrites `cursor_history`, and no ring ever writes `recolor_log`;
the rings propose, only the operator's confirmation applies.

**Retraction.** `autoReconcileSignificanceItems` (ring1, per tick):
retracts when the cited thread file is POSITIVELY gone from
`state/threads/` (dir readable, file absent — a recolor of deleted history
is moot); keeps on any read error, and keeps EVERYTHING when the dir is
unreadable (a mount hiccup must not mass-retract).

**The honest metric that gates Reach 3.** Every real-work close appends one
line to `state/significance-ledger.jsonl` (`recordSignificanceEvent`,
fail-open, same discipline as the suppression ledger): session, threads
touched, threads with history, entries shown, proposals filed.
`readSignificanceRate` (watchtower-lib) combines the ledger (denominator,
replay-deduped by session_id) with the queue's per-category dispositions
(numerator) into `{sessions, proposals_per_session, keep_ratio, …}` — with
null ratios when a denominator is zero, never fabricated 0s. This is the
L2 gate's named reader: Reach 3 (`act:a8b372a7`) is built only when an
observed significance-change rate on real data warrants it — replacing the
contradiction-density measurement the plan retired as the wrong instrument.

## Detector Symmetry (no detector without a retraction path)

The 2026-07-12 inbox drain (893→194 pending) hit the same disease four
times in four detectors: branch-diverged never retracted (35/39 stale),
completion-review never reconciled (28/66 moot), worktree-unmerged
retracted only on branch deletion, and dismissed items refiled on the
next tick because dedup checks only PENDING items (the `backup/*` loop
refiled within hours, twice in one day). `autoResolveWorktreeItems`'
own comment states the principle: dedup suppresses refiling but nothing
retracts the original — **stale alarms train the operator to ignore
real ones**. This contract encodes the rule so detector #5 cannot ship
with the same bug (grp:wt-noise-immunity, act:4d11fd53).

**Every detector that FILES an inbox item must declare, at ship time:**

1. **Its retraction condition** — the mechanical, per-tick check that
   the filed condition no longer holds (branch merged/gone, action
   closed, …). Retraction is truth-checking, not judgment: it runs in
   Ring 1's tick beside the other reconcilers.
2. **Its filing exclusions** — states that must never file, checked at
   the FILING site (not just retraction) so a human dismissal cannot
   reopen the loop: dedup consults only pending items, so an excluded
   state that files at all refiles after every dismissal, forever.
3. **Or an explicit exemption** — a detector with no possible
   mechanical retraction (pure knowledge extraction, advisory
   observations, session-historical facts) declares that explicitly in
   the registry, with the rationale.

**The registry and its enforcement:** `INBOX_DETECTOR_REGISTRY` in
`watchtower-lib.mjs` maps every ring-filed category to
`{ reconciler }` or `{ exempt }` (exactly one). A structural test
(`templates/scripts/__tests__/detector-registry.test.mjs`) parses the
`category:` literals at `createItem` filing sites across ring1, ring2,
and ring3-close (read-only source scan, house precedent:
suppression-ledger's wiring assertion) and fails the suite when a
filing site's category is missing from the registry — a new category
without a declared reconciler or exemption breaks the build, not the
operator's trust.

**Machine resolutions are machine acts, not engagement.** Every
auto-retraction resolves through `autoReconcileItem` (watchtower-lib):
`resolution_type: 'auto-reconciled'` + `evidence.actor: 'ring1'` + a
note naming the evidence (action fid / branch). The cross-ring reader's
engagement bucketing and the inbox assessment's `worked_recent` EXCLUDE
this type — cron sweeps must never read as operator engagement or
suppress the not-consumed verdict. A semantically-wrong close (e.g. an
action closed via the ungated `pib_update_action --status done` path)
stays traceable to its mechanical trigger through the stamp.

**Fail-toward-keeping.** A reconciler retracts only on POSITIVE
evidence that the condition cleared: branch absence is concluded only
from membership in a successful branch listing (a failed git call
retracts nothing); an action-fid lookup retracts only on a FOUND,
non-deleted, closed row — fid-not-found keeps the item, which is
load-bearing for flow (a readable-but-vestigial pib.db; the real
tracker is flow.db) and for misattributed items whose fid lives in a
different project's db. Foreign pib.dbs are opened READ-ONLY behind an
existsSync guard; reconciler writes land only in the watchtower queue.

**Branch exclusion list:** `defaults.long_lived_branches` (watchtower
config), default `["staging", "production", "backup/*"]`. Entries
without `*` are EXACT names (`staging-fix` files normally); `*` is a
glob. **Consumer-default risk, documented:** a consumer whose real work
branch is literally named `staging` or `production` will never get a
branch-diverged item for it — the branch stays visible on the attention
line / git-attention sidecar / summary / Standing Issues (the exclusion
gates filing ONLY), and the consumer overrides the list in config.

**Standing-debt aggregation (coverage-warning, memory-budget):** a
detector whose finding is a STANDING condition (recurs while a debt
persists) files ONE item per (project, debt-class) and APPENDS evidence
to the pending item, carrying `evidence.first_seen` (oldest evidence
date) so aging reads the debt's true age. Resolving the item closes the
accumulated view; if the debt persists, the next tick files FRESH —
post-disposition recurrence is a new signal, not a refile loop
(act:e888dd63; 49 identical coverage-warning items for one month-old
debt was the live specimen).

Three rules the second adopter (memory-budget, act:ea23b3a5) added, each
learned from a live failure mode:

1. **The occurrence key must be the operator's unit of time, not the
   ring's.** coverage-warning keys on the session; memory-budget keys on
   the CALENDAR DAY, because Ring 2 slow runs ~48 times a day. A per-run
   key makes the replay guard dead code, grows the key list by ~17,500
   entries a year inside one JSON file, renders a count no human can
   read, and — because the backlog-rot reader weighs standing debt by
   that count — poisons the `keeping` / `losing` / `not-consumed` verdict
   `/inbox` and `/briefing` lead with.
2. **Reuse an evidence spelling the readers already know.** The rot
   weigher (`itemSessionWeight`, watchtower-inbox-assessment) accepts
   `session_count` / `session_ids` / `sessions` and silently weighs
   everything else as 1. A new adopter that invents a fifth spelling
   reintroduces the blind spot the fourth was added to fix. memory-budget
   writes `session_count`.
3. **Prefer `annotateItemEvidence` over a direct item write, and do not
   bump `filed_at` without a reason.** The append gets a fresh read, a
   pending fence checked at write time, and a deep-equal skip for free.
   Bumping `filed_at` has three side effects worth choosing
   deliberately: it strips an `[AGING]` prefix the escalation pass added
   (and prevents its return), it re-escalates urgency the decay pass
   de-escalated, and — since `listPending` sorts by `filed_at` — it pins
   the item to the top of every pending list permanently. coverage-warning
   bumps on purpose (its expiry clock should measure the last
   recurrence); memory-budget does not.

**What does NOT aggregate.** `doc-drift` carries a per-claim,
mutually-exclusive fix-doc / fix-code decision, so N claims folded into
one item pose a question the operator cannot answer, and any reconciler
over the aggregate could only fire when every claim cleared.
`raised-unhandled` is free text: recognizing "this loose end restates
that one" needs a similarity matcher, and `proposeFolds`'
`overlapCoefficient` at `FOLD_SIMILARITY_THRESHOLD = 0.22` folds two
three-token titles that share ONE word — calibrated for advisory
retrieval, not for a destructive merge. Both instead route through Ring
2's `runDraftAnnotationSweep`, which annotates both sides with
`possible_duplicate_of` and demotes them out of batch sign-off. **A
lexical matcher may propose; it may never silently suppress.**

## Category Expiry

Every pending item ages out on a per-category policy. The table and its
helpers live in `watchtower-queue.mjs` (`expiryDaysFor`,
`categoryNeverExpires`, `CATEGORY_EXPIRE_DAYS`) — read the constants
there for the numbers; mirroring them into this document would be a
count claim that drifts, in a repo whose Ring 4 files `doc-drift` items
for exactly that.

**There are TWO expiry engines and both must delegate.** Ring 2's
`escalateQueueItems` runs on the 5-minute cron; `runExpiry` is called by
`/inbox` and `/briefing`. Before act:ea23b3a5 each hardcoded 30 days and
inlined its own qa-handoff carve-out, so a per-category policy set in one
would be silently violated by whichever engine reached an item first.

**The qa-handoff exemption is structural, not a preference.**
`expireItem` THROWS on a qa-handoff by the recipient-gate contract, so
`categoryNeverExpires` lives beside that throw: returning anything but
null for it would crash the caller's loop. One fact, one place.

**A shortened expiry can open a refile loop.** completion-review expires
at 14 days, which equals `COMPLETION_REVIEW_DEDUP_DAYS`. An item
therefore leaves the dedup window at exactly the moment it expires — so
Phase 2c's dedup corpus must include `expired` and `superseded`, or the
fid is in no corpus at all and the next session refiles it forever. That
is Detector Symmetry §2's named failure, reached from the other
direction: **when you shorten a category's expiry, check what its filing
site dedups against.**

## Queue Items Require a Decision; Ambient State Describes Conditions

A queue item asks the operator to decide something. A per-project state
file describes a condition. Filing a condition as an item spends the
operator's scarcest resource — a triage slot — on something they can
only acknowledge.

**The axis is who is judging, not whether the value is recomputable.**
Recomputability is the wrong test and would contradict a rule this
system already ships: derivable and perishable facts (act:471dd701,
act:a69c21f8) are recomputable *by definition*, and they are **always
filed** — routed to their derivation or the session record, never
dropped — because that routing is a per-item MODEL judgment, and
dropping one would be silent model auto-suppression. A deterministic
ring measurement is different in kind: the operator routes it once, by
category, and the routing holds.

**The functional test: does waiting cost something irreversible?**
`worktree-unmerged` is the calibrating counter-example. Ring 1
recomputes it from git every five minutes, so by a recomputability rule
it would be pure ambient state — and it must stay in the queue, because
the worktree gets cleaned up and the work is gone. A recomputable
condition with decay belongs in the queue; a recomputable condition that
is stable belongs in ambient state.

**The calibrating pair (act:ea23b3a5).** The cabinet-roster review
produces three signals. `uncovered-tech` names a specific per-project
gap and proposes adding a cabinet seat — a decision, so it stays a queue
item. `dormant-skill` and `stale-briefing` are measurements, so they
moved to `state/roster-review.json` and render in Ring 1's Standing
Issues.

Three obligations come with moving something to ambient state:

- **Fix the measurement first.** The dormant-skill count was a saturated
  display cap: every project ever measured reported exactly "12 dead",
  because the title was built from an array already sliced to
  `ROSTER_DORMANT_LIST_CAP`. Moving that into seven state files would
  have given a constant the authority of a fact.
- **Render on change, or give it a firing threshold.** Ambient state has
  no dismiss verb — the queue item at least had one. A number that never
  moves in a file read at every briefing is furniture by the third read.
  The precedent is the recall canary, which Ring 1 renders only on alert.
- **Retire what is already filed.** The filing site was usually the only
  code that ever touched those items. Removing it without a one-shot
  supersede leaves them displaying a stale count for weeks beside a live
  ambient line saying something different — dual existence.

**Known limitation (named, not hidden):** reconcilers run per
configured project — items whose project was deleted or de-registered
are never visited and age pending until a human disposes them (the
inbox's aging surfaces them). Auto-resolving on "project gone" would
guess; the honest state is pending.

## Deferred Schemas

The following are specified in project notes but NOT formalized until
their owning plan ships:

| Schema | Owner | Ships with |
|--------|-------|-----------|
| `messages/<session-id>.json` | Plan 8 | Session-directed messages |
| `ring3/cursors/<session-id>.json` | Plan 7 | Ring 3 live mode |
| `hooks/<ring>-<phase>.d/` | Plan 9 | Lifecycle hooks |
| `logs/<ring>.log` | Plan 4 | Ring 1 runner |
| `lock/<ring>.pid` | Plan 4 | Ring 1 runner |

## Ring 4 — Periodic Truth Reconciliation (design phase)

> **Superseded — stage 1 BUILT (act:36dae795).** This is the original design
> note, kept for its problem framing. The shipped implementation is documented
> below under "Ring 4 — Truth Reconciliation (built, stage 1)"; read that
> section for current behavior. The "concept" status line below describes the
> pre-build state only.

**Status: concept. Needs design session before implementation.**

Rings 1–3 operate on individual signals: individual files (R1),
individual patterns (R2), individual sessions (R3). Nothing catches
**cumulative drift** — the slow rot where twenty sessions each move
reality a little further from what documents claim, but no single
session is the tipping point.

Ring 4 is the answer to: "Is what we wrote still true?"

### The problem it solves

The maginnis project's architecture briefing said "Layer 4 Not built"
and "tech stack TBD" for three weeks after the platform shipped with
a Rails 8 app, Mantine frontend, 421 RSpec specs, and staging on
Railway. No individual session caused the staleness. No individual
session's debrief would flag it. The drift was invisible until
someone tried to use the briefing for a real audit and found it
described a project that no longer existed.

This class of problem includes:
- **Briefing-to-codebase drift** — claims about architecture, tech
  stack, file layout, or project state that no longer match reality
- **Memory-to-codebase drift** — memory files that reference
  functions, files, or flags that have been renamed or removed
- **CLAUDE.md drift** — sections describing architecture or
  conventions that have been refactored past
- **Plan-to-reality drift** — plan files describing work that's been
  done but never marked complete, or describing approaches that were
  abandoned

### Cadence and weight

Less frequent than R1–R3. Daily or weekly, not per-session or
per-minute. Heavier per run — reads real code, cross-references
document claims against codebase state, may invoke Claude for
semantic comparison. Acceptable cost because it runs rarely and
catches problems that compound silently.

### Relationship to other rings

Following the nervous system principle (not a stack): R4 consumes
signals from R1–R3 (what changed recently, what sessions touched,
what patterns emerged) to prioritize what to reconcile. R4 produces
inbox items when drift is detected. R4 does not mutate documents —
it flags, the user triages and routes.

R3 catches "this session broke the briefing." R4 catches "the
briefing has been slowly wrong for three weeks and nobody noticed."
They're complementary, not redundant.

### Open design questions

- **Scope per run:** Reconcile everything every time, or rotate
  through documents on a schedule? Full sweep is thorough but
  expensive; rotation risks missing urgent drift on off-cycle docs.
- **Drift threshold:** How wrong does a document need to be before
  it's worth flagging? A missing model in the architecture briefing
  is clear; a slightly outdated line count is noise.
- **Trigger vs schedule:** Pure schedule (weekly), or also triggered
  when R1/R2 detect significant codebase changes (new migration,
  major refactor, new dependency)?
- **Cross-project scope:** Per-project reconciliation, or also
  cross-project (e.g., a CC template claiming something about
  consumer behavior that's no longer true)?
- **Relationship to Ring 2 slow tier:** R2 slow already does some
  staleness detection (stale work, memory hygiene). Where's the line
  between R2's "is this work item stale?" and R4's "is this document
  still true?" Is R4 an extension of R2 slow, or genuinely distinct?

## Ring 4 — Truth Reconciliation (built, stage 1)

**Status: BUILT (act:36dae795). Supersedes the design-phase section
above** — the open design questions there are now resolved here.
Implemented in `templates/scripts/watchtower-ring4.mjs` (the ring) +
`templates/scripts/watchtower-ring4-runner.sh` (PID-locked runner,
modeled on the Ring 2 runner). Hermetic suite:
`templates/scripts/__tests__/ring4-reconcile.test.mjs`. Cron/launchd
registration is a `/watchtower install` follow-up, not part of this
build.

### What it does

Periodically compares documentary CLAIMS against codebase REALITY and
files drift as `doc-drift` inbox items. Reconciliation is COMPARISON,
NOT generation — Ring 4 never rewrites a document; it flags drift with
enough context to fix, and the operator triages it. Stage 1 is PURELY
MECHANICAL (no Claude API call), which keeps the cron cheap and the
ring hermetically testable.

It owns two ledger duties at orient/debrief retirement
(`orient-debrief-coverage-ledger.md` §C/§D): documentation staleness
(CLAUDE.md key-file claims, briefing files, system-status) and the
dropped embedded-pulse description-accuracy spot checks (counts). The
standalone `/pulse` stays invocable on demand.

### Resolved design questions

- **Scope per run → rotation, not full sweep.** Each run reconciles at
  most `RING4_PROJECT_CAP` (3) projects, least-recently-reconciled
  first, BUT a project with commits since its last reconcile jumps the
  queue. This is the nervous-system principle in mechanical form: R4
  consumes R1's signal (git recency) to prioritize, rather than
  blind-sweeping the portfolio. State in `state/ring4-reconcile.json`
  (`last_run`, `projects_checked`).
- **Drift threshold → mechanical existence/counts, high precision.**
  Stage 1 flags only (a) a backtick-fenced repo-relative path that is
  missing on disk, gated so the path's TOP-LEVEL directory still
  exists (kills illustrative/foreign-path noise — `webapp/...` in a
  CC memory file is skipped because `webapp/` isn't a repo dir) and
  not gitignored (a gitignored absent path is a generated/local
  artifact — its absence is expected, not drift); and (b) a count
  claim that disagrees with a mechanical file count, but ONLY for
  config-declared count rules (zero-noise default). A "slightly
  outdated line count" is deliberately NOT flagged.
- **Trigger vs schedule → weekly cadence + git-recency priority.** A
  weekly gate (`RECONCILE_INTERVAL_DAYS`, mirrors Ring 2's roster
  review) plus git-recency-driven project order, rather than coupling
  to R1/R2 internal trigger files.
- **Relationship to Ring 2 → genuinely distinct ring.** R2 slow asks
  "is this WORK ITEM stale?" (pib-db state); R4 asks "is this DOCUMENT
  still true?" (doc claims vs codebase). Distinct cadence (weekly vs
  30-min), distinct runner/cron, distinct produced category.
- **Cross-project → per-project only, stage 1.** A CC template
  claiming something about consumer behavior is a documented future
  extension, not built.

### The document set (current-reality docs only)

`collectDocuments()` scans docs consumed AS TRUTH, capped at
`RING4_DOC_CAP` (40): root `CLAUDE.md`, `system-status.md` (root and
`.claude/`), `.claude/cabinet/_briefing*.md`, and the project's
built-in memory entries (`MEMORY.md` + curated `*.md`). It
deliberately EXCLUDES `.claude/plans/` and `.claude/methodology/`:
those are HISTORICAL records — a plan for retired work SHOULD
reference now-deleted files, so path-existence over them is mostly
noise (the CC dogfood produced ~90 false claims from historical plans;
filtering to current-reality docs + gitignore-awareness cut it to 2
real findings). Whether a plan is actually DONE — plan-to-reality
drift — is a distinct SEMANTIC check, deferred.

### Memory is DRIFT-SUPERSEDE only

The memory pass is the missing-path reconciler applied to memory files
("is what we wrote still true?" — entries referencing renamed/removed
files). Paths in a memory file resolve against the PROJECT root, not
the memory dir. Memory HYGIENE (budget / decay / consolidate) stays
Ring 2 slow's `runMemoryHygiene` / `surfacePersistentViolations` —
Ring 4 does NOT fork a second memory-health producer (act:36dae795
2026-06-16 scope note; design in `cross-store-memory-redesign.md`).

### Inbox contract

Findings file `doc-drift` items (`filed_by: 'ring4'`, urgency `low`,
three triage options: fix-doc / fix-code / dismiss). Dedup is ONE
pending item per `evidence.drift_key` per project — `path:<doc>` for
missing-path, `count:<doc>:<label>` for count-mismatch (mirrors Ring
2's `roster_kind` convention: a still-open drift item is a reference,
not a duplicate). At most `RING4_ITEM_CAP` (8) items filed per run.
`doc-drift` is NOT a dispatched or gated category — it is a plain
inbox item the operator triages. The weekly cadence + per-doc dedup
keep re-nagging bounded.

### Config

Feature flag `defaults.truth_reconciliation` (default true) gates the
whole ring; `ring_frequencies.ring4` (604800 = weekly) carries the
intended cron interval. Count rules are per-project and opt-in:
`projects[<name>].reconcile.count_rules = [{ label, doc, pattern,
glob }]` where `pattern` is a regex source with one capture group
around the number and `glob` uses the small dependency-free grammar in
`countGlob` (`dir/*`, `dir/prefix-*/`, `dir/*.ext`, `dir/**/*.ext`).
Default empty → the count pass no-ops (no false drift).

### Deferred (future stages)

Semantic comparison (does this prose paragraph still describe the
code?), plan-to-reality / plan-status reconciliation, dependency-
version drift beyond the count-rule mechanism, gitignored-directory
patterns that don't match a non-existent path, and cross-project
template-vs-consumer reconciliation.

## Consumer Hook Contract (Plan 9)

The formalized extension model for **non-interactive** consumer customs at
the ring lifecycle seams (act:4a6e907c). Supersedes the deferred-schema
placeholder `hooks/<ring>-<phase>.d/` above — the real location is
per-project, not a global runtime dir. Interactive customs are owned by
routine dispatch (act:c2a55c08, "Routine Dispatch" above), never by hooks.

### Seams and invocation

The rings already invoke consumer hooks by running each command string in
`config.hooks[<seam>]` with the ring's state JSON on stdin. Three seams:

| Seam | Ring / scope | Outer timeout |
|------|--------------|---------------|
| `ring1-post-collect` | Ring 1, per project, post state-collect | 30s |
| `ring2-slow-post` | Ring 2 slow tier, portfolio-wide | 60s |
| `ring3-close-post` | Ring 3, per session close | 120s |

`watchtower-hook-runner.mjs --seam <seam>` is registered ONCE per seam (via
`--register`, called by `/watchtower install`). The rings invoke it like any
hook command — the rings are NOT modified. The runner then resolves the
target project(s) and runs that project's hook scripts.

### Registration (drop-a-file)

A consumer registers a hook per-project by placing an executable script in
`<project-root>/.claude/watchtower/hooks/<seam>/`. Presence is registration —
no config editing. Discovery is name-sorted (numeric-prefix convention:
`10-foo.sh` before `20-bar.sh`). A file is runnable if it has the executable
bit (run directly, shebang decides the interpreter) or a known extension
(`.sh`/`.bash` → bash, `.mjs`/`.js`/`.cjs` → node, `.py` → python3); other
files (`.json`, `.md`, …) are ignored. Files prefixed `_` or `.` are skipped
(disable convention).

### Project resolution

- Single-project seams (`ring1-post-collect`, `ring3-close-post`): the project
  is taken from the ring's stdin state (`.path`/`.name`, or `.project_path`/
  `.project`).
- Portfolio seam (`ring2-slow-post`): the slow state carries no project, so the
  runner enumerates `config.projects` and runs each project's seam dir.

### Hook I/O contract

A hook script receives:
- **stdin:** the ring's state JSON, verbatim (see the seam table for shape).
- **cwd:** the project root.
- **env:** `WATCHTOWER_SEAM`, `WATCHTOWER_PROJECT`, `WATCHTOWER_PROJECT_PATH`,
  `WATCHTOWER_SESSION_ID` (ring3), `WATCHTOWER_HOOK_DIR`.

A hook script returns:
- **exit 0** = success; non-zero = failure (isolated, recorded, never fatal).
- **stdout:** optional JSON. `{"additional_checks":[…]}` is the Ring 1
  passthrough — the runner surfaces those at the envelope top level so Ring
  1's existing `parsed.additional_checks` consumption works. Other JSON is
  captured as structured `output`; non-JSON is captured verbatim (truncated).
- **stderr:** captured for diagnostics; non-fatal.

### Isolation and budget

The runner is bulletproof: any single hook's failure (non-zero exit, timeout,
spawn error) becomes a typed status (`failed` / `timeout`) and never aborts
the loop, and the runner always prints a valid envelope and exits 0 — one bad
consumer hook can never break a ring tick. Because the runner is a single
command sharing the ring's one timeout envelope, it runs hooks sequentially
against a deadline (the seam timeout minus headroom) and marks any hook it
can't reach in time `skipped` (reason `budget-exhausted`) — no silent
truncation. `WATCHTOWER_HOOK_BUDGET_MS` overrides the per-seam budget.

### Output envelope

```json
{ "schema_version": 1, "seam": "<seam>",
  "targets": [{ "name": "...", "path": "..." }],
  "hooks": [{ "hook": "<path>", "project": "...", "status": "success|failed|timeout|skipped", "output"?: ..., "exit"?: N, "stderr"?: "...", "reason"?: "budget-exhausted" }],
  "additional_checks"?: [ ... ] }
```

### Migration shim

`watchtower-phase-shim.mjs --phase <path> [--cwd <dir>] [--seam <seam>]` is the
adapter for an EXISTING repo script (a former orient/debrief phase) that
expects the project root as cwd rather than reading stdin. Registered as a one
-line `config.hooks[<seam>]` entry, it runs the target with the same cwd/env/
stdin normalization and passes JSON stdout through transparently (preserving
`additional_checks`), propagating the target's exit code. New hooks prefer the
drop-in directory; the shim is for scripts that already exist.

## Decision Lineage (read-only projection — Plan 12, act:a2efc0ce)

The `/briefing lineage` drill-down answers "what past decisions still
constrain THIS project, and what's reversible?" It is a **projection** over
existing stores, never a new store, and it **writes nothing** — no state file,
no inbox item, no memory write. This is the structural invariant: the engine
holds no persisted copy, so it cannot drift from its sources.

`watchtower-narrative-corpus.mjs` is the read-only substrate helper. It covers
the two watchtower-NATIVE stores so it needs no auto-memory-dir resolver:

- `assembleNarrativeCorpus({cwd})` — current project ONLY (resolved
  worktree-aware via `resolveProjectIdentity`; no free `project` arg, so the
  five-namespace keying footgun can't arise). Returns `inbox_decisions`
  (knowledge-extraction items; `resolution_type: 'captured-to-memory'`
  duplicates dropped so a decision that became a memory file isn't
  double-counted; `superseded` status KEPT — it is the supersession view's
  own subject), `thread_cursors` (full `cursor_history` timelines),
  `per_store_counts`, `skipped_unresolved` (phantom-key items repo-wide that
  the resolver couldn't attribute — surfaced, never silently dropped),
  `time_span`. CLI: `--corpus --project-path <cwd>`.
- `parseDecisionEdges(markdown)` (pure) + `readMemoryDecisions(dir)` — the
  memory/methodology/pib stores are read by the `/briefing` CONSUMER (which
  resolves their paths), but the EDGE RULE lives here, tested: a
  `**Supersedes:**` block is a RECORDED directional edge; a `[[wikilink]]` is
  an undirected see-also and is **never** rendered as a supersession. CLI:
  `--memory <consumer-resolved-dir>`.

Provenance is load-bearing because a narrative is a trust surface: the render
labels *recorded* edges (parsed `Supersedes:` / pib `absorbs act:`) distinctly
from *inferred* ones (model-read from prose), and never presents an inferred
link as recorded history. Deliberately a SIBLING of `watchtower-snapshot.mjs`
(same reader family, same hermetic-test shape), touching zero ring code. Tests:
`__tests__/narrative-corpus.test.mjs`. Staged: the machine-readable
supersede-edge discipline (making edges consistent + live) is deferred and
MERGES INTO the cross-store `supersede` verb
(`.claude/plans/cross-store-memory-redesign.md`, Ring 2-slow), not a fork.

## Cross-Ring Reader (read-only projection — Stage 1, act:f5814d6c)

`watchtower-cross-ring-reader.mjs` is the synthesis SUBSTRATE for `/briefing`:
one call assembles, per configured project, what every ring produced —
Ring 1's parsed state-file sections + git-attention facts, Ring 3's recent
session summaries + thread cursor timelines, and the inbox's pending counts +
resolution history (`resolution_mix`: what the operator's dispositions
actually engaged vs discarded). The script GATHERS; the consumer SYNTHESIZES —
no convergence scoring or cross-store "insight" is computed here (a
mechanical projection on a trust surface must not fabricate synthesis). Like
its siblings it is a **projection** over existing stores, never a new store,
and it **writes nothing** — no write path exists in the module; the hermetic
test asserts the filesystem is untouched.

**Per-store join keys** (name = `config.projects` key, slug = `slugify(name)`;
the reader derives both exactly as `resolveProjectIdentity` does, parity-tested):

| Store | Located by | Key |
|-------|-----------|-----|
| Ring 1 state file | `state/projects/<slug>.md` | slug |
| Ring 3 sessions | `state/projects/<slug>/sessions/*.md` | slug |
| Threads | `sessions[].project` via `threadMatchesProject` | slug |
| git-attention facts | `fact.project` | name |
| Inbox items | `item.project` via `listItems` | name |

**Ring 2 has no dedicated block by design.** Its durable outputs already
arrive through two covered channels — pattern-promotion items ride the inbox,
and the recall canary is projected into Ring 1's Standing Issues — so a
dedicated block would double-report inside one output. Enrichment BODIES stay
behind the Enrichment Directory contract (`/inbox` reads them per-item).

**Honesty fields** (the complement of the config-driven walk — nothing falls
silently between views): `unattributed_items` (partitioned on config-key
MEMBERSHIP, not the `project_unresolved` flag), `orphan_threads`,
`orphaned_state_files`, `duplicate_path_warning` (realpath-compared),
per-view `path_exists` + `attributed_but_flagged`, and windowing counts
(`sessions_total` / `sessions_in_window` / `sessions_included`). Sessions
order by each file's content `Date:` line (same-day filenames sort randomly
by uuid). `superseded`/`expired` items never stamp `resolved_at`, so they are
reported as filed-date-window counts, never blended into the disposition-time
`resolution_mix`; untyped `resolution_type` lands in `untyped_or_other`,
counted, never dropped.

**Output-size caps, always with totals** (CP3: an uncapped live portfolio
measured 1.37 MB — no consumer channel carries that): thread histories keep
the newest `THREAD_HISTORY_CAP` (3) snapshots with per-thread `history_total`
(the full evolution is lineage mode's job — `projectCursorTimeline` itself is
uncapped); the resolution-event list keeps the newest `RESOLUTION_EVENTS_CAP`
(20) with `resolution_events_total` while `resolution_mix` counts ALL events.
The consumer sees "3 of 85", never a silently complete-looking 3. The
briefing consumes by writing `--portfolio` to a temp file and Reading slices —
never by echoing JSON through a truncating shell channel. `--project` accepts
the config-key name or a UNIQUE slug match (the /briefing scope filter is
slug-shaped).

**Consumer:** `/briefing` Step 1d — the reader is the REPLACEMENT gather path
for the old per-store state/thread reads (with a raw-read fallback for
consumers that haven't reinstalled), and its output feeds Step 3a chunk
synthesis and Step 4 cross-cutting synthesis. Pending counts are a narration
snapshot; the briefing's live `listPending()` load remains the disposition
source of truth. The 4-field cursor projection (`projectCursorTimeline`) has
its ONE definition here; `watchtower-narrative-corpus.mjs` imports it
(watchtower-lib is ring-loaded and soak-frozen, so the shared helper lives in
the non-ring reader). CLI: `--portfolio | --project <name> | --project-path
<cwd>`, `--since <ISO|Ndays>` (default 14d, UTC). Tests:
`__tests__/cross-ring-reader.test.mjs`.

**Staged:** precompute-and-cache (a Ring 2 slow-tier phase persisting the
view) is Stage 2, deferred until the recall-canary soak lifts; consolidating
the cursor projection into watchtower-lib waits for the same gate.
