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/src/manager.js CHANGED
@@ -131,10 +131,14 @@ import { reviewPath, reviewerPrompt } from './reviews.js';
131
131
  import { findingsPath, fixPath, fixerPrompt, hunterPrompt } from './bughunt.js';
132
132
  import { reminderFor, reminderSettings } from './reminders.js';
133
133
  import { combine, factLines, facts as scoreFacts, improveMessage, scorecardMarkdown, scorecardPrompt } from './scorecard.js';
134
+ import { acceptanceAgreedPrompt, acceptancePrompt, agreedMessage, cleanPoints, counts as acceptanceCounts, parseCriteria, results as acceptanceResults, SKIPPED_MESSAGE } from './acceptance.js';
134
135
  import { CLAIM_TEXTS, claimsMarkdown, claimsPrompt, combineClaims, parseClaims, totals as claimTotals } from './claims.js';
135
136
  import { CONTAINER_ENGINES, claudeToken, containerName, containerRunning, engineMounts, gitCommonDir, removeContainer, runArgs, stopContainer } from './container.js';
136
137
  import { conflictMessage, findConflicts, related, repoKey, summarize as summarizeConflicts } from './conflicts.js';
137
138
  import { answerMessage, loadQuestions, questionsPath, questionsPrompt } from './inbox.js';
139
+ import { PROOF_FILE, proofBlock, proofFacts, proofPrompt } from './proof.js';
140
+ import { GroundRules, groundRulesMessage } from './groundrules.js';
141
+ import { autonomySettings, callLadder, eligible as autonomyEligible, levelOf, modelName, parseLevel } from './autonomy.js';
138
142
  import { STUCK_DEFAULTS, detectStuck } from './stuck.js';
139
143
  import { Judge, clashPrompt, finishMessage, hash, reviewPrompt, screenPrompt, stripChrome, stuckPrompt } from './judge.js';
140
144
  import { findLocalUrls, findSignInLinks, parseCallback, parseUrl } from './preview.js';
@@ -325,7 +329,16 @@ export class AgentManager extends EventEmitter {
325
329
  // The AI judge: rules decide when to look, a model decides what is going on (see judge.js).
326
330
  this.rules = new Rules({ suggestAfter: config.rules?.suggestAfter, readOnly: config.rules?.readOnly });
327
331
  this.inboxSources = [];
328
- this.judge = new Judge({ config, call: (agent, prompt, { timeoutMs }) => this.oneShot(agent, prompt, { ...this.judgeModel(agent), timeoutMs }) });
332
+ this.groundRules = new GroundRules(); // the person's own rules for every session (groundrules.js)
333
+ // For an agent that runs without the person (autonomy.js), what is decided in their place (is it
334
+ // stuck and what nudge, what to answer or approve) is judged on the autonomy models, best first:
335
+ // what comes out is acted on without anyone reading it first.
336
+ this.judge = new Judge({
337
+ config,
338
+ call: (agent, prompt, { timeoutMs, kind }) =>
339
+ ['stuck', 'advise'].includes(kind) && agent && levelOf(agent) !== 'ask' ? this.ladderShot(agent, prompt, { timeoutMs }).then((r) => r.text) : this.oneShot(agent, prompt, { ...this.judgeModel(agent), timeoutMs }),
340
+ });
341
+ this.modelsDown = new Map(); // model name -> when a call on it last failed (autonomy's list of models)
329
342
  this.stuckVerdicts = new Map(); // agent id -> Map(finding key -> { at, since, data })
330
343
  this.signIns = new Map(); // agent id -> { url, port, callback, terminal, at, finished } from a CLI's sign-in link
331
344
  this.seenLinks = new Map(); // agent id -> Set of sign-in links already raised
@@ -470,7 +483,7 @@ export class AgentManager extends EventEmitter {
470
483
  else if (agent.brief?.status || rt?.pty || agent.status === 'preparing') outcome = 'in progress';
471
484
  }
472
485
  if (!outcome && !delivered.length && !blockers.length) return null;
473
- return { outcome: outcome ?? 'in progress', delivered, blockers, notes: r?.notes ?? '', fromAgent: Boolean(r) };
486
+ return { outcome: outcome ?? 'in progress', delivered, blockers, notes: r?.notes ?? '', confidence: r?.confidence ?? null, notDone: r?.notDone ?? [], notDoneSaid: Boolean(r?.notDoneSaid), fromAgent: Boolean(r) };
474
487
  }
