lastlight-core 0.32.1 → 0.33.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 (74) 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 +301 -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 +264 -0
  9. package/dist/admin/board.js +376 -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 +163 -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 +104 -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 +355 -0
  31. package/dist/engine/build-gate.js.map +1 -0
  32. package/dist/engine/executors/shared.d.ts +1 -0
  33. package/dist/engine/executors/shared.js +13 -2
  34. package/dist/engine/executors/shared.js.map +1 -1
  35. package/dist/engine/github/github-app-client.js +25 -1
  36. package/dist/engine/github/github-app-client.js.map +1 -1
  37. package/dist/engine/github/github.d.ts +195 -6
  38. package/dist/engine/github/github.js +331 -6
  39. package/dist/engine/github/github.js.map +1 -1
  40. package/dist/engine/pr-decisions.d.ts +23 -0
  41. package/dist/engine/pr-decisions.js.map +1 -1
  42. package/dist/engine/router.js +108 -1
  43. package/dist/engine/router.js.map +1 -1
  44. package/dist/engine/stage-advance.d.ts +92 -0
  45. package/dist/engine/stage-advance.js +129 -0
  46. package/dist/engine/stage-advance.js.map +1 -0
  47. package/dist/engine/stage-labels.d.ts +57 -0
  48. package/dist/engine/stage-labels.js +58 -0
  49. package/dist/engine/stage-labels.js.map +1 -0
  50. package/dist/engine/stage-observer.d.ts +79 -0
  51. package/dist/engine/stage-observer.js +221 -0
  52. package/dist/engine/stage-observer.js.map +1 -0
  53. package/dist/index.js +110 -2
  54. package/dist/index.js.map +1 -1
  55. package/dist/logging/phase-log.d.ts +6 -0
  56. package/dist/logging/phase-log.js +16 -0
  57. package/dist/logging/phase-log.js.map +1 -1
  58. package/dist/state/activity-store.d.ts +45 -1
  59. package/dist/state/activity-store.js +44 -0
  60. package/dist/state/activity-store.js.map +1 -1
  61. package/dist/state/execution-store.d.ts +48 -0
  62. package/dist/state/execution-store.js +112 -0
  63. package/dist/state/execution-store.js.map +1 -1
  64. package/dist/state/schema/pg.d.ts +2 -2
  65. package/dist/state/schema/sqlite.d.ts +2 -2
  66. package/dist/state/workflow-run-store.d.ts +51 -0
  67. package/dist/state/workflow-run-store.js +98 -0
  68. package/dist/state/workflow-run-store.js.map +1 -1
  69. package/dist/workflows/simple.d.ts +40 -1
  70. package/dist/workflows/simple.js +113 -2
  71. package/dist/workflows/simple.js.map +1 -1
  72. package/package.json +4 -4
  73. package/workflows/cron-autonomy.yaml +24 -0
  74. package/workflows/prompts/pr.md +18 -1
@@ -145,6 +145,63 @@ export interface RepoActivityItem {
145
145
  labels: string[];
146
146
  htmlUrl: string;
147
147
  }
