42 KiB
story_id, story_key, requirement, status, baseline_commit
| story_id | story_key | requirement | status | baseline_commit |
|---|---|---|---|---|
| 1.8 | 1-8-rest-execution-boundary-errors | FR-2 | done | 767428436d |
Story 1.8: Унифицировать REST execution и boundary errors
Status: done
Story
As an администратор или MCP-пользователь, I want получать одинаковое и предсказуемое выполнение Operation через UI и MCP, so that результат и классификация ошибки не зависят от входной точки.
Strategic Intent
Story 1.8 закрепляет единственную синхронную execution boundary существующего REST → MCP продукта после immutable Operation lifecycle из Story 1.7. Сегодня Admin Test и MCP tools/call оба вызывают runtime, но собирают неполный RuntimeExecutionRequest, разрешают optional correlation/scope, отдельно резолвят auth и независимо преобразуют RuntimeError в несовпадающие коды, сообщения и retryability. Admin history также способен сохранить error.to_string(), содержащий внутренние детали.
Итоговый контракт: Admin Draft Test и MCP exact Published Tool создают один полностью scoped typed request, проходят один runtime/adapter pipeline и получают один внутренний normalized outcome. HTTP и MCP отвечают своими wire-формами, но сохраняют одинаковые stage, stable code, retryability, outcome certainty, Request ID и Trace ID. Никакая boundary не анализирует текст ошибки и не знает варианты RestAdapterError.
Story является обязательным predecessor для 1.9 outbound/SSRF hardening, 1.13 immutable Agent catalog, Epic 3 dynamic capabilities и Epic 4 Tasks. Она не реализует DNS/redirect/retry policy, background Tasks, новый MCP wire revision или History UI.
Requirement: FR-2
Architecture: AD-1, AD-2, AD-4, AD-9, AD-11, AD-15, AD-19, AD-21, AD-23; consistency conventions
Applicable NFR: NFR-P4, NFR-R1, NFR-S1, NFR-S2, NFR-S4, NFR-S7, NFR-S8, NFR-O1, NFR-O4, NFR-O5, NFR-C1, NFR-C4
Primary risk/evidence: E1-R-007 (score 9); E1-17, E1-18, E1-19.
Acceptance Criteria
-
Один обязательный typed execution envelope
- Given Admin Test или MCP
tools/call - When application layer принимает выполнение
- Then она создаёт ровно один
RuntimeExecutionRequestс typedWorkspaceId, origin (admin_draft|agent_snapshot), optional typedAgentIdтолько по правилам origin, exactOperationId/version, authorization decision/resolved auth, input, monotonic deadline, canonical correlation, approval и idempotency context - And production constructor не допускает отсутствующий workspace, operation/version, deadline или correlation и не генерирует fallback IDs внутри runtime
- And secret-bearing resolved auth, confirmation и idempotency material не реализуют раскрывающий
Debug/Display/Serialize; fingerprint/context хранит только необходимые typed or redacted values - And invalid/missing/incompatible scope отклоняется до mapping, adapter lookup и outbound dispatch.
- Given Admin Test или MCP
-
Единый pipeline без transport bypass
- Given валидный execution envelope
- When начинается выполнение
- Then оба ingress проходят
RuntimeExecutionRequest → crank-runtime → ProtocolAdapter → crank-adapter-rest - And route/transport/service не вызывает REST client, SQLx persistence implementation или mapping/schema implementation напрямую
- And test-only convenience methods не остаются доступным production bypass.
-
Admin исполняет только exact current saved Draft
- Given active Operation и выбранная current Draft revision
- When Admin запускает Test
- Then application resolution из Story 1.7 фиксирует exact saved version до runtime admission и origin равен
admin_draft - And unsaved browser state, Published/archived/non-current/foreign version отклоняется до dispatch
- And выполнение не публикует Draft и не меняет Agent catalog.
-
MCP исполняет только exact immutable Agent snapshot
- Given авторизованный опубликованный Agent snapshot
- When клиент вызывает Tool
- Then tool resolution фиксирует exact Published Operation version из immutable binding и origin равен
agent_snapshotс typed Agent ID - And Draft, archived-new-binding, foreign Agent, непредоставленный Tool или capability вне snapshot получает safe not-found/denied без metadata leakage и без adapter call
- And existing pinned Agent behavior из Story 1.7 сохраняется.
-
Один normalized success outcome
- Given одинаковые exact Operation version, input, auth и deterministic upstream response
- When вызов выполнен через Admin и MCP
- Then schema validation, input mapping, request preparation, adapter execution, output mapping и output schema validation дают семантически одинаковый normalized output
- And HTTP Test DTO и MCP content/result являются только transport projections этого outcome
- And transport-specific envelope, status и localization не входят в runtime domain contract.
-
Закрытая typed failure taxonomy
- Given failure на
authorization|input_schema|input_mapping|request_preparation|admission|adapter|upstream|output_mapping|output_schema|mandatory_persistence|runtime - When failure покидает owning layer
- Then она преобразуется один раз в framework-free
ExecutionFailureс closedstage, stableerror_code,retryability,outcome_certainty, optional bounded safe context и correlation - And HTTP/MCP/history/metrics используют этот descriptor, не повторяют match по
RuntimeError/RestAdapterErrorи не выводят raw cause - And unknown internal failure fail closed как
runtime_internal,retryability=never, без произвольного текста.
- Given failure на
-
Фиксированная retryability/certainty семантика
- Given typed failure
- When клиент или оператор решает, можно ли повторять
- Then retryability принимает только
never|safe|after_delay|manual_reconcile|requires_confirmation, а certainty —certain|outcome_unknown - And validation/auth/not-found/conflict являются
never; overload/known pre-dispatch transport failure —after_delay; confirmation —requires_confirmation; ambiguous write/cancellation after dispatch —manual_reconcile + outcome_unknown - And
outcome_unknownникогда не превращается в recoverable/automatic retry по тексту, HTTP status или MCP transport status.
-
Deadline, timeout и cancellation не дают ложный success
- Given bounded monotonic deadline или cancellation
- When deadline истекает до dispatch, во время adapter wait либо после возможной отправки write
- Then runtime возвращает typed stage/certainty согласно фактически достигнутой dispatch boundary
- And cancelled idempotent execution завершает coordination state безопасно; cleanup failure не меняет внешний outcome и создаёт bounded operational incident
- And один upstream response/side effect не учитывается дважды.
-
Persistence semantics честны
- Given completed success/failure
- When Invocation History сохраняется
- Then новая запись сохраняет Request ID, Trace ID, source, exact Operation/version, stage, error code, retryability и outcome certainty независимо от sampling
- And schema evolution выполняется только append-only MigrationAuthority v5 с N/N-1 nullable compatibility; v1–v4 source/checksum не меняются
- And отказ обязательного pre-dispatch safety persistence блокирует dispatch, а отказ post-outcome diagnostic history сохраняет product outcome и создаёт typed History Loss incident (DC-08), не подменяя success на failure.
-
Safe localized boundaries
- Given normalized success/failure
- When формируется Admin Test или MCP response
- Then обе boundary возвращают stable
error_code, stage, explicit retryability/certainty, bounded RU/EN message согласно выбранной locale и одинаковые safe Request/Trace IDs - And raw upstream body, URL, headers, credential, SQLx/Reqwest/parser text, internal path и arbitrary payload отсутствуют в response, history message, logs, traces, metrics и evidence
- And существующие HTTP route paths, MCP method names/protocol negotiation и успешные response fields сохраняются; additive error fields документированы.
-
Typed observability без cardinality regression
- Given execution success или любая failure stage
- When записываются spans/metrics/history
- Then используются существующие typed
crank-tracestages иcrank-metricsoutcome enums; Request/Trace/Object IDs не становятся labels - And один execution создаёт согласованный terminal metric outcome, а Trace ID используется только как exemplar/trace field
- And redaction/preview остаются bounded valid UTF-8/JSON, включая oversized malformed upstream/error canaries.
-
Паритет и архитектура доказаны executable gates
- Given Story implementation
- When выполняются E1-17/E1-18/E1-19 suites
- Then table-driven matrix сравнивает Admin и MCP для success и всех stages по normalized output/code/stage/retryability/certainty/IDs и точному adapter call count
- And negative architecture fixtures ловят direct adapter/persistence call, alias, re-export и helper bypass
- And targeted suites, migration/SQLx checks, Capability Inventory, explicit Community scan, real REST→MCP smoke и
just verifyпроходят без dependency/toolchain/public-success-wire changes.
Frozen Execution Taxonomy
| Stage | Representative failures | Default retryability | Certainty |
|---|---|---|---|
authorization |
missing/foreign scope, revoked/missing profile/secret | never |
certain |
input_schema |
input violates schema | never |
certain |
input_mapping |
JSONPath/mapping failure | never |
certain |
request_preparation |
malformed mapped header/path/query/body | never |
certain |
admission |
concurrency/mandatory coordination unavailable | after_delay for overload/store outage; otherwise never |
certain |
adapter |
unsupported protocol/config before dispatch | never |
certain |
upstream |
status/transport/timeout | derived by typed dispatch evidence, never message text | certain or outcome_unknown |
output_mapping |
response mapping failure | never |
certain |
output_schema |
mapped response violates schema | never |
certain |
mandatory_persistence |
required safety record unavailable before acknowledgement | after_delay |
certain |
runtime |
invariant/internal normalized failure | never |
certain |
Additional non-error control outcomes such as requires_confirmation, idempotency in_progress|conflict|outcome_unknown remain explicit typed outcomes and map into the same retryability/certainty vocabulary. HTTP status and MCP isError are projections, not sources of truth.
Frozen machine codes
error_code является closed enum, а не произвольной строкой. Минимальный v1 vocabulary:
| Stage/control | Stable codes |
|---|---|
| authorization | authorization_denied, auth_profile_not_found, secret_not_found, secret_invalid |
| input_schema | input_schema_invalid |
| input_mapping | input_mapping_invalid |
| request_preparation | prepared_request_invalid |
| admission | execution_overloaded, safety_store_unavailable |
| adapter | protocol_unsupported, execution_mode_unsupported, adapter_configuration_invalid, outbound_target_rejected |
| upstream | upstream_auth_error, upstream_not_found, upstream_rate_limited, upstream_server_error, upstream_status_error, upstream_timeout, upstream_transport_error, upstream_response_too_large |
| output_mapping | output_mapping_invalid |
| output_schema | output_schema_invalid |
| mandatory_persistence | persistence_unavailable |
| runtime | runtime_internal |
| control | confirmation_required, confirmation_invalid, idempotency_in_progress, idempotency_conflict, idempotency_outcome_unknown |
Новое значение требует изменения typed enum, exhaustive parity table, RU/EN catalog и versioned contract evidence в одном change. Story 1.9 может уточнить typed upstream/outbound causes, но не переименовывает опубликованные v1 codes.
Tasks / Subtasks
-
Task 1 — Freeze RED parity oracle and current bypass inventory (AC: 1–12)
- Add table-driven fixtures proving current Admin/MCP code/stage/recoverable mismatches, raw history error leakage and optional-context fallback.
- Instrument fake adapter/store call counters; every pre-dispatch rejection asserts zero calls and every accepted execution asserts exactly one expected adapter call.
- Record current public success DTO/MCP output snapshots and Story 1.7 exact Draft/Agent resolution invariants.
-
Task 2 — Introduce framework-free execution identity/outcome contract (AC: 1, 5–8, 10)
- Add closed
ExecutionOrigin,ExecutionStage,ExecutionErrorCode,Retryability,OutcomeCertainty,ExecutionFailureand normalized success/outcome types in the lowest framework-free owner (crank-core), with bounded safe context only. - Define exact serialization only where a durable/internal contract requires it; domain types remain distinct from HTTP/MCP DTOs.
- Add exhaustive constructor/truth-table tests; forbid unknown stage/code or incompatible retryability/certainty combinations.
- Add closed
-
Task 3 — Make
RuntimeExecutionRequestcomplete and non-optional (AC: 1–4, 8)- Require typed scope/origin/exact target, input, deadline, correlation, authorization, approval and idempotency context at construction.
- Remove production fallback ID/context generation and convenience
execute_with_*bypasses; migrate tests to an explicit fixture builder unavailable to production callers. - Validate origin invariants (
admin_drafthas no Agent;agent_snapshotrequires Agent and immutable binding) before mapping/dispatch.
-
Task 4 — Centralize runtime stage and error normalization (AC: 5–8, 11)
- Split oversized executor/error responsibilities into focused modules before crossing code-health ceilings; keep one terminal outcome recorder.
- Normalize schema/mapping/preparation/admission/protocol/adapter/upstream/output errors once and retain internal source only for redacted diagnostics.
- Add deadline/cancellation/dispatch-evidence seam and deterministic tests for before-dispatch, known-no-dispatch and ambiguous-after-dispatch cases.
-
Task 5 — Unify Admin Draft execution composition (AC: 1–3, 5, 9–10)
- Preserve Story 1.7 exact current-Draft resolution and construct the full envelope after authorization/scope checks.
- Replace local
runtime_error_code/runtime_test_failurebranching and rawerror.to_string()history message with normalized outcome projection. - Keep Test route/success fields; add stable stage/retryability/certainty fields and localized safe failures with Request/Trace IDs.
- Update the existing wizard Test result/error projection to localize the stable code in RU/EN, retain loading/recovery and safe ID copy behavior, and ignore stale operation/workspace responses; no new page or frontend framework.
-
Task 6 — Unify MCP snapshot and approved execution composition (AC: 1–5, 9–10)
- Preserve exact immutable Agent binding resolution for direct and approved tool calls and construct the same full envelope.
- Replace adapter-specific matching in
tool_error.rs; MCP boundary projects only normalized execution outcome. - Keep protocol negotiation/JSON-RPC/
isErrorsemantics and confirmation flow compatible across supported MCP revisions.
-
Task 7 — Persist honest execution classification via migration v5 (AC: 7–9)
- Add contiguous transactional exact-byte checksummed
execution_outcome_v5.sql; never alter v1–v4. - Add nullable N-1 compatible fields/indexes/checks for exact operation version, stage, stable error code, retryability and certainty; legacy rows remain explicitly unknown rather than fabricated.
- Update registry models/queries, version-aware schema fingerprint, SQLx metadata and fresh/v4→v5/replay/rollback/corruption tests.
- Add contiguous transactional exact-byte checksummed
-
Task 8 — Build Admin/MCP differential contract suite (AC: 3–12)
- Cover success, every frozen stage, missing/foreign scope, timeout, cancellation, overload, confirmation, idempotency conflict/outcome-unknown and history loss.
- Compare normalized semantic output plus code/stage/retryability/certainty/correlation; assert transport-only differences explicitly.
- Add secret/body/URL/path canaries to response/history/log/trace/metric capture and concurrency isolation tests.
-
Task 9 — Harden architecture guardrails (AC: 2, 12)
- Extend scanner to reject direct REST adapter/client or persistence execution from Admin/MCP routes/services and forbidden dependency/re-export/helper aliases.
- Scan tracked plus explicit untracked Rust candidates, fail closed on symlinks/missing paths and add negative fixtures for each bypass spelling.
- Preserve valid composition-root adapter construction and runtime→protocol-adapter dependency direction.
-
Task 10 — Docs, evidence and final qualification (AC: 10–12)
- Update runtime/error/Admin/MCP/history/migration docs and RU/EN message catalog; document additive error fields and no automatic retry for unknown outcome.
- Refresh Capability Inventory/baseline only after accepted evidence; do not claim 1.9 SSRF/retry hardening complete.
- Run targeted/differential/PG/MCP suites, migration+SQLx/config/metrics/boundary checks, real authenticated product smoke, explicit Community scan and one final
just verify.
Review Findings
- [Review][Patch] [High] Закрыть production bypass обязательного execution envelope: поля
RuntimeExecutionRequestи rawexecute_requestне должны позволять обойтиtry_new/normalized outcome [crates/crank-runtime/src/execution_request.rs:14] - [Review][Patch] [High] Удалить отдельный Admin mapping-preview short circuit и выполнять mapping ровно один раз внутри canonical runtime pipeline [
apps/admin-api/src/service/operations.rs:601] - [Review][Patch] [High] Передавать точную dispatch evidence и mutability во все REST failures, включая connect/DNS, status, invalid/oversized response и deadline [
crates/crank-adapter-rest/src/lib.rs:62] - [Review][Patch] [High] Исправить idempotency lifecycle: pre-dispatch failure/cancellation освобождает reservation, а post-dispatch completion failure становится
manual_reconcile + outcome_unknown[crates/crank-runtime/src/executor.rs:370] - [Review][Patch] [High] Не терять normalized outcome и correlation при отказе финального сохранения approved execution [
crates/crank-community-mcp/src/approval_execution.rs:303] - [Review][Patch] [High] Убрать открытый MCP string taxonomy и проводить authorization/control failures через closed typed descriptor и history [
crates/crank-community-mcp/src/tool_error.rs:69] - [Review][Patch] [High] Закрыть v5 error-code vocabulary и проверять точные определения constraints/index, а не только их имена [
crates/crank-registry/src/migrations/execution_outcome_v5.sql:8] - [Review][Patch] [Medium] Запретить новым application writes сохранять Invocation History без exact version и полной execution classification, сохранив nullable только для legacy N-1 rows [
crates/crank-registry/src/postgres/observability.rs:42] - [Review][Patch] [High] Расширить execution-boundary gate на raw runtime, adapter invocation, SQLx/persistence, mapping/schema, aliases/re-exports/helpers и весь MCP production subtree [
scripts/check-execution-boundaries.py:11] - [Review][Patch] [High] Добавить реально исполняемую Admin/MCP differential matrix для success, всех frozen stages, call counts, IDs, history, redaction и concurrency; исправить ложные completion claims [
_bmad-output/implementation-artifacts/1-8-rest-execution-boundary-errors.md:196] - [Review][Patch] [Medium] Провести выбранную RU/EN locale через обе boundary и исправить ошибочное размещение русских execution keys внутри английского UI-каталога [
apps/ui/js/i18n.js:787] - [Review][Patch] [Medium] Добавить workspace/operation/generation guard для результата Wizard Test после каждого await [
apps/ui/js/wizard-live.js:832] - [Review][Patch] [High] Восстановить typed confirmation challenge в Admin Test response и поддержать подтверждённый повтор без раскрытия token через Debug/logs [
apps/admin-api/src/error.rs:529] - [Review][Patch] [Medium] Отличать недоступность PostgreSQL при auth resolution от повреждённого секрета и не классифицировать storage failure как
secret_invalid + never[crates/crank-community-mcp/src/app.rs:995] - [Review][Patch] [High] Санитизировать и ограничивать Admin request preview до HTTP projection, исключив credential/header/body canaries [
apps/admin-api/src/service/operations.rs:703] - [Review][Patch] [High] Удалить revealing
Debug/Serializeу secret-bearingPreparedRequestлибо отделить redacted domain type от adapter wire type [crates/crank-core/src/ext/protocol.rs:116] - [Review][Patch] [Medium] Сделать
ExecutionFailurecode-specific и bounded: запретить confirmation/retry metadata на несовместимых codes и ограничить token/TTL [crates/crank-core/src/execution.rs:441]
Dev Notes
Current Brownfield State and Confirmed Gaps
RuntimeExecutionRequestcurrently holds onlyoperation,input, optional resolved auth and optional request context. Workspace/origin/Agent/deadline/authorization decision are implicit;RuntimeExecutorcan generate fallback IDs/context.- Admin Test and both MCP direct/approved paths already call
execute_request, which is the correct seam to strengthen. Do not create a second orchestrator. - Admin resolves exact current Draft after Story 1.7; MCP resolves exact immutable published binding. Preserve these separate application-resolution rules, then converge only at the runtime envelope.
- Admin owns
runtime_error_codeplusruntime_test_failure_*; MCP owns anotherruntime_error_code, safe-message, recoverable and action matrix and directly matchesRestAdapterError. Codes already diverge (schema_errorvsschema_validation_error,rest_errorvs status-specific upstream codes). RuntimeErrorwraps library-specific errors and does not encode stage, retryability, dispatch certainty or deadline/cancellation. Several Display implementations contain operation/secret IDs, URL/target or internal reasons; they are not boundary-safe.- Admin failure history currently writes
error.to_string()intomessage. This is a confirmed NFR-S2/O5 violation risk even when HTTP response is sanitized. - Invocation History stores source/status/error_kind and correlation, but not exact operation version, stage, retryability or certainty. Migration v5 is required for honest persisted classification; old rows must remain nullable/unknown.
- Post-outcome history failure is intentionally non-fatal (DC-08) in Admin and MCP. Preserve external success and emit the existing bounded loss incident; do not make diagnostic persistence a hidden correctness dependency.
- REST adapter policy/security defects belong to Story 1.9. Story 1.8 may expose dispatch evidence and normalize errors but must not claim DNS/redirect/proxy/retry policy qualification.
Architecture and Implementation Guardrails
crank-coreowns framework-free execution vocabulary/ports only; it must not import Tokio, Axum, SQLx, Reqwest, tracing or adapter error types.crank-runtimeowns orchestration and typed normalization; it may call protocol adapters but never registry/Axum/SQLx. It must not persist history.- Apps remain composition roots and own exact Draft/Agent resolution, auth-profile/secret resolution and transport projection. Routes do not call runtime/adapter directly.
- Boundary DTOs remain in Admin
dto.rsand MCP transport/tool error owners. Do not serializeRuntimeErroror expose source chains. - Internal
ExecutionFailuremust carry stable bounded fields, never a rawStringcause. Diagnostic source is logged only through existing redaction vocabulary. - Use Story 1.5
CorrelationContext/typed IDs and Story 1.6 typed stages/metrics/exemplars. Never regenerate IDs in runtime or add object/error text labels. - MigrationAuthority is the sole DDL owner. Add v5, update machine sequence/schema fingerprint/SQLx metadata, preserve N/N-1 reads and controlled migrator-only writes.
- Keep Rust 1.96.1/Edition 2024, current dependencies, Compose, Alpine UI, MCP revisions and Community boundary unchanged.
File Map
NEW expected
crates/crank-core/src/execution.rs— closed framework-free identity/outcome taxonomy.crates/crank-runtime/src/execution_failure.rsand/or focused executor stage/deadline module.crates/crank-registry/src/migrations/execution_outcome_v5.sql.apps/admin-api/tests/integration/execution_parity.rsor a shared cross-app contract fixture at the lowest reusable test owner.- Focused boundary scanner fixtures/tests if existing scripts cannot express direct execution ownership safely.
docs/execution-contract.md— canonical stage/code/retryability/certainty and Admin/MCP projection contract.
UPDATE expected
- Core:
crates/crank-core/src/{lib.rs,observability.rs,ext/protocol.rs}only as required by the new contract. - Runtime:
crates/crank-runtime/src/{lib.rs,error.rs,executor.rs,request_context.rs,model.rs}and focused tests; split rather than growexecutor.rsbeyond its current debt ceiling. - REST adapter:
crates/crank-adapter-rest/src/{error.rs,lib.rs,client.rs}only for typed dispatch evidence/normalization seam; network policy changes remain 1.9. - Admin:
apps/admin-api/src/{dto.rs,error.rs,service.rs},src/service/operations.rs,src/routes/operations.rs; integration common/lifecycle/operations tests. - UI (only if the additive Test failure fields require presentation):
apps/ui/js/{wizard-live.js,i18n.js,api.js}and the existing lifecycle/wizard Playwright specs; preserve all Story 1.7 stale/ETag behavior. - MCP:
crates/crank-community-mcp/src/{app.rs,approval_execution.rs,tool_error.rs}, invocation-history helper and integration/unit tests. Extract focused modules rather than growapp.rs. - Registry:
crates/crank-registry/src/{model.rs,postgres/observability.rs,postgres/mod.rs}, migration authority/schema guard/tests and generated.sqlx/query-*.json. - Guardrails:
scripts/check-rust-module-boundaries.shand/or Python boundary checker plus unit fixtures;justfileonly if a distinct executable gate is necessary. - Docs/evidence:
docs/{execution-contract.md,admin-api.md,mcp-interface.md,observability.md,migrations.md,data-model.md,database-schema.md,capability-inventory.json}, migration sequence schema and baseline artifacts. - Local ignored: this Story, sprint status and
_bmad-output/project-context.md; never force-add them as canonical evidence.
Must not change
- Migration v1/v2/v3/v4 source bytes/checksums or Story 1.7 immutable Operation semantics.
- Outbound allow/deny/DNS/redirect/proxy/retry implementation except the minimal typed evidence seam explicitly needed by this Story.
- Public successful Admin/MCP response semantics, protocol revision negotiation, dependency/toolchain versions or deployment topology.
Testing Requirements and Commands
RED first: prove existing classification divergence and optional-scope bypass before production edits.
cargo test -p crank-core execution -- --test-threads=1
cargo test -p crank-runtime --all-targets -- --test-threads=1
cargo test -p crank-adapter-rest --all-targets -- --test-threads=1
cargo test -p admin-api --test integration execution_parity -- --test-threads=1
cargo test -p admin-api --test integration operation_lifecycle -- --test-threads=1
cargo test -p admin-api --test integration operations_agents -- --test-threads=1
cargo test -p crank-community-mcp --all-targets -- --test-threads=1
cargo test -p mcp-server --test integration -- --test-threads=1
cargo test -p crank-registry --test integration migrations -- --test-threads=1
cargo test -p crank-registry --test integration observability -- --test-threads=1
just migration-contract-check
just sqlx-check
just config-contract-check
just metrics-contract-check
just rust-boundaries
just capability-inventory-check
python3 -m unittest discover -s tests/unit
just authenticated-product-smoke http://localhost:3000
just verify
git diff --check
python3 scripts/check-community-scope.py --root . --files <every NEW/UPDATE tracked candidate>
Required assertions:
- Admin and MCP normalized outcomes match for all frozen stages; raw wire difference is explicitly projected and snapshot-tested.
- Every pre-dispatch failure observes adapter call count
0; every accepted unary execution observes exactly1; cancellation/unknown tests record dispatch evidence deterministically without sleeps. - Request/Trace IDs match ingress, runtime, captured upstream and history and remain distinct with telemetry sampling/export disabled.
- Foreign workspace/Agent/Tool probes return one non-disclosing outcome and do not access adapter/history rows of the foreign object.
- Canary credential, URL, body, parser, SQLx and host path never appears in boundary JSON/MCP content/history message/log/span/metric/evidence.
- v4→v5 preserves all rows, fresh/replay/rollback/corrupt states are deterministic, N-1 writer/read compatibility is explicit, and no old migration bytes change.
- No skipped/flaky/retry-promoted mandatory evidence.
Previous Story Intelligence
- Story 1.7 now guarantees exact immutable Operation versions, current-Draft test resolution, ETag/CAS lifecycle and pinned Agent behavior. Reuse these facts; do not reimplement lifecycle checks inside runtime.
- Story 1.7 exposed why persisted diagnostic claims must be honest: legacy fields remain unknown rather than fabricated. Apply the same rule to new v5 classification columns.
- Story 1.5 provides canonical correlation independent of telemetry sampling; production runtime fallback ID generation is now an anti-pattern.
- Story 1.6 provides closed stage/outcome metrics and exemplars; extend typed registry only when truly necessary and never mirror the error code as an unbounded label.
- Story 1.4 requires exact-byte append-only migration authority and version-aware fingerprints. The next schema version is v5.
- Product owner deferred Reference Deployment performance qualification to Epic 8. Story 1.8 still adds deterministic local overhead/adapter-call regressions but makes no formal NFR-P4 release claim.
Git Intelligence
- Current committed baseline
7674284freezes Story 1.6. Story 1.7 implementation is present in the shared worktree and is a hard predecessor even though it has not been committed by this workflow. - Preserve the full existing Story 1.7 diff and
.agents/; do not reset, stage, commit, push, tag or deploy without explicit owner authorization. - Recent patterns to reuse: framework-free typed contracts, closed enums, version-aware MigrationAuthority, SQLx offline metadata, table-driven parity/security tests and explicit Community scan.
Latest Technical Notes
- No dependency upgrade or new external library is required. Use locked Rust 1.96.1, Axum 0.8, Tokio 1, SQLx 0.9, Reqwest 0.12 and existing internal abstractions.
- Tokio cancellation is drop-based; a future being dropped is not itself evidence whether a write reached the upstream. Preserve explicit dispatch evidence and idempotency outcome-unknown cleanup rather than inferring certainty from
JoinErroror message text. - Reqwest timeout/transport errors do not universally prove that no bytes reached the peer. Classification must depend on known pipeline/dispatch state; ambiguous mutating calls require manual reconciliation.
References
- [Source:
_bmad-output/planning-artifacts/epics.md— Epic 1, Story 1.8, dependency waves] - [Source:
_bmad-output/planning-artifacts/prds/prd-crank-2026-08-03/prd.md— FR-2; NFR-P4/R1/S1/S2/S4/S7/S8/O1/O4/O5/C1/C4] - [Source:
_bmad-output/planning-artifacts/prds/prd-crank-2026-08-03/addendum.md— Community and evidence decisions] - [Source:
_bmad-output/planning-artifacts/architecture/architecture-crank-2026-08-03/ARCHITECTURE-SPINE.md— AD-1/9/11/15/19/21/23 and conventions] - [Source:
_bmad-output/planning-artifacts/implementation-readiness-report-2026-08-08.md— FR-2 mapping and story-level NFR evidence requirement] - [Source:
_bmad-output/test-artifacts/test-design-progress.md— E1-R-007 and E1-17/E1-18/E1-19] - [Source:
_bmad-output/implementation-artifacts/1-7-immutable-lifecycle-operation.md— immutable Draft/Published/Agent handoff and owner performance decision] - [Source:
_bmad-output/project-context.md— execution, migration, redaction, testing and boundary rules]
Dev Agent Record
Agent Model Used
GPT-5.6 Codex
Debug Log References
cargo check --workspace --all-targets— pass.cargo test -p crank-core --test execution— 5/5 pass; closed 30-code taxonomy and origin invariants.cargo test -p crank-runtime --all-targets -- --test-threads=1— pass; deadline, dispatch certainty, idempotency, confirmation and adapter call-count coverage.cargo test -p crank-registry --test integration migrations -- --test-threads=1— 22/22 pass, including honest v4→v5 upgrade.cargo test -p admin-api --test integration operations_agents -- --test-threads=1— 7/7 pass.cargo test -p crank-community-mcp --all-targets -- --test-threads=1and MCP execution-stage suite — pass.python3 -m unittest -v tests.unit.test_check_execution_boundariesandscripts/check-rust-module-boundaries.sh— pass.just sqlx-check,just verify-ui,git diff --check— pass.- Playwright
operation-lifecycle.spec.js,operations.spec.js,wizard.spec.js— 14/14 pass on Chromium real stack. - Authenticated product smoke on local split-port stack — pass through create, Draft Test, publish, Agent bind/publish, MCP list/call, edit/archive and pinned MCP call.
- Explicit Community scan — pass, 129 changed/new files scanned.
- Final
just verify— pass, including tooling, inventory/baseline, scope, config/migration/metrics contracts, boundaries, code health, dependency audit, fmt, clippy and full workspace tests. - Post-review
just sqlx-check— pass; all workspace queries compile against refreshed offline metadata. - Post-review Playwright
wizard.spec.js+operation-lifecycle.spec.js— 12/12 pass on Chromium. - Post-review differential suites: Admin unit 7/7, MCP unit 12/12, Runtime all targets 63/63 and REST adapter integration 10/10 pass.
Completion Notes List
- Added a framework-free closed execution taxonomy and canonical success/failure descriptor shared by Admin and MCP.
- Replaced optional production execution context with a mandatory scoped
RuntimeExecutionRequest; fallback IDs and production convenience bypasses were removed. - Centralized all runtime/protocol error normalization, including typed dispatch evidence and distinct read-only versus mutating deadline semantics.
- Unified Admin current-Draft Test, direct MCP snapshot calls and approved MCP calls on
execute_outcome; public success contracts remain compatible and errors gained additive typed fields. - Added RU/EN UI localization for stable execution codes while preserving Story 1.7 stale-response and correlation behavior.
- Added append-only MigrationAuthority v5 and persisted exact operation version, stage, error code, retryability and certainty without fabricating legacy values.
- Added exhaustive Admin/MCP projection parity tests, redaction/call-count/deadline coverage and a fail-closed execution-boundary scanner.
- Split MCP request DTOs and migration v5/owned-relation helpers into focused modules to keep legacy files inside code-health ceilings.
- Updated execution, Admin, MCP, history, observability, data-model and migration documentation. Capability Inventory/baseline remained semantically unchanged because the existing FR-2 flows already point to the refreshed executable evidence; both validators passed.
- No dependency/toolchain upgrade, deployment-topology change, Story 1.9 outbound-policy claim, commit, push or deployment was performed.
- Adversarial review closed all 17 High/Medium findings: the envelope, mapping, dispatch certainty, idempotency, persistence, taxonomy, locale, redaction, confirmation, stale-response and executable boundary/parity contracts are now fail-closed and covered by regression tests.
File List
_bmad-output/implementation-artifacts/1-8-rest-execution-boundary-errors.md_bmad-output/implementation-artifacts/sprint-status.yamlCargo.lockapps/admin-api/Cargo.tomlapps/admin-api/src/error.rsapps/admin-api/src/service/operations.rsapps/admin-api/tests/unit/error.rsapps/admin-api/tests/unit/execution_parity.rsapps/ui/js/i18n.jsapps/ui/js/wizard-live.jscrates/crank-adapter-rest/src/lib.rscrates/crank-adapter-rest/tests/integration/client.rscrates/crank-community-mcp/src/app.rscrates/crank-community-mcp/src/app/invocation_history.rscrates/crank-community-mcp/src/app/request.rscrates/crank-community-mcp/src/approval_execution.rscrates/crank-community-mcp/src/tool_error.rscrates/crank-community-mcp/src/app/tests.rscrates/crank-community-mcp/tests/unit/tool_error.rscrates/crank-core/src/execution.rscrates/crank-core/src/ext/protocol.rscrates/crank-core/src/lib.rscrates/crank-core/src/observability.rscrates/crank-core/tests/execution.rscrates/crank-registry/src/migrations.rscrates/crank-registry/src/migrations/authority.rscrates/crank-registry/src/migrations/execution_outcome_v5.rscrates/crank-registry/src/migrations/execution_outcome_v5.sqlcrates/crank-registry/src/migrations/owned_relations.rscrates/crank-registry/src/migrations/schema_guard.rscrates/crank-registry/src/model.rscrates/crank-registry/src/postgres/mod.rscrates/crank-registry/src/postgres/observability.rscrates/crank-registry/tests/integration/agents_usage.rscrates/crank-registry/tests/integration/common.rscrates/crank-registry/tests/integration/migrations.rscrates/crank-runtime/src/auth.rscrates/crank-runtime/src/error.rscrates/crank-runtime/src/execution_failure.rscrates/crank-runtime/src/execution_request.rscrates/crank-runtime/src/executor.rscrates/crank-runtime/src/lib.rscrates/crank-runtime/src/request_context.rscrates/crank-runtime/tests/integration.rscrates/crank-runtime/tests/integration/confirmation.rscrates/crank-runtime/tests/integration/idempotency.rscrates/crank-runtime/tests/product_metrics.rscrates/crank-runtime/tests/stages.rscrates/crank-runtime/tests/support/mod.rsdocs/README.mddocs/admin-api.mddocs/data-model.mddocs/database-schema.mddocs/en/migrations.mddocs/execution-boundary.mddocs/mcp-interface.mddocs/migrations.mddocs/observability.mddocs/schemas/migration-sequence.jsonscripts/README.mdscripts/check-execution-boundaries.pyscripts/check-rust-module-boundaries.shtests/unit/test_check_execution_boundaries.py.sqlx/query-*.json(offline metadata refreshed for affected invocation-history queries in the shared Story 1.7/1.8 worktree)
Change Log
- 2026-08-14: Story 1.8 created with a complete typed execution envelope, normalized outcome/error taxonomy, Admin/MCP parity matrix, MigrationAuthority v5 evidence and strict boundary/security scope.
- 2026-08-15: Story 1.8 implemented and moved to review after full workspace, UI, PostgreSQL, migration, boundary, explicit scope and authenticated REST→MCP qualification passed.
- 2026-08-15: Adversarial code review fixed all 17 High/Medium findings; post-review workspace, SQLx, migration, boundary and targeted Chromium gates passed, and Story 1.8 moved to done.