@indigoai-us/hq-cli 5.345.251 → 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 (188) hide show
  1. package/CHANGELOG.md +153 -0
  2. package/assets/scaffold/core/scripts/hq-session.sh +9 -0
  3. package/contracts/host-canary-release.json +9 -3
  4. package/dist/command-catalog.generated.d.ts +269 -1
  5. package/dist/command-catalog.generated.js +330 -1
  6. package/dist/command-registration-plan.d.ts +6 -0
  7. package/dist/command-registration-plan.js +1 -0
  8. package/dist/commands/bot.js +7 -2
  9. package/dist/commands/ci-intake.d.ts +15 -0
  10. package/dist/commands/ci-intake.js +252 -0
  11. package/dist/commands/ci-metrics.d.ts +8 -0
  12. package/dist/commands/ci-metrics.js +55 -0
  13. package/dist/commands/ci.d.ts +13 -0
  14. package/dist/commands/ci.js +10 -0
  15. package/dist/commands/core-bucket-c-work-mesh-offer-native.js +1 -1
  16. package/dist/commands/core-hq-session-binding.d.ts +140 -0
  17. package/dist/commands/core-hq-session-binding.js +363 -0
  18. package/dist/commands/core-hq-session-native.d.ts +23 -0
  19. package/dist/commands/core-hq-session-native.js +59 -9
  20. package/dist/commands/core-stop-autosave.js +1 -1
  21. package/dist/commands/core.js +10 -0
  22. package/dist/commands/doctor.d.ts +5 -1
  23. package/dist/commands/doctor.js +42 -5
  24. package/dist/commands/files.d.ts +62 -0
  25. package/dist/commands/files.js +250 -9
  26. package/dist/commands/install-global.js +4 -2
  27. package/dist/commands/logout.js +4 -0
  28. package/dist/commands/ontology-graph.d.ts +2 -0
  29. package/dist/commands/ontology-graph.js +33 -0
  30. package/dist/commands/report.js +35 -2
  31. package/dist/commands/storage-gate.js +1 -1
  32. package/dist/commands/vault-retention-flag.js +2 -1
  33. package/dist/commands/whoami.js +1 -1
  34. package/dist/hq-cloud-sync-runner/bin/sync-runner.js +238 -221
  35. package/dist/hq-cloud-sync-runner/package.json +1 -1
  36. package/dist/index.js +3 -1
  37. package/dist/lib/agent-kit/inbox-poll-backoff-flag.js +1 -1
  38. package/dist/lib/agent-kit/mcp/tools.js +48 -0
  39. package/dist/lib/bot/fleet-bots-update-pass.js +1 -1
  40. package/dist/lib/bot/fleet-cron.d.ts +50 -0
  41. package/dist/lib/bot/fleet-cron.js +173 -32
  42. package/dist/lib/bot/fleet-local.d.ts +18 -0
  43. package/dist/lib/bot/fleet-local.js +51 -5
  44. package/dist/lib/bot/inbox-poll-backoff-flag.js +1 -1
  45. package/dist/lib/bot/signals-engine-flag.d.ts +1 -1
  46. package/dist/lib/bot/signals-engine-flag.js +1 -1
  47. package/dist/lib/cli-invite-nudge.js +1 -1
  48. package/dist/lib/client-version.d.ts +2 -0
  49. package/dist/lib/client-version.js +24 -0
  50. package/dist/lib/company-flag-gate.d.ts +30 -0
  51. package/dist/lib/company-flag-gate.js +104 -0
  52. package/dist/lib/core-utils/hook-timeout-debug-context-flag.js +1 -1
  53. package/dist/lib/daemon/flag.js +2 -1
  54. package/dist/lib/daemon/legacy-journal-gate.js +3 -1
  55. package/dist/lib/daemon/run.js +4 -3
  56. package/dist/lib/daemon/shared-flag-reads.js +1 -1
  57. package/dist/lib/delivery/migrations.d.ts +32 -1
  58. package/dist/lib/delivery/migrations.js +69 -8
  59. package/dist/lib/doctor/checks/host-core.js +22 -4
  60. package/dist/lib/doctor/checks/jq.d.ts +27 -6
  61. package/dist/lib/doctor/checks/jq.js +46 -8
  62. package/dist/lib/doctor/client-health-reason-codes-flag.js +1 -1
  63. package/dist/lib/doctor/fix/refresh-sync-handoff.d.ts +1 -1
  64. package/dist/lib/doctor/fix/refresh-sync-handoff.js +1 -1
  65. package/dist/lib/flag-client-gate-headers.d.ts +38 -0
  66. package/dist/lib/flag-client-gate-headers.js +62 -0
  67. package/dist/lib/flag-client-headers.d.ts +15 -0
  68. package/dist/lib/flag-client-headers.js +25 -0
  69. package/dist/lib/flag-registry-worker-source.generated.d.ts +1 -1
  70. package/dist/lib/flag-registry-worker-source.generated.js +1 -1
  71. package/dist/lib/flag-registry-worker.js +35 -0
  72. package/dist/lib/flag-registry.d.ts +1 -20
  73. package/dist/lib/flag-registry.js +5 -81
  74. package/dist/lib/hook-engine/adapter-core-pin.d.ts +30 -0
  75. package/dist/lib/hook-engine/adapter-core-pin.js +30 -0
  76. package/dist/lib/hook-engine/coverage.d.ts +65 -1
  77. package/dist/lib/hook-engine/coverage.js +173 -8
  78. package/dist/lib/hook-engine/reconcile.js +3 -2
  79. package/dist/lib/hot-channels/prompts/signals-pass.md +20 -0
  80. package/dist/lib/hot-channels/signal-changes.d.ts +228 -0
  81. package/dist/lib/hot-channels/signal-changes.js +683 -0
  82. package/dist/lib/hot-channels/signals-pass.d.ts +24 -0
  83. package/dist/lib/hot-channels/signals-pass.js +232 -12
  84. package/dist/lib/lanes/outpost-worktree-pruner-flag.d.ts +1 -1
  85. package/dist/lib/lanes/outpost-worktree-pruner-flag.js +1 -1
  86. package/dist/lib/lanes/registry-flag.js +2 -1
  87. package/dist/lib/lanes/spawn.js +11 -1
  88. package/dist/lib/mesh/live/binding-intent.d.ts +61 -0
  89. package/dist/lib/mesh/live/binding-intent.js +201 -0
  90. package/dist/lib/mesh/live/binding-receipt.d.ts +157 -0
  91. package/dist/lib/mesh/live/binding-receipt.js +365 -0
  92. package/dist/lib/mesh/live/company-flag-refresh.js +1 -1
  93. package/dist/lib/mesh/live/daemon/doctor-telemetry.d.ts +39 -0
  94. package/dist/lib/mesh/live/daemon/doctor-telemetry.js +58 -0
  95. package/dist/lib/mesh/live/daemon/install.js +2 -1
  96. package/dist/lib/mesh/live/daemon/presence.js +9 -0
  97. package/dist/lib/mesh/live/daemon/run.d.ts +3 -0
  98. package/dist/lib/mesh/live/daemon/run.js +33 -1
  99. package/dist/lib/ontology-graph/lineage/index.d.ts +401 -0
  100. package/dist/lib/ontology-graph/lineage/index.js +1027 -0
  101. package/dist/lib/ontology-graph/model/index.d.ts +54 -0
  102. package/dist/lib/ontology-graph/model/index.js +112 -0
  103. package/dist/lib/ontology-graph/model/pass-tasks.d.ts +75 -0
  104. package/dist/lib/ontology-graph/model/pass-tasks.js +166 -0
  105. package/dist/lib/ontology-graph/model/pass.d.ts +6 -0
  106. package/dist/lib/ontology-graph/model/pass.js +9 -2
  107. package/dist/lib/ontology-graph/model/pending-items.d.ts +8 -0
  108. package/dist/lib/ontology-graph/model/pending-items.js +24 -1
  109. package/dist/lib/ontology-graph/model/step.d.ts +1 -1
  110. package/dist/lib/ontology-graph/model/tasks.d.ts +11 -3
  111. package/dist/lib/ontology-graph/model/tasks.js +20 -7
  112. package/dist/lib/ontology-graph/read/brief.js +41 -6
  113. package/dist/lib/ontology-graph/read/index.d.ts +4 -0
  114. package/dist/lib/ontology-graph/read/index.js +173 -29
  115. package/dist/lib/ontology-graph/read/lineage.d.ts +101 -0
  116. package/dist/lib/ontology-graph/read/lineage.js +262 -0
  117. package/dist/lib/ontology-graph/replay/buffered-store.js +17 -0
  118. package/dist/lib/ontology-graph/replay/engine.d.ts +32 -1
  119. package/dist/lib/ontology-graph/replay/engine.js +213 -8
  120. package/dist/lib/ontology-graph/replay/extractors.d.ts +26 -0
  121. package/dist/lib/ontology-graph/replay/extractors.js +25 -1
  122. package/dist/lib/ontology-graph/replay/index.d.ts +2 -0
  123. package/dist/lib/ontology-graph/replay/index.js +9 -3
  124. package/dist/lib/ontology-graph/replay/signal-changes.d.ts +118 -0
  125. package/dist/lib/ontology-graph/replay/signal-changes.js +687 -0
  126. package/dist/lib/ontology-graph/schema/decision-status.d.ts +18 -0
  127. package/dist/lib/ontology-graph/schema/decision-status.js +20 -0
  128. package/dist/lib/ontology-graph/schema/index.d.ts +1 -0
  129. package/dist/lib/ontology-graph/schema/index.js +1 -0
  130. package/dist/lib/ontology-graph/setup/index.js +13 -3
  131. package/dist/lib/search-index/index.d.ts +33 -1
  132. package/dist/lib/search-index/index.js +180 -25
  133. package/dist/lib/search-index/qmd-exit-diagnostics.d.ts +7 -0
  134. package/dist/lib/search-index/qmd-exit-diagnostics.js +25 -1
  135. package/dist/lib/signals/adapters-catalog.js +1 -1
  136. package/dist/lib/smart-ci/cost.d.ts +72 -0
  137. package/dist/lib/smart-ci/cost.js +120 -0
  138. package/dist/lib/smart-ci/github.d.ts +112 -0
  139. package/dist/lib/smart-ci/github.js +267 -0
  140. package/dist/lib/smart-ci/intake.d.ts +288 -0
  141. package/dist/lib/smart-ci/intake.js +1078 -0
  142. package/dist/lib/smart-ci/ledger.d.ts +218 -0
  143. package/dist/lib/smart-ci/ledger.js +527 -0
  144. package/dist/lib/smart-ci/metrics.d.ts +137 -0
  145. package/dist/lib/smart-ci/metrics.js +249 -0
  146. package/dist/lib/smart-ci/records.d.ts +265 -0
  147. package/dist/lib/smart-ci/records.js +281 -0
  148. package/dist/lib/smart-ci/reducer.d.ts +67 -0
  149. package/dist/lib/smart-ci/reducer.js +261 -0
  150. package/dist/lib/sync-core/engine-holds.d.ts +15 -0
  151. package/dist/lib/sync-core/engine-holds.js +104 -11
  152. package/dist/lib/sync-core/engine-home.d.ts +3 -0
  153. package/dist/lib/sync-core/engine-home.js +41 -1
  154. package/dist/lib/sync-core/flag.js +2 -1
  155. package/dist/lib/sync-core/hand-back.d.ts +1 -0
  156. package/dist/lib/sync-core/hand-back.js +7 -2
  157. package/dist/lib/sync-core/legacy-journal-export-child.js +5 -3
  158. package/dist/lib/sync-core/legacy-journal-export.d.ts +23 -4
  159. package/dist/lib/sync-core/legacy-journal-export.js +120 -55
  160. package/dist/lib/sync-core/reconcile.d.ts +2 -1
  161. package/dist/lib/sync-core/reconcile.js +40 -7
  162. package/dist/lib/sync-invalid-entity-warning.js +2 -1
  163. package/dist/lib/windows/install-followup.d.ts +41 -0
  164. package/dist/lib/windows/install-followup.js +87 -0
  165. package/dist/lib/windows/jq.d.ts +59 -0
  166. package/dist/lib/windows/jq.js +154 -3
  167. package/dist/lib/windows/user-path.d.ts +5 -0
  168. package/dist/lib/windows/user-path.js +1 -1
  169. package/dist/lib/work-context/auto-bind.d.ts +12 -0
  170. package/dist/lib/work-context/auto-bind.js +49 -3
  171. package/dist/lib/work-context/organize.d.ts +4 -2
  172. package/dist/lib/work-context/organize.js +18 -8
  173. package/dist/lib/work-context/reconcile.js +16 -1
  174. package/dist/main.js +12 -1
  175. package/dist/utils/client-health-contract.d.ts +30 -0
  176. package/dist/utils/client-health-contract.js +111 -0
  177. package/dist/utils/client-health.d.ts +5 -2
  178. package/dist/utils/client-health.js +74 -5
  179. package/dist/utils/exclusive-lock.d.ts +5 -1
  180. package/dist/utils/exclusive-lock.js +9 -2
  181. package/dist/utils/host-registration.d.ts +7 -0
  182. package/dist/utils/host-registration.js +10 -1
  183. package/dist/utils/pid.d.ts +31 -0
  184. package/dist/utils/pid.js +65 -0
  185. package/dist/utils/resident-package-preload.js +12 -4
  186. package/dist/utils/sentry-fingerprint.js +3 -0
  187. package/package.json +10 -8
  188. package/scripts/install-hook-engine.mjs +5 -3
