Repository navigation
Route CLI facade writes through declared daemon operations - #5172
Conversation
`polylogue-5vps8.2` closed on an empty
`layering-cli-mutation-authority-baseline.json`, but `mark`, `compare` and
`judge` still opened a writable `ArchiveStore` in the CLI process. The rule
could not see them: it matches a direct surface-to-substrate import, and these
writes entered through `polylogue.api.Polylogue._execute_facade_mutation`,
which the CLI rule allows unrestricted. The baseline was green because it was
enforcing a form the bypass does not take (polylogue-gjwto).
Decision D1: apply the mutation-authority rule to `polylogue/api` as well. The
facade's own executor imports are now visible and baselined, so the baseline
reads two honest entries instead of a misleading zero, and the ratchet can only
shrink them.
Declare and serve `mutation.session.mark`, `mutation.annotation.save` and
`mutation.judgment.record`; extend `mutation.session.tag` with a `remove_tags`
direction. `mark` (tags, marks, notes), `compare` and `judge` lower to them
through one new `submit_cli_mutation` seam. With no daemon the command refuses
with a typed error naming the operation and `polylogued run` -- the CLI is not
expected to work standalone, so there is no local fallback to offer.
Two authority defects surfaced while proving the route end to end:
`_declare_executor_authority` overwrote an authored `allowed_surfaces` with
`("api",)`, denying every CLI-lowered mark and annotation write; and the daemon
principal's capability set was derived from each spec's single `capability`, so
`mutation.session.mark` could add a mark but never remove one. Operations now
declare `additional_capabilities`, and the principal set is derived from that.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01DYUNBGoE652b3nfmq3CtqK
|
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 52 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 (25)
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. |
## Summary Three unrelated tests on `master` still describe the world before a landed product change. Each names the PR that moved the product. None is a product defect; in each case the product is right and the test was left behind. ## Evidence Receipt `.cache/verify/runs/20260914T233651Z-all-207009-89ddea6b` (`verify_all`, job 1699, 22,540 selected, 29 failed). **Caveat on that receipt:** its `run.json` records `git_head: f7964ac` — the tip of branch `rebase-5165`, *not* `master` and not an ancestor of it — and `final_git_head: 724d175`. The shared checkout advanced across 7 merged PRs during the run, so it is not evidence of a frozen tree. I re-ran all 29 node ids at true `master` HEAD: 17 reproduce, 12 do not. These 3 are among the 17. ## Per-failure classification | Failure | Classification | Which PR moved the product | | --- | --- | --- | | `test_schema_policy_contracts::test_read_only_archive_open_does_not_bootstrap_missing_tiers` | **stale test** | #5162 (`817eec6f4`) typed the refusal as `ArchiveTierUnavailableError` | | `test_write_path_state_machine::test_positional_branch_point_alias_is_typed_dangling` | **stale test** (premise no longer constructible) | #5103 (`398c60458`) made id-less message identity content-derived | | `test_compare_command::test_compare_with_verdict_records_and_is_readable_via_calibration` | **stale test** | #5172 (`724d17535`) routed CLI facade writes through declared daemon operations | ## Solution **#5162 leftover.** `ArchiveTierUnavailableError` is a `DatabaseError`, not an `sqlite3` exception, so it propagated straight through `pytest.raises(sqlite3.OperationalError)`. #5162 landed its own replacement (`test_absent_index_tier_is_typed.py`); this was the other half. The test's actual subject — `assert not any(tmp_path.glob("*.db"))`, that a read-only open of nothing creates nothing — is untouched. **#5103 leftover — the one worth reading closely.** The old test renumbered the parent (`A,B` → `X,A,B`) so the child's `p:<position>.<variant>` branch-point alias would land on a different row. Under content-derived identity that alias no longer exists: `message_id` is now `'c:' || content_identity || '.' || content_occurrence`, so "B" resolves to the same real message wherever it sits, the content witness matches, and the composed prefix `X, A, B` was **legitimately correct**. The writer was not wrongly resolving anything — there was no longer a dangling reference to detect. The dangling rule itself is intact and still worth proving, so I rebuilt the premise rather than relaxing the rule: the replacement now **drops "B" outright**, so the child's branch point genuinely vanishes and the envelope must truncate to the child's own tail. Renamed to `test_vanished_branch_point_is_typed_dangling` to say what it actually tests. **#5172 leftover.** Requiring a daemon for `compare --verdict` is not an over-reach — it is the stated single-writer route, and `judge` moved the same way. #5172 migrated `test_judge_command`, `test_mark_note_identity`, `test_verb_cardinality`, `test_cli_action_contracts` and `test_assertion_candidates`, but missed this file. The verdict case moves onto the same `cli_daemon_archive` stack (a real `DaemonOperationRuntime` behind a real UDS listener), so the file's whole stated premise — a real production caller for `blind_items`, `ClaimWithControls`, `compute_calibration` and `upsert_comparative_judgment_assertion` — survives rather than being mocked away. Its sibling `test_compare_without_verdict…` still passes untouched because it records nothing. ## Anti-vacuity - **Read-only open:** restore bootstrap on the read-only path (`initialize = not read_only`) and the no-`*.db` assertion goes red. Keeping the expected type narrow (rather than the `DatabaseError` base) keeps it red if the boundary re-leaks a raw driver error. - **Vanished branch point:** delete the content-witness guard in `write.py` (`if witness is not None: … composed = own; break`) and the child composes the wrong parent prefix instead of truncating. This is the condition the test always named — it just could not reach it any more. - **Compare:** mock the facade instead of supplying a daemon and the file's premise is lost; stub the storage chokepoint and the `--calibration` agreement rate goes wrong. ## Verification ``` devtools test tests/unit/storage/test_write_path_state_machine.py tests/unit/storage/test_schema_policy_contracts.py devtools test: PASSED exit=0 diagnosis=pytest_passed receipt=.cache/verify/runs/20260915T014134Z-focused-test-325111-9b54466f/run.json devtools test tests/unit/cli/test_compare_command.py devtools test: PASSED exit=0 diagnosis=pytest_passed receipt=.cache/verify/runs/20260915T014228Z-focused-test-325880-7bf93813/run.json ``` ## Schema closure ``` out tests/unit/cli/test_compare_command.py out tests/unit/storage/test_write_path_state_machine.py out tests/unit/storage/test_schema_policy_contracts.py ``` **All OUT.** Test-only change; no product file touched. Does not need to land before an archive rebuild. ## Residuals - `CLAUDE.md`'s identity section still documents the retired `p:` positional fallback that #5103 replaced with `c:`. Not corrected here — it is doc text, not a closure input, and belongs with whoever owns that section. - `test_cli_operation_authority.py` covers the daemon-down refusal matrix for `mark` and `judge` but not `compare`. Adding that case is worthwhile follow-up; it is new coverage rather than part of this red→green repair, so I have not claimed it. 🤖 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 Clears five of the six real failures on `master` at `c676444409`. All five are tests pinning behaviour their product route no longer has; no product code changed. ## Receipt and provenance Full-corpus `verify_all`, agentctl job `polylogue-verify_all-3e42cd1b`, receipt `.cache/verify/runs/20260915T020605Z-all-348770-0b1b4d33/run.json`: - `git_head = c676444` - `final_git_head = c676444` - `git_dirty = False`, `final_git_dirty = False` - `verification_scope = complete`, `diagnosis = pytest_failed`, 22,588 selected, 6 failures The checkout did not move across the 6,205 s run and was clean at both ends, so every failure is real. (Two earlier runs reporting 147 and 29 spanned a moving checkout; only 17 of the 29 reproduced at a settled head.) ## Per-failure classification | Test | Classification | | --- | --- | | `test_schema_preflight.py::test_live_batch_marks_structural_database_error_degraded` | stale test double | | `test_schema_preflight.py::test_ingest_files_short_circuits_when_degraded` | stale test double | | `test_schema_preflight.py::test_ingest_files_short_circuits_under_burst_after_degraded` | stale test double | | `test_cli_action_contracts.py::test_import_contract_guard_requires_daemon_acceptance` | stale fixture + wording pin (**not** a product defect) | | `test_note.py::test_terminal_note_idempotency_survives_root_judgment_canary_route` | missing daemon + wording pin | | `test_demo_seed_verify` | **not in scope** — `polylogue-wrvy2`, open operator decision; left red | ### A. `_StubCursor` has no `ops_write_scope` (3) #5169 added `CursorStore.ops_write_scope()` so one `ops.db` connection is shared per ingest batch; `LiveBatchProcessor.ingest_files` opens it unconditionally. The double in `test_schema_preflight.py` predates it and every call raised `AttributeError`. ### B. Daemon-required refusal wording (2) — wording drift, not a product defect Investigated both before retargeting, as instructed. **`import`**: the `'Error: unsupported_import_source: ...'` message is *not* the daemon guard failing for the wrong reason. `import_command.py` calls `_preflight_or_fail(staged)` (local `import_source_admissibility`) **before** `_submit_ingest`, which is where `daemon_accepts_schedule` lives. The test's source was `{}`, which is genuinely not a parseable Polylogue export shape, so it was refused by the earlier, correct guard and never reached the daemon guard at all. The ordering is deliberate and documented in `_preflight_or_fail`: refuse a locally-detectable inadmissible source rather than schedule an operation that can only fail later. Nothing to fix in the product; the fixture was invalid for what the test claims to test. **`judge`**: #5172/#5173 routed durable `user.db` writes through declared daemon operations, so `judge --accept` now refuses with a typed `OperationUnavailableError` when no daemon answers. Per the operator ruling, that is correct. The refusal itself is already pinned by `tests/unit/cli/test_cli_operation_authority.py::test_judge_accept_refuses_without_a_daemon`; the note canary is about capture/judge/replay idempotency and needed the daemon it now requires. ## Solution - `_StubCursor` implements the real `ops_write_scope` contract rather than a no-op: thread-local, depth-counted re-entry, and a flush of buffered stage events on **every** exit path including exceptions, with a thread-identity assertion on exit. It also gained `record_ingest_stage_event`, so the buffer and its flush are real rather than decorative. New `assert_scopes_balanced(at_least=n)` checks depth returned to zero, nothing was left unflushed, and the expected number of scopes completed. - `test_import_contract_guard_requires_daemon_acceptance` now writes an admissible ChatGPT-shaped export (asserting `import_source_admissibility(...).admissible` first, so the fixture cannot silently regress to being refused by the earlier guard), and asserts `result.exit_code == OUTCOME_EXIT_CODES["error"]` plus zero rows in `sessions` — the typed outcome and the absence of a CLI-side write, not the prose. - `test_terminal_note_idempotency_survives_root_judgment_canary_route` runs its lifecycle inside `tests.infra.daemon_operations.cli_daemon_archive`, a real `DaemonOperationRuntime` behind the socket the CLI probes. No assertion was weakened; only the fixture supplies what `judge` now requires. ## Verification Each retargeted test names an anti-vacuity condition, verified by reverting. Observed text: **A** — removed the `with self._cursor.ops_write_scope():` wrapper from `LiveBatchProcessor.ingest_files`; all three go red: ``` E AssertionError: expected at least 5 completed ops write scope(s), saw 0 E AssertionError: expected at least 2 completed ops write scope(s), saw 0 E AssertionError: expected at least 1 completed ops write scope(s), saw 0 ``` **B/import** — replaced the `OperationUnavailableError` refusal in `_submit_ingest` with a fabricated local acceptance; the test goes red on the fabricated success: ``` E AssertionError: Scheduled: .../archive/inbox/session.json E Operation: local-fallback ``` **B/note** — passed `idempotency_key=None` in `polylogue/cli/commands/note.py`; the replay stops resolving to the same candidate: ``` E AssertionError: assert 'assertion-te...-abdd99ef922a' == 'assertion-te...-089dae5a7e32' E - assertion-terminal-note:c5812cf3-3455-4e0d-8405-089dae5a7e32 E + assertion-terminal-note:f14ae865-ef88-4112-9cb9-abdd99ef922a ``` Product code restored to `c676444409` state after each mutation; the staged diff is tests only. Focused run (the three changed files plus the two suites that own the contracts being relied on): ``` devtools test tests/unit/daemon/test_schema_preflight.py \ tests/unit/cli/test_cli_action_contracts.py tests/unit/cli/test_note.py \ tests/unit/cli/test_cli_operation_authority.py \ tests/unit/sources/test_cursor_ops_write_scope.py devtools test: PASSED exit=0 diagnosis=pytest_passed receipt=.cache/verify/runs/20260915T040329Z-focused-test-435941-3ba8618b/run.json ======================== 66 passed, 1 warning in 17.09s ======================== ``` Static gates: ``` devtools verify --quick # exit 0; 17 gates, all ok ``` ## Schema closure Run on every touched file; none is in a fingerprint closure, so no reconvergence is implied: ``` devtools schema closure tests/unit/cli/test_cli_action_contracts.py -> out devtools schema closure tests/unit/cli/test_note.py -> out devtools schema closure tests/unit/daemon/test_schema_preflight.py -> out ``` ## Residuals - `test_demo_seed_verify` is still red by design: `polylogue-wrvy2` is an open operator decision (the demo builds a Claude-Code-shaped `Task` dispatch inside a Codex parent and expects `mapping_state:resolved`, which the Codex wire cannot express). Untouched. - Evidence here is the focused selection above plus the static gates. No affected/full suite was run; a full corpus run at the merged head is the only thing that proves the 6 → 1 reduction end to end. - The note canary now starts a real daemon stack (UDS listener plus coordinator loop), so it is heavier than the other tests in its module. That is the cost of exercising a route the daemon owns. - `pre-commit` secret-scan reports one candidate span in `test_cli_action_contracts.py`; it is the pre-existing `sk-voyage-CONTRACT-LEAKME` synthetic literal in the redaction test, untouched by this change. 🤖 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 - **Reliability** - Improved validation of daemon-mediated imports and note operations, including clearer handling when the daemon is unavailable. - Confirmed that failed or unreachable daemon operations do not create incomplete archive entries. - Strengthened safeguards around batched processing and database error handling to help maintain consistent operation state. - **Tests** - Expanded coverage for operation lifecycle, schema preflight checks, and repeated note-processing scenarios. <!-- end of auto-generated comment: release notes by coderabbit.ai --> Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
Summary
Step S10 of the CLI-unification design:
mark,compareandjudgestopwriting in the CLI process and lower to declared daemon operations, and the
mutation-authority layering rule is extended to
polylogue/api(decision D1) sothe route they used is visible to the gate that certifies sole-writer adoption.
Problem — the baseline certifies a property it cannot observe
polylogue-5vps8.2is closed anddocs/plans/layering-cli-mutation-authority-baseline.jsonreads
[]. That file is the machine-checked proof behind CLAUDE.md's sole-writerclaim, and it was green while the CLI still opened a writable store:
markcalledPolylogue.add_tag/remove_tag/add_mark/remove_mark/save_annotation, andcomparecalledrecord_comparative_judgment. Everyone lands in
PolylogueArchiveMixin._execute_facade_mutation(
polylogue/api/archive.py), which doesArchiveStore.open_existing(..., read_only=False)in the calling process.judgewroteuser.dbassertion rows through_archive_judge_assertion_candidates,a raw connection with no actuator, preview, authorization or audit record at all.
The rule (
docs/plans/layering.yaml) forbids a CLI import ofoperations/{mutation_transaction,mutation_actuators,delete_authorization,session_mutations}.The CLI imports none of them — the write goes
cli -> polylogue.api -> operations.mutation_transaction,and the CLI rule states API imports are unrestricted. So the rule's letter was
satisfied and its purpose defeated: an empty baseline was evidence about a form,
not about a behaviour (polylogue-gjwto).
Solution
D1 — the rule now covers two surfaces. A second rule targets
polylogue/apiwith the same
disallow.fromlist and the same baseline file.polylogue/api/archive.py'stwo executor imports become recorded, ratcheted debt.
Three operations declared and served, plus a second direction on an existing one:
mutation.session.markmark --star/--pin/--archiveand theirun-formsmutation.annotation.savemark --notemutation.judgment.recordcompare(comparative) andjudge(assertion review)mutation.session.tag(extended)mark --tag-remove, via aremove_tagsdirectionmutation.session.markandmutation.annotation.saveare deliberatelysession-scoped: a message- or block-targeted mark needs the async insight-target
resolver on the facade, which no daemon handler may import. The durable-owner
alias resolution both halves need moved to
polylogue/operations/user_state_resolution.py(relocation, not duplication —
api/archive.pyimports it).One CLI seam.
archive_query.submit_cli_mutation(env, operation, payload)isthe single entry point for a non-query CLI mutation, so "the CLI never holds
write authority" is one fact about one function.
Daemon-required is actionable. Per the operator's 2026-09-14 ruling that the
daemon is the standard and not an optional addon, the refusal now names the
operation and
polylogued run, rather than being a bare "daemon is unavailable".Two authority defects found by proving the route end to end, not by reading it:
_declare_executor_authorityinoperations/specs.pyoverwrote everyback-filled spec's
allowed_surfaceswith("api",), discarding an authoredboundary. Every CLI-lowered mark or annotation write died with
SurfaceDeniedError: 'mutate-save-annotation' is not allowed on 'cli'. It nowhonours an authored value. Verified by loading
origin/master's and thisbranch's
RUNTIME_OPERATION_SPECSside by side and diffing effectiveallowed_surfaces: exactly three specs change (mutate-add-mark,mutate-remove-mark,mutate-save-annotation) and nothing else is widened —specs that author their own
target_authority(mutate-bulk-tag-sessions,mutate-bulk-set-metadata) skip the back-fill entirely.{spec.capability}, one capabilityper operation, so
mutation.session.markcould add a mark but never removeone.
DaemonOperationSpecgainsadditional_capabilities;mutation.session.markdeclaresarchive.remove_mark, andDAEMON_PRINCIPAL_CAPABILITIESis derived from the declarations rather than aside table.
Verification
New evidence, not just migrated mocks:
tests/unit/cli/test_cli_operation_authority.py— daemon-down matrix overmark --star/--tag-add/--tag-remove/--noteandjudge --accept: nonzero exit,the declared operation name and
polylogued runin the refusal, and abyte-identical
user.db*digest.tests/unit/operations/test_user_state_mutation_operations.py— the newhandlers driven over a real
DaemonOperationRuntimeand its real socket, withthe durable rows read back.
tests/unit/cli/test_mark_note_identity.pynow runs insidecli_daemon_archiverather than mocking, so annotation identity and no-op semantics are proven
through the production handler.
got which ids" assertion became an assertion on the recorded
(operation, payload)sequence.Layering mutation-authority baseline:
[]before, 2 entries after — bothpolylogue/api/archive.py. That is the honest state, not a regression: the rulenow observes a writer it previously could not, and the entries can only shrink.
Schema closure (
devtools schema closure, every touched file): all out.One hazard caught: the comparative-judgment wire form was first drafted in
polylogue/analysis/judgment/types.py, which is IN the closure, so it wouldhave moved the derived schema identity and forced a reconvergence for a CLI
change. It lives in
polylogue/operations/judgment_wire.pyinstead;types.pyis byte-identical to master.Residuals
polylogue-r29bv:polylogue note(
capture_assertion_candidate),polylogue setting set(_archive_set_setting,a raw
user.dbwrite with no actuator cycle), andpolylogue annotations import.None is covered by the three operations this step declares; each needs its own.
They are why the baseline is 2 and not 0.
session-scoped by contract; widening them needs
_resolve_user_state_targetmoved into the operations layer first.
tests/unit/daemon/test_daemon_operation_route.py::test_uds_refuses_when_kernel_peer_credentials_cannot_be_readfails on this branch and in isolation. Inherited, not caused here: it fails
inside
polylogue/daemon_client.py::_reject_foreign_peerbefore any server coderuns, and
daemon_client.pyand that test file are unmodified(
git diff origin/masteris empty for both).tests/unit/operations/test_mutation_actuators.py::TestIdentityResetActuator::test_a_session_absent_from_the_index_is_still_tombstonedis likewise pre-existing and untouched by this branch.
D2 — does MCP
writemove too?Position: (b) for now — MCP stays on the facade, and it is recorded rather than
exempted. MCP
write(operation=add_tag|add_mark|remove_mark|save_annotation)still constructs
Polyloguein-process (mcp/server_cutover.py, viamcp/server_support.py). Three reasons this is a deliberate stop and not anoversight:
baseline entries above, and MCP is now the main reason they exist. The ratchet
cannot reach zero until MCP moves, so the decision has a forcing function
instead of resting on anyone remembering it.
block targets, which the session-scoped operations here do not serve; doing it
properly requires moving the async insight-target resolver into the operations
layer first.
running. That is the MCP owner's call, and the design explicitly declines to
decide it.
I recommend (a) as the destination: it is the
bp12ndirection and the onlyoutcome with one writer. This PR is written so (a) remains a clean follow-on.
🤖 Generated with Claude Code
https://claude.ai/code/session_01DYUNBGoE652b3nfmq3CtqK