Repository navigation
feat(operations): add MutationTransaction executor for delete/excise/reset - #3249
Conversation
…reset Problem: OperationSpec (specs.py) and CliActionContract declared operation safety metadata, but CLI, MCP, and API surfaces enforced role/confirm/preview independently per adapter. Session delete, session excision, and identity reset each reimplemented their own preview/confirm/receipt handling with no shared authorization protocol, and mutate-delete-session's OperationSpec declared previewable=False while its description claimed preview behavior (t46.9 2026-07-18 note) -- declared and actual behavior disagreed. Solution: add polylogue/operations/mutation_transaction.py, a PREPARE -> AUTHORIZE -> EXECUTE protocol (OperationExecutor + MutationActuator) that binds a plan hash across the lifecycle and refuses (PlanStaleError) when live state moves between AUTHORIZE and EXECUTE. Add mutation_actuators.py with SessionDeleteActuator, SessionExcisionActuator, and IdentityResetActuator, each wrapping the existing production mutation primitive (ArchiveStore.delete_sessions, security.excision plan/apply, the reset tombstone helpers) without changing it. Route every surface that exposes the two named routes (session delete/excision, derived identity reset) through the executor: CLI delete verb (archive_query._emit_delete), CLI excise command, CLI reset --session/--source, and the API's delete_session_safe (consumed by MCP write(operation='delete_session')). Add an executor_status field to OperationSpec (t46.9 AC1 inventory) and a checked docs/plans/mutation-census.yaml (kwsb.2 AC1 census) classifying every destructive CLI/MCP operation as executor-routed, declared-not-routed (visible Phase 2 debt), or typed-exemption. Deferred (named, not silent): the reversible tag/metadata family and the remaining MCP mutation tools (annotations, saved views, recall packs, workspaces, corrections, maintenance_execute/rebuild_*) stay declared-not-routed -- jn40's confirm-boolean sweep remains their interim mitigation. Bulk filesystem-tier reset (--database/--index/--blob/...) stays declared-not-routed pending a decision on whether MutationPlan's target-ref vocabulary should extend to file-tier targets. HTTP surface unchanged (reset/excise are CLI-only; delete_session is not HTTP-exposed). Verification: - devtools test tests/unit/cli/test_reset.py tests/unit/cli/test_excise.py tests/unit/security/test_excision.py tests/unit/cli/test_archive_query.py tests/unit/mcp/test_privileged_tools.py tests/unit/api/test_facade_contracts.py tests/unit/operations tests/unit/verification/test_code_refs_resolve.py -> 780 passed - mypy --strict on all changed/added files -> Success: no issues found - devtools render all --check -> clean (topology projection, quality reference regenerated for the new modules/tests) Ref polylogue-t46.9 Ref polylogue-kwsb.2 Co-Authored-By: Claude <[email protected]>
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
|
Warning Review limit reached
Next review available in: 27 minutes Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews. How do review limits work?CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability. For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window. Please refer docs for additional details. Review details⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (15)
✨ Finishing Touches🧪 Generate unit tests (beta)
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 |
|
Coordinator review (CodeRabbit rate-limited): read ~1,200 lines of the 2,299-line diff incl. the full census yaml, all three actuators, and the executor wiring at every adapter (CLI delete/excise/reset, API delete_session_safe → MCP write). The reconciled architecture is the right one: OperationSpec stays declarative, MutationTransaction is the runtime PREPARE→AUTHORIZE→EXECUTE lifecycle, actuators wrap the EXISTING production primitives (no forked mutation logic), plan-hash staleness refuses rather than partially applying. The census's honest declared-not-routed inventory (incl. the MCP no-spec family and the file-tier reset question) is exactly the visible-debt shape phase 1 needed. 780 tests green, mypy strict clean. Merging; t46.9/kwsb.2 stay open with phase-1 receipts — phase-2 route migration is the named remainder. |
…ionTransaction (polylogue-t46.9 phase 2) (#3253) ## Summary Phase 2 of the t46.9/kwsb.2 mutation-executor migration: routes the `reversible`-class tag, metadata, and mark mutation families through `OperationExecutor`/`MutationActuator` (the PREPARE → AUTHORIZE → EXECUTE lifecycle shipped in phase 1, PR #3249), replacing per-surface direct calls to the underlying `ArchiveStore` primitives. ## Problem `docs/plans/mutation-census.yaml` (phase 1) inventoried `mutate-add-tag`, `mutate-remove-tag`, `mutate-bulk-tag-sessions`, `mutate-set-metadata`, and `mutate-delete-metadata` as `declared-not-routed`: CLI (query-mutation path), MCP (`write(operation=...)`), and the Python API facade each reached `ArchiveStore.add_user_tags`/`remove_user_tags`/`set_user_metadata`/ `delete_user_metadata` independently, with no shared preview/authorize/ receipt contract and no `OperationSpec`-level executor status beyond "declared". Separately, `add_mark`/`remove_mark` was a genuine MCP-only mutation family with **no `OperationSpec` at all** — invisible to the t46.9 AC1 inventory. ## Solution **New actuators** (`polylogue/operations/mutation_actuators.py`): `TagAddActuator`, `TagRemoveActuator`, `BulkTagActuator`, `MetadataSetActuator`, `MetadataDeleteActuator`, `MarkAddActuator`, `MarkRemoveActuator`. Each wraps exactly one existing `ArchiveStore` primitive unchanged (`add_user_tags`/`remove_user_tags`/`set_user_metadata`/ `delete_user_metadata`/`add_mark`/`remove_mark`) and declares `destructive_class="reversible"` + `required_confirmation="role_only"` — the AC4 floor: reversible writes (undo = another write through the same actuator) must not force an interactive confirm ceremony, unlike phase 1's `confirm_flag`-gated delete/excise/reset actuators. **Routing** (`polylogue/api/archive.py`): `PolylogueArchiveMixin.add_tag`, `remove_tag`, `bulk_tag_sessions`, `set_metadata`, `delete_metadata`, `add_mark`, `remove_mark` now construct the actuator + `OperationExecutor` and drive PREPARE → AUTHORIZE → EXECUTE instead of calling the archive primitive directly. This is the single choke point every surface already funneled through (CLI's `apply_modifiers`/query-mutation path and `query_verbs.py`, MCP's `write(operation=...)` dispatch, and direct API callers), so routing it there covers all three surfaces in one place — mirroring how phase 1 routed `delete_session_safe`. **Specs** (`polylogue/operations/specs.py`): flipped the five existing tag/metadata specs' `executor_status` to `executor-routed`, and added two new specs, `mutate-add-mark`/`mutate-remove-mark` (previously absent from the catalog entirely) — the first MCP no-spec mutation family to gain both an `OperationSpec` and an executor route. **Census** (`docs/plans/mutation-census.yaml`): moved the seven rows above from `declared-not-routed` to `executor-routed` with actuator/adapter citations, and removed a stale duplicate `delete_metadata (MCP admin alias)` row that named the exact same code path as `mutate-delete-metadata` (there is only one `delete_metadata` code path in `mcp/server_cutover.py`). **Race-window fix** (`polylogue/api/archive.py`): widened the `KeyError → SessionNotFoundError` conversion in `add_tag`/`remove_tag`/ `set_metadata`/`delete_metadata` to wrap AUTHORIZE+EXECUTE as well as PREPARE. `OperationExecutor.execute` re-resolves the plan via a fresh `actuator.prepare()` call before mutating; if a session is deleted by a concurrent actor between AUTHORIZE and EXECUTE, that fresh PREPARE now raises `KeyError` inside the same `try` block instead of leaking an untyped exception past the facade boundary. ### Routing matrix | Family | Spec | Actuator | Surfaces | Census state | | --- | --- | --- | --- | --- | | add tag | `mutate-add-tag` | `TagAddActuator` | facade, mcp, api | executor-routed | | remove tag | `mutate-remove-tag` | `TagRemoveActuator` | facade, mcp, api | executor-routed | | bulk tag | `mutate-bulk-tag-sessions` | `BulkTagActuator` | mcp, api | executor-routed | | set metadata | `mutate-set-metadata` | `MetadataSetActuator` | facade, mcp, api | executor-routed | | delete metadata | `mutate-delete-metadata` | `MetadataDeleteActuator` | mcp, api | executor-routed | | add mark | `mutate-add-mark` (new) | `MarkAddActuator` | mcp, api | executor-routed | | remove mark | `mutate-remove-mark` (new) | `MarkRemoveActuator` | mcp, api | executor-routed | ### AC coverage (t46.9) - **AC1** (one inventory covers every mutation): extended — `add_mark`/ `remove_mark` now have `OperationSpec` entries where previously they had none; the census/spec cross-check test (`test_mutation_census.py`) stays green and honest. - **AC5** (internal actors use declared capabilities through the executor): not touched this phase — no daemon/maintenance internal actor was in scope here. - **AC8** (jn40 confirm booleans retained only as interim compat): not affected — none of the seven migrated operations were in jn40's confirm-gated list (only `delete_session`/`delete_annotation`/ `delete_saved_view`/`delete_recall_pack`/`delete_workspace`/ `maintenance_execute` family are), so there was no confirm boolean to remove or reduce here. ## Verification ``` devtools test tests/unit/operations/test_mutation_actuators.py \ tests/unit/operations/test_mutation_census.py \ tests/unit/operations/test_mutations.py \ tests/unit/api/test_facade_contracts.py # 307 passed devtools test tests/unit/mcp/test_mcp_edge_cases.py tests/unit/mcp/test_contract_evidence.py \ tests/unit/mcp/test_privileged_tools.py tests/unit/mcp/test_tool_discovery.py # 60 passed devtools verify --quick # exit_code: 0 (ruff format/check, mypy --strict, render all --check all clean) ``` Anti-vacuity (`tests/unit/operations/test_mutation_actuators.py`): each new actuator is driven against a real seeded `index.db`/`user.db` pair (real schema, real SQL) and asserts on the actual `assertions` table rows — e.g. `TestTagAddActuator::test_full_lifecycle_writes_the_tag_assertion` fails if `TagAddActuator.apply` stops calling `ArchiveStore.add_user_tags`. `TestReversibleActuatorsAcceptTheWeakestConfirmation` directly contrasts a `role_only` AUTHORIZE succeeding for the new reversible actuators against `SessionDeleteActuator` (phase 1) refusing the identical `role_only` strength with `ConfirmationRequiredError` — the AC4 evidence. `devtools test tests/unit/cli/test_verb_cardinality.py -k test_guard_dry_run_and_deleted_sets_are_identical_and_unlimited` fails identically on unmodified `master` (`git stash` before/after) — pre-existing "no running event loop" / `RuntimeServices` `ConfigError`, unrelated to this change; not touched here. Not run: full `devtools verify --all` (reserved for a final pre-merge pass per repo convention; the touched surface's affected-area tests above plus `--quick` gate cover this change). ## Remaining polylogue-t46.9 / polylogue-kwsb.2 scope Named as Phase 3 debt in the census, not attempted in this PR: - `save_annotation`/`delete_annotation`, `save_saved_view`/ `delete_saved_view`, `save_recall_pack`/`delete_recall_pack`, `save_workspace`/`delete_workspace` — `delete_*` members are jn40 confirm-gated at the MCP layer; not yet executor-routed. - `record_correction`/`clear_corrections`, `capture_assertion_candidate`, `blackboard_post`, `import_annotation_batch` — additive/low-blast-radius writes, still `declared-not-routed`. - `rebuild_index`/`update_index`/`rebuild_insights` (`maintenance_execute` family) — internal idempotent-rebuild maintenance, jn40 confirm-gated. - `ops reset --database/--index/--blob/--assets/--cache/--auth` (file-tier deletion) — census still asks whether to extend `MutationPlan`'s target-ref vocabulary to file-tier targets or keep this a typed exemption permanently; no decision made in this PR. - `bound_token` confirmation-strength adoption and durable audit-row persistence — untouched, as scoped by the task brief. Ref polylogue-t46.9 Ref polylogue-kwsb.2 Co-authored-by: Claude <[email protected]>
#3294) ## Summary Migrates the `record_correction` / `delete_correction` / `clear_corrections` learning-corrections family from `declared-not-routed` to `executor-routed` in the t46.9/kwsb.2 mutation-authority migration — phase 5 in the sequence started by #3249/#3253/#3258/#3262. ## Problem `docs/plans/mutation-census.yaml`'s `record_correction / clear_corrections` row was the next `declared-not-routed` family after phase 4 (#3262, saved-view/recall-pack/workspace) landed. These three operations independently mutated `user.db` without going through `OperationExecutor`'s PREPARE -> AUTHORIZE -> EXECUTE protocol, so they had no shared plan-hash staleness check or confirmation-strength floor — the same class of gap kwsb.2's design doc calls a security boundary (one adapter bypassing the proof required by another). ## Solution - `polylogue/operations/mutation_actuators.py`: new `CorrectionRecordActuator`, `CorrectionDeleteActuator`, `CorrectionsClearActuator` — all `reversible` class / `role_only` confirmation (AC4: reversible writes don't need interactive confirmation), following the exact same actuator shape as the annotation and workspace families. `CorrectionsClearActuator.prepare` resolves the *exact live set* of correction kinds for the session at plan time (mirroring `SessionDeleteActuator`'s re-resolve-against-live-state pattern), so a concurrent `record_correction` between AUTHORIZE and EXECUTE changes the plan hash and forces `PlanStaleError` instead of silently clearing a kind the caller never previewed. - `polylogue/operations/specs.py`: `mutate-record-correction`, `mutate-delete-correction`, `mutate-clear-corrections` `OperationSpec` entries, `executor_status="executor-routed"`. - `polylogue/api/archive.py`: `record_correction`/`delete_correction`/`clear_corrections` now build actuator args and drive `OperationExecutor.prepare/authorize/execute` instead of calling `ArchiveStore` directly. Behavior/return types are unchanged (same `LearningCorrection`/`bool`/`int` signatures). - `docs/plans/mutation-census.yaml`: replaced the single `declared-not-routed` row with three `executor-routed` rows citing their specs/actuators/adapters. - `docs/test-quality-workflows.md`: regenerated (the uncovered-runtime-operations list picked up the three new spec names, matching the existing pattern for e.g. `mutate-save-annotation`). Only this one family was migrated — per repo convention, the remaining `declared-not-routed` rows (`capture_assertion_candidate`, `blackboard_post`, `import_annotation_batch`, the `maintenance_execute` family, and the file-tier `ops reset` family) are untouched debt for later phases. ## Verification - `python -m pytest tests/unit/operations/{test_mutation_actuators,test_mutation_census,test_specs}.py -q` -> 56 passed - `devtools test tests/unit/operations/` -> 146 passed - `devtools test tests/unit/mcp/test_query_gap_projections.py tests/unit/api/test_facade_contracts.py` -> 295 passed (these two files exercise `record_correction`/`clear_corrections` through the MCP/API layers) - `python -m mypy polylogue/operations/mutation_actuators.py polylogue/operations/specs.py polylogue/api/archive.py tests/unit/operations/test_mutation_actuators.py` -> `Success: no issues found in 4 source files` - `ruff check` / `ruff format --check` on all changed `.py` files -> clean - `devtools render all --check` -> no `out of sync` surfaces (after regenerating `docs/test-quality-workflows.md`) - `devtools verify --quick` -> exit 0 (ran automatically on push via the pre-push hook too) New test: `tests/unit/operations/test_mutation_actuators.py::TestCorrectionActuators` — 5 cases including the anti-vacuity case `test_concurrent_record_between_authorize_and_execute_makes_clear_plan_stale`, which authorizes a clear-plan, records a new correction kind through a second actuator in between AUTHORIZE and EXECUTE, and asserts the held authorization is refused with `PlanStaleError` before any row is deleted — proving authorization is actually enforced, not just "it still works." Ref polylogue-kwsb.2 Ref polylogue-t46.9 Co-Authored-By: Claude <[email protected]>
Summary
Adds
OperationExecutor+MutationActuator(polylogue/operations/mutation_transaction.py): a PREPARE -> AUTHORIZE -> EXECUTE protocol that binds a content-addressed plan hash across the lifecycle and refuses execution (PlanStaleError) when live state moves between AUTHORIZE and EXECUTE. Routes the two named destructive routes (session delete/excision, derived identity reset) through it on every surface that exposes them (CLI, MCP, API).Problem
polylogue/operations/specs.py'sOperationSpecandoperations/action_contracts.py'sCliActionContractdeclared operation safety metadata (capability, destructive class, safety guards), but CLI, MCP, and API surfaces each enforced role/confirm/preview independently:archive_query._emit_delete(CLIdelete),security.excision+excise.py(CLIexcise), andreset.py's tombstone helpers (CLIreset --session/--source) had no shared authorization protocol. Themutate-delete-sessionOperationSpecdeclaredpreviewable=Falsewhile its description said "confirm flag on all surfaces" — declared and actual behavior disagreed (flagged in the t46.9 2026-07-18 GPT-Pro note).Solution
Architecture (the reconciliation)
OperationSpec/CliActionContractremain declarations (what an operation is).MutationTransactionis the runtime lifecycle —OperationExecutor's protocol for destructive-class operations specifically. There is one executable authority:MutationActuator:prepare()resolves exact targets from live state with zero mutation and returns a hashableMutationPlan;apply()performs the real mutation and returns aMutationReceipt.OperationExecutoris the only thing that runs PREPARE, checks a caller-declaredConfirmationStrengthagainst the actuator's declared floor, binds aMutationAuthorizationto the plan hash, and — immediately beforeapply— re-runs PREPARE and refuses if the hash no longer matches. No adapter callsactuator.applydirectly.ArchiveWriteGateway(a7xr.18) remains a distinct, narrower ingest-effects gateway; storage-layer excision guards remain defense in depth.MutationTransactionis strictly the authorization/preview/receipt layer above those.Named routes (t46.9 AC2)
Three actuators, each wrapping an existing production mutation primitive without changing it:
SessionDeleteActuator->ArchiveStore.delete_sessions(CLIdeleteviaarchive_query._emit_delete; APIPolylogueArchiveMixin.delete_session_safe, consumed by MCPwrite(operation='delete_session')).SessionExcisionActuator->security.excision.plan_session_excision/apply_session_excision(CLIexcise, standalone mode).IdentityResetActuator-> the reset tombstone helpers (CLIops reset --session/--source).Inventory + census
OperationSpecgainsexecutor_status: Literal["executor-routed","declared-not-routed","typed-exemption"] | None, required (validated at import time) whenevermutates_state=True. Two new specs added:mutate-session-excision,mutate-identity-reset.docs/plans/mutation-census.yaml(kwsb.2 AC1): classifies every destructive CLI/MCP operation found by inventory (tag/metadata mutations, MCP annotation/saved-view/recall-pack/workspace/correction/maintenance tools, bulk filesystem reset) asexecutor-routed,declared-not-routed(visible Phase-2 debt), ortyped-exemption. Enforced bytests/unit/operations/test_mutation_census.py(status vocabulary, exemption reasons required, census/OperationSpec.executor_statusagreement).Deferred (named, not silent)
mutate-add-tag/remove-tag/set-metadata/delete-metadata/bulk-tag-sessions) — Phase 2,role_only-strength candidate.maintenance_execute/rebuild_index/rebuild_session_insights) — jn40's confirm-boolean sweep remains their interim mitigation; not executor-routed.ops reset --database/--index/--blob/--assets/--cache/--auth— file-tier deletion, not addressable session/message/block object refs; deferred pending a decision on whetherMutationPlan.target_refsshould extend to file-tier targets.bound_tokenconfirmation strength) across separate process invocations — every current adapter recomputes the plan fresh within one call, soconfirm_flagis sufficient for now; thePlanStaleErrormechanism is real and tested but only exercised via concurrent-mutation-within-one-call simulation, not a genuine two-request preview/confirm round trip.Verification
devtools test tests/unit/cli/test_reset.py tests/unit/cli/test_excise.py tests/unit/security/test_excision.py tests/unit/cli/test_archive_query.py tests/unit/mcp/test_privileged_tools.py tests/unit/api/test_facade_contracts.py tests/unit/operations tests/unit/verification/test_code_refs_resolve.py-> 780 passedmypy(strict, viadevtools verify --quick) -> cleandevtools verify --quick-> all 16 steps green (format, lint, mypy, render-all, topology, layering, closure-matrix, manifests, doc-commands, docs-coverage, test-infra-currency, test-clock-hygiene, degrade-loudly)test_execute_refuses_when_live_state_moved_between_authorize_and_execute(the generalized "excision bypass" class — a bound authorization cannot be replayed against a target set that changed since PREPARE) and its actuator-level siblingtest_stale_plan_after_concurrent_delete_refuses(realArchiveStore, real SQLite schema).AC matrix — polylogue-t46.9
executor_statusis required on everymutates_state=Truespec (enforced at import time); the census additionally covers MCP-only operations with noOperationSpecentry yet (pre-existing gap). Not every mutation has anOperationSpecrow (deferred — MCP annotation/saved-view/etc. family).ConfirmationRequiredError(weak confirmation) andPlanStaleError(drift) are both real and tested.bound_tokenstrength itself (vsconfirm_flag) is not yet used by any adapter — deferred.AC matrix — polylogue-kwsb.2
docs/plans/mutation-census.yaml, enforced by test.AuthorizationMismatchError/PlanStaleError. Per-targetapplied/already_satisfied/blocked/failed/unknownstatus vocabulary exists (MutationTargetStatus) but onlyapplied/already_satisfied/blocked/unknownare currently emitted by the three actuators (no partial-multi-target-failure path yet — single-session/small-multi-session operations only).MutationAuthorization/MutationReceiptcarry actor/role/capability/plan_hash/status/target_refs; no separate durable audit-row persistence added in this PR (receipts are in-process return values, not yet written to a dedicated audit table — excision's ownExcisionReceipt/assertion-row audit trail is unchanged and still fires).ConfirmationRequiredError,AuthorizationMismatchError,PlanStaleError).Residual risk
bound_tokenconfirmation strength and true cross-request preview-token flow are unimplemented — a determined caller within one process can still authorize+execute in the same breath (as today), just now through a shared, tested chokepoint instead of three independent implementations.MutationAuthorization/MutationReceiptoutside excision's own existing receipt; Phase 2 should decide whether these belong inuser.dbassertionsor a dedicated table.OperationSpecentries at all (pre-existing gap, not introduced here) — the census covers them by name but the inventory AC is not fully closed until they do.Co-Authored-By: Claude [email protected]