@indigoai-us/hq-cli 5.345.269 → 5.345.272

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 (61) hide show
  1. package/CHANGELOG.md +81 -0
  2. package/contracts/host-canary-release.json +7 -7
  3. package/dist/command-catalog.generated.d.ts +2 -2
  4. package/dist/command-catalog.generated.js +2 -2
  5. package/dist/commands/core-checkpoint-stop-gate-native.js +2 -13
  6. package/dist/commands/core-session-journal-native.js +20 -4
  7. package/dist/commands/signals-run.d.ts +4 -1
  8. package/dist/commands/signals-run.js +6 -8
  9. package/dist/commands/sync-core.js +2 -1
  10. package/dist/lib/daemon/daemon-restart.d.ts +70 -0
  11. package/dist/lib/daemon/daemon-restart.js +114 -0
  12. package/dist/lib/daemon/hook-requests-work-mesh-shims.d.ts +41 -0
  13. package/dist/lib/daemon/hook-requests-work-mesh-shims.js +237 -0
  14. package/dist/lib/daemon/hook-requests.d.ts +4 -1
  15. package/dist/lib/daemon/hook-requests.js +23 -1
  16. package/dist/lib/daemon/hq-child-bootstrap.mjs +1 -0
  17. package/dist/lib/daemon/installed-cli-restart.js +14 -4
  18. package/dist/lib/daemon/run.d.ts +1 -1
  19. package/dist/lib/daemon/run.js +65 -51
  20. package/dist/lib/daemon/supervisor.js +0 -2
  21. package/dist/lib/hook-engine/coverage.d.ts +21 -0
  22. package/dist/lib/hook-engine/coverage.js +98 -5
  23. package/dist/lib/hook-engine/native-precompact-compatibility.json +1 -0
  24. package/dist/lib/hook-engine/native-stop-compatibility.json +4 -2
  25. package/dist/lib/hook-engine/reconcile.js +8 -0
  26. package/dist/lib/hook-engine/stable-heal.d.ts +17 -1
  27. package/dist/lib/hook-engine/stable-heal.js +42 -5
  28. package/dist/lib/hook-engine/stable-link.d.ts +70 -0
  29. package/dist/lib/hook-engine/stable-link.js +300 -0
  30. package/dist/lib/hot-channels/signals-pass.d.ts +10 -2
  31. package/dist/lib/hot-channels/signals-pass.js +13 -3
  32. package/dist/lib/install/hook-target.js +4 -1
  33. package/dist/lib/signals/engine.d.ts +0 -2
  34. package/dist/lib/signals/engine.js +12 -7
  35. package/dist/lib/signals/reply.js +35 -82
  36. package/dist/lib/signals/run-lock.d.ts +8 -0
  37. package/dist/lib/signals/run-lock.js +42 -7
  38. package/dist/lib/signals/run-record.js +2 -1
  39. package/dist/lib/signals/settings.d.ts +9 -4
  40. package/dist/lib/signals/settings.js +7 -5
  41. package/dist/lib/signals/steps/extract.d.ts +64 -17
  42. package/dist/lib/signals/steps/extract.js +175 -197
  43. package/dist/lib/signals/steps/types.d.ts +3 -2
  44. package/dist/lib/sync-core/reconcile.d.ts +7 -1
  45. package/dist/lib/sync-core/reconcile.js +105 -18
  46. package/dist/lib/sync-core/release.d.ts +52 -2
  47. package/dist/lib/sync-core/release.js +172 -11
  48. package/dist/lib/sync-core/rollout-state.d.ts +11 -0
  49. package/dist/lib/sync-core/rollout-state.js +16 -0
  50. package/dist/utils/client-health-contract.d.ts +32 -0
  51. package/dist/utils/client-health-contract.js +35 -0
  52. package/dist/utils/client-health.d.ts +43 -0
  53. package/dist/utils/client-health.js +106 -3
  54. package/dist/utils/hook-trust.js +7 -1
  55. package/dist/utils/host-registration.d.ts +12 -35
  56. package/dist/utils/host-registration.js +47 -177
  57. package/dist/utils/login-browser.d.ts +1 -0
  58. package/dist/utils/login-browser.js +31 -6
  59. package/dist/utils/spawn-detached-hidden.d.ts +66 -0
  60. package/dist/utils/spawn-detached-hidden.js +222 -0
  61. package/package.json +7 -7
@@ -33,6 +33,7 @@
33
33
  import { isExpiring, loadCachedTokens } from "./cognito-session.js";
34
34
  import { type VersionInfo } from "./feedback-versions.js";
35
35
  import { type ClientHealthArch, type ClientHealthFailureReason, type ClientHealthHeartbeat, type ClientHealthLocalFilesOverview, type ClientHealthPlatform, type ClientHealthSyncEngineVault } from "./client-health-contract.js";
36
+ import { type SyncCoreBinaryOutcome } from "../lib/sync-core/rollout-state.js";
36
37
  import { type DaemonPaths } from "../lib/daemon/paths.js";
37
38
  export declare const CLIENT_HEALTH_STATE_FILE = "cli-client-health.json";
38
39
  /**
@@ -182,12 +183,48 @@ export interface BuildCliHeartbeatInput {
182
183
  localFilesOverview?: ClientHealthLocalFilesOverview | null;
183
184
  syncEngine?: CliSyncEngine | null;
184
185
  daemonCliVersion?: string | null;
186
+ /** The live daemon's state file facts; null with no live daemon. */
187
+ daemon?: CliDaemonFacts | null;
188
+ /** True when this process was started by the daemon (a daemon unit): `versions.cli` is then what its units run. */
189
+ daemonUnit?: boolean;
185
190
  }
