@mmerterden/multi-agent-pipeline 21.0.0 → 21.1.1

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.
Files changed (54) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/README.md +8 -6
  3. package/README.tr.md +8 -6
  4. package/docs/architecture.md +3 -3
  5. package/docs/ecosystem.md +12 -12
  6. package/docs/facts.json +10 -9
  7. package/docs/features.md +1 -1
  8. package/install/claude.mjs +8 -1
  9. package/install/templates/claude-hooks.json +12 -1
  10. package/manifest.json +57 -41
  11. package/package.json +1 -1
  12. package/pipeline/agents/plan-critic.md +1 -1
  13. package/pipeline/commands/multi-agent/address-review/SKILL.md +183 -0
  14. package/pipeline/commands/multi-agent/sync/SKILL.md +3 -3
  15. package/pipeline/commands/multi-agent/update/SKILL.md +6 -4
  16. package/pipeline/multi-agent-refs/cross-cli-contract.md +4 -4
  17. package/pipeline/multi-agent-refs/features/approach-choice.md +61 -0
  18. package/pipeline/multi-agent-refs/features/root-cause.md +98 -0
  19. package/pipeline/multi-agent-refs/features/usage-reporting.md +1 -1
  20. package/pipeline/multi-agent-refs/features/visual-evidence.md +14 -0
  21. package/pipeline/multi-agent-refs/help/en.md +3 -2
  22. package/pipeline/multi-agent-refs/help/tr.md +3 -2
  23. package/pipeline/multi-agent-refs/phases/phase-1-plan.md +6 -4
  24. package/pipeline/multi-agent-refs/phases/phase-2-dev.md +2 -0
  25. package/pipeline/office/toolkit.json +1 -1
  26. package/pipeline/rules/debugging.md +10 -7
  27. package/pipeline/rules/outside-the-pipeline.md +1 -1
  28. package/pipeline/rules/tdd.md +4 -7
  29. package/pipeline/schemas/agent-state.schema.json +91 -0
  30. package/pipeline/schemas/prefs.schema.json +13 -1
  31. package/pipeline/schemas/toolkit-path-params.json +79 -1
  32. package/pipeline/scripts/_stack-routing.mjs +2 -0
  33. package/pipeline/scripts/approach-choice.mjs +232 -0
  34. package/pipeline/scripts/gate-ledger.mjs +30 -1
  35. package/pipeline/scripts/pr-threads.mjs +537 -0
  36. package/pipeline/scripts/pr-write-guard.mjs +139 -0
  37. package/pipeline/scripts/pr-write-guard.sh +34 -0
  38. package/pipeline/scripts/root-cause-gate.mjs +354 -0
  39. package/pipeline/skills/.skill-manifest.json +17 -5
  40. package/pipeline/skills/.skills-index.json +35 -2
  41. package/pipeline/skills/shared/README.md +8 -5
  42. package/pipeline/skills/shared/core/multi-agent-address-review/SKILL.md +44 -0
  43. package/pipeline/skills/shared/core/multi-agent-sync/SKILL.md +3 -3
  44. package/pipeline/skills/shared/core/multi-agent-update/SKILL.md +6 -4
  45. package/pipeline/skills/shared/external/humanizer/SKILL.md +48 -6
  46. package/pipeline/skills/shared/external/humanizer/evals/evals.json +13 -0
  47. package/pipeline/skills/shared/external/humanizer/references/turkish.md +88 -0
  48. package/pipeline/skills/shared/external/store-screenshots/SKILL.md +252 -0
  49. package/pipeline/skills/shared/external/store-screenshots/evals/evals.json +47 -0
  50. package/pipeline/skills/shared/external/thesis-writing/SKILL.md +140 -0
  51. package/pipeline/skills/shared/external/thesis-writing/evals/evals.json +40 -0
  52. package/pipeline/skills/shared/external/thesis-writing/references/review-checklist.md +33 -0
  53. package/pipeline/skills/shared/external/thesis-writing/references/turkish-thesis-conventions.md +65 -0
  54. package/pipeline/skills/skills-index.md +4 -1
