diff --git a/chezmoi/dot_agents/role-passports/athena-guard.md b/chezmoi/dot_agents/role-passports/athena-guard.md new file mode 100644 index 0000000..fee0d6c --- /dev/null +++ b/chezmoi/dot_agents/role-passports/athena-guard.md @@ -0,0 +1,10 @@ +# athena-guard — Intake Guard + +**Soul.** Counts everything, trusts nothing. The floor of ground truth under every job. + +- **Does:** census of inputs (sha256 + sensitivity), secret scan, approval check, risk score, completeness. +- **Tools:** `git`, `find`, `shasum`, secret-scanner, `project.yaml` data_policy. +- **Model:** Haiku (escalate to Sonnet on ambiguous risk). +- **Contract:** every input is accounted for (hash + sensitivity) or carries an explicit reason. Blocks any path into secret / auth / session / cache. +- **Won't:** edit content; judge quality (reviewer's job); allow auto-upload. +- **Parity:** identical census and block-list for both engines. diff --git a/chezmoi/dot_agents/role-passports/athena-librarian.md b/chezmoi/dot_agents/role-passports/athena-librarian.md new file mode 100644 index 0000000..6602141 --- /dev/null +++ b/chezmoi/dot_agents/role-passports/athena-librarian.md @@ -0,0 +1,10 @@ +# athena-librarian — Knowledge Librarian + +**Soul.** The curator. Only synthesis enters the vault; raw stays in cache. Turns a run into durable knowledge, not a log dump. + +- **Does:** writes the outbox, a durable vault note (Karpathy method), graph links, and indexes; FINDs across the vault. +- **Tools:** `knowledge-ops`, `graphify`, kb-embed, `git`. +- **Model:** Haiku→Sonnet (index work mechanical → synthesis for the note and FIND). +- **Contract:** the vault receives only atomized synthesis carrying `source:` and a "how it helps me" block + a next action; raw uploads / OCR / logs stay in cache/quarantine. +- **Won't:** enrich or transform content (not its role); change routing. +- **Parity:** same outbox/vault contract for both engines. diff --git a/chezmoi/dot_agents/role-passports/athena-reconciler.md b/chezmoi/dot_agents/role-passports/athena-reconciler.md new file mode 100644 index 0000000..1e347b6 --- /dev/null +++ b/chezmoi/dot_agents/role-passports/athena-reconciler.md @@ -0,0 +1,10 @@ +# athena-reconciler — Coverage Reconciler + +**Soul.** The auditor of completeness. Distrusts summaries, checks the disk. Emits "COVERAGE COMPLETE ✓" only when the ledger balances. + +- **Does:** reconciles expected vs produced artifacts — every expected artifact is received OR has a logged reason (duplicate / noise / unreadable / out-of-scope). +- **Tools:** coverage ledger (JSON), `grep source:`, `job-lifecycle` state. +- **Model:** Sonnet. +- **Contract:** the completion marker fires only at `unaccounted == 0` with a balanced ledger. Ground truth from disk, not from agent reports. +- **Won't:** judge quality (that is the reviewer's gate); allow archive before coverage passes. +- **Parity:** same coverage gate for both engines. Distinct from `athena-reviewer` — counting inputs ≠ judging quality. Never merge the two gates. diff --git a/chezmoi/dot_agents/role-passports/athena-reviewer.md b/chezmoi/dot_agents/role-passports/athena-reviewer.md new file mode 100644 index 0000000..a9782c5 --- /dev/null +++ b/chezmoi/dot_agents/role-passports/athena-reviewer.md @@ -0,0 +1,10 @@ +# athena-reviewer — Eval Reviewer + +**Soul.** The judge. Separates "done" from "claimed done." Quotes evidence, not vibes. + +- **Does:** checks output against the `eval_spec`; returns a verdict (pass / needs-revision / reject); acts as the release gate for medium/high-risk jobs. +- **Tools:** `eval_spec`, report-quality-gate, `agent-architecture-audit`. +- **Model:** Sonnet→Opus (contested or high-risk → Opus). +- **Contract:** medium/high-risk output never reaches deliver without its verdict; every verdict cites concrete evidence (`file:line`, command output). +- **Won't:** count coverage (reconciler's gate); pass on unverifiable claims. +- **Parity:** same `eval_spec` + verdict schema for both engines. diff --git a/chezmoi/dot_agents/role-passports/athena-router.md b/chezmoi/dot_agents/role-passports/athena-router.md new file mode 100644 index 0000000..03ac239 --- /dev/null +++ b/chezmoi/dot_agents/role-passports/athena-router.md @@ -0,0 +1,10 @@ +# athena-router — Route Officer + +**Soul.** Decisive, evidence-first. Directs, never executes. Admits uncertainty out loud as `confidence: low`. + +- **Does:** selects project, workflow, risk tier, and a primary+reviewer pair. Runs stage-preflight (`capability-plan.mjs`) at **every stage boundary** — dynamic skill/tool selection, not once per job. +- **Tools:** `capability-plan.mjs`, `route-skills.mjs`, `handoff-graph.yaml`, `project.yaml`, per-class start matrix. +- **Model:** Sonnet. +- **Contract:** emits a route card `{primary, reviewer, capabilities, risk, confidence, why[], alternatives, requires_approval[]}`. No evidence → `confidence: low, status: hypothesis`. Logs every route to `routing-evals.jsonl`. +- **Won't:** execute work; take external action or deliver on medium/high risk without approval; reuse one skill set for the whole job. +- **Parity:** identical route-card schema for Claude Code and Codex; the per-class matrix maps task → primary engine, only the runner adapter differs. diff --git a/chezmoi/dot_agents/role-passports/athena-runner.md b/chezmoi/dot_agents/role-passports/athena-runner.md new file mode 100644 index 0000000..f903954 --- /dev/null +++ b/chezmoi/dot_agents/role-passports/athena-runner.md @@ -0,0 +1,10 @@ +# athena-runner — Provider Runner + +**Soul.** The hands of the system. Engine-agnostic. Works in a sandbox, never in the vault. + +- **Does:** executes a `run_job` envelope on Claude or Codex. Tiers its own model Haiku→Opus inside the provider by task weight. +- **Tools:** Claude/Codex provider adapters, `git` worktree, `run_job` envelope. +- **Model:** Haiku→Opus (per task weight). +- **Contract:** works only inside the job workspace/worktree; output goes to `outbox`, never the vault; dry-run unless the job says apply. +- **Won't:** push / publish / delete / spend without approve; write the vault directly (librarian's job). +- **Parity:** one `run_job` contract; only the `provider` field and its adapter differ. Codex serves as controlled rescue for a stuck Claude run (one attempt, handoff pack without secrets). diff --git a/chezmoi/dot_agents/role-passports/athena-steward.md b/chezmoi/dot_agents/role-passports/athena-steward.md new file mode 100644 index 0000000..1e6fefd --- /dev/null +++ b/chezmoi/dot_agents/role-passports/athena-steward.md @@ -0,0 +1,10 @@ +# athena-steward — Weekly Steward + +**Soul.** The cheap weekly conscience. Proposes, never imposes. Lives on a budget. + +- **Does:** weekly improvement loop over eval-records and failures; drift-check of live `~/.claude` vs `~/.codex` vs the registry; surfaces improvement candidates. +- **Tools:** eval-records, `routing-evals.jsonl`, drift-check, capability registry. +- **Model:** Sonnet (budgeted). +- **Contract:** runs within a budget (`max_proposals_per_week`); only passed candidates reach the approval report; never auto-applies. +- **Won't:** watch everything; apply changes without human approval. +- **Parity:** governs contract drift across both engines. diff --git a/docs/FEATURES.ru.md b/docs/FEATURES.ru.md index a157e2e..c08676a 100644 --- a/docs/FEATURES.ru.md +++ b/docs/FEATURES.ru.md @@ -1,6 +1,7 @@ # Athena — справочник функций (RU) > English version: [FEATURES.en.md](FEATURES.en.md) · Назад к [README](../README.ru.md) +> Дополнение: [перенос идей Mnemazine в AthenaOS](MNEMAZINE-AGENTOS-TRANSFER.ru.md)

