@oss-autopilot/core 3.39.1 → 3.40.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 (43) hide show
  1. package/dist/cli-registry.js +105 -1
  2. package/dist/cli.bundle.cjs +163 -144
  3. package/dist/commands/daily.d.ts +6 -1
  4. package/dist/commands/daily.js +29 -6
  5. package/dist/commands/dashboard-data.js +16 -7
  6. package/dist/commands/index.d.ts +3 -0
  7. package/dist/commands/index.js +2 -0
  8. package/dist/commands/scout-bridge.js +23 -1
  9. package/dist/commands/setup.js +2 -1
  10. package/dist/commands/vet-list.js +18 -1
  11. package/dist/commands/vet.js +7 -1
  12. package/dist/commands/work.d.ts +134 -0
  13. package/dist/commands/work.js +313 -0
  14. package/dist/core/config-registry.js +6 -0
  15. package/dist/core/daily-logic.d.ts +2 -1
  16. package/dist/core/daily-logic.js +12 -1
  17. package/dist/core/engaged-issue-lookup.d.ts +82 -0
  18. package/dist/core/engaged-issue-lookup.js +157 -0
  19. package/dist/core/engaged-issues.d.ts +3 -3
  20. package/dist/core/engaged-issues.js +5 -5
  21. package/dist/core/gist-state-store.js +6 -2
  22. package/dist/core/index.d.ts +2 -0
  23. package/dist/core/index.js +2 -0
  24. package/dist/core/issue-conversation.d.ts +68 -21
  25. package/dist/core/issue-conversation.js +157 -75
  26. package/dist/core/machine-id.d.ts +18 -0
  27. package/dist/core/machine-id.js +131 -0
  28. package/dist/core/paths.d.ts +8 -0
  29. package/dist/core/paths.js +10 -0
  30. package/dist/core/pr-graphql.d.ts +2 -0
  31. package/dist/core/pr-graphql.js +2 -2
  32. package/dist/core/state-persistence.d.ts +8 -0
  33. package/dist/core/state-persistence.js +14 -1
  34. package/dist/core/state-schema.d.ts +54 -1
  35. package/dist/core/state-schema.js +68 -0
  36. package/dist/core/state.d.ts +39 -1
  37. package/dist/core/state.js +86 -2
  38. package/dist/core/types.d.ts +1 -1
  39. package/dist/core/work-claims.d.ts +89 -0
  40. package/dist/core/work-claims.js +196 -0
  41. package/dist/formatters/json.d.ts +130 -1
  42. package/dist/formatters/json.js +26 -0
  43. package/package.json +1 -1
