@indigoai-us/hq-cli 5.345.252 → 5.345.253

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/CHANGELOG.md +41 -0
  2. package/contracts/host-canary-release.json +5 -5
  3. package/dist/command-catalog.generated.d.ts +148 -0
  4. package/dist/command-catalog.generated.js +182 -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 +15 -0
  8. package/dist/commands/ci-intake.js +252 -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.d.ts +13 -0
  12. package/dist/commands/ci.js +10 -0
  13. package/dist/commands/files.d.ts +62 -0
  14. package/dist/commands/files.js +249 -8
  15. package/dist/lib/bot/fleet-cron.d.ts +15 -0
  16. package/dist/lib/bot/fleet-cron.js +119 -20
  17. package/dist/lib/daemon/run.js +4 -3
  18. package/dist/lib/delivery/migrations.d.ts +32 -1
  19. package/dist/lib/delivery/migrations.js +69 -8
  20. package/dist/lib/hook-engine/adapter-core-pin.d.ts +2 -1
  21. package/dist/lib/hook-engine/adapter-core-pin.js +2 -1
  22. package/dist/lib/hook-engine/coverage.d.ts +15 -0
  23. package/dist/lib/hook-engine/coverage.js +62 -1
  24. package/dist/lib/smart-ci/cost.d.ts +72 -0
  25. package/dist/lib/smart-ci/cost.js +120 -0
  26. package/dist/lib/smart-ci/github.d.ts +112 -0
  27. package/dist/lib/smart-ci/github.js +267 -0
  28. package/dist/lib/smart-ci/intake.d.ts +288 -0
  29. package/dist/lib/smart-ci/intake.js +1078 -0
  30. package/dist/lib/smart-ci/ledger.d.ts +218 -0
  31. package/dist/lib/smart-ci/ledger.js +527 -0
  32. package/dist/lib/smart-ci/metrics.d.ts +137 -0
  33. package/dist/lib/smart-ci/metrics.js +249 -0
  34. package/dist/lib/smart-ci/records.d.ts +265 -0
  35. package/dist/lib/smart-ci/records.js +281 -0
  36. package/dist/lib/smart-ci/reducer.d.ts +67 -0
  37. package/dist/lib/smart-ci/reducer.js +261 -0
  38. package/dist/lib/sync-core/engine-holds.d.ts +14 -0
  39. package/dist/lib/sync-core/engine-holds.js +78 -11
  40. package/dist/lib/sync-core/hand-back.d.ts +1 -0
  41. package/dist/lib/sync-core/hand-back.js +7 -2
  42. package/dist/lib/sync-core/reconcile.js +10 -2
  43. package/package.json +9 -7
