@indigoai-us/hq-cli 5.345.263 → 5.345.264

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 (62) hide show
  1. package/CHANGELOG.md +55 -0
  2. package/contracts/host-canary-release.json +7 -7
  3. package/dist/command-catalog.generated.d.ts +37 -0
  4. package/dist/command-catalog.generated.js +46 -0
  5. package/dist/command-registration-plan.d.ts +6 -0
  6. package/dist/command-registration-plan.js +1 -0
  7. package/dist/commands/bot.d.ts +2 -0
  8. package/dist/commands/bot.js +4 -3
  9. package/dist/commands/sync-held.d.ts +11 -0
  10. package/dist/commands/sync-held.js +65 -1
  11. package/dist/commands/sync-telemetry-report.d.ts +5 -0
  12. package/dist/commands/sync-telemetry-report.js +239 -0
  13. package/dist/commands/sync-telemetry.d.ts +47 -0
  14. package/dist/commands/sync-telemetry.js +309 -0
  15. package/dist/index.js +107 -43
  16. package/dist/lib/bot/runnable.d.ts +17 -7
  17. package/dist/lib/bot/runnable.js +17 -10
  18. package/dist/lib/capacity/available.js +6 -2
  19. package/dist/lib/capacity/collectors/claude-oauth.d.ts +10 -256
  20. package/dist/lib/capacity/collectors/claude-oauth.js +19 -1078
  21. package/dist/lib/capacity/ledger.d.ts +12 -1
  22. package/dist/lib/capacity/ledger.js +15 -5
  23. package/dist/lib/capacity/route.d.ts +2 -0
  24. package/dist/lib/capacity/route.js +21 -4
  25. package/dist/lib/capacity/scheduler.js +2 -3
  26. package/dist/lib/capacity/sign-in.js +4 -4
  27. package/dist/lib/daemon/ops/skill-command.d.ts +2 -0
  28. package/dist/lib/daemon/ops/skill-command.js +7 -1
  29. package/dist/lib/doctor/checks/antigravity-wiring.d.ts +2 -1
  30. package/dist/lib/doctor/checks/antigravity-wiring.js +59 -3
  31. package/dist/lib/doctor/checks/hook-engine.d.ts +2 -0
  32. package/dist/lib/doctor/checks/hook-engine.js +100 -1
  33. package/dist/lib/doctor/checks/host-core.d.ts +1 -1
  34. package/dist/lib/doctor/checks/host-core.js +11 -4
  35. package/dist/lib/hook-engine/coverage.d.ts +19 -10
  36. package/dist/lib/hook-engine/coverage.js +103 -24
  37. package/dist/lib/hook-engine/native-precompact-compatibility.json +7 -1
  38. package/dist/lib/hook-engine/native-stop-compatibility.json +8 -4
  39. package/dist/lib/hook-engine/reconcile.js +49 -1
  40. package/dist/lib/install/antigravity-targets.d.ts +22 -0
  41. package/dist/lib/install/antigravity-targets.js +82 -0
  42. package/dist/main.js +8 -3
  43. package/dist/sentry-init.d.ts +7 -1
  44. package/dist/sentry-init.js +6 -2
  45. package/dist/sentry.d.ts +7 -0
  46. package/dist/sentry.js +16 -1
  47. package/dist/started-version.d.ts +13 -0
  48. package/dist/started-version.js +34 -0
  49. package/dist/startup-registration.d.ts +9 -9
  50. package/dist/startup-registration.js +42 -18
  51. package/dist/utils/client-health.d.ts +1 -0
  52. package/dist/utils/client-health.js +54 -11
  53. package/dist/utils/core-next-kill.d.ts +9 -0
  54. package/dist/utils/core-next-kill.js +22 -0
  55. package/dist/utils/host-registration.d.ts +4 -2
  56. package/dist/utils/host-registration.js +55 -7
  57. package/dist/utils/install-tree-recovery-markers.d.ts +45 -0
  58. package/dist/utils/install-tree-recovery-markers.js +70 -0
  59. package/dist/utils/install-tree-torn.d.ts +102 -5
  60. package/dist/utils/install-tree-torn.js +199 -2
  61. package/dist/utils/sentry-fingerprint.js +3 -0
  62. package/package.json +7 -7
package/dist/sentry.d.ts CHANGED
@@ -24,8 +24,15 @@ export declare function epipeAwareBeforeSend(event: ErrorEvent, hint: EventHint)
24
24
  * exercised without an ingest request. Production callers pass nothing.
25
25
  */
26
26
  export declare function initSentry(overrides?: Partial<Pick<NodeOptions, "transport">>): void;
27
+ /** Initialize Sentry only if not already active; returns true when this call initialized it. */
28
+ export declare function ensureSentryInitialized(options?: {
29
+ startSession?: boolean;
30
+ transport?: NodeOptions["transport"];
31
+ }): boolean;
27
32
  /** Finish HQ's one per-invocation release-health session. */
28
33
  export declare function finishSentrySession(): void;
34
+ /** Discard any un-sent release-health session so a restarting parent does not double-count. */
35
+ export declare function discardSentrySession(): void;
29
36
  /** Close the Sentry transport's sockets after the run's final flush. */
30
37
  export declare function closeSentryTransport(): void;
31
38
  export {};
package/dist/sentry.js CHANGED
@@ -5,7 +5,7 @@ import { companySkillWrapperSentryTagsFor } from "./lib/company-skill-wrapper.js
5
5
  import { environmentalFsErrorMessage } from "./utils/environmental-error.js";
