ai-agentmanager 1.60.0 → 1.61.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.
@@ -0,0 +1,159 @@
1
+ // Standards, inside the Quality view: what every change in a repository has to meet. Lessons from
2
+ // what went wrong (proposed from the merged pull requests that had a problem, yours to word and
3
+ // accept), the paths that are high risk, and the checks the app runs itself before a change is scored.
4
+
5
+ const SAVED = 'agentmgr.standardsRepo';
6
+
7
+ export function initStandards({ api, esc, toast, rerender }) {
8
+ let data = null;
9
+ let repoKey = null;
10
+ let busy = null; // a lesson being worded by a model
11
+ try {
12
+ repoKey = localStorage.getItem(SAVED);
13
+ } catch {}
14
+
15
+ async function load() {
16
+ try {
17
+ data = await api('GET', '/standards');
18
+ // The one being looked at stays, whatever the order becomes (the ones with proposals come first).
19
+ if (!data.repos.some((r) => r.key === repoKey)) repoKey = data.repos[0]?.key ?? null;
20
+ } catch (e) {
21
+ toast?.(e.message, 5000);
22
+ }
23
+ rerender();
24
+ }
25
+
26
+ const repo = () => data?.repos.find((r) => r.key === repoKey) ?? data?.repos[0] ?? null;
27
+ const proposed = () => (data?.repos ?? []).reduce((n, r) => n + r.proposed.length, 0);
28
+
29
+ const source = (s) =>
30
+ s ? `<div class="hint">${s.url ? `<a href="${esc(s.url)}" target="_blank" rel="noopener">#${esc(s.number ?? '?')} ${esc(s.title ?? '')}</a>` : esc(s.title ?? '')}${s.detail ? ` · ${esc(s.detail)}` : ''}</div>` : '';
31
+
32
+ function lessonsHtml(r) {
33
+ const prop = r.proposed
34
+ .map(
35
+ (l) => `<li class="std-proposed" data-std-lesson="${esc(l.id)}">
36
+ ${source(l.source)}
37
+ <div class="std-line">
38
+ <input type="text" maxlength="300" value="${esc(l.text)}" placeholder="What should agents do differently here? One line." aria-label="The lesson" />
39
+ <button type="button" class="small" data-std="draft" ${busy === l.id ? 'disabled' : ''} title="Have a model word it from the pull request and what followed; yours to change">${busy === l.id ? 'Wording…' : 'Suggest wording'}</button>
40
+ <button type="button" class="small primary" data-std="accept" title="Every later agent in this repository is given it, and the scorecard checks it">Accept</button>
41
+ <button type="button" class="small ghost" data-std="dismiss" title="Nothing to learn from this one">Dismiss</button>
42
+ </div></li>`,
43
+ )
44
+ .join('');
45
+ const acc = r.lessons
46
+ .map((l) => `<li data-std-lesson="${esc(l.id)}"><div class="std-line"><span class="std-text">${esc(l.text)}</span><button type="button" class="link" data-std="remove" title="Agents are no longer given it">Remove</button></div>${source(l.source)}</li>`)
47
+ .join('');
48
+ return `<section class="std-section">
49
+ <h3>Lessons <span class="hint">${r.lessons.length} of ${data.limits.lessons}</span></h3>
50
+ <p class="hint">One line each. Every later agent in this repository is told to follow them, and the review scorecard checks each one against the changes: a lesson not followed means "Not ready".</p>
51
+ ${prop ? `<h4>Proposed, from pull requests that had a problem</h4><ul class="std-list">${prop}</ul>` : ''}
52
+ ${acc ? `<ul class="std-list">${acc}</ul>` : prop ? '' : '<p class="hint">No lessons yet. One is proposed here whenever a merged pull request is reverted, fixed afterwards, fails its checks or had changes requested.</p>'}
53
+ <form data-std-form="lesson" class="std-line"><input type="text" name="text" maxlength="300" required placeholder="Add a lesson: e.g. Every new endpoint checks the caller's permissions in a test" aria-label="A new lesson" /><button class="small">Add lesson</button></form>
54
+ </section>`;
55
+ }
56
+
57
+ function riskHtml(r) {
58
+ return `<section class="std-section">
59
+ <h3>High-risk paths <span class="hint">${r.risk.length}</span></h3>
60
+ <p class="hint">A change that touches one is never opened or merged by autopilot or on its Eval without you, is reviewed by another model, and cannot be scored "Ready to approve". Agents are told to say what they will change there before they do. <code>*</code> stays inside a folder, <code>**</code> crosses folders, a name without a slash fits at any depth.</p>
61
+ ${r.risk.length ? `<ul class="std-list">${r.risk.map((x) => `<li><div class="std-line"><code class="std-text">${esc(x.pattern)}</code><span class="hint">${esc(x.why)}</span><button type="button" class="link" data-std="unrisk" data-pattern="${esc(x.pattern)}">Remove</button></div></li>`).join('')}</ul>` : ''}
62
+ <form data-std-form="risk" class="std-line"><input type="text" name="pattern" maxlength="200" required placeholder="src/auth/** or **/migrations/** or *.sql" aria-label="A path pattern" /><input type="text" name="why" maxlength="200" placeholder="Why (optional)" aria-label="Why it is high risk" /><button class="small">Mark high risk</button></form>
63
+ </section>`;
64
+ }
65
+
66
+ function barHtml(r) {
67
+ const b = r.bar;
68
+ return `<section class="std-section">
69
+ <h3>Quality bar <span class="hint">${b.checks.length + (b.tests ? 1 : 0) + (b.secrets ? 1 : 0)} checks</span></h3>
70
+ <p class="hint">Run by the app on an agent's changes, in its folder, before they are scored. A failed check means "Not ready" whatever the agent says, and on autopilot the work goes back to the agent with the output. Each command gets ${Math.round(data.limits.checkSeconds / 60)} minutes.</p>
71
+ <label class="check"><input type="checkbox" data-std-bar="tests" ${b.tests ? 'checked' : ''} /> Code changes need a test file changed too</label>
72
+ <label class="check"><input type="checkbox" data-std-bar="secrets" ${b.secrets ? 'checked' : ''} /> No keys or tokens on the added lines</label>
73
+ ${b.checks.length ? `<ul class="std-list">${b.checks.map((c) => `<li><div class="std-line"><b>${esc(c.name)}</b><code class="std-text">${esc(c.command)}</code><button type="button" class="link" data-std="uncheck" data-name="${esc(c.name)}">Remove</button></div></li>`).join('')}</ul>` : ''}
74
+ ${r.suggested.length ? `<p class="hint">Found in this repository: ${r.suggested.map((c) => `<button type="button" class="chip" data-std="suggest" data-name="${esc(c.name)}" data-command="${esc(c.command)}" title="Add this check">+ ${esc(c.name)}: ${esc(c.command)}</button>`).join(' ')}</p>` : ''}
75
+ <form data-std-form="check" class="std-line"><input type="text" name="label" maxlength="60" placeholder="Name: Lint" aria-label="The check's name" class="std-short" /><input type="text" name="command" maxlength="500" required placeholder="Command: npm run lint" aria-label="The command" /><button class="small">Add check</button></form>
76
+ </section>`;
77
+ }
78
+
79
+ function html() {
80
+ if (!data) return '<p class="hint">Loading…</p>';
81
+ const r = repo();
82
+ if (!r) return '<p class="hint issues-empty">Standards are per repository. Start an agent in one, and it shows here.</p>';
83
+ return `<div class="std">
84
+ <p class="std-repo"><label>Repository <select data-std-repo aria-label="Repository">${data.repos.map((x) => `<option value="${esc(x.key)}" ${x.key === r.key ? 'selected' : ''}>${esc(x.name)}${x.proposed.length ? ` (${x.proposed.length} proposed)` : ''}</option>`).join('')}</select></label>
85
+ <span class="hint">${r.agents} agent${r.agents === 1 ? '' : 's'} here now · what is set applies to agents started from now on, and to every change scored from now on</span></p>
86
+ ${data.enabled ? '' : '<p class="hint"><b>Standards are turned off</b> in config.json ("standards": { "enabled": false }): nothing below is applied.</p>'}
87
+ ${lessonsHtml(r)}${riskHtml(r)}${barHtml(r)}
88
+ </div>`;
89
+ }
90
+
91
+ const save = async (fn, said) => {
92
+ try {
93
+ await fn();
94
+ if (said) toast?.(said);
95
+ } catch (e) {
96
+ toast?.(e.message, 6000);
97
+ }
98
+ document.activeElement?.blur();
99
+ return load();
100
+ };
101
+
102
+ /** A click inside the view; true when it was one of ours. */
103
+ function click(e) {
104
+ const b = e.target.closest('[data-std]');
105
+ const r = repo();
106
+ if (!b || !r) return false;
107
+ const act = b.dataset.std;
108
+ const li = b.closest('[data-std-lesson]');
109
+ const id = li?.dataset.stdLesson;
110
+ const text = li?.querySelector('input')?.value.trim();
111
+ if (act === 'accept') {
112
+ if (!text) return toast?.('Word the lesson first: one line', 4000), true;
113
+ save(() => api('PUT', `/standards/lessons/${id}`, { key: r.key, state: 'accepted', text }), 'Accepted: agents started from now on are given it');
114
+ } else if (act === 'dismiss' || act === 'remove') save(() => api('DELETE', `/standards/lessons/${id}?key=${encodeURIComponent(r.key)}`));
115
+ else if (act === 'draft') {
116
+ busy = id;
117
+ rerender(true);
118
+ save(() => api('POST', `/standards/lessons/${id}/draft`, { key: r.key })).finally(() => {
119
+ busy = null;
120
+ rerender(true);
121
+ });
122
+ } else if (act === 'unrisk') save(() => api('PUT', '/standards/repo', { key: r.key, risk: r.risk.filter((x) => x.pattern !== b.dataset.pattern) }));
123
+ else if (act === 'uncheck') save(() => api('PUT', '/standards/repo', { key: r.key, bar: { checks: r.bar.checks.filter((c) => c.name !== b.dataset.name) } }));
124
+ else if (act === 'suggest') save(() => api('PUT', '/standards/repo', { key: r.key, bar: { checks: [...r.bar.checks, { name: b.dataset.name, command: b.dataset.command }] } }), `Added: ${b.dataset.name}`);
125
+ return true;
126
+ }
127
+
128
+ function change(e) {
129
+ const r = repo();
130
+ if (e.target.matches('[data-std-repo]')) {
131
+ repoKey = e.target.value;
132
+ try {
133
+ localStorage.setItem(SAVED, repoKey);
134
+ } catch {}
135
+ e.target.blur();
136
+ rerender(true);
137
+ return true;
138
+ }
139
+ if (e.target.matches('[data-std-bar]') && r) {
140
+ save(() => api('PUT', '/standards/repo', { key: r.key, bar: { [e.target.dataset.stdBar]: e.target.checked } }));
141
+ return true;
142
+ }
143
+ return false;
144
+ }
145
+
146
+ function submit(e) {
147
+ const f = e.target.closest('[data-std-form]');
148
+ const r = repo();
149
+ if (!f || !r) return false;
150
+ e.preventDefault();
151
+ const kind = f.dataset.stdForm;
152
+ if (kind === 'lesson') save(() => api('POST', '/standards/lessons', { key: r.key, text: f.text.value }), 'Added: agents started from now on are given it');
153
+ else if (kind === 'risk') save(() => api('PUT', '/standards/repo', { key: r.key, risk: [...r.risk, { pattern: f.pattern.value, why: f.why.value }] }));
154
+ else if (kind === 'check') save(() => api('PUT', '/standards/repo', { key: r.key, bar: { checks: [...r.bar.checks, { name: f.label.value, command: f.command.value }] } }));
155
+ return true;
156
+ }
157
+
158
+ return { load, html, click, change, submit, proposed, loaded: () => Boolean(data) };
159
+ }
package/public/style.css CHANGED
@@ -1690,6 +1690,12 @@ table.os-table .num { text-align: right; font-variant-numeric: tabular-nums; whi
1690
1690
  .value-legend { margin: 6px 0 10px; display: flex; align-items: center; gap: 6px; flex-wrap: wrap; }
1691
1691
  .value-legend .sw { display: inline-block; width: 10px; height: 10px; border-radius: 2px; }
1692
1692
  .value-legend .sw.val { background: var(--accent); }
1693
+ .value-bar .bad, .value-legend .sw.bad { background: var(--red); }
1694
+ .value-bar .bad { border-radius: 3px 3px 0 0; }
1695
+ .quality-chip { display: inline-block; padding: 1px 8px; border-radius: 999px; font-size: 12px; white-space: nowrap; border: 1px solid var(--border); }
1696
+ .quality-chip.clean, .quality-chip.watching { color: var(--green); border-color: color-mix(in srgb, var(--green) 50%, transparent); }
1697
+ .quality-chip.reverted, .quality-chip.fixed, .quality-chip.broke, .quality-chip.problem { color: var(--red); border-color: color-mix(in srgb, var(--red) 50%, transparent); }
1698
+ .quality-chip.unchecked { color: var(--muted); }
1693
1699
  .value-legend .sw.rev { background: color-mix(in srgb, var(--green) 70%, transparent); }
1694
1700
  table.value-items td.mine { color: var(--accent); font-weight: 600; }
1695
1701
  table.value-items tr.excluded td { opacity: 0.5; text-decoration: line-through; }
@@ -1698,6 +1704,23 @@ table.value-items tr.value-edit td { background: var(--panel-2); }
1698
1704
  .value-fields { display: grid; grid-template-columns: repeat(auto-fit, minmax(140px, 1fr)); gap: 8px; }
1699
1705
  .value-fields input::placeholder { color: var(--muted); opacity: 0.8; }
1700
1706
  .value-settings { margin-top: 14px; }
1707
+ .sc-risk { margin: 8px 0; color: var(--red); }
1708
+ .sc-risk code, .sc-risk .hint { color: var(--text, inherit); }
1709
+ .sc-tail { max-height: 180px; overflow: auto; font-size: 12px; white-space: pre-wrap; margin: 4px 0 0; }
1710
+ .std-repo { display: flex; flex-wrap: wrap; gap: 8px 14px; align-items: center; margin: 4px 0 6px; }
1711
+ .std-section { border-top: 1px solid var(--border); padding: 10px 0 12px; }
1712
+ .std-section h3 { margin: 0 0 4px; font-size: 15px; }
1713
+ .std-section h4 { margin: 10px 0 4px; font-size: 13px; }
1714
+ .std-section .check { display: flex; gap: 8px; align-items: center; margin: 4px 0; }
1715
+ .std-section .check input[type=checkbox] { width: auto; }
1716
+ .std-repo select { width: auto; max-width: 100%; }
1717
+ .std-list { list-style: none; margin: 6px 0; padding: 0; }
1718
+ .std-list li { padding: 6px 0; border-bottom: 1px dashed var(--border); }
1719
+ .std-proposed { background: color-mix(in srgb, var(--accent) 6%, transparent); padding: 8px !important; border-radius: 6px; margin-bottom: 6px; }
1720
+ .std-line { display: flex; flex-wrap: wrap; gap: 6px 8px; align-items: center; }
1721
+ .std-line input[type="text"] { flex: 1 1 220px; min-width: 0; max-width: 100%; box-sizing: border-box; margin: 0; }
1722
+ .std-line input.std-short { flex: 0 1 140px; }
1723
+ .std-line .std-text { flex: 1 1 220px; min-width: 0; overflow-wrap: anywhere; }
1701
1724
  .value-settings summary { cursor: pointer; font-weight: 600; }
1702
1725
  .value-report-kinds { display: flex; flex-wrap: wrap; gap: 4px 14px; align-items: center; }
1703
1726
  .value-report-kinds input[type="time"] { width: auto; }
package/src/autopilot.js CHANGED
@@ -99,11 +99,18 @@ export class Autopilot {
99
99
  if (agent.preReview?.status === 'stalled') return this.hold(it, `The review rounds did not approve its changes (${agent.preReview.round} ${agent.preReview.round === 1 ? 'round' : 'rounds'}): see what is still open on the agent.`);
100
100
  if (pr?.state === 'CLOSED') return this.hold(it, 'Its pull request was closed without merging.');
101
101
  // Shipped in this round of review: see it through. Reopened since: the new work is scored and pushed to it.
102
- if (pr && ap.shipped === it.reviewAt) return level === 'merge' ? this.land(it, agent, pr) : undefined;
102
+ if (pr && ap.shipped === it.reviewAt) return level === 'merge' && !ap.risk ? this.land(it, agent, pr) : undefined;
103
103
 
104
104
  // Not shipped yet: the scorecard of the current changes decides (unless you said Ship it).
105
105
  const changes = await this.review.get(agent.id);
106
106
  if (!changes.files?.length) return this.hold(it, 'There are no changes to ship.');
107
+ // Under a path you marked high risk (standards.js): yours to approve, and never merged from here.
108
+ const risk = this.manager.standards?.riskIn(agent, changes.files) ?? [];
109
+ if (risk.length) {
110
+ if (ap.ship) return this.ship(it, agent, 'pr', { risk: true });
111
+ const paths = `${risk.slice(0, 3).map((r) => r.path).join(', ')}${risk.length > 3 ? ` and ${risk.length - 3} more` : ''}`;
112
+ return this.hold(it, `It changes high-risk paths (${paths}), so it is yours to approve. Ship it opens the pull request; merging it stays with you.`);
113
+ }
107
114
  if (ap.ship) return this.ship(it, agent, level);
108
115
  const card = agent.docs?.scorecard;
109
116
  if (card?.pending) return;
@@ -141,7 +148,7 @@ export class Autopilot {
141
148
  }
142
149
 
143
150
  /** Commit what's left, push and open the pull request; at "merge", landing takes it from there. */
144
- async ship(it, agent, level) {
151
+ async ship(it, agent, level, { risk = false } = {}) {
145
152
  this.note(it, { state: 'shipping', note: null });
146
153
  const title = it.title.split('\n')[0].slice(0, 100);
147
154
  try {
@@ -152,7 +159,7 @@ export class Autopilot {
152
159
  const { url } = await this.review.pr(agent.id, { title });
153
160
  if (!url) throw err(502, 'Pushed, but no pull request link came back.');
154
161
  this.log(`autopilot: opened ${url} for "${it.title}"`);
155
- this.note(it, { state: level === 'merge' ? 'landing' : 'pr', pr: url, shipped: it.reviewAt, ship: false });
162
+ this.note(it, { state: level === 'merge' ? 'landing' : 'pr', pr: url, shipped: it.reviewAt, ship: false, risk });
156
163
  await this.manager.refresh(agent.id, { withPrs: true }).catch(() => {});
157
164
  }
158
165
 
package/src/cli.js CHANGED
@@ -1378,6 +1378,149 @@ export async function main(argv) {
1378
1378
  console.log(`${r.dismissed} dismissed`);
1379
1379
  });
1380
1380
 
1381
+ const qualityCmd = program.command('quality').description("What happened to the agents' pull requests after they merged: reverted, fixed afterwards, failed checks, or held up; by day, week, month, quarter and year");
1382
+ qualityCmd
1383
+ .command('show', { isDefault: true })
1384
+ .description('The share that held up over the last periods, and the pull requests of the current one')
1385
+ .option('-p, --period <period>', 'day, week, month, quarter or year', 'week')
1386
+ .option('--json', 'print JSON')
1387
+ .action(async (opts) => {
1388
+ await daemon();
1389
+ const v = await api('GET', `/quality?period=${encodeURIComponent(opts.period)}`);
1390
+ if (opts.json) return console.log(JSON.stringify(v, null, 2));
1391
+ for (const p of v.periods.slice(0, 6)) {
1392
+ const t = p.totals;
1393
+ console.log(`${bold(p.label.padEnd(22))} ${String(t.prs).padStart(3)} PRs ${(t.heldPct == null ? '—' : `${t.heldPct}%`).padStart(4)} held up ${t.reverted} reverted ${t.fixed} fixed after ${t.broke} failed checks${t.problem ? ` ${t.problem} marked` : ''}${t.unchecked ? dim(` ${t.unchecked} not looked at`) : ''}${p.current ? dim(' (so far)') : ''}`);
1394
+ }
1395
+ const now = v.periods[0];
1396
+ const items = v.items.filter((it) => now.items.includes(it.url));
1397
+ if (items.length) console.log('');
1398
+ 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' };
1399
+ 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)}`);
1400
+ if (!v.github) console.log(dim('\nGitHub is not asked here, so nothing is looked at.'));
1401
+ });
1402
+ qualityCmd
1403
+ .command('mark <pr-url>')
1404
+ .description('Say what a merged pull request was: not a problem, a problem, or back to what was found')
1405
+ .option('--clean', 'it was not a problem')
1406
+ .option('--problem', 'it was a problem')
1407
+ .option('--found', 'back to what was found')
1408
+ .option('--note <text>', 'why, in a line')
1409
+ .action(async (url, o) => {
1410
+ await daemon();
1411
+ if ([o.clean, o.problem, o.found].filter(Boolean).length !== 1) throw new Error('Give one of --clean, --problem or --found');
1412
+ const it = await api('POST', '/quality/mark', { url, verdict: o.clean ? 'clean' : o.problem ? 'problem' : null, note: o.note ?? '' });
1413
+ console.log(`${green('✓')} #${it.number ?? '?'} ${bold(it.title)}: ${it.verdict}`);
1414
+ });
1415
+ qualityCmd
1416
+ .command('report')
1417
+ .description('The report for a period, as Markdown')
1418
+ .option('-k, --kind <kind>', 'day, week, month, quarter or year', 'week')
1419
+ .option('--current', 'the period so far, not the one just ended')
1420
+ .action(async (o) => {
1421
+ await daemon();
1422
+ console.log((await api('GET', `/quality/report?kind=${encodeURIComponent(o.kind)}${o.current ? '&current=1' : ''}`)).markdown);
1423
+ });
1424
+ qualityCmd
1425
+ .command('set')
1426
+ .description('Settings: how many days after a merge are watched, and on or off')
1427
+ .option('--days <n>', 'days watched after each merge (1 to 90)')
1428
+ .option('--on', 'look at merged pull requests')
1429
+ .option('--off', 'stop looking')
1430
+ .action(async (o) => {
1431
+ await daemon();
1432
+ const patch = { ...(o.days !== undefined ? { watchDays: Number(o.days) } : {}), ...(o.on ? { enabled: true } : {}), ...(o.off ? { enabled: false } : {}) };
1433
+ const v = Object.keys(patch).length ? await api('PUT', '/quality', patch) : await api('GET', '/quality');
1434
+ console.log(`quality: ${v.settings.enabled ? 'on' : 'off'}, ${v.settings.watchDays} days watched after each merge`);
1435
+ });
1436
+
1437
+ const standardsCmd = program.command('standards').description('What every change in a repository has to meet: lessons from what went wrong, high-risk paths that are never merged without you, and the checks the app runs itself');
1438
+ standardsCmd
1439
+ .command('show [repo]', { isDefault: true })
1440
+ .description('The lessons, high-risk paths and checks of each repository (or one)')
1441
+ .option('--json', 'print JSON')
1442
+ .action(async (repo, opts) => {
1443
+ await daemon();
1444
+ const v = await api('GET', '/standards');
1445
+ const repos = repo ? v.repos.filter((r) => r.key === repo || r.name === repo || r.name.split('/').at(-1) === repo) : v.repos;
1446
+ if (opts.json) return console.log(JSON.stringify(repo ? repos : v, null, 2));
1447
+ if (!repos.length) return console.log(dim(repo ? `No repository "${repo}" here.` : 'No repository yet: standards are per repository agents have worked in.'));
1448
+ for (const r of repos) {
1449
+ console.log(`${bold(r.name)} ${dim(r.key)}`);
1450
+ console.log(` Lessons: ${r.lessons.length}${r.proposed.length ? yellow(`, ${r.proposed.length} proposed`) : ''}`);
1451
+ for (const l of r.lessons) console.log(` ${dim(l.id)} ${l.text}`);
1452
+ for (const l of r.proposed) console.log(` ${dim(l.id)} ${yellow('proposed')} ${l.text || dim('(not worded yet)')} ${dim(`#${l.source?.number ?? '?'} ${truncate(l.source?.title ?? '', 40)}: ${l.source?.detail ?? ''}`)}`);
1453
+ console.log(` High-risk paths: ${r.risk.length ? '' : dim('none')}`);
1454
+ for (const x of r.risk) console.log(` ${x.pattern}${x.why ? dim(` (${x.why})`) : ''}`);
1455
+ console.log(` Quality bar: ${[r.bar.tests ? 'tests changed with the code' : null, r.bar.secrets ? 'no secrets in the changes' : null].filter(Boolean).join(', ') || dim('no built-in checks')}`);
1456
+ for (const c of r.bar.checks) console.log(` ${c.name}: ${dim(c.command)}`);
1457
+ for (const c of r.suggested) console.log(dim(` suggested: ${c.name}: ${c.command}`));
1458
+ }
1459
+ });
1460
+ standardsCmd
1461
+ .command('lesson <repo> [text]')
1462
+ .description('Add a lesson (one line); or with --accept, --dismiss or --draft and an id, decide a proposed one')
1463
+ .option('--accept <id>', 'accept a proposed lesson (with [text] as its wording, if given)')
1464
+ .option('--dismiss <id>', 'dismiss a lesson')
1465
+ .option('--draft <id>', 'have a model word a proposed lesson')
1466
+ .action(async (repo, text, o) => {
1467
+ await daemon();
1468
+ if (o.draft) return console.log((await api('POST', `/standards/lessons/${o.draft}/draft`, { key: repo })).text);
1469
+ if (o.dismiss) return (await api('DELETE', `/standards/lessons/${o.dismiss}?key=${encodeURIComponent(repo)}`), console.log(`${green('✓')} dismissed`));
1470
+ const l = o.accept ? await api('PUT', `/standards/lessons/${o.accept}`, { key: repo, state: 'accepted', ...(text ? { text } : {}) }) : await api('POST', '/standards/lessons', { key: repo, text });
1471
+ console.log(`${green('✓')} ${l.text}`);
1472
+ });
1473
+ standardsCmd
1474
+ .command('risk <repo> [patterns...]')
1475
+ .description('Mark paths high risk (src/auth/**, **/migrations/**, *.sql); with --remove, unmark them')
1476
+ .option('--why <text>', 'why, in a few words')
1477
+ .option('--remove', 'unmark the patterns')
1478
+ .action(async (repo, patterns, o) => {
1479
+ await daemon();
1480
+ const cur = (await api('GET', '/standards')).repos.find((r) => r.key === repo || r.name === repo || r.name.split('/').at(-1) === repo);
1481
+ if (!cur) throw new Error(`No repository "${repo}" here`);
1482
+ const risk = o.remove ? cur.risk.filter((x) => !patterns.includes(x.pattern)) : [...cur.risk.filter((x) => !patterns.includes(x.pattern)), ...patterns.map((pattern) => ({ pattern, why: o.why ?? '' }))];
1483
+ const r = patterns.length ? await api('PUT', '/standards/repo', { key: cur.key, risk }) : cur;
1484
+ console.log(r.risk.length ? r.risk.map((x) => `${x.pattern}${x.why ? dim(` (${x.why})`) : ''}`).join('\n') : dim('No high-risk paths'));
1485
+ });
1486
+ standardsCmd
1487
+ .command('bar <repo>')
1488
+ .description('The checks the app runs on changes before they are scored')
1489
+ .option('--add <name=command>', 'add a check, e.g. "Lint=npm run lint" (repeat for more)', (v, all) => [...all, v], [])
1490
+ .option('--remove <name>', 'remove a check (repeat for more)', (v, all) => [...all, v], [])
1491
+ .option('--tests', 'code changes need a test file changed too')
1492
+ .option('--no-tests', 'they do not')
1493
+ .option('--secrets', 'no keys or tokens on the added lines')
1494
+ .option('--no-secrets', 'do not look for them')
1495
+ .action(async (repo, o, cmd) => {
1496
+ await daemon();
1497
+ const cur = (await api('GET', '/standards')).repos.find((r) => r.key === repo || r.name === repo || r.name.split('/').at(-1) === repo);
1498
+ if (!cur) throw new Error(`No repository "${repo}" here`);
1499
+ const set = (n) => cmd.getOptionValueSource(n) === 'cli';
1500
+ const added = o.add.map((v) => {
1501
+ const i = v.indexOf('=');
1502
+ if (i < 1) throw new Error(`--add takes name=command, not "${v}"`);
1503
+ return { name: v.slice(0, i).trim(), command: v.slice(i + 1).trim() };
1504
+ });
1505
+ const checks = [...cur.bar.checks.filter((c) => !o.remove.includes(c.name) && !added.some((a) => a.name === c.name)), ...added];
1506
+ const change = added.length || o.remove.length || set('tests') || set('secrets');
1507
+ const r = change ? await api('PUT', '/standards/repo', { key: cur.key, bar: { checks, ...(set('tests') ? { tests: o.tests } : {}), ...(set('secrets') ? { secrets: o.secrets } : {}) } }) : cur;
1508
+ console.log(`tests changed with the code: ${r.bar.tests ? 'required' : 'not required'}; secrets: ${r.bar.secrets ? 'looked for' : 'not looked for'}`);
1509
+ for (const c of r.bar.checks) console.log(`${c.name}: ${dim(c.command)}`);
1510
+ });
1511
+ standardsCmd
1512
+ .command('run <agent>')
1513
+ .description("Run the repository's bar on an agent's changes now, and show the high-risk paths they touch")
1514
+ .action(async (ref) => {
1515
+ await daemon();
1516
+ const r = await api('POST', `/agents/${encodeURIComponent(ref)}/standards`, {});
1517
+ if (!r) return console.log(dim('Standards are turned off.'));
1518
+ for (const x of r.bar?.results ?? []) console.log(`${x.ok ? green('✓') : yellow('✗')} ${x.name}${x.command ? dim(` (${x.command})`) : ''}${x.ok ? '' : `\n${dim(x.tail)}`}`);
1519
+ if (!r.bar) console.log(dim('No checks set for this repository.'));
1520
+ if (r.risk.length) console.log(yellow(`High-risk paths touched: ${r.risk.map((x) => x.path).join(', ')}`));
1521
+ if (r.bar && !r.bar.ok) process.exitCode = 1;
1522
+ });
1523
+
1381
1524
  const valueCmd = program.command('value').description('What the delivered work is worth (AI estimates you can correct), and the pull requests merged, by day, week, month, quarter and year, with reports for management');
1382
1525
  const money = (n, cur = 'USD') => (n == null ? '—' : new Intl.NumberFormat('en-US', { style: 'currency', currency: cur, maximumFractionDigits: 0 }).format(n));
1383
1526
  valueCmd
package/src/landing.js CHANGED
@@ -246,6 +246,9 @@ export class Landing {
246
246
  tried[key] = { at: new Date().toISOString() };
247
247
  this.store.save();
248
248
  try {
249
+ // Under a path you marked high risk (standards.js): merged by you, not on a score.
250
+ const risk = (await this.manager.standards?.risk(agent.id)) ?? [];
251
+ if (risk.length) throw err(409, `It changes high-risk paths (${risk.slice(0, 3).map((r) => r.path).join(', ')}): yours to merge`);
249
252
  await this.merge(agent.id, { url: pr.url });
250
253
  tried[key].merged = true;
251
254
  this.log(`landing: merged ${pr.url}: its Eval is 100% on its latest commit`);
package/src/manager.js CHANGED
@@ -1434,6 +1434,9 @@ export class AgentManager extends EventEmitter {
1434
1434
  prompts.push(memoryPrompt(memoryText(memoryKey(agent))));
1435
1435
  allowedTools = [`Bash(${learnCommand()}:*)`];
1436
1436
  }
1437
+ // The repository's standards (standards.js): lessons to follow and the parts marked high risk.
1438
+ const standards = task ? this.standards?.prompt(agent) : '';
1439
+ if (standards) prompts.push(standards);
1437
1440
  // Commands you chose to always allow in this repo.
1438
1441
  const ruled = agent.workdir ? this.rules.allowed(memoryKey(agent)) : [];
1439
1442
  if (ruled.length) allowedTools = [...(allowedTools ?? []), ...ruled];
@@ -2499,6 +2502,8 @@ export class AgentManager extends EventEmitter {
2499
2502
  if (agent.hunting) return;
2500
2503
  // Reviewed in rounds before a pull request (prereview.js): the review and the score wait for their end.
2501
2504
  const rounds = !NO_REPO.has(agent.kind) && this.changesSource && this.preReview?.brief(agent, { finished });
2505
+ // A change under a high-risk path is reviewed by another model, also with review rounds off (standards.js).
2506
+ if (finished && !rounds && !NO_REPO.has(agent.kind) && this.changesSource) this.standards?.finished(agent).catch((e) => this.log?.(`standards: ${e.message}`));
2502
2507
  if (finished && this.judge.enabled && !rounds) this.requestReview(id, { trigger: 'brief' }).catch(() => {});
2503
2508
  // ...and score it for the reviewer ("scorecard": { "auto": false } in config.json turns this off).
2504
2509
  if ((improved || (finished && this.config.scorecard?.auto !== false && !rounds)) && !NO_REPO.has(agent.kind) && this.changesSource) this.summarize(id, 'scorecard').catch(() => {});
@@ -2802,10 +2807,12 @@ export class AgentManager extends EventEmitter {
2802
2807
  if (!hunks.length) throw Object.assign(new Error('No changes to score yet'), { status: 400 });
2803
2808
  const cur0 = this.store.get(agent.id) ?? agent;
2804
2809
  const doc = (n) => readSpecDoc(agent.id, n)?.markdown ?? '';
2805
- const f = scoreFacts({ files: data.files, prs: Object.values(cur0.prs ?? {}), brief: cur0.brief, plan: doc('plan'), spec: doc('spec') });
2810
+ // The repository's standards: its bar is run here, by the app, before the model is asked.
2811
+ const standards = (await this.standards?.assess(agent.id, data)) ?? null;
2812
+ const f = scoreFacts({ files: data.files, prs: Object.values(cur0.prs ?? {}), brief: cur0.brief, plan: doc('plan'), spec: doc('spec'), standards });
2806
2813
  const writer = this.writerFor(agent);
2807
- const prompt = scorecardPrompt({ ...ctx, briefMarkdown: this.briefFile(agent.id).markdown ?? '', intentDoc: doc('intent'), specDoc: doc('spec'), planDoc: doc('plan'), hunks, facts: f });
2808
- const sc = combine(parseJsonReply(await this.oneShot(agent, prompt, writer)), f, hunks);
2814
+ const prompt = scorecardPrompt({ ...ctx, briefMarkdown: this.briefFile(agent.id).markdown ?? '', intentDoc: doc('intent'), specDoc: doc('spec'), planDoc: doc('plan'), hunks, facts: f, lessons: standards?.lessons ?? [] });
2815
+ const sc = combine(parseJsonReply(await this.oneShot(agent, prompt, writer)), f, hunks, { lessons: standards?.lessons ?? [], bar: standards?.bar ?? null });
2809
2816
  const cur = this.store.get(agent.id);
2810
2817
  if (!cur) return null;
2811
2818
  return this.view(
package/src/prereview.js CHANGED
@@ -253,7 +253,12 @@ export class PreReview {
253
253
 
254
254
  /** Task agents with changes of their own that something here can review: not reviewers, bug hunts and their fixers, teams or agent builders (those have their own checks). */
255
255
  applies(agent) {
256
- return Boolean(this.settings.enabled && agent.kind === 'task' && agent.workdir && !agent.hunting && !agent.fixing && !agent.reviewing && !agent.team && !agent.builds && !agent.raceId && !this.skip(agent) && this.candidates(agent).length);
256
+ return Boolean(this.settings.enabled && this.can(agent));
257
+ }
258
+
259
+ /** Could its changes be reviewed here, whether or not rounds are on? */
260
+ can(agent) {
261
+ return Boolean(agent.kind === 'task' && agent.workdir && !agent.hunting && !agent.fixing && !agent.reviewing && !agent.team && !agent.builds && !agent.raceId && !this.skip(agent) && this.candidates(agent).length);
257
262
  }
258
263
 
259
264
  /** Told at launch that the pull request waits for the review? */
@@ -309,8 +314,9 @@ export class PreReview {
309
314
  return true;
310
315
  }
311
316
 
312
- begin(id) {
313
- this.manager.patch(id, { preReview: { status: 'reviewing', round: 0, max: this.settings.rounds, findings: [], rounds: [], startedAt: now(), endedAt: null, pr: null, error: null } });
317
+ /** `forced`: why rounds run with the switch off ('risk': a high-risk path was touched); the pull request is then left to the person. */
318
+ begin(id, { forced = null } = {}) {
319
+ this.manager.patch(id, { preReview: { status: 'reviewing', round: 0, max: this.settings.rounds, findings: [], rounds: [], startedAt: now(), endedAt: null, pr: null, error: null, ...(forced ? { forced } : {}) } });
314
320
  this.run(id);
315
321
  }
316
322
 
@@ -396,7 +402,7 @@ export class PreReview {
396
402
  this.manager.patch(id, { preReview: state });
397
403
  this.log(`review rounds: ${this.manager.store.get(id)?.name ?? id} ${state.status === 'approved' ? 'approved' : 'not approved'} in round ${state.round} of ${state.max}`);
398
404
  await this.after(id);
399
- if (state.status === 'approved' && this.settings.openPr && !this.managed(id)) await this.open(id).catch(() => {});
405
+ if (state.status === 'approved' && this.settings.openPr && !state.forced && !this.managed(id)) await this.open(id).catch(() => {});
400
406
  }
401
407
 
402
408
  /** What waited for the rounds: the AI review, and the score (which goes in the pull request's description). */