ai-agentmanager 1.62.0 → 1.63.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,13 @@ 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 { GroundRules, groundRulesMessage } from './groundrules.js';
140
+ import { autonomySettings, callLadder, eligible as autonomyEligible, levelOf, modelName, parseLevel } from './autonomy.js';
138
141
  import { STUCK_DEFAULTS, detectStuck } from './stuck.js';
139
142
  import { Judge, clashPrompt, finishMessage, hash, reviewPrompt, screenPrompt, stripChrome, stuckPrompt } from './judge.js';
140
143
  import { findLocalUrls, findSignInLinks, parseCallback, parseUrl } from './preview.js';
@@ -325,7 +328,16 @@ export class AgentManager extends EventEmitter {
325
328
  // The AI judge: rules decide when to look, a model decides what is going on (see judge.js).
326
329
  this.rules = new Rules({ suggestAfter: config.rules?.suggestAfter, readOnly: config.rules?.readOnly });
327
330
  this.inboxSources = [];
328
- this.judge = new Judge({ config, call: (agent, prompt, { timeoutMs }) => this.oneShot(agent, prompt, { ...this.judgeModel(agent), timeoutMs }) });
331
+ this.groundRules = new GroundRules(); // the person's own rules for every session (groundrules.js)
332
+ // For an agent that runs without the person (autonomy.js), what is decided in their place (is it
333
+ // stuck and what nudge, what to answer or approve) is judged on the autonomy models, best first:
334
+ // what comes out is acted on without anyone reading it first.
335
+ this.judge = new Judge({
336
+ config,
337
+ call: (agent, prompt, { timeoutMs, kind }) =>
338
+ ['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 }),
339
+ });
340
+ this.modelsDown = new Map(); // model name -> when a call on it last failed (autonomy's list of models)
329
341
  this.stuckVerdicts = new Map(); // agent id -> Map(finding key -> { at, since, data })
330
342
  this.signIns = new Map(); // agent id -> { url, port, callback, terminal, at, finished } from a CLI's sign-in link
331
343
  this.seenLinks = new Map(); // agent id -> Set of sign-in links already raised
@@ -470,7 +482,7 @@ export class AgentManager extends EventEmitter {
470
482
  else if (agent.brief?.status || rt?.pty || agent.status === 'preparing') outcome = 'in progress';
471
483
  }
472
484
  if (!outcome && !delivered.length && !blockers.length) return null;
473
- return { outcome: outcome ?? 'in progress', delivered, blockers, notes: r?.notes ?? '', fromAgent: Boolean(r) };
485
+ return { outcome: outcome ?? 'in progress', delivered, blockers, notes: r?.notes ?? '', confidence: r?.confidence ?? null, fromAgent: Boolean(r) };
474
486
  }
475
487
 
476
488
  changed(agent) {
@@ -636,6 +648,8 @@ export class AgentManager extends EventEmitter {
636
648
  start = true,
637
649
  plan = false,
638
650
  planReview,
651
+ acceptance,
652
+ autonomy,
639
653
  designDoc,
640
654
  demoPage,
641
655
  benchmarks,
@@ -702,6 +716,11 @@ export class AgentManager extends EventEmitter {
702
716
  // Attached files (a screenshot, a log) go in the agent's own uploads folder, listed in its request.
703
717
  if (staged.length) intent = [intent, attachmentNote(copyAttachments(staged, id))].filter(Boolean).join('\n\n');
704
718
 
719
+ // How far it goes without you (autonomy.js): "ask" (as before) unless a level is named or set as the default.
720
+ const plainTask = !general && !team && !builds && !reviewing && !hunting && !fixing && !race;
721
+ const asked = autonomy === undefined || autonomy === null || autonomy === '' ? null : parseLevel(autonomy);
722
+ if (autonomy && !asked) throw Object.assign(new Error('autonomy is one of ask, run, pr, merge'), { status: 400 });
723
+ const level = plainTask ? asked ?? autonomySettings(this.config).level : 'ask';
705
724
  const agent = {
706
725
  id,
707
726
  kind: general ? kind : 'task',
@@ -736,6 +755,10 @@ export class AgentManager extends EventEmitter {
736
755
  // Review the implementation plan before the agent implements it: null = no review.
737
756
  // Team members get their review from the team instead.
738
757
  planReview: !general && !team && !builds && !reviewing && !hunting && (planReview ?? this.config.planReview ?? false) ? { status: 'writing' } : null,
758
+ // Agree on what done means first (acceptance.js): the agent drafts the points and waits. null = not asked.
759
+ acceptance: !general && !team && !builds && !reviewing && !hunting && (acceptance ?? (level !== 'ask' ? true : this.config.acceptance) ?? false) ? { status: 'writing', wait: true, points: [] } : null,
760
+ // Runs without you past that point: { level, log, seen } (autonomy.js). null = asks, as before.
761
+ autonomy: level !== 'ask' ? { level, log: [], seen: {} } : null,
739
762
  // Write and publish a design doc (Google Doc + Artifact) after the plan, updated at the end.
740
763
  designDoc: !general && !team && !builds && !reviewing && !hunting && Boolean(designDoc ?? this.config.designDoc ?? true),
741
764
  demoPage: !general && !team && !builds && !reviewing && !hunting && Boolean(demoPage ?? this.config.demoPage ?? false),
@@ -1379,7 +1402,15 @@ export class AgentManager extends EventEmitter {
1379
1402
  fs.mkdirSync(briefDir(agent.id), { recursive: true });
1380
1403
  const dir = fs.realpathSync(briefDir(agent.id));
1381
1404
  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 }));
1405
+ 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) }));
1406
+ }
1407
+ // What done means: drafted and waiting for the person, or agreed (then the points are the app's, as written).
1408
+ if (agent.acceptance && task) {
1409
+ fs.mkdirSync(briefDir(agent.id), { recursive: true });
1410
+ const file = path.join(fs.realpathSync(briefDir(agent.id)), path.basename(specPath(agent.id)));
1411
+ writableDir ??= path.dirname(file);
1412
+ if (agent.acceptance.status === 'agreed') prompts.push(acceptanceAgreedPrompt(agent.acceptance.points));
1413
+ else if (this.acceptanceWaits(agent)) prompts.push(acceptancePrompt(file, { planReview: Boolean(agent.planReview) && agent.planReview.status !== 'approved' }));
1383
1414
  }
