ai-agentmanager 1.16.0 → 1.18.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/cli.js CHANGED
@@ -615,6 +615,25 @@ export async function main(argv) {
615
615
  console.log(`${green('✓')} ${r.existing ? 'pushed to' : 'opened'} ${r.url ?? '(no URL printed by gh)'}`);
616
616
  });
617
617
 
618
+ program
619
+ .command('worklog')
620
+ .description('Work record: pull requests opened and merged, bugs fixed, issues filed, agents finished; also appended to ~/.agentmanager/worklog.csv')
621
+ .option('-d, --days <n>', 'the last n days (0: all time)', '30')
622
+ .option('--summary', 'print the period as Markdown, for a review or status update')
623
+ .option('--json', 'print JSON')
624
+ .action(async (opts) => {
625
+ await daemon();
626
+ if (opts.summary) return console.log((await api('GET', `/worklog/summary?days=${Number(opts.days) || 0}`)).markdown);
627
+ const v = await api('GET', `/worklog?days=${Number(opts.days) || 0}`);
628
+ if (opts.json) return console.log(JSON.stringify(v, null, 2));
629
+ const t = v.totals;
630
+ console.log(bold(`Work record, ${v.days ? `last ${v.days} days` : 'all time'}`));
631
+ console.log(` PRs merged ${bold(t.prs_merged)} opened ${t.prs_opened}${t.prs_closed ? ` closed ${t.prs_closed}` : ''}${t.merge_rate != null ? ` merge rate ${Math.round(t.merge_rate * 100)}%` : ''}${t.median_hours_to_merge != null ? ` median ${t.median_hours_to_merge} h to merge` : ''}`);
632
+ console.log(` bugs fixed ${bold(t.bugs_fixed)} issues filed ${t.issues_filed} agents finished ${t.agents_finished}`);
633
+ for (const e of v.events.slice(0, 15)) console.log(dim(` ${e.date.slice(0, 10)} ${e.event.replace('_', ' ').padEnd(14)} ${truncate(e.title, 60)}${e.link ? ` ${e.link}` : ''}`));
634
+ console.log(dim(`\n ${v.files.events}\n ${v.files.weekly}`));
635
+ });
636
+
618
637
  program
619
638
  .command('stats')
620
639
  .description('Results across agents: merge rate, time to a first PR and to merge, cost per merged PR, by engine and model')
@@ -888,7 +907,7 @@ export async function main(argv) {
888
907
  await daemon();
889
908
  const items = await api('GET', '/inbox');
890
909
  if (!items.length) return console.log(dim('Nothing needs you right now.'));
891
- const label = { prompt: red('needs input'), waiting: red('waiting'), question: cyan('question'), review: cyan('AI review'), stuck: yellow('stuck?'), conflict: yellow('overlap') };
910
+ const label = { prompt: red('needs input'), waiting: red('waiting'), question: cyan('question'), review: cyan('AI review'), stuck: yellow('stuck?'), conflict: yellow('overlap'), reminder: cyan('follow up') };
892
911
  for (const it of items) {
893
912
  if (it.kind === 'repeat') {
894
913
  console.log(`${cyan('make it a playbook?')} asked ${it.count} times: ${it.intent}`);
@@ -915,6 +934,11 @@ export async function main(argv) {
915
934
  if (it.kind === 'review') console.log(dim(` ${it.review.verdict.replace('_', ' ')}${it.review.missing.length ? `; missing: ${it.review.missing.join('; ')}` : ''}`));
916
935
  if (it.kind === 'stuck') console.log(dim(` ${it.finding.detail}\n nudge: agentmgr tell ${it.agentId} "…"`));
917
936
  if (it.kind === 'conflict') console.log(dim(` ${it.conflict.files.map((f) => f.file).join(', ')}`));
937
+ if (it.kind === 'reminder') {
938
+ const r = it.reminder;
939
+ const next = r.kind === 'close' ? `close: agentmgr close ${it.agentId}` : r.closed ? `resume: agentmgr start ${it.agentId}` : `nudge: agentmgr tell ${it.agentId} "…" · close: agentmgr close ${it.agentId}`;
940
+ console.log(dim(` ${r.detail ? `${r.detail}\n ` : ''}${next} · later: agentmgr remind ${it.agentId} later|dismiss`));
941
+ }
918
942
  }
919
943
  });
920
944
 
@@ -968,6 +992,17 @@ export async function main(argv) {
968
992
  console.log(`${green('✓')} sent ${a.name} its scorecard (${a.docs.scorecard.data.overall ?? '—'}/100) to improve; scored again when it updates its brief`);
969
993
  });
