ai-agentmanager 1.68.0 → 1.69.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/brief.js CHANGED
@@ -571,6 +571,53 @@ export function walkthroughPrompt({ intent, status, digest, briefMarkdown, hunks
571
571
  ].join('\n');
572
572
  }
573
573
 
574
+ /**
575
+ * Understanding check: two or three questions a person who really read the change could answer,
576
+ * about what happens rather than what things are called. For a person to answer before approving a
577
+ * large change; the answers and where to read them come with the questions. `hunks` as walkthroughPrompt.
578
+ */
579
+ export function understandingPrompt({ intent, status, digest, briefMarkdown, hunks }) {
580
+ return [
581
+ "You write an understanding check for a person about to approve an AI coding agent's changes.",
582
+ 'Below are the changes as numbered hunks (H1, H2, ...), with the request and its conversation.',
583
+ '',
584
+ 'Reply with one JSON object only, no prose around it:',
585
+ '{"questions": [{"q": "<the question>", "answer": "<the answer, one or two sentences, concrete>", "why": "<why it matters for approving, one sentence>", "hunk": "H3"}]}',
586
+ '',
587
+ 'Rules:',
588
+ '- Two or three questions, never more. Fewer is better when the change is simple.',
589
+ '- Ask what happens: on a failure, a bad or empty input, a second call, a user without access, or what else depends on what changed. Not what a function is called, not trivia, not yes or no questions.',
590
+ '- Each must be answerable from the hunks and the context alone, and the answer must be what the code really does, not what was intended.',
591
+ '- "hunk" is the one hunk where the answer is found.',
592
+ '- Put the question that matters most for safety first.',
593
+ '',
594
+ ...contextBlock({ intent, status, digest, repo: '', briefMarkdown }),
595
+ '<hunks>',
596
+ ...hunks.map((h) => `<hunk id="${h.id}" file="${h.file}">\n${h.head}\n${h.text}\n</hunk>`),
597
+ '</hunks>',
598
+ ].join('\n');
599
+ }
600
+
601
+ /** The model's questions, cleaned and mapped to the hunk where each is answered: [{ q, answer, why, file, head }]. */
602
+ export function understandingFrom(reply, hunks) {
603
+ const byId = new Map(hunks.map((h) => [h.id, h]));
604
+ const clip = (t, n) => String(t ?? '').replace(/\s+/g, ' ').trim().slice(0, n);
605
+ return (Array.isArray(reply?.questions) ? reply.questions : [])
606
+ .map((x) => ({ q: clip(x?.q, 300), answer: clip(x?.answer, 500), why: clip(x?.why, 300), h: byId.get(String(x?.hunk ?? '').trim()) }))
607
+ .filter((x) => x.q && x.answer)
608
+ .slice(0, 3)
609
+ .map(({ h, ...x }) => ({ ...x, file: h?.file ?? null, head: h?.head ?? null }));
610
+ }
611
+
612
+ /** Markdown of a check: the questions, then the answers. */
613
+ export function understandingMarkdown(qs, name = '') {
614
+ const out = [`# Understanding check${name ? `: ${name}` : ''}`, ''];
615
+ qs.forEach((x, i) => out.push(`${i + 1}. ${x.q}`));
616
+ out.push('', '## Answers', '');
617
+ qs.forEach((x, i) => out.push(`${i + 1}. ${x.answer}${x.file ? ` (${x.file}${x.head ? `, ${x.head}` : ''})` : ''}${x.why ? ` Why it matters: ${x.why}` : ''}`));
618
+ return out.join('\n');
619
+ }
620
+
574
621
  /** The hunks a walkthrough explains, from a parsed diff: ids, and the text sent (capped). */
575
622
  export function walkthroughHunks(files, { maxLines = 80, maxChars = 60_000 } = {}) {
576
623
  const out = [];
package/src/cli.js CHANGED
@@ -831,16 +831,82 @@ export async function main(argv) {
831
831
  console.log(`${green('✓')} ${r.existing ? 'pushed to' : 'opened'} ${r.url ?? '(no URL printed by gh)'}`);
832
832
  });
833
833
 
