chore(bmad): preserve planning and acceptance artifacts in Git
This commit is contained in:
1 parent
fed5b7dfb3
commit
ea3b71cb5e
93 files changed
+20696
No files matched your search
@@ -0,0 +1,68 @@
|
||||
---
|
||||
scope: Production-ready Crank Community across FR-1..FR-54
|
||||
purpose: Build substrate for architecture, features, epics, implementation, and QA
|
||||
altitude: initiative
|
||||
updated: 2026-08-03T19:30
|
||||
---
|
||||
|
||||
- (decision) Fast path selected: draft the complete architecture spine with explicit assumptions for later correction.
|
||||
- (decision) The architecture spine is the only requested deliverable; no deck, C4 package, or expanded solution-design document is required.
|
||||
- (constraint) The final PRD and its confirmed decisions bind this architecture; architecture may choose mechanisms but may not weaken FR/NFR/Release Gate outcomes.
|
||||
- (constraint) Brownfield reality is authoritative for existing boundaries: ratify established conventions rather than invent a replacement architecture.
|
||||
- (decision) Adopt a hexagonal modular monolith with explicit control-plane and execution-plane composition roots; binds all FRs and prevents microservice proliferation or inward dependencies on transport/storage frameworks.
|
||||
- (decision) Keep crank-core as framework-free domain and ports, crank-registry as PostgreSQL adapter, crank-runtime as Operation execution application layer, protocol adapters at the edge, and apps as the only composition roots; binds FR-1..FR-45 and prevents cyclic or transport-owned business logic.
|
||||
- (decision) Model Operation, Resource, and Prompt as separate versioned aggregates sharing CapabilityKind, CapabilityRef, lifecycle, sensitivity and publication contracts; AgentVersion binds exact published refs and exposes one immutable catalog revision; binds FR-1, FR-4, FR-15..FR-18 and prevents EAV blobs, draft leakage and independently drifting lifecycle rules.
|
||||
- (decision) Dynamic Resources may execute only a pinned read-safe GET/HEAD Operation through RuntimeExecutor; Prompts are pure deterministic renderers over pinned Resource versions with no code execution; binds FR-16 and FR-18 and prevents safety bypass or hidden mutable dependencies.
|
||||
- (decision) PostgreSQL 16 is the sole source of truth for configuration, published catalogs, approvals, idempotency, Tasks, Load Runs, business events and safety state; Valkey 8 is optional rebuildable acceleration only; binds FR-1..FR-45, NFR-R2 and NFR-S7 and prevents split-brain correctness or silent safety degradation.
|
||||
- (decision) Serve MCP 2026-07-28 stateless and the 2025-11-25 and 2025-06-18 session-based revisions through version-specific transport/lifecycle adapters over shared method services; binds FR-13..FR-20 and NFR-C2 and prevents protocol-version branches from leaking into capability and execution domains.
|
||||
- (decision) Normalize Tools, Resources, Prompts, completion, progress, cancellation and notifications into internal service contracts, and advertise only behavior implemented for the negotiated revision; binds FR-13..FR-20 and prevents capability overclaiming.
|
||||
- (decision) Implement durable Tasks in a new crank-tasks application crate and task-worker composition root; crank-core owns task types and TaskStore port, crank-registry implements persistence, and crank-tasks depends on RuntimeExecutor through an execution port; binds FR-21..FR-26 and prevents background work inside HTTP handlers or protocol sessions.
|
||||
- (decision) Create Task record and dispatch intent in one PostgreSQL transaction before acknowledgement; claim queue rows with FOR UPDATE SKIP LOCKED, CAS lease expiry and monotonic fencing token; every write requires the current token; binds FR-22..FR-25 and prevents lost accepted work, double terminal commit and stale-worker mutation.
|
||||
- (decision) Task delivery is at-least-once; persist attempt and idempotency fingerprint before outbound dispatch, automatically retry writes only with a verified upstream idempotency contract, and route ambiguous side effects to nonterminal outcome_unknown reconciliation; binds FR-23..FR-26 and prevents false exactly-once claims or unsafe repeats.
|
||||
- (decision) Map the same internal Task lifecycle to the official io.modelcontextprotocol/tasks extension for 2026-07-28 and to the negotiated 2025-11-25 task shape; 2025-06-18 uses published synchronous fallback or explicit unsupported; binds FR-13, FR-20..FR-23 and prevents wire evolution from redefining durable semantics.
|
||||
- (decision) Move shared immutable files into crank-artifacts: a bounded content-addressed local store keyed by SHA-256 with atomic write/fsync/rename and PostgreSQL metadata; binds FR-7..FR-12, FR-15..FR-18, FR-40, FR-43 and prevents mutable file references, traversal and inconsistent restore.
|
||||
- (decision) OpenAPI preview resolves local and allowlisted external refs into an immutable content-addressed artifact graph; import commit consumes only the preview digest in one registry transaction; binds FR-7..FR-12 and prevents SSRF/TOCTOU, partial mutation and silent remote drift.
|
||||
- (decision) Use one canonical W3C TraceContext generated or validated at browser/Admin/MCP boundaries; persist request_id and trace_id in Invocation, Task and Load Run records and continue the stored context across worker attempts; binds FR-27..FR-31 and NFR-O1 and prevents correlation forks across foreground/background paths.
|
||||
- (decision) crank-observability alone owns redaction, W3C propagation, OTLP export, GlitchTip Sentry-envelope projection and per-destination disk-backed bounded spool; browser telemetry enters through a scrubbed same-origin Admin API relay; binds FR-27..FR-31 and prevents raw OTLP assumptions for GlitchTip, direct browser exfiltration and unobserved telemetry loss.
|
||||
- (decision) Telemetry is fail-open after validated startup; each evicted or expired undelivered envelope atomically creates a PostgreSQL Telemetry Loss Record through an app-injected sink, while spool partitions and quotas stay outside PostgreSQL and artifact safety reserve; binds FR-29..FR-31 and NFR-O2 and prevents backend outage from breaking requests or silently losing evidence.
|
||||
- (decision) crank-metrics exclusively defines low-cardinality technical/business metric names, labels and buckets; exact activation/adoption uniqueness is stored as PostgreSQL events and daily rollups, then exposed only as aggregates; binds FR-32..FR-35 and prevents identifier cardinality and inaccurate DAU inference.
|
||||
- (decision) Ship Prometheus scrape/rules and provisioned Grafana dashboards as versioned deployment assets; metrics listeners use a separate credential and Grafana reads Prometheus plus read-only PostgreSQL rollups where exact business aggregates are required; binds FR-32..FR-35 and prevents dashboard drift or high-cardinality Prometheus workarounds.
|
||||
- (decision) Run load generation in a separate load-runner process using the public MCP endpoint and immutable Scenario version; PostgreSQL owns Run/lease/stop state and a reserved independent control connection enforces heartbeat, hard ceilings and kill switch; binds FR-36..FR-40 and prevents self-measurement bias, arbitrary-target load and a saturated data plane blocking emergency stop.
|
||||
- (decision) All secret-using processes validate the same master-key fingerprint/epoch from PostgreSQL at startup and readiness; ciphertext carries key version and rotation is transactional re-encryption with old-key revocation evidence; binds FR-3, FR-36..FR-43 and prevents partial-key deployments and unrecoverable restore.
|
||||
- (decision) Replace mutable baseline-only migration behavior with one checksummed append-only core sequence, expand/migrate/contract compatibility and a dedicated migrate command under transaction advisory lock; runtime processes verify compatible schema but never apply migrations; binds FR-43 and NFR-C3 and prevents concurrent schema owners, modified history and unsafe rollback.
|
||||
- (decision) Introduce a leaf crank-config crate as the canonical typed configuration schema and validator; apps compose dependencies from it, generated examples/docs derive from it, and library crates do not read environment variables; binds FR-41..FR-45 and prevents parsed/documented/Compose drift.
|
||||
- (decision) Production topology is ui, admin-api, mcp-server, task-worker, load-runner, PostgreSQL and optional Valkey, with an optional isolated observability profile containing Prometheus, Grafana and GlitchTip on its own storage; minimal profile preserves product correctness without external telemetry services; binds FR-41..FR-45 and prevents observability dependencies from entering product readiness.
|
||||
- (decision) Use single-instance drain/restart: stop admission and new claims, checkpoint/lease accepted work, bound foreground drain to 30 seconds, flush telemetry to durable spool, and require N/N-1 schema/task envelope reads during rollback window; binds FR-23, FR-31, FR-43..FR-44 and NFR-R3 and prevents rolling-update claims the Community topology cannot prove.
|
||||
- (decision) Preserve the Alpine/concatenated UI architecture; all mutations use Admin API DTOs with stable machine error_code plus request_id/trace_id, stale-response identity guards, and no direct PostgreSQL/MCP/GlitchTip access; binds FR-1..FR-45 and prevents a frontend rewrite, cross-boundary writes and correlation loss.
|
||||
- (decision) Release evidence is immutable and content-addressed: Capability Inventory, protocol/import matrices, load/recovery/security results and environment/config/image digests are indexed by one Evidence Manifest tied to the RC digest; binds FR-12, FR-20, FR-40..FR-54 and prevents documentation-only gates or evidence from another artifact.
|
||||
- (version) Verified architecture seed on 2026-08-03: Rust 1.96.1 / Edition 2024 / MSRV 1.96, Axum 0.8, Tokio 1, SQLx 0.9, Reqwest 0.12, OpenTelemetry 0.32, Sentry 0.49, metrics 0.24.6, PostgreSQL 16, Valkey 8, Node 22, Alpine 3.15.12, Playwright 1.61.1.
|
||||
- (version) Verified MCP compatibility seed: current 2026-07-28 stateless protocol plus 2025-11-25 and 2025-06-18; official Tasks extension identifier io.modelcontextprotocol/tasks is isolated behind the MCP adapter.
|
||||
- (constraint) No independent paid or cloud backend is required; all data and telemetry remain operator-owned and outbound telemetry is opt-in.
|
||||
- (constraint) Reference Deployment, SLOs, release gates and ceilings from the final PRD are binding and architecture mechanisms may strengthen but not weaken them.
|
||||
- (decision) Reconciliation amendment: MCP support is a feature-freeze matrix of latest stable plus two prior stable revisions, while current 2025-03-26 compatibility remains until an evidence-backed deprecation gate; release candidates/extensions never become the sole path for a critical Tool.
|
||||
- (decision) Reconciliation amendment: ratify crank-community-mcp and crank-community-auth as brownfield composition-support adapters that may currently depend on concrete registry/runtime adapters; the dependency diagram must show these real edges and forbid them from lower layers rather than pretending they are already inverted.
|
||||
- (decision) Add a unified OutboundPolicy and execution-pipeline invariant for Admin test, MCP Tool, dynamic Resource and Task paths: actual-address validation on every connection, redirect revalidation, system proxy disabled by default, and bounded body/response/deadline/concurrency.
|
||||
- (decision) Add a capability publication validator for Resources and Prompts covering typed static/dynamic forms, exact dependency versions, DAG/root/template validation, MIME/size limits, secret scan and effective sensitivity policy.
|
||||
- (decision) Reconciliation amendment: OpenAPI pipeline is ParsedDocument to typed NormalizedIR plus complete Findings to immutable ImportPlan to idempotent transactional Apply; every construct is preserved or explicitly unsupported/blocking and raw credentials never enter artifacts or plans.
|
||||
- (decision) Add execution admission and approval invariants: synchronous executions, durable Tasks and queue records remain distinct; global/per-Agent/per-Tool bounded fairness and deadlines precede both sync/background paths; approvals deduplicate by full scope and input fingerprint with conditional terminal transitions.
|
||||
- (decision) Reconciliation amendment: input_required updates use versioned schema plus fingerprint/CAS; identical replay returns prior transition, conflicting replay is rejected, and TTL expiry cannot dispatch a new side effect.
|
||||
- (decision) Reconciliation amendment: production telemetry defaults to 100 percent generation, 7-day trace and 30-day error retention, delivery latency at least 99.99 percent, 25-hour completeness for outage up to 24 hours, and a 30-hour measured-p95 spool at 100 RPS plus a 250 RPS five-minute burst; GlitchTip remains a mandatory tested default path.
|
||||
- (decision) Reconciliation amendment: exact business rollups are exported through the typed Prometheus surface; Grafana queries Prometheus and reaches traces through exemplars/external URLs, never trace-id labels or direct product-table coupling. Non-loopback metrics uses a dedicated credential.
|
||||
- (decision) Reconciliation amendment: LoadAuthorizationPlan contains DAU assumptions, load-test-safe evidence, sandbox/test credential/quota/cleanup for writes, production flag with repeated confirmation, dead-man and control readiness; immutable ceilings are 1000 RPS, 512 VU, two hours and ten million iterations.
|
||||
- (decision) Add consistent backup and verified restore: BackupManifest binds snapshot time, PostgreSQL WAL LSN, artifact checksums, config digest and external protected master-key reference; RPO at most five minutes and RTO at most thirty minutes end only after a real MCP call using encrypted auth.
|
||||
- (decision) Add Admin identity and web boundary: community-auth owns one-time bootstrap, login backoff, sessions and CSRF lifecycle; PostgreSQL owns revocation/audit; TLS, trusted-proxy allowlist, secure cookies, deny CORS and security headers are production prerequisites; offline recovery is local-only and revokes sessions.
|
||||
- (decision) Add signed offline deployment artifact: digest-pinned images, Compose/config, SBOM, licenses and docs; non-root/minimal privilege/read-only checks, no Critical/High vulnerabilities, deny-by-default egress, and air-gapped fresh install/upgrade are release evidence.
|
||||
- (decision) Reconciliation amendment: Reference Deployment is Linux x86_64, 4 vCPU, 8 GiB, SSD at least 100 GB/3000 IOPS/100 MB/s, 1 Gbit/s, PostgreSQL 16 and Valkey 8 with 30 percent headroom; load generation and observability have separate budgets.
|
||||
- (decision) Reconciliation amendment: migration consolidation imports and verifies legacy core, MCP and extension ledgers without modifying baseline v1/checksum; extension migrations gain checksums and the dedicated migration command becomes sole writer only after compatibility transition.
|
||||
- (decision) Reconciliation amendment: new artifact refs are opaque content-addressed refs; legacy absolute file refs remain read-compatible during a digest-verified migration and are never rewritten before verification.
|
||||
- (decision) Reconciliation amendment: Evidence Manifest is signed and schema-validated, binds commands, raw results, owner, RC digest, 72-hour soak and 30-day burn-in; gate fails closed on missing/stale/mismatched evidence and requires executable Community guardrails/project context updated without allow-marker bypass.
|
||||
- (decision) Add dataset retention policy: History, Tasks, Load Runs, traces, errors and metrics have separate typed retention; published-version audit and signed release evidence remain immutable, and archive verification precedes deletion where required.
|
||||
- (decision) Reviewer amendment: crank-core owns the versioned ProductEvent schema and TelemetryLossSink port; apps emit typed events, registry persists them, and telemetry loss deduplicates by service/destination/spool-record id.
|
||||
- (decision) Reviewer amendment: artifact publication writes and verifies immutable bytes first, then commits PostgreSQL metadata/ref ownership; unreferenced bytes are swept only after a grace period, and referenced bytes delete only through retention-safe reference counting.
|
||||
- (event) spine finalized
|
||||
- (decision) Final reviewer amendment: every telemetry spool uses a dedicated quota-reserved persistent volume outside PostgreSQL/artifact reserve, write-ahead fsync before acceptance, crash recovery before export, least-privilege ownership and encryption-at-rest inherited from the deployment volume.
|
||||
- (decision) Final reviewer amendment: load-runner exposes a non-networked local operator CLI over a permission-restricted Unix control socket on a reserved runtime/control path; stop halts new dispatch immediately and handles in-flight work by immutable Run policy with durable/local audit fallback.
|
||||
- (decision) Final reviewer amendment: Logs, Task and Load Run UI must search/copy request and trace IDs and generate configured GlitchTip deep links, while Telemetry Loss Record or backend outage suppresses any claim that the trace is externally available; one E2E proves the path.
|
||||
- (decision) Final reviewer amendment: release evidence signatures use a repository-pinned release trust policy containing public key IDs, validity and revocation; protected offline/CI private keys sign manifests, rotation is reviewed and old keys remain verifiable for historical evidence.
|
||||
- (decision) Final reviewer amendment: queued Task keeps pinned execution semantics from enqueue but claim revalidates authorization, Agent publication, key revocation, deadline and current admission capacity; invalidated work terminates without outbound dispatch.
|
||||
- (event) late reviewer findings resolved; spine re-linted with zero findings and post-fix gate verdict GO
|
||||
+449
@@ -0,0 +1,449 @@
|
||||
---
|
||||
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.
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
# Reviewer Gate — Adversarial unit compatibility
|
||||
|
||||
## Verdict
|
||||
|
||||
**GO после трёх исправлений.** Построены пары независимо реализуемых units; найденные shared-data/ownership holes закрыты в AD-10, AD-12 и AD-13.
|
||||
|
||||
## Critical / High
|
||||
|
||||
Нет открытых Critical/High findings.
|
||||
|
||||
## Constructed incompatible pairs and disposition
|
||||
|
||||
### Admin capability publisher vs artifact store
|
||||
|
||||
До исправления обе стороны могли соблюдать AD-10, но выбрать противоположный порядок записи bytes/metadata и оставить dangling refs после crash.
|
||||
|
||||
**Исправлено:** bytes пишутся и проверяются идемпотентно первыми; metadata/owner refs коммитятся после; orphan sweep имеет grace period, delete учитывает durable refs/retention.
|
||||
|
||||
### Admin/MCP product event producers vs registry rollup
|
||||
|
||||
До исправления разные apps могли придумать одинаково допустимые, но несовместимые event names/payload versions.
|
||||
|
||||
**Исправлено:** `crank-core` является единственным владельцем versioned `ProductEvent` vocabulary; apps только эмитят typed events, registry сохраняет и сворачивает.
|
||||
|
||||
### Per-process telemetry spool vs PostgreSQL incident sink
|
||||
|
||||
До исправления каждый app мог выбрать свой deduplication key и создать дубли или потерять loss record при недоступной БД.
|
||||
|
||||
**Исправлено:** `crank-core::TelemetryLossSink`; durable local tombstone живёт до acknowledgement, registry uniqueness использует service + destination + spool-record ID.
|
||||
|
||||
## Pairs checked without findings
|
||||
|
||||
- Capability publishers vs MCP catalog reader: exact Published refs, typed binding tables and atomic catalog revision converge.
|
||||
- MCP version adapters vs Task engine: protocol state cannot alter internal Task semantics; unsupported clients use published fallback/error.
|
||||
- Sync runtime vs Task worker: both pass the same admission policy and unified runtime pipeline; Execution Attempt remains separate from Task.
|
||||
- Admin approval writer vs worker recovery: full-scope uniqueness and conditional PostgreSQL transitions prevent competing records.
|
||||
- Load control vs saturated runner: signed plan, reserved control capacity, heartbeat and local kill path converge on one stop authority.
|
||||
- Migrator N vs service N-1: ledger consolidation plus expand/migrate/contract and N/N-1 read window define compatible ownership.
|
||||
|
||||
## Medium / Low tail
|
||||
|
||||
- Canonical serialization/signature details for `LoadAuthorizationPlan` and Evidence Manifest belong in their feature specs; both must include schema version, digest and key identity to satisfy the existing signed-contract Rules.
|
||||
- Concrete Task fairness algorithm can differ internally only if it meets one policy snapshot and PRD SLO evidence; cross-unit surface is already fixed.
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
# Reviewer Gate — Technology and reality check
|
||||
|
||||
## Verdict
|
||||
|
||||
**GO.** Все binding technology claims либо подтверждены текущим репозиторием, либо проверены по первичным официальным источникам; изменяемые внешние версии не превращены в постоянный архитектурный контракт.
|
||||
|
||||
## Critical / High
|
||||
|
||||
Нет открытых Critical/High findings.
|
||||
|
||||
## Verified against repository
|
||||
|
||||
- Rust 1.96.1, Edition 2024/MSRV 1.96 и версии Axum/Tokio/SQLx/Reqwest/OpenTelemetry/Sentry/metrics подтверждены root `Cargo.toml` и project context.
|
||||
- PostgreSQL 16, Valkey 8, Node 22, Alpine.js 3.15.12 и Playwright 1.61.1 подтверждены deployment/UI manifests и project context.
|
||||
- Текущий MCP server действительно принимает `2025-03-26`, `2025-06-18`, `2025-11-25`; это отражено без преждевременного удаления старой ревизии.
|
||||
- Реальные module/dependency constraints подтверждены обоими boundary scripts и manifests; архитектура больше не разрешает `registry -> observability`.
|
||||
- Legacy core/MCP/extension migration ledgers и absolute `file://` refs учтены переходными правилами.
|
||||
|
||||
## Verified against official primary sources
|
||||
|
||||
- PostgreSQL 16 документирует `FOR UPDATE SKIP LOCKED` как подходящий механизм для queue-like consumers и transaction advisory locks для application-defined serialization.
|
||||
- MCP official material подтверждает stateless `2026-07-28` direction и `io.modelcontextprotocol/tasks`; spine корректно считает их candidate inputs до stable verification at feature freeze.
|
||||
- GlitchTip официально принимает performance transactions/spans через Sentry-compatible envelopes и не является raw OTLP receiver; AD-12 использует отдельную projection.
|
||||
- Prometheus pull model, low-cardinality instrumentation и Grafana exemplar/external-link flow согласуются с выбранным topology.
|
||||
|
||||
## Medium / Low tail
|
||||
|
||||
- Stable MCP matrix и container image versions обязательно перепроверяются в день feature freeze; это уже fail-closed input Evidence Manifest.
|
||||
- k6-compatible обозначает сменный runner contract, а не непроверенную обязательную библиотеку; конкретный engine требует benchmark/evidence до реализации.
|
||||
- Custom 30-hour spool является собственным компонентом Crank и требует fault/capacity tests; наличие OpenTelemetry Collector persistent queue не считается доказательством этого контракта.
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
# Reviewer Gate — Good-Spine Rubric
|
||||
|
||||
## Verdict
|
||||
|
||||
**PASS WITH FIXES.** The spine is unusually complete for initiative altitude: the paradigm is named, brownfield boundaries are mostly ratified, all FR/NFR areas are mapped, AD rules are generally enforceable, and Deferred does not hide a major architectural choice. The fixes below remove three real cross-unit divergences before finalization.
|
||||
|
||||
Lint evidence: `lint_spine.py` passed with zero mechanical findings.
|
||||
|
||||
## Critical
|
||||
|
||||
None.
|
||||
|
||||
## High
|
||||
|
||||
### H-1 — Durable telemetry has no bound persistence envelope
|
||||
|
||||
- **Touches:** AD-12, AD-18, AD-25, topology; FR-31 / NFR-O2a.
|
||||
- **Problem:** AD-12 mandates a per-process durable disk spool, while AD-25 permits read-only container filesystems and AD-18 gives the correctness set a shared 100 GB disk/headroom envelope. The topology shows logical spools but does not bind persistent mounts, quota reservation, crash-consistent acknowledgement, permissions/encryption, or separation from PostgreSQL/artifact safety reserve. Independent app implementations can therefore be “durable” in incompatible ways, and an ephemeral/container-local spool would violate restart completeness.
|
||||
- **Disposition:** **Autofix.** Bind either dedicated quota-reserved persistent volumes per process or one explicitly owned local collector/WAL boundary; state write-before-accept/recovery semantics, filesystem compatibility, and that the measured 30-hour budget is outside PostgreSQL/artifact reserve.
|
||||
|
||||
### H-2 — Emergency Load Run stop is not independently reachable
|
||||
|
||||
- **Touches:** AD-14, AD-19, deployment topology; FR-38..FR-39.
|
||||
- **Problem:** AD-14 requires an independent local kill path and reserved control capacity, but AD-19 routes UI product state only through Admin API and the topology exposes no operator endpoint/CLI/signal path to `load-runner`. Builders can choose incompatible stop mechanisms, including one that fails exactly when Admin/worker pools saturate.
|
||||
- **Disposition:** **Autofix.** Bind the independent operator surface and trust boundary (for example, local CLI/Unix socket or authenticated runner control listener), its authorization/audit behavior, and stop semantics for new versus in-flight work; show it in topology.
|
||||
|
||||
### H-3 — UI ↔ GlitchTip trace navigation is mapped but not invariant
|
||||
|
||||
- **Touches:** AD-11..AD-13, AD-19; FR-27..FR-30, especially FR-28.
|
||||
- **Problem:** IDs are persisted and boundary errors carry them, but no AD requires Logs/Task/Load Run UI to search/copy a local Trace ID, generate a configured deep link, or suppress a false “available in GlitchTip” claim when a Telemetry Loss Record exists. The capability map is not an enforceable rule, so UI and backend units can satisfy their local contracts while the user's principal diagnosis path remains broken.
|
||||
- **Disposition:** **Autofix.** Add this end-to-end navigation contract to AD-11 or AD-19, including backend-unavailable/loss-record behavior and the required cross-boundary E2E evidence.
|
||||
|
||||
## Medium
|
||||
|
||||
### M-1 — Admission policy timing for queued Tasks is ambiguous
|
||||
|
||||
AD-23 does not say whether the persisted `ExecutionAdmission` snapshot is authoritative at enqueue, revalidated at claim, or both. Bind which changes (revocation, capability archive, limits, deadlines) invalidate queued work. **Disposition: discuss/autofix.**
|
||||
|
||||
### M-2 — Topology contradicts the UI boundary
|
||||
|
||||
The topology includes `UI --> MCP`, while AD-19 says UI accesses product state only through Admin API. Clarify whether this is merely reverse-proxy routing for external MCP clients or remove the edge. **Disposition: autofix.**
|
||||
|
||||
### M-3 — Evidence signatures lack a trust-root owner
|
||||
|
||||
AD-20 binds signatures and fail-closed verification but not who owns the signing key, how the verifier obtains/trusts it, or how rotation/revocation is represented. Two CI/release units could produce mutually unverifiable manifests. **Disposition: autofix in AD-20/AD-25.**
|
||||
|
||||
## Low
|
||||
|
||||
### L-1 — Current-technology evidence should be normalized
|
||||
|
||||
The MCP Tasks source path in frontmatter is not the canonical extension host, and the 2026-07-28 line is still treated as an RC candidate at authoring. Preserve the safe feature-freeze gate, but record canonical official URLs/status and the verified-at date in the evidence/memlog. **Disposition: autofix metadata.**
|
||||
|
||||
## Checklist Summary
|
||||
|
||||
- Real divergence points: **pass with H-1..H-3 fixes**.
|
||||
- Enforceability of ADs: **pass**, except the three contracts above and M-1.
|
||||
- Deferred safety: **pass**; deferred tuning and later HA/adapters are bounded by existing invariants.
|
||||
- Brownfield fit: **pass**; existing crate boundaries, MCP revisions, UI model and migration ledgers are acknowledged rather than erased.
|
||||
- PRD coverage: **broadly pass**; FR-1..FR-54 and NFR families are mapped, with FR-28 requiring an actual invariant.
|
||||
- Initiative operational dimensions: **pass** for deployment, offline operation, security, migrations, backup/restore, upgrade, observability, capacity and release evidence, subject to the physical spool and kill-path fixes.
|
||||
|
||||
## Finalizer resolution
|
||||
|
||||
Все findings применены до handoff:
|
||||
|
||||
- **H-1:** AD-12 теперь фиксирует отдельные persistent quota-reserved volumes, write-ahead fsync/recovery/ack, permissions/encryption и изоляцию safety reserve.
|
||||
- **H-2:** AD-14 и topology фиксируют local operator CLI → permission-restricted Unix socket → reserved runner control runtime, audit и stop semantics.
|
||||
- **H-3:** AD-19 фиксирует search/copy/deep-link/loss-record behavior и обязательный cross-boundary E2E.
|
||||
- **M-1:** AD-23 разделяет pinned enqueue semantics и claim-time authorization/publication/revocation/deadline/capacity revalidation.
|
||||
- **M-2:** topology маркирует UI→MCP только как reverse-proxy route для MCP client, browser state идёт в Admin API.
|
||||
- **M-3:** AD-20 фиксирует repository-pinned `release-trust.json`, protected private keys и rotation/revocation semantics.
|
||||
- **L-1:** frontmatter содержит canonical Tasks extension URL; RC status остаётся non-binding до feature-freeze verification.
|
||||
|
||||
**Post-fix verdict: GO.**
|
||||
Reference in new issue
Block a user