pr-shepherd 0.51.1 → 0.52.1

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 (116) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/README.md +29 -18
  3. package/bin/cli/help-command-pages.d.mts +1 -1
  4. package/bin/cli/help-iterate-poll-pages.d.mts +1 -1
  5. package/bin/cli/help-iterate-poll-pages.mjs +4 -3
  6. package/bin/cli/help-top-page.d.mts +1 -1
  7. package/bin/cli/help-top-page.mjs +3 -2
  8. package/bin/cli/help.d.mts +2 -2
  9. package/bin/cli/iterate-instructions.mjs +41 -0
  10. package/bin/cli/iterate-lean.mjs +1 -3
  11. package/bin/cli/poll-summary-emitter.mjs +2 -3
  12. package/bin/cli/poll-summary-formatter.mjs +12 -3
  13. package/bin/cli/runner.d.mts +1 -0
  14. package/bin/cli/runner.mjs +3 -1
  15. package/bin/commands/check.mjs +14 -4
  16. package/bin/commands/clean.mjs +7 -13
  17. package/bin/commands/iterate/check-instructions.d.mts +2 -2
  18. package/bin/commands/iterate/check-instructions.mjs +11 -7
  19. package/bin/commands/iterate/escalate.mjs +4 -13
  20. package/bin/commands/iterate/fix-code.d.mts +2 -0
  21. package/bin/commands/iterate/fix-code.mjs +20 -43
  22. package/bin/commands/iterate/helpers.d.mts +0 -1
  23. package/bin/commands/iterate/helpers.mjs +0 -15
  24. package/bin/commands/iterate/index.mjs +178 -11
  25. package/bin/commands/iterate/merge-state.mjs +35 -18
  26. package/bin/commands/iterate/native-stack-rebase.d.mts +34 -0
  27. package/bin/commands/iterate/native-stack-rebase.mjs +43 -0
  28. package/bin/commands/iterate/parent-first.d.mts +25 -0
  29. package/bin/commands/iterate/parent-first.mjs +70 -0
  30. package/bin/commands/iterate/render.d.mts +1 -1
  31. package/bin/commands/iterate/render.mjs +7 -12
  32. package/bin/commands/iterate/stale-ancestry.d.mts +22 -0
  33. package/bin/commands/iterate/stale-ancestry.mjs +40 -0
  34. package/bin/commands/iterate/stall.mjs +40 -3
  35. package/bin/commands/poll-progress.d.mts +5 -1
  36. package/bin/commands/poll-progress.mjs +7 -1
  37. package/bin/commands/poll-summary-instructions.d.mts +6 -1
  38. package/bin/commands/poll-summary-instructions.mjs +151 -107
  39. package/bin/commands/poll-summary.mjs +32 -6
  40. package/bin/commands/poll.mjs +3 -1
  41. package/bin/commands/ready-delay.d.mts +9 -4
  42. package/bin/commands/ready-delay.mjs +34 -20
  43. package/bin/commands/shepherd-journal.mjs +4 -1
  44. package/bin/commands/stack-drain.d.mts +35 -0
  45. package/bin/commands/stack-drain.mjs +129 -0
  46. package/bin/commands/stack-layer-readiness.d.mts +7 -0
  47. package/bin/commands/stack-layer-readiness.mjs +35 -0
  48. package/bin/commands/stack-stall.d.mts +14 -0
  49. package/bin/commands/stack-stall.mjs +69 -0
  50. package/bin/commands/stack-work.d.mts +32 -0
  51. package/bin/commands/stack-work.mjs +39 -0
  52. package/bin/config/load.d.mts +2 -0
  53. package/bin/config/load.mjs +10 -0
  54. package/bin/config.json +1 -0
  55. package/bin/exit-codes.d.mts +2 -0
  56. package/bin/exit-codes.mjs +2 -0
  57. package/bin/github/batch-parsers.mjs +1 -0
  58. package/bin/github/batch-raw-types.d.mts +2 -0
  59. package/bin/github/errors.d.mts +5 -0
  60. package/bin/github/errors.mjs +4 -0
  61. package/bin/github/gql/batch-pr.gql +1 -0
  62. package/bin/github/gql/poll-stack-summary.gql +8 -2
  63. package/bin/github/gql/poll-stack-topology.gql +38 -0
  64. package/bin/github/gql/poll-summary-check-contexts.gql +34 -0
  65. package/bin/github/gql/poll-summary-check-page.gql +23 -0
  66. package/bin/github/gql/poll-summary-fragment.gql +53 -56
  67. package/bin/github/merge-queue-checks.mjs +10 -1
  68. package/bin/github/poll-summary-check-hydration.d.mts +12 -0
  69. package/bin/github/poll-summary-check-hydration.mjs +55 -0
  70. package/bin/github/poll-summary-fingerprint.d.mts +8 -0
  71. package/bin/github/poll-summary-fingerprint.mjs +48 -0
  72. package/bin/github/poll-summary-projector.mjs +70 -16
  73. package/bin/github/poll-summary-queue-removal.d.mts +5 -0
  74. package/bin/github/poll-summary-queue-removal.mjs +25 -0
  75. package/bin/github/poll-summary-raw.d.mts +52 -31
  76. package/bin/github/poll-summary-readiness.d.mts +6 -0
  77. package/bin/github/poll-summary-readiness.mjs +25 -0
  78. package/bin/github/poll-summary-route.mjs +8 -5
  79. package/bin/github/poll-summary.d.mts +3 -0
  80. package/bin/github/poll-summary.mjs +21 -73
  81. package/bin/github/queries.d.mts +7 -0
  82. package/bin/github/queries.mjs +9 -1
  83. package/bin/github/queue-removal-freshness.d.mts +16 -0
  84. package/bin/github/queue-removal-freshness.mjs +26 -0
  85. package/bin/github/stack-read.d.mts +34 -0
  86. package/bin/github/stack-read.mjs +92 -0
  87. package/bin/log/log-file.d.mts +1 -1
  88. package/bin/log/log-file.mjs +4 -17
  89. package/bin/state/base.d.mts +18 -1
  90. package/bin/state/base.mjs +65 -13
  91. package/bin/state/fix-attempts.d.mts +1 -1
  92. package/bin/state/fix-attempts.mjs +1 -1
  93. package/bin/state/graphql-quota-warnings.mjs +2 -6
  94. package/bin/state/iterate-stall.d.mts +7 -15
  95. package/bin/state/iterate-stall.mjs +6 -64
  96. package/bin/state/ready-receipts.d.mts +45 -0
  97. package/bin/state/ready-receipts.mjs +86 -0
  98. package/bin/state/rest-cache.d.mts +1 -1
  99. package/bin/state/rest-cache.mjs +1 -1
  100. package/bin/state/stack-stall.d.mts +16 -0
  101. package/bin/state/stack-stall.mjs +12 -0
  102. package/bin/state/stall-state-store.d.mts +37 -0
  103. package/bin/state/stall-state-store.mjs +74 -0
  104. package/bin/types/escalate.d.mts +2 -3
  105. package/bin/types/github.d.mts +2 -0
  106. package/bin/types/iterate.d.mts +2 -1
  107. package/bin/types/merge-requirements.d.mts +19 -0
  108. package/bin/types/poll-summary.d.mts +17 -2
  109. package/bin/types/report.d.mts +2 -0
  110. package/package.json +2 -2
  111. package/plugins/pr-shepherd/.codex-plugin/plugin.json +1 -1
  112. package/plugins/pr-shepherd/.codex.mcp.json +1 -1
  113. package/plugins/pr-shepherd/.mcp.json +1 -1
  114. package/plugins/pr-shepherd/skills/pr-shepherd/SKILL.md +3 -3
  115. package/bin/state/bot-cr-seen.d.mts +0 -51
  116. package/bin/state/bot-cr-seen.mjs +0 -100
