← Назад к задаче

automatic-review-design-v3.md

Automatic Execution + Independent Review Cycle — Design v3

Task: automatic-review design v3 (targeted corrections C1–C3 + legacy-test clarification) · Project: FACTORY-RUNTIME · Date: 2026-11-28
Inputs (read in full): automatic-review-requirements.md (REQ), review/automatic-review-design-v2.md (D2), review/automatic-review-design-review-v2.md (RV2, verdict FAIL: B3/B4/B8 partially open via C1–C3; B1, B2, B5, B6, B7, B9 CLOSED). D1, D2, RV and RV2 are preserved unchanged.
This file is the complete replacement design. Everything not listed in §1.2 is carried over from D2 verbatim in substance; only the clauses named in §1.2 changed.
Status: design only. No production code, production DB, service, permission or restart was touched; no probe was run for v3 (v2's reported probes are labelled as prior evidence in §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; v3: write scope is a complete declaration or a conservative workspace reservation (never contract paths), QUEUED+RUNNING are both checked, and uncontrolled writers require an isolated resource or a hold (B3/C1).
  4. Reviewer isolation is enforced by the OS (bubblewrap read-only root + scratch tmpfs); v3: with a disposable per-review CLI home, no reachable host mutation endpoint/control socket, the existing CLI sandbox retained (no bypass), and fail-closed REVIEW_ISOLATION_UNAVAILABLE when the profile cannot be built under existing permissions (B4/C2).
  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.

v3 delta (RV2): C1 (§5), C2 (§6), C3 (§3.6, §9.1), legacy-acceptance default and T-B1-1 clarification (§3.4, §11, OD-4), and a new separation of design requirements from implementation feasibility gates (§6.4, §13). Six groups already CLOSED by RV2 (B1, B2, B5, B6, B7, B9) are not reopened; see §1.2.

1. B1–B9 closure matrix

BRV findingDecisionEvidence from actual code (verified this task)v2 correctionWhereTest ids
B1Failed verification can be bypassed by manual acceptAccepted [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 statusShared predicate can_accept(task) (§3.4) called by apply_outcome and by decide('accept'); D1 I1 "explicit owner accept" exception removed§3.4, §7T-B1-1…6
B2Snapshot incomplete, not consistently used, created before approvalAccepted [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.5T-B2-1…7
B3Leases ignore legacy writers and path overlapAccepted [M]; v3 completes it (C1)claim() performs no resource check; l.110 default workspace is ROOT for codex/claude-code, so legacy tasks are broad writers by defaultAdmission check inside claim()'s existing BEGIN IMMEDIATE for all tasks; typed keys, canonical paths, component-wise containment; write set = complete declaration or conservative workspace reservation; QUEUED+RUNNING both checked; isolated resource for uncontrolled writers§5T-B3-1…12
B4Hash detection ≠ read-onlyAccepted [M]; v3 completes it (C2)executors/codex.py command uses --sandbox workspace-write … --add-dir WORKDIR; executors/claude_code.py uses --permission-mode acceptEdits --allowedTools Read,Bash,Edit,Write,…; subscription_env() selects /home/iovon/.claude-factory (shared persistent state)Review profile: executor CLI under bwrap read-only root, disposable per-review CLI home, no reachable host mutation endpoint/control socket, existing sandbox retained, fail closed§6T-B4-1…14
B5Step budgets/recovery semanticsAccepted [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 countsstep_attempt column, step-scoped history, recovery_decision(..., step=…); reviewer policy separate from task pin; exact launch caps§4T-B5-1…8
B6Stop/recovery/supersession incoherentAccepted [M]record_recovery checks only tasks.status; supervisor.eligible never reads cycles; /tasks/{id}/status, /decision mutate task status directlySingle transition table with fence precedence, CAS version, idempotency key; all owner routes call it; cycle tasks never end FAILED§3.2–§3.3, §7T-B6-1…8
B7Kill switch authorises unsafe legacy pathAccepted [M]D1 §3.1/§9; legacy ready query claims any READY row; legacy decide accepts any REVIEW/PAUSED/BLOCKED task with a resultDurable review_cycle_control.mode (ON / DRAIN / PARKED); never "legacy"; defined downgrade preflight; consistent backup§8T-B7-1…6
B8No-progress/non-blocking mis-stopsAccepted [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.6T-B8-1…8
B9Settings, capacity, selectionAccepted [M]; one claim in RV corrected in the same directionruntime.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 modulesExact settings schema; DB-level capacity inside claim(); scan-until-filled selection; capability allowlist not derived from "text-only" labels§9T-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 write sets (v3 supersedes the D2 refinement). D2 let a legacy task's contract file paths stand in for its write set; RV2 correctly showed a contract lists checked outputs, not every write (a task can check out/result.md yet edit src/worker.py). v3 therefore uses an explicit complete declaration when available and otherwise the whole workspace subtree, for legacy and cycle tasks alike (§5.2). The earlier throughput concern (REQ "independent branches continue") is preserved differently: only tasks whose workspace/declared scope actually overlaps wait; tasks in disjoint workspaces (e.g. workspaces/a vs workspaces/b) run in parallel, no global serialization. The throughput cost to ROOT-workspace legacy tasks while an overlapping cycle is open is disclosed and an owner decision (OD-2). Untracked external writers cannot be controlled by any lease; for them v3 requires an isolated resource or holds the cycle (§5.3) — it no longer claims that review isolation protects against them.
  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).

1.2 v3 closure matrix (RV2 C1–C3 and clarification)

ItemRV2 requirementv3 correctionWhereTests
C1-aWrite set must not be contract paths; use complete declared scope else conservative workspace reservation (cycle and legacy)Contract paths are only a floor; cycle needs resources_complete:true declaration covering source/test/config/output/DB/service, else the whole workspace subtree is reserved; legacy with no declaration = workspace subtree§5.1, §5.2, §9.1T-B3-9, T-B3-10
C1-bReverse race must include QUEUED as well as RUNNING legacy executionsCycle admission checks QUEUED+RUNNING legacy executions (same live-capacity definition as §9.2); legacy admission checks open cycle reservations§5.2T-B3-11
C1-cDrop the claim that a read-only reviewer mount protects against host writers; require isolated workspace/resource or hold; keep disjoint parallelismNew §5.3: reviewer mount is not an integrity control against external writers; isolated resource required or cycle held (WAITING_ISOLATION); no global serialization§5.3T-B3-12
C2-aDisposable per-review CLI home/config, only needed auth/settings, discarded; shared credential/config dirs read-only or hidden; nothing copied back; unavailable if impossibleMandatory profile property P1; ~/.codex/~/.claude-factory hidden, per-review copy of the minimum files on scratch tmpfs; adapter needing persistent auth writes ⇒ capability unavailable§6.1 P1, §6.2T-B4-9, T-B4-10
C2-bNo host mutation endpoints, write-capable connectors or host control sockets; enforceable under existing permissions else REVIEW_ISOLATION_UNAVAILABLE; no new proxy service/permissionMandatory properties P2–P3 (network and filesystem/abstract sockets); pre-launch denial probe; unavailable ⇒ fail closed; prompt promises/hashes explicitly not a control§6.1 P2–P3, §6.2T-B4-11, T-B4-12
C2-cDelete danger-full-access fallback and OD-3 default; keep existing sandbox; fail closedDeleted. P4: existing CLI sandbox stays enabled; nested failure ⇒ that reviewer excluded or stop. OD-3 rewritten§6.1 P4, §14T-B4-13
C3Remove STOP_ON_SUBSTANTIAL from §3.6 and §9; substantial nonblocking never stops or blocks PASS; keep 3 additional revisions, ceiling 5; two-opportunity no-progress threshold unchangedRemoved; owner_intervention.add is empty/reserved, any value rejected; manual stop unchanged§3.6, §9.1T-B8-9, T-B8-10, T-B9-9
Legacy clarificationPreserve legacy acceptance by default; T-B1-1 conditional on optional legacy hardening or a cycle fixture§3.4 default: legacy acceptance unchanged; hardening only under separately authorized OD-4 (default no); T-B1-1 split§3.4, §11, §14T-B1-1a, T-B1-1b
Gates vs requirementsSeparate implementation feasibility gates from design requirements§6.4 lists gates G1–G6 as R2 exit gates; gate failure ⇒ profile unavailable (fail closed), not a design defect§6.4, §13R2
Closed groupsPreserve B1, B2, B5, B6, B7, B9Their clauses unchanged except the two named consequential edits: §3.4 legacy default wording (B1, no behaviour change vs RV2) and the owner_intervention list in §9.1 (B9, as RV2 required)—existing T-B1/B2/B5/B6/B7/B9

Defaults unchanged: 3 additional revisions (initial + 3), absolute ceiling 5; no new permission, service, paid resource or sandbox bypass.

2. Concepts and invariants (unchanged from D1 unless marked)

3. Data model and lifecycle

3.1 Schema (additive; all via MIGRATIONS / CREATE IF NOT EXISTS, init_db() idempotent)

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:<execution_id>' | 'owner:<cycle_id>:<cycle.version>:<action>' | 'sys:<cycle_id>:<ver>:<kind>'
 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): '<criterion_id>|<check_id or target_ref>'
 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
0idem_key already in cycle_transitionsno-op, return recorded result
1Trigger 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
2Cycle state ∈ {SUPERSEDED, CANCELLED, PASSED}Same as 1 (record only)
3stop_requested=1 or control.mode ∈ {DRAIN, PARKED} and trigger is a worker outcomeRecord 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
4Trigger = owner change requirementscycle 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")
5Trigger = owner stopno live execution → STOPPED(MANUAL_STOP) now; live → stop_requested=1 only (settles at row 3); the CAS makes a duplicate click a no-op
6Trigger = 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
7Outcome = 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)
8Outcome = FACTORY_OUTCOME: OWNER_CHECKPOINT`STOPPED(BUSINESS_DECISION\EXTERNAL_BLOCKER), task REVIEW, checkpoint=1` (existing path)
9EXECUTION ok + verification passedphase=REVIEW; store producer_execution_id, manifest_sha256, verification artifact id+sha in acceptance_json; task READY
10EXECUTION ok + verification failedVERIFICATION findings (stable id `<criterion><check id>`); go to row 14 (content FAIL) — no review spent
11REVIEW verdict structurally invalid / no valid blocker with FAILREVIEW_FORMAT retry in step (§4.3), then STOPPED(REVIEW_OUTPUT_INVALID)
12REVIEW verdict PASS and can_accept holdscycle PASSED; task COMPLETED, or REVIEW if checkpoint=1 (owner accept then only resolves the checkpoint). Evaluated before no-progress. Recommendations are stored, never block
13REVIEW PASS but can_accept fails (stale/missing verification, manifest drift)re-run verification once for the producer (if inputs unchanged); else STOPPED(EVIDENCE_STALE)
14content 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_LIMITelse 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

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; /tasks/{id}/status and /result reject setting ACCEPTED/COMPLETED (already true) and, for cycle tasks, any status change not produced by cycle_apply (I7). Legacy (non-cycle) tasks keep today's acceptance behaviour by default (see below). 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 (v3 clarification): RV showed decide() accepts a FAILED legacy task with no verification evidence. This cycle change preserves legacy acceptance behaviour by default; the guard is mandatory for cycle tasks only. Hardening legacy acceptance (same two-line predicate: latest verification artifact exists and passed, unless executor='human'/contract absent as today) is optional [O], needs separate explicit owner authorization (OD-4, default no), and the cycle feature does not depend on it.

3.5 Frozen approval [M] (B2)

3.6 Findings, no-progress, scope [M] (B8)

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

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):

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 Write scope, declaration and canonicalization (v3/C1)

A verification contract lists checked outputs, not every source/config/test/DB write; it is never accepted as the write set. (Example: a task checks out/result.md but edits src/worker.py.)

Contract file paths, sqlite checks and deliverable paths are merged in as a minimum floor (sqlite ⇒ DB; api ⇒ none). They never shrink the reservation.

5.2 Admission in claim()

Inside the existing BEGIN IMMEDIATE of claim() (after dependency/live checks, before INSERT of the execution), for every task:

5.3 Uncontrolled writers and isolated resources (v3/C1)

Leases only govern dispatcher claims. An uncontrolled writer is any host process that can write a reserved scope without passing claim() (human edits, cron, external services, non-dispatcher scripts). A read-only reviewer mount restricts the reviewer's writes only; it does not stop such a process from changing the underlying files during review, so it is not an integrity control against them (D2's claim is withdrawn).

