agent-dealer 1.4.5 → 1.4.6

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.
@@ -25,6 +25,47 @@ export function parsePrView(json) {
25
25
  };
26
26
  }
27
27
  export const PR_VIEW_FIELDS = "number,url,baseRefName,headRefName,headRefOid,isDraft";
28
+ /** A `gh` checks read denied for permissions — never a transient failure. */
29
+ export class ChecksPermissionError extends Error {
30
+ source;
31
+ constructor(source, detail) {
32
+ super(detail);
33
+ this.name = "ChecksPermissionError";
34
+ this.source = source;
35
+ }
36
+ }
37
+ /**
38
+ * Neither the check rollup nor the fallback sources could be read — the token
39
+ * lacks Checks read and at least one of actions:read / commit statuses:read.
40
+ * Callers route this straight to a human with the message; no retry can help.
41
+ */
42
+ export class ChecksUnreadableError extends Error {
43
+ constructor(message) {
44
+ super(message);
45
+ this.name = "ChecksUnreadableError";
46
+ }
47
+ }
48
+ /** GitHub's permission-denial wording across GraphQL (`gh pr view`) and REST (`gh api`) reads. */
49
+ export function isChecksPermissionMessage(text) {
50
+ return /resource not accessible by/i.test(text) || /http 403\b/i.test(text);
51
+ }
52
+ function ghErrorText(err) {
53
+ const holder = err;
54
+ if (typeof holder?.stderr === "string" && holder.stderr)
55
+ return holder.stderr;
56
+ return err instanceof Error ? err.message : String(err);
57
+ }
58
+ /**
59
+ * Re-raises a `gh` throw as `ChecksPermissionError` when it is a permission
60
+ * denial; anything else (network, 5xx, malformed output) is rethrown as-is so
61
+ * callers keep today's infra-retry path for it.
62
+ */
63
+ function throwAsChecksPermissionError(err, source) {
64
+ const text = ghErrorText(err);
65
+ if (isChecksPermissionMessage(text))
66
+ throw new ChecksPermissionError(source, text);
67
+ throw err;
68
+ }
28
69
  /** Normalizes `gh pr view --json mergeable` output; anything unrecognized is UNKNOWN. */
29
70
  export function parsePrMergeableState(raw) {
30
71
  return raw === "CONFLICTING" || raw === "MERGEABLE" ? raw : "UNKNOWN";
@@ -420,6 +461,186 @@ async function ghPrView(exec, cwd, fields, selector) {
420
461
  throw new Error(`gh pr view failed: ${message}`);
421
462
  }
422
463
  }
