ai-agentmanager 1.68.0 → 1.70.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/public/weekly.js CHANGED
@@ -5,12 +5,16 @@
5
5
  export function initWeekly({ api, esc, toast, $, md }) {
6
6
  const dlg = $('#weekly-dialog');
7
7
  let current = false;
8
+ let kind = 'week';
8
9
  let report = null;
9
10
 
10
11
  function render() {
11
- $('#weekly-tabs').innerHTML = [[false, 'Last week'], [true, 'This week so far']]
12
- .map(([v, label]) => `<button type="button" class="chip ${v === current ? 'active' : ''}" role="tab" aria-selected="${v === current}" data-weekly-current="${v ? 1 : 0}">${label}</button>`)
13
- .join('');
12
+ $('#weekly-tabs').innerHTML =
13
+ [['week', 'Week'], ['month', 'Month'], ['quarter', 'Quarter']].map(([k, label]) => `<button type="button" class="chip ${k === kind ? 'active' : ''}" role="tab" aria-selected="${k === kind}" data-weekly-kind="${k}">${label}</button>`).join('') +
14
+ '<span class="weekly-gap"></span>' +
15
+ [[false, `Last ${kind}`], [true, `This ${kind} so far`]]
16
+ .map(([v, label]) => `<button type="button" class="chip ${v === current ? 'active' : ''}" role="tab" aria-selected="${v === current}" data-weekly-current="${v ? 1 : 0}">${label}</button>`)
17
+ .join('');
14
18
  $('#weekly-body').innerHTML = report ? `<div class="md weekly-md">${md(report.markdown)}</div>` : '<p class="hint">Loading…</p>';
15
19
  $('#weekly-note').textContent = report
16
20
  ? `${report.saved ? `Saved as ${report.file}. ` : ''}Put together from the work record, Value and Quality; estimates are marked as estimates. Work that is kept private is listed without a description. Nothing is sent from here.`
@@ -21,7 +25,7 @@ export function initWeekly({ api, esc, toast, $, md }) {
21
25
  report = null;
22
26
  render();
23
27
  try {
24
- report = await api('GET', `/weekly${current ? '?current=1' : ''}`);
28
+ report = await api('GET', `/weekly?kind=${kind}${current ? '&current=1' : ''}`);
25
29
  } catch (err) {
26
30
  $('#weekly-body').innerHTML = `<p class="error">${esc(err.message)}</p>`;
27
31
  return;
@@ -34,6 +38,11 @@ export function initWeekly({ api, esc, toast, $, md }) {
34
38
  load();
35
39
  };
36
40
  dlg.addEventListener('click', async (e) => {
41
+ const k = e.target.closest('[data-weekly-kind]');
42
+ if (k) {
43
+ kind = k.dataset.weeklyKind;
44
+ return load();
45
+ }
37
46
  const tab = e.target.closest('[data-weekly-current]');
38
47
  if (tab) {
39
48
  current = tab.dataset.weeklyCurrent === '1';
@@ -47,13 +56,13 @@ export function initWeekly({ api, esc, toast, $, md }) {
47
56
  await navigator.clipboard.writeText(report.markdown);
48
57
  toast(`Copied the summary for ${report.week.label}`);
49
58
  } else if (act === 'save') {
50
- report = await api('POST', '/weekly/save', { current });
59
+ report = await api('POST', '/weekly/save', { kind, current });
51
60
  toast(`Saved as ${report.file}`, 6000);
52
61
  render();
53
62
  } else if (act === 'download') {
54
63
  const a = document.createElement('a');
55
64
  a.href = URL.createObjectURL(new Blob([`${report.markdown}\n`], { type: 'text/markdown' }));
56
- a.download = `weekly-${report.week.start}.md`;
65
+ a.download = report.file.split('/').pop();
57
66
  a.click();
58
67
  URL.revokeObjectURL(a.href);
59
68
  }
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);
@@ -1575,7 +1641,7 @@ export async function main(argv) {
1575
1641
  const now = v.periods[0];
1576
1642
  const items = v.items.filter((it) => now.items.includes(it.url));
1577
1643
  if (items.length) console.log('');
1578
- const word = { reverted: 'reverted', fixed: 'fixed afterwards', broke: 'failed checks', problem: 'a problem (yours)', clean: 'held up', watching: 'fine so far', unchecked: 'not looked at' };
1644
+ const word = { incident: 'incident in production', reverted: 'reverted', fixed: 'fixed afterwards', broke: 'failed checks', problem: 'a problem (yours)', clean: 'held up', watching: 'fine so far', unchecked: 'not looked at' };
1579
1645
  for (const it of items) console.log(` ${truncate(`#${it.number ?? '?'} ${it.title}`, 54).padEnd(54)} ${(['clean', 'watching'].includes(it.verdict) ? green : it.verdict === 'unchecked' ? dim : yellow)(word[it.verdict].padEnd(17))} ${dim(it.url)}`);
1580
1646
  if (!v.github) console.log(dim('\nGitHub is not asked here, so nothing is looked at.'));
1581
1647
  });
@@ -1590,6 +1656,20 @@ export async function main(argv) {
1590
1656
  console.log((await api('GET', '/quality/record?format=md')).markdown);
1591
1657
  for (const p of r.projects.filter((x) => x.suggestion)) console.log(dim(`\nSet it: agentmgr autonomy --project "${p.label}" --default ${p.suggestion.level}`));
1592
1658
  });
1659
+ qualityCmd
1660
+ .command('incident <title>')
1661
+ .description('Report an incident from production. It is linked to the merged pull request it belongs to (by --pr, the --commit it was seen on, or --files from its stack trace), which then counts as one that did not hold up, in Quality, the track record and the weekly summary. For a monitoring tool or a script: POST /api/quality/incident with the same fields.')
1662
+ .option('--pr <url>', 'the pull request it belongs to')
1663
+ .option('--commit <sha>', 'the commit or release it was seen on')
1664
+ .option('--files <list>', 'files from its stack trace, comma separated')
1665
+ .option('--url <url>', 'a link to the incident in your monitoring tool')
1666
+ .option('--id <id>', 'its id in your monitoring tool: reported again, it is not counted twice')
1667
+ .option('--at <date>', 'when it happened (default: now)')
1668
+ .action(async (title, o) => {
1669
+ await daemon();
1670
+ const it = await api('POST', '/quality/incident', { title, pr: o.pr, commit: o.commit, files: o.files, url: o.url, id: o.id, at: o.at, source: 'cli' });
1671
+ console.log(`${green('✓')} linked to #${it.number ?? '?'} ${bold(it.title)} ${dim(`(matched by ${it.matchedBy})`)}`);
1672
+ });
1593
1673
  qualityCmd
1594
1674
  .command('mark <pr-url>')
1595
1675
  .description('Say what a merged pull request was: not a problem, a problem, or back to what was found')
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
  }
package/src/quality.js CHANGED
@@ -21,8 +21,8 @@ const RETRY_MS = HOUR;
21
21
  const PER_TICK = 3;
22
22
 
23
23
  export const QUALITY_DEFAULTS = { enabled: true, watchDays: 14 };
24
- export const VERDICTS = ['reverted', 'fixed', 'broke', 'problem', 'clean', 'watching', 'unchecked'];
25
- const PROBLEMS = new Set(['reverted', 'fixed', 'broke', 'problem']);
24
+ export const VERDICTS = ['incident', 'reverted', 'fixed', 'broke', 'problem', 'clean', 'watching', 'unchecked'];
25
+ const PROBLEMS = new Set(['incident', 'reverted', 'fixed', 'broke', 'problem']);
26
26
 
27
27
  const err = (status, message) => Object.assign(new Error(message), { status });
28
28
  const clip = (s, n) => {
@@ -94,6 +94,8 @@ export function commitChecks(runs) {
94
94
  export function verdictOf(it, s = QUALITY_DEFAULTS, t = Date.now()) {
95
95
  if (it.mark?.verdict === 'clean') return 'clean';
96
96
  if (it.mark?.verdict === 'problem') return 'problem';
97
+ // Seen in production (a monitoring tool reported it): what users met wins over what GitHub shows.
98
+ if (it.incidents?.length) return 'incident';
97
99
  if (!it.after) return 'unchecked';
98
100
  if (it.after.reverted) return 'reverted';
99
101
  if (it.after.fixes?.length) return 'fixed';
@@ -111,12 +113,12 @@ const round = (n, d = 0) => (Number.isFinite(n) ? Math.round(n * 10 ** d) / 10 *
111
113
 
112
114
  /** Totals for a set of merged pull requests. */
113
115
  export function totals(items, s = QUALITY_DEFAULTS, t = Date.now()) {
114
- const out = { prs: items.length, reverted: 0, fixed: 0, broke: 0, problem: 0, clean: 0, watching: 0, unchecked: 0, changesRequested: 0 };
116
+ const out = { prs: items.length, incident: 0, reverted: 0, fixed: 0, broke: 0, problem: 0, clean: 0, watching: 0, unchecked: 0, changesRequested: 0 };
115
117
  for (const it of items) {
116
118
  out[verdictOf(it, s, t)] += 1;
117
119
  if ((it.facts?.changesRequested ?? 0) > 0) out.changesRequested += 1;
118
120
  }
119
- out.problems = out.reverted + out.fixed + out.broke + out.problem;
121
+ out.problems = out.incident + out.reverted + out.fixed + out.broke + out.problem;
120
122
  // Of the ones looked at: the share that held up, and the share that didn't.
121
123
  out.checked = out.prs - out.unchecked;
122
124
  out.held = out.clean + out.watching;
@@ -147,7 +149,7 @@ export function aggregate(items, s = QUALITY_DEFAULTS, { period = 'week', count,
147
149
  return out;
148
150
  }
149
151
 
150
- const VERDICT_TEXT = { reverted: 'reverted', fixed: 'fixed afterwards', broke: 'checks failed after the merge', problem: 'a problem (marked by me)', clean: 'held up', watching: 'no problem so far', unchecked: 'not looked at yet' };
152
+ const VERDICT_TEXT = { incident: 'caused an incident in production', reverted: 'reverted', fixed: 'fixed afterwards', broke: 'checks failed after the merge', problem: 'a problem (marked by me)', clean: 'held up', watching: 'no problem so far', unchecked: 'not looked at yet' };
151
153
 
152
154
  /** A period's report as Markdown. */
153
155
  export function qualityMarkdown(p, items, s = QUALITY_DEFAULTS, { who = '', prev = null, t = Date.now() } = {}) {
@@ -159,7 +161,7 @@ export function qualityMarkdown(p, items, s = QUALITY_DEFAULTS, { who = '', prev
159
161
  `${x.prs} pull request${x.prs === 1 ? '' : 's'} from AI agents merged.`,
160
162
  '',
161
163
  `- **Held up**: ${x.heldPct == null ? 'n/a' : `${x.heldPct}%`}${was}: ${x.held} of ${x.checked} looked at${x.watching ? `, ${x.watching} still within the ${s.watchDays} days watched` : ''}`,
162
- `- **Problems after the merge**: ${x.problems}: ${x.reverted} reverted, ${x.fixed} fixed afterwards, ${x.broke} with failed checks${x.problem ? `, ${x.problem} marked by me` : ''}`,
164
+ `- **Problems after the merge**: ${x.problems}: ${x.incident ? `${x.incident} caused an incident in production, ` : ''}${x.reverted} reverted, ${x.fixed} fixed afterwards, ${x.broke} with failed checks${x.problem ? `, ${x.problem} marked by me` : ''}`,
163
165
  `- **Before the merge**: a reviewer asked for changes on ${x.changesRequested}${x.changesPct == null ? '' : ` (${x.changesPct}%)`}; ${x.hoursToMerge == null ? 'n/a' : `${x.hoursToMerge} hours`} from opened to merged (median)`,
164
166
  '',
165
167
  ];
@@ -220,6 +222,34 @@ export const github = {
220
222
  },
221
223
  };
222
224
 
225
+ /**
226
+ * Which merged pull request an incident from production belongs to. In order: the pull request it
227
+ * names; the one that merged as the commit it was seen on (a release is often a commit); else, of
228
+ * the ones merged in the watch days before it, the latest that changed a file in its stack trace.
229
+ * { item, by } or null. `items`: Quality's merged pull requests.
230
+ */
231
+ export function matchIncident(items, { pr = null, commit = null, files = [], at = Date.now() } = {}, s = QUALITY_DEFAULTS) {
232
+ if (pr) {
233
+ const it = items.find((x) => x.url === pr || x.url.replace(/\/+$/, '') === String(pr).replace(/\/+$/, ''));
234
+ return it ? { item: it, by: 'pull request' } : null;
235
+ }
236
+ const sha = String(commit ?? '').trim().toLowerCase();
237
+ if (sha.length >= 7) {
238
+ const it = items.find((x) => x.facts?.mergeCommit && (x.facts.mergeCommit.toLowerCase().startsWith(sha) || sha.startsWith(x.facts.mergeCommit.toLowerCase())));
239
+ if (it) return { item: it, by: 'commit' };
240
+ }
241
+ const want = (files ?? []).map((f) => String(f).replace(/^\.?\//, '').replace(/:\d+(:\d+)?$/, '')).filter(Boolean);
242
+ if (want.length) {
243
+ const t = typeof at === 'number' ? at : Date.parse(at) || Date.now();
244
+ const ends = (a, b) => a === b || a.endsWith(`/${b}`) || b.endsWith(`/${a}`);
245
+ const it = items
246
+ .filter((x) => Date.parse(x.mergedAt) <= t && t - Date.parse(x.mergedAt) <= s.watchDays * DAY && (x.facts?.files ?? []).some((f) => want.some((w) => ends(f, w))))
247
+ .sort((a, b) => b.mergedAt.localeCompare(a.mergedAt))[0];
248
+ if (it) return { item: it, by: 'files' };
249
+ }
250
+ return null;
251
+ }
252
+
223
253
  export class Quality {
224
254
  constructor({ manager, store, config = {}, who = null, gh = github, onChange = () => {}, log = (m) => console.log(`[agentmgr] ${m}`) }) {
225
255
  Object.assign(this, { manager, store, config, who, gh, onChange, log });
@@ -332,6 +362,39 @@ export class Quality {
332
362
  .sort((a, b) => (a.checkedAt ?? '').localeCompare(b.checkedAt ?? '') || b.mergedAt.localeCompare(a.mergedAt));
333
363
  }
334
364
 
365
+ /**
366
+ * An incident from production (any monitoring tool, a script or you): linked to the merged pull
367
+ * request it belongs to, which then counts as one that did not hold up. Reported again with the
368
+ * same id, it is not counted twice.
369
+ */
370
+ incident({ title = '', url = null, id = null, at = null, pr = null, commit = null, files = [], source = '' } = {}) {
371
+ this.scan();
372
+ const name = clip(title, 200);
373
+ if (!name) throw err(400, 'An incident needs a title: what went wrong');
374
+ const when = at ? Date.parse(at) : Date.now();
375
+ if (!Number.isFinite(when)) throw err(400, 'at is a date');
376
+ const found = matchIncident(Object.values(this.state.items), { pr, commit, files: Array.isArray(files) ? files : String(files ?? '').split(',').map((f) => f.trim()), at: when }, this.settings);
377
+ if (!found) throw err(404, pr ? 'No merged pull request with that link' : 'No merged pull request matches it: give the pull request, the commit it was seen on, or files from its stack trace');
378
+ const it = found.item;
379
+ const key = String(id ?? url ?? `${name}@${new Date(when).toISOString()}`);
380
+ it.incidents ??= [];
381
+ if (!it.incidents.some((x) => x.key === key)) it.incidents.push({ key, title: name, url: url ? clip(url, 500) : null, at: new Date(when).toISOString(), by: found.by, source: clip(source, 60) || null });
382
+ this.store.save();
383
+ this.onChange();
384
+ return { ...this.itemView(it), matchedBy: found.by };
385
+ }
386
+
387
+ /** Take an incident off a pull request (it was not this one's). */
388
+ dropIncident(url, key) {
389
+ const it = this.state.items[url];
390
+ if (!it) throw err(404, 'No merged pull request with that link');
391
+ it.incidents = (it.incidents ?? []).filter((x) => x.key !== key);
392
+ if (!it.incidents.length) delete it.incidents;
393
+ this.store.save();
394
+ this.onChange();
395
+ return this.itemView(it);
396
+ }
397
+
335
398
  /** What you say about a pull request: 'clean' (not a problem), 'problem', or null for what was found. */
336
399
  mark(url, { verdict = null, note = '' } = {}) {
337
400
  const it = this.state.items[url];
@@ -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
+ }