@@ -0,0 +1,252 @@
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
+ export const DEFAULT_REPOS = ["indigoai-us/hq-cli", "indigoai-us/hq-pro"];
18
+ export const DEFAULT_RUNNER_ORG = "indigoai-us";
19
+ class UsageError extends Error {
20
+ }
21
+ function positive(value, name, fallback) {
22
+ if (value === undefined)
23
+ return fallback;
24
+ const n = Number(value);
25
+ if (!Number.isFinite(n) || n <= 0)
26
+ throw new UsageError(`${name} must be a number above zero, got ${JSON.stringify(value)}`);
27
+ return n;
28
+ }
29
+ function nonNegative(value, name, fallback) {
30
+ if (value === undefined)
31
+ return fallback;
32
+ const n = Number(value);
33
+ if (!Number.isFinite(n) || n < 0)
34
+ throw new UsageError(`${name} must be zero or more, got ${JSON.stringify(value)}`);
35
+ return n;
36
+ }
37
+ /** Environment variables `gh` would take a token from in place of the signed-in login. */
38
+ const TOKEN_ENV = ["GH_TOKEN", "GITHUB_TOKEN", "GH_ENTERPRISE_TOKEN", "GITHUB_ENTERPRISE_TOKEN"];
39
+ const runGh = (file, args, env) => new Promise((resolve) => {
40
+ execFile(file, args, { timeout: 10_000, env }, (err, stdout) => resolve(err ? "" : stdout.trim()));
41
+ });
42
+ /**
43
+ * The GitHub token of this machine's signed-in `gh` login, and nothing else.
44
+ * A token in GH_TOKEN or GITHUB_TOKEN is never used: under an Actions or App
45
+ * installation token the intake would spend the allowance CI itself runs on.
46
+ * Those variables are also taken out of the environment `gh` is asked in, so
47
+ * `gh auth token` cannot hand one back. With no signed-in login the intake
48
+ * refuses to start. The token is held in memory and never printed or logged.
49
+ */
50
+ export async function resolveGitHubToken(env = process.env, run = runGh) {
51
+ const clean = { ...env };
52
+ for (const name of TOKEN_ENV)
53
+ delete clean[name];
54
+ const token = await run("gh", ["auth", "token", "--hostname", "github.com"], clean);
55
+ if (token === "") {
56
+ 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.");
57
+ }
58
+ return token;
59
+ }
60
+ function sleep(ms, signal) {
61
+ return new Promise((resolve) => {
62
+ if (signal.aborted)
63
+ return resolve();
64
+ const timer = setTimeout(done, ms);
65
+ function done() {
66
+ clearTimeout(timer);
67
+ signal.removeEventListener("abort", done);
68
+ resolve();
69
+ }
70
+ signal.addEventListener("abort", done);
71
+ });
72
+ }
73
+ async function runIntake(opts) {
74
+ const out = (line) => process.stdout.write(`${line}\n`);
75
+ const storeDir = opts.storeDir ?? defaultLedgerDir();
76
+ if (opts.recordFixture !== undefined) {
77
+ const repos = opts.repo ?? [];
78
+ if (repos.length !== 1 || !opts.from || !opts.to)
79
+ throw new UsageError("--record-fixture needs exactly one --repo, --from and --to");
80
+ const client = new GitHubReadClient({ token: await resolveGitHubToken(), auditPath: opts.auditLog });
81
+ 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);
82
+ const text = serializeFixture({ repo: repos[0], from: opts.from, to: opts.to, recordedAt: new Date().toISOString() }, observations);
83
+ const sensitive = findSensitive(text);
84
+ if (sensitive.length > 0) {
85
+ throw new IntakeInputError(`refusing to write the fixture: line ${sensitive[0].line} still holds ${sensitive[0].what} after scrubbing (${sensitive.length} lines in all)`);
86
+ }
87
+ writeFileSync(opts.recordFixture, opts.recordFixture.endsWith(".gz") ? gzipSync(text) : text);
88
+ const counts = client.counts();
89
+ const summary = { fixture: opts.recordFixture, observations: observations.length, requests: counts.total };
90
+ out(opts.json ? JSON.stringify(summary) : `Recorded ${observations.length} observations to ${opts.recordFixture} with ${counts.total} GitHub read requests.`);
91
+ return;
92
+ }
93
+ const ledger = SmartCiLedger.open({ dir: storeDir, controllerId: `smart-ci-intake@${hostname()}` });
94
+ try {
95
+ if (opts.replayFixture !== undefined) {
96
+ const fixture = readFixture(opts.replayFixture);
97
+ const report = replayFixture(ledger, fixture, {
98
+ batchSize: positive(opts.batchSize, "--batch-size", 200),
99
+ onBatch: (done, total) => process.stderr.write(`replayed ${done}/${total}\n`),
100
+ });
101
+ out(opts.json
102
+ ? JSON.stringify(report)
103
+ : `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.`);
104
+ return;
105
+ }
106
+ const repos = opts.repo && opts.repo.length > 0 ? opts.repo : [...DEFAULT_REPOS];
107
+ const intervalMs = positive(opts.intervalSeconds, "--interval-seconds", 60) * 1000;
108
+ if (intervalMs < 10_000)
109
+ throw new UsageError("--interval-seconds must be 10 or more, to stay inside the GitHub request budget");
110
+ const durationMs = opts.durationMinutes === undefined ? null : positive(opts.durationMinutes, "--duration-minutes", 60) * 60_000;
111
+ const lookbackMs = nonNegative(opts.lookbackMinutes, "--lookback-minutes", 0) * 60_000;
112
+ const auditPath = opts.auditLog ?? join(storeDir, "smart-ci-github-audit.jsonl");
113
+ const client = new GitHubReadClient({ token: await resolveGitHubToken(), auditPath });
114
+ const startedMs = Date.now();
115
+ const poller = new Poller(ledger, client, {
116
+ repos,
117
+ runnerOrg: opts.runners === false ? null : (opts.runnerOrg ?? DEFAULT_RUNNER_ORG),
118
+ startAt: new Date(startedMs - lookbackMs).toISOString(),
119
+ hourlyBudget: positive(opts.hourlyBudget, "--hourly-budget", DEFAULT_HOURLY_BUDGET),
120
+ rateFloor: nonNegative(opts.rateFloor, "--rate-floor", DEFAULT_RATE_FLOOR),
121
+ activeWindowMs: nonNegative(opts.activeWindowMinutes, "--active-window-minutes", 120) * 60_000,
122
+ checkRuns: opts.checkRuns,
123
+ log: (l) => process.stderr.write(`${l}\n`),
124
+ });
125
+ const stop = new AbortController();
126
+ const onSignal = () => stop.abort();
127
+ process.once("SIGINT", onSignal);
128
+ process.once("SIGTERM", onSignal);
129
+ let cycles = 0;
130
+ let recorded = 0;
131
+ let gaps = 0;
132
+ let archived = 0;
133
+ let sweepStartedAt = null;
134
+ const tally = (report, sweep) => {
135
+ cycles += 1;
136
+ recorded += report.created;
137
+ gaps += report.gaps;
138
+ archived += report.archived;
139
+ const line = {
140
+ at: report.startedAt,
141
+ sweep,
142
+ observations: report.observations,
143
+ created: report.created,
144
+ updated: report.updated,
145
+ runsFinalized: report.runsFinalized,
146
+ openRuns: report.openRuns,
147
+ requestsLastHour: report.requests.lastHour,
148
+ chargedLastHour: report.chargedLastHour,
149
+ rateRemaining: report.requests.rateRemaining,
150
+ gaps: report.gaps,
151
+ archived: report.archived,
152
+ skipped: report.skipped.length,
153
+ };
154
+ process.stderr.write(`${JSON.stringify(line)}\n`);
155
+ };
156
+ try {
157
+ for (;;) {
158
+ const cycleStart = Date.now();
159
+ tally(await poller.cycle(), false);
160
+ if (opts.once || stop.signal.aborted)
161
+ break;
162
+ if (durationMs !== null && Date.now() - startedMs >= durationMs)
163
+ break;
164
+ const wait = Math.max(1000, intervalMs - (Date.now() - cycleStart));
165
+ await sleep(durationMs === null ? wait : Math.min(wait, Math.max(0, startedMs + durationMs - Date.now())), stop.signal);
166
+ if (stop.signal.aborted)
167
+ break;
168
+ if (durationMs !== null && Date.now() - startedMs >= durationMs)
169
+ break;
170
+ }
171
+ if (!opts.once) {
172
+ // Before stopping, read every open run once more, so the ledger holds each job GitHub lists up to this moment.
173
+ sweepStartedAt = new Date().toISOString();
174
+ tally(await poller.finish(), true);
175
+ }
176
+ }
177
+ finally {
178
+ process.removeListener("SIGINT", onSignal);
179
+ process.removeListener("SIGTERM", onSignal);
180
+ }
181
+ const counts = client.counts();
182
+ const summary = {
183
+ repos,
184
+ startedAt: new Date(startedMs).toISOString(),
185
+ endedAt: new Date().toISOString(),
186
+ sweepStartedAt,
187
+ cycles,
188
+ recordsCreated: recorded,
189
+ recordsArchived: archived,
190
+ gaps,
191
+ requests: counts.total,
192
+ notModified: counts.notModified,
193
+ charged: counts.total - counts.notModified,
194
+ chargedLastHour: poller.chargedLastHour(),
195
+ auditLog: auditPath,
196
+ storeDir,
197
+ };
198
+ out(opts.json
199
+ ? JSON.stringify(summary)
200
+ : `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}`);
201
+ }
202
+ finally {
203
+ ledger.close();
204
+ }
205
+ }
206
+ export function registerCiIntakeCommand(ci) {
207
+ ci.command("intake")
208
+ .description("Record CI jobs, checks, pull requests, pushes and runner pool state into the run ledger (read-only towards GitHub)")
209
+ .option("--repo <owner/name>", "repository to record; repeat for more (default: indigoai-us/hq-cli and indigoai-us/hq-pro)", (v, prev = []) => [...prev, v])
210
+ .option("--runner-org <org>", `org whose runner pools are sampled (default: ${DEFAULT_RUNNER_ORG})`)
211
+ .option("--no-runners", "do not sample runner pools")
212
+ .option("--no-check-runs", "do not read check runs")
213
+ .option("--store-dir <path>", "ledger directory (default: HQ_SMART_CI_STORE_DIR, else ~/.hq/delivery/ledger)")
214
+ .option("--once", "run one cycle and stop")
215
+ .option("--duration-minutes <n>", "stop after this many minutes (default: run until stopped)")
216
+ .option("--interval-seconds <n>", "seconds between cycles (default: 60)")
217
+ .option("--lookback-minutes <n>", "on a first start, also record runs created this many minutes back (default: 0)")
218
+ .option("--hourly-budget <n>", `charged GitHub requests an hour the intake allows itself, counted across restarts (default: ${DEFAULT_HOURLY_BUDGET})`)
219
+ .option("--rate-floor <n>", `make no request while the gh login has this many or fewer requests left this hour (default: ${DEFAULT_RATE_FLOOR})`)
220
+ .option("--active-window-minutes <n>", "closed records older than this move to dated archive files; 0 keeps one file (default: 120)")
221
+ .option("--audit-log <path>", "where to write one line per GitHub request (default: smart-ci-github-audit.jsonl in the ledger directory)")
222
+ .option("--replay-fixture <path>", "record a fixture file instead of polling GitHub")
223
+ .option("--batch-size <n>", "observations per commit when replaying (default: 200)")
224
+ .option("--record-fixture <path>", "read a past window from GitHub and write it as a fixture; needs one --repo, --from and --to")
225
+ .option("--from <iso>", "start of the window to record (inclusive)")
226
+ .option("--to <iso>", "end of the window to record (exclusive)")
227
+ .option("--json", "print the final summary as JSON")
228
+ .action(async (opts) => {
229
+ try {
230
+ await runIntake(opts);
231
+ }
232
+ catch (err) {
233
+ if (err instanceof UsageError || err instanceof IntakeInputError || err instanceof GitHubReadError) {
234
+ process.stderr.write(`hq ci intake: ${err.message}\n`);
235
+ process.exitCode = err instanceof UsageError ? 2 : 1;
236
+ return;
237
+ }
238
+ if (err instanceof SmartCiLedgerError) {
239
+ process.stderr.write(`hq ci intake: ${err.message}\n`);
240
+ process.exitCode = 1;
241
+ return;
242
+ }
243
+ if (err instanceof DeliveryStoreError) {
244
+ process.stderr.write(`hq ci intake: the ledger could not be used (${err.code}). Found: ${err.found}. ${err.action}\n`);
245
+ process.exitCode = 1;
246
+ return;
247
+ }
248
+ throw err;
249
+ }
250
+ });
251
+ }
252
+ //# 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,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,10 @@
1
+ import { registerCiIntakeCommand } from "./ci-intake.js";
2
+ import { registerCiMetricsCommand } from "./ci-metrics.js";
3
+ /** One entry per subcommand, in help order. */
4
+ const CI_SUBCOMMANDS = [registerCiIntakeCommand, registerCiMetricsCommand];
5
+ export function registerCiCommand(program) {
6
+ const ci = program.command("ci").description("Smart CI: record and measure what CI does (watch-only)");
7
+ for (const register of CI_SUBCOMMANDS)
8
+ register(ci);
9
+ }
10
+ //# sourceMappingURL=ci.js.map
@@ -1,7 +1,7 @@
1
1
  import * as fs from "node:fs";
