@ouro.bot/cli 0.1.0-alpha.1556 → 0.1.0-alpha.1558

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 (87) hide show
  1. package/changelog.json +12 -0
  2. package/deploy/unraid/sanctuary.ouro/bundle-meta.json +1 -1
  3. package/deploy/unraid/sanctuary.xml +1 -1
  4. package/desk.lock.json +3 -3
  5. package/npm-shrinkwrap.json +2 -2
  6. package/package.json +1 -1
  7. package/vendor/desk/.claude-plugin/plugin.json +1 -1
  8. package/vendor/desk/.ouro-desk.json +3 -3
  9. package/vendor/desk/CHANGELOG.md +640 -0
  10. package/vendor/desk/activation/copilot-root.flattened-bundle.json +2 -2
  11. package/vendor/desk/activation/desk.activation.json +5 -5
  12. package/vendor/desk/agency.json +1 -1
  13. package/vendor/desk/docs/issue-drains.md +8 -6
  14. package/vendor/desk/docs/sessions.md +1 -1
  15. package/vendor/desk/hooks/lib/boot-checks.cjs +1 -1
  16. package/vendor/desk/hooks/lib/child-agent.cjs +2 -2
  17. package/vendor/desk/hooks/lib/factory-end.cjs +4 -1
  18. package/vendor/desk/mcp/README.md +9 -1
  19. package/vendor/desk/mcp/bootstrap.cjs +64 -38
  20. package/vendor/desk/mcp/idle-proxy.cjs +14 -6
  21. package/vendor/desk/mcp/scripts/crew.js +3 -3
  22. package/vendor/desk/mcp/scripts/drains-launcher.mjs +6 -5
  23. package/vendor/desk/mcp/scripts/factory.js +15 -6
  24. package/vendor/desk/mcp/scripts/local-recovery.js +89 -7
  25. package/vendor/desk/mcp/scripts/resolve-desk-root.js +1 -2
  26. package/vendor/desk/mcp/src/actions/desk-session.actions.mts +16 -1
  27. package/vendor/desk/mcp/src/actions/desk.actions.mts +2 -2
  28. package/vendor/desk/mcp/src/actions/generated/desk/actions.json +36 -1
  29. package/vendor/desk/mcp/src/actions/generated/desk/mcp.json +34 -1
  30. package/vendor/desk/mcp/src/activation/superpowers-context.js +9 -0
  31. package/vendor/desk/mcp/src/crew/workspace.js +30 -4
  32. package/vendor/desk/mcp/src/desk/card-commit-guard.js +3 -2
  33. package/vendor/desk/mcp/src/desk/content-home.js +16 -0
  34. package/vendor/desk/mcp/src/indexer/discover.js +8 -0
  35. package/vendor/desk/mcp/src/lib/ouro-ui/registry/ouro/ax/ax-claims.ts +2 -1
  36. package/vendor/desk/mcp/src/lib/ouro-ui/registry/ouro/ax/ax-command.ts +20 -0
  37. package/vendor/desk/mcp/src/lib/ouro-ui/registry/ouro/ax/mcp.ts +1 -1
  38. package/vendor/desk/mcp/src/lib/ouro-ui/registry/ouro/ax/xray.ts +40 -2
  39. package/vendor/desk/mcp/src/runtime/boot.js +0 -1
  40. package/vendor/desk/mcp/src/runtime/deliver.js +42 -5
  41. package/vendor/desk/mcp/src/runtime/drains-cli.js +9 -1
  42. package/vendor/desk/mcp/src/runtime/drains.js +479 -40
  43. package/vendor/desk/mcp/src/runtime/hosted.js +5 -3
  44. package/vendor/desk/mcp/src/runtime/pending-migrations.js +5 -1
  45. package/vendor/desk/mcp/src/runtime/pr-publication.js +55 -29
  46. package/vendor/desk/mcp/src/runtime/relays.js +10 -1
  47. package/vendor/desk/mcp/src/runtime/remote-identity.js +22 -0
  48. package/vendor/desk/mcp/src/runtime/sessions-cli.js +6 -6
  49. package/vendor/desk/mcp/src/runtime/sync-worker.js +10 -8
  50. package/vendor/desk/mcp/src/runtime/unmerged-saves.js +29 -3
  51. package/vendor/desk/mcp/src/server.js +3 -2
  52. package/vendor/desk/mcp/src/tool-names.js +0 -2
  53. package/vendor/desk/mcp/src/tool-schemas.js +3 -8
  54. package/vendor/desk/mcp/src/tools/archive-links.js +3 -0
  55. package/vendor/desk/mcp/src/tools/desk-save.js +8 -3
  56. package/vendor/desk/mcp/src/tools/move.js +32 -3
  57. package/vendor/desk/mcp/src/tools/sibling-desk.js +10 -4
  58. package/vendor/desk/mcp/src/tools/status.js +9 -6
  59. package/vendor/desk/mcp/src/tools/task-log.js +6 -2
  60. package/vendor/desk/mcp/src/tools/task.js +17 -5
  61. package/vendor/desk/mcp/src/util/citations.js +54 -0
  62. package/vendor/desk/mcp/web-auth.cjs +17 -0
  63. package/vendor/desk/mcp/web-sso.cjs +52 -0
  64. package/vendor/desk/plugin.json +2 -2
  65. package/vendor/desk/skills/add-workspace-mcp/SKILL.md +2 -2
  66. package/vendor/desk/skills/archive-workflow/SKILL.md +1 -1
  67. package/vendor/desk/skills/coordinating-lanes/SKILL.md +24 -0
  68. package/vendor/desk/skills/evidence-discipline/SKILL.md +8 -12
  69. package/vendor/desk/skills/git-hygiene/SKILL.md +6 -0
  70. package/vendor/desk/skills/interaction-style/SKILL.md +4 -2
  71. package/vendor/desk/skills/live-ui-iteration/SKILL.md +35 -0
  72. package/vendor/desk/skills/operator-voice-comments/SKILL.md +4 -0
  73. package/vendor/desk/skills/outside-approval/SKILL.md +10 -0
  74. package/vendor/desk/skills/pr-feedback-on-own-pr/SKILL.md +5 -1
  75. package/vendor/desk/skills/pr-reviewer-audit/SKILL.md +1 -1
  76. package/vendor/desk/skills/pr-reviewer-audit/helpers/audit.py +19 -1
  77. package/vendor/desk/skills/pr-reviewer-audit/helpers/test_audit.py +37 -1
  78. package/vendor/desk/skills/pr-self-review/SKILL.md +1 -1
  79. package/vendor/desk/skills/pr-surface-hygiene/SKILL.md +28 -4
  80. package/vendor/desk/skills/pr-surface-hygiene/check-visual-proof.cjs +27 -14
  81. package/vendor/desk/skills/prior-art/SKILL.md +14 -0
  82. package/vendor/desk/skills/runtime-symptom-investigation/SKILL.md +5 -1
  83. package/vendor/desk/skills/session-resumption/SKILL.md +3 -1
  84. package/vendor/desk/skills/using-desk/SKILL.md +3 -3
  85. package/vendor/desk/skills/using-superpowers-with-desk/SKILL.md +2 -0
  86. package/vendor/desk/skills/visual-proof/SKILL.md +42 -0
  87. package/vendor/desk/skills/work-orchestration/SKILL.md +17 -2
