ai-agentmanager 1.29.0 → 1.31.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,13 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.31.0 (2026-11-08)
4
+
5
+ - **Bugs on the Map.** The Map has a *Bugs* view (next to *Agents*): each folder is coloured by the bugs hunts found in it, the worst weighing most, plus a little for how often it changed in the last 30 days, and its bug count shows on it. Bugs that come with their path through the code (`file:line` steps) are drawn as arrows from folder to folder along it: the hot paths, thicker where more (and worse) bugs go the same way. Folders no hunt has looked at are hatched. Click a folder or an arrow for its bugs, with *Fix* and *Evidence*, or *Hunt here* to start a hunt on that folder.
6
+
7
+ ## 1.30.0 (2026-11-07)
8
+
9
+ - **Bug hunts fix what they find.** Turn on *Fix automatically* on a hunt, and the bugs it finds at or above the severity you pick (high and up by default) are fixed without you: each by its own agent on its own branch, which must add a test that fails before the fix and passes after, and pass the whole suite. The hunt's test command (optional) is run on the fix too, and the AI judge, when it's on, reviews the change. Only then is a **draft** pull request opened, with the bug, the test and the checks in its description; nothing is merged. They show in Today as *Fix ready* and under Bugs → *Draft PRs*. At most 3 a run, within the hunt's cost limit. A fix that doesn't hold up stays in the list with the reason, and with *file it as an issue* on, it's filed on GitHub so it isn't lost.
10
+
3
11
  ## 1.29.0 (2026-11-07)
4
12
 
5
13
  - **Questions for you, with answers ready.** The assistant now also finds questions put to you in Slack (and email and meeting notes, with those on), including ones you're only copied or mentioned on, and prepares an answer for each: it reads the thread and checks the code of your projects, Jira and docs. They show in Today (*Asked you* is pressing, *CC'd* can wait) and under Actions → Questions, with the draft to *Copy*, *Edit*, or *Draft again*, and *Thread* to open where it was asked. A question without a draft has *Draft an answer*, which starts a session that researches it. Nothing is ever sent for you. (`agentmgr actions add --question … [--cc]`, `agentmgr actions answer <id> "<text>"`.)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ai-agentmanager",
