Skip to content

fix: Read an unloadable vec0 extension as unmeasurable, not zero - #5146

Merged
Sinity merged 1 commit into
masterfrom
fix/embedding-coverage-unmeasurable-32ng2
Sep 14, 2026
Merged

Sinity merged 1 commit into
masterfrom
fix/embedding-coverage-unmeasurable-32ng2

Conversation

@Sinity

@Sinity Sinity commented Sep 14, 2026

Copy link
Copy Markdown
Owner

Summary

Classifies an unloadable vec0 extension as unmeasurable embedding coverage instead of a measured zero, and carries that third state — None, never 0 — through EmbeddingStatsSnapshot, ArchiveStats, the vec provider's stats route, the CLI, MCP and the TUI.

Closes polylogue-32ng2.

Context: polylogue-go581 and polylogue-g827i were already fixed on master by #5048 (verified against current source, see Residuals). This PR fixes the underlying predicate and the two consumers #5048 did not route through the probe.

Problem

polylogue/storage/embeddings/support.py:is_missing_table_error folded "no such module: vec0" in with a genuinely absent relation.

Concrete input: an embeddings.db holding a complete, reusable vector set, opened where the sqlite-vec extension cannot load (no sqlite_vec wheel for the interpreter, a stripped deployment, an enable_load_extension refusal).

Every SELECT ... FROM message_embeddings then raises no such module: vec0, the predicate swallowed it, and each of the eight call sites in support.py returned 0 / None / [].

Wrong observable outcome, at the two consumers that bypass ArchiveEmbeddingStateProbe:

  • storage/repository/vectors/repository_vectors.py published ArchiveStats(embedded_sessions=0, embedded_messages=0, pending_embedding_sessions=<whole corpus>), and ArchiveStats.embedding_readiness_status answered "none".
  • storage/search_providers/sqlite_vec_queries.py:get_embedding_stats published {"embedded_messages": 0, "pending_sessions": <whole corpus>}.

embeddings.db is the expensive to rebuild tier: its vectors are re-purchased from a paid provider, never replayed from source. An archive whose vectors are intact therefore reported as un-embedded and prescribed a full paid Voyage re-embed. An extension-load failure means cannot tell, not nothing embedded.

Two tests enshrined the behavior: test_read_embedding_stats_sync_treats_missing_vec_module_as_optional and TestEmbeddingStatsLockedConnection::test_missing_vec_module_treated_as_optional both raised no such module: vec0 and asserted the counts were 0.

Solution

  • EmbeddingCoverageUnmeasurableError (new, in support.py) carries "the tier could not be inspected" out of the optional-read helpers with its reason retained. _classify_optional_error is the single classification point all eight handlers now route through.
  • is_missing_table_error narrows to genuine absence. is_unmeasurable_coverage_error matches no such module.
  • no such column deliberately stays classified as absence. The audit proposed reclassifying it too; the first run of these tests refuted that. These readers use it as optional-feature detection against older derived shapes — embedding_status.message_count_embedded on the repo's own fixture — where the relation is present and the missing column genuinely means the feature is not recorded. Reclassifying it turned a healthy fixture unmeasurable.
  • EmbeddingStatsSnapshot / ArchiveStats type the coverage counts int | None and carry coverage_unmeasurable_reason. read_embedding_stats_sync/async convert the typed error into a snapshot with None counts.
  • ArchiveStats.embedding_readiness_status answers "unknown" (not "none"); embedding_coverage and retrieval_ready return None; to_dict publishes embedding_coverage_measurable and the reason.
  • Surfaces render the unknown rather than a number: the CLI stats line prints Embeddings: unknown -- coverage could not be measured (<reason>), the TUI dashboard shows ?, and MCP emits None. _payload_from_stats now honours the snapshot's own unmeasurable verdict (the fast route builds no probe), so the status payload reaches status: "unknown" / next_action: coverage_unmeasurable on that route too.

Verification

devtools test tests/unit/storage/test_embedding_stats.py \
  tests/unit/storage/test_embedding_contracts.py \
  tests/unit/storage/test_vec_dimension_refusal.py \
  tests/unit/storage/test_embedding_freshness_invariant.py \
  tests/unit/cli/test_embed_status_fast.py \
  tests/unit/archive/test_archive_stats.py
devtools test: PASSED exit=0 diagnosis=pytest_passed
  receipt=.cache/verify/runs/20260914T184344Z-focused-test-3816044-487e16b2/run.json

