pr-shepherd 1.5.0 → 1.6.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.
- package/.claude-plugin/plugin.json +1 -1
- package/README.md +8 -1
- package/bin/api.d.mts +1 -1
- package/bin/cli/display-body.d.mts +8 -0
- package/bin/cli/display-body.mjs +157 -0
- package/bin/cli/list-formatters.mjs +4 -2
- package/bin/commands/iterate/index.mjs +4 -0
- package/bin/commands/poll-events.d.mts +44 -0
- package/bin/commands/poll-events.mjs +123 -0
- package/bin/commands/poll-options.d.mts +9 -0
- package/bin/commands/poll-options.mjs +1 -0
- package/bin/commands/poll-progress.d.mts +2 -0
- package/bin/commands/poll-progress.mjs +6 -4
- package/bin/commands/poll-quota.d.mts +2 -0
- package/bin/commands/poll-quota.mjs +4 -0
- package/bin/commands/poll-summary.d.mts +1 -0
- package/bin/commands/poll-summary.mjs +30 -18
- package/bin/commands/poll-tick.d.mts +17 -0
- package/bin/commands/poll-tick.mjs +24 -0
- package/bin/commands/poll.d.mts +3 -9
- package/bin/commands/poll.mjs +64 -60
- package/bin/commands/stall-deadline.d.mts +20 -0
- package/bin/commands/stall-deadline.mjs +42 -0
- package/bin/commands/tick.mjs +1 -16
- package/bin/config/schema.d.mts +14 -0
- package/bin/config/schema.mjs +6 -0
- package/bin/events/config.d.mts +7 -0
- package/bin/events/config.mjs +66 -0
- package/bin/events/envelope.d.mts +4 -0
- package/bin/events/envelope.mjs +27 -0
- package/bin/events/filters.d.mts +8 -0
- package/bin/events/filters.mjs +27 -0
- package/bin/events/health.d.mts +14 -0
- package/bin/events/health.mjs +27 -0
- package/bin/events/matcher.d.mts +2 -0
- package/bin/events/matcher.mjs +32 -0
- package/bin/events/relay.d.mts +11 -0
- package/bin/events/relay.mjs +86 -0
- package/bin/events/serve.d.mts +10 -0
- package/bin/events/serve.mjs +137 -0
- package/bin/events/sse.d.mts +10 -0
- package/bin/events/sse.mjs +50 -0
- package/bin/events/types.d.mts +69 -0
- package/bin/events/types.mjs +1 -0
- package/bin/events/waiter.d.mts +47 -0
- package/bin/events/waiter.mjs +80 -0
- package/bin/github/batch-first-page.d.mts +17 -0
- package/bin/github/batch-first-page.mjs +48 -0
- package/bin/github/batch-page.d.mts +2 -0
- package/bin/github/batch-page.mjs +2 -2
- package/bin/github/batch-stack-evidence.d.mts +3 -1
- package/bin/github/batch-stack-evidence.mjs +4 -2
- package/bin/github/batch-viewer.d.mts +24 -0
- package/bin/github/batch-viewer.mjs +66 -0
- package/bin/github/batch.d.mts +1 -1
- package/bin/github/batch.mjs +30 -35
- package/bin/github/check-annotations-batch.mjs +1 -7
- package/bin/github/gql/batch-pr-viewer.gql +46 -0
- package/bin/github/gql-strip-viewer.d.mts +7 -0
- package/bin/github/gql-strip-viewer.mjs +14 -0
- package/bin/github/queries.d.mts +8 -0
- package/bin/github/queries.mjs +9 -0
- package/bin/github/thread-comments.d.mts +1 -1
- package/bin/github/thread-comments.mjs +7 -7
- package/bin/types/iterate.d.mts +9 -0
- package/bin/util/chunks.d.mts +2 -0
- package/bin/util/chunks.mjs +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/.codex.mcp.json +1 -1
- package/plugins/pr-shepherd/.mcp.json +1 -1
- package/plugins/pr-shepherd/package-lock.json +4 -4
- package/plugins/pr-shepherd/package.json +1 -1
- package/plugins/pr-shepherd/skills/pr-shepherd/SKILL.md +1 -0
- package/pr-shepherd.schema.json +21 -0
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/** One poll tick that waits out GitHub rate limits instead of failing. */
|
|
2
|
+
export function createTickRunner(input) {
|
|
3
|
+
return async (fingerprintCache) => {
|
|
4
|
+
while (true) {
|
|
5
|
+
try {
|
|
6
|
+
const result = await input.run(fingerprintCache);
|
|
7
|
+
input.retry.reset();
|
|
8
|
+
return result;
|
|
9
|
+
}
|
|
10
|
+
catch (err) {
|
|
11
|
+
const early = await input.retry.wait(err, {
|
|
12
|
+
untilTerminal: input.untilTerminal,
|
|
13
|
+
intervalMs: input.intervalMs,
|
|
14
|
+
tickLabel: input.tickLabel,
|
|
15
|
+
startedAt: input.startedAt,
|
|
16
|
+
targets: input.targets(),
|
|
17
|
+
onAllTerminal: input.onAllTerminal,
|
|
18
|
+
});
|
|
19
|
+
if (early)
|
|
20
|
+
return early;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
};
|
|
24
|
+
}
|
package/bin/commands/poll.d.mts
CHANGED
|
@@ -1,10 +1,4 @@
|
|
|
1
|
-
import type {
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
timeoutSeconds: number;
|
|
5
|
-
/** Settle window after first TRIAGE before returning. Default 60. 0 disables. */
|
|
6
|
-
debounceSeconds?: number;
|
|
7
|
-
quietStatus?: boolean;
|
|
8
|
-
untilTerminal?: boolean;
|
|
9
|
-
}
|
|
1
|
+
import type { IterateResult } from "../types.mts";
|
|
2
|
+
import type { PollCommandOptions } from "./poll-options.mts";
|
|
3
|
+
export type { PollCommandOptions } from "./poll-options.mts";
|
|
10
4
|
export declare function runPoll(opts: PollCommandOptions): Promise<IterateResult>;
|
package/bin/commands/poll.mjs
CHANGED
|
@@ -4,18 +4,20 @@ import { markEditedCommentsSeen } from "./iterate/edited-comment-markers.mjs";
|
|
|
4
4
|
import { sleep } from "../util/sleep.mjs";
|
|
5
5
|
import { withPollApiUsage } from "./poll-run.mjs";
|
|
6
6
|
import { loadConfig } from "../config/load.mjs";
|
|
7
|
-
import { carryQuotaWarning,
|
|
7
|
+
import { carryQuotaWarning, onePrSleepMs } from "./poll-quota.mjs";
|
|
8
8
|
import { onePrCancelFromPulls, onePrRateLimitTargets } from "./poll-rate-limit-cancel.mjs";
|
|
9
9
|
import { createUntilTerminalRateLimitRetry } from "./poll-rate-limit-wait.mjs";
|
|
10
|
+
import { createTickRunner } from "./poll-tick.mjs";
|
|
10
11
|
import { writeDebounceProgress, writeRuleAutoResolveProgress, writeWaitProgress, } from "./poll-progress.mjs";
|
|
11
|
-
import {
|
|
12
|
+
import { onePrDeadline } from "./stall-deadline.mjs";
|
|
13
|
+
import { onePrTargets, pauseBeforeNextTick, withPollEvents, } from "./poll-events.mjs";
|
|
12
14
|
const DEFAULT_POLL_DEBOUNCE_SECONDS = 60;
|
|
13
15
|
const MAX_TIMER_MS = 2 ** 31 - 1;
|
|
14
16
|
const TIMER_DRIFT_TOLERANCE_MS = 500;
|
|
15
17
|
export function runPoll(opts) {
|
|
16
|
-
return withPollApiUsage(() => runPollCore(opts), opts.untilTerminal === true, opts.intervalSeconds / 60);
|
|
18
|
+
return withPollEvents(opts.verbose === true, (events) => withPollApiUsage(() => runPollCore(opts, events), opts.untilTerminal === true, opts.intervalSeconds / 60));
|
|
17
19
|
}
|
|
18
|
-
async function runPollCore(opts) {
|
|
20
|
+
async function runPollCore(opts, events) {
|
|
19
21
|
const { intervalSeconds, timeoutSeconds, debounceSeconds: debounceSecondsOpt, quietStatus: quietStatusOpt, untilTerminal: untilTerminalOpt, ...iterateOpts } = opts;
|
|
20
22
|
const intervalMs = Math.min(intervalSeconds * 1000, MAX_TIMER_MS);
|
|
21
23
|
const timeoutMs = Math.min(timeoutSeconds * 1000, MAX_TIMER_MS);
|
|
@@ -34,43 +36,34 @@ async function runPollCore(opts) {
|
|
|
34
36
|
let prNumber = opts.prNumber;
|
|
35
37
|
let debounceUntil = null;
|
|
36
38
|
const rateLimitRetry = createUntilTerminalRateLimitRetry();
|
|
39
|
+
const head = {};
|
|
37
40
|
while (true) {
|
|
38
41
|
tick += 1;
|
|
42
|
+
const tickStartedAt = Date.now();
|
|
39
43
|
const pastDebounce = debounceUntil !== null && Date.now() >= debounceUntil;
|
|
40
44
|
const seenOptions = pollTickSeenOptions(debounceSeconds, pastDebounce);
|
|
41
45
|
const remainingBefore = untilTerminal
|
|
42
46
|
? Number.POSITIVE_INFINITY
|
|
43
47
|
: timeoutMs - (Date.now() - start);
|
|
44
48
|
const allowCache = debounceUntil === null && remainingBefore + TIMER_DRIFT_TOLERANCE_MS >= intervalMs;
|
|
45
|
-
const
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
49
|
+
const runTick = createTickRunner({
|
|
50
|
+
run: (fingerprintCache) => runIterate({
|
|
51
|
+
...iterateOpts,
|
|
52
|
+
prNumber,
|
|
53
|
+
...seenOptions,
|
|
54
|
+
...(events && { eventTargetSink: head, stallDeadlineSink: head }),
|
|
55
|
+
fingerprintCache,
|
|
56
|
+
deferQuotaWarning: !untilTerminal,
|
|
57
|
+
quotaWarningMinimumPollIntervalMinutes: intervalSeconds / 60,
|
|
58
|
+
}),
|
|
59
|
+
retry: rateLimitRetry,
|
|
60
|
+
untilTerminal,
|
|
61
|
+
intervalMs,
|
|
62
|
+
tickLabel: `poll tick ${tick}`,
|
|
63
|
+
startedAt: start,
|
|
64
|
+
targets: () => onePrRateLimitTargets(iterateOpts.targetRepository, prNumber, lastResult?.repo),
|
|
65
|
+
onAllTerminal: (pulls) => onePrCancelFromPulls(iterateOpts.targetRepository, lastResult?.repo, pulls),
|
|
52
66
|
});
|
|
53
|
-
const runTick = async (fingerprintCache) => {
|
|
54
|
-
while (true) {
|
|
55
|
-
try {
|
|
56
|
-
const result = await iterateTick(fingerprintCache);
|
|
57
|
-
rateLimitRetry.reset();
|
|
58
|
-
return result;
|
|
59
|
-
}
|
|
60
|
-
catch (err) {
|
|
61
|
-
const early = await rateLimitRetry.wait(err, {
|
|
62
|
-
untilTerminal,
|
|
63
|
-
intervalMs,
|
|
64
|
-
tickLabel: `poll tick ${tick}`,
|
|
65
|
-
startedAt: start,
|
|
66
|
-
targets: onePrRateLimitTargets(iterateOpts.targetRepository, prNumber, lastResult?.repo),
|
|
67
|
-
onAllTerminal: (pulls) => onePrCancelFromPulls(iterateOpts.targetRepository, lastResult?.repo, pulls),
|
|
68
|
-
});
|
|
69
|
-
if (early)
|
|
70
|
-
return early;
|
|
71
|
-
}
|
|
72
|
-
}
|
|
73
|
-
};
|
|
74
67
|
lastResult = await runTick(allowCache);
|
|
75
68
|
prNumber ??= lastResult.pr;
|
|
76
69
|
pendingQuotaWarning = carryQuotaWarning(pendingQuotaWarning, lastResult.quotaWarning);
|
|
@@ -80,6 +73,23 @@ async function runPollCore(opts) {
|
|
|
80
73
|
lastResult = await runTick(false);
|
|
81
74
|
pendingQuotaWarning = carryQuotaWarning(pendingQuotaWarning, lastResult.quotaWarning);
|
|
82
75
|
};
|
|
76
|
+
/** Wait for the next tick; true when the poll window ends first and the poll should stop. */
|
|
77
|
+
const pause = async (result, announce) => {
|
|
78
|
+
const deadline = events && (await onePrDeadline(result, iterateOpts, head));
|
|
79
|
+
const sleepMs = onePrSleepMs(quotaBands, result.apiUsage, intervalMs, MAX_TIMER_MS);
|
|
80
|
+
return pauseBeforeNextTick({
|
|
81
|
+
events,
|
|
82
|
+
targets: onePrTargets(result, head),
|
|
83
|
+
recheck: result.mergeStateStatus === "UNKNOWN",
|
|
84
|
+
sleepMs,
|
|
85
|
+
intervalMs,
|
|
86
|
+
label: `poll tick ${tick} / +${Math.round((Date.now() - start) / 1000)}s`,
|
|
87
|
+
tickStartedAt,
|
|
88
|
+
...deadline,
|
|
89
|
+
remainingMs: untilTerminal ? Infinity : timeoutMs - (Date.now() - start),
|
|
90
|
+
announce: (viaEvents) => announce(sleepMs, viaEvents),
|
|
91
|
+
});
|
|
92
|
+
};
|
|
83
93
|
if (untilTerminal &&
|
|
84
94
|
pendingQuotaWarning !== undefined &&
|
|
85
95
|
!(lastResult.action === "triage" && debounceSeconds > 0 && !pastDebounce) &&
|
|
@@ -106,40 +116,34 @@ async function runPollCore(opts) {
|
|
|
106
116
|
if (pendingQuotaWarning === undefined)
|
|
107
117
|
debounceUntil = null;
|
|
108
118
|
const elapsedMs = Date.now() - start;
|
|
109
|
-
const
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
quietStatus,
|
|
123
|
-
verbose,
|
|
124
|
-
lastWaitSignature,
|
|
119
|
+
const waiting = lastResult;
|
|
120
|
+
const stop = await pause(waiting, (sleepMs, viaEvents) => {
|
|
121
|
+
lastWaitSignature = writeWaitProgress({
|
|
122
|
+
tick,
|
|
123
|
+
elapsedMs,
|
|
124
|
+
sleepMs,
|
|
125
|
+
viaEvents,
|
|
126
|
+
result: waiting,
|
|
127
|
+
quietStatus,
|
|
128
|
+
verbose,
|
|
129
|
+
lastWaitSignature,
|
|
130
|
+
});
|
|
131
|
+
writeRuleAutoResolveProgress(waiting);
|
|
125
132
|
});
|
|
126
|
-
|
|
127
|
-
|
|
133
|
+
if (stop) {
|
|
134
|
+
await refreshIfReturning();
|
|
135
|
+
break;
|
|
136
|
+
}
|
|
128
137
|
continue;
|
|
129
138
|
}
|
|
130
139
|
if (swallowsMarkReady && lastResult.action === "mark_ready" && !pastDebounce) {
|
|
131
140
|
debounceUntil = null;
|
|
132
|
-
const
|
|
133
|
-
const
|
|
134
|
-
if (
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
await refreshIfReturning();
|
|
138
|
-
break;
|
|
139
|
-
}
|
|
141
|
+
const ready = lastResult;
|
|
142
|
+
const stop = await pause(ready, () => writeRuleAutoResolveProgress(ready));
|
|
143
|
+
if (stop) {
|
|
144
|
+
await refreshIfReturning();
|
|
145
|
+
break;
|
|
140
146
|
}
|
|
141
|
-
writeRuleAutoResolveProgress(lastResult);
|
|
142
|
-
await sleep(sleepMs);
|
|
143
147
|
continue;
|
|
144
148
|
}
|
|
145
149
|
if (lastResult.action === "triage" && debounceSeconds > 0 && !pastDebounce) {
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { IterateResult, PollSummaryResult } from "../types.mts";
|
|
2
|
+
export declare function earliestDeadline(...deadlines: (number | undefined)[]): number | undefined;
|
|
3
|
+
/**
|
|
4
|
+
* The `deadlineAt` (epoch ms) for an aggregate tick's event wait: a stack stall timer or a
|
|
5
|
+
* ready-delay countdown. No event announces either, so the wait must not outlast them.
|
|
6
|
+
*/
|
|
7
|
+
export declare function aggregateDeadline(result: PollSummaryResult, stallTimeoutSeconds: number | undefined): Promise<WaitDeadline | undefined>;
|
|
8
|
+
/** The `deadlineAt` for a single-PR wait: the stall timeout or the CI-start timeout. */
|
|
9
|
+
export declare function onePrDeadline(result: IterateResult, opts: {
|
|
10
|
+
stallTimeoutSeconds?: number;
|
|
11
|
+
}, sink: {
|
|
12
|
+
ciStartDeadlineSeconds?: number;
|
|
13
|
+
}): Promise<WaitDeadline | undefined>;
|
|
14
|
+
/** A capped event wait's deadline (epoch ms) and the timer it belongs to, for the wake log. */
|
|
15
|
+
export interface WaitDeadline {
|
|
16
|
+
deadlineAt: number;
|
|
17
|
+
deadlineReason: string;
|
|
18
|
+
}
|
|
19
|
+
/** When an unchanged state would trip the stall timeout, or undefined when no timer is running. */
|
|
20
|
+
export declare function readStallDeadline(result: IterateResult, stallTimeoutSeconds: number | undefined): Promise<number | undefined>;
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { loadConfig } from "../config/load.mjs";
|
|
2
|
+
import { readStallState } from "../state/iterate-stall.mjs";
|
|
3
|
+
import { readStackStallDeadline } from "./stack-stall.mjs";
|
|
4
|
+
export function earliestDeadline(...deadlines) {
|
|
5
|
+
const known = deadlines.filter((d) => d !== undefined);
|
|
6
|
+
return known.length > 0 ? Math.min(...known) : undefined;
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* The `deadlineAt` (epoch ms) for an aggregate tick's event wait: a stack stall timer or a
|
|
10
|
+
* ready-delay countdown. No event announces either, so the wait must not outlast them.
|
|
11
|
+
*/
|
|
12
|
+
export async function aggregateDeadline(result, stallTimeoutSeconds) {
|
|
13
|
+
const stall = await readStackStallDeadline(result, stallTimeoutSeconds ?? loadConfig().iterate["stall-timeout-minutes"] * 60);
|
|
14
|
+
const ready = result.prs
|
|
15
|
+
.filter((item) => (item.remainingSeconds ?? 0) > 0)
|
|
16
|
+
.map((item) => [Date.now() / 1000 + item.remainingSeconds, "ready-delay"]);
|
|
17
|
+
return firstDeadline([stall, "stall-timeout"], ...ready);
|
|
18
|
+
}
|
|
19
|
+
/** The `deadlineAt` for a single-PR wait: the stall timeout or the CI-start timeout. */
|
|
20
|
+
export async function onePrDeadline(result, opts, sink) {
|
|
21
|
+
return firstDeadline([await readStallDeadline(result, opts.stallTimeoutSeconds), "stall-timeout"], [result.action === "wait" ? sink.ciStartDeadlineSeconds : undefined, "CI-start"]);
|
|
22
|
+
}
|
|
23
|
+
function firstDeadline(...candidates) {
|
|
24
|
+
let first;
|
|
25
|
+
for (const [seconds, reason] of candidates) {
|
|
26
|
+
if (seconds !== undefined && (first === undefined || seconds * 1000 < first.deadlineAt)) {
|
|
27
|
+
first = { deadlineAt: seconds * 1000, deadlineReason: reason };
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
return first;
|
|
31
|
+
}
|
|
32
|
+
/** When an unchanged state would trip the stall timeout, or undefined when no timer is running. */
|
|
33
|
+
export async function readStallDeadline(result, stallTimeoutSeconds) {
|
|
34
|
+
if (result.action !== "wait")
|
|
35
|
+
return undefined;
|
|
36
|
+
const timeout = stallTimeoutSeconds ?? loadConfig().iterate["stall-timeout-minutes"] * 60;
|
|
37
|
+
const [owner, repo] = result.repo.split("/");
|
|
38
|
+
if (timeout <= 0 || !owner || !repo)
|
|
39
|
+
return undefined;
|
|
40
|
+
const read = await readStallState({ owner, repo, pr: result.pr });
|
|
41
|
+
return read.ok && read.state ? read.state.firstSeenAt + timeout : undefined;
|
|
42
|
+
}
|
package/bin/commands/tick.mjs
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { loadConfig } from "../config/load.mjs";
|
|
2
|
-
import { readStallState } from "../state/iterate-stall.mjs";
|
|
3
2
|
import { tickAggregateStep } from "./tick-instructions.mjs";
|
|
4
3
|
import { earliestNextCheck, MERGE_QUEUE_RECHECK_SECONDS, nextCheckCandidates, SAFETY_NET_SECONDS, } from "./next-check.mjs";
|
|
5
4
|
import { isHandedOffSelection, onlyDraftVerificationSelection, } from "./poll-summary-explicit-instructions.mjs";
|
|
6
5
|
import { runIterate } from "./iterate/index.mjs";
|
|
6
|
+
import { earliestDeadline, readStallDeadline } from "./stall-deadline.mjs";
|
|
7
7
|
import { runsSingleTick } from "./single-tick.mjs";
|
|
8
8
|
import { readStackStallDeadline } from "./stack-stall.mjs";
|
|
9
9
|
import { runPoll } from "./poll.mjs";
|
|
@@ -51,21 +51,6 @@ export function runPollCommand(opts) {
|
|
|
51
51
|
export function runAggregatePollCommand(opts) {
|
|
52
52
|
return runsSingleTick() ? runPollSummaryTick(opts) : runAggregatePoll(opts);
|
|
53
53
|
}
|
|
54
|
-
function earliestDeadline(...deadlines) {
|
|
55
|
-
const known = deadlines.filter((d) => d !== undefined);
|
|
56
|
-
return known.length > 0 ? Math.min(...known) : undefined;
|
|
57
|
-
}
|
|
58
|
-
/** When an unchanged state would trip the stall timeout, or undefined when no timer is running. */
|
|
59
|
-
async function readStallDeadline(result, stallTimeoutSeconds) {
|
|
60
|
-
if (result.action !== "wait")
|
|
61
|
-
return undefined;
|
|
62
|
-
const timeout = stallTimeoutSeconds ?? loadConfig().iterate["stall-timeout-minutes"] * 60;
|
|
63
|
-
const [owner, repo] = result.repo.split("/");
|
|
64
|
-
if (timeout <= 0 || !owner || !repo)
|
|
65
|
-
return undefined;
|
|
66
|
-
const read = await readStallState({ owner, repo, pr: result.pr });
|
|
67
|
-
return read.ok && read.state ? read.state.firstSeenAt + timeout : undefined;
|
|
68
|
-
}
|
|
69
54
|
async function withAggregateNextCheck(result, opts) {
|
|
70
55
|
const stallDeadlineSeconds = await readStackStallDeadline(result, opts.stallTimeoutSeconds ?? loadConfig().iterate["stall-timeout-minutes"] * 60);
|
|
71
56
|
const nextCheck = aggregateNextCheck(result, stallDeadlineSeconds);
|
package/bin/config/schema.d.mts
CHANGED
|
@@ -53,6 +53,13 @@ export declare const configSchema: z.ZodObject<{
|
|
|
53
53
|
"interval-factor": z.ZodOptional<z.ZodNumber>;
|
|
54
54
|
}, z.core.$strict>>>;
|
|
55
55
|
}, z.core.$strict>>;
|
|
56
|
+
events: z.ZodPrefault<z.ZodObject<{
|
|
57
|
+
source: z.ZodDefault<z.ZodEnum<{
|
|
58
|
+
"hook-harness": "hook-harness";
|
|
59
|
+
none: "none";
|
|
60
|
+
}>>;
|
|
61
|
+
"fallback-interval-seconds": z.ZodDefault<z.ZodNumber>;
|
|
62
|
+
}, z.core.$strict>>;
|
|
56
63
|
apply: z.ZodPrefault<z.ZodObject<{
|
|
57
64
|
"sha-poll-interval-seconds": z.ZodDefault<z.ZodNumber>;
|
|
58
65
|
"sha-poll-max-attempts": z.ZodDefault<z.ZodNumber>;
|
|
@@ -131,6 +138,13 @@ export declare const configFileSchema: z.ZodObject<{
|
|
|
131
138
|
"interval-factor": z.ZodOptional<z.ZodNumber>;
|
|
132
139
|
}, z.core.$strict>>>;
|
|
133
140
|
}, z.core.$strict>>;
|
|
141
|
+
events: z.ZodPrefault<z.ZodObject<{
|
|
142
|
+
source: z.ZodDefault<z.ZodEnum<{
|
|
143
|
+
"hook-harness": "hook-harness";
|
|
144
|
+
none: "none";
|
|
145
|
+
}>>;
|
|
146
|
+
"fallback-interval-seconds": z.ZodDefault<z.ZodNumber>;
|
|
147
|
+
}, z.core.$strict>>;
|
|
134
148
|
apply: z.ZodPrefault<z.ZodObject<{
|
|
135
149
|
"sha-poll-interval-seconds": z.ZodDefault<z.ZodNumber>;
|
|
136
150
|
"sha-poll-max-attempts": z.ZodDefault<z.ZodNumber>;
|
package/bin/config/schema.mjs
CHANGED
|
@@ -134,6 +134,12 @@ export const configSchema = z.strictObject({
|
|
|
134
134
|
"quota-warnings": quotaWarnings.default(() => structuredClone(DEFAULT_QUOTA_WARNINGS)),
|
|
135
135
|
})
|
|
136
136
|
.prefault({}),
|
|
137
|
+
events: z
|
|
138
|
+
.strictObject({
|
|
139
|
+
source: z.enum(["none", "hook-harness"]).default("none"),
|
|
140
|
+
"fallback-interval-seconds": positive().max(86_400).default(300),
|
|
141
|
+
})
|
|
142
|
+
.prefault({}),
|
|
137
143
|
apply: z
|
|
138
144
|
.strictObject({
|
|
139
145
|
"sha-poll-interval-seconds": positive().default(2),
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { EventsSourceConfig } from "./types.mts";
|
|
2
|
+
/**
|
|
3
|
+
* Resolve the hook-harness source with its own precedence: `HOOK_HARNESS_SOURCE` (a local
|
|
4
|
+
* `serve`) wins, then `HOOK_HARNESS_URL` + `HOOK_HARNESS_TOKEN`, then `client.json`. Throws a
|
|
5
|
+
* config error when none resolves. The token is returned to callers but never logged here.
|
|
6
|
+
*/
|
|
7
|
+
export declare function resolveEventsSource(env?: NodeJS.ProcessEnv): EventsSourceConfig;
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { EXIT, ShepherdError } from "../exit-codes.mjs";
|
|
5
|
+
const SETUP_HINT = "run `npx -y hook-harness@0.3.3 token create --repos 'owner/*' --label pr-shepherd --login`, " +
|
|
6
|
+
"or set HOOK_HARNESS_URL and HOOK_HARNESS_TOKEN, or set HOOK_HARNESS_SOURCE to a " +
|
|
7
|
+
"`hook-harness serve` URL";
|
|
8
|
+
/** Where hook-harness keeps `client.json`: the same resolution its own CLI uses. */
|
|
9
|
+
function hookHarnessConfigDir(env) {
|
|
10
|
+
if (env["HOOK_HARNESS_CONFIG_DIR"])
|
|
11
|
+
return env["HOOK_HARNESS_CONFIG_DIR"];
|
|
12
|
+
return join(env["XDG_CONFIG_HOME"] || join(homedir(), ".config"), "hook-harness");
|
|
13
|
+
}
|
|
14
|
+
function readSaved(env) {
|
|
15
|
+
try {
|
|
16
|
+
const saved = JSON.parse(readFileSync(join(hookHarnessConfigDir(env), "client.json"), "utf8"));
|
|
17
|
+
if (saved === null || typeof saved !== "object")
|
|
18
|
+
return {};
|
|
19
|
+
const { url, token } = saved;
|
|
20
|
+
return {
|
|
21
|
+
...(typeof url === "string" && { url }),
|
|
22
|
+
...(typeof token === "string" && { token }),
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
catch {
|
|
26
|
+
return {};
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
const LOOPBACK_HOSTS = new Set(["localhost", "127.0.0.1", "[::1]"]);
|
|
30
|
+
/** An http(s) URL; one that carries a bearer token must be https unless it is loopback. */
|
|
31
|
+
function checkedUrl(url, origin, token) {
|
|
32
|
+
let protocol;
|
|
33
|
+
let hostname = "";
|
|
34
|
+
try {
|
|
35
|
+
({ protocol, hostname } = new URL(url));
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
protocol = undefined;
|
|
39
|
+
}
|
|
40
|
+
if (protocol !== "http:" && protocol !== "https:") {
|
|
41
|
+
throw new ShepherdError(`events.source is hook-harness but ${origin} is not an http(s) URL.`, EXIT.CONFIG);
|
|
42
|
+
}
|
|
43
|
+
if (token && protocol === "http:" && !LOOPBACK_HOSTS.has(hostname)) {
|
|
44
|
+
throw new ShepherdError(`events.source is hook-harness but ${origin} would send a token over plain http to a non-loopback host; use https.`, EXIT.CONFIG);
|
|
45
|
+
}
|
|
46
|
+
return url;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Resolve the hook-harness source with its own precedence: `HOOK_HARNESS_SOURCE` (a local
|
|
50
|
+
* `serve`) wins, then `HOOK_HARNESS_URL` + `HOOK_HARNESS_TOKEN`, then `client.json`. Throws a
|
|
51
|
+
* config error when none resolves. The token is returned to callers but never logged here.
|
|
52
|
+
*/
|
|
53
|
+
export function resolveEventsSource(env = process.env) {
|
|
54
|
+
const source = env["HOOK_HARNESS_SOURCE"];
|
|
55
|
+
if (source) {
|
|
56
|
+
const token = env["HOOK_HARNESS_SOURCE_TOKEN"] ?? "";
|
|
57
|
+
return { kind: "serve", url: checkedUrl(source, "HOOK_HARNESS_SOURCE", token), token };
|
|
58
|
+
}
|
|
59
|
+
const saved = readSaved(env);
|
|
60
|
+
const url = env["HOOK_HARNESS_URL"] || saved.url;
|
|
61
|
+
const token = env["HOOK_HARNESS_TOKEN"] || saved.token;
|
|
62
|
+
if (!url || !token) {
|
|
63
|
+
throw new ShepherdError(`events.source is hook-harness but no hook-harness login was found: ${SETUP_HINT}.`, EXIT.CONFIG);
|
|
64
|
+
}
|
|
65
|
+
return { kind: "relay", url: checkedUrl(url, "the hook-harness relay URL", token), token };
|
|
66
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { EventEnvelope } from "./types.mts";
|
|
2
|
+
/** Keep only the fields pr-shepherd reads; additive envelope fields are ignored. */
|
|
3
|
+
export declare function parseEnvelope(raw: unknown): EventEnvelope | null;
|
|
4
|
+
export declare function parseEnvelopes(raw: unknown): EventEnvelope[];
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
const text = (value) => (typeof value === "string" ? value : null);
|
|
2
|
+
/** Keep only the fields pr-shepherd reads; additive envelope fields are ignored. */
|
|
3
|
+
export function parseEnvelope(raw) {
|
|
4
|
+
if (raw === null || typeof raw !== "object")
|
|
5
|
+
return null;
|
|
6
|
+
const value = raw;
|
|
7
|
+
if (typeof value["id"] !== "string" || typeof value["event"] !== "string")
|
|
8
|
+
return null;
|
|
9
|
+
const prs = Array.isArray(value["prs"])
|
|
10
|
+
? value["prs"].filter((pr) => typeof pr === "number")
|
|
11
|
+
: [];
|
|
12
|
+
return {
|
|
13
|
+
id: value["id"],
|
|
14
|
+
event: value["event"],
|
|
15
|
+
action: text(value["action"]),
|
|
16
|
+
repo: text(value["repo"]),
|
|
17
|
+
prs,
|
|
18
|
+
headSha: text(value["headSha"]),
|
|
19
|
+
headRef: text(value["headRef"]),
|
|
20
|
+
baseRef: text(value["baseRef"]),
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
export function parseEnvelopes(raw) {
|
|
24
|
+
if (!Array.isArray(raw))
|
|
25
|
+
return [];
|
|
26
|
+
return raw.flatMap((item) => parseEnvelope(item) ?? []);
|
|
27
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { EventFilter, WatchTarget } from "./types.mts";
|
|
2
|
+
/**
|
|
3
|
+
* A superset hint for the relay: events for these PR numbers, head SHAs, head branches, or pushes
|
|
4
|
+
* to their base branches. Local matching stays authoritative; older relays ignore the parameter.
|
|
5
|
+
*/
|
|
6
|
+
export declare function filtersFor(targets: readonly WatchTarget[]): EventFilter[];
|
|
7
|
+
/** The `filters` query value, or undefined when over the relay's limits (match locally). */
|
|
8
|
+
export declare function filtersParam(filters: readonly EventFilter[]): string | undefined;
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
const MAX_FILTERS = 50;
|
|
2
|
+
const MAX_FILTER_BYTES = 4096;
|
|
3
|
+
/**
|
|
4
|
+
* A superset hint for the relay: events for these PR numbers, head SHAs, head branches, or pushes
|
|
5
|
+
* to their base branches. Local matching stays authoritative; older relays ignore the parameter.
|
|
6
|
+
*/
|
|
7
|
+
export function filtersFor(targets) {
|
|
8
|
+
const unique = (values) => [
|
|
9
|
+
...new Set(values.filter((value) => Boolean(value))),
|
|
10
|
+
];
|
|
11
|
+
const sha = unique(targets.map((target) => target.headSha));
|
|
12
|
+
const ref = unique(targets.map((target) => target.headRef));
|
|
13
|
+
const base = unique(targets.map((target) => target.baseRef));
|
|
14
|
+
return [
|
|
15
|
+
{ pr: targets.map((target) => target.pr) },
|
|
16
|
+
...(sha.length > 0 ? [{ sha }] : []),
|
|
17
|
+
...(ref.length > 0 ? [{ ref }] : []),
|
|
18
|
+
...(base.length > 0 ? [{ event: ["push"], branch: base }] : []),
|
|
19
|
+
];
|
|
20
|
+
}
|
|
21
|
+
/** The `filters` query value, or undefined when over the relay's limits (match locally). */
|
|
22
|
+
export function filtersParam(filters) {
|
|
23
|
+
if (filters.length === 0 || filters.length > MAX_FILTERS)
|
|
24
|
+
return undefined;
|
|
25
|
+
const json = JSON.stringify(filters);
|
|
26
|
+
return json.length > MAX_FILTER_BYTES ? undefined : json;
|
|
27
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { WatchTarget } from "./types.mts";
|
|
2
|
+
export declare const ownerOf: (repo: string) => string;
|
|
3
|
+
/**
|
|
4
|
+
* Per-run source health. An owner the token cannot read stays uncovered for the run; transient
|
|
5
|
+
* trouble (5xx, network, gap) is tracked as a flag so each state change is noted exactly once.
|
|
6
|
+
*/
|
|
7
|
+
export interface EventHealth {
|
|
8
|
+
/** True when no watched owner is uncovered, so an event wait is worth attempting. */
|
|
9
|
+
covers(targets: readonly WatchTarget[]): boolean;
|
|
10
|
+
markUncovered(owner: string, reason: string): void;
|
|
11
|
+
markUnhealthy(reason: string): void;
|
|
12
|
+
markHealthy(): void;
|
|
13
|
+
}
|
|
14
|
+
export declare function createHealth(note: (message: string) => void): EventHealth;
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
export const ownerOf = (repo) => repo.split("/")[0].toLowerCase();
|
|
2
|
+
export function createHealth(note) {
|
|
3
|
+
const uncovered = new Set();
|
|
4
|
+
let unhealthy = false;
|
|
5
|
+
return {
|
|
6
|
+
covers: (targets) => targets.length > 0 && targets.every((target) => !uncovered.has(ownerOf(target.repo))),
|
|
7
|
+
markUncovered(owner, reason) {
|
|
8
|
+
const key = owner.toLowerCase();
|
|
9
|
+
if (uncovered.has(key))
|
|
10
|
+
return;
|
|
11
|
+
uncovered.add(key);
|
|
12
|
+
note(`events: ${owner} is not covered by this token (${reason}); polling it normally`);
|
|
13
|
+
},
|
|
14
|
+
markUnhealthy(reason) {
|
|
15
|
+
if (unhealthy)
|
|
16
|
+
return;
|
|
17
|
+
unhealthy = true;
|
|
18
|
+
note(`events: source unhealthy (${reason}); polling normally until it recovers`);
|
|
19
|
+
},
|
|
20
|
+
markHealthy() {
|
|
21
|
+
if (!unhealthy)
|
|
22
|
+
return;
|
|
23
|
+
unhealthy = false;
|
|
24
|
+
note("events: source recovered");
|
|
25
|
+
},
|
|
26
|
+
};
|
|
27
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
const QUEUE_REF = /^gh-readonly-queue\/(.+)\/pr-(\d+)-/;
|
|
2
|
+
function branch(ref) {
|
|
3
|
+
return ref === null ? null : ref.replace(/^refs\/heads\//, "");
|
|
4
|
+
}
|
|
5
|
+
function queuedPr(ref) {
|
|
6
|
+
const match = ref === null ? null : QUEUE_REF.exec(ref);
|
|
7
|
+
return match ? { base: match[1], pr: Number(match[2]) } : null;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* True when `event` may change what an iterate tick sees for `target`. Deliberately generous:
|
|
11
|
+
* a spurious wake costs one tick, a missed one costs up to the fallback interval.
|
|
12
|
+
*/
|
|
13
|
+
function matchesTarget(event, target) {
|
|
14
|
+
if (event.repo?.toLowerCase() !== target.repo.toLowerCase())
|
|
15
|
+
return false;
|
|
16
|
+
if (event.prs.includes(target.pr))
|
|
17
|
+
return true;
|
|
18
|
+
if (target.headSha !== undefined && event.headSha?.toLowerCase() === target.headSha.toLowerCase())
|
|
19
|
+
return true;
|
|
20
|
+
const eventHead = branch(event.headRef);
|
|
21
|
+
if (target.headRef !== undefined && eventHead === target.headRef)
|
|
22
|
+
return true;
|
|
23
|
+
const queued = queuedPr(eventHead);
|
|
24
|
+
if (queued?.pr === target.pr && (target.baseRef === undefined || queued.base === target.baseRef))
|
|
25
|
+
return true;
|
|
26
|
+
// Only a push moves the base. Other PRs' events also carry this base as `baseRef`; matching
|
|
27
|
+
// them would wake every PR in a busy repository on every sibling's activity.
|
|
28
|
+
return target.baseRef !== undefined && event.event === "push" && eventHead === target.baseRef;
|
|
29
|
+
}
|
|
30
|
+
export function matchesAny(event, targets) {
|
|
31
|
+
return targets.some((target) => matchesTarget(event, target));
|
|
32
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { EventDeps, EventTransport } from "./types.mts";
|
|
2
|
+
/** Per-request bound the default fetch applies (proxy-aware `githubFetch`). */
|
|
3
|
+
export declare const RELAY_REQUEST_TIMEOUT_MS = 10000;
|
|
4
|
+
/**
|
|
5
|
+
* Polls the relay's `GET /events`, one request per owner (DynamoDB partitions by owner). Cursors
|
|
6
|
+
* are opaque and echoed back exactly; the only one constructed is the bare epoch-ms start.
|
|
7
|
+
*/
|
|
8
|
+
export declare function createRelayTransport(config: {
|
|
9
|
+
url: string;
|
|
10
|
+
token: string;
|
|
11
|
+
}, startMs: number, deps: Pick<EventDeps, "fetch">): EventTransport;
|