@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
@@ -84,6 +84,7 @@ export const REGISTRATION_PLAN = [
84
84
  { type: "registrar", root: "library", parent: "program", module: "./commands/library.js", exportName: "registerLibraryCommand" },
85
85
  { type: "registrar", root: "index", parent: "program", module: "./commands/index-cmd.js", exportName: "registerIndexCommand" },
86
86
  { type: "registrar", root: "capacity", parent: "program", module: "./commands/capacity.js", exportName: "registerCapacityCommand" },
87
+ { type: "registrar", root: "ci", parent: "program", module: "./commands/ci.js", exportName: "registerCiCommand" },
87
88
  { type: "registrar", root: "env", parent: "program", module: "./commands/env.js", exportName: "registerEnvCommand" },
88
89
  { type: "registrar", root: "work-env", parent: "program", module: "./commands/work-env.js", exportName: "registerWorkEnvCommand" },
89
90
  { type: "registrar", root: "doctor", parent: "program", module: "./commands/doctor.js", exportName: "registerDoctorCommand" },
@@ -0,0 +1,32 @@
1
+ import type { Command } from "commander";
2
+ export declare const DEFAULT_REPOS: readonly string[];
3
+ export declare const DEFAULT_RUNNER_ORG = "indigoai-us";
4
+ export type TokenCommand = (file: string, args: string[], env: NodeJS.ProcessEnv) => Promise<string>;
5
+ /**
6
+ * The GitHub token of this machine's signed-in `gh` login, and nothing else.
7
+ * A token in GH_TOKEN or GITHUB_TOKEN is never used: under an Actions or App
8
+ * installation token the intake would spend the allowance CI itself runs on.
9
+ * Those variables are also taken out of the environment `gh` is asked in, so
10
+ * `gh auth token` cannot hand one back. With no signed-in login the intake
11
+ * refuses to start. The token is held in memory and never printed or logged.
12
+ */
13
+ export declare function resolveGitHubToken(env?: NodeJS.ProcessEnv, run?: TokenCommand): Promise<string>;
14
+ /** How long a starting intake waits for a brief holder of the ledger to let go. */
15
+ export declare const LEDGER_OPEN_WAIT_MS = 5000;
16
+ export interface PatientOpenOptions {
17
+ waitMs?: number;
18
+ stepMs?: number;
19
+ now?: () => number;
20
+ wait?: (ms: number) => Promise<void>;
21
+ }
22
+ /**
23
+ * Open the ledger, retrying while another live process on this host owns it.
24
+ * A standalone `hq ci priorities` write, or its writability probe, holds the
25
+ * ledger for milliseconds to a few seconds; an intake starting in that window
26
+ * waits for it rather than exiting. After `waitMs` the owner's refusal is
27
+ * thrown as it is. Any other refusal (an owner on another host, an unreadable
28
+ * lock, a delivery store) is thrown at once.
29
+ */
30
+ export declare function openLedgerPatiently<T>(open: () => T, opts?: PatientOpenOptions): Promise<T>;
31
+ export declare function registerCiIntakeCommand(ci: Command): void;
32
+ //# sourceMappingURL=ci-intake.d.ts.map
@@ -0,0 +1,294 @@
1
+ /**
2
+ * `hq ci intake` — record what CI does into the HQ Native run ledger.
3
+ *
4
+ * Read-only towards GitHub: it sends GET requests only and registers no
5
+ * webhook. Three modes: poll GitHub (the default), replay a recorded fixture
6
+ * (--replay-fixture), or record a past window as a fixture (--record-fixture).
7
+ */
8
+ import { execFile } from "node:child_process";
9
+ import { writeFileSync } from "node:fs";
10
+ import { hostname } from "node:os";
11
+ import { join } from "node:path";
12
+ import { gzipSync } from "node:zlib";
13
+ import { DeliveryStoreError } from "../lib/delivery/store.js";
14
+ import { GitHubReadClient, GitHubReadError } from "../lib/smart-ci/github.js";
15
+ import { DEFAULT_HOURLY_BUDGET, DEFAULT_RATE_FLOOR, IntakeInputError, Poller, findSensitive, readFixture, recordWindow, replayFixture, scrubObservation, serializeFixture } from "../lib/smart-ci/intake.js";
16
+ import { SmartCiLedger, SmartCiLedgerError, defaultLedgerDir } from "../lib/smart-ci/ledger.js";
17
+ import { PriorityRefreshHost } from "../lib/smart-ci/priority-refresh.js";
18
+ import { assertCompanySlug } from "../lib/smart-ci/sources.js";
19
+ import { resolveLanesHqRoot } from "../lib/lanes/hq-root.js";
20
+ export const DEFAULT_REPOS = ["indigoai-us/hq-cli", "indigoai-us/hq-pro"];
21
+ export const DEFAULT_RUNNER_ORG = "indigoai-us";
22
+ class UsageError extends Error {
23
+ }
24
+ function positive(value, name, fallback) {
25
+ if (value === undefined)
26
+ return fallback;
27
+ const n = Number(value);
28
+ if (!Number.isFinite(n) || n <= 0)
29
+ throw new UsageError(`${name} must be a number above zero, got ${JSON.stringify(value)}`);
30
+ return n;
31
+ }
32
+ function nonNegative(value, name, fallback) {
33
+ if (value === undefined)
34
+ return fallback;
35
+ const n = Number(value);
36
+ if (!Number.isFinite(n) || n < 0)
37
+ throw new UsageError(`${name} must be zero or more, got ${JSON.stringify(value)}`);
38
+ return n;
39
+ }
40
+ /** Environment variables `gh` would take a token from in place of the signed-in login. */
41
+ const TOKEN_ENV = ["GH_TOKEN", "GITHUB_TOKEN", "GH_ENTERPRISE_TOKEN", "GITHUB_ENTERPRISE_TOKEN"];
42
+ const runGh = (file, args, env) => new Promise((resolve) => {
43
+ execFile(file, args, { timeout: 10_000, env }, (err, stdout) => resolve(err ? "" : stdout.trim()));
44
+ });
45
+ /**
46
+ * The GitHub token of this machine's signed-in `gh` login, and nothing else.
47
+ * A token in GH_TOKEN or GITHUB_TOKEN is never used: under an Actions or App
48
+ * installation token the intake would spend the allowance CI itself runs on.
49
+ * Those variables are also taken out of the environment `gh` is asked in, so
50
+ * `gh auth token` cannot hand one back. With no signed-in login the intake
51
+ * refuses to start. The token is held in memory and never printed or logged.
52
+ */
53
+ export async function resolveGitHubToken(env = process.env, run = runGh) {
54
+ const clean = { ...env };
55
+ for (const name of TOKEN_ENV)
56
+ delete clean[name];
57
+ const token = await run("gh", ["auth", "token", "--hostname", "github.com"], clean);
58
+ if (token === "") {
59
+ throw new UsageError("No signed-in gh login. The intake reads GitHub as this machine's gh login only (GH_TOKEN and GITHUB_TOKEN are not used). Sign in with `gh auth login` and start it again.");
60
+ }
61
+ return token;
62
+ }
63
+ function sleep(ms, signal) {
64
+ return new Promise((resolve) => {
65
+ if (signal.aborted)
66
+ return resolve();
67
+ const timer = setTimeout(done, ms);
68
+ function done() {
69
+ clearTimeout(timer);
70
+ signal.removeEventListener("abort", done);
71
+ resolve();
72
+ }
73
+ signal.addEventListener("abort", done);
74
+ });
75
+ }
76
+ /** How long a starting intake waits for a brief holder of the ledger to let go. */
77
+ export const LEDGER_OPEN_WAIT_MS = 5_000;
78
+ const LEDGER_OPEN_STEP_MS = 100;
79
+ /**
80
+ * Open the ledger, retrying while another live process on this host owns it.
81
+ * A standalone `hq ci priorities` write, or its writability probe, holds the
82
+ * ledger for milliseconds to a few seconds; an intake starting in that window
83
+ * waits for it rather than exiting. After `waitMs` the owner's refusal is
84
+ * thrown as it is. Any other refusal (an owner on another host, an unreadable
85
+ * lock, a delivery store) is thrown at once.
86
+ */
87
+ export async function openLedgerPatiently(open, opts = {}) {
88
+ const now = opts.now ?? Date.now;
89
+ const wait = opts.wait ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
90
+ const stepMs = opts.stepMs ?? LEDGER_OPEN_STEP_MS;
91
+ const deadline = now() + (opts.waitMs ?? LEDGER_OPEN_WAIT_MS);
92
+ for (;;) {
93
+ try {
94
+ return open();
95
+ }
96
+ catch (err) {
97
+ const left = deadline - now();
98
+ if (!(err instanceof DeliveryStoreError && err.code === "CONTROLLER_OWNED") || left <= 0)
99
+ throw err;
100
+ await wait(Math.min(stepMs, left));
101
+ }
102
+ }
103
+ }
104
+ async function runIntake(opts) {
105
+ const out = (line) => process.stdout.write(`${line}\n`);
106
+ const storeDir = opts.storeDir ?? defaultLedgerDir();
107
+ if (opts.recordFixture !== undefined) {
108
+ const repos = opts.repo ?? [];
109
+ if (repos.length !== 1 || !opts.from || !opts.to)
110
+ throw new UsageError("--record-fixture needs exactly one --repo, --from and --to");
111
+ const client = new GitHubReadClient({ token: await resolveGitHubToken(), auditPath: opts.auditLog });
112
+ const observations = (await recordWindow(client, { repo: repos[0], from: opts.from, to: opts.to, checkRuns: opts.checkRuns, log: (l) => process.stderr.write(`${l}\n`) })).map(scrubObservation);
113
+ const text = serializeFixture({ repo: repos[0], from: opts.from, to: opts.to, recordedAt: new Date().toISOString() }, observations);
114
+ const sensitive = findSensitive(text);
115
+ if (sensitive.length > 0) {
116
+ throw new IntakeInputError(`refusing to write the fixture: line ${sensitive[0].line} still holds ${sensitive[0].what} after scrubbing (${sensitive.length} lines in all)`);
117
+ }
118
+ writeFileSync(opts.recordFixture, opts.recordFixture.endsWith(".gz") ? gzipSync(text) : text);
119
+ const counts = client.counts();
120
+ const summary = { fixture: opts.recordFixture, observations: observations.length, requests: counts.total };
121
+ out(opts.json ? JSON.stringify(summary) : `Recorded ${observations.length} observations to ${opts.recordFixture} with ${counts.total} GitHub read requests.`);
122
+ return;
123
+ }
124
+ const ledger = await openLedgerPatiently(() => SmartCiLedger.open({ dir: storeDir, controllerId: `smart-ci-intake@${hostname()}` }));
125
+ try {
126
+ if (opts.replayFixture !== undefined) {
127
+ const fixture = readFixture(opts.replayFixture);
128
+ const report = replayFixture(ledger, fixture, {
129
+ batchSize: positive(opts.batchSize, "--batch-size", 200),
130
+ onBatch: (done, total) => process.stderr.write(`replayed ${done}/${total}\n`),
131
+ });
132
+ out(opts.json
133
+ ? JSON.stringify(report)
134
+ : `Replayed fixture ${report.fixtureId}: ${report.applied} of ${report.total} observations applied (${report.resumedFrom} already recorded), ${report.created} records created, ${report.updated} updated, ${report.unchanged} unchanged.`);
135
+ return;
136
+ }
137
+ const repos = opts.repo && opts.repo.length > 0 ? opts.repo : [...DEFAULT_REPOS];
138
+ const intervalMs = positive(opts.intervalSeconds, "--interval-seconds", 60) * 1000;
139
+ if (intervalMs < 10_000)
140
+ throw new UsageError("--interval-seconds must be 10 or more, to stay inside the GitHub request budget");
141
+ const durationMs = opts.durationMinutes === undefined ? null : positive(opts.durationMinutes, "--duration-minutes", 60) * 60_000;
142
+ const lookbackMs = nonNegative(opts.lookbackMinutes, "--lookback-minutes", 0) * 60_000;
143
+ const auditPath = opts.auditLog ?? join(storeDir, "smart-ci-github-audit.jsonl");
144
+ const client = new GitHubReadClient({ token: await resolveGitHubToken(), auditPath });
145
+ const startedMs = Date.now();
146
+ const poller = new Poller(ledger, client, {
147
+ repos,
148
+ runnerOrg: opts.runners === false ? null : (opts.runnerOrg ?? DEFAULT_RUNNER_ORG),
149
+ startAt: new Date(startedMs - lookbackMs).toISOString(),
150
+ hourlyBudget: positive(opts.hourlyBudget, "--hourly-budget", DEFAULT_HOURLY_BUDGET),
151
+ rateFloor: nonNegative(opts.rateFloor, "--rate-floor", DEFAULT_RATE_FLOOR),
152
+ activeWindowMs: nonNegative(opts.activeWindowMinutes, "--active-window-minutes", 120) * 60_000,
153
+ checkRuns: opts.checkRuns,
154
+ log: (l) => process.stderr.write(`${l}\n`),
155
+ });
156
+ // The ledger has one owner. With --priorities, the priority map is refreshed here, beside the poll, and
157
+ // stored through this process's ledger; `hq ci priorities` only reads it while the intake runs.
158
+ let priorities = null;
159
+ if (opts.priorities !== undefined) {
160
+ assertCompanySlug(opts.priorities);
161
+ priorities = new PriorityRefreshHost(ledger, { company: opts.priorities, hqRoot: resolveLanesHqRoot(), repos, log: (l) => process.stderr.write(`${l}\n`) });
162
+ }
163
+ const stop = new AbortController();
164
+ const onSignal = () => stop.abort();
165
+ process.once("SIGINT", onSignal);
166
+ process.once("SIGTERM", onSignal);
167
+ let cycles = 0;
168
+ let recorded = 0;
169
+ let gaps = 0;
170
+ let archived = 0;
171
+ let sweepStartedAt = null;
172
+ const tally = (report, sweep) => {
173
+ cycles += 1;
174
+ recorded += report.created;
175
+ gaps += report.gaps;
176
+ archived += report.archived;
177
+ const line = {
178
+ at: report.startedAt,
179
+ sweep,
180
+ observations: report.observations,
181
+ created: report.created,
182
+ updated: report.updated,
183
+ runsFinalized: report.runsFinalized,
184
+ openRuns: report.openRuns,
185
+ requestsLastHour: report.requests.lastHour,
186
+ chargedLastHour: report.chargedLastHour,
187
+ rateRemaining: report.requests.rateRemaining,
188
+ gaps: report.gaps,
189
+ archived: report.archived,
190
+ skipped: report.skipped.length,
191
+ };
192
+ process.stderr.write(`${JSON.stringify(line)}\n`);
193
+ };
194
+ try {
195
+ for (;;) {
196
+ const cycleStart = Date.now();
197
+ priorities?.tick();
198
+ tally(await poller.cycle(), false);
199
+ if (opts.once || stop.signal.aborted)
200
+ break;
201
+ if (durationMs !== null && Date.now() - startedMs >= durationMs)
202
+ break;
203
+ const wait = Math.max(1000, intervalMs - (Date.now() - cycleStart));
204
+ await sleep(durationMs === null ? wait : Math.min(wait, Math.max(0, startedMs + durationMs - Date.now())), stop.signal);
205
+ if (stop.signal.aborted)
206
+ break;
207
+ if (durationMs !== null && Date.now() - startedMs >= durationMs)
208
+ break;
209
+ }
210
+ if (!opts.once) {
211
+ // Before stopping, read every open run once more, so the ledger holds each job GitHub lists up to this moment.
212
+ sweepStartedAt = new Date().toISOString();
213
+ tally(await poller.finish(), true);
214
+ }
215
+ }
216
+ finally {
217
+ process.removeListener("SIGINT", onSignal);
218
+ process.removeListener("SIGTERM", onSignal);
219
+ // A running refresh writes through this ledger: let it finish before the ledger closes.
220
+ await priorities?.drain();
221
+ }
222
+ const counts = client.counts();
223
+ const summary = {
224
+ repos,
225
+ startedAt: new Date(startedMs).toISOString(),
226
+ endedAt: new Date().toISOString(),
227
+ sweepStartedAt,
228
+ cycles,
229
+ recordsCreated: recorded,
230
+ recordsArchived: archived,
231
+ gaps,
232
+ requests: counts.total,
233
+ notModified: counts.notModified,
234
+ charged: counts.total - counts.notModified,
235
+ chargedLastHour: poller.chargedLastHour(),
236
+ auditLog: auditPath,
237
+ storeDir,
238
+ };
239
+ out(opts.json
240
+ ? JSON.stringify(summary)
241
+ : `Intake ran ${cycles} cycles over ${repos.join(", ")}: ${recorded} records created, ${counts.total} GitHub read requests (${counts.notModified} answered "not modified" and are not charged), ${gaps} gaps recorded. Audit log: ${auditPath}`);
242
+ }
243
+ finally {
244
+ ledger.close();
245
+ }
246
+ }
247
+ export function registerCiIntakeCommand(ci) {
248
+ ci.command("intake")
249
+ .description("Record CI jobs, checks, pull requests, pushes and runner pool state into the run ledger (read-only towards GitHub)")
250
+ .option("--repo <owner/name>", "repository to record; repeat for more (default: indigoai-us/hq-cli and indigoai-us/hq-pro)", (v, prev = []) => [...prev, v])
251
+ .option("--runner-org <org>", `org whose runner pools are sampled (default: ${DEFAULT_RUNNER_ORG})`)
252
+ .option("--no-runners", "do not sample runner pools")
253
+ .option("--no-check-runs", "do not read check runs")
254
+ .option("--store-dir <path>", "ledger directory (default: HQ_SMART_CI_STORE_DIR, else ~/.hq/delivery/ledger)")
255
+ .option("--priorities <company>", "also refresh and store this company's priority map (hq ci priorities) while the intake owns the ledger")
256
+ .option("--once", "run one cycle and stop")
257
+ .option("--duration-minutes <n>", "stop after this many minutes (default: run until stopped)")
258
+ .option("--interval-seconds <n>", "seconds between cycles (default: 60)")
259
+ .option("--lookback-minutes <n>", "on a first start, also record runs created this many minutes back (default: 0)")
260
+ .option("--hourly-budget <n>", `charged GitHub requests an hour the intake allows itself, counted across restarts (default: ${DEFAULT_HOURLY_BUDGET})`)
261
+ .option("--rate-floor <n>", `make no request while the gh login has this many or fewer requests left this hour (default: ${DEFAULT_RATE_FLOOR})`)
262
+ .option("--active-window-minutes <n>", "closed records older than this move to dated archive files; 0 keeps one file (default: 120)")
263
+ .option("--audit-log <path>", "where to write one line per GitHub request (default: smart-ci-github-audit.jsonl in the ledger directory)")
264
+ .option("--replay-fixture <path>", "record a fixture file instead of polling GitHub")
265
+ .option("--batch-size <n>", "observations per commit when replaying (default: 200)")
266
+ .option("--record-fixture <path>", "read a past window from GitHub and write it as a fixture; needs one --repo, --from and --to")
267
+ .option("--from <iso>", "start of the window to record (inclusive)")
268
+ .option("--to <iso>", "end of the window to record (exclusive)")
269
+ .option("--json", "print the final summary as JSON")
270
+ .action(async (opts) => {
271
+ try {
272
+ await runIntake(opts);
273
+ }
274
+ catch (err) {
275
+ if (err instanceof UsageError || err instanceof IntakeInputError || err instanceof GitHubReadError) {
276
+ process.stderr.write(`hq ci intake: ${err.message}\n`);
277
+ process.exitCode = err instanceof UsageError ? 2 : 1;
278
+ return;
279
+ }
280
+ if (err instanceof SmartCiLedgerError) {
281
+ process.stderr.write(`hq ci intake: ${err.message}\n`);
282
+ process.exitCode = 1;
283
+ return;
284
+ }
285
+ if (err instanceof DeliveryStoreError) {
286
+ process.stderr.write(`hq ci intake: the ledger could not be used (${err.code}). Found: ${err.found}. ${err.action}\n`);
287
+ process.exitCode = 1;
288
+ return;
289
+ }
290
+ throw err;
291
+ }
292
+ });
293
+ }
294
+ //# sourceMappingURL=ci-intake.js.map
@@ -0,0 +1,8 @@
1
+ /**
2
+ * `hq ci metrics` — queue waits, run times, replaced-head runs, runner idle and
3
+ * cold-start minutes, PR lead times and cost per merge for one repo, read from
4
+ * the run ledger. Reads only; works while the intake is running.
5
+ */
6
+ import type { Command } from "commander";
7
+ export declare function registerCiMetricsCommand(ci: Command): void;
8
+ //# sourceMappingURL=ci-metrics.d.ts.map
@@ -0,0 +1,55 @@
1
+ import { DeliveryStoreError } from "../lib/delivery/store.js";
2
+ import { SmartCiView, defaultLedgerDir, readSmartCiHistory } from "../lib/smart-ci/ledger.js";
3
+ import { computeMetrics, parseWhen, renderMetrics } from "../lib/smart-ci/metrics.js";
4
+ import { KIND } from "../lib/smart-ci/records.js";
5
+ function amount(value, name) {
6
+ if (value === undefined)
7
+ return undefined;
8
+ const n = Number(value);
9
+ if (!Number.isFinite(n) || n < 0)
10
+ throw new Error(`${name} must be an amount in US dollars, zero or more, got ${JSON.stringify(value)}`);
11
+ return n;
12
+ }
13
+ export function registerCiMetricsCommand(ci) {
14
+ ci.command("metrics")
15
+ .description("Print CI waits, waste and cost per merge for a repo from the run ledger")
16
+ .requiredOption("--repo <owner/name>", "repository to report on")
17
+ .requiredOption("--since <date>", "start of the window, a date (2026-11-21) or an ISO time, UTC")
18
+ .option("--until <date>", "end of the window, exclusive (default: now)")
19
+ .option("--store-dir <path>", "ledger directory (default: HQ_SMART_CI_STORE_DIR, else ~/.hq/delivery/ledger)")
20
+ .option("--deploy-workflow <name>", "workflow that deploys to production on merge (default: known per repo)")
21
+ .option("--github-billed-usd <amount>", "billed GitHub amount for this repo and window, to use in place of the estimate")
22
+ .option("--aws-fleet-usd <amount>", "AWS runner fleet amount for this window, to use in place of the estimate")
23
+ .option("--json", "print the numbers as JSON")
24
+ .action((opts) => {
25
+ try {
26
+ if (!/^[\w.-]+\/[\w.-]+$/.test(opts.repo))
27
+ throw new Error(`--repo must be owner/name, got ${JSON.stringify(opts.repo)}`);
28
+ const sinceMs = parseWhen(opts.since, "--since");
29
+ if (opts.until !== undefined)
30
+ parseWhen(opts.until, "--until");
31
+ // The active file plus the archives last written since the window began. Only the kinds the metrics use are kept in memory.
32
+ const used = new Set([KIND.job, KIND.run, KIND.pullRequest, KIND.runnerSample]);
33
+ const view = new SmartCiView(readSmartCiHistory(opts.storeDir ?? defaultLedgerDir(), { since: new Date(sinceMs).toISOString(), keep: (r) => used.has(r.kind) }));
34
+ const metrics = computeMetrics(view, {
35
+ repo: opts.repo,
36
+ since: opts.since,
37
+ until: opts.until,
38
+ deployWorkflow: opts.deployWorkflow,
39
+ githubBilledUsd: amount(opts.githubBilledUsd, "--github-billed-usd"),
40
+ awsFleetUsd: amount(opts.awsFleetUsd, "--aws-fleet-usd"),
41
+ });
42
+ process.stdout.write(opts.json ? `${JSON.stringify(metrics, null, 2)}\n` : renderMetrics(metrics));
43
+ }
44
+ catch (err) {
45
+ if (err instanceof DeliveryStoreError) {
46
+ process.stderr.write(`hq ci metrics: the ledger could not be read (${err.code}). Found: ${err.found}. ${err.action}\n`);
47
+ process.exitCode = 1;
48
+ return;
49
+ }
50
+ process.stderr.write(`hq ci metrics: ${err instanceof Error ? err.message : String(err)}\n`);
51
+ process.exitCode = 2;
52
+ }
53
+ });
54
+ }
55
+ //# sourceMappingURL=ci-metrics.js.map
@@ -0,0 +1,56 @@
1
+ /**
2
+ * `hq ci priorities` (smart-ci US-002): print the company's priority map in
3
+ * plain language, with the source of every line.
4
+ *
5
+ * The command reads; it writes only the "priorities" scope of the Smart CI
6
+ * ledger (the one `hq ci intake` writes, default ~/.hq/delivery/ledger). It
7
+ * changes nothing on GitHub, Work Mesh, the ontology or the vault. The company
8
+ * is always given by the caller: there is no default company.
9
+ *
10
+ * By default the map is refreshed first when a refresh is due (the schedule
11
+ * interval has passed, or a new standup transcript has arrived). When a
12
+ * source is down the previous map is printed and the failure is reported on
13
+ * stderr and recorded in the ledger.
14
+ *
15
+ * The ledger has one owner process at a time. While another process owns it
16
+ * (a running `hq ci intake`), this command prints the stored map without
17
+ * refreshing, since it could not store the result; that process refreshes the
18
+ * map when started with `--priorities <company>`. With `--refresh` the map is
19
+ * built and printed anyway, and stderr says it was not stored.
20
+ */
21
+ import { type Command } from "commander";
22
+ import { type PriorityMap } from "../lib/smart-ci/priorities.js";
23
+ import { type RefreshOptions, type RefreshResult } from "../lib/smart-ci/priority-refresh.js";
24
+ export interface CiPrioritiesOptions {
25
+ company: string;
26
+ /** Repos whose open pull requests are matched, as owner/name. */
27
+ repo?: string[];
28
+ /** true: always refresh. false: never refresh. undefined: refresh when due. */
29
+ refresh?: boolean;
30
+ json?: boolean;
31
+ hqRoot?: string;
32
+ /** Smart CI ledger directory. Default: HQ_SMART_CI_STORE_DIR, else ~/.hq/delivery/ledger. */
33
+ storeDir?: string;
34
+ days?: number;
35
+ /** Explicit window, ISO timestamps. */
36
+ from?: string;
37
+ to?: string;
38
+ top?: number;
39
+ }
40
+ export interface CiPrioritiesDeps {
41
+ out?: (text: string) => void;
42
+ err?: (text: string) => void;
43
+ clock?: () => number;
44
+ /** Extra refresh options (readers, runner) for tests. */
45
+ refreshOptions?: Partial<RefreshOptions>;
46
+ }
47
+ export interface CiPrioritiesResult {
48
+ exitCode: number;
49
+ map: PriorityMap | null;
50
+ refresh: RefreshResult | null;
51
+ }
52
+ /** Run `hq ci priorities`. Directly testable: every effect goes through `opts` and `deps`. */
53
+ export declare function runCiPriorities(opts: CiPrioritiesOptions, deps?: CiPrioritiesDeps): Promise<CiPrioritiesResult>;
54
+ /** Add `priorities` under the `hq ci` parent command. */
55
+ export declare function registerCiPriorities(ci: Command): Command;
56
+ //# sourceMappingURL=ci-priorities.d.ts.map
@@ -0,0 +1,144 @@
1
+ /**
2
+ * `hq ci priorities` (smart-ci US-002): print the company's priority map in
3
+ * plain language, with the source of every line.
4
+ *
5
+ * The command reads; it writes only the "priorities" scope of the Smart CI
6
+ * ledger (the one `hq ci intake` writes, default ~/.hq/delivery/ledger). It
7
+ * changes nothing on GitHub, Work Mesh, the ontology or the vault. The company
8
+ * is always given by the caller: there is no default company.
9
+ *
10
+ * By default the map is refreshed first when a refresh is due (the schedule
11
+ * interval has passed, or a new standup transcript has arrived). When a
12
+ * source is down the previous map is printed and the failure is reported on
13
+ * stderr and recorded in the ledger.
14
+ *
15
+ * The ledger has one owner process at a time. While another process owns it
16
+ * (a running `hq ci intake`), this command prints the stored map without
17
+ * refreshing, since it could not store the result; that process refreshes the
18
+ * map when started with `--priorities <company>`. With `--refresh` the map is
19
+ * built and printed anyway, and stderr says it was not stored.
20
+ */
21
+ import { InvalidArgumentError } from "commander";
22
+ import { resolveLanesHqRoot } from "../lib/lanes/hq-root.js";
23
+ import { renderPriorityMap } from "../lib/smart-ci/priorities.js";
24
+ import { defaultLedgerDir } from "../lib/smart-ci/ledger.js";
25
+ import { ledgerWritable } from "../lib/smart-ci/priority-snapshots.js";
26
+ import { currentPriorityMap, refreshDue, refreshPriorityMap } from "../lib/smart-ci/priority-refresh.js";
27
+ import { assertCompanySlug } from "../lib/smart-ci/sources.js";
28
+ function validWindow(from, to) {
29
+ if (from === undefined && to === undefined)
30
+ return undefined;
31
+ const fromMs = Date.parse(from ?? "");
32
+ const toMs = Date.parse(to ?? "");
33
+ if (Number.isNaN(fromMs) || Number.isNaN(toMs) || fromMs >= toMs)
34
+ throw new Error("--from and --to must both be ISO timestamps, with --from before --to");
35
+ return { from: new Date(fromMs).toISOString(), to: new Date(toMs).toISOString() };
36
+ }
37
+ function wholeNumber(name, min) {
38
+ return (value) => {
39
+ if (!/^\d+$/.test(value.trim()) || Number(value) < min)
40
+ throw new InvalidArgumentError(`${name} must be a whole number of at least ${min}.`);
41
+ return Number(value);
42
+ };
43
+ }
44
+ function checkCount(name, value, min) {
45
+ if (value !== undefined && (!Number.isInteger(value) || value < min))
46
+ throw new Error(`${name} must be a whole number of at least ${min}; got ${String(value)}`);
47
+ }
48
+ /** Run `hq ci priorities`. Directly testable: every effect goes through `opts` and `deps`. */
49
+ export async function runCiPriorities(opts, deps = {}) {
50
+ const out = deps.out ?? ((text) => process.stdout.write(text));
51
+ const err = deps.err ?? ((text) => process.stderr.write(text));
52
+ assertCompanySlug(opts.company);
53
+ checkCount("--days", opts.days, 1);
54
+ checkCount("--top", opts.top, 1);
55
+ const window = validWindow(opts.from, opts.to);
56
+ const hqRoot = opts.hqRoot ?? resolveLanesHqRoot();
57
+ const ledgerDir = opts.storeDir ?? defaultLedgerDir();
58
+ const build = opts.top === undefined ? undefined : { topCount: opts.top };
59
+ let refresh = null;
60
+ let wanted = opts.refresh === true;
61
+ if (opts.refresh === undefined) {
62
+ const due = refreshDue({ company: opts.company, hqRoot, ledgerDir, clock: deps.clock });
63
+ wanted = due.due;
64
+ if (wanted) {
65
+ // A refresh this process could not store would read every source again on each run: leave it to the owner.
66
+ const writable = ledgerWritable({ target: { dir: ledgerDir }, company: opts.company, clock: deps.clock });
67
+ if (!writable.writable) {
68
+ wanted = false;
69
+ err(`A refresh is due (${due.reason}) but was not run, because it could not be stored: ${writable.reason}\n`);
70
+ }
71
+ }
72
+ }
73
+ if (wanted) {
74
+ // With no --repo, the repos of the stored map are read again, so a refresh does not drop its pull requests.
75
+ let repos = opts.repo ?? [];
76
+ if (repos.length === 0) {
77
+ try {
78
+ repos = [...new Set((currentPriorityMap({ ledgerDir, company: opts.company })?.map.pullRequests ?? []).map((pr) => pr.repo))].sort();
79
+ }
80
+ catch {
81
+ repos = [];
82
+ }
83
+ }
84
+ refresh = await refreshPriorityMap({
85
+ company: opts.company,
86
+ hqRoot,
87
+ ledgerDir,
88
+ repos,
89
+ clock: deps.clock,
90
+ windowDays: opts.days,
91
+ window,
92
+ build,
93
+ log: (line) => err(`${line}\n`),
94
+ ...deps.refreshOptions,
95
+ });
96
+ }
97
+ const map = refresh ? refresh.map : (currentPriorityMap({ ledgerDir, company: opts.company })?.map ?? null);
98
+ if (!map) {
99
+ err(`No priority map is stored for ${opts.company} yet. Run: hq ci priorities --company ${opts.company} --refresh\n`);
100
+ return { exitCode: 1, map: null, refresh };
101
+ }
102
+ if (opts.json) {
103
+ out(`${JSON.stringify(map, null, 2)}\n`);
104
+ }
105
+ else {
106
+ out(renderPriorityMap(map));
107
+ if (refresh?.kept) {
108
+ out(`\nThis is the map built ${map.builtAt}. A refresh just now kept it because these sources were down: ${refresh.failures.map((f) => `${f.source} (${f.message})`).join("; ")}.\n`);
109
+ }
110
+ }
111
+ return { exitCode: 0, map, refresh };
112
+ }
113
+ function collect(value, previous) {
114
+ return [...previous, value];
115
+ }
116
+ /** Add `priorities` under the `hq ci` parent command. */
117
+ export function registerCiPriorities(ci) {
118
+ return ci
119
+ .command("priorities")
120
+ .description("Print the company's priority map: what matters most, which open pull requests it covers, and work in flight with no pull request yet")
121
+ .requiredOption("--company <slug>", "company whose work to read (required; there is no default)")
122
+ .option("--repo <owner/name>", "repo whose open pull requests are matched; repeat for more (default: the repos of the stored map)", collect, [])
123
+ .option("--refresh", "refresh the map from its sources before printing")
124
+ .option("--no-refresh", "print the stored map without reading any source")
125
+ .option("--days <n>", "days of standups and activity to read (default 7)", wholeNumber("--days", 1))
126
+ .option("--from <iso>", "start of an explicit window (with --to)")
127
+ .option("--to <iso>", "end of an explicit window (with --from)")
128
+ .option("--top <n>", "how many priorities count as top (default 5)", wholeNumber("--top", 1))
129
+ .option("--hq-root <path>", "HQ installation to read")
130
+ .option("--store-dir <path>", "ledger directory (default: HQ_SMART_CI_STORE_DIR, else ~/.hq/delivery/ledger)")
131
+ .option("--json", "print the map as JSON")
132
+ .action(async (options) => {
133
+ try {
134
+ const result = await runCiPriorities(options);
135
+ if (result.exitCode !== 0)
136
+ process.exitCode = result.exitCode;
137
+ }
138
+ catch (error) {
139
+ process.stderr.write(`hq ci priorities: ${error instanceof Error ? error.message : String(error)}\n`);
140
+ process.exitCode = 2;
141
+ }
142
+ });
143
+ }
144
+ //# sourceMappingURL=ci-priorities.js.map
@@ -0,0 +1,13 @@
1
+ /**
2
+ * `hq ci` — Smart CI (smart-ci project).
3
+ *
4
+ * The parent command only. Each subcommand lives in its own file and exports a
5
+ * `registerCi...(ci)` function; a new subcommand adds one import and one line
6
+ * to CI_SUBCOMMANDS and touches nothing else here.
7
+ *
8
+ * Smart CI is watch-only: nothing under `hq ci` changes GitHub, a workflow, a
9
+ * branch rule, the batch train or the runner fleet.
10
+ */
11
+ import type { Command } from "commander";
12
+ export declare function registerCiCommand(program: Command): void;
13
+ //# sourceMappingURL=ci.d.ts.map
@@ -0,0 +1,11 @@
1
+ import { registerCiIntakeCommand } from "./ci-intake.js";
2
+ import { registerCiMetricsCommand } from "./ci-metrics.js";
3
+ import { registerCiPriorities } from "./ci-priorities.js";
4
+ /** One entry per subcommand, in help order. */
5
+ const CI_SUBCOMMANDS = [registerCiIntakeCommand, registerCiMetricsCommand, registerCiPriorities];
6
+ export function registerCiCommand(program) {
7
+ const ci = program.command("ci").description("Smart CI: record and measure what CI does (watch-only)");
8
+ for (const register of CI_SUBCOMMANDS)
9
+ register(ci);
10
+ }
11
+ //# sourceMappingURL=ci.js.map