pr-shepherd 1.2.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/.claude-plugin/plugin.json +24 -2
  2. package/README.md +1 -0
  3. package/bin/api.mjs +4 -1
  4. package/bin/cli/api-usage-formatter.mjs +18 -8
  5. package/bin/cli-parser.mjs +5 -2
  6. package/bin/github/api-telemetry-adopt.d.mts +4 -0
  7. package/bin/github/api-telemetry-adopt.mjs +52 -0
  8. package/bin/github/api-telemetry-aggregate.d.mts +6 -2
  9. package/bin/github/api-telemetry-aggregate.mjs +19 -52
  10. package/bin/github/api-telemetry-summary.d.mts +4 -0
  11. package/bin/github/api-telemetry-summary.mjs +63 -0
  12. package/bin/github/api-telemetry.d.mts +2 -0
  13. package/bin/github/api-telemetry.mjs +2 -43
  14. package/bin/github/app-eligibility.d.mts +9 -0
  15. package/bin/github/app-eligibility.mjs +21 -0
  16. package/bin/github/app-quota.d.mts +10 -0
  17. package/bin/github/app-quota.mjs +44 -0
  18. package/bin/github/auth-target.d.mts +16 -0
  19. package/bin/github/auth-target.mjs +29 -0
  20. package/bin/github/client.mjs +4 -2
  21. package/bin/github/github-app-config.d.mts +12 -0
  22. package/bin/github/github-app-config.mjs +102 -0
  23. package/bin/github/github-app-token.d.mts +13 -0
  24. package/bin/github/github-app-token.mjs +107 -0
  25. package/bin/github/graphql-http.mjs +18 -2
  26. package/bin/github/http-auth.d.mts +15 -2
  27. package/bin/github/http-auth.mjs +35 -4
  28. package/bin/github/http-intermediate.d.mts +1 -0
  29. package/bin/github/http-intermediate.mjs +1 -0
  30. package/bin/github/rest-http.mjs +19 -2
  31. package/bin/github/rest-text.mjs +22 -3
  32. package/bin/pr-reference.mjs +3 -0
  33. package/bin/types/api-usage.d.mts +14 -0
  34. package/package.json +1 -1
  35. package/plugins/pr-shepherd/.claude-plugin/plugin.json +10 -2
  36. package/plugins/pr-shepherd/.codex-plugin/plugin.json +1 -1
  37. package/plugins/pr-shepherd/.codex.mcp.json +1 -1
  38. package/plugins/pr-shepherd/.mcp.json +1 -1
  39. package/plugins/pr-shepherd/hooks/hooks.json +16 -0
  40. package/plugins/pr-shepherd/hooks/poll-guard-detect.d.mts +11 -0
  41. package/plugins/pr-shepherd/hooks/poll-guard-detect.mjs +84 -0
  42. package/plugins/pr-shepherd/hooks/poll-guard.d.mts +15 -0
  43. package/plugins/pr-shepherd/hooks/poll-guard.mjs +76 -0
  44. package/plugins/pr-shepherd/package-lock.json +4 -4
  45. package/plugins/pr-shepherd/package.json +1 -1
  46. package/plugins/pr-shepherd/skills/pr-shepherd/SKILL.md +6 -4
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "pr-shepherd",
3
3
  "description": "Autonomous PR CI monitor and review-comment resolver for agentic coding tools",
4
- "version": "1.2.0",
4
+ "version": "1.4.0",
5
5
  "author": {
6
6
  "name": "Jonathan Ong",
7
7
  "email": "jonathanrichardong@gmail.com"
@@ -11,5 +11,27 @@
11
11
  "license": "MIT",
12
12
  "keywords": ["github", "pull-request", "ci", "code-review", "automation"],
13
13
  "skills": "./plugins/pr-shepherd/skills/",
14
- "mcpServers": "./plugins/pr-shepherd/.mcp.json"
14
+ "mcpServers": "./plugins/pr-shepherd/.mcp.json",
15
+ "hooks": {
16
+ "PreToolUse": [
17
+ {
18
+ "matcher": "Bash|Monitor",
19
+ "hooks": [
20
+ {
21
+ "type": "command",
22
+ "command": "node \"${CLAUDE_PLUGIN_ROOT}/plugins/pr-shepherd/hooks/poll-guard.mjs\"",
23
+ "timeout": 10
24
+ }
25
+ ]
26
+ }
27
+ ]
28
+ },
29
+ "userConfig": {
30
+ "poll_guard": {
31
+ "type": "string",
32
+ "title": "Poll guard",
33
+ "description": "What to do when a shell command polls GitHub PR or CI state instead of running pr-shepherd: disabled, advisory (run it and tell the agent), or fail (block it). The PR_SHEPHERD_POLL_GUARD environment variable overrides this.",
34
+ "default": "advisory"
35
+ }
36
+ }
15
37
  }