970
994
 
995
+ program
996
+ .command('desktop')
997
+ .description('Continue a Claude agent in the Claude desktop app (its session here closes; resume it here to pick up what was said there)')
998
+ .argument('<agent>')
999
+ .action(async (ref) => {
1000
+ await daemon();
1001
+ const a = await resolveAgent(ref);
1002
+ await api('POST', `/agents/${a.id}/desktop`);
1003
+ console.log(`${green('✓')} ${a.name} opened in the Claude desktop app; continue it here with: agentmgr start ${a.id}`);
1004
+ });
1005
+
971
1006
  program
972
1007
  .command('tell')
973
1008
  .description("Send a message into an agent's session (typed in when it is idle; resumes it if closed)")
@@ -1259,6 +1294,65 @@ export async function main(argv) {
1259
1294
  console.log(`removed ${sc}`);
1260
1295
  });
1261
1296
 
1297
+ const goal = program.command('goal').description('Goals: outcomes for today or this week across projects, planned into tasks that agents see through');
1298
+ const printGoal = (g) => {
1299
+ const c = g.counts;
1300
+ console.log(`${bold(g.id)} ${g.title} ${dim(`[${g.status}${g.overdue ? ', overdue' : ''}]`)}`);
1301
+ console.log(dim(` ${g.projects.join(', ')}${g.due ? ` due ${g.due.slice(0, 10)}` : ''} ${c.completed} completed · ${c.pending} pending · ${c.followUps} follow-ups${g.error ? ` ${g.error}` : ''}`));
1302
+ };
1303
+ goal
1304
+ .command('add')
1305
+ .description('Plan an outcome into tasks and start agents on them')
1306
+ .argument('<outcome>', 'what should be true when it is done')
1307
+ .requiredOption('-p, --projects <shortcuts>', 'comma-separated project shortcuts (agentmgr project ls)')
1308
+ .option('--today', 'due today')
1309
+ .option('--no-deadline', 'no due date (default: this week)')
1310
+ .option('--review', 'show the plan first; start it with: agentmgr goal approve <id>')
1311
+ .option('--priority <p>', '0-3 (P0 highest)', '2')
1312
+ .action(async (text, opts) => {
1313
+ await daemon();
1314
+ const period = opts.today ? 'day' : opts.deadline === false ? 'none' : 'week';
1315
+ printGoal(await api('POST', '/goals', { text, projects: opts.projects.split(','), period, review: Boolean(opts.review), priority: Number(opts.priority) }));
1316
+ console.log(dim(` planning; see it with: agentmgr goal show <id>`));
1317
+ });
1318
+ goal
1319
+ .command('ls')
1320
+ .description('Goals with completed, pending and follow-ups')
1321
+ .action(async () => {
1322
+ await daemon();
1323
+ const list = await api('GET', '/goals');
1324
+ if (!list.length) return console.log(dim('No goals yet. Add one: agentmgr goal add "outcome" -p <project>'));
1325
+ list.forEach(printGoal);
1326
+ });
1327
+ goal
1328
+ .command('show')
1329
+ .description("A goal's summary: completed, pending and follow-ups (Markdown)")
1330
+ .argument('<id>')
1331
+ .action(async (id) => {
1332
+ await daemon();
1333
+ const g = (await api('GET', '/goals')).find((x) => x.id === id);
1334
+ if (g?.status === 'review') console.log(`Plan (start with: agentmgr goal approve ${id}):\n${g.plan.map((t, i) => ` ${i + 1}. [${t.project}] ${t.title}`).join('\n')}\n`);
1335
+ console.log((await api('GET', `/goals/${id}/summary`)).markdown);
1336
+ });
1337
+ for (const [name, desc, method, route] of [
1338
+ ['approve', 'Start a goal whose plan you reviewed', 'POST', 'approve'],
1339
+ ['replan', 'Plan a goal again', 'POST', 'replan'],
1340
+ ['extend', 'Carry an overdue goal over to the next day or week', 'POST', 'extend'],
1341
+ ['stop', 'Stop a goal: its queued tasks are cancelled', 'POST', 'stop'],
1342
+ ['rm', 'Remove a stopped or finished goal', 'DELETE', ''],
1343
+ ]) {
1344
+ goal
1345
+ .command(name)
1346
+ .description(desc)
1347
+ .argument('<id>')
1348
+ .action(async (id) => {
1349
+ await daemon();
1350
+ const r = await api(method, `/goals/${id}${route ? `/${route}` : ''}`);
1351
+ if (r.counts) printGoal(r);
1352
+ else console.log(`${green('✓')} removed`);
1353
+ });
1354
+ }
1355
+
1262
1356
  const bl = program.command('backlog').description('Work orders that agents pick up one by one, per project, until done');