devtools verify --quick      all 17 gates ok

Anti-vacuity, verified by reverting and observing the failure. Restoring the pre-fix predicate (is_unmeasurable_coverage_error → False, no such module: vec0 back in is_missing_table_error):

tests/unit/storage/test_embedding_stats.py::test_read_embedding_stats_sync_reports_missing_vec_module_as_unmeasurable
>       assert stats.embedded_sessions is None
E       assert 0 is None
E        +  where 0 = EmbeddingStatsSnapshot(embedded_sessions=0, embedded_messages=0, pending_sessions=0, ...,
                      coverage_unmeasurable_reason=None).embedded_sessions

Removing the unknown branch from ArchiveStats.embedding_readiness_status:

tests/unit/storage/test_embedding_stats.py::test_archive_stats_never_renders_unmeasurable_coverage_as_none_status
>       if self.embedded_messages <= 0:
E       TypeError: '<=' not supported between instances of 'NoneType' and 'int'

Schema closure

devtools schema closure on every touched file:

file closure
polylogue/archive/stats.py IN
polylogue/storage/embeddings/embedding_stats.py IN
polylogue/storage/embeddings/models.py IN
polylogue/storage/embeddings/support.py IN
polylogue/storage/search_providers/sqlite_vec_queries.py IN
polylogue/storage/embeddings/status_payload.py out
polylogue/cli/query_stats.py out
polylogue/mcp/payloads.py out
polylogue/storage/repository/vectors/repository_vectors.py out
polylogue/ui/tui/screens/dashboard.py out

Five files are IN the derived schema closure, so the derived identity moves: this must land before a fresh rebuild starts, never during one.

Residuals

  • polylogue-go581 and polylogue-g827i are already fixed on master by fix: Report unmeasurable embedding coverage and stop dropping vectors on read #5048 (981e268d4, landed today), which both beads' text predates. _reconcile_vec0_dimension and its DROP TABLE IF EXISTS message_embeddings are gone; _assert_vec0_dimension raises a typed SchemaSkewError naming both dimensions, and discarding vectors is now only reachable through the explicit drop_vec0_for_dimension_change maintenance route. ArchiveEmbeddingStateProbe already separates measured / measured-absence / unmeasurable. Neither is re-fixed here.
  • g827i and 32ng2 are not duplicates: same defect shape, different layers. g827i was the status payload, fixed at the probe; 32ng2 is the predicate underneath it plus the two consumers that never call the probe.
  • no such column remains classified as absence, with the refuting evidence recorded in the predicate's docstring. If a caller later needs it to mean drift, it needs a per-call-site distinction, not a global reclassification.
  • docs/plans/sqlite-degradation-baseline.json: the four support.py anchors are re-fingerprinted 1:1 (same four sites, same counts, new digests because the handler bodies changed shape). Total is unchanged at 268; no new degradation site is baselined.
  • Broad/affected suites not run — focused evidence only, per the repo's verification policy.

🤖 Generated with Claude Code

https://claude.ai/code/session_01DYUNBGoE652b3nfmq3CtqK

`is_missing_table_error` folded `no such module: vec0` in with a genuinely
absent relation, so on an archive whose vectors are intact but whose
sqlite-vec extension does not load, every `SELECT ... FROM message_embeddings`
was converted to a measured 0. `ArchiveStats` then published
`embedded_messages=0` with `pending == the whole corpus`, and
`embedding_readiness_status` reported `none` -- the value that prescribes a
paid Voyage re-embed of vectors that are present and reusable.

`embeddings.db` is the expensive-to-rebuild tier: its vectors are
re-purchased from a paid provider, never replayed from source. An
extension-load failure means *cannot tell*, not *nothing embedded*.

A new `EmbeddingCoverageUnmeasurableError` carries that third state out of the
optional-read helpers. `EmbeddingStatsSnapshot` and `ArchiveStats` now type
the coverage counts `int | None` with a retained
`coverage_unmeasurable_reason`, and `embedding_readiness_status` answers
`unknown` rather than `none`. `no such column` deliberately stays classified
as absence: these readers use it as optional-feature detection against older
derived shapes (`embedding_status.message_count_embedded`), where the relation
is present and the missing column genuinely means the feature is not recorded.

Two tests that enshrined the zero are rewritten to assert the unmeasurable
state; both were confirmed red under the pre-fix predicate
(`assert 0 is None`).

