feat: Фаза 7 шаги 4-6 — session-review skill + postrun-report + quality-gate

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 <noreply@anthropic.com>
This commit is contained in:
Зарубин Филипп
2026-06-23 18:33:42 +03:00
co-authored by Claude Sonnet 4.6
parent 3094b0a6ae
commit cc947028c5
5 changed files with 536 additions and 1 deletions
@@ -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,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`.