ai-agentmanager 1.31.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/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/jira.js CHANGED
@@ -226,8 +226,8 @@ export async function issueSummary(issue, opts = {}) {
226
226
  }
227
227
 
228
228
  /**
229
- * The issue's summary and workflow status ({ summary, status, category }: category is Jira's
230
- * "new", "indeterminate" or "done"), or null when it can't be had.
229
+ * The issue's summary and workflow status ({ summary, status, category, components, labels }:
230
+ * category is Jira's "new", "indeterminate" or "done"), or null when it can't be had.
231
231
  */
232
232
  export async function issueFields({ key, site }, { jira = loadJira(), fetchImpl = fetch, timeoutMs = 6000, allow = null } = {}) {
233
233
  const host = (() => {
@@ -245,7 +245,7 @@ export async function issueFields({ key, site }, { jira = loadJira(), fetchImpl
245
245
  if (!allowed) return null;
246
246
  const headers = { accept: 'application/json' };
247
247
  if (configured) headers.authorization = authOf(jira);
248
- const q = `${encodeURIComponent(key)}?fields=summary,status,description`;
248
+ const q = `${encodeURIComponent(key)}?fields=summary,status,description,components,labels`;
249
249
  try {
250
250
  // Your site as saved: it may have a path (https://host/jira) that the link's origin leaves out.
251
251
  const res = await jiraGet(fetchImpl, configured ? jira.site : site, { path: `/rest/api/3/issue/${q}` }, configured ? { path: `/rest/api/2/issue/${q}` } : null, { headers, signal: AbortSignal.timeout(timeoutMs) });
@@ -258,7 +258,10 @@ export async function issueFields({ key, site }, { jira = loadJira(), fetchImpl
258
258
  const status = typeof f.status?.name === 'string' ? f.status.name.slice(0, 60) : null;
259
259
  if (!summary && !status) return null;
260
260
  const synopsis = synopsisOf(f.description);
261
- return { summary, status, category: typeof f.status?.statusCategory?.key === 'string' ? f.status.statusCategory.key : null, ...(synopsis ? { synopsis } : {}) };
261
+ // What part of the product it's in: the issue's components and labels.
262
+ const components = (Array.isArray(f.components) ? f.components : []).map((c) => c?.name).filter((n) => typeof n === 'string').map((n) => n.slice(0, 80));
263
+ const labels = (Array.isArray(f.labels) ? f.labels : []).filter((n) => typeof n === 'string').map((n) => n.slice(0, 80));
264
+ return { summary, status, category: typeof f.status?.statusCategory?.key === 'string' ? f.status.statusCategory.key : null, ...(synopsis ? { synopsis } : {}), ...(components.length ? { components } : {}), ...(labels.length ? { labels } : {}) };
262
265
  } catch (e) {
263
266
  if (configured) problem = { at: new Date().toISOString(), reason: reasonOf(jira.site, null, e) };
264
267
  return null;
package/src/manager.js CHANGED
@@ -107,8 +107,9 @@ import { spawn } from 'node:child_process';
107
107
  import * as git from './git.js';
108
108
  import { bugHeat, buildMap, touchedFiles } from './codemap.js';
109
109
  import { parseDiff } from '../public/review.js';
110
- import { assignedIssues, issueFields, issueSummary, jiraProblem, leadingIssue, loadJira, wordsAfterLink } from './jira.js';
111
- import { issueRows } from './issues.js';
110
+ import { assignedIssues, issueFields, jiraProblem, leadingIssue, loadJira, wordsAfterLink } from './jira.js';
111
+ import { issueOf, issueRows } from './issues.js';
112
+ import { askMessage, moduleBenchPrompt, resultsPath } from './benchmarks.js';
112
113
  import { designRows } from './designs.js';
113
114
  import { reviewPath, reviewerPrompt } from './reviews.js';
114
115
  import { findingsPath, fixPath, fixerPrompt, hunterPrompt } from './bughunt.js';
@@ -736,6 +737,9 @@ export class AgentManager extends EventEmitter {
736
737
  // and until then by the words after the link.
737
738
  const issue = leadingIssue(intent);
738
739
  if (issue) agent.synopsis = { text: wordsAfterLink(intent), source: 'request', key: issue.key };
740
+ // Modules where speed matters that the request names: benchmarked (benchmarks.js).
741
+ const named = this.benchModules?.forIssue(agent) ?? [];
742
+ if (named.length) agent.benchModules = named.map((m) => m.path);
739
743
  this.store.put(agent);
740
744
  this.registerProject(agent);
741
745
  this.changed(agent);
@@ -758,8 +762,14 @@ export class AgentManager extends EventEmitter {
758
762
  const agent = this.store.get(this.store.resolve(ref)?.id ?? ref);
759
763
  const issue = agent && leadingIssue(agent.intent);
760
764
  if (!issue) return null;
761
- const summary = await issueSummary(issue, this.jiraOptions ?? {});
765
+ const fields = await issueFields(issue, this.jiraOptions ?? {});
766
+ const summary = fields?.summary ?? null;
762
767
  const cur = this.store.get(agent.id);
768
+ // Its components and labels may name modules to benchmark.
769
+ if (cur && fields) {
770
+ const mods = this.benchModules?.forIssue(cur, { components: fields.components, labels: fields.labels }) ?? [];
771
+ if (mods.length) this.addBenchModules(cur.id, mods);
772
+ }
763
773
  if (!summary || !cur) return null;
764
774
  const bug = cur.bugs?.[issue.key];
765
775
  this.patch(cur.id, {
@@ -770,6 +780,40 @@ export class AgentManager extends EventEmitter {
770
780
  return summary;
771
781
  }
772
782
 
783
+ /** The Jira issue (or other tracker key) an agent works on, or null. */
784
+ issueKey(agent) {
785
+ return agent ? issueOf({ ...agent, bugs: Object.values(agent.bugs ?? {}) })?.key ?? null : null;
786
+ }
787
+
788
+ /**
789
+ * More modules for an agent to benchmark ([{ path, dir, existing }], benchmarks.js). A running
790
+ * agent is told now; one not started yet gets them with its instructions. `asked`: it said it was
791
+ * done without them.
792
+ */
793
+ addBenchModules(id, modules, { asked = false } = {}) {
794
+ const agent = this.store.get(id);
795
+ if (!agent) return null;
796
+ const have = new Set(agent.benchModules ?? []);
797
+ const fresh = modules.filter((m) => !have.has(m.path));
798
+ if (!fresh.length && !asked) return null;
799
+ this.patch(id, {
800
+ benchModules: [...have, ...fresh.map((m) => m.path)],
801
+ ...(asked ? { benchAsked: [...new Set([...(agent.benchAsked ?? []), ...modules.map((m) => m.path)])] } : {}),
802
+ });
803
+ for (const m of modules) fs.mkdirSync(m.dir, { recursive: true });
804
+ const { md, json } = this.benchFiles(id);
805
+ if (asked) this.tell(id, askMessage(md, json, modules), { source: 'benchmarks' });
806
+ else if (this.runtimes.get(id)?.pty && fresh.length) this.tell(id, `This issue is about ${fresh.map((m) => m.path || 'the repository').join(', ')}, where speed matters. ${moduleBenchPrompt(md, json, fresh)}`, { source: 'benchmarks' });
807
+ return this.view(this.store.get(id));
808
+ }
809
+
810
+ /** Where an agent writes its benchmark results: BENCHMARK.md and BENCH.json in its brief folder. */
811
+ benchFiles(id) {
812
+ fs.mkdirSync(briefDir(id), { recursive: true });
813
+ const dir = fs.realpathSync(briefDir(id));
814
+ return { md: path.join(dir, path.basename(benchPath(id))), json: path.join(dir, path.basename(resultsPath(id))) };
815
+ }
816
+
773
817
  /** INTENT.md for a task agent: the request as given and where it came from (see brief.js). */
774
818
  writeIntent(id) {
775
819
  const agent = this.store.get(id);
@@ -807,7 +851,7 @@ export class AgentManager extends EventEmitter {
807
851
  * The code map of a project (the one with the most going on, unless named). With `bugs`
808
852
  * ({ findings, hunts } of the bug hunts), it also has the bugs layer (codemap.js bugHeat).
809
853
  */
810
- async codeMap(projectKey, { bugs = null } = {}) {
854
+ async codeMap(projectKey, { bugs = null, speed = null } = {}) {
811
855
  const withCode = this.store.list().filter((a) => a.workdir && !NO_REPO.has(a.kind) && fs.existsSync(a.workdir));
812
856
  const groups = new Map();
813
857
  for (const a of withCode) {
@@ -834,6 +878,8 @@ export class AgentManager extends EventEmitter {
834
878
  return { id: a.id, name: a.name, busy: rt?.busy, attention: rt?.attention, changed: this.changeSets.get(a.id)?.files ?? {}, touched };
835
879
  });
836
880
  const out = { project: { key: g.key, name: g.name }, projects: list, map: buildMap({ files, agents }) };
881
+ // The Speed view: modules to benchmark and their issues' numbers (benchmarks.js).
882
+ if (speed) out.speed = speed.speed(g.key);
837
883
  if (bugs) {
838
884
  // Hunts and findings name the project by its shortcut.
839
885
  const mine = (shortcut) => this.resolveProject(shortcut)?.key === g.key;
@@ -1253,7 +1299,16 @@ export class AgentManager extends EventEmitter {
1253
1299
  const dir = fs.realpathSync(briefDir(agent.id));
1254
1300
  writableDir ??= dir;
1255
1301
  if (agent.demoPage) prompts.push(demoPagePrompt(path.join(dir, path.basename(demoPath(agent.id)))));
1256
- if (agent.benchmarks) prompts.push(benchmarksPrompt(path.join(dir, path.basename(benchPath(agent.id))), path.join(dir, 'bench')));
1302
+ if (agent.benchmarks && !agent.benchModules?.length) prompts.push(benchmarksPrompt(path.join(dir, path.basename(benchPath(agent.id))), path.join(dir, 'bench')));
1303
+ }
1304
+ // Modules where speed matters: their kept benchmarks, run before and after (benchmarks.js).
1305
+ const benchMods = task && !planning && agent.benchModules?.length && this.benchModules ? this.benchModules.forAgent(agent) : [];
1306
+ if (benchMods.length) {
1307
+ const { md, json } = this.benchFiles(agent.id);
1308
+ writableDir ??= path.dirname(md);
1309
+ for (const m of benchMods) fs.mkdirSync(m.dir, { recursive: true });
1310
+ writableDir = [writableDir, ...benchMods.map((m) => fs.realpathSync(m.dir))].flat();
1311
+ prompts.push(moduleBenchPrompt(md, json, benchMods));
1257
1312
  }
1258
1313
  if (agent.reviewing && task) {
1259
1314
  fs.mkdirSync(briefDir(agent.id), { recursive: true });
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);