ai-agentmanager 1.32.0 → 1.34.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,20 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.34.0 (2026-11-08)
4
+
5
+ - **Merge on the Eval.** A pull request is *sure to merge* when its agent's Eval is 100%, the app's own test run passed on the very commit the pull request is at with nothing left uncommitted, a reviewer approved it, and GitHub has it ready. The Land tab lists these first, marked **Sure to merge** with the Eval's percentage; a ready pull request that isn't sure says why (for example "The tests ran on a different commit than the pull request is at"). Turn on **Merge on the Eval** in the Land tab's settings and these merge on their own: each commit is tried once, your policies and branch protection still apply, and a merge that fails says why on the pull request's row. Off by default; the approval requirement can be turned off.
6
+
7
+ ## 1.33.0 (2026-11-08)
8
+
9
+ - **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:
10
+ - the tests the agent actually ran in its session and their results;
11
+ - the app's own test run;
12
+ - each acceptance criterion and what proves it;
13
+ - CI on the pull request and the AI judge's review;
14
+ - the brief's checks and the micro benchmarks;
15
+ - what is still pending.
16
+ 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).
17
+
3
18
  ## 1.32.0 (2026-11-08)
4
19
 
5
20
  - **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.34.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/land.js CHANGED
@@ -1,7 +1,10 @@
1
1
  // Land tab: every agent's open pull request, grouped by what it needs to get merged, with
2
- // Review, Update, Ask to fix and Merge. Settings for sending failures back to agents at the bottom.
2
+ // Review, Update, Ask to fix and Merge. Ones whose Eval is 100% on their latest commit come first.
3
+ // Settings for sending failures back to agents, and for merging on the Eval, at the bottom.
3
4
 
4
5
  import { listenHtml } from './speak.js';
6
+ import { evalChip } from './eval.js';
7
+ import { sureToMerge } from './sure.js';
5
8
  const SHORT = { ready: 'ready', fix: 'to fix', behind: 'behind', waiting: 'waiting', draft: 'draft' };