2
2
  import * as path from "node:path";
3
3
  import { loadCachedTokens } from "@indigoai-us/hq-cloud";
4
- import { createFlagClient } from "@indigoai-us/hq-flags-client";
4
+ import { createHqFlagClient as createFlagClient } from "../lib/flag-client-headers.js";
5
5
  import { resolveFlagRegistryEndpoint } from "../lib/flag-registry-endpoint.js";
6
6
  const success = (stdout) => ({ code: 0, stdout, stderr: "" });
7
7
  const failure = (stderr) => ({ code: 1, stdout: "", stderr: `${stderr}\n` });
@@ -0,0 +1,140 @@
1
+ /**
2
+ * After a successful `hq core hq-session` company change, write the session's
3
+ * binding receipt (src/lib/mesh/live/binding-receipt.ts).
4
+ *
5
+ * A receipt is written only for a change that reached `hq` from a person, an
6
+ * agent or a launcher:
7
+ *
8
+ * - not when `HQ_HQ_SESSION_NO_CLI=1` is set (a hook wrote meta.yaml itself
9
+ * and told the script not to come here);
10
+ * - not from inside a hook run. master-hook (`export HQ_HOOK_EVENT`) and the
11
+ * native hook host (crates/hq-hook/src/dispatch) set `HQ_HOOK_EVENT` for
12
+ * every child they start, so a bind a hook makes on its own, such as the
13
+ * SessionStart folder-registry bind, carries it. A command the agent runs
14
+ * is started by the host, not by a hook, and does not;
15
+ * - not, as a second guard for hook runtimes that set no such variable,
16
+ * when meta.yaml carries `foreign_cwd` (the registry bind's own line) and
17
+ * the session has not had a turn yet (no Work Mesh sequence file);
18
+ * - not for a session the command found through the global, last-writer-wins
19
+ * `workspace/sessions/.current`. Another session can rewrite that file
20
+ * between the change and this write.
21
+ * - not for a session found through the environment. A child process
22
+ * inherits its parent's session variables: a Codex child has the
23
+ * parent's CLAUDE_CODE_SESSION_ID next to its own CODEX_THREAD_ID, and a
24
+ * Cursor or Antigravity shell started from Claude Code has only the
25
+ * parent's. Only a `--session-id` the caller typed counts, and only when
26
+ * it names a session that no session variable in this environment names:
27
+ * hq-session.sh forwards an id it took from the environment as
28
+ * `--session-id` (and, from the release that has it, says so with
29
+ * `HQ_SESSION_ID_SOURCE=env`), so an id equal to one in the environment
30
+ * cannot be told from an inherited one by the CLI alone. That holds
31
+ * for scripts that do not set the marker too. Such a change gets a
32
+ * receipt only when the hook host confirmed it: the native scope guard
33
+ * leaves a single-use intent for the real session of the tool call that
34
+ * ran it (src/lib/mesh/live/binding-intent.ts), and this command consumes
35
+ * a matching one. Until the hook writes intents, there is none, and the
36
+ * change gets no counting receipt, as before. One rule keeps the
37
+ * receipt from disagreeing with the lock set: when such an unconfirmed
38
+ * change leaves a lock set different from the session's last line in
39
+ * this tree (an unbind, a remove, a switch, or an add that turns one
40
+ * company into two), a line is still written with the new lock set and
41
+ * the source `unconfirmed`, which never counts. Only an exact repeat of
42
+ * the last line's set writes nothing;
43
+ * - not when meta.yaml of that session does not show the change (another
44
+ * writer won).
45
+ *
46
+ * The receipt's source is the source of the bind action itself, never the
47
+ * label meta.yaml happens to carry: a `set company_slug` that got here is an
48
+ * explicit act (`explicit`), unless the caller names its own source in
49
+ * `HQ_SESSION_COMPANY_SOURCE` (a value that is not a plain lowercase word is
50
+ * recorded as no source, which never counts), or the run is unattended
51
+ * (`HQ_SYNC_UNATTENDED`,
52
+ * which `hq core job run` and Outpost units export): that is
53
+ * `scheduled_task`. `set company_source` writes no receipt, so the label
54
+ * cannot turn a default into a choice afterwards.
55
+ *
56
+ * Each line names the HQ tree it was made in, so a reader of another tree
57
+ * never counts it. When `--session-id` names a session other than the
58
+ * caller's own (the session id in the environment), the caller is recorded
59
+ * as `actor`.
60
+ *
61
+ * meta.yaml is read and the line appended under the session's company lock,
62
+ * so the line holds the lock set as the last writer left it.
63
+ *
64
+ * After a receipt line that leaves the session bound to exactly one company,
65
+ * when that bind counts and the company's `work-mesh-company-reporting-required`
66
+ * flag is fresh and on, the command prints "Activity in session <short id>
67
+ * (this session | not this session) is reported to <company>. Required by
68
+ * the company." Nothing records that the line was shown: whether a person
69
+ * saw it is decided by slice 6's person-only channel, not by this command.
70
+ *
71
+ * Nothing here can fail the command: any error means no receipt and no line.
72
+ */
73
+ import { type BindingAction, type BindingLine, type BindingPaths } from "../lib/mesh/live/binding-receipt.js";
74
+ import type { HqSessionTarget } from "./core-hq-session-native.js";
75
+ export interface RecordSessionBindingDeps extends BindingPaths {
76
+ /**
77
+ * The session the command changed and how it was found. Null, or found
78
+ * through `.current`: no receipt.
79
+ */
80
+ target: HqSessionTarget | null;
81
+ /** Writes the member line. Defaults to stdout. */
82
+ write?: (text: string) => void;
83
+ /** The company's cloud uid, for its reporting flag. Defaults to {@link companyCloudUid}. */
84
+ companyUid?: (hqRoot: string, slug: string) => string | null;
85
+ /** Runs the action while holding the session's company lock. */
86
+ withCompanyLock?: <T>(sessionId: string, action: () => T) => T;
87
+ }
88
+ type ReceiptAction = Exclude<BindingAction, "source">;
89
+ /** The company change a `hq-session` command line asks for, or null. */
90
+ export declare function bindingActionOf(argv: readonly string[]): {
91
+ globalArgs: string[];
92
+ action: ReceiptAction;
93
+ slug: string;
94
+ } | null;
95
+ /**
96
+ * The value of the last `--session-id` in the leading global arguments, as
97
+ * hq-session.sh and the native command read it (a later flag wins). Undefined
98
+ * when there is none.
99
+ */
100
+ export declare function lastSessionFlag(globalArgs: readonly string[]): string | undefined;
101
+ /**
102
+ * Every distinct session id the environment's session variables name,
103
+ * lower-cased: session folders and receipt files live on case-insensitive
104
+ * file systems, so ids that differ only in case are the same session.
105
+ */
106
+ export declare function environmentSessionIds(env: NodeJS.ProcessEnv): string[];
107
+ /**
108
+ * The id came from the environment: hq-session.sh said so, or it equals an
109
+ * id a session variable here names (an older script that sets no marker
110
+ * forwards such an id as --session-id, and an inherited id looks the same).
111
+ */
112
+ export declare function sessionIdFromEnvironment(sessionId: string, env: NodeJS.ProcessEnv): boolean;
113
+ /**
114
+ * The company's cloud uid: `companies/<slug>/.company-uid` first, then
115
+ * `companies.<slug>.cloud_uid` in companies/manifest.yaml, the same order as
116
+ * the daemon's recordedUid (src/lib/daemon/hook-requests-mesh.ts). Null when
117
+ * neither holds a valid uid.
118
+ */
119
+ export declare function companyCloudUid(hqRoot: string, slug: string): string | null;
120
+ /** The company's cloud uid from `companies/manifest.yaml` (`companies.<slug>.cloud_uid`), or null. */
121
+ export declare function manifestCompanyUid(hqRoot: string, slug: string): string | null;
122
+ /**
123
+ * The session the bundled hq-session.sh changed, from the two sources it
124
+ * reads before `.current`: the last `--session-id`, then a session id in the
125
+ * environment (same keys and order as core/scripts/lib/session-id.sh). Null
126
+ * when neither names one; the script then fell back to `.current`.
127
+ */
128
+ export declare function scriptSessionTarget(argv: readonly string[], env?: NodeJS.ProcessEnv): HqSessionTarget | null;
129
+ /**
130
+ * The source of this change. `previous` is the receipt's last line: the bind
131
+ * the session already had.
132
+ */
133
+ /** The source of an unconfirmed line that only closes: never on the allowlist. */
134
+ export declare const UNCONFIRMED_SOURCE = "unconfirmed";
135
+ export declare function recordSessionBinding(argv: readonly string[], context: {
136
+ cwd: string;
137
+ hqRoot?: string;
138
+ }, deps: RecordSessionBindingDeps): BindingLine | null;
139
+ export {};
140
+ //# sourceMappingURL=core-hq-session-binding.d.ts.map