@indigoai-us/hq-cli 5.345.217 → 5.345.218

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 (50) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/README.md +1 -1
  3. package/assets/bot-workers/setup/skills/add-a-pack.md +3 -3
  4. package/assets/scaffold/core/scripts/hq-session.sh +4 -0
  5. package/dist/commands/cloud.d.ts +1 -1
  6. package/dist/commands/cloud.js +1 -1
  7. package/dist/commands/core-hq-session-native.js +3 -0
  8. package/dist/commands/install-global.js +1 -1
  9. package/dist/commands/members.js +1 -1
  10. package/dist/commands/pack-start-bot.d.ts +1 -1
  11. package/dist/commands/pack-start-bot.js +2 -2
  12. package/dist/commands/pkg-update.js +1 -1
  13. package/dist/commands/sync-narrow.js +1 -1
  14. package/dist/commands/team-sync.js +1 -1
  15. package/dist/data/command-states.json +8 -1
  16. package/dist/lib/billing/usage-cost.js +5 -2
  17. package/dist/lib/bot/pack-link.d.ts +2 -2
  18. package/dist/lib/bot/pack-link.js +2 -2
  19. package/dist/lib/daemon/hook-env.d.ts +32 -0
  20. package/dist/lib/daemon/hook-env.js +51 -0
  21. package/dist/lib/daemon/ops/policy.js +5 -3
  22. package/dist/lib/daemon/run.js +7 -1
  23. package/dist/lib/doctor/checks/host-core.d.ts +2 -0
  24. package/dist/lib/doctor/checks/host-core.js +78 -10
  25. package/dist/lib/doctor/checks/sync-runtime.js +3 -3
  26. package/dist/lib/environment/credential-shapes.d.ts +61 -0
  27. package/dist/lib/environment/credential-shapes.js +333 -0
  28. package/dist/lib/environment/profile.js +4 -16
  29. package/dist/lib/hook-engine/coverage.d.ts +13 -0
  30. package/dist/lib/hook-engine/coverage.js +124 -0
  31. package/dist/lib/hook-engine/reconcile.js +294 -114
  32. package/dist/lib/hook-engine/registration.d.ts +10 -3
  33. package/dist/lib/hook-engine/registration.js +52 -16
  34. package/dist/lib/install/claude-targets.js +28 -15
  35. package/dist/lib/install/codex-pack-contributions.js +1 -1
  36. package/dist/lib/install/codex-targets.js +24 -11
  37. package/dist/lib/install/hook-target.d.ts +2 -2
  38. package/dist/lib/install/hook-target.js +7 -5
  39. package/dist/lib/packages/setup-block.d.ts +2 -2
  40. package/dist/lib/packages/setup-block.js +2 -2
  41. package/dist/lib/packages/start-bot.d.ts +1 -1
  42. package/dist/lib/packages/start-bot.js +1 -1
  43. package/dist/main.js +1 -1
  44. package/dist/types.d.ts +1 -1
  45. package/dist/utils/callback-port-busy.d.ts +1 -1
  46. package/dist/utils/callback-port-busy.js +4 -4
  47. package/dist/utils/hook-trust.js +4 -1
  48. package/dist/utils/host-registration.d.ts +57 -4
  49. package/dist/utils/host-registration.js +140 -13
  50. package/package.json +7 -7
@@ -1,4 +1,4 @@
1
- import { existsSync, readFileSync } from 'node:fs';
1
+ import { existsSync, lstatSync, readFileSync } from 'node:fs';
2
2
  import { writeConfigAtomic, jsonFormat } from '../../commands/mcp-registration.js';
3
3
  import { join } from 'node:path';
4
4
  import { homedir } from 'node:os';
@@ -6,57 +6,157 @@ import { addHqHooks, removeHqHooks } from '../install/claude-targets.js';
6
6
  import { legacyHookTarget } from '../install/hook-target.js';
7
7
  import { addCodexHooks, removeCodexHooks, codexHookEntry, codexHookTrustKeys } from '../install/codex-targets.js';
8
8
  import { engineArgs, isCoreNextEntry, isNativeEntry, registrationEngine } from './registration.js';
9
- import { coreNextArgs, coreNextTargetOrWarn } from '../../utils/host-registration.js';
9
+ import { coreNextArgs, coreNextTargetOrWarn, placeEvent } from '../../utils/host-registration.js';
10
+ import { forHost } from './coverage.js';
10
11
  /** The project master-hook command shipped in HQ's .claude/settings.json. */
