@indigoai-us/hq-cli 5.345.217 → 5.345.219

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