Closes polylogue-32ng2.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01DYUNBGoE652b3nfmq3CtqK
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, add credits to your account and enable them for code reviews in your settings.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 14, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
🔒 Security Review ✅ Completed 2026-09-14T18:58:01.659468Z 57f8704 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@coderabbitai

coderabbitai Bot commented Sep 14, 2026

Copy link
Copy Markdown

Warning

Review limit reached

Next included review available in 23 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Learn how review limits work.

Review configuration:

⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Advanced

Run ID: 437c5e2f-c34d-4721-83f2-f2645f422cbd

📥 Commits

Reviewing files that changed from the base of the PR and between a3f5f9c and 57f8704.

📒 Files selected for processing (13)
  • docs/plans/sqlite-degradation-baseline.json
  • polylogue/archive/stats.py
  • polylogue/cli/query_stats.py
  • polylogue/mcp/payloads.py
  • polylogue/storage/embeddings/embedding_stats.py
  • polylogue/storage/embeddings/models.py
  • polylogue/storage/embeddings/status_payload.py
  • polylogue/storage/embeddings/support.py
  • polylogue/storage/repository/vectors/repository_vectors.py
  • polylogue/storage/search_providers/sqlite_vec_queries.py
  • polylogue/ui/tui/screens/dashboard.py
  • tests/unit/storage/test_embedding_contracts.py
  • tests/unit/storage/test_embedding_stats.py

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@Sinity
Sinity merged commit e991cfa into master Sep 14, 2026
3 checks passed
@Sinity
Sinity deleted the fix/embedding-coverage-unmeasurable-32ng2 branch September 14, 2026 19:10
Sinity added a commit that referenced this pull request Sep 14, 2026
## Summary

Lands **Seam A** (`polylogue/cli/lowering.py`) and refines
`operation_kernel.dispatch`, then
**deletes the CLI's local `ArchiveStore` query executor**. Root `find`,
`analyze count/by/stats`,
exact-ref reads, `--stream`, `sample`, `latest`, `with <units>` and
`from <ref>` now all lower to a
declared operation and execute through one kernel. This is step S3 of
the CLI unification.

Based on #5109 (S2), which had not merged when this branch was cut.

## Problem

Two implementations of what `find` means coexisted: the in-process
`cli.query` handler
(`operations/daemon_reads.py`) and the local `ArchiveStore` branch of
`_execute_archive_query_stdout`
(`cli/archive_query.py`), with a gate
(`_daemon_session_page_supported`), a parameter rewriter
(`_daemon_session_query_params`) and a row normalizer deciding between
them. A query served locally
and the same query served by the operation could differ, and
`--no-daemon` forced the local branch —
so "daemon off" silently meant "different executor", not "same executor,
no socket".

S1 removed the stale rejections; five genuine capability gaps remained
(aggregates, exact-ref reads,
`--stream`, `sample`, `with` projection). S2 declared the operations
that close them. Neither half is
safe alone: deleting the gate without the branch changes behaviour for
the gaps, deleting the branch
without the operations loses capability. Hence one step.

## Solution

- **`cli/lowering.py` (new, Seam A)** — the only module that reads Click
parameter names, emitting
`OperationRequest`: `lower_cli_query`, `lower_query_units`,
`lower_query_aggregate`,
  `lower_session_read`, `lower_session_reference`.
- **`operation_kernel.dispatch`** — replaces `configured_read_operation`
(kept as a thin adapter for
callers not yet on Seam A). Direct-read context construction is now
**lazy**: a warm daemon no
longer pays for a vector binding it never uses. Adds `deadline_ms` and
`read_control`
(cancellation/deadline) passthrough. A handler's typed refusal on the
direct path is now framed as
the declared error envelope instead of escaping the kernel as a bare
exception — see Residuals.
- **Deleted** from `cli/archive_query.py`: the local branch,
`_query_hits`, `_count_root_matches`,
`_try_emit_daemon_session_page` / `_try_emit_daemon_unit_page`,
`_daemon_session_page_supported`,
`_cli_query_operation_params`, `_daemon_session_query_params`,
`_fetch_daemon_*`, `_paginate_rows`,
`_build_cursor`, `_matched_session_ids_for_stats`,
`_inject_attached_units`, `_emit_unit_source_rows`,
`_summary_payload`, `_hit_payload`, `_session_payload`, `_emit_search`,
`_emit_list`,
`_execute_reference_query_pipeline`, the `archive_read_context` import,
the `ArchiveStore` PEP-562
  shim and the `create_vector_provider` patch seam. 3,188 → 2,130 lines.