package/README.md CHANGED
@@ -209,6 +209,7 @@ Leave out the PR number to use the current branch.
209
209
  | Index of every doc | [docs/README.md](docs/README.md) |
210
210
  | Features, workflow assumptions, limits | [docs/features.md](docs/features.md) |
211
211
  | Commands, flags, stacks, polling | [docs/cli-usage.md](docs/cli-usage.md) |
212
+ | GitHub App auth (separate rate limit) | [docs/github-app.md](docs/github-app.md) |
212
213
  | Actions and exit codes | [docs/actions.md](docs/actions.md), [docs/exit-codes.md](docs/exit-codes.md) |
213
214
  | Configuration and classification rules | [docs/configuration.md](docs/configuration.md), [examples/classification/](examples/classification/) |
214
215
  | Journal, library API | [docs/api.md](docs/api.md) |
package/bin/api.mjs CHANGED
@@ -14,7 +14,9 @@ import { applyQueueRemovalAck, } from "./commands/apply-queue-removal.mjs";
14
14
  import { runWithExecutionCwd } from "./execution-context.mjs";
15
15
  import { loadConfig } from "./config/load.mjs";
16
16
  import { parsePrReference, normalizeRepositoryIdentity, resolveParsedPrTarget, } from "./pr-reference.mjs";
17
+ import { runWithAuthScope } from "./github/auth-target.mjs";
17
18
  import { getPullRequestBody, getRepoInfo } from "./github/client.mjs";
19
+ import { loadGithubApps } from "./github/github-app-config.mjs";
18
20
  import { getLocalHeadSha } from "./commands/suggestion-patch-git.mjs";
19
21
  import { extractShepherdJournal } from "./journal/index.mjs";
20
22
  /** Raised before any API mutation when an input cannot be validated. */
@@ -47,7 +49,8 @@ export function createPrShepherd(options = {}) {
47
49
  // Validate config first, as the CLI does, so a bad or pre-v1 file rejects before GitHub I/O.
48
50
  return runWithExecutionCwd(cwd, async () => {
49
51
  loadConfig();
50
- return transportRunner(work, input?.transport);
52
+ loadGithubApps();
53
+ return runWithAuthScope(() => transportRunner(work, input?.transport));
51
54
  });
52
55
  }
53
56
  function iterate(input = {}) {
@@ -37,19 +37,29 @@ function recommendation(warning) {
37
37
  }
38
38
  return "- Recommendation: keep polling pr-shepherd at the cadence above; for incidental PR reads use explicit REST endpoints such as `gh api repos/OWNER/REPO/pulls/PR`; do not substitute `gh pr checks` or `gh pr watch`";
39
39
  }
40
+ function formatChain(chain, indent) {
41
+ const lines = [];
42
+ if (chain.graphql !== undefined) {
43
+ lines.push(formatResource(chain.graphql));
44
+ lines.push(`- GraphQL measured cost: ${chain.graphql.measuredQueryCost} · unmeasured requests: ${chain.graphql.unmeasuredRequestCount} · nodes: ${chain.graphql.nodeCount}`);
45
+ }
46
+ for (const resource of chain.rest ?? [])
47
+ lines.push(formatResource(resource));
48
+ if (chain.unmeteredRestRequestCount !== undefined) {
49
+ lines.push(`- REST requests without rate-limit headers (unmetered): ${chain.unmeteredRestRequestCount}`);
50
+ }
51
+ return lines.map((line) => `${indent}${line}`);
52
+ }
40
53
  export function formatApiUsage(usage) {
41
54
  if (usage === undefined)
42
55
  return null;
43
56
  const lines = ["## GitHub API usage", ""];
44
- lines.push(`- Credential source: ${usage.credentialSources.map((source) => `\`${source}\``).join(", ")}`);
45
- if (usage.graphql !== undefined) {
46
- lines.push(formatResource(usage.graphql));
47
- lines.push(`- GraphQL measured cost: ${usage.graphql.measuredQueryCost} · unmeasured requests: ${usage.graphql.unmeasuredRequestCount} · nodes: ${usage.graphql.nodeCount}`);
57
+ if (usage.credentialSources.length > 0) {
58
+ lines.push(`- Credential source: ${usage.credentialSources.map((source) => `\`${source}\``).join(", ")}`);
48
59
  }
49
- for (const resource of usage.rest ?? [])
50
- lines.push(formatResource(resource));
51
- if (usage.unmeteredRestRequestCount !== undefined) {
52
- lines.push(`- REST requests without rate-limit headers (unmetered): ${usage.unmeteredRestRequestCount}`);
60
+ lines.push(...formatChain(usage, ""));
61
+ for (const app of usage.githubApps ?? []) {
62
+ lines.push(`- \`${app.source}\`:`, ...formatChain(app, " "));
53
63
  }
54
64
  return lines.join("\n");