6
6
  import { incompleteInstallCaptureContext, incompleteInstallMessage, } from "./utils/incomplete-install-error.js";
7
7
  import { installTreeTornSentryTagsFor, sentryFingerprintFor, sentryMcpCollisionContextFor, } from "./utils/sentry-fingerprint.js";
8
- import { closeSentryRuntimeTransport, finishSentryRuntimeSession, initSentryRuntime, } from "./sentry-init.js";
8
+ import { closeSentryRuntimeTransport, discardSentryRuntimeSession, finishSentryRuntimeSession, initSentryRuntime, } from "./sentry-init.js";
9
9
  const inertSentryScope = {
10
10
  setTag: () => inertSentryScope,
11
11
  setUser: () => inertSentryScope,
@@ -228,10 +228,25 @@ export function initSentry(overrides = {}) {
228
228
  return;
229
229
  pendingSentryBreadcrumbs = [];
230
230
  }
231
+ /** Initialize Sentry only if not already active; returns true when this call initialized it. */
232
+ export function ensureSentryInitialized(options = {}) {
233
+ if (sentryModule)
234
+ return false;
235
+ const overrides = options.transport ? { transport: options.transport } : {};
236
+ sentryModule = initSentryRuntime(epipeAwareBeforeSend, overrides, pendingSentryBreadcrumbs, { startSession: options.startSession });
237
+ if (!sentryModule)
238
+ return false;
239
+ pendingSentryBreadcrumbs = [];
240
+ return true;
241
+ }
231
242
  /** Finish HQ's one per-invocation release-health session. */
232
243
  export function finishSentrySession() {
233
244
  finishSentryRuntimeSession();
234
245
  }
246
+ /** Discard any un-sent release-health session so a restarting parent does not double-count. */
247
+ export function discardSentrySession() {
248
+ discardSentryRuntimeSession();
249
+ }
235
250
  /** Close the Sentry transport's sockets after the run's final flush. */
236
251
  export function closeSentryTransport() {
237
252
  closeSentryRuntimeTransport();
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Read this install's version from `../package.json` synchronously, returning
3
+ * `undefined` if the manifest is missing, unreadable, malformed, or belongs to
4
+ * a different package. Never throws so startup cannot fail on a torn manifest.
5
+ */
6
+ export declare function readStartedCliVersion(moduleUrl?: string, readFile?: (filePath: string, encoding: "utf-8") => string): string | undefined;
7
+ /**
8
+ * CLI version captured synchronously when the process entrypoint loads, before
9
+ * any lazy or fast-path import can run. Used by mixed-install skew detection
10
+ * (HQ-CLI-HD) so an install swap before `cli-version.js` loads is still caught.
11
+ */
12
+ export declare const STARTED_CLI_VERSION: string | undefined;
13
+ //# sourceMappingURL=started-version.d.ts.map
@@ -0,0 +1,34 @@
1
+ import { readFileSync } from "node:fs";
2
+ import * as path from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ const CLI_PACKAGE_NAME = "@indigoai-us/hq-cli";
5
+ /**
6
+ * Read this install's version from `../package.json` synchronously, returning
7
+ * `undefined` if the manifest is missing, unreadable, malformed, or belongs to
8
+ * a different package. Never throws so startup cannot fail on a torn manifest.
9
+ */
10
+ export function readStartedCliVersion(moduleUrl = import.meta.url, readFile = readFileSync) {
11
+ try {
12
+ const here = path.dirname(fileURLToPath(moduleUrl));
13
+ const pkgPath = path.resolve(here, "..", "package.json");
14
+ const parsed = JSON.parse(readFile(pkgPath, "utf-8"));
15
+ if (!parsed || typeof parsed !== "object")
16
+ return undefined;
17
+ if (parsed.name !== CLI_PACKAGE_NAME)
18
+ return undefined;
19
+ if (typeof parsed.version !== "string")
20
+ return undefined;
21
+ const trimmed = parsed.version.trim();
22
+ return trimmed.length > 0 ? trimmed : undefined;
23
+ }
24
+ catch {
25
+ return undefined;
26
+ }
27
+ }
28
+ /**
29
+ * CLI version captured synchronously when the process entrypoint loads, before
30
+ * any lazy or fast-path import can run. Used by mixed-install skew detection
31
+ * (HQ-CLI-HD) so an install swap before `cli-version.js` loads is still caught.
32
+ */
33
+ export const STARTED_CLI_VERSION = readStartedCliVersion();
34
+ //# sourceMappingURL=started-version.js.map
@@ -17,15 +17,9 @@
17
17
  * spawns, waits, or a real install tree.
18
18
  */
19
19
  import type { VersionGatePhase } from "./utils/version-gate.js";
20
- import { type InstallRewriteSignalArgs, type WaitForInstallTreeSettledArgs, type WaitForInstallTreeSettledResult } from "./utils/install-tree-torn.js";
21
- /**
22
- * Set on the re-exec'd child so it can NEVER wait or re-exec again — distinct
23
- * from self-update's HQ_RESCUE_SELF_UPDATED so the two recovery paths cannot
24
- * shadow each other.
25
- */
26
- export declare const INSTALL_TREE_RECOVERY_GUARD_ENV = "HQ_INSTALL_TREE_RECOVERED";
27
- /** Carries the writer-state observed by the parent into the guarded re-exec. */
28
- export declare const INSTALL_TREE_RECOVERY_TREE_STATE_ENV = "HQ_INSTALL_TREE_RECOVERY_TREE_STATE";
20
+ import { clearInstallTreeRecoveryEnv, INSTALL_TREE_RECOVERY_GUARD_ENV, INSTALL_TREE_RECOVERY_TREE_STATE_ENV } from "./utils/install-tree-recovery-markers.js";
21
+ import { type InstallRewriteSignalArgs, type InstallTreeFs, type MixedInstallRestartEvent, type WaitForInstallTreeSettledArgs, type WaitForInstallTreeSettledResult } from "./utils/install-tree-torn.js";
22
+ export { clearInstallTreeRecoveryEnv, INSTALL_TREE_RECOVERY_GUARD_ENV, INSTALL_TREE_RECOVERY_TREE_STATE_ENV, };
29
23
  /** Operator override for the settle wait's deadline. */
30
24
  export declare const INSTALL_SETTLE_TIMEOUT_ENV = "HQ_INSTALL_SETTLE_TIMEOUT_MS";
31
25
  /** Default settle deadline (ms). Overridable by {@link INSTALL_SETTLE_TIMEOUT_ENV}. */
@@ -93,6 +87,12 @@ export interface RegisterRecoveryDeps {
93
87
  versionGatePhase?: () => VersionGatePhase;
94
88
  /** node flags to forward to the re-exec child (defaults to process.execArgv). */
95
89
  execArgv?: readonly string[];
90
+ /** CLI version this process started with (defaults to CLI_VERSION). */
91
+ startedVersion?: string;
92
+ /** Filesystem surface for version-skew detection (defaults to real node:fs). */
93
+ fs?: InstallTreeFs;
94
+ /** Counted, non-error reporter called before a mixed-install restart (defaults to recordMixedInstallRestart). */
95
+ onMixedInstallRestart?: (event: MixedInstallRestartEvent) => void | Promise<void>;
96
96
  }
97
97
  export interface RegisterCommandsWithRecoveryArgs {
98
98
  /** Runs the existing registration (lazy command import or register-all import). */
@@ -19,15 +19,9 @@
19
19
  import { spawnSync } from "node:child_process";
20
20
  import { stringDerivedPackageRoot } from "./utils/hq-roots.js";
21
21
  import { updateLockPath, UPDATE_LOCK_STALE_MS } from "./utils/update-lock.js";
22
- import { classifyEvalThrow, classifyMissingRegistrationPlan, classifyModuleNotFound, installRewriteInProgress, InstallTreeTornError, waitForInstallTreeSettled, } from "./utils/install-tree-torn.js";
23
- /**
24
- * Set on the re-exec'd child so it can NEVER wait or re-exec again — distinct
25
- * from self-update's HQ_RESCUE_SELF_UPDATED so the two recovery paths cannot
26
- * shadow each other.
27
- */
28
- export const INSTALL_TREE_RECOVERY_GUARD_ENV = "HQ_INSTALL_TREE_RECOVERED";
29
- /** Carries the writer-state observed by the parent into the guarded re-exec. */
30
- export const INSTALL_TREE_RECOVERY_TREE_STATE_ENV = "HQ_INSTALL_TREE_RECOVERY_TREE_STATE";
22
+ import { clearInstallTreeRecoveryEnv, INSTALL_TREE_RECOVERY_GUARD_ENV, INSTALL_TREE_RECOVERY_TREE_STATE_ENV, } from "./utils/install-tree-recovery-markers.js";
23
+ import { classifyEvalThrow, classifyInstallVersionSkew, classifyMissingRegistrationPlan, classifyModuleNotFound, installRewriteInProgress, InstallTreeTornError, recordMixedInstallRestart, waitForInstallTreeSettled, } from "./utils/install-tree-torn.js";
24
+ export { clearInstallTreeRecoveryEnv, INSTALL_TREE_RECOVERY_GUARD_ENV, INSTALL_TREE_RECOVERY_TREE_STATE_ENV, };
31
25
  /** Operator override for the settle wait's deadline. */
32
26
  export const INSTALL_SETTLE_TIMEOUT_ENV = "HQ_INSTALL_SETTLE_TIMEOUT_MS";
33
27
  /** Default settle deadline (ms). Overridable by {@link INSTALL_SETTLE_TIMEOUT_ENV}. */
@@ -109,20 +103,30 @@ export async function registerCommandsWithRecovery(args) {
109
103
  const deps = args.deps ?? {};
110
104
  try {
111
105
  await register();
106
+ // Startup registration succeeded: clear the one-shot recovery markers from
107
+ // env so any descendant hq process spawned by this command can recover from
108
+ // a later torn install on its own.
109
+ clearInstallTreeRecoveryEnv(env);
112
110
  return {};
113
111
  }
114
112
  catch (err) {
115
113
  // The packageRoot bounds the eval-throw classifier's throw site and feeds the
116
114
  // settle wait's manifest-health / retired-sibling guards; resolved once here.
117
115
  const packageRoot = resolvePackageRoot(deps);
118
- // Classify the loader failure. classifyModuleNotFound covers the resolve/load
119
- // dialects (incl. HQ-CLI-1S resolve-enoent); classifyEvalThrow covers a
120
- // module-EVALUATION throw (HQ-CLI-1T). Anything unclassified is rethrown as the
121
- // SAME object to the existing boundary, preserving today's behaviour exactly.
122
- // classifyMissingRegistrationPlan covers a startup catalog root that the
123
- // lazily imported plan does not know (HQ-CLI-GM): the catalog and the plan
124
- // came from different installs, so it takes the loader-race path (no gate).
125
- const classified = classifyModuleNotFound(err) ??
116
+ // Classify the failure. Check version skew FIRST (HQ-CLI-HD): when the
117
+ // installed package.json on disk differs from the version this process
118
+ // started with, newly loaded files sit beside old code in memory and can
119
+ // throw export-mismatch SyntaxErrors, dist/ TypeErrors, or
120
+ // ERR_MODULE_NOT_FOUND for files renamed between releases. Treating it as
121
+ // version-skew with target `unknown` avoids polling forever for a deleted
122
+ // old filename and bypasses the eval-throw live-writer gate after a swap
123
+ // finishes. When the version on disk is unchanged or unreadable, this
124
+ // returns null and the existing classifiers run unchanged.
125
+ const classified = classifyInstallVersionSkew(err, packageRoot, {
126
+ startedVersion: deps.startedVersion,
127
+ fs: deps.fs,
128
+ }) ??
129
+ classifyModuleNotFound(err) ??
126
130
  classifyMissingRegistrationPlan(err) ??
127
131
  classifyEvalThrow(err, packageRoot);
128
132
  if (!classified)
@@ -207,7 +211,7 @@ export async function registerCommandsWithRecovery(args) {
207
211
  }
208
212
  const spawn = deps.spawn ?? spawnSync;
209
213
  const execArgv = deps.execArgv ?? process.execArgv;
210
- const treeState = result.sawLock || result.sawRetired || result.sawTreeChange
214
+ const treeState = classified.dialect === "version-skew" || result.sawLock || result.sawRetired || result.sawTreeChange
211
215
  ? "in_flight"
212
216
  : "stale";
213
217
  if (args.reexecOnSettled === false) {
@@ -230,6 +234,26 @@ export async function registerCommandsWithRecovery(args) {
230
234
  lockTool: result.lockTool,
231
235
  });
232
236
  }
237
+ if (classified.dialect === "version-skew") {
238
+ // Record the mixed-install restart as a counted, non-error event BEFORE
239
+ // spawnSync so a long-running child process does not delay reporting.
240
+ // Any telemetry error is swallowed so reporting never blocks recovery.
241
+ const reportMixedInstall = deps.onMixedInstallRestart ??
242
+ ((event) => recordMixedInstallRestart(event, { argv, env }));
243
+ try {
244
+ await reportMixedInstall({
245
+ startedVersion: classified.startedVersion ?? "",
246
+ onDiskVersion: classified.onDiskVersion ?? "",
247
+ errorName: classified.errorName ?? "",
248
+ waitedMs: result.waitedMs,
249
+ sawLock: result.sawLock,
250
+ sawRetired: result.sawRetired,
251
+ });
252
+ }
253
+ catch {
254
+ // Telemetry must never block the user-side restart.
255
+ }
256
+ }
233
257
  const child = spawn(process.execPath, [...execArgv, entryPath, ...argv.slice(2)], {
234
258
  stdio: "inherit",
235
259
  env: {
@@ -115,6 +115,7 @@ export declare function loadJournalObservation(stateDir: string): JournalObserva
115
115
  export declare function persistJournalObservation(stateDir: string, observation: JournalObservation): void;
116
116
  /** Best-effort persist — a read-only disk must never fail a command. */
117
117
  export declare function persistClientHealthState(stateDir: string, state: CliClientHealthState): void;
118
+ export declare const STATE_READ_ATTEMPTS = 4;
118
119
  /**
119
120
  * Strictly-increasing sequence: wall-clock ms when it is ahead (keeps
120
121
  * separate processes ordered without locking), else last + 1.
@@ -119,16 +119,7 @@ function isDirectory(target) {
119
119
  * never break a CLI command.
120
120
  */
121
121
  export function loadClientHealthState(stateDir) {
122
- let raw = {};
123
- try {
124
- const parsed = JSON.parse(fs.readFileSync(stateFilePath(stateDir), "utf-8"));
125
- if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) {
126
- raw = parsed;
127
- }
128
- }
129
- catch {
130
- // Missing or corrupt state file: start fresh.
131
- }
122
+ const raw = readPersistedState(stateFilePath(stateDir));
132
123
  const installationId = typeof raw.installationId === "string" &&
133
124
  INSTALLATION_ID.test(raw.installationId)
134
125
  ? raw.installationId
@@ -192,12 +183,64 @@ export function persistJournalObservation(stateDir, observation) {
192
183
  export function persistClientHealthState(stateDir, state) {
193
184
  try {
194
185
  fs.mkdirSync(stateDir, { recursive: true });
195
- fs.writeFileSync(stateFilePath(stateDir), `${JSON.stringify(state, null, 2)}\n`, "utf-8");
186
+ writeStateFileAtomically(stateFilePath(stateDir), `${JSON.stringify(state, null, 2)}\n`);
196
187
  }
197
188
  catch {
198
189
  // Best effort only.
199
190
  }
200
191
  }
192
+ export const STATE_READ_ATTEMPTS = 4;
193
+ const STATE_READ_RETRY_MS = 5;
194
+ const STATE_RENAME_ATTEMPTS = 4;
195
+ const STATE_RENAME_RETRY_MS = 10;
196
+ const RETRYABLE_RENAME_CODES = new Set(["EPERM", "EACCES", "EBUSY"]);
197
+ function pauseSync(ms) {
198
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
199
+ }
200
+ function readPersistedState(file) {
201
+ for (let attempt = 1;; attempt += 1) {
202
+ let text;
203
+ try {
204
+ text = fs.readFileSync(file, "utf-8");
205
+ }
206
+ catch {
207
+ return {};
208
+ }
209
+ try {
210
+ const parsed = JSON.parse(text);
211
+ return parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)
212
+ ? parsed
213
+ : {};
214
+ }
215
+ catch {
216
+ if (attempt >= STATE_READ_ATTEMPTS)
217
+ return {};
218
+ pauseSync(STATE_READ_RETRY_MS);
219
+ }
220
+ }
221
+ }
222
+ function writeStateFileAtomically(file, text) {
223
+ const temp = `${file}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
224
+ try {
225
+ fs.writeFileSync(temp, text, "utf-8");
226
+ for (let attempt = 1;; attempt += 1) {
227
+ try {
228
+ fs.renameSync(temp, file);
229
+ return;
230
+ }
231
+ catch (error) {
232
+ const code = error.code ?? "";
233
+ if (attempt >= STATE_RENAME_ATTEMPTS || !RETRYABLE_RENAME_CODES.has(code))
234
+ throw error;
235
+ pauseSync(STATE_RENAME_RETRY_MS);
236
+ }
237
+ }
238
+ }
239
+ catch (error) {
240
+ fs.rmSync(temp, { force: true });
241
+ throw error;
242
+ }
243
+ }
201
244
  /**
202
245
  * Strictly-increasing sequence: wall-clock ms when it is ahead (keeps
203
246
  * separate processes ordered without locking), else last + 1.
@@ -4,6 +4,8 @@ export declare const CORE_NEXT_KILL_FILE: string;
4
4
  /** The engine-wide kill switch the bridge already honors; the engine checks it too. */
5
5
  export declare const ENGINE_KILL_ENV = "HQ_HOOK_ENGINE";
6
6
  export declare const ENGINE_KILL_FILE: string;
7
+ /** Strict-mode marker file under the home folder (matches crates/hq-hook/src/bridge.rs). */
8
+ export declare const ENGINE_STRICT_FILE: string;
7
9
  /**
8
10
  * Why the new core is switched off on this machine, or null. The same four
9
11
  * switches the engine reads (`crates/hq-hook/src/core_next.rs` `kill_reason`):
@@ -13,4 +15,11 @@ export declare const ENGINE_KILL_FILE: string;
13
15
  * entries it added, so the registrations are what they were before the switch.
14
16
  */
15
17
  export declare function coreNextKillReason(home: string, env?: NodeJS.ProcessEnv): string | null;
18
+ /**
19
+ * Why strict mode is engaged on this machine, or null. Matches the engine's
20
+ * strict check (`crates/hq-hook/src/bridge.rs`): `HQ_HOOK_ENGINE=strict`
21
+ * (trimmed, ASCII case-insensitive) or `~/.hq/hook-engine.strict` present (a
22
+ * link counts).
23
+ */
24
+ export declare function coreNextStrictReason(home: string, env?: NodeJS.ProcessEnv): string | null;
16
25
  //# sourceMappingURL=core-next-kill.d.ts.map
@@ -7,6 +7,8 @@ export const CORE_NEXT_KILL_FILE = path.join('.hq', 'state', 'core-next.off');
7
7
  /** The engine-wide kill switch the bridge already honors; the engine checks it too. */
8
8
  export const ENGINE_KILL_ENV = 'HQ_HOOK_ENGINE';
9
9
  export const ENGINE_KILL_FILE = path.join('.hq', 'hook-engine.off');
10
+ /** Strict-mode marker file under the home folder (matches crates/hq-hook/src/bridge.rs). */
11
+ export const ENGINE_STRICT_FILE = path.join('.hq', 'hook-engine.strict');
10
12
  /**
11
13
  * Why the new core is switched off on this machine, or null. The same four
12
14
  * switches the engine reads (`crates/hq-hook/src/core_next.rs` `kill_reason`):
@@ -32,4 +34,24 @@ export function coreNextKillReason(home, env = process.env) {
32
34
  }
33
35
  return null;
34
36
  }
37
+ /**
38
+ * Why strict mode is engaged on this machine, or null. Matches the engine's
39
+ * strict check (`crates/hq-hook/src/bridge.rs`): `HQ_HOOK_ENGINE=strict`
40
+ * (trimmed, ASCII case-insensitive) or `~/.hq/hook-engine.strict` present (a
41
+ * link counts).
42
+ */
43
+ export function coreNextStrictReason(home, env = process.env) {
44
+ if (coreNextKillReason(home, env) !== null)
45
+ return null;
46
+ if (/^strict$/i.test((env[ENGINE_KILL_ENV] ?? '').trim()))
47
+ return `${ENGINE_KILL_ENV}=${env[ENGINE_KILL_ENV]}`;
48
+ const file = path.join(home, ENGINE_STRICT_FILE);
49
+ try {
50
+ fs.lstatSync(file);
51
+ return file;
52
+ }
53
+ catch {
54
+ return null;
55
+ }
56
+ }
35
57
  //# sourceMappingURL=core-next-kill.js.map
@@ -1,10 +1,10 @@
1
1
  import { type EngineOptions } from '../lib/hook-engine/resolve.js';
2
2
  import { type NativeTarget } from '../lib/hook-engine/registration.js';
3
3
  export { CORE_NEXT_FLAG, coreNextEnabled } from './core-next-flag.js';
4
- export { coreNextKillReason, CORE_NEXT_KILL_ENV, CORE_NEXT_KILL_FILE, ENGINE_KILL_ENV, ENGINE_KILL_FILE } from './core-next-kill.js';
4
+ export { coreNextKillReason, coreNextStrictReason, CORE_NEXT_KILL_ENV, CORE_NEXT_KILL_FILE, ENGINE_KILL_ENV, ENGINE_KILL_FILE, ENGINE_STRICT_FILE } from './core-next-kill.js';
5
5
  /** Name of the release-stable link next to the pinned engine versions. */
6
6
  export declare const STABLE_LINK_NAME = "stable";
7
- export type CoreNextHost = 'claude' | 'codex' | 'grok' | 'fleet-local' | 'agents-v2';
7
+ export type CoreNextHost = 'claude' | 'codex' | 'grok' | 'fleet-local' | 'agents-v2' | 'antigravity';
8
8
  /**
9
9
  * `project`: the HQ root's own registration, always answers.
10
10
  * `global`: the user-scope Claude Code entry; answers nothing inside an HQ
@@ -26,6 +26,8 @@ export interface CoreNextTarget {
26
26
  fallback?: FallbackTarget;
27
27
  /** The old dispatcher's hooks the engine does in full, per event (`capabilities --json` `covers`). */
28
28
  covers?: Readonly<Record<string, readonly string[]>>;
29
+ /** Hosts advertised by `capabilities --json` `registration_hosts`. */
30
+ registrationHosts?: readonly string[];
29
31
  /**
30
32
  * The host canary gate (US-019 criterion 4): true when `host` may switch
31
33
  * events in `root` to this engine. Set by [`coreNextTarget`]; checked by
@@ -52,8 +52,9 @@ import { SKIP_CANARY_GATE_ENV, checkHostCanary } from '../lib/hook-engine/canary
52
52
  import { resolvedUnder } from '../lib/hook-engine/coverage.js';
53
53
  export { CORE_NEXT_FLAG, coreNextEnabled } from './core-next-flag.js';
54
54
  import { CORE_NEXT_FLAG, coreNextEnabled } from './core-next-flag.js';
55
- export { coreNextKillReason, CORE_NEXT_KILL_ENV, CORE_NEXT_KILL_FILE, ENGINE_KILL_ENV, ENGINE_KILL_FILE } from './core-next-kill.js';
56
- import { coreNextKillReason } from './core-next-kill.js';
55
+ export { coreNextKillReason, coreNextStrictReason, CORE_NEXT_KILL_ENV, CORE_NEXT_KILL_FILE, ENGINE_KILL_ENV, ENGINE_KILL_FILE, ENGINE_STRICT_FILE } from './core-next-kill.js';
56
+ import { coreNextKillReason, coreNextStrictReason, ENGINE_STRICT_FILE } from './core-next-kill.js';
57
+ const HOOK_ENGINE_LOG_RELATIVE = path.join('.hq', 'logs', 'hook-engine.jsonl');
57
58
  /** Name of the release-stable link next to the pinned engine versions. */
58
59
  export const STABLE_LINK_NAME = 'stable';
59
60
  /** The target one event is registered to: the new core only for an event it can take. */
@@ -345,7 +346,13 @@ export function coreNextTargetFor(home, env, stable, caps, platform = process.pl
345
346
  const events = capableEvents(caps);
346
347
  if (!events.length)
347
348
  return null;
348
- return resolvedUnder({ coreNext: stable, events, covers: caps.covers ?? {}, canary: hostCanaryGate(home, env, caps.version, platform, warn) }, env);
349
+ return resolvedUnder({
350
+ coreNext: stable,
351
+ events,
352
+ covers: caps.covers ?? {},
353
+ ...(caps.registrationHosts ? { registrationHosts: caps.registrationHosts } : {}),
354
+ canary: hostCanaryGate(home, env, caps.version, platform, warn),
355
+ }, env);
349
356
  }
350
357
  const warned = new Set();
351
358
  function warnOnce(message, warn) {
@@ -371,21 +378,57 @@ function warnOnce(message, warn) {
371
378
  * canary cannot move a host onto the new core. A manual or install-time
372
379
  * reindex still applies the gate.
373
380
  */
381
+ function appendStrictCanaryLog(home, root, host, version, reason, strict) {
382
+ try {
383
+ const logFile = path.join(home, HOOK_ENGINE_LOG_RELATIVE);
384
+ fs.mkdirSync(path.dirname(logFile), { recursive: true, mode: 0o700 });
385
+ const strictLabel = strict.startsWith(home) ? ENGINE_STRICT_FILE : strict;
386
+ const entry = {
387
+ ts: new Date().toISOString(),
388
+ kind: 'strict-canary-hold',
389
+ host,
390
+ engine: version,
391
+ status: 'strict-canary-hold',
392
+ root: path.basename(root) || root,
393
+ strict: strictLabel,
394
+ reason: reason ?? 'unknown',
395
+ };
396
+ fs.appendFileSync(logFile, `${JSON.stringify(entry)}\n`, { mode: 0o600 });
397
+ }
398
+ catch {
399
+ // Best-effort engine log; the stderr error still surfaces the failure.
400
+ }
401
+ }
374
402
  function hostCanaryGate(home, env, version, platform, warn) {
403
+ const strictLogged = new Set();
404
+ const logStrictOnce = (root, host, reason, strict) => {
405
+ const key = `${root}\0${host}`;
406
+ if (strictLogged.has(key))
407
+ return;
408
+ strictLogged.add(key);
409
+ appendStrictCanaryLog(home, root, host, version, reason, strict);
410
+ };
375
411
  return (root, host) => {
376
- if (host === 'fleet-local')
412
+ if (host === 'fleet-local' || host === 'antigravity')
377
413
  return true;
378
414
  // agents-v2 is planned by `hq core hook-registration-plan`, which gates on
379
415
  // coverage and never asks this gate; any other caller keeps the shell plan.
380
416
  if (host === 'agents-v2')
381
417
  return false;
382
418
  const gate = checkHostCanary({ home, root, host, engineVersion: version, env, platform });
419
+ const strict = coreNextStrictReason(home, env);
383
420
  if (env[REINDEX_FROM_HOOK_ENV] === '1') {
384
421
  const current = hostOnCoreNext(home, env, root, host);
385
422
  if (current !== gate.allowed) {
386
- warnOnce(current
387
- ? `hq: warning: a reindex started by a hook keeps ${host} hook events on the new core: it never changes a host's core, and ${host} has no passing host canary for hq-hook ${version} and this HQ root (${gate.reason}). Run hq reindex to apply the host canary gate`
388
- : `hq: warning: a reindex started by a hook keeps the old hook registrations on ${host}: it never changes a host's core. Run hq reindex to switch ${host} to the new core (hq-hook ${version})`, warn);
423
+ if (current && strict) {
424
+ logStrictOnce(root, host, gate.reason, strict);
425
+ warnOnce(`hq: error: strict mode (${strict}) keeps ${host} hook events on the new core (hq-hook ${version}) even though the host canary gate failed (${gate.reason}); heal the canary forward instead of reverting to bash`, warn);
426
+ }
427
+ else {
428
+ warnOnce(current
429
+ ? `hq: warning: a reindex started by a hook keeps ${host} hook events on the new core: it never changes a host's core, and ${host} has no passing host canary for hq-hook ${version} and this HQ root (${gate.reason}). Run hq reindex to apply the host canary gate`
430
+ : `hq: warning: a reindex started by a hook keeps the old hook registrations on ${host}: it never changes a host's core. Run hq reindex to switch ${host} to the new core (hq-hook ${version})`, warn);
431
+ }
389
432
  }
390
433
  return current;
391
434
  }
@@ -393,6 +436,11 @@ function hostCanaryGate(home, env, version, platform, warn) {
393
436
  warnOnce(`hq: warning: ${SKIP_CANARY_GATE_ENV} is set: bypassing the host canary gate and switching ${host} hook events to the new core (hq-hook ${version}) without a passing host canary (${gate.reason})`, warn);
394
437
  }
395
438
  else if (!gate.allowed) {
439
+ if (strict && hostOnCoreNext(home, env, root, host)) {
440
+ logStrictOnce(root, host, gate.reason, strict);
441
+ warnOnce(`hq: error: strict mode (${strict}) refuses to revert ${host} hook events from the new core (hq-hook ${version}) back to bash after a failed host canary (${gate.reason}); keeping the Rust registrations in place. Heal the canary forward or remove ${ENGINE_STRICT_FILE}`, warn);
442
+ return true;
443
+ }
396
444
  warnOnce(`hq: warning: flag ${CORE_NEXT_FLAG} is on, but ${host} has no passing host canary for hq-hook ${version} and this HQ root (${gate.reason}); keeping the old hook registrations on ${host}. Run scripts/host-canary.mjs --host ${host}, or bypass the gate with hq reindex --skip-host-canary-gate`, warn);
397
445
  }
398
446
  return gate.allowed;
@@ -0,0 +1,45 @@
1
+ /**
2
+ * One-shot recovery markers for a process restarted by torn-install recovery.
3
+ *
4
+ * The parent passes `HQ_INSTALL_TREE_RECOVERED=1` and
5
+ * `HQ_INSTALL_TREE_RECOVERY_TREE_STATE` in the re-exec environment so the
6
+ * restarted child can never loop. Consuming those markers into process memory
7
+ * and removing them from `process.env` guarantees two things at once:
8
+ *
9
+ * 1. Every recovery seam inside THIS process (`index.ts`, fast routes, and
10
+ * `main.ts`) still sees the one-shot guard through `installTreeRecoveryEnv`
11
+ * and fails closed (`outcome: "guarded"`, `attempt: 2`) instead of looping.
12
+ * 2. Descendant `hq` processes spawned by the restarted command (hooks,
13
+ * runners, `hq daemon`, MCP children) do not inherit the markers and can
14
+ * recover from a later torn install on their own.
15
+ *
16
+ * Kept dependency-free so `index.ts` can load it at entry without growing any
17
+ * fast-path module closure.
18
+ */
19
+ /**
20
+ * Set on the re-exec'd child so it can NEVER wait or re-exec again — distinct
21
+ * from self-update's HQ_RESCUE_SELF_UPDATED so the two recovery paths cannot
22
+ * shadow each other.
23
+ */
24
+ export declare const INSTALL_TREE_RECOVERY_GUARD_ENV = "HQ_INSTALL_TREE_RECOVERED";
25
+ /** Carries the writer-state observed by the parent into the guarded re-exec. */
26
+ export declare const INSTALL_TREE_RECOVERY_TREE_STATE_ENV = "HQ_INSTALL_TREE_RECOVERY_TREE_STATE";
27
+ /**
28
+ * Consume the one-shot torn-install recovery markers from `env` and remove them
29
+ * so spawned child processes cannot inherit them. When called on `process.env`,
30
+ * retains them in process memory for this process's own recovery seams.
31
+ */
32
+ export declare function consumeInstallTreeRecoveryMarkers(env?: NodeJS.ProcessEnv): NodeJS.ProcessEnv | undefined;
33
+ /**
34
+ * Remove the one-shot recovery markers from `env` without recording them.
35
+ * Called once startup registration succeeds so direct callers that did not go
36
+ * through `index.ts` also avoid leaking markers to descendants.
37
+ */
38
+ export declare function clearInstallTreeRecoveryEnv(env?: NodeJS.ProcessEnv): void;
39
+ /**
40
+ * Re-attach this process's consumed one-shot recovery markers to an env view
41
+ * passed into `registerCommandsWithRecovery`, so multi-stage startup seams in
42
+ * the same restarted process still enforce the single-restart loop guard.
43
+ */
44
+ export declare function installTreeRecoveryEnv(base: NodeJS.ProcessEnv): NodeJS.ProcessEnv;
45
+ //# sourceMappingURL=install-tree-recovery-markers.d.ts.map
@@ -0,0 +1,70 @@
1
+ /**
2
+ * One-shot recovery markers for a process restarted by torn-install recovery.
3
+ *
4
+ * The parent passes `HQ_INSTALL_TREE_RECOVERED=1` and
5
+ * `HQ_INSTALL_TREE_RECOVERY_TREE_STATE` in the re-exec environment so the
6
+ * restarted child can never loop. Consuming those markers into process memory
7
+ * and removing them from `process.env` guarantees two things at once:
8
+ *
9
+ * 1. Every recovery seam inside THIS process (`index.ts`, fast routes, and
10
+ * `main.ts`) still sees the one-shot guard through `installTreeRecoveryEnv`
11
+ * and fails closed (`outcome: "guarded"`, `attempt: 2`) instead of looping.
12
+ * 2. Descendant `hq` processes spawned by the restarted command (hooks,
13
+ * runners, `hq daemon`, MCP children) do not inherit the markers and can
14
+ * recover from a later torn install on their own.
15
+ *
16
+ * Kept dependency-free so `index.ts` can load it at entry without growing any
17
+ * fast-path module closure.
18
+ */
19
+ /**
20
+ * Set on the re-exec'd child so it can NEVER wait or re-exec again — distinct
21
+ * from self-update's HQ_RESCUE_SELF_UPDATED so the two recovery paths cannot
22
+ * shadow each other.
23
+ */
24
+ export const INSTALL_TREE_RECOVERY_GUARD_ENV = "HQ_INSTALL_TREE_RECOVERED";
25
+ /** Carries the writer-state observed by the parent into the guarded re-exec. */
26
+ export const INSTALL_TREE_RECOVERY_TREE_STATE_ENV = "HQ_INSTALL_TREE_RECOVERY_TREE_STATE";
27
+ const ONE_SHOT_RECOVERY_KEYS = [
28
+ INSTALL_TREE_RECOVERY_GUARD_ENV,
29
+ INSTALL_TREE_RECOVERY_TREE_STATE_ENV,
30
+ ];
31
+ let consumedRecoveryMarkers;
32
+ /**
33
+ * Consume the one-shot torn-install recovery markers from `env` and remove them
34
+ * so spawned child processes cannot inherit them. When called on `process.env`,
35
+ * retains them in process memory for this process's own recovery seams.
36
+ */
37
+ export function consumeInstallTreeRecoveryMarkers(env = process.env) {
38
+ const markers = {};
39
+ for (const key of ONE_SHOT_RECOVERY_KEYS) {
40
+ const value = env[key];
41
+ if (typeof value === "string" && value !== "")
42
+ markers[key] = value;
43
+ delete env[key];
44
+ }
45
+ const hasMarkers = Object.keys(markers).length > 0;
46
+ if (env === process.env) {
47
+ consumedRecoveryMarkers = hasMarkers ? markers : undefined;
48
+ }
49
+ return hasMarkers ? markers : undefined;
50
+ }
51
+ /**
52
+ * Remove the one-shot recovery markers from `env` without recording them.
53
+ * Called once startup registration succeeds so direct callers that did not go
54
+ * through `index.ts` also avoid leaking markers to descendants.
55
+ */
56
+ export function clearInstallTreeRecoveryEnv(env = process.env) {
57
+ delete env[INSTALL_TREE_RECOVERY_GUARD_ENV];
58
+ delete env[INSTALL_TREE_RECOVERY_TREE_STATE_ENV];
59
+ }
60
+ /**
61
+ * Re-attach this process's consumed one-shot recovery markers to an env view
62
+ * passed into `registerCommandsWithRecovery`, so multi-stage startup seams in
63
+ * the same restarted process still enforce the single-restart loop guard.
64
+ */
65
+ export function installTreeRecoveryEnv(base) {
66
+ if (!consumedRecoveryMarkers)
67
+ return base;
68
+ return { ...consumedRecoveryMarkers, ...base };
69
+ }
70
+ //# sourceMappingURL=install-tree-recovery-markers.js.map