Skip to content

feat(operations): add MutationTransaction executor for delete/excise/reset - #3249

Merged
Sinity merged 1 commit into
masterfrom
feature/operations/mutation-authority-executor
Jul 21, 2026
Merged

Sinity merged 1 commit into
masterfrom
feature/operations/mutation-authority-executor

Conversation

@Sinity

@Sinity Sinity commented Jul 21, 2026

Copy link
Copy Markdown
Owner

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's OperationSpec and operations/action_contracts.py's CliActionContract declared operation safety metadata (capability, destructive class, safety guards), but CLI, MCP, and API surfaces each enforced role/confirm/preview independently: archive_query._emit_delete (CLI delete), security.excision + excise.py (CLI excise), and reset.py's tombstone helpers (CLI reset --session/--source) had no shared authorization protocol. The mutate-delete-session OperationSpec declared previewable=False while 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/CliActionContract remain declarations (what an operation is). MutationTransaction is the runtime lifecycle — OperationExecutor's protocol for destructive-class operations specifically. There is one executable authority:

  • A domain module owns a MutationActuator: prepare() resolves exact targets from live state with zero mutation and returns a hashable MutationPlan; apply() performs the real mutation and returns a MutationReceipt.
  • OperationExecutor is the only thing that runs PREPARE, checks a caller-declared ConfirmationStrength against the actuator's declared floor, binds a MutationAuthorization to the plan hash, and — immediately before apply — re-runs PREPARE and refuses if the hash no longer matches. No adapter calls actuator.apply directly.

ArchiveWriteGateway (a7xr.18) remains a distinct, narrower ingest-effects gateway; storage-layer excision guards remain defense in depth. MutationTransaction is 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 (CLI delete via archive_query._emit_delete; API PolylogueArchiveMixin.delete_session_safe, consumed by MCP write(operation='delete_session')).
  • SessionExcisionActuator -> security.excision.plan_session_excision/apply_session_excision (CLI excise, standalone mode).
  • IdentityResetActuator -> the reset tombstone helpers (CLI ops reset --session/--source).

Inventory + census

  • OperationSpec gains executor_status: Literal["executor-routed","declared-not-routed","typed-exemption"] | None, required (validated at import time) whenever mutates_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) as executor-routed, declared-not-routed (visible Phase-2 debt), or typed-exemption. Enforced by tests/unit/operations/test_mutation_census.py (status vocabulary, exemption reasons required, census/OperationSpec.executor_status agreement).

Deferred (named, not silent)

  • Reversible tag/metadata mutations (mutate-add-tag/remove-tag/set-metadata/delete-metadata/bulk-tag-sessions) — Phase 2, role_only-strength candidate.
  • Remaining MCP mutation tools (annotations, saved views, recall packs, workspaces, corrections, maintenance_execute/rebuild_index/rebuild_session_insights) — jn40's confirm-boolean sweep remains their interim mitigation; not executor-routed.
  • Bulk filesystem-tier ops reset --database/--index/--blob/--assets/--cache/--auth — file-tier deletion, not addressable session/message/block object refs; deferred pending a decision on whether MutationPlan.target_refs should extend to file-tier targets.
  • HTTP surface unchanged (reset/excise are CLI-only; delete_session is not HTTP-exposed).
  • Client-held preview-token flow (bound_token confirmation strength) across separate process invocations — every current adapter recomputes the plan fresh within one call, so confirm_flag is sufficient for now; the PlanStaleError mechanism 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 passed
  • mypy (strict, via devtools verify --quick) -> clean
  • devtools 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)
  • New regression tests: 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 sibling test_stale_plan_after_concurrent_delete_refuses (real ArchiveStore, real SQLite schema).