834
+ program
835
+ .command('trace')
836
+ .description('Requirement trace: each point of what done means for an agent, followed to what shows it: whether the scorecard found it met and its evidence, the checks the agent recorded for it (command, exit code, and whether it held when run again), and what is missing. Exit 1 when a point has a gap.')
837
+ .argument('<agent>')
838
+ .option('--json', 'print JSON')
839
+ .action(async (ref, o) => {
840
+ await daemon();
841
+ const a = await resolveAgent(ref);
842
+ const t = await api('GET', `/agents/${a.id}/trace`);
843
+ if (o.json) console.log(JSON.stringify(t, null, 2));
844
+ else console.log((await api('GET', `/agents/${a.id}/trace?format=md`)).markdown);
845
+ if (t.counts.gaps) process.exitCode = 1;
846
+ });
847
+
848
+ program
849
+ .command('understand')
850
+ .description("Understanding check: two or three questions about what an agent's changes do (what happens on a failure, an empty input, what else depends on it), to answer before you approve them. Without --answers it prints the questions only; the answers come with --answers (one-off model call).")
851
+ .argument('<agent>')
852
+ .option('--answers', 'print the answers and where to read them')
853
+ .option('--again', 'write new questions from the changes as they are now')
854
+ .action(async (ref, o) => {
855
+ await daemon();
856
+ const a = await resolveAgent(ref);
857
+ let u = a.docs?.understanding;
858
+ if (!u?.data?.questions?.length || o.again || (a.brief?.updatedAt && u.at && Date.parse(a.brief.updatedAt) > Date.parse(u.at))) {
859
+ process.stderr.write(dim('Writing the questions from its changes… (a separate model call; the agent is not interrupted)\n'));
860
+ u = (await api('POST', `/agents/${a.id}/docs/understanding`)).docs.understanding;
861
+ }
862
+ u.data.questions.forEach((x, i) => console.log(`${bold(`${i + 1}.`)} ${x.q}`));
863
+ if (!o.answers) return console.log(dim(`\nAnswer them first, then: agentmgr understand ${a.id} --answers`));
864
+ console.log('');
865
+ u.data.questions.forEach((x, i) => console.log(`${bold(`${i + 1}.`)} ${x.answer}${x.why ? dim(` ${x.why}`) : ''}${x.file ? dim(`\n read: ${x.file}${x.head ? ` ${x.head}` : ''}`) : ''}`));
866
+ });
867
+
868
+ program
869
+ .command('read-first')
870
+ .description('Finished work waiting for your review, the pieces that need reading most first: each with a level (read closely, look, skim), the reasons from what the app measured (high-risk files, the scorecard, checks, whether the tests notice a mistake, what was left out, risks not checked, its own confidence, size), and where to start. Exit 1 when something is to be read closely.')
871
+ .option('--reviewed <agent>', 'you have reviewed this one: it leaves the queue until the agent changes its work again')
872
+ .option('--reviewed-older <days>', 'mark every one finished more than this many days ago as reviewed')
873
+ .option('--json', 'print JSON')
874
+ .action(async (o) => {
875
+ await daemon();
876
+ if (o.reviewed) {
877
+ const a = await resolveAgent(o.reviewed);
878
+ await api('POST', '/read-first/reviewed', { agent: a.id });
879
+ console.log(`${green('✓')} ${bold(a.name)} marked as reviewed`);
880
+ }
881
+ if (o.reviewedOlder) console.log(`${green('✓')} ${(await api('POST', '/read-first/reviewed', { olderThanDays: Number(o.reviewedOlder) })).marked} marked as reviewed`);
882
+ const { items } = await api('GET', '/read-first');
883
+ if (o.json) return console.log(JSON.stringify(items, null, 2));
884
+ if (!items.length) return console.log(dim('No finished work is waiting for review.'));
885
+ const tone = { close: red, look: yellow, skim: green };
886
+ const word = { close: 'read closely', look: 'look', skim: 'skim' };
887
+ for (const it of items) {
888
+ console.log(`${tone[it.level](word[it.level].padEnd(12))} ${String(it.score).padStart(3)} ${bold(it.name)} ${dim(it.agentId)}${it.project ? dim(` ${it.project}`) : ''}`);
889
+ for (const r of it.reasons.slice(0, 4)) console.log(` - ${r.text}`);
890
+ for (const c of it.calm) console.log(dim(` + ${c}`));
891
+ if (it.start.length) console.log(dim(` start with: ${it.start.join(', ')}`));
892
+ console.log(dim(` agentmgr changes ${it.agentId}${it.pr ? ` · ${it.pr.url}` : ''}`));
893
+ }
894
+ if (items.some((it) => it.level === 'close')) process.exitCode = 1;
895
+ });
896
+
834
897
  program
835
898
  .command('weekly')
836
- .description("Weekly summary for management: a week's work and achievements on one page. The week in one line, highlights, what was merged and finished by project, bugs fixed, the numbers against the week before, estimated value, how the merged work held up, what is in progress and what is blocked. Work that is kept private is listed without a description. A draft: nothing is sent.")
837
- .option('--current', 'this week so far (default: the week that just ended)')
899
+ .description("Weekly summary for management (or --month, --quarter): a period's work and achievements on one page. The week in one line, highlights, what was merged and finished by project, bugs fixed, the numbers against the week before, estimated value, how the merged work held up, what is in progress and what is blocked. Work that is kept private is listed without a description. A draft: nothing is sent.")
900
+ .option('--current', 'the period so far (default: the one that just ended)')
901
+ .option('--month', 'the month instead of the week')
902
+ .option('--quarter', 'the quarter instead of the week')
838
903
  .option('--save', 'also write it to the reports folder (~/.agentmanager/reports/weekly-<monday>.md)')
839
904
  .option('-o, --out <file>', 'write it to this file')
840
905
  .option('--json', 'print the facts as JSON')
