From 9b8e296b19d208270428298bca53d57750f420d9 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=D0=97=D0=B0=D1=80=D1=83=D0=B1=D0=B8=D0=BD=20=D0=A4=D0=B8?=
=?UTF-8?q?=D0=BB=D0=B8=D0=BF=D0=BF?=
<289370046+zarubinphil@users.noreply.github.com>
Date: Tue, 23 Jun 2026 17:43:35 +0300
Subject: [PATCH 1/5] =?UTF-8?q?feat:=20=D0=A4=D0=B0=D0=B7=D0=B0=207=20Loca?=
=?UTF-8?q?l=20Agent=20Contract=20=E2=80=94=20=D1=81=D0=BF=D0=B5=D0=BA?=
=?UTF-8?q?=D0=B0=20+=207=20=D0=BF=D0=B0=D1=81=D0=BF=D0=BE=D1=80=D1=82?=
=?UTF-8?q?=D0=BE=D0=B2=20athena-*=20(English-first)?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Skeleton = docs/MNEMAZINE-AGENTOS-TRANSFER (local-first перенос идей Mnemazine).
Сверка Б против vault-канона показала: transfer-док сжал мастер-док до потери 6 контрактов.
Привиты: job-lifecycle FSM, eval-loop→router, project.yaml, security+emergency, per-class матрица.
Роли 6→7 (reviewer ≠ reconciler — раздельные ворота). Parity = run_job + matrix + smoke, не агент.
Паспорта English (English-first policy: артефакты EN, communication-язык спрашивается на установке).
- specs/07-local-agent-contract.md — спека Фазы 7 (EN)
- chezmoi/dot_agents/role-passports/*.md — 7 паспортов
- specs/00-roadmap.md — Фаза 7 запись + DoD
- docs/{MNEMAZINE-AGENTOS-TRANSFER,FEATURES.ru} — rationale + ссылка
---
.../dot_agents/role-passports/athena-guard.md | 10 +
.../role-passports/athena-librarian.md | 10 +
.../role-passports/athena-reconciler.md | 10 +
.../role-passports/athena-reviewer.md | 10 +
.../role-passports/athena-router.md | 10 +
.../role-passports/athena-runner.md | 10 +
.../role-passports/athena-steward.md | 10 +
docs/FEATURES.ru.md | 1 +
docs/MNEMAZINE-AGENTOS-TRANSFER.ru.md | 292 ++++++++++++++++++
specs/00-roadmap.md | 12 +
specs/07-local-agent-contract.md | 96 ++++++
11 files changed, 471 insertions(+)
create mode 100644 chezmoi/dot_agents/role-passports/athena-guard.md
create mode 100644 chezmoi/dot_agents/role-passports/athena-librarian.md
create mode 100644 chezmoi/dot_agents/role-passports/athena-reconciler.md
create mode 100644 chezmoi/dot_agents/role-passports/athena-reviewer.md
create mode 100644 chezmoi/dot_agents/role-passports/athena-router.md
create mode 100644 chezmoi/dot_agents/role-passports/athena-runner.md
create mode 100644 chezmoi/dot_agents/role-passports/athena-steward.md
create mode 100644 docs/MNEMAZINE-AGENTOS-TRANSFER.ru.md
create mode 100644 specs/07-local-agent-contract.md
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)
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.
--
2.54.0
From e432e46f5e799e2cf55375c73eeb8da6dbc9a301 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=D0=97=D0=B0=D1=80=D1=83=D0=B1=D0=B8=D0=BD=20=D0=A4=D0=B8?=
=?UTF-8?q?=D0=BB=D0=B8=D0=BF=D0=BF?=
<289370046+zarubinphil@users.noreply.github.com>
Date: Tue, 23 Jun 2026 17:49:18 +0300
Subject: [PATCH 2/5] =?UTF-8?q?feat:=20onboarding=20=D1=81=D0=BF=D1=80?=
=?UTF-8?q?=D0=B0=D1=88=D0=B8=D0=B2=D0=B0=D0=B5=D1=82=20=D1=8F=D0=B7=D1=8B?=
=?UTF-8?q?=D0=BA=20=D0=BE=D0=B1=D1=89=D0=B5=D0=BD=D0=B8=D1=8F=20=D0=BF?=
=?UTF-8?q?=D0=B5=D1=80=D0=B2=D1=8B=D0=BC=20=D0=B2=D0=BE=D0=BF=D1=80=D0=BE?=
=?UTF-8?q?=D1=81=D0=BE=D0=BC=20+=20=D0=BD=D0=B5=D0=B7=D1=8B=D0=B1=D0=BB?=
=?UTF-8?q?=D0=B5=D0=BC=D0=BE=D0=B5=20=D0=BF=D1=80=D0=B0=D0=B2=D0=B8=D0=BB?=
=?UTF-8?q?=D0=BE?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Шаг 0.1 setup-os: язык общения — до установки и грилла (был поздно, в P1).
Выбор → references/owner.md + CLAUDE.md (Правила НИКОГДА: «язык не менять без явной просьбы»).
Артефакты системы остаются English-first; выбор задаёт язык ОБЩЕНИЯ, не код/контракты.
Зеркало root⊆chezmoi идентично (E10-гард), smoke зелёный.
---
chezmoi/dot_claude/skills/setup-os/SKILL.md | 12 ++++++++++--
.../skills/setup-os/assets/CLAUDE.template.md | 2 +-
.../skills/setup-os/assets/owner.template.md | 2 +-
skills/setup-os/SKILL.md | 12 ++++++++++--
skills/setup-os/assets/CLAUDE.template.md | 2 +-
skills/setup-os/assets/owner.template.md | 2 +-
6 files changed, 24 insertions(+), 8 deletions(-)
diff --git a/chezmoi/dot_claude/skills/setup-os/SKILL.md b/chezmoi/dot_claude/skills/setup-os/SKILL.md
index c19dc44..e87aeb9 100644
--- a/chezmoi/dot_claude/skills/setup-os/SKILL.md
+++ b/chezmoi/dot_claude/skills/setup-os/SKILL.md
@@ -27,7 +27,15 @@ E Автоматизация→ ingest-hook, weekly health-check cron, parity Cl
---
-## Этап 0 — Разведка (молча, до вопросов)
+## Этап 0 — Язык + разведка
+
+**Шаг 0.1 — Язык общения (САМЫЙ ПЕРВЫЙ вопрос, до установки и любого этапа).**
+AskUserQuestion: «На каком языке вести установку и общаться дальше? / Which language should I use?» → [Русский] [English] [Español] [Other]. С этого момента ВЕСЬ онбординг (попапы, грилл, объяснения) — на выбранном языке.
+- Стамп `~/.claude/.athena-lang` (код языка, 1 строка) — резюм знает язык.
+- Выбор = **незыблемое правило**: пишется в `references/owner.md` (Язык) и `CLAUDE.md` (Правила НИКОГДА: «язык общения не менять без явной просьбы»).
+- **Артефакты системы остаются English-first** (паспорта/контракты/код). Выбор задаёт ЯЗЫК ОБЩЕНИЯ, не язык артефактов.
+
+**Шаг 0.2 — Разведка (молча, до вопросов).**
```bash
ls -la ~/.claude/ 2>/dev/null; ls ~/.claude/CLAUDE.md 2>/dev/null
ls "$HOME"/* knlow* "$HOME/Мозг" 2>/dev/null # vault?
@@ -89,7 +97,7 @@ AskUserQuestion: «Разрешаешь прогнать установочны
| Фаза | Собирает | Пишет (target) | Tier |
|---|---|---|---|
-| **P1 Идентичность** | роль/занятость, язык, локация+ограничения, домены экспертизы | `references/owner.md` | hot |
+| **P1 Идентичность** | роль/занятость, язык (уже зафиксирован на шаге 0.1 — подтвердить), локация+ограничения, домены экспертизы | `references/owner.md` | hot |
| **P2 Проекты+стек** | проекты (имя/статус/критичность), стек, что клонировать/ставить | `owner.md`, `projects.manifest`, `tools.manifest` | hot |
| **P3 Стиль+правила** | model-стенс, коммуникация/caveman, структура ответа, НИКОГДА/ВСЕГДА, gate пакетов | `CLAUDE.md` (слоты `{{ }}`) | hot |
| **P4 Операц-преференсы** | security-постура, design/UX-вкус+анти-паттерны, deploy, swarm, web-каскад | `references/{security,design,deploy,agents,scrapegraph}.md` | cold |
diff --git a/chezmoi/dot_claude/skills/setup-os/assets/CLAUDE.template.md b/chezmoi/dot_claude/skills/setup-os/assets/CLAUDE.template.md
index 811183a..e79a1dd 100644
--- a/chezmoi/dot_claude/skills/setup-os/assets/CLAUDE.template.md
+++ b/chezmoi/dot_claude/skills/setup-os/assets/CLAUDE.template.md
@@ -61,7 +61,7 @@
- Auto-memory — вспомогательная; canonical факты здесь.
## Правила НИКОГДА
-Не нарушать закон · не врать · не лебезить · не бросать задачу · не повторять ошибки · не работать без плана · не менять без бэкапа · **секреты не в коде/git** — только `.env`/secret manager · {{доп-НИКОГДА из грилла — напр. не ставить пакеты без явного добра}}.
+Не нарушать закон · не врать · не лебезить · не бросать задачу · не повторять ошибки · не работать без плана · не менять без бэкапа · **секреты не в коде/git** — только `.env`/secret manager · **язык общения = {{ЯЗЫК}}, не переключать без явной просьбы (незыблемо)** · {{доп-НИКОГДА из грилла — напр. не ставить пакеты без явного добра}}.
## Правила ВСЕГДА
1. Сначала план → действие.
diff --git a/chezmoi/dot_claude/skills/setup-os/assets/owner.template.md b/chezmoi/dot_claude/skills/setup-os/assets/owner.template.md
index c4d5601..4545e4e 100644
--- a/chezmoi/dot_claude/skills/setup-os/assets/owner.template.md
+++ b/chezmoi/dot_claude/skills/setup-os/assets/owner.template.md
@@ -4,7 +4,7 @@
## Кто
- **Имя:** {{ИМЯ}}
-- **Локация:** {{ГОРОД}} · **Язык:** {{ЯЗЫК}}
+- **Локация:** {{ГОРОД}} · **Язык:** {{ЯЗЫК}} (незыблемое правило общения — не переключать без явной просьбы)
- **Семья:** {{СЕМЬЯ}}
- **Тип занятости:** {{ТИП — соло / фирма / фаундер; сколько потоков дохода}}
- **Роли:** {{РОЛИ}}
diff --git a/skills/setup-os/SKILL.md b/skills/setup-os/SKILL.md
index c19dc44..e87aeb9 100644
--- a/skills/setup-os/SKILL.md
+++ b/skills/setup-os/SKILL.md
@@ -27,7 +27,15 @@ E Автоматизация→ ingest-hook, weekly health-check cron, parity Cl
---
-## Этап 0 — Разведка (молча, до вопросов)
+## Этап 0 — Язык + разведка
+
+**Шаг 0.1 — Язык общения (САМЫЙ ПЕРВЫЙ вопрос, до установки и любого этапа).**
+AskUserQuestion: «На каком языке вести установку и общаться дальше? / Which language should I use?» → [Русский] [English] [Español] [Other]. С этого момента ВЕСЬ онбординг (попапы, грилл, объяснения) — на выбранном языке.
+- Стамп `~/.claude/.athena-lang` (код языка, 1 строка) — резюм знает язык.
+- Выбор = **незыблемое правило**: пишется в `references/owner.md` (Язык) и `CLAUDE.md` (Правила НИКОГДА: «язык общения не менять без явной просьбы»).
+- **Артефакты системы остаются English-first** (паспорта/контракты/код). Выбор задаёт ЯЗЫК ОБЩЕНИЯ, не язык артефактов.
+
+**Шаг 0.2 — Разведка (молча, до вопросов).**
```bash
ls -la ~/.claude/ 2>/dev/null; ls ~/.claude/CLAUDE.md 2>/dev/null
ls "$HOME"/* knlow* "$HOME/Мозг" 2>/dev/null # vault?
@@ -89,7 +97,7 @@ AskUserQuestion: «Разрешаешь прогнать установочны
| Фаза | Собирает | Пишет (target) | Tier |
|---|---|---|---|
-| **P1 Идентичность** | роль/занятость, язык, локация+ограничения, домены экспертизы | `references/owner.md` | hot |
+| **P1 Идентичность** | роль/занятость, язык (уже зафиксирован на шаге 0.1 — подтвердить), локация+ограничения, домены экспертизы | `references/owner.md` | hot |
| **P2 Проекты+стек** | проекты (имя/статус/критичность), стек, что клонировать/ставить | `owner.md`, `projects.manifest`, `tools.manifest` | hot |
| **P3 Стиль+правила** | model-стенс, коммуникация/caveman, структура ответа, НИКОГДА/ВСЕГДА, gate пакетов | `CLAUDE.md` (слоты `{{ }}`) | hot |
| **P4 Операц-преференсы** | security-постура, design/UX-вкус+анти-паттерны, deploy, swarm, web-каскад | `references/{security,design,deploy,agents,scrapegraph}.md` | cold |
diff --git a/skills/setup-os/assets/CLAUDE.template.md b/skills/setup-os/assets/CLAUDE.template.md
index 811183a..e79a1dd 100644
--- a/skills/setup-os/assets/CLAUDE.template.md
+++ b/skills/setup-os/assets/CLAUDE.template.md
@@ -61,7 +61,7 @@
- Auto-memory — вспомогательная; canonical факты здесь.
## Правила НИКОГДА
-Не нарушать закон · не врать · не лебезить · не бросать задачу · не повторять ошибки · не работать без плана · не менять без бэкапа · **секреты не в коде/git** — только `.env`/secret manager · {{доп-НИКОГДА из грилла — напр. не ставить пакеты без явного добра}}.
+Не нарушать закон · не врать · не лебезить · не бросать задачу · не повторять ошибки · не работать без плана · не менять без бэкапа · **секреты не в коде/git** — только `.env`/secret manager · **язык общения = {{ЯЗЫК}}, не переключать без явной просьбы (незыблемо)** · {{доп-НИКОГДА из грилла — напр. не ставить пакеты без явного добра}}.
## Правила ВСЕГДА
1. Сначала план → действие.
diff --git a/skills/setup-os/assets/owner.template.md b/skills/setup-os/assets/owner.template.md
index c4d5601..4545e4e 100644
--- a/skills/setup-os/assets/owner.template.md
+++ b/skills/setup-os/assets/owner.template.md
@@ -4,7 +4,7 @@
## Кто
- **Имя:** {{ИМЯ}}
-- **Локация:** {{ГОРОД}} · **Язык:** {{ЯЗЫК}}
+- **Локация:** {{ГОРОД}} · **Язык:** {{ЯЗЫК}} (незыблемое правило общения — не переключать без явной просьбы)
- **Семья:** {{СЕМЬЯ}}
- **Тип занятости:** {{ТИП — соло / фирма / фаундер; сколько потоков дохода}}
- **Роли:** {{РОЛИ}}
--
2.54.0
From 3094b0a6ae1fded742a419c2cd1841854a8b22e0 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=D0=97=D0=B0=D1=80=D1=83=D0=B1=D0=B8=D0=BD=20=D0=A4=D0=B8?=
=?UTF-8?q?=D0=BB=D0=B8=D0=BF=D0=BF?=
<289370046+zarubinphil@users.noreply.github.com>
Date: Tue, 23 Jun 2026 17:55:32 +0300
Subject: [PATCH 3/5] =?UTF-8?q?feat:=20=D0=A4=D0=B0=D0=B7=D0=B0=207=20?=
=?UTF-8?q?=D1=88=D0=B0=D0=B3=D0=B8=202-3=20=E2=80=94=20handoff-=D0=B3?=
=?UTF-8?q?=D1=80=D0=B0=D1=84=20+=20agent-contract=20smoke?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
handoff-graph.yaml: directed DAG (7 agents/handoffs/forbidden/gates), engine-agnostic,
per-edge when, per-forbidden why, final-learning-tail (brief/trace/reflection/most_important).
agent-contract.sh: zero-dep валидатор (passports + граф integrity), врезан в smoke.sh.
Негатив-тесты подтверждены: ловит missing when/why/tail/passport. shellcheck 0 (error-level).
role-passports/_index.md — навигация по 7 душам.
---
chezmoi/dot_agents/handoff-graph.yaml | 83 +++++++++++++++++++++
chezmoi/dot_agents/role-passports/_index.md | 15 ++++
smoke/agent-contract.sh | 63 ++++++++++++++++
smoke/smoke.sh | 5 ++
specs/00-roadmap.md | 6 +-
specs/07-local-agent-contract.md | 4 +-
6 files changed, 171 insertions(+), 5 deletions(-)
create mode 100644 chezmoi/dot_agents/handoff-graph.yaml
create mode 100644 chezmoi/dot_agents/role-passports/_index.md
create mode 100755 smoke/agent-contract.sh
diff --git a/chezmoi/dot_agents/handoff-graph.yaml b/chezmoi/dot_agents/handoff-graph.yaml
new file mode 100644
index 0000000..b5f3a3e
--- /dev/null
+++ b/chezmoi/dot_agents/handoff-graph.yaml
@@ -0,0 +1,83 @@
+# AthenaOS — directed handoff graph (Phase 7, Local Agent Contract)
+# Engine-agnostic: Claude Code and Codex follow the same graph; only the runner adapter differs.
+# A pipeline without an allowed-transition graph is a draft, not production.
+# Validated by smoke/agent-contract.sh (passport + integrity gates).
+
+version: 1
+
+# Entry boundary (the input door, not an agent).
+entry: intake
+
+# Runtime agents. Each id must have a passport in role-passports/.md.
+agents:
+ - id: athena-router
+ role: route officer
+ input: job envelope
+ output: route card
+ tools: [capability-plan, route-skills, project-yaml]
+ - id: athena-guard
+ role: intake census
+ input: raw inputs
+ output: census + risk score
+ tools: [shasum, find, secret-scan]
+ - id: athena-runner
+ role: provider adapter
+ input: run_job
+ output: outbox artifacts
+ tools: [claude-adapter, codex-adapter, git-worktree]
+ - id: athena-reconciler
+ role: coverage ledger
+ input: expected vs produced
+ output: coverage marker
+ tools: [ledger, grep]
+ - id: athena-reviewer
+ role: eval / release gate
+ input: artifacts + eval_spec
+ output: verdict
+ tools: [eval_spec, report-quality-gate, agent-architecture-audit]
+ - id: athena-librarian
+ role: knowledge curator
+ input: approved artifacts
+ output: vault note + indexes
+ tools: [knowledge-ops, graphify, kb-embed]
+ - id: athena-steward
+ role: weekly governance
+ input: eval records
+ output: improvement candidates
+ tools: [registry, drift-check]
+
+# Allowed transitions. Every edge MUST carry a `when`.
+handoffs:
+ - { from: intake, to: athena-guard, when: always, payload: raw inputs }
+ - { from: athena-guard, to: athena-router, when: census passed, payload: census + risk }
+ - { from: athena-guard, to: athena-reconciler, when: census passed, payload: expected-artifact set }
+ - { from: athena-router, to: athena-runner, when: route approved, payload: run_job envelope }
+ - { from: athena-runner, to: athena-reviewer, when: artifacts produced, payload: outbox artifacts }
+ - { from: athena-runner, to: rescue-runner, when: runner stuck, payload: handoff pack (no secrets) }
+ - { from: rescue-runner, to: athena-reviewer, when: rescue produced, payload: outbox artifacts }
+ - { from: athena-reconciler, to: athena-reviewer, when: coverage complete, payload: coverage marker }
+ - { from: athena-reviewer, to: athena-librarian, when: verdict pass, payload: approved artifacts }
+ - { from: athena-librarian, to: report, when: vault written, payload: visual report + tail }
+ - { from: athena-steward, to: report, when: weekly, payload: improvement candidates }
+
+# Disallowed transitions. Every entry MUST carry a `why`.
+forbidden:
+ - { from: athena-runner, to: deliver, why: medium/high risk needs reviewer verdict first }
+ - { from: athena-router, to: external, why: no external action without human approval }
+ - { from: athena-runner, to: vault, why: vault writes go through the librarian, not the runner }
+ - { from: rescue-runner, to: rescue-runner, why: one rescue attempt only, no loop before human review }
+ - { from: athena-librarian, to: enrich, why: a storage role does not enrich or transform content }
+ - { from: any, to: secret-path, why: no agent touches secret/auth/session/cache paths }
+
+# Gates run by smoke/agent-contract.sh.
+gates:
+ - after: graph
+ name: handoff-integrity
+ checks:
+ - every agent has a passport
+ - every handoff has a when
+ - every forbidden has a why
+ - no orphan agent (each appears in handoffs)
+ - after: librarian
+ name: final-learning-tail
+ checks: [brief_md, agent_trace, self_reflection, most_important]
diff --git a/chezmoi/dot_agents/role-passports/_index.md b/chezmoi/dot_agents/role-passports/_index.md
new file mode 100644
index 0000000..fc60f8e
--- /dev/null
+++ b/chezmoi/dot_agents/role-passports/_index.md
@@ -0,0 +1,15 @@
+# Role Passports — index
+
+Engine-agnostic agent contracts read by **both Claude Code and Codex**. One file per agent; format `Soul · Does · Tools · Model · Contract · Won't · Parity`. The directed handoff graph (`../handoff-graph.yaml`) wires them; `smoke/agent-contract.sh` enforces passport + graph integrity.
+
+| Agent | Role | Model | Gate it owns |
+|---|---|---|---|
+| [athena-router](athena-router.md) | route officer | Sonnet | route card + stage-preflight |
+| [athena-guard](athena-guard.md) | intake census | Haiku | inputs accounted, secret-path blocked |
+| [athena-runner](athena-runner.md) | provider adapter | Haiku→Opus | sandboxed run, outbox-only |
+| [athena-reconciler](athena-reconciler.md) | coverage ledger | Sonnet | `unaccounted == 0` |
+| [athena-reviewer](athena-reviewer.md) | eval / release gate | Sonnet→Opus | verdict before deliver |
+| [athena-librarian](athena-librarian.md) | knowledge curator | Haiku→Sonnet | synthesis-only vault |
+| [athena-steward](athena-steward.md) | weekly governance | Sonnet | budgeted proposals |
+
+`reconciler` and `reviewer` are **separate gates** — accounting inputs ≠ judging quality. Never merge.
diff --git a/smoke/agent-contract.sh b/smoke/agent-contract.sh
new file mode 100755
index 0000000..409fe22
--- /dev/null
+++ b/smoke/agent-contract.sh
@@ -0,0 +1,63 @@
+#!/usr/bin/env bash
+# Phase 7 — Local Agent Contract smoke.
+# Validates role passports + the directed handoff graph. Zero deps (grep/awk).
+# A pipeline without a valid passport+graph contract is a draft, not production.
+# Usage: smoke/agent-contract.sh [REPO_ROOT] (default: repo root from script path)
+
+ROOT="${1:-$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)}"
+PASS_DIR="$ROOT/chezmoi/dot_agents/role-passports"
+GRAPH="$ROOT/chezmoi/dot_agents/handoff-graph.yaml"
+
+AGENTS="athena-router athena-guard athena-runner athena-reconciler athena-reviewer athena-librarian athena-steward"
+fail=0
+bad() { echo " ✗ $1" >&2; fail=1; }
+
+echo "[agent-contract] passports + handoff graph"
+
+# 1. Passports exist and carry the canon fields.
+for a in $AGENTS; do
+ f="$PASS_DIR/$a.md"
+ if [ ! -f "$f" ]; then bad "passport missing: $a"; continue; fi
+ for field in 'Soul' 'Does:' 'Tools:' 'Model:' 'Contract:' "Won't:" 'Parity:'; do
+ grep -q "$field" "$f" || bad "$a: missing field '$field'"
+ done
+done
+
+# 2. Graph exists with the required top-level keys.
+if [ ! -f "$GRAPH" ]; then
+ bad "handoff-graph.yaml missing"
+else
+ for key in entry agents handoffs forbidden gates; do
+ grep -q "^$key:" "$GRAPH" || bad "graph missing key: $key"
+ done
+
+ # 3. Each agent is declared and appears in handoffs (no orphan).
+ handoff_block=$(awk '/^handoffs:/{f=1;next} /^[a-z]/{f=0} f' "$GRAPH")
+ for a in $AGENTS; do
+ grep -q "id: $a" "$GRAPH" || bad "agent not declared: $a"
+ printf '%s\n' "$handoff_block" | grep -q "$a" || bad "orphan agent (absent from handoffs): $a"
+ done
+
+ # 4. Every handoff edge carries a `when` (each edge is one inline line).
+ n_edge=$(printf '%s\n' "$handoff_block" | grep -c 'from:')
+ n_when=$(printf '%s\n' "$handoff_block" | grep -c 'when:')
+ [ "$n_edge" = "$n_when" ] || bad "handoffs: $n_edge edges but $n_when 'when:' (every edge needs a when)"
+
+ # 5. Every forbidden entry carries a `why`.
+ forbid_block=$(awk '/^forbidden:/{f=1;next} /^[a-z]/{f=0} f' "$GRAPH")
+ n_forbid=$(printf '%s\n' "$forbid_block" | grep -c 'from:')
+ n_why=$(printf '%s\n' "$forbid_block" | grep -c 'why:')
+ [ "$n_forbid" = "$n_why" ] || bad "forbidden: $n_forbid entries but $n_why 'why:'"
+
+ # 6. The final-learning-tail gate names all four mandatory tail outputs.
+ for t in brief_md agent_trace self_reflection most_important; do
+ grep -q "$t" "$GRAPH" || bad "final-learning-tail missing output: $t"
+ done
+fi
+
+if [ "$fail" -ne 0 ]; then
+ echo "AGENT-CONTRACT FAIL" >&2
+ exit 1
+fi
+echo " ✓ 7 passports · graph integrity · learning-tail"
+echo "agent-contract OK"
diff --git a/smoke/smoke.sh b/smoke/smoke.sh
index 372e008..39c4e63 100755
--- a/smoke/smoke.sh
+++ b/smoke/smoke.sh
@@ -181,5 +181,10 @@ if [ -x "$HERE/smoke/git-leak-guard.test.sh" ]; then
chk "git-leak-guard 5 кейсов" "'$HERE/smoke/git-leak-guard.test.sh' >/dev/null 2>&1"
else echo " · git-leak-guard.test.sh нет (skip)"; fi
+echo "[agent-contract] Фаза 7: паспорта + handoff-граф integrity"
+if [ -x "$HERE/smoke/agent-contract.sh" ]; then
+ chk "agent-contract (7 паспортов + граф)" "'$HERE/smoke/agent-contract.sh' '$HERE' >/dev/null 2>&1"
+else echo " · agent-contract.sh нет (skip)"; fi
+
[ "$fail" = 0 ] && echo "SMOKE OK" || echo "SMOKE FAIL"
exit "$fail"
diff --git a/specs/00-roadmap.md b/specs/00-roadmap.md
index d0adac7..47a1714 100644
--- a/specs/00-roadmap.md
+++ b/specs/00-roadmap.md
@@ -89,9 +89,9 @@ Generic chezmoi-source собран (чистая пересборка, НЕ д
Самопроверяемый агентный слой: роли · 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).
+- [x] Шаг 1 — `chezmoi/dot_agents/role-passports/` (7 паспортов English + `_index.md`, канон-формат).
+- [x] Шаг 2 — `chezmoi/dot_agents/handoff-graph.yaml` (машиночитаемый: agents/handoffs/forbidden/gates + learning-tail).
+- [x] Шаг 3 — `smoke/agent-contract.sh` (passports + handoff integrity; негатив-тесты ловят when/why/tail/passport; врезан в smoke.sh).
- [ ] Шаги 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) — позже.
diff --git a/specs/07-local-agent-contract.md b/specs/07-local-agent-contract.md
index 8b51b2c..5bbf419 100644
--- a/specs/07-local-agent-contract.md
+++ b/specs/07-local-agent-contract.md
@@ -81,8 +81,8 @@ 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).
+2. `handoff-graph.yaml` — machine-readable (per-edge `when/payload`, forbidden ⊕ rescue/secret, `final-learning-tail` gate). **[done]**
+3. `smoke/agent-contract.sh` — passport schema + handoff integrity (orphan/when/forbidden/tail). **[done]**
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.
--
2.54.0
From cc947028c553ea292164869cf07360ccfdc4bd74 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=D0=97=D0=B0=D1=80=D1=83=D0=B1=D0=B8=D0=BD=20=D0=A4=D0=B8?=
=?UTF-8?q?=D0=BB=D0=B8=D0=BF=D0=BF?=
<289370046+zarubinphil@users.noreply.github.com>
Date: Tue, 23 Jun 2026 18:33:42 +0300
Subject: [PATCH 4/5] =?UTF-8?q?feat:=20=D0=A4=D0=B0=D0=B7=D0=B0=207=20?=
=?UTF-8?q?=D1=88=D0=B0=D0=B3=D0=B8=204-6=20=E2=80=94=20session-review=20s?=
=?UTF-8?q?kill=20+=20postrun-report=20+=20quality-gate?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Step 4: skills/agent-session-review/SKILL.md (dual-write root+chezmoi)
- 4 mandatory blocks: brief_md / agent_trace / self_reflection / most_important
- Karpathy method: synthesize on write, mandatory before deliver gate
Step 5: chezmoi/dot_agents/registry/scripts/athena-postrun-report.mjs
- Adapted from mnemazine-postrun-knowledge-report.mjs (520→~120 lines)
- Input: --results-json [{group_id, outcome, helps, next_action}]
- Output: --format md (default) | html | json
- Env: ATHENA_REPORTS, ATHENA_RUN_ID; zero hardcoded paths
Step 6: chezmoi/dot_agents/registry/scripts/athena-report-quality-gate.mjs
- Adapted from mnemazine-report-quality-gate.mjs (99→~110 lines)
- 5 rules: no-raw-ocr / no-local-paths / no-secrets / has-outcome / has-next-action
- Accepts .html and .md reports; exit 0=pass, 1=fail
Smoke: agent-contract.sh +4 checks (SKILL.md blocks, postrun synthetic,
gate positive PASS, gate negative FAIL). smoke green, shellcheck -S error 0.
Co-Authored-By: Claude Sonnet 4.6
---
.../scripts/athena-postrun-report.mjs | 164 ++++++++++++++++++
.../scripts/athena-report-quality-gate.mjs | 123 +++++++++++++
.../skills/agent-session-review/SKILL.md | 101 +++++++++++
skills/agent-session-review/SKILL.md | 101 +++++++++++
smoke/agent-contract.sh | 48 ++++-
5 files changed, 536 insertions(+), 1 deletion(-)
create mode 100644 chezmoi/dot_agents/registry/scripts/athena-postrun-report.mjs
create mode 100644 chezmoi/dot_agents/registry/scripts/athena-report-quality-gate.mjs
create mode 100644 chezmoi/dot_claude/skills/agent-session-review/SKILL.md
create mode 100644 skills/agent-session-review/SKILL.md
diff --git a/chezmoi/dot_agents/registry/scripts/athena-postrun-report.mjs b/chezmoi/dot_agents/registry/scripts/athena-postrun-report.mjs
new file mode 100644
index 0000000..e8b87db
--- /dev/null
+++ b/chezmoi/dot_agents/registry/scripts/athena-postrun-report.mjs
@@ -0,0 +1,164 @@
+#!/usr/bin/env node
+// Athena post-run report. Adapted from mnemazine-postrun-knowledge-report.mjs.
+// Input: --results-json — JSON array [{group_id, outcome, helps, next_action}]
+// Output: MD (default), HTML (--format html), or JSON (--format json)
+// Env: ATHENA_REPORTS (default $HOME/.agents/reports), ATHENA_RUN_ID
+import { promises as fs } from 'node:fs'
+import path from 'node:path'
+
+const argv = process.argv.slice(2)
+
+function arg(name, fallback = '') {
+ const hit = argv.find(a => a === `--${name}` || a.startsWith(`--${name}=`))
+ if (!hit) return fallback
+ return hit.includes('=') ? hit.split('=').slice(1).join('=') : argv[argv.indexOf(hit) + 1] || fallback
+}
+
+function flag(name) { return argv.includes(`--${name}`) }
+
+const HOME = process.env.HOME || ''
+const REPORTS = path.resolve(
+ arg('reports', process.env.ATHENA_REPORTS || path.join(HOME, '.agents', 'reports'))
+)
+const RUN_ID = arg('run-id', process.env.ATHENA_RUN_ID || new Date().toISOString().slice(0, 10))
+const TITLE = arg('title', 'Athena post-run report')
+const FORMAT = arg('format', 'md')
+const RESULTS_JSON = arg('results-json', '')
+
+function esc(s) {
+ return String(s ?? '').replace(/[&<>"']/g, c =>
+ ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]))
+}
+
+function mdEsc(s) {
+ return String(s ?? '').replace(/\|/g, '\\|').replace(/\n+/g, ' ').trim()
+}
+
+function trunc(s, max = 120) {
+ const t = String(s ?? '').replace(/\s+/g, ' ').trim()
+ return t.length > max ? `${t.slice(0, max - 1)}…` : t
+}
+
+async function loadResults() {
+ if (!RESULTS_JSON) return []
+ const raw = JSON.parse(await fs.readFile(RESULTS_JSON, 'utf8'))
+ const rows = Array.isArray(raw) ? raw
+ : Array.isArray(raw.processResults) ? raw.processResults
+ : []
+ const byGroup = new Map()
+ for (const row of rows) byGroup.set(row.group_id ?? String(Math.random()), row)
+ return [...byGroup.values()]
+}
+
+function outcomesSummary(results) {
+ const counts = {}
+ for (const r of results) counts[r.outcome ?? 'unknown'] = (counts[r.outcome ?? 'unknown'] || 0) + 1
+ return Object.entries(counts).map(([k, v]) => `${k}:${v}`).join(', ')
+}
+
+function markdown(results) {
+ const rows = results.map((r, i) =>
+ `| ${i + 1} | ${mdEsc(r.group_id)} | ${mdEsc(r.outcome)} | ${mdEsc(trunc(r.helps, 80))} | ${mdEsc(trunc(r.next_action, 80))} |`
+ ).join('\n')
+
+ return `# ${TITLE}
+
+Run: \`${RUN_ID}\`
+
+## Summary
+
+- Groups: **${results.length}**
+- Outcomes: ${outcomesSummary(results)}
+
+## Results
+
+| # | group_id | outcome | helps | next_action |
+|---:|---|---|---|---|
+${rows || '| — | no results | — | — | — |'}
+
+---
+*Generated by athena-postrun-report.mjs*
+`
+}
+
+function html(results) {
+ const cards = results.map(r => `
+ ${esc(r.group_id)}
+ ${esc(r.outcome ?? '')}
+ ${r.helps ? `Helps: ${esc(trunc(r.helps, 200))}
` : ''}
+ ${r.next_action ? `Next: ${esc(trunc(r.next_action, 200))}
` : ''}
+ `).join('\n')
+
+ const css = `:root{--bg:#f6f7fb;--card:#fff;--line:#e6eaf0;--ink:#111827;--muted:#667085;--blue:#0a66ff}
+*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--ink);font-family:-apple-system,sans-serif}
+.hero{padding:32px max(16px,4vw) 20px;background:#fff;border-bottom:1px solid var(--line)}
+.eyebrow{font-size:12px;font-weight:760;color:var(--blue);text-transform:uppercase;letter-spacing:.08em}
+h1{font-size:clamp(28px,4vw,48px);margin:8px 0 6px}h2{margin:18px 0 10px}
+.lead{color:#344054;font-size:15px}
+.stats{display:flex;gap:8px;flex-wrap:wrap;margin-top:12px}
+.stat{background:#f9fafb;border:1px solid var(--line);border-radius:8px;padding:8px 12px}
+.stat strong{display:block;font-size:20px}.stat span{font-size:11px;color:var(--muted)}
+main{padding:18px max(16px,4vw) 48px}
+.cards{display:grid;grid-template-columns:repeat(auto-fit,minmax(280px,1fr));gap:10px;margin-top:10px}
+.card{background:var(--card);border:1px solid var(--line);border-radius:8px;padding:14px}
+.card h3{margin:0 0 8px;font-size:16px}.meta{margin-bottom:8px}
+.tag{font-size:11px;color:#344054;background:#f2f4f7;border:1px solid var(--line);border-radius:6px;padding:3px 6px}
+.helps,.next{font-size:13px;color:#475467;margin:6px 0;line-height:1.45}
+.next b,.helps b{color:var(--ink)}`
+
+ return `
+
+
+
+
+${esc(TITLE)}
+
+
+
+
+ Athena post-run report
+ ${esc(TITLE)}
+ Run: ${esc(RUN_ID)} · ${esc(outcomesSummary(results))}
+
+
${results.length}groups
+
${results.filter(r => r.outcome === 'done').length}done
+
${results.filter(r => r.next_action).length}with next action
+
+
+
+ Results
+
+${cards || '
No results.
'}
+
+
+
+`
+}
+
+function jsonOut(results) {
+ return JSON.stringify({
+ ok: true,
+ run_id: RUN_ID,
+ groups: results.length,
+ outcomes: outcomesSummary(results),
+ results,
+ }, null, 2)
+}
+
+await fs.mkdir(REPORTS, { recursive: true })
+const results = await loadResults()
+const stamp = new Date().toISOString().slice(0, 10)
+const safeRun = RUN_ID.replace(/[^a-zA-Z0-9_-]+/g, '-')
+const base = `${stamp}-${safeRun}-athena-report`
+
+if (FORMAT === 'json') {
+ if (!flag('quiet')) process.stdout.write(jsonOut(results) + '\n')
+} else if (FORMAT === 'html') {
+ const htmlPath = path.join(REPORTS, `${base}.html`)
+ await fs.writeFile(htmlPath, html(results), 'utf8')
+ if (!flag('quiet')) process.stdout.write(JSON.stringify({ ok: true, run_id: RUN_ID, groups: results.length, html: htmlPath }, null, 2) + '\n')
+} else {
+ const mdPath = path.join(REPORTS, `${base}.md`)
+ await fs.writeFile(mdPath, markdown(results), 'utf8')
+ if (!flag('quiet')) process.stdout.write(JSON.stringify({ ok: true, run_id: RUN_ID, groups: results.length, md: mdPath }, null, 2) + '\n')
+}
diff --git a/chezmoi/dot_agents/registry/scripts/athena-report-quality-gate.mjs b/chezmoi/dot_agents/registry/scripts/athena-report-quality-gate.mjs
new file mode 100644
index 0000000..d853574
--- /dev/null
+++ b/chezmoi/dot_agents/registry/scripts/athena-report-quality-gate.mjs
@@ -0,0 +1,123 @@
+#!/usr/bin/env node
+// Athena report quality gate. Adapted from mnemazine-report-quality-gate.mjs.
+// Input: --report | --reports accepts .html and .md
+// Output: JSON stdout { ok, checked, failures[] } exit 0 = pass, 1 = fail
+// Rules: no-raw-ocr | no-local-paths | no-secrets | has-outcome | has-next-action
+import { promises as fs } from 'node:fs'
+import path from 'node:path'
+
+const argv = process.argv.slice(2)
+
+function arg(name, fallback = '') {
+ const hit = argv.find(a => a === `--${name}` || a.startsWith(`--${name}=`))
+ if (!hit) return fallback
+ return hit.includes('=') ? hit.split('=').slice(1).join('=') : argv[argv.indexOf(hit) + 1] || fallback
+}
+
+const HOME = process.env.HOME || ''
+const ROOT = process.env.ATHENA_ROOT || path.resolve(process.cwd())
+const REPORT = arg('report', '')
+const REPORTS_DIR = path.resolve(
+ arg('reports', process.env.ATHENA_REPORTS || path.join(HOME, '.agents', 'reports'))
+)
+
+// Rule 1: raw OCR / media file artifacts
+const rawMarkers = [
+ /\btemp_image[_-]/i,
+ /\bIMG_\d+/,
+ /\bscreenshot\d+/i,
+ /\bpaste-[a-zA-Z0-9]{4,}/i,
+ /\b\w+\.(?:WEBP|PNG|JPE?G|HEIC|TIFF|MOV|MP4)\b/i,
+ /raw\s+ocr/i,
+ /No extractable text/i,
+ /intake-draft/i,
+]
+
+// Rule 2: hardcoded local filesystem paths
+const localPathMarkers = [
+ /\/Users\/[a-zA-Z]/,
+ /\\Users\\[a-zA-Z]/,
+ /C:\\[Uu]sers\\/,
+]
+
+// Rule 3: secrets / credentials
+const secretMarkers = [
+ /\bsk-[A-Za-z0-9]{20,}/,
+ /\bAKIA[A-Z0-9]{16}/,
+ /\bBearer\s+[A-Za-z0-9_.-]{20,}/i,
+ /password\s*=\s*\S{8,}/i,
+ /api[_-]?key\s*[=:]\s*\S{8,}/i,
+ /secret\s*[=:]\s*["']?\S{16,}/i,
+]
+
+function stripHtml(htmlContent) {
+ return htmlContent
+ .replace(/