464
+ function actionsRunTime(run) {
465
+ for (const candidate of [run.run_started_at, run.created_at]) {
466
+ if (typeof candidate !== "string" || !candidate)
467
+ continue;
468
+ const time = Date.parse(candidate);
469
+ if (Number.isFinite(time))
470
+ return time;
471
+ }
472
+ return null;
473
+ }
474
+ /**
475
+ * NOT-670, consistent with NOT-629's newest-run-wins rule: re-runs share the
476
+ * commit SHA, so keep only the newest run per workflow (`workflow_id`, by
477
+ * `run_started_at`/`created_at`) — an older failure must not shadow a newer
478
+ * success. Runs whose age cannot be established are kept, like `newestChecks`'
479
+ * untimed entries.
480
+ */
481
+ function newestRunsPerWorkflow(runs) {
482
+ const bestByWorkflow = new Map();
483
+ const unkeyed = [];
484
+ for (const run of runs) {
485
+ const workflowId = run.workflow_id;
486
+ const time = actionsRunTime(run);
487
+ if (typeof workflowId !== "number" || time == null) {
488
+ unkeyed.push(run);
489
+ continue;
490
+ }
491
+ const current = bestByWorkflow.get(workflowId);
492
+ if (current == null || time >= current.time)
493
+ bestByWorkflow.set(workflowId, { run, time });
494
+ }
495
+ return [...bestByWorkflow.values()].map((v) => v.run).concat(unkeyed);
496
+ }
497
+ function asNonEmptyString(value) {
498
+ return typeof value === "string" && value.trim() ? value : undefined;
499
+ }
500
+ /**
501
+ * An Actions run as a `RawCheck` for the shared `summarizeChecks` verdict:
502
+ * scheduling/running `status` reads pending, completed runs are judged by
503
+ * `conclusion`. `workflowName` carries the workflow id (not the display name)
504
+ * so two workflows that share a display name can never merge in `newestChecks`.
505
+ */
506
+ function actionsRunToRawCheck(run) {
507
+ const name = asNonEmptyString(run.name)?.trim().slice(0, 200) ?? `actions run ${typeof run.id === "number" ? run.id : "unknown"}`;
508
+ return {
509
+ name,
510
+ workflowName: typeof run.workflow_id === "number" ? `actions-workflow-${run.workflow_id}` : name,
511
+ status: asNonEmptyString(run.status),
512
+ conclusion: asNonEmptyString(run.conclusion),
513
+ detailsUrl: asNonEmptyString(run.html_url),
514
+ startedAt: asNonEmptyString(run.run_started_at) ?? asNonEmptyString(run.created_at),
515
+ completedAt: asNonEmptyString(run.updated_at),
516
+ };
517
+ }
518
+ /** A commit status as a `RawCheck` — judged by its `state` under its `context`. */
519
+ function commitStatusToRawCheck(status) {
520
+ return {
521
+ context: asNonEmptyString(status.context),
522
+ state: asNonEmptyString(status.state),
523
+ targetUrl: asNonEmptyString(status.target_url),
524
+ startedAt: asNonEmptyString(status.updated_at),
525
+ createdAt: asNonEmptyString(status.created_at),
526
+ };
527
+ }
528
+ /** `owner`/`repo` from a PR URL (`https://<host>/<owner>/<repo>/pull/<n>`). */
529
+ function parseRepoSlugFromPrUrl(url) {
530
+ if (typeof url !== "string")
531
+ return null;
532
+ const match = url.match(/^https?:\/\/[^/]+\/([^/]+)\/([^/]+)\/pull\/\d+/i);
533
+ if (!match)
534
+ return null;
535
+ return { owner: match[1], repo: match[2].replace(/\.git$/, "") };
536
+ }
537
+ function formatChecksUnreadableMessage(slug, denied) {
538
+ const where = slug ? `${slug.owner}/${slug.repo}` : "this repository";
539
+ const names = denied.map((d) => (d === "actions" ? "Actions: read" : "Commit statuses: read")).join(" / ");
540
+ const grants = denied.map((d) => (d === "actions" ? "actions:read" : "commit statuses:read")).join(" and ");
541
+ return (`Cannot read PR checks for ${where}: the GitHub token lacks Checks read, ` +
542
+ `and the fallback also failed (${names}). ` +
543
+ `Grant ${grants} to the fine-grained token, or use a token with Checks access.`);
544
+ }
545
+ async function readStatusCheckRollup(exec, cwd, selector) {
546
+ try {
547
+ return await ghPrView(exec, cwd, "statusCheckRollup", selector);
548
+ }
549
+ catch (err) {
550
+ throwAsChecksPermissionError(err, "checks");
551
+ }
552
+ }
553
+ async function readActionsRunsForHead(exec, cwd, path) {
554
+ let stdout;
555
+ try {
556
+ ({ stdout } = await exec(["api", path], { cwd }));
557
+ }
558
+ catch (err) {
559
+ throwAsChecksPermissionError(err, "actions");
560
+ }
561
+ const parsed = JSON.parse(stdout);
562
+ const runs = Array.isArray(parsed?.workflow_runs) ? parsed.workflow_runs : [];
563
+ return newestRunsPerWorkflow(runs);
564
+ }
565
+ async function readCommitStatuses(exec, cwd, path) {
566
+ let stdout;
567
+ try {
568
+ ({ stdout } = await exec(["api", path], { cwd }));
569
+ }
570
+ catch (err) {
571
+ throwAsChecksPermissionError(err, "statuses");
572
+ }
573
+ const parsed = JSON.parse(stdout);
574
+ // Only the individual entries are judged — GitHub reports combined `pending`
575
+ // when NO statuses exist, so an empty array contributes nothing.
576
+ return Array.isArray(parsed?.statuses) ? parsed.statuses : [];
577
+ }
578
+ /**
579
+ * NOT-670 fallback when the check rollup is denied for permissions: read the PR
580
+ * head SHA (readable without Checks), then judge the same verdict from the
581
+ * Actions runs plus commit statuses on that SHA through the shared
582
+ * `summarizeChecks`. No runs and no statuses is `none`, so the NOT-311 none
583
+ * streak and `hasPullRequestWorkflow` wait logic still applies.
584
+ *
585
+ * A permission denial on either fallback source raises `ChecksUnreadableError`
586
+ * naming the missing permission(s) — judging on a partial read could wave a
587
+ * handoff through past an invisible failure. Non-permission errors propagate
588
+ * exactly as the rollup read's would.
589
+ */
590
+ async function checksSnapshotFallback(exec, opts) {
591
+ let head;
592
+ try {
593
+ head = await ghPrView(exec, opts.cwd, "headRefOid,url", opts.selector);
594
+ }
595
+ catch (err) {
596
+ // The head SHA bootstraps the fallback, so its denial cannot fall through
597
+ // to another source — it is already the end of the road.
598
+ if (isChecksPermissionMessage(ghErrorText(err))) {
599
+ throw new ChecksUnreadableError("Cannot read PR checks: the GitHub token lacks Checks read, and the PR head SHA " +
600
+ "needed for the Actions/commit-statuses fallback is also unreadable. Grant the " +
601
+ "fine-grained token PR read plus actions:read and commit statuses:read, or use a token with Checks access.");
602
+ }
603
+ throw err;
604
+ }
605
+ // The PR vanished between the rollup read and this read — no PR, no checks,
606
+ // exactly like the rollup path's null read.
607
+ if (!head)
608
+ return "none";
609
+ const headSha = typeof head.headRefOid === "string" && head.headRefOid ? head.headRefOid : "";
610
+ if (!headSha)
611
+ throw new Error("gh pr view returned no headRefOid for the checks fallback");
612
+ const slug = parseRepoSlugFromPrUrl(head.url);
613
+ const runsPath = slug
614
+ ? `repos/${slug.owner}/${slug.repo}/actions/runs?head_sha=${headSha}&per_page=100`
615
+ : `repos/{owner}/{repo}/actions/runs?head_sha=${headSha}&per_page=100`;
616
+ const statusPath = slug
617
+ ? `repos/${slug.owner}/${slug.repo}/commits/${headSha}/status`
618
+ : `repos/{owner}/{repo}/commits/${headSha}/status`;
619
+ // Both sources are always attempted so the unreadable error names every
620
+ // missing permission, not just the first denial.
621
+ const denied = [];
622
+ let runs = [];
623
+ let statuses = [];
624
+ try {
625
+ runs = await readActionsRunsForHead(exec, opts.cwd, runsPath);
626
+ }
627
+ catch (err) {
628
+ if (!(err instanceof ChecksPermissionError))
629
+ throw err;
630
+ denied.push("actions");
631
+ }
632
+ try {
633
+ statuses = await readCommitStatuses(exec, opts.cwd, statusPath);
634
+ }
635
+ catch (err) {
636
+ if (!(err instanceof ChecksPermissionError))
637
+ throw err;
638
+ denied.push("statuses");
639
+ }
640
+ if (denied.length > 0)
641
+ throw new ChecksUnreadableError(formatChecksUnreadableMessage(slug, denied));
642
+ return summarizeChecks([...runs.map(actionsRunToRawCheck), ...statuses.map(commitStatusToRawCheck)]);
643
+ }
423
644
  /** Real `gh` adapter, parameterized over the shell-out so tests can assert exact CLI args without a real `gh`. */
