@indigoai-us/hq-cli 5.345.226 → 5.345.228

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 (132) hide show
  1. package/CHANGELOG.md +142 -0
  2. package/dist/command-catalog.generated.d.ts +137 -0
  3. package/dist/command-catalog.generated.js +164 -0
  4. package/dist/commands/auth.d.ts +2 -2
  5. package/dist/commands/auth.js +3 -3
  6. package/dist/commands/core-delegate-w1b.js +92 -69
  7. package/dist/commands/core-delegate.d.ts +19 -1
  8. package/dist/commands/core-delegate.js +411 -6
  9. package/dist/commands/core-dm-bind-native.js +2 -1
  10. package/dist/commands/core-handoff.d.ts +5 -0
  11. package/dist/commands/core-handoff.js +1008 -14
  12. package/dist/commands/core-pin-native.d.ts +1 -0
  13. package/dist/commands/core-pin-native.js +3 -15
  14. package/dist/commands/core-register-project-native.d.ts +6 -0
  15. package/dist/commands/core-register-project-native.js +182 -52
  16. package/dist/commands/core-work-mesh-bind-trusted-native.js +4 -9
  17. package/dist/commands/daemon.js +2 -2
  18. package/dist/commands/index-cmd.d.ts +3 -1
  19. package/dist/commands/index-cmd.js +12 -0
  20. package/dist/commands/lanes-checks.js +1 -1
  21. package/dist/commands/lanes-session-start.d.ts +1 -2
  22. package/dist/commands/lanes-session-start.js +9 -145
  23. package/dist/commands/lanes-shared.d.ts +3 -0
  24. package/dist/commands/lanes.d.ts +3 -0
  25. package/dist/commands/lanes.js +94 -27
  26. package/dist/commands/link.d.ts +8 -3
  27. package/dist/commands/link.js +14 -17
  28. package/dist/commands/mcp-registration.d.ts +65 -7
  29. package/dist/commands/mcp-registration.js +289 -51
  30. package/dist/commands/mesh.d.ts +12 -0
  31. package/dist/commands/mesh.js +92 -10
  32. package/dist/commands/reindex.js +6 -0
  33. package/dist/commands/repo.d.ts +13 -0
  34. package/dist/commands/repo.js +39 -1
  35. package/dist/commands/sync-mode.d.ts +3 -1
  36. package/dist/commands/sync-mode.js +11 -1
  37. package/dist/lazy-commands.js +3 -4
  38. package/dist/lib/checkpoint-ontology/entity-file.js +4 -4
  39. package/dist/lib/checkpoint-ontology/merge-copies.js +7 -11
  40. package/dist/lib/checkpoint-ontology/plan.js +2 -1
  41. package/dist/lib/core-utils/archive-old-threads.js +5 -2
  42. package/dist/lib/core-utils/session-company.d.ts +13 -1
  43. package/dist/lib/core-utils/session-company.js +75 -4
  44. package/dist/lib/core-utils/worktree-resume.d.ts +6 -0
  45. package/dist/lib/core-utils/worktree-resume.js +8 -4
  46. package/dist/lib/daemon/background-qos.d.ts +7 -0
  47. package/dist/lib/daemon/background-qos.js +13 -0
  48. package/dist/lib/daemon/catalog.d.ts +9 -0
  49. package/dist/lib/daemon/catalog.js +8 -1
  50. package/dist/lib/daemon/hook-requests-acl-suggest.d.ts +18 -0
  51. package/dist/lib/daemon/hook-requests-acl-suggest.js +245 -0
  52. package/dist/lib/daemon/hook-requests-fleet-session-start.d.ts +32 -0
  53. package/dist/lib/daemon/hook-requests-fleet-session-start.js +214 -0
  54. package/dist/lib/daemon/hook-requests-mesh-tool-writes.d.ts +44 -0
  55. package/dist/lib/daemon/hook-requests-mesh-tool-writes.js +292 -0
  56. package/dist/lib/daemon/hook-requests-mesh.d.ts +54 -0
  57. package/dist/lib/daemon/hook-requests-mesh.js +559 -0
  58. package/dist/lib/daemon/hook-requests.d.ts +349 -8
  59. package/dist/lib/daemon/hook-requests.js +1312 -46
  60. package/dist/lib/daemon/machine-checks.d.ts +12 -2
  61. package/dist/lib/daemon/machine-checks.js +27 -10
  62. package/dist/lib/daemon/merge-sections.d.ts +24 -2
  63. package/dist/lib/daemon/merge-sections.js +58 -16
  64. package/dist/lib/daemon/ops/policy.js +4 -2
  65. package/dist/lib/daemon/resolver.js +9 -2
  66. package/dist/lib/daemon/run.d.ts +11 -7
  67. package/dist/lib/daemon/run.js +168 -24
  68. package/dist/lib/daemon/search-index-worker-v1.d.ts +2 -0
  69. package/dist/lib/daemon/search-index-worker-v1.js +25 -0
  70. package/dist/lib/daemon/session-registry.d.ts +0 -1
  71. package/dist/lib/daemon/session-registry.js +0 -3
  72. package/dist/lib/daemon/supervisor.d.ts +3 -1
  73. package/dist/lib/daemon/supervisor.js +1 -1
  74. package/dist/lib/daemon/tcc-eperm.d.ts +59 -4
  75. package/dist/lib/daemon/tcc-eperm.js +110 -8
  76. package/dist/lib/doctor/fix/process-identity.d.ts +20 -2
  77. package/dist/lib/doctor/fix/process-identity.js +48 -5
  78. package/dist/lib/hook-engine/canary-gate.js +1 -0
  79. package/dist/lib/hook-engine/native-stop-compatibility.json +2 -1
  80. package/dist/lib/hot-channels/adapters/attio.js +2 -1
  81. package/dist/lib/hot-channels/adapters/meetings.js +2 -1
  82. package/dist/lib/lanes/company-outposts.d.ts +37 -0
  83. package/dist/lib/lanes/company-outposts.js +164 -0
  84. package/dist/lib/lanes/liveness.d.ts +6 -0
  85. package/dist/lib/lanes/liveness.js +49 -8
  86. package/dist/lib/lanes/orphan-report.d.ts +15 -0
  87. package/dist/lib/lanes/orphan-report.js +223 -0
  88. package/dist/lib/lanes/orphan-sweep.d.ts +26 -0
  89. package/dist/lib/lanes/orphan-sweep.js +152 -0
  90. package/dist/lib/lanes/reaper.d.ts +2 -0
  91. package/dist/lib/lanes/reaper.js +11 -8
  92. package/dist/lib/lanes/reconcile.d.ts +8 -7
  93. package/dist/lib/lanes/reconcile.js +39 -0
  94. package/dist/lib/mesh/live/backfill-held.d.ts +13 -0
  95. package/dist/lib/mesh/live/backfill-held.js +23 -0
  96. package/dist/lib/mesh/live/daemon/mode.d.ts +8 -4
  97. package/dist/lib/mesh/live/daemon/mode.js +8 -4
  98. package/dist/lib/mesh/live/daemon/run.d.ts +14 -3
  99. package/dist/lib/mesh/live/daemon/run.js +116 -7
  100. package/dist/lib/mesh/live/direct-drain.d.ts +123 -0
  101. package/dist/lib/mesh/live/direct-drain.js +315 -0
  102. package/dist/lib/mesh/live/emit-replay.d.ts +10 -0
  103. package/dist/lib/mesh/live/emit-replay.js +10 -0
  104. package/dist/lib/mesh/live/flush.d.ts +15 -0
  105. package/dist/lib/mesh/live/flush.js +27 -0
  106. package/dist/lib/mesh/live/liveness-carry.d.ts +45 -0
  107. package/dist/lib/mesh/live/liveness-carry.js +141 -0
  108. package/dist/lib/mesh/live/spool.d.ts +19 -0
  109. package/dist/lib/mesh/live/spool.js +80 -0
  110. package/dist/lib/safe-store.d.ts +2 -0
  111. package/dist/lib/safe-store.js +8 -6
  112. package/dist/lib/search-index/index.d.ts +9 -3
  113. package/dist/lib/search-index/index.js +35 -10
  114. package/dist/lib/search-index/worker-process.d.ts +9 -0
  115. package/dist/lib/search-index/worker-process.js +171 -0
  116. package/dist/lib/session-company-lock.d.ts +3 -1
  117. package/dist/lib/session-company-lock.js +3 -2
  118. package/dist/utils/delegate-command-supervisor.d.ts +3 -0
  119. package/dist/utils/delegate-command-supervisor.js +44 -0
  120. package/dist/utils/delegate-lock.d.ts +12 -0
  121. package/dist/utils/delegate-lock.js +88 -0
  122. package/dist/utils/frontmatter.d.ts +27 -0
  123. package/dist/utils/frontmatter.js +33 -0
  124. package/dist/utils/hook-trust.d.ts +1 -0
  125. package/dist/utils/hook-trust.js +18 -2
  126. package/dist/utils/host-registration.d.ts +13 -1
  127. package/dist/utils/host-registration.js +98 -5
  128. package/dist/utils/package-use-lease.d.ts +1 -1
  129. package/dist/utils/package-use-lease.js +15 -7
  130. package/docs/anywhere-runtime.md +17 -0
  131. package/package.json +8 -7
  132. package/scripts/check-function-manifest.mjs +17 -3
