pr-shepherd 2.2.10 → 2.2.12
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/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 +15 -8
- 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/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/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
- package/plugins/pr-shepherd/skills/pr-shepherd/references/check-follow-up.md +1 -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
|
+
}
|
|
@@ -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. */
|
|
@@ -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;
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { execFileSync } from "node:child_process";
|
|
2
|
+
import { readFileSync } from "node:fs";
|
|
3
|
+
export const defaultProcessStartDeps = {
|
|
4
|
+
platform: process.platform,
|
|
5
|
+
readFile: (path) => readFileSync(path, "utf8"),
|
|
6
|
+
ps: (pid) => execFileSync("ps", ["-o", "lstart=", "-p", String(pid)], {
|
|
7
|
+
encoding: "utf8",
|
|
8
|
+
env: { ...process.env, LC_ALL: "C" },
|
|
9
|
+
timeout: 2000,
|
|
10
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
11
|
+
}),
|
|
12
|
+
};
|
|
13
|
+
/** Field 22 of `/proc/<pid>/stat` (start time in ticks since boot); `comm` may contain spaces. */
|
|
14
|
+
export function parseLinuxStartTicks(stat) {
|
|
15
|
+
const rest = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
|
|
16
|
+
const ticks = rest[19];
|
|
17
|
+
return ticks && /^\d+$/.test(ticks) ? ticks : undefined;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* An opaque token that identifies one process incarnation of `pid`: `/proc` start ticks on Linux,
|
|
21
|
+
* `ps -o lstart=` elsewhere (macOS). Undefined when it cannot be read, for example when a
|
|
22
|
+
* sandbox hides the process; callers must then fall back to PID liveness alone.
|
|
23
|
+
*/
|
|
24
|
+
export function readProcessStart(pid, deps = defaultProcessStartDeps) {
|
|
25
|
+
try {
|
|
26
|
+
if (deps.platform === "linux") {
|
|
27
|
+
const ticks = parseLinuxStartTicks(deps.readFile(`/proc/${pid}/stat`));
|
|
28
|
+
return ticks && `linux:${ticks}`;
|
|
29
|
+
}
|
|
30
|
+
return deps.ps(pid).trim() || undefined;
|
|
31
|
+
}
|
|
32
|
+
catch {
|
|
33
|
+
return undefined;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
export interface WatchRepo {
|
|
2
|
+
owner: string;
|
|
3
|
+
name: string;
|
|
4
|
+
}
|
|
5
|
+
export interface WatchHolder {
|
|
6
|
+
pr: number;
|
|
7
|
+
pid: number;
|
|
8
|
+
/** Opaque process start token; absent when the holder's start time could not be read. */
|
|
9
|
+
startedAt?: string;
|
|
10
|
+
/** The holder's relevant flags, such as `--merge`. */
|
|
11
|
+
flags: string[];
|
|
12
|
+
}
|
|
13
|
+
export type AcquireResult = {
|
|
14
|
+
acquired: true;
|
|
15
|
+
} | {
|
|
16
|
+
acquired: false;
|
|
17
|
+
holder: WatchHolder;
|
|
18
|
+
};
|
|
19
|
+
/** Claims the per-PR watcher lock, taking it over from a dead or PID-reused holder. */
|
|
20
|
+
export declare function acquireWatchLock(repo: WatchRepo, pr: number, flags: string[]): AcquireResult;
|
|
21
|
+
/**
|
|
22
|
+
* Per-tick ownership check for a PR this process holds: one file read when the lock is still ours.
|
|
23
|
+
* A missing or unreadable file is recreated (an `admin clean` may have removed the directory), a
|
|
24
|
+
* stale holder is taken over, and a live other holder is left untouched and returned as lost.
|
|
25
|
+
*/
|
|
26
|
+
export declare function verifyWatchLock(repo: WatchRepo, pr: number, flags: string[]): AcquireResult;
|
|
27
|
+
/** Removes this process's lock for `pr`; another process's lock is never touched. */
|
|
28
|
+
export declare function releaseWatchLock(repo: WatchRepo, pr: number): void;
|
|
29
|
+
export declare function releaseAllWatchLocks(): void;
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import { linkSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { dirname } from "node:path";
|
|
3
|
+
import { resolvePrStatePath } from "./base.mjs";
|
|
4
|
+
import { readProcessStart } from "./process-start.mjs";
|
|
5
|
+
const LOCK_FILE = "watch.lock.json";
|
|
6
|
+
const GUARD_FILE = "watch.lock.guard";
|
|
7
|
+
const GUARD_STALE_MS = 10_000;
|
|
8
|
+
const ATTEMPTS = 4;
|
|
9
|
+
const held = new Map();
|
|
10
|
+
let hooksInstalled = false;
|
|
11
|
+
let tmpSeq = 0;
|
|
12
|
+
const keyOf = (repo, pr) => `${repo.owner}/${repo.name}#${pr}`;
|
|
13
|
+
const pathFor = (repo, pr, file = LOCK_FILE) => resolvePrStatePath({ owner: repo.owner, repo: repo.name, pr }, file);
|
|
14
|
+
function readHolder(path) {
|
|
15
|
+
try {
|
|
16
|
+
const parsed = JSON.parse(readFileSync(path, "utf8"));
|
|
17
|
+
const valid = Number.isInteger(parsed.pid) && parsed.pid > 0 && Array.isArray(parsed.flags);
|
|
18
|
+
return valid ? parsed : undefined;
|
|
19
|
+
}
|
|
20
|
+
catch {
|
|
21
|
+
return undefined;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
/** Only ESRCH proves the process is gone; EPERM (a sandbox hiding it) means it exists. */
|
|
25
|
+
function pidAlive(pid) {
|
|
26
|
+
try {
|
|
27
|
+
process.kill(pid, 0);
|
|
28
|
+
return true;
|
|
29
|
+
}
|
|
30
|
+
catch (error) {
|
|
31
|
+
return error.code !== "ESRCH";
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
/** Dead holder, or a live PID whose readable start time differs (PID reuse). Unreadable start: alive. */
|
|
35
|
+
function isStale(holder) {
|
|
36
|
+
if (!pidAlive(holder.pid))
|
|
37
|
+
return true;
|
|
38
|
+
if (!holder.startedAt)
|
|
39
|
+
return false;
|
|
40
|
+
const current = readProcessStart(holder.pid);
|
|
41
|
+
return current !== undefined && current !== holder.startedAt;
|
|
42
|
+
}
|
|
43
|
+
/** Publishes the full lock content atomically: the hard link fails with EEXIST when a lock exists. */
|
|
44
|
+
function linkLock(path, holder) {
|
|
45
|
+
const tmp = `${path}.${process.pid}.${(tmpSeq += 1)}.tmp`;
|
|
46
|
+
writeFileSync(tmp, JSON.stringify(holder));
|
|
47
|
+
try {
|
|
48
|
+
linkSync(tmp, path);
|
|
49
|
+
return true;
|
|
50
|
+
}
|
|
51
|
+
catch (error) {
|
|
52
|
+
if (error.code === "EEXIST")
|
|
53
|
+
return false;
|
|
54
|
+
throw error;
|
|
55
|
+
}
|
|
56
|
+
finally {
|
|
57
|
+
rmSync(tmp, { force: true });
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
/** Only the holder of the guard may remove a stale lock, so two takeovers cannot both win. */
|
|
61
|
+
function takeOver(repo, pr, mine) {
|
|
62
|
+
const path = pathFor(repo, pr);
|
|
63
|
+
const guard = pathFor(repo, pr, GUARD_FILE);
|
|
64
|
+
try {
|
|
65
|
+
writeFileSync(guard, "", { flag: "wx" });
|
|
66
|
+
}
|
|
67
|
+
catch (error) {
|
|
68
|
+
if (error.code !== "EEXIST")
|
|
69
|
+
throw error;
|
|
70
|
+
// A guard left by a crashed takeover must not block the PR forever.
|
|
71
|
+
const guardMtime = statSync(guard, { throwIfNoEntry: false })?.mtimeMs ?? Date.now();
|
|
72
|
+
if (Date.now() - guardMtime > GUARD_STALE_MS) {
|
|
73
|
+
rmSync(guard, { force: true });
|
|
74
|
+
}
|
|
75
|
+
return false;
|
|
76
|
+
}
|
|
77
|
+
try {
|
|
78
|
+
const current = readHolder(path);
|
|
79
|
+
if (current && !isStale(current))
|
|
80
|
+
return false;
|
|
81
|
+
rmSync(path, { force: true });
|
|
82
|
+
return linkLock(path, mine);
|
|
83
|
+
}
|
|
84
|
+
finally {
|
|
85
|
+
rmSync(guard, { force: true });
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
/** Claims the per-PR watcher lock, taking it over from a dead or PID-reused holder. */
|
|
89
|
+
export function acquireWatchLock(repo, pr, flags) {
|
|
90
|
+
const path = pathFor(repo, pr);
|
|
91
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
92
|
+
const startedAt = readProcessStart(process.pid);
|
|
93
|
+
const mine = { pr, pid: process.pid, ...(startedAt && { startedAt }), flags };
|
|
94
|
+
for (let attempt = 0; attempt < ATTEMPTS; attempt += 1) {
|
|
95
|
+
if (linkLock(path, mine) || takeOverIfStale(repo, pr, mine)) {
|
|
96
|
+
track(repo, pr);
|
|
97
|
+
return { acquired: true };
|
|
98
|
+
}
|
|
99
|
+
const current = readHolder(path);
|
|
100
|
+
if (current && !isStale(current))
|
|
101
|
+
return { acquired: false, holder: current };
|
|
102
|
+
}
|
|
103
|
+
throw new Error(`could not acquire the watch lock for PR #${pr}`);
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* Per-tick ownership check for a PR this process holds: one file read when the lock is still ours.
|
|
107
|
+
* A missing or unreadable file is recreated (an `admin clean` may have removed the directory), a
|
|
108
|
+
* stale holder is taken over, and a live other holder is left untouched and returned as lost.
|
|
109
|
+
*/
|
|
110
|
+
export function verifyWatchLock(repo, pr, flags) {
|
|
111
|
+
if (readHolder(pathFor(repo, pr))?.pid === process.pid)
|
|
112
|
+
return { acquired: true };
|
|
113
|
+
const result = acquireWatchLock(repo, pr, flags);
|
|
114
|
+
if (!result.acquired)
|
|
115
|
+
held.delete(keyOf(repo, pr));
|
|
116
|
+
return result;
|
|
117
|
+
}
|
|
118
|
+
function takeOverIfStale(repo, pr, mine) {
|
|
119
|
+
const current = readHolder(pathFor(repo, pr));
|
|
120
|
+
return (current === undefined || isStale(current)) && takeOver(repo, pr, mine);
|
|
121
|
+
}
|
|
122
|
+
/** Removes this process's lock for `pr`; another process's lock is never touched. */
|
|
123
|
+
export function releaseWatchLock(repo, pr) {
|
|
124
|
+
held.delete(keyOf(repo, pr));
|
|
125
|
+
const path = pathFor(repo, pr);
|
|
126
|
+
if (readHolder(path)?.pid === process.pid)
|
|
127
|
+
rmSync(path, { force: true });
|
|
128
|
+
}
|
|
129
|
+
export function releaseAllWatchLocks() {
|
|
130
|
+
for (const { repo, pr } of held.values())
|
|
131
|
+
releaseWatchLock(repo, pr);
|
|
132
|
+
}
|
|
133
|
+
function track(repo, pr) {
|
|
134
|
+
held.set(keyOf(repo, pr), { repo, pr });
|
|
135
|
+
if (hooksInstalled)
|
|
136
|
+
return;
|
|
137
|
+
hooksInstalled = true;
|
|
138
|
+
process.on("exit", releaseAllWatchLocks);
|
|
139
|
+
for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"]) {
|
|
140
|
+
process.once(signal, () => {
|
|
141
|
+
releaseAllWatchLocks();
|
|
142
|
+
process.kill(process.pid, signal);
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
}
|