841
906
  .action(async (o) => {
842
907
  await daemon();
843
- const r = o.save ? await api('POST', '/weekly/save', { current: Boolean(o.current) }) : await api('GET', `/weekly${o.current ? '?current=1' : ''}`);
908
+ const kind = o.quarter ? 'quarter' : o.month ? 'month' : 'week';
909
+ const r = o.save ? await api('POST', '/weekly/save', { kind, current: Boolean(o.current) }) : await api('GET', `/weekly?kind=${kind}${o.current ? '&current=1' : ''}`);
844
910
  if (o.out) fs.writeFileSync(o.out, `${r.markdown}\n`);
845
911
  if (o.json) return console.log(JSON.stringify(r.facts, null, 2));
846
912
  console.log(r.markdown);
package/src/manager.js CHANGED
@@ -58,6 +58,9 @@ import {
58
58
  benchmarksPrompt,
59
59
  RISKS_PROMPT,
60
60
  OPTIONS_PROMPT,
61
+ understandingPrompt,
62
+ understandingFrom,
63
+ understandingMarkdown,
61
64
  } from './brief.js';
62
65
 
63
66
  // One-off summaries / documents built from an agent's live context.
@@ -69,6 +72,7 @@ const SUMMARIES = {
69
72
  diagrams: { doc: 'diagrams', run: 'runDiagrams' },
70
73
  walkthrough: { doc: 'walkthrough', run: 'runWalkthrough' },
71
74
  scorecard: { doc: 'scorecard', run: 'runScorecard' },
75
+ understanding: { doc: 'understanding', run: 'runUnderstanding' },
72
76
  update: { doc: 'update', run: 'runUpdate' },
73
77
  claims: { doc: 'claims', run: 'runClaims' },
74
78
  };
@@ -140,6 +144,8 @@ import { conflictMessage, findConflicts, related, repoKey, summarize as summariz
140
144
  import { answerMessage, loadQuestions, questionsPath, questionsPrompt } from './inbox.js';
141
145
  import { PROOF_FILE, proofBlock, proofFacts, proofPrompt } from './proof.js';
142
146
  import { PRIVATE_MESSAGE, ideaPatch, keptPrivate, mustBeShareable } from './private.js';
147
+ import { awaitsReview, readFirst } from './readfirst.js';
148
+ import { traceOf } from './trace.js';
143
149
  import { GroundRules, groundRulesMessage } from './groundrules.js';
144
150
  import { autonomySettings, callLadder, eligible as autonomyEligible, levelOf, modelName, parseLevel } from './autonomy.js';
145
151
  import { STUCK_DEFAULTS, detectStuck } from './stuck.js';
@@ -410,6 +416,8 @@ export class AgentManager extends EventEmitter {
410
416
  results: this.results(agent, rt, prs),
411
417
  // Why its work is not sent outside this computer (private.js), or null.
412
418
  keptPrivate: keptPrivate(agent),
419
+ // Finished and waiting for review: how much it needs reading, why, and where to start (readfirst.js).
420
+ readFirst: awaitsReview(agent) ? readFirst(agent, this.traceFor(agent)) : null,
413
421
  priority: agent.priority ?? 2,
414
422
  activeAt: this.activeAt(agent, rt),
415
423
  projectInfo: this.projectInfo(agent),
@@ -2547,6 +2555,13 @@ export class AgentManager extends EventEmitter {
2547
2555
  return true;
2548
2556
  }
2549
2557
 
2558
+ /** The requirement trace of an agent (trace.js), from its proof as it is on disk. */
2559
+ traceFor(agent) {
2560
+ if (!this.proof || (agent.acceptance?.status !== 'agreed' && !agent.docs?.scorecard?.data?.criteria?.length)) return null;
2561
+ const p = this.proof.forScore(agent);
2562
+ return traceOf(agent, p.entries, p.rerun);
2563
+ }
2564
+
2550
2565
  /**
2551
2566
  * Keep an agent's work private, allow sharing it, or go back to what was read (private.js). The
2552
2567
  * person's call. When it becomes private from outside its session, the agent is told.
@@ -2983,6 +2998,48 @@ export class AgentManager extends EventEmitter {
2983
2998
  );
2984
2999
  }
2985
3000
 
3001
+ /**
3002
+ * The understanding check: two or three questions about what the change does, to answer before
3003
+ * approving it. Made from the same diff as the walkthrough; the answers come with them.
3004
+ */
3005
+ async runUnderstanding(agent, ctx) {
3006
+ if (!this.changesSource) throw new Error('Changes are not available here');
3007
+ const data = await this.changesSource(agent.id);
3008
+ const { hunks } = walkthroughHunks(parseDiff(data.diff), { maxChars: 50_000 });
3009
+ if (!hunks.length) throw Object.assign(new Error('No changes to ask about yet'), { status: 400 });
3010
+ const writer = this.writerFor(agent);
3011
+ const questions = understandingFrom(parseJsonReply(await this.oneShot(agent, understandingPrompt({ ...ctx, hunks }), writer)), hunks);
3012
+ if (!questions.length) throw new Error('The model wrote no usable questions: try again');
3013
+ const cur = this.store.get(agent.id);
3014
+ if (!cur) return null;
3015
+ return this.view(
3016
+ this.patch(
3017
+ agent.id,
3018
+ summaryPatch(cur, 'understanding', {
3019
+ data: { questions },
3020
+ diffHash: hash(data.diff),
3021
+ markdown: understandingMarkdown(questions, cur.name),
3022
+ writer: `${writer.engine.label}${writer.model ? ` (${writer.model})` : ''}`,
3023
+ // What the person said about each (understanding.js): { [index]: true (knew it) | false }.
3024
+ knew: {},
3025
+ at: now(),
3026
+ pending: false,
3027
+ error: null,
3028
+ }),
3029
+ ),
3030
+ );
3031
+ }
3032
+
3033
+ /** The person says whether they knew the answer to a question of the check (never the agent's call). */
3034
+ understandingKnew(ref, index, knew) {
3035
+ const agent = this.mustGet(ref);
3036
+ const u = agent.docs?.understanding;
3037
+ const i = Number(index);
3038
+ if (!u?.data?.questions?.[i]) throw Object.assign(new Error('No such question: make the check first'), { status: 404 });
3039
+ this.patch(agent.id, { docs: { ...agent.docs, understanding: { ...u, knew: { ...u.knew, [i]: knew === null ? undefined : Boolean(knew) } } } });
3040
+ return this.view(this.store.get(agent.id));
3041
+ }
3042
+
2986
3043
  /**
2987
3044
  * The review scorecard (see scorecard.js): the same diff the review screen shows, scored against
2988
3045
  * the intent, spec and plan, with the facts the app measures capping what the model says.
package/src/proof.js CHANGED
@@ -156,12 +156,21 @@ export class Proof {
156
156
  constructor({ manager, store, run, log = () => {}, timeoutMs = RERUN_TIMEOUT_MS }) {
157
157
  Object.assign(this, { manager, store, run, log, timeoutMs });
158
158
  this.running = new Map(); // agentId -> the run in progress
159
+ this.cache = new Map(); // agentId -> { mtimeMs, entries }: the proof as last read
159
160
  }
160
161
 
162
+ /** What an agent recorded. Read again only when the file changed: views ask for it often. */
161
163
  read(agentId) {
162
164
  try {
163
- return parseProof(fs.readFileSync(proofPath(agentId), 'utf8'));
165
+ const file = proofPath(agentId);
166
+ const { mtimeMs } = fs.statSync(file);
167
+ const had = this.cache.get(agentId);
168
+ if (had?.mtimeMs === mtimeMs) return had.entries;
169
+ const entries = parseProof(fs.readFileSync(file, 'utf8'));
170
+ this.cache.set(agentId, { mtimeMs, entries });
171
+ return entries;
164
172
  } catch {
173
+ this.cache.delete(agentId);
165
174
  return [];
166
175
  }
167
176
  }
@@ -0,0 +1,148 @@
1
+ // Read first: where a person's attention goes. Finished work waiting for review is ranked by how
2
+ // much it needs reading, from what the app already measured: files marked high risk, the review
3
+ // scorecard, checks and CI, whether the tests notice a mistake (mutate.js), whether the recorded
4
+ // commands held when run again (proof.js), what the agent says it left out, the risks it named
5
+ // and did not check, its own confidence, the size of the change, and whether it ran without the
6
+ // person. Each piece gets a level (read closely, look, skim), the reasons, and where to start.
7
+ // No model is called: every reason is a fact the app holds, so the ranking can be checked.
8
+ import { keptPrivate } from './private.js';
9
+
10
+ export const LEVELS = { close: 'Read closely', look: 'Look', skim: 'Skim' };
11
+ const CLOSE = 45;
12
+ const LOOK = 20;
13
+ const plural = (n, one, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
14
+ const clip = (s, n = 160) => {
15
+ const t = String(s ?? '').replace(/\s+/g, ' ').trim();
16
+ return t.length > n ? `${t.slice(0, n - 1)}…` : t;
17
+ };
18
+
19
+ /**
20
+ * True for work that is finished and still to be reviewed: done or partial, with no merged pull
21
+ * request, and not marked as reviewed by the person since it last changed.
22
+ */
23
+ export function awaitsReview(agent) {
24
+ if (agent?.kind !== 'task' || agent.team || agent.reviewing || agent.hunting) return false;
25
+ const outcome = agent.brief?.results?.outcome;
26
+ const done = agent.brief?.status === 'done' || outcome === 'done' || outcome === 'partial';
27
+ const prs = Object.values(agent.prs ?? {}).filter((p) => p.source !== 'mentioned');
28
+ // Marked as reviewed by the person, and not changed since: done with.
29
+ if (agent.reviewed?.at && !(Date.parse(agent.brief?.updatedAt) > Date.parse(agent.reviewed.at))) return false;
30
+ return done && !prs.some((p) => p.state === 'MERGED') && !(prs.length && prs.every((p) => p.state === 'CLOSED'));
31
+ }
32
+
33
+ /**
34
+ * How much a finished piece of work needs reading: { score (0-100), level, reasons: [{ text,
35
+ * points }] (heaviest first), calm: [what speaks for it], start: [where to begin] }.
36
+ */
37
+ export function readFirst(agent, trace = null) {
38
+ const reasons = [];
39
+ const calm = [];
40
+ const start = [];
41
+ const add = (points, text) => reasons.push({ points, text });
42
+ const b = agent.brief ?? {};
43
+ const sc = agent.docs?.scorecard?.data;
44
+ const f = sc?.facts;
45
+
46
+ // Files the person marked high risk.
47
+ const risk = (agent.standards?.risk ?? []).map((r) => r.path ?? r).filter(Boolean);
48
+ if (risk.length) {
49
+ add(30, `Touches ${plural(risk.length, 'file')} you marked high risk: ${clip(risk.join(', '), 120)}`);
50
+ start.push(...risk.slice(0, 3));
51
+ }
52
+ // The repository's quality bar, CI and its own checks.
53
+ const barFailed = (agent.standards?.bar?.results ?? []).filter((r) => !r.ok).map((r) => r.name);
54
+ if (barFailed.length) add(25, `The quality bar is not met: ${clip(barFailed.join(', '), 100)}`);
55
+ const pr = Object.values(agent.prs ?? {}).find((p) => p.state === 'OPEN');
56
+ if (pr?.checks?.state === 'failed') add(25, 'CI is failing on its pull request');
57
+ const failed = (b.checks ?? []).filter((c) => c.state === 'failed').length;
58
+ const passed = (b.checks ?? []).filter((c) => c.state === 'passed').length;
59
+ if (failed) add(20, `${plural(failed, 'check')} of its own failed`);
60
+
61
+ // The review scorecard.
62
+ if (!sc) add(10, 'Not scored yet');
63
+ else if (sc.recommendation === 'not_ready') add(30, `The scorecard says not ready${sc.reasons?.length ? `: ${clip(sc.reasons[0], 100)}` : ''}`);
64
+ else if (sc.recommendation === 'look') add(15, `The scorecard says to look first${Number.isFinite(sc.overall) ? ` (${sc.overall} of 100)` : ''}`);
65
+ else if (sc.recommendation === 'ready') calm.push(`The scorecard says ready${Number.isFinite(sc.overall) ? ` (${sc.overall} of 100)` : ''}`);
66
+ for (const l of sc?.look ?? []) if (!start.includes(l.file)) start.push(l.file);
67
+
68
+ // Do its tests notice a mistake?
69
+ const m = agent.breaks;
70
+ if (m && !m.baseline?.ok) add(25, 'Its tests failed when the app ran them');
71
+ else if (m) {
72
+ const missed = (m.breaks ?? []).filter((x) => x.status === 'missed');
73
+ const caught = (m.breaks ?? []).filter((x) => x.status === 'caught').length;
74
+ if (missed.length) {
75
+ add(Math.min(20, 8 + 4 * missed.length), `${missed.length} of ${plural(missed.length + caught, 'deliberate break')} in its code went unnoticed by its tests`);
76
+ for (const x of missed.slice(0, 3)) start.push(`${x.file}:${x.line}`);
77
+ } else if (caught) calm.push(`Its tests caught all ${plural(caught, 'deliberate break')}`);
78
+ } else if ((f?.codeFiles ?? 0) > 0) add(5, 'Its tests have not been tested');
79
+
80
+ // Its recorded commands, run again.
81
+ const rerun = agent.proof && agent.proof.proofAt === (agent.proofDoc?.updatedAt ?? null) ? agent.proof.results ?? [] : [];
82
+ const differs = rerun.filter((r) => r.status === 'differs').length;
83
+ if (differs) add(25, `${plural(differs, 'recorded command')} gave a different result when run again`);
84
+ else if (rerun.some((r) => r.status === 'same')) calm.push('Its recorded commands gave the same result when run again');
85
+ if (passed && !agent.proofDoc?.commands) add(8, `No proof recorded for its ${plural(passed, 'passed check')}`);
86
+
87
+ // What done means, point by point (trace.js): points with nothing that shows them.
88
+ const gaps = (trace?.rows ?? []).filter((r) => r.gap && r.status !== 'not_met');
89
+ const notMet = (trace?.rows ?? []).filter((r) => r.status === 'not_met');
90
+ if (notMet.length) add(Math.min(30, 15 * notMet.length), `${plural(notMet.length, 'point')} of what done means ${notMet.length === 1 ? 'is' : 'are'} not met: ${clip(notMet.map((r) => `${r.id} ${r.text}`).join('; '), 120)}`);
91
+ if (gaps.length) add(Math.min(18, 6 * gaps.length), `${plural(gaps.length, 'point')} of what done means ${gaps.length === 1 ? 'has' : 'have'} no recorded run behind ${gaps.length === 1 ? 'it' : 'them'}: ${clip(gaps.map((r) => r.id).join(', '), 60)}`);
92
+ if (trace?.rows.length && !notMet.length && !gaps.length) calm.push(trace.rows.length === 1 ? 'The one point of what done means is shown by a recorded run' : `All ${trace.rows.length} points of what done means are shown by a recorded run`);
93
+
94
+ // What it says itself.
95
+ const notDone = b.results?.notDone ?? [];
96
+ if (notDone.length) add(Math.min(18, 6 * notDone.length), `It lists ${plural(notDone.length, 'thing')} as not done: ${clip(notDone.join('; '), 120)}`);
97
+ const happened = (b.risks ?? []).filter((r) => r.state === 'happened');
98
+ const open = (b.risks ?? []).filter((r) => r.state === 'open');
99
+ if (happened.length) add(Math.min(20, 10 * happened.length), `${plural(happened.length, 'risk')} it named happened: ${clip(happened.map((r) => r.text).join('; '), 120)}`);
100
+ if (open.length) add(Math.min(15, 5 * open.length), `${plural(open.length, 'risk')} it named ${open.length === 1 ? 'was' : 'were'} not checked: ${clip(open.map((r) => r.text).join('; '), 120)}`);
101
+ const conf = b.results?.confidence?.percent;
102
+ if (!Number.isFinite(conf)) add(5, 'It gave no confidence');
103
+ else if (conf < 65) add(15, `Its own confidence is ${conf}%${b.results.confidence.why ? `: ${clip(b.results.confidence.why, 100)}` : ''}`);
104
+ else if (conf < 85) add(5, `Its own confidence is ${conf}%`);
105
+ if (b.results?.outcome === 'partial') add(10, 'It says the work is partial');
106
+
107
+ // Size, and how far it ran without the person.
108
+ const lines = (f?.added ?? 0) + (f?.removed ?? 0);
109
+ if (lines > 1500) add(20, `A large change: ${lines} lines in ${plural(f.files, 'file')}`);
110
+ else if (lines > 400) add(10, `${lines} lines changed in ${plural(f.files, 'file')}`);
111
+ if (f && (f.codeFiles ?? 0) > 0 && !f.testFiles) add(8, 'Code changed with no test file');
112
+ const answered = (agent.autonomy?.log ?? []).filter((e) => e.kind === 'answer').length;
113
+ if (answered) add(Math.min(12, 4 + 2 * answered), `${plural(answered, 'question')} answered for you while it ran without you`);
114
+
115
+ reasons.sort((x, y) => y.points - x.points);
116
+ const score = Math.min(100, reasons.reduce((n, r) => n + r.points, 0));
117
+ return { score, level: score >= CLOSE ? 'close' : score >= LOOK ? 'look' : 'skim', reasons, calm, start: [...new Set(start)].slice(0, 5) };
118
+ }
119
+
120
+ /** The queue: finished work still to be reviewed, the pieces that need reading most first. */
121
+ export function readQueue(agents, view = () => ({})) {
122
+ return agents
123
+ .filter(awaitsReview)
124
+ .map((a) => {
125
+ const v = view(a);
126
+ const pr = Object.values(a.prs ?? {}).find((p) => p.state === 'OPEN' && p.source !== 'mentioned');
127
+ const kept = keptPrivate(a);
128
+ // (The view already ranked it with its trace; this is for callers that only have the agent.)
129
+ return { agentId: a.id, name: a.name, project: v.projectInfo?.name ?? null, title: clip(String(a.intent ?? a.name).split('\n')[0], 120), pr: pr ? { url: pr.url, number: pr.number ?? null } : null, finishedAt: a.brief?.updatedAt ?? null, keptPrivate: Boolean(kept), ...(v.readFirst ?? readFirst(a)) };
130
+ })
131
+ .sort((x, y) => y.score - x.score || String(x.finishedAt).localeCompare(String(y.finishedAt)));
132
+ }
133
+
134
+ export function queueMarkdown(items) {
135
+ const out = ['# Read first', ''];
136
+ if (!items.length) return [...out, 'No finished work is waiting for review.'].join('\n');
137
+ const n = (l) => items.filter((i) => i.level === l).length;
138
+ out.push(`${plural(items.length, 'piece')} of finished work waiting for review: ${n('close')} to read closely, ${n('look')} to look at, ${n('skim')} to skim.`, '');
139
+ for (const it of items) {
140
+ out.push(`## ${LEVELS[it.level]} (${it.score}): ${it.name}${it.project ? ` · ${it.project}` : ''}`, '', it.title, '');
141
+ for (const r of it.reasons.slice(0, 6)) out.push(`- ${r.text}`);
142
+ for (const c of it.calm) out.push(`- In its favour: ${c}`);
143
+ if (it.start.length) out.push('', `Start with: ${it.start.join(', ')}`);
144
+ if (it.pr) out.push('', it.pr.url);
145
+ out.push('');
146
+ }
147
+ return out.join('\n').trimEnd();
148
+ }
package/src/record.js CHANGED
@@ -5,6 +5,8 @@
5
5
  // "said 85% on average, 6 of 10 held up". Per project it also says what level of "Without you"
6
6
  // the record supports. The level stays the person's to set; this only suggests. No model is called.
7
7
 
8
+ import { costOf } from './budgets.js';
9
+
8
10
  export const MIN_TO_SAY = 5; // fewer settled pull requests than this say nothing
9
11
  const LEVELS = ['ask', 'run', 'pr', 'merge'];
10
12
  const LEVEL_LABEL = { ask: 'Ask me', run: 'Agree, then run', pr: 'Run to pull request', merge: 'Run to merge' };
@@ -26,6 +28,8 @@ export function saidOf(agent, { engine = null } = {}) {
26
28
  engine: engine ?? agent.engine ?? 'claude',
27
29
  model: agent.model ?? null,
28
30
  level: LEVELS.includes(agent.autonomy?.level) ? agent.autonomy.level : 'ask',
31
+ // What the AI work cost as it merged, kept only to compare models with each other (never shown as money).
32
+ cost: costOf(agent) || null,
29
33
  };
30
34
  }
31
35
 
@@ -78,6 +82,37 @@ export function suggestLevel(settled, current = 'ask') {
78
82
  return null;
79
83
  }
80
84
 
85
+ const modelKey = (it) => `${it.said?.engine ?? 'unknown'}${it.said?.model ? ` · ${it.said.model}` : ''}`;
86
+
87
+ /**
88
+ * Model fit: which model held up as well as the most used one at a lower cost. Per model: how many
89
+ * settled pieces, the share that held up, the average review scorecard, and the cost per piece
90
+ * against the most used model's (a ratio, not money). A suggestion needs MIN_TO_SAY settled pieces
91
+ * for both, a share that held up within 5 points of the most used model's, and a cost at most
92
+ * three quarters of it. `settled`: the settled pull requests.
93
+ */
94
+ export function modelFit(settled) {
95
+ const keys = [...new Set(settled.map(modelKey))];
96
+ const rows = keys.map((k) => {
97
+ const list = settled.filter((it) => modelKey(it) === k);
98
+ const held = list.filter((it) => it.held).length;
99
+ const costs = list.map((it) => it.said?.cost).filter((c) => Number.isFinite(c) && c > 0);
100
+ const scores = list.map((it) => it.said?.score).filter(Number.isFinite);
101
+ return { model: k, n: list.length, held, heldPct: round((held / list.length) * 100), avgCost: costs.length ? costs.reduce((a, c) => a + c, 0) / costs.length : null, costed: costs.length, score: scores.length ? round(scores.reduce((a, c) => a + c, 0) / scores.length) : null };
102
+ }).sort((a, b) => b.n - a.n);
103
+ const base = rows[0] ?? null;
104
+ const out = rows.map((r) => ({ ...r, costVsMain: base?.avgCost && r.avgCost ? Math.round((r.avgCost / base.avgCost) * 100) / 100 : null, avgCost: undefined }));
105
+ let suggestion = null;
106
+ if (base && base.n >= MIN_TO_SAY && base.avgCost) {
107
+ const better = out
108
+ .slice(1)
109
+ .filter((r) => r.n >= MIN_TO_SAY && r.costed >= MIN_TO_SAY && r.costVsMain != null && r.costVsMain <= 0.75 && r.heldPct >= base.heldPct - 5)
110
+ .sort((a, b) => a.costVsMain - b.costVsMain)[0];
111
+ if (better) suggestion = { model: better.model, main: base.model, costVsMain: better.costVsMain, heldPct: better.heldPct, mainHeldPct: base.heldPct, n: better.n };
112
+ }
113
+ return { rows: out, suggestion };
114
+ }
115
+
81
116
  /**
82
117
  * The record from Quality's items. `verdict(it)` is quality.js's verdictOf; a pull request counts
83
118
  * once it is settled: held up after the watch days, or a problem. `levels`: { default, projects }.
@@ -116,6 +151,7 @@ export function trackRecord(items, verdict, { levels = {} } = {}) {
116
151
  ]),
117
152
  models: rowsOf(settled, uniq((it) => `${it.said?.engine ?? 'unknown'}${it.said?.model ? ` · ${it.said.model}` : ''}`).map((k) => [k, k, (it) => `${it.said?.engine ?? 'unknown'}${it.said?.model ? ` · ${it.said.model}` : ''}` === k])),
118
153
  levels: rowsOf(settled, LEVELS.map((l) => [l, LEVEL_LABEL[l], (it) => (it.said?.level ?? 'ask') === l])),
154
+ fit: modelFit(settled),
119
155
  projects: projects.sort((a, b) => b.n - a.n),
120
156
  defaultLevel: levels.default ?? 'ask',
121
157
  };
@@ -136,6 +172,11 @@ export function recordMarkdown(r) {
136
172
  part('Tests tested', r.tests);
137
173
  part('Model', r.models);
138
174
  part('Without you', r.levels);
175
+ if (r.fit.rows.length > 1) {
176
+ out.push('## Model fit', '', ...r.fit.rows.map((m) => `- ${m.model}: ${m.held} of ${m.n} held up (${m.heldPct}%)${m.score != null ? `, scorecard ${m.score} on average` : ''}${m.costVsMain != null && m !== r.fit.rows[0] ? `, ${m.costVsMain} times the cost of ${r.fit.rows[0].model}` : ''}`));
177
+ if (r.fit.suggestion) out.push('', `**${r.fit.suggestion.model}** held up as well as ${r.fit.suggestion.main} (${r.fit.suggestion.heldPct}% against ${r.fit.suggestion.mainHeldPct}%) at ${r.fit.suggestion.costVsMain} times the cost, over ${r.fit.suggestion.n} settled pull requests: worth trying for more of the work.`);
178
+ out.push('');
179
+ }
139
180
  if (r.projects.length) {
140
181
  out.push('## Projects', '');
141
182
  for (const p of r.projects) {
package/src/server.js CHANGED
@@ -59,6 +59,8 @@ import { Value, valueSlack } from './value.js';
59
59
  import { Quality } from './quality.js';
60
60
  import { recordMarkdown } from './record.js';
61
61
  import { Weekly } from './weekly.js';
62
+ import { queueMarkdown, readQueue } from './readfirst.js';
63
+ import { traceMarkdown, traceOf } from './trace.js';
62
64
  import { PRIVATE_MESSAGE, keptPrivate, mustBeShareable } from './private.js';
63
65
  import { Standards, runCheck } from './standards.js';
64
66
  import { Proof, proofMarkdown } from './proof.js';
@@ -643,6 +645,11 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
643
645
  if (![true, false, null].includes(b.private ?? null)) throw fail(400, 'private is true (keep it private), false (allow sharing) or null (what was read)');
644
646
  return manager.setPrivate(req.params.id, { private: b.private ?? null, note: b.note ?? '' });
645
647
  }));
648
+ // Understanding check: whether you knew the answer. Yours to say, not the agent's.
649
+ api.post('/agents/:id/understanding/knew', wrap((req) => {
650
+ if (req.headers['x-agentmgr-agent']) throw fail(403, 'Whether you knew an answer is said by the person, not by an agent');
651
+ return manager.understandingKnew(req.params.id, req.body?.question, req.body?.knew ?? null);
652
+ }));
646
653
  const DOC_LIST = ['analysis', 'design', 'flow', 'proposal', 'humanai', 'estimate', 'documentation'];
647
654
  api.post('/agents/:id/humanai/answers', wrap((req) => manager.humanAiAnswers(req.params.id, req.body?.answers, { send: req.body?.send === true })));
648
655
  api.post(
@@ -731,6 +738,13 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
731
738
  if (req.headers['x-agentmgr-agent']) throw fail(403, 'Running the proof again is asked by the person, not by an agent');
732
739
  return manager.proof.rerun(req.params.id);
733
740
  }));
741
+ // Requirement trace (trace.js): each point of what done means, followed to the scorecard's finding and the recorded checks.
742
+ api.get('/agents/:id/trace', wrap((req) => {
743
+ const a = manager.mustGet(req.params.id);
744
+ const p = manager.proof.forScore(a);
745
+ const t = traceOf(a, p.entries, p.rerun);
746
+ return req.query.format === 'md' ? { markdown: traceMarkdown(a.name, t) } : t;
747
+ }));
734
748
  // Test the tests (mutate.js): changed lines broken one at a time, the tests run on each. The
735
749
  // person's call only: it runs commands here and changes the agent's files for a moment.
736
750
  api.get('/agents/:id/breaks', wrap(async (req) => {
@@ -1260,9 +1274,26 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
1260
1274
  api.get('/repeats', wrap(() => repeats.view()));
1261
1275
  api.post('/repeats/dismiss', wrap((req) => repeats.dismiss(String(req.body?.key ?? ''))));
1262
1276
  api.post('/playbooks/:id/run', wrap((req) => playbooks.run(req.params.id, { vars: req.body?.vars ?? {} })));
1277
+ // Read first (readfirst.js): finished work waiting for review, the pieces that need reading most first.
1278
+ api.get('/read-first', wrap((req) => {
1279
+ const items = readQueue(store.list(), (a) => manager.view(a));
1280
+ return req.query.format === 'md' ? { markdown: queueMarkdown(items) } : { items };
1281
+ }));
1282
+ // Reviewed: the person has read it, so it leaves the queue until the agent changes its brief again. `olderThanDays` marks every one finished longer ago.
1283
+ api.post('/read-first/reviewed', wrap((req) => {
1284
+ if (req.headers['x-agentmgr-agent']) throw fail(403, 'Whether work was reviewed is said by the person, not by an agent');
1285
+ const b = req.body ?? {};
1286
+ const at = new Date().toISOString();
1287
+ let ids = [];
1288
+ if (b.agent) ids = [manager.mustGet(b.agent).id];
1289
+ else if (Number(b.olderThanDays) > 0) ids = readQueue(store.list(), (a) => manager.view(a)).filter((i) => Date.parse(i.finishedAt) < Date.now() - Number(b.olderThanDays) * 86_400_000).map((i) => i.agentId);
1290
+ else throw fail(400, 'Give agent, or olderThanDays');
1291
+ for (const id of ids) manager.patch(id, { reviewed: b.reviewed === false ? null : { at } });
1292
+ return { marked: ids.length, items: readQueue(store.list(), (a) => manager.view(a)) };
1293
+ }));
1263
1294
  // Weekly summary (weekly.js): a week's work and achievements on one page, for management. A draft: nothing is sent.
1264
- api.get('/weekly', wrap((req) => weekly.report({ current: req.query.current === '1' })));
1265
- api.post('/weekly/save', wrap((req) => weekly.save({ current: req.body?.current === true })));
1295
+ api.get('/weekly', wrap((req) => weekly.report({ kind: String(req.query.kind ?? 'week'), current: req.query.current === '1' })));
1296
+ api.post('/weekly/save', wrap((req) => weekly.save({ kind: String(req.body?.kind ?? 'week'), current: req.body?.current === true })));
1266
1297
  api.get('/worklog', wrap(async (req) => (await worklog.record(), worklog.view({ days: Number(req.query.days ?? 30) || 0 }))));
1267
1298
  api.get('/worklog/summary', wrap(async (req) => {
1268
1299
  await worklog.record();
package/src/trace.js ADDED
@@ -0,0 +1,69 @@
1
+ // Requirement trace: each point of what done means, followed to what shows it. For every agreed
2
+ // acceptance point (acceptance.js), or the scorecard's criteria when none were agreed: whether the
3
+ // review scorecard found it met, with its evidence; the checks the agent recorded for it in its
4
+ // proof (the command, its exit code, and whether it gave the same result when the app ran it
5
+ // again); and what is missing. A point with nothing behind it stands out. No model is called: it
6
+ // joins what the scorecard and the proof already hold.
7
+
8
+ const STATUS = { met: 'Met', not_met: 'Not met', unverified: 'Not verified', unscored: 'Not scored yet' };
9
+ const plain = (s) => String(s ?? '').toLowerCase().replace(/[^\p{L}\p{N}]+/gu, ' ').trim();
10
+ const clip = (s, n = 200) => {
11
+ const t = String(s ?? '').replace(/\s+/g, ' ').trim();
12
+ return t.length > n ? `${t.slice(0, n - 1)}…` : t;
13
+ };
14
+
15
+ /** What is missing behind a point, in a few words, or null when it is shown by a run that held. */
16
+ export function gapOf(row) {
17
+ if (row.status === 'not_met') return 'the scorecard found it not met';
18
+ const runs = row.proof.filter((p) => p.command);
19
+ if (runs.some((p) => p.rerun === 'differs')) return 'its recorded command gave a different result when run again';
20
+ if (!row.proof.length) return row.status === 'met' ? 'met by the scorecard, with no check recorded for it' : 'nothing recorded for it';
21
+ if (!runs.length) return 'checked by reading only: no command was run';
22
+ if (runs.some((p) => p.exit !== null && p.exit !== 0 && !/fail|error|reject|invalid|usage|throw/i.test(`${row.text} ${p.title}`))) return 'its recorded command did not exit with success';
23
+ if (row.status === 'unverified') return 'the scorecard could not verify it';
24
+ return null;
25
+ }
26
+
27
+ /**
28
+ * The trace of an agent's points. `entries`: its proof (proof.js parseProof), `rerun`: the app's
29
+ * last run of it ({ results, stale }). Returns { source, rows, counts }.
30
+ */
31
+ export function traceOf(agent, entries = [], rerun = null) {
32
+ const agreed = agent.acceptance?.status === 'agreed' ? agent.acceptance.points ?? [] : [];
33
+ const criteria = agent.docs?.scorecard?.data?.criteria ?? [];
34
+ const points = agreed.length ? agreed.map((p) => ({ id: p.id, text: p.text })) : criteria.map((c, i) => ({ id: c.id || `C${i + 1}`, text: c.criterion }));
35
+ const again = new Map((rerun && !rerun.stale ? rerun.results ?? [] : []).map((r) => [`${r.title}\n${r.command}`, r.status]));
36
+ const rows = points.map((p) => {
37
+ const c = criteria.find((x) => x.id && x.id === p.id) ?? criteria.find((x) => plain(x.criterion) === plain(p.text));
38
+ // Its proof: sections that start with its id ("A2 …"), or whose title says the same as the point.
39
+ const proof = entries
40
+ .filter((e) => (e.point && e.point === String(p.id).toUpperCase()) || plain(e.title) === plain(p.text))
41
+ .map((e) => ({ title: e.title, command: e.command, exit: e.exit, note: e.command ? '' : clip(e.note, 160), rerun: again.get(`${e.title}\n${e.command}`) ?? null }));
42
+ const row = { id: p.id, text: p.text, status: c?.status ?? 'unscored', evidence: clip(c?.evidence, 240), proof };
43
+ return { ...row, gap: gapOf(row) };
44
+ });
45
+ const n = (f) => rows.filter(f).length;
46
+ return {
47
+ source: agreed.length ? 'agreed' : criteria.length ? 'scorecard' : 'none',
48
+ rows,
49
+ counts: { points: rows.length, met: n((r) => r.status === 'met'), notMet: n((r) => r.status === 'not_met'), shown: n((r) => !r.gap), gaps: n((r) => r.gap) },
50
+ };
51
+ }
52
+
53
+ /** "4 of 5 points shown by a check that held; 1 with a gap" */
54
+ export function traceLine(t) {
55
+ if (!t?.rows.length) return '';
56
+ return `${t.counts.shown} of ${t.counts.points} point${t.counts.points === 1 ? '' : 's'} shown by a recorded run${t.counts.gaps ? `; ${t.counts.gaps} with a gap` : ''}`;
57
+ }
58
+
59
+ export function traceMarkdown(name, t) {
60
+ const out = [`# Requirement trace: ${name}`, ''];
61
+ if (!t.rows.length) return [...out, 'No points to trace: nothing was agreed as what done means, and the scorecard holds no criteria.'].join('\n');
62
+ out.push(t.source === 'agreed' ? 'The points agreed with you as what done means.' : "The scorecard's criteria (no points were agreed).", '', `${traceLine(t)}.`, '');
63
+ for (const r of t.rows) {
64
+ out.push(`## ${r.id} ${r.text}`, '', `- Scorecard: ${STATUS[r.status]}${r.evidence ? `: ${r.evidence}` : ''}`);
65
+ for (const p of r.proof) out.push(`- Check: ${p.command ? `\`${p.command}\`${p.exit === null ? '' : ` (exit ${p.exit})`}${p.rerun ? `, ${p.rerun === 'same' ? 'the same result when run again' : p.rerun === 'differs' ? 'a different result when run again' : 'not run again'}` : ''}` : `by reading${p.note ? `: ${p.note}` : ''}`}`);
66
+ out.push(r.gap ? `- **Gap:** ${r.gap}` : '- Shown by a recorded run.', '');
67
+ }
68
+ return out.join('\n').trimEnd();
69
+ }