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/backlog.js CHANGED
@@ -47,6 +47,14 @@ export class Backlog extends EventEmitter {
47
47
  return AUTOPILOT_LEVELS.includes(level) ? level : 'off';
48
48
  }
49
49
 
50
+ /**
51
+ * Autopilot for one item: its own autonomy level when that says "pr" or "merge" (autonomy.js),
52
+ * else its project's.
53
+ */
54
+ levelFor(it) {
55
+ return ['pr', 'merge'].includes(it?.autonomy) ? it.autonomy : this.autopilotFor(it?.projectKey);
56
+ }
57
+
50
58
  /** The score autopilot ships at (50-100), or null: whenever the scorecard says ready. */
51
59
  targetFor(projectKey) {
52
60
  const n = Number(this.data.targets[projectKey] ?? this.config.autopilot?.target);
@@ -104,7 +112,7 @@ export class Backlog extends EventEmitter {
104
112
  // ------------------------------------------------------------ editing
105
113
 
106
114
  /** Queue one item per title. Options are what an agent would take (repo, dir, base, project, ...). */
107
- add(titles, { repo, dir, base, project, worktree, permissionMode, model, plan, planReview, designDoc, demoPage, benchmarks, engine, attachments, isolation, priority = 2 } = {}) {
115
+ add(titles, { repo, dir, base, project, worktree, permissionMode, model, plan, planReview, acceptance, autonomy, designDoc, demoPage, benchmarks, engine, attachments, isolation, priority = 2 } = {}) {
108
116
  const list = titles.map((t) => String(t ?? '').trim()).filter(Boolean);
109
117
  if (!list.length) throw err(400, 'At least one item is required');
110
118
  const pr = parsePriority(priority);
@@ -141,6 +149,9 @@ export class Backlog extends EventEmitter {
141
149
  isolation: isolation === undefined ? undefined : isolation || '',
142
150
  plan: Boolean(plan),
143
151
  planReview: planReview ?? null,
152
+ acceptance: acceptance ?? null,
153
+ // How far its agent goes without you (autonomy.js): null = the default.
154
+ autonomy: autonomy || null,
144
155
  designDoc: designDoc ?? null,
145
156
  demoPage: demoPage ?? null,
146
157
  benchmarks: benchmarks ?? null,
@@ -266,6 +277,8 @@ export class Backlog extends EventEmitter {
266
277
  isolation: it.isolation,
267
278
  plan: it.plan,
268
279
  planReview: it.planReview ?? undefined,
280
+ acceptance: it.acceptance ?? undefined,
281
+ autonomy: it.autonomy ?? undefined,
269
282
  designDoc: it.designDoc ?? undefined,
270
283
  demoPage: it.demoPage ?? undefined,
271
284
  benchmarks: it.benchmarks ?? undefined,
@@ -416,8 +429,8 @@ export class Backlog extends EventEmitter {
416
429
  if (it.status !== 'queued') throw err(409, 'Only queued items can be split');
417
430
  const titles = (Array.isArray(parts) ? parts : it.aiSplit?.parts ?? []).map((t) => String(t).trim()).filter(Boolean);
418
431
  if (titles.length < 2) throw err(400, 'Give at least two parts');
419
- const { repo, dir, base, project, worktree, permissionMode, model, plan, planReview, designDoc, demoPage, benchmarks, engine, priority } = it;
420
- const added = this.add(titles, { repo, dir, base, project, worktree, permissionMode, model, plan, planReview, designDoc, demoPage, benchmarks, engine, priority });
432
+ const { repo, dir, base, project, worktree, permissionMode, model, plan, planReview, acceptance, autonomy, designDoc, demoPage, benchmarks, engine, priority } = it;
433
+ const added = this.add(titles, { repo, dir, base, project, worktree, permissionMode, model, plan, planReview, acceptance, autonomy, designDoc, demoPage, benchmarks, engine, priority });
421
434
  this.manager.judge?.feedback('dispatch', { summary: `split "${it.title}"`, verdict: it.aiSplit ? 'split suggested' : 'not suggested', outcome: 'split it' });
422
435
  delete this.data.items[id];
423
436
  this.changed();
package/src/brief.js CHANGED
@@ -29,6 +29,9 @@ export const briefPrompt = (file) =>
29
29
  '"- Delivered: ..." for each concrete result (PR or commit links, files, documents, answers), and\n' +
30
30
  '"- Blocked by: ... (needs: who or what)" for anything blocking progress, and\n' +
31
31
  '"- Filed: <issue link> <title>" for each bug or issue you opened (GitHub, Jira, ...). Keep it current; it is what reviewers read first.\n' +
32
+ 'Whenever the outcome is partial or done, add one more line under it: "Confidence: <0-100>% - <what you verified that makes you sure, ' +
33
+ 'and the one thing you are least sure about>". Give the number honestly: what you ran and saw working counts, what you only read or ' +
34
+ 'assumed does not, and anything in the request you did not do lowers it. Update it when you learn more.\n' +
32
35
  'Add a fifth section only when the task links Jira issues (or other tickets):\n' +
33
36
  '## References\nLook each linked issue up (use your Jira / Atlassian tools if you have them) and list the ' +
34
37
  'documents its fields point to, above all its PRD and Tech Spec fields, plus design docs or Confluence pages. ' +
@@ -73,6 +76,19 @@ function sectionKey(heading) {
73
76
  const CHECK_STATES = { ' ': 'pending', '~': 'running', x: 'passed', X: 'passed', '!': 'failed' };
74
77
 
75
78
  /** Parse the brief Markdown into its four sections. Unknown sections are ignored. */
79
+ const CONFIDENCE_LINE = /^\s*(?:[-*]\s+)?\**\s*confidence\s*\**\s*:\s*\**\s*(\d{1,3})\s*%?\s*\**\s*(?:[-–—:,;.]\s*)?(.*)$/i;
80
+
81
+ /** The agent's own confidence in what it built, from its Results: { percent, why, level } or null. */
82
+ export function parseConfidence(body) {
83
+ for (const line of String(body ?? '').split('\n')) {
84
+ const m = CONFIDENCE_LINE.exec(line);
85
+ if (!m) continue;
86
+ const percent = Math.max(0, Math.min(100, Number(m[1])));
87
+ return { percent, why: m[2].trim().slice(0, 400), level: percent >= 85 ? 'high' : percent >= 65 ? 'medium' : 'low' };
88
+ }
89
+ return null;
90
+ }
91
+
76
92
  export function parseBrief(markdown) {
77
93
  const out = { status: null, problem: '', solution: '', diagram: null, diagramNotes: '', checks: [], references: [], results: null };
78
94
  const st = markdown.split(/^##\s/m)[0].match(/^\s*\**status\**\s*:\s*\**\s*(planning|working|blocked|done)\b/im);
@@ -96,8 +112,10 @@ export function parseBrief(markdown) {
96
112
  delivered: pick(/^\s*[-*]\s+\**\s*delivered\s*\**\s*:\s*\**\s*(.+)$/i),
97
113
  blockers: pick(/^\s*[-*]\s+\**\s*blocked by\s*\**\s*:\s*\**\s*(.+)$/i),
98
114
  filed: pick(/^\s*[-*]\s+\**\s*filed\s*\**\s*:\s*\**\s*(.+)$/i),
115
+ // "Confidence: 85% - why": the agent's own, in what it built (null until it says).
116
+ confidence: parseConfidence(body),
99
117
  notes: lines
100
- .filter((l) => !/^\s*\**\s*outcome\s*\**\s*:/i.test(l) && !/^\s*[-*]\s+\**\s*(delivered|blocked by|filed)\s*\**\s*:/i.test(l))
118
+ .filter((l) => !/^\s*\**\s*outcome\s*\**\s*:/i.test(l) && !CONFIDENCE_LINE.test(l) && !/^\s*[-*]\s+\**\s*(delivered|blocked by|filed)\s*\**\s*:/i.test(l))
101
119
  .join('\n')
102
120
  .trim(),
103
121
  };
@@ -953,14 +971,14 @@ export function intentMarkdown(agent) {
953
971
  }
954
972
 
955
973
  /** The agent's instructions for SPEC.md and PLAN.md (the plan only when the plan review isn't on). */
956
- export const specPrompt = (specFile, planFile, { withPlan = true } = {}) =>
974
+ export const specPrompt = (specFile, planFile, { withPlan = true, wait = false } = {}) =>
957
975
  `Before you change any code, write a short spec of the task to ${specFile} (Markdown), so reviewers (people and other agents) ` +
958
976
  'can check the work against it:\n# Spec: <short name>\n## Requirements\nWhat must be true when it is done, as a list.\n' +
959
977
  '## Acceptance criteria\nHow each requirement is checked: a command, a test or an observable behavior.\n## Out of scope\n## Open questions\n' +
960
978
  (withPlan
961
979
  ? `Then write your plan to ${planFile}: "# Plan: <short name>", then "## Steps" as a task list ("- [ ]" to do, "- [x]" done), ` +
962
980
  'small enough to check, and "## Files to change". Keep both current: tick steps as you finish them, and update the spec ' +
963
- 'if the requirements change (say why). Do not stop to wait for approval; carry on with the work. '
981
+ `if the requirements change (say why). ${wait ? '' : 'Do not stop to wait for approval; carry on with the work. '}`
964
982
  : 'Keep it current if the requirements change (say why). ') +
965
983
  'Both files are outside the repository: never copy them into the repo or commit them.';
966
984
 
package/src/bughunt.js CHANGED
@@ -532,6 +532,7 @@ export class BugHunts {
532
532
  name: `fix-${f.title}`.toLowerCase().replace(/[^a-z0-9-]+/g, '-').slice(0, 40),
533
533
  worktree: true,
534
534
  planReview: false,
535
+ acceptance: false,
535
536
  designDoc: false,
536
537
  demoPage: false,
537
538
  benchmarks: false,
package/src/cli.js CHANGED
@@ -350,6 +350,8 @@ export async function main(argv) {
350
350
  .option('--no-container', 'run on this computer even if containers are the default')
351
351
  .option('--plan', 'while a repo URL clones, plan the task with Claude (moves into the repo when ready)')
352
352
  .option('--no-design-doc', 'no design doc for this agent (on by default: "designDoc" in config.json)')
353
+ .option('--acceptance', 'agree on what done means first: the agent writes its points and waits for "agentmgr acceptance <agent> --agree"')
354
+ .option('--autonomy <level>', 'how far it goes without you: ask (the default), run (you agree on what done means, then routine questions are answered and nudges sent for you), pr (and its pull request is opened), merge (and merged when everything says ready)')
353
355
  .option('--demo-page', 'make a sample demo page of the change, published as an Artifact')
354
356
  .option('--benchmarks', 'micro benchmarks of the changed code, before and after')
355
357
  .option('--no-start', 'create without launching')
@@ -379,6 +381,8 @@ export async function main(argv) {
379
381
  start: opts.start,
380
382
  plan: opts.plan,
381
383
  designDoc: cmd.getOptionValueSource('designDoc') === 'cli' ? opts.designDoc : undefined,
384
+ acceptance: opts.acceptance || undefined,
385
+ autonomy: opts.autonomy || undefined,
382
386
  demoPage: opts.demoPage || undefined,
383
387
  benchmarks: opts.benchmarks || undefined,
384
388
  });
@@ -578,6 +582,61 @@ export async function main(argv) {
578
582
  if (d.data.verdict === 'wrong') process.exitCode = 1;
579
583
  });
580
584
 
585
+ program
586
+ .command('acceptance')
587
+ .description('What done means for an agent: the points its work is checked against. The agent drafts them in its spec; you edit and agree; the review scorecard then reports each one as met, not met or not verified')
588
+ .argument('<agent>')
589
+ .option('--agree', 'agree on the points (as the agent wrote them, or as changed by the options below)')
590
+ .option('--add <text>', 'add a point; repeat for more', collect)
591
+ .option('--remove <n>', 'take out point n; repeat for more', collect)
592
+ .option('--set <n=text>', 'reword point n; repeat for more', collect)
593
+ .option('--skip', 'stop waiting: the agent goes ahead with the criteria in its own spec')
594
+ .option('--check', 'score the work against the agreed points now (a separate model call)')
595
+ .option('--json', 'print it as JSON')
596
+ .action(async (ref, opts) => {
597
+ await daemon();
598
+ const a = await resolveAgent(ref);
599
+ let v = await api('GET', `/agents/${a.id}/acceptance`);
600
+ const edits = opts.add?.length || opts.remove?.length || opts.set?.length;
601
+ if (opts.skip) {
602
+ await api('POST', `/agents/${a.id}/acceptance/skip`);
603
+ return console.log(`${green('✓')} Not waiting any more; ${bold(a.name)} goes ahead with its own criteria`);
604
+ }
605
+ if (edits || opts.agree) {
606
+ const points = (v.status === 'agreed' ? v.points.map((p) => p.text) : v.draft).slice();
607
+ const at = (n) => {
608
+ const i = Number(n) - 1;
609
+ if (!Number.isInteger(i) || i < 0 || i >= points.length) throw new Error(`There is no point ${n} (there are ${points.length})`);
610
+ return i;
611
+ };
612
+ for (const s of opts.set ?? []) {
613
+ const m = /^(\d+)=(.+)$/s.exec(s);
614
+ if (!m) throw new Error('--set takes n=text, e.g. --set "2=The export has a header row"');
615
+ points[at(m[1])] = m[2];
616
+ }
617
+ // Highest first, so the numbers the person gave stay right.
618
+ for (const i of [...new Set((opts.remove ?? []).map(at))].sort((x, y) => y - x)) points.splice(i, 1);
619
+ points.push(...(opts.add ?? []));
620
+ await api('POST', `/agents/${a.id}/acceptance/agree`, { points });
621
+ v = await api('GET', `/agents/${a.id}/acceptance`);
622
+ console.error(`${green('✓')} Agreed on ${v.points.length} point${v.points.length === 1 ? '' : 's'} for ${bold(a.name)}`);
623
+ }
624
+ if (opts.check) {
625
+ if (v.status !== 'agreed') throw new Error('Agree on the points first: agentmgr acceptance <agent> --agree');
626
+ process.stderr.write(dim('Checking… (a separate model call; the agent is not interrupted)\n'));
627
+ await api('POST', `/agents/${a.id}/docs/scorecard`);
628
+ v = await api('GET', `/agents/${a.id}/acceptance`);
629
+ }
630
+ if (opts.json) console.log(JSON.stringify(v, null, 2));
631
+ else {
632
+ const { acceptanceMarkdown } = await import('./acceptance.js');
633
+ process.stdout.write(`${acceptanceMarkdown(v, a.name)}\n`);
634
+ if (v.status === 'review' || (v.status === 'none' && v.draft.length)) console.log(dim(`Agree: agentmgr acceptance ${a.slug ?? a.id} --agree (change them with --set n=text, --remove n, --add text)`));
635
+ }
636
+ // For scripts: an agreed point the work does not meet.
637
+ if (v.counts.notMet) process.exitCode = 1;
638
+ });
639
+
581
640
  program
582
641
  .command('insights')
583
642
  .description('Why / What / How / Now for an agent, three tidy points each (one-off Claude call)')
@@ -1700,6 +1759,79 @@ export async function main(argv) {
1700
1759
  if (r.text) console.log(r.text.trimEnd());
1701
1760
  });
1702
1761
 
1762
+ program
1763
+ .command('autonomy')
1764
+ .description('How far agents go without you. Without an agent: the default level and the models used. With one: its level and what was answered, sent or merged for you')
1765
+ .argument('[agent]')
1766
+ .argument('[level]', 'ask, run, pr or merge: set it for this agent')
1767
+ .option('--default <level>', 'the level new agents get when none is named')
1768
+ .option('--models <list>', 'the models its calls run on, best first; the next one is used when a call fails (default: fable,opus,sonnet)')
1769
+ .option('--ok <entry>', 'you have seen an answer given for you (its id from the list; "hold" for a held merge)')
1770
+ .option('--change <entry=answer>', 'your own answer to a question that was answered for you; the agent is told to apply it')
1771
+ .option('--json', 'print as JSON')
1772
+ .action(async (ref, level, o) => {
1773
+ await daemon();
1774
+ const { LEVEL_LABEL, logLine } = await import('./autonomy.js');
1775
+ if (!ref) {
1776
+ const patch = { ...(o.default ? { level: o.default } : {}), ...(o.models ? { models: o.models } : {}) };
1777
+ const s = Object.keys(patch).length ? await api('PUT', '/autonomy', patch) : await api('GET', '/autonomy');
1778
+ if (o.json) return console.log(JSON.stringify(s, null, 2));
1779
+ console.log(`${bold('New agents:')} ${LEVEL_LABEL[s.level]} ${dim(`(${s.level})`)}`);
1780
+ console.log(`${bold('Models, best first:')} ${s.models.map((m) => (typeof m === 'string' ? m : `${m.engine ?? 'claude'}:${m.model}`)).join(' → ')}`);
1781
+ console.log(dim(`${s.agents} agent${s.agents === 1 ? '' : 's'} running without you · ${s.calls} of ${s.dailyCalls} calls today${s.lastModel ? ` · last answered by ${s.lastModel}` : ''}`));
1782
+ if (s.lastError) console.log(dim(`Last failure ${s.lastError.at}: ${s.lastError.message}`));
1783
+ return;
1784
+ }
1785
+ const a = await resolveAgent(ref);
1786
+ let v = a;
1787
+ if (level) v = await api('POST', `/agents/${a.id}/autonomy`, { level });
1788
+ if (o.ok) v = await api('POST', `/agents/${a.id}/autonomy/ack`, { entry: o.ok });
1789
+ if (o.change) {
1790
+ const i = o.change.indexOf('=');
1791
+ if (i < 1 || !o.change.slice(i + 1).trim()) throw new Error('--change takes <entry>=<your answer>');
1792
+ v = await api('POST', `/agents/${a.id}/autonomy/correct`, { entry: o.change.slice(0, i).trim(), text: o.change.slice(i + 1).trim() });
1793
+ }
1794
+ const st = v.autonomy;
1795
+ if (o.json) return console.log(JSON.stringify(st ?? { level: 'ask', log: [] }, null, 2));
1796
+ console.log(`${bold(v.name)}: ${LEVEL_LABEL[st?.level ?? 'ask']} ${dim(`(${st?.level ?? 'ask'})`)}${st?.log?.length ? dim(` · ${logLine(st.log)}`) : ''}`);
1797
+ if (st?.hold && !st.hold.ack) console.log(` ${bold('Not merged:')} ${st.hold.note} ${dim('(--ok hold)')}`);
1798
+ for (const e of st?.log ?? []) {
1799
+ const when = dim(e.at.slice(0, 16).replace('T', ' '));
1800
+ if (e.kind === 'answer') console.log(` ${when} ${dim(e.id)} ${bold('Answered:')} ${e.question}\n → ${e.corrected ? `${dim(e.answer)} → yours: ${e.corrected}` : e.answer}${e.basis ? dim(`\n from: ${e.basis}`) : ''}${dim(` (${e.model ?? (e.via === 'decide' ? 'Decide' : 'model')}, ${Math.round((e.confidence ?? 0) * 100)}%)`)}${e.ack ? '' : dim(' · not seen')}`);
1801
+ else if (e.kind === 'left') console.log(` ${when} ${bold('Left for you:')} ${e.question}${e.why ? dim(`\n ${e.why}`) : ''}`);
1802
+ else console.log(` ${when} ${bold(e.kind === 'nudge' ? 'Nudged:' : e.kind === 'followup' ? 'Told to carry on:' : e.kind === 'plan' ? 'Plan:' : 'Merged:')} ${e.title ?? ''}${e.text ? dim(`\n ${e.text}`) : ''}`);
1803
+ }
1804
+ });
1805
+
1806
+ program
1807
+ .command('ground-rules')
1808
+ .description('Your own rules for every agent, in every repository, next to what is in memory: show them, or change them')
1809
+ .option('--add <rule>', 'add a rule, one short line (repeatable)', collect, [])
1810
+ .option('--remove <n>', 'take out rule n (repeatable)', collect, [])
1811
+ .option('--clear', 'remove them all')
1812
+ .option('--tell', 'also tell the agents running now (others get them when they start)')
1813
+ .option('--json', 'print as JSON')
1814
+ .action(async (o) => {
1815
+ await daemon();
1816
+ let v = await api('GET', '/ground-rules');
1817
+ if (o.clear || o.add.length || o.remove.length) {
1818
+ let rules = o.clear ? [] : v.rules.slice();
1819
+ const drop = new Set();
1820
+ for (const raw of o.remove) {
1821
+ const n = Number(raw);
1822
+ if (!Number.isInteger(n) || n < 1 || n > rules.length) throw new Error(`There is no rule ${raw}: there ${rules.length === 1 ? 'is 1 rule' : `are ${rules.length} rules`}`);
1823
+ drop.add(n - 1);
1824
+ }
1825
+ rules = [...rules.filter((_, i) => !drop.has(i)), ...o.add];
1826
+ v = await api('PUT', '/ground-rules', { rules, tell: Boolean(o.tell) });
1827
+ if (!o.json) console.log(v.changed ? `${green('✓')} ${v.rules.length} ground rule${v.rules.length === 1 ? '' : 's'}; agents get them when they start${v.told ? `, and ${v.told} running now ${v.told === 1 ? 'was' : 'were'} told` : ''}` : dim('Nothing changed.'));
1828
+ }
1829
+ if (o.json) return console.log(JSON.stringify(v, null, 2));
1830
+ if (!v.rules.length) return console.log(dim('No ground rules yet: agentmgr ground-rules --add "Ask before adding a dependency"'));
1831
+ v.rules.forEach((r, i) => console.log(`${dim(`${i + 1}.`)} ${r}`));
1832
+ console.log(dim(v.file));
1833
+ });
1834
+
1703
1835
  const pb = program.command('playbook').description('Saved requests you run again, in several projects, by hand or on a schedule');
1704
1836
  pb.command('ls', { isDefault: true })
1705
1837
  .description('List playbooks')
package/src/config.js CHANGED
@@ -85,6 +85,9 @@ const DEFAULTS = {
85
85
  // Local models: servers on this computer (Ollama, LM Studio, llama.cpp, MLX) and their models, for the
86
86
  // "Local model" engine; `context` is the room Ollama gives a model for an agent (localmodels.js).
87
87
  localModels: { enabled: true, context: 32768 },
88
+ // How far agents go without you (autonomy.js): `level` for new agents (ask, run, pr, merge) and the
89
+ // `models` its decisions run on, best first: { level: 'ask', models: ['fable', 'opus', 'sonnet'] }.
90
+ // Your own rules for every agent are in ~/.agentmanager/ground-rules.md (groundrules.js).
88
91
  // Review rounds before a pull request (prereview.js): critics on other models, until they approve.
89
92
  preReview: { enabled: true, rounds: 4, critics: 2, openPr: true },
90
93
  // Screen (screen.js): this computer's screen in the page, through its own screen sharing on this port.
package/src/decisions.js CHANGED
@@ -7,7 +7,7 @@
7
7
  import crypto from 'node:crypto';
8
8
 
9
9
  const MAX = 2000;
10
- export const DECISION_KINDS = { plan: 'Plan review', answer: 'Your answer', design: 'Design', tradeoff: 'Trade-off', manual: 'Added by you' };
10
+ export const DECISION_KINDS = { plan: 'Plan review', acceptance: 'What done means', answer: 'Your answer', design: 'Design', tradeoff: 'Trade-off', manual: 'Added by you' };
11
11
  const err = (status, message) => Object.assign(new Error(message), { status });
12
12
  const clip = (s, n) => {
13
13
  const t = String(s ?? '').replace(/\s+/g, ' ').trim();
@@ -94,6 +94,10 @@ export class Decisions {
94
94
  if (pr?.decidedAt && ['approved', 'changes'].includes(pr.status)) {
95
95
  put(`plan:${a.id}:${pr.decidedAt}`, { ...base, kind: 'plan', at: pr.decidedAt, title: `Plan for ${a.name}`, decision: pr.status === 'approved' ? 'Approved' : 'Sent back for changes', why: clip(pr.note, 1000) || null });
96
96
  }
97
+ const acc = a.acceptance;
98
+ if (acc?.status === 'agreed') {
99
+ put(`acceptance:${a.id}:${acc.agreedAt}`, { ...base, kind: 'acceptance', at: acc.agreedAt, title: `What done means for ${a.name}`, decision: `Agreed on ${acc.points.length} point${acc.points.length === 1 ? '' : 's'}${acc.yours ? ` (${acc.yours} yours)` : ''}`, why: clip(acc.points.map((p) => `${p.id}: ${p.text}`).join('\n'), 1000) || null });
100
+ }
97
101
  const answers = a.answers ?? {};
98
102
  if (Object.keys(answers).length) {
99
103
  const qs = new Map(this.questions(a).map((q) => [q.id, q]));
@@ -0,0 +1,97 @@
1
+ // Ground rules: the person's own rules for every agent, in every repository and on every engine,
2
+ // given with each session's instructions next to (not instead of) the repository's memory and
3
+ // standards. Memory is what agents learned; standards are per repository; these are how this
4
+ // person wants agents to work anywhere ("ask before adding a dependency", "never force-push").
5
+ // One Markdown file, ~/.agentmanager/ground-rules.md, one rule per line. Only the person sets
6
+ // them: an agent's own calls to change them are refused (server.js).
7
+ import fs from 'node:fs';
8
+ import path from 'node:path';
9
+ import { paths } from './config.js';
10
+
11
+ export const MAX_RULES = 40;
12
+ export const MAX_RULE_CHARS = 400;
13
+ const err = (status, message) => Object.assign(new Error(message), { status });
14
+
15
+ export const groundRulesFile = () => path.join(paths.home, 'ground-rules.md');
16
+
17
+ /** The rules in a text: one per line, list marks and numbers dropped, no empty lines, no repeats. */
18
+ export function parseRules(text) {
19
+ const out = [];
20
+ const seen = new Set();
21
+ for (const raw of String(text ?? '').split('\n')) {
22
+ const line = raw.replace(/\s+/g, ' ').replace(/^\s*(?:[-*+]|\d+[.)])\s+/, '').trim();
23
+ if (!line || /^#/.test(line) || seen.has(line.toLowerCase())) continue;
24
+ seen.add(line.toLowerCase());
25
+ out.push(line);
26
+ }
27
+ return out;
28
+ }
29
+
30
+ /** The rules the person sent, checked: a text or a list. Throws with a status when one is too long or there are too many. */
31
+ export function cleanRules(input) {
32
+ const rules = parseRules(Array.isArray(input) ? input.join('\n') : input);
33
+ const long = rules.find((r) => r.length > MAX_RULE_CHARS);
34
+ if (long) throw err(400, `A ground rule is one short line (${MAX_RULE_CHARS} characters at most): "${long.slice(0, 60)}…"`);
35
+ if (rules.length > MAX_RULES) throw err(400, `At most ${MAX_RULES} ground rules: a long list is not followed, keep the ones that matter`);
36
+ return rules;
37
+ }
38
+
39
+ /** What every session is told, or '' when there are none. */
40
+ export function groundRulesPrompt(rules) {
41
+ if (!rules?.length) return '';
42
+ return [
43
+ 'Ground rules from the user, for everything you do in this session. They come before your own preferences and before what the repository\'s memory suggests. ' +
44
+ 'If the task cannot be done without breaking one, stop and say which and why (in the brief, or as a question) instead of working around it:',
45
+ ...rules.map((r) => `- ${r}`),
46
+ ].join('\n');
47
+ }
48
+
49
+ /** For a session that is already running when the rules change. */
50
+ export const groundRulesMessage = (rules) =>
51
+ rules.length
52
+ ? `The user changed their ground rules. From now on, these apply to everything you do in this session (they replace any ground rules you were given before):\n${rules.map((r) => `- ${r}`).join('\n')}`
53
+ : 'The user removed their ground rules: the ones you were given at the start no longer apply.';
54
+
55
+ export class GroundRules {
56
+ constructor({ file = groundRulesFile() } = {}) {
57
+ this.file = file;
58
+ this.cache = null; // { mtimeMs, rules }
59
+ }
60
+
61
+ /** The rules now (read again when the file changed: it can be edited by hand). */
62
+ list() {
63
+ try {
64
+ const { mtimeMs } = fs.statSync(this.file);
65
+ if (this.cache?.mtimeMs !== mtimeMs) this.cache = { mtimeMs, rules: parseRules(fs.readFileSync(this.file, 'utf8')).slice(0, MAX_RULES) };
66
+ return this.cache.rules;
67
+ } catch {
68
+ this.cache = null;
69
+ return [];
70
+ }
71
+ }
72
+
73
+ view() {
74
+ const rules = this.list();
75
+ let updatedAt = null;
76
+ try {
77
+ updatedAt = fs.statSync(this.file).mtime.toISOString();
78
+ } catch {}
79
+ return { rules, text: rules.join('\n'), file: this.file, max: MAX_RULES, maxChars: MAX_RULE_CHARS, updatedAt };
80
+ }
81
+
82
+ /** Replace the rules. Returns { changed, ...view }. */
83
+ set(input) {
84
+ const rules = cleanRules(input);
85
+ const changed = JSON.stringify(rules) !== JSON.stringify(this.list());
86
+ if (changed) {
87
+ fs.mkdirSync(path.dirname(this.file), { recursive: true });
88
+ fs.writeFileSync(this.file, rules.length ? `${rules.map((r) => `- ${r}`).join('\n')}\n` : '');
89
+ this.cache = null;
90
+ }
91
+ return { changed, ...this.view() };
92
+ }
93
+
94
+ prompt() {
95
+ return groundRulesPrompt(this.list());
96
+ }
97
+ }
package/src/judge.js CHANGED
@@ -259,7 +259,7 @@ export class Judge {
259
259
  const u = this.usage();
260
260
  if (u.calls >= u.cap) return null;
261
261
  this.state.calls++;
262
- const data = parseJsonReply(await this.call(agent, prompt, { timeoutMs: this.settings.timeoutSec * 1000 }));
262
+ const data = parseJsonReply(await this.call(agent, prompt, { timeoutMs: this.settings.timeoutSec * 1000, kind: key.split(':')[0] }));
263
263
  if (!validate(data)) throw new Error('reply did not have the expected shape');
264
264
  data.confidence = Math.max(0, Math.min(1, Number(data.confidence) || 0));
265
265
  return data;