Files
canina/backend/src/orchestration/PREPARE_CONTRACT.md
T

8.1 KiB

Bounded Stage PREPARE workflow foundation

This slice is NOT a runtime executor, deployment mechanism, or full v4 completion. It enables authenticated proposal/Gate1/queue APIs and provides internal worker/CI service methods. Default worker/CI identity allowlists are empty: no browser or production execution route exists.

Panel HTTP contract

All routes require existing JWT authentication with Admin or SUPER_ADMIN. Actor is exclusively req.user.id ?? req.user.sub, role exclusively req.user.role. Top-level unknown mutation fields return 400; client actor/profile fields are never trusted.

Base /admin/orchestration:

  • GET /tasks: task array.
  • GET /tasks/:id: task object.
  • GET /overview: existing inventory items plus capabilities {mutations:true, prepare:true, release:false, gate2Decisions:false, chat:false, runtime:false}, reason bounded_stage_prepare_only.
  • POST /tasks: existing CreateOrchestrationTaskDto {key,title,department,operationMode:"PREPARE",budgetLimitCents,metadata:{commitSha,scope,acceptanceCriteria}}; commitSha is required lowercase 40hex; scope is a non-blank string of at most 2000 characters; acceptanceCriteria is 1..20 non-blank strings of at most 500 characters each; budget is integer 20..10000 cents. Returns 201 projected task, state DRAFT/version1. Validated scope and acceptance criteria are persisted exactly and remain unchanged by workflow transitions. The internal workflowScope:"STAGE_PREPARE", environment and createdBy are server-owned; input profile/actor/other arbitrary keys are discarded. Key max120, title max255, department max50. Proposal key is unique; sequential or concurrent duplicate keys return 409, without updating the original task or appending another proposal event. Fetch/reconcile the existing task rather than retry blindly.
  • PUT /tasks/:id/transition: {toState:"GATE1_PENDING"|"READY",expectedVersion,idempotencyKey,reason?}. Only DRAFT->GATE1_PENDING and GATE1_APPROVED->READY. Owner or SUPER_ADMIN. Returns 200 projected task. READY atomically creates dispatch outbox. Requires unexpired Gate1.
  • POST /tasks/:id/gates/1/decide: existing GateDecisionDto {decision:"APPROVED"|"REJECTED",expectedVersion,idempotencyKey,expiresAt,notes?}. SUPER_ADMIN independent from proposer. Future expiry <=24h. Returns 201 projected task, not decision object.
  • Gate2 decision, budget writes/reconcile, command routes (including release), chat and kill-switch HTTP mutations remain 403. Runtime resource reads remain 503.

Task projection keeps existing scalar fields and safe nested runs/artifacts, decisions, events and ledger. Adds only metadata:{scope,acceptanceCriteria,environment:"staging",commitSha} for bounded proposals, otherwise {}. Never includes createdBy, workflowScope, payloads, URI, signatures, tokens or lease credentials. Pre-fix rows with the legacy scope sentinel remain readable/operable but have no recovered acceptance criteria: do not represent those as complete immutable scope review evidence.

availableActions:string[] is state/identity-derived: DRAFT owner -> SUBMIT_GATE1; GATE1_PENDING independent SUPER_ADMIN -> APPROVE_GATE1,REJECT_GATE1; GATE1_APPROVED owner/SUPER_ADMIN -> QUEUE_PREPARE; all worker/verification/Gate2 and legacy states -> []. Actions indicate workflow eligibility, not a guarantee: current kill switch, approval expiry and concurrent versions are rechecked transactionally on mutation. Panel must not infer actions from state or send actor identity.

Common errors: 400 invalid DTO/binding; 403 wrong scope/identity/independence/kill/budget/expiry; 409 duplicate proposal key, stale version or idempotency payload mismatch. Transition/decision replay returns current persisted task and does not duplicate side effects.

Internal service contracts (NOT browser endpoints)

