pr-shepherd 2.2.18 → 2.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/README.md +1 -0
  3. package/bin/api.d.mts +10 -0
  4. package/bin/api.mjs +21 -1
  5. package/bin/cli/iterate-formatter.mjs +3 -1
  6. package/bin/cli/triage-formatter.mjs +2 -0
  7. package/bin/cli/workflow-elsewhere-format.d.mts +3 -0
  8. package/bin/cli/workflow-elsewhere-format.mjs +112 -0
  9. package/bin/commands/iterate/base.mjs +1 -0
  10. package/bin/commands/iterate/helpers.mjs +1 -0
  11. package/bin/commands/iterate/index.mjs +11 -3
  12. package/bin/commands/iterate/queue-recovery-instructions.d.mts +1 -1
  13. package/bin/commands/iterate/queue-recovery-instructions.mjs +7 -4
  14. package/bin/commands/iterate/render.mjs +2 -1
  15. package/bin/commands/iterate/triage.mjs +24 -7
  16. package/bin/commands/iterate/workflow-elsewhere.d.mts +19 -0
  17. package/bin/commands/iterate/workflow-elsewhere.mjs +144 -0
  18. package/bin/commands/ready-delay.mjs +24 -1
  19. package/bin/comments/rest-reply.mjs +2 -1
  20. package/bin/comments/uncertain-replies.mjs +2 -1
  21. package/bin/comments/uncertain-reply-guards.mjs +2 -1
  22. package/bin/config/schema.d.mts +6 -0
  23. package/bin/config/schema.mjs +3 -0
  24. package/bin/execution-context.d.mts +7 -0
  25. package/bin/execution-context.mjs +13 -1
  26. package/bin/github/gql/default-branch-workflow-runs.gql +71 -0
  27. package/bin/github/graphql-http.mjs +2 -0
  28. package/bin/github/graphql-internal-retry.mjs +2 -1
  29. package/bin/github/queries.d.mts +2 -0
  30. package/bin/github/queries.mjs +2 -0
  31. package/bin/github/read-only-guard.d.mts +4 -0
  32. package/bin/github/read-only-guard.mjs +25 -0
  33. package/bin/github/rest-http.mjs +2 -0
  34. package/bin/github/rest-identities.mjs +16 -2
  35. package/bin/github/workflow-elsewhere-parse.d.mts +19 -0
  36. package/bin/github/workflow-elsewhere-parse.mjs +172 -0
  37. package/bin/github/workflow-elsewhere-queue.d.mts +28 -0
  38. package/bin/github/workflow-elsewhere-queue.mjs +137 -0
  39. package/bin/github/workflow-elsewhere-read.d.mts +26 -0
  40. package/bin/github/workflow-elsewhere-read.mjs +120 -0
  41. package/bin/github/workflow-elsewhere-rest-runs.d.mts +20 -0
  42. package/bin/github/workflow-elsewhere-rest-runs.mjs +54 -0
  43. package/bin/github/workflow-elsewhere-rest.d.mts +3 -0
  44. package/bin/github/workflow-elsewhere-rest.mjs +126 -0
  45. package/bin/log/log-file.mjs +1 -1
  46. package/bin/state/base.mjs +30 -12
  47. package/bin/state/check-blockers.mjs +2 -1
  48. package/bin/state/check-follow-up.mjs +2 -1
  49. package/bin/state/ci-retrigger.mjs +2 -1
  50. package/bin/state/conflicting-head-seen.mjs +2 -1
  51. package/bin/state/fix-attempts.mjs +2 -1
  52. package/bin/state/graphql-quota-claims.mjs +6 -1
  53. package/bin/state/graphql-quota-warnings.mjs +2 -1
  54. package/bin/state/guarded-fs.d.mts +16 -0
  55. package/bin/state/guarded-fs.mjs +49 -0
  56. package/bin/state/merge-request.mjs +2 -1
  57. package/bin/state/pr-fingerprint.mjs +2 -1
  58. package/bin/state/queue-removal-ack.mjs +2 -1
  59. package/bin/state/ready-receipts.mjs +2 -1
  60. package/bin/state/rest-cache.mjs +2 -1
  61. package/bin/state/rest-snapshot-report.mjs +2 -1
  62. package/bin/state/seen-comments.mjs +2 -1
  63. package/bin/state/signature-marker.mjs +2 -1
  64. package/bin/state/stack-merge-approval.mjs +2 -1
  65. package/bin/state/stall-repair.mjs +2 -1
  66. package/bin/state/stall-state-store.mjs +2 -1
  67. package/bin/types/iterate.d.mts +2 -0
  68. package/bin/types/report.d.mts +7 -0
  69. package/bin/types/workflow-elsewhere-raw.d.mts +108 -0
  70. package/bin/types/workflow-elsewhere-raw.mjs +1 -0
  71. package/bin/types/workflow-elsewhere.d.mts +55 -0
  72. package/bin/types/workflow-elsewhere.mjs +1 -0
  73. package/bin/types.d.mts +1 -0
  74. package/bin/types.mjs +1 -0
  75. package/package.json +1 -1
  76. package/plugins/pr-shepherd/.claude-plugin/plugin.json +1 -1
  77. package/plugins/pr-shepherd/.codex-plugin/plugin.json +1 -1
  78. package/plugins/pr-shepherd/skills/pr-shepherd/references/merge-queue-ejection.md +1 -1
  79. package/pr-shepherd.schema.json +13 -0
