# Automatic Execution + Independent Review Cycle — Design Task: FR-AUTO-REVIEW-DESIGN-001 · Project: FACTORY-RUNTIME · Date: 2026-11-28 Input: `data/project_materials/FACTORY-RUNTIME/automatic-review-requirements.md` (read in full; referred to as **REQ**). Status: design only. No production code, DB, service or restart was touched (DB queried read-only with `sqlite3 -readonly`). ## 0. Summary One logical task keeps one `tasks` row. A new opt-in **review cycle** drives it through `EXECUTION → (dispatcher verification) → REVIEW → [FAIL → REVISION → …] → PASS`. Reviews and revisions are extra `executions` rows tagged with `cycle_id/revision/phase`. They are not extra tasks, which is how the owner currently has to build them (the `*-CLAUDE` / `*-REVIEW` task pairs in AI-NUMISMATIST-VALIDATION). The task status stays `READY`/`RUNNING` while the cycle is active. Dependants therefore wait with **no change to dependency gating**, because it only releases on `COMPLETED`/`ACCEPTED`. Technical retry (existing `runtime.record_recovery`) and content revision (new) have separate counters and separate state. Everything is additive and off by default. With `enabled=false` the code path is byte-for-byte the legacy path. ## 1. Evidence: what exists today (read, not assumed) | Area | Fact (file) | Consequence for the design | |---|---|---| | Schema | `control_plane/schema.sql`: `tasks`, `executions UNIQUE(task_id,attempt)`, `artifacts`, `events`, `task_dependencies`. Additive columns via `MIGRATIONS` in `db.py`, `init_db()` is idempotent and runs at service start. | New tables/columns use the same additive mechanism. No destructive migration is needed. | | Claim | `dispatcher/control_plane_dispatcher.py:62-126` `claim()`: `BEGIN IMMEDIATE`; requires `READY`, dependencies COMPLETED/ACCEPTED (and `checkpoint=1` ⇒ ACCEPTED only); refuses a live execution; **`prior>=max_attempts` where `prior=COUNT(*) FROM executions WHERE task_id`** (l.86-91) ⇒ FAILED. | Reviews and revisions would burn the technical retry budget (5). The budget must be scoped per cycle step. This is the main compatibility trap. | | Finalize | `run_one()` l.167-322: executor runs outside any transaction; finalization is one `BEGIN IMMEDIATE`. Verification runs in-line (`verification.verify`); a failed verification becomes `FAILED` + `TASK_OR_VALIDATION`, which `recovery_decision` maps to `FAILED/OWNER_DECISION` (not retried). `FACTORY_OUTCOME: OWNER_CHECKPOINT` ⇒ `REVIEW`, `checkpoint=1`. | In cycle mode a failed verification is a *content* failure (revision), not a terminal FAILED. The OWNER_CHECKPOINT path is reused as is. | | Dependencies | `prepare_dependencies` l.42-60; the `ready` query l.363-372. FAIL set `{FAILED,BLOCKED,CANCELLED}` blocks dependants. | A task parked in `REVIEW` (cycle stopped) leaves dependants `WAITING`, not `BLOCKED`. Revision must never set `FAILED`. | | Recovery | `control_plane/recovery.py`: orphan `RUNNING` ⇒ `INTERRUPTED`, `PROCESS_CRASH`, task ⇒ `READY` via `runtime.record_recovery`. `runtime.recovery_decision`: TRANSIENT retry/fallback, per-executor `FAILURES_PER_EXECUTOR=2`, backoff 10..300 s, quota ⇒ REVIEW, EXPLICIT executor pins. | Technical retry stays exactly this. Only the counting queries gain a `(cycle_id,revision,phase)` filter. | | Supervisor | `control_plane/supervisor.py`: deterministic, no model calls; looks only at `REVIEW/FAILED` tasks whose latest execution is a proven technical stop; `MAX_ATTEMPTS=5` against `COUNT(executions)`; `DENIED_PROJECTS={L-IT,CORAL}`; probes subscription auth. | Same attempts scoping. Cycle stops by content are not "technical" ⇒ already held (`OWNER_OR_UNPROVEN_STOP`). The deny list is honoured. | | Verification | `control_plane/verification.py`: operator-owned `verification_json` (`file/sqlite/api/test`), fail-closed `require()`, `snapshot()` before-hashes, `configure()` refuses only while RUNNING. | The contract is part of the frozen approval snapshot. `configure()` must refuse while a cycle is active. Reuse `snapshot()` to prove the reviewer did not modify artifacts. | | Owner decisions | `console/owner_decisions.py`: `decide()` with optimistic `version` token (hash of task + latest execution), `confirmed=yes`, actor; `revise` clears approval and appends to `instruction`. `runtime.approve_task()` records `approved_at/by`. | Approval snapshot is taken inside `approve_task`. Manual cycle actions copy the `decide()` pattern (token, confirmation, actor, event). | | Executor policy | `executor_policy.py` PRIMARY/SECONDARY/EXPLICIT; projects hold `primary_executor=codex`, `secondary_executor=claude-code`. | Cycle `executor` defaults to the resolved effective executor; the reviewer is chosen independently (§4). | | Capacity | `claude_code.py:8,58` process-wide `_CLAUDE_RUN_LOCK` (one Claude run at a time); `MAX_WORKERS=3`; the `ready` query LIMITs 3 by priority with no executor awareness. | Threads can sit on the Claude lock while holding `RUNNING` rows. Cycle tasks need an executor-capacity check at selection time. | | Shared workspace | Default `workspace_path` = repo ROOT for codex/claude-code (l.110). | Many tasks share one tree. A per-workspace lock would serialize all legacy work, so leases are opt-in and based on declared resources (§6). | | Docs | `docs/FACTORY_RUNTIME.md`, `FACTORY_SUPERVISOR.md`, `TASK_SUBMISSION_RUNBOOK.md`, `Capabilities.md`, `AI_FACTORY_ARCHITECTURE.md`, `project-executor-policy.md`, `control_plane/VERIFICATION.md`, `docs/operating-model/02-security.md`. | Update these in place, with no new standalone doc (REQ). The security rules are applied in §11. | | Live state (read-only, 2026-11-28) | AI-NUMISMATIST-VALIDATION has `AINUM-MVP-VALUE-REVIEW` and `AINUM-MVP-LANG-REVIEW` **RUNNING**, `SHEET/UI/PACK` (+`-REVIEW`) **WAITING**, two checkpoint tasks in REVIEW. Three tasks are RUNNING globally (including this one). | No restart or pilot now. The pilot only touches *new* tasks, after that chain ends (§10). | ## 2. Concepts and invariants * **Logical task** = one `tasks` row, one `key`, one result, one approval. * **Cycle** = durable state machine attached to that task (`review_cycles`). At most one non-terminal cycle per task (partial unique index). * **Step** = `(revision r, phase p)` with `p ∈ {EXECUTION, REVIEW}`; `r=0` is the initial run. Each step has its own technical-retry budget. * **Technical retry** (existing): same step, same inputs, new `attempt` after TIMEOUT/RATE_LIMIT/5XX/CONNECTION/PROCESS_CRASH/EXECUTOR_UNAVAILABLE. It never changes `revision`. * **Revision** (new): the reviewer or the dispatcher verification found a blocking defect. `revision+=1`, with the findings. It never creates an `attempt` failure and never sets `FAILED`. Invariants: 1. I1: a cycle task is never `COMPLETED` before PASS (or an explicit owner accept). 2. I2: the cycle never exceeds `max_revisions` additional revisions (default 3 ⇒ ≤4 executor runs, ≤4 reviews), and each step never exceeds `MAX_ATTEMPTS`. 3. I3: every transition is applied exactly once (§5.3). 4. I4: the reviewer judges only against the **frozen snapshot**, never against a mutated `instruction`. 5. I5: failed verification is never bypassed. The reviewer cannot overrule it, and a PASS needs verification passed and the review verdict PASS. 6. I6: the reviewer's executor differs from the executor that produced the artifact under review. ## 3. Schema (additive) ```sql -- settings: project default and per-task override (JSON, validated in code) ALTER TABLE projects ADD COLUMN review_cycle_json TEXT NOT NULL DEFAULT '{}'; ALTER TABLE tasks ADD COLUMN review_cycle_json TEXT NOT NULL DEFAULT '{}'; -- step tagging; defaults reproduce legacy rows exactly 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; ``` (all via the `MIGRATIONS` tuple in `db.py`) ```sql CREATE TABLE IF NOT EXISTS cycle_snapshots ( -- approval snapshot, immutable id INTEGER PRIMARY KEY, task_id INTEGER NOT NULL REFERENCES tasks(id) ON DELETE CASCADE, version INTEGER NOT NULL, -- 1,2,… increments only on changed requirements instruction TEXT NOT NULL, expected_result TEXT NOT NULL, criteria_json TEXT NOT NULL, -- [{"id":"AC1","text":"…"}] verification_json TEXT NOT NULL, attachments_json TEXT NOT NULL DEFAULT '[]', config_json TEXT NOT NULL, -- resolved settings (§4) sha256 TEXT NOT NULL, approved_by TEXT NOT NULL, approved_at TEXT NOT NULL, 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, -- max incl. owner grants executor TEXT NOT NULL, reviewer TEXT NOT NULL, -- configured/resolved stop_reason TEXT, stop_detail TEXT NOT NULL DEFAULT '', stop_requested INTEGER NOT NULL DEFAULT 0, version INTEGER NOT NULL DEFAULT 0, -- CAS counter 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 ( -- idempotency + audit; one row per applied outcome id INTEGER PRIMARY KEY, cycle_id INTEGER NOT NULL REFERENCES review_cycles(id) ON DELETE CASCADE, execution_id INTEGER UNIQUE REFERENCES executions(id), -- UNIQUE ⇒ outcome applied once from_step TEXT NOT NULL, to_step TEXT NOT NULL, outcome TEXT NOT NULL, detail TEXT NOT NULL DEFAULT '', 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, revision INTEGER NOT NULL, source TEXT NOT NULL CHECK(source IN ('REVIEWER','VERIFICATION','OWNER')), review_execution_id INTEGER REFERENCES executions(id), fid TEXT NOT NULL, severity TEXT NOT NULL CHECK(severity IN ('BLOCKING','SUBSTANTIAL','RECOMMENDATION')), criterion_ref TEXT, finding_key TEXT NOT NULL, -- sha256(criterion_ref|check id|normalised summary) summary TEXT NOT NULL, evidence_json TEXT NOT NULL, expected TEXT NOT NULL DEFAULT '', actual TEXT NOT NULL DEFAULT '', status TEXT NOT NULL DEFAULT 'OPEN' CHECK(status IN ('OPEN','FIXED_CLAIMED','RESOLVED','DISPUTED','WAIVED')), response_json TEXT NOT NULL DEFAULT '{}', response_execution_id INTEGER, created_at TEXT NOT NULL, UNIQUE(review_execution_id,fid)); CREATE TABLE IF NOT EXISTS resource_leases ( resource TEXT NOT NULL, cycle_id INTEGER NOT NULL REFERENCES review_cycles(id) ON DELETE CASCADE, mode TEXT NOT NULL CHECK(mode IN ('EXCLUSIVE','SHARED')), acquired_at TEXT NOT NULL, PRIMARY KEY(resource,cycle_id)); ``` Notes: * `execution_rounds`, `artifacts` and `events` are reused unchanged. Event names are `CYCLE_STARTED/STEP_CLAIMED/REVIEW_PASS/REVIEW_FAIL/REVISION_STARTED/CYCLE_STOPPED/CYCLE_PASSED/CYCLE_MANUAL_*`. * Artifacts per review: `review-r{n}-verdict.json` (kind `review`) and the reviewer's raw output. Per revision: `responses-r{n}.json`. * Leases are valid only while their cycle is `ACTIVE`. Stale leases are *derived* (join on `review_cycles.state`), so there is no TTL and no cleanup race after a crash. ### 3.1 Settings (`review_cycle_json`) Project default and task override use the same shape. A task value wins field by field; absent ⇒ inherit. Absent project value ⇒ `enabled=false`. ```json {"enabled": false, "executor": null, // null ⇒ effective_executor(task, project) "reviewer": null, // null ⇒ opposite of the executor in {codex, claude-code} "max_revisions": 3, // additional revisions, hard ceiling 5 "criteria": [{"id":"AC1","text":"…"}], // required at approval (task-level; UI prefills from expected_result lines) "resources": ["workspaces/x/out.md"], // optional; default = contract file/deliverable paths "owner_intervention": ["BUSINESS_DECISION","SCOPE_EXPANSION","RIGHTS_OR_PAID_RESOURCE","EXTERNAL_BLOCKER","NO_PROGRESS","REVISION_LIMIT"] } ``` Validation: executor and reviewer ∈ `validate_executor`; reviewer ∈ {`codex`, `claude-code`} (tool-capable: must run tests and read files; DeepSeek/antigravity are text-only; the 12 outdated DeepSeek legacy tests are a known separate debt). `reviewer != executor`, rejected otherwise. Global kill-switch `AI_FACTORY_REVIEW_CYCLE=0` (env, default on-but-opt-in) forces legacy behaviour. ## 4. State machine Cycle `state` × `phase`; task status shown in brackets. ``` approve_task (enabled) ─▶ snapshot v + cycle ACTIVE/EXECUTION r0 [WAITING→READY by existing gating] claim EXECUTION r [RUNNING] ─exec ok + verification pass─▶ phase=REVIEW [READY] ─exec ok + verification FAIL─▶ VERIFICATION finding(s) → §4.1 (content) ─exec technical failure───────▶ existing record_recovery (same step) [READY/REVIEW/FAILED] ─FACTORY_OUTCOME: OWNER_CHECKPOINT─▶ STOPPED(BUSINESS_DECISION|EXTERNAL_BLOCKER) [REVIEW, checkpoint=1] claim REVIEW r [RUNNING] ─verdict PASS─────▶ cycle PASSED; task COMPLETED (or REVIEW if checkpoint=1) → dependants release ─verdict FAIL (valid blocking)─▶ §4.1 ─verdict BLOCKED_EXTERNAL / NEEDS_OWNER / scope_expansion─▶ STOPPED(reason) [REVIEW] ─malformed output─▶ technical retry of the review step (class REVIEW_FORMAT, ≤2) then STOPPED(REVIEW_OUTPUT_INVALID) ─reviewer changed artifact hashes─▶ verdict discarded, STOPPED(REVIEWER_MODIFIED_ARTIFACTS) §4.1 FAIL handling: if revision >= max_revisions → STOPPED(REVISION_LIMIT) elif NO_PROGRESS test hits → STOPPED(NO_PROGRESS) else revision+=1; phase=EXECUTION; findings persisted; task READY with retry_at=NULL owner: stop / resume(+N revisions, guidance) / accept / change requirements (new snapshot, back to PLANNED, approval cleared) ``` Stop reasons (enum, REQ list + implementation guards): `REVISION_LIMIT, EXTERNAL_BLOCKER, SCOPE_EXPANSION, RIGHTS_OR_PAID_RESOURCE, NO_PROGRESS, BUSINESS_DECISION, DISPUTE_UNRESOLVED, REVIEW_OUTPUT_INVALID, REVIEWER_MODIFIED_ARTIFACTS, REVIEWER_UNAVAILABLE, TECHNICAL_EXHAUSTED, MANUAL_STOP, REQUIREMENTS_CHANGED`. Every STOPPED cycle puts the task in `REVIEW` and emits the Russian owner summary (§8). `PASSED` is the only non-owner terminal. ### 4.1 Review contract (strict, bounded) Reviewer prompt (built from the **snapshot**, never from `tasks.instruction`) contains: criteria with ids; the original instruction and expected result; the verification contract and the latest `verification.json` evidence path; the executor output artifact path and deliverable manifest; the workspace path; prior findings with executor responses; and the rules "block only on a violated listed criterion with reproducible evidence; do not add scope; do not edit files". The reply must end with one JSON block: ```json {"verdict":"PASS|FAIL|BLOCKED_EXTERNAL|NEEDS_OWNER", "findings":[{"fid":"F1","severity":"BLOCKING|SUBSTANTIAL|RECOMMENDATION","criterion_ref":"AC2", "summary":"…","expected":"…","actual":"…", "evidence":[{"type":"artifact|test|file","ref":"path or argv","sha256":"…","excerpt":"…"}], "scope_expansion":false}], "dispute_rulings":[{"fid":"F1","ruling":"UPHELD|WITHDRAWN","reason":"…"}], "stop_reason":null} ``` Dispatcher-side validation (the reviewer is not trusted to be consistent): * `FAIL` needs ≥1 `BLOCKING` finding with a `criterion_ref` ∈ snapshot criteria **and** non-empty evidence whose `ref` exists under the workspace or `data/artifacts` (path-contained) or is a recorded test command. A finding that fails this check is **downgraded to SUBSTANTIAL** and stored, never blocking. If no valid blocking finding remains, the verdict is *not* silently converted to PASS: it is treated as malformed (retry ≤2, then REVIEW_OUTPUT_INVALID for the owner). Success is never fabricated. * `SUBSTANTIAL`/`RECOMMENDATION` never trigger a revision. They are stored, shown to the owner, and the executor sees them only as optional context. * `scope_expansion:true` or a finding about work outside the criteria ⇒ STOPPED(SCOPE_EXPANSION). * Free text is passed through `providers.output.safe_text` and bounded before storage. Executor revision prompt: the snapshot, the previous executor output artifact path, verification evidence, **all open BLOCKING findings with evidence**, and a required reply block `{"responses":[{"fid":"F1","status":"FIXED|DISPUTED|CANNOT","evidence":[…],"note":"…"}]}`. A `DISPUTED` response must carry evidence; the next review must rule on it (`dispute_rulings`). A second `UPHELD` ruling on the same `finding_key` ⇒ STOPPED(DISPUTE_UNRESOLVED), a judgement call for the owner. `CANNOT` with an external cause ⇒ STOPPED(EXTERNAL_BLOCKER). No-progress test (deterministic, no model): after review r+1, STOPPED(NO_PROGRESS) if (a) the same `finding_key` is BLOCKING in two consecutive reviews after the executor claimed `FIXED`, or (b) the set of verification-relevant artifact hashes is identical before and after a revision (nothing changed). Dispatcher verification findings: if `verification.verify` fails in an EXECUTION step, the dispatcher writes `source=VERIFICATION, severity=BLOCKING` findings (one per failed check, evidence = the `verification` artifact) and goes to §4.1 without spending a review. ## 5. Dispatcher, recovery and supervisor changes ### 5.1 Claim * Cycle task detection: `execution.cycle_id` set when an ACTIVE cycle exists. Executor for `phase=EXECUTION` = the existing `effective_executor` (so `next_executor` fallback keeps working). For `phase=REVIEW` = the cycle reviewer, falling back **only** within {codex, claude-code} minus the executor that produced the artifact (I6); none left ⇒ technical retry/backoff and finally STOPPED(REVIEWER_UNAVAILABLE). * Budget: `prior` counts executions of the *same* `(cycle_id,revision,phase)`; legacy rows use `cycle_id IS NULL` ⇒ identical to today. Overall hard cap `2*(max_revisions+1)*MAX_ATTEMPTS` guards against any logic fault. * `verification.require` runs against the **snapshot** contract. The reviewer step also needs the contract's read paths to exist. * Before a REVIEW step the dispatcher records `verification.snapshot()` plus deliverable hashes; after it compares them (§4). ### 5.2 Selection (`cycle()` ready query) Add, for cycle tasks only: (a) resource lease acquisition (§6) inside `claim`'s `BEGIN IMMEDIATE`, all-or-nothing; (b) executor-capacity check (§6). Legacy tasks keep the exact query path. ### 5.3 Finalization and idempotency The existing finalization transaction in `run_one` gains one call, `review_cycle.apply_outcome(db, task, eid, …)`, executed in the **same** transaction as the execution update. It does a CAS on `review_cycles.version` and inserts the `cycle_transitions` row (UNIQUE `execution_id`). A replay (restart, duplicate call) hits the unique constraint and is a no-op, so findings, revision and status are written once. If the owner changed the task while it ran (`status != RUNNING` or `stop_requested`), the outcome is recorded but the state is not advanced (same rule as `record_recovery`'s OWNER_OVERRIDE). ### 5.4 Restart recovery No new recovery loop. State is entirely in the DB: * Crash mid-step ⇒ existing startup recovery marks the `RUNNING` execution `INTERRUPTED` and re-arms the task `READY`. The cycle is unchanged (`phase/revision` are only advanced inside the finalize transaction), so the claim re-runs the **same step** with a new `attempt` (technical retry, same step budget). A revision that was interrupted is re-run on the workspace as left, never double-counted. A review is read-only, so repeating it is safe. * Crash after finalize ⇒ the next claim reads `phase/revision` and continues. * `recover_interrupted` and supervisor counts are filtered by step; `executions.cycle_id` is carried over to the new attempt. * Supervisor: `snapshot()` unchanged; `attempts` computed per step; it never releases a task whose latest cycle state is `STOPPED` with a content reason, and `eligible()` already rejects it as an unproven technical stop. The cycle fields are added to `fingerprint` so a changed cycle invalidates a stale hold. ### 5.5 Prompt/Contract reuse `run_one` keeps building `project_context + CURRENT TASK + RUNTIME DELIVERY CONTRACT + acceptance checks`. For cycle steps the CURRENT TASK block comes from the snapshot, and the revision block and findings are appended after `DURABLE EXECUTION CONTEXT`. The Russian owner-summary rule remains in the RUNTIME DELIVERY CONTRACT for the executor. The reviewer prompt uses the same contract with its own output format. ## 6. Safe concurrency * **Independent branches continue**: tasks without a lease conflict are selected as today. A cycle waiting on a lease or on capacity simply stays `READY` and is skipped in this poll; other branches proceed (no head-of-line blocking, which is the starvation defect fixed in FR-EXECUTOR-VERIFY). * **Dependency gating**: unchanged. Dependants see `READY/RUNNING/REVIEW` (not COMPLETED) until PASS. With `checkpoint=1` the existing rule (ACCEPTED required) still applies after PASS. * **Executor subscription capacity**: `capacity = {claude-code:1, codex:MAX_WORKERS}` (the first mirrors the existing `_CLAUDE_RUN_LOCK`; the values live in `config/review_cycle.json`). Selection counts live executions per executor, from the DB across all tasks, and skips a cycle step whose executor is full. A review and an execution of the same cycle never overlap (sequential). * **Shared-resource conflicts**: a cycle declares `resources` (default = paths from the contract `file`/deliverables checks, plus the workspace subdirectory if not ROOT). On the first claim of a cycle it takes `EXCLUSIVE` leases for all resources in one transaction (all-or-nothing ⇒ no hold-and-wait ⇒ no deadlock) and holds them until the cycle is terminal, so no other cycle can modify an artifact between execution and review. If any resource is held by another ACTIVE cycle, the task waits. Legacy tasks take no leases, so the conflict protection is cycle-to-cycle only. This is stated in the docs and not hidden. * **Reviewer read-only**: the executors cannot be sandboxed read-only without touching them (Codex is `workspace-write`, Claude is `acceptEdits`), so write protection is *detective*: artifact hashes before/after (§5.1), with an invalid verdict and an owner stop on any change. ## 7. UI and API (compact) Reuse the existing project page and `GET /api/projects/{key}` snapshot (`project_snapshot` + `owner_decisions.enrich`). * Snapshot fields per cycle task: `cycle:{state, phase, revision, max_revisions, executor, reviewer, stop_reason, snapshot_version}`, `findings` (history), `steps`. * Task row, one line: `executor → reviewer · rev 1/3 · REVIEW` badge. Cycle phase is a sub-badge; the task status remains the existing one. * Collapsible history: per revision, executor output link, verification, findings (severity, criterion, evidence links), executor responses, reviewer rulings. Stop reason plus the Russian owner summary appear when STOPPED. * Controls (forms in the style of `/tasks/{id}/decision`, each with `version` token + `confirmed=yes` + actor): `POST /tasks/{id}/cycle/stop`, `/cycle/resume` (grants +N revisions, with guidance text stored as an OWNER finding), `/cycle/requirements` (see §7.1), plus the existing `accept`. `owner_decisions.version()` hashes the open cycle row only when one exists, so legacy tokens do not change. * Settings: project executors panel gets default cycle settings; the task form gets an enable toggle and criteria editor, prefilled from `expected_result` lines. * `console` status/label tables learn nothing new: task statuses are unchanged. ### 7.1 Manual controls * **Stop**: sets `stop_requested=1`; if no live execution the cycle goes STOPPED(MANUAL_STOP) at once and the task to `REVIEW`; if one is running, it finishes (executors have no safe kill) and the outcome is recorded but not advanced. * **Revise/resume**: only from STOPPED; `max_revisions += N` (≤ ceiling), the owner text is attached as findings, the same snapshot continues, no new approval (scope unchanged). * **Change requirements**: creates snapshot v+1, cycle `SUPERSEDED`, task `PLANNED` with `approved_at` cleared, so renewed approval is required (the same as the existing `revise` semantics). Revision counter restarts for the new snapshot; history stays linked. * `verification.configure()` and assignment edits refuse while a cycle is ACTIVE (change goes through requirements). ## 8. Owner summary on stop On every STOPPED transition a bounded Russian text is generated deterministically from fields (no model): `Итог / Проблемы / Решение`, stored in `review_cycles.stop_detail` and in the `CYCLE_STOPPED` event, shown in the UI. The executor/reviewer Russian summary required by the existing delivery contract remains separate. ## 9. Migration, rollout, rollback 1. **Migrate (no behaviour change)**: additive `MIGRATIONS` + `CREATE IF NOT EXISTS` run by `init_db()`. Defaults: `review_cycle_json='{}'`, `executions.phase='EXECUTION'`, `revision=0`, `cycle_id` NULL. Verify with the 46 control-plane/runtime and 123 executor tests (FR-EXECUTOR-VERIFY baseline) plus the new legacy-parity test. 2. **Deploy code flag-off**: dispatcher/console/supervisor restart only in an owner-approved idle window (a restart now would kill 3 RUNNING executions; REQ forbids restarting during active work). Use the existing `privileges/dispatcher_restart` helper and the recovery already proven in FR-EXECUTOR-VERIFY. 3. **Enable per task** (opt-in), never per project, until the E2E and the pilot pass. 4. **Rollback**: set the kill-switch / disable project defaults; `STOP` all ACTIVE cycles (bulk manual stop ⇒ tasks `REVIEW`) **before** reverting code, because old code would claim a cycle task's `READY` step as a plain task. Tables/columns are kept (old code ignores them); no data is dropped. A preflight script `review_cycle --check-drained` must report zero ACTIVE cycles before a downgrade. 5. Backup: copy `data/factory.db` (WAL checkpoint first) before step 2, per `operating-model/02-security.md` ("rollback before substantial changes"; no per-minor-change backups). ## 10. Phased roadmap (task dependencies) | # | Task | Depends on | Output | Acceptance | |---|---|---|---|---| | P0 | Owner accepts this design; settles §12 decisions | none | decision | Owner decision recorded | | P1 | `review_cycle.py`: schema/migrations, settings validation, pure state machine, finding validation, no-progress, lease functions + unit tests (no dispatcher wiring) | P0 | module + tests | Matrix rows 1-12 green offline; legacy suites unchanged (46+123) | | P2 | Dispatcher/claim/finalize wiring, step-scoped budgets in `runtime`/`recovery`/`supervisor`, capacity + leases, approval snapshot in `approve_task`, `configure()` guards | P1 | code + tests | Rows 1-22 green; legacy parity test shows identical claim/finalize/recovery trace with `enabled=false` | | P3 | Console/API/UI, manual controls, Russian stop summary | P2 | code + tests | Rows 23-27; UI rendered at desktop/mobile as in `owner-decision-evidence` | | P4 | Docs updated in place (see below) | P2 (parallel with P3) | docs diff | No new standalone docs; examples runnable | | P5 | Independent review of code **and** docs by a different executor than the implementer (the cycle's own rule, applied manually) | P3, P4 | review report | PASS with no blocking findings; evidence per finding | | P6 | Controlled deploy flag-off in idle window + **real E2E Claude/Codex**: trivial approved task, codex executes/claude reviews, with a seeded first-pass FAIL, then PASS (and the reverse pairing) | P5, idle window | evidence in `docs/implementation-evidence/` | fail-fix-pass observed through real CLIs on subscription auth, no manual step, dependants released only after PASS, one restart-mid-cycle recovery | | P7 | Pilot on AI-NUMISMATIST-VALIDATION | P6 + chain `AINUM-MVP-*` finished + owner OK | pilot report | Only new tasks, none converted; no change to existing rows/approvals | Docs to update in place (REQ): `AI_FACTORY_ARCHITECTURE.md` (data model, lifecycle, recovery, concurrency), `Capabilities.md` (row), `FACTORY_RUNTIME.md` (Control Plane + Dispatcher + settings + examples), `FACTORY_SUPERVISOR.md` (step-scoped attempts, cycle holds), `TASK_SUBMISSION_RUNBOOK.md` (opt-in, criteria, structured handoff formats), `project-executor-policy.md` (reviewer pairing and defaults), `control_plane/VERIFICATION.md` (frozen contract, configure guard), agent instructions (executor `responses` block and reviewer verdict block). ## 11. Security and policy * No new paid service, permission, executor name or secret: reuses subscription `codex`/`claude-code` with the existing `auth_status`/supervisor probes (API-key env is stripped as today). * `DENIED_PROJECTS` (`L-IT`, `CORAL`) cannot enable a cycle; the delivery contract line "no write to Coral/L-IT" is kept in both prompts. * Untrusted text (reviewer/executor output) is bounded and `safe_text`-sanitised; evidence refs are path-contained to the workspace or `data/artifacts` (same check style as `verification.local_path` and `execution_context`). No secrets enter prompts or findings. * Per `02-security.md`: no protections added to created files; proportionate checks: one verification per execution plus one review per revision, never repeated re-verification; real vulnerabilities fixed minimally, no blocking on hypotheticals (also encoded in the reviewer rules). * Loop bounds: step attempts ≤5, revisions ≤`max_revisions` (≤5 ceiling), overall cap formula (§5.1). No unbounded loop exists. ## 12. Test matrix (offline unless noted; dummy/fake executors, in-memory DB) | # | Case | Expected | |---|---|---| | 1 | Legacy parity: `enabled=false`/absent | claim/finalize/recovery/supervisor traces identical to baseline; no cycle rows | | 2 | First-pass PASS | one exec + one review; task COMPLETED; dependants released | | 3 | Fail-fix-pass | rev1 with findings and response, then PASS; findings RESOLVED | | 4 | Multiple revisions (2-3) | prompt carries all prior findings/responses/artifacts; counters exact | | 5 | Exhaustion | STOPPED(REVISION_LIMIT), task REVIEW (not FAILED), dependants WAITING not BLOCKED | | 6 | Nonblocking only | SUBSTANTIAL/RECOMMENDATION ⇒ PASS recorded, no revision | | 7 | Invalid blocking (no criterion/evidence) | downgraded, no revision; FAIL with none valid ⇒ malformed path | | 8 | Verification failure | VERIFICATION findings, revision without review; never PASS | | 9 | Technical failure vs content | transient failure ⇒ same step, `revision` unchanged, step budget separate; fallback pins respected | | 10 | Reviewer independence | reviewer ≠ producing executor, also after fallback; none left ⇒ REVIEWER_UNAVAILABLE | | 11 | Reviewer mutates artifacts | verdict discarded, STOPPED | | 12 | Dispute | DISPUTED with evidence ⇒ ruling; double UPHELD ⇒ DISPUTE_UNRESOLVED | | 13 | No-progress | repeated finding after FIXED / identical hashes ⇒ NO_PROGRESS | | 14 | External blocker / OWNER_CHECKPOINT / scope expansion / rights-paid | STOPPED with right reason, Russian summary present | | 15 | Idempotency | `apply_outcome` replayed twice ⇒ one transition | | 16 | Restart mid-EXECUTION / mid-REVIEW / just-after-finalize | same step re-run / next step; no double revision | | 17 | Parallel branches | two cycles + a legacy task; no starvation when one waits on lease/capacity | | 18 | Lease conflict | overlapping resources serialise; all-or-nothing acquire; released on PASS/STOP/cancel | | 19 | Executor capacity | claude-code ≤1 live across tasks | | 20 | Dependency release | dependants stay WAITING through revisions; release at PASS; `checkpoint=1` needs ACCEPTED | | 21 | Approval snapshot | instruction/contract edits after approval do not change the cycle; `configure()` refused while ACTIVE | | 22 | Supervisor | step-scoped attempts; content STOPPED never auto-released; denied projects | | 23 | Manual stop (idle and running) | as §7.1 | | 24 | Manual resume (+N, guidance) | within ceiling; same snapshot | | 25 | Change requirements | snapshot v+1, SUPERSEDED, PLANNED, approval required, history kept | | 26 | UI/API | compact row, collapsible history, stop reason, stale token ⇒ 409 | | 27 | Migration | fresh DB and a copy of the production DB both converge; downgrade-drain check | | 28 | **Real E2E (P6, live)** | Codex↔Claude fail-fix-pass, restart recovery, parallel legacy task untouched | ## 13. Risks | Risk | Mitigation | |---|---| | Step budget regression silently changes legacy retry counts | Row 1 parity test; filters default to legacy semantics when `cycle_id IS NULL` | | Reviewer perfectionism / endless nitpicks | Blocking only with valid criterion + evidence; deterministic downgrade; revision cap; no-progress stop | | Reviewer says FAIL with unusable format | Retry ≤2, then owner stop, never auto-PASS | | Weak independence: Claude and Codex have different blind spots but share the host | Documented; the owner can pin a different reviewer. A third tool-capable executor is out of scope (no new services) | | Reviewer edits files | Detective hash check (preventive sandboxing would need executor changes) | | Single shared ROOT workspace | Leases only protect cycle-to-cycle. Legacy writers remain unprotected, so the owner is told | | Claude capacity 1 slows paired work | Capacity-aware selection prevents blocked workers; throughput is bounded by the subscription anyway | | Rollback with ACTIVE cycles | Drain check before downgrade (§9.4) | | Restart during active work | Flag-off deploy in an idle window only | | Long cycles hide cost | UI shows rev/max; hard cap; owner stop; subscription-only executors | ## 14. Alternatives considered 1. **Reviewer as separate dependent task (today's AINUM pattern).** No code, but it duplicates tasks, the dependency graph releases dependants on the executor's COMPLETED unless wired by hand, there is no automatic return to the executor, and findings live in prose. Rejected: it does not meet REQ. 2. **New task statuses (`IN_REVIEW`, `REVISING`).** Clear, and safe under downgrade, but touches the status set, console, mobile, activity, supervisor and dependency code. Rejected for minimality. Status stays READY/RUNNING with the cycle table as the source of truth (cost: the drain step on rollback). 3. **Self-review by the same executor/session.** Cheap, but violates "independent". Rejected. 4. **External orchestration (ChatGPT) between revisions.** This is exactly what REQ removes. 5. **Hard per-executor locks in the executor modules.** More invasive than DB-level capacity; the Claude process lock stays as a backstop. 6. **Separate review service/process.** More moving parts; the existing dispatcher, supervisor and DB already provide durability and recovery. ## 15. Open decisions (defaults proposed; owner may keep all) 1. Reviewer pairing default: opposite of the executor within {codex, claude-code}. 2. A STOPPED cycle uses `REVIEW` status, and technical exhaustion keeps existing `FAILED` semantics. 3. `max_revisions=3` default, ceiling 5; NO_PROGRESS after two consecutive repeats. 4. Cycle controls are per task; no project-wide default enablement until after the pilot. 5. Window for P6 deploy/restart, and pilot timing for AI-NUMISMATIST-VALIDATION. --- ## Сводка для владельца (повтор в конце файла) Итог: подготовлен проект нативного цикла «исполнение → независимая проверка → автодоработка» с включением по задаче: одна логическая задача, отдельные счётчики технических повторов и доработок, зафиксированный снимок требований, аренды ресурсов, восстановление после перезапуска, без изменения поведения по умолчанию. Проблемы: сейчас в проекте идут задачи (3 RUNNING, цепочка AI-NUMISMATIST), поэтому перезапуск и пилот сейчас невозможны; при откате код нужно сначала «осушить» от активных циклов. Решение: утвердить дизайн и значения по умолчанию (§15), назначить окно для деплоя и реального E2E Claude/Codex, и согласовать начало пилота на AI-NUMISMATIST-VALIDATION только после завершения текущей цепочки.