AC matrix — polylogue-t46.9

  1. One OperationSpec-to-handler inventory covers every mutation — partially satisfied: executor_status is required on every mutates_state=True spec (enforced at import time); the census additionally covers MCP-only operations with no OperationSpec entry yet (pre-existing gap). Not every mutation has an OperationSpec row (deferred — MCP annotation/saved-view/etc. family).
  2. Session delete/excision and derived reset run through OperationExecutor from every surface — satisfied for the two named routes on CLI/MCP/API.
  3. Destructive execution without a bound token fails; plan/target drift returns explicit rejection — satisfied: ConfirmationRequiredError (weak confirmation) and PlanStaleError (drift) are both real and tested. bound_token strength itself (vs confirm_flag) is not yet used by any adapter — deferred.
  4. Reversible writes don't acquire unnecessary confirmation — not yet migrated (declared-not-routed, Phase 2).
  5. Internal maintenance/system actors use declared capabilities through the same executor — not yet migrated (declared-not-routed).
  6. Storage excision guards and ArchiveWriteGateway effects remain enforced behind the executor — satisfied: unchanged, actuators wrap the existing primitives rather than replacing them.
  7. A production-route bypass mutation for each adapter family fails — satisfied for the two named routes (regression tests above); not yet extended to Phase-2 families.
  8. jn40 confirm booleans retained as interim compatibility — satisfied, unchanged; not reduced to preview-token adapters (that's the Phase 2 migration).

AC matrix — polylogue-kwsb.2

  1. Census classifies every destructive operation/adapter — satisfied: docs/plans/mutation-census.yaml, enforced by test.
  2. Preview/prepare performs zero mutation and returns exact target refs/tiers/hash — satisfied for the three actuators (target refs, affected tiers, plan hash; reversibility flag). Expiry is not yet modeled (deferred).
  3. Apply requires a matching fresh authorization, revalidates the plan, is idempotent, TOCTOU returns replan-required — satisfied: AuthorizationMismatchError/PlanStaleError. Per-target applied/already_satisfied/blocked/failed/unknown status vocabulary exists (MutationTargetStatus) but only applied/already_satisfied/blocked/unknown are currently emitted by the three actuators (no partial-multi-target-failure path yet — single-session/small-multi-session operations only).
  4. CLI/MCP/HTTP/Python parity fixtures for reset/excision — partially satisfied: CLI+API(MCP)+Python parity for delete; CLI-only for reset/excision (no MCP/HTTP tool exists for those yet, out of scope to add here). No role-denial matrix yet.
  5. Crash/timeout and partial multi-target failure resume without duplicate effects — not addressed this PR (named deferral; single-target/small-set operations only, no crash-resume state machine).
  6. Audit records contain actor/authority/policy/targets/hashes/outcome without secrets — partially satisfied: MutationAuthorization/MutationReceipt carry 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 own ExcisionReceipt/assertion-row audit trail is unchanged and still fires).
  7. Mutation tests fail when preview writes / authorization omitted or drifted / plan drift ignored / adapter bypasses actuator — satisfied by the new test suite (zero-mutation-in-prepare tests, ConfirmationRequiredError, AuthorizationMismatchError, PlanStaleError).

Residual risk

  • The bound_token confirmation 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.
  • No durable audit-row table yet for MutationAuthorization/MutationReceipt outside excision's own existing receipt; Phase 2 should decide whether these belong in user.db assertions or a dedicated table.
  • The MCP-only mutation family (annotations, saved views, recall packs, workspaces, corrections) has no OperationSpec entries 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]

…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]>
@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, you can upgrade your account or add credits to your account and enable them for code reviews in your settings.

@coderabbitai

coderabbitai Bot commented Jul 21, 2026

Copy link
Copy Markdown

Warning

Review limit reached

@Sinity, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 27 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

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 configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 2b7cb695-22f1-47fb-aec2-4d844ebb06fd

📥 Commits

Reviewing files that changed from the base of the PR and between 24a5248 and 1d77709.

📒 Files selected for processing (15)
  • docs/plans/mutation-census.yaml
  • docs/plans/topology-target.yaml
  • docs/test-quality-workflows.md
  • docs/topology-status.md
  • polylogue/api/archive.py
  • polylogue/cli/archive_query.py
  • polylogue/cli/commands/excise.py
  • polylogue/cli/commands/reset.py
  • polylogue/operations/mutation_actuators.py
  • polylogue/operations/mutation_transaction.py
  • polylogue/operations/specs.py
  • tests/unit/operations/test_mutation_actuators.py
  • tests/unit/operations/test_mutation_census.py
  • tests/unit/operations/test_mutation_transaction.py
  • tests/unit/operations/test_specs.py
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/operations/mutation-authority-executor

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 commented Jul 21, 2026

Copy link
Copy Markdown
Owner Author

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.

@Sinity
Sinity merged commit b17bd49 into master Jul 21, 2026
2 of 3 checks passed
@Sinity
Sinity deleted the feature/operations/mutation-authority-executor branch July 21, 2026 16:58
Sinity added a commit that referenced this pull request Jul 21, 2026
…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]>
Sinity added a commit that referenced this pull request Jul 27, 2026
#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]>
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