ai-agentmanager 1.28.0 → 1.30.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/bughunt.js 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/cli.js CHANGED
@@ -757,9 +757,13 @@ export async function main(argv) {
757
757
  .option('--from <who>', 'who asked')
758
758
  .option('--due <when>', 'when it is due, if said')
759
759
  .option('--context <text>', 'a sentence or two of background')
760
+ .option('--question <words>', 'a question put to you: its words (the action then is to answer it)')
761
+ .option('--cc', "you're copied or mentioned on it, not asked directly")
762
+ .option('--answer <text>', 'a draft answer, to edit and send yourself')
763
+ .option('--sources <text>', 'with --answer: the links or files it is based on')
760
764
  .action(async (words, opts) => {
761
765
  await daemon();
762
- const a = await api('POST', '/actions', { text: words.join(' '), source: opts.source, link: opts.link, from: opts.from, due: opts.due, context: opts.context });
766
+ const a = await api('POST', '/actions', { text: words.join(' '), source: opts.source, link: opts.link, from: opts.from, due: opts.due, context: opts.context, question: opts.question, cc: Boolean(opts.cc), answer: opts.answer, sources: opts.sources });
763
767
  console.log(a.duplicate ? dim(`Already listed: ${a.id}`) : `${green('+')} ${bold(a.id)} ${a.text}`);
764
768
  });
765
769
  actionsCmd
@@ -775,6 +779,17 @@ export async function main(argv) {
775
779
  if (r.set.length) console.log(`${green('✓')} ${r.set.join(', ')}: ${state}`);
776
780
  for (const x of r.failed) console.log(`${red('!')} ${bold(x.id)}: ${x.reason}`);
777
781
  });
782
+ actionsCmd
783
+ .command('answer')
784
+ .description('Record a draft answer to a question (to edit and send yourself; nothing is sent)')
785
+ .argument('<id>')
786
+ .argument('<text...>', 'the answer')
787
+ .option('--sources <text>', 'the links or files it is based on')
788
+ .action(async (id, words, opts) => {
789
+ await daemon();
790
+ await api('PUT', `/actions/${id}/answer`, { text: words.join(' '), sources: opts.sources });
791
+ console.log(`${green('✓')} ${bold(id)}: draft answer saved`);
792
+ });
778
793
  actionsCmd
779
794
  .command('discuss')
780
795
  .description('Talk an action item through with Claude, in a session of its own')
package/src/issues.js CHANGED
@@ -34,9 +34,11 @@ export const GROUPS = {
34
34
  * the list). Any of them can be changed later; skipped, done and removed issues aren't proposed or
35
35
  * started by the assistant.
36
36
  */
37
- export const ACTIONS = ['assign', 'skip', 'done', 'remove'];
38
- const SET_ASIDE = { skip: 'skipped', done: 'done', remove: 'removed' };
39
- const ACTION_NOTE = { skip: 'Skipped by you', done: 'Marked done by you', remove: 'Removed by you' };
37
+ export const ACTIONS = ['assign', 'skip', 'snooze', 'done', 'remove'];
38
+ const SET_ASIDE = { skip: 'skipped', snooze: 'snoozed', done: 'done', remove: 'removed' };
39
+ const ACTION_NOTE = { skip: 'Skipped by you', snooze: 'Snoozed by you', done: 'Marked done by you', remove: 'Removed by you' };
40
+ // A snooze whose time has come is no decision any more.
41
+ const expired = (e, t = Date.now()) => e?.action === 'snooze' && !(Date.parse(e.until ?? '') > t);
40
42
 
41
43
  /** The issue an agent works on: { key, url }, from the link its request starts with or one in it. */