1384
1415
  // Its changes are reviewed in rounds before a pull request (prereview.js): it leaves opening one to that.
1385
1416
  if (withBrief && !planning && this.preReview?.instructs(agent)) prompts.push(preReviewPrompt());
@@ -1439,6 +1470,9 @@ export class AgentManager extends EventEmitter {
1439
1470
  // The repository's standards (standards.js): lessons to follow and the parts marked high risk.
1440
1471
  const standards = task ? this.standards?.prompt(agent) : '';
1441
1472
  if (standards) prompts.push(standards);
1473
+ // The person's own ground rules, for every session in every repository (groundrules.js).
1474
+ const ground = this.groundRules.prompt();
1475
+ if (ground) prompts.push(ground);
1442
1476
  // Commands you chose to always allow in this repo.
1443
1477
  const ruled = agent.workdir ? this.rules.allowed(memoryKey(agent)) : [];
1444
1478
  if (ruled.length) allowedTools = [...(allowedTools ?? []), ...ruled];
@@ -1931,6 +1965,14 @@ export class AgentManager extends EventEmitter {
1931
1965
  allowed.model = String(fields.model ?? '').trim() || null;
1932
1966
  if (engineOf(agent).checkModel) allowed.model = engineOf(agent).checkModel(allowed.model, this.config);
1933
1967
  }
1968
+ // How far it goes without you (autonomy.js); what was done for you so far is kept.
1969
+ if ('autonomy' in fields) {
1970
+ const level = parseLevel(fields.autonomy);
1971
+ if (!level) throw bad('autonomy is one of ask, run, pr, merge');
1972
+ if (level !== 'ask' && !autonomyEligible(agent)) throw bad('Only a task agent with changes of its own can run without you');
1973
+ const cur = agent.autonomy;
1974
+ if (level !== levelOf(agent)) allowed.autonomy = level === 'ask' && !cur?.log?.length ? null : { log: [], seen: {}, ...cur, level, hold: null };
1975
+ }
1934
1976
  // Keep: clean up never closes or deletes it.
1935
1977
  if ('keep' in fields) allowed.keep = Boolean(fields.keep);
1936
1978
  if ('budgetUsd' in fields) {
@@ -2508,7 +2550,21 @@ export class AgentManager extends EventEmitter {
2508
2550
  if (finished && !rounds && !NO_REPO.has(agent.kind) && this.changesSource) this.standards?.finished(agent).catch((e) => this.log?.(`standards: ${e.message}`));
2509
2551
  if (finished && this.judge.enabled && !rounds) this.requestReview(id, { trigger: 'brief' }).catch(() => {});
2510
2552
  // ...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(() => {});
2553
+ // The points were agreed (or changed) after the last score: the brief saying done again is checked against them.
2554
+ const reagreed = brief.status === 'done' && agent.acceptance?.status === 'agreed' && agent.docs?.scorecard?.data && agent.docs.scorecard.acceptanceAt !== agent.acceptance.agreedAt;
2555
+ if ((improved || reagreed || (finished && this.config.scorecard?.auto !== false && !rounds)) && !NO_REPO.has(agent.kind) && this.changesSource) this.summarize(id, 'scorecard').catch(() => {});
2556
+ }
2557
+ // Its points for what done means, written or revised in the spec: they wait for the person.
2558
+ if (this.acceptanceWaits(agent)) {
2559
+ let at = null;
2560
+ try {
2561
+ at = fs.statSync(specPath(id)).mtime.toISOString();
2562
+ } catch {}
2563
+ if (at && at !== agent.acceptance.specAt) {
2564
+ const points = parseCriteria(readSpecDoc(id, 'spec')?.markdown);
2565
+ const cur = this.store.get(id).acceptance;
2566
+ 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 } : {}) } });
2567
+ }
2512
2568
  }
