@indigoai-us/hq-cli 5.345.252 → 5.345.254

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 (67) hide show
  1. package/CHANGELOG.md +73 -0
  2. package/contracts/host-canary-release.json +11 -5
  3. package/dist/command-catalog.generated.d.ts +209 -0
  4. package/dist/command-catalog.generated.js +257 -0
  5. package/dist/command-registration-plan.d.ts +6 -0
  6. package/dist/command-registration-plan.js +1 -0
  7. package/dist/commands/ci-intake.d.ts +32 -0
  8. package/dist/commands/ci-intake.js +294 -0
  9. package/dist/commands/ci-metrics.d.ts +8 -0
  10. package/dist/commands/ci-metrics.js +55 -0
  11. package/dist/commands/ci-priorities.d.ts +56 -0
  12. package/dist/commands/ci-priorities.js +144 -0
  13. package/dist/commands/ci.d.ts +13 -0
  14. package/dist/commands/ci.js +11 -0
  15. package/dist/commands/cloud.d.ts +11 -0
  16. package/dist/commands/cloud.js +76 -0
  17. package/dist/commands/files.d.ts +62 -0
  18. package/dist/commands/files.js +249 -8
  19. package/dist/lib/bot/fleet-cron.d.ts +15 -0
  20. package/dist/lib/bot/fleet-cron.js +119 -20
  21. package/dist/lib/daemon/run.js +4 -3
  22. package/dist/lib/daemon/verified-jq.d.ts +6 -0
  23. package/dist/lib/daemon/verified-jq.js +17 -5
  24. package/dist/lib/delivery/migrations.d.ts +32 -1
  25. package/dist/lib/delivery/migrations.js +69 -8
  26. package/dist/lib/hook-engine/adapter-core-pin.d.ts +2 -1
  27. package/dist/lib/hook-engine/adapter-core-pin.js +2 -1
  28. package/dist/lib/hook-engine/coverage.d.ts +15 -0
  29. package/dist/lib/hook-engine/coverage.js +62 -1
  30. package/dist/lib/hook-engine/fleet-registration.d.ts +4 -0
  31. package/dist/lib/hook-engine/fleet-registration.js +25 -3
  32. package/dist/lib/smart-ci/cost.d.ts +72 -0
  33. package/dist/lib/smart-ci/cost.js +120 -0
  34. package/dist/lib/smart-ci/github.d.ts +112 -0
  35. package/dist/lib/smart-ci/github.js +267 -0
  36. package/dist/lib/smart-ci/intake.d.ts +288 -0
  37. package/dist/lib/smart-ci/intake.js +1078 -0
  38. package/dist/lib/smart-ci/ledger.d.ts +218 -0
  39. package/dist/lib/smart-ci/ledger.js +527 -0
  40. package/dist/lib/smart-ci/metrics.d.ts +137 -0
  41. package/dist/lib/smart-ci/metrics.js +249 -0
  42. package/dist/lib/smart-ci/priorities.d.ts +331 -0
  43. package/dist/lib/smart-ci/priorities.js +964 -0
  44. package/dist/lib/smart-ci/priority-refresh.d.ts +192 -0
  45. package/dist/lib/smart-ci/priority-refresh.js +366 -0
  46. package/dist/lib/smart-ci/priority-snapshots.d.ts +88 -0
  47. package/dist/lib/smart-ci/priority-snapshots.js +233 -0
  48. package/dist/lib/smart-ci/records.d.ts +265 -0
  49. package/dist/lib/smart-ci/records.js +281 -0
  50. package/dist/lib/smart-ci/reducer.d.ts +67 -0
  51. package/dist/lib/smart-ci/reducer.js +261 -0
  52. package/dist/lib/smart-ci/sources.d.ts +294 -0
  53. package/dist/lib/smart-ci/sources.js +659 -0
  54. package/dist/lib/smart-ci/text.d.ts +24 -0
  55. package/dist/lib/smart-ci/text.js +83 -0
  56. package/dist/lib/smart-ci/work-in-flight.d.ts +68 -0
  57. package/dist/lib/smart-ci/work-in-flight.js +154 -0
  58. package/dist/lib/sync/cli-manifest-reconcile.d.ts +20 -0
  59. package/dist/lib/sync/cli-manifest-reconcile.js +170 -0
  60. package/dist/lib/sync-core/engine-holds.d.ts +14 -0
  61. package/dist/lib/sync-core/engine-holds.js +78 -11
  62. package/dist/lib/sync-core/hand-back.d.ts +1 -0
  63. package/dist/lib/sync-core/hand-back.js +7 -2
  64. package/dist/lib/sync-core/reconcile.js +10 -2
  65. package/dist/utils/host-registration.d.ts +1 -0
  66. package/dist/utils/host-registration.js +1 -1
  67. package/package.json +9 -7
