ai-agentmanager 1.21.0 → 1.23.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 +12 -0
- package/README.md +84 -2
- package/package.json +1 -1
- package/public/app.js +64 -2
- package/public/designs.js +172 -0
- package/public/index.html +18 -0
- package/public/issues.js +255 -0
- package/public/keys.js +6 -2
- package/public/land.js +2 -0
- package/public/prvoice.js +103 -0
- package/public/reviews.js +318 -0
- package/public/speak.js +7 -2
- package/public/style.css +144 -0
- package/public/value.js +299 -0
- package/src/assistant.js +20 -5
- package/src/cli.js +252 -1
- package/src/designs.js +72 -0
- package/src/issues.js +272 -0
- package/src/jira.js +15 -4
- package/src/manager.js +78 -8
- package/src/notify.js +1 -0
- package/src/reviews.js +359 -0
- package/src/server.js +89 -0
- package/src/value.js +609 -0
package/src/jira.js
CHANGED
|
@@ -76,7 +76,15 @@ export function wordsAfterLink(text) {
|
|
|
76
76
|
* The issue's summary, or null when it can't be had (not a site we contact, no access, offline).
|
|
77
77
|
* `fetchImpl` and `allow` are for tests.
|
|
78
78
|
*/
|
|
79
|
-
export async function issueSummary(
|
|
79
|
+
export async function issueSummary(issue, opts = {}) {
|
|
80
|
+
return (await issueFields(issue, opts))?.summary ?? null;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* The issue's summary and workflow status ({ summary, status, category }: category is Jira's
|
|
85
|
+
* "new", "indeterminate" or "done"), or null when it can't be had.
|
|
86
|
+
*/
|
|
87
|
+
export async function issueFields({ key, site }, { jira = loadJira(), fetchImpl = fetch, timeoutMs = 6000, allow = null } = {}) {
|
|
80
88
|
const host = (() => {
|
|
81
89
|
try {
|
|
82
90
|
return new URL(site).host;
|
|
@@ -90,10 +98,13 @@ export async function issueSummary({ key, site }, { jira = loadJira(), fetchImpl
|
|
|
90
98
|
const headers = { accept: 'application/json' };
|
|
91
99
|
if (configured && jira.email && jira.token) headers.authorization = `Basic ${Buffer.from(`${jira.email}:${jira.token}`).toString('base64')}`;
|
|
92
100
|
try {
|
|
93
|
-
const res = await fetchImpl(`${site}/rest/api/3/issue/${encodeURIComponent(key)}?fields=summary`, { headers, redirect: 'error', signal: AbortSignal.timeout(timeoutMs) });
|
|
101
|
+
const res = await fetchImpl(`${site}/rest/api/3/issue/${encodeURIComponent(key)}?fields=summary,status`, { headers, redirect: 'error', signal: AbortSignal.timeout(timeoutMs) });
|
|
94
102
|
if (!res.ok) return null;
|
|
95
|
-
const
|
|
96
|
-
|
|
103
|
+
const f = (await res.json())?.fields ?? {};
|
|
104
|
+
const summary = typeof f.summary === 'string' && f.summary.trim() ? f.summary.trim().slice(0, 300) : null;
|
|
105
|
+
const status = typeof f.status?.name === 'string' ? f.status.name.slice(0, 60) : null;
|
|
106
|
+
if (!summary && !status) return null;
|
|
107
|
+
return { summary, status, category: typeof f.status?.statusCategory?.key === 'string' ? f.status.statusCategory.key : null };
|
|
97
108
|
} catch {
|
|
98
109
|
return null;
|
|
99
110
|
}
|
package/src/manager.js
CHANGED
|
@@ -107,7 +107,10 @@ import { spawn } from 'node:child_process';
|
|
|
107
107
|
import * as git from './git.js';
|
|
108
108
|
import { buildMap, touchedFiles } from './codemap.js';
|
|
109
109
|
import { parseDiff } from '../public/review.js';
|
|
110
|
-
import { issueSummary, leadingIssue, wordsAfterLink } from './jira.js';
|
|
110
|
+
import { issueFields, issueSummary, leadingIssue, loadJira, wordsAfterLink } from './jira.js';
|
|
111
|
+
import { issueRows } from './issues.js';
|
|
112
|
+
import { designRows } from './designs.js';
|
|
113
|
+
import { reviewPath, reviewerPrompt } from './reviews.js';
|
|
111
114
|
import { reminderFor, reminderSettings } from './reminders.js';
|
|
112
115
|
import { combine, facts as scoreFacts, improveMessage, scorecardMarkdown, scorecardPrompt } from './scorecard.js';
|
|
113
116
|
import { CONTAINER_ENGINES, claudeToken, containerName, containerRunning, engineMounts, gitCommonDir, removeContainer, runArgs, stopContainer } from './container.js';
|
|
@@ -620,6 +623,7 @@ export class AgentManager extends EventEmitter {
|
|
|
620
623
|
attachments,
|
|
621
624
|
isolation,
|
|
622
625
|
builds,
|
|
626
|
+
reviewing,
|
|
623
627
|
}) {
|
|
624
628
|
intent = (intent ?? '').trim();
|
|
625
629
|
const staged = stagedFiles(attachments);
|
|
@@ -674,6 +678,8 @@ export class AgentManager extends EventEmitter {
|
|
|
674
678
|
...(isolation ? { isolation } : {}),
|
|
675
679
|
// A session that develops an agent built here (builder.js): { name, engine }.
|
|
676
680
|
...(builds ? { builds: { name: String(builds.name), engine: String(builds.engine ?? 'claude') } } : {}),
|
|
681
|
+
// Reviews someone else's pull request (reviews.js): { url, slug, number, title }.
|
|
682
|
+
...(!general && reviewing ? { reviewing } : {}),
|
|
677
683
|
name: name?.trim() || jiraKey || slug,
|
|
678
684
|
slug,
|
|
679
685
|
intent,
|
|
@@ -690,11 +696,11 @@ export class AgentManager extends EventEmitter {
|
|
|
690
696
|
model: model || null,
|
|
691
697
|
// Review the implementation plan before the agent implements it: null = no review.
|
|
692
698
|
// Team members get their review from the team instead.
|
|
693
|
-
planReview: !general && !team && !builds && (planReview ?? this.config.planReview ?? false) ? { status: 'writing' } : null,
|
|
699
|
+
planReview: !general && !team && !builds && !reviewing && (planReview ?? this.config.planReview ?? false) ? { status: 'writing' } : null,
|
|
694
700
|
// Write and publish a design doc (Google Doc + Artifact) after the plan, updated at the end.
|
|
695
|
-
designDoc: !general && !team && !builds && Boolean(designDoc ?? this.config.designDoc ?? true),
|
|
696
|
-
demoPage: !general && !team && !builds && Boolean(demoPage ?? this.config.demoPage ?? false),
|
|
697
|
-
benchmarks: !general && !team && !builds && Boolean(benchmarks ?? this.config.benchmarks ?? false),
|
|
701
|
+
designDoc: !general && !team && !builds && !reviewing && Boolean(designDoc ?? this.config.designDoc ?? true),
|
|
702
|
+
demoPage: !general && !team && !builds && !reviewing && Boolean(demoPage ?? this.config.demoPage ?? false),
|
|
703
|
+
benchmarks: !general && !team && !builds && !reviewing && Boolean(benchmarks ?? this.config.benchmarks ?? false),
|
|
698
704
|
status: 'preparing',
|
|
699
705
|
desired: start ? 'running' : 'stopped',
|
|
700
706
|
error: null,
|
|
@@ -715,7 +721,8 @@ export class AgentManager extends EventEmitter {
|
|
|
715
721
|
...(team ? { team } : {}),
|
|
716
722
|
...(imported ? { imported } : {}),
|
|
717
723
|
};
|
|
718
|
-
|
|
724
|
+
// The PR a reviewer reviews isn't its own: it stays "mentioned", so landing and the rest leave it alone.
|
|
725
|
+
for (const pr of refs.prs) agent.prs[pr.url] = { ...pr, source: pr.url === agent.reviewing?.url ? 'mentioned' : 'intent' };
|
|
719
726
|
for (const bug of refs.bugs) agent.bugs[bug.key] = { ...bug, source: 'intent' };
|
|
720
727
|
// A request that starts with an issue link: describe it by the issue's summary (fetched below),
|
|
721
728
|
// and until then by the words after the link.
|
|
@@ -817,6 +824,50 @@ export class AgentManager extends EventEmitter {
|
|
|
817
824
|
return { project: { key: g.key, name: g.name }, projects: list, map: buildMap({ files, agents }) };
|
|
818
825
|
}
|
|
819
826
|
|
|
827
|
+
/**
|
|
828
|
+
* The issues agents work on, for the summary: one row per agent, with each issue's Jira status
|
|
829
|
+
* (fetched a few at a time, kept five minutes).
|
|
830
|
+
*/
|
|
831
|
+
async issues(proposed = []) {
|
|
832
|
+
const views = this.store.list().map((a) => this.view(a));
|
|
833
|
+
const rows = issueRows(views, new Map(), () => null, proposed);
|
|
834
|
+
this.jiraCache ??= new Map();
|
|
835
|
+
const jira = new Map();
|
|
836
|
+
const want = [];
|
|
837
|
+
for (const r of rows) {
|
|
838
|
+
if (jira.has(r.key)) continue;
|
|
839
|
+
const hit = this.jiraCache.get(r.key);
|
|
840
|
+
if (hit && Date.now() - hit.at < 5 * 60_000) jira.set(r.key, hit.fields);
|
|
841
|
+
else if (r.url && want.length < 40) {
|
|
842
|
+
let site = null;
|
|
843
|
+
try {
|
|
844
|
+
site = new URL(r.url).origin;
|
|
845
|
+
} catch {}
|
|
846
|
+
if (site) want.push({ key: r.key, site });
|
|
847
|
+
jira.set(r.key, null);
|
|
848
|
+
}
|
|
849
|
+
}
|
|
850
|
+
const opts = { ...this.jiraOptions };
|
|
851
|
+
for (let i = 0; i < want.length; i += 4) {
|
|
852
|
+
await Promise.all(
|
|
853
|
+
want.slice(i, i + 4).map(async (w) => {
|
|
854
|
+
const fields = await issueFields(w, opts).catch(() => null);
|
|
855
|
+
this.jiraCache.set(w.key, { at: Date.now(), fields });
|
|
856
|
+
jira.set(w.key, fields);
|
|
857
|
+
}),
|
|
858
|
+
);
|
|
859
|
+
}
|
|
860
|
+
for (const [k, v] of jira) if (!v) jira.delete(k);
|
|
861
|
+
const j = loadJira();
|
|
862
|
+
return { rows: issueRows(views, jira, (id, name) => readSpecDoc(id, name)?.markdown ?? null, proposed), jira: { site: j.site, signedIn: Boolean(j.site && j.email && j.token) } };
|
|
863
|
+
}
|
|
864
|
+
|
|
865
|
+
/** Every agent's design doc, for the Designs list. */
|
|
866
|
+
designs() {
|
|
867
|
+
const views = this.store.list().map((a) => this.view(a));
|
|
868
|
+
return { rows: designRows(views, (id) => readSpecDoc(id, 'designdoc')?.markdown ?? null) };
|
|
869
|
+
}
|
|
870
|
+
|
|
820
871
|
/** A repository's tracked files, for the map (kept a few minutes). */
|
|
821
872
|
async repoFiles(dir) {
|
|
822
873
|
this.fileLists ??= new Map();
|
|
@@ -831,6 +882,7 @@ export class AgentManager extends EventEmitter {
|
|
|
831
882
|
|
|
832
883
|
/** Fill in summaries still missing (after Jira settings change); returns how many it found. */
|
|
833
884
|
async refreshSynopses() {
|
|
885
|
+
this.jiraCache?.clear();
|
|
834
886
|
let found = 0;
|
|
835
887
|
for (const a of this.store.list()) {
|
|
836
888
|
if (a.synopsis?.source === 'jira' || !leadingIssue(a.intent)) continue;
|
|
@@ -1131,7 +1183,7 @@ export class AgentManager extends EventEmitter {
|
|
|
1131
1183
|
}
|
|
1132
1184
|
// SPEC.md before changing code, and PLAN.md kept as it goes (unless the plan review asks for the plan).
|
|
1133
1185
|
// A session building an agent keeps its analysis in the agent's folder instead.
|
|
1134
|
-
if (task && this.config.specs !== false && !agent.builds) {
|
|
1186
|
+
if (task && this.config.specs !== false && !agent.builds && !agent.reviewing) {
|
|
1135
1187
|
fs.mkdirSync(briefDir(agent.id), { recursive: true });
|
|
1136
1188
|
const dir = fs.realpathSync(briefDir(agent.id));
|
|
1137
1189
|
writableDir ??= dir;
|
|
@@ -1156,6 +1208,12 @@ export class AgentManager extends EventEmitter {
|
|
|
1156
1208
|
if (agent.demoPage) prompts.push(demoPagePrompt(path.join(dir, path.basename(demoPath(agent.id)))));
|
|
1157
1209
|
if (agent.benchmarks) prompts.push(benchmarksPrompt(path.join(dir, path.basename(benchPath(agent.id))), path.join(dir, 'bench')));
|
|
1158
1210
|
}
|
|
1211
|
+
if (agent.reviewing && task) {
|
|
1212
|
+
fs.mkdirSync(briefDir(agent.id), { recursive: true });
|
|
1213
|
+
const file = path.join(fs.realpathSync(briefDir(agent.id)), path.basename(reviewPath(agent.id)));
|
|
1214
|
+
writableDir ??= path.dirname(file);
|
|
1215
|
+
prompts.push(reviewerPrompt(file, agent.reviewing));
|
|
1216
|
+
}
|
|
1159
1217
|
if (planning) prompts.push(planningPrompt(agent));
|
|
1160
1218
|
// What earlier agents learned in this repo, and the one command to add to it.
|
|
1161
1219
|
let allowedTools = null;
|
|
@@ -2074,7 +2132,7 @@ export class AgentManager extends EventEmitter {
|
|
|
2074
2132
|
if (k === 'source') continue;
|
|
2075
2133
|
if (v != null && merged[k] !== v) merged[k] = v;
|
|
2076
2134
|
}
|
|
2077
|
-
if ((SOURCE_RANK[item.source] ?? 0) > (SOURCE_RANK[cur.source] ?? 0)) merged.source = item.source;
|
|
2135
|
+
if ((SOURCE_RANK[item.source] ?? 0) > (SOURCE_RANK[cur.source] ?? 0) && key !== agent.reviewing?.url) merged.source = item.source;
|
|
2078
2136
|
if (JSON.stringify(merged) !== JSON.stringify(cur)) {
|
|
2079
2137
|
bag[key] = merged;
|
|
2080
2138
|
changed = true;
|
|
@@ -2490,6 +2548,18 @@ export class AgentManager extends EventEmitter {
|
|
|
2490
2548
|
return this.view(this.store.get(agent.id));
|
|
2491
2549
|
}
|
|
2492
2550
|
|
|
2551
|
+
/**
|
|
2552
|
+
* One Google Doc in a Drive folder (created the first time, `folderId` after that), through the
|
|
2553
|
+
* Google Drive connector of the Claude account: { folderId, id, url }.
|
|
2554
|
+
*/
|
|
2555
|
+
async publishDriveDoc({ folderTitle, folderId = null, title, markdown }) {
|
|
2556
|
+
const sent = [{ key: 'doc', title, html: driveHtml(title, markdown) }];
|
|
2557
|
+
const reply = await this.oneShot({ id: 'drive' }, drivePrompt({ folderTitle, folderId, docs: sent, trash: [] }), { engine: engineOf('claude'), tools: DRIVE_TOOLS, timeoutMs: 600_000 });
|
|
2558
|
+
const r = parseDrive(reply, ['doc']);
|
|
2559
|
+
if (!r.files.doc) throw new Error(r.errors[0] ?? 'Google Drive returned no document (is the Google Drive connector linked to your Claude account?)');
|
|
2560
|
+
return { folderId: r.folderId, id: r.files.doc, url: docUrl(r.files.doc) };
|
|
2561
|
+
}
|
|
2562
|
+
|
|
2493
2563
|
/** Diagrams only: the problem and its solution drawn from the documents already written and the live context. */
|
|
2494
2564
|
async runDiagrams(agent, ctx) {
|
|
2495
2565
|
const cur0 = this.store.get(agent.id) ?? agent;
|
package/src/notify.js
CHANGED
|
@@ -19,6 +19,7 @@ export const EVENT_DEFAULTS = {
|
|
|
19
19
|
assistant: true, // an agent was started for new work (assistant, GitHub label, webhook)
|
|
20
20
|
budget: true, // an agent neared or reached its budget, or today's spend reached the daily limit
|
|
21
21
|
standup: true, // the daily standup is ready to play
|
|
22
|
+
value: true, // a scheduled value report (week, month, quarter)
|
|
22
23
|
};
|
|
23
24
|
|
|
24
25
|
// Alerts the AI judge may hold for the digest or drop; the rest are always sent at once.
|
package/src/reviews.js
ADDED
|
@@ -0,0 +1,359 @@
|
|
|
1
|
+
// Reviews: agents that review other people's pull requests for you. A reviewer agent reads the
|
|
2
|
+
// change, checks out its head, asks the critical questions the code doesn't answer and decides
|
|
3
|
+
// whether anything blocks approval. It writes REVIEW.json next to its brief; nothing goes to
|
|
4
|
+
// GitHub until you tick what to send and post it as a pending review under your name. When the
|
|
5
|
+
// author pushes, the reviewer re-checks its earlier blockers.
|
|
6
|
+
|
|
7
|
+
import fs from 'node:fs';
|
|
8
|
+
import path from 'node:path';
|
|
9
|
+
import { briefDir } from './brief.js';
|
|
10
|
+
import { run } from './git.js';
|
|
11
|
+
import { ghBin } from './tracker.js';
|
|
12
|
+
|
|
13
|
+
export const REVIEW_FILE = 'REVIEW.json';
|
|
14
|
+
export const reviewPath = (agentId) => path.join(briefDir(agentId), REVIEW_FILE);
|
|
15
|
+
|
|
16
|
+
const PR_URL = /^<?(https?:\/\/[\w.-]+\/([\w.-]+)\/([\w.-]+)\/pull\/(\d+))/;
|
|
17
|
+
const VERDICTS = ['approve', 'approve_with_nits', 'blocked'];
|
|
18
|
+
export const VERDICT_LABEL = { approve: 'Approve', approve_with_nits: 'Approve with nits', blocked: 'Blocked' };
|
|
19
|
+
const CATEGORIES = ['correctness', 'security', 'data', 'breaking', 'tests', 'performance', 'design', 'other'];
|
|
20
|
+
const err = (status, message) => Object.assign(new Error(message), { status });
|
|
21
|
+
const clip = (s, n) => {
|
|
22
|
+
const t = String(s ?? '').trim();
|
|
23
|
+
return t.length > n ? `${t.slice(0, n - 1)}…` : t;
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
/** A pull request link -> { url, owner, repo, number, slug: "owner/repo" }, or null. */
|
|
27
|
+
export function parsePrUrl(text) {
|
|
28
|
+
const m = String(text ?? '').trim().match(PR_URL);
|
|
29
|
+
if (!m) return null;
|
|
30
|
+
return { url: m[1], owner: m[2], repo: m[3], number: Number(m[4]), slug: `${m[2]}/${m[3]}` };
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** The reviewer's instructions: read-only, the review in `file` as JSON. */
|
|
34
|
+
export function reviewerPrompt(file, pr) {
|
|
35
|
+
return [
|
|
36
|
+
`You are reviewing someone else's pull request for the user, who is a requested reviewer on it: ${pr.url}. You don't change it.`,
|
|
37
|
+
`Getting the code: in your folder, run "git fetch origin pull/${pr.number}/head:review/pr-${pr.number}" and "git checkout review/pr-${pr.number}" (fetch again after new pushes). ` +
|
|
38
|
+
`Read the description and discussion (gh pr view ${pr.url} --comments), the diff (gh pr diff ${pr.url}), and as much of the surrounding code as you need to understand what the change touches: callers, tests, config, migrations. ` +
|
|
39
|
+
'Read the linked issue or design doc if there is one. You may build and run the tests.',
|
|
40
|
+
'Never commit, push, edit the pull request, approve, request changes or comment on GitHub: the user decides and posts. Don\'t change files in the repository except to run the tests.',
|
|
41
|
+
'Be critical, like a careful senior reviewer. For each concern, reason it through against the code before you write it down: is it real, how would it fail, who would notice? ' +
|
|
42
|
+
'A blocker is something that should stop approval: a bug, a security or data-loss risk, a breaking change without a migration, a missing test for risky logic, or a change that doesn\'t do what the PR says. Style and taste are nits, never blockers. ' +
|
|
43
|
+
'Questions are what the code and description don\'t answer and the author should: intent, edge cases, rollout and rollback, why this approach.',
|
|
44
|
+
`Write the review to ${file} as JSON, and keep it current:\n` +
|
|
45
|
+
'{\n' +
|
|
46
|
+
` "pr": "${pr.url}",\n` +
|
|
47
|
+
' "headSha": "<the commit you reviewed: git rev-parse HEAD>",\n' +
|
|
48
|
+
' "verdict": "approve" | "approve_with_nits" | "blocked",\n' +
|
|
49
|
+
' "why": "<one or two sentences: why that verdict>",\n' +
|
|
50
|
+
' "summary": "<what the change does, in two or three sentences>",\n' +
|
|
51
|
+
' "blockers": [{ "id": "b1", "title": "<short>", "file": "<path>", "line": <line in the new file, or null>, "category": "correctness|security|data|breaking|tests|performance|design|other", "why": "<how it fails, with evidence from the code>", "unblock": "<what would resolve it>", "status": "open" | "resolved" }],\n' +
|
|
52
|
+
' "questions": [{ "id": "q1", "question": "<for the author>", "why": "<why it matters>", "file": "<path or null>", "line": <line or null> }],\n' +
|
|
53
|
+
' "risks": ["<risk that isn\'t a blocker>"],\n' +
|
|
54
|
+
' "testGaps": ["<behaviour with no test>"],\n' +
|
|
55
|
+
' "nits": [{ "id": "n1", "text": "<minor>", "file": "<path or null>", "line": <line or null> }],\n' +
|
|
56
|
+
' "tests": "<what you ran and the result, or why you didn\'t>"\n' +
|
|
57
|
+
'}\n' +
|
|
58
|
+
'Every blocker has a verdict of "blocked" behind it; with no open blockers the verdict is approve or approve_with_nits. Lines are lines of the new file that the diff touches, so they can carry a comment.',
|
|
59
|
+
`When a message says the author pushed, fetch again, re-check each blocker (mark it "resolved" when the new code fixes it, and say how in "why"), review what changed, update headSha and the verdict, and rewrite ${file}.`,
|
|
60
|
+
'Finish each pass with your status as done in the brief and the verdict in one line.',
|
|
61
|
+
].join('\n\n');
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const list = (xs, n, f) => (Array.isArray(xs) ? xs : []).slice(0, n).map(f).filter(Boolean);
|
|
65
|
+
const lineOf = (v) => (Number.isInteger(v) && v > 0 ? v : null);
|
|
66
|
+
|
|
67
|
+
/** REVIEW.json, cleaned up: unknown values dropped, ids filled in, lengths capped. */
|
|
68
|
+
export function normalizeReview(raw) {
|
|
69
|
+
if (!raw || typeof raw !== 'object') return null;
|
|
70
|
+
const blockers = list(raw.blockers, 30, (b, i) =>
|
|
71
|
+
b?.title || b?.why
|
|
72
|
+
? {
|
|
73
|
+
id: String(b.id || `b${i + 1}`),
|
|
74
|
+
title: clip(b.title || b.why, 200),
|
|
75
|
+
file: b.file ? clip(b.file, 300) : null,
|
|
76
|
+
line: lineOf(b.line),
|
|
77
|
+
category: CATEGORIES.includes(b.category) ? b.category : 'other',
|
|
78
|
+
why: clip(b.why, 2000),
|
|
79
|
+
unblock: clip(b.unblock, 1000),
|
|
80
|
+
status: b.status === 'resolved' ? 'resolved' : 'open',
|
|
81
|
+
}
|
|
82
|
+
: null,
|
|
83
|
+
);
|
|
84
|
+
const open = blockers.filter((b) => b.status === 'open').length;
|
|
85
|
+
let verdict = VERDICTS.includes(raw.verdict) ? raw.verdict : open ? 'blocked' : null;
|
|
86
|
+
// An open blocker always blocks, whatever the verdict says.
|
|
87
|
+
if (open && verdict !== 'blocked') verdict = 'blocked';
|
|
88
|
+
return {
|
|
89
|
+
pr: raw.pr ? String(raw.pr) : null,
|
|
90
|
+
headSha: /^[0-9a-f]{7,40}$/i.test(raw.headSha ?? '') ? raw.headSha : null,
|
|
91
|
+
verdict,
|
|
92
|
+
why: clip(raw.why, 1000),
|
|
93
|
+
summary: clip(raw.summary, 1500),
|
|
94
|
+
blockers,
|
|
95
|
+
questions: list(raw.questions, 30, (q, i) =>
|
|
96
|
+
q?.question ? { id: String(q.id || `q${i + 1}`), question: clip(q.question, 1000), why: clip(q.why, 1000), file: q.file ? clip(q.file, 300) : null, line: lineOf(q.line) } : null,
|
|
97
|
+
),
|
|
98
|
+
risks: list(raw.risks, 20, (r) => (r ? clip(r, 600) : null)),
|
|
99
|
+
testGaps: list(raw.testGaps, 20, (r) => (r ? clip(r, 600) : null)),
|
|
100
|
+
nits: list(raw.nits, 40, (n, i) => (n?.text ? { id: String(n.id || `n${i + 1}`), text: clip(n.text, 600), file: n.file ? clip(n.file, 300) : null, line: lineOf(n.line) } : null)),
|
|
101
|
+
tests: clip(raw.tests, 1000),
|
|
102
|
+
openBlockers: open,
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** The reviewer's REVIEW.json: { review, updatedAt } or null (missing or not JSON yet). */
|
|
107
|
+
export function readReview(agentId) {
|
|
108
|
+
try {
|
|
109
|
+
const file = reviewPath(agentId);
|
|
110
|
+
const st = fs.statSync(file);
|
|
111
|
+
const text = fs.readFileSync(file, 'utf8');
|
|
112
|
+
// Tolerate a fenced block or text around the object.
|
|
113
|
+
const json = text.slice(text.indexOf('{'), text.lastIndexOf('}') + 1);
|
|
114
|
+
const review = normalizeReview(JSON.parse(json));
|
|
115
|
+
return review ? { review, updatedAt: st.mtime.toISOString() } : null;
|
|
116
|
+
} catch {
|
|
117
|
+
return null;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** What to tell a reviewer when the author pushed. */
|
|
122
|
+
export const recheckMessage = (pr, head) =>
|
|
123
|
+
`The author pushed new commits to ${pr.url} (head ${String(head).slice(0, 12)}). Fetch them, re-check each blocker (resolved or still open), review what changed, and update the review.`;
|
|
124
|
+
|
|
125
|
+
const where = (x) => (x.file ? `\`${x.file}${x.line ? `:${x.line}` : ''}\`` : '');
|
|
126
|
+
|
|
127
|
+
/** Each item you can send, by id: what it says as a comment. */
|
|
128
|
+
function items(review) {
|
|
129
|
+
const out = [];
|
|
130
|
+
for (const b of review.blockers.filter((x) => x.status === 'open')) {
|
|
131
|
+
out.push({ id: b.id, kind: 'blocker', file: b.file, line: b.line, text: `**Blocker: ${b.title}**\n\n${b.why}${b.unblock ? `\n\nTo resolve: ${b.unblock}` : ''}` });
|
|
132
|
+
}
|
|
133
|
+
for (const q of review.questions) out.push({ id: q.id, kind: 'question', file: q.file, line: q.line, text: `**Question:** ${q.question}${q.why ? `\n\n${q.why}` : ''}` });
|
|
134
|
+
for (const n of review.nits) out.push({ id: n.id, kind: 'nit', file: n.file, line: n.line, text: `Nit: ${n.text}` });
|
|
135
|
+
return out;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* The review as you'd send it: the picked items (all open blockers and questions when `ids` is
|
|
140
|
+
* not given). Comments with a file and line go on those lines; the rest go in the body.
|
|
141
|
+
*/
|
|
142
|
+
export function reviewDraft(review, ids = null) {
|
|
143
|
+
const all = items(review);
|
|
144
|
+
const want = ids ? new Set(ids) : null;
|
|
145
|
+
const picked = all.filter((i) => (want ? want.has(i.id) : i.kind !== 'nit'));
|
|
146
|
+
const inline = picked.filter((i) => i.file && i.line);
|
|
147
|
+
const general = picked.filter((i) => !(i.file && i.line));
|
|
148
|
+
const head = review.openBlockers ? `${review.openBlockers} thing${review.openBlockers === 1 ? '' : 's'} to resolve before this can be approved.` : '';
|
|
149
|
+
const body = [head, ...general.map((i) => `${i.text.replace(/\n\n/g, '\n')}${i.file ? `\n(${where(i)})` : ''}`)].filter(Boolean).join('\n\n');
|
|
150
|
+
return { body, comments: inline.map((i) => ({ path: i.file, line: i.line, side: 'RIGHT', body: i.text })), picked: picked.map((i) => i.id) };
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** The whole review as Markdown, to read or paste. */
|
|
154
|
+
export function reviewMarkdown(row) {
|
|
155
|
+
const r = row.review;
|
|
156
|
+
const head = `## Review of ${row.pr.title ? `${row.pr.title} ` : ''}(${row.pr.url})`;
|
|
157
|
+
if (!r) return `${head}\n\nThe reviewer is still reading the change.`;
|
|
158
|
+
const sec = (title, xs) => (xs.length ? `### ${title}\n${xs.join('\n')}` : null);
|
|
159
|
+
return [
|
|
160
|
+
head,
|
|
161
|
+
`**${VERDICT_LABEL[r.verdict] ?? 'No verdict yet'}**${r.why ? `: ${r.why}` : ''}`,
|
|
162
|
+
r.summary,
|
|
163
|
+
sec('Blockers', r.blockers.map((b) => `- ${b.status === 'resolved' ? '~~' : ''}**${b.title}**${b.status === 'resolved' ? '~~ (resolved)' : ''} ${where(b)} (${b.category})\n ${b.why}${b.unblock ? `\n To resolve: ${b.unblock}` : ''}`)),
|
|
164
|
+
sec('Questions for the author', r.questions.map((q) => `- ${q.question} ${where(q)}${q.why ? `\n ${q.why}` : ''}`)),
|
|
165
|
+
sec('Risks', r.risks.map((x) => `- ${x}`)),
|
|
166
|
+
sec('Test gaps', r.testGaps.map((x) => `- ${x}`)),
|
|
167
|
+
sec('Nits', r.nits.map((n) => `- ${n.text} ${where(n)}`)),
|
|
168
|
+
r.tests ? `### Tests\n${r.tests}` : null,
|
|
169
|
+
]
|
|
170
|
+
.filter(Boolean)
|
|
171
|
+
.join('\n\n');
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** One row per reviewer agent, then requested PRs that have none (newest first). */
|
|
175
|
+
export function reviewRows(views, requested = [], read = readReview) {
|
|
176
|
+
const rows = [];
|
|
177
|
+
const taken = new Set();
|
|
178
|
+
for (const v of views) {
|
|
179
|
+
if (!v.reviewing) continue;
|
|
180
|
+
const pr = (v.prs ?? []).find((p) => p.url === v.reviewing.url) ?? {};
|
|
181
|
+
const got = read(v.id);
|
|
182
|
+
const review = got?.review ?? null;
|
|
183
|
+
taken.add(v.reviewing.url);
|
|
184
|
+
const head = pr.head ?? null;
|
|
185
|
+
rows.push({
|
|
186
|
+
pr: { url: v.reviewing.url, repo: v.reviewing.slug, number: v.reviewing.number, title: pr.title ?? v.reviewing.title ?? null, state: pr.state ?? null, isDraft: Boolean(pr.isDraft), checks: pr.checks ?? null, head },
|
|
187
|
+
agent: { id: v.id, name: v.name, running: Boolean(v.runtime?.running), busy: Boolean(v.runtime?.busy) },
|
|
188
|
+
review,
|
|
189
|
+
updatedAt: got?.updatedAt ?? v.createdAt ?? null,
|
|
190
|
+
// The author pushed since this review was written.
|
|
191
|
+
stale: Boolean(review?.headSha && head && !head.startsWith(review.headSha) && !review.headSha.startsWith(head)),
|
|
192
|
+
posted: v.reviewing.posted ?? null,
|
|
193
|
+
status: !review ? (v.runtime?.busy || v.status === 'preparing' ? 'reviewing' : 'no review') : review.verdict ?? 'reviewing',
|
|
194
|
+
});
|
|
195
|
+
}
|
|
196
|
+
for (const p of requested) {
|
|
197
|
+
if (taken.has(p.url)) continue;
|
|
198
|
+
rows.push({ pr: { url: p.url, repo: p.repo, number: p.number, title: p.title ?? null, state: 'OPEN', author: p.author ?? null }, agent: null, review: null, updatedAt: p.updatedAt ?? null, stale: false, posted: null, status: 'requested' });
|
|
199
|
+
}
|
|
200
|
+
const rank = { requested: 0, blocked: 1, approve_with_nits: 2, approve: 3, reviewing: 4, 'no review': 5 };
|
|
201
|
+
return rows.sort((a, b) => Number(b.stale) - Number(a.stale) || (rank[a.status] ?? 9) - (rank[b.status] ?? 9) || String(b.updatedAt ?? '').localeCompare(String(a.updatedAt ?? '')));
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** PRs where your review is requested, from GitHub: [{ url, repo, number, title, author, updatedAt }]. */
|
|
205
|
+
export async function requestedReviews() {
|
|
206
|
+
if (process.env.AGENTMGR_NO_GH) return [];
|
|
207
|
+
try {
|
|
208
|
+
const out = await run(ghBin(), ['search', 'prs', '--review-requested=@me', '--state=open', '--limit', '50', '--json', 'url,title,repository,author,updatedAt,number'], { timeout: 30_000 });
|
|
209
|
+
return JSON.parse(out || '[]').map((p) => ({ url: p.url, repo: p.repository?.nameWithOwner ?? parsePrUrl(p.url)?.slug ?? null, number: p.number, title: p.title, author: p.author?.login ?? null, updatedAt: p.updatedAt }));
|
|
210
|
+
} catch {
|
|
211
|
+
return [];
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
export class Reviews {
|
|
216
|
+
constructor({ manager, store, log = () => {} }) {
|
|
217
|
+
this.manager = manager;
|
|
218
|
+
this.store = store;
|
|
219
|
+
this.log = log;
|
|
220
|
+
this.requested = { at: 0, list: [] };
|
|
221
|
+
this.onPrs = (agent) => this.recheck(agent);
|
|
222
|
+
manager.on('prs', this.onPrs);
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
close() {
|
|
226
|
+
this.manager.off('prs', this.onPrs);
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/** The reviewer agent for a PR, if there is one. */
|
|
230
|
+
agentFor(url) {
|
|
231
|
+
return this.store.list().find((a) => a.reviewing?.url === url) ?? null;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/** The project whose repository is the PR's, else its GitHub URL. */
|
|
235
|
+
where(pr, project) {
|
|
236
|
+
if (project) {
|
|
237
|
+
const p = String(project).replace(/^@/, '');
|
|
238
|
+
if (!this.manager.resolveProject(p)) throw err(400, `No project @${p}; see agentmgr project ls`);
|
|
239
|
+
return { project: p };
|
|
240
|
+
}
|
|
241
|
+
const slug = pr.slug.toLowerCase();
|
|
242
|
+
const match = this.manager.listProjects().find((p) => {
|
|
243
|
+
const repo = String(p.repo ?? '').toLowerCase().replace(/\.git$/, '');
|
|
244
|
+
return repo.endsWith(`/${slug}`) || repo.endsWith(`:${slug}`) || String(p.key ?? '').endsWith(`/${slug}`);
|
|
245
|
+
});
|
|
246
|
+
return match ? { project: match.shortcut } : { repo: `https://github.com/${pr.slug}.git` };
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/** Start a reviewer for a PR link. */
|
|
250
|
+
start({ url, project = null, startedBy = null, notes = '' } = {}) {
|
|
251
|
+
const pr = parsePrUrl(url);
|
|
252
|
+
if (!pr) throw err(400, 'Give a pull request link (https://github.com/<owner>/<repo>/pull/<number>)');
|
|
253
|
+
const prev = this.agentFor(pr.url);
|
|
254
|
+
if (prev) throw err(409, `${prev.name} (${prev.id}) already reviews ${pr.url}`);
|
|
255
|
+
const title = this.requested.list.find((p) => p.url === pr.url)?.title ?? null;
|
|
256
|
+
const intent = `Review ${pr.url}${title ? `: ${title}` : ''}${notes ? `\n\n${String(notes).trim()}` : ''}`;
|
|
257
|
+
return this.manager.create({
|
|
258
|
+
...this.where(pr, project),
|
|
259
|
+
intent,
|
|
260
|
+
name: `review-${pr.repo}-${pr.number}`.toLowerCase(),
|
|
261
|
+
reviewing: { url: pr.url, slug: pr.slug, number: pr.number, title },
|
|
262
|
+
...(startedBy ? { startedBy } : {}),
|
|
263
|
+
});
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/** Requested PRs, refreshed at most once a minute. */
|
|
267
|
+
async requestedList({ fresh = false } = {}) {
|
|
268
|
+
if (fresh || Date.now() - this.requested.at > 60_000) this.requested = { at: Date.now(), list: await requestedReviews() };
|
|
269
|
+
return this.requested.list;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
async rows({ fresh = false } = {}) {
|
|
273
|
+
const views = this.store.list().filter((a) => a.reviewing).map((a) => this.manager.view(a));
|
|
274
|
+
const skip = new Set(this.store.data.reviewsDismissed ?? []);
|
|
275
|
+
return reviewRows(views, (await this.requestedList({ fresh })).filter((p) => !skip.has(p.url)));
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/** Requested PRs you won't have an agent review: off the list. */
|
|
279
|
+
dismiss(urls = []) {
|
|
280
|
+
const list = (this.store.data.reviewsDismissed ??= []);
|
|
281
|
+
let n = 0;
|
|
282
|
+
for (const u of urls.map((x) => parsePrUrl(x)?.url).filter(Boolean)) {
|
|
283
|
+
if (!list.includes(u)) {
|
|
284
|
+
list.push(u);
|
|
285
|
+
n += 1;
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
if (list.length > 300) list.splice(0, list.length - 300);
|
|
289
|
+
this.store.save();
|
|
290
|
+
return { dismissed: n };
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
row(ref) {
|
|
294
|
+
const a = this.manager.mustGet(ref);
|
|
295
|
+
if (!a.reviewing) throw err(400, `${a.name} isn't reviewing a pull request`);
|
|
296
|
+
return reviewRows([this.manager.view(a)])[0];
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/** After the author pushes: tell the reviewer once per new head. */
|
|
300
|
+
recheck(agent) {
|
|
301
|
+
if (!agent?.reviewing) return;
|
|
302
|
+
const pr = agent.prs?.[agent.reviewing.url];
|
|
303
|
+
const got = readReview(agent.id);
|
|
304
|
+
if (!pr?.head || pr.state !== 'OPEN' || !got?.review?.headSha) return;
|
|
305
|
+
const reviewed = got.review.headSha;
|
|
306
|
+
if (pr.head.startsWith(reviewed) || reviewed.startsWith(pr.head)) return;
|
|
307
|
+
if (agent.reviewing.recheckedFor === pr.head) return;
|
|
308
|
+
this.manager.patch(agent.id, { reviewing: { ...agent.reviewing, recheckedFor: pr.head } });
|
|
309
|
+
try {
|
|
310
|
+
this.manager.tell(agent.id, recheckMessage(pr, pr.head), { source: 'reviews' });
|
|
311
|
+
this.log(`review: ${agent.name}: author pushed ${pr.head.slice(0, 7)}, re-checking`);
|
|
312
|
+
} catch {}
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
/**
|
|
316
|
+
* Post the picked items as a pending review on GitHub, under your name: you finish and submit it
|
|
317
|
+
* there. A line GitHub can't comment on goes in the body instead.
|
|
318
|
+
*/
|
|
319
|
+
async post(ref, { ids = null } = {}) {
|
|
320
|
+
const a = this.manager.mustGet(ref);
|
|
321
|
+
if (!a.reviewing) throw err(400, `${a.name} isn't reviewing a pull request`);
|
|
322
|
+
const got = readReview(a.id);
|
|
323
|
+
if (!got) throw err(409, 'No review written yet');
|
|
324
|
+
const draft = reviewDraft(got.review, ids);
|
|
325
|
+
if (!draft.picked.length) throw err(400, 'Pick at least one blocker, question or nit to send');
|
|
326
|
+
if (process.env.AGENTMGR_NO_GH) throw err(503, 'GitHub is off (AGENTMGR_NO_GH)');
|
|
327
|
+
const { slug, number } = a.reviewing;
|
|
328
|
+
// gh reads the payload from a file: comments with lines need real JSON, not -f fields.
|
|
329
|
+
const file = path.join(briefDir(a.id), 'review-post.json');
|
|
330
|
+
const send = async (payload) => {
|
|
331
|
+
fs.writeFileSync(file, JSON.stringify(payload));
|
|
332
|
+
try {
|
|
333
|
+
const out = await run(ghBin(), ['api', '-X', 'POST', `repos/${slug}/pulls/${number}/reviews`, '--input', file], { timeout: 30_000 });
|
|
334
|
+
return JSON.parse(out || '{}');
|
|
335
|
+
} finally {
|
|
336
|
+
fs.rmSync(file, { force: true });
|
|
337
|
+
}
|
|
338
|
+
};
|
|
339
|
+
const base = { ...(got.review.headSha ? { commit_id: got.review.headSha } : {}), body: draft.body || ' ' };
|
|
340
|
+
let res;
|
|
341
|
+
let moved = 0;
|
|
342
|
+
try {
|
|
343
|
+
res = await send({ ...base, comments: draft.comments });
|
|
344
|
+
} catch (e) {
|
|
345
|
+
// 422: a line outside the diff. Put those comments in the body instead.
|
|
346
|
+
if (!/422|Unprocessable|line/i.test(e.message) || !draft.comments.length) throw err(502, `GitHub refused the review: ${clip(e.message, 300)}`);
|
|
347
|
+
moved = draft.comments.length;
|
|
348
|
+
const extra = draft.comments.map((c) => `${c.body.replace(/\n\n/g, '\n')}\n(\`${c.path}:${c.line}\`)`);
|
|
349
|
+
try {
|
|
350
|
+
res = await send({ ...base, body: [draft.body, ...extra].filter(Boolean).join('\n\n') });
|
|
351
|
+
} catch (e2) {
|
|
352
|
+
throw err(502, `GitHub refused the review: ${clip(e2.message, 300)}`);
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
const posted = { at: new Date().toISOString(), url: res.html_url ?? `${a.reviewing.url}/files`, ids: draft.picked, moved };
|
|
356
|
+
this.manager.patch(a.id, { reviewing: { ...a.reviewing, posted } });
|
|
357
|
+
return posted;
|
|
358
|
+
}
|
|
359
|
+
}
|