@mnaimfaizy/agent-kit 1.0.0-beta.16 → 1.0.0-beta.17

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.
@@ -6,17 +6,18 @@
6
6
  // Launcher (`ctx.launch`, a sandbox that holds no GitHub token), plan-publish,
7
7
  // stage-release.
8
8
  // qa qa-target, qa-start, qa-check, stage-release. QA runs no agent yet.
9
- // review review-target, review-start, review-check, stage-release.
10
- // security security-target, security-start, security-check, stage-release.
9
+ // review review-target, review-start, stage-limits, the review brief (built from Kit-owned
10
+ // files read from the default branch, the pull request fenced as untrusted), the
11
+ // Launcher (stage `review`), the Review report and its threads (published here, in this
12
+ // process, by the Kit's `review-threads.mjs` run as a child with the token in its
13
+ // environment only, never in the sandbox), review-check, stage-release.
14
+ // security security-target, security-start, stage-limits, the audit brief (built from Kit-owned
15
+ // and Threat pack files read from the default branch), the Launcher (stage `audit`),
16
+ // the draft advisory (published here, in this process, never in the sandbox),
17
+ // security-check, stage-release.
11
18
  // build (only with a Launcher that runs a Chief of Staff) the factory-mode Stage of
12
19
  // build/factory.mjs: a Snapshot, an Outbox, sibling sandboxes for Delegations.
13
20
  //
14
- // Review and security have the seam but no brief builder and no publish step here (their
15
- // briefs and the review threads, the audit verdict, are built in the reusable workflows):
16
- // they start no Launcher run, so review ends in the Stage check `error` and security in
17
- // `failure` ("held for a maintainer"). That is the safe end; docs/factory/engine.md says
18
- // to keep the merge gate off on this engine. The open work, not yet ticketed: the review
19
- // brief and publish step, and the security brief and verdict, on the Orchestrate engine.
20
21
 
21
22
  import { mkdirSync, readFileSync, statSync } from "node:fs";
22
23
  import { join } from "node:path";
@@ -27,7 +28,28 @@ import { runStageLimits, runStageRelease } from "../claims/command.mjs";
27
28
  import { runPlanAnswers } from "../decision/command.mjs";
28
29
  import { runPlanPublish } from "../plan/command.mjs";
29
30
  import { runQaCheck, runQaStart, runQaTarget } from "../qa/command.mjs";
31
+ import {
32
+ REVIEW_SKILL,
33
+ REVIEW_THREADS_SCRIPT,
34
+ REVIEW_TRUSTED_READS,
35
+ buildReviewBrief,
36
+ resolveReviewSettings,
37
+ verifiedPlan,
38
+ } from "../review/brief.mjs";
30
39
  import { runReviewCheck, runReviewStart, runReviewTarget } from "../review/command.mjs";
40
+ import {
41
+ AUDIT_PROMPT,
42
+ AUDIT_REPORT_FORMAT,
43
+ AUDIT_SKILL,
44
+ AUDIT_TRUSTED_READS,
45
+ FINDINGS_LEDGER,
46
+ THREAT_MODEL,
47
+ advisoryPayload,
48
+ buildAuditBrief,
49
+ probeAdvisoryWrite,
50
+ publishAdvisory,
51
+ resolveAuditSettings,
52
+ } from "../security/audit.mjs";
31
53
  import { runSecurityCheck, runSecurityStart, runSecurityTarget } from "../security/command.mjs";
32
54
 
33
55
  /** The trusted steps by name; a test hands `createPipelines` others. */
@@ -52,11 +74,19 @@ export { limitFlagsOf };
52
74
  const PLANNER_PROMPT = ".github/agent-pipeline/planner-prompt.md";
53
75
  const HEADER_PROMPT = ".github/agent-factory/planner-header-prompt.md";
54
76
  /**
55
- * Every path the engine reads through `ctx.readTrusted` (`git show HEAD:<path>`): each must be
56
- * in the checked-out commit, so `init --factory --engine orchestrate` writes them all (they are
57
- * under the Kit-owned paths `.github/agent-pipeline/` and `.github/agent-factory/`).
77
+ * Every Kit-owned path the engine reads through `ctx.readTrusted`: each is read from the default
78
+ * branch's remote head, so it must be merged there. `init --factory --engine orchestrate` writes
79
+ * them all (they are under the Kit-owned paths `.github/agent-pipeline/`, `.github/agent-factory/`,
80
+ * `.github/security-audit/`, `.claude/skills/security-audit/`, `.claude/skills/code-review/` and
81
+ * `.github/agent-runtime/`). The Consumer's Threat pack
82
+ * (`THREAT_MODEL`, `FINDINGS_LEDGER`) is read the same way but is the Consumer's own, so it is not here.
58
83
  */
