@indigoai-us/hq-cli 5.345.267 → 5.345.269

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 (52) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/README.md +12 -0
  3. package/contracts/host-canary-release.json +7 -7
  4. package/dist/commands/core-job-notify-native.d.ts +6 -0
  5. package/dist/commands/core-job-notify-native.js +64 -4
  6. package/dist/commands/core-jobs-native.js +3 -16
  7. package/dist/commands/install-global.js +54 -17
  8. package/dist/lib/daemon/machine-check-owner.js +1 -1
  9. package/dist/lib/daemon/machine-checks.d.ts +3 -11
  10. package/dist/lib/daemon/machine-checks.js +4 -15
  11. package/dist/lib/daemon/run.js +12 -0
  12. package/dist/lib/doctor/checks/codex-wiring.d.ts +4 -2
  13. package/dist/lib/doctor/checks/codex-wiring.js +70 -13
  14. package/dist/lib/doctor/checks/fleet-hook-core.d.ts +4 -4
  15. package/dist/lib/doctor/checks/fleet-hook-core.js +5 -10
  16. package/dist/lib/doctor/checks/grok-wiring.js +38 -0
  17. package/dist/lib/doctor/checks/hook-engine.js +0 -2
  18. package/dist/lib/doctor/checks/host-core.d.ts +1 -1
  19. package/dist/lib/doctor/checks/host-core.js +8 -38
  20. package/dist/lib/hook-engine/coverage.d.ts +10 -1
  21. package/dist/lib/hook-engine/coverage.js +63 -8
  22. package/dist/lib/hook-engine/fleet-registration.js +7 -4
  23. package/dist/lib/hook-engine/native-precompact-compatibility.json +7 -1
  24. package/dist/lib/hook-engine/native-stop-compatibility.json +30 -11
  25. package/dist/lib/hook-engine/reconcile.d.ts +10 -1
  26. package/dist/lib/hook-engine/reconcile.js +339 -42
  27. package/dist/lib/hook-engine/stable-gate.d.ts +43 -0
  28. package/dist/lib/hook-engine/stable-gate.js +276 -0
  29. package/dist/lib/hot-channels/fleet-complete.js +2 -2
  30. package/dist/lib/install/antigravity-targets.js +2 -1
  31. package/dist/lib/install/claude-targets.d.ts +6 -6
  32. package/dist/lib/install/claude-targets.js +13 -9
  33. package/dist/lib/install/codex-targets.d.ts +4 -4
  34. package/dist/lib/install/codex-targets.js +26 -16
  35. package/dist/lib/install/hook-target.d.ts +23 -2
  36. package/dist/lib/install/hook-target.js +89 -16
  37. package/dist/lib/outpost-identity-env.d.ts +18 -0
  38. package/dist/lib/outpost-identity-env.js +29 -0
  39. package/dist/lib/signals/steps/extract.js +46 -12
  40. package/dist/utils/core-next-kill.d.ts +2 -15
  41. package/dist/utils/core-next-kill.js +5 -36
  42. package/dist/utils/hook-engine-crash.d.ts +86 -0
  43. package/dist/utils/hook-engine-crash.js +325 -0
  44. package/dist/utils/hook-engine-rollup.d.ts +8 -3
  45. package/dist/utils/hook-engine-rollup.js +0 -1
  46. package/dist/utils/hook-trust.d.ts +2 -0
  47. package/dist/utils/hook-trust.js +156 -13
  48. package/dist/utils/host-registration.d.ts +158 -4
  49. package/dist/utils/host-registration.js +500 -17
  50. package/dist/utils/version-gate.d.ts +42 -4
  51. package/dist/utils/version-gate.js +84 -25
  52. package/package.json +7 -7