Requirement: a cycle is dispatched only if every reserved resource is an isolated resource, else it is held (task READY/REVIEW per state, event WAITING_ISOLATION, owner summary names the shared resource; approval returns 409 ISOLATED_RESOURCE_REQUIRED when this is already knowable). Isolated means one of:

  1. a dedicated workspace workspaces/<key> used only by this task's cycle (no other open task, not a parent/child of another workspace or reservation), and DB/SERVICE resources likewise dedicated to the cycle; or
  2. for file-only review state: a per-review immutable copy of the producer's manifest taken at review start on scratch and hash-verified, so the reviewer reads a copy no host writer can touch.

ROOT and any shared workspace are not isolated by definition (a broad host writer may use them); recommending a subdirectory is insufficient while such a writer exists. Parallel execution of demonstrably disjoint isolated resources is unchanged. The before/after manifest hash check (§6.2) stays as secondary detection; a mismatch discards the verdict.

6. Reviewer isolation using existing permissions [M] (B4 — v3: C2)

6.1 Mandatory profile properties (design requirements)

During a REVIEW step the reviewing process (and everything it spawns) must satisfy all of:

Executor-phase processes are not wrapped (they must write); only REVIEW is.

6.2 Profile shape (illustrative; the properties above are normative)

bwrap --ro-bind / / --dev /dev --proc /proc --tmpfs /tmp --tmpfs /run --tmpfs /var/run \
      --tmpfs <real-cli-home> --bind <scratch>/cli-home <cli-home-path-used-by-CLI> \
      --unshare-pid --unshare-ipc --unshare-net --new-session --die-with-parent \
      <existing executor argv, existing sandbox flags unchanged, CLI home env -> scratch>