- **`session.read` result reshaped** (S2 contract): `session` now
carries the archive's own identity
vocabulary (message/block ids, raw `origin`, canonical topology) instead
of the browser reader's
display envelope, which relabels `origin` through `role_label` — a label
the Origin mapping cannot
be reversed from. Renderers are now pure functions of the operation
result.
- **Capability kept, moved handler-side**: the `lineage:id:`
recursive-graph projection columns and
the `with <unit>` attached-unit projection are now produced by the
`cli.query` handler and joined
onto rows by the renderer. `cli.query`'s handler also now resolves an
explicit `--id` scope to a
full session id before filtering (an unresolved native id silently
scoped a page to nothing), and
the ranked path now emits `total_unit` — without it a `--no-root` search
labelled subagent rows
"top-level sessions". `QueryResult` requires that label on both branches
now, not just the list.
- **`operations.operation_context.operation_archive_root`** resolves the
file set a read executes
against from `config.db_path`, so a `--db` pin at a non-active
generation is answered from the
generation the operator named. Placed in the operations layer
deliberately: doing it in the CLI
  would have restored a `cli → storage` layering edge this step removes.

### Regressions found by test retargeting and fixed here

Retargeting the tests surfaced seven behaviour differences the
documented-invocation corpus could
not see, because no documented example exercises them. All are fixed and
the original law restored:
`--semantic` (the CLI-only lane spelling is now desugared in Seam A, not
left to reach a handler
that refuses it); `--id <native-id> <terms>`; `--id X --open` (now a
one-message window to resolve
the reference, not a full hydration); `--no-root` total labelling; a
missing local `index.db`
(deferred so a resident daemon can still serve); the `--db` split-root
pin; and an unparseable
`--since` (back to exit 1, `Cannot parse date: '...'`). A missing `--id`
is exit 1 again, not 2.

## Golden bytes

`scripts/golden_find_bytes.py` (added) extracts every documented `find`
invocation from
`docs/cli-reference.md` and runs it against a seeded `cli-mixed` archive
under a frozen clock and
pinned `perf_counter`, with the daemon off. Deterministic (verified by
repeat runs).

**36 of 37 invocations are byte-identical** before and after. 13 were
skipped as side-effecting
(`--to browser`, `then mark`, `then delete --yes`, `then continue
--exec`) or as help screens.

The one difference is deliberate and is exactly the divergence S1
declined to resolve:

```
polylogue find 'near:"semantic search"' then read
- Error: Vector retrieval requires configured sqlite-vec and Voyage embeddings.
+ Error: semantic retrieval is unavailable: no configured/constructible vector backend;
+        configure Voyage/sqlite-vec and retry
```
Same refusal, same exit code (2); the operation's message names the next
step. The local branch's
message is gone with the local branch.

The documented aggregate invocations all land on **empty** selections in
the fixture, which is weak
evidence, so a second set of 10 non-empty cases was captured on the base
commit and re-run here:
`analyze` plain/`--count`/`--by origin`/json forms, `--sample`,
`--latest`, `--stream`,
`--stream --limit 2`. **9 of 10 byte-identical.** The tenth is
`--sample`, which is defined to return
a random page: verified genuinely random across 8 separate processes (8
distinct orders), so its
bytes are not a stable golden. Within one process repeated `--sample`
requests reuse the pinned
reader and repeat — pre-existing to the operation executor, not
introduced here, but it means a
resident daemon would repeat a sample; recorded as a residual.

## Layering

`polylogue/cli/archive_query.py` had **6** surface→substrate baseline
entries
(`storage.archive_identity`, `storage.search_providers`,
`.search_providers.sqlite_vec_support`,
`storage.sqlite.archive_tiers.{archive,index,write}`). It now has **0**
— the module does not import
`polylogue.storage` at all. `polylogue/cli` entries: **79 → 73**; total
baseline **279 → 273**.
`devtools gate layering` passes with 0 violations.

## Verification