55
65
  }
@@ -24,6 +24,8 @@ import { handleApplyMerge } from "./cli/apply-merge-handler.mjs";
24
24
  import { getLocalHeadSha } from "./commands/suggestion-patch-git.mjs";
25
25
  import { extractTransportArgs } from "./cli/transport-args.mjs";
26
26
  import { parseGithubTransport } from "./github/transport-mode.mjs";
27
+ import { runWithAuthScope } from "./github/auth-target.mjs";
28
+ import { loadGithubApps } from "./github/github-app-config.mjs";
27
29
  import { runWithGithubTransport } from "./github/transport.mjs";
28
30
  // ---------------------------------------------------------------------------
29
31
  // Entry
@@ -53,6 +55,7 @@ export async function main(argv) {
53
55
  // Validate config before any GitHub work, so a bad or pre-v1 config file exits 78 up front.
54
56
  try {
55
57
  loadConfig();
58
+ loadGithubApps();
56
59
  }
57
60
  catch (error) {
58
61
  if (!(error instanceof ShepherdError))
@@ -61,9 +64,9 @@ export async function main(argv) {
61
64
  process.exitCode = error.exitCode;
62
65
  return;
63
66
  }
64
- return runWithGithubTransport(mode, () => dispatch(dispatched), {
67
+ return runWithAuthScope(() => runWithGithubTransport(mode, () => dispatch(dispatched), {
65
68
  verbose: extracted.args.includes("--verbose"),
66
- });
69
+ }));
67
70
  }
68
71
  async function dispatch(argv) {
69
72
  const args = argv.slice(2); // strip node + script path
@@ -0,0 +1,4 @@
1
+ import type { RateLimitInfo } from "./http-utils.mts";
2
+ import type { RestTelemetryGroup, TelemetryAggregate } from "./api-telemetry-aggregate.mts";
3
+ export declare function adoptGraphqlRateLimit(graphql: TelemetryAggregate["graphql"], candidate: RateLimitInfo, fingerprint: string | undefined): void;
4
+ export declare function adoptRestRateLimit(group: RestTelemetryGroup, candidate: RateLimitInfo, fingerprint: string | undefined, sequence: number | undefined, latestCredentialFingerprint?: string | undefined, latestCredentialSequence?: number | undefined): void;
@@ -0,0 +1,52 @@
1
+ import { mostConservativeSample } from "./rate-limit-sample.mjs";
2
+ export function adoptGraphqlRateLimit(graphql, candidate, fingerprint) {
3
+ // Two credentials' samples are compared whole, never mixed: a mixed sample would be
4
+ // attributed to whichever credential supplied the changed half.
5
+ const sameCredential = fingerprint === undefined ||
6
+ graphql.credentialFingerprint === undefined ||
7
+ fingerprint === graphql.credentialFingerprint;
8
+ const next = selectAuthoritativeRateLimit(graphql.rateLimit, candidate, sameCredential);
9
+ if (next !== graphql.rateLimit)
10
+ graphql.credentialFingerprint = fingerprint;
11
+ graphql.rateLimit = next;
12
+ }
13
+ export function adoptRestRateLimit(group, candidate, fingerprint, sequence, latestCredentialFingerprint = fingerprint, latestCredentialSequence = sequence) {
14
+ const credentialChanged = group.latestCredentialFingerprint !== undefined &&
15
+ latestCredentialFingerprint !== undefined &&
16
+ group.latestCredentialFingerprint !== latestCredentialFingerprint;
17
+ const olderCredentialObservation = credentialChanged &&
18
+ group.latestCredentialSequence !== undefined &&
19
+ latestCredentialSequence !== undefined &&
20
+ latestCredentialSequence < group.latestCredentialSequence;
21
+ if (olderCredentialObservation)
22
+ return;
23
+ if (group.rateLimit === undefined || credentialChanged) {
24
+ group.rateLimit = { ...candidate };
25
+ group.credentialFingerprint = fingerprint;
26
+ }
27
+ else {
28
+ const next = selectAuthoritativeRateLimit(group.rateLimit, candidate);
29
+ if (next !== group.rateLimit) {
30
+ group.rateLimit = next;
31
+ group.credentialFingerprint = fingerprint;
32
+ }
33
+ }
34
+ if (latestCredentialFingerprint !== undefined &&
35
+ (group.latestCredentialSequence === undefined ||
36
+ latestCredentialSequence === undefined ||
37
+ latestCredentialSequence >= group.latestCredentialSequence)) {
38
+ group.latestCredentialFingerprint = latestCredentialFingerprint;
39
+ group.latestCredentialSequence = latestCredentialSequence;
40
+ }
41
+ }
42
+ function selectAuthoritativeRateLimit(current, candidate, sameCredential = true) {
43
+ if (current === undefined)
44
+ return { ...candidate };
45
+ if (candidate.resetAt !== current.resetAt) {
46
+ return candidate.resetAt > current.resetAt ? { ...candidate } : current;
47
+ }
48
+ if (!sameCredential)
49
+ return candidate.remaining < current.remaining ? { ...candidate } : current;
50
+ const merged = mostConservativeSample(current, candidate);
51
+ return merged.remaining === current.remaining && merged.used === current.used ? current : merged;
52
+ }
@@ -1,6 +1,6 @@
1
1
  import type { ApiTelemetryEvent } from "./api-telemetry.mts";
2
2
  import type { RateLimitInfo } from "./http-utils.mts";
3
- interface RestTelemetryGroup {
3
+ export interface RestTelemetryGroup {
4
4
  /** Quota-consuming requests; 304 Not Modified responses are tallied separately. */
5
5
  requestCount: number;
6
6
  notModifiedCount: number;
@@ -25,6 +25,11 @@ export interface TelemetryAggregate {
25
25
  rest: Map<string, RestTelemetryGroup>;
26
26
  /** Headerless REST responses (not 304s), kept out of every resource group: the proxy's `ccr` routes. */
27
27
  unmeteredRestRequestCount: number;
28
+ /**
29
+ * GitHub App installation requests, kept apart so the fields above describe only the user's
30
+ * token chain. Keyed by installation source; each value's own `apps` is empty.
31
+ */
32
+ apps: Map<string, TelemetryAggregate>;
28
33
  }
29
34
  export interface SequencedApiTelemetryEvent extends ApiTelemetryEvent {
30
35
  sequence: number;
@@ -41,4 +46,3 @@ export declare function emptyAggregate(): TelemetryAggregate;
41
46
  export declare function aggregateEvents(events: SequencedApiTelemetryEvent[]): TelemetryAggregate;
42
47
  export declare function mergeAggregate(target: TelemetryAggregate, source: TelemetryAggregate): void;
43
48
  export declare function aggregateStore(active: TelemetryStore): TelemetryAggregate;
44
- export {};
@@ -1,4 +1,4 @@
1
- import { mostConservativeSample } from "./rate-limit-sample.mjs";
1
+ import { adoptGraphqlRateLimit, adoptRestRateLimit } from "./api-telemetry-adopt.mjs";
2
2
  export function emptyAggregate() {
3
3
  return {
4
4
  eventCount: 0,
@@ -6,12 +6,20 @@ export function emptyAggregate() {
6
6
  graphql: { requestCount: 0, measuredQueryCost: 0, unmeasuredRequestCount: 0, nodeCount: 0 },
7
7
  rest: new Map(),
8
8
  unmeteredRestRequestCount: 0,
9
+ apps: new Map(),
9
10
  };
10
11
  }
11
12
  export function aggregateEvents(events) {
12
13
  const aggregate = emptyAggregate();
14
+ const appEvents = new Map();
13
15
  for (const event of events) {
14
16
  aggregate.eventCount += 1;
17
+ if (event.githubApp) {
18
+ const group = appEvents.get(event.authSource) ?? [];
19
+ group.push(event);
20
+ appEvents.set(event.authSource, group);
21
+ continue;
22
+ }
15
23
  if (!aggregate.credentialSources.has(event.authSource)) {
16
24
  aggregate.credentialSources.set(event.authSource, event.sequence);
17
25
  }
@@ -42,6 +50,11 @@ export function aggregateEvents(events) {
42
50
  adoptRestRateLimit(group, sample, event.credentialFingerprint, event.sequence);
43
51
  aggregate.rest.set(resource, group);
44
52
  }
53
+ for (const [source, group] of appEvents) {
54
+ // Re-aggregate as a plain chain: clearing the flag keeps the nested pass from splitting again.
55
+ const chain = group.map((event) => ({ ...event, githubApp: false }));
56
+ aggregate.apps.set(source, aggregateEvents(chain));
57
+ }
45
58
  return aggregate;
46
59
  }
47
60
  export function mergeAggregate(target, source) {
@@ -57,6 +70,11 @@ export function mergeAggregate(target, source) {
57
70
  target.graphql.unmeasuredRequestCount += source.graphql.unmeasuredRequestCount;
58
71
  target.graphql.nodeCount += source.graphql.nodeCount;
59
72
  target.unmeteredRestRequestCount += source.unmeteredRestRequestCount;
73
+ for (const [appSource, sourceApp] of source.apps) {
74
+ const targetApp = target.apps.get(appSource) ?? emptyAggregate();
75
+ mergeAggregate(targetApp, sourceApp);
76
+ target.apps.set(appSource, targetApp);
77
+ }
60
78
  if (source.graphql.rateLimit !== undefined) {
61
79
  adoptGraphqlRateLimit(target.graphql, source.graphql.rateLimit, source.graphql.credentialFingerprint);
62
80
  }
@@ -76,54 +94,3 @@ export function aggregateStore(active) {
76
94
  mergeAggregate(all, aggregateEvents(active.events));
77
95
  return all;
78
96
  }
79
- function adoptGraphqlRateLimit(graphql, candidate, fingerprint) {
80
- // Two credentials' samples are compared whole, never mixed: a mixed sample would be
81
- // attributed to whichever credential supplied the changed half.
82
- const sameCredential = fingerprint === undefined ||
83
- graphql.credentialFingerprint === undefined ||
84
- fingerprint === graphql.credentialFingerprint;
85
- const next = selectAuthoritativeRateLimit(graphql.rateLimit, candidate, sameCredential);
86
- if (next !== graphql.rateLimit)
87
- graphql.credentialFingerprint = fingerprint;
88
- graphql.rateLimit = next;
89
- }
90
- function adoptRestRateLimit(group, candidate, fingerprint, sequence, latestCredentialFingerprint = fingerprint, latestCredentialSequence = sequence) {
91
- const credentialChanged = group.latestCredentialFingerprint !== undefined &&
92
- latestCredentialFingerprint !== undefined &&
93
- group.latestCredentialFingerprint !== latestCredentialFingerprint;
94
- const olderCredentialObservation = credentialChanged &&
95
- group.latestCredentialSequence !== undefined &&
96
- latestCredentialSequence !== undefined &&
97
- latestCredentialSequence < group.latestCredentialSequence;
98
- if (olderCredentialObservation)
99
- return;
100
- if (group.rateLimit === undefined || credentialChanged) {
101
- group.rateLimit = { ...candidate };
102
- group.credentialFingerprint = fingerprint;
103
- }
104
- else {
105
- const next = selectAuthoritativeRateLimit(group.rateLimit, candidate);
106
- if (next !== group.rateLimit) {
107
- group.rateLimit = next;
108
- group.credentialFingerprint = fingerprint;
109
- }
110
- }
111
- if (latestCredentialFingerprint !== undefined &&
112
- (group.latestCredentialSequence === undefined ||
113
- latestCredentialSequence === undefined ||
114
- latestCredentialSequence >= group.latestCredentialSequence)) {
115
- group.latestCredentialFingerprint = latestCredentialFingerprint;
116
- group.latestCredentialSequence = latestCredentialSequence;
117
- }
118
- }
119
- function selectAuthoritativeRateLimit(current, candidate, sameCredential = true) {
120
- if (current === undefined)
121
- return { ...candidate };
122
- if (candidate.resetAt !== current.resetAt) {
123
- return candidate.resetAt > current.resetAt ? { ...candidate } : current;
124
- }
125
- if (!sameCredential)
126
- return candidate.remaining < current.remaining ? { ...candidate } : current;
127
- const merged = mostConservativeSample(current, candidate);
128
- return merged.remaining === current.remaining && merged.used === current.used ? current : merged;
129
- }
@@ -0,0 +1,4 @@
1
+ import type { ApiUsage } from "../types.mts";
2
+ import type { TelemetryAggregate } from "./api-telemetry-aggregate.mts";
3
+ /** Top level covers the user's token chain only; each GitHub App installation is its own entry. */
4
+ export declare function summarizeAggregate(selected: TelemetryAggregate): ApiUsage | undefined;
@@ -0,0 +1,63 @@
1
+ function orderedSources(selected) {
2
+ return [...selected.credentialSources.entries()]
3
+ .sort((left, right) => left[1] - right[1])
4
+ .map(([source]) => source);
5
+ }
6
+ /** Usage of one credential chain: per-resource counts, costs, nodes and quota sample. */
7
+ function summarizeChain(selected) {
8
+ const graphql = summarizeGraphql(selected.graphql);
9
+ const rest = summarizeRest(selected.rest);
10
+ const unmeteredRestRequestCount = selected.unmeteredRestRequestCount;
11
+ return {
12
+ ...(graphql !== undefined && { graphql }),
13
+ ...(rest.length > 0 && { rest }),
14
+ ...(unmeteredRestRequestCount > 0 && { unmeteredRestRequestCount }),
15
+ };
16
+ }
17
+ /** Top level covers the user's token chain only; each GitHub App installation is its own entry. */
18
+ export function summarizeAggregate(selected) {
19
+ if (selected.eventCount === 0)
20
+ return undefined;
21
+ const githubApps = [...selected.apps.values()]
22
+ .map((app) => ({ app, first: Math.min(...app.credentialSources.values()) }))
23
+ .sort((left, right) => left.first - right.first)
24
+ .map(({ app }) => {
25
+ const { graphql, rest } = summarizeChain(app);
26
+ return {
27
+ source: orderedSources(app)[0],
28
+ ...(graphql !== undefined && { graphql }),
29
+ ...(rest !== undefined && { rest }),
30
+ };
31
+ });
32
+ return {
33
+ credentialSources: orderedSources(selected),
34
+ ...summarizeChain(selected),
35
+ ...(githubApps.length > 0 && { githubApps }),
36
+ };
37
+ }
38
+ function summarizeGraphql(selected) {
39
+ if (selected.rateLimit === undefined)
40
+ return undefined;
41
+ return {
42
+ ...resourceUsage(selected.rateLimit, selected.requestCount, "graphql"),
43
+ measuredQueryCost: selected.measuredQueryCost,
44
+ unmeasuredRequestCount: selected.unmeasuredRequestCount,
45
+ nodeCount: selected.nodeCount,
46
+ };
47
+ }
48
+ function summarizeRest(selected) {
49
+ return [...selected.entries()].flatMap(([resource, group]) => group.rateLimit
50
+ ? [resourceUsage(group.rateLimit, group.requestCount, resource, group.notModifiedCount)]
51
+ : []);
52
+ }
53
+ function resourceUsage(rateLimit, requestCount, fallbackResource, notModified = 0) {
54
+ return {
55
+ resource: rateLimit.resource ?? fallbackResource,
56
+ ...(requestCount > 0 && { requestCount }),
57
+ ...(notModified > 0 && { notModified }),
58
+ limit: rateLimit.limit,
59
+ ...(rateLimit.used !== undefined && { used: rateLimit.used }),
60
+ remaining: rateLimit.remaining,
61
+ resetAt: rateLimit.resetAt,
62
+ };
63
+ }
@@ -4,6 +4,8 @@ export interface ApiTelemetryEvent {
4
4
  kind: "GraphQL" | "REST";
5
5
  method: string;
6
6
  authSource: string;
7
+ /** True when a GitHub App installation token answered this request, not the user's chain. */
8
+ githubApp: boolean;
7
9
  /** Truncated SHA-256 of the credential that produced this request. */
8
10
  credentialFingerprint?: string;
9
11
  rateLimit?: RateLimitInfo;
@@ -1,5 +1,6 @@
1
1
  import { AsyncLocalStorage } from "node:async_hooks";
2
2
  import { aggregateEvents, aggregateStore, emptyAggregate, mergeAggregate, } from "./api-telemetry-aggregate.mjs";
3
+ import { summarizeAggregate } from "./api-telemetry-summary.mjs";
3
4
  const GRAPHQL_RATE_LIMIT_ALIAS = "_shepherdRateLimit";
4
5
  const eventStorage = new AsyncLocalStorage();
5
6
  function store() {
@@ -91,49 +92,7 @@ export function withRestCoreCredentialFingerprint(sample) {
91
92
  }
92
93
  export function summarizeApiTelemetry() {
93
94
  const active = store();
94
- if (active === undefined)
95
- return undefined;
96
- const selected = aggregateStore(active);
97
- if (selected.eventCount === 0)
98
- return undefined;
99
- const credentialSources = [...selected.credentialSources.entries()]
100
- .sort((left, right) => left[1] - right[1])
101
- .map(([source]) => source);
102
- const graphql = summarizeGraphql(selected.graphql);
103
- const rest = summarizeRest(selected.rest);
104
- const unmeteredRestRequestCount = selected.unmeteredRestRequestCount;
105
- return {
106
- credentialSources,
107
- ...(graphql !== undefined && { graphql }),
108
- ...(rest.length > 0 && { rest }),
109
- ...(unmeteredRestRequestCount > 0 && { unmeteredRestRequestCount }),
110
- };
111
- }
112
- function summarizeGraphql(selected) {
113
- if (selected.rateLimit === undefined)
114
- return undefined;
115
- return {
116
- ...resourceUsage(selected.rateLimit, selected.requestCount, "graphql"),
117
- measuredQueryCost: selected.measuredQueryCost,
118
- unmeasuredRequestCount: selected.unmeasuredRequestCount,
119
- nodeCount: selected.nodeCount,
120
- };
121
- }
122
- function summarizeRest(selected) {
123
- return [...selected.entries()].flatMap(([resource, group]) => group.rateLimit
124
- ? [resourceUsage(group.rateLimit, group.requestCount, resource, group.notModifiedCount)]
125
- : []);
126
- }
127
- function resourceUsage(rateLimit, requestCount, fallbackResource, notModified = 0) {
128
- return {
129
- resource: rateLimit.resource ?? fallbackResource,
130
- ...(requestCount > 0 && { requestCount }),
131
- ...(notModified > 0 && { notModified }),
132
- limit: rateLimit.limit,
133
- ...(rateLimit.used !== undefined && { used: rateLimit.used }),
134
- remaining: rateLimit.remaining,
135
- resetAt: rateLimit.resetAt,
136
- };
95
+ return active === undefined ? undefined : summarizeAggregate(aggregateStore(active));
137
96
  }
138
97
  function extractGraphqlRateLimit(data) {
139
98
  if (data === null || typeof data !== "object" || Array.isArray(data))
@@ -0,0 +1,9 @@
1
+ /**
2
+ * The app answers only requests whose answer does not depend on who asks. Everything else
3
+ * (writes, `/user`, viewer fields) stays on the user's token, so identity semantics are the same
4
+ * as running without the app.
5
+ */
6
+ /** A GET or HEAD of a repository route. Caller-relative routes (`/user`, `/rate_limit`) are not. */
7
+ export declare function isAppEligibleRest(method: string, path: string): boolean;
8
+ /** A query that selects no viewer-relative field (`viewer`, `viewerCan*`, `isReadByViewer`, …). */
9
+ export declare function isAppEligibleGraphql(document: string): boolean;
@@ -0,0 +1,21 @@
1
+ import { isGraphQlMutationDocument } from "./graphql-internal-retry.mjs";
2
+ /**
3
+ * The app answers only requests whose answer does not depend on who asks. Everything else
4
+ * (writes, `/user`, viewer fields) stays on the user's token, so identity semantics are the same
5
+ * as running without the app.
6
+ */
7
+ /** A GET or HEAD of a repository route. Caller-relative routes (`/user`, `/rate_limit`) are not. */
8
+ export function isAppEligibleRest(method, path) {
9
+ return (method === "GET" || method === "HEAD") && path.startsWith("/repos/");
10
+ }
11
+ const VIEWER_RELATIVE = /\bviewer\w*|\w+ByViewer\b/;
12
+ const eligibility = new Map();
13
+ /** A query that selects no viewer-relative field (`viewer`, `viewerCan*`, `isReadByViewer`, …). */
14
+ export function isAppEligibleGraphql(document) {
15
+ const known = eligibility.get(document);
16
+ if (known !== undefined)
17
+ return known;
18
+ const eligible = !isGraphQlMutationDocument(document) && !VIEWER_RELATIVE.test(document.replace(/#[^\n]*/g, ""));
19
+ eligibility.set(document, eligible);
20
+ return eligible;
21
+ }
@@ -0,0 +1,10 @@
1
+ export type AppResource = "graphql" | "core";
2
+ export declare function _resetAppQuota(): void;
3
+ /** True while the installation's bucket for the resource is empty. */
4
+ export declare function isAppExhausted(installationId: number, resource: AppResource): boolean;
5
+ /**
6
+ * Re-run an app-authenticated request once with the user's token when the installation's own
7
+ * primary limit is spent. `work` re-resolves its credential on every call, so the second run
8
+ * sees the exhaustion mark and uses the user chain until GitHub resets the bucket.
9
+ */
10
+ export declare function withAppQuotaFallback<T>(resource: AppResource, work: () => Promise<T>): Promise<T>;
@@ -0,0 +1,44 @@
1
+ import { appendEntry } from "../log/log-file.mjs";
2
+ import { GitHubRequestError } from "./errors.mjs";
3
+ import { needsGraphQlQuotaProbe } from "./graphql-quota-probe.mjs";
4
+ import { rateLimitKind } from "./rate-limit-kind.mjs";
5
+ const APP_SOURCE = /^GitHub App \d+ \(installation (\d+)\)$/;
6
+ const FALLBACK_WINDOW_MS = 60_000;
7
+ /** `installation:resource` to the epoch milliseconds when GitHub resets that bucket. */
8
+ const exhausted = new Map();
9
+ export function _resetAppQuota() {
10
+ exhausted.clear();
11
+ }
12
+ /** True while the installation's bucket for the resource is empty. */
13
+ export function isAppExhausted(installationId, resource) {
14
+ const until = exhausted.get(`${installationId}:${resource}`);
15
+ return until !== undefined && until > Date.now();
16
+ }
17
+ /** Primary exhaustion only. Secondary (abuse) limits are never a reason to switch credentials. */
18
+ function isPrimaryExhaustion(error) {
19
+ return rateLimitKind(error) === "primary" || needsGraphQlQuotaProbe(error);
20
+ }
21
+ /**
22
+ * Re-run an app-authenticated request once with the user's token when the installation's own
23
+ * primary limit is spent. `work` re-resolves its credential on every call, so the second run
24
+ * sees the exhaustion mark and uses the user chain until GitHub resets the bucket.
25
+ */
26
+ export async function withAppQuotaFallback(resource, work) {
27
+ try {
28
+ return await work();
29
+ }
30
+ catch (error) {
31
+ const installation = APP_SOURCE.exec(error instanceof GitHubRequestError ? (error.authSource ?? "") : "")?.[1];
32
+ if (!(error instanceof GitHubRequestError) || !installation || !isPrimaryExhaustion(error)) {
33
+ throw error;
34
+ }
35
+ const resetAt = error.rateLimit?.resetAt;
36
+ const reset = resetAt ? resetAt * 1000 : 0;
37
+ const until = reset > Date.now() ? reset : Date.now() + FALLBACK_WINDOW_MS;
38
+ if (!isAppExhausted(Number(installation), resource)) {
39
+ appendEntry(`GitHub App installation ${installation} exhausted its ${resource} rate limit until ${new Date(until).toISOString()}; using the user token.\n`);
40
+ }
41
+ exhausted.set(`${installation}:${resource}`, until);
42
+ return work();
43
+ }
44
+ }
@@ -0,0 +1,16 @@
1
+ export interface AuthTarget {
2
+ owner: string;
3
+ repo: string;
4
+ }
5
+ /** Wrap a complete command so every request it makes shares one target record. */
6
+ export declare function runWithAuthScope<T>(work: () => Promise<T>): Promise<T>;
7
+ /** Record the command's repository; a no-op outside `runWithAuthScope`. */
8
+ export declare function setAuthTarget(repository: {
9
+ owner: string;
10
+ name: string;
11
+ }, kind: "explicit" | "inferred"): void;
12
+ export declare function currentAuthTarget(): AuthTarget | undefined;
13
+ /** `/repos/{owner}/{repo}/…` */
14
+ export declare function authTargetFromRestPath(path: string): AuthTarget | undefined;
15
+ /** `owner` plus `repo` (or `name`) string variables. */
16
+ export declare function authTargetFromGraphqlVars(vars: Record<string, unknown>): AuthTarget | undefined;
@@ -0,0 +1,29 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ const scope = new AsyncLocalStorage();
3
+ /** Wrap a complete command so every request it makes shares one target record. */
4
+ export function runWithAuthScope(work) {
5
+ return scope.run({}, work);
6
+ }
7
+ /** Record the command's repository; a no-op outside `runWithAuthScope`. */
8
+ export function setAuthTarget(repository, kind) {
9
+ const current = scope.getStore();
10
+ if (current)
11
+ current[kind] = { owner: repository.owner, repo: repository.name };
12
+ }
13
+ export function currentAuthTarget() {
14
+ const current = scope.getStore();
15
+ return current?.explicit ?? current?.inferred;
16
+ }
17
+ /** `/repos/{owner}/{repo}/…` */
18
+ export function authTargetFromRestPath(path) {
19
+ const match = /^\/repos\/([^/?#]+)\/([^/?#]+)/.exec(path);
20
+ return match ? { owner: match[1], repo: match[2] } : undefined;
21
+ }
22
+ /** `owner` plus `repo` (or `name`) string variables. */
23
+ export function authTargetFromGraphqlVars(vars) {
24
+ const { owner, repo, name } = vars;
25
+ const repository = typeof repo === "string" ? repo : name;
26
+ return typeof owner === "string" && typeof repository === "string"
27
+ ? { owner, repo: repository }
28
+ : undefined;
29
+ }
@@ -15,6 +15,7 @@ import { promisify } from "node:util";
15
15
  import { graphql as httpGraphql, rest } from "./http.mjs";
16
16
  import { PR_NUMBER_BY_BRANCH_QUERY, GET_PR_HEAD_SHA_QUERY, GET_PR_BODY_QUERY, UPDATE_PR_BODY_MUTATION, } from "./queries.mjs";
17
17
  import { getExecutionCwd } from "../execution-context.mjs";
18
+ import { setAuthTarget } from "./auth-target.mjs";
18
19
  const execFile = promisify(execFileCb);
19
20
  // ---------------------------------------------------------------------------
20
21
  // GraphQL — thin re-exports so callers don't need to import http.mts directly
@@ -28,8 +29,9 @@ export async function getRepoInfo() {
28
29
  const { stdout } = await execFile("git", ["remote", "get-url", "origin"], {
29
30
  cwd: getExecutionCwd(),
30
31
  });
31
- const url = stdout.trim();
32
- return parseRemoteUrl(url);
32
+ const repository = parseRemoteUrl(stdout.trim());
33
+ setAuthTarget(repository, "inferred");
34
+ return repository;
33
35
  }
34
36
  /**
35
37
  * Derives the PR number for the current HEAD branch.
@@ -0,0 +1,12 @@
1
+ export interface GithubApp {
2
+ appId: number;
3
+ /** Absolute path of the PEM private key. */
4
+ privateKeyFile: string;
5
+ /** Lowercased `owner/*` or `owner/repo` patterns. */
6
+ repositories: string[];
7
+ }
8
+ export declare function _resetGithubApps(): void;
9
+ /** Read `github-apps.yml` once per process. A missing file turns the feature off. */
10
+ export declare function loadGithubApps(): GithubApp[];
11
+ /** First listed app whose patterns match the repository. Matching ignores case. */
12
+ export declare function findGithubApp(owner: string, repo: string): GithubApp | undefined;