11
12
  function projectClaudeCommand(event) {
12
13
  return 'env BASH_ENV=/dev/null bash "$CLAUDE_PROJECT_DIR/.claude/hooks/master-hook.sh" ' + event;
13
14
  }
15
+ function hooksOf(doc) {
16
+ const hooks = doc?.hooks;
17
+ return hooks && typeof hooks === 'object' && !Array.isArray(hooks) ? hooks : undefined;
18
+ }
19
+ function entriesOf(groups) {
20
+ return Array.isArray(groups)
21
+ ? groups.flatMap((g) => Array.isArray(g?.hooks) ? g.hooks.filter((h) => !!h && typeof h === 'object') : [])
22
+ : [];
23
+ }
24
+ function allEntries(doc) {
25
+ return Object.values(hooksOf(doc) ?? {}).flatMap(entriesOf);
26
+ }
27
+ function readJson(file) {
28
+ try {
29
+ return jsonFormat.parse(readFileSync(file, 'utf8'));
30
+ }
31
+ catch {
32
+ // Absent or not JSON: no registration of ours to reconcile in it.
33
+ return undefined;
34
+ }
35
+ }
36
+ /** Run `merge` over each event's groups; the same object back when nothing changed. */
37
+ function mapEvents(doc, events, merge) {
38
+ const hooks = hooksOf(doc);
39
+ const next = { ...(hooks ?? {}) };
40
+ for (const event of new Set([...Object.keys(next), ...events])) {
41
+ const groups = next[event];
42
+ if (groups !== undefined && !Array.isArray(groups))
43
+ continue;
44
+ const merged = merge(event, groups);
45
+ if (merged === undefined || (groups === undefined && merged.length === 0))
46
+ continue;
47
+ next[event] = merged;
48
+ }
49
+ const out = { ...doc, hooks: next };
50
+ return JSON.stringify(out) === JSON.stringify(hooks ? doc : { ...doc, hooks: {} }) ? doc : out;
51
+ }
14
52
  /**
15
- * Rewrite matching entries where they sit. Groups, order, foreign entries and
16
- * extra fields such as timeout are kept, so a flag-on then flag-off pass
17
- * restores the original file.
53
+ * `.claude/settings.local.json` without the new-core entries for this root,
54
+ * and the entries it held, by event. An HQ settings merge (`hq rescue`, an HQ
55
+ * update) moves an entry it does not ship out of settings.json into this file
56
+ * as a "user customization"; the new-core entry the first release wrote in
57
+ * place of master-hook.sh went there that way, and its master-hook line was
58
+ * left out of settings.json. Empty groups, events and the hooks key this
59
+ * leaves behind are removed; every other entry, and every other key, stays.
18
60
  */