@@ -0,0 +1,1078 @@
1
+ /**
2
+ * Smart CI intake (smart-ci US-001): reads what CI did and records it.
3
+ *
4
+ * Three ways in, one way to the ledger. The poller reads GitHub with
5
+ * conditional GET requests. replayFixture reads a recorded file of
6
+ * observations. recordWindow reads a past window from GitHub and returns the
7
+ * observations for a fixture. All of them hand observations to IntakeEngine,
8
+ * which reduces them to records and commits records and cursors together.
9
+ *
10
+ * The intake only reads GitHub. It registers no webhook and calls no endpoint
11
+ * that changes a run, a check, a pull request, a branch or a runner.
12
+ *
13
+ * Restart: a poll cycle is one commit, and that commit carries the cursors for
14
+ * what it covers. A run stays open in the ledger (jobsFinal false) until all
15
+ * of its jobs were recorded after it completed, and that flag is written in
16
+ * the same commit as the jobs. So a process killed at any point restarts from
17
+ * the cursors and the open runs on disk, reads a little again, and the keyed
18
+ * records absorb the repeat.
19
+ *
20
+ * Requests: every request the poller makes is checked against an hourly
21
+ * budget of charged requests. The count is kept in the ledger, so a restart
22
+ * does not start a new allowance.
23
+ */
24
+ import { createHash } from "node:crypto";
25
+ import { existsSync, readFileSync } from "node:fs";
26
+ import { gunzipSync } from "node:zlib";
27
+ import { GitHubReadError } from "./github.js";
28
+ import { KIND, OBSERVATION_TYPES, ROTATED_KINDS, checkRunFromApi, jobFromApi, pullRequestFromApi, pushFromApi, runFromApi, runKey, runnerSampleFromApi, validateObservation, } from "./records.js";
29
+ import { Reducer } from "./reducer.js";
30
+ export class IntakeInputError extends Error {
31
+ constructor(message) {
32
+ super(message);
33
+ this.name = "IntakeInputError";
34
+ }
35
+ }
36
+ /**
37
+ * Reduces observations to records and commits them with their cursors.
38
+ *
39
+ * stage() adds to a batch held in memory; flush() writes the batch and its
40
+ * cursors in one commit. Reads through the engine (runs, peek, cursor) see the
41
+ * batch laid over the ledger, so a poll cycle can act on what it has just read
42
+ * before anything is committed.
43
+ */
44
+ export class IntakeEngine {
45
+ ledger;
46
+ reducer;
47
+ cursors = new Map();
48
+ constructor(ledger) {
49
+ this.ledger = ledger;
50
+ this.reducer = new Reducer(ledger);
51
+ }
52
+ /** Add observations and cursor moves to the batch. A malformed observation refuses the whole call; nothing of it is staged. */
53
+ stage(observations, cursors = []) {
54
+ observations.forEach((o, i) => {
55
+ const errors = validateObservation(o);
56
+ if (errors.length > 0)
57
+ throw new IntakeInputError(`observation ${i + 1} of ${observations.length} is malformed: ${errors.slice(0, 3).join("; ")}`);
58
+ });
59
+ try {
60
+ for (const o of observations)
61
+ this.reducer.reduce(o);
62
+ }
63
+ catch (err) {
64
+ this.reset();
65
+ throw err;
66
+ }
67
+ for (const c of cursors)
68
+ this.cursors.set(c.stream, c.position);
69
+ }
70
+ /** Add a record that is not derived from an observation (a gap note) to the batch. */
71
+ stageRecord(kind, id, body) {
72
+ this.reducer.put(kind, id, body);
73
+ }
74
+ /** Commit the batch: its records and cursors, plus any cursors given here, in one commit. */
75
+ flush(extraCursors = []) {
76
+ for (const c of extraCursors)
77
+ this.cursors.set(c.stream, c.position);
78
+ try {
79
+ const report = this.ledger.apply(this.reducer.take(), [...this.cursors].map(([stream, position]) => ({ stream, position })));
80
+ this.cursors.clear();
81
+ return report;
82
+ }
83
+ catch (err) {
84
+ // The reducer's indexes may hold records that never reached disk; rebuild from the ledger.
85
+ this.reset();
86
+ throw err;
87
+ }
88
+ }
89
+ /** Record a batch and move the cursors in one commit. A malformed observation refuses the whole batch; nothing is written. */
90
+ apply(observations, cursors = []) {
91
+ this.stage(observations, cursors);
92
+ return this.flush();
93
+ }
94
+ /** Drop the batch and read the ledger again. */
95
+ reset() {
96
+ this.reducer = new Reducer(this.ledger);
97
+ this.cursors.clear();
98
+ }
99
+ /** Every run record, as it will be after the batch. */
100
+ runs() {
101
+ return this.reducer.list(KIND.run, (r) => runKey(r.repo, r.runId, r.attempt));
102
+ }
103
+ peek(kind, id) {
104
+ return this.reducer.peek(kind, id);
105
+ }
106
+ cursor(stream) {
107
+ return this.cursors.get(stream) ?? this.ledger.cursor(stream);
108
+ }
109
+ }
110
+ /** One header line, then one observation per line. */
111
+ export function serializeFixture(header, observations) {
112
+ const lines = observations.map((o) => JSON.stringify(o));
113
+ const id = createHash("sha256").update(lines.join("\n")).digest("hex").slice(0, 16);
114
+ const full = { id, repo: header.repo, from: header.from, to: header.to, recordedAt: header.recordedAt, observations: observations.length };
115
+ return `${JSON.stringify({ fixture: full })}\n${lines.join("\n")}\n`;
116
+ }
117
+ /** Read a fixture file (.jsonl or .jsonl.gz). Every line is validated; a bad line is refused with its number. */
118
+ export function readFixture(path) {
119
+ if (!existsSync(path))
120
+ throw new IntakeInputError(`no fixture file at ${path}`);
121
+ const raw = readFileSync(path);
122
+ const text = path.endsWith(".gz") ? gunzipSync(raw).toString("utf8") : raw.toString("utf8");
123
+ const lines = text.split("\n").filter((l) => l.trim() !== "");
124
+ if (lines.length === 0)
125
+ throw new IntakeInputError(`${path} is empty`);
126
+ let header;
127
+ try {
128
+ header = JSON.parse(lines[0]).fixture;
129
+ }
130
+ catch {
131
+ throw new IntakeInputError(`${path} line 1 is not a fixture header`);
132
+ }
133
+ if (!header || typeof header.id !== "string" || header.id === "" || typeof header.observations !== "number") {
134
+ throw new IntakeInputError(`${path} line 1 is not a fixture header`);
135
+ }
136
+ const observations = [];
137
+ for (let i = 1; i < lines.length; i++) {
138
+ let parsed;
139
+ try {
140
+ parsed = JSON.parse(lines[i]);
141
+ }
142
+ catch {
143
+ throw new IntakeInputError(`${path} line ${i + 1} is not JSON`);
144
+ }
145
+ const errors = validateObservation(parsed);
146
+ if (errors.length > 0)
147
+ throw new IntakeInputError(`${path} line ${i + 1}: ${errors.slice(0, 3).join("; ")}`);
148
+ observations.push(parsed);
149
+ }
150
+ if (observations.length !== header.observations) {
151
+ throw new IntakeInputError(`${path} holds ${observations.length} observations but its header says ${header.observations}; the file is cut short or was edited`);
152
+ }
153
+ return { header, observations };
154
+ }
155
+ export const fixtureStream = (fixtureId) => `fixture:${fixtureId}`;
156
+ /**
157
+ * Replay a fixture into the ledger in batches. The cursor is the count of
158
+ * observations recorded, and it moves in the same commit as each batch, so a
159
+ * replay killed part way continues at the first unrecorded observation, and a
160
+ * second replay of a finished fixture writes nothing.
161
+ */
162
+ export function replayFixture(ledger, fixture, opts = {}) {
163
+ const batchSize = Math.max(1, Math.floor(opts.batchSize ?? 200));
164
+ const stream = fixtureStream(fixture.header.id);
165
+ const total = fixture.observations.length;
166
+ const saved = Number(ledger.cursor(stream) ?? "0");
167
+ const start = opts.fromStart ? 0 : Number.isInteger(saved) && saved >= 0 && saved <= total ? saved : 0;
168
+ const engine = new IntakeEngine(ledger);
169
+ const report = { fixtureId: fixture.header.id, total, resumedFrom: start, applied: 0, batches: 0, created: 0, updated: 0, unchanged: 0 };
170
+ for (let at = start; at < total; at += batchSize) {
171
+ const batch = fixture.observations.slice(at, at + batchSize);
172
+ const done = at + batch.length;
173
+ // Replaying from the start again must not move a finished cursor backwards.
174
+ const position = String(Math.max(done, opts.fromStart ? saved : 0));
175
+ const r = engine.apply(batch, [{ stream, position }]);
176
+ report.applied += batch.length;
177
+ report.batches += 1;
178
+ report.created += r.created;
179
+ report.updated += r.updated;
180
+ report.unchanged += r.unchanged;
181
+ opts.onBatch?.(done, total);
182
+ }
183
+ return report;
184
+ }
185
+ // ---------------------------------------------------------------------------
186
+ // Reading GitHub.
187
+ function list(body, key) {
188
+ const v = key === undefined ? body : body?.[key];
189
+ return Array.isArray(v) ? v : [];
190
+ }
191
+ function repoParts(repo) {
192
+ const m = /^([\w.-]+)\/([\w.-]+)$/.exec(repo);
193
+ if (!m)
194
+ throw new IntakeInputError(`repo must be owner/name, got ${JSON.stringify(repo)}`);
195
+ return { owner: m[1], name: m[2] };
196
+ }
197
+ /**
198
+ * Every job of one run, all attempts, following pages. null when nothing
199
+ * changed since the last read (304 on the first page). A 304 on page 1 says
200
+ * nothing about later pages, so a run known to have more than one page must be
201
+ * read with `conditional` false.
202
+ */
203
+ async function fetchJobs(get, repo, runId, conditional) {
204
+ const jobs = [];
205
+ let pages = 0;
206
+ for (let page = 1; page <= 20; page++) {
207
+ const res = await get(`/repos/${repo}/actions/runs/${runId}/jobs?filter=all&per_page=100&page=${page}`, { conditional: conditional && page === 1 });
208
+ if (res.notModified)
209
+ return null;
210
+ pages = page;
211
+ const pageJobs = list(res.body, "jobs");
212
+ for (const j of pageJobs)
213
+ jobs.push(jobFromApi(j));
214
+ if (pageJobs.length < 100)
215
+ break;
216
+ }
217
+ return { jobs, pages };
218
+ }
219
+ async function fetchCheckRuns(get, repo, sha) {
220
+ const out = [];
221
+ for (let page = 1; page <= 10; page++) {
222
+ const res = await get(`/repos/${repo}/commits/${sha}/check-runs?filter=all&per_page=100&page=${page}`, { conditional: false });
223
+ const runs = list(res.body, "check_runs");
224
+ for (const c of runs)
225
+ out.push({ type: "check_run", repo, checkRun: checkRunFromApi(c) });
226
+ if (runs.length < 100)
227
+ break;
228
+ }
229
+ return out;
230
+ }
231
+ export const DEFAULT_HOURLY_BUDGET = 1500;
232
+ export const DEFAULT_RATE_FLOOR = 500;
233
+ /** A completed run whose jobs still do not all read completed is closed anyway after this long without a change. */
234
+ const FINALIZE_GIVE_UP_MS = 30 * 60_000;
235
+ /**
236
+ * A completed run that lists no job yet is read again until it has been quiet
237
+ * this long. GitHub creates the job of a skipped run a few seconds after the
238
+ * run itself reads completed (seen live: run completed at :16, job created at
239
+ * :22), so one read straight after completion can come back empty.
240
+ */
241
+ const EMPTY_RUN_SETTLE_MS = 120_000;
242
+ const JUST_COMPLETED_MS = 20_000;
243
+ /** Share of the budget kept back from reads that can wait: pull requests, pushes and runner samples, then check runs. */
244
+ const RESERVE_SECONDARY = 0.05;
245
+ const RESERVE_CHECK_RUNS = 0.2;
246
+ const MAX_QUEUED_CHECKS = 500;
247
+ /** A time in milliseconds taken down to its whole second, the precision of GitHub's timestamps. */
248
+ export function wholeSecond(ms) {
249
+ return Math.floor(ms / 1000) * 1000;
250
+ }
251
+ const runsStream = (repo) => `github:${repo}:runs`;
252
+ const runsOriginStream = (repo) => `github:${repo}:runs:origin`;
253
+ const pullsStream = (repo) => `github:${repo}:pulls`;
254
+ const activityStream = (repo) => `github:${repo}:activity`;
255
+ /** Charged requests by clock minute for the last hour, as JSON: the budget's memory across restarts. */
256
+ export const REQUEST_COUNT_STREAM = "smart-ci:requests:github";
257
+ /** Thrown inside a cycle when the next request would pass the budget or the rate floor. */
258
+ class BudgetStop extends Error {
259
+ }
260
+ function parseMinutes(position) {
261
+ if (position === null)
262
+ return [];
263
+ try {
264
+ const v = JSON.parse(position);
265
+ if (!Array.isArray(v))
266
+ return [];
267
+ return v.filter((e) => Array.isArray(e) && e.length === 2 && Number.isInteger(e[0]) && Number.isInteger(e[1]) && e[1] >= 0);
268
+ }
269
+ catch {
270
+ return [];
271
+ }
272
+ }
273
+ /** Polls GitHub for the configured repos and records what changed, one commit a cycle. */
274
+ export class Poller {
275
+ ledger;
276
+ client;
277
+ opts;
278
+ engine;
279
+ clock;
280
+ log;
281
+ activeRefreshMs;
282
+ statusRefreshMs;
283
+ runnerSampleMs;
284
+ rerunSweepMs;
285
+ overlapMs;
286
+ maxListPages;
287
+ hourlyBudget;
288
+ rateFloor;
289
+ activeWindowMs;
290
+ rotateEveryMs;
291
+ lastJobsFetch = new Map();
292
+ lastStatusCheck = new Map();
293
+ /** Runs whose jobs filled more than one page: read without If-None-Match. */
294
+ multiPage = new Set();
295
+ checkedShas = new Map();
296
+ checkQueue = new Map();
297
+ lastRerunSweep = new Map();
298
+ /** Per repo: the oldest created_at the last run listing reached. Runs newer than this had their status read from the listing. */
299
+ listingFloor = new Map();
300
+ /** Per repo: the oldest created_at on page 1 of the last full listing. */
301
+ pageOneFloor = new Map();
302
+ /** Charged requests of earlier processes in the last hour, by clock minute. */
303
+ carried;
304
+ /** No requests before this clock time: set when GitHub rate limits the intake or the allowance is low. */
305
+ pausedUntil = 0;
306
+ lastRunnerSample = 0;
307
+ lastRotate = 0;
308
+ runnersUnavailable = false;
309
+ get;
310
+ /** opts.startAt taken down to its whole second. */
311
+ startAt;
312
+ constructor(ledger, client, opts) {
313
+ this.ledger = ledger;
314
+ this.client = client;
315
+ this.opts = opts;
316
+ for (const r of opts.repos)
317
+ repoParts(r);
318
+ if (Number.isNaN(Date.parse(opts.startAt)))
319
+ throw new IntakeInputError(`startAt is not a time: ${opts.startAt}`);
320
+ this.startAt = new Date(wholeSecond(Date.parse(opts.startAt))).toISOString();
321
+ this.engine = new IntakeEngine(ledger);
322
+ this.clock = opts.clock ?? Date.now;
323
+ this.log = opts.log ?? (() => undefined);
324
+ this.activeRefreshMs = opts.activeRefreshMs ?? 600_000;
325
+ this.statusRefreshMs = opts.statusRefreshMs ?? 120_000;
326
+ this.runnerSampleMs = opts.runnerSampleMs ?? 120_000;
327
+ this.rerunSweepMs = opts.rerunSweepMs ?? 0;
328
+ this.overlapMs = opts.overlapMs ?? 900_000;
329
+ this.maxListPages = Math.max(1, Math.floor(opts.maxListPages ?? 10));
330
+ this.hourlyBudget = opts.hourlyBudget ?? DEFAULT_HOURLY_BUDGET;
331
+ this.rateFloor = opts.rateFloor ?? DEFAULT_RATE_FLOOR;
332
+ this.activeWindowMs = opts.activeWindowMs ?? 7_200_000;
333
+ this.rotateEveryMs = opts.rotateEveryMs ?? 900_000;
334
+ this.carried = parseMinutes(ledger.cursor(REQUEST_COUNT_STREAM));
335
+ this.get = (path, o) => this.read(path, o);
336
+ }
337
+ /** Charged requests in the last hour: this process's and, from the ledger, those of the processes before it. */
338
+ chargedLastHour() {
339
+ const cutoff = Math.floor((this.clock() - 3_600_000) / 60_000);
340
+ this.carried = this.carried.filter(([minute]) => minute > cutoff);
341
+ return this.carried.reduce((s, [, n]) => s + n, 0) + this.client.counts().lastHourCounted;
342
+ }
343
+ /**
344
+ * True when one more request may be made now. `reserve` is the share of the
345
+ * budget this kind of read leaves for more important ones.
346
+ */
347
+ allow(reserve = 0) {
348
+ const now = this.clock();
349
+ if (now < this.pausedUntil)
350
+ return false;
351
+ const remaining = this.client.counts().rateRemaining;
352
+ const reset = this.client.rateResetsAt();
353
+ // The number GitHub last reported is only good until its window resets.
354
+ if (remaining !== null && remaining <= this.rateFloor && reset !== null && now < reset) {
355
+ this.pausedUntil = reset;
356
+ this.log(`GitHub reports ${remaining} requests left for this login, at or under the floor of ${this.rateFloor}; no requests until ${new Date(reset).toISOString()}`);
357
+ return false;
358
+ }
359
+ return this.chargedLastHour() < this.hourlyBudget * (1 - reserve);
360
+ }
361
+ /** The one way the poller makes a request: refused once the budget or the rate floor is reached. */
362
+ async read(path, opts = {}, reserve = 0) {
363
+ if (!this.allow(reserve))
364
+ throw new BudgetStop();
365
+ return this.client.get(path, opts);
366
+ }
367
+ /**
368
+ * Put what a stream read into the cycle's batch. An observation GitHub
369
+ * returned in a shape the ledger cannot hold is left out and logged, so one
370
+ * odd object cannot stop the stream or pin its cursor.
371
+ */
372
+ stage(observations, cursors, report) {
373
+ const good = observations.filter((o) => {
374
+ const errors = validateObservation(o);
375
+ if (errors.length === 0)
376
+ return true;
377
+ const note = `left out one ${o.type} observation GitHub returned malformed: ${errors[0]}`;
378
+ report.skipped.push(note);
379
+ this.log(note);
380
+ return false;
381
+ });
382
+ this.engine.stage(good, cursors);
383
+ report.observations += good.length;
384
+ }
385
+ gap(repo, stream, fromMs, toMs, reason, report) {
386
+ if (!(toMs > fromMs))
387
+ return;
388
+ const body = { repo, stream, from: new Date(fromMs).toISOString(), to: new Date(toMs).toISOString(), reason, notedAt: new Date(this.clock()).toISOString() };
389
+ this.engine.stageRecord(KIND.gap, `${repo}/${stream}/${body.from}/${body.to}`, body);
390
+ report.gaps += 1;
391
+ const note = `${repo} ${stream}: not read from ${body.from} to ${body.to} (${reason}); recorded as a gap and the cursor moved on`;
392
+ report.skipped.push(note);
393
+ this.log(note);
394
+ }
395
+ /**
396
+ * One pass over every repo and the runner pools, committed once at the end.
397
+ * A failed stream is logged and the others still run. With `sweep`, every
398
+ * open run is asked for its state and jobs whatever its last read time: the
399
+ * intake does this once as it stops.
400
+ */
401
+ async cycle(opts = {}) {
402
+ const report = {
403
+ startedAt: new Date(this.clock()).toISOString(),
404
+ observations: 0,
405
+ created: 0,
406
+ updated: 0,
407
+ runsFinalized: 0,
408
+ openRuns: 0,
409
+ skipped: [],
410
+ gaps: 0,
411
+ archived: 0,
412
+ chargedLastHour: this.chargedLastHour(),
413
+ requests: this.client.counts(),
414
+ };
415
+ if (this.clock() < this.pausedUntil) {
416
+ report.skipped.push(`paused until ${new Date(this.pausedUntil).toISOString()}: GitHub asked the intake to slow down`);
417
+ return report;
418
+ }
419
+ const guarded = async (what, fn) => {
420
+ if (this.clock() < this.pausedUntil)
421
+ return;
422
+ try {
423
+ await fn();
424
+ }
425
+ catch (err) {
426
+ if (err instanceof BudgetStop) {
427
+ report.skipped.push(`${what}: request budget reached, read next cycle`);
428
+ return;
429
+ }
430
+ if (!(err instanceof GitHubReadError))
431
+ throw err;
432
+ report.skipped.push(`${what}: ${err.message}`);
433
+ this.log(`skipped ${what}: ${err.message}`);
434
+ this.backOff(err);
435
+ }
436
+ };
437
+ try {
438
+ for (const repo of this.opts.repos) {
439
+ await guarded(`${repo} runs`, () => this.discoverRuns(repo, report));
440
+ await guarded(`${repo} active runs`, () => this.sweepActiveRuns(repo, report, opts.sweep === true));
441
+ await guarded(`${repo} open runs`, () => this.refreshOpenRuns(repo, report, opts.sweep === true));
442
+ }
443
+ for (const repo of this.opts.repos) {
444
+ await guarded(`${repo} pull requests`, () => this.readPulls(repo, report));
445
+ await guarded(`${repo} pushes`, () => this.readActivity(repo, report));
446
+ }
447
+ if (this.opts.runnerOrg !== null)
448
+ await guarded("runner pools", () => this.sampleRunners(this.opts.runnerOrg, report));
449
+ await guarded("check runs", () => this.readCheckRuns(report));
450
+ const applied = this.engine.flush([{ stream: REQUEST_COUNT_STREAM, position: this.requestCountPosition() }]);
451
+ report.created = applied.created;
452
+ report.updated = applied.updated;
453
+ }
454
+ catch (err) {
455
+ // Nothing of this cycle reached the ledger: forget what it read, so the next cycle reads it again.
456
+ this.client.forgetAll();
457
+ this.engine.reset();
458
+ this.lastJobsFetch.clear();
459
+ this.lastStatusCheck.clear();
460
+ this.lastRerunSweep.clear();
461
+ this.checkedShas.clear();
462
+ this.lastRunnerSample = 0;
463
+ throw err;
464
+ }
465
+ report.archived = this.rotate();
466
+ report.openRuns = this.engine.runs().filter((r) => !r.jobsFinal && this.opts.repos.includes(r.repo)).length;
467
+ report.chargedLastHour = this.chargedLastHour();
468
+ report.requests = this.client.counts();
469
+ return report;
470
+ }
471
+ /** The last pass before the intake stops: every open run is read once more, within the budget. */
472
+ finish() {
473
+ return this.cycle({ sweep: true });
474
+ }
475
+ requestCountPosition() {
476
+ this.chargedLastHour();
477
+ const merged = new Map(this.carried);
478
+ for (const [minute, n] of this.client.chargedByMinute())
479
+ merged.set(minute, (merged.get(minute) ?? 0) + n);
480
+ return JSON.stringify([...merged].sort((a, b) => a[0] - b[0]));
481
+ }
482
+ /** Move closed records older than the active window into archive files, so the file each commit rewrites stays small. */
483
+ rotate() {
484
+ const now = this.clock();
485
+ if (this.activeWindowMs <= 0 || now - this.lastRotate < this.rotateEveryMs)
486
+ return 0;
487
+ this.lastRotate = now;
488
+ const open = new Set(this.ledger.list(KIND.run).filter((r) => !r.jobsFinal).map((r) => runKey(r.repo, r.runId, r.attempt)));
489
+ const moved = this.ledger.rotate({
490
+ kinds: ROTATED_KINDS,
491
+ olderThan: new Date(now - this.activeWindowMs).toISOString(),
492
+ keep: (rec) => {
493
+ if (rec.kind === KIND.run)
494
+ return !rec.body.jobsFinal;
495
+ if (rec.kind === KIND.job) {
496
+ const j = rec.body;
497
+ return open.has(runKey(j.repo, j.runId, j.runAttempt));
498
+ }
499
+ if (rec.kind === KIND.pullRequest)
500
+ return rec.body.state === "open";
501
+ return false;
502
+ },
503
+ }).moved;
504
+ // The reducer indexes what is in the active file; drop what left it.
505
+ if (moved > 0)
506
+ this.engine.reset();
507
+ return moved;
508
+ }
509
+ /** After a rate-limit answer, stop asking until GitHub's stated time. A plain permission refusal is not one. */
510
+ backOff(err) {
511
+ if (err.status !== 403 && err.status !== 429)
512
+ return;
513
+ const now = this.clock();
514
+ const exhausted = this.client.counts().rateRemaining === 0;
515
+ if (err.retryAfterSeconds === null && !exhausted && err.status !== 429)
516
+ return;
517
+ const reset = this.client.rateResetsAt();
518
+ const until = err.retryAfterSeconds !== null ? now + err.retryAfterSeconds * 1000 : exhausted && reset !== null && reset > now ? reset : now + 60_000;
519
+ this.pausedUntil = Math.max(this.pausedUntil, until);
520
+ this.log(`GitHub is rate limiting the intake; no requests until ${new Date(this.pausedUntil).toISOString()}`);
521
+ }
522
+ openRuns(repo) {
523
+ return this.engine
524
+ .runs()
525
+ .filter((r) => r.repo === repo && !r.jobsFinal)
526
+ .sort((a, b) => Date.parse(a.createdAt) - Date.parse(b.createdAt));
527
+ }
528
+ /**
529
+ * Read the newest runs, page by page, back to a little behind the cursor.
530
+ *
531
+ * - Every run created at or after `cursor - overlap` is recorded, so a run
532
+ * GitHub lists late is still picked up; records are keyed, so reading the
533
+ * overlap again writes nothing. A run behind the cursor that is older than
534
+ * the active window is left alone: its record may have moved to an
535
+ * archive file, and reading it as new would record it a second time.
536
+ * - Older runs on the pages read are recorded only when the ledger holds
537
+ * them open (a status change) or when they are a new attempt that changed
538
+ * inside the overlap (a rerun).
539
+ * - The listing never pages back for an old open run: those are asked for
540
+ * by id (refreshOpenRuns).
541
+ * - Each page is checked against the request budget, and at most
542
+ * maxListPages are read. When either stops the read short of the cursor,
543
+ * the cursor still moves to the newest run and the stretch not read is
544
+ * written as a gap record, so a long stop costs a bounded number of
545
+ * requests once and the hole is visible in the ledger.
546
+ */
547
+ async discoverRuns(repo, report) {
548
+ const stream = runsStream(repo);
549
+ const saved = this.ledger.cursor(stream);
550
+ const savedOrigin = this.ledger.cursor(runsOriginStream(repo));
551
+ // The first start time of this ledger for this repo: nothing older is recorded as new.
552
+ const origin = savedOrigin ?? (saved !== null && Date.parse(saved) < Date.parse(this.startAt) ? saved : this.startAt);
553
+ // An origin saved by an earlier build can hold milliseconds; compare at GitHub's whole seconds.
554
+ const originMs = wholeSecond(Date.parse(origin));
555
+ const cursor = saved ?? origin;
556
+ const cursorMs = Date.parse(cursor);
557
+ const floor = saved === null ? originMs : Math.max(originMs, cursorMs - this.overlapMs);
558
+ // Nothing created after this can have been archived yet.
559
+ const notArchived = this.activeWindowMs > 0 ? this.clock() - this.activeWindowMs : Number.NEGATIVE_INFINITY;
560
+ const openIds = new Set(this.openRuns(repo).map((r) => r.runId));
561
+ const observations = [];
562
+ let newest = cursor;
563
+ let reached = false;
564
+ let oldestReached = Number.POSITIVE_INFINITY;
565
+ let stoppedBy = "page limit";
566
+ const firstPage = `/repos/${repo}/actions/runs?per_page=100&page=1`;
567
+ try {
568
+ for (let page = 1; page <= this.maxListPages; page++) {
569
+ if (!this.allow()) {
570
+ if (page === 1)
571
+ throw new BudgetStop();
572
+ stoppedBy = "request budget";
573
+ break;
574
+ }
575
+ const res = await this.client.get(`/repos/${repo}/actions/runs?per_page=100&page=${page}`, { conditional: page === 1 });
576
+ if (res.notModified) {
577
+ // Page 1 is unchanged, which says nothing about older pages: open runs older than page 1 are asked for by id.
578
+ this.listingFloor.set(repo, this.pageOneFloor.get(repo) ?? Number.POSITIVE_INFINITY);
579
+ return;
580
+ }
581
+ const runs = list(res.body, "workflow_runs").map(runFromApi);
582
+ let oldestOnPage = Number.POSITIVE_INFINITY;
583
+ for (const run of runs) {
584
+ const created = Date.parse(run.createdAt);
585
+ if (Number.isNaN(created))
586
+ continue;
587
+ oldestOnPage = Math.min(oldestOnPage, created);
588
+ const fresh = saved === null ? created >= originMs : created > cursorMs;
589
+ if (!fresh && !(created >= floor && created >= notArchived)) {
590
+ const changedLately = run.updatedAt !== null && Date.parse(run.updatedAt) >= floor && Date.parse(run.updatedAt) >= notArchived;
591
+ const rerun = run.attempt > 1 && changedLately && this.engine.peek(KIND.run, runKey(repo, run.id, run.attempt)) === undefined;
592
+ if (!openIds.has(run.id) && !rerun)
593
+ continue;
594
+ }
595
+ observations.push({ type: "workflow_run", repo, run });
596
+ if (created > Date.parse(newest))
597
+ newest = run.createdAt;
598
+ }
599
+ if (page === 1)
600
+ this.pageOneFloor.set(repo, oldestOnPage);
601
+ this.listingFloor.set(repo, oldestOnPage);
602
+ oldestReached = Math.min(oldestReached, oldestOnPage);
603
+ if (runs.length < 100 || oldestOnPage < floor) {
604
+ reached = true;
605
+ break;
606
+ }
607
+ }
608
+ if (!reached)
609
+ this.gap(repo, "runs", floor, oldestReached, `${stoppedBy} reached while listing runs`, report);
610
+ const cursors = [{ stream, position: newest }];
611
+ if (savedOrigin === null)
612
+ cursors.push({ stream: runsOriginStream(repo), position: origin });
613
+ this.stage(observations, cursors, report);
614
+ }
615
+ catch (err) {
616
+ // The ETag of page 1 was kept before its runs were staged; without this the next read would answer 304 and skip them.
617
+ this.client.forget(firstPage);
618
+ throw err;
619
+ }
620
+ }
621
+ /**
622
+ * List the runs GitHub reports as in progress or queued, one page each. A
623
+ * rerun keeps its original created_at, so the listing by creation time never
624
+ * shows the rerun of an old run; this does. It also finds a run that is
625
+ * active but was never recorded.
626
+ */
627
+ async sweepActiveRuns(repo, report, force) {
628
+ const now = this.clock();
629
+ if (!force && now - (this.lastRerunSweep.get(repo) ?? Number.NEGATIVE_INFINITY) < this.rerunSweepMs)
630
+ return;
631
+ const origin = this.engine.cursor(runsOriginStream(repo)) ?? this.startAt;
632
+ const originMs = wholeSecond(Date.parse(origin));
633
+ const observations = [];
634
+ for (const status of ["in_progress", "queued"]) {
635
+ const res = await this.read(`/repos/${repo}/actions/runs?status=${status}&per_page=100`, { conditional: true }, RESERVE_SECONDARY);
636
+ if (res.notModified)
637
+ continue;
638
+ for (const run of list(res.body, "workflow_runs").map(runFromApi)) {
639
+ const created = Date.parse(run.createdAt);
640
+ if (Number.isNaN(created))
641
+ continue;
642
+ if (created >= originMs || run.attempt > 1)
643
+ observations.push({ type: "workflow_run", repo, run });
644
+ }
645
+ }
646
+ this.lastRerunSweep.set(repo, now);
647
+ this.stage(observations, [], report);
648
+ }
649
+ /**
650
+ * For each run not yet final: once it completed, read all of its jobs and
651
+ * mark it final in the same commit, provided every job of that attempt
652
+ * reads completed; while it is going, read its jobs at most every
653
+ * activeRefreshMs. Completed runs first, then the runs read longest ago. A
654
+ * run that cannot be read is logged and the next one is still tried.
655
+ */
656
+ async refreshOpenRuns(repo, report, force) {
657
+ const now = this.clock();
658
+ const all = this.engine.runs().filter((r) => r.repo === repo);
659
+ const latestAttempt = new Map();
660
+ for (const r of all)
661
+ latestAttempt.set(r.runId, Math.max(latestAttempt.get(r.runId) ?? 0, r.attempt));
662
+ const keyOfRun = (r) => `${repo}/${r.runId}/${r.attempt}`;
663
+ const isDone = (r) => r.status === "completed" || r.attempt < (latestAttempt.get(r.runId) ?? r.attempt);
664
+ const open = all
665
+ .filter((r) => !r.jobsFinal)
666
+ .sort((a, b) => Number(isDone(b)) - Number(isDone(a)) || (this.lastJobsFetch.get(keyOfRun(a)) ?? 0) - (this.lastJobsFetch.get(keyOfRun(b)) ?? 0) || Date.parse(a.createdAt) - Date.parse(b.createdAt));
667
+ for (const listed of open) {
668
+ const key = keyOfRun(listed);
669
+ let run = listed;
670
+ try {
671
+ let superseded = run.attempt < (latestAttempt.get(run.runId) ?? run.attempt);
672
+ // A run older than what the listing covered is asked for by id, so its completion or rerun is still seen.
673
+ const beyondListing = Date.parse(run.createdAt) < (this.listingFloor.get(repo) ?? Number.POSITIVE_INFINITY);
674
+ if (run.status !== "completed" && !superseded && beyondListing && (force || now - (this.lastStatusCheck.get(key) ?? Number.NEGATIVE_INFINITY) >= this.statusRefreshMs)) {
675
+ const single = await this.read(`/repos/${repo}/actions/runs/${run.runId}`);
676
+ this.lastStatusCheck.set(key, now);
677
+ if (!single.notModified) {
678
+ const seen = runFromApi(single.body);
679
+ this.stage([{ type: "workflow_run", repo, run: seen }], [], report);
680
+ if (seen.attempt > run.attempt)
681
+ superseded = true;
682
+ else
683
+ run = this.engine.peek(KIND.run, runKey(repo, run.runId, run.attempt)) ?? run;
684
+ }
685
+ }
686
+ if (run.status === "completed" || superseded) {
687
+ const read = await fetchJobs(this.get, repo, run.runId, false);
688
+ const jobs = read?.jobs ?? [];
689
+ const mine = jobs.filter((j) => j.runAttempt === run.attempt);
690
+ const unfinished = mine.filter((j) => j.status !== "completed").length;
691
+ const quietMs = now - Date.parse(run.updatedAt ?? run.createdAt);
692
+ // Any run read within seconds of completing is read once more, in case a job is still being created.
693
+ const settling = quietMs < JUST_COMPLETED_MS || (mine.length === 0 && quietMs < EMPTY_RUN_SETTLE_MS);
694
+ // A rerun replaced this attempt: GitHub no longer reports it, so it is closed with the jobs it has.
695
+ const final = superseded || (unfinished === 0 && !settling) || quietMs > FINALIZE_GIVE_UP_MS;
696
+ const observations = jobs.map((job) => ({ type: "workflow_job", repo, job }));
697
+ if (final)
698
+ observations.push({ type: "workflow_run", repo, run: { ...runObservationOf(run), jobsFinal: true } });
699
+ this.stage(observations, [], report);
700
+ if (!final) {
701
+ report.skipped.push(settling
702
+ ? `${repo} run ${run.runId}: completed moments ago${mine.length === 0 ? " and lists no job yet" : ""}; read again next cycle`
703
+ : `${repo} run ${run.runId}: completed, but ${unfinished} of its jobs do not read completed yet; read again next cycle`);
704
+ continue;
705
+ }
706
+ report.runsFinalized += 1;
707
+ this.lastJobsFetch.delete(key);
708
+ this.lastStatusCheck.delete(key);
709
+ this.multiPage.delete(key);
710
+ this.queueCheckRuns(repo, run.headSha);
711
+ continue;
712
+ }
713
+ const last = this.lastJobsFetch.get(key);
714
+ if (!force && last !== undefined && now - last < this.activeRefreshMs)
715
+ continue;
716
+ const read = await fetchJobs(this.get, repo, run.runId, !this.multiPage.has(key));
717
+ this.lastJobsFetch.set(key, now);
718
+ if (read === null)
719
+ continue;
720
+ if (read.pages > 1)
721
+ this.multiPage.add(key);
722
+ this.stage(read.jobs.map((job) => ({ type: "workflow_job", repo, job })), [], report);
723
+ }
724
+ catch (err) {
725
+ if (err instanceof BudgetStop)
726
+ throw err;
727
+ if (!(err instanceof GitHubReadError))
728
+ throw err;
729
+ if (err.status === 404 || err.status === 410) {
730
+ // The run was deleted on GitHub. Close it with what was recorded, so it stops holding the queue.
731
+ this.stage([{ type: "workflow_run", repo, run: { ...runObservationOf(run), jobsFinal: true } }], [], report);
732
+ report.skipped.push(`${repo} run ${run.runId}: no longer on GitHub (${err.status}); closed with the jobs already recorded`);
733
+ continue;
734
+ }
735
+ report.skipped.push(`${repo} run ${run.runId}: ${err.message}`);
736
+ if (err.status === 403 || err.status === 429 || err.status === 0)
737
+ throw err;
738
+ }
739
+ }
740
+ }
741
+ queueCheckRuns(repo, sha) {
742
+ if (this.opts.checkRuns === false)
743
+ return;
744
+ const key = `${repo}/${sha}`;
745
+ if (this.checkedShas.has(key) || this.checkQueue.has(key))
746
+ return;
747
+ if (this.checkQueue.size >= MAX_QUEUED_CHECKS) {
748
+ const oldest = this.checkQueue.keys().next().value;
749
+ this.checkQueue.delete(oldest);
750
+ }
751
+ this.checkQueue.set(key, { repo, sha });
752
+ }
753
+ /**
754
+ * Check runs of the heads whose runs finished, read last and only while a
755
+ * fifth of the budget is still free: a workflow job is itself a check run
756
+ * and is already recorded, so this adds only the checks other apps report.
757
+ */
758
+ async readCheckRuns(report) {
759
+ const now = this.clock();
760
+ // A head's check runs are read again if another of its runs finishes later.
761
+ for (const [k, at] of this.checkedShas)
762
+ if (now - at > 600_000)
763
+ this.checkedShas.delete(k);
764
+ for (const [key, { repo, sha }] of [...this.checkQueue]) {
765
+ if (!this.allow(RESERVE_CHECK_RUNS)) {
766
+ report.skipped.push(`check runs: ${this.checkQueue.size} heads wait for request budget`);
767
+ return;
768
+ }
769
+ this.checkQueue.delete(key);
770
+ try {
771
+ const observations = await fetchCheckRuns((path, o) => this.read(path, o, RESERVE_CHECK_RUNS), repo, sha);
772
+ this.checkedShas.set(key, now);
773
+ this.stage(observations, [], report);
774
+ }
775
+ catch (err) {
776
+ if (err instanceof BudgetStop)
777
+ return;
778
+ if (!(err instanceof GitHubReadError))
779
+ throw err;
780
+ report.skipped.push(`${repo} check runs of ${sha.slice(0, 12)}: ${err.message}`);
781
+ if (err.status === 403 || err.status === 429 || err.status === 0)
782
+ throw err;
783
+ }
784
+ }
785
+ }
786
+ async readPulls(repo, report) {
787
+ const stream = pullsStream(repo);
788
+ const cursor = this.ledger.cursor(stream) ?? this.startAt;
789
+ const cursorMs = wholeSecond(Date.parse(cursor));
790
+ const observations = [];
791
+ let newest = cursor;
792
+ let reachedCursor = false;
793
+ let oldestReached = Number.POSITIVE_INFINITY;
794
+ let stoppedBy = "page limit";
795
+ const firstPage = `/repos/${repo}/pulls?state=all&sort=updated&direction=desc&per_page=100&page=1`;
796
+ try {
797
+ for (let page = 1; page <= this.maxListPages; page++) {
798
+ if (!this.allow(RESERVE_SECONDARY)) {
799
+ if (page === 1)
800
+ throw new BudgetStop();
801
+ stoppedBy = "request budget";
802
+ break;
803
+ }
804
+ const res = await this.client.get(`/repos/${repo}/pulls?state=all&sort=updated&direction=desc&per_page=100&page=${page}`, { conditional: page === 1 });
805
+ if (res.notModified)
806
+ return;
807
+ const pulls = list(res.body).map(pullRequestFromApi);
808
+ for (const pr of pulls) {
809
+ // The boundary is read again on purpose: two pull requests can share an updated_at second.
810
+ if (Date.parse(pr.updatedAt) < cursorMs) {
811
+ reachedCursor = true;
812
+ break;
813
+ }
814
+ observations.push({ type: "pull_request", repo, pr });
815
+ if (!Number.isNaN(Date.parse(pr.updatedAt)))
816
+ oldestReached = Math.min(oldestReached, Date.parse(pr.updatedAt));
817
+ if (Date.parse(pr.updatedAt) > Date.parse(newest))
818
+ newest = pr.updatedAt;
819
+ }
820
+ if (reachedCursor || pulls.length < 100) {
821
+ reachedCursor = true;
822
+ break;
823
+ }
824
+ }
825
+ if (!reachedCursor)
826
+ this.gap(repo, "pulls", cursorMs, oldestReached, `${stoppedBy} reached while listing pull requests`, report);
827
+ this.stage(observations, [{ stream, position: newest }], report);
828
+ }
829
+ catch (err) {
830
+ this.client.forget(firstPage);
831
+ throw err;
832
+ }
833
+ }
834
+ async readActivity(repo, report) {
835
+ const stream = activityStream(repo);
836
+ const cursor = this.ledger.cursor(stream) ?? this.startAt;
837
+ const cursorMs = wholeSecond(Date.parse(cursor));
838
+ const observations = [];
839
+ let newest = cursor;
840
+ let query = "per_page=100";
841
+ let reachedCursor = false;
842
+ let oldestReached = Number.POSITIVE_INFINITY;
843
+ let stoppedBy = "page limit";
844
+ try {
845
+ for (let page = 1; page <= this.maxListPages; page++) {
846
+ if (!this.allow(RESERVE_SECONDARY)) {
847
+ if (page === 1)
848
+ throw new BudgetStop();
849
+ stoppedBy = "request budget";
850
+ break;
851
+ }
852
+ const res = await this.client.get(`/repos/${repo}/activity?${query}`, { conditional: page === 1 });
853
+ if (res.notModified)
854
+ return;
855
+ const items = list(res.body).map(pushFromApi);
856
+ for (const push of items) {
857
+ if (Date.parse(push.at) < cursorMs) {
858
+ reachedCursor = true;
859
+ break;
860
+ }
861
+ observations.push({ type: "push", repo, push });
862
+ if (!Number.isNaN(Date.parse(push.at)))
863
+ oldestReached = Math.min(oldestReached, Date.parse(push.at));
864
+ if (Date.parse(push.at) > Date.parse(newest))
865
+ newest = push.at;
866
+ }
867
+ const after = res.nextQuery === null ? null : new URLSearchParams(res.nextQuery).get("after");
868
+ if (reachedCursor || after === null) {
869
+ reachedCursor = true;
870
+ break;
871
+ }
872
+ query = `per_page=100&after=${encodeURIComponent(after)}`;
873
+ }
874
+ if (!reachedCursor)
875
+ this.gap(repo, "activity", cursorMs, oldestReached, `${stoppedBy} reached while listing pushes`, report);
876
+ this.stage(observations, [{ stream, position: newest }], report);
877
+ }
878
+ catch (err) {
879
+ this.client.forget(`/repos/${repo}/activity?per_page=100`);
880
+ throw err;
881
+ }
882
+ }
883
+ async sampleRunners(org, report) {
884
+ const now = this.clock();
885
+ if (this.runnersUnavailable || now - this.lastRunnerSample < this.runnerSampleMs)
886
+ return;
887
+ const runners = [];
888
+ try {
889
+ for (let page = 1; page <= 10; page++) {
890
+ const res = await this.read(`/orgs/${org}/actions/runners?per_page=100&page=${page}`, { conditional: false }, RESERVE_SECONDARY);
891
+ const pageRunners = list(res.body, "runners");
892
+ runners.push(...pageRunners);
893
+ if (pageRunners.length < 100)
894
+ break;
895
+ }
896
+ }
897
+ catch (err) {
898
+ if (err instanceof GitHubReadError && (err.status === 403 || err.status === 404)) {
899
+ // The token cannot list org runners. Say so once and stop asking; the rest of the intake is unaffected.
900
+ this.runnersUnavailable = true;
901
+ this.log(`runner pools of ${org} cannot be read with this token (GitHub answered ${err.status}); idle runner minutes will not be measured`);
902
+ }
903
+ throw err;
904
+ }
905
+ this.lastRunnerSample = now;
906
+ const sample = runnerSampleFromApi(runners, new Date(now).toISOString());
907
+ this.stage([{ type: "runner_pool", org, sample }], [], report);
908
+ }
909
+ }
910
+ function runObservationOf(run) {
911
+ return {
912
+ id: run.runId,
913
+ attempt: run.attempt,
914
+ name: run.name,
915
+ event: run.event,
916
+ status: run.status,
917
+ conclusion: run.conclusion,
918
+ headBranch: run.headBranch,
919
+ headSha: run.headSha,
920
+ createdAt: run.createdAt,
921
+ startedAt: run.startedAt,
922
+ updatedAt: run.updatedAt,
923
+ prNumbers: run.prNumbers,
924
+ };
925
+ }
926
+ const secondsIso = (ms) => `${new Date(ms).toISOString().slice(0, 19)}Z`;
927
+ /**
928
+ * Read one past window of a repo from GitHub and return it as the stream of
929
+ * observations a live intake would have seen, in time order: each run when it
930
+ * was created and when it completed, each job when it was queued, started and
931
+ * finished, each push, each pull request that was opened, merged or closed in
932
+ * the window, and the check runs of each head. Read-only.
933
+ */
934
+ export async function recordWindow(client, opts) {
935
+ repoParts(opts.repo);
936
+ const from = Date.parse(opts.from);
937
+ const to = Date.parse(opts.to);
938
+ if (Number.isNaN(from) || Number.isNaN(to) || to <= from)
939
+ throw new IntakeInputError("record window: --from must be before --to, both ISO times");
940
+ const log = opts.log ?? (() => undefined);
941
+ const repo = opts.repo;
942
+ const timed = [];
943
+ let order = 0;
944
+ const emit = (at, o) => timed.push({ at: Date.parse(at), order: order++, o });
945
+ // Runs, an hour at a time: the created filter returns at most 1000 runs per query.
946
+ const runs = new Map();
947
+ for (let start = from; start < to; start += 3_600_000) {
948
+ const end = Math.min(start + 3_600_000, to) - 1000;
949
+ for (let page = 1; page <= 10; page++) {
950
+ const range = encodeURIComponent(`${secondsIso(start)}..${secondsIso(end)}`);
951
+ const res = await client.get(`/repos/${repo}/actions/runs?created=${range}&per_page=100&page=${page}`, { conditional: false });
952
+ const pageRuns = list(res.body, "workflow_runs").map(runFromApi);
953
+ for (const r of pageRuns)
954
+ runs.set(`${r.id}/${r.attempt}`, r);
955
+ if (pageRuns.length < 100)
956
+ break;
957
+ }
958
+ }
959
+ log(`runs in window: ${runs.size}`);
960
+ const shas = new Set();
961
+ for (const run of [...runs.values()].sort((a, b) => a.id - b.id)) {
962
+ shas.add(run.headSha);
963
+ emit(run.createdAt, { type: "workflow_run", repo, run: { ...run, status: "queued", conclusion: null, updatedAt: run.createdAt } });
964
+ const jobs = (await fetchJobs((path, o) => client.get(path, o), repo, run.id, false))?.jobs ?? [];
965
+ let lastJobAt = run.createdAt;
966
+ for (const job of jobs) {
967
+ const ran = job.runnerName !== null && job.startedAt !== null;
968
+ if (ran) {
969
+ emit(job.createdAt, { type: "workflow_job", repo, job: { ...job, status: "queued", conclusion: null, startedAt: null, completedAt: null, runnerName: null, runnerGroup: null } });
970
+ if (job.status !== "queued")
971
+ emit(job.startedAt, { type: "workflow_job", repo, job: { ...job, status: "in_progress", conclusion: null, completedAt: null } });
972
+ }
973
+ // A job that never ran (skipped, or cancelled while queued) is one observation.
974
+ if (job.status === "completed" || !ran)
975
+ emit(job.completedAt ?? job.createdAt, { type: "workflow_job", repo, job });
976
+ if (job.completedAt !== null && Date.parse(job.completedAt) > Date.parse(lastJobAt))
977
+ lastJobAt = job.completedAt;
978
+ }
979
+ const doneAt = run.status === "completed" && run.updatedAt !== null && Date.parse(run.updatedAt) > Date.parse(lastJobAt) ? run.updatedAt : lastJobAt;
980
+ emit(doneAt, { type: "workflow_run", repo, run: { ...run, jobsFinal: run.status === "completed" } });
981
+ }
982
+ log(`jobs read for ${runs.size} runs`);
983
+ // Pushes in the window.
984
+ let query = "per_page=100";
985
+ for (let page = 1; page <= 100; page++) {
986
+ const res = await client.get(`/repos/${repo}/activity?${query}`, { conditional: false });
987
+ const items = list(res.body).map(pushFromApi);
988
+ let before = false;
989
+ for (const push of items) {
990
+ const at = Date.parse(push.at);
991
+ if (at < from) {
992
+ before = true;
993
+ break;
994
+ }
995
+ if (at < to)
996
+ emit(push.at, { type: "push", repo, push });
997
+ }
998
+ const after = res.nextQuery === null ? null : new URLSearchParams(res.nextQuery).get("after");
999
+ if (before || after === null)
1000
+ break;
1001
+ query = `per_page=100&after=${encodeURIComponent(after)}`;
1002
+ }
1003
+ // Pull requests opened, merged or closed in the window, as GitHub reports them now.
1004
+ const inWindow = (t) => t !== null && Date.parse(t) >= from && Date.parse(t) < to;
1005
+ for (let page = 1; page <= 100; page++) {
1006
+ const res = await client.get(`/repos/${repo}/pulls?state=all&sort=updated&direction=desc&per_page=100&page=${page}`, { conditional: false });
1007
+ const pulls = list(res.body).map(pullRequestFromApi);
1008
+ let before = false;
1009
+ for (const pr of pulls) {
1010
+ if (Date.parse(pr.updatedAt) < from) {
1011
+ before = true;
1012
+ break;
1013
+ }
1014
+ if (!inWindow(pr.createdAt) && !inWindow(pr.mergedAt) && !inWindow(pr.closedAt))
1015
+ continue;
1016
+ const at = [pr.mergedAt, pr.closedAt, pr.createdAt].find(inWindow);
1017
+ emit(at, { type: "pull_request", repo, pr });
1018
+ }
1019
+ if (before || pulls.length < 100)
1020
+ break;
1021
+ }
1022
+ if (opts.checkRuns !== false) {
1023
+ for (const sha of [...shas].sort()) {
1024
+ for (const o of await fetchCheckRuns((path, o) => client.get(path, o), repo, sha)) {
1025
+ const c = o.checkRun;
1026
+ const at = c.completedAt ?? c.startedAt;
1027
+ if (at !== null)
1028
+ emit(at, o);
1029
+ }
1030
+ }
1031
+ log(`check runs read for ${shas.size} heads`);
1032
+ }
1033
+ timed.sort((a, b) => a.at - b.at || a.order - b.order);
1034
+ return timed.map((t) => t.o);
1035
+ }
1036
+ const EMAIL = /[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/;
1037
+ const SECRET_SHAPES = [/gh[pousr]_[A-Za-z0-9]{20,}/, /github_pat_[A-Za-z0-9_]{20,}/, /AKIA[0-9A-Z]{16}/, /-----BEGIN [A-Z ]*PRIVATE KEY-----/, /xox[baprs]-[A-Za-z0-9-]{10,}/];
1038
+ /** Lines of a serialized fixture that hold an email address or something shaped like a credential. Empty means clean. */
1039
+ export function findSensitive(text) {
1040
+ const found = [];
1041
+ text.split("\n").forEach((l, i) => {
1042
+ if (EMAIL.test(l))
1043
+ found.push({ line: i + 1, what: "email address" });
1044
+ if (SECRET_SHAPES.some((p) => p.test(l)))
1045
+ found.push({ line: i + 1, what: "credential-shaped text" });
1046
+ });
1047
+ return found;
1048
+ }
1049
+ /**
1050
+ * Remove email addresses and credential-shaped text from the free-text fields
1051
+ * of an observation (a pull request title, a branch name). Every other field
1052
+ * is an id, a time, a status or a label.
1053
+ */
1054
+ export function scrubObservation(o) {
1055
+ const clean = (s) => {
1056
+ let out = s.replace(new RegExp(EMAIL.source, "g"), "[email removed]");
1057
+ for (const p of SECRET_SHAPES)
1058
+ out = out.replace(new RegExp(p.source, "g"), "[removed]");
1059
+ return out;
1060
+ };
1061
+ const cleanOrNull = (s) => (s === null ? null : clean(s));
1062
+ switch (o.type) {
1063
+ case "pull_request":
1064
+ return { ...o, pr: { ...o.pr, title: clean(o.pr.title), headRef: clean(o.pr.headRef), baseRef: clean(o.pr.baseRef), labels: o.pr.labels.map(clean) } };
1065
+ case "workflow_run":
1066
+ return { ...o, run: { ...o.run, name: clean(o.run.name), headBranch: cleanOrNull(o.run.headBranch) } };
1067
+ case "workflow_job":
1068
+ return { ...o, job: { ...o.job, name: clean(o.job.name), workflow: clean(o.job.workflow), headBranch: cleanOrNull(o.job.headBranch), runnerName: cleanOrNull(o.job.runnerName) } };
1069
+ case "check_run":
1070
+ return { ...o, checkRun: { ...o.checkRun, name: clean(o.checkRun.name) } };
1071
+ case "push":
1072
+ return { ...o, push: { ...o.push, ref: clean(o.push.ref) } };
1073
+ default:
1074
+ return o;
1075
+ }
1076
+ }
1077
+ export { OBSERVATION_TYPES };
1078
+ //# sourceMappingURL=intake.js.map