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.
@@ -0,0 +1,572 @@
1
+ // Standards: what every change in a repository has to meet, set by you per repository.
2
+ // lessons - one line each, from what went wrong before (a revert, a fix afterwards, failed checks,
3
+ // a reviewer's change request: proposed from Quality, yours to word and accept). Every
4
+ // later agent in the repository is given them, and the scorecard checks each one.
5
+ // risk - paths that are high risk (auth, payments, migrations, public APIs). A change that
6
+ // touches one is never shipped or merged without you, is reviewed by another model,
7
+ // and can't be scored "ready".
8
+ // bar - checks the app runs itself on the agent's changes before they are scored: your
9
+ // commands (lint, types, tests, a dependency scan), tests changed along with the code,
10
+ // and no secrets in the diff. A failed one means "not ready", whatever the agent says.
11
+ import fs from 'node:fs';
12
+ import path from 'node:path';
13
+ import crypto from 'node:crypto';
14
+ import { spawn } from 'node:child_process';
15
+ import { NO_REPO, projectOf } from './manager.js';
16
+ import { memoryKey } from './memory.js';
17
+ import { run } from './git.js';
18
+ import { ghBin } from './tracker.js';
19
+
20
+ const err = (status, message) => Object.assign(new Error(message), { status });
21
+ const clip = (s, n) => String(s ?? '').replace(/\s+/g, ' ').trim().slice(0, n);
22
+ const now = () => new Date().toISOString();
23
+
24
+ export const MAX_LESSONS = 40; // accepted per repository: every agent reads them all
25
+ export const MAX_RULES = 50;
26
+ export const MAX_CHECKS = 12;
27
+ const TEST_FILE = /(^|\/)(tests?|__tests__|spec|specs)\/|[._-](test|spec)\.[a-z]+$|_test\.go$|Test\.java$/i;
28
+ const NOT_CODE = /\.(md|txt|rst|adoc|json|ya?ml|toml|lock|css|svg|png|jpe?g|gif)$|(^|\/)docs?\//i;
29
+
30
+ // ---------------------------------------------------------------- high-risk paths
31
+
32
+ /**
33
+ * A path pattern as a test. `*` stays inside a folder, `**` crosses folders, a pattern without a
34
+ * slash matches at any depth, and a folder matches everything under it.
35
+ */
36
+ export function pathMatcher(pattern) {
37
+ const p = String(pattern ?? '').trim().replace(/^\.?\/+/, '').replace(/\/+$/, '');
38
+ if (!p) return () => false;
39
+ const body = p
40
+ .split(/(\*\*\/|\*\*|\*|\?)/)
41
+ .map((tok) => (tok === '**/' ? '(?:.*/)?' : tok === '**' ? '.*' : tok === '*' ? '[^/]*' : tok === '?' ? '[^/]' : tok.replace(/[.+^${}()|[\]\\]/g, '\\$&')))
42
+ .join('');
43
+ const re = new RegExp(`^${p.includes('/') ? '' : '(?:.*/)?'}${body}(?:/.*)?$`);
44
+ return (file) => re.test(String(file));
45
+ }
46
+
47
+ /** The changed files under a high-risk path: [{ path, pattern, why }], each file once. */
48
+ export function riskOf(files = [], rules = []) {
49
+ const tests = rules.map((r) => ({ ...r, test: pathMatcher(r.pattern) }));
50
+ const out = [];
51
+ for (const f of files) {
52
+ const file = typeof f === 'string' ? f : f?.path;
53
+ const hit = file && tests.find((r) => r.test(file));
54
+ if (hit) out.push({ path: file, pattern: hit.pattern, why: hit.why ?? '' });
55
+ }
56
+ return out.slice(0, 100);
57
+ }
58
+
59
+ const riskRules = (list) => {
60
+ if (!Array.isArray(list)) throw err(400, 'risk is a list of { pattern, why }');
61
+ const out = [];
62
+ for (const r of list) {
63
+ const pattern = clip(typeof r === 'string' ? r : r?.pattern, 200);
64
+ if (!pattern || out.some((o) => o.pattern === pattern)) continue;
65
+ out.push({ pattern, why: clip(r?.why, 200) });
66
+ }
67
+ if (out.length > MAX_RULES) throw err(400, `At most ${MAX_RULES} high-risk paths per repository`);
68
+ return out;
69
+ };
70
+
71
+ // ---------------------------------------------------------------- the quality bar
72
+
73
+ const SECRETS = [
74
+ ['a private key', /-----BEGIN (?:[A-Z]+ )?PRIVATE KEY-----/],
75
+ ['an AWS access key', /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/],
76
+ ['a GitHub token', /\b(?:gh[pousr]_[A-Za-z0-9]{36,}|github_pat_[A-Za-z0-9_]{40,})\b/],
77
+ ['a Slack token', /\bxox[baprs]-[A-Za-z0-9-]{20,}/],
78
+ ['an Anthropic API key', /\bsk-ant-[A-Za-z0-9_-]{24,}/],
79
+ ['an OpenAI API key', /\bsk-(?:proj-)?[A-Za-z0-9_-]{40,}/],
80
+ ['a Google API key', /\bAIza[0-9A-Za-z_-]{35}\b/],
81
+ ['a Stripe live key', /\b[sr]k_live_[0-9a-zA-Z]{20,}/],
82
+ ];
83
+
84
+ /** What looks like a secret on the added lines of a diff: [{ file, line, kind }]. The text itself is never kept. */
85
+ export function findSecrets(diff = '') {
86
+ const out = [];
87
+ let file = null;
88
+ let line = 0;
89
+ for (const l of String(diff).split('\n')) {
90
+ if (l.startsWith('+++ ')) {
91
+ file = l.slice(4).replace(/^b\//, '').trim();
92
+ continue;
93
+ }
94
+ const hunk = /^@@ -\d+(?:,\d+)? \+(\d+)/.exec(l);
95
+ if (hunk) {
96
+ line = Number(hunk[1]) - 1;
97
+ continue;
98
+ }
99
+ if (l.startsWith('-')) continue;
100
+ line++;
101
+ if (!l.startsWith('+') || !file || file === '/dev/null') continue;
102
+ for (const [kind, re] of SECRETS) {
103
+ if (re.test(l)) {
104
+ out.push({ file, line, kind });
105
+ break;
106
+ }
107
+ }
108
+ if (out.length >= 20) break;
109
+ }
110
+ return out;
111
+ }
112
+
113
+ export const BAR_DEFAULTS = { tests: false, secrets: true, checks: [] };
114
+
115
+ export function barSettings(bar = {}) {
116
+ const list = bar.checks ?? [];
117
+ if (!Array.isArray(list)) throw err(400, 'checks is a list of { name, command }');
118
+ const checks = [];
119
+ for (const c of list) {
120
+ const command = String(c?.command ?? '').trim().slice(0, 500);
121
+ if (!command) continue;
122
+ const name = clip(c?.name, 60) || command.split(/\s+/).slice(0, 3).join(' ');
123
+ if (checks.some((o) => o.name === name)) throw err(400, `Two checks are named "${name}"`);
124
+ checks.push({ name, command });
125
+ }
126
+ if (checks.length > MAX_CHECKS) throw err(400, `At most ${MAX_CHECKS} checks per repository`);
127
+ return { tests: bar.tests === true, secrets: bar.secrets !== false, checks };
128
+ }
129
+
130
+ /** Checks a repository most likely has, from the files in a folder of it. */
131
+ export function suggestChecks(dir) {
132
+ const has = (f) => fs.existsSync(path.join(dir, f));
133
+ const out = [];
134
+ try {
135
+ if (has('package.json')) {
136
+ const scripts = JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8')).scripts ?? {};
137
+ const pm = has('pnpm-lock.yaml') ? 'pnpm' : has('yarn.lock') ? 'yarn' : 'npm';
138
+ for (const [name, script] of [['Lint', 'lint'], ['Types', 'typecheck'], ['Types', 'type-check'], ['Types', 'tsc'], ['Tests', 'test']]) {
139
+ if (scripts[script] && !out.some((o) => o.name === name)) out.push({ name, command: script === 'test' ? `${pm} test` : `${pm} run ${script}` });
140
+ }
141
+ if (has('package-lock.json')) out.push({ name: 'Dependencies', command: 'npm audit --audit-level=high' });
142
+ }
143
+ if (has('go.mod')) out.push({ name: 'Vet', command: 'go vet ./...' }, { name: 'Tests', command: 'go test ./...' });
144
+ if (has('Cargo.toml')) out.push({ name: 'Lint', command: 'cargo clippy -- -D warnings' }, { name: 'Tests', command: 'cargo test' });
145
+ if (has('pyproject.toml') || has('setup.py')) out.push({ name: 'Lint', command: 'ruff check .' }, { name: 'Tests', command: 'pytest -q' });
146
+ } catch {}
147
+ return out.filter((c, i) => out.findIndex((o) => o.name === c.name) === i);
148
+ }
149
+
150
+ /** Run one command in a folder: { ok, code, ms, tail } (the end of what it printed). */
151
+ export function runCheck(command, { cwd, timeoutMs = 600_000 } = {}) {
152
+ return new Promise((resolve) => {
153
+ const started = Date.now();
154
+ let out = '';
155
+ let timedOut = false;
156
+ const child = spawn('/bin/sh', ['-c', command], { cwd, env: { ...process.env, CI: '1', FORCE_COLOR: '0', NO_COLOR: '1' }, stdio: ['ignore', 'pipe', 'pipe'], detached: true });
157
+ const kill = () => {
158
+ try {
159
+ process.kill(-child.pid, 'SIGKILL');
160
+ } catch {
161
+ child.kill('SIGKILL');
162
+ }
163
+ };
164
+ const timer = setTimeout(() => {
165
+ timedOut = true;
166
+ kill();
167
+ }, timeoutMs);
168
+ const add = (d) => (out = (out + d).slice(-8000));
169
+ child.stdout.on('data', add);
170
+ child.stderr.on('data', add);
171
+ const done = (code, extra = '') => {
172
+ clearTimeout(timer);
173
+ const tail = (out.replace(/\x1b\[[0-9;]*[A-Za-z]/g, '').trim() + extra).slice(-1500);
174
+ resolve({ ok: code === 0 && !timedOut, code: timedOut ? null : code, ms: Date.now() - started, tail: timedOut ? `${tail}\n(stopped after ${Math.round(timeoutMs / 1000)} seconds)`.trim() : tail });
175
+ };
176
+ child.on('error', (e) => done(127, `\n${e.message}`));
177
+ child.on('close', (code) => done(code ?? 1));
178
+ });
179
+ }
180
+
181
+ /** The bar's own checks, from the changed files and the diff alone. */
182
+ export function builtInChecks(bar, { files = [], diff = '' } = {}) {
183
+ const out = [];
184
+ if (bar.tests) {
185
+ const paths = files.map((f) => f.path);
186
+ const code = paths.filter((p) => !TEST_FILE.test(p) && !NOT_CODE.test(p));
187
+ const tests = paths.filter((p) => TEST_FILE.test(p));
188
+ out.push({ name: 'Tests changed with the code', builtIn: 'tests', ok: !code.length || tests.length > 0, tail: !code.length ? 'No code files changed' : tests.length ? `${tests.length} test file${tests.length === 1 ? '' : 's'} changed` : `${code.length} code file${code.length === 1 ? '' : 's'} changed and no test file` });
189
+ }
190
+ if (bar.secrets) {
191
+ const found = findSecrets(diff);
192
+ out.push({ name: 'No secrets in the changes', builtIn: 'secrets', ok: !found.length, tail: found.length ? found.map((s) => `${s.file}:${s.line} looks like ${s.kind}`).join('\n') : 'Nothing that looks like a key or token on the added lines' });
193
+ }
194
+ return out;
195
+ }
196
+
197
+ // ---------------------------------------------------------------- lessons
198
+
199
+ const SOURCE_TEXT = {
200
+ reverted: 'was reverted',
201
+ fixed: 'needed a fix afterwards',
202
+ broke: 'failed its checks once merged',
203
+ problem: 'was a problem after it merged',
204
+ review: 'had changes requested by a reviewer',
205
+ };
206
+
207
+ /** One line, without Markdown that could break a list. */
208
+ export function cleanLesson(text) {
209
+ const t = String(text ?? '').replace(/\s+/g, ' ').replace(/^[-*#>\s]+/, '').trim();
210
+ if (!t) throw err(400, 'A lesson is one line of text');
211
+ if (t.length > 300) throw err(400, 'Keep a lesson to one short line (300 characters at most)');
212
+ return t;
213
+ }
214
+
215
+ /** What a merged pull request in Quality could teach: { kind, detail } or null. */
216
+ export function lessonSource(it) {
217
+ const a = it.after ?? {};
218
+ const name = (x) => clip(`${x?.number ? `#${x.number} ` : ''}${x?.title ?? ''}`, 140);
219
+ if (it.verdict === 'reverted') return { kind: 'reverted', detail: a.reverted ? `Reverted by ${name(a.reverted)}` : 'Reverted' };
220
+ if (it.verdict === 'fixed') return { kind: 'fixed', detail: `Fixed afterwards by ${(a.fixes ?? []).map(name).join('; ')}` };
221
+ if (it.verdict === 'broke') return { kind: 'broke', detail: `Checks failed on the commit it merged as: ${(a.checks?.failed ?? []).join(', ')}` };
222
+ if (it.verdict === 'problem') return { kind: 'problem', detail: it.mark?.note ? `You marked it a problem: ${it.mark.note}` : 'You marked it a problem' };
223
+ if (it.facts?.changesRequested && !it.mark) return { kind: 'review', detail: `A reviewer asked for changes before it merged (${it.facts.changesRequested})` };
224
+ return null;
225
+ }
226
+
227
+ export function lessonPrompt({ source, pr = null, repo = '' }) {
228
+ return [
229
+ 'Write one lesson for AI coding agents working in a repository, from something that went wrong with an earlier change there.',
230
+ 'Reply with the lesson alone: one imperative sentence of at most 200 characters, about how to work in this repository so it does not happen again.',
231
+ 'Make it specific to what went wrong and checkable in a later change (a reviewer must be able to say whether a change follows it). Not a general virtue like "test more carefully".',
232
+ 'If the material does not show what went wrong, reply with the single word UNKNOWN.',
233
+ '',
234
+ `<repository>${repo}</repository>`,
235
+ '<what_happened>',
236
+ `Pull request ${source.number ? `#${source.number} ` : ''}"${source.title}" ${SOURCE_TEXT[source.kind] ?? 'had a problem'}.`,
237
+ source.detail,
238
+ '</what_happened>',
239
+ pr ? `<pull_request>\n${pr}\n</pull_request>` : '',
240
+ ]
241
+ .filter((l) => l !== '')
242
+ .join('\n');
243
+ }
244
+
245
+ /** What an agent is told at its start: the lessons to follow and the paths to be careful in. */
246
+ export function standardsPrompt({ lessons = [], risk = [] } = {}) {
247
+ const out = [];
248
+ if (lessons.length) {
249
+ out.push(
250
+ `Lessons from earlier work in this repository, set by the person you work for. Follow each one; your changes are checked against them before review:\n${lessons.map((l) => `- ${l.text}`).join('\n')}`,
251
+ );
252
+ }
253
+ if (risk.length) {
254
+ out.push(
255
+ `High-risk parts of this repository, marked by the person you work for:\n${risk.map((r) => `- ${r.pattern}${r.why ? ` (${r.why})` : ''}`).join('\n')}\n` +
256
+ 'If your task needs a change there: before you edit, write in your brief (or the plan, if you have one) what you will change there, what could go wrong and how you will verify it. Keep the change there as small as the task allows, add or update tests for it, and name the files in your brief. Such a change is reviewed by another model and is not merged without the person. Do not touch these parts for anything the task does not need.',
257
+ );
258
+ }
259
+ return out.join('\n\n');
260
+ }
261
+
262
+ // ---------------------------------------------------------------- per repository, in the store
263
+
264
+ export class Standards {
265
+ constructor({ manager, store, config = {}, quality = null, onChange = () => {}, log = (m) => console.log(`[agentmgr] ${m}`) }) {
266
+ Object.assign(this, { manager, store, config, quality, onChange, log });
267
+ this.running = new Map(); // agentId -> the bar being run for it
268
+ manager.standards = this;
269
+ }
270
+
271
+ get state() {
272
+ const st = (this.store.data.standards ??= {});
273
+ st.repos ??= {};
274
+ st.seen ??= {};
275
+ return st;
276
+ }
277
+
278
+ get checkTimeoutMs() {
279
+ const n = Number(this.config.standards?.checkTimeoutMs);
280
+ return Number.isFinite(n) && n >= 1000 ? Math.min(n, 3_600_000) : 600_000;
281
+ }
282
+
283
+ /** The repository an agent works in, or null (a session with none). */
284
+ keyOf(agent) {
285
+ if (!agent || NO_REPO.has(agent.kind)) return null;
286
+ const key = memoryKey(agent);
287
+ return key === 'other' ? null : key;
288
+ }
289
+
290
+ repo(key) {
291
+ return this.state.repos[key] ?? null;
292
+ }
293
+
294
+ ensure(key, name) {
295
+ if (!key) throw err(400, 'Which repository? Give its key (see the list)');
296
+ const r = (this.state.repos[key] ??= { name: name ?? this.nameOf(key) ?? key, risk: [], bar: { ...BAR_DEFAULTS }, lessons: [] });
297
+ return r;
298
+ }
299
+
300
+ agentsOf(key) {
301
+ return this.store.list().filter((a) => this.keyOf(a) === key);
302
+ }
303
+
304
+ nameOf(key) {
305
+ const a = this.agentsOf(key)[0];
306
+ if (!a) return null;
307
+ const p = projectOf({ ...a, projectMove: null, project: null });
308
+ return p.full ?? p.name;
309
+ }
310
+
311
+ /** What applies to an agent's changes. */
312
+ forAgent(agent) {
313
+ const r = this.repo(this.keyOf(agent));
314
+ return { lessons: (r?.lessons ?? []).filter((l) => l.state === 'accepted'), risk: r?.risk ?? [], bar: barSettings(r?.bar ?? BAR_DEFAULTS) };
315
+ }
316
+
317
+ prompt(agent) {
318
+ if (this.config.standards?.enabled === false) return '';
319
+ const { lessons, risk } = this.forAgent(agent);
320
+ return standardsPrompt({ lessons, risk });
321
+ }
322
+
323
+ /** The changed files of an agent that are under a high-risk path. */
324
+ riskIn(agent, files) {
325
+ if (this.config.standards?.enabled === false) return [];
326
+ return riskOf(files, this.forAgent(agent).risk);
327
+ }
328
+
329
+ async risk(ref) {
330
+ const agent = this.manager.mustGet(ref);
331
+ if (!this.forAgent(agent).risk.length || !this.manager.changesSource) return [];
332
+ const changes = await this.manager.changesSource(agent.id);
333
+ return this.riskIn(agent, changes.files ?? []);
334
+ }
335
+
336
+ /**
337
+ * An agent's changes against its repository's standards: the high-risk files touched, and the bar
338
+ * (run once per state of the changes; `fresh` runs it again). Kept on the agent as `standards`.
339
+ */
340
+ async assess(ref, data = null, { fresh = false } = {}) {
341
+ const agent = this.manager.mustGet(ref);
342
+ if (this.config.standards?.enabled === false) return null;
343
+ const std = this.forAgent(agent);
344
+ data ??= await this.manager.changesSource(agent.id);
345
+ const risk = riskOf(data.files ?? [], std.risk);
346
+ const diffHash = data.diffHash ?? crypto.createHash('sha1').update(data.diff ?? '').digest('hex');
347
+ const cur = this.store.get(agent.id)?.standards;
348
+ const want = JSON.stringify(std.bar);
349
+ let bar = null;
350
+ if (std.bar.tests || std.bar.secrets || std.bar.checks.length) {
351
+ if (!fresh && cur?.bar && cur.diffHash === diffHash && cur.bar.of === want) bar = cur.bar;
352
+ else if (this.running.has(agent.id)) bar = await this.running.get(agent.id);
353
+ else {
354
+ const p = this.runBar(agent, std.bar, data).then((results) => ({ of: want, at: now(), ok: results.every((r) => r.ok), results }));
355
+ this.running.set(agent.id, p);
356
+ try {
357
+ bar = await p;
358
+ } finally {
359
+ this.running.delete(agent.id);
360
+ }
361
+ }
362
+ }
363
+ const out = { diffHash, at: bar?.at ?? now(), risk, bar, lessons: std.lessons.map((l) => ({ id: l.id, text: l.text })) };
364
+ if (this.store.get(agent.id)) {
365
+ const { lessons, ...kept } = out;
366
+ if (JSON.stringify({ ...cur, at: 0 }) !== JSON.stringify({ ...kept, at: 0 })) this.manager.patch(agent.id, { standards: kept });
367
+ }
368
+ return out;
369
+ }
370
+
371
+ async runBar(agent, bar, data) {
372
+ const results = builtInChecks(bar, data);
373
+ for (const c of bar.checks) {
374
+ if (!agent.workdir || !fs.existsSync(agent.workdir)) {
375
+ results.push({ name: c.name, command: c.command, ok: false, code: null, ms: 0, tail: "The agent's folder is not on this computer" });
376
+ continue;
377
+ }
378
+ this.log(`standards: ${agent.name}: ${c.name} (${c.command})`);
379
+ results.push({ name: c.name, command: c.command, ...(await runCheck(c.command, { cwd: agent.workdir, timeoutMs: this.checkTimeoutMs })) });
380
+ }
381
+ return results;
382
+ }
383
+
384
+ /**
385
+ * When an agent says it is done: a change under a high-risk path is reviewed by another model,
386
+ * also where review rounds are off (the pull request stays yours to open).
387
+ */
388
+ async finished(agent) {
389
+ const pre = this.manager.preReview;
390
+ if (!pre || !this.forAgent(agent).risk.length) return false;
391
+ const risk = await this.risk(agent.id);
392
+ const cur = this.store.get(agent.id);
393
+ if (!risk.length || !cur || !pre.can(cur) || ['reviewing', 'fixing'].includes(cur.preReview?.status)) return false;
394
+ this.log(`standards: ${cur.name} touches high-risk paths (${risk.slice(0, 3).map((r) => r.path).join(', ')}): reviewed by another model`);
395
+ pre.begin(cur.id, { forced: 'risk' });
396
+ return true;
397
+ }
398
+
399
+ // -------------------------------------------------------------- settings
400
+
401
+ update(key, patch = {}) {
402
+ const r = this.ensure(key);
403
+ if (patch.risk !== undefined) r.risk = riskRules(patch.risk);
404
+ if (patch.bar !== undefined) r.bar = barSettings({ ...r.bar, ...patch.bar });
405
+ this.saved();
406
+ return this.repoView(key);
407
+ }
408
+
409
+ addLesson(key, text, { source = null } = {}) {
410
+ const r = this.ensure(key);
411
+ const line = cleanLesson(text);
412
+ const norm = (s) => s.toLowerCase().replace(/[^a-z0-9]+/g, ' ').trim();
413
+ if (r.lessons.some((l) => l.state === 'accepted' && norm(l.text) === norm(line))) throw err(409, 'That lesson is already there');
414
+ if (r.lessons.filter((l) => l.state === 'accepted').length >= MAX_LESSONS) throw err(409, `A repository keeps at most ${MAX_LESSONS} lessons, since every agent reads them all: remove one first`);
415
+ const lesson = { id: crypto.randomBytes(4).toString('hex'), text: line, state: 'accepted', source, at: now() };
416
+ r.lessons.push(lesson);
417
+ this.saved();
418
+ return lesson;
419
+ }
420
+
421
+ lesson(key, id) {
422
+ const l = this.repo(key)?.lessons.find((x) => x.id === id);
423
+ if (!l) throw err(404, 'No such lesson');
424
+ return l;
425
+ }
426
+
427
+ /** Accept (with its wording), dismiss, reword, or put back as proposed. */
428
+ setLesson(key, id, { state, text } = {}) {
429
+ const l = this.lesson(key, id);
430
+ if (text !== undefined) l.text = state === 'dismissed' ? clip(text, 300) : cleanLesson(text);
431
+ if (state !== undefined) {
432
+ if (!['accepted', 'dismissed', 'proposed'].includes(state)) throw err(400, 'state is accepted, dismissed or proposed');
433
+ if (state === 'accepted') {
434
+ l.text = cleanLesson(l.text);
435
+ if (l.state !== 'accepted' && this.repo(key).lessons.filter((x) => x.state === 'accepted').length >= MAX_LESSONS) throw err(409, `A repository keeps at most ${MAX_LESSONS} lessons: remove one first`);
436
+ }
437
+ l.state = state;
438
+ l.at = now();
439
+ }
440
+ this.saved();
441
+ return l;
442
+ }
443
+
444
+ removeLesson(key, id) {
445
+ const r = this.repo(key);
446
+ const l = this.lesson(key, id);
447
+ // One that came from a pull request stays dismissed, so it is not proposed again.
448
+ if (l.source?.url) l.state = 'dismissed';
449
+ else r.lessons.splice(r.lessons.indexOf(l), 1);
450
+ this.saved();
451
+ return { ok: true };
452
+ }
453
+
454
+ /** A model's wording for a proposed lesson, from the pull request and what followed it. */
455
+ async draft(key, id) {
456
+ const l = this.lesson(key, id);
457
+ if (!l.source) throw err(400, 'This lesson did not come from a pull request');
458
+ const agent = this.store.get(l.source.agentId) ?? this.agentsOf(key)[0];
459
+ if (!agent) throw err(409, 'No agent of this repository is left to ask a model with: write the lesson yourself');
460
+ let pr = null;
461
+ if (!process.env.AGENTMGR_NO_GH && l.source.url) {
462
+ // The description and what reviewers wrote, as far as GitHub gives them.
463
+ pr = await run(ghBin(), ['pr', 'view', l.source.url, '--json', 'title,body,reviews,comments'], { timeout: 30_000 })
464
+ .then((out) => {
465
+ const p = JSON.parse(out);
466
+ const said = [...(p.reviews ?? []), ...(p.comments ?? [])].map((c) => clip(c.body, 600)).filter(Boolean);
467
+ return [`Description: ${clip(p.body, 1500)}`, ...said.slice(0, 12).map((s) => `A reviewer wrote: ${s}`)].join('\n');
468
+ })
469
+ .catch(() => null);
470
+ }
471
+ const said = clip(await this.manager.oneShot(agent, lessonPrompt({ source: l.source, pr, repo: this.repo(key).name }), { ...this.manager.writerFor(agent), timeoutMs: 120_000 }), 600);
472
+ // Quotes around the whole reply go; ones inside it are the lesson's own.
473
+ const reply = /^(["'`])[\s\S]*\1$/.test(said) ? said.slice(1, -1).trim() : said;
474
+ if (!reply || /^UNKNOWN\b/i.test(reply)) throw err(422, 'The model could not tell what went wrong from what GitHub shows: write the lesson yourself');
475
+ l.text = reply.slice(0, 300);
476
+ this.saved();
477
+ return l;
478
+ }
479
+
480
+ /** Propose a lesson for each merged pull request that had a problem (once each); drop untouched ones that turned out fine. */
481
+ scan() {
482
+ if (!this.quality) return 0;
483
+ const st = this.state;
484
+ let changed = 0;
485
+ for (const it of this.quality.view().items) {
486
+ const src = lessonSource(it);
487
+ const seen = st.seen[it.url];
488
+ if (!src) {
489
+ if (!seen) continue;
490
+ const r = st.repos[seen];
491
+ const i = r?.lessons.findIndex((l) => l.source?.url === it.url && l.state === 'proposed' && !l.text) ?? -1;
492
+ if (i >= 0) {
493
+ r.lessons.splice(i, 1);
494
+ delete st.seen[it.url];
495
+ changed++;
496
+ }
497
+ continue;
498
+ }
499
+ if (seen) {
500
+ // What followed it can change (fixed, then reverted): a proposal not yet worded follows.
501
+ const l = st.repos[seen]?.lessons.find((x) => x.source?.url === it.url && x.state === 'proposed');
502
+ if (l && (l.source.kind !== src.kind || l.source.detail !== src.detail)) {
503
+ Object.assign(l.source, src);
504
+ changed++;
505
+ }
506
+ continue;
507
+ }
508
+ const agent = this.store.get(it.agentId);
509
+ const key = this.keyOf(agent);
510
+ if (!key) continue;
511
+ this.ensure(key).lessons.push({ id: crypto.randomBytes(4).toString('hex'), text: '', state: 'proposed', source: { ...src, url: it.url, number: it.number, title: it.title, agentId: it.agentId }, at: now() });
512
+ st.seen[it.url] = key;
513
+ changed++;
514
+ }
515
+ if (changed) this.store.save();
516
+ return changed;
517
+ }
518
+
519
+ saved() {
520
+ this.store.save();
521
+ this.onChange();
522
+ }
523
+
524
+ // -------------------------------------------------------------- views
525
+
526
+ repoView(key) {
527
+ const r = this.repo(key);
528
+ const agents = this.agentsOf(key);
529
+ const dir = agents.map((a) => a.workdir).find((d) => d && fs.existsSync(d));
530
+ const bar = barSettings(r?.bar ?? BAR_DEFAULTS);
531
+ const lessons = r?.lessons ?? [];
532
+ return {
533
+ key,
534
+ name: r?.name ?? this.nameOf(key) ?? key,
535
+ agents: agents.length,
536
+ risk: r?.risk ?? [],
537
+ bar,
538
+ suggested: dir ? suggestChecks(dir).filter((c) => !bar.checks.some((o) => o.command === c.command)) : [],
539
+ lessons: lessons.filter((l) => l.state === 'accepted'),
540
+ proposed: lessons.filter((l) => l.state === 'proposed'),
541
+ dismissed: lessons.filter((l) => l.state === 'dismissed').length,
542
+ };
543
+ }
544
+
545
+ view() {
546
+ this.scan();
547
+ const keys = new Set(Object.keys(this.state.repos));
548
+ for (const a of this.store.list()) {
549
+ const k = a.kind === 'task' ? this.keyOf(a) : null;
550
+ if (k) keys.add(k);
551
+ }
552
+ const repos = [...keys].map((k) => this.repoView(k)).sort((a, b) => b.proposed.length - a.proposed.length || a.name.localeCompare(b.name));
553
+ return { enabled: this.config.standards?.enabled !== false, repos, limits: { lessons: MAX_LESSONS, checks: MAX_CHECKS, checkSeconds: Math.round(this.checkTimeoutMs / 1000) } };
554
+ }
555
+
556
+ /** Which repository: its key, or a name that fits just one. */
557
+ find(ref) {
558
+ const v = this.view().repos;
559
+ const hit = v.find((r) => r.key === ref) ?? (() => {
560
+ const m = v.filter((r) => r.name === ref || r.name.split('/').at(-1) === ref);
561
+ if (m.length > 1) throw err(409, `"${ref}" fits ${m.length} repositories: give the key`);
562
+ return m[0];
563
+ })();
564
+ if (!hit) throw err(404, `No repository "${ref}" here: agents have to have worked in it`);
565
+ return hit.key;
566
+ }
567
+
568
+ /** Lessons proposed and not yet accepted or dismissed, over all repositories. */
569
+ pending() {
570
+ return Object.values(this.state.repos).reduce((n, r) => n + r.lessons.filter((l) => l.state === 'proposed').length, 0);
571
+ }
572
+ }