lastlight-core 0.32.2 → 0.33.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.
Files changed (71) hide show
  1. package/config/default.yaml +81 -0
  2. package/dist/admin/board-cache.d.ts +81 -0
  3. package/dist/admin/board-cache.js +303 -0
  4. package/dist/admin/board-cache.js.map +1 -0
  5. package/dist/admin/board-stream.d.ts +47 -0
  6. package/dist/admin/board-stream.js +45 -0
  7. package/dist/admin/board-stream.js.map +1 -0
  8. package/dist/admin/board.d.ts +284 -0
  9. package/dist/admin/board.js +369 -0
  10. package/dist/admin/board.js.map +1 -0
  11. package/dist/admin/routes.js +943 -13
  12. package/dist/admin/routes.js.map +1 -1
  13. package/dist/config/config.d.ts +88 -0
  14. package/dist/config/config.js +156 -0
  15. package/dist/config/config.js.map +1 -1
  16. package/dist/connectors/github-webhook.d.ts +16 -0
  17. package/dist/connectors/github-webhook.js +105 -8
  18. package/dist/connectors/github-webhook.js.map +1 -1
  19. package/dist/connectors/types.d.ts +9 -2
  20. package/dist/cron/issue-discovery.d.ts +120 -0
  21. package/dist/cron/issue-discovery.js +127 -0
  22. package/dist/cron/issue-discovery.js.map +1 -0
  23. package/dist/cron/runner.d.ts +25 -1
  24. package/dist/cron/runner.js +53 -10
  25. package/dist/cron/runner.js.map +1 -1
  26. package/dist/engine/build-decisions.d.ts +91 -0
  27. package/dist/engine/build-decisions.js +295 -0
  28. package/dist/engine/build-decisions.js.map +1 -0
  29. package/dist/engine/build-gate.d.ts +78 -0
  30. package/dist/engine/build-gate.js +423 -0
  31. package/dist/engine/build-gate.js.map +1 -0
  32. package/dist/engine/github/github.d.ts +213 -6
  33. package/dist/engine/github/github.js +340 -6
  34. package/dist/engine/github/github.js.map +1 -1
  35. package/dist/engine/pr-decisions.d.ts +23 -0
  36. package/dist/engine/pr-decisions.js.map +1 -1
  37. package/dist/engine/router.js +108 -1
  38. package/dist/engine/router.js.map +1 -1
  39. package/dist/engine/stage-advance.d.ts +92 -0
  40. package/dist/engine/stage-advance.js +129 -0
  41. package/dist/engine/stage-advance.js.map +1 -0
  42. package/dist/engine/stage-labels.d.ts +57 -0
  43. package/dist/engine/stage-labels.js +58 -0
  44. package/dist/engine/stage-labels.js.map +1 -0
  45. package/dist/engine/stage-observer.d.ts +79 -0
  46. package/dist/engine/stage-observer.js +221 -0
  47. package/dist/engine/stage-observer.js.map +1 -0
  48. package/dist/index.js +110 -2
  49. package/dist/index.js.map +1 -1
  50. package/dist/logging/phase-log.d.ts +6 -0
  51. package/dist/logging/phase-log.js +16 -0
  52. package/dist/logging/phase-log.js.map +1 -1
  53. package/dist/state/activity-store.d.ts +45 -1
  54. package/dist/state/activity-store.js +44 -0
  55. package/dist/state/activity-store.js.map +1 -1
  56. package/dist/state/execution-store.d.ts +48 -0
  57. package/dist/state/execution-store.js +112 -0
  58. package/dist/state/execution-store.js.map +1 -1
  59. package/dist/state/schema/pg.d.ts +2 -2
  60. package/dist/state/schema/sqlite.d.ts +2 -2
  61. package/dist/state/workflow-run-store.d.ts +75 -0
  62. package/dist/state/workflow-run-store.js +151 -7
  63. package/dist/state/workflow-run-store.js.map +1 -1
  64. package/dist/workflows/resume.js +45 -2
  65. package/dist/workflows/resume.js.map +1 -1
  66. package/dist/workflows/simple.d.ts +40 -1
  67. package/dist/workflows/simple.js +113 -2
  68. package/dist/workflows/simple.js.map +1 -1
  69. package/package.json +3 -3
  70. package/workflows/cron-autonomy.yaml +24 -0
  71. package/workflows/prompts/pr.md +18 -1
@@ -145,6 +145,79 @@ export interface RepoActivityItem {
145
145
  labels: string[];
146
146
  htmlUrl: string;
147
147
  }
