pr-shepherd 2.6.0 → 2.7.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 (132) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/bin/classify/standard/coderabbit-walkthrough.d.mts +10 -0
  3. package/bin/classify/standard/coderabbit-walkthrough.mjs +21 -0
  4. package/bin/classify/standard/devin-no-issues.d.mts +7 -0
  5. package/bin/classify/standard/devin-no-issues.mjs +18 -0
  6. package/bin/classify/standard/index.d.mts +2 -1
  7. package/bin/classify/standard/index.mjs +6 -1
  8. package/bin/cli/apply-merge-handler.mjs +2 -0
  9. package/bin/cli/body-truncate.d.mts +7 -0
  10. package/bin/cli/body-truncate.mjs +8 -4
  11. package/bin/cli/help-command-pages.d.mts +4 -2
  12. package/bin/cli/help-command-pages.mjs +4 -1
  13. package/bin/cli/help-iterate-poll-pages.d.mts +1 -1
  14. package/bin/cli/help-iterate-poll-pages.mjs +1 -1
  15. package/bin/cli/help-top-page.d.mts +1 -1
  16. package/bin/cli/help-top-page.mjs +3 -1
  17. package/bin/cli/help-watch-status-page.d.mts +1 -0
  18. package/bin/cli/help-watch-status-page.mjs +21 -0
  19. package/bin/cli/help.d.mts +5 -3
  20. package/bin/cli/help.mjs +2 -0
  21. package/bin/cli/iterate-lean.d.mts +0 -5
  22. package/bin/cli/iterate-lean.mjs +9 -2
  23. package/bin/cli/poll-summary-formatter.mjs +2 -1
  24. package/bin/cli/review-body-cap.d.mts +10 -0
  25. package/bin/cli/review-body-cap.mjs +84 -0
  26. package/bin/cli/stack-layer-view.d.mts +2 -0
  27. package/bin/cli/stack-layer-view.mjs +8 -0
  28. package/bin/cli/stack-overview.mjs +4 -5
  29. package/bin/cli/triage-formatter.mjs +4 -1
  30. package/bin/cli/watch-status-handler.d.mts +2 -0
  31. package/bin/cli/watch-status-handler.mjs +56 -0
  32. package/bin/cli-parser.mjs +7 -0
  33. package/bin/commands/apply-merge-default-route.d.mts +56 -0
  34. package/bin/commands/apply-merge-default-route.mjs +149 -0
  35. package/bin/commands/apply-merge-output.d.mts +2 -0
  36. package/bin/commands/apply-merge-output.mjs +8 -0
  37. package/bin/commands/apply-merge-pull.d.mts +3 -0
  38. package/bin/commands/apply-merge-resume.d.mts +2 -3
  39. package/bin/commands/apply-merge-resume.mjs +74 -32
  40. package/bin/commands/apply-merge-stack-membership.d.mts +27 -0
  41. package/bin/commands/apply-merge-stack-membership.mjs +85 -0
  42. package/bin/commands/apply-merge-submit.d.mts +20 -0
  43. package/bin/commands/apply-merge-submit.mjs +47 -0
  44. package/bin/commands/apply-merge-supersede.d.mts +17 -0
  45. package/bin/commands/apply-merge-supersede.mjs +30 -0
  46. package/bin/commands/apply-merge-sync-fallback.d.mts +16 -0
  47. package/bin/commands/apply-merge-sync-fallback.mjs +55 -0
  48. package/bin/commands/apply-merge.d.mts +2 -0
  49. package/bin/commands/apply-merge.mjs +65 -41
  50. package/bin/commands/check-review-budget.mjs +12 -1
  51. package/bin/commands/check.d.mts +2 -0
  52. package/bin/commands/check.mjs +9 -1
  53. package/bin/commands/iterate/escalate.mjs +5 -0
  54. package/bin/commands/iterate/index.mjs +34 -4
  55. package/bin/commands/iterate/merge-plan.d.mts +2 -0
  56. package/bin/commands/iterate/merge-plan.mjs +1 -1
  57. package/bin/commands/iterate/merge.mjs +7 -3
  58. package/bin/commands/iterate/stack-boundary.mjs +6 -6
  59. package/bin/commands/iterate/stale-ancestry.mjs +8 -3
  60. package/bin/commands/iterate/triage.mjs +19 -6
  61. package/bin/commands/poll-events.d.mts +1 -1
  62. package/bin/commands/poll-events.mjs +8 -3
  63. package/bin/commands/poll-seen-options.d.mts +7 -0
  64. package/bin/commands/poll-seen-options.mjs +9 -0
  65. package/bin/commands/poll-summary-instructions.d.mts +1 -0
  66. package/bin/commands/poll-summary-instructions.mjs +17 -7
  67. package/bin/commands/poll-summary.mjs +8 -4
  68. package/bin/commands/poll.mjs +2 -2
  69. package/bin/commands/rest-stack-merge-readiness.d.mts +6 -2
  70. package/bin/commands/rest-stack-merge-readiness.mjs +59 -7
  71. package/bin/commands/stack-drain.d.mts +7 -1
  72. package/bin/commands/stack-drain.mjs +30 -6
  73. package/bin/commands/stack-lower-heads.d.mts +32 -0
  74. package/bin/commands/stack-lower-heads.mjs +53 -0
  75. package/bin/commands/stack-merge-escalations.d.mts +2 -1
  76. package/bin/commands/stack-merge-plan.mjs +35 -41
  77. package/bin/commands/stack-merge-trunk-check.d.mts +0 -2
  78. package/bin/commands/stack-merge-trunk-check.mjs +0 -2
  79. package/bin/commands/stack-ownership.mjs +3 -3
  80. package/bin/commands/stack-stall.d.mts +1 -0
  81. package/bin/commands/stack-stall.mjs +6 -2
  82. package/bin/commands/stack-trunk-behind.d.mts +1 -1
  83. package/bin/commands/stack-trunk-behind.mjs +1 -1
  84. package/bin/commands/stack-work.mjs +1 -1
  85. package/bin/config/merge-command-args.d.mts +2 -0
  86. package/bin/config/merge-command-args.mjs +13 -0
  87. package/bin/config/merge-method.d.mts +0 -5
  88. package/bin/config/merge-method.mjs +0 -6
  89. package/bin/config/schema.d.mts +2 -0
  90. package/bin/config/schema.mjs +2 -13
  91. package/bin/github/batch-parser-helpers.d.mts +5 -0
  92. package/bin/github/batch-parser-helpers.mjs +7 -2
  93. package/bin/github/batch-parsers.mjs +6 -2
  94. package/bin/github/errors.d.mts +2 -0
  95. package/bin/github/errors.mjs +1 -1
  96. package/bin/github/poll-summary-annotation-probe.d.mts +1 -1
  97. package/bin/github/poll-summary-annotation-probe.mjs +2 -2
  98. package/bin/github/poll-summary-command.d.mts +3 -2
  99. package/bin/github/poll-summary-command.mjs +6 -4
  100. package/bin/github/poll-summary-projector.mjs +16 -14
  101. package/bin/github/poll-summary-readiness.d.mts +4 -0
  102. package/bin/github/poll-summary-readiness.mjs +22 -0
  103. package/bin/github/poll-summary-rest-queue.d.mts +13 -0
  104. package/bin/github/poll-summary-rest-queue.mjs +21 -0
  105. package/bin/github/poll-summary-review-helpers.mjs +8 -4
  106. package/bin/state/merge-method-cache.d.mts +19 -0
  107. package/bin/state/merge-method-cache.mjs +27 -0
  108. package/bin/state/merge-request-claim.d.mts +23 -0
  109. package/bin/state/merge-request-claim.mjs +44 -0
  110. package/bin/state/merge-request-clear.d.mts +24 -0
  111. package/bin/state/merge-request-clear.mjs +36 -0
  112. package/bin/state/merge-request-lock.d.mts +13 -0
  113. package/bin/state/merge-request-lock.mjs +136 -0
  114. package/bin/state/merge-request-stack-heads.d.mts +2 -0
  115. package/bin/state/merge-request-stack-heads.mjs +8 -0
  116. package/bin/state/merge-request.d.mts +23 -6
  117. package/bin/state/merge-request.mjs +29 -29
  118. package/bin/state/ready-receipts.d.mts +11 -0
  119. package/bin/state/ready-receipts.mjs +7 -0
  120. package/bin/state/watch-lock.d.mts +10 -0
  121. package/bin/state/watch-lock.mjs +38 -3
  122. package/bin/types/poll-summary.d.mts +2 -0
  123. package/package.json +12 -5
  124. package/plugins/pr-shepherd/.claude-plugin/plugin.json +1 -1
  125. package/plugins/pr-shepherd/.codex-plugin/plugin.json +1 -1
  126. package/plugins/pr-shepherd/skills/pr-shepherd/SKILL.md +1 -1
  127. package/plugins/pr-shepherd/skills/pr-shepherd/references/create-a-pr.md +2 -2
  128. package/plugins/pr-shepherd/skills/pr-shepherd/references/waiting.md +1 -1
  129. package/plugins/pr-shepherd/skills/setup-pr-shepherd/references/classifiers.md +1 -1
  130. package/pr-shepherd.schema.json +8 -0
  131. package/bin/commands/stack-merge-flag.d.mts +0 -7
  132. package/bin/commands/stack-merge-flag.mjs +0 -6
