Repository navigation
refactor: Rewrite convergence around a domain-owned derivation kernel - #5027
Conversation
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
|
Important Review skippedToo many files! This PR contains 129 files, which is 29 over the limit of 100. To get a review, reduce the PR to 100 files or fewer by splitting it into smaller PRs or changing its base branch. Upgrade to a paid plan to raise the limit. This review couldn't start because sufficient usage credits or metered capacity aren't available. Add credits or update usage-based reviews in the billing tab, then retry. ⚙️ Run configurationConfiguration used: Organization UI Review profile: ASSERTIVE Plan: Advanced Run ID: 📒 Files selected for processing (129)
You can disable this status message by setting the Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
… laws
Four tests failed on the convergence rewrite but pass on master. Each was a
distinct cause:
- convergence_harness: the rewritten session-profile converger calls
asyncio.run from a sync fixture builder, which async tests call directly.
Drive the coroutine on its own thread when a loop is already running.
- test_fts_repair_sql: the delete assertion pinned one exact SQL string.
Assert the surviving law instead — every FTS delete a session repair
issues is keyed by rowid and names exactly that session's block rowids.
- test_perf_rescue_1314: the membership assertion guessed a corpus word
("analysis") the generated fixture does not contain. Derive the term from
the fixture and assert search returns exactly the sessions the FTS
relation holds, before and after a repaired-away session.
- test_raw_observation_derivation: the assertion that a spent inspection
budget blocks compute memorialised the pre-rewrite budget ledger. The
kernel now deliberately exempts an already-inspected key from the
inspection cap. Assert the discovery bound itself: enumeration stops
mid-domain, the cursor is not swept, and the withheld raws are deferred
rather than dropped.
Verification: devtools test over the four files — 39 passed.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01DYUNBGoE652b3nfmq3CtqK
Per-session inspection and the publish delete set resolved FTS identity rows through an INNER JOIN to blocks. That join cannot see the one class of row the query exists to find: an FTS/identity row whose canonical block has been deleted. Bulk ingest suspends the FTS triggers around block writes, so this is the ordinary residue shape, not a corrupted-database hypothetical. Inspection called such a partition VALID and publish left it in place, so messages_fts kept matching a block that no longer exists. Master used a block_id prefix range, which sees that residue but also claims a colon-prefixed child session's live rows. Neither predicate alone is right: the range finds block-less residue, and `b.block_id IS NULL OR b.session_id = key` keeps a sibling session's rows out of it. Applied to excess_rows, duplicate_rows and the publish delete set alike. Also stamp the global orphan cadence after the probe runs rather than before, so a pass that returns early does not burn the whole interval. Verification: devtools test tests/unit/storage/test_fts_derivation.py tests/unit/storage/test_fts_repair_sql.py — passed. Anti-vacuity checked by restoring the inner join: the new residue test goes red. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01DYUNBGoE652b3nfmq3CtqK
`import polylogue.operations.fts_derivation` raised ImportError from a partially initialized module: operations.fts_derivation imports polylogue.daemon.derivation, whose package __init__ reaches through daemon.cli and browser_capture back into daemon.fts_status, which imported operations.fts_derivation at module scope. It was latent only because production importers happen to reach polylogue.daemon first. Move the two names into the functions that use them. Verification: .venv/bin/python -c "import polylogue.operations.fts_derivation; import polylogue.daemon.fts_status" now succeeds. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01DYUNBGoE652b3nfmq3CtqK
inspect_session_summary discarded everything it had measured when its 1s deadline expired, returning state="unknown". readiness/claim_guard turns any non-READY domain into converged:false, so an archive whose census cannot finish inside the deadline reported not-converged for a reason that describes the probe rather than the archive. A partial scan cannot prove readiness, but one drifted session is a complete counterexample to it. Return "stale" when drift was already measured, on both expiry paths — the row-loop check and the query_deadline interrupt that surfaces as Unavailable. This narrows the wrong claim; it does not remove it. A converged archive larger than the deadline still reports "unknown", because proving readiness is archive-proportional and the probe budget is sub-second. That remaining gap is a design decision for the branch owner, reported separately. Verification: devtools test over the kernel laws plus the summary, FTS and raw-observation suites — passed. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01DYUNBGoE652b3nfmq3CtqK
claim_guard collapsed "inspection did not finish" into converged:false, so a probe that ran out of budget published a negative claim about the archive that nothing had measured. AC7 keeps authoritative readiness and operation health separate and forbids silently collapsing either into the other. Give the claim a third state, mirroring the terminal-outcome rule that a named gap is never reported as an ordinary negative result: - converged:true — every required domain inspected and found ready. - converged:false — a domain inspected its own output relation and found it wanting. Only a determinate domain may say this, and a proven failure outranks an unmeasured one, so a real counterexample is never masked. - converged:null — inspection incomplete. determinate=false and the reason names the domain and its gap. ClaimGuardEntry.value becomes bool | None and to_dict carries `determinate`. Existing consumers that test truthiness are unaffected (null is falsy, so nothing newly claims convergence); consumers testing `is False` now correctly fire only on a proven failure. Profile freshness verification becomes opt-in for the same reason: it recomputes every profile and cannot run inside a sub-second component budget. The cheap counts can still refute readiness — a missing, orphaned or uncounted profile row is a complete counterexample — and otherwise report unknown rather than asserting a readiness never checked. Also de-duplicate the double input_for per FTS partition inspection, which materialized and hashed every block's search_text twice per session. Verification: devtools test over claim_guard, daemon_status, health_contract, fts_readiness_fallback, readiness_capability, fts_derivation, summary derivation and the kernel laws — passed. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01DYUNBGoE652b3nfmq3CtqK
…dget The archive status path replaced `pending_messages_exact = include_detail` with `authoritative_state is not None`, attaching the flag to the wrong question. `pending_messages_exact` tells a caller an exact count from an estimate — it answers "did you pay for detail?", not "could the embedded-state inspection certify itself". Conflating them inverted the contract in both directions: a cheap status read of an archive index published an exact backlog nobody asked it to compute, while a detail read of an archive whose refs/meta/vectors cannot be inspected together withheld the backlog entirely — the case whose own test is titled "even disabled config still exposes the backlog instead of hiding it". The authoritative_state gate stays where it belongs, on embedded_sessions, embedded_messages and coverage. When it is unavailable nothing is provably embedded, so the detail pass counts every embeddable message as pending: a conservative backlog that is exact, and consistent with the pending_sessions = total_sessions set in that same branch. These two tests were inert on this branch until PR #5026 replaced a duck-typed config double with a real PolylogueConfig; every test in the file had been dying at the same TypeError, so the regression shipped unobserved. Verification: devtools test tests/unit/daemon/test_embedding_readiness.py tests/unit/daemon/test_derivation_kernel_laws.py — 43 passed. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01DYUNBGoE652b3nfmq3CtqK
Replacing the duck-typed config double with a real PolylogueConfig left `typing.Any` unused, which fails the lint gate. Verification: devtools verify --quick — 14/14 gates ok, exit 0. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01DYUNBGoE652b3nfmq3CtqK
59d7410 to
7167e11
Compare
…5033) Advances `polylogue-7lhl5`. 13 of 15 remaining failures in `test_embed_status_fast.py` fixed; the last 2 are a separate product regression, filed as `polylogue-5mjla` and **deliberately left red as evidence**. ## Summary Rebuild the embed-status test fixture on the v6 embeddings schema, through the production write route, with real sqlite-vec vectors. ## Problem `EMBEDDINGS_SCHEMA_VERSION` went 5 → 6, adding `message_content_hash` to the embedding refs. The fixture was v5-shaped, so `_embedding_refs_have_message_semantics` short-circuited `_authoritative_archive_embedding_state` to `None` for every test using it — including a literal `EmbeddingGenerationError: embedding database has schema v5, expected v6`. These 15 were previously masked by 29 × `TypeError: unsupported embedding status configuration: _Cfg` and had never executed. #5032 unmasked them. ## Solution `_seed_archive_file_set_from_archive_tiers` now calls `initialize_archive_database(embeddings_db, ArchiveTier.EMBEDDINGS)` for the real DDL, then publishes through `begin_embedding_attempt` → `complete_embedding_attempt_success` with a real 1024-float vector. **No embedding row is hand-inserted.** Index `content_hash` values became real 32-byte hashes so the same value reaches `message_embedding_refs.message_content_hash`, whose CHECK requires 32 bytes. Building through the production route rather than fabricating rows is deliberate: a hand-built fixture drifts from production exactly the way the `FakeArchiveStore` doubles did (`polylogue-banw4`), ending up proving only that it matches itself. ### Anti-vacuity New `test_status_json_reports_metadata_only_row_as_not_ready` deletes *only* the physical vec0 vector, leaving meta, refs (with a current `message_content_hash`), `embedding_derivation_state = 'succeeded'` and `embedding_status` exactly as production wrote them — then asserts `embedded_sessions == 0` and `retrieval_ready is False`. Removing the `EXISTS (... message_embeddings)` conjunct makes it red. A pragma bump without real vectors also leaves it red, which is the specific shortcut this fixture had to avoid. **sqlite-vec:** no difficulty — `try_load_sqlite_vec` returns `(True, None)` here. There is no stub anywhere; the fixture `pytest.fail`s loudly if the extension is ever missing. `_open_embeddings` was added because plain connections hit `no such module: vec0` on any statement naming the virtual table. ## Verification ``` devtools test tests/unit/cli/test_embed_status_fast.py before: 15 failed (after unmasking) after: 32 passed, 2 failed receipt 20260913T222928Z-focused-test-1680636-e427fc80 devtools verify --quick all gates ok, exit 0 ``` ## The 2 remaining failures are a product regression, not fixture shape `_archive_embedding_status_payload` hardwires `blocked_sessions = 0` on **both** branches (`status_payload.py:900,903`). `git show 14e1d82` confirms PR #5027 removed `legacy_blocked_sessions`, the `blocked_session_clause`, and the three-tuple exact session state carrying `session_state.blocked_sessions`, replacing all of it with those two constants. Consequence: a session excluded from automatic retry by an acknowledged/terminal embedding failure is reported as ordinary pending. The failing assertions were **left standing as evidence rather than rewritten to match the regression** — filed as `polylogue-5mjla` (P1). Merging this is still a net improvement: those 2 were already failing behind the `_Cfg` mask, so master's red count falls by 13 and a real regression becomes visible instead of hidden. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01DYUNBGoE652b3nfmq3CtqK Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
…ad (#5034) Closes `polylogue-5mjla` (P1). A regression introduced by #5027 and caught by the fixture rebuild in #5033. ## Summary Restore blocked-session accounting by surfacing the embeddings domain's existing `failed_terminal` classification, rather than re-adding the deleted legacy SQL. ## Problem `git show 14e1d82 -- polylogue/storage/embeddings/status_payload.py` confirms #5027 deleted `legacy_blocked_sessions`, the `blocked_session_clause`, and the three-tuple exact session state, replacing all of it with two literal `blocked_sessions = 0`. So a session excluded from automatic retry by an acknowledged or terminal embedding failure was reported as **ordinary pending** — it looked like work about to happen, permanently. Reproduced: `blocked_sessions` returned `0` instead of `1`, and `_embedding_status` fell to `"none"` instead of `"partial"` because its `blocked <= 0` branch fired. ## Solution No new counter was invented, and the legacy SQL was not restored. The embeddings domain **already carries this classification**: `_archive_embedding_freshness_predicate` in `materialization.py` has three branches — `fresh_sql` / `blocked_sql` / `pending_sql` — where `blocked_sql` is "current derivation key (session, source hash, recipe hash, output contract) AND `attempt_state = 'failed_terminal'`", and `pending_sql` is literally `NOT fresh AND NOT blocked`. That same predicate already drives `_select_pending_archive_session_window_by_derivation`, which keeps these keys out of the catchup work set. **The writer was already excluding them; only the status surface had stopped saying so.** New `archive_embedding_blocked_counts_sql` reuses that predicate verbatim; the status payload owns only the read timeout. This fits the derivation model rather than working around it: pending is `required − valid(inspect)`, and a terminally refused key is neither — not valid (no output) and not pending (no retry will ever produce one). The kernel's `PendingReason.BLOCKED` / poison notion was **deliberately not** reused: that is per-pass prerequisite-closure isolation, not a durable relation a status read can query. The payload clamps `blocked` against the pending set so `embedded + pending + blocked` still equals the eligible total, and subtracts a blocked key's own still-unembedded required messages from the message-level backlog on the same basis. ### Anti-vacuity — verified by reverting, not asserted Replacing the clamp with `blocked_sessions = 0` turns both tests red: `test_status_excludes_acknowledged_terminal_failure_from_retry_backlog` fails `assert 0 == 1` on `blocked_sessions`, and `test_status_json_reports_terminal_failures_before_ready` fails `assert 1 == 0` on `pending_sessions`. Neither assertion was weakened — both were concluded correct under the new model, and the code had regressed away from them. ## Verification ``` devtools test tests/unit/cli/test_embed_status_fast.py 34 passed / 34 receipt 20260913T225039Z-focused-test-1933459-5ac841fe devtools verify --quick 15/15 gates, exit 0 devtools test test_embedding_freshness_invariant.py test_embedding_stats.py \ test_embedding_contracts.py test_embedding_pinned_status.py 76/76 ``` A wider embedding selection ran 90/91; the single failure, `test_seed_demo_archive_creates_ready_queryable_archive`, reproduces identically at `49759f25d` and is not from this change. **Schema identity does NOT move.** `devtools schema closure` reports both changed files `out`, and both identities were *computed* rather than inferred from closure membership: index `615d3e5612845629047b537a26c2046860eed4dc1cffcdcdccf6fbda773ac105`, ops `0a44d6a6764cb6687f73e14b2644265f43841c771bcf2038192ef76f5d164a7a` — byte-identical before and after. ## Other surfaces hit by the same deletion: none A dedicated sweep of #5027's 129-file commit found blocked-session accounting touched in `status_payload.py` only. `materialization.py`'s `ArchiveEmbeddingSessionState` and `blocked_sql` were never modified. The two downstream consumers — `cli/shared/embed_stats.py` (renders "Blocked sessions") and `operations/daemon_status.py` (forwards the dict into the daemon status snapshot) — are pass-throughs that were untouched and become correct with this fix. Recorded but deliberately not changed: `daemon_status.py`'s `_unavailable_embedding_status` fallback hardcodes `blocked_sessions: 0`, which predates #5027 and is the honest value for an unavailable tier. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01DYUNBGoE652b3nfmq3CtqK <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Embedding status now reports terminally blocked archive sessions separately from the pending backlog. * Status details now include the number of blocked sessions and their unembedded eligible messages. * Pending session and message counts are adjusted to exclude blocked work for clearer progress tracking. <!-- end of auto-generated comment: release notes by coderabbit.ai --> Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
…cts (#5041) Triage of the CLI-output share of the 58 failures from the first complete full-corpus run (job 650). **Only 4 of 18 were test problems.** The other 14 are product defects, now on beads. ## The lead I was given was wrong, and that mattered I was told the two `convergence debt:` assertions were almost certainly asserting a surface deliberately removed by #5027. **They are not stale.** The renderer still emits `Convergence debt:` at `cli/commands/status.py:363/:454/:460`, and the `convergence_debt` table survives across ~20 modules. Both tests die *before* any convergence rendering — on the daemon refusal. Reproduced without pytest, same workspace both ways: ``` POLYLOGUE_DAEMON_URL=http://127.0.0.1:1 → "Daemon: running / Status snapshot: unavailable" (unset) → "Daemon: not running / No archive found." ``` Fixing `polylogue-2d8oq` should turn them green **with no test change**. Recorded on that bead so it is not re-derived. ## Fixed (4) | Test | Class | Cause | |---|---|---| | `test_query_composition_laws` | TEST-INFRA | The `_daemon_delete_route` double returned `authorization_token`; #4867 renamed the contract to `authorization_refs`. Every other double was already migrated — including the one this test's docstring says it mirrors. | | `test_paths::test_archive_override_unifies_…` | STALE-TEST | #4955 moved reset behind `maintenance.reset`; the test asserted the deleted in-process bypass. Now asserts the refusal *and* that the override still reaches the read-only preview. | | `test_plain_cli_snapshots::test_json_analyze_snapshot` | STALE-TEST | Snapshot updated — scoped to the single node, recording the terminal `outcome` field the envelope now carries. | | `test_maintenance_registration::test_blob_conservation_json_…` | ORDER-DEPENDENT | Verified: passes alone and in a 74-test cross-file selection; fails at directory scope and in the corpus. | ## Not fixed — 14 product defects, on beads - **7 → `polylogue-2d8oq`** (existing): `basic_usage_cli` ×3, `json_envelope_contract` ×2, `test_json_status_snapshot`, `test_terminal_snapshots`, `test_convergence_surface_contract`. - **5 → `polylogue-jih4s`** (filed): read-only query verbs take an **exclusive maintenance ownership lock** and mint an auth token into the archive root. Regression from #4867. - **1 → `polylogue-kjy0a`** (filed): `ops status` publishes `converged: false` with `reason: "ready"` on a pristine empty archive. `daemon_status.py:158-162` derives `ready` and `summary` from *different* predicates, and omits `determinate` — so the converged-vs-unknown collapse from `polylogue-bp12n.1` is **still live on this path**. - **1 → `polylogue-uf7un`** (filed): daemon and direct `find` disagree on the resolved root filter. ## #4867 again `1d901ec73` now accounts for **12 of these 18** — 7 via 2d8oq, 5 via jih4s — on top of the five clusters already attributed to it on `polylogue-7lhl5`. ## Verification ``` devtools test tests/unit/cli 3040 collected, 12 not-green — every one on a filed bead devtools verify --quick 15/15 gates, exit 0 ``` One snapshot updated, justified above. No test was written that agrees a nonexistent daemon is running. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01DYUNBGoE652b3nfmq3CtqK --------- Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
…batch (#5040) Triage of the sources/ingest/schema share of the 58 failures from the first complete full-corpus run (job 650). **All 16 classified and fixed: 602 passed, 0 failed** across the owned files. ## Two campaign-blocking product defects Both would have damaged the final archive build silently. Filed as `polylogue-gjfsx` and `polylogue-0zhhc`. ### 1. Ingest admitted Hermes SQLite page images that replay refuses `test_binary_payload_parse_parity.py` ×2, `test_revision_backfill.py` ×2. Replay refuses anything that is not the declared logical export; the daemon's per-raw ingest route still parsed page images into sessions. **Would corrupt a from-scratch build:** a reindex mints a *second* source authority for content the archive already holds under its logical revision. CLAUDE.md states the rule directly — *"A mutable SQLite source is the one material that is not its own bytes… that export's blob hash is the member's logical revision. A page image cannot be proven against a live database and re-snapshots on every commit."* Fixed by gating `_hermes_sqlite_marker_payload` on `is_declared_logical_export`. The fixtures were retargeted to real logical exports rather than relaxing the production check — the check is what makes the revision provable. ### 2. One excised file aborted an entire reingest batch `test_excision.py::test_reingest_batch_skips_excised_file_without_aborting`. Two acquire-time excision gates raised different exception classes. The orchestrators catch only `ContentExcisedError`, so the policy gate's bare `ExcisionPolicyError` escaped, rolled back the in-flight batch and re-raised. **Would silently truncate a from-scratch build:** excision markers survive an `index.db` rebuild by design, so a rebuild over a tree containing one excised file drops every unrelated session in that batch and every file after it — and reports success. Fixed at the raise site; refusal semantics unchanged. ## A verification hole, restored The retryable-SQLite-lock guard has been **vacuous since #4924** (`polylogue-6e9d5`). A drifted stub raised `TypeError` instead of the injected lock, so the two tests proving *"a lock must not advance or poison a cursor"* never exercised it. Production was never wrong — but cursor-advance-past-unwritten-data was unverified, and the rebuild runs heavy concurrent writers, which is exactly the condition the guard exists for. The stub is now signature-agnostic and cannot drift. ## No parse, conservation, or identity defect exists Two tempting wrong conclusions were checked and rejected: - `Provider.GEMINI == Provider.UNKNOWN` is documented **forward** provider-wire normalization, not an Origin reversed into a guessed Provider. The test hand-maintained a token list that omitted most real aliases. - The claude-code "duplication" was a **measurement artifact** — the parser emits each wire value exactly once, proven by counterfactual; the planted side was blind to `text`/`thinking`/tool-argument positions the observed side counted. Fixed by **symmetry rather than suppression**, which strengthened the check: claude-code checked bodies 42 → 221, with no generated bytes changed. ## Remaining classifications **STALE-TEST ×6** — convergence-debt rows deliberately retired by #5027 (pending is now `required − valid` derived from the durable relation, so the backlog is not lost), Codex envelope support landed by #4881, the provider-token list. **TEST-INFRA ×5** — drifted stub, measurement asymmetry. **ORDER-DEPENDENT ×0** — the one candidate was Hypothesis nondeterminism, disproved rather than assumed. None carry rebuild risk. ## Verification ``` devtools test <11 owned files> 602 passed, 0 failed devtools verify --quick exit 0 ``` ## Residual, flagged not fixed `ConservationResult.to_dict()` emits findings as strings while `tests/infra/wire_support.py` deserializes them as objects — latently broken for any non-conserved cached receipt. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01DYUNBGoE652b3nfmq3CtqK <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Bug Fixes** * Improved archive ingestion and replay consistency by validating logical exports and rejecting unsupported raw database images. * Preserved conservation failures and detailed findings when restoring saved support data. * Improved handling of content-excision violations with clearer error details, including the affected content and source path. * Enhanced recovery and retry behavior for deferred indexing and sidecar ingestion. * Improved recognition of common provider aliases during data processing. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
Triage of the daemon/async share of the 58 corpus failures. **21 of 23 fixed** across 17 commits — and it uncovered **silent production data loss** that would have crippled the from-scratch rebuild. ## The finding that matters The brief framed the four `test_daemon_resilience` failures as "grouping or daemon lifecycle". Raising the module timeout — a 300s wait under a 120s ceiling could **never** complete — unmasked the real diagnostics. On an **idle** machine `sigkill_recovery` reported *byte-identically* the same "20 messages" as the corpus run, proving load was not the cause. **The daemon ingested one session per root and stopped.** `FileIntakeAdapter.discover` advanced its cursor past the entire discovered page while the dispatcher consumed only its head, and the walk only moves forward. Compounding it, adapters charge `estimated_cost` in **bytes** while the service budget was `64` — a *count*. Every session after the lexicographically-first was retained on disk and never archived. Introduced by `#4913`, which made the dispatcher the sole discovery authority and disabled the watcher's own catch-up. This is not a test defect. The fresh-start ruling is *"move the six database files aside, start the daemon fresh, let ordinary convergence rebuild everything from the actual sources"* — so the rebuild **is** this code path. Building on the previous head would have produced an archive containing roughly one session per source root and reported success. ## Classification of all 23 **PRODUCT-BUG (8)** — the discovery/budget loss above (resilience ×3 + `large_session_file`); workload probe ×2 (the adapter treated "file exists" as "tier bootstrapped", and `inspect` opened a DB to answer an empty question); MCP clamp (the CLI clamps `limit=-1`, MCP refused it — the declared clamp was applied to the routing probe but not the typed request); daemon SIGTERM forensics (the signal handler wrote without the process-wide lease, `UnleasedWriteError` swallowed → `(None, 'signal')`). **STALE-TEST (8)** — the insight cluster ×4 (still calling the facade #5030 retired); visual ×2, red since #4645's WebUI cutover because `tests/visual/` is not in the fast gate; `daemon_status` (`(0 sessions, 1 message)` is unreachable by construction post-#5027); demo seed. **ORDER-DEPENDENT (3)** — `test_daemon_cli.py`. Passed alone *and* across `tests/unit/daemon`; the corpus receipt showed a `MagicMock` and a shut-down adapter leaking through the process-global `_SHARED_COMPUTE_ADAPTER`. `reset_daemon_compute_adapter()` already existed and **nothing called it**. Verified red→green with a deterministic two-file reproducer. **TEST-INFRA (3)** — `live_read_amplification` (double drifted from a keyword-only signature); `resume` (rename debris from #4614, `insights` vs `analysis`); `write_path_state_machine`. **Root verb (1)** — `verification-export` regrew the surface `985e0f9d9` folded. The verb was wrong, not the test. ## Two left unfixed, deliberately - **`test_demo_seed_verify`** — Codex declares `parent_dispatch` structurally absent, so `mapping_state:resolved` is unreachable for that fixture (confirmed by counterfactual: forcing the origin gate only changes the refusal reason). A Claude Code delegation fixture was started; each step revealed another required piece, so it was **reverted cleanly** rather than left half-built. - **`test_installed_package_smoke`** — diagnosed precisely, then **both commits reverted** after three fixes each broke a different legitimate caller. The third was rejected by `devtools gate layering`'s own ratchet. That the architecture refuses the CLI-layer catch says this needs a deliberate owner decision, not a triage patch. Full rationale is in the revert commit. ## Verification ``` 2,976 passed, 0 failed devtools verify --quick exit 0, 15/15 gates ``` ## Residuals recorded in commits A pre-existing `_assert_resolved_link` property failure (replayed against base — fails there too, no delete involved); an unleased-writer bug in the daemon health/cursor-lag path; a whale-pass deadlock against the daemon's own ownership flock; and a note that two reds in `tests/unit/sources/` assert FTS convergence debt which the inline repair here makes obsolete. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01DYUNBGoE652b3nfmq3CtqK <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Updated the verification export command to use `verify export`. * Newly ingested sessions become searchable immediately. * Improved intake processing so skipped items can be rediscovered. * **Bug Fixes** * Out-of-range session list limits are now handled safely. * Improved daemon lifecycle signaling under write-lease enforcement. * Clearer errors are provided when source databases are missing required data. * Intake processing now uses a byte-based default budget. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
## Summary Delete the raw-authority frontier **apply/recover/validate** chain, which has been unreachable from production since PR #5002. 12 files, +16/−2,443. The inspect/census side is untouched and remains production-reachable. ## Problem `polylogue-6kur` ("Eliminate repair as a product concept") requires that no public generic repair, cleanup, doctor-apply, or break-glass route remains. The generic repair framework (`storage/repair.py`) is gone, but a generic *actuator* route survived as dead code: PR #5002 ("Retire the all-valid raw materialization scanner from production") deleted the legacy `_run_raw_materialization_pass` wholesale, and with it the only call site of `_converge_raw_authority_frontier`: ``` - frontier_repaired = _converge_raw_authority_frontier(config, limit=min(limit, 8)) ``` Nothing in the #5027 derivation-kernel rewrite re-wired it. At this head the caller list is empty at every level: - `_converge_raw_authority_frontier` — referenced only by its own definition and one test that called it directly. - `_emit_raw_materialization_pass` — same; the `raw_materialization_pass` event it shaped has no other emitter anywhere in the tree. - `maintenance.raw_authority.apply_frontier` / `recover_interrupted_frontier` / `_validate_frontier_apply_report` — reachable only from the above. - `raw_reconciler.apply_raw_authority_frontier` and friends — reachable only from those. So the last thing in the tree that could *execute* a historical repair strategy was already incapable of being invoked. It was a generic repair actuator kept alive only by its own tests. ## Solution Delete the dead closure, computed with a reachability analysis seeded from every symbol referenced outside the two storage modules: - `daemon/cli.py`: `_converge_raw_authority_frontier`, `_emit_raw_materialization_pass` - `maintenance/raw_authority.py`: `apply_frontier`, `_validate_frontier_apply_report`, `recover_interrupted_frontier` - `storage/raw_reconciler.py`: `apply_raw_authority_frontier`, `recover_interrupted_raw_authority_frontier`, `validate_raw_authority_frontier_apply_report`, `_validate_raw_authority_frontier_apply_counts`, `RawAuthorityFrontierApplyReport`, `_apply_strategy`, `_preview_plan_ids`, `_terminalized_preview_items`, `_state_counts` - `storage/raw_convergence.py`: the `_apply_*` / `_stage_*` / `_finalize_*` / `_restore_*` strategy actuators for browser-capture origin, duplicate raw identity, and quarantined accepted raw **Deliberately retained**, because it is still the only route to something real and still production-reachable: the whole inspect/census side — `inspect_raw_authority_frontier`, `_classify_frontier`, the three `inspect_*` strategies, the `maintenance raw-authority-frontier|census|detail|blockers` commands, `mutate-resolve-raw-authority-blocker`, the readiness payload fields, and the MCP census resources. Operators can still see the frontier and its blockers; they just cannot invoke an actuator that no production route could reach anyway. Tests covering the removed route were deleted, not weakened — no test was skipped, xfailed, loosened, or stubbed. Where a test mixed inspect and apply assertions, only the apply half was removed and the test kept its real inspect checks (four such tests, three renamed to match what they now prove). Atlas citations into `daemon/cli.py` were re-verified and their line ranges corrected against the new content. ## Verification ``` devtools test tests/unit/storage/test_raw_authority_ledger.py tests/unit/storage/test_quarantined_accepted_raw_repair.py tests/unit/storage/test_duplicate_raw_identity_repair.py tests/unit/storage/test_browser_capture_origin_repair.py tests/unit/storage/test_quarantine_repair_budget.py tests/unit/product/test_raw_authority.py => 102 passed, 1 warning in 114.96s (devtools test: PASSED exit=0 diagnosis=pytest_passed) devtools test tests/unit/daemon/test_daemon_cli.py => 104 passed, 1 warning in 43.92s (devtools test: PASSED exit=0 diagnosis=pytest_passed) devtools verify --quick => all 15 gates ok, exit 0 (incl. oracle-integrity, consumer-reachability, layering, schema-manifest) ``` Anti-vacuity: a scripted reachability closure over both storage modules reports zero unreachable module-level definitions after the deletion, and a tree-wide grep for every deleted symbol across `polylogue`, `tests`, `devtools` and `docs` returns nothing. ## Residuals (honest) - **This moves the derived schema identity.** `storage/raw_convergence.py` is `IN` the closure per `devtools schema closure`. It must land **before** the fresh rebuild starts, never during one. - **`devtools gate atlas` still reports the daemon/00-core sections as stale.** This is structural, not ignorable-by-choice: the stamp is a commit SHA, so a PR that edits an anchored file can never stamp itself, and a squash merge changes the SHA again. Master is already red on this gate for the same reason (`docs/structured-logging.md` after #5074). The *anchors* in this PR were re-verified by hand and their line ranges corrected; only the `verified:` stamp is unchanged. `atlas` is not a `--quick` gate. - This does **not** close `polylogue-6kur`. It advances AC 1/2. The durable raw-authority census/plan/blocker tables, the operator-facing census commands, and the three historical inspect strategies all survive; their disposition belongs to `polylogue-2x6xu` and depends on the operator's archive-wipe decision. - Remaining `repair` vocabulary in the tree (FTS membership convergence, stale-observation reconciliation) names live derivations, not a repair product; renaming belongs to `polylogue-z07nu`. - Pre-existing and untouched: `docs/design/raw-decision-authority.md` cites `raw_convergence.py:4608-6194`, anchors that died when the engine was removed in #5005/#5027. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01DYUNBGoE652b3nfmq3CtqK Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
## Summary Four `test_plain_cli_snapshots.py` failures. Two were stale snapshots from additive changes that were never re-recorded. One was a **product defect** in `daemon_status.py` — a never-derived profile domain reported as `stale`, which flipped global `ok` to false on a pristine archive — fixed here, which is what lets its snapshot be re-recorded honestly. The fourth is a genuine read-path parity defect, filed and left red. ## Evidence Full-corpus `verify_all` on frozen `master` (`890a2921e`), job 1570, receipt `.cache/verify/runs/20260914T200510Z-all-4027943-f8bc83ff`, 22,524 selected, **147 failures with zero schema skew**. Four of them in this file. ## Per-failure classification | Failure | Classification | | --- | --- | | `test_json_analyze_snapshot` | **Stale snapshot** (#5146) — re-recorded | | `test_json_read_all_snapshot` | **Stale snapshot** (#5152) — re-recorded | | `test_json_status_snapshot` | **Product defect** (#5027) — product fixed; snapshot then re-recorded | | `test_facets_command_json_matches_analyze_facets` | **Product defect** (#4867) — **not fixed**, filed as `polylogue-mtxl2`, left red | ### `test_json_analyze_snapshot` — stale, purely additive Two fields on `ArchiveStats.to_dict()` / `query_stats`: `embedding_coverage_measurable: true`, `embedding_coverage_unmeasurable_reason: null`. Added by **e991cfa5e / #5146** ("Read an unloadable vec0 extension as unmeasurable, not zero"), confirmed with `git log -S` on `archive/stats.py` and `cli/query_stats.py`. Values verified correct rather than merely current: `embedding_coverage_measurable` is defined as `embedding_coverage_unmeasurable_reason is None`, and the seeded archive's embeddings tier *is* inspectable — so `embedded_sessions: 0` is a measured zero, not an unknown. That is consistent with the pre-existing `embedding_coverage_percent: 0.0`, since an unmeasurable tier renders `null` there. Nothing removed, nothing changed. ### `test_json_read_all_snapshot` — stale, purely additive `outcome: {state: "ok", reason: null, detail: {}}` and `source: "direct"`. Added by **8d981b806 / #5152** ("Serve every root query through one declared read operation"), which deleted the local `ArchiveStore` branch of `_execute_archive_query_stdout` and routed root queries through `operations/daemon_reads.py`. Values verified: the envelope reports `total: 2`, and `decide_outcome(matched=2)` is `ok` — not `empty`, not `degraded` — per the `surfaces/outcome.py` contract. `source: "direct"` is correct because the test environment has no daemon, matching `ops status`'s own `source` on the same archive. ### `test_json_status_snapshot` — product defect, fixed This one was **not** merely stale: `polylogue ops status --format json` *exited 1* on the seeded archive, so no re-record could have made it green. Root cause: `_session_profile_component` (`operations/daemon_status.py`) collapsed every not-ready shape into `STALE`. On the seeded archive 0 of 2 profiles had ever been materialized — nothing was computed, so nothing could have gone out of date. That is `MISSING`, not `STALE`. The distinction is load-bearing: `_status_ok` tolerates a never-converged derived family through the `required_missing` allowlist, but treats `stale` as unconditionally not-ok. So on one archive, `embeddings` (`missing`) and `transforms` (`unknown`) were correctly tolerated as never-converged while `session_profiles` — equally never-converged — flipped global `ok` to false. Introduced by **14e1d821f / #5027** ("Rewrite convergence around a domain-owned derivation kernel"), which is when this test went red. `component_from_derived_model`, in the same file, already draws exactly this line (`source_rows == 0 and materialized_rows == 0` → `MISSING`; stale rows → `STALE`). The profile domain was the outlier; it now follows the same rule. The fix is not a green-washing of the signal. The re-recorded snapshot still reports the domain honestly and the claim guard still refuses to certify: ``` "session_profiles": { "state": "missing", "summary": "session profiles not derived", "missing_profiles": 2, "repair_hint": "polylogued run" } "converged": { "value": false, "determinate": true, "reason": "session profiles not derived", "signal": "derived_domain_readiness.session_profiles" } ``` `ok: true` (the archive is usable) and `converged: false` (a derived family has not run) are different claims, and both are now reported correctly. Note the stored snapshot already expected `"ok": true` — the product fix restores what the test always asserted. The snapshot was *also* independently stale by several PRs, which the re-record picks up. That diff is strictly an improvement: it replaces zeros with the seeded archive's real measurements (`raw_artifact_count` 0→2, `materialized_raw_artifact_count` 0→2, `archive_session_count` 0→2, `message_indexed_count` 12) and adds the `search`, `session_profiles` and `session_summary` components that did not exist when it was recorded. Removed fields (`raw_records`, `unidentified_artifacts`) and the constant `next_action` / `config_path: null` are the deliberate shape of the pinned-archive route, which states in its own `diagnostic.reason` that it excludes CLI first-run diagnostics. ### `test_facets_command_json_matches_analyze_facets` — product defect, left red Not a snapshot — a real parity assertion between `polylogue facets` and `analyze --facets`, and genuinely broken. `operations/daemon_reads.py::_facets_payload` *reimplements* the facets envelope while its docstring claims it reuses the API's canonical `facets()` (`api/archive.py:6053`); it reuses only `_archive_facet_buckets`. Measured divergence on the seeded archive: | field | `facets` (operation route) | `analyze --facets` (API) | |---|---|---| | `family_status` | `{}` | full per-family descriptors | | `availability` | `null` | `{projection, state: ready, deadline_s, elapsed_s, …}` | | `deadline_s` / `elapsed_s` | `null` / `null` | `2.0` / measured | | `complete_families` | `["origins","tags"]` | `["total_counts","origins","tags"]` | | `deferred_families` | spurious `"omitted"` | no `"omitted"` | The direct `facets` command loses the family-state reporting its own docstring promises ("reports their state explicitly instead of rendering empty buckets as authoritative facts") — it renders exactly the empty buckets that docstring disclaims. Red since **1d901ec73 / #4867**. **Deliberately not fixed here.** `facets()` is `async`, owns its own archive acquisition, and computes `availability` / `deadline_s` / `elapsed_s` under a deadline from `analysis.projection_contracts.facets_availability`. Delegating properly means running it over a caller-pinned `ArchiveStore` without changing its cancellation and deadline semantics — a read-path design decision that owes CLI/API/MCP parity, pagination and cancellation evidence per CLAUDE.md, not a patch at the tail of a test-failure sweep. Filed as **`polylogue-mtxl2`** (P1) with the measured table and the introducing commit. The test stays red and the bead names the wanted outcome; its existing parity assertion is its own anti-vacuity condition. ## Verification ``` devtools test tests/unit/cli/test_plain_cli_snapshots.py -k test_json_status_snapshot --snapshot-update devtools test: PASSED exit=0 diagnosis=pytest_passed receipt=.cache/verify/runs/20260914T224544Z-focused-test-97274-741f4d02/run.json ``` ``` devtools test tests/unit/cli/test_plain_cli_snapshots.py devtools test: FAILED exit=1 receipt=.cache/verify/runs/20260914T231034Z-focused-test-152736-9534a424/run.json 23 of 24 pass. The single remaining failure is test_facets_command_json_matches_analyze_facets, the filed defect above (polylogue-mtxl2), left deliberately red. ``` `devtools gate format` / `devtools gate lint` — clean. ## Schema closure ``` out polylogue/operations/daemon_status.py out tests/unit/cli/__snapshots__/test_plain_cli_snapshots.ambr ``` Neither is in the derived-schema identity closure; this PR does not gate the archive rebuild. ## Residuals - `test_facets_command_json_matches_analyze_facets` remains red, tracked by `polylogue-mtxl2`. - `_status_ok` still treats `stale` as unconditionally not-ok while gating `missing` and `unknown` through allowlists. This PR fixes the one domain that was mis-stating its state; it does not revisit whether that asymmetry is right in general. - The `session_profiles` state now depends on `profile_row_count == 0 and total_sessions > 0`. A *partially* derived set (some profiles present, some missing) is still `STALE`, which is the intended reading. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01DYUNBGoE652b3nfmq3CtqK <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit - **Bug Fixes** - Session profile status now clearly reports when profiles have not yet been derived, rather than labeling them as incomplete. - **CLI Improvements** - Updated JSON analysis output with clearer embedding coverage details and reasons when coverage cannot be measured. - Enhanced read-all results with outcome and source information. - Refined status output with additional readiness indicators, clearer configuration and claim status details, and more transparent unavailable-data reasons. <!-- end of auto-generated comment: release notes by coderabbit.ai --> Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
## Summary Move daemon metrics collection and convergence acquisition into their operations owners. Remove fifteen surface-to-substrate exemptions and eight retired SQLite degradation anchors. ## Problem Historical F756 on PR #4308 remains real for `daemon/convergence_stages.py` and `daemon/metrics.py`: both acquired substrate state directly while their baseline exemptions made the ratchet accept it. The FTS convergence import was already corrected in #5027 and its stale exemption removed in #5531. The connected source membership route also fell back to a readable conventional shadow when the promoted index could not be acquired; workflow publication followed the promoted generation directory instead of the configured durable root. ## Solution Operations owns metric acquisition, complete collector groups and exposition; the HTTP adapter publishes the product result. Workflow materialization and its ordered current receipt, source-to-session membership, and Sinex configured publication/barrier composition have substantive product owners. Existing FTS operations owns binding inspection and transactional publication. Every connected caller follows those owners, and unused predecessor helpers are deleted. Required membership faults propagate; optional metric probe failures retain their typed evidence and existing diagnostic outcome. The ops-only corruption probe uses the canonical query-only diagnostic reader, preserves the schema-cookie check and closes its handle. Process collectors retain their lifecycle owners and the metric/HTTP contract is unchanged. | Finding | Disposition | Evidence | | --- | --- | --- | | F756 / CX56.F080, remaining stage and metric adapters | fixed | cc9d913 plus f823d48 and 3845fb4; zero corresponding direct imports or baseline exemptions; anti-vacuity regression covers restoring either | | F756, FTS convergence import | fixed-later | 14e1d82 (#5027); stale exemption removed by 9d33b52 (#5531) | ## Verification `agentctl job start polylogue pytest_focused --workspace <candidate-worktree> --` followed by this exact selection: ```text tests/integration/test_claude_workflow_admission.py tests/unit/core/test_sqlite_lock_classification.py tests/unit/daemon/test_convergence_debt_alert.py tests/unit/daemon/test_convergence_final_state.py tests/unit/daemon/test_convergence_restart_law.py tests/unit/daemon/test_convergence_stages.py tests/unit/daemon/test_daemon_cli.py tests/unit/daemon/test_daemon_ops_lease_boundary.py tests/unit/daemon/test_diagnostic_metrics.py tests/unit/daemon/test_embedding_convergence_progress.py tests/unit/daemon/test_fts_readiness_binding.py tests/unit/daemon/test_hook_liveness.py tests/unit/daemon/test_maintenance_read_profiles.py tests/unit/daemon/test_metrics_endpoint.py tests/unit/daemon/test_selected_session_parts.py tests/unit/daemon/test_session_profile_composition.py tests/unit/daemon/test_standing_queries_default_evaluator.py tests/unit/daemon/test_unmeasured_observations.py tests/unit/devtools/test_layering_gates.py tests/unit/devtools/test_verify_rebuild_routes.py tests/unit/insights/test_claude_workflow_evidence.py tests/unit/operations/test_session_source_membership.py tests/unit/sinex/test_convergence.py tests/unit/sources/test_live_ingest_ops_work.py tests/unit/storage/test_archive_readiness.py tests/unit/storage/test_raw_observation_derivation.py tests/unit/storage/test_write_lease.py ``` Job 5242, head `cc9d913464231f24c0e46830733b1df358b7cee4`, receipt `20261001T022107Z-focused-test-3540546-6877456b`: `495 passed, 3 warnings`; exit 0, 495 unique selected/terminal nodes, no retry. `agentctl job start polylogue verify_quick --workspace <candidate-worktree>`: job 5243, same head, receipt `20261001T022113Z-quick-3540667-b9396fbd`: `verify: PASSED exit=0`, all twelve gates pass. A fresh independent local review of exact head cc9d913 found no remaining scoped defect. Hosted Codex reviews are disabled by operator direction; no manual hosted request was made. The selector covers 27 connected modules. No complete-corpus claim. Schema closure inspection found all eleven changed production files outside the derived identity closure; the final schema-closure gate also passes. ## Self-review Author reviewed the whole diff against base 81fff68, including transferred bodies, all connected callers and the retired inventories. Three correction passes; final pass after verification found no remaining scoped defect. 1. ✓ **Siblings and owners.** The complete census covers both remaining F756 adapters, the source membership consumer in session-profile convergence, all three barrier consumers, the workflow receipt and existing FTS owner. All 15 adapter exemptions and eight predecessor anchors are removed. 2. ✓ **The fix itself.** Reviewed the acquisition changes and the transferred functions against their original bodies. The final metrics AST census proves 48 function/class bodies unchanged and isolates seven typed refusal rewrites plus the canonical ops-only probe acquisition; their original fallback values and finally-close blocks remain. Hot-source capture is restricted to the original attachment failure branch. 3. ✓ **Memory and limits.** No new limit, cache, timeout or archive enumeration is added. The existing scoped source/session join and collector buffers are retained. Existing sampling policies are unchanged. 4. ✓ **Cost per unit.** The product retains its SQL parameters and indexed ordering. Membership now opens the active generation once instead of probing then reopening or falling back to a shadow. Source membership joins every selected path once. No per-row bootstrap or new archive-wide scan is introduced. 5. ✓ **Interruption.** FTS publication retains BEGIN IMMEDIATE, rollback on refusal/exception, commit on certified binding and finally-close. Existing stage admission and derivation scheduling remain the cancellation/restart owners. 6. ✓ **Ordering and races.** Workflow current receipts retain pass-start ordering and rejection of older failures. FTS binds within the existing admitted transaction. The configured root remains distinct from active index authority. 7. ✓ **Failure classification.** Seven metrics readers and the hot-source attachment project existing Measured/Unavailable evidence with original event tokens and fallback behavior. Required source join and active-generation acquisition faults propagate; only a genuinely absent index remains empty. The existing index-probe diagnostic is retained before re-raising. Schema skew remains outside sqlite capture. 8. ✓ **Silent outcomes.** No stage is retired without a replacement. FTS absence retains empty success, an invalid surface retains pending refusal, and collector failures retain availability evidence and process counters. 9. ✓ **Cleanup on failure.** Transferred readers retain finally-close, including the ops-only schema-cookie probe now acquired through the canonical query-only diagnostic profile; FTS retains rollback and close. New authorizer-based fault regressions check that actual acquired metric connections close. Synthetic membership connections use explicit closing. 10. ✓ **Identity and keys.** No durable DDL or ID partition changes. Workflow retains its stable current receipt key. The active generation still comes from ArchiveLocation; workflow materialization and ops receipt now keep the configured root. 11. ✓ **Lossless transforms.** Metrics family names, labels, samples and process collectors are unchanged. The moved scalar SQL declaration names the same function and argument at its new owner. No public serialized schema changes. 12. ✓ **Degenerate inputs.** Existing metrics coverage includes missing/malformed archives and measured/unmeasured groups. Source regression covers duplicate paths, an absent path, multiple matching sessions and a malformed required join. Empty stages retain their existing outcomes. 13. ✓ **Consumers.** Repository search found and updated metrics imports, workflow direct tests, receipt callers and all barrier consumers. Unused archive writer and transient-lock wrappers are deleted, as is the sole-consumer active-index probe/fallback. Retired helper-name search has zero hits in the connected production/test/docs paths; the independent embedding orphan helper does not fall back after a failed read. The HTTP adapter retains only responder/content-type/handler responsibilities. The existing query-only reader census now covers all relocated owners. 14. ✓ **Tests and stubs.** New regressions name restoring substrate imports or exemptions, following the promoted generation parent, swallowing a required join fault, losing typed metric diagnostics, or omitting finally-close as their failing mutations. The unchanged complete selector covers 27 connected modules. First candidate 5206 had 490 passes and one fixture setup failure; corrected 5234 had 492 passes and one real direct-open census failure, both reproduced by automatic diagnostic retry. Third candidate 5242 passed all 495 selected tests with three inherited lifecycle warnings; no diagnostic retry was needed. The damaged-column fixture removes its two dependent triggers before damaging the column, retaining all unavailable assertions. 15. ✓ **Trust boundaries.** Only neutral synthetic database fixtures were added. No operator archive, transcript, original capture or private evidence enters Git. Diagnostic event policy is unchanged; metric payloads retain their existing bounded reason tokens. 16. ✓ **Assigned criteria.** F756 implementation and regression are present; focused verification and twelve static gates pass on cc9d913; default-branch disposition remains pending independent local review, enforced checks and merge proof. Hosted Codex reviews were disabled by the operator. Neither the parent task nor the other nine F179 findings is claimed complete. 17. ✓ **Defect census.** Search covers every old helper name, daemon metric import and configured barrier consumer. JSON baselines shrink only, with no replacements at the new operations paths. 18. ✓ **Complete interface changes.** New owners replace the old definitions in the same batch. Direct workflow test consumers import operations, the three daemon composition sites import the new barrier owner, and HTTP still publishes the same response. 19. ✓ **Typed visible failures.** capture_sqlite_read owns SQLite acquisition refusal; events retain original reasons. Required joins still raise, collector groups still expose availability, and unsuccessful FTS publication remains pending. 20. ✓ **Regression mutations.** Restoring any adapter substrate import or exemption fails the gate regression. Returning the active generation parent fails workflow root/receipt assertions. Swallowing malformed joins, serving a stale conventional index after promoted acquisition failure, or retaining a metric reader fails the new production boundary tests. 21. ✓ **Public evidence.** The patch contains code, current ownership docs and synthetic tests only. Scratch patch, AST census, selector and review remain outside Git under the task scratch directory. ## Residuals Inherited coroutine and writer-lifecycle warnings were handed to the active writer custody owner with their full immutable traces. This ownership change neither suppresses them nor claims their production fix. Historical task acceptance remains pending gated merge and default-branch proof; unrelated F179 findings are outside this batch.
Closes the implementation half of
polylogue-bp12n.1. The bead stays open: itsown acceptance contract is explicitly UNSATISFIED and the residuals are listed
below with their owning beads.
Summary
Replace the optional-stage / convergence-debt / freshness control plane with one
small domain-owned derivation kernel. 129 files, +5,224/−11,487.
The kernel knows only
bind(frame)/required(frame)/inspect(frame, keys)/
compute(frame, key)/publish(frame, key, replacement). Pending correctnessis
required − valid(inspect)— never a debt row, cursor, queue membership,freshness flag, or operation receipt. Derived relations stay authoritative: no
generic artifact store, no durable work queue, no global freshness ledger. FTS
membership, a partitioned aggregate, embeddings, and normalized raw-to-logical
membership each implement the same laws while keeping their own SQL.
Problem
The previous architecture had no single correctness relation.
ConvergenceStagecallbacks, path/session variants, barriers,
false_means_pending,convergence_debt, FTS repair and freshness ledgers, aggregate refresh guardsand status-specific probes each carried part of "is this output current?" — with
duplicated repair and readiness surfaces, and the sole-writer boundary held
across work computable from a stable read snapshot.
Solution
Architecture follows the already-decided SELECT-HYBRID result from the closed
polylogue-04r9f; that experiment is not reopened.Compute runs outside the writer lease; only
publishis admitted, revalidatingframe and upstream identities and atomically replacing exactly one partition.
Generation isolation holds: all adapters bind to a resolved active index path and
refuse a moved binding, so a bulk rebuild cannot certify the active generation.
Embedding reuse requires exact message semantic identity plus complete recipe
identity, and
inspectadditionally requires physical vector presence ratherthan trusting metadata.
Readiness now has a third state.
ClaimGuardEntry.valueisbool | Nonewith adeterminateflag:valuedeterminatereasontruetruereadyfalsetruenullfalseTwo ordering guarantees: only a determinate domain may produce
false, and aproven failure outranks an unmeasured one, so a real counterexample beside an
unknown still reports
false.nullis falsy, so no consumer newly claimsconvergence; consumers testing
is Falsenow fire only on a proven failure.This is AC7's "operation health and readiness are not silently collapsed".
Verification
Baselined against clean master rather than assumed: of 36 failures in the first
full daemon+storage run, 32 reproduce identically on master and are tracked
under
polylogue-7lhl5. This branch introduced 4 and fixed 1(
test_insight_readiness_reads_convergence_debt_as_its_only_signal, a testmemorializing the deleted debt machinery — exactly what AC9 requires). All 4 are
fixed here:
converge_session_profilescalledasyncio.run()from a sync builder that async tests invoke directly. Fixed bydriving the coroutine on its own thread.
surviving behaviour, each stating its anti-vacuity condition — not deleted, and
no assertion weakened.
Correctness fix found in review
storage/fts/derivation.pyclassified a session partitionvalidwhile theoutput relation still held rows for a deleted block, and the session publisher
could no longer remove them. The candidate had replaced master's
block_id-rangepredicate with an inner join to
blocks, which structurally cannot see anFTS row whose canonical block is gone.
Master's plain prefix range is also wrong — it claims a colon-prefixed child
session's live rows — so neither predicate alone is correct. The fix composes
both: the range finds block-less residue, and
b.block_id IS NULL OR b.session_id = keykeeps a sibling's rows out. Applied toexcess_rows,duplicate_rowsand the publish delete set.Anti-vacuity verified, not asserted: restoring the inner join makes the new
test fail. The orphan-cadence stamp also moved to after the probe, so a pass that
finds nothing no longer burns the whole 3600s window.
Also fixed: a circular import that made
import polylogue.operations.fts_derivationfail unless
polylogue.daemonwas imported first, and the doubledinput_for/SHA-256 per FTS partition inspection.Schema identity
The derived index identity moves, as expected for this change:
docs/design/domain-derivation-deletion-ledger.mdrecords it and the"land before a rebuild starts, never during one" constraint. No hardcoded
identity hash exists anywhere in the tree and nothing assumes it unchanged.
EMBEDDINGS_SCHEMA_VERSION5 → 6 hard-invalidates an existingembeddings.db;maintenance/embedding_preservation.pyis the vector-preserving replacementroute.
Residuals — the bead stays open
polylogue-crwl6—fts_readiness_info's five request-path callers stilldo archive-proportional work. The bounded-report fix was implemented here and
the existing tests refuted it:
test_health_contract.pyrequires/healthz/readyto return a real membership verdict while forbidding exactscans, so reporting "unmeasured" turned a healthy daemon into a 503. Reverted
cleanly. That is the proof these callers have no honest bounded answer without
domain-local binding columns, which is what that bead owns.
polylogue-av5j1—repair_message_fts_index_syncis ~8× slower on therebuild route (45.7s vs 5.7s over 2000 sessions), and the partition SQL builds
an unbounded
IN (...)list against the repo's own never-assume-above-999rule. Inherited on both heads, but newly on more routes here.
ConvergenceStageusers are exactly the six product domains thedeletion ledger names: Sinex publication, cache warming, attachment bytes,
Claude workflow, delegation evidence, standing queries.
convergence_debtsurvives only as evidence; no migrated domain consults it as authority.
tests/unit/cli/test_status.py::test_status_subprocess_malformed_convergence_debt_json_is_explicitly_unavailablefails at this branch's base, bisected — same readiness-claim class, noted on
polylogue-crwl6.devtools gate atlasfails on both heads; this branch reduces it 135 → 113BLOCK lines but adds some of its own in
docs/atlas/storage.md.storage/fts/drift_sampling.pyis now callerless, soops.db'sfts_drift_samplesis a permanently empty disposable relation.🤖 Generated with Claude Code
https://claude.ai/code/session_01DYUNBGoE652b3nfmq3CtqK