6
9
  const GROUPS = [
7
10
  ['ready', 'Ready to merge'],
@@ -35,10 +38,10 @@ export function initLand({ api, esc, toast, agents, $, scoreBadge = () => '', se
35
38
  for (const a of agents.values()) {
36
39
  for (const pr of a.prs ?? []) {
37
40
  if (pr.state !== 'OPEN' || pr.source === 'mentioned') continue;
38
- out.push({ a, pr, land: pr.land ?? 'waiting' });
41
+ out.push({ a, pr, land: pr.land ?? 'waiting', sure: sureToMerge(a, pr, { needApproval: settings?.sureNeedsApproval ?? true }) });
39
42
  }
40
43
  }
41
- return out.sort((x, y) => (x.a.priority ?? 2) - (y.a.priority ?? 2));
44
+ return out.sort((x, y) => Number(y.sure.sure) - Number(x.sure.sure) || (x.a.priority ?? 2) - (y.a.priority ?? 2));
42
45
  };
43
46
 
44
47
  // Review comments sent to the agent so far, and when last.
@@ -47,13 +50,21 @@ export function initLand({ api, esc, toast, agents, $, scoreBadge = () => '', se
47
50
  return ` <span class="hint" title="Last sent ${esc(new Date(c.lastAt).toLocaleString())}">${c.count} review comment${c.count === 1 ? '' : 's'} sent</span>`;
48
51
  }
49
52
 
50
- function rowHtml({ a, pr, land }) {
53
+ // Why a ready pull request isn't sure, or why merging it on its own didn't work.
54
+ function sureHint(a, pr, land, sure) {
55
+ const tried = a.landing?.sure?.[`${pr.url}@${pr.head}`];
56
+ if (tried?.error) return ` <span class="hint fail" title="${esc(tried.error)}">Couldn't merge on its own</span>`;
57
+ if (land === 'ready' && !sure.sure && a.eval?.items) return ` <span class="hint" title="Why it isn't merged on its Eval">${esc(sure.why)}</span>`;
58
+ return '';
59
+ }
60
+
61
+ function rowHtml({ a, pr, land, sure }) {
51
62
  const canFix = land === 'fix' || land === 'behind';
52
63
  return `<li class="agent land-row" data-agent="${a.id}" data-url="${esc(pr.url)}">
53
64
  <div class="line1"><span class="prio p${a.priority ?? 2}">P${a.priority ?? 2}</span>
54
65
  <a class="name" href="${esc(pr.url)}" target="_blank" rel="noopener" title="${esc(pr.title ?? pr.url)}">#${esc(pr.number ?? '')} ${esc(pr.title ?? pr.url)}</a></div>
55
- <div class="line2"><button class="link" data-land="goto">${esc(a.name)}</button>${a.runtime?.busy ? ' <span class="hint">working</span>' : ''}${commentsHint(a.landing?.comments?.[pr.url])}</div>
56
- <div class="land-chips">${scoreBadge(a.docs?.scorecard, esc)} ${prChips(pr, esc)}</div>
66
+ <div class="line2"><button class="link" data-land="goto">${esc(a.name)}</button>${a.runtime?.busy ? ' <span class="hint">working</span>' : ''}${commentsHint(a.landing?.comments?.[pr.url])}${sureHint(a, pr, land, sure)}</div>
67
+ <div class="land-chips">${scoreBadge(a.docs?.scorecard, esc)} ${evalChip(a.eval, esc)} ${sure.sure ? `<span class="tag open" title="${esc(sure.why)}">Sure to merge</span>` : ''} ${prChips(pr, esc)}</div>
57
68
  <div class="bl-actions">
58
69
  <button class="small" data-land="review" title="Its diff, line comments for the agent, commit and push">Review</button>
59
70
  ${listenHtml(`prvoice:${a.id}`, { title: 'Explain the review aloud: the PR, its checks, the AI review, the riskiest changes and what is left', label: 'Explain' })}
@@ -91,6 +102,11 @@ export function initLand({ api, esc, toast, agents, $, scoreBadge = () => '', se
91
102
  <label>At most <input type="number" min="0" max="20" data-set="maxFixes" value="${s.maxFixes}"> times per pull request</label>
92
103
  <label>Merge with <select data-set="mergeMethod">${['squash', 'merge', 'rebase'].map((m) => `<option ${m === s.mergeMethod ? 'selected' : ''}>${m}</option>`).join('')}</select></label>
93
104
  <label class="check"><input type="checkbox" data-set="deleteBranch" ${s.deleteBranch ? 'checked' : ''}> Delete the branch on GitHub after merging</label>
105
+ </details>
106
+ <details class="land-settings"><summary>Merge on the Eval</summary>
107
+ <label class="check"><input type="checkbox" data-set="mergeWhenSure" ${s.mergeWhenSure ? 'checked' : ''}> Merge a pull request on its own when its Eval is 100%, the app's own test run passed on the commit the pull request is at, and GitHub has it ready</label>
108
+ <label class="check"><input type="checkbox" data-set="sureNeedsApproval" ${s.sureNeedsApproval ? 'checked' : ''}> Only once a reviewer has approved it</label>
109
+ <p class="hint">Each commit is tried once, and your policies and branch protection still apply. When this is off, these pull requests are only listed first, marked <b>Sure to merge</b>.</p>
94
110
  </details>` : ''}`;
95
111
  }
96
112
 
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/sure.js ADDED
@@ -0,0 +1,21 @@
1
+ // Sure to merge: a pull request whose agent's Eval backs it all the way. The daemon merges on it
2
+ // (when that is turned on) and the Land tab lists these first, so both use this one rule.
3
+
4
+ /**
5
+ * Whether a pull request can be merged on the strength of its agent's Eval: { sure, why }. Sure
6
+ * means 100%, with the tests run by the app on the very commit the PR is at and nothing left
7
+ * uncommitted, a reviewer's approval (unless that's turned off), and GitHub ready to merge it.
8
+ */
9
+ export function sureToMerge(agent, pr, { needApproval = true, land = pr?.land } = {}) {
10
+ const ev = agent?.eval;
11
+ const no = (why) => ({ sure: false, why });
12
+ if (!ev?.items) return no('No Eval yet');
13
+ if (ev.rerun?.running) return no('Its tests are running');
14
+ if (ev.confidence !== 100) return no(`The Eval is ${ev.confidence}%`);
15
+ if (!ev.rerun?.passed) return no("The app's own test run didn't pass");
16
+ if (!pr?.head || ev.rerun.head !== pr.head) return no('The tests ran on a different commit than the pull request is at');
17
+ if (ev.rerun.clean === false) return no('There were uncommitted changes when the tests ran');
18
+ if (needApproval && pr.review !== 'APPROVED') return no('No reviewer has approved it');
19
+ if (land !== 'ready') return no(`GitHub doesn't have it ready to merge (${land ?? 'unknown'})`);
20
+ return { sure: true, why: needApproval ? '100% on its latest commit, approved and ready' : '100% on its latest commit and ready' };
21
+ }
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,442 @@
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, commit = async () => null, changes = async () => ({ files: [] }), transcript, benches = null, log = () => {} }) {
268
+ this.manager = manager;
269
+ this.store = store;
270
+ this.run = run;
271
+ this.state = state;
272
+ // The commit the tests ran on, and whether nothing was left uncommitted: merging relies on it.
273
+ this.commit = commit;
274
+ this.changes = changes;
275
+ this.transcript = transcript;
276
+ this.benches = benches;
277
+ this.log = log;
278
+ this.running = new Set();
279
+ this.onFinished = (agent) => {
280
+ if (agent && this.eligible(agent)) this.verify(agent.id).catch((e) => this.log(`eval: ${e.message}`));
281
+ };
282
+ manager.on('finished', this.onFinished);
283
+ this.timer = null;
284
+ }
285
+
286
+ close() {
287
+ this.manager.off('finished', this.onFinished);
288
+ clearInterval(this.timer);
289
+ }
290
+
291
+ /** Every minute: work out again the Evals whose inputs changed (a review, the scorecard, CI). */
292
+ startTimer(ms = 60_000) {
293
+ this.timer = setInterval(() => this.refreshAll().catch((e) => this.log(`eval: ${e.message}`)), ms);
294
+ this.timer.unref?.();
295
+ }
296
+
297
+ /** Task agents on a Jira issue (not hunters, reviewers, fixers or team members). */
298
+ eligible(agent) {
299
+ return Boolean(agent && agent.kind === 'task' && agent.workdir && !agent.hunting && !agent.reviewing && !agent.fixing && !agent.team && !agent.builds && this.manager.issueKey(agent));
300
+ }
301
+
302
+ /** The project's test command: set for the project, else found in its files, else the agent's usual one. */
303
+ testCommand(agent, runs = []) {
304
+ const p = this.manager.projectInfo(agent);
305
+ const set = Object.values(this.store.data.projects ?? {}).find((x) => x.key === p?.key)?.testCommand;
306
+ if (set) return set;
307
+ const dir = agent.workdir;
308
+ 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;
309
+ return found ?? usualCommand(runs);
310
+ }
311
+
312
+ /** Set the test command for an agent's project (empty: back to finding it). */
313
+ setTestCommand(ref, command) {
314
+ const agent = this.manager.mustGet(ref);
315
+ const p = this.manager.projectInfo(agent);
316
+ const entry = Object.values(this.store.data.projects ?? {}).find((x) => x.key === p?.key);
317
+ if (!entry) throw err(409, "This agent's project isn't registered");
318
+ const c = String(command ?? '').trim().slice(0, 300);
319
+ if (c) entry.testCommand = c;
320
+ else delete entry.testCommand;
321
+ this.store.save();
322
+ return { testCommand: this.testCommand(agent) };
323
+ }
324
+
325
+ /** Run the tests on the agent's change as it is now, then work the Eval out. */
326
+ async verify(ref) {
327
+ const agent = this.manager.mustGet(ref);
328
+ if (!agent.workdir || !fs.existsSync(agent.workdir)) throw err(409, 'The agent has no folder to run the tests in');
329
+ if (this.running.has(agent.id)) return this.view(agent.id);
330
+ const runs = this.runsOf(agent);
331
+ const command = this.testCommand(agent, runs ?? []);
332
+ if (!command) return this.compute(agent.id);
333
+ this.running.add(agent.id);
334
+ this.manager.patch(agent.id, { eval: { ...(agent.eval ?? {}), rerun: { command, running: true, at: now() } } });
335
+ let rerun = null;
336
+ try {
337
+ const started = Date.now();
338
+ const st = await this.state(agent).catch(() => null);
339
+ const at = await this.commit(agent).catch(() => null);
340
+ const res = await this.run(agent, command);
341
+ 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, head: at?.head ?? null, clean: at?.clean ?? null, at: now(), ms: Date.now() - started };
342
+ } catch (e) {
343
+ rerun = { command, passed: false, counts: null, tail: clip(String(e?.message ?? e), 2000), timedOut: false, state: null, at: now(), ms: 0 };
344
+ } finally {
345
+ this.running.delete(agent.id);
346
+ }
347
+ // The run and what it means are kept together, so no one sees one without the other.
348
+ return this.compute(agent.id, rerun);
349
+ }
350
+
351
+ runsOf(agent) {
352
+ const text = this.transcript(agent);
353
+ return text === null ? null : testRuns(text);
354
+ }
355
+
356
+ /** Work the Eval out from what is known now (no test run), and keep it on the agent. */
357
+ async compute(id, rerun) {
358
+ const stored = this.store.get(id);
359
+ if (!stored) return null;
360
+ const agent = rerun ? { ...stored, eval: { ...(stored.eval ?? {}), rerun } } : stored;
361
+ const runs = this.runsOf(agent);
362
+ const ch = await this.changes(agent).catch(() => ({ files: [] }));
363
+ const TEST = /(^|\/)(tests?|__tests__|spec|specs)\/|[._-](test|spec)\.[a-z]+$|_test\.go$|Test\.java$/i;
364
+ const files = (ch?.files ?? []).map((f) => f.path ?? f);
365
+ const testFiles = files.filter((p) => TEST.test(p)).length;
366
+ const codeFiles = files.filter((p) => !TEST.test(p) && !/\.(md|txt|rst|adoc)$/i.test(p) && !/(^|\/)docs?\//i.test(p)).length;
367
+ const pr = Object.values(agent.prs ?? {}).find((p) => p.source !== 'mentioned' && p.state === 'OPEN') ?? Object.values(agent.prs ?? {}).find((p) => p.source !== 'mentioned');
368
+ const benchRuns = this.benches ? this.benches.runs.filter((r) => r.agentId === id) : [];
369
+ const benchMods = [...new Set([...(agent.benchModules ?? []), ...benchRuns.map((r) => r.module)])];
370
+ const ev = evaluate({
371
+ runs: runs ?? [],
372
+ readable: runs !== null,
373
+ rerun: agent.eval?.rerun ?? null,
374
+ state: await this.state(agent).catch(() => null),
375
+ scorecard: agent.docs?.scorecard?.data ?? null,
376
+ hasSpec: Boolean(readSpecDoc(id, 'spec')?.markdown?.trim()),
377
+ ci: pr?.checks?.state ?? null,
378
+ ciFailed: pr?.checks?.failed ?? [],
379
+ review: agent.aiReview ?? null,
380
+ judgeOn: this.manager.judge?.enabled !== false,
381
+ checks: agent.brief?.checks ?? [],
382
+ codeFiles,
383
+ testFiles,
384
+ bench: benchMods.length ? { modules: benchMods, runs: benchRuns } : null,
385
+ testCommand: this.testCommand(agent, runs ?? []),
386
+ });
387
+ ev.sig = this.signature(agent);
388
+ ev.markdown = evalMarkdown(ev, agent.name);
389
+ ev.testCommand = this.testCommand(agent, runs ?? []);
390
+ const cur = this.store.get(id);
391
+ if (!cur) return null;
392
+ // A test run ended while this was worked out: the one it ended with has the newer answer.
393
+ if (!rerun && (cur.eval?.rerun?.at ?? null) !== (agent.eval?.rerun?.at ?? null)) return this.view(id);
394
+ this.manager.patch(id, { eval: { ...ev, rerun: rerun ?? cur.eval?.rerun ?? null, postedTo: cur.eval?.postedTo ?? null } });
395
+ this.manager.emit?.('evaluated', this.store.get(id));
396
+ return this.view(id);
397
+ }
398
+
399
+ /** What the Eval was worked out from: when it changes, it's worked out again. */
400
+ signature(agent) {
401
+ const pr = Object.values(agent.prs ?? {}).map((p) => `${p.url}:${p.state}:${p.checks?.state ?? ''}`).join(',');
402
+ const bench = this.benches ? this.benches.runs.filter((r) => r.agentId === agent.id).map((r) => `${r.id}:${r.at}:${r.accepted ?? ''}`).join(',') : '';
403
+ return [agent.aiReview?.at, agent.aiReview?.pending, agent.docs?.scorecard?.at, agent.brief?.updatedAt, pr, bench, agent.eval?.rerun?.at].join('|');
404
+ }
405
+
406
+ async refreshAll() {
407
+ for (const a of this.store.list()) {
408
+ if (!a.eval || a.eval.rerun?.running || this.running.has(a.id)) continue;
409
+ if (a.eval.sig !== this.signature(a)) await this.compute(a.id);
410
+ }
411
+ }
412
+
413
+ view(id) {
414
+ const a = this.store.get(id);
415
+ return a ? { id: a.id, name: a.name, eval: a.eval ?? null, markdown: a.eval?.markdown ?? null } : null;
416
+ }
417
+
418
+ /** Send the gaps to the agent. */
419
+ closeGaps(ref) {
420
+ const agent = this.manager.mustGet(ref);
421
+ if (!agent.eval?.items) throw err(409, 'Work the Eval out first');
422
+ if (!agent.eval.pending.length) throw err(409, 'Nothing is pending');
423
+ this.manager.tell(agent.id, gapsMessage(agent.eval), { source: 'eval' });
424
+ return { ok: true };
425
+ }
426
+
427
+ /** Agents done with their issue but not 100% sure, for Today. */
428
+ unsure() {
429
+ 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));
430
+ }
431
+
432
+ /** "Seen": off Today until its confidence changes (Undo: seen false). */
433
+ seen(ref, seen = true) {
434
+ const a = this.manager.mustGet(ref);
435
+ if (!a.eval) throw err(409, 'No Eval yet');
436
+ const ev = { ...a.eval };
437
+ if (seen) Object.assign(ev, { seenAt: now(), seenConfidence: ev.confidence });
438
+ else delete ev.seenAt;
439
+ this.manager.patch(a.id, { eval: ev });
440
+ return { ok: true };
441
+ }
442
+ }
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/landing.js CHANGED
@@ -1,16 +1,18 @@
1
1
  // Landing: getting agents' pull requests merged. Failing checks and requested changes are sent
