@indigoai-us/hq-cli 5.345.215 → 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 (161) hide show
  1. package/CHANGELOG.md +168 -0
  2. package/README.md +46 -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/assets/scaffold/core/scripts/lib/epochrealtime.sh +30 -0
  6. package/assets/scaffold/core/scripts/lib/work-mesh-enqueue.sh +12 -5
  7. package/dist/command-catalog.generated.d.ts +59 -4
  8. package/dist/command-catalog.generated.js +74 -4
  9. package/dist/command-help.js +3 -1
  10. package/dist/command-registration-plan.d.ts +6 -0
  11. package/dist/command-registration-plan.js +1 -0
  12. package/dist/commands/auth.d.ts +1 -1
  13. package/dist/commands/auth.js +11 -52
  14. package/dist/commands/bot.js +11 -4
  15. package/dist/commands/cloud-demote.d.ts +19 -4
  16. package/dist/commands/cloud-demote.js +85 -12
  17. package/dist/commands/cloud-provision.d.ts +5 -1
  18. package/dist/commands/cloud-provision.js +6 -2
  19. package/dist/commands/cloud.d.ts +37 -1
  20. package/dist/commands/cloud.js +110 -27
  21. package/dist/commands/core-hq-session-native.js +3 -0
  22. package/dist/commands/core.js +1 -0
  23. package/dist/commands/daemon.js +4 -1
  24. package/dist/commands/dm.js +7 -0
  25. package/dist/commands/doctor-usage.d.ts +8 -0
  26. package/dist/commands/doctor-usage.js +20 -0
  27. package/dist/commands/doctor.js +7 -1
  28. package/dist/commands/env.d.ts +18 -0
  29. package/dist/commands/env.js +82 -0
  30. package/dist/commands/install-global.js +3 -3
  31. package/dist/commands/lanes.js +100 -24
  32. package/dist/commands/logout.d.ts +7 -0
  33. package/dist/commands/logout.js +41 -34
  34. package/dist/commands/members.js +1 -1
  35. package/dist/commands/pack-start-bot.d.ts +1 -1
  36. package/dist/commands/pack-start-bot.js +2 -2
  37. package/dist/commands/pkg-update.js +1 -1
  38. package/dist/commands/sources.d.ts +8 -2
  39. package/dist/commands/sources.js +65 -9
  40. package/dist/commands/sync-narrow.js +1 -1
  41. package/dist/commands/team-sync.js +1 -1
  42. package/dist/commands/whoami.js +26 -1
  43. package/dist/data/command-states.json +22 -0
  44. package/dist/index.js +52 -4
  45. package/dist/lazy-commands.js +2 -1
  46. package/dist/lib/anywhere-person-setting.d.ts +2 -0
  47. package/dist/lib/anywhere-person-setting.js +6 -3
  48. package/dist/lib/billing/usage-card.d.ts +25 -4
  49. package/dist/lib/billing/usage-card.js +76 -9
  50. package/dist/lib/billing/usage-cost.d.ts +3 -3
  51. package/dist/lib/billing/usage-cost.js +40 -15
  52. package/dist/lib/billing/usage-only.js +4 -2
  53. package/dist/lib/billing/usage-rate-card.d.ts +2 -2
  54. package/dist/lib/billing/usage-rate-card.js +3 -0
  55. package/dist/lib/bot/fleet-cron.js +93 -6
  56. package/dist/lib/bot/inflight.d.ts +9 -0
  57. package/dist/lib/bot/inflight.js +10 -0
  58. package/dist/lib/bot/jobs/hot-signal-sync.js +12 -1
  59. package/dist/lib/bot/pack-link.d.ts +2 -2
  60. package/dist/lib/bot/pack-link.js +2 -2
  61. package/dist/lib/bot/runtime/grok-acp.d.ts +1 -0
  62. package/dist/lib/bot/runtime/grok-acp.js +26 -11
  63. package/dist/lib/bot/runtime/grok.js +1 -1
  64. package/dist/lib/daemon/flag-monitor.d.ts +8 -0
  65. package/dist/lib/daemon/flag-monitor.js +17 -6
  66. package/dist/lib/daemon/flag.d.ts +65 -1
  67. package/dist/lib/daemon/flag.js +190 -40
  68. package/dist/lib/daemon/hook-env.d.ts +32 -0
  69. package/dist/lib/daemon/hook-env.js +51 -0
  70. package/dist/lib/daemon/ops/policy.js +67 -8
  71. package/dist/lib/daemon/paths.d.ts +72 -2
  72. package/dist/lib/daemon/paths.js +154 -3
  73. package/dist/lib/daemon/run.js +32 -21
  74. package/dist/lib/daemon/selfcheck.d.ts +22 -0
  75. package/dist/lib/daemon/selfcheck.js +40 -1
  76. package/dist/lib/daemon/server.d.ts +3 -1
  77. package/dist/lib/daemon/server.js +7 -22
  78. package/dist/lib/daemon/state-file-switch.d.ts +57 -0
  79. package/dist/lib/daemon/state-file-switch.js +88 -0
  80. package/dist/lib/daemon/state-file.d.ts +198 -0
  81. package/dist/lib/daemon/state-file.js +419 -0
  82. package/dist/lib/daemon/timed-flag-monitors.d.ts +47 -0
  83. package/dist/lib/daemon/timed-flag-monitors.js +75 -0
  84. package/dist/lib/doctor/checks/host-core.d.ts +52 -0
  85. package/dist/lib/doctor/checks/host-core.js +337 -0
  86. package/dist/lib/doctor/checks/replay-recorder.d.ts +39 -0
  87. package/dist/lib/doctor/checks/replay-recorder.js +261 -0
  88. package/dist/lib/doctor/checks/sync-runtime.js +3 -3
  89. package/dist/lib/doctor/registry.js +4 -0
  90. package/dist/lib/environment/credential-shapes.d.ts +61 -0
  91. package/dist/lib/environment/credential-shapes.js +333 -0
  92. package/dist/lib/environment/profile.d.ts +239 -0
  93. package/dist/lib/environment/profile.js +239 -0
  94. package/dist/lib/hook-engine/coverage.d.ts +13 -0
  95. package/dist/lib/hook-engine/coverage.js +124 -0
  96. package/dist/lib/hook-engine/reconcile.js +300 -94
  97. package/dist/lib/hook-engine/registration.d.ts +17 -1
  98. package/dist/lib/hook-engine/registration.js +62 -7
  99. package/dist/lib/hot-channels/adapters/slack.d.ts +21 -5
  100. package/dist/lib/hot-channels/adapters/slack.js +64 -21
  101. package/dist/lib/hot-channels/alert.d.ts +2 -0
  102. package/dist/lib/hot-channels/alert.js +8 -1
  103. package/dist/lib/hot-channels/contract.d.ts +12 -0
  104. package/dist/lib/hot-channels/contract.js +7 -0
  105. package/dist/lib/hot-channels/loop.js +1 -0
  106. package/dist/lib/hot-channels/run.d.ts +6 -0
  107. package/dist/lib/hot-channels/run.js +4 -0
  108. package/dist/lib/hot-channels/signals-pass.d.ts +64 -1
  109. package/dist/lib/hot-channels/signals-pass.js +21 -49
  110. package/dist/lib/install/claude-targets.d.ts +12 -1
  111. package/dist/lib/install/claude-targets.js +70 -5
  112. package/dist/lib/install/codex-pack-contributions.js +1 -1
  113. package/dist/lib/install/codex-targets.d.ts +2 -2
  114. package/dist/lib/install/codex-targets.js +48 -5
  115. package/dist/lib/install/hook-target.d.ts +4 -1
  116. package/dist/lib/install/hook-target.js +14 -1
  117. package/dist/lib/lanes/canonical-host.d.ts +35 -0
  118. package/dist/lib/lanes/canonical-host.js +65 -0
  119. package/dist/lib/lanes/host-capacity.d.ts +30 -0
  120. package/dist/lib/lanes/host-capacity.js +29 -3
  121. package/dist/lib/mesh/live/daemon/run.d.ts +2 -0
  122. package/dist/lib/mesh/live/daemon/run.js +5 -2
  123. package/dist/lib/mesh/live/flush.d.ts +5 -1
  124. package/dist/lib/mesh/live/flush.js +12 -6
  125. package/dist/lib/mesh/live/reporting-privacy.d.ts +32 -0
  126. package/dist/lib/mesh/live/reporting-privacy.js +56 -1
  127. package/dist/lib/mesh/live/spool.d.ts +7 -0
  128. package/dist/lib/mesh/live/spool.js +25 -0
  129. package/dist/lib/packages/setup-block.d.ts +2 -2
  130. package/dist/lib/packages/setup-block.js +2 -2
  131. package/dist/lib/packages/start-bot.d.ts +1 -1
  132. package/dist/lib/packages/start-bot.js +1 -1
  133. package/dist/lib/person-setting-cache.d.ts +38 -0
  134. package/dist/lib/person-setting-cache.js +98 -0
  135. package/dist/lib/safe-store.d.ts +245 -0
  136. package/dist/lib/safe-store.js +777 -0
  137. package/dist/lib/signals/engine.d.ts +29 -2
  138. package/dist/lib/signals/engine.js +103 -4
  139. package/dist/lib/signals/reply.js +73 -18
  140. package/dist/lib/signals/steps/adapters.js +7 -2
  141. package/dist/lib/signals/steps/extract.d.ts +13 -0
  142. package/dist/lib/signals/steps/extract.js +84 -4
  143. package/dist/main.js +47 -4
  144. package/dist/schemas/hq-environment-profile.v1.schema.json +438 -0
  145. package/dist/types.d.ts +1 -1
  146. package/dist/utils/auth-expiry.d.ts +8 -0
  147. package/dist/utils/auth-expiry.js +53 -0
  148. package/dist/utils/callback-port-busy.d.ts +1 -1
  149. package/dist/utils/callback-port-busy.js +4 -4
  150. package/dist/utils/cli-telemetry.d.ts +21 -0
  151. package/dist/utils/cli-telemetry.js +34 -0
  152. package/dist/utils/command-usage.d.ts +275 -0
  153. package/dist/utils/command-usage.js +797 -0
  154. package/dist/utils/hook-trust.d.ts +7 -0
  155. package/dist/utils/hook-trust.js +34 -4
  156. package/dist/utils/host-registration.d.ts +179 -0
  157. package/dist/utils/host-registration.js +505 -0
  158. package/dist/utils/resident-package-preload.js +2 -0
  159. package/package.json +10 -8
  160. package/scripts/bench-core.mjs +1096 -0
  161. package/scripts/check-function-manifest.mjs +702 -0