@@ -0,0 +1,26 @@
1
+ import { type RepoInfo } from "./client.mts";
2
+ import { type StateKey } from "../state/rest-cache.mts";
3
+ import type { ElsewhereRun, ElsewhereScope } from "../types/workflow-elsewhere.mts";
4
+ export interface ReadWorkflowElsewhereInput {
5
+ repo: RepoInfo;
6
+ prNumber: number;
7
+ workflowId: string;
8
+ workflowName?: string;
9
+ workflowPath?: string;
10
+ currentRunId: string;
11
+ currentCommitOid: string;
12
+ windowStartMs: number;
13
+ since: string;
14
+ }
15
+ export type WorkflowElsewhereReadResult = {
16
+ runs: ElsewhereRun[];
17
+ scope: ElsewhereScope;
18
+ } | {
19
+ unread: string;
20
+ };
21
+ /** Format an optional workflow-elsewhere read failure into a single-line `unread` reason. */
22
+ export declare function summarizeElsewhereError(error: unknown): string;
23
+ /** Resolve numeric workflow ID from `GET /actions/runs/{id}` when GraphQL did not include it. */
24
+ export declare function resolveWorkflowId(repo: RepoInfo, runId: string, stateKey: StateKey): Promise<string | undefined>;
25
+ /** Read same-workflow runs on the default branch and other merge-queue entries. */
26
+ export declare function readWorkflowElsewhere(input: ReadWorkflowElsewhereInput): Promise<WorkflowElsewhereReadResult>;
@@ -0,0 +1,120 @@
1
+ import { graphql } from "./client.mjs";
2
+ import { GitHubRequestError } from "./errors.mjs";
3
+ import { rest } from "./http.mjs";
4
+ import { DEFAULT_BRANCH_WORKFLOW_RUNS_QUERY } from "./queries.mjs";
5
+ import { githubOperation } from "./transport.mjs";
6
+ import { pollRateLimitRetryAfterMs } from "../commands/poll-quota.mjs";
7
+ import { loadDerived, storeDerived } from "../state/rest-cache.mjs";
8
+ import { MAX_ELSEWHERE_RUNS_PER_SOURCE, parseDefaultBranchRuns, sortNewestFirst, } from "./workflow-elsewhere-parse.mjs";
9
+ import { buildQueueCommitsQuery, mergeQueueCommitDetails, selectOtherQueueRestRuns, } from "./workflow-elsewhere-queue.mjs";
10
+ import { readWorkflowElsewhereRest } from "./workflow-elsewhere-rest.mjs";
11
+ import { fetchRestWorkflowRunsPaged } from "./workflow-elsewhere-rest-runs.mjs";
12
+ const MAX_ERROR_CHARS = 120;
13
+ const repoPrefix = (repo) => `/repos/${encodeURIComponent(repo.owner)}/${encodeURIComponent(repo.name)}`;
14
+ /** Format an optional workflow-elsewhere read failure into a single-line `unread` reason. */
15
+ export function summarizeElsewhereError(error) {
16
+ const retry = pollRateLimitRetryAfterMs(error);
17
+ if (retry !== null) {
18
+ return `rate limited, retry after ${Math.max(1, Math.ceil(retry.ms / 1000))}s`;
19
+ }
20
+ if (error instanceof GitHubRequestError)
21
+ return `HTTP ${error.status}`;
22
+ const raw = error instanceof Error ? error.message : String(error);
23
+ const compact = raw.replace(/\s+/g, " ").trim();
24
+ if (!compact)
25
+ return "request failed";
26
+ return compact.length <= MAX_ERROR_CHARS ? compact : `${compact.slice(0, MAX_ERROR_CHARS - 1)}…`;
27
+ }
28
+ /** Resolve numeric workflow ID from `GET /actions/runs/{id}` when GraphQL did not include it. */
29
+ export async function resolveWorkflowId(repo, runId, stateKey) {
30
+ const cacheName = `run-workflow-id:${runId}`;
31
+ const cached = await loadDerived(stateKey, cacheName);
32
+ if (cached && typeof cached.value === "string" && /^\d+$/.test(cached.value)) {
33
+ return cached.value;
34
+ }
35
+ const data = await rest("GET", `${repoPrefix(repo)}/actions/runs/${encodeURIComponent(runId)}`);
36
+ const id = data?.workflow_id;
37
+ if (typeof id !== "number" || !Number.isSafeInteger(id) || id <= 0)
38
+ return undefined;
39
+ const resolved = String(id);
40
+ await storeDerived(stateKey, cacheName, resolved);
41
+ return resolved;
42
+ }
43
+ /** Read same-workflow runs on the default branch and other merge-queue entries. */
44
+ export async function readWorkflowElsewhere(input) {
45
+ const { repo, workflowId, windowStartMs, since } = input;
46
+ const defaultOutcome = await githubOperation("WorkflowElsewhereDefault", async () => ({
47
+ kind: "graphql",
48
+ data: (await graphql(DEFAULT_BRANCH_WORKFLOW_RUNS_QUERY, {
49
+ owner: repo.owner,
50
+ repo: repo.name,
51
+ })).data,
52
+ }), async () => ({ kind: "rest", result: await readWorkflowElsewhereRest(input) }));
53
+ if (defaultOutcome.kind === "rest")
54
+ return defaultOutcome.result;
55
+ const defaultParsed = parseDefaultBranchRuns(defaultOutcome.data, workflowId, windowStartMs);
56
+ if (defaultParsed.incomplete)
57
+ return { unread: "GitHub returned incomplete (null) nodes" };
58
+ if (defaultParsed.unavailable)
59
+ return { unread: defaultParsed.unavailable };
60
+ // Keep the REST queue listing outside `githubOperation` so a REST error never flips the
61
+ // session transport from GraphQL to REST.
62
+ const wfPath = `${repoPrefix(repo)}/actions/workflows/${encodeURIComponent(workflowId)}/runs`;
63
+ let queueRead;
64
+ try {
65
+ queueRead = await fetchRestWorkflowRunsPaged(`${wfPath}?event=merge_group&status=completed`, windowStartMs, (items) => selectOtherQueueRestRuns(items, {
66
+ prNumber: input.prNumber,
67
+ currentRunId: input.currentRunId,
68
+ currentCommitOid: input.currentCommitOid,
69
+ windowStartMs,
70
+ }), MAX_ELSEWHERE_RUNS_PER_SOURCE);
71
+ }
72
+ catch (error) {
73
+ return { unread: summarizeElsewhereError(error) };
74
+ }
75
+ if ("unread" in queueRead)
76
+ return queueRead;
77
+ const queueCandidates = queueRead.candidates;
78
+ const oids = [
79
+ ...new Set(queueCandidates.filter((c) => c.conclusion !== "SUCCESS").map((c) => c.headSha)),
80
+ ];
81
+ let queueData;
82
+ const oidToAlias = new Map();
83
+ if (oids.length > 0) {
84
+ oids.forEach((oid, i) => oidToAlias.set(oid, `c${i}`));
85
+ const { query, variables } = buildQueueCommitsQuery(repo.owner, repo.name, oids);
86
+ const queueOutcome = await githubOperation("WorkflowElsewhereQueue", async () => ({
87
+ kind: "graphql",
88
+ data: (await graphql(query, variables)).data,
89
+ }), async () => ({ kind: "rest", result: await readWorkflowElsewhereRest(input) }));
90
+ if (queueOutcome.kind === "rest")
91
+ return queueOutcome.result;
92
+ queueData = queueOutcome.data;
93
+ }
94
+ const queueParsed = mergeQueueCommitDetails(queueCandidates, oidToAlias, queueData);
95
+ if (queueParsed.incomplete)
96
+ return { unread: "GitHub returned incomplete (null) nodes" };
97
+ if (queueParsed.unavailable)
98
+ return { unread: queueParsed.unavailable };
99
+ const workflowName = defaultParsed.workflowName ?? queueRead.workflowName ?? input.workflowName;
100
+ const workflowPath = defaultParsed.workflowPath ?? queueRead.workflowPath ?? input.workflowPath;
101
+ const scope = {
102
+ ...(workflowName !== undefined && { workflowName }),
103
+ ...(workflowPath !== undefined && { workflowPath }),
104
+ since,
105
+ defaultBranch: {
106
+ branch: defaultParsed.branch,
107
+ commitsRead: defaultParsed.commitsRead,
108
+ matched: defaultParsed.matched,
109
+ matchedComplete: defaultParsed.matchedComplete,
110
+ shown: defaultParsed.runs.length,
111
+ },
112
+ mergeQueue: {
113
+ runsRead: queueRead.runsRead,
114
+ matched: queueRead.matched,
115
+ matchedComplete: queueRead.matchedComplete,
116
+ shown: queueParsed.runs.length,
117
+ },
118
+ };
119
+ return { runs: sortNewestFirst([...defaultParsed.runs, ...queueParsed.runs]), scope };
120
+ }
@@ -0,0 +1,20 @@
1
+ import type { RestRunCandidate, RestWorkflowRunItem } from "../types/workflow-elsewhere-raw.mts";
2
+ /**
3
+ * Page REST workflow runs up to `MAX_RUN_PAGES` until `targetCount` candidates are found, a page
4
+ * is partial, or one full page past the `created_at < windowStartMs` cutoff has been read (so
5
+ * re-runs of older runs completing inside the window are seen). Returns `unread` if the budget
6
+ * exhausts before that condition is met.
7
+ */
8
+ export declare function fetchRestWorkflowRunsPaged(baseQuery: string, windowStartMs: number, select: (items: readonly RestWorkflowRunItem[]) => {
9
+ candidates: RestRunCandidate[];
10
+ matched: number;
11
+ }, targetCount: number): Promise<{
12
+ candidates: RestRunCandidate[];
13
+ matched: number;
14
+ matchedComplete: boolean;
15
+ runsRead: number;
16
+ workflowName?: string;
17
+ workflowPath?: string;
18
+ } | {
19
+ unread: string;
20
+ }>;
@@ -0,0 +1,54 @@
1
+ import { normalizeWorkflowPath } from "../checks/workflow-path.mjs";
2
+ import { rest } from "./http.mjs";
3
+ const REST_RUNS_PER_PAGE = 30;
4
+ const MAX_RUN_PAGES = 3;
5
+ function extractRestWorkflowMeta(items) {
6
+ let workflowName;
7
+ let workflowPath;
8
+ for (const item of items) {
9
+ if (!workflowName && item.name?.trim())
10
+ workflowName = item.name.trim();
11
+ if (!workflowPath)
12
+ workflowPath = normalizeWorkflowPath(item.path);
13
+ if (workflowName && workflowPath)
14
+ break;
15
+ }
16
+ return {
17
+ ...(workflowName !== undefined && { workflowName }),
18
+ ...(workflowPath !== undefined && { workflowPath }),
19
+ };
20
+ }
21
+ /**
22
+ * Page REST workflow runs up to `MAX_RUN_PAGES` until `targetCount` candidates are found, a page
23
+ * is partial, or one full page past the `created_at < windowStartMs` cutoff has been read (so
24
+ * re-runs of older runs completing inside the window are seen). Returns `unread` if the budget
25
+ * exhausts before that condition is met.
26
+ */
27
+ export async function fetchRestWorkflowRunsPaged(baseQuery, windowStartMs, select, targetCount) {
28
+ const all = [];
29
+ let sawPreWindowPage = false;
30
+ for (let page = 1; page <= MAX_RUN_PAGES; page++) {
31
+ // eslint-disable-next-line no-await-in-loop
32
+ const payload = await rest("GET", `${baseQuery}&per_page=${REST_RUNS_PER_PAGE}&page=${page}`);
33
+ if (!Array.isArray(payload?.workflow_runs))
34
+ return { unread: "malformed workflow runs response" };
35
+ const items = payload.workflow_runs;
36
+ all.push(...items);
37
+ const { candidates, matched } = select(all);
38
+ const reachedEnd = items.length < REST_RUNS_PER_PAGE || sawPreWindowPage;
39
+ if (reachedEnd || candidates.length >= targetCount) {
40
+ return {
41
+ candidates,
42
+ matched,
43
+ matchedComplete: reachedEnd,
44
+ runsRead: all.length,
45
+ ...extractRestWorkflowMeta(all),
46
+ };
47
+ }
48
+ const oldestCreatedMs = Date.parse(items[items.length - 1].created_at);
49
+ if (Number.isFinite(oldestCreatedMs) && oldestCreatedMs < windowStartMs) {
50
+ sawPreWindowPage = true;
51
+ }
52
+ }
53
+ return { unread: "workflow runs pagination truncated" };
54
+ }
@@ -0,0 +1,3 @@
1
+ import type { ReadWorkflowElsewhereInput, WorkflowElsewhereReadResult } from "./workflow-elsewhere-read.mts";
2
+ /** REST transport reader for same-workflow runs on the default branch and other queue entries. */
3
+ export declare function readWorkflowElsewhereRest(input: ReadWorkflowElsewhereInput): Promise<WorkflowElsewhereReadResult>;
@@ -0,0 +1,126 @@
1
+ import { rest } from "./http.mjs";
2
+ import { mapPool } from "../util/pool.mjs";
3
+ import { MAX_ELSEWHERE_ANNOTATIONS, MAX_ELSEWHERE_FAILED_JOBS, MAX_ELSEWHERE_RUNS_PER_SOURCE, normalizeAnnotationMessage, sortNewestFirst, } from "./workflow-elsewhere-parse.mjs";
4
+ import { selectDefaultBranchRestRuns, selectOtherQueueRestRuns, } from "./workflow-elsewhere-queue.mjs";
5
+ import { fetchRestWorkflowRunsPaged } from "./workflow-elsewhere-rest-runs.mjs";
6
+ const REST_JOBS_PER_PAGE = 100;
7
+ const MAX_JOB_PAGES = 3;
8
+ const REST_ANNOTATIONS_PER_PAGE = 50;
9
+ const repoPrefix = (repo) => `/repos/${encodeURIComponent(repo.owner)}/${encodeURIComponent(repo.name)}`;
10
+ async function hydrateRestFailedJobs(repo, candidate) {
11
+ if (candidate.conclusion === "SUCCESS")
12
+ return { jobs: [] };
13
+ const failed = [];
14
+ const jobsBase = candidate.runAttempt
15
+ ? `${repoPrefix(repo)}/actions/runs/${encodeURIComponent(candidate.runId)}/attempts/${candidate.runAttempt}/jobs?per_page=${REST_JOBS_PER_PAGE}`
16
+ : `${repoPrefix(repo)}/actions/runs/${encodeURIComponent(candidate.runId)}/jobs?filter=latest&per_page=${REST_JOBS_PER_PAGE}`;
17
+ for (let page = 1; page <= MAX_JOB_PAGES; page++) {
18
+ // eslint-disable-next-line no-await-in-loop
19
+ const jobsPayload = await rest("GET", `${jobsBase}&page=${page}`);
20
+ if (!Array.isArray(jobsPayload?.jobs))
21
+ return { unread: "malformed workflow jobs response" };
22
+ for (const job of jobsPayload.jobs) {
23
+ const c = job.conclusion?.toUpperCase();
24
+ if (c === "FAILURE" || c === "TIMED_OUT") {
25
+ failed.push({ id: job.id, name: job.name, conclusion: c });
26
+ if (failed.length >= MAX_ELSEWHERE_FAILED_JOBS)
27
+ break;
28
+ }
29
+ }
30
+ if (failed.length >= MAX_ELSEWHERE_FAILED_JOBS || jobsPayload.jobs.length < REST_JOBS_PER_PAGE)
31
+ break;
32
+ if (page === MAX_JOB_PAGES)
33
+ return { unread: "workflow jobs pagination truncated" };
34
+ }
35
+ const hydrated = await mapPool(failed, 4, async (job) => {
36
+ const rawAnnotations = await rest("GET", `${repoPrefix(repo)}/check-runs/${job.id}/annotations?per_page=${REST_ANNOTATIONS_PER_PAGE}`);
37
+ if (!Array.isArray(rawAnnotations)) {
38
+ return { unread: "malformed check-run annotations response" };
39
+ }
40
+ const annotations = rawAnnotations
41
+ .slice(0, MAX_ELSEWHERE_ANNOTATIONS)
42
+ .map((ann) => ({
43
+ path: (ann.path ?? "").trim(),
44
+ line: typeof ann.start_line === "number" && ann.start_line > 0 ? ann.start_line : null,
45
+ message: normalizeAnnotationMessage(ann.message),
46
+ }));
47
+ const moreAnnotations = rawAnnotations.length > MAX_ELSEWHERE_ANNOTATIONS &&
48
+ rawAnnotations.length < REST_ANNOTATIONS_PER_PAGE
49
+ ? rawAnnotations.length - MAX_ELSEWHERE_ANNOTATIONS
50
+ : undefined;
51
+ return {
52
+ name: job.name,
53
+ conclusion: job.conclusion,
54
+ annotations,
55
+ ...(moreAnnotations !== undefined && { moreAnnotations }),
56
+ };
57
+ });
58
+ const bad = hydrated.find((item) => "unread" in item);
59
+ return bad ? bad : { jobs: hydrated };
60
+ }
61
+ /** REST transport reader for same-workflow runs on the default branch and other queue entries. */
62
+ export async function readWorkflowElsewhereRest(input) {
63
+ const { repo, workflowId, windowStartMs, since } = input;
64
+ const repoPayload = await rest("GET", repoPrefix(repo));
65
+ if (typeof repoPayload?.default_branch !== "string" || !repoPayload.default_branch) {
66
+ return { unread: "default branch unavailable" };
67
+ }
68
+ const branch = repoPayload.default_branch;
69
+ const wfPath = `${repoPrefix(repo)}/actions/workflows/${encodeURIComponent(workflowId)}/runs`;
70
+ const [defaultRead, queueRead] = await Promise.all([
71
+ fetchRestWorkflowRunsPaged(`${wfPath}?branch=${encodeURIComponent(branch)}&status=completed`, windowStartMs, (items) => selectDefaultBranchRestRuns(items, branch, windowStartMs), MAX_ELSEWHERE_RUNS_PER_SOURCE),
72
+ fetchRestWorkflowRunsPaged(`${wfPath}?event=merge_group&status=completed`, windowStartMs, (items) => selectOtherQueueRestRuns(items, {
73
+ prNumber: input.prNumber,
74
+ currentRunId: input.currentRunId,
75
+ currentCommitOid: input.currentCommitOid,
76
+ windowStartMs,
77
+ }), MAX_ELSEWHERE_RUNS_PER_SOURCE),
78
+ ]);
79
+ if ("unread" in defaultRead)
80
+ return defaultRead;
81
+ if ("unread" in queueRead)
82
+ return queueRead;
83
+ const toRun = async (candidate, source) => {
84
+ const jobsRes = await hydrateRestFailedJobs(repo, candidate);
85
+ if ("unread" in jobsRes)
86
+ return jobsRes;
87
+ return {
88
+ source,
89
+ ...(candidate.branch !== undefined && { branch: candidate.branch }),
90
+ ...(candidate.pr !== undefined && { pr: candidate.pr }),
91
+ headSha: candidate.headSha.slice(0, 7),
92
+ runId: candidate.runId,
93
+ conclusion: candidate.conclusion,
94
+ completedAt: candidate.completedAt,
95
+ failedJobs: jobsRes.jobs,
96
+ };
97
+ };
98
+ const results = [
99
+ ...(await mapPool(defaultRead.candidates, 3, (c) => toRun(c, "default-branch"))),
100
+ ...(await mapPool(queueRead.candidates, 3, (c) => toRun(c, "merge-queue"))),
101
+ ];
102
+ const bad = results.find((item) => "unread" in item);
103
+ if (bad)
104
+ return bad;
105
+ const workflowName = defaultRead.workflowName ?? queueRead.workflowName ?? input.workflowName;
106
+ const workflowPath = defaultRead.workflowPath ?? queueRead.workflowPath ?? input.workflowPath;
107
+ const scope = {
108
+ ...(workflowName !== undefined && { workflowName }),
109
+ ...(workflowPath !== undefined && { workflowPath }),
110
+ since,
111
+ defaultBranch: {
112
+ branch,
113
+ runsRead: defaultRead.runsRead,
114
+ matched: defaultRead.matched,
115
+ matchedComplete: defaultRead.matchedComplete,
116
+ shown: defaultRead.candidates.length,
117
+ },
118
+ mergeQueue: {
119
+ runsRead: queueRead.runsRead,
120
+ matched: queueRead.matched,
121
+ matchedComplete: queueRead.matchedComplete,
122
+ shown: queueRead.candidates.length,
123
+ },
124
+ };
125
+ return { runs: sortNewestFirst(results), scope };
126
+ }
@@ -7,7 +7,7 @@
7
7
  * Write failures flip an internal disabled flag so the CLI never crashes because