2
2
  // back to the agent that owns the PR (a few times per PR at most), new review comments are sent
3
3
  // to it for as long as the PR is open, a branch that fell behind is brought up to date with the
4
- // branch it targets, and ready PRs are merged with one click.
4
+ // branch it targets, and ready PRs are merged with one click. A PR whose Eval is 100% on its latest
5
+ // commit is "sure": listed first, and merged on its own when that is turned on.
5
6
  import os from 'node:os';
6
7
  import * as git from './git.js';
7
8
  import { NO_REPO } from './manager.js';
8
- import { AGENT_MARK, ghBin, newFeedback, prFeedback } from './tracker.js';
9
+ import { AGENT_MARK, ghBin, landState, newFeedback, prFeedback } from './tracker.js';
9
10
  import { triggerSettings } from './triggers.js';
10
11
  import { parseBaseRef } from './review.js';
12
+ import { sureToMerge as sureOf } from '../public/sure.js';
11
13
 
12
14
  export const MERGE_METHODS = ['squash', 'merge', 'rebase'];
13
- export const LANDING_DEFAULTS = { fixChecks: true, fixReviews: true, fixComments: true, maxFixes: 3, mergeMethod: 'squash', deleteBranch: true };
15
+ export const LANDING_DEFAULTS = { fixChecks: true, fixReviews: true, fixComments: true, maxFixes: 3, mergeMethod: 'squash', deleteBranch: true, mergeWhenSure: false, sureNeedsApproval: true };
14
16
  // Rounds of review comments sent per PR: a stop in case an agent's own replies keep coming back.
