Полная документация
# Autonomous Factory Runtime The SQLite dispatcher reconciles existing approved work on every poll. `READY` and `WAITING` remain approval boundaries. Existing `PLANNED` tasks are released only when both `approved_at` and `approved_by` explicitly record authorization. Unapproved tasks and empty future roadmap items stay PLANNED. Reconciliation records `APPROVED_TASK_RELEASED` and activates corresponding planned roadmap items. It never creates tasks or scope. Only ACTIVE projects dispatch. Atomic claims enforce completed dependencies, checkpoint acceptance, due retry times and one live execution per task. Scheduling filters gated tasks before applying the worker limit so unrelated branches can proceed. READY rows with existing live executions are also excluded before the limit, matching the atomic claim guard. A successful checkpoint task enters REVIEW. Its dependents require ACCEPTED, including checkpoints previously marked COMPLETED. Existing owner acceptance controls release the branch. Runtime-created dependency blocks are distinguished from manual BLOCKED tasks: repairing/accepting their dependencies releases only the former. Operator pauses/cancellations made during execution take precedence when the attempt finishes. Failures have durable `failure_class`, `recovery_action`, and `next_state` fields on each execution. Classes are TIMEOUT, RATE_LIMIT, PROVIDER_5XX, CONNECTION, PROCESS_CRASH, and TASK_OR_VALIDATION. Executors can return `failure_class`; otherwise the runtime classifies exception types, exit codes and error text. Task/validation failures require an owner decision. Transient attempts use 10-second exponential backoff capped at 300 seconds, persisted in `tasks.retry_at`. No worker sleeps during backoff. The existing five-attempt default remains configurable through AI_FACTORY_MAX_ATTEMPTS. A first dispatcher interruption retains immediate restart recovery for compatibility; repeated crashes use the normal backoff and fallback policy. After two transient failures on an executor, fallback selects a capability compatible, allowed executor: - DeepSeek and Codex can exchange coding work in a compatible preserved workspace. - Antigravity text work can fall back to an enabled OpenRouter profile; OpenRouter work falls back to Antigravity rather than changing aliases on the same provider. - Server, materializer, dummy and specialized search work have no generic fallback. If no appropriate fallback exists, the task enters REVIEW with OWNER_DECISION. The runtime never substitutes a text-only model for coding/system work. Existing Codex work keeps its Factory-root working directory. DeepSeek is restricted to Factory/workspaces, so Codex work outside that sandbox stops for owner review rather than silently moving the checkout. A stored compatible workspace enables Codex-to-DeepSeek fallback; DeepSeek-to-Codex preserves the existing workspace. Workspace paths persist on tasks. Attempts append execution history and separate output/round artifacts; retries never clear task results, decision notes or files. Recovery instructions include bounded prior attempt/dependency summaries and artifact references. Legacy recovery without an outcome journal is at-least-once: side-effecting executors must be resumable/idempotent. Prepared journals now replay finalization without executing again; incomplete journals require owner review. The runtime cannot infer whether an unrecorded external action completed. RECOVERY_DECISION events contain JSON with executor, failure class/reason, recovery action, next state, next executor and retry time. Project snapshots and existing execution details expose these fields. UI changes are limited to those monitoring fields. Schema upgrades are additive and idempotent. Offline verification (temporary SQLite databases and artifacts, stub executors): ```sh .venv/bin/python -m unittest -v control_plane.tests.test_runtime control_plane.tests.test_control_plane_dispatcher .venv/bin/python -m unittest discover -s control_plane/tests -q .venv/bin/python -m unittest discover -s executors/tests -q ``` The controlled A -> B -> C test runs the real polling/claim/recovery paths. B fails twice with HTTP 503, retries then falls back from Antigravity to Nemotron, succeeds, and automatically releases C. It asserts preserved output artifacts, workspace data, monotonic history and structured recovery events; PLANNED work remains untouched. Other tests cover coding workspace continuity, checkpoints, independent branches, delayed claims, crash recovery, budgets, concurrent claims, operator overrides and migration from the previous schema. No live providers, production tasks, L-IT or Coral are involved. Independent validation (2026-10-07), run from repository root: Control Plane module invocation and discovery each report **46 passed** (18 runtime tests and all 28 existing regressions); executor suite **123 passed**, all exit 0. The runtime tests use a package-qualified fixture import. The A -> B -> C test asserts every poll's state, attempts 1/2/3, two failures followed by success, and exactly two recovery decisions without operator changes. Backoff is set to zero only in this controlled flow; durable retry gating and the cap are tested separately. The monitoring template is rendered and checked for failure class, reason and recovery action. Compilation checks also pass. Additional legacy dispatcher discovery (`.venv/bin/python -m unittest discover -s dispatcher/tests -q`) reports **96 tests, 84 passed, 12 failed**. All failures are in `test_deepseek`: these tests expect the former text-only executor, whereas the current coding executor first requires a workspace. These legacy tests do not import the modified Control Plane dispatcher. They and the DeepSeek executor were left unchanged; this result is not an all-repository green claim. Real-project integration (2026-10-07): `cycle(project_key="LEAD-GEN")` limits scheduling, reconciliation and orphan recovery to that project and uses a project lock for a supervised nested run. It also holds the global lock when available; if a parent supervisor holds it, the scoped run skips orphan recovery so it cannot re-arm any live worker. Atomic claims prevent duplicate execution. Normal unscoped dispatch retains its global lock. Human-only tasks use executor `human` plus checkpoint=1. Once dependencies pass, they enter REVIEW without calling any executor. Explicitly approved executor work may return `FACTORY_OUTCOME: OWNER_CHECKPOINT` when required inputs are missing; this marks the task as a checkpoint and gates descendants on acceptance. Other successful output is persisted to an empty task Result; owner-authored Results are preserved. Full output/error artifacts and execution history remain separate from the bounded Result. Direct dependency output content and accepted local document content are included for executors that cannot read local files. Research/discovery instructions route to Perplexity rather than text-only models. Antigravity startup failures caused by unavailable local sockets/filesystem are classified EXECUTOR_UNAVAILABLE, immediately falling back to a configured text provider. An unavailable executor is excluded from further fallback for the task. A narrowly guarded reconciliation corrects old misclassified startup failures on explicitly approved tasks, preserving the original event and adding RECOVERY_CLASSIFICATION_CORRECTED. Ordinary task failures still require an owner. The real LEAD-GEN run released eight existing tasks but stopped on LEAD-001.2: Antigravity could not start in the restricted execution environment, and two Nemotron/OpenRouter attempts failed to connect. This verifies real release, selection, retry/fallback and persisted monitoring, **not successful lead work or end-to-end completion**. See `data/artifacts/FACTORY-RUNTIME/lead-gen-e2e/`. ## GitHub и Git: существующие доступы (состояние на 2026-11-09) **Аккаунт:** `AK34cy`. Он подключён к ChatGPT GitHub Plugin: доступны личные репозитории, в том числе приватные. Для организаций разрешения установленного приложения могут отличаться от прав самого аккаунта. **Организации:** - `iovon` — аккаунт `AK34cy` является владельцем; репозиторий `iovon/iovon-dev-console`. Доступ через ChatGPT GitHub Plugin проверять отдельно. - `L-IT-GmbH` — аккаунт имеет роль Member; доступно чтение приватного `L-IT-GmbH/Website`. Fork запрещён политикой организации. Установка ChatGPT Codex Connector требует одобрения администратора; ранее отправленный запрос пользователь отменил. **Сервер `iovon.com`:** Linux, рабочий пользователь `iovon`, Git 2.43.0, GitHub CLI (`gh`), HTTPS для GitHub. Сервер доступен через Remote Desktop Commander. 2026-11-09 `gh auth status` подтвердил авторизацию `AK34cy`, а `git ls-remote` успешно прочитал HEAD приватного `L-IT-GmbH/Website`. Для этого сценария новые SSH-ключи не требуются. **Проверенный перенос (2026-11-09):** `L-IT-GmbH/Website` → приватный `AK34cy/lit-website`. Оригинал клонирован на IOVON, история Git удалена в рабочей копии, репозиторий инициализирован заново, сделан первый коммит, через `gh` создан приватный репозиторий и загружена ветка `main`. Рабочая директория: `/home/iovon/projects/lit-website/source`. Исходный репозиторий организации не изменён. **Это подтверждённый пример, не требование сбрасывать историю Git при каждом копировании.** **Порядок работы исполнителей:** 1. Сначала проверить существующий доступ и авторизацию: GitHub Plugin и/или `gh auth status` на IOVON. 2. Если Plugin не видит организационный репозиторий, проверить доступ с сервера через `gh` / `git ls-remote`; отсутствие в Plugin не означает отсутствие прав у пользователя. 3. Не предлагать новую авторизацию, SSH-ключи или установку коннектора, пока существующие средства не проверены. 4. Различать права аккаунта, права в организации и разрешения конкретного GitHub-приложения. 5. Не изменять оригинальные репозитории сторонних организаций без явного разрешения владельца. 6. Если нужна независимая разработка, создавать приватную рабочую копию в `AK34cy` с учётом прав и условий доступа к исходному коду. 7. Не выводить токены или содержимое credential storage в логи и отчёты. **Реестр инструментов:** `config/resources.json` (секция `local_tools`). ## Durable dispatcher finalization (2026-11-29; pending independent review) The dispatcher now closes SQLite context-managed connections deterministically on both commit and rollback, including failed commits. No connection or read cursor from task preparation is retained across executor execution. SQLite's native connection context alone does not close a connection. Before launching an executor, the dispatcher atomically writes the original file baseline to `data/artifacts/outcomes/<database-path-hash>/<execution-id>.json`. It saves the returned executor result before verification, then atomically replaces the journal with the complete baseline/result/verification/finalization payload before opening the final DB transaction. Each replacement uses a sibling temporary file, file fsync, rename, and directory fsync, plus a SHA-256 envelope. The journal retains full outcome text separately from SQLite's bounded preview. It is operational evidence, not an owner acceptance or a security boundary. Finalization retries only SQLite BUSY/LOCKED, at most four whole transactions (5-second SQLite busy timeout each, 50/100/200 ms intervening backoff). Every failed transaction rolls back and closes before retry. Persistent contention leaves the RUNNING attempt and journal intact. Every dispatcher poll, including the first after restart, checks orphans before dependency scheduling. Prepared journals replay the saved result without invoking executors or verification commands. A terminal execution is a no-op, so replay cannot duplicate DB artifacts/events or consume another attempt. Deliverables retain existing checksum validation and registration failure semantics. A host-local per-task flock is acquired before claim and held through execution and finalization. Recovery must acquire the same lock nonblocking; busy workers are skipped regardless of age. Existing global/scoped dispatcher locks remain. This is single-host coordination, not a distributed lease; deleting/replacing lock files or changing database/artifact paths while workers run is unsupported. The legacy `startup_recovery()` one-shot API uses the same fenced replay path; normal polling does not depend on its one-shot flag. Incomplete/corrupt journals produce INTERRUPTED with unknown exit code and EVIDENCE_MISSING/REVIEW, preserving the journal for inspection. They never invent success or automatically repeat possibly completed work. Older executions with no journal retain legacy bounded PROCESS_CRASH retry/fallback behavior; an unrecorded external side effect cannot be inferred. The tiny interval after claim and before the first journal precedes executor launch. Active R1-managed cycles and cycle-bound executions are excluded from legacy recovery/finalization; cycle recovery remains R3 scope. Owner task status/result/notes and retry fields are preserved when an owner has moved the task out of RUNNING. Dependency and checkpoint acceptance gates and attempt budgets remain in the normal claim path. Code remains PARKED/pending activation. No migration is introduced. Do not use this documentation as authorization for a restart, deployment or production repair. For the offline evidence and incident limitations see `data/project_materials/FACTORY-RUNTIME/review/dispatcher-recovery-fix.md`. Recovery hardening (still PARKED): each orphan is isolated. One non-lock finalization failure parks only that execution as INTERRUPTED/unknown exit, `RECOVERY_FAILED`, and its still-RUNNING task as REVIEW. The retained journal is not replayed against a terminal attempt. BUSY/LOCKED exhaustion leaves the attempt/journal intact for another poll; inability to write REVIEW also preserves the attempt. Diagnostics are best-effort and cannot abort healthy recovery or worker collection. Global DB contention can still prevent claims until released. Mixed versions are unsupported. The default production DB now requires a versioned activation receipt before initialization, recovery or claim. Only a separately authorized idle rollout may publish it: disable all launch sources, drain without interrupting live work, stop every old/scoped worker, verify zero RUNNING/QUEUED executions and zero RUNNING tasks globally. The activation helper checks the existing global flock and read-only idle counts, with explicit operator attestations for workers that do not hold that lock. Temporary DB overrides are for offline tests, not production activation. Runbook §8.1–8.3 is the operational procedure for activation refusal, receipt invalidation, rollback, indefinite unresolved-journal retention and operator REVIEW handling. No production receipt was issued by this hardening task.