ai-agentmanager 1.48.0 → 1.50.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/advisor.js ADDED
@@ -0,0 +1,780 @@
1
+ // Decide: help with the decisions, not only the tasks.
2
+ // brief - a plan waiting for review or an agent's question arrives with its options, the one
3
+ // recommended, why, the evidence, the risk and how hard it is to undo.
4
+ // standing - a call you keep making becomes a standing decision: offered once it is seen three
5
+ // times, and from then on handled for you and reported afterwards.
6
+ // autonomy - per project, how much may be decided without you.
7
+ // impact - the backlog ranked by what each item is worth now (the nearest date, what it
8
+ // unblocks, its priority), with the reason beside it.
9
+ // tradeoff - a date at risk laid out as choices (cut, move the date, add agents), one
10
+ // recommended; picking one carries it out and logs it.
11
+ // evidence - "Try both": the options of a question run as a race, so you decide from results.
12
+ // lookback - what followed each past decision; the ones worth another look, and what they teach.
13
+ // The reasoning is the AI judge's (one tool-less call each, on your own plan, within its daily
14
+ // budget). With the judge off, plain rules stand in and say so.
15
+
16
+ import crypto from 'node:crypto';
17
+
18
+ export const LEVELS = ['ask', 'standing', 'safe', 'most'];
19
+ export const LEVEL_LABEL = {
20
+ ask: 'Ask me everything',
21
+ standing: 'Only my standing decisions',
22
+ safe: 'Also what is sure and easy to undo',
23
+ most: 'Most things; ask when unsure',
24
+ };
25
+ export const SURE = 0.85;
26
+ export const LIKELY = 0.7;
27
+ export const OFFER_AFTER = 3;
28
+ const DAY = 86_400_000;
29
+ const err = (status, message) => Object.assign(new Error(message), { status });
30
+ const hash = (s) => crypto.createHash('sha1').update(String(s)).digest('hex').slice(0, 12);
31
+ const clip = (s, n) => {
32
+ const t = String(s ?? '').replace(/\s+/g, ' ').trim();
33
+ return t.length > n ? `${t.slice(0, n - 1)}…` : t;
34
+ };
35
+ const norm = (s) => String(s ?? '').toLowerCase().replace(/[^a-z0-9]+/g, ' ').trim();
36
+ const JSON_ONLY = 'Reply with one JSON object and nothing else.';
37
+
38
+ /** Whether a brief may be carried out without asking, at this level of autonomy. */
39
+ export function mayAct(level, b) {
40
+ if (!b || level === 'ask' || !LEVELS.includes(level)) return false;
41
+ const opt = b.options?.[b.recommend];
42
+ if (!opt || !['approve', 'changes', 'answer'].includes(opt.action)) return false;
43
+ if ((opt.action === 'changes' || opt.action === 'answer') && !opt.text) return false;
44
+ const c = Number(b.confidence) || 0;
45
+ if (b.standing && c >= LIKELY) return true;
46
+ if (level === 'safe') return c >= SURE && b.undo === 'easy';
47
+ if (level === 'most') return c >= LIKELY && b.undo === 'easy';
48
+ return false;
49
+ }
50
+
51
+ const standingLines = (rules) =>
52
+ rules.length
53
+ ? `Standing decisions the person has made (apply one only when it clearly fits; then name its id in "standing"):\n${rules.map((r) => `- [${r.id}] when ${r.when} -> ${r.action}${r.text ? `: ${r.text}` : ''}`).join('\n')}`
54
+ : 'The person has no standing decisions for this yet ("standing": null).';
55
+ const pastLines = (past) =>
56
+ past.length ? `How the person decided similar things lately:\n${past.map((h) => `- ${clip(h.title, 120)}: recommended "${clip(h.recommended, 60)}", they chose "${clip(h.chose, 80)}"${h.note ? ` (${clip(h.note, 100)})` : ''}`).join('\n')}` : '';
57
+ const lessonLines = (lessons) => (lessons.length ? `What earlier decisions taught:\n${lessons.map((l) => `- ${clip(l, 200)}`).join('\n')}` : '');
58
+
59
+ /** The prompt for one thing waiting on the person: a plan to review, or an agent's question. */
60
+ export function briefPrompt(item, { standing = [], past = [], lessons = [], dates = '' } = {}) {
61
+ const head =
62
+ 'You advise a senior engineer who supervises AI coding agents. Something waits for their decision. ' +
63
+ 'Lay out the real options, recommend one, and say why in terms of this project. Be concrete and brief; do not flatter; when the evidence is thin, say so with a low confidence.';
64
+ const shape =
65
+ item.kind === 'plan'
66
+ ? '{"options":[{"label":"Approve","action":"approve","text":"","consequence":"..."},{"label":"Send back","action":"changes","text":"exactly what to change, as you would tell the agent","consequence":"..."}],"recommend":0,"why":"...","evidence":["what in the plan or the project supports it"],"risk":"what could go wrong with the recommendation","undo":"easy|hard","confidence":0.0,"standing":null}'
67
+ : '{"options":[{"label":"short name","action":"answer","text":"the answer to send the agent","consequence":"..."}],"recommend":0,"why":"...","evidence":["..."],"risk":"...","undo":"easy|hard","confidence":0.0,"standing":null}';
68
+ const body =
69
+ item.kind === 'plan'
70
+ ? `The agent "${item.agentName}" wrote an implementation plan and waits for approval before changing anything.\nWhat it was asked: ${clip(item.intent, 1200)}\n\nThe plan:\n${String(item.markdown ?? '').slice(0, 7000)}\n\nCheck it against the ask: scope (too much, too little), order, tests and how it will be verified, what it could break, and how it is rolled back.`
71
+ : `The agent "${item.agentName}" asks a question and goes on with its default until answered.\nWhat it was asked to do: ${clip(item.intent, 1200)}\nThe question: ${item.question}\n${item.context ? `Context: ${item.context}\n` : ''}${item.options?.length ? `Its options: ${item.options.join(' | ')}\n` : ''}${item.default ? `Its default: ${item.default}\n` : ''}Give two to four options (its own when it named them).`;
72
+ return [
73
+ head,
74
+ `Project: ${item.project}.${dates ? ` ${dates}` : ''}`,
75
+ body,
76
+ standingLines(standing),
77
+ pastLines(past),
78
+ lessonLines(lessons),
79
+ '"undo" is "hard" when the choice is costly to reverse once acted on (data, public interfaces, releases, money, a large rewrite), else "easy". "confidence" is how sure you are that the person would agree, 0 to 1.',
80
+ `${JSON_ONLY} Shape: ${shape}`,
81
+ ]
82
+ .filter(Boolean)
83
+ .join('\n\n');
84
+ }
85
+
86
+ /** A reply made safe to keep and show; null when it isn't usable. */
87
+ export function normalizeBrief(d, item, standing = []) {
88
+ if (!d || !Array.isArray(d.options)) return null;
89
+ const allowed = item.kind === 'plan' ? ['approve', 'changes'] : ['answer'];
90
+ const options = d.options
91
+ .filter((o) => o && allowed.includes(o.action))
92
+ .slice(0, 4)
93
+ .map((o) => ({ label: clip(o.label || o.action, 60), action: o.action, text: clip(o.text, 1200), consequence: clip(o.consequence, 300) }))
94
+ .filter((o) => o.action === 'approve' || o.text);
95
+ if (!options.length) return null;
96
+ const recommend = Number.isInteger(d.recommend) && options[d.recommend] ? d.recommend : 0;
97
+ return {
98
+ options,
99
+ recommend,
100
+ why: clip(d.why, 600),
101
+ evidence: (Array.isArray(d.evidence) ? d.evidence : []).map((e) => clip(e, 240)).filter(Boolean).slice(0, 4),
102
+ risk: clip(d.risk, 300),
103
+ undo: d.undo === 'hard' ? 'hard' : 'easy',
104
+ confidence: Math.max(0, Math.min(1, Number(d.confidence) || 0)),
105
+ standing: standing.some((r) => r.id === d.standing) ? d.standing : null,
106
+ };
107
+ }
108
+
109
+ /** Asked when three or more recent decisions may share a pattern worth making standing. */
110
+ export function standingPrompt(history, rules) {
111
+ return [
112
+ 'A senior engineer decides on AI agents\' plans and questions. Below are their recent decisions, numbered. Find calls they keep making that could be made once: a condition and the action they always take when it holds.',
113
+ 'Offer one only when at least three of the decisions clearly agree and none contradicts it. Make the condition specific enough to be safe (name the kind of change, the project when it matters), never "always approve".',
114
+ `Decisions:\n${history.map((h, i) => `${i + 1}. [${h.kind}, project ${h.project}] ${clip(h.title, 140)} -> ${clip(h.chose, 100)}${h.note ? ` (${clip(h.note, 120)})` : ''}`).join('\n')}`,
115
+ rules.length ? `Already standing (do not repeat):\n${rules.map((r) => `- when ${r.when} -> ${r.action}`).join('\n')}` : '',
116
+ `${JSON_ONLY} Shape: {"offers":[{"kind":"plan|question","project":"the project's name, or null for every project","when":"the condition, in the person's words","action":"approve|changes|answer","text":"the note or answer to send; empty for approve","basedOn":[1,2,3],"confidence":0.0}]}. An empty list when there is no clear pattern.`,
117
+ ]
118
+ .filter(Boolean)
119
+ .join('\n\n');
120
+ }
121
+
122
+ /** Without the judge: the same question answered the same way three times. */
123
+ export function standingFallback(history) {
124
+ const groups = new Map();
125
+ for (const h of history) {
126
+ if (h.kind !== 'question') continue;
127
+ const k = `${norm(h.title)}|${norm(h.chose)}`;
128
+ groups.set(k, [...(groups.get(k) ?? []), h]);
129
+ }
130
+ return [...groups.values()]
131
+ .filter((g) => g.length >= OFFER_AFTER)
132
+ .map((g) => ({ kind: 'question', project: new Set(g.map((h) => h.project)).size === 1 ? g[0].project : null, when: `an agent asks "${clip(g[0].title, 160)}"`, action: 'answer', text: g[0].chose, count: g.length, confidence: 0.8 }));
133
+ }
134
+
135
+ /** What a backlog item is worth doing now, by plain rules: { score, reasons }. */
136
+ export function impactScore(it, { stage = null, now = Date.now() } = {}) {
137
+ const reasons = [];
138
+ let score = [40, 25, 12, 4][it.priority] ?? 12;
139
+ reasons.push(`P${it.priority}`);
140
+ if (stage && !stage.reached) {
141
+ const n = stage.daysLeft;
142
+ const add = n < 0 ? 30 : n <= 7 ? 25 : n <= 14 ? 15 : n <= 30 ? 5 : 0;
143
+ if (add) {
144
+ score += add;
145
+ reasons.push(n < 0 ? `${stage.label} is ${-n} day${n === -1 ? '' : 's'} late` : `${stage.label} in ${n} day${n === 1 ? '' : 's'}`);
146
+ }
147
+ }
148
+ if (/\b(fix|bug|crash|regression|broken|fail(s|ing|ure)?|security|data loss|leak)\b/i.test(it.title)) {
149
+ score += 10;
150
+ reasons.push('a fix');
151
+ }
152
+ if (/\b(block(s|ed|er|ing)?|unblock|prerequisite|needed (for|by)|before (rc|ga|release))\b/i.test(`${it.title} ${it.notes ?? ''}`)) {
153
+ score += 8;
154
+ reasons.push('unblocks other work');
155
+ }
156
+ const age = Math.floor((now - (Date.parse(it.createdAt) || now)) / DAY);
157
+ if (age >= 7) {
158
+ score += Math.min(8, Math.floor(age / 7) * 2);
159
+ reasons.push(`waiting ${age} days`);
160
+ }
161
+ if (it.status === 'active' || it.status === 'review') score += 5; // nearly there: finishing beats starting
162
+ return { score, reasons };
163
+ }
164
+
165
+ export function impactPrompt(items, { project, dates, bugs = 0, decisions = [] } = {}) {
166
+ return [
167
+ 'Rank a project\'s open backlog by impact: what is worth the most to do next. Weigh the nearest commitment date, what an item unblocks, risk removed (bugs, security, data), what users notice, and effort. An item that others depend on comes before them.',
168
+ `Project: ${project}. ${dates || 'No commitment dates set.'}${bugs ? ` Open critical or high bugs: ${bugs}.` : ''}`,
169
+ decisions.length ? `Recent decisions here:\n${decisions.map((d) => `- ${clip(d, 160)}`).join('\n')}` : '',
170
+ `Items:\n${items.map((it) => `- [${it.id}] P${it.priority}, ${it.status}: ${clip(it.title, 300)}`).join('\n')}`,
171
+ `${JSON_ONLY} Shape: {"order":[{"id":"...","impact":"high|medium|low","why":"one line: what it is worth now","unblocks":["ids it should come before"],"priority":0}],"confidence":0.0}. Every id once, most valuable first. "priority" (0 to 3) only when the item's priority is clearly wrong, else leave it out.`,
172
+ ]
173
+ .filter(Boolean)
174
+ .join('\n\n');
175
+ }
176
+
177
+ /** Items finished per day lately, from the backlog's own record. */
178
+ export function pace(items, { now = Date.now(), days = 14 } = {}) {
179
+ const done = items.filter((it) => it.status === 'done' && it.doneAt && now - Date.parse(it.doneAt) <= days * DAY).length;
180
+ return Math.round((done / days) * 100) / 100;
181
+ }
182
+
183
+ const addDays = (date, n) => new Date(Date.parse(`${date}T12:00:00Z`) + n * DAY).toISOString().slice(0, 10);
184
+
185
+ /**
186
+ * A date at risk as choices. `ranked` is the project's open items, most valuable first (each with
187
+ * its status); `perDay` the pace; `limit` how many agents run at once now.
188
+ */
189
+ export function tradeoffOptions({ stage, ranked, perDay, limit = 1 }) {
190
+ const open = ranked.length;
191
+ const left = Math.max(0, stage.daysLeft);
192
+ const need = perDay > 0 ? Math.ceil(open / perDay) : null;
193
+ const fits = perDay > 0 ? Math.floor(perDay * left) : 0;
194
+ const slip = need === null ? Math.max(3, Math.ceil(open / Math.max(1, limit)) - left) : Math.max(0, need - left);
195
+ const queued = ranked.filter((it) => it.status === 'queued');
196
+ const out = [];
197
+ const over = Math.max(0, open - fits);
198
+ const cut = queued.slice(-Math.min(queued.length, over || 0)).reverse();
199
+ if (cut.length) {
200
+ out.push({
201
+ id: 'cut',
202
+ label: `Cut ${cut.length} item${cut.length === 1 ? '' : 's'}`,
203
+ what: `Hold the ${cut.length === 1 ? 'least valuable queued item' : `${cut.length} least valuable queued items`} until after ${stage.label} (${stage.date}).`,
204
+ consequence: over > cut.length ? `Still ${over - cut.length} more than the pace allows: the rest is already started.` : `What is left fits the ${left} day${left === 1 ? '' : 's'} at the current pace.`,
205
+ items: cut.map((it) => ({ id: it.id, title: it.title })),
206
+ });
207
+ }
208
+ const move = Math.max(1, slip);
209
+ out.push({ id: 'move', label: `Move the date ${move} day${move === 1 ? '' : 's'}`, what: `${stage.label} moves from ${stage.date} to ${addDays(stage.date, move)}; later dates move with it when they would no longer be in order.`, consequence: 'Everything planned stays in. Whoever was promised the date has to be told.', days: move, date: addDays(stage.date, move) });
210
+ const extra = Math.min(queued.length, Math.max(1, Math.min(3, Math.ceil(over / Math.max(1, left || 1)))));
211
+ if (queued.length) {
212
+ out.push({ id: 'add', label: `Run ${extra} more agent${extra === 1 ? '' : 's'}`, what: `Raise this project's limit from ${limit} to ${limit + extra} agents at once, so ${extra} more queued item${extra === 1 ? ' starts' : 's start'} now.`, consequence: 'More in parallel: more of your time on reviews and answers, more spend, and more chance of agents overlapping.', extra, limit: limit + extra });
213
+ }
214
+ // Plain rules for the recommendation, when the judge isn't asked.
215
+ const rule = out.find((o) => o.id === 'add') && slip <= 2 ? 'add' : out.find((o) => o.id === 'cut') && cut.length <= Math.max(1, Math.round(open * 0.3)) ? 'cut' : 'move';
216
+ return { options: out, open, perDay, need, slip, recommend: rule, why: rule === 'add' ? 'The gap is a day or two: more in parallel closes it.' : rule === 'cut' ? 'A few of the least valuable items account for the gap.' : 'The gap is too wide to close by cutting a little or adding agents.' };
217
+ }
218
+
219
+ export function tradeoffPrompt({ project, stage, facts, t }) {
220
+ return [
221
+ 'A project\'s commitment date is at risk. Recommend one of the choices below, as a senior engineering lead would: protect what the date is for, be honest about what is given up.',
222
+ `Project: ${project}. ${stage.label} is ${stage.date} (${stage.words}). Open work: ${t.open} item${t.open === 1 ? '' : 's'}; pace lately ${t.perDay} finished a day${t.need !== null ? `, so about ${t.need} days are needed` : ''}. ${facts}`,
223
+ `Choices:\n${t.options.map((o) => `- ${o.id}: ${o.what} ${o.consequence}${o.items ? ` Items: ${o.items.map((i) => clip(i.title, 80)).join('; ')}` : ''}`).join('\n')}`,
224
+ `${JSON_ONLY} Shape: {"recommend":"${t.options.map((o) => o.id).join('|')}","why":"two sentences at most","confidence":0.0}`,
225
+ ].join('\n\n');
226
+ }
227
+
228
+ /** What followed a decision, from the agent it was about: { outcome: held|revisit|early, signs }. */
229
+ export function lookBackSigns(decision, agent, { stageLate = false, item = null } = {}) {
230
+ const signs = [];
231
+ if (!agent) return { outcome: 'early', signs: ['its agent is gone'] };
232
+ const after = (t) => t && String(t) > String(decision.at);
233
+ if (decision.kind === 'plan' && decision.decision === 'Approved' && agent.planReview?.status === 'changes' && after(agent.planReview.decidedAt)) signs.push('the plan was sent back after it was approved');
234
+ if (agent.aiReview?.verdict && agent.aiReview.verdict !== 'complete') signs.push(`the finished work was judged ${agent.aiReview.verdict.replace('_', ' ')}${agent.aiReview.missing?.length ? `: missing ${clip(agent.aiReview.missing.join('; '), 160)}` : ''}`);
235
+ const prs = Object.values(agent.prs ?? {}).filter((p) => p.source !== 'mentioned');
236
+ if (prs.some((p) => p.checks?.state === 'failed')) signs.push('its pull request has failing checks');
237
+ if (prs.some((p) => p.state === 'CLOSED')) signs.push('its pull request was closed without merging');
238
+ if ((item?.reopened ?? 0) > 0) signs.push(`the work was reopened ${item.reopened === 1 ? 'once' : `${item.reopened} times`}`);
239
+ if (agent.status === 'error') signs.push('the agent ended in an error');
240
+ if (stageLate) signs.push('a date of the project has since been missed');
241
+ if (signs.length) return { outcome: 'revisit', signs };
242
+ const landed = prs.some((p) => p.state === 'MERGED') || agent.status === 'done' || item?.status === 'done';
243
+ return landed ? { outcome: 'held', signs: ['the work landed'] } : { outcome: 'early', signs: [] };
244
+ }
245
+
246
+ export function lookBackPrompt(rows) {
247
+ return [
248
+ 'Look back at decisions a senior engineer made about AI agents\' work, with what followed each. For each, say whether the decision itself is worth another look (it likely caused what followed) or held (what followed has another cause), and the lesson in one line the person could apply next time. No blame, no generalities.',
249
+ rows.map((r, i) => `${i + 1}. [${r.id}] ${r.kind} on ${r.project}: ${clip(r.title, 140)} -> ${clip(r.decision, 120)}${r.why ? ` (because: ${clip(r.why, 160)})` : ''}\n What followed: ${r.signs.join('; ')}`).join('\n'),
250
+ `${JSON_ONLY} Shape: {"items":[{"id":"...","verdict":"revisit|held","lesson":"..."}],"confidence":0.0}`,
251
+ ].join('\n\n');
252
+ }
253
+
254
+ export class Advisor {
255
+ /**
256
+ * manager: the agents (approvePlan, requestPlanChanges, answerQuestion, view, judge, listProjects);
257
+ * backlog, milestones, decisions, races: the other parts it reads and acts through;
258
+ * questions(agent): its questions; projectOf(agent): its project.
259
+ */
260
+ constructor({ store, manager, backlog, milestones, decisions, races, questions, projectOf, bugs = () => 0, enabled = () => true, notify = null, onChange = () => {}, now = () => Date.now(), log = (m) => console.log(`[agentmgr] ${m}`), timer = true }) {
261
+ Object.assign(this, { store, manager, backlog, milestones, decisions, races, questions, projectOf, bugs, enabled, notify, onChange, now, log });
262
+ this.pending = new Set();
263
+ if (timer) {
264
+ this.timer = setInterval(() => this.tick().catch(() => {}), 20_000);
265
+ this.timer.unref?.();
266
+ this.slow = setInterval(() => this.lookBack().catch(() => {}), 60 * 60_000);
267
+ this.slow.unref?.();
268
+ }
269
+ }
270
+
271
+ close() {
272
+ clearInterval(this.timer);
273
+ clearInterval(this.slow);
274
+ }
275
+
276
+ get judge() {
277
+ return this.manager.judge;
278
+ }
279
+
280
+ get state() {
281
+ const s = (this.store.data.advisor ??= {});
282
+ for (const [k, v] of Object.entries({ briefs: {}, standing: {}, offers: {}, dismissed: {}, autonomy: {}, handled: [], history: [], impact: {}, tradeoffs: {}, reviews: {}, lessons: [], learnedAt: 0 })) s[k] ??= v;
283
+ return s;
284
+ }
285
+
286
+ save() {
287
+ this.store.save();
288
+ this.onChange();
289
+ }
290
+
291
+ iso() {
292
+ return new Date(this.now()).toISOString();
293
+ }
294
+
295
+ levelFor(projectKey) {
296
+ return this.state.autonomy[projectKey] ?? 'standing';
297
+ }
298
+
299
+ setAutonomy(projectKey, level) {
300
+ if (!LEVELS.includes(level)) throw err(400, `level must be one of ${LEVELS.join(', ')}`);
301
+ if (!projectKey) throw err(400, 'Pick a project');
302
+ this.state.autonomy[projectKey] = level;
303
+ this.save();
304
+ this.tick().catch(() => {});
305
+ return this.view();
306
+ }
307
+
308
+ // ------------------------------------------------------------ what waits
309
+
310
+ /** Everything a brief is written for, as it stands now. */
311
+ waiting() {
312
+ const out = [];
313
+ for (const a of this.store.list()) {
314
+ const p = this.projectOf(a);
315
+ if (!p || ['general', 'assistant'].includes(p.key) || a.hunting || a.reviewing) continue;
316
+ const base = { agentId: a.id, agentName: a.name, intent: a.intent, project: p.name, projectKey: p.key };
317
+ const pr = a.planReview;
318
+ if (pr?.status === 'review' && pr.markdown) out.push({ ...base, key: `plan:${a.id}`, kind: 'plan', title: pr.markdown.match(/^#\s+(.+)$/m)?.[1] ?? `Plan for ${a.name}`, markdown: pr.markdown, hash: hash(pr.markdown) });
319
+ for (const q of this.questions(a)) {
320
+ if (a.answers?.[q.id]) continue;
321
+ out.push({ ...base, key: `q:${a.id}:${q.id}`, kind: 'question', qid: q.id, title: q.question, question: q.question, context: q.context, options: q.options, default: q.default, hash: hash(`${q.question}|${q.context}|${q.options.join('|')}`) });
322
+ }
323
+ }
324
+ return out;
325
+ }
326
+
327
+ rulesFor(item) {
328
+ return Object.values(this.state.standing).filter((r) => r.on !== false && r.kind === item.kind && (!r.project || r.project === item.projectKey));
329
+ }
330
+
331
+ datesFor(projectKey) {
332
+ const p = this.manager.listProjects().find((x) => x.key === projectKey);
333
+ const stages = p ? this.milestones.stages(p) : [];
334
+ return { p, stages, next: stages.find((s) => !s.reached) ?? null, words: stages.filter((s) => !s.reached).map((s) => `${s.label}: ${s.date} (${s.words}, ${s.status.replace('-', ' ')})`).join('; ') };
335
+ }
336
+
337
+ /** Write the briefs that are missing, settle the ones decided elsewhere, and act where allowed. */
338
+ async tick() {
339
+ if (!this.enabled()) return;
340
+ const st = this.state;
341
+ const items = this.waiting();
342
+ const live = new Map(items.map((i) => [i.key, i]));
343
+ let changed = false;
344
+ // Decided without the brief (in the plan dialog, the inbox, the terminal): learn from it.
345
+ for (const b of Object.values(st.briefs)) {
346
+ if (live.has(b.key)) continue;
347
+ if (b.status === 'open') {
348
+ this.settle(b);
349
+ changed = true;
350
+ }
351
+ if (this.now() - Date.parse(b.at) > 14 * DAY) {
352
+ delete st.briefs[b.key];
353
+ changed = true;
354
+ }
355
+ }
356
+ if (changed) this.save();
357
+ const jobs = [];
358
+ for (const item of items) {
359
+ const have = st.briefs[item.key];
360
+ if (have?.hash === item.hash && have.status !== 'stale') {
361
+ if (have.status === 'open' && mayAct(this.levelFor(item.projectKey), have)) jobs.push(this.apply(item.key, have.recommend, { by: 'auto' }).catch((e) => this.log(`decide: ${e.message}`)));
362
+ continue;
363
+ }
364
+ if (this.pending.has(item.key)) continue;
365
+ this.pending.add(item.key);
366
+ jobs.push(this.write(item).finally(() => this.pending.delete(item.key)));
367
+ }
368
+ await Promise.all(jobs);
369
+ this.learn().catch(() => {});
370
+ }
371
+
372
+ async write(item) {
373
+ const standing = this.rulesFor(item);
374
+ const past = this.state.history.filter((h) => h.kind === item.kind).slice(-6);
375
+ const prompt = briefPrompt(item, { standing, past, lessons: this.state.lessons.slice(-5), dates: this.datesFor(item.projectKey).words });
376
+ const agent = this.store.get(item.agentId) ?? null;
377
+ const d = normalizeBrief(await this.judge.ask(`advise:${item.key}:${item.hash}`, agent, prompt, (x) => Array.isArray(x.options)), item, standing);
378
+ const still = this.waiting().find((i) => i.key === item.key);
379
+ if (!still || still.hash !== item.hash) return;
380
+ const base = { key: item.key, kind: item.kind, agentId: item.agentId, agentName: item.agentName, project: item.project, projectKey: item.projectKey, title: clip(item.title, 300), qid: item.qid ?? null, hash: item.hash, at: this.iso(), status: 'open' };
381
+ // No judge (off, over budget, or no usable reply): the card says so instead of guessing.
382
+ this.state.briefs[item.key] = d ? { ...base, ...d } : { ...base, options: [], recommend: null, why: '', evidence: [], risk: '', undo: 'easy', confidence: 0, standing: null, none: this.judge.enabled ? 'No recommendation could be written (the AI judge gave no usable answer, or is over its daily budget).' : 'The AI judge is off, so there is no recommendation.' };
383
+ this.save();
384
+ const b = this.state.briefs[item.key];
385
+ if (mayAct(this.levelFor(item.projectKey), b)) await this.apply(item.key, b.recommend, { by: 'auto' }).catch((e) => this.log(`decide: ${e.message}`));
386
+ }
387
+
388
+ /** Ask for the brief again (the judge was off, or you want a second look). */
389
+ refresh(key) {
390
+ const b = this.state.briefs[key];
391
+ if (b) b.status = 'stale';
392
+ this.tick().catch(() => {});
393
+ return this.view();
394
+ }
395
+
396
+ /** Carry out one option of a brief. `by`: 'you' or 'auto'. */
397
+ async apply(key, option, { by = 'you', text = null } = {}) {
398
+ const b = this.state.briefs[key];
399
+ if (!b || b.status !== 'open') throw err(409, 'That is no longer waiting');
400
+ const opt = b.options[option];
401
+ if (!opt) throw err(400, 'No such option');
402
+ const say = clip(text ?? opt.text, 1200);
403
+ const auto = by === 'auto';
404
+ const rule = b.standing ? this.state.standing[b.standing] : null;
405
+ const note = auto ? `${say ? `${say}\n\n` : ''}(Decided for you${rule ? ` by your standing decision "${clip(rule.when, 120)}"` : ' on the recommendation'}: ${b.why})` : say;
406
+ if (opt.action === 'approve') this.manager.approvePlan(b.agentId, note || null);
407
+ else if (opt.action === 'changes') this.manager.requestPlanChanges(b.agentId, note);
408
+ else this.manager.answerQuestion(b.agentId, b.qid, say);
409
+ const followed = option === b.recommend;
410
+ Object.assign(b, { status: auto ? 'auto' : 'applied', chosen: option, decidedAt: this.iso(), by });
411
+ this.remember(b, { chose: opt.action === 'answer' ? say : opt.label, followed, note: opt.action === 'changes' ? say : null, by });
412
+ if (auto) {
413
+ this.state.handled.push({ at: b.decidedAt, key, kind: b.kind, agentId: b.agentId, agentName: b.agentName, project: b.project, projectKey: b.projectKey, title: b.title, did: opt.action === 'answer' ? `Answered: ${clip(say, 200)}` : opt.action === 'approve' ? 'Approved the plan' : `Sent the plan back: ${clip(say, 200)}`, why: b.why, standing: b.standing, standingWhen: rule?.when ?? null, confidence: b.confidence });
414
+ if (this.state.handled.length > 200) this.state.handled.splice(0, this.state.handled.length - 200);
415
+ if (rule) Object.assign(rule, { uses: (rule.uses ?? 0) + 1, lastUsedAt: b.decidedAt });
416
+ this.notify?.(`Decided for you on *${b.project}*: ${clip(b.title, 120)} → ${this.state.handled.at(-1).did}`, `Decided for you on ${b.project}: ${clip(b.title, 120)}: ${this.state.handled.at(-1).did}`)?.catch?.(() => {});
417
+ }
418
+ this.log2decisions(b, { by, followed });
419
+ this.save();
420
+ return this.view();
421
+ }
422
+
423
+ /** A brief whose item was decided another way: what was chosen, and whether it matched. */
424
+ settle(b) {
425
+ const a = this.store.get(b.agentId);
426
+ let chose = null;
427
+ let note = null;
428
+ if (a && b.kind === 'plan' && ['approved', 'changes'].includes(a.planReview?.status)) {
429
+ chose = a.planReview.status === 'approved' ? 'Approve' : 'Send back';
430
+ note = a.planReview.note ?? null;
431
+ } else if (a && b.kind === 'question' && a.answers?.[b.qid]) chose = typeof a.answers[b.qid] === 'string' ? a.answers[b.qid] : a.answers[b.qid].text;
432
+ b.status = 'decided';
433
+ b.decidedAt = this.iso();
434
+ if (!chose) return;
435
+ const rec = b.options[b.recommend];
436
+ const followed = rec ? (b.kind === 'plan' ? (rec.action === 'approve') === (chose === 'Approve') : norm(rec.text) === norm(chose) || norm(rec.label) === norm(chose)) : null;
437
+ this.remember(b, { chose, followed, note, by: 'you' });
438
+ this.log2decisions(b, { by: 'you', followed });
439
+ }
440
+
441
+ remember(b, { chose, followed, note, by }) {
442
+ const rec = b.options[b.recommend];
443
+ this.state.history.push({ at: this.iso(), kind: b.kind, project: b.project, projectKey: b.projectKey, title: b.title, recommended: rec ? (rec.action === 'answer' ? rec.text : rec.label) : '', chose, followed, note, by });
444
+ if (this.state.history.length > 300) this.state.history.splice(0, this.state.history.length - 300);
445
+ if (rec && by === 'you') this.judge.feedback('advise', { summary: `${b.kind}: ${b.title}`, verdict: `${rec.label} (${b.confidence})`, outcome: followed ? 'they agreed' : `they chose: ${clip(chose, 80)}` });
446
+ }
447
+
448
+ /** The decision log's entry for it gets the reasoning, who decided, and whether it was the recommendation. */
449
+ log2decisions(b, { by, followed }) {
450
+ try {
451
+ this.decisions.sync();
452
+ const a = this.store.get(b.agentId);
453
+ const id = b.kind === 'plan' ? `plan:${b.agentId}:${a?.planReview?.decidedAt}` : `answer:${b.agentId}:${b.qid}`;
454
+ if (b.options.length) this.decisions.annotate(id, { reason: b.why, by, followed, recommended: b.options[b.recommend]?.label ?? null, confidence: b.confidence, standing: b.standing });
455
+ } catch {}
456
+ }
457
+
458
+ /** Evidence first: the options of a question, each tried by its own agent, compared side by side. */
459
+ race(key) {
460
+ const b = this.state.briefs[key];
461
+ if (!b || b.status !== 'open') throw err(409, 'That is no longer waiting');
462
+ if (b.kind !== 'question' || b.options.length < 2) throw err(400, 'Trying both needs a question with at least two options');
463
+ const a = this.store.get(b.agentId);
464
+ if (!a) throw err(404, 'Its agent is gone');
465
+ const race = this.races.create({
466
+ intent: `${a.intent}\n\nAn open question decides the approach: ${b.title}`,
467
+ variants: b.options.map((o) => ({ label: o.label, instructions: o.text })),
468
+ name: `${a.name}-try`,
469
+ ...(a.repo ? { repo: a.repo, base: a.base ?? undefined } : { dir: a.requestedDir ?? a.workdir }),
470
+ });
471
+ b.raceId = race.id;
472
+ this.save();
473
+ return { race: race.id, view: this.view() };
474
+ }
475
+
476
+ // ------------------------------------------------------------ standing decisions
477
+
478
+ addStanding({ kind, project = null, when, action, text = '' } = {}, { source = 'you' } = {}) {
479
+ if (!['plan', 'question'].includes(kind)) throw err(400, 'kind must be plan or question');
480
+ const acts = kind === 'plan' ? ['approve', 'changes'] : ['answer'];
481
+ if (!acts.includes(action)) throw err(400, `For a ${kind}, the action is ${acts.join(' or ')}`);
482
+ const w = clip(when, 400);
483
+ const t = clip(text, 1200);
484
+ if (w.length < 8) throw err(400, 'Say when it applies');
485
+ if (action !== 'approve' && !t) throw err(400, action === 'answer' ? 'Say what to answer' : 'Say what to send back');
486
+ const key = project ? this.projects().find((p) => p.key === project || p.shortcut === project || p.name === project)?.key ?? null : null;
487
+ if (project && !key) throw err(400, 'No such project');
488
+ const id = `s${crypto.randomBytes(3).toString('hex')}`;
489
+ this.state.standing[id] = { id, kind, project: key, when: w, action, text: t, source, on: true, uses: 0, createdAt: this.iso(), lastUsedAt: null };
490
+ this.save();
491
+ this.tick().catch(() => {});
492
+ return this.state.standing[id];
493
+ }
494
+
495
+ updateStanding(id, { on } = {}) {
496
+ const r = this.state.standing[id];
497
+ if (!r) throw err(404, 'No such standing decision');
498
+ if (typeof on === 'boolean') r.on = on;
499
+ this.save();
500
+ return r;
501
+ }
502
+
503
+ removeStanding(id) {
504
+ if (!this.state.standing[id]) throw err(404, 'No such standing decision');
505
+ delete this.state.standing[id];
506
+ for (const b of Object.values(this.state.briefs)) if (b.standing === id) b.standing = null;
507
+ this.save();
508
+ return { ok: true };
509
+ }
510
+
511
+ acceptOffer(id) {
512
+ const o = this.state.offers[id];
513
+ if (!o) throw err(404, 'No such offer');
514
+ delete this.state.offers[id];
515
+ this.state.dismissed[id] = this.iso();
516
+ return this.addStanding(o, { source: 'offered' });
517
+ }
518
+
519
+ dismissOffer(id) {
520
+ if (!this.state.offers[id]) throw err(404, 'No such offer');
521
+ delete this.state.offers[id];
522
+ this.state.dismissed[id] = this.iso();
523
+ this.save();
524
+ return { ok: true };
525
+ }
526
+
527
+ /** Three more decisions of your own since the last look: is there a call you keep making? */
528
+ async learn({ force = false } = {}) {
529
+ const st = this.state;
530
+ const mine = st.history.filter((h) => h.by === 'you');
531
+ if (!force && mine.length - (st.learnedAt ?? 0) < OFFER_AFTER) return [];
532
+ if (this.learning) return [];
533
+ this.learning = true;
534
+ try {
535
+ st.learnedAt = mine.length;
536
+ const recent = mine.slice(-40);
537
+ const rules = Object.values(st.standing);
538
+ const d = await this.judge.ask(`standing:${hash(JSON.stringify(recent.map((h) => [h.title, h.chose])))}`, null, standingPrompt(recent, rules), (x) => Array.isArray(x.offers));
539
+ const found = d
540
+ ? d.offers.filter((o) => Array.isArray(o.basedOn) && new Set(o.basedOn).size >= OFFER_AFTER && (Number(o.confidence) || 0) >= 0.6).map((o) => ({ ...o, count: new Set(o.basedOn).size, project: this.projects().find((p) => p.name === o.project || p.shortcut === o.project)?.key ?? null }))
541
+ : standingFallback(recent).map((o) => ({ ...o, project: this.projects().find((p) => p.name === o.project)?.key ?? null }));
542
+ const added = [];
543
+ for (const o of found) {
544
+ if (!['plan', 'question'].includes(o.kind) || !(o.kind === 'plan' ? ['approve', 'changes'] : ['answer']).includes(o.action)) continue;
545
+ if (o.action !== 'approve' && !clip(o.text, 10)) continue;
546
+ const id = `o${hash(`${o.kind}|${o.project}|${norm(o.when)}`)}`;
547
+ if (st.offers[id] || st.dismissed[id] || rules.some((r) => norm(r.when) === norm(o.when))) continue;
548
+ st.offers[id] = { id, kind: o.kind, project: o.project, when: clip(o.when, 400), action: o.action, text: clip(o.text, 1200), count: o.count, confidence: Number(o.confidence) || 0, at: this.iso(), by: d ? 'judge' : 'rule' };
549
+ added.push(st.offers[id]);
550
+ }
551
+ this.save();
552
+ return added;
553
+ } finally {
554
+ this.learning = false;
555
+ }
556
+ }
557
+
558
+ // ------------------------------------------------------------ impact
559
+
560
+ openItems(projectKey) {
561
+ return this.backlog.items().filter((it) => it.projectKey === projectKey && ['queued', 'active', 'review', 'blocked'].includes(it.status));
562
+ }
563
+
564
+ /** A project's open backlog, most valuable first, each with why. The judge's ranking when it has one for these very items. */
565
+ impact(projectKey, { ask = true } = {}) {
566
+ const items = this.openItems(projectKey);
567
+ const { p, next, words } = this.datesFor(projectKey);
568
+ const scored = items.map((it) => ({ it, ...impactScore(it, { stage: next, now: this.now() }) }));
569
+ const h = hash(JSON.stringify(items.map((it) => [it.id, it.title, it.priority, it.status])) + words);
570
+ const ai = this.state.impact[projectKey];
571
+ const byId = new Map(scored.map((s) => [s.it.id, s]));
572
+ let rows;
573
+ let by = 'rules';
574
+ if (ai?.hash === h && ai.order?.length) {
575
+ by = 'judge';
576
+ const seen = new Set();
577
+ rows = ai.order.filter((o) => byId.has(o.id) && !seen.has(o.id) && seen.add(o.id)).map((o) => ({ ...byId.get(o.id), why: o.why, level: o.impact, unblocks: o.unblocks ?? [], suggest: Number.isInteger(o.priority) && o.priority !== byId.get(o.id).it.priority ? o.priority : null }));
578
+ rows.push(...scored.filter((s) => !seen.has(s.it.id)).sort((a, b) => b.score - a.score));
579
+ } else {
580
+ rows = scored.sort((a, b) => b.score - a.score);
581
+ if (ask && items.length >= 2 && !this.pending.has(`impact:${projectKey}`)) {
582
+ this.pending.add(`impact:${projectKey}`);
583
+ const recent = Object.values(this.decisions.state.items).filter((d) => d.project.key === projectKey).sort((a, b) => String(b.at).localeCompare(String(a.at))).slice(0, 5).map((d) => `${d.title}: ${d.decision}`);
584
+ this.judge
585
+ .ask(`impact:${projectKey}:${h}`, null, impactPrompt(items, { project: p?.name ?? projectKey, dates: words, bugs: this.bugs(projectKey), decisions: recent }), (d) => Array.isArray(d.order))
586
+ .then((d) => {
587
+ if (!d) return;
588
+ this.state.impact[projectKey] = { hash: h, at: this.iso(), confidence: d.confidence, order: d.order.filter((o) => o && typeof o.id === 'string').map((o) => ({ id: o.id, impact: ['high', 'medium', 'low'].includes(o.impact) ? o.impact : 'medium', why: clip(o.why, 240), unblocks: (Array.isArray(o.unblocks) ? o.unblocks : []).filter((x) => typeof x === 'string').slice(0, 6), priority: [0, 1, 2, 3].includes(o.priority) ? o.priority : undefined })) };
589
+ this.save();
590
+ })
591
+ .finally(() => this.pending.delete(`impact:${projectKey}`));
592
+ }
593
+ }
594
+ const now = this.backlog.items().filter((it) => it.projectKey === projectKey).map((it) => it.id);
595
+ const queuedNow = now.filter((id) => byId.get(id)?.it.status === 'queued');
596
+ const queuedWant = rows.filter((r) => r.it.status === 'queued').map((r) => r.it.id);
597
+ return {
598
+ project: { key: projectKey, name: p?.name ?? items[0]?.projectName ?? projectKey },
599
+ by,
600
+ thinking: this.pending.has(`impact:${projectKey}`),
601
+ confidence: by === 'judge' ? ai.confidence : null,
602
+ inOrder: queuedNow.join() === queuedWant.join() && !rows.some((r) => r.suggest != null),
603
+ items: rows.map((r, i) => ({ id: r.it.id, title: r.it.title, status: r.it.status, priority: r.it.priority, heldUntil: r.it.heldUntil ?? null, rank: i + 1, score: r.score, level: r.level ?? (r.score >= 55 ? 'high' : r.score >= 30 ? 'medium' : 'low'), why: r.why ?? r.reasons.join(' · '), unblocks: r.unblocks ?? [], suggest: r.suggest ?? null })),
604
+ };
605
+ }
606
+
607
+ /** Put the queue in the order of its impact (and the priorities the judge found wrong). */
608
+ applyImpact(projectKey) {
609
+ const v = this.impact(projectKey, { ask: false });
610
+ for (const r of v.items) if (r.suggest != null && r.status === 'queued') this.backlog.update(r.id, { priority: r.suggest });
611
+ this.backlog.reorder(v.items.filter((r) => r.status === 'queued').map((r) => r.id));
612
+ this.backlog.dispatch().catch(() => {});
613
+ this.save();
614
+ return this.impact(projectKey, { ask: false });
615
+ }
616
+
617
+ // ------------------------------------------------------------ trade-offs
618
+
619
+ /** Every date at risk or late, as choices. */
620
+ tradeoffs({ ask = true } = {}) {
621
+ const out = [];
622
+ for (const p of this.manager.listProjects()) {
623
+ for (const stage of this.milestones.stages(p)) {
624
+ if (!['at-risk', 'late'].includes(stage.status)) continue;
625
+ const ranked = this.impact(p.key, { ask: false }).items;
626
+ if (!ranked.length) continue;
627
+ const all = this.backlog.items().filter((it) => it.projectKey === p.key);
628
+ const t = tradeoffOptions({ stage, ranked, perDay: pace(all, { now: this.now() }), limit: this.backlog.limitFor(p.key) });
629
+ const h = hash(JSON.stringify([stage.id, stage.date, stage.daysLeft, ranked.map((r) => r.id), t.options.map((o) => o.id)]));
630
+ const key = `${p.key}:${stage.id}`;
631
+ const ai = this.state.tradeoffs[key];
632
+ const row = { key, project: { key: p.key, name: p.name }, stage: { id: stage.id, label: stage.label, date: stage.date, words: stage.words, status: stage.status }, ...t, by: 'rules', confidence: null };
633
+ if (ai?.hash === h && t.options.some((o) => o.id === ai.recommend)) Object.assign(row, { recommend: ai.recommend, why: ai.why, confidence: ai.confidence, by: 'judge' });
634
+ else if (ask && !this.pending.has(`tradeoff:${key}`)) {
635
+ this.pending.add(`tradeoff:${key}`);
636
+ const f = stage.checklist.filter((i) => i.auto && !i.ok).map((i) => i.text).join('; ');
637
+ this.judge
638
+ .ask(`tradeoff:${key}:${h}`, null, tradeoffPrompt({ project: p.name, stage, facts: f ? `Also open: ${f}.` : '', t }), (d) => typeof d.recommend === 'string')
639
+ .then((d) => {
640
+ if (!d) return;
641
+ this.state.tradeoffs[key] = { hash: h, at: this.iso(), recommend: d.recommend, why: clip(d.why, 400), confidence: d.confidence };
642
+ this.save();
643
+ })
644
+ .finally(() => this.pending.delete(`tradeoff:${key}`));
645
+ }
646
+ out.push(row);
647
+ }
648
+ }
649
+ return out;
650
+ }
651
+
652
+ /** Carry out one choice for a date at risk, and log it as a decision. */
653
+ applyTradeoff(key, option) {
654
+ const t = this.tradeoffs({ ask: false }).find((x) => x.key === key);
655
+ if (!t) throw err(409, 'That date is no longer at risk');
656
+ const o = t.options.find((x) => x.id === option);
657
+ if (!o) throw err(400, 'No such choice');
658
+ if (o.id === 'cut') for (const it of o.items) this.backlog.update(it.id, { heldUntil: addDays(t.stage.date, 1), notes: `${this.backlog.get(it.id).notes ? `${this.backlog.get(it.id).notes}\n` : ''}Held until after ${t.stage.label} (${t.stage.date}).` });
659
+ else if (o.id === 'move') {
660
+ const p = this.manager.listProjects().find((x) => x.key === t.project.key);
661
+ const stages = this.milestones.stages(p);
662
+ const dates = {};
663
+ let from = false;
664
+ for (const s of stages) {
665
+ if (s.id === t.stage.id) from = true;
666
+ if (from && !s.reached) dates[s.id] = addDays(s.date, o.days);
667
+ }
668
+ this.milestones.set(t.project.key, dates);
669
+ } else if (o.id === 'add') this.backlog.settings({ project: t.project.key, limit: o.limit });
670
+ const followed = option === t.recommend;
671
+ this.decisions.record({ kind: 'tradeoff', project: t.project, title: `${t.stage.label} (${t.stage.date}) at risk: ${o.label.toLowerCase()}`, decision: o.what, why: followed ? t.why : `${o.consequence} (The recommendation was to ${t.options.find((x) => x.id === t.recommend)?.label.toLowerCase() ?? t.recommend}.)` });
672
+ this.state.history.push({ at: this.iso(), kind: 'tradeoff', project: t.project.name, projectKey: t.project.key, title: `${t.stage.label} at risk`, recommended: t.recommend, chose: o.id, followed, note: null, by: 'you' });
673
+ delete this.state.tradeoffs[key];
674
+ this.save();
675
+ return this.view();
676
+ }
677
+
678
+ // ------------------------------------------------------------ looking back
679
+
680
+ /** What followed each decision; the ones worth another look get a lesson from the judge. */
681
+ async lookBack({ force = false } = {}) {
682
+ if (!this.enabled() && !force) return this.lookBackView();
683
+ const st = this.state;
684
+ this.decisions.sync();
685
+ const lateBy = new Map();
686
+ const rows = [];
687
+ for (const d of Object.values(this.decisions.state.items)) {
688
+ if (d.superseded || !d.agentId || !['plan', 'answer', 'design'].includes(d.kind)) continue;
689
+ if (this.now() - Date.parse(d.at) < 2 * DAY && !force) continue;
690
+ const a = this.store.get(d.agentId) ?? null;
691
+ if (!lateBy.has(d.project.key)) {
692
+ const p = this.manager.listProjects().find((x) => x.key === d.project.key);
693
+ lateBy.set(d.project.key, p ? this.milestones.stages(p).some((s) => s.status === 'late' && s.date > String(d.at).slice(0, 10)) : false);
694
+ }
695
+ const item = a ? this.backlog.items().find((it) => it.agentId === a.id) ?? null : null;
696
+ const r = lookBackSigns(d, a, { stageLate: lateBy.get(d.project.key), item });
697
+ const prev = st.reviews[d.id];
698
+ const sig = r.signs.join('|');
699
+ if (prev?.sig === sig && prev.outcome === r.outcome) continue;
700
+ st.reviews[d.id] = { id: d.id, at: this.iso(), outcome: r.outcome, signs: r.signs, sig, lesson: prev?.sig === sig ? prev.lesson : null };
701
+ if (r.outcome === 'revisit') rows.push({ id: d.id, kind: d.kind, project: d.project.name, title: d.title, decision: d.decision, why: d.why ?? d.reason ?? null, signs: r.signs });
702
+ else this.decisions.annotate(d.id, { outcome: r.outcome });
703
+ }
704
+ for (const id of Object.keys(st.reviews)) if (!this.decisions.state.items[id]) delete st.reviews[id];
705
+ if (rows.length) {
706
+ const batch = rows.slice(0, 8);
707
+ const d = await this.judge.ask(`lookback:${hash(JSON.stringify(batch.map((r) => [r.id, r.signs])))}`, null, lookBackPrompt(batch), (x) => Array.isArray(x.items));
708
+ for (const r of batch) {
709
+ const v = d?.items.find((x) => x.id === r.id);
710
+ const rev = st.reviews[r.id];
711
+ // The judge may clear the decision: what followed had another cause.
712
+ if (v?.verdict === 'held') rev.outcome = 'held';
713
+ rev.lesson = v?.lesson ? clip(v.lesson, 300) : null;
714
+ rev.by = v ? 'judge' : 'rules';
715
+ this.decisions.annotate(r.id, { outcome: rev.outcome, lesson: rev.lesson });
716
+ if (rev.outcome === 'revisit' && rev.lesson && !st.lessons.includes(rev.lesson)) st.lessons.push(rev.lesson);
717
+ }
718
+ if (st.lessons.length > 12) st.lessons.splice(0, st.lessons.length - 12);
719
+ }
720
+ st.lookedAt = this.iso();
721
+ this.save();
722
+ return this.lookBackView();
723
+ }
724
+
725
+ lookBackView() {
726
+ const items = this.decisions.state.items;
727
+ const rows = Object.values(this.state.reviews)
728
+ .filter((r) => items[r.id])
729
+ .map((r) => ({ ...r, sig: undefined, kind: items[r.id].kind, title: items[r.id].title, decision: items[r.id].decision, project: items[r.id].project, decidedAt: items[r.id].at, agentId: this.store.get(items[r.id].agentId) ? items[r.id].agentId : null, agentName: items[r.id].agentName }));
730
+ const order = { revisit: 0, held: 1, early: 2 };
731
+ rows.sort((a, b) => order[a.outcome] - order[b.outcome] || String(b.decidedAt).localeCompare(String(a.decidedAt)));
732
+ return { items: rows, revisit: rows.filter((r) => r.outcome === 'revisit').length, held: rows.filter((r) => r.outcome === 'held').length, lessons: this.state.lessons, lookedAt: this.state.lookedAt ?? null };
733
+ }
734
+
735
+ // ------------------------------------------------------------ the view
736
+ /** The projects there is something to decide for: the ones with a shortcut, and any other an agent works in. */
737
+ projects() {
738
+ const out = new Map(this.manager.listProjects().map((p) => [p.key, { key: p.key, name: p.name, shortcut: p.shortcut }]));
739
+ for (const a of this.store.list()) {
740
+ const p = this.projectOf(a);
741
+ if (p && !['general', 'assistant'].includes(p.key) && !a.hunting && !a.reviewing && !out.has(p.key)) out.set(p.key, { key: p.key, name: p.name, shortcut: p.shortcut ?? null });
742
+ }
743
+ return [...out.values()].sort((x, y) => x.name.localeCompare(y.name));
744
+ }
745
+
746
+
747
+ seen() {
748
+ this.state.seenAt = this.iso();
749
+ this.save();
750
+ return { ok: true };
751
+ }
752
+
753
+ /** `think`: also ask the judge for the rankings and trade-off advice that are missing (the Decide window does; a glance from the inbox doesn't). */
754
+ view({ think = false } = {}) {
755
+ const st = this.state;
756
+ const live = new Set(this.waiting().map((i) => i.key));
757
+ const projects = this.manager.listProjects();
758
+ const everywhere = this.projects();
759
+ const name = (key) => everywhere.find((p) => p.key === key)?.name ?? null;
760
+ const mine = st.history.filter((h) => h.by === 'you' && h.followed !== null && h.recommended);
761
+ const briefs = Object.values(st.briefs).filter((b) => b.status === 'open' && live.has(b.key)).sort((a, b) => String(a.at).localeCompare(String(b.at)));
762
+ const withWork = projects.filter((p) => this.openItems(p.key).length);
763
+ return {
764
+ enabled: this.enabled(),
765
+ judge: { enabled: this.judge.enabled, ...this.judge.usage() },
766
+ levels: LEVELS.map((id) => ({ id, label: LEVEL_LABEL[id] })),
767
+ briefs: briefs.map((b) => ({ ...b, level: this.levelFor(b.projectKey), canRace: b.kind === 'question' && b.options.length >= 2 && !b.raceId })),
768
+ writing: [...this.pending].filter((k) => k.startsWith('plan:') || k.startsWith('q:')).length,
769
+ handled: [...st.handled].reverse().slice(0, 50).map((h) => ({ ...h, isNew: !st.seenAt || h.at > st.seenAt, agentGone: !this.store.get(h.agentId) })),
770
+ newHandled: st.handled.filter((h) => !st.seenAt || h.at > st.seenAt).length,
771
+ standing: Object.values(st.standing).sort((a, b) => String(b.createdAt).localeCompare(String(a.createdAt))).map((r) => ({ ...r, projectName: r.project ? name(r.project) : null })),
772
+ offers: Object.values(st.offers).map((o) => ({ ...o, projectName: o.project ? name(o.project) : null })),
773
+ autonomy: everywhere.map((p) => ({ ...p, level: this.levelFor(p.key) })),
774
+ agreement: mine.length ? { decided: mine.length, followed: mine.filter((h) => h.followed).length } : null,
775
+ impact: withWork.map((p) => this.impact(p.key, { ask: think })),
776
+ tradeoffs: this.tradeoffs({ ask: think }),
777
+ lookback: this.lookBackView(),
778
+ };
779
+ }
780
+ }