6.3 Prior evidence (reported, not repeated for v3)

D2 recorded (reported, /tmp-only probes): bwrap --ro-bind / / denied writes to workspace/data//home, allowed /tmp; NoNewPrivs=1 refused sudo; remount refused; claude --version, codex exec --help ran inside the wrapper. RV2 independently confirmed only that the minimal bwrap command exits 0 (/usr/bin/bwrap, unprivileged user namespaces enabled). Corrections to D2's reading of that evidence: (i) D2 observed that the model API is reachable with the host network namespace — which is exactly what exposes host mutation endpoints; it is evidence of the problem, not of acceptability; (ii) masking only /run/dbus is not a socket boundary; (iii) D2's residual (b) "network access to localhost is a documented residual risk" is withdrawn; (iv) the danger-full-access fallback is withdrawn. The nested codex sandbox linux probe remained inconclusive.

6.4 Implementation feasibility gates (NOT design requirements)

The design is complete once §6.1 is mandated. Whether this host can realise a profile is established at R2; failure of a gate makes that reviewer capability unavailable (fail closed), never a weakened profile, and is not a design failure.

GateQuestionPassFailure outcome
G1Does real codex exec run nested in the profile with its inner sandbox enabled?review completes, writes deniedCodex not a reviewer
G2Does real claude run nested with a disposable config home?review completesClaude not a reviewer
G3Do both CLIs authenticate from a minimal per-review config copy without needing persistent auth writes?yes, no copy-backcapability unavailable
G4Is there an existing-permission, already-installed network arrangement giving model API egress without host loopback/mutation endpoints?probes P2 passno reviewer capability; cycles cannot enable (approval 409 REVIEW_ISOLATION_UNAVAILABLE)
G5Does socket enumeration (filesystem + abstract) show none reachable?nonecapability unavailable
G6Do denial probes (workspace/data/real CLI home write, loopback connect, socket connect, sudo, remount) all fail while scratch writes work, in the wrapped real CLI?all as expectedcapability unavailable