148
+ /**
149
+ * One open issue or pull request as the BOARD reads it (`src/admin/board.ts`).
150
+ *
151
+ * Deliberately not {@link RepoActivityItem}: the board is a projection of
152
+ * LABELS onto columns, so it needs each label's `color` and `description` (a
153
+ * chip has to render) where the digest needed only names, and it needs nothing
154
+ * about closure or merges because every item it sees is open.
155
+ */
156
+ export interface BoardItem {
157
+ /** Qualified `owner/repo` — the board spans repos, so the bare name is ambiguous. */
158
+ repo: string;
159
+ number: number;
160
+ /** True when this item is a pull request rather than an issue. */
161
+ isPr: boolean;
162
+ title: string;
163
+ url: string;
164
+ author: string;
165
+ createdAt: string;
166
+ updatedAt: string;
167
+ draft: boolean;
168
+ labels: Array<{
169
+ name: string;
170
+ color: string;
171
+ description?: string;
172
+ }>;
173
+ /**
174
+ * GitHub's `bodyText` — the markdown already flattened to prose, so an
175
+ * excerpt reads as a sentence rather than a slice of `<details>` scaffolding.
176
+ * Same field {@link DigestItemDetail} uses, for the same reason.
177
+ *
178
+ * TRUNCATED HERE, not by the reader. A board spans twenty repos at fifty
179
+ * items each, and a handful of essay-length issue bodies would dominate a
180
+ * payload whose whole design is a small response served from cache. The card
181
+ * shows two lines; 280 characters is comfortably more than that.
182
+ */
183
+ body: string;
184
+ }
185
+ /**
186
+ * One repo's slice of a {@link GitHubClient.listOpenBoardItems} answer.
187
+ *
188
+ * A failed repo is a VALUE here, never a throw: the board renders twenty repos
189
+ * and one of them 404ing (or the App losing its installation on that owner)
190
+ * must degrade that column's contents, not the request. The caller reports
191
+ * `error` as a `degraded` entry and keeps serving the rest.
192
+ *
193
+ * `fallback` says the items came from the REST path rather than the GraphQL
194
+ * search — fewer fields (a label has no colour there) and a bounded window —
195
+ * so the caller marks the repo degraded even though it has data.
196
+ * `throttled` says GitHub refused for rate-limit reasons, which is the signal
197
+ * the board cache backs off on.
198
+ */
199
+ export interface BoardRepoItems {
200
+ items: BoardItem[];
201
+ error?: string;
202
+ fallback?: boolean;
203
+ throttled?: boolean;
204
+ }
148
205
  /**
149
206
  * One issue or pull request with its text — the unit
150
207
  * {@link GitHubClient.listRepoDigestDetail} lists.
@@ -231,6 +288,17 @@ export interface ChecksQueryOptions {
231
288
  */
232
289
  excludeApp?: string;
233
290
  }
291
+ /**
292
+ * One item's body, flattened and clipped to {@link BOARD_EXCERPT_CHARS}.
293
+ *
294
+ * Clipped on the SERVER rather than by the card, because the cost being
295
+ * controlled is the payload: twenty repos x fifty items x an essay-length issue
296
+ * body is a response whose whole design is "small enough to serve from cache
297
+ * every twenty seconds". Whitespace is collapsed first so the clip lands on
298
+ * prose rather than in the middle of a blank line, and a clipped string gets an
299
+ * ellipsis so the card never has to guess whether it is seeing all of it.
300
+ */
301
+ export declare function boardExcerpt(bodyText: string | null | undefined): string;
234
302
  /**
235
303
  * Raised when a harness-side call targets an account the GitHub App is not
236
304
  * installed on. Distinct from a 404 so callers can say the actionable thing
@@ -301,13 +369,17 @@ export declare class GitHubClient {
301
369
  /**
302
370
  * Add labels to an issue/PR, leaving existing labels alone.
303
371
  *
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
372
+ * One of exactly TWO harness-side label WRITEs — {@link removeLabel} is the
373
+ * other, and it arrived with the software-factory stage pipeline. Every other
374
+ * label mutation in the system happens INSIDE the sandbox, through
375
+ * agentic-pi's `github_*` tools driven from a prompt — which is the right
376
+ * place for a label whose value is an agent's judgement
377
+ * (`dependency-trivial`, the triage vocabulary). These two are different in
378
+ * kind, and different for the same reason: both fire at a moment when there
379
+ * is no sandbox and no agent to ask. The dispatch-time escalation
309
380
  * (`../pr-escalation.ts`) fires precisely when we have decided NOT to
310
- * provision a sandbox, so there is no agent to ask.
381
+ * provision a sandbox; the stage advance (`../stage-advance.ts`) fires at the
382
+ * dispatch choke point itself, BEFORE one has been provisioned.
311
383
  *
312
384
  * GitHub's own endpoint creates a label that does not exist yet (with an
313
385
  * arbitrary colour), so there is no `ensureLabels` companion to write.
@@ -316,6 +388,32 @@ export declare class GitHubClient {
316
388
  * `../pr-escalation.ts` for the record that does.
317
389
  */