148
+ /**
149
+ * A pull request that will close a board issue — GitHub's closing reference,
150
+ * which our PR template writes as `Closes #N` and a human can add by hand.
151
+ */
152
+ export interface BoardLinkedPr {
153
+ number: number;
154
+ url: string;
155
+ title: string;
156
+ /** `OPEN` | `CLOSED` | `MERGED`. */
157
+ state: string;
158
+ draft: boolean;
159
+ }
160
+ /**
161
+ * One open ISSUE as the BOARD reads it (`src/admin/board.ts`). The pipeline
162
+ * builds issues, so pull requests are never board items — a PR appears only as
163
+ * a {@link BoardLinkedPr} on the issue it closes.
164
+ *
165
+ * Deliberately not {@link RepoActivityItem}: the board is a projection of
166
+ * LABELS onto columns, so it needs each label's `color` and `description` (a
167
+ * chip has to render) where the digest needed only names, and it needs nothing
168
+ * about closure or merges because every item it sees is open.
169
+ */
170
+ export interface BoardItem {
171
+ /** Qualified `owner/repo` — the board spans repos, so the bare name is ambiguous. */
172
+ repo: string;
173
+ number: number;
174
+ title: string;
175
+ url: string;
176
+ author: string;
177
+ createdAt: string;
178
+ updatedAt: string;
179
+ labels: Array<{
180
+ name: string;
181
+ color: string;
182
+ description?: string;
183
+ }>;
184
+ /**
185
+ * Pull requests that close this issue, open or merged or closed. Empty on the
186
+ * throttled REST fallback, which does not read closing references.
187
+ */
188
+ linkedPrs: BoardLinkedPr[];
189
+ /**
190
+ * GitHub's `bodyText` — the markdown already flattened to prose, so an
191
+ * excerpt reads as a sentence rather than a slice of `<details>` scaffolding.
192
+ * Same field {@link DigestItemDetail} uses, for the same reason.
193
+ *
194
+ * TRUNCATED HERE, not by the reader. A board spans twenty repos at fifty
195
+ * items each, and a handful of essay-length issue bodies would dominate a
196
+ * payload whose whole design is a small response served from cache. The card
197
+ * shows two lines; 280 characters is comfortably more than that.
198
+ */
199
+ body: string;
200
+ }
201
+ /**
202
+ * One repo's slice of a {@link GitHubClient.listOpenBoardItems} answer.
203
+ *
204
+ * A failed repo is a VALUE here, never a throw: the board renders twenty repos
205
+ * and one of them 404ing (or the App losing its installation on that owner)
206
+ * must degrade that column's contents, not the request. The caller reports
207
+ * `error` as a `degraded` entry and keeps serving the rest.
208
+ *
209
+ * `fallback` says the items came from the REST path rather than the GraphQL
210
+ * search — fewer fields (a label has no colour there) and a bounded window —
211
+ * so the caller marks the repo degraded even though it has data.
212
+ * `throttled` says GitHub refused for rate-limit reasons, which is the signal
213
+ * the board cache backs off on.
214
+ */
215
+ export interface BoardRepoItems {
216
+ items: BoardItem[];
217
+ error?: string;
218
+ fallback?: boolean;
219
+ throttled?: boolean;
220
+ }
148
221
  /**
149
222
  * One issue or pull request with its text — the unit
150
223
  * {@link GitHubClient.listRepoDigestDetail} lists.
@@ -231,6 +304,17 @@ export interface ChecksQueryOptions {
231
304
  */
232
305
  excludeApp?: string;
233
306
  }
307
+ /**
308
+ * One item's body, flattened and clipped to {@link BOARD_EXCERPT_CHARS}.
309
+ *
310
+ * Clipped on the SERVER rather than by the card, because the cost being
311
+ * controlled is the payload: twenty repos x fifty items x an essay-length issue
312
+ * body is a response whose whole design is "small enough to serve from cache
313
+ * every twenty seconds". Whitespace is collapsed first so the clip lands on
314
+ * prose rather than in the middle of a blank line, and a clipped string gets an
315
+ * ellipsis so the card never has to guess whether it is seeing all of it.
316
+ */
317
+ export declare function boardExcerpt(bodyText: string | null | undefined): string;
234
318
  /**
235
319
  * Raised when a harness-side call targets an account the GitHub App is not
236
320
  * installed on. Distinct from a 404 so callers can say the actionable thing
@@ -301,13 +385,17 @@ export declare class GitHubClient {
301
385
  /**
302
386
  * Add labels to an issue/PR, leaving existing labels alone.
303
387
  *
304
- * The only harness-side label WRITE. Every other label mutation in the system
305
- * happens INSIDE the sandbox, through agentic-pi's `github_*` tools driven
306
- * from a prompt — which is the right place for a label whose value is an
307
- * agent's judgement (`dependency-trivial`, the triage vocabulary). This one
308
- * is different in kind: the dispatch-time escalation
388
+ * One of exactly TWO harness-side label WRITEs — {@link removeLabel} is the
389
+ * other, and it arrived with the software-factory stage pipeline. Every other
390
+ * label mutation in the system happens INSIDE the sandbox, through
391
+ * agentic-pi's `github_*` tools driven from a prompt — which is the right
392
+ * place for a label whose value is an agent's judgement
393
+ * (`dependency-trivial`, the triage vocabulary). These two are different in
394
+ * kind, and different for the same reason: both fire at a moment when there
395
+ * is no sandbox and no agent to ask. The dispatch-time escalation
309
396
  * (`../pr-escalation.ts`) fires precisely when we have decided NOT to
310
- * provision a sandbox, so there is no agent to ask.
397
+ * provision a sandbox; the stage advance (`../stage-advance.ts`) fires at the
398
+ * dispatch choke point itself, BEFORE one has been provisioned.
311
399
  *
312
400
  * GitHub's own endpoint creates a label that does not exist yet (with an
313
401
  * arbitrary colour), so there is no `ensureLabels` companion to write.
@@ -316,6 +404,32 @@ export declare class GitHubClient {
316
404
  * `../pr-escalation.ts` for the record that does.
317
405
  */
