ai-agentmanager 1.64.0 → 1.65.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
@@ -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);
@@ -2966,7 +2994,8 @@ export class AgentManager extends EventEmitter {
2966
2994
  // The repository's standards: its bar is run here, by the app, before the model is asked.
2967
2995
  const standards = (await this.standards?.assess(agent.id, data)) ?? null;
2968
2996
  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 });
2997
+ const breaks = this.mutate?.forScore(cur0, data.diffHash) ?? null;
2998
+ 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
2999
  const writer = this.writerFor(agent);
2971
3000
  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
3001
  const sc = combine(parseJsonReply(await this.oneShot(agent, prompt, writer)), f, hunks, { lessons: standards?.lessons ?? [], bar: standards?.bar ?? null });
@@ -3112,6 +3141,7 @@ export class AgentManager extends EventEmitter {
3112
3141
  */
3113
3142
  publishToDrive(ref) {
3114
3143
  const agent = this.mustGet(ref);
3144
+ mustBeShareable(agent, 'Publishing to Google Drive');
3115
3145
  if (NO_REPO.has(agent.kind)) throw Object.assign(new Error('Only task agents have documents to publish'), { status: 400 });
3116
3146
  if (agent.drive?.pending) return this.view(agent);
3117
3147
  const docs = this.driveDocuments(agent);
@@ -3204,6 +3234,7 @@ export class AgentManager extends EventEmitter {
3204
3234
  /** The update's details as one Google Doc, through the Drive connector; its link then goes under both messages. */
3205
3235
  publishUpdate(ref) {
3206
3236
  const agent = this.mustGet(ref);
3237
+ mustBeShareable(agent, 'Publishing the update');
3207
3238
  const markdown = agent.docs?.update?.markdown;
3208
3239
  if (!markdown) throw Object.assign(new Error('Write the update first'), { status: 409 });
3209
3240
  if (agent.announce?.publishing) return this.view(agent);
@@ -3441,6 +3472,7 @@ export class AgentManager extends EventEmitter {
3441
3472
  continue;
3442
3473
  }
3443
3474
  // Idle, no prompt open, and not right after our last message (give it time to react).
3475
+ if (this.mutate?.holds(id)) continue; // its files are changed for a moment (mutate.js)
3444
3476
  if (!rt?.pty || rt.busy || rt.attention || rt.planning || t - (rt.startedAt ?? 0) < 2500 || t - (rt.toldAt ?? 0) < 8000) continue;
3445
3477
  const { text } = queue.shift();
3446
3478
  rt.toldAt = t;
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
+ }
package/src/private.js ADDED
@@ -0,0 +1,52 @@
1
+ // Kept private: work that may be patentable is not published by the app until the person says so.
2
+ // Publishing before filing can cost the right to a patent, so once part of an agent's work is
3
+ // read as possibly new (the agent says so in its brief, Insights reads it as possibly patentable,
4
+ // or the person marks it), everything that sends it outside this computer is held: Google Drive,
5
+ // updates and Slack, comments on the pull request, and opening the pull request itself. Only the
6
+ // person lifts it (an agent's own call is refused in server.js). It is a guard on what the app
7
+ // sends, not on what the agent can do in its terminal: the agent is told as well.
8
+ import { parseKind } from '../public/valuelens.js';
9
+
10
+ const clip = (s, n) => {
11
+ const t = String(s ?? '').replace(/\s+/g, ' ').trim();
12
+ return t.length > n ? `${t.slice(0, n - 1)}…` : t;
13
+ };
14
+
15
+ /** Insights' "### Kind" section of an agent, parsed, or null. */
16
+ export function insightsKind(agent) {
17
+ const part = String(agent?.insights?.markdown ?? '').split(/^###\s+/m).find((p) => /^kind\b/i.test(p));
18
+ return part ? parseKind(part.split('\n').slice(1).join('\n')) : null;
19
+ }
20
+
21
+ /**
22
+ * Why an agent's work is kept private: { why, from: 'you' | 'agent' | 'insights' }, or null when
23
+ * it is not (nothing was read as new, or the person allowed sharing).
24
+ */
25
+ export function keptPrivate(agent) {
26
+ const st = agent?.idea ?? {};
27
+ if (st.allowed) return null;
28
+ if (st.private) return { from: 'you', why: st.note ? `You marked it private: ${clip(st.note, 200)}` : 'You marked it private' };
29
+ const fresh = agent?.brief?.options?.new;
30
+ if (fresh) return { from: 'agent', why: `The agent says part of its design may be new: ${clip(fresh, 200)}` };
31
+ const kind = insightsKind(agent);
32
+ if (kind?.kind === 'patent') return { from: 'insights', why: `Insights reads it as possibly patentable${kind.new ? `: ${clip(kind.new, 200)}` : ''}` };
33
+ return null;
34
+ }
35
+
36
+ /** Refuse a step that sends an agent's work outside this computer while it is kept private. */
37
+ export function mustBeShareable(agent, what) {
38
+ const kept = keptPrivate(agent);
39
+ if (kept) throw Object.assign(new Error(`${what} is held: this work is kept private. ${kept.why}. Publishing before filing can cost the right to a patent. To share it anyway: agentmgr private ${agent.id} --allow`), { status: 409, keptPrivate: true });
40
+ }
41
+
42
+ /** What the agent is told when its work is marked private from outside its session. */
43
+ export const PRIVATE_MESSAGE =
44
+ 'Part of this work may be new enough to protect, so it is kept private for now. Until I say otherwise: do not publish any of it outside this ' +
45
+ 'repository. No design doc or artifact published, no Google Doc, no public gist, post, issue or package, and do not open or update a pull request. ' +
46
+ 'Keep working locally and keep your documents as files.';
47
+
48
+ /** The person's own word: `private` true keeps it private, false allows sharing, null goes back to what was read. */
49
+ export function ideaPatch(agent, { private: keep = null, note = '' } = {}) {
50
+ if (keep === null) return { idea: agent?.idea?.toldAt ? { toldAt: agent.idea.toldAt } : null };
51
+ return { idea: keep ? { private: true, note: clip(note, 300), at: new Date().toISOString() } : { allowed: true, note: clip(note, 300), at: new Date().toISOString() } };
52
+ }
package/src/quality.js CHANGED
@@ -10,6 +10,7 @@ import { PERIODS } from './value.js';
10
10
  import { repoOf } from './landing.js';
11
11
  import { ghBin } from './tracker.js';
12
12
  import { run } from './git.js';
13
+ import { saidOf, trackRecord } from './record.js';
13
14
 
14
15
  const HOUR = 3_600_000;
15
16
  const DAY = 24 * HOUR;
@@ -265,9 +266,14 @@ export class Quality {
265
266
  mergedAt: new Date(p.mergedAt).toISOString(),
266
267
  };
267
268
  if (!cur) {
268
- st.items[p.url] = { ...fields, facts: null, after: null, addedAt: new Date(t).toISOString() };
269
+ // What is said about the work as it merges (record.js): compared later with what held.
270
+ st.items[p.url] = { ...fields, facts: null, after: null, said: saidOf(a), addedAt: new Date(t).toISOString() };
269
271
  added++;
270
- } else Object.assign(cur, fields);
272
+ } else {
273
+ Object.assign(cur, fields);
274
+ // One merged before this was kept: what is said now, marked as read late.
275
+ if (!cur.said) (cur.said = { ...saidOf(a), late: true }), added++;
276
+ }
271
277
  }
272
278
  }
273
279
  if (added) this.store.save();
@@ -358,6 +364,14 @@ export class Quality {
358
364
  return { settings: s, period, periods: aggregate(all, s, { period, t }), items: all.map((it) => this.itemView(it, t)), github: !process.env.AGENTMGR_NO_GH };
359
365
  }
360
366
 
367
+ /** The track record (record.js): what was said at the merge against what held, and the level each project's record supports. */
368
+ record(t = Date.now()) {
369
+ this.scan(t);
370
+ const s = this.settings;
371
+ const au = this.config.autonomy ?? {};
372
+ return trackRecord(Object.values(this.state.items), (it) => verdictOf(it, s, t), { levels: { default: au.level ?? 'ask', projects: au.projects ?? {} } });
373
+ }
374
+
361
375
  /** A period's report: the latest complete one of a kind, or the current one so far. */
362
376
  async report(kind = 'week', { current = false, t = Date.now() } = {}) {
363
377
  if (!PERIODS[kind]) throw err(400, `kind is one of ${Object.keys(PERIODS).join(', ')}`);