agent-dealer 1.4.4 → 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.
Files changed (70) hide show
  1. package/bundle/server/dist/adapters/github.js +233 -3
  2. package/bundle/server/dist/adapters/github.test.js +177 -1
  3. package/bundle/server/dist/adapters/muse-capability.js +81 -8
  4. package/bundle/server/dist/adapters/muse-capability.test.js +89 -1
  5. package/bundle/server/dist/coordinator/commands.js +2 -1
  6. package/bundle/server/dist/coordinator/developer-effect.js +11 -1
  7. package/bundle/server/dist/coordinator/developer-effect.test.js +26 -1
  8. package/bundle/server/dist/coordinator/failure-reason.js +3 -0
  9. package/bundle/server/dist/coordinator/merge-conflict-sync.js +5 -1
  10. package/bundle/server/dist/coordinator/routing.js +5 -0
  11. package/bundle/server/dist/coordinator/routing.test.js +32 -0
  12. package/bundle/server/package.json +2 -2
  13. package/bundle/server/static-ui/assets/index-2IuALSbV.js +64 -0
  14. package/bundle/server/static-ui/assets/index-MgimDoh2.css +1 -0
  15. package/bundle/server/static-ui/index.html +2 -2
  16. package/bundle/shared/package.json +1 -1
  17. package/dist/bin.js +0 -0
  18. package/package.json +2 -3
  19. package/bundle/server/dist/adapters/authority-lifecycle.js +0 -289
  20. package/bundle/server/dist/adapters/execution-authority.js +0 -103
  21. package/bundle/server/dist/adapters/execution-authority.test.js +0 -166
  22. package/bundle/server/dist/adapters/external.js +0 -20
  23. package/bundle/server/dist/coordinator/authority-recovery.integration.test.js +0 -661
  24. package/bundle/server/dist/coordinator/dispatcher.js +0 -58
  25. package/bundle/server/dist/coordinator/dispatcher.test.js +0 -81
  26. package/bundle/server/dist/coordinator/intent-forecast.js +0 -13
  27. package/bundle/server/dist/coordinator/intent-forecast.test.js +0 -34
  28. package/bundle/server/dist/coordinator/session-lifecycle.integration.test.js +0 -127
  29. package/bundle/server/dist/coordinator/session-lifecycle.js +0 -280
  30. package/bundle/server/dist/coordinator/session-lifecycle.test.js +0 -121
  31. package/bundle/server/dist/db/authority-attempts-stale-at-migration.test.js +0 -65
  32. package/bundle/server/dist/intake/agent-routing.js +0 -32
  33. package/bundle/server/dist/queue/answers.test.js +0 -117
  34. package/bundle/server/dist/queue/dispatcher-recovery.test.js +0 -37
  35. package/bundle/server/dist/queue/dispatcher.js +0 -597
  36. package/bundle/server/dist/queue/plan-delegation.js +0 -27
  37. package/bundle/server/dist/queue/plan-delegation.test.js +0 -61
  38. package/bundle/server/dist/queue/plan-gate.test.js +0 -55
  39. package/bundle/server/dist/queue/result-qa.js +0 -66
  40. package/bundle/server/dist/queue/result-qa.test.js +0 -146
  41. package/bundle/server/dist/repository/authority-attempts.js +0 -189
  42. package/bundle/server/dist/repository/result-qa.js +0 -37
  43. package/bundle/server/dist/runners/codex-args.js +0 -59
  44. package/bundle/server/dist/runners/codex-args.test.js +0 -72
  45. package/bundle/server/dist/runners/codex-resume.test.js +0 -19
  46. package/bundle/server/dist/runners/codex.js +0 -46
  47. package/bundle/server/dist/runners/muse-code-settings.js +0 -23
  48. package/bundle/server/dist/runners/muse-code-settings.test.js +0 -18
  49. package/bundle/server/dist/runners/persist.js +0 -142
  50. package/bundle/server/dist/runners/qa.js +0 -54
  51. package/bundle/server/dist/runners/run-context.js +0 -183
  52. package/bundle/server/dist/runners/stream-json.test.js +0 -95
  53. package/bundle/server/dist/trace-summary.js +0 -93
  54. package/bundle/server/dist/usage-summary.js +0 -61
  55. package/bundle/server/dist/usage-summary.test.js +0 -33
  56. package/bundle/server/static-ui/assets/index-CHCiztRI.css +0 -1
  57. package/bundle/server/static-ui/assets/index-CrLQFFpw.js +0 -64
  58. package/bundle/server/static-ui/fonts/Monaco.ttf +0 -0
  59. package/bundle/shared/dist/cursor-auth-health.d.ts +0 -12
  60. package/bundle/shared/dist/cursor-auth-health.js +0 -36
  61. package/bundle/shared/dist/cursor-auth-health.test.d.ts +0 -1
  62. package/bundle/shared/dist/cursor-auth-health.test.js +0 -40
  63. package/bundle/shared/dist/plan-triage.d.ts +0 -317
  64. package/bundle/shared/dist/plan-triage.js +0 -65
  65. package/bundle/shared/dist/plan-triage.test.d.ts +0 -1
  66. package/bundle/shared/dist/plan-triage.test.js +0 -66
  67. package/bundle/shared/dist/result-qa.d.ts +0 -45
  68. package/bundle/shared/dist/result-qa.js +0 -25
  69. package/bundle/shared/dist/result-qa.test.d.ts +0 -1
  70. package/bundle/shared/dist/result-qa.test.js +0 -60