424
645
  export function createGithubAdapter(exec = defaultExec) {
425
646
  return {
@@ -451,9 +672,18 @@ export function createGithubAdapter(exec = defaultExec) {
451
672
  },
452
673
  async checksSnapshot({ cwd, number, branch }) {
453
674
  const selector = number != null ? String(number) : branch;
454
- const raw = await ghPrView(exec, cwd, "statusCheckRollup", selector);
455
- const rollup = raw?.statusCheckRollup ?? [];
456
- return summarizeChecks(rollup);
675
+ try {
676
+ const raw = await readStatusCheckRollup(exec, cwd, selector);
677
+ const rollup = raw?.statusCheckRollup ?? [];
678
+ return summarizeChecks(rollup);
679
+ }
680
+ catch (err) {
681
+ // NOT-670: only a permission denial takes the Actions/statuses fallback —
682
+ // every other `gh` failure (network, 5xx) throws exactly as before.
683
+ if (!(err instanceof ChecksPermissionError))
684
+ throw err;
685
+ return checksSnapshotFallback(exec, { cwd, selector });
686
+ }
457
687
  },
458
688
  async fetchChecksFailureEvidence({ cwd, number, branch, expectedHeadSha, prNumber }) {
459
689
  try {
@@ -1,7 +1,7 @@
1
1
  // packages/server/src/adapters/github.test.ts
2
2
  import { test } from "node:test";
3
3
  import assert from "node:assert/strict";
4
- import { parsePrView, summarizeChecks, pollPrChecks, pollPrChecksDetailed, baseRefHasPullRequestWorkflow, workflowHasPullRequestTrigger, createGithubAdapter, fetchChecksFailureEvidence, sanitizeCiText, sanitizeUrl, extractActionsRunId, buildFailureExcerpt, formatChecksFailureDetails, CHECKS_EVIDENCE_MAX_EXCERPT_CHARS, CHECKS_EVIDENCE_MAX_EXCERPT_LINES, CHECKS_EVIDENCE_MAX_RAW_LOG_CHARS_PER_RUN, CHECKS_EVIDENCE_GH_LOG_MAX_BUFFER, CHECKS_FAILURE_GENERIC_REASON, PR_VIEW_FIELDS, parseWorkflowRunInfo, } from "./github.js";
4
+ import { ChecksPermissionError, ChecksUnreadableError, isChecksPermissionMessage, parsePrView, summarizeChecks, pollPrChecks, pollPrChecksDetailed, baseRefHasPullRequestWorkflow, workflowHasPullRequestTrigger, createGithubAdapter, fetchChecksFailureEvidence, sanitizeCiText, sanitizeUrl, extractActionsRunId, buildFailureExcerpt, formatChecksFailureDetails, CHECKS_EVIDENCE_MAX_EXCERPT_CHARS, CHECKS_EVIDENCE_MAX_EXCERPT_LINES, CHECKS_EVIDENCE_MAX_RAW_LOG_CHARS_PER_RUN, CHECKS_EVIDENCE_GH_LOG_MAX_BUFFER, CHECKS_FAILURE_GENERIC_REASON, PR_VIEW_FIELDS, parseWorkflowRunInfo, } from "./github.js";
5
5
  test("parsePrView extracts the ground-truth handoff fields, including draft status", () => {
6
6
  const view = parsePrView(JSON.stringify({
7
7
  number: 7,
@@ -1035,3 +1035,179 @@ test("AGENT_DEALER_REVIEWER_GH_TOKEN: non-review gh calls never receive the revi
1035
1035
  assert.equal(execOpts.length, 1);
1036
1036
  assert.equal(execOpts[0].env, undefined);
1037
1037
  });
1038
+ // --- NOT-670: Actions-runs + commit-statuses fallback for fine-grained PATs ---
1039
+ const NOT670_SHA = "29ddecffa76869075eb0dbd03779f422ec5cac69";
1040
+ const NOT670_PR_URL = "https://github.com/not-so-fat/agent-box/pull/4";
1041
+ /** The exact denial the box token hits on private repos (agent-box PR #4). */
1042
+ const NOT670_ROLLUP_DENIAL = "GraphQL: Resource not accessible by personal access token (repository.pullRequest.statusCheckRollup.nodes.0.commit.statusCheckRollup.contexts.nodes.0)";
1043
+ function not670ActionsRuns(runs) {
1044
+ return JSON.stringify({ total_count: runs.length, workflow_runs: runs });
1045
+ }
1046
+ function not670Run(overrides = {}) {
1047
+ return {
1048
+ id: 45683890522,
1049
+ name: "ci",
1050
+ workflow_id: 11,
1051
+ head_sha: NOT670_SHA,
1052
+ status: "completed",
1053
+ conclusion: "success",
1054
+ created_at: "2026-11-25T10:00:00Z",
1055
+ run_started_at: "2026-11-25T10:00:05Z",
1056
+ updated_at: "2026-11-25T10:05:00Z",
1057
+ html_url: "https://github.com/not-so-fat/agent-box/actions/runs/45683890522",
1058
+ ...overrides,
1059
+ };
1060
+ }
1061
+ /** Rollup denial, then the readable head SHA + PR URL that bootstraps the fallback. */
1062
+ function not670DeniedRollup() {
1063
+ return [
1064
+ { error: NOT670_ROLLUP_DENIAL },
1065
+ { stdout: JSON.stringify({ headRefOid: NOT670_SHA, url: NOT670_PR_URL }) },
1066
+ ];
1067
+ }
1068
+ test("NOT-670: readable checks take the unchanged path — no actions/runs or status call", async () => {
1069
+ const { exec, calls } = queuedExec([
1070
+ { stdout: JSON.stringify({ statusCheckRollup: [{ conclusion: "success" }] }) },
1071
+ ]);
1072
+ const snapshot = await createGithubAdapter(exec).checksSnapshot({ cwd: "/repo", number: 42 });
1073
+ assert.equal(snapshot, "success");
1074
+ assert.deepEqual(calls, [["pr", "view", "42", "--json", "statusCheckRollup"]]);
1075
+ assert.ok(calls.every((args) => !args.some((a) => a.includes("actions/runs") || a.includes("/status"))), "no fallback call on the readable path");
1076
+ });
1077
+ test("NOT-670: rollup permission error with Actions completed/success (statuses empty, combined pending) returns success", async () => {
1078
+ const { exec, calls } = queuedExec([
1079
+ ...not670DeniedRollup(),
1080
+ { stdout: not670ActionsRuns([not670Run({ conclusion: "success" })]) },
1081
+ { stdout: JSON.stringify({ state: "pending", statuses: [] }) },
1082
+ ]);
1083
+ const snapshot = await createGithubAdapter(exec).checksSnapshot({ cwd: "/repo", number: 4 });
1084
+ assert.equal(snapshot, "success");
1085
+ assert.deepEqual(calls[0], ["pr", "view", "4", "--json", "statusCheckRollup"]);
1086
+ assert.deepEqual(calls[1], ["pr", "view", "4", "--json", "headRefOid,url"]);
1087
+ assert.deepEqual(calls[2], ["api", `repos/not-so-fat/agent-box/actions/runs?head_sha=${NOT670_SHA}&per_page=100`]);
1088
+ assert.deepEqual(calls[3], ["api", `repos/not-so-fat/agent-box/commits/${NOT670_SHA}/status`]);
1089
+ });
1090
+ test("NOT-670: fallback pending — an in_progress Actions run returns pending", async () => {
1091
+ const { exec } = queuedExec([
1092
+ ...not670DeniedRollup(),
1093
+ { stdout: not670ActionsRuns([not670Run({ status: "in_progress", conclusion: null })]) },
1094
+ { stdout: JSON.stringify({ state: "pending", statuses: [] }) },
1095
+ ]);
1096
+ assert.equal(await createGithubAdapter(exec).checksSnapshot({ cwd: "/repo", number: 4 }), "pending");
1097
+ });
1098
+ test("NOT-670: fallback pending — a queued run and a pending commit status return pending", async () => {
1099
+ const queued = queuedExec([
1100
+ ...not670DeniedRollup(),
1101
+ { stdout: not670ActionsRuns([not670Run({ status: "queued", conclusion: null })]) },
1102
+ { stdout: JSON.stringify({ state: "pending", statuses: [] }) },
1103
+ ]);
1104
+ assert.equal(await createGithubAdapter(queued.exec).checksSnapshot({ cwd: "/repo", number: 4 }), "pending");
1105
+ const statusPending = queuedExec([
1106
+ ...not670DeniedRollup(),
1107
+ { stdout: not670ActionsRuns([]) },
1108
+ {
1109
+ stdout: JSON.stringify({
1110
+ state: "pending",
1111
+ statuses: [{ context: "ci/external", state: "pending", target_url: "https://ci.example/r/1" }],
1112
+ }),
1113
+ },
1114
+ ]);
1115
+ assert.equal(await createGithubAdapter(statusPending.exec).checksSnapshot({ cwd: "/repo", number: 4 }), "pending");
1116
+ });
1117
+ test("NOT-670: fallback failure — a completed run with conclusion failure returns failure", async () => {
1118
+ const { exec } = queuedExec([
1119
+ ...not670DeniedRollup(),
1120
+ { stdout: not670ActionsRuns([not670Run({ conclusion: "failure" })]) },
1121
+ { stdout: JSON.stringify({ state: "pending", statuses: [] }) },
1122
+ ]);
1123
+ assert.equal(await createGithubAdapter(exec).checksSnapshot({ cwd: "/repo", number: 4 }), "failure");
1124
+ });
1125
+ test("NOT-670: a newer successful re-run of the same workflow_id supersedes an older failure", async () => {
1126
+ const { exec } = queuedExec([
1127
+ ...not670DeniedRollup(),
1128
+ {
1129
+ stdout: not670ActionsRuns([
1130
+ not670Run({ id: 1, conclusion: "failure", run_started_at: "2026-11-25T10:00:05Z", created_at: "2026-11-25T10:00:00Z" }),
1131
+ not670Run({ id: 2, conclusion: "success", run_started_at: "2026-11-25T11:00:05Z", created_at: "2026-11-25T11:00:00Z" }),
1132
+ ]),
1133
+ },
1134
+ { stdout: JSON.stringify({ state: "pending", statuses: [] }) },
1135
+ ]);
1136
+ assert.equal(await createGithubAdapter(exec).checksSnapshot({ cwd: "/repo", number: 4 }), "success");
1137
+ });
1138
+ test("NOT-670: no runs and no statuses gives none, so the NOT-311 wait logic still applies", async () => {
1139
+ const { exec } = queuedExec([
1140
+ ...not670DeniedRollup(),
1141
+ { stdout: not670ActionsRuns([]) },
1142
+ { stdout: JSON.stringify({ state: "pending", statuses: [] }) },
1143
+ ]);
1144
+ assert.equal(await createGithubAdapter(exec).checksSnapshot({ cwd: "/repo", number: 4 }), "none");
1145
+ });
1146
+ test("NOT-670: both unreadable raises the typed checks-unreadable error naming the missing permissions", async () => {
1147
+ const { exec } = queuedExec([
1148
+ ...not670DeniedRollup(),
1149
+ { error: "HTTP 403: Resource not accessible by integration" },
1150
+ { error: "HTTP 403: Resource not accessible by integration" },
1151
+ ]);
1152
+ await assert.rejects(createGithubAdapter(exec).checksSnapshot({ cwd: "/repo", number: 4 }), (err) => {
1153
+ assert.ok(err instanceof ChecksUnreadableError);
1154
+ assert.match(err.message, /Cannot read PR checks for not-so-fat\/agent-box/);
1155
+ assert.match(err.message, /lacks Checks read/);
1156
+ assert.match(err.message, /Actions: read/);
1157
+ assert.match(err.message, /Commit statuses: read/);
1158
+ assert.match(err.message, /actions:read and commit statuses:read/);
1159
+ return true;
1160
+ });
1161
+ });
1162
+ test("NOT-670: a denial on either fallback source alone also raises checks-unreadable (no partial verdicts)", async () => {
1163
+ const actionsDenied = queuedExec([
1164
+ ...not670DeniedRollup(),
1165
+ { error: "HTTP 403: Resource not accessible by integration" },
1166
+ { stdout: JSON.stringify({ state: "success", statuses: [{ context: "ci/external", state: "success" }] }) },
1167
+ ]);
1168
+ await assert.rejects(createGithubAdapter(actionsDenied.exec).checksSnapshot({ cwd: "/repo", number: 4 }), (err) => {
1169
+ assert.ok(err instanceof ChecksUnreadableError);
1170
+ assert.match(err.message, /Actions: read/);
1171
+ assert.doesNotMatch(err.message, /Commit statuses: read/);
1172
+ return true;
1173
+ });
1174
+ const statusesDenied = queuedExec([
1175
+ ...not670DeniedRollup(),
1176
+ { stdout: not670ActionsRuns([not670Run({ conclusion: "success" })]) },
1177
+ { error: "HTTP 403: Resource not accessible by integration" },
1178
+ ]);
1179
+ await assert.rejects(createGithubAdapter(statusesDenied.exec).checksSnapshot({ cwd: "/repo", number: 4 }), (err) => {
1180
+ assert.ok(err instanceof ChecksUnreadableError);
1181
+ assert.match(err.message, /Commit statuses: read/);
1182
+ assert.doesNotMatch(err.message, /Actions: read/);
1183
+ return true;
1184
+ });
1185
+ });
1186
+ test("NOT-670: permission detection recognizes PAT/integration denials and HTTP 403, not transient failures", () => {
1187
+ assert.equal(isChecksPermissionMessage(NOT670_ROLLUP_DENIAL), true);
1188
+ assert.equal(isChecksPermissionMessage("HTTP 403: Resource not accessible by integration (https://api.github.com/...)"), true);
1189
+ assert.equal(isChecksPermissionMessage("gh pr view failed: GraphQL: Resource not accessible by personal access token (x)"), true);
1190
+ assert.equal(isChecksPermissionMessage("failed to connect: dial tcp: lookup api.github.com: no such host"), false);
1191
+ assert.equal(isChecksPermissionMessage("HTTP 502 Bad Gateway"), false);
1192
+ assert.ok(new ChecksPermissionError("checks", "denied") instanceof Error);
1193
+ });
1194
+ test("NOT-670: a non-permission gh failure still throws without touching the fallback", async () => {
1195
+ const { exec, calls } = queuedExec([{ error: "failed to connect: dial tcp: lookup api.github.com: no such host" }]);
1196
+ await assert.rejects(createGithubAdapter(exec).checksSnapshot({ cwd: "/repo", number: 4 }), /gh pr view failed/);
1197
+ assert.equal(calls.length, 1, "no fallback call after a transient rollup failure");
1198
+ });
1199
+ test("NOT-670: a non-permission fallback failure propagates as-is instead of checks-unreadable", async () => {
1200
+ const { exec } = queuedExec([
1201
+ ...not670DeniedRollup(),
1202
+ { error: "HTTP 502 Bad Gateway" },
1203
+ ]);
1204
+ await assert.rejects(createGithubAdapter(exec).checksSnapshot({ cwd: "/repo", number: 4 }), (err) => {
1205
+ assert.ok(!(err instanceof ChecksUnreadableError));
1206
+ assert.match(String(err), /502/);
1207
+ return true;
1208
+ });
1209
+ });
1210
+ test("NOT-670: fetchChecksFailureEvidence still degrades to null when the rollup is unreadable", async () => {
1211
+ const { exec } = queuedExec([{ error: NOT670_ROLLUP_DENIAL }]);
1212
+ assert.equal(await fetchChecksFailureEvidence(exec, { cwd: "/repo", number: 4, expectedHeadSha: NOT670_SHA, prNumber: 4 }), null);
1213
+ });
@@ -32,7 +32,7 @@ import { recordIssueBaseSha } from "../repository/issues.js";
32
32
  import { ensureIssueRepoCheckout, roleWorktreePathForResolution, resolveCheckoutBaseBranch, } from "../adapters/managed-repo.js";
33
33
  import { baseRefCandidates, inspectBranchProgress } from "./branch-progress.js";
34
34
  import { prepareWorkerDeckConnection, releaseWorkerDeckConnection, verifyWorkerDeckConnection } from "../adapters/agent-deck-bind.js";
35
- import { realGithubAdapter, pollPrChecksDetailed, } from "../adapters/github.js";
35
+ import { ChecksUnreadableError, realGithubAdapter, pollPrChecksDetailed, } from "../adapters/github.js";
36
36
  import { checksWaitCeilingExceeded, checksWaitCeilingMs } from "./checks-wait-config.js";
37
37
  import { museCapabilitySafetyNetAfterSession } from "../adapters/muse-capability.js";
38
38
  import { getOrAssignSessionCorrelationId, getWorkerSession, mergeSessionMetadata, patchRunningSession, recordSessionProcess, setSessionInputSha } from "../repository/worker-sessions.js";
@@ -898,6 +898,12 @@ async function runPublishOnlyHandoff(ctx, deps, branchName) {
898
898
  };
899
899
  }
900
900
  catch (err) {
901
+ // NOT-670: unreadable checks (token lacks Checks read and the fallback is
902
+ // denied too) is a permission problem, not infra — escalate once without
903
+ // spending an attempt instead of entering the adapter_failure retry loop.
904
+ if (err instanceof ChecksUnreadableError) {
905
+ return { kind: "checks_unreadable", reason: err.message };
906
+ }
901
907
  return {
902
908
  kind: "adapter_failure",
903
909
  reason: String(err),
@@ -2161,6 +2167,10 @@ export async function runDeveloperEffect(ctx, deps = defaultDeps) {
2161
2167
  console.error("[coordinator] developer session could not start", { issueId: issue.id, sessionId, round, err });
2162
2168
  return { kind: "session_failed", reason };
2163
2169
  }
2170
+ // NOT-670: same permission short-circuit as the publish-only path above.
2171
+ if (err instanceof ChecksUnreadableError) {
2172
+ return { kind: "checks_unreadable", reason: err.message };
2173
+ }
2164
2174
  return { kind: "adapter_failure", reason: String(err) };
2165
2175
  }
2166
2176
  finally {
@@ -33,7 +33,7 @@ const { registerEffectHandler, resetEffectHandlers } = await import("./effect-re
33
33
  const { runCoordinatorTick, drainCoordinator } = await import("./worker-loop.js");
34
34
  const { runDeveloperEffect, extractPrDescription } = await import("./developer-effect.js");
35
35
  const { realDeveloperSpawn } = await import("./spawn.js");
36
- const { realGithubAdapter } = await import("../adapters/github.js");
36
+ const { realGithubAdapter, ChecksUnreadableError } = await import("../adapters/github.js");
37
37
  const { branchExists, roleWorktreePath, withRepoLock, observeGitCommands } = await import("../adapters/git-worktree.js");
38
38
  before(() => migrate());
39
39
  // NOT-220's test runs reviewer effects, which record review_publications rows keyed
@@ -243,6 +243,31 @@ test("clean handoff: real worktree, real push, fake GitHub — issue moves to re
243
243
  assert.ok(finished);
244
244
  assert.equal(finished.actorType, "developer");
245
245
  });
246
+ test("NOT-670: unreadable checks land in needs_human once with the permission message and no infra attempt spent", async () => {
247
+ const issueId = await makeIssue();
248
+ const github = fakeGithub();
249
+ github.checksSnapshot = async () => {
250
+ throw new ChecksUnreadableError("Cannot read PR checks for not-so-fat/agent-box: the GitHub token lacks Checks read, " +
251
+ "and the fallback also failed (Actions: read / Commit statuses: read). Grant actions:read " +
252
+ "and commit statuses:read to the fine-grained token, or use a token with Checks access.");
253
+ };
254
+ registerEffectHandler("developer", (ctx) => runDeveloperEffect(ctx, { deckCallTool: okDeckCallTool, spawn: commitingSpawn, github }));
255
+ startWorkflow(issueId);
256
+ await pump(1);
257
+ const issue = getIssue(issueId);
258
+ assert.equal(issue.status, "needs_human");
259
+ assert.equal(issue.infraAttempts, 0, "a permission problem never spends an infra attempt");
260
+ assert.equal(issue.currentRound, 1);
261
+ assert.equal(listWorkItemsForIssue(issueId).filter((i) => i.kind === "reviewer").length, 0);
262
+ assert.equal(listWorkItemsForIssue(issueId).filter((i) => i.kind === "developer" && i.status === "pending").length, 0, "no developer retry is queued");
263
+ const action = listHumanActionsForIssue(issueId).find((a) => a.actionType === "policy_escalation");
264
+ assert.ok(action, "expected a single policy_escalation human action");
265
+ assert.match(action.reason, /Cannot read PR checks for not-so-fat\/agent-box/);
266
+ assert.match(action.reason, /Actions: read/);
267
+ assert.match(action.reason, /Commit statuses: read/);
268
+ assert.match(action.reason, /Checks/);
269
+ assert.doesNotMatch(action.reason, /infra-attempt limit reached/);
270
+ });
246
271
  test("no_pr: the agent makes no commits — retried, no reviewer work item", async () => {
247
272
  const issueId = await makeIssue();
248
273
  registerEffectHandler("developer", (ctx) => runDeveloperEffect(ctx, { deckCallTool: okDeckCallTool, spawn: noopSpawn, github: fakeGithub() }));
@@ -224,6 +224,8 @@ function fallbackReasonForKind(outcome) {
224
224
  return "muse_cron_used: the Muse session called a cron_* tool, which Muse cannot disable.";
225
225
  case "adapter_failure":
226
226
  return "Git/GitHub verification failed.";
227
+ case "checks_unreadable":
228
+ return "PR checks cannot be read with the current GitHub token.";
227
229
  case "deck_failure":
228
230
  return "Agent Deck preflight failed.";
229
231
  case "deck_unavailable":
@@ -277,6 +279,7 @@ export function outcomeShouldRecordError(outcome) {
277
279
  outcome.kind === "no_pr" ||
278
280
  outcome.kind === "checks_failed" ||
279
281
  outcome.kind === "adapter_failure" ||
282
+ outcome.kind === "checks_unreadable" ||
280
283
  outcome.kind === "deck_failure" ||
281
284
  outcome.kind === "unpushed_commit" ||
282
285
  outcome.kind === "worktree_conflict" ||
@@ -60,7 +60,7 @@ import { cancelWorkItem, enqueueWorkItem, finishWorkItem, listWorkItemsForIssue,
60
60
  import { appendWorkflowEvent, getActiveWorkflowInstance, listWorkflowEventsForIssue, } from "../repository/workflow-events.js";
61
61
  import { addWorktree, DEFAULT_BASE_FETCH_TIMEOUT_MS, fastForwardLocalBranchToSha, fetchFreshBase, fetchReusedBranch, findWorktreeForBranch, isAncestor, isWorktreeClean, pruneWorktrees, removeWorktree, revParseHead, safeRemoveWorktree, } from "../adapters/git-worktree.js";
62
62
  import { classifyIssueRepo, worktreesRootForResolution, } from "../adapters/managed-repo.js";
63
- import { pollPrChecks, realGithubAdapter, } from "../adapters/github.js";
63
+ import { ChecksUnreadableError, pollPrChecks, realGithubAdapter, } from "../adapters/github.js";
64
64
  import { withRepoLock } from "../runners/process-registry.js";
65
65
  import { checkDeveloperWorktreeOwnerLiveness } from "./worktree-owner-liveness.js";
66
66
  import { buildProfileSnapshot, serializeProfileSnapshot } from "./profile-snapshot.js";
@@ -839,6 +839,10 @@ export async function runMergeConflictSync(opts) {
839
839
  }
840
840
  catch (err) {
841
841
  await cleanupSyncCheckout(repoPath, syncPath);
842
+ // NOT-670: surface the missing-permission message as-is so the operator
843
+ // sees what to grant, not a generic poll error.
844
+ if (err instanceof ChecksUnreadableError)
845
+ return failed(err.message);
842
846
  const detail = err instanceof Error ? err.message : String(err);
843
847
  return failed(`checks poll errored: ${detail}`);
844
848
  }
@@ -111,6 +111,11 @@ export function routeDeveloperOutcome(outcome, limits) {
111
111
  ? { next: "retry_developer", reason }
112
112
  : { next: "human_action", actionType: "policy_escalation", reason: `${reason} (infra-attempt limit reached).` };
113
113
  }
114
+ case "checks_unreadable":
115
+ // NOT-670: a missing GitHub permission — retrying the developer (or the
116
+ // poll) cannot grant it, so escalate once with the exact message: no
117
+ // infra attempt spent, no retry, no limit-reached suffix.
118
+ return { next: "human_action", actionType: "policy_escalation", reason: outcome.reason };
114
119
  case "no_pr":
115
120
  case "deck_failure": {
116
121
  // Unified infra-failure policy: the session/environment failed to produce a
@@ -260,6 +260,38 @@ test("adapter failure escalates once the infra-attempt limit is reached", () =>
260
260
  assert.equal(result.next, "human_action");
261
261
  assert.equal(result.actionType, "policy_escalation");
262
262
  });
263
+ test("NOT-670: unreadable checks escalate once with the missing-permission message, spending no infra attempt", () => {
264
+ const outcome = {
265
+ kind: "checks_unreadable",
266
+ reason: "Cannot read PR checks for not-so-fat/agent-box: the GitHub token lacks Checks read, " +
267
+ "and the fallback also failed (Actions: read / Commit statuses: read). Grant actions:read " +
268
+ "and commit statuses:read to the fine-grained token, or use a token with Checks access.",
269
+ };
270
+ // Fresh budget and exhausted budget route identically — a permission problem is
271
+ // never retried, so the infra-attempt count is untouched either way.
272
+ for (const limits of [INFRA_ATTEMPTS_LEFT, INFRA_AT_LIMIT]) {
273
+ assert.deepStrictEqual(routeDeveloperOutcome(outcome, limits), {
274
+ next: "human_action",
275
+ actionType: "policy_escalation",
276
+ reason: outcome.reason,
277
+ });
278
+ }
279
+ const result = routeDeveloperOutcome(outcome, INFRA_ATTEMPTS_LEFT);
280
+ assert.match(result.reason, /Actions: read/);
281
+ assert.match(result.reason, /Commit statuses: read/);
282
+ assert.match(result.reason, /Checks/);
283
+ assert.doesNotMatch(result.reason, /infra-attempt limit reached/);
284
+ });
285
+ test("NOT-670: a non-permission gh failure keeps the adapter_failure infra-retry path", () => {
286
+ const outcome = {
287
+ kind: "adapter_failure",
288
+ reason: "Error: gh pr view failed: failed to connect: dial tcp: lookup api.github.com: no such host",
289
+ };
290
+ assert.deepStrictEqual(routeDeveloperOutcome(outcome, INFRA_ATTEMPTS_LEFT), {
291
+ next: "retry_developer",
292
+ reason: `Git/GitHub verification failed: ${outcome.reason}`,
293
+ });
294
+ });
263
295
  test("timed_out with infra attempts remaining retries (same bucket as session_failed/no_pr)", () => {
264
296
  const outcome = { kind: "timed_out" };
265
297
  assert.deepStrictEqual(routeDeveloperOutcome(outcome, INFRA_ATTEMPTS_LEFT), {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agent-dealer/server",
3
- "version": "1.4.5",
3
+ "version": "1.4.6",
4
4
  "type": "module",
5
5
  "main": "dist/index.js",
6
6
  "files": [
@@ -23,7 +23,7 @@
23
23
  "test": "AGENT_DEALER_SKIP_GITHUB_HEALTH=1 AGENT_DEALER_SKIP_AGENT_HEALTH=1 npm run build -w @agent-dealer/shared && AGENT_DEALER_SKIP_GITHUB_HEALTH=1 AGENT_DEALER_SKIP_AGENT_HEALTH=1 node ../../scripts/run-workspace-tests.mjs"
24
24
  },
25
25
  "dependencies": {
26
- "@agent-dealer/shared": "1.4.5",
26
+ "@agent-dealer/shared": "1.4.6",
27
27
  "@fastify/cors": "^11.0.1",
28
28
  "@fastify/static": "^8.2.0",
29
29
  "@modelcontextprotocol/sdk": "^1.29.0",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agent-dealer/shared",
3
- "version": "1.4.5",
3
+ "version": "1.4.6",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-dealer",
3
- "version": "1.4.5",
3
+ "version": "1.4.6",
4
4
  "description": "Human control plane for agent execution — queue, plan approval, audit",
5
5
  "license": "MIT",
6
6
  "type": "module",