Полная документация
# AI Factory — Task Execution Runbook
Проверено: 2026-11-09. Источник: действующие control_plane/verification.py, supervisor.py, dispatcher/control_plane_dispatcher.py, console/app.py, control_plane/service.py, executor_policy.py, db.py и SQLite factory.db. Версия релиза не установлена; код является источником истины.
## 1. Создание
1. Найти существующий проект по key; при отсутствии создать через control_plane.service.create_project(key,name,description,status='PLANNED',priority=100,primary_executor='codex',secondary_executor='claude-code'). Для диспетчеризации проект должен быть ACTIVE.
2. Создать roadmap item через форму консоли /projects/{key}/roadmap; задачи привязаны к roadmap_item_id, а project_id получается через эту связь.
3. Создать задачу через /projects/{key}/tasks: task_key, title, instruction, expected_result, executor_policy, executor. Начальный статус PLANNED.
4. Назначить PRIMARY (исполнитель проекта), SECONDARY (резервный исполнитель проекта) или EXPLICIT (конкретный исполнитель). По умолчанию PRIMARY; project defaults codex/claude-code. Значения имён проверяются control_plane/executor_policy.py и расширяемым реестром OpenRouter.
5. Указать зависимости в task_dependencies, если они есть; READY допустим только при завершённых зависимостях (checkpoint требует ACCEPTED).
6. Определить workspace_path и фактические права исполнителя; для Codex/Claude по умолчанию корень фабрики, для остальных обычно workspaces/<project-key>. Не предполагать наличие доступа к другим каталогам или сети.
7. Согласовать критерии приёмки и установить verification contract **до** разрешения запуска.
8. Получить явное разрешение владельца в интерфейсе задачи: /tasks/{task_id}/approve, confirmed=yes и непустой actor. Не подменять разрешение сменой статуса.
9. Перевести задачу в WAITING/READY через штатный интерфейс; дождаться фактического execution RUNNING и события TASK_STARTED. READY означает готовность, но не запуск.
10. Проверять executions, events, verification artifacts; после успешной проверки и при необходимости REVIEW владелец принимает результат через owner decision panel.
## 2. Параметры (значения и примеры)
| Параметр | Обязателен | Значения / default | Пример |
|---|---|---|---|
| Project key / ID | да | уникальный key; ID создаёт БД | LIT-WEBSITE-AUDIT |
| Roadmap item ID | да | существующий item в проекте | 1 (пример, не реальный ID) |
| Task key / ID | да | уникальный key; ID создаёт БД | LIT-SEO-GEO-001 |
| Title | да | текст | SEO/GEO audit |
| Instruction | форма допускает пустое; для работы необходимо | текст | Проверить публичный сайт |
| Expected result | форма допускает пустое; рекомендуется | текст | SEO_GEO_AUDIT.md |
| Primary / Secondary | настройки проекта | codex / claude-code по умолчанию | codex |
| Executor policy | да | PRIMARY / SECONDARY / EXPLICIT; default PRIMARY | EXPLICIT |
| Explicit executor | при EXPLICIT | имя из executor_names() | codex |
| Dependencies | нет | task_dependencies; пусто | нет |
| Verification contract | да для реального исполнителя | JSON с непустым checks; default {} непригоден | см. шаблоны |
| Task status | да | PLANNED из формы; затем WAITING/READY | PLANNED |
| Approval | требуется для санкционированного запуска/восстановления | approved_at + approved_by; исходно отсутствует | owner approval |
| Workspace | нет при создании, нужен при исполнении | workspace_path или вычисляемый путь | workspaces/lit-website-audit |
| Файлы / сеть / внешние сервисы | ограничения зависят от executor и sandbox | нет универсального параметра в форме | codex workspace-write |
## 3. Состояния
Project: PLANNED, ACTIVE, PAUSED, BLOCKED, DONE, ARCHIVED.
Roadmap: PLANNED, ACTIVE, BLOCKED, DONE, CANCELLED.
Task: PLANNED, WAITING, READY, RUNNING, REVIEW, COMPLETED, ACCEPTED, FAILED, BLOCKED, PAUSED, CANCELLED.
Execution: QUEUED, RUNNING, COMPLETED, FAILED, CANCELLED, INTERRUPTED.
WAITING — ожидание зависимостей; READY — кандидат для диспетчера; RUNNING — создана попытка; REVIEW — решение владельца/блокировка; COMPLETED — завершено без checkpoint; ACCEPTED — принято владельцем; FAILED — ошибка/исчерпание попыток. Не приравнивать task status к execution status.
## 4. Verification Contract
Контракт хранится в tasks.verification_json, принадлежит оператору и не может быть подменён текстом исполнителя. Все проверки обязательны. Без валидного контракта реальный executor не запускается: событие VERIFICATION_CONTRACT_REQUIRED, статус REVIEW, execution не создаётся. Dummy — только симуляция.
- file: workspace-relative path; optional min_bytes, json, sha256, changed. По умолчанию файл должен появиться или измениться в текущей попытке; changed:false допускает существующий.
- sqlite: workspace-relative path, query, expected_rows, optional params. Read-only query-only SQL; точное сравнение строк.
- api: HTTP(S) GET url, expected_json, optional status=200; требуется точное соответствие JSON.
- test: непустой argv массив строк, optional timeout=60, диапазон 1..300; subprocess без shell. Использовать конкретный тест, не пустой autodiscovery.
- access_policy: optional объект с единственным разрешённым ключом host_verification (boolean).
- Пути абсолютные и с '..' отклоняются; при исполнении проверяется, что resolved path остаётся внутри workspace.
- Команды тестов и URL проверять до установки; тесты способны выполнять код.
Команды (из корня /home/iovon/ai-factory):
```bash
.venv/bin/python -m control_plane.verification set TASK_KEY config/verification/TASK_KEY.json --operator OPERATOR
.venv/bin/python -m control_plane.verification show TASK_KEY
```
Для REVIEW после именно VERIFICATION_CONTRACT_REQUIRED допустим set ... --release (возвращает WAITING); для других REVIEW/FAILED/COMPLETED использовать owner decision panel. Контракт не переписывает историю выполнений. Успех exit code без проверок недостаточен; verification evidence сохраняется с checksum.
## 5. Реальный пример LIT-SEO-GEO-001
Проект LIT-WEBSITE-AUDIT, аудит https://l-it.gmbh/. Первоначально возник VERIFICATION_CONTRACT_REQUIRED и затем supervisor HOLD NO_EXPLICIT_APPROVAL. 2026-11-09 контракт установлен, approval зарегистрирован; фактический снимок SQLite: task id 99, status RUNNING, executor codex, EXPLICIT, workspace /home/iovon/ai-factory/workspaces/lit-website-audit; событие TASK_STARTED attempt=1. Это **не** подтверждает COMPLETED или ACCEPTED.
Реальный контракт: config/verification/LIT-SEO-GEO-001.json: два file-check для SEO_GEO_AUDIT.md (min_bytes 4500, changed true) и EXECUTIVE_SUMMARY.md (min_bytes 800, changed true).
Правильный порядок: создать проект/roadmap/task → настроить workspace и критерии → установить и show контракт → явное approval владельца → WAITING/READY → дождаться TASK_STARTED → проверка artifacts/verification → owner acceptance.
## 6. Действия, требующие владельца
Явное approval исполнения; приёмка checkpoint/REVIEW; решение о повторе после failed/completed/reviewed delivery; необратимые изменения и выход за разрешённый scope. Самовольный обход gate запрещён.
## 7. Task Deliverables, Results & Downloads (2026-11-28; code pending activation)
Owner/operator defines optional `deliverables` beside the existing nonempty `checks` in the verification contract. Existing contracts remain valid and do not publish workspace files automatically. Executor only writes declared output files; dispatcher verifies and registers `artifacts.kind=deliverable` after all checks pass. Registration failure fails verification. Approval, owner decisions and task transitions remain unchanged.
```json
{"checks":[{"kind":"file","path":"output/report.pdf"}],"deliverables":[{"path":"output/report.pdf","description":"Final report","group":"report","required":true},{"directory":"output/images","glob":"*.png","max_files":40,"description":"Report images","group":"images","required":true}]}
```
Paths are relative to the task workspace. Declare either one `path` or one `directory` with an immediate-child `glob` (default `*`) and explicit `max_files` (1–500). No recursive glob or automatic sweep. Required defaults to true; a missing required file/empty set fails verification. Optional missing files are omitted; unsafe files and oversized sets still fail. Bounds: 50 MiB/file, 500 files, 512 MiB total. Optional metadata: `description`, `mime`, `group`, `required`. Metadata records original relative path, attempt and provenance; artifact columns record task/execution IDs, size and SHA256. Hidden/sensitive paths, symlinks, nonregular files and recognized private keys/tokens are rejected. This is not a general secret scanner: operator must review declared outputs.
Immutable snapshots live under existing `data/artifacts/deliverables/{task_id}/{execution_id}/{sha256}`. No overwrite or hard link to mutable workspace originals; repeated registration reuses the snapshot. Different original names with identical content share one blob within an attempt. Previous attempts remain downloadable. Technical logs/inputs are excluded unless explicitly declared.
Task Deliverables and collapsible Project Deliverables show original names, MIME, size, description, source task, execution date, executor, attempt, current/prior attempt and recorded owner acceptance. Current means latest execution, not approval. Acceptance comes from the owner decision at that attempt; a later retry does not inherit it. PNG/JPEG/WebP previews and PDF inline views are available; Markdown/text previews are plain text. HTML/SVG and other formats download as attachments. Original download works for all formats. ZIP all/group is per attempt and uses shortened, collision-safe relative paths with original filenames. One shared project-material root is removed when all selected files belong to it; otherwise names are relative to the common parent of the selected files. Directory hierarchy and different project names remain distinct; duplicate names and file/directory conflicts are rejected. ZIPs are buffered in memory within the bounds above.
Routes, behind the existing console access boundary:
- `/tasks/{task_id}/executions/{execution_id}/deliverables/{artifact_id}` (`?download=1` for original)
- `/tasks/{task_id}/executions/{execution_id}/deliverables.zip` (`?group=NAME` optional)
- Existing `/artifacts/{id}` now requires containment under `data/artifacts`, rejecting symlinks. Existing legitimate indexed artifacts under that root retain access.
Historical registration (operator only; no status changes or reruns):
```bash
.venv/bin/python -m control_plane.deliverables --task 209 --execution 301 --declarations config/deliverables/HRV-WORKSHOP-001.json --operator OPERATOR
```
The declarations file contains a JSON array in the format above. CLI requires a completed matching execution, no active execution for that task, passing stored verification evidence with a valid checksum, and each current source file's size/hash matching that execution's file checks or deliverables evidence. Unknown provenance is refused. Runs are idempotent; altered files cannot replace an attempt. Do not install historical declarations as a new verification contract or rerun accepted tasks.
### F1/F2 compatibility and filtering
Legacy `kind=deliverable` rows without provenance or `relative_path` remain accessible only through `/artifacts/{id}` with matching task/execution, artifact-root confinement and applicable hash checks. They are excluded from the new id-bound deliverable routes and ZIPs. Historical examples: artifacts 321/322, task 108/execution 175. These do not grant report-file exceptions.
Directory/glob declarations inspect immediate children only: subdirectories, hidden entries and FIFOs are ignored; a matching symlink (including symlinked directory or a symlink in the declared path) fails closed. Required empty sets fail; optional empty sets are omitted. Explicit unsafe/nonregular paths still fail.
### Owner summary, preview and report fallback
`/tasks/{id}/summary` prefers a recorded `## Сводка для владельца` block with `Итог:`, `Проблемы:`, `Решение:` (English `Owner summary` / `Outcome`, `Issues`, `Decision` also supported). Task result is checked before latest execution summary. New executor prompts request this block after dispatcher activation; historical results are not rewritten. Missing structured data shows the stored result with a historical-fallback note, strips the `FACTORY_OUTCOME` transport prefix, and pretty-prints valid JSON; it invents no outcome. Status supplies decision guidance; execution errors in fallback are limited to 1500 characters. Empty results say `Результат пока не записан`. Cards prefer the structured outcome in the task result, then latest execution summary, otherwise strip the transport prefix; previews remain limited to 400 characters/three lines. The summary page is not truncated.
`/tasks/{id}/report` serves the first existing mentioned Markdown report allowed for that task/project. Normal roots: `data/project_materials/{project_key}` and the configured workspace only when it is the conventional `workspaces/{project_key.lower()}` or a descendant (default: that conventional workspace). The shared factory workspace grants no general root/docs/workspaces access. Dot/sensitive paths, traversal outside allowed roots and symlinks are denied. Files above 2,000,000 bytes return 413. Missing/denied reports return a 200 saved-result fallback; unknown task returns 404. Markdown is escaped; NUL is removed, link attributes are protected from emphasis formatting, and protocol-relative links are inert.
Five verified legacy exceptions are exact task ID/key/project/file tuples in `console/owner_result.py`, not directory permissions:
- 54 / FACTORY-VERIFY-001 / FACTORY-RUNTIME → `control_plane/VERIFICATION.md`
- 83 / YUR-001 / YURKEVICH-ARCHIVE → `archive-discovery-report.md`
- 84 / YUR-002 / YURKEVICH-ARCHIVE → `archive-followup-report.md`
- 98 / FACTORY-HEALTH-20261106 / AI-FACTORY → `docs/acceptance/FACTORY-HEALTH-20261106.md`
- 108 / CBS-001 / CRYPTO-BACKUP-STORAGE → `CRYPTO_BACKUP_REPORT.md`
### Ordering, evidence and activation
Dashboard projects/recent tasks and project task lists sort newest meaningful task activity first, with descending ID ties and `julianday` timestamp normalization. Activity includes task creation/update/approval/acceptance, execution creation/start/completion, owner decisions and attachments (deletion updates the task). Polling/telemetry and project-only edits do not reorder lists. HTML is no-store; CSS is content-hash versioned.
Earlier implementation/review reports and their counts are historical evidence, not current behavior specifications. The independent final review recorded 11 runtime/supervisor/approved-runtime baseline failures and six stale owner-decision/executor-policy UI failures/errors; those are separate cleanup work, not a reversal of owner acceptance of FI-OWNER-ACTION-001. See `data/project_materials/FACTORY-INTERFACE/review/final-hardening.md` for current focused results. Code is not live until separately authorized activation: require no RUNNING/QUEUED executions, SQLite backup API backup, dispatcher/console restart, authenticated smoke checks and owner mobile review. This hardening task performs no restart or production DB changes.
## 8. Dispatcher outcome recovery (pending activation, PARKED)
If finalization reports SQLite BUSY/LOCKED, retain the attempt and its outcome
journal under `data/artifacts/outcomes/<database-path-hash>/<execution-id>.json`.
Do not manually rerun the executor or synthesize exit code/baseline evidence.
The updated dispatcher retries finalization four times, then a later poll or
restart replays a complete journal under the worker fence. Completed execution
replay is idempotent. Busy worker locks are skipped; age alone is not a lease.
Incomplete/corrupt journals stop in REVIEW with unknown exit code and require
owner investigation. Preserve those files; do not delete task lock files while
workers run. Legacy attempts without journals retain bounded interruption policy.
Task 253/execution 343 is historical operator recovery: its exit code was not
recovered and its original baseline was lost. The reconstructed baseline is not
an original snapshot. Its saved message is evidence of the delivered message,
not proof of process exit status. The current fix does not rewrite that history.
See `docs/FACTORY_RUNTIME.md` and the dispatcher recovery review report for exact
boundaries. Production writes, migration, restart and deployment require their
own authorization; this delivery leaves PARKED unchanged.
### 8.1 Hardening B1: isolated recovery and operator REVIEW
One non-lock finalization failure is the configured bound (N=1): no blind
repetition of a poisoned prepared outcome. While holding its task fence, recovery
uses a minimal separate transaction to mark the execution INTERRUPTED, unknown
exit code, `RECOVERY_FAILED`, and the still-RUNNING task REVIEW. An owner-changed
task keeps its state (`OWNER_OVERRIDE`); R1/cycle-managed attempts remain excluded.
The original journal is retained verbatim. Invalid/incomplete evidence normally
retains the existing `EVIDENCE_MISSING` path. Artifact and logging functions are
not prerequisites for the minimal parking transaction. Diagnostics use a separate
best-effort event, then stderr; failure of both does not abort dispatch.
BUSY/LOCKED exhaustion does **not** consume this non-lock bound or change the
attempt: keep RUNNING and the journal, continue other rows, retry on a later poll.
If the parking transaction itself cannot commit, leave the attempt unchanged,
report `review_write_failed`, continue other rows and retry later. Failure to
acquire/open a task fence never authorizes an execution mutation. Recovery scan
and worker-future errors do not discard healthy candidates/results. A database-
wide write lock can still prevent all writes/claims until released; this change
cannot make SQLite writable under another writer. Existing finalization waits
remain bounded at four attempts (up to about 20.35 seconds per locked attempt);
parking and diagnostic DB writes use a 50 ms busy timeout.
Operator recovery: preserve the journal, execution/attempt identity and artifact
files; inspect the saved failure, checksum, baseline, returned result and verified
deliverable hashes. Fix storage/permissions/capacity or investigate identity
mismatch before deciding. Never edit a checksum envelope to force acceptance,
fabricate an exit code, reset INTERRUPTED to RUNNING, or blindly release REVIEW.
After confirming workers are absent, use the existing owner decision workflow to
accept independently established evidence or explicitly authorize a new attempt.
The existing finalized-attempt CAS deliberately will not replay a parked terminal
execution. If a later repair tool is needed to publish its original evidence,
that requires a separately reviewed operator action, not direct SQL here. For
`review_write_failed`, first restore DB writes; a later poll can park the retained
RUNNING attempt. Diagnose repeated lock exhaustion separately; do not delete the
journal or requeue to work around a lock.
### 8.2 Controlled single-version idle activation (not performed)
Mixed old/new dispatchers are unsupported. A live old worker has neither the new
journal nor the worker fence and MUST NOT be exposed to the new recovery poll.
The default production DB (`data/factory.db`) is guarded before `cycle` performs
initialization and before `poll_recovery`, `claim` or `run_one`. Without the valid
versioned, DB-path-bound activation receipt, these entry points raise
`ActivationRefused` without reconciling or claiming any task. Explicit temporary
`control_plane.db.DB_PATH` overrides are the offline test/embedding interface,
not an approved way to relocate production or bypass rollout. Deployments using
another production DB path must bind `recovery_activation.PRODUCTION_DB` to it
and review that configuration before activation.
Only in a separately authorized maintenance window:
1. Keep current legacy code/workers running until their work completes. Pause new
admissions using the established operator/service controls, disable all timer,
supervisor, global and project-scoped launch sources and automatic restarts.
Do not kill live work or edit its states to obtain an idle count. If it cannot
drain safely, postpone activation; an orphan/QUEUED record needs its own owner
decision, never automatic cleanup by the new version.
2. After drain, stop the old dispatcher, supervisor and all child/scoped workers.
Confirm through the service manager AND process inventory that none remain.
The global flock alone cannot establish absence of old/scoped workers.
3. Confirm globally, not just for FACTORY-RUNTIME, using read-only SQLite:
`SELECT count(*) FROM executions WHERE status IN ('RUNNING','QUEUED');`
and `SELECT count(*) FROM tasks WHERE status='RUNNING';` — both must be zero.
Keep launch sources disabled throughout check, installation and activation.
4. Retain the previous source release and obtain an authorized SQLite backup-API
snapshot plus artifact/journal backup. Install one reviewed release only.
No schema migration is part of this hardening.
5. The future operator entry point is `control_plane.recovery_activation.activate`
with a named `operator`, `old_workers_stopped=True` and
`launch_sources_disabled=True`. These are explicit operator attestations, not
automatic process detection. The helper takes the existing global flock
nonblocking, rechecks both idle counts through `mode=ro`, and only then atomically
publishes `data/factory.db.recovery-activation.json` with fsync. A new fully
attested activation first removes/fsyncs any old receipt, so a failed new
preflight leaves no stale authorization. Archive the previous receipt before
invoking it. Routine same-version restart uses the existing receipt instead. Missing
attestations, held global lock, any RUNNING/QUEUED execution, any RUNNING task,
or unreadable DB refuse activation. This delivery never calls it on production.
6. Start only the new version; verify receipt/version/path and the service process
inventory, then re-enable approved admissions. Routine same-version crash
recovery reuses the receipt and may recover its own RUNNING attempts. The
receipt is not proof that an old binary can safely be restarted later.
Rollback: disable admissions and all restart sources again; let new live work
finish, resolve pending journals/REVIEW explicitly, require the same zero counts,
then stop all new workers. Archive/remove the activation receipt before starting
any old release; never leave a receipt that would let new code coexist with old.
Restore the saved source release only after idle verification. Preserve current
DB/artifacts/journals; do not restore a stale database backup over newer completed
work. Any actual DB restore needs a separate reconciled owner-approved plan.
If drain cannot finish, keep the new version stopped from new admissions and
investigate; do not run old recovery against new RUNNING attempts. No rollback,
restart, deployment or activation is authorized by this documentation.
### 8.3 Journal retention
No automatic GC is installed. Retain all journals for RUNNING, QUEUED, REVIEW,
INTERRUPTED and unresolved attempts indefinitely until operator resolution.
Never delete or move task lock files, the DB path or the artifact root while
workers or recovery may run. In particular, deleting an unresolved journal can
make it look like a pre-launch legacy crash and permit a duplicate external action.
Terminal, resolved journals may be archived only during an authorized idle window,
after matching execution identity/status, exporting their checksum and preserving
related baseline/results/artifacts in the backup. Do not automatically purge even
resolved journals: retention duration and irreversible deletion require the owner's
separate policy. Journals contain full output and share the sensitivity/access
boundary of execution artifacts; checksums detect corruption, not same-user edits.