ai-agentmanager 1.17.0 → 1.18.1

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/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
+ }
package/src/manager.js CHANGED
@@ -101,6 +101,7 @@ import { spawn } from 'node:child_process';
101
101
  import * as git from './git.js';
102
102
  import { parseDiff } from '../public/review.js';
103
103
  import { issueSummary, leadingIssue, wordsAfterLink } from './jira.js';
104
+ import { reminderFor, reminderSettings } from './reminders.js';
104
105
  import { combine, facts as scoreFacts, improveMessage, scorecardMarkdown, scorecardPrompt } from './scorecard.js';
105
106
  import { CONTAINER_ENGINES, claudeToken, containerName, containerRunning, engineMounts, gitCommonDir, removeContainer, runArgs, stopContainer } from './container.js';
106
107
  import { conflictMessage, findConflicts, related, repoKey, summarize as summarizeConflicts } from './conflicts.js';
@@ -150,6 +151,8 @@ const ANSI = /\x1b(\[[0-9;?<>=]*[ -\/]*[@-~]|\][^\x07\x1b]*(\x07|\x1b\\)|[()][0-
150
151
  // When a link is found from several sources, the higher-ranked source is kept.
151
152
  const SOURCE_RANK = { manual: 5, intent: 4, session: 3, branch: 2, mentioned: 1 };
152
153
  const BUSY_IDLE_MS = 3000;
154
+ // A planning session moves into its ready repo only after this long without you typing in it.
155
+ const HANDOFF_TYPING_MS = 15000;
153
156
  // The attention label engines give a tool permission menu (what rules can answer).
154
157
  const PERMISSION = 'Permission prompt';
155
158
  /** Looser stuck thresholds: candidates the judge looks at before anyone is bothered. */
@@ -349,7 +352,7 @@ export class AgentManager extends EventEmitter {
349
352
  usage.io = usage.input + usage.output;
350
353
  const costs = (agent.sessions ?? []).map((s) => s.cost?.usd).filter((c) => c != null);
351
354
  const prs = Object.values(agent.prs ?? {});
352
- return {
355
+ const v = {
353
356
  ...agent,
354
357
  // Intent, spec and plan files that exist, with when each changed (task agents).
355
358
  ...(NO_REPO.has(agent.kind) ? {} : { specDocs: specDocsInfo(agent.id) }),
@@ -381,6 +384,9 @@ export class AgentManager extends EventEmitter {
381
384
  prompt: rt?.pty && !rt.busy && rt.attention ? this.promptView(agent, rt) : null,
382
385
  },
383
386
  };
387
+ // A recent agent gone quiet: follow up on it, or close its finished session (reminders.js).
388
+ v.followUp = reminderFor(v, reminderSettings(this.config));
389
+ return v;
384
390
  }
385
391
 
386
392
  /**
@@ -1252,16 +1258,19 @@ export class AgentManager extends EventEmitter {
1252
1258
 
1253
1259
  /**
1254
1260
  * Move a planning session into its now-ready workspace. Without `force` it
1255
- * only does so when nobody is looking at the terminal and Claude is idle, so
1256
- * it never yanks the session away mid-conversation; otherwise it flags the
1257
- * agent "ready" and waits for Continue in repo.
1261
+ * waits until Claude is idle and, with a terminal open, you have stopped
1262
+ * typing too, so it never yanks the session away mid-turn or mid-sentence;
1263
+ * until then it flags the agent "ready" (Continue in repo moves it now).
1258
1264
  */
1259
1265
  async maybeHandoff(id, { force = false } = {}) {
1260
1266
  const agent = this.store.get(id);
1261
1267
  const rt = this.runtimes.get(id);
1262
1268
  if (!agent?.workdir || agent.status === 'preparing' || !(rt?.pty && rt.planning)) return agent && this.view(agent);
1263
1269
  const idleMs = (this.config.handoffIdleSec ?? 5) * 1000;
1264
- const quiet = !rt.clients.size && !rt.busy && Date.now() - (rt.lastOutputAt ?? 0) >= idleMs;
1270
+ const t = Date.now();
1271
+ // Watching the terminal: also wait for a pause in your typing (a half-typed message is lost in the move).
1272
+ const typing = rt.clients.size > 0 && t - (this.inputAt.get(id) ?? 0) < Math.max(idleMs, HANDOFF_TYPING_MS);
1273
+ const quiet = !rt.busy && !typing && t - (rt.lastOutputAt ?? 0) >= idleMs;
1265
1274
  if (!force && !quiet) {
1266
1275
  if (!agent.planning?.ready) this.patch(id, { planning: { ...agent.planning, ready: true } });
1267
1276
  return this.view(agent);
@@ -1304,6 +1313,32 @@ export class AgentManager extends EventEmitter {
1304
1313
  });
1305
1314
  }
1306
1315
 
1316
+ /**
1317
+ * Close every open agent session (not the assistant's), from one button. Agents working right
1318
+ * now are left open unless `working`; they're returned so the person can decide.
1319
+ */
1320
+ async closeAll({ working = false } = {}) {
1321
+ const open = this.store.list().filter((a) => a.kind !== 'assistant' && this.runtimes.get(a.id)?.pty);
1322
+ const busy = (a) => this.runtimes.get(a.id)?.busy;
1323
+ const close = open.filter((a) => working || !busy(a));
1324
+ const results = await Promise.allSettled(close.map((a) => this.stop(a.id)));
1325
+ const failed = close.filter((a, i) => results[i].status === 'rejected').map((a) => ({ id: a.id, name: a.name }));
1326
+ return {
1327
+ closed: close.filter((a, i) => results[i].status === 'fulfilled').map((a) => ({ id: a.id, name: a.name })),
1328
+ failed,
1329
+ working: open.filter((a) => !working && busy(a)).map((a) => ({ id: a.id, name: a.name })),
1330
+ };
1331
+ }
1332
+
1333
+ /** A reminder's "Later" (hidden for a few hours) or "Not needed" (hidden until the agent is used again). */
1334
+ remind(ref, action) {
1335
+ const agent = this.mustGet(ref);
1336
+ const v = this.view(agent);
1337
+ if (action === 'later') return this.view(this.patch(agent.id, { reminder: { ...agent.reminder, laterUntil: new Date(Date.now() + reminderSettings(this.config).laterHours * 3_600_000).toISOString() } }));
1338
+ if (action === 'dismiss') return this.view(this.patch(agent.id, { reminder: { ...agent.reminder, dismissedAt: v.activeAt ?? now() } }));
1339
+ throw Object.assign(new Error('action must be later or dismiss'), { status: 400 });
1340
+ }
1341
+
1307
1342
  /** Daemon shutdown: close everything but remember which agents should come back. */
1308
1343
  async stopAll({ final = false } = {}) {
1309
1344
  // On a real shutdown, a workspace that finishes preparing afterwards must not launch its agent.
@@ -2934,6 +2969,7 @@ export class AgentManager extends EventEmitter {
2934
2969
  if (agent.aiReview?.verdict && !agent.aiReview.seen) {
2935
2970
  items.push({ ...base, kind: 'review', key: `review:${agent.id}`, title: agent.aiReview.summary, review: agent.aiReview, at: agent.aiReview.at });
2936
2971
  }
2972
+ if (v.followUp) items.push({ ...base, kind: 'reminder', key: `reminder:${agent.id}`, title: v.followUp.title, reminder: v.followUp, at: v.followUp.since });
2937
2973
  for (const f of v.stuck) items.push({ ...base, kind: 'stuck', key: `stuck:${agent.id}:${f.key}`, title: f.title, finding: f, at: f.since });
2938
2974
  for (const g of v.conflicts) {
2939
2975
  // One entry per pair, on the agent that should rebase.
@@ -2945,7 +2981,7 @@ export class AgentManager extends EventEmitter {
2945
2981
  for (const r of this.rules.view().suggestions) items.push({ kind: 'rule', key: `rule:${r.repo}:${r.rule}`, title: `Always allow ${r.label}?`, priority: 2, ...r });
2946
2982
  // Others' items (autopilot's held backlog work).
2947
2983
  for (const source of this.inboxSources) items.push(...source());
2948
- const order = { prompt: 0, waiting: 1, question: 1, rule: 2, review: 2, autopilot: 2, stuck: 3, conflict: 4, repeat: 5 };
2984
+ const order = { prompt: 0, waiting: 1, question: 1, rule: 2, review: 2, autopilot: 2, stuck: 3, conflict: 4, reminder: 5, repeat: 5 };
2949
2985
  return items.sort((a, b) => order[a.kind] - order[b.kind] || a.priority - b.priority);
2950
2986
  }
2951
2987
 
@@ -0,0 +1,58 @@
1
+ // Reminders about recent agents that went quiet: work that needs a follow-up, or a finished
2
+ // agent whose session is still open. They show in the inbox once an agent used in the last few
3
+ // days has been quiet for a couple of hours (and isn't already waiting on you for something else):
4
+ // follow-up - open, not finished: nudge it, open it, or close it
5
+ // - closed before it finished, by itself or by the session cap / clean up: resume it
6
+ // close - finished (brief done, or its pull requests merged) with its session still open
7
+ // Agents you closed yourself are left alone. "Later" hides a reminder for a few hours; "Not
8
+ // needed" hides it until the agent is used again.
9
+ export const REMINDER_DEFAULTS = { enabled: true, quietHours: 2, recentDays: 3, laterHours: 4 };
10
+ const HOUR = 3_600_000;
11
+
12
+ /** Settings from config.json's "reminders", with defaults. */
13
+ export function reminderSettings(config = {}) {
14
+ const r = { ...REMINDER_DEFAULTS, ...config.reminders };
15
+ const n = (v, d) => (Number(v) > 0 ? Number(v) : d);
16
+ return { enabled: r.enabled !== false, quietHours: n(r.quietHours, 2), recentDays: n(r.recentDays, 3), laterHours: n(r.laterHours, 4) };
17
+ }
18
+
19
+ const hours = (ms) => {
20
+ const h = Math.floor(ms / HOUR);
21
+ if (h < 1) return `${Math.max(1, Math.floor(ms / 60_000))} minutes`;
22
+ return h >= 48 ? `${Math.floor(h / 24)} days` : `${h} hour${h === 1 ? '' : 's'}`;
23
+ };
24
+
25
+ /**
26
+ * The reminder for an agent's view now, or null: { kind: 'followup' | 'close', title, detail, since }.
27
+ * `v` is the agent's view (runtime, results, prs, activeAt).
28
+ */
29
+ export function reminderFor(v, settings, t = Date.now()) {
30
+ if (!settings.enabled || v.kind === 'assistant' || v.status === 'preparing' || v.builds) return null;
31
+ const rt = v.runtime ?? {};
32
+ if (rt.busy || rt.attention || rt.waiting || rt.planning) return null;
33
+ const active = Date.parse(v.activeAt ?? v.createdAt ?? '') || 0;
34
+ const quiet = t - active;
35
+ if (quiet < settings.quietHours * HOUR || quiet > settings.recentDays * 24 * HOUR) return null;
36
+ const r = v.reminder ?? {};
37
+ if (r.dismissedAt && Date.parse(r.dismissedAt) >= active) return null;
38
+ if (r.laterUntil && Date.parse(r.laterUntil) > t) return null;
39
+ const outcome = v.results?.outcome ?? null;
40
+ const prs = v.prs ?? [];
41
+ const merged = prs.length > 0 && prs.every((p) => p.state === 'MERGED' || p.state === 'CLOSED') && prs.some((p) => p.state === 'MERGED');
42
+ const done = outcome === 'done' || merged;
43
+ const since = new Date(active).toISOString();
44
+ if (rt.running) {
45
+ if (done) return { kind: 'close', title: `${merged ? 'Its pull request merged' : 'Done'} and quiet for ${hours(quiet)}, but its session is still open`, detail: null, since };
46
+ const open = prs.find((p) => p.state === 'OPEN');
47
+ const detail =
48
+ (outcome === 'blocked' && v.results?.blockers?.[0]?.text ? `Blocked: ${v.results.blockers[0].text}` : null) ??
49
+ (open ? `Pull request #${String(open.url ?? '').split('/').pop()} is open${open.land === 'fix' ? ' and needs fixes' : ''}` : null) ??
50
+ (v.git?.dirtyFiles ? `${v.git.dirtyFiles} file${v.git.dirtyFiles === 1 ? '' : 's'} changed, not committed` : null);
51
+ return { kind: 'followup', title: `Quiet for ${hours(quiet)} and not finished`, detail, since };
52
+ }
53
+ // Closed: only when it closed by itself or was closed for you (session cap, clean up).
54
+ const byItself = v.status === 'exited' || v.closedBy === 'cap' || v.closedBy === 'cleanup';
55
+ if (done || !byItself || !v.sessionId) return null;
56
+ const how = v.closedBy === 'cap' ? 'closed by the session cap' : v.closedBy === 'cleanup' ? 'closed by clean up' : 'its session ended';
57
+ return { kind: 'followup', title: `Not finished, and ${how}`, detail: outcome === 'blocked' && v.results?.blockers?.[0]?.text ? `Blocked: ${v.results.blockers[0].text}` : null, since, closed: true };
58
+ }
package/src/server.js CHANGED
@@ -18,12 +18,14 @@ import { Assistant } from './assistant.js';
18
18
  import { Cleanup } from './cleanup.js';
19
19
  import { Landing } from './landing.js';
20
20
  import { Autopilot } from './autopilot.js';
21
+ import { Goals, goalMarkdown } from './goals.js';
21
22
  import { Budgets } from './budgets.js';
22
23
  import { stats } from './stats.js';
23
24
  import { Playbooks } from './playbooks.js';
24
25
  import { Repeats } from './repeats.js';
25
26
  import { Updates } from './update.js';
26
27
  import { identity } from './identity.js';
28
+ import { WorkLog, summaryMarkdown } from './worklog.js';
27
29
  import { Studio } from './studio.js';
28
30
  import { Memory } from './memory.js';
29
31
  import { doctor } from './doctor.js';
@@ -95,6 +97,11 @@ export async function startServer({ port = PORT, host = HOST } = {}) {
95
97
  // Backlog work the scorecard calls ready goes on to a pull request (and merged) by itself.
96
98
  const autopilot = new Autopilot({ manager, store, backlog, review, landing, config });
97
99
  manager.inboxSources.push(() => autopilot.inbox());
100
+ // Daily or weekly goals across projects, planned into backlog tasks and seen through (goals.js).
101
+ const goals = new Goals({ manager, store, backlog, config });
102
+ // What agents got done, appended to a CSV for reviews (worklog.js).
103
+ const me = identity().then((i) => i.display, () => '');
104
+ const worklog = new WorkLog({ manager, store, config, who: me });
98
105
  const assistant = new Assistant({ manager, store, config });
99
106
  // Alerts link to the phone address when remote access is on, else the local UI.
100
107
  const notifier = new Notifier({
@@ -416,6 +423,8 @@ export async function startServer({ port = PORT, host = HOST } = {}) {
416
423
  );
417
424
  api.post('/agents/:id/start', wrap((req) => manager.start(req.params.id, req.body ?? {})));
418
425
  api.post('/agents/:id/stop', wrap((req) => manager.stop(req.params.id)));
426
+ api.post('/agents/close-all', wrap((req) => manager.closeAll({ working: Boolean(req.body?.working) })));
427
+ api.post('/agents/:id/reminder', wrap((req) => manager.remind(req.params.id, req.body?.action)));
419
428
  api.post('/agents/:id/desktop', wrap((req) => manager.openInDesktop(req.params.id)));
420
429
  api.post('/agents/:id/refresh', wrap((req) => manager.refresh(req.params.id, { withPrs: true })));
421
430
  api.post('/agents/:id/links', wrap((req) => manager.addLink(req.params.id, req.body ?? {})));
@@ -696,6 +705,19 @@ export async function startServer({ port = PORT, host = HOST } = {}) {
696
705
  api.get('/repeats', wrap(() => repeats.view()));
697
706
  api.post('/repeats/dismiss', wrap((req) => repeats.dismiss(String(req.body?.key ?? ''))));
698
707
  api.post('/playbooks/:id/run', wrap((req) => playbooks.run(req.params.id, { vars: req.body?.vars ?? {} })));
708
+ api.get('/worklog', wrap(async (req) => (await worklog.record(), worklog.view({ days: Number(req.query.days ?? 30) || 0 }))));
709
+ api.get('/worklog/summary', wrap(async (req) => {
710
+ await worklog.record();
711
+ return { markdown: summaryMarkdown(worklog.view({ days: Number(req.query.days ?? 30) || 0 }), { who: await me }) };
712
+ }));
713
+ for (const [name, which] of [['worklog.csv', 'events'], ['worklog-weekly.csv', 'weekly']]) {
714
+ api.get(`/worklog/${name}`, async (req, res) => {
715
+ await worklog.record().catch(() => {});
716
+ const file = worklog.files[which];
717
+ if (!fs.existsSync(file)) return res.status(404).json({ error: 'Nothing recorded yet' });
718
+ res.download(file, name);
719
+ });
720
+ }
699
721
  api.get('/stats', wrap((req) => {
700
722
  const days = req.query.days === undefined ? 30 : Math.max(0, Math.min(3650, Math.floor(Number(req.query.days)) || 0));
701
723
  return stats(store.list(), { days, projectOf: (a) => manager.projectInfo(a)?.name ?? null });
@@ -747,6 +769,14 @@ export async function startServer({ port = PORT, host = HOST } = {}) {
747
769
  api.post('/backlog/:id/move', wrap((req) => backlog.move(req.params.id, req.body?.where)));
748
770
  api.post('/backlog/:id/split', wrap((req) => backlog.split(req.params.id, req.body?.parts)));
749
771
  api.post('/backlog/:id/keep-whole', wrap((req) => backlog.keepWhole(req.params.id)));
772
+ api.get('/goals', wrap(() => goals.list()));
773
+ api.post('/goals', wrap((req) => goals.create(req.body ?? {})));
774
+ api.post('/goals/:id/approve', wrap((req) => goals.approve(req.params.id, req.body ?? {})));
775
+ api.post('/goals/:id/replan', wrap((req) => goals.replan(req.params.id)));
776
+ api.post('/goals/:id/extend', wrap((req) => goals.extend(req.params.id)));
777
+ api.post('/goals/:id/stop', wrap((req) => goals.stop(req.params.id)));
778
+ api.delete('/goals/:id', wrap((req) => goals.remove(req.params.id)));
779
+ api.get('/goals/:id/summary', wrap((req) => ({ markdown: goalMarkdown(goals.view(goals.get(req.params.id))) })));
750
780
  api.post('/backlog/:id/ship', wrap((req) => autopilot.shipNow(req.params.id)));
751
781
  api.post(
752
782
  '/shutdown',
@@ -863,7 +893,7 @@ export async function startServer({ port = PORT, host = HOST } = {}) {
863
893
  const eventSinks = new Set();
864
894
  api.get('/events/stream', (req, res) => {
865
895
  const send = sse(req, res);
866
- send({ t: 'snapshot', agents: manager.list(), backlog: backlog.view(), projects: manager.listProjects(), races: races.list(), teams: teams.list(), built: reports.list() });
896
+ send({ t: 'snapshot', agents: manager.list(), backlog: backlog.view(), goals: goals.list(), projects: manager.listProjects(), races: races.list(), teams: teams.list(), built: reports.list() });
867
897
  eventSinks.add(send);
868
898
  req.on('close', () => eventSinks.delete(send));
869
899
  });
@@ -964,6 +994,19 @@ export async function startServer({ port = PORT, host = HOST } = {}) {
964
994
  live.closeAgent(id).catch(() => {});
965
995
  });
966
996
  backlog.on('change', (view) => broadcast({ t: 'backlog', backlog: view }));
997
+ // Goals' summaries follow their tasks and agents: sent at most every couple of seconds.
998
+ let goalsSoon = null;
999
+ const sendGoals = () => {
1000
+ if (goalsSoon) return;
1001
+ goalsSoon = setTimeout(() => {
1002
+ goalsSoon = null;
1003
+ broadcast({ t: 'goals', goals: goals.list() });
1004
+ }, 2000);
1005
+ goalsSoon.unref?.();
1006
+ };
1007
+ goals.on('change', sendGoals);
1008
+ backlog.on('change', sendGoals);
1009
+ manager.on('change', () => Object.values(goals.data).some((g) => g.status === 'running') && sendGoals());
967
1010
  const raceTimers = new Map();
968
1011
  races.on('change', (id) => {
969
1012
  if (raceTimers.has(id)) return;
@@ -995,7 +1038,7 @@ export async function startServer({ port = PORT, host = HOST } = {}) {
995
1038
  const url = new URL(req.url, 'http://x');
996
1039
  if (url.pathname === '/ws/events') {
997
1040
  eventClients.add(ws);
998
- ws.send(JSON.stringify({ t: 'snapshot', agents: manager.list(), backlog: backlog.view(), projects: manager.listProjects(), races: races.list(), teams: teams.list(), built: reports.list(), rules: manager.rules.view(), repeats: repeats.view() }));
1041
+ ws.send(JSON.stringify({ t: 'snapshot', agents: manager.list(), backlog: backlog.view(), goals: goals.list(), projects: manager.listProjects(), races: races.list(), teams: teams.list(), built: reports.list(), rules: manager.rules.view(), repeats: repeats.view() }));
999
1042
  ws.on('close', () => eventClients.delete(ws));
1000
1043
  return;
1001
1044
  }
@@ -1077,6 +1120,8 @@ export async function startServer({ port = PORT, host = HOST } = {}) {
1077
1120
  cleanup.close();
1078
1121
  landing.close();
1079
1122
  autopilot.close();
1123
+ goals.close();
1124
+ worklog.close();
1080
1125
  triggers.close();
1081
1126
  budgets.close();
1082
1127
  playbooks.close();