Task: automatic-review design v4 (owner-approved change of the reviewer isolation requirement) · Project: FACTORY-RUNTIME · Date: 2026-11-28
Inputs: automatic-review-requirements.md (REQ), review/automatic-review-design-v3.md (D3), review/automatic-review-design-review-v3.md (RV3, verdict PASS, design only). D1–D3 and RV–RV3 are preserved unchanged.
This file is the complete replacement design. Everything not listed in §0.1/§1.3 is carried over from D3 verbatim in substance.
Status: design only. No production code, production DB, service, permission, sandbox setting or restart was touched; no probe or test was run for v4.
After RV3 PASS the owner explicitly changed the reviewer-isolation requirement. This is an owner decision, not a design weakening discovered by the author, and it supersedes the D3 §6 (P1–P7, G1–G6) wording and RV3's "R2 must establish G1–G6" gate. An independent review of v4 must judge the reviewer-isolation design against the clauses below, not against D3 §6.
Revised requirement (scope: internal single-owner MVP):
Consequences removed from D3: P1 disposable CLI home, P2 no host mutation endpoint, P3 no control sockets, P6 per-launch isolation probe, gates G1–G6, status REVIEW_ISOLATION_UNAVAILABLE, approval 409 for unavailable isolation, invariant I8 as "OS-enforced". Consequences added: §6 below, new stop reasons REVIEWER_MODIFIED_ARTIFACTS (kept) and REVIEWER_STATE_VIOLATION (new), tests T-B4L-*, mandatory documentation edits (§10).
Note on §5.3 (preserved, not reviewer isolation): the isolated-resource-or-hold rule is a resource conflict control between the cycle and uncontrolled host writers and is kept as accepted in RV3. It does not require the reviewer itself to be physically isolated. The sentence that the reviewer mount protects nothing is now vacuous because there is no reviewer mount; the integrity check of §6.3 is detection only.
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):
executions.attempt stays monotonic only for its UNIQUE constraint (B5).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.
| 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]; 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 default | Admission 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 | §5 | T-B3-1…12 |
| B4 | Hash detection ≠ read-only | Accepted [M]; v3 completed it (C2); v4: requirement changed by owner (§0.1) — logical isolation | 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) | v4: injected role instructions + unchanged sandbox + integrity check + reject-and-stop; residual risks disclosed (v3 OS profile superseded by owner decision) | §6 | T-B4L-1…12 |
| 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 |
No RV finding is disputed as incorrect. Three refinements keep original scope and avoid over-correction:
can_accept finds the manifest digest changed.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.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).Historical (D3, RV3 PASS). Rows C2-a, C2-b, C2-c and "Gates vs requirements" are superseded by the owner-approved change in §0.1/§6; they are kept only to show what was replaced and are not v4 requirements. C1, C3 and the legacy clarification remain in force.
| Item | RV2 requirement | v3 correction | Where | Tests |
|---|---|---|---|---|
| C1-a | Write 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.1 | T-B3-9, T-B3-10 |
| C1-b | Reverse race must include QUEUED as well as RUNNING legacy executions | Cycle admission checks QUEUED+RUNNING legacy executions (same live-capacity definition as §9.2); legacy admission checks open cycle reservations | §5.2 | T-B3-11 |
| C1-c | Drop the claim that a read-only reviewer mount protects against host writers; require isolated workspace/resource or hold; keep disjoint parallelism | New §5.3: reviewer mount is not an integrity control against external writers; isolated resource required or cycle held (WAITING_ISOLATION); no global serialization | §5.3 | T-B3-12 |
| C2-a | Disposable per-review CLI home/config, only needed auth/settings, discarded; shared credential/config dirs read-only or hidden; nothing copied back; unavailable if impossible | Mandatory 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.2 | T-B4-9, T-B4-10 |
| C2-b | No host mutation endpoints, write-capable connectors or host control sockets; enforceable under existing permissions else REVIEW_ISOLATION_UNAVAILABLE; no new proxy service/permission | Mandatory 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.2 | T-B4-11, T-B4-12 |
| C2-c | Delete danger-full-access fallback and OD-3 default; keep existing sandbox; fail closed | Deleted. P4: existing CLI sandbox stays enabled; nested failure ⇒ that reviewer excluded or stop. OD-3 rewritten | §6.1 P4, §14 | T-B4-13 |
| C3 | Remove 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 unchanged | Removed; owner_intervention.add is empty/reserved, any value rejected; manual stop unchanged | §3.6, §9.1 | T-B8-9, T-B8-10, T-B9-9 |
| Legacy clarification | Preserve 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, §14 | T-B1-1a, T-B1-1b |
| Gates vs requirements | Separate 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, §13 | R2 |
| Closed groups | Preserve B1, B2, B5, B6, B7, B9 | Their 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 |
| Item | Owner requirement | v4 clause | Where | Tests |
|---|---|---|---|---|
| O1 | Logical isolation with mandatory automatically injected role instructions | Dispatcher builds the reviewer prompt; role block is injected by code, not left to task authors; review does not launch without it; block hash recorded | §6.1 | T-B4L-1, 2 |
| O2 | Existing sandbox unchanged; no bypass | Adapter sandbox/permission flags are asserted equal to the pre-change values; any flag diff fails a test | §6.2 | T-B4L-3 |
| O3 | Safe tests / scratch | Reviewer runs only non-mutating checks; test commands run in scratch copies/TMPDIR; declared-state tests use a copy or read-only access | §6.1(R3–R5) | T-B4L-4 |
| O4 | Before/after integrity checks of reviewed files and relevant declared state | Snapshot of manifest hashes plus declared DB/service state digests before launch and after exit | §6.3 | T-B4L-5…8 |
| O5 | Reject verdict and stop on mutation | Mismatch ⇒ verdict discarded, STOPPED(REVIEWER_MODIFIED_ARTIFACTS) (files) or REVIEWER_STATE_VIOLATION (state/forbidden action), no revision consumed, no auto-retry, no dependency release | §6.4 | T-B4L-5…9 |
| O6 | No physical isolation prerequisite; no new service/permission | §6.2: nothing required; D3 P1–P3, P6, G1–G6 removed; availability depends only on §6.6 tests | §6, §6.6 | T-B4L-10 |
| O7 | Document residual risks; no security-boundary claim | §6.5 list (untracked writes, write-restore, API mutation, others); mandatory wording in docs | §6.5, §10 | docs review R5 |
| O8 | Preserve v3 requirements, conflict controls, verification guards | §0.1 item 5; §§3–5, 7–9 unchanged except named edits | §0.1 | existing T-B1…B3, B5…B9 |
| O9 | Mandatory updates to runbook, context card, agent instructions, architecture | §10 list with required content, part of R4/R5 acceptance | §10 | R5 |
Defaults unchanged: 3 additional revisions (initial + 3), absolute ceiling 5; no new permission, service, paid resource or sandbox bypass.
tasks row. Cycle = durable state machine on it. Step = (revision r, phase p) with p ∈ {EXECUTION, REVIEW}; r=0 initial.revision.revision += 1; never sets task FAILED.COMPLETED/ACCEPTED only if can_accept (§3.4) holds. No exception.2*(max_revisions+1)*MAX_ATTEMPTS (default 40, absolute ceiling 60 with max_revisions=5); technical retries and format retries are inside step caps.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.
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 `<criterion> | <check 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).
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.can_accept(task) [M] (B1)True only if all hold, evaluated in one transaction:
cycle.snapshot_id is the highest version for the task, and tasks.approved_at ≥ snapshot.approved_at.acceptance_json.producer_execution_id is the latest COMPLETED EXECUTOR-role execution of the cycle, in the current revision.passed=true, digest equal to acceptance_json, and verification_json equals the snapshot's.manifest_sha256 (the producer's changed:true baseline is not compared against the reviewer's pre-review hash).producer_execution_id = (2), valid verdict PASS, reviewer ≠ producer executor.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.
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).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.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.stable_id = "<criterion_id>|<check id | target_ref>" 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.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_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.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.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.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. (v3/C3) STOP_ON_SUBSTANTIAL is deleted. No stop may be keyed to nonblocking findings: SUBSTANTIAL nonblocking findings and RECOMMENDATIONs are stored and shown in history and the owner summary, but never stop progress and never prevent PASS (REQ). The set of optional stops is empty; owner_intervention.add is reserved for future, REQ-consistent stops and any value is rejected at validation today. Manual owner stop (row 5) is always available. The no-progress threshold (two persisted opportunities) and the defaults max_revisions=3, ceiling 5 are unchanged.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 is instructed to write nothing outside scratch, §6.1; the dispatcher, not the reviewer, writes the verdict artifact). Executor revision prompt = snapshot + prior output + verification evidence + all open BLOCKING findings with evidence; required {"responses":[…]} block.
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.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.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).counts, unavailable, exhausted executors) filter by the step, not by task.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).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").{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).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.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).
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 expected to be safe because the reviewer is instructed not to write and mutation is detected (§6); a detected mutation stops the cycle instead of replaying; a revision replay re-runs on the workspace as left, never double-counting a revision (revision changes only in cycle_apply).
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.)
snapshot.resources_json = typed list [{kind:'PATH'|'DB'|'SERVICE', key, mode:'WRITE'|'READ'}] plus resources_complete:boolean. The reservation is:resources_complete=true: the declaration, which must cover every path the executor may write (source, tests, config, outputs) and all relevant DB/SERVICE resources. The author asserts completeness; approval validates only form/containment, not truth, which is why §5.3 exists;false/absent): conservative — PATH WRITE on the whole frozen workspace subtree, plus any declared DB/SERVICE. Contract file paths, sqlite checks and deliverable paths are merged in as a minimum floor (sqlite ⇒ DB; api ⇒ none). They never shrink the reservation.
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). A symlink along a declared path widens the reservation to its real target and the link itself. DB/SERVICE keys use exact typed equality.claim()Inside the existing BEGIN IMMEDIATE of claim() (after dependency/live checks, before INSERT of the execution), for every task:
resource_reservations row of another open cycle (state ACTIVE or STOPPED-with-live-process) has an overlapping key under the containment rule and either side is WRITE; or, for a cycle task, if any QUEUED or RUNNING legacy (or other-cycle) execution's write set overlaps (computed from the live row and its task; no table needed). QUEUED is included for the same reason §9.2 counts QUEUED+RUNNING as live: a claimed-but-not-started execution is already an admitted writer.WAITING_RESOURCE (rate-limited). Reservations are acquired all-or-nothing in the same transaction (no hold-and-wait ⇒ no deadlock).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; disjoint workspaces/resources keep running in parallel.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:
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; orROOT 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 integrity check (§6.3) is detection only; a mismatch discards the verdict and stops (§6.4). Because the reviewer is only logically isolated (v4), the "immutable copy" alternative above protects the reviewer input from host writers, not the reviewed state from the reviewer.
Scope: internal single-owner MVP. The control is procedural plus detective. It does not prevent a reviewing CLI from writing; it instructs, bounds and checks. It is not a security boundary (§6.5).
The dispatcher (never the task author, never the executor) appends a fixed reviewer role block to every REVIEW-step prompt. It is part of the prompt builder (§3.7); a REVIEW launch without it is refused in code (failure_class='REVIEW_ROLE_BLOCK_MISSING', cycle stops with an actionable reason). The block text lives in one versioned constant (REVIEWER_ROLE_BLOCK_V1), is not overridable by project/task settings, and its SHA-256 is stored in the review execution's metadata and in the verdict record. The block states, in substance:
data/ (including the database and artifacts), other workspaces, the home directory or any CLI config/credential directory. Do not call any mutation endpoint of the factory console or any other local or remote API (status/result/decision routes, POST/PUT/PATCH/DELETE to any service), do not change service, git or database state, do not install packages, do not touch credentials.TMPDIR/a fresh directory under /tmp) using a copy of the needed files, or in non-mutating mode. If a check would write into the reviewed workspace, DB or service, do not run it there; run it on a copy or report it as not verifiable.SELECT, GET, sqlite3 -readonly/mode=ro URI). Never run a command whose effect on reviewed state you cannot establish as read-only.self_reported_mutation field of the verdict; the dispatcher treats it as a violation (§6.4).--disallowedTools Edit,Write,NotebookEdit for Claude as defence in depth; Bash stays so tests can run). This is an additional instruction-level control and changes no sandbox flag.The same block is injected for every reviewer adapter (codex, claude-code) and for each retry of a review step. Prompt text is a convention the model may violate; it is why §6.3 exists and why §6.5 is mandatory reading.
--sandbox workspace-write … --add-dir WORKDIR; Claude --permission-mode acceptEdits with its current allowed tools, plus the optional --disallowedTools of R8). danger-full-access, permission-skip flags or any weakening are forbidden; a test asserts the final argv/flags equal the baseline except the R8 addition (T-B4L-3).Immediately before launching a REVIEW step the dispatcher records, and immediately after the process exits (success, failure or timeout) recomputes and compares:
DB resource is digested read-only (SQLite: PRAGMA data_version is not used; use a read-only connection and a hash of .dump-equivalent table checksums for the declared tables, or the file hash for a dedicated DB file); each declared SERVICE resource may declare a read-only fingerprint probe (an existing GET) whose result is compared. A resource with no fingerprint method is listed in the review record as unchecked (visible to the owner), never silently treated as checked.tasks, cycles, executions rows of the reviewed task and its dependants (status/version/result digests) must be unchanged except by the dispatcher's own transitions, so a console-route mutation by the reviewer is seen where it changes these rows.~/.codex/~/.claude-factory that are not expected to change in a run, excluding known session/cache files by an explicit allowlist (the allowlist is data, reviewed in R5).The check is read-only, uses existing tools, runs in the dispatcher process, and its result is recorded (review_integrity_json) with the list of checked and unchecked resources. A run whose "before" snapshot cannot be taken is not launched (it is an ordinary technical failure, retried within the step budget); an "after" check that cannot complete is treated as a violation-unknown ⇒ stop (§6.4), not as success.
self_reported_mutation, or a forbidden action observed in the reviewer transcript by a simple dispatcher scan (calls with mutating HTTP methods to loopback/console routes, rm/mv/> writes to non-scratch absolute paths in logged tool calls — best effort, not complete), ⇒ the verdict is discarded unread (not parsed into findings), the review execution is marked REJECTED_MUTATION, and the cycle moves by the §3.2 stop row to STOPPED(REVIEWER_MODIFIED_ARTIFACTS) for file changes or STOPPED(REVIEWER_STATE_VIOLATION) for state/control-plane/config changes, self-report or transcript violation.can_accept evidence (§3.4: changed bytes invalidate any earlier PASS and re-verification is required before accept).reject are idempotent and fenced like the other §3.2 stop rows (CAS version, idem_key='review:<exec>:mutation'); a stale reviewer outcome after the stop is ignored (B6 unchanged).The design does not claim that a reviewer cannot change anything. Residual risks the owner accepts for the internal single-owner MVP:
data/, home, /etc-like paths the process user can write, git metadata, caches) are not detected unless covered by §6.3 items 3–4.SERVICE/DB resources that were not declared or have no read-only fingerprint are unchecked; undeclared state is invisible.REVIEWER_MODIFIED_ARTIFACTS (safe direction; §5.3 hold reduces it).Consequences for the owner: acceptance of the MVP means accepting these risks for internal single-owner use. Do not use this reviewer logical isolation for untrusted content, multi-tenant use, or production-critical state without physical isolation (a future, separately authorized change). All documents in §10 must carry this statement; none may call the reviewer "sandboxed", "read-only enforced" or "secure".
An adapter is added to CYCLE_CAPABLE as a reviewer only if, in R2: (a) the injected block is present in the final prompt for first launch and retries (T-B4L-1, 2); (b) its sandbox flags equal the baseline (T-B4L-3); (c) the integrity check catches a real file create/modify/delete by a fake reviewer, a declared-DB change, a control-plane row change, a self-report, and rejects (T-B4L-5…9); (d) a real E2E review run completes with the integrity check "unchanged" (E2E-1). No probe of network or sockets is required or performed.
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.
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.REVIEW (not READY/WAITING), so legacy claim/prepare_dependencies cannot pick them.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.sqlite3 data/factory.db ".backup <file>" (consistent snapshot), not a file copy; before the migration deploy, per operating-model/02-security.md.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.{"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": []}}
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.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) and resources_complete boolean; owner_intervention.add must be [] (v3/C3: STOP_ON_SUBSTANTIAL and any nonblocking-finding stop removed; field reserved); mandatory stops (§3.6) cannot be removed.executor ∈ {codex, claude-code, deepseek (workspace under workspaces/)}, reviewer ∈ {codex, claude-code} (capability allowlist, constant CYCLE_CAPABLE, extended only for an adapter whose role-instruction injection and integrity-check tests pass, §6.6); 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 or identical pair ⇒ 400 at save and 409 at approve. DENIED_PROJECTS cannot enable.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).
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).
All edits are made during implementation (R4) in the existing documents, no duplicate docs, and are checked by the R5 independent review. Required common statements in every document touched: the cycle is opt-in; reviewer isolation is logical (role instructions + unchanged sandbox + integrity checks + stop on mutation) and not a security boundary; the §6.5 residual risks (untracked writes, write-and-restore, API/external mutation, undeclared state, prompt non-compliance); no document may say the reviewer is sandboxed, read-only enforced or secure.
| Document | Mandatory update |
|---|---|
Task Submission Runbook (TASK_SUBMISSION_RUNBOOK.md) | Opt-in and how to enable per project/task; criteria; declaring resources/resources_complete and why undeclared state is unchecked; instruct submitters to declare DB/SERVICE state that a review must not alter and, if possible, a read-only fingerprint; do not put instructions aimed at the reviewer in task text (role block is automatic, cannot be overridden); structured handoff, verdict/response examples; stop reasons REVIEWER_MODIFIED_ARTIFACTS / REVIEWER_STATE_VIOLATION with the owner actions (inspect evidence, restore manually if needed, resume or revise); residual-risk section; when not to use cycles (untrusted content, critical production state) |
| Context card (project context card / the context block the Factory attaches to tasks) | Short normative paragraph: reviewer must follow the role block R1–R8; executors must declare scope and answer findings with a responses block; cycle semantics (PASS ⇒ checkpoint; STOPPED ≠ failed); the isolation level and residual-risk one-liner in Russian and English; unchanged legacy behaviour |
Agent instructions (executor and reviewer instructions, project-executor-policy.md, adapter prompt templates) | Reviewer instruction = exact text of REVIEWER_ROLE_BLOCK_V1 (single source; docs quote it, code owns it); executor responses block; forbidden-action list; scratch/test rules; self-report duty; reviewer pairing and capability allowlist (conformance §6.6, not host isolation); statement that the sandbox is unchanged |
Architecture (AI_FACTORY_ARCHITECTURE.md; operating-model/02-security.md) | Data model (cycles, snapshots, reservations, review_integrity_json), lifecycle/transition table, recovery, concurrency/admission, §6 logical-isolation design and its explicit non-boundary status, residual-risk table, the owner decision that replaced physical isolation (date 2026-11-28, v4 §0.1) and the condition to revisit (untrusted content / multi-tenant / production-critical state), integrity-check coverage and unchecked-resource reporting |
Capabilities.md | Capability "automatic review cycle" with its isolation level and limits |
FACTORY_RUNTIME.md | Control Plane + Dispatcher behaviour, settings schema (§9.1), integrity-check configuration (size bound, CLI-state allowlist), examples |
FACTORY_SUPERVISOR.md | Step-scoped attempts, CYCLE_MANAGED, mutation stops are owner-only (no auto resume) |
control_plane/VERIFICATION.md | Frozen contract, acceptance predicate, configure guard, re-verification after changed bytes |
Acceptance rule: R5 fails if any listed document lacks the common statements, contradicts the code (flags, stop reasons, settings), or describes isolation as a security boundary.
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-1a | Legacy (non-cycle) FAILED task, result present, no verification evidence, owner accept | unchanged 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-1b | Cycle fixture task: FAILED/failed-verification execution, result present, owner accept | 409; never ACCEPTED (mandatory) |
| 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-B3-9 | legacy task whose contract checks out/result.md but edits src/worker.py; cycle reserving src/worker.py | conflict detected via workspace subtree; contract paths never used as write set |
| T-B3-10 | cycle with resources_complete=false vs true | false ⇒ whole workspace reserved; true ⇒ declared scope only (floor merged) |
| T-B3-11 | legacy execution QUEUED (claimed, not yet RUNNING) then cycle claim; and reverse | cycle waits; no overlap in either order |
| T-B3-12 | cycle on ROOT/shared workspace; cycle on dedicated workspaces/<key>; per-review manifest copy (protects reviewer input only, §5.3); disjoint cycles | shared ⇒ held WAITING_ISOLATION / 409; dedicated runs; disjoint run in parallel; no global serialization |
| T-B4L-1 | Build REVIEW prompt for codex and claude-code, first launch and each retry | role block present, hash recorded; block not overridable by task/project settings or task text |
| T-B4L-2 | Prompt builder with block removed / settings attempt to override | launch refused REVIEW_ROLE_BLOCK_MISSING; cycle stops with reason |
| T-B4L-3 | Compare final argv/sandbox/permission flags of both adapters with baseline | identical except optional --disallowedTools (R8); danger-full-access/skip flags rejected by test |
| T-B4L-4 | Reviewer test run policy: fake reviewer runs checks on a scratch copy | no change to reviewed state; integrity "unchanged"; declared-state test uses read-only access |
| T-B4L-5 | Fake reviewer modifies a manifest file; creates a file in declared scope; deletes a file | verdict discarded unread; STOPPED(REVIEWER_MODIFIED_ARTIFACTS); no revision consumed; task REVIEW, not FAILED; no dependency release |
| T-B4L-6 | Fake reviewer changes a declared DB table; mutates a control-plane row via test console route (test server/copy DB only) | STOPPED(REVIEWER_STATE_VIOLATION); verdict discarded |
| T-B4L-7 | Fake reviewer returns self_reported_mutation / transcript contains a mutating call to a console route | stop REVIEWER_STATE_VIOLATION; scan best-effort documented |
| T-B4L-8 | Reviewer touches persistent CLI state file listed in the allowlist vs a known session/cache file | listed ⇒ violation; allowlisted cache ⇒ ignored |
| T-B4L-9 | Mutation stop: restart mid-stop, duplicate outcome, stale outcome after stop, owner resume | idempotent; no auto retry; resume uses fresh baseline and requires renewed can_accept evidence |
| T-B4L-10 | Host without bwrap/netns/egress helper (simulated), reviewer still launches | no isolation prerequisite; review runs; no new service/permission referenced |
| T-B4L-11 | Documented limits (negative-expectation tests): write-and-restore, write outside manifest/declared scope, API call without fingerprint effect | not detected; test asserts the review record lists the resource as unchecked or marks coverage limits and that docs state the limit (guards against overclaiming) |
| T-B4L-12 | Concurrent uncontrolled writer changes reviewed file during review | false-positive stop (safe); event explains possible external writer |
| T-DOC-1 | Docs lint in R5: runbook, context card, agent instructions, architecture contain the common statements (§10) and the exact role block; none contains "security boundary" as a claim, "sandboxed reviewer", "read-only enforced" | pass |
| 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-B8-9 | review with only SUBSTANTIAL/RECOMMENDATION findings, several revisions' worth | never stops, never blocks PASS; shown in summary |
| T-B8-10 | owner_intervention.add=["STOP_ON_SUBSTANTIAL"] or any value | rejected at validation (400) |
| 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 |
| T-B9-9 | settings schema with removed stop / unknown keys | rejected; mandatory stops intact |
| 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); real review with role block and integrity check "unchanged" for both reviewers; injected mutation test on a copy | 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.
| Risk | Mitigation / status |
|---|---|
| Reviewer can mutate state; isolation is logical only (owner-accepted, §0.1) | Mandatory role block, unchanged sandbox, before/after integrity checks, reject-and-stop, mandatory disclosure of §6.5 in all docs; revisit with physical isolation if scope grows to untrusted/multi-tenant/critical use |
| Undetected mutation (untracked writes, write-and-restore, API) | Accepted residual risk (§6.5); declared state fingerprints reduce it; unchecked resources are shown to the owner |
| False-positive stops from uncontrolled host writers | Safe direction; §5.3 isolated-resource rule; owner resume |
| Overclaiming safety in documents | §10 acceptance rule and T-DOC-1 |
| ROOT/shared-workspace tasks wait or cannot host cycles | cycles require isolated resources (§5.3); conservative reservation affects only overlapping tasks; 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 |
Removed from D3: infeasible-profile and no-reviewer-capability risks (no physical prerequisite remains).
| Stage | Depends on | Output / exit gate |
|---|---|---|
| R0 | this v4 | Independent re-review of v4 against the revised owner requirement (§0.1) = PASS; owner decisions OD-1…OD-6 recorded. D3 §6/G1–G6 are not review criteria |
| R1 Model & approval | R0 | Migrations (§3.1, plus review_integrity_json), snapshot-in-approval, cycle_apply + transition table (incl. mutation stop reasons), can_accept, finding/stable-id/no-progress logic, settings validation. T-B1, T-B2, T-B6, T-B8 green; legacy parity green |
| R2 Admission & logical reviewer isolation | R1 | claim() admission (resources, capacity, scan); REVIEWER_ROLE_BLOCK_V1 injection; integrity check and mutation stop (§6.3–6.4); §6.6 conformance. T-B3, T-B4L, T-B9 green; no starvation. No probe/wrapper/permission work |
| 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 + mandatory docs | R3 (docs drafted in parallel) | §7, §9 UI; in-place updates of runbook, context card, agent instructions, architecture and the rest of §10 with the residual-risk statements; examples consistent with code |
| R5 Independent offline acceptance | R4 | Different executor reviews code and docs (T-DOC-1 + manual read); re-run existing suites (46 control-plane/runtime, 123 executor) + full §11 matrix on fresh/copy DBs; verdict PASS. Historical results are not cited |
| 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 |
The owner-approved change (§0.1) is applied: §6 is rewritten as logical reviewer isolation (injected role block, unchanged sandbox, scratch/safe tests, before/after integrity checks, reject-and-stop), D3 physical-isolation properties and gates are removed, residual risks are disclosed (§6.5), and mandatory documentation updates are specified (§10). B1, B2, B5, B6, B7, B9, C1 resource controls, C3 and the verification guards are untouched. No production code, permission, service, sandbox change or restart is made or required; this is a design deliverable only.
Итог: подготовлен полный дизайн v4 по вашему изменению: логическая изоляция ревьюера (автоматически вставляемые обязательные инструкции роли, прежний sandbox без изменений, безопасные тесты в scratch, проверки целостности файлов и объявленного состояния до/после, отклонение вердикта и остановка при мутации); без физической изоляции, новых сервисов и прав; остаточные риски описаны, граница безопасности не заявляется; roadmap и обязательные правки runbook, context card, инструкций агентов и архитектуры указаны.
Проблемы: нет; остаточные риски (незамеченные записи, запись с восстановлением, мутация через API) приняты вами и должны быть записаны в документации.
Решение: подтвердить OD-6 (покрытие проверки целостности и ручное возобновление после остановки) и отправить v4 на независимую проверку по изменённому требованию. Код, рестарт и деплой не требуются.