Repository navigation
Declare the read operations the CLI still executes locally - #5109
Conversation
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
|
Warning Review limit reachedNext included review available in 53 minutes. View limit detailsLimit 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. Review configuration: ⚙️ Run configurationConfiguration used: Organization UI Review profile: ASSERTIVE Plan: Advanced Run ID: 📒 Files selected for processing (6)
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 |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
Declare query.aggregate, session.read and session.reference, and extend cli.query with sample, latest and the `with <units>` projection, so every remaining CLI read has a declared operation to lower to. Handlers call the existing shared executors (stats/stats_by/count_*, read_session_page, fetch_attached_units, the durable reference resolver) rather than growing a second implementation of what a query means. session.read is windowed by construction: a whole transcript can exceed the 8 MiB operation result bound, so the handler composes one page at the storage layer, mints a snapshot-bound QueryContinuation for the next window, and refuses a window it cannot deliver whole instead of truncating one silently. Request/result models live in the new operations/read_contracts.py, which is OUT of the derived-schema identity closure; surfaces/payloads.py is IN, so declaring them there would have moved the archive's schema identity for a CLI-only change. The `with <units>` projection rides beside the canonical list envelope for the same reason. polylogue/cli/operation_bindings.py joins every declared operation to the CLI code that lowers and renders it, or records why it has none, and the registry test keeps that table total. This step is declaration only; S3 migrates the call sites. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01DYUNBGoE652b3nfmq3CtqK
229050e to
bfde745
Compare
## 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]>
Summary
Step S2 of the CLI unification: declare the read operations the CLI still has
no operation for, so no CLI read needs a local executor. Declaration only —
S3 migrates the call sites.
query.aggregate(count / stats / stats_by)session.read(windowed transcript reads with a snapshot-bound continuation)session.reference(barefrom <ref>operands)cli.queryextensions:sample,latest, and thewith <units>projectionProblem
Five of the thirteen rejection groups in
_daemon_session_page_supported(
cli/archive_query.py:1293-1309) name real gaps rather than stale caution:aggregates, exact-ref transcript reads,
--stream,--sample, and thewithprojection have no declared operation, so those inputs are always served by the
local
ArchiveStorebranch. The reference pipeline (archive_query.py:211-288)is a second local executor with no operation at all. Until those exist, S3
cannot delete the local branch without losing capability.
Solution
polylogue/operations/read_contracts.py(new) holds the request/resultmodels. It is OUT of the derived-schema identity closure (D5);
surfaces/payloads.pyis IN, so declaring them there would have moved thearchive's schema identity for a CLI-only change.
daemon_reads.pycall the existing shared executors:archive.stats/stats_by/count_sessions/count_search_sessionsbehindspec_session_filter_kwargs+stats_filter_kwargs,read_session_page+session_detail_envelope_from_domain,fetch_attached_units, andresolve_ref_operandwithDurableRefResolverover the pinned reader'spaths. No handler carries its own query logic.
session.readis windowed by construction rather than bydiscovery: the handler composes only
[offset, offset+limit)at the storagelayer, mints a
QueryContinuationbound to the archive epoch for the nextwindow (reusing
archive/query/transaction.py, which is IN the closure andis therefore only consumed, never edited), and refuses a window whose
serialized size exceeds
MAX_OPERATION_RESULT_BYTESwith a message namingthe smaller limit.
complete/next_offset/continuationare checkedagainst each other by the result model, so a truncated read cannot report
itself whole.
with <units>projection rides beside the canonical list envelope(
attached_units) rather than inside it:SessionListResponseforbidsextras and lives in the closure.
QueryResult's validator (indaemon_protocol.py, OUT) validates the projection's shape and hands theenvelope the rest.
polylogue/cli/operation_bindings.py(new) is the registry diff the designnames: every
DaemonOperationSpecis bound to a CLI lowering + renderer,listed as pending adoption with the step that adopts it, or listed as
CLI-external with the reason. The three new operations arrive bound, not
pending.
Verification
Closure (
devtools schema closure) for every file this PR touches:No file in this change is in the closure; the derived schema identity does not
move and no reconvergence is required.
Anti-vacuity, verified by reverting and observing the failure:
empty_selection = False)test_text_selection_scopes_the_aggregate_to_matched_sessions:assert 2 == 0session.readalways mints a continuationtest_final_window_carries_no_continuation:TypeError: '<' not supported between instances of 'NoneType' and 'int'inQueryTransactionRequest.__post_init__session.readfrom the binding registrytest_every_declared_operation_is_classified_exactly_once:assert ('session.read',) == ();test_read_operations_declared_for_the_cli_are_bound_not_pending:OperationBindingError: session.read is not classifiedSessionReadResultcompleteness invarianttest_a_window_cannot_claim_completeness_and_a_next_offset:Failed: DID NOT RAISE OperationResultContractErrordevtools test tests/unit/cli/test_archive_query.py tests/unit/cli/test_daemon_operation_transport.py tests/unit/cli/test_json_envelope_contract.pyfails on exactly one test,
test_confirmed_delete_uses_an_unbounded_daemon_wait(
auth_tokenlambda vsNone) — an inherited failure from #5043, ownedelsewhere and untouched here. (Checked pre-rebase; #5043's fix may since have
landed.)
Residuals
513c8873aafter S0 (refactor: Share one query lowering and type daemon client errors #5094) and fix: Serve stale-gated session pages through the cli.query operation #5102 landed mid-flight. Theaggregate and
cli.queryhandlers go through the delegating_cli_query_spec/_lower_cli_query_params, which S0 repointed atoperations/query_lowering.py, so there is one lowering, not two. Theconflict resolution dropped my duplicate
latestclamp in favour of the onefix: Serve stale-gated session pages through the cli.query operation #5102 landed, and kept fix: Serve stale-gated session pages through the cli.query operation #5102's
_session_list_row.tests/unit/daemon/test_daemon_operation_route.py::test_cancelled_long_delete_retains_writer_until_blocked_apply_releasesfailed once on a 25 ms
operation.awaitdeadline race and passed on rerunand on the file alone. Pre-existing timing flake, untouched by this change.
session.referenceopens the durable user tier by path(
archive.user_db_path,archive.index_db_pathfrom the pinned reader)rather than through the pinned connection, mirroring the CLI route it
replaces. The generation is the pinned one; the connection is not.
ProjectionSpec→ContentProjectionSpecmapping covers the blockkinds
body_policyproduces (tool calls, tool outputs, reasoning). The fullread-view classification is D3/S8's table, not this step's.
session.lineage,context.compileand the write operations in §2.3 arenot in this step (S9/S10).
completionandingestare declared but still unreached from the CLI; theyare recorded in
CLI_PENDING_ADOPTIONwith their adopting steps (S7, S11).🤖 Generated with Claude Code
https://claude.ai/code/session_01DYUNBGoE652b3nfmq3CtqK