@@ -0,0 +1,313 @@
1
+ /**
2
+ * Work claim commands (#1856, #1852 gap 2): `work claim`, `work finish`,
3
+ * `work release`, `work list`.
4
+ *
5
+ * A claim records that some session is working an item, so other sessions
6
+ * (same machine or another one via the Gist) see it instead of starting the
7
+ * same work. `implementation` claims sit on issue URLs while a fix is built
8
+ * in the background; `pr` claims sit on PR URLs while a session does Tier 2
9
+ * work there. Rules live in `core/work-claims.ts`; this file validates input,
10
+ * applies the state mutation and pushes it to the Gist.
11
+ *
12
+ * Each `run*` has a `*Work(stateManager, options)` twin that takes the
13
+ * manager explicitly, so the Gist concurrency tests can drive two machines
14
+ * through the real command path.
15
+ */
16
+ import os from 'node:os';
17
+ import { WORK_CLAIM_DEFAULT_TTL_HOURS, WORK_CLAIM_FINISHED_TTL_HOURS, WORK_CLAIM_MAX_TTL_HOURS, checkImplementationClaim, describeWorkClaim, findWorkClaim, getMachineId, getStateManager, heldByOtherSession, maybeCheckpoint, normalizeWorktreePath, } from '../core/index.js';
18
+ import { ValidationError } from '../core/errors.js';
19
+ import { buildStalenessWarning } from '../formatters/json.js';
20
+ import { ISSUE_URL_PATTERN, PR_URL_PATTERN, validateGitHubUrl, validateUrl } from './validation.js';
21
+ const MODULE = 'work';
22
+ /** Longest free-text field (`session`, `branch`, `worktree`, `runId`) accepted, in characters. */
23
+ const MAX_FIELD_LENGTH = 500;
24
+ /** Control characters (Unicode category Cc), which would break the one-line menu rendering of a claim. */
25
+ const CONTROL_CHARACTERS = /\p{Cc}/u;
26
+ function isoAt(ms) {
27
+ const at = new Date(ms);
28
+ return at.toISOString();
29
+ }
30
+ function validateField(name, value) {
31
+ if (value === undefined)
32
+ return undefined;
33
+ const trimmed = value.trim();
34
+ if (trimmed.length === 0)
35
+ throw new ValidationError(`--${name} must not be empty`);
36
+ if (trimmed.length > MAX_FIELD_LENGTH)
37
+ throw new ValidationError(`--${name} is longer than ${MAX_FIELD_LENGTH} characters`);
38
+ if (CONTROL_CHARACTERS.test(trimmed))
39
+ throw new ValidationError(`--${name} must not contain control characters`);
40
+ return trimmed;
41
+ }
42
+ function validateKind(kind) {
43
+ if (kind === 'implementation' || kind === 'pr')
44
+ return kind;
45
+ throw new ValidationError(`--kind must be "implementation" or "pr", got "${kind}"`);
46
+ }
47
+ function validateTtl(ttlHours) {
48
+ if (ttlHours === undefined)
49
+ return undefined;
50
+ if (!Number.isFinite(ttlHours) || ttlHours <= 0 || ttlHours > WORK_CLAIM_MAX_TTL_HOURS) {
51
+ throw new ValidationError(`--ttl must be a number of hours between 0 and ${WORK_CLAIM_MAX_TTL_HOURS}`);
52
+ }
53
+ return ttlHours;
54
+ }
55
+ /** Validate a claim's URL against its kind: implementations sit on issues, pr claims on PRs. */
56
+ function validateClaimUrl(url, kind) {
57
+ validateUrl(url);
58
+ if (kind === 'pr') {
59
+ validateGitHubUrl(url, PR_URL_PATTERN, 'PR');
60
+ }
61
+ else {
62
+ validateGitHubUrl(url, ISSUE_URL_PATTERN, 'issue');
63
+ }
64
+ }
65
+ /**
66
+ * This machine's short hostname, as `hostname -s` prints it: `os.hostname()`
67
+ * may carry a domain (`air.local`, `air.example.com`) that differs between
68
+ * networks, and the workflow docs compare a claim's `host` to `hostname -s`.
69
+ */
70
+ function shortHostname() {
71
+ return os.hostname().split('.', 1)[0];
72
+ }
73
+ /**
74
+ * The validated `--worktree` with the identity of the machine it is on:
75
+ * the short hostname (display, and the legacy comparison key) and the
76
+ * machine id (the comparison key; absent when the id file is unusable).
77
+ * Empty when no worktree was given.
78
+ */
79
+ function checkoutIdentity(rawWorktree) {
80
+ const worktree = validateField('worktree', rawWorktree);
81
+ if (worktree === undefined)
82
+ return {};
83
+ return { worktree: normalizeWorktreePath(worktree), host: shortHostname(), machineId: getMachineId() };
84
+ }
85
+ function validateClaimInput(options) {
86
+ const kind = validateKind(options.kind);
87
+ validateClaimUrl(options.url, kind);
88
+ const session = validateField('session', options.session);
89
+ if (session === undefined)
90
+ throw new ValidationError('--session is required');
91
+ const branch = validateField('branch', options.branch);
92
+ const runId = validateField('run-id', options.runId);
93
+ const checkout = checkoutIdentity(options.worktree);
94
+ if (kind === 'implementation' && runId === undefined && checkout.worktree === undefined) {
95
+ throw new ValidationError('An implementation claim needs --worktree (local checkout) or --run-id (remote worker run)');
96
+ }
97
+ const ttlHours = validateTtl(options.ttlHours);
98
+ const isTakeover = options.takeover === true;
99
+ return { kind, session, branch, ...checkout, runId, ttlHours, url: options.url, takeover: isTakeover };
100
+ }
101
+ /**
102
+ * Why the claim may not be recorded against the manager's current claims:
103
+ * another session holds the item (and `takeover` was not passed), the
104
+ * implementation cap is reached, or the checkout hosts another
105
+ * implementation. Null when it may proceed. Evaluated on the local state
106
+ * first and again on the Gist's copy after a conflict, so a claim another
107
+ * machine recorded first is never overwritten.
108
+ */
109
+ function claimRefusal(stateManager, input, nowMs) {
110
+ const claims = stateManager.getWorkClaims();
111
+ const holder = heldByOtherSession(claims, input.url, input.session, nowMs);
112
+ if (holder && !input.takeover) {
113
+ return (`${input.url} is already claimed: ${describeWorkClaim(holder, nowMs)}. ` +
114
+ `Pass --takeover (takeover: true) to replace that claim.`);
115
+ }
116
+ if (input.kind === 'implementation') {
117
+ const cap = stateManager.getState().config.maxConcurrentImplementations;
118
+ const conflict = checkImplementationClaim(claims, input, cap, nowMs);
119
+ if (conflict)
120
+ return conflict.message;
121
+ }
122
+ return null;
123
+ }
124
+ /**
125
+ * Build the claim to store. Renewing this session's own `finished`
126
+ * implementation keeps it finished (and collectable for the finished TTL):
127
+ * a renewal must not quietly turn a branch that is ready to collect back
128
+ * into a run in progress. To start over, release the claim first.
129
+ */
130
+ function buildClaim(input, existing, nowMs) {
131
+ const finishedOwn = isOwnFinishedClaim(input, existing) ? existing : undefined;
132
+ const ttlHours = input.ttlHours ?? (finishedOwn ? WORK_CLAIM_FINISHED_TTL_HOURS : WORK_CLAIM_DEFAULT_TTL_HOURS[input.kind]);
133
+ return {
134
+ kind: input.kind,
135
+ url: input.url,
136
+ session: input.session,
137
+ startedAt: isoAt(nowMs),
138
+ expiresAt: isoAt(nowMs + ttlHours * 3_600_000),
139
+ status: finishedOwn ? 'finished' : 'running',
140
+ ...locationFields(input),
141
+ ...(finishedOwn?.finishedAt !== undefined && { finishedAt: finishedOwn.finishedAt }),
142
+ };
143
+ }
144
+ /** The optional location fields of `input` that are set, so an absent one is left off the stored claim. */
145
+ function locationFields(input) {
146
+ const { branch, worktree, host, machineId, runId } = input;
147
+ return {
148
+ ...(branch !== undefined && { branch }),
149
+ ...(worktree !== undefined && { worktree }),
150
+ ...(host !== undefined && { host }),
151
+ ...(machineId !== undefined && { machineId }),
152
+ ...(runId !== undefined && { runId }),
153
+ };
154
+ }
155
+ /** Whether `existing` is this session's own finished claim of the same kind (a renewal keeps it finished). */
156
+ function isOwnFinishedClaim(input, existing) {
157
+ return (existing !== undefined &&
158
+ existing.session === input.session &&
159
+ existing.kind === input.kind &&
160
+ existing.status === 'finished');
161
+ }
162
+ /** What recording `claim` over `existing` amounts to. */
163
+ function outcomeFor(existing, session) {
164
+ if (existing === undefined)
165
+ return 'claimed';
166
+ return existing.session === session ? 'renewed' : 'took-over';
167
+ }
168
+ /**
169
+ * Take (or renew) a claim on an item (#1856, #1852).
170
+ *
171
+ * An implementation claim needs a `worktree` or a `runId` so the
172
+ * one-implementation-per-checkout rule has something to compare, and it is
173
+ * refused when `maxConcurrentImplementations` running implementations
174
+ * already exist or another live implementation uses the same checkout on
175
+ * this machine. A live claim another session holds is refused unless `takeover`
176
+ * is set (the workflow asks first); this session's own claim is renewed.
177
+ *
178
+ * In Gist mode the checks run again on the Gist's copy when the push
179
+ * conflicts with another machine: if that copy refuses the claim, nothing is
180
+ * recorded and the refusal is thrown. The claim is `synced: false` when it
181
+ * exists locally only.
182
+ *
183
+ * @throws {ValidationError} On a malformed URL or kind mismatch, a missing
184
+ * location for an implementation, an out-of-range TTL, or when another
185
+ * session's claim, the cap or the checkout rule blocks the claim.
186
+ */
187
+ export async function runWorkClaim(options) {
188
+ return claimWork(getStateManager(), options);
189
+ }
190
+ /** {@link runWorkClaim} against an explicit manager. */
191
+ export async function claimWork(stateManager, options) {
192
+ const input = validateClaimInput(options);
193
+ const now = Date.now();
194
+ const refusedLocally = claimRefusal(stateManager, input, now);
195
+ if (refusedLocally)
196
+ throw new ValidationError(refusedLocally);
197
+ const existing = findWorkClaim(stateManager.getWorkClaims(), input.url, now);
198
+ const claim = buildClaim(input, existing, now);
199
+ const outcome = outcomeFor(existing, input.session);
200
+ // The reapply (pre-push and after a Gist conflict) re-checks on whatever
201
+ // state is current. On the local state it sees this claim and passes; on
202
+ // a refreshed Gist copy it may find another machine got there first, and
203
+ // then it records the refusal instead of writing over that claim.
204
+ const remote = { message: null };
205
+ const apply = () => {
206
+ remote.message = claimRefusal(stateManager, input, now);
207
+ if (remote.message === null)
208
+ stateManager.upsertWorkClaim(claim, now);
209
+ };
210
+ apply();
211
+ const gistSyncWarning = await maybeCheckpoint(stateManager, MODULE, apply);
212
+ if (remote.message !== null) {
213
+ throw new ValidationError(`${remote.message} (recorded on another machine first; this claim was not saved)`);
214
+ }
215
+ const isSynced = gistSyncWarning === null && stateManager.getGistHealth().degraded === null;
216
+ return { claim, outcome, synced: isSynced, ...(gistSyncWarning && { gistSyncWarning }) };
217
+ }
218
+ /**
219
+ * Mark the live claim on `url` finished (#1856): the implementation's branch
220
+ * is ready to collect. The claim stays (with its expiry extended to at least
221
+ * a week) until it is released or expires, so the action menu can offer
222
+ * "Collect finished implementations" and search keeps skipping the issue.
223
+ * With `session`, a claim another session holds is refused rather than
224
+ * finished on its behalf.
225
+ *
226
+ * @throws {ValidationError} When `session` is given and the live claim belongs to another session.
227
+ */
228
+ export async function runWorkFinish(options) {
229
+ return finishWork(getStateManager(), options);
230
+ }
231
+ /** {@link runWorkFinish} against an explicit manager. */
232
+ export async function finishWork(stateManager, options) {
233
+ validateUrl(options.url);
234
+ const session = validateField('session', options.session);
235
+ const now = Date.now();
236
+ const at = isoAt(now);
237
+ const mismatch = () => {
238
+ const existing = findWorkClaim(stateManager.getWorkClaims(), options.url, now);
239
+ if (existing === undefined || session === undefined || existing.session === session)
240
+ return null;
241
+ return `The claim on ${options.url} belongs to session ${existing.session}, not ${session}; it was not marked finished.`;
242
+ };
243
+ const refusal = { message: mismatch() };
244
+ if (refusal.message !== null)
245
+ throw new ValidationError(refusal.message);
246
+ const result = { claim: null };
247
+ const apply = () => {
248
+ refusal.message = mismatch();
249
+ if (refusal.message === null)
250
+ result.claim = stateManager.finishWorkClaim(options.url, at, now) ?? null;
251
+ };
252
+ apply();
253
+ const gistSyncWarning = result.claim ? await maybeCheckpoint(stateManager, MODULE, apply) : null;
254
+ if (refusal.message !== null)
255
+ throw new ValidationError(refusal.message);
256
+ return { url: options.url, claim: result.claim, ...(gistSyncWarning && { gistSyncWarning }) };
257
+ }
258
+ /**
259
+ * Drop claims (#1856, #1852): the claim on `url`, or every claim `session`
260
+ * holds (Session End releases that session's `pr` claims with
261
+ * `{ session, kind: 'pr' }`). Releasing an item nobody holds is not an
262
+ * error: `released` is simply empty.
263
+ *
264
+ * @throws {ValidationError} When neither `url` nor `session` is given.
265
+ */
266
+ export async function runWorkRelease(options) {
267
+ return releaseWork(getStateManager(), options);
268
+ }
269
+ /** {@link runWorkRelease} against an explicit manager. */
270
+ export async function releaseWork(stateManager, options) {
271
+ const session = validateField('session', options.session);
272
+ const kind = options.kind === undefined ? undefined : validateKind(options.kind);
273
+ if (options.url !== undefined)
274
+ validateUrl(options.url);
275
+ if (session === undefined && options.url === undefined) {
276
+ throw new ValidationError('work release needs a URL or --session <name>');
277
+ }
278
+ const selector = { url: options.url, session, kind };
279
+ const released = stateManager.releaseWorkClaims(selector);
280
+ const gistSyncWarning = released.length > 0
281
+ ? await maybeCheckpoint(stateManager, MODULE, () => stateManager.releaseWorkClaims(selector))
282
+ : null;
283
+ return { released, ...(gistSyncWarning && { gistSyncWarning }) };
284
+ }
285
+ /**
286
+ * The live claims (#1856). Read-only: expired claims are counted, not
287
+ * pruned. In Gist mode the state is refreshed first (throttled to once per
288
+ * 30 s by the store; a failed fetch serves the cached copy and sets a
289
+ * `warnings` entry) so a claim another machine pushed since this process
290
+ * loaded state is visible.
291
+ */
292
+ export async function runWorkList() {
293
+ return listWork(getStateManager());
294
+ }
295
+ /** {@link runWorkList} against an explicit manager. */
296
+ export async function listWork(stateManager) {
297
+ if (stateManager.isGistMode()) {
298
+ await stateManager.refreshFromGist();
299
+ }
300
+ else {
301
+ stateManager.reloadIfChanged();
302
+ }
303
+ const now = Date.now();
304
+ const all = stateManager.getWorkClaims();
305
+ const claims = stateManager.getActiveWorkClaims(now);
306
+ const staleness = stateManager.getStateStaleness();
307
+ return {
308
+ claims,
309
+ expiredCount: all.length - claims.length,
310
+ now: isoAt(now),
311
+ ...(staleness && { warnings: [buildStalenessWarning(staleness)] }),
312
+ };
313
+ }
@@ -43,6 +43,12 @@ export const CONFIG_KEY_REGISTRY = [
43
43
  settableVia: 'setup',
44
44
  valueHint: 'non-negative integer (0 = no limit)',
45
45
  },