@@ -10,3 +10,24 @@ export function restQueueRequirement(raw) {
10
10
  return undefined;
11
11
  return false;
12
12
  }
13
+ /**
14
+ * A trunk that requires linear history excludes merge commits from a stack's direct merge. Only
15
+ * a positive rule is surfaced: a negative or unreadable policy stays omitted so a row never
16
+ * claims a requirement it did not see. Non-stack GraphQL rows omit it too, since a one-PR merge
17
+ * reads linear history itself.
18
+ */
19
+ export function stackLinearHistoryRequirement(raw) {
20
+ if (raw.transport !== "rest" && !raw.stack)
21
+ return undefined;
22
+ return parseBranchRules(raw.baseRef).requiresLinearHistory ? true : undefined;
23
+ }
24
+ /**
25
+ * GraphQL reads the complete rules and the queue flag, so a native-stack row states its trunk's
26
+ * queue requirement and the printed stack merge picks the queue or direct route without a guess.
27
+ * Other rows omit it: a one-PR merge reads queue policy itself.
28
+ */
29
+ export function graphqlStackQueueRequirement(raw) {
30
+ if (!raw.stack || !raw.baseRef)
31
+ return undefined;
32
+ return parseBranchRules(raw.baseRef).requiresMergeQueue || raw.isMergeQueueEnabled === true;
33
+ }
@@ -3,7 +3,7 @@ import { shouldMinimizeAuthor } from "../comments/minimize-policy.mjs";
3
3
  import { isConfiguredBotAuthor, isHumanAuthor, normalizeAuthorType, } from "../comments/authors.mjs";
4
4
  import { classifyItem, mutationWasDenied } from "../state/seen-comments.mjs";
5
5
  import { canGenerateGithubMutation } from "./mutation-policy.mjs";
