@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,527 @@
1
+ /**
2
+ * The smart-ci namespace of the HQ Native run ledger (smart-ci US-001).
3
+ *
4
+ * Smart CI keeps its records in the delivery store's own state file, under
5
+ * `state.smartCi`, and writes them only through DeliveryStore.commit. So they
6
+ * get the store's guarantees unchanged: one owner at a time, fenced writes,
7
+ * and a commit that is either wholly on disk or not at all. There is no second
8
+ * kind of store.
9
+ *
10
+ * Exactly-once comes from two rules. A record is keyed by kind and id, so
11
+ * writing the same observation again replaces it and never adds a second one.
12
+ * A cursor moves in the same commit as the records it covers, so after a kill
13
+ * the cursor on disk never points past a record that was not written, and a
14
+ * restart reads again from there.
15
+ *
16
+ * One process owns the ledger. Other smart-ci modules in that process record
17
+ * through the same SmartCiLedger: `scope({ company, namespace })` gives them
18
+ * their own keyed records (there is no default company), a latest-of-kind
19
+ * read, a blob per record and pruning by kind. Other processes read with
20
+ * readSmartCiSnapshot or readSmartCiHistory, which take no ownership.
21
+ *
22
+ * Growth: every commit rewrites the whole state file, so the file a writer
23
+ * holds must stay small. rotate() moves old records into dated store
24
+ * directories under `archive/` (each one a delivery store of the same format,
25
+ * named for the UTC hour its records were last written) and removes them
26
+ * from the active file. readSmartCiHistory reads the active file and the
27
+ * archives together.
28
+ */
29
+ import { createHash } from "node:crypto";
30
+ import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from "node:fs";
31
+ import { homedir } from "node:os";
32
+ import { join } from "node:path";
33
+ import { parseStoreText } from "../delivery/migrations.js";
34
+ import { DeliveryStore, storeExists, withStoreSnapshot } from "../delivery/store.js";
35
+ export class SmartCiLedgerError extends Error {
36
+ code;
37
+ constructor(code, message) {
38
+ super(message);
39
+ this.code = code;
40
+ this.name = "SmartCiLedgerError";
41
+ }
42
+ }
43
+ /** Where the ledger lives when no directory is given: HQ_SMART_CI_STORE_DIR, else ~/.hq/delivery/ledger. */
44
+ export function defaultLedgerDir(env = process.env, home = homedir()) {
45
+ const override = env.HQ_SMART_CI_STORE_DIR?.trim();
46
+ return override ? override : join(home, ".hq", "delivery", "ledger");
47
+ }
48
+ const keyOf = (kind, id) => `${kind}\u0000${id}`;
49
+ /**
50
+ * Key order is part of JSON text, so two equal bodies built in a different
51
+ * field order would look different. Bodies are compared and stored in sorted
52
+ * key order.
53
+ */
54
+ function canonical(value) {
55
+ if (Array.isArray(value))
56
+ return value.map(canonical);
57
+ if (typeof value === "object" && value !== null) {
58
+ const out = {};
59
+ for (const k of Object.keys(value).sort())
60
+ out[k] = canonical(value[k]);
61
+ return out;
62
+ }
63
+ return value;
64
+ }
65
+ const asRecord = (r) => ({ kind: r.kind, id: r.id, recordedAt: r.recordedAt, updatedAt: r.updatedAt, body: r.body });
66
+ /** The record of a list that was written last. Ties go to the one later in the list. */
67
+ function latestOf(records) {
68
+ let best;
69
+ for (const r of records)
70
+ if (best === undefined || Date.parse(r.updatedAt) >= Date.parse(best.updatedAt))
71
+ best = r;
72
+ return best;
73
+ }
74
+ const SLUG = /^[a-z0-9][a-z0-9-]{0,62}$/;
75
+ const SCOPED_KIND = /^[A-Za-z0-9][A-Za-z0-9._-]{0,62}$/;
76
+ function scopePrefix(ref) {
77
+ if (typeof ref?.company !== "string" || !SLUG.test(ref.company)) {
78
+ throw new SmartCiLedgerError("SCOPE_INVALID", `a smart-ci scope needs a company slug (lower-case letters, digits and dashes); got ${JSON.stringify(ref?.company)}. There is no default company.`);
79
+ }
80
+ if (typeof ref.namespace !== "string" || !SLUG.test(ref.namespace)) {
81
+ throw new SmartCiLedgerError("SCOPE_INVALID", `a smart-ci scope needs a namespace (lower-case letters, digits and dashes); got ${JSON.stringify(ref.namespace)}`);
82
+ }
83
+ return `co:${ref.company}:${ref.namespace}:`;
84
+ }
85
+ function scopedKind(prefix, kind) {
86
+ if (!SCOPED_KIND.test(kind))
87
+ throw new SmartCiLedgerError("SCOPE_INVALID", `a scoped record kind is letters, digits, dots, dashes and underscores; got ${JSON.stringify(kind)}`);
88
+ return `${prefix}${kind}`;
89
+ }
90
+ /** The field of a record body that names its blob. */
91
+ export const BLOB_FIELD = "$blob";
92
+ function blobPath(dir, company, sha256) {
93
+ return join(dir, "blobs", company, sha256);
94
+ }
95
+ /** Read a blob by its hash and check the bytes against it. */
96
+ export function readBlob(dir, company, sha256) {
97
+ if (!SLUG.test(company) || !/^[0-9a-f]{64}$/.test(sha256))
98
+ throw new SmartCiLedgerError("BLOB_MISSING", "a blob is read by company slug and sha256");
99
+ const path = blobPath(dir, company, sha256);
100
+ if (!existsSync(path))
101
+ throw new SmartCiLedgerError("BLOB_MISSING", `no blob ${sha256} for ${company} in ${dir}`);
102
+ const bytes = readFileSync(path);
103
+ if (createHash("sha256").update(bytes).digest("hex") !== sha256)
104
+ throw new SmartCiLedgerError("BLOB_CORRUPT", `blob ${sha256} for ${company} does not match its hash`);
105
+ return bytes;
106
+ }
107
+ /** A read-only view of the namespace, with lookup by kind and id. */
108
+ export class SmartCiView {
109
+ dir;
110
+ byKey = new Map();
111
+ byKind = new Map();
112
+ cursorMap = new Map();
113
+ constructor(ns,
114
+ /** The ledger directory, when the view was read from one: needed to read blobs. */
115
+ dir = null) {
116
+ this.dir = dir;
117
+ for (const r of ns.records) {
118
+ this.byKey.set(keyOf(r.kind, r.id), r);
119
+ const list = this.byKind.get(r.kind);
120
+ if (list)
121
+ list.push(r);
122
+ else
123
+ this.byKind.set(r.kind, [r]);
124
+ }
125
+ for (const c of ns.cursors)
126
+ this.cursorMap.set(c.stream, c.position);
127
+ }
128
+ get(kind, id) {
129
+ return this.byKey.get(keyOf(kind, id))?.body;
130
+ }
131
+ list(kind) {
132
+ return (this.byKind.get(kind) ?? []).map((r) => r.body);
133
+ }
134
+ records(kind) {
135
+ return (this.byKind.get(kind) ?? []).map((r) => asRecord(r));
136
+ }
137
+ latest(kind) {
138
+ return latestOf(this.records(kind));
139
+ }
140
+ count(kind) {
141
+ return this.byKind.get(kind)?.length ?? 0;
142
+ }
143
+ cursor(stream) {
144
+ return this.cursorMap.get(stream) ?? null;
145
+ }
146
+ /** The records of one module for one company, read-only. */
147
+ scope(ref) {
148
+ return new ScopedView(this, scopePrefix(ref), ref.company);
149
+ }
150
+ }
151
+ /** Reads of one scope. Works on a snapshot, so it needs no ownership. */
152
+ export class ScopedView {
153
+ view;
154
+ prefix;
155
+ company;
156
+ constructor(view, prefix, company) {
157
+ this.view = view;
158
+ this.prefix = prefix;
159
+ this.company = company;
160
+ }
161
+ get(kind, id) {
162
+ return this.view.get(scopedKind(this.prefix, kind), id);
163
+ }
164
+ list(kind) {
165
+ return this.view.list(scopedKind(this.prefix, kind));
166
+ }
167
+ records(kind) {
168
+ return this.view.records(scopedKind(this.prefix, kind)).map((r) => ({ ...r, kind }));
169
+ }
170
+ /** The record of this kind written last, or undefined when there is none. */
171
+ latest(kind) {
172
+ const r = this.view.latest(scopedKind(this.prefix, kind));
173
+ return r === undefined ? undefined : { ...r, kind };
174
+ }
175
+ /** The blob stored with a record, or null when the record has none. */
176
+ blob(kind, id) {
177
+ const ref = this.get(kind, id)?.[BLOB_FIELD];
178
+ if (ref === undefined || this.view.dir === null)
179
+ return null;
180
+ return readBlob(this.view.dir, this.company, ref.sha256);
181
+ }
182
+ }
183
+ // ---------------------------------------------------------------------------
184
+ // Reading without ownership.
185
+ /**
186
+ * Read the committed smart-ci namespace of the active file without taking
187
+ * ownership, so a read works while the intake holds the store. Returns an
188
+ * empty namespace when the directory holds no store yet.
189
+ */
190
+ export function readSmartCiSnapshot(dir, waitMs = 5000) {
191
+ if (!storeExists(dir))
192
+ return { records: [], cursors: [] };
193
+ return withStoreSnapshot(dir, waitMs, (text) => parseStoreText(text, join(dir, "state.json")).state.smartCi);
194
+ }
195
+ const ARCHIVE_DIR = "archive";
196
+ const ARCHIVE_NAME = /^\d{4}-\d{2}-\d{2}T\d{2}$/;
197
+ const archiveName = (iso) => new Date(Date.parse(iso)).toISOString().slice(0, 13);
198
+ /** The archive directories of a ledger, oldest first. */
199
+ export function listArchives(dir) {
200
+ const root = join(dir, ARCHIVE_DIR);
201
+ if (!existsSync(root))
202
+ return [];
203
+ return readdirSync(root)
204
+ .filter((n) => ARCHIVE_NAME.test(n))
205
+ .sort();
206
+ }
207
+ /**
208
+ * The active file and the archives as one namespace, each record once. Where
209
+ * a key is in more than one file (a kill between writing an archive and
210
+ * removing the record from the active file, or a record written again after
211
+ * it was archived) the active file wins, then the newest archive.
212
+ */
213
+ export function readSmartCiHistory(dir, opts = {}) {
214
+ const waitMs = opts.waitMs ?? 5000;
215
+ const active = readSmartCiSnapshot(dir, waitMs);
216
+ const keep = opts.keep ?? (() => true);
217
+ const seen = new Set();
218
+ const records = [];
219
+ const take = (list) => {
220
+ for (const r of list) {
221
+ const key = keyOf(r.kind, r.id);
222
+ if (seen.has(key))
223
+ continue;
224
+ seen.add(key);
225
+ if (keep(r))
226
+ records.push(r);
227
+ }
228
+ };
229
+ take(active.records);
230
+ const floor = opts.since === undefined ? null : archiveName(opts.since);
231
+ for (const name of listArchives(dir).reverse()) {
232
+ if (floor !== null && name < floor)
233
+ break;
234
+ take(readSmartCiSnapshot(join(dir, ARCHIVE_DIR, name), waitMs).records);
235
+ }
236
+ return { records, cursors: active.cursors };
237
+ }
238
+ /** The single writer of the smart-ci namespace. One process holds it at a time; a second open is refused by the store. */
239
+ export class SmartCiLedger {
240
+ dir;
241
+ report;
242
+ store;
243
+ openOptions;
244
+ /** Position of each record in state.smartCi.records. */
245
+ index = new Map();
246
+ cursorIndex = new Map();
247
+ constructor(store, opts) {
248
+ this.store = store;
249
+ this.openOptions = opts;
250
+ this.dir = store.dir;
251
+ this.report = store.report;
252
+ this.reindex();
253
+ }
254
+ reindex() {
255
+ this.index.clear();
256
+ this.cursorIndex.clear();
257
+ this.store.state.smartCi.records.forEach((r, i) => this.index.set(keyOf(r.kind, r.id), i));
258
+ this.store.state.smartCi.cursors.forEach((c, i) => this.cursorIndex.set(c.stream, i));
259
+ }
260
+ /**
261
+ * Take ownership of the store directory. A live owner is refused; a dead
262
+ * owner on this host is taken over. A store that has delivery workers
263
+ * enrolled is a delivery controller's store, not a Smart CI ledger: it is
264
+ * refused before anything is written to the directory.
265
+ */
266
+ static open(opts) {
267
+ if (storeExists(opts.dir)) {
268
+ // Read the state file as it is, without the store's lock database: opening that would create a file in the directory.
269
+ // The store replaces the file by rename, so a plain read sees a whole one.
270
+ const statePath = join(opts.dir, "state.json");
271
+ const workers = parseStoreText(readFileSync(statePath, "utf8"), statePath).state.workers.length;
272
+ if (workers > 0) {
273
+ throw new SmartCiLedgerError("STORE_HAS_WORKERS", `${opts.dir} is a delivery store with ${workers} enrolled worker${workers === 1 ? "" : "s"}. Smart CI does not write into a delivery controller's store; give it its own directory (--store-dir or HQ_SMART_CI_STORE_DIR). Nothing was written.`);
274
+ }
275
+ }
276
+ return new SmartCiLedger(DeliveryStore.open({
277
+ dir: opts.dir,
278
+ controllerId: opts.controllerId,
279
+ clock: opts.clock,
280
+ host: opts.host,
281
+ pid: opts.pid,
282
+ isPidAlive: opts.isPidAlive,
283
+ crashPoint: opts.crashPoint,
284
+ // Give a concurrent snapshot read time to finish.
285
+ gateWaitMs: 10_000,
286
+ }), opts);
287
+ }
288
+ get(kind, id) {
289
+ const i = this.index.get(keyOf(kind, id));
290
+ return i === undefined ? undefined : this.store.state.smartCi.records[i].body;
291
+ }
292
+ list(kind) {
293
+ return this.store.state.smartCi.records.filter((r) => r.kind === kind).map((r) => r.body);
294
+ }
295
+ records(kind) {
296
+ return this.store.state.smartCi.records.filter((r) => r.kind === kind).map((r) => asRecord(r));
297
+ }
298
+ /** The record of this kind written last, or undefined when there is none. */
299
+ latest(kind) {
300
+ return latestOf(this.records(kind));
301
+ }
302
+ /** Every record, of every kind. */
303
+ allRecords() {
304
+ return this.store.state.smartCi.records.map((r) => asRecord(r));
305
+ }
306
+ count(kind) {
307
+ const records = this.store.state.smartCi.records;
308
+ return kind === undefined ? records.length : records.filter((r) => r.kind === kind).length;
309
+ }
310
+ cursor(stream) {
311
+ const i = this.cursorIndex.get(stream);
312
+ return i === undefined ? null : this.store.state.smartCi.cursors[i].position;
313
+ }
314
+ /**
315
+ * Write records and move cursors in one atomic commit. An upsert whose body
316
+ * equals the stored one writes nothing; when nothing differs at all there is
317
+ * no commit. Either everything in the call is on disk afterwards or nothing is.
318
+ */
319
+ apply(upserts, cursors = []) {
320
+ const report = { created: 0, updated: 0, unchanged: 0, cursorsMoved: 0, committed: false };
321
+ // The last upsert for a key wins inside one call.
322
+ const pending = new Map();
323
+ for (const u of upserts) {
324
+ const body = canonical(u.body);
325
+ pending.set(keyOf(u.kind, u.id), { kind: u.kind, id: u.id, body, text: JSON.stringify(body) });
326
+ }
327
+ const records = this.store.state.smartCi.records;
328
+ const changes = [];
329
+ for (const [key, p] of pending) {
330
+ const at = this.index.get(key);
331
+ if (at !== undefined && JSON.stringify(records[at].body) === p.text) {
332
+ report.unchanged += 1;
333
+ continue;
334
+ }
335
+ changes.push({ key, at, kind: p.kind, id: p.id, body: p.body });
336
+ }
337
+ const cursorChanges = new Map();
338
+ for (const c of cursors) {
339
+ if (this.cursor(c.stream) !== c.position)
340
+ cursorChanges.set(c.stream, c.position);
341
+ else
342
+ cursorChanges.delete(c.stream);
343
+ }
344
+ if (changes.length === 0 && cursorChanges.size === 0)
345
+ return report;
346
+ const now = this.store.now();
347
+ const epoch = this.store.epoch;
348
+ const newIndex = [];
349
+ const newCursorIndex = [];
350
+ this.store.commit(epoch, (draft) => {
351
+ for (const c of changes) {
352
+ if (c.at === undefined) {
353
+ newIndex.push([c.key, draft.smartCi.records.length]);
354
+ draft.smartCi.records.push({ kind: c.kind, id: c.id, recordedAt: now, recordedEpoch: epoch, updatedAt: now, updatedEpoch: epoch, body: c.body });
355
+ }
356
+ else {
357
+ const old = draft.smartCi.records[c.at];
358
+ draft.smartCi.records[c.at] = { ...old, updatedAt: now, updatedEpoch: epoch, body: c.body };
359
+ }
360
+ }
361
+ for (const [stream, position] of cursorChanges) {
362
+ const at = this.cursorIndex.get(stream);
363
+ const entry = { stream, position, updatedAt: now, updatedEpoch: epoch };
364
+ if (at === undefined) {
365
+ newCursorIndex.push([stream, draft.smartCi.cursors.length]);
366
+ draft.smartCi.cursors.push(entry);
367
+ }
368
+ else
369
+ draft.smartCi.cursors[at] = entry;
370
+ }
371
+ });
372
+ // Only after the commit is on disk do the in-memory indexes learn the new positions.
373
+ for (const [k, i] of newIndex)
374
+ this.index.set(k, i);
375
+ for (const [s, i] of newCursorIndex)
376
+ this.cursorIndex.set(s, i);
377
+ report.created = changes.filter((c) => c.at === undefined).length;
378
+ report.updated = changes.length - report.created;
379
+ report.cursorsMoved = cursorChanges.size;
380
+ report.committed = true;
381
+ return report;
382
+ }
383
+ /** Remove records by key in one commit. Returns how many were there. */
384
+ remove(keys) {
385
+ const gone = new Set(keys.map((k) => keyOf(k.kind, k.id)).filter((k) => this.index.has(k)));
386
+ if (gone.size === 0)
387
+ return 0;
388
+ this.store.commit(this.store.epoch, (draft) => {
389
+ draft.smartCi.records = draft.smartCi.records.filter((r) => !gone.has(keyOf(r.kind, r.id)));
390
+ });
391
+ this.reindex();
392
+ return gone.size;
393
+ }
394
+ /**
395
+ * Remove old records of one kind in one commit: all but the `keepLatest`
396
+ * most recently written, or those last written before `olderThan`, or both
397
+ * (a record goes when either rule says so). Returns how many were removed.
398
+ */
399
+ prune(kind, opts) {
400
+ if (opts.keepLatest === undefined && opts.olderThan === undefined)
401
+ return 0;
402
+ const all = this.records(kind)
403
+ .map((r, i) => ({ r, i }))
404
+ .sort((a, b) => Date.parse(b.r.updatedAt) - Date.parse(a.r.updatedAt) || b.i - a.i);
405
+ const cutoff = opts.olderThan === undefined ? null : Date.parse(opts.olderThan);
406
+ const drop = all.filter((x, rank) => (opts.keepLatest !== undefined && rank >= Math.max(0, opts.keepLatest)) || (cutoff !== null && Date.parse(x.r.updatedAt) < cutoff));
407
+ return this.remove(drop.map((x) => ({ kind, id: x.r.id })));
408
+ }
409
+ /**
410
+ * Move old records out of the active file into archive store directories
411
+ * named for the UTC hour each record was last written. Each archive is
412
+ * written and closed before the records leave the active file, so a kill in
413
+ * between leaves a record in both places (readers count it once) and never
414
+ * in neither.
415
+ */
416
+ rotate(opts) {
417
+ const cutoff = Date.parse(opts.olderThan);
418
+ const kinds = new Set(opts.kinds);
419
+ const keep = opts.keep ?? (() => false);
420
+ const groups = new Map();
421
+ for (const r of this.store.state.smartCi.records) {
422
+ if (!kinds.has(r.kind) || Date.parse(r.updatedAt) >= cutoff || keep(asRecord(r)))
423
+ continue;
424
+ const name = archiveName(r.updatedAt);
425
+ const list = groups.get(name);
426
+ if (list)
427
+ list.push(r);
428
+ else
429
+ groups.set(name, [r]);
430
+ }
431
+ const report = { moved: 0, archives: [] };
432
+ if (groups.size === 0)
433
+ return report;
434
+ const moved = [];
435
+ for (const [name, list] of [...groups].sort((a, b) => a[0].localeCompare(b[0]))) {
436
+ const dir = join(this.dir, ARCHIVE_DIR, name);
437
+ mkdirSync(dir, { recursive: true });
438
+ const archive = SmartCiLedger.open({ ...this.openOptions, dir, controllerId: `${this.openOptions.controllerId}:archive` });
439
+ try {
440
+ archive.apply(list.map((r) => ({ kind: r.kind, id: r.id, body: r.body })));
441
+ }
442
+ finally {
443
+ archive.close();
444
+ }
445
+ report.archives.push(name);
446
+ for (const r of list)
447
+ moved.push({ kind: r.kind, id: r.id });
448
+ }
449
+ report.moved = this.remove(moved);
450
+ return report;
451
+ }
452
+ /** Records of one module for one company. Throws when the company or namespace is missing or malformed. */
453
+ scope(ref) {
454
+ return new ScopedLedger(this, scopePrefix(ref), ref.company);
455
+ }
456
+ /** The committed namespace as this owner sees it. */
457
+ view() {
458
+ return new SmartCiView(this.store.state.smartCi, this.dir);
459
+ }
460
+ /** Release ownership. Idempotent. */
461
+ close() {
462
+ this.store.close();
463
+ }
464
+ }
465
+ /** Writes and reads of one scope, through the owning ledger. */
466
+ export class ScopedLedger extends ScopedView {
467
+ ledger;
468
+ scopedPrefix;
469
+ scopedCompany;
470
+ constructor(ledger, scopedPrefix, scopedCompany) {
471
+ super(ledger, scopedPrefix, scopedCompany);
472
+ this.ledger = ledger;
473
+ this.scopedPrefix = scopedPrefix;
474
+ this.scopedCompany = scopedCompany;
475
+ }
476
+ /** Write one record (and its blob, when given) in one commit. */
477
+ put(kind, id, body, opts = {}) {
478
+ return this.putMany([{ kind, id, body, blob: opts.blob }]);
479
+ }
480
+ /** Write several records in one commit. Blob files are written first, so a committed record never names a missing blob. */
481
+ putMany(puts) {
482
+ const upserts = puts.map((p) => {
483
+ const kind = scopedKind(this.scopedPrefix, p.kind);
484
+ if (BLOB_FIELD in p.body)
485
+ throw new SmartCiLedgerError("SCOPE_INVALID", `the body field ${BLOB_FIELD} is set by the ledger; pass the bytes as blob`);
486
+ if (p.blob === undefined)
487
+ return { kind, id: p.id, body: p.body };
488
+ const bytes = typeof p.blob === "string" ? Buffer.from(p.blob, "utf8") : Buffer.from(p.blob);
489
+ const sha256 = createHash("sha256").update(bytes).digest("hex");
490
+ const path = blobPath(this.ledger.dir, this.scopedCompany, sha256);
491
+ if (!existsSync(path)) {
492
+ mkdirSync(join(this.ledger.dir, "blobs", this.scopedCompany), { recursive: true });
493
+ const temp = `${path}.tmp-${process.pid}`;
494
+ writeFileSync(temp, bytes);
495
+ renameSync(temp, path);
496
+ }
497
+ const ref = { sha256, bytes: bytes.length };
498
+ return { kind, id: p.id, body: { ...p.body, [BLOB_FIELD]: ref } };
499
+ });
500
+ return this.ledger.apply(upserts);
501
+ }
502
+ /** Remove old records of one kind (see SmartCiLedger.prune), then the blobs of this company no record names any more. */
503
+ prune(kind, opts) {
504
+ const removed = this.ledger.prune(scopedKind(this.scopedPrefix, kind), opts);
505
+ if (removed > 0)
506
+ this.sweepBlobs();
507
+ return removed;
508
+ }
509
+ sweepBlobs() {
510
+ const root = join(this.ledger.dir, "blobs", this.scopedCompany);
511
+ if (!existsSync(root))
512
+ return;
513
+ const named = new Set();
514
+ const companyPrefix = `co:${this.scopedCompany}:`;
515
+ for (const r of this.ledger.allRecords()) {
516
+ if (!r.kind.startsWith(companyPrefix))
517
+ continue;
518
+ const ref = r.body[BLOB_FIELD];
519
+ if (ref !== undefined)
520
+ named.add(ref.sha256);
521
+ }
522
+ for (const name of readdirSync(root))
523
+ if (/^[0-9a-f]{64}$/.test(name) && !named.has(name))
524
+ rmSync(join(root, name), { force: true });
525
+ }
526
+ }
527
+ //# sourceMappingURL=ledger.js.map
@@ -0,0 +1,137 @@
1
+ /**
2
+ * Smart CI metrics (smart-ci US-001): what the ledger says about waits, waste
3
+ * and cost for one repo over one window.
4
+ *
5
+ * Definitions, so the numbers can be checked by hand:
6
+ *
7
+ * - The window is [since, until). A job is in it by its queue time, a pull
8
+ * request by its merge time, a runner sample by its sample time.
9
+ * - A job "ran" when a runner picked it up (it has a runner name and a start
10
+ * time). Skipped jobs and jobs cancelled while still queued never ran and
11
+ * are left out of wait and run times.
12
+ * - Queue wait = start - queued. Run time = finish - start (finished jobs only).
13
+ * - Median and p90 use the nearest-rank method: the value at position
14
+ * ceil(p x n) of the sorted list. No interpolation.
15
+ * - A replaced-head job is one whose branch got a newer push at or after the
16
+ * job was queued and before it finished.
17
+ * - A cold start is a job that ran on the runner launched for it: the runner's
18
+ * name is ec2-<this job's id>-<n>, which is how hq-github-runners names a
19
+ * runner it launches for a queued job. Its queue wait is the cold-start
20
+ * time. A job that landed on a warm runner (ec2-warm-...), on a runner
21
+ * launched for another job, or on another pool did not wait for a launch.
22
+ * - Idle runner minutes come from runner pool samples: idle runners at a
23
+ * sample, times the gap to the next sample (capped at 5 minutes so a pause in
24
+ * sampling is not counted as idle time). A pool serves several repos, so the
25
+ * repo is given its share of each pool's idle minutes: its run minutes on
26
+ * the pool over the run minutes of every recorded repo on that pool in the
27
+ * window. The shares of the recorded repos add up to the pool's idle
28
+ * minutes, so summing across repos does not count a pool twice. Where
29
+ * samples are missing (gaps over 5 minutes) the figure covers only part of
30
+ * the window and is reported as an estimate with its coverage.
31
+ * - Merge to production = completion of the first successful deploy workflow
32
+ * run created at or after the merge on the base branch, minus the merge time.
33
+ * The run is matched by time, never by its head sha, which for hq-pro is not
34
+ * the commit it deploys. For hq-pro this is a lower bound: a green Deploy
35
+ * Prod run means the deploy was queued, and the deploy itself finishes
36
+ * minutes later in CodeBuild, which GitHub does not report and the ledger
37
+ * does not record.
38
+ */
39
+ import { type CostPerMerge, type CostRates, type PoolClass } from "./cost.js";
40
+ import type { SmartCiView } from "./ledger.js";
41
+ /** Repos whose merge to the base branch deploys to production, and the workflow that does it. */
42
+ export declare const DEPLOY_ON_MERGE: Readonly<Record<string, string>>;
43
+ export declare const COLD_START_RUNNER: RegExp;
44
+ /** Idle minutes are called measured only when samples cover at least this share of the sampled span. */
45
+ export declare const IDLE_MEASURED_COVERAGE = 0.95;
46
+ export interface MetricsOptions {
47
+ repo: string;
48
+ /** Inclusive, ISO date or time. */
49
+ since: string;
50
+ /** Exclusive, ISO. Default: no upper bound. */
51
+ until?: string;
52
+ /** Deploy workflow name; default from DEPLOY_ON_MERGE; null for a repo that does not deploy on merge. */
53
+ deployWorkflow?: string | null;
54
+ rates?: CostRates;
55
+ githubBilledUsd?: number;
56
+ awsFleetUsd?: number;
57
+ }
58
+ export interface Distribution {
59
+ count: number;
60
+ medianSeconds: number | null;
61
+ p90Seconds: number | null;
62
+ }
63
+ export interface Metrics {
64
+ repo: string;
65
+ since: string;
66
+ until: string | null;
67
+ jobs: {
68
+ recorded: number;
69
+ ran: number;
70
+ finished: number;
71
+ neverRan: number;
72
+ };
73
+ queueWait: Distribution;
74
+ runTime: Distribution;
75
+ replacedHead: {
76
+ /** Workflow runs with at least one replaced-head job. */
77
+ runs: number;
78
+ jobs: number;
79
+ /** Run time of the replaced-head jobs that finished. */
80
+ minutes: number;
81
+ /** The part of those minutes spent after the newer push arrived. */
82
+ minutesAfterReplacement: number;
83
+ onPullRequests: {
84
+ runs: number;
85
+ jobs: number;
86
+ minutes: number;
87
+ };
88
+ };
89
+ coldStart: {
90
+ jobs: number;
91
+ minutes: number;
92
+ };
93
+ idleRunners: {
94
+ /** This repo's share of the idle minutes of the pools it used. */
95
+ minutes: number;
96
+ samples: number;
97
+ /** This repo's share, by pool. */
98
+ byPool: Record<string, number>;
99
+ /** Idle minutes of each whole pool, all repos. */
100
+ poolMinutes: Record<string, number>;
101
+ /** This repo's share of each pool's run minutes among the recorded repos, 0 to 1. */
102
+ share: Record<string, number>;
103
+ /** Part of the time between the first and last sample that samples cover, 0 to 1. */
104
+ coverage: number;
105
+ } | null;
106
+ pullRequests: {
107
+ merged: number;
108
+ openToMerge: Distribution;
109
+ };
110
+ mergeToProduction: {
111
+ applicable: false;
112
+ } | {
113
+ applicable: true;
114
+ workflow: string;
115
+ deployed: number;
116
+ notYetDeployed: number;
117
+ distribution: Distribution;
118
+ };
119
+ cost: CostPerMerge;
120
+ poolMinutes: Array<{
121
+ pool: string;
122
+ poolClass: PoolClass;
123
+ jobs: number;
124
+ runMinutes: number;
125
+ billedMinutes: number;
126
+ }>;
127
+ }
128
+ /** Nearest-rank percentile of a list of numbers; null for an empty list. */
129
+ export declare function percentile(values: readonly number[], p: number): number | null;
130
+ /** A date (2026-11-21) means the start of that UTC day. Throws on anything that is not a time. */
131
+ export declare function parseWhen(value: string, name: string): number;
132
+ export declare function computeMetrics(view: SmartCiView, opts: MetricsOptions): Metrics;
133
+ /** 95 -> "1m 35s"; 4000 -> "1h 6m 40s". */
134
+ export declare function formatDuration(seconds: number | null): string;
135
+ /** The plain-text report `hq ci metrics` prints. */
136
+ export declare function renderMetrics(m: Metrics): string;
137
+ //# sourceMappingURL=metrics.d.ts.map