@@ -1,50 +1,162 @@
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';
5
5
  import { addHqHooks, removeHqHooks } from '../install/claude-targets.js';
6
- import { hookTargetFor } from '../install/hook-target.js';
6
+ import { legacyHookTarget } from '../install/hook-target.js';
7
7
  import { addCodexHooks, removeCodexHooks, codexHookEntry, codexHookTrustKeys } from '../install/codex-targets.js';
8
- import { engineArgs, isNativeEntry, registrationEngine } from './registration.js';
8
+ import { engineArgs, isCoreNextEntry, isNativeEntry, registrationEngine } from './registration.js';
9
+ import { coreNextArgs, coreNextTargetOrWarn, placeEvent } from '../../utils/host-registration.js';
10
+ import { forHost } from './coverage.js';
9
11
  /** The project master-hook command shipped in HQ's .claude/settings.json. */
10
12
  function projectClaudeCommand(event) {
11
13
  return 'env BASH_ENV=/dev/null bash "$CLAUDE_PROJECT_DIR/.claude/hooks/master-hook.sh" ' + event;
12
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
+ }
13
52
  /**
14
- * Rewrite matching entries where they sit. Groups, order, foreign entries and
15
- * extra fields such as timeout are kept, so a flag-on then flag-off pass
16
- * 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.
17
60
  */
