Repository crash recovery implementation handoff
Dated: 10 October 2026, Europe/Warsaw. Implementation baseline: 7c16313e34647fd9cae49f5d297bc64e69181df3. Owning work: #1009. This is an implementation derivation of ADR-032, not a competing target, shipped claim or live board. ADR-032 is normative; unchanged ADR-030 clauses remain controlling. Stop on any contradiction rather than choosing another protocol.
This handoff authorizes no implementation in the present documentation task. Future implementation must use the fixed contract, existing owners and ordinary provider-free regression/security checks. No inference, evals, real reboot or host provisioning is authorized. This contract revision closes no implementation milestone or epic.
Observable result and boundaries
A NEW v4 original-producer admission can recover its authentic already-completed bounded work after backend loss, including a rollback followed by normal authentication touch or same-session bearer refresh. Recovery reuses the original Root, Task/Attempt, producer, accounting group, fences and cutoffs. It cannot dispatch missing commands, replay ambiguous effects, mint a new lease, renew approval/budget/deadline or rebind a new login. Existing public recovery remains fail-closed 503 until the complete authenticated API/UI and same-database managed kill/restart acceptance is proved.
Historical v1/v2/v3 registrations and artifacts remain historical. Never rewrite an inventory, retro-register a producer, reconstruct an immutable commitment from current rows or reinterpret old mixed audit digests. Existing unsupported debt remains visibly held; it does not become success or free capacity.
Existing owners and the bounded edit map
| Owner/path | Existing symbols and intended extension |
|---|---|
backend/src/workflows/repo_repair_source.py | read_repository_inventory (490), repository_checkpoint_inventory (562), prepare_repository_original_admission (3816): NEW server-selected v4, same exact v3 vector/49 identities at three iterations; version readers reject mixed/unknown sets. _repository_startup_mutation_fence (34), _repository_startup_protected_lineage (53): classify authentic existing v3 AND new v4 before accounting/stale mutation; do not downgrade v3 debt protection. _validate_repository_unknown_root_projection (326): retain exact predecessor/current proof. stage_repository_completion_appends (649), repository_completion_append_metadata (709), _append_repository_record (758): retain original append constructors/metadata and the reserved cleanup/readback IDs. |
backend/src/workflows/repo_repair_stop.py | _static (131), _context (149), _validate_repository_stop_context_rows_sql (347): separately version v4 Stop/auth projection, preserve original Stop publication sequencing, exact current row CAS and cleanup-only authority. |
backend/src/workflows/repo_repair_source_recovery.py | read_registered_repository_producer (133), issue_repository_source_producer (1143), _load_recovery_original (1110), stage_original_repository_completion_publication (1779), _original_repository_completion_publication (1791): typed v4/v2 dispatch, one immutable retry commitment and fresh full writer checks. _read_original_cleanup_envelope_if_present (1489), _verify_repository_knownpost_root (346), stage_repository_knownpost_completion (1619): strict versioned artifact readers, historical deny/no repair, exact committed-Unknown proof. _repository_original_accounting_rows (1551): retain complete canonical membership/status/cost validation. |
backend/src/execution/repo_original_producer.py | run_original_producer (514), verify_completion (793), child_main (861), stage_original_producer_completion (367): registration/completion v2 and the distinct post-material-fsync durability.json signer proof exactly as ADR-032 specifies. Do not broaden the ordinary executor's transport predicate. |
backend/src/auth/service.py; backend/src/db/models.py | create_session (210), authenticate_session (552), _touch_session (604), OperatorSession (3084): consume existing exact-session auth, do not change login/refresh ownership semantics. WorkflowRunState (1819): freeze declared field inventory; no generic ORM-field exclusion heuristic. |
backend/src/api/workflows.py; frontend/src/components/cockpit/RepoRepairInspector.tsx | Existing Source recovery adapter around backend 8422 and typed recovery projection/parser/UI around frontend 395/471/1308. Preserve 503/read-only held projections until complete proof; never make a metadata parser a recovery grant. |
Line numbers refer to the pinned baseline and must be refreshed after a predecessor changes it. No new queue, authority ledger, inventory identity or generic recovery graph belongs in this batch. Small pure typed projection helpers may live inside these owners; do not introduce an alternative service.
Frozen cleanup artifact and immutable retry commitment
NEW v4 cleanup artifact has schema repository.original_cleanup_artifact.v2 and EXACT outer keys: schema, physical_projection, source_completion_cas, source_append_metadata, recovery_commitment. Preserve the existing exact physical projection and eight-key CAS (before_revision, post_revision, iteration_id, producer_registration_digest, producer_completion_digest, stop_digest, unknown_projection_digest, rows_digest). Preserve cleanup-then-readback append metadata and its original constructor timestamps. rows_digest retains repository.source_completion_rows.v1: ordered FIRST staging full context JSON, proposal/approval and reservation audit. No timestamp deletion/normalization or reinterpretation of that historical audit is permitted.
The closed recovery_commitment contains ONLY:
| Field | Fixed meaning/type |
|---|---|
schema, domain | Literal repository.recovery_commitment.v1, repository.source_recovery_immutable.v1 |
root_key, before_revision | Strict string WorkflowRunState table plus colon plus stringified existing Stop _key(root), not run_identity; strict nonnegative original preappend revision equal to original CAS.before_revision |
root_static_digest, root_updated_at | Lowercase 64-hex digest of the exact Root projection below; exact original model-JSON timestamp, without normalization |
journal_prefix_count, journal_prefix_digest | Strict nonnegative count within existing 50-record limit; digest of the complete ordered original preappend journal wrappers, payloads, state digests, safe flags and constructor metadata |
owner_identity | Closed object EXACT id, principal_id, created_at, absolute_expires_at; actual original owner IDs and exact model-JSON timestamps |
non_root_static | Exact ordered ten-entry vector {slot,table,key,digest} described below; no subset/superset/duplicate/foreign slot |
producer_registration_digest, producer_completion_digest, stop_digest, unknown_projection_digest | Exact original producer/Stop/Unknown links; producer hashes lowercase 64-hex; Stop/Unknown null iff the original CAS link is null, otherwise exact lowercase 64-hex |
All objects forbid extras and coercions. Owner IDs are strict strings; owner timestamps and root_updated_at are exact stored model-JSON strings, never normalized. Non-Root keys are stringified existing Stop _key(actual row) values; fixed slots determine the expected table/key. Apply existing 16-KiB record and 1-MiB private artifact bounds; overflow denies, never truncates. Construct this object ONCE at the FIRST private Source staging of authentic v4 completion, before cleanup/readback appends. Bind it through the existing immutable private artifact digest and literal readback. Caller JSON, a rehashed current row or copied witness cannot supply it.
Root and each non-Root static digest are SHA256 over repository.stop_static.v2, one NUL byte and the existing sorted-key compact UTF-8 canonical JSON bytes of the explicit projection. The prefix digest is SHA256 over repository.source_recovery_journal.v1, one NUL byte and canonical JSON of the exact full ordered preappend wrapper array; journal_prefix_count must equal that complete original array length, not a caller-chosen prefix. Any derived in-memory commitment digest is SHA256 over repository.source_recovery_immutable.v1, one NUL byte and canonical JSON of the closed recovery_commitment object. Do not add a stored digest field: the existing whole immutable artifact SHA/readback binds the object, and the derived digest cannot replace that proof.
Root static contains EVERY declared baseline WorkflowRunState field except ONLY updated_at, revision, checkpoint_receipts_json, heartbeat_at. Bind the excluded journal and revision independently above; bind updated_at independently as root_updated_at so the existing committed-Unknown timestamp protection remains exact. Unknown's existing seven-field predecessor reconstruction is a separate narrowly permitted proof, never a general omission from Root static.
The exact frozen Root field inventory is: id, run_identity, root_run_identity, parent_run_identity, workflow_name, tool_name, session_id, conversation_id, operator_session_id, status, branch_kind, branch_depth, run_fingerprint, arguments_json, approval_context_json, checkpoint_context_json, artifact_paths_json, continued_error_steps_json, last_completed_step_id, error, heartbeat_at, started_at, updated_at, finished_at, metadata_json, record_schema_version, parent_job_id, parent_fencing_token, job_kind, owner_kind, owner_principal_id, service_id, goal_id, goal_revision, plan_revision, candidate_id, source_task_id, selected_context_reserved_bytes, capability_version, input_digest, authority_digest, budget_digest, idempotency_scope, idempotency_key, idempotency_binding, priority, dependencies_json, resource_claims_json, declared_authority_json, deadline_at, lease_owner, lease_expires_at, fencing_token, revision, attempt_count, max_attempts, failure_reason, checkpoint_receipts_json, artifact_receipts_json, effect_receipts_json, github_read_revision_json, github_read_observation_history_json, github_capacity_closure_json, result_digest, result_summary. Unknown/new declared fields fail closed pending a reviewed contract update.
The proposed fixed eleven context rows are Root plus these ten ordered slots: original_parent (WorkflowRunState), native_invocation (WorkflowRunState), parent_task (WorkBoardTask), parent_attempt (WorkBoardAttempt), parent_input (WorkBoardInputArtifact), goal (Goal), operator_session (OperatorSession), repository_task (WorkBoardTask), repository_attempt (WorkBoardAttempt), repository_input (WorkBoardInputArtifact). Baseline Running _repository_precontact at source.py:1027 actually stages ten rows and omits original C1 parent_input; Stop/Unknown discovery at source.py:1400 stages eleven. Implementation MUST fetch/verify/stage the missing original C1 WorkBoardInputArtifact through the original parent Task and manifest, and unify the fixed eleven slots before commitment construction. Hash by fixed slot order, never incidental context-list order. Keys come from actual canonical rows, never caller selection. The operator-session entry hashes only closed owner_identity; the other nine entries use existing Stop static projection: exclude updated_at for all; original parent additionally excludes revision/checkpoint_receipts_json; native invocation additionally excludes revision/status/failure_reason/heartbeat_at; no other omissions. Freeze their baseline model field sets as well and reject extras. v4 Stop intent uses repository.stop_intent.v2 and snapshot repository.stop_snapshot.v2, with exact existing keys except schema; per-static hash domain is repository.stop_static.v2 plus NUL and canonical projection. The auth projection is immutable owner_identity only. Historical v1 Stop bytes/hashes are never reinterpreted.
The commitment anchors the ACTUAL first-stage Root: Running OR Unknown. Running rollback retry must match its original actual Root/static commitment, exact journal prefix and before revision. An orphan Running commitment cannot be reused after Running→Unknown: this is an epoch change and stays held, without recapture or replacement of the immutable commitment.
For v4, Unknown uses repository.stop_uncertainty_successor.v2 with the exact existing twelve keys and seven-field P/Q projections, retaining checkpoint ID repository:stop-uncertainty-successor:v1. Predecessor, successor and reconstructed-current Root hashes use repository.stop_static.v2 plus NUL and canonical explicit Root projection. Whole Stop and whole Unknown object digests remain the existing unframed canonical SHA256. Every producer, validator, parser and knownpost helper dispatches these domains from the sealed inventory; never mix a v4 framed static hash with a historical unframed static hash.
P reconstructs the earlier Running Root ONLY for the separate original Stop proof. An actual-Unknown first-stage commitment binds Q, not P. For committed Unknown, strip EXACTLY the final cleanup/readback wrappers and decrement revision ONCE to recover the actual preappend Unknown Q Root and exact original journal prefix. Preserve all seven Unknown fields and updated_at, then compare this Q projection to the actual-Unknown commitment. Separately validate the earlier Stop/P/Q transition. Only this exact committed-Unknown post-R+1 proof permits the particular committed successor; no R+2/R+3, extra suffix, prefix rewrite, timestamp repair or database-only artifact rewrite is permitted.
Frozen producer proof and timing
NEW v4 uses transport original_producer_durable_v2, registration repository.original_producer.v2 with the existing 31-key grammar and completion repository.original_producer_completion.v2 with the existing 11-key body and {completion,signature} envelope. Completion signature domain is seraph.repository.original_producer_completion.v2 plus NUL and canonical body bytes. Preserve v1 literal domains/readers for historical evidence only.
The admission-predeclared durability.json envelope is exactly {durability,signature}, at most16,384 UTF-8 bytes; signature is canonical base64 of64 Ed25519 bytes. Its body has exactly12 fields: schema=repository.original_producer_durability.v1, completion_sha256 (exact canonical completion-envelope bytes), registration_digest, admission_digest, ready_digest (lowercase64hex), boot_id (original nonempty string≤128), nonce (original lowercase64hex), observed_after_fsync_monotonic and deadline_monotonic (finite positive JSON numbers, never bool), observed_after_fsync_wall (canonical UTC ISO), execution_wall_cutoff and original_deadline_at (exact registered strings). Signature domain is seraph.repository.original_producer_durability.v1 plus NUL and canonical durability body bytes; verify with the authentic original registration key, never caller key.
Sample/sign only after ALL material outputs, completion.json and necessary containing-directory fsyncs return successfully. The signed observation must be before both original clock cutoffs, including both registered wall bounds. Check both original cutoffs before EACH proof write/link/fsync; initiate none after expiry. One already admitted blocking syscall may return late; then perform no remaining proof operations, close descriptors and stop. A complete proof made visible/durable by that in-flight operation remains historical evidence, subject to current expired-Stop/negative-cleanup gates. Missing/incomplete proof stays held; late observation denies. Never create a fresh admin/cleanup window or retry/export missing proof. Retain the existing one-second serialization reserve as an opportunity inside original bounds, not a hard fsync-duration guarantee. Slow syscalls keep physical guard/capacity held until actual closure. Never repurpose the separate five-second boot-cleanup budget.
Fresh authorization is always separate
Every retry reauthenticates the exact original active session and checks current bearer validity, idle and absolute expiry, revocation, tombstone and replacement state. In-place real refresh may rotate token_hash and activity timestamps but preserves the original session/principal/absolute expiry. A new login, including one sharing a data-continuity identity, never rebinds execution. authenticate_websocket_session replacement-following is forbidden here.
Stage complete CURRENT context rows, proposal/approval, original group and complete reservation vector; then compare those full bytes exactly to fresh IMMEDIATE-writer rows under the same Source/configuration fence. Auth changes between staging and CAS cause bounded restaging/denial, not a weakened SQL predicate. Keep Goal/native mapping, artifact TTL, source/profile/runtime, original budget/cutoff, held/Unknown liability, reservation membership/status/cost and fence checks. Immutable historical proof never substitutes for fresh permission. Recovery does not refresh or renew these limits.
Numbered implementation order
- Read ADR-032 and unchanged ADR-030. Record exact baseline, existing test failures and method/version inventory; do not fix unrelated failures or weaken checks.
- Add strict pure version readers/projections and regression negatives first. Readers understand historical versions under historical predicates, while new recovery authority requires authentic v4/v2 evidence. No backfill or automatic upgrade.
- Extend only NEW original-producer admission to server-seal v4 with the SAME identity vector/count as v3. Freeze registration/completion v2 and
durability.jsonsigning/fsync sequence exactly from ADR-032 before dispatch; preserve original handshake, no key export and no missing-command replay. - Extend original producer verifier/private physical staging to require the normative durable proof. A valid completion signature alone cannot assert that a later fsync happened. Keep fixed filenames, descriptor identity, bounds, guard closure, trusted boot/host and original cutoffs.
- Add the missing original C1 input-artifact row to Running staging and unify fixed eleven-slot order. Implement new Stop/static owner projection and immutable cleanup commitment construction. Stage physical artifacts outside SQL; reuse actual original append metadata. Persist/read back the private v2 artifact without replacement before SQL publication.
- Verify Running now stages the missing original C1 parent input artifact in the same fixed eleven-slot vector as Stop/Unknown. Update all sealed-version producer/parser/Stop/static/Unknown/knownpost domain seams together:
read_registered_repository_producer, producer completion staging/verifier,_static,_stop_static_rows_match,_validate_repository_unknown_root_projection,_repository_unknown_root_projection,_repository_discovery_metadata,_verify_repository_knownpost_rootand the cleanup artifact readers. Extend Running and Unknown retry validators with exact actual-first-stage immutable commitment/journal checks, fresh exact original-session authorization and existing full staged-to-writer/proposal/approval/reservation equality. Retain committed-Unknown post-R+1/updated_at proof by reconstructing preappend Q, not earlier P. Deny orphan Running→Unknown epoch change without recapture; identical same-epoch successors dedupe, different successors roll back. - Preserve existing authentic v3 and extend startup classification for exact v4 Root/native invocation/original parent before accounting recovery or stale mutation. Protect only the proven bounded lineage, never siblings or every Goal job. Malformed/unsupported evidence retains debt and blocks new authority.
- Run the provider-free isolated tests and actual local physical/readback journeys below; independently review cumulative changes. Keep public recovery 503 through failed or missing acceptance.
- Execute separately authorized managed same-database kill/restart acceptance, then typed authenticated API/UI and accounting/physical release readback. Enable public actions only after every gate passes; describe unresolved held debt honestly. Update owning shipped/partial docs only to the verified final behavior.
Validation plan — all commands NOT_RUN here
Use the existing autouse forbid_external_inference fixture in backend/tests/test_general_task_planner.py:39: it denies AF_INET/AF_INET6 connect/connect_ex before contact and removes provider keys. Import it into every new backend fixture family and retain real local SQLite/artifact/process mechanics. Key blanking alone is not a network guard. No existing complete managed-restart/child-denial harness was verified. Its PLANNED owner is backend/tests/test_repo_source_managed_restart.py with cases test_managed_child_egress_denial_precedes_job, test_managed_running_auth_refresh_same_receipt, test_managed_unknown_auth_refresh_same_receipt and parameterized test_managed_original_producer_crash_cutpoints. This module must enforce precontact denial before application imports in every child backend/producer process. The existing fixture blanket-denies all TCP; the harness must permit ONLY its explicit fixture-owned loopback control socket tuples at the exact managed backend address/port, with no broad loopback exemption. No ambient, non-loopback, provider or local-model socket may connect. Verify denial in every process before launching any job; outside that exact control allowance reuse the fixture denial behavior. If a child can contact a provider or local model, stop; do not rely on inherited monkeypatches.
The primary checkout interpreter exists; this worktree has no backend .venv. From this worktree's backend/, use the existing /Users/bigcube/Desktop/repos/seraph/backend/.venv/bin/python; no dependency installation is part of this handoff.
TMPDIR=/private/tmp OPENROUTER_API_KEY= OPENAI_API_KEY= /Users/bigcube/Desktop/repos/seraph/backend/.venv/bin/python -m pytest --no-cov tests/test_repo_source_recovery_authority.py tests/test_repo_work_original_producer_source.py tests/test_repo_work_original_producer_startup.py tests/test_repo_source_stop_knownpost_candidate.py tests/test_repo_source_recovered_finalizer.py tests/test_repo_work_stop_uncertainty.py tests/test_repository_stop_closure_contract.py tests/test_repo_source_public_recovery.py tests/test_operator_auth.py tests/test_auth_owner_continuity.py
Existing paths above were verified by read-only inspection. Retain existing actual rollback/retry, changed reservation, Unknown due-auth-touch, startup candidate-order and unrelated-lineage negatives. Planned additions belong in these existing owners: Running rollback → actual due auth touch → same immutable receipt retry; Running and Unknown rollback → actual HTTP bearer refresh → same receipt retry; retired bearer/new login/replacement/revocation/expiry denial; immutable field/journal/commitment tamper; registration/completion/durability signer substitution; all fsync cutpoints; old v1-v3 denial; full reservation membership/state/cost change; no authority/deadline renewal. Add exact v4 framed static versus historical unframed digest rejection at every Unknown/producer/parser/knownpost seam; actual first-stage Unknown Q retry and committed Q-minus-two-wrappers/revision-one proof; earlier P substitution denial; orphan Running→Unknown epoch-change denial without immutable commitment recapture. These additions and the separately named managed-restart module are PLANNED, not existing passed cases.
From frontend/ (commands NOT_RUN):
npm test -- src/components/cockpit/RepoRepairInspector.test.tsx
npm run build
Extend real typed held/continuation/cleanup readbacks; inspect no unsafe retry/dispatch button before acceptance, explicit stale/expired/revoked states, exact original lineage and no raw key/path/proposal leakage. UI/parser passing cannot open the recovery gate.
Managed acceptance is a PLANNED implementation-owned harness, not an existing passed script. Launch with repository ./manage.sh -e dev local run, retain exact managed backend PID/start identity, same file-backed SQLite/workspace and enforced inference denial; signal only that owned backend. Restart using the same managed command, never direct uvicorn/Vite. Do not clear/reseed the database between processes. Cutpoints: original registration commit before ACK; completion signature before material fsync; material fsync before durability proof; durability proof installation/directory fsync before backend notification; cleanup artifact fsync before first SQL append; injected cleanup/readback SQL rollback; successful cleanup/readback commit before terminal CAS. Test Running and already-Unknown originals, real auth touch/refresh between rollback and retry, and original expiry without a new cleanup window. Assert no missing-command replay, no duplicate append/charge, unchanged receipt bytes/constructor times, retained Unknown liability, exact startup isolation, verified physical closure and final accounting/readback. A process restart fixture or database reopen is not managed backend kill/restart evidence.
Retain private receipts in repository .agent-evidence/ with restrictive permissions: command/status/count/failure, exact source commit, database/workspace identity, owned PID/start/boot identity, original Root/Task/Attempt/revisions/fences, artifact/commitment/journal hashes, denial callback counts, fsync/SQL cutpoint, current auth session and unchanged absolute/task cutoffs, reservation before/after and redacted API/UI screenshots. No tokens, keys, raw private outputs or operator workspace contents in public docs/PRs.
Stop conditions and review
Stop and report exact path/symbol/baseline, intended invariant, observed mismatch and unaffected work if normative schema/domain/proof grammar is incomplete, existing owners cannot enforce it, an old receipt requires retroconstruction, pure SQL contains physical I/O, a fresh login can gain old authority, a child bypasses inference denial, a real local failure remains, or fsync/crash/auth/CAS evidence is absent. Do not choose an alternative signature protocol, add an inventory identity, weaken public 503 or mark acceptance from parser/docs checks. Missing Linux trusted-host proof is blocked selected-mode evidence; do not reboot/provision a host or substitute namespace fixtures for actual boot identity.
Independent cumulative Critic review must specifically inspect immutable versus current authority, exact version/migration dispatch, registration/completion/durability ordering, journal/updated_at proof, Running and Unknown refresh retry, reservation liabilities, startup isolation and API/UI gate. Findings must be fixed, explicitly rejected with rationale, or tracked with ownership before completion. This documentation task provides no runtime test or implementation completion receipt.
Copyable implementation starting prompt
Apply the reviewed documentation PR commit containing ADR-032 and this handoff to the latest #1009 feature branch; confirm it is not main/develop, verify the surviving baseline and any reviewed predecessors, and stop on contract drift. Implement #1009 strictly from ADR-032 plus unchanged ADR-030, following this handoff's numbered order. Preserve historical v3 startup debt protection, add NEW v4 authority only, and stage Running's original C1 input artifact before immutable commitment construction. Enforce the named child-process provider/local-model denial with only exact fixture loopback control allowances; run ordinary isolated tests and actual same-database managed crash/restart/auth-refresh/API/UI proof without inference or evals. Retain private evidence and report unrun/failed gates honestly; keep public recovery 503 until complete proof. Obtain independent Critic review of the exact pushed cumulative implementation head and resolve material findings. Do not merge or deploy without explicit user authorization.