```
devtools verify --quick     all 17 gates ok (format, lint, mypy, generated-surfaces,
                            layering, patterns, doc-commands, schema-manifest,
                            oracle-integrity, testmon-selection, consumer-reachability,
                            test-packages, timestamp-doctrine, durable-enum-checks,
                            schema-privacy, atlas, population-coverage)
devtools render all --check exit 0, no "out of sync"
mypy polylogue tests        Success: no issues found in 2746 source files

devtools test tests/unit/cli -k "query or find or kernel"
  PASSED exit=0 diagnosis=pytest_passed

devtools test tests/unit/cli
  FAILED exit=1 — 3032 passed / 6 failed / 2 xfailed / 2 skipped

devtools test tests/unit/operations tests/unit/surfaces \
             tests/unit/archive/test_route_hydration_parity.py \
             tests/unit/mcp/test_lineage_completeness_payload.py
  PASSED exit=0 diagnosis=pytest_passed
```

**The 4 remaining reds are inherited, not caused here**, all in
`test_plain_cli_snapshots.py`:

- `test_json_read_all_snapshot`, `test_json_status_snapshot` — stored
`.ambr` snapshots
predating the terminal-outcome envelope. Both fail identically on
unmodified
  `bfde745c3` (verified by running them there).
- `test_facets_command_json_matches_analyze_facets` — `facets` returns
empty
`family_status` / `deadline_s None` where `analyze --facets` returns
populated. Also
  red on `bfde745c3`.
- `test_json_analyze_snapshot` — #5146 ("Read an unloadable vec0
extension as
  unmeasurable, not zero") added `embedding_coverage_measurable` and
`embedding_coverage_unmeasurable_reason` to `ArchiveStats.to_dict()`
without
re-recording this snapshot. The diff is two *added keys*, not changed
values, and
`_emit_stats` (which calls `to_dict()`) is untouched here. Checked
explicitly that this
step's stats round-trip is not hiding behind it:
`_archive_stats_from_result` preserves
`embedding_coverage_unmeasurable_reason` (a real dataclass field) and
re-derives
`embedding_coverage_measurable` (a property) — a reason of
`vec0_unloadable` survives
  the wire round-trip and still yields `measurable=False`.

Two reds present earlier in this branch's life —

`test_status_subprocess_malformed_convergence_debt_json_is_explicitly_unavailable`
and both
`test_daemon_client.py::test_daemon_mutation_*_indeterminate` (stale
doubles missing
`connect()`) — were fixed on master and are green after the rebase.

## Layering

`polylogue/cli/archive_query.py` had **6** surface→substrate baseline
entries
(`storage.archive_identity`, `storage.search_providers`,
`.search_providers.sqlite_vec_support`,
`storage.sqlite.archive_tiers.{archive,index,write}`). It now has **0**
— the module does not import
`polylogue.storage` at all. `polylogue/cli` entries: **79 → 73**; total
baseline **279 → 273**.
`devtools gate layering` passes with 0 violations.

## Verification

```
devtools verify --quick     all 17 gates ok (format, lint, mypy, generated-surfaces,
                            layering, patterns, doc-commands, schema-manifest,
                            oracle-integrity, testmon-selection, consumer-reachability,
                            test-packages, timestamp-doctrine, durable-enum-checks,
                            schema-privacy, atlas, population-coverage)
devtools render all --check exit 0, no "out of sync"
mypy polylogue tests        Success: no issues found in 2746 source files

devtools test tests/unit/cli -k "query or find or kernel"
  PASSED exit=0 diagnosis=pytest_passed

devtools test tests/unit/cli
  FAILED exit=1 — 3032 passed / 6 failed / 2 xfailed / 2 skipped

devtools test tests/unit/operations tests/unit/surfaces \
             tests/unit/archive/test_route_hydration_parity.py \
             tests/unit/mcp/test_lineage_completeness_payload.py
  PASSED exit=0 diagnosis=pytest_passed
```

**The 6 remaining reds are inherited, not caused here.** Each was run on
unmodified
`bfde745c3` and fails there identically: `test_json_read_all_snapshot`
and
`test_json_status_snapshot` (stored `.ambr` snapshots predating the
terminal-outcome
envelope), `test_facets_command_json_matches_analyze_facets` (`facets`
returns empty
`family_status`/`deadline_s` where `analyze --facets` returns
populated),

`test_status_subprocess_malformed_convergence_debt_json_is_explicitly_unavailable`,
and
both `test_daemon_client.py::test_daemon_mutation_*_indeterminate` (test
doubles missing
the `connect()` production has called since before this branch). They
are deliberately
left red rather than repaired inside this PR.

## Closure

`devtools schema closure` on every file touched:

