251 lines
23 KiB
Markdown
251 lines
23 KiB
Markdown
---
|
||
story_id: "1.14"
|
||
story_key: "1-14-approvals-side-effects"
|
||
requirement: "FR-5"
|
||
status: "done"
|
||
baseline_commit: "767428436d3a54e60809a727044dfcec48e1f1dd"
|
||
created: "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
|
||
|
||
1. **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.
|
||
2. **Concurrent pending deduplication.** Given несколько concurrent execution requests с одинаковым approval scope, when active approval отсутствует, then в PostgreSQL создаётся один canonical pending approval record, and остальные requests получают ссылку на тот же record без конкурирующих approvals.
|
||
3. **Pending replay returns status.** Given active pending approval, when тот же request повторяется, then возвращается существующий status и безопасная metadata, and новый approval cycle не создаётся без явного terminal outcome и нового разрешённого request.
|
||
4. **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.
|
||
5. **Single-winner transitions.** Given approve, deny, expiry или recovery происходят конкурентно, when выполняется state transition, then PostgreSQL conditional update допускает ровно один разрешённый переход из текущего state, and проигравший caller получает deterministic prior/conflict outcome без перезаписи terminal decision.
|
||
6. **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.
|
||
7. **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.
|
||
8. **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.
|
||
9. **Idempotency conflict.** Given idempotency key для write Operation, when повторяется execution с тем же scoped key и тем же input fingerprint, then возвращается ранее сохранённый outcome либо состояние существующей попытки, and тот же key с иным fingerprint возвращает conflict.
|
||
10. **Side-effect honesty.** Given write Operation без подтверждённого upstream idempotency contract, when после dispatch результат становится uncertain, then Crank не обещает exactly-once и не выполняет автоматический retry, and outcome явно классифицируется как потенциально совершивший side effect с сохранённым attempt/audit trail.
|
||
11. **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.
|
||
12. **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
|
||
|
||
- [x] Task 1 — Freeze approval oracle and RED tests (AC: 1–12)
|
||
- [x] Characterize current approval/confirmation flow in core/runtime/registry/MCP/Admin/UI and document what remains backward-compatible.
|
||
- [x] Add RED tests for full-scope fingerprint, concurrent pending deduplication, single-winner decisions, replay, fingerprint mismatch and stale approval.
|
||
- [x] Add RED tests for store outage, revoked approval key, foreign scope, unsafe uncertainty and safe metadata/redaction.
|
||
|
||
- [x] Task 2 — Domain approval identity and safe metadata (AC: 1, 3–4, 7, 11)
|
||
- [x] Add typed approval scope/fingerprint in `crank-core`, using deterministic canonical JSON with confirmation/approval control fields removed.
|
||
- [x] Bound summary fields and never store raw request payload as UI/API metadata; store safe summary plus fingerprint.
|
||
- [x] Keep request_id/trace_id on approval responses/errors and never expose raw secret, approval key, auth header, full request body or foreign metadata.
|
||
|
||
- [x] Task 3 — PostgreSQL authority and conditional transitions (AC: 2, 3, 5, 6, 8, 12)
|
||
- [x] Add append-only migration if current schema cannot express full scope, single-use admission, execution lease/attempt and closed transition constraints.
|
||
- [x] Create/reuse pending approvals with one transactional upsert/lock keyed by workspace, Agent, Operation/version and fingerprint.
|
||
- [x] Implement approve/deny/expiry/claim/finish/recovery via conditional updates with deterministic prior/conflict outcomes.
|
||
- [x] Add real-PG concurrency tests; no in-memory/Valkey authority for required approval.
|
||
|
||
- [x] Task 4 — Runtime/MCP admission and side-effect honesty (AC: 6–10, 12)
|
||
- [x] MCP tool call must create/reuse pending approval before runtime dispatch and return existing safe status on replay.
|
||
- [x] Approved execution must claim/consume approval atomically before outbound dispatch or durable dispatch intent.
|
||
- [x] Revalidate Agent publication/catalog revision, Operation version, credential status, authorization context, deadline and idempotency fingerprint before dispatch.
|
||
- [x] Preserve `outcome_unknown/manual_reconcile` for uncertain post-dispatch writes and prevent automatic unsafe retry.
|
||
|
||
- [x] Task 5 — Approval HTTP/API boundaries and audit (AC: 4–8, 11–12)
|
||
- [x] Approval endpoints accept only active approval keys with correct kind/scope/origin/status/expiry.
|
||
- [x] Approve/deny responses are deterministic for pending, terminal, expired and conflict states.
|
||
- [x] Audit/invocation records contain bounded safe approval metadata, request_id, trace_id and outcome without payload/secret leakage.
|
||
|
||
- [x] Task 6 — Admin/UI approval experience (AC: 3, 5, 11)
|
||
- [x] UI lists pending/terminal approvals with safe summary, exact Agent/Operation Version, expiry, request_id and trace_id.
|
||
- [x] Approve/deny require confirmation and expose loading/conflict/expired/stale-response states.
|
||
- [x] RU/EN strings are added together; async responses are guarded by workspace/approval identity.
|
||
- [x] Add Playwright coverage for approval pending view, approve/deny, conflict/expired and stale-response behavior.
|
||
|
||
- [x] Task 7 — Docs, inventory, gates and handoff (AC: 12)
|
||
- [x] 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.
|
||
- [x] Run targeted registry/runtime/MCP/Admin/UI tests, migration/config/metrics/boundary/capability gates and final `just verify`.
|
||
- [x] Update Dev Agent Record, File List, Change Log and status to `done` only after review patches and all gates pass.
|
||
|
||
### Review Findings
|
||
|
||
- [x] [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.
|
||
- [x] [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.
|
||
- [x] [Review][Patch] v10 migration dropped the v9 `ON CONFLICT` arbiter — resolved by preserving the v9 arbiter and adding the v10 scoped index/columns append-only.
|
||
- [x] [Review][Patch] Approve/deny transition did not predicate on operation_id, operation_version, or request_fingerprint — resolved with full-scope decision predicates.
|
||
- [x] [Review][Patch] Terminal approval response payload was stored and returned without bounded redaction — resolved by sanitizing terminal response previews before storage/projection.
|
||
- [x] [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.
|
||
- [x] [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.
|
||
- [x] [Review][Patch] Pending-expiry update was not workspace-scoped — resolved by adding workspace scope to expiry updates.
|
||
- [x] [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.
|
||
- [x] [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.rs` has `ApprovalRequestStatus` and `ApprovalRequest`, but the record stores `request_payload` and lacks a typed full-scope fingerprint/value object.
|
||
- `crates/crank-runtime/src/confirmation.rs` currently gates dangerous Operations through confirmation tokens stored in `CoordinationStateStore`. This is not sufficient for FR-5 because Valkey/in-memory cannot be approval authority; required approvals must be PostgreSQL-authoritative.
|
||
- `crates/crank-registry` already has `approval_requests` schema 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.rs` and `approval_execution.rs` own MCP approval creation, approval HTTP endpoints and recovery. Approved execution already uses `RuntimeRequestContext::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.rs` currently may include `approval.request_payload` when policy `show_payload_preview` is 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.rs` and submodules `pending.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 explicitly `outcome_unknown`.
|
||
- Foreign workspace/Agent/Operation/key failures must not reveal object metadata.
|
||
- `request_id` and `trace_id` are support identifiers, never metric labels.
|
||
- Do not claim exactly-once external side effects. Without verified upstream idempotency, post-dispatch uncertainty is `outcome_unknown` and 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.rs`
|
||
- `crates/crank-core/src/operation.rs`
|
||
- `crates/crank-runtime/src/confirmation.rs`
|
||
- `crates/crank-runtime/src/executor.rs`
|
||
- `crates/crank-runtime/src/idempotency.rs`
|
||
- `crates/crank-runtime/src/request_context.rs`
|
||
- `crates/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.rs`
|
||
- `apps/mcp-server/tests/integration/catalog_access/approval_access/{pending.rs,revocation.rs}`
|
||
- `apps/admin-api/src/service/observability.rs`
|
||
- `apps/ui/js/{logs-usage.js,i18n.js,api.js}`
|
||
- `apps/ui/tests/e2e/logs-usage.spec.js` or new `approvals.spec.js`
|
||
- `docs/{admin-api.md,mcp-interface.md,data-model.md,manual-regression-checklist.md,capability-inventory.json}`
|
||
|
||
Likely NEW:
|
||
|
||
- `crates/crank-core/src/approval_identity.rs` if keeping identity logic separate.
|
||
- `crates/crank-registry/src/migrations/approval_side_effects_v10.sql` if schema gaps require v10.
|
||
- `crates/crank-registry/tests/integration/approval.rs`
|
||
- `crates/crank-runtime/tests/integration/approval.rs`
|
||
- `apps/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: backlog` and no dedicated story file existed. Baseline commit `767428436d3a54e60809a727044dfcec48e1f1dd`.
|
||
- 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 verify` passed 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 verify` and 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 verify` exit 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.yaml`
|
||
- `apps/admin-api/src/app.rs`
|
||
- `apps/admin-api/src/dto.rs`
|
||
- `apps/admin-api/src/routes/observability.rs`
|
||
- `apps/admin-api/src/service/observability.rs`
|
||
- `apps/admin-api/tests/migration_command.rs`
|
||
- `apps/mcp-server/tests/integration/catalog_access/approval_access/pending.rs`
|
||
- `apps/ui/js/api.js`
|
||
- `apps/ui/js/i18n.js`
|
||
- `apps/ui/js/logs.js`
|
||
- `apps/ui/tests/e2e/approvals.spec.js`
|
||
- `crates/crank-community-mcp/src/app.rs`
|
||
- `crates/crank-community-mcp/src/approval_response.rs`
|
||
- `crates/crank-core/src/approval.rs`
|
||
- `crates/crank-core/src/observability.rs`
|
||
- `crates/crank-metrics/src/schema.rs`
|
||
- `crates/crank-metrics/tests/schema_v1.rs`
|
||
- `crates/crank-registry/src/migrations.rs`
|
||
- `crates/crank-registry/src/migrations/approval_side_effects_v10.rs`
|
||
- `crates/crank-registry/src/migrations/approval_side_effects_v10.sql`
|
||
- `crates/crank-registry/src/migrations/authority.rs`
|
||
- `crates/crank-registry/src/migrations/authority_tests.rs`
|
||
- `crates/crank-registry/src/migrations/schema_guard.rs`
|
||
- `crates/crank-registry/src/migrations/schema_guard_v10.rs`
|
||
- `crates/crank-registry/src/postgres/approval.rs`
|
||
- `crates/crank-registry/tests/integration.rs`
|
||
- `crates/crank-registry/tests/integration/approval.rs`
|
||
- `crates/crank-registry/tests/integration/migrations.rs`
|
||
- `docs/admin-api.md`
|
||
- `docs/capability-baseline/manifest.json`
|
||
- `docs/capability-inventory.json`
|
||
- `docs/data-model.md`
|
||
- `docs/manual-regression-checklist.md`
|
||
- `docs/mcp-interface.md`
|
||
- `docs/migrations.md`
|
||
- `docs/schemas/metrics-registry-v1.json`
|
||
- `docs/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 verify` passed.
|
||
- 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.
|