8
8
  * logging failed.
9
9
  */
10
- import { appendFileSync, mkdirSync } from "node:fs";
10
+ import { appendFileSyncGuarded as appendFileSync, mkdirSyncGuarded as mkdirSync, } from "../state/guarded-fs.mjs";
11
11
  import { dirname, join } from "node:path";
12
12
  import { resolveRepoStateDir } from "../state/base.mjs";
13
13
  import { getWorktreeKey } from "../util/worktree.mjs";
@@ -3,6 +3,7 @@ import { join } from "node:path";
3
3
  import { tmpdir } from "node:os";
4
4
  import { SAFE_PR_NUMBER, SAFE_SEGMENT } from "../util/path-segment.mjs";
5
5
  import { resolveDurableStateBase } from "./durable-state.mjs";
6
+ import { isReadOnly } from "../execution-context.mjs";
6
7
  /** Read once per process; null when the platform is not Linux or the shared base is unusable. */
7
8
  let linuxUserStateBase;
8
9
  /**
@@ -12,17 +13,23 @@ let linuxUserStateBase;
12
13
  * directory must be a real directory (not a symlink) owned by this user and not writable by
13
14
  * anyone else; it must also be readable, writable, and searchable from this process. Otherwise fall back to `TMPDIR`.
14
15
  */