2513
2569
  if (agent.planReview) {
2514
2570
  const file = loadPlanFile(id, agent.planReview);
@@ -2560,6 +2616,97 @@ export class AgentManager extends EventEmitter {
2560
2616
  return this.tell(agent.id, `Plan changes requested. Revise the plan file and wait for approval again:\n${note.trim()}`);
2561
2617
  }
2562
2618
 
2619
+ // ------------------------------------------------------------ ground rules
2620
+
2621
+ /**
2622
+ * Replace the person's ground rules. Sessions started from now on get them with their
2623
+ * instructions; with `tell`, the ones running now are told too. Returns the rules and how many
2624
+ * sessions were told.
2625
+ */
2626
+ setGroundRules(input, { tell = false } = {}) {
2627
+ const r = this.groundRules.set(input);
2628
+ let told = 0;
2629
+ if (tell && r.changed) {
2630
+ for (const [id, rt] of this.runtimes) {
2631
+ const agent = this.store.get(id);
2632
+ if (!rt.pty || !agent) continue;
2633
+ try {
2634
+ this.tell(id, groundRulesMessage(r.rules), { source: 'ground-rules' });
2635
+ told++;
2636
+ } catch {}
2637
+ }
2638
+ }
2639
+ return { ...r, told };
2640
+ }
2641
+
2642
+ // -------------------------------------------------------------- acceptance
2643
+
2644
+ /** Whether the agent is stopped until the person agrees on what done means. */
2645
+ acceptanceWaits(agent) {
2646
+ return Boolean(agent.acceptance?.wait) && ['writing', 'review'].includes(agent.acceptance.status);
2647
+ }
2648
+
2649
+ /**
2650
+ * What done means for an agent: the agreed points with what the last scorecard found for each,
2651
+ * or (not agreed) the points its spec has now. `stale`: agreed or changed since they were checked.
2652
+ */
2653
+ acceptanceOf(ref) {
2654
+ const agent = this.mustGet(ref);
2655
+ const acc = agent.acceptance;
2656
+ const draft = acc?.status === 'agreed' ? [] : parseCriteria(readSpecDoc(agent.id, 'spec')?.markdown);
2657
+ if (acc?.status !== 'agreed') {
2658
+ const status = !acc ? 'none' : draft.length ? 'review' : 'writing';
2659
+ return { id: agent.id, name: agent.name, status, wait: this.acceptanceWaits(agent), draft, points: [], results: [], counts: acceptanceCounts([]), agreedAt: null, checkedAt: null, stale: false };
2660
+ }
2661
+ const sc = agent.docs?.scorecard;
2662
+ const current = Boolean(sc?.data) && sc.acceptanceAt === acc.agreedAt;
2663
+ const res = acceptanceResults(acc.points, current ? sc.data.criteria : null);
2664
+ return {
2665
+ id: agent.id,
2666
+ name: agent.name,
2667
+ status: 'agreed',
2668
+ wait: false,
2669
+ draft: [],
2670
+ points: acc.points,
2671
+ results: res,
2672
+ counts: acceptanceCounts(res),
2673
+ agreedAt: acc.agreedAt,
2674
+ checkedAt: current ? sc.at : null,
2675
+ // Checked against other points, or the brief moved on since: the result is not of the work as it is.
2676
+ stale: Boolean(sc?.data) && (!current || (sc.briefUpdatedAt ?? null) !== (agent.brief?.updatedAt ?? null)),
2677
+ scoring: Boolean(sc?.pending),
2678
+ };
2679
+ }
2680
+
2681
+ /**
2682
+ * Agree on the points (as the agent wrote them, or as the person edited them). From here they
2683
+ * are kept by the app; an agent that is running is told them, one that was waiting goes ahead.
2684
+ */
2685
+ agreeAcceptance(ref, list) {
2686
+ const agent = this.mustGet(ref);
2687
+ if (NO_REPO.has(agent.kind)) throw Object.assign(new Error('Acceptance is for agents that work on a task'), { status: 400 });
2688
+ const prev = agent.acceptance;
2689
+ const draft = prev?.status === 'agreed' ? prev.points.filter((p) => p.from === 'agent').map((p) => p.text) : parseCriteria(readSpecDoc(agent.id, 'spec')?.markdown);
2690
+ const points = cleanPoints(list ?? draft, draft);
2691
+ const waiting = this.acceptanceWaits(agent);
2692
+ const changed = prev?.status === 'agreed';
2693
+ if (changed && prev.points.length === points.length && prev.points.every((p, i) => p.text === points[i].text)) return this.view(agent);
2694
+ 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 } });
2695
+ // 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).
2696
+ 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' }));
2697
+ // Already scored against other criteria: score it against these.
2698
+ if (agent.docs?.scorecard?.data && this.changesSource) this.summarize(agent.id, 'scorecard').catch(() => {});
2699
+ return this.view(this.store.get(agent.id));
2700
+ }
2701
+
2702
+ /** Stop waiting for the person: the agent goes ahead with the criteria in its own spec. */
2703
+ skipAcceptance(ref) {
2704
+ const agent = this.mustGet(ref);
2705
+ if (!this.acceptanceWaits(agent)) throw Object.assign(new Error('The agent is not waiting for the acceptance points'), { status: 409 });
2706
+ this.patch(agent.id, { acceptance: null });
2707
+ return this.tell(agent.id, SKIPPED_MESSAGE);
2708
+ }
2709
+
2563
2710
  /** Turn plan review on (before the agent has implemented anything) or off (no longer waits). */