186
191
  export interface CliSyncEngine {
187
192
  release: string;
188
193
  vaults: number;
189
194
  byVault?: ClientHealthSyncEngineVault[];
195
+ pinned?: string;
196
+ pinSource?: "server" | "built-in" | "last-good";
197
+ reconcileAt?: string;
198
+ reconcileOutcome?: SyncCoreBinaryOutcome;
199
+ reconcileWarnings?: number;
190
200
  }
201
+ export interface CliDaemonFacts {
202
+ startedAt?: string;
203
+ hosted: boolean;
204
+ }
205
+ /**
206
+ * How long the daemon's state file may go without a rewrite before HQ stops
207
+ * trusting it. A running daemon rewrites state.json on every reconcile pass
208
+ * (15 s), so a state this old belongs to a daemon that is no longer running,
209
+ * even when its pid now names another live process.
210
+ */
211
+ export declare const DAEMON_STATE_FRESH_MS: number;
212
+ /**
213
+ * The live daemon's start time and whether an app hosts it, read only from
214
+ * its lock and state files; null when none runs. The state counts only when
215
+ * it was written by the daemon instance that holds the lock (same pid, and
216
+ * started no earlier than the lock was taken) and was rewritten within
217
+ * {@link DAEMON_STATE_FRESH_MS}.
218
+ */
219
+ export declare function readCliDaemonFacts(paths?: DaemonPaths, alive?: (pid: number) => boolean, now?: () => number): CliDaemonFacts | null;
220
+ /**
221
+ * True for the hq process a daemon (or its staged launcher) started for a
222
+ * unit. A daemon running this release records the unit's parent in
223
+ * HQ_DAEMON_UNIT_PARENT_PID, and a bot or session below the unit inherits it
224
+ * with a different parent, so it does not count. An older daemon sets no
225
+ * marker; its units are recognised by HQ_DAEMON_CLI_VERSION alone, as before.
226
+ */
227
+ export declare function isDirectDaemonUnit(env: NodeJS.ProcessEnv, parentPid?: number): boolean;
191
228
  export declare function readCliSyncEngine(stateDir: string, now?: Date, paths?: DaemonPaths, alive?: (pid: number) => boolean): CliSyncEngine | null;
192
229
  /** Classify sync failures using typed error identity/code fields only. */
193
230
  export declare function classifySyncFailure(err: unknown): ClientHealthFailureReason;
@@ -218,6 +255,12 @@ export interface ClientHealthDeps {
218
255
  syncEngine?: () => CliSyncEngine | null;
219
256
  daemonPaths?: DaemonPaths;
220
257
  daemonCliVersion?: () => Promise<string | null>;
258
+ daemonFacts?: () => CliDaemonFacts | null;
259
+ daemonAlive?: (pid: number) => boolean;
260
+ /** This process's environment, read for HQ_DAEMON_CLI_VERSION and HQ_DAEMON_UNIT_PARENT_PID. */
261
+ env?: NodeJS.ProcessEnv;
262
+ /** This process's parent pid at startup; see {@link isDirectDaemonUnit}. */
263
+ parentPid?: number;
221
264
  /** Override for {@link JOURNAL_OBSERVATION_TTL_MS}. */
222
265
  journalObservationTtlMs?: number;
223
266
  /** Override for {@link JOURNAL_OBSERVATION_LOCK_STALE_MS}. */
@@ -42,12 +42,13 @@ import { vaultApiFetch } from "./vault-api.js";
42
42
  import { collectVersions } from "./feedback-versions.js";
43
43
  import { resolveDaemonCliVersion } from "./daemon-cli-version.js";
44
44
  import { isAuthError } from "./auth-error.js";
45
- import { CLIENT_HEALTH_CONTRACT_VERSION, CLIENT_HEALTH_MAX_SYNC_ENGINE_VAULTS, CLIENT_HEALTH_MAX_SYNC_ENGINE_VAULT_ENTRIES, CLIENT_HEALTH_SYNC_ENGINE_HOLD_KINDS, parseClientHealthHeartbeat, SEMVER, } from "./client-health-contract.js";
45
+ import { CLIENT_HEALTH_CONTRACT_VERSION, CLIENT_HEALTH_MAX_SYNC_ENGINE_VAULTS, CLIENT_HEALTH_MAX_RECONCILE_WARNINGS, CLIENT_HEALTH_MAX_SYNC_ENGINE_VAULT_ENTRIES, CLIENT_HEALTH_SYNC_ENGINE_HOLD_KINDS, parseClientHealthHeartbeat, SEMVER, } from "./client-health-contract.js";
46
46
  import { collectLocalFilesOverview } from "./local-files-overview.js";
47
47
  import { readSyncCoreRolloutStateFile } from "../lib/sync-core/rollout-state.js";
48
+ const ISO_UTC_MS = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?Z$/;
48
49
  import { readEngineStatus, SYNC_CORE_STATUS_WORK_LIMIT, syncCoreUnitId } from "../lib/sync-core/engine-home.js";
49
50
  import { daemonPaths } from "../lib/daemon/paths.js";
50
- import { isProcessAlive, runningDaemonPid } from "../lib/daemon/lock.js";
51
+ import { isProcessAlive, liveDaemonLock, runningDaemonPid } from "../lib/daemon/lock.js";
51
52
  import { readEngineHoldKinds } from "../lib/sync-core/engine-holds.js";
52
53
  /** Same bound as CLI telemetry: a heartbeat may never stall a command. */
53
54
  const CLIENT_HEALTH_TIMEOUT_MS = 1_200;
@@ -430,6 +431,62 @@ function acquireJournalObservationLock(stateDir, nowMs, staleMs) {
430
431
  }
431
432
  };