46
+ {
47
+ key: 'maxConcurrentImplementations',
48
+ description: 'How many implementations may run at once across sessions and machines (work claim --kind implementation refuses past it). Default 2; 0 disables the cap.',
49
+ settableVia: 'setup',
50
+ valueHint: 'non-negative integer (0 = no limit)',
51
+ },
46
52
  {
47
53
  key: 'dormantDays',
48
54
  description: 'Alias for dormantThresholdDays: days of inactivity before a PR is considered dormant.',
@@ -193,11 +193,12 @@ export declare function collectActionableIssues(prs: FetchedPR[], lastDigestAt?:
193
193
  * @param closedPRStatusCount - Closed-unmerged PRs whose linked issue still needs a status update (#1863); non-zero adds a closed_pr_status item
194
194
  * @param mergedPRNotesCount - Recently merged PRs carrying maintainer notes the user has not answered (#1861); non-zero adds a merged_pr_notes item
195
195
  * @param reviewedPRCount - PRs the user reviewed where the author pushed or replied since (#1857); non-zero adds a review_follow_ups item
196
+ * @param finishedImplementationCount - Background implementations whose branch is ready to collect (#1856); non-zero adds a collect_implementations item
196
197
  * @returns Action menu with context flags for orchestration
197
198
  */
198
199
  export declare function computeActionMenu(actionableIssues: ActionableIssue[], capacity: CapacityAssessment, commentedIssues?: CommentedIssue[], attention?: Pick<AttentionSummary, 'stuckCI' | 'dormantFollowup'> & {
199
200
  closeSuggested?: number;
200
- }, unextractedMergeCount?: number, closedPRStatusCount?: number, mergedPRNotesCount?: number, reviewedPRCount?: number): ActionMenu;
201
+ }, unextractedMergeCount?: number, closedPRStatusCount?: number, mergedPRNotesCount?: number, reviewedPRCount?: number, finishedImplementationCount?: number): ActionMenu;
201
202
  /**
202
203
  * Whether a dismiss stamped at `dismissedAt` still covers the reply posted
203
204
  * at `lastResponseAt`: both parse and the dismiss is not older than the
@@ -490,9 +490,10 @@ export function collectActionableIssues(prs, lastDigestAt) {
490
490
  * @param closedPRStatusCount - Closed-unmerged PRs whose linked issue still needs a status update (#1863); non-zero adds a closed_pr_status item
491
491
  * @param mergedPRNotesCount - Recently merged PRs carrying maintainer notes the user has not answered (#1861); non-zero adds a merged_pr_notes item
492
492
  * @param reviewedPRCount - PRs the user reviewed where the author pushed or replied since (#1857); non-zero adds a review_follow_ups item
493
+ * @param finishedImplementationCount - Background implementations whose branch is ready to collect (#1856); non-zero adds a collect_implementations item
493
494
  * @returns Action menu with context flags for orchestration
494
495
  */
495
- export function computeActionMenu(actionableIssues, capacity, commentedIssues = [], attention, unextractedMergeCount, closedPRStatusCount = 0, mergedPRNotesCount = 0, reviewedPRCount = 0) {
496
+ export function computeActionMenu(actionableIssues, capacity, commentedIssues = [], attention, unextractedMergeCount, closedPRStatusCount = 0, mergedPRNotesCount = 0, reviewedPRCount = 0, finishedImplementationCount = 0) {
496
497
  const issueResponses = commentedIssues.filter((i) => i.status === 'new_response');
497
498
  const items = [];
498
499
  const hasActionableIssues = actionableIssues.length > 0;
@@ -595,6 +596,16 @@ export function computeActionMenu(actionableIssues, capacity, commentedIssues =
595
596
  description: 'PRs you reviewed where the author pushed or replied since; re-review the changes and answer their questions',
596
597
  });
597
598
  }
599
+ // A background implementation (#1856) reported its branch ready; collecting
600
+ // it enters the draft-first workflow at the review step. Running ones are
601
+ // shown in the menu header from `workClaims`, not as an item.
602
+ if (finishedImplementationCount > 0) {
603
+ items.push({
604
+ key: 'collect_implementations',
605
+ label: `Collect finished implementations (${finishedImplementationCount})`,
606
+ description: 'Review a branch a background implementation prepared, then push and open its PR',
607
+ });
608
+ }
598
609
  // The orchestration layer (commands/oss.md Action Menu section) may insert issue-list
599
610
  // options before the search item when a curated list is available.
600
611
  const searchItem = {
@@ -0,0 +1,82 @@
1
+ /**
2
+ * Batched GraphQL lookup of engaged issues the comment search missed (#1862).
3
+ *
4
+ * The REST path spent one `issues.get` per engaged issue to learn whether it
5
+ * was still open and had changed since the engagement, and capped those
6
+ * lookups in insertion order, so a user with more engaged issues than the cap
7
+ * never had the tail looked at on any run. One aliased GraphQL query per
8
+ * {@link ENGAGED_LOOKUP_BATCH_SIZE} issues answers the same question from
9
+ * GitHub's separate GraphQL point bucket (a few points per query), so every
10
+ * engaged issue is checked and the cap moves to the comment fetches, applied
11
+ * only to the issues that actually changed.
12
+ *
13
+ * `issueOrPullRequest` rather than `issue`: a closing keyword can name a pull
14
+ * request, and `issue(number:)` reports one as NOT_FOUND, the same as a deleted
15
+ * issue. The union keeps the two apart, so a PR number is skipped quietly
16
+ * instead of warned about as gone.
17
+ *
18
+ * Outcomes per issue: `found` (an issue node), `pull_request`, `gone` (a null
19
+ * node, or a NOT_FOUND error in a partial response: deleted or now private;
20
+ * GitHub follows a transferred issue to its new repo, so the node's `url`
21
+ * can differ from the ref's), or `failed` (any other per-alias error, or a
22
+ * whole query that failed for a reason other than rate limiting or auth;
23
+ * those rethrow).
24
+ */
25
+ import type { Octokit } from '@octokit/rest';
26
+ /** Issues per aliased GraphQL query. */
27
+ export declare const ENGAGED_LOOKUP_BATCH_SIZE = 50;
28
+ /** One engaged issue to look up. */
29
+ export interface EngagedIssueRef {
30
+ owner: string;
31
+ repo: string;
32
+ number: number;
33
+ /** Canonical issue URL; the result map is keyed by it. */
34
+ url: string;
35
+ }
36
+ /** The fields read off an issue node. */
37
+ export interface EngagedIssueNode {
38
+ __typename: 'Issue';
39
+ url: string;
40
+ number: number;
41
+ title: string;
42
+ state: 'OPEN' | 'CLOSED';
43
+ updatedAt: string;
44
+ author: {
45
+ login: string;
46
+ } | null;
47
+ labels: {
48
+ nodes: Array<{
49
+ name: string;
50
+ } | null>;
51
+ } | null;
52
+ }
53
+ export type EngagedIssueLookup = {
54
+ kind: 'found';
55
+ node: EngagedIssueNode;
56
+ } | {
57
+ kind: 'pull_request';
58
+ } | {
59
+ kind: 'gone';
60
+ reason: string;
61
+ } | {
62
+ kind: 'failed';
63
+ error: string;
64
+ };
65
+ /**
66
+ * Build the aliased query for one batch. Owner, repo and number travel as
67
+ * GraphQL variables, never interpolated into the query text.
68
+ */
69
+ export declare function buildEngagedIssueQuery(refs: EngagedIssueRef[]): {
70
+ query: string;
71
+ variables: Record<string, string | number>;
72
+ };
73
+ /**
74
+ * Look up every ref, one query per batch, sequentially (GitHub recommends
75
+ * serial GraphQL requests). A batch that fails outright (a 502, a network
76
+ * blip, a server-side timeout on a large query) is retried once as two
77
+ * half-size queries, so one bad response does not fail fifty issues; a half
78
+ * that fails again fails its refs. Returns an outcome per ref, keyed by URL.
79
+ *
80
+ * @throws The GraphQL error when it is a rate-limit or auth failure.
81
+ */
82
+ export declare function lookupEngagedIssues(octokit: Octokit, refs: EngagedIssueRef[]): Promise<Map<string, EngagedIssueLookup>>;
@@ -0,0 +1,157 @@
1
+ /**
2
+ * Batched GraphQL lookup of engaged issues the comment search missed (#1862).
3
+ *
4
+ * The REST path spent one `issues.get` per engaged issue to learn whether it
5
+ * was still open and had changed since the engagement, and capped those
6
+ * lookups in insertion order, so a user with more engaged issues than the cap
7
+ * never had the tail looked at on any run. One aliased GraphQL query per
8
+ * {@link ENGAGED_LOOKUP_BATCH_SIZE} issues answers the same question from
9
+ * GitHub's separate GraphQL point bucket (a few points per query), so every
10
+ * engaged issue is checked and the cap moves to the comment fetches, applied
11
+ * only to the issues that actually changed.
12
+ *
13
+ * `issueOrPullRequest` rather than `issue`: a closing keyword can name a pull
14
+ * request, and `issue(number:)` reports one as NOT_FOUND, the same as a deleted
15
+ * issue. The union keeps the two apart, so a PR number is skipped quietly
16
+ * instead of warned about as gone.
17
+ *
18
+ * Outcomes per issue: `found` (an issue node), `pull_request`, `gone` (a null
19
+ * node, or a NOT_FOUND error in a partial response: deleted or now private;
20
+ * GitHub follows a transferred issue to its new repo, so the node's `url`
21
+ * can differ from the ref's), or `failed` (any other per-alias error, or a
22
+ * whole query that failed for a reason other than rate limiting or auth;
23
+ * those rethrow).
24
+ */
25
+ import { errorMessage, isRateLimitOrAuthError } from './errors.js';
26
+ import { chunk, isGraphqlRateLimited } from './pr-graphql.js';
27
+ /** Issues per aliased GraphQL query. */
28
+ export const ENGAGED_LOOKUP_BATCH_SIZE = 50;
29
+ /** Labels requested per issue; the labels are display-only on the digest entry. */
30
+ const LABELS_CAP = 20;
31
+ const ISSUE_FIELDS = `
32
+ __typename
33
+ ... on Issue {
34
+ url
35
+ number
36
+ title
37
+ state
38
+ updatedAt
39
+ author { login }
40
+ labels(first: ${LABELS_CAP}) { nodes { name } }
41
+ }
42
+ `;
43
+ /**
44
+ * Build the aliased query for one batch. Owner, repo and number travel as
45
+ * GraphQL variables, never interpolated into the query text.
46
+ */
47
+ export function buildEngagedIssueQuery(refs) {
48
+ const varDefs = [];
49
+ const selections = [];
50
+ const variables = {};
51
+ for (const [i, ref] of refs.entries()) {
52
+ varDefs.push(`$o${i}: String!, $r${i}: String!, $n${i}: Int!`);
53
+ variables[`o${i}`] = ref.owner;
54
+ variables[`r${i}`] = ref.repo;
55
+ variables[`n${i}`] = ref.number;
56
+ selections.push(`i${i}: repository(owner: $o${i}, name: $r${i}) {\n issueOrPullRequest(number: $n${i}) {${ISSUE_FIELDS}}\n}`);
57
+ }
58
+ const query = `query engagedIssues(${varDefs.join(', ')}) {\n${selections.join('\n')}\n}`;
59
+ return { query, variables };
60
+ }
61
+ /** The errors of a partial response: keyed by the alias they point at, plus the ones without a path. */
62
+ function partitionErrors(err) {
63
+ const byAlias = new Map();
64
+ const unattributed = [];
65
+ const errors = err?.errors;
66
+ if (!Array.isArray(errors))
67
+ return { byAlias, unattributed };
68
+ for (const entry of errors) {
69
+ if (!entry)
70
+ continue;
71
+ const alias = entry.path?.[0];
72
+ if (typeof alias === 'string') {
73
+ const list = byAlias.get(alias) ?? [];
74
+ list.push(entry);
75
+ byAlias.set(alias, list);
76
+ }
77
+ else {
78
+ unattributed.push(entry);
79
+ }
80
+ }
81
+ return { byAlias, unattributed };
82
+ }
83
+ /**
84
+ * Run one batch. A partial-data error keeps the aliases that resolved and the
85
+ * errors for the rest; rate-limit and auth errors (REST-style status or the
86
+ * GraphQL-native `RATE_LIMITED`) rethrow; anything else fails the batch.
87
+ */
88
+ async function runChunk(octokit, refs) {
89
+ const { query, variables } = buildEngagedIssueQuery(refs);
90
+ try {
91
+ const data = await octokit.graphql(query, variables);
92
+ return { data, byAlias: new Map(), unattributed: [] };
93
+ }
94
+ catch (err) {
95
+ if (isRateLimitOrAuthError(err) || isGraphqlRateLimited(err))
96
+ throw err;
97
+ const partial = err.data;
98
+ if (partial)
99
+ return { data: partial, ...partitionErrors(err) };
100
+ return { failure: errorMessage(err) };
101
+ }
102
+ }
103
+ function describeEntry(entry) {
104
+ return `${entry.type ?? 'GraphQL'}: ${entry.message ?? 'error'}`;
105
+ }
106
+ /**
107
+ * The outcome for one alias of a resolved batch. A null node is gone only
108
+ * when GitHub said NOT_FOUND for it, or returned no error at all; a null
109
+ * node in a response whose errors have no path (a server-side timeout, say)
110
+ * is a failure, not a missing issue.
111
+ */
112
+ function outcomeFor(chunk, alias) {
113
+ const node = chunk.data[alias]?.issueOrPullRequest;
114
+ if (node)
115
+ return node.__typename === 'PullRequest' ? { kind: 'pull_request' } : { kind: 'found', node };
116
+ const errors = chunk.byAlias.get(alias) ?? [];
117
+ const blocking = errors.find((e) => e.type !== 'NOT_FOUND');
118
+ if (blocking)
119
+ return { kind: 'failed', error: describeEntry(blocking) };
120
+ const notFound = errors[0];
121
+ if (notFound)
122
+ return { kind: 'gone', reason: `NOT_FOUND: ${notFound.message ?? ''}`.trim() };
123
+ const unattributed = chunk.unattributed[0];
124
+ if (unattributed)
125
+ return { kind: 'failed', error: describeEntry(unattributed) };
126
+ return { kind: 'gone', reason: 'not returned by GitHub' };
127
+ }
128
+ /** Record one batch's result, an outcome per ref; aliases index from `i0` within each query. */
129
+ function recordChunk(outcomes, batch, result) {
130
+ for (const [i, ref] of batch.entries()) {
131
+ outcomes.set(ref.url, 'failure' in result ? { kind: 'failed', error: result.failure } : outcomeFor(result, `i${i}`));
132
+ }
133
+ }
134
+ /**
135
+ * Look up every ref, one query per batch, sequentially (GitHub recommends
136
+ * serial GraphQL requests). A batch that fails outright (a 502, a network
137
+ * blip, a server-side timeout on a large query) is retried once as two
138
+ * half-size queries, so one bad response does not fail fifty issues; a half
139
+ * that fails again fails its refs. Returns an outcome per ref, keyed by URL.
140
+ *
141
+ * @throws The GraphQL error when it is a rate-limit or auth failure.
142
+ */
143
+ export async function lookupEngagedIssues(octokit, refs) {
144
+ const outcomes = new Map();
145
+ for (const batch of chunk(refs, ENGAGED_LOOKUP_BATCH_SIZE)) {
146
+ const result = await runChunk(octokit, batch);
147
+ if (!('failure' in result) || batch.length === 1) {
148
+ recordChunk(outcomes, batch, result);
149
+ continue;
150
+ }
151
+ const half = Math.ceil(batch.length / 2);
152
+ for (const part of [batch.slice(0, half), batch.slice(half)]) {
153
+ recordChunk(outcomes, part, await runChunk(octokit, part));
154
+ }
155
+ }
156
+ return outcomes;
157
+ }
@@ -8,7 +8,7 @@
8
8
  * ledger entry no older than {@link LEDGER_LINK_MAX_AGE_DAYS}. Plain
9
9
  * mentions in a PR body ("similar to #12", "see #4 for the upstream bug") are
10
10
  * not engagement: they named unrelated issues, bumped the engagement time
11
- * past earlier maintainer replies, and ate into the direct-fetch cap.
11
+ * past earlier maintainer replies, and ate into the comment-fetch cap.
12
12
  * `IssueConversationMonitor` scans engaged issues under a wider reply rule
13
13
  * (any substantive non-bot comment counts, not only maintainer or @mention
14
14
  * replies) and fetches the live ones directly when the commenter search does
@@ -85,8 +85,8 @@ export interface CollectEngagedIssuesOptions {
85
85
  * Links that do not parse as GitHub URLs, or that name one of the user's own
86
86
  * PRs, are skipped. Iteration order is strongest-reason first (engagements
87
87
  * are visited in that order, so an issue is inserted at its strongest
88
- * reason's position), so a caller that caps direct fetches keeps the open-PR
89
- * and claim issues.
88
+ * reason's position). The monitor looks every live entry up regardless of
89
+ * order; its comment-fetch cap ranks by the issue's own update time.
90
90
  */
91
91
  export declare function collectEngagedIssues(input: EngagedIssuesInput, options?: CollectEngagedIssuesOptions): Map<string, EngagedIssue>;
92
92
  /** The `IssueEngagement` projection of an engaged issue, for the digest entry. */
@@ -8,7 +8,7 @@
8
8
  * ledger entry no older than {@link LEDGER_LINK_MAX_AGE_DAYS}. Plain
9
9
  * mentions in a PR body ("similar to #12", "see #4 for the upstream bug") are
10
10
  * not engagement: they named unrelated issues, bumped the engagement time
11
- * past earlier maintainer replies, and ate into the direct-fetch cap.
11
+ * past earlier maintainer replies, and ate into the comment-fetch cap.
12
12
  * `IssueConversationMonitor` scans engaged issues under a wider reply rule
13
13
  * (any substantive non-bot comment counts, not only maintainer or @mention
14
14
  * replies) and fetches the live ones directly when the commenter search does
@@ -94,8 +94,8 @@ function* engagements(input, nowMs) {
94
94
  }
95
95
  /**
96
96
  * Keys of the user's own PRs. A closing keyword can name one of them
97
- * ("closes #50" on a follow-up to PR #50); that is not an issue, and fetching
98
- * it would spend one of the capped direct lookups to learn so.
97
+ * ("closes #50" on a follow-up to PR #50); that is not an issue, and looking
98
+ * it up would only confirm so.
99
99
  */
100
100
  function ownPRKeys(input) {
101
101
  const keys = new Set();
@@ -158,8 +158,8 @@ function record(byKey, engagement) {
158
158
  * Links that do not parse as GitHub URLs, or that name one of the user's own
159
159
  * PRs, are skipped. Iteration order is strongest-reason first (engagements
160
160
  * are visited in that order, so an issue is inserted at its strongest
161
- * reason's position), so a caller that caps direct fetches keeps the open-PR
162
- * and claim issues.
161
+ * reason's position). The monitor looks every live entry up regardless of
162
+ * order; its comment-fetch cap ranks by the issue's own update time.
163
163
  */
164
164
  export function collectEngagedIssues(input, options = {}) {
165
165
  const nowMs = (options.now ?? new Date()).getTime();