FACTORY_OUTCOME: COMPLETED ## Сводка для владельца Итог: в DEV (`/home/iovon/ai-factory-dev`, коммиты `bde3231`, `2961037`) реализованы: песочница с очищенным env и минимальными монтированиями без сокетов хоста, fail-closed маршрутизация fake-исполнителей, замороженные зависимости с манифестом, одноразовое состояние и надёжный ненулевой общий код тестов; динамически проверено на хосте (9/9 проверок границы, 17 новых тестов, базовые 15/13/4 падений без изменений). Готов переносимый патч маршрутизации Factory (выключен по умолчанию), его принудительное действие показано офлайн. Проблемы: ABC-тесты (15 падений control_plane) по-прежнему красные и остаются блокером выпуска; маршрутизация только задаёт рабочий каталог реального агента, но не изолирует его; PROD не менялся, патч и режим не активированы; в DEV остаются жёстко прописанные пути прежней базы (код целиком в PROD переносить нельзя). Решение: разрешить ли отдельную задачу независимой проверки этого DEV-коммита и пилотного применения только патча `patches/factory-workspace-routing.patch` (отдельное окно, с конфигом `enabled:false` → затем `true`), а также отдельную задачу по ABC-падениям; активацию PROD не разрешать до этого. # R1.5a — DEV safety: test isolation, fail-closed fakes, workspace routing patch (task 260) Scope kept: all edits in `/home/iovon/ai-factory-dev`; PROD only read (the PROD venv `site-packages`, the task 259/260 reports and `harden-evidence/resume-full-failures.json`) and this report written. **No PROD source/config/service/DB change, restart, migration or activation; no real executor/CLI launched; no network.** PROD parity re-check: `sha256sum -c PROD_PARITY.sha256` run in PROD → exit 0 (all 295 manifest files unchanged). One slip, already undone: I once unpacked venv site-packages into the host `/tmp` by mistake (not PROD); I removed exactly those entries; only the pre-existing `cc-socks` and `claude-1001` remained. ## 1. DEV Git state (tags preserved) | Ref | Commit | Meaning | |---|---|---| | `dev-baseline-0-pristine-unverified` | `ccd1bd4` | unchanged | | `dev-baseline-1-isolated-unverified` | `e7891e3` | unchanged | | `dev-baseline-2-safety-unverified` | `bde3231` | all safety work | | `dev-baseline-3-r15a-final-unverified` (HEAD) | `2961037` | + portable patch file | Nothing is called stable. Working tree clean after commits. ## 2. Mapping to review findings | Task-260 finding | What was done | Evidence | |---|---|---| | 1 Inherited env, host visibility, sockets | `dev_tools/run_sandboxed.sh` rewritten: re-execs with `env -i`; bwrap `--unshare-all --clearenv`; only an allowlist is set (`PATH HOME TMPDIR LANG PYTHONPATH=/deps PYTHONDONTWRITEBYTECODE PYTHONNOUSERSITE PYTEST_DISABLE_PLUGIN_AUTOLOAD AI_FACTORY_*`). Mounts: `/usr` ro, `/etc/ld.so.cache` ro, `/proc`, `/dev`, tmpfs `/tmp`, frozen deps ro, disposable source copy. Absent: `/run /var /opt /srv`, rest of `/etc`, `/home` except the DEV path, PROD tree, venv. `/usr/bin/node` masked, `/usr/lib/node_modules` emptied (so `/usr/bin/codex`, gemini, npm dangle); `claude` is under `/home` (not mounted). | `dev_tools/verify_sandbox.sh` 9/9 PASS (below) | | 2 Fake routing partial/opt-in | New `control_plane/execution_mode.py`. Fake mode = `AI_FACTORY_EXECUTION_MODE=fake` **or any legacy hint** (`AI_FACTORY_DEV`, `AI_FACTORY_EXECUTOR_DIR`); invalid value, `real`+hints, missing dir, missing fake module, or path-like name → `ExecutionModeError` (never fall back to real). Wired into `dispatcher/control_plane_dispatcher.load_executor`, legacy `dispatcher/dispatcher.load_executor`, `openrouter_registry.load_executor` (aliases → `fake_executors/_registry_alias.py`). Direct paths: first line of every real `run`/`run_text`/`run_research` in 11 executors + 3 providers + `Executor.run` is `forbid_real(...)`. A static test fails if any new `run` lacks the guard. Pytest-only second layer `conftest.py`: in fake mode or inside the sandbox, spawning anything outside `{python*,sh,true,false,sleep,cat,echo}` (or `shell=True`) and connecting to non-loopback/unix paths outside `/tmp` raise. | `control_plane/tests/test_execution_mode.py` 8 tests / 53 subtests; mutation check: deleting the guard from `executors/codex.py` made 2 tests fail, then restored | | 3 No enforced Factory→DEV routing | `control_plane/workspace_routing.py` + hook in `claim()`; portable patch (§5). Separate from fake execution: this decides where a *real* dev agent works; fakes decide whether *tests* may run real code. | `test_workspace_routing.py` 9 tests / 7 subtests | | 4 Writable shared DEV, unpinned venv | Each run copies `git ls-files --cached --others --exclude-standard` into a fresh temp dir mounted at the DEV path; the copy (incl. `data/`, DB, locks, workspaces) is deleted on exit — nothing is written to the checkout (verified). The PROD venv is no longer mounted: `.deps/` (gitignored, 2626 files, 147 MB, read-only) is a copy of its `site-packages` (pip excluded) attested by committed `dev_tools/deps/MANIFEST.sha256` (+`requirements.lock`, 41 pins); the runner calls `deps/verify.sh` first and refuses to run on any missing/extra/changed file (tamper test exit non-zero). `build.sh` rebuilds from a given site-packages dir and re-verifies. | verify_sandbox.sh | | Test exit not reliable | `dev_tools/test_all.sh` rewritten: no pipes into `tail`, one sandbox per suite, `rc` captured, per-suite failing ids compared with `dev_tools/baseline/*.txt`. Exit **0** all pass; **1** only baseline failures (still not success); **2** new failure, collection error, missing baseline, no summary line, runner/sandbox/deps error. | tested below | ## 3. Host verification (this host, bubblewrap works with `--unshare-all`; the sandbox is never weakened — if bwrap cannot start nothing runs, no fallback) `dev_tools/verify_sandbox.sh` (canaries injected into the caller: `OPENROUTER_API_KEY`, `ANTHROPIC_API_KEY`, `HTTPS_PROXY`, `PYTHONPATH=/evil`, `LD_PRELOAD`, `SSH_AUTH_SOCK`, `DBUS_SESSION_BUS_ADDRESS`): - inside env keys: `AI_FACTORY_DEV, AI_FACTORY_EXECUTION_MODE, AI_FACTORY_EXECUTOR_DIR, AI_FACTORY_SANDBOX, HOME, LANG, PATH, PWD, PYTEST_DISABLE_PLUGIN_AUTOLOAD, PYTHONDONTWRITEBYTECODE, PYTHONNOUSERSITE, PYTHONPATH, TMPDIR`; canaries: none; `PYTHONPATH=/deps`. - `/` = `bin deps dev etc home lib lib64 proc sbin tmp usr`; `/home` = `iovon/ai-factory-dev` only. `/run /var /opt /srv /etc/passwd /etc/ai-factory /home/iovon/.local/bin/claude /home/iovon/ai-factory(+secrets) /usr/bin/codex /run/dbus/system_bus_socket /var/run/docker.sock` all absent; `/usr/bin/node` size 0. - network: `1.1.1.1:80` errno 101, `127.0.0.1:9` refused; only interface `lo`. - sandbox writes (`sandbox-write-probe.txt`, `data/probe`) not present in the checkout afterwards; tampered `.deps` → payload did not run; deps re-attested after restore. **9 PASS, exit 0.** Test suites (`dev_tools/test_all.sh`, ≈25 s, aggregate exit 1 = baseline only): | Suite | Tier | Result | vs earlier evidence | |---|---|---|---| | control_plane/tests | fake | 15 failed / 236 passed / 136 subtests | failing ids identical to `resume-full-failures.json` (15); +17 new tests, all pass | | dispatcher/tests | real-mocked | 13 failed / 83 passed | same counts as task 259 | | executors/tests (`*0078*` ignored) | real-mocked | 4 failed / 37 passed | same counts | | tests/ | fake | 8 passed | same | Aggregate-exit proofs: `DEV_SUITES=tests` → 0; added a failing test file → 2 (diff of ids printed); `.deps` hidden → runner exit 3 → aggregate 2. (A first version of my script wrongly returned 1 on a new failure because of a loose "error" grep; found by that injection test and fixed before commit.) Tiers: suites that import real executor/provider modules and mock their I/O (dispatcher, executors) fail by design when `forbid_real` is active, so they run with `DEV_EXEC_MODE=real` — still inside the same sandbox (no network, creds, CLIs) with `conftest.py` spawn/socket denial. Control-plane flow tests run in fake mode. ## 4. Fake vs real separation (summary) - **Fake test execution:** runner default (`fake`), fail-closed as above; success strings (`AI_FACTORY_DEV_FAKE_OK`) prove routing only, not artifact delivery or ABC. - **Real development agent routing:** unrelated to fake mode; config-driven, inert unless configured, never decided by `AI_FACTORY_DEV`. - Alias coverage: every `BUILTIN` name and every registry alias is loaded in fake mode with `providers.openrouter.run_text` patched to raise — none reached it. ## 5. Portable Factory routing patch (NOT applied to PROD) `patches/factory-workspace-routing.patch` in DEV (sha256 `26a52b7e4616db124084f8eb86d65a7a23b62bb01300c56ceddd16c850fbd8c8`, 4 files, +155/−1): `control_plane/workspace_routing.py`, 9-line hook in `claim()` replacing the single `workspace=` line, `control_plane/tests/test_workspace_routing.py`, `config/dev_routing.json.example` (`enabled:false`). No hardcoded path (a test asserts neither `/home/` nor `ai-factory` appears in the module); the dev root comes only from config (`config/dev_routing.json` or `AI_FACTORY_DEV_ROUTING_FILE`). Behaviour: no config file → identical to today (codex/claude-code default to the code root). Enabled → for routed executors (default `codex`, `claude-code`; optional `executors`, `project_keys`) the workspace is the configured root when unset, otherwise must resolve (symlinks followed, `..` collapsed) inside it; root must be absolute, existing, and neither equal to, containing nor inside the dispatcher code root; unreadable/invalid config **fails closed**. Violation → task set to `REVIEW`, event `WORKSPACE_ROUTING_REFUSED`, **no execution row created**. Offline demonstration (real `claim()`, temp DB, no executor started): unconfigured codex task → code root (legacy); enabled → dev root; subdirectory accepted; outside path, code root, `..` escape, symlink escape → refused/parked with 0 executions; root overlapping code root/missing/relative and broken JSON → refused; `dummy` executor and unlisted project untouched. Applicability checks: `git apply --check` + apply succeeded on (a) a temp copy of the *current PROD* control_plane/dispatcher/executors/providers/config files and (b) an export of the pristine tag; the new tests then passed there (9 passed/7 subtests) inside a bwrap with no network (temp copy, removed). PROD was not patched. **Not in the patch (DEV-only harness):** `execution_mode.py`, guards in executors/providers, `conftest.py`, sandbox runner, fakes. They are path-free in code but have not been reviewed for PROD; promoting them is a separate decision. ## 6. Limitations / residual risk (explicit) 1. **Placement is not confinement.** The patch sets the agent's working directory; a real codex/claude process can still touch anything its OS user can. Real-agent sandboxing is not implemented or tested. 2. **ABC remains a blocker:** the 15 control_plane failures (incl. `test_abc_transient_retry_fallback_and_artifact_continuity`, supervisor ABC) are unchanged — not fixed, not reclassified. dispatcher 13 / executors 4 baselines were recorded from this DEV run (counts equal task 259; ids not compared with a fresh pristine run). 3. Sandbox relies on host bubblewrap/user namespaces; `/usr` (incl. system python and libs) is trusted and not hash-attested; `.deps` is attested but is a copy of the PROD venv taken on 2026-11-30, i.e. it inherits any defect there. `ld.so.cache` is the only `/etc` file. 4. `conftest.py` protects only pytest processes; a dispatcher process in fake mode depends on routing + sandbox. `DEV_EXEC_MODE=real` exists for mocked unit tests and relies on the sandbox/conftest, not on `forbid_real`. 5. DEV still carries the hardcoded DEV paths from baseline-1 (executors, providers, deploy/systemd, privileges); the runner mounts the snapshot at its own real path so they resolve. Do **not** promote HEAD wholesale; only the patch above is portable. 6. Not done (outside scope or not testable here): port reservations, exit-78/`RestartPreventExitStatus` policy, release/rollback rehearsal, immutable release dir, power-loss/load/mixed-version tests, independent review of this commit. Snapshot copies only git-visible files (tracked + untracked non-ignored); ignored data is intentionally absent. 7. No secrets collected; canary values were synthetic. ## 7. Reproduce `dev_tools/deps/verify.sh` · `dev_tools/verify_sandbox.sh` · `dev_tools/test_all.sh; echo $?` (expect 1) · `git apply --check patches/factory-workspace-routing.patch` in a copy of the target tree. Logs in DEV `data/test-logs/` (gitignored).