59
- export const TRUSTED_READS = Object.freeze([PLANNER_PROMPT, HEADER_PROMPT]);
84
+ export const TRUSTED_READS = Object.freeze([
85
+ PLANNER_PROMPT,
86
+ HEADER_PROMPT,
87
+ ...AUDIT_TRUSTED_READS,
88
+ ...REVIEW_TRUSTED_READS,
89
+ ]);
60
90
 
61
91
  /** One bundle command, run in this process: its exit code, its `key=value` outputs, its lines. */
62
92
  function step(command, ctx, args, extraEnv = {}, extra = {}) {
@@ -198,8 +228,429 @@ async function plan(ctx, commands) {
198
228
  return { outcome: code === 0 ? "done" : "failed", code };
199
229
  }
200
230
 
231
+ /**
232
+ * Runs `fn` on a checkout of the pull request's head: a detached worktree the engine makes and
233
+ * removes, so the Stage judges that code wherever the host's checkout sits. `fn` gets
234
+ * `{ git, cwd }`: the git to read the code with, and the directory the Launcher runs in
235
+ * (undefined: the Launcher's own); a checkout that could not be made gives `{ checkoutError }`.
236
+ * A context with no `checkout` (a host that does not make one) runs on the host's checkout, which the Stage's own guard then compares with the head.
237
+ */
238
+ async function onHead(ctx, sha, fn) {
239
+ if (typeof ctx.checkout !== "function") return fn({ git: ctx.git, cwd: undefined });
240
+ const made = ctx.checkout(sha);
241
+ if (made.error) return { checkoutError: made.error };
242
+ try {
243
+ return await fn({ git: made.git, cwd: made.path });
244
+ } finally {
245
+ made.remove();
246
+ }
247
+ }
248
+
249
+ /** The audit's own file, read by the Launcher's caller: the bytes, or null (a missing or empty file). */
250
+ const readText = (ctx, path) => {
251
+ const bytes = (ctx.readFile ?? readBytes)(path);
252
+ return bytes && bytes.length ? String(bytes) : null;
253
+ };
254
+
255
+ /**
256
+ * The audit, from the brief to the draft advisory: `{ jobResult, result, usagePath }` for
257
+ * security-check (the equivalents of the reusable's job result and `result` output), or
258
+ * `{ cancelled: true }`. Anything that goes wrong holds: the verdict is `success` and `clean`
259
+ * only for an audit the Launcher completed, whose report was filed as a draft advisory and
260
+ * holds no finding.
261
+ */
262
+ async function audit(ctx, commands, args) {
263
+ const done = await onHead(ctx, args.sha, (co) => auditOn(ctx, commands, args, co));
264
+ if (!done.checkoutError) return done;
265
+ if (ctx.signal.aborted) return { cancelled: true };
266
+ ctx.log?.(`#${ctx.issue} security: no checkout of the head: ${done.checkoutError}: held`);
267
+ return { jobResult: "failure", result: "held" };
268
+ }
269
+
270
+ async function auditOn(ctx, commands, { sha, base, dir }, co) {
271
+ const say = (line) => ctx.log?.(`#${ctx.issue} security: ${line}`);
272
+ const held = (usagePath) => ({ jobResult: "failure", result: "held", usagePath });
273
+ // A harness the audit is not wired for, a model or an effort it refuses: before the Launcher starts.
274
+ const settings = resolveAuditSettings(ctx.env);
275
+ if (settings.refused) {
276
+ say(settings.refused);
277
+ return held();
278
+ }
279
+ for (const note of settings.notes) say(note);
280
+ const limits = step(commands.limits, ctx, ["--stage", "security", "--harness", settings.harness]);
281
+ if (limits.code !== 0) return held();
282
+
283
+ const briefPath = join(dir, "security-audit-brief.md");
284
+ const resultPath = join(dir, "security-audit-report.md");
285
+ const sessionPath = join(dir, "security-audit-session.md");
286
+ const logPath = join(dir, "security-audit-cli.log");
287
+ const usagePath = join(dir, "usage.json");
288
+ let trustedRef;
289
+ try {
290
+ // The Launcher copies the checkout's commit in: it is the audit only when it is the pull request's head.
291
+ const head = co.git(["rev-parse", "HEAD"]);
292
+ if (head.status !== 0 || String(head.stdout).trim() !== sha) {
293
+ say("the checkout is not at the pull request's head, so it would audit other code: held");
294
+ return held();
295
+ }
296
+ const trusted = (path) => ctx.readTrusted(path);
297
+ // The Threat pack is the Consumer's own, so `init` never writes it: a miss names it, not init.
298
+ const pack = (path) => {
299
+ try {
300
+ return trusted(path);
301
+ } catch {
302
+ throw new Error(
303
+ `the Threat pack is not on the default branch: ${THREAT_MODEL} and ${FINDINGS_LEDGER} are the repository's own files; set them up as the security audit's setup describes (docs/factory/security.md)`,
304
+ );
305
+ }
306
+ };
307
+ const files = {
308
+ skill: trusted(AUDIT_SKILL),
309
+ prompt: trusted(AUDIT_PROMPT),
310
+ reportFormat: trusted(AUDIT_REPORT_FORMAT),
311
+ ledger: pack(FINDINGS_LEDGER),
312
+ threatModel: pack(THREAT_MODEL),
313
+ };
314
+ // The default branch commit the files above came from: the Launcher takes its instruction files
315
+ // from it (the pull request's head must not rewrite the instructions that audit it).
316
+ trustedRef = ctx.trustedCommit();
317
+ if (!trustedRef) throw new Error("the default branch's commit is not known");
318
+ const names = co.git(["diff", "--name-only", `${base}...HEAD`]);
319
+ const diff = co.git([
320
+ "diff",
321
+ "--text",
322
+ "--no-ext-diff",
323
+ "--no-textconv",
324
+ "--unified=3",
325
+ `${base}...HEAD`,
326
+ ]);
327
+ if (names.status !== 0 || diff.status !== 0)
328
+ throw new Error("the pull request's diff could not be read");
329
+ ctx.writeFile(
330
+ briefPath,
331
+ buildAuditBrief({
332
+ repo: ctx.repo,
333
+ base,
334
+ changed: String(names.stdout),
335
+ diff: String(diff.stdout),
336
+ ...files,
337
+ }),
338
+ );
339
+ } catch (error) {
340
+ say(`no audit brief: ${error.message}`);
341
+ return held();
342
+ }
343
+ if (ctx.signal.aborted) return { cancelled: true };
344
+ // The draft advisory is filed with the engine's token: find out it may before the model runs.
345
+ const probe = probeAdvisoryWrite({ gh: ctx.gh, repo: ctx.repo });
346
+ if (!probe.ok) {
347
+ say(`${probe.message}: held before the Launcher started`);
348
+ return held();
349
+ }
350
+
351
+ const code = await ctx.launch({
352
+ stage: "audit",
353
+ cwd: co.cwd,
354
+ harness: settings.harness,
355
+ model: settings.model,
356
+ effort: settings.effort,
357
+ briefPath,
358
+ resultPath,
359
+ transcriptPath: sessionPath,
360
+ errorLogPath: logPath,
361
+ usagePath,
362
+ trustedRef,
363
+ limitFlags: limitFlagsOf(limits.outputs.flags),
364
+ signal: ctx.signal,
365
+ });
366
+ if (ctx.trace) ctx.trace.launcherCode = code;
367
+ // A cancelled run files nothing: its Claim is released by the sweep or the drain.
368
+ if (ctx.signal.aborted) return { cancelled: true };
369
+
370
+ // What the run left: the transcript and the harness's error output, and, from a run that did
371
+ // not complete, the report it left joins the transcript (no report is filed then).
372
+ let session = readText(ctx, sessionPath);
373
+ const errorLog = readText(ctx, logPath);
374
+ const left = readText(ctx, resultPath);
375
+ if (code !== 0 && session === null && errorLog === null) return held(); // the agent never ran
376
+ session ??= "No transcript came out of the sandbox.";
377
+ if (errorLog) session += `\n\n--- harness error output ---\n\n${errorLog}`;
378
+ const report = code === 0 ? left : null;
379
+ if (code !== 0 && left) session += `\n\n--- the report the incomplete run left ---\n\n${left}`;
380
+
381
+ const filed = advisoryPayload({
382
+ repo: ctx.repo,
383
+ report: report ?? "",
384
+ transcript: session,
385
+ emptyReport: report === null,
386
+ now: new Date((ctx.now ?? Date.now)()),
387
+ });
388
+ const published = await publishAdvisory({
389
+ gh: ctx.gh,
390
+ repo: ctx.repo,
391
+ payload: filed.payload,
392
+ sleep: ctx.sleep,
393
+ signal: ctx.signal,
394
+ });
395
+ if (ctx.signal.aborted) return { cancelled: true };
396
+ if (!published.ok) say(`the draft advisory could not be filed; the report stays in ${dir}`);
397
+ const clean =
398
+ published.ok &&
399
+ report !== null &&
400
+ code === 0 &&
401
+ filed.parsed.count === 0 &&
402
+ !filed.parsed.mismatch;
403
+ return {
404
+ jobResult: published.ok && report !== null && code === 0 ? "success" : "failure",
405
+ result: clean ? "clean" : "held",
406
+ usagePath,
407
+ };
408
+ }
409
+
410
+ /**
411
+ * The security Stage: the pull request to audit, the pending check, the audit, then the check
412
+ * from its outcome and the release comment (with the Launcher's usage).
413
+ */
414
+ async function security(ctx, commands) {
415
+ const found = step(commands.securityTarget, ctx, ["--issue", String(ctx.issue)]);
416
+ if (found.code !== 0) return { outcome: "failed", code: found.code };
417
+ const { head_sha: sha, base_sha: base } = found.outputs;
418
+ if (ctx.trace) ctx.trace.head = sha;
419
+ step(commands.securityStart, ctx, ["--sha", sha]);
420
+ if (ctx.signal.aborted) return { outcome: "cancelled" };
421
+ const dir = join(ctx.runDir(ctx.claim));
422
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
423
+ const done = await audit(ctx, commands, { sha, base, dir });
424
+ if (done.cancelled) return { outcome: "cancelled" };
425
+ const checked = step(commands.securityCheck, ctx, ["--sha", sha], {
426
+ AUDIT_JOB_RESULT: done.jobResult,
427
+ AUDIT_RESULT: done.result,
428
+ });
429
+ const state = checked.outputs.state;
430
+ release(ctx, "security", state === "success" ? 0 : 1, done.usagePath, commands);
431
+ return { outcome: state === "success" ? "done" : "failed", state };
432
+ }
433
+
434
+ /** The reviewed head still stands on GitHub: the pull request's head, or an ancestor of it. */
435
+ function reviewedHeadStands(ctx, pr, sha) {
436
+ const now = ctx.gh(["api", `repos/${ctx.repo}/pulls/${pr}`, "--jq", ".head.sha"]);
437
+ if (now.status !== 0) return false;
438
+ const current = String(now.stdout).trim();
439
+ if (current === sha) return true;
440
+ // A push moved the head on: the review still belongs on the commit it read. A force push left
441
+ // it on no branch, which the compare answers `diverged` (or 404).
442
+ const compared = ctx.gh([
443
+ "api",
444
+ `repos/${ctx.repo}/compare/${sha}...${current}`,
445
+ "--jq",
446
+ ".status",
447
+ ]);
448
+ return compared.status === 0 && /^(?:ahead|identical)$/.test(String(compared.stdout).trim());
449
+ }
450
+
451
+ /**
452
+ * The review, from the brief to the published Review report: `{ published, usagePath }`, or
453
+ * `{ cancelled: true }`. `published` is true only for a review the Launcher completed whose
454
+ * result the Kit's own publish script posted; anything that goes wrong holds (not published), and
455
+ * review-check then finds no report of this run and writes `error`.
456
+ */
457
+ async function reviewRun(ctx, commands, args) {
458
+ const done = await onHead(ctx, args.sha, (co) => reviewOn(ctx, commands, args, co));
459
+ if (!done.checkoutError) return done;
460
+ if (ctx.signal.aborted) return { cancelled: true };
461
+ ctx.log?.(`#${ctx.issue} review: no checkout of the head: ${done.checkoutError}: held`);
462
+ return { published: false };
463
+ }
464
+
465
+ async function reviewOn(ctx, commands, { sha, base, pr, dir, runId }, co) {
466
+ const say = (line) => ctx.log?.(`#${ctx.issue} review: ${line}`);
467
+ const held = (usagePath) => ({ published: false, usagePath });
468
+ const settings = resolveReviewSettings(ctx.env);
469
+ if (settings.refused) {
470
+ say(settings.refused);
471
+ return held();
472
+ }
473
+ for (const note of settings.notes) say(note);
474
+ const limits = step(commands.limits, ctx, ["--stage", "review", "--harness", settings.harness]);
475
+ if (limits.code !== 0) return held();
476
+
477
+ const path = (name) => join(dir, name);
478
+ const briefPath = path("review-brief.md");
479
+ const diffPath = path("review-diff.patch");
480
+ const logPath = path("review-log.txt");
481
+ const resultPath = path("review.json");
482
+ const sessionPath = path("review-session.log");
483
+ const errorLogPath = path("review-cli.log");
484
+ const usagePath = path("usage.json");
485
+ const listedPath = path("review-listed.json");
486
+ const scriptPath = path("review-threads.mjs");
487
+ // The reviewer is the engine's token's person: its threads carry the Kit's marker, because the
488
+ // same login also writes the maintainer's own comments.
489
+ const scriptEnv = {
490
+ GITHUB_REPOSITORY: ctx.repo,
491
+ GITHUB_SERVER_URL: "https://github.com",
492
+ AGENT_KIT_REVIEWER_LOGIN: ctx.identity,
493
+ AGENT_KIT_REVIEWER_TYPE: "User",
494
+ };
495
+ const script = (args) => ctx.runScript(scriptPath, args, scriptEnv);
496
+ let trustedRef;
497
+ try {
498
+ // The Launcher copies the checkout's commit in: it reviews the pull request only at its head.
499
+ const head = co.git(["rev-parse", "HEAD"]);
500
+ if (head.status !== 0 || String(head.stdout).trim() !== sha) {
501
+ say("the checkout is not at the pull request's head, so it would review other code: held");
502
+ return held();
503
+ }
504
+ const skill = ctx.readTrusted(REVIEW_SKILL);
505
+ // The Kit's publish script, from the default branch, read-only beside the run's files.
506
+ ctx.writeFile(scriptPath, ctx.readTrusted(REVIEW_THREADS_SCRIPT), { mode: 0o444 });
507
+ trustedRef = ctx.trustedCommit();
508
+ if (!trustedRef) throw new Error("the default branch's commit is not known");
509
+ const threads = script(["open-threads", "--pr", String(pr), "--list", listedPath]);
510
+ const listed = (ctx.readFile ?? readBytes)(listedPath);
511
+ if (threads.status !== 0 || !listed || !listed.length) {
512
+ throw new Error("the reviewer's open threads could not be listed");
513
+ }
514
+ const pull = ctx.gh(["api", `repos/${ctx.repo}/issues/${pr}`]);
515
+ if (pull.status !== 0) throw new Error("the pull request could not be read");
516
+ const { title, body } = JSON.parse(pull.stdout);
517
+ const spec = verifiedPlan(ctx.tracker.readComments(ctx.issue), ctx.identity);
518
+ const names = co.git(["diff", "--name-only", `${base}...HEAD`]);
519
+ const diff = co.git(["diff", "--text", "--no-ext-diff", "--no-textconv", `${base}...HEAD`]);
520
+ const log = co.git(["log", "--oneline", `${base}..HEAD`]);
521
+ if (names.status !== 0 || diff.status !== 0 || log.status !== 0) {
522
+ throw new Error("the pull request's diff could not be read");
523
+ }
524
+ ctx.writeFile(diffPath, String(diff.stdout));
525
+ ctx.writeFile(logPath, String(log.stdout));
526
+ ctx.writeFile(
527
+ briefPath,
528
+ buildReviewBrief({
529
+ base,
530
+ head: sha,
531
+ pr,
532
+ title: String(title ?? ""),
533
+ body: String(body ?? ""),
534
+ openThreads: String(threads.stdout),
535
+ changed: String(names.stdout),
536
+ spec,
537
+ issue: ctx.issue,
538
+ skill: String(skill),
539
+ }),
540
+ );
541
+ } catch (error) {
542
+ say(`no review brief: ${error.message}`);
543
+ return held();
544
+ }
545
+ if (ctx.signal.aborted) return { cancelled: true };
546
+
547
+ const code = await ctx.launch({
548
+ stage: "review",
549
+ cwd: co.cwd,
550
+ harness: settings.harness,
551
+ model: settings.model,
552
+ effort: settings.effort,
553
+ briefPath,
554
+ inputPaths: [diffPath, logPath],
555
+ resultPath,
556
+ transcriptPath: sessionPath,
557
+ errorLogPath,
558
+ usagePath,
559
+ trustedRef,
560
+ limitFlags: limitFlagsOf(limits.outputs.flags),
561
+ signal: ctx.signal,
562
+ });
563
+ if (ctx.trace) ctx.trace.launcherCode = code;
564
+ // A cancelled run publishes nothing: its Claim is released by the sweep or the drain.
565
+ if (ctx.signal.aborted) return { cancelled: true };
566
+ // Only a completed run's result is published.
567
+ if (code !== 0 || !readText(ctx, resultPath)) {
568
+ say(
569
+ code !== 0
570
+ ? `the Launcher exited ${code}: nothing published`
571
+ : "no result: nothing published",
572
+ );
573
+ return held(usagePath);
574
+ }
575
+ if (!reviewedHeadStands(ctx, pr, sha)) {
576
+ say(
577
+ `the reviewed commit ${sha.slice(0, 7)} is on no branch of the repository (a force push during the run): nothing published`,
578
+ );
579
+ return held(usagePath);
580
+ }
581
+ // Where a comment can go: the same two commits, without --text (a binary file takes no comment).
582
+ const publishDiff = co.git(["diff", "--no-ext-diff", "--no-textconv", `${base}...${sha}`]);
583
+ if (publishDiff.status !== 0) {
584
+ say("the pull request's diff could not be read: nothing published");
585
+ return held(usagePath);
586
+ }
587
+ const publishDiffPath = path("review-publish.patch");
588
+ ctx.writeFile(publishDiffPath, String(publishDiff.stdout));
589
+ const published = script([
590
+ "publish",
591
+ "--pr",
592
+ String(pr),
593
+ "--head",
594
+ sha,
595
+ "--result",
596
+ resultPath,
597
+ "--diff",
598
+ publishDiffPath,
599
+ "--listed",
600
+ listedPath,
601
+ "--harness",
602
+ settings.harness,
603
+ "--run-url",
604
+ `https://github.com/${ctx.repo}/actions/runs/${runId}`,
605
+ "--factory",
606
+ ]);
607
+ if (ctx.signal.aborted) return { cancelled: true };
608
+ if (published.status !== 0) {
609
+ say(
610
+ `the review could not be published: ${
611
+ String(published.stdout)
612
+ .split("\n")
613
+ .find((l) => l.startsWith("::error")) ?? "see the run folder"
614
+ }`,
615
+ );
616
+ return held(usagePath);
617
+ }
618
+ return { published: true, usagePath };
619
+ }
620
+
621
+ /**
622
+ * The review Stage: the pull request to review, the pending check, the review, then the check from
623
+ * the report this run published and the release comment (with the Launcher's usage). A review that
624
+ * was not published is checked against a run id no report carries, so the check is `error`, never
625
+ * `success` (a partly posted review is not a review a gate may pass on).
626
+ */
627
+ async function review(ctx, commands) {
628
+ const found = step(commands.reviewTarget, ctx, ["--issue", String(ctx.issue)]);
629
+ if (found.code !== 0) return { outcome: "failed", code: found.code };
630
+ const { head_sha: sha, base_sha: base, pr_number: pr } = found.outputs;
631
+ if (ctx.trace) ctx.trace.head = sha;
632
+ step(commands.reviewStart, ctx, ["--sha", sha]);
633
+ if (ctx.signal.aborted) return { outcome: "cancelled" };
634
+ const dir = join(ctx.runDir(ctx.claim));
635
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
636
+ const runId = ctx.runId();
637
+ const done = await reviewRun(ctx, commands, { sha, base, pr, dir, runId });
638
+ if (done.cancelled) return { outcome: "cancelled" };
639
+ const checked = step(commands.reviewCheck, ctx, [
640
+ "--sha",
641
+ sha,
642
+ "--pr",
643
+ pr,
644
+ "--run-id",
645
+ String(done.published ? runId : 1),
646
+ ]);
647
+ const state = checked.outputs.state;
648
+ release(ctx, "review", state === "success" ? 0 : 1, done.usagePath, commands);
649
+ return { outcome: state === "success" ? "done" : "failed", state };
650
+ }
651
+
201
652
  /** The Stage check pipelines: find the pull request, mark `pending`, (agent), write the check. */
202
- function checked(stage, { target, start, check, checkEnv = () => ({}), needsRun }, commands) {
653
+ function checked(stage, { target, start, check }, commands) {
203
654
  return async (ctx) => {
204
655
  const found = step(target, ctx, ["--issue", String(ctx.issue)]);
205
656
  if (found.code !== 0) return { outcome: "failed", code: found.code };
@@ -207,11 +658,7 @@ function checked(stage, { target, start, check, checkEnv = () => ({}), needsRun
207
658
  if (ctx.trace) ctx.trace.head = sha;
208
659
  step(start, ctx, ["--sha", sha]);
209
660
  if (ctx.signal.aborted) return { outcome: "cancelled" };
210
- const args =
211
- stage === "security"
212
- ? ["--sha", sha]
213
- : ["--sha", sha, "--pr", pr, ...(needsRun ? ["--run-id", String(ctx.runId())] : [])];
214
- const done = step(check, ctx, args, checkEnv(ctx));
661
+ const done = step(check, ctx, ["--sha", sha, "--pr", pr]);
215
662
  const state = done.outputs.state;
216
663
  release(ctx, stage, state === "success" ? 0 : 1, undefined, commands);
217
664
  return { outcome: state === "success" ? "done" : "failed", state };
@@ -241,21 +688,7 @@ export function createPipelines(overrides = {}, { factory = false, pumpMs } = {}
241
688
  : {}),
242
689
  plan: (ctx) => plan(ctx, c),
243
690
  qa: checked("qa", { target: c.qaTarget, start: c.qaStart, check: c.qaCheck }, c),
244
- review: checked(
245
- "review",
246
- { target: c.reviewTarget, start: c.reviewStart, check: c.reviewCheck, needsRun: true },
247
- c,
248
- ),
249
- // No audit ran here: the verdict is `skipped`, which the check writes as held.
250
- security: checked(
251
- "security",
252
- {
253
- target: c.securityTarget,
254
- start: c.securityStart,
255
- check: c.securityCheck,
256
- checkEnv: () => ({ AUDIT_JOB_RESULT: "skipped", AUDIT_RESULT: "" }),
257
- },
258
- c,
259
- ),
691
+ review: (ctx) => review(ctx, c),
692
+ security: (ctx) => security(ctx, c),
260
693
  };
261
694
  }
@@ -5,11 +5,13 @@
5
5
  // a different one, is refused. A token whose reach cannot be read is let through with a
6
6
  // notice; a fine-grained token's own settings still bound it.
7
7
 
8
+ import { PAT_PERMISSIONS, patPermissionsSummary } from "../setup/command.mjs";
9
+
8
10
  /**
9
- * @param {{ gh: (args: string[]) => { status: number | null, stdout: string, stderr: string }, repo: string, token: string }} deps
11
+ * @param {{ gh: (args: string[]) => { status: number | null, stdout: string, stderr: string }, repo: string, token: string, permissions?: typeof PAT_PERMISSIONS }} deps
10
12
  * @returns {{ login: string, notice?: string } | { refused: string }}
11
13
  */
12
- export function checkToken({ gh, repo, token }) {
14
+ export function checkToken({ gh, repo, token, permissions = PAT_PERMISSIONS }) {
13
15
  if (token.startsWith("ghp_")) {
14
16
  return {
15
17
  refused: `the token is a classic token, which reaches every repository its owner can, not only ${repo}: make a fine-grained token for this one repository`,
@@ -62,7 +64,7 @@ export function checkToken({ gh, repo, token }) {
62
64
  }
63
65
  if (!here)
64
66
  return {
65
- refused: `the token does not reach ${repo}: it needs Contents, Issues, Pull requests and Statuses write there`,
67
+ refused: `the token does not reach ${repo}: it needs ${patPermissionsSummary(permissions)} there`,
66
68
  };
67
69
  return { login };
68
70
  }