@indigoai-us/hq-cli 5.345.269 → 5.345.270

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.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,31 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## [5.345.270] — 2026-11-30
6
+ - Fixed: wired `crates/hq-hook/tests/win_store.rs` into the `hq-hook.yml` Windows "Unit and pipe tests" list (and release archive shards), the PR test list, and the Windows PR scope selector for `src/spool`.
7
+ - Change `hq-hook Windows baseline` schedule from hourly (`47 * * * *`) to once nightly at 07:47 UTC (`47 7 * * *`, outside the 13:00–03:00 UTC train window) and skip scheduled runs when the `main` commit or its git tree already has a green `hq-hook Windows tests (Beaker)` result from a `train/**` run (`covered by train <run id>`, fail-closed on ambiguity or API errors).
8
+ - Run `hq-hook` Windows CI jobs only when the diff can affect Windows or the hook crate (failing closed on unreadable diffs or unknown paths), and let `scripts/ci/batch-train.py` honor the not-relevant verdict for non-Windows batches.
9
+ - Update hook-engine architecture, host-canary, and replay documentation to point at native hq-hook commands instead of removed US-027 shell adapters, and sync scripts/function-manifest.yaml with removed scripts from hq-core-staging main.
10
+ - `hq-hook`: isolate inherited `GIT_CONFIG_GLOBAL` runner overrides in `grok_stop_observe` and `us027_teardown` tests while keeping explicit refusal regression coverage.
11
+ - Avoid quadratic per-piece vector cloning during Bash word expansion in `hq-hook`, keeping long multi-piece quoted words well within the linear scan budget on Windows.
12
+ - Enable the full `injector` parity corpus tests on Windows in `hq-hook` (US-022 c1 preflight).
13
+ - Record canary-accepted hook engines in `~/.hq/bin/hq-hook/accepted-engine.json` on the non-native `core.next` registration paths (`hq reindex`, `hq install --global`, and Grok hook trust) after a real host canary pass so immediate `stable` link roll-back healing works on machines whose registrations use that path. Paths that skip or fail the canary still write no acceptance record.
14
+ - Fixed: `hq signals` extract on no-shell runtimes now accepts structured JSON candidates (`{"candidates":[{"kind","type","body"}]}`) and builds the pinned candidate writer argv on the host, preserving arbitrary quotes, `$`, backticks, and newlines in candidate bodies and dropping only individual invalid candidates instead of failing the whole item.
15
+ - Keep `~/.hq/bin/hq-hook/stable` from moving back to an older hook engine while the newer engine it names still runs; native-only and Windows roots keep using that newer engine after a CLI downgrade. The start-up heal relinks a rolled-back link at once (before the reindex) when the pinned engine was canary-accepted on this machine. An operator rollback to an older engine needs an explicit downgrade option that no command offers yet.
16
+ - `hq reindex` can now move Codex and Grok Build SessionStart and UserPromptSubmit to the native hook core when an HQ has personal, pack or company hooks for those events. The native core runs those hooks as the Codex and Grok adapters did, with the same payload, variables and advisory handling.
17
+ - Changed: the host canary record shipped with the CLI is refreshed for the 5.345.270 release build.
18
+ - The native Stop now accepts the hq-core v16.0.53 `master-hook.sh`. Before, it refused every Stop on a v16.0.53 core. It also writes the environment-id alias entry that this `master-hook.sh` records on every hook event, as the native PreToolUse already did. v16.0.51 and v16.0.52 roots stay on the shell Stop.
19
+ - Reduce native `UserPromptSubmit` hook latency in `hq-hook`: check the daemon `lanes_monitor` state before scanning `workspace/lanes/lanes`, evaluate policy triggers and frequency/retrieval lookups lazily without per-policy regex or heap churn, skip `Held::lock` directory creation on `UserPromptSubmit` for hosts that never hold reminders (Claude Code and Codex) when no held reminder or lock exists on disk, share a per-chain 1 MiB regular-file/symlink read cache for `hook-registry.json` and `hook-gate.sh` (following symlinks like bash `[ -f ]`, while a FIFO `hook-gate.sh` fails closed natively where bash would block), read listed policy files once across skill and brief scans, filter non-policy directory entries before allocating during macOS bulk manifest scans, and accept `hook-lib.sh` `436493e3` (`hq-core` v16.0.52) in `skill_command_script::classify`.
20
+ - Resolve `for`/`select` loop variables strictly inside closed `do ... done` bodies in `mandatory-scope-authorizer` even when the loop follows `&&`/`||` (`evt-2df47d001eec4541`), while keeping post-`done`, cross-company, and computed/glob loop cases refused.
21
+ - Record `mandatory-scope-authorizer` fail-closed refusal on relative operands after `.`/`source` (`evt-d1c0d86c3e1552f9`) in the `US-012` intended-differences ledger with a pinning test.
22
+ - Update Windows GUI no-console probe (`GuiProbe.cs` and `no-console.ps1`) from the removed legacy `hq-hook <Event>` launcher form to `hq-hook run --host claude <Event> --hq-root <root>`, and use `CREATE_NO_WINDOW` instead of `DETACHED_PROCESS` in `spawn_windows` so MSYS2 `bash.exe` starts with a hidden console and never flashes a visible window when running folder hooks.
23
+ - Test: pin original file descriptors in `injector::held` atomic-replace unit tests so Linux filesystems cannot reuse unlinked inodes during multi-rename rearm checks.
24
+ - Fixed: `codex_session_start_parity` and `grok_session_start_bind` now serialize adapter runs across `cargo nextest` worker processes using a shared advisory file lock.
25
+ - Test: avoid 120 redundant `fsyncSync` snapshot rewrites in the one-hour `shared-flag-reads.test.ts` poller test so it stays fast and deterministic under CI disk contention.
26
+ - Fixed: split `smart-ci` fixture replay crash-recovery loop in `intake.test.ts` into per-case parameterized tests so each commit-kill case runs independently within the default Vitest timeout under CI disk contention.
27
+ - Test-only: verify the beta.105 10-second folder-hook cut in `stop_beta105::a_folder_hook_cut_at_the_beta105_ten_second_limit_is_refused` with start/finish marker files instead of host-speed-sensitive wall-clock assertions.
28
+ - Expand an expandable 8.3 short-name `HOME` on Windows in `grok_adapter` so non-credential calls are allowed while credential paths under both short and long spellings stay refused (split from #3921 and #4050).
29
+
5
30
  ## [5.345.269] — 2026-11-29
6
31
  - Shard `.github/workflows/hq-hook.yml` self-hosted Windows (`matrix.beaker`) `Unit and pipe tests` across 6 parallel `hq-windows` runners using a prebuilt `cargo nextest` archive (`windows-build-archive` + `windows-test-shard`), cutting release-tag Windows test wall time while preserving full target parity and all `build` job release duties.
7
32
  - Run the hq-hook Windows baseline shard and join jobs on the AWS Windows runners: they no longer ask for the `beaker` label, so they use the same `self-hosted, Windows, X64, hq-windows` label set as the PR and train Windows jobs they are compared with.
@@ -1,24 +1,24 @@
1
1
  {
2
2
  "schema": "hq.host-canary-release.v1",
3
- "cliVersion": "5.345.269",
3
+ "cliVersion": "5.345.270",
4
4
  "hosts": {
5
5
  "claude": [
6
6
  {
7
7
  "passed": true,
8
- "at": "2026-11-29T18:12:55.433Z",
9
- "engineVersion": "0.3.1+hq.5.345.269.src.59ee74f3c4e4594944cf3944b26360e7060f2c54a18817cb87fa3cfddc33163d",
8
+ "at": "2026-11-30T02:02:55.216Z",
9
+ "engineVersion": "0.3.1+hq.5.345.270.src.fb37f49ebae3604d89308abc7685e866c6c4e37fa36961d5511730cf3627ca96",
10
10
  "gateSha256": "a2879dfe692233f5953bac86672947bbd82f3c5247292f3efcb80f16c3d2c6b1"
11
11
  },
12
12
  {
13
13
  "passed": true,
14
- "at": "2026-11-29T18:13:15.465Z",
15
- "engineVersion": "0.3.1+hq.5.345.269.src.59ee74f3c4e4594944cf3944b26360e7060f2c54a18817cb87fa3cfddc33163d",
14
+ "at": "2026-11-30T02:03:13.811Z",
15
+ "engineVersion": "0.3.1+hq.5.345.270.src.fb37f49ebae3604d89308abc7685e866c6c4e37fa36961d5511730cf3627ca96",
16
16
  "gateSha256": "ca58a94859eae0a345c11c8d9c59303eb76350dc1cf223391037d21979c28718"
17
17
  },
18
18
  {
19
19
  "passed": true,
20
- "at": "2026-11-29T18:13:51.865Z",
21
- "engineVersion": "0.3.1+hq.5.345.269.src.59ee74f3c4e4594944cf3944b26360e7060f2c54a18817cb87fa3cfddc33163d",
20
+ "at": "2026-11-30T02:03:49.977Z",
21
+ "engineVersion": "0.3.1+hq.5.345.270.src.fb37f49ebae3604d89308abc7685e866c6c4e37fa36961d5511730cf3627ca96",
22
22
  "gateSha256": "ecdbab7c2e0a1d94eb9c98f15e760390f215bc7115a217ded24b4275322722d2"
23
23
  }
24
24
  ]
@@ -384,7 +384,8 @@
384
384
  ".claude/hooks/master-hook.sh": [
385
385
  "1a2439aee50652c5143ccd18561a0aa84a1e94848d02c1aa1c99157f70023f29",
386
386
  "d5049d5fb38d2b33467d493a4a136df8f6d9021c29e722df0d1e6a17d7f452ab",
387
- "774bca73a2e806b4d9ad96b803525bdf25afd2265d63c9216881aa4ced403f16"
387
+ "774bca73a2e806b4d9ad96b803525bdf25afd2265d63c9216881aa4ced403f16",
388
+ "f9a32c25f5984856a1bb91a7914495577e505c42a8c02831acf8faf049a9a806"
388
389
  ]
389
390
  }
390
391
  }
@@ -186,6 +186,14 @@ export function reconcileHookRegistrations(root, home = homedir(), env = process
186
186
  claudeProjectNext = claudeProjectTarget(rawCoreNext, claudeNext, root, env);
187
187
  codexNext = forHost(rawCoreNext, root, 'codex', env);
188
188
  antigravityNext = rawCoreNext;
189
+ const acceptedHosts = [];
190
+ if (claudeNext || claudeProjectNext)
191
+ acceptedHosts.push('claude');
192
+ if (codexNext)
193
+ acceptedHosts.push('codex');
194
+ if (acceptedHosts.length > 0) {
195
+ getCoreNextCandidate(rawCoreNext)?.recordAccepted?.(acceptedHosts);
196
+ }
189
197
  }
190
198
  else if (rawCoreNext) {
191
199
  const candidate = getCoreNextCandidate(rawCoreNext);
@@ -1,6 +1,7 @@
1
1
  /**
2
2
  * After an update, heal the `stable` link core.next registrations name by
3
- * re-running the gated reconcile, never by moving the link directly.
3
+ * re-running the gated reconcile; the heal moves the link directly only to
4
+ * undo a roll-back (below).
4
5
  *
5
6
  * `npm install -g @indigoai-us/hq-cli` pins the new engine and rewrites the
6
7
  * `current` pointer. `stable` keeps naming the previous engine until
@@ -15,6 +16,19 @@
15
16
  *
16
17
  * The postinstall moves nothing ([`staleStableEngine`] only reports).
17
18
  *
19
+ * Two cases do not wait for the reindex, so a code-complete engine never flips
20
+ * back:
21
+ * - Roll-back: `stable` names an older engine than the pinned one, and the
22
+ * pinned engine is recorded in the accepted-engine record
23
+ * ([`isAcceptedHookEngine`]): it already passed the host canary gate on this
24
+ * machine. Something older (an old hq-cli run with the real home) moved the
25
+ * link back below it. The heal relinks to the pinned engine at once, then
26
+ * starts the reindex as usual. A pinned engine with no acceptance record waits
27
+ * for the gated reindex, as after any update.
28
+ * - `stable` names a newer engine than this CLI pins, and its version folder is
29
+ * still there: an older CLI is running. The heal starts nothing, so it cannot
30
+ * move the link back.
31
+ *
18
32
  * The roots come from the `--hq-root` arguments in the user-scope hook files,
19
33
  * so this starts an unattended `hq reindex` in any folder named there. That is
20
34
  * no new boundary: only someone who can already write those files (and so
@@ -60,6 +74,8 @@ export interface StableHealResult {
60
74
  roots: string[];
61
75
  /** Why no reindex was started, when stale and none was. */
62
76
  skipped?: string;
77
+ /** The engine version `stable` was moved back up to before any reindex (a roll-back healed at once). */
78
+ relinked?: string;
63
79
  }
64
80
  /**
65
81
  * The HQ roots to reconcile: each root a user-scope hook file (Claude Code,
@@ -1,6 +1,7 @@
1
1
  /**
2
2
  * After an update, heal the `stable` link core.next registrations name by
3
- * re-running the gated reconcile, never by moving the link directly.
3
+ * re-running the gated reconcile; the heal moves the link directly only to
4
+ * undo a roll-back (below).
4
5
  *
5
6
  * `npm install -g @indigoai-us/hq-cli` pins the new engine and rewrites the
6
7
  * `current` pointer. `stable` keeps naming the previous engine until
@@ -15,6 +16,19 @@
15
16
  *
16
17
  * The postinstall moves nothing ([`staleStableEngine`] only reports).
17
18
  *
19
+ * Two cases do not wait for the reindex, so a code-complete engine never flips
20
+ * back:
21
+ * - Roll-back: `stable` names an older engine than the pinned one, and the
22
+ * pinned engine is recorded in the accepted-engine record
23
+ * ([`isAcceptedHookEngine`]): it already passed the host canary gate on this
24
+ * machine. Something older (an old hq-cli run with the real home) moved the
25
+ * link back below it. The heal relinks to the pinned engine at once, then
26
+ * starts the reindex as usual. A pinned engine with no acceptance record waits
27
+ * for the gated reindex, as after any update.
28
+ * - `stable` names a newer engine than this CLI pins, and its version folder is
29
+ * still there: an older CLI is running. The heal starts nothing, so it cannot
30
+ * move the link back.
31
+ *
18
32
  * The roots come from the `--hq-root` arguments in the user-scope hook files,
19
33
  * so this starts an unattended `hq reindex` in any folder named there. That is
20
34
  * no new boundary: only someone who can already write those files (and so
@@ -32,6 +46,7 @@ import * as path from 'node:path';
32
46
  import { CORE_NEXT_LINK, hqRootArgument, userHookSettingsFile } from './registration-identity.js';
33
47
  import { staleStableEngine } from './resolve.js';
34
48
  import { resolveDefaultHqRoot } from '../../utils/hq-root-resolver.js';
49
+ import { appendStableHealLog, compareEngineVersions, engineVersionOf, isAcceptedHookEngine, linkStableEngine, stableLinkVersion } from './stable-link.js';
35
50
  /** Set in the reindex the heal starts, so that process does not start another. */
36
51
  export const STABLE_HEAL_ENV = 'HQ_STABLE_HEAL';
37
52
  /**
@@ -175,16 +190,38 @@ export function healStableEngine(options = {}) {
175
190
  if (!stale)
176
191
  return { stale: null, roots: [] };
177
192
  const now = (options.now ?? Date.now)();
193
+ const linked = stableLinkVersion(home);
194
+ const pinnedVersion = engineVersionOf(stale.pinned, home);
195
+ const order = linked && pinnedVersion ? compareEngineVersions(linked, pinnedVersion) : null;
196
+ if (order !== null && order > 0 && stale.resolved !== null) {
197
+ // No log line here: an older CLI reaches this on every command.
198
+ return { stale, roots: [], skipped: 'stable names a newer engine than this CLI pins' };
199
+ }
200
+ let relinked;
201
+ if (order !== null && order < 0 && isAcceptedHookEngine(home, stale.pinned, platform)) {
202
+ // The pinned engine already passed the host canary gate here (commitStable
203
+ // recorded it), so the link was rolled back below an accepted engine:
204
+ // relink now, not after the reindex.
205
+ try {
206
+ linkStableEngine(stale.pinned, home, platform, { now: () => now });
207
+ relinked = pinnedVersion;
208
+ appendStableHealLog(home, `stable rolled back to ${linked}; relinked to the canary-accepted pinned engine ${stale.pinned} before the reindex`, now);
209
+ }
210
+ catch (error) {
211
+ appendStableHealLog(home, `stable rolled back to ${linked}; relink to ${stale.pinned} failed: ${error instanceof Error ? error.message : String(error)}`, now);
212
+ }
213
+ }
214
+ const extra = relinked ? { relinked } : {};
178
215
  const last = readState(home);
179
216
  if (last && last.pinned === stale.pinned && typeof last.at === 'number' && now - last.at >= 0 && now - last.at < STABLE_HEAL_RETRY_MS) {
180
- return { stale, roots: [], skipped: 'a heal for this engine started less than an hour ago' };
217
+ return { stale, roots: [], skipped: 'a heal for this engine started less than an hour ago', ...extra };
181
218
  }
182
219
  const roots = stableHealRoots(home, env, options.cwd ?? process.cwd(), platform);
183
220
  if (!roots.length)
184
- return { stale, roots: [], skipped: 'no HQ root to reconcile' };
221
+ return { stale, roots: [], skipped: 'no HQ root to reconcile', ...extra };
185
222
  const cliEntry = options.cliEntry ?? process.argv[1];
186
223
  if (!cliEntry)
187
- return { stale, roots: [], skipped: 'no CLI entry to run' };
224
+ return { stale, roots: [], skipped: 'no CLI entry to run', ...extra };
188
225
  writeState(home, stale.pinned, now);
189
226
  const childEnv = { ...env, [STABLE_HEAL_ENV]: '1', HQ_INSTALL_FOLLOWUP: '1' };
190
227
  for (const name of GATE_WEAKENING_ENV)
@@ -209,6 +246,6 @@ export function healStableEngine(options = {}) {
209
246
  finally {
210
247
  fs.closeSync(log);
211
248
  }
212
- return { stale, roots };
249
+ return { stale, roots, ...extra };
213
250
  }
214
251
  //# sourceMappingURL=stable-heal.js.map
@@ -0,0 +1,70 @@
1
+ /** Name of the release-stable link next to the pinned engine versions. */
2
+ export declare const STABLE_LINK_NAME = "stable";
3
+ /** Record of canary-accepted hook engines committed to `stable`, under the home folder. */
4
+ export declare const ACCEPTED_HOOK_ENGINE_RECORD: string;
5
+ /** Schema of [`ACCEPTED_HOOK_ENGINE_RECORD`]. */
6
+ export declare const ACCEPTED_HOOK_ENGINE_SCHEMA = "hq.accepted-hook-engine.v1";
7
+ export type CoreNextHost = 'claude' | 'codex' | 'grok' | 'fleet-local' | 'agents-v2' | 'antigravity';
8
+ /** One canary-accepted engine recorded when `commitStable` moved `stable` to it. */
9
+ export interface AcceptedHookEngineEntry {
10
+ engineVersion: string;
11
+ pinnedEngine: string;
12
+ acceptedAt: string;
13
+ hosts: CoreNextHost[];
14
+ }
15
+ export interface AcceptedHookEngineRecord {
16
+ schema: typeof ACCEPTED_HOOK_ENGINE_SCHEMA;
17
+ engines: Record<string, AcceptedHookEngineEntry>;
18
+ }
19
+ /**
20
+ * Read `<home>/.hq/bin/hq-hook/accepted-engine.json`; null when absent,
21
+ * unreadable, invalid, or writable by another user.
22
+ */
23
+ export declare function readAcceptedHookEngineRecord(home: string, platform?: NodeJS.Platform): AcceptedHookEngineRecord | null;
24
+ /** True when `pinned` resolves to an engine recorded in the accepted-engine record (it passed the host canary gate here). */
25
+ export declare function isAcceptedHookEngine(home: string, pinned: string, platform?: NodeJS.Platform): boolean;
26
+ /** Thrown when `stable` names a newer, runnable engine and the caller did not ask for a downgrade. */
27
+ export declare class StableDowngradeRefused extends Error {
28
+ constructor(message: string);
29
+ }
30
+ export declare function hookEngineDir(home: string): string;
31
+ /** The stable path that stands for a pinned engine path. */
32
+ export declare function stableEnginePath(pinned: string, home: string): string;
33
+ /**
34
+ * Semver precedence of two engine version folder names: negative when `a` is
35
+ * older, positive when newer, 0 when equal. Null when either is not a version
36
+ * folder name, so the caller cannot tell which is older.
37
+ */
38
+ export declare function compareEngineVersions(a: string, b: string): number | null;
39
+ /** The version folder an engine path under `<home>/.hq/bin/hq-hook` sits in; null when it is not under it. */
40
+ export declare function engineVersionOf(pinned: string, home: string): string | null;
41
+ /** The version folder name `stable` names (even when that folder is gone); null when it is not a link. */
42
+ export declare function stableLinkVersion(home: string): string | null;
43
+ /** Append one line to `<home>/.hq/logs/stable-heal.log`; best effort. */
44
+ export declare function appendStableHealLog(home: string, line: string, now?: number): void;
45
+ export interface LinkStableEngineOptions {
46
+ /**
47
+ * The person asked to move `stable` to an older engine (a repair or a
48
+ * downgrade they requested). Only such a command passes true.
49
+ */
50
+ allowDowngrade?: boolean;
51
+ now?: () => number;
52
+ }
53
+ /**
54
+ * Point `<home>/.hq/bin/hq-hook/stable` at the pinned engine's version folder
55
+ * and return the stable engine path. The link is replaced by rename, so a
56
+ * planted file at the temporary name or the link itself is never followed. A
57
+ * `stable` that is a real folder (not a link) is someone else's and is left
58
+ * alone: the call fails and the caller keeps the current registrations.
59
+ *
60
+ * A link that names a newer engine than `pinned`, which is still there and
61
+ * runnable, stays where it is: the call records the refusal in stable-heal.log
62
+ * and throws [`StableDowngradeRefused`], unless the person asked for the
63
+ * downgrade ([`LinkStableEngineOptions.allowDowngrade`]).
64
+ */
65
+ export declare function linkStableEngine(pinned: string, home: string, platform?: NodeJS.Platform, options?: LinkStableEngineOptions): string;
66
+ /** A real folder or file (not a link) of this user that group and others cannot write. */
67
+ export declare function checkOwnedEntry(entry: string, kind: 'folder' | 'file', platform: NodeJS.Platform): void;
68
+ /** True when the link resolves to `folder` (Windows reports junction targets in its own spelling). */
69
+ export declare function pointsAt(link: string, folder: string): boolean;
70
+ //# sourceMappingURL=stable-link.d.ts.map
@@ -0,0 +1,300 @@
1
+ /**
2
+ * The release-stable link `<home>/.hq/bin/hq-hook/stable`, which every
3
+ * core.next registration runs the engine through.
4
+ *
5
+ * Kept apart from host-registration.ts so the start-up heal
6
+ * (stable-heal.ts) can move the link without loading the registration switch,
7
+ * the canary gate and their imports. host-registration.ts re-exports what it
8
+ * always exported from here.
9
+ *
10
+ * The link never moves to a lower engine version than the one it names unless
11
+ * the caller is a repair or downgrade the person asked for and passes
12
+ * `allowDowngrade: true` (no command does yet). There is deliberately no
13
+ * environment switch: a lane or an old install script could set one. The
14
+ * refusal applies only while the newer engine the link names is still there
15
+ * and runnable. An older hq-cli run with the real home once moved it from
16
+ * 5.345.268 back to 5.345.238; the older engine did not know the installed gate
17
+ * and refused every PreToolUse call until a heal finished. This guard only
18
+ * binds CLIs that carry it; stable-heal.ts undoes a roll-back made by an older
19
+ * CLI when the pinned engine was canary-accepted on this machine.
20
+ */
21
+ import * as fs from 'node:fs';
22
+ import * as path from 'node:path';
23
+ /** Name of the release-stable link next to the pinned engine versions. */
24
+ export const STABLE_LINK_NAME = 'stable';
25
+ /** Record of canary-accepted hook engines committed to `stable`, under the home folder. */
26
+ export const ACCEPTED_HOOK_ENGINE_RECORD = path.join('.hq', 'bin', 'hq-hook', 'accepted-engine.json');
27
+ /** Schema of [`ACCEPTED_HOOK_ENGINE_RECORD`]. */
28
+ export const ACCEPTED_HOOK_ENGINE_SCHEMA = 'hq.accepted-hook-engine.v1';
29
+ /**
30
+ * Read `<home>/.hq/bin/hq-hook/accepted-engine.json`; null when absent,
31
+ * unreadable, invalid, or writable by another user.
32
+ */
33
+ export function readAcceptedHookEngineRecord(home, platform = process.platform) {
34
+ const file = path.join(home, ACCEPTED_HOOK_ENGINE_RECORD);
35
+ let text;
36
+ try {
37
+ checkOwnedEntry(file, 'file', platform);
38
+ text = fs.readFileSync(file, 'utf8');
39
+ }
40
+ catch {
41
+ return null;
42
+ }
43
+ let doc;
44
+ try {
45
+ doc = JSON.parse(text);
46
+ }
47
+ catch {
48
+ return null;
49
+ }
50
+ const rec = doc;
51
+ if (!rec || rec.schema !== ACCEPTED_HOOK_ENGINE_SCHEMA || !rec.engines || typeof rec.engines !== 'object' || Array.isArray(rec.engines)) {
52
+ return null;
53
+ }
54
+ const engines = {};
55
+ for (const [key, raw] of Object.entries(rec.engines)) {
56
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw))
57
+ continue;
58
+ const entry = raw;
59
+ if (typeof entry.engineVersion !== 'string' || !entry.engineVersion)
60
+ continue;
61
+ if (typeof entry.pinnedEngine !== 'string' || !entry.pinnedEngine)
62
+ continue;
63
+ if (!Array.isArray(entry.hosts))
64
+ continue;
65
+ const hosts = entry.hosts.filter((h) => typeof h === 'string');
66
+ if (hosts.length === 0)
67
+ continue;
68
+ engines[key] = {
69
+ engineVersion: entry.engineVersion,
70
+ pinnedEngine: entry.pinnedEngine,
71
+ acceptedAt: typeof entry.acceptedAt === 'string' ? entry.acceptedAt : '',
72
+ hosts,
73
+ };
74
+ }
75
+ return { schema: ACCEPTED_HOOK_ENGINE_SCHEMA, engines };
76
+ }
77
+ /** True when `pinned` resolves to an engine recorded in the accepted-engine record (it passed the host canary gate here). */
78
+ export function isAcceptedHookEngine(home, pinned, platform = process.platform) {
79
+ let resolved;
80
+ try {
81
+ resolved = fs.realpathSync(pinned);
82
+ }
83
+ catch {
84
+ return false;
85
+ }
86
+ const entry = readAcceptedHookEngineRecord(home, platform)?.engines[resolved];
87
+ return !!entry && entry.hosts.length > 0;
88
+ }
89
+ /** Thrown when `stable` names a newer, runnable engine and the caller did not ask for a downgrade. */
90
+ export class StableDowngradeRefused extends Error {
91
+ constructor(message) {
92
+ super(message);
93
+ this.name = 'StableDowngradeRefused';
94
+ }
95
+ }
96
+ export function hookEngineDir(home) {
97
+ return path.join(home, '.hq', 'bin', 'hq-hook');
98
+ }
99
+ /** The stable path that stands for a pinned engine path. */
100
+ export function stableEnginePath(pinned, home) {
101
+ const relative = path.relative(hookEngineDir(home), pinned);
102
+ const [, ...rest] = relative.split(/[\\/]/);
103
+ if (relative.startsWith('..') || path.isAbsolute(relative) || rest.length === 0) {
104
+ throw new Error(`hook engine ${pinned} is not under ${hookEngineDir(home)}`);
105
+ }
106
+ return path.join(hookEngineDir(home), STABLE_LINK_NAME, ...rest);
107
+ }
108
+ function parseVersion(version) {
109
+ const match = /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?$/.exec(version);
110
+ if (!match)
111
+ return null;
112
+ return { core: [Number(match[1]), Number(match[2]), Number(match[3])], pre: match[4] ? match[4].split('.') : [] };
113
+ }
114
+ /**
115
+ * Semver precedence of two engine version folder names: negative when `a` is
116
+ * older, positive when newer, 0 when equal. Null when either is not a version
117
+ * folder name, so the caller cannot tell which is older.
118
+ */
119
+ export function compareEngineVersions(a, b) {
120
+ const left = parseVersion(a);
121
+ const right = parseVersion(b);
122
+ if (!left || !right)
123
+ return null;
124
+ for (let i = 0; i < 3; i += 1) {
125
+ if (left.core[i] !== right.core[i])
126
+ return left.core[i] - right.core[i];
127
+ }
128
+ if (!left.pre.length || !right.pre.length)
129
+ return right.pre.length - left.pre.length;
130
+ for (let i = 0; i < Math.max(left.pre.length, right.pre.length); i += 1) {
131
+ const x = left.pre[i];
132
+ const y = right.pre[i];
133
+ if (x === undefined)
134
+ return -1;
135
+ if (y === undefined)
136
+ return 1;
137
+ if (x === y)
138
+ continue;
139
+ const xn = /^\d+$/.test(x);
140
+ const yn = /^\d+$/.test(y);
141
+ if (xn && yn)
142
+ return Number(x) - Number(y);
143
+ if (xn !== yn)
144
+ return xn ? -1 : 1;
145
+ return x < y ? -1 : 1;
146
+ }
147
+ return 0;
148
+ }
149
+ /** The version folder an engine path under `<home>/.hq/bin/hq-hook` sits in; null when it is not under it. */
150
+ export function engineVersionOf(pinned, home) {
151
+ const relative = path.relative(hookEngineDir(home), pinned);
152
+ if (relative.startsWith('..') || path.isAbsolute(relative))
153
+ return null;
154
+ const version = relative.split(/[\\/]/)[0];
155
+ return version && version !== STABLE_LINK_NAME ? version : null;
156
+ }
157
+ /** The version folder name `stable` names (even when that folder is gone); null when it is not a link. */
158
+ export function stableLinkVersion(home) {
159
+ try {
160
+ const target = fs.readlinkSync(path.join(hookEngineDir(home), STABLE_LINK_NAME));
161
+ return target.split(/[\\/]/).filter(Boolean).pop() ?? null;
162
+ }
163
+ catch {
164
+ return null;
165
+ }
166
+ }
167
+ /** True when `file` resolves to a regular file that this platform can run. */
168
+ function isRunnableFile(file, platform) {
169
+ try {
170
+ const stat = fs.statSync(fs.realpathSync(file));
171
+ return stat.isFile() && (platform === 'win32' || (stat.mode & 0o111) !== 0);
172
+ }
173
+ catch {
174
+ return false;
175
+ }
176
+ }
177
+ /** Append one line to `<home>/.hq/logs/stable-heal.log`; best effort. */
178
+ export function appendStableHealLog(home, line, now = Date.now()) {
179
+ try {
180
+ const logDir = path.join(home, '.hq', 'logs');
181
+ fs.mkdirSync(logDir, { recursive: true });
182
+ fs.appendFileSync(path.join(logDir, 'stable-heal.log'), `${new Date(now).toISOString()} ${line}\n`);
183
+ }
184
+ catch {
185
+ // Nowhere left to record it; the caller still gets the error.
186
+ }
187
+ }
188
+ /**
189
+ * Point `<home>/.hq/bin/hq-hook/stable` at the pinned engine's version folder
190
+ * and return the stable engine path. The link is replaced by rename, so a
191
+ * planted file at the temporary name or the link itself is never followed. A
192
+ * `stable` that is a real folder (not a link) is someone else's and is left
193
+ * alone: the call fails and the caller keeps the current registrations.
194
+ *
195
+ * A link that names a newer engine than `pinned`, which is still there and
196
+ * runnable, stays where it is: the call records the refusal in stable-heal.log
197
+ * and throws [`StableDowngradeRefused`], unless the person asked for the
198
+ * downgrade ([`LinkStableEngineOptions.allowDowngrade`]).
199
+ */
200
+ export function linkStableEngine(pinned, home, platform = process.platform, options = {}) {
201
+ const root = hookEngineDir(home);
202
+ const relative = path.relative(root, pinned).split(/[\\/]/);
203
+ const version = relative[0];
204
+ if (!version || version === '..' || version === STABLE_LINK_NAME || path.isAbsolute(path.relative(root, pinned))) {
205
+ throw new Error(`hook engine ${pinned} is not under ${root}`);
206
+ }
207
+ const stable = path.join(root, STABLE_LINK_NAME);
208
+ // Store rule v2: every path component this follows or creates under the home
209
+ // folder is a real folder of this user that group and others cannot write:
210
+ // .hq, .hq/bin, .hq/bin/hq-hook, the version folder and any folder below it
211
+ // up to the engine, and the engine file itself.
212
+ const components = [path.join(home, '.hq'), path.join(home, '.hq', 'bin'), root];
213
+ for (let i = 0; i < relative.length - 1; i += 1)
214
+ components.push(path.join(root, ...relative.slice(0, i + 1)));
215
+ for (const component of components)
216
+ checkOwnedEntry(component, 'folder', platform);
217
+ checkOwnedEntry(pinned, 'file', platform);
218
+ // Windows creates a junction, which needs an absolute target; elsewhere the
219
+ // link is relative so it names the version folder beside it.
220
+ const target = platform === 'win32' ? path.join(root, version) : version;
221
+ let current;
222
+ try {
223
+ current = fs.lstatSync(stable);
224
+ }
225
+ catch (error) {
226
+ if (error.code !== 'ENOENT')
227
+ throw error;
228
+ }
229
+ if (current && !current.isSymbolicLink())
230
+ throw new Error(`${stable} exists and is not a link; leaving it in place`);
231
+ if (current && pointsAt(stable, path.join(root, version)))
232
+ return stableEnginePath(pinned, home);
233
+ if (current && options.allowDowngrade !== true) {
234
+ const linked = stableLinkVersion(home);
235
+ const order = linked ? compareEngineVersions(version, linked) : null;
236
+ // Only a newer engine that still runs holds the link: a dangling or broken
237
+ // target is relinked to the engine installed now.
238
+ const linkedEngine = path.join(stable, ...relative.slice(1));
239
+ if (order !== null && order < 0 && pointsAt(stable, path.join(root, linked)) && isRunnableFile(linkedEngine, platform)) {
240
+ const message = `refused to move ${stable} from ${linked} back to the older engine ${version} (${pinned}); only an explicit repair or downgrade may move it back`;
241
+ appendStableHealLog(home, message, (options.now ?? Date.now)());
242
+ throw new StableDowngradeRefused(message);
243
+ }
244
+ }
245
+ if (platform === 'win32') {
246
+ // A junction cannot be renamed over another. A running engine keeps its
247
+ // own image open, which the junction does not hold.
248
+ if (current) {
249
+ try {
250
+ fs.unlinkSync(stable);
251
+ }
252
+ catch {
253
+ fs.rmdirSync(stable);
254
+ }
255
+ }
256
+ fs.symlinkSync(target, stable, 'junction');
257
+ }
258
+ else {
259
+ const staged = path.join(root, `.${STABLE_LINK_NAME}.${process.pid}.tmp`);
260
+ try {
261
+ fs.unlinkSync(staged);
262
+ }
263
+ catch (error) {
264
+ if (error.code !== 'ENOENT')
265
+ throw error;
266
+ }
267
+ fs.symlinkSync(target, staged);
268
+ try {
269
+ fs.renameSync(staged, stable);
270
+ }
271
+ catch (error) {
272
+ try {
273
+ fs.unlinkSync(staged);
274
+ }
275
+ catch { /* already gone */ }
276
+ throw error;
277
+ }
278
+ }
279
+ return stableEnginePath(pinned, home);
280
+ }
281
+ /** A real folder or file (not a link) of this user that group and others cannot write. */
282
+ export function checkOwnedEntry(entry, kind, platform) {
283
+ const stat = fs.lstatSync(entry);
284
+ if (stat.isSymbolicLink() || (kind === 'folder' ? !stat.isDirectory() : !stat.isFile()))
285
+ throw new Error(`${entry} is not a ${kind}`);
286
+ if (typeof process.getuid === 'function' && stat.uid !== process.getuid())
287
+ throw new Error(`${entry} is not owned by this user`);
288
+ if (platform !== 'win32' && (stat.mode & 0o022) !== 0)
289
+ throw new Error(`${entry} is writable by group or others`);
290
+ }
291
+ /** True when the link resolves to `folder` (Windows reports junction targets in its own spelling). */
292
+ export function pointsAt(link, folder) {
293
+ try {
294
+ return fs.realpathSync(link) === fs.realpathSync(folder);
295
+ }
296
+ catch {
297
+ return false;
298
+ }
299
+ }
300
+ //# sourceMappingURL=stable-link.js.map
@@ -83,7 +83,10 @@ export function resolveInstallHookTarget(hqRoot, home, daemonInstalled, env = pr
83
83
  }
