ai-agentmanager 1.27.0 → 1.29.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/bughunt.js ADDED
@@ -0,0 +1,475 @@
1
+ // Bug hunts: an agent that looks for bugs in a project, or one folder of it, in the background:
2
+ // in what changed since its last run, or in the whole module, a part at a time. It doesn't change
3
+ // the code. Each bug it reports comes with evidence (a test that fails, or the path through the
4
+ // code that breaks), and a second, independent check (the AI judge) keeps only those that hold up,
5
+ // so the list stays worth reading. Bugs already reported, or that you said aren't bugs, aren't
6
+ // reported again. From the list: Fix (an agent starts on it, with the failing test), File it (a
7
+ // filled-in issue to submit), Not a bug, or Snooze.
8
+
9
+ import crypto from 'node:crypto';
10
+ import fs from 'node:fs';
11
+ import path from 'node:path';
12
+ import { briefDir } from './brief.js';
13
+
14
+ export const FINDINGS_FILE = 'FINDINGS.json';
15
+ export const findingsPath = (agentId) => path.join(briefDir(agentId), FINDINGS_FILE);
16
+
17
+ export const FOCUS = { changes: 'What changed since the last run', module: 'The whole module, a part at a time' };
18
+ export const KINDS = {
19
+ correctness: 'Wrong results and edge cases',
20
+ concurrency: 'Races and deadlocks',
21
+ errors: 'Error handling: swallowed, unchecked or wrong errors',
22
+ resources: 'Leaks: files, connections, goroutines, memory',
23
+ security: 'Security: injection, auth, secrets',
24
+ data: 'Data loss or corruption',
25
+ performance: 'Performance that breaks under load',
26
+ };
27
+ export const SEVERITIES = ['critical', 'high', 'medium', 'low'];
28
+ export const SCHEDULES = { manual: 'Only when you press Hunt now', nightly: 'Every night (1–5am), when no hunt is running' };
29
+ export const STATUSES = ['open', 'fixing', 'filed', 'notbug', 'snoozed', 'dropped'];
30
+
31
+ const MAX_FINDINGS = 500;
32
+ const MAX_RUNS = 20;
33
+ const KEEP_AT = 0.6;
34
+ const err = (status, message) => Object.assign(new Error(message), { status });
35
+ const clip = (s, n) => {
36
+ const t = String(s ?? '').trim();
37
+ return t.length > n ? `${t.slice(0, n - 1)}…` : t;
38
+ };
39
+ const now = () => new Date().toISOString();
40
+
41
+ /** A folder in the repository: relative, no way out of it. Empty means the whole repository. */
42
+ export function cleanPath(p) {
43
+ const v = String(p ?? '').trim().replace(/\\/g, '/').replace(/^\.?\/+/, '').replace(/\/+$/, '');
44
+ if (!v) return '';
45
+ if (v.split('/').some((s) => s === '..') || path.isAbsolute(v)) throw err(400, 'The folder is a path inside the repository, like pkg/providers');
46
+ return v.slice(0, 300);
47
+ }
48
+
49
+ /** The hunter's instructions: read-only, findings with evidence in `file` as JSON. */
50
+ export function hunterPrompt(file, h) {
51
+ const where = h.path ? `the folder ${h.path} (and what it calls, as far as needed to judge a bug)` : 'the repository';
52
+ const kinds = h.kinds?.length ? h.kinds.map((k) => KINDS[k] ?? k).join('; ') : 'any kind of bug';
53
+ const scope =
54
+ h.focus === 'changes'
55
+ ? h.since
56
+ ? `Look at what changed in ${where} since commit ${h.since}: "git log --oneline ${h.since}..HEAD -- ${h.path || '.'}" and "git diff ${h.since}..HEAD -- ${h.path || '.'}". Read enough of the code around each change to judge it.`
57
+ : `Look at what changed in ${where} in the last 14 days: "git log --since=14.days --oneline -- ${h.path || '.'}" and the diffs of those commits. Read enough of the code around each change to judge it.`
58
+ : `Go through ${where}, a part at a time. ${h.covered?.length ? `Earlier runs covered: ${h.covered.slice(-40).join(', ')}. Start with what they didn't, or what changed since.` : 'Start with the code that matters most: entry points, shared state, I/O and error paths.'} Note in "covered" what you went through.`;
59
+ return [
60
+ `You are hunting for bugs in this repository for the user, in the background. Scope: ${where}. Looking for: ${kinds}.`,
61
+ scope,
62
+ "Don't change the code: never commit, push, open pull requests or edit files in the repository. You may build, run the tests, and write new test files to prove a bug (outside the repository's own test folders if you can, or delete them afterwards). The user decides what to fix.",
63
+ 'Report only real bugs: behaviour that is wrong for some input, timing or state the code can actually get into. Not style, naming, missing comments, refactoring ideas or speculation. ' +
64
+ 'For each, prove it: best is a test that fails (say how you ran it and what it printed); else the exact path through the code, with file:line steps, from an input or event to the wrong result. ' +
65
+ "If you can't show how it fails, leave it out. Fewer, solid findings are worth far more than many weak ones.",
66
+ `Write your findings to ${file} as JSON, and keep it current while you work:\n` +
67
+ '{\n' +
68
+ ' "headSha": "<git rev-parse HEAD>",\n' +
69
+ ' "covered": ["<folders or files you went through>"],\n' +
70
+ ' "findings": [{\n' +
71
+ ' "title": "<short: what goes wrong>",\n' +
72
+ ' "file": "<path>", "line": <line or null>,\n' +
73
+ ` "kind": "${Object.keys(KINDS).join('|')}",\n` +
74
+ ` "severity": "${SEVERITIES.join('|')}",\n` +
75
+ ' "why": "<how it fails: the input or timing, what happens, what should happen>",\n' +
76
+ ' "evidence": { "type": "test" | "trace", "detail": "<the failing test\'s output, or the file:line steps>", "test": "<the test code, when you wrote one>" },\n' +
77
+ ' "fix": "<what would fix it, in a sentence or two>",\n' +
78
+ ' "confidence": <0 to 1>\n' +
79
+ ' }],\n' +
80
+ ' "notes": "<what you checked and found fine, in a few lines>"\n' +
81
+ '}',
82
+ 'When you are done, set your status as done in the brief, with how many bugs you found in one line.',
83
+ ].join('\n\n');
84
+ }
85
+
86
+ const lineOf = (v) => (Number.isInteger(v) && v > 0 ? v : null);
87
+
88
+ /** FINDINGS.json, cleaned up: unknown values dropped, lengths capped. */
89
+ export function normalizeFindings(raw) {
90
+ if (!raw || typeof raw !== 'object') return null;
91
+ const findings = (Array.isArray(raw.findings) ? raw.findings : [])
92
+ .slice(0, 50)
93
+ .map((f) =>
94
+ f?.title && f?.why
95
+ ? {
96
+ title: clip(f.title, 200),
97
+ file: f.file ? clip(f.file, 300) : null,
98
+ line: lineOf(f.line),
99
+ kind: KINDS[f.kind] ? f.kind : 'correctness',
100
+ severity: SEVERITIES.includes(f.severity) ? f.severity : 'medium',
101
+ why: clip(f.why, 3000),
102
+ evidence: { type: f.evidence?.type === 'test' ? 'test' : 'trace', detail: clip(f.evidence?.detail, 4000), test: f.evidence?.test ? clip(f.evidence.test, 6000) : null },
103
+ fix: clip(f.fix, 1000),
104
+ confidence: Math.max(0, Math.min(1, Number(f.confidence) || 0)),
105
+ }
106
+ : null,
107
+ )
108
+ .filter(Boolean);
109
+ return {
110
+ headSha: /^[0-9a-f]{7,40}$/i.test(raw.headSha ?? '') ? raw.headSha : null,
111
+ covered: (Array.isArray(raw.covered) ? raw.covered : []).slice(0, 100).map((c) => clip(c, 200)).filter(Boolean),
112
+ findings,
113
+ notes: clip(raw.notes, 2000),
114
+ };
115
+ }
116
+
117
+ /** The hunter's FINDINGS.json: { ...findings, updatedAt } or null (missing or not JSON yet). */
118
+ export function readFindings(agentId) {
119
+ try {
120
+ const file = findingsPath(agentId);
121
+ const st = fs.statSync(file);
122
+ const text = fs.readFileSync(file, 'utf8');
123
+ const got = normalizeFindings(JSON.parse(text.slice(text.indexOf('{'), text.lastIndexOf('}') + 1)));
124
+ return got ? { ...got, updatedAt: st.mtime.toISOString() } : null;
125
+ } catch {
126
+ return null;
127
+ }
128
+ }
129
+
130
+ /** The same bug found again: same file and the same words in its title (line numbers move). */
131
+ export function fingerprint(huntKey, f) {
132
+ const words = String(f.title ?? '')
133
+ .toLowerCase()
134
+ .replace(/[^a-z0-9 ]+/g, ' ')
135
+ .split(/\s+/)
136
+ .filter((w) => w.length > 2)
137
+ .sort()
138
+ .join(' ');
139
+ return crypto.createHash('sha1').update(`${huntKey}|${f.file ?? ''}|${words}`).digest('hex').slice(0, 12);
140
+ }
141
+
142
+ /** The judge's question: does this finding hold up against the code? */
143
+ export function checkPrompt(f, snippet) {
144
+ return [
145
+ 'A bug-hunting agent reported the bug below. Check it independently against the code: is it a real bug that can happen, and is the evidence sound? Agents over-report: reject speculation, style, things the code already handles, and anything the evidence does not show.',
146
+ `Bug: ${f.title}\nWhere: ${f.file ?? '?'}${f.line ? `:${f.line}` : ''}\nKind: ${f.kind}, severity ${f.severity}\nHow it fails: ${f.why}\nEvidence (${f.evidence.type}): ${f.evidence.detail}${f.evidence.test ? `\nTest:\n${f.evidence.test}` : ''}`,
147
+ snippet ? `The code around it:\n${snippet}` : 'The code around it could not be read.',
148
+ 'Reply with JSON only: { "real": true|false, "confidence": <0 to 1>, "severity": "critical|high|medium|low", "reason": "<one or two sentences>" }',
149
+ ].join('\n\n');
150
+ }
151
+
152
+ /** Lines around `line` of `file` in `dir`, numbered; null when it can't be read. */
153
+ export function snippetOf(dir, file, line, around = 40) {
154
+ if (!dir || !file) return null;
155
+ try {
156
+ const full = path.resolve(dir, file);
157
+ if (!full.startsWith(path.resolve(dir) + path.sep)) return null;
158
+ const lines = fs.readFileSync(full, 'utf8').split('\n');
159
+ const at = line ? line - 1 : 0;
160
+ const from = Math.max(0, at - around);
161
+ return lines
162
+ .slice(from, Math.min(lines.length, at + around))
163
+ .map((l, i) => `${from + i + 1}: ${l}`)
164
+ .join('\n')
165
+ .slice(0, 12_000);
166
+ } catch {
167
+ return null;
168
+ }
169
+ }
170
+
171
+ /** Whether a finding is kept: the judge's word when it gave one, else a failing test. */
172
+ export function keep(f, check) {
173
+ if (check) return Boolean(check.real) && check.confidence >= KEEP_AT;
174
+ return f.evidence.type === 'test' && f.confidence >= KEEP_AT;
175
+ }
176
+
177
+ /** What a Fix agent is asked to do. */
178
+ export function fixIntent(f) {
179
+ return [
180
+ `Fix this bug found by a bug hunt: ${f.title}`,
181
+ `Where: ${f.file ?? '?'}${f.line ? `:${f.line}` : ''} (${f.kind}, ${f.severity})`,
182
+ `How it fails: ${f.why}`,
183
+ `Evidence (${f.evidence.type}): ${f.evidence.detail}`,
184
+ f.evidence.test ? `A test that shows it:\n${f.evidence.test}` : null,
185
+ f.fix ? `Suggested fix: ${f.fix}` : null,
186
+ 'First confirm it with a test that fails, then fix it so the test passes, without changing other behaviour. If it turns out not to be a bug, say why and stop.',
187
+ ]
188
+ .filter(Boolean)
189
+ .join('\n\n');
190
+ }
191
+
192
+ /** The finding as an issue, in Markdown. */
193
+ export function findingMarkdown(f) {
194
+ return [
195
+ `**Where:** \`${f.file ?? '?'}${f.line ? `:${f.line}` : ''}\` · ${KINDS[f.kind] ?? f.kind} · severity ${f.severity}`,
196
+ '',
197
+ `**How it fails:** ${f.why}`,
198
+ '',
199
+ `**Evidence (${f.evidence.type === 'test' ? 'a failing test' : 'the path through the code'}):**`,
200
+ '',
201
+ '```',
202
+ f.evidence.detail,
203
+ '```',
204
+ ...(f.evidence.test ? ['', '**Test:**', '', '```', f.evidence.test, '```'] : []),
205
+ ...(f.fix ? ['', `**Suggested fix:** ${f.fix}`] : []),
206
+ '',
207
+ '_Found by a bug hunt in AI Agent Manager._',
208
+ ].join('\n');
209
+ }
210
+
211
+ /** A GitHub new-issue link for the finding on `repo` (a GitHub URL), or null. */
212
+ export function issueLinkFor(repo, f) {
213
+ const m = String(repo ?? '').match(/github\.com[/:]([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?$/);
214
+ if (!m) return null;
215
+ let body = findingMarkdown(f);
216
+ if (body.length > 6000) body = `${body.slice(0, 5900)}\n\n_(cut short to fit the link)_`;
217
+ return `https://github.com/${m[1]}/${m[2]}/issues/new?${new URLSearchParams({ title: f.title, labels: 'bug', body })}`;
218
+ }
219
+
220
+ export class BugHunts {
221
+ /** `judge` is the AI judge (ask(key, agent, prompt, validate)); `read` gives a hunter's findings (tests). */
222
+ constructor({ manager, store, judge = null, log = () => {}, read = readFindings }) {
223
+ this.read = read;
224
+ this.manager = manager;
225
+ this.store = store;
226
+ this.judge = judge;
227
+ this.log = log;
228
+ this.checking = new Set();
229
+ this.onFinished = (agent) => {
230
+ if (agent?.hunting) this.ingest(agent.id).catch((e) => this.log(`bughunt: ${e.message}`));
231
+ };
232
+ manager.on('finished', this.onFinished);
233
+ this.timer = null;
234
+ }
235
+
236
+ close() {
237
+ this.manager.off('finished', this.onFinished);
238
+ clearInterval(this.timer);
239
+ }
240
+
241
+ get hunts() {
242
+ return (this.store.data.bugHunts ??= []);
243
+ }
244
+
245
+ get findings() {
246
+ return (this.store.data.bugFindings ??= []);
247
+ }
248
+
249
+ mustHunt(id) {
250
+ const h = this.hunts.find((x) => x.id === id);
251
+ if (!h) throw err(404, 'No such hunt');
252
+ return h;
253
+ }
254
+
255
+ /** A hunt's settings, checked: { project, path, focus, kinds, schedule, maxUsd, name }. */
256
+ settings(input = {}, prev = {}) {
257
+ const project = String(input.project ?? prev.project ?? '').trim().replace(/^@/, '');
258
+ if (!project) throw err(400, 'Pick a project to hunt in');
259
+ if (!this.manager.resolveProject(project)) throw err(400, `No project @${project}; see agentmgr project ls`);
260
+ const focus = input.focus ?? prev.focus ?? 'changes';
261
+ if (!FOCUS[focus]) throw err(400, `The focus is ${Object.keys(FOCUS).join(' or ')}`);
262
+ const kinds = (Array.isArray(input.kinds) ? input.kinds : prev.kinds ?? []).filter((k) => KINDS[k]);
263
+ const schedule = input.schedule ?? prev.schedule ?? 'manual';
264
+ if (!SCHEDULES[schedule]) throw err(400, `The schedule is ${Object.keys(SCHEDULES).join(' or ')}`);
265
+ const raw = input.maxUsd === undefined ? prev.maxUsd ?? 5 : Number(input.maxUsd);
266
+ if (!(Number.isFinite(raw) && raw > 0 && raw <= 500)) throw err(400, 'The cost limit per run is a number of dollars, up to 500');
267
+ const p = cleanPath(input.path ?? prev.path ?? '');
268
+ return { project, path: p, focus, kinds, schedule, maxUsd: Math.round(raw * 100) / 100, name: clip(input.name ?? prev.name ?? '', 80) || `${project}${p ? `/${p}` : ''}` };
269
+ }
270
+
271
+ add(input) {
272
+ const h = { id: crypto.randomBytes(3).toString('hex'), ...this.settings(input), createdAt: now(), runs: [], covered: [], lastSha: null };
273
+ this.hunts.push(h);
274
+ this.store.save();
275
+ return this.view(h);
276
+ }
277
+
278
+ update(id, input) {
279
+ const h = this.mustHunt(id);
280
+ Object.assign(h, this.settings(input, h));
281
+ this.store.save();
282
+ return this.view(h);
283
+ }
284
+
285
+ remove(id) {
286
+ const i = this.hunts.findIndex((x) => x.id === id);
287
+ if (i < 0) throw err(404, 'No such hunt');
288
+ this.hunts.splice(i, 1);
289
+ this.store.save();
290
+ return { removed: id };
291
+ }
292
+
293
+ /** The hunt agent running now, if any (one at a time, so hunts never crowd out your own work). */
294
+ runningAgent() {
295
+ return this.store.list().find((a) => a.hunting && a.desired === 'running' && !a.hunting.ingestedAt) ?? null;
296
+ }
297
+
298
+ /** Start a run: a read-only agent on the hunt's project, capped at the hunt's cost limit. */
299
+ run(id, { by = 'you' } = {}) {
300
+ const h = this.mustHunt(id);
301
+ const busy = this.runningAgent();
302
+ if (busy) throw err(409, `A hunt is running already (${busy.name}); one at a time`);
303
+ const hunting = { huntId: h.id, path: h.path, focus: h.focus, kinds: h.kinds, since: h.focus === 'changes' ? h.lastSha : null, covered: h.focus === 'module' ? h.covered : [], by };
304
+ const agent = this.manager.create({
305
+ project: h.project,
306
+ intent: `Bug hunt: ${h.name} (${h.focus === 'changes' ? 'recent changes' : 'whole module'})`,
307
+ name: `hunt-${h.name}`.toLowerCase().replace(/[^a-z0-9-]+/g, '-').slice(0, 40),
308
+ hunting,
309
+ });
310
+ this.manager.patch(agent.id, { budgetUsd: h.maxUsd });
311
+ h.runs.unshift({ agentId: agent.id, at: now(), by, status: 'running' });
312
+ h.runs.splice(MAX_RUNS);
313
+ this.store.save();
314
+ this.log(`bughunt: ${h.name}: started ${agent.name}`);
315
+ return { hunt: this.view(h), agent: { id: agent.id, name: agent.name } };
316
+ }
317
+
318
+ /**
319
+ * Take in what a hunter found: each new finding is checked by the judge, kept or dropped, and
320
+ * the hunter is stopped. Safe to call more than once.
321
+ */
322
+ async ingest(agentId) {
323
+ const agent = this.store.get(agentId);
324
+ if (!agent?.hunting || agent.hunting.ingestedAt || this.checking.has(agentId)) return null;
325
+ this.checking.add(agentId);
326
+ try {
327
+ const h = this.hunts.find((x) => x.id === agent.hunting.huntId) ?? null;
328
+ const got = this.read(agentId);
329
+ const huntKey = h ? `${h.project}|${h.path}` : agent.hunting.huntId;
330
+ let found = 0;
331
+ let kept = 0;
332
+ for (const f of got?.findings ?? []) {
333
+ const id = fingerprint(huntKey, f);
334
+ // Already on the list, or you said it isn't a bug: not again.
335
+ if (this.findings.some((x) => x.id === id)) continue;
336
+ found += 1;
337
+ const check = this.judge
338
+ ? await this.judge.ask(`hunt:${id}`, agent, checkPrompt(f, snippetOf(agent.workdir, f.file, f.line)), (d) => typeof d.real === 'boolean').catch(() => null)
339
+ : null;
340
+ const ok = keep(f, check);
341
+ if (ok) kept += 1;
342
+ this.findings.unshift({
343
+ id,
344
+ huntId: agent.hunting.huntId,
345
+ project: h?.project ?? agent.project ?? null,
346
+ ...f,
347
+ severity: check?.real && SEVERITIES.includes(check.severity) ? check.severity : f.severity,
348
+ check: check ? { real: check.real, confidence: check.confidence, reason: clip(check.reason, 600) } : null,
349
+ status: ok ? 'open' : 'dropped',
350
+ foundBy: agent.id,
351
+ at: now(),
352
+ });
353
+ }
354
+ this.findings.splice(MAX_FINDINGS);
355
+ if (h) {
356
+ if (got?.headSha) h.lastSha = got.headSha;
357
+ if (got?.covered?.length) h.covered = [...new Set([...h.covered, ...got.covered])].slice(-200);
358
+ const r = h.runs.find((x) => x.agentId === agentId);
359
+ if (r) Object.assign(r, { status: 'done', doneAt: now(), found, kept, dropped: found - kept, notes: got?.notes ?? null, wrote: Boolean(got) });
360
+ }
361
+ this.manager.patch(agentId, { hunting: { ...agent.hunting, ingestedAt: now() } });
362
+ this.store.save();
363
+ // Its work is in the list now: the session needn't stay open.
364
+ try {
365
+ this.manager.stop(agentId);
366
+ } catch {}
367
+ this.log(`bughunt: ${agent.name}: ${kept} kept of ${found} new`);
368
+ return { found, kept };
369
+ } finally {
370
+ this.checking.delete(agentId);
371
+ }
372
+ }
373
+
374
+ /** Runs that ended without saying done (stopped, out of budget): their findings are taken in too. */
375
+ async sweep() {
376
+ for (const a of this.store.list()) {
377
+ if (!a.hunting || a.hunting.ingestedAt) continue;
378
+ const rt = this.manager.runtimes?.get(a.id);
379
+ if (a.brief?.status === 'done' || (a.desired !== 'running' && !rt?.pty)) await this.ingest(a.id).catch(() => {});
380
+ }
381
+ }
382
+
383
+ /** Nightly hunts: between 1 and 5 in the morning, once a day, one at a time. */
384
+ async tick(at = new Date()) {
385
+ await this.sweep();
386
+ const hour = at.getHours();
387
+ if (hour < 1 || hour >= 5 || this.runningAgent()) return null;
388
+ const due = this.hunts.find((h) => h.schedule === 'nightly' && !(h.runs[0] && at.getTime() - Date.parse(h.runs[0].at) < 20 * 3_600_000));
389
+ if (!due) return null;
390
+ try {
391
+ return this.run(due.id, { by: 'schedule' });
392
+ } catch (e) {
393
+ this.log(`bughunt: ${due.name}: ${e.message}`);
394
+ return null;
395
+ }
396
+ }
397
+
398
+ startTimer(ms = 10 * 60_000) {
399
+ this.timer = setInterval(() => this.tick().catch(() => {}), ms);
400
+ this.timer.unref?.();
401
+ }
402
+
403
+ /** Your decision on findings: open, notbug, snoozed (until a time), filed. */
404
+ set(ids = [], status, { until = null } = {}) {
405
+ if (!['open', 'notbug', 'snoozed', 'filed'].includes(status)) throw err(400, 'The decision is open, notbug, snoozed or filed');
406
+ let snoozeUntil = null;
407
+ if (status === 'snoozed') {
408
+ const t = Date.parse(until ?? '');
409
+ if (!Number.isFinite(t) || t <= Date.now()) throw err(400, 'Snooze until a time to come');
410
+ snoozeUntil = new Date(t).toISOString();
411
+ }
412
+ const set = [];
413
+ for (const id of new Set(ids)) {
414
+ const f = this.findings.find((x) => x.id === id);
415
+ if (!f) continue;
416
+ f.prev = f.status;
417
+ f.status = status;
418
+ f.snoozeUntil = snoozeUntil;
419
+ f.decidedAt = now();
420
+ set.push(id);
421
+ }
422
+ this.store.save();
423
+ return { set };
424
+ }
425
+
426
+ /** Start an agent to fix a finding, in the hunt's project. */
427
+ fix(id) {
428
+ const f = this.findings.find((x) => x.id === id);
429
+ if (!f) throw err(404, 'No such finding');
430
+ const prev = f.fixAgentId ? this.store.get(f.fixAgentId) : null;
431
+ if (prev) return { agent: { id: prev.id, name: prev.name }, existing: true };
432
+ const [agent] = this.manager.createMany([fixIntent(f)], { project: f.project, name: `fix-${f.title}`.slice(0, 40) });
433
+ f.fixAgentId = agent.id;
434
+ f.status = 'fixing';
435
+ f.decidedAt = now();
436
+ this.store.save();
437
+ return { agent: { id: agent.id, name: agent.name }, existing: false };
438
+ }
439
+
440
+ /** The finding as an issue: a GitHub link when the project is on GitHub, and the Markdown. */
441
+ issue(id) {
442
+ const f = this.findings.find((x) => x.id === id);
443
+ if (!f) throw err(404, 'No such finding');
444
+ const repo = f.project ? this.manager.resolveProject(f.project)?.repo : null;
445
+ return { title: f.title, markdown: findingMarkdown(f), url: issueLinkFor(repo, f) };
446
+ }
447
+
448
+ view(h) {
449
+ const agent = h.runs[0] ? this.store.get(h.runs[0].agentId) : null;
450
+ const open = this.findings.filter((f) => f.huntId === h.id && f.status === 'open').length;
451
+ return { ...h, covered: undefined, coveredCount: h.covered.length, open, running: Boolean(agent?.hunting && !agent.hunting.ingestedAt && agent.desired === 'running'), last: h.runs[0] ?? null };
452
+ }
453
+
454
+ /** Findings, snoozed ones back once their time comes; the hunts; what's running. */
455
+ list() {
456
+ const t = Date.now();
457
+ for (const f of this.findings) {
458
+ if (f.status === 'snoozed' && f.snoozeUntil && Date.parse(f.snoozeUntil) <= t) {
459
+ f.status = 'open';
460
+ f.snoozeUntil = null;
461
+ }
462
+ if (f.status === 'fixing' && f.fixAgentId && !this.store.get(f.fixAgentId)) f.status = 'open';
463
+ }
464
+ const running = this.runningAgent();
465
+ const rank = Object.fromEntries(SEVERITIES.map((s, i) => [s, i]));
466
+ return {
467
+ hunts: this.hunts.map((h) => this.view(h)),
468
+ findings: [...this.findings].sort((a, b) => rank[a.severity] - rank[b.severity] || String(b.at).localeCompare(String(a.at))).map((f) => ({ ...f, hunt: this.hunts.find((h) => h.id === f.huntId)?.name ?? null })),
469
+ running: running ? { id: running.id, name: running.name, huntId: running.hunting.huntId } : null,
470
+ focus: FOCUS,
471
+ kinds: KINDS,
472
+ schedules: SCHEDULES,
473
+ };
474
+ }
475
+ }
package/src/cli.js CHANGED
@@ -757,9 +757,13 @@ export async function main(argv) {
757
757
  .option('--from <who>', 'who asked')
758
758
  .option('--due <when>', 'when it is due, if said')
759
759
  .option('--context <text>', 'a sentence or two of background')
760
+ .option('--question <words>', 'a question put to you: its words (the action then is to answer it)')
761
+ .option('--cc', "you're copied or mentioned on it, not asked directly")
762
+ .option('--answer <text>', 'a draft answer, to edit and send yourself')
763
+ .option('--sources <text>', 'with --answer: the links or files it is based on')
760
764
  .action(async (words, opts) => {
761
765
  await daemon();
762
- const a = await api('POST', '/actions', { text: words.join(' '), source: opts.source, link: opts.link, from: opts.from, due: opts.due, context: opts.context });
766
+ const a = await api('POST', '/actions', { text: words.join(' '), source: opts.source, link: opts.link, from: opts.from, due: opts.due, context: opts.context, question: opts.question, cc: Boolean(opts.cc), answer: opts.answer, sources: opts.sources });
763
767
  console.log(a.duplicate ? dim(`Already listed: ${a.id}`) : `${green('+')} ${bold(a.id)} ${a.text}`);
764
768
  });
765
769
  actionsCmd
@@ -775,6 +779,17 @@ export async function main(argv) {
775
779
  if (r.set.length) console.log(`${green('✓')} ${r.set.join(', ')}: ${state}`);
776
780
  for (const x of r.failed) console.log(`${red('!')} ${bold(x.id)}: ${x.reason}`);
777
781
  });
782
+ actionsCmd
783
+ .command('answer')
784
+ .description('Record a draft answer to a question (to edit and send yourself; nothing is sent)')
785
+ .argument('<id>')
786
+ .argument('<text...>', 'the answer')
787
+ .option('--sources <text>', 'the links or files it is based on')
788
+ .action(async (id, words, opts) => {
789
+ await daemon();
790
+ await api('PUT', `/actions/${id}/answer`, { text: words.join(' '), sources: opts.sources });
791
+ console.log(`${green('✓')} ${bold(id)}: draft answer saved`);
792
+ });
778
793
  actionsCmd
779
794
  .command('discuss')
780
795
  .description('Talk an action item through with Claude, in a session of its own')
package/src/issues.js CHANGED
@@ -34,9 +34,11 @@ export const GROUPS = {
34
34
  * the list). Any of them can be changed later; skipped, done and removed issues aren't proposed or
35
35
  * started by the assistant.
36
36
  */
37
- export const ACTIONS = ['assign', 'skip', 'done', 'remove'];
38
- const SET_ASIDE = { skip: 'skipped', done: 'done', remove: 'removed' };
39
- const ACTION_NOTE = { skip: 'Skipped by you', done: 'Marked done by you', remove: 'Removed by you' };
37
+ export const ACTIONS = ['assign', 'skip', 'snooze', 'done', 'remove'];
38
+ const SET_ASIDE = { skip: 'skipped', snooze: 'snoozed', done: 'done', remove: 'removed' };
39
+ const ACTION_NOTE = { skip: 'Skipped by you', snooze: 'Snoozed by you', done: 'Marked done by you', remove: 'Removed by you' };
40
+ // A snooze whose time has come is no decision any more.
41
+ const expired = (e, t = Date.now()) => e?.action === 'snooze' && !(Date.parse(e.until ?? '') > t);
40
42
 
41
43
  /** The issue an agent works on: { key, url }, from the link its request starts with or one in it. */
42
44
  export function issueOf(v) {
@@ -105,6 +107,7 @@ function designOf(v, read) {
105
107
  export function issueRows(views, jira = new Map(), read = () => null, proposed = [], actions = {}, assigned = []) {
106
108
  const rank = Object.fromEntries(Object.keys(GROUPS).map((k, i) => [k, i]));
107
109
  const rows = [];
110
+ actions = Object.fromEntries(Object.entries(actions).filter(([, e]) => !expired(e)));
108
111
  // What the search for issues assigned to you found: their summaries stand in where nothing else has one.
109
112
  const mine = new Map(assigned.map((i) => [i.key, i]));
110
113
  // Issues proposed for agents, not started yet: they wait for you to tick them.
@@ -113,6 +116,7 @@ export function issueRows(views, jira = new Map(), read = () => null, proposed =
113
116
  const action = actions[p.key]?.action ?? (p.status === 'dismissed' ? 'remove' : null);
114
117
  rows.push({
115
118
  actionAt: actions[p.key]?.at ?? null,
119
+ snoozeUntil: actions[p.key]?.action === 'snooze' ? actions[p.key].until : null,
116
120
  key: p.key,
117
121
  url: p.url,
118
122
  title: j?.summary ?? mine.get(p.key)?.summary ?? p.title,
@@ -142,6 +146,7 @@ export function issueRows(views, jira = new Map(), read = () => null, proposed =
142
146
  const design = designOf(v, read);
143
147
  rows.push({
144
148
  actionAt: actions[issue.key]?.at ?? null,
149
+ snoozeUntil: actions[issue.key]?.action === 'snooze' ? actions[issue.key].until : null,
145
150
  key: issue.key,
146
151
  url: issue.url,
147
152
  title: j?.summary ?? mine.get(issue.key)?.summary ?? issue.title,
@@ -167,6 +172,7 @@ export function issueRows(views, jira = new Map(), read = () => null, proposed =
167
172
  const action = actions[i.key]?.action ?? null;
168
173
  rows.push({
169
174
  actionAt: actions[i.key]?.at ?? null,
175
+ snoozeUntil: actions[i.key]?.action === 'snooze' ? actions[i.key].until : null,
170
176
  key: i.key,
171
177
  url: i.url,
172
178
  title: i.summary,
@@ -244,7 +250,9 @@ export class ProposedIssues {
244
250
 
245
251
  /** Your action per issue key: { action, at }. */
246
252
  get actions() {
247
- return (this.store.data.issueActions ??= {});
253
+ const all = (this.store.data.issueActions ??= {});
254
+ for (const [k, e] of Object.entries(all)) if (expired(e)) delete all[k];
255
+ return all;
248
256
  }
249
257
 
250
258
  /** Skip, done or remove when you set one; dismissed before actions existed counts as remove. */
@@ -276,8 +284,10 @@ export class ProposedIssues {
276
284
  * Set your action on issues (null clears it). Assign starts an agent from the proposal when none
277
285
  * works on the issue yet. Returns { set: [keys], started: [{ key, agent }], failed: [{ key, reason }] }.
278
286
  */
279
- setAction(keys = [], action = null) {
287
+ setAction(keys = [], action = null, { until = null } = {}) {
280
288
  if (action !== null && !ACTIONS.includes(action)) throw err(400, `The action is one of ${ACTIONS.join(', ')}, or none to clear it`);
289
+ const wakeAt = action === 'snooze' ? Date.parse(until ?? '') : null;
290
+ if (action === 'snooze' && !(Number.isFinite(wakeAt) && wakeAt > Date.now())) throw err(400, 'Snooze until a time to come');
281
291
  const set = [];
282
292
  const started = [];
283
293
  const failed = [];
@@ -307,7 +317,7 @@ export class ProposedIssues {
307
317
  agent = r.started[0].agent;
308
318
  }
309
319
  // Assign is what an agent on it means anyway; only the others are kept.
310
- if (SET_ASIDE[action]) this.actions[key] = { action, at: new Date().toISOString() };
320
+ if (SET_ASIDE[action]) this.actions[key] = { action, at: new Date().toISOString(), ...(action === 'snooze' ? { until: new Date(wakeAt).toISOString() } : {}) };
311
321
  else delete this.actions[key];
312
322
  if (p?.status === 'dismissed') p.status = 'waiting';
313
323
  set.push(key);
package/src/manager.js CHANGED
@@ -111,6 +111,7 @@ import { assignedIssues, issueFields, issueSummary, jiraProblem, leadingIssue, l
111
111
  import { issueRows } from './issues.js';
112
112
  import { designRows } from './designs.js';
113
113
  import { reviewPath, reviewerPrompt } from './reviews.js';
114
+ import { findingsPath, hunterPrompt } from './bughunt.js';
114
115
  import { reminderFor, reminderSettings } from './reminders.js';
115
116
  import { combine, facts as scoreFacts, improveMessage, scorecardMarkdown, scorecardPrompt } from './scorecard.js';
116
117
  import { CONTAINER_ENGINES, claudeToken, containerName, containerRunning, engineMounts, gitCommonDir, removeContainer, runArgs, stopContainer } from './container.js';
@@ -396,7 +397,8 @@ export class AgentManager extends EventEmitter {
396
397
  },
397
398
  };
398
399
  // A recent agent gone quiet: follow up on it, or close its finished session (reminders.js).
399
- v.followUp = reminderFor(v, reminderSettings(this.config));
400
+ // A bug hunt's work goes to the Bugs list, not a follow-up.
401
+ v.followUp = agent.hunting ? null : reminderFor(v, reminderSettings(this.config));
400
402
  return v;
401
403
  }
402
404
 
@@ -624,6 +626,7 @@ export class AgentManager extends EventEmitter {
624
626
  isolation,
625
627
  builds,
626
628
  reviewing,
629
+ hunting,
627
630
  }) {
628
631
  intent = (intent ?? '').trim();
629
632
  const staged = stagedFiles(attachments);
@@ -680,6 +683,8 @@ export class AgentManager extends EventEmitter {
680
683
  ...(builds ? { builds: { name: String(builds.name), engine: String(builds.engine ?? 'claude') } } : {}),
681
684
  // Reviews someone else's pull request (reviews.js): { url, slug, number, title }.
682
685
  ...(!general && reviewing ? { reviewing } : {}),
686
+ // Hunts for bugs, read-only (bughunt.js): { huntId, path, focus, kinds, since, covered }.
687
+ ...(!general && hunting ? { hunting } : {}),
683
688
  name: name?.trim() || jiraKey || slug,
684
689
  slug,
685
690
  intent,
@@ -696,11 +701,11 @@ export class AgentManager extends EventEmitter {
696
701
  model: model || null,
697
702
  // Review the implementation plan before the agent implements it: null = no review.
698
703
  // Team members get their review from the team instead.
699
- planReview: !general && !team && !builds && !reviewing && (planReview ?? this.config.planReview ?? false) ? { status: 'writing' } : null,
704
+ planReview: !general && !team && !builds && !reviewing && !hunting && (planReview ?? this.config.planReview ?? false) ? { status: 'writing' } : null,
700
705
  // Write and publish a design doc (Google Doc + Artifact) after the plan, updated at the end.
701
- designDoc: !general && !team && !builds && !reviewing && Boolean(designDoc ?? this.config.designDoc ?? true),
702
- demoPage: !general && !team && !builds && !reviewing && Boolean(demoPage ?? this.config.demoPage ?? false),
703
- benchmarks: !general && !team && !builds && !reviewing && Boolean(benchmarks ?? this.config.benchmarks ?? false),
706
+ designDoc: !general && !team && !builds && !reviewing && !hunting && Boolean(designDoc ?? this.config.designDoc ?? true),
707
+ demoPage: !general && !team && !builds && !reviewing && !hunting && Boolean(demoPage ?? this.config.demoPage ?? false),
708
+ benchmarks: !general && !team && !builds && !reviewing && !hunting && Boolean(benchmarks ?? this.config.benchmarks ?? false),
704
709
  status: 'preparing',
705
710
  desired: start ? 'running' : 'stopped',
706
711
  error: null,
@@ -1194,7 +1199,7 @@ export class AgentManager extends EventEmitter {
1194
1199
  }
1195
1200
  // SPEC.md before changing code, and PLAN.md kept as it goes (unless the plan review asks for the plan).
1196
1201
  // A session building an agent keeps its analysis in the agent's folder instead.
1197
- if (task && this.config.specs !== false && !agent.builds && !agent.reviewing) {
1202
+ if (task && this.config.specs !== false && !agent.builds && !agent.reviewing && !agent.hunting) {
1198
1203
  fs.mkdirSync(briefDir(agent.id), { recursive: true });
1199
1204
  const dir = fs.realpathSync(briefDir(agent.id));
1200
1205
  writableDir ??= dir;
@@ -1225,6 +1230,12 @@ export class AgentManager extends EventEmitter {
1225
1230
  writableDir ??= path.dirname(file);
1226
1231
  prompts.push(reviewerPrompt(file, agent.reviewing));
1227
1232
  }
1233
+ if (agent.hunting && task) {
1234
+ fs.mkdirSync(briefDir(agent.id), { recursive: true });
1235
+ const file = path.join(fs.realpathSync(briefDir(agent.id)), path.basename(findingsPath(agent.id)));
1236
+ writableDir ??= path.dirname(file);
1237
+ prompts.push(hunterPrompt(file, agent.hunting));
1238
+ }
1228
1239
  if (planning) prompts.push(planningPrompt(agent));
1229
1240
  // What earlier agents learned in this repo, and the one command to add to it.
1230
1241
  let allowedTools = null;
@@ -2205,6 +2216,9 @@ export class AgentManager extends EventEmitter {
2205
2216
  // Asked to improve: its next update of the brief as done is scored again (also with auto off).
2206
2217
  const improved = brief.status === 'done' && agent.improving && brief.updatedAt !== agent.improving.briefAt;
2207
2218
  // The agent says it is done: have the judge check the work before the person looks.
2219
+ if (finished) this.emit('finished', this.store.get(id));
2220
+ // A bug hunt's findings are checked one by one instead (bughunt.js).
2221
+ if (agent.hunting) return;
2208
2222
  if (finished && this.judge.enabled) this.requestReview(id, { trigger: 'brief' }).catch(() => {});
2209
2223
  // ...and score it for the reviewer ("scorecard": { "auto": false } in config.json turns this off).
2210
2224
  if ((improved || (finished && this.config.scorecard?.auto !== false)) && !NO_REPO.has(agent.kind) && this.changesSource) this.summarize(id, 'scorecard').catch(() => {});