23 KiB
story_id, story_key, requirement, status, baseline_commit, created
| story_id | story_key | requirement | status | baseline_commit | created |
|---|---|---|---|---|---|
| 1.14 | 1-14-approvals-side-effects | FR-5 | done | 767428436d |
2026-08-22T17:04:50+03:00 |
Story 1.14: Сделать approvals атомарными и side effects честными
Status: done
Story
As an администратор, I want требовать точное и одноразовое подтверждение опасных Operations, so that concurrent requests и retries не обходят approval и не создают неконтролируемые side effects.
Operational Brief
Story 1.14 закрывает FR-5. Это safety-слой поверх уже hardened цепочки:
- 1.7: Published Operation Version immutable;
- 1.8: Execution failures имеют closed typed taxonomy и честную uncertainty;
- 1.9: outbound REST защищён и не делает unsafe retry без idempotency;
- 1.10–1.12: machine/approval/Admin credentials имеют lifecycle и boundary separation;
- 1.13: Agent catalog immutable и MCP discovery/call привязан к published snapshot.
Теперь главный риск — human approval как обходной или racing механизм. Approval должен быть PostgreSQL-authoritative, full-scope, deduplicated, single-use и честно связан с side-effect outcome. Valkey/in-memory confirmation token может оставаться вспомогательной оптимизацией только для safe UX, но не должен быть authority для required approval.
Цель:
- вычислять canonical approval fingerprint до outbound dispatch;
- создавать ровно один active pending approval на full scope;
- проверять approval key, workspace, Agent, Operation Version, fingerprint, expiry и status при approve/deny;
- допускать ровно один terminal/consumption transition через conditional PostgreSQL update;
- не выполнять второй side effect при replay approved request/token;
- fail closed при недоступном mandatory approval/idempotency authority;
- честно маркировать uncertain post-dispatch outcome как
outcome_unknown/manual_reconcile, без exactly-once promises.
Acceptance Criteria
- Full-scope approval identity. Given Published Operation Version с policy
approval_required, when Agent запрашивает execution, then до outbound dispatch вычисляется canonical input fingerprint и approval scope из workspace, Agent, Operation/version и input, and изменение любого элемента scope требует отдельного approval. - Concurrent pending deduplication. Given несколько concurrent execution requests с одинаковым approval scope, when active approval отсутствует, then в PostgreSQL создаётся один canonical pending approval record, and остальные requests получают ссылку на тот же record без конкурирующих approvals.
- Pending replay returns status. Given active pending approval, when тот же request повторяется, then возвращается существующий status и безопасная metadata, and новый approval cycle не создаётся без явного terminal outcome и нового разрешённого request.
- Approval credential and scope checks. Given approval key, when выполняется approve или deny, then проверяются workspace, Agent, Operation/version, fingerprint, key scope, key status и expiry, and foreign, revoked, malformed или wrong-purpose key отклоняется без metadata leakage.
- Single-winner transitions. Given approve, deny, expiry или recovery происходят конкурентно, when выполняется state transition, then PostgreSQL conditional update допускает ровно один разрешённый переход из текущего state, and проигравший caller получает deterministic prior/conflict outcome без перезаписи terminal decision.
- Single-use execution admission. Given approved execution, when runtime собирается выполнить outbound dispatch, then approval потребляется single-use атомарно с execution admission либо durable dispatch intent, and replay approval token не разрешает второй side effect.
- Stale approval revalidation. Given approval был выдан ранее, when перед dispatch изменились Agent publication, Operation version, credential status, deadline или authorization context, then execution fail closed и не использует stale approval, and audit record объясняет безопасную причину отказа без раскрытия secret.
- Mandatory store fail-closed. Given mandatory approval/idempotency store недоступен, when Operation требует approval, then execution отклоняется до outbound dispatch и dependency отражается в readiness, and Valkey или in-memory fallback не заменяет PostgreSQL authority.
- Idempotency conflict. Given idempotency key для write Operation, when повторяется execution с тем же scoped key и тем же input fingerprint, then возвращается ранее сохранённый outcome либо состояние существующей попытки, and тот же key с иным fingerprint возвращает conflict.
- Side-effect honesty. Given write Operation без подтверждённого upstream idempotency contract, when после dispatch результат становится uncertain, then Crank не обещает exactly-once и не выполняет автоматический retry, and outcome явно классифицируется как потенциально совершивший side effect с сохранённым attempt/audit trail.
- Approval UI RU/EN. Given approval UI на RU и EN, when администратор просматривает, подтверждает или отклоняет request, then UI показывает точные Agent, Operation Version, безопасный input summary, expiry, Request ID и Trace ID, and approve/deny имеют confirmation, loading, conflict, expired и stale-response states.
- Security/race suite. Given approval security suite, when выполняются integration и race tests, then покрыты concurrent creation/decision, token replay, fingerprint mismatch, cross-Agent/workspace access, key revocation, expiry, store outage и uncertain side effect, and проходят registry/runtime/Admin/MCP/Playwright tests и
just verify.
Tasks / Subtasks
-
Task 1 — Freeze approval oracle and RED tests (AC: 1–12)
- Characterize current approval/confirmation flow in core/runtime/registry/MCP/Admin/UI and document what remains backward-compatible.
- Add RED tests for full-scope fingerprint, concurrent pending deduplication, single-winner decisions, replay, fingerprint mismatch and stale approval.
- Add RED tests for store outage, revoked approval key, foreign scope, unsafe uncertainty and safe metadata/redaction.
-
Task 2 — Domain approval identity and safe metadata (AC: 1, 3–4, 7, 11)
- Add typed approval scope/fingerprint in
crank-core, using deterministic canonical JSON with confirmation/approval control fields removed. - Bound summary fields and never store raw request payload as UI/API metadata; store safe summary plus fingerprint.
- Keep request_id/trace_id on approval responses/errors and never expose raw secret, approval key, auth header, full request body or foreign metadata.
- Add typed approval scope/fingerprint in
-
Task 3 — PostgreSQL authority and conditional transitions (AC: 2, 3, 5, 6, 8, 12)
- Add append-only migration if current schema cannot express full scope, single-use admission, execution lease/attempt and closed transition constraints.
- Create/reuse pending approvals with one transactional upsert/lock keyed by workspace, Agent, Operation/version and fingerprint.
- Implement approve/deny/expiry/claim/finish/recovery via conditional updates with deterministic prior/conflict outcomes.
- Add real-PG concurrency tests; no in-memory/Valkey authority for required approval.
-
Task 4 — Runtime/MCP admission and side-effect honesty (AC: 6–10, 12)
- MCP tool call must create/reuse pending approval before runtime dispatch and return existing safe status on replay.
- Approved execution must claim/consume approval atomically before outbound dispatch or durable dispatch intent.
- Revalidate Agent publication/catalog revision, Operation version, credential status, authorization context, deadline and idempotency fingerprint before dispatch.
- Preserve
outcome_unknown/manual_reconcilefor uncertain post-dispatch writes and prevent automatic unsafe retry.
-
Task 5 — Approval HTTP/API boundaries and audit (AC: 4–8, 11–12)
- Approval endpoints accept only active approval keys with correct kind/scope/origin/status/expiry.
- Approve/deny responses are deterministic for pending, terminal, expired and conflict states.
- Audit/invocation records contain bounded safe approval metadata, request_id, trace_id and outcome without payload/secret leakage.
-
Task 6 — Admin/UI approval experience (AC: 3, 5, 11)
- UI lists pending/terminal approvals with safe summary, exact Agent/Operation Version, expiry, request_id and trace_id.
- Approve/deny require confirmation and expose loading/conflict/expired/stale-response states.
- RU/EN strings are added together; async responses are guarded by workspace/approval identity.
- Add Playwright coverage for approval pending view, approve/deny, conflict/expired and stale-response behavior.
-
Task 7 — Docs, inventory, gates and handoff (AC: 12)
- Update
docs/admin-api.md,docs/mcp-interface.md,docs/data-model.md, manual regression checklist and capability inventory for FR-5 only after evidence passes. - Run targeted registry/runtime/MCP/Admin/UI tests, migration/config/metrics/boundary/capability gates and final
just verify. - Update Dev Agent Record, File List, Change Log and status to
doneonly after review patches and all gates pass.
- Update
Review Findings
- [Review][Patch] Admin approval UI scope contradicted AC11 — resolved by implementing Admin approve/deny routes and UI confirmation/loading/stale guards with request_id/trace_id visibility.
- [Review][Patch] Approved execution used redacted/truncated approval summary as runtime input — resolved by preserving raw request payload for execution while projecting only safe summaries externally.
- [Review][Patch] v10 migration dropped the v9
ON CONFLICTarbiter — resolved by preserving the v9 arbiter and adding the v10 scoped index/columns append-only. - [Review][Patch] Approve/deny transition did not predicate on operation_id, operation_version, or request_fingerprint — resolved with full-scope decision predicates.
- [Review][Patch] Terminal approval response payload was stored and returned without bounded redaction — resolved by sanitizing terminal response previews before storage/projection.
- [Review][Patch] Safe approval summary redacted sensitive key names but not secret-looking string values under neutral keys — resolved by extending safe preview redaction to secret-looking string values.
- [Review][Patch] Approval fingerprint recursively stripped reserved
_crank_*field names from nested business payloads — resolved by limiting control-field stripping to the top-level request envelope. - [Review][Patch] Pending-expiry update was not workspace-scoped — resolved by adding workspace scope to expiry updates.
- [Review][Patch] Approval records and UI evidence did not carry request_id and trace_id — resolved by persisting/projecting both identifiers and showing them in the Admin UI.
- [Review][Patch] AC12/GATES evidence overclaimed the security matrix — resolved by adding scoped regression tests and updating gate evidence to actual command outputs.
Dev Notes
Current State / Repository Findings
crates/crank-core/src/approval.rshasApprovalRequestStatusandApprovalRequest, but the record storesrequest_payloadand lacks a typed full-scope fingerprint/value object.crates/crank-runtime/src/confirmation.rscurrently gates dangerous Operations through confirmation tokens stored inCoordinationStateStore. This is not sufficient for FR-5 because Valkey/in-memory cannot be approval authority; required approvals must be PostgreSQL-authoritative.crates/crank-registryalready hasapproval_requestsschema and methods for create/list/get/decide/expire/claim/finish/recovery, with partial baseline fields:execution_started_at,execution_attempts,request_fingerprint, pending fingerprint index.crates/crank-community-mcp/src/app.rsandapproval_execution.rsown MCP approval creation, approval HTTP endpoints and recovery. Approved execution already usesRuntimeRequestContext::with_approval_granted(), but 1.14 must ensure this cannot be replayed or stale after Agent/Operation/key changes.crates/crank-community-mcp/src/approval_response.rscurrently may includeapproval.request_payloadwhen policyshow_payload_previewis true. Story 1.14 requires safe bounded summary instead of raw payload exposure.- Story 1.10 already enforced approval-key kind/scope/origin/revocation and duplicate Authorization rejection; preserve those boundaries and extend them to exact scope/fingerprint checks.
- Story 1.8/1.9 already introduced typed runtime outcomes, dispatch uncertainty and idempotency safeguards. Reuse those contracts; do not create ad-hoc approval error taxonomy.
- Existing MCP approval tests live under
apps/mcp-server/tests/integration/catalog_access/approval_access.rsand submodulespending.rs,revocation.rs. Extend them rather than duplicating setup. - UI currently has Logs/Usage approval panels but must be verified for exact pending summary, approve/deny confirmations, stale/expired conflict states and RU/EN text.
Architecture and Safety Constraints
- PostgreSQL is the correctness authority for approvals. Valkey/cache loss must not allow approval bypass or duplicate side effect.
- Approval identity is unique on workspace, Agent, published Agent/catalog revision as needed, Operation ID/version and canonical input fingerprint.
- Every state change uses one transaction and conditional predicates. No check-then-write without row lock for approval state.
Pending → Approved|Denied|Expired; approved execution claim moves into an execution/admission state exactly once; completion/failure/recovery is terminal or explicitlyoutcome_unknown.- Foreign workspace/Agent/Operation/key failures must not reveal object metadata.
request_idandtrace_idare support identifiers, never metric labels.- Do not claim exactly-once external side effects. Without verified upstream idempotency, post-dispatch uncertainty is
outcome_unknownand requires manual reconciliation. - No dependency/toolchain/MSRV change. No runtime DDL outside MigrationAuthority. Previous migration bytes/checksums remain immutable.
Likely File Map
Likely UPDATE:
crates/crank-core/src/approval.rscrates/crank-core/src/operation.rscrates/crank-runtime/src/confirmation.rscrates/crank-runtime/src/executor.rscrates/crank-runtime/src/idempotency.rscrates/crank-runtime/src/request_context.rscrates/crank-registry/src/{model.rs,error.rs,lib.rs}crates/crank-registry/src/postgres/{approval.rs,mod.rs}crates/crank-registry/src/migrations/{authority.rs,schema_guard.rs}crates/crank-registry/tests/integration/{workspace_access.rs,common.rs}crates/crank-runtime/tests/integration/{confirmation.rs,idempotency.rs}crates/crank-community-mcp/src/{app.rs,approval_execution.rs,approval_response.rs,access.rs,tool_error.rs}apps/mcp-server/tests/integration/catalog_access/approval_access.rsapps/mcp-server/tests/integration/catalog_access/approval_access/{pending.rs,revocation.rs}apps/admin-api/src/service/observability.rsapps/ui/js/{logs-usage.js,i18n.js,api.js}apps/ui/tests/e2e/logs-usage.spec.jsor newapprovals.spec.jsdocs/{admin-api.md,mcp-interface.md,data-model.md,manual-regression-checklist.md,capability-inventory.json}
Likely NEW:
crates/crank-core/src/approval_identity.rsif keeping identity logic separate.crates/crank-registry/src/migrations/approval_side_effects_v10.sqlif schema gaps require v10.crates/crank-registry/tests/integration/approval.rscrates/crank-runtime/tests/integration/approval.rsapps/ui/tests/e2e/approvals.spec.js
Required Test Matrix
- Same workspace/Agent/Operation/version/input ⇒ one pending approval under 32 concurrent callers.
- Any difference in workspace, Agent, Operation, version, fingerprint or key scope ⇒ different approval or safe denial.
- Repeat pending call ⇒ existing status and safe metadata, no new cycle.
- Approve vs deny vs expire vs recovery race ⇒ one legal transition, losers deterministic.
- Approved replay ⇒ no second outbound call.
- Approval key revoked/expired/wrong-kind/wrong-agent/wrong-origin ⇒ denied before mutation.
- Agent unpublish/archive/catalog revision change, Operation version unavailable, credential status change or deadline expiry after approval ⇒ fail closed before dispatch.
- Mandatory PostgreSQL approval store unavailable ⇒ no outbound dispatch.
- Idempotency same key+same fingerprint ⇒ previous outcome/attempt; same key+different fingerprint ⇒ conflict.
- Mutating post-dispatch timeout/transport uncertainty ⇒
outcome_unknown/manual_reconcile, no automatic retry. - UI RU/EN: pending summary, approve, deny, expired, conflict, stale response, request_id, trace_id.
Dev Agent Record
Agent Model Used
GPT-5 Codex
Debug Log References
- 2026-08-22T17:04:50+03:00 — Created Story 1.14 from Epic 1 FR-5 because sprint-status had
1-14-approvals-side-effects: backlogand no dedicated story file existed. Baseline commit767428436d3a54e60809a727044dfcec48e1f1dd. - 2026-08-22T17:14:00+03:00 — RED registry approval race test reproduced the defect: 32 concurrent equal-scope calls could create 32 pending approvals because volatile confirmation/approval control fields were included in the fingerprint.
- 2026-08-22T17:31:00+03:00 — Implemented safe request summary storage and canonical fingerprint stripping for approval/confirmation control fields.
- 2026-08-22T17:43:00+03:00 — Added v10 approval-side-effects migration and schema guard; pending approval uniqueness is now scoped by workspace, Agent, Operation version and canonical fingerprint.
- 2026-08-22T17:52:00+03:00 — Targeted registry, MCP approval, runtime confirmation/idempotency, UI build/Playwright, migration contract and capability inventory checks passed.
- 2026-08-22T18:02:00+03:00 — Final
just verifypassed after updating the append-only migration authority test to include v10. - 2026-08-23T00:15:13+03:00 — Code-review patches completed: Admin approve/deny API/UI, raw execution payload preservation, v9 arbiter preservation, request_id/trace_id persistence, redaction/fingerprint fixes and metrics route registry update. Final
just verifyand Playwright approval spec passed.
Completion Notes List
- Implemented canonical approval deduplication on the existing PostgreSQL authority path: volatile approval/confirmation control fields no longer create distinct approval fingerprints.
- Pending approval projections now expose only bounded safe summaries, while the PostgreSQL authority path preserves raw request payload for approved execution admission.
- Added append-only v10 migration and schema guard for the approval-side-effects contract; previous migration bytes remain untouched.
- MCP approval endpoints continue to enforce approval-key approval boundaries. Admin API/UI now exposes operator approve/deny actions for existing approval records with confirmation/loading/stale guards; execution admission and side-effect dispatch remain in the canonical MCP/runtime path.
- Updated FR-5 docs, data model, MCP/Admin API references, manual regression checklist, capability inventory and baseline manifest evidence.
- Final repository gate passed:
just verifyexit code 0 on 2026-08-23T00:15:13+03:00; approval Playwright spec passed after fixing the test assertion.
File List
_bmad-output/implementation-artifacts/1-14-approvals-side-effects.md_bmad-output/implementation-artifacts/sprint-status.yamlapps/admin-api/src/app.rsapps/admin-api/src/dto.rsapps/admin-api/src/routes/observability.rsapps/admin-api/src/service/observability.rsapps/admin-api/tests/migration_command.rsapps/mcp-server/tests/integration/catalog_access/approval_access/pending.rsapps/ui/js/api.jsapps/ui/js/i18n.jsapps/ui/js/logs.jsapps/ui/tests/e2e/approvals.spec.jscrates/crank-community-mcp/src/app.rscrates/crank-community-mcp/src/approval_response.rscrates/crank-core/src/approval.rscrates/crank-core/src/observability.rscrates/crank-metrics/src/schema.rscrates/crank-metrics/tests/schema_v1.rscrates/crank-registry/src/migrations.rscrates/crank-registry/src/migrations/approval_side_effects_v10.rscrates/crank-registry/src/migrations/approval_side_effects_v10.sqlcrates/crank-registry/src/migrations/authority.rscrates/crank-registry/src/migrations/authority_tests.rscrates/crank-registry/src/migrations/schema_guard.rscrates/crank-registry/src/migrations/schema_guard_v10.rscrates/crank-registry/src/postgres/approval.rscrates/crank-registry/tests/integration.rscrates/crank-registry/tests/integration/approval.rscrates/crank-registry/tests/integration/migrations.rsdocs/admin-api.mddocs/capability-baseline/manifest.jsondocs/capability-inventory.jsondocs/data-model.mddocs/manual-regression-checklist.mddocs/mcp-interface.mddocs/migrations.mddocs/schemas/metrics-registry-v1.jsondocs/schemas/migration-sequence.json
Change Log
- 2026-08-22 — Created Story 1.14 from Epic 1 FR-5 with approval atomicity, side-effect honesty, UI and race-test context.
- 2026-08-22 — Implemented Story 1.14 approval fingerprint/safe-summary/v10 migration hardening and moved story to review after targeted checks and
just verifypassed. - 2026-08-23 — Applied code-review patches, added Admin approve/deny UI/API, corrected approval payload/redaction/fingerprint/migration evidence gaps, reran final gates and moved story to done.