6
- import { parseCreatedAt } from "./batch-parser-helpers.mjs";
6
+ import { latestApprovedLogins, parseCreatedAt } from "./batch-parser-helpers.mjs";
7
7
  import { ruleHides, summaryRuleAction } from "./poll-summary-rule-items.mjs";
8
8
  const authorOf = (author) => ({
9
9
  login: author?.login ?? "",
@@ -39,7 +39,11 @@ function canMinimizeSummaryReview(review, blockedReviewIds, seen, minimizeCommen
39
39
  }
40
40
  export function countActionableSummaryReviews(input) {
41
41
  const { raw, summaryActions, rules, confirmed, unconfirmed, blockedReviewIds, seen, viewerCanAdminister, minimizeApprovals, minimizeSupersededApprovals, minimizeComments, bots, } = input;
42
- const latestStateByAuthor = new Map((raw.latestReviews?.nodes ?? []).flatMap((review) => review.author ? [[review.author.login.toLowerCase(), review.state]] : []));
42
+ // The full check's rule, shared: a latest APPROVED or DISMISSED review settles the author's
43
+ // older CHANGES_REQUESTED reviews, so the full check never shows or marks them.
44
+ const settledAuthors = latestApprovedLogins(
45
+ // A review with no author settles nothing, and nothing settles it.
46
+ (raw.latestReviews?.nodes ?? []).flatMap((review) => review.author ? [{ login: review.author.login, state: review.state }] : []));
43
47
  const supersededApprovalIds = summarySupersededApprovalIds(raw);
44
48
  const canMinimize = (review) => canMinimizeSummaryReview(review, blockedReviewIds, seen, minimizeComments, bots);
45
49
  let actionable = 0;
@@ -64,8 +68,8 @@ export function countActionableSummaryReviews(input) {
64
68
  }
65
69
  if (review.state !== "CHANGES_REQUESTED")
66
70
  continue;
67
- const login = review.author?.login.toLowerCase();
68
- if (login && latestStateByAuthor.get(login) === "APPROVED")
71
+ const login = review.author?.login;
72
+ if (login && settledAuthors.has(login.toLowerCase()))
69
73
  continue;
70
74
  if (ruleHides(summaryRuleAction(rules, "changes-requested", review), "changes-requested", false))
71
75
  continue;
@@ -0,0 +1,19 @@
1
+ import type { MergeMethod } from "../config/merge-method.mts";
2
+ /**
3
+ * The one merge method a repository allows, learned when `apply merge --merge-action default`
4
+ * could not read its asynchronous status. Open schema: readers ignore unknown fields.
5
+ */
6
+ export interface RepoMergeMethodRecord {
7
+ method: MergeMethod;
8
+ reason: string;
9
+ recordedAt: number;
10
+ }
11
+ type Key = {
12
+ owner: string;
13
+ repo: string;
14
+ };
15
+ /** An unreadable or malformed file counts as no cache; the next call re-reads the settings. */
16
+ export declare function readRepoMergeMethod(key: Key): Promise<RepoMergeMethodRecord | null>;
17
+ export declare function writeRepoMergeMethod(key: Key, record: RepoMergeMethodRecord): Promise<void>;
18
+ export declare function clearRepoMergeMethod(key: Key): Promise<void>;
19
+ export {};
@@ -0,0 +1,27 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import { mkdir, rm, writeFile } from "./guarded-fs.mjs";
4
+ import { resolveRepoStateDir } from "./base.mjs";
5
+ const path = (key) => join(resolveRepoStateDir(key), "merge-method.json");
6
+ /** An unreadable or malformed file counts as no cache; the next call re-reads the settings. */
7
+ export async function readRepoMergeMethod(key) {
8
+ try {
9
+ const parsed = JSON.parse(await readFile(path(key), "utf8"));
10
+ return parsed !== null &&
11
+ typeof parsed === "object" &&
12
+ typeof parsed.method === "string" &&
13
+ ["merge", "squash", "rebase"].includes(parsed.method)
14
+ ? parsed
15
+ : null;
16
+ }
17
+ catch {
18
+ return null;
19
+ }
20
+ }
21
+ export async function writeRepoMergeMethod(key, record) {
22
+ await mkdir(resolveRepoStateDir(key), { recursive: true });
23
+ await writeFile(path(key), `${JSON.stringify(record)}\n`, "utf8");
24
+ }
25
+ export async function clearRepoMergeMethod(key) {
26
+ await rm(path(key), { force: true });
27
+ }
@@ -0,0 +1,23 @@
1
+ import { type MergeRequestRecord } from "./merge-request.mts";
2
+ type Key = {
3
+ owner: string;
4
+ repo: string;
5
+ pr: number;
6
+ };
7
+ /**
8
+ * Take the PR's request path for `record` under the merge-request lock, only while it still holds
9
+ * exactly `existing` (null: empty). A superseded request is replaced in one atomic rename that
10
+ * carries its UUID forward, so the path is never vacant and its possibly outstanding job stays on
11
+ * record. False means another process changed the path since it was read, or held the lock.
12
+ */
13
+ export declare function claimMergeRequestLocked(key: Key, existing: MergeRequestRecord | null, record: MergeRequestRecord, supersede: boolean, removalAcknowledged?: boolean): Promise<boolean>;
14
+ /**
15
+ * Rewrite the status of the request `existing` names from its current state under the lock, so a
16
+ * marker another run recorded since (such as `syncMergeSent`) is never replaced by a stale
17
+ * snapshot. Skipped when the request was replaced or retired, or the lock stayed busy: the status
18
+ * file only caches what the next status read reports again. `update` returns null to skip, for an
19
+ * observation that a newer one already recorded superseded. False means the lock stayed busy, so
20
+ * nothing was decided.
21
+ */
22
+ export declare function updateMergeRequestStatusLocked(key: Key, existing: MergeRequestRecord, update: (current: MergeRequestRecord) => MergeRequestRecord | null): Promise<boolean>;
23
+ export {};
@@ -0,0 +1,44 @@
1
+ import { rm } from "./guarded-fs.mjs";
2
+ import { withMergeRequestLock } from "./merge-request-lock.mjs";
3
+ import { claimMergeRequest, mergeRequestGeneration, mergeRequestStatusPath, readMergeRequest, replaceFailedMergeRequest, writeMergeRequest, writeMergeRequestStatus, } from "./merge-request.mjs";
4
+ /**
5
+ * Take the PR's request path for `record` under the merge-request lock, only while it still holds
6
+ * exactly `existing` (null: empty). A superseded request is replaced in one atomic rename that
7
+ * carries its UUID forward, so the path is never vacant and its possibly outstanding job stays on
8
+ * record. False means another process changed the path since it was read, or held the lock.
9
+ */
10
+ export async function claimMergeRequestLocked(key, existing, record, supersede, removalAcknowledged = false) {
11
+ return withMergeRequestLock(key, async () => {
12
+ if (JSON.stringify(await readMergeRequest(key)) !== JSON.stringify(existing))
13
+ return false;
14
+ if (!existing)
15
+ return claimMergeRequest(key, record);
16
+ if (!supersede)
17
+ return replaceFailedMergeRequest(key, existing, record, removalAcknowledged);
18
+ await writeMergeRequest(key, {
19
+ ...record,
20
+ ...(existing.uuid && { supersededUuid: existing.uuid }),
21
+ });
22
+ await rm(mergeRequestStatusPath(key, existing), { force: true });
23
+ return true;
24
+ }, () => false);
25
+ }
26
+ /**
27
+ * Rewrite the status of the request `existing` names from its current state under the lock, so a
28
+ * marker another run recorded since (such as `syncMergeSent`) is never replaced by a stale
29
+ * snapshot. Skipped when the request was replaced or retired, or the lock stayed busy: the status
30
+ * file only caches what the next status read reports again. `update` returns null to skip, for an
31
+ * observation that a newer one already recorded superseded. False means the lock stayed busy, so
32
+ * nothing was decided.
33
+ */
34
+ export async function updateMergeRequestStatusLocked(key, existing, update) {
35
+ return withMergeRequestLock(key, async () => {
36
+ const current = await readMergeRequest(key);
37
+ if (!current || mergeRequestGeneration(current) !== mergeRequestGeneration(existing))
38
+ return true;
39
+ const next = update(current);
40
+ if (next)
41
+ await writeMergeRequestStatus(key, next);
42
+ return true;
43
+ }, () => false);
44
+ }
@@ -0,0 +1,24 @@
1
+ import type { RestMergeResponse } from "../github/rest-merge.mts";
2
+ import { type MergeRequestRecord } from "./merge-request.mts";
3
+ type Key = {
4
+ owner: string;
5
+ repo: string;
6
+ pr: number;
7
+ };
8
+ /**
9
+ * Retire a request only while the path still holds the generation the caller owns, under the
10
+ * merge-request lock, so a successor claimed since is never removed and the path is never vacant
11
+ * while it is checked. The status file goes first: a later request of the same generation (same
12
+ * options, same second) must not inherit its markers, and an interruption between the two removals
13
+ * leaves the main record, whose rerun stays SHA-guarded. Returns false when the record changed or
14
+ * the lock stayed busy; the record is then left in place.
15
+ */
16
+ export declare function clearMergeRequestIf(key: Key, expected: MergeRequestRecord): Promise<boolean>;
17
+ /**
18
+ * Record a definite failed answer on the request, only while the path still holds the generation
19
+ * the caller owns, under the merge-request lock, so a successor is never overwritten. The failed
20
+ * response lets the replace-failed path retire it for a changed head or option. Returns false when
21
+ * nothing was recorded (a successor, a missing or unreadable record, or the lock stayed busy).
22
+ */
23
+ export declare function recordFailedResponseIf(key: Key, expected: MergeRequestRecord, details: RestMergeResponse["details"]): Promise<boolean>;
24
+ export {};
@@ -0,0 +1,36 @@
1
+ import { rm } from "./guarded-fs.mjs";
2
+ import { withMergeRequestLock } from "./merge-request-lock.mjs";
3
+ import { mergeRequestGeneration, mergeRequestPath, mergeRequestStatusPath, readMergeRequest, writeMergeRequest, } from "./merge-request.mjs";
4
+ /**
5
+ * Retire a request only while the path still holds the generation the caller owns, under the
6
+ * merge-request lock, so a successor claimed since is never removed and the path is never vacant
7
+ * while it is checked. The status file goes first: a later request of the same generation (same
8
+ * options, same second) must not inherit its markers, and an interruption between the two removals
9
+ * leaves the main record, whose rerun stays SHA-guarded. Returns false when the record changed or
10
+ * the lock stayed busy; the record is then left in place.
11
+ */
12
+ export async function clearMergeRequestIf(key, expected) {
13
+ return withMergeRequestLock(key, async () => {
14
+ const current = await readMergeRequest(key).catch(() => null);
15
+ if (!current || mergeRequestGeneration(current) !== mergeRequestGeneration(expected))
16
+ return false;
17
+ await rm(mergeRequestStatusPath(key, expected), { force: true });
18
+ await rm(mergeRequestPath(key), { force: true });
19
+ return true;
20
+ }, () => false);
21
+ }
22
+ /**
23
+ * Record a definite failed answer on the request, only while the path still holds the generation
24
+ * the caller owns, under the merge-request lock, so a successor is never overwritten. The failed
25
+ * response lets the replace-failed path retire it for a changed head or option. Returns false when
26
+ * nothing was recorded (a successor, a missing or unreadable record, or the lock stayed busy).
27
+ */
28
+ export async function recordFailedResponseIf(key, expected, details) {
29
+ return withMergeRequestLock(key, async () => {
30
+ const current = await readMergeRequest(key).catch(() => null);
31
+ if (!current || mergeRequestGeneration(current) !== mergeRequestGeneration(expected))
32
+ return false;
33
+ await writeMergeRequest(key, { ...current, response: { status: "failed", details } });
34
+ return true;
35
+ }, () => false);
36
+ }
@@ -0,0 +1,13 @@
1
+ type Key = {
2
+ owner: string;
3
+ repo: string;
4
+ pr: number;
5
+ };
6
+ /**
7
+ * Runs `fn` while this process exclusively owns the PR's merge-request state, so claiming,
8
+ * superseding, and retiring a request are each one step to every other `apply merge`. The lock
9
+ * covers local file work only, never a GitHub call, so the bounded wait is short. A dead or
10
+ * PID-reused holder is taken over. Returns `onBusy()` when a live holder keeps it.
11
+ */
12
+ export declare function withMergeRequestLock<T>(key: Key, fn: () => Promise<T>, onBusy: () => T): Promise<T>;
13
+ export {};
@@ -0,0 +1,136 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { readFile } from "node:fs/promises";
3
+ import { setTimeout as delay } from "node:timers/promises";
4
+ import { dirname } from "node:path";
5
+ import { link, mkdir, rename, unlink, writeFile } from "./guarded-fs.mjs";
6
+ import { resolvePrStatePath } from "./base.mjs";
7
+ import { readProcessStart } from "./process-start.mjs";
8
+ const ATTEMPTS = 40;
9
+ const RETRY_MS = 25;
10
+ let ownStartToken;
11
+ /** This process's start token, read once: reading it may spawn `ps`. */
12
+ function ownStart() {
13
+ ownStartToken ??= { value: readProcessStart(process.pid) };
14
+ return ownStartToken.value;
15
+ }
16
+ const lockPath = (key) => resolvePrStatePath(key, "merge-request.lock");
17
+ /** The lock's raw bytes, or null when there is no lock file. */
18
+ async function readRaw(path) {
19
+ try {
20
+ return await readFile(path, "utf8");
21
+ }
22
+ catch (error) {
23
+ if (error.code === "ENOENT")
24
+ return null;
25
+ throw error;
26
+ }
27
+ }
28
+ function parseHolder(raw) {
29
+ try {
30
+ const parsed = JSON.parse(raw);
31
+ return Number.isInteger(parsed.pid) && parsed.pid > 0 && typeof parsed.token === "string"
32
+ ? parsed
33
+ : undefined;
34
+ }
35
+ catch {
36
+ return undefined;
37
+ }
38
+ }
39
+ /** The watch lock's rule: only ESRCH, or a readable start time that differs, proves a dead holder. */
40
+ function isStale(holder) {
41
+ try {
42
+ process.kill(holder.pid, 0);
43
+ }
44
+ catch (error) {
45
+ if (error.code === "ESRCH")
46
+ return true;
47
+ }
48
+ if (!holder.startedAt)
49
+ return false;
50
+ const current = holder.pid === process.pid ? ownStart() : readProcessStart(holder.pid);
51
+ return current !== undefined && current !== holder.startedAt;
52
+ }
53
+ /** Publishes the full holder atomically: the hard link fails with EEXIST while a lock exists. */
54
+ async function linkLock(path, mine) {
55
+ const temporary = `${path}.${mine.token}.tmp`;
56
+ await writeFile(temporary, JSON.stringify(mine));
57
+ try {
58
+ await link(temporary, path);
59
+ return true;
60
+ }
61
+ catch (error) {
62
+ if (error.code === "EEXIST")
63
+ return false;
64
+ throw error;
65
+ }
66
+ finally {
67
+ await unlink(temporary).catch(() => { });
68
+ }
69
+ }
70
+ /**
71
+ * Replaces a dead or unparseable holder's lock without ever deleting a path by name. Only the one
72
+ * process that exclusively creates the claim named for those exact bytes may replace them, so two
73
+ * takeovers of one stale lock cannot both win; every lock carries a random token, so a newer lock
74
+ * never shares that name. The claimant re-reads the lock and swaps its own holder in with one atomic
75
+ * rename. Nothing else can change the path in between: a normal acquisition fails while the stale
76
+ * lock exists, and only this claimant may replace it. A pause anywhere in this sequence therefore
77
+ * cannot hand the lock to a second owner. A claimant that crashes before the rename leaves its
78
+ * claim behind, so that lock stays busy (fail closed) until `pr-shepherd admin clean pr <N>`
79
+ * removes the PR's state. A missing file is not taken over: the next link attempt claims it.
80
+ */
81
+ async function takeOverIfStale(path, mine) {
82
+ const seen = await readRaw(path);
83
+ if (seen === null)
84
+ return false;
85
+ const holder = parseHolder(seen);
86
+ if (holder && !isStale(holder))
87
+ return false;
88
+ const claim = `${path}.takeover-${createHash("sha256").update(seen).digest("hex").slice(0, 32)}`;
89
+ try {
90
+ await writeFile(claim, JSON.stringify(mine), { flag: "wx" });
91
+ }
92
+ catch (error) {
93
+ if (error.code === "EEXIST")
94
+ return false;
95
+ throw error;
96
+ }
97
+ try {
98
+ if ((await readRaw(path)) !== seen)
99
+ return false;
100
+ const temporary = `${path}.${mine.token}.takeover.tmp`;
101
+ await writeFile(temporary, JSON.stringify(mine));
102
+ await rename(temporary, path);
103
+ return true;
104
+ }
105
+ finally {
106
+ // This process created the claim, and the bytes it names are gone or were never the lock's.
107
+ await unlink(claim).catch(() => { });
108
+ }
109
+ }
110
+ /**
111
+ * Runs `fn` while this process exclusively owns the PR's merge-request state, so claiming,
112
+ * superseding, and retiring a request are each one step to every other `apply merge`. The lock
113
+ * covers local file work only, never a GitHub call, so the bounded wait is short. A dead or
114
+ * PID-reused holder is taken over. Returns `onBusy()` when a live holder keeps it.
115
+ */
116
+ export async function withMergeRequestLock(key, fn, onBusy) {
117
+ const path = lockPath(key);
118
+ await mkdir(dirname(path), { recursive: true });
119
+ const startedAt = ownStart();
120
+ const mine = { pid: process.pid, ...(startedAt && { startedAt }), token: randomUUID() };
121
+ for (let attempt = 0;; attempt += 1) {
122
+ if ((await linkLock(path, mine)) || (await takeOverIfStale(path, mine)))
123
+ break;
124
+ if (attempt + 1 >= ATTEMPTS)
125
+ return onBusy();
126
+ await delay(RETRY_MS);
127
+ }
128
+ try {
129
+ return await fn();
130
+ }
131
+ finally {
132
+ const current = await readRaw(path).catch(() => null);
133
+ if (current !== null && parseHolder(current)?.token === mine.token)
134
+ await unlink(path).catch(() => { });
135
+ }
136
+ }
@@ -0,0 +1,2 @@
1
+ /** Reject a persisted stack-head baseline that is not a list of `{ pr, headRefOid }` layers. */
2
+ export declare function assertValidStackHeads(heads: unknown): void;
@@ -0,0 +1,8 @@
1
+ /** Reject a persisted stack-head baseline that is not a list of `{ pr, headRefOid }` layers. */
2
+ export function assertValidStackHeads(heads) {
3
+ if (heads === undefined)
4
+ return;
5
+ if (!Array.isArray(heads) ||
6
+ heads.some((layer) => !Number.isSafeInteger(layer?.pr) || !/^[0-9a-f]{40}$/.test(String(layer?.headRefOid ?? ""))))
7
+ throw new Error("Invalid asynchronous merge state: malformed stackHeads");
8
+ }
@@ -3,28 +3,45 @@ export interface MergeRequestRecord {
3
3
  version: 1;
4
4
  options: RestMergeOptions;
5
5
  startedAtUnix: number;
6
+ /** The second just before the submit PUT that GitHub answered `enqueued`; an acknowledged removal must be later. */
7
+ submittedAtUnix?: number;
6
8
  uuid?: string;
7
9
  response?: RestMergeResponse;
8
10
  uncertain?: true;
11
+ /** A `default` request whose asynchronous status read was refused and could not be routed. */
12
+ statusUnreadable?: true;
13
+ /** The synchronous fallback was sent for this request; its outcome is not yet confirmed. */
14
+ syncMergeSent?: true;
15
+ /** The UUID of the unreadable `default` request this one superseded; it may still execute. */
16
+ supersededUuid?: string;
9
17
  /** Identifies the one consumable source of a permanently recorded successor. */
10
18
  replacementToken?: string;
19
+ /** Unique per fresh claim, so a successor never shares a generation with the request it replaced. */
20
+ claimId?: string;
21
+ /** Changes on every readable status write, so an older refused read can tell it was overtaken. */
22
+ statusRevision?: string;
23
+ /** Native-stack heads validated at submission, kept even without an `expectedStack`. */
24
+ stackHeads?: Array<{
25
+ pr: number;
26
+ headRefOid: string;
27
+ }>;
11
28
  }
12
29
  type Key = {
13
30
  owner: string;
14
31
  repo: string;
15
32
  pr: number;
16
33
  };
34
+ export declare const mergeRequestPath: (key: Key) => string;
35
+ export declare const mergeRequestGeneration: (record: MergeRequestRecord) => string;
36
+ export declare const mergeRequestStatusPath: (key: Key, record: MergeRequestRecord) => string;
17
37
  export declare function readMergeRequest(key: Key): Promise<MergeRequestRecord | null>;
18
38
  /** Persist intent exclusively before contacting GitHub; another process cannot submit it twice. */
19
39
  export declare function claimMergeRequest(key: Key, record: MergeRequestRecord): Promise<boolean>;
20
- /** Consume one durable successor of a failed request or an enqueue guarded by an older head. */
21
- export declare function replaceFailedMergeRequest(key: Key, previous: MergeRequestRecord, next: MergeRequestRecord): Promise<boolean>;
22
40
  /**
23
- * Retire a request whose asynchronous status can no longer be read, once the synchronous fallback
24
- * has answered. A merged PR is detected from the pull itself, so no record is needed; a refusal is
25
- * surfaced to the caller, and a rerun starts a fresh guarded attempt instead of replaying it.
41
+ * Consume one durable successor of a failed request, an enqueue guarded by an older head, or an
42
+ * enqueue whose queue removal the caller acknowledged (`removalAcknowledged`).
26
43
  */
27
- export declare function clearMergeRequest(key: Key): Promise<void>;
44
+ export declare function replaceFailedMergeRequest(key: Key, previous: MergeRequestRecord, next: MergeRequestRecord, removalAcknowledged?: boolean): Promise<boolean>;
28
45
  export declare function writeMergeRequest(key: Key, record: MergeRequestRecord): Promise<void>;
29
46
  /** A delayed status poll can update only its own intent, never a later main request. */
30
47
  export declare function writeMergeRequestStatus(key: Key, record: MergeRequestRecord): Promise<void>;
@@ -1,11 +1,12 @@
1
+ import { assertValidStackHeads } from "./merge-request-stack-heads.mjs";
1
2
  import { createHash, randomUUID } from "node:crypto";
2
3
  import { readFile } from "node:fs/promises";
3
- import { link, mkdir, rename, rm, unlink, writeFile } from "./guarded-fs.mjs";
4
+ import { link, 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 { restMergeStackGuardKey, validateRestMergeStackGuard, } from "../github/rest-merge-stack-guard.mjs";
7
- const path = (key) => resolvePrStatePath(key, "merge-async.json");
8
- const generation = (record) => createHash("sha256")
8
+ export const mergeRequestPath = (key) => resolvePrStatePath(key, "merge-async.json");
9
+ export const mergeRequestGeneration = (record) => createHash("sha256")
9
10
  .update(JSON.stringify([
10
11
  record.options.requireSha,
11
12
  record.options.mergeAction,
@@ -15,24 +16,25 @@ const generation = (record) => createHash("sha256")
15
16
  ...(record.options.expectedStack
16
17
  ? [restMergeStackGuardKey(record.options.expectedStack)]
17
18
  : []),
19
+ ...(record.claimId ? [{ claimId: record.claimId }] : []),
18
20
  ]))
19
21
  .digest("hex")
20
22
  .slice(0, 24);
21
- const statusPath = (key, record) => resolvePrStatePath(key, `merge-async-status-${generation(record)}.json`);
23
+ export const mergeRequestStatusPath = (key, record) => resolvePrStatePath(key, `merge-async-status-${mergeRequestGeneration(record)}.json`);
22
24
  export async function readMergeRequest(key) {
23
25
  let raw;
24
26
  try {
25
- raw = await readFile(path(key), "utf8");
27
+ raw = await readFile(mergeRequestPath(key), "utf8");
26
28
  }
27
29
  catch (error) {
28
30
  if (error.code === "ENOENT")
29
31
  return null;
30
32
  throw error;
31
33
  }
32
- const record = parseRecord(raw);
34
+ const record = parseMergeRequest(raw);
33
35
  try {
34
- const status = parseRecord(await readFile(statusPath(key, record), "utf8"));
35
- if (generation(status) !== generation(record))
36
+ const status = parseMergeRequest(await readFile(mergeRequestStatusPath(key, record), "utf8"));
37
+ if (mergeRequestGeneration(status) !== mergeRequestGeneration(record))
36
38
  throw new Error("Asynchronous merge status does not match its persisted intent");
37
39
  return status;
38
40
  }
@@ -42,17 +44,20 @@ export async function readMergeRequest(key) {
42
44
  throw error;
43
45
  }
44
46
  }
45
- function parseRecord(raw) {
47
+ const UUID_V4 = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
48
+ function parseMergeRequest(raw) {
46
49
  const record = JSON.parse(raw);
47
50
  if (record?.version !== 1 ||
48
51
  !/^[0-9a-f]{40}$/.test(record.options?.requireSha ?? "") ||
49
52
  !["direct_merge", "merge_queue", "default"].includes(record.options.mergeAction) ||
50
53
  !Number.isSafeInteger(record.startedAtUnix) ||
54
+ (record.submittedAtUnix !== undefined && !Number.isSafeInteger(record.submittedAtUnix)) ||
51
55
  (record.uuid !== undefined && !/^[0-9a-f-]{36}$/i.test(record.uuid)) ||
52
- (record.replacementToken !== undefined &&
53
- !/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(record.replacementToken))) {
56
+ (record.supersededUuid !== undefined && !/^[0-9a-f-]{36}$/i.test(record.supersededUuid)) ||
57
+ [record.replacementToken, record.claimId, record.statusRevision].some((token) => token !== undefined && !UUID_V4.test(token))) {
54
58
  throw new Error("Invalid asynchronous merge state; outcome must be reconciled before another request");
55
59
  }
60
+ assertValidStackHeads(record.stackHeads);
56
61
  if (record.options.expectedStack !== undefined) {
57
62
  validateRestMergeStackGuard(record.options.expectedStack);
58
63
  if (record.options.expectedStack.prefix.at(-1)?.headRefOid !== record.options.requireSha)
@@ -62,9 +67,9 @@ function parseRecord(raw) {
62
67
  }
63
68
  /** Persist intent exclusively before contacting GitHub; another process cannot submit it twice. */
64
69
  export async function claimMergeRequest(key, record) {
65
- await mkdir(dirname(path(key)), { recursive: true });
70
+ await mkdir(dirname(mergeRequestPath(key)), { recursive: true });
66
71
  try {
67
- await writeFile(path(key), `${JSON.stringify(record)}\n`, { flag: "wx" });
72
+ await writeFile(mergeRequestPath(key), `${JSON.stringify(record)}\n`, { flag: "wx" });
68
73
  return true;
69
74
  }
70
75
  catch (error) {
@@ -73,14 +78,17 @@ export async function claimMergeRequest(key, record) {
73
78
  throw error;
74
79
  }
75
80
  }
76
- /** Consume one durable successor of a failed request or an enqueue guarded by an older head. */
77
- export async function replaceFailedMergeRequest(key, previous, next) {
81
+ /**
82
+ * Consume one durable successor of a failed request, an enqueue guarded by an older head, or an
83
+ * enqueue whose queue removal the caller acknowledged (`removalAcknowledged`).
84
+ */
85
+ export async function replaceFailedMergeRequest(key, previous, next, removalAcknowledged = false) {
78
86
  if (previous.uncertain ||
79
87
  (previous.response?.status !== "failed" &&
80
88
  !(previous.response?.status === "enqueued" &&
81
- previous.options.requireSha !== next.options.requireSha)))
89
+ (removalAcknowledged || previous.options.requireSha !== next.options.requireSha))))
82
90
  return false;
83
- const stem = resolvePrStatePath(key, `merge-async-successor-${generation(previous)}`);
91
+ const stem = resolvePrStatePath(key, `merge-async-successor-${mergeRequestGeneration(previous)}`);
84
92
  const candidate = { ...next, replacementToken: randomUUID() };
85
93
  const source = `${stem}-${candidate.replacementToken}.json`;
86
94
  let created = false;
@@ -99,7 +107,7 @@ export async function replaceFailedMergeRequest(key, previous, next) {
99
107
  catch (error) {
100
108
  if (error.code !== "EEXIST")
101
109
  throw error;
102
- persisted = parseRecord(await readFile(`${stem}.json`, "utf8"));
110
+ persisted = parseMergeRequest(await readFile(`${stem}.json`, "utf8"));
103
111
  if (!persisted.replacementToken)
104
112
  throw new Error("Merge successor has no recovery token; reconcile its outcome");
105
113
  if (persisted.options.requireSha !== next.options.requireSha ||
@@ -113,7 +121,7 @@ export async function replaceFailedMergeRequest(key, previous, next) {
113
121
  return false;
114
122
  try {
115
123
  // Never recreate this source: its absence means another caller already consumed the intent.
116
- await rename(`${stem}-${persisted.replacementToken}.json`, path(key));
124
+ await rename(`${stem}-${persisted.replacementToken}.json`, mergeRequestPath(key));
117
125
  }
118
126
  catch (error) {
119
127
  if (error.code === "ENOENT")
@@ -127,20 +135,12 @@ export async function replaceFailedMergeRequest(key, previous, next) {
127
135
  await unlink(source).catch(() => { });
128
136
  }
129
137
  }
130
- /**
131
- * Retire a request whose asynchronous status can no longer be read, once the synchronous fallback
132
- * has answered. A merged PR is detected from the pull itself, so no record is needed; a refusal is
133
- * surfaced to the caller, and a rerun starts a fresh guarded attempt instead of replaying it.
134
- */
135
- export async function clearMergeRequest(key) {
136
- await rm(path(key), { force: true });
137
- }
138
138
  export async function writeMergeRequest(key, record) {
139
- await writeRecord(path(key), record);
139
+ await writeRecord(mergeRequestPath(key), record);
140
140
  }
141
141
  /** A delayed status poll can update only its own intent, never a later main request. */
142
142
  export async function writeMergeRequestStatus(key, record) {
143
- await writeRecord(statusPath(key, record), record);
143
+ await writeRecord(mergeRequestStatusPath(key, record), record);
144
144
  }
145
145
  async function writeRecord(destination, record) {
146
146
  const temporary = `${destination}.${randomUUID()}.tmp`;
@@ -17,6 +17,12 @@ export interface ReadyReceipt {
17
17
  readinessFingerprint: string;
18
18
  /** Exact merge-queue removal observed by the one-PR session, if any. */
19
19
  acknowledgedQueueRemovalId?: string;
20
+ /**
21
+ * The READY full check read every review thread, for the summary hashed here (same request),
22
+ * and found all of them resolved. Only such a receipt vouches for threads older than the
23
+ * compact summary's window.
24
+ */
25
+ allThreadsResolved?: true;
20
26
  recordedAtUnix: number;
21
27
  }
22
28
  export interface ReadyReceiptKey {
@@ -43,3 +49,8 @@ export declare function clearReadyReceipt(key: ReadyReceiptKey): Promise<void>;
43
49
  * to create the receipt; ref OIDs alone are not sufficient.
44
50
  */
45
51
  export declare function isReadyReceiptCurrent(receipt: ReadyReceipt | null, current: ReadyReceiptCurrentState): receipt is ReadyReceipt;
52
+ /** The receipt's full check found every review thread resolved at exactly these commits. */
53
+ export declare function receiptResolvedAllThreads(receipt: ReadyReceipt | null, current: {
54
+ headRefOid: string;
55
+ baseRefOid: string;
56
+ }): boolean;
@@ -55,6 +55,12 @@ export function isReadyReceiptCurrent(receipt, current) {
55
55
  receipt.baseRefOid === current.baseRefOid &&
56
56
  receipt.readinessFingerprint === current.readinessFingerprint);
57
57
  }
58
+ /** The receipt's full check found every review thread resolved at exactly these commits. */
59
+ export function receiptResolvedAllThreads(receipt, current) {
60
+ return (receipt?.allThreadsResolved === true &&
61
+ receipt.headRefOid === current.headRefOid &&
62
+ receipt.baseRefOid === current.baseRefOid);
63
+ }
58
64
  function receiptPath(key) {
59
65
  return resolvePrStatePath(key, "ready-receipt.json");
60
66
  }
@@ -82,6 +88,7 @@ function isReadyReceipt(value) {
82
88
  (candidate.acknowledgedQueueRemovalId === undefined ||
83
89
  (typeof candidate.acknowledgedQueueRemovalId === "string" &&
84
90
  candidate.acknowledgedQueueRemovalId.length > 0)) &&
91
+ (candidate.allThreadsResolved === undefined || candidate.allThreadsResolved === true) &&
85
92
  typeof candidate.recordedAtUnix === "number" &&
86
93
  Number.isFinite(candidate.recordedAtUnix));
87
94
  }