ai-agentmanager 1.55.1 → 1.56.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/CHANGELOG.md +11 -0
- package/README.md +29 -0
- package/package.json +1 -1
- package/public/app.js +88 -4
- package/public/style.css +4 -0
- package/src/autopilot.js +3 -0
- package/src/cli.js +41 -1
- package/src/config.js +2 -0
- package/src/manager.js +15 -3
- package/src/prereview.js +475 -0
- package/src/review.js +9 -3
- package/src/server.js +35 -13
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,16 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 1.56.0 (2026-11-17)
|
|
4
|
+
|
|
5
|
+
- **Review rounds before a pull request.** A pull request's reviewers, people or GitHub Copilot, should not be the ones who find the bugs. When an agent says it is done, critics on other models read its changes in the background and report what is wrong or missing: wrong results and missed cases, error handling, behavior callers relied on, security, missing tests, and what the task asked for that isn't there. The findings go to the agent's session as one message, it fixes them and says done again, and the critics look again, until no blocker or major finding is open or the rounds run out (4 by default, 5 at most).
|
|
6
|
+
- **Approved:** the changes are committed, pushed and opened as a pull request whose description starts with *Reviewed before opening*: the round, the critics, and what was found and dealt with. **Not approved in time:** nothing is opened; it waits in your inbox with what is still open (**Another round**, **Open the pull request anyway**, or leave it).
|
|
7
|
+
- **The critics** are other models of the engine the agent runs on, without the model it runs on when that is known: a Claude Code agent on opus is read by sonnet and haiku. No other provider is needed. To use one, name it in config.json (`"preReview": { "models": [{ "engine": "codex" }] }`). A critic that fails is replaced by the next model. For an engine other than Claude Code, list its review models (`"engines": { "codex": { "reviewModels": [...] } }`); without that one critic reads each round.
|
|
8
|
+
- **This is on by default, and changes two things.** Each round is one call per critic on your own plan: two calls for a change approved at once, eight for one that needs four rounds. And agents are now told to leave the pull request to the review, so it opens after approval, not when the agent decides. Turn it off with the line under the inbox or `agentmgr rounds --off`; keep the rounds but open pull requests yourself with `agentmgr rounds --pr off`.
|
|
9
|
+
- **Where to see it.** The agent's page shows each round, each critic's verdict and every finding. `agentmgr rounds` shows the settings (`--rounds`, `--critics`), and `agentmgr rounds <agent>` an agent's rounds (`--start`, `--again`, `--open`, `--stop`). The AI review and the scorecard are made once, after the rounds. Backlog work on autopilot is reviewed first, and held when the rounds don't approve it.
|
|
10
|
+
- **Not for** reviewers of others' pull requests, bug hunts and their fixes, teams and races. An agent on a local model or an ACP agent is read by Claude Code when it is installed, and has no rounds without it.
|
|
11
|
+
- **Tried so far** on small changes, in up to two rounds; opening the pull request on GitHub is covered by tests against a stand-in for `gh`. A very large diff is cut to fit, and the critics say so.
|
|
12
|
+
- **Fixed:** when opening a pull request or posting a scorecard failed, the message was the whole `gh` command with its description. It is now what `gh` said.
|
|
13
|
+
|
|
3
14
|
## 1.55.1 (2026-11-16)
|
|
4
15
|
|
|
5
16
|
From running a real task on `gpt-oss:20b` (Ollama) through each harness.
|
package/README.md
CHANGED
|
@@ -36,6 +36,7 @@ Run one background [Claude Code](https://claude.com/claude-code) agent per inten
|
|
|
36
36
|
- **Skills.** **Skills…** in the menu (or `agentmgr skills`) lists the Agent Skills Claude Code has here, yours and each project's, with which agents used them. Add more from a git repository (`anthropics/skills`, or any https address): you see what it offers first, with each skill's scripts flagged, then pick. A skill added here remembers its repository and commit, so **Check** says when a newer version is there and **Update** brings it; one you edited says so.
|
|
37
37
|
- **Board.** **Board** in the top bar (or `B`, `#board`): every agent as a card in the column for where its work stands: starting, working, needs you, waiting, in review, done, closed. Cards move by themselves; drag one onto **Closed** to close its session, or from Closed onto **Waiting** to resume it.
|
|
38
38
|
- **Lanes.** Every agent gets a range of ports and a name ending no other agent has, in its environment and its instructions, so dev servers and test databases of agents working side by side don't collide. **OS** shows what each open session listens on (`agentmgr lanes`).
|
|
39
|
+
- **Review rounds before a pull request.** When an agent says it is done, critics on other models of the engine it runs on read its changes in the background and report what is wrong or missing. Their findings go to the agent's session, it fixes them, and they look again: until they approve or the rounds run out. Approved changes are committed, pushed and opened as a pull request that says what was found and fixed, so the bugs are met here and not by the pull request's reviewers. See [Review rounds](#review-rounds-before-a-pull-request).
|
|
39
40
|
- **Local models.** Models served on this computer by Ollama, LM Studio, llama.cpp or MLX are found by themselves, and an agent can run on one, with the Codex CLI, OpenCode or Claude Code as the harness: no plan, no limits, nothing leaves the machine (`agentmgr models`).
|
|
40
41
|
- **Lean output.** A switch in **Usage** (off by default; `agentmgr usage --lean on`): long command output (test runs, installs, builds) is trimmed before the agent reads it, so a plan's limits last longer. Colours and progress redraws go, runs of near-identical lines are folded, and of a long middle only the lines that look like errors or warnings stay; the start and end are kept, and the whole output is saved to a file the agent can read. Claude Code only, for sessions started after you switch it on. Usage shows how much was trimmed.
|
|
41
42
|
- **Runbooks for support.** A runbook for the support team written from a release ticket, every ticket of an epic, or a project's code changes in a time frame: what changed, what customers may see, how to check it, troubleshooting, rollback, when to escalate, and what to confirm with engineering.
|
|
@@ -204,6 +205,7 @@ agentmgr debt <project> --scan # the tech debt radar: files that
|
|
|
204
205
|
agentmgr audit <agent> --start # security audit in its session (a scope in words, --fix "1 and 3"; no arguments: the report)
|
|
205
206
|
agentmgr skills # Claude Code's skills here (look <repo>, add <repo> <names...>, check|update|rm <id>)
|
|
206
207
|
agentmgr lanes # every agent's own ports and name ending (--off, --port off, --base, --size)
|
|
208
|
+
agentmgr rounds [agent] # review rounds before a pull request: the settings, or an agent's rounds (--start, --again, --open, --stop)
|
|
207
209
|
agentmgr models # models served on this computer (Ollama, LM Studio, llama.cpp, MLX), for --engine local
|
|
208
210
|
agentmgr usage # each engine's plan limits: used, left, resets (--now, --lean on, --warn 80, --hold 95, --default codex)
|
|
209
211
|
agentmgr runbook --ticket REL-42 # a support runbook from a release ticket (or --epic KEY, or --since 2026-10-01 -p <project>; -o file.md)
|
|
@@ -447,6 +449,32 @@ Each card has at most **three points of about 12 words each**, so they're easy t
|
|
|
447
449
|
|
|
448
450
|
The same from the API: `GET /api/agents/:id/changes`, `POST …/changes/comments`, `…/changes/commit`, `…/changes/pr`. Plugins can refuse a commit or a pull request (`agent.commit`, `agent.pr`).
|
|
449
451
|
|
|
452
|
+
## Review rounds: before a pull request
|
|
453
|
+
|
|
454
|
+
A pull request's reviewers, people or GitHub Copilot, should not be the ones who find the bugs. So an agent's changes are reviewed before there is a pull request, by models other than the one that wrote them, as many times as it takes.
|
|
455
|
+
|
|
456
|
+
1. **The agent says it is done** (its brief turns to done). Review rounds start by themselves, in the background.
|
|
457
|
+
2. **Critics read the diff.** Two by default, each on a different model of the engine the agent runs on, and not the model it runs on when that is known: a Claude Code agent on opus is read by sonnet and haiku, one on its default model by opus and sonnet. No other provider is needed. Each gets the diff, the task, the spec and the brief, and reports defects in the changed code: wrong results and missed cases, error handling, behavior that callers relied on, security, tests that are missing, and what the task asked for that isn't there. Every finding has a severity, the line, and the input that goes wrong. Two critics on one defect make one finding.
|
|
458
|
+
3. **The findings go to the agent's session** as one message. It fixes each one, or says in its brief why a finding is wrong, runs the tests and says done again.
|
|
459
|
+
4. **The critics look again**: at what they raised, and at the new diff. This repeats until no blocker or major finding is open, or the rounds run out (4 by default, 5 at most).
|
|
460
|
+
5. **Approved:** the changes are committed, pushed and opened as a pull request. Its description starts with *Reviewed before opening*: the round it was approved in, by whom, and what was found and dealt with. The AI review and the scorecard are made once, of the changes that go out.
|
|
461
|
+
6. **Not approved in time:** nothing is opened. It waits in your inbox with what is still open, and you choose: **Another round**, **Open the pull request anyway** (its description lists what is open), or leave it.
|
|
462
|
+
|
|
463
|
+
Minor findings and nits are passed to the agent but do not hold the pull request; what is left of them is listed in its description.
|
|
464
|
+
|
|
465
|
+
The agent's detail shows the rounds as they go: the round, each critic's verdict, and every finding with whether it is dealt with. **Review rounds** there starts them by hand, also with the switch off. From the command line: `agentmgr rounds <agent>` (`--start`, `--again`, `--open`, `--stop`).
|
|
466
|
+
|
|
467
|
+
- **The switch** is the line under the inbox, or `agentmgr rounds --on|--off`. It is on by default.
|
|
468
|
+
- **Rounds and critics:** `agentmgr rounds --rounds 5 --critics 3`. A critic that fails in a round is replaced by the next model.
|
|
469
|
+
- **Other providers, if you have them.** A different provider catches different mistakes. To use one, name the critics yourself in config.json: `"preReview": { "models": [{ "engine": "codex" }, { "engine": "claude", "model": "opus" }] }`. They come first, and an engine that isn't installed is left out.
|
|
470
|
+
- **Engines other than Claude Code.** The app knows Claude Code's model names. For another engine, say which of its models review: `"engines": { "codex": { "reviewModels": ["…", "…"] } }`. Without that, one critic reads each round, on the model the engine is set up with. An agent on a local model or an ACP agent is read by the engine that writes its summaries (Claude Code); with none installed, it has no review rounds.
|
|
471
|
+
- **Leave the pull request to you:** `agentmgr rounds --pr off`. The rounds still run; you open it from the agent.
|
|
472
|
+
- **What it costs.** Each round is one call per critic, on your own plans, and takes about a minute. A change the critics pass at once costs two calls; one that needs every round costs eight.
|
|
473
|
+
- **Who it is for.** Task agents with changes of their own. Not reviewers of others' pull requests, bug hunts and their fixes, teams (they have a reviewer) or races. Backlog work on autopilot is reviewed in rounds first; autopilot opens its pull request after they approve, and holds the item when they don't.
|
|
474
|
+
- Agents are told at launch to leave the pull request to the review. One that opens it anyway is still reviewed, and pushes its fixes to it.
|
|
475
|
+
|
|
476
|
+
Critics judge the diff they are sent: a very large change is cut to fit and they say so. They can be wrong both ways. A finding the agent shows to be mistaken is closed by the critics in the next round; a bug no critic sees still reaches the pull request.
|
|
477
|
+
|
|
450
478
|
## Landing pull requests
|
|
451
479
|
|
|
452
480
|
The **Land** tab lists every agent's open pull request by what it needs to get merged, ready ones first:
|
|
@@ -1440,6 +1468,7 @@ State lives in `~/.agentmanager/` (`state.json`, `daemon.log`, `repos/` for shar
|
|
|
1440
1468
|
"conflictRefreshSec": 60,
|
|
1441
1469
|
"stuck": { "repeatFailures": 3, "thrashReverts": 2, "thrashEdits": 10, "driftMinutes": 20, "driftActions": 25 },
|
|
1442
1470
|
"judge": { "enabled": true, "model": "haiku", "dailyCalls": 300 },
|
|
1471
|
+
"preReview": { "enabled": true, "rounds": 4, "critics": 2, "openPr": true },
|
|
1443
1472
|
"cleanup": { "strategy": "close", "closeAfterDays": 14, "deleteAfterDays": 14 },
|
|
1444
1473
|
"hub": { "allow": ["view"], "projects": ["*"] }
|
|
1445
1474
|
}
|
package/package.json
CHANGED
package/public/app.js
CHANGED
|
@@ -553,6 +553,36 @@ function explainBox(a) {
|
|
|
553
553
|
return { button, box };
|
|
554
554
|
}
|
|
555
555
|
|
|
556
|
+
/** Review rounds before a pull request (prereview.js): where they stand, each round, and what was found. */
|
|
557
|
+
const ROUNDS_HOLD = new Set(['blocker', 'major']);
|
|
558
|
+
function roundsBox(a) {
|
|
559
|
+
const r = a.preReview;
|
|
560
|
+
if (noRepo(a) || !r) return '';
|
|
561
|
+
const open = (r.findings ?? []).filter((f) => f.status === 'open');
|
|
562
|
+
const hold = open.filter((f) => ROUNDS_HOLD.has(f.severity));
|
|
563
|
+
const state = {
|
|
564
|
+
reviewing: `<span class="verdict partial">Round ${r.round} of ${r.max}</span> Critics are reading the changes…`,
|
|
565
|
+
fixing: `<span class="verdict partial">Round ${r.round} of ${r.max}</span> The agent is fixing ${hold.length} ${hold.length === 1 ? 'finding' : 'findings'}; the critics look again when it says done.`,
|
|
566
|
+
approved: `<span class="verdict complete">✓ Approved in round ${r.round}</span> ${r.pr ? `<a href="${esc(r.pr)}" target="_blank" rel="noopener">Pull request opened</a>` : r.prError ? `The pull request was not opened: ${esc(r.prError)}` : ''}`,
|
|
567
|
+
stalled: `<span class="verdict not_done">✗ Not approved after ${r.round} ${r.round === 1 ? 'round' : 'rounds'}</span> ${hold.length} still open.`,
|
|
568
|
+
opened: `<span class="verdict partial">Not approved after ${r.round} rounds</span> ${r.pr ? `<a href="${esc(r.pr)}" target="_blank" rel="noopener">Opened anyway</a>` : 'Opened anyway.'}`,
|
|
569
|
+
stopped: '<span class="verdict">Review rounds stopped</span>',
|
|
570
|
+
error: `<span class="verdict not_done">The review failed</span> ${esc(r.error ?? '')}`,
|
|
571
|
+
}[r.status] ?? esc(r.status);
|
|
572
|
+
const finding = (f) => `<li class="${f.status === 'open' ? (ROUNDS_HOLD.has(f.severity) ? 'failed' : 'pending') : 'passed'}" title="${esc([f.why, f.fix && `Fix: ${f.fix}`, f.by?.length && `Raised by ${f.by.join(', ')}`].filter(Boolean).join('\n'))}">
|
|
573
|
+
<span class="icon">${f.status === 'open' ? (ROUNDS_HOLD.has(f.severity) ? '✗' : '○') : '✓'}</span><span><b>${esc(f.severity)}</b>${f.file ? ` <code>${esc(f.file)}</code>` : ''} ${esc(f.title)}</span></li>`;
|
|
574
|
+
const rounds = (r.rounds ?? []).map((rd) => `Round ${rd.n}: ${rd.critics.map((c) => `${esc(c.by)} ${c.error ? 'failed' : c.verdict === 'approve' ? 'approves' : 'asks for changes'}`).join(', ')}`).join(' · ');
|
|
575
|
+
const actions = [
|
|
576
|
+
['stalled', 'error'].includes(r.status) ? '<button class="small primary" data-act="rounds-again" title="One more round: what is open goes to the agent first">Another round</button>' : '',
|
|
577
|
+
r.status === 'stalled' || (r.status === 'approved' && !r.pr) ? `<button class="small" data-act="rounds-open" title="Commit, push and open the pull request${r.status === 'stalled' ? ', with what is still open in its description' : ''}">Open the pull request${r.status === 'stalled' ? ' anyway' : ''}</button>` : '',
|
|
578
|
+
['reviewing', 'fixing'].includes(r.status) ? '<button class="small ghost" data-act="rounds-stop" title="No more rounds for this work">Stop</button>' : '<button class="small ghost" data-act="rounds-start" title="Review the changes again, from round one">Review again</button>',
|
|
579
|
+
].join('');
|
|
580
|
+
return `<div class="explain rounds"><p>${state}</p>
|
|
581
|
+
${r.findings?.length ? `<ul class="checks">${r.findings.map(finding).join('')}</ul>` : ''}
|
|
582
|
+
${rounds ? `<p class="hint">Reviewed before a pull request. ${rounds}.</p>` : '<p class="hint">Reviewed before a pull request, by other models.</p>'}
|
|
583
|
+
<div class="need-actions">${actions}</div></div>`;
|
|
584
|
+
}
|
|
585
|
+
|
|
556
586
|
const REVIEW_VERDICT = { complete: '✓ Complete', partial: '≈ Partly done', not_done: '✗ Not done' };
|
|
557
587
|
/** The AI judge's review of the work against the intent and brief: button, and the last result once handled. */
|
|
558
588
|
function reviewBox(a) {
|
|
@@ -560,6 +590,8 @@ function reviewBox(a) {
|
|
|
560
590
|
const r = a.aiReview;
|
|
561
591
|
const button = `<button class="small" data-act="review" ${r?.pending ? 'disabled' : ''}
|
|
562
592
|
title="Check the work against the intent and brief: what is met, missing or risky. A separate one-off model call; runs by itself when the agent says it is done">${r?.pending ? 'Reviewing…' : 'Review with AI'}</button>${
|
|
593
|
+
a.preReview || !a.workdir ? '' : '<button class="small" data-act="rounds-start" title="Before a pull request: critics on other models read the changes, the agent fixes what they find, and they look again until they approve. Runs by itself when the agent says it is done, if review rounds are on">Review rounds</button>'
|
|
594
|
+
}${
|
|
563
595
|
r?.verdict || a.prs?.some((p) => p.source !== 'mentioned' && p.state)
|
|
564
596
|
? listenHtml(`prvoice:${a.id}`, { title: 'Explain the review aloud: the PR, its checks, the AI review, the riskiest changes and what is left', label: 'Explain review' })
|
|
565
597
|
: ''
|
|
@@ -1018,6 +1050,7 @@ function briefPanel(a) {
|
|
|
1018
1050
|
${resultsCard(a)}
|
|
1019
1051
|
${ins.box}
|
|
1020
1052
|
${ex.box}
|
|
1053
|
+
${roundsBox(a)}
|
|
1021
1054
|
${rv.box}
|
|
1022
1055
|
<p class="hint">Problem, solution, diagram and checks appear here once the agent writes its brief.
|
|
1023
1056
|
${a.lastStartedAt && !a.runtime.running ? ' Agents started before this feature write one after their next resume.' : ''}</p>
|
|
@@ -1035,7 +1068,8 @@ function briefPanel(a) {
|
|
|
1035
1068
|
${resultsCard(a)}
|
|
1036
1069
|
${ins.box}
|
|
1037
1070
|
${ex.box}
|
|
1038
|
-
${
|
|
1071
|
+
${roundsBox(a)}
|
|
1072
|
+
${rv.box}
|
|
1039
1073
|
<div class="brief-grid">
|
|
1040
1074
|
<section><h4>Problem</h4>${b.problem ? clamp(a, 'problem', md(b.problem)) : '<p class="hint">—</p>'}</section>
|
|
1041
1075
|
<section><h4>Solution</h4>${b.solution ? clamp(a, 'solution', md(b.solution)) : '<p class="hint">—</p>'}</section>
|
|
@@ -1490,7 +1524,7 @@ function loadLimitEngines() {
|
|
|
1490
1524
|
})
|
|
1491
1525
|
.catch(() => (limitEngines = null));
|
|
1492
1526
|
}
|
|
1493
|
-
const NEED_ORDER = { approval: 0, prompt: 0, limit: 1, waiting: 1, plan: 1, question: 1, team: 1, rule: 2, review: 2, autopilot: 2, stuck: 3, conflict: 4, reminder: 5, close: 5, repeat: 5 };
|
|
1527
|
+
const NEED_ORDER = { approval: 0, prompt: 0, limit: 1, waiting: 1, plan: 1, question: 1, team: 1, rule: 2, review: 2, prereview: 2, autopilot: 2, stuck: 3, conflict: 4, reminder: 5, close: 5, repeat: 5 };
|
|
1494
1528
|
/** What an agent needs from the user. `both`: overlaps on both agents (detail), else only the one that should rebase (inbox). */
|
|
1495
1529
|
function needsFor(a, { both = false } = {}) {
|
|
1496
1530
|
const items = [];
|
|
@@ -1499,6 +1533,7 @@ function needsFor(a, { both = false } = {}) {
|
|
|
1499
1533
|
if (a.runtime.waiting) items.push({ a, kind: 'waiting', key: `waiting:${a.id}` });
|
|
1500
1534
|
if (a.planReview?.status === 'review') items.push({ a, kind: 'plan', key: `plan:${a.id}` });
|
|
1501
1535
|
if (a.aiReview?.verdict && !a.aiReview.seen) items.push({ a, kind: 'review', key: `review:${a.id}` });
|
|
1536
|
+
if (['stalled', 'error'].includes(a.preReview?.status)) items.push({ a, kind: 'prereview', key: `prereview:${a.id}` });
|
|
1502
1537
|
for (const q of a.questions ?? []) if (!q.answer) items.push({ a, kind: 'question', key: `q:${a.id}:${q.id}`, q });
|
|
1503
1538
|
for (const f of a.stuck ?? []) items.push({ a, kind: 'stuck', key: `stuck:${a.id}:${f.key}`, f });
|
|
1504
1539
|
if (a.followUp) items.push({ a, kind: a.followUp.kind === 'close' ? 'close' : 'reminder', key: `reminder:${a.id}`, r: a.followUp });
|
|
@@ -1537,7 +1572,7 @@ function inboxItems() {
|
|
|
1537
1572
|
.sort((x, y) => NEED_ORDER[x.kind] - NEED_ORDER[y.kind] || (x.a.priority ?? 2) - (y.a.priority ?? 2));
|
|
1538
1573
|
}
|
|
1539
1574
|
|
|
1540
|
-
const NEED_LABEL = { limit: 'Limit', reminder: 'Follow up', close: 'Close session?', repeat: 'Make it a playbook?', autopilot: 'Autopilot held', rule: 'Always allow?', approval: 'Approval', team: 'Team', prompt: 'Needs input', waiting: 'Waiting on you', plan: 'Plan review', question: 'Question', review: 'AI review', stuck: 'Stuck?', conflict: 'Overlap' };
|
|
1575
|
+
const NEED_LABEL = { limit: 'Limit', reminder: 'Follow up', close: 'Close session?', repeat: 'Make it a playbook?', autopilot: 'Autopilot held', rule: 'Always allow?', approval: 'Approval', team: 'Team', prompt: 'Needs input', waiting: 'Waiting on you', plan: 'Plan review', question: 'Question', review: 'AI review', prereview: 'Not approved', stuck: 'Stuck?', conflict: 'Overlap' };
|
|
1541
1576
|
/** Why the AI judge thinks so, as a small tag. */
|
|
1542
1577
|
const aiTag = (confidence, what = 'AI') => `<span class="tag ai" title="Judged by a model from the agent's activity; your reactions tune later calls">🤖 ${what}${confidence != null ? ` ${Math.round(confidence * 100)}%` : ''}</span>`;
|
|
1543
1578
|
/** What a permission prompt asks about: the command, file or tool. */
|
|
@@ -1635,6 +1670,16 @@ function needCard(it, { inDetail = false } = {}) {
|
|
|
1635
1670
|
<button class="small ${r.missing.length ? '' : 'primary'}" data-ib="review-accept">Looks good</button>
|
|
1636
1671
|
${improveHtml(a).replace('small primary', 'small')}
|
|
1637
1672
|
</div>`;
|
|
1673
|
+
} else if (it.kind === 'prereview') {
|
|
1674
|
+
const r = a.preReview;
|
|
1675
|
+
const hold = (r.findings ?? []).filter((f) => f.status === 'open' && ROUNDS_HOLD.has(f.severity));
|
|
1676
|
+
body = `<p class="need-title">${r.status === 'error' ? `The review before its pull request failed: ${esc(r.error ?? '')}` : `Its changes were not approved after ${r.round} review ${r.round === 1 ? 'round' : 'rounds'}: ${hold.length} ${hold.length === 1 ? 'finding' : 'findings'} still open`}</p>
|
|
1677
|
+
${hold.length ? `<ul class="need-files">${hold.slice(0, 6).map((f) => `<li>${f.file ? `<code>${esc(f.file)}</code> ` : ''}${esc(f.title)}</li>`).join('')}</ul>` : ''}
|
|
1678
|
+
<div class="need-actions">
|
|
1679
|
+
<button class="small primary" data-ib="rounds-again" title="One more round: what is open goes to the agent first">Another round</button>
|
|
1680
|
+
${r.status === 'stalled' ? '<button class="small" data-ib="rounds-open" title="Commit, push and open the pull request, with what is still open in its description">Open the pull request anyway</button>' : ''}
|
|
1681
|
+
<button class="small ghost" data-ib="rounds-stop">Leave it</button>
|
|
1682
|
+
</div>`;
|
|
1638
1683
|
} else if (it.kind === 'team') {
|
|
1639
1684
|
const t = it.t;
|
|
1640
1685
|
body = `<p class="need-title">${t.stage === 'ready' ? `✓ The reviewer approved <b>${esc(t.name)}</b>${t.gaps ? ', with parts still missing: run a gap round?' : ''}` : `<b>${esc(t.name)}</b> needs a decision: ${esc(t.blocked?.reason ?? '')}`}</p>
|
|
@@ -1712,9 +1757,21 @@ async function loadJudge() {
|
|
|
1712
1757
|
} catch {
|
|
1713
1758
|
judgeStatus = null;
|
|
1714
1759
|
}
|
|
1760
|
+
roundsStatus = await api('GET', '/prereview').catch(() => null);
|
|
1715
1761
|
renderInbox();
|
|
1716
1762
|
}
|
|
1717
1763
|
|
|
1764
|
+
/** Review rounds before a pull request (prereview.js): the switch, with what a round costs. */
|
|
1765
|
+
let roundsStatus = null;
|
|
1766
|
+
function roundsLine() {
|
|
1767
|
+
const r = roundsStatus;
|
|
1768
|
+
if (!r) return '';
|
|
1769
|
+
const text = r.enabled
|
|
1770
|
+
? `🔎 Review rounds on: when an agent says it is done, ${r.critics} ${r.critics === 1 ? 'critic' : 'critics'} on other models read its changes, it fixes what they find, and they look again (up to ${r.rounds} rounds). ${r.openPr ? 'The pull request is opened when they approve.' : ''} Each round is ${r.critics === 1 ? 'a call' : `${r.critics} calls`} on your own plan.`
|
|
1771
|
+
: '🔎 Review rounds off: changes are not reviewed by other models before a pull request.';
|
|
1772
|
+
return `<p class="judge-line hint">${esc(text)} <button class="small ghost" data-rounds="${r.enabled ? 'off' : 'on'}">${r.enabled ? 'Turn off' : 'Turn on'}</button></p>`;
|
|
1773
|
+
}
|
|
1774
|
+
|
|
1718
1775
|
function judgeLine() {
|
|
1719
1776
|
const j = judgeStatus;
|
|
1720
1777
|
if (!j) return '';
|
|
@@ -1736,7 +1793,7 @@ function renderInbox() {
|
|
|
1736
1793
|
view,
|
|
1737
1794
|
(items.length
|
|
1738
1795
|
? `<div class="counts"><span>${items.length} waiting on you</span></div><div class="needs inbox">${promptGroups(items).map(groupCard).join('')}${items.map((it) => needCard(it)).join('')}</div>`
|
|
1739
|
-
: `<div class="empty"><p>Nothing needs you right now.</p><p>Prompts waiting for an answer, questions agents ask, agents that seem stuck and agents editing the same files show up here.</p></div>`) + judgeLine(),
|
|
1796
|
+
: `<div class="empty"><p>Nothing needs you right now.</p><p>Prompts waiting for an answer, questions agents ask, agents that seem stuck and agents editing the same files show up here.</p></div>`) + judgeLine() + roundsLine(),
|
|
1740
1797
|
);
|
|
1741
1798
|
}
|
|
1742
1799
|
|
|
@@ -1751,6 +1808,14 @@ async function onNeed(e) {
|
|
|
1751
1808
|
renderInbox();
|
|
1752
1809
|
}, judge.dataset.judge === 'on' ? 'AI judge on' : 'AI judge off');
|
|
1753
1810
|
}
|
|
1811
|
+
const rounds = e.target.closest('[data-rounds]');
|
|
1812
|
+
if (rounds) {
|
|
1813
|
+
e.preventDefault();
|
|
1814
|
+
return act(async () => {
|
|
1815
|
+
roundsStatus = await api('PUT', '/prereview', { enabled: rounds.dataset.rounds === 'on' });
|
|
1816
|
+
renderInbox();
|
|
1817
|
+
}, rounds.dataset.rounds === 'on' ? 'Review rounds on' : 'Review rounds off');
|
|
1818
|
+
}
|
|
1754
1819
|
const goto = e.target.closest('[data-goto]');
|
|
1755
1820
|
if (goto) {
|
|
1756
1821
|
e.preventDefault();
|
|
@@ -1846,6 +1911,12 @@ async function onNeed(e) {
|
|
|
1846
1911
|
return act(async () => upsert(await api('POST', `/agents/${id}/reminder`, { action: 'dismiss' })));
|
|
1847
1912
|
case 'waiting-dismiss':
|
|
1848
1913
|
return act(async () => upsert(await api('POST', `/agents/${id}/waiting/dismiss`)));
|
|
1914
|
+
case 'rounds-again':
|
|
1915
|
+
return act(async () => upsert(await api('POST', `/agents/${id}/prereview/again`)), 'Another review round');
|
|
1916
|
+
case 'rounds-open':
|
|
1917
|
+
return act(async () => upsert(await api('POST', `/agents/${id}/prereview/open`)), 'Pull request opened');
|
|
1918
|
+
case 'rounds-stop':
|
|
1919
|
+
return act(async () => upsert(await api('DELETE', `/agents/${id}/prereview`)));
|
|
1849
1920
|
case 'review-finish':
|
|
1850
1921
|
return act(async () => upsert(await api('POST', `/agents/${id}/review/ack`, { action: 'finish' })), 'Sent back with the missing items');
|
|
1851
1922
|
case 'review-accept':
|
|
@@ -3968,6 +4039,19 @@ $('#detail-body').addEventListener('click', async (e) => {
|
|
|
3968
4039
|
btn.textContent = 'Thinking…';
|
|
3969
4040
|
act(async () => upsert(await api('POST', `/agents/${a.id}/insights`)));
|
|
3970
4041
|
break;
|
|
4042
|
+
case 'rounds-start':
|
|
4043
|
+
act(async () => upsert(await api('POST', `/agents/${a.id}/prereview`)), 'Critics are reading the changes');
|
|
4044
|
+
break;
|
|
4045
|
+
case 'rounds-again':
|
|
4046
|
+
act(async () => upsert(await api('POST', `/agents/${a.id}/prereview/again`)), 'Another review round');
|
|
4047
|
+
break;
|
|
4048
|
+
case 'rounds-open':
|
|
4049
|
+
btn.disabled = true;
|
|
4050
|
+
act(async () => upsert(await api('POST', `/agents/${a.id}/prereview/open`)), 'Pull request opened');
|
|
4051
|
+
break;
|
|
4052
|
+
case 'rounds-stop':
|
|
4053
|
+
act(async () => upsert(await api('DELETE', `/agents/${a.id}/prereview`)));
|
|
4054
|
+
break;
|
|
3971
4055
|
case 'review':
|
|
3972
4056
|
btn.disabled = true;
|
|
3973
4057
|
btn.textContent = 'Reviewing…';
|
package/public/style.css
CHANGED
|
@@ -583,6 +583,10 @@ dialog::backdrop { background: rgba(0, 0, 0, .45); }
|
|
|
583
583
|
.need.conflict .need-kind { color: #8e59ff; }
|
|
584
584
|
.need.waiting .need-kind { color: var(--red); }
|
|
585
585
|
.need.review .need-kind { color: var(--green); }
|
|
586
|
+
.need.prereview .need-kind { color: var(--yellow); }
|
|
587
|
+
/* Review rounds before a pull request */
|
|
588
|
+
.explain.rounds .checks { margin: 4px 0; }
|
|
589
|
+
.explain.rounds .checks code { font-size: 11.5px; }
|
|
586
590
|
/* The AI judge */
|
|
587
591
|
.tag.ai { font-size: 10.5px; font-weight: 600; color: var(--accent); background: var(--panel-2); border: 1px solid var(--border); border-radius: 10px; padding: 0 6px; white-space: nowrap; }
|
|
588
592
|
.verdict.complete { color: var(--green); font-weight: 600; }
|
package/src/autopilot.js
CHANGED
|
@@ -94,6 +94,9 @@ export class Autopilot {
|
|
|
94
94
|
if (level === 'off' && !ap.ship) return;
|
|
95
95
|
if (ap.state === 'held' && ap.round === it.reviewAt) return;
|
|
96
96
|
if (this.manager.view(agent).runtime.busy) return;
|
|
97
|
+
// Its changes are being reviewed in rounds (prereview.js): what comes out of that is scored and shipped.
|
|
98
|
+
if (['reviewing', 'fixing'].includes(agent.preReview?.status)) return;
|
|
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.`);
|
|
97
100
|
if (pr?.state === 'CLOSED') return this.hold(it, 'Its pull request was closed without merging.');
|
|
98
101
|
// Shipped in this round of review: see it through. Reopened since: the new work is scored and pushed to it.
|
|
99
102
|
if (pr && ap.shipped === it.reviewAt) return level === 'merge' ? this.land(it, agent, pr) : undefined;
|
package/src/cli.js
CHANGED
|
@@ -1691,7 +1691,7 @@ export async function main(argv) {
|
|
|
1691
1691
|
await daemon();
|
|
1692
1692
|
const items = await api('GET', '/inbox');
|
|
1693
1693
|
if (!items.length) return console.log(dim('Nothing needs you right now.'));
|
|
1694
|
-
const label = { prompt: red('needs input'), waiting: red('waiting'), question: cyan('question'), review: cyan('AI review'), stuck: yellow('stuck?'), conflict: yellow('overlap'), reminder: cyan('follow up') };
|
|
1694
|
+
const label = { prompt: red('needs input'), waiting: red('waiting'), question: cyan('question'), review: cyan('AI review'), prereview: yellow('not approved'), stuck: yellow('stuck?'), conflict: yellow('overlap'), reminder: cyan('follow up') };
|
|
1695
1695
|
for (const it of items) {
|
|
1696
1696
|
if (it.kind === 'repeat') {
|
|
1697
1697
|
console.log(`${cyan('make it a playbook?')} asked ${it.count} times: ${it.intent}`);
|
|
@@ -1716,6 +1716,7 @@ export async function main(argv) {
|
|
|
1716
1716
|
}
|
|
1717
1717
|
if (it.kind === 'waiting') console.log(dim(` ${it.waiting.choices?.length ? `choices: ${it.waiting.choices.join(' | ')}\n ` : ''}answer: agentmgr tell ${it.agentId} "…"`));
|
|
1718
1718
|
if (it.kind === 'review') console.log(dim(` ${it.review.verdict.replace('_', ' ')}${it.review.missing.length ? `; missing: ${it.review.missing.join('; ')}` : ''}`));
|
|
1719
|
+
if (it.kind === 'prereview') console.log(dim(`${it.open.map((o) => ` ${o}\n`).join('')} agentmgr rounds ${it.agentId} · another round: --again · open the pull request anyway: --open`));
|
|
1719
1720
|
if (it.kind === 'stuck') console.log(dim(` ${it.finding.detail}\n nudge: agentmgr tell ${it.agentId} "…"`));
|
|
1720
1721
|
if (it.kind === 'conflict') console.log(dim(` ${it.conflict.files.map((f) => f.file).join(', ')}`));
|
|
1721
1722
|
if (it.kind === 'reminder') {
|
|
@@ -1766,6 +1767,45 @@ export async function main(argv) {
|
|
|
1766
1767
|
console.log(`${green('✓')} answer queued for ${a.name}; it is typed into the session when the agent is idle`);
|
|
1767
1768
|
});
|
|
1768
1769
|
|
|
1770
|
+
program
|
|
1771
|
+
.command('rounds')
|
|
1772
|
+
.description("Review rounds before a pull request: critics on other models read an agent's changes when it says it is done, the agent fixes what they find, and the pull request is opened when they approve")
|
|
1773
|
+
.argument('[agent]', "an agent, for its rounds; without one, the settings")
|
|
1774
|
+
.option('--start', "review this agent's changes now, from round one")
|
|
1775
|
+
.option('--again', 'not approved, or it failed: one more round')
|
|
1776
|
+
.option('--open', 'not approved: open the pull request anyway, with what is still open in its description')
|
|
1777
|
+
.option('--stop', 'no more rounds for this agent')
|
|
1778
|
+
.option('--on', 'review every agent that says it is done')
|
|
1779
|
+
.option('--off', 'no review rounds')
|
|
1780
|
+
.option('--rounds <n>', 'at most this many rounds (1 to 5)')
|
|
1781
|
+
.option('--critics <n>', 'how many critics read each round, each on another model (1 to 3)')
|
|
1782
|
+
.option('--pr <on|off>', 'open the pull request when the critics approve')
|
|
1783
|
+
.option('--json', 'print JSON')
|
|
1784
|
+
.action(async (ref, opts) => {
|
|
1785
|
+
await daemon();
|
|
1786
|
+
if (!ref) {
|
|
1787
|
+
const patch = { ...(opts.on ? { enabled: true } : opts.off ? { enabled: false } : {}), ...(opts.rounds !== undefined ? { rounds: Number(opts.rounds) } : {}), ...(opts.critics !== undefined ? { critics: Number(opts.critics) } : {}), ...(opts.pr !== undefined ? { openPr: opts.pr === 'on' } : {}) };
|
|
1788
|
+
const v = Object.keys(patch).length ? await api('PUT', '/prereview', patch) : await api('GET', '/prereview');
|
|
1789
|
+
if (opts.json) return console.log(JSON.stringify(v, null, 2));
|
|
1790
|
+
if (!v.enabled) return console.log(`Review rounds ${dim('off')} ${dim('(agentmgr rounds --on)')}`);
|
|
1791
|
+
console.log(`Review rounds ${green('on')}: up to ${v.rounds} rounds, ${v.critics} ${v.critics === 1 ? 'critic' : 'critics'} a round${v.models.length ? ` (${v.models.map((m) => `${m.engine}${m.model ? ` ${m.model}` : ''}`).join(', ')})` : ''}; the pull request ${v.openPr ? 'is opened on approval' : 'is left to you'}`);
|
|
1792
|
+
console.log(dim(`Can review here: ${v.engines.map((e) => e.label).join(', ') || 'no engine (install Claude Code or Codex)'}`));
|
|
1793
|
+
return;
|
|
1794
|
+
}
|
|
1795
|
+
let a = await resolveAgent(ref);
|
|
1796
|
+
if (opts.start) a = await api('POST', `/agents/${a.id}/prereview`);
|
|
1797
|
+
else if (opts.again) a = await api('POST', `/agents/${a.id}/prereview/again`);
|
|
1798
|
+
else if (opts.open) a = await api('POST', `/agents/${a.id}/prereview/open`);
|
|
1799
|
+
else if (opts.stop) a = await api('DELETE', `/agents/${a.id}/prereview`);
|
|
1800
|
+
const r = a.preReview;
|
|
1801
|
+
if (opts.json) return console.log(JSON.stringify(r ?? null, null, 2));
|
|
1802
|
+
if (!r) return console.log(dim(`${a.name} has had no review rounds (agentmgr rounds ${a.id} --start)`));
|
|
1803
|
+
const state = { reviewing: yellow(`round ${r.round} of ${r.max}: being reviewed`), fixing: yellow(`round ${r.round} of ${r.max}: the agent is fixing what was found`), approved: green(`approved in round ${r.round}`), stalled: red(`not approved after ${r.round} rounds`), opened: yellow(`not approved after ${r.round} rounds; opened anyway`), stopped: dim('stopped'), error: red(`failed: ${r.error}`) };
|
|
1804
|
+
console.log(`${bold(a.name)} ${state[r.status] ?? r.status}${r.pr ? ` ${r.pr}` : ''}${r.prError ? ` ${red(`the pull request was not opened: ${r.prError}`)}` : ''}`);
|
|
1805
|
+
for (const rd of r.rounds ?? []) console.log(dim(` round ${rd.n}: ${rd.critics.map((c) => `${c.by} ${c.error ? `failed (${c.error})` : c.verdict === 'approve' ? 'approves' : 'asks for changes'}`).join(' · ')} · ${rd.raised} new, ${rd.open} open`));
|
|
1806
|
+
for (const f of r.findings ?? []) console.log(` ${f.status === 'open' ? (['blocker', 'major'].includes(f.severity) ? red('open') : yellow('open')) : green('done')} ${f.id.padEnd(6)} ${f.severity.padEnd(7)} ${f.file ? `${f.file}: ` : ''}${f.title}`);
|
|
1807
|
+
});
|
|
1808
|
+
|
|
1769
1809
|
program
|
|
1770
1810
|
.command('improve')
|
|
1771
1811
|
.description("Before review: send an agent its scorecard's low scores, unmet criteria and where a reviewer would look, to fix; it is scored again when done")
|
package/src/config.js
CHANGED
|
@@ -85,6 +85,8 @@ const DEFAULTS = {
|
|
|
85
85
|
// Local models: servers on this computer (Ollama, LM Studio, llama.cpp, MLX) and their models, for the
|
|
86
86
|
// "Local model" engine; `context` is the room Ollama gives a model for an agent (localmodels.js).
|
|
87
87
|
localModels: { enabled: true, context: 32768 },
|
|
88
|
+
// Review rounds before a pull request (prereview.js): critics on other models, until they approve.
|
|
89
|
+
preReview: { enabled: true, rounds: 4, critics: 2, openPr: true },
|
|
88
90
|
// AI News: the frontier labs' latest releases, summarized; see NEWS_DEFAULTS in news.js for every field.
|
|
89
91
|
news: { enabled: true },
|
|
90
92
|
demoPage: false,
|
package/src/manager.js
CHANGED
|
@@ -124,6 +124,7 @@ import { assignedIssues, issueFields, jiraProblem, leadingIssue, loadJira, words
|
|
|
124
124
|
import { issueOf, issueRows } from './issues.js';
|
|
125
125
|
import { askMessage, moduleBenchPrompt, resultsPath } from './benchmarks.js';
|
|
126
126
|
import { designRows } from './designs.js';
|
|
127
|
+
import { preReviewPrompt } from './prereview.js';
|
|
127
128
|
import { reviewPath, reviewerPrompt } from './reviews.js';
|
|
128
129
|
import { findingsPath, fixPath, fixerPrompt, hunterPrompt } from './bughunt.js';
|
|
129
130
|
import { reminderFor, reminderSettings } from './reminders.js';
|
|
@@ -1376,6 +1377,8 @@ export class AgentManager extends EventEmitter {
|
|
|
1376
1377
|
writableDir ??= dir;
|
|
1377
1378
|
prompts.push(specPrompt(path.join(dir, path.basename(specPath(agent.id))), path.join(dir, path.basename(planPath(agent.id))), { withPlan: !agent.planReview }));
|
|
1378
1379
|
}
|
|
1380
|
+
// Its changes are reviewed in rounds before a pull request (prereview.js): it leaves opening one to that.
|
|
1381
|
+
if (withBrief && !planning && this.preReview?.instructs(agent)) prompts.push(preReviewPrompt());
|
|
1379
1382
|
if (agent.planReview && task) {
|
|
1380
1383
|
fs.mkdirSync(briefDir(agent.id), { recursive: true });
|
|
1381
1384
|
const file = path.join(fs.realpathSync(briefDir(agent.id)), path.basename(planPath(agent.id)));
|
|
@@ -2492,9 +2495,11 @@ export class AgentManager extends EventEmitter {
|
|
|
2492
2495
|
if (finished) this.emit('finished', this.store.get(id));
|
|
2493
2496
|
// A bug hunt's findings are checked one by one instead (bughunt.js).
|
|
2494
2497
|
if (agent.hunting) return;
|
|
2495
|
-
|
|
2498
|
+
// Reviewed in rounds before a pull request (prereview.js): the review and the score wait for their end.
|
|
2499
|
+
const rounds = !NO_REPO.has(agent.kind) && this.changesSource && this.preReview?.brief(agent, { finished });
|
|
2500
|
+
if (finished && this.judge.enabled && !rounds) this.requestReview(id, { trigger: 'brief' }).catch(() => {});
|
|
2496
2501
|
// ...and score it for the reviewer ("scorecard": { "auto": false } in config.json turns this off).
|
|
2497
|
-
if ((improved || (finished && this.config.scorecard?.auto !== false)) && !NO_REPO.has(agent.kind) && this.changesSource) this.summarize(id, 'scorecard').catch(() => {});
|
|
2502
|
+
if ((improved || (finished && this.config.scorecard?.auto !== false && !rounds)) && !NO_REPO.has(agent.kind) && this.changesSource) this.summarize(id, 'scorecard').catch(() => {});
|
|
2498
2503
|
}
|
|
2499
2504
|
if (agent.planReview) {
|
|
2500
2505
|
const file = loadPlanFile(id, agent.planReview);
|
|
@@ -3524,6 +3529,13 @@ export class AgentManager extends EventEmitter {
|
|
|
3524
3529
|
if (agent.aiReview?.verdict && !agent.aiReview.seen) {
|
|
3525
3530
|
items.push({ ...base, kind: 'review', key: `review:${agent.id}`, title: agent.aiReview.summary, review: agent.aiReview, at: agent.aiReview.at });
|
|
3526
3531
|
}
|
|
3532
|
+
// Review rounds that ended without approval, or failed (prereview.js).
|
|
3533
|
+
if (['stalled', 'error'].includes(agent.preReview?.status)) {
|
|
3534
|
+
const r = agent.preReview;
|
|
3535
|
+
const open = (r.findings ?? []).filter((f) => f.status === 'open' && ['blocker', 'major'].includes(f.severity));
|
|
3536
|
+
const title = r.status === 'error' ? `The review before its pull request failed: ${r.error}` : `Not approved after ${r.round} review ${r.round === 1 ? 'round' : 'rounds'}: ${open.length} ${open.length === 1 ? 'finding' : 'findings'} still open`;
|
|
3537
|
+
items.push({ ...base, kind: 'prereview', key: `prereview:${agent.id}`, title, open: open.map((f) => `${f.file ? `${f.file}: ` : ''}${f.title}`), at: r.endedAt ?? r.startedAt });
|
|
3538
|
+
}
|
|
3527
3539
|
if (v.followUp) items.push({ ...base, kind: 'reminder', key: `reminder:${agent.id}`, title: v.followUp.title, reminder: v.followUp, at: v.followUp.since });
|
|
3528
3540
|
for (const f of v.stuck) items.push({ ...base, kind: 'stuck', key: `stuck:${agent.id}:${f.key}`, title: f.title, finding: f, at: f.since });
|
|
3529
3541
|
for (const g of v.conflicts) {
|
|
@@ -3536,7 +3548,7 @@ export class AgentManager extends EventEmitter {
|
|
|
3536
3548
|
for (const r of this.rules.view().suggestions) items.push({ kind: 'rule', key: `rule:${r.repo}:${r.rule}`, title: `Always allow ${r.label}${r.everywhere ? ' in every repo' : ''}?`, priority: 2, ...r });
|
|
3537
3549
|
// Others' items (autopilot's held backlog work).
|
|
3538
3550
|
for (const source of this.inboxSources) items.push(...source());
|
|
3539
|
-
const order = { prompt: 0, limit: 1, waiting: 1, question: 1, rule: 2, review: 2, autopilot: 2, stuck: 3, conflict: 4, reminder: 5, repeat: 5 };
|
|
3551
|
+
const order = { prompt: 0, limit: 1, waiting: 1, question: 1, rule: 2, review: 2, prereview: 2, autopilot: 2, stuck: 3, conflict: 4, reminder: 5, repeat: 5 };
|
|
3540
3552
|
return items.sort((a, b) => order[a.kind] - order[b.kind] || a.priority - b.priority);
|
|
3541
3553
|
}
|
|
3542
3554
|
|
package/src/prereview.js
ADDED
|
@@ -0,0 +1,475 @@
|
|
|
1
|
+
// Review rounds: an agent's changes are reviewed before they become a pull request, so the bugs
|
|
2
|
+
// are found here and not by the reviewers of the pull request (people, or GitHub Copilot).
|
|
3
|
+
//
|
|
4
|
+
// When an agent says it is done, critics on other models of the engine it runs on (Claude Code's
|
|
5
|
+
// opus and sonnet, say: another provider may not be installed) each read the diff in the background and
|
|
6
|
+
// report defects: wrong logic, missed edge cases, error handling, behavior callers rely on,
|
|
7
|
+
// missing tests, and what the task asked for that isn't there. Their findings go to the agent's
|
|
8
|
+
// session as one message; it fixes them and says done again, and the critics look again: at what
|
|
9
|
+
// they raised, and at the new diff. That repeats until they approve or the rounds run out (4 by
|
|
10
|
+
// default, 5 at most). Approved: the changes are committed, pushed and opened as a pull request
|
|
11
|
+
// whose description says what was found and fixed. Not approved in time: it waits for you, with
|
|
12
|
+
// what is still open.
|
|
13
|
+
//
|
|
14
|
+
// A finding blocks when it is a blocker or major; minor ones and nits are passed on but don't
|
|
15
|
+
// hold the pull request. Config: "preReview": { "enabled", "rounds", "critics", "models", "openPr" }.
|
|
16
|
+
|
|
17
|
+
import { parseDiff } from '../public/review.js';
|
|
18
|
+
import { parseJsonReply, readSpecDoc, walkthroughHunks } from './brief.js';
|
|
19
|
+
import { DEFAULT_ENGINE, ENGINES, installed } from './engines/index.js';
|
|
20
|
+
|
|
21
|
+
export const PREREVIEW_DEFAULTS = { enabled: true, rounds: 4, critics: 2, openPr: true };
|
|
22
|
+
export const MAX_ROUNDS = 5;
|
|
23
|
+
export const MAX_CRITICS = 3;
|
|
24
|
+
export const SEVERITIES = ['blocker', 'major', 'minor', 'nit'];
|
|
25
|
+
const BLOCKING = new Set(['blocker', 'major']);
|
|
26
|
+
/**
|
|
27
|
+
* The models of an engine that critics run on, strongest first. For another engine, name them in
|
|
28
|
+
* config.json: "engines": { "codex": { "reviewModels": ["…", "…"] } }.
|
|
29
|
+
*/
|
|
30
|
+
const CRITIC_MODELS = { claude: ['opus', 'sonnet', 'haiku'] };
|
|
31
|
+
/** Rounds under way: the agent's other reviews wait for their end. */
|
|
32
|
+
export const ACTIVE = new Set(['reviewing', 'fixing']);
|
|
33
|
+
|
|
34
|
+
const now = () => new Date().toISOString();
|
|
35
|
+
const err = (status, message) => Object.assign(new Error(message), { status });
|
|
36
|
+
const clip = (s, n) => String(s ?? '').trim().slice(0, n);
|
|
37
|
+
const whole = (v, lo, hi, or) => (Number.isInteger(Number(v)) && v !== null && v !== '' ? Math.max(lo, Math.min(hi, Number(v))) : or);
|
|
38
|
+
|
|
39
|
+
/** The settings from config.json, with defaults. `models`: critics you chose, [{ engine, model }]. */
|
|
40
|
+
export function preReviewSettings(config = {}) {
|
|
41
|
+
const c = config.preReview ?? {};
|
|
42
|
+
const models = Array.isArray(c.models) ? c.models.filter((m) => m && typeof m.engine === 'string').map((m) => ({ engine: m.engine, model: m.model ? String(m.model) : null })) : [];
|
|
43
|
+
return {
|
|
44
|
+
enabled: c.enabled !== false,
|
|
45
|
+
rounds: whole(c.rounds, 1, MAX_ROUNDS, PREREVIEW_DEFAULTS.rounds),
|
|
46
|
+
critics: whole(c.critics, 1, MAX_CRITICS, PREREVIEW_DEFAULTS.critics),
|
|
47
|
+
models,
|
|
48
|
+
openPr: c.openPr !== false,
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export const blocking = (findings = []) => findings.filter((f) => f.status === 'open' && BLOCKING.has(f.severity));
|
|
53
|
+
|
|
54
|
+
/** What an agent is told when it starts: the pull request waits for the review. */
|
|
55
|
+
export const preReviewPrompt = () =>
|
|
56
|
+
[
|
|
57
|
+
'Review before a pull request: when your work is done, do not open a pull request yourself. Mark your brief as done.',
|
|
58
|
+
'Your changes are then reviewed by other models. You get their findings to fix, they look again, and the pull request is opened for you when they approve.',
|
|
59
|
+
].join(' ');
|
|
60
|
+
|
|
61
|
+
/** One critic's prompt: the diff, what was asked, and what earlier rounds raised. */
|
|
62
|
+
export function criticPrompt({ intent, briefMarkdown, specDoc, hunks, cut, round, max, earlier = [] }) {
|
|
63
|
+
return [
|
|
64
|
+
"You review an AI coding agent's changes before they become a pull request.",
|
|
65
|
+
`This is round ${round} of at most ${max}. Other reviewers read the same diff independently, and after this the pull request goes to its human reviewers: a defect you miss is found by them.`,
|
|
66
|
+
'Find what is wrong or missing in the CHANGED code. Be exact and skeptical; do not praise.',
|
|
67
|
+
'',
|
|
68
|
+
'Reply with one JSON object only:',
|
|
69
|
+
'{"verdict": "approve|changes", "summary": "<one or two sentences>",',
|
|
70
|
+
' "findings": [{"severity": "blocker|major|minor|nit", "hunk": "H3", "line": "<the changed line it is on, copied, or empty>", "title": "<the defect in a few words>", "why": "<the input or sequence that goes wrong, and what happens then>", "fix": "<what to change>"}],',
|
|
71
|
+
' "missing": ["<something the task or spec asks for that the change does not do>"],',
|
|
72
|
+
' "earlier": [{"id": "R1-2", "status": "resolved|open", "note": "<if open: what is still wrong>"}]}',
|
|
73
|
+
'',
|
|
74
|
+
'What to look for, in the changed lines and what they affect:',
|
|
75
|
+
'- wrong results: logic errors, off-by-one, wrong operator or condition, wrong variable, a case the code forgets (empty, null, zero, negative, very large, duplicate, unicode, concurrent)',
|
|
76
|
+
'- errors: swallowed, unchecked, or handled in a way that hides the failure; resources not released',
|
|
77
|
+
'- behavior that callers, saved data or the public interface relied on and that this changes without saying',
|
|
78
|
+
'- security: input trusted that should not be, secrets, injection, paths, permissions',
|
|
79
|
+
'- new or changed behavior with no test, a test that cannot fail, docs or configuration not updated to match',
|
|
80
|
+
'- leftovers: debug output, commented-out code, TODOs for work the task needed',
|
|
81
|
+
'',
|
|
82
|
+
'Rules:',
|
|
83
|
+
'- severity: blocker = data loss, a security hole, or a crash on the main path. major = a bug a user would hit, or a required part of the task missing. minor = an unlikely edge case, or a small gap in tests or docs. nit = style or naming.',
|
|
84
|
+
'- Every finding needs evidence from the diff: name the input or sequence in "why". If it depends on code you cannot see, say so and rate it minor at most.',
|
|
85
|
+
'- One finding per defect; at most 12, the most serious first. No general advice.',
|
|
86
|
+
'- "earlier": one entry for every finding in EARLIER FINDINGS. "resolved" when the diff now fixes it, or the agent\'s reply in the brief shows it was not a defect; else "open". Do not list an earlier finding again under "findings".',
|
|
87
|
+
'- verdict "approve" only when you have no blocker or major finding, nothing missing, and no earlier blocker or major finding still open.',
|
|
88
|
+
cut ? '- The diff was too long to send whole: review what is here, and say in "summary" that you saw part of it.' : null,
|
|
89
|
+
'',
|
|
90
|
+
'<task>',
|
|
91
|
+
intent || '(none)',
|
|
92
|
+
'</task>',
|
|
93
|
+
'<spec>',
|
|
94
|
+
specDoc || '(no spec written)',
|
|
95
|
+
'</spec>',
|
|
96
|
+
'<brief>',
|
|
97
|
+
(briefMarkdown || '(none)').slice(-12_000),
|
|
98
|
+
'</brief>',
|
|
99
|
+
'<earlier_findings>',
|
|
100
|
+
earlier.length ? earlier.map((f) => `${f.id} [${f.severity}] ${f.file ? `${f.file}: ` : ''}${f.title}\n why: ${f.why}${f.note ? `\n still open last round because: ${f.note}` : ''}`).join('\n') : '(none: this is the first round)',
|
|
101
|
+
'</earlier_findings>',
|
|
102
|
+
'<hunks>',
|
|
103
|
+
...hunks.map((h) => `<hunk id="${h.id}" file="${h.file}">\n${h.head}\n${h.text}\n</hunk>`),
|
|
104
|
+
'</hunks>',
|
|
105
|
+
]
|
|
106
|
+
.filter((l) => l !== null)
|
|
107
|
+
.join('\n');
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** A critic's reply made safe to use: known severities, hunks mapped to files, text cut to size. */
|
|
111
|
+
export function normalizeCritique(reply, hunks = []) {
|
|
112
|
+
if (!reply || typeof reply !== 'object') throw new Error('The reply was not a JSON object');
|
|
113
|
+
const byId = new Map(hunks.map((h) => [h.id, h]));
|
|
114
|
+
const findings = [];
|
|
115
|
+
for (const f of Array.isArray(reply.findings) ? reply.findings : []) {
|
|
116
|
+
const title = clip(f?.title, 160);
|
|
117
|
+
if (!title) continue;
|
|
118
|
+
const h = byId.get(String(f.hunk ?? '').trim());
|
|
119
|
+
findings.push({
|
|
120
|
+
severity: SEVERITIES.includes(f.severity) ? f.severity : 'minor',
|
|
121
|
+
file: h?.file ?? (clip(f.file, 300) || null),
|
|
122
|
+
head: h?.head ?? null,
|
|
123
|
+
line: clip(f.line, 200),
|
|
124
|
+
title,
|
|
125
|
+
why: clip(f.why, 600),
|
|
126
|
+
fix: clip(f.fix, 600),
|
|
127
|
+
});
|
|
128
|
+
if (findings.length === 12) break;
|
|
129
|
+
}
|
|
130
|
+
// Something the task asked for that isn't there holds the pull request like a bug does.
|
|
131
|
+
for (const m of Array.isArray(reply.missing) ? reply.missing.slice(0, 6) : []) {
|
|
132
|
+
const title = clip(m, 160);
|
|
133
|
+
if (title) findings.push({ severity: 'major', file: null, head: null, line: '', title: `Missing: ${title}`, why: 'The task or spec asks for this and the change does not do it.', fix: '' });
|
|
134
|
+
}
|
|
135
|
+
const earlier = {};
|
|
136
|
+
for (const e of Array.isArray(reply.earlier) ? reply.earlier : []) {
|
|
137
|
+
const id = clip(e?.id, 20);
|
|
138
|
+
if (id) earlier[id] = { status: e.status === 'open' ? 'open' : 'resolved', note: clip(e.note, 400) };
|
|
139
|
+
}
|
|
140
|
+
const verdict = reply.verdict === 'approve' && !findings.some((f) => BLOCKING.has(f.severity)) ? 'approve' : 'changes';
|
|
141
|
+
return { verdict, summary: clip(reply.summary, 400), findings, earlier };
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
const words = (s) => new Set(String(s).toLowerCase().match(/[a-z0-9_]{3,}/g) ?? []);
|
|
145
|
+
/**
|
|
146
|
+
* Two critics describing one defect: titles that mostly share their words, or share a third of
|
|
147
|
+
* them on the same line (one line can have two defects: when unsure they stay two findings, since
|
|
148
|
+
* one told twice costs less than one lost).
|
|
149
|
+
*/
|
|
150
|
+
function sameDefect(a, b) {
|
|
151
|
+
if ((a.file ?? '') !== (b.file ?? '')) return false;
|
|
152
|
+
const [x, y] = [words(a.title), words(b.title)];
|
|
153
|
+
if (!x.size || !y.size) return false;
|
|
154
|
+
const shared = [...x].filter((w) => y.has(w)).length / Math.min(x.size, y.size);
|
|
155
|
+
return shared >= (a.line && a.line === b.line ? 1 / 3 : 0.6);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* A round's result from its critics' replies ({ by, verdict, findings, earlier } or { by, error }):
|
|
160
|
+
* the earlier findings with where they stand now, then the new ones (one per defect, with who
|
|
161
|
+
* raised it). An earlier finding stays open when any critic says it is.
|
|
162
|
+
*/
|
|
163
|
+
export function mergeRound(replies, earlier = [], round = 1) {
|
|
164
|
+
const ok = replies.filter((r) => !r.error);
|
|
165
|
+
const carried = earlier.map((f) => {
|
|
166
|
+
if (f.status !== 'open') return { ...f };
|
|
167
|
+
const said = ok.map((r) => r.earlier?.[f.id]).filter(Boolean);
|
|
168
|
+
const open = said.find((s) => s.status === 'open');
|
|
169
|
+
return open ? { ...f, note: open.note || f.note || '' } : { ...f, status: 'resolved', resolvedIn: round, note: '' };
|
|
170
|
+
});
|
|
171
|
+
const fresh = [];
|
|
172
|
+
for (const r of ok) {
|
|
173
|
+
for (const f of r.findings) {
|
|
174
|
+
// The same thing raised again under a new name stays the earlier finding.
|
|
175
|
+
const old = carried.find((c) => sameDefect(c, f));
|
|
176
|
+
if (old) {
|
|
177
|
+
if (old.status !== 'open') Object.assign(old, { status: 'open', resolvedIn: null, note: f.why });
|
|
178
|
+
continue;
|
|
179
|
+
}
|
|
180
|
+
const dup = fresh.find((x) => sameDefect(x, f));
|
|
181
|
+
if (dup) {
|
|
182
|
+
if (!dup.by.includes(r.by)) dup.by.push(r.by);
|
|
183
|
+
if (SEVERITIES.indexOf(f.severity) < SEVERITIES.indexOf(dup.severity)) dup.severity = f.severity;
|
|
184
|
+
continue;
|
|
185
|
+
}
|
|
186
|
+
fresh.push({ ...f, by: [r.by], round, status: 'open' });
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
fresh.sort((a, b) => SEVERITIES.indexOf(a.severity) - SEVERITIES.indexOf(b.severity));
|
|
190
|
+
fresh.forEach((f, i) => (f.id = `R${round}-${i + 1}`));
|
|
191
|
+
return [...carried, ...fresh];
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
const findingLines = (f, i) =>
|
|
195
|
+
[`${i + 1}. [${f.id}] ${f.severity}${f.file ? ` · ${f.file}` : ''}: ${f.title}`, f.line ? ` Line: ${f.line}` : null, f.why ? ` Why: ${f.note || f.why}` : null, f.fix ? ` Fix: ${f.fix}` : null].filter(Boolean).join('\n');
|
|
196
|
+
|
|
197
|
+
/** The message that takes a round's findings to the agent's session. */
|
|
198
|
+
export function fixMessage({ round, max, by = [], findings = [], pushed = false }) {
|
|
199
|
+
const open = findings.filter((f) => f.status === 'open');
|
|
200
|
+
const must = open.filter((f) => BLOCKING.has(f.severity));
|
|
201
|
+
const rest = open.filter((f) => !BLOCKING.has(f.severity));
|
|
202
|
+
return [
|
|
203
|
+
`Before a pull request is opened, your changes were reviewed${by.length ? ` by ${by.join(' and ')}` : ''} (round ${round} of ${max}). ${must.length} ${must.length === 1 ? 'finding has' : 'findings have'} to be dealt with:`,
|
|
204
|
+
'',
|
|
205
|
+
...must.map(findingLines),
|
|
206
|
+
...(rest.length ? ['', 'Smaller things, to fix where you agree:', '', ...rest.map(findingLines)] : []),
|
|
207
|
+
'',
|
|
208
|
+
'For each one: fix it, or if the finding is wrong leave the code and say why. Look for the same mistake elsewhere in your changes, and add or update tests for what you fix. Then run the tests.',
|
|
209
|
+
`When all of it is done, add a "## Review round ${round}" section to your brief with one line per finding id (what you changed, or why it stands), ${pushed ? 'commit and push, ' : ''}and mark the brief as done again. The changes are then reviewed again.`,
|
|
210
|
+
pushed ? '' : 'Do not open a pull request yourself: it is opened when the review approves.',
|
|
211
|
+
]
|
|
212
|
+
.join('\n')
|
|
213
|
+
.trim();
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/** For the pull request's description: how the review went. */
|
|
217
|
+
export function prNote(state = {}) {
|
|
218
|
+
const all = state.findings ?? [];
|
|
219
|
+
const fixed = all.filter((f) => f.status === 'resolved');
|
|
220
|
+
const open = all.filter((f) => f.status === 'open');
|
|
221
|
+
const by = [...new Set((state.rounds ?? []).flatMap((r) => r.critics.filter((c) => !c.error).map((c) => c.by)))];
|
|
222
|
+
const line = (f) => `- ${f.severity}${f.file ? ` · \`${f.file}\`` : ''}: ${f.title}`;
|
|
223
|
+
const head =
|
|
224
|
+
state.status === 'approved'
|
|
225
|
+
? `Approved in round ${state.round} of ${state.max}${by.length ? ` by ${by.join(' and ')}` : ''}. ${all.length ? `${fixed.length} of ${all.length} findings were dealt with before this was opened.` : 'Nothing was found.'}`
|
|
226
|
+
: `Not approved after ${state.round} ${state.round === 1 ? 'round' : 'rounds'}${by.length ? ` (${by.join(', ')})` : ''}: opened anyway.`;
|
|
227
|
+
const out = ['### Reviewed before opening', '', head];
|
|
228
|
+
const hold = open.filter((f) => BLOCKING.has(f.severity));
|
|
229
|
+
const small = open.filter((f) => !BLOCKING.has(f.severity));
|
|
230
|
+
if (hold.length) out.push('', '**Still open:**', '', ...hold.map(line));
|
|
231
|
+
if (small.length) out.push('', 'Smaller things left as they are:', '', ...small.map(line));
|
|
232
|
+
if (fixed.length) out.push('', `<details><summary>Found and dealt with (${fixed.length})</summary>`, '', ...fixed.map(line), '', '</details>');
|
|
233
|
+
return out.join('\n');
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
export class PreReview {
|
|
237
|
+
/**
|
|
238
|
+
* `ship(agentId, { body })` commits, pushes and opens the pull request. `managed(agentId)`: true
|
|
239
|
+
* when something else opens it (autopilot, for backlog work). `skip(agent)`: agents this isn't for.
|
|
240
|
+
*/
|
|
241
|
+
constructor({ manager, config, ship, managed = () => false, skip = () => false, log = () => {} }) {
|
|
242
|
+
Object.assign(this, { manager, config, ship, managed, skip, log, running: new Set() });
|
|
243
|
+
manager.preReview = this;
|
|
244
|
+
// A round cut short by a restart can be run again.
|
|
245
|
+
for (const a of manager.store.list()) {
|
|
246
|
+
if (a.preReview?.status === 'reviewing') manager.patch(a.id, { preReview: { ...a.preReview, status: 'error', round: Math.max(0, a.preReview.round - 1), error: 'The review was interrupted when the app restarted' } });
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
get settings() {
|
|
251
|
+
return preReviewSettings(this.config);
|
|
252
|
+
}
|
|
253
|
+
|
|
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
|
+
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);
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/** Told at launch that the pull request waits for the review? */
|
|
260
|
+
instructs(agent) {
|
|
261
|
+
return this.applies(agent) && this.settings.openPr && !this.managed(agent.id);
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/**
|
|
265
|
+
* Who can review, best first: other models of the engine the agent runs on (another provider may
|
|
266
|
+
* not be there at all), the one it runs on left out when that is known. `models` in config.json
|
|
267
|
+
* names critics yourself, on any engine installed. A round takes the first `critics` of these;
|
|
268
|
+
* one that fails is replaced by the next. An agent on an engine that can't make a one-shot call
|
|
269
|
+
* (a local model, an ACP agent) is reviewed by the engine that writes its summaries.
|
|
270
|
+
*/
|
|
271
|
+
candidates(agent) {
|
|
272
|
+
const usable = (e) => e?.supports.oneShot && installed(e, this.config);
|
|
273
|
+
const own = this.manager.writerFor(agent);
|
|
274
|
+
const fallback = (e) => (e.id === DEFAULT_ENGINE ? this.config.explainModel : this.config.engines?.[e.id]?.explainModel) ?? null;
|
|
275
|
+
const picked = this.settings.models.filter((m) => usable(ENGINES[m.engine])).map((m) => ({ engine: ENGINES[m.engine], model: m.model ?? fallback(ENGINES[m.engine]) }));
|
|
276
|
+
const same = [];
|
|
277
|
+
if (usable(own.engine)) {
|
|
278
|
+
const mine = (agent.engine ?? DEFAULT_ENGINE) === own.engine.id ? String(agent.model ?? '').toLowerCase() : '';
|
|
279
|
+
const names = this.config.engines?.[own.engine.id]?.reviewModels ?? CRITIC_MODELS[own.engine.id] ?? [];
|
|
280
|
+
const other = names.map(String).filter((n) => !mine || !mine.includes(n.toLowerCase()));
|
|
281
|
+
// No other model known for this engine: the one it is set up with, once.
|
|
282
|
+
same.push(...(other.length ? other.map((model) => ({ engine: own.engine, model })) : [{ engine: own.engine, model: own.model ?? null }]));
|
|
283
|
+
}
|
|
284
|
+
const out = [];
|
|
285
|
+
for (const c of [...picked, ...same]) {
|
|
286
|
+
if (!out.some((x) => x.engine.id === c.engine.id && x.model === c.model)) out.push(c);
|
|
287
|
+
}
|
|
288
|
+
return out;
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
critics(agent) {
|
|
292
|
+
return this.candidates(agent).slice(0, this.settings.critics);
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/**
|
|
296
|
+
* From the manager, when an agent's brief changes. True while rounds are under way: its AI
|
|
297
|
+
* review and score wait for their end, so each is made once, of the changes that go out.
|
|
298
|
+
*/
|
|
299
|
+
brief(agent, { finished = false } = {}) {
|
|
300
|
+
const st = agent.preReview;
|
|
301
|
+
// Rounds already under way carry on (also ones you started by hand with the switch off).
|
|
302
|
+
if (st?.status === 'reviewing') return true;
|
|
303
|
+
if (st?.status === 'fixing') {
|
|
304
|
+
if (agent.brief?.status === 'done' && agent.brief.updatedAt !== st.briefAt) this.run(agent.id);
|
|
305
|
+
return true;
|
|
306
|
+
}
|
|
307
|
+
if (!finished || !this.applies(agent)) return false;
|
|
308
|
+
this.begin(agent.id);
|
|
309
|
+
return true;
|
|
310
|
+
}
|
|
311
|
+
|
|
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 } });
|
|
314
|
+
this.run(id);
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/** On request: review this agent's changes now, from round one. */
|
|
318
|
+
start(ref) {
|
|
319
|
+
const agent = this.manager.mustGet(ref);
|
|
320
|
+
if (agent.kind !== 'task' || !agent.workdir || this.skip(agent)) throw err(400, 'This agent has no changes of its own to review');
|
|
321
|
+
if (this.running.has(agent.id)) throw err(409, 'Its changes are being reviewed now');
|
|
322
|
+
this.begin(agent.id);
|
|
323
|
+
return this.manager.view(this.manager.store.get(agent.id));
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
/** The next round, in the background. */
|
|
327
|
+
run(id) {
|
|
328
|
+
if (this.running.has(id)) return;
|
|
329
|
+
this.running.add(id);
|
|
330
|
+
this.round(id)
|
|
331
|
+
.catch((e) => {
|
|
332
|
+
const cur = this.manager.store.get(id);
|
|
333
|
+
this.log(`review rounds: ${cur?.name ?? id}: ${e.message}`);
|
|
334
|
+
if (cur?.preReview) this.manager.patch(id, { preReview: { ...cur.preReview, status: 'error', round: Math.max(0, cur.preReview.round - 1), error: e.message.slice(0, 300) } });
|
|
335
|
+
})
|
|
336
|
+
.finally(() => this.running.delete(id));
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
async round(id) {
|
|
340
|
+
const m = this.manager;
|
|
341
|
+
const agent = m.mustGet(id);
|
|
342
|
+
const prev = agent.preReview ?? {};
|
|
343
|
+
const n = (prev.round ?? 0) + 1;
|
|
344
|
+
const max = Math.max(prev.max ?? this.settings.rounds, n);
|
|
345
|
+
m.patch(id, { preReview: { ...prev, status: 'reviewing', round: n, max, error: null, endedAt: null } });
|
|
346
|
+
const data = await m.changesSource(id);
|
|
347
|
+
const { hunks, cut } = walkthroughHunks(parseDiff(data.diff), { maxLines: 300, maxChars: 80_000 });
|
|
348
|
+
if (!hunks.length) {
|
|
349
|
+
// Nothing changed: nothing to review, and no pull request to open.
|
|
350
|
+
m.patch(id, { preReview: null });
|
|
351
|
+
return this.after(id);
|
|
352
|
+
}
|
|
353
|
+
const pool = this.candidates(agent);
|
|
354
|
+
if (!pool.length) throw new Error('Nothing here can review these changes: the engine has to make one-shot calls (Claude Code and Codex do), or critics have to be named in config.json (preReview.models)');
|
|
355
|
+
const ctx = await m.explainContext(agent);
|
|
356
|
+
const earlier = (prev.findings ?? []).filter((f) => f.status === 'open');
|
|
357
|
+
const prompt = criticPrompt({ intent: readSpecDoc(id, 'intent')?.markdown || agent.intent, briefMarkdown: ctx.briefMarkdown, specDoc: readSpecDoc(id, 'spec')?.markdown ?? '', hunks, cut, round: n, max, earlier });
|
|
358
|
+
const label = (c) => `${c.engine.label}${c.model ? ` (${c.model})` : ''}`;
|
|
359
|
+
const ask = async (c) => {
|
|
360
|
+
try {
|
|
361
|
+
return { by: label(c), ...normalizeCritique(parseJsonReply(await m.oneShot(agent, prompt, { ...c, timeoutMs: 600_000 })), hunks) };
|
|
362
|
+
} catch (e) {
|
|
363
|
+
return { by: label(c), error: e.message.slice(0, 300) };
|
|
364
|
+
}
|
|
365
|
+
};
|
|
366
|
+
// A critic that fails (no answer, or not what was asked for) is replaced by the next who can review.
|
|
367
|
+
const spare = pool.slice(this.settings.critics);
|
|
368
|
+
const stand = async (c) => {
|
|
369
|
+
const r = await ask(c);
|
|
370
|
+
return r.error && spare.length ? [r, ...(await stand(spare.shift()))] : [r];
|
|
371
|
+
};
|
|
372
|
+
const replies = (await Promise.all(pool.slice(0, this.settings.critics).map(stand))).flat();
|
|
373
|
+
const cur = m.store.get(id);
|
|
374
|
+
if (!cur?.preReview || cur.preReview.status !== 'reviewing') return; // deleted, or stopped meanwhile
|
|
375
|
+
if (replies.every((r) => r.error)) throw new Error(`The review failed: ${replies[0].error}`);
|
|
376
|
+
const findings = mergeRound(replies, prev.findings ?? [], n);
|
|
377
|
+
const hold = blocking(findings);
|
|
378
|
+
const rounds = [...(prev.rounds ?? []), { n, at: now(), cut, critics: replies.map((r) => ({ by: r.by, verdict: r.verdict ?? null, summary: r.summary ?? '', error: r.error ?? null })), raised: findings.filter((f) => f.round === n).length, open: hold.length }];
|
|
379
|
+
const state = { ...cur.preReview, round: n, max, findings, rounds, error: null };
|
|
380
|
+
if (!hold.length) return this.end(id, { ...state, status: 'approved', endedAt: now() });
|
|
381
|
+
if (n >= max) return this.end(id, { ...state, status: 'stalled', endedAt: now() });
|
|
382
|
+
this.send(id, state);
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
/** The open findings into the agent's session; the next round runs when it says done again. */
|
|
386
|
+
send(id, state) {
|
|
387
|
+
const m = this.manager;
|
|
388
|
+
const agent = m.store.get(id);
|
|
389
|
+
const pushed = Object.values(agent.prs ?? {}).some((p) => p.state === 'OPEN' && p.source !== 'mentioned');
|
|
390
|
+
m.patch(id, { preReview: { ...state, status: 'fixing', briefAt: agent.brief?.updatedAt ?? null, sentAt: now() } });
|
|
391
|
+
m.tell(id, fixMessage({ round: state.round, max: state.max, by: state.rounds.at(-1)?.critics.filter((c) => !c.error).map((c) => c.by), findings: state.findings, pushed }), { source: 'prereview' });
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
/** Approved, or out of rounds: the reviews that waited are made, and an approved change is opened. */
|
|
395
|
+
async end(id, state) {
|
|
396
|
+
this.manager.patch(id, { preReview: state });
|
|
397
|
+
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
|
+
await this.after(id);
|
|
399
|
+
if (state.status === 'approved' && this.settings.openPr && !this.managed(id)) await this.open(id).catch(() => {});
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
/** What waited for the rounds: the AI review, and the score (which goes in the pull request's description). */
|
|
403
|
+
async after(id) {
|
|
404
|
+
const m = this.manager;
|
|
405
|
+
if (m.judge.enabled) m.requestReview(id, { trigger: 'brief' }).catch(() => {});
|
|
406
|
+
if (this.config.scorecard?.auto !== false) await m.summarize(id, 'scorecard').catch(() => {});
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
/** Commit, push and open the pull request, with how the review went in its description. */
|
|
410
|
+
async open(ref) {
|
|
411
|
+
const m = this.manager;
|
|
412
|
+
const agent = m.mustGet(ref);
|
|
413
|
+
const st = agent.preReview;
|
|
414
|
+
if (!st || ACTIVE.has(st.status)) throw err(409, 'The review is still under way');
|
|
415
|
+
try {
|
|
416
|
+
const r = await this.ship(agent.id, { body: prNote(st) });
|
|
417
|
+
const cur = m.store.get(agent.id);
|
|
418
|
+
if (cur?.preReview) m.patch(agent.id, { preReview: { ...cur.preReview, pr: r.url ?? null, prError: null, status: cur.preReview.status === 'stalled' ? 'opened' : cur.preReview.status } });
|
|
419
|
+
return m.view(m.store.get(agent.id));
|
|
420
|
+
} catch (e) {
|
|
421
|
+
const cur = m.store.get(agent.id);
|
|
422
|
+
if (cur?.preReview) m.patch(agent.id, { preReview: { ...cur.preReview, prError: e.message.split('\n')[0].slice(0, 300) } });
|
|
423
|
+
throw e;
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
/** Out of rounds, or it failed: one more round. What is open goes to the agent again first. */
|
|
428
|
+
again(ref) {
|
|
429
|
+
const agent = this.manager.mustGet(ref);
|
|
430
|
+
const st = agent.preReview;
|
|
431
|
+
if (!st || !['stalled', 'error'].includes(st.status)) throw err(409, 'There is no review to carry on with');
|
|
432
|
+
if (this.running.has(agent.id)) throw err(409, 'Its changes are being reviewed now');
|
|
433
|
+
if (st.status === 'error' || !blocking(st.findings).length) {
|
|
434
|
+
this.manager.patch(agent.id, { preReview: { ...st, status: 'reviewing', max: Math.max(st.max, Math.min(MAX_ROUNDS, st.round + 1)), error: null } });
|
|
435
|
+
this.run(agent.id);
|
|
436
|
+
} else this.send(agent.id, { ...st, max: st.round + 1 });
|
|
437
|
+
return this.manager.view(this.manager.store.get(agent.id));
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
/** Leave it: no more rounds for this work, and the reviews that waited are made. */
|
|
441
|
+
stop(ref) {
|
|
442
|
+
const agent = this.manager.mustGet(ref);
|
|
443
|
+
const st = agent.preReview;
|
|
444
|
+
if (!st) throw err(404, 'This agent has no review rounds');
|
|
445
|
+
const was = ACTIVE.has(st.status);
|
|
446
|
+
this.manager.patch(agent.id, { preReview: { ...st, status: 'stopped', endedAt: now() } });
|
|
447
|
+
if (was) this.after(agent.id).catch(() => {});
|
|
448
|
+
return this.manager.view(this.manager.store.get(agent.id));
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
view() {
|
|
452
|
+
const s = this.settings;
|
|
453
|
+
const usable = Object.values(ENGINES).filter((e) => e.supports.oneShot && installed(e, this.config)).map((e) => ({ id: e.id, label: e.label }));
|
|
454
|
+
return { ...s, maxRounds: MAX_ROUNDS, maxCritics: MAX_CRITICS, engines: usable };
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
/** Changes from the API: `enabled`, `rounds`, `critics`, `openPr`, `models: [{ engine, model }]`. */
|
|
458
|
+
change(b = {}) {
|
|
459
|
+
const next = { ...this.config.preReview };
|
|
460
|
+
for (const k of ['enabled', 'openPr']) if (k in b) next[k] = b[k] === true || b[k] === 'on';
|
|
461
|
+
for (const [k, hi] of [['rounds', MAX_ROUNDS], ['critics', MAX_CRITICS]]) {
|
|
462
|
+
if (!(k in b)) continue;
|
|
463
|
+
const n = Number(b[k]);
|
|
464
|
+
if (!Number.isInteger(n) || n < 1 || n > hi) throw err(400, `${k} is a number from 1 to ${hi}`);
|
|
465
|
+
next[k] = n;
|
|
466
|
+
}
|
|
467
|
+
if ('models' in b) {
|
|
468
|
+
if (!Array.isArray(b.models)) throw err(400, 'models is a list of { engine, model }');
|
|
469
|
+
for (const m of b.models) if (!ENGINES[m?.engine]?.supports.oneShot) throw err(400, `"${m?.engine}" can't review: choose from ${Object.values(ENGINES).filter((e) => e.supports.oneShot).map((e) => e.id).join(', ')}`);
|
|
470
|
+
next.models = b.models.map((m) => ({ engine: m.engine, ...(m.model ? { model: String(m.model) } : {}) }));
|
|
471
|
+
}
|
|
472
|
+
this.config.preReview = next;
|
|
473
|
+
return next;
|
|
474
|
+
}
|
|
475
|
+
}
|
package/src/review.js
CHANGED
|
@@ -27,6 +27,12 @@ export function parseBaseRef(baseRef) {
|
|
|
27
27
|
return m ? { ref: m[1], sha: m[2] } : null;
|
|
28
28
|
}
|
|
29
29
|
|
|
30
|
+
/** What gh itself said when a call failed: the error has the whole command before it, and a description can be many lines. */
|
|
31
|
+
const ghSaid = (e, args) => {
|
|
32
|
+
const head = `${ghBin()} ${args.join(' ')} failed: `;
|
|
33
|
+
return e.message.startsWith(head) ? e.message.slice(head.length) : e.message.replace(/^\S+ [\s\S]*? failed: /, '');
|
|
34
|
+
};
|
|
35
|
+
|
|
30
36
|
/** The branch a pull request should target, from the ref the agent branched from. */
|
|
31
37
|
export function prBase(ref) {
|
|
32
38
|
if (!ref || ref === 'HEAD' || /^[0-9a-f]{7,40}$/.test(ref)) return null;
|
|
@@ -173,7 +179,7 @@ export class Review {
|
|
|
173
179
|
await git.run(ghBin(), again ? [...args, '--edit-last'] : args, opts);
|
|
174
180
|
} catch (e) {
|
|
175
181
|
// The comment we edited may be gone; add a new one.
|
|
176
|
-
if (!again) throw err(502, `Posting the scorecard failed: ${e
|
|
182
|
+
if (!again) throw err(502, `Posting the scorecard failed: ${ghSaid(e, args)}`);
|
|
177
183
|
await git.run(ghBin(), args, opts);
|
|
178
184
|
}
|
|
179
185
|
const cur = this.manager.store.get(agent.id);
|
|
@@ -194,7 +200,7 @@ export class Review {
|
|
|
194
200
|
try {
|
|
195
201
|
await git.run(ghBin(), again ? [...args, '--edit-last'] : args, opts);
|
|
196
202
|
} catch (e) {
|
|
197
|
-
if (!again) throw err(502, `Posting the Eval failed: ${e
|
|
203
|
+
if (!again) throw err(502, `Posting the Eval failed: ${ghSaid(e, args)}`);
|
|
198
204
|
await git.run(ghBin(), args, opts);
|
|
199
205
|
}
|
|
200
206
|
const cur = this.manager.store.get(agent.id);
|
|
@@ -275,7 +281,7 @@ export class Review {
|
|
|
275
281
|
} catch (e) {
|
|
276
282
|
const m = /https:\/\/\S+\/pull\/\d+/.exec(e.message);
|
|
277
283
|
if (m && /already exists/i.test(e.message)) out = m[0];
|
|
278
|
-
else throw err(502, `Pushed, but opening the pull request failed: ${e
|
|
284
|
+
else throw err(502, `Pushed, but opening the pull request failed: ${ghSaid(e, args)}`);
|
|
279
285
|
}
|
|
280
286
|
const url = /https:\/\/\S+\/pull\/\d+/.exec(out)?.[0];
|
|
281
287
|
if (url) this.manager.addLink(agent.id, { type: 'pr', value: url });
|
package/src/server.js
CHANGED
|
@@ -17,6 +17,7 @@ import { Teams } from './teams.js';
|
|
|
17
17
|
import { Assistant, FEATURES, featuresOf } from './assistant.js';
|
|
18
18
|
import { Cleanup } from './cleanup.js';
|
|
19
19
|
import { Landing } from './landing.js';
|
|
20
|
+
import { PreReview } from './prereview.js';
|
|
20
21
|
import { Autopilot } from './autopilot.js';
|
|
21
22
|
import { Goals, goalMarkdown } from './goals.js';
|
|
22
23
|
import { Budgets } from './budgets.js';
|
|
@@ -206,6 +207,30 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
|
|
|
206
207
|
const teams = new Teams({ manager, store, config });
|
|
207
208
|
const cleanup = new Cleanup({ manager, store, config, teams });
|
|
208
209
|
const landing = new Landing({ manager, store, config });
|
|
210
|
+
/** Commit what's left, push and open the agent's pull request, titled after the issue or request. */
|
|
211
|
+
const shipAgent = async (ref, { title = '', body = '' } = {}) => {
|
|
212
|
+
const a = manager.mustGet(ref);
|
|
213
|
+
const key = leadingJiraKey(a.intent);
|
|
214
|
+
const words = a.synopsis?.text ?? a.brief?.title ?? String(a.intent ?? '').replace(/^<?https?:\/\/\S+>?\s*/, '').split('\n')[0];
|
|
215
|
+
title = String(title ?? '').trim() || `${key ? `${key}: ` : ''}${words || a.name}`.slice(0, 100);
|
|
216
|
+
try {
|
|
217
|
+
await review.commit(a.id, { message: title });
|
|
218
|
+
} catch (e) {
|
|
219
|
+
if (e.status !== 409 || !/nothing to commit/i.test(e.message)) throw e;
|
|
220
|
+
}
|
|
221
|
+
const r = await review.pr(a.id, { title, body });
|
|
222
|
+
await manager.refresh(a.id, { withPrs: true }).catch(() => {});
|
|
223
|
+
return { url: r.url ?? null, title };
|
|
224
|
+
};
|
|
225
|
+
// An agent's changes are reviewed in rounds, by other models, before they become a pull request.
|
|
226
|
+
// Backlog work on autopilot is opened by autopilot, once the rounds are over.
|
|
227
|
+
const preReview = new PreReview({
|
|
228
|
+
manager,
|
|
229
|
+
config,
|
|
230
|
+
ship: shipAgent,
|
|
231
|
+
managed: (id) => backlog.items().some((it) => it.agentId === id && ['active', 'review'].includes(it.status) && backlog.autopilotFor(it.projectKey) !== 'off'),
|
|
232
|
+
log: (m) => console.log(`[agentmgr] ${m}`),
|
|
233
|
+
});
|
|
209
234
|
// Backlog work the scorecard calls ready goes on to a pull request (and merged) by itself.
|
|
210
235
|
const autopilot = new Autopilot({ manager, store, backlog, review, landing, config });
|
|
211
236
|
manager.inboxSources.push(() => autopilot.inbox());
|
|
@@ -833,20 +858,17 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
|
|
|
833
858
|
api.post('/agents/:id/changes/commit', wrap((req) => review.commit(req.params.id, req.body ?? {})));
|
|
834
859
|
api.post('/agents/:id/changes/pr', wrap((req) => review.pr(req.params.id, req.body ?? {})));
|
|
835
860
|
// Done but no pull request: commit what's left, push and open one, titled after the issue or request.
|
|
836
|
-
api.post('/agents/:id/ship', wrap(
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
await review.commit(a.id, { message: title });
|
|
843
|
-
} catch (e) {
|
|
844
|
-
if (e.status !== 409 || !/nothing to commit/i.test(e.message)) throw e;
|
|
845
|
-
}
|
|
846
|
-
const r = await review.pr(a.id, { title });
|
|
847
|
-
await manager.refresh(a.id, { withPrs: true }).catch(() => {});
|
|
848
|
-
return { url: r.url ?? null, title };
|
|
861
|
+
api.post('/agents/:id/ship', wrap((req) => shipAgent(req.params.id, { title: req.body?.title })));
|
|
862
|
+
// Review rounds before a pull request (prereview.js).
|
|
863
|
+
api.get('/prereview', wrap(() => preReview.view()));
|
|
864
|
+
api.put('/prereview', wrap((req) => {
|
|
865
|
+
saveConfig({ preReview: preReview.change(req.body ?? {}) });
|
|
866
|
+
return preReview.view();
|
|
849
867
|
}));
|
|
868
|
+
api.post('/agents/:id/prereview', wrap((req) => preReview.start(req.params.id)));
|
|
869
|
+
api.post('/agents/:id/prereview/again', wrap((req) => preReview.again(req.params.id)));
|
|
870
|
+
api.post('/agents/:id/prereview/open', wrap((req) => preReview.open(req.params.id)));
|
|
871
|
+
api.delete('/agents/:id/prereview', wrap((req) => preReview.stop(req.params.id)));
|
|
850
872
|
api.post('/agents/:id/fork', wrap((req) => manager.fork(req.params.id, req.body ?? {})));
|
|
851
873
|
api.post('/agents/:id/continue-on', wrap((req) => manager.continueOn(req.params.id, { engine: req.body?.engine })));
|
|
852
874
|
|