@@ -0,0 +1,267 @@
1
+ /**
2
+ * Read-only GitHub client for the Smart CI intake (smart-ci US-001).
3
+ *
4
+ * This client can only read. It has one request function, and that function
5
+ * sends GET: there is no method argument, so no caller can make it write. It
6
+ * also refuses any path outside the short list of read endpoints the intake
7
+ * uses, so a mistake elsewhere cannot reach, say, a rerun or cancel URL.
8
+ *
9
+ * Every request is written to an audit log (one JSON line: time, method, path,
10
+ * status, whether it was conditional, and the rate-limit numbers GitHub
11
+ * returned). The token is never logged. The audit log is the evidence that the
12
+ * intake made no write call and of how many requests it makes an hour.
13
+ *
14
+ * Conditional requests: the ETag of each response is kept, and the next
15
+ * request for the same path sends If-None-Match. GitHub answers 304 with no
16
+ * body when nothing changed, and a 304 does not count against the rate limit
17
+ * (checked against x-ratelimit-used in the audit log of a live hour: the
18
+ * counter did not move on a 304). So the client counts two things: every
19
+ * request, and the charged ones (every answer but a 304).
20
+ *
21
+ * The audit log is bounded: when it passes auditMaxBytes it is renamed to
22
+ * `<name>.1`, replacing the one before, and a new file is started.
23
+ */
24
+ import { appendFileSync, existsSync, mkdirSync, renameSync, statSync } from "node:fs";
25
+ import { dirname } from "node:path";
26
+ export const GITHUB_API = "https://api.github.com";
27
+ /** The only paths the intake may request. Each is a read endpoint. */
28
+ const ALLOWED_PATHS = [
29
+ /^\/repos\/[\w.-]+\/[\w.-]+\/actions\/runs(\?[^#]*)?$/,
30
+ /^\/repos\/[\w.-]+\/[\w.-]+\/actions\/runs\/\d+$/,
31
+ /^\/repos\/[\w.-]+\/[\w.-]+\/actions\/runs\/\d+\/jobs(\?[^#]*)?$/,
32
+ /^\/repos\/[\w.-]+\/[\w.-]+\/commits\/[0-9a-f]{7,64}\/check-runs(\?[^#]*)?$/,
33
+ /^\/repos\/[\w.-]+\/[\w.-]+\/pulls(\?[^#]*)?$/,
34
+ /^\/repos\/[\w.-]+\/[\w.-]+\/activity(\?[^#]*)?$/,
35
+ /^\/orgs\/[\w.-]+\/actions\/runners(\?[^#]*)?$/,
36
+ /^\/rate_limit$/,
37
+ ];
38
+ export class GitHubReadError extends Error {
39
+ status;
40
+ path;
41
+ retryAfterSeconds;
42
+ constructor(message, status, path,
43
+ /** Seconds to wait before another request, when GitHub said so. */
44
+ retryAfterSeconds = null) {
45
+ super(message);
46
+ this.status = status;
47
+ this.path = path;
48
+ this.retryAfterSeconds = retryAfterSeconds;
49
+ this.name = "GitHubReadError";
50
+ }
51
+ }
52
+ export class GitHubReadClient {
53
+ token;
54
+ baseUrl;
55
+ fetchImpl;
56
+ clock;
57
+ auditPath;
58
+ auditMaxBytes;
59
+ auditBytes = 0;
60
+ onRequest;
61
+ userAgent;
62
+ etags = new Map();
63
+ recent = [];
64
+ total = 0;
65
+ notModified = 0;
66
+ errors = 0;
67
+ rateRemaining = null;
68
+ rateResetAt = null;
69
+ constructor(opts) {
70
+ if (opts.token.trim() === "")
71
+ throw new Error("GitHubReadClient: a token is required");
72
+ this.token = opts.token;
73
+ this.baseUrl = (opts.baseUrl ?? GITHUB_API).replace(/\/+$/, "");
74
+ this.fetchImpl = opts.fetch ?? globalThis.fetch;
75
+ this.clock = opts.clock ?? Date.now;
76
+ this.auditPath = opts.auditPath;
77
+ this.onRequest = opts.onRequest;
78
+ this.userAgent = opts.userAgent ?? "hq-smart-ci-intake";
79
+ this.auditMaxBytes = Math.max(1024, opts.auditMaxBytes ?? 16 * 1024 * 1024);
80
+ if (this.auditPath) {
81
+ mkdirSync(dirname(this.auditPath), { recursive: true });
82
+ this.auditBytes = existsSync(this.auditPath) ? statSync(this.auditPath).size : 0;
83
+ }
84
+ }
85
+ /**
86
+ * GET one allowed path. With `conditional` (the default) a known ETag is sent
87
+ * and a 304 comes back as notModified. Throws GitHubReadError for any other
88
+ * status than 200 or 304.
89
+ */
90
+ async get(path, opts = {}) {
91
+ const segments = path.split("?")[0].split("/");
92
+ if (segments.includes("..") || segments.includes(".") || !ALLOWED_PATHS.some((p) => p.test(path))) {
93
+ throw new GitHubReadError(`refused: ${path.split("?")[0]} is not one of the read endpoints the Smart CI intake may call`, 0, path);
94
+ }
95
+ const etag = opts.conditional === false ? undefined : this.etags.get(path);
96
+ const headers = {
97
+ accept: "application/vnd.github+json",
98
+ authorization: `Bearer ${this.token}`,
99
+ "user-agent": this.userAgent,
100
+ "x-github-api-version": "2022-11-28",
101
+ };
102
+ if (etag)
103
+ headers["if-none-match"] = etag;
104
+ let status = 0;
105
+ let res = null;
106
+ try {
107
+ res = await this.fetchImpl(`${this.baseUrl}${path}`, { method: "GET", headers });
108
+ status = res.status;
109
+ }
110
+ catch (err) {
111
+ // No answer at all (DNS, a reset connection, a sleeping laptop). Reported like any failed read, so a poll cycle skips this stream and tries again.
112
+ throw new GitHubReadError(`could not reach GitHub for GET ${path.split("?")[0]}: ${err instanceof Error ? err.message : String(err)}`, 0, path);
113
+ }
114
+ finally {
115
+ const remaining = res ? intHeader(res.headers.get("x-ratelimit-remaining")) : null;
116
+ const reset = res ? intHeader(res.headers.get("x-ratelimit-reset")) : null;
117
+ if (remaining !== null)
118
+ this.rateRemaining = remaining;
119
+ if (reset !== null)
120
+ this.rateResetAt = reset * 1000;
121
+ this.record({
122
+ ts: new Date(this.clock()).toISOString(),
123
+ method: "GET",
124
+ path,
125
+ status,
126
+ conditional: etag !== undefined,
127
+ rateRemaining: remaining,
128
+ rateUsed: res ? intHeader(res.headers.get("x-ratelimit-used")) : null,
129
+ });
130
+ }
131
+ if (res === null)
132
+ throw new GitHubReadError(`could not reach GitHub for GET ${path.split("?")[0]}`, 0, path);
133
+ if (status === 304)
134
+ return { status, notModified: true, body: null, nextQuery: null };
135
+ let text;
136
+ try {
137
+ text = await res.text();
138
+ }
139
+ catch (err) {
140
+ throw new GitHubReadError(`the answer to GET ${path.split("?")[0]} was cut off: ${err instanceof Error ? err.message : String(err)}`, 0, path);
141
+ }
142
+ if (status !== 200) {
143
+ const retryAfter = intHeader(res.headers.get("retry-after"));
144
+ throw new GitHubReadError(`GitHub answered ${status} for GET ${path.split("?")[0]}`, status, path, retryAfter);
145
+ }
146
+ const newEtag = res.headers.get("etag");
147
+ if (newEtag)
148
+ this.etags.set(path, newEtag);
149
+ let body;
150
+ try {
151
+ body = JSON.parse(text);
152
+ }
153
+ catch {
154
+ throw new GitHubReadError(`GitHub answered 200 for GET ${path.split("?")[0]} with a body that is not JSON`, status, path);
155
+ }
156
+ return { status, notModified: false, body, nextQuery: this.nextQuery(res.headers.get("link")) };
157
+ }
158
+ /** Forget the ETag of a path, so the next read returns the body again. */
159
+ forget(path) {
160
+ this.etags.delete(path);
161
+ }
162
+ /** Forget every ETag: what was read since the last commit did not reach the ledger. */
163
+ forgetAll() {
164
+ this.etags.clear();
165
+ }
166
+ /** Charged requests (every answer but a 304) of the last hour, by clock minute, oldest first. */
167
+ chargedByMinute() {
168
+ this.counts();
169
+ const out = new Map();
170
+ for (const r of this.recent)
171
+ if (r.counted)
172
+ out.set(Math.floor(r.at / 60_000), (out.get(Math.floor(r.at / 60_000)) ?? 0) + 1);
173
+ return [...out].sort((a, b) => a[0] - b[0]);
174
+ }
175
+ nextQuery(link) {
176
+ if (!link)
177
+ return null;
178
+ for (const part of link.split(",")) {
179
+ const m = /<([^>]+)>;\s*rel="next"/.exec(part);
180
+ if (!m)
181
+ continue;
182
+ try {
183
+ return new URL(m[1]).search.replace(/^\?/, "");
184
+ }
185
+ catch {
186
+ return null;
187
+ }
188
+ }
189
+ return null;
190
+ }
191
+ record(entry) {
192
+ this.total += 1;
193
+ if (entry.status === 304)
194
+ this.notModified += 1;
195
+ if (entry.status !== 200 && entry.status !== 304)
196
+ this.errors += 1;
197
+ this.recent.push({ at: this.clock(), counted: entry.status !== 304 });
198
+ if (this.auditPath) {
199
+ const line = `${JSON.stringify(entry)}\n`;
200
+ if (this.auditBytes > 0 && this.auditBytes + line.length > this.auditMaxBytes) {
201
+ renameSync(this.auditPath, `${this.auditPath}.1`);
202
+ this.auditBytes = 0;
203
+ }
204
+ appendFileSync(this.auditPath, line);
205
+ this.auditBytes += line.length;
206
+ }
207
+ this.onRequest?.(entry);
208
+ }
209
+ counts() {
210
+ const cutoff = this.clock() - 3_600_000;
211
+ while (this.recent.length > 0 && this.recent[0].at < cutoff)
212
+ this.recent.shift();
213
+ return {
214
+ total: this.total,
215
+ notModified: this.notModified,
216
+ errors: this.errors,
217
+ lastHour: this.recent.length,
218
+ lastHourCounted: this.recent.filter((r) => r.counted).length,
219
+ rateRemaining: this.rateRemaining,
220
+ };
221
+ }
222
+ /** When GitHub's rate window resets, in clock milliseconds, or null when not yet known. */
223
+ rateResetsAt() {
224
+ return this.rateResetAt;
225
+ }
226
+ }
227
+ function intHeader(v) {
228
+ if (v === null || !/^\d+$/.test(v.trim()))
229
+ return null;
230
+ return Number(v.trim());
231
+ }
232
+ /** Read an audit log and count its requests. Any method other than GET is a write call. */
233
+ export function summarizeAudit(lines) {
234
+ let requests = 0;
235
+ let writes = 0;
236
+ let notModified = 0;
237
+ let firstAt = null;
238
+ let lastAt = null;
239
+ const byStatus = {};
240
+ for (const line of lines) {
241
+ if (line.trim() === "")
242
+ continue;
243
+ const e = JSON.parse(line);
244
+ requests += 1;
245
+ if (e.method !== "GET")
246
+ writes += 1;
247
+ if (e.status === 304)
248
+ notModified += 1;
249
+ byStatus[String(e.status)] = (byStatus[String(e.status)] ?? 0) + 1;
250
+ if (typeof e.ts === "string") {
251
+ firstAt ??= e.ts;
252
+ lastAt = e.ts;
253
+ }
254
+ }
255
+ const hours = firstAt && lastAt ? (Date.parse(lastAt) - Date.parse(firstAt)) / 3_600_000 : 0;
256
+ return {
257
+ requests,
258
+ writes,
259
+ notModified,
260
+ byStatus,
261
+ firstAt,
262
+ lastAt,
263
+ perHour: hours > 0 ? requests / hours : null,
264
+ countedPerHour: hours > 0 ? (requests - notModified) / hours : null,
265
+ };
266
+ }
267
+ //# sourceMappingURL=github.js.map
@@ -0,0 +1,288 @@
1
+ import { type GitHubReadClient, type RequestCounts } from "./github.js";
2
+ import type { ApplyReport, CursorMove, SmartCiLedger } from "./ledger.js";
3
+ import { OBSERVATION_TYPES, type Observation, type RunBody } from "./records.js";
4
+ export declare class IntakeInputError extends Error {
5
+ constructor(message: string);
6
+ }
7
+ /**
8
+ * Reduces observations to records and commits them with their cursors.
9
+ *
10
+ * stage() adds to a batch held in memory; flush() writes the batch and its
11
+ * cursors in one commit. Reads through the engine (runs, peek, cursor) see the
12
+ * batch laid over the ledger, so a poll cycle can act on what it has just read
13
+ * before anything is committed.
14
+ */
15
+ export declare class IntakeEngine {
16
+ private readonly ledger;
17
+ private reducer;
18
+ private readonly cursors;
19
+ constructor(ledger: SmartCiLedger);
20
+ /** Add observations and cursor moves to the batch. A malformed observation refuses the whole call; nothing of it is staged. */
21
+ stage(observations: readonly Observation[], cursors?: readonly CursorMove[]): void;
22
+ /** Add a record that is not derived from an observation (a gap note) to the batch. */
23
+ stageRecord(kind: string, id: string, body: Record<string, unknown>): void;
24
+ /** Commit the batch: its records and cursors, plus any cursors given here, in one commit. */
25
+ flush(extraCursors?: readonly CursorMove[]): ApplyReport;
26
+ /** Record a batch and move the cursors in one commit. A malformed observation refuses the whole batch; nothing is written. */
27
+ apply(observations: readonly Observation[], cursors?: readonly CursorMove[]): ApplyReport;
28
+ /** Drop the batch and read the ledger again. */
29
+ reset(): void;
30
+ /** Every run record, as it will be after the batch. */
31
+ runs(): RunBody[];
32
+ peek<T extends Record<string, unknown>>(kind: string, id: string): T | undefined;
33
+ cursor(stream: string): string | null;
34
+ }
35
+ export interface FixtureHeader {
36
+ id: string;
37
+ repo: string;
38
+ from: string;
39
+ to: string;
40
+ recordedAt: string;
41
+ observations: number;
42
+ }
43
+ export interface Fixture {
44
+ header: FixtureHeader;
45
+ observations: Observation[];
46
+ }
47
+ /** One header line, then one observation per line. */
48
+ export declare function serializeFixture(header: Omit<FixtureHeader, "id" | "observations">, observations: readonly Observation[]): string;
49
+ /** Read a fixture file (.jsonl or .jsonl.gz). Every line is validated; a bad line is refused with its number. */
50
+ export declare function readFixture(path: string): Fixture;
51
+ export interface ReplayReport {
52
+ fixtureId: string;
53
+ total: number;
54
+ /** Observations already recorded by an earlier run and skipped. */
55
+ resumedFrom: number;
56
+ applied: number;
57
+ batches: number;
58
+ created: number;
59
+ updated: number;
60
+ unchanged: number;
61
+ }
62
+ export declare const fixtureStream: (fixtureId: string) => string;
63
+ /**
64
+ * Replay a fixture into the ledger in batches. The cursor is the count of
65
+ * observations recorded, and it moves in the same commit as each batch, so a
66
+ * replay killed part way continues at the first unrecorded observation, and a
67
+ * second replay of a finished fixture writes nothing.
68
+ */
69
+ export declare function replayFixture(ledger: SmartCiLedger, fixture: Fixture, opts?: {
70
+ batchSize?: number;
71
+ fromStart?: boolean;
72
+ onBatch?: (done: number, total: number) => void;
73
+ }): ReplayReport;
74
+ export interface PollerOptions {
75
+ repos: string[];
76
+ /** Org whose runner pools are sampled, or null to skip. */
77
+ runnerOrg: string | null;
78
+ /**
79
+ * Record runs, pull requests and pushes from this time on. Used only for a
80
+ * ledger that has no cursor yet. GitHub gives times in whole seconds, so the
81
+ * start is taken down to its whole second: a run created in the second the
82
+ * intake starts is recorded.
83
+ */
84
+ startAt: string;
85
+ /** Ask again for the jobs of a run that is still going at most this often. Default 10 minutes. */
86
+ activeRefreshMs?: number;
87
+ /** Ask by id for the state of an open run the listing no longer reaches at most this often. Default 2 minutes. */
88
+ statusRefreshMs?: number;
89
+ /** Sample the runner pools at most this often. Default 2 minutes. */
90
+ runnerSampleMs?: number;
91
+ /**
92
+ * List the runs GitHub reports as queued or in progress at most this often:
93
+ * how reruns of older runs are found. Default 0, every cycle. Each listing is
94
+ * a conditional request, so an unchanged one is not charged.
95
+ */
96
+ rerunSweepMs?: number;
97
+ /** Read the run listing again this far behind the cursor, for runs GitHub lists late. Default 15 minutes. */
98
+ overlapMs?: number;
99
+ /** Pages of 100 a listing is followed for in one cycle. Past it the cursor moves on and a gap record is written. Default 10. */
100
+ maxListPages?: number;
101
+ /**
102
+ * Charged requests (every answer but a 304) the intake allows itself in any
103
+ * hour, counted across restarts. Every request is checked against it.
104
+ * Default 1500.
105
+ */
106
+ hourlyBudget?: number;
107
+ /** Make no request while GitHub reports this many or fewer left in the login's hourly allowance. Default 500. */
108
+ rateFloor?: number;
109
+ /** Read the check runs of each finished run's head. Default true. */
110
+ checkRuns?: boolean;
111
+ /** Closed records last written longer ago than this are moved to archive files. 0 keeps everything in the active file. Default 2 hours. */
112
+ activeWindowMs?: number;
113
+ /** Look for records to archive at most this often. Default 15 minutes. */
114
+ rotateEveryMs?: number;
115
+ clock?: () => number;
116
+ log?: (line: string) => void;
117
+ }
118
+ export interface CycleReport {
119
+ startedAt: string;
120
+ observations: number;
121
+ created: number;
122
+ updated: number;
123
+ runsFinalized: number;
124
+ openRuns: number;
125
+ skipped: string[];
126
+ /** Gap records written this cycle. */
127
+ gaps: number;
128
+ /** Records moved to archive files this cycle. */
129
+ archived: number;
130
+ /** Charged requests in the last hour, counted across restarts: the number the budget is checked against. */
131
+ chargedLastHour: number;
132
+ requests: RequestCounts;
133
+ }
134
+ export declare const DEFAULT_HOURLY_BUDGET = 1500;
135
+ export declare const DEFAULT_RATE_FLOOR = 500;
136
+ /** A time in milliseconds taken down to its whole second, the precision of GitHub's timestamps. */
137
+ export declare function wholeSecond(ms: number): number;
138
+ /** Charged requests by clock minute for the last hour, as JSON: the budget's memory across restarts. */
139
+ export declare const REQUEST_COUNT_STREAM = "smart-ci:requests:github";
140
+ /** Polls GitHub for the configured repos and records what changed, one commit a cycle. */
141
+ export declare class Poller {
142
+ private readonly ledger;
143
+ private readonly client;
144
+ private readonly opts;
145
+ private readonly engine;
146
+ private readonly clock;
147
+ private readonly log;
148
+ private readonly activeRefreshMs;
149
+ private readonly statusRefreshMs;
150
+ private readonly runnerSampleMs;
151
+ private readonly rerunSweepMs;
152
+ private readonly overlapMs;
153
+ private readonly maxListPages;
154
+ private readonly hourlyBudget;
155
+ private readonly rateFloor;
156
+ private readonly activeWindowMs;
157
+ private readonly rotateEveryMs;
158
+ private readonly lastJobsFetch;
159
+ private readonly lastStatusCheck;
160
+ /** Runs whose jobs filled more than one page: read without If-None-Match. */
161
+ private readonly multiPage;
162
+ private readonly checkedShas;
163
+ private readonly checkQueue;
164
+ private readonly lastRerunSweep;
165
+ /** Per repo: the oldest created_at the last run listing reached. Runs newer than this had their status read from the listing. */
166
+ private readonly listingFloor;
167
+ /** Per repo: the oldest created_at on page 1 of the last full listing. */
168
+ private readonly pageOneFloor;
169
+ /** Charged requests of earlier processes in the last hour, by clock minute. */
170
+ private carried;
171
+ /** No requests before this clock time: set when GitHub rate limits the intake or the allowance is low. */
172
+ private pausedUntil;
173
+ private lastRunnerSample;
174
+ private lastRotate;
175
+ private runnersUnavailable;
176
+ private readonly get;
177
+ /** opts.startAt taken down to its whole second. */
178
+ private readonly startAt;
179
+ constructor(ledger: SmartCiLedger, client: GitHubReadClient, opts: PollerOptions);
180
+ /** Charged requests in the last hour: this process's and, from the ledger, those of the processes before it. */
181
+ chargedLastHour(): number;
182
+ /**
183
+ * True when one more request may be made now. `reserve` is the share of the
184
+ * budget this kind of read leaves for more important ones.
185
+ */
186
+ private allow;
187
+ /** The one way the poller makes a request: refused once the budget or the rate floor is reached. */
188
+ private read;
189
+ /**
190
+ * Put what a stream read into the cycle's batch. An observation GitHub
191
+ * returned in a shape the ledger cannot hold is left out and logged, so one
192
+ * odd object cannot stop the stream or pin its cursor.
193
+ */
194
+ private stage;
195
+ private gap;
196
+ /**
197
+ * One pass over every repo and the runner pools, committed once at the end.
198
+ * A failed stream is logged and the others still run. With `sweep`, every
199
+ * open run is asked for its state and jobs whatever its last read time: the
200
+ * intake does this once as it stops.
201
+ */
202
+ cycle(opts?: {
203
+ sweep?: boolean;
204
+ }): Promise<CycleReport>;
205
+ /** The last pass before the intake stops: every open run is read once more, within the budget. */
206
+ finish(): Promise<CycleReport>;
207
+ private requestCountPosition;
208
+ /** Move closed records older than the active window into archive files, so the file each commit rewrites stays small. */
209
+ private rotate;
210
+ /** After a rate-limit answer, stop asking until GitHub's stated time. A plain permission refusal is not one. */
211
+ private backOff;
212
+ private openRuns;
213
+ /**
214
+ * Read the newest runs, page by page, back to a little behind the cursor.
215
+ *
216
+ * - Every run created at or after `cursor - overlap` is recorded, so a run
217
+ * GitHub lists late is still picked up; records are keyed, so reading the
218
+ * overlap again writes nothing. A run behind the cursor that is older than
219
+ * the active window is left alone: its record may have moved to an
220
+ * archive file, and reading it as new would record it a second time.
221
+ * - Older runs on the pages read are recorded only when the ledger holds
222
+ * them open (a status change) or when they are a new attempt that changed
223
+ * inside the overlap (a rerun).
224
+ * - The listing never pages back for an old open run: those are asked for
225
+ * by id (refreshOpenRuns).
226
+ * - Each page is checked against the request budget, and at most
227
+ * maxListPages are read. When either stops the read short of the cursor,
228
+ * the cursor still moves to the newest run and the stretch not read is
229
+ * written as a gap record, so a long stop costs a bounded number of
230
+ * requests once and the hole is visible in the ledger.
231
+ */
232
+ private discoverRuns;
233
+ /**
234
+ * List the runs GitHub reports as in progress or queued, one page each. A
235
+ * rerun keeps its original created_at, so the listing by creation time never
236
+ * shows the rerun of an old run; this does. It also finds a run that is
237
+ * active but was never recorded.
238
+ */
239
+ private sweepActiveRuns;
240
+ /**
241
+ * For each run not yet final: once it completed, read all of its jobs and
242
+ * mark it final in the same commit, provided every job of that attempt
243
+ * reads completed; while it is going, read its jobs at most every
244
+ * activeRefreshMs. Completed runs first, then the runs read longest ago. A
245
+ * run that cannot be read is logged and the next one is still tried.
246
+ */
247
+ private refreshOpenRuns;
248
+ private queueCheckRuns;
249
+ /**
250
+ * Check runs of the heads whose runs finished, read last and only while a
251
+ * fifth of the budget is still free: a workflow job is itself a check run
252
+ * and is already recorded, so this adds only the checks other apps report.
253
+ */
254
+ private readCheckRuns;
255
+ private readPulls;
256
+ private readActivity;
257
+ private sampleRunners;
258
+ }
259
+ export interface RecordOptions {
260
+ repo: string;
261
+ /** Inclusive start, ISO. */
262
+ from: string;
263
+ /** Exclusive end, ISO. */
264
+ to: string;
265
+ checkRuns?: boolean;
266
+ log?: (line: string) => void;
267
+ }
268
+ /**
269
+ * Read one past window of a repo from GitHub and return it as the stream of
270
+ * observations a live intake would have seen, in time order: each run when it
271
+ * was created and when it completed, each job when it was queued, started and
272
+ * finished, each push, each pull request that was opened, merged or closed in
273
+ * the window, and the check runs of each head. Read-only.
274
+ */
275
+ export declare function recordWindow(client: GitHubReadClient, opts: RecordOptions): Promise<Observation[]>;
276
+ /** Lines of a serialized fixture that hold an email address or something shaped like a credential. Empty means clean. */
277
+ export declare function findSensitive(text: string): Array<{
278
+ line: number;
279
+ what: string;
280
+ }>;
281
+ /**
282
+ * Remove email addresses and credential-shaped text from the free-text fields
283
+ * of an observation (a pull request title, a branch name). Every other field
284
+ * is an id, a time, a status or a label.
285
+ */
286
+ export declare function scrubObservation(o: Observation): Observation;
287
+ export { OBSERVATION_TYPES };
288
+ //# sourceMappingURL=intake.d.ts.map