ai-agentmanager 1.70.2 → 1.72.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +14 -0
- package/README.md +36 -0
- package/package.json +1 -1
- package/public/app.js +69 -5
- package/public/glance.js +241 -0
- package/public/index.html +20 -0
- package/public/review.js +40 -2
- package/public/style.css +32 -0
- package/public/valuelens.js +19 -4
- package/src/blame.js +146 -0
- package/src/calibration.js +115 -0
- package/src/cli.js +127 -0
- package/src/echo.js +110 -0
- package/src/fence.js +81 -0
- package/src/manager.js +147 -2
- package/src/nightwatch.js +155 -0
- package/src/races.js +54 -0
- package/src/server.js +116 -4
package/public/valuelens.js
CHANGED
|
@@ -77,8 +77,19 @@ export function kindHtml(k, esc) {
|
|
|
77
77
|
${k.kind === 'patent' ? '<p class="hint">A first read, not legal advice. Publishing before filing can cost the right to a patent: keep it private until you have talked to a patent attorney.</p>' : ''}`;
|
|
78
78
|
}
|
|
79
79
|
|
|
80
|
-
|
|
80
|
+
/**
|
|
81
|
+
* The paths, preferred first. `tries` (in an agent's Results): each other path gets a Try this
|
|
82
|
+
* path button, or the agent already trying it: { 2: { id, name } }.
|
|
83
|
+
*/
|
|
84
|
+
export function pathsHtml(p, esc, tries = null) {
|
|
81
85
|
if (!p?.paths.length) return '';
|
|
86
|
+
const tryOf = (i) => {
|
|
87
|
+
if (!tries || i === 0) return '';
|
|
88
|
+
const t = tries[i + 1];
|
|
89
|
+
return t
|
|
90
|
+
? `<div class="vl-try hint">Being tried by <button class="link" data-act="try-path-open" data-agent="${esc(t.id)}">${esc(t.name)}</button></div>`
|
|
91
|
+
: `<div class="vl-try"><button class="small" data-act="try-path" data-path="${i + 1}" title="Start this path as a second agent from the same commit, and compare the two">Try this path</button></div>`;
|
|
92
|
+
};
|
|
82
93
|
const chip = (label, l, good) => (l ? `<span class="vl-chip ${good.includes(l) ? 'vl-good' : l === 'medium' ? '' : 'vl-poor'}">${label} ${l}</span>` : '');
|
|
83
94
|
return `<ol class="vl-paths">${p.paths
|
|
84
95
|
.map(
|
|
@@ -86,18 +97,22 @@ export function pathsHtml(p, esc) {
|
|
|
86
97
|
<div class="vl-name">${i === 0 ? '<span class="tag vl-pick">Preferred</span> ' : ''}<b>${esc(x.name)}</b>${x.what ? ` <span class="hint">${esc(x.what)}</span>` : ''}</div>
|
|
87
98
|
<div class="vl-chips">${chip('now', x.now, ['high'])}${chip('later', x.later, ['high'])}${chip('cost', x.cost, ['small'])}${chip('risk', x.risk, ['low'])}</div>
|
|
88
99
|
${x.when ? `<div class="hint">Pick when: ${esc(x.when)}</div>` : ''}
|
|
100
|
+
${tryOf(i)}
|
|
89
101
|
</li>`,
|
|
90
102
|
)
|
|
91
103
|
.join('')}</ol>
|
|
92
104
|
${p.preferred ? `<p class="vl-line"><b>Why the first</b> ${esc(p.preferred)}</p>` : ''}`;
|
|
93
105
|
}
|
|
94
106
|
|
|
95
|
-
/**
|
|
96
|
-
|
|
107
|
+
/**
|
|
108
|
+
* In the agent's Results: the ways it weighed before building, preferred first. `tries`: the
|
|
109
|
+
* agents trying its other paths ({ n: { id, name } }), or null where none can be tried.
|
|
110
|
+
*/
|
|
111
|
+
export function optionsRows(a, esc, tries = null) {
|
|
97
112
|
const o = a.brief?.options;
|
|
98
113
|
if (!o?.paths?.length && !o?.new) return '';
|
|
99
114
|
return `<details class="vl-options"${o.new ? ' open' : ''}><summary><b>Paths it weighed</b> <span class="hint">${o.paths.length ? `${o.paths.length}, preferred first${o.paths[0] ? `: ${esc(o.paths[0].name)}` : ''}` : ''}</span></summary>
|
|
100
|
-
${pathsHtml(o, esc)}
|
|
115
|
+
${pathsHtml(o, esc, tries)}
|
|
101
116
|
${o.new ? `<p class="vl-line"><span class="tag vl-kind vl-kind-paper">Possibly new</span> ${esc(o.new)} <span class="hint">Kept inside the repository; whether it is worth a paper or a patent is yours to decide.</span></p>` : ''}
|
|
102
117
|
</details>`;
|
|
103
118
|
}
|
package/src/blame.js
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
// Conversation blame: why is this line here? `git blame` names a commit; this names the moment in
|
|
2
|
+
// the agent's conversation that wrote the line: what it had been asked, what it said just before,
|
|
3
|
+
// the commands it had just run, and the edit itself. Read from its own transcripts (Claude Code's
|
|
4
|
+
// JSONL, its subagents' too), so nothing is guessed: a line no edit wrote is said to be not found.
|
|
5
|
+
import fs from 'node:fs';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
|
|
8
|
+
const EDITS = new Set(['Edit', 'MultiEdit', 'Write', 'NotebookEdit']);
|
|
9
|
+
const clip = (s, n) => {
|
|
10
|
+
const t = String(s ?? '').trim();
|
|
11
|
+
return t.length > n ? `${t.slice(0, n - 1)}…` : t;
|
|
12
|
+
};
|
|
13
|
+
// Code keeps its indentation: only the line breaks at its ends go.
|
|
14
|
+
const clipCode = (s, n) => {
|
|
15
|
+
const t = String(s ?? '').replace(/^\n+|\s+$/g, '');
|
|
16
|
+
return t.length > n ? `${t.slice(0, n - 1)}…` : t;
|
|
17
|
+
};
|
|
18
|
+
const norm = (s) => String(s ?? '').trim().replace(/\s+/g, ' ');
|
|
19
|
+
|
|
20
|
+
/** Text of a message's content: a string, or its text parts. */
|
|
21
|
+
function textOf(content) {
|
|
22
|
+
if (typeof content === 'string') return content;
|
|
23
|
+
return (Array.isArray(content) ? content : [])
|
|
24
|
+
.filter((c) => c?.type === 'text' && typeof c.text === 'string')
|
|
25
|
+
.map((c) => c.text)
|
|
26
|
+
.join('\n');
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** What an edit wrote, as lines (each write of a MultiEdit, a file's whole content). */
|
|
30
|
+
function written(c) {
|
|
31
|
+
const i = c.input ?? {};
|
|
32
|
+
if (c.name === 'Write') return [{ before: null, after: String(i.content ?? '') }];
|
|
33
|
+
if (c.name === 'MultiEdit') return (i.edits ?? []).map((e) => ({ before: String(e.old_string ?? ''), after: String(e.new_string ?? '') }));
|
|
34
|
+
if (c.name === 'NotebookEdit') return [{ before: null, after: String(i.new_source ?? '') }];
|
|
35
|
+
return [{ before: String(i.old_string ?? ''), after: String(i.new_string ?? '') }];
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** A user's own words: not a tool result, not a note the program added (isMeta, reminders). */
|
|
39
|
+
function promptOf(entry) {
|
|
40
|
+
if (entry.type !== 'user' || entry.isMeta) return null;
|
|
41
|
+
const content = entry.message?.content;
|
|
42
|
+
if (Array.isArray(content) && content.some((c) => c?.type === 'tool_result')) return null;
|
|
43
|
+
const t = textOf(content).replace(/<system-reminder>[\s\S]*?<\/system-reminder>/g, '').trim();
|
|
44
|
+
if (!t || /^<(command-|local-command)/.test(t)) return null;
|
|
45
|
+
return t;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* The transcript entries, oldest first, from JSONL text. Lines that are not JSON are skipped.
|
|
50
|
+
*/
|
|
51
|
+
export function parseTranscript(text) {
|
|
52
|
+
const out = [];
|
|
53
|
+
for (const line of String(text ?? '').split('\n')) {
|
|
54
|
+
if (!line.trim()) continue;
|
|
55
|
+
try {
|
|
56
|
+
out.push(JSON.parse(line));
|
|
57
|
+
} catch {}
|
|
58
|
+
}
|
|
59
|
+
return out;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Why `line` (its text) is in `file`: the edits in the transcripts that wrote it, and the last
|
|
64
|
+
* one's moment. `file` is relative to `workdir`; edits name absolute paths or relative ones.
|
|
65
|
+
* Returns { found: false } or { found: true, at, tool, prompt, promptAt, said, ran, edit: { before,
|
|
66
|
+
* after }, times, firstAt, session }.
|
|
67
|
+
*/
|
|
68
|
+
export function blameLine(transcripts, { file, line, workdir }) {
|
|
69
|
+
const want = norm(line);
|
|
70
|
+
if (!want) return { found: false, why: 'The line is empty' };
|
|
71
|
+
const root = workdir ? path.resolve(workdir) : null;
|
|
72
|
+
const sameFile = (p) => {
|
|
73
|
+
if (typeof p !== 'string') return false;
|
|
74
|
+
const abs = path.isAbsolute(p) ? path.resolve(p) : root ? path.resolve(root, p) : p;
|
|
75
|
+
return root ? abs === path.resolve(root, file) : abs.endsWith(`/${file}`) || abs === file;
|
|
76
|
+
};
|
|
77
|
+
const hits = [];
|
|
78
|
+
for (const { session, entries } of transcripts) {
|
|
79
|
+
let prompt = null;
|
|
80
|
+
let promptAt = null;
|
|
81
|
+
let said = [];
|
|
82
|
+
let ran = [];
|
|
83
|
+
for (const entry of entries) {
|
|
84
|
+
const p = promptOf(entry);
|
|
85
|
+
if (p) {
|
|
86
|
+
prompt = p;
|
|
87
|
+
promptAt = entry.timestamp ?? null;
|
|
88
|
+
said = [];
|
|
89
|
+
ran = [];
|
|
90
|
+
continue;
|
|
91
|
+
}
|
|
92
|
+
if (entry.type !== 'assistant') continue;
|
|
93
|
+
for (const c of entry.message?.content ?? []) {
|
|
94
|
+
if (c?.type === 'text' && c.text?.trim()) said = [...said, c.text.trim()].slice(-2);
|
|
95
|
+
else if (c?.type === 'thinking' && c.thinking?.trim()) said = [...said, c.thinking.trim()].slice(-2);
|
|
96
|
+
else if (c?.type === 'tool_use' && c.name === 'Bash' && typeof c.input?.command === 'string') ran = [...ran, c.input.command].slice(-3);
|
|
97
|
+
else if (c?.type === 'tool_use' && EDITS.has(c.name) && sameFile(c.input?.file_path ?? c.input?.notebook_path)) {
|
|
98
|
+
// An edit that adds the line, not one that only carries it along as context.
|
|
99
|
+
const count = (t) => (t ?? '').split('\n').filter((l) => norm(l) === want).length;
|
|
100
|
+
const edit = written(c).find((w) => count(w.after) > count(w.before));
|
|
101
|
+
if (edit) hits.push({ at: entry.timestamp ?? null, tool: c.name, prompt, promptAt, said: [...said], ran: [...ran], edit, session });
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
if (!hits.length) return { found: false, why: 'No edit in its conversation wrote this line: it was there before, or written by a command' };
|
|
107
|
+
hits.sort((a, b) => String(a.at).localeCompare(String(b.at)));
|
|
108
|
+
const last = hits.at(-1);
|
|
109
|
+
return {
|
|
110
|
+
found: true,
|
|
111
|
+
at: last.at,
|
|
112
|
+
tool: last.tool,
|
|
113
|
+
prompt: last.prompt ? clip(last.prompt, 1500) : null,
|
|
114
|
+
promptAt: last.promptAt,
|
|
115
|
+
said: last.said.map((s) => clip(s, 800)),
|
|
116
|
+
ran: last.ran.map((s) => clip(s, 300)),
|
|
117
|
+
edit: { before: last.edit.before === null ? null : clipCode(last.edit.before, 1500), after: clipCode(last.edit.after, 1500) },
|
|
118
|
+
times: hits.length,
|
|
119
|
+
firstAt: hits[0].at,
|
|
120
|
+
session: last.session,
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** The transcripts of an agent's sessions (and their subagents'), read from disk. */
|
|
125
|
+
export function readTranscripts(files) {
|
|
126
|
+
const out = [];
|
|
127
|
+
for (const { session, file } of files) {
|
|
128
|
+
try {
|
|
129
|
+
out.push({ session, entries: parseTranscript(fs.readFileSync(file, 'utf8')) });
|
|
130
|
+
} catch {}
|
|
131
|
+
}
|
|
132
|
+
return out;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
export function blameMarkdown(b, { file, lineNo, line } = {}) {
|
|
136
|
+
const out = [`# Why is this line here?`, '', `\`${file}${lineNo ? `:${lineNo}` : ''}\`: \`${clip(line, 200)}\``, ''];
|
|
137
|
+
if (!b.found) return [...out, b.why].join('\n');
|
|
138
|
+
out.push(`Written by ${b.tool} at ${b.at}${b.times > 1 ? ` (written ${b.times} times, first at ${b.firstAt})` : ''}.`, '');
|
|
139
|
+
if (b.prompt) out.push('## What it was asked', '', b.prompt, '');
|
|
140
|
+
if (b.said.length) out.push('## What it said just before', '', ...b.said.flatMap((s) => [s, '']));
|
|
141
|
+
if (b.ran.length) out.push('## Commands it had just run', '', ...b.ran.map((c) => `- \`${c}\``), '');
|
|
142
|
+
out.push('## The edit', '');
|
|
143
|
+
if (b.edit.before !== null) out.push('```diff', ...b.edit.before.split('\n').map((l) => `- ${l}`), ...b.edit.after.split('\n').map((l) => `+ ${l}`), '```');
|
|
144
|
+
else out.push('```', b.edit.after, '```');
|
|
145
|
+
return out.join('\n').trimEnd();
|
|
146
|
+
}
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
// Your calibration: before an agent starts you can guess, in one tap each, whether it will finish,
|
|
2
|
+
// how long it will take, and how much reading its work will need. Once the work settles, the guess
|
|
3
|
+
// is set against what happened: the outcome it wrote, the time from start to its finished brief,
|
|
4
|
+
// and the Read first level its work got (readfirst.js). Over weeks this says what you judge well
|
|
5
|
+
// and what you don't, by kind of work, next to how the agents' own confidence held up. It stays on
|
|
6
|
+
// this computer, for you: no one else's numbers, and nothing is sent anywhere.
|
|
7
|
+
import { kindOf, KIND_LABEL } from './record.js';
|
|
8
|
+
|
|
9
|
+
export const REVIEW = ['skim', 'look', 'close'];
|
|
10
|
+
const REVIEW_WORD = { skim: 'skim', look: 'look', close: 'read closely' };
|
|
11
|
+
const HOUR = 3_600_000;
|
|
12
|
+
|
|
13
|
+
/** A guess as given (from the form or the command line), or null when nothing was guessed. */
|
|
14
|
+
export function cleanGuess(g) {
|
|
15
|
+
if (!g || typeof g !== 'object') return null;
|
|
16
|
+
const out = {};
|
|
17
|
+
if (g.finish === true || g.finish === 'yes') out.finish = 'yes';
|
|
18
|
+
else if (g.finish === false || g.finish === 'no') out.finish = 'no';
|
|
19
|
+
const h = Number(g.hours);
|
|
20
|
+
if (g.hours !== undefined && g.hours !== '' && g.hours !== null) {
|
|
21
|
+
if (!Number.isFinite(h) || h <= 0 || h > 24 * 30) throw Object.assign(new Error('hours is a number above 0'), { status: 400 });
|
|
22
|
+
out.hours = h;
|
|
23
|
+
}
|
|
24
|
+
if (g.review) {
|
|
25
|
+
if (!REVIEW.includes(g.review)) throw Object.assign(new Error('review is skim, look or close'), { status: 400 });
|
|
26
|
+
out.review = g.review;
|
|
27
|
+
}
|
|
28
|
+
return Object.keys(out).length ? { ...out, at: new Date().toISOString() } : null;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** What happened, once the work settled; null before. `a` is the agent's view. */
|
|
32
|
+
export function actualOf(a) {
|
|
33
|
+
const b = a.brief ?? {};
|
|
34
|
+
const outcome = b.results?.outcome ?? null;
|
|
35
|
+
const merged = Object.values(a.prs ?? {}).some((p) => p.state === 'MERGED' && p.source !== 'mentioned');
|
|
36
|
+
// Settled: an outcome it wrote (not "in progress"), a merged pull request, or a brief marked done.
|
|
37
|
+
if (!['done', 'partial', 'blocked'].includes(outcome) && !merged && b.status !== 'done') return null;
|
|
38
|
+
// What it says of its outcome first: "done" with part of it left is not finished.
|
|
39
|
+
const finish = outcome === 'blocked' || outcome === 'partial' ? 'no' : outcome === 'done' || merged || b.status === 'done' ? 'yes' : null;
|
|
40
|
+
const end = Date.parse(b.updatedAt ?? a.activeAt ?? '');
|
|
41
|
+
const start = Date.parse(a.createdAt ?? '');
|
|
42
|
+
const hours = Number.isFinite(end - start) && end > start ? Math.max(0.1, Math.round(((end - start) / HOUR) * 10) / 10) : null;
|
|
43
|
+
const review = a.readFirst?.level ?? a.guess?.actual?.review ?? null;
|
|
44
|
+
return { finish, hours, review };
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const median = (xs) => {
|
|
48
|
+
const s = [...xs].sort((x, y) => x - y);
|
|
49
|
+
if (!s.length) return null;
|
|
50
|
+
const m = Math.floor(s.length / 2);
|
|
51
|
+
return s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2;
|
|
52
|
+
};
|
|
53
|
+
const round = (x) => Math.round(x * 10) / 10;
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Your guesses against what happened: { rows, finish: { right, of }, time: { ratio, of }, review:
|
|
57
|
+
* { right, heavier, lighter, of }, kinds: [{ kind, label, of, missed }], agents: { held, of } }.
|
|
58
|
+
*/
|
|
59
|
+
export function calibration(views) {
|
|
60
|
+
const rows = views
|
|
61
|
+
.filter((a) => a.guess)
|
|
62
|
+
.map((a) => ({ id: a.id, name: a.name, kind: kindOf(a.intent), guess: a.guess, actual: actualOf(a) }))
|
|
63
|
+
.filter((r) => r.actual);
|
|
64
|
+
const pick = (k) => rows.filter((r) => r.guess[k] != null && r.actual[k] != null);
|
|
65
|
+
const fin = pick('finish');
|
|
66
|
+
const time = pick('hours');
|
|
67
|
+
const rev = pick('review');
|
|
68
|
+
const idx = (l) => REVIEW.indexOf(l);
|
|
69
|
+
const missed = (r) =>
|
|
70
|
+
(r.guess.finish && r.actual.finish && r.guess.finish !== r.actual.finish) ||
|
|
71
|
+
(r.guess.review && r.actual.review && r.guess.review !== r.actual.review) ||
|
|
72
|
+
(r.guess.hours && r.actual.hours && (r.actual.hours / r.guess.hours > 2 || r.actual.hours / r.guess.hours < 0.5));
|
|
73
|
+
const kinds = [...new Set(rows.map((r) => r.kind))]
|
|
74
|
+
.map((kind) => {
|
|
75
|
+
const of = rows.filter((r) => r.kind === kind);
|
|
76
|
+
return { kind, label: KIND_LABEL[kind] ?? kind, of: of.length, missed: of.filter(missed).length };
|
|
77
|
+
})
|
|
78
|
+
.sort((x, y) => y.missed / y.of - x.missed / x.of || y.of - x.of);
|
|
79
|
+
// The agents' own confidence, on the same settled work: 80% or more said, and it finished.
|
|
80
|
+
const conf = views.map((a) => ({ c: a.brief?.results?.confidence?.percent, act: actualOf(a) })).filter((x) => Number.isFinite(x.c) && x.c >= 80 && x.act?.finish);
|
|
81
|
+
return {
|
|
82
|
+
rows,
|
|
83
|
+
finish: { right: fin.filter((r) => r.guess.finish === r.actual.finish).length, of: fin.length },
|
|
84
|
+
time: { ratio: time.length ? round(median(time.map((r) => r.actual.hours / r.guess.hours))) : null, of: time.length },
|
|
85
|
+
review: { right: rev.filter((r) => r.guess.review === r.actual.review).length, heavier: rev.filter((r) => idx(r.actual.review) > idx(r.guess.review)).length, lighter: rev.filter((r) => idx(r.actual.review) < idx(r.guess.review)).length, of: rev.length },
|
|
86
|
+
kinds,
|
|
87
|
+
agents: { held: conf.filter((x) => x.act.finish === 'yes').length, of: conf.length },
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** The few sentences it comes to. */
|
|
92
|
+
export function calibrationLines(c) {
|
|
93
|
+
if (!c.rows.length) return ['No guess has settled yet. Guess when you start an agent (New agent, Your guess), and come back once its work is done.'];
|
|
94
|
+
const out = [];
|
|
95
|
+
if (c.finish.of) out.push(`Whether it finishes: right ${c.finish.right} of ${c.finish.of} times.`);
|
|
96
|
+
if (c.time.of) {
|
|
97
|
+
const r = c.time.ratio;
|
|
98
|
+
out.push(r >= 1.3 ? `Time: it takes ${r}× what you guess (the middle of ${c.time.of}).` : r <= 0.77 ? `Time: it takes ${r}× what you guess: quicker than you think (the middle of ${c.time.of}).` : `Time: about what you guess (${r}×, the middle of ${c.time.of}).`);
|
|
99
|
+
}
|
|
100
|
+
if (c.review.of) out.push(`Reading it needs: right ${c.review.right} of ${c.review.of}${c.review.heavier ? `; ${c.review.heavier} needed more than you guessed` : ''}${c.review.lighter ? `; ${c.review.lighter} less` : ''}.`);
|
|
101
|
+
const worst = c.kinds.find((k) => k.missed && k.of >= 2);
|
|
102
|
+
if (worst) out.push(`Most often off: ${worst.label.toLowerCase()} (${worst.missed} of ${worst.of}). Spend your attention there, or write those briefs more fully.`);
|
|
103
|
+
if (c.agents.of) out.push(`For comparison, the agents' own confidence of 80% or more held up ${c.agents.held} of ${c.agents.of} times.`);
|
|
104
|
+
return out;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export function calibrationMarkdown(c) {
|
|
108
|
+
const out = ['# Your calibration', '', ...calibrationLines(c), ''];
|
|
109
|
+
if (c.rows.length) {
|
|
110
|
+
out.push('| Agent | Kind | Finishes | Hours | Reading |', '|---|---|---|---|---|');
|
|
111
|
+
const cell = (g, a, word = (x) => x) => (g == null ? '–' : `${word(g)} → ${a == null ? '?' : word(a)}`);
|
|
112
|
+
for (const r of c.rows) out.push(`| ${r.name} | ${KIND_LABEL[r.kind] ?? r.kind} | ${cell(r.guess.finish, r.actual.finish)} | ${cell(r.guess.hours, r.actual.hours)} | ${cell(r.guess.review, r.actual.review, (x) => REVIEW_WORD[x])} |`);
|
|
113
|
+
}
|
|
114
|
+
return out.join('\n').trimEnd();
|
|
115
|
+
}
|
package/src/cli.js
CHANGED
|
@@ -865,6 +865,37 @@ export async function main(argv) {
|
|
|
865
865
|
u.data.questions.forEach((x, i) => console.log(`${bold(`${i + 1}.`)} ${x.answer}${x.why ? dim(` ${x.why}`) : ''}${x.file ? dim(`\n read: ${x.file}${x.head ? ` ${x.head}` : ''}`) : ''}`));
|
|
866
866
|
});
|
|
867
867
|
|
|
868
|
+
program
|
|
869
|
+
.command('glance')
|
|
870
|
+
.description('Every agent on one line, grouped by what it needs from you: needs you now (a prompt, a question it stopped at, a sign-in, an error, stuck), to fix (failing checks, changes requested, a conflict, blocked), to review, to answer (questions asked without stopping), working, to follow up, to tidy up, and idle; each with why. Exit 1 when something needs you now or is to fix.')
|
|
871
|
+
.option('-a, --all', 'list the idle agents too')
|
|
872
|
+
.option('-o, --out <file>', 'write it as Markdown to a file')
|
|
873
|
+
.option('--json', 'print JSON')
|
|
874
|
+
.action(async (o) => {
|
|
875
|
+
await daemon();
|
|
876
|
+
const g = await api('GET', `/glance${o.all ? '?all=1' : ''}`);
|
|
877
|
+
if (o.json) return console.log(JSON.stringify(g, null, 2));
|
|
878
|
+
if (o.out) {
|
|
879
|
+
fs.writeFileSync(o.out, `${g.markdown}\n`);
|
|
880
|
+
console.log(`${green('✓')} written to ${o.out}`);
|
|
881
|
+
} else {
|
|
882
|
+
console.log(bold(g.line));
|
|
883
|
+
const tone = { act: red, fix: yellow, review: cyan, answer: cyan, working: green, follow: yellow, tidy: dim, quiet: dim };
|
|
884
|
+
const label = { act: 'Needs you now', fix: 'To fix', review: 'To review', answer: 'To answer', working: 'Working', follow: 'Follow up', tidy: 'Tidy up', quiet: 'Idle' };
|
|
885
|
+
for (const key of Object.keys(label)) {
|
|
886
|
+
const list = g.items.filter((i) => i.group === key);
|
|
887
|
+
if (!list.length) continue;
|
|
888
|
+
if (key === 'quiet' && !o.all) {
|
|
889
|
+
console.log(dim(`\n${list.length} idle (agentmgr glance --all to list them)`));
|
|
890
|
+
continue;
|
|
891
|
+
}
|
|
892
|
+
console.log(`\n${tone[key](label[key])} ${dim(`(${list.length})`)}`);
|
|
893
|
+
for (const i of list) console.log(` ${bold(i.name)} ${dim(i.id)}${i.project ? dim(` ${i.project}`) : ''}\n ${i.why.slice(0, 3).join(dim(' · '))}`);
|
|
894
|
+
}
|
|
895
|
+
}
|
|
896
|
+
if (g.counts.act || g.counts.fix) process.exitCode = 1;
|
|
897
|
+
});
|
|
898
|
+
|
|
868
899
|
program
|
|
869
900
|
.command('read-first')
|
|
870
901
|
.description('Finished work waiting for your review, the pieces that need reading most first: each with a level (read closely, look, skim), the reasons from what the app measured (high-risk files, the scorecard, checks, whether the tests notice a mistake, what was left out, risks not checked, its own confidence, size), and where to start. Exit 1 when something is to be read closely.')
|
|
@@ -2529,6 +2560,102 @@ export async function main(argv) {
|
|
|
2529
2560
|
table(cps.map((c) => [`#${c.n}`, c.at.replace('T', ' ').slice(0, 19), c.sha.slice(0, 9), (c.prompt ?? '').slice(0, 60)]), ['N', 'AT', 'SNAPSHOT', 'PROMPT']);
|
|
2530
2561
|
});
|
|
2531
2562
|
|
|
2563
|
+
program
|
|
2564
|
+
.command('guess')
|
|
2565
|
+
.description('Your guess for an agent, kept private and set against what happens (agentmgr calibration): whether it finishes, how many hours it takes, how much reading it needs')
|
|
2566
|
+
.argument('<agent>')
|
|
2567
|
+
.option('--finish <yes|no>', 'whether it finishes')
|
|
2568
|
+
.option('--hours <n>', 'how long it takes, in hours')
|
|
2569
|
+
.option('--review <skim|look|close>', 'how much reading its work needs')
|
|
2570
|
+
.action(async (ref, o) => {
|
|
2571
|
+
await daemon();
|
|
2572
|
+
const a = await resolveAgent(ref);
|
|
2573
|
+
const v = await api('PUT', `/agents/${a.id}/guess`, { finish: o.finish, hours: o.hours, review: o.review });
|
|
2574
|
+
console.log(v.guess ? `${green('✓')} guessed for ${bold(v.name)}: ${[v.guess.finish && `finishes: ${v.guess.finish}`, v.guess.hours && `${v.guess.hours} h`, v.guess.review && `reading: ${v.guess.review}`].filter(Boolean).join(', ')}` : dim('guess cleared'));
|
|
2575
|
+
});
|
|
2576
|
+
program
|
|
2577
|
+
.command('calibration')
|
|
2578
|
+
.description("Your calibration: your guesses when agents started, against what happened (finishing, time, the reading their work needed), by kind of work, next to how the agents' own confidence held up. Private to this computer")
|
|
2579
|
+
.option('--json', 'print JSON')
|
|
2580
|
+
.action(async (o) => {
|
|
2581
|
+
await daemon();
|
|
2582
|
+
const c = await api('GET', '/calibration?format=md');
|
|
2583
|
+
if (o.json) return console.log(JSON.stringify(c, null, 2));
|
|
2584
|
+
console.log(c.markdown);
|
|
2585
|
+
});
|
|
2586
|
+
|
|
2587
|
+
program
|
|
2588
|
+
.command('night-watch')
|
|
2589
|
+
.description("Does merged work still hold on the latest main? For work merged in the last days, the agent's recorded commands are run again against the latest main in a checkout of its own; one that no longer holds names the commits since that changed the same files. Off until turned on (--on); --run runs it now. Exit 1 when something no longer holds")
|
|
2590
|
+
.option('--run', 'run it now (it waits until done)')
|
|
2591
|
+
.option('--on', 'run it every night')
|
|
2592
|
+
.option('--off', 'stop running it at night')
|
|
2593
|
+
.option('--hour <h>', 'the hour it runs at (0-23)')
|
|
2594
|
+
.option('--days <n>', 'how far back merged work is watched')
|
|
2595
|
+
.option('--json', 'print JSON')
|
|
2596
|
+
.action(async (o) => {
|
|
2597
|
+
await daemon();
|
|
2598
|
+
if (o.on || o.off || o.hour || o.days) await api('PUT', '/night-watch', { ...(o.on ? { enabled: true } : o.off ? { enabled: false } : {}), ...(o.hour ? { hour: o.hour } : {}), ...(o.days ? { days: o.days } : {}) });
|
|
2599
|
+
if (o.run) await api('POST', '/night-watch/run', {});
|
|
2600
|
+
const v = await api('GET', '/night-watch?format=md');
|
|
2601
|
+
if (o.json) return console.log(JSON.stringify(v, null, 2));
|
|
2602
|
+
console.log(dim(`${v.settings.enabled ? `On: every night from ${v.settings.hour}:00` : 'Off at night (agentmgr night-watch --on)'}, merged work of the last ${v.settings.days} days`));
|
|
2603
|
+
console.log(v.markdown);
|
|
2604
|
+
if (v.broken) process.exitCode = 1;
|
|
2605
|
+
});
|
|
2606
|
+
|
|
2607
|
+
program
|
|
2608
|
+
.command('fence')
|
|
2609
|
+
.description('Scope fence: the areas of code it changes that what it was asked and planned does not name (tests, docs and config never count). Allow an area, or pull it back. Exit 1 while it drifts')
|
|
2610
|
+
.argument('<agent>')
|
|
2611
|
+
.option('--allow <area>', 'that area belongs to the task: in scope from now on')
|
|
2612
|
+
.option('--pull', 'tell it to stay within its task and undo those changes unless they are needed')
|
|
2613
|
+
.action(async (ref, o) => {
|
|
2614
|
+
await daemon();
|
|
2615
|
+
let a = await resolveAgent(ref);
|
|
2616
|
+
if (o.allow || o.pull) a = await api('POST', `/agents/${a.id}/fence`, o.allow ? { allow: o.allow } : { pull: true });
|
|
2617
|
+
const drift = a.fence?.drift ?? [];
|
|
2618
|
+
if (o.pull) console.log(`${green('✓')} told to stay within its task`);
|
|
2619
|
+
if (!drift.length) return console.log(dim(`${a.name}: nothing outside its task${a.fence?.allowed?.length ? ` (allowed: ${a.fence.allowed.join(', ')})` : ''}`));
|
|
2620
|
+
console.log(`${yellow('Outside its task')} ${bold(a.name)}`);
|
|
2621
|
+
for (const d of drift) console.log(` ${bold(d.area)} ${dim(`${d.files.length} files, ${d.lines} lines: ${d.files.slice(0, 4).join(', ')}`)}`);
|
|
2622
|
+
console.log(dim(` agentmgr fence ${a.id} --allow <area> · agentmgr fence ${a.id} --pull`));
|
|
2623
|
+
process.exitCode = 1;
|
|
2624
|
+
});
|
|
2625
|
+
|
|
2626
|
+
program
|
|
2627
|
+
.command('why')
|
|
2628
|
+
.description("Why is this line here: the moment in the agent's conversation that wrote it (what it was asked, what it said just before, the commands it had just run, and the edit), from its own transcripts")
|
|
2629
|
+
.argument('<agent>')
|
|
2630
|
+
.argument('<place>', 'file:line, a path in its folder')
|
|
2631
|
+
.option('-t, --text <text>', 'the line\'s text instead of a line number')
|
|
2632
|
+
.option('--json', 'print JSON')
|
|
2633
|
+
.action(async (ref, place, o) => {
|
|
2634
|
+
await daemon();
|
|
2635
|
+
const a = await resolveAgent(ref);
|
|
2636
|
+
const m = /^(.+?)(?::(\d+))?$/.exec(place);
|
|
2637
|
+
if (!m[2] && !o.text) throw new Error('Give file:line, or --text');
|
|
2638
|
+
const q = new URLSearchParams({ file: m[1], format: 'md', ...(m[2] ? { line: m[2] } : {}), ...(o.text ? { text: o.text } : {}) });
|
|
2639
|
+
const b = await api('GET', `/agents/${a.id}/why?${q}`);
|
|
2640
|
+
if (o.json) return console.log(JSON.stringify(b, null, 2));
|
|
2641
|
+
console.log(b.markdown);
|
|
2642
|
+
if (!b.found) process.exitCode = 1;
|
|
2643
|
+
});
|
|
2644
|
+
|
|
2645
|
+
program
|
|
2646
|
+
.command('try-path')
|
|
2647
|
+
.description('Try the other path: the agent wrote down the ways it weighed (## Options, the one it takes first). Start path N as a second agent from the same base commit, raced against the first: compare them with agentmgr race show, and keep one with agentmgr race pick')
|
|
2648
|
+
.argument('<agent>')
|
|
2649
|
+
.argument('<path>', 'the number of the path, 2 or more')
|
|
2650
|
+
.action(async (ref, n) => {
|
|
2651
|
+
await daemon();
|
|
2652
|
+
const a = await resolveAgent(ref);
|
|
2653
|
+
const race = await api('POST', `/agents/${a.id}/try-path`, { path: Number(n) });
|
|
2654
|
+
const added = race.rows.at(-1);
|
|
2655
|
+
console.log(`${green('+')} ${bold(added.name)} ${dim(added.id)} takes ${added.variant?.instructions ?? `path ${n}`}`);
|
|
2656
|
+
console.log(dim(` raced against ${a.name} in ${race.id}: agentmgr race show ${race.id}`));
|
|
2657
|
+
});
|
|
2658
|
+
|
|
2532
2659
|
const raceCmd = program.command('race').description('Several agents try the same intent; compare and keep the best');
|
|
2533
2660
|
raceCmd
|
|
2534
2661
|
.command('start')
|
package/src/echo.js
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
// Bug echo: one mistake, found in every agent at once. When a lesson is accepted in a repository's
|
|
2
|
+
// standards (often the one proposed from an incident or a revert), later agents are given it, but
|
|
3
|
+
// the ones already at work are not. So each of them with changes in that repository is checked now:
|
|
4
|
+
// a model reads its diff against the lesson and says whether it makes the same mistake, and where.
|
|
5
|
+
// One that does is flagged (Glance: to fix; its Results), and you can tell it, or say it is not
|
|
6
|
+
// the same. A diff already checked against a lesson is not checked again until it changes.
|
|
7
|
+
import crypto from 'node:crypto';
|
|
8
|
+
import { NO_REPO } from './manager.js';
|
|
9
|
+
|
|
10
|
+
const MAX_DIFF = 40_000;
|
|
11
|
+
const clip = (s, n) => String(s ?? '').replace(/\s+/g, ' ').trim().slice(0, n);
|
|
12
|
+
|
|
13
|
+
export function echoPrompt({ lesson, diff, intent }) {
|
|
14
|
+
return [
|
|
15
|
+
'A lesson was learned in this repository from a change that went wrong. Decide whether the diff below makes the same mistake.',
|
|
16
|
+
'Reply with JSON only: {"repeats": true or false, "where": "file:line of the place, or empty", "why": "one sentence: what in the diff repeats it, or why it does not"}.',
|
|
17
|
+
'Say true only when the diff itself does what the lesson warns against; not for code that merely is near the same subject, and not for what the diff does not touch.',
|
|
18
|
+
'',
|
|
19
|
+
`<lesson>${lesson}</lesson>`,
|
|
20
|
+
`<task>${clip(intent, 600)}</task>`,
|
|
21
|
+
'<diff>',
|
|
22
|
+
diff.length > MAX_DIFF ? `${diff.slice(0, MAX_DIFF)}\n[cut: the diff is longer]` : diff,
|
|
23
|
+
'</diff>',
|
|
24
|
+
].join('\n');
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** The model's answer, or null when it can't be read. */
|
|
28
|
+
export function parseEcho(text) {
|
|
29
|
+
const m = String(text ?? '').match(/\{[\s\S]*\}/);
|
|
30
|
+
if (!m) return null;
|
|
31
|
+
try {
|
|
32
|
+
const j = JSON.parse(m[0]);
|
|
33
|
+
if (typeof j.repeats !== 'boolean') return null;
|
|
34
|
+
return { repeats: j.repeats, where: clip(j.where, 200) || null, why: clip(j.why, 400) || null };
|
|
35
|
+
} catch {
|
|
36
|
+
return null;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** What the agent is told when you send it the echo. */
|
|
41
|
+
export const echoMessage = (e) =>
|
|
42
|
+
`A lesson was learned in this repository from a change that went wrong: "${e.lesson}". Your changes look like they repeat it${e.where ? ` at ${e.where}` : ''}${e.why ? `: ${e.why}` : ''}. Check, and fix it if so; if it is not the same, say why in your brief.`;
|
|
43
|
+
|
|
44
|
+
/** Agents whose open work could repeat a lesson: task agents with a folder, not merged yet. */
|
|
45
|
+
export function openWork(agents, except = null) {
|
|
46
|
+
return agents.filter((a) => {
|
|
47
|
+
if (a.id === except || NO_REPO.has(a.kind) || a.kind !== 'task' || a.reviewing || a.hunting || !a.workdir) return false;
|
|
48
|
+
const prs = Object.values(a.prs ?? {}).filter((p) => p.source !== 'mentioned');
|
|
49
|
+
return !prs.some((p) => p.state === 'MERGED' || p.state === 'CLOSED');
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export class Echo {
|
|
54
|
+
constructor({ manager, standards, review, log = () => {} }) {
|
|
55
|
+
this.manager = manager;
|
|
56
|
+
this.standards = standards;
|
|
57
|
+
this.review = review;
|
|
58
|
+
this.log = log;
|
|
59
|
+
this.running = new Set();
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Check the open work in repository `key` against `lesson` (accepted). Returns how many were checked. */
|
|
63
|
+
async run(key, lesson) {
|
|
64
|
+
if (!lesson?.text || lesson.state !== 'accepted') return 0;
|
|
65
|
+
const agents = openWork(this.standards.agentsOf(key), lesson.source?.agentId ?? null);
|
|
66
|
+
let n = 0;
|
|
67
|
+
for (const a of agents) {
|
|
68
|
+
if (await this.check(a.id, lesson).catch((e) => this.log(`bug echo: ${a.name}: ${e.message}`))) n++;
|
|
69
|
+
}
|
|
70
|
+
return n;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** One agent against one lesson; kept on the agent as echoes[lessonId]. */
|
|
74
|
+
async check(id, lesson) {
|
|
75
|
+
const k = `${id}:${lesson.id}`;
|
|
76
|
+
if (this.running.has(k)) return false;
|
|
77
|
+
this.running.add(k);
|
|
78
|
+
try {
|
|
79
|
+
const { diff } = await this.review.get(id);
|
|
80
|
+
if (!diff?.trim()) return false;
|
|
81
|
+
const hash = crypto.createHash('sha1').update(`${lesson.text}\n${diff}`).digest('hex').slice(0, 12);
|
|
82
|
+
const agent = this.manager.get(id);
|
|
83
|
+
const prev = agent?.echoes?.[lesson.id];
|
|
84
|
+
if (!agent || prev?.hash === hash) return false;
|
|
85
|
+
const r = await this.manager.ladderShot(agent, echoPrompt({ lesson: lesson.text, diff, intent: agent.intent }), { timeoutMs: 180_000 });
|
|
86
|
+
const found = parseEcho(r.text);
|
|
87
|
+
if (!found) return false;
|
|
88
|
+
const now = this.manager.get(id);
|
|
89
|
+
if (!now) return false;
|
|
90
|
+
this.manager.patch(id, { echoes: { ...now.echoes, [lesson.id]: { lesson: lesson.text, ...found, hash, by: r.by ?? null, at: new Date().toISOString(), state: found.repeats ? 'open' : 'clear' } } });
|
|
91
|
+
return true;
|
|
92
|
+
} finally {
|
|
93
|
+
this.running.delete(k);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** You on a flagged one: 'tell' (it is sent the echo) or 'dismiss' (not the same). */
|
|
98
|
+
act(id, lessonId, what) {
|
|
99
|
+
const agent = this.manager.mustGet(id);
|
|
100
|
+
const e = agent.echoes?.[lessonId];
|
|
101
|
+
if (!e || !e.repeats) throw Object.assign(new Error('Nothing flagged for that lesson'), { status: 404 });
|
|
102
|
+
if (what === 'tell') this.manager.tell(id, echoMessage(e), { source: 'echo' });
|
|
103
|
+
else if (what !== 'dismiss') throw Object.assign(new Error('tell or dismiss'), { status: 400 });
|
|
104
|
+
this.manager.patch(id, { echoes: { ...agent.echoes, [lessonId]: { ...e, state: what === 'tell' ? 'told' : 'dismissed', doneAt: new Date().toISOString() } } });
|
|
105
|
+
return this.manager.view(this.manager.get(id));
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** The flagged ones still to act on, for Glance and the Results. */
|
|
110
|
+
export const openEchoes = (a) => Object.entries(a.echoes ?? {}).filter(([, e]) => e.repeats && e.state === 'open').map(([id, e]) => ({ id, ...e }));
|
package/src/fence.js
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
// Scope fence: an agent asked to fix login that starts rewriting payments is not stuck, it is
|
|
2
|
+
// wandering. The areas of the code it changed (a folder such as src/payments) are set against
|
|
3
|
+
// what it was asked and planned (INTENT, SPEC, PLAN, its brief): an area none of them names,
|
|
4
|
+
// changed in more than a line or two, is drift. Tests, docs and config are never drift, and an
|
|
5
|
+
// area the person allowed is in scope from then on. When the intent and plan name no area at all,
|
|
6
|
+
// nothing can be judged and nothing is said. No model is asked: each area is a fact to check.
|
|
7
|
+
|
|
8
|
+
// Folders that hold modules: their area is one level deeper (src/payments, packages/api).
|
|
9
|
+
const CONTAINERS = new Set(['src', 'lib', 'app', 'apps', 'packages', 'services', 'internal', 'pkg', 'cmd', 'modules', 'components', 'server', 'client', 'web', 'api']);
|
|
10
|
+
const MIN_FILES = 2;
|
|
11
|
+
const MIN_LINES = 30;
|
|
12
|
+
|
|
13
|
+
/** The area of a file: its module folder, or "(top)" for a file at the top. */
|
|
14
|
+
export function areaOf(file) {
|
|
15
|
+
const parts = String(file).split('/').filter(Boolean);
|
|
16
|
+
if (parts.length < 2) return '(top)';
|
|
17
|
+
if (CONTAINERS.has(parts[0]) && parts.length > 2) return `${parts[0]}/${parts[1]}`;
|
|
18
|
+
return parts[0];
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** Tests, docs and config: changed along with any work, never a sign of drift. */
|
|
22
|
+
export function incidental(file) {
|
|
23
|
+
const f = String(file).toLowerCase();
|
|
24
|
+
const base = f.split('/').pop();
|
|
25
|
+
return (
|
|
26
|
+
/(^|\/)(tests?|__tests__|spec|e2e|fixtures|docs?|\.github|\.vscode)\//.test(f) ||
|
|
27
|
+
/\.(test|spec)\.[a-z]+$|_test\.[a-z]+$|\.(md|txt|rst|lock)$/.test(f) ||
|
|
28
|
+
/^(package(-lock)?\.json|yarn\.lock|pnpm-lock\.yaml|tsconfig.*\.json|\.gitignore|\.eslintrc.*|\.prettierrc.*|dockerfile|makefile|readme.*|changelog.*|license.*)$/.test(base) ||
|
|
29
|
+
/\.config\.[a-z]+$/.test(base)
|
|
30
|
+
);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const words = (s) => new Set(String(s ?? '').toLowerCase().split(/[^a-z0-9_-]+/).filter((w) => w.length >= 3));
|
|
34
|
+
|
|
35
|
+
/** Whether the text names an area: its path, its folder name, or one of its files. */
|
|
36
|
+
function named(area, files, text, ws) {
|
|
37
|
+
if (area === '(top)') return files.some((f) => text.includes(f.toLowerCase()) || ws.has(f.split('/').pop().replace(/\.[^.]+$/, '').toLowerCase()));
|
|
38
|
+
const a = area.toLowerCase();
|
|
39
|
+
const leaf = a.split('/').pop();
|
|
40
|
+
if (text.includes(a) || (leaf.length >= 4 && ws.has(leaf))) return true;
|
|
41
|
+
// A singular or plural of the folder ("payment" for payments).
|
|
42
|
+
if (leaf.length >= 5 && (ws.has(leaf.replace(/s$/, '')) || ws.has(`${leaf}s`))) return true;
|
|
43
|
+
return files.some((f) => {
|
|
44
|
+
const base = f.split('/').pop().toLowerCase();
|
|
45
|
+
const stem = base.replace(/\.[^.]+$/, '');
|
|
46
|
+
return text.includes(f.toLowerCase()) || text.includes(base) || (stem.length >= 4 && ws.has(stem));
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* The fence: { judged, areas: [{ area, files, lines, inScope, why }], drift: [the out-of-scope
|
|
52
|
+
* areas big enough to mention] }. `files`: { path: { added, removed } } (what it changed so far);
|
|
53
|
+
* `text`: what it was asked and planned; `allowed`: areas the person said are fine.
|
|
54
|
+
*/
|
|
55
|
+
export function fenceOf({ files = {}, text = '', allowed = [] }) {
|
|
56
|
+
const t = String(text).toLowerCase();
|
|
57
|
+
const ws = words(text);
|
|
58
|
+
const by = new Map();
|
|
59
|
+
for (const [f, c] of Object.entries(files)) {
|
|
60
|
+
if (incidental(f)) continue;
|
|
61
|
+
const a = areaOf(f);
|
|
62
|
+
const e = by.get(a) ?? by.set(a, { area: a, files: [], lines: 0 }).get(a);
|
|
63
|
+
e.files.push(f);
|
|
64
|
+
e.lines += (c?.added ?? 0) + (c?.removed ?? 0);
|
|
65
|
+
}
|
|
66
|
+
const areas = [...by.values()].map((e) => {
|
|
67
|
+
const ok = allowed.includes(e.area) ? 'allowed by you' : named(e.area, e.files, t, ws) ? 'named in what it was asked or planned' : null;
|
|
68
|
+
return { ...e, files: e.files.sort(), inScope: Boolean(ok), why: ok ?? 'not named in what it was asked or planned' };
|
|
69
|
+
});
|
|
70
|
+
// Nothing in the intent or plan names any area it changed: a vague task, which can't be fenced.
|
|
71
|
+
const judged = areas.some((a) => a.inScope && a.why !== 'allowed by you');
|
|
72
|
+
const drift = judged ? areas.filter((a) => !a.inScope && (a.files.length >= MIN_FILES || a.lines >= MIN_LINES)).sort((x, y) => y.lines - x.lines) : [];
|
|
73
|
+
return { judged, areas: areas.sort((x, y) => y.lines - x.lines), drift };
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** One line for a drift: "src/payments (3 files, 80 lines)". */
|
|
77
|
+
export const driftLine = (d) => `${d.area} (${d.files.length} file${d.files.length === 1 ? '' : 's'}, ${d.lines} line${d.lines === 1 ? '' : 's'})`;
|
|
78
|
+
|
|
79
|
+
/** What the agent is told when the person pulls it back. */
|
|
80
|
+
export const pullBackMessage = (drift) =>
|
|
81
|
+
`You have been changing code outside what you were asked and planned: ${drift.map(driftLine).join('; ')}. Stay within the task. Undo those changes unless the task cannot be done without them; if it cannot, say why in your brief and keep them as small as you can.`;
|