ai-agentmanager 1.46.0 → 1.47.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
@@ -731,6 +731,98 @@ export async function main(argv) {
731
731
  for (const x of r.failed) console.log(`${red('!')} ${bold(x.key)}: ${x.reason}`);
732
732
  });
733
733
 
734
+ program
735
+ .command('dates')
736
+ .description("A project's commitment dates (code complete, RC, GA): how far each is, what is still open, and the reminders. With dates: set them")
737
+ .argument('[project]', 'a project shortcut or name (default: every project with dates)')
738
+ .option('--cc <date>', 'code complete, as YYYY-MM-DD ("none" clears it)')
739
+ .option('--rc <date>', 'release candidate')
740
+ .option('--ga <date>', 'GA')
741
+ .option('--reached <stage>', 'mark a date as met: cc, rc or ga')
742
+ .option('--json', 'print JSON')
743
+ .action(async (ref, opts) => {
744
+ await daemon();
745
+ const stage = { cc: 'codeComplete', rc: 'rc', ga: 'ga' };
746
+ const date = (v) => (v === undefined ? undefined : /^(none|clear|-)$/i.test(v) ? null : v);
747
+ const set = Object.fromEntries(Object.entries({ codeComplete: date(opts.cc), rc: date(opts.rc), ga: date(opts.ga) }).filter(([, v]) => v !== undefined));
748
+ if ((Object.keys(set).length || opts.reached) && !ref) throw new Error('Name the project: agentmgr dates <project> --cc 2026-12-01');
749
+ if (Object.keys(set).length) await api('PUT', `/milestones/${encodeURIComponent(ref)}`, set);
750
+ if (opts.reached) {
751
+ if (!stage[opts.reached]) throw new Error('--reached takes cc, rc or ga');
752
+ await api('POST', `/milestones/${encodeURIComponent(ref)}/reach`, { stage: stage[opts.reached] });
753
+ }
754
+ const v = await api('GET', '/milestones');
755
+ const r = String(ref ?? '').replace(/^@/, '').toLowerCase();
756
+ const list = v.projects.filter((p) => !r || p.shortcut === r || p.name.toLowerCase() === r);
757
+ if (opts.json) return console.log(JSON.stringify(list, null, 2));
758
+ if (!list.length) return console.log(dim(ref ? `No dates for ${ref}. Set them: agentmgr dates ${ref} --cc 2026-12-01 --rc 2026-12-10 --ga 2026-12-20` : 'No dates yet. Set them: agentmgr dates <project> --cc 2026-12-01 --rc 2026-12-10 --ga 2026-12-20'));
759
+ const color = { late: red, 'at-risk': yellow, 'on-track': green, reached: dim };
760
+ for (const p of list) {
761
+ console.log(`\n${bold(p.name)} ${dim(`@${p.shortcut}`)}`);
762
+ for (const s of p.stages) {
763
+ console.log(` ${s.label.padEnd(18)} ${s.date} ${color[s.status](s.status.replace('-', ' ').padEnd(8))} ${s.words}`);
764
+ for (const i of s.checklist) if (i.auto ? !i.ok : !i.done) console.log(dim(` ${i.auto ? '•' : '☐'} ${i.text}`));
765
+ }
766
+ }
767
+ });
768
+
769
+ program
770
+ .command('decisions')
771
+ .description('The decision log: what was decided on each project and why (from plan reviews, your answers and design docs)')
772
+ .argument('[project]', 'only this project')
773
+ .option('--md', 'print it as Markdown')
774
+ .option('--add <title>', 'add one of your own (with --decision, and --why)')
775
+ .option('--decision <text>')
776
+ .option('--why <text>')
777
+ .option('--json', 'print JSON')
778
+ .action(async (ref, opts) => {
779
+ await daemon();
780
+ if (opts.add) {
781
+ if (!ref || !opts.decision) throw new Error('agentmgr decisions <project> --add "<the question>" --decision "<what was decided>" [--why "<why>"]');
782
+ await api('POST', '/decisions', { project: ref, title: opts.add, decision: opts.decision, why: opts.why });
783
+ return console.log(`${green('✓')} added to the decision log`);
784
+ }
785
+ const all = await api('GET', '/decisions');
786
+ const r = String(ref ?? '').replace(/^@/, '').toLowerCase();
787
+ const key = ref ? all.projects.find((p) => p.name.toLowerCase() === r)?.key ?? (await api('GET', '/projects')).find((p) => p.shortcut === r)?.key : null;
788
+ if (ref && !key) return console.log(dim(`No decisions recorded for ${ref}.`));
789
+ if (opts.md) return console.log(await (await fetch(`${BASE}/api/decisions?format=markdown&project=${encodeURIComponent(key ?? '')}`)).text());
790
+ const items = all.items.filter((i) => !key || i.project.key === key);
791
+ if (opts.json) return console.log(JSON.stringify(items, null, 2));
792
+ if (!items.length) return console.log(dim('No decisions recorded yet.'));
793
+ for (const i of items) {
794
+ console.log(`${bold(i.title)}${i.superseded ? dim(' (replaced since)') : ''}`);
795
+ console.log(` ${i.decision}${i.why ? dim(` because: ${i.why}`) : ''}`);
796
+ console.log(dim(` ${i.project.name} · ${i.kindLabel}${i.agentName ? ` · ${i.agentName}` : ''} · ${String(i.at).slice(0, 10)}`));
797
+ }
798
+ });
799
+
800
+ program
801
+ .command('debt')
802
+ .description("The tech debt radar: a project's files that change often and are hard to read, from git and the files (no model call)")
803
+ .argument('[project]', 'only this project')
804
+ .option('-s, --scan', 'scan the repository again now')
805
+ .option('--json', 'print JSON')
806
+ .action(async (ref, opts) => {
807
+ await daemon();
808
+ if (opts.scan && !ref) throw new Error('Name the project to scan: agentmgr debt <project> --scan');
809
+ let v = opts.scan ? await api('POST', `/debt/${encodeURIComponent(ref)}/scan`, {}) : await api('GET', '/debt');
810
+ const r = String(ref ?? '').replace(/^@/, '').toLowerCase();
811
+ const mine = () => v.projects.filter((p) => !r || p.shortcut === r || p.name.toLowerCase() === r);
812
+ for (let i = 0; opts.scan && mine().some((p) => p.scanning) && i < 300; i++) {
813
+ await new Promise((res) => setTimeout(res, 1000));
814
+ v = await api('GET', '/debt');
815
+ }
816
+ if (opts.json) return console.log(JSON.stringify(mine(), null, 2));
817
+ const list = mine().filter((p) => ref || p.at);
818
+ if (!list.length) return console.log(dim('Nothing scanned yet. Scan a project: agentmgr debt <project> --scan'));
819
+ for (const p of list) {
820
+ console.log(`\n${bold(p.name)} ${dim(`@${p.shortcut} ${p.error ? `couldn't scan: ${p.error}` : p.at ? `${p.commits} commits in ${p.days} days` : p.hasRepo ? 'not scanned yet (--scan)' : 'no local repository yet'}`)}`);
821
+ for (const h of p.spots) console.log(` ${String(h.score).padStart(3)} ${h.file}\n ${dim(h.reasons.join(' · '))}`);
822
+ if (p.at && !p.error && !p.spots.length) console.log(dim(' No hot spots.'));
823
+ }
824
+ });
825
+
734
826
  program