@@ -1,5 +1,6 @@
1
1
  import type { ApiUsage, GraphqlQuotaWarning } from "./api-usage.mts";
2
2
  import type { MergeableState, MergeStateStatus, ReviewDecision } from "./github.mts";
3
+ import type { MergeQueueRemovalStatus } from "./merge-requirements.mts";
3
4
  import type { ShepherdAction } from "./iterate.mts";
4
5
  export interface PollSummaryChecks {
5
6
  passing?: number;
@@ -50,12 +51,22 @@ export interface PollSummaryItem {
50
51
  baseRefName: string;
51
52
  isDraft?: true;
52
53
  isInMergeQueue?: true;
54
+ queueRemoval?: MergeQueueRemovalStatus;
53
55
  blockingReviewerInProgress?: true;
54
56
  remainingSeconds?: number;
55
57
  checks?: PollSummaryChecks;
56
58
  review?: PollSummaryReview;
57
59
  stack?: PollSummaryStack;
58
60
  pollCommand?: string;
61
+ /**
62
+ * `pollCommand` is one bounded tick without automatic mark-ready: it surfaces and routes review
63
+ * or CI work but cannot advance this draft, so repeating it for a waiting layer changes nothing.
64
+ */
65
+ pollProbe?: true;
66
+ /** A current one-PR READY-after-delay completion was verified. */
67
+ readyReceipt?: true;
68
+ /** Lowest unready ancestor that prevents this layer from being stack-mergeable. */
69
+ blockedByPr?: number;
59
70
  }
60
71
  export type PollSummarySelection = {
61
72
  kind: "prs";
@@ -66,6 +77,8 @@ export type PollSummarySelection = {
66
77
  stackNumber: number;
67
78
  stackSize: number;
68
79
  };
80
+ /** Aggregate-only transition; one-PR actions remain unchanged. */
81
+ export type StackNextAction = "shepherd" | "wait" | "merge" | "cancel" | "escalate";
69
82
  export interface PollSummaryResult {
70
83
  mode: "summary";
71
84
  repo: string;
@@ -74,8 +87,10 @@ export interface PollSummaryResult {
74
87
  prs: PollSummaryItem[];
75
88
  /** Present only for native-stack boundaries whose recorded refs differ. */
76
89
  stackAncestry?: PollSummaryStackAncestry[];
77
- /** The next stack-level transition, which may differ from an individual row's hint. */
78
- nextAction?: ShepherdAction;
90
+ /** Immediate stack transition; human blockers surface in rows while shepherdable work remains. */
91
+ nextAction?: StackNextAction;
92
+ /** Whether every open layer is independently ready and stack ancestry is linear. */
93
+ stackMergeable?: boolean;
79
94
  instructions?: string[];
80
95
  apiUsage?: ApiUsage;
81
96
  quotaWarning?: GraphqlQuotaWarning;
@@ -31,6 +31,8 @@ export interface ShepherdReport {
31
31
  status: ShepherdStatus;
32
32
  /** PR base branch from the GraphQL batch. */
33
33
  baseBranch: string;
34
+ /** Base commit GitHub recorded for this PR (`PullRequest.baseRefOid`), not the branch's live tip. */
35
+ baseRefOid?: string;
34
36
  mergeStatus: MergeStatusResult;
35
37
  checks: {
36
38
  passing: ClassifiedCheck[];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pr-shepherd",
3
- "version": "0.51.1",
3
+ "version": "0.52.1",
4
4
  "description": "Autonomous PR CI monitor and review-comment resolver for agentic coding tools",
5
5
  "keywords": [
6
6
  "automation",
@@ -89,7 +89,7 @@
89
89
  "husky": "^9.1.7",
90
90
  "knip": "^6.14.1",
91
91
  "marked": "^18.0.11",
92
- "oxfmt": "^0.66.0",
92
+ "oxfmt": "^0.67.0",
93
93
  "oxlint": "^1.60.0",
94
94
  "typescript": "^7.0.2",
95
95
  "vitest": "^5.0.0"
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pr-shepherd",
3
- "version": "0.51.1",
3
+ "version": "0.52.1",
4
4
  "description": "Autonomous PR CI monitor and review-comment resolver for Codex.",
5
5
  "author": {
6
6
  "name": "Jonathan Ong",
@@ -2,7 +2,7 @@
2
2
  "mcpServers": {
3
3
  "pr-shepherd": {
4
4
  "command": "npx",
5
- "args": ["--yes", "--package", "pr-shepherd@0.51.1", "pr-shepherd-mcp"]
5
+ "args": ["--yes", "--package", "pr-shepherd@0.52.1", "pr-shepherd-mcp"]
6
6
  }
7
7
  }
8
8
  }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "pr-shepherd": {
3
3
  "command": "npx",
4
- "args": ["--yes", "--package", "pr-shepherd@0.51.1", "pr-shepherd-mcp"]
4
+ "args": ["--yes", "--package", "pr-shepherd@0.52.1", "pr-shepherd-mcp"]
5
5
  }
6
6
  }
@@ -20,11 +20,11 @@ If the requested PR does not exist yet, review and commit the in-scope changes,
20
20
 
21
21
  1. Parse optional PR numbers, repository-qualified `owner/repo#N` references, or GitHub PR URLs and an optional `--merge` flag from `$ARGUMENTS`; alternatively parse one `--stack PR` selector. A clear request to merge, land, or enqueue the selected PR or stack also opts into `--merge` without a literal flag; a request only to create or open a PR does not. When the user asks to shepherd or merge a native stack and supplies an anchor PR without a literal `--stack`, use that PR as the `--stack` selector. Otherwise let pr-shepherd infer the current branch PR. Reject any remaining argument. Follow the target repository's local `AGENTS.md` and `CLAUDE.md` standards while making changes.
22
22
 
23
- 2. For the CLI, convert supplied `owner/repo#N` references to `https://github.com/owner/repo/pull/N`; otherwise pass supplied URLs or bare numbers unchanged, then run `pr-shepherd [PR ...] --until-terminal`, or `pr-shepherd --stack PR --until-terminal` for a stack, omitting `[PR ...]` when none was supplied and appending `--merge` when requested. This command keeps ordinary `[WAIT]` and `[MARK_READY]` ticks inside the same invocation; aggregate selectors return when any row needs work or all rows are terminal. It also returns for a quota warning or an emitted `[MERGE]` command, which is non-terminal and must run before the next invocation. A qualified reference may name a fork or upstream repository: it is the GitHub target, while the current checkout continues to supply local git/config/rules context. Do not run `pr-shepherd iterate`. If the CLI is unavailable and the `iterate` MCP tool is available, first repository-qualify every supplied reference with its GitHub URL or `owner/repo#N`; resolve bare numbers through `gh pr view <number> --json url --jq .url`, and resolve an omitted target with `gh pr view --json url --jq .url`. If that does not produce the required qualified selector, stop and report that MCP cannot safely determine it. Otherwise call `iterate` with `pr`, `prs`, or `stack` as selected, plus `merge: true` when merge intent was requested, and print its full result.
23
+ 2. For the CLI, convert supplied `owner/repo#N` references to `https://github.com/owner/repo/pull/N`; otherwise pass supplied URLs or bare numbers unchanged, then run `pr-shepherd [PR ...] --until-terminal`, or `pr-shepherd --stack PR --until-terminal` for a stack, omitting `[PR ...]` when none was supplied and appending `--merge` when requested. This command keeps ordinary `[WAIT]` and `[MARK_READY]` ticks inside the same invocation; aggregate selectors return their next stack action or terminal result. A qualified reference may name a fork or upstream repository: it is the GitHub target, while the current checkout continues to supply local git/config/rules context. Do not run `pr-shepherd iterate`. If the CLI is unavailable and the `iterate` MCP tool is available, first repository-qualify every supplied reference with its GitHub URL or `owner/repo#N`; resolve bare numbers through `gh pr view <number> --json url --jq .url`, and resolve an omitted target with `gh pr view --json url --jq .url`. If that does not produce the required qualified selector, stop and report that MCP cannot safely determine it. Otherwise call `iterate` with `pr`, `prs`, or `stack` as selected, plus `merge: true` when merge intent was requested, and print its full result.
24
24
 
25
25
  3. Print the full result and follow every returned `## Instructions` step exactly. For CLI output, run each printed mutation command when instructed. For MCP output, use MCP `apply` and `build_suggestion_patches` with the same qualified PR reference; do not run a shell `pr-shepherd apply` command.
26
26
 
27
- 4. After completing the returned instructions, immediately repeat step 2 with the same target and canonical options unless the action is `[CANCEL]` or `[ESCALATE]`, or the human directs you to stop. Preserve `--until-terminal` and any requested `--merge`; apply any polling-cadence adjustment printed by the CLI. Every other action is non-terminal: complete its instructions and rerun without asking whether to continue. `[FIX_CODE]` is always non-terminal, and only `[ESCALATE]` hands work to a human. After a push or `rerun:`, do not wait for CI to finish first — you may pull check logs, but do not poll with `gh pr checks`, `gh pr watch`, `gh run watch`, or equivalent GitHub MCP check waiters.
27
+ 4. After completing the returned instructions, immediately repeat step 2 with the same target and canonical options unless the action is `[CANCEL]` or `[ESCALATE]`, or the human directs you to stop. Preserve `--until-terminal` and any requested `--merge`; apply any polling-cadence adjustment printed by the CLI. Every other action is non-terminal: complete its instructions and rerun without asking whether to continue. `[FIX_CODE]` is always non-terminal, as is stack-level `[SHEPHERD]`; only `[ESCALATE]` hands work to a human. After a push or `rerun:`, do not wait for CI to finish first — you may pull check logs, but do not poll with `gh pr checks`, `gh pr watch`, `gh run watch`, or equivalent GitHub MCP check waiters.
28
28
 
29
29
  ## Playbooks
30
30
 
@@ -59,7 +59,7 @@ Match each failure's `[conclusion: …]` tag under `## Failing checks` to a rule
59
59
 
60
60
  More specific rows win over the general "GitHub Actions failure" row — check conclusion first.
61
61
 
62
- A `[rerun authorized]` tag with a `rerun:` command means the viewer's repository role grants GitHub's Actions rerun capability (WRITE+) and GitHub reports the original workflow attempt — Shepherd verified these from `repositoryPermission` and `run_attempt`. Run the printed command at most once. Later attempts carry an `[attempt: N]` tag, never get another command, and return `[ESCALATE]` when no other autonomous work remains, even when a log excerpt exists. A run still in progress, an `ACTION_REQUIRED` run (paused pending manual workflow approval — a rerun cannot grant that approval), a check whose runId does not resolve to a GitHub Actions workflow, or a run whose attempt metadata is unavailable never gets `[rerun authorized]`. When a check has no autonomous follow-up and no other agent work remains, Shepherd returns `[ESCALATE]`; do not invent a handoff from a `[FIX_CODE]` result.
62
+ A `[rerun authorized]` tag with a `rerun:` command means the viewer's repository role grants GitHub's Actions rerun capability (WRITE+) and GitHub reports the original workflow attempt — Shepherd verified these from `repositoryPermission` and `run_attempt`. Run the printed command at most once. Later attempts carry an `[attempt: N]` tag and never get another rerun command; an included log excerpt remains autonomous investigation work, while a later attempt without usable evidence can return `[ESCALATE]` when no other work remains. A run still in progress, an `ACTION_REQUIRED` run (paused pending manual workflow approval — a rerun cannot grant that approval), a check whose runId does not resolve to a GitHub Actions workflow, or a run whose attempt metadata is unavailable never gets `[rerun authorized]`. When a check has no autonomous follow-up and no other agent work remains, Shepherd returns `[ESCALATE]`; do not invent a handoff from a `[FIX_CODE]` result.
63
63
 
64
64
  When several bullets share one runId (matrix jobs from the same run), the `rerun:` command is printed once, on the first bullet; every bullet for that runId still carries `[rerun authorized]` and is covered by that single command — do not run it more than once.
65
65
 
@@ -1,51 +0,0 @@
1
- /**
2
- * Persistent first-seen state for bot CHANGES_REQUESTED reviews.
3
- *
4
- * Bot CRs are auto-dismissed via `--dismiss-review-ids` in the post-push
5
- * `apply review:` command. If the agent drops that flag, the bot CR keeps the PR in
6
- * `CHANGES_REQUESTED` state. This file tracks when each bot CR was first
7
- * observed so the iterate loop can escalate after `iterate.stallTimeoutMinutes`
8
- * — independent of the broader fingerprint-based `stall-timeout` mechanism in
9
- * `iterate-stall.mts` (which only fires when no field of the iterate result
10
- * changed).
11
- *
12
- * State lives in
13
- * `$TMPDIR/pr-shepherd-state/<owner>-<repo>/<pr>/bot-cr-seen.json`.
14
- *
15
- * `bodyHash` lets us reset `firstSeenAt` when the bot re-issues the review
16
- * with a different body, so a fresh review gets the full timeout window.
17
- */
18
- interface BotCrSeenEntry {
19
- /** Unix timestamp (seconds) when this review was first observed undismissed. */
20
- firstSeenAt: number;
21
- /** SHA-256 body-hash prefix; reset firstSeenAt when this changes. */
22
- bodyHash: string;
23
- }
24
- export interface BotCrSeenState {
25
- reviews: Record<string, BotCrSeenEntry>;
26
- }
27
- interface StateKey {
28
- owner: string;
29
- repo: string;
30
- pr: number;
31
- }
32
- export declare function readBotCrSeenState(key: StateKey): Promise<BotCrSeenState | null>;
33
- export declare function writeBotCrSeenState(key: StateKey, state: BotCrSeenState): Promise<void>;
34
- /**
35
- * Update tracked entries against the current set of bot CR reviews:
36
- * - Insert any new IDs with `firstSeenAt = now` and the current body hash.
37
- * - Reset `firstSeenAt` for entries whose body hash changed (review re-issued).
38
- * - Drop entries whose IDs are no longer in the input (review was dismissed
39
- * or superseded by an approval).
40
- *
41
- * Pure function: returns the next state and the IDs whose age has reached the
42
- * `stallTimeoutSeconds` threshold (escalate candidates).
43
- */
44
- export declare function updateBotCrSeenState(previous: BotCrSeenState | null, currentBotCrReviews: ReadonlyArray<{
45
- id: string;
46
- body: string;
47
- }>, nowSeconds: number, stallTimeoutSeconds: number): {
48
- next: BotCrSeenState;
49
- staleIds: string[];
50
- };
51
- export {};
@@ -1,100 +0,0 @@
1
- /**
2
- * Persistent first-seen state for bot CHANGES_REQUESTED reviews.
3
- *
4
- * Bot CRs are auto-dismissed via `--dismiss-review-ids` in the post-push
5
- * `apply review:` command. If the agent drops that flag, the bot CR keeps the PR in
6
- * `CHANGES_REQUESTED` state. This file tracks when each bot CR was first
7
- * observed so the iterate loop can escalate after `iterate.stallTimeoutMinutes`
8
- * — independent of the broader fingerprint-based `stall-timeout` mechanism in
9
- * `iterate-stall.mts` (which only fires when no field of the iterate result
10
- * changed).
11
- *
12
- * State lives in
13
- * `$TMPDIR/pr-shepherd-state/<owner>-<repo>/<pr>/bot-cr-seen.json`.
14
- *
15
- * `bodyHash` lets us reset `firstSeenAt` when the bot re-issues the review
16
- * with a different body, so a fresh review gets the full timeout window.
17
- */
18
- import { readFile, writeFile, rename, unlink, mkdir } from "node:fs/promises";
19
- import { randomUUID } from "node:crypto";
20
- import { dirname } from "node:path";
21
- import { resolvePrStatePath } from "./base.mjs";
22
- import { hashBody } from "./seen-comments.mjs";
23
- export async function readBotCrSeenState(key) {
24
- try {
25
- const raw = await readFile(resolvePath(key), "utf8");
26
- const parsed = JSON.parse(raw);
27
- if (parsed === null || typeof parsed !== "object")
28
- return null;
29
- const reviews = parsed["reviews"];
30
- if (reviews === null || typeof reviews !== "object" || Array.isArray(reviews))
31
- return null;
32
- const validated = {};
33
- for (const [id, entry] of Object.entries(reviews)) {
34
- if (entry === null || typeof entry !== "object")
35
- continue;
36
- const e = entry;
37
- if (typeof e["firstSeenAt"] !== "number" || !Number.isFinite(e["firstSeenAt"]))
38
- continue;
39
- if (typeof e["bodyHash"] !== "string")
40
- continue;
41
- validated[id] = { firstSeenAt: e["firstSeenAt"], bodyHash: e["bodyHash"] };
42
- }
43
- return { reviews: validated };
44
- }
45
- catch {
46
- return null;
47
- }
48
- }
49
- export async function writeBotCrSeenState(key, state) {
50
- let tmp;
51
- try {
52
- const path = resolvePath(key);
53
- tmp = `${path}.${randomUUID()}.tmp`;
54
- await mkdir(dirname(path), { recursive: true });
55
- await writeFile(tmp, JSON.stringify(state), "utf8");
56
- await rename(tmp, path);
57
- tmp = undefined;
58
- }
59
- catch {
60
- // best-effort
61
- }
62
- finally {
63
- if (tmp !== undefined) {
64
- try {
65
- await unlink(tmp);
66
- }
67
- catch {
68
- // best-effort cleanup
69
- }
70
- }
71
- }
72
- }
73
- /**
74
- * Update tracked entries against the current set of bot CR reviews:
75
- * - Insert any new IDs with `firstSeenAt = now` and the current body hash.
76
- * - Reset `firstSeenAt` for entries whose body hash changed (review re-issued).
77
- * - Drop entries whose IDs are no longer in the input (review was dismissed
78
- * or superseded by an approval).
79
- *
80
- * Pure function: returns the next state and the IDs whose age has reached the
81
- * `stallTimeoutSeconds` threshold (escalate candidates).
82
- */
83
- export function updateBotCrSeenState(previous, currentBotCrReviews, nowSeconds, stallTimeoutSeconds) {
84
- const previousReviews = previous?.reviews ?? {};
85
- const next = {};
86
- const staleIds = [];
87
- for (const r of currentBotCrReviews) {
88
- const bodyHash = hashBody(r.body);
89
- const prior = previousReviews[r.id];
90
- const entry = prior && prior.bodyHash === bodyHash ? prior : { firstSeenAt: nowSeconds, bodyHash };
91
- next[r.id] = entry;
92
- if (stallTimeoutSeconds > 0 && nowSeconds - entry.firstSeenAt >= stallTimeoutSeconds) {
93
- staleIds.push(r.id);
94
- }
95
- }
96
- return { next: { reviews: next }, staleIds };
97
- }
98
- function resolvePath(key) {
99
- return resolvePrStatePath(key, "bot-cr-seen.json");
100
- }