Pairing validation (§9.1) consults the most recent gate/probe result; the per-launch probe (P6) is authoritative. If one reviewer capability is available (e.g. only Claude), only pairings using it can be enabled.

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:<cycle>:<version>:<action>'. /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)

9. Settings, capacity and selection [M] (B9)

9.1 Settings schema (project default and task override; same shape)

{"enabled": false,
 "executor": null, "reviewer": null,
 "max_revisions": 3,
 "criteria": [{"id": "AC1", "text": "…"}],
 "resources": [{"kind": "PATH", "key": "workspaces/x", "mode": "WRITE"}], "resources_complete": false,
 "owner_intervention": {"add": []}}

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, network/socket isolation requirement).

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:

IdCaseExpected
T-B1-1aLegacy (non-cycle) FAILED task, result present, no verification evidence, owner acceptunchanged legacy behaviour by default; conditional test: asserts 409 only if optional legacy hardening (OD-4) is separately authorized and enabled. Not a cycle acceptance gate
T-B1-1bCycle fixture task: FAILED/failed-verification execution, result present, owner accept409; never ACCEPTED (mandatory)
T-B1-2cycle task, verification failed/missing/stale, accept via /decision, /status, /resultall rejected; never ACCEPTED
T-B1-3PASS + checkpointtask REVIEW; dependant WAITING; after owner accept dependant READY
T-B1-4manifest changed after PASScan_accept false; re-verify once or EVIDENCE_STALE
T-B1-5read-only review leaves producer changed:true baseline intactPASS accepted
T-B1-6contract/requirements changedneeds renewed approval + new run
T-B2-1…7edit project defaults / stopped task's contract / attachment / executor assignment / workspace; resume; restartold 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…8cycle↔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; agingconflicts wait without attempt; no deadlock; unrelated proceeds
T-B3-9legacy task whose contract checks out/result.md but edits src/worker.py; cycle reserving src/worker.pyconflict detected via workspace subtree; contract paths never used as write set
T-B3-10cycle with resources_complete=false vs truefalse ⇒ whole workspace reserved; true ⇒ declared scope only (floor merged)
T-B3-11legacy execution QUEUED (claimed, not yet RUNNING) then cycle claim; and reversecycle waits; no overlap in either order
T-B3-12cycle on ROOT/shared workspace; cycle on dedicated workspaces/<key>; per-review manifest copy; disjoint cyclesshared ⇒ held WAITING_ISOLATION / 409; dedicated runs; disjoint run in parallel; no global serialization
T-B4-1…8wrapped reviewer: shell write, Edit tool, sibling path, symlink, write-then-restore, scratch test, verdict publication, probe failure, wrapper absentwrites denied; scratch ok; dispatcher publishes verdict; unavailable ⇒ fail closed STOPPED; hash check as secondary
T-B4-9reviewer writes to its CLI homelands in disposable home; real ~/.codex/~/.claude-factory byte-identical after; home discarded
T-B4-10adapter requiring persistent auth writecapability unavailable, REVIEW_ISOLATION_UNAVAILABLE
T-B4-11reviewer connects to host loopback console (/tasks/{id}/status, /result) and decision routes (against a test server only)connection denied; no state change
T-B4-12reviewer connects to filesystem/abstract control socketsdenied; probe enumerates none reachable; probe failure ⇒ fail closed
T-B4-13profile build with inner sandbox disabled / danger-full-access requestedrefused by code; REVIEW_ISOLATION_UNAVAILABLE
T-B4-14prompt asks reviewer to call localhoststill denied (control is enforcement, not prompt)
T-B5-1…8later 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 capexact counters
T-B6-1…8stop 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 transitionsno resurrection, no dependency release
T-B7-1…6mode DRAIN/PARKED in READY, RUNNING, backoff, REVIEW, checkpoint states; env veto; downgrade preflight refuses unsafe state; old-code dry run on copy; consistent backupno legacy execution/acceptance of cycle tasks
T-B8-1…8optional 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 errorcorrect stop reason each
T-B8-9review with only SUBSTANTIAL/RECOMMENDATION findings, several revisions' worthnever stops, never blocks PASS; shown in summary
T-B8-10owner_intervention.add=["STOP_ON_SUBSTANTIAL"] or any valuerejected at validation (400)
T-B9-1…8absent/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_PROJECTSenforced
T-B9-9settings schema with removed stop / unknown keysrejected; mandatory stops intact
E2E-1real 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 Codexbounded 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)