@@ -0,0 +1,325 @@
1
+ /**
2
+ * Prompt upload of hq-hook crash lines (decision 3.1).
3
+ *
4
+ * The Rust engine's panic hook (`crates/hq-hook/src/core_next/crash_report.rs`)
5
+ * appends one `kind: "panic"` line per crash to `~/.hq/logs/hook-engine.jsonl`.
6
+ * The daemon reads the tail of that log every few minutes and sends each new
7
+ * line as one `hook_engine_crash` event to `POST /v1/telemetry/events`, through
8
+ * the same signed-in client, consent read and `HQ_TELEMETRY` opt-out as the
9
+ * daily `hook_engine_failure_rollup` (`hook-engine-rollup.ts`). The rollup
10
+ * ignores `panic` lines, so nothing is counted twice.
11
+ *
12
+ * - Dedupe: every line carries a unique `id`. Ids already sent are kept in the
13
+ * state file, and the event's idempotency key is built from the id.
14
+ * - Rate limit: at most {@link HOOK_ENGINE_CRASH_MAX_PER_HOUR} events per
15
+ * rolling hour. Lines over the limit are not sent; their number rides on
16
+ * the next sent event as `suppressed`.
17
+ * - Nothing written before the uploader first saw consent (`sendFrom`), while
18
+ * `HQ_TELEMETRY=0` was set, while signed out, or while consent was declined
19
+ * is ever sent.
20
+ *
21
+ * Every property is checked against a closed shape; a line with anything else
22
+ * is skipped. The active-install denominator is `cli_session_started`, which
23
+ * already carries `properties.version` (`cli-telemetry.ts`).
24
+ */
25
+ import * as fs from "node:fs";
26
+ import * as path from "node:path";
27
+ import { HOOK_ENGINE_LOG_RELATIVE, defaultHookEngineRollupClient, engineVersion, } from "./hook-engine-rollup.js";
28
+ import { isCliTelemetryDisabled } from "./cli-telemetry.js";
29
+ import { readStoreFile, writeStoreFile } from "../lib/daemon/paths.js";
30
+ export const HOOK_ENGINE_CRASH_EVENT = "hook_engine_crash";
31
+ export const HOOK_ENGINE_CRASH_STATE_FILE = "hook-engine-crash.json";
32
+ /** How often the daemon looks for new crash lines. */
33
+ export const HOOK_ENGINE_CRASH_INTERVAL_MS = 5 * 60_000;
34
+ /** First look after the daemon starts. */
35
+ export const HOOK_ENGINE_CRASH_FIRST_DELAY_MS = 60_000;
36
+ /** Bytes read from the end of the log (and of `.1` when the log is shorter). */
37
+ export const HOOK_ENGINE_CRASH_TAIL_BYTES = 1024 * 1024;
38
+ /** Events sent per rolling hour, at most. */
39
+ export const HOOK_ENGINE_CRASH_MAX_PER_HOUR = 12;
40
+ /** Sent ids remembered for dedupe. */
41
+ export const HOOK_ENGINE_CRASH_MAX_SEEN = 512;
42
+ /** Lines older than this are never sent. */
43
+ export const HOOK_ENGINE_CRASH_LOOKBACK_MS = 7 * 86_400_000;
44
+ const HOUR_MS = 3_600_000;
45
+ const STATE_MAX_BYTES = 256 * 1024;
46
+ export const HOOK_ENGINE_CRASH_MESSAGE_CLASSES = new Set([
47
+ "non-string",
48
+ "unwrap-none",
49
+ "unwrap-err",
50
+ "index-out-of-bounds",
51
+ "slice-index",
52
+ "divide-by-zero",
53
+ "overflow",
54
+ "alloc",
55
+ "already-borrowed",
56
+ "poisoned",
57
+ "assertion",
58
+ "unimplemented",
59
+ "unreachable",
60
+ "other",
61
+ ]);
62
+ const ID_RE = /^[0-9a-f]{24}$/;
63
+ const SIGNATURE_RE = /^[0-9a-f]{16}$/;
64
+ const PLATFORM_RE = /^[a-z0-9_]{1,16}$/;
65
+ const LOCATION_RE = /^(?:[A-Za-z0-9/._-]{1,160}:\d{1,7}|unknown)$/;
66
+ const APP_VERSION_RE = /^\d{1,6}\.\d{1,6}\.\d{1,6}(?:-[0-9A-Za-z.-]{1,40})?$/;
67
+ const SUBJECT_RE = /^[a-z0-9:-]{1,80}$/;
68
+ const MAX_SUPPRESSED = 1_000_000;
69
+ function safeInteger(value, min, max) {
70
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= min && value <= max ? value : undefined;
71
+ }
72
+ function readState(file) {
73
+ const read = readStoreFile(file, STATE_MAX_BYTES);
74
+ if (!read)
75
+ return null;
76
+ try {
77
+ const raw = JSON.parse(read.text);
78
+ if (raw.version !== 1)
79
+ return null;
80
+ const state = { version: 1, seen: [], sentAt: [], suppressed: 0 };
81
+ if (typeof raw.subject === "string" && SUBJECT_RE.test(raw.subject))
82
+ state.subject = raw.subject;
83
+ const sendFrom = safeInteger(raw.sendFrom, 0, Number.MAX_SAFE_INTEGER);
84
+ if (sendFrom !== undefined)
85
+ state.sendFrom = sendFrom;
86
+ if (Array.isArray(raw.seen)) {
87
+ state.seen = raw.seen.filter((id) => typeof id === "string" && ID_RE.test(id)).slice(-HOOK_ENGINE_CRASH_MAX_SEEN);
88
+ }
89
+ if (Array.isArray(raw.sentAt)) {
90
+ state.sentAt = raw.sentAt
91
+ .filter((at) => safeInteger(at, 0, Number.MAX_SAFE_INTEGER) !== undefined)
92
+ .slice(-HOOK_ENGINE_CRASH_MAX_PER_HOUR);
93
+ }
94
+ state.suppressed = safeInteger(raw.suppressed, 0, MAX_SUPPRESSED) ?? 0;
95
+ return state;
96
+ }
97
+ catch {
98
+ return null;
99
+ }
100
+ }
101
+ function writeState(file, state) {
102
+ writeStoreFile(file, JSON.stringify(state), { create: true });
103
+ }
104
+ /** Closed-shape properties for one engine-log row, or null when it is not a valid crash line. */
105
+ export function classifyHookEngineCrashRow(row) {
106
+ if (row.kind !== "panic" || row.schema !== 1)
107
+ return null;
108
+ const at = typeof row.ts === "string" ? Date.parse(row.ts) : Number.NaN;
109
+ if (!Number.isFinite(at))
110
+ return null;
111
+ const { id, signature, location, message_class: messageClass, app_version: appVersion, os, arch } = row;
112
+ if (typeof id !== "string" || !ID_RE.test(id) ||
113
+ typeof signature !== "string" || !SIGNATURE_RE.test(signature) ||
114
+ typeof location !== "string" || !LOCATION_RE.test(location) ||
115
+ typeof messageClass !== "string" || !HOOK_ENGINE_CRASH_MESSAGE_CLASSES.has(messageClass) ||
116
+ typeof appVersion !== "string" || !APP_VERSION_RE.test(appVersion) ||
117
+ typeof os !== "string" || !PLATFORM_RE.test(os) ||
118
+ typeof arch !== "string" || !PLATFORM_RE.test(arch)) {
119
+ return null;
120
+ }
121
+ const version = engineVersion(row.engine);
122
+ return {
123
+ at,
124
+ properties: {
125
+ crashId: id,
126
+ signature,
127
+ location,
128
+ messageClass,
129
+ appVersion,
130
+ engine: version.engine,
131
+ ...(version.release ? { release: version.release } : {}),
132
+ os,
133
+ arch,
134
+ },
135
+ };
136
+ }
137
+ function readTail(file, maxBytes) {
138
+ try {
139
+ const flags = process.platform === "win32" ? fs.constants.O_RDONLY : fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW;
140
+ const fd = fs.openSync(file, flags);
141
+ try {
142
+ const stat = fs.fstatSync(fd);
143
+ if (!stat.isFile())
144
+ return "";
145
+ const length = Math.min(stat.size, maxBytes);
146
+ if (length <= 0)
147
+ return "";
148
+ const buffer = Buffer.alloc(length);
149
+ let read = 0;
150
+ while (read < length) {
151
+ const n = fs.readSync(fd, buffer, read, length - read, stat.size - length + read);
152
+ if (n === 0)
153
+ break;
154
+ read += n;
155
+ }
156
+ const text = buffer.subarray(0, read).toString("utf8");
157
+ // A cut first line is not a whole record.
158
+ return length < stat.size ? text.slice(text.indexOf("\n") + 1) : text;
159
+ }
160
+ finally {
161
+ fs.closeSync(fd);
162
+ }
163
+ }
164
+ catch {
165
+ return "";
166
+ }
167
+ }
168
+ /** Valid crash lines in the tail of the engine log (and its rotated copy), oldest first. */
169
+ export function readHookEngineCrashLines(home, maxBytes = HOOK_ENGINE_CRASH_TAIL_BYTES) {
170
+ const logFile = path.join(home, HOOK_ENGINE_LOG_RELATIVE);
171
+ const current = readTail(logFile, maxBytes);
172
+ const left = maxBytes - Buffer.byteLength(current);
173
+ const rotated = left > 0 ? readTail(`${logFile}.1`, left) : "";
174
+ const lines = [];
175
+ const byId = new Set();
176
+ for (const text of [rotated, current]) {
177
+ for (const raw of text.split("\n")) {
178
+ if (!raw.includes("\"kind\":\"panic\""))
179
+ continue;
180
+ let parsed;
181
+ try {
182
+ parsed = JSON.parse(raw);
183
+ }
184
+ catch {
185
+ continue;
186
+ }
187
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
188
+ continue;
189
+ const line = classifyHookEngineCrashRow(parsed);
190
+ if (!line || byId.has(line.properties.crashId))
191
+ continue;
192
+ byId.add(line.properties.crashId);
193
+ lines.push(line);
194
+ }
195
+ }
196
+ return lines.sort((a, b) => a.at - b.at);
197
+ }
198
+ export function buildHookEngineCrashEvent(line, consentBasis, suppressed = 0) {
199
+ return {
200
+ eventName: HOOK_ENGINE_CRASH_EVENT,
201
+ app: "hq-cli",
202
+ source: "cli",
203
+ occurredAt: new Date(line.at).toISOString(),
204
+ consentBasis,
205
+ schemaVersion: 1,
206
+ idempotencyKey: `hook-engine-crash.${line.properties.crashId}`,
207
+ properties: suppressed > 0 ? { ...line.properties, suppressed } : { ...line.properties },
208
+ };
209
+ }
210
+ function restart(file, saved, now, subject) {
211
+ const kept = subject ?? saved?.subject;
212
+ writeState(file, {
213
+ version: 1,
214
+ ...(kept ? { subject: kept } : {}),
215
+ sendFrom: now,
216
+ seen: saved?.seen ?? [],
217
+ sentAt: saved?.sentAt ?? [],
218
+ suppressed: 0,
219
+ });
220
+ }
221
+ export async function runHookEngineCrashUpload(options) {
222
+ const env = options.env ?? process.env;
223
+ const now = (options.now ?? Date.now)();
224
+ const saved = readState(options.stateFile);
225
+ if (isCliTelemetryDisabled(env)) {
226
+ restart(options.stateFile, saved, now);
227
+ return { status: "disabled" };
228
+ }
229
+ const client = (options.client ?? (defaultHookEngineRollupClient))();
230
+ if (!client) {
231
+ restart(options.stateFile, saved, now);
232
+ return { status: "no-identity" };
233
+ }
234
+ const consent = await client.consent();
235
+ if (consent === "unknown")
236
+ return { status: "consent-unknown" };
237
+ if (consent === "no") {
238
+ restart(options.stateFile, saved, now, client.subject);
239
+ return { status: "not-consented" };
240
+ }
241
+ if (!saved || saved.sendFrom === undefined || saved.subject !== client.subject || saved.sendFrom > now) {
242
+ restart(options.stateFile, saved, now, client.subject);
243
+ return { status: "started" };
244
+ }
245
+ const seen = new Set(saved.seen);
246
+ const oldest = Math.max(saved.sendFrom, now - HOOK_ENGINE_CRASH_LOOKBACK_MS);
247
+ const fresh = readHookEngineCrashLines(options.home).filter((line) => line.at >= oldest && line.at <= now + 60_000 && !seen.has(line.properties.crashId));
248
+ if (fresh.length === 0)
249
+ return { status: "nothing-to-send" };
250
+ const sentAt = saved.sentAt.filter((at) => at > now - HOUR_MS && at <= now);
251
+ const room = Math.max(0, HOOK_ENGINE_CRASH_MAX_PER_HOUR - sentAt.length);
252
+ const toSend = fresh.slice(0, room);
253
+ const over = fresh.slice(room);
254
+ const remember = (ids) => [...saved.seen, ...ids].slice(-HOOK_ENGINE_CRASH_MAX_SEEN);
255
+ const suppressed = Math.min(saved.suppressed + over.length, MAX_SUPPRESSED);
256
+ if (toSend.length === 0) {
257
+ writeState(options.stateFile, { ...saved, sentAt, seen: remember(over.map((l) => l.properties.crashId)), suppressed });
258
+ return { status: "nothing-to-send" };
259
+ }
260
+ const consentBasis = client.consentBasis ?? "opted-in";
261
+ // The suppressed count rides on the first event sent.
262
+ const events = toSend.map((line, index) => buildHookEngineCrashEvent(line, consentBasis, index === 0 ? suppressed : 0));
263
+ const result = await client.post(events);
264
+ if (result === "retry")
265
+ return { status: "send-failed" };
266
+ const ids = [...toSend, ...over].map((line) => line.properties.crashId);
267
+ if (result === "rejected") {
268
+ writeState(options.stateFile, { ...saved, sentAt, seen: remember(ids), suppressed: 0 });
269
+ return { status: "rejected", events: events.length };
270
+ }
271
+ writeState(options.stateFile, {
272
+ ...saved,
273
+ sentAt: [...sentAt, ...toSend.map(() => now)].slice(-HOOK_ENGINE_CRASH_MAX_PER_HOUR),
274
+ seen: remember(ids),
275
+ suppressed: 0,
276
+ });
277
+ return { status: "sent", events: events.length, suppressed };
278
+ }
279
+ export function hookEngineCrashLogLine(result) {
280
+ if (result.status === "sent")
281
+ return { level: "info", message: `hook-engine crash reports sent ${result.events} events` };
282
+ if (result.status === "rejected")
283
+ return { level: "warn", message: `hook-engine crash reports rejected (${result.events} events)` };
284
+ if (result.status === "send-failed")
285
+ return { level: "warn", message: "hook-engine crash report send failed; it retries on a later tick" };
286
+ return null;
287
+ }
288
+ /** The daemon's crash-upload timer: first look after a minute, then every five. */
289
+ export function startHookEngineCrashSchedule(options) {
290
+ let closed = false;
291
+ let running = false;
292
+ const tick = async () => {
293
+ if (closed || running)
294
+ return;
295
+ running = true;
296
+ try {
297
+ const line = hookEngineCrashLogLine(await options.run());
298
+ if (line)
299
+ options.log(line.level, line.message);
300
+ }
301
+ catch (error) {
302
+ options.log("warn", `hook-engine crash upload failed (${error instanceof Error ? error.name : "UnknownError"})`);
303
+ }
304
+ finally {
305
+ running = false;
306
+ }
307
+ };
308
+ let repeat;
309
+ const first = setTimeout(() => {
310
+ void tick();
311
+ repeat = setInterval(() => void tick(), options.intervalMs ?? HOOK_ENGINE_CRASH_INTERVAL_MS);
312
+ repeat.unref?.();
313
+ }, options.firstDelayMs ?? HOOK_ENGINE_CRASH_FIRST_DELAY_MS);
314
+ first.unref?.();
315
+ return {
316
+ tick,
317
+ close() {
318
+ closed = true;
319
+ clearTimeout(first);
320
+ if (repeat)
321
+ clearInterval(repeat);
322
+ },
323
+ };
324
+ }
325
+ //# sourceMappingURL=hook-engine-crash.js.map
@@ -38,11 +38,16 @@ export interface HookEngineRollupEvent {
38
38
  export type HookEngineRollupConsentBasis = "opted-in" | "agent-required";
39
39
  export type HookEngineRollupConsent = "yes" | "no" | "unknown";
40
40
  export type HookEngineRollupPostResult = "ok" | "retry" | "rejected";
41
- export interface HookEngineRollupClient {
41
+ /**
42
+ * The signed-in identity, its telemetry consent and its `/v1/telemetry/events`
43
+ * post. `E` is the event shape it posts: the daily rollup by default, or the
44
+ * crash uploader's `hook_engine_crash` (`hook-engine-crash.ts`).
45
+ */
46
+ export interface HookEngineRollupClient<E = HookEngineRollupEvent> {
42
47
  subject: string;
43
48
  consentBasis?: HookEngineRollupConsentBasis;
44
49
  consent(): Promise<HookEngineRollupConsent>;
45
- post(events: readonly HookEngineRollupEvent[]): Promise<HookEngineRollupPostResult>;
50
+ post(events: readonly E[]): Promise<HookEngineRollupPostResult>;
46
51
  }
47
52
  export interface HookEngineRollupOptions {
48
53
  home: string;
@@ -86,7 +91,7 @@ export declare function buildHookEngineRollupEvents(groups: ReadonlyArray<{
86
91
  day: string;
87
92
  properties: HookEngineFailureProperties;
88
93
  }>, runId: string, consentBasis?: HookEngineRollupConsentBasis): HookEngineRollupEvent[];
89
- export declare function defaultHookEngineRollupClient(): HookEngineRollupClient | null;
94
+ export declare function defaultHookEngineRollupClient<E = HookEngineRollupEvent>(): HookEngineRollupClient<E> | null;
90
95
  export declare function hookEngineRollupLogLine(result: HookEngineRollupResult, previous: HookEngineRollupResult["status"] | undefined): {
91
96
  level: "info" | "warn";
92
97
  message: string;
@@ -22,7 +22,6 @@ const STATE_MAX_BYTES = 1024 * 1024;
22
22
  const MAX_EXCLUDED_STRETCHES = 64;
23
23
  const DAY_MS = 86_400_000;
24
24
  export const HOOK_ENGINE_SHIPPED_HOOK_IDS = new Set([
25
- "block-hq-grep",
26
25
  "enforce-vault-write-access",
27
26
  "block-numbered-policy-sibling",
28
27
  "block-agent-secrets-reveal",
@@ -34,6 +34,8 @@ export interface HookTrustDependencies {
34
34
  * flag `core.next`.
35
35
  */
36
36
  coreNextTarget?: (home: string) => CoreNextTarget | null;
37
+ /** Test seam for linking `<home>/.hq/bin/hq-hook/stable` on native-only roots. */
38
+ ensureStableEngine?: (home: string, platform: NodeJS.Platform) => string | null;
37
39
  /**
38
40
  * Reads the HQ `.codex` hook files exactly as the installed core release
39
41
  * ships them. Used only by the post-rescue re-trust; see
@@ -11,8 +11,11 @@ import { parse as parseToml } from 'smol-toml';
11
11
  import { acquireLock, atomicReplace, backupConfig, realpathOrSelf, releaseLock, restoreFromBackup, } from '../commands/mcp-registration.js';
12
12
  import { findExecutableOnPath } from './resolve-executable.js';
13
13
  import { loadShippedCodexHookFiles } from './shipped-codex-hooks.js';
14
- import { forHost } from '../lib/hook-engine/coverage.js';
15
- import { coreNextTargetOrWarn, grokBridgeJson, replaceFileNoFollow } from './host-registration.js';
14
+ import { forHost, isNativeOnlyCoreRoot } from '../lib/hook-engine/coverage.js';
15
+ import { isCoreNextEntry } from '../lib/hook-engine/registration.js';
16
+ import { detectMachineHookHosts, evaluateStableCommit } from '../lib/hook-engine/stable-gate.js';
17
+ import { HQ_CLI_NPM_REPAIR_COMMAND } from './npm-install-flags.js';
18
+ import { coreNextOffReason, coreNextTargetOrWarn, ensureStableHookEngine, getCoreNextCandidate, GROK_NATIVE_HOOK_EVENTS, grokBridgeJson, nativeGrokBridgeJson, portableGrokBridgeJson, replaceFileNoFollow, resolvePortableEngineForNativeOnly, STABLE_LINK_NAME } from './host-registration.js';
16
19
  import { planResolvedCommandSpawn } from './windows-spawn.js';
17
20
  /**
18
21
  * The home directory every runtime's config is resolved under.
@@ -688,7 +691,7 @@ function textMatches(file, text) {
688
691
  function tomlEscapeKey(value) {
689
692
  return value.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
690
693
  }
691
- function grokTrustIsCurrent(hqRoot, home, wantJson) {
694
+ function grokTrustIsCurrent(hqRoot, home, wantJson, requireBridgeSh = true) {
692
695
  const grokHome = path.join(home, '.grok');
693
696
  // The key is written TOML-escaped, so match the escaped form. On POSIX paths
694
697
  // (no backslash/quote) this is identical to the raw path.
@@ -714,7 +717,7 @@ function grokTrustIsCurrent(hqRoot, home, wantJson) {
714
717
  return (folderTrusted &&
715
718
  legacyTrusted &&
716
719
  claudeCompatQuiet &&
717
- filesMatch(path.join(sourceHooks, 'hq-grok-user-bridge.sh'), path.join(userHooks, 'hq-hq-bridge.sh')) &&
720
+ (!requireBridgeSh || filesMatch(path.join(sourceHooks, 'hq-grok-user-bridge.sh'), path.join(userHooks, 'hq-hq-bridge.sh'))) &&
718
721
  (wantJson === undefined
719
722
  ? filesMatch(path.join(sourceHooks, 'hq-grok-user-bridge.json'), path.join(userHooks, 'hq-hq-bridge.json'))
720
723
  : textMatches(path.join(userHooks, 'hq-hq-bridge.json'), wantJson)));
@@ -822,15 +825,156 @@ export function trustGrokProjectHooks(hqRoot, deps = DEFAULT_DEPS) {
822
825
  const sourceHooks = path.join(hqRoot, '.grok', 'hooks');
823
826
  const sourceBridgeSh = path.join(sourceHooks, 'hq-grok-user-bridge.sh');
824
827
  const sourceBridgeJson = path.join(sourceHooks, 'hq-grok-user-bridge.json');
825
- if (!fs.existsSync(sourceBridgeSh) || !fs.existsSync(sourceBridgeJson)) {
826
- return {
827
- runtime: 'grok',
828
- status: 'skipped',
829
- trusted: 0,
830
- reason: 'project .grok bridge sources absent',
831
- };
832
- }
828
+ const legacySourcesPresent = fs.existsSync(sourceBridgeSh) && fs.existsSync(sourceBridgeJson);
833
829
  const home = deps.homeDir?.() ?? process.env.HOME ?? os.homedir();
830
+ const platform = deps.platform ?? process.platform;
831
+ const nativeOnly = isNativeOnlyCoreRoot(hqRoot);
832
+ if (nativeOnly || !legacySourcesPresent) {
833
+ // Post-US-027 native-only root: `.grok/hooks/hq-grok-user-bridge.{sh,json}`
834
+ // were removed (or left behind by rescue before cleanup), so synthesize
835
+ // `~/.grok/hooks/hq-hq-bridge.json` directly for `hq-hook run --host grok`.
836
+ if (!nativeOnly && !fs.existsSync(path.join(hqRoot, '.grok'))) {
837
+ return {
838
+ runtime: 'grok',
839
+ status: 'skipped',
840
+ trusted: 0,
841
+ reason: 'project .grok bridge sources absent',
842
+ };
843
+ }
844
+ let target;
845
+ let grok;
846
+ try {
847
+ target = (deps.coreNextTarget ?? ((h) => coreNextTargetOrWarn(h, process.env, { platform, deferLink: nativeOnly })))(home);
848
+ }
849
+ catch (error) {
850
+ return { runtime: 'grok', status: 'failed', trusted: 0, reason: errorMessage(error) };
851
+ }
852
+ const candidate = getCoreNextCandidate(target);
853
+ let refusedHosts;
854
+ let checkedHosts;
855
+ let acceptedHosts = ['grok'];
856
+ if (nativeOnly && target && candidate?.commitStable) {
857
+ const decision = evaluateStableCommit({
858
+ rawCoreNext: target,
859
+ root: hqRoot,
860
+ home,
861
+ env: process.env,
862
+ engineVersion: candidate.engineVersion,
863
+ requiredHosts: ['grok'],
864
+ });
865
+ if (decision.allowed && decision.targets.grok && decision.targets.grok.events.length > 0) {
866
+ grok = decision.targets.grok;
867
+ acceptedHosts = decision.acceptedHosts;
868
+ }
869
+ else {
870
+ if (decision.refusalSummary)
871
+ process.stderr.write(`${decision.refusalSummary}\n`);
872
+ grok = null;
873
+ refusedHosts = decision.refusedHosts.length > 0 ? decision.refusedHosts : ['grok'];
874
+ checkedHosts = decision.checkedHosts;
875
+ }
876
+ }
877
+ else {
878
+ try {
879
+ grok = forHost(target, hqRoot, 'grok');
880
+ }
881
+ catch (error) {
882
+ return { runtime: 'grok', status: 'failed', trusted: 0, reason: errorMessage(error) };
883
+ }
884
+ }
885
+ let wantJson;
886
+ if (grok && grok.events.length > 0) {
887
+ try {
888
+ candidate?.commitStable?.(acceptedHosts);
889
+ }
890
+ catch (error) {
891
+ return { runtime: 'grok', status: 'failed', trusted: 0, reason: errorMessage(error) };
892
+ }
893
+ wantJson = nativeGrokBridgeJson(hqRoot, grok, platform);
894
+ }
895
+ else if (nativeOnly) {
896
+ const candidateRefused = target !== null || (!deps.coreNextTarget && coreNextOffReason(home, process.env, platform) === null);
897
+ let stable;
898
+ let refusalReason;
899
+ let keptPriorEngine = false;
900
+ if (candidateRefused) {
901
+ const machineHosts = checkedHosts ?? [...new Set(['grok', ...detectMachineHookHosts(hqRoot, home, process.env)])];
902
+ const resolution = resolvePortableEngineForNativeOnly(home, {
903
+ platform,
904
+ env: process.env,
905
+ host: refusedHosts?.[0] ?? 'grok',
906
+ root: hqRoot,
907
+ candidate: candidate
908
+ ? { ...candidate, refusedHosts, checkedHosts: machineHosts }
909
+ : (refusedHosts ? { refusedHosts, checkedHosts: machineHosts } : null),
910
+ requiredHosts: machineHosts,
911
+ });
912
+ stable = resolution.stable;
913
+ refusalReason = resolution.refusalReason;
914
+ keptPriorEngine = Boolean(resolution.keptPriorEngine);
915
+ }
916
+ else {
917
+ try {
918
+ stable = (deps.ensureStableEngine ?? ((h, p) => ensureStableHookEngine(h, { platform: p })))(home, platform);
919
+ }
920
+ catch (error) {
921
+ return { runtime: 'grok', status: 'failed', trusted: 0, reason: errorMessage(error) };
922
+ }
923
+ }
924
+ if (!stable) {
925
+ return {
926
+ runtime: 'grok',
927
+ status: 'failed',
928
+ trusted: 0,
929
+ reason: refusalReason ?? `native hook engine unavailable; cannot create ${path.join(home, '.hq', 'bin', 'hq-hook', STABLE_LINK_NAME)}. Repair: ${HQ_CLI_NPM_REPAIR_COMMAND}`,
930
+ };
931
+ }
932
+ // When keeping a previously accepted engine at `stable` after a refusal,
933
+ // preserve an already-written core.next bridge so it keeps running the
934
+ // prior `stable` engine without unnecessary churn.
935
+ const existingBridgePath = path.join(home, '.grok', 'hooks', 'hq-hq-bridge.json');
936
+ let preservedExisting = null;
937
+ if (keptPriorEngine && fs.existsSync(existingBridgePath)) {
938
+ try {
939
+ const existingText = fs.readFileSync(existingBridgePath, 'utf8');
940
+ const parsed = JSON.parse(existingText);
941
+ const hasAllCoreNext = Boolean(parsed.hooks
942
+ && GROK_NATIVE_HOOK_EVENTS.every((ev) => Array.isArray(parsed.hooks?.[ev])
943
+ && parsed.hooks[ev].some((g) => Array.isArray(g?.hooks) && g.hooks.some((h) => isCoreNextEntry(h, hqRoot)))));
944
+ if (hasAllCoreNext)
945
+ preservedExisting = existingText;
946
+ }
947
+ catch {
948
+ preservedExisting = null;
949
+ }
950
+ }
951
+ wantJson = preservedExisting ?? portableGrokBridgeJson(hqRoot, platform);
952
+ }
953
+ else {
954
+ return {
955
+ runtime: 'grok',
956
+ status: 'skipped',
957
+ trusted: 0,
958
+ reason: 'project .grok bridge sources absent',
959
+ };
960
+ }
961
+ if (grokTrustIsCurrent(hqRoot, home, wantJson, false)) {
962
+ return { runtime: 'grok', status: 'unchanged', trusted: 0 };
963
+ }
964
+ try {
965
+ const grokHome = path.join(home, '.grok');
966
+ const userHooks = path.join(grokHome, 'hooks');
967
+ fs.mkdirSync(userHooks, { recursive: true });
968
+ writeGrokFolderTrust(path.join(grokHome, 'trusted_folders.toml'), hqRoot);
969
+ writeGrokLegacyTrust(path.join(grokHome, 'trusted-hook-projects'), hqRoot);
970
+ quietGrokClaudeCompat(path.join(grokHome, 'config.toml'));
971
+ replaceFileNoFollow(path.join(userHooks, 'hq-hq-bridge.json'), wantJson, home);
972
+ return { runtime: 'grok', status: 'trusted', trusted: 1 };
973
+ }
974
+ catch (error) {
975
+ return { runtime: 'grok', status: 'failed', trusted: 0, reason: errorMessage(error) };
976
+ }
977
+ }
834
978
  // Flag `core.next` on: the user hook file calls the new core's entry point
835
979
  // (hq-core-rust US-017) for each event the engine has every guard for. Off,
836
980
  // when the engine is not available, or when the shipped file cannot be
@@ -841,7 +985,6 @@ export function trustGrokProjectHooks(hqRoot, deps = DEFAULT_DEPS) {
841
985
  const target = (deps.coreNextTarget ?? ((h) => coreNextTargetOrWarn(h)))(home);
842
986
  // Only the events the new core covers in full on Grok switch.
843
987
  const grok = forHost(target, hqRoot, 'grok');
844
- const platform = deps.platform ?? process.platform;
845
988
  wantJson = grok || platform === 'win32'
846
989
  ? grokBridgeJson(fs.readFileSync(sourceBridgeJson, 'utf8'), hqRoot, grok, platform, home)
847
990
  : undefined;