PrepareWorkflowService is exported by OrchestrationModule. Trusted backend composition must override PREPARE_WORKFLOW_CONFIG with explicit workerIds and stageCiIds, default both empty. Do not populate from request bodies or user-selected runtime profiles. Worker identities require role WORKFLOW_WORKER AND ID allowlist; Stage identities require STAGE_CI AND separate ID allowlist. Credential/session provisioning and transport remain the integrating runtime owner's responsibility.

  • claim(identity, taskId?) -> null | {taskId,runId,attempt,leaseToken,leaseUntil,commitSha,environment:"staging",maxCostCents:20}. Transactional task row lock with SKIP LOCKED, immutable run binding, 30s lease, max3 attempts. Each attempt reserves a fixed hard upper bound of 20 cents, not an estimated or measured departmental cost. Unknown cost on expired attempts remains reserved conservatively.
  • heartbeat(identity,{taskId,runId,leaseToken}) -> {leaseUntil}. Same owner/token, unexpired active lease required.
  • complete(identity,{taskId,runId,leaseToken,sha256,uri,actualCents}) -> task. QA success ingestion only; lowercase sha256, HTTPS URI, actual cost integer0..20 from trusted worker. Atomically records immutable QA artifact/attestation, SUCCEEDED run, reservation reconciliation, DONE outbox and VERIFYING task. Expired/stale/foreign token cannot finish. Not replayable after success; caller must read persisted task/run after response loss.
  • stageEvidence(identity,{taskId,runId,sha256,commitSha,evidenceSha256,uri}) -> task. Independently allowlisted Stage CI identity, successful exact staging commit/run, registered QA subject, independent QA signer. Atomically records Stage artifact/attestation and reaches GATE2_PENDING. No release or Gate2 approval. Does not perform or claim deployment itself. Caller supplies actual trusted CI evidence, not browser assertions.

Verification and explicit gaps

Real isolated PostgreSQL16, no published ports/no live volumes. Added migrations applied with ON_ERROR_STOP. TDD RED logs cover missing workflow behavior, heartbeat/QA behavior and HTTP enablement. Full backend regression excluding existing legacy release-containing orchestration.integration.spec: 106 suites /851 tests including seven real-DB workflow cases, build exit0. No RELEASE_AUTHORIZE service operation executed.

DB regressions: concurrent claim winner, queue race/replay mismatch, hard budget rollback, stale lease fencing, max3 attempts, conservative expired costs, kill switch, self approval, trusted IDs, QA reconciliation and Stage evidence to Gate2 pending. Test fixture artifact URIs/hashes are not real deployment evidence.

Remaining: actual authenticated runtime worker transport/executor and pinned CI evidence transport; shared department/company budget model and locking (NOT implemented or represented by fake totals); retry backoff/dead-letter UX/cancellation; hard total execution wall-time; durable request replay of completion/evidence; kill-switch concurrent insertion/version locking; migration rehearsal with full legacy schema; real Stage CI artifact/deployment verification. No push/deploy/live DB/runtime edits. Production release remains denied at HTTP boundary; unsafe legacy core release method is deliberately untouched and must never be called by this slice.

Contract repair verification

Actual frontend inspection confirmed proposal submission sent human scope and acceptanceCriteria but omitted required commitSha. Frontend repair is separately assigned; no frontend file changed here. New proposals now require all three fields. Internal Stage restriction uses a separate server-owned workflowScope marker rather than overwriting user scope. No metadata update route exists in this bounded workflow.

TDD RED→GREEN against isolated PostgreSQL16 reproduced dropped scope/criteria, nine invalid metadata acceptances (including array-to-string commit coercion), and duplicate-key P2002 leakage. Final database suite: 24 cases, including authenticated HTTP create/list/detail persistence, 400 validation, and 409 duplicate responses. Full allowed backend regression: 106 suites / 868 tests passed; legacy orchestration.integration.spec.ts excluded to avoid executing RELEASE_AUTHORIZE. Build exit0. Scoped lint remains failing on inherited require-await/no-unnecessary-type-assertion errors (13 errors); no lint suppression or config change applied. Disposable DB only; no live edits/push/deploy.