ai-agentmanager 1.60.0 → 1.62.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/quality.js ADDED
@@ -0,0 +1,383 @@
1
+ // Quality: what happened to the agents' pull requests after they merged. For each one it looks,
2
+ // for some days after the merge, at what GitHub shows: whether it was reverted, whether a fix to
3
+ // the same files followed, and whether the checks failed on the commit it merged as; and, from
4
+ // before the merge, whether a reviewer asked for changes and how long it took. By day, week,
5
+ // month, quarter and year that gives the share of merged work that held up, next to how much was
6
+ // merged (value.js counts that). A follow-up fix is a guess from titles and files, so you can
7
+ // say a pull request was not a problem, or that it was one nothing here saw. No model is called.
8
+
9
+ import { PERIODS } from './value.js';
10
+ import { repoOf } from './landing.js';
11
+ import { ghBin } from './tracker.js';
12
+ import { run } from './git.js';
13
+
14
+ const HOUR = 3_600_000;
15
+ const DAY = 24 * HOUR;
16
+ // Like Value: a first run goes back about a quarter.
17
+ const BACKFILL_DAYS = 100;
18
+ const RECHECK_MS = 6 * HOUR;
19
+ const RETRY_MS = HOUR;
20
+ const PER_TICK = 3;
21
+
22
+ export const QUALITY_DEFAULTS = { enabled: true, watchDays: 14 };
23
+ export const VERDICTS = ['reverted', 'fixed', 'broke', 'problem', 'clean', 'watching', 'unchecked'];
24
+ const PROBLEMS = new Set(['reverted', 'fixed', 'broke', 'problem']);
25
+
26
+ const err = (status, message) => Object.assign(new Error(message), { status });
27
+ const clip = (s, n) => {
28
+ const t = String(s ?? '').replace(/\s+/g, ' ').trim();
29
+ return t.length > n ? `${t.slice(0, n - 1)}…` : t;
30
+ };
31
+
32
+ /** Settings from config.json's "quality", with defaults and sane bounds. */
33
+ export function qualitySettings(config = {}) {
34
+ const c = { ...QUALITY_DEFAULTS, ...config.quality };
35
+ const days = Number(c.watchDays);
36
+ return { enabled: c.enabled !== false, watchDays: Number.isFinite(days) ? Math.min(90, Math.max(1, Math.round(days))) : QUALITY_DEFAULTS.watchDays };
37
+ }
38
+
39
+ /** A title that says the change repairs something. */
40
+ export const looksLikeFix = (title) => /^\s*(fix|hotfix|bugfix|revert)\b|\b(fix(es|ed)?|hotfix|regression|broke[n]?|repair)\b/i.test(String(title ?? ''));
41
+
42
+ const mentions = (text, number) => new RegExp(`(^|[^\\w/])#${number}(?!\\d)|/pull/${number}(?!\\d)`).test(String(text ?? ''));
43
+
44
+ /**
45
+ * What followed a merged pull request, from the repository's later merged pull requests and the
46
+ * later commits on its base branch: { reverted, fixes }.
47
+ * reverted - a pull request titled Revert "…" that names this one, or a commit that says it
48
+ * reverts the commit this one merged as.
49
+ * fixes - pull requests merged within the watch days whose title says they fix something and
50
+ * that change a file this one changed, or name it. A guess: you can overrule it.
51
+ */
52
+ export function followUps(it, { later = [], commits = [] } = {}, s = QUALITY_DEFAULTS) {
53
+ const merged = Date.parse(it.mergedAt);
54
+ const until = merged + s.watchDays * DAY;
55
+ const files = new Set(it.facts?.files ?? []);
56
+ let reverted = null;
57
+ const fixes = [];
58
+ for (const p of later) {
59
+ const at = Date.parse(p.mergedAt);
60
+ if (p.url === it.url || !(at > merged)) continue;
61
+ const named = mentions(p.title, it.number) || mentions(p.body, it.number);
62
+ if (/^\s*revert\b/i.test(p.title ?? '') && (named || (it.title && String(p.title).includes(it.title)))) {
63
+ if (!reverted || at < Date.parse(reverted.at)) reverted = { number: p.number ?? null, title: clip(p.title, 160), url: p.url ?? null, at: new Date(at).toISOString() };
64
+ continue;
65
+ }
66
+ if (at > until || !looksLikeFix(p.title)) continue;
67
+ const shared = (p.files ?? []).map((f) => f.path ?? f).filter((f) => files.has(f));
68
+ if (!shared.length && !named) continue;
69
+ fixes.push({ number: p.number ?? null, title: clip(p.title, 160), url: p.url ?? null, at: new Date(at).toISOString(), shared: shared.slice(0, 5), named });
70
+ }
71
+ const sha = it.facts?.mergeCommit;
72
+ if (!reverted && sha) {
73
+ for (const c of commits) {
74
+ const at = Date.parse(c.at);
75
+ if (!(at > merged) || !String(c.message ?? '').includes(`This reverts commit ${sha}`)) continue;
76
+ if (!reverted || at < Date.parse(reverted.at)) reverted = { number: null, title: clip(String(c.message).split('\n')[0], 160), url: c.url ?? null, at: new Date(at).toISOString() };
77
+ }
78
+ }
79
+ fixes.sort((a, b) => a.at.localeCompare(b.at));
80
+ return { reverted, fixes: fixes.slice(0, 5) };
81
+ }
82
+
83
+ /** GitHub's check runs on a commit -> { state: passed|failed|running|none, failed: [names] }. */
84
+ export function commitChecks(runs) {
85
+ const list = Array.isArray(runs) ? runs : [];
86
+ // A cancelled run was replaced by a newer one, or stopped by a person: not a failure of the change.
87
+ const failed = list.filter((r) => ['failure', 'timed_out', 'startup_failure'].includes(r.conclusion)).map((r) => r.name ?? 'check');
88
+ const running = list.filter((r) => r.status && r.status !== 'completed').length;
89
+ return { state: !list.length ? 'none' : failed.length ? 'failed' : running ? 'running' : 'passed', failed: [...new Set(failed)].slice(0, 10) };
90
+ }
91
+
92
+ /** Where a merged pull request stands: one of VERDICTS. What you said wins. */
93
+ export function verdictOf(it, s = QUALITY_DEFAULTS, t = Date.now()) {
94
+ if (it.mark?.verdict === 'clean') return 'clean';
95
+ if (it.mark?.verdict === 'problem') return 'problem';
96
+ if (!it.after) return 'unchecked';
97
+ if (it.after.reverted) return 'reverted';
98
+ if (it.after.fixes?.length) return 'fixed';
99
+ if (it.after.checks?.state === 'failed') return 'broke';
100
+ return t < Date.parse(it.mergedAt) + s.watchDays * DAY ? 'watching' : 'clean';
101
+ }
102
+
103
+ const median = (list) => {
104
+ const a = list.filter(Number.isFinite).sort((x, y) => x - y);
105
+ if (!a.length) return null;
106
+ const m = a.length >> 1;
107
+ return a.length % 2 ? a[m] : (a[m - 1] + a[m]) / 2;
108
+ };
109
+ const round = (n, d = 0) => (Number.isFinite(n) ? Math.round(n * 10 ** d) / 10 ** d : null);
110
+
111
+ /** Totals for a set of merged pull requests. */
112
+ export function totals(items, s = QUALITY_DEFAULTS, t = Date.now()) {
113
+ const out = { prs: items.length, reverted: 0, fixed: 0, broke: 0, problem: 0, clean: 0, watching: 0, unchecked: 0, changesRequested: 0 };
114
+ for (const it of items) {
115
+ out[verdictOf(it, s, t)] += 1;
116
+ if ((it.facts?.changesRequested ?? 0) > 0) out.changesRequested += 1;
117
+ }
118
+ out.problems = out.reverted + out.fixed + out.broke + out.problem;
119
+ // Of the ones looked at: the share that held up, and the share that didn't.
120
+ out.checked = out.prs - out.unchecked;
121
+ out.held = out.clean + out.watching;
122
+ out.heldPct = out.checked ? round((out.held / out.checked) * 100) : null;
123
+ out.failurePct = out.checked ? round((out.problems / out.checked) * 100) : null;
124
+ const known = items.filter((it) => it.facts);
125
+ out.changesPct = known.length ? round((out.changesRequested / known.length) * 100) : null;
126
+ out.hoursToMerge = round(median(items.map((it) => (Date.parse(it.mergedAt) - Date.parse(it.openedAt)) / HOUR)), 1);
127
+ return out;
128
+ }
129
+
130
+ /** The last `count` periods of a kind, newest first, each with its totals and pull requests. */
131
+ export function aggregate(items, s = QUALITY_DEFAULTS, { period = 'week', count, t = Date.now() } = {}) {
132
+ const P = PERIODS[period];
133
+ if (!P) throw err(400, `period is one of ${Object.keys(PERIODS).join(', ')}`);
134
+ const out = [];
135
+ let start = P.start(t);
136
+ for (let i = 0; i < (count ?? P.count); i++) {
137
+ const end = P.next(start);
138
+ const from = start;
139
+ const inside = items.filter((it) => {
140
+ const at = Date.parse(it.mergedAt);
141
+ return at >= from && at < end;
142
+ });
143
+ out.push({ key: P.key(start), label: P.label(start), start: new Date(start).toISOString(), end: new Date(end).toISOString(), current: i === 0, totals: totals(inside, s, t), items: inside.map((it) => it.url) });
144
+ start = P.start(start - 1);
145
+ }
146
+ return out;
147
+ }
148
+
149
+ const VERDICT_TEXT = { reverted: 'reverted', fixed: 'fixed afterwards', broke: 'checks failed after the merge', problem: 'a problem (marked by me)', clean: 'held up', watching: 'no problem so far', unchecked: 'not looked at yet' };
150
+
151
+ /** A period's report as Markdown. */
152
+ export function qualityMarkdown(p, items, s = QUALITY_DEFAULTS, { who = '', prev = null, t = Date.now() } = {}) {
153
+ const x = p.totals;
154
+ const was = prev?.totals.checked ? ` (${prev.totals.heldPct}% the period before)` : '';
155
+ const lines = [
156
+ `# Quality of merged work: ${p.label}${who ? `, ${who}` : ''}`,
157
+ '',
158
+ `${x.prs} pull request${x.prs === 1 ? '' : 's'} from AI agents merged.`,
159
+ '',
160
+ `- **Held up**: ${x.heldPct == null ? 'n/a' : `${x.heldPct}%`}${was}: ${x.held} of ${x.checked} looked at${x.watching ? `, ${x.watching} still within the ${s.watchDays} days watched` : ''}`,
161
+ `- **Problems after the merge**: ${x.problems}: ${x.reverted} reverted, ${x.fixed} fixed afterwards, ${x.broke} with failed checks${x.problem ? `, ${x.problem} marked by me` : ''}`,
162
+ `- **Before the merge**: a reviewer asked for changes on ${x.changesRequested}${x.changesPct == null ? '' : ` (${x.changesPct}%)`}; ${x.hoursToMerge == null ? 'n/a' : `${x.hoursToMerge} hours`} from opened to merged (median)`,
163
+ '',
164
+ ];
165
+ const bad = items.filter((it) => PROBLEMS.has(verdictOf(it, s, t)));
166
+ if (bad.length) {
167
+ lines.push('## What did not hold up', '');
168
+ for (const it of bad.slice(0, 25)) {
169
+ const v = verdictOf(it, s, t);
170
+ const by = v === 'reverted' ? it.after?.reverted : v === 'fixed' ? it.after?.fixes?.[0] : null;
171
+ const why = v === 'broke' ? `: ${(it.after?.checks?.failed ?? []).join(', ')}` : by ? `: ${by.url ? `[${by.title}](${by.url})` : by.title}` : it.mark?.note ? `: ${it.mark.note}` : '';
172
+ lines.push(`- [#${it.number ?? '?'} ${clip(it.title, 100)}](${it.url}): ${VERDICT_TEXT[v]}${why}`);
173
+ }
174
+ lines.push('');
175
+ }
176
+ lines.push(`_From what GitHub shows for ${s.watchDays} days after each merge. "Fixed afterwards" is a later fix to the same files, which is a guess. Made with AI Agent Manager._`);
177
+ return lines.join('\n');
178
+ }
179
+
180
+ // ---------------------------------------------------------------- GitHub, through the gh CLI
181
+
182
+ /** owner/repo (and the host, when it isn't github.com) for gh api. */
183
+ const apiArgs = (repo) => {
184
+ const parts = String(repo).split('/');
185
+ return parts.length === 3 ? { host: ['--hostname', parts[0]], path: `repos/${parts[1]}/${parts[2]}` } : { host: [], path: `repos/${repo}` };
186
+ };
187
+ const day = (ms) => new Date(ms).toISOString().slice(0, 10);
188
+
189
+ /** What Quality asks GitHub, each returning plain data (swapped out in the tests). */
190
+ export const github = {
191
+ /** The facts of a merged pull request that don't change after the merge. */
192
+ async facts(url) {
193
+ const p = JSON.parse(await run(ghBin(), ['pr', 'view', url, '--json', 'number,title,mergeCommit,baseRefName,files,reviews,additions,deletions,createdAt,mergedAt'], { timeout: 30_000 }));
194
+ return {
195
+ mergeCommit: p.mergeCommit?.oid ?? null,
196
+ base: p.baseRefName ?? null,
197
+ files: (p.files ?? []).map((f) => f.path).filter(Boolean).slice(0, 300),
198
+ lines: (p.additions ?? 0) + (p.deletions ?? 0),
199
+ changesRequested: (p.reviews ?? []).filter((r) => r.state === 'CHANGES_REQUESTED').length,
200
+ reviews: (p.reviews ?? []).length,
201
+ };
202
+ },
203
+ /** Pull requests merged in a repository since a time. */
204
+ async mergedSince(repo, since) {
205
+ const out = await run(ghBin(), ['pr', 'list', '--repo', repo, '--state', 'merged', '--search', `merged:>=${day(since)}`, '--limit', '200', '--json', 'number,title,url,mergedAt,body,files'], { timeout: 60_000 });
206
+ return JSON.parse(out || '[]').map((p) => ({ number: p.number, title: p.title, url: p.url, mergedAt: p.mergedAt, body: clip(p.body, 2000), files: (p.files ?? []).map((f) => f.path).filter(Boolean) }));
207
+ },
208
+ /** Commits on a branch since a time, for reverts pushed without a pull request. */
209
+ async commitsSince(repo, base, since) {
210
+ const { host, path } = apiArgs(repo);
211
+ const out = await run(ghBin(), ['api', ...host, `${path}/commits?sha=${encodeURIComponent(base)}&since=${new Date(since).toISOString()}&per_page=100`], { timeout: 60_000 });
212
+ return JSON.parse(out || '[]').map((c) => ({ sha: c.sha, message: c.commit?.message ?? '', at: c.commit?.committer?.date ?? c.commit?.author?.date ?? null, url: c.html_url ?? null }));
213
+ },
214
+ /** The check runs on a commit. */
215
+ async checkRuns(repo, sha) {
216
+ const { host, path } = apiArgs(repo);
217
+ const out = await run(ghBin(), ['api', ...host, `${path}/commits/${sha}/check-runs?per_page=100`], { timeout: 30_000 });
218
+ return (JSON.parse(out || '{}').check_runs ?? []).map((r) => ({ name: r.name, status: r.status, conclusion: r.conclusion }));
219
+ },
220
+ };
221
+
222
+ export class Quality {
223
+ constructor({ manager, store, config = {}, who = null, gh = github, onChange = () => {}, log = (m) => console.log(`[agentmgr] ${m}`) }) {
224
+ Object.assign(this, { manager, store, config, who, gh, onChange, log });
225
+ this.repoCache = new Map(); // repo -> { at, since, later, commits: Map(base -> list) }
226
+ this.busy = false;
227
+ this.timer = setInterval(() => this.tick().catch((e) => this.log(`quality: ${e.message}`)), 120_000);
228
+ this.timer.unref?.();
229
+ this.first = setTimeout(() => this.tick().catch((e) => this.log(`quality: ${e.message}`)), config.qualityFirstMs ?? 20_000);
230
+ this.first.unref?.();
231
+ }
232
+
233
+ close() {
234
+ clearInterval(this.timer);
235
+ clearTimeout(this.first);
236
+ }
237
+
238
+ get settings() {
239
+ return qualitySettings(this.config);
240
+ }
241
+
242
+ get state() {
243
+ return (this.store.data.quality ??= { items: {} });
244
+ }
245
+
246
+ /** Add the agents' newly merged pull requests; keep names current. */
247
+ scan(t = Date.now()) {
248
+ const st = this.state;
249
+ let added = 0;
250
+ for (const a of this.store.list()) {
251
+ if (a.kind !== 'task') continue;
252
+ for (const p of Object.values(a.prs ?? {})) {
253
+ if (p.source === 'mentioned' || p.state !== 'MERGED' || !p.url || !Number.isFinite(Date.parse(p.mergedAt))) continue;
254
+ const cur = st.items[p.url];
255
+ if (!cur && Date.parse(p.mergedAt) < t - BACKFILL_DAYS * DAY) continue;
256
+ const fields = {
257
+ url: p.url,
258
+ number: p.number ?? (Number(/\/pull\/(\d+)/.exec(p.url)?.[1]) || null),
259
+ title: clip(p.title ?? a.name, 160),
260
+ repo: repoOf(p.url),
261
+ agentId: a.id,
262
+ agentName: a.name,
263
+ project: this.manager.view(a).projectInfo?.name ?? null,
264
+ openedAt: p.openedAt ?? null,
265
+ mergedAt: new Date(p.mergedAt).toISOString(),
266
+ };
267
+ if (!cur) {
268
+ st.items[p.url] = { ...fields, facts: null, after: null, addedAt: new Date(t).toISOString() };
269
+ added++;
270
+ } else Object.assign(cur, fields);
271
+ }
272
+ }
273
+ if (added) this.store.save();
274
+ return added;
275
+ }
276
+
277
+ /** A repository's later pull requests and commits, asked once for all its watched pull requests. */
278
+ async repoAfter(repo, base, since, t) {
279
+ let c = this.repoCache.get(repo);
280
+ if (!c || t - c.at > 10 * 60_000 || c.since > since) {
281
+ c = { at: t, since, later: await this.gh.mergedSince(repo, since), commits: new Map() };
282
+ this.repoCache.set(repo, c);
283
+ }
284
+ if (base && !c.commits.has(base)) c.commits.set(base, await this.gh.commitsSince(repo, base, c.since).catch(() => []));
285
+ return { later: c.later, commits: (base && c.commits.get(base)) || [] };
286
+ }
287
+
288
+ /** Look at one pull request now: its facts once, then what followed it (`fresh`: ask GitHub again, not what was asked minutes ago). */
289
+ async check(url, { t = Date.now(), fresh = false } = {}) {
290
+ const it = this.state.items[url];
291
+ if (!it) throw err(404, 'No merged pull request with that link');
292
+ if (process.env.AGENTMGR_NO_GH) throw err(409, 'GitHub is not asked here (AGENTMGR_NO_GH is set)');
293
+ if (!it.repo) throw err(400, 'Not a GitHub pull request link');
294
+ const s = this.settings;
295
+ if (fresh) this.repoCache.delete(it.repo);
296
+ try {
297
+ it.facts ??= await this.gh.facts(url);
298
+ const merged = Date.parse(it.mergedAt);
299
+ // The oldest pull request of this repository still watched: one list serves them all.
300
+ const since = Math.min(merged, ...Object.values(this.state.items).filter((o) => o.repo === it.repo && !o.final).map((o) => Date.parse(o.mergedAt)));
301
+ const { later, commits } = await this.repoAfter(it.repo, it.facts.base, since, t);
302
+ const after = followUps(it, { later, commits }, s);
303
+ // Checks once they have all finished: they don't change after.
304
+ const had = it.after?.checks;
305
+ after.checks = had && had.state !== 'running' && had.state !== 'none' ? had : it.facts.mergeCommit ? commitChecks(await this.gh.checkRuns(it.repo, it.facts.mergeCommit).catch(() => [])) : { state: 'none', failed: [] };
306
+ it.after = after;
307
+ it.checkedAt = new Date(t).toISOString();
308
+ delete it.error;
309
+ // A revert can come any time, but nothing is looked for after the watch days.
310
+ it.final = t > merged + s.watchDays * DAY && after.checks.state !== 'running';
311
+ } catch (e) {
312
+ it.error = clip(e.message, 200);
313
+ it.triedAt = new Date(t).toISOString();
314
+ throw err(502, `GitHub: ${it.error}`);
315
+ } finally {
316
+ this.store.save();
317
+ this.onChange();
318
+ }
319
+ return this.itemView(it, t);
320
+ }
321
+
322
+ /** The pull requests due a look: never looked at first, then the ones not looked at for longest. */
323
+ due(t = Date.now()) {
324
+ return Object.values(this.state.items)
325
+ .filter((it) => it.repo && !it.final && !(it.error && t - Date.parse(it.triedAt) < RETRY_MS) && !(it.checkedAt && t - Date.parse(it.checkedAt) < RECHECK_MS))
326
+ .sort((a, b) => (a.checkedAt ?? '').localeCompare(b.checkedAt ?? '') || b.mergedAt.localeCompare(a.mergedAt));
327
+ }
328
+
329
+ /** What you say about a pull request: 'clean' (not a problem), 'problem', or null for what was found. */
330
+ mark(url, { verdict = null, note = '' } = {}) {
331
+ const it = this.state.items[url];
332
+ if (!it) throw err(404, 'No merged pull request with that link');
333
+ if (verdict !== null && verdict !== 'clean' && verdict !== 'problem') throw err(400, 'verdict is clean, problem or null');
334
+ if (verdict === null) delete it.mark;
335
+ else it.mark = { verdict, note: clip(note, 300), at: new Date().toISOString() };
336
+ this.store.save();
337
+ this.onChange();
338
+ return this.itemView(it);
339
+ }
340
+
341
+ update(patch = {}) {
342
+ if (patch.watchDays !== undefined && !Number.isFinite(Number(patch.watchDays))) throw err(400, 'watchDays must be a number');
343
+ this.config.quality = qualitySettings({ quality: { ...this.config.quality, ...patch } });
344
+ // Longer watch days: look again at the ones that were done.
345
+ for (const it of Object.values(this.state.items)) if (it.final && Date.now() < Date.parse(it.mergedAt) + this.config.quality.watchDays * DAY) it.final = false;
346
+ this.onChange();
347
+ return this.config.quality;
348
+ }
349
+
350
+ itemView(it, t = Date.now()) {
351
+ return { ...it, verdict: verdictOf(it, this.settings, t), gone: !this.store.get(it.agentId) };
352
+ }
353
+
354
+ view({ period = 'week', t = Date.now() } = {}) {
355
+ this.scan(t);
356
+ const s = this.settings;
357
+ const all = Object.values(this.state.items).sort((a, b) => b.mergedAt.localeCompare(a.mergedAt));
358
+ return { settings: s, period, periods: aggregate(all, s, { period, t }), items: all.map((it) => this.itemView(it, t)), github: !process.env.AGENTMGR_NO_GH };
359
+ }
360
+
361
+ /** A period's report: the latest complete one of a kind, or the current one so far. */
362
+ async report(kind = 'week', { current = false, t = Date.now() } = {}) {
363
+ if (!PERIODS[kind]) throw err(400, `kind is one of ${Object.keys(PERIODS).join(', ')}`);
364
+ this.scan(t);
365
+ const s = this.settings;
366
+ const start = current ? PERIODS[kind].start(t) : PERIODS[kind].start(PERIODS[kind].start(t) - 1);
367
+ // Verdicts as of now, for the period that started then.
368
+ const [p, prev] = aggregate(Object.values(this.state.items), s, { period: kind, count: 2, t: start }).map((x) => ({ ...x, totals: totals(x.items.map((u) => this.state.items[u]), s, t) }));
369
+ return { period: p, markdown: qualityMarkdown(p, p.items.map((u) => this.state.items[u]), s, { who: (await this.who) ?? '', prev, t }) };
370
+ }
371
+
372
+ async tick(t = Date.now()) {
373
+ if (!this.settings.enabled || this.busy) return;
374
+ this.busy = true;
375
+ try {
376
+ if (this.scan(t)) this.onChange();
377
+ if (process.env.AGENTMGR_NO_GH) return;
378
+ for (const it of this.due(t).slice(0, PER_TICK)) await this.check(it.url, { t }).catch(() => {});
379
+ } finally {
380
+ this.busy = false;
381
+ }
382
+ }
383
+ }
package/src/scorecard.js CHANGED
@@ -16,7 +16,7 @@ const WEIGHTS = { intent: 25, spec: 20, tests: 20, safety: 15, scope: 10, plan:
16
16
  const TEST_FILE = /(^|\/)(tests?|__tests__|spec|specs)\/|[._-](test|spec)\.[a-z]+$|_test\.go$|Test\.java$/i;
17
17
 
18
18
  /** Facts the app knows without a model: CI, test files touched, the agent's checks, plan and spec progress. */
19
- export function facts({ files = [], prs = [], brief = null, plan = '', spec = '' }) {
19
+ export function facts({ files = [], prs = [], brief = null, plan = '', spec = '', standards = null }) {
20
20
  const paths = files.map((f) => f.path);
21
21
  const tests = paths.filter((p) => TEST_FILE.test(p));
22
22
  const code = paths.filter((p) => !TEST_FILE.test(p) && !/\.(md|txt|rst|adoc)$/i.test(p) && !/(^|\/)docs?\//i.test(p));
@@ -37,19 +37,24 @@ export function facts({ files = [], prs = [], brief = null, plan = '', spec = ''
37
37
  plan: steps.length ? { steps: steps.length, done: steps.filter((s) => s === 'x').length } : null,
38
38
  criteria: criteriaBlock.split('\n').filter((l) => /^\s*[-*\d]/.test(l) && /\w/.test(l)).length,
39
39
  hasSpec: Boolean(String(spec).trim()),
40
+ // The repository's standards (standards.js): high-risk files touched, and the bar the app ran.
41
+ risk: (standards?.risk ?? []).map((r) => r.path),
42
+ bar: standards?.bar ? { passed: standards.bar.results.filter((r) => r.ok).length, failed: standards.bar.results.filter((r) => !r.ok).map((r) => r.name) } : null,
40
43
  };
41
44
  }
42
45
 
43
- const factLines = (f) =>
46
+ export const factLines = (f) =>
44
47
  [
45
48
  `files changed: ${f.files} (+${f.added} -${f.removed}); code files: ${f.codeFiles}; test files: ${f.testFiles}`,
46
49
  `CI on the pull request: ${f.ci ?? 'no pull request or no checks yet'}${f.ciFailed.length ? ` (failing: ${f.ciFailed.join(', ')})` : ''}`,
47
50
  `the agent's own checks (from its brief): ${f.checks.passed} passed, ${f.checks.failed} failed, ${f.checks.pending} pending`,
48
51
  `plan: ${f.plan ? `${f.plan.done} of ${f.plan.steps} steps ticked` : 'no plan written'}`,
49
52
  `spec: ${f.hasSpec ? `${f.criteria} acceptance criteria` : 'no spec written'}`,
53
+ ...(f.bar ? [`the repository's quality bar, run by the app: ${f.bar.passed} passed, ${f.bar.failed.length} failed${f.bar.failed.length ? ` (${f.bar.failed.join(', ')})` : ''}`] : []),
54
+ ...(f.risk?.length ? [`files under paths the person marked high risk: ${f.risk.join(', ')}`] : []),
50
55
  ].join('\n');
51
56
 
52
- export function scorecardPrompt({ intent, status, digest, briefMarkdown, intentDoc, specDoc, planDoc, hunks, facts: f }) {
57
+ export function scorecardPrompt({ intent, status, digest, briefMarkdown, intentDoc, specDoc, planDoc, hunks, facts: f, lessons = [] }) {
53
58
  return [
54
59
  "You score an AI coding agent's changes for a reviewer who wants to approve with confidence and read as little as possible.",
55
60
  'Be skeptical: a claim without evidence in the diff, the tests or the checks counts as unverified. Base everything on the material below.',
@@ -58,7 +63,8 @@ export function scorecardPrompt({ intent, status, digest, briefMarkdown, intentD
58
63
  '{"summary": "<two sentences: what the change does and how sure you are>",',
59
64
  ' "scores": {"intent": {"score": 0-100, "why": "<one sentence>"}, "scope": {...}, "plan": {...}, "tests": {...}, "safety": {...}},',
60
65
  ' "criteria": [{"criterion": "<an acceptance criterion from the spec>", "status": "met|not_met|unverified", "evidence": "<where: file, test, check>"}],',
61
- ' "look": [{"id": "H3", "reason": "<why a person should read this hunk>"}]}',
66
+ ` "look": [{"id": "H3", "reason": "<why a person should read this hunk>"}]${lessons.length ? ',' : '}'}`,
67
+ ...(lessons.length ? [' "lessons": [{"id": "L1", "status": "followed|broken|not_applicable", "evidence": "<where in the diff>"}]}'] : []),
62
68
  '',
63
69
  'Scoring (100 is best; be calibrated, not generous):',
64
70
  '- intent: how fully the change does what INTENT asks. Missing parts of the ask pull it down hard.',
@@ -68,6 +74,7 @@ export function scorecardPrompt({ intent, status, digest, briefMarkdown, intentD
68
74
  '- safety: 100 when nothing risky is touched or risks are handled; lower for security, auth, data loss, migrations, concurrency, money, new dependencies or public API changes without care.',
69
75
  '- criteria: one entry per acceptance criterion in SPEC, in its order; leave the list empty if there is no spec.',
70
76
  '- look: at most 5 hunks a person must read (the risky, subtle or unverified ones), most important first. Not the obvious ones.',
77
+ ...(lessons.length ? ['- lessons: one entry per lesson in LESSONS. "broken" only when the diff shows the change going against it; "not_applicable" when the change has nothing to do with it.'] : []),
71
78
  '',
72
79
  '<facts_measured_by_the_app>',
73
80
  factLines(f),
@@ -81,6 +88,7 @@ export function scorecardPrompt({ intent, status, digest, briefMarkdown, intentD
81
88
  '<plan>',
82
89
  planDoc || '(no plan written)',
83
90
  '</plan>',
91
+ ...(lessons.length ? ['<lessons>', ...lessons.map((l, i) => `L${i + 1}: ${l.text}`), '</lessons>'] : []),
84
92
  '<agent_status>',
85
93
  status,
86
94
  '</agent_status>',
@@ -102,7 +110,7 @@ const clamp = (n) => Math.max(0, Math.min(100, Math.round(Number(n) || 0)));
102
110
  * The scorecard from the model's reply and the facts: scores capped by what was measured, the spec
103
111
  * score computed from the criteria, the overall weighted, and a recommendation by rule.
104
112
  */
105
- export function combine(reply, f, hunks) {
113
+ export function combine(reply, f, hunks, { lessons = [], bar = null } = {}) {
106
114
  const s = reply?.scores ?? {};
107
115
  const score = (k) => (s[k] && Number.isFinite(Number(s[k].score)) ? { score: clamp(s[k].score), why: String(s[k].why ?? '').slice(0, 300), notes: [] } : null);
108
116
  const out = { intent: score('intent'), scope: score('scope'), plan: score('plan'), tests: score('tests'), safety: score('safety'), spec: null };
@@ -116,6 +124,9 @@ export function combine(reply, f, hunks) {
116
124
  if (f.ci === 'failed') cap('tests', 30, `CI is failing${f.ciFailed.length ? ` (${f.ciFailed.join(', ')})` : ''}`);
117
125
  if (f.checks.failed) cap('tests', 40, `${f.checks.failed} of the agent's checks failed`);
118
126
  if (f.codeFiles && !f.testFiles && !f.checks.passed && f.ci !== 'passed') cap('tests', 45, 'code changed with no tests and no passing checks');
127
+ // The repository's quality bar, run by the app: a failed check is not verified, whatever else passed.
128
+ const barFailed = (bar?.results ?? []).filter((r) => !r.ok);
129
+ if (barFailed.length) cap('tests', 30, `the quality bar is not met (${barFailed.map((r) => r.name).join(', ')})`);
119
130
  // Plan: bounded by the steps ticked.
120
131
  if (f.plan && out.plan) cap('plan', Math.round(40 + (60 * f.plan.done) / f.plan.steps), `${f.plan.done} of ${f.plan.steps} plan steps ticked`);
121
132
  if (!f.plan && out.plan) out.plan.notes.push('no plan written');
@@ -140,11 +151,26 @@ export function combine(reply, f, hunks) {
140
151
  if (f.ci === 'failed') reasons.push('CI is failing');
141
152
  if (notMet.length) reasons.push(`${notMet.length} acceptance criteri${notMet.length === 1 ? 'on' : 'a'} not met`);
142
153
  if (out.intent && out.intent.score < 50) reasons.push('it does not do enough of what was asked');
143
- if (out.tests && out.tests.score < 40 && f.ci !== 'failed') reasons.push('it is barely verified');
154
+ if (barFailed.length) reasons.push(`the quality bar is not met: ${barFailed.map((r) => r.name).join(', ')}`);
155
+ // Lessons of the repository, as the model found them in the diff: one it says is broken holds the change.
156
+ const said = new Map((Array.isArray(reply?.lessons) ? reply.lessons : []).map((l) => [String(l?.id ?? '').trim().toUpperCase(), l]));
157
+ const checked = lessons.map((l, i) => {
158
+ const r = said.get(`L${i + 1}`);
159
+ return { id: l.id, text: l.text, status: ['followed', 'broken', 'not_applicable'].includes(r?.status) ? r.status : 'unverified', evidence: String(r?.evidence ?? '').slice(0, 300) };
160
+ });
161
+ const broken = checked.filter((l) => l.status === 'broken');
162
+ if (broken.length) reasons.push(`${broken.length} lesson${broken.length === 1 ? '' : 's'} of this repository not followed`);
163
+ if (out.tests && out.tests.score < 40 && f.ci !== 'failed' && !barFailed.length) reasons.push('it is barely verified');
144
164
  let recommendation;
145
165
  if (reasons.length) recommendation = 'not_ready';
146
166
  else if (overall != null && overall >= 80 && (out.tests?.score ?? 0) >= 70 && (out.safety?.score ?? 100) >= 70 && (out.spec?.score ?? 100) >= 70 && f.ci !== 'running') recommendation = 'ready';
147
167
  else recommendation = 'look';
168
+ // High-risk paths: never "ready" on a score alone; a person reads it.
169
+ if (f.risk?.length) {
170
+ if (recommendation === 'ready') recommendation = 'look';
171
+ const shown = f.risk.slice(0, 4).join(', ');
172
+ reasons.push(`touches high-risk paths (${shown}${f.risk.length > 4 ? `, and ${f.risk.length - 4} more` : ''})`);
173
+ }
148
174
  // Where to look, mapped back to hunks.
149
175
  const byId = new Map(hunks.map((h) => [h.id, h]));
150
176
  const look = (Array.isArray(reply?.look) ? reply.look : [])
@@ -152,7 +178,7 @@ export function combine(reply, f, hunks) {
152
178
  .filter((l) => l.h)
153
179
  .slice(0, 5)
154
180
  .map(({ h, reason }) => ({ file: h.file, head: h.head, reason }));
155
- return { summary: String(reply?.summary ?? '').slice(0, 600), overall, recommendation, reasons, scores: out, criteria, look, facts: f };
181
+ return { summary: String(reply?.summary ?? '').slice(0, 600), overall, recommendation, reasons, scores: out, criteria, look, lessons: checked, bar: bar ? { ok: !barFailed.length, results: bar.results.map((r) => ({ name: r.name, ok: r.ok, ...(r.command ? { command: r.command } : {}), tail: String(r.tail ?? '').slice(-600) })) } : null, facts: f };
156
182
  }
157
183
 
158
184
  export const RECOMMENDATION = { ready: 'Ready to approve', look: 'Look at these first', not_ready: 'Not ready' };
@@ -169,10 +195,14 @@ export function improveMessage(sc) {
169
195
  .map(([k, label]) => `- ${label} ${sc.scores[k].score}/100: ${[sc.scores[k].why, ...sc.scores[k].notes].filter(Boolean).join('; ')}`);
170
196
  const criteria = sc.criteria.filter((c) => c.status !== 'met').map((c) => `- ${c.status === 'not_met' ? 'Not met' : 'Not verified'}: ${c.criterion}${c.evidence ? ` (${c.evidence})` : ''}`);
171
197
  const look = sc.look.map((l) => `- ${l.file}: ${l.reason}`);
198
+ const bar = (sc.bar?.results ?? []).filter((r) => !r.ok).map((r) => `- ${r.name}${r.command ? ` (\`${r.command}\`)` : ''} failed${r.tail ? `:\n${r.tail.split('\n').slice(-12).map((l) => ` ${l}`).join('\n')}` : ''}`);
199
+ const lessons = (sc.lessons ?? []).filter((l) => l.status === 'broken').map((l) => `- ${l.text}${l.evidence ? ` (${l.evidence})` : ''}`);
172
200
  return [
173
201
  `Before this goes to review: the review scorecard rates your changes ${sc.overall ?? '?'}/100 (${RECOMMENDATION[sc.recommendation]}${sc.reasons.length ? `: ${sc.reasons.join('; ')}` : ''}). Improve them where they fall short.`,
174
202
  weak.length ? `Scores to raise:\n${weak.join('\n')}` : '',
175
203
  criteria.length ? `Acceptance criteria:\n${criteria.join('\n')}` : '',
204
+ bar.length ? `The repository's quality bar, run on your changes (run the same commands yourself until they pass):\n${bar.join('\n')}` : '',
205
+ lessons.length ? `Lessons of this repository your changes do not follow:\n${lessons.join('\n')}` : '',
176
206
  look.length ? `Where a reviewer would look first:\n${look.join('\n')}` : '',
177
207
  'Fix what these point at: add or fix tests and run them, meet the criteria, handle the risky spots. Stay within the task, and say in the brief what you left as it is and why. Update the brief when you are done; the changes are scored again then.',
178
208
  ]
@@ -202,11 +232,20 @@ export function scorecardMarkdown(sc, title = '') {
202
232
  out.push('', '**Acceptance criteria**', '');
203
233
  for (const c of sc.criteria) out.push(`- ${c.status === 'met' ? '✅' : c.status === 'not_met' ? '❌' : '❔'} ${c.criterion}${c.evidence ? ` (${c.evidence})` : ''}`);
204
234
  }
235
+ const f = sc.facts;
236
+ if (sc.bar) {
237
+ out.push('', '**Quality bar** (run by the app)', '');
238
+ for (const r of sc.bar.results) out.push(`- ${r.ok ? '✅' : '❌'} ${r.name}${r.command ? ` (\`${r.command}\`)` : ''}`);
239
+ }
240
+ if (sc.lessons?.length) {
241
+ out.push('', '**Lessons of this repository**', '');
242
+ for (const l of sc.lessons) out.push(`- ${l.status === 'followed' ? '✅' : l.status === 'broken' ? '❌' : l.status === 'not_applicable' ? '➖' : '❔'} ${l.text}${l.evidence ? ` (${l.evidence})` : ''}`);
243
+ }
244
+ if (f.risk?.length) out.push('', `**High-risk paths touched**: ${f.risk.map((p) => `\`${p}\``).join(', ')}`);
205
245
  if (sc.look.length) {
206
246
  out.push('', '**Where to look**', '');
207
247
  for (const l of sc.look) out.push(`- \`${l.file}\` \`${l.head.replace(/^(@@[^@]*@@).*/, '$1')}\`: ${l.reason}`);
208
248
  }
209
- const f = sc.facts;
210
249
  out.push('', `<sub>Measured: ${f.files} files (+${f.added} −${f.removed}), ${f.testFiles} test files, CI ${f.ci ?? 'n/a'}, checks ${f.checks.passed}✓ ${f.checks.failed}✗${f.plan ? `, plan ${f.plan.done}/${f.plan.steps}` : ''}. Scored by AI Agent Manager.</sub>`);
211
250
  return out.join('\n');
212
251
  }
package/src/server.js CHANGED
@@ -55,6 +55,8 @@ import { AgentkitReports } from './agentkit-reports.js';
55
55
  import { Builder } from './builder.js';
56
56
  import { Standup } from './standup.js';
57
57
  import { Value, valueSlack } from './value.js';
58
+ import { Quality } from './quality.js';
59
+ import { Standards } from './standards.js';
58
60
  import { News } from './news.js';
59
61
  import { System } from './system.js';
60
62
  import { Advisor } from './advisor.js';
@@ -122,6 +124,7 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
122
124
  // ACP agents (Gemini CLI, OpenCode, Goose, … and config's "acp") become engines.
123
125
  registerAcpEngines(config);
124
126
  const manager = new AgentManager({ store, config, plugins });
127
+ manager.setMaxListeners(40); // each feature below listens for changes
125
128
  const localModels = new LocalModels({ config, save: saveConfig });
126
129
  localModels.view().catch(() => {});
127
130
  const backlog = new Backlog({ manager, store, config });
@@ -276,7 +279,11 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
276
279
  const cur = store.get(id);
277
280
  if (!cur?.docs?.update?.markdown) return;
278
281
  manager.patch(id, { announce: { ...cur.announce, auto: { milestone, at: new Date().toISOString() }, sent: {}, dismissedAt: null } });
279
- notifier.send('announce', manager.get(id), `${milestone === 'done' ? 'is finished' : 'opened a pull request'}: an update for the people who asked is ready for you to send`);
282
+ // Its statements are checked against the work before you are told it is ready (claims.js).
283
+ if (config.claims?.auto !== false) await manager.summarize(id, 'claims').catch((e) => console.log(`[agentmgr] claims check for ${cur.name}: ${e.message.slice(0, 160)}`));
284
+ const checked = store.get(id)?.docs?.claims?.data?.texts.find((t) => t.key === 'update' && t.at === store.get(id).docs.update?.at && !t.error);
285
+ const doubt = checked ? checked.counts.contradicted + checked.counts.not_backed + checked.missing.length : 0;
286
+ notifier.send('announce', manager.get(id), `${milestone === 'done' ? 'is finished' : 'opened a pull request'}: an update for the people who asked is ready for you to send${doubt ? ` (${doubt} of its statements ${doubt === 1 ? 'is' : 'are'} not backed by the work: see Claims)` : ''}`);
280
287
  },
281
288
  });
282
289
  // Awake (awake.js): the computer kept from sleeping, always or while an agent works.
@@ -320,6 +327,11 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
320
327
  return r;
321
328
  },
322
329
  });
330
+ // Quality: what happened to the agents' pull requests after they merged (quality.js).
331
+ let pushQuality = () => {};
332
+ const quality = new Quality({ manager, store, config, who: me, onChange: () => pushQuality() });
333
+ // Standards per repository: lessons from what went wrong, high-risk paths, and the quality bar (standards.js).
334
+ const standards = new Standards({ manager, store, config, quality, onChange: () => pushQuality() });
323
335
  // AI News: the frontier labs' latest releases, summarized (news.js).
324
336
  let pushNews = () => {};
325
337
  const news = new News({
@@ -616,6 +628,14 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
616
628
  saveNotify({ announce: { webhookUrl: url || null } });
617
629
  return announceView();
618
630
  }));
631
+ // Claims check: whether an update written by itself is checked by itself too.
632
+ api.get('/claims/settings', wrap(() => ({ auto: config.claims?.auto !== false })));
633
+ api.put('/claims/settings', wrap((req) => {
634
+ if (typeof req.body?.auto !== 'boolean') throw fail(400, 'auto is true or false');
635
+ config.claims = { ...config.claims, auto: req.body.auto };
636
+ saveConfig({ claims: config.claims });
637
+ return { auto: config.claims.auto };
638
+ }));
619
639
  api.put('/agents/:id/announce', wrap((req) => manager.updateState(req.params.id, req.body ?? {})));
620
640
  api.post('/agents/:id/announce/publish', wrap((req) => manager.publishUpdate(req.params.id)));
621
641
  api.post('/agents/:id/announce/slack', wrap(async (req) => {
@@ -1258,6 +1278,28 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
1258
1278
  saveConfig({ value: next });
1259
1279
  return value.view({ period: String(req.query.period ?? 'week') });
1260
1280
  }));
1281
+ api.get('/quality', wrap((req) => quality.view({ period: String(req.query.period ?? 'week') })));
1282
+ api.put('/quality', wrap((req) => {
1283
+ saveConfig({ quality: quality.update(req.body ?? {}) });
1284
+ return quality.view({ period: String(req.query.period ?? 'week') });
1285
+ }));
1286
+ // A pull request is named by its link, so it travels in the body.
1287
+ api.post('/quality/mark', wrap((req) => quality.mark(String(req.body?.url ?? ''), { verdict: req.body?.verdict ?? null, note: req.body?.note ?? '' })));
1288
+ api.post('/quality/check', wrap((req) => quality.check(String(req.body?.url ?? ''), { fresh: true })));
1289
+ // Standards are the person's to set: an agent's own calls can read them, not change them.
1290
+ const yours = (req) => {
1291
+ if (req.headers['x-agentmgr-agent']) throw Object.assign(new Error('Standards are set by the person, not by an agent'), { status: 403 });
1292
+ return req.body ?? {};
1293
+ };
1294
+ api.get('/standards', wrap(() => standards.view()));
1295
+ api.put('/standards/repo', wrap((req) => standards.update(standards.find(String(yours(req).key ?? '')), { risk: req.body.risk, bar: req.body.bar })));
1296
+ api.post('/standards/lessons', wrap((req) => standards.addLesson(standards.find(String(yours(req).key ?? '')), req.body.text)));
1297
+ api.put('/standards/lessons/:id', wrap((req) => standards.setLesson(standards.find(String(yours(req).key ?? '')), req.params.id, { state: req.body.state, text: req.body.text })));
1298
+ api.delete('/standards/lessons/:id', wrap((req) => (yours(req), standards.removeLesson(standards.find(String(req.query.key ?? '')), req.params.id))));
1299
+ api.post('/standards/lessons/:id/draft', wrap((req) => standards.draft(standards.find(String(yours(req).key ?? '')), req.params.id)));
1300
+ api.get('/agents/:id/standards', wrap((req) => standards.assess(req.params.id)));
1301
+ api.post('/agents/:id/standards', wrap((req) => (yours(req), standards.assess(req.params.id, null, { fresh: true }))));
1302
+ api.get('/quality/report', wrap((req) => quality.report(String(req.query.kind ?? 'week'), { current: req.query.current === '1' })));
1261
1303
  api.patch('/value/items/:id', wrap((req) => value.edit(req.params.id, req.body ?? {})));
1262
1304
  api.post('/value/items/:id/estimate', wrap((req) => value.estimate(req.params.id).then((it) => value.itemView(it))));
1263
1305
  api.post('/value/items/:id/exclude', wrap((req) => value.exclude(req.params.id, req.body?.excluded !== false)));
@@ -1799,6 +1841,7 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
1799
1841
  pushScreen = (viewers) => broadcast({ t: 'screen', viewers });
1800
1842
  pushStandup = (latest) => broadcast({ t: 'standup', latest });
1801
1843
  pushValue = () => broadcast({ t: 'value' });
1844
+ pushQuality = () => broadcast({ t: 'quality' });
1802
1845
  pushNews = () => broadcast({ t: 'news' });
1803
1846
  pushPlan = () => broadcast({ t: 'plan' });
1804
1847
  pushAdvisor = () => broadcast({ t: 'advisor' });
@@ -1962,6 +2005,7 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
1962
2005
  landing.close();
1963
2006
  standup.close();
1964
2007
  value.close();
2008
+ quality.close();
1965
2009
  news.close();
1966
2010
  system.close();
1967
2011
  milestones.close();