feat: Phase 7 Local Agent Contract — passports, handoff graph, session tail, postrun report, quality gate #2

Merged
zarubinvibe merged 5 commits from phase7-local-agent-contract into main 2026-06-23 19:12:41 +00:00
26 changed files with 1209 additions and 10 deletions
+2
View File
@@ -12,6 +12,8 @@ jobs:
runs-on: macos-latest runs-on: macos-latest
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
with:
fetch-depth: 0 # нужен для merge-base в email-check
- name: shellcheck (lint) - name: shellcheck (lint)
run: | run: |
+83
View File
@@ -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/<id>.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]
@@ -0,0 +1,164 @@
#!/usr/bin/env node
// Athena post-run report. Adapted from mnemazine-postrun-knowledge-report.mjs.
// Input: --results-json <file> — 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 =>
({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[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 => ` <article class="card">
<h3>${esc(r.group_id)}</h3>
<div class="meta"><span class="tag">${esc(r.outcome ?? '')}</span></div>
${r.helps ? `<p class="helps"><b>Helps:</b> ${esc(trunc(r.helps, 200))}</p>` : ''}
${r.next_action ? `<p class="next"><b>Next:</b> ${esc(trunc(r.next_action, 200))}</p>` : ''}
</article>`).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 `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>${esc(TITLE)}</title>
<style>${css}</style>
</head>
<body>
<header class="hero">
<div class="eyebrow">Athena post-run report</div>
<h1>${esc(TITLE)}</h1>
<p class="lead">Run: <code>${esc(RUN_ID)}</code> &middot; ${esc(outcomesSummary(results))}</p>
<div class="stats">
<div class="stat"><strong>${results.length}</strong><span>groups</span></div>
<div class="stat"><strong>${results.filter(r => r.outcome === 'done').length}</strong><span>done</span></div>
<div class="stat"><strong>${results.filter(r => r.next_action).length}</strong><span>with next action</span></div>
</div>
</header>
<main>
<h2>Results</h2>
<div class="cards">
${cards || ' <p>No results.</p>'}
</div>
</main>
</body>
</html>`
}
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')
}
@@ -0,0 +1,123 @@
#!/usr/bin/env node
// Athena report quality gate. Adapted from mnemazine-report-quality-gate.mjs.
// Input: --report <file> | --reports <dir> 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(/<script[\s\S]*?<\/script>/gi, ' ')
.replace(/<style[\s\S]*?<\/style>/gi, ' ')
.replace(/<[^>]+>/g, ' ')
.replace(/&nbsp;/g, ' ')
.replace(/&amp;/g, '&')
.replace(/\s+/g, ' ')
.trim()
}
function toText(content, filename) {
return filename.endsWith('.html') ? stripHtml(content) : content
}
async function listReports() {
if (REPORT) return [path.resolve(REPORT)]
const files = await fs.readdir(REPORTS_DIR, { withFileTypes: true }).catch(() => [])
return files
.filter(e => e.isFile() && (e.name.endsWith('.html') || e.name.endsWith('.md')))
.map(e => path.join(REPORTS_DIR, e.name))
}
function checkReport(file, text) {
const failures = []
// 1. No raw OCR / media artifacts
const rawHits = rawMarkers.filter(re => re.test(text)).map(re => String(re))
if (rawHits.length) failures.push({ rule: 'no-raw-ocr', details: rawHits })
// 2. No hardcoded local paths
const pathHits = localPathMarkers.filter(re => re.test(text)).map(re => String(re))
if (pathHits.length) failures.push({ rule: 'no-local-paths', details: pathHits })
// 3. No secrets / credentials
const secretHits = secretMarkers.filter(re => re.test(text)).map(re => String(re))
if (secretHits.length) failures.push({ rule: 'no-secrets', details: secretHits })
// 4. Must contain an outcome / result signal
if (!/\boutcome\b|\bresult\b/i.test(text)) {
failures.push({ rule: 'has-outcome', details: 'no "outcome" or "result" found in report' })
}
// 5. Must contain a next-action signal
if (!/next[_\s-]action|next\s+step|следующ/i.test(text)) {
failures.push({ rule: 'has-next-action', details: 'no "next_action" or "next step" found in report' })
}
return failures.length ? { file: path.relative(ROOT, file), failures } : null
}
const reports = await listReports()
if (!reports.length) {
process.stdout.write(JSON.stringify({ ok: true, checked: 0, note: 'no reports found' }, null, 2) + '\n')
process.exit(0)
}
const allFailures = []
for (const file of reports) {
const content = await fs.readFile(file, 'utf8')
const text = toText(content, file)
const failure = checkReport(file, text)
if (failure) allFailures.push(failure)
}
if (allFailures.length) {
process.stderr.write(JSON.stringify({ ok: false, checked: reports.length, failures: allFailures }, null, 2) + '\n')
process.exit(1)
}
process.stdout.write(JSON.stringify({ ok: true, checked: reports.length }, null, 2) + '\n')
@@ -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.
@@ -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.
@@ -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.
@@ -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.
@@ -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.
@@ -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.
@@ -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).
@@ -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.
@@ -0,0 +1,101 @@
---
name: agent-session-review
description: Local session learning tail — capture brief_md / agent_trace / self_reflection / most_important at the final edge of a job. Mandatory gate before deliver. Triggers: "session tail", "job done", "end of run", "learning tail", /agent-session-review.
metadata:
model: Sonnet
---
# Agent Session Review (learning tail)
The final edge of every job. A job is not done with a text answer — it is done when the tail is written.
Karpathy method: synthesize on write, not store raw. Short, precise, survives context compression.
Runs at the end of every meaningful agent session **before** handoff / deliver gate.
Mandated by the `final-learning-tail` gate in `handoff-graph.yaml`.
---
## Trigger
- After completing a multi-step job (any provider: Claude Code, Codex).
- Before writing to vault, before handoff, before the deliver gate fires.
- Gate edge `final-learning-tail` checks all four blocks are present.
---
## Four required blocks
All four **must** be present. Missing any block → gate fails.
---
### brief_md
3–5 bullets. What was actually done — artifacts produced, decisions made.
Describe what changed, not what was asked.
```
## Session Brief
- [artifact]: [one concrete line]
- [decision]: [one concrete line]
```
---
### agent_trace
Chronology of key tool calls and decision points.
Not every tool — only inflection points where direction was chosen or changed.
```
## Agent Trace
1. [tool / action] → [outcome or decision]
2. ...
```
---
### self_reflection
One short paragraph each.
```
## Self-Reflection
**Went well:** ...
**Went wrong / could be better:** ...
**Next time:** ...
```
---
### most_important
Single most important thing not to lose: a constraint, a lesson, a warning, a pattern.
Must fit in **one sentence** — this is what survives context compression.
```
## Most Important
[one sentence]
```
---
## Output
Write the tail to `~/.agents/reports/<run-id>-session-tail.md`
or append to the job outbox note.
Optionally pass to the postrun report:
```bash
node ~/.agents/registry/scripts/athena-postrun-report.mjs \
--results-json <results.json> \
--run-id <run-id>
```
---
## Gate check (smoke/agent-contract.sh)
Smoke verifies this file exists and contains all four block names:
`brief_md`, `agent_trace`, `self_reflection`, `most_important`.
+10 -2
View File
@@ -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 ```bash
ls -la ~/.claude/ 2>/dev/null; ls ~/.claude/CLAUDE.md 2>/dev/null ls -la ~/.claude/ 2>/dev/null; ls ~/.claude/CLAUDE.md 2>/dev/null
ls "$HOME"/* knlow* "$HOME/Мозг" 2>/dev/null # vault? ls "$HOME"/* knlow* "$HOME/Мозг" 2>/dev/null # vault?
@@ -89,7 +97,7 @@ AskUserQuestion: «Разрешаешь прогнать установочны
| Фаза | Собирает | Пишет (target) | Tier | | Фаза | Собирает | Пишет (target) | Tier |
|---|---|---|---| |---|---|---|---|
| **P1 Идентичность** | роль/занятость, язык, локация+ограничения, домены экспертизы | `references/owner.md` | hot | | **P1 Идентичность** | роль/занятость, язык (уже зафиксирован на шаге 0.1 — подтвердить), локация+ограничения, домены экспертизы | `references/owner.md` | hot |
| **P2 Проекты+стек** | проекты (имя/статус/критичность), стек, что клонировать/ставить | `owner.md`, `projects.manifest`, `tools.manifest` | hot | | **P2 Проекты+стек** | проекты (имя/статус/критичность), стек, что клонировать/ставить | `owner.md`, `projects.manifest`, `tools.manifest` | hot |
| **P3 Стиль+правила** | model-стенс, коммуникация/caveman, структура ответа, НИКОГДА/ВСЕГДА, gate пакетов | `CLAUDE.md` (слоты `{{ }}`) | hot | | **P3 Стиль+правила** | model-стенс, коммуникация/caveman, структура ответа, НИКОГДА/ВСЕГДА, gate пакетов | `CLAUDE.md` (слоты `{{ }}`) | hot |
| **P4 Операц-преференсы** | security-постура, design/UX-вкус+анти-паттерны, deploy, swarm, web-каскад | `references/{security,design,deploy,agents,scrapegraph}.md` | cold | | **P4 Операц-преференсы** | security-постура, design/UX-вкус+анти-паттерны, deploy, swarm, web-каскад | `references/{security,design,deploy,agents,scrapegraph}.md` | cold |
@@ -61,7 +61,7 @@
- Auto-memory — вспомогательная; canonical факты здесь. - Auto-memory — вспомогательная; canonical факты здесь.
## Правила НИКОГДА ## Правила НИКОГДА
Не нарушать закон · не врать · не лебезить · не бросать задачу · не повторять ошибки · не работать без плана · не менять без бэкапа · **секреты не в коде/git** — только `.env`/secret manager · {{доп-НИКОГДА из грилла — напр. не ставить пакеты без явного добра}}. Не нарушать закон · не врать · не лебезить · не бросать задачу · не повторять ошибки · не работать без плана · не менять без бэкапа · **секреты не в коде/git** — только `.env`/secret manager · **язык общения = {{ЯЗЫК}}, не переключать без явной просьбы (незыблемо)** · {{доп-НИКОГДА из грилла — напр. не ставить пакеты без явного добра}}.
## Правила ВСЕГДА ## Правила ВСЕГДА
1. Сначала план → действие. 1. Сначала план → действие.
@@ -4,7 +4,7 @@
## Кто ## Кто
- **Имя:** {{ИМЯ}} - **Имя:** {{ИМЯ}}
- **Локация:** {{ГОРОД}} · **Язык:** {{ЯЗЫК}} - **Локация:** {{ГОРОД}} · **Язык:** {{ЯЗЫК}} (незыблемое правило общения — не переключать без явной просьбы)
- **Семья:** {{СЕМЬЯ}} - **Семья:** {{СЕМЬЯ}}
- **Тип занятости:** {{ТИП — соло / фирма / фаундер; сколько потоков дохода}} - **Тип занятости:** {{ТИП — соло / фирма / фаундер; сколько потоков дохода}}
- **Роли:** {{РОЛИ}} - **Роли:** {{РОЛИ}}
+1
View File
@@ -1,6 +1,7 @@
# Athena — справочник функций (RU) # Athena — справочник функций (RU)
> English version: [FEATURES.en.md](FEATURES.en.md) · Назад к [README](../README.ru.md) > English version: [FEATURES.en.md](FEATURES.en.md) · Назад к [README](../README.ru.md)
> Дополнение: [перенос идей Mnemazine в AthenaOS](MNEMAZINE-AGENTOS-TRANSFER.ru.md)
<p align="center"> <p align="center">
<img src="assets/six-layers.png" alt="Слоистый разворот Athena" width="85%"> <img src="assets/six-layers.png" alt="Слоистый разворот Athena" width="85%">
+292
View File
@@ -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, а не только хранить логи.
+101
View File
@@ -0,0 +1,101 @@
---
name: agent-session-review
description: Local session learning tail — capture brief_md / agent_trace / self_reflection / most_important at the final edge of a job. Mandatory gate before deliver. Triggers: "session tail", "job done", "end of run", "learning tail", /agent-session-review.
metadata:
model: Sonnet
---
# Agent Session Review (learning tail)
The final edge of every job. A job is not done with a text answer — it is done when the tail is written.
Karpathy method: synthesize on write, not store raw. Short, precise, survives context compression.
Runs at the end of every meaningful agent session **before** handoff / deliver gate.
Mandated by the `final-learning-tail` gate in `handoff-graph.yaml`.
---
## Trigger
- After completing a multi-step job (any provider: Claude Code, Codex).
- Before writing to vault, before handoff, before the deliver gate fires.
- Gate edge `final-learning-tail` checks all four blocks are present.
---
## Four required blocks
All four **must** be present. Missing any block → gate fails.
---
### brief_md
3–5 bullets. What was actually done — artifacts produced, decisions made.
Describe what changed, not what was asked.
```
## Session Brief
- [artifact]: [one concrete line]
- [decision]: [one concrete line]
```
---
### agent_trace
Chronology of key tool calls and decision points.
Not every tool — only inflection points where direction was chosen or changed.
```
## Agent Trace
1. [tool / action] → [outcome or decision]
2. ...
```
---
### self_reflection
One short paragraph each.
```
## Self-Reflection
**Went well:** ...
**Went wrong / could be better:** ...
**Next time:** ...
```
---
### most_important
Single most important thing not to lose: a constraint, a lesson, a warning, a pattern.
Must fit in **one sentence** — this is what survives context compression.
```
## Most Important
[one sentence]
```
---
## Output
Write the tail to `~/.agents/reports/<run-id>-session-tail.md`
or append to the job outbox note.
Optionally pass to the postrun report:
```bash
node ~/.agents/registry/scripts/athena-postrun-report.mjs \
--results-json <results.json> \
--run-id <run-id>
```
---
## Gate check (smoke/agent-contract.sh)
Smoke verifies this file exists and contains all four block names:
`brief_md`, `agent_trace`, `self_reflection`, `most_important`.
+10 -2
View File
@@ -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 ```bash
ls -la ~/.claude/ 2>/dev/null; ls ~/.claude/CLAUDE.md 2>/dev/null ls -la ~/.claude/ 2>/dev/null; ls ~/.claude/CLAUDE.md 2>/dev/null
ls "$HOME"/* knlow* "$HOME/Мозг" 2>/dev/null # vault? ls "$HOME"/* knlow* "$HOME/Мозг" 2>/dev/null # vault?
@@ -89,7 +97,7 @@ AskUserQuestion: «Разрешаешь прогнать установочны
| Фаза | Собирает | Пишет (target) | Tier | | Фаза | Собирает | Пишет (target) | Tier |
|---|---|---|---| |---|---|---|---|
| **P1 Идентичность** | роль/занятость, язык, локация+ограничения, домены экспертизы | `references/owner.md` | hot | | **P1 Идентичность** | роль/занятость, язык (уже зафиксирован на шаге 0.1 — подтвердить), локация+ограничения, домены экспертизы | `references/owner.md` | hot |
| **P2 Проекты+стек** | проекты (имя/статус/критичность), стек, что клонировать/ставить | `owner.md`, `projects.manifest`, `tools.manifest` | hot | | **P2 Проекты+стек** | проекты (имя/статус/критичность), стек, что клонировать/ставить | `owner.md`, `projects.manifest`, `tools.manifest` | hot |
| **P3 Стиль+правила** | model-стенс, коммуникация/caveman, структура ответа, НИКОГДА/ВСЕГДА, gate пакетов | `CLAUDE.md` (слоты `{{ }}`) | hot | | **P3 Стиль+правила** | model-стенс, коммуникация/caveman, структура ответа, НИКОГДА/ВСЕГДА, gate пакетов | `CLAUDE.md` (слоты `{{ }}`) | hot |
| **P4 Операц-преференсы** | security-постура, design/UX-вкус+анти-паттерны, deploy, swarm, web-каскад | `references/{security,design,deploy,agents,scrapegraph}.md` | cold | | **P4 Операц-преференсы** | security-постура, design/UX-вкус+анти-паттерны, deploy, swarm, web-каскад | `references/{security,design,deploy,agents,scrapegraph}.md` | cold |
+1 -1
View File
@@ -61,7 +61,7 @@
- Auto-memory — вспомогательная; canonical факты здесь. - Auto-memory — вспомогательная; canonical факты здесь.
## Правила НИКОГДА ## Правила НИКОГДА
Не нарушать закон · не врать · не лебезить · не бросать задачу · не повторять ошибки · не работать без плана · не менять без бэкапа · **секреты не в коде/git** — только `.env`/secret manager · {{доп-НИКОГДА из грилла — напр. не ставить пакеты без явного добра}}. Не нарушать закон · не врать · не лебезить · не бросать задачу · не повторять ошибки · не работать без плана · не менять без бэкапа · **секреты не в коде/git** — только `.env`/secret manager · **язык общения = {{ЯЗЫК}}, не переключать без явной просьбы (незыблемо)** · {{доп-НИКОГДА из грилла — напр. не ставить пакеты без явного добра}}.
## Правила ВСЕГДА ## Правила ВСЕГДА
1. Сначала план → действие. 1. Сначала план → действие.
+1 -1
View File
@@ -4,7 +4,7 @@
## Кто ## Кто
- **Имя:** {{ИМЯ}} - **Имя:** {{ИМЯ}}
- **Локация:** {{ГОРОД}} · **Язык:** {{ЯЗЫК}} - **Локация:** {{ГОРОД}} · **Язык:** {{ЯЗЫК}} (незыблемое правило общения — не переключать без явной просьбы)
- **Семья:** {{СЕМЬЯ}} - **Семья:** {{СЕМЬЯ}}
- **Тип занятости:** {{ТИП — соло / фирма / фаундер; сколько потоков дохода}} - **Тип занятости:** {{ТИП — соло / фирма / фаундер; сколько потоков дохода}}
- **Роли:** {{РОЛИ}} - **Роли:** {{РОЛИ}}
+109
View File
@@ -0,0 +1,109 @@
#!/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
# 7. agent-session-review skill exists and carries all four required blocks.
SKILL_FILE="$ROOT/chezmoi/dot_claude/skills/agent-session-review/SKILL.md"
if [ ! -f "$SKILL_FILE" ]; then
bad "agent-session-review SKILL.md missing"
else
for block in brief_md agent_trace self_reflection most_important; do
grep -q "$block" "$SKILL_FILE" || bad "agent-session-review SKILL.md: missing block '$block'"
done
fi
# 8-10. Script smoke (requires node — skipped gracefully if absent).
REPORT_SCRIPT="$ROOT/chezmoi/dot_agents/registry/scripts/athena-postrun-report.mjs"
GATE_SCRIPT="$ROOT/chezmoi/dot_agents/registry/scripts/athena-report-quality-gate.mjs"
if command -v node >/dev/null 2>&1 && [ -f "$REPORT_SCRIPT" ] && [ -f "$GATE_SCRIPT" ]; then
SMOKE_TMP="$(mktemp -d /tmp/athena-smoke-XXXXXX)"
trap 'rm -rf "$SMOKE_TMP"' EXIT
# 8. Synthetic postrun-report run — valid input → exit 0 + produces .md file.
printf '[{"group_id":"g1","outcome":"done","helps":"helped with X","next_action":"do Y"}]' \
> "$SMOKE_TMP/results.json"
ATHENA_REPORTS="$SMOKE_TMP/reports" node "$REPORT_SCRIPT" \
--results-json "$SMOKE_TMP/results.json" --run-id smoke --quiet \
&& true || bad "postrun-report: exit non-zero on valid input"
GOOD_REPORT=$(ls "$SMOKE_TMP/reports/"*.md 2>/dev/null | head -1)
if [ -n "$GOOD_REPORT" ]; then
# 9. Quality gate on good report → must PASS (exit 0).
node "$GATE_SCRIPT" --report "$GOOD_REPORT" >/dev/null 2>&1 \
|| bad "quality-gate: good report should PASS"
else
bad "postrun-report: no .md file produced"
fi
# 10. Quality gate on bad report (raw OCR marker, no outcome/next_action) → must FAIL (exit 1).
printf 'temp_image_20240101.HEIC dummy content no outcome here' \
> "$SMOKE_TMP/bad-report.md"
node "$GATE_SCRIPT" --report "$SMOKE_TMP/bad-report.md" >/dev/null 2>&1 \
&& bad "quality-gate: bad report should FAIL" \
|| true
else
[ ! -f "$REPORT_SCRIPT" ] && bad "athena-postrun-report.mjs missing"
[ ! -f "$GATE_SCRIPT" ] && bad "athena-report-quality-gate.mjs missing"
command -v node >/dev/null 2>&1 || echo " → node not found; skipping report+gate smoke"
fi
if [ "$fail" -ne 0 ]; then
echo "AGENT-CONTRACT FAIL" >&2
exit 1
fi
echo " ✓ 7 passports · graph integrity · learning-tail · session-review skill · report+gate"
echo "agent-contract OK"
+16 -2
View File
@@ -31,8 +31,17 @@ echo "[личное] нет имён/usernames/приватных идентиф
# shellcheck disable=SC2034 # используется через eval в chk (строка 31) # shellcheck disable=SC2034 # используется через eval в chk (строка 31)
PERSONAL_RE='(Philipp|Filipp|Zarubin(?!phil)|Филипп|Кирилов|Ломоносов|Менделеев|Калачов|com\.zarubin|7teenno1)' PERSONAL_RE='(Philipp|Filipp|Zarubin(?!phil)|Филипп|Кирилов|Ломоносов|Менделеев|Калачов|com\.zarubin|7teenno1)'
chk "нет личных данных в публичных tracked-файлах" "! git -C '$HERE' grep -IPni -e \"\$PERSONAL_RE\" -- ':!smoke/smoke.sh' ':!docs/audit-2026-06-16/**' >/dev/null 2>&1" chk "нет личных данных в публичных tracked-файлах" "! git -C '$HERE' grep -IPni -e \"\$PERSONAL_RE\" -- ':!smoke/smoke.sh' ':!docs/audit-2026-06-16/**' >/dev/null 2>&1"
# Email автора в истории = PII вне file-grep. Разрешён только GitHub noreply. # Email автора = PII. Проверяем только коммиты ветки/PR, не всю историю репо.
chk "нет личных email в авторах коммитов" "! git -C '$HERE' log --format='%ae %ce' | tr ' ' '\n' | grep -vE '(noreply|^\$)' | grep -q ." # CI checkout refs/pull/N/merge → HEAD = merge commit, HEAD^2 = PR tip, HEAD^1 = main tip.
if _ec_p2=$(git -C "$HERE" rev-parse HEAD^2 2>/dev/null) && [ -n "$_ec_p2" ]; then
_ec_range="HEAD^1..$_ec_p2"
elif _ec_base=$(git -C "$HERE" merge-base HEAD origin/main 2>/dev/null) && [ -n "$_ec_base" ]; then
_ec_range="$_ec_base..HEAD"
else
_ec_range="HEAD"
fi
chk "нет личных email в авторах коммитов" \
"! git -C '$HERE' log '$_ec_range' --no-merges --format='%ae %ce' | tr ' ' '\n' | grep -vE '(noreply|^\$)' | grep -q ."
echo "[канон] chezmoi-source Сознания на месте" echo "[канон] chezmoi-source Сознания на месте"
for f in chezmoi/dot_claude/CLAUDE.md chezmoi/dot_claude/settings.json.tmpl chezmoi/dot_claude/AGENTS.md.tmpl chezmoi/dot_claude/hooks/security-guard.sh chezmoi/dot_claude/hooks/bash-guard.sh chezmoi/dot_claude/rules/structure.md; do for f in chezmoi/dot_claude/CLAUDE.md chezmoi/dot_claude/settings.json.tmpl chezmoi/dot_claude/AGENTS.md.tmpl chezmoi/dot_claude/hooks/security-guard.sh chezmoi/dot_claude/hooks/bash-guard.sh chezmoi/dot_claude/rules/structure.md; do
@@ -181,5 +190,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" 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 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" [ "$fail" = 0 ] && echo "SMOKE OK" || echo "SMOKE FAIL"
exit "$fail" exit "$fail"
+12
View File
@@ -84,3 +84,15 @@ Generic chezmoi-source собран (чистая пересборка, НЕ д
- [x] SKILL.md: Этап A → полный грилл; Этап B → mandatory Карпаты. - [x] SKILL.md: Этап A → полный грилл; Этап B → mandatory Карпаты.
- [x] smoke +12 чеков (assets, ≤200, функц-тест хука nudge/silent/marker); dry-validate зелёный. - [x] smoke +12 чеков (assets, ≤200, функц-тест хука nudge/silent/marker); dry-validate зелёный.
**DoD:** ✓ smoke OK, assets public-safe (личных значений 0). Push — после P1-live-bootstrap (фича не блокирует гейт). **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 матрица.
- [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) — позже.
**DoD:** agent-contract smoke зелёный · 7 паспортов+handoff проходят integrity · прогон оставляет brief/trace/reflection/most-important · parity-smoke `identical` · 0 хардкода путей.
+96
View File
@@ -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/<id>.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 "<stage sub-task>"` **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/<id>.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). **[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.
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.