735
827
  .command('news')
736
828
  .description("AI News: the frontier labs' latest releases, each summarized, with links")
package/src/config.js CHANGED
@@ -72,6 +72,10 @@ const DEFAULTS = {
72
72
  // and micro benchmarks of the code it changed, before and after. Per agent: demoPage, benchmarks.
73
73
  // Each morning (weekdays), a spoken standup of the agents' news; see standup.js.
74
74
  standup: { enabled: true, at: '09:00', weekends: false, ai: true, notify: true },
75
+ // Plan: the tech debt radar (see DEBT_DEFAULTS in debt.js) and the calendar Today is planned around
76
+ // (its private iCal addresses and the working day; see CALENDAR_DEFAULTS in calendar.js).
77
+ debt: { enabled: true },
78
+ calendar: { ics: [], workStart: '09:00', workEnd: '18:00' },
75
79
  // AI News: the frontier labs' latest releases, summarized; see NEWS_DEFAULTS in news.js for every field.
76
80
  news: { enabled: true },
77
81
  demoPage: false,
package/src/debt.js ADDED
@@ -0,0 +1,276 @@
1
+ // Tech debt radar: where a project's code costs the most to change. For each source file it
2
+ // weighs how often it changed lately (git history), how many of those changes were fixes, and
3
+ // how tangled it is (size, branching, deep nesting, TODO/FIXME notes), plus the open bugs the bug
4
+ // hunts found there. Files that are both changed a lot and hard to read come first: that is where
5
+ // paying debt down pays back. Each hot spot says why it is one, and can be handed to an agent
6
+ // through the backlog. All from git and the files themselves: no model is called, nothing is sent.
7
+
8
+ import { spawn } from 'node:child_process';
9
+ import fs from 'node:fs';
10
+ import { run } from './git.js';
11
+
12
+ export const DEBT_DEFAULTS = { enabled: true, days: 90, autoDays: 7, top: 30 };
13
+ const MAX_FILES = 300; // read at most this many (the most changed)
14
+ const MAX_BYTES = 400_000;
15
+ const CODE = /\.(js|jsx|mjs|cjs|ts|tsx|py|go|rs|java|kt|kts|rb|php|cs|c|h|cc|cpp|hpp|swift|scala|m|mm|sh|sql|vue|svelte|lua|dart|ex|exs|clj|pl)$/i;
16
+ const SKIP = /(^|\/)(node_modules|vendor|third_party|dist|build|out|target|coverage|\.git|__generated__|generated|migrations|fixtures|testdata|snapshots|__snapshots__)\/|\.min\.|\.generated\.|\.pb\.|_pb2?\.|\.lock$|-lock\./i;
17
+ // Tests change with every feature: that churn says less about debt.
18
+ const TEST = /(^|\/)(tests?|__tests__|specs?|e2e)\/|[._-](test|spec)\./i;
19
+ const FIX = /\b(fix(es|ed)?|bug|hotfix|revert|regression|crash|broken|patch)\b/i;
20
+
21
+ const err = (status, message) => Object.assign(new Error(message), { status });
22
+ const plural = (n, one, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
23
+
24
+ /** `git log --name-only --format=%x01%s`: [{ subject, files }]. */
25
+ export function parseLog(text) {
26
+ return String(text ?? '')
27
+ .split('\x01')
28
+ .slice(1)
29
+ .map((c) => {
30
+ const [subject, ...files] = c.split('\n');
31
+ return { subject: subject.trim(), files: files.map((f) => f.trim()).filter(Boolean) };
32
+ });
33
+ }
34
+
35
+ /** `git ls-tree -r -l`: Map of path -> size, blobs only. */
36
+ export function parseTree(text) {
37
+ const out = new Map();
38
+ for (const line of String(text ?? '').split('\n')) {
39
+ const m = line.match(/^\d+ blob [0-9a-f]+\s+(\d+)\t(.+)$/);
40
+ if (m) out.set(m[2], Number(m[1]));
41
+ }
42
+ return out;
43
+ }
44
+
45
+ /** How tangled a file is: its lines, branch points, lines nested 5 levels or deeper, and TODO-like notes. */
46
+ export function metricsOf(source) {
47
+ const lines = String(source ?? '').split('\n');
48
+ let code = 0;
49
+ let branches = 0;
50
+ let deep = 0;
51
+ let todos = 0;
52
+ // The indent step: the smallest indent in use (2, 4, 8 spaces or a tab).
53
+ const widths = lines.map((l) => l.match(/^[ \t]*/)[0].replace(/\t/g, ' ').length).filter((w) => w > 0);
54
+ const step = Math.max(2, Math.min(8, widths.length ? Math.min(...widths) : 4));
55
+ for (const l of lines) {
56
+ const t = l.trim();
57
+ if (!t) continue;
58
+ code++;
59
+ if (/\b(TODO|FIXME|HACK|XXX)\b/.test(t)) todos++;
60
+ branches += (t.match(/\b(if|else if|elif|for|while|case|catch|except|when|unless)\b|&&|\|\||\?(?=[^.:?])/g) ?? []).length;
61
+ if (l.match(/^[ \t]*/)[0].replace(/\t/g, ' ').length / step >= 5) deep++;
62
+ }
63
+ return { lines: code, branches, deep, todos };
64
+ }
65
+
66
+ /**
67
+ * The hot spots: [{ file, score (0-100), churn, fixes, lines, branches, deep, todos, bugs, reasons }],
68
+ * worst first. `files`: Map of path -> metrics; `commits` from parseLog; `bugs`: paths with open bugs.
69
+ */
70
+ export function hotSpots({ commits = [], files = new Map(), bugs = [], days = 90, top = 30 } = {}) {
71
+ const churn = new Map();
72
+ const fixes = new Map();
73
+ for (const c of commits) {
74
+ // A sweeping commit (a rename, a formatter) says little about any one file.
75
+ if (c.files.length > 40) continue;
76
+ for (const f of c.files) {
77
+ churn.set(f, (churn.get(f) ?? 0) + 1);
78
+ if (FIX.test(c.subject)) fixes.set(f, (fixes.get(f) ?? 0) + 1);
79
+ }
80
+ }
81
+ const bugCount = new Map();
82
+ for (const f of bugs) if (f) bugCount.set(f, (bugCount.get(f) ?? 0) + 1);
83
+ const rows = [...files].map(([file, m]) => ({ file, ...m, churn: churn.get(file) ?? 0, fixes: fixes.get(file) ?? 0, bugs: bugCount.get(file) ?? 0 }));
84
+ const maxChurn = Math.max(1, ...rows.map((r) => r.churn));
85
+ const tangle = (r) => r.branches + r.deep * 2 + r.lines / 20;
86
+ const maxTangle = Math.max(1, ...rows.map(tangle));
87
+ for (const r of rows) {
88
+ const c = r.churn / maxChurn;
89
+ const t = Math.log1p(tangle(r)) / Math.log1p(maxTangle);
90
+ const fixShare = r.churn ? r.fixes / r.churn : 0;
91
+ r.score = Math.min(100, Math.round(100 * Math.sqrt(c * t) * (0.75 + 0.5 * fixShare) * (TEST.test(r.file) ? 0.6 : 1)) + Math.min(8, r.todos) + Math.min(12, r.bugs * 6));
92
+ r.reasons = [
93
+ r.churn >= 3 && `changed ${plural(r.churn, 'time')} in ${days} days`,
94
+ r.fixes >= 2 && `${r.fixes} of them fixes`,
95
+ r.lines >= 400 && `${r.lines.toLocaleString('en-US')} lines`,
96
+ r.deep >= 15 && `${r.deep} lines nested 5 deep or more`,
97
+ r.branches >= 80 && `${r.branches} branch points`,
98
+ r.todos >= 3 && `${r.todos} TODO/FIXME notes`,
99
+ r.bugs && `${plural(r.bugs, 'open bug')} found here`,
100
+ ].filter(Boolean);
101
+ }
102
+ return rows
103
+ .filter((r) => r.score >= 20 && r.reasons.length >= 2)
104
+ .sort((a, b) => b.score - a.score || b.churn - a.churn || a.file.localeCompare(b.file))
105
+ .slice(0, top);
106
+ }
107
+
108
+ /** What an agent is asked when a hot spot is handed over. */
109
+ export const debtTask = (h) =>
110
+ `Pay down tech debt in ${h.file} (${h.reasons.join('; ')}). First find what makes it hard to change: long functions, deep nesting, ` +
111
+ 'mixed responsibilities, duplicated logic, stale TODOs. Cover its current behaviour with tests where they are missing, then refactor in small steps ' +
112
+ 'without changing behaviour, running the tests after each. Keep the pull request small and reviewable; if more is needed, list what is left in the description.';
113
+
114
+ /** The contents of many files at a ref, through one `git cat-file --batch`: Map of path -> text. */
115
+ function readBlobs(dir, ref, paths) {
116
+ return new Promise((resolve, reject) => {
117
+ const child = spawn('git', ['cat-file', '--batch'], { cwd: dir, stdio: ['pipe', 'pipe', 'ignore'] });
118
+ const chunks = [];
119
+ child.stdout.on('data', (d) => chunks.push(d));
120
+ child.on('error', reject);
121
+ child.on('close', () => {
122
+ const buf = Buffer.concat(chunks);
123
+ const out = new Map();
124
+ let at = 0;
125
+ for (const p of paths) {
126
+ const nl = buf.indexOf(10, at);
127
+ if (nl < 0) break;
128
+ const head = buf.toString('utf8', at, nl);
129
+ at = nl + 1;
130
+ const size = Number(head.match(/^[0-9a-f]+ blob (\d+)$/)?.[1]);
131
+ if (!Number.isFinite(size)) continue; // "missing": no content follows
132
+ const body = buf.subarray(at, at + size);
133
+ at += size + 1;
134
+ // Binary files (a NUL in the first bytes) aren't code.
135
+ if (!body.subarray(0, 4000).includes(0)) out.set(p, body.toString('utf8'));
136
+ }
137
+ resolve(out);
138
+ });
139
+ child.stdin.on('error', () => {});
140
+ child.stdin.end(paths.map((p) => `${ref}:${p}\n`).join(''));
141
+ });
142
+ }
143
+
144
+ /** Read a repository's history and files: { commits, files (path -> metrics), scanned }. */
145
+ export async function scanRepo(dir, { days = 90, ref = 'HEAD' } = {}) {
146
+ const [log, tree] = await Promise.all([
147
+ run('git', ['log', `--since=${days}.days.ago`, '--no-merges', '--name-only', '--format=%x01%s', ref], { cwd: dir, timeout: 120_000 }),
148
+ run('git', ['ls-tree', '-r', '-l', ref], { cwd: dir, timeout: 120_000 }),
149
+ ]);
150
+ const commits = parseLog(log);
151
+ const sizes = parseTree(tree);
152
+ const churn = new Map();
153
+ for (const c of commits) for (const f of c.files) churn.set(f, (churn.get(f) ?? 0) + 1);
154
+ const paths = [...sizes]
155
+ .filter(([p, size]) => CODE.test(p) && !SKIP.test(p) && size > 0 && size <= MAX_BYTES && (churn.get(p) ?? 0) >= 2)
156
+ .sort((a, b) => churn.get(b[0]) - churn.get(a[0]))
157
+ .slice(0, MAX_FILES)
158
+ .map(([p]) => p);
159
+ const blobs = paths.length ? await readBlobs(dir, ref, paths) : new Map();
160
+ return { commits, files: new Map([...blobs].map(([p, text]) => [p, metricsOf(text)])), scanned: paths.length };
161
+ }
162
+
163
+ export class Debt {
164
+ /**
165
+ * `projects()` lists the projects; `dirOf(project)` is its local repository (or null);
166
+ * `bugs(project)` the files with open bugs; `queue(project, title)` hands a task to an agent.
167
+ */
168
+ constructor({ store, config = {}, projects, dirOf, bugs = () => [], queue = null, scan = scanRepo, onChange = () => {}, log = (m) => console.log(`[agentmgr] ${m}`), now = () => Date.now(), timer = true }) {
169
+ Object.assign(this, { store, config, projects, dirOf, bugs, queue, scanFn: scan, onChange, log, now });
170
+ this.running = new Map();
171
+ if (timer && this.settings.enabled) {
172
+ this.timer = setInterval(() => this.tick(), 30 * 60_000);
173
+ this.first = setTimeout(() => this.tick(), 3 * 60_000);
174
+ this.timer.unref?.();
175
+ this.first.unref?.();
176
+ }
177
+ }
178
+
179
+ get settings() {
180
+ const s = { ...DEBT_DEFAULTS, ...this.config.debt };
181
+ const num = (v, d, min) => (Number.isFinite(Number(v)) && Number(v) >= min ? Number(v) : d);
182
+ return { enabled: s.enabled !== false, days: num(s.days, 90, 7), autoDays: num(s.autoDays, 7, 0), top: Math.min(100, num(s.top, 30, 5)) };
183
+ }
184
+
185
+ get state() {
186
+ return (this.store.data.debt ??= { projects: {} });
187
+ }
188
+
189
+ close() {
190
+ clearInterval(this.timer);
191
+ clearTimeout(this.first);
192
+ }
193
+
194
+ project(ref) {
195
+ const r = String(ref ?? '').trim().replace(/^@/, '').toLowerCase();
196
+ const p = this.projects().find((x) => x.shortcut === r || x.key === ref || x.name.toLowerCase() === r);
197
+ if (!p) throw err(404, `No project matches "${ref}"`);
198
+ return p;
199
+ }
200
+
201
+ /** Scan a project's repository now (one scan of a project at a time). */
202
+ scan(ref) {
203
+ const p = this.project(ref);
204
+ const dir = this.dirOf(p);
205
+ if (!dir || !fs.existsSync(dir)) return Promise.reject(err(409, `${p.name} has no local repository yet: start an agent in it first`));
206
+ if (!this.running.has(p.key)) {
207
+ const s = this.settings;
208
+ const job = (async () => {
209
+ const rec = (this.state.projects[p.key] ??= { dismissed: {}, queued: {} });
210
+ try {
211
+ const r = await this.scanFn(dir, { days: s.days });
212
+ const spots = hotSpots({ ...r, bugs: this.bugs(p), days: s.days, top: s.top + Object.keys(rec.dismissed ?? {}).length });
213
+ Object.assign(rec, { at: new Date(this.now()).toISOString(), error: null, days: s.days, commits: r.commits.length, scanned: r.scanned, spots });
214
+ } catch (e) {
215
+ Object.assign(rec, { at: new Date(this.now()).toISOString(), error: String(e.message).slice(0, 300) });
216
+ this.log(`debt: ${p.name}: ${e.message}`);
217
+ }
218
+ this.store.save();
219
+ })().finally(() => {
220
+ this.running.delete(p.key);
221
+ this.onChange();
222
+ });
223
+ this.running.set(p.key, job);
224
+ this.onChange();
225
+ }
226
+ return this.running.get(p.key).then(() => this.view());
227
+ }
228
+
229
+ /** The oldest scan that is due again (or a project never scanned that has a repository here): one per tick. */
230
+ tick() {
231
+ const s = this.settings;
232
+ if (!s.enabled || !s.autoDays || this.running.size) return;
233
+ const due = this.projects()
234
+ .map((p) => ({ p, at: Date.parse(this.state.projects[p.key]?.at ?? '') || 0, dir: this.dirOf(p) }))
235
+ .filter((x) => x.dir && fs.existsSync(x.dir) && this.now() - x.at >= s.autoDays * 86_400_000)
236
+ .sort((a, b) => a.at - b.at)[0];
237
+ if (due) this.scan(due.p.key).catch(() => {});
238
+ }
239
+
240
+ /** Hand a hot spot to an agent (through the backlog). */
241
+ queueSpot(ref, file) {
242
+ const p = this.project(ref);
243
+ const rec = this.state.projects[p.key];
244
+ const h = rec?.spots?.find((x) => x.file === file);
245
+ if (!h) throw err(404, 'No such hot spot (scan again?)');
246
+ if (!this.queue) throw err(409, 'The backlog is not available');
247
+ const added = this.queue(p, debtTask(h));
248
+ rec.queued = { ...rec.queued, [file]: { at: new Date(this.now()).toISOString(), id: added?.id ?? null } };
249
+ this.store.save();
250
+ this.onChange();
251
+ return this.view();
252
+ }
253
+
254
+ /** Not debt (generated, or meant to be that way): off the list, also after the next scan. */
255
+ dismiss(ref, file, dismissed = true) {
256
+ const p = this.project(ref);
257
+ const rec = (this.state.projects[p.key] ??= { dismissed: {}, queued: {} });
258
+ rec.dismissed ??= {};
259
+ if (dismissed) rec.dismissed[file] = new Date(this.now()).toISOString();
260
+ else delete rec.dismissed[file];
261
+ this.store.save();
262
+ this.onChange();
263
+ return this.view();
264
+ }
265
+
266
+ view() {
267
+ const s = this.settings;
268
+ const projects = this.projects().map((p) => {
269
+ const rec = this.state.projects[p.key] ?? {};
270
+ const dir = this.dirOf(p);
271
+ const spots = (rec.spots ?? []).filter((h) => !rec.dismissed?.[h.file]).slice(0, s.top).map((h) => ({ ...h, queued: rec.queued?.[h.file]?.at ?? null }));
272
+ return { key: p.key, shortcut: p.shortcut, name: p.name, hasRepo: Boolean(dir && fs.existsSync(dir)), scanning: this.running.has(p.key), at: rec.at ?? null, error: rec.error ?? null, days: rec.days ?? s.days, commits: rec.commits ?? 0, scanned: rec.scanned ?? 0, dismissed: Object.keys(rec.dismissed ?? {}).length, spots };
273
+ });
274
+ return { projects: projects.sort((a, b) => (b.spots[0]?.score ?? -1) - (a.spots[0]?.score ?? -1) || a.name.localeCompare(b.name)), settings: s };
275
+ }
276
+ }
@@ -0,0 +1,188 @@
1
+ // Decisions: what was decided on each project and why, in one log, so "why did we do it this way"
2
+ // has an answer later. It is gathered from what already happens here: plans you approved or sent
3
+ // back (with your notes), the answers you gave agents' questions, and the "Decisions and risks"
4
+ // of each agent's design doc; and you can add your own. Entries stay after their agent is deleted.
5
+ // Nothing is sent anywhere, and no model is called.
6
+
7
+ import crypto from 'node:crypto';
8
+
9
+ const MAX = 2000;
10
+ export const DECISION_KINDS = { plan: 'Plan review', answer: 'Your answer', design: 'Design', manual: 'Added by you' };
11
+ const err = (status, message) => Object.assign(new Error(message), { status });
12
+ const clip = (s, n) => {
13
+ const t = String(s ?? '').replace(/\s+/g, ' ').trim();
14
+ return t.length > n ? `${t.slice(0, n - 1)}…` : t;
15
+ };
16
+ const hash = (s) => crypto.createHash('sha1').update(String(s)).digest('hex').slice(0, 10);
17
+ const plain = (s) => String(s ?? '').replace(/\*\*([^*]+)\*\*/g, '$1').replace(/`([^`]+)`/g, '$1').trim();
18
+
19
+ /** The bullets under "## Decisions and risks" (or "## Decisions") of a design doc. */
20
+ export function designDecisions(markdown) {
21
+ const out = [];
22
+ let on = false;
23
+ let cur = null;
24
+ const flush = () => {
25
+ if (cur?.trim()) out.push(cur.replace(/\s+/g, ' ').trim());
26
+ cur = null;
27
+ };
28
+ for (const line of String(markdown ?? '').split('\n')) {
29
+ if (/^#{1,6}\s/.test(line)) {
30
+ flush();
31
+ on = /^#{2,3}\s+(key\s+)?decisions\b/i.test(line);
32
+ continue;
33
+ }
34
+ if (!on) continue;
35
+ const b = line.match(/^\s{0,3}[-*]\s+(.*)$/);
36
+ if (b) {
37
+ flush();
38
+ cur = b[1];
39
+ } else if (cur !== null && line.trim()) cur += ` ${line.trim()}`;
40
+ else flush();
41
+ }
42
+ flush();
43
+ // A line that only names a risk isn't a decision.
44
+ return out.filter((t) => t.length > 8 && !/^\**risks?\b[^:]*:/i.test(t));
45
+ }
46
+
47
+ /** A decision bullet as { title, decision }: its bold lead or first clause, then the whole of it. */
48
+ function splitBullet(text) {
49
+ const bold = text.match(/^\*\*([^*]{3,120})\*\*[:.]?\s*(.*)$/);
50
+ if (bold) return { title: plain(bold[1]), decision: plain(bold[2]) || plain(bold[1]) };
51
+ const t = plain(text);
52
+ const lead = t.match(/^(.{12,110}?)(?::\s|\s[–—-]\s|;\s|\.\s)(.+)$/);
53
+ return lead ? { title: lead[1], decision: t } : { title: clip(t, 110), decision: t };
54
+ }
55
+
56
+ export class Decisions {
57
+ /**
58
+ * `agents()` lists the agent records; `projectOf(agent)` names its project; `questions(agent)`
59
+ * its questions ([{ id, question }]); `designDoc(id)` its design doc ({ markdown, updatedAt }).
60
+ */
61
+ constructor({ store, agents, projectOf, questions = () => [], designDoc = () => null, onChange = () => {}, now = () => new Date().toISOString(), timer = true }) {
62
+ Object.assign(this, { store, agents, projectOf, questions, designDoc, onChange, now });
63
+ if (timer) {
64
+ // Gathered now and then too, so an agent deleted between two looks still leaves its decisions.
65
+ this.timer = setInterval(() => this.sync(), 5 * 60_000);
66
+ this.timer.unref?.();
67
+ }
68
+ }
69
+
70
+ close() {
71
+ clearInterval(this.timer);
72
+ }
73
+
74
+ get state() {
75
+ return (this.store.data.decisions ??= { items: {}, removed: {} });
76
+ }
77
+
78
+ /** Gather what's new from the agents; true when something was added or changed. */
79
+ sync() {
80
+ const st = this.state;
81
+ let changed = false;
82
+ const put = (id, rec) => {
83
+ if (st.removed[id]) return;
84
+ const prev = st.items[id];
85
+ if (prev && prev.decision === rec.decision && prev.why === rec.why && !prev.superseded) return;
86
+ st.items[id] = { ...prev, id, ...rec, superseded: false };
87
+ changed = true;
88
+ };
89
+ for (const a of this.agents()) {
90
+ const p = this.projectOf(a);
91
+ if (!p || ['general', 'assistant'].includes(p.key)) continue;
92
+ const base = { project: { key: p.key, name: p.name }, agentId: a.id, agentName: a.name };
93
+ const pr = a.planReview;
94
+ if (pr?.decidedAt && ['approved', 'changes'].includes(pr.status)) {
95
+ put(`plan:${a.id}:${pr.decidedAt}`, { ...base, kind: 'plan', at: pr.decidedAt, title: `Plan for ${a.name}`, decision: pr.status === 'approved' ? 'Approved' : 'Sent back for changes', why: clip(pr.note, 1000) || null });
96
+ }
97
+ const answers = a.answers ?? {};
98
+ if (Object.keys(answers).length) {
99
+ const qs = new Map(this.questions(a).map((q) => [q.id, q]));
100
+ for (const [qid, ans] of Object.entries(answers)) {
101
+ const text = typeof ans === 'string' ? ans : ans?.text;
102
+ if (!text) continue;
103
+ put(`answer:${a.id}:${qid}`, { ...base, kind: 'answer', at: ans?.at ?? this.now(), title: clip(qs.get(qid)?.question ?? `A question from ${a.name}`, 300), decision: clip(text, 1000), why: qs.get(qid)?.why ? clip(qs.get(qid).why, 500) : null });
104
+ }
105
+ }
106
+ const doc = this.designDoc(a.id);
107
+ if (doc?.markdown) {
108
+ const seen = new Set();
109
+ for (const b of designDecisions(doc.markdown)) {
110
+ const { title, decision } = splitBullet(b);
111
+ const id = `design:${a.id}:${hash(b)}`;
112
+ seen.add(id);
113
+ if (!st.items[id]) put(id, { ...base, kind: 'design', at: doc.updatedAt ?? this.now(), title: clip(title, 300), decision: clip(decision, 1000), why: null });
114
+ }
115
+ // The design moved on: what it no longer says is kept, marked as replaced.
116
+ for (const it of Object.values(st.items)) {
117
+ if (it.kind === 'design' && it.agentId === a.id && !seen.has(it.id) && !it.superseded) {
118
+ it.superseded = true;
119
+ changed = true;
120
+ }
121
+ }
122
+ }
123
+ }
124
+ if (changed) {
125
+ const all = Object.values(st.items).sort((x, y) => String(y.at).localeCompare(String(x.at)));
126
+ if (all.length > MAX) st.items = Object.fromEntries(all.slice(0, MAX).map((i) => [i.id, i]));
127
+ this.store.save();
128
+ this.onChange();
129
+ }
130
+ return changed;
131
+ }
132
+
133
+ /** Add one of your own: { project (a known project's key and name), title, decision, why }. */
134
+ add({ project, title, decision, why = null } = {}) {
135
+ if (!project?.key) throw err(400, 'Pick the project it belongs to');
136
+ const t = clip(title, 300);
137
+ const d = clip(decision, 1000);
138
+ if (t.length < 3 || d.length < 2) throw err(400, 'Say what was decided: a title and the decision');
139
+ const id = `manual:${crypto.randomBytes(4).toString('hex')}`;
140
+ this.state.items[id] = { id, kind: 'manual', at: this.now(), project: { key: project.key, name: project.name }, agentId: null, agentName: null, title: t, decision: d, why: clip(why, 1000) || null, superseded: false };
141
+ this.store.save();
142
+ this.onChange();
143
+ return this.state.items[id];
144
+ }
145
+
146
+ /** Take one off the log (it isn't gathered again). */
147
+ remove(id) {
148
+ const st = this.state;
149
+ if (!st.items[id]) throw err(404, 'No such decision');
150
+ delete st.items[id];
151
+ st.removed[id] = this.now();
152
+ this.store.save();
153
+ this.onChange();
154
+ return { ok: true };
155
+ }
156
+
157
+ /** The log, newest first: all of it, or one project's, or what matches `q`. */
158
+ view({ project = null, q = '' } = {}) {
159
+ this.sync();
160
+ const all = Object.values(this.state.items).sort((x, y) => String(y.at).localeCompare(String(x.at)));
161
+ const counts = new Map();
162
+ for (const i of all) counts.set(i.project.key, { key: i.project.key, name: i.project.name, count: (counts.get(i.project.key)?.count ?? 0) + 1 });
163
+ const words = String(q ?? '').trim().toLowerCase();
164
+ const live = new Set(this.agents().map((a) => a.id));
165
+ const items = all
166
+ .filter((i) => (!project || i.project.key === project) && (!words || `${i.title} ${i.decision} ${i.why ?? ''} ${i.agentName ?? ''} ${i.project.name}`.toLowerCase().includes(words)))
167
+ .map((i) => ({ ...i, kindLabel: DECISION_KINDS[i.kind] ?? i.kind, agentGone: Boolean(i.agentId) && !live.has(i.agentId) }));
168
+ return { items, total: all.length, projects: [...counts.values()].sort((a, b) => a.name.localeCompare(b.name)), kinds: DECISION_KINDS };
169
+ }
170
+
171
+ /** The log as Markdown, a project a section, newest first. */
172
+ markdown({ project = null } = {}) {
173
+ const { items } = this.view({ project });
174
+ const by = new Map();
175
+ for (const i of items) by.set(i.project.name, [...(by.get(i.project.name) ?? []), i]);
176
+ const out = ['# Decision log', ''];
177
+ if (!items.length) out.push('No decisions recorded yet.', '');
178
+ for (const [name, list] of [...by].sort((a, b) => a[0].localeCompare(b[0]))) {
179
+ out.push(`## ${name}`, '');
180
+ for (const i of list) {
181
+ out.push(`### ${i.title}`, '', `- **Decided:** ${i.decision}`);
182
+ if (i.why) out.push(`- **Why:** ${i.why}`);
183
+ out.push(`- **When:** ${String(i.at).slice(0, 10)} · ${i.kindLabel}${i.agentName ? ` · agent ${i.agentName}` : ''}${i.superseded ? ' · replaced since' : ''}`, '');
184
+ }
185
+ }
186
+ return out.join('\n');
187
+ }
188
+ }