@@ -4,9 +4,9 @@
4
4
  //
5
5
  // `updated_at` alone is not a revision: the drain's own label edits and status comment move it too. An issue is news only when
6
6
  // something other than the drain changed it since the revision last recorded for that issue.
7
- import { createHash } from "node:crypto"
7
+ import { createHash, randomUUID } from "node:crypto"
8
8
  import { spawnSync } from "node:child_process"
9
- import { closeSync, existsSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs"
9
+ import { existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, renameSync, rmdirSync, unlinkSync, writeFileSync } from "node:fs"
10
10
  import { fileURLToPath } from "node:url"
11
11
  import * as os from "node:os"
12
12
  import * as path from "node:path"
@@ -26,9 +26,11 @@ const TURN_MS = 90 * 60_000
26
26
  const TURNS_KEPT = 50
27
27
  /** A closed issue's record is kept this long, so one that comes back unchanged is not mistaken for a new issue. */
28
28
  const GONE_MS = 30 * 24 * 3_600_000
29
- const LOCK_STALE_MS = 15 * 60_000
30
29
  const MAX_TITLES = 20
31
30
  const PAGE = 100
31
+ const EDIT_FIELDS = "totalCount pageInfo { hasNextPage hasPreviousPage startCursor endCursor } nodes { id editedAt deletedAt editor { __typename login } }"
32
+ const EDITS_FORWARD = `query($owner: String!, $name: String!, $number: Int!, $cursor: String) { rateLimit { cost } repository(owner: $owner, name: $name) { issue(number: $number) { updatedAt userContentEdits(first: 100, after: $cursor) { ${EDIT_FIELDS} } } } }`
33
+ const EDITS_BACKWARD = `query($owner: String!, $name: String!, $number: Int!, $cursor: String) { rateLimit { cost } repository(owner: $owner, name: $name) { issue(number: $number) { updatedAt userContentEdits(last: 100, before: $cursor) { ${EDIT_FIELDS} } } } }`
32
34
  /** A full listing of the open issues is read again this often; between them only issues updated since the last change are read. */
33
35
  const FULL_SYNC_MS = 3_600_000
34
36
  /** The list is read from a little before the newest change it knew, so an update GitHub lists late is still seen. */
@@ -225,38 +227,207 @@ function writeDrainStates(file, states) {
225
227
  renameSync(temporary, file)
226
228
  }
227
229
 
228
- function create(lockFile) {
229
- closeSync(openSync(lockFile, "wx"))
230
- writeFileSync(lockFile, String(process.pid))
230
+ const OWNER_FILE = /^owner-[0-9a-f-]{36}$/u
231
+ const busy = (lockFile, who) => problem("desk_drains_busy", "drains lock", `${who} holds ${lockFile} and is still working`, `check that process; it releases the lock itself when it finishes, and a lock whose process has died is taken over by the next run`, "run the command again once it finishes")
232
+ const lockProblem = (code, lockFile, probably, look, fix) => problem(code, "drains lock", probably, look, fix)
233
+ const unavailable = (lockFile, error) => lockProblem("desk_drains_lock_unavailable", lockFile, `${lockFile} cannot be created or read because of ${error.code ?? error.message}`, `the permissions and free space of ${path.dirname(lockFile)}, and the error code ${error.code ?? "unknown"}`, "fix that, then run the command again")
234
+
235
+ /**
236
+ * Takes the lock, or throws. The lock is a directory that is published whole: a sibling `<lock>.new-<pid>-<token>` is filled with
237
+ * the one file `owner-<token>` (this process's id) and then renamed onto the lock, which succeeds only where the lock is absent or
238
+ * an empty directory. So the lock is never visible empty or half-written, and a live owner is never taken from, however long it
239
+ * works. A dead owner is retired by removing its own `owner-<token>` file, a name no later owner reuses, so a contender holding a
240
+ * stale view finds nothing to remove (ENOENT) instead of a newer owner's lock; the empty directory is then removed with `rmdir`,
241
+ * which refuses a directory that has become someone's. Nothing is aged out, renamed away or removed recursively. An earlier Desk's
242
+ * lock is a plain file: it is never replaced, because replacing it by name cannot be made safe against that Desk's own takeover.
243
+ * `onStep` is a test seam called at "staging" (the sibling exists, the owner file is not written), "staged" and "inspected".
244
+ */
245
+ export function acquireDrainLock(lockFile, { alive = processAlive, onStep = () => {}, rename = publishDirectory } = {}) {
246
+ const dir = path.dirname(lockFile)
247
+ const base = path.basename(lockFile)
248
+ sweepStaging(dir, base, alive)
249
+ for (let attempt = 0; attempt < 3; attempt++) {
250
+ const token = randomUUID()
251
+ const staging = path.join(dir, `${base}.new-${process.pid}-${token}`)
252
+ const owner = path.join(staging, `owner-${token}`)
253
+ let renamed = false
254
+ try {
255
+ try {
256
+ mkdirSync(staging)
257
+ onStep("staging")
258
+ writeFileSync(owner, `${process.pid}\n`)
259
+ onStep("staged")
260
+ } catch (error) {
261
+ throw unavailable(lockFile, error)
262
+ }
263
+ try {
264
+ rename(staging, lockFile)
265
+ renamed = true
266
+ } catch (error) {
267
+ // Platforms name an occupied target differently (POSIX ENOTEMPTY, ENOTDIR, EEXIST; Windows EPERM), so the error code is not
268
+ // trusted: the target itself is inspected next. Only a rename that failed with nothing in the way is a failure to use the lock.
269
+ // A move that was cut short (Windows, a timeout) may still have happened. It is ours only if the lock is a directory holding this
270
+ // acquisition's own `owner-<token>` (a name nothing else uses); any other target, live or legacy, is left alone.
271
+ if (!existsAt(staging) && holdsOwner(lockFile, `owner-${token}`)) renamed = true
272
+ else if (!existsAt(lockFile)) throw unavailable(lockFile, error)
273
+ }
274
+ } finally {
275
+ if (!renamed) removeStaging(staging)
276
+ }
277
+ if (renamed) return () => releaseDrainLock(lockFile, `owner-${token}`)
278
+ retireDeadOwner(lockFile, alive, onStep)
279
+ }
280
+ throw busy(lockFile, "another poll, which started while this one looked,")
281
+ }
282
+
283
+ /** The one step that must never replace what is at the lock: POSIX `rename` refuses all but an absent or empty directory, but Windows' replaces a plain file. */
284
+ function publishDirectory(from, to) {
285
+ // Only Windows runs the first branch; the native Windows suite (desk-windows-suite.yml) exercises it, a Linux or macOS run cannot.
286
+ /* istanbul ignore if */
287
+ if (process.platform === "win32") moveWithoutReplace(from, to, { shells: ["pwsh", "powershell"] })
288
+ else renameSync(from, to)
289
+ }
290
+
291
+ // Fixed script, paths as data (environment), never interpolated. Directory.Move ends in MoveFileExW without MOVEFILE_REPLACE_EXISTING
292
+ // (dotnet/runtime, Interop.MoveFileEx.cs and FileSystem.Windows.cs: MoveFile(..., overwrite: false)), so an existing target is refused
293
+ // by the system, not by a check made first. Windows PowerShell 5.1 runs .NET Framework, whose Directory.InternalMove makes no existence
294
+ // check either: it validates paths and the shared root, then calls Win32Native.MoveFile, i.e. MoveFileEx(src, dst, 2 /* MOVEFILE_COPY_ALLOWED */)
295
+ // or MoveFileW, neither of which replaces (microsoft/referencesource@ec9fa9ae770d, mscorlib/system/io/directory.cs InternalMove and
296
+ // mscorlib/microsoft/win32/win32native.cs MoveFile). The native per-shell target tests are evidence, not a proof of every interleaving. Exit 3 means "refused", with the outer exception, and its inner one if any, named on stderr.
297
+ const MOVE_SCRIPT = "try { [System.IO.Directory]::Move($env:DESK_MOVE_FROM, $env:DESK_MOVE_TO) } catch { $e = $_.Exception; $i = $e.InnerException; [Console]::Error.Write('refused ' + $e.GetType().Name + ' ' + $e.HResult + $(if ($i) { ' inner ' + $i.GetType().Name + ' ' + $i.HResult } else { ' no-inner' })); exit 3 }"
298
+
299
+ /**
300
+ * Moves a directory to a path that must not exist, failing (and changing nothing) if anything is there. The next shell is tried only
301
+ * when the first cannot be launched at all; a move that ran, was refused or timed out is never retried and never falls back to `rename`.
302
+ */
303
+ export function moveWithoutReplace(from, to, { shells, timeoutMs = TOKEN_MS }) {
304
+ for (const shell of shells) {
305
+ const result = spawnSync(shell, ["-NoProfile", "-NonInteractive", "-Command", MOVE_SCRIPT], { env: { ...process.env, DESK_MOVE_FROM: from, DESK_MOVE_TO: to }, encoding: "utf8", timeout: timeoutMs, windowsHide: true })
306
+ if (result.error?.code === "ENOENT") continue
307
+ if (result.error) throw Object.assign(new Error(`${shell}: ${result.error.message}`), { code: result.error.code })
308
+ if (result.status === 0) return
309
+ throw Object.assign(new Error(`Run the command again once what is at the lock is dealt with: ${shell} did not move it (exit ${result.status}): ${String(result.stderr).trim() || "no message"}`), { code: "desk_move_refused" })
310
+ }
311
+ throw Object.assign(new Error(`Install PowerShell (pwsh) or put powershell on PATH: none of ${shells.join(", ")} could be started`), { code: "desk_move_no_shell" })
312
+ }
313
+
314
+ function holdsOwner(lockFile, ownerName) {
315
+ try {
316
+ return lstatSync(lockFile).isDirectory() && lstatSync(path.join(lockFile, ownerName)).isFile()
317
+ } catch (error) {
318
+ if (error.code === "ENOENT" || error.code === "ENOTDIR") return false
319
+ throw unavailable(lockFile, error)
320
+ }
231
321
  }
232
322
 
233
- function lockOwner(lockFile, now) {
323
+ function existsAt(target) {
234
324
  try {
235
- return { pid: Number.parseInt(readFileSync(lockFile, "utf8"), 10), ageMs: now - statSync(lockFile).mtimeMs }
325
+ lstatSync(target)
326
+ return true
327
+ } catch (error) {
328
+ if (error.code === "ENOENT") return false
329
+ throw unavailable(target, error)
330
+ }
331
+ }
332
+
333
+ function legacyLock(lockFile) {
334
+ let pid = "an unknown process"
335
+ try {
336
+ pid = `process ${Number.parseInt(readFileSync(lockFile, "utf8"), 10)}`
236
337
  } catch {
237
- return null
338
+ // A file that cannot be read is named by its path alone.
238
339
  }
340
+ return lockProblem("desk_drains_lock_legacy", lockFile, `${lockFile} is a file, the lock of an earlier Desk, and Desk cannot tell whether a poll still holds it (it names ${pid})`, `whether ${pid}, or any drains poll or ack started by an earlier Desk, is still running`, `once none is, remove ${lockFile} yourself and run the command again; Desk never replaces it, because that could take the lock from a poll that is still working`)
239
341
  }
240
342
 
241
- /** Runs `work`, which may be async, while this process owns the lock file. A live owner means another poll or ack is mid-write, so this one stops instead of racing it. */
242
- export async function withDrainLock(lockFile, work, { now = Date.now(), alive = processAlive } = {}) {
243
- assertNotRealStateUnderTest(path.dirname(lockFile))
244
- mkdirSync(path.dirname(lockFile), { recursive: true })
343
+ function removeStaging(staging) {
245
344
  try {
246
- create(lockFile)
345
+ for (const name of readdirSync(staging)) if (OWNER_FILE.test(name)) unlinkSync(path.join(staging, name))
346
+ rmdirSync(staging)
247
347
  } catch (error) {
248
- if (error.code !== "EEXIST") throw error
249
- const owner = lockOwner(lockFile, now)
250
- if (owner && owner.ageMs <= LOCK_STALE_MS && alive(owner.pid)) {
251
- throw problem("desk_drains_busy", "drains lock", `process ${owner.pid} holds ${lockFile} and is still working`, `check that process, then look at ${lockFile}`, "run the command again once it finishes")
252
- }
253
- rmSync(lockFile, { force: true })
254
- create(lockFile)
348
+ if (!["ENOENT", "ENOTEMPTY"].includes(error.code)) throw unavailable(staging, error)
255
349
  }
350
+ }
351
+
352
+ /** A staging directory is never shared, so one whose creating process has died is a crash leftover and is removed by its exact name. */
353
+ function sweepStaging(dir, base, alive) {
354
+ let names
355
+ try {
356
+ names = readdirSync(dir)
357
+ } catch (error) {
358
+ if (error.code === "ENOENT") return
359
+ throw unavailable(path.join(dir, base), error)
360
+ }
361
+ for (const name of names) {
362
+ const match = name.startsWith(`${base}.new-`) ? /^(\d+)-[0-9a-f-]{36}$/u.exec(name.slice(base.length + 5)) : null
363
+ if (match && !alive(Number(match[1]))) removeStaging(path.join(dir, name))
364
+ }
365
+ }
366
+
367
+ function retireDeadOwner(lockFile, alive, onStep) {
368
+ let names = null
369
+ try {
370
+ if (lstatSync(lockFile).isDirectory()) names = readdirSync(lockFile)
371
+ } catch (error) {
372
+ // A lock that vanished since the publish failed belongs to someone who just released it: the next attempt publishes.
373
+ /* istanbul ignore if -- a race with another process's release */
374
+ if (error.code === "ENOENT") return
375
+ throw unavailable(lockFile, error)
376
+ }
377
+ if (names === null) throw legacyLock(lockFile)
378
+ if (names.length === 0) return removeEmptyLock(lockFile)
379
+ if (names.length !== 1 || !OWNER_FILE.test(names[0])) {
380
+ throw lockProblem("desk_drains_lock_unrecognized", lockFile, `${lockFile} holds ${names.slice(0, 5).join(", ")}, which is not one owner file of this Desk's lock`, `${lockFile}, and whether another tool or a newer Desk made it`, "leave it, or ask its owner; Desk removes nothing it did not make")
381
+ }
382
+ let pid
383
+ try {
384
+ pid = Number.parseInt(readFileSync(path.join(lockFile, names[0]), "utf8"), 10)
385
+ } catch (error) {
386
+ /* istanbul ignore if -- a race with another process's release */
387
+ if (error.code === "ENOENT") return
388
+ throw unavailable(lockFile, error)
389
+ }
390
+ if (!Number.isInteger(pid) || pid <= 0) {
391
+ throw lockProblem("desk_drains_lock_unrecognized", lockFile, `${path.join(lockFile, names[0])} does not name a process`, `${lockFile}, and whether another tool or a newer Desk made it`, "leave it, or ask its owner; Desk removes nothing it did not make")
392
+ }
393
+ if (alive(pid)) throw busy(lockFile, `process ${pid}`)
394
+ onStep("inspected")
395
+ try {
396
+ unlinkSync(path.join(lockFile, names[0]))
397
+ } catch (error) {
398
+ if (error.code !== "ENOENT") throw unavailable(lockFile, error)
399
+ }
400
+ removeEmptyLock(lockFile)
401
+ }
402
+
403
+ /** `rmdir` fails on a directory that has an owner, so it cannot remove a lock published after it was looked at. */
404
+ function removeEmptyLock(lockFile) {
405
+ try {
406
+ rmdirSync(lockFile)
407
+ } catch (error) {
408
+ if (!["ENOENT", "ENOTEMPTY", "EEXIST"].includes(error.code)) throw unavailable(lockFile, error)
409
+ }
410
+ }
411
+
412
+ /** Removes only this run's own owner file, so a lock that has since passed to another owner is left alone. */
413
+ function releaseDrainLock(lockFile, ownerName) {
414
+ try {
415
+ unlinkSync(path.join(lockFile, ownerName))
416
+ } catch (error) {
417
+ if (error.code !== "ENOENT") throw unavailable(lockFile, error)
418
+ }
419
+ removeEmptyLock(lockFile)
420
+ }
421
+
422
+ /** Runs `work`, which may be async, while this process holds the lock (see acquireDrainLock). Only this run's owner file is removed afterwards. */
423
+ export async function withDrainLock(lockFile, work, { alive = processAlive, onStep } = {}) {
424
+ assertNotRealStateUnderTest(path.dirname(lockFile))
425
+ mkdirSync(path.dirname(lockFile), { recursive: true })
426
+ const release = acquireDrainLock(lockFile, { alive, onStep })
256
427
  try {
257
428
  return await work()
258
429
  } finally {
259
- rmSync(lockFile, { force: true })
430
+ release()
260
431
  }
261
432
  }
262
433
 
@@ -306,7 +477,163 @@ const ownStatus = (comment, login) => comment.user?.login?.toLowerCase() === log
306
477
  /** A comment a drain's `ignoreComments` rule skips: written by the rule's author (case-insensitive) and, when the rule has a `match`, a body that matches it. */
307
478
  const ignoredComment = (comment, rules) => rules.some((rule) => comment.user?.login?.toLowerCase() === rule.author && (rule.match === null || rule.match.test(comment.body ?? "")))
308
479
 
309
- const isBot = (comment) => comment.user?.type === "Bot" || (comment.user?.login ?? "").toLowerCase().endsWith("[bot]")
480
+ const isBot = (item) => item.user?.type === "Bot" || (item.user?.login ?? "").toLowerCase().endsWith("[bot]")
481
+ const isBotActor = (actor) => actor?.type === "Bot" || (actor?.login ?? "").toLowerCase().endsWith("[bot]")
482
+
483
+ // ── Who edited an issue's body ──
484
+ //
485
+ // An issue whose body changed is news unless every edit made since it was last recorded was a bot's. The proof reads the issue's
486
+ // edit history one GraphQL page at a time, and the progress is kept in `state.scans[number]`, so a history of any length is read
487
+ // across polls and quota windows without starting over. No order of the history is assumed. What is counted instead:
488
+ // - `base`: how many edits were already judged when the issue was last recorded (null when that is not known: the first pass
489
+ // then counts the edits older than `floor` as it reads forward, and knows `base` once it reaches the end);
490
+ // - an edit is new when it is not older than `floor` and is not one of the `tail` ids already judged at that second;
491
+ // - `total` is read from every page, so the new edits still to find are `total - base`, wherever they sit and however many more
492
+ // arrive while the scan runs (an edit that arrives behind the cursor makes `total` grow, and the scan reads on until it has found them).
493
+ // The scan stops at once on an edit that is not a bot's (or has no editor, no id, no time, or is deleted): that is news.
494
+
495
+ const pagesFor = (total) => Math.ceil(total / PAGE) + 1
496
+ const emptySide = () => ({ cursor: null, pages: 0, done: false })
497
+
498
+ function newScan(before) {
499
+ const edits = before.edits
500
+ return { of: before.updatedAt, floor: edits?.at ?? before.updatedAt, base: edits ? edits.total : null, tail: edits ? [...edits.tail] : [], old: 0, found: {}, total: 0, passTotal: null, fwd: emptySide(), bwd: emptySide(), next: "fwd", stamp: null, served: 0 }
501
+ }
502
+
503
+ const restartPass = (scan) => Object.assign(scan, { fwd: emptySide(), bwd: emptySide(), passTotal: scan.total, old: 0, next: "fwd" })
504
+
505
+ const isNewEdit = (scan, edit) => !(Date.parse(edit.editedAt) < Date.parse(scan.floor)) && !scan.tail.includes(edit.id)
506
+
507
+ const botEdit = (edit) => typeof edit.id === "string" && Number.isFinite(Date.parse(edit.editedAt)) && !edit.deletedAt && Boolean(edit.editor) && isBotActor(edit.editor)
508
+
509
+ /** What a finished scan leaves on the issue's record: how many edits are now judged, when the newest was made and which ones were made then. */
510
+ function baselineOf(scan) {
511
+ const at = Object.values(scan.found).reduce((top, editedAt) => (Date.parse(editedAt) > Date.parse(top) ? editedAt : top))
512
+ const same = (editedAt) => Date.parse(editedAt) === Date.parse(at)
513
+ return { total: scan.total, at, tail: [...(same(scan.floor) ? scan.tail : []), ...Object.entries(scan.found).filter(([, editedAt]) => same(editedAt)).map(([id]) => id)] }
514
+ }
515
+
516
+ const NEWS = { kind: "news" }
517
+
518
+ const validPage = (page) => Array.isArray(page.edits) && Number.isInteger(page.total) && typeof page.updatedAt === "string" && typeof page.hasMore === "boolean"
519
+
520
+ /** What the pages read so far settle: the issue's new edits are all found (a bot-only proof, once a page is as fresh as the issue), not all found yet (null), or cannot be explained (news). */
521
+ function conclude(scan, issue) {
522
+ const found = Object.keys(scan.found).length
523
+ const exhausted = scan.base === null ? scan.fwd.done : scan.fwd.done || scan.bwd.done
524
+ const expected = scan.total - (scan.base ?? scan.old)
525
+ if (found === expected && (scan.base !== null || exhausted)) {
526
+ if (found === 0) return NEWS
527
+ if (Date.parse(scan.stamp) < Date.parse(issue.updated_at)) {
528
+ scan.base ??= scan.old
529
+ scan.lag = true
530
+ return { kind: "deferred", message: "Wait for the next poll: GitHub's edit history is behind the issue and is read again then", code: "drains_edit_history_behind" }
531
+ }
532
+ return { kind: "bot", baseline: baselineOf(scan) }
533
+ }
534
+ if (found > expected && scan.base !== null) return NEWS
535
+ if (exhausted) {
536
+ // Edits that arrived while the history was being read make `total` grow past the pass, and another pass finds them. When nothing new arrived the count cannot be explained.
537
+ if (scan.total <= scan.passTotal || found + (scan.base === null ? scan.old : 0) > scan.total) return NEWS
538
+ scan.base ??= scan.old
539
+ restartPass(scan)
540
+ }
541
+ return null
542
+ }
543
+
544
+ /** Reads one page of the scan and says what it settled, or null when it is not settled yet: news, a bot-only proof with the record it leaves, or waiting for GitHub's history to catch up with the issue. */
545
+ async function advance(api, repo, issue, scan) {
546
+ if (!Number.isFinite(Date.parse(scan.floor)) || typeof api.editPage !== "function") return NEWS
547
+ if (scan.lag) {
548
+ // The history was behind the issue: the first page, read again, tells whether it has caught up and whether more edits arrived.
549
+ const page = await api.editPage(repo, issue.number, { backward: false, cursor: null })
550
+ if (!page || !validPage(page)) return NEWS
551
+ scan.total = page.total
552
+ scan.stamp = page.updatedAt
553
+ if (Date.parse(scan.stamp) < Date.parse(issue.updated_at)) return { kind: "deferred", message: "Wait for the next poll: GitHub's edit history is behind the issue and is read again then", code: "drains_edit_history_behind" }
554
+ scan.lag = false
555
+ return conclude(scan, issue)
556
+ }
557
+ let direction = scan.base !== null && scan.next === "bwd" ? "bwd" : "fwd"
558
+ // A finished side ends the pass in `conclude`, which either settles it or restarts both sides, so this only guards a state no page can produce.
559
+ /* istanbul ignore if */
560
+ if (scan[direction].done) direction = direction === "fwd" ? "bwd" : "fwd"
561
+ const side = scan[direction]
562
+ const page = await api.editPage(repo, issue.number, { backward: direction === "bwd", cursor: side.cursor })
563
+ if (!page || !validPage(page)) return NEWS
564
+ scan.total = page.total
565
+ scan.stamp = page.updatedAt
566
+ scan.passTotal ??= page.total
567
+ side.pages += 1
568
+ scan.next = direction === "fwd" ? "bwd" : "fwd"
569
+ for (const edit of page.edits) {
570
+ if (!edit || typeof edit !== "object") return NEWS
571
+ if (!isNewEdit(scan, edit)) {
572
+ if (scan.base === null) scan.old += 1
573
+ continue
574
+ }
575
+ if (!botEdit(edit)) return NEWS
576
+ scan.found[edit.id] = edit.editedAt
577
+ }
578
+ if (page.hasMore) {
579
+ // A cursor that does not move, or more pages than the history can hold, is a cycle: it would never end.
580
+ if (typeof page.cursor !== "string" || page.cursor === side.cursor || side.pages >= pagesFor(scan.total)) return NEWS
581
+ side.cursor = page.cursor
582
+ } else {
583
+ side.done = true
584
+ }
585
+ return conclude(scan, issue)
586
+ }
587
+
588
+ /** Whether the GraphQL quota allows another page now: the same reserve as REST's, read from the connection's own headers, else from the last poll's reading while its window is open. */
589
+ function canSpend(api, state, now) {
590
+ const quota = api.graphqlQuota?.() ?? state.graphqlQuota
591
+ if (!quota || now >= quota.reset * 1000) return true
592
+ return quota.remaining - (api.graphqlCost?.() ?? 1) > QUOTA_RESERVE
593
+ }
594
+
595
+ /**
596
+ * Settles, for the issues whose body changed, whether bots alone made the edits. Every open scan gets one page per round, the one
597
+ * served longest ago first (`served` is kept with the scan), so scans that outnumber the pages the quota allows still take turns,
598
+ * and an issue with a short history is settled in the first round. A scan that cannot go on keeps its progress and is deferred,
599
+ * never settled by a guess.
600
+ */
601
+ async function attribute(api, repo, state, needs, now) {
602
+ const verdicts = new Map()
603
+ const scans = state.scans ?? (state.scans = {})
604
+ const wanted = new Set(needs.map(({ issue }) => String(issue.number)))
605
+ for (const key of Object.keys(scans)) if (!wanted.has(key)) delete scans[key]
606
+ const pending = new Set()
607
+ for (const { issue, before } of needs) {
608
+ const key = String(issue.number)
609
+ if (scans[key]?.of !== before.updatedAt) scans[key] = newScan(before)
610
+ pending.add({ issue, key, scan: scans[key] })
611
+ }
612
+ let halted = null
613
+ while (pending.size > 0 && !halted) {
614
+ for (const item of [...pending].sort((a, b) => a.scan.served - b.scan.served || a.issue.number - b.issue.number)) {
615
+ if (!canSpend(api, state, now)) {
616
+ const quota = api.graphqlQuota?.() ?? state.graphqlQuota
617
+ halted = { message: `Wait for the quota to reset: GitHub's GraphQL limit leaves ${quota.remaining}/${quota.limit} calls until ${new Date(quota.reset * 1000).toISOString()}`, code: "drains_rate_limited" }
618
+ break
619
+ }
620
+ item.scan.served = state.scanTurn = (state.scanTurn ?? 0) + 1
621
+ try {
622
+ const verdict = await advance(api, repo, item.issue, item.scan)
623
+ if (!verdict) continue
624
+ verdicts.set(item.issue.number, verdict)
625
+ pending.delete(item)
626
+ if (verdict.kind !== "deferred") delete scans[item.key]
627
+ } catch (error) {
628
+ pending.delete(item)
629
+ verdicts.set(item.issue.number, { kind: "deferred", message: error.message, code: error.code })
630
+ if (error.code === "drains_rate_limited") halted = { message: error.message, code: error.code }
631
+ }
632
+ }
633
+ }
634
+ for (const item of pending) verdicts.set(item.issue.number, { kind: "deferred", ...halted })
635
+ return verdicts
636
+ }
310
637
 
311
638
  /** A bot comment's text without what changes from run to run: run URLs and IDs, dates, times and durations. */
312
639
  function repeatableText(body) {
@@ -338,12 +665,16 @@ const duringTurn = (event, login, turns) => {
338
665
  return event.actor?.login?.toLowerCase() === login.toLowerCase() && turns.some((from) => at >= from - TURN_LEAD_MS && at <= from + TURN_MS)
339
666
  }
340
667
 
341
- /** What made a reopen or a label change news, or null: a label outside the drain's namespace, ignored list and ignored patterns, or a reopen that is not the drain claiming the issue (its own `drain:` label change within a minute). A label applied within a minute of the issue being opened was part of filing it, and the "new issue" wake shows it. A label or reopen by the polling account during the drain's turn is its own work. Closes, assignments and mentions are not news. */
668
+ /** What made a reopen or a label change news, or null: a label outside the drain's namespace, ignored list and ignored patterns, a reopen that is not the drain claiming the issue, or an assignment change (assigned or unassigned) outside the drain's turn (its own `drain:` label change within a minute). A label or assignee applied within a minute of the issue being opened was part of filing it, and the "new issue" wake shows it. A label, reopen or assignment change by the polling account during the drain's turn is its own work. Closes and mentions are not news. */
342
669
  function newsEvent(event, rules, claims, login, openedAt) {
343
670
  if (event.event === "reopened") {
344
671
  const own = event.actor?.login?.toLowerCase() === login.toLowerCase() && claims.some((claim) => claim.actor?.login?.toLowerCase() === login.toLowerCase() && Math.abs(Date.parse(claim.created_at) - Date.parse(event.created_at)) <= CLAIM_SLACK_MS)
345
672
  return own || duringTurn(event, login, rules.turns) ? null : "reopened"
346
673
  }
674
+ if (event.event === "assigned" || event.event === "unassigned") {
675
+ if (event.event === "assigned" && Date.parse(event.created_at) <= openedAt + OPENING_LABEL_MS) return null
676
+ return duringTurn(event, login, rules.turns) ? null : `${event.event} ${event.assignee?.login ?? "nobody"}`
677
+ }
347
678
  if (event.event !== "labeled" && event.event !== "unlabeled") return null
348
679
  if (event.event === "labeled" && Date.parse(event.created_at) <= openedAt + OPENING_LABEL_MS) return null
349
680
  const name = (event.label?.name ?? "").toLowerCase()
@@ -354,10 +685,10 @@ function newsEvent(event, rules, claims, login, openedAt) {
354
685
  /** An issue the drain filed or already triaged: a label in its `drain:` namespace, or its status marker in the body, is there before the poll first sees it, so it is already seen. */
355
686
  const filedByDrain = (issue) => (issue.labels ?? []).some((label) => (label?.name ?? "").toLowerCase().startsWith(DRAIN_LABEL_PREFIX)) || (issue.body ?? "").includes(DRAIN_STATUS_MARKER)
356
687
 
357
- /** What someone but the drain changed since `before` (a new issue, an edit, another comment, a reopen or a label outside the drain's own), or null. The reason travels with the event. */
358
- async function changedByOthers(api, repo, issue, before, digest, ignored, rules) {
688
+ /** What someone but the drain changed since `before` (a new issue, a title or body edit (an edit that only bots made to the body, such as a health table's refresh, is not news), an edit, another comment, a reopen or a label outside the drain's own), or null. The reason travels with the event. */
689
+ async function changedByOthers(api, repo, issue, before, digest, ignored, rules, edited) {
359
690
  if (!before) return filedByDrain(issue) ? null : "new issue"
360
- if (before.digest && (before.ignored ?? "") === ignored && before.digest !== digest) return "title or body edited"
691
+ if (edited) return edited
361
692
  const since = before.updatedAt
362
693
  const comments = (await api.comments(repo, issue.number, since)).filter((comment) => comment.updated_at > since)
363
694
  const all = {}
@@ -415,8 +746,7 @@ async function listIssues(api, drain, state, now) {
415
746
  const since = isoSeconds(Date.parse(state.cursor) - DELTA_SLACK_MS)
416
747
  const changed = await api.changedIssues(drain.repo, since, state.etag?.since === since ? state.etag.tag : undefined)
417
748
  if (changed.notModified) return { full: false, issues: [], untouched: true }
418
- state.etag = changed.etag ? { since, tag: changed.etag } : undefined
419
- return { full: false, issues: changed.issues }
749
+ return { full: false, issues: changed.issues, etag: changed.etag ? { since, tag: changed.etag } : undefined, newEtag: true }
420
750
  }
421
751
 
422
752
  /** What the account's quota says to do about this drain now: null to poll, or why not (until the window resets, or for a while). */
@@ -433,6 +763,7 @@ export function quotaHold(quota, lastPollAt, now) {
433
763
  export async function pollDrain(drain, states, { connect, now, desk }) {
434
764
  const state = states[drain.repo] ?? (states[drain.repo] = blank())
435
765
  let api = null
766
+ let left = null
436
767
  try {
437
768
  const knownLogin = state.loginAt && now - Date.parse(state.loginAt) < LOGIN_MS ? state.login : undefined
438
769
  api = await connect(drain.account, { login: knownLogin })
@@ -441,14 +772,34 @@ export async function pollDrain(drain, states, { connect, now, desk }) {
441
772
  state.loginAt = new Date(now).toISOString()
442
773
  }
443
774
  const listed = await listIssues(api, drain, state, now)
444
- if (!listed.untouched) await recordChanges(api, drain, state, listed, { now, desk })
775
+ if (!listed.untouched) {
776
+ const { deferred } = await recordChanges(api, drain, state, listed, { now, desk })
777
+ // The tag of the list is kept only once every change in it is recorded: a failed poll, or an issue left for the next one, asks for the same list again, never a 304 for it.
778
+ if (deferred.length > 0) delete state.etag
779
+ else if (listed.newEtag) state.etag = listed.etag
780
+ if (deferred.length > 0) {
781
+ const shown = deferred.slice(0, 3).map((item) => `#${item.number} (${item.message})`).join(", ")
782
+ left = { message: `Wait for the next poll: ${deferred.length} issue(s) were left for it: ${shown}${deferred.length > 3 ? ", …" : ""}`, code: "drains_issues_deferred" }
783
+ const specific = deferred.find((item) => item.code)?.code
784
+ if (specific) left.code = specific
785
+ }
786
+ }
445
787
  state.lastOkAt = new Date(now).toISOString()
446
788
  delete state.lastError
789
+ delete state.lastErrorCode
790
+ if (left) {
791
+ state.lastError = left.message
792
+ state.lastErrorCode = left.code
793
+ }
447
794
  } catch (error) {
448
795
  state.lastError = error.message
796
+ if (typeof error.code === "string") state.lastErrorCode = error.code
797
+ else delete state.lastErrorCode
449
798
  }
450
799
  const quota = api?.quota?.()
451
800
  if (quota) state.quota = quota
801
+ const graphqlQuota = api?.graphqlQuota?.()
802
+ if (graphqlQuota) state.graphqlQuota = graphqlQuota
452
803
  state.calls = api?.calls?.() ?? { total: 0, notModified: 0 }
453
804
  delete state.hold
454
805
  state.lastPollAt = new Date(now).toISOString()
@@ -463,6 +814,9 @@ async function recordChanges(api, drain, state, { full, issues }, { now, desk })
463
814
  const seen = full ? {} : { ...state.seen }
464
815
  const recorded = []
465
816
  const closed = new Set()
817
+ const todo = []
818
+ const deferred = []
819
+ let held = null
466
820
  let cursor = state.cursor ?? ""
467
821
  for (const issue of issues) {
468
822
  if (!full && issue.updated_at > cursor) cursor = issue.updated_at
@@ -476,10 +830,31 @@ async function recordChanges(api, drain, state, { full, issues }, { now, desk })
476
830
  }
477
831
  if (full && issue.updated_at > cursor) cursor = issue.updated_at
478
832
  const digest = digestOf(issue, trailers)
479
- seen[key] = { updatedAt: issue.updated_at, digest, ...(ignored ? { ignored } : {}) }
833
+ seen[key] = { updatedAt: issue.updated_at, digest, title: issue.title, ...(ignored ? { ignored } : {}), ...(before?.edits && before.digest === digest ? { edits: before.edits } : {}) }
480
834
  if (!state.seeded || before?.updatedAt === issue.updated_at) continue
481
- const why = await changedByOthers(api, drain.repo, issue, before, digest, ignored, rules)
482
- if (why) recorded.push({ number: issue.number, title: issue.title, updatedAt: issue.updated_at, seenAt: new Date(now).toISOString(), why })
835
+ // A body that changed is news unless bots alone edited it, whoever created the issue.
836
+ const bodyChanged = Boolean(before?.digest) && (before.ignored ?? "") === ignored && before.digest !== digest
837
+ // A record from before titles were kept cannot show the title is unchanged, so its first changed poll is news as it always was.
838
+ const edited = bodyChanged && before.title !== issue.title ? "title or body edited" : null
839
+ todo.push({ issue, key, before, digest, edited, scan: bodyChanged && !edited })
840
+ }
841
+ const verdicts = await attribute(api, drain.repo, state, todo.filter((item) => item.scan), now)
842
+ for (const item of todo) {
843
+ const { issue, key, before, digest } = item
844
+ const verdict = verdicts.get(issue.number)
845
+ try {
846
+ if (verdict?.kind === "deferred") throw Object.assign(new Error(verdict.message), { code: verdict.code })
847
+ if (verdict?.kind === "news") item.edited = "title or body edited"
848
+ const why = await changedByOthers(api, drain.repo, issue, before, digest, ignored, rules, item.edited)
849
+ if (verdict?.kind === "bot") seen[key].edits = verdict.baseline
850
+ if (why) recorded.push({ number: issue.number, title: issue.title, updatedAt: issue.updated_at, seenAt: new Date(now).toISOString(), why })
851
+ } catch (error) {
852
+ // This issue's marker stays where it was, so the next poll judges the same change again; the others go on.
853
+ // Only an issue that was seen before can fail here (a new one is judged without a read), so there is always a marker to restore.
854
+ seen[key] = before
855
+ deferred.push({ number: issue.number, message: error.message, code: error.code })
856
+ if (!held || issue.updated_at < held) held = issue.updated_at
857
+ }
483
858
  }
484
859
  for (const [key, entry] of Object.entries(state.seen)) {
485
860
  const gone = seenIssue(entry)
@@ -494,8 +869,10 @@ async function recordChanges(api, drain, state, { full, issues }, { now, desk })
494
869
  state.seen = seen
495
870
  state.seeded = true
496
871
  state.openCount = Object.values(seen).filter((entry) => !seenIssue(entry).goneAt).length
872
+ if (held && (!cursor || held < cursor)) cursor = held
497
873
  if (cursor) state.cursor = cursor
498
874
  if (full) state.syncedAt = new Date(now).toISOString()
875
+ return { deferred }
499
876
  }
500
877
 
501
878
  function span(ms) {
@@ -569,7 +946,7 @@ export async function pollDrains({ paths, connect, now, ackCommand, ackFlags = [
569
946
  const id = wakeId(drain.repo, events)
570
947
  return { id, repo: drain.repo, session: sessionOf(drain, states[drain.repo]), message: wakeMessage(drain.repo, events), replaces: wakePrefix(drain.repo), events, done: [...ackCommand, "ack", "--repo", drain.repo, "--wake", id, ...ackFlags] }
571
948
  })
572
- const errors = drains.filter((drain) => states[drain.repo].lastError).map((drain) => ({ repo: drain.repo, error: states[drain.repo].lastError }))
949
+ const errors = drains.filter((drain) => states[drain.repo].lastError).map((drain) => ({ repo: drain.repo, error: states[drain.repo].lastError, ...(states[drain.repo].lastErrorCode ? { code: states[drain.repo].lastErrorCode } : {}) }))
573
950
  const calls = drains.reduce((sum, drain) => sum + states[drain.repo].calls.total, 0)
574
951
  return { at: new Date(now).toISOString(), wakes, errors, calls, status: drainStatusLines(drains, states, now) }
575
952
  }
@@ -685,6 +1062,13 @@ export function recoverDrainTarget({ paths, repo, now, start = startSuccessor })
685
1062
 
686
1063
  // ── GitHub ──
687
1064
 
1065
+ /** What a non-OK answer means: GitHub's own server failing (5xx) clears by itself; only a 401 (a refused credential) is for the person to fix; any other refusal is reported as the answer GitHub gave, with no credential diagnosis. */
1066
+ function failedAnswer(status, route) {
1067
+ if (status >= 500) return Object.assign(new Error(`Wait for the next poll: GitHub's server answered HTTP ${status} for ${route} (asked twice); this usually clears on its own and needs nothing from you`), { code: "drains_github_server_error", status })
1068
+ if (status === 401) return Object.assign(new Error(`Check gh auth status, then try again: GitHub answered HTTP ${status} for ${route}, which means the token was refused`), { code: "drains_check_gh_auth_status_then", status })
1069
+ return Object.assign(new Error(`Read GitHub's answer, then fix its cause: GitHub refused the request with HTTP ${status} for ${route}; that is not by itself a credential problem`), { code: "drains_github_refused", status })
1070
+ }
1071
+
688
1072
  /** The drain's GitHub access: its account's token from the `gh` CLI, then the REST API. `login` skips asking GitHub who the token is. */
689
1073
  export async function connectGithub(account, { spawn = spawnSync, fetchImpl = fetch, env = process.env, login: knownLogin, pauseMs = TOKEN_PAUSE_MS } = {}) {
690
1074
  const tokenArgs = ["auth", "token", "--hostname", "github.com", ...(account ? ["--user", account] : [])]
@@ -705,15 +1089,24 @@ export async function connectGithub(account, { spawn = spawnSync, fetchImpl = fe
705
1089
  if (!token && transient) throw Object.assign(new Error(`Wait for the next poll, which reads the token again: the GitHub CLI's token read for ${account ?? "its active account"} gave no answer, probably because the keyring was busy or slow (${transient.slice(0, 160)})`), { code: "drains_github_cli_token_unavailable", transient: true })
706
1090
  if (!token) throw Object.assign(new Error(`Sign in the GitHub CLI: the GitHub CLI has no token for ${account ?? "its active account"} (run \`gh auth login --hostname github.com\`)`), { code: "drains_sign_in_the_github_cli" })
707
1091
  // What this connection spent and what GitHub says is left in the account's window; a 304 answer costs nothing against it.
708
- const meter = { total: 0, notModified: 0, quota: null }
1092
+ const meter = { total: 0, notModified: 0, quota: null, graphqlQuota: null, graphqlCost: 1 }
1093
+ // A read that GitHub answers with a 5xx is asked once more, at once: its own server failing usually clears. Only reads are repeated, never a write.
1094
+ const readTwice = async (url, init) => {
1095
+ let response = await fetchImpl(url, init())
1096
+ meter.total += 1
1097
+ if (response.status >= 500) {
1098
+ response = await fetchImpl(url, init())
1099
+ meter.total += 1
1100
+ }
1101
+ return response
1102
+ }
709
1103
  const get = async (route, { etag } = {}) => {
710
- const response = await fetchImpl(`https://api.github.com${route}`, {
1104
+ const response = await readTwice(`https://api.github.com${route}`, () => ({
711
1105
  headers: { Authorization: `Bearer ${token}`, Accept: "application/vnd.github+json", "User-Agent": "desk-issue-drains", ...(etag ? { "If-None-Match": etag } : {}) },
712
1106
  signal: AbortSignal.timeout(30_000),
713
- })
714
- meter.total += 1
1107
+ }))
715
1108
  const remaining = response.headers.get("x-ratelimit-remaining")
716
- if (remaining !== null) meter.quota = { remaining: Number(remaining), limit: Number(response.headers.get("x-ratelimit-limit")), reset: Number(response.headers.get("x-ratelimit-reset")), at: new Date().toISOString() }
1109
+ if (remaining !== null && response.headers.get("x-ratelimit-resource") !== "graphql") meter.quota = { remaining: Number(remaining), limit: Number(response.headers.get("x-ratelimit-limit")), reset: Number(response.headers.get("x-ratelimit-reset")), at: new Date().toISOString() }
717
1110
  if (response.status === 304) {
718
1111
  meter.notModified += 1
719
1112
  return { notModified: true }
@@ -726,7 +1119,7 @@ export async function connectGithub(account, { spawn = spawnSync, fetchImpl = fe
726
1119
  const until = Number.isFinite(reset) && reset > 0 ? new Date(reset * 1000).toISOString() : "the next window"
727
1120
  throw Object.assign(new Error(`Wait for the quota to reset: GitHub's hourly API limit is used up, rate limited until ${until} (HTTP ${response.status} for ${route.split("?")[0]})`), { code: "drains_rate_limited", status: response.status, rateLimited: true })
728
1121
  }
729
- throw Object.assign(new Error(`Check gh auth status, then try again: GitHub answered HTTP ${response.status} for ${route.split("?")[0]}`), { code: "drains_check_gh_auth_status_then", status: response.status })
1122
+ throw failedAnswer(response.status, route.split("?")[0])
730
1123
  }
731
1124
  return { body: await response.json(), next: /rel="next"/u.test(response.headers.get("link") ?? ""), etag: response.headers.get("etag") }
732
1125
  }
@@ -752,6 +1145,49 @@ export async function connectGithub(account, { spawn = spawnSync, fetchImpl = fe
752
1145
  meter.total += 1
753
1146
  return { ok: response.ok, status: response.status, body: await response.json().catch(() => ({})) }
754
1147
  }
1148
+ // GraphQL has its own quota window: its headers are kept apart from the REST reading, and a failure names this API.
1149
+ const graphql = async (query, variables) => {
1150
+ const response = await readTwice("https://api.github.com/graphql", () => ({
1151
+ method: "POST",
1152
+ headers: { Authorization: `Bearer ${token}`, Accept: "application/vnd.github+json", "User-Agent": "desk-issue-drains", "Content-Type": "application/json" },
1153
+ body: JSON.stringify({ query, variables }),
1154
+ signal: AbortSignal.timeout(30_000),
1155
+ }))
1156
+ const remaining = response.headers.get("x-ratelimit-remaining")
1157
+ if (remaining !== null) meter.graphqlQuota = { remaining: Number(remaining), limit: Number(response.headers.get("x-ratelimit-limit")), reset: Number(response.headers.get("x-ratelimit-reset")), at: new Date().toISOString() }
1158
+ const payload = response.ok ? await response.json().catch(() => null) : null
1159
+ const limited = response.status === 429 || (response.status === 403 && remaining === "0") || (payload?.errors ?? []).some((error) => error?.type === "RATE_LIMITED")
1160
+ if (limited) {
1161
+ const reset = Number(response.headers.get("x-ratelimit-reset"))
1162
+ const until = Number.isFinite(reset) && reset > 0 ? new Date(reset * 1000).toISOString() : "the next window"
1163
+ throw Object.assign(new Error(`Wait for the quota to reset: GitHub's hourly GraphQL limit is used up, rate limited until ${until} (HTTP ${response.status} for /graphql)`), { code: "drains_rate_limited", status: response.status, rateLimited: true })
1164
+ }
1165
+ if (!response.ok) throw failedAnswer(response.status, "/graphql")
1166
+ if (!payload || (Array.isArray(payload.errors) && payload.errors.length > 0) || typeof payload.data !== "object" || payload.data === null) {
1167
+ const said = Array.isArray(payload?.errors) ? payload.errors.map((error) => String(error?.message ?? "")).join("; ").slice(0, 160) : "no data"
1168
+ throw Object.assign(new Error(`Read GitHub's answer, then retry on the next poll: its GraphQL answer for the issue's edit history was refused or unreadable (${said}); that is not by itself a credential problem`), { code: "drains_graphql_failed" })
1169
+ }
1170
+ return payload.data
1171
+ }
1172
+ // One page of an issue's edit history, from its start or, with `backward`, from its end, after `cursor`. `hasMore` says whether
1173
+ // more lies beyond in that direction; `total` and `updatedAt` are the issue's as this page saw them.
1174
+ const editPage = async (repo, number, { backward = false, cursor = null } = {}) => {
1175
+ const [owner, name] = repo.split("/")
1176
+ const data = await graphql(backward ? EDITS_BACKWARD : EDITS_FORWARD, { owner, name, number, cursor })
1177
+ if (Number.isFinite(data.rateLimit?.cost)) meter.graphqlCost = data.rateLimit.cost
1178
+ const found = data.repository?.issue
1179
+ if (!found) return null
1180
+ const connection = found.userContentEdits
1181
+ const info = connection?.pageInfo
1182
+ if (!Array.isArray(connection?.nodes) || typeof info?.[backward ? "hasPreviousPage" : "hasNextPage"] !== "boolean") return { edits: null }
1183
+ return {
1184
+ updatedAt: found.updatedAt,
1185
+ total: connection.totalCount,
1186
+ edits: connection.nodes.map((node) => ({ id: node?.id ?? null, editedAt: node?.editedAt ?? null, deletedAt: node?.deletedAt ?? null, editor: node?.editor ? { type: node.editor.__typename ?? null, login: node.editor.login ?? null } : null })),
1187
+ hasMore: backward ? info.hasPreviousPage : info.hasNextPage,
1188
+ cursor: backward ? info.startCursor : info.endCursor,
1189
+ }
1190
+ }
755
1191
  // Who the token really is decides which comments are the drain's own, so each drain's account is resolved from the token that polls its repository.
756
1192
  const login = knownLogin || (await get("/user").then(({ body }) => String(body.login ?? ""), () => "")) || account || ""
757
1193
  return {
@@ -774,6 +1210,9 @@ export async function connectGithub(account, { spawn = spawnSync, fetchImpl = fe
774
1210
  get,
775
1211
  send,
776
1212
  quota: () => meter.quota,
1213
+ graphqlQuota: () => meter.graphqlQuota,
1214
+ editPage,
1215
+ graphqlCost: () => meter.graphqlCost,
777
1216
  calls: () => ({ total: meter.total, notModified: meter.notModified }),
778
1217
  timeline: (repo, issue) => all(`/repos/${repo}/issues/${issue}/timeline`),
779
1218
  pull: async (repo, number) => (await get(`/repos/${repo}/pulls/${number}`)).body,