318
406
  addLabels(owner: string, repo: string, issueNumber: number, labels: string[]): Promise<void>;
407
+ /**
408
+ * Remove ONE label from an issue/PR, leaving every other label alone.
409
+ *
410
+ * The second of the two harness-side label writes (see {@link addLabels}),
411
+ * and the load-bearing half of the software-factory stage pipeline: the
412
+ * stage label IS the source of truth for where an issue has got to, and the
413
+ * ENTRY label (`ready-for-agent`) must come off BEFORE the run it triggered
414
+ * starts. That ordering is not cosmetic. The backstop cron sweep finds work
415
+ * by querying `label:ready-for-agent`; if the label is still there while the
416
+ * run is in flight, the sweep is structurally able to re-pick an issue that
417
+ * was already dispatched, and re-pick it again on the next tick. This repo
418
+ * has a recorded production incident of exactly that shape — a cron gated on
419
+ * a signal the work never wrote, every run reporting `succeeded` while it
420
+ * burned roughly $1.30/hour. Removing the entry label at dispatch is what
421
+ * makes the re-pick impossible rather than merely unlikely.
422
+ *
423
+ * **A missing label is a 404, and a 404 here is success.** GitHub answers
424
+ * `404` when the label is not on the issue (and also when the label does not
425
+ * exist in the repo at all). Either way the desired end state — "this label
426
+ * is not on this issue" — already holds, so removing an absent label is a
427
+ * no-op and we swallow that ONE status. Everything else (403 from a
428
+ * downscoped token, 5xx, a network failure) propagates: a blanket catch here
429
+ * would turn "we could not take the entry label off" into silence, which is
430
+ * precisely the re-dispatch loop above.
431
+ */
432
+ removeLabel(owner: string, repo: string, issueNumber: number, label: string): Promise<void>;
319
433
  /**
320
434
  * List every repository ONE installation can access, as `owner/repo` full
321
435
  * names. Paginated — handles installs with hundreds of repos.
@@ -1525,6 +1639,99 @@ export declare class GitHubClient {
1525
1639
  headSha: string;
1526
1640
  createdAt: string;
1527
1641
  }>>;
1642
+ /**
1643
+ * The repo's OPEN ISSUES carrying `label`, as light records (number / title /
1644
+ * labels / created-at).
1645
+ *
1646
+ * The autonomy backstop sweep's one GitHub read (`cron/issue-discovery.ts`):
1647
+ * it asks GitHub to do the filtering — `state: "open"` + `labels:` are both
1648
+ * server-side — so a repo with thousands of issues costs one page, not a walk.
1649
+ * `labels` rides the same response, which is what lets the discoverer exclude
1650
+ * a partially-advanced issue (one carrying the stage's `running` label as well
1651
+ * as its `enter` label) without a second call, and what lets the dispatch gate
1652
+ * read the hold label off the candidate it was handed.
1653
+ *
1654
+ * **A PULL REQUEST IS NEVER RETURNED.** `GET /repos/{o}/{r}/issues` returns
1655
+ * pull requests alongside issues — a PR *is* an issue to this API, and it
1656
+ * carries the same labels — so an unfiltered response would offer PRs to a
1657
+ * pipeline that dispatches `build` runs against an ISSUE number. That would
1658
+ * not fail loudly; it would clone the repo and set an agent to work on a
1659
+ * "feature request" that is somebody's open pull request. `item.pull_request`
1660
+ * is present on exactly those items and absent on real issues, so it is the
1661
+ * discriminator (the same one `listRepoActivitySince` uses to set `isPr`).
1662
+ *
1663
+ * Page-bounded to `maxPages` (3 × 100 = 300 items) for the same reason
1664
+ * `listRepoActivitySince` is: an unbounded paginate here runs per repo on
1665
+ * every tick, which is a rate-limit hazard, and a repo with 300 open issues
1666
+ * sitting at one stage label has a queue problem rather than a paging one.
1667
+ * Oldest first, so the caller's per-repo cap is stable across ticks rather
1668
+ * than starving the same tail.
1669
+ */
1670
+ listOpenIssuesByLabel(owner: string, repo: string, label: string, opts?: {
1671
+ maxPages?: number;
1672
+ }): Promise<Array<{
1673
+ number: number;
1674
+ title: string;
1675
+ labels: string[];
1676
+ createdAt: string;
1677
+ }>>;
1678
+ /**
1679
+ * Every OPEN issue across `repos`, for the board, each with the pull requests
1680
+ * that close it. Pull requests are excluded at the query (`is:issue`): the
1681
+ * pipeline builds issues, and a PR shows only as a link on its issue.
1682
+ *
1683
+ * ## The rate-limit budget is what decides this method's shape
1684
+ *
1685
+ * The obvious implementation — `issues.listForRepo` per repo, per poll — does
1686
+ * not survive contact with the numbers. A dashboard polling at 15 s over 20
1687
+ * repos is ~4,800 requests an hour, and each open tab multiplies it; the
1688
+ * installation's 5,000/hr budget is the SAME budget the harness spends
1689
+ * reviewing pull requests and fixing CI, so a board left open would starve the
1690
+ * work it exists to display. That version must not ship.
1691
+ *
1692
+ * So: ONE GraphQL document per batch of up to ten repos, each an aliased
1693
+ * `search(type: ISSUE, query: "repo:o/r is:open is:issue")` block. That is the idiom
1694
+ * {@link listRepoDigestDetail} already uses for its three aliased searches —
1695
+ * aliases ride one request and one rate-limit point between them. Twenty
1696
+ * repos therefore cost TWO requests per refresh, and with the board cache's
1697
+ * 120 s TTL in front (`src/admin/board-cache.ts`) the steady state is ~60
1698
+ * requests an hour **regardless of how many dashboards are open**.
1699
+ *
1700
+ * ## Batched by OWNER, because the token is
1701
+ *
1702
+ * {@link kit} resolves a per-OWNER installation and each installation mints
1703
+ * its own token, so a single document can only span repos of one account.
1704
+ * The caller groups by owner; this method takes the owner explicitly and
1705
+ * treats `repos` as bare names under it.
1706
+ *
1707
+ * ## `search` is subject to SECONDARY limits, which the point budget does not
1708
+ * describe
1709
+ *
1710
+ * GitHub throttles search independently of the documented points, with no
1711
+ * warning in the response headers. A throttle therefore falls back to
1712
+ * {@link listRepoActivitySince} (`maxPages: 1`) per repo and marks the result
1713
+ * `fallback` + `throttled`: the board degrades to a bounded, slightly
1714
+ * lossy view of the repo rather than showing an empty column, and the cache
1715
+ * reads `throttled` as its cue to back off that owner.
1716
+ *
1717
+ * Keyed by the QUALIFIED `owner/repo` so the caller can index one map across
1718
+ * every owner it asked about.
1719
+ */
1720
+ listOpenBoardItems(owner: string, repos: string[], opts?: {
1721
+ first?: number;
1722
+ batchSize?: number;
1723
+ }): Promise<Map<string, BoardRepoItems>>;
1724
+ /** The aliased-search half of {@link listOpenBoardItems}. One request. */
1725
+ private searchOpenBoardItems;
1726
+ /**
1727
+ * The REST fallback for ONE repo when search is throttled.
1728
+ *
1729
+ * Bounded to a single page and to items still open. It is lossy on purpose:
1730
+ * `listRepoActivitySince` filters on `updated_at`, so an open issue nobody has
1731
+ * touched in the window is missing, and its labels carry no colour. A board
1732
+ * that says so (`degraded`) beats a board that shows an empty column.
1733
+ */
1734
+ private restBoardFallback;
1528
1735
  /**
1529
1736
  * What happened in a repo between `sinceIso` and now — issues AND pull
1530
1737
  * requests, opened / closed / merged.
@@ -6,6 +6,40 @@ const log = logger("github");
6
6
  const REPO_CONFIG_DIR = ".lastlight";
7
7
  const REPO_CONFIG_DEFAULT_MAX_FILES = 200;
8
8
  const REPO_CONFIG_DEFAULT_MAX_BYTES = 2 * 1024 * 1024;
9
+ /** How much of an item's body the board carries. Two rendered lines, with room. */
10
+ const BOARD_EXCERPT_CHARS = 280;
11
+ /**
12
+ * One item's body, flattened and clipped to {@link BOARD_EXCERPT_CHARS}.
13
+ *
14
+ * Clipped on the SERVER rather than by the card, because the cost being
15
+ * controlled is the payload: twenty repos x fifty items x an essay-length issue
16
+ * body is a response whose whole design is "small enough to serve from cache
17
+ * every twenty seconds". Whitespace is collapsed first so the clip lands on
18
+ * prose rather than in the middle of a blank line, and a clipped string gets an
19
+ * ellipsis so the card never has to guess whether it is seeing all of it.
20
+ */
21
+ export function boardExcerpt(bodyText) {
22
+ const flat = (bodyText ?? "").replace(/\s+/g, " ").trim();
23
+ if (flat.length <= BOARD_EXCERPT_CHARS)
24
+ return flat;
25
+ return `${flat.slice(0, BOARD_EXCERPT_CHARS).trimEnd()}…`;
26
+ }
27
+ /**
28
+ * Did GitHub refuse this for rate-limit reasons?
29
+ *
30
+ * Secondary limits are the hazard the board has to survive, and they do NOT
31
+ * arrive as a documented point exhaustion: they surface as a 403 or 429 whose
32
+ * prose names abuse detection or a secondary limit. Both codes and the prose
33
+ * are checked, because the shape has changed before and a missed throttle costs
34
+ * the fallback that keeps the board readable.
35
+ */
36
+ function isThrottleError(err) {
37
+ const status = err?.status;
38
+ if (status === 429 || status === 403)
39
+ return true;
40
+ const message = err instanceof Error ? err.message : String(err ?? "");
41
+ return /secondary rate limit|abuse detection|rate limit|too many requests/i.test(message);
42
+ }
9
43
  /** octokit surfaces HTTP failures as errors carrying the numeric `status`. */
