Files
crank/_bmad-output/planning-artifacts/architecture/architecture-crank-2026-08-03/ARCHITECTURE-SPINE.md
T

450 lines
40 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
---
name: 'Crank Community Production Readiness'
type: architecture-spine
purpose: build-substrate
altitude: initiative
paradigm: 'hexagonal modular monolith with control-plane/execution-plane split'
scope: 'Production-ready Crank Community: current platform hardening, OpenAPI, modern MCP, durable Tasks, observability, load testing and release evidence'
status: final
created: '2026-08-03'
updated: '2026-08-03'
binds:
- FR-1..FR-54
sources:
- '../../prds/prd-crank-2026-08-03/prd.md'
- '../../prds/prd-crank-2026-08-03/addendum.md'
- '../../../project-context.md'
- '../../../../docs/architecture.md'
- 'https://blog.modelcontextprotocol.io/posts/2026-07-28-release-candidate/'
- 'https://modelcontextprotocol.io/seps/2663-tasks-extension'
- 'https://modelcontextprotocol.io/extensions/tasks/overview'
- 'https://www.postgresql.org/docs/16/sql-select.html'
- 'https://opentelemetry.io/docs/collector/resiliency/'
- 'https://glitchtip.com/documentation/performance/'
companions: []
---
# Architecture Spine — Crank Community Production Readiness
## Design Paradigm
Crank remains a **hexagonal modular monolith** distributed as several process-level composition roots. `admin-api` owns the control plane, `mcp-server` owns the public execution plane, and isolated workers own durable/background work. They share domain contracts and PostgreSQL, but never call each other through private HTTP APIs. Brownfield composition-support crates remain explicit: `crank-community-mcp` and `crank-community-auth` currently wire concrete adapters below the app binaries and are not reusable inner layers.
```mermaid
flowchart TB
Apps["Composition roots\napps/*"]
MCPFacade["MCP composition support\ncrank-community-mcp"]
AuthFacade["Auth composition support\ncrank-community-auth"]
UseCases["Application services\nruntime · tasks · load · import"]
Rest["REST adapter\ncrank-adapter-rest"]
Registry["PostgreSQL adapter\ncrank-registry"]
Core["Domain and ports\ncrank-core"]
Schema["Pure contracts\nschema · mapping"]
Metrics["Metric leaf\ncrank-metrics"]
Obs["Observability edge\ncrank-observability"]
InfraLeaf["Infrastructure leaves\nconfig · artifacts"]
Apps --> MCPFacade
Apps --> AuthFacade
Apps --> UseCases
Apps --> Registry
Apps --> Obs
Apps --> InfraLeaf
MCPFacade --> Registry
MCPFacade --> UseCases
MCPFacade --> Rest
MCPFacade --> Core
MCPFacade --> Metrics
AuthFacade --> Registry
AuthFacade --> Core
UseCases --> Rest
UseCases --> Core
UseCases --> Schema
UseCases --> Metrics
Registry --> Core
Registry --> Schema
Rest --> Core
Rest --> Metrics
Obs --> Metrics
```
Arrows mean “may depend on”. `crank-core`, `crank-metrics`, `crank-config` and `crank-artifacts` are leaves with the narrower dependencies defined by their manifests; `crank-observability` may depend only on `crank-metrics`. `crank-registry` never depends on runtime, REST or observability; runtime/application crates never depend on registry implementations; reusable crates never depend on `apps/*`. Existing boundary scripts are extended for every new crate and run as a mandatory CI gate.
## Invariants & Rules
### AD-1 — [ADOPTED] Hexagonal modular monolith
- **Binds:** all
- **Prevents:** microservice proliferation, cyclic dependencies and business rules in Axum/SQLx handlers.
- **Rule:** domain types and external-dependency ports live in `crank-core`; reusable use cases live in application crates; SQLx, Axum, transport and environment wiring remain adapters or composition concerns. Process apps and the explicitly named brownfield `crank-community-mcp`/`crank-community-auth` composition-support crates may wire concrete adapters; no inner or new reusable crate may do so. Internal process collaboration uses shared ports and durable state, not private service-to-service HTTP.
### AD-2 — Versioned capability model and published catalog
- **Binds:** FR-1, FR-4, FR-14..FR-18, FR-33
- **Prevents:** draft leakage, mutable published behavior and a schema-less “universal capability” blob.
- **Rule:** Operation, Resource and Prompt are separate typed aggregates with a shared `CapabilityKind`, `CapabilityRef`, lifecycle, sensitivity and publication contract. Every published version is immutable. `AgentVersion` binds exact published refs; publication atomically creates one immutable catalog snapshot and monotonically increasing `catalog_revision`. MCP reads only that snapshot.
### AD-3 — Resource and Prompt execution boundary
- **Binds:** FR-15..FR-19, FR-27, FR-32
- **Prevents:** a read capability bypassing SSRF/auth/idempotency controls or a Prompt executing arbitrary code.
- **Rule:** Resource kinds are static text/JSON/binary or REST-backed URI template. A dynamic Resource can reference only a pinned, published, read-safe `GET`/`HEAD` Operation and executes it through `RuntimeExecutor`. Prompts are parameterized system/user/assistant message templates; rendering is deterministic and side-effect free, and each dependency is an exact Published Resource Version. Before publication one validator checks dependency DAG, URI-template/root traversal, arguments, MIME/size, secret findings and effective sensitivity/access; any unresolved or secret-bearing fallback blocks publication.
### AD-4 — [ADOPTED] PostgreSQL correctness, optional Valkey acceleration
- **Binds:** FR-1..FR-45, NFR-R2, NFR-S7
- **Prevents:** split-brain state, lost accepted work and safety behavior that changes when cache is lost.
- **Rule:** PostgreSQL 16 is authoritative for configuration, published catalogs, approvals, idempotency, Tasks, Load Runs, business events and safety state. Valkey 8 may accelerate cache, rate limiting, wake-up and coordination projections only. Every Valkey structure is reconstructible from PostgreSQL; PG-only mode remains correct and any path without a safe fallback fails closed.
### AD-5 — Version-isolated MCP multi-revision adapters
- **Binds:** FR-13..FR-20, FR-21, NFR-C2
- **Prevents:** transport-era assumptions leaking into capabilities, release-candidate behavior becoming a stable promise and a protocol upgrade breaking existing clients.
- **Rule:** at feature freeze, Capability Inventory selects the official latest stable MCP revision plus its two previous supported stable revisions and records executable conformance evidence. One endpoint routes each revision into shared method services through version-specific lifecycle, header, pagination, notification and result adapters. Existing `2025-03-26` support remains until a separate evidence-backed deprecation gate. Release candidates and experimental extensions are isolated adapters and cannot be the only path for a critical Tool.
### AD-6 — Complete MCP method services
- **Binds:** FR-14..FR-20
- **Prevents:** independently implemented handlers producing incompatible auth, pagination, cancellation or error semantics.
- **Rule:** Tools, Resources, Prompts, completion, progress, cancellation, logging and change signals each have one internal service contract enforcing Agent scope before protocol serialization. Version adapters map that contract to the negotiated stable method set. Deprecated, client-role and extension features remain explicit in the executable capability inventory; no critical state relies only on notification delivery.
### AD-7 — Durable Task application boundary
- **Binds:** FR-21..FR-26, NFR-R2, NFR-R5
- **Prevents:** background futures tied to HTTP/SSE lifetime and protocol changes redefining durability.
- **Rule:** foreground parallel Executions, durable MCP Tasks and the internal dispatch queue are three different contracts. `crank-core` owns Task types and ports; `crank-tasks` owns lifecycle/use cases; `crank-registry` implements persistence; `task-worker` is the execution composition root. MCP/admin handlers only create, inspect, update, reconcile or cancel durable Tasks. Each selected protocol revision maps the internal state through its tested stable/extension adapter; clients without a compatible Task contract receive the Tool’s published synchronous fallback or explicit unsupported result.
### AD-8 — Transactional dispatch, leases and fencing
- **Binds:** FR-22..FR-25, NFR-P2, NFR-R3, NFR-R5
- **Prevents:** acknowledged-but-missing tasks, duplicate terminal commits and stale-worker writes.
- **Rule:** Task record and dispatch intent commit in one PostgreSQL transaction before acknowledgement. Workers claim bounded batches with `FOR UPDATE SKIP LOCKED`; claim/renew/update use compare-and-swap on lease owner, expiry and a monotonic fencing token. Every progress/checkpoint/result write carries the current token. Terminal transition is a single conditional update from an allowed nonterminal state. `input_required` stores a versioned schema and update fingerprint: identical replay returns the prior outcome, conflicting replay returns conflict, and TTL expiry fails without a new dispatch.
```mermaid
stateDiagram-v2
[*] --> queued
queued --> working: fenced claim
working --> input_required: durable input request
input_required --> working: validated update
working --> completed: terminal CAS
working --> failed: terminal CAS
queued --> cancelled: accepted cancel
working --> cancelled: confirmed pre-dispatch cancel
working --> outcome_unknown: ambiguous side effect
outcome_unknown --> completed: reconciliation evidence
outcome_unknown --> failed: reconciliation evidence
outcome_unknown --> working: explicit confirmed retry
input_required --> failed: input TTL expired
completed --> [*]
failed --> [*]
cancelled --> [*]
```
### AD-9 — At-least-once and side-effect honesty
- **Binds:** FR-2, FR-5, FR-21..FR-26
- **Prevents:** false exactly-once guarantees and automated duplication of external side effects.
- **Rule:** persist attempt ID and idempotency fingerprint before outbound dispatch. Delivery is at-least-once; automatic retry/recovery of a write requires a verified upstream idempotency contract. Cancellation is cooperative. Lost certainty after dispatch becomes nonterminal `outcome_unknown`, blocks ordinary retry/cancel-as-success and exits only through evidence-bearing reconciliation or an explicitly confirmed new attempt.
### AD-10 — Content-addressed artifacts and two-phase OpenAPI import
- **Binds:** FR-7..FR-12, FR-15..FR-18, FR-40, FR-43
- **Prevents:** path traversal, mutable external references, preview/commit TOCTOU and inconsistent restore.
- **Rule:** `crank-artifacts` stores bounded immutable bytes under opaque SHA-256 refs using atomic write, fsync and rename; PostgreSQL stores ownership, MIME, size, sensitivity and digest. Publication writes/verifies idempotent bytes first, then commits metadata and owning refs; unreferenced bytes are swept only after a grace period, and referenced bytes are removed only through retention-safe reference accounting. Legacy absolute `file://` refs remain read-compatible during a digest-verified migration and are not rewritten before verification. Import flows `ParsedDocument → typed NormalizedIR + complete Findings → immutable ImportPlan → transactional Apply`. Every source construct is preserved according to the support matrix or produces explicit unsupported/blocker evidence. Apply is deduplicated by plan digest/request key, executes the selected `skip`/`rename`/`new-version` policy atomically and never accepts raw credential values—only typed security metadata and optional `AuthProfileRef`.
### AD-11 — One correlation identity across every boundary
- **Binds:** FR-6, FR-22, FR-26..FR-31, FR-40, NFR-O1
- **Prevents:** unrelated browser/server/worker traces and loss of diagnosis when the external backend is down.
- **Rule:** every browser, Admin and MCP ingress has a distinct validated `request_id` and canonical W3C `TraceContext`; invalid identities are replaced, never echoed. `traceparent` is strictly parsed; `tracestate` and `baggage` have explicit size budgets and an allowlist, and user values are not forwarded by default. System propagation overrides user mappings. Invocation, Task, attempt and Load Run records persist both IDs. A worker continues the stored parent context across the durable boundary, retaining the origin trace ID; each retry is a distinct child attempt span.
### AD-12 — Durable, redacted telemetry delivery
- **Binds:** FR-27..FR-31, FR-41, NFR-O2..NFR-O5
- **Prevents:** secret leakage, assuming GlitchTip accepts raw OTLP, and silent loss during backend outages.
- **Rule:** only `crank-observability` owns redaction, W3C propagation, OTLP serialization, GlitchTip Sentry-envelope projection and an isolated per-process/per-destination disk spool. Each spool has a dedicated quota-reserved persistent volume outside PostgreSQL/artifact safety reserve, least-privilege ownership and deployment-volume encryption at rest; a record is fsynced before local acceptance, recovered before export after restart and acknowledged only after receiver success. The browser sends a scrubbed same-origin envelope to Admin API; it never owns a direct external DSN. Production generates 100% of traces, retains traces 7 days and errors at least 30 days, targets delivery ≥99.99% within 60 seconds and 100% completeness within 25 hours for an outage ≤24 hours; replay after recovery targets 5 minutes. Capacity evidence uses measured p95 serialized trace size and proves 30 hours at 100 RPS plus a 250 RPS five-minute burst, ≤5% p95 latency and ≤10% CPU overhead. Before eviction/expiry, the spool atomically records a durable local loss tombstone; the `crank-core::TelemetryLossSink` port persists it through registry with uniqueness on service, destination and spool-record ID, and the tombstone remains until acknowledgement. Production cannot pass its gate without the default tested GlitchTip path; telemetry remains fail-open for product requests after validated startup.
### AD-13 — Typed metrics and local product analytics
- **Binds:** FR-6, FR-32..FR-35, FR-39..FR-40
- **Prevents:** high-cardinality Prometheus series and inaccurate DAU derived from scrape-time state.
- **Rule:** `crank-metrics` exclusively declares names, types, labels, buckets and recording calls. Labels are closed enums and never contain user/object/request/trace/URL/error text. `crank-core` owns the versioned typed `ProductEvent` vocabulary; apps emit it and registry persists/folds it idempotently into UTC daily rollups exposed through the typed Prometheus surface. Grafana queries Prometheus; metric-to-trace navigation uses exemplars/external URLs, never a `trace_id` label. Non-loopback scrape uses a dedicated credential that is not an Admin/MCP credential. Telemetry and product-metric egress are deny-by-default and require explicit opt-in. Versioned scrape configs, rules and dashboards are release assets.
#### Application alert delivery — decision 2026-09-13
- **Provider-neutral boundary:** application producers and evaluator ingress adapters submit a versioned `NotificationMessage` to the common notification dispatcher, which calls the `NotificationSink` port. `crank-core` owns these framework-free types/port; the implementation follows existing app/library boundaries without requiring a new standalone service or crate. The message carries notification identity, logical route reference, bounded kind/severity/content, timestamps/expiry and safe correlation links; alert fingerprint and firing/resolved state are typed alert-specific fields. Apprise URLs, tags, keys, HTTP codes and payload shapes never enter the common contract or business code.
- **Adapter boundary:** `AppriseNotificationSink` is the first production implementation. Composition/configuration selects the sink and maps logical routes to provider-specific secret-backed destinations. Replacing it changes only the adapter and provider configuration, not producers, rule definitions, UI or common dispatcher policy. The port returns typed accepted/retryable/permanent/uncertain outcomes with redacted diagnostics; provider response classification stays inside the adapter. A recording/fault-injection sink proves substitutability without shipping a second provider.
- **Policy ownership:** common dispatch owns bounded admission/queue, retry/backoff/expiry, redaction and delivery accounting; adapters perform bounded delivery attempts and must not introduce independent unbounded retry. The alert evaluator owns alert grouping/silences/repeat state, translated at ingress into the canonical envelope. Queued envelopes remain provider-neutral, with versioned logical route bindings; configuration changes cannot silently reroute already queued messages to different recipients. Exactly-once delivery is not guaranteed. MCP protocol notifications remain separate from this operator-notification gateway; no generic messaging platform is added to scope.
- Apprise API is the self-hosted notification gateway, integrated over HTTP, not an embedded Python dependency. Rule evaluation remains in the Prometheus/Grafana alerting layer; Apprise delivers notifications, it does not replace SLO evaluation. The owning story pins and tests an explicit payload adapter to the selected evaluator; arbitrary raw webhook compatibility must not be assumed.
- Stateful destination configuration stays in the gateway/operator secret store; config keys, channel URLs/tokens and gateway credentials are sensitive. A configuration key is not authentication. Private network exposure plus authenticated ingress/trusted TLS proxy, fixed operator-controlled endpoint/routes, bounded redacted payloads and explicit external-egress opt-in are mandatory. No user-provided attachment URLs or runtime-selected notification targets.
- Notification dispatch is outside the synchronous product request path. Its integration contract owns stable alert fingerprints, firing/resolved state, grouping, repeat/silence policy and bounded queue/retry/expiry; ownership of these controls must be explicit in the selected evaluator/adapter, not presumed to exist in Apprise. Timeouts, partial/permanent failures and uncertain delivery remain distinguishable; no exactly-once or human-receipt guarantee. Failed delivery is locally diagnosable without recursive notification storms or changing product readiness.
- Crank owns application signals and their delivery integration. Host/VM/LXC, disk/network and infrastructure-service monitoring/remediation, including independent detection of a wholly unavailable Crank or notification stack, belongs to the infrastructure owner. Application-visible dependency failures remain diagnosable; this ownership boundary does not weaken safety/recovery or alter approved SLI exclusions.
- Delivery configuration/profile assets belong to Story 5.9; lifecycle, scope and end-to-end notification verification belong to Story 5.11. Gateway deployment is optional or replaceable by an operator-managed endpoint; no external channel is enabled automatically. Reference: [Apprise API integration contract](https://appriseit.com/api/integrations/).
### AD-14 — Isolated, bounded load runner
- **Binds:** FR-36..FR-40, NFR-P1..NFR-P4
- **Prevents:** measuring an in-process shortcut, arbitrary-target load and loss of emergency control during saturation.
- **Rule:** `load-runner` is a separate process with a replaceable k6-compatible runner contract and invokes the public MCP endpoint from an immutable Scenario version. DAU conversion requires actions/session, sessions/user/day, activity window, think time and scenario mix. Before Start, Admin signs a `LoadAuthorizationPlan` containing exact capability versions, `load-test-safe` evidence and target policy; writes additionally require sandbox endpoint, separate test Auth Profile, quota and cleanup. Production mode requires an operator flag and repeated confirmation. The runner revalidates lease and reserved control capacity before dispatch. A non-networked local operator CLI reaches a permission-restricted Unix control socket on a separate reserved control runtime; unavailable control forbids Start, and heartbeat loss or operator stop halts new dispatch immediately. In-flight work drains or cancels exactly as pinned in the Run policy; control actions audit to PostgreSQL or a local durable fallback for later replay. Non-lowerable ceilings are 1,000 RPS, 512 VU, 2 hours and 10,000,000 iterations.
### AD-15 — Shared master-key identity
- **Binds:** FR-3, FR-10, FR-15..FR-18, FR-36..FR-43
- **Prevents:** one process writing ciphertext another cannot decrypt and backups that restore metadata without secrets.
- **Rule:** every secret-using process validates the same non-secret master-key fingerprint and active epoch against PostgreSQL before readiness. Ciphertext carries key version. Rotation writes re-encrypted versions transactionally, verifies reads under the new key and records old-key revocation evidence; the key material itself never enters PostgreSQL, manifests, logs or diagnostics.
### AD-16 — Single migration authority and rollback window
- **Binds:** FR-43, NFR-R2, NFR-C1, NFR-C3
- **Prevents:** concurrent schema owners, modified migration history and destructive rollback.
- **Rule:** `crank-registry` owns the target append-only, ordered, checksummed Community sequence. A consolidation migration first verifies and imports the legacy core, MCP-session and `RegistryExtension` ledgers without modifying baseline v1/checksum; legacy ledgers remain readable during transition and extension entries gain checksums. After consolidation, a dedicated migrate command is the sole schema writer and applies each change transactionally under a PostgreSQL advisory lock; service startup only verifies compatibility. Changes follow expand/migrate/contract, and application N reads schema and Task envelopes from N and N-1 until rollback closes.
### AD-17 — One typed configuration contract
- **Binds:** FR-31, FR-41..FR-45
- **Prevents:** divergence among environment parsing, Compose, documentation and UI.
- **Rule:** leaf crate `crank-config` owns typed fields, defaults, bounds, sensitivity and cross-field validation. Apps receive validated config and compose dependencies; reusable libraries do not read environment variables. Compose examples and parameter reference are generated/checked against the schema. Unknown or unsafe production combinations fail startup; dependency health and schema/key compatibility fail readiness.
### AD-18 — [ADOPTED] Self-hosted topology and lifecycle
- **Binds:** FR-41..FR-45, NFR-R1..NFR-R4, NFR-S1..NFR-S7
- **Prevents:** mandatory cloud dependencies, unproved rolling deployment and observability outages blocking the product.
- **Rule:** the correctness set is UI, Admin API, MCP Server, Task Worker, PostgreSQL and shared artifact storage; Load Runner is isolated/on-demand and Valkey is optional for correctness. The Reference Deployment is Linux x86_64 with Crank services, PostgreSQL 16 and Valkey 8 within 4 vCPU, 8 GiB RAM, SSD ≥100 GB/3,000 IOPS/100 MB/s and 1 Gbit/s while retaining ≥30% headroom. Load generation and the optional Prometheus/Grafana/self-hosted-GlitchTip profile have separate resource/failure budgets; external compatible endpoints are allowed. Upgrade is single-instance drain/restart: stop admission/claims, checkpoint work, bound foreground drain to 30 seconds, persist telemetry and restart. Rolling multi-instance upgrade is not claimed.
### AD-19 — [ADOPTED] UI and boundary error contract
- **Binds:** FR-1..FR-45, NFR-P5, NFR-C4
- **Prevents:** a frontend rewrite, stale cross-object responses and errors without support correlation.
- **Rule:** retain Alpine.js and the existing concatenated `window.Crank*` modules. UI accesses product state only through Admin API and uses identity/revision guards on async responses. Logs, Task and Load Run screens search/copy `request_id`/`trace_id` and generate a deep link from validated operator configuration; a Telemetry Loss Record or unavailable backend suppresses any claim that the trace is present in GlitchTip. One cross-boundary E2E proves browser/API-or-MCP/runtime/upstream/local-history/deep-link correlation. Domain, persistence and wire DTOs remain distinct. Every safe boundary error has stable `error_code`, bounded localized message, `request_id` and `trace_id`; raw causes and payloads never cross the boundary.
### AD-20 — Evidence belongs to the release artifact
- **Binds:** FR-12, FR-20, FR-40, FR-46..FR-54
- **Prevents:** documentation-only gates and combining evidence from different builds or environments.
- **Rule:** Capability Inventory, OpenAPI corpus, MCP matrix, load/soak/recovery/security results and manual sign-off are immutable content-addressed raw artifacts indexed by a signed, JSON-Schema-validated Evidence Manifest. A protected offline/CI release key signs; the verifier trusts only a protected-branch `release-trust.json` containing public key IDs, validity and revocation. Reviewed rotation adds the new key before use and retains old public keys for historical verification. The manifest binds commands, owner identity, signing-key ID, RC/image/config/topology digests, checksummed Reference Workload, exact raw counts/results, the 128-active/10,000-queued background variant with recovery ≤60 seconds, 72-hour soak and 30-day burn-in. Gate evaluation is fail-closed on a missing FR/SM item, invalid/untrusted/revoked signature, invalid schema, stale required evidence (>24 hours where freshness applies), or any digest mismatch. The passed digest must equal the published RC. First enabling work updates `project-context.md` and executable Community guardrails for Resources/Prompts/Tasks/Load Runs; allow-marker bypass is forbidden.
### AD-21 — [ADOPTED] Unified outbound execution pipeline
- **Binds:** FR-2, FR-5, FR-9, FR-16, FR-21..FR-25, FR-36..FR-38, NFR-S3..NFR-S4
- **Prevents:** Admin tests, Resources, Tasks or redirects bypassing the hardened REST path.
- **Rule:** Admin test, MCP Tool, dynamic Resource and Task attempts all enter through `RuntimeExecutionRequest → crank-runtime → crank-adapter-rest`. A shared `OutboundPolicy` validates the actual resolved address at every connection and again after every allowed redirect, applies deny-before-allow host/IP policy, disables system proxy and implicit redirects by default, reserves system correlation headers, and enforces bounded request/response bytes, deadline, retries and concurrency. OpenAPI external refs use the same network policy with a narrower allowlist; Load Runner can target only Crank’s MCP endpoint.
### AD-22 — Admin identity and web security boundary
- **Binds:** FR-3, FR-41, FR-44, NFR-S1..NFR-S2
- **Prevents:** default credentials, session fixation, spoofed proxy identity and browser cross-origin mutation.
- **Rule:** `crank-community-auth` owns one-time Admin bootstrap, login throttling/backoff, account/session/CSRF state machines and constant-shape authentication errors; PostgreSQL owns revocation and audit. Non-loopback production exposure requires TLS, an explicit trusted-proxy allowlist, Secure/HttpOnly/appropriate SameSite cookies, CSRF on state changes, deny-by-default CORS, session rotation/expiry and security headers. Offline recovery requires local operator access, never bypasses master-key protection and revokes all sessions/tokens. Invalid key/schema/security configuration fails startup or readiness.
### AD-23 — Approval and execution admission gates
- **Binds:** FR-5, FR-14, FR-21..FR-26, NFR-P2, NFR-R5, NFR-S4, NFR-S7
- **Prevents:** duplicate approvals, unbounded work and sync/background semantics drifting apart.
- **Rule:** one `ExecutionAdmission` policy snapshot precedes synchronous and background execution and enforces global, per-Agent and per-Tool concurrency, bounded queues, fairness, deadline propagation and overload response with retry guidance. A queued Task pins published execution semantics at enqueue; at claim it revalidates authorization, Agent publication/archive status, credential revocation, deadline and current capacity. Invalidated work reaches a safe terminal/reconciliation state without outbound dispatch. Execution Attempt has its own lifecycle independently of Task. Approval identity is unique on workspace, Agent, Operation version and canonical input fingerprint; creation/deduplication, expiry, decision and recovery are PostgreSQL-authoritative conditional transitions. Mandatory safety-store failure is fail-closed and reflected in readiness.
### AD-24 — Consistent backup, verified restore and retention
- **Binds:** FR-6, FR-22, FR-29, FR-40, FR-43, NFR-R2..NFR-R4
- **Prevents:** restoring PostgreSQL without matching artifacts/keys and claiming recovery before the product works.
- **Rule:** a `BackupManifest` binds snapshot time, PostgreSQL WAL LSN/PITR chain, artifact checksums, config digest and an opaque reference to separately protected master-key material; key bytes are absent. Production targets RPO ≤5 minutes and RTO ≤30 minutes. Restore completes only after a real MCP call through an Operation using an encrypted Auth Profile, and rotation evidence proves re-encryption plus old-key revocation. History, Tasks, Load Runs, traces, errors and metrics have separate typed retention; archive verification precedes required deletion, while Published Version audit and signed release evidence remain immutable.
### AD-25 — Signed offline and hardened deployment artifact
- **Binds:** FR-41, FR-42, FR-44, FR-54, NFR-S5..NFR-S6
- **Prevents:** hidden cloud dependencies, mutable images and an unverified “offline” installation.
- **Rule:** Community production is installable by one documented command from a signed offline bundle containing digest-pinned images, Compose/config, SBOM, licenses and documentation. CI performs air-gapped fresh install and N-1 upgrade, default-deny egress verification, non-root/minimal-capability/read-only-filesystem checks where applicable and secret-dump tests. The release contains no unresolved Critical/High image/dependency finding; external telemetry is opt-in and never a correctness dependency.
## Consistency Conventions
| Concern | Convention |
| --- | --- |
| Rust namespaces | Domain nouns are singular modules; application actions are verbs; adapters use technology/protocol suffixes. Public module ownership follows the dependency diagram. |
| Identifiers | Typed newtypes internally, strings on wire; new request/task/execution/run IDs use UUIDv7 with validated bounded text. Existing persisted IDs are never rewritten. |
| Capability refs | `{kind, id, version}` only; draft refs cannot cross a publish boundary. Catalog cache keys include Agent ID/version and `catalog_revision`. |
| Dates and durations | UTC `timestamptz` in PostgreSQL, RFC 3339 on wire, integer milliseconds for MCP/config, seconds for Prometheus histograms. |
| Enums and JSON | Admin/internal wire enums are `snake_case`; MCP names/values follow the negotiated specification exactly. Unknown local input enum is rejected with `error_code`; JSON object ordering never carries meaning. |
| Pagination | Opaque, bounded cursor tied to owner scope and catalog/query revision; stable order is `(created_at, id)` unless the protocol defines another order. |
| Mutation | Multi-aggregate state transitions use one PostgreSQL transaction and conditional version/state predicates; no read-modify-write without CAS or a row lock. |
| Errors | Typed domain/application errors map once at HTTP/MCP boundaries to stable codes and safe messages; retryability is explicit, never inferred from text. |
| Auth scope | Every store/cache/task/idempotency key includes full workspace, Agent and authorization scope; “not found” does not reveal foreign metadata. |
| Observability | Spans and metrics use closed typed dictionaries; IDs live in traces/local records, never metric labels; payload capture is deny-by-default. |
| Events | Audit/product events use immutable name, schema version, occurred-at and idempotency key; consumers tolerate unknown additive fields. |
| Retention | Dataset-specific policy names the clock, terminal-state rules and archive/delete action; deletion cannot break Published Version audit or release evidence. |
| Configuration | Parse and validate once before serving; every duration/size field states its unit in the name; secrets use redacted wrappers; processes log only non-sensitive normalized settings. |
| Localization | New user-facing RU and EN strings land together and share the same machine `error_code`. |
| Tests | Each fixed defect adds the lowest-level regression plus an edge/contract test when the failure crossed a boundary. |
## Stack
| Name | Version |
| --- | --- |
| Rust toolchain / edition / MSRV | 1.96.1 / 2024 / 1.96 |
| Axum | 0.8 |
| Tokio | 1 |
| SQLx | 0.9 |
| Reqwest | 0.12 |
| OpenTelemetry | 0.32 |
| Sentry Rust SDK | 0.49 |
| `metrics` / Prometheus exporter | 0.24.6 / 0.18.3 |
| PostgreSQL | 16 |
| Valkey | 8 |
| Node.js | 22 |
| Alpine.js | 3.15.12 |
| Playwright | 1.61.1 |
| MCP protocol matrix | latest stable at feature freeze + N-1 + N-2; retain 2025-03-26 until deprecation gate |
Prometheus, Grafana and GlitchTip container tags are digest-pinned in the RC Evidence Manifest after feature-freeze compatibility, license and vulnerability checks; their product versions are deployment inputs rather than Rust architecture contracts.
At authoring, the brownfield MCP server supports `2025-03-26`, `2025-06-18` and `2025-11-25`. The researched `2026-07-28` stateless line and Tasks extension remain adapter candidates until their stable status is verified at feature freeze; the Evidence Manifest records the actual selected matrix.
## Structural Seed
```text
apps/ # additive target structure; existing entries are retained
admin-api/ # control plane, browser telemetry relay
mcp-server/ # versioned MCP transport composition root
task-worker/ # durable execution worker
load-runner/ # isolated MCP load generator and kill path
ui/ # existing nginx + Alpine UI
crates/
crank-core/ # framework-free domain and ports
crank-community-auth/ # existing Admin/machine identity composition support
crank-community-mcp/ # existing MCP composition support and version adapters
crank-schema/ # existing schema validation contracts
crank-mapping/ # existing deterministic input/output mappings
crank-runtime/ # synchronous Operation execution pipeline
crank-tasks/ # Task lifecycle, claims and reconciliation use cases
crank-load/ # Scenario validation and load engine contracts
crank-import/ # pure OpenAPI parsing/normalization/findings
crank-registry/ # PostgreSQL records, queries and migrations
crank-artifacts/ # bounded content-addressed local artifact store
crank-config/ # typed configuration schema and validation
crank-adapter-rest/ # outbound REST adapter and network policy
crank-metrics/ # only metric schema/recorder owner
crank-trace/ # safe span stage and attribute vocabulary
crank-observability/ # exporters, redaction and durable telemetry spool
crank-test-support/ # shared deterministic test infrastructure
deploy/community/
minimal/ # correctness set
production/ # resource limits, observability and release profile
prometheus/ # scrape, recording and alert rules
grafana/ # datasource and dashboard provisioning
backup/ # WAL/PITR, artifact and config backup/restore contracts
tests/
openapi-corpus/ # versioned specifications and expected findings
mcp-conformance/ # protocol/client capability matrix
recovery/ # crash, partition, upgrade and restore matrix
release-evidence/ # manifest schema and evidence validators
```
```mermaid
flowchart LR
Browser[Browser]
Client[MCP clients]
UI[UI / reverse proxy]
Admin[Admin API]
MCP[MCP Server]
Worker[Task Worker]
Runner[Load Runner]
Operator[Local operator CLI]
Control[Root/operator-only Unix control socket]
PG[(Crank PostgreSQL 16)]
Art[(Artifact volume)]
Valkey[(Valkey 8 optional)]
Upstream[Allowed REST upstreams]
AdminSpool[(Admin spool)]
MCPSpool[(MCP spool)]
WorkerSpool[(Worker spool)]
RunnerSpool[(Runner spool)]
Prom[Prometheus]
Grafana[Grafana]
GT[GlitchTip]
GTStore[(GlitchTip storage)]
Ops[Migration / backup CLI]
Backup[(Protected backup storage)]
KeyStore[(Separate master-key backup)]
Browser --> UI
UI -->|browser Admin API proxy| Admin
UI -->|MCP reverse-proxy route only| MCP
Client -->|MCP route| UI
Runner --> MCP
Operator --> Control
Control --> Runner
Admin --> PG
MCP --> PG
Worker --> PG
Runner --> PG
Admin --> Art
MCP --> Art
Admin -. acceleration .-> Valkey
MCP -. acceleration .-> Valkey
Worker -. wake-up .-> Valkey
Admin --> Upstream
MCP --> Upstream
Worker --> Upstream
Admin --> AdminSpool
MCP --> MCPSpool
Worker --> WorkerSpool
Runner --> RunnerSpool
AdminSpool --> GT
MCPSpool --> GT
WorkerSpool --> GT
RunnerSpool --> GT
GT --> GTStore
Prom -->|scrape| Admin
Prom -->|scrape| MCP
Prom -->|scrape| Worker
Prom -->|scrape| Runner
Grafana --> Prom
Ops --> PG
Ops --> Art
Ops --> Backup
Ops --> KeyStore
```
```mermaid
erDiagram
WORKSPACE ||--o{ OPERATION_VERSION : owns
WORKSPACE ||--o{ RESOURCE_VERSION : owns
WORKSPACE ||--o{ PROMPT_VERSION : owns
WORKSPACE ||--o{ AGENT_VERSION : owns
AGENT_VERSION ||--o{ AGENT_OPERATION_BINDING : freezes
AGENT_VERSION ||--o{ AGENT_RESOURCE_BINDING : freezes
AGENT_VERSION ||--o{ AGENT_PROMPT_BINDING : freezes
OPERATION_VERSION ||--o{ AGENT_OPERATION_BINDING : tool
RESOURCE_VERSION ||--o{ AGENT_RESOURCE_BINDING : resource
PROMPT_VERSION ||--o{ AGENT_PROMPT_BINDING : prompt
OPERATION_VERSION ||--o{ RESOURCE_VERSION : read_source
RESOURCE_VERSION ||--o{ PROMPT_DEPENDENCY : composes
PROMPT_VERSION ||--o{ PROMPT_DEPENDENCY : pins
AGENT_VERSION ||--o{ TASK : authorizes
TASK ||--o{ TASK_ATTEMPT : executes
LOAD_SCENARIO_VERSION ||--o{ LOAD_RUN : instantiates
AGENT_VERSION ||--o{ LOAD_RUN : targets
```
## Capability → Architecture Map
| Capability / Area | Lives in | Governed by |
| --- | --- | --- |
| FR-1..FR-6 — current Operations, Agents, secrets, approvals, history | `crank-core`, `crank-runtime`, `crank-registry`, Admin/MCP apps | AD-1, AD-2, AD-4, AD-9, AD-15, AD-21..AD-24, conventions |
| FR-7..FR-12 — OpenAPI | `crank-import`, `crank-artifacts`, Admin API, registry transaction | AD-10, AD-20 |
| FR-13..FR-20 — modern MCP, Tools/Resources/Prompts | `crank-community-mcp`, core capability aggregates, runtime, artifacts | AD-2, AD-3, AD-5, AD-6, AD-21 |
| FR-21..FR-26 — concurrency and Tasks | `crank-tasks`, `task-worker`, registry TaskStore, runtime | AD-7, AD-8, AD-9, AD-11, AD-21, AD-23 |
| FR-27..FR-31 — traceability and GlitchTip | UI relay, `crank-trace`, `crank-observability`, local records | AD-11, AD-12, AD-19 |
| FR-32..FR-35 — technical/business metrics | `crank-metrics`, registry product events/rollups, Prometheus/Grafana assets | AD-13 |
| FR-36..FR-40 — Load Runs | `crank-load`, `load-runner`, registry LoadStore, public MCP endpoint | AD-4, AD-14, AD-15, AD-20, AD-21 |
| FR-41..FR-45 — deployment, offline, recovery, config | `crank-config`, registry migrator, Compose/scripts/docs | AD-15..AD-18, AD-22, AD-24, AD-25 |
| FR-46..FR-54 — testing and public Release Gate | CI suites, corpus/matrices, Evidence Manifest validators | AD-20 and every bound AD |
| NFR-P/R/S/O/C | all apps plus deployment/recovery/evidence assets | AD-4, AD-8..AD-25, conventions |
## Deferred
- Exact PostgreSQL tables, indexes, partitioning and archive thresholds are fixed in feature/epic design after production-size query plans; ownership and transactional invariants are already bound here.
- Exact Task polling intervals, lease durations, batch sizes and fairness weights are configuration/performance-tuning decisions bounded by PRD SLOs and hard limits.
- Exact Grafana panel layout and alert thresholds derive from accepted recording rules and burn-rate tests; metric ownership and SLI formulas cannot change there.
- Digest-pinned Prometheus, Grafana and GlitchTip image versions are selected at feature freeze and recorded in the Evidence Manifest after license/SBOM/security verification.
- S3-compatible artifact storage, multi-instance workers/API, rolling upgrades and HA PostgreSQL are post-launch extensions; their introduction must preserve ports, fencing, publication and rollback invariants.
- Multi-workspace/RBAC/SSO, non-REST upstream adapters, arbitrary distributed load targets and loads above built-in ceilings remain outside this release.
- MCP revisions published after feature freeze enter the next compatibility cycle; they receive a new version adapter and may not modify internal capability or Task semantics.