ai-agentmanager 1.70.2 → 1.72.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/manager.js CHANGED
@@ -146,6 +146,8 @@ import { PROOF_FILE, proofBlock, proofFacts, proofPrompt } from './proof.js';
146
146
  import { PRIVATE_MESSAGE, ideaPatch, keptPrivate, mustBeShareable } from './private.js';
147
147
  import { awaitsReview, readFirst } from './readfirst.js';
148
148
  import { traceOf } from './trace.js';
149
+ import { blameLine, readTranscripts } from './blame.js';
150
+ import { fenceOf, pullBackMessage } from './fence.js';
149
151
  import { GroundRules, groundRulesMessage } from './groundrules.js';
150
152
  import { autonomySettings, callLadder, eligible as autonomyEligible, levelOf, modelName, parseLevel } from './autonomy.js';
151
153
  import { STUCK_DEFAULTS, detectStuck } from './stuck.js';
@@ -169,7 +171,9 @@ import {
169
171
  prDetails,
170
172
  prFromUrl,
171
173
  prsForBranch,
174
+ subagentTranscripts,
172
175
  sumUsage,
176
+ transcriptPath,
173
177
  } from './tracker.js';
174
178
 
175
179
  // Per-session markers a parent Claude Code session sets. Inherited, they make the
@@ -331,6 +335,7 @@ export class AgentManager extends EventEmitter {
331
335
  this.refreshing = new Map(); // agent id -> the refresh in progress
332
336
  this.lastPrCheck = new Map();
333
337
  this.changeSets = new Map(); // agent id -> { files, baseSha, at }: what its branch changed (conflict radar)
338
+ this.fences = new Map(); // agent id -> { key, value }: its scope fence, kept until its changes or brief change (fence.js)
334
339
  this.conflicts = new Map(); // agent id -> [conflict]
335
340
  this.activity = new Map(); // session id -> transcript activity window (stuck detection)
336
341
  this.stuck = new Map(); // agent id -> [finding]
@@ -418,6 +423,8 @@ export class AgentManager extends EventEmitter {
418
423
  keptPrivate: keptPrivate(agent),
419
424
  // Finished and waiting for review: how much it needs reading, why, and where to start (readfirst.js).
420
425
  readFirst: awaitsReview(agent) ? readFirst(agent, this.traceFor(agent)) : null,
426
+ // Changing code outside what it was asked and planned (fence.js): { drift, allowed }, or null.
427
+ fence: NO_REPO.has(agent.kind) || agent.reviewing || agent.hunting ? null : this.fenceFor(agent),
421
428
  priority: agent.priority ?? 2,
422
429
  activeAt: this.activeAt(agent, rt),
423
430
  projectInfo: this.projectInfo(agent),
@@ -1943,6 +1950,7 @@ export class AgentManager extends EventEmitter {
1943
1950
  if (agent.workdir && fs.existsSync(agent.workdir)) await git.deleteRefs(agent.workdir, `refs/agentmgr/${agent.id}/`).catch(() => {});
1944
1951
  else if (agent.sourceDir && fs.existsSync(agent.sourceDir)) await git.deleteRefs(agent.sourceDir, `refs/agentmgr/${agent.id}/`).catch(() => {});
1945
1952
  this.changeSets.delete(agent.id);
1953
+ this.fences.delete(agent.id);
1946
1954
  for (const k of this.clashVerdicts.keys()) if (k.split('|').includes(agent.id)) this.clashVerdicts.delete(k);
1947
1955
  this.stuck.delete(agent.id);
1948
1956
  this.outbox.delete(agent.id);
@@ -2087,7 +2095,24 @@ export class AgentManager extends EventEmitter {
2087
2095
  this.termRuntime(id, kind)?.pty?.write(data);
2088
2096
  }
2089
2097
 
2090
- /** Resize a session. `from`: the viewer that asked, which is not sent its own size back. */
2098
+ /**
2099
+ * Text from the box under the terminal, typed and submitted here rather than by the page: the
2100
+ * Enter is pressed once the program has taken the text in, and again if it still sits in the
2101
+ * input box (submitTold). Sent by the page as two keystrokes, a phone's separate requests could
2102
+ * bring the Enter too early, and a long message stayed unsent.
2103
+ */
2104
+ typeIn(id, text, kind = 'claude') {
2105
+ const rt = this.termRuntime(id, kind);
2106
+ if (!rt?.pty) throw Object.assign(new Error('The session is not running'), { status: 409 });
2107
+ text = String(text ?? '');
2108
+ if (!text.trim()) throw Object.assign(new Error('Message is empty'), { status: 400 });
2109
+ this.inputAt.set(id, Date.now());
2110
+ if (shellNumber(kind)) return rt.pty.write(`${text}\r`);
2111
+ rt.pty.write(text.includes('\n') ? `\x1b[200~${text}\x1b[201~` : text);
2112
+ this.submitTold(rt, text);
2113
+ }
2114
+
2115
+ /** Resize a session; every viewer is sent the size it took. */
2091
2116
  resize(id, cols, rows, kind = 'claude') {
2092
2117
  const rt = this.termRuntime(id, kind);
2093
2118
  if (!rt || !(cols > 0 && rows > 0)) return;
@@ -2559,6 +2584,93 @@ export class AgentManager extends EventEmitter {
2559
2584
  }
2560
2585
 
2561
2586
  /** The requirement trace of an agent (trace.js), from its proof as it is on disk. */
2587
+ /**
2588
+ * The scope fence (fence.js), worked out again only when its changes, brief or allowed areas
2589
+ * change: { drift: [{ area, files, lines }], allowed }, or null when there is nothing to say.
2590
+ */
2591
+ fenceFor(agent) {
2592
+ const cs = this.changeSets.get(agent.id);
2593
+ if (!cs?.files || !Object.keys(cs.files).length) return null;
2594
+ const allowed = agent.scope?.allowed ?? [];
2595
+ const mtime = (f) => {
2596
+ try {
2597
+ return fs.statSync(f(agent.id)).mtimeMs;
2598
+ } catch {
2599
+ return 0;
2600
+ }
2601
+ };
2602
+ const key = `${cs.at}|${agent.brief?.updatedAt}|${allowed.join(',')}|${mtime(intentPath)}|${mtime(specPath)}|${mtime(planPath)}|${agent.acceptance?.points?.length ?? 0}|${agent.intent?.length}`;
2603
+ const hit = this.fences.get(agent.id);
2604
+ if (hit?.key === key) return hit.value;
2605
+ const read = (f) => {
2606
+ try {
2607
+ return fs.readFileSync(f(agent.id), 'utf8');
2608
+ } catch {
2609
+ return '';
2610
+ }
2611
+ };
2612
+ const b = agent.brief ?? {};
2613
+ const text = [agent.intent, read(intentPath), read(specPath), read(planPath), b.problem, b.solution, ...(agent.acceptance?.points ?? []).map((p) => p.text ?? p)].join('\n');
2614
+ const f = fenceOf({ files: cs.files, text, allowed });
2615
+ const value = f.drift.length ? { drift: f.drift.map(({ area, files, lines }) => ({ area, files: files.slice(0, 8), lines })), allowed } : allowed.length ? { drift: [], allowed } : null;
2616
+ this.fences.set(agent.id, { key, value });
2617
+ return value;
2618
+ }
2619
+
2620
+ /** The person on the fence: `allow` an area (in scope from now on), or `pull` it back (it is told). */
2621
+ setFence(ref, { allow, pull } = {}) {
2622
+ const agent = this.mustGet(ref);
2623
+ if (allow) {
2624
+ const area = String(allow).trim();
2625
+ if (!area) throw Object.assign(new Error('Which area?'), { status: 400 });
2626
+ this.patch(agent.id, { scope: { ...agent.scope, allowed: [...new Set([...(agent.scope?.allowed ?? []), area])] } });
2627
+ } else if (pull) {
2628
+ const drift = this.fenceFor(agent)?.drift ?? [];
2629
+ if (!drift.length) throw Object.assign(new Error('It is not changing anything outside its task'), { status: 409 });
2630
+ this.tell(agent.id, pullBackMessage(drift), { source: 'fence' });
2631
+ this.patch(agent.id, { scope: { ...agent.scope, pulledAt: now() } });
2632
+ } else throw Object.assign(new Error('allow (an area) or pull is required'), { status: 400 });
2633
+ return this.view(this.store.get(agent.id));
2634
+ }
2635
+
2636
+ /**
2637
+ * Why is this line here (blame.js): the moment in its conversation that wrote line `lineNo` of
2638
+ * `file` (or the given `text`), from its sessions' transcripts and their subagents'.
2639
+ */
2640
+ whyLine(ref, { file, line: lineNo, text } = {}) {
2641
+ const agent = this.mustGet(ref);
2642
+ if ((agent.engine ?? DEFAULT_ENGINE) !== 'claude') throw Object.assign(new Error('Only for Claude Code agents for now'), { status: 409 });
2643
+ if (!agent.workdir) throw Object.assign(new Error('It has no folder yet'), { status: 409 });
2644
+ file = String(file ?? '').replace(/^\.?\//, '');
2645
+ const abs = path.resolve(agent.workdir, file);
2646
+ const inside = (p, root) => p.startsWith(`${root}${path.sep}`);
2647
+ if (!file || !inside(abs, path.resolve(agent.workdir))) throw Object.assign(new Error('A file in its folder is required'), { status: 400 });
2648
+ // A link inside its folder that leads out of it is not followed.
2649
+ const root = fs.realpathSync(agent.workdir);
2650
+ let real = path.resolve(root, file);
2651
+ try {
2652
+ real = fs.realpathSync(abs);
2653
+ } catch {}
2654
+ if (!inside(real, root)) throw Object.assign(new Error('A file in its folder is required'), { status: 400 });
2655
+ if (text == null) {
2656
+ const n = Number(lineNo);
2657
+ if (!Number.isInteger(n) || n < 1) throw Object.assign(new Error('line (a number from 1) or text is required'), { status: 400 });
2658
+ let lines;
2659
+ try {
2660
+ lines = fs.readFileSync(abs, 'utf8').split('\n');
2661
+ } catch {
2662
+ throw Object.assign(new Error(`No file ${file} in its folder`), { status: 404 });
2663
+ }
2664
+ if (n > lines.length) throw Object.assign(new Error(`${file} has ${lines.length} lines`), { status: 400 });
2665
+ text = lines[n - 1];
2666
+ }
2667
+ const files = (agent.sessions ?? []).flatMap((s) => [
2668
+ { session: s.id, file: transcriptPath(agent.workdir, s.id) },
2669
+ ...subagentTranscripts(agent.workdir, s.id).map((f) => ({ session: s.id, file: f })),
2670
+ ]);
2671
+ return { file, line: lineNo == null ? null : Number(lineNo), text, ...blameLine(readTranscripts(files), { file, line: text, workdir: agent.workdir }) };
2672
+ }
2673
+
2562
2674
  traceFor(agent) {
2563
2675
  if (!this.proof || (agent.acceptance?.status !== 'agreed' && !agent.docs?.scorecard?.data?.criteria?.length)) return null;
2564
2676
  const p = this.proof.forScore(agent);
@@ -3541,12 +3653,45 @@ export class AgentManager extends EventEmitter {
3541
3653
  rt.toldAt = t;
3542
3654
  // Bracketed paste keeps a multi-line message as one message instead of submitting each line.
3543
3655
  rt.pty.write(text.includes('\n') ? `\x1b[200~${text}\x1b[201~` : text);
3544
- setTimeout(() => rt.pty?.write('\r'), 250);
3656
+ this.submitTold(rt, text);
3545
3657
  const a = this.store.get(id);
3546
3658
  if (a) this.changed(a);
3547
3659
  }
3548
3660
  }
3549
3661
 
3662
+ /**
3663
+ * Press Enter on a message just typed, and again if it is still sitting in the input box. A long
3664
+ * message takes the program a moment to take in (Claude Code folds it into "[Pasted text]"), and
3665
+ * an Enter that comes before then is lost or becomes a line break. Still in the box a moment
3666
+ * later, and the agent not working: Enter again (twice at most).
3667
+ */
3668
+ submitTold(rt, text, { waits = [4500, 8000] } = {}) {
3669
+ // The longer the message, the longer it takes in: 250 ms, up to 1.5 s for a long one.
3670
+ const first = 250 + Math.min(1250, Math.round(text.length / 4));
3671
+ setTimeout(() => rt.pty?.write('\r'), first);
3672
+ // (The box wraps long lines anywhere, so spaces are left out when comparing.)
3673
+ const snippet = text.replace(/\s+/g, '').slice(-24);
3674
+ const unsent = () => {
3675
+ if (!rt.pty || rt.busy || rt.attention) return false;
3676
+ // What is in the input box: after its prompt mark, the last one on the screen ("❯", or
3677
+ // "│ >" in older versions). The message shown anywhere else (sent, in the conversation) is not.
3678
+ const bottom = this.screenText(rt).slice(-600).replace(/\s+/g, '');
3679
+ const box = Math.max(bottom.lastIndexOf('❯'), bottom.lastIndexOf('│>'));
3680
+ if (box < 0) return false;
3681
+ const inBox = bottom.slice(box);
3682
+ return /\[Pastedtext#\d+/.test(inBox) || (snippet.length >= 8 && inBox.includes(snippet));
3683
+ };
3684
+ // (The text's own echo keeps it busy for a few seconds, so the first look is after that. While
3685
+ // pressing again, the next queued message waits.)
3686
+ for (const ms of waits) {
3687
+ setTimeout(() => {
3688
+ if (!unsent()) return;
3689
+ rt.pty.write('\r');
3690
+ rt.toldAt = Date.now();
3691
+ }, first + ms);
3692
+ }
3693
+ }
3694
+
3550
3695
  // ------------------------------------------------------- conflict radar
3551
3696
 
3552
3697
  /** Recompute what an agent's branch changed since it branched (needs a base commit). */
@@ -0,0 +1,155 @@
1
+ // Night watch: does merged work still hold on the latest main? An agent's proof (proof.js) shows
2
+ // its checks passed on its own branch. Later merges can break that without any one review seeing
3
+ // it. So, for work merged in the last days, the recorded commands are run again against the latest
4
+ // main, in a checkout of its own (the agent's folder is left alone), and each is compared with
5
+ // what was recorded. A proof that no longer holds names the commits since its merge that changed
6
+ // the same files: where to look first. Off until you turn it on (it runs agents' commands on this
7
+ // computer); run by hand any time. A command that changes things is never run (proof.js).
8
+ import fs from 'node:fs';
9
+ import os from 'node:os';
10
+ import path from 'node:path';
11
+ import * as git from './git.js';
12
+ import { changesThings, compareRun, parseProof, proofPath } from './proof.js';
13
+
14
+ export const NIGHT_DEFAULTS = { enabled: false, hour: 3, days: 14, maxAgents: 12 };
15
+ const MAX_COMMANDS = 6;
16
+ // Installed dependencies are not part of git: the agent's own are lent to the checkout.
17
+ const DEPS = ['node_modules', '.venv', 'venv', 'vendor'];
18
+
19
+ export function nightSettings(config = {}) {
20
+ const n = config.nightWatch ?? {};
21
+ const num = (v, d, lo, hi) => (Number.isFinite(Number(v)) ? Math.min(hi, Math.max(lo, Number(v))) : d);
22
+ return { enabled: n.enabled === true, hour: num(n.hour, NIGHT_DEFAULTS.hour, 0, 23), days: num(n.days, NIGHT_DEFAULTS.days, 1, 90), maxAgents: num(n.maxAgents, NIGHT_DEFAULTS.maxAgents, 1, 50) };
23
+ }
24
+
25
+ /** Whether a scheduled run is due: on, at its hour or after, and not yet run today. */
26
+ export function due(settings, lastRunAt, t = new Date()) {
27
+ if (!settings.enabled || t.getHours() < settings.hour) return false;
28
+ const last = lastRunAt ? new Date(lastRunAt) : null;
29
+ return !last || last.toDateString() !== t.toDateString();
30
+ }
31
+
32
+ /** The merged work to watch: merged in the last `days`, its agent still known, newest first. */
33
+ export function watchList(items, { days, maxAgents }, t = Date.now()) {
34
+ return items
35
+ .filter((it) => it.agentId && it.facts?.mergeCommit && Date.parse(it.mergedAt) >= t - days * 86_400_000)
36
+ .sort((a, b) => b.mergedAt.localeCompare(a.mergedAt))
37
+ .slice(0, maxAgents);
38
+ }
39
+
40
+ /** One merged piece of work: { status: 'holds' | 'broken' | 'skipped', why?, results, suspects }. */
41
+ export function verdictOf(results) {
42
+ const ran = results.filter((r) => r.status !== 'skipped');
43
+ if (!ran.length) return 'skipped';
44
+ return ran.some((r) => r.status === 'differs') ? 'broken' : 'holds';
45
+ }
46
+
47
+ export class NightWatch {
48
+ constructor({ manager, store, quality, run, config = {}, log = () => {}, readProof = (id) => fs.readFileSync(proofPath(id), 'utf8') }) {
49
+ Object.assign(this, { manager, store, quality, run, config, log, readProof });
50
+ store.data.nightWatch ??= { lastRunAt: null, runs: {} };
51
+ this.state = store.data.nightWatch;
52
+ this.running = null;
53
+ }
54
+
55
+ get settings() {
56
+ return nightSettings(this.config);
57
+ }
58
+
59
+ view() {
60
+ const runs = Object.values(this.state.runs).sort((a, b) => b.mergedAt.localeCompare(a.mergedAt));
61
+ return { settings: this.settings, lastRunAt: this.state.lastRunAt, running: Boolean(this.running), runs, broken: runs.filter((r) => r.status === 'broken').length };
62
+ }
63
+
64
+ /** Called on a timer: runs when due. */
65
+ tick(t = new Date()) {
66
+ if (this.running || !due(this.settings, this.state.lastRunAt, t)) return null;
67
+ return this.runAll().catch((e) => this.log(`night watch: ${e.message}`));
68
+ }
69
+
70
+ /** Watch every piece of merged work in the list now. The person's call, or the schedule's. */
71
+ async runAll() {
72
+ if (this.running) return this.running;
73
+ this.running = (async () => {
74
+ const list = watchList(this.quality.view().items, this.settings);
75
+ for (const it of list) {
76
+ const r = await this.watch(it).catch((e) => ({ status: 'skipped', why: e.message, results: [], suspects: [] }));
77
+ this.state.runs[it.url] = { url: it.url, number: it.number ?? null, title: it.title ?? null, agentId: it.agentId, mergedAt: it.mergedAt, at: new Date().toISOString(), ...r };
78
+ const a = this.store.get(it.agentId);
79
+ if (a) this.manager.patch(a.id, { nightWatch: { at: new Date().toISOString(), status: r.status, mainSha: r.mainSha ?? null, broken: (r.results ?? []).filter((x) => x.status === 'differs').map((x) => x.title), suspects: (r.suspects ?? []).slice(0, 3), url: it.url } });
80
+ }
81
+ // Kept for the work still watched, and a little after (twice its days).
82
+ const keep = Date.now() - 2 * this.settings.days * 86_400_000;
83
+ for (const [url, r] of Object.entries(this.state.runs)) if (Date.parse(r.mergedAt) < keep) delete this.state.runs[url];
84
+ this.state.lastRunAt = new Date().toISOString();
85
+ this.store.save();
86
+ return this.view();
87
+ })().finally(() => (this.running = null));
88
+ return this.running;
89
+ }
90
+
91
+ /** One merged piece of work against the latest main. */
92
+ async watch(it) {
93
+ const agent = this.store.get(it.agentId);
94
+ let entries = [];
95
+ try {
96
+ entries = parseProof(this.readProof(it.agentId)).filter((e) => e.command);
97
+ } catch {}
98
+ if (!entries.length) return { status: 'skipped', why: 'It recorded no commands', results: [], suspects: [] };
99
+ const repoDir = agent?.sourceDir;
100
+ if (!repoDir || !(await git.isGitRepo(repoDir))) return { status: 'skipped', why: 'Its repository is not on this computer', results: [], suspects: [] };
101
+ await git.fetch(repoDir).catch(() => {});
102
+ const base = it.facts.base || 'main';
103
+ const ref = await git.run('git', ['rev-parse', '--verify', '--quiet', `origin/${base}`], { cwd: repoDir }).catch(() => git.run('git', ['rev-parse', '--verify', base], { cwd: repoDir }));
104
+ const dest = fs.mkdtempSync(path.join(os.tmpdir(), 'agentmgr-night-'));
105
+ try {
106
+ await git.run('git', ['worktree', 'add', '--detach', '--force', dest, ref], { cwd: repoDir, timeout: 5 * 60_000 });
107
+ for (const d of DEPS) {
108
+ const from = agent.workdir && path.join(agent.workdir, d);
109
+ if (from && fs.existsSync(from) && !fs.existsSync(path.join(dest, d))) fs.symlinkSync(from, path.join(dest, d));
110
+ }
111
+ const results = [];
112
+ let ran = 0;
113
+ for (const e of entries) {
114
+ const why = changesThings(e.command) ?? (ran >= MAX_COMMANDS ? `only the first ${MAX_COMMANDS} are run` : null);
115
+ if (why) {
116
+ results.push({ title: e.title, command: e.command, status: 'skipped', why });
117
+ continue;
118
+ }
119
+ ran++;
120
+ this.log(`night watch: ${it.title ?? it.url}: ${e.command}`);
121
+ const r = await this.run(e.command, { cwd: dest, timeoutMs: 180_000 });
122
+ results.push({ title: e.title, command: e.command, code: r.code, tail: String(r.tail ?? '').split('\n').slice(-8).join('\n').slice(-800), ...compareRun(e, r) });
123
+ }
124
+ const status = verdictOf(results);
125
+ // Where to look first: the commits since its merge that changed the files it changed.
126
+ let suspects = [];
127
+ if (status === 'broken') {
128
+ const files = (it.facts.files ?? []).slice(0, 100);
129
+ const out = await git.run('git', ['log', '--format=%h%x09%s%x09%cI', '-n', '8', `${it.facts.mergeCommit}..${ref}`, '--', ...files], { cwd: repoDir }).catch(() => '');
130
+ suspects = out.split('\n').filter(Boolean).map((l) => {
131
+ const [sha, subject, at] = l.split('\t');
132
+ return { sha, subject, at };
133
+ });
134
+ }
135
+ return { status, mainSha: ref.slice(0, 9), results, suspects };
136
+ } finally {
137
+ await git.run('git', ['worktree', 'remove', '--force', dest], { cwd: repoDir }).catch(async () => {
138
+ fs.rmSync(dest, { recursive: true, force: true });
139
+ await git.run('git', ['worktree', 'prune'], { cwd: repoDir }).catch(() => {});
140
+ });
141
+ }
142
+ }
143
+ }
144
+
145
+ export function nightMarkdown(v) {
146
+ const out = ['# Night watch', '', v.lastRunAt ? `Last run ${v.lastRunAt}. ${v.broken} of ${v.runs.length} no longer hold on main.` : 'Not run yet.', ''];
147
+ for (const r of v.runs) {
148
+ out.push(`## ${r.status === 'broken' ? 'No longer holds' : r.status === 'holds' ? 'Holds' : 'Not checked'}: ${r.number ? `#${r.number} ` : ''}${r.title ?? r.url}`, '');
149
+ if (r.why) out.push(r.why, '');
150
+ for (const x of r.results ?? []) out.push(`- ${x.status === 'differs' ? 'Differs' : x.status === 'same' ? 'Same' : 'Skipped'}: ${x.title} \`${x.command}\`${x.status === 'differs' ? ` (exit ${x.code})` : ''}`);
151
+ if (r.suspects?.length) out.push('', 'Changed the same files since it merged:', ...r.suspects.map((s) => `- ${s.sha} ${s.subject}`));
152
+ out.push('');
153
+ }
154
+ return out.join('\n').trimEnd();
155
+ }
package/src/races.js CHANGED
@@ -68,6 +68,60 @@ export class Races extends EventEmitter {
68
68
  return this.view(id);
69
69
  }
70
70
 
71
+ /**
72
+ * Try the other path: an agent wrote down the ways it weighed (## Options, its preferred one
73
+ * first, the one it takes). Path `n` is started as a second agent from the same base commit,
74
+ * told to take that path, and the two are raced: the scoreboard, a test command run in both,
75
+ * and picking the one to keep. A path already being tried is not started twice.
76
+ */
77
+ tryPath(agentId, n) {
78
+ const src = this.manager.mustGet(agentId);
79
+ const paths = src.brief?.options?.paths ?? [];
80
+ n = Number(n);
81
+ if (!paths.length) throw err(409, 'It has not written the paths it weighed (## Options in its brief)');
82
+ if (!Number.isInteger(n) || n < 2 || n > paths.length) throw err(400, `Pick a path from 2 to ${paths.length}: path 1 is the one it takes`);
83
+ if (src.kind !== 'task' || src.team) throw err(409, 'Only a task agent of its own can try another path');
84
+ // In a race: only the one its own Try this path started (not a race of variants, nor one where it is the other path).
85
+ if (src.raceId && this.store.data.races[src.raceId] && this.store.data.races[src.raceId].tryOf !== src.id) throw err(409, 'It is already in a race');
86
+ const repoDir = src.sourceDir ?? src.workdir;
87
+ if (!src.repo && !repoDir) throw err(409, 'It has no repository to start another agent in');
88
+ const label = `path-${n}`;
89
+ let race = src.raceId ? this.store.data.races[src.raceId] : null;
90
+ if (race && race.members.some((m) => this.manager.get(m)?.variant?.label === label)) throw err(409, `Path ${n} is already being tried`);
91
+ const p = paths[n - 1];
92
+ const first = paths[0];
93
+ const say = (x) => `"${x.name}"${x.what ? ` (${x.what})` : ''}`;
94
+ const raceId = race?.id ?? `r${crypto.randomBytes(3).toString('hex')}`;
95
+ const instructions = `Take path ${n}, ${say(p)}. Another agent is taking path 1, ${say(first)}: do not take that one. In ## Options, put the path you take first.`;
96
+ const a = this.manager.create({
97
+ intent: `${src.intent}\n\nApproach for this attempt: ${instructions}`,
98
+ name: `${src.name}-path${n}`,
99
+ ...(src.repo ? { repo: src.repo } : { dir: repoDir }),
100
+ worktree: true,
101
+ // The commit the first agent started from (its branch would carry its own path).
102
+ base: src.baseRef?.split(' @ ')[1] ?? undefined,
103
+ permissionMode: src.permissionMode ?? undefined,
104
+ model: src.model ?? undefined,
105
+ engine: src.engine ?? undefined,
106
+ project: src.project ?? undefined,
107
+ priority: src.priority,
108
+ autonomy: src.autonomy?.level ?? undefined,
109
+ designDoc: src.designDoc ?? undefined,
110
+ // (It starts at once: what done means was agreed for the task with the first agent.)
111
+ acceptance: false,
112
+ race: { id: raceId, variant: { label, model: src.model ?? null, instructions: `Path ${n}: ${p.name}` } },
113
+ });
114
+ // The race is made once the agent is: a refused one leaves none behind.
115
+ if (!race) {
116
+ race = { id: raceId, intent: src.intent, testCommand: null, createdAt: now(), members: [src.id], tests: {}, winner: null, tryOf: src.id };
117
+ this.store.data.races[raceId] = race;
118
+ this.manager.patch(src.id, { raceId, variant: { label: 'path-1', model: src.model ?? null, instructions: `Path 1: ${first.name}` } });
119
+ }
120
+ race.members.push(a.id);
121
+ this.save(race);
122
+ return this.view(race.id);
123
+ }
124
+
71
125
  get(id) {
72
126
  const race = this.store.data.races[id];
73
127
  if (!race) throw err(404, `No race ${id}`);
package/src/server.js CHANGED
@@ -60,6 +60,11 @@ import { Quality } from './quality.js';
60
60
  import { recordMarkdown } from './record.js';
61
61
  import { Weekly } from './weekly.js';
62
62
  import { queueMarkdown, readQueue } from './readfirst.js';
63
+ import { blameMarkdown } from './blame.js';
64
+ import { Echo } from './echo.js';
65
+ import { calibration, calibrationLines, calibrationMarkdown, cleanGuess } from './calibration.js';
66
+ import { NightWatch, nightMarkdown, nightSettings } from './nightwatch.js';
67
+ import { glance, glanceLine, glanceMarkdown } from '../public/glance.js';
63
68
  import { traceMarkdown, traceOf } from './trace.js';
64
69
  import { PRIVATE_MESSAGE, keptPrivate, mustBeShareable } from './private.js';
65
70
  import { Standards, runCheck } from './standards.js';
@@ -358,6 +363,16 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
358
363
  const quality = new Quality({ manager, store, config, who: me, onChange: () => pushQuality() });
359
364
  // Standards per repository: lessons from what went wrong, high-risk paths, and the quality bar (standards.js).
360
365
  const standards = new Standards({ manager, store, config, quality, onChange: () => pushQuality() });
366
+ // Night watch: merged work's recorded commands run again against the latest main (nightwatch.js). Off until turned on.
367
+ const nightWatch = new NightWatch({ manager, store, quality, run: runCheck, config, log: (m) => console.log(`[agentmgr] ${m}`) });
368
+ setInterval(() => nightWatch.tick(), 10 * 60_000).unref();
369
+ // Bug echo: a lesson accepted, the agents at work in that repository checked for the same mistake (echo.js).
370
+ const echo = new Echo({ manager, standards, review, log: (m) => console.log(`[agentmgr] ${m}`) });
371
+ const echoLesson = (key, lesson) => {
372
+ if (config.echo?.enabled === false || config.standards?.enabled === false || lesson?.state !== 'accepted') return lesson;
373
+ echo.run(key, lesson).catch((e) => console.log(`[agentmgr] bug echo: ${e.message}`));
374
+ return lesson;
375
+ };
361
376
  // A week's work and achievements on one page, for management (weekly.js); written as a draft file when the week is over.
362
377
  const weekly = new Weekly({ manager, store, worklog, value, quality, who: me, config });
363
378
  // AI News: the frontier labs' latest releases, summarized (news.js).
@@ -624,7 +639,13 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
624
639
  // Agents the assistant's own session starts: its limits apply, and they are marked as its.
625
640
  const extra = assistant.admit(req.headers['x-agentmgr-agent'], list, opts);
626
641
  if (extra.startedBy) proposed.refuseSetAside(list);
627
- const created = manager.createMany(list, { ...opts, ...extra });
642
+ // Your guess (calibration.js): yours only, so not on the ones the assistant starts. Checked first.
643
+ const guess = extra.startedBy ? null : cleanGuess(opts.guess);
644
+ let created = manager.createMany(list, { ...opts, ...extra });
645
+ if (guess) {
646
+ for (const a of created) manager.patch(a.id, { guess });
647
+ created = created.map((a) => manager.view(store.get(a.id) ?? a));
648
+ }
628
649
  if (!extra.startedBy) repeats.record(created.map((a) => ({ text: a.intent, projectKey: projectOf(store.get(a.id) ?? a).key })));
629
650
  if (extra.startedBy) {
630
651
  for (const a of created) notifier.send('assistant', a, `was started by the assistant: ${a.intent.replace(/\s+/g, ' ').slice(0, 160)}`);
@@ -1100,6 +1121,11 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
1100
1121
  // Attachments: copied once to a shared folder and listed in the request every attempt gets.
1101
1122
  const withFiles = ({ attachments, ...body } = {}) => ({ ...body, intent: manager.withSharedAttachments(body.intent, attachments) });
1102
1123
  api.post('/races', wrap((req) => races.create(withFiles(req.body ?? {}))));
1124
+ // Try the other path: the path it weighed and did not take, raced against the one it took (races.js).
1125
+ api.post('/agents/:id/try-path', wrap((req) => {
1126
+ if (req.headers['x-agentmgr-agent']) throw fail(403, 'Another path is tried when the person asks, not an agent');
1127
+ return races.tryPath(req.params.id, req.body?.path);
1128
+ }));
1103
1129
  api.get('/races/:id', wrap((req) => races.view(req.params.id)));
1104
1130
  api.post('/races/:id/tests', wrap((req) => races.runTests(req.params.id, req.body ?? {})));
1105
1131
  api.get('/races/:id/diff/:agent', wrap((req) => races.diff(req.params.id, req.params.agent)));
@@ -1275,6 +1301,39 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
1275
1301
  api.post('/repeats/dismiss', wrap((req) => repeats.dismiss(String(req.body?.key ?? ''))));
1276
1302
  api.post('/playbooks/:id/run', wrap((req) => playbooks.run(req.params.id, { vars: req.body?.vars ?? {} })));
1277
1303
  // Read first (readfirst.js): finished work waiting for review, the pieces that need reading most first.
1304
+ // At a glance: every agent on one line, grouped by what it needs from you (public/glance.js).
1305
+ api.get('/glance', wrap((req) => {
1306
+ const g = glance(store.list().map((a) => manager.view(a)));
1307
+ return { ...g, line: glanceLine(g), markdown: glanceMarkdown(g, { all: req.query.all === '1' }) };
1308
+ }));
1309
+ // Scope fence: allow an area it changes outside its task, or pull it back (fence.js).
1310
+ api.post('/agents/:id/fence', wrap((req) => {
1311
+ if (req.headers['x-agentmgr-agent']) throw fail(403, 'What is in scope is said by the person, not by an agent');
1312
+ return manager.setFence(req.params.id, req.body ?? {});
1313
+ }));
1314
+ // Your calibration: your guesses at the start against what happened (calibration.js).
1315
+ // The Read first level is gone once the work is reviewed: it is kept with the guess first.
1316
+ const keepActual = (v) => {
1317
+ if (v?.guess && v.readFirst && v.guess.actual?.review !== v.readFirst.level) manager.patch(v.id, { guess: { ...v.guess, actual: { review: v.readFirst.level } } });
1318
+ };
1319
+ api.put('/agents/:id/guess', wrap((req) => {
1320
+ if (req.headers['x-agentmgr-agent']) throw fail(403, 'A guess is yours, not an agent\'s');
1321
+ const a = manager.mustGet(req.params.id);
1322
+ const guess = cleanGuess(req.body ?? {});
1323
+ manager.patch(a.id, { guess: guess ? { ...guess, ...(a.guess?.actual ? { actual: a.guess.actual } : {}) } : null });
1324
+ return manager.view(manager.get(a.id));
1325
+ }));
1326
+ api.get('/calibration', wrap((req) => {
1327
+ const views = store.list().map((a) => manager.view(a));
1328
+ for (const v of views) keepActual(v);
1329
+ const c = calibration(store.list().map((a) => manager.view(a)));
1330
+ return { ...c, lines: calibrationLines(c), ...(req.query.format === 'md' ? { markdown: calibrationMarkdown(c) } : {}) };
1331
+ }));
1332
+ // Why is this line here: the moment in the agent's conversation that wrote it (blame.js).
1333
+ api.get('/agents/:id/why', wrap((req) => {
1334
+ const b = manager.whyLine(req.params.id, { file: req.query.file, line: req.query.line, text: req.query.text });
1335
+ return req.query.format === 'md' ? { ...b, markdown: blameMarkdown(b, { file: b.file, lineNo: b.line, line: b.text }) } : b;
1336
+ }));
1278
1337
  api.get('/read-first', wrap((req) => {
1279
1338
  const items = readQueue(store.list(), (a) => manager.view(a));
1280
1339
  return req.query.format === 'md' ? { markdown: queueMarkdown(items) } : { items };
@@ -1288,7 +1347,10 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
1288
1347
  if (b.agent) ids = [manager.mustGet(b.agent).id];
1289
1348
  else if (Number(b.olderThanDays) > 0) ids = readQueue(store.list(), (a) => manager.view(a)).filter((i) => Date.parse(i.finishedAt) < Date.now() - Number(b.olderThanDays) * 86_400_000).map((i) => i.agentId);
1290
1349
  else throw fail(400, 'Give agent, or olderThanDays');
1291
- for (const id of ids) manager.patch(id, { reviewed: b.reviewed === false ? null : { at } });
1350
+ for (const id of ids) {
1351
+ keepActual(manager.view(manager.get(id)));
1352
+ manager.patch(id, { reviewed: b.reviewed === false ? null : { at } });
1353
+ }
1292
1354
  return { marked: ids.length, items: readQueue(store.list(), (a) => manager.view(a)) };
1293
1355
  }));
1294
1356
  // Weekly summary (weekly.js): a week's work and achievements on one page, for management. A draft: nothing is sent.
@@ -1436,8 +1498,48 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
1436
1498
  };
1437
1499
  api.get('/standards', wrap(() => standards.view()));
1438
1500
  api.put('/standards/repo', wrap((req) => standards.update(standards.find(String(yours(req).key ?? '')), { risk: req.body.risk, bar: req.body.bar })));
1439
- api.post('/standards/lessons', wrap((req) => standards.addLesson(standards.find(String(yours(req).key ?? '')), req.body.text)));
1440
- api.put('/standards/lessons/:id', wrap((req) => standards.setLesson(standards.find(String(yours(req).key ?? '')), req.params.id, { state: req.body.state, text: req.body.text })));
1501
+ api.post('/standards/lessons', wrap((req) => {
1502
+ const key = standards.find(String(yours(req).key ?? ''));
1503
+ return echoLesson(key, standards.addLesson(key, req.body.text));
1504
+ }));
1505
+ api.put('/standards/lessons/:id', wrap((req) => {
1506
+ const key = standards.find(String(yours(req).key ?? ''));
1507
+ const was = standards.lesson(key, req.params.id).state;
1508
+ const l = standards.setLesson(key, req.params.id, { state: req.body.state, text: req.body.text });
1509
+ return was === 'accepted' && req.body.text === undefined ? l : echoLesson(key, l);
1510
+ }));
1511
+ // Check the agents at work against an accepted lesson again (bug echo), or act on one flagged.
1512
+ api.post('/standards/lessons/:id/echo', wrap(async (req) => {
1513
+ const key = standards.find(String(yours(req).key ?? ''));
1514
+ const l = standards.lesson(key, req.params.id);
1515
+ if (l.state !== 'accepted') throw fail(409, 'Only an accepted lesson is checked against the agents at work');
1516
+ return { checked: await echo.run(key, l) };
1517
+ }));
1518
+ api.get('/night-watch', wrap((req) => {
1519
+ const v = nightWatch.view();
1520
+ return req.query.format === 'md' ? { ...v, markdown: nightMarkdown(v) } : v;
1521
+ }));
1522
+ api.post('/night-watch/run', wrap(async (req) => {
1523
+ if (req.headers['x-agentmgr-agent']) throw fail(403, "Night watch runs agents' commands: the person starts it, not an agent");
1524
+ const p = nightWatch.runAll();
1525
+ if (req.body?.wait !== false) return p;
1526
+ p.catch((e) => console.log(`[agentmgr] night watch: ${e.message}`));
1527
+ return nightWatch.view();
1528
+ }));
1529
+ api.put('/night-watch', wrap((req) => {
1530
+ if (req.headers['x-agentmgr-agent']) throw fail(403, 'Night watch is set by the person, not by an agent');
1531
+ const b = req.body ?? {};
1532
+ const next = { ...config.nightWatch };
1533
+ if (typeof b.enabled === 'boolean') next.enabled = b.enabled;
1534
+ for (const k of ['hour', 'days']) if (b[k] !== undefined) next[k] = Number(b[k]);
1535
+ config.nightWatch = nightSettings({ nightWatch: next });
1536
+ saveConfig({ nightWatch: config.nightWatch });
1537
+ return nightWatch.view();
1538
+ }));
1539
+ api.post('/agents/:id/echo', wrap((req) => {
1540
+ if (req.headers['x-agentmgr-agent']) throw fail(403, 'The person acts on a flagged mistake, not an agent');
1541
+ return echo.act(req.params.id, String(req.body?.lesson ?? ''), req.body?.act);
1542
+ }));
1441
1543
  api.delete('/standards/lessons/:id', wrap((req) => (yours(req), standards.removeLesson(standards.find(String(req.query.key ?? '')), req.params.id))));
1442
1544
  api.post('/standards/lessons/:id/draft', wrap((req) => standards.draft(standards.find(String(yours(req).key ?? '')), req.params.id)));
1443
1545
  api.get('/agents/:id/standards', wrap((req) => standards.assess(req.params.id)));
@@ -1906,6 +2008,16 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
1906
2008
  return { ok: true };
1907
2009
  }),
1908
2010
  );
2011
+ // The box under the terminal: text typed and submitted by the daemon (manager.typeIn).
2012
+ api.post(
2013
+ '/agents/:id/term/send',
2014
+ wrap((req) => {
2015
+ const agent = termAgent(req.params.id);
2016
+ if (typeof req.body?.text !== 'string') throw fail(400, 'text (string) is required');
2017
+ manager.typeIn(agent.id, req.body.text, termKind(req.body.kind));
2018
+ return { ok: true };
2019
+ }),
2020
+ );
1909
2021
  api.post(
1910
2022
  '/agents/:id/term/resize',
1911
2023
  wrap((req) => {