18
- function rewriteEntries(doc, convert) {
19
- let changed = false;
20
- const hooks = {};
21
- for (const [event, groups] of Object.entries(doc.hooks)) {
22
- hooks[event] = !Array.isArray(groups) ? groups : groups.map((group) => {
23
- if (!Array.isArray(group?.hooks))
24
- return group;
25
- return { ...group, hooks: group.hooks.map((entry) => {
26
- const next = entry && typeof entry === 'object' ? convert(entry, event) : undefined;
27
- if (!next)
28
- return entry;
29
- changed = true;
30
- return next;
31
- }) };
32
- });
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;
33
96
  }
34
- 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;
35
121
  }
36
122
  /** Reconcile existing registrations only; reindex must not install a runtime. */
37
123
  export function reconcileHookRegistrations(root, home = homedir(), env = process.env, daemonInstalled) {
38
124
  const result = { codexUserKeys: [], failures: [] };
39
- const engine = registrationEngine(home, env);
40
- // Flag-off rollback restores the same bash target install would choose (the
41
- // hqd shim when the daemon serves this root). Resolved only when a
42
- // registration is rewritten, so the default-off path reads no daemon state.
43
- let target;
44
- const globalTarget = () => (target ??= engine ? { engine } : hookTargetFor(root, home, daemonInstalled, env));
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.
135
+ const coreNext = coreNextTargetOrWarn(home, env);
136
+ const claudeNext = forHost(coreNext, root, 'claude');
137
+ const codexNext = forHost(coreNext, root, 'codex');
138
+ const launcher = registrationEngine(home, env);
139
+ const native = coreNext ?? (launcher ? { engine: launcher } : null);
140
+ const ours = (entry) => isNativeEntry(entry, root) || isCoreNextEntry(entry, root);
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
+ };
45
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
+ }
46
159
  for (const [file, runtime, global] of [
47
- [join(root, '.claude/settings.json'), 'claude', false],
48
160
  [join(env.CLAUDE_CONFIG_DIR || join(home, '.claude'), 'settings.json'), 'claude', true],
49
161
  [join(env.CODEX_HOME || join(home, '.codex'), 'hooks.json'), 'codex', true],
50
162
  [join(root, '.codex/hooks.json'), 'codex', false],
@@ -54,76 +166,58 @@ export function reconcileHookRegistrations(root, home = homedir(), env = process
54
166
  try {
55
167
  if (!existsSync(file))
56
168
  continue;
57
- // Default-off must not acquire a write lock or create backups for a legacy
58
- // registration. The merge below repeats this check under the lock when a
59
- // native entry was found, so a concurrent writer still wins safely.
60
- if (!engine) {
61
- let current;
62
- // A file we cannot parse holds no native entry of ours; leave it untouched.
63
- try {
64
- current = jsonFormat.parse(readFileSync(file, 'utf8'));
65
- }
66
- catch {
67
- 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'));
68
178
  }
69
- const entries = current?.hooks && typeof current.hooks === 'object'
70
- ? Object.values(current.hooks).flatMap(groups => Array.isArray(groups) ? groups.flatMap(g => Array.isArray(g?.hooks) ? g.hooks : []) : [])
71
- : [];
72
- if (!entries.some(e => e && isNativeEntry(e, root)))
73
- continue;
74
- }
75
- let expected;
76
- let codexKeys;
77
- writeConfigAtomic({ target: file, pack: 'hq-hook-engine', format: {
78
- ...jsonFormat,
79
- assertEntry: (doc) => {
80
- if (expected !== undefined && JSON.stringify(doc) !== expected)
81
- 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 } : {}) };
82
200
  },
83
- }, env: { home }, assertName: 'hooks', merge: (doc) => {
84
- if (!doc || typeof doc !== 'object' || !doc.hooks || typeof doc.hooks !== 'object')
85
- return doc;
86
- const entries = Object.values(doc.hooks).flatMap(groups => Array.isArray(groups) ? groups.flatMap(g => Array.isArray(g?.hooks) ? g.hooks : []) : []);
87
- if (!engine && !entries.some(e => e && isNativeEntry(e, root)))
88
- return doc;
89
- if (global && (runtime === 'codex' ? removeCodexHooks(doc, root) : removeHqHooks(doc, root)) === doc)
90
- return doc;
91
- let next;
92
- if (global)
93
- next = runtime === 'codex' ? addCodexHooks(doc, root, globalTarget()) : addHqHooks(doc, root, globalTarget());
94
- else if (runtime === 'codex') {
95
- // Only an entry install itself writes is converted. HQ's own project
96
- // file routes through hook-gate.sh and has none, so it stays as is.
97
- next = rewriteEntries(doc, (entry, event) => {
98
- if (!isNativeEntry(entry, root) && !codexBash(event).includes(entry.command))
99
- return undefined;
100
- const { command: _command, commandWindows: _windows, ...rest } = entry;
101
- const { command, commandWindows } = codexHookEntry(root, event, globalTarget());
102
- return { ...rest, command, ...(commandWindows ? { commandWindows } : {}) };
103
- });
104
- }
105
- else {
106
- // Only the exact shipped master-hook command is converted; a wrapped
107
- // or extended invocation is someone's edit and is left alone.
108
- next = rewriteEntries(doc, (entry, event) => {
109
- if (!isNativeEntry(entry, root) && entry.command !== projectClaudeCommand(event))
110
- return undefined;
111
- const { args, commandWindows: _windows, ...rest } = entry;
112
- if (engine)
113
- return { ...rest, command: engine, args: engineArgs(root, event, 'claude') };
114
- return { ...rest, command: projectClaudeCommand(Array.isArray(args) && typeof args[0] === 'string' ? args[0] : event) };
115
- });
116
- }
117
- expected = JSON.stringify(next);
118
- if (runtime === 'codex' && global)
119
- codexKeys = codexHookTrustKeys(next, file, root);
120
- return next;
121
- } });
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);
122
216
  // Keys are positions in the file. Only once the write and its verify have
