ai-agentmanager 1.26.1 → 1.28.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/issues.js CHANGED
@@ -112,6 +112,7 @@ export function issueRows(views, jira = new Map(), read = () => null, proposed =
112
112
  const j = jira.get(p.key) ?? null;
113
113
  const action = actions[p.key]?.action ?? (p.status === 'dismissed' ? 'remove' : null);
114
114
  rows.push({
115
+ actionAt: actions[p.key]?.at ?? null,
115
116
  key: p.key,
116
117
  url: p.url,
117
118
  title: j?.summary ?? mine.get(p.key)?.summary ?? p.title,
@@ -140,6 +141,7 @@ export function issueRows(views, jira = new Map(), read = () => null, proposed =
140
141
  const note = ACTION_NOTE[action] ? `${ACTION_NOTE[action]} (${where.charAt(0).toLowerCase()}${where.slice(1)})` : where;
141
142
  const design = designOf(v, read);
142
143
  rows.push({
144
+ actionAt: actions[issue.key]?.at ?? null,
143
145
  key: issue.key,
144
146
  url: issue.url,
145
147
  title: j?.summary ?? mine.get(issue.key)?.summary ?? issue.title,
@@ -164,6 +166,7 @@ export function issueRows(views, jira = new Map(), read = () => null, proposed =
164
166
  listed.add(i.key);
165
167
  const action = actions[i.key]?.action ?? null;
166
168
  rows.push({
169
+ actionAt: actions[i.key]?.at ?? null,
167
170
  key: i.key,
168
171
  url: i.url,
169
172
  title: i.summary,
package/src/jira.js CHANGED
@@ -88,13 +88,15 @@ const authOf = (jira) => (jira.email ? `Basic ${Buffer.from(`${jira.email}:${jir
88
88
  /** The reason in words for an answer that isn't ok, or a fetch that threw. */
89
89
  function reasonOf(site, res, e) {
90
90
  if (res) {
91
+ if (res.status >= 300 && res.status < 400) return `${site} sent the request on to ${res.movedTo ?? 'another address'} (a sign-in page?): put your Atlassian address (https://yourcompany.atlassian.net) in Settings → Jira`;
91
92
  const why = {
92
93
  401: 'the email or API token is not accepted (Settings → Jira)',
93
94
  403: 'no permission; if you mistyped the token a few times, Jira may want you to sign in once in the browser',
94
95
  404: 'no Jira API at that address (is the site right?)',
96
+ issue404: 'no such issue, or the account in Settings can\'t see it (is the email the one you sign in to Jira with?)',
95
97
  429: 'too many requests; trying again later',
96
- }[res.status];
97
- return `${site} answered ${res.status}${why ? `: ${why}` : ''}`;
98
+ }[res.forIssue && res.status === 404 ? 'issue404' : res.status];
99
+ return `${site} answered ${res.status}${res.forIssue ? ` for ${res.forIssue}` : ''}${why ? `: ${why}` : ''}`;
98
100
  }
99
101
  const m = String(e?.cause?.message ?? e?.message ?? e ?? '');
100
102
  if (e?.name === 'TimeoutError' || /abort|timeout/i.test(m)) return `${site} did not answer in time (VPN off?)`;
@@ -107,9 +109,29 @@ function reasonOf(site, res, e) {
107
109
  * isn't there. Returns the response, or throws.
108
110
  */
109
111
  async function jiraGet(fetchImpl, site, v3, v2, init) {
110
- const res = await fetchImpl(`${site}${v3.path}`, { ...init, ...v3.init });
112
+ const res = await follow(fetchImpl, `${site}${v3.path}`, { ...init, ...v3.init });
111
113
  if (res.status !== 404 || !v2) return res;
112
- return fetchImpl(`${site}${v2.path}`, { ...init, ...v2.init });
114
+ return follow(fetchImpl, `${site}${v2.path}`, { ...init, ...v2.init });
115
+ }
116
+
117
+ /**
118
+ * A site on its own domain (jira.company.com) may send API calls on to its Atlassian Cloud
119
+ * address: followed once, to the same host or an *.atlassian.net one only, so the token never goes
120
+ * anywhere else. Any other redirect (a sign-in page) comes back as it is.
121
+ */
122
+ async function follow(fetchImpl, url, init) {
123
+ const res = await fetchImpl(url, { ...init, redirect: 'manual' });
124
+ if (!(res.status >= 300 && res.status < 400)) return res;
125
+ const where = res.headers?.get?.('location');
126
+ const to = (() => {
127
+ try {
128
+ return where ? new URL(where, url) : null;
129
+ } catch {
130
+ return null;
131
+ }
132
+ })();
133
+ if (!to || to.protocol !== 'https:' || !(to.host === new URL(url).host || /\.atlassian\.net$/.test(to.host))) return Object.assign(res, { movedTo: to?.host ?? null });
134
+ return fetchImpl(to.href, { ...init, redirect: 'manual' });
113
135
  }
114
136
 
115
137
  /**
@@ -130,7 +152,7 @@ export async function assignedIssues({ jira = loadJira(), fetchImpl = fetch, tim
130
152
  jira.site,
131
153
  { path: '/rest/api/3/search/jql', init: { method: 'POST', body: JSON.stringify({ jql, fields, maxResults: max }) } },
132
154
  { path: `/rest/api/2/search?${q}`, init: { method: 'GET' } },
133
- { headers, redirect: 'error', signal: AbortSignal.timeout(timeoutMs) },
155
+ { headers, signal: AbortSignal.timeout(timeoutMs) },
134
156
  );
135
157
  if (!res.ok) {
136
158
  problem = { at: new Date().toISOString(), reason: reasonOf(jira.site, res) };
@@ -215,18 +237,20 @@ export async function issueFields({ key, site }, { jira = loadJira(), fetchImpl
215
237
  return '';
216
238
  }
217
239
  })();
218
- const configured = jira.site && new URL(jira.site).host === host;
240
+ // With your site saved, the issue is asked of it, whatever address the link has: links often use
241
+ // the site's own domain (jira.company.com) while the API is on its Atlassian address, or the
242
+ // other way round. Without one, only public Atlassian Cloud issues are asked for, signed out.
243
+ const configured = Boolean(jira.site && jira.token);
219
244
  const allowed = configured || /\.atlassian\.net$/.test(host) || allow?.(site);
220
245
  if (!allowed) return null;
221
246
  const headers = { accept: 'application/json' };
222
- if (configured && jira.token) headers.authorization = authOf(jira);
247
+ if (configured) headers.authorization = authOf(jira);
223
248
  const q = `${encodeURIComponent(key)}?fields=summary,status,description`;
224
249
  try {
225
250
  // Your site as saved: it may have a path (https://host/jira) that the link's origin leaves out.
226
- const res = await jiraGet(fetchImpl, configured ? jira.site : site, { path: `/rest/api/3/issue/${q}` }, configured ? { path: `/rest/api/2/issue/${q}` } : null, { headers, redirect: 'error', signal: AbortSignal.timeout(timeoutMs) });
251
+ const res = await jiraGet(fetchImpl, configured ? jira.site : site, { path: `/rest/api/3/issue/${q}` }, configured ? { path: `/rest/api/2/issue/${q}` } : null, { headers, signal: AbortSignal.timeout(timeoutMs) });
227
252
  if (!res.ok) {
228
- // Your own site refusing (not a missing issue) is worth saying.
229
- if (configured && res.status !== 404) problem = { at: new Date().toISOString(), reason: reasonOf(jira.site, res) };
253
+ if (configured) problem = { at: new Date().toISOString(), reason: reasonOf(jira.site, Object.assign(res, { forIssue: key })) };
230
254
  return null;
231
255
  }
232
256
  const f = (await res.json())?.fields ?? {};
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(() => {});