| file | |
| --- | --- |
| `polylogue/cli/lowering.py` | out |
| `polylogue/cli/operation_kernel.py` | out |
| `polylogue/cli/archive_query.py` | out |
| `polylogue/cli/operation_bindings.py` | out |
| `polylogue/operations/daemon_reads.py` | out |
| `polylogue/operations/daemon_protocol.py` | out |
| `polylogue/operations/operation_context.py` | out |
| `polylogue/api/archive.py` | out |
| `polylogue/daemon/http.py` | out |
| `docs/plans/layering-surface-baseline.json` | out |
| `scripts/golden_find_bytes.py` | out |

S3 is closure-free, as the design predicted. The derived schema identity
does not move.

### Machine-envelope change, named deliberately

`source` on a list/search envelope now reports the executor that
actually answered
(`"direct"` or `"daemon"`), read from the result's own authority.
Previously the local
branch emitted no `source` key and the daemon branch hardcoded
`"daemon"` — so after
unification every `--no-daemon` page would have claimed daemon
provenance. On the direct
route this is a new key. `test_json_envelope_contract.py` does
membership checks rather
than pinning an exact key set, so nothing was silently broken.

## Residuals

- **One in-process read remains in `archive_query.py`**:
`_search_miss_diagnostics`, the zero-hit
query-miss diagnosis, still calls `env.polylogue.diagnose_query_miss`
through the async facade. No
operation declares a query-miss diagnosis. Routing it through the
operation would have silently
dropped the "Why this may have missed" block from three documented
invocations, so it is kept and
  labelled as the single exception. Declaring it is follow-up work.
- **`from <ref>` plaintext rendering changed deliberately**: the old
renderer joined member refs on
`"\\n"` — a literal backslash-n — putting every ref on one line. It now
emits one ref per line. No
documented invocation and no fixture covers a reference query, so this
is unverified by the golden
  set.
- **`--cursor` with `--latest`** now refuses again ("only supported for
list and search pages"). S1's
gate removal had let that combination through; the refusal is the
documented intent.
- **`--sample` within one process** repeats its page (pinned-reader
reuse in the operation executor).
  Per-invocation CLI use is unaffected; a resident daemon would repeat.
- **`cli/query_stats.py` was NOT deleted.** The design lists it as an S3
deletion with
"`archive_query.py` only" as its consumer; that is stale —
`cli/query_output.py` imports it. It
  belongs to S4, which owns `query_output.py`.
- **`polylogue/storage/search_providers/hybrid.py`** still cites
`cli/archive_query.py` as a
retrieval executor in its module docstring. That file is **IN** the
derived-schema closure, so
fixing a docstring there would move the schema identity and force a
reconvergence; left for
whoever next edits it for a real reason. The equivalent stale citation
in `daemon/http.py` (out of
  closure) is fixed here.
- **The kernel's catch-all is a sharp edge.** `OperationKernel.execute`
maps any exception
from its call into `daemon_transport_error`. That is right for a daemon
call and wrong
for the local reader: while direct execution sat inside that callback, a
fresh install's
`sqlite3.OperationalError` — which `ops status` reads as "no archive
yet, daemon not
running" — was rewritten into "daemon unreachable". `dispatch` now runs
the direct read
outside the kernel. Worth knowing before S4-S12 move more routes through
it.
- **`polylogue.daemon.api_auth` transitively imports the whole
`polylogue.api` stack**, so
a daemon-served query pays that import at the transport boundary.
Verified pre-existing
on master — `test_daemon_fastpath_import_cost.py` only passed before
because it stubbed
above the kernel. The test keeps its original scope with the gap
documented rather than
  being widened into an unrelated failure here. Deserves its own task.
- **`lineage:id:` pages lose the page-level `continuation` column.** The
operation's list path has no
cursor machinery, so `parent_refs`/`child_refs` are restored but
`continuation` is not. No fixture
  exercises a lineage page; untested either way.

🤖 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]>
Sinity added a commit that referenced this pull request Sep 14, 2026
## Summary

Lands Seam B of the CLI unification design (`cli-unification-design.md`
§2.1, step S4) as `polylogue/cli/render/`: one row renderer over
declared operation results, one owner of the terminal exit code, and the
deletion of the client-side row translation layer S3 left standing.

## Problem