123
217
  // succeeded do they point at HQ's entries; a failed write leaves the old
124
218
  // file, where the same position can hold a foreign hook.
125
- if (codexKeys)
126
- result.codexUserKeys = codexKeys;
219
+ if (runtime === 'codex' && global)
220
+ result.codexUserKeys = codexHookTrustKeys(next, file, root);
127
221
  }
128
222
  catch (error) {
129
223
  result.failures.push(`${file}: ${error.message}`);
@@ -131,4 +225,116 @@ export function reconcileHookRegistrations(root, home = homedir(), env = process
131
225
  }
132
226
  return result;
133
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
+ }
134
340
  //# sourceMappingURL=reconcile.js.map
@@ -10,8 +10,24 @@ 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;
22
+ /**
23
+ * A registration that calls the new core's entry point, `hq-hook run --host
24
+ * <host> <Event> --hq-root <root>`, through the release-stable link
25
+ * (hq-core-rust US-017). Recognized by the stable path, the `run --host`
26
+ * words and a root argument that names this root ([`sameHqRoot`]), in exec
27
+ * form (`args`) or as a command string (Codex, Grok).
28
+ */
29
+ export declare const CORE_NEXT_LINK: RegExp;
30
+ export declare function isCoreNextEntry(entry: Record<string, unknown>, root: string): boolean;
15
31
  export declare function quotePosix(value: string): string;