10
44
  function httpStatus(err) {
11
45
  const status = err?.status;
@@ -180,13 +214,17 @@ export class GitHubClient {
180
214
  /**
181
215
  * Add labels to an issue/PR, leaving existing labels alone.
182
216
  *
183
- * The only harness-side label WRITE. Every other label mutation in the system
184
- * happens INSIDE the sandbox, through agentic-pi's `github_*` tools driven
185
- * from a prompt — which is the right place for a label whose value is an
186
- * agent's judgement (`dependency-trivial`, the triage vocabulary). This one
187
- * is different in kind: the dispatch-time escalation
217
+ * One of exactly TWO harness-side label WRITEs — {@link removeLabel} is the
218
+ * other, and it arrived with the software-factory stage pipeline. Every other
219
+ * label mutation in the system happens INSIDE the sandbox, through
220
+ * agentic-pi's `github_*` tools driven from a prompt — which is the right
221
+ * place for a label whose value is an agent's judgement
222
+ * (`dependency-trivial`, the triage vocabulary). These two are different in
223
+ * kind, and different for the same reason: both fire at a moment when there
224
+ * is no sandbox and no agent to ask. The dispatch-time escalation
188
225
  * (`../pr-escalation.ts`) fires precisely when we have decided NOT to
189
- * provision a sandbox, so there is no agent to ask.
226
+ * provision a sandbox; the stage advance (`../stage-advance.ts`) fires at the
227
+ * dispatch choke point itself, BEFORE one has been provisioned.
190
228
  *
191
229
  * GitHub's own endpoint creates a label that does not exist yet (with an
192
230
  * arbitrary colour), so there is no `ensureLabels` companion to write.
@@ -205,6 +243,50 @@ export class GitHubClient {
205
243
  labels,
206
244
  });
207
245
  }
246
+ /**
247
+ * Remove ONE label from an issue/PR, leaving every other label alone.
248
+ *
249
+ * The second of the two harness-side label writes (see {@link addLabels}),
250
+ * and the load-bearing half of the software-factory stage pipeline: the
251
+ * stage label IS the source of truth for where an issue has got to, and the
252
+ * ENTRY label (`ready-for-agent`) must come off BEFORE the run it triggered
253
+ * starts. That ordering is not cosmetic. The backstop cron sweep finds work
254
+ * by querying `label:ready-for-agent`; if the label is still there while the
255
+ * run is in flight, the sweep is structurally able to re-pick an issue that
256
+ * was already dispatched, and re-pick it again on the next tick. This repo
257
+ * has a recorded production incident of exactly that shape — a cron gated on
258
+ * a signal the work never wrote, every run reporting `succeeded` while it
259
+ * burned roughly $1.30/hour. Removing the entry label at dispatch is what
260
+ * makes the re-pick impossible rather than merely unlikely.
261
+ *
262
+ * **A missing label is a 404, and a 404 here is success.** GitHub answers
263
+ * `404` when the label is not on the issue (and also when the label does not
264
+ * exist in the repo at all). Either way the desired end state — "this label
265
+ * is not on this issue" — already holds, so removing an absent label is a
266
+ * no-op and we swallow that ONE status. Everything else (403 from a
267
+ * downscoped token, 5xx, a network failure) propagates: a blanket catch here
268
+ * would turn "we could not take the entry label off" into silence, which is
269
+ * precisely the re-dispatch loop above.
270
+ */
271
+ async removeLabel(owner, repo, issueNumber, label) {
272
+ if (!label)
273
+ return;
274
+ const kit = await this.kit(owner);
275
+ try {
276
+ await kit.rest.issues.removeLabel({
277
+ owner,
278
+ repo,
279
+ issue_number: issueNumber,
280
+ name: label,
281
+ });
282
+ }
283
+ catch (err) {
284
+ // The one status that means "already in the desired state".
285
+ if (httpStatus(err) === 404)
286
+ return;
287
+ throw err;
288
+ }
289
+ }
208
290
  /**
209
291
  * List every repository ONE installation can access, as `owner/repo` full
210
292
  * names. Paginated — handles installs with hundreds of repos.
@@ -581,6 +663,258 @@ export class GitHubClient {
581
663
  createdAt: p.created_at ?? "",
582
664
  }));
583
665
  }
666
+ /**
667
+ * The repo's OPEN ISSUES carrying `label`, as light records (number / title /
668
+ * labels / created-at).
669
+ *
670
+ * The autonomy backstop sweep's one GitHub read (`cron/issue-discovery.ts`):
671
+ * it asks GitHub to do the filtering — `state: "open"` + `labels:` are both
672
+ * server-side — so a repo with thousands of issues costs one page, not a walk.
673
+ * `labels` rides the same response, which is what lets the discoverer exclude
674
+ * a partially-advanced issue (one carrying the stage's `running` label as well
675
+ * as its `enter` label) without a second call, and what lets the dispatch gate
676
+ * read the hold label off the candidate it was handed.
677
+ *
678
+ * **A PULL REQUEST IS NEVER RETURNED.** `GET /repos/{o}/{r}/issues` returns
679
+ * pull requests alongside issues — a PR *is* an issue to this API, and it
680
+ * carries the same labels — so an unfiltered response would offer PRs to a
681
+ * pipeline that dispatches `build` runs against an ISSUE number. That would
682
+ * not fail loudly; it would clone the repo and set an agent to work on a
683
+ * "feature request" that is somebody's open pull request. `item.pull_request`
684
+ * is present on exactly those items and absent on real issues, so it is the
685
+ * discriminator (the same one `listRepoActivitySince` uses to set `isPr`).
686
+ *
687
+ * Page-bounded to `maxPages` (3 × 100 = 300 items) for the same reason
688
+ * `listRepoActivitySince` is: an unbounded paginate here runs per repo on
689
+ * every tick, which is a rate-limit hazard, and a repo with 300 open issues
690
+ * sitting at one stage label has a queue problem rather than a paging one.
691
+ * Oldest first, so the caller's per-repo cap is stable across ticks rather
692
+ * than starving the same tail.
693
+ */
694
+ async listOpenIssuesByLabel(owner, repo, label, opts = {}) {
695
+ const kit = await this.kit(owner);
696
+ const maxPages = opts.maxPages ?? 3;
697
+ const items = [];
698
+ for (let page = 1; page <= maxPages; page++) {
699
+ const { data } = await kit.rest.issues.listForRepo({
700
+ owner,
701
+ repo,
702
+ state: "open",
703
+ labels: label,
704
+ sort: "created",
705
+ direction: "asc",
706
+ per_page: 100,
707
+ page,
708
+ });
709
+ for (const item of data) {
710
+ // See the header: this endpoint returns PRs as issues, and a pull
711
+ // request reaching the build pipeline would be badly wrong.
712
+ if (item.pull_request)
713
+ continue;
714
+ items.push({
715
+ number: item.number,
716
+ title: item.title ?? "",
717
+ labels: (item.labels ?? [])
718
+ .map((l) => (typeof l === "string" ? l : l.name ?? ""))
719
+ .filter(Boolean),
720
+ createdAt: item.created_at,
721
+ });
722
+ }
723
+ if (data.length < 100)
724
+ break;
725
+ }
726
+ return items;
727
+ }
728
+ /**
729
+ * Every OPEN issue across `repos`, for the board, each with the pull requests
730
+ * that close it. Pull requests are excluded at the query (`is:issue`): the
731
+ * pipeline builds issues, and a PR shows only as a link on its issue.
732
+ *
733
+ * ## The rate-limit budget is what decides this method's shape
734
+ *
735
+ * The obvious implementation — `issues.listForRepo` per repo, per poll — does
736
+ * not survive contact with the numbers. A dashboard polling at 15 s over 20
737
+ * repos is ~4,800 requests an hour, and each open tab multiplies it; the
738
+ * installation's 5,000/hr budget is the SAME budget the harness spends
739
+ * reviewing pull requests and fixing CI, so a board left open would starve the
740
+ * work it exists to display. That version must not ship.
741
+ *
742
+ * So: ONE GraphQL document per batch of up to ten repos, each an aliased
743
+ * `search(type: ISSUE, query: "repo:o/r is:open is:issue")` block. That is the idiom
744
+ * {@link listRepoDigestDetail} already uses for its three aliased searches —
745
+ * aliases ride one request and one rate-limit point between them. Twenty
746
+ * repos therefore cost TWO requests per refresh, and with the board cache's
747
+ * 120 s TTL in front (`src/admin/board-cache.ts`) the steady state is ~60
748
+ * requests an hour **regardless of how many dashboards are open**.
749
+ *
750
+ * ## Batched by OWNER, because the token is
751
+ *
752
+ * {@link kit} resolves a per-OWNER installation and each installation mints
753
+ * its own token, so a single document can only span repos of one account.
754
+ * The caller groups by owner; this method takes the owner explicitly and
755
+ * treats `repos` as bare names under it.
756
+ *
757
+ * ## `search` is subject to SECONDARY limits, which the point budget does not
758
+ * describe
759
+ *
760
+ * GitHub throttles search independently of the documented points, with no
761
+ * warning in the response headers. A throttle therefore falls back to
762
+ * {@link listRepoActivitySince} (`maxPages: 1`) per repo and marks the result
763
+ * `fallback` + `throttled`: the board degrades to a bounded, slightly
764
+ * lossy view of the repo rather than showing an empty column, and the cache
765
+ * reads `throttled` as its cue to back off that owner.
766
+ *
767
+ * Keyed by the QUALIFIED `owner/repo` so the caller can index one map across
768
+ * every owner it asked about.
769
+ */
770
+ async listOpenBoardItems(owner, repos, opts = {}) {
771
+ const out = new Map();
772
+ const names = [...new Set(repos.filter((r) => !!r))];
773
+ if (names.length === 0)
774
+ return out;
775
+ // Search caps a page at 100. 50 is the board's per-repo ceiling: a repo with
776
+ // more than fifty open items has a queue problem, not a paging one, and the
777
+ // column would be unreadable either way.
778
+ const first = Math.min(Math.max(opts.first ?? 50, 1), 100);
779
+ // Ten aliases per document — enough to make twenty repos two requests,
780
+ // small enough that one hostile repo's page size can't blow the response.
781
+ const batchSize = Math.min(Math.max(opts.batchSize ?? 10, 1), 10);
782
+ for (let i = 0; i < names.length; i += batchSize) {
783
+ const batch = names.slice(i, i + batchSize);
784
+ try {
785
+ const results = await this.searchOpenBoardItems(owner, batch, first);
786
+ for (const [repo, items] of results)
787
+ out.set(repo, { items });
788
+ }
789
+ catch (err) {
790
+ const throttled = isThrottleError(err);
791
+ const message = err instanceof Error ? err.message : String(err);
792
+ log.warn("board search failed", { owner, repos: batch, throttled, err });
793
+ // Per-repo REST fallback. Only worth the requests on a throttle: any
794
+ // other failure (a dead installation, a 5xx) would fail the same way
795
+ // again, and spending ten more requests to prove it is the opposite of
796
+ // what a rate-limit hazard wants.
797
+ for (const repo of batch) {
798
+ const key = `${owner}/${repo}`;
799
+ if (!throttled) {
800
+ out.set(key, { items: [], error: message });
801
+ continue;
802
+ }
803
+ try {
804
+ out.set(key, {
805
+ items: await this.restBoardFallback(owner, repo),
806
+ error: `GitHub search was throttled; showing a bounded REST view (${message})`,
807
+ fallback: true,
808
+ throttled: true,
809
+ });
810
+ }
811
+ catch (fallbackErr) {
812
+ out.set(key, {
813
+ items: [],
814
+ error: fallbackErr instanceof Error ? fallbackErr.message : String(fallbackErr),
815
+ throttled: true,
816
+ });
817
+ }
818
+ }
819
+ }
820
+ }
821
+ return out;
822
+ }
823
+ /** The aliased-search half of {@link listOpenBoardItems}. One request. */
824
+ async searchOpenBoardItems(owner, repos, first) {
825
+ const kit = await this.kit(owner);
826
+ // The document is built from the batch because the alias count varies.
827
+ // `__typename` is what splits an Issue from a PullRequest — `search` returns
828
+ // both for `type: ISSUE` and the board colours them differently.
829
+ const params = repos.map((_, idx) => `$q${idx}: String!`).join(", ");
830
+ const blocks = repos
831
+ .map((_, idx) => `r${idx}: search(query: $q${idx}, type: ISSUE, first: $first) {
832
+ nodes {
833
+ __typename
834
+ ... on Issue {
835
+ number title url createdAt updatedAt bodyText
836
+ author { login }
837
+ labels(first: 10) { nodes { name color description } }
838
+ closedByPullRequestsReferences(first: 5, includeClosedPrs: true) {
839
+ nodes { number url title state isDraft }
840
+ }
841
+ }
842
+ }
843
+ }`)
844
+ .join("\n ");
845
+ const variables = { first };
846
+ repos.forEach((repo, idx) => {
847
+ variables[`q${idx}`] = `repo:${owner}/${repo} is:open is:issue`;
848
+ });
849
+ const res = await kit.graphql(`query(${params}, $first: Int!) {
850
+ ${blocks}
851
+ }`, variables);
852
+ const out = new Map();
853
+ repos.forEach((repo, idx) => {
854
+ const nodes = res[`r${idx}`]?.nodes ?? [];
855
+ out.set(`${owner}/${repo}`, nodes
856
+ // `is:issue` already excludes pull requests; the typename check keeps
857
+ // one out even if the query is ever widened.
858
+ .filter((n) => !!n && typeof n.number === "number" && n.__typename !== "PullRequest")
859
+ .map((n) => ({
860
+ repo: `${owner}/${repo}`,
861
+ number: n.number,
862
+ title: n.title ?? "",
863
+ url: n.url ?? "",
864
+ author: n.author?.login ?? "",
865
+ createdAt: n.createdAt ?? "",
866
+ updatedAt: n.updatedAt ?? n.createdAt ?? "",
867
+ body: boardExcerpt(n.bodyText),
868
+ linkedPrs: (n.closedByPullRequestsReferences?.nodes ?? [])
869
+ .filter((pr) => !!pr && typeof pr.number === "number")
870
+ .map((pr) => ({
871
+ number: pr.number,
872
+ url: pr.url ?? "",
873
+ title: pr.title ?? "",
874
+ state: pr.state ?? "OPEN",
875
+ draft: !!pr.isDraft,
876
+ })),
877
+ labels: (n.labels?.nodes ?? [])
878
+ .filter((l) => !!l?.name)
879
+ .map((l) => ({
880
+ name: l.name,
881
+ color: l.color ?? "",
882
+ description: l.description ?? undefined,
883
+ })),
884
+ })));
885
+ });
886
+ return out;
887
+ }
888
+ /**
889
+ * The REST fallback for ONE repo when search is throttled.
890
+ *
891
+ * Bounded to a single page and to items still open. It is lossy on purpose:
892
+ * `listRepoActivitySince` filters on `updated_at`, so an open issue nobody has
893
+ * touched in the window is missing, and its labels carry no colour. A board
894
+ * that says so (`degraded`) beats a board that shows an empty column.
895
+ */
896
+ async restBoardFallback(owner, repo) {
897
+ const since = new Date(Date.now() - 90 * 24 * 60 * 60 * 1000).toISOString();
898
+ const items = await this.listRepoActivitySince(owner, repo, since, { maxPages: 1 });
899
+ return items
900
+ .filter((item) => !item.closedAt && !item.isPr)
901
+ .map((item) => ({
902
+ repo: `${owner}/${repo}`,
903
+ number: item.number,
904
+ title: item.title,
905
+ url: item.htmlUrl,
906
+ author: item.authorLogin,
907
+ createdAt: item.createdAt,
908
+ updatedAt: item.createdAt,
909
+ // Closing references need GraphQL — the degraded view goes without.
910
+ linkedPrs: [],
911
+ labels: item.labels.map((name) => ({ name, color: "" })),
912
+ // The REST list carries a `body`, but this path exists because GitHub
913
+ // just throttled us — it is the degraded answer, and the card renders
914
+ // without an excerpt rather than paying more requests for one.
915
+ body: "",
916
+ }));
917
+ }
584
918
  /**
585
919
  * What happened in a repo between `sinceIso` and now — issues AND pull
586
920
  * requests, opened / closed / merged.