475
488
 
476
489
  changed(agent) {
@@ -636,6 +649,8 @@ export class AgentManager extends EventEmitter {
636
649
  start = true,
637
650
  plan = false,
638
651
  planReview,
652
+ acceptance,
653
+ autonomy,
639
654
  designDoc,
640
655
  demoPage,
641
656
  benchmarks,
@@ -702,6 +717,11 @@ export class AgentManager extends EventEmitter {
702
717
  // Attached files (a screenshot, a log) go in the agent's own uploads folder, listed in its request.
703
718
  if (staged.length) intent = [intent, attachmentNote(copyAttachments(staged, id))].filter(Boolean).join('\n\n');
704
719
 
720
+ // How far it goes without you (autonomy.js): "ask" (as before) unless a level is named or set as the default.
721
+ const plainTask = !general && !team && !builds && !reviewing && !hunting && !fixing && !race;
722
+ const asked = autonomy === undefined || autonomy === null || autonomy === '' ? null : parseLevel(autonomy);
723
+ if (autonomy && !asked) throw Object.assign(new Error('autonomy is one of ask, run, pr, merge'), { status: 400 });
724
+ const level = plainTask ? asked ?? autonomySettings(this.config).level : 'ask';
705
725
  const agent = {
706
726
  id,
707
727
  kind: general ? kind : 'task',
@@ -736,6 +756,10 @@ export class AgentManager extends EventEmitter {
736
756
  // Review the implementation plan before the agent implements it: null = no review.
737
757
  // Team members get their review from the team instead.
738
758
  planReview: !general && !team && !builds && !reviewing && !hunting && (planReview ?? this.config.planReview ?? false) ? { status: 'writing' } : null,
759
+ // Agree on what done means first (acceptance.js): the agent drafts the points and waits. null = not asked.
760
+ acceptance: !general && !team && !builds && !reviewing && !hunting && (acceptance ?? (level !== 'ask' ? true : this.config.acceptance) ?? false) ? { status: 'writing', wait: true, points: [] } : null,
761
+ // Runs without you past that point: { level, log, seen } (autonomy.js). null = asks, as before.
762
+ autonomy: level !== 'ask' ? { level, log: [], seen: {} } : null,
739
763
  // Write and publish a design doc (Google Doc + Artifact) after the plan, updated at the end.
740
764
  designDoc: !general && !team && !builds && !reviewing && !hunting && Boolean(designDoc ?? this.config.designDoc ?? true),
741
765
  demoPage: !general && !team && !builds && !reviewing && !hunting && Boolean(demoPage ?? this.config.demoPage ?? false),
@@ -1371,6 +1395,8 @@ export class AgentManager extends EventEmitter {
1371
1395
  const dir = fs.realpathSync(briefDir(agent.id));
1372
1396
  writableDir = dir;
1373
1397
  prompts.push(briefPrompt(path.join(dir, path.basename(briefPath(agent.id)))));
1398
+ // What it ran to verify, kept so it can be checked, and what it left out (proof.js).
1399
+ if (this.config.proof !== false) prompts.push(proofPrompt(path.join(dir, PROOF_FILE)));
1374
1400
  if (this.config.inbox !== false) prompts.push(questionsPrompt(path.join(dir, path.basename(questionsPath(agent.id)))));
1375
1401
  }
1376
1402
  // SPEC.md before changing code, and PLAN.md kept as it goes (unless the plan review asks for the plan).
@@ -1379,7 +1405,15 @@ export class AgentManager extends EventEmitter {
1379
1405
  fs.mkdirSync(briefDir(agent.id), { recursive: true });
1380
1406
  const dir = fs.realpathSync(briefDir(agent.id));
1381
1407
  writableDir ??= dir;
1382
- prompts.push(specPrompt(path.join(dir, path.basename(specPath(agent.id))), path.join(dir, path.basename(planPath(agent.id))), { withPlan: !agent.planReview }));
1408
+ prompts.push(specPrompt(path.join(dir, path.basename(specPath(agent.id))), path.join(dir, path.basename(planPath(agent.id))), { withPlan: !agent.planReview, wait: this.acceptanceWaits(agent) }));
1409
+ }
1410
+ // What done means: drafted and waiting for the person, or agreed (then the points are the app's, as written).
1411
+ if (agent.acceptance && task) {
1412
+ fs.mkdirSync(briefDir(agent.id), { recursive: true });
1413
+ const file = path.join(fs.realpathSync(briefDir(agent.id)), path.basename(specPath(agent.id)));
1414
+ writableDir ??= path.dirname(file);
1415
+ if (agent.acceptance.status === 'agreed') prompts.push(acceptanceAgreedPrompt(agent.acceptance.points));
1416
+ else if (this.acceptanceWaits(agent)) prompts.push(acceptancePrompt(file, { planReview: Boolean(agent.planReview) && agent.planReview.status !== 'approved' }));
1383
1417
  }
1384
1418
  // Its changes are reviewed in rounds before a pull request (prereview.js): it leaves opening one to that.
1385
1419
  if (withBrief && !planning && this.preReview?.instructs(agent)) prompts.push(preReviewPrompt());
@@ -1439,6 +1473,9 @@ export class AgentManager extends EventEmitter {
1439
1473
  // The repository's standards (standards.js): lessons to follow and the parts marked high risk.
1440
1474
  const standards = task ? this.standards?.prompt(agent) : '';
1441
1475
  if (standards) prompts.push(standards);
1476
+ // The person's own ground rules, for every session in every repository (groundrules.js).
1477
+ const ground = this.groundRules.prompt();
1478
+ if (ground) prompts.push(ground);
1442
1479
  // Commands you chose to always allow in this repo.
1443
1480
  const ruled = agent.workdir ? this.rules.allowed(memoryKey(agent)) : [];
1444
1481
  if (ruled.length) allowedTools = [...(allowedTools ?? []), ...ruled];
@@ -1931,6 +1968,14 @@ export class AgentManager extends EventEmitter {
1931
1968
  allowed.model = String(fields.model ?? '').trim() || null;
1932
1969
  if (engineOf(agent).checkModel) allowed.model = engineOf(agent).checkModel(allowed.model, this.config);
1933
1970
  }
1971
+ // How far it goes without you (autonomy.js); what was done for you so far is kept.
1972
+ if ('autonomy' in fields) {
1973
+ const level = parseLevel(fields.autonomy);
1974
+ if (!level) throw bad('autonomy is one of ask, run, pr, merge');
1975
+ if (level !== 'ask' && !autonomyEligible(agent)) throw bad('Only a task agent with changes of its own can run without you');
1976
+ const cur = agent.autonomy;
1977
+ if (level !== levelOf(agent)) allowed.autonomy = level === 'ask' && !cur?.log?.length ? null : { log: [], seen: {}, ...cur, level, hold: null };
1978
+ }
1934
1979
  // Keep: clean up never closes or deletes it.
1935
1980
  if ('keep' in fields) allowed.keep = Boolean(fields.keep);
1936
1981
  if ('budgetUsd' in fields) {
@@ -2492,6 +2537,7 @@ export class AgentManager extends EventEmitter {
2492
2537
  const agent = this.store.get(id);
2493
2538
  if (!agent) return;
2494
2539
  const before = agent.brief; // patch() below changes agent.brief in place
2540
+ this.proof?.reload(id);
2495
2541
  const brief = loadBrief(id, before);
2496
2542
  if (brief) {
2497
2543
  this.patch(id, { brief });
@@ -2508,7 +2554,21 @@ export class AgentManager extends EventEmitter {
2508
2554
  if (finished && !rounds && !NO_REPO.has(agent.kind) && this.changesSource) this.standards?.finished(agent).catch((e) => this.log?.(`standards: ${e.message}`));
2509
2555
  if (finished && this.judge.enabled && !rounds) this.requestReview(id, { trigger: 'brief' }).catch(() => {});
2510
2556
  // ...and score it for the reviewer ("scorecard": { "auto": false } in config.json turns this off).
2511
- if ((improved || (finished && this.config.scorecard?.auto !== false && !rounds)) && !NO_REPO.has(agent.kind) && this.changesSource) this.summarize(id, 'scorecard').catch(() => {});
2557
+ // The points were agreed (or changed) after the last score: the brief saying done again is checked against them.
2558
+ const reagreed = brief.status === 'done' && agent.acceptance?.status === 'agreed' && agent.docs?.scorecard?.data && agent.docs.scorecard.acceptanceAt !== agent.acceptance.agreedAt;
2559
+ if ((improved || reagreed || (finished && this.config.scorecard?.auto !== false && !rounds)) && !NO_REPO.has(agent.kind) && this.changesSource) this.summarize(id, 'scorecard').catch(() => {});
2560
+ }
2561
+ // Its points for what done means, written or revised in the spec: they wait for the person.
2562
+ if (this.acceptanceWaits(agent)) {
2563
+ let at = null;
2564
+ try {
2565
+ at = fs.statSync(specPath(id)).mtime.toISOString();
2566
+ } catch {}
2567
+ if (at && at !== agent.acceptance.specAt) {
2568
+ const points = parseCriteria(readSpecDoc(id, 'spec')?.markdown);
2569
+ const cur = this.store.get(id).acceptance;
2570
+ this.patch(id, { acceptance: { ...cur, specAt: at, ...(points.length ? { status: 'review', points: points.map((text, i) => ({ id: `A${i + 1}`, text, from: 'agent' })), updatedAt: at } : {}) } });
2571
+ }
2512
2572
  }
2513
2573
  if (agent.planReview) {
2514
2574
  const file = loadPlanFile(id, agent.planReview);
@@ -2560,6 +2620,97 @@ export class AgentManager extends EventEmitter {
2560
2620
  return this.tell(agent.id, `Plan changes requested. Revise the plan file and wait for approval again:\n${note.trim()}`);
2561
2621
  }
2562
2622
 
2623
+ // ------------------------------------------------------------ ground rules
2624
+
2625
+ /**
2626
+ * Replace the person's ground rules. Sessions started from now on get them with their
2627
+ * instructions; with `tell`, the ones running now are told too. Returns the rules and how many
2628
+ * sessions were told.
2629
+ */
2630
+ setGroundRules(input, { tell = false } = {}) {
2631
+ const r = this.groundRules.set(input);
2632
+ let told = 0;
2633
+ if (tell && r.changed) {
2634
+ for (const [id, rt] of this.runtimes) {
2635
+ const agent = this.store.get(id);
2636
+ if (!rt.pty || !agent) continue;
2637
+ try {
2638
+ this.tell(id, groundRulesMessage(r.rules), { source: 'ground-rules' });
2639
+ told++;
2640
+ } catch {}
2641
+ }
2642
+ }
2643
+ return { ...r, told };
2644
+ }
2645
+
2646
+ // -------------------------------------------------------------- acceptance
2647
+
2648
+ /** Whether the agent is stopped until the person agrees on what done means. */
2649
+ acceptanceWaits(agent) {
2650
+ return Boolean(agent.acceptance?.wait) && ['writing', 'review'].includes(agent.acceptance.status);
2651
+ }
2652
+
2653
+ /**
2654
+ * What done means for an agent: the agreed points with what the last scorecard found for each,
2655
+ * or (not agreed) the points its spec has now. `stale`: agreed or changed since they were checked.
2656
+ */
2657
+ acceptanceOf(ref) {
2658
+ const agent = this.mustGet(ref);
2659
+ const acc = agent.acceptance;
2660
+ const draft = acc?.status === 'agreed' ? [] : parseCriteria(readSpecDoc(agent.id, 'spec')?.markdown);
2661
+ if (acc?.status !== 'agreed') {
2662
+ const status = !acc ? 'none' : draft.length ? 'review' : 'writing';
2663
+ return { id: agent.id, name: agent.name, status, wait: this.acceptanceWaits(agent), draft, points: [], results: [], counts: acceptanceCounts([]), agreedAt: null, checkedAt: null, stale: false };
2664
+ }
2665
+ const sc = agent.docs?.scorecard;
2666
+ const current = Boolean(sc?.data) && sc.acceptanceAt === acc.agreedAt;
2667
+ const res = acceptanceResults(acc.points, current ? sc.data.criteria : null);
2668
+ return {
2669
+ id: agent.id,
2670
+ name: agent.name,
2671
+ status: 'agreed',
2672
+ wait: false,
2673
+ draft: [],
2674
+ points: acc.points,
2675
+ results: res,
2676
+ counts: acceptanceCounts(res),
2677
+ agreedAt: acc.agreedAt,
2678
+ checkedAt: current ? sc.at : null,
2679
+ // Checked against other points, or the brief moved on since: the result is not of the work as it is.
2680
+ stale: Boolean(sc?.data) && (!current || (sc.briefUpdatedAt ?? null) !== (agent.brief?.updatedAt ?? null)),
2681
+ scoring: Boolean(sc?.pending),
2682
+ };
2683
+ }
2684
+
2685
+ /**
2686
+ * Agree on the points (as the agent wrote them, or as the person edited them). From here they
2687
+ * are kept by the app; an agent that is running is told them, one that was waiting goes ahead.
2688
+ */
2689
+ agreeAcceptance(ref, list) {
2690
+ const agent = this.mustGet(ref);
2691
+ if (NO_REPO.has(agent.kind)) throw Object.assign(new Error('Acceptance is for agents that work on a task'), { status: 400 });
2692
+ const prev = agent.acceptance;
2693
+ const draft = prev?.status === 'agreed' ? prev.points.filter((p) => p.from === 'agent').map((p) => p.text) : parseCriteria(readSpecDoc(agent.id, 'spec')?.markdown);
2694
+ const points = cleanPoints(list ?? draft, draft);
2695
+ const waiting = this.acceptanceWaits(agent);
2696
+ const changed = prev?.status === 'agreed';
2697
+ if (changed && prev.points.length === points.length && prev.points.every((p, i) => p.text === points[i].text)) return this.view(agent);
2698
+ this.patch(agent.id, { acceptance: { status: 'agreed', wait: false, points, agreedAt: now(), rounds: (prev?.rounds ?? 0) + 1, yours: points.filter((p) => p.from === 'you').length } });
2699
+ // A session at work hears now; one that isn't running reads them when it next starts (its work is scored against them either way).
2700
+ if (waiting || this.runtimes.get(agent.id)?.pty) return this.tell(agent.id, agreedMessage(points, { waiting, changed, planNext: Boolean(agent.planReview) && agent.planReview.status !== 'approved' }));
2701
+ // Already scored against other criteria: score it against these.
2702
+ if (agent.docs?.scorecard?.data && this.changesSource) this.summarize(agent.id, 'scorecard').catch(() => {});
2703
+ return this.view(this.store.get(agent.id));
2704
+ }
2705
+
2706
+ /** Stop waiting for the person: the agent goes ahead with the criteria in its own spec. */
2707
+ skipAcceptance(ref) {
2708
+ const agent = this.mustGet(ref);
2709
+ if (!this.acceptanceWaits(agent)) throw Object.assign(new Error('The agent is not waiting for the acceptance points'), { status: 409 });
2710
+ this.patch(agent.id, { acceptance: null });
2711
+ return this.tell(agent.id, SKIPPED_MESSAGE);
2712
+ }
2713
+
2563
2714
  /** Turn plan review on (before the agent has implemented anything) or off (no longer waits). */
2564
2715
  setPlanReview(ref, on) {
2565
2716
  const agent = this.mustGet(ref);
@@ -2698,6 +2849,9 @@ export class AgentManager extends EventEmitter {
2698
2849
  }
2699
2850
  // The spec and plan go along with the brief: what done means, and how it gets there.
2700
2851
  const extra = ['spec', 'plan'].map((n) => readSpecDoc(agent.id, n)?.markdown.trim()).filter(Boolean);
2852
+ // And its proof (proof.js): what it recorded of its checks, and what the app saw when it ran them again.
2853
+ const proof = this.proof?.forScore(agent);
2854
+ if (proof?.entries.length) extra.push(['# Proof of its checks, as the agent recorded it', ...proofFacts(proof.doc, proof.rerun), '', proofBlock(proof.entries, 4000)].join('\n'));
2701
2855
  return { intent: agent.intent, status, digest, repo, briefMarkdown: [briefMarkdown, ...extra].filter(Boolean).join('\n\n') };
2702
2856
  }
2703
2857
 
@@ -2811,9 +2965,10 @@ export class AgentManager extends EventEmitter {
2811
2965
  const doc = (n) => readSpecDoc(agent.id, n)?.markdown ?? '';
2812
2966
  // The repository's standards: its bar is run here, by the app, before the model is asked.
2813
2967
  const standards = (await this.standards?.assess(agent.id, data)) ?? null;
2814
- const f = scoreFacts({ files: data.files, prs: Object.values(cur0.prs ?? {}), brief: cur0.brief, plan: doc('plan'), spec: doc('spec'), standards });
2968
+ const proof = this.proof?.forScore(cur0) ?? null;
2969
+ const f = scoreFacts({ files: data.files, prs: Object.values(cur0.prs ?? {}), brief: cur0.brief, plan: doc('plan'), spec: doc('spec'), standards, agreed: cur0.acceptance?.status === 'agreed' ? cur0.acceptance.points : null, proof });
2815
2970
  const writer = this.writerFor(agent);
2816
- const prompt = scorecardPrompt({ ...ctx, briefMarkdown: this.briefFile(agent.id).markdown ?? '', intentDoc: doc('intent'), specDoc: doc('spec'), planDoc: doc('plan'), hunks, facts: f, lessons: standards?.lessons ?? [] });
2971
+ const prompt = scorecardPrompt({ ...ctx, briefMarkdown: this.briefFile(agent.id).markdown ?? '', intentDoc: doc('intent'), specDoc: doc('spec'), planDoc: doc('plan'), proofDoc: proof?.entries?.length ? proofBlock(proof.entries) : '', hunks, facts: f, lessons: standards?.lessons ?? [] });
2817
2972
  const sc = combine(parseJsonReply(await this.oneShot(agent, prompt, writer)), f, hunks, { lessons: standards?.lessons ?? [], bar: standards?.bar ?? null });
2818
2973
  const cur = this.store.get(agent.id);
2819
2974
  if (!cur) return null;
@@ -2830,6 +2985,8 @@ export class AgentManager extends EventEmitter {
2830
2985
  improvedFrom: cur.improving ? cur.improving.from : null,
2831
2986
  at: now(),
2832
2987
  briefUpdatedAt: cur.brief?.updatedAt ?? null,
2988
+ // The agreed points it was checked against (acceptance.js); null when none were agreed then.
2989
+ acceptanceAt: f.agreed ? cur0.acceptance.agreedAt : null,
2833
2990
  pending: false,
2834
2991
  error: null,
2835
2992
  }),
@@ -3535,6 +3692,26 @@ export class AgentManager extends EventEmitter {
3535
3692
  return this.writerFor(agent);
3536
3693
  }
3537
3694
 
3695
+ /** The models autonomy's own calls run on, best first: config `autonomy.models` on Claude Code, else the summary writer. */
3696
+ ladderModels(agent) {
3697
+ const usable = (e) => e?.supports.oneShot && installed(e, this.config);
3698
+ const out = [];
3699
+ for (const m of autonomySettings(this.config).models) {
3700
+ const engine = ENGINES[typeof m === 'string' ? DEFAULT_ENGINE : m.engine ?? DEFAULT_ENGINE];
3701
+ if (usable(engine)) out.push({ engine, model: typeof m === 'string' ? m : m.model });
3702
+ }
3703
+ return out.length ? out : [this.writerFor(agent)];
3704
+ }
3705
+
3706
+ /**
3707
+ * One call for an agent that runs without the person: on the first of the models that answers.
3708
+ * Resolves to { text, by } (`by`: the model that answered); rejects when none did.
3709
+ */
3710
+ async ladderShot(agent, prompt, { timeoutMs = 120_000 } = {}) {
3711
+ const r = await callLadder(this.ladderModels(agent), (m) => this.oneShot(agent, prompt, { ...m, timeoutMs }), { down: this.modelsDown, retryMs: autonomySettings(this.config).retryMin * 60_000 });
3712
+ return { text: r.text, by: modelName(r.model), tried: r.tried };
3713
+ }
3714
+
3538
3715
  /** The end of the terminal screen as text: cursor moves become spaces or line breaks. */
3539
3716
  screenText(rt) {
3540
3717
  return rt.tail
@@ -3715,7 +3892,7 @@ export class AgentManager extends EventEmitter {
3715
3892
 
3716
3893
  /** A live prompt's question and choices, and the tool call it asks about when the transcript says. */
3717
3894
  promptView(agent, rt) {
3718
- const p = engineOf(agent).promptChoices(rt.tail);
3895
+ const p = engineOf(agent).promptChoices(rt.tail, rt.attention);
3719
3896
  const call = rt.attention === PERMISSION ? this.pendingCall(agent) : null;
3720
3897
  return call ? { ...p, tool: describeTool(call) } : p;
3721
3898
  }
package/src/notify.js CHANGED
@@ -252,7 +252,23 @@ export class Notifier {
252
252
  this.send('question', a, `asks: ${q.question}`);
253
253
  }
254
254
  }
255
+ for (const e of a.autonomy?.log ?? []) {
256
+ const k = `auto:${e.id}`;
257
+ // A question it stopped on, answered for you (autonomy.js); what Decide handled is alerted by Decide.
258
+ if (e.kind === 'answer' && e.via !== 'decide' && !e.ack && !s.sent.has(k)) {
259
+ s.sent.add(k);
260
+ this.send('decided', a, `asked: ${e.question} It was answered for you: ${e.answer}`);
261
+ }
262
+ }
255
263
  // A plan waiting for review is an inbox decision too (same switch as questions).
264
+ // So are its points for what done means, when it waits for them to be agreed.
265
+ if (a.acceptance?.status === 'review' && a.acceptance.wait) {
266
+ const k = `acceptance:${a.acceptance.updatedAt}`;
267
+ if (!s.sent.has(k)) {
268
+ s.sent.add(k);
269
+ this.send('question', a, `wrote what done means (${a.acceptance.points.length} point${a.acceptance.points.length === 1 ? '' : 's'}); agree on it before it starts`);
270
+ }
271
+ }
256
272
  if (a.planReview?.status === 'review') {
257
273
  const k = `plan:${a.planReview.updatedAt}`;
258
274
  if (!s.sent.has(k)) {
package/src/prereview.js CHANGED
@@ -261,9 +261,14 @@ export class PreReview {
261
261
  return Boolean(agent.kind === 'task' && agent.workdir && !agent.hunting && !agent.fixing && !agent.reviewing && !agent.team && !agent.builds && !agent.raceId && !this.skip(agent) && this.candidates(agent).length);
262
262
  }
263
263
 
264
+ /** Is its pull request opened on approval? The setting, or its own autonomy level saying so (autonomy.js). */
265
+ opensPr(agent) {
266
+ return this.settings.openPr || ['pr', 'merge'].includes(agent?.autonomy?.level);
267
+ }
268
+
264
269
  /** Told at launch that the pull request waits for the review? */
265
270
  instructs(agent) {
266
- return this.applies(agent) && this.settings.openPr && !this.managed(agent.id);
271
+ return this.applies(agent) && this.opensPr(agent) && !this.managed(agent.id);
267
272
  }
268
273
 
269
274
  /**
@@ -402,7 +407,7 @@ export class PreReview {
402
407
  this.manager.patch(id, { preReview: state });
403
408
  this.log(`review rounds: ${this.manager.store.get(id)?.name ?? id} ${state.status === 'approved' ? 'approved' : 'not approved'} in round ${state.round} of ${state.max}`);
404
409
  await this.after(id);
405
- if (state.status === 'approved' && this.settings.openPr && !state.forced && !this.managed(id)) await this.open(id).catch(() => {});
410
+ if (state.status === 'approved' && this.opensPr(this.manager.store.get(id)) && !state.forced && !this.managed(id)) await this.open(id).catch(() => {});
406
411
  }
407
412
 
408
413
  /** What waited for the rounds: the AI review, and the score (which goes in the pull request's description). */
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
+ }