ai-agentmanager 1.63.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/proof.js ADDED
@@ -0,0 +1,255 @@
1
+ // Proof: what the agent ran to verify its work, kept so it can be checked. Next to its brief the
2
+ // agent keeps PROOF.md: for each check it ticked (or each agreed point of what done means), the
3
+ // exact command, its exit code and the last lines of real output. The app shows it, gives it to
4
+ // the review scorecard as the agent's own record, and, when the person asks, runs the commands
5
+ // again in the agent's folder and says which gave the same result.
6
+ //
7
+ // Running them again is the person's call only (an agent's own request is refused in server.js):
8
+ // the commands were written by the agent, and here they run without its permission prompts. A
9
+ // command that changes things (deleting, committing, pushing, publishing, installing) is not run.
10
+ import fs from 'node:fs';
11
+ import path from 'node:path';
12
+ import { briefDir } from './brief.js';
13
+
14
+ export const PROOF_FILE = 'PROOF.md';
15
+ export const proofPath = (agentId) => path.join(briefDir(agentId), PROOF_FILE);
16
+ export const MAX_ENTRIES = 30;
17
+ export const MAX_RERUN = 12;
18
+ const RERUN_TIMEOUT_MS = 120_000;
19
+
20
+ export const proofPrompt = (file) =>
21
+ `Keep the proof of your checks in ${file} (Markdown), next to the brief, so the user can verify them without ` +
22
+ 'taking your word. One section for each check you tick as passed, and for each agreed acceptance point:\n' +
23
+ '## <the check, starting with the acceptance point id when there is one, e.g. "A2 output is plain text">\n' +
24
+ 'Command: <the exact command you ran, on one line, runnable from the repository root; "none" when you verified by reading>\n' +
25
+ 'Exit: <its exit code>\n' +
26
+ 'then a fenced code block with the last lines of its real output (15 at most), or one line on what you read when there was no command.\n' +
27
+ 'Record only commands you really ran, with the output you really got: never write output from memory or as you expect it to be. ' +
28
+ 'Prefer commands that only look (tests, a build, a run of the program): the user may run them again. ' +
29
+ 'Update a section when you run its check again. The file is outside the repository: never commit it.\n' +
30
+ 'In the Results section of the brief, also list what you did not do: one "- Not done: ..." line for each thing the request asked or ' +
31
+ 'clearly implied that you skipped, stubbed, left untested or only assumed, and "- Not done: nothing" when there is none.';
32
+
33
+ const clip = (s, n) => {
34
+ const t = String(s ?? '').trim();
35
+ return t.length > n ? `${t.slice(0, n - 1)}…` : t;
36
+ };
37
+ const lastLines = (s, n = 15, max = 1500) => String(s ?? '').replace(/\s+$/, '').split('\n').slice(-n).join('\n').slice(-max);
38
+
39
+ /**
40
+ * PROOF.md as entries: [{ title, point, command, exit, output, note }]. `point` is the agreed
41
+ * acceptance point a title starts with ("A2"), `command` null when it was verified by reading.
42
+ */
43
+ export function parseProof(markdown) {
44
+ const parts = String(markdown ?? '').split(/^##\s+(.+?)\s*#*\s*$/m);
45
+ const out = [];
46
+ for (let i = 1; i < parts.length && out.length < MAX_ENTRIES; i += 2) {
47
+ const title = clip(parts[i].replace(/[*_`]/g, ''), 200);
48
+ const body = parts[i + 1] ?? '';
49
+ if (!title) continue;
50
+ const fence = /```[^\n]*\n([\s\S]*?)```/.exec(body);
51
+ const rest = fence ? body.replace(fence[0], '') : body;
52
+ const field = (name) => new RegExp(`^\\s*[-*]?\\s*\\**${name}\\**\\s*:\\s*\\**\\s*(.*)$`, 'im').exec(rest)?.[1]?.trim() ?? '';
53
+ const raw = field('command').replace(/^`+|`+$/g, '').trim();
54
+ const command = raw && !/^(none|n\/a|-|—)\b/i.test(raw) ? raw.slice(0, 500) : null;
55
+ const code = /^-?\d+/.exec(field('exit'))?.[0];
56
+ const note = rest
57
+ .split('\n')
58
+ .filter((l) => l.trim() && !/^\s*[-*]?\s*\**(command|exit)\**\s*:/i.test(l))
59
+ .join(' ')
60
+ .trim();
61
+ out.push({ title, point: /^(A\d+)\b/i.exec(title)?.[1].toUpperCase() ?? null, command, exit: code === undefined ? null : Number(code), output: lastLines(fence?.[1] ?? ''), note: clip(note, 300) });
62
+ }
63
+ return out;
64
+ }
65
+
66
+ const CHANGES = [
67
+ [/(^|[;&|(]\s*)(sudo|doas)\b/, 'it runs as administrator'],
68
+ [/(^|[;&|(]\s*)(rm|rmdir|mv|dd|chmod|chown|kill|pkill|killall|truncate|shred)\b/, 'it deletes, moves or stops things'],
69
+ [/\bgit\s+(?:-\S+\s+)*(push|commit|reset|clean|checkout|switch|restore|rebase|merge|tag|stash|rm|mv|apply|am|cherry-pick|revert|pull|fetch|gc|branch\s+-[dDmM])\b/, 'it changes the repository'],
70
+ [/\bgh\s+\w+\s+(create|merge|close|delete|edit|comment|review|reopen|ready)\b|\bgh\s+release\b|\bgh\s+api\b.*(-X|--method)/i, 'it changes things on GitHub'],
71
+ [/\b(npm|pnpm|yarn|bun)\s+(publish|install|i|add|remove|uninstall|update|upgrade|link|login|ci)\b|\b(pip3?|uv|poetry|cargo|gem|brew|apt|apt-get|go)\s+(install|add|remove|uninstall|publish|upgrade|get)\b/, 'it installs or publishes'],
72
+ [/\b(deploy|kubectl|helm|terraform|pulumi|ansible|docker\s+(push|rm|rmi|run|compose|kill|stop)|vercel|netlify|fly|railway|heroku|aws|gcloud|az)\b/, 'it deploys or reaches a service'],
73
+ [/\b(curl|wget|nc|ssh|scp|rsync|ftp)\b/, 'it reaches the network'],
74
+ [/(^|[^0-9&>])>{1,2}(?!\s*(\/dev\/null|&\d))/, 'it writes to a file'],
75
+ [/\b(drop|truncate)\s+(table|database)\b|\bdelete\s+from\b/i, 'it changes data'],
76
+ [/\$\(|`/, 'it runs a command inside the command'],
77
+ ];
78
+
79
+ /** Why a recorded command is not run again by the app (a short phrase), or null when it only looks. */
80
+ export function changesThings(command) {
81
+ const c = String(command ?? '');
82
+ return CHANGES.find(([re]) => re.test(c))?.[1] ?? null;
83
+ }
84
+
85
+ const squash = (s) => String(s ?? '').replace(/\s+/g, ' ').trim();
86
+
87
+ /**
88
+ * A run by the app against what the agent recorded: "same" when the exit code is the one it wrote
89
+ * (or success when it wrote none), "differs" otherwise. `output` says whether the last line it
90
+ * recorded was printed again (durations and dates make output differ without anything being wrong).
91
+ */
92
+ export function compareRun(entry, run) {
93
+ const want = entry.exit ?? 0;
94
+ const last = squash(entry.output.split('\n').filter((l) => l.trim()).at(-1));
95
+ return {
96
+ status: run.code === want ? 'same' : 'differs',
97
+ output: !last ? null : squash(run.tail).includes(last) ? 'same' : 'differs',
98
+ };
99
+ }
100
+
101
+ /** Counts for the agent's view: { entries, commands, points }. */
102
+ export const proofCounts = (entries) => ({ entries: entries.length, commands: entries.filter((e) => e.command).length, points: entries.filter((e) => e.point).length });
103
+
104
+ /** "3 of 4 checks with a recorded run" for a brief with `passed` ticked checks. */
105
+ export function proofLine(doc, passed = 0) {
106
+ if (!doc?.entries) return passed ? `none recorded for ${passed} passed check${passed === 1 ? '' : 's'}` : 'none recorded';
107
+ return `${doc.commands} recorded run${doc.commands === 1 ? '' : 's'}${doc.entries > doc.commands ? `, ${doc.entries - doc.commands} by reading` : ''}`;
108
+ }
109
+
110
+ /** The lines the review scorecard is given (facts the app measured). */
111
+ export function proofFacts(doc, rerun) {
112
+ if (!doc?.entries) return ["the agent's proof of its checks: none recorded"];
113
+ const lines = [`the agent's proof of its checks (its own record, not run by the app): ${doc.commands} with a command and output, ${doc.entries - doc.commands} verified by reading`];
114
+ if (rerun?.results?.length && !rerun.stale) {
115
+ const same = rerun.results.filter((r) => r.status === 'same').length;
116
+ const differs = rerun.results.filter((r) => r.status === 'differs');
117
+ const skipped = rerun.results.filter((r) => r.status === 'skipped').length;
118
+ lines.push(
119
+ `those commands run again by the app, at the person's request: ${same} gave the recorded exit code, ${differs.length} did not${differs.length ? ` (${differs.map((r) => r.title).join('; ')})` : ''}${skipped ? `, ${skipped} not run (they change things)` : ''}`,
120
+ );
121
+ }
122
+ return lines;
123
+ }
124
+
125
+ /** PROOF.md for the scorecard prompt, cut to size. */
126
+ export function proofBlock(entries, max = 6000) {
127
+ const out = [];
128
+ let used = 0;
129
+ for (const e of entries) {
130
+ const text = [`## ${e.title}`, `Command: ${e.command ?? 'none (verified by reading)'}`, e.exit === null ? '' : `Exit: ${e.exit}`, e.output ? lastLines(e.output, 8, 600) : e.note].filter(Boolean).join('\n');
131
+ if (used + text.length > max) {
132
+ out.push(`(${entries.length - out.length} more not shown)`);
133
+ break;
134
+ }
135
+ used += text.length;
136
+ out.push(text);
137
+ }
138
+ return out.join('\n\n');
139
+ }
140
+
141
+ export function proofMarkdown(view) {
142
+ const out = [`# Proof: ${view.name}`, ''];
143
+ if (!view.entries.length) return [...out, 'The agent recorded no proof of its checks.'].join('\n');
144
+ const mark = { same: '✅ same result when run again', differs: '❌ a different result when run again', skipped: '➖ not run again' };
145
+ for (const e of view.entries) {
146
+ out.push(`## ${e.title}`, '', e.command ? `Command: \`${e.command}\`${e.exit === null ? '' : ` (exit ${e.exit})`}` : `Verified by reading${e.note ? `: ${e.note}` : ''}`);
147
+ if (e.output) out.push('', '```', e.output, '```');
148
+ if (e.rerun) out.push('', `${mark[e.rerun.status]}${e.rerun.status === 'differs' ? `: exit ${e.rerun.code ?? 'none (stopped)'}` : e.rerun.status === 'skipped' ? `: ${e.rerun.why}` : ''}`);
149
+ out.push('');
150
+ }
151
+ return out.join('\n');
152
+ }
153
+
154
+ export class Proof {
155
+ /** `run(command, { cwd, timeoutMs })` resolves { ok, code, ms, tail } (standards.js runCheck). */
156
+ constructor({ manager, store, run, log = () => {}, timeoutMs = RERUN_TIMEOUT_MS }) {
157
+ Object.assign(this, { manager, store, run, log, timeoutMs });
158
+ this.running = new Map(); // agentId -> the run in progress
159
+ }
160
+
161
+ read(agentId) {
162
+ try {
163
+ return parseProof(fs.readFileSync(proofPath(agentId), 'utf8'));
164
+ } catch {
165
+ return [];
166
+ }
167
+ }
168
+
169
+ /** Pick up changes to PROOF.md: the counts go on the agent (for the list and the results card). */
170
+ reload(agentId) {
171
+ const agent = this.store.get(agentId);
172
+ if (!agent) return;
173
+ let st;
174
+ try {
175
+ st = fs.statSync(proofPath(agentId));
176
+ } catch {
177
+ return;
178
+ }
179
+ if (agent.proofDoc?.mtimeMs === st.mtimeMs) return;
180
+ this.manager.patch(agentId, { proofDoc: { ...proofCounts(this.read(agentId)), mtimeMs: st.mtimeMs, updatedAt: st.mtime.toISOString() } });
181
+ }
182
+
183
+ /** What an agent recorded, with the last run by the app beside each entry. */
184
+ view(ref) {
185
+ const agent = this.manager.mustGet(ref);
186
+ const entries = this.read(agent.id);
187
+ const rerun = agent.proof ?? null;
188
+ // A run made before the agent changed its proof no longer speaks for it.
189
+ const stale = Boolean(rerun) && rerun.proofAt !== (agent.proofDoc?.updatedAt ?? null);
190
+ const by = new Map((stale ? [] : rerun?.results ?? []).map((r) => [`${r.title}\n${r.command}`, r]));
191
+ return {
192
+ id: agent.id,
193
+ name: agent.name,
194
+ entries: entries.map((e) => ({ ...e, runnable: e.command ? !changesThings(e.command) : false, why: e.command ? changesThings(e.command) : null, rerun: by.get(`${e.title}\n${e.command}`) ?? null })),
195
+ counts: proofCounts(entries),
196
+ passed: (agent.brief?.checks ?? []).filter((c) => c.state === 'passed').length,
197
+ notDone: agent.brief?.results?.notDone ?? [],
198
+ rerun: rerun ? { at: rerun.at, stale, same: rerun.results.filter((r) => r.status === 'same').length, differs: rerun.results.filter((r) => r.status === 'differs').length, skipped: rerun.results.filter((r) => r.status === 'skipped').length } : null,
199
+ running: this.running.has(agent.id),
200
+ canRun: this.cannotRun(agent) === null,
201
+ whyNot: this.cannotRun(agent),
202
+ };
203
+ }
204
+
205
+ cannotRun(agent) {
206
+ if (agent.container) return 'It works in a container: its commands are not run on this computer.';
207
+ if (!agent.workdir || !fs.existsSync(agent.workdir)) return "The agent's folder is not on this computer.";
208
+ return null;
209
+ }
210
+
211
+ /** For the scorecard: the counts, the entries and the last run, or null when nothing is recorded. */
212
+ forScore(agent) {
213
+ const entries = this.read(agent.id);
214
+ const rerun = agent.proof ? { ...agent.proof, stale: agent.proof.proofAt !== (agent.proofDoc?.updatedAt ?? null) } : null;
215
+ return { doc: proofCounts(entries), entries, rerun };
216
+ }
217
+
218
+ /** Run the recorded commands again, one after the other, in the agent's folder. The person's call. */
219
+ async run_(agent) {
220
+ const entries = this.read(agent.id).filter((e) => e.command);
221
+ const results = [];
222
+ let ran = 0;
223
+ for (const e of entries) {
224
+ const why = changesThings(e.command) ?? (ran >= MAX_RERUN ? `only the first ${MAX_RERUN} are run` : null);
225
+ if (why) {
226
+ results.push({ title: e.title, command: e.command, status: 'skipped', why });
227
+ continue;
228
+ }
229
+ ran++;
230
+ this.log(`proof: ${agent.name}: ${e.command}`);
231
+ const r = await this.run(e.command, { cwd: agent.workdir, timeoutMs: this.timeoutMs });
232
+ results.push({ title: e.title, command: e.command, code: r.code, ms: r.ms, tail: lastLines(r.tail, 12, 1000), ...compareRun(e, r) });
233
+ }
234
+ return results;
235
+ }
236
+
237
+ async rerun(ref) {
238
+ const agent = this.manager.mustGet(ref);
239
+ const no = this.cannotRun(agent);
240
+ if (no) throw Object.assign(new Error(no), { status: 400 });
241
+ if (!this.read(agent.id).some((e) => e.command)) throw Object.assign(new Error('The agent recorded no commands to run again'), { status: 400 });
242
+ if (!this.running.has(agent.id)) {
243
+ const proofAt = agent.proofDoc?.updatedAt ?? null;
244
+ const p = this.run_(agent)
245
+ .then((results) => {
246
+ if (this.store.get(agent.id)) this.manager.patch(agent.id, { proof: { at: new Date().toISOString(), proofAt, results } });
247
+ })
248
+ .finally(() => this.running.delete(agent.id));
249
+ this.running.set(agent.id, p);
250
+ this.manager.changed?.(agent);
251
+ }
252
+ await this.running.get(agent.id);
253
+ return this.view(agent.id);
254
+ }
255
+ }
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(', ')}`);
package/src/record.js ADDED
@@ -0,0 +1,147 @@
1
+ // Track record: was the confidence right? Quality (quality.js) knows what happened to each merged
2
+ // pull request: held up, or reverted, fixed afterwards, failed checks. This keeps, for each one,
3
+ // what was said about it when it merged (the agent's own confidence, the review scorecard, whether
4
+ // its tests were tested, the model, how far it ran without the person) and compares the two:
5
+ // "said 85% on average, 6 of 10 held up". Per project it also says what level of "Without you"
6
+ // the record supports. The level stays the person's to set; this only suggests. No model is called.
7
+
8
+ export const MIN_TO_SAY = 5; // fewer settled pull requests than this say nothing
9
+ const LEVELS = ['ask', 'run', 'pr', 'merge'];
10
+ const LEVEL_LABEL = { ask: 'Ask me', run: 'Agree, then run', pr: 'Run to pull request', merge: 'Run to merge' };
11
+ const PROBLEMS = new Set(['reverted', 'fixed', 'broke', 'problem']);
12
+ const round = (n) => (Number.isFinite(n) ? Math.round(n) : null);
13
+
14
+ /** What is said about an agent's work now, kept when its pull request merges. */
15
+ export function saidOf(agent, { engine = null } = {}) {
16
+ const sc = agent.docs?.scorecard?.data;
17
+ const b = agent.breaks?.baseline?.ok ? agent.breaks.breaks ?? [] : null;
18
+ const n = (st) => b.filter((x) => x.status === st).length;
19
+ const pct = agent.brief?.results?.confidence?.percent;
20
+ return {
21
+ confidence: Number.isFinite(pct) ? pct : null,
22
+ score: Number.isFinite(sc?.overall) ? sc.overall : null,
23
+ recommendation: sc?.recommendation ?? null,
24
+ breaks: b && n('caught') + n('missed') ? { caught: n('caught'), tried: n('caught') + n('missed') } : null,
25
+ notDone: agent.brief?.results?.notDone?.length ?? 0,
26
+ engine: engine ?? agent.engine ?? 'claude',
27
+ model: agent.model ?? null,
28
+ level: LEVELS.includes(agent.autonomy?.level) ? agent.autonomy.level : 'ask',
29
+ };
30
+ }
31
+
32
+ const BANDS = [
33
+ ['90', '90 to 100%', (c) => c >= 90],
34
+ ['70', '70 to 89%', (c) => c >= 70 && c < 90],
35
+ ['50', '50 to 69%', (c) => c >= 50 && c < 70],
36
+ ['0', 'under 50%', (c) => c < 50],
37
+ ];
38
+ const RECOMMENDATION = { ready: 'Ready to approve', look: 'Look at these first', not_ready: 'Not ready' };
39
+
40
+ /** How what was said compares with what held: a few words, or that there are too few to say. */
41
+ export function readOf(row) {
42
+ if (row.n < MIN_TO_SAY) return 'too few to say';
43
+ if (row.said == null) return '';
44
+ if (row.said - row.heldPct >= 15) return 'said more than held up';
45
+ if (row.heldPct - row.said >= 15) return 'held up better than said';
46
+ return 'about right';
47
+ }
48
+
49
+ function rowsOf(settled, groups) {
50
+ return groups
51
+ .map(([key, label, test]) => {
52
+ const list = settled.filter((it) => test(it));
53
+ const held = list.filter((it) => it.held).length;
54
+ const conf = list.map((it) => it.said?.confidence).filter(Number.isFinite);
55
+ const row = { key, label, n: list.length, held, heldPct: list.length ? round((held / list.length) * 100) : null, said: conf.length ? round(conf.reduce((a, c) => a + c, 0) / conf.length) : null };
56
+ return { ...row, read: readOf(row) };
57
+ })
58
+ .filter((r) => r.n);
59
+ }
60
+
61
+ /**
62
+ * The level of "Without you" a project's record supports: { level, why } when it differs from the
63
+ * one it has, else null. One step at a time; down after a recent problem, up only on a clean run.
64
+ * `settled`: the project's settled pull requests, newest first.
65
+ */
66
+ export function suggestLevel(settled, current = 'ask') {
67
+ const i = LEVELS.indexOf(current);
68
+ const last = (n) => settled.slice(0, n);
69
+ const bad3 = last(3).filter((it) => !it.held).length;
70
+ if (bad3 && i > 0) return { level: LEVELS[i - 1], direction: 'down', why: `${bad3} of its last ${last(3).length} merged pull request${last(3).length === 1 ? '' : 's'} did not hold up` };
71
+ const held = settled.filter((it) => it.held).length;
72
+ const pct = settled.length ? (held / settled.length) * 100 : 0;
73
+ if (current === 'pr') {
74
+ if (settled.length >= 10 && pct >= 95 && last(10).every((it) => it.held)) return { level: 'merge', direction: 'up', why: `${held} of ${settled.length} held up, and all of the last 10` };
75
+ return null;
76
+ }
77
+ if (i < LEVELS.indexOf('pr') && settled.length >= MIN_TO_SAY && pct >= 90 && last(5).every((it) => it.held)) return { level: LEVELS[i + 1], direction: 'up', why: `${held} of ${settled.length} held up, and all of the last 5` };
78
+ return null;
79
+ }
80
+
81
+ /**
82
+ * The record from Quality's items. `verdict(it)` is quality.js's verdictOf; a pull request counts
83
+ * once it is settled: held up after the watch days, or a problem. `levels`: { default, projects }.
84
+ */
85
+ export function trackRecord(items, verdict, { levels = {} } = {}) {
86
+ const all = items.map((it) => ({ ...it, verdict: verdict(it) }));
87
+ const settled = all
88
+ .filter((it) => it.verdict === 'clean' || PROBLEMS.has(it.verdict))
89
+ .map((it) => ({ ...it, held: it.verdict === 'clean' }))
90
+ .sort((a, b) => b.mergedAt.localeCompare(a.mergedAt));
91
+ const held = settled.filter((it) => it.held).length;
92
+ const withConf = settled.filter((it) => Number.isFinite(it.said?.confidence));
93
+ const uniq = (f) => [...new Set(settled.map(f))];
94
+ const overall = rowsOf(withConf, [['all', 'all with a confidence', () => true]])[0] ?? null;
95
+ const projects = uniq((it) => it.project ?? 'No project').map((name) => {
96
+ const list = settled.filter((it) => (it.project ?? 'No project') === name);
97
+ const row = rowsOf(list, [[name, name, () => true]])[0];
98
+ const level = levels.projects?.[name] ?? null;
99
+ const current = level ?? levels.default ?? 'ask';
100
+ return { ...row, level, current, suggestion: name === 'No project' ? null : suggestLevel(list, current) };
101
+ });
102
+ return {
103
+ settled: settled.length,
104
+ open: all.length - settled.length,
105
+ held,
106
+ heldPct: settled.length ? round((held / settled.length) * 100) : null,
107
+ // The agent's own confidence against what held: overall, then by what it said.
108
+ confidence: overall,
109
+ bands: rowsOf(withConf, BANDS.map(([k, label, test]) => [k, label, (it) => test(it.said.confidence)])),
110
+ noConfidence: settled.length - withConf.length,
111
+ scorecard: rowsOf(settled, [...Object.entries(RECOMMENDATION).map(([k, label]) => [k, label, (it) => it.said?.recommendation === k]), ['none', 'No scorecard', (it) => !it.said?.recommendation]]),
112
+ tests: rowsOf(settled, [
113
+ ['all', 'Tests tested: every break caught', (it) => it.said?.breaks && it.said.breaks.caught === it.said.breaks.tried],
114
+ ['some', 'Tests tested: a break not noticed', (it) => it.said?.breaks && it.said.breaks.caught < it.said.breaks.tried],
115
+ ['none', 'Tests not tested', (it) => !it.said?.breaks],
116
+ ]),
117
+ models: rowsOf(settled, uniq((it) => `${it.said?.engine ?? 'unknown'}${it.said?.model ? ` · ${it.said.model}` : ''}`).map((k) => [k, k, (it) => `${it.said?.engine ?? 'unknown'}${it.said?.model ? ` · ${it.said.model}` : ''}` === k])),
118
+ levels: rowsOf(settled, LEVELS.map((l) => [l, LEVEL_LABEL[l], (it) => (it.said?.level ?? 'ask') === l])),
119
+ projects: projects.sort((a, b) => b.n - a.n),
120
+ defaultLevel: levels.default ?? 'ask',
121
+ };
122
+ }
123
+
124
+ const line = (r) => `${r.label}: ${r.held} of ${r.n} held up${r.heldPct == null ? '' : ` (${r.heldPct}%)`}${r.said != null ? `, said ${r.said}% on average` : ''}${r.read ? `: ${r.read}` : ''}`;
125
+
126
+ export function recordMarkdown(r) {
127
+ const out = ['# Track record', ''];
128
+ if (!r.settled) return [...out, `No merged pull request is settled yet${r.open ? ` (${r.open} still watched or not looked at)` : ''}. One counts once it held up for the watch days, or was reverted, fixed afterwards or failed its checks.`].join('\n');
129
+ out.push(`${r.held} of ${r.settled} merged pull requests held up (${r.heldPct}%).${r.open ? ` ${r.open} more are still watched or not looked at.` : ''}`, '');
130
+ const part = (title, rows, note = '') => {
131
+ if (!rows.length) return;
132
+ out.push(`## ${title}`, '', ...rows.map((x) => `- ${line(x)}`), ...(note ? ['', note] : []), '');
133
+ };
134
+ part("The agent's own confidence", [...(r.confidence ? [r.confidence] : []), ...r.bands], r.noConfidence ? `${r.noConfidence} had no confidence written.` : '');
135
+ part('The review scorecard', r.scorecard);
136
+ part('Tests tested', r.tests);
137
+ part('Model', r.models);
138
+ part('Without you', r.levels);
139
+ if (r.projects.length) {
140
+ out.push('## Projects', '');
141
+ for (const p of r.projects) {
142
+ out.push(`- ${line(p)}. New agents: ${LEVEL_LABEL[p.current]}${p.level ? '' : ' (the default)'}.${p.suggestion ? ` The record supports **${LEVEL_LABEL[p.suggestion.level]}**: ${p.suggestion.why}.` : ''}`);
143
+ }
144
+ out.push('');
145
+ }
146
+ return out.join('\n').trimEnd();
147
+ }
package/src/scorecard.js CHANGED
@@ -4,6 +4,9 @@
4
4
  // plan ticks, the spec's criteria) cap and correct it, and the recommendation follows fixed rules,
5
5
  // so a confident-sounding model can't talk a change into "ready".
6
6
 
7
+ import { proofFacts } from './proof.js';
8
+ import { breakCounts, breakFacts } from './mutate.js';
9
+
7
10
  export const DIMENSIONS = [
8
11
  ['intent', 'Intent', 'Does it do what was asked?'],
9
12
  ['spec', 'Spec', 'Are the acceptance criteria met?'],
@@ -16,7 +19,7 @@ const WEIGHTS = { intent: 25, spec: 20, tests: 20, safety: 15, scope: 10, plan:
16
19
  const TEST_FILE = /(^|\/)(tests?|__tests__|spec|specs)\/|[._-](test|spec)\.[a-z]+$|_test\.go$|Test\.java$/i;
17
20
 
18
21
  /** Facts the app knows without a model: CI, test files touched, the agent's checks, plan and spec progress. */
19
- export function facts({ files = [], prs = [], brief = null, plan = '', spec = '', standards = null, agreed = null }) {
22
+ export function facts({ files = [], prs = [], brief = null, plan = '', spec = '', standards = null, agreed = null, proof = null, breaks = null }) {
20
23
  const paths = files.map((f) => f.path);
21
24
  const tests = paths.filter((p) => TEST_FILE.test(p));
22
25
  const code = paths.filter((p) => !TEST_FILE.test(p) && !/\.(md|txt|rst|adoc)$/i.test(p) && !/(^|\/)docs?\//i.test(p));
@@ -37,6 +40,13 @@ export function facts({ files = [], prs = [], brief = null, plan = '', spec = ''
37
40
  plan: steps.length ? { steps: steps.length, done: steps.filter((s) => s === 'x').length } : null,
38
41
  criteria: criteriaBlock.split('\n').filter((l) => /^\s*[-*\d]/.test(l) && /\w/.test(l)).length,
39
42
  hasSpec: Boolean(String(spec).trim()),
43
+ // Its proof (proof.js): what it recorded, what the app ran again, and what it says it left out.
44
+ proof: proof ? { doc: proof.doc, rerun: proof.rerun ?? null } : null,
45
+ notDone: brief?.results?.notDone ?? [],
46
+ // Its pre-mortem (brief.js): the risks it named before starting, and how each ended.
47
+ risks: brief?.risks ?? [],
48
+ // Its tests tested (mutate.js): changed lines broken one at a time, and whether the tests noticed.
49
+ breaks: breaks && !breaks.stale ? breaks : null,
40
50
  // What done means, agreed with the person (acceptance.js): these are checked, whatever the spec says now.
41
51
  agreed: agreed?.length ? agreed.map((p) => ({ id: p.id, text: p.text })) : null,
42
52
  // The repository's standards (standards.js): high-risk files touched, and the bar the app ran.
@@ -55,9 +65,19 @@ export const factLines = (f) =>
55
65
  ...(f.agreed ? [`acceptance agreed with the person: ${f.agreed.length} point${f.agreed.length === 1 ? '' : 's'}`] : []),
56
66
  ...(f.bar ? [`the repository's quality bar, run by the app: ${f.bar.passed} passed, ${f.bar.failed.length} failed${f.bar.failed.length ? ` (${f.bar.failed.join(', ')})` : ''}`] : []),
57
67
  ...(f.risk?.length ? [`files under paths the person marked high risk: ${f.risk.join(', ')}`] : []),
68
+ ...(f.proof ? proofFacts(f.proof.doc, f.proof.rerun) : []),
69
+ ...breakFacts(f.breaks),
70
+ ...(f.risks?.length
71
+ ? [
72
+ `risks the agent named before starting: ${f.risks.length}; it marks ${f.risks.filter((r) => r.state === 'avoided').length} avoided, ${f.risks.filter((r) => r.state === 'happened').length} happened, ${f.risks.filter((r) => r.state === 'open').length} not checked` +
73
+ (f.risks.some((r) => r.state !== 'avoided') ? ` (${f.risks.filter((r) => r.state !== 'avoided').map((r) => `${r.state === 'happened' ? 'happened' : 'not checked'}: ${r.text.slice(0, 120)}`).join('; ')})` : '') +
74
+ '. Check the ones not marked avoided against the changes.',
75
+ ]
76
+ : []),
77
+ ...(f.notDone?.length ? [`the agent lists as not done: ${f.notDone.join('; ')}`] : []),
58
78
  ].join('\n');
59
79
 
60
- export function scorecardPrompt({ intent, status, digest, briefMarkdown, intentDoc, specDoc, planDoc, hunks, facts: f, lessons = [] }) {
80
+ export function scorecardPrompt({ intent, status, digest, briefMarkdown, intentDoc, specDoc, planDoc, proofDoc = '', hunks, facts: f, lessons = [] }) {
61
81
  return [
62
82
  "You score an AI coding agent's changes for a reviewer who wants to approve with confidence and read as little as possible.",
63
83
  'Be skeptical: a claim without evidence in the diff, the tests or the checks counts as unverified. Base everything on the material below.',
@@ -106,6 +126,8 @@ export function scorecardPrompt({ intent, status, digest, briefMarkdown, intentD
106
126
  '<brief>',
107
127
  briefMarkdown || '(none)',
108
128
  '</brief>',
129
+ // Its own record of what it ran: evidence for a check when the output shown fits the claim, but not run by the app unless the facts say so.
130
+ ...(proofDoc ? ['<proof_recorded_by_the_agent>', proofDoc, '</proof_recorded_by_the_agent>'] : []),
109
131
  '<hunks>',
110
132
  ...hunks.map((h) => `<hunk id="${h.id}" file="${h.file}">\n${h.head}\n${h.text}\n</hunk>`),
111
133
  '</hunks>',
@@ -137,6 +159,22 @@ export function combine(reply, f, hunks, { lessons = [], bar = null } = {}) {
137
159
  // The repository's quality bar, run by the app: a failed check is not verified, whatever else passed.
138
160
  const barFailed = (bar?.results ?? []).filter((r) => !r.ok);
139
161
  if (barFailed.length) cap('tests', 30, `the quality bar is not met (${barFailed.map((r) => r.name).join(', ')})`);
162
+ // Its recorded commands, run again by the app at the person's request: one that now gives another result is not verified.
163
+ const differs = f.proof?.rerun && !f.proof.rerun.stale ? f.proof.rerun.results.filter((r) => r.status === 'differs') : [];
164
+ if (differs.length) cap('tests', 40, `${differs.length} of its recorded commands gave a different result when run again (${differs.map((r) => r.title).join('; ').slice(0, 200)})`);
165
+ // Its tests tested by the app: breaks the tests did not notice are lines nothing verifies.
166
+ if (f.breaks?.baseline?.ok) {
167
+ const c = breakCounts(f.breaks.breaks);
168
+ if (c.tried >= 3 && !c.caught) cap('tests', 35, `none of ${c.tried} breaks made in the changed code was noticed by the tests`);
169
+ else if (c.tried >= 3 && c.missed * 2 > c.tried) cap('tests', 55, `${c.missed} of ${c.tried} breaks made in the changed code were not noticed by the tests`);
170
+ else if (c.missed && out.tests) out.tests.notes.push(`${c.missed} of ${c.tried} breaks made in the changed code ${c.missed === 1 ? 'was' : 'were'} not noticed by the tests`);
171
+ } else if (f.breaks?.baseline) cap('tests', 40, 'the tests failed when the app ran them');
172
+ // Its own pre-mortem: a risk it named and did not check is a place nobody looked.
173
+ const unchecked = (f.risks ?? []).filter((r) => r.state === 'open');
174
+ const happened = (f.risks ?? []).filter((r) => r.state === 'happened');
175
+ if (unchecked.length && out.tests) out.tests.notes.push(`${unchecked.length} of the ${f.risks.length} risks it named before starting ${unchecked.length === 1 ? 'was' : 'were'} not checked`);
176
+ if (happened.length && out.safety) out.safety.notes.push(`${happened.length} of the risks it named happened: ${happened.map((r) => r.text.slice(0, 100)).join('; ')}`);
177
+ if (f.notDone?.length && out.intent) out.intent.notes.push(`the agent lists ${f.notDone.length} thing${f.notDone.length === 1 ? '' : 's'} as not done`);
140
178
  // Plan: bounded by the steps ticked.
141
179
  if (f.plan && out.plan) cap('plan', Math.round(40 + (60 * f.plan.done) / f.plan.steps), `${f.plan.done} of ${f.plan.steps} plan steps ticked`);
142
180
  if (!f.plan && out.plan) out.plan.notes.push('no plan written');
package/src/server.js CHANGED
@@ -57,7 +57,11 @@ import { Builder } from './builder.js';
57
57
  import { Standup } from './standup.js';
58
58
  import { Value, valueSlack } from './value.js';
59
59
  import { Quality } from './quality.js';
60
- import { Standards } from './standards.js';
60
+ import { recordMarkdown } from './record.js';
61
+ import { PRIVATE_MESSAGE, keptPrivate, mustBeShareable } from './private.js';
62
+ import { Standards, runCheck } from './standards.js';
63
+ import { Proof, proofMarkdown } from './proof.js';
64
+ import { Mutate, breaksMarkdown } from './mutate.js';
61
65
  import { News } from './news.js';
62
66
  import { System } from './system.js';
63
67
  import { Advisor } from './advisor.js';
@@ -218,6 +222,7 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
218
222
  /** Commit what's left, push and open the agent's pull request, titled after the issue or request. */
219
223
  const shipAgent = async (ref, { title = '', body = '' } = {}) => {
220
224
  const a = manager.mustGet(ref);
225
+ mustBeShareable(a, 'Opening the pull request');
221
226
  const key = leadingJiraKey(a.intent);
222
227
  const words = a.synopsis?.text ?? a.brief?.title ?? String(a.intent ?? '').replace(/^<?https?:\/\/\S+>?\s*/, '').split('\n')[0];
223
228
  title = String(title ?? '').trim() || `${key ? `${key}: ` : ''}${words || a.name}`.slice(0, 100);
@@ -245,6 +250,15 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
245
250
  // Agents that run without you (autonomy.js): routine questions answered from what is decided,
246
251
  // nudges and follow-ups sent, and at "merge" the pull request merged when everything says ready.
247
252
  const autonomy = new Autonomy({ manager, store, config, review, landing, backlog });
253
+ manager.proof = new Proof({ manager, store, run: runCheck, log: (m) => console.log(`[agentmgr] ${m}`) });
254
+ manager.mutate = new Mutate({ manager, store, run: runCheck, changes: (id) => review.get(id), config: config.testTheTests ?? {}, log: (m) => console.log(`[agentmgr] ${m}`) });
255
+ manager.mutate.recover();
256
+ // Read as possibly patentable by Insights: the agent is told once to keep it inside the repository (private.js).
257
+ manager.on('change', (v) => {
258
+ if (v.keptPrivate?.from !== 'insights' || v.idea?.toldAt || !manager.runtimes.get(v.id)?.pty) return;
259
+ manager.patch(v.id, { idea: { ...v.idea, toldAt: new Date().toISOString() } });
260
+ manager.tell(v.id, PRIVATE_MESSAGE);
261
+ });
248
262
  manager.inboxSources.push(() => autonomy.inbox());
249
263
  // How far an agent goes without the person is the person's to set: never an agent's own call.
250
264
  const yourLevel = (req) => {
@@ -619,6 +633,13 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
619
633
  const bg = (req) => req.query.background === '1' || req.body?.background === true;
620
634
  api.post('/agents/:id/explain', wrap((req) => (bg(req) ? manager.summarizeInBackground(req.params.id, ['explain']) : manager.explain(req.params.id))));
621
635
  api.post('/agents/:id/insights', wrap((req) => (bg(req) ? manager.summarizeInBackground(req.params.id, ['insights']) : manager.insights(req.params.id))));
636
+ // Kept private (private.js): yours to set and to lift, never the agent's.
637
+ api.post('/agents/:id/private', wrap((req) => {
638
+ if (req.headers['x-agentmgr-agent']) throw fail(403, 'Whether work is kept private is decided by the person, not by an agent');
639
+ const b = req.body ?? {};
640
+ if (![true, false, null].includes(b.private ?? null)) throw fail(400, 'private is true (keep it private), false (allow sharing) or null (what was read)');
641
+ return manager.setPrivate(req.params.id, { private: b.private ?? null, note: b.note ?? '' });
642
+ }));
622
643
  const DOC_LIST = ['analysis', 'design', 'flow', 'proposal', 'humanai', 'estimate', 'documentation'];
623
644
  api.post('/agents/:id/humanai/answers', wrap((req) => manager.humanAiAnswers(req.params.id, req.body?.answers, { send: req.body?.send === true })));
624
645
  api.post(
@@ -654,6 +675,7 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
654
675
  api.put('/agents/:id/announce', wrap((req) => manager.updateState(req.params.id, req.body ?? {})));
655
676
  api.post('/agents/:id/announce/publish', wrap((req) => manager.publishUpdate(req.params.id)));
656
677
  api.post('/agents/:id/announce/slack', wrap(async (req) => {
678
+ mustBeShareable(manager.mustGet(req.params.id), 'Posting the update to Slack');
657
679
  const to = announceSlack();
658
680
  if (!to) throw fail(409, 'Slack is not set up: give a webhook for updates (agentmgr announce --webhook <url>), or set up Slack alerts');
659
681
  const text = manager.updateSlackText(req.params.id, req.body?.text ?? null);
@@ -674,7 +696,7 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
674
696
  });
675
697
  // All of an agent's documents to Google Drive (through the Claude account's Google Drive connector).
676
698
  api.post('/agents/:id/drive', wrap((req) => manager.publishToDrive(req.params.id)));
677
- api.post('/agents/:id/scorecard/post', wrap((req) => review.postScorecard(req.params.id)));
699
+ api.post('/agents/:id/scorecard/post', wrap((req) => (mustBeShareable(manager.mustGet(req.params.id), 'Posting the scorecard on the pull request'), review.postScorecard(req.params.id))));
678
700
  // Improve: its scorecard goes back to the agent; a backlog item in review is reopened with it.
679
701
  api.post(
680
702
  '/agents/:id/scorecard/improve',
@@ -696,6 +718,30 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
696
718
  };
697
719
  api.post('/agents/:id/acceptance/agree', wrap((req) => (person(req), manager.agreeAcceptance(req.params.id, req.body?.points))));
698
720
  api.post('/agents/:id/acceptance/skip', wrap((req) => (person(req), manager.skipAcceptance(req.params.id))));
721
+ // Proof (proof.js): what the agent recorded of its checks. Running the commands again is the
722
+ // person's call: they were written by the agent, and here they run without its permission prompts.
723
+ api.get('/agents/:id/proof', wrap((req) => {
724
+ const v = manager.proof.view(req.params.id);
725
+ return req.query.format === 'md' ? { markdown: proofMarkdown(v) } : v;
726
+ }));
727
+ api.post('/agents/:id/proof/run', wrap((req) => {
728
+ if (req.headers['x-agentmgr-agent']) throw fail(403, 'Running the proof again is asked by the person, not by an agent');
729
+ return manager.proof.rerun(req.params.id);
730
+ }));
731
+ // Test the tests (mutate.js): changed lines broken one at a time, the tests run on each. The
732
+ // person's call only: it runs commands here and changes the agent's files for a moment.
733
+ api.get('/agents/:id/breaks', wrap(async (req) => {
734
+ const v = await manager.mutate.view(req.params.id);
735
+ return req.query.format === 'md' ? { markdown: breaksMarkdown(v) } : v;
736
+ }));
737
+ api.post('/agents/:id/breaks/run', wrap((req) => {
738
+ if (req.headers['x-agentmgr-agent']) throw fail(403, 'Testing the tests is asked by the person, not by an agent');
739
+ return manager.mutate.start(req.params.id, { command: req.body?.command, max: req.body?.max });
740
+ }));
741
+ api.post('/agents/:id/breaks/send', wrap((req) => {
742
+ if (req.headers['x-agentmgr-agent']) throw fail(403, 'Testing the tests is asked by the person, not by an agent');
743
+ return manager.mutate.send(req.params.id);
744
+ }));
699
745
  // Autonomy (autonomy.js): the default level and the models its calls run on; one agent's level;
700
746
  // and what was done for the person: seen ("ack"), or an answer changed to their own ("correct").
701
747
  api.get('/autonomy', wrap(() => autonomy.status()));
@@ -1333,6 +1379,11 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
1333
1379
  return quality.view({ period: String(req.query.period ?? 'week') });
1334
1380
  }));
1335
1381
  // A pull request is named by its link, so it travels in the body.
1382
+ // Track record (record.js): what was said at the merge against what held, and the level each project's record supports.
1383
+ api.get('/quality/record', wrap((req) => {
1384
+ const r = quality.record();
1385
+ return req.query.format === 'md' ? { markdown: recordMarkdown(r) } : r;
1386
+ }));
1336
1387
  api.post('/quality/mark', wrap((req) => quality.mark(String(req.body?.url ?? ''), { verdict: req.body?.verdict ?? null, note: req.body?.note ?? '' })));
1337
1388
  api.post('/quality/check', wrap((req) => quality.check(String(req.body?.url ?? ''), { fresh: true })));
1338
1389
  // Standards are the person's to set: an agent's own calls can read them, not change them.