84
84
  const coreNext = forHost(rawCoreNext, hqRoot, host, env);
85
85
  if (coreNext) {
86
- candidate?.commitStable?.([host]);
86
+ if (candidate?.commitStable)
87
+ candidate.commitStable([host]);
88
+ else
89
+ candidate?.recordAccepted?.([host]);
87
90
  return { target: { ...coreNext, fallback } };
88
91
  }
89
92
  const existingHosts = nativeOnly ? detectMachineHookHosts(hqRoot, home, env) : [];
@@ -281,15 +281,35 @@ export declare function codexFilesystemProfile(installDir: string, workDir: stri
281
281
  export declare function grokSandboxProfile(scope: TurnScope, envPath: string | undefined): string;
282
282
  /** Grok can read the source; candidate writing belongs to the host. */
283
283
  export declare function grokAllowRules(channelDir: string): string[];
284
- /** Parse literal arguments only. No shell ever interprets model output. */
285
- export declare function grokCandidateArgv(command: string, wrapperPath: string): string[] | null;
284
+ export interface DroppedCandidate {
285
+ index: number;
286
+ reason: string;
287
+ }
288
+ export type CandidateParseResult = {
289
+ ok: true;
290
+ argv: string[];
291
+ } | {
292
+ ok: false;
293
+ reason: string;
294
+ };
295
+ export interface ExecuteCandidatesResult {
296
+ error?: string;
297
+ dropped: DroppedCandidate[];
298
+ }
299
+ /**
300
+ * Validate one structured candidate object and build the fixed 7-element argv
301
+ * for the pinned candidate wrapper. No shell ever interprets model output, and
302
+ * the model can never change the executable, wrapper path, or flag shape.
303
+ */
304
+ export declare function structuredCandidateArgv(candidate: unknown, wrapperPath: string): CandidateParseResult;
286
305
  /**
287
- * Validate the whole batch before writing. Only the host executes the pinned
288
- * writer. When `expectedWrapper` is set, the file is compared to that text
289
- * immediately before each exec. Strict can write the turn directory, so a
290
- * writer that no longer matches is not run.
306
+ * Validate structured candidates and execute each valid one through the pinned
307
+ * wrapper using a fixed argv array (never a shell command string). A malformed
308
+ * or invalid candidate drops only itself, records why, and keeps the rest of
309
+ * the item's valid candidates. When `expectedWrapper` is set, the file on disk
310
+ * is compared to that text immediately before each exec.
291
311
  */
292
- export declare function executeGrokCandidates(text: string, wrapperPath: string, spawn: SpawnSyncFn, opts: Parameters<SpawnSyncFn>[2], expectedWrapper?: string, runtime?: "grok" | "codex" | "claude"): string | undefined;
312
+ export declare function executeGrokCandidates(text: string, wrapperPath: string, spawn: SpawnSyncFn, opts: Parameters<SpawnSyncFn>[2], expectedWrapper?: string, runtime?: "grok" | "codex" | "claude"): ExecuteCandidatesResult;
293
313
  /**
294
314
  * Read denies for the grok login. Grok matches a `~` tool path literally and
295
315
  * expands `~` only after that check, so the absolute temp home is not enough.