ai-agentmanager 1.62.0 → 1.64.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 +40 -0
- package/README.md +109 -0
- package/package.json +1 -1
- package/public/acceptance.js +194 -0
- package/public/app.js +84 -3
- package/public/attach.js +4 -0
- package/public/autonomy.js +144 -0
- package/public/boardcols.js +1 -0
- package/public/dropzone.js +203 -0
- package/public/groups.js +2 -0
- package/public/index.html +63 -0
- package/public/machine.js +2 -0
- package/public/menu.js +20 -0
- package/public/proof.js +114 -0
- package/public/scorecard.js +1 -1
- package/public/standup.js +1 -0
- package/public/style.css +61 -2
- package/src/acceptance.js +123 -0
- package/src/advisor.js +30 -8
- package/src/autonomy.js +684 -0
- package/src/autopilot.js +9 -1
- package/src/backlog.js +16 -3
- package/src/brief.js +24 -3
- package/src/bughunt.js +1 -0
- package/src/cli.js +171 -3
- package/src/config.js +5 -0
- package/src/decisions.js +5 -1
- package/src/engines/claude.js +4 -2
- package/src/groundrules.js +97 -0
- package/src/inbox.js +48 -0
- package/src/judge.js +1 -1
- package/src/manager.js +184 -7
- package/src/notify.js +16 -0
- package/src/prereview.js +7 -2
- package/src/proof.js +255 -0
- package/src/scorecard.js +40 -10
- package/src/server.js +66 -4
- package/src/service.js +24 -3
- package/src/standup.js +1 -0
package/src/autonomy.js
ADDED
|
@@ -0,0 +1,684 @@
|
|
|
1
|
+
// Autonomy: how far an agent goes without the person. One level per agent:
|
|
2
|
+
// ask - today's flow: questions, stuck findings and follow-ups wait in the inbox.
|
|
3
|
+
// run - "agree, then run": the person agrees on what done means (acceptance.js), and the middle
|
|
4
|
+
// is handled for them. A question in QUESTIONS.md or a plan waiting for review is decided
|
|
5
|
+
// by Decide (advisor.js) at its "most things" level, whatever the project's level is; a
|
|
6
|
+
// question the agent stopped on in its terminal is answered here from what is already
|
|
7
|
+
// decided (the request, the agreed points, the ground rules, the repository's lessons,
|
|
8
|
+
// earlier answers); a nudge the judge is sure of is sent; a quiet, unfinished agent is
|
|
9
|
+
// told to carry on. Each is recorded, and an answer shows in the inbox as "Answered for
|
|
10
|
+
// you", where the person can change it.
|
|
11
|
+
// pr - and its pull request is opened when the work is ready (review rounds for an agent,
|
|
12
|
+
// autopilot for a backlog item), also when that is turned off in general.
|
|
13
|
+
// merge - and the pull request is merged when its checks pass, the review found it ready and it
|
|
14
|
+
// touches no high-risk path.
|
|
15
|
+
// What never happens here: a permission prompt is never answered by a model, a question about
|
|
16
|
+
// deleting, publishing, money, credentials or scope is left for the person, and an agent cannot
|
|
17
|
+
// raise its own level (server.js refuses its calls).
|
|
18
|
+
//
|
|
19
|
+
// The model calls made here run on a list of models, best first ("fable", "opus", "sonnet" by
|
|
20
|
+
// default): the first one that answers is used, and one that fails is skipped for a while.
|
|
21
|
+
import crypto from 'node:crypto';
|
|
22
|
+
import fs from 'node:fs';
|
|
23
|
+
import { parseJsonReply, specPath } from './brief.js';
|
|
24
|
+
import { FREE_CHOICE } from './inbox.js';
|
|
25
|
+
import { memoryKey, memoryText } from './memory.js';
|
|
26
|
+
import { landState } from './tracker.js';
|
|
27
|
+
|
|
28
|
+
export const LEVELS = ['ask', 'run', 'pr', 'merge'];
|
|
29
|
+
export const LEVEL_LABEL = { ask: 'Ask me', run: 'Agree, then run', pr: 'Run to pull request', merge: 'Run to merge' };
|
|
30
|
+
export const AUTONOMY_DEFAULTS = {
|
|
31
|
+
level: 'ask', // for new agents that name none
|
|
32
|
+
models: ['fable', 'opus', 'sonnet'], // best first; the next one when a call fails
|
|
33
|
+
answers: true,
|
|
34
|
+
nudges: true,
|
|
35
|
+
followUps: true,
|
|
36
|
+
minConfidence: 0.7, // of the model, to act on its answer or its nudge
|
|
37
|
+
minBuildConfidence: 70, // of the agent in its own work (its brief), to merge without the person
|
|
38
|
+
maxAnswers: 12, // per agent
|
|
39
|
+
maxNudges: 3,
|
|
40
|
+
maxFollowUps: 2,
|
|
41
|
+
dailyCalls: 80,
|
|
42
|
+
retryMin: 15, // a model that failed is skipped this long
|
|
43
|
+
};
|
|
44
|
+
const LOG_KEEP = 40;
|
|
45
|
+
const SEEN_KEEP = 200;
|
|
46
|
+
|
|
47
|
+
const now = () => new Date().toISOString();
|
|
48
|
+
const today = () => new Date().toISOString().slice(0, 10);
|
|
49
|
+
const err = (status, message) => Object.assign(new Error(message), { status });
|
|
50
|
+
const hash = (s) => crypto.createHash('sha1').update(String(s)).digest('hex').slice(0, 10);
|
|
51
|
+
const clip = (s, n) => {
|
|
52
|
+
const t = String(s ?? '').replace(/\s+/g, ' ').trim();
|
|
53
|
+
return t.length > n ? `${t.slice(0, n - 1)}…` : t;
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
/** A level by its name ("pr", "Run to pull request", "off"); null when it is none of them. */
|
|
57
|
+
export function parseLevel(v) {
|
|
58
|
+
const t = String(v ?? '').trim().toLowerCase();
|
|
59
|
+
if (!t) return null;
|
|
60
|
+
if (LEVELS.includes(t)) return t;
|
|
61
|
+
if (['off', 'none', 'no', 'false'].includes(t)) return 'ask';
|
|
62
|
+
if (['on', 'true', 'yes'].includes(t)) return 'run';
|
|
63
|
+
return LEVELS.find((l) => LEVEL_LABEL[l].toLowerCase() === t) ?? null;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export const levelOf = (agent) => (LEVELS.includes(agent?.autonomy?.level) ? agent.autonomy.level : 'ask');
|
|
67
|
+
export const atLeast = (level, min) => LEVELS.indexOf(level) >= LEVELS.indexOf(min);
|
|
68
|
+
|
|
69
|
+
/** Settings from config.json's "autonomy", with defaults. `models`: names, or { engine, model }. */
|
|
70
|
+
export function autonomySettings(config = {}) {
|
|
71
|
+
const c = config.autonomy ?? {};
|
|
72
|
+
const n = (v, d, lo, hi) => (Number.isFinite(Number(v)) && v !== null && v !== '' ? Math.max(lo, Math.min(hi, Number(v))) : d);
|
|
73
|
+
const models = cleanModels(c.models);
|
|
74
|
+
const d = AUTONOMY_DEFAULTS;
|
|
75
|
+
return {
|
|
76
|
+
level: parseLevel(c.level) ?? d.level,
|
|
77
|
+
models: models.length ? models : d.models,
|
|
78
|
+
answers: c.answers !== false,
|
|
79
|
+
nudges: c.nudges !== false,
|
|
80
|
+
followUps: c.followUps !== false,
|
|
81
|
+
minConfidence: n(c.minConfidence, d.minConfidence, 0.5, 1),
|
|
82
|
+
minBuildConfidence: n(c.minBuildConfidence, d.minBuildConfidence, 0, 100),
|
|
83
|
+
maxAnswers: n(c.maxAnswers, d.maxAnswers, 0, 100),
|
|
84
|
+
maxNudges: n(c.maxNudges, d.maxNudges, 0, 20),
|
|
85
|
+
maxFollowUps: n(c.maxFollowUps, d.maxFollowUps, 0, 20),
|
|
86
|
+
dailyCalls: n(c.dailyCalls, d.dailyCalls, 0, 2000),
|
|
87
|
+
retryMin: n(c.retryMin, d.retryMin, 1, 1440),
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** A list of models as given ("fable, opus", ["fable", { engine, model }]), cleaned: no empty ones, no repeats, six at most. */
|
|
92
|
+
export function cleanModels(input) {
|
|
93
|
+
const list = typeof input === 'string' ? input.split(/[,\s>]+/) : Array.isArray(input) ? input : [];
|
|
94
|
+
const out = [];
|
|
95
|
+
const seen = new Set();
|
|
96
|
+
for (const m of list) {
|
|
97
|
+
const item = typeof m === 'string' ? m.trim() : m && typeof m.model === 'string' ? { ...(m.engine ? { engine: String(m.engine) } : {}), model: m.model.trim() } : null;
|
|
98
|
+
const name = typeof item === 'string' ? item : item?.model;
|
|
99
|
+
if (!name || !/^[\w.:\/\[\]-]{1,80}$/.test(name)) continue;
|
|
100
|
+
const key = typeof item === 'string' ? item : `${item.engine ?? ''}/${item.model}`;
|
|
101
|
+
if (seen.has(key)) continue;
|
|
102
|
+
seen.add(key);
|
|
103
|
+
out.push(item);
|
|
104
|
+
}
|
|
105
|
+
return out.slice(0, 6);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export const modelName = (m) => (typeof m === 'string' ? m : m?.model ? `${m.engine?.label ?? m.engine ?? ''}${m.engine ? ' ' : ''}${m.model}`.trim() : m?.engine?.label ?? 'the default model');
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Run `call(model)` on the first model that answers, best first. A model that failed within
|
|
112
|
+
* `retryMs` is tried only after the others. `down` (model name -> when it failed) is kept by the
|
|
113
|
+
* caller between calls. Resolves to { text, model, tried: [{ model, error }] }; rejects when none answered.
|
|
114
|
+
*/
|
|
115
|
+
export async function callLadder(models, call, { down = new Map(), retryMs = 15 * 60_000, t = Date.now() } = {}) {
|
|
116
|
+
const isDown = (m) => t - (down.get(modelName(m)) ?? -Infinity) < retryMs;
|
|
117
|
+
const order = [...models.filter((m) => !isDown(m)), ...models.filter(isDown)];
|
|
118
|
+
const tried = [];
|
|
119
|
+
for (const model of order) {
|
|
120
|
+
try {
|
|
121
|
+
const text = await call(model);
|
|
122
|
+
down.delete(modelName(model));
|
|
123
|
+
return { text, model, tried };
|
|
124
|
+
} catch (e) {
|
|
125
|
+
down.set(modelName(model), Date.now());
|
|
126
|
+
tried.push({ model: modelName(model), error: String(e?.message ?? e).slice(0, 200) });
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
throw Object.assign(new Error(`No model answered (${tried.map((x) => x.model).join(', ') || 'none configured'})${tried.length ? `: ${tried.at(-1).error}` : ''}`), { tried });
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// Questions that are the person's whatever the sources say: the words that go with what cannot be
|
|
133
|
+
// taken back, costs money, or reaches outside the repository.
|
|
134
|
+
const SENSITIVE = [
|
|
135
|
+
[/\b(delet\w*|drop(?:ping)?\s+(?:the\s+)?(?:table|database|column|index)|truncat\w*|wip\w+|eras\w+|rm\s+-rf|overwrit\w+)\b/i, 'deleting or overwriting'],
|
|
136
|
+
[/\b(force[- ]?push\w*|rewrit\w+\s+(?:the\s+)?history|reset\s+--hard|rebase\s+(?:onto\s+)?(?:main|master))\b/i, 'rewriting history'],
|
|
137
|
+
[/\b(deploy\w*|publish\w*|releas\w+|ship\s+to|go\s+live|production|prod\b|merge\s+(?:it|this|the\s+(?:pull\s+request|pr|branch))|npm\s+publish)\b/i, 'publishing, deploying or merging'],
|
|
138
|
+
[/\b(password|credential\w*|secret\w*|api[- ]?keys?|private\s+keys?|access\s+tokens?|auth\s+tokens?)\b/i, 'credentials'],
|
|
139
|
+
[/\b(pay(?:ment|ing)?|purchas\w+|billing|invoice\w*|subscription|pricing|paid\s+plan|cost\s+money|licen[cs]e\w*|legal)\b/i, 'money, licences or legal matters'],
|
|
140
|
+
[/\b(personal\s+data|pii|customer\s+data|user\s+data|gdpr|privacy)\b/i, 'personal data'],
|
|
141
|
+
[/\b(send\s+(?:an?\s+)?(?:email|message)|email\s+(?:the|to)|post\s+(?:to|in|on)\s+(?:slack|the\s+channel)|notify\s+(?:the\s+)?(?:customer|client|team))\b/i, 'sending something to other people'],
|
|
142
|
+
[/\b(scope|out\s+of\s+scope|drop\s+(?:the\s+)?(?:feature|requirement)|skip\s+(?:the\s+)?(?:tests?|requirement|acceptance))\b/i, 'the scope of the task'],
|
|
143
|
+
];
|
|
144
|
+
|
|
145
|
+
/** Why a question is the person's to answer (a short phrase), or null when a model may look at it. */
|
|
146
|
+
export function sensitive(text) {
|
|
147
|
+
const t = String(text ?? '');
|
|
148
|
+
return SENSITIVE.find(([re]) => re.test(t))?.[1] ?? null;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
const PERMISSION_ASK = /\bdo you want to (?:proceed|allow|make this edit|create|run|overwrite)\b|\b(?:allow|grant|approve)\b.{0,60}\b(?:access|permission|command|tool|edit|read|write)|\bpermission (?:prompt|request|to)\b|\bwaiting for (?:approval|permission)\b|\btrust (?:the files in )?this folder\b/i;
|
|
152
|
+
const PERMISSION_CHOICE = /don'?t ask again|switch to auto mode|\ballow (?:reading|writing|all edits|this|it)\b|\balways allow\b|\bfor this (?:session|project)\b/i;
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* Whether what the screen judge read as a question is the engine's own permission prompt (run this
|
|
156
|
+
* command? allow this read?). Those are never answered for the person, and no model is asked: a
|
|
157
|
+
* numbered Yes/No menu counts, so does the wording of the prompt or of what the judge saw.
|
|
158
|
+
*/
|
|
159
|
+
export function permissionPrompt({ question, options = [], summary } = {}) {
|
|
160
|
+
const opts = options.map((o) => String(o).replace(/^\s*\d+[.)]\s*/, ''));
|
|
161
|
+
if (opts.some((o) => /^yes\b/i.test(o)) && opts.some((o) => /^no\b/i.test(o))) return true;
|
|
162
|
+
if (opts.some((o) => PERMISSION_CHOICE.test(o))) return true;
|
|
163
|
+
return PERMISSION_ASK.test(`${question ?? ''}\n${summary ?? ''}`);
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
const block = (tag, body) => (String(body ?? '').trim() ? [`<${tag}>`, String(body).trim(), `</${tag}>`] : []);
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* The call that stands in for the person on one question. `ctx`: { question, options, default,
|
|
170
|
+
* context, intent, spec, points, groundRules, lessons, memory, answers: [{ question, answer }],
|
|
171
|
+
* past: [{ question, answer, outcome }] }.
|
|
172
|
+
*/
|
|
173
|
+
export function answerPrompt(ctx) {
|
|
174
|
+
return [
|
|
175
|
+
'You stand in for a person who is away, for ONE question an AI coding agent asked while working on their task.',
|
|
176
|
+
'Answer it only when one of these holds:',
|
|
177
|
+
'- the answer is already decided by what the person wrote or agreed: the request, the agreed points for what done means, their ground rules, the lessons of the repository, or an earlier answer of theirs;',
|
|
178
|
+
'- it is a routine implementation detail the request leaves to the implementer and that is cheap to change later (a name, where a file goes, which existing helper to use, a default the agent itself proposes).',
|
|
179
|
+
'Leave it for the person ("ask": true) when it changes what is built or how much; when it trades off cost, security, privacy, data or compatibility;',
|
|
180
|
+
'when it would delete, overwrite, publish, deploy, merge, spend money, touch credentials or reach outside the repository; when the request itself says to ask the person about this choice;',
|
|
181
|
+
'when the sources disagree or do not cover it; or when you are not sure.',
|
|
182
|
+
'Never invent a preference the person has not shown. When nothing decides it and the choice is cheap to change, the agent\'s own stated default is the answer.',
|
|
183
|
+
'Reply with one JSON object only, no prose around it. confidence is a number from 0 to 1.',
|
|
184
|
+
'Shape: {"ask": true|false, "answer": "what to tell the agent, one to three sentences, or empty", "basis": "the source that decides it, quoted briefly, or: routine detail, cheap to change", "confidence": 0.0}',
|
|
185
|
+
'',
|
|
186
|
+
'<question>',
|
|
187
|
+
ctx.question,
|
|
188
|
+
ctx.menu?.length ? `The agent shows a menu and takes one of these, by its number:\n${ctx.menu.map((c) => `${c.key}. ${c.label}${c.hint ? ` (${c.hint})` : ''}`).join('\n')}` : ctx.options?.length ? `Options: ${ctx.options.join(' | ')}` : '',
|
|
189
|
+
ctx.menu?.length ? 'When you answer, add "option": the number of the one to pick, and give its label as the answer. If none of them is right, leave it for the person.' : '',
|
|
190
|
+
ctx.default ? `The agent's default until answered: ${ctx.default}` : '',
|
|
191
|
+
ctx.context ? `Context from the agent: ${ctx.context}` : '',
|
|
192
|
+
'</question>',
|
|
193
|
+
...block('request', clip(ctx.intent, 3000)),
|
|
194
|
+
...block('agreed_points_for_done', (ctx.points ?? []).map((p) => `${p.id}: ${p.text}`).join('\n')),
|
|
195
|
+
...block('ground_rules', (ctx.groundRules ?? []).map((r) => `- ${r}`).join('\n')),
|
|
196
|
+
...block('lessons_of_the_repository', (ctx.lessons ?? []).map((l) => `- ${l}`).join('\n')),
|
|
197
|
+
...block('earlier_answers_from_the_person', (ctx.answers ?? []).map((a) => `- Q: ${clip(a.question, 200)}\n A: ${clip(a.answer, 300)}`).join('\n')),
|
|
198
|
+
...block('spec_written_by_the_agent', String(ctx.spec ?? '').slice(0, 5000)),
|
|
199
|
+
...block('repository_memory', String(ctx.memory ?? '').slice(0, 2500)),
|
|
200
|
+
...(ctx.past?.length
|
|
201
|
+
? ['<how_the_person_took_earlier_answers_given_for_them>', ...ctx.past.map((p) => `- Q: ${clip(p.question, 160)} → answered: ${clip(p.answer, 160)}; the person ${p.outcome}`), '</how_the_person_took_earlier_answers_given_for_them>', 'Calibrate to these: where they changed an answer, be slower to answer that kind of question.']
|
|
202
|
+
: []),
|
|
203
|
+
]
|
|
204
|
+
.filter((l) => l !== '')
|
|
205
|
+
.join('\n');
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/** The model's reply as { ask, answer, basis, confidence }, or null when it is unusable. */
|
|
209
|
+
export function parseAnswer(text) {
|
|
210
|
+
let d;
|
|
211
|
+
try {
|
|
212
|
+
d = parseJsonReply(text);
|
|
213
|
+
} catch {
|
|
214
|
+
return null;
|
|
215
|
+
}
|
|
216
|
+
if (!d || typeof d !== 'object' || typeof d.ask !== 'boolean') return null;
|
|
217
|
+
const answer = clip(d.answer, 600);
|
|
218
|
+
const option = /^\d$/.test(String(d.option ?? '')) ? String(d.option) : null;
|
|
219
|
+
return { ask: d.ask || !answer, answer, option, basis: clip(d.basis, 300), confidence: Math.max(0, Math.min(1, Number(d.confidence) || 0)) };
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/** What the agent is told: the answer, and that it was given for the person, not by them. */
|
|
223
|
+
export const autoAnswerMessage = (question, e) =>
|
|
224
|
+
`Answer to your question "${question}": ${e.answer}\n(Given for the user by AI Agent Manager while they are away, from what is already decided${e.basis ? `: ${e.basis}` : ''}. The user sees it and may change it; record it in your brief as an assumption.)`;
|
|
225
|
+
|
|
226
|
+
export const correctionMessage = (e, text) => `Correction from the user: your question "${e.question}" was answered for them with "${e.answer}". Their own answer is: ${text}\nApply it, and undo what you did on the earlier answer where it differs.`;
|
|
227
|
+
|
|
228
|
+
export const nudgeNote = '\n(Sent by AI Agent Manager while the user is away. If this does not help, set your brief to blocked and say what you need.)';
|
|
229
|
+
|
|
230
|
+
export const followUpMessage = (v) =>
|
|
231
|
+
`You have been quiet for a while and the task is not finished${v?.detail ? ` (${v.detail})` : ''}. Carry on from where you stopped: check your brief and plan, do the next step, and keep the brief current. ` +
|
|
232
|
+
'If you are waiting for something only the user can give, set the brief to blocked and say exactly what you need.';
|
|
233
|
+
|
|
234
|
+
/** "2 answered, 1 nudge, 1 left for you", from an agent's log. */
|
|
235
|
+
export function logLine(log = []) {
|
|
236
|
+
const n = (k) => log.filter((e) => e.kind === k).length;
|
|
237
|
+
const parts = [
|
|
238
|
+
n('answer') ? `${n('answer')} answered` : '',
|
|
239
|
+
n('nudge') ? `${n('nudge')} nudge${n('nudge') === 1 ? '' : 's'}` : '',
|
|
240
|
+
n('followup') ? `${n('followup')} follow-up${n('followup') === 1 ? '' : 's'}` : '',
|
|
241
|
+
n('plan') ? 'plan decided' : '',
|
|
242
|
+
n('merge') ? 'merged' : '',
|
|
243
|
+
n('left') ? `${n('left')} left for you` : '',
|
|
244
|
+
].filter(Boolean);
|
|
245
|
+
return parts.join(', ');
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/** An agent this can work for: a task with changes of its own, not a team member, reviewer, hunter or builder. */
|
|
249
|
+
/**
|
|
250
|
+
* The agent's own question shown as a menu (not a permission prompt, not one that takes several
|
|
251
|
+
* ticks): { key, question, options, menu: [{ key, label, hint }] }, or null.
|
|
252
|
+
*/
|
|
253
|
+
export function menuOf(view) {
|
|
254
|
+
const p = view?.runtime?.attention === 'Question' ? view.runtime.prompt : null;
|
|
255
|
+
const menu = (p?.choices ?? []).filter((c) => !FREE_CHOICE.test(c.label));
|
|
256
|
+
if (!p?.question || menu.length < 2 || p.multi) return null;
|
|
257
|
+
return { key: `m:${hash(`${p.question}\n${menu.map((c) => c.label).join('\n')}`)}`, question: p.question, options: menu.map((c) => c.label), menu };
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/** Why a merge is the person's: the agent says it left something out, or its proof did not hold when run again. */
|
|
261
|
+
export function leftOut(agent, view) {
|
|
262
|
+
const nd = view?.results?.notDone ?? [];
|
|
263
|
+
if (nd.length) return `The agent lists as not done: ${clip(nd.join('; '), 240)}.`;
|
|
264
|
+
const rerun = agent.proof && agent.proof.proofAt === (agent.proofDoc?.updatedAt ?? null) ? agent.proof.results.filter((r) => r.status === 'differs') : [];
|
|
265
|
+
if (rerun.length) return `${rerun.length} of its recorded commands gave a different result when run again: ${clip(rerun.map((r) => r.title).join('; '), 200)}.`;
|
|
266
|
+
return null;
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
export const eligible = (agent) => agent?.kind === 'task' && !agent.team && !agent.builds && !agent.reviewing && !agent.hunting && !agent.fixing && !agent.raceId;
|
|
270
|
+
|
|
271
|
+
export class Autonomy {
|
|
272
|
+
/**
|
|
273
|
+
* `review.get(id)` gives an agent's changes ({ files, diffHash }); `landing` merges; `backlog`
|
|
274
|
+
* says which agents are a backlog item's (autopilot ships those).
|
|
275
|
+
*/
|
|
276
|
+
constructor({ manager, store, config = {}, review = null, landing = null, backlog = null, log = (m) => console.log(`[agentmgr] ${m}`) }) {
|
|
277
|
+
Object.assign(this, { manager, store, config, review, landing, backlog, log });
|
|
278
|
+
this.working = new Set(); // agent ids with a step in progress
|
|
279
|
+
this.queued = null;
|
|
280
|
+
this.kick = () => this.schedule();
|
|
281
|
+
manager.autonomy = this;
|
|
282
|
+
manager.on('change', this.kick);
|
|
283
|
+
manager.on('prs', this.kick);
|
|
284
|
+
this.timer = setInterval(this.kick, 30_000);
|
|
285
|
+
this.timer.unref?.();
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
close() {
|
|
289
|
+
clearInterval(this.timer);
|
|
290
|
+
clearTimeout(this.queued);
|
|
291
|
+
this.manager.off('change', this.kick);
|
|
292
|
+
this.manager.off('prs', this.kick);
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
get settings() {
|
|
296
|
+
return autonomySettings(this.config);
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
schedule() {
|
|
300
|
+
if (this.queued) return;
|
|
301
|
+
this.queued = setTimeout(() => {
|
|
302
|
+
this.queued = null;
|
|
303
|
+
this.tick();
|
|
304
|
+
}, 500);
|
|
305
|
+
this.queued.unref?.();
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/** One look at every agent that runs without the person. Steps of different agents run side by side. */
|
|
309
|
+
tick() {
|
|
310
|
+
const runs = [];
|
|
311
|
+
for (const agent of this.store.list()) {
|
|
312
|
+
const level = levelOf(agent);
|
|
313
|
+
if (level === 'ask' || !eligible(agent) || this.working.has(agent.id)) continue;
|
|
314
|
+
this.working.add(agent.id);
|
|
315
|
+
runs.push(
|
|
316
|
+
this.step(agent.id, level)
|
|
317
|
+
.catch((e) => this.log(`autonomy: ${agent.name}: ${e.message}`))
|
|
318
|
+
.finally(() => this.working.delete(agent.id)),
|
|
319
|
+
);
|
|
320
|
+
}
|
|
321
|
+
return Promise.all(runs);
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
// ------------------------------------------------------------ the record
|
|
325
|
+
|
|
326
|
+
state(agent) {
|
|
327
|
+
return { log: [], seen: {}, ...agent.autonomy };
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
/** Change an agent's record, from the stored one (a step can take a while). */
|
|
331
|
+
put(id, fn) {
|
|
332
|
+
const agent = this.store.get(id);
|
|
333
|
+
if (!agent?.autonomy) return null;
|
|
334
|
+
const st = this.state(agent);
|
|
335
|
+
fn(st);
|
|
336
|
+
if (st.log.length > LOG_KEEP) st.log = st.log.slice(-LOG_KEEP);
|
|
337
|
+
// What was looked at, newest kept: a question or finding seen long ago does not come back.
|
|
338
|
+
const seen = Object.entries(st.seen);
|
|
339
|
+
if (seen.length > SEEN_KEEP) st.seen = Object.fromEntries(seen.sort((a, b) => String(a[1]).localeCompare(String(b[1]))).slice(-SEEN_KEEP));
|
|
340
|
+
return this.manager.patch(id, { autonomy: st });
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
record(id, entry) {
|
|
344
|
+
const e = { id: crypto.randomBytes(4).toString('hex'), at: now(), ...entry };
|
|
345
|
+
this.put(id, (st) => st.log.push(e));
|
|
346
|
+
return e;
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
usage() {
|
|
350
|
+
const u = (this.store.data.autonomy ??= {});
|
|
351
|
+
if (u.day !== today()) Object.assign(u, { day: today(), calls: 0 });
|
|
352
|
+
return u;
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
status() {
|
|
356
|
+
const s = this.settings;
|
|
357
|
+
const u = this.usage();
|
|
358
|
+
const agents = this.store.list().filter((a) => levelOf(a) !== 'ask');
|
|
359
|
+
return { ...s, labels: LEVEL_LABEL, levels: LEVELS, calls: u.calls, lastModel: u.lastModel ?? null, lastError: u.lastError ?? null, agents: agents.length };
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
/** Changes from the API: `level` (for new agents), `models` (best first), the switches and the limits. */
|
|
363
|
+
change(b = {}) {
|
|
364
|
+
const next = { ...this.config.autonomy };
|
|
365
|
+
if ('level' in b) {
|
|
366
|
+
const level = parseLevel(b.level);
|
|
367
|
+
if (!level) throw err(400, `level is one of ${LEVELS.join(', ')}`);
|
|
368
|
+
next.level = level;
|
|
369
|
+
}
|
|
370
|
+
if ('models' in b) {
|
|
371
|
+
const models = cleanModels(b.models);
|
|
372
|
+
if (!models.length) throw err(400, 'Name at least one model, best first: fable, opus, sonnet');
|
|
373
|
+
next.models = models;
|
|
374
|
+
}
|
|
375
|
+
for (const k of ['answers', 'nudges', 'followUps']) if (k in b) next[k] = b[k] === true || b[k] === 'on';
|
|
376
|
+
for (const k of ['minConfidence', 'minBuildConfidence', 'maxAnswers', 'maxNudges', 'maxFollowUps', 'dailyCalls']) {
|
|
377
|
+
if (!(k in b)) continue;
|
|
378
|
+
if (!Number.isFinite(Number(b[k])) || Number(b[k]) < 0) throw err(400, `${k} must be a number`);
|
|
379
|
+
next[k] = Number(b[k]);
|
|
380
|
+
}
|
|
381
|
+
this.config.autonomy = next;
|
|
382
|
+
return next;
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
// ------------------------------------------------------------ one agent
|
|
386
|
+
|
|
387
|
+
/** Set an agent's level. Its record (what was answered and sent for you) is kept. */
|
|
388
|
+
setLevel(ref, value) {
|
|
389
|
+
const agent = this.manager.mustGet(ref);
|
|
390
|
+
const level = parseLevel(value);
|
|
391
|
+
if (!level) throw err(400, `autonomy is one of ${LEVELS.join(', ')}`);
|
|
392
|
+
if (level !== 'ask' && !eligible(agent)) throw err(400, 'Only a task agent with changes of its own can run without you (not a team member, a reviewer, a bug hunt or a general session)');
|
|
393
|
+
if (level === levelOf(agent)) return this.manager.view(agent);
|
|
394
|
+
const st = this.state(agent);
|
|
395
|
+
const next = level === 'ask' && !st.log.length ? null : { ...st, level, hold: null };
|
|
396
|
+
const v = this.manager.view(this.manager.patch(agent.id, { autonomy: next }));
|
|
397
|
+
this.schedule();
|
|
398
|
+
return v;
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
async step(id, level) {
|
|
402
|
+
const agent = this.store.get(id);
|
|
403
|
+
if (!agent || agent.status === 'preparing' || agent.desktop) return;
|
|
404
|
+
const s = this.settings;
|
|
405
|
+
const v = this.manager.view(agent);
|
|
406
|
+
const st = this.state(agent);
|
|
407
|
+
const count = (k) => st.log.filter((e) => e.kind === k).length;
|
|
408
|
+
// While what done means or the plan waits for the person, the agent is asking for exactly that:
|
|
409
|
+
// nothing is answered or nudged for them.
|
|
410
|
+
const theirs = this.manager.acceptanceWaits(agent) || Boolean(agent.planReview && agent.planReview.status !== 'approved');
|
|
411
|
+
|
|
412
|
+
if (s.answers && !theirs) {
|
|
413
|
+
// Questions in QUESTIONS.md and plans are Decide's (advisor.js); the one it stopped on in its terminal is ours.
|
|
414
|
+
const w = v.runtime?.waiting;
|
|
415
|
+
const asked = w?.state === 'question' ? w.question || w.summary : null;
|
|
416
|
+
// A permission prompt the app itself sees is in the inbox already, as a prompt.
|
|
417
|
+
const prompted = v.runtime?.prompt || v.runtime?.attention;
|
|
418
|
+
if (asked && !prompted && !st.seen[`w:${hash(asked)}`]) return this.answer(agent, { key: `w:${hash(asked)}`, question: asked, options: w.choices ?? [], summary: w.summary });
|
|
419
|
+
// Its question as a menu: one option is picked by its key (a typed message would not be read).
|
|
420
|
+
const menu = menuOf(v);
|
|
421
|
+
if (menu && !st.seen[menu.key]) return this.answer(agent, menu);
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
if (s.nudges && !theirs) {
|
|
425
|
+
for (const f of v.stuck ?? []) {
|
|
426
|
+
const key = `s:${f.key}:${f.since}`;
|
|
427
|
+
if (st.seen[key] || f.ai?.verdict !== 'stuck' || !(f.ai.confidence >= s.minConfidence) || !f.nudge) continue;
|
|
428
|
+
if (count('nudge') >= s.maxNudges) {
|
|
429
|
+
this.put(id, (x) => (x.seen[key] = now()));
|
|
430
|
+
continue; // it stays in the inbox, for the person
|
|
431
|
+
}
|
|
432
|
+
this.put(id, (x) => (x.seen[key] = now()));
|
|
433
|
+
this.manager.tell(id, `${f.nudge}${nudgeNote}`, { source: 'autonomy' });
|
|
434
|
+
this.manager.dismissStuck(id, f.key, { feedback: null });
|
|
435
|
+
this.record(id, { kind: 'nudge', title: f.title, text: f.nudge, confidence: f.ai.confidence, model: f.ai.by ?? null });
|
|
436
|
+
this.log(`autonomy: nudged ${agent.name}: ${f.title}`);
|
|
437
|
+
return;
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
const fu = v.followUp;
|
|
442
|
+
if (s.followUps && fu?.kind === 'followup' && !st.seen[`f:${fu.since}`]) {
|
|
443
|
+
const waitsOnPerson = theirs || v.results?.outcome === 'blocked';
|
|
444
|
+
if (!waitsOnPerson) {
|
|
445
|
+
this.put(id, (x) => (x.seen[`f:${fu.since}`] = now()));
|
|
446
|
+
if (count('followup') < s.maxFollowUps) {
|
|
447
|
+
this.manager.tell(id, followUpMessage(fu), { source: 'autonomy' });
|
|
448
|
+
this.record(id, { kind: 'followup', title: fu.title, text: fu.detail ?? '' });
|
|
449
|
+
this.log(`autonomy: told ${agent.name} to carry on (${fu.title})`);
|
|
450
|
+
return;
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
if (level === 'merge' && this.landing && !this.backlogItem(id)) await this.land(agent, v);
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
/** The backlog item an agent works on, if any: autopilot ships those (autopilot.js). */
|
|
459
|
+
backlogItem(id) {
|
|
460
|
+
return this.backlog?.items().find((it) => it.agentId === id) ?? null;
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
// -------------------------------------------------------------- answers
|
|
464
|
+
|
|
465
|
+
context(agent) {
|
|
466
|
+
let spec = '';
|
|
467
|
+
try {
|
|
468
|
+
spec = fs.readFileSync(specPath(agent.id), 'utf8');
|
|
469
|
+
} catch {}
|
|
470
|
+
const questions = new Map((this.manager.questionsView(agent) ?? []).map((q) => [q.id, q.question]));
|
|
471
|
+
const answers = Object.entries(agent.answers ?? {})
|
|
472
|
+
.filter(([, a]) => a.by !== 'autonomy')
|
|
473
|
+
.map(([qid, a]) => ({ question: questions.get(qid) ?? '(an earlier question)', answer: a.text }))
|
|
474
|
+
.slice(-8);
|
|
475
|
+
const past = [];
|
|
476
|
+
for (const a of this.store.list()) {
|
|
477
|
+
for (const e of a.autonomy?.log ?? []) if (e.kind === 'answer' && (e.ack || e.corrected)) past.push({ at: e.at, question: e.question, answer: e.answer, outcome: e.corrected ? `changed it to: ${clip(e.corrected, 160)}` : 'kept it' });
|
|
478
|
+
}
|
|
479
|
+
past.sort((x, y) => x.at.localeCompare(y.at));
|
|
480
|
+
return {
|
|
481
|
+
intent: agent.intent,
|
|
482
|
+
spec,
|
|
483
|
+
points: agent.acceptance?.status === 'agreed' ? agent.acceptance.points : [],
|
|
484
|
+
groundRules: this.manager.groundRules?.list() ?? [],
|
|
485
|
+
lessons: (this.manager.standards?.forAgent(agent).lessons ?? []).map((l) => l.text).filter(Boolean),
|
|
486
|
+
memory: this.config.memory === false ? '' : memoryText(memoryKey(agent)),
|
|
487
|
+
answers,
|
|
488
|
+
past: past.slice(-8),
|
|
489
|
+
};
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
/** One question: leave it for the person, or answer it from what is already decided. */
|
|
493
|
+
async answer(agent, q) {
|
|
494
|
+
const id = agent.id;
|
|
495
|
+
const s = this.settings;
|
|
496
|
+
const st = this.state(agent);
|
|
497
|
+
const left = (why) => {
|
|
498
|
+
this.put(id, (x) => (x.seen[q.key] = now()));
|
|
499
|
+
this.record(id, { kind: 'left', key: q.key, question: clip(q.question, 300), why });
|
|
500
|
+
};
|
|
501
|
+
if (permissionPrompt(q)) return left('It is a permission prompt: only you answer those.');
|
|
502
|
+
const touchy = sensitive([q.question, ...(q.options ?? []), q.default, q.context].filter(Boolean).join('\n'));
|
|
503
|
+
if (touchy) return left(`It is about ${touchy}: yours to answer.`);
|
|
504
|
+
if (st.log.filter((e) => e.kind === 'answer').length >= s.maxAnswers) return left(`${s.maxAnswers} questions were already answered for you on this agent.`);
|
|
505
|
+
const u = this.usage();
|
|
506
|
+
if (u.calls >= s.dailyCalls) return left("Today's calls for answering are used up.");
|
|
507
|
+
u.calls++;
|
|
508
|
+
// Seen before the call: a second look while it runs must not ask again.
|
|
509
|
+
this.put(id, (x) => (x.seen[q.key] = now()));
|
|
510
|
+
let r;
|
|
511
|
+
try {
|
|
512
|
+
r = await this.manager.ladderShot(agent, answerPrompt({ ...q, ...this.context(agent) }), { timeoutMs: 120_000 });
|
|
513
|
+
} catch (e) {
|
|
514
|
+
u.lastError = { at: now(), message: String(e.message).slice(0, 300) };
|
|
515
|
+
this.store.save();
|
|
516
|
+
this.record(id, { kind: 'left', key: q.key, question: clip(q.question, 300), why: 'No model could be reached to look at it.' });
|
|
517
|
+
return;
|
|
518
|
+
}
|
|
519
|
+
u.lastModel = r.by;
|
|
520
|
+
this.store.save();
|
|
521
|
+
const d = parseAnswer(r.text);
|
|
522
|
+
if (!d || d.ask || d.confidence < s.minConfidence) {
|
|
523
|
+
this.record(id, { kind: 'left', key: q.key, question: clip(q.question, 300), why: d ? (d.ask ? d.basis || 'Nothing already decided covers it.' : `Not sure enough (${Math.round(d.confidence * 100)}%).`) : 'The reply could not be read.', model: r.by });
|
|
524
|
+
return;
|
|
525
|
+
}
|
|
526
|
+
// The person may have answered while the model was thinking: theirs stands.
|
|
527
|
+
const cur = this.store.get(id);
|
|
528
|
+
if (!cur || levelOf(cur) === 'ask') return;
|
|
529
|
+
if (q.qid) {
|
|
530
|
+
if (cur.answers?.[q.qid]) return;
|
|
531
|
+
this.manager.patch(id, { answers: { ...cur.answers, [q.qid]: { text: d.answer, at: now(), by: 'autonomy', model: r.by, basis: d.basis } } });
|
|
532
|
+
} else if (q.menu) {
|
|
533
|
+
const c = q.menu.find((x) => x.key === d.option);
|
|
534
|
+
if (!c || menuOf(this.manager.view(cur))?.key !== q.key) {
|
|
535
|
+
if (!c) this.record(id, { kind: 'left', key: q.key, question: clip(q.question, 300), why: 'The reply did not pick one of the choices.' });
|
|
536
|
+
return; // or the menu was answered, or changed, meanwhile
|
|
537
|
+
}
|
|
538
|
+
const e = this.record(id, { kind: 'answer', key: q.key, qid: null, question: clip(q.question, 300), answer: c.label, basis: d.basis, confidence: d.confidence, model: r.by, ack: false });
|
|
539
|
+
this.manager.answerPrompt(id, c.key);
|
|
540
|
+
this.log(`autonomy: picked "${c.label}" for ${agent.name} (${r.by}): ${clip(q.question, 80)}`);
|
|
541
|
+
return e;
|
|
542
|
+
} else {
|
|
543
|
+
const rt = this.manager.runtimes.get(id);
|
|
544
|
+
const w = rt?.waiting;
|
|
545
|
+
if (!w || (w.question || w.summary) !== q.question) return;
|
|
546
|
+
rt.waiting = null;
|
|
547
|
+
}
|
|
548
|
+
const e = this.record(id, { kind: 'answer', key: q.key, qid: q.qid ?? null, question: clip(q.question, 300), answer: d.answer, basis: d.basis, confidence: d.confidence, model: r.by, ack: false });
|
|
549
|
+
this.manager.tell(id, autoAnswerMessage(q.question, e), { source: 'autonomy' });
|
|
550
|
+
this.log(`autonomy: answered for ${agent.name} (${r.by}): ${clip(q.question, 80)}`);
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
// ---------------------------------------------- with Decide (advisor.js)
|
|
554
|
+
|
|
555
|
+
/** For Decide: does this agent run without the person? */
|
|
556
|
+
autonomous(agentId) {
|
|
557
|
+
const agent = this.store.get(agentId);
|
|
558
|
+
return Boolean(agent) && eligible(agent) && levelOf(agent) !== 'ask' && this.settings.answers;
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
/** For Decide: why an item is the person's whatever is recommended, or null. */
|
|
562
|
+
guard(item) {
|
|
563
|
+
return sensitive([item.question, ...(item.options ?? []), item.default, item.context].filter(Boolean).join('\n'));
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
/** For Decide: what its recommendation should know of this agent's task. */
|
|
567
|
+
briefContext(item) {
|
|
568
|
+
const agent = this.store.get(item.agentId);
|
|
569
|
+
if (!agent) return {};
|
|
570
|
+
const c = this.context(agent);
|
|
571
|
+
return { points: c.points, groundRules: c.groundRules, repoLessons: c.lessons };
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
/** Decide carried something out for an agent that runs without the person: it goes on that agent's record. */
|
|
575
|
+
decided(h) {
|
|
576
|
+
const agent = this.store.get(h.agentId);
|
|
577
|
+
if (!agent?.autonomy || levelOf(agent) === 'ask') return;
|
|
578
|
+
if (h.action === 'answer') this.record(agent.id, { kind: 'answer', via: 'decide', qid: h.qid ?? null, question: clip(h.title, 300), answer: clip(h.text, 600), basis: clip(h.why, 300), confidence: h.confidence ?? null, model: null, ack: false });
|
|
579
|
+
else this.record(agent.id, { kind: 'plan', via: 'decide', title: h.did, text: clip(h.why, 300) });
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
entry(agent, entryId) {
|
|
583
|
+
const e = (agent.autonomy?.log ?? []).find((x) => x.id === entryId);
|
|
584
|
+
if (!e) throw err(404, 'No such entry');
|
|
585
|
+
return e;
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
/** "OK": the person has seen what was done for them (an answer, a held merge). */
|
|
589
|
+
ack(ref, entryId) {
|
|
590
|
+
const agent = this.manager.mustGet(ref);
|
|
591
|
+
if (entryId === 'hold') return this.manager.view(this.put(agent.id, (st) => st.hold && (st.hold.ack = true)) ?? agent);
|
|
592
|
+
this.entry(agent, entryId);
|
|
593
|
+
return this.manager.view(this.put(agent.id, (st) => (st.log.find((x) => x.id === entryId).ack = true)));
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
/** The person's own answer to a question that was answered for them: the agent is told to apply it. */
|
|
597
|
+
correct(ref, entryId, text) {
|
|
598
|
+
const agent = this.manager.mustGet(ref);
|
|
599
|
+
const e = this.entry(agent, entryId);
|
|
600
|
+
if (e.kind !== 'answer') throw err(400, 'Only an answer can be changed');
|
|
601
|
+
text = String(text ?? '').trim();
|
|
602
|
+
if (!text) throw err(400, 'Your answer is empty');
|
|
603
|
+
if (e.qid) this.manager.patch(agent.id, { answers: { ...agent.answers, [e.qid]: { text, at: now() } } });
|
|
604
|
+
this.put(agent.id, (st) => Object.assign(st.log.find((x) => x.id === entryId), { ack: true, corrected: clip(text, 600) }));
|
|
605
|
+
return this.manager.tell(agent.id, correctionMessage(e, text), { source: 'answer' });
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
// ---------------------------------------------------------------- merge
|
|
609
|
+
|
|
610
|
+
/** Stop and wait for the person on this state of the pull request; shown once in the inbox. */
|
|
611
|
+
hold(id, key, note) {
|
|
612
|
+
const cur = this.store.get(id)?.autonomy?.hold;
|
|
613
|
+
if (cur?.key === key && cur.note === note) return;
|
|
614
|
+
this.log(`autonomy: holding ${this.store.get(id)?.name}: ${note}`);
|
|
615
|
+
this.put(id, (st) => (st.hold = { key, note: clip(note, 500), at: now(), ack: false }));
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
/** "Run to merge" for an agent that is not a backlog item: merge its pull request when everything says ready. */
|
|
619
|
+
async land(agent, v) {
|
|
620
|
+
const id = agent.id;
|
|
621
|
+
const s = this.settings;
|
|
622
|
+
for (const pr of this.landing.openPrs(agent)) {
|
|
623
|
+
const state = landState(pr);
|
|
624
|
+
const key = `${pr.url}@${pr.head ?? ''}`;
|
|
625
|
+
const st = this.state(this.store.get(id) ?? agent);
|
|
626
|
+
if (st.hold?.key === key || st.merged === key) continue;
|
|
627
|
+
if (state === 'behind' && st.updated !== key) {
|
|
628
|
+
this.put(id, (x) => (x.updated = key));
|
|
629
|
+
await this.landing.updateBranch(id).catch((e) => this.hold(id, key, `Its branch is behind and could not be updated: ${e.message}`));
|
|
630
|
+
return;
|
|
631
|
+
}
|
|
632
|
+
if (state === 'draft') return this.hold(id, key, 'Its pull request is a draft.');
|
|
633
|
+
if (state !== 'ready') continue; // waiting for checks; failing ones go back to the agent through Landing
|
|
634
|
+
if (v.runtime?.busy) return;
|
|
635
|
+
// Reviewed in rounds: only what the critics approved is merged.
|
|
636
|
+
const pre = agent.preReview;
|
|
637
|
+
if (['reviewing', 'fixing'].includes(pre?.status)) return;
|
|
638
|
+
if (pre && pre.status !== 'approved') return this.hold(id, key, pre.status === 'stalled' ? `The review rounds did not approve its changes (${pre.round} ${pre.round === 1 ? 'round' : 'rounds'}).` : 'Its changes were not approved by the review rounds.');
|
|
639
|
+
if (this.manager.acceptanceWaits(agent)) return this.hold(id, key, 'What done means is not agreed yet.');
|
|
640
|
+
const own = v.results?.confidence;
|
|
641
|
+
if (own && own.percent < s.minBuildConfidence) return this.hold(id, key, `The agent's own confidence in this is ${own.percent}%${own.why ? `: ${own.why}` : ''}.`);
|
|
642
|
+
const left = leftOut(agent, v);
|
|
643
|
+
if (left) return this.hold(id, key, left);
|
|
644
|
+
const changes = this.review ? await this.review.get(id) : null;
|
|
645
|
+
const risk = changes ? this.manager.standards?.riskIn(agent, changes.files ?? []) ?? [] : [];
|
|
646
|
+
if (risk.length) return this.hold(id, key, `It changes high-risk paths (${risk.slice(0, 3).map((r) => r.path).join(', ')}${risk.length > 3 ? ` and ${risk.length - 3} more` : ''}): yours to merge.`);
|
|
647
|
+
const card = this.store.get(id)?.docs?.scorecard;
|
|
648
|
+
if (card?.pending) return;
|
|
649
|
+
if (!card?.data || (changes?.diffHash && card.diffHash !== changes.diffHash)) {
|
|
650
|
+
if (st.scored === key) return this.hold(id, key, card?.error ? `Couldn't score the changes: ${card.error}` : "Couldn't score the changes.");
|
|
651
|
+
this.put(id, (x) => (x.scored = key));
|
|
652
|
+
await this.manager.summarize(id, 'scorecard').catch(() => {});
|
|
653
|
+
return this.schedule();
|
|
654
|
+
}
|
|
655
|
+
const sc = card.data;
|
|
656
|
+
if (sc.recommendation !== 'ready') return this.hold(id, key, `The review scorecard says ${sc.recommendation === 'look' ? 'to look first' : 'it is not ready'} (${sc.overall ?? '?'}/100)${sc.reasons?.length ? `: ${sc.reasons.join('; ')}` : ''}.`);
|
|
657
|
+
this.put(id, (x) => (x.merged = key));
|
|
658
|
+
try {
|
|
659
|
+
await this.landing.merge(id, { url: pr.url });
|
|
660
|
+
} catch (e) {
|
|
661
|
+
this.put(id, (x) => (x.merged = null));
|
|
662
|
+
return this.hold(id, key, `The merge failed: ${e.message}`);
|
|
663
|
+
}
|
|
664
|
+
this.record(id, { kind: 'merge', title: `Merged ${pr.url}`, text: `Checks passed, the scorecard said ready (${sc.overall ?? '?'}/100)${own ? `, its own confidence ${own.percent}%` : ''}.`, url: pr.url });
|
|
665
|
+
this.log(`autonomy: merged ${pr.url}`);
|
|
666
|
+
return;
|
|
667
|
+
}
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
// ---------------------------------------------------------------- inbox
|
|
671
|
+
|
|
672
|
+
/** What was decided for the person and they have not seen: answers given, a merge held. */
|
|
673
|
+
inbox() {
|
|
674
|
+
const items = [];
|
|
675
|
+
for (const agent of this.store.list()) {
|
|
676
|
+
const st = agent.autonomy;
|
|
677
|
+
if (!st) continue;
|
|
678
|
+
const base = { kind: 'auto', agentId: agent.id, agentName: agent.name, priority: agent.priority ?? 2 };
|
|
679
|
+
for (const e of st.log ?? []) if (e.kind === 'answer' && !e.ack) items.push({ ...base, key: `auto:${agent.id}:${e.id}`, title: `Answered for you: ${e.question}`, entry: e, at: e.at });
|
|
680
|
+
if (st.hold && !st.hold.ack && levelOf(agent) === 'merge') items.push({ ...base, key: `auto:${agent.id}:hold`, title: `Not merged: ${st.hold.note}`, entry: { id: 'hold', kind: 'hold', ...st.hold }, at: st.hold.at });
|
|
681
|
+
}
|
|
682
|
+
return items;
|
|
683
|
+
}
|
|
684
|
+
}
|