pr-shepherd 2.2.9 → 2.2.11
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.
- package/.agents/plugins/marketplace.json +2 -2
- package/.claude-plugin/marketplace.json +2 -2
- package/.claude-plugin/plugin.json +1 -1
- package/.grok-plugin/marketplace.json +2 -2
- package/README.md +1 -1
- package/bin/checks/classify.mjs +4 -2
- package/bin/cli/help-command-pages.d.mts +2 -2
- package/bin/cli/help-iterate-poll-pages.d.mts +2 -2
- package/bin/cli/help-iterate-poll-pages.mjs +7 -0
- package/bin/cli/help-top-page.d.mts +1 -1
- package/bin/cli/help-top-page.mjs +1 -0
- package/bin/cli/help.d.mts +3 -3
- package/bin/cli/iterate-instructions.mjs +7 -4
- package/bin/cli/poll-handler.mjs +49 -67
- package/bin/cli/poll-loop-options.d.mts +25 -0
- package/bin/cli/poll-loop-options.mjs +58 -0
- package/bin/cli/poll-watch.d.mts +27 -0
- package/bin/cli/poll-watch.mjs +48 -0
- package/bin/cli/watch-report.d.mts +17 -0
- package/bin/cli/watch-report.mjs +33 -0
- package/bin/commands/iterate/api-usage.mjs +16 -1
- package/bin/commands/iterate/gh-cache.d.mts +12 -0
- package/bin/commands/iterate/gh-cache.mjs +98 -0
- package/bin/commands/iterate/index.mjs +77 -55
- package/bin/commands/iterate/merge-plan.d.mts +1 -1
- package/bin/commands/poll-options.d.mts +3 -0
- package/bin/commands/poll-summary.d.mts +3 -0
- package/bin/commands/poll-summary.mjs +5 -1
- package/bin/commands/poll-watch-verify.d.mts +6 -0
- package/bin/commands/poll-watch-verify.mjs +16 -0
- package/bin/commands/poll.mjs +3 -3
- package/bin/exit-codes.d.mts +2 -0
- package/bin/exit-codes.mjs +2 -0
- package/bin/github/batch-parser-helpers.mjs +4 -1
- package/bin/state/process-start.d.mts +14 -0
- package/bin/state/process-start.mjs +35 -0
- package/bin/state/watch-lock.d.mts +29 -0
- package/bin/state/watch-lock.mjs +145 -0
- package/bin/state/watch-set.d.mts +23 -0
- package/bin/state/watch-set.mjs +58 -0
- package/bin/types/merge-action.d.mts +8 -0
- package/package.json +1 -1
- package/plugins/pr-shepherd/.claude-plugin/plugin.json +1 -1
- package/plugins/pr-shepherd/.codex-plugin/plugin.json +1 -1
- package/plugins/pr-shepherd/hooks/pipe-guard-parse.d.mts +4 -0
- package/plugins/pr-shepherd/hooks/pipe-guard-parse.mjs +142 -0
- package/plugins/pr-shepherd/hooks/poll-guard.d.mts +1 -0
- package/plugins/pr-shepherd/hooks/poll-guard.mjs +23 -1
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { type WatchSet } from "../state/watch-set.mts";
|
|
2
|
+
import type { WatchRepo } from "../state/watch-lock.mts";
|
|
3
|
+
export interface WatchSpec {
|
|
4
|
+
/** The repository the PRs live in; the checkout's `origin` when omitted. */
|
|
5
|
+
repo?: WatchRepo;
|
|
6
|
+
/** PRs this run will poll. Empty means no lock, unless `growing`. */
|
|
7
|
+
prs: number[];
|
|
8
|
+
/** A stack names its member PRs only after its first read, so they are locked per tick. */
|
|
9
|
+
growing?: boolean;
|
|
10
|
+
/** The holder flags worth comparing, such as `--merge`. */
|
|
11
|
+
flags: string[];
|
|
12
|
+
format: "text" | "json";
|
|
13
|
+
}
|
|
14
|
+
/** The flags a second caller would compare against: those that change what a watcher does. */
|
|
15
|
+
export declare function watchFlagsOf(options: {
|
|
16
|
+
merge?: boolean;
|
|
17
|
+
untilTerminal?: boolean;
|
|
18
|
+
noAutoMarkReady?: boolean;
|
|
19
|
+
}): string[];
|
|
20
|
+
/** Stops a one-PR watcher that lost its lock to another live process: reported as watched, exit 17. */
|
|
21
|
+
export declare function lostWatchGuard(watch: WatchSet): void;
|
|
22
|
+
/**
|
|
23
|
+
* Runs a repeating poll under per-PR watcher locks. PRs another live process already watches are
|
|
24
|
+
* dropped and reported; when none remain, nothing polls and the process exits `EXIT.WATCHED`.
|
|
25
|
+
* Cloud sessions run one tick per invocation, so they take no lock.
|
|
26
|
+
*/
|
|
27
|
+
export declare function withWatchLock(spec: WatchSpec, run: (watch: WatchSet | undefined, prs: number[]) => Promise<void>): Promise<void>;
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { runsSingleTick } from "../commands/single-tick.mjs";
|
|
2
|
+
import { getRepoInfo } from "../github/client.mjs";
|
|
3
|
+
import { createWatchSet, WatchedError } from "../state/watch-set.mjs";
|
|
4
|
+
import { emitWatched, noteWatched } from "./watch-report.mjs";
|
|
5
|
+
/** The flags a second caller would compare against: those that change what a watcher does. */
|
|
6
|
+
export function watchFlagsOf(options) {
|
|
7
|
+
return [
|
|
8
|
+
...(options.merge ? ["--merge"] : []),
|
|
9
|
+
...(options.untilTerminal ? ["--until-terminal"] : []),
|
|
10
|
+
...(options.noAutoMarkReady ? ["--no-auto-mark-ready"] : []),
|
|
11
|
+
];
|
|
12
|
+
}
|
|
13
|
+
/** Stops a one-PR watcher that lost its lock to another live process: reported as watched, exit 17. */
|
|
14
|
+
export function lostWatchGuard(watch) {
|
|
15
|
+
const lost = watch.verify();
|
|
16
|
+
if (lost.length > 0)
|
|
17
|
+
throw new WatchedError(watch.repo, lost);
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Runs a repeating poll under per-PR watcher locks. PRs another live process already watches are
|
|
21
|
+
* dropped and reported; when none remain, nothing polls and the process exits `EXIT.WATCHED`.
|
|
22
|
+
* Cloud sessions run one tick per invocation, so they take no lock.
|
|
23
|
+
*/
|
|
24
|
+
export async function withWatchLock(spec, run) {
|
|
25
|
+
if (runsSingleTick() || (spec.prs.length === 0 && spec.growing !== true)) {
|
|
26
|
+
return run(undefined, spec.prs);
|
|
27
|
+
}
|
|
28
|
+
const repo = spec.repo ?? (await getRepoInfo());
|
|
29
|
+
const watch = createWatchSet(repo, spec.flags);
|
|
30
|
+
try {
|
|
31
|
+
const blocked = watch.claim(spec.prs);
|
|
32
|
+
if (spec.prs.length > 0 && blocked.length === spec.prs.length) {
|
|
33
|
+
return emitWatched(repo, blocked, spec.format);
|
|
34
|
+
}
|
|
35
|
+
if (blocked.length > 0)
|
|
36
|
+
noteWatched(repo, blocked);
|
|
37
|
+
const skipped = new Set(blocked.map((holder) => holder.pr));
|
|
38
|
+
await run(watch, spec.prs.filter((pr) => !skipped.has(pr)));
|
|
39
|
+
}
|
|
40
|
+
catch (error) {
|
|
41
|
+
if (!(error instanceof WatchedError))
|
|
42
|
+
throw error;
|
|
43
|
+
emitWatched(repo, error.holders, spec.format);
|
|
44
|
+
}
|
|
45
|
+
finally {
|
|
46
|
+
watch.releaseAll();
|
|
47
|
+
}
|
|
48
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { WatchHolder, WatchRepo } from "../state/watch-lock.mts";
|
|
2
|
+
export interface WatchedReport {
|
|
3
|
+
mode: "watch-lock";
|
|
4
|
+
repo: string;
|
|
5
|
+
alreadyWatched: Array<{
|
|
6
|
+
pr: number;
|
|
7
|
+
pid: number;
|
|
8
|
+
flags: string[];
|
|
9
|
+
}>;
|
|
10
|
+
instructions: string[];
|
|
11
|
+
}
|
|
12
|
+
export declare function buildWatchedReport(repo: WatchRepo, holders: WatchHolder[]): WatchedReport;
|
|
13
|
+
export declare function formatWatchedReport(report: WatchedReport): string;
|
|
14
|
+
/** Every requested PR is watched elsewhere: print the report on stdout and exit with `EXIT.WATCHED`. */
|
|
15
|
+
export declare function emitWatched(repo: WatchRepo, holders: WatchHolder[], format: "text" | "json"): void;
|
|
16
|
+
/** Some PRs are watched elsewhere; this run continues on the rest, so the note goes to stderr. */
|
|
17
|
+
export declare function noteWatched(repo: WatchRepo, holders: WatchHolder[]): void;
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { EXIT } from "../exit-codes.mjs";
|
|
2
|
+
export function buildWatchedReport(repo, holders) {
|
|
3
|
+
const lines = holders.map(({ pr, pid, flags }) => {
|
|
4
|
+
const shown = flags.length > 0 ? flags.join(" ") : "none";
|
|
5
|
+
return `PR #${pr} is already watched by PID ${pid} (flags: ${shown}).`;
|
|
6
|
+
});
|
|
7
|
+
const pids = [...new Set(holders.map((holder) => holder.pid))].join(", ");
|
|
8
|
+
const steps = [
|
|
9
|
+
...lines,
|
|
10
|
+
"Do not start another watcher for a PR listed above; the process that holds it already polls it.",
|
|
11
|
+
`If its flags differ from what you need (for example you need \`--merge\` and it lacks it), stop PID ${pids} and rerun this command.`,
|
|
12
|
+
];
|
|
13
|
+
return {
|
|
14
|
+
mode: "watch-lock",
|
|
15
|
+
repo: `${repo.owner}/${repo.name}`,
|
|
16
|
+
alreadyWatched: holders.map(({ pr, pid, flags }) => ({ pr, pid, flags })),
|
|
17
|
+
instructions: steps.map((step, index) => `${index + 1}. ${step}`),
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
export function formatWatchedReport(report) {
|
|
21
|
+
const prs = report.alreadyWatched.map((item) => `#${item.pr}`).join(", ");
|
|
22
|
+
return `## Already watched\n\n${report.repo} ${prs}\n\n## Instructions\n\n${report.instructions.join("\n")}`;
|
|
23
|
+
}
|
|
24
|
+
/** Every requested PR is watched elsewhere: print the report on stdout and exit with `EXIT.WATCHED`. */
|
|
25
|
+
export function emitWatched(repo, holders, format) {
|
|
26
|
+
const report = buildWatchedReport(repo, holders);
|
|
27
|
+
process.stdout.write(format === "json" ? `${JSON.stringify(report)}\n` : `${formatWatchedReport(report)}\n`);
|
|
28
|
+
process.exitCode = EXIT.WATCHED;
|
|
29
|
+
}
|
|
30
|
+
/** Some PRs are watched elsewhere; this run continues on the rest, so the note goes to stderr. */
|
|
31
|
+
export function noteWatched(repo, holders) {
|
|
32
|
+
process.stderr.write(`${formatWatchedReport(buildWatchedReport(repo, holders))}\n`);
|
|
33
|
+
}
|
|
@@ -4,9 +4,24 @@ import { selectQuotaWarning } from "../quota-selection.mjs";
|
|
|
4
4
|
import { buildQuotaAwareContinuation } from "../../quota-warning.mjs";
|
|
5
5
|
import { getGithubTransport } from "../../github/transport.mjs";
|
|
6
6
|
import { isTriageContinuation } from "./check-instructions.mjs";
|
|
7
|
+
import { scanGhCacheForRateLimit } from "./gh-cache.mjs";
|
|
7
8
|
function shouldWarn(result) {
|
|
8
9
|
return ["wait", "mark_ready", "merge", "triage"].includes(result.action);
|
|
9
10
|
}
|
|
11
|
+
/**
|
|
12
|
+
* `gh pr merge` replays a cached GraphQL rate-limit error for 24h. Report it only when Shepherd's
|
|
13
|
+
* own live GraphQL reading shows quota left, which proves the cached error is stale.
|
|
14
|
+
*/
|
|
15
|
+
function withStaleGhCache(result, apiUsage) {
|
|
16
|
+
if (result.action !== "merge" || result.merge.mode === "rest")
|
|
17
|
+
return result;
|
|
18
|
+
if ((apiUsage.graphql?.remaining ?? 0) <= 0)
|
|
19
|
+
return result;
|
|
20
|
+
const ghCacheStaleRateLimit = scanGhCacheForRateLimit();
|
|
21
|
+
if (!ghCacheStaleRateLimit)
|
|
22
|
+
return result;
|
|
23
|
+
return { ...result, merge: { ...result.merge, ghCacheStaleRateLimit } };
|
|
24
|
+
}
|
|
10
25
|
export async function attachApiUsage(result, persistWarning, preservePersistedWarning = false, minimumPollIntervalMinutes = 0) {
|
|
11
26
|
const apiUsage = summarizeApiTelemetry();
|
|
12
27
|
if (apiUsage === undefined)
|
|
@@ -23,7 +38,7 @@ export async function attachApiUsage(result, persistWarning, preservePersistedWa
|
|
|
23
38
|
quotaWarning = await selectQuotaWarning({ owner, repo }, bands, apiUsage, persistWarning, getGithubTransport());
|
|
24
39
|
}
|
|
25
40
|
}
|
|
26
|
-
const { quotaWarning: _deferredWarning, ...baseResult } = result;
|
|
41
|
+
const { quotaWarning: _deferredWarning, ...baseResult } = withStaleGhCache(result, apiUsage);
|
|
27
42
|
const withWarning = {
|
|
28
43
|
...baseResult,
|
|
29
44
|
apiUsage,
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
interface GhCacheStaleRateLimit {
|
|
2
|
+
/** Absolute paths of cached responses that carry a GraphQL rate-limit error. */
|
|
3
|
+
paths: string[];
|
|
4
|
+
/** ISO time the newest listed entry expires on its own (mtime + 24h). */
|
|
5
|
+
expiresAt: string;
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* Read-only scan for cached `gh` responses that hold a GraphQL rate-limit error. `gh pr merge`
|
|
9
|
+
* replays these for 24h. Any error, a missing directory, or an exceeded cap means "nothing found".
|
|
10
|
+
*/
|
|
11
|
+
export declare function scanGhCacheForRateLimit(now?: number, env?: NodeJS.ProcessEnv, platform?: NodeJS.Platform): GhCacheStaleRateLimit | undefined;
|
|
12
|
+
export {};
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import { closeSync, constants, fstatSync, openSync, opendirSync, readSync, } from "node:fs";
|
|
2
|
+
import { homedir, tmpdir } from "node:os";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
/** gh's HTTP cache TTL for its GraphQL schema feature-detection query. */
|
|
5
|
+
const GH_CACHE_TTL_MS = 24 * 60 * 60 * 1000;
|
|
6
|
+
const MAX_FILE_BYTES = 4096;
|
|
7
|
+
const MAX_FILES_VISITED = 5000;
|
|
8
|
+
const MAX_SCAN_MS = 1500;
|
|
9
|
+
const MAX_DEPTH = 4;
|
|
10
|
+
const STALE_MARKER = '"type":"RATE_LIMIT"';
|
|
11
|
+
/** Mirrors go-gh `config.CacheDir()`: XDG_CACHE_HOME, LocalAppData (Windows), `~/.cache/gh`. */
|
|
12
|
+
function ghCacheDir(env, platform) {
|
|
13
|
+
if (env["XDG_CACHE_HOME"])
|
|
14
|
+
return join(env["XDG_CACHE_HOME"], "gh");
|
|
15
|
+
if (platform === "win32" && env["LocalAppData"])
|
|
16
|
+
return join(env["LocalAppData"], "GitHub CLI");
|
|
17
|
+
const home = homedir();
|
|
18
|
+
return home ? join(home, ".cache", "gh") : join(tmpdir(), "gh-cli-cache");
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Read-only scan for cached `gh` responses that hold a GraphQL rate-limit error. `gh pr merge`
|
|
22
|
+
* replays these for 24h. Any error, a missing directory, or an exceeded cap means "nothing found".
|
|
23
|
+
*/
|
|
24
|
+
export function scanGhCacheForRateLimit(now = Date.now(), env = process.env, platform = process.platform) {
|
|
25
|
+
const deadline = Date.now() + MAX_SCAN_MS;
|
|
26
|
+
const paths = [];
|
|
27
|
+
let newest = 0;
|
|
28
|
+
let visited = 0;
|
|
29
|
+
/** Whether `full` is a small, fresh regular file whose body carries the marker. */
|
|
30
|
+
const poisoned = (full) => {
|
|
31
|
+
let fd;
|
|
32
|
+
try {
|
|
33
|
+
fd = openSync(full, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
|
|
34
|
+
const info = fstatSync(fd);
|
|
35
|
+
if (!info.isFile() || info.size >= MAX_FILE_BYTES)
|
|
36
|
+
return undefined;
|
|
37
|
+
if (now - info.mtimeMs >= GH_CACHE_TTL_MS)
|
|
38
|
+
return undefined;
|
|
39
|
+
const buffer = Buffer.alloc(MAX_FILE_BYTES);
|
|
40
|
+
const bytes = readSync(fd, buffer, 0, MAX_FILE_BYTES, 0);
|
|
41
|
+
if (bytes >= MAX_FILE_BYTES)
|
|
42
|
+
return undefined;
|
|
43
|
+
return buffer.toString("utf8", 0, bytes).includes(STALE_MARKER) ? info.mtimeMs : undefined;
|
|
44
|
+
}
|
|
45
|
+
catch {
|
|
46
|
+
return undefined;
|
|
47
|
+
}
|
|
48
|
+
finally {
|
|
49
|
+
if (fd !== undefined)
|
|
50
|
+
closeSync(fd);
|
|
51
|
+
}
|
|
52
|
+
};
|
|
53
|
+
const walk = (dir, depth) => {
|
|
54
|
+
let handle;
|
|
55
|
+
try {
|
|
56
|
+
handle = opendirSync(dir);
|
|
57
|
+
}
|
|
58
|
+
catch {
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
61
|
+
try {
|
|
62
|
+
// Read one entry at a time so the caps bound enumeration, not just file reads.
|
|
63
|
+
for (let entry; (entry = handle.readSync()) !== null;) {
|
|
64
|
+
if (visited >= MAX_FILES_VISITED || Date.now() > deadline)
|
|
65
|
+
return;
|
|
66
|
+
const full = join(dir, entry.name);
|
|
67
|
+
if (entry.isDirectory()) {
|
|
68
|
+
if (depth < MAX_DEPTH)
|
|
69
|
+
walk(full, depth + 1);
|
|
70
|
+
continue;
|
|
71
|
+
}
|
|
72
|
+
if (!entry.isFile())
|
|
73
|
+
continue;
|
|
74
|
+
visited += 1;
|
|
75
|
+
const mtime = poisoned(full);
|
|
76
|
+
if (mtime === undefined)
|
|
77
|
+
continue;
|
|
78
|
+
paths.push(full);
|
|
79
|
+
newest = Math.max(newest, mtime);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
catch {
|
|
83
|
+
// Enumeration failed part-way: keep what was found.
|
|
84
|
+
}
|
|
85
|
+
finally {
|
|
86
|
+
try {
|
|
87
|
+
handle.closeSync();
|
|
88
|
+
}
|
|
89
|
+
catch {
|
|
90
|
+
// Already closed.
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
};
|
|
94
|
+
walk(ghCacheDir(env, platform), 0);
|
|
95
|
+
if (paths.length === 0)
|
|
96
|
+
return undefined;
|
|
97
|
+
return { paths: paths.sort(), expiresAt: new Date(newest + GH_CACHE_TTL_MS).toISOString() };
|
|
98
|
+
}
|
|
@@ -317,8 +317,8 @@ async function runIterateCore(opts, tick) {
|
|
|
317
317
|
if (markReadyResult)
|
|
318
318
|
return markReadyResult;
|
|
319
319
|
if (readyState.shouldCancel && !report.mergeStatus.isDraft) {
|
|
320
|
-
const
|
|
321
|
-
? "written"
|
|
320
|
+
const outcome = receiptCurrent
|
|
321
|
+
? { status: "written" }
|
|
322
322
|
: await recordReadyReceipt(receiptKey, report, checkContext);
|
|
323
323
|
// Aggregate `stack` routing trusts only a layer's receipt, so an unwritten
|
|
324
324
|
// one keeps the elapsed marker and retries next tick. A one-PR receipt
|
|
@@ -327,14 +327,13 @@ async function runIterateCore(opts, tick) {
|
|
|
327
327
|
// still holds it, but without --merge its one-PR session ends like a
|
|
328
328
|
// single PR's instead of waiting for a stall-timeout.
|
|
329
329
|
const stackLayer = report.mergeStatus.mergeRequirements?.stack !== undefined;
|
|
330
|
-
if (stackLayer &&
|
|
330
|
+
if (stackLayer &&
|
|
331
|
+
(outcome.status === "failed" || (outcome.status === "blocked" && opts.merge))) {
|
|
331
332
|
const receiptWait = {
|
|
332
333
|
...base,
|
|
333
334
|
action: "wait",
|
|
334
335
|
shouldCancel: false,
|
|
335
|
-
log:
|
|
336
|
-
? `WAIT: PR #${base.pr} reached ready-delay but GitHub reports BLOCKED, so its stack readiness receipt was not certified`
|
|
337
|
-
: `WAIT: PR #${base.pr} reached ready-delay but its stack readiness receipt could not be persisted`,
|
|
336
|
+
log: receiptWaitLog(base.pr, outcome),
|
|
338
337
|
};
|
|
339
338
|
return annotateBlockedWait(await applyStallGuard(stallKey, stallTimeoutSeconds, headSha, base, prNumber, receiptWait, reportForWork, reviewSummaryIds, opts.stallDeadlineSink, opts.persistSeen !== false), blockerGate);
|
|
340
339
|
}
|
|
@@ -373,55 +372,81 @@ async function runIterateCore(opts, tick) {
|
|
|
373
372
|
};
|
|
374
373
|
return annotateBlockedWait(await applyStallGuard(stallKey, stallTimeoutSeconds, headSha, base, prNumber, wait, reportForWork, reviewSummaryIds, opts.stallDeadlineSink, opts.persistSeen !== false), blockerGate);
|
|
375
374
|
}
|
|
375
|
+
const short = (oid) => oid.slice(0, 7);
|
|
376
|
+
const failed = (reason) => ({ status: "failed", reason });
|
|
377
|
+
const errMessage = (e) => (e instanceof Error ? e.message : String(e));
|
|
378
|
+
function receiptWaitLog(pr, outcome) {
|
|
379
|
+
const head = `WAIT: PR #${pr} reached ready-delay but`;
|
|
380
|
+
if (outcome.status === "blocked")
|
|
381
|
+
return `${head} GitHub reports BLOCKED, so its stack readiness receipt was not certified`;
|
|
382
|
+
if (outcome.persistFailure)
|
|
383
|
+
return `${head} its stack readiness receipt could not be persisted: ${outcome.reason}`;
|
|
384
|
+
return `${head} its stack readiness receipt was not certified: ${outcome.reason}`;
|
|
385
|
+
}
|
|
376
386
|
/**
|
|
377
387
|
* Persist a READY receipt from a fresh compact snapshot. `blocked` means the
|
|
378
|
-
* snapshot is ready except for GitHub's BLOCKED state; `failed`
|
|
379
|
-
* stale, or not-ready evidence
|
|
388
|
+
* snapshot is ready except for GitHub's BLOCKED state; `failed` carries the
|
|
389
|
+
* reason the receipt was not certified (missing, stale, or not-ready evidence,
|
|
390
|
+
* or a write error flagged `persistFailure`).
|
|
380
391
|
*/
|
|
381
392
|
async function recordReadyReceipt(key, report, context) {
|
|
382
|
-
if (report.status !== "READY"
|
|
383
|
-
report.
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
393
|
+
if (report.status !== "READY")
|
|
394
|
+
return failed(`report status is ${report.status}, not READY`);
|
|
395
|
+
if (!report.headSha)
|
|
396
|
+
return failed("report has no head SHA");
|
|
397
|
+
if (!report.baseRefOid)
|
|
398
|
+
return failed("report has no base SHA");
|
|
399
|
+
let raw;
|
|
400
|
+
let fingerprint;
|
|
401
|
+
let summary;
|
|
389
402
|
try {
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
return
|
|
403
|
+
raw = await receiptSummaryForReport(key, report, context);
|
|
404
|
+
const fresh = fingerprintRawSummaryPr(raw);
|
|
405
|
+
if (fresh === null)
|
|
406
|
+
return failed("fresh summary has no fingerprint");
|
|
407
|
+
fingerprint = fresh;
|
|
408
|
+
if (raw.state !== "OPEN")
|
|
409
|
+
return failed(`fresh summary shows PR ${raw.state}, not OPEN`);
|
|
410
|
+
if (raw.isDraft)
|
|
411
|
+
return failed("fresh summary shows PR as a draft");
|
|
412
|
+
if (raw.headRefOid !== report.headSha)
|
|
413
|
+
return failed(`head moved (report ${short(report.headSha)}, fresh ${short(raw.headRefOid)})`);
|
|
414
|
+
if (raw.baseRefOid !== report.baseRefOid)
|
|
415
|
+
return failed(`base moved (report ${short(report.baseRefOid)}, fresh ${short(raw.baseRefOid)})`);
|
|
397
416
|
// Summarize hydrates annotation totals onto the snapshot before the stored hash.
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
417
|
+
summary = await summarizePollSummaryPr(raw, { owner: key.owner, name: key.repo }, { stackPrNumber: report.pr });
|
|
418
|
+
}
|
|
419
|
+
catch (e) {
|
|
420
|
+
// The receipt is supplementary evidence. A transient summary fetch failure
|
|
421
|
+
// must not turn a completed one-PR poll into a different Shepherd action.
|
|
422
|
+
return failed(`fresh summary unavailable: ${errMessage(e)}`);
|
|
423
|
+
}
|
|
424
|
+
if (annotationProbeUnavailable(raw))
|
|
425
|
+
return failed("annotation probe unavailable");
|
|
426
|
+
const checks = summary.checks ?? {};
|
|
427
|
+
const review = summary.review ?? {};
|
|
428
|
+
if (!isCurrentSummaryReady(raw, checks, review)) {
|
|
429
|
+
const onlyBlocked = raw.mergeStateStatus === "BLOCKED" &&
|
|
430
|
+
!raw.isInMergeQueue &&
|
|
431
|
+
isCurrentSummaryReady(raw, checks, review, { allowBlocked: true });
|
|
432
|
+
return onlyBlocked
|
|
433
|
+
? { status: "blocked" }
|
|
434
|
+
: failed("fresh summary is not ready (checks, review, or merge state changed)");
|
|
435
|
+
}
|
|
436
|
+
const removalEvent = currentQueueRemovalEvent(raw);
|
|
437
|
+
// Bind recovery to the exact evidence the one-PR check accepted. A new ejection
|
|
438
|
+
// between that check and this fresh snapshot must get its own acknowledgment.
|
|
439
|
+
if (report.mergeQueue?.removalAcknowledged) {
|
|
440
|
+
const accepted = report.mergeQueue.latestRemoval;
|
|
441
|
+
if (raw.isInMergeQueue ||
|
|
442
|
+
!accepted ||
|
|
443
|
+
!removalEvent ||
|
|
444
|
+
removalEvent.beforeCommit?.oid !== accepted.beforeCommitOid ||
|
|
445
|
+
Math.floor(Date.parse(removalEvent.createdAt) / 1000) !== accepted.createdAtUnix ||
|
|
446
|
+
removalEvent.reason !== accepted.reason)
|
|
447
|
+
return failed("merge-queue removal evidence changed since the one-PR check");
|
|
448
|
+
}
|
|
449
|
+
try {
|
|
425
450
|
await writeReadyReceipt({
|
|
426
451
|
version: 1,
|
|
427
452
|
...key,
|
|
@@ -435,13 +460,10 @@ async function recordReadyReceipt(key, report, context) {
|
|
|
435
460
|
}),
|
|
436
461
|
recordedAtUnix: Math.floor(Date.now() / 1000),
|
|
437
462
|
});
|
|
438
|
-
return "written";
|
|
463
|
+
return { status: "written" };
|
|
439
464
|
}
|
|
440
|
-
catch {
|
|
441
|
-
|
|
442
|
-
// state-directory failure must not turn a completed one-PR poll into a
|
|
443
|
-
// different Shepherd action.
|
|
444
|
-
return "failed";
|
|
465
|
+
catch (e) {
|
|
466
|
+
return { status: "failed", reason: errMessage(e), persistFailure: true };
|
|
445
467
|
}
|
|
446
468
|
}
|
|
447
469
|
/** Clear a stale READY receipt; return whether a current receipt remains. */
|
|
@@ -15,7 +15,7 @@ export interface MergePlanInput {
|
|
|
15
15
|
allowedMergeMethods?: readonly MergeMethod[];
|
|
16
16
|
/** Branch policy requires linear history, so merge commits are excluded. */
|
|
17
17
|
linearHistory?: boolean;
|
|
18
|
-
/** Attach a REST equivalent of the GraphQL merge commands, for when GraphQL
|
|
18
|
+
/** Attach a REST equivalent of the GraphQL merge commands, for when `gh` reports a GraphQL rate limit. */
|
|
19
19
|
restFallback?: boolean;
|
|
20
20
|
expectedStack?: RestMergeStackGuard;
|
|
21
21
|
}
|
|
@@ -6,4 +6,7 @@ export interface PollCommandOptions extends IterateCommandOptions {
|
|
|
6
6
|
debounceSeconds?: number;
|
|
7
7
|
quietStatus?: boolean;
|
|
8
8
|
untilTerminal?: boolean;
|
|
9
|
+
/** Runs before every tick; the per-PR watcher lock uses it to stop a watcher that lost its lock. */
|
|
10
|
+
beforeTick?: () => void;
|
|
9
11
|
}
|
|
12
|
+
export type Announce = (sleepMs: number, viaEvents: boolean) => void;
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { WatchSet } from "../state/watch-set.mts";
|
|
1
2
|
import type { PollSummaryCommandOptions, PollSummaryResult } from "../types.mts";
|
|
2
3
|
export interface AggregatePollCommandOptions extends PollSummaryCommandOptions {
|
|
3
4
|
intervalSeconds: number;
|
|
@@ -6,6 +7,8 @@ export interface AggregatePollCommandOptions extends PollSummaryCommandOptions {
|
|
|
6
7
|
quietStatus?: boolean;
|
|
7
8
|
untilTerminal?: boolean;
|
|
8
9
|
verbose?: boolean;
|
|
10
|
+
/** Per-PR watcher locks to keep in step with each tick's rows. */
|
|
11
|
+
watch?: WatchSet;
|
|
9
12
|
}
|
|
10
13
|
export declare function runPollSummary(opts: PollSummaryCommandOptions): Promise<PollSummaryResult>;
|
|
11
14
|
export declare function runAggregatePoll(opts: AggregatePollCommandOptions): Promise<PollSummaryResult>;
|
|
@@ -8,6 +8,7 @@ import { withApiTelemetryScope, summarizeApiTelemetry } from "../github/api-tele
|
|
|
8
8
|
import { aggregateRerunCommand, stackApprovalCommands } from "../github/poll-summary-command.mjs";
|
|
9
9
|
import { fetchPollSummary } from "../github/poll-summary.mjs";
|
|
10
10
|
import { writeStackHandoffs } from "../github/stack-handoff.mjs";
|
|
11
|
+
import { verifyWatchedPrs } from "./poll-watch-verify.mjs";
|
|
11
12
|
import { aggregateQuotaWarning, carryQuotaWarning, quotaPollIntervalMs } from "./poll-quota.mjs";
|
|
12
13
|
import { aggregateCancelFromPulls, aggregateRateLimitTargets } from "./poll-rate-limit-cancel.mjs";
|
|
13
14
|
import { createUntilTerminalRateLimitRetry } from "./poll-rate-limit-wait.mjs";
|
|
@@ -88,7 +89,8 @@ async function readPollSummaryTick(opts) {
|
|
|
88
89
|
const result = await applyStackStallGuard(planned, repo, opts.stallTimeoutSeconds ?? loadConfig().iterate["stall-timeout-minutes"] * 60);
|
|
89
90
|
return { result, repo, ...(fetched.handoffSource && { handoffSource: fetched.handoffSource }) };
|
|
90
91
|
}
|
|
91
|
-
async function runAggregatePollCore(
|
|
92
|
+
async function runAggregatePollCore(options, events) {
|
|
93
|
+
let opts = options;
|
|
92
94
|
const intervalMs = Math.min(opts.intervalSeconds * 1000, MAX_TIMER_MS);
|
|
93
95
|
const timeoutMs = Math.min(opts.timeoutSeconds * 1000, MAX_TIMER_MS);
|
|
94
96
|
const debounceMs = Math.min((opts.debounceSeconds ?? 60) * 1000, MAX_TIMER_MS);
|
|
@@ -102,11 +104,13 @@ async function runAggregatePollCore(opts, events) {
|
|
|
102
104
|
const rateLimitRetry = createUntilTerminalRateLimitRetry();
|
|
103
105
|
let pendingQuotaWarning;
|
|
104
106
|
while (true) {
|
|
107
|
+
opts = verifyWatchedPrs(opts);
|
|
105
108
|
tick += 1;
|
|
106
109
|
const tickStartedAt = Date.now();
|
|
107
110
|
try {
|
|
108
111
|
lastTick = await readPollSummaryTick(opts);
|
|
109
112
|
last = lastTick.result;
|
|
113
|
+
opts.watch?.sync(last.prs);
|
|
110
114
|
writeAggregateRuleAutoResolve(last);
|
|
111
115
|
rateLimitRetry.reset();
|
|
112
116
|
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { AggregatePollCommandOptions } from "./poll-summary.mts";
|
|
2
|
+
/**
|
|
3
|
+
* Before an aggregate tick, drop the PRs whose watcher lock another live process now holds and
|
|
4
|
+
* report them. When nothing is left to watch (or a stack lost a layer), the run stops as watched.
|
|
5
|
+
*/
|
|
6
|
+
export declare function verifyWatchedPrs(opts: AggregatePollCommandOptions): AggregatePollCommandOptions;
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { noteWatched } from "../cli/watch-report.mjs";
|
|
2
|
+
import { WatchedError } from "../state/watch-set.mjs";
|
|
3
|
+
/**
|
|
4
|
+
* Before an aggregate tick, drop the PRs whose watcher lock another live process now holds and
|
|
5
|
+
* report them. When nothing is left to watch (or a stack lost a layer), the run stops as watched.
|
|
6
|
+
*/
|
|
7
|
+
export function verifyWatchedPrs(opts) {
|
|
8
|
+
const lost = opts.watch?.verify() ?? [];
|
|
9
|
+
if (lost.length === 0)
|
|
10
|
+
return opts;
|
|
11
|
+
const remaining = opts.prNumbers?.filter((pr) => !lost.some((holder) => holder.pr === pr));
|
|
12
|
+
if (!remaining?.length)
|
|
13
|
+
throw new WatchedError(opts.watch.repo, lost);
|
|
14
|
+
noteWatched(opts.watch.repo, lost);
|
|
15
|
+
return { ...opts, prNumbers: remaining };
|
|
16
|
+
}
|
package/bin/commands/poll.mjs
CHANGED
|
@@ -11,17 +11,16 @@ import { createTickRunner } from "./poll-tick.mjs";
|
|
|
11
11
|
import { writeDebounceProgress, writeRuleAutoResolveProgress, writeWaitProgress, } from "./poll-progress.mjs";
|
|
12
12
|
import { onePrDeadline } from "./stall-deadline.mjs";
|
|
13
13
|
import { onePrTargets, pauseBeforeNextTick, withPollEvents, } from "./poll-events.mjs";
|
|
14
|
-
const DEFAULT_POLL_DEBOUNCE_SECONDS = 60;
|
|
15
14
|
const MAX_TIMER_MS = 2 ** 31 - 1;
|
|
16
15
|
const TIMER_DRIFT_TOLERANCE_MS = 500;
|
|
17
16
|
export function runPoll(opts) {
|
|
18
17
|
return withPollEvents(opts.verbose === true, (events) => withPollApiUsage(() => runPollCore(opts, events), opts.untilTerminal === true, opts.intervalSeconds / 60));
|
|
19
18
|
}
|
|
20
19
|
async function runPollCore(opts, events) {
|
|
21
|
-
const { intervalSeconds, timeoutSeconds, debounceSeconds: debounceSecondsOpt, quietStatus: quietStatusOpt, untilTerminal: untilTerminalOpt, ...iterateOpts } = opts;
|
|
20
|
+
const { intervalSeconds, timeoutSeconds, debounceSeconds: debounceSecondsOpt, quietStatus: quietStatusOpt, untilTerminal: untilTerminalOpt, beforeTick, ...iterateOpts } = opts;
|
|
22
21
|
const intervalMs = Math.min(intervalSeconds * 1000, MAX_TIMER_MS);
|
|
23
22
|
const timeoutMs = Math.min(timeoutSeconds * 1000, MAX_TIMER_MS);
|
|
24
|
-
const debounceSeconds = debounceSecondsOpt ??
|
|
23
|
+
const debounceSeconds = debounceSecondsOpt ?? 60;
|
|
25
24
|
const debounceMs = Math.min(debounceSeconds * 1000, MAX_TIMER_MS);
|
|
26
25
|
const quotaBands = loadConfig().quotaWarningBands;
|
|
27
26
|
const start = Date.now();
|
|
@@ -38,6 +37,7 @@ async function runPollCore(opts, events) {
|
|
|
38
37
|
const rateLimitRetry = createUntilTerminalRateLimitRetry();
|
|
39
38
|
const head = {};
|
|
40
39
|
while (true) {
|
|
40
|
+
beforeTick?.();
|
|
41
41
|
tick += 1;
|
|
42
42
|
const tickStartedAt = Date.now();
|
|
43
43
|
const pastDebounce = debounceUntil !== null && Date.now() >= debounceUntil;
|
package/bin/exit-codes.d.mts
CHANGED
|
@@ -28,6 +28,8 @@ export declare const EXIT: Readonly<{
|
|
|
28
28
|
readonly MERGE: 15;
|
|
29
29
|
/** Aggregate stack has PRs to shepherd through one-PR sessions. */
|
|
30
30
|
readonly SHEPHERD: 16;
|
|
31
|
+
/** Every requested PR is already watched by another live `pr-shepherd` process. */
|
|
32
|
+
readonly WATCHED: 17;
|
|
31
33
|
/** Bad/unknown flag, unknown subcommand, missing required arg, invalid duration. */
|
|
32
34
|
readonly USAGE: 64;
|
|
33
35
|
/** Malformed caller data: bad `--require-sha`, `PRRC_*` IDs, bad repo string. */
|
package/bin/exit-codes.mjs
CHANGED
|
@@ -26,6 +26,8 @@ export const EXIT = Object.freeze({
|
|
|
26
26
|
MERGE: 15,
|
|
27
27
|
/** Aggregate stack has PRs to shepherd through one-PR sessions. */
|
|
28
28
|
SHEPHERD: 16,
|
|
29
|
+
/** Every requested PR is already watched by another live `pr-shepherd` process. */
|
|
30
|
+
WATCHED: 17,
|
|
29
31
|
/** Bad/unknown flag, unknown subcommand, missing required arg, invalid duration. */
|
|
30
32
|
USAGE: 64,
|
|
31
33
|
/** Malformed caller data: bad `--require-sha`, `PRRC_*` IDs, bad repo string. */
|
|
@@ -36,7 +36,10 @@ export function mapCheckRunNode(node) {
|
|
|
36
36
|
return {
|
|
37
37
|
id: node.id,
|
|
38
38
|
name: node.name,
|
|
39
|
-
|
|
39
|
+
// GitHub can report a finished run (conclusion and/or completed_at set) with a stale
|
|
40
|
+
// status such as IN_PROGRESS. A recorded outcome means the run is completed; keep the
|
|
41
|
+
// reported conclusion as-is and invent nothing.
|
|
42
|
+
status: (node.conclusion ? "COMPLETED" : node.status),
|
|
40
43
|
conclusion: node.conclusion,
|
|
41
44
|
source: "check_run",
|
|
42
45
|
detailsUrl: node.detailsUrl ?? "",
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
export interface ProcessStartDeps {
|
|
2
|
+
platform: NodeJS.Platform;
|
|
3
|
+
readFile: (path: string) => string;
|
|
4
|
+
ps: (pid: number) => string;
|
|
5
|
+
}
|
|
6
|
+
export declare const defaultProcessStartDeps: ProcessStartDeps;
|
|
7
|
+
/** Field 22 of `/proc/<pid>/stat` (start time in ticks since boot); `comm` may contain spaces. */
|
|
8
|
+
export declare function parseLinuxStartTicks(stat: string): string | undefined;
|
|
9
|
+
/**
|
|
10
|
+
* An opaque token that identifies one process incarnation of `pid`: `/proc` start ticks on Linux,
|
|
11
|
+
* `ps -o lstart=` elsewhere (macOS). Undefined when it cannot be read, for example when a
|
|
12
|
+
* sandbox hides the process; callers must then fall back to PID liveness alone.
|
|
13
|
+
*/
|
|
14
|
+
export declare function readProcessStart(pid: number, deps?: ProcessStartDeps): string | undefined;
|