42
44
  export function issueOf(v) {
@@ -105,6 +107,7 @@ function designOf(v, read) {
105
107
  export function issueRows(views, jira = new Map(), read = () => null, proposed = [], actions = {}, assigned = []) {
106
108
  const rank = Object.fromEntries(Object.keys(GROUPS).map((k, i) => [k, i]));
107
109
  const rows = [];
110
+ actions = Object.fromEntries(Object.entries(actions).filter(([, e]) => !expired(e)));
108
111
  // What the search for issues assigned to you found: their summaries stand in where nothing else has one.
109
112
  const mine = new Map(assigned.map((i) => [i.key, i]));
110
113
  // Issues proposed for agents, not started yet: they wait for you to tick them.
@@ -113,6 +116,7 @@ export function issueRows(views, jira = new Map(), read = () => null, proposed =
113
116
  const action = actions[p.key]?.action ?? (p.status === 'dismissed' ? 'remove' : null);
114
117
  rows.push({
115
118
  actionAt: actions[p.key]?.at ?? null,
119
+ snoozeUntil: actions[p.key]?.action === 'snooze' ? actions[p.key].until : null,
116
120
  key: p.key,
117
121
  url: p.url,
118
122
  title: j?.summary ?? mine.get(p.key)?.summary ?? p.title,
@@ -142,6 +146,7 @@ export function issueRows(views, jira = new Map(), read = () => null, proposed =
142
146
  const design = designOf(v, read);
143
147
  rows.push({
144
148
  actionAt: actions[issue.key]?.at ?? null,
149
+ snoozeUntil: actions[issue.key]?.action === 'snooze' ? actions[issue.key].until : null,
145
150
  key: issue.key,
146
151
  url: issue.url,
147
152
  title: j?.summary ?? mine.get(issue.key)?.summary ?? issue.title,
@@ -167,6 +172,7 @@ export function issueRows(views, jira = new Map(), read = () => null, proposed =
167
172
  const action = actions[i.key]?.action ?? null;
168
173
  rows.push({
169
174
  actionAt: actions[i.key]?.at ?? null,
175
+ snoozeUntil: actions[i.key]?.action === 'snooze' ? actions[i.key].until : null,
170
176
  key: i.key,
171
177
  url: i.url,
172
178
  title: i.summary,
@@ -244,7 +250,9 @@ export class ProposedIssues {
244
250
 
245
251
  /** Your action per issue key: { action, at }. */
246
252
  get actions() {
247
- return (this.store.data.issueActions ??= {});
253
+ const all = (this.store.data.issueActions ??= {});
254
+ for (const [k, e] of Object.entries(all)) if (expired(e)) delete all[k];
255
+ return all;
248
256
  }
249
257
 
250
258
  /** Skip, done or remove when you set one; dismissed before actions existed counts as remove. */
@@ -276,8 +284,10 @@ export class ProposedIssues {
276
284
  * Set your action on issues (null clears it). Assign starts an agent from the proposal when none
277
285
  * works on the issue yet. Returns { set: [keys], started: [{ key, agent }], failed: [{ key, reason }] }.
278
286
  */
279
- setAction(keys = [], action = null) {
287
+ setAction(keys = [], action = null, { until = null } = {}) {
280
288
  if (action !== null && !ACTIONS.includes(action)) throw err(400, `The action is one of ${ACTIONS.join(', ')}, or none to clear it`);
289
+ const wakeAt = action === 'snooze' ? Date.parse(until ?? '') : null;
290
+ if (action === 'snooze' && !(Number.isFinite(wakeAt) && wakeAt > Date.now())) throw err(400, 'Snooze until a time to come');
281
291
  const set = [];
282
292
  const started = [];
283
293
  const failed = [];
@@ -307,7 +317,7 @@ export class ProposedIssues {
307
317
  agent = r.started[0].agent;
308
318
  }
309
319
  // Assign is what an agent on it means anyway; only the others are kept.
310
- if (SET_ASIDE[action]) this.actions[key] = { action, at: new Date().toISOString() };
320
+ if (SET_ASIDE[action]) this.actions[key] = { action, at: new Date().toISOString(), ...(action === 'snooze' ? { until: new Date(wakeAt).toISOString() } : {}) };
311
321
  else delete this.actions[key];
312
322
  if (p?.status === 'dismissed') p.status = 'waiting';
313
323
  set.push(key);
package/src/manager.js CHANGED
@@ -111,7 +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
+ 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,
@@ -1236,6 +1239,12 @@ export class AgentManager extends EventEmitter {
1236
1239
  writableDir ??= path.dirname(file);
1237
1240
  prompts.push(hunterPrompt(file, agent.hunting));
1238
1241
  }
1242
+ if (agent.fixing && task) {
1243
+ fs.mkdirSync(briefDir(agent.id), { recursive: true });
1244
+ const file = path.join(fs.realpathSync(briefDir(agent.id)), path.basename(fixPath(agent.id)));
1245
+ writableDir ??= path.dirname(file);
1246
+ prompts.push(fixerPrompt(file, agent.fixing));
1247
+ }
1239
1248
  if (planning) prompts.push(planningPrompt(agent));
1240
1249
  // What earlier agents learned in this repo, and the one command to add to it.
1241
1250
  let allowedTools = null;
package/src/server.js CHANGED
@@ -52,7 +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 { ghBin, leadingJiraKey } from './tracker.js';
55
56
  import { BugHunts } from './bughunt.js';
57
+ import * as git from './git.js';
56
58
 
57
59
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
58
60
  const require = createRequire(import.meta.url);
@@ -99,7 +101,44 @@ export async function startServer({ port = PORT, host = HOST } = {}) {
99
101
  const myActions = new MyActions({ store, manager });
100
102
  const reviews = new Reviews({ manager, store, log: (m) => console.log(`[agentmgr] ${m}`) });
101
103
  // 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}`) });
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}`) });
103
142
  hunts.startTimer();
104
143
  const races = new Races({ manager, store });
105
144
  const review = new Review({ manager });
@@ -607,6 +646,21 @@ export async function startServer({ port = PORT, host = HOST } = {}) {
607
646
  api.post('/agents/:id/changes/comments', wrap((req) => review.comment(req.params.id, req.body ?? {})));
608
647
  api.post('/agents/:id/changes/commit', wrap((req) => review.commit(req.params.id, req.body ?? {})));
609
648
  api.post('/agents/:id/changes/pr', wrap((req) => review.pr(req.params.id, req.body ?? {})));
649
+ // Done but no pull request: commit what's left, push and open one, titled after the issue or request.
650
+ api.post('/agents/:id/ship', wrap(async (req) => {
651
+ const a = manager.mustGet(req.params.id);
652
+ const key = leadingJiraKey(a.intent);
653
+ const words = a.synopsis?.text ?? a.brief?.title ?? String(a.intent ?? '').replace(/^<?https?:\/\/\S+>?\s*/, '').split('\n')[0];
654
+ const title = String(req.body?.title ?? '').trim() || `${key ? `${key}: ` : ''}${words || a.name}`.slice(0, 100);
655
+ try {
656
+ await review.commit(a.id, { message: title });
657
+ } catch (e) {
658
+ if (e.status !== 409 || !/nothing to commit/i.test(e.message)) throw e;
659
+ }
660
+ const r = await review.pr(a.id, { title });
661
+ await manager.refresh(a.id, { withPrs: true }).catch(() => {});
662
+ return { url: r.url ?? null, title };
663
+ }));
610
664
  api.post('/agents/:id/fork', wrap((req) => manager.fork(req.params.id, req.body ?? {})));
611
665
 
612
666
  api.get('/races', wrap(() => races.list()));
@@ -826,7 +880,11 @@ export async function startServer({ port = PORT, host = HOST } = {}) {
826
880
  // My actions: what's asked of you in Slack and meeting notes (the assistant adds them).
827
881
  api.get('/actions', wrap(() => ({ rows: myActions.rows(), features: featuresOf(config) })));
828
882
  api.post('/actions', wrap((req) => myActions.add({ ...req.body, by: req.headers['x-agentmgr-agent'] ? 'assistant' : 'you' })));
829
- api.post('/actions/set', wrap((req) => myActions.set(Array.isArray(req.body?.ids) ? req.body.ids.map(String) : [], String(req.body?.state ?? ''), { project: req.body?.project ?? null })));
883
+ api.post('/actions/set', wrap((req) => myActions.set(Array.isArray(req.body?.ids) ? req.body.ids.map(String) : [], String(req.body?.state ?? ''), { project: req.body?.project ?? null, until: req.body?.until ?? null })));
884
+ // The draft answer to a question: the assistant's (from its session) or yours, edited.
885
+ api.put('/actions/:id/answer', wrap((req) => myActions.answer(req.params.id, { text: req.body?.text, sources: req.body?.sources ?? null, by: req.headers['x-agentmgr-agent'] ? 'assistant' : 'you' })));
886
+ // A session that researches the question and records a draft answer.
887
+ api.post('/actions/:id/draft', wrap((req) => myActions.draft(req.params.id, `node ${JSON.stringify(path.join(__dirname, '..', 'bin', 'agentmgr.js'))}`, manager.listProjects().map((p) => ({ name: p.name ?? p.shortcut, dir: p.dir ?? null, repo: p.repo ?? null })))));
830
888
  api.post('/actions/:id/discuss', wrap((req) => myActions.discuss(req.params.id, `node ${JSON.stringify(path.join(__dirname, '..', 'bin', 'agentmgr.js'))}`)));
831
889
  // The parts you use: Jira, Slack, meeting notes. Off hides its list and the assistant skips it.
832
890
  api.get('/features', wrap(() => ({ features: featuresOf(config), me: assistant.settings.me })));
@@ -839,7 +897,7 @@ export async function startServer({ port = PORT, host = HOST } = {}) {
839
897
  return { features: featuresOf(config), me: assistant.settings.me };
840
898
  }));
841
899
  // Your action on issues: assign (starts an agent from the proposal), skip, done, remove, or null to clear.
842
- api.post('/issues/action', wrap((req) => proposed.setAction(Array.isArray(req.body?.keys) ? req.body.keys.map(String) : [], req.body?.action ?? null)));
900
+ api.post('/issues/action', wrap((req) => proposed.setAction(Array.isArray(req.body?.keys) ? req.body.keys.map(String) : [], req.body?.action ?? null, { until: req.body?.until ?? null })));
843
901
  // Design docs of all agents; the same ?group= and ?format=markdown.
844
902
  api.get('/designs', wrap((req) => {
845
903
  const v = manager.designs();
@@ -916,7 +974,7 @@ export async function startServer({ port = PORT, host = HOST } = {}) {
916
974
  f.slack || f.gemini ? got('actions', () => myActions.rows()) : [],
917
975
  got('reviews', () => reviews.rows()),
918
976
  ]);
919
- const findings = hunts.list().findings.filter((x) => x.status === 'open');
977
+ const findings = hunts.list().findings.filter((x) => x.status === 'open' || x.status === 'pr');
920
978
  const items = todayItems({ inbox, issues, actions, reviews: prs, findings });
921
979
  return { items, aside: todayAside({ issues, actions }), speech: todaySpeech(items), features: f, errors };
922
980
  }));