15
17
  const COMMENT_ROUNDS = 30;
16
18
  const QUOTE_MAX = 1500;
@@ -30,9 +32,12 @@ export function landingSettings(config = {}) {
30
32
  maxFixes: Number.isFinite(n) && n >= 0 ? Math.min(20, Math.floor(n)) : LANDING_DEFAULTS.maxFixes,
31
33
  mergeMethod: MERGE_METHODS.includes(c.mergeMethod) ? c.mergeMethod : LANDING_DEFAULTS.mergeMethod,
32
34
  deleteBranch: c.deleteBranch !== false,
35
+ mergeWhenSure: c.mergeWhenSure === true,
36
+ sureNeedsApproval: c.sureNeedsApproval !== false,
33
37
  };
34
38
  }
35
39
 
40
+
36
41
  export function checksMessage(pr) {
37
42
  const names = pr.checks?.failed?.length ? pr.checks.failed.join(', ') : 'some checks';
38
43
  return [
@@ -84,6 +89,9 @@ export function updateMessage(base) {
84
89
  return `Your branch is behind ${base}. Merge ${base} into it (git fetch, then git merge ${base}), resolve any conflicts keeping both sides' intent, run the tests, then commit and push.`;
85
90
  }
86
91
 
92
+ /** sureToMerge with where the pull request stands worked out here. */
93
+ export const sureToMerge = (agent, pr, opts = {}) => sureOf(agent, pr, { ...opts, land: landState(pr) });
94
+
87
95
  export class Landing {
88
96
  constructor({ manager, store, config = {}, log = (m) => console.log(`[agentmgr] ${m}`) }) {
89
97
  this.manager = manager;
@@ -92,6 +100,8 @@ export class Landing {
92
100
  this.log = log;
93
101
  this.onPrs = (agent) => this.react(agent).catch((e) => this.log(`landing: ${e.message}`));
94
102
  manager.on('prs', this.onPrs);
103
+ this.onEvaluated = (agent) => agent && this.mergeIfSure(agent).catch((e) => this.log(`landing: ${e.message}`));
104
+ manager.on('evaluated', this.onEvaluated);
95
105
  // Running agents' PRs are refreshed by the manager; closed agents with an open PR every few minutes.
96
106
  this.timer = setInterval(() => this.refreshClosed().catch(() => {}), (config.landingRefreshMin ?? 6) * 60_000);
97
107
  this.timer.unref?.();
@@ -100,6 +110,7 @@ export class Landing {
100
110
  close() {
101
111
  clearInterval(this.timer);
102
112
  this.manager.off('prs', this.onPrs);
113
+ this.manager.off('evaluated', this.onEvaluated);
103
114
  }
104
115
 
105
116
  get settings() {
@@ -109,8 +120,11 @@ export class Landing {
109
120
  update(patch = {}) {
110
121
  if (patch.mergeMethod !== undefined && !MERGE_METHODS.includes(patch.mergeMethod)) throw err(400, `mergeMethod must be one of ${MERGE_METHODS.join(', ')}`);
111
122
  if (patch.maxFixes !== undefined && !(Number(patch.maxFixes) >= 0)) throw err(400, 'maxFixes must be 0 or more');
123
+ const was = this.settings.mergeWhenSure;
112
124
  const next = landingSettings({ landing: { ...this.config.landing, ...patch } });
113
125
  this.config.landing = next;
126
+ // Just turned on: what is already sure merges now, not on its next change.
127
+ if (next.mergeWhenSure && !was) for (const a of this.store.list()) this.mergeIfSure(a).catch((e) => this.log(`landing: ${e.message}`));
114
128
  return next;
115
129
  }
116
130
 
@@ -147,6 +161,36 @@ export class Landing {
147
161
  else if (s.fixReviews && pr.review === 'CHANGES_REQUESTED' && !watched?.changesRequested) send('review', reviewMessage(pr));
148
162
  }
149
163
  if (sent) this.store.save();
164
+ await this.mergeIfSure(agent);
165
+ }
166
+
167
+ /**
168
+ * Merge the agent's pull requests that are sure to merge, when that is turned on. Tried once per
169
+ * commit: a failure (a policy, branch protection) is kept and shown, not retried until it changes.
170
+ */
171
+ async mergeIfSure(agent) {
172
+ const s = this.settings;
173
+ if (!s.mergeWhenSure || NO_REPO.has(agent.kind)) return;
174
+ for (const pr of this.openPrs(agent)) {
175
+ if (!sureToMerge(agent, pr, { needApproval: s.sureNeedsApproval }).sure) continue;
176
+ const cur = this.store.get(agent.id);
177
+ if (!cur) return;
178
+ const tried = ((cur.landing ??= { sent: {} }).sure ??= {});
179
+ const key = `${pr.url}@${pr.head}`;
180
+ if (tried[key]) continue;
181
+ tried[key] = { at: new Date().toISOString() };
182
+ this.store.save();
183
+ try {
184
+ await this.merge(agent.id, { url: pr.url });
185
+ tried[key].merged = true;
186
+ this.log(`landing: merged ${pr.url}: its Eval is 100% on its latest commit`);
187
+ } catch (e) {
188
+ tried[key].error = e.message;
189
+ this.log(`landing: couldn't merge ${pr.url} on its Eval: ${e.message}`);
190
+ }
191
+ // Through patch, so open screens show the merge or why it didn't happen.
192
+ if (this.store.get(agent.id)) this.manager.patch(agent.id, { landing: this.store.get(agent.id).landing });
193
+ }
150
194
  }
151
195
 
152
196
  /**
@@ -198,11 +242,13 @@ export class Landing {
198
242
  for (const pr of view.prs.filter((p) => p.state === 'OPEN' && p.source !== 'mentioned')) {
199
243
  const fixes = Object.keys(agent.landing?.sent ?? {}).filter((k) => k.startsWith(`${pr.url}#`)).length;
200
244
  const comments = agent.landing?.comments?.[pr.url]?.count ?? 0;
201
- rows.push({ agent: { id: agent.id, name: agent.name, priority: view.priority, busy: view.runtime.busy, running: view.runtime.running }, pr, land: pr.land ?? 'waiting', fixes, comments });
245
+ const sure = sureToMerge(agent, pr, { needApproval: this.settings.sureNeedsApproval });
246
+ const tried = agent.landing?.sure?.[`${pr.url}@${pr.head}`] ?? null;
247
+ rows.push({ agent: { id: agent.id, name: agent.name, priority: view.priority, busy: view.runtime.busy, running: view.runtime.running }, pr, land: pr.land ?? 'waiting', fixes, comments, confidence: agent.eval?.confidence ?? null, sure, tried });
202
248
  }
203
249
  }
204
250
  const rank = (r) => (LAND_ORDER.includes(r.land) ? LAND_ORDER.indexOf(r.land) : LAND_ORDER.length);
205
- return { settings: this.settings, rows: rows.sort((a, b) => rank(a) - rank(b) || a.agent.priority - b.agent.priority) };
251
+ return { settings: this.settings, rows: rows.sort((a, b) => rank(a) - rank(b) || Number(b.sure.sure) - Number(a.sure.sure) || a.agent.priority - b.agent.priority) };
206
252
  }
207
253
 
208
254
  agentPr(ref, url) {
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,28 @@ 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
+ commit: async (a) => {
170
+ const opts = { cwd: a.workdir, timeout: 30_000 };
171
+ const [head, status] = await Promise.all([git.run('git', ['rev-parse', 'HEAD'], opts), git.run('git', ['status', '--porcelain'], opts)]);
172
+ return { head: head.trim(), clean: !status.trim() };
173
+ },
174
+ changes: (a) => review.get(a.id),
175
+ // Claude Code's session: the test runs in it. Other engines keep theirs differently.
176
+ transcript: (a) => (engineOf(a).id === 'claude' && a.workdir ? readTail(engineOf(a).sessionFile(a.workdir, a.sessionId)) : null),
177
+ log: (m) => console.log(`[agentmgr] ${m}`),
178
+ });
179
+ evals.startTimer();
154
180
  const races = new Races({ manager, store });
155
181
  const review = new Review({ manager });
156
182
  // The walkthrough explains the same diff the review screen shows.
@@ -876,6 +902,18 @@ export async function startServer({ port = PORT, host = HOST } = {}) {
876
902
  api.delete('/benchmodules/:id', wrap((req) => benches.unwatch(req.params.id)));
877
903
  api.post('/benchruns/:id/accept', wrap((req) => benches.accept(req.params.id, req.body?.accepted !== false)));
878
904
  api.post('/benchruns/:id/fix', wrap((req) => benches.askToFix(req.params.id)));
905
+ 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))));
906
+ api.post('/agents/:id/eval', wrap((req) => evals.compute(manager.mustGet(req.params.id).id)));
907
+ api.post('/agents/:id/eval/verify', wrap(async (req) => {
908
+ const a = manager.mustGet(req.params.id);
909
+ // Answered at once; the run's result comes with the agent's next update.
910
+ evals.verify(a.id).catch((e) => console.log(`[agentmgr] eval: ${e.message}`));
911
+ return { started: true };
912
+ }));
913
+ api.put('/agents/:id/eval/command', wrap((req) => evals.setTestCommand(req.params.id, req.body?.command)));
914
+ api.post('/agents/:id/eval/gaps', wrap((req) => evals.closeGaps(req.params.id)));
915
+ api.post('/agents/:id/eval/seen', wrap((req) => evals.seen(req.params.id, req.body?.seen !== false)));
916
+ api.post('/agents/:id/eval/post', wrap((req) => review.postEval(req.params.id, evals.view(manager.mustGet(req.params.id).id)?.markdown)));
879
917
  // Issues agents work on, for the summary; ?group=you|agent|done and ?format=markdown to paste.
880
918
  api.get('/issues', wrap(async (req) => {
881
919
  // ?fresh=1 (the ↻ button) asks Jira again: the issues assigned to you and each issue's status.
@@ -992,7 +1030,7 @@ export async function startServer({ port = PORT, host = HOST } = {}) {
992
1030
  got('reviews', () => reviews.rows()),
993
1031
  ]);
994
1032
  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() });
1033
+ 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
1034
  return { items, aside: todayAside({ issues, actions }), speech: todaySpeech(items), features: f, errors };
997
1035
  }));
998
1036
  // Support tickets: kept on this computer, each with a filled-in link to a new GitHub issue.
@@ -1436,6 +1474,7 @@ export async function startServer({ port = PORT, host = HOST } = {}) {
1436
1474
  reviews.close();
1437
1475
  hunts.close();
1438
1476
  benches.close();
1477
+ evals.close();
1439
1478
  autopilot.close();
1440
1479
  goals.close();
1441
1480
  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];