432
433
  }
434
+ /**
435
+ * How long the daemon's state file may go without a rewrite before HQ stops
436
+ * trusting it. A running daemon rewrites state.json on every reconcile pass
437
+ * (15 s), so a state this old belongs to a daemon that is no longer running,
438
+ * even when its pid now names another live process.
439
+ */
440
+ export const DAEMON_STATE_FRESH_MS = 2 * 60_000;
441
+ /** How far the state's start may precede its lock's ts (whole-second rounding and clock skew). */
442
+ const DAEMON_LOCK_TS_SLACK_MS = 2_000;
443
+ /**
444
+ * The live daemon's start time and whether an app hosts it, read only from
445
+ * its lock and state files; null when none runs. The state counts only when
446
+ * it was written by the daemon instance that holds the lock (same pid, and
447
+ * started no earlier than the lock was taken) and was rewritten within
448
+ * {@link DAEMON_STATE_FRESH_MS}.
449
+ */
450
+ export function readCliDaemonFacts(paths = daemonPaths(), alive = isProcessAlive, now = Date.now) {
451
+ try {
452
+ const lock = liveDaemonLock(paths.lockPath, alive);
453
+ if (lock === null)
454
+ return null;
455
+ const state = JSON.parse(fs.readFileSync(paths.statePath, "utf8"));
456
+ if (!state || state.pid !== lock.pid)
457
+ return null;
458
+ const updatedAt = typeof state.updatedAt === "number" && Number.isFinite(state.updatedAt) ? state.updatedAt : undefined;
459
+ if (updatedAt === undefined || now() - updatedAt > DAEMON_STATE_FRESH_MS)
460
+ return null;
461
+ const hosted = typeof state.host === "string" && state.host.length > 0;
462
+ const startedAtMs = typeof state.startedAt === "number" && Number.isFinite(state.startedAt) && state.startedAt > 0 ? state.startedAt : undefined;
463
+ if (startedAtMs === undefined)
464
+ return { hosted };
465
+ if (startedAtMs + DAEMON_LOCK_TS_SLACK_MS < lock.ts * 1000)
466
+ return null;
467
+ return { startedAt: new Date(startedAtMs).toISOString(), hosted };
468
+ }
469
+ catch {
470
+ return null;
471
+ }
472
+ }
473
+ const startupParentPid = process.ppid;
474
+ /**
475
+ * True for the hq process a daemon (or its staged launcher) started for a
476
+ * unit. A daemon running this release records the unit's parent in
477
+ * HQ_DAEMON_UNIT_PARENT_PID, and a bot or session below the unit inherits it
478
+ * with a different parent, so it does not count. An older daemon sets no
479
+ * marker; its units are recognised by HQ_DAEMON_CLI_VERSION alone, as before.
480
+ */
481
+ export function isDirectDaemonUnit(env, parentPid = startupParentPid) {
482
+ if (!env.HQ_DAEMON_CLI_VERSION?.trim())
483
+ return false;
484
+ const marker = env.HQ_DAEMON_UNIT_PARENT_PID?.trim();
485
+ if (!marker)
486
+ return true;
487
+ const spawner = Number(marker);
488
+ return Number.isInteger(spawner) && spawner > 1 && spawner === parentPid;
489
+ }
433
490
  function readDaemonUnitStatuses(paths, alive) {
434
491
  try {
435
492
  const daemonPid = runningDaemonPid(paths.lockPath, alive);
@@ -495,7 +552,19 @@ export function readCliSyncEngine(stateDir, now = new Date(), paths = daemonPath
495
552
  add(vault.uid, () => syncEngineVaultFacts(vault, "legacy", units, now));
496
553
  for (const { uid } of [...(state.skipped ?? []), ...(state.held ?? [])])
497
554
  add(uid, () => ({ vaultUid: uid, owner: "legacy" }));
498
- return { release: state.release, vaults, byVault };
555
+ return {
556
+ release: state.release,
557
+ vaults,
558
+ byVault,
559
+ ...(state.binaryOutcome
560
+ ? {
561
+ ...(state.pin ? { pinned: state.pin.release, pinSource: state.pin.source } : {}),
562
+ reconcileAt: state.readAt,
563
+ reconcileOutcome: state.binaryOutcome,
564
+ reconcileWarnings: state.warnings ?? 0,
565
+ }
566
+ : {}),
567
+ };
499
568
  }
500
569
  /** Classify sync failures using typed error identity/code fields only. */
501
570
  export function classifySyncFailure(err) {
@@ -616,6 +685,28 @@ export function buildCliHeartbeat(input) {
616
685
  if (input.daemonCliVersion && SEMVER.test(input.daemonCliVersion)) {
617
686
  heartbeat.daemonCliVersion = input.daemonCliVersion;
618
687
  }
688
+ if (input.daemon) {
689
+ if (input.daemon.startedAt && ISO_UTC_MS.test(input.daemon.startedAt))
690
+ heartbeat.daemonStartedAt = input.daemon.startedAt;
691
+ heartbeat.daemonHosted = input.daemon.hosted;
692
+ }
693
+ if (input.daemonUnit && versions.cli)
694
+ heartbeat.daemonUnitCliVersion = versions.cli;
695
+ const engine = input.syncEngine;
696
+ if (engine) {
697
+ const pinned = engine.pinned?.replace(/^v/, "");
698
+ if (pinned && SEMVER.test(pinned))
699
+ heartbeat.syncEnginePinned = pinned;
700
+ if (engine.pinSource)
701
+ heartbeat.syncEnginePinSource = engine.pinSource;
702
+ if (engine.reconcileAt && ISO_UTC_MS.test(engine.reconcileAt))
703
+ heartbeat.syncEngineReconcileAt = engine.reconcileAt;
704
+ if (engine.reconcileOutcome)
705
+ heartbeat.syncEngineReconcileOutcome = engine.reconcileOutcome;
706
+ if (engine.reconcileWarnings !== undefined) {
707
+ heartbeat.syncEngineReconcileWarnings = Math.min(engine.reconcileWarnings, CLIENT_HEALTH_MAX_RECONCILE_WARNINGS);
708
+ }
709
+ }
619
710
  return heartbeat;
620
711
  }
621
712
  const defaultPoster = (heartbeat, token, signal) => vaultApiFetch({
@@ -792,6 +883,16 @@ async function contributeClientHealthUnbounded(kind, deps, failureReason) {
792
883
  catch {
793
884
  daemonCliVersion = null;
794
885
  }
886
+ let daemon = null;
887
+ try {
888
+ daemon = deps.daemonFacts
889
+ ? deps.daemonFacts()
890
+ : readCliDaemonFacts(deps.daemonPaths ?? daemonPaths(), deps.daemonAlive ?? isProcessAlive, () => now.getTime());
891
+ }
892
+ catch {
893
+ daemon = null;
894
+ }
895
+ const daemonUnit = isDirectDaemonUnit(deps.env ?? process.env, deps.parentPid ?? startupParentPid);
795
896
  const heartbeat = buildCliHeartbeat({
796
897
  kind,
797
898
  state,
@@ -803,6 +904,8 @@ async function contributeClientHealthUnbounded(kind, deps, failureReason) {
803
904
  failureReason,
804
905
  syncEngine,
805
906
  daemonCliVersion,
907
+ daemon,
908
+ daemonUnit,
806
909
  });
807
910
  if (!heartbeat)
808
911
  return;
@@ -885,7 +885,10 @@ export function trustGrokProjectHooks(hqRoot, deps = DEFAULT_DEPS) {
885
885
  let wantJson;
886
886
  if (grok && grok.events.length > 0) {
887
887
  try {
888
- candidate?.commitStable?.(acceptedHosts);
888
+ if (candidate?.commitStable)
889
+ candidate.commitStable(acceptedHosts);
890
+ else
891
+ candidate?.recordAccepted?.(acceptedHosts);
889
892
  }
890
893
  catch (error) {
891
894
  return { runtime: 'grok', status: 'failed', trusted: 0, reason: errorMessage(error) };
@@ -985,6 +988,9 @@ export function trustGrokProjectHooks(hqRoot, deps = DEFAULT_DEPS) {
985
988
  const target = (deps.coreNextTarget ?? ((h) => coreNextTargetOrWarn(h)))(home);
986
989
  // Only the events the new core covers in full on Grok switch.
987
990
  const grok = forHost(target, hqRoot, 'grok');
991
+ if (grok && grok.events.length > 0) {
992
+ getCoreNextCandidate(target)?.recordAccepted?.(['grok']);
993
+ }
988
994
  wantJson = grok || platform === 'win32'
989
995
  ? grokBridgeJson(fs.readFileSync(sourceBridgeJson, 'utf8'), hqRoot, grok, platform, home)
990
996
  : undefined;
@@ -1,14 +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
+ import { type CanaryHost } from '../lib/hook-engine/canary-gate.js';
3
4
  export { CORE_NEXT_FLAG, coreNextEnabled } from './core-next-flag.js';
4
5
  export { coreNextStrictReason, ENGINE_STRICT_ENV, ENGINE_STRICT_FILE } from './core-next-kill.js';
5
- /** Name of the release-stable link next to the pinned engine versions. */
6
- export declare const STABLE_LINK_NAME = "stable";
7
- /** Record of canary-accepted hook engines committed to `stable`, under the home folder. */
8
- export declare const ACCEPTED_HOOK_ENGINE_RECORD: string;
9
- /** Schema of [`ACCEPTED_HOOK_ENGINE_RECORD`]. */
10
- export declare const ACCEPTED_HOOK_ENGINE_SCHEMA = "hq.accepted-hook-engine.v1";
11
- export type CoreNextHost = 'claude' | 'codex' | 'grok' | 'fleet-local' | 'agents-v2' | 'antigravity';
6
+ export { ACCEPTED_HOOK_ENGINE_RECORD, ACCEPTED_HOOK_ENGINE_SCHEMA, STABLE_LINK_NAME, StableDowngradeRefused, linkStableEngine, readAcceptedHookEngineRecord, stableEnginePath, type AcceptedHookEngineEntry, type AcceptedHookEngineRecord, type CoreNextHost, type LinkStableEngineOptions, } from '../lib/hook-engine/stable-link.js';
7
+ import { type CoreNextHost } from '../lib/hook-engine/stable-link.js';
12
8
  /**
13
9
  * `project`: the HQ root's own registration, always answers.
14
10
  * `global`: the user-scope Claude Code entry; answers nothing inside an HQ
@@ -44,6 +40,11 @@ export interface CoreNextCandidateMeta {
44
40
  pinnedEngine: string;
45
41
  engineVersion: string;
46
42
  commitStable?: (acceptedHosts?: readonly CoreNextHost[]) => string;
43
+ /**
44
+ * Record `acceptedHosts` in `<home>/.hq/bin/hq-hook/accepted-engine.json`
45
+ * after `stable` is linked and a real host canary has passed on this machine.
46
+ */
47
+ recordAccepted?: (acceptedHosts?: readonly CoreNextHost[]) => void;
47
48
  }
48
49
  /** Read the candidate engine metadata attached by [`coreNextTarget`], if any. */
49
50
  export declare function getCoreNextCandidate(target: CoreNextTarget | null | undefined): CoreNextCandidateMeta | undefined;
@@ -84,16 +85,6 @@ export declare function probeEngine(engine: string): EngineCapabilities;
84
85
  * new-core registration with nothing to run.
85
86
  */
86
87
  export declare function checkStableEngine(stable: string, pinned: string): void;
87
- /** The stable path that stands for a pinned engine path. */
88
- export declare function stableEnginePath(pinned: string, home: string): string;
89
- /**
90
- * Point `<home>/.hq/bin/hq-hook/stable` at the pinned engine's version folder
91
- * and return the stable engine path. The link is replaced by rename, so a
92
- * planted file at the temporary name or the link itself is never followed. A
93
- * `stable` that is a real folder (not a link) is someone else's and is left
94
- * alone: the call fails and the caller keeps the current registrations.
95
- */
96
- export declare function linkStableEngine(pinned: string, home: string, platform?: NodeJS.Platform): string;
97
88
  export interface CoreNextOptions {
98
89
  platform?: NodeJS.Platform;
99
90
  /** Reads the engine's capabilities; `probeEngine` by default. */
@@ -130,22 +121,6 @@ export interface CoreNextEngine {
130
121
  * writes. Both fail when the pinned bundle or the stable link is wrong.
131
122
  */
132
123
  export declare function resolveCoreNextEngine(home: string, options: CoreNextEngineOptions): CoreNextEngine;
133
- /** One canary-accepted engine recorded when `commitStable` moved `stable` to it. */
134
- export interface AcceptedHookEngineEntry {
135
- engineVersion: string;
136
- pinnedEngine: string;
137
- acceptedAt: string;
138
- hosts: CoreNextHost[];
139
- }
140
- export interface AcceptedHookEngineRecord {
141
- schema: typeof ACCEPTED_HOOK_ENGINE_SCHEMA;
142
- engines: Record<string, AcceptedHookEngineEntry>;
143
- }
144
- /**
145
- * Read `<home>/.hq/bin/hq-hook/accepted-engine.json`; null when absent,
146
- * unreadable, invalid, or writable by another user.
147
- */
148
- export declare function readAcceptedHookEngineRecord(home: string, platform?: NodeJS.Platform): AcceptedHookEngineRecord | null;
149
124
  /**
150
125
  * Record `pinned` (`engineVersion`) as canary-accepted for `hosts` after
151
126
  * committing `<home>/.hq/bin/hq-hook/stable`. Merges `hosts` when the same
@@ -183,7 +158,9 @@ export declare function existingAcceptedStableHookEngine(home: string, options:
183
158
  * Windows), regardless of `core.next`. When the npm engine package is gone,
184
159
  * reuses an existing runnable `stable` or relinks `stable` from an already-
185
160
  * pinned copy of this CLI's version under `<home>/.hq/bin/hq-hook/<version>`.
186
- * Returns null when no usable engine exists on disk.
161
+ * When `stable` names a newer engine that still runs, it is kept and returned
162
+ * (the link never moves back on its own). Returns null when no usable engine
163
+ * exists on disk.
187
164
  */
188
165
  export declare function ensureStableHookEngine(home: string, options?: {
189
166
  platform?: NodeJS.Platform;
@@ -238,7 +215,7 @@ export declare function coreNextTarget(home: string, env?: NodeJS.ProcessEnv, op
238
215
  * capable event. [`coreNextTarget`] builds its target here, and `hq doctor`
239
216
  * uses it to ask the same questions without installing anything.
240
217
  */
241
- export declare function coreNextTargetFor(home: string, env: NodeJS.ProcessEnv, stable: string, caps: EngineCapabilities, platform?: NodeJS.Platform, warn?: (message: string) => void): CoreNextTarget | null;
218
+ export declare function coreNextTargetFor(home: string, env: NodeJS.ProcessEnv, stable: string, caps: EngineCapabilities, platform?: NodeJS.Platform, warn?: (message: string) => void, onCanaryPassed?: (host: CanaryHost) => void): CoreNextTarget | null;
242
219
  /**
243
220
  * Set by `hq reindex --from-hook` (a reindex the daemon runs for a hook's
244
221
  * request note): the host canary gate then keeps every host on the core it is
@@ -65,12 +65,8 @@ import { CORE_NEXT_FLAG, coreNextEnabled } from './core-next-flag.js';
65
65
  export { coreNextStrictReason, ENGINE_STRICT_ENV, ENGINE_STRICT_FILE } from './core-next-kill.js';
66
66
  import { coreNextStrictReason, ENGINE_STRICT_FILE } from './core-next-kill.js';
67
67
  const HOOK_ENGINE_LOG_RELATIVE = path.join('.hq', 'logs', 'hook-engine.jsonl');
68
- /** Name of the release-stable link next to the pinned engine versions. */
69
- export const STABLE_LINK_NAME = 'stable';
70
- /** Record of canary-accepted hook engines committed to `stable`, under the home folder. */
71
- export const ACCEPTED_HOOK_ENGINE_RECORD = path.join('.hq', 'bin', 'hq-hook', 'accepted-engine.json');
72
- /** Schema of [`ACCEPTED_HOOK_ENGINE_RECORD`]. */
73
- export const ACCEPTED_HOOK_ENGINE_SCHEMA = 'hq.accepted-hook-engine.v1';
68
+ export { ACCEPTED_HOOK_ENGINE_RECORD, ACCEPTED_HOOK_ENGINE_SCHEMA, STABLE_LINK_NAME, StableDowngradeRefused, linkStableEngine, readAcceptedHookEngineRecord, stableEnginePath, } from '../lib/hook-engine/stable-link.js';
69
+ import { ACCEPTED_HOOK_ENGINE_RECORD, ACCEPTED_HOOK_ENGINE_SCHEMA, STABLE_LINK_NAME, StableDowngradeRefused, hookEngineDir, linkStableEngine, readAcceptedHookEngineRecord, stableEnginePath, } from '../lib/hook-engine/stable-link.js';
74
70
  const coreNextCandidates = new WeakMap();
75
71
  /** Read the candidate engine metadata attached by [`coreNextTarget`], if any. */
76
72
  export function getCoreNextCandidate(target) {
@@ -192,113 +188,6 @@ export function checkStableEngine(stable, pinned) {
192
188
  if (!fs.statSync(resolved).isFile())
193
189
  throw new Error(`${resolved} is not a file`);
194
190
  }
195
- function hookEngineDir(home) {
196
- return path.join(home, '.hq', 'bin', 'hq-hook');
197
- }
198
- /** The stable path that stands for a pinned engine path. */
199
- export function stableEnginePath(pinned, home) {
200
- const relative = path.relative(hookEngineDir(home), pinned);
201
- const [, ...rest] = relative.split(/[\\/]/);
202
- if (relative.startsWith('..') || path.isAbsolute(relative) || rest.length === 0) {
203
- throw new Error(`hook engine ${pinned} is not under ${hookEngineDir(home)}`);
204
- }
205
- return path.join(hookEngineDir(home), STABLE_LINK_NAME, ...rest);
206
- }
207
- /**
208
- * Point `<home>/.hq/bin/hq-hook/stable` at the pinned engine's version folder
209
- * and return the stable engine path. The link is replaced by rename, so a
210
- * planted file at the temporary name or the link itself is never followed. A
211
- * `stable` that is a real folder (not a link) is someone else's and is left
212
- * alone: the call fails and the caller keeps the current registrations.
213
- */
214
- export function linkStableEngine(pinned, home, platform = process.platform) {
215
- const root = hookEngineDir(home);
216
- const relative = path.relative(root, pinned).split(/[\\/]/);
217
- const version = relative[0];
218
- if (!version || version === '..' || version === STABLE_LINK_NAME || path.isAbsolute(path.relative(root, pinned))) {
219
- throw new Error(`hook engine ${pinned} is not under ${root}`);
220
- }
221
- const stable = path.join(root, STABLE_LINK_NAME);
222
- // Store rule v2: every path component this follows or creates under the home
223
- // folder is a real folder of this user that group and others cannot write:
224
- // .hq, .hq/bin, .hq/bin/hq-hook, the version folder and any folder below it
225
- // up to the engine, and the engine file itself.
226
- const components = [path.join(home, '.hq'), path.join(home, '.hq', 'bin'), root];
227
- for (let i = 0; i < relative.length - 1; i += 1)
228
- components.push(path.join(root, ...relative.slice(0, i + 1)));
229
- for (const component of components)
230
- checkOwnedEntry(component, 'folder', platform);
231
- checkOwnedEntry(pinned, 'file', platform);
232
- // Windows creates a junction, which needs an absolute target; elsewhere the
233
- // link is relative so it names the version folder beside it.
234
- const target = platform === 'win32' ? path.join(root, version) : version;
235
- let current;
236
- try {
237
- current = fs.lstatSync(stable);
238
- }
239
- catch (error) {
240
- if (error.code !== 'ENOENT')
241
- throw error;
242
- }
243
- if (current && !current.isSymbolicLink())
244
- throw new Error(`${stable} exists and is not a link; leaving it in place`);
245
- if (current && pointsAt(stable, path.join(root, version)))
246
- return stableEnginePath(pinned, home);
247
- if (platform === 'win32') {
248
- // A junction cannot be renamed over another. A running engine keeps its
249
- // own image open, which the junction does not hold.
250
- if (current) {
251
- try {
252
- fs.unlinkSync(stable);
253
- }
254
- catch {
255
- fs.rmdirSync(stable);
256
- }
257
- }
258
- fs.symlinkSync(target, stable, 'junction');
259
- }
260
- else {
261
- const staged = path.join(root, `.${STABLE_LINK_NAME}.${process.pid}.tmp`);
262
- try {
263
- fs.unlinkSync(staged);
264
- }
265
- catch (error) {
266
- if (error.code !== 'ENOENT')
267
- throw error;
268
- }
269
- fs.symlinkSync(target, staged);
270
- try {
271
- fs.renameSync(staged, stable);
272
- }
273
- catch (error) {
274
- try {
275
- fs.unlinkSync(staged);
276
- }
277
- catch { /* already gone */ }
278
- throw error;
279
- }
280
- }
281
- return stableEnginePath(pinned, home);
282
- }
283
- /** A real folder or file (not a link) of this user that group and others cannot write. */
284
- function checkOwnedEntry(entry, kind, platform) {
285
- const stat = fs.lstatSync(entry);
286
- if (stat.isSymbolicLink() || (kind === 'folder' ? !stat.isDirectory() : !stat.isFile()))
287
- throw new Error(`${entry} is not a ${kind}`);
288
- if (typeof process.getuid === 'function' && stat.uid !== process.getuid())
289
- throw new Error(`${entry} is not owned by this user`);
290
- if (platform !== 'win32' && (stat.mode & 0o022) !== 0)
291
- throw new Error(`${entry} is writable by group or others`);
292
- }
293
- /** True when the link resolves to `folder` (Windows reports junction targets in its own spelling). */
294
- function pointsAt(link, folder) {
295
- try {
296
- return fs.realpathSync(link) === fs.realpathSync(folder);
297
- }
298
- catch {
299
- return false;
300
- }
301
- }
302
191
  /** Why this home stays on shell registrations, or null when engine selection may run. */
303
192
  export function coreNextOffReason(home, env, platform) {
304
193
  if (platform === 'win32')
@@ -362,54 +251,6 @@ function isRunnableEngineFile(filePath, platform) {
362
251
  return null;
363
252
  }
364
253
  }
365
- /**
366
- * Read `<home>/.hq/bin/hq-hook/accepted-engine.json`; null when absent,
367
- * unreadable, invalid, or writable by another user.
368
- */
369
- export function readAcceptedHookEngineRecord(home, platform = process.platform) {
370
- const file = path.join(home, ACCEPTED_HOOK_ENGINE_RECORD);
371
- let text;
372
- try {
373
- checkOwnedEntry(file, 'file', platform);
374
- text = fs.readFileSync(file, 'utf8');
375
- }
376
- catch {
377
- return null;
378
- }
379
- let doc;
380
- try {
381
- doc = JSON.parse(text);
382
- }
383
- catch {
384
- return null;
385
- }
386
- const rec = doc;
387
- if (!rec || rec.schema !== ACCEPTED_HOOK_ENGINE_SCHEMA || !rec.engines || typeof rec.engines !== 'object' || Array.isArray(rec.engines)) {
388
- return null;
389
- }
390
- const engines = {};
391
- for (const [key, raw] of Object.entries(rec.engines)) {
392
- if (!raw || typeof raw !== 'object' || Array.isArray(raw))
393
- continue;
394
- const entry = raw;
395
- if (typeof entry.engineVersion !== 'string' || !entry.engineVersion)
396
- continue;
397
- if (typeof entry.pinnedEngine !== 'string' || !entry.pinnedEngine)
398
- continue;
399
- if (!Array.isArray(entry.hosts))
400
- continue;
401
- const hosts = entry.hosts.filter((h) => typeof h === 'string');
402
- if (hosts.length === 0)
403
- continue;
404
- engines[key] = {
405
- engineVersion: entry.engineVersion,
406
- pinnedEngine: entry.pinnedEngine,
407
- acceptedAt: typeof entry.acceptedAt === 'string' ? entry.acceptedAt : '',
408
- hosts,
409
- };
410
- }
411
- return { schema: ACCEPTED_HOOK_ENGINE_SCHEMA, engines };
412
- }
413
254
  /**
414
255
  * Record `pinned` (`engineVersion`) as canary-accepted for `hosts` after
415
256
  * committing `<home>/.hq/bin/hq-hook/stable`. Merges `hosts` when the same
@@ -510,16 +351,32 @@ export function existingAcceptedStableHookEngine(home, options) {
510
351
  * Windows), regardless of `core.next`. When the npm engine package is gone,
511
352
  * reuses an existing runnable `stable` or relinks `stable` from an already-
512
353
  * pinned copy of this CLI's version under `<home>/.hq/bin/hq-hook/<version>`.
513
- * Returns null when no usable engine exists on disk.
354
+ * When `stable` names a newer engine that still runs, it is kept and returned
355
+ * (the link never moves back on its own). Returns null when no usable engine
356
+ * exists on disk.
514
357
  */
515
358
  export function ensureStableHookEngine(home, options = {}) {
516
359
  const platform = options.platform ?? process.platform;
517
360
  const installed = installHookEngine(options.lookup ? { ...options.lookup, home, platform } : { home, platform });
518
- if (installed) {
519
- const stable = linkStableEngine(installed, home, platform);
520
- checkStableEngine(stable, installed);
521
- return stable;
522
- }
361
+ // `stable` naming a newer engine that still runs (this CLI was downgraded on
362
+ // purpose, or an older one is running): keep using that engine.
363
+ const linkOrKeepNewer = (engine) => {
364
+ try {
365
+ const stable = linkStableEngine(engine, home, platform);
366
+ checkStableEngine(stable, engine);
367
+ return stable;
368
+ }
369
+ catch (error) {
370
+ if (!(error instanceof StableDowngradeRefused))
371
+ throw error;
372
+ const existing = existingStableHookEngine(home, { platform });
373
+ if (!existing)
374
+ throw error;
375
+ return existing;
376
+ }
377
+ };
378
+ if (installed)
379
+ return linkOrKeepNewer(installed);
523
380
  const existing = existingStableHookEngine(home, { platform });
524
381
  if (existing)
525
382
  return existing;
@@ -531,9 +388,7 @@ export function ensureStableHookEngine(home, options = {}) {
531
388
  for (const candidate of engineBinaryCandidates(pinnedDir, platform)) {
532
389
  if (!isRunnableEngineFile(candidate, platform))
533
390
  continue;
534
- const stable = linkStableEngine(candidate, home, platform);
535
- checkStableEngine(stable, candidate);
536
- return stable;
391
+ return linkOrKeepNewer(candidate);
537
392
  }
538
393
  }
539
394
  return null;
@@ -637,20 +492,30 @@ export function coreNextTarget(home, env = process.env, options = {}) {
637
492
  probe: options.probe,
638
493
  deferLink: options.deferLink,
639
494
  });
640
- const target = coreNextTargetFor(home, env, stable, caps, platform, options.warn);
495
+ const passedCanaryHosts = new Set();
496
+ const target = coreNextTargetFor(home, env, stable, caps, platform, options.warn, (host) => {
497
+ passedCanaryHosts.add(host);
498
+ });
641
499
  if (!target)
642
500
  return null;
501
+ const recordAccepted = (acceptedHosts) => {
502
+ if (!acceptedHosts || acceptedHosts.length === 0 || canaryGateSkipped(env))
503
+ return;
504
+ const verified = acceptedHosts.filter((host) => CANARY_HOSTS.includes(host) && passedCanaryHosts.has(host));
505
+ if (verified.length === 0)
506
+ return;
507
+ recordAcceptedHookEngine(home, pinned, caps.version, verified, platform);
508
+ };
643
509
  coreNextCandidates.set(target, {
644
510
  pinnedEngine: pinned,
645
511
  engineVersion: caps.version,
512
+ recordAccepted,
646
513
  ...(options.deferLink
647
514
  ? {
648
515
  commitStable: (acceptedHosts) => {
649
516
  const linked = linkStableEngine(pinned, home, platform);
650
517
  checkStableEngine(linked, pinned);
651
- if (acceptedHosts && acceptedHosts.length > 0 && !canaryGateSkipped(env)) {
652
- recordAcceptedHookEngine(home, pinned, caps.version, acceptedHosts, platform);
653
- }
518
+ recordAccepted(acceptedHosts);
654
519
  return linked;
655
520
  },
656
521
  }
@@ -664,7 +529,7 @@ export function coreNextTarget(home, env = process.env, options = {}) {
664
529
  * capable event. [`coreNextTarget`] builds its target here, and `hq doctor`
665
530
  * uses it to ask the same questions without installing anything.
666
531
  */
667
- export function coreNextTargetFor(home, env, stable, caps, platform = process.platform, warn) {
532
+ export function coreNextTargetFor(home, env, stable, caps, platform = process.platform, warn, onCanaryPassed) {
668
533
  const events = capableEvents(caps);
669
534
  if (!events.length)
670
535
  return null;
@@ -673,7 +538,7 @@ export function coreNextTargetFor(home, env, stable, caps, platform = process.pl
673
538
  events,
674
539
  covers: caps.covers ?? {},
675
540
  ...(caps.registrationHosts ? { registrationHosts: caps.registrationHosts } : {}),
676
- canary: hostCanaryGate(home, env, caps.version, platform, warn),
541
+ canary: hostCanaryGate(home, env, caps.version, platform, warn, onCanaryPassed),
677
542
  }, env);
678
543
  }
679
544
  const warned = new Set();
@@ -721,7 +586,7 @@ function appendStrictCanaryLog(home, root, host, version, reason, strict) {
721
586
  // Best-effort engine log; the stderr error still surfaces the failure.
722
587
  }
723
588
  }
724
- function hostCanaryGate(home, env, version, platform, warn) {
589
+ function hostCanaryGate(home, env, version, platform, warn, onCanaryPassed) {
725
590
  const strictLogged = new Set();
726
591
  const logStrictOnce = (root, host, reason, strict) => {
727
592
  const key = `${root}\0${host}`;
@@ -752,6 +617,8 @@ function hostCanaryGate(home, env, version, platform, warn) {
752
617
  : `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);
753
618
  }
754
619
  }
620
+ if (current && gate.allowed && !gate.skipped)
621
+ onCanaryPassed?.(host);
755
622
  return current;
756
623
  }
757
624
  if (gate.skipped) {
@@ -765,6 +632,9 @@ function hostCanaryGate(home, env, version, platform, warn) {
765
632
  }
766
633
  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);
767
634
  }
635
+ else {
636
+ onCanaryPassed?.(host);
637
+ }
768
638
  return gate.allowed;
769
639
  };
770
640
  }
@@ -1,4 +1,5 @@
1
1
  import type { CognitoAuthConfig, CognitoTokens } from "@indigoai-us/hq-cloud";
2
+ export declare function usesHqChoicePage(config: CognitoAuthConfig, env?: NodeJS.ProcessEnv): boolean;
2
3
  /** Keep desktop login unchanged; manual login uses the same PKCE loopback flow. */
3
4
  export declare function loginWithBrowserPreference(requested: CognitoAuthConfig, browser?: boolean): Promise<CognitoTokens>;
4
5
  //# sourceMappingURL=login-browser.d.ts.map