ai-agentmanager 1.32.0 → 1.33.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,16 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.33.0 (2026-11-08)
4
+
5
+ - **Eval for each Jira change, with a confidence.** When an agent on a Jira issue says it's done, the app runs the project's tests again itself, on the change as it is (the test command is found in the project's files, or set once per project), and works out an *Eval* from evidence, not from the agent's word. It covers:
6
+ - the tests the agent actually ran in its session and their results;
7
+ - the app's own test run;
8
+ - each acceptance criterion and what proves it;
9
+ - CI on the pull request and the AI judge's review;
10
+ - the brief's checks and the micro benchmarks;
11
+ - what is still pending.
12
+ The **confidence** comes from fixed rules over these: it is **100% only when** the tests pass when run again on the code as it is now, every criterion is met, CI and the judge agree, and nothing is pending. A change made after the run takes it below 100% until the tests run again. It shows as a percentage on the agent, in the Jira list and, for issues done but under 100%, in Today. From the Eval: *Close the gaps* sends what's pending to the agent, *Run tests again*, *Copy for Jira* (Markdown), and *Post to PR* (a comment, only when you press it).
13
+
3
14
  ## 1.32.0 (2026-11-08)
4
15
 
5
16
  - **Micro benchmarks per module, for Jira issues.** The Map has a *Speed* view: click a folder where speed matters, *Benchmark this folder*, and optionally name the Jira components or labels that mean it. An agent on a Jira issue then benchmarks that module when its issue names it (a component or label, or the folder in the request), or when its change touches it: if it says it's done without having measured it, it's asked to once. It runs every case before and after its change on the same machine, and adds cases for what it changed. A module's benchmarks are kept on this computer, outside the repository, so the next issue on it runs the same ones and the numbers line up. Each issue's numbers show on the module (case, before, after, change), and the folder is coloured by what the last issue did to its speed. A case more than 5% slower shows in Today as *Slower*, with *Ask to fix* (the agent makes it as fast as before, or says why it can't be) and *It's fine*. Jira issues' components and labels are now read along with their summary.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ai-agentmanager",
3
- "version": "1.32.0",
3
+ "version": "1.33.0",
4
4
  "description": "Run background coding agents (Claude Code, Codex) per intent, and keep track of them from a web UI, your phone or the CLI",
5
5
  "keywords": [
6
6
  "claude",
package/public/app.js CHANGED
@@ -9,6 +9,7 @@ import { initSide } from '/side.js';
9
9
  import { openCopy, pasteInto } from '/termclip.js';
10
10
  import { initBuilt } from '/built.js';
11
11
  import { addTools, download, htmlFile, initExport } from '/export.js';
12
+ import { evalChip, evalHtml } from '/eval.js';
12
13
  import { badgeHtml as scoreBadge, chipHtml as scoreChip, improveHtml, scorecardHtml, scorecardSpeech } from '/scorecard.js';
13
14
  import { bindListen, listenHtml, play, speakable, now as speaking, stop as stopSpeaking } from '/speak.js';
14
15
  import { initReview } from '/review.js';
@@ -267,6 +268,7 @@ const todayUi = initToday({
267
268
  openReviews: () => reviewsUi.open(),
268
269
  openBugs: (show = 'open') => bugsUi.open({ show }),
269
270
  openChanges: (id) => (showTab('agents'), select(id), reviewUi.open(id)),
271
+ openEval: (id) => (showTab('agents'), select(id), openDoc(id, 'eval')),
270
272
  });
271
273
  $('#today-btn').onclick = () => todayUi.open();
272
274
  // Designs: every agent's design doc, the ones waiting for your review first.
@@ -497,7 +499,7 @@ const INSIGHT_ICONS = { why: '🎯', what: '📦', how: '🛠', now: '📍' };
497
499
  const DOCS = { analysis: 'Analysis', design: 'Design', flow: 'Flow', proposal: 'Proposal', humanai: 'Human vs AI', diagrams: 'Diagrams', scorecard: 'Scorecard' };
498
500
  // Optional extras that "Write all" leaves out.
499
501
  const DOC_EXTRAS = new Set(['diagrams', 'scorecard']);
500
- const DOC_TITLES = { ...DOCS, plan: 'Plan', intent: 'Intent', spec: 'Spec', designdoc: 'Design doc', benchmark: 'Benchmark' };
502
+ const DOC_TITLES = { ...DOCS, eval: 'Eval', plan: 'Plan', intent: 'Intent', spec: 'Spec', designdoc: 'Design doc', benchmark: 'Benchmark' };
501
503
  // The agent's intent, spec and plan files (read from the daemon when opened; kept here by agent and kind).
502
504
  const SPEC_KINDS = { intent: 'Intent', spec: 'Spec', plan: 'Plan', designdoc: 'Design doc', benchmark: 'Benchmark' };
503
505
  // What each optional file is, for its button before it's written.
@@ -513,7 +515,7 @@ async function loadSpec(agentId, kind) {
513
515
  }
514
516
  /** What the document dialog shows: a stakeholder document, or the agent's plan under review. */
515
517
  const docOf = (a, kind) =>
516
- isSpecKind(a, kind) ? specCache.get(`${a?.id}:${kind}`) : kind === 'plan' ? a?.planReview && { markdown: a.planReview.markdown, at: a.planReview.updatedAt } : a?.docs?.[kind];
518
+ kind === 'eval' ? (a?.eval?.markdown ? { markdown: a.eval.markdown, at: a.eval.at } : null) : isSpecKind(a, kind) ? specCache.get(`${a?.id}:${kind}`) : kind === 'plan' ? a?.planReview && { markdown: a.planReview.markdown, at: a.planReview.updatedAt } : a?.docs?.[kind];
517
519
 
518
520
  const VERDICT = { agree: '✓ Agrees', partly: '≈ Partly agrees', disagree: '✗ Disagrees', keep: '✓ Keep', ai: '🤖 AI could answer', reword: '✎ Reword' };
519
521
  const CONFIDENCE = { high: 'High confidence', medium: 'Medium confidence', low: 'Low confidence' };
@@ -629,6 +631,7 @@ function renderDocDialog() {
629
631
  const specKind = isSpecKind(a, docView.kind);
630
632
  $('#doc-title').textContent = `${label} · ${a?.name ?? ''}`;
631
633
  const body = $('#doc-body');
634
+ if (docView.kind === 'eval') return renderEval(a, body, d);
632
635
  body.classList.toggle('diagrams-view', docView.kind === 'diagrams');
633
636
  if (d?.pending) {
634
637
  body.innerHTML = `<p class="hint">${docView.kind === 'humanai' ? 'Splitting the open questions and answering the AI ones, then asking a second model to check…' : docView.kind === 'diagrams' ? "Drawing the diagrams from the documents and the agent's work so far…" : `Writing the ${label.toLowerCase()} document from the agent's work so far…`}</p>`;
@@ -675,13 +678,61 @@ function openDoc(agentId, kind) {
675
678
  $('#doc-body').dataset.rendered = '';
676
679
  $('#doc-dialog').showModal();
677
680
  const a = agents.get(agentId);
678
- if (isSpecKind(a, kind)) {
681
+ if (kind === 'eval') {
682
+ if (!a?.eval?.items) api('POST', `/agents/${agentId}/eval`).catch((e) => toast(e.message, 6000));
683
+ } else if (isSpecKind(a, kind)) {
679
684
  specCache.delete(`${agentId}:${kind}`);
680
685
  loadSpec(agentId, kind).then(() => docView?.agentId === agentId && docView.kind === kind && renderDocDialog());
681
686
  } else if (kind !== 'plan' && !a.docs?.[kind]?.markdown && !a.docs?.[kind]?.pending) generateDoc();
682
687
  renderDocDialog();
683
688
  }
684
689
 
690
+ /** The Eval in the document dialog: drawn again when it or its test run changes. */
691
+ function renderEval(a, body, d) {
692
+ body.classList.remove('diagrams-view');
693
+ const ev = a?.eval;
694
+ const version = `${ev?.at}:${ev?.rerun?.at}:${Boolean(ev?.rerun?.running)}`;
695
+ if (body.dataset.rendered !== version) {
696
+ body.innerHTML = evalHtml(ev, esc, { canPost: Object.values(a?.prs ?? {}).some((p) => p.state === 'OPEN') });
697
+ body.dataset.rendered = version;
698
+ }
699
+ $('#doc-meta').textContent = ev?.at ? `Worked out ${ago(ev.at)}${ev.postedTo ? ' · posted on the pull request' : ''}` : '';
700
+ for (const id of ['doc-copy', 'doc-download', 'doc-print']) $(`#${id}`).disabled = !d?.markdown;
701
+ $('#doc-html').hidden = true;
702
+ $('#doc-listen').innerHTML = '';
703
+ $('#doc-print').hidden = true;
704
+ $('#doc-regen').hidden = true;
705
+ $('#doc-bg').hidden = true;
706
+ $('#doc-foot').hidden = true;
707
+ }
708
+
709
+ $('#doc-body').addEventListener('click', (e) => {
710
+ const b = e.target.closest('[data-eval]');
711
+ if (!b || docView?.kind !== 'eval') return;
712
+ const id = docView.agentId;
713
+ const what = b.dataset.eval;
714
+ if (what === 'copy') {
715
+ return navigator.clipboard.writeText(agents.get(id)?.eval?.markdown ?? '').then(
716
+ () => toast('Eval copied as Markdown; paste it in the Jira issue'),
717
+ () => toast('Copy failed: your browser blocked clipboard access'),
718
+ );
719
+ }
720
+ if (what === 'verify') return act(() => api('POST', `/agents/${id}/eval/verify`), 'Running the tests again on the change');
721
+ if (what === 'gaps') return act(() => api('POST', `/agents/${id}/eval/gaps`), 'Sent the gaps to the agent; the Eval is worked out again when it is done');
722
+ if (what === 'post') return act(async () => toast((await api('POST', `/agents/${id}/eval/post`)).edited ? 'Eval updated on the pull request' : 'Eval posted on the pull request', 4000));
723
+ });
724
+ $('#doc-body').addEventListener('submit', (e) => {
725
+ const f = e.target.closest('[data-eval-command]');
726
+ if (!f || docView?.kind !== 'eval') return;
727
+ e.preventDefault();
728
+ const id = docView.agentId;
729
+ act(async () => {
730
+ const r = await api('PUT', `/agents/${id}/eval/command`, { command: f.command.value });
731
+ await api('POST', `/agents/${id}/eval/verify`);
732
+ toast(r.testCommand ? `Saved; running ${r.testCommand}` : 'Saved', 4000);
733
+ });
734
+ });
735
+
685
736
  function generateDoc() {
686
737
  const { agentId, kind } = docView;
687
738
  act(async () => upsert(await api('POST', `/agents/${agentId}/docs/${kind}`)));
@@ -835,8 +886,9 @@ const OUTCOME = {
835
886
 
836
887
  /** The scorecard before you review: the score, Improve, and the full card. */
837
888
  function scoreStrip(a) {
838
- if (!a.docs?.scorecard?.data && !a.improving) return '';
839
- return `<div class="sc-strip">${scoreBadge(a.docs?.scorecard, esc, { improving: a.improving })} ${improveHtml(a)} ${a.docs?.scorecard?.data ? '<button class="small ghost" data-doc="scorecard">Scorecard</button>' : ''}</div>`;
889
+ const ev = a.eval?.items || a.eval?.rerun?.running ? `${evalChip(a.eval, esc, 'data-doc="eval"')}` : '';
890
+ if (!a.docs?.scorecard?.data && !a.improving && !ev) return '';
891
+ return `<div class="sc-strip">${ev} ${scoreBadge(a.docs?.scorecard, esc, { improving: a.improving })} ${improveHtml(a)} ${a.docs?.scorecard?.data ? '<button class="small ghost" data-doc="scorecard">Scorecard</button>' : ''}${ev ? '<button class="small ghost" data-doc="eval">Eval</button>' : ''}</div>`;
840
892
  }
841
893
 
842
894
  /** End result, status and blockers: first thing a reviewer reads. */
@@ -983,7 +1035,7 @@ function agentItem(a, { project = false } = {}) {
983
1035
  ${a.prs.length ? `<span>${a.prs.length} PR</span>` : ''}
984
1036
  ${a.bugs.length ? `<span>${a.bugs.length} bug</span>` : ''}
985
1037
  ${a.usage?.total ? `<span title="${esc(usageTitle(a.usage))}">${fmtTokens(ioOf(a.usage))} tok</span>` : ''}
986
- ${scoreChip(a, esc)}
1038
+ ${scoreChip(a, esc)}${evalChip(a.eval, esc)}
987
1039
  ${(a.brief?.references ?? []).filter((r) => r.key && r.url).map((r) => `<span class="tag key-ref" title="${esc(r.title || r.url)}">${esc(r.label)}</span>`).join('')}
988
1040
  ${a.brief?.summary?.total
989
1041
  ? `<span class="${a.brief.summary.failed ? 'fail' : ''}" title="${esc(checksSummary(a.brief))}">✓${a.brief.summary.passed}/${a.brief.summary.total}${a.brief.summary.failed ? ` ✗${a.brief.summary.failed}` : ''}</span>`
package/public/eval.js ADDED
@@ -0,0 +1,42 @@
1
+ // Eval on the page: the confidence for an agent's Jira change, what was run and verified, and
2
+ // what's pending. Shared by the agent's Eval document, its strip, the Jira list and Today.
3
+
4
+ const MARK = { ok: '✅', partial: '🟡', pending: '⏳', failed: '❌', na: '—' };
5
+ const tone = (n) => (n === 100 ? 'good' : n >= 70 ? 'mid' : 'bad');
6
+
7
+ /** A small chip: "✔ 100%" / "87%" (or "Testing…"); `attr` makes it a button. */
8
+ export function evalChip(ev, esc, attr = '') {
9
+ if (!ev?.items && !ev?.rerun?.running) return '';
10
+ if (ev.rerun?.running && !ev.items) return `<span class="eval-chip" title="Running the tests again">Testing…</span>`;
11
+ const tip = ev.confidence === 100 ? 'Eval: every check holds up' : `Eval: ${ev.pending.length} pending: ${ev.pending.slice(0, 3).join('; ')}`;
12
+ const inner = `${ev.confidence === 100 ? '✔ ' : ''}${ev.confidence}%${ev.rerun?.running ? ' ↻' : ''}`;
13
+ return attr ? `<button class="eval-chip ${tone(ev.confidence)}" ${attr} title="${esc(tip)}">${inner}</button>` : `<span class="eval-chip ${tone(ev.confidence)}" title="${esc(tip)}">${inner}</span>`;
14
+ }
15
+
16
+ /** The whole Eval: confidence, each verification, the criteria, the tests run, what's pending, and actions. */
17
+ export function evalHtml(ev, esc, { canPost = false } = {}) {
18
+ if (!ev?.items) return `<p class="hint">${ev?.rerun?.running ? `Running <code>${esc(ev.rerun.command)}</code> on the change…` : 'Working the Eval out…'}</p>`;
19
+ const last = new Map();
20
+ for (const r of ev.runs) last.set(r.command, r);
21
+ const rerun = ev.rerun;
22
+ const counts = (c) => (c ? ` <span class="hint">${c.passed} passed${c.failed ? `, ${c.failed} failed` : ''}${c.unit ? ` (${esc(c.unit)})` : ''}</span>` : '');
23
+ return `<div class="eval">
24
+ <div class="eval-head"><span class="eval-score ${tone(ev.confidence)}">${ev.confidence}%</span> <b>${ev.confidence === 100 ? 'Confident: every check holds up' : `confident · ${ev.pending.length} pending`}</b>
25
+ <span class="eval-acts">
26
+ <button class="small" data-eval="verify" ${rerun?.running ? 'disabled' : ''} title="Run the tests again on the change as it is now">${rerun?.running ? 'Running tests…' : 'Run tests again'}</button>
27
+ ${ev.pending.length ? '<button class="small primary" data-eval="gaps" title="Send what is pending to the agent, to bring it to 100%">Close the gaps</button>' : ''}
28
+ ${canPost ? '<button class="small" data-eval="post" title="Post it as a comment on the pull request (edited in place next time)">Post to PR</button>' : ''}
29
+ <button class="small" data-eval="copy" title="Copy as Markdown, to paste in the Jira issue">Copy for Jira</button>
30
+ </span></div>
31
+ <table class="eval-items"><tbody>${ev.items.map((i) => `<tr class="eval-${i.state}"><td>${MARK[i.state]}</td><td>${esc(i.label)}</td><td>${esc(i.detail)}</td></tr>`).join('')}</tbody></table>
32
+ ${ev.criteria.length ? `<h4>Acceptance criteria</h4><ul class="eval-list">${ev.criteria.map((c) => `<li>${c.status === 'met' ? '✅' : c.status === 'not_met' ? '❌' : '⏳'} ${esc(c.criterion)}${c.evidence ? ` <span class="hint">— ${esc(c.evidence)}</span>` : ''}</li>`).join('')}</ul>` : ''}
33
+ <h4>Tests run</h4>
34
+ <ul class="eval-list">
35
+ ${rerun && !rerun.running ? `<li>${rerun.passed ? '✅' : '❌'} <code>${esc(rerun.command)}</code> run again by AI Agent Manager${counts(rerun.counts)} <span class="hint">${esc(new Date(rerun.at).toLocaleString())}${rerun.ms ? ` · ${Math.round(rerun.ms / 1000)}s` : ''}</span>${rerun.passed ? '' : `<pre class="eval-tail">${esc(rerun.tail ?? '')}</pre>`}</li>` : ''}
36
+ ${[...last.values()].map((r) => `<li>${r.passed ? '✅' : '❌'} <code>${esc(r.command)}</code> by the agent${counts(r.counts)} ${ev.runs.filter((x) => x.command === r.command).length > 1 ? `<span class="hint">· ran ${ev.runs.filter((x) => x.command === r.command).length}×, last shown</span>` : ''}</li>`).join('') || '<li class="hint">The agent ran no tests in its session.</li>'}
37
+ </ul>
38
+ <form class="eval-command" data-eval-command><label class="hint">Test command for this project <input name="command" value="${esc(ev.testCommand ?? '')}" placeholder="e.g. npm test" autocomplete="off" /></label> <button class="small">Save</button></form>
39
+ ${ev.pending.length ? `<h4>Pending</h4><ul class="eval-list">${ev.pending.map((p) => `<li>⏳ ${esc(p)}</li>`).join('')}</ul>` : '<p class="hint">Nothing pending.</p>'}
40
+ <p class="hint">Confidence comes from fixed rules over these, not from a model: it is 100% only when the tests pass when run again on the code as it is now, every acceptance criterion is met, CI and the AI judge agree, and nothing is pending.</p>
41
+ </div>`;
42
+ }
package/public/issues.js CHANGED
@@ -4,6 +4,7 @@
4
4
  // agents start only for the ticked ones. Each issue has your action on its left (assign, skip, done,
5
5
  // remove), kept by the daemon across restarts and updates, and changeable any time.
6
6
 
7
+ import { evalChip } from './eval.js';
7
8
  import { listenHtml } from './speak.js';
8
9
  import { holdWhilePicking, rowKeys } from './rowkeys.js';
9
10
  import { expandButton, expandable } from './expand.js';
@@ -119,7 +120,7 @@ export function initIssues({ api, $, esc, ago, openAgent, openDoc, openChanges,
119
120
  : '<span class="hint">—</span>';
120
121
  return `<tr data-row-id="${esc(r.key)}" class="stage-${esc(r.stage)} action-${esc(r.action)}">${box}${actionCell(r)}
121
122
  <td>${issue}${aboutIssue(r)}</td>
122
- <td>${status}</td>
123
+ <td>${status}${r.eval ? `<div>${evalChip(r.eval, esc, `data-issue-doc="eval" data-agent="${esc(r.agent.id)}"`)}</div>` : ''}</td>
123
124
  <td class="issue-note">${esc(r.note)}${r.snoozeUntil ? `<div class="hint">until ${esc(new Date(r.snoozeUntil).toLocaleString([], { weekday: 'short', hour: 'numeric', minute: '2-digit' }))}</div>` : ''}${r.stage === 'review' && !r.pr ? `<div class="issue-ship"><button class="small" data-issue-ship="changes" data-agent="${esc(r.agent.id)}" title="The diff, to look over first">See changes</button> <button class="small primary" data-issue-ship="pr" data-agent="${esc(r.agent.id)}" title="Commit what is left, push and open the pull request">Open PR</button></div>` : ''}</td>
124
125
  <td class="nowrap">${plan}</td>
125
126
  <td class="nowrap">${design}</td>
package/public/style.css CHANGED
@@ -1392,3 +1392,28 @@ tr.bug-detail pre { white-space: pre-wrap; max-height: 280px; overflow: auto; pa
1392
1392
  .today-ask .today-label { color: var(--accent, currentColor); }
1393
1393
  table.today-table td.today-acts { white-space: normal; text-align: right; width: 34%; }
1394
1394
  table.today-table td.today-acts > * { margin: 2px 0; }
1395
+
1396
+ /* ---------- Eval: confidence for a Jira change */
1397
+ .eval-chip { display: inline-block; margin-left: 4px; padding: 0 6px; border-radius: 8px; font-size: 11px; font-weight: 700; white-space: nowrap; background: var(--panel); border: 1px solid currentColor; color: var(--muted); }
1398
+ button.eval-chip { cursor: pointer; }
1399
+ .eval-chip.good { color: var(--green); }
1400
+ .eval-chip.mid { color: var(--amber, #c98a12); }
1401
+ .eval-chip.bad { color: var(--red); }
1402
+ .eval-head { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; margin-bottom: 10px; }
1403
+ .eval-score { font-size: 26px; font-weight: 800; }
1404
+ .eval-score.good { color: var(--green); }
1405
+ .eval-score.mid { color: var(--amber, #c98a12); }
1406
+ .eval-score.bad { color: var(--red); }
1407
+ .eval-acts { margin-left: auto; display: flex; flex-wrap: wrap; gap: 6px; }
1408
+ table.eval-items { width: 100%; border-collapse: collapse; font-size: 13px; }
1409
+ table.eval-items td { padding: 4px 8px 4px 0; border-bottom: 1px solid var(--border); vertical-align: top; }
1410
+ table.eval-items td:first-child { width: 1.6em; }
1411
+ table.eval-items td:nth-child(2) { white-space: nowrap; font-weight: 600; }
1412
+ table.eval-items tr.eval-na td { color: var(--muted); }
1413
+ .eval h4 { margin: 14px 0 4px; }
1414
+ .eval-list { margin: 0; padding-left: 1.2em; list-style: none; }
1415
+ .eval-list li { margin: 3px 0; text-indent: -1.2em; }
1416
+ .eval-tail { margin: 4px 0 0 1.2em; text-indent: 0; max-height: 160px; overflow: auto; font-size: 11.5px; white-space: pre-wrap; }
1417
+ .eval-command { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; margin-top: 10px; }
1418
+ .eval-command input { min-width: 220px; }
1419
+ @media (max-width: 600px) { table.eval-items td:nth-child(2) { white-space: normal; } .eval-acts { margin-left: 0; } }
package/public/today.js CHANGED
@@ -10,7 +10,7 @@ import { expandButton, expandable } from './expand.js';
10
10
  // Up to this score an item is pressing: it counts on the button.
11
11
  const PRESSING = 32;
12
12
 
13
- export function initToday({ api, $, esc, ago, openAgent, showInbox, openActions, openIssues, openReviews, openBugs, openChanges, toast }) {
13
+ export function initToday({ api, $, esc, ago, openAgent, showInbox, openActions, openIssues, openReviews, openBugs, openChanges, openEval, toast }) {
14
14
  const dialog = $('#today-dialog');
15
15
  const body = $('#today-body');
16
16
  let data = null;
@@ -61,6 +61,7 @@ export function initToday({ api, $, esc, ago, openAgent, showInbox, openActions,
61
61
  if (it.kind === 'pr-requested') return [btn('review', 'Review it', 'A reviewer agent reads it and finds what blocks approval (a)', true), link(it.url, 'PR')].join(' ');
62
62
  if (it.kind === 'pr-ready') return [btn('open-reviews', 'Open review', 'Pick what to post (Enter)', true), link(it.url, 'PR')].join(' ');
63
63
  if (it.kind === 'rule') return btn('inbox', 'Inbox', 'Decide in the inbox (Enter)', true);
64
+ if (it.kind === 'eval') return [btn('gaps', 'Close the gaps', 'Send what is pending to the agent, to bring it to 100% (a)', true), btn('eval', 'Eval', 'What was run and verified, and what is pending (Enter)'), btn('done', 'Seen', 'Off the list until its confidence changes (d)'), btn('open', 'Open', "Open the agent's session")].join(' ');
64
65
  if (it.kind === 'bench') return [btn('fix', 'Ask to fix', 'Ask the agent to make it as fast as before, or say why it can\'t be (a)', true), btn('done', "It's fine", 'The slowdown is expected: off the list (d)'), btn('open', 'Open', "Open the agent's session (Enter)")].join(' ');
65
66
  if (it.kind === 'bug-pr') return [link(it.url, 'Open PR'), btn('done', 'Done', 'You looked at it: off the list (d)'), btn('bugs', 'Details', 'The bug and how the fix was checked (Enter)')].join(' ');
66
67
  if (it.kind === 'bug') return [btn('fix', 'Fix', 'Start an agent on it, with the failing test (a)', true), btn('skip', 'Snooze', 'Until tomorrow 9am (s)'), btn('notbug', 'Not a bug', "It won't be reported again"), btn('bugs', 'Evidence', 'See it in Bugs (Enter)')].join(' ');
@@ -201,7 +202,7 @@ export function initToday({ api, $, esc, ago, openAgent, showInbox, openActions,
201
202
  async function act(it, what) {
202
203
  if (!it) return;
203
204
  try {
204
- if (what === 'open' || (what === 'enter' && it.agentId && !['pr-ready', 'rule'].includes(it.kind))) {
205
+ if (what === 'open' || (what === 'enter' && it.agentId && !['pr-ready', 'rule', 'eval'].includes(it.kind))) {
205
206
  if (!it.agentId) return;
206
207
  dialog.close();
207
208
  return openAgent(it.agentId);
@@ -214,6 +215,10 @@ export function initToday({ api, $, esc, ago, openAgent, showInbox, openActions,
214
215
  dialog.close();
215
216
  return openReviews();
216
217
  }
218
+ if (it.kind === 'eval' && (what === 'eval' || what === 'enter')) {
219
+ dialog.close();
220
+ return openEval?.(it.agentId);
221
+ }
217
222
  if (what === 'bugs' || (what === 'enter' && (it.kind === 'bug' || it.kind === 'bug-pr'))) {
218
223
  dialog.close();
219
224
  return openBugs?.(it.kind === 'bug-pr' ? 'pr' : undefined);
@@ -283,6 +288,13 @@ export function initToday({ api, $, esc, ago, openAgent, showInbox, openActions,
283
288
  t.setHours(9, 0, 0, 0);
284
289
  await api('POST', '/findings/set', { ids: [it.findingId], status: what === 'skip' ? 'snoozed' : 'notbug', until: what === 'skip' ? t.toISOString() : null });
285
290
  changedWith(what === 'skip' ? 'Snoozed until tomorrow 9am' : "Not a bug: it won't be reported again", what === 'skip' ? 'snoozed' : 'not a bug', () => api('POST', '/findings/set', { ids: [it.findingId], status: 'open' }));
291
+ } else if (it.kind === 'eval' && (what === 'gaps' || what === 'assign')) {
292
+ await api('POST', `/agents/${it.agentId}/eval/gaps`, {});
293
+ toast?.('Sent the gaps to the agent; the Eval is worked out again when it is done', 4000);
294
+ return;
295
+ } else if (it.kind === 'eval' && what === 'done') {
296
+ await api('POST', `/agents/${it.agentId}/eval/seen`, { seen: true });
297
+ changedWith('Seen: off the list until its confidence changes', 'seen', () => api('POST', `/agents/${it.agentId}/eval/seen`, { seen: false }));
286
298
  } else if (it.kind === 'bench' && (what === 'fix' || what === 'assign')) {
287
299
  await api('POST', `/benchruns/${it.runId}/fix`, {});
288
300
  toast?.('Asked the agent to fix it, or say why it can\'t be', 4000);
package/src/eval.js ADDED
@@ -0,0 +1,438 @@
1
+ // Eval: how sure we can be of the change an agent made for a Jira issue, from evidence rather than
2
+ // the agent's word. It lists the tests the agent ran (from its session, with their results), the
3
+ // tests this app ran again itself on the final change, the acceptance criteria and what proves
4
+ // each, CI, the AI judge's review, the brief's checks and the micro benchmarks; and what is still
5
+ // pending. Confidence is computed by fixed rules from those: 100% only when every item holds up
6
+ // (the app's own test run passes on the code as it is now, every criterion is met, CI and the
7
+ // judge agree, nothing is pending). A model's say-so can't raise it.
8
+ //
9
+ // When an agent on a Jira issue says it's done, the project's test command is run in its folder;
10
+ // the Eval is worked out again whenever its inputs change (a review, the scorecard, CI).
11
+
12
+ import crypto from 'node:crypto';
13
+ import fs from 'node:fs';
14
+ import path from 'node:path';
15
+ import { SLOWER_PCT } from './benchmarks.js';
16
+ import { readSpecDoc } from './brief.js';
17
+
18
+ const TAIL_BYTES = 4 * 1024 * 1024;
19
+ const MAX_RUNS = 60;
20
+ const now = () => new Date().toISOString();
21
+ const err = (status, message) => Object.assign(new Error(message), { status });
22
+ const clip = (s, n) => {
23
+ const t = String(s ?? '');
24
+ return t.length > n ? `${t.slice(0, n - 1)}…` : t;
25
+ };
26
+
27
+ // A command that runs tests (not one that only builds or lints).
28
+ export const TEST_COMMAND =
29
+ /(^|[\s;&|(])((npm|pnpm|yarn|bun)\s+(run\s+)?(test|t)\b|npx\s+(jest|vitest|mocha|playwright\s+test|ava|tap)\b|node\s+(--test|[\w./-]*test[\w./-]*\.m?js)\b|jest\b|vitest\b|mocha\b|go\s+test\b|pytest\b|python3?\s+-m\s+(pytest|unittest)\b|tox\b|cargo\s+(test|nextest)\b|mvn\b[^;&|]*\b(test|verify)\b|(\.\/)?gradlew?\b[^;&|]*\btest\b|make\s+(test|check)\b|dotnet\s+test\b|rspec\b|rake\s+test\b|ctest\b|swift\s+test\b|phpunit\b|mix\s+test\b|deno\s+test\b)/;
30
+
31
+ /** Passed and failed counts from a test run's output, when it says (node, jest, pytest, go, mvn, cargo…). */
32
+ export function countsOf(output) {
33
+ const t = String(output ?? '');
34
+ const num = (re) => {
35
+ const m = re.exec(t);
36
+ return m ? Number(m[1]) : null;
37
+ };
38
+ // node --test (TAP)
39
+ let passed = num(/^# pass (\d+)/m);
40
+ let failed = num(/^# fail (\d+)/m);
41
+ if (passed !== null || failed !== null) return { passed: passed ?? 0, failed: failed ?? 0 };
42
+ // jest / vitest: "Tests: 1 failed, 12 passed, 13 total" / "Tests 12 passed (12)"
43
+ const jest = /Tests:?\s+(?:(\d+) failed,?\s*)?(?:\d+ skipped,?\s*)?(?:(\d+) passed)/.exec(t);
44
+ if (jest) return { passed: Number(jest[2] ?? 0), failed: Number(jest[1] ?? 0) };
45
+ // pytest: "== 3 failed, 41 passed in 2.1s ==" (its last summary line)
46
+ const py = [...t.matchAll(/^=+ ([^=\n]*\b(?:passed|failed)\b[^=\n]*) =+$/gm)].pop()?.[1];
47
+ if (py) return { passed: Number(/(\d+) passed/.exec(py)?.[1] ?? 0), failed: Number(/(\d+) failed/.exec(py)?.[1] ?? 0) + Number(/(\d+) errors?/.exec(py)?.[1] ?? 0) };
48
+ // mvn / surefire: "Tests run: 12, Failures: 1, Errors: 0"
49
+ const mvn = [...t.matchAll(/Tests run: (\d+), Failures: (\d+), Errors: (\d+)/g)].pop();
50
+ if (mvn) return { passed: Number(mvn[1]) - Number(mvn[2]) - Number(mvn[3]), failed: Number(mvn[2]) + Number(mvn[3]) };
51
+ // cargo: "test result: ok. 12 passed; 0 failed"
52
+ const cargo = [...t.matchAll(/test result: \w+\. (\d+) passed; (\d+) failed/g)];
53
+ if (cargo.length) return cargo.reduce((s, m) => ({ passed: s.passed + Number(m[1]), failed: s.failed + Number(m[2]) }), { passed: 0, failed: 0 });
54
+ // go: "ok pkg" / "FAIL pkg" lines, and "--- FAIL:" per test
55
+ const ok = (t.match(/^ok\s+\S+/gm) ?? []).length;
56
+ const bad = (t.match(/^--- FAIL:/gm) ?? []).length || (t.match(/^FAIL\s+\S+/gm) ?? []).length;
57
+ if (ok || bad) return { passed: ok, failed: bad, unit: 'packages' };
58
+ return null;
59
+ }
60
+
61
+ /** The text of a tool result (a string, or a list of text parts). */
62
+ const resultText = (c) => (typeof c === 'string' ? c : Array.isArray(c) ? c.map((x) => (typeof x === 'string' ? x : x?.text ?? '')).join('\n') : '');
63
+
64
+ /**
65
+ * The test runs in an agent's session (Claude Code's transcript, JSON lines): every Bash call that
66
+ * ran tests, with whether it passed and the counts it printed. Oldest first.
67
+ */
68
+ export function testRuns(text) {
69
+ const calls = new Map();
70
+ const runs = [];
71
+ for (const line of String(text ?? '').split('\n')) {
72
+ if (!line.includes('"tool_use"') && !line.includes('"tool_result"')) continue;
73
+ let entry;
74
+ try {
75
+ entry = JSON.parse(line);
76
+ } catch {
77
+ continue; // the first line may be cut
78
+ }
79
+ for (const c of entry.message?.content ?? []) {
80
+ if (c?.type === 'tool_use' && c.name === 'Bash' && typeof c.input?.command === 'string' && TEST_COMMAND.test(c.input.command)) {
81
+ calls.set(c.id, { command: clip(c.input.command.trim(), 300), at: entry.timestamp ?? null });
82
+ } else if (c?.type === 'tool_result' && calls.has(c.tool_use_id)) {
83
+ const call = calls.get(c.tool_use_id);
84
+ calls.delete(c.tool_use_id);
85
+ const out = resultText(c.content);
86
+ const counts = countsOf(out);
87
+ // A command that failed says so (is_error, "Exit code N"); failures counted mean failed too.
88
+ const passed = !c.is_error && !/^Exit code [1-9]/m.test(out) && !(counts?.failed > 0);
89
+ runs.push({ ...call, passed, counts, tail: clip(out.split('\n').slice(-8).join('\n'), 600) });
90
+ }
91
+ }
92
+ }
93
+ return runs.slice(-MAX_RUNS);
94
+ }
95
+
96
+ /** Read the end of a transcript (big sessions: the last few MB, where the final runs are). */
97
+ export function readTail(file) {
98
+ try {
99
+ const st = fs.statSync(file);
100
+ const len = Math.min(st.size, TAIL_BYTES);
101
+ const fd = fs.openSync(file, 'r');
102
+ try {
103
+ const buf = Buffer.alloc(len);
104
+ fs.readSync(fd, buf, 0, len, st.size - len);
105
+ return buf.toString('utf8');
106
+ } finally {
107
+ fs.closeSync(fd);
108
+ }
109
+ } catch {
110
+ return '';
111
+ }
112
+ }
113
+
114
+ /** The project's test command from its files, or null: `exists(name)` and `read(name)` look in its folder. */
115
+ export function detectTestCommand({ exists, read }) {
116
+ if (exists('package.json')) {
117
+ try {
118
+ const t = JSON.parse(read('package.json'))?.scripts?.test;
119
+ if (t && !/no test specified/.test(t)) return exists('pnpm-lock.yaml') ? 'pnpm test' : exists('yarn.lock') ? 'yarn test' : 'npm test';
120
+ } catch {}
121
+ }
122
+ if (exists('go.mod')) return 'go test ./...';
123
+ if (exists('Cargo.toml')) return 'cargo test';
124
+ if (exists('pom.xml')) return exists('mvnw') ? './mvnw -q test' : 'mvn -q test';
125
+ if (exists('gradlew')) return './gradlew test';
126
+ if (['pytest.ini', 'conftest.py', 'tox.ini', 'pyproject.toml', 'setup.cfg'].some(exists)) return 'python3 -m pytest -q';
127
+ if (exists('Makefile') && /^test:/m.test(read('Makefile') ?? '')) return 'make test';
128
+ return null;
129
+ }
130
+
131
+ /** The command the agent ran most (its last run of it wins ties): what it thinks the tests are. */
132
+ export function usualCommand(runs) {
133
+ const n = new Map();
134
+ for (const r of runs) n.set(r.command, (n.get(r.command) ?? 0) + 1);
135
+ let best = null;
136
+ for (const [c, k] of n) if (!best || k >= best[1]) best = [c, k];
137
+ return best?.[0] ?? null;
138
+ }
139
+
140
+ // What each item weighs in the confidence; "na" items don't count either way.
141
+ export const WEIGHTS = { rerun: 25, criteria: 25, agentTests: 10, coverage: 10, ci: 10, judge: 10, checks: 5, bench: 5 };
142
+ export const LABELS = {
143
+ rerun: 'Tests run again by AI Agent Manager',
144
+ criteria: 'Acceptance criteria',
145
+ agentTests: 'Tests the agent ran',
146
+ coverage: 'Tests for the changed code',
147
+ ci: 'CI on the pull request',
148
+ judge: 'AI judge review',
149
+ checks: 'Checks in the brief',
150
+ bench: 'Micro benchmarks',
151
+ };
152
+
153
+ /**
154
+ * The Eval from what is known: { confidence, items: [{ key, label, state, score, detail }],
155
+ * pending: [text], runs, rerun, criteria }. state: ok | partial | pending | failed | na.
156
+ */
157
+ export function evaluate({ runs = [], rerun = null, state = null, scorecard = null, hasSpec = false, ci = null, ciFailed = [], review = null, judgeOn = true, checks = [], codeFiles = 0, testFiles = 0, bench = null, testCommand = null, readable = true }) {
158
+ const items = [];
159
+ const add = (key, st, score, detail, extra = {}) => items.push({ key, label: LABELS[key], state: st, score, detail, ...extra });
160
+
161
+ // The app's own run, on the code as it is now.
162
+ if (rerun?.running) add('rerun', 'pending', 0, `Running ${rerun.command}…`);
163
+ else if (!rerun) add('rerun', 'pending', 0, testCommand ? `Not run yet (${testCommand})` : 'No test command found for this project: set one');
164
+ else if (state && rerun.state !== state) add('rerun', 'pending', 0, `The code changed after the last run (${rerun.passed ? 'passed' : 'failed'} ${rerun.at}): run again`);
165
+ else if (rerun.passed) add('rerun', 'ok', 1, `${rerun.command} passed${rerun.counts ? `: ${rerun.counts.passed} passed` : ''}`);
166
+ else add('rerun', 'failed', 0, `${rerun.command} failed${rerun.counts ? `: ${rerun.counts.failed} failed, ${rerun.counts.passed} passed` : rerun.timedOut ? ' (timed out)' : ''}`);
167
+
168
+ // Acceptance criteria, as the scorecard found them.
169
+ const crit = scorecard?.criteria ?? [];
170
+ if (crit.length) {
171
+ const met = crit.filter((c) => c.status === 'met').length;
172
+ const st = met === crit.length ? 'ok' : crit.some((c) => c.status === 'not_met') ? 'failed' : 'partial';
173
+ add('criteria', st, met / crit.length, `${met} of ${crit.length} met`);
174
+ } else if (scorecard) add('criteria', 'pending', 0, hasSpec ? 'Not assessed by the scorecard' : 'No acceptance criteria written (no spec)');
175
+ else add('criteria', 'pending', 0, hasSpec ? 'Not checked yet: the scorecard checks them' : 'No acceptance criteria written (no spec)');
176
+
177
+ // The agent's own runs: the last run of each command.
178
+ const last = new Map();
179
+ for (const r of runs) last.set(r.command, r);
180
+ const finals = [...last.values()];
181
+ if (!readable) add('agentTests', 'na', 0, "This engine's session can't be read for test runs");
182
+ else if (!runs.length) add('agentTests', 'pending', 0, 'The agent ran no tests in its session');
183
+ else if (finals.every((r) => r.passed)) add('agentTests', 'ok', 1, `${runs.length} run${runs.length === 1 ? '' : 's'}; the last of each passed`);
184
+ else add('agentTests', 'failed', 0, `Last run failed: ${finals.filter((r) => !r.passed).map((r) => r.command).join(', ')}`);
185
+
186
+ if (!codeFiles) add('coverage', 'na', 0, 'No code changed');
187
+ else if (testFiles) add('coverage', 'ok', 1, `${testFiles} test file${testFiles === 1 ? '' : 's'} changed with ${codeFiles} code file${codeFiles === 1 ? '' : 's'}`);
188
+ else add('coverage', 'pending', 0, `${codeFiles} code file${codeFiles === 1 ? '' : 's'} changed, no test changed or added`);
189
+
190
+ if (ci === 'passed') add('ci', 'ok', 1, 'All checks pass');
191
+ else if (ci === 'failed') add('ci', 'failed', 0, `Failing${ciFailed.length ? `: ${ciFailed.join(', ')}` : ''}`);
192
+ else if (ci === 'running') add('ci', 'pending', 0, 'Checks still running');
193
+ else add('ci', 'na', 0, 'No pull request (or no checks) yet');
194
+
195
+ if (!judgeOn) add('judge', 'na', 0, 'The AI judge is off');
196
+ else if (review?.pending) add('judge', 'pending', 0, 'Reviewing…');
197
+ else if (!review?.verdict) add('judge', 'pending', 0, 'Not reviewed yet');
198
+ else if (review.verdict === 'complete') add('judge', 'ok', 1, `Complete${review.summary ? `: ${clip(review.summary, 160)}` : ''}`);
199
+ else if (review.verdict === 'partial') add('judge', 'partial', 0.5, `Partly done${review.missing?.length ? `; missing: ${review.missing.join('; ')}` : ''}`);
200
+ else add('judge', 'failed', 0, `Not done${review.missing?.length ? `; missing: ${review.missing.join('; ')}` : ''}`);
201
+
202
+ const count = (st) => checks.filter((c) => c.state === st).length;
203
+ if (!checks.length) add('checks', 'na', 0, 'No checks listed');
204
+ else if (count('failed')) add('checks', 'failed', 0, `${count('failed')} of ${checks.length} failed`);
205
+ else if (count('pending') + count('running')) add('checks', 'partial', count('passed') / checks.length, `${count('passed')} of ${checks.length} passed, ${count('pending') + count('running')} pending`);
206
+ else add('checks', 'ok', 1, `${checks.length} passed`);
207
+
208
+ if (!bench) add('bench', 'na', 0, 'Not benchmarked');
209
+ else if (!bench.runs.length) add('bench', 'pending', 0, `${bench.modules.join(', ')}: not measured yet`);
210
+ else {
211
+ const slow = bench.runs.filter((r) => r.worst !== null && r.worst > SLOWER_PCT && !r.accepted);
212
+ if (slow.length) add('bench', 'failed', 0, slow.map((r) => `${r.module || 'repository'} ${r.worst}% slower`).join('; '));
213
+ else add('bench', 'ok', 1, bench.runs.map((r) => `${r.module || 'repository'} ${r.worst === null ? 'measured' : r.worst > 0 ? `+${r.worst}%` : `${r.worst}%`}`).join('; '));
214
+ }
215
+
216
+ const counted = items.filter((i) => i.state !== 'na');
217
+ const total = counted.reduce((n, i) => n + WEIGHTS[i.key], 0);
218
+ let confidence = total ? Math.floor((100 * counted.reduce((n, i) => n + WEIGHTS[i.key] * i.score, 0)) / total) : 0;
219
+ // 100 only when everything holds up.
220
+ if (counted.some((i) => i.state !== 'ok')) confidence = Math.min(confidence, 99);
221
+ const pending = [
222
+ ...items.filter((i) => i.state !== 'ok' && i.state !== 'na').map((i) => `${i.label}: ${i.detail}`),
223
+ ...crit.filter((c) => c.status !== 'met').map((c) => `${c.status === 'not_met' ? 'Not met' : 'Not verified'}: ${c.criterion}`),
224
+ ];
225
+ return { confidence, items, pending, criteria: crit, runs, rerun, at: now() };
226
+ }
227
+
228
+ const MARK = { ok: '✅', partial: '🟡', pending: '⏳', failed: '❌', na: '—' };
229
+
230
+ /** Markdown: to copy into Jira or post on the pull request. */
231
+ export function evalMarkdown(ev, title = '') {
232
+ const last = new Map();
233
+ for (const r of ev.runs) last.set(r.command, r);
234
+ return [
235
+ `### Eval${title ? `: ${title}` : ''}`,
236
+ '',
237
+ `**Confidence: ${ev.confidence}%**${ev.confidence === 100 ? ' (every check holds up)' : ''}`,
238
+ '',
239
+ '| | Verification | Result |',
240
+ '| --- | --- | --- |',
241
+ ...ev.items.map((i) => `| ${MARK[i.state]} | ${i.label} | ${String(i.detail).replace(/\|/g, '/').replace(/\n/g, ' ')} |`),
242
+ '',
243
+ ...(ev.criteria.length ? ['**Acceptance criteria**', '', ...ev.criteria.map((c) => `- ${c.status === 'met' ? '✅' : c.status === 'not_met' ? '❌' : '⏳'} ${c.criterion}${c.evidence ? ` — ${c.evidence}` : ''}`), ''] : []),
244
+ ...(last.size ? ['**Tests run**', '', ...[...last.values()].map((r) => `- ${r.passed ? '✅' : '❌'} \`${r.command}\`${r.counts ? ` (${r.counts.passed} passed, ${r.counts.failed} failed)` : ''}`), ...(ev.rerun && !ev.rerun.running ? [`- ${ev.rerun.passed ? '✅' : '❌'} \`${ev.rerun.command}\` run again by AI Agent Manager on the final change${ev.rerun.counts ? ` (${ev.rerun.counts.passed} passed, ${ev.rerun.counts.failed} failed)` : ''}`] : []), ''] : []),
245
+ ...(ev.pending.length ? ['**Pending**', '', ...ev.pending.map((p) => `- ${p}`), ''] : ['Nothing pending.', '']),
246
+ ].join('\n');
247
+ }
248
+
249
+ /** "Close the gaps": what the agent is asked to do to bring confidence to 100%. */
250
+ export function gapsMessage(ev) {
251
+ return [
252
+ `The Eval of this change is ${ev.confidence}% confident. To make it 100%, close these gaps:`,
253
+ ev.pending.map((p) => `- ${p}`).join('\n'),
254
+ 'Add or fix tests for the changed code and run them, meet each acceptance criterion and show what proves it (a test or a check in the brief), and fix what fails. Stay within the task. Update the brief when you are done; the tests are run again and the Eval worked out again then.',
255
+ ].join('\n\n');
256
+ }
257
+
258
+ /** A short hash of the code as it is: HEAD, and what is changed or added on top. */
259
+ export const stateHash = (head, status, diff) => crypto.createHash('sha1').update(`${head}\n${status}\n${diff}`).digest('hex').slice(0, 16);
260
+
261
+ export class Evals {
262
+ /**
263
+ * `run(agent, command)` → { passed, output, timedOut } runs a command in the agent's folder;
264
+ * `state(agent)` → a hash of its code as it is; `changes(agent)` → { files: [{ path }] };
265
+ * `transcript(agent)` → its session's text (Claude Code), or null when it can't be read.
266
+ */
267
+ constructor({ manager, store, run, state, changes = async () => ({ files: [] }), transcript, benches = null, log = () => {} }) {
268
+ this.manager = manager;
269
+ this.store = store;
270
+ this.run = run;
271
+ this.state = state;
272
+ this.changes = changes;
273
+ this.transcript = transcript;
274
+ this.benches = benches;
275
+ this.log = log;
276
+ this.running = new Set();
277
+ this.onFinished = (agent) => {
278
+ if (agent && this.eligible(agent)) this.verify(agent.id).catch((e) => this.log(`eval: ${e.message}`));
279
+ };
280
+ manager.on('finished', this.onFinished);
281
+ this.timer = null;
282
+ }
283
+
284
+ close() {
285
+ this.manager.off('finished', this.onFinished);
286
+ clearInterval(this.timer);
287
+ }
288
+
289
+ /** Every minute: work out again the Evals whose inputs changed (a review, the scorecard, CI). */
290
+ startTimer(ms = 60_000) {
291
+ this.timer = setInterval(() => this.refreshAll().catch((e) => this.log(`eval: ${e.message}`)), ms);
292
+ this.timer.unref?.();
293
+ }
294
+
295
+ /** Task agents on a Jira issue (not hunters, reviewers, fixers or team members). */
296
+ eligible(agent) {
297
+ return Boolean(agent && agent.kind === 'task' && agent.workdir && !agent.hunting && !agent.reviewing && !agent.fixing && !agent.team && !agent.builds && this.manager.issueKey(agent));
298
+ }
299
+
300
+ /** The project's test command: set for the project, else found in its files, else the agent's usual one. */
301
+ testCommand(agent, runs = []) {
302
+ const p = this.manager.projectInfo(agent);
303
+ const set = Object.values(this.store.data.projects ?? {}).find((x) => x.key === p?.key)?.testCommand;
304
+ if (set) return set;
305
+ const dir = agent.workdir;
306
+ const found = dir && fs.existsSync(dir) ? detectTestCommand({ exists: (n) => fs.existsSync(path.join(dir, n)), read: (n) => fs.readFileSync(path.join(dir, n), 'utf8') }) : null;
307
+ return found ?? usualCommand(runs);
308
+ }
309
+
310
+ /** Set the test command for an agent's project (empty: back to finding it). */
311
+ setTestCommand(ref, command) {
312
+ const agent = this.manager.mustGet(ref);
313
+ const p = this.manager.projectInfo(agent);
314
+ const entry = Object.values(this.store.data.projects ?? {}).find((x) => x.key === p?.key);
315
+ if (!entry) throw err(409, "This agent's project isn't registered");
316
+ const c = String(command ?? '').trim().slice(0, 300);
317
+ if (c) entry.testCommand = c;
318
+ else delete entry.testCommand;
319
+ this.store.save();
320
+ return { testCommand: this.testCommand(agent) };
321
+ }
322
+
323
+ /** Run the tests on the agent's change as it is now, then work the Eval out. */
324
+ async verify(ref) {
325
+ const agent = this.manager.mustGet(ref);
326
+ if (!agent.workdir || !fs.existsSync(agent.workdir)) throw err(409, 'The agent has no folder to run the tests in');
327
+ if (this.running.has(agent.id)) return this.view(agent.id);
328
+ const runs = this.runsOf(agent);
329
+ const command = this.testCommand(agent, runs ?? []);
330
+ if (!command) return this.compute(agent.id);
331
+ this.running.add(agent.id);
332
+ this.manager.patch(agent.id, { eval: { ...(agent.eval ?? {}), rerun: { command, running: true, at: now() } } });
333
+ let rerun = null;
334
+ try {
335
+ const started = Date.now();
336
+ const st = await this.state(agent).catch(() => null);
337
+ const res = await this.run(agent, command);
338
+ rerun = { command, passed: Boolean(res.passed), counts: countsOf(res.output), tail: clip(String(res.output ?? '').split('\n').slice(-15).join('\n'), 2000), timedOut: Boolean(res.timedOut), state: st, at: now(), ms: Date.now() - started };
339
+ } catch (e) {
340
+ rerun = { command, passed: false, counts: null, tail: clip(String(e?.message ?? e), 2000), timedOut: false, state: null, at: now(), ms: 0 };
341
+ } finally {
342
+ this.running.delete(agent.id);
343
+ }
344
+ // The run and what it means are kept together, so no one sees one without the other.
345
+ return this.compute(agent.id, rerun);
346
+ }
347
+
348
+ runsOf(agent) {
349
+ const text = this.transcript(agent);
350
+ return text === null ? null : testRuns(text);
351
+ }
352
+
353
+ /** Work the Eval out from what is known now (no test run), and keep it on the agent. */
354
+ async compute(id, rerun) {
355
+ const stored = this.store.get(id);
356
+ if (!stored) return null;
357
+ const agent = rerun ? { ...stored, eval: { ...(stored.eval ?? {}), rerun } } : stored;
358
+ const runs = this.runsOf(agent);
359
+ const ch = await this.changes(agent).catch(() => ({ files: [] }));
360
+ const TEST = /(^|\/)(tests?|__tests__|spec|specs)\/|[._-](test|spec)\.[a-z]+$|_test\.go$|Test\.java$/i;
361
+ const files = (ch?.files ?? []).map((f) => f.path ?? f);
362
+ const testFiles = files.filter((p) => TEST.test(p)).length;
363
+ const codeFiles = files.filter((p) => !TEST.test(p) && !/\.(md|txt|rst|adoc)$/i.test(p) && !/(^|\/)docs?\//i.test(p)).length;
364
+ const pr = Object.values(agent.prs ?? {}).find((p) => p.source !== 'mentioned' && p.state === 'OPEN') ?? Object.values(agent.prs ?? {}).find((p) => p.source !== 'mentioned');
365
+ const benchRuns = this.benches ? this.benches.runs.filter((r) => r.agentId === id) : [];
366
+ const benchMods = [...new Set([...(agent.benchModules ?? []), ...benchRuns.map((r) => r.module)])];
367
+ const ev = evaluate({
368
+ runs: runs ?? [],
369
+ readable: runs !== null,
370
+ rerun: agent.eval?.rerun ?? null,
371
+ state: await this.state(agent).catch(() => null),
372
+ scorecard: agent.docs?.scorecard?.data ?? null,
373
+ hasSpec: Boolean(readSpecDoc(id, 'spec')?.markdown?.trim()),
374
+ ci: pr?.checks?.state ?? null,
375
+ ciFailed: pr?.checks?.failed ?? [],
376
+ review: agent.aiReview ?? null,
377
+ judgeOn: this.manager.judge?.enabled !== false,
378
+ checks: agent.brief?.checks ?? [],
379
+ codeFiles,
380
+ testFiles,
381
+ bench: benchMods.length ? { modules: benchMods, runs: benchRuns } : null,
382
+ testCommand: this.testCommand(agent, runs ?? []),
383
+ });
384
+ ev.sig = this.signature(agent);
385
+ ev.markdown = evalMarkdown(ev, agent.name);
386
+ ev.testCommand = this.testCommand(agent, runs ?? []);
387
+ const cur = this.store.get(id);
388
+ if (!cur) return null;
389
+ // A test run ended while this was worked out: the one it ended with has the newer answer.
390
+ if (!rerun && (cur.eval?.rerun?.at ?? null) !== (agent.eval?.rerun?.at ?? null)) return this.view(id);
391
+ this.manager.patch(id, { eval: { ...ev, rerun: rerun ?? cur.eval?.rerun ?? null, postedTo: cur.eval?.postedTo ?? null } });
392
+ return this.view(id);
393
+ }
394
+
395
+ /** What the Eval was worked out from: when it changes, it's worked out again. */
396
+ signature(agent) {
397
+ const pr = Object.values(agent.prs ?? {}).map((p) => `${p.url}:${p.state}:${p.checks?.state ?? ''}`).join(',');
398
+ const bench = this.benches ? this.benches.runs.filter((r) => r.agentId === agent.id).map((r) => `${r.id}:${r.at}:${r.accepted ?? ''}`).join(',') : '';
399
+ return [agent.aiReview?.at, agent.aiReview?.pending, agent.docs?.scorecard?.at, agent.brief?.updatedAt, pr, bench, agent.eval?.rerun?.at].join('|');
400
+ }
401
+
402
+ async refreshAll() {
403
+ for (const a of this.store.list()) {
404
+ if (!a.eval || a.eval.rerun?.running || this.running.has(a.id)) continue;
405
+ if (a.eval.sig !== this.signature(a)) await this.compute(a.id);
406
+ }
407
+ }
408
+
409
+ view(id) {
410
+ const a = this.store.get(id);
411
+ return a ? { id: a.id, name: a.name, eval: a.eval ?? null, markdown: a.eval?.markdown ?? null } : null;
412
+ }
413
+
414
+ /** Send the gaps to the agent. */
415
+ closeGaps(ref) {
416
+ const agent = this.manager.mustGet(ref);
417
+ if (!agent.eval?.items) throw err(409, 'Work the Eval out first');
418
+ if (!agent.eval.pending.length) throw err(409, 'Nothing is pending');
419
+ this.manager.tell(agent.id, gapsMessage(agent.eval), { source: 'eval' });
420
+ return { ok: true };
421
+ }
422
+
423
+ /** Agents done with their issue but not 100% sure, for Today. */
424
+ unsure() {
425
+ return this.store.list().filter((a) => a.eval?.items && a.eval.confidence < 100 && a.brief?.status === 'done' && !a.eval.rerun?.running && !(a.eval.seenAt && a.eval.seenConfidence === a.eval.confidence));
426
+ }
427
+
428
+ /** "Seen": off Today until its confidence changes (Undo: seen false). */
429
+ seen(ref, seen = true) {
430
+ const a = this.manager.mustGet(ref);
431
+ if (!a.eval) throw err(409, 'No Eval yet');
432
+ const ev = { ...a.eval };
433
+ if (seen) Object.assign(ev, { seenAt: now(), seenConfidence: ev.confidence });
434
+ else delete ev.seenAt;
435
+ this.manager.patch(a.id, { eval: ev });
436
+ return { ok: true };
437
+ }
438
+ }
package/src/issues.js CHANGED
@@ -159,6 +159,8 @@ export function issueRows(views, jira = new Map(), read = () => null, proposed =
159
159
  agent: { id: v.id, name: v.name, project: v.projectInfo?.name ?? null, running: Boolean(v.runtime?.running), busy: Boolean(v.runtime?.busy), from: v.startedBy ? 'assistant' : v.trigger?.source ?? null },
160
160
  pr: pr ? { url: pr.url, number: pr.number ?? null, title: pr.title ?? null, state: pr.state, checks: pr.checks?.state ?? null, review: pr.review ?? null } : null,
161
161
  aiReview: v.aiReview?.verdict ?? null,
162
+ // The Eval's confidence (eval.js), and what's pending.
163
+ eval: v.eval?.items || v.eval?.rerun?.running ? { items: v.eval.items ?? null, confidence: v.eval.confidence ?? null, pending: v.eval.pending ?? [], rerun: v.eval.rerun ? { running: Boolean(v.eval.rerun.running) } : null } : null,
162
164
  plan: planOf(v, read),
163
165
  design,
164
166
  updatedAt: v.activeAt ?? v.createdAt ?? null,
package/src/review.js CHANGED
@@ -181,6 +181,27 @@ export class Review {
181
181
  return { url: pr.url, edited: again };
182
182
  }
183
183
 
184
+ /** The Eval as a comment on the agent's open pull request (edited in place when posted before). */
185
+ async postEval(ref, markdown) {
186
+ const agent = this.agentWithRepo(ref);
187
+ if (!markdown) throw err(409, 'Work the Eval out first');
188
+ const pr = Object.values(agent.prs ?? {}).find((p) => p.state === 'OPEN');
189
+ if (!pr) throw err(409, 'No open pull request for this agent');
190
+ this.manager.plugins.check('agent.pr', { agent: this.manager.auditView(agent), title: 'eval comment', draft: false });
191
+ const opts = { cwd: agent.workdir, timeout: 60_000 };
192
+ const args = ['pr', 'comment', pr.url, '--body', markdown];
193
+ const again = agent.eval?.postedTo === pr.url;
194
+ try {
195
+ await git.run(ghBin(), again ? [...args, '--edit-last'] : args, opts);
196
+ } catch (e) {
197
+ if (!again) throw err(502, `Posting the Eval failed: ${e.message.replace(/^gh .*? failed: /, '')}`);
198
+ await git.run(ghBin(), args, opts);
199
+ }
200
+ const cur = this.manager.store.get(agent.id);
201
+ this.manager.patch(agent.id, { eval: { ...cur.eval, postedTo: pr.url, postedAt: new Date().toISOString() } });
202
+ return { url: pr.url, edited: again };
203
+ }
204
+
184
205
  /** Send the comments to the agent as one message (typed in when it is idle). */
185
206
  comment(ref, { comments = [], note = '' } = {}) {
186
207
  const agent = this.agentWithRepo(ref);
package/src/server.js CHANGED
@@ -55,6 +55,8 @@ import { Support } from './support.js';
55
55
  import { ghBin, leadingJiraKey } from './tracker.js';
56
56
  import { BugHunts } from './bughunt.js';
57
57
  import { ModuleBenchmarks } from './benchmarks.js';
58
+ import { Evals, readTail, stateHash } from './eval.js';
59
+ import { engineOf } from './engines/index.js';
58
60
  import * as git from './git.js';
59
61
 
60
62
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
@@ -131,13 +133,15 @@ export async function startServer({ port = PORT, host = HOST } = {}) {
131
133
  const keep = (d) => (out = (out + d).slice(-4000));
132
134
  child.stdout.on('data', keep);
133
135
  child.stderr.on('data', keep);
136
+ let timedOut = false;
134
137
  const timer = setTimeout(() => {
138
+ timedOut = true;
135
139
  try {
136
140
  process.kill(-child.pid, 'SIGKILL');
137
141
  } catch {}
138
142
  }, 15 * 60_000);
139
143
  child.on('error', (e) => (clearTimeout(timer), resolve({ passed: false, output: e.message })));
140
- child.on('close', (code) => (clearTimeout(timer), resolve({ passed: code === 0, output: out })));
144
+ child.on('close', (code) => (clearTimeout(timer), resolve({ passed: code === 0 && !timedOut, output: out, timedOut })));
141
145
  });
142
146
  const hunts = new BugHunts({ manager, store, judge: manager.judge, git: huntGit, log: (m) => console.log(`[agentmgr] ${m}`) });
143
147
  hunts.startTimer();
@@ -151,6 +155,23 @@ export async function startServer({ port = PORT, host = HOST } = {}) {
151
155
  },
152
156
  log: (m) => console.log(`[agentmgr] ${m}`),
153
157
  });
158
+ // Eval: the tests run, the checks done and what's pending for each Jira change, with a confidence.
159
+ const evals = new Evals({
160
+ manager,
161
+ store,
162
+ benches,
163
+ run: (a, command) => runCommand(a, command),
164
+ state: async (a) => {
165
+ const opts = { cwd: a.workdir, timeout: 30_000 };
166
+ const [head, status, diff] = await Promise.all([git.run('git', ['rev-parse', 'HEAD'], opts), git.run('git', ['status', '--porcelain'], opts), git.run('git', ['diff', 'HEAD'], opts)]);
167
+ return stateHash(head.trim(), status, diff);
168
+ },
169
+ changes: (a) => review.get(a.id),
170
+ // Claude Code's session: the test runs in it. Other engines keep theirs differently.
171
+ transcript: (a) => (engineOf(a).id === 'claude' && a.workdir ? readTail(engineOf(a).sessionFile(a.workdir, a.sessionId)) : null),
172
+ log: (m) => console.log(`[agentmgr] ${m}`),
173
+ });
174
+ evals.startTimer();
154
175
  const races = new Races({ manager, store });
155
176
  const review = new Review({ manager });
156
177
  // The walkthrough explains the same diff the review screen shows.
@@ -876,6 +897,18 @@ export async function startServer({ port = PORT, host = HOST } = {}) {
876
897
  api.delete('/benchmodules/:id', wrap((req) => benches.unwatch(req.params.id)));
877
898
  api.post('/benchruns/:id/accept', wrap((req) => benches.accept(req.params.id, req.body?.accepted !== false)));
878
899
  api.post('/benchruns/:id/fix', wrap((req) => benches.askToFix(req.params.id)));
900
+ api.get('/agents/:id/eval', wrap(async (req) => (manager.mustGet(req.params.id).eval ? evals.view(manager.mustGet(req.params.id).id) : evals.compute(manager.mustGet(req.params.id).id))));
901
+ api.post('/agents/:id/eval', wrap((req) => evals.compute(manager.mustGet(req.params.id).id)));
902
+ api.post('/agents/:id/eval/verify', wrap(async (req) => {
903
+ const a = manager.mustGet(req.params.id);
904
+ // Answered at once; the run's result comes with the agent's next update.
905
+ evals.verify(a.id).catch((e) => console.log(`[agentmgr] eval: ${e.message}`));
906
+ return { started: true };
907
+ }));
908
+ api.put('/agents/:id/eval/command', wrap((req) => evals.setTestCommand(req.params.id, req.body?.command)));
909
+ api.post('/agents/:id/eval/gaps', wrap((req) => evals.closeGaps(req.params.id)));
910
+ api.post('/agents/:id/eval/seen', wrap((req) => evals.seen(req.params.id, req.body?.seen !== false)));
911
+ api.post('/agents/:id/eval/post', wrap((req) => review.postEval(req.params.id, evals.view(manager.mustGet(req.params.id).id)?.markdown)));
879
912
  // Issues agents work on, for the summary; ?group=you|agent|done and ?format=markdown to paste.
880
913
  api.get('/issues', wrap(async (req) => {
881
914
  // ?fresh=1 (the ↻ button) asks Jira again: the issues assigned to you and each issue's status.
@@ -992,7 +1025,7 @@ export async function startServer({ port = PORT, host = HOST } = {}) {
992
1025
  got('reviews', () => reviews.rows()),
993
1026
  ]);
994
1027
  const findings = hunts.list().findings.filter((x) => x.status === 'open' || x.status === 'pr');
995
- const items = todayItems({ inbox, issues, actions, reviews: prs, findings, slower: benches.slower() });
1028
+ const items = todayItems({ inbox, issues, actions, reviews: prs, findings, slower: benches.slower(), unsure: evals.unsure().map((a) => ({ id: a.id, name: a.name, issue: manager.issueKey(a), confidence: a.eval.confidence, pending: a.eval.pending, at: a.eval.at })) });
996
1029
  return { items, aside: todayAside({ issues, actions }), speech: todaySpeech(items), features: f, errors };
997
1030
  }));
998
1031
  // Support tickets: kept on this computer, each with a filled-in link to a new GitHub issue.
@@ -1436,6 +1469,7 @@ export async function startServer({ port = PORT, host = HOST } = {}) {
1436
1469
  reviews.close();
1437
1470
  hunts.close();
1438
1471
  benches.close();
1472
+ evals.close();
1439
1473
  autopilot.close();
1440
1474
  goals.close();
1441
1475
  worklog.close();
package/src/today.js CHANGED
@@ -59,7 +59,7 @@ const INBOX = {
59
59
  * The list: [{ id, kind, label, title, why, score, at, agentId?, url?, actionId?, issueKey?, reviewUrl? }],
60
60
  * most pressing first. Each source may be missing (turned off, or it couldn't be had).
61
61
  */
62
- export function todayItems({ inbox = [], issues = [], actions = [], reviews = [], findings = [], slower = [], now = new Date() } = {}) {
62
+ export function todayItems({ inbox = [], issues = [], actions = [], reviews = [], findings = [], slower = [], unsure = [], now = new Date() } = {}) {
63
63
  const items = [];
64
64
  // The issue each agent works on: named on its questions, and not listed twice.
65
65
  const issueOfAgent = new Map(issues.filter((r) => r.agent?.id).map((r) => [r.agent.id, r]));
@@ -120,6 +120,11 @@ export function todayItems({ inbox = [], issues = [], actions = [], reviews = []
120
120
  const failed = f.auto?.state === 'failed' ? ` · the automatic fix didn't hold up: ${f.auto.reason}` : '';
121
121
  items.push({ id: `bug:${f.id}`, kind: 'bug', label: 'Bug', title: f.title, why: `${f.severity === 'critical' ? 'Critical' : 'High'}: found by the ${f.hunt ?? 'bug'} hunt${f.file ? ` in ${f.file}${f.line ? `:${f.line}` : ''}` : ''}${f.evidence?.type === 'test' ? ' · a test fails' : ''}${failed}`, score: f.severity === 'critical' ? 28 : 38, at: f.at ?? null, findingId: f.id });
122
122
  }
123
+ // Done, by its agent's account, but the Eval isn't sure: what's still missing.
124
+ for (const u of unsure) {
125
+ const title = `${u.issue ? `${u.issue}: ` : ''}${u.confidence}% confident`;
126
+ items.push({ id: `eval:${u.id}`, kind: 'eval', label: 'Eval', title, why: u.pending.slice(0, 3).join(' · ') + (u.pending.length > 3 ? ` · and ${u.pending.length - 3} more` : ''), score: u.confidence < 60 ? 26 : 35, at: u.at ?? null, agentId: u.id, issueKey: u.issue ?? null });
127
+ }
123
128
  // An issue's change made a module slower in its micro benchmarks (benchmarks.js).
124
129
  for (const r of slower) {
125
130
  const worst = r.cases.filter((c) => c.change !== null).sort((a, b) => b.change - a.change)[0];