@indigoai-us/hq-cli 5.345.215 → 5.345.217

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 (135) hide show
  1. package/CHANGELOG.md +141 -0
  2. package/README.md +45 -0
  3. package/assets/scaffold/core/scripts/lib/epochrealtime.sh +30 -0
  4. package/assets/scaffold/core/scripts/lib/work-mesh-enqueue.sh +12 -5
  5. package/dist/command-catalog.generated.d.ts +59 -4
  6. package/dist/command-catalog.generated.js +74 -4
  7. package/dist/command-help.js +3 -1
  8. package/dist/command-registration-plan.d.ts +6 -0
  9. package/dist/command-registration-plan.js +1 -0
  10. package/dist/commands/auth.d.ts +1 -1
  11. package/dist/commands/auth.js +11 -52
  12. package/dist/commands/bot.js +11 -4
  13. package/dist/commands/cloud-demote.d.ts +19 -4
  14. package/dist/commands/cloud-demote.js +85 -12
  15. package/dist/commands/cloud-provision.d.ts +5 -1
  16. package/dist/commands/cloud-provision.js +6 -2
  17. package/dist/commands/cloud.d.ts +36 -0
  18. package/dist/commands/cloud.js +109 -26
  19. package/dist/commands/core.js +1 -0
  20. package/dist/commands/daemon.js +4 -1
  21. package/dist/commands/dm.js +7 -0
  22. package/dist/commands/doctor-usage.d.ts +8 -0
  23. package/dist/commands/doctor-usage.js +20 -0
  24. package/dist/commands/doctor.js +7 -1
  25. package/dist/commands/env.d.ts +18 -0
  26. package/dist/commands/env.js +82 -0
  27. package/dist/commands/install-global.js +2 -2
  28. package/dist/commands/lanes.js +100 -24
  29. package/dist/commands/logout.d.ts +7 -0
  30. package/dist/commands/logout.js +41 -34
  31. package/dist/commands/sources.d.ts +8 -2
  32. package/dist/commands/sources.js +65 -9
  33. package/dist/commands/whoami.js +26 -1
  34. package/dist/data/command-states.json +15 -0
  35. package/dist/index.js +52 -4
  36. package/dist/lazy-commands.js +2 -1
  37. package/dist/lib/anywhere-person-setting.d.ts +2 -0
  38. package/dist/lib/anywhere-person-setting.js +6 -3
  39. package/dist/lib/billing/usage-card.d.ts +25 -4
  40. package/dist/lib/billing/usage-card.js +76 -9
  41. package/dist/lib/billing/usage-cost.d.ts +3 -3
  42. package/dist/lib/billing/usage-cost.js +35 -13
  43. package/dist/lib/billing/usage-only.js +4 -2
  44. package/dist/lib/billing/usage-rate-card.d.ts +2 -2
  45. package/dist/lib/billing/usage-rate-card.js +3 -0
  46. package/dist/lib/bot/fleet-cron.js +93 -6
  47. package/dist/lib/bot/inflight.d.ts +9 -0
  48. package/dist/lib/bot/inflight.js +10 -0
  49. package/dist/lib/bot/jobs/hot-signal-sync.js +12 -1
  50. package/dist/lib/bot/runtime/grok-acp.d.ts +1 -0
  51. package/dist/lib/bot/runtime/grok-acp.js +26 -11
  52. package/dist/lib/bot/runtime/grok.js +1 -1
  53. package/dist/lib/daemon/flag-monitor.d.ts +8 -0
  54. package/dist/lib/daemon/flag-monitor.js +17 -6
  55. package/dist/lib/daemon/flag.d.ts +65 -1
  56. package/dist/lib/daemon/flag.js +190 -40
  57. package/dist/lib/daemon/ops/policy.js +62 -5
  58. package/dist/lib/daemon/paths.d.ts +72 -2
  59. package/dist/lib/daemon/paths.js +154 -3
  60. package/dist/lib/daemon/run.js +25 -20
  61. package/dist/lib/daemon/selfcheck.d.ts +22 -0
  62. package/dist/lib/daemon/selfcheck.js +40 -1
  63. package/dist/lib/daemon/server.d.ts +3 -1
  64. package/dist/lib/daemon/server.js +7 -22
  65. package/dist/lib/daemon/state-file-switch.d.ts +57 -0
  66. package/dist/lib/daemon/state-file-switch.js +88 -0
  67. package/dist/lib/daemon/state-file.d.ts +198 -0
  68. package/dist/lib/daemon/state-file.js +419 -0
  69. package/dist/lib/daemon/timed-flag-monitors.d.ts +47 -0
  70. package/dist/lib/daemon/timed-flag-monitors.js +75 -0
  71. package/dist/lib/doctor/checks/host-core.d.ts +50 -0
  72. package/dist/lib/doctor/checks/host-core.js +269 -0
  73. package/dist/lib/doctor/checks/replay-recorder.d.ts +39 -0
  74. package/dist/lib/doctor/checks/replay-recorder.js +261 -0
  75. package/dist/lib/doctor/registry.js +4 -0
  76. package/dist/lib/environment/profile.d.ts +239 -0
  77. package/dist/lib/environment/profile.js +251 -0
  78. package/dist/lib/hook-engine/reconcile.js +39 -13
  79. package/dist/lib/hook-engine/registration.d.ts +9 -0
  80. package/dist/lib/hook-engine/registration.js +19 -0
  81. package/dist/lib/hot-channels/adapters/slack.d.ts +21 -5
  82. package/dist/lib/hot-channels/adapters/slack.js +64 -21
  83. package/dist/lib/hot-channels/alert.d.ts +2 -0
  84. package/dist/lib/hot-channels/alert.js +8 -1
  85. package/dist/lib/hot-channels/contract.d.ts +12 -0
  86. package/dist/lib/hot-channels/contract.js +7 -0
  87. package/dist/lib/hot-channels/loop.js +1 -0
  88. package/dist/lib/hot-channels/run.d.ts +6 -0
  89. package/dist/lib/hot-channels/run.js +4 -0
  90. package/dist/lib/hot-channels/signals-pass.d.ts +64 -1
  91. package/dist/lib/hot-channels/signals-pass.js +21 -49
  92. package/dist/lib/install/claude-targets.d.ts +12 -1
  93. package/dist/lib/install/claude-targets.js +57 -5
  94. package/dist/lib/install/codex-targets.d.ts +2 -2
  95. package/dist/lib/install/codex-targets.js +36 -6
  96. package/dist/lib/install/hook-target.d.ts +3 -0
  97. package/dist/lib/install/hook-target.js +11 -0
  98. package/dist/lib/lanes/canonical-host.d.ts +35 -0
  99. package/dist/lib/lanes/canonical-host.js +65 -0
  100. package/dist/lib/lanes/host-capacity.d.ts +30 -0
  101. package/dist/lib/lanes/host-capacity.js +29 -3
  102. package/dist/lib/mesh/live/daemon/run.d.ts +2 -0
  103. package/dist/lib/mesh/live/daemon/run.js +5 -2
  104. package/dist/lib/mesh/live/flush.d.ts +5 -1
  105. package/dist/lib/mesh/live/flush.js +12 -6
  106. package/dist/lib/mesh/live/reporting-privacy.d.ts +32 -0
  107. package/dist/lib/mesh/live/reporting-privacy.js +56 -1
  108. package/dist/lib/mesh/live/spool.d.ts +7 -0
  109. package/dist/lib/mesh/live/spool.js +25 -0
  110. package/dist/lib/person-setting-cache.d.ts +38 -0
  111. package/dist/lib/person-setting-cache.js +98 -0
  112. package/dist/lib/safe-store.d.ts +245 -0
  113. package/dist/lib/safe-store.js +777 -0
  114. package/dist/lib/signals/engine.d.ts +29 -2
  115. package/dist/lib/signals/engine.js +103 -4
  116. package/dist/lib/signals/reply.js +73 -18
  117. package/dist/lib/signals/steps/adapters.js +7 -2
  118. package/dist/lib/signals/steps/extract.d.ts +13 -0
  119. package/dist/lib/signals/steps/extract.js +84 -4
  120. package/dist/main.js +46 -3
  121. package/dist/schemas/hq-environment-profile.v1.schema.json +438 -0
  122. package/dist/utils/auth-expiry.d.ts +8 -0
  123. package/dist/utils/auth-expiry.js +53 -0
  124. package/dist/utils/cli-telemetry.d.ts +21 -0
  125. package/dist/utils/cli-telemetry.js +34 -0
  126. package/dist/utils/command-usage.d.ts +275 -0
  127. package/dist/utils/command-usage.js +797 -0
  128. package/dist/utils/hook-trust.d.ts +7 -0
  129. package/dist/utils/hook-trust.js +31 -4
  130. package/dist/utils/host-registration.d.ts +126 -0
  131. package/dist/utils/host-registration.js +378 -0
  132. package/dist/utils/resident-package-preload.js +2 -0
  133. package/package.json +10 -8
  134. package/scripts/bench-core.mjs +1096 -0
  135. package/scripts/check-function-manifest.mjs +702 -0