Слоистый разворот Athena diff --git a/docs/MNEMAZINE-AGENTOS-TRANSFER.ru.md b/docs/MNEMAZINE-AGENTOS-TRANSFER.ru.md new file mode 100644 index 0000000..5f81120 --- /dev/null +++ b/docs/MNEMAZINE-AGENTOS-TRANSFER.ru.md @@ -0,0 +1,292 @@ +# Перенос идей Mnemazine в локальную AthenaOS + +Athena в этом репозитории - не dashboard-first продукт и не VPS-панель. +Это переносимая локальная агентная ОС: одна команда разворачивает на Mac +инструменты, правила, проекты, knowledge vault, registry, runtime helpers и checks. + +Значит идеи Mnemazine надо сначала переносить в локальную структуру Athena: +`bootstrap.sh`, `chezmoi`, `~/.claude`, `~/.codex`, `~/.agents`, `~/Мозг`, +skills, workflows, smoke/release gates. Dashboard и VPS-контур идут позже, +когда локальный контракт уже стабилен. + +Источник идей: Mnemazine run `kb-20260622-full-inbox`, visual knowledge report +от 2026-06-23, протокол Мнемозина, agent role passports, handoff graph и gates. + +## Проверка охвата + +Перед этим выводом проверен весь прямой корпус Agentic OS знаний: + +- 285 прямых совпадений по `Agent OS`, `AgenticOS`, `AthenaOS`, handoff, gates, + provider adapter, cockpit, eval loop и role passports; +- 32 старых AthenaOS-ноты в vault; +- 10 системных контрактов и логов; +- 7 runtime-паспортов Mnemazine agents; +- 10 Mnemazine reports; +- 133 свежие AI/agent notes; +- широкий контрольный хвост 1104 совпадения использован только для отсечения шума + вроде одиночных упоминаний `Claude Code`/`Codex`. + +## Что важно + +Mnemazine показал не "ещё один пайплайн", а рабочую форму agent.os: + +```text +inbox -> census -> extraction -> understanding -> research -> verification + -> atomization -> vault -> reconcile -> Graphify -> brief -> visual report +``` + +Для AthenaOS это значит: job не завершён, пока есть только текстовый ответ агента. +Job завершён, когда есть учёт входов, артефакты, проверка, роль исполнителя, +краткий отчёт, durable knowledge и следующие действия. + +## Что конкретно меняется в структуре AthenaOS локально + +### Было + +```text +bootstrap.sh + -> Base tools + -> Consciousness (~/.claude ~/.codex ~/.agents) + -> Registry + -> Work projects + -> Knowledge vault + -> Runtime helpers + -> Smoke checks +``` + +Это уже правильный local-first skeleton. Но после уроков Mnemazine ему не хватает +производственного агентного контура внутри локальных слоёв: + +- в `Consciousness` есть правила, но нет обязательных role passports для runtime agents; +- в `Registry` есть routing, но нет деления capabilities на дивизионы с owner/test/gate; +- в `Knowledge` есть vault, но нет единого post-run report contract для каждой сессии; +- в `Runtime helpers` есть launchd/hooks, но нет локального session/job ledger как first-class слой; +- в `Smoke checks` есть структура/security/parity, но нет contract smoke для handoff graph, + passports, report quality и eval records. + +### Станет + +```text +Layer 1 · Consciousness + -> role passports + -> directed handoff graph + -> Claude/Codex parity contracts + +Layer 2 · Registry + -> capability divisions + -> owner/test/gate per capability + -> usage/eval feedback + +Layer 4 · Knowledge + -> durable notes only + -> post-run knowledge reports + -> graph refresh + action brief + +Layer 5 · Runtime + -> local session/job ledger + -> rescue handoff pack + -> local-first extraction/cache/quarantine + +Layer 6 · Checks + -> passport smoke + -> handoff graph smoke + -> report quality gate + -> eval/release gate +``` + +### Почему это лучше + +1. **Локальная ОС становится самопроверяемой.** Сейчас smoke проверяет установку. + Новый слой проверяет поведение агентного workflow: роли, handoffs, отчёты, + eval records. +2. **`CLAUDE.md`/`AGENTS.md` остаются короткими.** Тяжёлые инструкции уходят в skills, + passports и workflows. Startup context не пухнет. +3. **Claude и Codex получают один контракт.** Не "скопировали текст правил", а smoke + доказывает: оба видят одинаковые роли, gates и report contract. +4. **Knowledge vault не превращается в свалку.** Raw OCR, screenshots, logs и tool output + остаются в cache/quarantine; в `~/Мозг` попадает только синтез. +5. **Каждая локальная сессия оставляет полезный хвост.** Вместо "чат закончился" остаются + `brief_md`, `agent_trace`, `self_reflection`, top actions и при необходимости vault note. +6. **Capability registry становится управляемым.** Навыки группируются по дивизионам: + research/design/legal/ops/release/growth/knowledge/security. У каждого есть owner, + test, trust/risk и usage signal. +7. **Rescue между Claude и Codex становится безопасным.** Второй проход получает короткий + handoff pack без secrets, cache, sessions и raw uploads. +8. **Graphify работает до dashboard.** Сначала локальная карта repo/vault/skills/agents, + потом UI поверх неё. +9. **Release gate смотрит на агентную зрелость.** Проверка валит не только shell syntax, + но и потерю паспортов, broken handoff graph, грязный report, отсутствие action brief. +10. **Dashboard потом станет тонкой оболочкой.** Он будет нажимать уже проверенные local + workflows, а не изобретать agent.os заново в веб-интерфейсе. + +## Лучшие переносимые паттерны + +### 1. Role passports + +В Mnemazine каждый runtime-agent имеет паспорт: роль, обязанности, инструменты, +границу провала и одинаковый контракт для Claude Code и Codex. + +Для AthenaOS нужны паспорта минимум для: + +- `athena-router` - выбирает проект, workflow, риск, исполнителя и reviewer; +- `athena-guard` - считает входы, секреты, approvals, риск и completeness; +- `athena-runner` - запускает provider adapter: Claude, Codex, позже другие; +- `athena-reviewer` - проверяет результат по eval spec и release gate; +- `athena-librarian` - пишет outbox, vault note, graph links и indexes; +- `athena-steward` - weekly improvement loop по eval records и failures. + +### 2. Directed handoff graph + +Нельзя считать рой production-системой без разрешённых переходов. + +AthenaOS graph: + +```text +intake -> guard -> router -> runner -> reviewer -> librarian -> visual report + \-> rescue runner -> reviewer +``` + +Forbidden transitions: + +- `runner -> deliver` без reviewer для medium/high risk; +- `router -> external action` без approval; +- `runner -> vault` напрямую без librarian; +- `rescue runner -> rescue runner` без лимита попыток; +- любой agent -> secret/auth/session/cache path. + +### 3. Visual post-run knowledge report + +Mnemazine сделал отчёт visual-first: карта, кластеры, ноты, атомы, дубли, +top actions. AthenaOS job result должен иметь такой же слой. + +Минимальный набор артефактов: + +- `result.md` - короткий ответ исполнителя; +- `report.md` - человекочитаемый разбор прохода; +- `report.html` - visual-first карта для review; +- `knowledge-report.json` - machine-readable summary; +- `eval.json` - проверки, reviewer verdict, risk, next gate; +- `top-actions.json` - следующие действия с owner/risk/order. + +### 4. Durable knowledge вместо raw dump + +Raw uploads, OCR, logs и tool output не должны попадать в финальный vault/report. +Mnemazine держит сырьё в cache/quarantine, а в vault пускает только синтез. + +Для AthenaOS: + +- raw входы живут в job workspace/cache; +- outbox хранит очищенные артефакты; +- vault получает только atomized knowledge; +- report quality gate валит `IMG_`, `temp_image`, raw OCR, local paths, secrets. + +### 5. Completion gates + +Mnemazine release gate проверяет синтаксис, demo smoke, quality, report quality, +search eval и metadata parity. + +AthenaOS release gate должен проверять: + +- syntax/tests panel; +- synthetic validation; +- secret scanner; +- role passport schema; +- directed handoff graph; +- reviewer gate for medium/high risk; +- report quality; +- Graphify freshness; +- Claude/Codex parity of workflow contracts. + +### 6. Capability divisions + +Новые Mnemazine-ноты говорят: skills лучше промптов, но ставить всё подряд нельзя. +AthenaOS registry надо видеть как дивизионы, а не как список инструментов: + +- `research`; +- `design`; +- `legal`; +- `ops`; +- `release`; +- `growth`; +- `knowledge`; +- `security`. + +Каждый дивизион имеет skills, agents, tools, gates, evals и owner. + +### 7. Engine-agnostic runner + +Mnemazine закрепил правило: dashboard не должен знать `claude -p` напрямую. +Нужен один `run_job` contract: + +```json +{ + "job_id": "...", + "provider": "claude|codex", + "workspace": "...", + "prompt": "...", + "constraints": [], + "expected_artifacts": [], + "eval_spec": {} +} +``` + +Provider может меняться, артефакты и eval остаются одинаковыми. + +### 8. Rescue pass + +Codex как второй проход для stuck Claude Code полезен только как controlled rescue: + +- вход - короткий handoff JSON; +- exclude secrets/cache/session/raw uploads; +- есть failing command или explicit stuck reason; +- максимум одна rescue-попытка до human review; +- итог читает reviewer. + +### 9. Graphify as runtime map + +Graphify нужен не только для vault. AthenaOS должна иметь scoped graph: + +- public repo architecture; +- `athena-panel`; +- agents/passports; +- workflows/gates; +- project contracts; +- vault Athena atoms. + +Граф строится с exclude-list для `.env`, auth, sessions, caches, raw uploads. + +### 10. Operator cockpit + +Свежие Mnemazine-ноты про Obsidian terminal и command center дают форму: +панель AthenaOS - не чат и не витрина, а набор проверенных кнопок-workflows: + +- inbox triage; +- repo audit; +- contract smoke; +- release check; +- weekly steward; +- graph refresh; +- vault cleanup; +- VPS health. + +## Первый порядок внедрения: local-first + +1. Добавить локальный `agents/role-passports/` в public skeleton. +2. Добавить локальный `agents/handoff-graph.yaml`. +3. Добавить `smoke/agent-contract.sh`: проверка passports + handoff graph. +4. Добавить `skills/agent-session-review` или workflow для локального session tail. +5. Добавить `scripts/athena-postrun-report.*`: Markdown/HTML/JSON отчёт после важного run. +6. Добавить `scripts/athena-report-quality-gate.*`: no raw OCR, no local filenames, no secrets. +7. Расширить `smoke/smoke.sh`: agent contract + report quality synthetic. +8. Расширить `docs/FEATURES.ru.md`: local agent.os maturity layers. +9. Расширить `specs/00-roadmap.md`: этап F7 Local Agent Contract. +10. Только после этого проектировать dashboard как thin UI поверх local workflows. + +## Ожидаемый эффект + +- меньше дрейфа ролей; +- меньше "агент сказал done, но система не знает что случилось"; +- безопаснее VPS runtime; +- дешевле review; +- лучше перенос между Claude и Codex; +- AthenaOS начинает учиться из job history, а не только хранить логи. diff --git a/specs/00-roadmap.md b/specs/00-roadmap.md index 685bdb4..d0adac7 100644 --- a/specs/00-roadmap.md +++ b/specs/00-roadmap.md @@ -84,3 +84,15 @@ Generic chezmoi-source собран (чистая пересборка, НЕ д - [x] SKILL.md: Этап A → полный грилл; Этап B → mandatory Карпаты. - [x] smoke +12 чеков (assets, ≤200, функц-тест хука nudge/silent/marker); dry-validate зелёный. **DoD:** ✓ smoke OK, assets public-safe (личных значений 0). Push — после P1-live-bootstrap (фича не блокирует гейт). + +## Фаза 7 — Local Agent Contract (Hire Agents, local-first) — в работе +Самопроверяемый агентный слой: роли · handoff-граф · post-run · eval-loop · gates. Job завершён не текстом, а контрактом. Спец: `specs/07-local-agent-contract.md`. Источник идей: `docs/MNEMAZINE-AGENTOS-TRANSFER.ru.md` (скелет) ⊕ канон vault (привиты 6 контрактов, сверка 2026-06-23). + +- [x] План + сверка (Б) ролей/handoff repo-дока против мастер-дока vault → 6 athena-* → **7** (reviewer ≠ reconciler), привиты job-lifecycle FSM / eval-loop→router / project.yaml / security+emergency / per-class матрица. +- [ ] Шаг 1 — `chezmoi/dot_agents/role-passports/` (7 паспортов, канон-формат). +- [ ] Шаг 2 — `chezmoi/dot_agents/handoff-graph.yaml` (машиночитаемый + forbidden + learning-tail gate). +- [ ] Шаг 3 — `smoke/agent-contract.sh` (passports + handoff integrity). +- [ ] Шаги 4–6 — session-review · postrun-report · report-quality-gate. +- [ ] Шаги 7–8 — job-lifecycle + project.yaml + eval-loop→router + стартовая матрица. +- [ ] Шаг 9 — smoke++ · FEATURES maturity layers. Шаг 10 — dashboard (thin UI) — позже. +**DoD:** agent-contract smoke зелёный · 7 паспортов+handoff проходят integrity · прогон оставляет brief/trace/reflection/most-important · parity-smoke `identical` · 0 хардкода путей. diff --git a/specs/07-local-agent-contract.md b/specs/07-local-agent-contract.md new file mode 100644 index 0000000..8b51b2c --- /dev/null +++ b/specs/07-local-agent-contract.md @@ -0,0 +1,96 @@ +# Phase 7 — Local Agent Contract (Hire Agents, local-first) + +> Project artifacts are English-first. Communication language is asked at install; if the operator chooses Russian it becomes an inviolable rule. This spec is an artifact → English. + +Athena today checks the **install** (structure, secrets, parity render). Phase 7 adds a layer that checks the **behavior** of the agent workflow: roles, transitions, reports, eval records. A job is not done when there is only a text answer — a job is done when there is an accounting of inputs, artifacts, a check, the executor role, a short report, durable knowledge, and next actions. + +The layer is engine-agnostic: one contract for Claude Code and Codex. Dashboard / VPS come later, as a thin shell over verified local workflows. + +## Sources (provenance, reconciled) + +- Skeleton: `docs/MNEMAZINE-AGENTOS-TRANSFER.ru.md` (23 Jun, local-first, two-engine rescue). +- Canon detail (grafted below): `~/Мозг/03 Проекты/AthenaOS/Atoms/2026-05-27 — {Agent Registry, Agent Router, Athena Steward, Eval feedback loop, Capability Registry, Job envelope, Job lifecycle, Inbox Outbox contract, Project contract, Security & governance, Codex/Claude start matrix}.md`. +- Runtime-proven passport + handoff format: `~/Мозг/99 Система/{Паспорта_агентов_Мнемозины, Agent_Handoff_Graph}.md`. + +> Reconciliation (step B) found the transfer doc compressed the master document to the loss of 6 load-bearing contracts. They are grafted below. The VPS↔local-first conflict is resolved in favor of local-first (paths `/srv`→`$HOME`; the substance is engine-neutral). + +## Roles (7 passports) + +A name is part of the interface; an agent without a name is a faceless task-runner. Passport format: `Does · Tools · Model · Contract(invariant) · Won't · Parity`. Model by the quality-per-token rule. Files: `chezmoi/dot_agents/role-passports/.md` (English). + +| Agent | Does | Model | Contract invariant | Won't | +|---|---|---|---|---| +| **athena-router** | picks project/workflow/risk/executor+reviewer; **stage-preflight at every stage** | Sonnet | route card with `confidence`+`why[]`; no data → `confidence:low, status:hypothesis` | execute; external action without approval | +| **athena-guard** | census of inputs (sha256+sensitivity), secret scan, approvals, risk, completeness | Haiku | every input accounted or explicit reason; secret-path blocked | edit content; judge quality | +| **athena-runner** | provider adapter: runs `run_job` on Claude/Codex; tier Haiku→Opus inside provider | Haiku→Opus | works in workspace/worktree; output to outbox, not vault | push/publish/delete/spend without approve | +| **athena-reconciler** | coverage ledger: each expected artifact received OR a logged reason | Sonnet | "COVERAGE COMPLETE ✓" only at `unaccounted==0` + balanced ledger | judge quality (reviewer's gate) | +| **athena-reviewer** | eval-spec check + release-gate verdict (pass/needs-revision/reject) | Sonnet→Opus | medium/high risk never delivers without its verdict | count coverage (reconciler's gate) | +| **athena-librarian** | outbox, durable vault note (Karpathy method), graph links, indexes | Haiku→Sonnet | vault gets only synthesis; raw/OCR/logs stay in cache | enrich content; change routing | +| **athena-steward** | weekly improvement loop over eval records + failures; cheap governance | Sonnet | budget (`max_proposals/week`); only passed → approval report | watch everything; auto-apply | + +> `reconciler` and `reviewer` are **separate gates** (canon invariant): accounting inputs ≠ judging quality. Never merge. triage — deferred (YAGNI). Coordinator / learning-tail — not a role, a gate edge (below). + +## Directed handoff graph (machine-readable) + +`~/.agents/handoff-graph.yaml` — `agents[]` (role/input/output/tools), `handoffs[{from,to,when,payload}]`, `forbidden[{from,to,why}]`, `gates[{after,checks}]`. Chain: + +```text +intake -> guard -> router -> runner -> reviewer -> librarian -> visual report + \-> rescue runner -> reviewer +guard -> reconciler (coverage) ----------------/ (before deliver) +``` + +Forbidden (canon ⊕ transfer): `runner->deliver` without reviewer for medium/high; `router->external` without approval; `runner->vault` directly without librarian; `rescue->rescue` without a limit (1 attempt); any `agent->secret/auth/session/cache path`; `librarian->enrich` (a storage role does not enrich). + +Gates: `handoff-integrity` (all agents exist, every edge has a `when`, forbidden documented) + **`final-learning-tail`** (tail = `brief_md, agent_trace, self_reflection, most_important` — mandatory, formalized as an edge + gate, not optional). + +## Parity Claude ↔ Codex + +Parity = **enforcement (smoke), not a job title.** Lesson: memory ≠ obedience; checks only through a gate. + +- **`run_job`** (engine-agnostic, provenance fields grafted from Job envelope): `{job_id, project_id, provider:claude|codex, workspace, prompt, inputs[{content_hash,sensitivity}], constraints[], expected_artifacts[], route{primary,reviewer,confidence}, eval_spec{}, execution{target:local-first, vps_allowed:false}}`. Provider changes — artifacts and eval stay the same. +- **Per-class start matrix** (router core, grafted): 10 classes (code-edit/debug/arch/docs/legal/obsidian/deploy/ui/security/steward) → primary+reviewer+why. Code/debug/deploy/UI → Codex primary, Claude reviewer; arch/docs/legal/obsidian/security/steward → Claude primary, Codex reviewer. The matrix is a hypothesis; eval logs refine it. +- **Capability divisions** (research/design/legal/ops/release/growth/knowledge/security): per-capability `owner/test/trust/risk/usage-signal/provenance`. +- **parity-smoke**: one task through both clients → compare route card + output (`identical|divergent+why`) + drift-check of live `~/.claude` vs `~/.codex` against the registry. + +## Grafted contracts (lost in compression → restored) + +1. **Job lifecycle FSM** (`~/.agents/job-lifecycle.yaml`): `Draft→Staging→ProjectDetection→RouteProposed→Approved→Queued→Running→NeedsInput→ReviewReady→Delivered→Archived` (+`Failed→Retry`). The ledger records the current state. +2. **Eval feedback loop closed onto the router**: user-correction → router-update (wrong project → matching penalty; always one provider → project policy; bad artifact → eval label). Without closing the loop, "learn from history" is a slogan. +3. **project.yaml** (project passport, claude-starter): `data_policy{sensitivity,allow_cloud,allow_embeddings,retention_days,require_upload_manifest}`, `capabilities{allowed,blocked}`, `agents.preferred_pair{primary,reviewer}`, `steward.max_proposals_per_week`. Per-project enforcement + smoke validation. +4. **Security governance + Emergency switch**: no auto-upload; per-project memory boundary; audit log per job; retention/deletion pipeline; emergency mode (`disable_new_jobs/pause_uploads/disable_mcp/revoke_tokens/preserve_audit`). + +## Dynamic skill selection (stage-preflight loop) + +`athena-router` runs `capability-plan.mjs ""` **at every stage boundary**, not once per job: name the sub-task → finalists (cheap `route-skills.mjs` for routine, full plan at phase boundaries) → read only the selected SKILL.md → not in skills → vault `~/Мозг` via `_ROUTING.md` → a "why" line → act. Each choice → `routing-evals.jsonl` → eval loop. "One skill set for the whole job" is forbidden. + +## Layout (deployed paths, both clients) + +| Artifact | chezmoi source | Deploy | +|---|---|---| +| Role passports | `chezmoi/dot_agents/role-passports/.md` | `~/.agents/role-passports/` | +| Handoff graph | `chezmoi/dot_agents/handoff-graph.yaml` | `~/.agents/handoff-graph.yaml` | +| Job lifecycle FSM | `chezmoi/dot_agents/job-lifecycle.yaml` | `~/.agents/` | +| Postrun report | `chezmoi/dot_agents/registry/scripts/athena-postrun-report.mjs` | `~/.agents/registry/scripts/` | +| Report quality gate | `chezmoi/dot_agents/registry/scripts/athena-report-quality-gate.mjs` | `~/.agents/registry/scripts/` | +| Contract smoke | `smoke/agent-contract.sh` (repo) | CI + live smoke | +| project.yaml | `claude-starter/project.yaml` (template) | the user's end project | + +All paths on `$HOME` / chezmoi `.tmpl`; zero hardcoded `/Users` or `/srv`. + +## Implementation order (10 steps, amended) + +1. `role-passports/` — 7 passports (canon format: model/tools/contract/won't). **[done]** +2. `handoff-graph.yaml` — machine-readable (per-edge `when/payload`, forbidden ⊕ rescue/secret, `final-learning-tail` gate). +3. `smoke/agent-contract.sh` — passport schema + handoff integrity (orphan/when/forbidden/tail). +4. `skills/agent-session-review` (or workflow) — local session tail (brief/trace/reflection/most-important). +5. `scripts/athena-postrun-report.mjs` — Markdown/HTML/JSON report after a meaningful run (`results-json {group_id,outcome,helps,next_action}`). +6. `scripts/athena-report-quality-gate.mjs` — no raw OCR / local filenames / secrets. +7. `job-lifecycle.yaml` + ledger state; `project.yaml` template + validation. +8. eval loop → router (routing-evals.jsonl); start matrix into the router. +9. Extend `smoke/smoke.sh` (agent-contract + report-quality synthetic); `docs/FEATURES.ru.md` (maturity layers); this file in the roadmap. +10. Only then — dashboard as a thin UI over verified local workflows. + +## Gates / DoD + +The Phase-7 release gate fails not only on shell syntax but on: a lost passport, a broken handoff graph, a dirty report (raw/secrets), a missing action brief, an unclosed eval, divergent parity. **DoD:** `smoke/agent-contract.sh` green · 7 passports + handoff pass integrity · one run leaves `brief_md/agent_trace/self_reflection/most_important` · parity-smoke `identical` on a test task · 0 hardcoded paths.