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

automatic-review-design.md

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)

AreaFact (file)Consequence for the design
Schemacontrol_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.
Claimdispatcher/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.
Finalizerun_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.
Dependenciesprepare_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.
Recoverycontrol_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.
Supervisorcontrol_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.
Verificationcontrol_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 decisionsconsole/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 policyexecutor_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).
Capacityclaude_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 workspaceDefault 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).
Docsdocs/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

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)

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

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:

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.

{"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:

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

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

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:

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

7. UI and API (compact)

Reuse the existing project page and GET /api/projects/{key} snapshot (project_snapshot + owner_decisions.enrich).

7.1 Manual controls

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)

#TaskDepends onOutputAcceptance
P0Owner accepts this design; settles §12 decisionsnonedecisionOwner decision recorded
P1review_cycle.py: schema/migrations, settings validation, pure state machine, finding validation, no-progress, lease functions + unit tests (no dispatcher wiring)P0module + testsMatrix rows 1-12 green offline; legacy suites unchanged (46+123)
P2Dispatcher/claim/finalize wiring, step-scoped budgets in runtime/recovery/supervisor, capacity + leases, approval snapshot in approve_task, configure() guardsP1code + testsRows 1-22 green; legacy parity test shows identical claim/finalize/recovery trace with enabled=false
P3Console/API/UI, manual controls, Russian stop summaryP2code + testsRows 23-27; UI rendered at desktop/mobile as in owner-decision-evidence
P4Docs updated in place (see below)P2 (parallel with P3)docs diffNo new standalone docs; examples runnable
P5Independent review of code and docs by a different executor than the implementer (the cycle's own rule, applied manually)P3, P4review reportPASS with no blocking findings; evidence per finding
P6Controlled 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 windowevidence 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
P7Pilot on AI-NUMISMATIST-VALIDATIONP6 + chain AINUM-MVP-* finished + owner OKpilot reportOnly 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

12. Test matrix (offline unless noted; dummy/fake executors, in-memory DB)

#CaseExpected
1Legacy parity: enabled=false/absentclaim/finalize/recovery/supervisor traces identical to baseline; no cycle rows
2First-pass PASSone exec + one review; task COMPLETED; dependants released
3Fail-fix-passrev1 with findings and response, then PASS; findings RESOLVED
4Multiple revisions (2-3)prompt carries all prior findings/responses/artifacts; counters exact
5ExhaustionSTOPPED(REVISION_LIMIT), task REVIEW (not FAILED), dependants WAITING not BLOCKED
6Nonblocking onlySUBSTANTIAL/RECOMMENDATION ⇒ PASS recorded, no revision
7Invalid blocking (no criterion/evidence)downgraded, no revision; FAIL with none valid ⇒ malformed path
8Verification failureVERIFICATION findings, revision without review; never PASS
9Technical failure vs contenttransient failure ⇒ same step, revision unchanged, step budget separate; fallback pins respected
10Reviewer independencereviewer ≠ producing executor, also after fallback; none left ⇒ REVIEWER_UNAVAILABLE
11Reviewer mutates artifactsverdict discarded, STOPPED
12DisputeDISPUTED with evidence ⇒ ruling; double UPHELD ⇒ DISPUTE_UNRESOLVED
13No-progressrepeated finding after FIXED / identical hashes ⇒ NO_PROGRESS
14External blocker / OWNER_CHECKPOINT / scope expansion / rights-paidSTOPPED with right reason, Russian summary present
15Idempotencyapply_outcome replayed twice ⇒ one transition
16Restart mid-EXECUTION / mid-REVIEW / just-after-finalizesame step re-run / next step; no double revision
17Parallel branchestwo cycles + a legacy task; no starvation when one waits on lease/capacity
18Lease conflictoverlapping resources serialise; all-or-nothing acquire; released on PASS/STOP/cancel
19Executor capacityclaude-code ≤1 live across tasks
20Dependency releasedependants stay WAITING through revisions; release at PASS; checkpoint=1 needs ACCEPTED
21Approval snapshotinstruction/contract edits after approval do not change the cycle; configure() refused while ACTIVE
22Supervisorstep-scoped attempts; content STOPPED never auto-released; denied projects
23Manual stop (idle and running)as §7.1
24Manual resume (+N, guidance)within ceiling; same snapshot
25Change requirementssnapshot v+1, SUPERSEDED, PLANNED, approval required, history kept
26UI/APIcompact row, collapsible history, stop reason, stale token ⇒ 409
27Migrationfresh DB and a copy of the production DB both converge; downgrade-drain check
28Real E2E (P6, live)Codex↔Claude fail-fix-pass, restart recovery, parallel legacy task untouched

13. Risks

RiskMitigation
Step budget regression silently changes legacy retry countsRow 1 parity test; filters default to legacy semantics when cycle_id IS NULL
Reviewer perfectionism / endless nitpicksBlocking only with valid criterion + evidence; deterministic downgrade; revision cap; no-progress stop
Reviewer says FAIL with unusable formatRetry ≤2, then owner stop, never auto-PASS
Weak independence: Claude and Codex have different blind spots but share the hostDocumented; the owner can pin a different reviewer. A third tool-capable executor is out of scope (no new services)
Reviewer edits filesDetective hash check (preventive sandboxing would need executor changes)
Single shared ROOT workspaceLeases only protect cycle-to-cycle. Legacy writers remain unprotected, so the owner is told
Claude capacity 1 slows paired workCapacity-aware selection prevents blocked workers; throughput is bounded by the subscription anyway
Rollback with ACTIVE cyclesDrain check before downgrade (§9.4)
Restart during active workFlag-off deploy in an idle window only
Long cycles hide costUI 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 только после завершения текущей цепочки.

Материалы