RiskMitigation
Reviewer profile infeasible on this host (nested CLI, disposable auth, network egress without host loopback)§6.4 gates G1–G6 at R2; per-launch probe; unavailable ⇒ fail closed; no bypass, no new service
Cycles cannot be enabled if no reviewer capability passes the gatesvalid fail-closed outcome; owner informed; legacy flow unaffected
ROOT/shared-workspace tasks wait or cannot host cyclescycles require isolated resources (§5.3); conservative reservation only affects overlapping tasks; OD-2
Claude capacity 1 queues at READY instead of lockequivalent throughput; documented
Downgrade rarely possibleby design: PARKED is the rollback
Step counters regress legacystep=None ⇒ unchanged code path; parity test
Perfectionist reviewervalidated blocker + stable ids + threshold 2 + revision cap

13. Updated roadmap

StageDepends onOutput / exit gate
R0this v3Independent Codex re-review of the changed clauses (§1.2) and closure matrix = PASS; owner decisions OD-1…OD-5 recorded
R1 Model & approvalR0Migrations (§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 & isolationR1claim() admission (resources, capacity, scan), review profile + probe. Feasibility gates G1–G6 (§6.4) evaluated on the real host with real nested CLIs and denial proofs; T-B3, T-B4, T-B9 green; no starvation. Gate failure ⇒ capability unavailable, documented, not a weaker profile
R3 Runtime integrationR1, R2Step 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 + docsR3 (docs drafted in parallel)§7, §9 UI, in-place doc updates (§10), examples consistent with code
R5 Independent offline acceptanceR4Different executor reviews code and docs; re-run existing suites + full §11 matrix on fresh/copy DBs; verdict PASS
R6 Controlled deploy + real E2ER5 + authorized idle windowBackup; deploy PARKED; enable; E2E-1; stop/switch safety shown
R7 Optional pilotR6 + refreshed active-task check + owner OKNew AI-NUMISMATIST-VALIDATION tasks only, no retroactive change

14. Owner decisions (defaults proposed; owner may keep all)

Closure summary (v3)

C1, C2, C3 and the legacy test clarification are applied as listed in §1.2; B1, B2, B5, B6, B7, B9 are untouched in substance. Implementation feasibility (§6.4) is deliberately separate from the design requirements. No production change, permission, service, restart or sandbox bypass is introduced.

Сводка для владельца (повтор в конце файла)

Итог: подготовлен полный дизайн v3 с поправками C1–C3: полный объявленный набор записи или резервирование всего рабочего каталога, проверка QUEUED и RUNNING, изолированные ресурсы для неконтролируемых писателей; одноразовая конфигурация ревьюера без доступа к управляющим эндпоинтам и сокетам хоста, действующий sandbox сохранён, при невозможности изоляции — остановка; STOP_ON_SUBSTANTIAL удалён.
Проблемы: нет проблем дизайна; осуществимость профиля (вложенные Codex/Claude, сетевой доступ без localhost) проверяется отдельно на этапе R2, при неудаче возможность ревью просто недоступна.
Решение: подтвердить OD-2, OD-3 (без обхода sandbox) и OD-4 (по умолчанию нет); отправить v3 на независимую повторную проверку изменённых пунктов. Деплой и перезапуск не требуются.

Материалы