@@ -0,0 +1,269 @@
1
+ /**
2
+ * `hq doctor`: which core each host on this machine is using, per event, and
3
+ * why (hq-core-rust US-017). Reads the registration files `hq reindex` writes
4
+ * and the kill switch, and writes nothing. When an event is registered to the
5
+ * new core, or the flag is on, it starts the engine once (`--version` and
6
+ * `capabilities --json`) to see which evaluators it has. An event registered
7
+ * to a new core that is missing, does not run, or lacks the event's guards is
8
+ * FAIL; a host with no HQ registration is NA.
9
+ */
10
+ import * as fs from 'node:fs';
11
+ import * as os from 'node:os';
12
+ import * as path from 'node:path';
13
+ import { jsonFormat } from '../../../commands/mcp-registration.js';
14
+ import { CORE_NEXT_LINK, isCoreNextEntry, isNativeEntry } from '../../hook-engine/registration.js';
15
+ import { isAdapterEntry } from '../../install/codex-targets.js';
16
+ import { masterHookPath, shimPath } from '../../install/claude-targets.js';
17
+ import { CORE_NEXT_FLAG, CORE_NEXT_KILL_ENV, CORE_NEXT_KILL_FILE, ENGINE_KILL_ENV, ENGINE_KILL_FILE, REQUIRED_EVALUATORS, STABLE_LINK_NAME, coreNextEnabled, missingEvaluators, probeEngine, } from '../../../utils/host-registration.js';
18
+ import { HOOKS_FAMILY_ID } from '../registry.js';
19
+ export const HOST_CORE_FAMILY_ID = 'host-core';
20
+ export const HOST_CORE_FAMILY_TITLE = 'Hook core per host';
21
+ /** The registration files `hq reindex` reconciles, per host. */
22
+ export function hostRegistrationFiles(root, home, env) {
23
+ return [
24
+ { host: 'claude', scope: 'project', file: path.join(root, '.claude', 'settings.json') },
25
+ { host: 'claude', scope: 'user', file: path.join(env.CLAUDE_CONFIG_DIR || path.join(home, '.claude'), 'settings.json') },
26
+ { host: 'codex', scope: 'project', file: path.join(root, '.codex', 'hooks.json') },
27
+ { host: 'codex', scope: 'user', file: path.join(env.CODEX_HOME || path.join(home, '.codex'), 'hooks.json') },
28
+ { host: 'grok', scope: 'user', file: path.join(home, '.grok', 'hooks', 'hq-hq-bridge.json') },
29
+ ];
30
+ }
31
+ function hookEntries(doc) {
32
+ const hooks = doc?.hooks;
33
+ if (!hooks || typeof hooks !== 'object' || Array.isArray(hooks))
34
+ return [];
35
+ return Object.values(hooks).flatMap((groups) => Array.isArray(groups)
36
+ ? groups.flatMap((g) => Array.isArray(g?.hooks) ? g.hooks.filter((h) => !!h && typeof h === 'object') : [])
37
+ : []);
38
+ }
39
+ /** Which core one HQ hook entry calls, or null when the entry is not HQ's. */
40
+ export function classifyEntry(entry, host, root) {
41
+ if (isCoreNextEntry(entry, root))
42
+ return 'new-core';
43
+ if (isNativeEntry(entry, root))
44
+ return 'launcher';
45
+ const command = entry.command;
46
+ if (typeof command !== 'string')
47
+ return null;
48
+ // A stable-path entry for another HQ root still calls the new core.
49
+ if (CORE_NEXT_LINK.test(command))
50
+ return 'new-core';
51
+ if (host === 'grok')
52
+ return command.includes('hq-hq-bridge.sh') ? 'old-dispatcher' : null;
53
+ if (host === 'codex') {
54
+ if (isAdapterEntry(entry, root))
55
+ return 'old-dispatcher';
56
+ return command.includes('hq-codex-hook-adapter.sh') ? 'old-dispatcher' : null;
57
+ }
58
+ return command.includes('master-hook.sh') || command.includes(masterHookPath(root)) || command.includes(shimPath(root)) ? 'old-dispatcher' : null;
59
+ }
60
+ const OLD_DISPATCHER = {
61
+ claude: 'old dispatcher (master-hook.sh)',
62
+ codex: 'old dispatcher (Codex hook adapter)',
63
+ grok: 'old dispatcher (Grok bash bridge)',
64
+ };
65
+ function label(kind, host) {
66
+ if (kind === 'new-core')
67
+ return 'new core (hq-hook run)';
68
+ if (kind === 'launcher')
69
+ return 'old dispatcher through the pinned hq-hook launcher';
70
+ return OLD_DISPATCHER[host];
71
+ }
72
+ /**
73
+ * The engine path a new-core entry runs: the command itself in exec form, or
74
+ * the first single-quoted word of a command string (POSIX or PowerShell form).
75
+ */
76
+ function enginePathOf(entries, host, root) {
77
+ const entry = entries.find((e) => classifyEntry(e, host, root) === 'new-core');
78
+ const command = entry?.command;
79
+ if (typeof command !== 'string')
80
+ return undefined;
81
+ if (Array.isArray(entry.args))
82
+ return command;
83
+ const quoted = command.match(/^(?:& )?'((?:[^']|'\\'')*)'/)?.[1];
84
+ return quoted?.replace(/'\\''/g, "'");
85
+ }
86
+ const RANK = { PASS: 0, WARN: 1, FAIL: 2 };
87
+ /** The stable engine path for this platform (what a new-core registration names). */
88
+ function defaultStableEngine(home, platform) {
89
+ const binary = platform === 'darwin' ? path.join('hq-hook.app', 'Contents', 'MacOS', 'hq-hook') : 'hq-hook';
90
+ return path.join(home, '.hq', 'bin', 'hq-hook', STABLE_LINK_NAME, binary);
91
+ }
92
+ /**
93
+ * One result per registration file, with each event's core and the reason
94
+ * for it. An event registered to the new core passes only when its engine
95
+ * runs and has every evaluator the event needs; a missing or dangling engine
96
+ * link, an engine that does not run, or a missing evaluator is FAIL with the
97
+ * fix. With the flag on, an event left on the old dispatcher says why.
98
+ */
99
+ export function hostCoreResults(root, options = {}) {
100
+ const env = options.env ?? process.env;
101
+ const home = options.home ?? env.HOME ?? os.homedir();
102
+ const platform = options.platform ?? process.platform;
103
+ const probe = options.probe ?? probeEngine;
104
+ const flagOn = coreNextEnabled(env);
105
+ const probed = new Map();
106
+ const capabilities = (engine) => {
107
+ let found = probed.get(engine);
108
+ if (!found) {
109
+ try {
110
+ found = probe(engine);
111
+ }
112
+ catch (error) {
113
+ found = error;
114
+ }
115
+ probed.set(engine, found);
116
+ }
117
+ return found;
118
+ };
119
+ const newCore = (event, engine) => {
120
+ if (!engine)
121
+ return { status: 'FAIL', reason: 'the registration names no engine path' };
122
+ try {
123
+ fs.realpathSync(engine);
124
+ }
125
+ catch {
126
+ return { status: 'FAIL', reason: `${engine} does not resolve (missing or dangling ${STABLE_LINK_NAME} link), so this event has no hook running` };
127
+ }
128
+ const caps = capabilities(engine);
129
+ if (caps instanceof Error)
130
+ return { status: 'FAIL', reason: `the engine does not run (${caps.message})` };
131
+ const missing = missingEvaluators(caps, event);
132
+ if (missing === null)
133
+ return { status: 'FAIL', reason: 'no new-core port of the old hooks for this event' };
134
+ if (missing.length > 0)
135
+ return { status: 'FAIL', reason: `the new core lacks ${missing.join(', ')}` };
136
+ return { status: 'PASS', reason: `the new core has ${REQUIRED_EVALUATORS[event].join(', ')}` };
137
+ };
138
+ const oldCore = (event) => {
139
+ if (!flagOn)
140
+ return { status: 'PASS', reason: `flag ${CORE_NEXT_FLAG} is off` };
141
+ if (platform === 'win32')
142
+ return { status: 'PASS', reason: 'Windows keeps the old registration until US-022' };
143
+ if (!REQUIRED_EVALUATORS[event])
144
+ return { status: 'PASS', reason: 'no new-core port of the old hooks for this event yet' };
145
+ const caps = capabilities(defaultStableEngine(home, platform));
146
+ if (caps instanceof Error)
147
+ return { status: 'PASS', reason: `the new core is not available (${caps.message})` };
148
+ const missing = missingEvaluators(caps, event);
149
+ if (missing.length > 0)
150
+ return { status: 'PASS', reason: `the new core lacks ${missing.join(', ')}` };
151
+ return { status: 'WARN', reason: 'the new core can take this event; run hq reindex to switch it' };
152
+ };
153
+ const results = [];
154
+ for (const target of hostRegistrationFiles(root, home, env)) {
155
+ const checkId = `host-core:${target.host}-${target.scope}`;
156
+ let text;
157
+ try {
158
+ text = fs.readFileSync(target.file, 'utf8');
159
+ }
160
+ catch {
161
+ results.push({ status: 'NA', checkId, target: target.file, message: `${target.host} (${target.scope}): no registration file` });
162
+ continue;
163
+ }
164
+ let doc;
165
+ try {
166
+ doc = jsonFormat.parse(text);
167
+ }
168
+ catch {
169
+ results.push({ status: 'WARN', checkId, target: target.file, message: `${target.host} (${target.scope}): registration file is not valid JSON` });
170
+ continue;
171
+ }
172
+ const events = [];
173
+ const mixed = [];
174
+ for (const [event, entries] of eventEntries(doc)) {
175
+ const kinds = [...new Set(entries.map((entry) => classifyEntry(entry, target.host, root)).filter((k) => k !== null))];
176
+ if (kinds.length === 0)
177
+ continue;
178
+ if (kinds.length > 1) {
179
+ mixed.push(event);
180
+ events.push({ event, core: kinds.includes('new-core') ? 'new-core' : kinds[0], status: 'WARN', reason: `two HQ registrations: ${kinds.map((k) => label(k, target.host)).join(', ')}` });
181
+ continue;
182
+ }
183
+ const core = kinds[0];
184
+ events.push({ event, core, ...(core === 'new-core' ? newCore(event, enginePathOf(entries, target.host, root)) : oldCore(event)) });
185
+ }
186
+ if (events.length === 0) {
187
+ results.push({ status: 'NA', checkId, target: target.file, message: `${target.host} (${target.scope}): no HQ hook registered` });
188
+ continue;
189
+ }
190
+ const status = events.reduce((worst, e) => (RANK[e.status] > RANK[worst] ? e.status : worst), 'PASS');
191
+ // Events grouped by core and reason, in file order: "<core> for A, B (reason)".
192
+ const groups = new Map();
193
+ for (const e of events) {
194
+ const key = `${label(e.core, target.host)}\u0000${e.reason}`;
195
+ groups.set(key, [...(groups.get(key) ?? []), e.event]);
196
+ }
197
+ const summary = [...groups].map(([key, names]) => {
198
+ const [label, reason] = key.split('\u0000');
199
+ return `${label} for ${names.join(', ')} (${reason})`;
200
+ }).join('; ');
201
+ const cores = [...new Set(events.map((e) => e.core))];
202
+ const failed = events.filter((e) => e.status === 'FAIL').map((e) => e.event);
203
+ results.push({
204
+ status,
205
+ checkId,
206
+ target: target.file,
207
+ message: `${target.host} (${target.scope}): ${summary}`,
208
+ details: { ...(cores.length === 1 ? { core: cores[0] } : {}), cores, events },
209
+ ...(failed.length > 0
210
+ ? { remediation: `Run hq reindex: it puts ${failed.join(', ')} back on the old dispatcher when the new core cannot take them, or repairs the ${STABLE_LINK_NAME} link. Until then those events run no HQ hook, or a new core without their guards.` }
211
+ : mixed.length > 0
212
+ ? { remediation: 'Run hq reindex to leave one HQ registration per event.' }
213
+ : {}),
214
+ });
215
+ }
216
+ return results;
217
+ }
218
+ /** HQ-relevant entries per event, in file order. */
219
+ function eventEntries(doc) {
220
+ const hooks = doc?.hooks;
221
+ if (!hooks || typeof hooks !== 'object' || Array.isArray(hooks))
222
+ return [];
223
+ return Object.entries(hooks).map(([event, groups]) => [event, hookEntries({ hooks: { [event]: groups } })]);
224
+ }
225
+ /** Flag and kill-switch state, shown once. */
226
+ export function coreSwitchResult(options = {}) {
227
+ const env = options.env ?? process.env;
228
+ const home = options.home ?? env.HOME ?? os.homedir();
229
+ const on = coreNextEnabled(env);
230
+ const killedBy = [
231
+ /^(off|0|false|no)$/i.test((env[CORE_NEXT_KILL_ENV] ?? '').trim()) ? `${CORE_NEXT_KILL_ENV}=${env[CORE_NEXT_KILL_ENV]}` : '',
232
+ /^off$/i.test((env[ENGINE_KILL_ENV] ?? '').trim()) ? `${ENGINE_KILL_ENV}=${env[ENGINE_KILL_ENV]}` : '',
233
+ exists(path.join(home, CORE_NEXT_KILL_FILE)) ? path.join(home, CORE_NEXT_KILL_FILE) : '',
234
+ exists(path.join(home, ENGINE_KILL_FILE)) ? path.join(home, ENGINE_KILL_FILE) : '',
235
+ ].filter(Boolean);
236
+ const flag = `flag ${CORE_NEXT_FLAG} is ${on ? 'on' : 'off'}`;
237
+ const kill = killedBy.length
238
+ ? `; kill switch on (${killedBy.join(', ')}): new-core registrations hand each event to the old dispatcher`
239
+ : '';
240
+ return { status: 'PASS', checkId: 'host-core:switch', message: `${flag}${kill}`, details: { flag: on, killSwitch: killedBy } };
241
+ }
242
+ function exists(file) {
243
+ try {
244
+ fs.lstatSync(file);
245
+ return true;
246
+ }
247
+ catch {
248
+ return false;
249
+ }
250
+ }
251
+ /** The family `hq doctor` prints. */
252
+ export async function hostCoreFamily(context, options = {}) {
253
+ return {
254
+ family: { id: HOST_CORE_FAMILY_ID, title: HOST_CORE_FAMILY_TITLE },
255
+ results: [coreSwitchResult(options), ...hostCoreResults(context.hqRoot, options)],
256
+ };
257
+ }
258
+ /**
259
+ * The one call `hq doctor` makes on a run without `--only`: when the hook
260
+ * wiring family ran, add this family right after it. Registries without it
261
+ * (tests that register their own families) are left as they are.
262
+ */
263
+ export async function addHostCoreFamily(families, registry, context, options = {}) {
264
+ if (!registry.has(HOOKS_FAMILY_ID))
265
+ return;
266
+ const hooks = families.findIndex((run) => run.family.id === HOOKS_FAMILY_ID);
267
+ families.splice(hooks + 1, 0, await hostCoreFamily(context, options));
268
+ }
269
+ //# sourceMappingURL=host-core.js.map
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Replay recorder: is it on, and how much does it hold?
3
+ *
4
+ * The recorder (`hq-hook record`, crates/hq-hook/src/recorder.rs) appends
5
+ * redacted hook events to `~/.hq/replay-recorder/` when the flag
6
+ * `core.replay-recorder` is on for the person or machine. It is off by default.
7
+ * This check reads the same three inputs the recorder reads (the kill switch
8
+ * variable, the kill switch file and the cached person flag snapshot) and the
9
+ * size of the store. It starts no process and makes no network call.
10
+ */
11
+ import type { CheckFamily, CheckResult } from "../types.js";
12
+ export declare const REPLAY_RECORDER_FLAG = "core.replay-recorder";
13
+ export declare const REPLAY_RECORDER_KILL_ENV = "HQ_REPLAY_RECORDER";
14
+ export declare const REPLAY_RECORDER_MAX_BYTES_ENV = "HQ_REPLAY_RECORDER_MAX_BYTES";
15
+ export interface ReplayRecorderProbe {
16
+ env?: NodeJS.ProcessEnv;
17
+ /** Home directory. Default: `os.homedir()`. */
18
+ home?: string;
19
+ /** Clock in epoch milliseconds. Default: `Date.now()`. */
20
+ now?: number;
21
+ /** Temporary folder that holds the permission-fallback snapshot. Default: `os.tmpdir()`. */
22
+ tmpdir?: string;
23
+ /** Operating system. Default: `process.platform`. */
24
+ platform?: NodeJS.Platform;
25
+ }
26
+ export type ReplayRecorderOffReason = "kill-switch-env" | "kill-switch-file" | "flag-off" | "store-inside-repo" | "store-not-private" | "off-on-windows";
27
+ /** `HQ_REPLAY_RECORDER` values that turn recording off, in any case. Mirrors `recorder::KILL_SWITCH_VALUES`. */
28
+ export declare const REPLAY_RECORDER_KILL_VALUES: readonly string[];
29
+ export interface ReplayRecorderStore {
30
+ segments: number;
31
+ bytes: number;
32
+ }
33
+ /** Why the recorder is off, or `null` when it is recording. Mirrors `recorder::gate`. */
34
+ export declare function replayRecorderOffReason(probe?: ReplayRecorderProbe): ReplayRecorderOffReason | null;
35
+ /** Segment count and total size of the store. An absent store holds nothing. */
36
+ export declare function readReplayRecorderStore(home?: string): ReplayRecorderStore;
37
+ export declare function checkReplayRecorder(probe?: ReplayRecorderProbe): CheckResult;
38
+ export declare const replayRecorderFamily: CheckFamily;
39
+ //# sourceMappingURL=replay-recorder.d.ts.map
@@ -0,0 +1,261 @@
1
+ /**
2
+ * Replay recorder: is it on, and how much does it hold?
3
+ *
4
+ * The recorder (`hq-hook record`, crates/hq-hook/src/recorder.rs) appends
5
+ * redacted hook events to `~/.hq/replay-recorder/` when the flag
6
+ * `core.replay-recorder` is on for the person or machine. It is off by default.
7
+ * This check reads the same three inputs the recorder reads (the kill switch
8
+ * variable, the kill switch file and the cached person flag snapshot) and the
9
+ * size of the store. It starts no process and makes no network call.
10
+ */
11
+ import * as fs from "node:fs";
12
+ import * as os from "node:os";
13
+ import * as path from "node:path";
14
+ import { FLAG_SNAPSHOT_MAX_AGE_MS } from "../../flag-snapshot-file.js";
15
+ export const REPLAY_RECORDER_FLAG = "core.replay-recorder";
16
+ export const REPLAY_RECORDER_KILL_ENV = "HQ_REPLAY_RECORDER";
17
+ export const REPLAY_RECORDER_MAX_BYTES_ENV = "HQ_REPLAY_RECORDER_MAX_BYTES";
18
+ const CHECK_ID = "replay-recorder.state";
19
+ const STORE_DISPLAY = "~/.hq/replay-recorder";
20
+ const DEFAULT_MAX_BYTES = 64 * 1024 * 1024;
21
+ const MIN_MAX_BYTES = 8 * 1024;
22
+ const MAX_MAX_BYTES = 1024 * 1024 * 1024;
23
+ /** `HQ_REPLAY_RECORDER` values that turn recording off, in any case. Mirrors `recorder::KILL_SWITCH_VALUES`. */
24
+ export const REPLAY_RECORDER_KILL_VALUES = ["off", "0", "false", "no", "disabled"];
25
+ function storeDir(home) {
26
+ return path.join(home, ".hq", "replay-recorder");
27
+ }
28
+ /** One snapshot file, when it is for the person scope and fresh. */
29
+ function readPersonSnapshot(file, now) {
30
+ let parsed;
31
+ try {
32
+ parsed = JSON.parse(fs.readFileSync(file, "utf8"));
33
+ }
34
+ catch {
35
+ return null;
36
+ }
37
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
38
+ return null;
39
+ const value = parsed;
40
+ if (Object.keys(value).sort().join(",") !== "fetched_at,flags,scope" || value.scope !== "person")
41
+ return null;
42
+ if (typeof value.fetched_at !== "string")
43
+ return null;
44
+ const fetchedAt = Date.parse(value.fetched_at);
45
+ const age = now - fetchedAt;
46
+ if (!Number.isFinite(age) || age < 0 || age > FLAG_SNAPSHOT_MAX_AGE_MS)
47
+ return null;
48
+ const flags = value.flags;
49
+ if (!flags || typeof flags !== "object" || Array.isArray(flags))
50
+ return null;
51
+ return { fetchedAt, flags: flags };
52
+ }
53
+ /**
54
+ * The snapshot the CLI writes in its private temporary folder when it cannot
55
+ * write the cache folder (`fallbackPersonSnapshotPath` in
56
+ * `flag-snapshot-file.ts`). Only a folder chain this user owns and nobody else
57
+ * can enter is read.
58
+ */
59
+ function fallbackPersonSnapshotFile(tmpdir) {
60
+ if (typeof process.getuid !== "function")
61
+ return null;
62
+ const uid = process.getuid();
63
+ const root = path.join(tmpdir, `hq-cli-flag-snapshots-${uid}`);
64
+ const directories = [root, path.join(root, "hq"), path.join(root, "hq", "flags")];
65
+ for (const directory of directories) {
66
+ try {
67
+ const stat = fs.lstatSync(directory);
68
+ if (!stat.isDirectory() || stat.isSymbolicLink() || stat.uid !== uid)
69
+ return null;
70
+ if ((stat.mode & 0o077) !== 0)
71
+ return null;
72
+ }
73
+ catch {
74
+ return null;
75
+ }
76
+ }
77
+ return path.join(root, "hq", "flags", "snapshot-person.json");
78
+ }
79
+ /**
80
+ * Same rule as `flags::person_flag_enabled` in the engine: the newer valid one
81
+ * of the cache snapshot and the permission-fallback snapshot decides, and the
82
+ * flag is on only as the boolean `true`. Equal timestamps keep the cache file.
83
+ */
84
+ function personFlagOn(home, env, now, tmpdir) {
85
+ const cacheHome = env.XDG_CACHE_HOME || path.join(home, ".cache");
86
+ const primary = readPersonSnapshot(path.join(cacheHome, "hq", "flags", "snapshot-person.json"), now);
87
+ const fallbackFile = fallbackPersonSnapshotFile(tmpdir);
88
+ const fallback = fallbackFile ? readPersonSnapshot(fallbackFile, now) : null;
89
+ const chosen = primary && fallback ? (fallback.fetchedAt > primary.fetchedAt ? fallback : primary) : (primary ?? fallback);
90
+ return chosen?.flags[REPLAY_RECORDER_FLAG] === true;
91
+ }
92
+ function hasRepoOrHqMarkerAbove(directory) {
93
+ let current = directory;
94
+ for (;;) {
95
+ if (fs.existsSync(path.join(current, ".git")))
96
+ return true;
97
+ try {
98
+ if (fs.statSync(path.join(current, "core", "core.yaml")).isFile())
99
+ return true;
100
+ }
101
+ catch {
102
+ // No HQ root marker at this level.
103
+ }
104
+ const parent = path.dirname(current);
105
+ if (parent === current)
106
+ return false;
107
+ current = parent;
108
+ }
109
+ }
110
+ /**
111
+ * The store path as written, and where it really is: a symlinked parent
112
+ * (`~/.hq` pointing into a checkout) hides the checkout from a walk over the
113
+ * written path, so the nearest ancestor that exists is resolved and walked too.
114
+ */
115
+ function insideRepoOrHqTree(directory) {
116
+ if (hasRepoOrHqMarkerAbove(directory))
117
+ return true;
118
+ let current = path.dirname(directory);
119
+ for (;;) {
120
+ try {
121
+ return hasRepoOrHqMarkerAbove(fs.realpathSync(current));
122
+ }
123
+ catch {
124
+ // This ancestor does not exist yet; try the one above it.
125
+ }
126
+ const parent = path.dirname(current);
127
+ if (parent === current)
128
+ return false;
129
+ current = parent;
130
+ }
131
+ }
132
+ /** Why the recorder is off, or `null` when it is recording. Mirrors `recorder::gate`. */
133
+ export function replayRecorderOffReason(probe = {}) {
134
+ const env = probe.env ?? process.env;
135
+ const home = probe.home ?? os.homedir();
136
+ if (REPLAY_RECORDER_KILL_VALUES.includes((env[REPLAY_RECORDER_KILL_ENV] ?? "").trim().toLowerCase())) {
137
+ return "kill-switch-env";
138
+ }
139
+ // The recorder records only on Unix until US-022, whatever the flag says.
140
+ if ((probe.platform ?? process.platform) === "win32")
141
+ return "off-on-windows";
142
+ if (fs.existsSync(path.join(home, ".hq", "replay-recorder.off")))
143
+ return "kill-switch-file";
144
+ if (!personFlagOn(home, env, probe.now ?? Date.now(), probe.tmpdir ?? os.tmpdir()))
145
+ return "flag-off";
146
+ if (insideRepoOrHqTree(storeDir(home)))
147
+ return "store-inside-repo";
148
+ if (storeDirNotPrivate(storeDir(home)))
149
+ return "store-not-private";
150
+ return null;
151
+ }
152
+ /**
153
+ * An existing store folder owned by another user, or one group or others can
154
+ * write to. The recorder refuses it and leaves its permissions as they are.
155
+ * Unix only, as in the recorder.
156
+ */
157
+ function storeDirNotPrivate(store) {
158
+ if (typeof process.getuid !== "function")
159
+ return false;
160
+ let stat;
161
+ try {
162
+ stat = fs.lstatSync(store);
163
+ }
164
+ catch {
165
+ return false;
166
+ }
167
+ return stat.isDirectory() && (stat.uid !== process.getuid() || (stat.mode & 0o022) !== 0);
168
+ }
169
+ /** Segment count and total size of the store. An absent store holds nothing. */
170
+ export function readReplayRecorderStore(home = os.homedir()) {
171
+ const store = { segments: 0, bytes: 0 };
172
+ let names;
173
+ try {
174
+ names = fs.readdirSync(storeDir(home));
175
+ }
176
+ catch {
177
+ return store;
178
+ }
179
+ for (const name of names) {
180
+ if (!/^segment-\d+\.jsonl$/.test(name))
181
+ continue;
182
+ try {
183
+ const stat = fs.statSync(path.join(storeDir(home), name));
184
+ if (!stat.isFile())
185
+ continue;
186
+ store.segments += 1;
187
+ store.bytes += stat.size;
188
+ }
189
+ catch {
190
+ // A segment removed by a rotation while this check ran.
191
+ }
192
+ }
193
+ return store;
194
+ }
195
+ function capBytes(env) {
196
+ const raw = (env[REPLAY_RECORDER_MAX_BYTES_ENV] ?? "").trim();
197
+ if (!/^\d+$/.test(raw))
198
+ return DEFAULT_MAX_BYTES;
199
+ return Math.min(MAX_MAX_BYTES, Math.max(MIN_MAX_BYTES, Number(raw)));
200
+ }
201
+ function megabytes(bytes) {
202
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
203
+ }
204
+ const OFF_TEXT = {
205
+ "kill-switch-env": `${REPLAY_RECORDER_KILL_ENV} is set to turn it off`,
206
+ "kill-switch-file": "~/.hq/replay-recorder.off exists",
207
+ "flag-off": `flag ${REPLAY_RECORDER_FLAG} is not on for this person or machine`,
208
+ "store-inside-repo": "the home directory, or the folder ~/.hq links to, is inside a git checkout or an HQ tree",
209
+ "store-not-private": `${STORE_DISPLAY} is owned by another user or writable by group or others`,
210
+ "off-on-windows": "off on Windows until US-022",
211
+ };
212
+ export function checkReplayRecorder(probe = {}) {
213
+ const env = probe.env ?? process.env;
214
+ const home = probe.home ?? os.homedir();
215
+ const reason = replayRecorderOffReason({ ...probe, env, home });
216
+ const store = readReplayRecorderStore(home);
217
+ const cap = capBytes(env);
218
+ const holds = store.segments === 0
219
+ ? "It holds nothing."
220
+ : `It holds ${store.segments} segment${store.segments === 1 ? "" : "s"}, ${megabytes(store.bytes)} of a ${megabytes(cap)} cap.`;
221
+ const details = {
222
+ enabled: reason === null,
223
+ reason: reason ?? "on",
224
+ segments: store.segments,
225
+ bytes: store.bytes,
226
+ capBytes: cap,
227
+ };
228
+ if (reason === null) {
229
+ return {
230
+ checkId: CHECK_ID,
231
+ status: "WARN",
232
+ target: STORE_DISPLAY,
233
+ message: `Replay recorder is on: hook events on this machine are redacted and recorded to ${STORE_DISPLAY}. ${holds}`,
234
+ details,
235
+ remediation: `To stop recording, set ${REPLAY_RECORDER_KILL_ENV}=off or create ~/.hq/replay-recorder.off. Delete ${STORE_DISPLAY} to remove what it holds.`,
236
+ };
237
+ }
238
+ if (store.segments > 0) {
239
+ return {
240
+ checkId: CHECK_ID,
241
+ status: "WARN",
242
+ target: STORE_DISPLAY,
243
+ message: `Replay recorder is off (${OFF_TEXT[reason]}), but an earlier recording is still on disk. ${holds}`,
244
+ details,
245
+ remediation: `Delete ${STORE_DISPLAY} when the recording is no longer needed.`,
246
+ };
247
+ }
248
+ return {
249
+ checkId: CHECK_ID,
250
+ status: "PASS",
251
+ target: STORE_DISPLAY,
252
+ message: `Replay recorder is off (${OFF_TEXT[reason]}). ${holds}`,
253
+ details,
254
+ };
255
+ }
256
+ export const replayRecorderFamily = {
257
+ id: "replay-recorder",
258
+ title: "Replay recorder",
259
+ run: async () => [checkReplayRecorder()],
260
+ };
261
+ //# sourceMappingURL=replay-recorder.js.map
@@ -32,6 +32,7 @@ import { releaseLinksFamily } from "./checks/release-links.js";
32
32
  import { cliPathFamily } from "./checks/cli-path.js";
33
33
  import { ps1ShimsFamily } from "./checks/ps1-shims.js";
34
34
  import { tempHomesFamily } from "./checks/temp-homes.js";
35
+ import { replayRecorderFamily } from "./checks/replay-recorder.js";
35
36
  import { fixtureCoverageFamily } from "./fixtures/discover.js";
36
37
  import { checkClaudeWiring } from "./checks/claude-wiring.js";
37
38
  /**
@@ -289,6 +290,9 @@ export function createDefaultRegistry() {
289
290
  // Idle tmp.* throwaway homes holding a Rust toolchain download. Dry-run
290
291
  // scan only; `hq doctor --sweep-temp-homes` is the delete path.
291
292
  registry.register(tempHomesFamily);
293
+ // Replay recorder (flag core.replay-recorder, off by default): whether hook
294
+ // events are being recorded on this machine and how much the store holds.
295
+ registry.register(replayRecorderFamily);
292
296
  return registry;
293
297
  }
294
298
  //# sourceMappingURL=registry.js.map