318
390
  addLabels(owner: string, repo: string, issueNumber: number, labels: string[]): Promise<void>;
391
+ /**
392
+ * Remove ONE label from an issue/PR, leaving every other label alone.
393
+ *
394
+ * The second of the two harness-side label writes (see {@link addLabels}),
395
+ * and the load-bearing half of the software-factory stage pipeline: the
396
+ * stage label IS the source of truth for where an issue has got to, and the
397
+ * ENTRY label (`ready-for-agent`) must come off BEFORE the run it triggered
398
+ * starts. That ordering is not cosmetic. The backstop cron sweep finds work
399
+ * by querying `label:ready-for-agent`; if the label is still there while the
400
+ * run is in flight, the sweep is structurally able to re-pick an issue that
401
+ * was already dispatched, and re-pick it again on the next tick. This repo
402
+ * has a recorded production incident of exactly that shape — a cron gated on
403
+ * a signal the work never wrote, every run reporting `succeeded` while it
404
+ * burned roughly $1.30/hour. Removing the entry label at dispatch is what
405
+ * makes the re-pick impossible rather than merely unlikely.
406
+ *
407
+ * **A missing label is a 404, and a 404 here is success.** GitHub answers
408
+ * `404` when the label is not on the issue (and also when the label does not
409
+ * exist in the repo at all). Either way the desired end state — "this label
410
+ * is not on this issue" — already holds, so removing an absent label is a
411
+ * no-op and we swallow that ONE status. Everything else (403 from a
412
+ * downscoped token, 5xx, a network failure) propagates: a blanket catch here
413
+ * would turn "we could not take the entry label off" into silence, which is
414
+ * precisely the re-dispatch loop above.
415
+ */
416
+ removeLabel(owner: string, repo: string, issueNumber: number, label: string): Promise<void>;
319
417
  /**
320
418
  * List every repository ONE installation can access, as `owner/repo` full
321
419
  * names. Paginated — handles installs with hundreds of repos.
@@ -1525,6 +1623,97 @@ export declare class GitHubClient {
1525
1623
  headSha: string;
1526
1624
  createdAt: string;
1527
1625
  }>>;
1626
+ /**
1627
+ * The repo's OPEN ISSUES carrying `label`, as light records (number / title /
1628
+ * labels / created-at).
1629
+ *
1630
+ * The autonomy backstop sweep's one GitHub read (`cron/issue-discovery.ts`):
1631
+ * it asks GitHub to do the filtering — `state: "open"` + `labels:` are both
1632
+ * server-side — so a repo with thousands of issues costs one page, not a walk.
1633
+ * `labels` rides the same response, which is what lets the discoverer exclude
1634
+ * a partially-advanced issue (one carrying the stage's `running` label as well
1635
+ * as its `enter` label) without a second call, and what lets the dispatch gate
1636
+ * read the hold label off the candidate it was handed.
1637
+ *
1638
+ * **A PULL REQUEST IS NEVER RETURNED.** `GET /repos/{o}/{r}/issues` returns
1639
+ * pull requests alongside issues — a PR *is* an issue to this API, and it
1640
+ * carries the same labels — so an unfiltered response would offer PRs to a
1641
+ * pipeline that dispatches `build` runs against an ISSUE number. That would
1642
+ * not fail loudly; it would clone the repo and set an agent to work on a
1643
+ * "feature request" that is somebody's open pull request. `item.pull_request`
1644
+ * is present on exactly those items and absent on real issues, so it is the
1645
+ * discriminator (the same one `listRepoActivitySince` uses to set `isPr`).
1646
+ *
1647
+ * Page-bounded to `maxPages` (3 × 100 = 300 items) for the same reason
1648
+ * `listRepoActivitySince` is: an unbounded paginate here runs per repo on
1649
+ * every tick, which is a rate-limit hazard, and a repo with 300 open issues
1650
+ * sitting at one stage label has a queue problem rather than a paging one.
1651
+ * Oldest first, so the caller's per-repo cap is stable across ticks rather
1652
+ * than starving the same tail.
1653
+ */
1654
+ listOpenIssuesByLabel(owner: string, repo: string, label: string, opts?: {
1655
+ maxPages?: number;
1656
+ }): Promise<Array<{
1657
+ number: number;
1658
+ title: string;
1659
+ labels: string[];
1660
+ createdAt: string;
1661
+ }>>;
1662
+ /**
1663
+ * Every OPEN issue and pull request across `repos`, for the board.
1664
+ *
1665
+ * ## The rate-limit budget is what decides this method's shape
1666
+ *
1667
+ * The obvious implementation — `issues.listForRepo` per repo, per poll — does
1668
+ * not survive contact with the numbers. A dashboard polling at 15 s over 20
1669
+ * repos is ~4,800 requests an hour, and each open tab multiplies it; the
1670
+ * installation's 5,000/hr budget is the SAME budget the harness spends
1671
+ * reviewing pull requests and fixing CI, so a board left open would starve the
1672
+ * work it exists to display. That version must not ship.
1673
+ *
1674
+ * So: ONE GraphQL document per batch of up to ten repos, each an aliased
1675
+ * `search(type: ISSUE, query: "repo:o/r is:open")` block. That is the idiom
1676
+ * {@link listRepoDigestDetail} already uses for its three aliased searches —
1677
+ * aliases ride one request and one rate-limit point between them. Twenty
1678
+ * repos therefore cost TWO requests per refresh, and with the board cache's
1679
+ * 120 s TTL in front (`src/admin/board-cache.ts`) the steady state is ~60
1680
+ * requests an hour **regardless of how many dashboards are open**.
1681
+ *
1682
+ * ## Batched by OWNER, because the token is
1683
+ *
1684
+ * {@link kit} resolves a per-OWNER installation and each installation mints
1685
+ * its own token, so a single document can only span repos of one account.
1686
+ * The caller groups by owner; this method takes the owner explicitly and
1687
+ * treats `repos` as bare names under it.
1688
+ *
1689
+ * ## `search` is subject to SECONDARY limits, which the point budget does not
1690
+ * describe
1691
+ *
1692
+ * GitHub throttles search independently of the documented points, with no
1693
+ * warning in the response headers. A throttle therefore falls back to
1694
+ * {@link listRepoActivitySince} (`maxPages: 1`) per repo and marks the result
1695
+ * `fallback` + `throttled`: the board degrades to a bounded, slightly
1696
+ * lossy view of the repo rather than showing an empty column, and the cache
1697
+ * reads `throttled` as its cue to back off that owner.
1698
+ *
1699
+ * Keyed by the QUALIFIED `owner/repo` so the caller can index one map across
1700
+ * every owner it asked about.
1701
+ */
1702
+ listOpenBoardItems(owner: string, repos: string[], opts?: {
1703
+ first?: number;
1704
+ batchSize?: number;
1705
+ }): Promise<Map<string, BoardRepoItems>>;
1706
+ /** The aliased-search half of {@link listOpenBoardItems}. One request. */
1707
+ private searchOpenBoardItems;
1708
+ /**
1709
+ * The REST fallback for ONE repo when search is throttled.
1710
+ *
1711
+ * Bounded to a single page and to items still open. It is lossy on purpose:
1712
+ * `listRepoActivitySince` filters on `updated_at`, so an open issue nobody has
1713
+ * touched in the window is missing, and its labels carry no colour. A board
1714
+ * that says so (`degraded`) beats a board that shows an empty column.
1715
+ */
1716
+ private restBoardFallback;
1528
1717
  /**
1529
1718
  * What happened in a repo between `sinceIso` and now — issues AND pull
1530
1719
  * 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,249 @@ 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 and pull request across `repos`, for the board.
730
+ *
731
+ * ## The rate-limit budget is what decides this method's shape
732
+ *
733
+ * The obvious implementation — `issues.listForRepo` per repo, per poll — does
734
+ * not survive contact with the numbers. A dashboard polling at 15 s over 20
735
+ * repos is ~4,800 requests an hour, and each open tab multiplies it; the
736
+ * installation's 5,000/hr budget is the SAME budget the harness spends
737
+ * reviewing pull requests and fixing CI, so a board left open would starve the
738
+ * work it exists to display. That version must not ship.
739
+ *
740
+ * So: ONE GraphQL document per batch of up to ten repos, each an aliased
741
+ * `search(type: ISSUE, query: "repo:o/r is:open")` block. That is the idiom
742
+ * {@link listRepoDigestDetail} already uses for its three aliased searches —
743
+ * aliases ride one request and one rate-limit point between them. Twenty
744
+ * repos therefore cost TWO requests per refresh, and with the board cache's
745
+ * 120 s TTL in front (`src/admin/board-cache.ts`) the steady state is ~60
746
+ * requests an hour **regardless of how many dashboards are open**.
747
+ *
748
+ * ## Batched by OWNER, because the token is
749
+ *
750
+ * {@link kit} resolves a per-OWNER installation and each installation mints
751
+ * its own token, so a single document can only span repos of one account.
752
+ * The caller groups by owner; this method takes the owner explicitly and
753
+ * treats `repos` as bare names under it.
754
+ *
755
+ * ## `search` is subject to SECONDARY limits, which the point budget does not
756
+ * describe
757
+ *
758
+ * GitHub throttles search independently of the documented points, with no
759
+ * warning in the response headers. A throttle therefore falls back to
760
+ * {@link listRepoActivitySince} (`maxPages: 1`) per repo and marks the result
761
+ * `fallback` + `throttled`: the board degrades to a bounded, slightly
762
+ * lossy view of the repo rather than showing an empty column, and the cache
763
+ * reads `throttled` as its cue to back off that owner.
764
+ *
765
+ * Keyed by the QUALIFIED `owner/repo` so the caller can index one map across
766
+ * every owner it asked about.
767
+ */
768
+ async listOpenBoardItems(owner, repos, opts = {}) {
769
+ const out = new Map();
770
+ const names = [...new Set(repos.filter((r) => !!r))];
771
+ if (names.length === 0)
772
+ return out;
773
+ // Search caps a page at 100. 50 is the board's per-repo ceiling: a repo with
774
+ // more than fifty open items has a queue problem, not a paging one, and the
775
+ // column would be unreadable either way.
776
+ const first = Math.min(Math.max(opts.first ?? 50, 1), 100);
777
+ // Ten aliases per document — enough to make twenty repos two requests,
778
+ // small enough that one hostile repo's page size can't blow the response.
779
+ const batchSize = Math.min(Math.max(opts.batchSize ?? 10, 1), 10);
780
+ for (let i = 0; i < names.length; i += batchSize) {
781
+ const batch = names.slice(i, i + batchSize);
782
+ try {
783
+ const results = await this.searchOpenBoardItems(owner, batch, first);
784
+ for (const [repo, items] of results)
785
+ out.set(repo, { items });
786
+ }
787
+ catch (err) {
788
+ const throttled = isThrottleError(err);
789
+ const message = err instanceof Error ? err.message : String(err);
790
+ log.warn("board search failed", { owner, repos: batch, throttled, err });
791
+ // Per-repo REST fallback. Only worth the requests on a throttle: any
792
+ // other failure (a dead installation, a 5xx) would fail the same way
793
+ // again, and spending ten more requests to prove it is the opposite of
794
+ // what a rate-limit hazard wants.
795
+ for (const repo of batch) {
796
+ const key = `${owner}/${repo}`;
797
+ if (!throttled) {
798
+ out.set(key, { items: [], error: message });
799
+ continue;
800
+ }
801
+ try {
802
+ out.set(key, {
803
+ items: await this.restBoardFallback(owner, repo),
804
+ error: `GitHub search was throttled; showing a bounded REST view (${message})`,
805
+ fallback: true,
806
+ throttled: true,
807
+ });
808
+ }
809
+ catch (fallbackErr) {
810
+ out.set(key, {
811
+ items: [],
812
+ error: fallbackErr instanceof Error ? fallbackErr.message : String(fallbackErr),
813
+ throttled: true,
814
+ });
815
+ }
816
+ }
817
+ }
818
+ }
819
+ return out;
820
+ }
821
+ /** The aliased-search half of {@link listOpenBoardItems}. One request. */
822
+ async searchOpenBoardItems(owner, repos, first) {
823
+ const kit = await this.kit(owner);
824
+ // The document is built from the batch because the alias count varies.
825
+ // `__typename` is what splits an Issue from a PullRequest — `search` returns
826
+ // both for `type: ISSUE` and the board colours them differently.
827
+ const params = repos.map((_, idx) => `$q${idx}: String!`).join(", ");
828
+ const blocks = repos
829
+ .map((_, idx) => `r${idx}: search(query: $q${idx}, type: ISSUE, first: $first) {
830
+ nodes {
831
+ __typename
832
+ ... on Issue {
833
+ number title url createdAt updatedAt bodyText
834
+ author { login }
835
+ labels(first: 10) { nodes { name color description } }
836
+ }
837
+ ... on PullRequest {
838
+ number title url createdAt updatedAt isDraft bodyText
839
+ author { login }
840
+ labels(first: 10) { nodes { name color description } }
841
+ }
842
+ }
843
+ }`)
844
+ .join("\n ");
845
+ const variables = { first };
846
+ repos.forEach((repo, idx) => {
847
+ variables[`q${idx}`] = `repo:${owner}/${repo} is:open`;
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
+ .filter((n) => !!n && typeof n.number === "number")
857
+ .map((n) => ({
858
+ repo: `${owner}/${repo}`,
859
+ number: n.number,
860
+ isPr: n.__typename === "PullRequest",
861
+ title: n.title ?? "",
862
+ url: n.url ?? "",
863
+ author: n.author?.login ?? "",
864
+ createdAt: n.createdAt ?? "",
865
+ updatedAt: n.updatedAt ?? n.createdAt ?? "",
866
+ body: boardExcerpt(n.bodyText),
867
+ draft: !!n.isDraft,
868
+ labels: (n.labels?.nodes ?? [])
869
+ .filter((l) => !!l?.name)
870
+ .map((l) => ({
871
+ name: l.name,
872
+ color: l.color ?? "",
873
+ description: l.description ?? undefined,
874
+ })),
875
+ })));
876
+ });
877
+ return out;
878
+ }
879
+ /**
880
+ * The REST fallback for ONE repo when search is throttled.
881
+ *
882
+ * Bounded to a single page and to items still open. It is lossy on purpose:
883
+ * `listRepoActivitySince` filters on `updated_at`, so an open issue nobody has
884
+ * touched in the window is missing, and its labels carry no colour. A board
885
+ * that says so (`degraded`) beats a board that shows an empty column.
886
+ */
887
+ async restBoardFallback(owner, repo) {
888
+ const since = new Date(Date.now() - 90 * 24 * 60 * 60 * 1000).toISOString();
889
+ const items = await this.listRepoActivitySince(owner, repo, since, { maxPages: 1 });
890
+ return items
891
+ .filter((item) => !item.closedAt)
892
+ .map((item) => ({
893
+ repo: `${owner}/${repo}`,
894
+ number: item.number,
895
+ isPr: item.isPr,
896
+ title: item.title,
897
+ url: item.htmlUrl,
898
+ author: item.authorLogin,
899
+ createdAt: item.createdAt,
900
+ updatedAt: item.createdAt,
901
+ draft: item.draft,
902
+ labels: item.labels.map((name) => ({ name, color: "" })),
903
+ // The REST list carries a `body`, but this path exists because GitHub
904
+ // just throttled us — it is the degraded answer, and the card renders
905
+ // without an excerpt rather than paying more requests for one.
906
+ body: "",
907
+ }));
908
+ }
584
909
  /**
585
910
  * What happened in a repo between `sinceIso` and now — issues AND pull
586
911
  * requests, opened / closed / merged.