3
- "version": "1.29.0",
3
+ "version": "1.31.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
@@ -203,7 +203,7 @@ const watchUi = initWatch({
203
203
  $('#watch-btn').onclick = () => (mapUi.isOpen() && mapUi.show(false), watchUi.show(!watchUi.isOpen()));
204
204
 
205
205
  // Map: where each agent is in the code, and who is about to collide.
206
- const mapUi = initCodeMap({ api, $, esc, agents, toast: (m, ms) => toast(m, ms), openAgent: (id) => (showTab('agents'), select(id)) });
206
+ const mapUi = initCodeMap({ api, $, esc, agents, toast: (m, ms, a) => toast(m, ms, a), openAgent: (id) => (showTab('agents'), select(id)), openBugs: () => bugsUi.open({ show: 'open' }) });
207
207
  $('#map-btn').onclick = () => (watchUi.isOpen() && watchUi.show(false), mapUi.show(!mapUi.isOpen()));
208
208
 
209
209
  // The standup: each agent's news read aloud, stopping on the ones that need you.
@@ -265,7 +265,7 @@ const todayUi = initToday({
265
265
  openActions: () => actionsUi.open(),
266
266
  openIssues: () => issuesUi.open(),
267
267
  openReviews: () => reviewsUi.open(),
268
- openBugs: () => bugsUi.open({ show: 'open' }),
268
+ openBugs: (show = 'open') => bugsUi.open({ show }),
269
269
  openChanges: (id) => (showTab('agents'), select(id), reviewUi.open(id)),
270
270
  });
271
271
  $('#today-btn').onclick = () => todayUi.open();
package/public/bughunt.js CHANGED
@@ -1,7 +1,8 @@
1
1
  // Bugs: what background bug hunts found, checked, worst first; and the hunts themselves (a project
2
2
  // or a folder of it, recent changes or the whole module, by hand or every night, with a cost
3
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.
4
+ // filled-in issue, Not a bug keeps it from coming back, Snooze hides it until later. A hunt can
5
+ // fix the serious ones itself: those come as draft pull requests, under Draft PRs.
5
6
 
6
7
  import { holdWhilePicking, rowKeys } from './rowkeys.js';
7
8
  import { expandButton, expandable } from './expand.js';
@@ -10,9 +11,11 @@ const SAVED = 'agentmgr.bugsFilter';
10
11
  const FILTERS = [
11
12
  ['open', 'Open'],
12
13
  ['fixing', 'Fixing'],
14
+ ['pr', 'Draft PRs'],
13
15
  ['snoozed', 'Snoozed'],
14
16
  ['filed', 'Filed'],
15
17
  ['notbug', 'Not a bug'],
18
+ ['done', 'Done'],
16
19
  ['dropped', 'Not kept'],
17
20
  ['hunts', 'Hunts'],
18
21
  ];
@@ -70,9 +73,21 @@ export function initBugHunt({ api, $, esc, ago, toast, openAgent }) {
70
73
  <button class="small" data-bug="file" title="A filled-in issue to submit (i)">File it</button>
71
74
  <button class="small" data-bug="notbug" title="Not a bug: it won't be reported again (x)">Not a bug</button>
72
75
  <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
+ : f.status === 'pr'
77
+ ? `${f.prUrl ? `<a class="small-link primary-link" href="${esc(f.prUrl)}" target="_blank" rel="noopener" title="The draft pull request: look it over, then mark it ready">Open PR ↗</a>` : ''}
78
+ <button class="small" data-bug="done" title="You looked at it: off the list (d)">Done</button>
79
+ ${f.fixAgentId ? '<button class="small" data-bug="open-fix" title="The session that fixed it">Session</button>' : ''}`
80
+ : f.status === 'fixing' && f.fixAgentId
81
+ ? `<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>`
82
+ : `<button class="small" data-bug="back" title="Back to open (o)">Bring back</button>`;
83
+ const auto =
84
+ f.auto?.state === 'fixing'
85
+ ? ' · fixing automatically'
86
+ : f.auto?.state === 'failed'
87
+ ? ` · the automatic fix didn't hold up: ${f.auto.reason}`
88
+ : f.status === 'pr'
89
+ ? ' · fixed automatically: a draft pull request'
90
+ : '';
76
91
  const full =
77
92
  opened === f.id
78
93
  ? `<tr class="bug-detail"><td colspan="3">
@@ -80,18 +95,20 @@ export function initBugHunt({ api, $, esc, ago, toast, openAgent }) {
80
95
  <p><b>Evidence: ${f.evidence.type === 'test' ? 'a failing test' : 'the path through the code'}.</b></p><pre>${esc(f.evidence.detail)}</pre>
81
96
  ${f.evidence.test ? `<p><b>Test.</b></p><pre>${esc(f.evidence.test)}</pre>` : ''}
82
97
  ${f.fix ? `<p><b>Suggested fix.</b> ${esc(f.fix)}</p>` : ''}
98
+ ${f.auto?.check ? `<p class="hint">The fix was reviewed by the AI judge: ${esc(f.auto.check.reason ?? '')} (${Math.round(f.auto.check.confidence * 100)}%).</p>` : ''}
99
+ ${f.issueUrl ? `<p class="hint">Filed: <a href="${esc(f.issueUrl)}" target="_blank" rel="noopener">${esc(f.issueUrl)}</a></p>` : ''}
83
100
  <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
101
  </td></tr>`
85
102
  : '';
86
103
  return `<tr data-row-id="${esc(f.id)}" class="bug-${esc(f.severity)}">
87
104
  <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>
105
+ <td><div class="today-title">${esc(f.title)}</div><div class="hint">${esc(where(f))}${f.evidence?.type === 'test' ? ' · a test fails' : ''}${esc(auto)}${f.snoozeUntil ? ` · until ${esc(new Date(f.snoozeUntil).toLocaleString())}` : ''}</div></td>
89
106
  <td class="nowrap today-acts">${acts}</td>
90
107
  </tr>${full}`;
91
108
  }
92
109
 
93
110
  function huntForm(h) {
94
- const p = h ?? { focus: 'changes', schedule: 'manual', maxUsd: 5, kinds: [], path: '', project: projects[0]?.shortcut ?? '' };
111
+ const p = h ?? { focus: 'changes', schedule: 'manual', maxUsd: 5, kinds: [], path: '', project: projects[0]?.shortcut ?? '', autoFix: false, fixAt: 'high', fileIssues: false, testCommand: '' };
95
112
  return `<form class="hunt-form alerts-body" data-hunt-form="${esc(h?.id ?? 'new')}">
96
113
  <h3>${h ? `Edit ${esc(h.name)}` : 'New hunt'}</h3>
97
114
  <div class="row three">
@@ -106,6 +123,14 @@ export function initBugHunt({ api, $, esc, ago, toast, openAgent }) {
106
123
  <label>Cost limit per run ($) <input name="maxUsd" type="number" min="0.5" max="500" step="0.5" value="${esc(p.maxUsd)}" /></label>
107
124
  </div>
108
125
  <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>
126
+ <fieldset><legend>Fix automatically</legend>
127
+ <label class="check"><input type="checkbox" name="autoFix" ${p.autoFix ? 'checked' : ''} /> Fix the bugs it finds, from
128
+ <select name="fixAt" class="small">${Object.entries(SEV).map(([k, label]) => `<option value="${k}" ${(p.fixAt ?? 'high') === k ? 'selected' : ''}>${esc(label)}${k === 'critical' ? ' only' : ' and up'}</option>`).join('')}</select>,
129
+ as draft pull requests</label>
130
+ <label>Test command <span class="hint">(optional: run on each fix before its pull request, like npm test)</span><input name="testCommand" value="${esc(p.testCommand ?? '')}" placeholder="npm test" autocomplete="off" /></label>
131
+ <label class="check"><input type="checkbox" name="fileIssues" ${p.fileIssues ? 'checked' : ''} /> When a fix doesn't hold up, file the bug as a GitHub issue <span class="hint">(issues on a public repository are public)</span></label>
132
+ <p class="hint">Each fix is made by its own agent on its own branch: its test must fail before and pass after, the whole suite must pass, and the AI judge (when it's on) reviews the change. Only then is a <b>draft</b> pull request opened; nothing is merged. At most 3 a run, within the cost limit above.</p>
133
+ </fieldset>
109
134
  <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
135
  </form>`;
111
136
  }
@@ -116,7 +141,7 @@ export function initBugHunt({ api, $, esc, ago, toast, openAgent }) {
116
141
  .map((h) => {
117
142
  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
143
  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>
144
+ <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)}${h.autoFix ? ` · fixes ${esc(h.fixAt === 'critical' ? 'critical ones' : `${h.fixAt} and up`)} as draft PRs` : ''}</div></td>
120
145
  <td class="hint">${esc(last)}${h.open ? ` · ${h.open} open` : ''}</td>
121
146
  <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
147
  </tr>`;
@@ -136,6 +161,7 @@ export function initBugHunt({ api, $, esc, ago, toast, openAgent }) {
136
161
  const empty = {
137
162
  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
163
  dropped: "Findings the second check didn't confirm. They aren't reported again.",
164
+ pr: 'No draft pull requests. A hunt with Fix automatically on opens one for each bug it fixes and the checks accept.',
139
165
  };
140
166
  body.innerHTML = `
141
167
  <div class="issues-head">
@@ -152,7 +178,7 @@ export function initBugHunt({ api, $, esc, ago, toast, openAgent }) {
152
178
  : rows.length
153
179
  ? `<div class="issues-scroll"><table class="issues today-table"><tbody>${rows.map(findingRow).join('')}</tbody></table></div>`
154
180
  : `<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>'}`;
181
+ ${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, d done (a draft PR looked at), o bring back, r look again, [ ] filters, f bigger.</p>'}`;
156
182
  keys.redraw();
157
183
  }
158
184
  const render = holdWhilePicking(body, draw);
@@ -165,7 +191,7 @@ export function initBugHunt({ api, $, esc, ago, toast, openAgent }) {
165
191
  const before = ids.map((id) => [id, finding(id)?.status, finding(id)?.snoozeUntil]);
166
192
  try {
167
193
  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];
194
+ const label = { open: 'Back on the list', notbug: 'Not a bug: it won\'t be reported again', snoozed: 'Snoozed', filed: 'Marked filed', done: 'Done' }[status];
169
195
  const undo = undoing ? null : { label: 'Undo', run: async () => {
170
196
  for (const [id, st, u] of before) if (st && st !== 'fixing') await decide([id], st, st === 'snoozed' ? u : null, { undoing: true });
171
197
  } };
@@ -199,6 +225,7 @@ export function initBugHunt({ api, $, esc, ago, toast, openAgent }) {
199
225
  }
200
226
  }
201
227
  if (what === 'notbug') return decide([id], 'notbug');
228
+ if (what === 'done') return decide([id], 'done');
202
229
  if (what === 'snooze') return decide([id], 'snoozed', later(extra || 'day'));
203
230
  if (what === 'back') return decide([id], 'open');
204
231
  if (what === 'open-fix' && f.fixAgentId) return dialog.close(), openAgent(f.fixAgentId);
@@ -218,6 +245,7 @@ export function initBugHunt({ api, $, esc, ago, toast, openAgent }) {
218
245
  x: (r) => act(r.dataset.rowId, 'notbug'),
219
246
  s: (r) => act(r.dataset.rowId, 'snooze', 'day'),
220
247
  o: (r) => act(r.dataset.rowId, 'back'),
248
+ d: (r) => act(r.dataset.rowId, 'done'),
221
249
  r: Object.assign(() => load(), { needsRow: false }),
222
250
  },
223
251
  });
@@ -257,7 +285,7 @@ export function initBugHunt({ api, $, esc, ago, toast, openAgent }) {
257
285
  e.preventDefault();
258
286
  document.activeElement?.blur?.();
259
287
  const fd = new FormData(form);
260
- 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')) };
288
+ 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')), autoFix: fd.get('autoFix') === 'on', fixAt: fd.get('fixAt'), fileIssues: fd.get('fileIssues') === 'on', testCommand: fd.get('testCommand') };
261
289
  try {
262
290
  const id = form.dataset.huntForm;
263
291
  await api(id === 'new' ? 'POST' : 'PUT', id === 'new' ? '/hunts' : `/hunts/${id}`, input);
package/public/codemap.js CHANGED
@@ -1,8 +1,13 @@
1
1
  // Map: a repository's folders as tiles sized by their files, with each agent as a badge on the
2
2
  // folders it is changing (solid) or reading (ring) now. A red line joins two agents that changed
3
3
  // the same file; a dashed one runs from an agent reading a file to the agent that changed it.
4
+ // The Bugs view colours each folder by the bugs hunts found there (worst weigh most) and how much it
5
+ // changed lately, draws the paths through the code those bugs take as arrows between folders, and
6
+ // hatches the folders no hunt has looked at. Click a folder or an arrow for its bugs, or Hunt here.
4
7
 
5
8
  const SAVED = 'agentmgr.mapProject';
9
+ const LAYER = 'agentmgr.mapLayer';
10
+ const SEV = { critical: 'Critical', high: 'High', medium: 'Medium', low: 'Low' };
6
11
  const EVERY_MS = 8000;
7
12
 
8
13
  const hue = (id) => [...String(id)].reduce((h, c) => (h * 31 + c.charCodeAt(0)) % 360, 17);
@@ -53,14 +58,17 @@ export function squarify(items, x, y, w, h) {
53
58
  return out;
54
59
  }
55
60
 
56
- export function initCodeMap({ api, $, esc, agents, openAgent, toast }) {
61
+ export function initCodeMap({ api, $, esc, agents, openAgent, openBugs, toast }) {
57
62
  const view = $('#map-view');
58
63
  let open = false;
59
64
  let data = null;
60
65
  let timer = null;
61
66
  let project = null;
67
+ let layer = 'agents';
68
+ let picked = null; // in the Bugs view: { module } or { from, to }
62
69
  try {
63
70
  project = localStorage.getItem(SAVED) || null;
71
+ layer = localStorage.getItem(LAYER) === 'bugs' ? 'bugs' : 'agents';
64
72
  } catch {}
65
73
 
66
74
  const nameOf = (id) => data?.map.agents.find((a) => a.id === id)?.name ?? agents.get(id)?.name ?? id;
@@ -68,7 +76,8 @@ export function initCodeMap({ api, $, esc, agents, openAgent, toast }) {
68
76
 
69
77
  async function load() {
70
78
  try {
71
- data = await api('GET', `/codemap${project ? `?project=${encodeURIComponent(project)}` : ''}`);
79
+ const q = new URLSearchParams({ ...(project ? { project } : {}), ...(layer === 'bugs' ? { layer } : {}) });
80
+ data = await api('GET', `/codemap${q.size ? `?${q}` : ''}`);
72
81
  if (data.project && data.project.key !== project) project = data.project.key;
73
82
  } catch (e) {
74
83
  toast?.(e.message, 5000);
@@ -92,10 +101,14 @@ export function initCodeMap({ api, $, esc, agents, openAgent, toast }) {
92
101
  $('#map-bar').innerHTML = `
93
102
  <b>Map</b>
94
103
  ${projects.length ? `<select data-map-set="project" aria-label="Project">${projects.map((p) => `<option value="${esc(p.key)}" ${p.key === data?.project?.key ? 'selected' : ''}>${esc(p.name)} (${p.running} running)</option>`).join('')}</select>` : ''}
95
- <span class="map-legend"><span class="map-key solid"></span>changing <span class="map-key ring"></span>reading <span class="map-key red"></span>same file changed <span class="map-key dash"></span>reading what another changed</span>
104
+ <span class="chips map-layers" role="tablist"><button class="chip ${layer === 'agents' ? 'active' : ''}" data-map-layer="agents" role="tab" aria-selected="${layer === 'agents'}">Agents</button><button class="chip ${layer === 'bugs' ? 'active' : ''}" data-map-layer="bugs" role="tab" aria-selected="${layer === 'bugs'}" title="Where hunts found bugs, and the paths through the code they take">Bugs</button></span>
105
+ ${layer === 'bugs'
106
+ ? '<span class="map-legend"><span class="map-key heat"></span>bugs (worst weigh most) and recent changes <span class="map-key arrow"></span>path a bug takes <span class="map-key cold"></span>no hunt has looked here</span>'
107
+ : '<span class="map-legend"><span class="map-key solid"></span>changing <span class="map-key ring"></span>reading <span class="map-key red"></span>same file changed <span class="map-key dash"></span>reading what another changed</span>'}
96
108
  <span class="spacer"></span>
97
109
  <button class="small" data-map="refresh" title="Look again now (it refreshes every few seconds)">↻</button>
98
110
  <button class="small" data-map="close" title="Back (Esc)">Close</button>`;
111
+ if (layer === 'bugs') return drawBugs();
99
112
  const warn = (m?.links ?? []).filter((l) => l.kind !== 'near');
100
113
  $('#map-warn').innerHTML = warn.length ? `<ul>${warn.map(sentence).join('')}</ul>` : m?.agents.length ? '<p class="hint">No agents are on the same code.</p>' : '';
101
114
  const box = $('#map-box');
@@ -165,6 +178,129 @@ export function initCodeMap({ api, $, esc, agents, openAgent, toast }) {
165
178
  svg.innerHTML = lines.join('');
166
179
  }
167
180
 
181
+ const finding = (id) => data?.heat?.findings.find((f) => f.id === id);
182
+
183
+ /** The Bugs view: folders by heat, arrows along bugs' paths, cold spots hatched. */
184
+ function drawBugs() {
185
+ const m = data?.map;
186
+ const heat = data?.heat;
187
+ const box = $('#map-box');
188
+ $('#map-agents').innerHTML = '';
189
+ if (!m || !heat || !m.modules.length) {
190
+ box.innerHTML = `<p class="hint map-empty">${data?.project ? 'No files to show for this project yet.' : 'No projects with a repository yet.'}</p>`;
191
+ $('#map-warn').innerHTML = '';
192
+ return;
193
+ }
194
+ const of = (key) => heat.modules[key] ?? { score: 0, bugs: {}, churn: 0, covered: false, files: [], findings: [] };
195
+ // Hot folders get more room, so their names and counts show.
196
+ const items = m.modules.map((mod) => ({ ...mod, weight: Math.max(1, mod.files) + of(mod.key).score * 3 })).sort((a, b) => b.weight - a.weight);
197
+ const W = box.clientWidth;
198
+ const H = Math.max(320, view.clientHeight - box.offsetTop - 24);
199
+ box.style.height = `${H}px`;
200
+ const big = items.slice(0, 100);
201
+ const rest = items.slice(100);
202
+ if (rest.length) big.push({ key: `${rest.length} more folders`, files: rest.reduce((s2, x) => s2 + x.files, 0), weight: rest.reduce((s2, x) => s2 + x.weight, 0), more: true });
203
+ const rects = squarify(big, 0, 0, W, H);
204
+ const at = new Map(rects.map((r) => [r.item.key, r]));
205
+ const tiles = rects
206
+ .map(({ x, y, w, h, item }) => {
207
+ const t = of(item.key);
208
+ const n = Object.values(t.bugs).reduce((a, b) => a + b, 0);
209
+ const r = heat.max ? t.score / heat.max : 0;
210
+ const worst = ['critical', 'high', 'medium', 'low'].find((k) => t.bugs[k]);
211
+ const cold = heat.hunted && !t.covered && !item.more;
212
+ const sel = picked?.module === item.key || picked?.from === item.key || picked?.to === item.key;
213
+ const tip = `${item.key}: ${item.files} files${n ? ` · ${n} bug${n === 1 ? '' : 's'}` : ''}${t.churn ? ` · changed ${t.churn}× in 30 days` : ''}${cold ? ' · no hunt has looked here' : ''}`;
214
+ return `<div class="map-tile heat ${n ? 'buggy' : ''} ${cold ? 'cold' : ''} ${sel ? 'picked' : ''} ${item.more ? 'more' : ''}" data-map-mod="${esc(item.more ? '' : item.key)}" style="left:${x}px;top:${y}px;width:${w}px;height:${h}px;--heat:${r.toFixed(3)}" title="${esc(tip)}">
215
+ ${w > 46 && h > 22 ? `<span class="map-name">${esc(item.key === '.' ? '(top level)' : item.key)}</span>` : ''}
216
+ ${n && w > 40 && h > 38 ? `<span class="map-bugs ${worst}">${n} bug${n === 1 ? '' : 's'}</span>` : w > 46 && h > 38 ? `<span class="map-count">${item.files}</span>` : ''}
217
+ </div>`;
218
+ })
219
+ .join('');
220
+ // Arrows from the middle of one folder to the next, thicker the more (and worse) bugs go that way.
221
+ const maxW = Math.max(1, ...heat.paths.map((p) => p.weight));
222
+ const mid = (r) => [r.x + r.w / 2, r.y + r.h / 2];
223
+ const arrows = heat.paths
224
+ .map((p, i) => {
225
+ const a = at.get(p.from);
226
+ const b = at.get(p.to);
227
+ if (!a || !b || a === b) return '';
228
+ const [x1, y1] = mid(a);
229
+ const [x2, y2] = mid(b);
230
+ // A slight curve, so arrows both ways between two folders don't overlap.
231
+ const cx = (x1 + x2) / 2 - (y2 - y1) * 0.15;
232
+ const cy = (y1 + y2) / 2 + (x2 - x1) * 0.15;
233
+ const sel = picked?.from === p.from && picked?.to === p.to;
234
+ const sw = 1.5 + (4.5 * p.weight) / maxW;
235
+ // Each arrow its own head, sized to its width.
236
+ const head = Math.max(10, Math.min(20, sw * 3)).toFixed(1);
237
+ return `<marker id="map-arrow-${i}" class="${sel ? 'picked' : ''}" viewBox="0 0 10 10" refX="7" refY="5" markerUnits="userSpaceOnUse" markerWidth="${head}" markerHeight="${head}" orient="auto"><path d="M0,0 L10,5 L0,10 z" /></marker><path class="bug-path ${sel ? 'picked' : ''}" data-map-path="${i}" d="M${x1},${y1} Q${cx},${cy} ${x2},${y2}" stroke-width="${sw.toFixed(1)}" marker-end="url(#map-arrow-${i})"><title>${esc(`${p.from} → ${p.to}: ${p.findings.length} bug${p.findings.length === 1 ? '' : 's'}`)}</title></path>`;
238
+ })
239
+ .join('');
240
+ box.innerHTML = `${tiles}<svg class="map-links bug-paths" width="${W}" height="${H}">${arrows}</svg>`;
241
+ $('#map-warn').innerHTML = bugPanel(of);
242
+ }
243
+
244
+ function bugRow(f) {
245
+ return `<li data-map-finding="${esc(f.id)}"><span class="bug-sev ${esc(f.severity)}">${esc(SEV[f.severity] ?? f.severity)}</span> ${esc(f.title)} <span class="hint">${esc(f.file)}${f.line ? `:${f.line}` : ''}${f.status === 'pr' ? ' · draft PR' : f.status === 'fixing' ? ' · being fixed' : f.status === 'snoozed' ? ' · snoozed' : ''}</span>
246
+ ${f.status === 'open' ? '<button class="small" data-map-bug="fix" title="Start an agent on it">Fix</button>' : ''}
247
+ ${f.prUrl ? `<a class="small-link" href="${esc(f.prUrl)}" target="_blank" rel="noopener">PR ↗</a>` : ''}
248
+ <button class="small" data-map-bug="evidence" title="See it in Bugs">Evidence</button></li>`;
249
+ }
250
+
251
+ /** Under the map: the picked folder's or path's bugs, else the hottest folders. */
252
+ function bugPanel(of) {
253
+ const heat = data.heat;
254
+ const hunt = data.project?.shortcut ? `<button class="small primary" data-map-hunt title="A hunt on this folder, the whole module a part at a time">Hunt here</button>` : '';
255
+ if (picked?.module !== undefined) {
256
+ const t = of(picked.module);
257
+ const list = t.findings.map(finding).filter(Boolean);
258
+ const name = picked.module === '.' ? '(top level)' : picked.module;
259
+ return `<div class="map-pick"><b>${esc(name)}</b> <span class="hint">${list.length ? `${list.length} bug${list.length === 1 ? '' : 's'}` : 'no bugs found'}${t.churn ? ` · changed ${t.churn}× in 30 days` : ''}${heat.hunted && !t.covered ? ' · no hunt has looked here yet' : ''}${t.files.length ? ` · hottest: ${t.files.map((x) => `<code>${esc(x.file)}</code>`).join(', ')}` : ''}</span> ${hunt} <button class="small" data-map-unpick>×</button>
260
+ ${list.length ? `<ul class="map-bug-list">${list.map(bugRow).join('')}</ul>` : ''}</div>`;
261
+ }
262
+ if (picked?.from !== undefined) {
263
+ const p = heat.paths.find((x) => x.from === picked.from && x.to === picked.to);
264
+ const list = (p?.findings ?? []).map(finding).filter(Boolean);
265
+ return `<div class="map-pick"><b>${esc(picked.from)} → ${esc(picked.to)}</b> <span class="hint">the path ${list.length === 1 ? 'this bug takes' : `${list.length} bugs take`} through the code</span> <button class="small" data-map-unpick>×</button>
266
+ <ul class="map-bug-list">${list.map(bugRow).join('')}</ul></div>`;
267
+ }
268
+ const hot = Object.entries(heat.modules).filter(([, t]) => t.findings.length).sort((a, b) => b[1].score - a[1].score).slice(0, 5);
269
+ if (!heat.hunted) return '<p class="hint">No bug hunts on this project yet: set one up under Bugs (b), and what it finds shows here. Folders are coloured by recent changes until then.</p>';
270
+ if (!hot.length) return `<p class="hint">No open bugs in this project.${heat.findings.length ? '' : ' Hatched folders are ones no hunt has looked at.'} Click a folder to hunt there.</p>`;
271
+ return `<p class="hint">Hottest: ${hot.map(([k, t]) => `<button class="link" data-map-mod="${esc(k)}">${esc(k === '.' ? '(top level)' : k)}</button> (${t.findings.length})`).join(', ')}. ${heat.paths.length ? 'Arrows are the paths bugs take through the code; click one for its bugs.' : ''} Hatched folders are ones no hunt has looked at.</p>`;
272
+ }
273
+
274
+ async function bugAct(id, what) {
275
+ if (what === 'evidence') {
276
+ show(false);
277
+ return openBugs?.();
278
+ }
279
+ if (what === 'fix') {
280
+ try {
281
+ const r = await api('POST', `/findings/${id}/fix`, {});
282
+ toast?.(r.existing ? `${r.agent.name} is on it already` : `Agent ${r.agent.name} started on it`, 4000, { label: 'Open', run: () => (show(false), openAgent(r.agent.id)) });
283
+ } catch (e) {
284
+ toast?.(e.message, 6000);
285
+ }
286
+ load();
287
+ }
288
+ }
289
+
290
+ /** Hunt the picked folder: its hunt if there is one, else a new whole-module hunt; then run it. */
291
+ async function huntHere() {
292
+ const folder = picked?.module === '.' ? '' : picked?.module ?? '';
293
+ try {
294
+ const { hunts } = await api('GET', '/hunts');
295
+ let h = hunts.find((x) => x.project === data.project.shortcut && x.path === folder);
296
+ h ??= await api('POST', '/hunts', { project: data.project.shortcut, path: folder, focus: 'module' });
297
+ const r = await api('POST', `/hunts/${h.id}/run`, {});
298
+ toast?.(`${r.agent.name} is hunting in ${folder || 'the whole project'}. Its findings come in when it's done.`, 5000);
299
+ } catch (e) {
300
+ toast?.(e.message, 6000);
301
+ }
302
+ }
303
+
168
304
  function show(on) {
169
305
  open = on;
170
306
  view.hidden = !on;
@@ -179,6 +315,28 @@ export function initCodeMap({ api, $, esc, agents, openAgent, toast }) {
179
315
  }
180
316
 
181
317
  view.addEventListener('click', (e) => {
318
+ const lay = e.target.closest('[data-map-layer]');
319
+ if (lay) {
320
+ layer = lay.dataset.mapLayer;
321
+ picked = null;
322
+ try {
323
+ localStorage.setItem(LAYER, layer);
324
+ } catch {}
325
+ return load();
326
+ }
327
+ if (layer === 'bugs') {
328
+ const ba = e.target.closest('[data-map-bug]');
329
+ if (ba) return bugAct(ba.closest('[data-map-finding]')?.dataset.mapFinding, ba.dataset.mapBug);
330
+ if (e.target.closest('[data-map-hunt]')) return huntHere();
331
+ if (e.target.closest('[data-map-unpick]')) return (picked = null), draw();
332
+ const path = e.target.closest('[data-map-path]');
333
+ if (path) {
334
+ const p = data.heat.paths[Number(path.dataset.mapPath)];
335
+ return (picked = p ? { from: p.from, to: p.to } : null), draw();
336
+ }
337
+ const mod = e.target.closest('[data-map-mod]');
338
+ if (mod?.dataset.mapMod) return (picked = picked?.module === mod.dataset.mapMod ? null : { module: mod.dataset.mapMod }), draw();
339
+ }
182
340
  const o = e.target.closest('[data-map-open]');
183
341
  if (o) {
184
342
  show(false);
@@ -191,6 +349,7 @@ export function initCodeMap({ api, $, esc, agents, openAgent, toast }) {
191
349
  view.addEventListener('change', (e) => {
192
350
  if (e.target.dataset.mapSet !== 'project') return;
193
351
  project = e.target.value;
352
+ picked = null;
194
353
  try {
195
354
  localStorage.setItem(SAVED, project);
196
355
  } catch {}
package/public/style.css CHANGED
@@ -1126,6 +1126,28 @@ body.mapping .layout, body.mapping .watch-view { display: none; }
1126
1126
  .map-agents { display: flex; flex-wrap: wrap; gap: 6px 12px; margin-top: 8px; }
1127
1127
  .map-agent { display: inline-flex; align-items: center; gap: 6px; background: none; border: none; padding: 2px 0; cursor: pointer; font-size: 13px; color: inherit; }
1128
1128
  #map-btn.active { background: var(--accent); color: var(--accent-text); border-color: var(--accent); }
1129
+ /* Map, Bugs view: heat, the paths bugs take, cold spots */
1130
+ .map-layers { display: inline-flex; gap: 4px; }
1131
+ .map-layers .chip { font-size: 12px; padding: 3px 12px; border-radius: 999px; border: 1px solid var(--border); background: var(--panel); color: inherit; cursor: pointer; }
1132
+ .map-layers .chip.active { background: var(--accent); color: var(--accent-text); border-color: var(--accent); }
1133
+ .map-key.heat { background: linear-gradient(90deg, color-mix(in srgb, var(--red) 12%, var(--panel)), var(--red)); }
1134
+ .map-key.arrow { height: 0; border-top: 3px solid var(--accent); }
1135
+ .map-key.cold { background: repeating-linear-gradient(45deg, var(--border) 0 2px, transparent 2px 5px); border: 1px solid var(--border); }
1136
+ .map-tile.heat { cursor: pointer; background: color-mix(in srgb, var(--red) calc(var(--heat) * 70%), color-mix(in srgb, var(--border) 45%, var(--panel))); }
1137
+ .map-tile.heat.cold { background-image: repeating-linear-gradient(45deg, color-mix(in srgb, var(--border) 80%, transparent) 0 2px, transparent 2px 7px); }
1138
+ .map-tile.heat.picked { outline: 2px solid var(--accent); outline-offset: -2px; z-index: 1; }
1139
+ .map-tile.heat:hover { filter: brightness(1.08); }
1140
+ .map-bugs { display: inline-block; margin-top: 2px; padding: 0 6px; border-radius: 8px; font-size: 10.5px; font-weight: 700; background: var(--panel); border: 1px solid currentColor; }
1141
+ .map-bugs.critical, .map-bugs.high { color: var(--red); }
1142
+ .map-bugs.medium { color: var(--amber, #c98a12); }
1143
+ .map-bugs.low { color: var(--muted); }
1144
+ .bug-paths path.bug-path { fill: none; stroke: var(--accent); stroke-linecap: round; opacity: 0.8; pointer-events: stroke; cursor: pointer; }
1145
+ .bug-paths path.bug-path:hover, .bug-paths path.bug-path.picked { opacity: 1; stroke: var(--text, currentColor); }
1146
+ .bug-paths marker path { fill: var(--accent); }
1147
+ .bug-paths marker.picked path { fill: var(--text, currentColor); }
1148
+ .map-pick { padding: 6px 10px; margin-bottom: 8px; border-radius: 6px; background: var(--panel); font-size: 13px; }
1149
+ .map-warn .map-bug-list li { border-left: none; padding: 4px 0; margin: 0; background: none; display: flex; flex-wrap: wrap; align-items: center; gap: 6px; }
1150
+ .map-bug-list { margin: 6px 0 0 !important; }
1129
1151
 
1130
1152
  /* ---------- Jira: issues agents work on */
1131
1153
  .issues-dialog { width: min(1100px, calc(100% - 32px)); max-height: calc(100% - 32px); padding: 16px; }
package/public/today.js CHANGED
@@ -61,6 +61,7 @@ export function initToday({ api, $, esc, ago, openAgent, showInbox, openActions,
61
61
  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(' ');
62
62
  if (it.kind === 'pr-ready') return [btn('open-reviews', 'Open review', 'Pick what to post (Enter)', true), link(it.url, 'PR')].join(' ');
63
63
  if (it.kind === 'rule') return btn('inbox', 'Inbox', 'Decide in the inbox (Enter)', true);
64
+ if (it.kind === 'bug-pr') return [link(it.url, 'Open PR'), btn('done', 'Done', 'You looked at it: off the list (d)'), btn('bugs', 'Details', 'The bug and how the fix was checked (Enter)')].join(' ');
64
65
  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(' ');
65
66
  return [it.agentId ? btn('open', 'Open', "Open the agent's session (Enter)", it.score < 20) : '', link(it.url, it.issueKey ? 'Jira' : 'Link')].join(' ');
66
67
  }
@@ -212,9 +213,9 @@ export function initToday({ api, $, esc, ago, openAgent, showInbox, openActions,
212
213
  dialog.close();
213
214
  return openReviews();
214
215
  }
215
- if (what === 'bugs' || (what === 'enter' && it.kind === 'bug')) {
216
+ if (what === 'bugs' || (what === 'enter' && (it.kind === 'bug' || it.kind === 'bug-pr'))) {
216
217
  dialog.close();
217
- return openBugs?.();
218
+ return openBugs?.(it.kind === 'bug-pr' ? 'pr' : undefined);
218
219
  }
219
220
  if (what === 'enter') {
220
221
  if (it.kind === 'action') {
@@ -281,6 +282,9 @@ export function initToday({ api, $, esc, ago, openAgent, showInbox, openActions,
281
282
  t.setHours(9, 0, 0, 0);
282
283
  await api('POST', '/findings/set', { ids: [it.findingId], status: what === 'skip' ? 'snoozed' : 'notbug', until: what === 'skip' ? t.toISOString() : null });
283
284
  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' }));
285
+ } else if (it.kind === 'bug-pr' && what === 'done') {
286
+ await api('POST', '/findings/set', { ids: [it.findingId], status: 'done' });
287
+ changedWith('Done: off the list', 'done', () => api('POST', '/findings/set', { ids: [it.findingId], status: 'pr' }));
284
288
  } else if (it.kind === 'pr-requested' && (what === 'review' || what === 'assign')) {
285
289
  const a = await api('POST', '/reviews', { url: it.reviewUrl });
286
290
  toast?.(`Reviewer ${a.name ?? 'agent'} started`, 3000);
package/src/bughunt.js CHANGED
@@ -5,6 +5,12 @@
5
5
  // so the list stays worth reading. Bugs already reported, or that you said aren't bugs, aren't
6
6
  // reported again. From the list: Fix (an agent starts on it, with the failing test), File it (a
7
7
  // filled-in issue to submit), Not a bug, or Snooze.
8
+ //
9
+ // With "Fix automatically" on a hunt, the serious ones are fixed without you: an agent fixes each
10
+ // on its own branch (its test must go from failing to passing, and the whole suite must pass), the
11
+ // judge reviews the change against the finding, and what holds up is opened as a draft pull
12
+ // request for you to review. Nothing is merged. A fix that doesn't hold up stays in the list with
13
+ // the reason (and, when you asked for it, is filed as an issue so it isn't lost).
8
14
 
9
15
  import crypto from 'node:crypto';
10
16
  import fs from 'node:fs';
@@ -13,6 +19,8 @@ import { briefDir } from './brief.js';
13
19
 
14
20
  export const FINDINGS_FILE = 'FINDINGS.json';
15
21
  export const findingsPath = (agentId) => path.join(briefDir(agentId), FINDINGS_FILE);
22
+ export const FIX_FILE = 'FIX.json';
23
+ export const fixPath = (agentId) => path.join(briefDir(agentId), FIX_FILE);
16
24
 
17
25
  export const FOCUS = { changes: 'What changed since the last run', module: 'The whole module, a part at a time' };
18
26
  export const KINDS = {
@@ -26,11 +34,14 @@ export const KINDS = {
26
34
  };
27
35
  export const SEVERITIES = ['critical', 'high', 'medium', 'low'];
28
36
  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'];
37
+ export const STATUSES = ['open', 'fixing', 'pr', 'done', 'filed', 'notbug', 'snoozed', 'dropped'];
30
38
 
31
39
  const MAX_FINDINGS = 500;
32
40
  const MAX_RUNS = 20;
33
41
  const KEEP_AT = 0.6;
42
+ // Fix automatically: at most this many pull requests a run, and never for less than this each.
43
+ export const MAX_AUTO_PRS = 3;
44
+ const MIN_FIX_USD = 0.5;
34
45
  const err = (status, message) => Object.assign(new Error(message), { status });
35
46
  const clip = (s, n) => {
36
47
  const t = String(s ?? '').trim();
@@ -189,6 +200,84 @@ export function fixIntent(f) {
189
200
  .join('\n\n');
190
201
  }
191
202
 
203
+ /** What an automatic fix agent is asked to do: the finding (its request). */
204
+ export function autoFixIntent(f) {
205
+ return `Bug fix: ${f.title}\n\n${fixIntent(f)}`;
206
+ }
207
+
208
+ /** An automatic fix agent's instructions: proven, unattended, and a report in `file`. */
209
+ export function fixerPrompt(file, fixing = {}) {
210
+ return [
211
+ `This fix runs without the user: nobody will answer questions, so decide yourself, and keep the change as small as the fix needs. ${fixing.testCommand ? `The project's tests run with: ${fixing.testCommand}` : "Find how the project's tests run (package.json, Makefile, CI config)."}`,
212
+ "1. Add a test for the bug to the project's tests and run it: it must fail before the fix. 2. Fix it. 3. Run that test again (it must pass) and then the whole test suite (it must pass). Don't commit, push or open a pull request: that's done for you once the fix is checked.",
213
+ `Write what happened to ${file} as JSON:\n` +
214
+ '{ "fixed": true|false, "why": "<one or two sentences: the fix, or why you could not fix it or it is not a bug>",\n' +
215
+ ' "test": { "file": "<the test file>", "before": "fail|pass", "after": "fail|pass" },\n' +
216
+ ' "suite": { "command": "<how you ran all the tests>", "passed": true|false, "output": "<the last lines it printed>" } }',
217
+ 'Then set your status as done in the brief.',
218
+ ].join('\n\n');
219
+ }
220
+
221
+ /** FIX.json, cleaned up, or null. */
222
+ export function normalizeFix(raw) {
223
+ if (!raw || typeof raw !== 'object' || typeof raw.fixed !== 'boolean') return null;
224
+ const pf = (v) => (v === 'pass' || v === 'fail' ? v : null);
225
+ return {
226
+ fixed: raw.fixed,
227
+ why: clip(raw.why, 1000),
228
+ test: { file: raw.test?.file ? clip(raw.test.file, 300) : null, before: pf(raw.test?.before), after: pf(raw.test?.after) },
229
+ suite: { command: raw.suite?.command ? clip(raw.suite.command, 300) : null, passed: raw.suite?.passed === true, output: clip(raw.suite?.output, 2000) },
230
+ };
231
+ }
232
+
233
+ /** A fix agent's FIX.json, or null. */
234
+ export function readFix(agentId) {
235
+ try {
236
+ const text = fs.readFileSync(fixPath(agentId), 'utf8');
237
+ return normalizeFix(JSON.parse(text.slice(text.indexOf('{'), text.lastIndexOf('}') + 1)));
238
+ } catch {
239
+ return null;
240
+ }
241
+ }
242
+
243
+ /** Why a fix's own report doesn't hold up, or null when it does. */
244
+ export function fixProblem(report) {
245
+ if (!report) return 'The fix agent wrote no report';
246
+ if (!report.fixed) return `The fix agent didn't fix it${report.why ? `: ${report.why}` : ''}`;
247
+ if (report.test.before !== 'fail') return "Its test didn't fail before the fix, so it doesn't show the bug";
248
+ if (report.test.after !== 'pass') return "Its test still fails after the fix";
249
+ if (!report.suite.passed) return 'The test suite fails with the fix';
250
+ return null;
251
+ }
252
+
253
+ /** The judge's question: does this change fix the finding, and nothing else? */
254
+ export function fixCheckPrompt(f, diff) {
255
+ return [
256
+ 'An agent fixed the bug below without a person watching. Review its change before it goes to the user as a pull request: does it fix the bug at its cause, with a test that shows the bug, without changing other behaviour or weakening other tests? Reject changes that only hide the symptom, skip or loosen tests, or do unrelated things.',
257
+ `Bug: ${f.title}\nWhere: ${f.file ?? '?'}${f.line ? `:${f.line}` : ''}\nHow it fails: ${f.why}`,
258
+ `The change:\n${String(diff ?? '').slice(0, 30_000)}`,
259
+ 'Reply with JSON only: { "ok": true|false, "confidence": <0 to 1>, "reason": "<one or two sentences>" }',
260
+ ].join('\n\n');
261
+ }
262
+
263
+ /** The draft pull request's description: the finding, how the fix was checked. */
264
+ export function fixPrBody(f, report, check, testCommand = null) {
265
+ return [
266
+ `Fixes a bug found by a bug hunt.`,
267
+ findingMarkdown(f).replace(/\n\n_Found by a bug hunt in AI Agent Manager\._$/, ''),
268
+ '**How the fix was checked**',
269
+ [
270
+ `- The test${report.test.file ? ` (\`${report.test.file}\`)` : ''} failed before the fix and passes after it.`,
271
+ `- The whole suite passes${report.suite.command ? ` (\`${report.suite.command}\`)` : ''}.`,
272
+ testCommand ? `- Run again here before this pull request: \`${testCommand}\` passes.` : null,
273
+ check ? `- The AI judge reviewed the change: ${check.reason || 'it holds up'} (confidence ${Math.round(check.confidence * 100)}%).` : null,
274
+ ]
275
+ .filter(Boolean)
276
+ .join('\n'),
277
+ '_Opened as a draft by AI Agent Manager. Nothing was merged: look it over, then mark it ready._',
278
+ ].join('\n\n');
279
+ }
280
+
192
281
  /** The finding as an issue, in Markdown. */
193
282
  export function findingMarkdown(f) {
194
283
  return [
@@ -218,9 +307,17 @@ export function issueLinkFor(repo, f) {
218
307
  }
219
308
 
220
309
  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 }) {
310
+ /**
311
+ * `judge` is the AI judge (ask(key, agent, prompt, validate)); `read` gives a hunter's findings
312
+ * and `readFix` a fix agent's report (tests). `git` does what fixing automatically needs:
313
+ * { diff(agentId), commit(agentId, message), pr(agentId, { title, body, draft }),
314
+ * test(agentId, command) → { passed, output }, fileIssue(project, { title, body }) → url }.
315
+ */
316
+ constructor({ manager, store, judge = null, log = () => {}, read = readFindings, readFix: rf = readFix, git = null }) {
223
317
  this.read = read;
318
+ this.readFix = rf;
319
+ this.git = git;
320
+ this.settling = new Set();
224
321
  this.manager = manager;
225
322
  this.store = store;
226
323
  this.judge = judge;
@@ -228,6 +325,7 @@ export class BugHunts {
228
325
  this.checking = new Set();
229
326
  this.onFinished = (agent) => {
230
327
  if (agent?.hunting) this.ingest(agent.id).catch((e) => this.log(`bughunt: ${e.message}`));
328
+ else if (agent && this.autoFinding(agent.id)) this.settle(agent.id).catch((e) => this.log(`bughunt: ${e.message}`));
231
329
  };
232
330
  manager.on('finished', this.onFinished);
233
331
  this.timer = null;
@@ -265,7 +363,23 @@ export class BugHunts {
265
363
  const raw = input.maxUsd === undefined ? prev.maxUsd ?? 5 : Number(input.maxUsd);
266
364
  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
365
  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}` : ''}` };
366
+ const fixAt = input.fixAt ?? prev.fixAt ?? 'high';
367
+ if (!SEVERITIES.includes(fixAt)) throw err(400, `Fix automatically from ${SEVERITIES.join(', ')}`);
368
+ const flag = (k) => Boolean(input[k] ?? prev[k] ?? false);
369
+ const testCommand = clip(input.testCommand ?? prev.testCommand ?? '', 300) || null;
370
+ return {
371
+ project,
372
+ path: p,
373
+ focus,
374
+ kinds,
375
+ schedule,
376
+ maxUsd: Math.round(raw * 100) / 100,
377
+ name: clip(input.name ?? prev.name ?? '', 80) || `${project}${p ? `/${p}` : ''}`,
378
+ autoFix: flag('autoFix'),
379
+ fixAt,
380
+ fileIssues: flag('fileIssues'),
381
+ testCommand,
382
+ };
269
383
  }
270
384
 
271
385
  add(input) {
@@ -365,18 +479,139 @@ export class BugHunts {
365
479
  this.manager.stop(agentId);
366
480
  } catch {}
367
481
  this.log(`bughunt: ${agent.name}: ${kept} kept of ${found} new`);
368
- return { found, kept };
482
+ return h?.autoFix ? { found, kept, fixing: this.autoFix(h, agentId) } : { found, kept };
369
483
  } finally {
370
484
  this.checking.delete(agentId);
371
485
  }
372
486
  }
373
487
 
374
- /** Runs that ended without saying done (stopped, out of budget): their findings are taken in too. */
488
+ /**
489
+ * Runs that ended without saying done (stopped, out of budget): their findings are taken in too.
490
+ * Likewise automatic fixes: one that stopped is settled as it stands.
491
+ */
375
492
  async sweep() {
376
493
  for (const a of this.store.list()) {
377
- if (!a.hunting || a.hunting.ingestedAt) continue;
378
494
  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(() => {});
495
+ const ended = a.brief?.status === 'done' || (a.desired !== 'running' && !rt?.pty);
496
+ if (a.hunting && !a.hunting.ingestedAt) {
497
+ if (ended) await this.ingest(a.id).catch(() => {});
498
+ } else if (ended && this.autoFinding(a.id)) await this.settle(a.id).catch(() => {});
499
+ }
500
+ }
501
+
502
+ /** The finding an automatic fix agent is working on, while it is. */
503
+ autoFinding(agentId) {
504
+ return this.findings.find((f) => f.auto?.agentId === agentId && f.auto.state === 'fixing') ?? null;
505
+ }
506
+
507
+ /**
508
+ * Fix automatically: the run's new findings at or above the hunt's severity, worst first, up to
509
+ * MAX_AUTO_PRS, each by its own agent on its own branch. What's left of the run's cost limit is
510
+ * shared between them. Returns the ids of the findings being fixed.
511
+ */
512
+ autoFix(h, hunterId) {
513
+ const rank = (s) => SEVERITIES.indexOf(s);
514
+ const picked = this.findings
515
+ .filter((f) => f.foundBy === hunterId && f.status === 'open' && rank(f.severity) <= rank(h.fixAt ?? 'high'))
516
+ .sort((a, b) => rank(a.severity) - rank(b.severity))
517
+ .slice(0, MAX_AUTO_PRS);
518
+ if (!picked.length) return [];
519
+ const spent = Number(this.manager.get?.(hunterId)?.costUsd) || 0;
520
+ const each = Math.floor(((h.maxUsd - spent) / picked.length) * 100) / 100;
521
+ const started = [];
522
+ for (const f of picked) {
523
+ if (!this.git || each < MIN_FIX_USD) {
524
+ f.auto = { state: 'failed', at: now(), reason: this.git ? `The run's cost limit ($${h.maxUsd}) was used up by the hunt` : "Pull requests can't be opened from here" };
525
+ continue;
526
+ }
527
+ try {
528
+ const agent = this.manager.create({
529
+ project: f.project,
530
+ intent: autoFixIntent(f),
531
+ fixing: { findingId: f.id, testCommand: h.testCommand ?? null },
532
+ name: `fix-${f.title}`.toLowerCase().replace(/[^a-z0-9-]+/g, '-').slice(0, 40),
533
+ worktree: true,
534
+ planReview: false,
535
+ designDoc: false,
536
+ demoPage: false,
537
+ benchmarks: false,
538
+ });
539
+ this.manager.patch(agent.id, { budgetUsd: each });
540
+ f.fixAgentId = agent.id;
541
+ f.status = 'fixing';
542
+ f.auto = { state: 'fixing', agentId: agent.id, at: now(), budgetUsd: each };
543
+ started.push(f.id);
544
+ this.log(`bughunt: fixing "${f.title}" automatically (${agent.name}, up to $${each})`);
545
+ } catch (e) {
546
+ f.auto = { state: 'failed', at: now(), reason: `Couldn't start a fix: ${e.message}` };
547
+ }
548
+ }
549
+ this.store.save();
550
+ return started;
551
+ }
552
+
553
+ /**
554
+ * An automatic fix ended: its report, the tests (when the hunt has a test command) and the judge
555
+ * decide. What holds up is committed and opened as a draft pull request; what doesn't stays in
556
+ * the list with the reason, and is filed as an issue when the hunt says so. Safe to call twice.
557
+ */
558
+ async settle(agentId) {
559
+ const f = this.autoFinding(agentId);
560
+ if (!f || this.settling.has(agentId)) return null;
561
+ this.settling.add(agentId);
562
+ const h = this.hunts.find((x) => x.id === f.huntId) ?? null;
563
+ const agent = this.store.get(agentId);
564
+ try {
565
+ const report = this.readFix(agentId);
566
+ let problem = fixProblem(report);
567
+ const diff = problem ? '' : await this.git.diff(agentId).catch(() => '');
568
+ if (!problem && !diff.trim()) problem = 'The fix agent changed nothing';
569
+ if (!problem && h?.testCommand) {
570
+ const t = await this.git.test(agentId, h.testCommand).catch((e) => ({ passed: false, output: e.message }));
571
+ if (!t.passed) problem = `The tests fail with the fix (${h.testCommand})${t.output ? `: ${clip(t.output.split('\n').slice(-6).join(' '), 300)}` : ''}`;
572
+ }
573
+ let check = null;
574
+ // With the judge off (Settings), the tests decide alone.
575
+ if (!problem && this.judge && this.judge.enabled !== false) {
576
+ check = await this.judge.ask(`fix:${f.id}`, agent, fixCheckPrompt(f, diff), (d) => typeof d.ok === 'boolean').catch(() => null);
577
+ if (!check) problem = "The judge couldn't review the change";
578
+ else if (!(check.ok && check.confidence >= KEEP_AT)) problem = `The judge didn't accept the change: ${clip(check.reason, 400) || 'no reason given'}`;
579
+ }
580
+ if (!problem) {
581
+ const title = `Fix: ${f.title}`.slice(0, 100);
582
+ try {
583
+ await this.git.commit(agentId, title).catch((e) => {
584
+ if (!/nothing to commit/i.test(e.message)) throw e;
585
+ });
586
+ const pr = await this.git.pr(agentId, { title, body: fixPrBody(f, report, check, h?.testCommand ?? null), draft: true });
587
+ f.status = 'pr';
588
+ f.prUrl = pr.url ?? null;
589
+ f.auto = { ...f.auto, state: 'pr', doneAt: now(), check: check ? { confidence: check.confidence, reason: clip(check.reason, 600) } : null };
590
+ this.log(`bughunt: "${f.title}": draft pull request ${f.prUrl ?? '(no link)'}`);
591
+ } catch (e) {
592
+ problem = `Fixed, but the pull request couldn't be opened: ${e.message}`;
593
+ }
594
+ }
595
+ if (problem) {
596
+ f.status = 'open';
597
+ f.auto = { ...f.auto, state: 'failed', doneAt: now(), reason: clip(problem, 600) };
598
+ this.log(`bughunt: "${f.title}": automatic fix didn't hold up: ${problem}`);
599
+ if (h?.fileIssues && !f.issueUrl) {
600
+ try {
601
+ f.issueUrl = await this.git.fileIssue(f.project, { title: f.title, body: `${findingMarkdown(f)}\n\n_An automatic fix was tried and didn't hold up: ${clip(problem, 400)}_` });
602
+ if (f.issueUrl) f.status = 'filed';
603
+ } catch (e) {
604
+ f.auto.issueError = clip(e.message, 300);
605
+ }
606
+ }
607
+ }
608
+ this.store.save();
609
+ try {
610
+ this.manager.stop(agentId);
611
+ } catch {}
612
+ return { status: f.status, problem: problem ?? null, prUrl: f.prUrl ?? null };
613
+ } finally {
614
+ this.settling.delete(agentId);
380
615
  }
381
616
  }
382
617
 
@@ -400,9 +635,9 @@ export class BugHunts {
400
635
  this.timer.unref?.();
401
636
  }
402
637
 
403
- /** Your decision on findings: open, notbug, snoozed (until a time), filed. */
638
+ /** Your decision on findings: open, notbug, snoozed (until a time), filed, done (its fix looked at). */
404
639
  set(ids = [], status, { until = null } = {}) {
405
- if (!['open', 'notbug', 'snoozed', 'filed'].includes(status)) throw err(400, 'The decision is open, notbug, snoozed or filed');
640
+ if (!['open', 'notbug', 'snoozed', 'filed', 'done', 'pr'].includes(status)) throw err(400, 'The decision is open, notbug, snoozed, filed or done');
406
641
  let snoozeUntil = null;
407
642
  if (status === 'snoozed') {
408
643
  const t = Date.parse(until ?? '');
@@ -412,7 +647,8 @@ export class BugHunts {
412
647
  const set = [];
413
648
  for (const id of new Set(ids)) {
414
649
  const f = this.findings.find((x) => x.id === id);
415
- if (!f) continue;
650
+ // Back to its draft pull request (Undo) only when it has one.
651
+ if (!f || (status === 'pr' && !f.prUrl)) continue;
416
652
  f.prev = f.status;
417
653
  f.status = status;
418
654
  f.snoozeUntil = snoozeUntil;
package/src/codemap.js CHANGED
@@ -113,3 +113,88 @@ export function buildMap({ files = [], agents = [], depth = 2 }) {
113
113
  links,
114
114
  };
115
115
  }
116
+
117
+ // Bugs on the map: each folder's heat is its open bugs, weighted by severity, plus a little for how
118
+ // much it changed lately (new bugs come from changed code). A finding that names its path through
119
+ // the code ("a.js:3 -> b/c.js:9") is drawn as arrows from folder to folder along it: the hot paths,
120
+ // thicker where several bugs go the same way. Folders no hunt has looked at are the cold spots.
121
+
122
+ export const SEVERITY_WEIGHT = { critical: 8, high: 4, medium: 2, low: 1 };
123
+ // Still in the code: not a bug, not kept, or done with are left out.
124
+ const LIVE = new Set(['open', 'fixing', 'pr', 'filed', 'snoozed']);
125
+ const CHURN_WEIGHT = 0.25;
126
+ const MAX_CHURN = 20;
127
+
128
+ /** A path as the repository lists it: as given, without "./" or an absolute prefix, or by its unique end. */
129
+ export function resolveFile(p, files, set = new Set(files)) {
130
+ const v = String(p ?? '').trim().replace(/\\/g, '/').replace(/^\.\//, '');
131
+ if (!v) return null;
132
+ if (set.has(v)) return v;
133
+ const tail = v.replace(/^\/+/, '');
134
+ if (set.has(tail)) return tail;
135
+ const hits = files.filter((f) => f === tail || f.endsWith(`/${tail}`) || tail.endsWith(`/${f}`));
136
+ return hits.length === 1 ? hits[0] : null;
137
+ }
138
+
139
+ /** The files, in order, of a path through the code written as file:line steps. */
140
+ export function traceFiles(detail, files, set = new Set(files)) {
141
+ const out = [];
142
+ for (const m of String(detail ?? '').matchAll(/([\w@.\-/\\]+\.[A-Za-z]\w*):(\d+)/g)) {
143
+ const f = resolveFile(m[1], files, set);
144
+ if (f && out[out.length - 1] !== f) out.push(f);
145
+ }
146
+ return out;
147
+ }
148
+
149
+ /**
150
+ * The bugs layer: { modules: { key: { score, bugs, churn, covered, files, findings } }, paths, findings, max, hunted }.
151
+ * `findings` are a hunt's findings in this repository; `churn` the recent commits, each a list of
152
+ * the files it changed (a folder's churn is how many commits touched it, however many files); `hunts`
153
+ * the project's hunts (their folder, focus, what they covered, and whether one has run).
154
+ */
155
+ export function bugHeat({ files = [], findings = [], churn = [], hunts = [], depth = 2 }) {
156
+ const set = new Set(files);
157
+ const modules = {};
158
+ const mod = (key) => (modules[key] ??= { score: 0, bugs: { critical: 0, high: 0, medium: 0, low: 0 }, churn: 0, covered: false, files: {}, findings: [] });
159
+ for (const commit of churn) for (const key of new Set(commit.filter((f) => set.has(f)).map((f) => moduleOf(f, depth)))) mod(key).churn += 1;
160
+ const paths = new Map();
161
+ const shown = [];
162
+ for (const f of findings) {
163
+ if (!LIVE.has(f.status)) continue;
164
+ const file = resolveFile(f.file, files, set);
165
+ const steps = f.evidence?.type === 'trace' ? traceFiles(f.evidence.detail, files, set) : [];
166
+ if (file && steps[steps.length - 1] !== file) steps.push(file);
167
+ const at = file ?? steps[steps.length - 1];
168
+ if (!at) continue;
169
+ const w = SEVERITY_WEIGHT[f.severity] ?? 1;
170
+ const m = mod(moduleOf(at, depth));
171
+ m.bugs[f.severity in m.bugs ? f.severity : 'medium'] += 1;
172
+ m.score += w;
173
+ m.files[at] = (m.files[at] ?? 0) + w;
174
+ m.findings.push(f.id);
175
+ shown.push({ id: f.id, title: f.title, severity: f.severity, status: f.status, file: at, line: f.line ?? null, module: moduleOf(at, depth), prUrl: f.prUrl ?? null, steps: steps.length });
176
+ // Folder to folder along its path; staying in one folder isn't an arrow.
177
+ const route = steps.map((s) => moduleOf(s, depth)).filter((x, i, a) => i === 0 || a[i - 1] !== x);
178
+ for (let i = 1; i < route.length; i++) {
179
+ const key = `${route[i - 1]}\u0000${route[i]}`;
180
+ const p = paths.get(key) ?? paths.set(key, { from: route[i - 1], to: route[i], weight: 0, findings: [] }).get(key);
181
+ p.weight += w;
182
+ if (!p.findings.includes(f.id)) p.findings.push(f.id);
183
+ }
184
+ }
185
+ // Covered: a hunt that has run looks at this folder (its folder, and for a whole-module hunt, the parts it went through).
186
+ const ran = hunts.filter((h) => h.ran);
187
+ const inside = (key, p) => !p || key === p || key.startsWith(`${p}/`) || p.startsWith(`${key}/`);
188
+ for (const key of new Set(files.slice(0, 20_000).map((f) => moduleOf(f, depth)))) {
189
+ const m = mod(key);
190
+ m.covered = ran.some((h) => inside(key, h.path) && (h.focus !== 'module' || !h.covered?.length || h.covered.some((c) => inside(key, String(c).replace(/^\.?\/+|\/+$/g, '')))));
191
+ }
192
+ let max = 0;
193
+ for (const m of Object.values(modules)) {
194
+ m.score += Math.min(m.churn, MAX_CHURN) * CHURN_WEIGHT;
195
+ m.score = Math.round(m.score * 100) / 100;
196
+ max = Math.max(max, m.score);
197
+ m.files = Object.entries(m.files).sort((a, b) => b[1] - a[1]).slice(0, 3).map(([file, score]) => ({ file, score }));
198
+ }
199
+ return { modules, paths: [...paths.values()].sort((a, b) => b.weight - a.weight).slice(0, 60), findings: shown, max, hunted: hunts.length > 0 };
200
+ }
package/src/manager.js CHANGED
@@ -105,13 +105,13 @@ async function repoLayout(dir) {
105
105
  }
106
106
  import { spawn } from 'node:child_process';
107
107
  import * as git from './git.js';
108
- import { buildMap, touchedFiles } from './codemap.js';
108
+ import { bugHeat, buildMap, touchedFiles } from './codemap.js';
109
109
  import { parseDiff } from '../public/review.js';
110
110
  import { assignedIssues, issueFields, issueSummary, jiraProblem, leadingIssue, loadJira, wordsAfterLink } from './jira.js';
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
+ import { findingsPath, fixPath, fixerPrompt, hunterPrompt } from './bughunt.js';
115
115
  import { reminderFor, reminderSettings } from './reminders.js';
116
116
  import { combine, facts as scoreFacts, improveMessage, scorecardMarkdown, scorecardPrompt } from './scorecard.js';
117
117
  import { CONTAINER_ENGINES, claudeToken, containerName, containerRunning, engineMounts, gitCommonDir, removeContainer, runArgs, stopContainer } from './container.js';
@@ -398,7 +398,7 @@ export class AgentManager extends EventEmitter {
398
398
  };
399
399
  // A recent agent gone quiet: follow up on it, or close its finished session (reminders.js).
400
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));
401
+ v.followUp = agent.hunting || agent.fixing ? null : reminderFor(v, reminderSettings(this.config));
402
402
  return v;
403
403
  }
404
404
 
@@ -627,6 +627,7 @@ export class AgentManager extends EventEmitter {
627
627
  builds,
628
628
  reviewing,
629
629
  hunting,
630
+ fixing,
630
631
  }) {
631
632
  intent = (intent ?? '').trim();
632
633
  const staged = stagedFiles(attachments);
@@ -685,6 +686,8 @@ export class AgentManager extends EventEmitter {
685
686
  ...(!general && reviewing ? { reviewing } : {}),
686
687
  // Hunts for bugs, read-only (bughunt.js): { huntId, path, focus, kinds, since, covered }.
687
688
  ...(!general && hunting ? { hunting } : {}),
689
+ // Fixes a hunt's finding without you (bughunt.js): { findingId, testCommand }.
690
+ ...(!general && fixing ? { fixing } : {}),
688
691
  name: name?.trim() || jiraKey || slug,
689
692
  slug,
690
693
  intent,
@@ -800,7 +803,11 @@ export class AgentManager extends EventEmitter {
800
803
  * The codebase map of one project (its key, else the one with the most running agents): its
801
804
  * folders, and where each of its agents is changing and reading code now (codemap.js).
802
805
  */
803
- async codeMap(projectKey) {
806
+ /**
807
+ * The code map of a project (the one with the most going on, unless named). With `bugs`
808
+ * ({ findings, hunts } of the bug hunts), it also has the bugs layer (codemap.js bugHeat).
809
+ */
810
+ async codeMap(projectKey, { bugs = null } = {}) {
804
811
  const withCode = this.store.list().filter((a) => a.workdir && !NO_REPO.has(a.kind) && fs.existsSync(a.workdir));
805
812
  const groups = new Map();
806
813
  for (const a of withCode) {
@@ -826,7 +833,20 @@ export class AgentManager extends EventEmitter {
826
833
  } catch {}
827
834
  return { id: a.id, name: a.name, busy: rt?.busy, attention: rt?.attention, changed: this.changeSets.get(a.id)?.files ?? {}, touched };
828
835
  });
829
- return { project: { key: g.key, name: g.name }, projects: list, map: buildMap({ files, agents }) };
836
+ const out = { project: { key: g.key, name: g.name }, projects: list, map: buildMap({ files, agents }) };
837
+ if (bugs) {
838
+ // Hunts and findings name the project by its shortcut.
839
+ const mine = (shortcut) => this.resolveProject(shortcut)?.key === g.key;
840
+ const hunts = (bugs.hunts ?? []).filter((h) => mine(h.project));
841
+ out.project.shortcut = Object.values(this.store.data.projects ?? {}).find((p) => p.key === g.key)?.shortcut ?? null;
842
+ out.heat = bugHeat({
843
+ files,
844
+ findings: (bugs.findings ?? []).filter((f) => mine(f.project)),
845
+ churn: await this.churn(root),
846
+ hunts: hunts.map((h) => ({ path: h.path, focus: h.focus, covered: h.covered ?? [], ran: (h.runs ?? []).some((r) => r.status === 'done') })),
847
+ });
848
+ }
849
+ return out;
830
850
  }
831
851
 
832
852
  /**
@@ -884,6 +904,17 @@ export class AgentManager extends EventEmitter {
884
904
  }
885
905
 
886
906
  /** A repository's tracked files, for the map (kept a few minutes). */
907
+ /** The commits of the last 30 days, each as the files it changed (kept ten minutes). */
908
+ async churn(dir) {
909
+ this.churns ??= new Map();
910
+ const hit = this.churns.get(dir);
911
+ if (hit && Date.now() - hit.at < 10 * 60_000) return hit.commits;
912
+ const out = await git.run('git', ['log', '--since=30.days', '--name-only', '--format=%x01', '--no-renames', '-n', '2000'], { cwd: dir, timeout: 30_000 }).catch(() => '');
913
+ const commits = out.split('\x01').map((c) => c.split('\n').filter(Boolean)).filter((c) => c.length);
914
+ this.churns.set(dir, { at: Date.now(), commits });
915
+ return commits;
916
+ }
917
+
887
918
  async repoFiles(dir) {
888
919
  this.fileLists ??= new Map();
889
920
  const hit = this.fileLists.get(dir);
@@ -1236,6 +1267,12 @@ export class AgentManager extends EventEmitter {
1236
1267
  writableDir ??= path.dirname(file);
1237
1268
  prompts.push(hunterPrompt(file, agent.hunting));
1238
1269
  }
1270
+ if (agent.fixing && task) {
1271
+ fs.mkdirSync(briefDir(agent.id), { recursive: true });
1272
+ const file = path.join(fs.realpathSync(briefDir(agent.id)), path.basename(fixPath(agent.id)));
1273
+ writableDir ??= path.dirname(file);
1274
+ prompts.push(fixerPrompt(file, agent.fixing));
1275
+ }
1239
1276
  if (planning) prompts.push(planningPrompt(agent));
1240
1277
  // What earlier agents learned in this repo, and the one command to add to it.
1241
1278
  let allowedTools = null;
package/src/server.js CHANGED
@@ -52,8 +52,9 @@ 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 { leadingJiraKey } from './tracker.js';
55
+ import { ghBin, leadingJiraKey } from './tracker.js';
56
56
  import { BugHunts } from './bughunt.js';
57
+ import * as git from './git.js';
57
58
 
58
59
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
59
60
  const require = createRequire(import.meta.url);
@@ -100,7 +101,44 @@ export async function startServer({ port = PORT, host = HOST } = {}) {
100
101
  const myActions = new MyActions({ store, manager });
101
102
  const reviews = new Reviews({ manager, store, log: (m) => console.log(`[agentmgr] ${m}`) });
102
103
  // Bug hunts: the judge checks each finding when it's on (else only failing tests are kept).
103
- const hunts = new BugHunts({ manager, store, judge: manager.judge, log: (m) => console.log(`[agentmgr] ${m}`) });
104
+ // Fixing automatically: the change, the tests, a commit and a draft pull request, or an issue.
105
+ const huntGit = {
106
+ diff: async (id) => {
107
+ const a = manager.mustGet(id);
108
+ const base = await review.base(a);
109
+ return base ? git.fullDiff(a.workdir, base.sha) : '';
110
+ },
111
+ commit: (id, message) => review.commit(id, { message }),
112
+ pr: (id, opts) => review.pr(id, opts),
113
+ test: (id, command) => runCommand(manager.mustGet(id), command),
114
+ fileIssue: async (project, { title, body }) => {
115
+ const p = manager.resolveProject(project);
116
+ const slug = /github\.com[/:]([\w.-]+\/[\w.-]+?)(?:\.git)?\/?$/.exec(p?.repo ?? '')?.[1];
117
+ if (!slug && !p?.dir) throw new Error('The project has no GitHub repository to file in');
118
+ const out = await git.run(ghBin(), ['issue', 'create', ...(slug ? ['-R', slug] : []), '--title', title, '--body', body, '--label', 'bug'], { cwd: p?.dir ?? undefined, timeout: 60_000 }).catch((e) =>
119
+ // A repository without a "bug" label: file it without one.
120
+ /label/i.test(e.message) ? git.run(ghBin(), ['issue', 'create', ...(slug ? ['-R', slug] : []), '--title', title, '--body', body], { cwd: p?.dir ?? undefined, timeout: 60_000 }) : Promise.reject(e),
121
+ );
122
+ return /https:\/\/\S+\/issues\/\d+/.exec(out)?.[0] ?? null;
123
+ },
124
+ };
125
+ /** A shell command in an agent's folder: { passed, output } (the last lines), killed after 15 minutes. */
126
+ const runCommand = (agent, command) =>
127
+ new Promise((resolve) => {
128
+ const child = spawn(process.env.SHELL || '/bin/sh', ['-lc', command], { cwd: agent.workdir, env: manager.childEnv(agent), detached: true });
129
+ let out = '';
130
+ const keep = (d) => (out = (out + d).slice(-4000));
131
+ child.stdout.on('data', keep);
132
+ child.stderr.on('data', keep);
133
+ const timer = setTimeout(() => {
134
+ try {
135
+ process.kill(-child.pid, 'SIGKILL');
136
+ } catch {}
137
+ }, 15 * 60_000);
138
+ child.on('error', (e) => (clearTimeout(timer), resolve({ passed: false, output: e.message })));
139
+ child.on('close', (code) => (clearTimeout(timer), resolve({ passed: code === 0, output: out })));
140
+ });
141
+ const hunts = new BugHunts({ manager, store, judge: manager.judge, git: huntGit, log: (m) => console.log(`[agentmgr] ${m}`) });
104
142
  hunts.startTimer();
105
143
  const races = new Races({ manager, store });
106
144
  const review = new Review({ manager });
@@ -820,7 +858,8 @@ export async function startServer({ port = PORT, host = HOST } = {}) {
820
858
  const days = req.query.days === undefined ? 30 : Math.max(0, Math.min(3650, Math.floor(Number(req.query.days)) || 0));
821
859
  return stats(store.list(), { days, projectOf: (a) => manager.projectInfo(a)?.name ?? null });
822
860
  }));
823
- api.get('/codemap', wrap((req) => manager.codeMap(req.query.project ? String(req.query.project) : null)));
861
+ // ?layer=bugs adds where the bug hunts found bugs: heat per folder, and the paths through the code.
862
+ api.get('/codemap', wrap((req) => manager.codeMap(req.query.project ? String(req.query.project) : null, { bugs: req.query.layer === 'bugs' ? { findings: hunts.findings, hunts: hunts.hunts } : null })));
824
863
  // Issues agents work on, for the summary; ?group=you|agent|done and ?format=markdown to paste.
825
864
  api.get('/issues', wrap(async (req) => {
826
865
  // ?fresh=1 (the ↻ button) asks Jira again: the issues assigned to you and each issue's status.
@@ -936,7 +975,7 @@ export async function startServer({ port = PORT, host = HOST } = {}) {
936
975
  f.slack || f.gemini ? got('actions', () => myActions.rows()) : [],
937
976
  got('reviews', () => reviews.rows()),
938
977
  ]);
939
- const findings = hunts.list().findings.filter((x) => x.status === 'open');
978
+ const findings = hunts.list().findings.filter((x) => x.status === 'open' || x.status === 'pr');
940
979
  const items = todayItems({ inbox, issues, actions, reviews: prs, findings });
941
980
  return { items, aside: todayAside({ issues, actions }), speech: todaySpeech(items), features: f, errors };
942
981
  }));
package/src/today.js CHANGED
@@ -111,8 +111,14 @@ export function todayItems({ inbox = [], issues = [], actions = [], reviews = []
111
111
  }
112
112
  // Bugs a hunt found and the check confirmed: the serious ones (the rest wait in the Bugs list).
113
113
  for (const f of findings) {
114
+ // Fixed without you: a draft pull request to look over.
115
+ if (f.status === 'pr') {
116
+ items.push({ id: `bug:${f.id}`, kind: 'bug-pr', label: 'Fix ready', title: f.title, why: `Fixed automatically (${f.severity}): a draft pull request; its test failed before and passes now${f.auto?.check ? ', and the judge reviewed it' : ''}`, score: 34, at: f.auto?.doneAt ?? f.at ?? null, findingId: f.id, url: f.prUrl ?? null });
117
+ continue;
118
+ }
114
119
  if (f.status !== 'open' || !['critical', 'high'].includes(f.severity)) continue;
115
- 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 });
120
+ const failed = f.auto?.state === 'failed' ? ` · the automatic fix didn't hold up: ${f.auto.reason}` : '';
121
+ 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' : ''}${failed}`, score: f.severity === 'critical' ? 28 : 38, at: f.at ?? null, findingId: f.id });
116
122
  }
117
123
  return items.sort((x, y) => x.score - y.score || String(y.at ?? '').localeCompare(String(x.at ?? '')));
118
124
  }