@@ -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
+ });
@@ -67,7 +67,7 @@ function normalizeChecked(raw, currentVersion) {
67
67
  const c = raw;
68
68
  if (typeof c.version !== "string" || c.version !== currentVersion)
69
69
  return null;
70
- if (c.status !== "capable" && c.status !== "missing" && c.status !== "error")
70
+ if (c.status !== "capable" && c.status !== "missing" && c.status !== "host-sandbox" && c.status !== "error")
71
71
  return null;
72
72
  if (typeof c.checkedAt !== "number")
73
73
  return null;
@@ -170,6 +170,20 @@ function formatDuration(ms) {
170
170
  function issueFor(checked, from, exhausted = false) {
171
171
  if (checked.status === "capable")
172
172
  return [];
173
+ // NOT-641: the host cannot start Muse's sandbox (e.g. AppArmor blocking unprivileged
174
+ // user namespaces) — a host problem, never a version regression. Names the sandbox
175
+ // error and the host fix; deliberately not the "update removed access" text.
176
+ if (checked.status === "host-sandbox") {
177
+ return [
178
+ {
179
+ code: "runtime_capability",
180
+ message: `Muse's shell sandbox failed to start on this host (${checked.detail}) — ` +
181
+ `developer admission blocked until the host allows Muse's sandbox ` +
182
+ `(e.g. an AppArmor profile permitting unprivileged user namespaces). ` +
183
+ `This is a host problem, not a Muse Code version regression (probed ${checked.version}).`,
184
+ },
185
+ ];
186
+ }
173
187
  const head = transition(from, checked.version);
174
188
  if (checked.status === "missing") {
175
189
  return [
@@ -269,7 +283,7 @@ function startCheck(version) {
269
283
  console.log(`[muse-capability] ${transition(from, version)}: developer ${CAPABILITY} confirmed`);
270
284
  dropMissWatchersExcept(null);
271
285
  }
272
- else if (result.status === "missing") {
286
+ else if (result.status === "missing" || result.status === "host-sandbox") {
273
287
  console.warn(`[muse-capability] ${issueFor(checked, from)[0].message}`);
274
288
  escalateWatchedVersion(version);
275
289
  }
@@ -331,7 +345,9 @@ export function museCapabilityIssues(version, onSettled = () => { }) {
331
345
  return s.confirmedVersion ? [] : verifyingIssue(version, from);
332
346
  if (checked.status === "capable")
333
347
  return [];
334
- if (checked.status === "missing") {
348
+ // NOT-641: a host sandbox failure blocks like a confirmed loss (the host cannot run
349
+ // shell sessions on any version), with the host message — never the version text.
350
+ if (checked.status === "missing" || checked.status === "host-sandbox") {
335
351
  return s.overriddenVersions.includes(checked.version) ? [] : issueFor(checked, from);
336
352
  }
337
353
  // Inconclusive: never a block while any baseline exists to work on. With none, the
@@ -362,13 +378,13 @@ function actionKindOf(action, fallback) {
362
378
  const evidence = action.evidenceJson
363
379
  ? JSON.parse(action.evidenceJson)
364
380
  : null;
365
- if (evidence?.kind === "missing" || evidence?.kind === "unverified")
381
+ if (evidence?.kind === "missing" || evidence?.kind === "unverified" || evidence?.kind === "host-sandbox")
366
382
  return evidence.kind;
367
383
  }
368
384
  catch {
369
385
  // Fall through to the request_id prefix below.
370
386
  }
371
- const prefixed = /^muse-capability:(missing|unverified):/.exec(action.requestId ?? "");
387
+ const prefixed = /^muse-capability:(missing|unverified|host-sandbox):/.exec(action.requestId ?? "");
372
388
  if (prefixed)
373
389
  return prefixed[1];
374
390
  return fallback;
@@ -405,6 +421,21 @@ function escalationFor(checked, s) {
405
421
  `on ${checked.version} anyway${rollback}`,
406
422
  };
407
423
  }
424
+ // NOT-641: host sandbox start failure — names the host cause and the host fix, never
425
+ // the version-regression text. Acknowledging records an override like `missing` (the
426
+ // operator fixed the host and wants this version admitted).
427
+ if (checked.status === "host-sandbox" && !s.overriddenVersions.includes(checked.version)) {
428
+ return {
429
+ kind: "host-sandbox",
430
+ reason: `Muse's shell sandbox failed to start on this host (${checked.detail}). Last probe ran ` +
431
+ `${formatDuration(checked.durationMs)} (probe timeout ${formatDuration(PROBE_TIMEOUT_MS)}). ` +
432
+ `Developer admission is blocked for ${checked.version}; last confirmed baseline is ${baseline}. ` +
433
+ `This is a host problem, not a Muse Code version regression — no pin/roll back will fix it.`,
434
+ question: `Muse's sandbox cannot start on this host (${checked.detail}). Allow Muse's sandbox on the ` +
435
+ `host (e.g. an AppArmor profile permitting unprivileged user namespaces), then acknowledge ` +
436
+ `to admit developers on ${checked.version} anyway?`,
437
+ };
438
+ }
408
439
  if (isExhausted(checked) && checked.status === "error") {
409
440
  const detail = checked.detail;
410
441
  // With a baseline, admission proceeds on it and probing stops; with none (fresh
@@ -476,7 +507,7 @@ export function ensureMuseCapabilityEscalation(issueId) {
476
507
  // parseable choice) falls through and re-raises a fresh action below.
477
508
  const acknowledged = sameKind.some((a) => a.status === "resolved" && resolutionChoiceOf(a) === "acknowledge");
478
509
  if (acknowledged) {
479
- if (escalation.kind === "missing")
510
+ if (escalation.kind === "missing" || escalation.kind === "host-sandbox")
480
511
  recordMuseCapabilityOverride(checked.version);
481
512
  return null;
482
513
  }
@@ -493,7 +524,7 @@ export function ensureMuseCapabilityEscalation(issueId) {
493
524
  durationMs: checked.durationMs,
494
525
  capability: CAPABILITY,
495
526
  },
496
- responseOptions: [{ choice: "acknowledge", label: `Acknowledge — ${escalation.kind === "missing" ? `admit on ${checked.version}` : "keep working on baseline"}` }],
527
+ responseOptions: [{ choice: "acknowledge", label: `Acknowledge — ${escalation.kind === "unverified" ? "keep working on baseline" : `admit on ${checked.version}`}` }],
497
528
  requestId,
498
529
  });
499
530
  }
@@ -572,6 +603,27 @@ export function countMuseShellToolCalls(logPath) {
572
603
  }
573
604
  return parsed === 0 ? null : shells;
574
605
  }
606
+ /**
607
+ * NOT-641: extract a host sandbox start failure from probe session log text (the
608
+ * normalized `probe.ndjson` plus the raw stdout envelopes, whichever holds it).
609
+ * Matches bubblewrap/`bwrap` start errors (e.g. AppArmor's unprivileged user-namespace
610
+ * restriction: `bwrap: loopback: Failed RTM_NEWADDR: Operation not permitted`).
611
+ *
612
+ * The log may be JSON envelopes (raw stdout, tool output double-encoded) or plain
613
+ * text (stderr trailer), so the error itself is matched — stopping at JSON escapes,
614
+ * quotes, or newlines — rather than whole lines. Returns the error text, or null.
615
+ *
616
+ * Deliberately narrow: a bare `Operation not permitted` is a normal sandbox denial
617
+ * (e.g. writing outside the workspace) and never counts — only sandbox-startup
618
+ * signatures (`bwrap:`, `bubblewrap`, `RTM_NEWADDR`) do.
619
+ */
620
+ export function extractHostSandboxError(logText) {
621
+ const m = /bwrap:[^\n\\"]{0,300}|bubblewrap[^\n\\"]{0,300}|Failed RTM_NEWADDR[^\n\\"]{0,200}/i.exec(logText);
622
+ if (!m)
623
+ return null;
624
+ const line = m[0].trim();
625
+ return line === "" ? null : line;
626
+ }
575
627
  /**
576
628
  * NOT-308 safety net: a developer session ending with a dirty worktree but zero shell
577
629
  * tool calls is exactly what a shell-less build looks like from the outside, so when
@@ -594,7 +646,7 @@ export function museCapabilitySafetyNetAfterSession(input) {
594
646
  if (s.confirmedVersion === version)
595
647
  return "skipped";
596
648
  const checked = s.lastChecked;
597
- if (checked && checked.version === version && checked.status === "missing") {
649
+ if (checked && checked.version === version && (checked.status === "missing" || checked.status === "host-sandbox")) {
598
650
  ensureMuseCapabilityEscalation(input.issueId);
599
651
  return "escalated";
600
652
  }
@@ -749,6 +801,27 @@ export async function defaultMuseCapabilityProbe(version, opts = {}) {
749
801
  catch {
750
802
  written = null;
751
803
  }
804
+ // NOT-641: when the shell did not produce its output, a sandbox start failure in
805
+ // the session logs (bwrap/AppArmor userns) is a host problem, not a version
806
+ // regression — report it as such whatever the exit/failure said. A bare
807
+ // `Operation not permitted` without sandbox-startup context is a normal denial
808
+ // and never takes this path (see extractHostSandboxError).
809
+ if (written !== gitBlobSha1(nonce)) {
810
+ const logTexts = [];
811
+ for (const logFile of [run.logPath, run.muse?.rawLogPath]) {
812
+ if (!logFile)
813
+ continue;
814
+ try {
815
+ logTexts.push(fs.readFileSync(logFile, "utf8"));
816
+ }
817
+ catch {
818
+ // An unreadable log is not a sandbox failure — ignore it.
819
+ }
820
+ }
821
+ const sandboxError = logTexts.length > 0 ? extractHostSandboxError(logTexts.join("\n")) : null;
822
+ if (sandboxError)
823
+ return { status: "host-sandbox", detail: sandboxError };
824
+ }
752
825
  // A session that did not complete cleanly is never a verdict, even if the shell ran first.
753
826
  if (run.timedOut)
754
827
  return { status: "error", detail: `probe session on ${version} timed out` };