ai-agentmanager 1.22.0 → 1.24.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/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
+ }
package/src/server.js CHANGED
@@ -41,6 +41,7 @@ import * as service from './service.js';
41
41
  import { jiraView, saveJira } from './jira.js';
42
42
  import { ProposedIssues, issuesMarkdown } from './issues.js';
43
43
  import { designsMarkdown } from './designs.js';
44
+ import { Reviews, reviewDraft, reviewMarkdown } from './reviews.js';
44
45
  import { CONTAINER_ENGINES, buildImage, claudeToken, dockerStatus, isBuilding, saveSecrets } from './container.js';
45
46
  import { AgentkitReports } from './agentkit-reports.js';
46
47
  import { Builder } from './builder.js';
@@ -91,6 +92,7 @@ export async function startServer({ port = PORT, host = HOST } = {}) {
91
92
  const manager = new AgentManager({ store, config, plugins });
92
93
  const backlog = new Backlog({ manager, store, config });
93
94
  const proposed = new ProposedIssues({ store, manager });
95
+ const reviews = new Reviews({ manager, store, log: (m) => console.log(`[agentmgr] ${m}`) });
94
96
  const races = new Races({ manager, store });
95
97
  const review = new Review({ manager });
96
98
  // The walkthrough explains the same diff the review screen shows.
@@ -295,6 +297,7 @@ export async function startServer({ port = PORT, host = HOST } = {}) {
295
297
  const list = (Array.isArray(intents) ? intents : [intent]).map((i) => String(i ?? '').trim()).filter(Boolean);
296
298
  // Agents the assistant's own session starts: its limits apply, and they are marked as its.
297
299
  const extra = assistant.admit(req.headers['x-agentmgr-agent'], list, opts);
300
+ if (extra.startedBy) proposed.refuseSetAside(list);
298
301
  const created = manager.createMany(list, { ...opts, ...extra });
299
302
  if (!extra.startedBy) repeats.record(created.map((a) => ({ text: a.intent, projectKey: projectOf(store.get(a.id) ?? a).key })));
300
303
  if (extra.startedBy) {
@@ -784,15 +787,20 @@ export async function startServer({ port = PORT, host = HOST } = {}) {
784
787
  api.get('/codemap', wrap((req) => manager.codeMap(req.query.project ? String(req.query.project) : null)));
785
788
  // Issues agents work on, for the summary; ?group=you|agent|done and ?format=markdown to paste.
786
789
  api.get('/issues', wrap(async (req) => {
787
- const v = await manager.issues(proposed.waiting());
790
+ // ?fresh=1 (the ↻ button) asks Jira again for the issues assigned to you.
791
+ if (req.query.fresh === '1') manager.assignedAt = 0;
792
+ const v = await manager.issues(proposed.listed(), proposed.actions);
788
793
  const group = req.query.group ? String(req.query.group) : null;
789
- const rows = group && group !== 'all' ? v.rows.filter((r) => r.group === group) : v.rows;
794
+ // "all" is everything still on the list: removed ones only when asked for.
795
+ const rows = !group ? v.rows : group === 'all' ? v.rows.filter((r) => r.group !== 'removed') : v.rows.filter((r) => r.group === group);
790
796
  return req.query.format === 'markdown' ? { markdown: issuesMarkdown(rows) } : { ...v, rows };
791
797
  }));
792
798
  // Issues proposed for agents (the assistant, when you pick): start the ticked ones, or dismiss them.
793
799
  api.post('/issues/proposed', wrap((req) => proposed.add({ ...req.body, by: req.headers['x-agentmgr-agent'] ? 'assistant' : 'you' })));
794
800
  api.post('/issues/start', wrap((req) => proposed.start(Array.isArray(req.body?.keys) ? req.body.keys.map(String) : [])));
795
801
  api.post('/issues/dismiss', wrap((req) => proposed.dismiss(Array.isArray(req.body?.keys) ? req.body.keys.map(String) : [])));
802
+ // Your action on issues: assign (starts an agent from the proposal), skip, done, remove, or null to clear.
803
+ api.post('/issues/action', wrap((req) => proposed.setAction(Array.isArray(req.body?.keys) ? req.body.keys.map(String) : [], req.body?.action ?? null)));
796
804
  // Design docs of all agents; the same ?group= and ?format=markdown.
797
805
  api.get('/designs', wrap((req) => {
798
806
  const v = manager.designs();
@@ -803,6 +811,22 @@ export async function startServer({ port = PORT, host = HOST } = {}) {
803
811
  .filter((r) => !q || [r.title, r.summary, r.agent.name, r.agent.project, r.issue?.key].some((s) => String(s ?? '').toLowerCase().includes(q)));
804
812
  return req.query.format === 'markdown' ? { markdown: designsMarkdown(rows) } : { rows };
805
813
  }));
814
+ // Reviews: reviewer agents on other people's PRs, and PRs where your review is requested.
815
+ api.get('/reviews', wrap(async (req) => {
816
+ const rows = await reviews.rows({ fresh: req.query.fresh === '1' });
817
+ return req.query.format === 'markdown' ? { markdown: rows.filter((r) => r.agent).map(reviewMarkdown).join('\n\n---\n\n') || 'No reviews.' } : { rows };
818
+ }));
819
+ api.post('/reviews', wrap((req) => {
820
+ // Started by the assistant's own session: its limits apply, and it's marked as its.
821
+ const extra = assistant.admit(req.headers['x-agentmgr-agent'], [String(req.body?.url ?? '')]);
822
+ return reviews.start({ url: req.body?.url, project: req.body?.project, notes: req.body?.notes, startedBy: extra.startedBy ?? null });
823
+ }));
824
+ api.post('/reviews/dismiss', wrap((req) => reviews.dismiss(Array.isArray(req.body?.urls) ? req.body.urls.map(String) : [])));
825
+ api.get('/reviews/:id', wrap((req) => {
826
+ const row = reviews.row(req.params.id);
827
+ return { ...row, markdown: reviewMarkdown(row), draft: row.review ? reviewDraft(row.review) : null };
828
+ }));
829
+ api.post('/reviews/:id/post', wrap((req) => reviews.post(req.params.id, { ids: Array.isArray(req.body?.ids) ? req.body.ids.map(String) : null })));
806
830
  // Value: totals by period, items with estimates you can correct, reports.
807
831
  api.get('/value', wrap((req) => value.view({ period: String(req.query.period ?? 'week') })));
808
832
  api.put('/value', wrap((req) => {
@@ -1230,6 +1254,7 @@ export async function startServer({ port = PORT, host = HOST } = {}) {
1230
1254
  landing.close();
1231
1255
  standup.close();
1232
1256
  value.close();
1257
+ reviews.close();
1233
1258
  autopilot.close();
1234
1259
  goals.close();
1235
1260
  worklog.close();