feat: Фаза 8 — dashboard (athena-status + athena-weekly-report)

- specs/08-dashboard.md: спек тонкого UI над Ф7 local-workflows.
- athena-status.mjs: CLI snapshot ≤20 строк из routing-evals.jsonl
  (jobs/classes/split/corrections/steward/reports); exit 1 при unretried failed.
- athena-weekly-report.mjs: weekly MD+HTML из routing-evals.jsonl (last 7d);
  next-steps секция; quality-gate (athena-report-quality-gate.mjs) pass.
- smoke/agent-contract.sh: +Phase 8 проверки (status exit 0 + weekly→quality-gate).
- specs/00-roadmap.md: Ф8 закрыта (✓). docs/FEATURES.ru.md: §20 Dashboard.
- shellcheck -S warning: 0 warnings · SMOKE OK.
This commit is contained in:
Зарубин Филипп
2026-06-23 22:23:50 +03:00
parent 4962d1f721
commit b9aad52bca
6 changed files with 377 additions and 4 deletions
@@ -0,0 +1,84 @@
#!/usr/bin/env node
// Athena status snapshot. Reads routing-evals.jsonl → prints ≤20-line summary.
// Usage: node athena-status.mjs [--days=7] [--evals=PATH] [--json]
// Exit 0: no critical issues. Exit 1: failed jobs with no retry.
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 flag = name => argv.includes(`--${name}`)
const HOME = process.env.HOME || ''
const EVALS_PATH = arg('evals', path.join(HOME, '.agents', 'routing-evals.jsonl'))
const LEDGER_PATH = arg('ledger', path.join(HOME, '.agents', 'job-ledger.jsonl'))
const REPORTS_DIR = arg('reports', path.join(HOME, '.agents', 'reports'))
const STEWARD_PATH = arg('steward', path.join(HOME, '.agents', 'steward-log.jsonl'))
const DAYS = parseInt(arg('days', '7'), 10)
async function readJsonl(filePath) {
try {
const raw = await fs.readFile(filePath, 'utf8')
return raw.split('\n').filter(l => l.trim()).map(l => JSON.parse(l))
} catch { return [] }
}
const cutoff = new Date(Date.now() - DAYS * 86400_000).toISOString()
const evals = (await readJsonl(EVALS_PATH)).filter(e => (e.ts || '') >= cutoff)
const steward = (await readJsonl(STEWARD_PATH)).filter(e => (e.ts || '') >= cutoff)
let reportCount = 0
try {
const files = await fs.readdir(REPORTS_DIR)
reportCount = files.filter(f => f.endsWith('.md') || f.endsWith('.html')).length
} catch { /* not created yet */ }
// Counts
const byOutcome = {}, byClass = {}, byPrimary = {}
let corrections = 0, highConf = 0, medConf = 0, lowConf = 0
for (const e of evals) {
byOutcome[e.outcome || 'unknown'] = (byOutcome[e.outcome || 'unknown'] || 0) + 1
byClass[e.task_class || 'unknown'] = (byClass[e.task_class || 'unknown'] || 0) + 1
byPrimary[e.primary || 'unknown'] = (byPrimary[e.primary || 'unknown'] || 0) + 1
if (e.correction) corrections++
if (e.confidence === 'high') highConf++
else if (e.confidence === 'medium') medConf++
else lowConf++
}
const total = evals.length
const delivered = byOutcome['delivered'] || 0
const failed = (byOutcome['failed'] || 0) + (byOutcome['error'] || 0)
const retry = byOutcome['retry'] || 0
const topClasses = Object.entries(byClass).sort((a, b) => b[1] - a[1]).slice(0, 5)
.map(([k, v]) => `${k} ×${v}`).join(' ') || 'none'
const primarySplit = Object.entries(byPrimary).sort((a, b) => b[1] - a[1])
.map(([k, v]) => `${k} ${v} (${total ? Math.round(v/total*100) : 0}%)`).join(' · ') || 'none'
const now = new Date().toISOString().slice(0, 16).replace('T', ' ')
if (flag('json')) {
process.stdout.write(JSON.stringify({ total, delivered, failed, retry, corrections,
byClass, byPrimary, confidence: { high: highConf, medium: medConf, low: lowConf },
stewardPending: steward.length, reportCount }, null, 2) + '\n')
} else {
const lines = [
`Athena status — ${now} (last ${DAYS}d)`,
`Jobs: ${total} total · ${delivered} delivered · ${retry} retry · ${failed} failed`,
`Top classes: ${topClasses}`,
`Primary split: ${primarySplit}`,
`Confidence: high ×${highConf} medium ×${medConf} low ×${lowConf}`,
`Corrections: ${corrections}`,
`Pending steward proposals: ${steward.length}`,
`Reports: ${REPORTS_DIR} (${reportCount} files)`,
]
process.stdout.write(lines.join('\n') + '\n')
}
// Exit 1 only if failed > 0 and no retry (needs human attention)
if (failed > 0 && retry === 0) process.exit(1)
@@ -0,0 +1,172 @@
#!/usr/bin/env node
// Athena weekly report. Reads routing-evals.jsonl (last 7d) → MD + HTML.
// Input: --evals=PATH (default ~/.agents/routing-evals.jsonl)
// Output: ~/.agents/reports/weekly-<YYYY-Www>.md (+ .html with --format=html)
// Quality-gate: passes athena-report-quality-gate.mjs checks.
import { promises as fs } from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
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 flag = name => argv.includes(`--${name}`)
const HOME = process.env.HOME || ''
const EVALS_PATH = arg('evals', process.env.ATHENA_EVALS ||
path.join(HOME, '.agents', 'routing-evals.jsonl'))
const REPORTS = path.resolve(arg('reports', process.env.ATHENA_REPORTS ||
path.join(HOME, '.agents', 'reports')))
const FORMAT = arg('format', 'md')
const DAYS = parseInt(arg('days', '7'), 10)
// ISO week helper
function isoWeek(d) {
const dt = new Date(d)
dt.setHours(0, 0, 0, 0)
dt.setDate(dt.getDate() + 3 - (dt.getDay() + 6) % 7)
const jan4 = new Date(dt.getFullYear(), 0, 4)
const week = 1 + Math.round(((dt - jan4) / 86400000 - 3 + (jan4.getDay() + 6) % 7) / 7)
return `${dt.getFullYear()}-W${String(week).padStart(2, '0')}`
}
function esc(s) {
return String(s ?? '').replace(/[&<>"']/g, c =>
({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]))
}
async function readJsonl(filePath) {
try {
const raw = await fs.readFile(filePath, 'utf8')
return raw.split('\n').filter(l => l.trim()).map(l => JSON.parse(l))
} catch { return [] }
}
const now = new Date()
const cutoff = new Date(now - DAYS * 86400_000).toISOString()
const allEvals = await readJsonl(EVALS_PATH)
const evals = allEvals.filter(e => (e.ts || '') >= cutoff)
const week = isoWeek(now)
const total = evals.length
const byClass = {}, byPrimary = {}, byOutcome = {}
let corrections = 0
for (const e of evals) {
byClass[e.task_class || '?'] = (byClass[e.task_class || '?'] || 0) + 1
byPrimary[e.primary || '?'] = (byPrimary[e.primary || '?'] || 0) + 1
byOutcome[e.outcome || '?'] = (byOutcome[e.outcome || '?'] || 0) + 1
if (e.correction) corrections++
}
const delivered = byOutcome['delivered'] || 0
const successRate = total ? Math.round(delivered / total * 100) : 0
function classTable() {
const rows = Object.entries(byClass).sort((a, b) => b[1] - a[1])
.map(([k, v]) => `| ${k} | ${v} | ${total ? Math.round(v/total*100) : 0}% |`).join('\n')
return `| Class | Count | Share |\n|---|---|---|\n${rows || '| — | 0 | — |'}`
}
function evalTable() {
if (!evals.length) return '_No jobs this period._'
return evals.slice(-10).reverse().map(e =>
`| ${(e.ts||'').slice(0,10)} | ${e.task_class||'?'} | ${e.primary||'?'} | ${e.outcome||'?'} |${e.correction ? ' ⚠' : ''}`
).join('\n')
}
const correctionNote = corrections > 0
? `Review ${corrections} correction(s) — update start matrix weights in athena-router.`
: 'No corrections this week — matrix routing hypothesis holds.'
const nextSteps = [
correctionNote,
delivered < total ? `Investigate ${total - delivered} undelivered job(s).` : 'All jobs delivered.',
'Run athena-steward if proposals are pending.',
]
const mdContent = `# Athena Weekly Report — ${week}
Generated: ${now.toISOString().slice(0, 16).replace('T', ' ')}
Period: last ${DAYS} days (since ${cutoff.slice(0, 10)})
## Summary
- **Jobs:** ${total}
- **Delivered:** ${delivered} (${successRate}% success rate)
- **Corrections:** ${corrections}
- **Primary split:** ${Object.entries(byPrimary).map(([k,v])=>`${k} ${v}`).join(', ') || 'none'}
## By class
${classTable()}
## Last 10 jobs
| Date | Class | Primary | Outcome | |
|---|---|---|---|---|
${evalTable()}
## Next steps
${nextSteps.map(s => `- ${s}`).join('\n')}
---
*Generated by athena-weekly-report.mjs. Quality-gate: athena-report-quality-gate.mjs.*
`
function htmlContent() {
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(24px,4vw,40px);margin:8px 0 6px}h2{margin:18px 0 10px}
.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}
table{width:100%;border-collapse:collapse;font-size:13px}td,th{text-align:left;padding:6px 8px;border-bottom:1px solid var(--line)}
th{background:#f9fafb;font-weight:600}`
const classRows = Object.entries(byClass).sort((a, b) => b[1] - a[1])
.map(([k, v]) => `<tr><td>${esc(k)}</td><td>${v}</td><td>${total ? Math.round(v/total*100) : 0}%</td></tr>`).join('')
const evalRows = evals.slice(-10).reverse()
.map(e => `<tr><td>${esc((e.ts||'').slice(0,10))}</td><td>${esc(e.task_class||'?')}</td><td>${esc(e.primary||'?')}</td><td>${esc(e.outcome||'?')}${e.correction?' ⚠':''}</td></tr>`).join('')
return `<!doctype html><html lang="en"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Athena Weekly — ${esc(week)}</title><style>${css}</style></head>
<body><header class="hero">
<div class="eyebrow">Athena Weekly Report</div>
<h1>${esc(week)}</h1>
<div class="stats">
<div class="stat"><strong>${total}</strong><span>jobs</span></div>
<div class="stat"><strong>${delivered}</strong><span>delivered</span></div>
<div class="stat"><strong>${successRate}%</strong><span>success rate</span></div>
<div class="stat"><strong>${corrections}</strong><span>corrections</span></div>
</div></header>
<main>
<h2>By class</h2>
<table><thead><tr><th>Class</th><th>Count</th><th>Share</th></tr></thead>
<tbody>${classRows || '<tr><td colspan="3">No data</td></tr>'}</tbody></table>
<h2>Last 10 jobs</h2>
<table><thead><tr><th>Date</th><th>Class</th><th>Primary</th><th>Outcome</th></tr></thead>
<tbody>${evalRows || '<tr><td colspan="4">No data</td></tr>'}</tbody></table>
</main></body></html>`
}
await fs.mkdir(REPORTS, { recursive: true })
const base = `weekly-${week}`
if (FORMAT === 'html') {
const htmlPath = path.join(REPORTS, `${base}.html`)
await fs.writeFile(htmlPath, htmlContent(), 'utf8')
if (!flag('quiet')) console.log(JSON.stringify({ ok: true, week, total, html: htmlPath }))
} else {
const mdPath = path.join(REPORTS, `${base}.md`)
await fs.writeFile(mdPath, mdContent, 'utf8')
if (!flag('quiet')) console.log(JSON.stringify({ ok: true, week, total, md: mdPath }))
}
+8
View File
@@ -130,3 +130,11 @@ Postrun-report + quality-gate (нет OCR/secrets/без next_action — fail).
eval-feedback-loop замкнутым на router через `routing-evals.jsonl`.
**Зачем:** Без контракта «агент выполнил задачу» — слоган. С контрактом — falsifiable. Каждый
прогон оставляет accounting: brief/trace/self_reflection/most_important.
## 20. Dashboard — thin status report (Фаза 8)
**Что:** CLI статус-снапшот + weekly HTML-отчёт поверх Ф7 local-workflows. Без сервера и новой логики.
**Как:** `athena-status.mjs` читает `~/.agents/routing-evals.jsonl` → ≤20-строчный сводный вывод
(jobs/классы/split/коррекции/pending proposals). `athena-weekly-report.mjs` генерирует
`weekly-YYYY-Www.md` (+ `.html`) из тех же eval-логов; quality-gate pass обязателен.
**Зачем:** Видимость без overhead. Каждый routing-decision — falsifiable prediction;
статус показывает тренд без ручного grep'а по логам.
+38
View File
@@ -146,10 +146,48 @@ elif [ -x "$PARITY" ]; then
"$PARITY" "$ROOT" >/dev/null 2>&1 || bad "parity-smoke.sh failed"
fi
# 16. Phase 8 — status + weekly report scripts exist (node syntax check).
STATUS_SCRIPT="$ROOT/chezmoi/dot_agents/registry/scripts/athena-status.mjs"
WEEKLY_SCRIPT="$ROOT/chezmoi/dot_agents/registry/scripts/athena-weekly-report.mjs"
if command -v node >/dev/null 2>&1; then
[ -f "$STATUS_SCRIPT" ] || bad "athena-status.mjs missing"
[ -f "$WEEKLY_SCRIPT" ] || bad "athena-weekly-report.mjs missing"
if [ -f "$STATUS_SCRIPT" ]; then
# status with empty inputs → exit 0
node "$STATUS_SCRIPT" --evals=/dev/null --reports=/tmp/athena-smoke-status >/dev/null 2>&1 \
|| bad "athena-status.mjs: non-zero exit on empty inputs"
fi
if [ -f "$WEEKLY_SCRIPT" ]; then
WEEKLY_TMP="$(mktemp -d /tmp/athena-smoke-weekly-XXXXXX)"
trap 'rm -rf "$WEEKLY_TMP"' EXIT
# synthetic eval → weekly MD produced → quality-gate pass
printf '{"ts":"2026-01-01T00:00:00Z","job_id":"j1","task_class":"code-edit","primary":"codex","reviewer":"claude","confidence":"high","why":["matrix"],"outcome":"delivered","correction":null}\n' \
> "$WEEKLY_TMP/evals.jsonl"
node "$WEEKLY_SCRIPT" --evals="$WEEKLY_TMP/evals.jsonl" --reports="$WEEKLY_TMP/reports" --quiet \
>/dev/null 2>&1 || bad "athena-weekly-report.mjs: non-zero exit on valid input"
WEEKLY_RPT="$(ls "$WEEKLY_TMP/reports/"*.md 2>/dev/null | head -1)"
if [ -n "$WEEKLY_RPT" ]; then
node "$ROOT/chezmoi/dot_agents/registry/scripts/athena-report-quality-gate.mjs" \
--report "$WEEKLY_RPT" >/dev/null 2>&1 \
|| bad "weekly-report quality-gate: FAIL on synthetic report"
else
bad "athena-weekly-report.mjs: no .md produced"
fi
fi
else
[ ! -f "$STATUS_SCRIPT" ] && bad "athena-status.mjs missing"
[ ! -f "$WEEKLY_SCRIPT" ] && bad "athena-weekly-report.mjs missing"
echo " → node not found; skipping Phase 8 runtime 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 " ✓ job-lifecycle FSM · project.yaml template · routing-evals format · start matrix · parity-smoke"
echo " ✓ Phase 8: status CLI · weekly-report · quality-gate on synthetic data"
echo "agent-contract OK"
+8 -4
View File
@@ -95,8 +95,12 @@ Generic chezmoi-source собран (чистая пересборка, НЕ д
- [x] Шаг 10 — shellcheck 0 warnings · SMOKE OK · PR #2 + PR #3 смержены.
**DoD:** ✓ agent-contract smoke зелёный · 7 паспортов · handoff integrity · job-lifecycle FSM · project.yaml · parity-smoke identical · 0 hardcoded paths.
## Фаза 8 — Dashboard (thin UI over verified local workflows)
Тонкий UI-слой поверх Ф7 local-workflows. Без собственной логики — только отображение состояния job-ledger + маршрутизации.
- [ ] Spec + грилл (входные данные: job-lifecycle.yaml + routing-evals.jsonl).
- [ ] Реализация: web/TUI — после live-bootstrap (Ф5 P1) или параллельно.
## Фаза 8 — Dashboard (thin UI over verified local workflows) ✓ (2026-06-23)
Тонкий UI-слой поверх Ф7 local-workflows. Без собственной логики — только читает что производит Ф7.
- [x] Spec: `specs/08-dashboard.md` (входные данные: routing-evals.jsonl + job-ledger).
- [x] `athena-status.mjs` — CLI snapshot (≤20 строк, exit 1 при unretried failed).
- [x] `athena-weekly-report.mjs` — weekly MD+HTML из routing-evals.jsonl; quality-gate pass.
- [x] smoke/agent-contract.sh +Phase 8 проверки (status exit 0 · weekly → quality-gate pass).
- [x] shellcheck 0 warnings · SMOKE OK.
**DoD:** ✓ status + weekly report · quality-gate · smoke green · 0 hardcoded paths.
**Граница:** dashboard НЕ добавляет бизнес-логику. Любой новый контракт → Ф7-spec сначала.
+67
View File
@@ -0,0 +1,67 @@
# Phase 8 — Dashboard (thin UI over verified local workflows)
> Artifact language: English. Communication language: per owner profile.
A dashboard must not invent logic. It reads what Phase 7 produces and makes it visible.
No web server. No database. No new contracts — only new readers.
## What Phase 7 produces (inputs for Phase 8)
| Artifact | Location | Content |
|---|---|---|
| Routing evals | `~/.agents/routing-evals.jsonl` | per-job route decisions |
| Job ledger | `~/.agents/job-ledger.jsonl` | per-job state history |
| Postrun reports | `~/.agents/reports/*.md` | per-run Markdown reports |
| Steward proposals | `~/.agents/steward-log.jsonl` | weekly improvement candidates |
> Phase 7 defines the format; Phase 8 reads it. If a file doesn't exist yet, the reader skips gracefully.
## Two deliverables
### 1. `athena-status.mjs` — CLI status snapshot
```
$ node ~/.agents/registry/scripts/athena-status.mjs
```
Output (≤20 lines):
```
Athena status — 2026-06-23 12:00
Jobs (last 7d): 12 total · 10 delivered · 1 retry · 1 failed
Top classes: code-edit ×4 debug ×3 arch ×2 docs ×2 deploy ×1
Primary split: codex 7 (58%) · claude 5 (42%)
Confidence: high ×9 medium ×2 low ×1
Corrections: 0 this week
Pending steward proposals: 0
Reports: ~/.agents/reports/ (3 files)
```
Returns exit 0 if no critical issues; exit 1 if `failed > 0` and no retry.
### 2. `athena-weekly-report.mjs` — HTML/Markdown weekly summary
Extends `athena-postrun-report.mjs` pattern (same --quiet, --run-id flags).
Reads last 7 days from `routing-evals.jsonl` + steward-log.
Produces `~/.agents/reports/weekly-<YYYY-WW>.md` (+ `.html`).
Quality-gate: same `athena-report-quality-gate.mjs` pass required.
## Layout
| Artifact | chezmoi source | Deploy |
|---|---|---|
| Status CLI | `chezmoi/dot_agents/registry/scripts/athena-status.mjs` | `~/.agents/registry/scripts/` |
| Weekly report | `chezmoi/dot_agents/registry/scripts/athena-weekly-report.mjs` | `~/.agents/registry/scripts/` |
## Smoke additions
- `athena-status.mjs` exists + `node --input-type=module --eval 'import("./athena-status.mjs")'` syntax-check.
- Weekly report: synthetic JSONL → produces `.md` → quality-gate pass.
## DoD
- [ ] `athena-status.mjs` exits 0 on empty inputs (no evals yet).
- [ ] `athena-weekly-report.mjs` produces a valid report from synthetic JSONL.
- [ ] Quality gate passes on the weekly report.
- [ ] Smoke green; shellcheck 0 warnings (bash parts only).
- [ ] 0 hardcoded paths.