ai-agentmanager 1.27.0 → 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/CHANGELOG.md CHANGED
@@ -1,5 +1,9 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.28.0 (2026-11-07)
4
+
5
+ - **Bug hunts.** *Bugs* (or `b`) runs agents that look for bugs in the background, in a project or one folder of it: in what changed since the last run, or the whole module a part at a time, for any bug or the kinds you pick (races, error handling, leaks, security, data). A hunt runs by hand (*Hunt now*) or every night, one at a time, and stops at its cost limit. The hunter reads the code and runs the tests on its own copy and never commits or pushes. Each bug must come with evidence (a failing test, or the path through the code), and the AI judge checks each one against the code: only those that hold up are listed, worst first, and nothing is reported twice. On each: *Fix* starts an agent with the finding and its test, *File it* opens a filled-in GitHub issue (or copies it as Markdown), *Not a bug* keeps it from coming back, *Snooze* hides it until tomorrow or Monday. Critical and high ones show in Today.
6
+
3
7
  ## 1.27.0 (2026-11-07)
4
8
 
5
9
  - **Jira on your company's own address.** With your site saved in Settings → Jira, every issue's summary and status are asked of that site, whatever address its link has (links often use the company's own domain, like `jira.company.com`, while the API answers on `company.atlassian.net`). A site that sends the API on to its Atlassian address is followed there (and only there). When Jira says it can't find an issue, the Jira list says so: usually the email in Settings isn't the one you sign in to Jira with.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ai-agentmanager",
3
- "version": "1.27.0",
3
+ "version": "1.28.0",
4
4
  "description": "Run background coding agents (Claude Code, Codex) per intent, and keep track of them from a web UI, your phone or the CLI",
5
5
  "keywords": [
6
6
  "claude",
package/public/app.js CHANGED
@@ -32,6 +32,7 @@ import { initToday } from '/today.js';
32
32
  import { reviewSpeech } from '/prvoice.js';
33
33
  import { initDesigns } from '/designs.js';
34
34
  import { initReviews } from '/reviews.js';
35
+ import { initBugHunt } from '/bughunt.js';
35
36
  import { drawDiagram } from '/diagram.js';
36
37
  import { initValue } from '/value.js';
37
38
  import { initCodeMap } from '/codemap.js';
@@ -263,6 +264,7 @@ const todayUi = initToday({
263
264
  openActions: () => actionsUi.open(),
264
265
  openIssues: () => issuesUi.open(),
265
266
  openReviews: () => reviewsUi.open(),
267
+ openBugs: () => bugsUi.open({ show: 'open' }),
266
268
  });
267
269
  $('#today-btn').onclick = () => todayUi.open();
268
270
  // Designs: every agent's design doc, the ones waiting for your review first.
@@ -279,6 +281,9 @@ $('#designs-btn').onclick = () => designsUi.open();
279
281
  // Reviews: other people's pull requests, reviewed by agents for you.
280
282
  const reviewsUi = initReviews({ api, $, esc, ago, toast: (m, ms) => toast(m, ms), openAgent: (id) => (showTab('agents'), select(id)) });
281
283
  $('#reviews-btn').onclick = () => reviewsUi.open();
284
+ // Bugs: background bug hunts and what they found.
285
+ const bugsUi = initBugHunt({ api, $, esc, ago, toast: (m, ms, a) => toast(m, ms, a), openAgent: (id) => (showTab('agents'), select(id)) });
286
+ $('#bugs-btn').onclick = () => bugsUi.open();
282
287
  // Value: what the delivered work is worth, for you and for management.
283
288
  const valueUi = initValue({ api, $, esc, toast: (m, ms) => toast(m, ms), openAgent: (id) => (showTab('agents'), select(id)) });
284
289
  $('#value-btn').onclick = () => valueUi.open();
@@ -330,6 +335,7 @@ function shortcut(act) {
330
335
  if (act === 'results') return $('#spend-btn').click();
331
336
  if (act === 'designs') return designsUi.open();
332
337
  if (act === 'reviews') return reviewsUi.open();
338
+ if (act === 'bugs') return bugsUi.open();
333
339
  if (act === 'value') return valueUi.open();
334
340
  if (act === 'today') return todayUi.open();
335
341
  if (act.startsWith('tab:')) return showTab(act.slice(4));
@@ -4239,6 +4245,7 @@ function handleEvent(msg) {
4239
4245
  todayUi.changed();
4240
4246
  designsUi.changed();
4241
4247
  if (msg.agent.reviewing) reviewsUi.changed();
4248
+ if (msg.agent.hunting) bugsUi.changed();
4242
4249
  // The detail, terminal and document views show one agent; another agent's update leaves them be.
4243
4250
  return invalidate([
4244
4251
  'list', 'backlog', 'land', 'inbox', 'race', 'team',
@@ -0,0 +1,316 @@
1
+ // Bugs: what background bug hunts found, checked, worst first; and the hunts themselves (a project
2
+ // or a folder of it, recent changes or the whole module, by hand or every night, with a cost
3
+ // limit per run). Each finding opens to its evidence; Fix starts an agent on it, File it opens a
4
+ // filled-in issue, Not a bug keeps it from coming back, Snooze hides it until later.
5
+
6
+ import { holdWhilePicking, rowKeys } from './rowkeys.js';
7
+ import { expandButton, expandable } from './expand.js';
8
+
9
+ const SAVED = 'agentmgr.bugsFilter';
10
+ const FILTERS = [
11
+ ['open', 'Open'],
12
+ ['fixing', 'Fixing'],
13
+ ['snoozed', 'Snoozed'],
14
+ ['filed', 'Filed'],
15
+ ['notbug', 'Not a bug'],
16
+ ['dropped', 'Not kept'],
17
+ ['hunts', 'Hunts'],
18
+ ];
19
+ const SEV = { critical: 'Critical', high: 'High', medium: 'Medium', low: 'Low' };
20
+
21
+ /** Tomorrow at 9, or next Monday at 9. */
22
+ function later(which) {
23
+ const d = new Date();
24
+ d.setHours(9, 0, 0, 0);
25
+ d.setDate(d.getDate() + (which === 'week' ? ((8 - d.getDay()) % 7 || 7) : 1));
26
+ return d.toISOString();
27
+ }
28
+
29
+ export function initBugHunt({ api, $, esc, ago, toast, openAgent }) {
30
+ const dialog = $('#bugs-dialog');
31
+ const body = $('#bugs-body');
32
+ let data = null;
33
+ let filter = 'open';
34
+ let opened = null; // the finding shown in full
35
+ let editing = null; // a hunt being added ('new') or edited (its id)
36
+ let sure = null; // a hunt whose Delete was pressed once
37
+ try {
38
+ filter = localStorage.getItem(SAVED) || 'open';
39
+ } catch {}
40
+ let projects = [];
41
+
42
+ async function load() {
43
+ try {
44
+ data = await api('GET', '/hunts');
45
+ } catch (e) {
46
+ toast?.(e.message, 5000);
47
+ }
48
+ badge();
49
+ render();
50
+ }
51
+
52
+ function badge() {
53
+ const n = data ? data.findings.filter((f) => f.status === 'open').length : 0;
54
+ const el = $('#bugs-count');
55
+ if (el) {
56
+ el.textContent = n ? String(n) : '';
57
+ el.title = n ? `${n} open bug${n === 1 ? '' : 's'} found by hunts` : '';
58
+ }
59
+ const b = $('#bugs-btn');
60
+ if (b) b.classList.toggle('hunting', Boolean(data?.running));
61
+ }
62
+
63
+ const count = (k) => (k === 'hunts' ? data.hunts.length : data.findings.filter((f) => f.status === k).length);
64
+ const where = (f) => (f.file ? `${f.file}${f.line ? `:${f.line}` : ''}` : '');
65
+
66
+ function findingRow(f) {
67
+ const acts =
68
+ f.status === 'open'
69
+ ? `<button class="small primary" data-bug="fix" title="Start an agent on it, with the failing test (a)">Fix</button>
70
+ <button class="small" data-bug="file" title="A filled-in issue to submit (i)">File it</button>
71
+ <button class="small" data-bug="notbug" title="Not a bug: it won't be reported again (x)">Not a bug</button>
72
+ <select class="small" data-bug-snooze title="Hide it until then (s: tomorrow)"><option value="">Snooze…</option><option value="day">Until tomorrow 9am</option><option value="week">Until Monday 9am</option></select>`
73
+ : f.status === 'fixing' && f.fixAgentId
74
+ ? `<button class="small" data-bug="open-fix" title="Open the agent fixing it">Open fix</button> <button class="small" data-bug="back" title="Back to open (o)">Bring back</button>`
75
+ : `<button class="small" data-bug="back" title="Back to open (o)">Bring back</button>`;
76
+ const full =
77
+ opened === f.id
78
+ ? `<tr class="bug-detail"><td colspan="3">
79
+ <p><b>How it fails.</b> ${esc(f.why)}</p>
80
+ <p><b>Evidence: ${f.evidence.type === 'test' ? 'a failing test' : 'the path through the code'}.</b></p><pre>${esc(f.evidence.detail)}</pre>
81
+ ${f.evidence.test ? `<p><b>Test.</b></p><pre>${esc(f.evidence.test)}</pre>` : ''}
82
+ ${f.fix ? `<p><b>Suggested fix.</b> ${esc(f.fix)}</p>` : ''}
83
+ <p class="hint">${f.check ? `Second check: ${f.check.real ? 'holds up' : 'does not hold up'} (${Math.round(f.check.confidence * 100)}%). ${esc(f.check.reason ?? '')}` : 'Second check: not asked (the AI judge is off); kept because a test fails.'} Found ${esc(ago(f.at))} by the ${esc(f.hunt ?? '')} hunt${f.foundBy ? ` · <button class="link" data-bug-agent="${esc(f.foundBy)}">its session</button>` : ''}.</p>
84
+ </td></tr>`
85
+ : '';
86
+ return `<tr data-row-id="${esc(f.id)}" class="bug-${esc(f.severity)}">
87
+ <td class="nowrap"><span class="bug-sev ${esc(f.severity)}">${esc(SEV[f.severity] ?? f.severity)}</span></td>
88
+ <td><div class="today-title">${esc(f.title)}</div><div class="hint">${esc(where(f))}${f.evidence?.type === 'test' ? ' · a test fails' : ''}${f.snoozeUntil ? ` · until ${esc(new Date(f.snoozeUntil).toLocaleString())}` : ''}</div></td>
89
+ <td class="nowrap today-acts">${acts}</td>
90
+ </tr>${full}`;
91
+ }
92
+
93
+ function huntForm(h) {
94
+ const p = h ?? { focus: 'changes', schedule: 'manual', maxUsd: 5, kinds: [], path: '', project: projects[0]?.shortcut ?? '' };
95
+ return `<form class="hunt-form alerts-body" data-hunt-form="${esc(h?.id ?? 'new')}">
96
+ <h3>${h ? `Edit ${esc(h.name)}` : 'New hunt'}</h3>
97
+ <div class="row three">
98
+ <label>Project <select name="project" required>${projects.map((x) => `<option value="${esc(x.shortcut)}" ${x.shortcut === p.project ? 'selected' : ''}>${esc(x.name ?? x.shortcut)}</option>`).join('')}</select></label>
99
+ <label>Folder <span class="hint">(empty: all of it)</span><input name="path" value="${esc(p.path)}" placeholder="pkg/providers" autocomplete="off" /></label>
100
+ <label>Name <span class="hint">(optional)</span><input name="name" value="${esc(h?.name ?? '')}" autocomplete="off" /></label>
101
+ </div>
102
+ <fieldset><legend>Look at</legend>${Object.entries(data.focus).map(([k, label]) => `<label class="check"><input type="radio" name="focus" value="${k}" ${p.focus === k ? 'checked' : ''} /> ${esc(label)}</label>`).join('')}</fieldset>
103
+ <fieldset><legend>For <span class="hint">(none ticked: any kind of bug)</span></legend><div class="hunt-kinds">${Object.entries(data.kinds).map(([k, label]) => `<label class="check"><input type="checkbox" name="kind" value="${k}" ${p.kinds.includes(k) ? 'checked' : ''} /> ${esc(label)}</label>`).join('')}</div></fieldset>
104
+ <div class="row three">
105
+ <label>When <select name="schedule">${Object.entries(data.schedules).map(([k, label]) => `<option value="${k}" ${p.schedule === k ? 'selected' : ''}>${esc(label)}</option>`).join('')}</select></label>
106
+ <label>Cost limit per run ($) <input name="maxUsd" type="number" min="0.5" max="500" step="0.5" value="${esc(p.maxUsd)}" /></label>
107
+ </div>
108
+ <p class="hint">The hunter reads the code and runs the tests on its own copy; it never commits or pushes. One hunt runs at a time, and it stops at the cost limit.</p>
109
+ <div class="dialog-actions"><button type="button" class="ghost" data-bug="cancel-hunt">Cancel</button><button type="submit" class="primary">${h ? 'Save' : 'Add hunt'}</button></div>
110
+ </form>`;
111
+ }
112
+
113
+ function huntsHtml() {
114
+ if (editing) return huntForm(editing === 'new' ? null : data.hunts.find((h) => h.id === editing));
115
+ const rows = data.hunts
116
+ .map((h) => {
117
+ const last = h.last ? `${h.last.status === 'running' ? 'running now' : `${h.last.kept ?? 0} kept of ${h.last.found ?? 0} new`} · ${ago(h.last.at)}` : 'not run yet';
118
+ return `<tr data-hunt="${esc(h.id)}">
119
+ <td><div class="today-title">${esc(h.name)}</div><div class="hint">${esc(h.focus === 'changes' ? 'recent changes' : `whole module${h.coveredCount ? ` (${h.coveredCount} parts covered)` : ''}`)}${h.kinds.length ? ` · ${esc(h.kinds.join(', '))}` : ''} · ${esc(h.schedule === 'nightly' ? 'nightly' : 'by hand')} · up to $${esc(h.maxUsd)}</div></td>
120
+ <td class="hint">${esc(last)}${h.open ? ` · ${h.open} open` : ''}</td>
121
+ <td class="nowrap today-acts"><button class="small primary" data-bug="run" ${data.running ? 'disabled title="A hunt is running; one at a time"' : 'title="Start a run now"'}>Hunt now</button> <button class="small" data-bug="edit">Edit</button> <button class="small ${sure === h.id ? 'danger' : ''}" data-bug="delete">${sure === h.id ? 'Delete it?' : 'Delete'}</button></td>
122
+ </tr>`;
123
+ })
124
+ .join('');
125
+ return `${rows ? `<div class="issues-scroll"><table class="issues today-table"><tbody>${rows}</tbody></table></div>` : '<p class="hint issues-empty">No hunts yet. A hunt looks for bugs in a project, or one folder of it, in the background: in what changed since its last run, or the whole module a part at a time. Each bug comes with evidence, and a second check keeps only those that hold up.</p>'}
126
+ <p><button class="small primary" data-bug="new-hunt" ${projects.length ? '' : 'disabled title="Add a project first"'}>+ New hunt</button></p>`;
127
+ }
128
+
129
+ function draw() {
130
+ if (!dialog.open) return;
131
+ if (!data) {
132
+ body.innerHTML = '<p class="hint">Loading…</p>';
133
+ return;
134
+ }
135
+ const rows = data.findings.filter((f) => f.status === filter);
136
+ const empty = {
137
+ open: data.hunts.length ? 'No open bugs. Hunts add what they find here, worst first.' : 'No bugs yet: set up a hunt under Hunts.',
138
+ dropped: "Findings the second check didn't confirm. They aren't reported again.",
139
+ };
140
+ body.innerHTML = `
141
+ <div class="issues-head">
142
+ <h2>Bugs</h2>
143
+ <div class="chips" role="tablist">${FILTERS.map(([k, label]) => `<button class="chip ${k === filter ? 'active' : ''}" role="tab" aria-selected="${k === filter}" data-bugs-filter="${k}">${label} <span class="count">${count(k)}</span></button>`).join('')}</div>
144
+ <span class="spacer"></span>
145
+ <button class="small" data-bug="refresh" title="Look again (r)">↻</button>
146
+ ${expandButton(dialog)}
147
+ <button class="small" data-bug="close" title="Close (Esc)">Close</button>
148
+ </div>
149
+ ${data.running ? `<p class="hunt-running">Hunting now: <button class="link" data-bug-agent="${esc(data.running.id)}">${esc(data.running.name)}</button>. Its findings come in when it's done.</p>` : ''}
150
+ ${filter === 'hunts'
151
+ ? huntsHtml()
152
+ : rows.length
153
+ ? `<div class="issues-scroll"><table class="issues today-table"><tbody>${rows.map(findingRow).join('')}</tbody></table></div>`
154
+ : `<p class="hint issues-empty">${esc(empty[filter] ?? 'None here.')}</p>`}
155
+ ${filter === 'hunts' ? '' : '<p class="hint">Keys: j/k move (or click a row), Enter shows the evidence, a fix, i file it, x not a bug, s snooze until tomorrow, o bring back, r look again, [ ] filters, f bigger.</p>'}`;
156
+ keys.redraw();
157
+ }
158
+ const render = holdWhilePicking(body, draw);
159
+ expandable(dialog, draw);
160
+
161
+ const finding = (id) => data?.findings.find((f) => f.id === id) ?? null;
162
+
163
+ /** Set findings to a decision; Undo puts each back. */
164
+ async function decide(ids, status, until = null, { undoing = false } = {}) {
165
+ const before = ids.map((id) => [id, finding(id)?.status, finding(id)?.snoozeUntil]);
166
+ try {
167
+ await api('POST', '/findings/set', { ids, status, until });
168
+ const label = { open: 'Back on the list', notbug: 'Not a bug: it won\'t be reported again', snoozed: 'Snoozed', filed: 'Marked filed' }[status];
169
+ const undo = undoing ? null : { label: 'Undo', run: async () => {
170
+ for (const [id, st, u] of before) if (st && st !== 'fixing') await decide([id], st, st === 'snoozed' ? u : null, { undoing: true });
171
+ } };
172
+ toast?.(label, undo ? 6000 : 2500, undo);
173
+ } catch (e) {
174
+ toast?.(e.message, 6000);
175
+ }
176
+ load();
177
+ }
178
+
179
+ async function act(id, what, extra) {
180
+ const f = finding(id);
181
+ if (!f) return;
182
+ if (what === 'fix') {
183
+ try {
184
+ const r = await api('POST', `/findings/${id}/fix`, {});
185
+ toast?.(r.existing ? `${r.agent.name} is on it already` : `Agent ${r.agent.name} started on it`, 4000, { label: 'Open', run: () => (dialog.close(), openAgent(r.agent.id)) });
186
+ } catch (e) {
187
+ toast?.(e.message, 6000);
188
+ }
189
+ return load();
190
+ }
191
+ if (what === 'file') {
192
+ try {
193
+ const r = await api('GET', `/findings/${id}/issue`);
194
+ if (r.url) window.open(r.url, '_blank', 'noopener');
195
+ else await navigator.clipboard?.writeText(`# ${r.title}\n\n${r.markdown}`).catch(() => {});
196
+ return decide([id], 'filed', null).then(() => toast?.(r.url ? 'GitHub opened with the issue filled in: submit it there' : 'Copied as Markdown, to paste into your tracker', 5000));
197
+ } catch (e) {
198
+ return toast?.(e.message, 6000);
199
+ }
200
+ }
201
+ if (what === 'notbug') return decide([id], 'notbug');
202
+ if (what === 'snooze') return decide([id], 'snoozed', later(extra || 'day'));
203
+ if (what === 'back') return decide([id], 'open');
204
+ if (what === 'open-fix' && f.fixAgentId) return dialog.close(), openAgent(f.fixAgentId);
205
+ if (what === 'enter') {
206
+ opened = opened === id ? null : id;
207
+ return render();
208
+ }
209
+ }
210
+
211
+ const keys = rowKeys(dialog, {
212
+ rows: () => [...body.querySelectorAll('tbody tr[data-row-id]')],
213
+ filters: () => [...body.querySelectorAll('[data-bugs-filter]')],
214
+ keys: {
215
+ Enter: (r) => act(r.dataset.rowId, 'enter'),
216
+ a: (r) => act(r.dataset.rowId, 'fix'),
217
+ i: (r) => act(r.dataset.rowId, 'file'),
218
+ x: (r) => act(r.dataset.rowId, 'notbug'),
219
+ s: (r) => act(r.dataset.rowId, 'snooze', 'day'),
220
+ o: (r) => act(r.dataset.rowId, 'back'),
221
+ r: Object.assign(() => load(), { needsRow: false }),
222
+ },
223
+ });
224
+
225
+ async function hunt(id, what) {
226
+ try {
227
+ if (what === 'run') {
228
+ const r = await api('POST', `/hunts/${id}/run`, {});
229
+ toast?.(`${r.agent.name} is hunting. Its findings come in when it's done.`, 5000);
230
+ } else if (what === 'edit') {
231
+ editing = id;
232
+ sure = null;
233
+ return render();
234
+ } else if (what === 'delete') {
235
+ if (sure !== id) {
236
+ sure = id;
237
+ return render();
238
+ }
239
+ sure = null;
240
+ await api('DELETE', `/hunts/${id}`);
241
+ toast?.('Hunt deleted; its findings stay', 3000);
242
+ }
243
+ } catch (e) {
244
+ toast?.(e.message, 6000);
245
+ }
246
+ load();
247
+ }
248
+
249
+ body.addEventListener('change', (e) => {
250
+ const s = e.target.closest('[data-bug-snooze]');
251
+ if (s && s.value) act(e.target.closest('tr[data-row-id]')?.dataset.rowId, 'snooze', s.value);
252
+ });
253
+
254
+ body.addEventListener('submit', async (e) => {
255
+ const form = e.target.closest('[data-hunt-form]');
256
+ if (!form) return;
257
+ e.preventDefault();
258
+ const fd = new FormData(form);
259
+ const input = { project: fd.get('project'), path: fd.get('path'), name: fd.get('name'), focus: fd.get('focus'), kinds: fd.getAll('kind'), schedule: fd.get('schedule'), maxUsd: Number(fd.get('maxUsd')) };
260
+ try {
261
+ const id = form.dataset.huntForm;
262
+ await api(id === 'new' ? 'POST' : 'PUT', id === 'new' ? '/hunts' : `/hunts/${id}`, input);
263
+ editing = null;
264
+ toast?.(id === 'new' ? 'Hunt added: press Hunt now to start it' : 'Saved', 3000);
265
+ } catch (err) {
266
+ return toast?.(err.message, 6000);
267
+ }
268
+ load();
269
+ });
270
+
271
+ body.addEventListener('click', (e) => {
272
+ const ag = e.target.closest('[data-bug-agent]');
273
+ if (ag) return dialog.close(), openAgent(ag.dataset.bugAgent);
274
+ const f = e.target.closest('[data-bugs-filter]');
275
+ if (f) {
276
+ filter = f.dataset.bugsFilter;
277
+ editing = null;
278
+ try {
279
+ localStorage.setItem(SAVED, filter);
280
+ } catch {}
281
+ return render();
282
+ }
283
+ const b = e.target.closest('[data-bug]')?.dataset.bug;
284
+ if (!b) {
285
+ // A click on a finding's title shows its evidence.
286
+ const row = e.target.closest('tr[data-row-id]');
287
+ if (row && e.target.closest('.today-title')) act(row.dataset.rowId, 'enter');
288
+ return;
289
+ }
290
+ if (b === 'close') return dialog.close();
291
+ if (b === 'refresh') return load();
292
+ if (b === 'new-hunt') return (editing = 'new'), render();
293
+ if (b === 'cancel-hunt') return (editing = null), render();
294
+ const huntRow = e.target.closest('tr[data-hunt]');
295
+ if (huntRow) return hunt(huntRow.dataset.hunt, b);
296
+ act(e.target.closest('tr[data-row-id]')?.dataset.rowId, b);
297
+ });
298
+
299
+ async function open({ show } = {}) {
300
+ if (dialog.open && !show) return dialog.close();
301
+ if (show) filter = show;
302
+ if (!dialog.open) dialog.showModal();
303
+ render();
304
+ projects = await api('GET', '/projects').catch(() => []);
305
+ load();
306
+ }
307
+
308
+ let again = null;
309
+ function changed() {
310
+ clearTimeout(again);
311
+ again = setTimeout(load, dialog.open ? 1500 : 20_000);
312
+ }
313
+
314
+ load();
315
+ return { open, changed, load, decide, fix: (id) => act(id, 'fix') };
316
+ }
package/public/index.html CHANGED
@@ -36,6 +36,7 @@
36
36
  <button id="actions-btn" title="Actions: what's asked of you in Slack and in meeting notes, found by the assistant; decide on each one">Actions <span id="actions-count" class="badge ready"></span></button>
37
37
  <button id="issues-btn" title="Jira: every issue an agent works on, with its Jira status, pull request and agent, the ones waiting for your review first">Jira <span id="issues-count" class="badge ready"></span></button>
38
38
  <button id="designs-btn" title="Designs: every agent's design doc with its summary and links, the ones waiting for your review first">Designs <span id="designs-count" class="badge ready"></span></button>
39
+ <button id="bugs-btn" title="Bugs: background hunts in a project or folder, and what they found, checked and worst first">Bugs <span id="bugs-count" class="badge"></span></button>
39
40
  <button id="reviews-btn" title="Reviews: pull requests you review. Reviewer agents ask the critical questions and find what blocks approval; you post what you pick">Reviews <span id="reviews-count" class="badge ready"></span></button>
40
41
  <button id="value-btn" title="Value: what the delivered work is worth, by day, week, month and quarter, against the AI cost and your time; reports for management">Value</button>
41
42
  <button id="map-btn" title="The codebase map: where each agent is changing and reading code, and who is about to collide">Map</button>
@@ -395,6 +396,9 @@
395
396
  <dialog id="designs-dialog" class="issues-dialog" aria-label="Design docs">
396
397
  <div id="designs-body"></div>
397
398
  </dialog>
399
+ <dialog id="bugs-dialog" class="issues-dialog" aria-label="Bugs">
400
+ <div id="bugs-body"></div>
401
+ </dialog>
398
402
  <dialog id="reviews-dialog" class="issues-dialog" aria-label="Reviews">
399
403
  <div id="reviews-body"></div>
400
404
  </dialog>
package/public/keys.js CHANGED
@@ -13,6 +13,7 @@ export const SHORTCUTS = [
13
13
  ]],
14
14
  ['Anywhere', [
15
15
  [['y'], 'Today: what needs you, most pressing first', 'today'],
16
+ [['b'], 'Bugs: what bug hunts found, and the hunts', 'bugs'],
16
17
  [['n'], 'New agents', 'new'],
17
18
  [['a'], 'Ask Agent (a general session)', 'ask'],
18
19
  [['/'], 'Filter agents', 'filter'],
@@ -61,11 +62,11 @@ export const SHORTCUTS = [
61
62
  // A single key, as an event names it, to its action.
62
63
  export const SINGLE = {
63
64
  j: 'next', k: 'prev', Enter: 'terminal', t: 'terminal',
64
- r: 'changes', s: 'start', X: 'stop', e: 'edit', n: 'new', a: 'ask', '/': 'filter', w: 'watch', p: 'standup', m: 'map', i: 'issues', o: 'actions', h: 'assistant', ',': 'settings', d: 'designs', g: 'reviews', v: 'value', y: 'today', '?': 'help',
65
+ r: 'changes', s: 'start', X: 'stop', e: 'edit', n: 'new', a: 'ask', '/': 'filter', w: 'watch', p: 'standup', m: 'map', i: 'issues', o: 'actions', h: 'assistant', ',': 'settings', d: 'designs', g: 'reviews', v: 'value', y: 'today', b: 'bugs', '?': 'help',
65
66
  1: 'tab:agents', 2: 'tab:inbox', 3: 'tab:backlog', 4: 'tab:land', 5: 'tab:built',
66
67
  };
67
68
  // While Watch is open: only what makes sense there.
68
- const ON_WATCH = new Set(['today', 'new', 'ask', 'watch', 'standup', 'map', 'issues', 'actions', 'assistant', 'settings', 'designs', 'reviews', 'value', 'help']);
69
+ const ON_WATCH = new Set(['today', 'new', 'ask', 'watch', 'standup', 'map', 'issues', 'actions', 'assistant', 'settings', 'designs', 'reviews', 'value', 'bugs', 'help']);
69
70
 
70
71
  /** Typing somewhere: a field, an editor or a terminal (xterm types through a textarea). */
71
72
  const typing = (el) => Boolean(el?.closest?.('input, textarea, select, [contenteditable=""], [contenteditable="true"], .xterm, .cm-editor'));
package/public/style.css CHANGED
@@ -1321,3 +1321,19 @@ table.issues tr.kb-on td:first-child { box-shadow: inset 3px 0 0 var(--accent);
1321
1321
  .support-shot-acts { display: flex; justify-content: flex-end; margin-top: 6px; }
1322
1322
  #support-earlier ul { margin: 6px 0; padding-left: 18px; font-size: 13px; }
1323
1323
  #support-earlier summary { cursor: pointer; font-size: 13px; }
1324
+
1325
+ /* Bugs */
1326
+ .bug-sev { display: inline-block; padding: 1px 8px; border-radius: 10px; font-size: 11px; font-weight: 600; border: 1px solid currentColor; }
1327
+ .bug-sev.critical, .bug-sev.high { color: var(--red); }
1328
+ .bug-sev.medium { color: var(--amber, #c98a12); }
1329
+ .bug-sev.low { color: var(--muted); }
1330
+ tr.bug-detail td { padding: 4px 12px 14px; font-size: 13px; }
1331
+ tr.bug-detail pre { white-space: pre-wrap; max-height: 280px; overflow: auto; padding: 8px; border: 1px solid var(--border); border-radius: 6px; font-size: 12px; }
1332
+ .hunt-running { margin: 0 0 8px; padding: 6px 10px; border-left: 3px solid var(--accent, currentColor); font-size: 13px; }
1333
+ .hunt-form { padding: 8px 0; }
1334
+ .hunt-form h3 { margin: 0; font-size: 15px; }
1335
+ .hunt-kinds { display: grid; grid-template-columns: repeat(auto-fill, minmax(240px, 1fr)); gap: 4px 16px; }
1336
+ #bugs-btn.hunting::after { content: ' ●'; color: var(--accent, currentColor); }
1337
+ .today-bug .today-label { color: var(--red); }
1338
+ #bugs-dialog td.today-acts { white-space: normal; text-align: right; }
1339
+ #bugs-dialog td.today-acts > * { margin: 2px 0; }
package/public/today.js CHANGED
@@ -10,7 +10,7 @@ import { expandButton, expandable } from './expand.js';
10
10
  // Up to this score an item is pressing: it counts on the button.
11
11
  const PRESSING = 32;
12
12
 
13
- export function initToday({ api, $, esc, ago, openAgent, showInbox, openActions, openIssues, openReviews, toast }) {
13
+ export function initToday({ api, $, esc, ago, openAgent, showInbox, openActions, openIssues, openReviews, openBugs, toast }) {
14
14
  const dialog = $('#today-dialog');
15
15
  const body = $('#today-body');
16
16
  let data = null;
@@ -54,6 +54,7 @@ export function initToday({ api, $, esc, ago, openAgent, showInbox, openActions,
54
54
  if (it.kind === 'pr-requested') return [btn('review', 'Review it', 'A reviewer agent reads it and finds what blocks approval (a)', true), link(it.url, 'PR')].join(' ');
55
55
  if (it.kind === 'pr-ready') return [btn('open-reviews', 'Open review', 'Pick what to post (Enter)', true), link(it.url, 'PR')].join(' ');
56
56
  if (it.kind === 'rule') return btn('inbox', 'Inbox', 'Decide in the inbox (Enter)', true);
57
+ if (it.kind === 'bug') return [btn('fix', 'Fix', 'Start an agent on it, with the failing test (a)', true), btn('skip', 'Snooze', 'Until tomorrow 9am (s)'), btn('notbug', 'Not a bug', "It won't be reported again"), btn('bugs', 'Evidence', 'See it in Bugs (Enter)')].join(' ');
57
58
  return [it.agentId ? btn('open', 'Open', "Open the agent's session (Enter)", it.score < 20) : '', link(it.url, it.issueKey ? 'Jira' : 'Link')].join(' ');
58
59
  }
59
60
 
@@ -161,6 +162,10 @@ export function initToday({ api, $, esc, ago, openAgent, showInbox, openActions,
161
162
  dialog.close();
162
163
  return openReviews();
163
164
  }
165
+ if (what === 'bugs' || (what === 'enter' && it.kind === 'bug')) {
166
+ dialog.close();
167
+ return openBugs?.();
168
+ }
164
169
  if (what === 'enter') {
165
170
  if (it.kind === 'action') {
166
171
  dialog.close();
@@ -186,6 +191,15 @@ export function initToday({ api, $, esc, ago, openAgent, showInbox, openActions,
186
191
  const bad = r.failed.map((x) => x.reason).join('; ');
187
192
  if (bad || r.started.length) toast?.(bad ? `Not changed: ${bad}` : `Started an agent on ${it.title}`, bad ? 6000 : 3000);
188
193
  else changedWith(`${it.title}: skipped`, `skipped ${it.issueKey}`, () => api('POST', '/issues/action', { keys: [it.issueKey], action: null }));
194
+ } else if (it.kind === 'bug' && (what === 'fix' || what === 'assign')) {
195
+ const r = await api('POST', `/findings/${it.findingId}/fix`, {});
196
+ toast?.(r.existing ? `${r.agent.name} is on it already` : `Agent ${r.agent.name} started on it`, 4000);
197
+ } else if (it.kind === 'bug' && ['skip', 'notbug'].includes(what)) {
198
+ const t = new Date();
199
+ t.setDate(t.getDate() + 1);
200
+ t.setHours(9, 0, 0, 0);
201
+ await api('POST', '/findings/set', { ids: [it.findingId], status: what === 'skip' ? 'snoozed' : 'notbug', until: what === 'skip' ? t.toISOString() : null });
202
+ changedWith(what === 'skip' ? 'Snoozed until tomorrow 9am' : "Not a bug: it won't be reported again", what === 'skip' ? 'snoozed' : 'not a bug', () => api('POST', '/findings/set', { ids: [it.findingId], status: 'open' }));
189
203
  } else if (it.kind === 'pr-requested' && (what === 'review' || what === 'assign')) {
190
204
  const a = await api('POST', '/reviews', { url: it.reviewUrl });
191
205
  toast?.(`Reviewer ${a.name ?? 'agent'} started`, 3000);
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/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(() => {});
package/src/server.js CHANGED
@@ -52,6 +52,7 @@ import { Value, valueSlack } from './value.js';
52
52
  import { Store } from './store.js';
53
53
  import { about, latestRelease } from './about.js';
54
54
  import { Support } from './support.js';
55
+ import { BugHunts } from './bughunt.js';
55
56
 
56
57
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
57
58
  const require = createRequire(import.meta.url);
@@ -97,6 +98,9 @@ export async function startServer({ port = PORT, host = HOST } = {}) {
97
98
  const proposed = new ProposedIssues({ store, manager });
98
99
  const myActions = new MyActions({ store, manager });
99
100
  const reviews = new Reviews({ manager, store, log: (m) => console.log(`[agentmgr] ${m}`) });
101
+ // Bug hunts: the judge checks each finding when it's on (else only failing tests are kept).
102
+ const hunts = new BugHunts({ manager, store, judge: manager.judge, log: (m) => console.log(`[agentmgr] ${m}`) });
103
+ hunts.startTimer();
100
104
  const races = new Races({ manager, store });
101
105
  const review = new Review({ manager });
102
106
  // The walkthrough explains the same diff the review screen shows.
@@ -912,7 +916,8 @@ export async function startServer({ port = PORT, host = HOST } = {}) {
912
916
  f.slack || f.gemini ? got('actions', () => myActions.rows()) : [],
913
917
  got('reviews', () => reviews.rows()),
914
918
  ]);
915
- const items = todayItems({ inbox, issues, actions, reviews: prs });
919
+ const findings = hunts.list().findings.filter((x) => x.status === 'open');
920
+ const items = todayItems({ inbox, issues, actions, reviews: prs, findings });
916
921
  return { items, aside: todayAside({ issues, actions }), speech: todaySpeech(items), features: f, errors };
917
922
  }));
918
923
  // Support tickets: kept on this computer, each with a filled-in link to a new GitHub issue.
@@ -933,6 +938,18 @@ export async function startServer({ port = PORT, host = HOST } = {}) {
933
938
  res.status(e.status ?? 500).json({ error: e.message });
934
939
  }
935
940
  });
941
+ // Bug hunts and what they found.
942
+ api.get('/hunts', wrap(async () => {
943
+ await hunts.sweep();
944
+ return hunts.list();
945
+ }));
946
+ api.post('/hunts', wrap((req) => hunts.add(req.body ?? {})));
947
+ api.put('/hunts/:id', wrap((req) => hunts.update(req.params.id, req.body ?? {})));
948
+ api.delete('/hunts/:id', wrap((req) => hunts.remove(req.params.id)));
949
+ api.post('/hunts/:id/run', wrap((req) => hunts.run(req.params.id)));
950
+ api.post('/findings/set', wrap((req) => hunts.set(Array.isArray(req.body?.ids) ? req.body.ids.map(String) : [], req.body?.status, { until: req.body?.until ?? null })));
951
+ api.post('/findings/:id/fix', wrap((req) => hunts.fix(req.params.id)));
952
+ api.get('/findings/:id/issue', wrap((req) => hunts.issue(req.params.id)));
936
953
  api.get('/standup', wrap(() => standup.view()));
937
954
  api.post('/standup', wrap(async () => ({ ...standup.view(), latest: await standup.make({ reason: 'asked' }) })));
938
955
  api.put('/standup', wrap((req) => {
@@ -1342,6 +1359,7 @@ export async function startServer({ port = PORT, host = HOST } = {}) {
1342
1359
  standup.close();
1343
1360
  value.close();
1344
1361
  reviews.close();
1362
+ hunts.close();
1345
1363
  autopilot.close();
1346
1364
  goals.close();
1347
1365
  worklog.close();
@@ -1390,6 +1408,7 @@ export async function startServer({ port = PORT, host = HOST } = {}) {
1390
1408
  .catch((err) => console.error(`[agentmgr] could not join the hub ${process.env.AGENTMGR_HUB_URL}: ${err.message}`));
1391
1409
  }
1392
1410
  return {
1411
+ hunts,
1393
1412
  hubLink,
1394
1413
  server,
1395
1414
  manager,
package/src/today.js CHANGED
@@ -59,7 +59,7 @@ const INBOX = {
59
59
  * The list: [{ id, kind, label, title, why, score, at, agentId?, url?, actionId?, issueKey?, reviewUrl? }],
60
60
  * most pressing first. Each source may be missing (turned off, or it couldn't be had).
61
61
  */
62
- export function todayItems({ inbox = [], issues = [], actions = [], reviews = [], now = new Date() } = {}) {
62
+ export function todayItems({ inbox = [], issues = [], actions = [], reviews = [], findings = [], now = new Date() } = {}) {
63
63
  const items = [];
64
64
  // The issue each agent works on: named on its questions, and not listed twice.
65
65
  const issueOfAgent = new Map(issues.filter((r) => r.agent?.id).map((r) => [r.agent.id, r]));
@@ -100,6 +100,11 @@ export function todayItems({ inbox = [], issues = [], actions = [], reviews = []
100
100
  items.push({ id: `pr:${r.pr.url}`, kind: 'pr-ready', label: 'Review', title, why: `${r.agent.name}'s review is ready to post: ${verdict}${r.stale ? ' (the author pushed since)' : ''}`, score: 32, at: r.updatedAt ?? null, agentId: r.agent.id, url: r.pr.url, reviewUrl: r.pr.url });
101
101
  }
102
102
  }
103
+ // Bugs a hunt found and the check confirmed: the serious ones (the rest wait in the Bugs list).
104
+ for (const f of findings) {
105
+ if (f.status !== 'open' || !['critical', 'high'].includes(f.severity)) continue;
106
+ items.push({ id: `bug:${f.id}`, kind: 'bug', label: 'Bug', title: f.title, why: `${f.severity === 'critical' ? 'Critical' : 'High'}: found by the ${f.hunt ?? 'bug'} hunt${f.file ? ` in ${f.file}${f.line ? `:${f.line}` : ''}` : ''}${f.evidence?.type === 'test' ? ' · a test fails' : ''}`, score: f.severity === 'critical' ? 28 : 38, at: f.at ?? null, findingId: f.id });
107
+ }
103
108
  return items.sort((x, y) => x.score - y.score || String(y.at ?? '').localeCompare(String(x.at ?? '')));
104
109
  }
105
110