@@ -0,0 +1,537 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * @file pr-threads.mjs - the engine behind /multi-agent:address-review.
4
+ *
5
+ * Usage:
6
+ * pr-threads.mjs fetch --repo OWNER/NAME --pr N --out FILE
7
+ * pr-threads.mjs check --threads FILE --verdicts FILE --dir CHECKOUT [--json]
8
+ * pr-threads.mjs draft --threads FILE --verdicts FILE --out FILE
9
+ * pr-threads.mjs propose --threads FILE --action reply|resolve --thread ID [--body-file FILE]
10
+ * pr-threads.mjs propose --threads FILE --action push --dir CHECKOUT
11
+ * pr-threads.mjs apply (the same flags as propose) --confirm TOKEN
12
+ *
13
+ * `fetch` reads the review threads of one open pull request the viewer
14
+ * authored, through `gh api graphql`, and keeps the unresolved ones; resolved
15
+ * and outdated threads are counted, not returned for classification. A pull
16
+ * request that is closed, merged or someone else's is refused: this command
17
+ * answers review on our own work only.
18
+ *
19
+ * `check` holds the verdicts file to its contract: one verdict per open
20
+ * thread, a class of fix, pushback or question, a reason, a reply, and for fix
21
+ * and pushback at least one `file:line` anchor that resolves in the checkout
22
+ * (an optional quote must be on that line). A pushback reply cites a
23
+ * `file:line`; no reply opens with praise or agreement in place of substance.
24
+ *
25
+ * `propose` prints one GitHub write - a reply, a resolve or a push - exactly
26
+ * as it would be made, with a token computed from the live thread or branch.
27
+ * `apply` re-reads that state, refuses when the token no longer matches, and
28
+ * makes that one write. Both refuse when MULTI_AGENT_UNATTENDED=1: unattended
29
+ * runs end at `draft`. A push is never forced, goes only to the checkout's
30
+ * remote for the PR's head repository, and is refused for a fork's PR and
31
+ * for a head branch that is the repository's default branch or a protected
32
+ * name (main, master, develop, release/*).
33
+ *
34
+ * Every read of GitHub is live: there is no flag that substitutes a recorded
35
+ * response. Tests inject the GraphQL and git calls through `main()`.
36
+ *
37
+ * Exit: 0 done, 1 check failed or write refused, 2 usage error, 4 not an open
38
+ * pull request of the viewer, 5 refused unattended, 6 stale token.
39
+ *
40
+ * @module pipeline/scripts/pr-threads
41
+ */
42
+
43
+ import { createHash } from "node:crypto";
44
+ import { spawnSync } from "node:child_process";
45
+ import { mkdirSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
46
+ import { dirname } from "node:path";
47
+
48
+ import { ArgsError, parseArgs, unknownSubcommand } from "../lib/args.mjs";
49
+ import { invokedDirectly } from "../lib/invoked-directly.mjs";
50
+ import { isUnattended } from "../lib/unattended.mjs";
51
+ import { messages, outputLanguage } from "../lib/user-facing.mjs";
52
+ import { resolveOne } from "./verify-citations.mjs";
53
+
54
+ export const CLASSES = ["fix", "pushback", "question"];
55
+ export const ACTIONS = ["reply", "resolve", "push"];
56
+ const SUBCOMMANDS = ["fetch", "check", "draft", "propose", "apply"];
57
+ const CITATION = /[\w./-]+\.[\w]+:\d+/;
58
+
59
+ export const PERFORMATIVE = [
60
+ /^\s*(you'?re|you are)\s+(absolutely\s+|totally\s+|completely\s+)?right\b/i,
61
+ /^\s*(great|good|nice|excellent)\s+(catch|point|find|suggestion)\b/i,
62
+ /^\s*thanks?( you)?( so much)?( for)?\b/i,
63
+ /^\s*(kesinlikle|tamamen|çok)\s+haklısın(ız)?\b/i,
64
+ /^\s*haklısın(ız)?\b/i,
65
+ /^\s*(harika|güzel|süper)\s+(yakalama|tespit|öneri|nokta)\b/i,
66
+ /^\s*teşekkür(ler| ederim)\b/i,
67
+ ];
68
+
69
+ const QUERY = `query($owner:String!,$name:String!,$number:Int!){
70
+ viewer{login}
71
+ repository(owner:$owner,name:$name){
72
+ defaultBranchRef{name}
73
+ pullRequest(number:$number){
74
+ number url state headRefName headRefOid author{login} isCrossRepository
75
+ headRepository{nameWithOwner url sshUrl}
76
+ reviewThreads(first:100){
77
+ pageInfo{hasNextPage}
78
+ nodes{
79
+ id isResolved isOutdated path line originalLine
80
+ first:comments(first:1){nodes{id author{login} body url}}
81
+ recent:comments(last:50){
82
+ totalCount pageInfo{hasPreviousPage}
83
+ nodes{id author{login} body url}
84
+ }
85
+ }
86
+ }
87
+ }
88
+ }
89
+ }`;
90
+
91
+ const REPLY = `mutation($thread:ID!,$body:String!){
92
+ addPullRequestReviewThreadReply(input:{pullRequestReviewThreadId:$thread,body:$body}){comment{url}}
93
+ }`;
94
+ const RESOLVE = `mutation($thread:ID!){resolveReviewThread(input:{threadId:$thread}){thread{isResolved}}}`;
95
+
96
+ const TEXT = {
97
+ en: {
98
+ notOwn: (pr, who) => `PR #${pr} is authored by ${who}; address-review only answers our own PRs`,
99
+ notOpen: (pr, s) => `PR #${pr} is ${s.toLowerCase()}, not open`,
100
+ unattended: "refused: MULTI_AGENT_UNATTENDED=1 allows drafts only, never a GitHub write",
101
+ stale: "refused: the thread or branch changed since propose; propose again",
102
+ crossRepo: (r) =>
103
+ `refused: the PR's head is in ${r}, not in this repository; push to it by hand`,
104
+ noRemote: (r) => `refused: no git remote in --dir points at ${r}`,
105
+ protectedRef: (b) => `refused: ${b} is a protected branch; address-review never pushes to it`,
106
+ heading: (pr) => `# Review replies for PR #${pr} (draft, nothing posted)`,
107
+ classLabel: { fix: "Fix", pushback: "Push back", question: "Question" },
108
+ evidence: "Evidence",
109
+ reply: "Reply",
110
+ skipped: (r, o) => `Skipped: ${r} resolved, ${o} outdated.`,
111
+ willReply: (id) => `Reply on thread ${id}:`,
112
+ willResolve: (id) => `Resolve thread ${id}`,
113
+ willPush: (b, sha) => `Push ${sha.slice(0, 12)} to ${b} (no force)`,
114
+ done: "done",
115
+ },
116
+ tr: {
117
+ notOwn: (pr, who) =>
118
+ `PR #${pr} ${who} tarafından açılmış; address-review yalnızca kendi PR'larımızı yanıtlar`,
119
+ notOpen: (pr, s) => `PR #${pr} açık değil (${s.toLowerCase()})`,
120
+ unattended: "reddedildi: MULTI_AGENT_UNATTENDED=1 yalnızca taslağa izin verir, GitHub'a yazmaz",
121
+ stale: "reddedildi: thread ya da branch propose'dan sonra değişti; yeniden propose et",
122
+ crossRepo: (r) => `reddedildi: PR'ın head'i ${r} içinde, bu repoda değil; elle push et`,
123
+ noRemote: (r) => `reddedildi: --dir içinde ${r} adresini gösteren bir git remote yok`,
124
+ protectedRef: (b) => `reddedildi: ${b} korumalı bir branch; address-review oraya push etmez`,
125
+ heading: (pr) => `# PR #${pr} review cevapları (taslak, hiçbiri gönderilmedi)`,
126
+ classLabel: { fix: "Düzeltme", pushback: "İtiraz", question: "Soru" },
127
+ evidence: "Kanıt",
128
+ reply: "Cevap",
129
+ skipped: (r, o) => `Atlanan: ${r} çözülmüş, ${o} güncelliğini yitirmiş.`,
130
+ willReply: (id) => `${id} thread'ine cevap:`,
131
+ willResolve: (id) => `${id} thread'ini çözüldü olarak işaretle`,
132
+ willPush: (b, sha) => `${sha.slice(0, 12)} commit'ini ${b} branch'ine push et (force yok)`,
133
+ done: "tamam",
134
+ },
135
+ };
136
+
137
+ class UsageError extends Error {}
138
+ class RefusedError extends Error {
139
+ constructor(message, code) {
140
+ super(message);
141
+ this.code = code;
142
+ }
143
+ }
144
+
145
+ const sha = (s) => createHash("sha256").update(String(s)).digest("hex");
146
+ const readJson = (f) => JSON.parse(readFileSync(f, "utf8"));
147
+
148
+ function gh(args, env) {
149
+ const r = spawnSync("gh", args, { encoding: "utf8", env, timeout: 60_000 });
150
+ if (r.status !== 0) throw new Error(`gh ${args[0]} failed: ${(r.stderr || "").trim()}`);
151
+ return r.stdout;
152
+ }
153
+
154
+ function graphql(query, vars, env) {
155
+ const args = ["api", "graphql", "-f", `query=${query}`];
156
+ for (const [k, v] of Object.entries(vars)) {
157
+ args.push(typeof v === "number" ? "-F" : "-f", `${k}=${v}`);
158
+ }
159
+ const res = JSON.parse(gh(args, env));
160
+ if (Array.isArray(res?.errors) && res.errors.length) {
161
+ throw new Error(`GitHub GraphQL: ${res.errors.map((e) => e?.message ?? "error").join("; ")}`);
162
+ }
163
+ return res;
164
+ }
165
+
166
+ /**
167
+ * Normalize a GraphQL response into the threads document.
168
+ *
169
+ * @param {object} raw the `gh api graphql` response
170
+ * @param {string} repo OWNER/NAME
171
+ */
172
+ export function normalize(raw, repo) {
173
+ if (Array.isArray(raw?.errors) && raw.errors.length) {
174
+ throw new Error(`GitHub GraphQL: ${raw.errors.map((e) => e?.message ?? "error").join("; ")}`);
175
+ }
176
+ const data = raw?.data ?? raw;
177
+ const pr = data?.repository?.pullRequest;
178
+ if (!pr) throw new Error("no pull request in the response");
179
+ const viewer = data?.viewer?.login ?? null;
180
+ const nodes = pr.reviewThreads?.nodes ?? [];
181
+ const threads = [];
182
+ let resolved = 0;
183
+ let outdated = 0;
184
+ let longThreads = 0;
185
+ for (const t of nodes) {
186
+ if (t.isResolved) {
187
+ resolved++;
188
+ continue;
189
+ }
190
+ if (t.isOutdated) {
191
+ outdated++;
192
+ continue;
193
+ }
194
+ const shape = (c) => ({
195
+ id: c.id,
196
+ author: c.author?.login ?? null,
197
+ body: c.body ?? "",
198
+ url: c.url ?? null,
199
+ });
200
+ const recent = (t.recent?.nodes ?? t.comments?.nodes ?? []).map(shape);
201
+ const opening = (t.first?.nodes ?? []).map(shape)[0] ?? recent[0] ?? null;
202
+ const comments =
203
+ opening && !recent.some((c) => c.id === opening.id) ? [opening, ...recent] : recent;
204
+ if (t.recent?.pageInfo?.hasPreviousPage) longThreads++;
205
+ threads.push({
206
+ threadId: t.id,
207
+ path: t.path ?? null,
208
+ line: t.line ?? t.originalLine ?? null,
209
+ author: opening?.author ?? null,
210
+ body: opening?.body ?? "",
211
+ url: opening?.url ?? null,
212
+ lastCommentId: recent.at(-1)?.id ?? null,
213
+ commentCount: t.recent?.totalCount ?? comments.length,
214
+ comments,
215
+ });
216
+ }
217
+ return {
218
+ repo,
219
+ pr: pr.number,
220
+ url: pr.url,
221
+ state: pr.state,
222
+ author: pr.author?.login ?? null,
223
+ viewer,
224
+ headRef: pr.headRefName,
225
+ defaultBranch: data?.repository?.defaultBranchRef?.name ?? null,
226
+ headSha: pr.headRefOid,
227
+ headRepo: pr.headRepository?.nameWithOwner ?? null,
228
+ headRepoUrls: [pr.headRepository?.url, pr.headRepository?.sshUrl].filter(Boolean),
229
+ isCrossRepository: pr.isCrossRepository === true,
230
+ truncated: pr.reviewThreads?.pageInfo?.hasNextPage === true,
231
+ longThreads,
232
+ skipped: { resolved, outdated },
233
+ threads,
234
+ };
235
+ }
236
+
237
+ /** Why this pull request may not be answered, or null. */
238
+ export function ownershipError(doc, t) {
239
+ if (doc.state !== "OPEN") return t.notOpen(doc.pr, doc.state);
240
+ if (!doc.viewer || doc.author !== doc.viewer) return t.notOwn(doc.pr, doc.author ?? "?");
241
+ return null;
242
+ }
243
+
244
+ function anchorOf(e) {
245
+ if (typeof e === "string") {
246
+ const m = /^(.+):(\d+)$/.exec(e.trim());
247
+ return m ? { file: m[1], line: Number(m[2]) } : null;
248
+ }
249
+ if (e && typeof e.file === "string" && Number.isInteger(e.line)) {
250
+ return { file: e.file, line: e.line, ...(e.quote ? { quote: e.quote } : {}) };
251
+ }
252
+ return null;
253
+ }
254
+
255
+ /**
256
+ * Hold verdicts to the contract. Returns the list of problems; empty passes.
257
+ *
258
+ * @param {object} threadsDoc
259
+ * @param {object} verdictsDoc { verdicts: [{ threadId, class, reason, reply, evidence[] }] }
260
+ * @param {string} dir the checkout anchors resolve in
261
+ */
262
+ export function checkVerdicts(threadsDoc, verdictsDoc, dir) {
263
+ const problems = [];
264
+ const open = new Set((threadsDoc.threads ?? []).map((t) => t.threadId));
265
+ const seen = new Map();
266
+ const cache = new Map();
267
+ for (const v of verdictsDoc?.verdicts ?? []) {
268
+ const id = v?.threadId;
269
+ if (!open.has(id)) {
270
+ problems.push(`${id}: no such open thread`);
271
+ continue;
272
+ }
273
+ seen.set(id, (seen.get(id) ?? 0) + 1);
274
+ if (!CLASSES.includes(v.class))
275
+ problems.push(`${id}: class must be one of ${CLASSES.join(", ")}`);
276
+ if (!String(v.reason ?? "").trim()) problems.push(`${id}: reason is empty`);
277
+ const reply = String(v.reply ?? "").trim();
278
+ if (!reply) problems.push(`${id}: reply is empty`);
279
+ if (PERFORMATIVE.some((re) => re.test(reply))) {
280
+ problems.push(`${id}: reply opens with praise or agreement instead of the substance`);
281
+ }
282
+ if (v.class === "pushback" && !CITATION.test(reply)) {
283
+ problems.push(`${id}: a pushback reply cites the code as file:line`);
284
+ }
285
+ const evidence = Array.isArray(v.evidence) ? v.evidence : [];
286
+ if (v.class !== "question" && evidence.length === 0) {
287
+ problems.push(`${id}: ${v.class} needs at least one file:line anchor`);
288
+ }
289
+ for (const e of evidence) {
290
+ const a = anchorOf(e);
291
+ if (!a) {
292
+ problems.push(`${id}: evidence ${JSON.stringify(e)} is not file:line`);
293
+ continue;
294
+ }
295
+ const err = resolveOne(dir, null, { quote: undefined, ...a }, cache);
296
+ if (err) problems.push(`${id}: ${a.file}:${a.line} ${err}`);
297
+ }
298
+ }
299
+ for (const id of open) {
300
+ const n = seen.get(id) ?? 0;
301
+ if (n === 0) problems.push(`${id}: no verdict`);
302
+ if (n > 1) problems.push(`${id}: ${n} verdicts, expected one`);
303
+ }
304
+ return problems;
305
+ }
306
+
307
+ /** The draft every run ends with: what would be posted, in outputLanguage. */
308
+ export function renderDraft(threadsDoc, verdictsDoc, t) {
309
+ const byId = new Map((verdictsDoc.verdicts ?? []).map((v) => [v.threadId, v]));
310
+ const out = [t.heading(threadsDoc.pr), ""];
311
+ for (const th of threadsDoc.threads ?? []) {
312
+ const v = byId.get(th.threadId);
313
+ if (!v) continue;
314
+ const where = th.path ? `${th.path}${th.line ? `:${th.line}` : ""}` : "PR";
315
+ out.push(`## ${t.classLabel[v.class] ?? v.class} - ${where} (@${th.author ?? "?"})`, "");
316
+ out.push(...th.body.split("\n").map((l) => `> ${l}`), "");
317
+ const ev = (v.evidence ?? []).map((e) => {
318
+ const a = anchorOf(e);
319
+ return a ? `${a.file}:${a.line}` : String(e);
320
+ });
321
+ if (ev.length) out.push(`${t.evidence}: ${ev.join(", ")}`, "");
322
+ out.push(`${t.reply}:`, "", String(v.reply ?? "").trim(), "");
323
+ }
324
+ out.push(t.skipped(threadsDoc.skipped?.resolved ?? 0, threadsDoc.skipped?.outdated ?? 0));
325
+ return `${out.join("\n")}\n`;
326
+ }
327
+
328
+ const PROTECTED = new Set(["main", "master", "develop"]);
329
+
330
+ /** True when a push to `ref` is never made: a protected name or the default branch. */
331
+ export function protectedRef(ref, defaultBranch) {
332
+ const b = String(ref ?? "").replace(/^refs\/heads\//, "");
333
+ if (!b) return true;
334
+ return (
335
+ PROTECTED.has(b) || b.startsWith("release/") || (defaultBranch != null && b === defaultBranch)
336
+ );
337
+ }
338
+
339
+ /** owner/name from a GitHub remote URL (https, ssh or scp form), lower-cased. */
340
+ export function repoOfUrl(url) {
341
+ const m = /github\.com[:/]([^/\s]+)\/([^/\s]+?)(?:\.git)?\/?$/i.exec(String(url ?? "").trim());
342
+ return m ? `${m[1]}/${m[2]}`.toLowerCase() : null;
343
+ }
344
+
345
+ /** The remote in `dir` whose fetch URL is the PR's head repository, or null. */
346
+ export function matchingRemote(remotes, headRepo) {
347
+ const want = String(headRepo ?? "").toLowerCase();
348
+ return remotes.find((r) => repoOfUrl(r.url) === want) ?? null;
349
+ }
350
+
351
+ function remotesOf(dir, io) {
352
+ const out = io.git(dir, ["remote", "-v"]);
353
+ const seen = new Map();
354
+ for (const line of out.split("\n")) {
355
+ const m = /^(\S+)\s+(\S+)\s+\(push\)$/.exec(line.trim());
356
+ if (m && !seen.has(m[1])) seen.set(m[1], { name: m[1], url: m[2] });
357
+ }
358
+ return [...seen.values()];
359
+ }
360
+
361
+ function git(dir, args) {
362
+ const r = spawnSync("git", ["-C", dir, ...args], { encoding: "utf8", timeout: 60_000 });
363
+ if (r.status !== 0) throw new Error(`git ${args[0]} failed: ${(r.stderr || "").trim()}`);
364
+ return r.stdout.trim();
365
+ }
366
+
367
+ /**
368
+ * The token for one write, computed from the state it would be made against.
369
+ */
370
+ export function tokenFor({ action, thread, body, headRef, localSha, remoteSha, remote, dir }) {
371
+ if (action === "push") {
372
+ return sha(
373
+ JSON.stringify(["push", headRef, localSha, remoteSha, remote?.name, remote?.url, dir]),
374
+ ).slice(0, 16);
375
+ }
376
+ return sha(
377
+ JSON.stringify([action, thread.threadId, thread.lastCommentId, sha(body ?? "")]),
378
+ ).slice(0, 16);
379
+ }
380
+
381
+ function liveThreads(flags, env, io) {
382
+ const doc = readJson(flags.threads);
383
+ const [owner, name] = String(doc.repo).split("/");
384
+ return normalize(io.graphql(QUERY, { owner, name, number: Number(doc.pr) }, env), doc.repo);
385
+ }
386
+
387
+ function operation(flags, env, live, t, io) {
388
+ const action = flags.action;
389
+ if (!ACTIONS.includes(action))
390
+ throw new UsageError(`--action must be one of ${ACTIONS.join(", ")}`);
391
+ const doc = live ? liveThreads(flags, env, io) : readJson(flags.threads);
392
+ const bad = ownershipError(doc, t);
393
+ if (bad) throw new RefusedError(bad, 4);
394
+ if (action === "push") {
395
+ if (!flags.dir) throw new UsageError("push needs --dir");
396
+ if (doc.isCrossRepository) throw new RefusedError(t.crossRepo(doc.headRepo ?? "?"), 1);
397
+ if (protectedRef(doc.headRef, doc.defaultBranch)) {
398
+ throw new RefusedError(t.protectedRef(doc.headRef || "?"), 1);
399
+ }
400
+ const headRepo = doc.headRepo ?? doc.repo;
401
+ const remote = matchingRemote(remotesOf(flags.dir, io), headRepo);
402
+ if (!remote) throw new RefusedError(t.noRemote(headRepo), 1);
403
+ const dir = realpathSync(flags.dir);
404
+ const localSha = io.git(dir, ["rev-parse", "HEAD"]);
405
+ return { action, doc, localSha, remoteSha: doc.headSha, headRef: doc.headRef, remote, dir };
406
+ }
407
+ if (!flags.thread) throw new UsageError(`${action} needs --thread`);
408
+ const thread = (doc.threads ?? []).find((x) => x.threadId === flags.thread);
409
+ if (!thread) throw new RefusedError(`thread ${flags.thread} is not open on this PR`, 1);
410
+ let body = null;
411
+ if (action === "reply") {
412
+ if (!flags["body-file"]) throw new UsageError("reply needs --body-file");
413
+ body = readFileSync(flags["body-file"], "utf8").trim();
414
+ if (!body) throw new UsageError("the reply body is empty");
415
+ }
416
+ return { action, doc, thread, body };
417
+ }
418
+
419
+ async function run(sub, flags, env, out, t, io) {
420
+ if (sub === "fetch") {
421
+ for (const k of ["repo", "pr", "out"])
422
+ if (!flags[k]) throw new UsageError(`fetch needs --${k}`);
423
+ const [owner, name] = String(flags.repo).split("/");
424
+ if (!owner || !name) throw new UsageError("--repo is OWNER/NAME");
425
+ const raw = io.graphql(QUERY, { owner, name, number: Number(flags.pr) }, env);
426
+ const doc = normalize(raw, flags.repo);
427
+ const bad = ownershipError(doc, t);
428
+ if (bad) throw new RefusedError(bad, 4);
429
+ mkdirSync(dirname(flags.out), { recursive: true });
430
+ writeFileSync(flags.out, `${JSON.stringify(doc, null, 2)}\n`);
431
+ out(
432
+ JSON.stringify({
433
+ out: flags.out,
434
+ open: doc.threads.length,
435
+ ...doc.skipped,
436
+ truncated: doc.truncated,
437
+ longThreads: doc.longThreads,
438
+ crossRepository: doc.isCrossRepository,
439
+ }),
440
+ );
441
+ return 0;
442
+ }
443
+ if (sub === "check") {
444
+ for (const k of ["threads", "verdicts", "dir"])
445
+ if (!flags[k]) throw new UsageError(`check needs --${k}`);
446
+ const problems = checkVerdicts(readJson(flags.threads), readJson(flags.verdicts), flags.dir);
447
+ if (flags.json) out(JSON.stringify({ ok: problems.length === 0, problems }, null, 2));
448
+ else out(problems.length ? problems.map((p) => ` - ${p}`).join("\n") : "ok");
449
+ return problems.length ? 1 : 0;
450
+ }
451
+ if (sub === "draft") {
452
+ for (const k of ["threads", "verdicts", "out"])
453
+ if (!flags[k]) throw new UsageError(`draft needs --${k}`);
454
+ mkdirSync(dirname(flags.out), { recursive: true });
455
+ writeFileSync(flags.out, renderDraft(readJson(flags.threads), readJson(flags.verdicts), t));
456
+ out(flags.out);
457
+ return 0;
458
+ }
459
+ if (sub === "propose" || sub === "apply") {
460
+ if (isUnattended(env)) throw new RefusedError(t.unattended, 5);
461
+ if (!flags.threads) throw new UsageError(`${sub} needs --threads`);
462
+ const op = operation(flags, env, sub === "apply", t, io);
463
+ const token = tokenFor({ ...op, headRef: op.headRef });
464
+ if (sub === "propose") {
465
+ if (op.action === "push")
466
+ out(`${t.willPush(op.headRef, op.localSha)} [${op.remote.name} ${op.remote.url}]`);
467
+ else if (op.action === "resolve") out(t.willResolve(op.thread.threadId));
468
+ else out(`${t.willReply(op.thread.threadId)}\n\n${op.body}`);
469
+ out(`\ntoken: ${token}`);
470
+ return 0;
471
+ }
472
+ if (!flags.confirm) throw new UsageError("apply needs --confirm TOKEN from propose");
473
+ if (flags.confirm !== token) throw new RefusedError(t.stale, 6);
474
+ if (op.action === "push") {
475
+ io.git(op.dir, ["push", op.remote.name, `HEAD:refs/heads/${op.headRef}`]);
476
+ } else if (op.action === "resolve") {
477
+ io.graphql(RESOLVE, { thread: op.thread.threadId }, env);
478
+ } else {
479
+ io.graphql(REPLY, { thread: op.thread.threadId, body: op.body }, env);
480
+ }
481
+ out(t.done);
482
+ return 0;
483
+ }
484
+ throw unknownSubcommand(sub, SUBCOMMANDS);
485
+ }
486
+
487
+ /**
488
+ * @param {string[]} [argv]
489
+ * @param {Record<string, string|undefined>} [env]
490
+ * @param {{graphql?: Function, git?: Function, out?: (s: string) => void}} [io]
491
+ * the GitHub and git calls and the output sink; tests replace them, the CLI
492
+ * never can
493
+ */
494
+ export async function main(argv = process.argv.slice(2), env = process.env, io = {}) {
495
+ const t = messages(TEXT, outputLanguage());
496
+ const out = io.out ?? ((s) => process.stdout.write(`${s}\n`));
497
+ const calls = { graphql: io.graphql ?? graphql, git: io.git ?? git };
498
+ const [sub, ...rest] = argv;
499
+ if (!sub || sub === "-h" || sub === "--help") {
500
+ const lines = readFileSync(new URL(import.meta.url), "utf8").split("\n");
501
+ const start = lines.findIndex((l) => l.includes("Usage:"));
502
+ const end = lines.findIndex((l, i) => i > start && l.trim() === "*");
503
+ out(
504
+ lines
505
+ .slice(start, end)
506
+ .map((l) => l.replace(/^ \*\s?/, ""))
507
+ .join("\n"),
508
+ );
509
+ return sub ? 0 : 2;
510
+ }
511
+ try {
512
+ const { flags } = parseArgs(rest, {
513
+ booleans: ["json"],
514
+ strings: [
515
+ "repo",
516
+ "pr",
517
+ "out",
518
+ "threads",
519
+ "verdicts",
520
+ "dir",
521
+ "action",
522
+ "thread",
523
+ "body-file",
524
+ "confirm",
525
+ ],
526
+ unknown: "error",
527
+ positionals: false,
528
+ });
529
+ return await run(sub, flags, env, out, t, calls);
530
+ } catch (e) {
531
+ process.stderr.write(`pr-threads: ${e.message}\n`);
532
+ if (e instanceof RefusedError) return e.code;
533
+ return e instanceof ArgsError || e instanceof UsageError ? 2 : 1;
534
+ }
535
+ }
536
+
537
+ if (invokedDirectly(import.meta.url)) process.exitCode = await main();
@@ -0,0 +1,139 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * pr-write-guard.mjs - a GitHub write by /multi-agent:address-review is
4
+ * approved by the person at the host, not only in the command's prose.
5
+ *
6
+ * PreToolUse on Bash. A command that runs `pr-threads.mjs apply` (directly,
7
+ * through a variable holding the path, inside `bash -c`, after `env`, or as
8
+ * `node <path>`) is answered with `permissionDecision: "ask"` and a reason
9
+ * naming the PR and the operation, so the host asks the person before the
10
+ * write runs. With MULTI_AGENT_UNATTENDED=1 it is `deny`: unattended runs end
11
+ * at the draft.
12
+ *
13
+ * Detection is textual and errs toward asking. After quotes and backslashes
14
+ * are removed, a command that names the script loosely (`pr-threads`,
15
+ * `pr?threads`, `pr*threads`) and holds the word `apply` or runs inline code
16
+ * (`node -e`, `--eval`, `-p`) asks, and so does any command carrying both
17
+ * `--confirm` and `--action reply|resolve|push`, which only an apply takes.
18
+ * Every other Bash call gets no output.
19
+ *
20
+ * Output: the PreToolUse hook JSON or nothing. Exit 0 always; an unreadable
21
+ * payload is allowed attended and denied unattended.
22
+ *
23
+ * @module pipeline/scripts/pr-write-guard
24
+ */
25
+
26
+ import { readFileSync } from "node:fs";
27
+
28
+ import { exitOnHelp } from "../lib/cli-help.mjs";
29
+ import { invokedDirectly } from "../lib/invoked-directly.mjs";
30
+ import { isUnattended } from "../lib/unattended.mjs";
31
+ import { messages, outputLanguage } from "../lib/user-facing.mjs";
32
+
33
+ exitOnHelp(import.meta.url);
34
+
35
+ const MENTION = /pr.{0,4}threads/i;
36
+ const EVAL =
37
+ /(?:^|[\s;&|(])(?:\S*\/)?(?:node|bun|deno)\s+(?:\S+\s+)*?(?:-e|--eval|-p|--print)(?=[\s=]|$)/;
38
+ const APPLY_WORD = /(?:^|[\s'"`;&|(])apply(?=$|[\s'"`;&|)])/;
39
+ const CONFIRM = /--confirm(?:[=\s])/;
40
+ const ACTION = /--action(?:=|\s+)['"]?(reply|resolve|push)\b/;
41
+
42
+ const TEXT = {
43
+ en: {
44
+ ask: (op, where) =>
45
+ `address-review: ${op} on ${where} writes to GitHub. Approve this one write only if you saw what propose printed.`,
46
+ deny: (op, where) =>
47
+ `address-review: ${op} on ${where} refused: unattended runs end at the draft and write nothing to GitHub.`,
48
+ unknownPr: "the PR named in the threads file",
49
+ },
50
+ tr: {
51
+ ask: (op, where) =>
52
+ `address-review: ${where} üzerinde ${op} GitHub'a yazar. propose çıktısını gördüysen yalnızca bu tek yazmayı onayla.`,
53
+ deny: (op, where) =>
54
+ `address-review: ${where} üzerinde ${op} reddedildi: gözetimsiz koşular taslakta biter, GitHub'a yazmaz.`,
55
+ unknownPr: "threads dosyasındaki PR",
56
+ },
57
+ };
58
+
59
+ /**
60
+ * The shell text with line continuations joined and quotes and backslashes
61
+ * removed, so `pr''-threads`, `"pr-threads"` and `pr\-threads` read alike;
62
+ * glob spellings (`pr?threads`, `pr*threads`) match the loose name pattern.
63
+ */
64
+ export function flatten(command) {
65
+ return String(command ?? "")
66
+ .replace(/\\\n/g, " ")
67
+ .replace(/['"\\]/g, "");
68
+ }
69
+
70
+ /** True when the shell text runs a pr-threads apply. */
71
+ export function isApply(command) {
72
+ const text = flatten(command);
73
+ if (MENTION.test(text) && (APPLY_WORD.test(text) || EVAL.test(text))) return true;
74
+ return CONFIRM.test(text) && ACTION.test(text);
75
+ }
76
+
77
+ function flag(text, name) {
78
+ const m = new RegExp(`--${name}(?:=|\\s+)(?:"([^"]+)"|'([^']+)'|(\\S+))`).exec(text);
79
+ return m ? (m[1] ?? m[2] ?? m[3]) : null;
80
+ }
81
+
82
+ /** "reply on thread X", "push", ... and "acme/app#7" when the threads file says. */
83
+ export function describe(command, t, readFile = readFileSync) {
84
+ const text = String(command ?? "");
85
+ const action = ACTION.exec(text)?.[1] ?? "apply";
86
+ const thread = flag(text, "thread");
87
+ const op = thread ? `${action} (thread ${thread})` : action;
88
+ let where = t.unknownPr;
89
+ const threads = flag(text, "threads");
90
+ if (threads && !threads.includes("$")) {
91
+ try {
92
+ const doc = JSON.parse(readFile(threads, "utf8"));
93
+ if (doc?.repo && doc?.pr) where = `${doc.repo}#${doc.pr}`;
94
+ } catch {
95
+ where = `${t.unknownPr} (${threads})`;
96
+ }
97
+ }
98
+ return { op, where };
99
+ }
100
+
101
+ /** The hook decision for one payload, or null. */
102
+ export function decide(payload, env = process.env, t = messages(TEXT, outputLanguage())) {
103
+ if (payload?.tool_name !== "Bash") return null;
104
+ const command = payload?.tool_input?.command;
105
+ if (!isApply(command)) return null;
106
+ const { op, where } = describe(command, t);
107
+ const unattended = isUnattended(env);
108
+ return {
109
+ hookSpecificOutput: {
110
+ hookEventName: "PreToolUse",
111
+ permissionDecision: unattended ? "deny" : "ask",
112
+ permissionDecisionReason: unattended ? t.deny(op, where) : t.ask(op, where),
113
+ },
114
+ };
115
+ }
116
+
117
+ function main() {
118
+ let payload;
119
+ try {
120
+ payload = JSON.parse(readFileSync(0, "utf8"));
121
+ } catch {
122
+ if (isUnattended()) {
123
+ process.stdout.write(
124
+ `${JSON.stringify({
125
+ hookSpecificOutput: {
126
+ hookEventName: "PreToolUse",
127
+ permissionDecision: "deny",
128
+ permissionDecisionReason: "pr-write-guard: unreadable hook payload",
129
+ },
130
+ })}\n`,
131
+ );
132
+ }
133
+ return;
134
+ }
135
+ const out = decide(payload);
136
+ if (out) process.stdout.write(`${JSON.stringify(out)}\n`);
137
+ }
138
+
139
+ if (invokedDirectly(import.meta.url)) main();