19
- function rewriteEntries(doc, convert) {
20
- let changed = false;
21
- const hooks = {};
22
- for (const [event, groups] of Object.entries(doc.hooks)) {
23
- hooks[event] = !Array.isArray(groups) ? groups : groups.map((group) => {
24
- if (!Array.isArray(group?.hooks))
25
- return group;
26
- return { ...group, hooks: group.hooks.map((entry) => {
27
- const next = entry && typeof entry === 'object' ? convert(entry, event) : undefined;
28
- if (!next || JSON.stringify(next) === JSON.stringify(entry))
29
- return entry;
30
- changed = true;
31
- return next;
32
- }) };
33
- });
61
+ function withoutMovedEntries(local, root) {
62
+ const moved = new Map();
63
+ const hooks = hooksOf(local);
64
+ if (!hooks)
65
+ return { doc: local, moved };
66
+ const next = {};
67
+ for (const [event, groups] of Object.entries(hooks)) {
68
+ if (!Array.isArray(groups)) {
69
+ next[event] = groups;
70
+ continue;
71
+ }
72
+ let removed = false;
73
+ const kept = [];
74
+ for (const group of groups) {
75
+ if (!Array.isArray(group?.hooks)) {
76
+ kept.push(group);
77
+ continue;
78
+ }
79
+ const entries = group.hooks.filter((entry) => {
80
+ if (!entry || typeof entry !== 'object' || !isCoreNextEntry(entry, root))
81
+ return true;
82
+ if (!moved.has(event))
83
+ moved.set(event, entry);
84
+ removed = true;
85
+ return false;
86
+ });
87
+ if (entries.length === group.hooks.length)
88
+ kept.push(group);
89
+ else if (entries.length > 0)
90
+ kept.push({ ...group, hooks: entries });
91
+ }
92
+ if (!removed)
93
+ next[event] = groups;
94
+ else if (kept.length > 0)
95
+ next[event] = kept;
34
96
  }
35
- return changed ? { ...doc, hooks } : doc;
97
+ if (moved.size === 0)
98
+ return { doc: local, moved };
99
+ const doc = { ...local, hooks: next };
100
+ if (Object.keys(next).length === 0)
101
+ delete doc.hooks;
102
+ return { doc, moved };
103
+ }
104
+ /** Write `merge(doc)` to `file` under the shared lock, verified, when it changes anything. */
105
+ function writeMerged(file, home, merge) {
106
+ let expected;
107
+ let written;
108
+ writeConfigAtomic({ target: file, pack: 'hq-hook-engine', format: {
109
+ ...jsonFormat,
110
+ assertEntry: (doc) => {
111
+ if (expected !== undefined && JSON.stringify(doc) !== expected)
112
+ throw new Error('Hook registration verification failed');
113
+ },
114
+ }, env: { home }, assertName: 'hooks', merge: (doc) => {
115
+ const next = doc && typeof doc === 'object' ? merge(doc) : doc;
116
+ expected = JSON.stringify(next);
117
+ written = next;
118
+ return next;
119
+ } });
120
+ return written;
36
121
  }
37
122
  /** Reconcile existing registrations only; reindex must not install a runtime. */
38
123
  export function reconcileHookRegistrations(root, home = homedir(), env = process.env, daemonInstalled) {
39
124
  const result = { codexUserKeys: [], failures: [] };
40
- // `core.next` (hq-core-rust US-017) wins over the pinned launcher flag. Both
41
- // off: registrations are left exactly as they are, or rolled back to the
42
- // bash target when an earlier pass wrote a native entry.
43
- // With `core.next` on, only the events the engine has every guard for
44
- // switch (`coreNext.events`); the others keep the flag-off registration. A
45
- // failure to set up the new core is one warning and the flag-off path.
125
+ // `core.next` (hq-core-rust US-017) wins over the pinned launcher flag.
126
+ // With it on, an event switches on a host only when the engine covers every
127
+ // hook the old dispatcher runs for it there (`coverage.ts`); its new-core
128
+ // entry then replaces the shell entry, so the engine owns the whole event.
129
+ // Every other event stays on the shell with no new-core entry. With the flag
130
+ // off, or the kill switch on as this process sees it (`HQ_CORE_NEXT=off`,
131
+ // `~/.hq/state/core-next.off`, or the engine-wide switch), the new-core
132
+ // entries are removed and the shell registrations are what they were before
133
+ // the switch. A failure to set up the new core is one warning and the
134
+ // flag-off path.
46
135
  const coreNext = coreNextTargetOrWarn(home, env);
136
+ const claudeNext = forHost(coreNext, root, 'claude');
137
+ const codexNext = forHost(coreNext, root, 'codex');
47
138
  const launcher = registrationEngine(home, env);
48
139
  const native = coreNext ?? (launcher ? { engine: launcher } : null);
49
140
  const ours = (entry) => isNativeEntry(entry, root) || isCoreNextEntry(entry, root);
50
- // Flag-off rollback restores the same bash target install would choose (the
51
- // hqd shim when the daemon serves this root). Resolved only when a
52
- // registration is rewritten, so the default-off path reads no daemon state.
53
- let target;
54
- const globalTarget = () => (target ??= coreNext
55
- ? { ...coreNext, fallback: legacyHookTarget(root, home, daemonInstalled, env) }
56
- : legacyHookTarget(root, home, daemonInstalled, env));
141
+ // The shell target install would choose (the hqd shim when the daemon serves
142
+ // this root). Resolved only when a registration is rewritten, so the
143
+ // default-off path reads no daemon state.
144
+ let shell;
145
+ const shellTarget = () => (shell ??= legacyHookTarget(root, home, daemonInstalled, env));
146
+ const globalTarget = (host) => {
147
+ const next = host === 'codex' ? codexNext : claudeNext;
148
+ return next ? { ...next, fallback: shellTarget() } : shellTarget();
149
+ };
57
150
  const codexBash = (event) => [codexHookEntry(root, event, 'master').command, codexHookEntry(root, event, 'shim').command];
151
+ // Claude Code project files: settings.json and the settings.local.json
152
+ // Claude Code merges over it, together.
153
+ try {
154
+ result.failures.push(...reconcileClaudeProject(root, home, claudeNext, launcher, ours, !!native));
155
+ }
156
+ catch (error) {
157
+ result.failures.push(`${join(root, '.claude/settings.json')}: ${error.message}`);
158
+ }
58
159
  for (const [file, runtime, global] of [
59
- [join(root, '.claude/settings.json'), 'claude', false],
60
160
  [join(env.CLAUDE_CONFIG_DIR || join(home, '.claude'), 'settings.json'), 'claude', true],
61
161
  [join(env.CODEX_HOME || join(home, '.codex'), 'hooks.json'), 'codex', true],
62
162
  [join(root, '.codex/hooks.json'), 'codex', false],
@@ -66,90 +166,58 @@ export function reconcileHookRegistrations(root, home = homedir(), env = process
66
166
  try {
67
167
  if (!existsSync(file))
68
168
  continue;
69
- // Default-off must not acquire a write lock or create backups for a legacy
70
- // registration. The merge below repeats this check under the lock when a
71
- // native entry was found, so a concurrent writer still wins safely.
72
- if (!native) {
73
- let current;
74
- // A file we cannot parse holds no native entry of ours; leave it untouched.
75
- try {
76
- current = jsonFormat.parse(readFileSync(file, 'utf8'));
77
- }
78
- catch {
79
- continue;
169
+ const merge = (doc) => {
170
+ if (!hooksOf(doc))
171
+ return doc;
172
+ if (!native && !allEntries(doc).some(ours))
173
+ return doc;
174
+ if (global) {
175
+ if ((runtime === 'codex' ? removeCodexHooks(doc, root) : removeHqHooks(doc, root)) === doc)
176
+ return doc;
177
+ return runtime === 'codex' ? addCodexHooks(doc, root, globalTarget('codex')) : addHqHooks(doc, root, globalTarget('claude'));
80
178
  }
81
- const entries = current?.hooks && typeof current.hooks === 'object'
82
- ? Object.values(current.hooks).flatMap(groups => Array.isArray(groups) ? groups.flatMap(g => Array.isArray(g?.hooks) ? g.hooks : []) : [])
83
- : [];
84
- if (!entries.some(e => e && ours(e)))
85
- continue;
86
- }
87
- let expected;
88
- let codexKeys;
89
- writeConfigAtomic({ target: file, pack: 'hq-hook-engine', format: {
90
- ...jsonFormat,
91
- assertEntry: (doc) => {
92
- if (expected !== undefined && JSON.stringify(doc) !== expected)
93
- throw new Error('Hook registration verification failed');
179
+ // Project hooks.json: only an entry install itself writes is
180
+ // converted. HQ's own project file routes through hook-gate.sh and
181
+ // has none, so it stays as is.
182
+ // `command` keeps its place to and from the new core, so switching
183
+ // back restores the original bytes. The launcher path keeps its
184
+ // existing key order.
185
+ const inPlace = (entry, want) => {
186
+ const { commandWindows: _old, ...kept } = entry;
187
+ return { ...kept, command: want.command, ...(want.commandWindows ? { commandWindows: want.commandWindows } : {}) };
188
+ };
189
+ return mapEvents(doc, [], (event, groups) => groups && placeEvent(groups, {
190
+ isShell: (entry) => isNativeEntry(entry, root) || codexBash(event).includes(entry.command),
191
+ isNative: (entry) => isCoreNextEntry(entry, root),
192
+ toShell: (entry) => {
193
+ const { command: _command, commandWindows: _windows, ...rest } = entry;
194
+ const want = codexHookEntry(root, event, shellTarget());
195
+ if (entry.command === want.command && entry.commandWindows === want.commandWindows)
196
+ return entry;
197
+ if (isCoreNextEntry(entry, root) || coreNext)
198
+ return inPlace(entry, want);
199
+ return { ...rest, command: want.command, ...(want.commandWindows ? { commandWindows: want.commandWindows } : {}) };
94
200
  },
95
- }, env: { home }, assertName: 'hooks', merge: (doc) => {
96
- if (!doc || typeof doc !== 'object' || !doc.hooks || typeof doc.hooks !== 'object')
97
- return doc;
98
- const entries = Object.values(doc.hooks).flatMap(groups => Array.isArray(groups) ? groups.flatMap(g => Array.isArray(g?.hooks) ? g.hooks : []) : []);
99
- if (!native && !entries.some(e => e && ours(e)))
100
- return doc;
101
- if (global && (runtime === 'codex' ? removeCodexHooks(doc, root) : removeHqHooks(doc, root)) === doc)
102
- return doc;
103
- let next;
104
- if (global)
105
- next = runtime === 'codex' ? addCodexHooks(doc, root, globalTarget()) : addHqHooks(doc, root, globalTarget());
106
- else if (runtime === 'codex') {
107
- // Only an entry install itself writes is converted. HQ's own project
108
- // file routes through hook-gate.sh and has none, so it stays as is.
109
- next = rewriteEntries(doc, (entry, event) => {
110
- if (!ours(entry) && !codexBash(event).includes(entry.command))
111
- return undefined;
112
- const { command: _command, commandWindows: _windows, ...rest } = entry;
113
- const { command, commandWindows } = codexHookEntry(root, event, globalTarget());
114
- // To or from the new core (US-017), `command` keeps its place so
115
- // switching back restores the original bytes. The launcher path
116
- // keeps its existing key order.
117
- if (isCoreNextEntry(entry, root) || coreNext) {
118
- const { commandWindows: _old, ...inPlace } = entry;
119
- return { ...inPlace, command, ...(commandWindows ? { commandWindows } : {}) };
120
- }
121
- return { ...rest, command, ...(commandWindows ? { commandWindows } : {}) };
122
- });
123
- }
124
- else {
125
- // Only the exact shipped master-hook command is converted; a wrapped
126
- // or extended invocation is someone's edit and is left alone.
127
- next = rewriteEntries(doc, (entry, event) => {
128
- if (!ours(entry) && entry.command !== projectClaudeCommand(event))
129
- return undefined;
130
- const { args, commandWindows: _windows, ...rest } = entry;
131
- // The event an existing native entry was written for: the first
132
- // launcher argument, or the one after `run --host claude`.
133
- const written = Array.isArray(args) ? (args[0] === 'run' ? args[3] : args[0]) : undefined;
134
- const original = typeof written === 'string' ? written : event;
135
- // The new core only for an event it has every guard for.
136
- if (coreNext?.events.includes(original))
137
- return { ...rest, command: coreNext.coreNext, args: coreNextArgs('claude', original, root, 'project') };
138
- if (launcher)
139
- return { ...rest, command: launcher, args: engineArgs(root, original, 'claude') };
140
- return { ...rest, command: projectClaudeCommand(original) };
141
- });
142
- }
143
- expected = JSON.stringify(next);
144
- if (runtime === 'codex' && global)
145
- codexKeys = codexHookTrustKeys(next, file, root);
146
- return next;
147
- } });
201
+ toNative: codexNext?.events.includes(event) ? (entry) => inPlace(entry, codexHookEntry(root, event, codexNext)) : null,
202
+ }));
203
+ };
204
+ // Nothing to change: no write lock, no backup. A file we cannot parse
205
+ // holds no entry of ours when the switch is off and is left alone; with
206
+ // it on, the locked write below reports it as a failure.
207
+ const current = readJson(file);
208
+ if (!current && !native)
209
+ continue;
210
+ if (current && JSON.stringify(merge(current)) === JSON.stringify(current)) {
211
+ if (current && runtime === 'codex' && global && native)
212
+ result.codexUserKeys = codexHookTrustKeys(current, file, root);
213
+ continue;
214
+ }
215
+ const next = writeMerged(file, home, merge);
148
216
  // Keys are positions in the file. Only once the write and its verify have
149
217
  // succeeded do they point at HQ's entries; a failed write leaves the old
150
218
  // file, where the same position can hold a foreign hook.
151
- if (codexKeys)
152
- result.codexUserKeys = codexKeys;
219
+ if (runtime === 'codex' && global)
220
+ result.codexUserKeys = codexHookTrustKeys(next, file, root);
153
221
  }
154
222
  catch (error) {
155
223
  result.failures.push(`${file}: ${error.message}`);
@@ -157,4 +225,116 @@ export function reconcileHookRegistrations(root, home = homedir(), env = process
157
225
  }
158
226
  return result;
159
227
  }
228
+ /**
229
+ * Any master-hook.sh registration for `event`, shipped or wrapped
230
+ * (`... master-hook.sh" Stop 2>>log`, `bash .../master-hook.sh 'Stop'`).
231
+ */
232
+ function hasMasterHook(docs, event) {
233
+ const pattern = new RegExp(`master-hook\\.sh["']?\\s+["']?${event}(?![A-Za-z])`);
234
+ return docs.some((doc) => entriesOf(hooksOf(doc)?.[event]).some((entry) => typeof entry.command === 'string' && pattern.test(entry.command)));
235
+ }
236
+ /**
237
+ * `.claude/settings.json` and `.claude/settings.local.json` of the HQ root.
238
+ *
239
+ * settings.json: an event the new core covers in full (`target`, already
240
+ * narrowed to Claude Code in this root) has its shipped master-hook entry (or
241
+ * the launcher entry that stands for it) replaced in place by the new-core
242
+ * entry. Every other event keeps its shell entry: a new-core entry standing in
243
+ * its place becomes master-hook again, and an event whose new-core entry was
244
+ * moved into settings.local.json, with its master-hook line lost, gets the
245
+ * master-hook entry back, unless a master-hook entry for that event (wrapped
246
+ * or not) is still registered in either file. Only the exact shipped command
247
+ * is switched; a wrapped or extended invocation is someone's edit and is left
248
+ * alone.
249
+ *
250
+ * settings.local.json: the new-core entries for this root are removed (they
251
+ * are reindex's own, moved there by an HQ settings merge); nothing else is
252
+ * touched. A settings.local.json that cannot be parsed, or that is a link, is
253
+ * not written: it is reported as a failure and left as it is, and nothing is
254
+ * restored in settings.json for it. settings.json is written first.
255
+ *
256
+ * Returns one failure line per file left alone for a reason the user must see.
257
+ */
258
+ function reconcileClaudeProject(root, home, target, launcher, ours, active) {
259
+ const failures = [];
260
+ const file = join(root, '.claude/settings.json');
261
+ const localFile = join(root, '.claude/settings.local.json');
262
+ if (!existsSync(file))
263
+ return failures;
264
+ const toShell = (event) => (entry) => {
265
+ const { args, commandWindows: _windows, ...rest } = entry;
266
+ // The event an existing native entry was written for: the first
267
+ // launcher argument, or the one after `run --host claude`.
268
+ const written = Array.isArray(args) ? (args[0] === 'run' ? args[3] : args[0]) : undefined;
269
+ const original = typeof written === 'string' ? written : event;
270
+ if (launcher)
271
+ return { ...rest, command: launcher, args: engineArgs(root, original, 'claude') };
272
+ return { ...rest, command: projectClaudeCommand(original) };
273
+ };
274
+ // The new-core entry takes the shell entry's place and keeps its other
275
+ // fields, so switching back gives the original bytes.
276
+ const toNative = (event) => (entry) => {
277
+ const { args: _args, commandWindows: _windows, ...rest } = entry;
278
+ return { ...rest, command: target.coreNext, args: coreNextArgs('claude', event, root, 'project') };
279
+ };
280
+ const project = (doc, local, moved) => {
281
+ if (!hooksOf(doc) && moved.size === 0)
282
+ return doc;
283
+ if (!active && moved.size === 0 && !allEntries(doc).some(ours))
284
+ return doc;
285
+ return mapEvents(doc, moved.keys(), (event, groups) => placeEvent(groups ?? [], {
286
+ isShell: (entry) => entry.command === projectClaudeCommand(event) || isNativeEntry(entry, root),
287
+ isNative: (entry) => isCoreNextEntry(entry, root),
288
+ toShell: toShell(event),
289
+ toNative: target?.events.includes(event) ? toNative(event) : null,
290
+ restore: moved.has(event) && !hasMasterHook([doc, local], event) ? toShell(event)(moved.get(event)) : null,
291
+ }));
292
+ };
293
+ // settings.local.json as it can be used: parsed, not a link.
294
+ const readLocal = (report) => {
295
+ let link;
296
+ try {
297
+ link = lstatSync(localFile).isSymbolicLink();
298
+ }
299
+ catch {
300
+ // Absent: nothing to clean up.
301
+ return undefined;
302
+ }
303
+ const doc = readJson(localFile);
304
+ if (!doc) {
305
+ if (report)
306
+ failures.push(`${localFile}: not valid JSON; reindex cannot check it for new-core hook entries and left it as it is`);
307
+ return undefined;
308
+ }
309
+ const { doc: next, moved } = withoutMovedEntries(doc, root);
310
+ if (link) {
311
+ if (report && moved.size > 0)
312
+ failures.push(`${localFile}: a link; reindex does not write through it, so its new-core hook entries for ${[...moved.keys()].join(', ')} were left in place. Remove them by hand.`);
313
+ return undefined;
314
+ }
315
+ return { doc, moved, next };
316
+ };
317
+ // Nothing to change in either file: no write lock, no backup.
318
+ const current = readJson(file);
319
+ // A settings.json we cannot parse is left alone, and so is settings.local.json:
320
+ // removing an entry there could leave the event with no registration at all.
321
+ // With the switch on, the locked write reports it as a failure.
322
+ if (!current) {
323
+ if (active)
324
+ writeMerged(file, home, (doc) => doc);
325
+ return failures;
326
+ }
327
+ const local = readLocal(true);
328
+ const moved = local?.moved ?? new Map();
329
+ if (JSON.stringify(project(current, local?.doc, moved)) !== JSON.stringify(current)) {
330
+ writeMerged(file, home, (doc) => {
331
+ const now = readLocal(false);
332
+ return project(doc, now?.doc, now?.moved ?? new Map());
333
+ });
334
+ }
335
+ if (local && local.moved.size > 0) {
336
+ writeMerged(localFile, home, (doc) => withoutMovedEntries(doc, root).doc);
337
+ }
338
+ return failures;
339
+ }
160
340
  //# sourceMappingURL=reconcile.js.map
@@ -10,14 +10,21 @@ export interface NativeTarget {
10
10
  */
11
11
  export declare function launcherRoot(root: string): string;
12
12
  export declare function engineArgs(root: string, event: string, runtime: 'claude' | 'codex', global?: boolean): string[];
13
- /** Recognize only our pinned executable with the exact root argument. */
13
+ /**
14
+ * True when an entry's `--hq-root` names this HQ root: the same spelling
15
+ * (trailing separators aside), or another spelling of the same folder
16
+ * (`/private/tmp/x` and `/tmp/x`, a symlinked root and its target), found
17
+ * by resolving both. An entry for any other folder is not this root's.
18
+ */
19
+ export declare function sameHqRoot(value: string | undefined, root: string): boolean;
20
+ /** Recognize only our pinned executable with this root's argument. */
14
21
  export declare function isNativeEntry(entry: Record<string, unknown>, root: string): boolean;
15
22
  /**
16
23
  * A registration that calls the new core's entry point, `hq-hook run --host
17
24
  * <host> <Event> --hq-root <root>`, through the release-stable link
18
25
  * (hq-core-rust US-017). Recognized by the stable path, the `run --host`
19
- * words and the exact root argument, in exec form (`args`) or as a command
20
- * string (Codex, Grok).
26
+ * words and a root argument that names this root ([`sameHqRoot`]), in exec
27
+ * form (`args`) or as a command string (Codex, Grok).
21
28
  */
22
29
  export declare const CORE_NEXT_LINK: RegExp;
23
30
  export declare function isCoreNextEntry(entry: Record<string, unknown>, root: string): boolean;
@@ -1,4 +1,5 @@
1
1
  /** Offline, default-off registration gate. No network work on the hook path. */
2
+ import { realpathSync } from 'node:fs';
2
3
  import { readFlagSnapshotFile, readPersonFlagSnapshotFile } from '../flag-snapshot-file.js';
3
4
  import { resolveProcessFlagCompanyContext } from '../process-flag-company-context.js';
4
5
  import { installHookEngine } from './resolve.js';
@@ -26,38 +27,73 @@ export function launcherRoot(root) {
26
27
  export function engineArgs(root, event, runtime, global = false) {
27
28
  return [event, '--hq-root', launcherRoot(root), '--runtime', runtime, ...(global && runtime === 'claude' ? ['--global'] : [])];
28
29
  }
29
- /** Recognize only our pinned executable with the exact root argument. */
30
+ /**
31
+ * The `--hq-root` value of an HQ entry: the argument after it in exec form,
32
+ * or the single-quoted word after it in a POSIX or PowerShell command string.
33
+ */
34
+ function hqRootArgument(entry) {
35
+ if (Array.isArray(entry.args)) {
36
+ const i = entry.args.indexOf('--hq-root');
37
+ const value = i >= 0 ? entry.args[i + 1] : undefined;
38
+ return typeof value === 'string' ? value : undefined;
39
+ }
40
+ if (typeof entry.command !== 'string')
41
+ return undefined;
42
+ // `& '...'` is the PowerShell form (quote doubled); anything else is POSIX (`'\''`).
43
+ if (entry.command.startsWith('& ')) {
44
+ const windows = entry.command.match(/'--hq-root' '((?:[^']|'')*)'/);
45
+ return windows ? windows[1].replace(/''/g, "'") : undefined;
46
+ }
47
+ const posix = entry.command.match(/'--hq-root' '((?:[^']|'\\'')*)'/);
48
+ return posix ? posix[1].replace(/'\\''/g, "'") : undefined;
49
+ }
50
+ function realpathOrNull(p) {
51
+ try {
52
+ return realpathSync(p);
53
+ }
54
+ catch {
55
+ // A path that does not exist names no folder, so it matches no root.
56
+ return null;
57
+ }
58
+ }
59
+ /**
60
+ * True when an entry's `--hq-root` names this HQ root: the same spelling
61
+ * (trailing separators aside), or another spelling of the same folder
62
+ * (`/private/tmp/x` and `/tmp/x`, a symlinked root and its target), found
63
+ * by resolving both. An entry for any other folder is not this root's.
64
+ */
65
+ export function sameHqRoot(value, root) {
66
+ if (value === undefined)
67
+ return false;
68
+ if (value === launcherRoot(root) || launcherRoot(value) === launcherRoot(root))
69
+ return true;
70
+ const a = realpathOrNull(value);
71
+ return a !== null && a === realpathOrNull(root);
72
+ }
73
+ /** Recognize only our pinned executable with this root's argument. */
30
74
  export function isNativeEntry(entry, root) {
31
75
  if (typeof entry.command !== 'string')
32
76
  return false;
33
77
  const pinned = /[\\/]\.hq[\\/]bin[\\/]hq-hook[\\/]\d+\.\d+\.\d+[^\\/]*[\\/]/;
34
78
  if (!pinned.test(entry.command))
35
79
  return false;
36
- const spelling = launcherRoot(root);
37
- if (Array.isArray(entry.args)) {
38
- const i = entry.args.indexOf('--hq-root');
39
- return i >= 0 && entry.args[i + 1] === spelling;
40
- }
41
- return entry.command.includes(quotePosix('--hq-root') + ' ' + quotePosix(spelling));
80
+ return sameHqRoot(hqRootArgument(entry), root);
42
81
  }
43
82
  /**
44
83
  * A registration that calls the new core's entry point, `hq-hook run --host
45
84
  * <host> <Event> --hq-root <root>`, through the release-stable link
46
85
  * (hq-core-rust US-017). Recognized by the stable path, the `run --host`
47
- * words and the exact root argument, in exec form (`args`) or as a command
48
- * string (Codex, Grok).
86
+ * words and a root argument that names this root ([`sameHqRoot`]), in exec
87
+ * form (`args`) or as a command string (Codex, Grok).
49
88
  */
50
89
  export const CORE_NEXT_LINK = /[\\/]\.hq[\\/]bin[\\/]hq-hook[\\/]stable[\\/]/;
51
90
  export function isCoreNextEntry(entry, root) {
52
91
  if (typeof entry.command !== 'string' || !CORE_NEXT_LINK.test(entry.command))
53
92
  return false;
54
- const spelling = launcherRoot(root);
55
- if (Array.isArray(entry.args)) {
56
- const i = entry.args.indexOf('--hq-root');
57
- return entry.args[0] === 'run' && entry.args[1] === '--host' && i >= 0 && entry.args[i + 1] === spelling;
58
- }
59
- return entry.command.includes(`${quotePosix('run')} ${quotePosix('--host')}`)
60
- && entry.command.includes(`${quotePosix('--hq-root')} ${quotePosix(spelling)}`);
93
+ const runHost = Array.isArray(entry.args)
94
+ ? entry.args[0] === 'run' && entry.args[1] === '--host'
95
+ : entry.command.includes(`${quotePosix('run')} ${quotePosix('--host')}`);
96
+ return runHost && sameHqRoot(hqRootArgument(entry), root);
61
97
  }
62
98
  export function quotePosix(value) { return "'" + value.replace(/'/g, "'\\''") + "'"; }
63
99
  export function quoteWindows(value) {