# Automatic Execution + Independent Review Cycle — Design v2 Task: FR-AUTO-REVIEW-DESIGN-002 · Project: FACTORY-RUNTIME · Date: 2026-11-28 Inputs (read in full): `automatic-review-requirements.md` (**REQ**), `review/automatic-review-design.md` (**D1**), `review/automatic-review-design-review.md` (**RV**, verdict FAIL, B1–B9). D1 and RV are preserved unchanged. This file is the complete replacement design; it does not require reading D1 to be implemented, but where D1 is unchanged it says so. Status: design only. No production code, production DB, service or restart was touched. Feasibility probes ran only in `/tmp` with throwaway commands (§6.3). ## 0. Summary and how v2 differs The shape is unchanged from D1: one logical task = one `tasks` row; a cycle is an additive durable state machine (`EXECUTION → verification → REVIEW → [FAIL → REVISION …] → PASS`); reviews/revisions are extra `executions` rows; task statuses are unchanged; opt-in; off by default; no new service, permission, paid resource or executor. What changes (all nine RV blocking groups were accepted, none rejected; see §1 for the two refinements of scope/remedy): 1. One **acceptance predicate** gates automatic finalization *and* every owner acceptance route (B1). 2. The snapshot is created **inside the approval transaction** and is the only source of requirements for every cycle step, including resume (B2). 3. **Resource admission applies to every dispatcher claim**, legacy included, with path-containment semantics (B3). 4. Reviewer isolation is **enforced by the OS** (bubblewrap read-only root + scratch tmpfs), not by prompt/hash; unavailable ⇒ fail closed. Feasible with already-installed software and the dispatcher's existing user — no new privilege or service (B4; §6). 5. Budgets/recovery are keyed by **step**; global `executions.attempt` stays monotonic only for its UNIQUE constraint (B5). 6. One **transition table with precedence** replaces the D1 prose (B6). 7. The kill switch is a **durable operator mode** and never turns a cycle task into a legacy task (B7). 8. Finding identity, no-progress and scope-stop rules are rewritten (B8). 9. Settings schema is exact; capacity is reserved inside the claim transaction; selection scans past blocked candidates (B9). Mandatory vs optional is marked throughout: **[M]** = mandatory correction required for R0 acceptance; **[O]** = optional recommendation, never a blocker. ## 1. B1–B9 closure matrix | B | RV finding | Decision | Evidence from actual code (verified this task) | v2 correction | Where | Test ids | |---|---|---|---|---|---|---| | B1 | Failed verification can be bypassed by manual accept | **Accepted [M]** | `console/owner_decisions.py` `decide()`: `if action=='accept' and not task['result'].strip()` is the only acceptance guard; `DECIDABLE` includes FAILED/REVIEW; no verification lookup. `claim()` l.80-82 and `ready` query l.369-371 treat `ACCEPTED` as sufficient. Routes `/tasks/{id}/status` (app.py l.275) and `/tasks/{id}/result` (l.378, `action=review`) also move status | Shared predicate `can_accept(task)` (§3.4) called by `apply_outcome` and by `decide('accept')`; D1 I1 "explicit owner accept" exception removed | §3.4, §7 | T-B1-1…6 | | B2 | Snapshot incomplete, not consistently used, created before approval | **Accepted [M]** | `executor_policy.effective_executor` reads live project defaults and `next_executor`; `run_one` builds the prompt from live `task['instruction']`, `expected_result` and `verification.contract(task)`; routes `PUT /api/projects/{key}/executors` (l.503), `PUT …/tasks/{id}/executor` (l.519), `verification.configure` (refuses only RUNNING), attachments routes (l.226, l.262) | Snapshot written in `approve_task` transaction with resolved config, workspace, resources, deps, digests; all steps read snapshot; guards on ACTIVE **and** STOPPED cycles and on any approved-but-unfinished cycle | §3.1, §3.5 | T-B2-1…7 | | B3 | Leases ignore legacy writers and path overlap | **Accepted [M]**, remedy refined (§1.1) | `claim()` performs no resource check; l.110 default workspace is `ROOT` for codex/claude-code, so legacy tasks are broad writers by default | Admission check inside `claim()`'s existing `BEGIN IMMEDIATE` for **all** tasks; typed keys, canonical paths, component-wise containment, symlink-conservative | §5 | T-B3-1…8 | | B4 | Hash detection ≠ read-only | **Accepted [M]**; feasibility proven (§6.3) | `executors/codex.py` command uses `--sandbox workspace-write … --add-dir WORKDIR`; `executors/claude_code.py` uses `--permission-mode acceptEdits --allowedTools Read,Bash,Edit,Write,…` | Review launch profile: executor CLI is started under `bwrap --ro-bind / /` with scratch tmpfs and only its own credential/config dir writable; fail closed if probe fails | §6 | T-B4-1…8 | | B5 | Step budgets/recovery semantics | **Accepted [M]** | `claim()` l.86-91 `prior=COUNT(*) FROM executions WHERE task_id`; `runtime.recovery_decision` compares `attempt>=max_attempts` and computes backoff from global `attempt`, and applies task `EXPLICIT` pin to every executor; `recover_interrupted`/`supervisor.eligible` (`row['attempts']>=MAX_ATTEMPTS or row['attempt']>=MAX_ATTEMPTS`) use task-wide counts | `step_attempt` column, step-scoped history, `recovery_decision(..., step=…)`; reviewer policy separate from task pin; exact launch caps | §4 | T-B5-1…8 | | B6 | Stop/recovery/supersession incoherent | **Accepted [M]** | `record_recovery` checks only `tasks.status`; `supervisor.eligible` never reads cycles; `/tasks/{id}/status`, `/decision` mutate task status directly | Single transition table with fence precedence, CAS `version`, idempotency key; all owner routes call it; cycle tasks never end FAILED | §3.2–§3.3, §7 | T-B6-1…8 | | B7 | Kill switch authorises unsafe legacy path | **Accepted [M]** | D1 §3.1/§9; legacy `ready` query claims any `READY` row; legacy `decide` accepts any REVIEW/PAUSED/BLOCKED task with a result | Durable `review_cycle_control.mode` (ON / DRAIN / PARKED); never "legacy"; defined downgrade preflight; consistent backup | §8 | T-B7-1…6 | | B8 | No-progress/non-blocking mis-stops | **Accepted [M]** | D1 §4.1 rules (verbatim in RV) | Stable ids; scope stop only for *necessary* out-of-scope work; evidence-based no-progress; PASS evaluated first | §3.6 | T-B8-1…8 | | B9 | Settings, capacity, selection | **Accepted [M]**; one claim in RV corrected in the same direction | `runtime.candidates('deepseek')` returns codex/deepseek/claude-code ⇒ DeepSeek is tool-capable in the runtime; `cycle()` l.363-372 `LIMIT MAX_WORKERS` before claim; `claude_code._CLAUDE_RUN_LOCK` is module-level and `load_executor` builds fresh modules | Exact settings schema; DB-level capacity inside `claim()`; scan-until-filled selection; capability allowlist **not** derived from "text-only" labels | §9 | T-B9-1…8 | ### 1.1 Disputes / refinements (with evidence) No RV finding is disputed as incorrect. Three refinements keep original scope and avoid over-correction: 1. **B1 "reuse bound evidence while unchanged; reverify when stale".** Accepted; D1 §11 "never repeated re-verification" is deleted. One verification per produced revision, plus a re-run only when `can_accept` finds the manifest digest changed. 2. **B3 conservative legacy write sets.** Treating every legacy ROOT-workspace task as a writer to the whole tree would serialize all codex/claude work against any open cycle (violates REQ "independent branches continue"). Evidence: `claim()` l.110 gives ROOT to all Codex/Claude tasks. Remedy adopted: legacy tasks conflict only with **cycle reservations they can actually overlap** (§5.2); a cycle should normally reserve a narrow declared scope or run in its own `workspaces/` directory; the throughput cost for ROOT legacy tasks that overlap an open cycle is **disclosed and is an owner decision** (OD-2), not hidden. Untracked external writers cannot be controlled by any lease, as RV states; the design says so in the docs and makes review isolation (not leases) the integrity control for the review window. 3. **B9 capability allowlist.** RV is right that DeepSeek must not be excluded by a "text-only" label. The reason it is not an initial cycle **reviewer** is different and verifiable: the review isolation profile (§6) is implemented/tested only for `codex` and `claude-code`; DeepSeek runs through its own tool sandbox (`executor.WORKSPACE`, restricted to `workspaces/`). It remains allowed as an *executor* when its workspace is under `workspaces/` (same rule as `recovery_decision`). ## 2. Concepts and invariants (unchanged from D1 unless marked) * **Logical task** = one `tasks` row. **Cycle** = durable state machine on it. **Step** = `(revision r, phase p)` with `p ∈ {EXECUTION, REVIEW}`; `r=0` initial. * **Technical retry** = same step, new launch after a transient/unavailable failure; never changes `revision`. * **Revision** = content defect (validated blocking finding or dispatcher verification failure). `revision += 1`; never sets task `FAILED`. * Invariants (changed items marked *): 1. I1*: a cycle task is `COMPLETED/ACCEPTED` only if `can_accept` (§3.4) holds. No exception. 2. I2*: launches per cycle ≤ `2*(max_revisions+1)*MAX_ATTEMPTS` (default 40, absolute ceiling 60 with `max_revisions=5`); technical retries and format retries are inside step caps. 3. I3: every transition applied exactly once (§3.3). 4. I4*: every step (executor and reviewer) reads requirements **only** from the approved snapshot. 5. I5: failed verification is never bypassed by reviewer, supervisor or owner action. 6. I6: reviewer ≠ executor that produced the artifact under review, including after fallback. 7. I7 (new): while a cycle is open (ACTIVE or STOPPED), no route can change its inputs, assignment, contract or status except through a §3.2 transition. 8. I8 (new): a reviewer process cannot write to the workspace, DB or artifacts (OS-enforced, §6). ## 3. Data model and lifecycle ### 3.1 Schema (additive; all via `MIGRATIONS` / `CREATE IF NOT EXISTS`, `init_db()` idempotent) ```sql ALTER TABLE projects ADD COLUMN review_cycle_json TEXT NOT NULL DEFAULT '{}'; ALTER TABLE tasks ADD COLUMN review_cycle_json TEXT NOT NULL DEFAULT '{}'; ALTER TABLE executions ADD COLUMN cycle_id INTEGER; -- NULL = legacy ALTER TABLE executions ADD COLUMN phase TEXT NOT NULL DEFAULT 'EXECUTION'; ALTER TABLE executions ADD COLUMN revision INTEGER NOT NULL DEFAULT 0; ALTER TABLE executions ADD COLUMN step_attempt INTEGER NOT NULL DEFAULT 1; -- per (cycle,revision,phase) ALTER TABLE executions ADD COLUMN role TEXT NOT NULL DEFAULT 'EXECUTOR'; -- EXECUTOR|REVIEWER ALTER TABLE executions ADD COLUMN producer_execution_id INTEGER; -- reviews: the execution under review ALTER TABLE executions ADD COLUMN manifest_sha256 TEXT; -- deliverable manifest digest at finish CREATE TABLE IF NOT EXISTS review_cycle_control ( -- durable operator switch (B7) id INTEGER PRIMARY KEY CHECK(id=1), mode TEXT NOT NULL DEFAULT 'ON' CHECK(mode IN ('ON','DRAIN','PARKED')), updated_by TEXT NOT NULL DEFAULT '', updated_at TEXT NOT NULL DEFAULT '', note TEXT NOT NULL DEFAULT ''); INSERT OR IGNORE INTO review_cycle_control(id) VALUES(1); CREATE TABLE IF NOT EXISTS cycle_snapshots ( -- immutable; INSERT only inside approve_task id INTEGER PRIMARY KEY, task_id INTEGER NOT NULL REFERENCES tasks(id) ON DELETE CASCADE, version INTEGER NOT NULL, instruction TEXT NOT NULL, expected_result TEXT NOT NULL, criteria_json TEXT NOT NULL, verification_json TEXT NOT NULL, config_json TEXT NOT NULL, -- RESOLVED settings: executor, reviewer, fallbacks, max_revisions, owner_intervention workspace_path TEXT NOT NULL, -- resolved, canonical resources_json TEXT NOT NULL, -- typed declared write scope (§5.1) depends_json TEXT NOT NULL, -- [{task_id,key,checkpoint}] at approval checkpoint INTEGER NOT NULL, inputs_json TEXT NOT NULL, -- [{kind:'attachment'|'material'|'project_instruction', id, sha256, role:'REQUIREMENT'|'CONTEXT'}] sha256 TEXT NOT NULL, -- digest over all fields above approved_by TEXT NOT NULL, approved_at TEXT NOT NULL, -- NOT NULL: no snapshot without approval UNIQUE(task_id,version)); CREATE TABLE IF NOT EXISTS review_cycles ( id INTEGER PRIMARY KEY, task_id INTEGER NOT NULL REFERENCES tasks(id) ON DELETE CASCADE, snapshot_id INTEGER NOT NULL REFERENCES cycle_snapshots(id), state TEXT NOT NULL CHECK(state IN ('ACTIVE','STOPPED','PASSED','SUPERSEDED','CANCELLED')), phase TEXT NOT NULL CHECK(phase IN ('EXECUTION','REVIEW')), revision INTEGER NOT NULL DEFAULT 0, max_revisions INTEGER NOT NULL, -- incl. owner grants, ≤5 executor TEXT NOT NULL, reviewer TEXT NOT NULL, -- resolved at approval stop_requested INTEGER NOT NULL DEFAULT 0, stop_reason TEXT, stop_detail TEXT NOT NULL DEFAULT '', acceptance_json TEXT NOT NULL DEFAULT '{}', -- producer_execution_id, verification_artifact_id+sha, manifest_sha256, review_execution_id version INTEGER NOT NULL DEFAULT 0, -- CAS counter, +1 per transition created_at TEXT NOT NULL, updated_at TEXT NOT NULL, finished_at TEXT); CREATE UNIQUE INDEX IF NOT EXISTS ux_cycle_one_open ON review_cycles(task_id) WHERE state IN ('ACTIVE','STOPPED'); CREATE TABLE IF NOT EXISTS cycle_transitions ( -- audit + idempotency for ALL transitions, not only execution outcomes id INTEGER PRIMARY KEY, cycle_id INTEGER NOT NULL REFERENCES review_cycles(id) ON DELETE CASCADE, idem_key TEXT NOT NULL UNIQUE, -- 'exec:' | 'owner:::' | 'sys:::' execution_id INTEGER REFERENCES executions(id), from_state TEXT NOT NULL, to_state TEXT NOT NULL, from_step TEXT NOT NULL, to_step TEXT NOT NULL, outcome TEXT NOT NULL, detail TEXT NOT NULL DEFAULT '', actor TEXT NOT NULL DEFAULT 'dispatcher', created_at TEXT NOT NULL); CREATE TABLE IF NOT EXISTS cycle_findings ( id INTEGER PRIMARY KEY, cycle_id INTEGER NOT NULL REFERENCES review_cycles(id) ON DELETE CASCADE, stable_id TEXT NOT NULL, -- identity across revisions (§3.6): '|' first_revision INTEGER NOT NULL, last_revision INTEGER NOT NULL, source TEXT NOT NULL CHECK(source IN ('REVIEWER','VERIFICATION','OWNER')), severity TEXT NOT NULL CHECK(severity IN ('BLOCKING','SUBSTANTIAL','RECOMMENDATION')), status TEXT NOT NULL DEFAULT 'OPEN' CHECK(status IN ('OPEN','FIXED_CLAIMED','RESOLVED','DISPUTED','UPHELD','WAIVED')), summary TEXT NOT NULL, expected TEXT NOT NULL DEFAULT '', actual TEXT NOT NULL DEFAULT '', evidence_json TEXT NOT NULL, response_json TEXT NOT NULL DEFAULT '{}', rulings_json TEXT NOT NULL DEFAULT '[]', persisted_after_remediation INTEGER NOT NULL DEFAULT 0, -- no-progress counter (§3.6) review_execution_id INTEGER REFERENCES executions(id), created_at TEXT NOT NULL, UNIQUE(cycle_id,stable_id)); CREATE TABLE IF NOT EXISTS resource_reservations ( -- §5; replaces D1 resource_leases id INTEGER PRIMARY KEY, kind TEXT NOT NULL CHECK(kind IN ('PATH','DB','SERVICE')), key TEXT NOT NULL, -- canonical absolute path | db file | service name mode TEXT NOT NULL CHECK(mode IN ('WRITE','READ')), owner_cycle_id INTEGER NOT NULL REFERENCES review_cycles(id) ON DELETE CASCADE, acquired_at TEXT NOT NULL, UNIQUE(kind,key,owner_cycle_id)); ``` Notes: artifacts per review `review-r{n}-verdict.json`; per revision `responses-r{n}.json`; event names as D1. `executions.attempt` stays globally monotonic (UNIQUE(task_id,attempt)); **budgets use `step_attempt`**. `cycle_findings` is keyed by stable id (not review row), which fixes D1's `finding_key` over prose. ### 3.2 Transition table (single source of truth) Evaluate **top to bottom, first match wins**, inside one `BEGIN IMMEDIATE` (`cycle_apply`). Inputs: cycle row (state, phase, revision, version, stop_requested), control mode, trigger. | # | Guard (evaluated in this order) | Effect | |---|---|---| | 0 | `idem_key` already in `cycle_transitions` | no-op, return recorded result | | 1 | Trigger is a worker outcome and `(cycle.id, snapshot_id, phase, revision, execution_id)` ≠ the cycle's current expected step or `execution.cycle_id` mismatch (late/stale worker) | Record execution result and artifacts only; **no state change**; event `STALE_OUTCOME`; resources untouched | | 2 | Cycle `state ∈ {SUPERSEDED, CANCELLED, PASSED}` | Same as 1 (record only) | | 3 | `stop_requested=1` **or** `control.mode ∈ {DRAIN, PARKED}` and trigger is a worker outcome | Record execution result; settle `STOPPED(MANUAL_STOP \| OPERATOR_PARK)`, task `REVIEW`; **never** enter `FAILED`; release reservations (execution has exited — the outcome *is* the exit). Advance nothing. No revision/finding derived from this outcome | | 4 | Trigger = owner **change requirements** | cycle `SUPERSEDED`, task `PLANNED`, `approved_at/by` cleared, draft requirements stored; reservations released after quiescence (no live execution; if live → set `stop_requested=1` first and settle via row 3 then supersede on the next owner action; the route returns 409 "stopping") | | 5 | Trigger = owner **stop** | no live execution → `STOPPED(MANUAL_STOP)` now; live → `stop_requested=1` only (settles at row 3); the CAS makes a duplicate click a no-op | | 6 | Trigger = owner **resume(+N, guidance)** and `state=STOPPED` and `stop_reason ∈ resumable` and snapshot unchanged and inputs digests unchanged (§3.5) and reservations re-acquirable and, if the cycle had produced evidence, `can_accept` inputs re-validated (§3.4) | `ACTIVE`, same snapshot, `max_revisions += N` (≤5, never reset spent history), guidance stored as OWNER finding that may only *explain* an existing criterion; otherwise 409 and "requirements change" is the only path | | 7 | Outcome = technical failure (class ∈ TRANSIENT ∪ {EXECUTOR_UNAVAILABLE}) | step-scoped `recovery_decision` (§4.2) → stay in step, `READY`+backoff **or** `STOPPED(TECHNICAL_EXHAUSTED \| REVIEWER_UNAVAILABLE \| QUOTA_EXHAUSTED \| ACCESS_REVIEW_REQUIRED)` with task `REVIEW` (never FAILED for cycle tasks) | | 8 | Outcome = `FACTORY_OUTCOME: OWNER_CHECKPOINT` | `STOPPED(BUSINESS_DECISION\|EXTERNAL_BLOCKER)`, task `REVIEW`, `checkpoint=1` (existing path) | | 9 | EXECUTION ok + verification **passed** | phase=REVIEW; store `producer_execution_id`, `manifest_sha256`, verification artifact id+sha in `acceptance_json`; task `READY` | | 10 | EXECUTION ok + verification **failed** | VERIFICATION findings (stable id `|`); go to row 14 (content FAIL) — no review spent | | 11 | REVIEW verdict structurally invalid / no valid blocker with `FAIL` | `REVIEW_FORMAT` retry in step (§4.3), then `STOPPED(REVIEW_OUTPUT_INVALID)` | | 12 | REVIEW verdict `PASS` and `can_accept` holds | cycle `PASSED`; task `COMPLETED`, or `REVIEW` if `checkpoint=1` (owner `accept` then only resolves the checkpoint). **Evaluated before no-progress.** Recommendations are stored, never block | | 13 | REVIEW `PASS` but `can_accept` fails (stale/missing verification, manifest drift) | re-run verification once for the producer (if inputs unchanged); else `STOPPED(EVIDENCE_STALE)` | | 14 | content FAIL: stop checks in this order: `BLOCKED_EXTERNAL/NEEDS_OWNER` → matching stop; necessary out-of-scope work (§3.6) → `SCOPE_EXPANSION`/`RIGHTS_OR_PAID_RESOURCE`; unresolved dispute (`UPHELD` twice on same stable id) → `DISPUTE_UNRESOLVED`; no-progress (§3.6) → `NO_PROGRESS`; `revision ≥ max_revisions` → `REVISION_LIMIT` | else `revision += 1`, phase=EXECUTION, task `READY`, `retry_at=NULL` | Every transition: CAS `UPDATE review_cycles SET …, version=version+1 WHERE id=? AND version=?` (rowcount≠1 ⇒ rollback, caller re-reads), insert `cycle_transitions`, event, Russian owner summary on any STOPPED (deterministic, no model). Task status mapping for **cycle tasks**: every STOPPED (technical, content, manual, parked) ⇒ task `REVIEW`; `execution` rows keep honest FAILED/INTERRUPTED status. `FAILED` task status (which blocks dependants) is reserved for non-cycle tasks. PASSED+checkpoint ⇒ cycle `PASSED`, task `REVIEW` until owner accept; dependants release only at `ACCEPTED`/`COMPLETED` through the existing predicate, now guarded by §3.4. Crash points (each tested): after execution row finished but before `cycle_apply` (startup recovery marks INTERRUPTED, `cycle_apply` row 7 handles it as PROCESS_CRASH in the same step); after `cycle_apply` before event write (same transaction ⇒ impossible); between stop request and exit (row 3 on exit; on dispatcher death recovery sees `stop_requested` and settles STOPPED instead of re-arming READY). ### 3.3 Idempotency and recovery wiring * Worker finalization in `run_one` calls `cycle_apply` in the same `BEGIN IMMEDIATE` as the execution update; replay hits row 0 (`UNIQUE idem_key`). * `runtime.record_recovery` and `recovery.recover_interrupted` first call `cycle_fence(db, task_id)`: if an open cycle has `stop_requested`, mode ≠ ON, or state ≠ ACTIVE, they record the interruption but **do not set the task READY** (they route through row 3/7). Without a cycle they behave exactly as today. * `supervisor.eligible` gains one early return: an open cycle (ACTIVE with content reason, STOPPED, PASSED-awaiting-checkpoint, SUPERSEDED) ⇒ `CYCLE_MANAGED` (not eligible). The supervisor never releases, accepts or rearms a cycle task; technical retries inside an ACTIVE cycle are handled by row 7, not by the supervisor. `fingerprint` includes cycle id/version. ### 3.4 Acceptance predicate `can_accept(task)` [M] (B1) True only if all hold, evaluated in one transaction: 1. An approved snapshot exists, `cycle.snapshot_id` is the highest version for the task, and `tasks.approved_at` ≥ `snapshot.approved_at`. 2. `acceptance_json.producer_execution_id` is the **latest COMPLETED EXECUTOR-role execution** of the cycle, in the current revision. 3. A durable verification artifact for that execution exists with `passed=true`, digest equal to `acceptance_json`, and `verification_json` equals the snapshot's. 4. The deliverable manifest recomputed now equals `manifest_sha256` (the producer's `changed:true` baseline is not compared against the reviewer's pre-review hash). 5. A REVIEWER-role execution with `producer_execution_id` = (2), valid verdict `PASS`, reviewer ≠ producer executor. 6. No QUEUED/RUNNING execution for the task. Callers: `cycle_apply` row 12; `owner_decisions.decide(action='accept')` for any task having an open or PASSED cycle (and for any legacy task whose latest execution has a failed verification artifact — see below); `/tasks/{id}/status` and `/result` reject setting `ACCEPTED/COMPLETED` (already true) and, for cycle tasks, any status change not produced by `cycle_apply` (I7). Owner accept after PASS **only resolves the checkpoint**; it cannot waive failed/missing/stale verification or replace the review. A changed contract/requirement ⇒ new snapshot ⇒ renewed approval (row 4). Legacy compatibility note: the probe in RV shows `decide()` accepts a FAILED legacy task with no verification evidence. Closing that for **non-cycle** tasks changes legacy behaviour; it is the same unsafe gap and the same two-line predicate (`latest verification artifact exists and passed` unless `executor='human'`/contract absent as today). Default: **[M] for cycle tasks, [O] for legacy tasks** (OD-4). The cycle feature does not depend on the legacy change. ### 3.5 Frozen approval [M] (B2) * `runtime.approve_task` (already transactional, `BEGIN IMMEDIATE` in the route) additionally, when the resolved settings have `enabled=true`, validates settings (§9), resolves defaults **once**, canonicalizes workspace and resources, hashes referenced attachments/materials/project instructions, inserts `cycle_snapshots(version=n+1)` and creates the cycle `ACTIVE/EXECUTION r0` — all in the approval transaction. A rollback leaves no snapshot (approved_by/at NOT NULL). * `inputs_json` separates `role:'REQUIREMENT'` (task attachments, task instruction/expected result) from `role:'CONTEXT'` (project materials, project instructions). Digest mismatch of a REQUIREMENT input at claim ⇒ `STOPPED(REQUIREMENTS_CHANGED)`; CONTEXT mismatch ⇒ warning event only (context is background, not an approved requirement). * Executor of each step = `snapshot.config.executor` (with the step-scoped fallback of §4.2); reviewer = `snapshot.config.reviewer`. `effective_executor()`/project defaults are **not** consulted for cycle tasks after approval. `run_one` builds `task['instruction']`, `expected_result`, `verification_json`, `workspace_path` from the snapshot for cycle steps. * Guard I7 on routes: when an open cycle exists, `verification.configure`, `PUT …/executors`, `PUT …/tasks/{id}/executor`, attachment add/delete, `/tasks/{id}/status`, `/tasks/{id}/result`, `/decision(revise/hold)`, project workspace/materials edits that touch snapshot inputs → 409 "cycle open; use cycle controls". Edits to project defaults still succeed but affect only future approvals. A hold/revise via `/decision` on a cycle task is mapped to row 5 / row 4 respectively. * Stopped-cycle resume uses row 6 (digest re-check). New scope never dispatches without a new approval. ### 3.6 Findings, no-progress, scope [M] (B8) * **Stable identity.** `stable_id = "|"` where `check id` is the verification contract check index/name or reviewer-supplied `target_ref` (normalized path/test id). Prose never forms identity. The reviewer prompt receives the open stable ids and must reuse them; a new blocker must map to a snapshot criterion and a target; otherwise it is downgraded to SUBSTANTIAL. * **Validation (unchanged idea).** `FAIL` requires ≥1 `BLOCKING` finding with `criterion_ref` ∈ snapshot criteria and evidence whose `ref` exists (path-contained) or is a recorded test; invalid blockers are downgraded and never trigger a revision; FAIL with none valid is a *protocol error* (row 11), bounded separately, **not** a content revision and not silently PASS. * **Scope.** `SCOPE_EXPANSION` stop only when a *valid blocking* finding states that satisfying the criterion **requires** work outside the approved scope (flag `requires_out_of_scope:true` + reason). Optional outside-scope advice is a RECOMMENDATION and never blocks (REQ: recommendations never block). PASS with recommendations stays PASS. * **No-progress** is counted per stable id only while a **validated blocker persists after one full remediation opportunity**: (revision r review lists blocker B; revision r+1 executes; review r+1 or dispatcher verification r+1 lists B again) ⇒ `persisted_after_remediation=1`; threshold = 2 consecutive persisted opportunities (one threshold everywhere; D1 §15 wording retired). Dispatcher verification failures count as the review of that revision. Support evidence (not sufficient alone): relevant evidence digests unchanged (workspace manifest of the files named by the finding/contract plus test result digest) **and** no response with evidence. Output-byte identity alone is not no-progress: an evidenced fix (changed source/test config, response `FIXED` with new evidence the reviewer confirms) resets the counter. * **Disputes.** Executor response `DISPUTED` must carry evidence; reviewer rules `UPHELD|WITHDRAWN` (bounded rulings stored); `WITHDRAWN` or a verified changed result resolves; second `UPHELD` on the same stable id ⇒ `DISPUTE_UNRESOLVED`. * Mandatory stops that `owner_intervention` can never remove: `REVISION_LIMIT, NO_PROGRESS, SCOPE_EXPANSION, RIGHTS_OR_PAID_RESOURCE, EXTERNAL_BLOCKER, BUSINESS_DECISION, MANUAL_STOP, REQUIREMENTS_CHANGED, OPERATOR_PARK, TECHNICAL_EXHAUSTED`. `owner_intervention` may only **add** optional stops (e.g. `STOP_ON_SUBSTANTIAL`). ### 3.7 Review contract (unchanged format, tightened) Reviewer prompt built from the snapshot (criteria with ids, instruction, expected result, contract, latest verification artifact path, producer output + manifest, open stable ids with executor responses). Verdict JSON as D1 §4.1 plus per-finding `stable_id` and `requires_out_of_scope`. Free text goes through `providers.output.safe_text` and is bounded. Verdict is **published by the dispatcher** from the reply text (the reviewer writes nothing to disk, §6). Executor revision prompt = snapshot + prior output + verification evidence + all open BLOCKING findings with evidence; required `{"responses":[…]}` block. ## 4. Step budgets, recovery and fallback [M] (B5) ### 4.1 Counters * `executions.attempt`: unchanged (global monotonic, for UNIQUE and artifact names). New `executions.step_attempt` = 1 + count of prior executions with same `(cycle_id, revision, phase)`. * `claim()` budget check for cycle tasks: `step_attempt > MAX_ATTEMPTS` ⇒ stop `TECHNICAL_EXHAUSTED` (row 7), not `FAILED`; for non-cycle tasks the existing `prior>=max_attempts` code (l.86-91) is untouched. * Absolute guard: `COUNT(executions WHERE cycle_id=?) ≥ 2*(max_revisions+1)*MAX_ATTEMPTS` ⇒ `STOPPED(TECHNICAL_EXHAUSTED)`. Defaults: `max_revisions=3`, `MAX_ATTEMPTS=5` ⇒ **40 launches** (D1's "≤4 executor runs" counted content only). Owner grants raise `max_revisions` only up to 5 and never reset spent history. ### 4.2 Step-scoped recovery `recovery_decision(db, task_id, executor, attempt, failure, max_attempts, step=None)`; `step=None` ⇒ byte-identical legacy logic. With `step=(cycle_id, revision, phase, role, producer_executor, allowed)`: * `attempt` ← `step_attempt` for the cap and for the backoff exponent (so a later revision starts at 10 s, not 300 s; reproduces and fixes RV probe 3). * History queries (`counts`, `unavailable`, exhausted executors) filter by the step, not by task. * The task's `EXPLICIT` pin applies only to the **executor role of EXECUTION steps** (cycle executor = pin at approval). It is **not** applied to REVIEWER steps (fixes RV probe 2 `EXPLICIT_EXECUTOR_MISMATCH`). * EXECUTION fallback: `candidates(executor) ∩ allowed_executors`, existing `secondary` preference, deepseek workspace rule as today; result stored as step state, **cleared at phase change** (`tasks.next_executor` is set to NULL by `cycle_apply` rows 9/14; the snapshot executor, not `next_executor`, seeds each new EXECUTION step — fixes "execution-phase `next_executor` inherited by review"). * REVIEW fallback: `{codex, claude-code} − {producer_executor} − {exhausted in step}`; **never** the producer; if none ⇒ backoff retry until step cap, then `STOPPED(REVIEWER_UNAVAILABLE)`. After an execution fallback changes the producer, the reviewer is **re-selected** (configured reviewer if ≠ new producer, else the other allowed one, else stop). * `QUOTA_EXHAUSTED` and `ACCESS_DENIED` keep their existing REVIEW outcomes mapped to `STOPPED(QUOTA_EXHAUSTED|ACCESS_REVIEW_REQUIRED)`. * Claimless unavailable condition (no executor currently available, no claim made): bounded by wall time, not a counter: once `UNAVAILABLE_WAIT_MAX` (default 6 h since the step became READY, taken from the last `cycle_transitions.created_at`) ⇒ `STOPPED(EXECUTOR_UNAVAILABLE_TIMEOUT)`. Waiting consumes no attempt. ### 4.3 Review format retries Class `REVIEW_FORMAT` (new, cycle-only, not in legacy `TRANSIENT`). At most **2 additional launches** per REVIEW step, **inside** the 5-launch step cap, counted from durable `executions.failure_class='REVIEW_FORMAT'` for the step (restart cannot reset). Third failure ⇒ `STOPPED(REVIEW_OUTPUT_INVALID)`. ### 4.4 Restart recovery State lives only in the DB. Startup recovery marks orphan RUNNING as INTERRUPTED (existing) and then `cycle_fence` + row 7 decide: same step re-run (new `step_attempt`) unless a stop/park fence exists. A review replay is safe now because the reviewer cannot write (§6); a revision replay re-runs on the workspace as left, never double-counting a revision (revision changes only in `cycle_apply`). ## 5. Resource admission [M] (B3) ### 5.1 Declared scope and canonicalization `snapshot.resources_json` = typed list `[{kind:'PATH'|'DB'|'SERVICE', key, mode:'WRITE'|'READ'}]`. Default derivation at approval: contract `file` check paths and deliverable output paths ⇒ PATH WRITE; contract `sqlite` checks ⇒ DB; `api` checks ⇒ none (READ). Plus owner-declared `resources` in settings. PATHs are canonicalized against the **frozen workspace**: `os.path.realpath` of the **nearest existing ancestor** (resolves symlinks) + remaining components, must stay inside the workspace (escape ⇒ reject at approval). Containment is by path components (`a/out` conflicts with `a/out/x.md`, not with `a/outside`). If a symlink inside the tree is found along any declared path the reservation widens to the symlink's real target **and** the link itself. DB/SERVICE keys use exact typed equality. ### 5.2 Admission in `claim()` Inside the existing `BEGIN IMMEDIATE` of `claim()` (after dependency/live checks, before INSERT of the execution), for **every** task: * Compute the task's write set: cycle task ⇒ its snapshot reservations; **legacy task ⇒ declared contract `file` paths if present else its workspace root (conservative)**. * Conflict if any `resource_reservations` row of **another** open cycle (state ACTIVE or STOPPED-with-live-process) has overlapping key under the containment rule and either side is `WRITE`; or, for a cycle task, if any **RUNNING legacy execution's** write set overlaps (computed from the live row; no table needed). * On conflict: rollback, return None, task stays READY, **no attempt consumed**, event `WAITING_RESOURCE` (rate-limited). Reservations are acquired all-or-nothing in the same transaction (no hold-and-wait ⇒ no deadlock). * Reverse race: a legacy claim arriving after a cycle reservation sees the reservation and waits; a cycle arriving after a RUNNING legacy writer waits. Both orders are covered by the one transaction (SQLite write lock). * Fairness [M for liveness]: a cycle waiting more than `ADMISSION_AGING` (default 3 polls) for a legacy writer to finish causes new *overlapping* legacy claims to be deferred until it is admitted. Non-overlapping tasks are never affected. * Release: reservations are held while the cycle is ACTIVE and through a stop request until the process has exited; on STOPPED they are released only after quiescence (row 3) and **re-acquired + evidence re-validated on resume (row 6)**; PASSED/SUPERSEDED/CANCELLED release. A reservation of a cycle whose live process still runs is never released by supervisor or kill switch. * No overlapping reservation ⇒ legacy path unchanged. The compatibility promise is therefore: "identical behaviour unless an open cycle's declared scope overlaps the task's write set", replacing D1's "byte-for-byte". * **Honest limit**: writers outside the dispatcher (human edits, external services, cron) cannot be admitted. Documented. Use a dedicated `workspaces/` for cycle tasks (recommended default for new cycle tasks; the owner decision OD-2 covers the ROOT case). Review-window integrity is protected by §6, not by leases. ## 6. Reviewer isolation using existing permissions [M] (B4) ### 6.1 Requirement During a REVIEW step the reviewing process must be unable to modify the reviewed workspace, `data/` (DB, artifacts), other workspaces, `~`/system files, or sockets that mutate host state; it may read everything it could already read, write only a disposable scratch area, and reach the model API. Verdict is returned as reply text; the **dispatcher** writes the verdict artifact. ### 6.2 Design (no new service, permission or privilege) Add an **isolation wrapper** used only when `role='REVIEWER'` (and only inside the existing adapter modules; no new executor name): ``` bwrap --ro-bind / / --dev /dev --proc /proc --tmpfs /tmp --tmpfs /run/dbus \ --bind \ # claude: ~/.claude-factory ; codex: ~/.codex --unshare-pid --new-session --die-with-parent \ ``` * Root filesystem read-only ⇒ shell, Edit/Write tools, sibling paths and symlinks are all denied by the kernel regardless of tool permissions. `NoNewPrivs=1` is set (sudo is refused), no remount possible. * Test scratch = the tmpfs `/tmp` (and TMPDIR points there); tests needing writable project state run on a copy under `/tmp` made from the reviewed manifest (instructed in the reviewer prompt; verified by T-B4-3). * Only the executor's own credential/config directory is writable (the CLI needs it for auth/session files). It is outside the reviewed workspace; the same directory is already writable by the writable executors, so no privilege is added. * Claude: `cli_options()` gets `--disallowedTools Edit,Write,NotebookEdit` as defence in depth (Bash remains for running tests; the sandbox is the control). Codex: keep `--sandbox workspace-write` for the adapter's own checks, **but the wrapper is the enforcement**; if the Codex inner sandbox cannot start nested inside bwrap (see 6.3 — not yet proven), the allowed fallback is `--sandbox danger-full-access` **only inside the wrapper** (the outer read-only mount, not the flag, is what limits writes). That flag is an existing CLI option, not a new capability, but it is called out for the owner (OD-3). * **Fail closed**: before every REVIEW launch the adapter runs a ~1 s probe inside the same wrapper (`touch /.probe` must fail with EROFS and `touch /tmp/.probe` must succeed). Probe failure ⇒ `failure_class='REVIEW_ISOLATION_UNAVAILABLE'` ⇒ `STOPPED(REVIEW_ISOLATION_UNAVAILABLE)` with actionable reason; the review **never** runs writable. * Secondary integrity check (kept, per RV): manifest/verification-snapshot hashes before/after; difference ⇒ verdict discarded, `STOPPED(REVIEWER_MODIFIED_ARTIFACTS)`. With the sandbox this should never fire; it detects wrapper bypass bugs. * Executor-phase processes are **not** wrapped (they must write); only review is. ### 6.3 Feasibility evidence (this task, `/tmp` only, no repository or DB writes) Host: Linux 6.8, user `iovon` (the dispatcher's service user, `User=iovon`, no `NoNewPrivileges`/`RestrictNamespaces` in `ai-factory-dispatcher.service`), `/usr/bin/bwrap` already installed, `max_user_namespaces=7534`, `unprivileged_userns_clone=1`. | Probe (run as `iovon`, inside `bwrap --ro-bind / / --dev /dev --proc /proc --tmpfs /tmp --unshare-pid --new-session --die-with-parent`) | Result | |---|---| | `touch /home/iovon/ai-factory/data/x`, `touch /home/iovon/zz`, `ln -s … /home/iovon/ai-factory/l` | all `Read-only file system`; no file created (verified from outside) | | `echo > /tmp/ok` | succeeds (scratch) | | `sudo -n true` | refused: "no new privileges flag is set"; `NoNewPrivs: 1` | | `mount -o remount,rw /home` | "must be superuser" | | `/run/dbus/system_bus_socket` present | masked by `--tmpfs /run/dbus` in the design (`--tmpfs /run` broke DNS via `/run/systemd/resolve`, so only `/run/dbus` is masked) | | `curl https://api.anthropic.com` inside wrapper | HTTP 404 reply (network reachable, same as outside) | | `claude --version`, `codex exec --help` inside wrapper | run normally | | `codex sandbox linux -- …` inside wrapper | fails ("Failed to execvp linux"): the Codex **probe** command is absent in this build (already known in `executors/codex.py`), so nested-Codex-inner-sandbox behaviour is **not** established by this probe | **Conclusion:** the outer enforcement is feasible now with no new privilege, service, package or paid resource. **Residual items, none a blocker for design acceptance:** (a) a real nested `codex exec` review under the wrapper has not been run (it would consume a subscription call) — it is the first R2 gate; if the inner Codex sandbox fails nested, use the 6.2 fallback flag, and if that also fails Codex cannot be a *reviewer* (Claude-as-reviewer / Codex-as-executor still works; fail closed otherwise — a capability gap, not a weakened profile); (b) bubblewrap does not isolate the network namespace (needed for the model API), so a reviewer could in principle call a localhost HTTP service. Mitigation: the reviewer prompt forbids it, the hash check is secondary, and the owner is told; closing it needs a proxy/netns service, which is out of scope ("no new services"); (c) sandbox is skipped if the probe passes but the CLI later spawns outside it — not possible with `--die-with-parent` + PID namespace for descendants. If the owner prefers zero residual (b), the alternative is R2 blocker **B-ISO-NET**; this design does not claim it is closed. ## 7. Owner controls and UI (compact) Reuse `project_snapshot` + `owner_decisions.enrich`. Per cycle task: `executor → reviewer · rev r/max · phase badge`, collapsible history (per revision: executor output, verification, findings with severity/criterion/evidence, executor responses, reviewer rulings), stop reason + Russian summary. Controls (token + `confirmed=yes` + actor, as `/tasks/{id}/decision`): `POST /tasks/{id}/cycle/{stop|resume|requirements}`; each maps to §3.2 rows 5/6/4 using `idem_key='owner:::'`. `/decision accept` calls `can_accept` (§3.4); `revise` ⇒ row 4; `hold` ⇒ row 5. `owner_decisions.version()` hashes the open cycle row only if present (legacy tokens unchanged). `owner_decisions.enrich` shows `can_accept` reasons when disabled. Settings controls: project executors panel and task form expose all fields of §9. ## 8. Kill switch, rollout, rollback [M] (B7) * **Durable mode** `review_cycle_control.mode`, set via an owner-authenticated console action (event `CYCLE_MODE_CHANGED`) — works with **no restart**. Read at: `approve_task` (creation), `claim()` (cycle step admission), `cycle_apply` (row 3), `recover_interrupted`, supervisor. * `ON`: normal. `DRAIN`: no new cycles; ACTIVE cycles with live workers settle through row 3 and park; idle ACTIVE cycles park immediately (`STOPPED(OPERATOR_PARK)`, task REVIEW). `PARKED`: same, and also refuses resume/creation. * `AI_FACTORY_REVIEW_CYCLE=0` (env, read at process start) may **veto** `ON` but never raises: effective mode = most restrictive of env and DB. It never "forces legacy behaviour" and never changes any cycle into a legacy task. * Parked cycle tasks are `REVIEW` (not READY/WAITING), so legacy claim/`prepare_dependencies` cannot pick them. * **Code downgrade preflight** (`review_cycle --check-downgrade`, read-only) must report all of: mode `PARKED`; zero cycle executions QUEUED/RUNNING; zero `stop_requested`; zero reservations; zero cycle tasks in READY/RUNNING/WAITING; **zero open cycle tasks** whose status the old code would act on — old `decide()` accepts REVIEW/PAUSED/BLOCKED with a result and old selection claims READY, and no status exists that old code ignores; therefore any unresolved cycle task (STOPPED, or PASSED awaiting checkpoint) ⇒ **downgrade refused; owner first resolves it** (accept via the new guarded route, supersede, or cancel). Supervisor release/dispatch disabled during the window. An old-code dry run on a *copy* of the DB must show no cycle task selected or acceptable. Because downgrade is therefore rarely possible, the primary rollback is **`PARKED` mode with the new code retained**. * **Backup**: `sqlite3 data/factory.db ".backup "` (consistent snapshot), not a file copy; before the migration deploy, per `operating-model/02-security.md`. * Deploy: migrations additive; deploy code with mode `PARKED` (equivalent to off); restart **only** in an authorized idle window with no unrelated active work (REQ), using the existing `privileges/dispatcher_restart` helper; then `ON` via the console. This design does not authorize a restart. ## 9. Settings, capacity and selection [M] (B9) ### 9.1 Settings schema (project default and task override; same shape) ```json {"enabled": false, "executor": null, "reviewer": null, "max_revisions": 3, "criteria": [{"id": "AC1", "text": "…"}], "resources": [{"kind": "PATH", "key": "workspaces/x/out", "mode": "WRITE"}], "owner_intervention": {"add": []}} ``` * Merge: task value wins per field; **absent = inherit**; explicit `false` = disabled (overrides project `true`); `null` allowed only for `executor`/`reviewer` meaning auto-select; absent project value = `enabled:false`. Resolved **once at approval** into `snapshot.config`. * Validation (API and approve): unknown keys rejected; `enabled` must be boolean; `max_revisions` int 0..5 (default 3); `criteria` non-empty, unique ids, text ≤ 2000 chars, **required at approval** for enabled cycles (task-level criteria replace project-level; no concatenation); `resources` typed/valid (§5.1); `owner_intervention.add` ⊂ optional stop names; mandatory stops (§3.6) cannot be removed. * Pairing: `executor ∈ {codex, claude-code, deepseek (workspace under workspaces/)}`, `reviewer ∈ {codex, claude-code}` (capability allowlist, constant `CYCLE_CAPABLE`, extended only with a tested isolation profile); `reviewer ≠ executor`; auto: reviewer = other of {codex, claude-code} than the resolved executor; if executor is `deepseek`, reviewer = project primary if allowed else `codex`. Unsupported/identical pair ⇒ 400 at save and 409 at approve. `DENIED_PROJECTS` cannot enable. * Project-default changes affect only **future approvals** (snapshot immutable); enabling a project default creates no cycles retroactively and never touches already approved tasks. ### 9.2 Capacity (atomic with claim) Inside the `claim()` transaction, before INSERT: `SELECT COUNT(*) FROM executions WHERE status IN ('QUEUED','RUNNING') AND executor=?` compared to `CAPACITY = {claude-code:1, codex:MAX_WORKERS (3)}` (config `config/review_cycle.json`), across **all tasks and processes** (SQLite write lock makes it race-free; the existing `_CLAUDE_RUN_LOCK` stays as a backstop only). Full ⇒ return None, no attempt consumed. Applied to all claims while mode≠legacy-parity is a behaviour change for legacy Claude tasks (they queue as READY instead of sitting RUNNING on the lock) — functionally equivalent, called out in docs (OD-5 default: apply to all claims). ### 9.3 Selection `cycle()` replaces `LIMIT MAX_WORKERS` with an ordered scan (priority, id; paginated, bounded e.g. 200 rows): for each candidate call `claim()` sequentially; skip `None`; stop when `MAX_WORKERS` claims succeeded or candidates exhausted; then run the claimed tasks in the pool (`run_one` split into `claim` + `run_claimed`). A fourth eligible task behind three blocked candidates therefore runs. Waiting consumes no attempt (§4.2). ## 10. Documentation to update in place (REQ; no new standalone doc) `AI_FACTORY_ARCHITECTURE.md` (data model, lifecycle, recovery, concurrency), `Capabilities.md`, `FACTORY_RUNTIME.md` (Control Plane + Dispatcher + settings + examples), `FACTORY_SUPERVISOR.md` (step-scoped attempts, `CYCLE_MANAGED`), `TASK_SUBMISSION_RUNBOOK.md` (opt-in, criteria, structured handoff, verdict/response examples), `project-executor-policy.md` (reviewer pairing, capability allowlist), `control_plane/VERIFICATION.md` (frozen contract, acceptance predicate, configure guard), agent instructions (executor `responses` block; reviewer verdict block, read-only scratch rules), `operating-model/02-security.md` (reviewer isolation, residual network note). ## 11. Test matrix (offline; fake executors, in-memory/copy DB) — D1 rows 1-28 retained, plus the B-regressions Retained from D1 (names unchanged): legacy parity, first-pass PASS (genuine, **no** seeded failure), seeded defect → FAIL → fix → PASS, multiple revisions, exhaustion (STOPPED/REVIEW not FAILED), nonblocking only, invalid blocker downgraded, verification failure, technical vs content, reviewer independence, dispute, external blocker/OWNER_CHECKPOINT/scope/rights, idempotency, restart (mid-exec/mid-review/after-finalize), parallel branches, dependency release (checkpoint ⇒ ACCEPTED), supervisor, manual stop/resume/requirements, UI/API, migration on fresh and copied DB, real E2E. New, one or more per blocking group: | Id | Case | Expected | |---|---|---| | T-B1-1 | FAILED task, result present, no verification evidence, owner accept | 409; stays FAILED | | T-B1-2 | cycle task, verification failed/missing/stale, accept via `/decision`, `/status`, `/result` | all rejected; never ACCEPTED | | T-B1-3 | PASS + checkpoint | task REVIEW; dependant WAITING; after owner accept dependant READY | | T-B1-4 | manifest changed after PASS | `can_accept` false; re-verify once or `EVIDENCE_STALE` | | T-B1-5 | read-only review leaves producer `changed:true` baseline intact | PASS accepted | | T-B1-6 | contract/requirements changed | needs renewed approval + new run | | T-B2-1…7 | edit project defaults / stopped task's contract / attachment / executor assignment / workspace; resume; restart | old snapshot unchanged, edits 409 or future-only, resume uses exact snapshot, no dispatch before approval, snapshot created in approval tx (rollback ⇒ none) | | T-B3-1…8 | cycle↔legacy both arrival orders; parent↔child path; `a/out` vs `a/outside`; relative/absolute alias; symlink alias; existing live writer; stopped-but-still-running process; resume after outside change; unrelated branch still runs; aging | conflicts wait without attempt; no deadlock; unrelated proceeds | | T-B4-1…8 | wrapped reviewer: shell write, Edit tool, sibling path, symlink, write-then-restore, scratch test, verdict publication, probe failure, wrapper absent | writes denied; scratch ok; dispatcher publishes verdict; unavailable ⇒ fail closed STOPPED; hash check as secondary | | T-B5-1…8 | later revision with global attempt>5 starts at full step budget and low backoff; pinned executor + distinct reviewer; fallback never self-reviews; reviewer re-selected after execution fallback; malformed output ×3; restart mid-format-retry; claimless unavailable timeout; grants cannot exceed 5 or reset history; 40-launch cap | exact counters | | T-B6-1…8 | stop during execution/review; crash after stop request; stale worker outcome after requirements change; duplicate outcome; duplicate owner click; supervisor pass over STOPPED/superseded; cycle tasks never FAILED; owner `hold/revise/accept` through transitions | no resurrection, no dependency release | | T-B7-1…6 | mode DRAIN/PARKED in READY, RUNNING, backoff, REVIEW, checkpoint states; env veto; downgrade preflight refuses unsafe state; old-code dry run on copy; consistent backup | no legacy execution/acceptance of cycle tasks | | T-B8-1…8 | optional advice never scope-stops; source-only fix passes with unchanged output file; repeated verification failure stops at threshold without spending all revisions; paraphrased blocker same stable id; PASS evaluated before no-progress; dispute ruling flows; FAIL with no valid blocker = protocol error | correct stop reason each | | T-B9-1…8 | absent/false/true/null inheritance matrix; invalid fields/pairings; approved task unchanged by default change; simultaneous scoped+global claims; Claude capacity 1 across processes; fourth task behind three blocked candidates; deepseek as executor only under `workspaces/`; DENIED_PROJECTS | enforced | | E2E-1 | real Codex↔Claude (both pairings): genuine first-pass PASS; seeded defect fail-fix-pass; checkpoint/dependency release; technical retry; restart recovery (isolated harness or authorized idle window); wrapped real review incl. nested Codex | bounded counts, switch safety shown | Existing suites (46 control-plane/runtime, 123 executor) are historical results; they must be **re-run** at R5, not cited. The 12 outdated DeepSeek tests remain separate debt. ## 12. Risks (changes vs D1) | Risk | Mitigation | |---|---| | Nested Codex under bwrap unproven | R2 first gate; fallback flag inside wrapper; else Codex not a reviewer (fail closed) | | Localhost HTTP reachable from reviewer | documented residual; secondary hash check; no new service | | ROOT-workspace legacy tasks wait while an overlapping cycle is open | prefer `workspaces/` for cycle tasks; owner decision OD-2 | | Claude capacity 1 queues at READY instead of lock | equivalent throughput; documented | | Downgrade rarely possible | by design: `PARKED` is the rollback | | Step counters regress legacy | `step=None` ⇒ unchanged code path; parity test | | Perfectionist reviewer | validated blocker + stable ids + threshold 2 + revision cap | ## 13. Updated roadmap | Stage | Depends on | Output / exit gate | |---|---|---| | R0 | this v2 | Independent Codex re-review of v2 = PASS on B1–B9 (no unresolved safety exception); owner decisions OD-1…OD-5 recorded | | R1 Model & approval | R0 | Migrations (§3.1), snapshot-in-approval, `cycle_apply` + transition table, `can_accept`, finding/stable-id/no-progress logic, settings validation. Isolated tests T-B1, T-B2, T-B6, T-B8 green; legacy parity green | | R2 Admission & isolation | R1 | `claim()` admission (resources, capacity, scan), review wrapper + probe. **Gate 1:** real nested `codex exec` review under wrapper (or documented fallback/exclusion) with denied-write proof; T-B3, T-B4, T-B9 green; no starvation | | R3 Runtime integration | R1, R2 | Step budgets in claim/recovery/startup/supervisor; snapshot-driven prompts; owner routes through transitions; durable switch + downgrade preflight. T-B5, T-B7 green | | R4 Settings/UI + docs | R3 (docs drafted in parallel) | §7, §9 UI, in-place doc updates (§10), examples consistent with code | | R5 Independent offline acceptance | R4 | Different executor reviews code **and** docs; re-run existing suites + full §11 matrix on fresh/copy DBs; verdict PASS | | R6 Controlled deploy + real E2E | R5 + authorized idle window | Backup; deploy `PARKED`; enable; E2E-1; stop/switch safety shown | | R7 Optional pilot | R6 + refreshed active-task check + owner OK | New AI-NUMISMATIST-VALIDATION tasks only, no retroactive change | ## 14. Owner decisions (defaults proposed; owner may keep all) * OD-1 Reviewer pairing default: other of {codex, claude-code}. * OD-2 ROOT-workspace legacy tasks wait while an overlapping open cycle holds a reservation (default; cycles use dedicated `workspaces/` when possible). * OD-3 Permit `--sandbox danger-full-access` for Codex **only inside the read-only bwrap wrapper** if nested sandbox fails (default: yes; otherwise Codex is not a reviewer). * OD-4 Apply the verification acceptance guard also to legacy non-cycle tasks (default: yes, same two-line predicate; cycle feature does not depend on it). * OD-5 Executor-capacity check applies to all claims (default: yes). * Timing of R6 window and R7 pilot — separate approvals; nothing here authorizes restart or pilot. ## Сводка для владельца (повтор в конце файла) Итог: подготовлен полный пересмотренный дизайн v2; все девять блокирующих групп B1–B9 закрыты конкретными исправлениями с доказательствами из кода, есть матрица закрытия, обновлённая дорожная карта и тесты. Изоляция ревьюера выполнима без новых прав и сервисов: bubblewrap уже установлен и в пробе в /tmp запретил запись, sudo и remount. Проблемы: вложенный Codex внутри изоляции реальным запуском не проверен (первый шаг R2, иначе Codex не будет ревьюером); сетевой доступ ревьюера к localhost остаётся задокументированным остаточным риском; задачи в общем ROOT могут ждать при пересечении с открытым циклом. Решение: принять OD-1…OD-5 (в частности OD-3 — флаг Codex только внутри read-only обёртки — и OD-2); независимая повторная проверка Codex; окно деплоя и пилот согласовать отдельно после PASS реализации.