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
package/README.md
CHANGED
|
@@ -113,6 +113,11 @@ Waiting is where most quota goes, and where Shepherd saves the most. By default
|
|
|
113
113
|
|
|
114
114
|
Fewer requests help on both tiers. The GitHub MCP server issues one or more REST requests per tool call, so unbatched calls drain `core` and the per-minute pool faster.
|
|
115
115
|
|
|
116
|
+
Two optional setups take most of the remaining spend off your token. They are independent and combine:
|
|
117
|
+
|
|
118
|
+
- **[GitHub App](docs/github-app.md):** reads whose answer does not depend on who asks go to an app installation, which has its own budget. On a live PR, one tick's user-token GraphQL dropped from a 3,135-node read to a 4-node viewer read, and a tick that reuses the stored report spends none, except that a native-stack layer still reads `PollStackTopology` on your token. Six ticks went from 7 user-token requests (21,945 nodes) to 2 (8 nodes). READY-receipt reads, stack summaries, and ticks while the app's quota is spent stay on your token ([details](docs/github-app.md#the-batchpr-viewer-split)).
|
|
119
|
+
- **[hook-harness events](docs/hook-harness.md):** a poll waits for a GitHub webhook event about the PR instead of sleeping a fixed interval. A quiet PR ticks every 5 minutes (`events.fallback-interval-seconds`) instead of every minute. A push or check result wakes it after a 10-second settle, but never sooner than `poll.interval-seconds` after the previous tick began, so up to about a minute at the default interval. Events never make ticks more frequent than plain polling.
|
|
120
|
+
|
|
116
121
|
Per session, assumed and deterministic, from the [token bench](evals/tokens/README.md):
|
|
117
122
|
|
|
118
123
|
| Session | GraphQL points: Shepherd / `gh` / MCP | REST core: Shepherd / `gh` / MCP |
|
|
@@ -140,6 +145,7 @@ See [docs/graphql-usage.md](docs/graphql-usage.md) and [docs/rest-usage.md](docs
|
|
|
140
145
|
- Cursor and other stdio clients use the [MCP server](docs/mcp.md).
|
|
141
146
|
- Shell and CI use the [CLI](docs/cli-usage.md).
|
|
142
147
|
- In Claude Code cloud sessions, Shepherd switches to the [REST transport](docs/rest.md) and [single ticks](docs/cloud.md).
|
|
148
|
+
- Optional [event-driven waiting](docs/hook-harness.md) wakes a poll on GitHub webhook events instead of a fixed sleep.
|
|
143
149
|
- `stack` reports every layer of a native GitHub stacked PR and shepherds the layers you own.
|
|
144
150
|
|
|
145
151
|
## Use cases
|
|
@@ -210,6 +216,7 @@ Leave out the PR number to use the current branch.
|
|
|
210
216
|
| Features, workflow assumptions, limits | [docs/features.md](docs/features.md) |
|
|
211
217
|
| Commands, flags, stacks, polling | [docs/cli-usage.md](docs/cli-usage.md) |
|
|
212
218
|
| GitHub App auth (separate rate limit) | [docs/github-app.md](docs/github-app.md) |
|
|
219
|
+
| Event-driven waits (hook-harness) | [docs/hook-harness.md](docs/hook-harness.md) |
|
|
213
220
|
| Actions and exit codes | [docs/actions.md](docs/actions.md), [docs/exit-codes.md](docs/exit-codes.md) |
|
|
214
221
|
| Configuration and classification rules | [docs/configuration.md](docs/configuration.md), [examples/classification/](examples/classification/) |
|
|
215
222
|
| Journal, library API | [docs/api.md](docs/api.md) |
|
|
@@ -218,7 +225,7 @@ Leave out the PR number to use the current branch.
|
|
|
218
225
|
|
|
219
226
|
## Harness ecosystem
|
|
220
227
|
|
|
221
|
-
- [
|
|
228
|
+
- [hook-harness](https://github.com/jonathanong/hook-harness): GitHub webhook relay that agents poll for events instead of polling GitHub
|
|
222
229
|
- [agent-blackboard](https://github.com/jonathanong/agent-blackboard): session-scoped telemetry for autonomous agents
|
|
223
230
|
- [pr-shepherd](https://github.com/jonathanong/pr-shepherd): autonomous pull request shepherd
|
|
224
231
|
- [no-mistakes](https://github.com/jonathanong/no-mistakes): deterministic AST-based codebase intelligence, test selection, and linting for agents
|
package/bin/api.d.mts
CHANGED
|
@@ -27,7 +27,7 @@ export interface CreatePrShepherdOptions {
|
|
|
27
27
|
}
|
|
28
28
|
/** A positive PR number, GitHub pull-request URL, or owner/repo#number reference. */
|
|
29
29
|
export type PrReference = number | string;
|
|
30
|
-
type IterateOptions = Omit<IterateCommandOptions, "format" | "prNumber" | "targetRepository" | "persistSeen" | "deferEditedCommentMarkers" | "fingerprintCache" | "stallDeadlineSink" | "deferQuotaWarning" | "quotaWarningMinimumPollIntervalMinutes">;
|
|
30
|
+
type IterateOptions = Omit<IterateCommandOptions, "format" | "prNumber" | "targetRepository" | "persistSeen" | "deferEditedCommentMarkers" | "fingerprintCache" | "stallDeadlineSink" | "eventTargetSink" | "deferQuotaWarning" | "quotaWarningMinimumPollIntervalMinutes">;
|
|
31
31
|
export type SingleIterateInput = IterateOptions & {
|
|
32
32
|
pr?: PrReference;
|
|
33
33
|
prs?: never;
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The visible text of a GitHub Markdown body, for Markdown output: closed HTML comments,
|
|
3
|
+
* `<picture>` image wrappers, and links left empty by them are dropped, because GitHub does not
|
|
4
|
+
* display them. Fenced and indented code and inline code spans are kept verbatim. Blank runs
|
|
5
|
+
* collapse to one; a body with no visible text is returned unchanged. JSON and `--verbose` keep
|
|
6
|
+
* the raw body.
|
|
7
|
+
*/
|
|
8
|
+
export declare function displayBody(body: string): string;
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
const COMMENT_OPEN = "<!--";
|
|
2
|
+
const COMMENT_CLOSE = "-->";
|
|
3
|
+
const PICTURE_RE = /<picture>[\s\S]*?<\/picture>/g;
|
|
4
|
+
const IMG_RE = /<img\s[^>]*>/;
|
|
5
|
+
// A link left with no visible content after the pictures inside it are dropped.
|
|
6
|
+
const EMPTY_ANCHOR_RE = /<a\s[^>]*>\s*<\/a>/g;
|
|
7
|
+
function fenceMarker(line) {
|
|
8
|
+
const match = /^ {0,3}(`{3,}|~{3,})/.exec(line);
|
|
9
|
+
return match ? match[1] : null;
|
|
10
|
+
}
|
|
11
|
+
function closesFence(line, fence) {
|
|
12
|
+
const trimmed = line.trim();
|
|
13
|
+
return trimmed.length >= fence.length && [...trimmed].every((c) => c === fence[0]);
|
|
14
|
+
}
|
|
15
|
+
const isIndented = (line) => /^(?: {4}|\t)/.test(line);
|
|
16
|
+
// Blockquote and list markers are containers: code inside a quote or list item is still code.
|
|
17
|
+
const containerContent = (line) => line.replace(/^(?: {0,3}(?:> ?|(?:[-*+]|\d{1,9}[.)])(?: |$)))+/, "");
|
|
18
|
+
const attribute = (tag, name) => new RegExp(`\\s${name}="([^"]*)"`).exec(tag)?.[1];
|
|
19
|
+
/**
|
|
20
|
+
* A `<picture>` as Markdown image text. An image whose `alt` is explicitly empty is decorative
|
|
21
|
+
* (CodeRabbit's severity icons) and is dropped; any other keeps its alt text and source.
|
|
22
|
+
*/
|
|
23
|
+
function pictureText(picture) {
|
|
24
|
+
const img = IMG_RE.exec(picture)?.[0];
|
|
25
|
+
if (img === undefined)
|
|
26
|
+
return "";
|
|
27
|
+
const alt = attribute(img, "alt");
|
|
28
|
+
if (alt === "")
|
|
29
|
+
return "";
|
|
30
|
+
const src = attribute(img, "src");
|
|
31
|
+
return src === undefined ? (alt ?? "") : ``;
|
|
32
|
+
}
|
|
33
|
+
const isBlank = (line) => line.trim() === "";
|
|
34
|
+
/**
|
|
35
|
+
* Marks lines GitHub renders as code: fenced blocks and indented blocks (which start after a
|
|
36
|
+
* blank line and continue through indented or blank lines).
|
|
37
|
+
*/
|
|
38
|
+
function codeLines(lines) {
|
|
39
|
+
const code = [];
|
|
40
|
+
let fence = null;
|
|
41
|
+
let indented = false;
|
|
42
|
+
const content = lines.map(containerContent);
|
|
43
|
+
for (let i = 0; i < content.length; i++) {
|
|
44
|
+
const line = content[i];
|
|
45
|
+
if (fence) {
|
|
46
|
+
code.push(true);
|
|
47
|
+
if (closesFence(line, fence))
|
|
48
|
+
fence = null;
|
|
49
|
+
continue;
|
|
50
|
+
}
|
|
51
|
+
fence = fenceMarker(line);
|
|
52
|
+
// A blank line ends `indented`, but the next indented line restarts it (blank line before).
|
|
53
|
+
indented = isIndented(line) && (indented || i === 0 || isBlank(content[i - 1]));
|
|
54
|
+
code.push(fence !== null || (indented && !isBlank(line)));
|
|
55
|
+
}
|
|
56
|
+
return code;
|
|
57
|
+
}
|
|
58
|
+
/** Index just past the inline code span opening at `i`, or -1 when its backticks never close. */
|
|
59
|
+
function codeSpanEnd(text, i) {
|
|
60
|
+
let n = 0;
|
|
61
|
+
while (text[i + n] === "`")
|
|
62
|
+
n++;
|
|
63
|
+
const run = "`".repeat(n);
|
|
64
|
+
let at = text.indexOf(run, i + n);
|
|
65
|
+
while (at !== -1) {
|
|
66
|
+
let len = 0;
|
|
67
|
+
while (text[at + len] === "`")
|
|
68
|
+
len++;
|
|
69
|
+
if (len === n)
|
|
70
|
+
return at + n;
|
|
71
|
+
at = text.indexOf(run, at + len);
|
|
72
|
+
}
|
|
73
|
+
return -1;
|
|
74
|
+
}
|
|
75
|
+
const dropImageMarkup = (text) => text.replace(PICTURE_RE, pictureText).replace(EMPTY_ANCHOR_RE, "");
|
|
76
|
+
/**
|
|
77
|
+
* Removes closed `<!-- … -->` comments, `<picture>` wrappers, and links left empty, all outside
|
|
78
|
+
* inline code spans; unclosed comment openers stay literal.
|
|
79
|
+
*/
|
|
80
|
+
function stripHiddenMarkup(text) {
|
|
81
|
+
let out = "";
|
|
82
|
+
let plain = "";
|
|
83
|
+
let i = 0;
|
|
84
|
+
while (i < text.length) {
|
|
85
|
+
if (text[i] === "`") {
|
|
86
|
+
let n = 0;
|
|
87
|
+
while (text[i + n] === "`")
|
|
88
|
+
n++;
|
|
89
|
+
const end = codeSpanEnd(text, i);
|
|
90
|
+
const next = end === -1 ? i + n : end;
|
|
91
|
+
if (end === -1) {
|
|
92
|
+
plain += text.slice(i, next);
|
|
93
|
+
}
|
|
94
|
+
else {
|
|
95
|
+
out += dropImageMarkup(plain) + text.slice(i, next);
|
|
96
|
+
plain = "";
|
|
97
|
+
}
|
|
98
|
+
i = next;
|
|
99
|
+
continue;
|
|
100
|
+
}
|
|
101
|
+
if (text.startsWith(COMMENT_OPEN, i)) {
|
|
102
|
+
const close = text.indexOf(COMMENT_CLOSE, i + COMMENT_OPEN.length);
|
|
103
|
+
if (close !== -1) {
|
|
104
|
+
i = close + COMMENT_CLOSE.length;
|
|
105
|
+
continue;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
plain += text[i];
|
|
109
|
+
i++;
|
|
110
|
+
}
|
|
111
|
+
return out + dropImageMarkup(plain);
|
|
112
|
+
}
|
|
113
|
+
/** Strips one run of non-code lines and returns its lines. */
|
|
114
|
+
function visibleLines(run) {
|
|
115
|
+
return stripHiddenMarkup(run.join("\n"))
|
|
116
|
+
.split("\n")
|
|
117
|
+
.map((line) => line.trimEnd());
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* The visible text of a GitHub Markdown body, for Markdown output: closed HTML comments,
|
|
121
|
+
* `<picture>` image wrappers, and links left empty by them are dropped, because GitHub does not
|
|
122
|
+
* display them. Fenced and indented code and inline code spans are kept verbatim. Blank runs
|
|
123
|
+
* collapse to one; a body with no visible text is returned unchanged. JSON and `--verbose` keep
|
|
124
|
+
* the raw body.
|
|
125
|
+
*/
|
|
126
|
+
export function displayBody(body) {
|
|
127
|
+
const lines = body.replace(/\r\n?/g, "\n").split("\n");
|
|
128
|
+
const code = codeLines(lines);
|
|
129
|
+
const out = [];
|
|
130
|
+
const push = (line) => {
|
|
131
|
+
if (isBlank(line) && (out.length === 0 || isBlank(out[out.length - 1])))
|
|
132
|
+
return;
|
|
133
|
+
out.push(line);
|
|
134
|
+
};
|
|
135
|
+
let run = [];
|
|
136
|
+
const flush = () => {
|
|
137
|
+
if (run.length === 0)
|
|
138
|
+
return;
|
|
139
|
+
for (const line of visibleLines(run))
|
|
140
|
+
push(line);
|
|
141
|
+
run = [];
|
|
142
|
+
};
|
|
143
|
+
lines.forEach((line, i) => {
|
|
144
|
+
if (code[i]) {
|
|
145
|
+
flush();
|
|
146
|
+
out.push(line);
|
|
147
|
+
}
|
|
148
|
+
else {
|
|
149
|
+
run.push(line);
|
|
150
|
+
}
|
|
151
|
+
});
|
|
152
|
+
flush();
|
|
153
|
+
while (out.length > 0 && isBlank(out[out.length - 1]))
|
|
154
|
+
out.pop();
|
|
155
|
+
// A body with no visible text (only comments) stays raw rather than rendering as nothing.
|
|
156
|
+
return out.length > 0 ? out.join("\n") : body;
|
|
157
|
+
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { renderLineRange, renderSuggestionBlock } from "./suggestion-renderer.mjs";
|
|
2
2
|
import { threadComments } from "../threads/transcript.mjs";
|
|
3
3
|
import { truncateBody, BODY_TRUNCATE_MAX_CHARS, NESTED_BODY_TRUNCATE_MAX_CHARS, } from "./body-truncate.mjs";
|
|
4
|
+
import { displayBody } from "./display-body.mjs";
|
|
4
5
|
const BODY_PREVIEW_MAX = 100;
|
|
5
6
|
export function renderAuthor(author, authorType, authorAssociation, viewerDidAuthor) {
|
|
6
7
|
// `User` is the default author type; only `Bot` and `Unknown` are worth a label.
|
|
@@ -10,7 +11,7 @@ export function renderAuthor(author, authorType, authorAssociation, viewerDidAut
|
|
|
10
11
|
.join(" · ");
|
|
11
12
|
}
|
|
12
13
|
export function renderBodyPreview(body) {
|
|
13
|
-
const normalizedBody = body
|
|
14
|
+
const normalizedBody = displayBody(body);
|
|
14
15
|
const firstLine = normalizedBody.split("\n")[0]?.trim() ?? "";
|
|
15
16
|
return firstLine.slice(0, BODY_PREVIEW_MAX);
|
|
16
17
|
}
|
|
@@ -69,7 +70,8 @@ export function renderThreadConversation(t, verbose = false) {
|
|
|
69
70
|
.join("\n\n");
|
|
70
71
|
}
|
|
71
72
|
export function blockquote(body, maxChars, url) {
|
|
72
|
-
|
|
73
|
+
// Capped review bodies show only GitHub-visible text; uncapped (`--verbose`, annotations) stay raw.
|
|
74
|
+
const text = maxChars === undefined ? body : truncateBody(displayBody(body), maxChars, url);
|
|
73
75
|
return text
|
|
74
76
|
.replace(/\r\n/g, "\n")
|
|
75
77
|
.split("\n")
|
|
@@ -78,6 +78,10 @@ async function runIterateCore(opts, tick) {
|
|
|
78
78
|
reviewOutputMaxChars: config.iterate["review-output-max-chars"],
|
|
79
79
|
}, checkContext);
|
|
80
80
|
tick.report = report;
|
|
81
|
+
if (opts.eventTargetSink) {
|
|
82
|
+
opts.eventTargetSink.headSha = report.headSha;
|
|
83
|
+
opts.eventTargetSink.headRef = report.headRefName;
|
|
84
|
+
}
|
|
81
85
|
const [repoOwner, repoName] = report.repo.split("/");
|
|
82
86
|
if (!repoOwner || !repoName) {
|
|
83
87
|
throw new ShepherdError(`Unexpected repo format: "${report.repo}" (expected "owner/name")`, EXIT.DATAERR);
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import type { IterateResult, PollSummaryResult } from "../types.mts";
|
|
2
|
+
import type { WatchTarget } from "../events/types.mts";
|
|
3
|
+
interface WaitTickInput {
|
|
4
|
+
/** Progress prefix, e.g. `poll tick 3 / +45s`. */
|
|
5
|
+
label: string;
|
|
6
|
+
targets: readonly WatchTarget[];
|
|
7
|
+
sleepMs: number;
|
|
8
|
+
intervalMs: number;
|
|
9
|
+
tickStartedAt: number;
|
|
10
|
+
/** Time left in the poll window; `Infinity` for `--until-terminal`. */
|
|
11
|
+
remainingMs: number;
|
|
12
|
+
recheck: boolean;
|
|
13
|
+
/** Epoch ms of a time-based deadline that caps the healthy event wait. */
|
|
14
|
+
deadlineAt?: number;
|
|
15
|
+
/** Which timer `deadlineAt` belongs to: `stall-timeout`, `ready-delay`, or `CI-start`. */
|
|
16
|
+
deadlineReason?: string;
|
|
17
|
+
}
|
|
18
|
+
export interface PollEvents {
|
|
19
|
+
engaged(targets: readonly WatchTarget[]): boolean;
|
|
20
|
+
/** Wait for the next tick. Returns true when the poll window elapsed with no event. */
|
|
21
|
+
waitTick(input: WaitTickInput): Promise<boolean>;
|
|
22
|
+
close(): void;
|
|
23
|
+
}
|
|
24
|
+
/** Run a poll with its event wait (if configured), always closing the source afterwards. */
|
|
25
|
+
export declare function withPollEvents<T>(verbose: boolean, run: (events: PollEvents | undefined) => Promise<T>): Promise<T>;
|
|
26
|
+
export interface PauseInput extends WaitTickInput {
|
|
27
|
+
events: PollEvents | undefined;
|
|
28
|
+
/** `viaEvents` is true when the pause waits for an event rather than sleeping. */
|
|
29
|
+
announce: (viaEvents: boolean) => void;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Pause until the next tick, by event wait when engaged and by plain sleep otherwise. Returns
|
|
33
|
+
* true when the poll should stop: the window is over, or (without events) the next sleep would
|
|
34
|
+
* not fit in what is left. `announce` runs once the pause is certain, before it starts.
|
|
35
|
+
*/
|
|
36
|
+
export declare function pauseBeforeNextTick(input: PauseInput): Promise<boolean>;
|
|
37
|
+
/** The one PR a single-PR tick watched; head SHA and ref come from that tick's batch data. */
|
|
38
|
+
export declare function onePrTargets(result: Pick<IterateResult, "repo" | "pr" | "baseBranch">, head: {
|
|
39
|
+
headSha?: string;
|
|
40
|
+
headRef?: string;
|
|
41
|
+
}): WatchTarget[];
|
|
42
|
+
/** Every open PR of an aggregate tick. */
|
|
43
|
+
export declare function aggregateTargets(result: PollSummaryResult): WatchTarget[];
|
|
44
|
+
export {};
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import { loadConfig } from "../config/load.mjs";
|
|
2
|
+
import { resolveEventsSource } from "../events/config.mjs";
|
|
3
|
+
import { createRelayTransport, RELAY_REQUEST_TIMEOUT_MS } from "../events/relay.mjs";
|
|
4
|
+
import { createServeTransport } from "../events/serve.mjs";
|
|
5
|
+
import { createEventWaiter } from "../events/waiter.mjs";
|
|
6
|
+
import { githubFetch } from "../github/github-fetch.mjs";
|
|
7
|
+
import { appendEntry } from "../log/log-file.mjs";
|
|
8
|
+
import { sleep } from "../util/sleep.mjs";
|
|
9
|
+
const TIMER_DRIFT_TOLERANCE_MS = 500;
|
|
10
|
+
function describe(wake, degraded) {
|
|
11
|
+
if (wake.kind === "timer")
|
|
12
|
+
return degraded ? "timer (events unavailable)" : "fallback timer";
|
|
13
|
+
const { event, action, repo } = wake.event;
|
|
14
|
+
return `${action ? `${event}.${action}` : event} ${repo ?? ""}`.trim();
|
|
15
|
+
}
|
|
16
|
+
function createTransport(startMs) {
|
|
17
|
+
const source = resolveEventsSource();
|
|
18
|
+
return source.kind === "serve"
|
|
19
|
+
? createServeTransport(source, startMs, {
|
|
20
|
+
fetch: (input, init) => globalThis.fetch(input, init),
|
|
21
|
+
})
|
|
22
|
+
: createRelayTransport(source, startMs, {
|
|
23
|
+
fetch: (input, init) => githubFetch(input, init, RELAY_REQUEST_TIMEOUT_MS),
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* The event-driven wait for a poll loop, or `undefined` when `events.source` is `none`. Captures
|
|
28
|
+
* the start time now, before the first tick snapshots GitHub, so no event in between is missed.
|
|
29
|
+
* Throws a config error when hook-harness is selected but no source resolves.
|
|
30
|
+
*/
|
|
31
|
+
function createPollEvents(verbose) {
|
|
32
|
+
const config = loadConfig().events;
|
|
33
|
+
if (config.source === "none")
|
|
34
|
+
return undefined;
|
|
35
|
+
const note = (message) => {
|
|
36
|
+
if (verbose)
|
|
37
|
+
process.stderr.write(`${message}\n`);
|
|
38
|
+
appendEntry(`- ${message}\n`);
|
|
39
|
+
};
|
|
40
|
+
const waiter = createEventWaiter({
|
|
41
|
+
transport: createTransport(Date.now()),
|
|
42
|
+
fallbackMs: config["fallback-interval-seconds"] * 1000,
|
|
43
|
+
deps: { now: () => Date.now(), sleep },
|
|
44
|
+
note,
|
|
45
|
+
});
|
|
46
|
+
return {
|
|
47
|
+
engaged: (targets) => waiter.engaged(targets),
|
|
48
|
+
close: () => waiter.close(),
|
|
49
|
+
async waitTick(input) {
|
|
50
|
+
const waitStart = Date.now();
|
|
51
|
+
const { wake, degraded } = await waiter.wait({
|
|
52
|
+
targets: input.targets,
|
|
53
|
+
sleepMs: input.sleepMs,
|
|
54
|
+
windowMs: input.remainingMs,
|
|
55
|
+
recheck: input.recheck,
|
|
56
|
+
// Events never make ticks more frequent than plain polling would.
|
|
57
|
+
minGapMs: input.sleepMs,
|
|
58
|
+
tickStartedAt: input.tickStartedAt,
|
|
59
|
+
...(input.deadlineAt !== undefined && { deadlineAt: input.deadlineAt }),
|
|
60
|
+
});
|
|
61
|
+
const atDeadline = wake.kind === "timer" &&
|
|
62
|
+
!degraded &&
|
|
63
|
+
input.deadlineAt !== undefined &&
|
|
64
|
+
Date.now() + TIMER_DRIFT_TOLERANCE_MS >= input.deadlineAt;
|
|
65
|
+
note(`[${input.label}] woke on ${atDeadline ? `${input.deadlineReason ?? "time-based"} deadline` : describe(wake, degraded)}`);
|
|
66
|
+
return (wake.kind === "timer" &&
|
|
67
|
+
Date.now() - waitStart + TIMER_DRIFT_TOLERANCE_MS >= input.remainingMs);
|
|
68
|
+
},
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
/** Run a poll with its event wait (if configured), always closing the source afterwards. */
|
|
72
|
+
export async function withPollEvents(verbose, run) {
|
|
73
|
+
const events = createPollEvents(verbose);
|
|
74
|
+
try {
|
|
75
|
+
return await run(events);
|
|
76
|
+
}
|
|
77
|
+
finally {
|
|
78
|
+
events?.close();
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Pause until the next tick, by event wait when engaged and by plain sleep otherwise. Returns
|
|
83
|
+
* true when the poll should stop: the window is over, or (without events) the next sleep would
|
|
84
|
+
* not fit in what is left. `announce` runs once the pause is certain, before it starts.
|
|
85
|
+
*/
|
|
86
|
+
export async function pauseBeforeNextTick(input) {
|
|
87
|
+
const { events, announce, ...wait } = input;
|
|
88
|
+
const viaEvents = events?.engaged(wait.targets) === true;
|
|
89
|
+
const { remainingMs, sleepMs } = wait;
|
|
90
|
+
if (remainingMs <= 0 || (!viaEvents && remainingMs + TIMER_DRIFT_TOLERANCE_MS < sleepMs)) {
|
|
91
|
+
return true;
|
|
92
|
+
}
|
|
93
|
+
announce(viaEvents);
|
|
94
|
+
if (!events || !viaEvents) {
|
|
95
|
+
await sleep(sleepMs);
|
|
96
|
+
return false;
|
|
97
|
+
}
|
|
98
|
+
return events.waitTick(wait);
|
|
99
|
+
}
|
|
100
|
+
/** The one PR a single-PR tick watched; head SHA and ref come from that tick's batch data. */
|
|
101
|
+
export function onePrTargets(result, head) {
|
|
102
|
+
return [
|
|
103
|
+
{
|
|
104
|
+
repo: result.repo,
|
|
105
|
+
pr: result.pr,
|
|
106
|
+
baseRef: result.baseBranch,
|
|
107
|
+
...(head.headSha && { headSha: head.headSha }),
|
|
108
|
+
...(head.headRef && { headRef: head.headRef }),
|
|
109
|
+
},
|
|
110
|
+
];
|
|
111
|
+
}
|
|
112
|
+
/** Every open PR of an aggregate tick. */
|
|
113
|
+
export function aggregateTargets(result) {
|
|
114
|
+
return result.prs
|
|
115
|
+
.filter((item) => item.state === "OPEN")
|
|
116
|
+
.map((item) => ({
|
|
117
|
+
repo: item.repo,
|
|
118
|
+
pr: item.pr,
|
|
119
|
+
headSha: item.headRefOid,
|
|
120
|
+
headRef: item.headRefName,
|
|
121
|
+
baseRef: item.baseRefName,
|
|
122
|
+
}));
|
|
123
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { IterateCommandOptions } from "../types.mts";
|
|
2
|
+
export interface PollCommandOptions extends IterateCommandOptions {
|
|
3
|
+
intervalSeconds: number;
|
|
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
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -6,6 +6,8 @@ export declare function writeWaitProgress(opts: {
|
|
|
6
6
|
tick: number;
|
|
7
7
|
elapsedMs: number;
|
|
8
8
|
sleepMs: number;
|
|
9
|
+
/** The pause waits for a hook-harness event, so `sleepMs` is not its length. */
|
|
10
|
+
viaEvents?: boolean;
|
|
9
11
|
result: WaitResult;
|
|
10
12
|
quietStatus: boolean;
|
|
11
13
|
verbose: boolean;
|
|
@@ -23,7 +23,7 @@ function waitSignature(result) {
|
|
|
23
23
|
reviewItemsSinceLatestCommit: activity.reviewItemsSinceLatestCommit.length,
|
|
24
24
|
});
|
|
25
25
|
}
|
|
26
|
-
function writeQuietStatus(tick, elapsedSeconds, sleepSeconds, result) {
|
|
26
|
+
function writeQuietStatus(tick, elapsedSeconds, sleepSeconds, result, viaEvents) {
|
|
27
27
|
const activeChecks = result.inProgressChecks ?? [];
|
|
28
28
|
const activeCheckText = activeChecks.map((c) => `${c.name} (${c.status})`).join(", ");
|
|
29
29
|
const active = activeChecks.length > 0 ? ` · active: ${activeCheckText}` : "";
|
|
@@ -33,7 +33,7 @@ function writeQuietStatus(tick, elapsedSeconds, sleepSeconds, result) {
|
|
|
33
33
|
const commitSeg = commitCount > 0 ? ` · ${commitCount} commits` : "";
|
|
34
34
|
const reviewRoundSeg = reviewRounds > 0 ? ` · ${reviewRounds} review rounds` : "";
|
|
35
35
|
const reviewSeg = reviewItems > 0 ? ` · ${reviewItems} review items since latest commit` : "";
|
|
36
|
-
process.stderr.write(`[poll tick ${tick} / +${elapsedSeconds}s] WAIT ${result.status}/${result.mergeStateStatus}/${result.reviewDecision ?? "NO_REVIEW_DECISION"}${active}${commitSeg}${reviewRoundSeg}${reviewSeg} — sleeping ${sleepSeconds}s\n`);
|
|
36
|
+
process.stderr.write(`[poll tick ${tick} / +${elapsedSeconds}s] WAIT ${result.status}/${result.mergeStateStatus}/${result.reviewDecision ?? "NO_REVIEW_DECISION"}${active}${commitSeg}${reviewRoundSeg}${reviewSeg} — ${viaEvents ? "waiting for an event" : `sleeping ${sleepSeconds}s`}\n`);
|
|
37
37
|
}
|
|
38
38
|
export function writeWaitProgress(opts) {
|
|
39
39
|
const elapsedSeconds = Math.round(opts.elapsedMs / 1000);
|
|
@@ -41,12 +41,14 @@ export function writeWaitProgress(opts) {
|
|
|
41
41
|
if (!opts.quietStatus) {
|
|
42
42
|
const reason = waitReason(opts.result);
|
|
43
43
|
// The tick interval is the caller's own `--interval`; only verbose mode repeats it.
|
|
44
|
-
writeTickProgress(opts.tick, elapsedSeconds, opts.verbose
|
|
44
|
+
writeTickProgress(opts.tick, elapsedSeconds, opts.verbose
|
|
45
|
+
? `${reason} — ${opts.viaEvents ? "waiting for an event" : `sleeping ${sleepSeconds}s`}`
|
|
46
|
+
: reason);
|
|
45
47
|
return opts.lastWaitSignature;
|
|
46
48
|
}
|
|
47
49
|
const signature = waitSignature(opts.result);
|
|
48
50
|
if (signature !== opts.lastWaitSignature) {
|
|
49
|
-
writeQuietStatus(opts.tick, elapsedSeconds, sleepSeconds, opts.result);
|
|
51
|
+
writeQuietStatus(opts.tick, elapsedSeconds, sleepSeconds, opts.result, opts.viaEvents === true);
|
|
50
52
|
}
|
|
51
53
|
return signature;
|
|
52
54
|
}
|
|
@@ -7,6 +7,8 @@ export declare function quotaPollIntervalMs(bands: GraphqlQuotaWarningBand[], us
|
|
|
7
7
|
graphql?: Pick<GraphqlApiUsage, "remaining" | "limit">;
|
|
8
8
|
rest?: Pick<ApiResourceUsage, "resource" | "remaining" | "limit">[];
|
|
9
9
|
} | undefined, fallbackMs: number, maxMs: number, transport?: "graphql" | "rest"): number;
|
|
10
|
+
/** The plain poll sleep for a single-PR tick: the interval raised by any quota band. */
|
|
11
|
+
export declare function onePrSleepMs(bands: GraphqlQuotaWarningBand[], usage: Parameters<typeof quotaPollIntervalMs>[1], intervalMs: number, maxMs: number): number;
|
|
10
12
|
export interface RateLimitRetry {
|
|
11
13
|
ms: number;
|
|
12
14
|
resource: string;
|
|
@@ -25,6 +25,10 @@ export function quotaPollIntervalMs(bands, usage, fallbackMs, maxMs, transport)
|
|
|
25
25
|
const core = usage?.rest?.find((item) => item.resource === "core");
|
|
26
26
|
return Math.max(graphqlQuotaPollIntervalMs(bands, transport === "rest" ? undefined : usage?.graphql, fallbackMs, maxMs), graphqlQuotaPollIntervalMs(bands, core, fallbackMs, maxMs));
|
|
27
27
|
}
|
|
28
|
+
/** The plain poll sleep for a single-PR tick: the interval raised by any quota band. */
|
|
29
|
+
export function onePrSleepMs(bands, usage, intervalMs, maxMs) {
|
|
30
|
+
return quotaPollIntervalMs(bands, usage, intervalMs, maxMs, getGithubTransport());
|
|
31
|
+
}
|
|
28
32
|
/**
|
|
29
33
|
* Retry delay for `--until-terminal` when GitHub exhausts a primary quota or
|
|
30
34
|
* returns a secondary limit. `null` means the error is not a retryable rate limit.
|
|
@@ -5,6 +5,7 @@ export interface AggregatePollCommandOptions extends PollSummaryCommandOptions {
|
|
|
5
5
|
debounceSeconds?: number;
|
|
6
6
|
quietStatus?: boolean;
|
|
7
7
|
untilTerminal?: boolean;
|
|
8
|
+
verbose?: boolean;
|
|
8
9
|
}
|
|
9
10
|
export declare function runPollSummary(opts: PollSummaryCommandOptions): Promise<PollSummaryResult>;
|
|
10
11
|
export declare function runAggregatePoll(opts: AggregatePollCommandOptions): Promise<PollSummaryResult>;
|
|
@@ -7,15 +7,15 @@ import { withApiTelemetryScope, summarizeApiTelemetry } from "../github/api-tele
|
|
|
7
7
|
import { aggregateRerunCommand } from "../github/poll-summary-command.mjs";
|
|
8
8
|
import { fetchPollSummary } from "../github/poll-summary.mjs";
|
|
9
9
|
import { writeStackHandoffs } from "../github/stack-handoff.mjs";
|
|
10
|
-
import { sleep } from "../util/sleep.mjs";
|
|
11
10
|
import { aggregateQuotaWarning, carryQuotaWarning, quotaPollIntervalMs } from "./poll-quota.mjs";
|
|
12
11
|
import { aggregateCancelFromPulls, aggregateRateLimitTargets } from "./poll-rate-limit-cancel.mjs";
|
|
13
12
|
import { createUntilTerminalRateLimitRetry } from "./poll-rate-limit-wait.mjs";
|
|
14
13
|
import { planPollSummary, withPollSummaryInstructions } from "./poll-summary-instructions.mjs";
|
|
15
14
|
import { summaryStatusSignature } from "./poll-summary-signature.mjs";
|
|
16
15
|
import { applyStackStallGuard } from "./stack-stall.mjs";
|
|
16
|
+
import { aggregateDeadline } from "./stall-deadline.mjs";
|
|
17
|
+
import { aggregateTargets, pauseBeforeNextTick, withPollEvents, } from "./poll-events.mjs";
|
|
17
18
|
const MAX_TIMER_MS = 2 ** 31 - 1;
|
|
18
|
-
const TIMER_DRIFT_TOLERANCE_MS = 500;
|
|
19
19
|
export function runPollSummary(opts) {
|
|
20
20
|
return withApiTelemetryScope(async () => {
|
|
21
21
|
const tick = await readPollSummaryTick(opts);
|
|
@@ -24,7 +24,7 @@ export function runPollSummary(opts) {
|
|
|
24
24
|
});
|
|
25
25
|
}
|
|
26
26
|
export function runAggregatePoll(opts) {
|
|
27
|
-
return withApiTelemetryScope(() => runAggregatePollCore(opts));
|
|
27
|
+
return withPollEvents(opts.verbose === true, (events) => withApiTelemetryScope(() => runAggregatePollCore(opts, events)));
|
|
28
28
|
}
|
|
29
29
|
async function runPollSummaryCore(opts) {
|
|
30
30
|
return (await readPollSummaryTick(opts)).result;
|
|
@@ -65,7 +65,7 @@ async function readPollSummaryTick(opts) {
|
|
|
65
65
|
const result = await applyStackStallGuard(planned, repo, opts.stallTimeoutSeconds ?? loadConfig().iterate["stall-timeout-minutes"] * 60);
|
|
66
66
|
return { result, repo, ...(fetched.handoffSource && { handoffSource: fetched.handoffSource }) };
|
|
67
67
|
}
|
|
68
|
-
async function runAggregatePollCore(opts) {
|
|
68
|
+
async function runAggregatePollCore(opts, events) {
|
|
69
69
|
const intervalMs = Math.min(opts.intervalSeconds * 1000, MAX_TIMER_MS);
|
|
70
70
|
const timeoutMs = Math.min(opts.timeoutSeconds * 1000, MAX_TIMER_MS);
|
|
71
71
|
const debounceMs = Math.min((opts.debounceSeconds ?? 60) * 1000, MAX_TIMER_MS);
|
|
@@ -80,6 +80,7 @@ async function runAggregatePollCore(opts) {
|
|
|
80
80
|
let pendingQuotaWarning;
|
|
81
81
|
while (true) {
|
|
82
82
|
tick += 1;
|
|
83
|
+
const tickStartedAt = Date.now();
|
|
83
84
|
try {
|
|
84
85
|
lastTick = await readPollSummaryTick(opts);
|
|
85
86
|
last = lastTick.result;
|
|
@@ -178,20 +179,31 @@ async function runAggregatePollCore(opts) {
|
|
|
178
179
|
const sleepMs = debounceUntil
|
|
179
180
|
? Math.min(intervalMs, Math.max(debounceUntil - Date.now(), 0))
|
|
180
181
|
: quotaPollIntervalMs(quotaBands, summarizeApiTelemetry(), intervalMs, MAX_TIMER_MS, getGithubTransport());
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
182
|
+
const useEvents = debounceUntil ? undefined : events;
|
|
183
|
+
const deadline = useEvents && (await aggregateDeadline(last, opts.stallTimeoutSeconds));
|
|
184
|
+
const stop = await pauseBeforeNextTick({
|
|
185
|
+
// The settle window after a first TRIAGE is a plain timer, never an event wait.
|
|
186
|
+
events: useEvents,
|
|
187
|
+
...deadline,
|
|
188
|
+
targets: aggregateTargets(last),
|
|
189
|
+
recheck: last.prs.some((item) => item.mergeStateStatus === "UNKNOWN"),
|
|
190
|
+
sleepMs,
|
|
191
|
+
intervalMs,
|
|
192
|
+
label: `aggregate poll tick ${tick} / +${Math.round(elapsedMs / 1000)}s`,
|
|
193
|
+
tickStartedAt,
|
|
194
|
+
remainingMs: opts.untilTerminal || debounceUntil !== null ? Infinity : timeoutMs - elapsedMs,
|
|
195
|
+
announce: () => {
|
|
196
|
+
const statusSignature = summaryStatusSignature(last);
|
|
197
|
+
if (!opts.quietStatus || hasFix || statusSignature !== lastStatusSignature) {
|
|
198
|
+
process.stderr.write(`[aggregate poll tick ${tick} / +${Math.round(elapsedMs / 1000)}s] ${last.prs
|
|
199
|
+
.map((item) => `#${item.pr} ${item.action.toUpperCase()}`)
|
|
200
|
+
.join(", ")}\n`);
|
|
201
|
+
}
|
|
202
|
+
lastStatusSignature = statusSignature;
|
|
203
|
+
},
|
|
204
|
+
});
|
|
205
|
+
if (stop)
|
|
206
|
+
return attachUsage({ ...last, reason: "timeout" }, opts);
|
|
195
207
|
}
|
|
196
208
|
}
|
|
197
209
|
/** An auto-resolve is a one-tick event; forward it so a swallowed tick still records it. */
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { IterateResult } from "../types.mts";
|
|
2
|
+
import type { RateLimitProbePull, RateLimitPullTarget } from "./poll-rate-limit-cancel.mts";
|
|
3
|
+
import type { createUntilTerminalRateLimitRetry } from "./poll-rate-limit-wait.mts";
|
|
4
|
+
export interface TickRunnerInput {
|
|
5
|
+
/** One iterate read; `fingerprintCache` allows reuse of a previous WAIT-shaped report. */
|
|
6
|
+
run: (fingerprintCache: boolean) => Promise<IterateResult>;
|
|
7
|
+
retry: ReturnType<typeof createUntilTerminalRateLimitRetry>;
|
|
8
|
+
untilTerminal: boolean;
|
|
9
|
+
intervalMs: number;
|
|
10
|
+
tickLabel: string;
|
|
11
|
+
startedAt: number;
|
|
12
|
+
/** Read lazily: the last result can change between a tick and its retry. */
|
|
13
|
+
targets: () => RateLimitPullTarget[];
|
|
14
|
+
onAllTerminal: (pulls: RateLimitProbePull[]) => IterateResult | undefined;
|
|
15
|
+
}
|
|
16
|
+
/** One poll tick that waits out GitHub rate limits instead of failing. */
|
|
17
|
+
export declare function createTickRunner(input: TickRunnerInput): (fingerprintCache: boolean) => Promise<IterateResult>;
|