2564
2711
  setPlanReview(ref, on) {
2565
2712
  const agent = this.mustGet(ref);
@@ -2811,7 +2958,7 @@ export class AgentManager extends EventEmitter {
2811
2958
  const doc = (n) => readSpecDoc(agent.id, n)?.markdown ?? '';
2812
2959
  // The repository's standards: its bar is run here, by the app, before the model is asked.
2813
2960
  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 });
2961
+ 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 });
2815
2962
  const writer = this.writerFor(agent);
2816
2963
  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 ?? [] });
2817
2964
  const sc = combine(parseJsonReply(await this.oneShot(agent, prompt, writer)), f, hunks, { lessons: standards?.lessons ?? [], bar: standards?.bar ?? null });
@@ -2830,6 +2977,8 @@ export class AgentManager extends EventEmitter {
2830
2977
  improvedFrom: cur.improving ? cur.improving.from : null,
2831
2978
  at: now(),
2832
2979
  briefUpdatedAt: cur.brief?.updatedAt ?? null,
2980
+ // The agreed points it was checked against (acceptance.js); null when none were agreed then.
2981
+ acceptanceAt: f.agreed ? cur0.acceptance.agreedAt : null,
2833
2982
  pending: false,
2834
2983
  error: null,
2835
2984
  }),
@@ -3535,6 +3684,26 @@ export class AgentManager extends EventEmitter {
3535
3684
  return this.writerFor(agent);
3536
3685
  }
3537
3686
 
3687
+ /** The models autonomy's own calls run on, best first: config `autonomy.models` on Claude Code, else the summary writer. */
3688
+ ladderModels(agent) {
3689
+ const usable = (e) => e?.supports.oneShot && installed(e, this.config);
3690
+ const out = [];
3691
+ for (const m of autonomySettings(this.config).models) {
3692
+ const engine = ENGINES[typeof m === 'string' ? DEFAULT_ENGINE : m.engine ?? DEFAULT_ENGINE];
3693
+ if (usable(engine)) out.push({ engine, model: typeof m === 'string' ? m : m.model });
3694
+ }
3695
+ return out.length ? out : [this.writerFor(agent)];
3696
+ }
3697
+
3698
+ /**
3699
+ * One call for an agent that runs without the person: on the first of the models that answers.
3700
+ * Resolves to { text, by } (`by`: the model that answered); rejects when none did.
3701
+ */
3702
+ async ladderShot(agent, prompt, { timeoutMs = 120_000 } = {}) {
3703
+ const r = await callLadder(this.ladderModels(agent), (m) => this.oneShot(agent, prompt, { ...m, timeoutMs }), { down: this.modelsDown, retryMs: autonomySettings(this.config).retryMin * 60_000 });
3704
+ return { text: r.text, by: modelName(r.model), tried: r.tried };
3705
+ }
3706
+
3538
3707
  /** The end of the terminal screen as text: cursor moves become spaces or line breaks. */
