Files

174 lines
7.0 KiB
JavaScript

#!/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 safe = (p, name) => { if (p.includes('..')) throw new Error(`${name}: path traversal not allowed`); return p }
const EVALS_PATH = safe(arg('evals', process.env.ATHENA_EVALS ||
path.join(HOME, '.agents', 'routing-evals.jsonl')), '--evals')
const REPORTS = path.resolve(safe(arg('reports', process.env.ATHENA_REPORTS ||
path.join(HOME, '.agents', 'reports')), '--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 }))
}