ai-agentmanager 1.64.0 → 1.66.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.
@@ -107,6 +107,9 @@ export default {
107
107
  attention: [
108
108
  [/trustthisfolder/i, 'Folder trust prompt'],
109
109
  [/Doyouwantto(proceed|make|create|allow|run|overwrite)/i, 'Permission prompt'],
110
+ // The same prompt when a redraw dropped letters of its question ("Do you want to pro eed?"): its
111
+ // choices and footer, Yes first, No last, then "Esc to cancel" (a question menu ends "Enter to select").
112
+ [/(?:^|[^a-z0-9])1\.?Yes.{0,300}\d\.?No.{0,60}(?<!Entertoselect.{0,40})Esctocancel/i, 'Permission prompt'],
110
113
  // The agent's own question, as a menu: a message typed now would pick the highlighted option.
111
114
  [/Entertoselect.{0,40}Esctocancel/i, 'Question'],
112
115
  ],
package/src/inbox.js CHANGED
@@ -119,7 +119,10 @@ export function questionMenu(screen) {
119
119
  export function promptChoices(screen) {
120
120
  const text = String(screen ?? '')
121
121
  .replace(/\x1b\[(\d*)C/g, (_, n) => ' '.repeat(Math.min(Number(n || 1), 8)))
122
- .replace(/\x1b\[[0-9;]*[ABDGHJKfm]/g, '\n')
122
+ // A jump along the line is a gap, not a new line. Claude Code redraws only the cells that
123
+ // changed, so a prompt can arrive as "pro" + jump + "eed?" and "❯ 1" + jump + "Yes".
124
+ .replace(/\x1b\[\d*G/g, ' ')
125
+ .replace(/\x1b\[[0-9;]*[ABDHJKfm]/g, '\n')
123
126
  .replace(/\x1b\[[0-9;?<>=]*[ -\/]*[@-~]|\x1b\][^\x07\x1b]*(\x07|\x1b\\)/g, '')
124
127
  .replace(/\r/g, '\n');
125
128
  const lines = text.split('\n').map((l) => l.replace(/\s+/g, ' ').trim());
@@ -127,9 +130,11 @@ export function promptChoices(screen) {
127
130
  const choices = new Map();
128
131
  let question = '';
129
132
  for (let i = lines.length - 1; i >= 0; i--) {
130
- const m = /^(?:[❯>›]\s*)?(\d)[.)]\s+(.{1,80})$/.exec(lines[i]);
133
+ // The highlighted choice can lose its dot to a redraw ("❯ 1 Yes"): the pointer marks it as one.
134
+ const m = /^(?:[❯>›]\s*(\d)[.)]?|(\d)[.)])\s+(.{1,80})$/.exec(lines[i]);
131
135
  if (m) {
132
- if (!choices.has(m[1])) choices.set(m[1], m[2].trim());
136
+ const key = m[1] ?? m[2];
137
+ if (!choices.has(key)) choices.set(key, m[3].replace(/\s*·.*$/, '').trim());
133
138
  } else if (choices.size && lines[i]) {
134
139
  question = lines[i].slice(0, 200);
135
140
  break;
@@ -139,13 +144,14 @@ export function promptChoices(screen) {
139
144
  // and switch to auto mode 3. No Esc to cancel"): read the flattened screen after the last question.
140
145
  if (!choices.size) {
141
146
  const flat = lines.join(' ').replace(/\s+/g, ' ');
142
- const at = flat.search(/\?\s*(?:[❯>›]\s*)?1[.)]\s*\S[^?]*$/);
147
+ const at = flat.search(/\?\s*(?:[❯>›]\s*1[.)]?|1[.)])\s*\S[^?]*$/);
143
148
  if (at >= 0) {
144
149
  const head = flat.slice(0, at + 1);
145
150
  // Drop what's left of the box around it (╌ ─ │ and stray letters before them).
146
151
  question = (/([^.?!│]*\?)$/.exec(head)?.[1] ?? '').replace(/^.*[╌─│━]+\s*/, '').trim().slice(-200);
147
- for (const m of flat.slice(at + 1).matchAll(/(?:[❯>›]\s*)?\b(\d)[.)]\s*(.+?)(?=\s+(?:[❯>›]\s*)?\d[.)]\s|\s+Esc to cancel|\s+Enter to|$)/g)) {
148
- if (!choices.has(m[1])) choices.set(m[1], m[2].replace(/\s*·.*$/, '').trim().slice(0, 80));
152
+ for (const m of flat.slice(at + 1).matchAll(/(?:[❯>›]\s*(\d)[.)]?|\b(\d)[.)])\s*(.+?)(?=\s+(?:[❯>›]\s*)?\d[.)]\s|\s+Esc to cancel|\s+Enter to|$)/g)) {
153
+ const key = m[1] ?? m[2];
154
+ if (!choices.has(key)) choices.set(key, m[3].replace(/\s*·.*$/, '').trim().slice(0, 80));
149
155
  }
150
156
  }
151
157
  }
package/src/manager.js CHANGED
@@ -56,6 +56,8 @@ import {
56
56
  demoPagePrompt,
57
57
  benchPath,
58
58
  benchmarksPrompt,
59
+ RISKS_PROMPT,
60
+ OPTIONS_PROMPT,
59
61
  } from './brief.js';
60
62
 
61
63
  // One-off summaries / documents built from an agent's live context.
@@ -137,6 +139,7 @@ import { CONTAINER_ENGINES, claudeToken, containerName, containerRunning, engine
137
139
  import { conflictMessage, findConflicts, related, repoKey, summarize as summarizeConflicts } from './conflicts.js';
138
140
  import { answerMessage, loadQuestions, questionsPath, questionsPrompt } from './inbox.js';
139
141
  import { PROOF_FILE, proofBlock, proofFacts, proofPrompt } from './proof.js';
142
+ import { PRIVATE_MESSAGE, ideaPatch, keptPrivate, mustBeShareable } from './private.js';
140
143
  import { GroundRules, groundRulesMessage } from './groundrules.js';
141
144
  import { autonomySettings, callLadder, eligible as autonomyEligible, levelOf, modelName, parseLevel } from './autonomy.js';
142
145
  import { STUCK_DEFAULTS, detectStuck } from './stuck.js';
@@ -405,6 +408,8 @@ export class AgentManager extends EventEmitter {
405
408
  // Intent, spec and plan files that exist, with when each changed (task agents).
406
409
  ...(NO_REPO.has(agent.kind) ? {} : { specDocs: specDocsInfo(agent.id) }),
407
410
  results: this.results(agent, rt, prs),
411
+ // Why its work is not sent outside this computer (private.js), or null.
412
+ keptPrivate: keptPrivate(agent),
408
413
  priority: agent.priority ?? 2,
409
414
  activeAt: this.activeAt(agent, rt),
410
415
  projectInfo: this.projectInfo(agent),
@@ -784,6 +789,12 @@ export class AgentManager extends EventEmitter {
784
789
  ...(team ? { team } : {}),
785
790
  ...(imported ? { imported } : {}),
786
791
  };
792
+ // A project with a level of its own (autonomy.js, set from its track record): its new agents get it when none is named.
793
+ const own = plainTask && !asked ? autonomySettings(this.config).projects[projectOf(agent).name] : null;
794
+ if (own && own !== level) {
795
+ agent.autonomy = own !== 'ask' ? { level: own, log: [], seen: {} } : null;
796
+ if (acceptance === undefined || acceptance === null) agent.acceptance = (own !== 'ask' ? true : this.config.acceptance) ? { status: 'writing', wait: true, points: [] } : null;
797
+ }
787
798
  // The PR a reviewer reviews isn't its own: it stays "mentioned", so landing and the rest leave it alone.
788
799
  for (const pr of refs.prs) agent.prs[pr.url] = { ...pr, source: pr.url === agent.reviewing?.url ? 'mentioned' : 'intent' };
789
800
  for (const bug of refs.bugs) agent.bugs[bug.key] = { ...bug, source: 'intent' };
@@ -1397,6 +1408,10 @@ export class AgentManager extends EventEmitter {
1397
1408
  prompts.push(briefPrompt(path.join(dir, path.basename(briefPath(agent.id)))));
1398
1409
  // What it ran to verify, kept so it can be checked, and what it left out (proof.js).
1399
1410
  if (this.config.proof !== false) prompts.push(proofPrompt(path.join(dir, PROOF_FILE)));
1411
+ // The pre-mortem: how this could go wrong, named before it starts and marked at the end (brief.js).
1412
+ if (this.config.premortem !== false) prompts.push(RISKS_PROMPT);
1413
+ // Value and paths: more than one way is a decision, listed with what each is worth now and later (brief.js).
1414
+ if (this.config.valueLens !== false) prompts.push(OPTIONS_PROMPT);
1400
1415
  if (this.config.inbox !== false) prompts.push(questionsPrompt(path.join(dir, path.basename(questionsPath(agent.id)))));
1401
1416
  }
1402
1417
  // SPEC.md before changing code, and PLAN.md kept as it goes (unless the plan review asks for the plan).
@@ -2532,6 +2547,19 @@ export class AgentManager extends EventEmitter {
2532
2547
  return true;
2533
2548
  }
2534
2549
 
2550
+ /**
2551
+ * Keep an agent's work private, allow sharing it, or go back to what was read (private.js). The
2552
+ * person's call. When it becomes private from outside its session, the agent is told.
2553
+ */
2554
+ setPrivate(ref, { private: keep = null, note = '' } = {}) {
2555
+ const agent = this.mustGet(ref);
2556
+ const before = keptPrivate(agent);
2557
+ this.patch(agent.id, ideaPatch(agent, { private: keep, note }));
2558
+ const cur = this.store.get(agent.id);
2559
+ if (keep === true && !before && this.runtimes.get(agent.id)?.pty) this.tell(agent.id, PRIVATE_MESSAGE);
2560
+ return this.view(cur);
2561
+ }
2562
+
2535
2563
  /** Pick up changes to the agent's brief file. */
2536
2564
  reloadBrief(id) {
2537
2565
  const agent = this.store.get(id);
@@ -2557,6 +2585,9 @@ export class AgentManager extends EventEmitter {
2557
2585
  // The points were agreed (or changed) after the last score: the brief saying done again is checked against them.
2558
2586
  const reagreed = brief.status === 'done' && agent.acceptance?.status === 'agreed' && agent.docs?.scorecard?.data && agent.docs.scorecard.acceptanceAt !== agent.acceptance.agreedAt;
2559
2587
  if ((improved || reagreed || (finished && this.config.scorecard?.auto !== false && !rounds)) && !NO_REPO.has(agent.kind) && this.changesSource) this.summarize(id, 'scorecard').catch(() => {});
2588
+ // ...and read it for what it is worth and what kind of idea it is (Insights), so work that may be worth
2589
+ // protecting is noticed without anyone asking ("insights": { "auto": false } in config.json turns this off).
2590
+ if (finished && this.config.insights?.auto !== false && !NO_REPO.has(agent.kind)) this.summarize(id, 'insights').catch(() => {});
2560
2591
  }
2561
2592
  // Its points for what done means, written or revised in the spec: they wait for the person.
2562
2593
  if (this.acceptanceWaits(agent)) {
@@ -2966,7 +2997,8 @@ export class AgentManager extends EventEmitter {
2966
2997
  // The repository's standards: its bar is run here, by the app, before the model is asked.
2967
2998
  const standards = (await this.standards?.assess(agent.id, data)) ?? null;
2968
2999
  const proof = this.proof?.forScore(cur0) ?? null;
2969
- const f = scoreFacts({ files: data.files, prs: Object.values(cur0.prs ?? {}), brief: cur0.brief, plan: doc('plan'), spec: doc('spec'), standards, agreed: cur0.acceptance?.status === 'agreed' ? cur0.acceptance.points : null, proof });
3000
+ const breaks = this.mutate?.forScore(cur0, data.diffHash) ?? null;
3001
+ const f = scoreFacts({ files: data.files, prs: Object.values(cur0.prs ?? {}), brief: cur0.brief, plan: doc('plan'), spec: doc('spec'), standards, agreed: cur0.acceptance?.status === 'agreed' ? cur0.acceptance.points : null, proof, breaks });
2970
3002
  const writer = this.writerFor(agent);
2971
3003
  const prompt = scorecardPrompt({ ...ctx, briefMarkdown: this.briefFile(agent.id).markdown ?? '', intentDoc: doc('intent'), specDoc: doc('spec'), planDoc: doc('plan'), proofDoc: proof?.entries?.length ? proofBlock(proof.entries) : '', hunks, facts: f, lessons: standards?.lessons ?? [] });
2972
3004
  const sc = combine(parseJsonReply(await this.oneShot(agent, prompt, writer)), f, hunks, { lessons: standards?.lessons ?? [], bar: standards?.bar ?? null });
@@ -3112,6 +3144,7 @@ export class AgentManager extends EventEmitter {
3112
3144
  */
3113
3145
  publishToDrive(ref) {
3114
3146
  const agent = this.mustGet(ref);
3147
+ mustBeShareable(agent, 'Publishing to Google Drive');
3115
3148
  if (NO_REPO.has(agent.kind)) throw Object.assign(new Error('Only task agents have documents to publish'), { status: 400 });
3116
3149
  if (agent.drive?.pending) return this.view(agent);
3117
3150
  const docs = this.driveDocuments(agent);
@@ -3204,6 +3237,7 @@ export class AgentManager extends EventEmitter {
3204
3237
  /** The update's details as one Google Doc, through the Drive connector; its link then goes under both messages. */
3205
3238
  publishUpdate(ref) {
3206
3239
  const agent = this.mustGet(ref);
3240
+ mustBeShareable(agent, 'Publishing the update');
3207
3241
  const markdown = agent.docs?.update?.markdown;
3208
3242
  if (!markdown) throw Object.assign(new Error('Write the update first'), { status: 409 });
3209
3243
  if (agent.announce?.publishing) return this.view(agent);
@@ -3441,6 +3475,7 @@ export class AgentManager extends EventEmitter {
3441
3475
  continue;
3442
3476
  }
3443
3477
  // Idle, no prompt open, and not right after our last message (give it time to react).
3478
+ if (this.mutate?.holds(id)) continue; // its files are changed for a moment (mutate.js)
3444
3479
  if (!rt?.pty || rt.busy || rt.attention || rt.planning || t - (rt.startedAt ?? 0) < 2500 || t - (rt.toldAt ?? 0) < 8000) continue;
3445
3480
  const { text } = queue.shift();
3446
3481
  rt.toldAt = t;
@@ -3884,9 +3919,14 @@ export class AgentManager extends EventEmitter {
3884
3919
  }
3885
3920
  // Commands you keep allowing in a repo: offer to always allow them there.
3886
3921
  for (const r of this.rules.view().suggestions) items.push({ kind: 'rule', key: `rule:${r.repo}:${r.rule}`, title: `Always allow ${r.label}${r.everywhere ? ' in every repo' : ''}?`, priority: 2, ...r });
3922
+ // Work read as possibly worth protecting (private.js) that you have not decided on: keep it private, or allow sharing.
3923
+ for (const agent of this.store.list()) {
3924
+ const kept = keptPrivate(agent);
3925
+ if (kept && kept.from !== 'you') items.push({ kind: 'idea', key: `idea:${agent.id}`, agentId: agent.id, agentName: agent.name, priority: agent.priority ?? 2, title: kept.why, from: kept.from, at: agent.insights?.at ?? agent.brief?.updatedAt ?? null });
3926
+ }
3887
3927
  // Others' items (autopilot's held backlog work).
3888
3928
  for (const source of this.inboxSources) items.push(...source());
3889
- const order = { prompt: 0, limit: 1, waiting: 1, question: 1, rule: 2, review: 2, prereview: 2, autopilot: 2, stuck: 3, conflict: 4, reminder: 5, repeat: 5 };
3929
+ const order = { prompt: 0, limit: 1, waiting: 1, question: 1, rule: 2, review: 2, prereview: 2, autopilot: 2, idea: 2, stuck: 3, conflict: 4, reminder: 5, repeat: 5 };
3890
3930
  return items.sort((a, b) => order[a.kind] - order[b.kind] || a.priority - b.priority);
3891
3931
  }
3892
3932
 
package/src/mutate.js ADDED
@@ -0,0 +1,456 @@
1
+ // Test the tests: do the agent's tests notice when its code is wrong? The app takes the lines the
2
+ // agent changed, breaks one at a time in a small way (=== becomes !==, && becomes ||, a number
3
+ // goes up by one), runs the tests, and puts the line back. A break the tests fail on is caught;
4
+ // one they still pass on shows a line no test checks. Proof (proof.js) says the checks ran; this
5
+ // says whether they could have failed.
6
+ //
7
+ // It is the person's call only (an agent's own request is refused in server.js): the commands run
8
+ // here without the agent's permission prompts, and its files are changed for a moment. One line
9
+ // of one file is different at a time, never while the agent works; what was changed is written
10
+ // down first so a daemon that stops halfway puts it back when it starts again.
11
+ import fs from 'node:fs';
12
+ import path from 'node:path';
13
+ import { briefDir } from './brief.js';
14
+ import { changesThings } from './proof.js';
15
+
16
+ export const MAX_BREAKS = 8;
17
+ const JOURNAL = 'mutant.json';
18
+ const SOURCE = /\.(m?js|cjs|jsx|tsx?|py|go|rb|java|kt|rs|c|cc|cpp|h|hpp|cs|php|swift|scala)$/i;
19
+ const TEST_FILE = /(^|\/)(tests?|__tests__|spec|specs|e2e|fixtures|testdata)\/|[._-](test|spec)\.[a-z]+$|_test\.go$|Tests?\.(java|kt|cs)$|(^|\/)(test_[^/]*|conftest)\.py$/i;
20
+ const HASH_COMMENT = /\.(py|rb)$/i;
21
+ const SKIP_LINE = /^\s*(import\b|from\s+\S+\s+import\b|export\s+\*|export\s+\{[^}]*\}\s+from\b|package\b|use\b|using\b|#include\b|require\b|@|\*|\/\*|\/\/|<!--)|\brequire\(|^\s*(console|logger?|log|print|println|printf|fmt\.Print\w*|System\.out)\b/;
22
+
23
+ const clip = (s, n) => {
24
+ const t = String(s ?? '').trim();
25
+ return t.length > n ? `${t.slice(0, n - 1)}…` : t;
26
+ };
27
+ const lastLines = (s, n = 10, max = 800) => String(s ?? '').replace(/\s+$/, '').split('\n').slice(-n).join('\n').slice(-max);
28
+
29
+ /** The lines a diff adds, by file: Map path -> [{ line, text }] (line numbers in the new file). */
30
+ export function addedLines(diff) {
31
+ const out = new Map();
32
+ let file = null;
33
+ let n = 0;
34
+ for (const l of String(diff ?? '').split('\n')) {
35
+ if (l.startsWith('+++ ')) {
36
+ const p = l.slice(4).trim().replace(/^"|"$/g, '');
37
+ file = p === '/dev/null' ? null : p.replace(/^b\//, '');
38
+ continue;
39
+ }
40
+ if (l.startsWith('diff --git') || l.startsWith('--- ')) {
41
+ if (l.startsWith('diff --git')) file = null;
42
+ continue;
43
+ }
44
+ const h = /^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@/.exec(l);
45
+ if (h) {
46
+ n = Number(h[1]);
47
+ continue;
48
+ }
49
+ if (!file || !n) continue;
50
+ if (l.startsWith('+')) {
51
+ if (!out.has(file)) out.set(file, []);
52
+ out.get(file).push({ line: n, text: l.slice(1) });
53
+ n++;
54
+ } else if (l.startsWith(' ') || l === '') n++;
55
+ }
56
+ return out;
57
+ }
58
+
59
+ /** The line with what is inside strings and comments blanked out, so only code is changed. */
60
+ export function codeOf(text, file = '') {
61
+ const out = [...String(text)];
62
+ let quote = null;
63
+ for (let i = 0; i < out.length; i++) {
64
+ const c = out[i];
65
+ if (quote) {
66
+ if (c === '\\') {
67
+ out[i] = ' ';
68
+ if (i + 1 < out.length) out[++i] = ' ';
69
+ } else if (c === quote) quote = null;
70
+ else out[i] = ' ';
71
+ continue;
72
+ }
73
+ if (c === '"' || c === "'" || c === '`') quote = c;
74
+ else if ((c === '/' && out[i + 1] === '/') || (c === '#' && HASH_COMMENT.test(file)) || (c === '/' && out[i + 1] === '*')) {
75
+ for (let j = i; j < out.length; j++) out[j] = ' ';
76
+ break;
77
+ }
78
+ }
79
+ return out.join('');
80
+ }
81
+
82
+ /**
83
+ * The lines of a file that begin inside a block comment, a docstring or a string over several
84
+ * lines (their numbers, from 1): text there is not code, so a break in it would never be caught.
85
+ */
86
+ export function insideBlocks(text, file = '') {
87
+ const out = new Set();
88
+ const py = /\.py$/i.test(file);
89
+ const hash = HASH_COMMENT.test(file);
90
+ const TRIPLE = ['"""', "'''"];
91
+ let state = null; // null (code), a quote, a block comment or a triple quote
92
+ let line = 1;
93
+ const s = String(text ?? '');
94
+ for (let i = 0; i < s.length; i++) {
95
+ const c = s[i];
96
+ if (c === '\n') {
97
+ line++;
98
+ if (state === "'" || state === '"') state = null; // one-line strings end with the line
99
+ if (state) out.add(line);
100
+ continue;
101
+ }
102
+ if (state === '/*') {
103
+ if (c === '*' && s[i + 1] === '/') (state = null), i++;
104
+ } else if (TRIPLE.includes(state)) {
105
+ if (s.startsWith(state, i)) (state = null), (i += 2);
106
+ } else if (state) {
107
+ if (c === '\\') i++;
108
+ else if (c === state) state = null;
109
+ } else if (py && TRIPLE.some((t) => s.startsWith(t, i))) (state = s.slice(i, i + 3)), (i += 2);
110
+ else if (c === '/' && s[i + 1] === '*' && !py) (state = '/*'), i++;
111
+ else if ((c === '/' && s[i + 1] === '/' && !py) || (c === '#' && hash)) {
112
+ const end = s.indexOf('\n', i);
113
+ i = (end < 0 ? s.length : end) - 1;
114
+ } else if (c === '"' || c === "'" || (c === '`' && !py)) state = c;
115
+ }
116
+ return out;
117
+ }
118
+
119
+ // [what to find in the code, what it becomes, the kind]. The first on a line that fits is used,
120
+ // starting from a different rule for each line so one change gets several kinds of break.
121
+ const RULES = [
122
+ [/===/, '!==', 'equal'],
123
+ [/!==/, '===', 'equal'],
124
+ [/(?<![=!<>])==(?!=)/, '!=', 'equal'],
125
+ [/!=(?!=)/, '==', 'equal'],
126
+ [/<=/, '>', 'compare'],
127
+ [/>=/, '<', 'compare'],
128
+ [/(?<=\s)<(?=\s)/, '>=', 'compare'],
129
+ [/(?<=\s)>(?=\s)/, '<=', 'compare'],
130
+ [/&&/, '||', 'logic'],
131
+ [/\|\|/, '&&', 'logic'],
132
+ [/\band\b/, 'or', 'logic', /\.py$/i],
133
+ [/\bor\b/, 'and', 'logic', /\.py$/i],
134
+ [/\btrue\b/, 'false', 'truth'],
135
+ [/\bfalse\b/, 'true', 'truth'],
136
+ [/\bTrue\b/, 'False', 'truth'],
137
+ [/\bFalse\b/, 'True', 'truth'],
138
+ [/(?<=[\w)\]]\s)\+(?=\s)/, '-', 'arithmetic'],
139
+ [/(?<=[\w)\]]\s)-(?=\s)/, '+', 'arithmetic'],
140
+ [/\+=/, '-=', 'arithmetic'],
141
+ [/-=/, '+=', 'arithmetic'],
142
+ [/(?<![\w.])\d+(?![\w.])/, (m) => String(Number(m) + 1), 'number'],
143
+ ];
144
+ const KINDS = ['equal', 'compare', 'logic', 'truth', 'arithmetic', 'number'];
145
+
146
+ /**
147
+ * The small breaks one line allows: [{ kind, from, to, text }] (`text` is the line broken), one
148
+ * for each kind that fits. Lines that are comments, imports or logging give none.
149
+ */
150
+ export function breaksOf(text, file = '') {
151
+ if (SKIP_LINE.test(text) || text.length > 400) return [];
152
+ const code = codeOf(text, file);
153
+ const out = [];
154
+ for (const [re, to, kind, only] of RULES) {
155
+ if (only && !only.test(file)) continue;
156
+ if (out.some((b) => b.kind === kind)) continue;
157
+ const m = re.exec(code);
158
+ if (!m) continue;
159
+ const put = typeof to === 'function' ? to(m[0]) : to;
160
+ out.push({ kind, from: m[0], to: put, text: text.slice(0, m.index) + put + text.slice(m.index + m[0].length) });
161
+ }
162
+ return out;
163
+ }
164
+
165
+ /**
166
+ * Which breaks to try for a change: at most `max`, one a line, spread over the changed lines and
167
+ * over the kinds of break. `changes` is addedLines(diff); `read(file)` gives a file's text now
168
+ * (null when it is gone), so only lines that are still as the diff says are used.
169
+ */
170
+ export function pickBreaks(changes, { max = MAX_BREAKS, read = () => null } = {}) {
171
+ const lines = [];
172
+ for (const [file, added] of changes) {
173
+ if (!SOURCE.test(file) || TEST_FILE.test(file)) continue;
174
+ const now = read(file);
175
+ if (now === null) continue;
176
+ const cur = now.split('\n');
177
+ const blocks = insideBlocks(now, file);
178
+ for (const a of added) {
179
+ if (cur[a.line - 1] !== a.text || blocks.has(a.line)) continue;
180
+ const breaks = breaksOf(a.text, file);
181
+ if (breaks.length) lines.push({ file, line: a.line, before: a.text, breaks });
182
+ }
183
+ }
184
+ if (!lines.length) return [];
185
+ // Evenly through the change, then a kind for each that the ones before used least.
186
+ const step = Math.max(1, lines.length / max);
187
+ const chosen = [];
188
+ for (let i = 0; chosen.length < max && Math.floor(i) < lines.length; i += step) chosen.push(lines[Math.floor(i)]);
189
+ const used = Object.fromEntries(KINDS.map((k) => [k, 0]));
190
+ return chosen.map((l) => {
191
+ const b = [...l.breaks].sort((x, y) => used[x.kind] - used[y.kind] || KINDS.indexOf(x.kind) - KINDS.indexOf(y.kind))[0];
192
+ used[b.kind]++;
193
+ return { file: l.file, line: l.line, kind: b.kind, from: b.from, to: b.to, before: l.before, after: b.text };
194
+ });
195
+ }
196
+
197
+ /** Put a broken line back. True when the file is as it was (or the line is no longer ours). */
198
+ export function putBack(j) {
199
+ let now;
200
+ try {
201
+ now = fs.readFileSync(j.path, 'utf8');
202
+ } catch {
203
+ return true; // the file is gone: nothing of ours is left
204
+ }
205
+ if (now === j.broken) {
206
+ fs.writeFileSync(j.path, j.original);
207
+ return true;
208
+ }
209
+ if (now === j.original) return true;
210
+ // Someone changed the file meanwhile: only our line goes back.
211
+ const lines = now.split('\n');
212
+ if (lines[j.line - 1] === j.after) {
213
+ lines[j.line - 1] = j.before;
214
+ fs.writeFileSync(j.path, lines.join('\n'));
215
+ return true;
216
+ }
217
+ const at = lines.indexOf(j.after);
218
+ if (at >= 0 && lines.indexOf(j.after, at + 1) < 0 && !lines.includes(j.before)) {
219
+ lines[at] = j.before;
220
+ fs.writeFileSync(j.path, lines.join('\n'));
221
+ }
222
+ return true;
223
+ }
224
+
225
+ export const breakCounts = (breaks = []) => ({
226
+ tried: breaks.filter((b) => b.status !== 'skipped').length,
227
+ caught: breaks.filter((b) => b.status === 'caught').length,
228
+ missed: breaks.filter((b) => b.status === 'missed').length,
229
+ skipped: breaks.filter((b) => b.status === 'skipped').length,
230
+ });
231
+
232
+ /** "5 of 6 breaks caught by its tests" */
233
+ export function breaksLine(m) {
234
+ if (!m) return '';
235
+ if (m.baseline && !m.baseline.ok) return 'the tests fail before anything is changed';
236
+ const c = breakCounts(m.breaks);
237
+ if (!c.tried) return 'no line of the change could be broken in a small way';
238
+ return `${c.caught} of ${c.tried} break${c.tried === 1 ? '' : 's'} caught by its tests`;
239
+ }
240
+
241
+ /** The lines the review scorecard is given (facts the app measured). */
242
+ export function breakFacts(m) {
243
+ if (!m || m.stale) return [];
244
+ if (m.baseline && !m.baseline.ok) return [`the tests, run by the app at the person's request (${m.commands.join(' && ')}): they fail before anything is changed`];
245
+ const c = breakCounts(m.breaks);
246
+ if (!c.tried) return [];
247
+ const missed = m.breaks.filter((b) => b.status === 'missed');
248
+ return [
249
+ `the app broke ${c.tried} changed line${c.tried === 1 ? '' : 's'} one at a time and ran the tests (${m.commands.join(' && ')}): ${c.caught} caught, ${c.missed} not noticed${missed.length ? ` (${missed.map((b) => `${b.file}:${b.line} ${b.from} became ${b.to}`).join('; ')})` : ''}`,
250
+ ];
251
+ }
252
+
253
+ /** What to send the agent about the breaks its tests did not notice. */
254
+ export function breaksMessage(m) {
255
+ const missed = (m?.breaks ?? []).filter((b) => b.status === 'missed');
256
+ if (!missed.length) return null;
257
+ return [
258
+ `I broke lines of your change one at a time and ran your tests (${m.commands.join(' && ')}). They still passed with these ${missed.length === 1 ? 'break' : 'breaks'}, so nothing checks ${missed.length === 1 ? 'this line' : 'these lines'}:`,
259
+ ...missed.map((b) => `- ${b.file}:${b.line}: \`${b.from}\` became \`${b.to}\` in \`${clip(b.before, 160)}\``),
260
+ 'The lines are back as you wrote them. For each one, add or strengthen a test that fails when the line is wrong, or tell me why no test should cover it (for example the two versions behave the same). Do not change the code just to make this pass.',
261
+ ].join('\n');
262
+ }
263
+
264
+ export function breaksMarkdown(view) {
265
+ const out = [`# Test the tests: ${view.name}`, ''];
266
+ const m = view.last;
267
+ if (!m) return [...out, 'Not run yet.'].join('\n');
268
+ out.push(`Tests: \`${m.commands.join(' && ')}\``, '');
269
+ if (!m.baseline.ok) return [...out, `The tests fail before anything is changed (exit ${m.baseline.code ?? 'none (stopped)'}):`, '', '```', m.baseline.tail ?? '', '```'].join('\n');
270
+ const mark = { caught: '✅ caught', missed: '❌ not noticed', skipped: '➖ not tried' };
271
+ for (const b of m.breaks) out.push(`- ${mark[b.status]} · ${b.file}:${b.line} · \`${b.from}\` became \`${b.to}\`${b.status === 'caught' && b.stopped ? ' (the tests did not finish)' : ''}${b.status === 'skipped' ? ` (${b.why})` : ''}`, ` \`${clip(b.before, 160)}\``);
272
+ if (!m.breaks.length) out.push('No line of the change could be broken in a small way.');
273
+ out.push('', breaksLine(m) + (m.stale ? ' (before the latest changes)' : ''));
274
+ if (m.restored === false) out.push('', 'The folder is not as it was before the run: look at its changes.');
275
+ return out.join('\n');
276
+ }
277
+
278
+ export class Mutate {
279
+ /**
280
+ * `run(command, { cwd, timeoutMs })` resolves { ok, code, ms, tail } (standards.js runCheck);
281
+ * `changes(id)` gives the agent's changes ({ diff, diffHash }, the review screen's).
282
+ */
283
+ constructor({ manager, store, run, changes, config = {}, log = () => {}, dir = briefDir }) {
284
+ Object.assign(this, { manager, store, run, changes, log });
285
+ // Where the line being broken is written down, so a stop halfway can be undone.
286
+ this.journal = (agentId) => path.join(dir(agentId), JOURNAL);
287
+ this.max = config.max ?? MAX_BREAKS;
288
+ this.timeoutMs = config.timeoutMs ?? 300_000;
289
+ this.budgetMs = config.budgetMs ?? 900_000;
290
+ this.running = new Map(); // agentId -> the run in progress
291
+ }
292
+
293
+ /** After a daemon that stopped halfway: put back the line it had broken. */
294
+ recover() {
295
+ for (const a of this.store.list()) {
296
+ const file = this.journal(a.id);
297
+ let j;
298
+ try {
299
+ j = JSON.parse(fs.readFileSync(file, 'utf8'));
300
+ } catch {
301
+ continue;
302
+ }
303
+ try {
304
+ putBack(j);
305
+ this.log(`test the tests: ${a.name}: put back ${j.path}:${j.line} after a stop`);
306
+ } catch (e) {
307
+ this.log(`test the tests: ${a.name}: could not put back ${j.path}:${j.line}: ${e.message}`);
308
+ continue;
309
+ }
310
+ fs.rmSync(file, { force: true });
311
+ }
312
+ }
313
+
314
+ /** True while an agent's files are being changed by a run: nothing is sent to it meanwhile. */
315
+ holds(agentId) {
316
+ return this.running.has(agentId);
317
+ }
318
+
319
+ /** The commands that test: the one given, or the ones the agent recorded that passed and only look. */
320
+ commandsFor(agent, command) {
321
+ const given = String(command ?? '').trim();
322
+ if (given) return [given.slice(0, 500)];
323
+ const seen = new Set();
324
+ return (this.manager.proof?.read(agent.id) ?? [])
325
+ .filter((e) => e.command && (e.exit ?? 0) === 0 && !changesThings(e.command) && !seen.has(e.command) && seen.add(e.command))
326
+ .map((e) => e.command)
327
+ .slice(0, 3);
328
+ }
329
+
330
+ cannotRun(agent) {
331
+ if (agent.container) return 'It works in a container: its tests are not run on this computer.';
332
+ if (!agent.workdir || !fs.existsSync(agent.workdir)) return "The agent's folder is not on this computer.";
333
+ return null;
334
+ }
335
+
336
+ /** Not while it works: its files are changed for a moment. Asked at the start of a run. */
337
+ working(agent) {
338
+ return this.manager.runtimes?.get(agent.id)?.busy ? 'The agent is working. Its files are changed for a moment during this, so wait until it stops and ask again.' : null;
339
+ }
340
+
341
+ async view(ref) {
342
+ const agent = this.manager.mustGet(ref);
343
+ const last = agent.breaks ?? null;
344
+ let stale = false;
345
+ if (last && !this.running.has(agent.id)) stale = ((await this.changes(agent.id).catch(() => null))?.diffHash ?? null) !== last.diffHash;
346
+ const commands = this.commandsFor(agent);
347
+ return {
348
+ id: agent.id,
349
+ name: agent.name,
350
+ commands,
351
+ last: last ? { ...last, stale, ...breakCounts(last.breaks) } : null,
352
+ line: last ? breaksLine(last) : '',
353
+ running: this.running.has(agent.id),
354
+ canRun: this.cannotRun(agent) === null,
355
+ whyNot: this.cannotRun(agent),
356
+ max: this.max,
357
+ };
358
+ }
359
+
360
+ /** For the scorecard: the last run, marked stale when the changes are no longer the ones it broke. */
361
+ forScore(agent, diffHash) {
362
+ return agent.breaks ? { ...agent.breaks, stale: agent.breaks.diffHash !== diffHash } : null;
363
+ }
364
+
365
+ async tests(agent, commands, timeoutMs) {
366
+ const started = Date.now();
367
+ for (const command of commands) {
368
+ const r = await this.run(command, { cwd: agent.workdir, timeoutMs });
369
+ if (!r.ok) return { ok: false, command, code: r.code, ms: Date.now() - started, tail: lastLines(r.tail) };
370
+ }
371
+ return { ok: true, ms: Date.now() - started };
372
+ }
373
+
374
+ async run_(agent, commands, max) {
375
+ const before = await this.changes(agent.id);
376
+ const read = (file) => {
377
+ try {
378
+ return fs.readFileSync(path.join(agent.workdir, file), 'utf8');
379
+ } catch {
380
+ return null;
381
+ }
382
+ };
383
+ const out = { at: null, commands, diffHash: before.diffHash, baseline: null, breaks: [], restored: true };
384
+ this.log(`test the tests: ${agent.name}: ${commands.join(' && ')}`);
385
+ out.baseline = await this.tests(agent, commands, this.timeoutMs);
386
+ if (out.baseline.ok) {
387
+ const picked = pickBreaks(addedLines(before.diff), { max, read });
388
+ // A break that hangs the tests is caught; it need not take the full time to say so.
389
+ const each = Math.min(this.timeoutMs, Math.max(20_000, out.baseline.ms * 4));
390
+ const started = Date.now();
391
+ const until = started + this.budgetMs;
392
+ for (const b of picked) {
393
+ const file = path.join(agent.workdir, b.file);
394
+ const original = read(b.file);
395
+ const lines = original?.split('\n');
396
+ const why =
397
+ Date.now() > until ? 'the time for a run was used up' : (this.manager.inputAt?.get(agent.id) ?? 0) > started ? 'you typed to the agent, so the run stopped' : !lines || lines[b.line - 1] !== b.before ? 'the line changed meanwhile' : null;
398
+ if (why) {
399
+ out.breaks.push({ ...b, status: 'skipped', why });
400
+ continue;
401
+ }
402
+ lines[b.line - 1] = b.after;
403
+ const j = { path: file, line: b.line, before: b.before, after: b.after, original, broken: lines.join('\n') };
404
+ fs.mkdirSync(path.dirname(this.journal(agent.id)), { recursive: true });
405
+ fs.writeFileSync(this.journal(agent.id), JSON.stringify(j));
406
+ let r;
407
+ try {
408
+ fs.writeFileSync(file, j.broken);
409
+ r = await this.tests(agent, commands, each);
410
+ } finally {
411
+ putBack(j);
412
+ fs.rmSync(this.journal(agent.id), { force: true });
413
+ }
414
+ out.breaks.push({ ...b, status: r.ok ? 'missed' : 'caught', ms: r.ms, ...(r.ok ? {} : { by: r.command, code: r.code, stopped: r.code === null, tail: lastLines(r.tail, 6, 500) }) });
415
+ }
416
+ // The folder as it was: the same changes as before the run.
417
+ const after = await this.changes(agent.id).catch(() => null);
418
+ // (Typing to the agent meanwhile changes them for its own reasons.)
419
+ out.restored = !after || after.diffHash === before.diffHash || (this.manager.inputAt?.get(agent.id) ?? 0) > started;
420
+ }
421
+ out.at = new Date().toISOString();
422
+ return out;
423
+ }
424
+
425
+ /** Break the changed lines one at a time and run the tests. The person's call. */
426
+ async start(ref, { command, max } = {}) {
427
+ const agent = this.manager.mustGet(ref);
428
+ const bad = (msg) => Object.assign(new Error(msg), { status: 400 });
429
+ if (!this.running.has(agent.id)) {
430
+ const no = this.cannotRun(agent) ?? this.working(agent);
431
+ if (no) throw bad(no);
432
+ const commands = this.commandsFor(agent, command);
433
+ if (!commands.length) throw bad('No test command: the agent recorded none that passed. Give the command that runs the tests.');
434
+ const n = Math.max(1, Math.min(30, Number(max) || this.max));
435
+ const p = this.run_(agent, commands, n)
436
+ .then((breaks) => {
437
+ if (this.store.get(agent.id)) this.manager.patch(agent.id, { breaks });
438
+ })
439
+ .finally(() => this.running.delete(agent.id));
440
+ this.running.set(agent.id, p);
441
+ this.manager.changed?.(agent);
442
+ }
443
+ await this.running.get(agent.id);
444
+ return this.view(agent.id);
445
+ }
446
+
447
+ /** Tell the agent which breaks its tests did not notice. */
448
+ async send(ref) {
449
+ const agent = this.manager.mustGet(ref);
450
+ const text = breaksMessage(agent.breaks);
451
+ if (!text) throw Object.assign(new Error('Nothing to send: no break went unnoticed'), { status: 400 });
452
+ this.manager.tell(agent.id, text);
453
+ this.manager.patch(agent.id, { breaks: { ...agent.breaks, sentAt: new Date().toISOString() } });
454
+ return this.view(agent.id);
455
+ }
456
+ }