@@ -3,7 +3,7 @@ import * as path from "node:path";
3
3
  import { resolveSessionId } from "./core-utils/session-id.js";
4
4
  import { resolveDefaultHqRoot } from "../utils/hq-root-resolver.js";
5
5
  /** Read the session's validated company scope capability or legacy metadata. */
6
- export function readSessionCompanyLock(env = process.env) {
6
+ export function readSessionCompanyLock(env = process.env, { requireAllCompanies = false } = {}) {
7
7
  const root = resolveDefaultHqRoot({ env });
8
8
  const sessionId = resolveSessionId(root, env);
9
9
  if (!sessionId)
@@ -90,8 +90,9 @@ export function readSessionCompanyLock(env = process.env) {
90
90
  return false;
91
91
  }
92
92
  });
93
- if (primary && real[0] !== primary)
93
+ if ((primary && real[0] !== primary) || (requireAllCompanies && real.length !== companies.length)) {
94
94
  return { sessionId, companies: [] };
95
+ }
95
96
  return { sessionId, companies: real };
96
97
  }
97
98
  //# sourceMappingURL=session-company-lock.js.map
@@ -0,0 +1,3 @@
1
+ /** Fixed supervisor for bounded delegate children. Arguments remain argv, never shell text. */
2
+ export declare const DELEGATE_COMMAND_SUPERVISOR: string;
3
+ //# sourceMappingURL=delegate-command-supervisor.d.ts.map
@@ -0,0 +1,44 @@
1
+ /** Fixed supervisor for bounded delegate children. Arguments remain argv, never shell text. */
2
+ export const DELEGATE_COMMAND_SUPERVISOR = String.raw `
3
+ const { spawn, spawnSync } = require('node:child_process');
4
+ const [budget, command, encoded] = process.argv.slice(1);
5
+ const plan = JSON.parse(encoded);
6
+ const windows = process.platform === 'win32';
7
+ let child;
8
+ let stopped = false;
9
+ let timer;
10
+ const stop = () => {
11
+ if (stopped) return;
12
+ stopped = true;
13
+ clearTimeout(timer);
14
+ if (child && child.pid) {
15
+ if (windows) {
16
+ const result = spawnSync('taskkill.exe', ['/PID', String(child.pid), '/T', '/F'], { stdio: 'ignore', timeout: 5000, windowsHide: true });
17
+ if (result.error || result.status !== 0) child.kill('SIGKILL');
18
+ } else {
19
+ try { process.kill(-child.pid, 'SIGKILL'); } catch (error) {
20
+ if (error.code !== 'ESRCH') process.stderr.write('delegate: process group cleanup failed\n');
21
+ }
22
+ }
23
+ }
24
+ process.exit(124);
25
+ };
26
+ process.on('SIGTERM', stop);
27
+ process.on('SIGINT', stop);
28
+ try {
29
+ child = spawn(command, plan.args, { stdio: ['inherit', 'pipe', 'pipe'], shell: false, detached: !windows, windowsHide: true, windowsVerbatimArguments: plan.windowsVerbatimArguments === true });
30
+ child.stdout.pipe(process.stdout);
31
+ child.stderr.pipe(process.stderr);
32
+ timer = setTimeout(stop, Number(budget));
33
+ child.on('error', () => { clearTimeout(timer); process.stderr.write('delegate: child launch failed\n'); process.exit(127); });
34
+ child.on('close', (code) => {
35
+ if (stopped) return;
36
+ clearTimeout(timer);
37
+ process.exitCode = code === null ? 128 : code;
38
+ });
39
+ } catch {
40
+ process.stderr.write('delegate: child launch failed\n');
41
+ process.exit(127);
42
+ }
43
+ `;
44
+ //# sourceMappingURL=delegate-command-supervisor.js.map
@@ -0,0 +1,12 @@
1
+ export interface DelegateLockOptions {
2
+ now?: () => number;
3
+ startOf?: (pid: number) => string | null;
4
+ alive?: (pid: number) => boolean;
5
+ }
6
+ export interface DelegateLock {
7
+ release(): void;
8
+ }
9
+ /** A complete owner file is linked into place atomically. Legacy mkdir writers
10
+ * see EEXIST; unknown legacy directories stay held. */
11
+ export declare function acquireDelegateLock(lock: string, options?: DelegateLockOptions): DelegateLock | null;
12
+ //# sourceMappingURL=delegate-lock.d.ts.map
@@ -0,0 +1,88 @@
1
+ import * as fs from 'node:fs';
2
+ import { randomUUID } from 'node:crypto';
3
+ import { acquireUpdateLock } from './update-lock.js';
4
+ import { processStartTime } from '../lib/doctor/fix/process-identity.js';
5
+ /** A complete owner file is linked into place atomically. Legacy mkdir writers
6
+ * see EEXIST; unknown legacy directories stay held. */
7
+ export function acquireDelegateLock(lock, options = {}) {
8
+ const startOf = options.startOf ?? processStartTime;
9
+ const now = options.now ?? Date.now;
10
+ const alive = options.alive ?? ((pid) => {
11
+ try {
12
+ process.kill(pid, 0);
13
+ return true;
14
+ }
15
+ catch (error) {
16
+ return error.code !== 'ESRCH';
17
+ }
18
+ });
19
+ const ownStart = startOf(process.pid);
20
+ if (!ownStart)
21
+ return null;
22
+ const coordinate = () => acquireUpdateLock({ lockPath: `${lock}.coord`, tool: 'delegate-lock', heartbeatMs: 0, takeoverWaitMs: 0 });
23
+ const mutex = coordinate();
24
+ if (!mutex)
25
+ return null;
26
+ const token = randomUUID();
27
+ const body = JSON.stringify({ pid: process.pid, start: ownStart, createdAt: now(), token });
28
+ const staged = `${lock}.pending-${token}`;
29
+ let identity;
30
+ try {
31
+ fs.writeFileSync(staged, body, { flag: 'wx', mode: 0o600 });
32
+ try {
33
+ fs.linkSync(staged, lock);
34
+ }
35
+ catch (error) {
36
+ if (error.code !== 'EEXIST')
37
+ return null;
38
+ const before = fs.lstatSync(lock);
39
+ if (before.isSymbolicLink() || !before.isFile())
40
+ return null;
41
+ const ownerFile = lock;
42
+ const fileStat = fs.lstatSync(ownerFile);
43
+ if (!fileStat.isFile() || fileStat.isSymbolicLink() || fileStat.size > 4096)
44
+ return null;
45
+ const oldText = fs.readFileSync(ownerFile, 'utf8');
46
+ const old = JSON.parse(oldText);
47
+ if (!old || !Number.isSafeInteger(old.pid) || old.pid <= 0 || typeof old.start !== 'string' || !old.start || !Number.isFinite(old.createdAt))
48
+ return null;
49
+ const currentStart = startOf(old.pid);
50
+ if (alive(old.pid) && (currentStart === null || currentStart === old.start))
51
+ return null;
52
+ const after = fs.lstatSync(lock);
53
+ if (before.dev !== after.dev || before.ino !== after.ino || fs.readFileSync(ownerFile, 'utf8') !== oldText)
54
+ return null;
55
+ fs.unlinkSync(lock);
56
+ fs.linkSync(staged, lock);
57
+ }
58
+ identity = fs.lstatSync(lock);
59
+ }
60
+ catch {
61
+ return null;
62
+ }
63
+ finally {
64
+ try {
65
+ fs.unlinkSync(staged);
66
+ }
67
+ catch { /* A crash before publication leaves no held lock. */ }
68
+ mutex.release();
69
+ }
70
+ return {
71
+ release() {
72
+ const releaseMutex = coordinate();
73
+ if (!releaseMutex)
74
+ return;
75
+ try {
76
+ const current = fs.lstatSync(lock);
77
+ if (!current.isFile() || current.isSymbolicLink() || current.dev !== identity.dev || current.ino !== identity.ino || fs.readFileSync(lock, 'utf8') !== body)
78
+ return;
79
+ fs.unlinkSync(lock);
80
+ }
81
+ catch { /* Preserve a replacement or an unknown owner. */ }
82
+ finally {
83
+ releaseMutex.release();
84
+ }
85
+ },
86
+ };
87
+ }
88
+ //# sourceMappingURL=delegate-lock.js.map
@@ -0,0 +1,27 @@
1
+ /**
2
+ * The one home for splitting a `---` YAML frontmatter fence off a document.
3
+ *
4
+ * Both splitters take the text as given: no BOM stripping (a leading BOM means
5
+ * no fence) and no line-ending rewrite (`\r\n` and `\n` are both accepted at the
6
+ * fences). They never parse YAML; each caller keeps its own parser options and
7
+ * its own answer for malformed YAML.
8
+ *
9
+ * test/ci/frontmatter-inventory.test.ts fails when a new fence split appears
10
+ * outside this file without a reviewed reason.
11
+ */
12
+ /**
13
+ * Match a frontmatter fence at the very start of `text`. `[1]` is the YAML
14
+ * text between the fences, `[0]` runs through the closing fence's line ending.
15
+ * Null when the text does not open with a fence.
16
+ */
17
+ export declare function matchFrontmatter(text: string): RegExpExecArray | null;
18
+ /**
19
+ * Split `text` into the fenced block (both fences and the line ending after the
20
+ * closing one, kept byte for byte) and the body after it. Null when the text
21
+ * does not open with a fence.
22
+ */
23
+ export declare function splitFrontmatterBlock(text: string): {
24
+ frontmatter: string;
25
+ body: string;
26
+ } | null;
27
+ //# sourceMappingURL=frontmatter.d.ts.map
@@ -0,0 +1,33 @@
1
+ /**
2
+ * The one home for splitting a `---` YAML frontmatter fence off a document.
3
+ *
4
+ * Both splitters take the text as given: no BOM stripping (a leading BOM means
5
+ * no fence) and no line-ending rewrite (`\r\n` and `\n` are both accepted at the
6
+ * fences). They never parse YAML; each caller keeps its own parser options and
7
+ * its own answer for malformed YAML.
8
+ *
9
+ * test/ci/frontmatter-inventory.test.ts fails when a new fence split appears
10
+ * outside this file without a reviewed reason.
11
+ */
12
+ /** Closing fence must end its line or the text. Group 1 is the YAML text. */
13
+ const FENCE_RE = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/;
14
+ /** Closing fence may run straight into the body. Group 1 is the fenced block, group 2 the rest. */
15
+ const BLOCK_RE = /^(---\r?\n[\s\S]*?\r?\n---\r?\n?)([\s\S]*)$/;
16
+ /**
17
+ * Match a frontmatter fence at the very start of `text`. `[1]` is the YAML
18
+ * text between the fences, `[0]` runs through the closing fence's line ending.
19
+ * Null when the text does not open with a fence.
20
+ */
21
+ export function matchFrontmatter(text) {
22
+ return FENCE_RE.exec(text);
23
+ }
24
+ /**
25
+ * Split `text` into the fenced block (both fences and the line ending after the
26
+ * closing one, kept byte for byte) and the body after it. Null when the text
27
+ * does not open with a fence.
28
+ */
29
+ export function splitFrontmatterBlock(text) {
30
+ const match = BLOCK_RE.exec(text);
31
+ return match ? { frontmatter: match[1], body: match[2] } : null;
32
+ }
33
+ //# sourceMappingURL=frontmatter.js.map
@@ -21,6 +21,7 @@ export declare function defaultHomeDir(): string;
21
21
  export interface HookTrustDependencies {
22
22
  createCodexClient: (cwd: string) => Promise<CodexRpcClient>;
23
23
  homeDir?: () => string;
24
+ platform?: NodeJS.Platform;
24
25
  /**
25
26
  * Reads a config file as text. Injected only so tests can reproduce the race
26
27
  * the Claude leg guards against — Claude rewriting `~/.claude.json` between
@@ -836,20 +836,36 @@ export function trustGrokProjectHooks(hqRoot, deps = DEFAULT_DEPS) {
836
836
  // when the engine is not available, or when the shipped file cannot be
837
837
  // read as JSON: the shipped file, copied byte for byte as before.
838
838
  let wantJson;
839
+ let projectUpdates = [];
839
840
  try {
840
841
  const target = (deps.coreNextTarget ?? ((h) => coreNextTargetOrWarn(h)))(home);
841
842
  // Only the events the new core covers in full on Grok switch.
842
843
  const grok = forHost(target, hqRoot, 'grok');
843
- wantJson = grok ? grokBridgeJson(fs.readFileSync(sourceBridgeJson, 'utf8'), hqRoot, grok) : undefined;
844
+ const platform = deps.platform ?? process.platform;
845
+ wantJson = grok || platform === 'win32'
846
+ ? grokBridgeJson(fs.readFileSync(sourceBridgeJson, 'utf8'), hqRoot, grok, platform, home)
847
+ : undefined;
848
+ if (platform === 'win32') {
849
+ projectUpdates = fs.readdirSync(sourceHooks).filter(name => name.endsWith('.json') && name !== 'hq-grok-user-bridge.json').map(name => {
850
+ const file = path.join(sourceHooks, name);
851
+ return { file, content: grokBridgeJson(fs.readFileSync(file, 'utf8'), hqRoot, null, 'win32', home) };
852
+ });
853
+ }
844
854
  }
845
855
  catch (error) {
856
+ if ((deps.platform ?? process.platform) === 'win32') {
857
+ return { runtime: 'grok', status: 'failed', trusted: 0, reason: errorMessage(error) };
858
+ }
846
859
  process.stderr.write(`hq: warning: the Grok user hook file stays on the old dispatcher (${errorMessage(error)})\n`);
847
860
  wantJson = undefined;
848
861
  }
849
- if (grokTrustIsCurrent(hqRoot, home, wantJson)) {
862
+ if (grokTrustIsCurrent(hqRoot, home, wantJson) && projectUpdates.every(({ file, content }) => textMatches(file, content))) {
850
863
  return { runtime: 'grok', status: 'unchanged', trusted: 0 };
851
864
  }
852
865
  try {
866
+ for (const { file, content } of projectUpdates)
867
+ if (!textMatches(file, content))
868
+ replaceFileNoFollow(file, content);
853
869
  const grokHome = path.join(home, '.grok');
854
870
  const userHooks = path.join(grokHome, 'hooks');
855
871
  fs.mkdirSync(userHooks, { recursive: true });
@@ -117,6 +117,18 @@ export declare function resolveCoreNextEngine(home: string, options: CoreNextEng
117
117
  * stays as it is today.
118
118
  */
119
119
  export declare function coreNextTarget(home: string, env?: NodeJS.ProcessEnv, options?: CoreNextOptions): CoreNextTarget | null;
120
+ /**
121
+ * Set by `hq reindex --from-hook` (a reindex the daemon runs for a hook's
122
+ * request note): the host canary gate then keeps every host on the core it is
123
+ * on now ([`hostCanaryGate`]).
124
+ */
125
+ export declare const REINDEX_FROM_HOOK_ENV = "HQ_REINDEX_FROM_HOOK";
126
+ /**
127
+ * True when `host` is registered on the new core in this root: one of its hook
128
+ * files holds a new-core entry (`hq-hook run --host ...` through the stable
129
+ * link) for this root. A missing or unreadable file holds none.
130
+ */
131
+ export declare function hostOnCoreNext(home: string, env: NodeJS.ProcessEnv, root: string, host: 'claude' | 'codex' | 'grok'): boolean;
120
132
  /**
121
133
  * [`coreNextTarget`], with any failure turned into one warning and null, so
122
134
  * `hq install` and `hq reindex` go on with the old registrations.
@@ -176,7 +188,7 @@ export declare function placeEvent(groups: readonly unknown[], options: EventOpt
176
188
  * engine instead; matchers, timeouts, the other events and every other entry
177
189
  * stay as they are.
178
190
  */
179
- export declare function grokBridgeJson(source: string, root: string, target: CoreNextTarget | null, platform?: NodeJS.Platform): string;
191
+ export declare function grokBridgeJson(source: string, root: string, target: CoreNextTarget | null, platform?: NodeJS.Platform, home?: string): string;
180
192
  /**
181
193
  * Write `content` to `file` through the shared safe store (store rule v2): the
182
194
  * folder is held open and checked (a real folder of this user, not a link,
@@ -46,6 +46,7 @@ import { installHookEngine } from '../lib/hook-engine/resolve.js';
46
46
  // Read-only names stay on this namespace. host-registration.test.ts mocks a module that exports only installHookEngine.
47
47
  import * as hookEngineResolve from '../lib/hook-engine/resolve.js';
48
48
  import { launcherRoot, quotePosix, quoteWindows } from '../lib/hook-engine/registration.js';
49
+ import { isCoreNextEntry, userHookSettingsFile } from '../lib/hook-engine/registration-identity.js';
49
50
  import { openStoreDir } from '../lib/safe-store.js';
50
51
  import { SKIP_CANARY_GATE_ENV, checkHostCanary } from '../lib/hook-engine/canary-gate.js';
51
52
  import { resolvedUnder } from '../lib/hook-engine/coverage.js';
@@ -77,6 +78,22 @@ export const REQUIRED_EVALUATORS = {
77
78
  SessionEnd: ['policy-injection'],
78
79
  PreCompact: ['stop-check', 'policy-injection'],
79
80
  Stop: ['stop-check'],
81
+ // The events with no guard of their own (hq-core-rust US-050 c3). Each
82
+ // needs the native port of the old dispatcher's own work for it
83
+ // (`lifecycle-dispatch`) before it may leave the old registration. An engine
84
+ // without that evaluator keeps the old registration for the event, and
85
+ // `hq-hook run` answers such an event with no verdict (exit 1 and a line on
86
+ // stderr), never a silent allow. Claude Code sends Notification,
87
+ // SubagentStart and SubagentStop; Codex and the fleet runtimes SubagentStop;
88
+ // the Grok bridge all eight.
89
+ Notification: ['lifecycle-dispatch'],
90
+ SubagentStart: ['lifecycle-dispatch'],
91
+ SubagentStop: ['lifecycle-dispatch'],
92
+ StopCancelled: ['lifecycle-dispatch'],
93
+ StopFailure: ['lifecycle-dispatch'],
94
+ PostToolUseFailure: ['lifecycle-dispatch'],
95
+ PermissionDenied: ['lifecycle-dispatch'],
96
+ PostCompact: ['lifecycle-dispatch'],
80
97
  };
81
98
  /** Schema of `hq-hook capabilities --json`. */
82
99
  export const CAPABILITIES_SCHEMA = 'hq-hook.capabilities.v1';
@@ -336,6 +353,14 @@ function warnOnce(message, warn) {
336
353
  * registrations on that host. `HQ_SKIP_HOST_CANARY_GATE=1` lets the switch go
337
354
  * on, with a warning that names what it bypassed. `fleet-local` is not a host
338
355
  * the canary runs and is not gated here.
356
+ *
357
+ * A reindex started by a hook (`hq reindex --from-hook`, which sets
358
+ * [`REINDEX_FROM_HOOK_ENV`]) never changes a host's core (owner ruling (A) on
359
+ * #3039, Q-ST2-04-1): the gate answers with the core the host is on now in
360
+ * this root ([`hostOnCoreNext`]), whatever the canary says, so a missing or
361
+ * stale canary record cannot move a host back to the old dispatcher, and a new
362
+ * canary cannot move a host onto the new core. A manual or install-time
363
+ * reindex still applies the gate.
339
364
  */
340
365
  function hostCanaryGate(home, env, version, platform, warn) {
341
366
  return (root, host) => {
@@ -346,6 +371,15 @@ function hostCanaryGate(home, env, version, platform, warn) {
346
371
  if (host === 'agents-v2')
347
372
  return false;
348
373
  const gate = checkHostCanary({ home, root, host, engineVersion: version, env, platform });
374
+ if (env[REINDEX_FROM_HOOK_ENV] === '1') {
375
+ const current = hostOnCoreNext(home, env, root, host);
376
+ if (current !== gate.allowed) {
377
+ warnOnce(current
378
+ ? `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`
379
+ : `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);
380
+ }
381
+ return current;
382
+ }
349
383
  if (gate.skipped) {
350
384
  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);
351
385
  }
@@ -355,6 +389,43 @@ function hostCanaryGate(home, env, version, platform, warn) {
355
389
  return gate.allowed;
356
390
  };
357
391
  }
392
+ /**
393
+ * Set by `hq reindex --from-hook` (a reindex the daemon runs for a hook's
394
+ * request note): the host canary gate then keeps every host on the core it is
395
+ * on now ([`hostCanaryGate`]).
396
+ */
397
+ export const REINDEX_FROM_HOOK_ENV = 'HQ_REINDEX_FROM_HOOK';
398
+ /** The hook files `hq reindex` writes for `host` and this root. */
399
+ function hostHookFiles(home, env, root, host) {
400
+ if (host === 'claude')
401
+ return [path.join(root, '.claude', 'settings.json'), path.join(root, '.claude', 'settings.local.json'), userHookSettingsFile('claude', home, env)];
402
+ if (host === 'codex')
403
+ return [userHookSettingsFile('codex', home, env), path.join(root, '.codex', 'hooks.json')];
404
+ return [path.join(home, '.grok', 'hooks', 'hq-hq-bridge.json')];
405
+ }
406
+ /**
407
+ * True when `host` is registered on the new core in this root: one of its hook
408
+ * files holds a new-core entry (`hq-hook run --host ...` through the stable
409
+ * link) for this root. A missing or unreadable file holds none.
410
+ */
411
+ export function hostOnCoreNext(home, env, root, host) {
412
+ return hostHookFiles(home, env, root, host).some((file) => {
413
+ let doc;
414
+ try {
415
+ doc = JSON.parse(fs.readFileSync(file, 'utf8'));
416
+ }
417
+ catch {
418
+ return false;
419
+ }
420
+ const hooks = doc && typeof doc === 'object' ? doc.hooks : undefined;
421
+ if (!hooks || typeof hooks !== 'object')
422
+ return false;
423
+ return Object.values(hooks).some((groups) => Array.isArray(groups) && groups.some((group) => {
424
+ const entries = groupEntries(group);
425
+ return !!entries && entries.some((entry) => isEntry(entry) && isCoreNextEntry(entry, root));
426
+ }));
427
+ });
428
+ }
358
429
  /**
359
430
  * [`coreNextTarget`], with any failure turned into one warning and null, so
360
431
  * `hq install` and `hq reindex` go on with the old registrations.
@@ -479,24 +550,37 @@ export function placeEvent(groups, options) {
479
550
  * engine instead; matchers, timeouts, the other events and every other entry
480
551
  * stay as they are.
481
552
  */
482
- export function grokBridgeJson(source, root, target, platform = process.platform) {
483
- if (!target)
553
+ export function grokBridgeJson(source, root, target, platform = process.platform, home) {
554
+ if (!target && platform !== 'win32')
484
555
  return source;
485
556
  const doc = JSON.parse(source);
486
557
  if (!doc.hooks || typeof doc.hooks !== 'object')
487
558
  return source;
488
- if (!Object.keys(doc.hooks).some((event) => target.events.includes(event)))
559
+ if (platform !== 'win32' && !Object.keys(doc.hooks).some((event) => target?.events.includes(event)))
489
560
  return source;
490
561
  const hooks = {};
491
562
  for (const [event, groups] of Object.entries(doc.hooks)) {
492
- hooks[event] = !Array.isArray(groups) || !target.events.includes(event) ? groups : groups.map((group) => {
563
+ hooks[event] = !Array.isArray(groups) ? groups : groups.map((group) => {
493
564
  if (!group || !Array.isArray(group.hooks))
494
565
  return group;
495
566
  return {
496
567
  ...group,
497
568
  hooks: group.hooks.map((entry) => {
498
- if (!entry || typeof entry.command !== 'string' || !entry.command.includes(GROK_BRIDGE_SCRIPT))
569
+ if (!entry || typeof entry.command !== 'string')
499
570
  return entry;
571
+ if (platform === 'win32' && /^(?:\.\/hq-grok-hook-adapter\.sh|bash "[^"]*\/\.grok\/hooks\/hq-grok-hook-adapter\.sh"(?: & if errorlevel 1 exit \/b 2)?)$/.test(entry.command)) {
572
+ return { ...entry, command: windowsGrokShellCommand(path.win32.join(root, '.grok/hooks/hq-grok-hook-adapter.sh'), event) };
573
+ }
574
+ if (!entry.command.includes(GROK_BRIDGE_SCRIPT))
575
+ return entry;
576
+ if (!target?.events.includes(event)) {
577
+ if (platform !== 'win32')
578
+ return entry;
579
+ if (!home)
580
+ throw new Error('Windows Grok bridge requires an explicit home folder');
581
+ const bridge = path.win32.join(home, '.grok', 'hooks', GROK_BRIDGE_SCRIPT);
582
+ return { ...entry, command: windowsGrokShellCommand(bridge, event) };
583
+ }
500
584
  const { env: _env, command: _command, ...rest } = entry;
501
585
  const command = platform === 'win32'
502
586
  ? coreNextCommandWindows(target.coreNext, 'grok', event, root, 'in-tree')
@@ -508,6 +592,15 @@ export function grokBridgeJson(source, root, target, platform = process.platform
508
592
  }
509
593
  return `${JSON.stringify({ ...doc, hooks }, null, 2)}\n`;
510
594
  }
595
+ /** cmd.exe never expands HOME or resolves a project hook relative to its file. */
596
+ function windowsGrokShellCommand(script, event) {
597
+ if (!path.win32.isAbsolute(script) || /["\r\n\0%!^&|<>]/.test(script))
598
+ throw new Error('Grok hook path cannot be quoted safely for cmd.exe');
599
+ const command = `bash "${script.replace(/\\/g, '/')}"`;
600
+ // Grok's blocking status is 2. A missing bash/script ordinarily returns
601
+ // 1/127/9009, so guard events must convert a failed launch to that status.
602
+ return event === 'PreToolUse' ? `${command} & if errorlevel 1 exit /b 2` : command;
603
+ }
511
604
  /**
512
605
  * Write `content` to `file` through the shared safe store (store rule v2): the
513
606
  * folder is held open and checked (a real folder of this user, not a link,
@@ -36,7 +36,7 @@ export interface PackageUseLeaseHandoff {
36
36
  export declare function npmPrefix(root: string, platform?: NodeJS.Platform): string | null;
37
37
  export declare function packageUseLeaseDirectory(prefix: string, stateDirectory?: string): string;
38
38
  declare function waitForUpdateRequest(requestPath: string, timeoutMs: number, notify?: (() => void) | null): void;
39
- export declare function acquirePackageUseLease(prefix: string, hqVersion: string, stateDirectory?: string, purpose?: PackageUseLeasePurpose): PackageUseLease;
39
+ export declare function acquirePackageUseLease(prefix: string, hqVersion: string, stateDirectory?: string, purpose?: PackageUseLeasePurpose, waitMs?: number, onMaxHold?: () => void): PackageUseLease;
40
40
  /**
41
41
  * Create a bounded, per-reexec rendezvous in the current lease directory.
42
42
  * The child confirms readiness only after publishing its own atomic lease.
@@ -231,7 +231,7 @@ function waitForUpdateRequest(requestPath, timeoutMs, notify = null) {
231
231
  function notifyWaitingForUpdate() {
232
232
  process.stderr.write("hq-cli: waiting for the HQ CLI update to finish...\n");
233
233
  }
234
- export function acquirePackageUseLease(prefix, hqVersion, stateDirectory, purpose = "command") {
234
+ export function acquirePackageUseLease(prefix, hqVersion, stateDirectory, purpose = "command", waitMs = updateWaitTimeoutMs(), onMaxHold) {
235
235
  const directory = packageUseLeaseDirectory(prefix, stateDirectory);
236
236
  mkdirSync(directory, { recursive: true, mode: 0o700 });
237
237
  const requestPath = path.join(directory, UPDATE_REQUEST);
@@ -245,6 +245,7 @@ export function acquirePackageUseLease(prefix, hqVersion, stateDirectory, purpos
245
245
  const tempPath = `${leasePath}.${Math.random().toString(36).slice(2)}.tmp`;
246
246
  let released = false;
247
247
  let heartbeatInFlight = false;
248
+ let expiryNotified = false;
248
249
  let heartbeat = null;
249
250
  const acquiredAtMs = Date.now();
250
251
  const maxHoldMs = packageUseLeaseMaxHoldMs();
@@ -253,11 +254,18 @@ export function acquirePackageUseLease(prefix, hqVersion, stateDirectory, purpos
253
254
  if (released || heartbeatInFlight)
254
255
  return;
255
256
  const heldMs = Date.now() - acquiredAtMs;
256
- if (heldMs >= maxHoldMs) {
257
- process.stderr.write(`hq-cli: released the HQ CLI package-use lease held by pid ${record.pid} (${purpose}) ` +
258
- `after ${formatHoldDuration(heldMs)} so HQ CLI updates are not blocked\n`);
259
- release();
260
- return;
257
+ if (heldMs >= maxHoldMs && !expiryNotified) {
258
+ expiryNotified = true;
259
+ if (onMaxHold) {
260
+ // The owner is responsible for stopping package reads and releasing.
261
+ onMaxHold();
262
+ }
263
+ else {
264
+ process.stderr.write(`hq-cli: released the HQ CLI package-use lease held by pid ${record.pid} (${purpose}) ` +
265
+ `after ${formatHoldDuration(heldMs)} so HQ CLI updates are not blocked\n`);
266
+ release();
267
+ return;
268
+ }
261
269
  }
262
270
  heartbeatInFlight = true;
263
271
  const now = new Date();
@@ -289,7 +297,7 @@ export function acquirePackageUseLease(prefix, hqVersion, stateDirectory, purpos
289
297
  };
290
298
  const releaseOnExit = () => release();
291
299
  for (let attempt = 0; attempt < 2; attempt += 1) {
292
- waitForUpdateRequest(requestPath, updateWaitTimeoutMs(), notifyWaitingForUpdate);
300
+ waitForUpdateRequest(requestPath, waitMs, notifyWaitingForUpdate);
293
301
  try {
294
302
  writeFileSync(tempPath, `${JSON.stringify(record)}\n`, { flag: "wx", mode: 0o600 });
295
303
  renameSync(tempPath, leasePath);
@@ -33,6 +33,23 @@ The CLI stores the HQ root at `~/.hq/root` and keeps the folder registry in
33
33
  `~/.hq/registry.json`. These files belong to the current host. They are not
34
34
  stored in a repository or synced HQ folder.
35
35
 
36
+ While it updates a runtime's config file (for example `~/.claude.json`), the
37
+ installer holds a lock file beside it (`~/.claude.json.hqlock`). A second hq
38
+ command that finds the lock waits up to 10 seconds and then stops without
39
+ writing, and its message gives the time at which hq clears the lock by itself.
40
+ hq clears a lock once it is older than the maximum hold time, even when the
41
+ process that wrote it still appears to be running. A lock whose process has
42
+ exited is cleared after 30 seconds. If a lock is past its limit but another
43
+ program has the file open (on Windows, without delete sharing), hq clears it
44
+ once that program closes the file, and the message says so. If the lock
45
+ exists but cannot be read (for example it was left by an hq command run as
46
+ root, the path is a directory, or it is a symlink whose target is missing), hq waits out the 10 seconds, then stops and
47
+ names the lock and the read error; it never clears a lock it cannot read. The default
48
+ maximum hold time is 10 minutes. `HQ_CONFIG_LOCK_MAX_HOLD_MS` changes it, in
49
+ whole milliseconds. Values below 10000 (10 seconds) are raised to 10000, and
50
+ values above 604800000 (7 days) are lowered to 604800000. 0, negative numbers
51
+ and anything that is not a whole number are ignored, and the default applies.
52
+
36
53
  Windows requires Windows PowerShell 5.1 or PowerShell 7 for the bundled pipe
37
54
  host. If it is unavailable, the pipe cannot be created with a verified
38
55
  current-user-only DACL, or another process already owns the pipe name, hqd
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@indigoai-us/hq-cli",
3
- "version": "5.345.226",
3
+ "version": "5.345.228",
4
4
  "description": "HQ by Indigo management CLI — modules and cloud sync",
5
5
  "main": "dist/index.js",
6
6
  "bin": {
@@ -94,6 +94,7 @@
94
94
  "eslint": "^10.5.0",
95
95
  "husky": "^9.1.7",
96
96
  "lint-staged": "^15.5.2",
97
+ "tar": "7.5.22",
97
98
  "typescript": "^5.7.0",
98
99
  "typescript-eslint": "^8.61.1",
99
100
  "vitest": "^4.1.2"
@@ -124,11 +125,11 @@
124
125
  "*.{ts,tsx,mts,cts,js,jsx,mjs,cjs}": "eslint --cache --no-error-on-unmatched-pattern"
125
126
  },
126
127
  "optionalDependencies": {
127
- "@indigoai-us/hq-hook-win32-x64": "5.345.226",
128
- "@indigoai-us/hq-hook-win32-arm64": "5.345.226",
129
- "@indigoai-us/hq-hook-darwin-x64": "5.345.226",
130
- "@indigoai-us/hq-hook-darwin-arm64": "5.345.226",
131
- "@indigoai-us/hq-hook-linux-x64": "5.345.226",
132
- "@indigoai-us/hq-hook-linux-arm64": "5.345.226"
128
+ "@indigoai-us/hq-hook-win32-x64": "5.345.228",
129
+ "@indigoai-us/hq-hook-win32-arm64": "5.345.228",
130
+ "@indigoai-us/hq-hook-darwin-x64": "5.345.228",
131
+ "@indigoai-us/hq-hook-darwin-arm64": "5.345.228",
132
+ "@indigoai-us/hq-hook-linux-x64": "5.345.228",
133
+ "@indigoai-us/hq-hook-linux-arm64": "5.345.228"
133
134
  }
134
135
  }