3539
3708
  screenText(rt) {
3540
3709
  return rt.tail
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/scorecard.js CHANGED
@@ -16,7 +16,7 @@ const WEIGHTS = { intent: 25, spec: 20, tests: 20, safety: 15, scope: 10, plan:
16
16
  const TEST_FILE = /(^|\/)(tests?|__tests__|spec|specs)\/|[._-](test|spec)\.[a-z]+$|_test\.go$|Test\.java$/i;
17
17
 
18
18
  /** Facts the app knows without a model: CI, test files touched, the agent's checks, plan and spec progress. */
19
- export function facts({ files = [], prs = [], brief = null, plan = '', spec = '', standards = null }) {
19
+ export function facts({ files = [], prs = [], brief = null, plan = '', spec = '', standards = null, agreed = null }) {
20
20
  const paths = files.map((f) => f.path);
21
21
  const tests = paths.filter((p) => TEST_FILE.test(p));
22
22
  const code = paths.filter((p) => !TEST_FILE.test(p) && !/\.(md|txt|rst|adoc)$/i.test(p) && !/(^|\/)docs?\//i.test(p));
@@ -37,6 +37,8 @@ export function facts({ files = [], prs = [], brief = null, plan = '', spec = ''
37
37
  plan: steps.length ? { steps: steps.length, done: steps.filter((s) => s === 'x').length } : null,
38
38
  criteria: criteriaBlock.split('\n').filter((l) => /^\s*[-*\d]/.test(l) && /\w/.test(l)).length,
39
39
  hasSpec: Boolean(String(spec).trim()),
40
+ // What done means, agreed with the person (acceptance.js): these are checked, whatever the spec says now.
41
+ agreed: agreed?.length ? agreed.map((p) => ({ id: p.id, text: p.text })) : null,
40
42
  // The repository's standards (standards.js): high-risk files touched, and the bar the app ran.
41
43
  risk: (standards?.risk ?? []).map((r) => r.path),
42
44
  bar: standards?.bar ? { passed: standards.bar.results.filter((r) => r.ok).length, failed: standards.bar.results.filter((r) => !r.ok).map((r) => r.name) } : null,
@@ -50,6 +52,7 @@ export const factLines = (f) =>
50
52
  `the agent's own checks (from its brief): ${f.checks.passed} passed, ${f.checks.failed} failed, ${f.checks.pending} pending`,
51
53
  `plan: ${f.plan ? `${f.plan.done} of ${f.plan.steps} steps ticked` : 'no plan written'}`,
52
54
  `spec: ${f.hasSpec ? `${f.criteria} acceptance criteria` : 'no spec written'}`,
55
+ ...(f.agreed ? [`acceptance agreed with the person: ${f.agreed.length} point${f.agreed.length === 1 ? '' : 's'}`] : []),
53
56
  ...(f.bar ? [`the repository's quality bar, run by the app: ${f.bar.passed} passed, ${f.bar.failed.length} failed${f.bar.failed.length ? ` (${f.bar.failed.join(', ')})` : ''}`] : []),
54
57
  ...(f.risk?.length ? [`files under paths the person marked high risk: ${f.risk.join(', ')}`] : []),
55
58
  ].join('\n');
@@ -62,7 +65,9 @@ export function scorecardPrompt({ intent, status, digest, briefMarkdown, intentD
62
65
  'Reply with one JSON object only:',
63
66
  '{"summary": "<two sentences: what the change does and how sure you are>",',
64
67
  ' "scores": {"intent": {"score": 0-100, "why": "<one sentence>"}, "scope": {...}, "plan": {...}, "tests": {...}, "safety": {...}},',
65
- ' "criteria": [{"criterion": "<an acceptance criterion from the spec>", "status": "met|not_met|unverified", "evidence": "<where: file, test, check>"}],',
68
+ f.agreed
69
+ ? ' "criteria": [{"id": "A1", "criterion": "<the point, as written>", "status": "met|not_met|unverified", "evidence": "<where: file, test, check>"}],'
70
+ : ' "criteria": [{"criterion": "<an acceptance criterion from the spec>", "status": "met|not_met|unverified", "evidence": "<where: file, test, check>"}],',
66
71
  ` "look": [{"id": "H3", "reason": "<why a person should read this hunk>"}]${lessons.length ? ',' : '}'}`,
67
72
  ...(lessons.length ? [' "lessons": [{"id": "L1", "status": "followed|broken|not_applicable", "evidence": "<where in the diff>"}]}'] : []),
68
73
  '',
@@ -72,7 +77,9 @@ export function scorecardPrompt({ intent, status, digest, briefMarkdown, intentD
72
77
  '- plan: how closely the change follows PLAN (steps done, departures explained). Without a plan, judge whether the work is coherent.',
73
78
  '- tests: whether the changed behavior is verified: tests added or updated for it, CI, checks the agent ran. Code changes with no tests and no passing checks score low.',
74
79
  '- safety: 100 when nothing risky is touched or risks are handled; lower for security, auth, data loss, migrations, concurrency, money, new dependencies or public API changes without care.',
75
- '- criteria: one entry per acceptance criterion in SPEC, in its order; leave the list empty if there is no spec.',
80
+ f.agreed
81
+ ? '- criteria: one entry per point in AGREED_ACCEPTANCE, with its id, in its order. The person agreed on these with the agent, so judge the work against them as written, not against the criteria in SPEC. "met" only when the diff, a test or a check shows it; "not_met" when the change does not do it or goes against it; otherwise "unverified".'
82
+ : '- criteria: one entry per acceptance criterion in SPEC, in its order; leave the list empty if there is no spec.',
76
83
  '- look: at most 5 hunks a person must read (the risky, subtle or unverified ones), most important first. Not the obvious ones.',
77
84
  ...(lessons.length ? ['- lessons: one entry per lesson in LESSONS. "broken" only when the diff shows the change going against it; "not_applicable" when the change has nothing to do with it.'] : []),
78
85
  '',
@@ -85,6 +92,7 @@ export function scorecardPrompt({ intent, status, digest, briefMarkdown, intentD
85
92
  '<spec>',
86
93
  specDoc || '(no spec written)',
87
94
  '</spec>',
95
+ ...(f.agreed ? ['<agreed_acceptance>', ...f.agreed.map((p) => `${p.id}: ${p.text}`), '</agreed_acceptance>'] : []),
88
96
  '<plan>',
89
97
  planDoc || '(no plan written)',
90
98
  '</plan>',
@@ -105,6 +113,8 @@ export function scorecardPrompt({ intent, status, digest, briefMarkdown, intentD
105
113
  }
106
114
 
107
115
  const clamp = (n) => Math.max(0, Math.min(100, Math.round(Number(n) || 0)));
116
+ const plain = (s) => String(s ?? '').toLowerCase().replace(/[^\p{L}\p{N}]+/gu, ' ').trim();
117
+ const sameText = (a, b) => plain(a) === plain(b);
108
118
 
109
119
  /**
110
120
  * The scorecard from the model's reply and the facts: scores capped by what was measured, the spec
@@ -131,16 +141,23 @@ export function combine(reply, f, hunks, { lessons = [], bar = null } = {}) {
131
141
  if (f.plan && out.plan) cap('plan', Math.round(40 + (60 * f.plan.done) / f.plan.steps), `${f.plan.done} of ${f.plan.steps} plan steps ticked`);
132
142
  if (!f.plan && out.plan) out.plan.notes.push('no plan written');
133
143
  // Spec: computed from the criteria (met 1, unverified ½, not met 0); none without a spec.
134
- const criteria = (Array.isArray(reply?.criteria) ? reply.criteria : [])
135
- .filter((c) => c?.criterion)
144
+ const told = (Array.isArray(reply?.criteria) ? reply.criteria : [])
145
+ .filter((c) => c?.criterion || c?.id)
136
146
  .slice(0, 20)
137
- .map((c) => ({ criterion: String(c.criterion).slice(0, 300), status: ['met', 'not_met', 'unverified'].includes(c.status) ? c.status : 'unverified', evidence: String(c.evidence ?? '').slice(0, 300) }));
147
+ .map((c) => ({ id: String(c.id ?? '').trim().toUpperCase(), criterion: String(c.criterion ?? '').slice(0, 300), status: ['met', 'not_met', 'unverified'].includes(c.status) ? c.status : 'unverified', evidence: String(c.evidence ?? '').slice(0, 300) }));
148
+ // Points agreed with the person: exactly those, in their words; one the model skipped is unverified.
149
+ const criteria = f.agreed
150
+ ? f.agreed.map((p) => {
151
+ const c = told.find((t) => t.id === p.id) ?? told.find((t) => !t.id && sameText(t.criterion, p.text));
152
+ return { id: p.id, criterion: p.text, status: c?.status ?? 'unverified', evidence: c?.evidence ?? '', agreed: true };
153
+ })
154
+ : told.filter((c) => c.criterion).map(({ id, ...c }) => c);
138
155
  // A spec with criteria the model didn't assess: they count as unverified, not as passed.
139
- if (f.hasSpec && f.criteria && !criteria.length) out.spec = { score: 50, why: `${f.criteria} acceptance criteri${f.criteria === 1 ? 'on' : 'a'} not assessed`, notes: ['treated as unverified'] };
140
- if (f.hasSpec && criteria.length) {
156
+ if (!f.agreed && f.hasSpec && f.criteria && !criteria.length) out.spec = { score: 50, why: `${f.criteria} acceptance criteri${f.criteria === 1 ? 'on' : 'a'} not assessed`, notes: ['treated as unverified'] };
157
+ if ((f.hasSpec || f.agreed) && criteria.length) {
141
158
  const pts = criteria.reduce((n, c) => n + (c.status === 'met' ? 1 : c.status === 'unverified' ? 0.5 : 0), 0);
142
159
  const met = criteria.filter((c) => c.status === 'met').length;
143
- out.spec = { score: clamp((100 * pts) / criteria.length), why: `${met} of ${criteria.length} acceptance criteri${criteria.length === 1 ? 'on' : 'a'} met${criteria.some((c) => c.status === 'not_met') ? ', some not met' : ''}`, notes: [] };
160
+ out.spec = { score: clamp((100 * pts) / criteria.length), why: `${met} of ${criteria.length} acceptance criteri${criteria.length === 1 ? 'on' : 'a'} met${criteria.some((c) => c.status === 'not_met') ? ', some not met' : ''}`, notes: f.agreed ? ['the points agreed with the person'] : [] };
144
161
  }
145
162
  // Overall: weighted over the scores there are.
146
163
  const have = Object.entries(WEIGHTS).filter(([k]) => out[k]);
package/src/server.js CHANGED
@@ -22,6 +22,7 @@ import { Screen } from './screen.js';
22
22
  import { Awake } from './awake.js';
23
23
  import { Files } from './files.js';
24
24
  import { Announcer } from './announce.js';
25
+ import { Autonomy, LEVELS as AUTONOMY_LEVELS, parseLevel } from './autonomy.js';
25
26
  import { Autopilot } from './autopilot.js';
26
27
  import { Goals, goalMarkdown } from './goals.js';
27
28
  import { Budgets } from './budgets.js';
@@ -235,12 +236,20 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
235
236
  manager,
236
237
  config,
237
238
  ship: shipAgent,
238
- managed: (id) => backlog.items().some((it) => it.agentId === id && ['active', 'review'].includes(it.status) && backlog.autopilotFor(it.projectKey) !== 'off'),
239
+ managed: (id) => backlog.items().some((it) => it.agentId === id && ['active', 'review'].includes(it.status) && backlog.levelFor(it) !== 'off'),
239
240
  log: (m) => console.log(`[agentmgr] ${m}`),
240
241
  });
241
242
  // Backlog work the scorecard calls ready goes on to a pull request (and merged) by itself.
242
243
  const autopilot = new Autopilot({ manager, store, backlog, review, landing, config });
243
244
  manager.inboxSources.push(() => autopilot.inbox());
245
+ // Agents that run without you (autonomy.js): routine questions answered from what is decided,
246
+ // nudges and follow-ups sent, and at "merge" the pull request merged when everything says ready.
247
+ const autonomy = new Autonomy({ manager, store, config, review, landing, backlog });
248
+ manager.inboxSources.push(() => autonomy.inbox());
249
+ // How far an agent goes without the person is the person's to set: never an agent's own call.
250
+ const yourLevel = (req) => {
251
+ if (req.headers['x-agentmgr-agent']) throw fail(403, 'How far an agent goes without the person is set by the person, not by an agent');
252
+ };
244
253
  // Daily or weekly goals across projects, planned into backlog tasks and seen through (goals.js).
245
254
  const goals = new Goals({ manager, store, backlog, config });
246
255
  // What agents got done, appended to a CSV for reviews (worklog.js).
@@ -357,7 +366,7 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
357
366
  return {
358
367
  working: views.filter((v) => ['planning', 'working', 'blocked'].includes(v.brief?.status) || (v.runtime.running && v.brief?.status !== 'done')),
359
368
  backlog: backlog.view().items.filter((it) => it.projectKey === p.key && ['queued', 'active', 'review', 'blocked'].includes(it.status)),
360
- waiting: views.filter((v) => v.runtime.attention || v.runtime.waiting || v.planReview?.status === 'review' || (v.questions ?? []).some((q) => !q.answer)),
369
+ waiting: views.filter((v) => v.runtime.attention || v.runtime.waiting || v.planReview?.status === 'review' || (v.acceptance?.status === 'review' && v.acceptance.wait) || (v.questions ?? []).some((q) => !q.answer)),
361
370
  prs,
362
371
  failing: prs.filter((x) => x.checks?.state === 'failed'),
363
372
  bugs: openFindings(p).filter((f) => ['critical', 'high'].includes(f.severity)),
@@ -390,6 +399,11 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
390
399
  questions: (a) => (NO_REPO.has(a.kind) ? [] : loadQuestions(a.id)),
391
400
  bugs: (key) => hunts.list().findings.filter((f) => ['open', 'fixing', 'pr'].includes(f.status) && ['critical', 'high'].includes(f.severity) && manager.resolveProject(f.project)?.key === key).length,
392
401
  enabled: () => config.decide?.enabled !== false,
402
+ // Agents that run without you (autonomy.js): "most things" may be decided for them, never what cannot be taken back.
403
+ autonomous: (id) => autonomy.autonomous(id),
404
+ guard: (item) => (autonomy.autonomous(item.agentId) ? autonomy.guard(item) : null),
405
+ context: (item) => autonomy.briefContext(item),
406
+ onAuto: (h) => autonomy.decided(h),
393
407
  onChange: () => pushAdvisor(),
394
408
  notify: async (text, plain) => {
395
409
  const n = loadNotify();
@@ -586,6 +600,7 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
586
600
  wrap((req) => {
587
601
  const { intents, intent, startedBy, ...opts } = req.body ?? {};
588
602
  if (opts.kind === 'assistant') throw fail(400, 'Start the assistant with POST /assistant/start');
603
+ if (opts.autonomy) yourLevel(req);
589
604
  const list = (Array.isArray(intents) ? intents : [intent]).map((i) => String(i ?? '').trim()).filter(Boolean);
590
605
  // Agents the assistant's own session starts: its limits apply, and they are marked as its.
591
606
  const extra = assistant.admit(req.headers['x-agentmgr-agent'], list, opts);
@@ -673,6 +688,32 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
673
688
  api.post('/agents/:id/plan/approve', wrap((req) => manager.approvePlan(req.params.id, req.body?.note)));
674
689
  api.post('/agents/:id/plan/changes', wrap((req) => manager.requestPlanChanges(req.params.id, req.body?.note)));
675
690
  api.post('/agents/:id/plan/review', wrap((req) => manager.setPlanReview(req.params.id, req.body?.on === true)));
691
+ // Acceptance: what done means, agreed with the person; the scorecard checks each point (acceptance.js).
692
+ api.get('/agents/:id/acceptance', wrap((req) => manager.acceptanceOf(req.params.id)));
693
+ // The points are the person's to agree on: an agent's own calls can read them, not set or skip them.
694
+ const person = (req) => {
695
+ if (req.headers['x-agentmgr-agent']) throw fail(403, 'What done means is agreed by the person, not by an agent');
696
+ };
697
+ api.post('/agents/:id/acceptance/agree', wrap((req) => (person(req), manager.agreeAcceptance(req.params.id, req.body?.points))));
698
+ api.post('/agents/:id/acceptance/skip', wrap((req) => (person(req), manager.skipAcceptance(req.params.id))));
699
+ // Autonomy (autonomy.js): the default level and the models its calls run on; one agent's level;
700
+ // and what was done for the person: seen ("ack"), or an answer changed to their own ("correct").
701
+ api.get('/autonomy', wrap(() => autonomy.status()));
702
+ api.put('/autonomy', wrap((req) => {
703
+ yourLevel(req);
704
+ saveConfig({ autonomy: autonomy.change(req.body ?? {}) });
705
+ return autonomy.status();
706
+ }));
707
+ api.post('/agents/:id/autonomy', wrap((req) => (yourLevel(req), autonomy.setLevel(req.params.id, req.body?.level))));
708
+ api.post('/agents/:id/autonomy/ack', wrap((req) => (yourLevel(req), autonomy.ack(req.params.id, String(req.body?.entry ?? '')))));
709
+ api.post('/agents/:id/autonomy/correct', wrap((req) => (yourLevel(req), autonomy.correct(req.params.id, String(req.body?.entry ?? ''), req.body?.text))));
710
+ // Ground rules: the person's own rules for every session (groundrules.js). Agents can read them, not change them.
711
+ api.get('/ground-rules', wrap(() => manager.groundRules.view()));
712
+ api.put('/ground-rules', wrap((req) => {
713
+ if (req.headers['x-agentmgr-agent']) throw fail(403, 'Ground rules are set by the person, not by an agent');
714
+ const b = req.body ?? {};
715
+ return manager.setGroundRules(b.rules ?? b.text ?? '', { tell: b.tell === true });
716
+ }));
676
717
  api.post('/agents/:id/handoff', wrap((req) => manager.maybeHandoff(manager.mustGet(req.params.id).id, { force: true })));
677
718
  // ---------------------------------------------------------- studio: files and editor
678
719
  api.get('/agents/:id/files', wrap((req) => studio.list(req.params.id, req.query.dir ?? '')));
@@ -743,7 +784,10 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
743
784
  return agent;
744
785
  }),
745
786
  );
746
- api.patch('/agents/:id', wrap((req) => manager.update(req.params.id, req.body ?? {})));
787
+ api.patch('/agents/:id', wrap((req) => {
788
+ if ('autonomy' in (req.body ?? {})) yourLevel(req);
789
+ return manager.update(req.params.id, req.body ?? {});
790
+ }));
747
791
  api.post('/agents/:id/browsers', wrap((req) => manager.addBrowser(req.params.id, req.body?.url, { mode: req.body?.mode })));
748
792
  api.patch(
749
793
  '/agents/:id/browsers/:n',
@@ -900,6 +944,11 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
900
944
  '/backlog',
901
945
  wrap((req) => {
902
946
  const { items, item, ...opts } = req.body ?? {};
947
+ if (opts.autonomy) {
948
+ yourLevel(req);
949
+ opts.autonomy = parseLevel(opts.autonomy);
950
+ if (!opts.autonomy) throw fail(400, `autonomy is one of ${AUTONOMY_LEVELS.join(', ')}`);
951
+ }
903
952
  const added = backlog.add(Array.isArray(items) ? items : [item], opts);
904
953
  repeats.record(added.map((it) => ({ text: it.title, projectKey: it.projectKey })));
905
954
  return added;
@@ -2018,6 +2067,7 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
2018
2067
  benches.close();
2019
2068
  evals.close();
2020
2069
  autopilot.close();
2070
+ autonomy.close();
2021
2071
  goals.close();
2022
2072
  worklog.close();
2023
2073
  triggers.close();
package/src/standup.js CHANGED
@@ -28,6 +28,7 @@ export function needsOf(v) {
28
28
  if (rt.attention) out.push({ kind: 'prompt', text: clip(rt.prompt?.tool?.text ? `${rt.prompt.tool.name} ${rt.prompt.tool.text}` : rt.prompt?.question || rt.attention) });
29
29
  if (rt.waiting) out.push({ kind: 'waiting', text: clip(rt.waiting.summary) });
30
30
  if (v.planReview?.status === 'review') out.push({ kind: 'plan', text: 'its plan is waiting for your review' });
31
+ if (v.acceptance?.status === 'review' && v.acceptance.wait) out.push({ kind: 'acceptance', text: 'what done means is waiting for you to agree' });
31
32
  for (const q of v.questions ?? []) if (!q.answer) out.push({ kind: 'question', text: clip(q.question) });
32
33
  for (const f of v.stuck ?? []) out.push({ kind: 'stuck', text: clip(f.title) });
33
34
  for (const g of v.conflicts ?? []) if (g.mergeFirst !== v.id) out.push({ kind: 'conflict', text: `changes the same files as ${g.agent?.name ?? 'another agent'}` });