16
32
  export declare function quoteWindows(value: string): string;
17
33
  //# sourceMappingURL=registration.d.ts.map
@@ -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,19 +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);
81
+ }
82
+ /**
83
+ * A registration that calls the new core's entry point, `hq-hook run --host
84
+ * <host> <Event> --hq-root <root>`, through the release-stable link
85
+ * (hq-core-rust US-017). Recognized by the stable path, the `run --host`
86
+ * words and a root argument that names this root ([`sameHqRoot`]), in exec
87
+ * form (`args`) or as a command string (Codex, Grok).
88
+ */
89
+ export const CORE_NEXT_LINK = /[\\/]\.hq[\\/]bin[\\/]hq-hook[\\/]stable[\\/]/;
90
+ export function isCoreNextEntry(entry, root) {
91
+ if (typeof entry.command !== 'string' || !CORE_NEXT_LINK.test(entry.command))
92
+ return false;
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);
42
97
  }
43
98
  export function quotePosix(value) { return "'" + value.replace(/'/g, "'\\''") + "'"; }
44
99
  export function quoteWindows(value) {
@@ -27,11 +27,18 @@
27
27
  * `slack_participants`.
28
28
  *
29
29
  * Slack pauses event delivery to an app that exceeds its rate limit and sends
30
- * `app_rate_limited`. A marker newer than the cursor (`_app_rate_limited.json`
31
- * or a document with `type: app_rate_limited` in `sources/slack/`, without a
32
- * `resolved_at`) fails the adapter with `SlackAppRateLimitedError`, whose
33
- * message lands in the run ledger's `error`. The cursor does not move.
34
- * Writing that marker from the webhook is an hq-pro-agents follow-up.
30
+ * `app_rate_limited`. hq-pro-agents' Slack receiver writes that as
31
+ * `_app_rate_limited.json` in `sources/slack/`: `at` is the first pause of an
32
+ * unresolved run, `last_at` the newest, and `resolved_at` is set once a later
33
+ * event for the same team arrives. A landed document with
34
+ * `type: app_rate_limited` counts the same way. A marker fails the adapter
35
+ * with `SlackAppRateLimitedError`, whose message lands in the run ledger's
36
+ * `error`, while all of these hold: it has no `resolved_at`, its newest pause
37
+ * (newest readable of `last_at`, `at`, `ingested_at`) is under an hour old,
38
+ * and that newest pause is after the cursor. The cursor does not move. A
39
+ * marker time more than five minutes ahead of now is ignored on its own. The
40
+ * hour limit exists because a quiet company may never send the later event
41
+ * that sets `resolved_at`.
35
42
  */
36
43
  import { type PollHotChannelAdapter } from "../contract.js";
37
44
  export declare const SLACK_ADAPTER_ID = "slack";
@@ -66,5 +73,14 @@ export interface SlackAdapterOptions {
66
73
  /** Threads newer than the cursor per page. Default 100. */
67
74
  pageSize?: number;
68
75
  }
76
+ /**
77
+ * An open marker whose newest pause is older than this is treated as resolved.
78
+ * While Slack keeps an app paused it sends `app_rate_limited` about once a
79
+ * minute and the receiver moves `last_at` forward, so an ongoing pause stays
80
+ * well inside this window. The receiver only sets `resolved_at` when a later
81
+ * event for the team arrives, so a quiet company would otherwise keep an open
82
+ * marker, and a failing Slack sync, forever.
83
+ */
84
+ export declare const SLACK_RATE_LIMIT_MARKER_MAX_AGE_MS: number;
69
85
  export declare function createSlackAdapter(options: SlackAdapterOptions): PollHotChannelAdapter;
70
86
  //# sourceMappingURL=slack.d.ts.map