15
- function readLinuxUserStateBase() {
16
+ function sharedLinuxStateDir() {
17
+ return join("/tmp", `pr-shepherd-state-${process.getuid()}`);
18
+ }
19
+ /** `"missing"` only when `create` is false and the directory does not exist yet. */
20
+ function readLinuxUserStateBase(create) {
16
21
  if (process.platform !== "linux" || typeof process.getuid !== "function")
17
22
  return null;
18
23
  const uid = process.getuid();
19
- const dir = join("/tmp", `pr-shepherd-state-${uid}`);
20
- try {
21
- mkdirSync(dir, { mode: 0o700 });
22
- }
23
- catch (err) {
24
- if (err.code !== "EEXIST")
25
- return null;
24
+ const dir = sharedLinuxStateDir();
25
+ if (create) {
26
+ try {
27
+ mkdirSync(dir, { mode: 0o700 });
28
+ }
29
+ catch (err) {
30
+ if (err.code !== "EEXIST")
31
+ return null;
32
+ }
26
33
  }
27
34
  try {
28
35
  const stat = lstatSync(dir);
@@ -31,8 +38,8 @@ function readLinuxUserStateBase() {
31
38
  accessSync(dir, constants.R_OK | constants.W_OK | constants.X_OK);
32
39
  return dir;
33
40
  }
34
- catch {
35
- return null;
41
+ catch (err) {
42
+ return !create && err.code === "ENOENT" ? "missing" : null;
36
43
  }
37
44
  }
38
45
  export function resolveStateBase() {
@@ -42,8 +49,19 @@ export function resolveStateBase() {
42
49
  const durable = resolveDurableStateBase();
43
50
  if (durable)
44
51
  return durable;
45
- if (linuxUserStateBase === undefined)
46
- linuxUserStateBase = readLinuxUserStateBase();
52
+ if (linuxUserStateBase === undefined) {
53
+ // A read-only scope never creates the shared base. A missing base holds no state to read, so
54
+ // name it without caching the answer: the next writing call must still create it.
55
+ if (isReadOnly()) {
56
+ const base = readLinuxUserStateBase(false);
57
+ if (base === "missing")
58
+ return sharedLinuxStateDir();
59
+ linuxUserStateBase = base;
60
+ }
61
+ else {
62
+ linuxUserStateBase = readLinuxUserStateBase(true);
63
+ }
64
+ }
47
65
  if (linuxUserStateBase)
48
66
  return linuxUserStateBase;
49
67
  return join(tmpdir(), "pr-shepherd-state");
@@ -3,7 +3,8 @@
3
3
  *
4
4
  * `$PR_SHEPHERD_STATE_DIR/<owner>/<repo>/<pr>/check-blockers.json`
5
5
  */
6
- import { readFile, writeFile, rename, unlink, mkdir } from "node:fs/promises";
6
+ import { readFile } from "node:fs/promises";
7
+ import { writeFile, rename, unlink, mkdir } from "./guarded-fs.mjs";
7
8
  import { randomUUID } from "node:crypto";
8
9
  import { dirname } from "node:path";
9
10
  import { resolvePrStatePath } from "./base.mjs";
@@ -6,7 +6,8 @@
6
6
  * not that the caller ran it. The next presented tick with the same head and checks escalates.
7
7
  * Internal debounce preview ticks do not write this marker.
8
8
  */
9
- import { mkdir, readFile, writeFile } from "node:fs/promises";
9
+ import { readFile } from "node:fs/promises";
10
+ import { mkdir, writeFile } from "./guarded-fs.mjs";
10
11
  import { dirname } from "node:path";
11
12
  import { resolvePrStatePath } from "./base.mjs";
12
13
  /**
@@ -6,7 +6,8 @@
6
6
  * Reopening does not change the head SHA, so the next presented tick must not offer it again.
7
7
  * Internal debounce preview ticks do not write this marker.
8
8
  */
9
- import { mkdir, readFile, writeFile } from "node:fs/promises";
9
+ import { readFile } from "node:fs/promises";
10
+ import { mkdir, writeFile } from "./guarded-fs.mjs";
10
11
  import { dirname } from "node:path";
11
12
  import { resolvePrStatePath } from "./base.mjs";
12
13
  /** The stored head and context set, or undefined when no usable marker exists. */
@@ -5,7 +5,8 @@
5
5
  * GitHub's Commit object has no push timestamp, so the missing-CI grace
6
6
  * starts at this observation instead of `committedDate`.
7
7
  */
8
- import { mkdir, readFile, writeFile } from "node:fs/promises";
8
+ import { readFile } from "node:fs/promises";
9
+ import { mkdir, writeFile } from "./guarded-fs.mjs";
9
10
  import { dirname } from "node:path";
10
11
  import { resolvePrStatePath } from "./base.mjs";
11
12
  /** Unix seconds of the first observation of `headSha`, or undefined when state cannot be used. */
@@ -6,7 +6,8 @@
6
6
  *
7
7
  * State lives in `$PR_SHEPHERD_STATE_DIR/<owner>/<repo>/<pr>/fix-attempts.json`.
8
8
  */
9
- import { readFile, writeFile, rename, unlink, mkdir } from "node:fs/promises";
9
+ import { readFile } from "node:fs/promises";
10
+ import { writeFile, rename, unlink, mkdir } from "./guarded-fs.mjs";
10
11
  import { randomUUID } from "node:crypto";
11
12
  import { dirname } from "node:path";
12
13
  import { resolvePrStatePath } from "./base.mjs";
@@ -1,6 +1,11 @@
1
- import { mkdir, open, readdir, unlink } from "node:fs/promises";
1
+ import { open, readdir } from "node:fs/promises";
2
+ import { mkdir, unlink } from "./guarded-fs.mjs";
2
3
  import { join } from "node:path";
4
+ import { isReadOnly } from "../execution-context.mjs";
3
5
  export async function claimWarning(path, warning, now, rearmEpoch) {
6
+ // A read-only check surfaces the warning without taking the claim another session would need.
7
+ if (isReadOnly())
8
+ return true;
4
9
  const claimsDir = `${path}.claims`;
5
10
  const claimPath = join(claimsDir, `${warning.resetAt}-${warning.limit}-${warning.thresholdPercent}-${rearmEpoch}.json`);
6
11
  let handle;
@@ -1,5 +1,6 @@
1
1
  import { randomUUID } from "node:crypto";
2
- import { mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
2
+ import { readFile } from "node:fs/promises";
3
+ import { mkdir, rename, unlink, writeFile } from "./guarded-fs.mjs";
3
4
  import { dirname, join } from "node:path";
4
5
  import { resolveRepoStateDir } from "./base.mjs";
5
6
  import { getWorktreeKey } from "../util/worktree.mjs";
@@ -0,0 +1,16 @@
1
+ /**
2
+ * The one door for local state writes. Inside a read-only scope (`runReadOnly`, used by the library
3
+ * `status` method) every write, delete, rename, link and directory creation is a silent no-op, so a
4
+ * check can never create, refresh or clear state that a concurrent session owns. Reads stay on
5
+ * `node:fs/promises` directly.
6
+ */
7
+ import * as fsp from "node:fs/promises";
8
+ import { appendFileSync, mkdirSync } from "node:fs";
9
+ export declare function writeFile(...args: Parameters<typeof fsp.writeFile>): Promise<void>;
10
+ export declare function mkdir(...args: Parameters<typeof fsp.mkdir>): Promise<void>;
11
+ export declare function rename(...args: Parameters<typeof fsp.rename>): Promise<void>;
12
+ export declare function unlink(...args: Parameters<typeof fsp.unlink>): Promise<void>;
13
+ export declare function rm(...args: Parameters<typeof fsp.rm>): Promise<void>;
14
+ export declare function link(...args: Parameters<typeof fsp.link>): Promise<void>;
15
+ export declare function appendFileSyncGuarded(...args: Parameters<typeof appendFileSync>): void;
16
+ export declare function mkdirSyncGuarded(...args: Parameters<typeof mkdirSync>): void;
@@ -0,0 +1,49 @@
1
+ /**
2
+ * The one door for local state writes. Inside a read-only scope (`runReadOnly`, used by the library
3
+ * `status` method) every write, delete, rename, link and directory creation is a silent no-op, so a
4
+ * check can never create, refresh or clear state that a concurrent session owns. Reads stay on
5
+ * `node:fs/promises` directly.
6
+ */
7
+ import * as fsp from "node:fs/promises";
8
+ import { appendFileSync, mkdirSync } from "node:fs";
9
+ import { isReadOnly } from "../execution-context.mjs";
10
+ export async function writeFile(...args) {
11
+ if (isReadOnly())
12
+ return;
13
+ await fsp.writeFile(...args);
14
+ }
15
+ export async function mkdir(...args) {
16
+ if (isReadOnly())
17
+ return;
18
+ await fsp.mkdir(...args);
19
+ }
20
+ export async function rename(...args) {
21
+ if (isReadOnly())
22
+ return;
23
+ await fsp.rename(...args);
24
+ }
25
+ export async function unlink(...args) {
26
+ if (isReadOnly())
27
+ return;
28
+ await fsp.unlink(...args);
29
+ }
30
+ export async function rm(...args) {
31
+ if (isReadOnly())
32
+ return;
33
+ await fsp.rm(...args);
34
+ }
35
+ export async function link(...args) {
36
+ if (isReadOnly())
37
+ return;
38
+ await fsp.link(...args);
39
+ }
40
+ export function appendFileSyncGuarded(...args) {
41
+ if (isReadOnly())
42
+ return;
43
+ appendFileSync(...args);
44
+ }
45
+ export function mkdirSyncGuarded(...args) {
46
+ if (isReadOnly())
47
+ return;
48
+ mkdirSync(...args);
49
+ }
@@ -1,5 +1,6 @@
1
1
  import { createHash, randomUUID } from "node:crypto";
2
- import { link, mkdir, readFile, rename, rm, unlink, writeFile } from "node:fs/promises";
2
+ import { readFile } from "node:fs/promises";
3
+ import { link, mkdir, rename, rm, unlink, writeFile } from "./guarded-fs.mjs";
3
4
  import { dirname } from "node:path";
4
5
  import { resolvePrStatePath } from "./base.mjs";
5
6
  import { restMergeStackGuardKey, validateRestMergeStackGuard, } from "../github/rest-merge-stack-guard.mjs";
@@ -1,6 +1,7 @@
1
1
  import { createHash, randomUUID } from "node:crypto";
2
2
  import { readFileSync } from "node:fs";
3
- import { mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
3
+ import { readFile } from "node:fs/promises";
4
+ import { mkdir, rename, unlink, writeFile } from "./guarded-fs.mjs";
4
5
  import { dirname } from "node:path";
5
6
  import { resolvePrStatePath } from "./base.mjs";
6
7
  import { discoverRuleFiles } from "../classify/loader.mjs";
@@ -1,5 +1,6 @@
1
1
  /** A caller's acknowledgment of one observed CI-driven native-stack queue removal. */
2
- import { mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
2
+ import { readFile } from "node:fs/promises";
3
+ import { mkdir, rename, unlink, writeFile } from "./guarded-fs.mjs";
3
4
  import { randomUUID } from "node:crypto";
4
5
  import { dirname } from "node:path";
5
6
  import { resolvePrStatePath } from "./base.mjs";
@@ -1,4 +1,5 @@
1
- import { mkdir, readFile, unlink, writeFile } from "node:fs/promises";
1
+ import { readFile } from "node:fs/promises";
2
+ import { mkdir, unlink, writeFile } from "./guarded-fs.mjs";
2
3
  import { dirname } from "node:path";
3
4
  import { resolvePrStatePath } from "./base.mjs";
4
5
  /** Read a persisted one-PR readiness receipt. Invalid/stale-shaped files are ignored. */
@@ -18,7 +18,8 @@
18
18
  * and are removed for free when `pr-shepherd clean` deletes the PR's state
19
19
  * directory — there is no separate pruning routine.
20
20
  */
21
- import { readFile, writeFile, rename, unlink, mkdir } from "node:fs/promises";
21
+ import { readFile } from "node:fs/promises";
22
+ import { writeFile, rename, unlink, mkdir } from "./guarded-fs.mjs";
22
23
  import { dirname } from "node:path";
23
24
  import { createHash, randomUUID } from "node:crypto";
24
25
  import { resolvePrStatePath } from "./base.mjs";
@@ -1,5 +1,6 @@
1
1
  import { randomUUID } from "node:crypto";
2
- import { mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
2
+ import { readFile } from "node:fs/promises";
3
+ import { mkdir, rename, unlink, writeFile } from "./guarded-fs.mjs";
3
4
  import { dirname } from "node:path";
4
5
  import { resolvePrStatePath } from "./base.mjs";
5
6
  import { fingerprintInputDigest } from "./pr-fingerprint.mjs";
@@ -1,5 +1,6 @@
1
1
  /* eslint-disable max-lines */
2
- import { readFile, writeFile, rename, unlink, mkdir, access, readdir } from "node:fs/promises";
2
+ import { readFile, access, readdir } from "node:fs/promises";
3
+ import { writeFile, rename, unlink, mkdir } from "./guarded-fs.mjs";
3
4
  import { join, dirname } from "node:path";
4
5
  import { createHash, randomUUID } from "node:crypto";
5
6
  import { SAFE_SEGMENT } from "../util/path-segment.mjs";