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(//gi, ' ') + .replace(//gi, ' ') + .replace(/<[^>]+>/g, ' ') + .replace(/ /g, ' ') + .replace(/&/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') diff --git a/chezmoi/dot_claude/skills/agent-session-review/SKILL.md b/chezmoi/dot_claude/skills/agent-session-review/SKILL.md new file mode 100644 index 0000000..5240e47 --- /dev/null +++ b/chezmoi/dot_claude/skills/agent-session-review/SKILL.md @@ -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/-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 \ + --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`. diff --git a/skills/agent-session-review/SKILL.md b/skills/agent-session-review/SKILL.md new file mode 100644 index 0000000..5240e47 --- /dev/null +++ b/skills/agent-session-review/SKILL.md @@ -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/-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 \ + --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`. diff --git a/smoke/agent-contract.sh b/smoke/agent-contract.sh index 409fe22..ecf2fcf 100755 --- a/smoke/agent-contract.sh +++ b/smoke/agent-contract.sh @@ -55,9 +55,55 @@ else 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" +echo " ✓ 7 passports · graph integrity · learning-tail · session-review skill · report+gate" echo "agent-contract OK"