1263
1357
  const ST = { queued: dim('queued'), active: green('active'), review: yellow('review'), blocked: red('blocked'), done: dim('done'), cancelled: dim('cancelled') };
1264
1358
  const printBacklog = (v, { all = false } = {}) => {
@@ -1270,13 +1364,13 @@ export async function main(argv) {
1270
1364
  for (const it of items) {
1271
1365
  if (it.projectKey !== last) {
1272
1366
  const p = proj[it.projectKey];
1273
- const ap = p?.autopilot && p.autopilot !== 'off' ? `, autopilot: ${p.autopilot === 'merge' ? 'merge' : 'open PRs'}` : '';
1367
+ const ap = p?.autopilot && p.autopilot !== 'off' ? `, autopilot: ${p.autopilot === 'merge' ? 'merge' : 'open PRs'}${p.target ? ` at ${p.target}+` : ''}` : '';
1274
1368
  console.log(`\n${bold(it.projectName)} ${dim(`(${p?.limit ?? v.defaultLimit} at a time${ap})`)}`);
1275
1369
  last = it.projectKey;
1276
1370
  }
1277
1371
  const agent = it.agent ? dim(` → ${it.agent.name} (${it.agent.id})${it.agent.briefStatus ? ` brief: ${it.agent.briefStatus}` : ''}`) : '';
1278
1372
  console.log(` ${it.id} P${it.priority} ${(ST[it.status] ?? it.status).padEnd(18)} ${truncate(it.title, 60)}${agent}`);
1279
- if (it.status === 'review' && it.autopilot?.state) console.log(dim(` autopilot: ${it.autopilot.state}${it.autopilot.pr ? ` ${it.autopilot.pr}` : ''}${it.autopilot.note ? `: ${it.autopilot.note}` : ''}`));
1373
+ if (it.status === 'review' && it.autopilot?.state) console.log(dim(` autopilot: ${it.autopilot.state}${it.autopilot.pr ? ` ${it.autopilot.pr}` : ''}${it.autopilot.note ? `: ${it.autopilot.note}` : ''}${it.autopilot.scores?.length ? ` (scores ${it.autopilot.scores.join(' → ')})` : ''}`));
1280
1374
  }
1281
1375
  };
1282
1376
  bl.command('ls')
@@ -1368,9 +1462,10 @@ export async function main(argv) {
1368
1462
  .description("Take a project's finished items on by themselves when the review scorecard says ready: off, pr (open the pull request) or merge (and merge it once checks pass)")
1369
1463
  .argument('<project>', 'project name as shown in "backlog ls"')
1370
1464
  .argument('<level>', 'off, pr or merge')
1371
- .action(async (project, level) => {
1465
+ .option('--target <score>', 'ship only at this review score or more (50-100), sending the work back to improve until then; "none" ships when ready')
1466
+ .action(async (project, level, opts) => {
1372
1467
  await daemon();
1373
- printBacklog(await api('POST', '/backlog/settings', { project, autopilot: level }));
1468
+ printBacklog(await api('POST', '/backlog/settings', { project, autopilot: level, ...(opts.target !== undefined ? { target: opts.target } : {}) }));
1374
1469
  });
1375
1470
  itemCmd('ship', 'Go ahead with an item autopilot held: open its pull request (and merge, at the merge level)', 'ship');
1376
1471
  bl.command('pause')
@@ -2064,6 +2159,18 @@ export async function main(argv) {
2064
2159
  }
2065
2160
  });
2066
2161
 
2162
+ program
2163
+ .command('remind')
2164
+ .description('Snooze a follow-up reminder: later (a few hours) or dismiss (until the agent is used again)')
2165
+ .argument('<agent>')
2166
+ .argument('<action>', 'later or dismiss')
2167
+ .action(async (ref, action) => {
2168
+ await daemon();
2169
+ const a = await resolveAgent(ref);
2170
+ await api('POST', `/agents/${a.id}/reminder`, { action });
2171
+ console.log(`${green('✓')} ${action === 'later' ? 'reminding you later about' : 'no reminder until it is used again for'} ${a.name}`);
2172
+ });
2173
+
2067
2174
  program
2068
2175
  .command('rm')
2069
2176
  .description('Forget agents (optionally deleting worktrees agentmgr created)')
package/src/goals.js ADDED
@@ -0,0 +1,359 @@
1
+ // Goals: a work order of outcomes for today, this week or no deadline, across one or more
2
+ // projects, taken to completion by agents. Each goal is
3
+ // planned - a model breaks the outcome into tasks, one per agent, each in one of its projects
4
+ // queued - the tasks go to the backlog (its limits start the agents; autopilot ships them
5
+ // where it's on), right away or after you look at the plan
6
+ // checked - when every task is finished, the model checks the outcome against what was done
7
+ // and queues what's still missing, a couple of rounds at most; then it's done
8
+ // Its summary is kept current: completed, pending, and follow-ups (what needs you: blocked or
9
+ // held work, work waiting for your review, agents waiting on you or gone quiet).
10
+ import crypto from 'node:crypto';
11
+ import { EventEmitter } from 'node:events';
12
+ import { parseJsonReply } from './brief.js';
13
+
14
+ export const GOAL_PERIODS = ['day', 'week', 'none'];
15
+ const CHECK_ROUNDS = 2; // extra rounds for what the check finds missing
16
+ const MAX_TASKS = 12;
17
+ const OPEN = new Set(['queued', 'active', 'review', 'blocked']);
18
+
19
+ const now = () => new Date().toISOString();
20
+ const err = (status, message) => Object.assign(new Error(message), { status });
21
+
22
+ /** The end of today or of this week (Sunday), local time; null for no deadline. */
23
+ export function dueFor(period, t = Date.now()) {
24
+ if (period === 'none') return null;
25
+ const d = new Date(t);
26
+ d.setHours(23, 59, 59, 999);
27
+ if (period === 'week') d.setDate(d.getDate() + ((7 - d.getDay()) % 7));
28
+ return d.toISOString();
29
+ }
30
+
31
+ export function planPrompt({ text, projects, due, done = [], round = 0 }) {
32
+ const list = projects.map((p) => `- ${p.shortcut}: ${p.name}${p.repo ? ` (${p.repo})` : p.dir ? ` (${p.dir})` : ''}`);
33
+ if (!round) {
34
+ return [
35
+ 'You plan a work order for AI coding agents. Each task you list becomes one agent, working on its own branch in one of the',
36
+ 'projects below, ending in a pull request or another concrete result. Break the outcome into the fewest independent tasks that',
37
+ 'together achieve it, at most 12. Write each task as a self-contained request: what to change and where, and how to verify it.',
38
+ 'Use only the projects listed, by their shortcut. Leave out anything outside them, and say so in the note.',
39
+ 'Reply with JSON only: {"tasks": [{"project": "<shortcut>", "title": "<the request>"}], "note": "<one line, or empty>"}',
40
+ '',
41
+ `<outcome${due ? ` due="${due}"` : ''}>`,
42
+ text,
43
+ '</outcome>',
44
+ '<projects>',
45
+ ...list,
46
+ '</projects>',
47
+ ].join('\n');
48
+ }
49
+ return [
50
+ 'You check a work order for AI coding agents. The tasks below were done to achieve the outcome. Decide whether the outcome',
51
+ 'is met from what each task delivered. If it is not, list only the remaining tasks needed (the same rules: one agent each, one',
52
+ 'project each by its shortcut, a self-contained request with how to verify it, at most 6). Do not repeat work already delivered.',
53
+ 'Reply with JSON only: {"met": true | false, "reason": "<one line>", "tasks": [{"project": "<shortcut>", "title": "<the request>"}]}',
54
+ '',
55
+ `<outcome${due ? ` due="${due}"` : ''}>`,
56
+ text,
57
+ '</outcome>',
58
+ '<projects>',
59
+ ...list,
60
+ '</projects>',
61
+ '<done>',
62
+ ...done.map((d) => `- (${d.project}) ${d.title}\n outcome: ${d.outcome ?? 'unknown'}${d.delivered.length ? `\n delivered: ${d.delivered.join('; ')}` : ''}${d.prs.length ? `\n pull requests: ${d.prs.join(', ')}` : ''}`),
63
+ '</done>',
64
+ ].join('\n');
65
+ }
66
+
67
+ /** Tasks from a reply, kept to the goal's projects. */
68
+ function tasksFrom(reply, projects, max = MAX_TASKS) {
69
+ const known = new Map(projects.map((p) => [p.shortcut, p]));
70
+ return (Array.isArray(reply?.tasks) ? reply.tasks : [])
71
+ .map((t) => ({ project: String(t?.project ?? '').trim().replace(/^@/, '').toLowerCase(), title: String(t?.title ?? '').trim().slice(0, 2000) }))
72
+ .filter((t) => t.title && known.has(t.project))
73
+ .slice(0, max);
74
+ }
75
+
76
+ export class Goals extends EventEmitter {
77
+ constructor({ manager, store, backlog, config = {}, log = (m) => console.log(`[agentmgr] ${m}`) }) {
78
+ super();
79
+ Object.assign(this, { manager, store, backlog, config, log });
80
+ store.data.goals ??= {};
81
+ this.data = store.data.goals;
82
+ this.checking = new Set();
83
+ this.kick = () => this.schedule();
84
+ backlog.on('change', this.kick);
85
+ manager.on('change', this.kick);
86
+ this.timer = setInterval(this.kick, 60_000);
87
+ this.timer.unref?.();
88
+ }
89
+
90
+ close() {
91
+ clearInterval(this.timer);
92
+ clearTimeout(this.queued);
93
+ this.backlog.off('change', this.kick);
94
+ this.manager.off('change', this.kick);
95
+ }
96
+
97
+ changed() {
98
+ this.store.save();
99
+ this.emit('change', this.list());
100
+ }
101
+
102
+ get(id) {
103
+ const g = this.data[id];
104
+ if (!g) throw err(404, `No goal "${id}"`);
105
+ return g;
106
+ }
107
+
108
+ /** A goal's projects as the backlog knows them (shortcut, name, repo or folder). */
109
+ projectsOf(g) {
110
+ return g.projects.map((s) => this.manager.resolveProject(s)).filter(Boolean);
111
+ }
112
+
113
+ /** New goal: plans it now; queues the tasks at once unless `review`. */
114
+ async create({ text, period = 'week', projects = [], review = false, priority = 2 } = {}) {
115
+ text = String(text ?? '').trim();
116
+ if (!text) throw err(400, 'Say what the goal is');
117
+ if (!GOAL_PERIODS.includes(period)) throw err(400, `period must be one of ${GOAL_PERIODS.join(', ')}`);
118
+ const list = (Array.isArray(projects) ? projects : String(projects).split(',')).map((p) => this.manager.resolveProject(p));
119
+ if (!list.length) throw err(400, 'Pick at least one project');
120
+ if (list.some((p) => !p)) throw err(400, `Unknown project: ${(Array.isArray(projects) ? projects : String(projects).split(','))[list.findIndex((p) => !p)]}`);
121
+ const g = {
122
+ id: crypto.randomBytes(3).toString('hex'),
123
+ text,
124
+ title: text.split('\n')[0].slice(0, 120),
125
+ period,
126
+ due: dueFor(period),
127
+ projects: [...new Set(list.map((p) => p.shortcut))],
128
+ review: Boolean(review),
129
+ priority: Number(priority) >= 0 && Number(priority) <= 3 ? Number(priority) : 2,
130
+ status: 'planning',
131
+ round: 0,
132
+ plan: [],
133
+ note: '',
134
+ items: [],
135
+ checks: [],
136
+ createdAt: now(),
137
+ doneAt: null,
138
+ error: null,
139
+ };
140
+ this.data[g.id] = g;
141
+ this.changed();
142
+ this.plan(g).catch(() => {});
143
+ return this.view(g);
144
+ }
145
+
146
+ /** Ask the model for the tasks (round 0), or what's still missing (later rounds). */
147
+ async plan(g, done = []) {
148
+ const projects = this.projectsOf(g);
149
+ const writer = this.manager.writerFor({});
150
+ try {
151
+ const reply = parseJsonReply(await this.manager.oneShot(null, planPrompt({ text: g.text, projects, due: g.due, done, round: g.round }), writer));
152
+ if (g.round) {
153
+ const tasks = tasksFrom(reply, projects, 6);
154
+ g.checks.push({ at: now(), round: g.round, met: Boolean(reply?.met) || !tasks.length, reason: String(reply?.reason ?? '').slice(0, 300), tasks: tasks.length });
155
+ if (reply?.met || !tasks.length) return this.finish(g);
156
+ this.queue(g, tasks);
157
+ return;
158
+ }
159
+ const tasks = tasksFrom(reply, projects);
160
+ if (!tasks.length) throw new Error(`no tasks for these projects${reply?.note ? `: ${reply.note}` : ''}`);
161
+ g.plan = tasks;
162
+ g.note = String(reply?.note ?? '').slice(0, 300);
163
+ g.error = null;
164
+ if (g.review) {
165
+ g.status = 'review';
166
+ this.changed();
167
+ } else this.queue(g, tasks);
168
+ } catch (e) {
169
+ g.status = g.round ? 'running' : 'error';
170
+ g.error = `Couldn't plan it: ${e.message}`;
171
+ this.log(`goal "${g.title}": ${g.error}`);
172
+ this.changed();
173
+ }
174
+ }
175
+
176
+ /** The tasks go to the backlog, tagged with the goal. */
177
+ queue(g, tasks) {
178
+ for (const t of tasks) {
179
+ const [it] = this.backlog.add([t.title], { project: t.project, priority: g.priority });
180
+ it.goalId = g.id;
181
+ g.items.push(it.id);
182
+ }
183
+ g.status = 'running';
184
+ g.error = null;
185
+ this.backlog.changed();
186
+ this.changed();
187
+ }
188
+
189
+ finish(g) {
190
+ g.status = 'done';
191
+ g.doneAt = now();
192
+ this.log(`goal done: "${g.title}"`);
193
+ this.changed();
194
+ }
195
+
196
+ /** Review: start the plan, with your edits (`tasks`: [{ project, title }]) if any. */
197
+ approve(id, { tasks } = {}) {
198
+ const g = this.get(id);
199
+ if (g.status !== 'review') throw err(409, `The goal is ${g.status}`);
200
+ const list = tasks ? tasksFrom({ tasks }, this.projectsOf(g)) : g.plan;
201
+ if (!list.length) throw err(400, 'No tasks to start');
202
+ g.plan = list;
203
+ this.queue(g, list);
204
+ return this.view(g);
205
+ }
206
+
207
+ /** Plan again (after an error, or to get a different plan before starting). */
208
+ replan(id) {
209
+ const g = this.get(id);
210
+ if (!['error', 'review'].includes(g.status)) throw err(409, `The goal is ${g.status}`);
211
+ g.status = 'planning';
212
+ g.error = null;
213
+ this.changed();
214
+ this.plan(g).catch(() => {});
215
+ return this.view(g);
216
+ }
217
+
218
+ /** Carry an unfinished goal over to the next day or week. */
219
+ extend(id) {
220
+ const g = this.get(id);
221
+ if (g.period === 'none') throw err(409, 'This goal has no deadline');
222
+ const from = Math.max(Date.now(), Date.parse(g.due ?? '') || 0) + 1000;
223
+ g.due = dueFor(g.period, from);
224
+ this.changed();
225
+ return this.view(g);
226
+ }
227
+
228
+ /** Stop: its queued tasks are cancelled; work in progress goes on as ordinary backlog items. */
229
+ stop(id) {
230
+ const g = this.get(id);
231
+ for (const itemId of g.items) {
232
+ const it = this.backlog.data.items[itemId];
233
+ if (it?.status === 'queued') this.backlog.cancel(itemId);
234
+ }
235
+ g.status = 'stopped';
236
+ this.changed();
237
+ return this.view(g);
238
+ }
239
+
240
+ remove(id) {
241
+ const g = this.get(id);
242
+ if (g.status === 'running' || g.status === 'planning') throw err(409, 'Stop the goal first');
243
+ delete this.data[id];
244
+ this.changed();
245
+ return { id };
246
+ }
247
+
248
+ schedule() {
249
+ if (this.queued) return;
250
+ this.queued = setTimeout(() => {
251
+ this.queued = null;
252
+ this.tick();
253
+ }, 1000);
254
+ this.queued.unref?.();
255
+ }
256
+
257
+ /** A running goal whose tasks are all finished: check it against the outcome. */
258
+ tick() {
259
+ for (const g of Object.values(this.data)) {
260
+ if (g.status !== 'running' || this.checking.has(g.id) || !g.items.length) continue;
261
+ const items = g.items.map((id) => this.backlog.data.items[id]).filter(Boolean);
262
+ if (items.some((it) => OPEN.has(it.status))) continue;
263
+ const done = items.filter((it) => it.status === 'done');
264
+ if (!done.length) continue; // all cancelled: leave it to the person
265
+ if (g.round >= CHECK_ROUNDS) {
266
+ g.checks.push({ at: now(), round: g.round + 1, met: null, reason: `Stopped checking after ${CHECK_ROUNDS} extra rounds`, tasks: 0 });
267
+ this.finish(g);
268
+ continue;
269
+ }
270
+ g.round += 1;
271
+ g.status = 'checking';
272
+ this.changed();
273
+ this.checking.add(g.id);
274
+ const projects = this.projectsOf(g);
275
+ this.plan(g, done.map((it) => this.doneFacts(it, projects)))
276
+ .catch(() => {})
277
+ .finally(() => this.checking.delete(g.id));
278
+ }
279
+ }
280
+
281
+ doneFacts(it, projects = []) {
282
+ const agent = it.agentId && this.store.get(it.agentId);
283
+ const r = agent?.brief?.results;
284
+ return {
285
+ title: it.title,
286
+ project: projects.find((p) => p.key === it.projectKey)?.shortcut ?? it.projectName,
287
+ outcome: r?.outcome ?? (agent?.brief?.status === 'done' ? 'done' : null),
288
+ delivered: (r?.delivered ?? []).slice(0, 8),
289
+ prs: Object.values(agent?.prs ?? {})
290
+ .filter((p) => p.source !== 'mentioned')
291
+ .map((p) => `${p.url} (${String(p.state ?? '').toLowerCase()})`),
292
+ };
293
+ }
294
+
295
+ /** Completed, pending and follow-ups, from the goal's backlog items and their agents. */
296
+ summary(g) {
297
+ const completed = [];
298
+ const pending = [];
299
+ const followUps = [];
300
+ for (const id of g.items) {
301
+ const it = this.backlog.data.items[id];
302
+ if (!it) continue;
303
+ const agent = it.agentId ? this.store.get(it.agentId) : null;
304
+ const v = agent ? this.manager.view(agent) : null;
305
+ const prs = (v?.prs ?? []).filter((p) => p.source !== 'mentioned').map((p) => ({ url: p.url, state: p.state }));
306
+ const row = { itemId: it.id, title: it.title, project: it.projectName, status: it.status, agentId: it.agentId, agentName: agent?.name ?? null, prs };
307
+ if (it.status === 'done') {
308
+ completed.push({ ...row, at: it.doneAt });
309
+ continue;
310
+ }
311
+ if (it.status === 'cancelled') continue;
312
+ const why =
313
+ (it.status === 'blocked' && (it.notes || 'Setup failed')) ||
314
+ (it.autopilot?.state === 'held' && it.autopilot.round === it.reviewAt && `Autopilot held: ${it.autopilot.note ?? ''}`) ||
315
+ (it.status === 'review' && this.backlog.autopilotFor(it.projectKey) === 'off' && !it.autopilot?.ship && 'Waiting for your review (Accept or Reopen)') ||
316
+ (v?.runtime.attention && `Needs input: ${v.runtime.attention}`) ||
317
+ (v?.runtime.waiting && `Waiting on you: ${v.runtime.waiting.question || v.runtime.waiting.summary}`) ||
318
+ (v?.questions?.some((q) => !q.answer) && 'Asked a question') ||
319
+ (v?.stuck?.length && `Stuck? ${v.stuck[0].title}`) ||
320
+ (v?.followUp && v.followUp.title) ||
321
+ null;
322
+ if (why) followUps.push({ ...row, why: String(why).slice(0, 300) });
323
+ else pending.push({ ...row, state: it.status === 'review' ? (it.autopilot?.state ? `autopilot: ${it.autopilot.state}` : 'in review') : it.status === 'active' ? 'agent working' : 'queued' });
324
+ }
325
+ return { completed, pending, followUps };
326
+ }
327
+
328
+ view(g) {
329
+ const s = this.summary(g);
330
+ const total = s.completed.length + s.pending.length + s.followUps.length;
331
+ return { ...g, summary: s, counts: { completed: s.completed.length, pending: s.pending.length, followUps: s.followUps.length, total }, overdue: Boolean(g.due && g.status !== 'done' && g.status !== 'stopped' && Date.parse(g.due) < Date.now()) };
332
+ }
333
+
334
+ list() {
335
+ return Object.values(this.data)
336
+ .sort((a, b) => b.createdAt.localeCompare(a.createdAt))
337
+ .map((g) => this.view(g));
338
+ }
339
+ }
340
+
341
+ /** A goal's summary as Markdown: for a stand-up, a status update or a review. */
342
+ export function goalMarkdown(v) {
343
+ const s = v.summary;
344
+ const pr = (r) => (r.prs.length ? ` ${r.prs.map((p) => `[#${p.url.split('/').pop()}](${p.url})${p.state && p.state !== 'OPEN' ? ` ${p.state.toLowerCase()}` : ''}`).join(', ')}` : '');
345
+ const due = v.due ? ` (due ${v.due.slice(0, 10)}${v.overdue ? ', overdue' : ''})` : '';
346
+ return [
347
+ `# Goal: ${v.title}${due}`,
348
+ `${v.counts.completed} completed, ${v.counts.pending} pending, ${v.counts.followUps} follow-up${v.counts.followUps === 1 ? '' : 's'} · ${v.status}`,
349
+ '',
350
+ '## Completed',
351
+ ...(s.completed.length ? s.completed.map((r) => `- ${r.title.split('\n')[0]} (${r.project})${pr(r)}`) : ['- nothing yet']),
352
+ '',
353
+ '## Pending',
354
+ ...(s.pending.length ? s.pending.map((r) => `- ${r.title.split('\n')[0]} (${r.project}): ${r.state}${pr(r)}`) : ['- nothing']),
355
+ '',
356
+ '## Follow-ups',
357
+ ...(s.followUps.length ? s.followUps.map((r) => `- ${r.title.split('\n')[0]} (${r.project}): ${r.why}${pr(r)}`) : ['- none']),
358
+ ].join('\n');
359
+ }