After S3 (#5152) every root read is a declared operation, but the CLI
still carried a second idea of what a session row is:

- `archive_query._normalize_daemon_list_item` +
`_DAEMON_LIST_ITEM_KEEP_KEYS` reshaped every operation row into a CLI
row. Its `word_count` → `words` fallback was already dead (both sides
build `SessionListEnvelope`), leaving a keep-key table as the only
remaining difference — a second declaration of the row vocabulary, on
the wrong side of the boundary.
- `_emit_daemon_list_payload` / `_emit_daemon_search_payload` re-derived
`total`, `limit`, `next_offset` and, when absent, the terminal outcome,
duplicating facts the operation had already reported.
- `_emit_degraded_daemon_search_payload` ended with `raise
SystemExit(OUTCOME_EXIT_CODES["degraded"])`, and `_emit_open_no_results`
with `emit(exit_code=OUTCOME_EXIT_CODES["empty"])` — two surfaces
choosing an exit status by name instead of from the outcome, which is
exactly how a `degraded` zero-row page can be reported as `empty`.
- No-results feedback had three owners: `archive_query._emit_no_results`
(envelope-driven), `cli/query_feedback.py` (spec-driven) and
`cli/convergence_feedback.py` (the warning both printed).
- `query_output.py` carried six functions with zero production
consumers, and they were the only thing keeping `cli/query_stats.py` and
`cli/query_semantic.py` reachable.

## Solution

**`polylogue/cli/render/rows.py`** — one row renderer.
`emit_session_list_page` and `emit_session_search_page` (which absorbs
the degraded and empty forms) render the operation's page verbatim:
`total`, `limit`, `total_unit`, `next_cursor` and `outcome` are read,
never re-derived. `emit_rows`, `project_payload`, `selected_fields`,
`csv_text`, `summary_line_renderer`, `hit_line` and `stats_by_line`
relocate here, along with the render-phase timing `ContextVar`.

**The operation row is the CLI row.** The row vocabulary is declared
once, in `operations/daemon_reads._SESSION_LIST_ROW_FIELDS`, at the
boundary that builds the row. `SessionListEnvelope`'s remaining three
fields (`title_source`, `title_ref`, `cost_provenance`) describe how a
title or cost was derived — reader-surface provenance affordances that
no CLI format has ever printed — so they are projected out where the row
is made rather than filtered out where it is rendered. `daemon_reads.py`
is OUT of the derived-schema closure, so this does not move the
identity.

**`polylogue/cli/render/outcome.py`** — one exit-code authority. Absorbs
`_emit_no_results` (as `emit_empty_page`) and all of
`cli/query_feedback.py`. `exit_for(outcome)` is the only exit path,
`EMPTY_EXIT_CODE` is derived from
`outcome_exit_code(decide_outcome(matched=0))` rather than named, and
both previous by-name lookups are gone. A daemon-supplied outcome is
still preserved verbatim.

`cli/convergence_feedback.py` is **not** folded in, deliberately: the
probe imports `storage.archive_readiness`, which is precisely the
substrate import the Seam B rule (design §2.2) forbids a renderer.
Moving it made `gate layering` go red on a new unbaselined edge — the
gate correctly refusing the shortcut. `render/outcome.py` renders the
warning; the probe keeps producing it. Its real home is behind the
`status` operation, which already reports
`component_readiness.raw_materialization` (residual below).

**Deletions.** The four `_emit_daemon_*` functions,
`_normalize_daemon_list_item`, `_DAEMON_LIST_ITEM_KEEP_KEYS`,
`cli/query_feedback.py`, `cli/query_stats.py`, `cli/query_semantic.py`,
and the `query_output.py` functions the design named. Five of the six
had zero consumers anywhere. The sixth, `summary_to_dict`, has an
in-module caller (`format_summary_list`) the design's grep missed, so
its *export* is deleted and it becomes `_summary_to_dict`.
`tests/unit/cli/test_query_stats.py` goes with the module it certified;
`test_query_fmt.py` loses the `_format_list`/`_write_message_streaming`
cases; `test_query_exec_laws.py`'s semantic-parity test is rewritten to
assert the surviving substrate law (`matches_referenced_path` across a
session's actions) now that the Python re-derivation it was paired
against is gone.

## Golden bytes

`scripts/golden_find_bytes.py` — **37 documented `find` invocations, 0
differing.**

S3's warning is that the documented aggregate examples land on empty
selections, so a companion harness over the same immutable `cli-mixed`
workload and frozen clock exercises 22 hand-picked **non-empty** cases
(list in all five formats, `--limit`/`--offset` pages, `--fields`
projection, `analyze count`, `analyze by origin`, `analyze by day`,
ranked search in text/json/csv, `--origin` filter, `--sort`/`--reverse`,
a `messages where` unit query, `--sample`, `with messages` projection;
17 exit 0 with rows). **22 cases, 0 differing** once
`run_id`/`generation_id`/`archive_epoch` — which vary per harness run on
master too — are normalized.

## Layering

`devtools gate layering`: **273 baseline entries before, 273 after**
(230 matched, 43 stale), 0 violations. S4 removes no baseline entry:
`query_output.py -> storage.runtime` survives on the still-live
`render_stream_*` signatures, and the deleted modules had no entries.
The one edge S4 would have *added* (`render/outcome.py ->
storage.archive_readiness`) was resolved by not moving the probe, not by
baselining it.

## Verification

```
devtools test tests/unit/cli/test_json_envelope_contract.py tests/unit/cli/test_query_fmt.py \
              tests/unit/cli/test_plain_cli_snapshots.py tests/unit/cli/test_machine_contract.py
  devtools test: FAILED exit=1 diagnosis=pytest_failed
```

Four failures, all inherited, all in `test_plain_cli_snapshots.py`:
`test_json_read_all_snapshot`, `test_json_analyze_snapshot`,
`test_json_status_snapshot`,
`test_facets_command_json_matches_analyze_facets`. The identical four
fail on `master` at this worktree's base (`devtools test
tests/unit/cli/test_plain_cli_snapshots.py`, receipt
`20260914T201951Z`). Every other test in the selection passes, and no
test moves between the two runs.

S4 does **not** re-record those snapshots. The renderer work produces
byte-identical output on 59 verified invocations, so these snapshots are
stale for reasons outside this change (three long-standing, one from
#5146 adding `to_dict()` fields); re-recording them here would fold an
unrelated fix into a refactor whose whole claim is that nothing changed.

```
devtools verify --quick   → exit 0, all 17 gates ok
devtools gate layering    → exit 0, 0 violations, 273 baseline entries
devtools render all --check → exit 0, grep "out of sync": 0 hits
devtools gate mypy        → Success: no issues found in 2866 source files
```

## Closure

```
devtools schema closure ...
  out  polylogue/cli/archive_query.py
  out  polylogue/cli/query_output.py
  out  polylogue/cli/render/__init__.py
  out  polylogue/cli/render/outcome.py
  out  polylogue/cli/render/rows.py
  out  polylogue/cli/convergence_feedback.py
  out  polylogue/operations/daemon_reads.py
```

Every touched file is OUT. **This PR does not move the derived schema
identity and does not gate a rebuild.**

That is a deliberate choice about the two fixes S1 applied at the
operation boundary rather than at their natural homes, which S3 recorded
as S4 work:

1. `daemon_reads._session_list_row` re-spells the archive's `...Z`
timestamps over the `...+00:00` that
`session_list_envelope_from_summary` produces. Natural home:
`surfaces/payloads.py` (IN).
2. `cli/lowering._selection_params` imports `_RECOGNIZED_PARAMS` under
its private name because a public alias would move the identity. Natural
home: `archive/query/spec.py` (IN).

**Neither is moved.** Both are cosmetic — a timestamp spelling and an
underscore — and moving either forces a full archive reconvergence for a
CLI-only refactor. The comments at both sites still name the correct
home, so whichever closure-moving change lands next can carry them for
free.

## Residuals

- `cli/convergence_feedback.py` remains a substrate read reachable from
a render path. The `status` operation already reports the same
readiness; a CLI read consuming it would retire the probe.
- Most of the rest of `query_output.py` (`format_summary_list`,
`output_summary_list`, `output_search_hits`, `format_search_envelope`,
`render_stream_*`, `no_results`, `open_result`) also has no production
consumer, only tests. That is S12's census, not S4's: several carry real
format laws whose surviving owner has to be named first.
- `archive_query.py`'s remaining renderers (`_session_text`,
`_emit_session_result`, `_emit_stream`, the `_*_query_line` family) have
not moved into `render/`; they go with S5's deletion of the module.
- The design's D4 claim that the operation row uses `word_count` is
stale at this head — both sides build `SessionListEnvelope`, which
spells it `words`. The only real divergence was the keep-key table,
which this PR resolves in the operation's favour.

🤖 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]>
Sinity added a commit that referenced this pull request Sep 14, 2026
## 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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant