@indigoai-us/hq-cli 5.345.215-beta.0 → 5.345.217

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 (241) hide show
  1. package/CHANGELOG.md +206 -1
  2. package/README.md +45 -0
  3. package/assets/scaffold/core/scripts/hq-delegate-verify.sh +5 -2
  4. package/assets/scaffold/core/scripts/lib/epochrealtime.sh +30 -0
  5. package/assets/scaffold/core/scripts/lib/work-mesh-enqueue.sh +12 -5
  6. package/dist/command-catalog.generated.d.ts +105 -10
  7. package/dist/command-catalog.generated.js +127 -10
  8. package/dist/command-help.js +3 -1
  9. package/dist/command-registration-plan.d.ts +6 -0
  10. package/dist/command-registration-plan.js +1 -0
  11. package/dist/commands/auth.d.ts +1 -1
  12. package/dist/commands/auth.js +11 -52
  13. package/dist/commands/bot.js +75 -10
  14. package/dist/commands/capacity.d.ts +4 -1
  15. package/dist/commands/capacity.js +46 -10
  16. package/dist/commands/cloud-demote.d.ts +19 -4
  17. package/dist/commands/cloud-demote.js +85 -12
  18. package/dist/commands/cloud-provision.d.ts +5 -1
  19. package/dist/commands/cloud-provision.js +6 -2
  20. package/dist/commands/cloud.d.ts +36 -0
  21. package/dist/commands/cloud.js +110 -27
  22. package/dist/commands/core-delegate-w1b.js +15 -1
  23. package/dist/commands/core-policy.js +67 -8
  24. package/dist/commands/core.js +1 -0
  25. package/dist/commands/daemon.js +9 -1
  26. package/dist/commands/dm.js +7 -0
  27. package/dist/commands/doctor-usage.d.ts +8 -0
  28. package/dist/commands/doctor-usage.js +20 -0
  29. package/dist/commands/doctor.js +7 -1
  30. package/dist/commands/env.d.ts +18 -0
  31. package/dist/commands/env.js +82 -0
  32. package/dist/commands/files-browse.d.ts +11 -4
  33. package/dist/commands/files-browse.js +21 -4
  34. package/dist/commands/files.d.ts +1 -1
  35. package/dist/commands/files.js +25 -11
  36. package/dist/commands/install-global.js +2 -2
  37. package/dist/commands/integrations-auth-rules.d.ts +27 -0
  38. package/dist/commands/integrations-auth-rules.js +79 -0
  39. package/dist/commands/integrations-import.js +124 -12
  40. package/dist/commands/lanes.js +102 -26
  41. package/dist/commands/logout.d.ts +7 -0
  42. package/dist/commands/logout.js +41 -34
  43. package/dist/commands/mesh.d.ts +2 -0
  44. package/dist/commands/mesh.js +60 -35
  45. package/dist/commands/sources.d.ts +8 -2
  46. package/dist/commands/sources.js +65 -9
  47. package/dist/commands/sync-held.js +5 -2
  48. package/dist/commands/whoami.js +26 -1
  49. package/dist/data/command-states.json +15 -0
  50. package/dist/index.js +52 -4
  51. package/dist/lazy-commands.js +5 -6
  52. package/dist/lib/anywhere-person-setting.d.ts +2 -0
  53. package/dist/lib/anywhere-person-setting.js +6 -3
  54. package/dist/lib/billing/usage-card.d.ts +25 -4
  55. package/dist/lib/billing/usage-card.js +76 -9
  56. package/dist/lib/billing/usage-cost.d.ts +3 -3
  57. package/dist/lib/billing/usage-cost.js +35 -13
  58. package/dist/lib/billing/usage-only.js +4 -2
  59. package/dist/lib/billing/usage-rate-card.d.ts +2 -2
  60. package/dist/lib/billing/usage-rate-card.js +3 -0
  61. package/dist/lib/bot/fleet-cron.d.ts +8 -0
  62. package/dist/lib/bot/fleet-cron.js +126 -7
  63. package/dist/lib/bot/fleet-daemon.d.ts +46 -0
  64. package/dist/lib/bot/fleet-daemon.js +99 -1
  65. package/dist/lib/bot/inflight.d.ts +9 -0
  66. package/dist/lib/bot/inflight.js +10 -0
  67. package/dist/lib/bot/jobs/hot-signal-sync.js +12 -1
  68. package/dist/lib/bot/probe.js +7 -1
  69. package/dist/lib/bot/run.js +20 -1
  70. package/dist/lib/bot/runtime/codex.js +1 -1
  71. package/dist/lib/bot/runtime/grok-acp.d.ts +6 -1
  72. package/dist/lib/bot/runtime/grok-acp.js +32 -14
  73. package/dist/lib/bot/runtime/grok.js +1 -1
  74. package/dist/lib/bot/runtime/index.js +19 -9
  75. package/dist/lib/bot/runtime/messages-stream.js +2 -2
  76. package/dist/lib/bot/runtime/types.d.ts +15 -0
  77. package/dist/lib/bot/runtime/types.js +9 -0
  78. package/dist/lib/bot/runtime-failure.d.ts +23 -0
  79. package/dist/lib/bot/runtime-failure.js +43 -1
  80. package/dist/lib/capacity/accounts.d.ts +8 -0
  81. package/dist/lib/capacity/accounts.js +19 -0
  82. package/dist/lib/capacity/available.d.ts +154 -0
  83. package/dist/lib/capacity/available.js +905 -0
  84. package/dist/lib/capacity/codex-availability.d.ts +14 -1
  85. package/dist/lib/capacity/codex-availability.js +26 -1
  86. package/dist/lib/capacity/collectors/claude-oauth.d.ts +29 -2
  87. package/dist/lib/capacity/collectors/claude-oauth.js +104 -7
  88. package/dist/lib/capacity/collectors/codex.js +10 -7
  89. package/dist/lib/capacity/ledger.d.ts +37 -1
  90. package/dist/lib/capacity/ledger.js +207 -30
  91. package/dist/lib/capacity/project.d.ts +26 -0
  92. package/dist/lib/capacity/project.js +137 -8
  93. package/dist/lib/capacity/refusal-rows.d.ts +31 -0
  94. package/dist/lib/capacity/refusal-rows.js +61 -0
  95. package/dist/lib/capacity/refusal.d.ts +53 -2
  96. package/dist/lib/capacity/refusal.js +284 -65
  97. package/dist/lib/capacity/route.js +46 -11
  98. package/dist/lib/capacity/widget.d.ts +12 -1
  99. package/dist/lib/capacity/widget.js +91 -3
  100. package/dist/lib/daemon/flag-monitor.d.ts +8 -0
  101. package/dist/lib/daemon/flag-monitor.js +17 -6
  102. package/dist/lib/daemon/flag.d.ts +65 -1
  103. package/dist/lib/daemon/flag.js +190 -40
  104. package/dist/lib/daemon/ops/policy.js +62 -5
  105. package/dist/lib/daemon/paths.d.ts +72 -2
  106. package/dist/lib/daemon/paths.js +154 -3
  107. package/dist/lib/daemon/resolver.d.ts +2 -0
  108. package/dist/lib/daemon/resolver.js +3 -0
  109. package/dist/lib/daemon/run.d.ts +9 -0
  110. package/dist/lib/daemon/run.js +79 -21
  111. package/dist/lib/daemon/selfcheck.d.ts +22 -0
  112. package/dist/lib/daemon/selfcheck.js +40 -1
  113. package/dist/lib/daemon/server.d.ts +5 -1
  114. package/dist/lib/daemon/server.js +17 -23
  115. package/dist/lib/daemon/state-file-switch.d.ts +57 -0
  116. package/dist/lib/daemon/state-file-switch.js +88 -0
  117. package/dist/lib/daemon/state-file.d.ts +198 -0
  118. package/dist/lib/daemon/state-file.js +419 -0
  119. package/dist/lib/daemon/tcc-eperm.d.ts +153 -0
  120. package/dist/lib/daemon/tcc-eperm.js +310 -0
  121. package/dist/lib/daemon/timed-flag-monitors.d.ts +47 -0
  122. package/dist/lib/daemon/timed-flag-monitors.js +75 -0
  123. package/dist/lib/delivery/admission.d.ts +86 -0
  124. package/dist/lib/delivery/admission.js +148 -0
  125. package/dist/lib/delivery/artifacts.d.ts +7 -1
  126. package/dist/lib/delivery/artifacts.js +29 -10
  127. package/dist/lib/delivery/attempt-id.d.ts +13 -0
  128. package/dist/lib/delivery/attempt-id.js +16 -0
  129. package/dist/lib/delivery/disposable-target.d.ts +42 -0
  130. package/dist/lib/delivery/disposable-target.js +111 -0
  131. package/dist/lib/delivery/effects.d.ts +136 -0
  132. package/dist/lib/delivery/effects.js +541 -0
  133. package/dist/lib/delivery/enrollment.d.ts +21 -17
  134. package/dist/lib/delivery/enrollment.js +83 -5
  135. package/dist/lib/delivery/escalations.d.ts +51 -0
  136. package/dist/lib/delivery/escalations.js +60 -0
  137. package/dist/lib/delivery/lease.d.ts +80 -0
  138. package/dist/lib/delivery/lease.js +134 -0
  139. package/dist/lib/delivery/migrations.d.ts +120 -4
  140. package/dist/lib/delivery/migrations.js +215 -15
  141. package/dist/lib/delivery/mqtt.d.ts +2 -0
  142. package/dist/lib/delivery/mqtt.js +7 -0
  143. package/dist/lib/delivery/reconciler.d.ts +65 -1
  144. package/dist/lib/delivery/reconciler.js +224 -13
  145. package/dist/lib/delivery/rpc/client.d.ts +22 -0
  146. package/dist/lib/delivery/rpc/client.js +159 -0
  147. package/dist/lib/delivery/rpc/port.d.ts +40 -0
  148. package/dist/lib/delivery/rpc/port.js +16 -0
  149. package/dist/lib/delivery/rpc/server.d.ts +30 -0
  150. package/dist/lib/delivery/rpc/server.js +205 -0
  151. package/dist/lib/delivery/rpc/wire.d.ts +85 -0
  152. package/dist/lib/delivery/rpc/wire.js +143 -0
  153. package/dist/lib/delivery/store.d.ts +2 -0
  154. package/dist/lib/delivery/store.js +4 -0
  155. package/dist/lib/delivery/windows-service-install.d.ts +262 -0
  156. package/dist/lib/delivery/windows-service-install.js +892 -0
  157. package/dist/lib/delivery/workers/macos.d.ts +16 -1
  158. package/dist/lib/delivery/workers/macos.js +54 -12
  159. package/dist/lib/delivery/workers/windows-service-live.d.ts +121 -0
  160. package/dist/lib/delivery/workers/windows-service-live.js +711 -0
  161. package/dist/lib/delivery/workers/windows-service-runner.d.ts +33 -0
  162. package/dist/lib/delivery/workers/windows-service-runner.js +82 -0
  163. package/dist/lib/delivery/workers/windows-service.d.ts +140 -0
  164. package/dist/lib/delivery/workers/windows-service.js +584 -0
  165. package/dist/lib/delivery/workers/windows.d.ts +32 -22
  166. package/dist/lib/delivery/workers/windows.js +50 -64
  167. package/dist/lib/doctor/checks/host-core.d.ts +50 -0
  168. package/dist/lib/doctor/checks/host-core.js +269 -0
  169. package/dist/lib/doctor/checks/replay-recorder.d.ts +39 -0
  170. package/dist/lib/doctor/checks/replay-recorder.js +261 -0
  171. package/dist/lib/doctor/registry.js +4 -0
  172. package/dist/lib/environment/profile.d.ts +239 -0
  173. package/dist/lib/environment/profile.js +251 -0
  174. package/dist/lib/hook-engine/reconcile.js +39 -13
  175. package/dist/lib/hook-engine/registration.d.ts +9 -0
  176. package/dist/lib/hook-engine/registration.js +19 -0
  177. package/dist/lib/hot-channels/adapters/meetings.d.ts +15 -0
  178. package/dist/lib/hot-channels/adapters/meetings.js +36 -3
  179. package/dist/lib/hot-channels/adapters/slack.d.ts +21 -5
  180. package/dist/lib/hot-channels/adapters/slack.js +64 -21
  181. package/dist/lib/hot-channels/alert.d.ts +2 -0
  182. package/dist/lib/hot-channels/alert.js +8 -1
  183. package/dist/lib/hot-channels/contract.d.ts +12 -0
  184. package/dist/lib/hot-channels/contract.js +7 -0
  185. package/dist/lib/hot-channels/loop.js +1 -0
  186. package/dist/lib/hot-channels/run.d.ts +6 -0
  187. package/dist/lib/hot-channels/run.js +4 -0
  188. package/dist/lib/hot-channels/signals-pass.d.ts +74 -1
  189. package/dist/lib/hot-channels/signals-pass.js +82 -41
  190. package/dist/lib/hot-channels/signals-redo.js +10 -2
  191. package/dist/lib/install/claude-targets.d.ts +12 -1
  192. package/dist/lib/install/claude-targets.js +57 -5
  193. package/dist/lib/install/codex-targets.d.ts +2 -2
  194. package/dist/lib/install/codex-targets.js +36 -6
  195. package/dist/lib/install/hook-target.d.ts +3 -0
  196. package/dist/lib/install/hook-target.js +11 -0
  197. package/dist/lib/lanes/canonical-host.d.ts +35 -0
  198. package/dist/lib/lanes/canonical-host.js +65 -0
  199. package/dist/lib/lanes/host-capacity.d.ts +30 -0
  200. package/dist/lib/lanes/host-capacity.js +29 -3
  201. package/dist/lib/lanes/watcher.js +35 -0
  202. package/dist/lib/mesh/live/daemon/run.d.ts +2 -0
  203. package/dist/lib/mesh/live/daemon/run.js +5 -2
  204. package/dist/lib/mesh/live/flush.d.ts +5 -1
  205. package/dist/lib/mesh/live/flush.js +12 -6
  206. package/dist/lib/mesh/live/reporting-privacy.d.ts +32 -0
  207. package/dist/lib/mesh/live/reporting-privacy.js +56 -1
  208. package/dist/lib/mesh/live/spool.d.ts +7 -0
  209. package/dist/lib/mesh/live/spool.js +25 -0
  210. package/dist/lib/person-setting-cache.d.ts +38 -0
  211. package/dist/lib/person-setting-cache.js +98 -0
  212. package/dist/lib/safe-store.d.ts +245 -0
  213. package/dist/lib/safe-store.js +777 -0
  214. package/dist/lib/signals/engine.d.ts +29 -2
  215. package/dist/lib/signals/engine.js +103 -4
  216. package/dist/lib/signals/reply.js +73 -18
  217. package/dist/lib/signals/steps/adapters.js +7 -2
  218. package/dist/lib/signals/steps/extract.d.ts +13 -0
  219. package/dist/lib/signals/steps/extract.js +122 -6
  220. package/dist/main.js +46 -3
  221. package/dist/schemas/hq-available-ai.v1.schema.json +76 -0
  222. package/dist/schemas/hq-environment-profile.v1.schema.json +438 -0
  223. package/dist/utils/auth-expiry.d.ts +8 -0
  224. package/dist/utils/auth-expiry.js +53 -0
  225. package/dist/utils/catalog-runtime-paths.d.ts +34 -0
  226. package/dist/utils/catalog-runtime-paths.js +53 -0
  227. package/dist/utils/cli-telemetry.d.ts +21 -0
  228. package/dist/utils/cli-telemetry.js +34 -0
  229. package/dist/utils/command-usage.d.ts +275 -0
  230. package/dist/utils/command-usage.js +797 -0
  231. package/dist/utils/files-browse-acl.js +1 -1
  232. package/dist/utils/hook-trust.d.ts +7 -0
  233. package/dist/utils/hook-trust.js +31 -4
  234. package/dist/utils/host-registration.d.ts +126 -0
  235. package/dist/utils/host-registration.js +378 -0
  236. package/dist/utils/resident-package-preload.js +2 -0
  237. package/package.json +10 -8
  238. package/scripts/bench-core.mjs +1096 -0
  239. package/scripts/check-function-manifest.mjs +702 -0
  240. package/dist/lib/delivery/workers/windows-boundary.d.ts +0 -453
  241. package/dist/lib/delivery/workers/windows-boundary.js +0 -693
@@ -5,7 +5,8 @@
5
5
  * safe-write substrate.
6
6
  */
7
7
  import * as path from 'path';
8
- import { engineArgs, isNativeEntry } from '../hook-engine/registration.js';
8
+ import { engineArgs, isCoreNextEntry, isNativeEntry } from '../hook-engine/registration.js';
9
+ import { coreNextArgs, targetForEvent } from '../../utils/host-registration.js';
9
10
  /** Events master-hook.sh is registered for at user scope. */
10
11
  const GLOBAL_HOOK_EVENTS = [
11
12
  'SessionStart',
@@ -99,13 +100,49 @@ export function removeClaudeMdBlock(current) {
99
100
  function isHqHookEntry(entry, hqRoot) {
100
101
  if (!entry || typeof entry !== 'object')
101
102
  return false;
102
- if (isNativeEntry(entry, hqRoot))
103
+ if (isNativeEntry(entry, hqRoot) || isCoreNextEntry(entry, hqRoot))
103
104
  return true;
104
105
  const cmd = entry.command;
105
106
  if (typeof cmd !== 'string')
106
107
  return false;
107
108
  return [masterHookPath(hqRoot), shimPath(hqRoot)].some((target) => cmd.includes(target) || cmd.includes(JSON.stringify(target)) || cmd.includes(shellQuote(target)));
108
109
  }
110
+ function isCoreNext(target) {
111
+ return typeof target === 'object' && 'coreNext' in target;
112
+ }
113
+ /**
114
+ * `groups` with `want` in the place of the first entry `ours` matches, every
115
+ * other matching entry removed (a group it leaves empty is dropped), and
116
+ * everything else where it was. Null when no entry matches.
117
+ */
118
+ export function replaceInPlace(groups, want, ours) {
119
+ let placed = false;
120
+ const out = [];
121
+ for (const group of groups) {
122
+ if (!group || !Array.isArray(group.hooks)) {
123
+ out.push(group);
124
+ continue;
125
+ }
126
+ let touched = false;
127
+ const hooks = [];
128
+ for (const entry of group.hooks) {
129
+ if (!ours(entry)) {
130
+ hooks.push(entry);
131
+ continue;
132
+ }
133
+ touched = true;
134
+ if (!placed) {
135
+ hooks.push(want);
136
+ placed = true;
137
+ }
138
+ }
139
+ if (!touched)
140
+ out.push(group);
141
+ else if (hooks.length > 0)
142
+ out.push({ ...group, hooks });
143
+ }
144
+ return placed ? out : null;
145
+ }
109
146
  /**
110
147
  * Add one HQ hook group per event; idempotent. An HQ entry for the other
111
148
  * target (master-hook.sh vs the hqd shim) is swapped out. Foreign hooks are untouched.
@@ -114,13 +151,28 @@ export function addHqHooks(doc, hqRoot, target = 'master') {
114
151
  const hooks = { ...(doc.hooks ?? {}) };
115
152
  let changed = false;
116
153
  for (const event of GLOBAL_HOOK_EVENTS) {
117
- const want = typeof target === 'object'
118
- ? { type: 'command', command: target.engine, args: engineArgs(hqRoot, event, 'claude', true), timeout: 300 }
119
- : { type: 'command', command: hookCommand(hqRoot, event, target), timeout: 300 };
154
+ // With the new core (US-017), an event it cannot take yet keeps the
155
+ // flag-off target.
156
+ const t = targetForEvent(target, event);
157
+ const want = typeof t !== 'object'
158
+ ? { type: 'command', command: hookCommand(hqRoot, event, t), timeout: 300 }
159
+ : 'coreNext' in t
160
+ ? { type: 'command', command: t.coreNext, args: coreNextArgs('claude', event, hqRoot, 'global'), timeout: 300 }
161
+ : { type: 'command', command: t.engine, args: engineArgs(hqRoot, event, 'claude', true), timeout: 300 };
120
162
  let groups = Array.isArray(hooks[event]) ? [...hooks[event]] : [];
121
163
  const present = groups.some((g) => Array.isArray(g?.hooks) && g.hooks.some((h) => h.command === want.command && JSON.stringify(h.args) === JSON.stringify('args' in want ? want.args : undefined)));
122
164
  if (present)
123
165
  continue;
166
+ // To or from the new core, the HQ entry keeps its place among the user's
167
+ // own entries, so their positions (and Codex's position-keyed trust) do
168
+ // not move. Other target swaps keep today's behaviour.
169
+ const inPlace = isCoreNext(target) || groups.some((g) => Array.isArray(g?.hooks) && g.hooks.some((h) => isCoreNextEntry(h, hqRoot)));
170
+ const replaced = inPlace ? replaceInPlace(groups, want, (h) => isHqHookEntry(h, hqRoot)) : null;
171
+ if (replaced) {
172
+ hooks[event] = replaced;
173
+ changed = true;
174
+ continue;
175
+ }
124
176
  groups = removeHqHooks({ hooks: { [event]: groups } }, hqRoot).hooks?.[event] ?? [];
125
177
  groups.push({ hooks: [want] });
126
178
  hooks[event] = groups;
@@ -73,9 +73,9 @@ export declare function codexUserHookClaimed(hqRoot: string, target: HookTarget,
73
73
  * The user-scope hooks.json entry: {@link codexHookEntry} behind
74
74
  * {@link codexUserHookClaimed}. `commandWindows` is unchanged.
75
75
  */
76
- export declare function codexUserHookEntry(hqRoot: string, event: string, target?: HookTarget): Record<string, unknown>;
76
+ export declare function codexUserHookEntry(hqRoot: string, event: string, eventTarget?: HookTarget): Record<string, unknown>;
77
77
  /** The HQ hooks.json entry for one event and target. */
78
- export declare function codexHookEntry(hqRoot: string, event: string, target?: HookTarget): Record<string, unknown>;
78
+ export declare function codexHookEntry(hqRoot: string, event: string, eventTarget?: HookTarget): Record<string, unknown>;
79
79
  /**
80
80
  * Add one HQ hook group per event; idempotent. An HQ entry for the other
81
81
  * target (adapter vs the hqd shim) is swapped out, and so is an HQ entry
@@ -10,9 +10,10 @@
10
10
  * module never writes a second adapter.
11
11
  */
12
12
  import * as fs from 'fs';
13
- import { engineArgs, isNativeEntry, quotePosix, quoteWindows } from '../hook-engine/registration.js';
13
+ import { engineArgs, isCoreNextEntry, isNativeEntry, quotePosix, quoteWindows } from '../hook-engine/registration.js';
14
14
  import * as path from 'path';
15
- import { shimPath } from './claude-targets.js';
15
+ import { replaceInPlace, shimPath } from './claude-targets.js';
16
+ import { coreNextCommand, coreNextCommandWindows, targetForEvent } from '../../utils/host-registration.js';
16
17
  /** Events the Codex hook adapter is registered for at user scope. */
17
18
  const CODEX_HOOK_EVENTS = [
18
19
  'SessionStart',
@@ -92,7 +93,7 @@ export function removeAgentsMdBlock(current) {
92
93
  export function isAdapterEntry(entry, hqRoot) {
93
94
  if (!entry || typeof entry !== 'object')
94
95
  return false;
95
- if (isNativeEntry(entry, hqRoot))
96
+ if (isNativeEntry(entry, hqRoot) || isCoreNextEntry(entry, hqRoot))
96
97
  return true;
97
98
  const cmd = entry.command;
98
99
  return (typeof cmd === 'string' &&
@@ -118,7 +119,7 @@ function codexHookTargetPath(hqRoot, target) {
118
119
  if (target === 'shim')
119
120
  return shimPath(hqRoot);
120
121
  if (typeof target === 'object')
121
- return target.engine;
122
+ return 'coreNext' in target ? target.coreNext : target.engine;
122
123
  return codexAdapterPath(hqRoot);
123
124
  }
124
125
  /**
@@ -170,15 +171,33 @@ export function codexUserHookClaimed(hqRoot, target, command) {
170
171
  * The user-scope hooks.json entry: {@link codexHookEntry} behind
171
172
  * {@link codexUserHookClaimed}. `commandWindows` is unchanged.
172
173
  */
173
- export function codexUserHookEntry(hqRoot, event, target = 'master') {
174
+ export function codexUserHookEntry(hqRoot, event, eventTarget = 'master') {
175
+ const target = targetForEvent(eventTarget, event);
174
176
  const entry = codexHookEntry(hqRoot, event, target);
177
+ // The new core (hq-core-rust US-017) is called directly, with no shell
178
+ // wrapper and no scope option: like the claimed entry above, it answers
179
+ // inside an HQ tree too, because Codex may not load or trust the root's own
180
+ // project hooks. Where both run, each answers, as both do today.
181
+ if (typeof target === 'object' && 'coreNext' in target)
182
+ return entry;
175
183
  return { ...entry, command: codexUserHookClaimed(hqRoot, target, entry.command) };
176
184
  }
177
185
  /** The HQ hooks.json entry for one event and target. */
178
- export function codexHookEntry(hqRoot, event, target = 'master') {
186
+ export function codexHookEntry(hqRoot, event, eventTarget = 'master') {
179
187
  const timeout = event === 'SessionEnd' ? 3 : 300;
188
+ // With the new core (US-017), an event it cannot take yet keeps the flag-off target.
189
+ const target = targetForEvent(eventTarget, event);
180
190
  if (typeof target !== 'object')
181
191
  return { type: 'command', command: codexHookCommand(hqRoot, target), timeout };
192
+ if ('coreNext' in target) {
193
+ const scope = 'project';
194
+ return {
195
+ type: 'command',
196
+ command: coreNextCommand(target.coreNext, 'codex', event, hqRoot, scope),
197
+ ...(target.coreNext.endsWith('.exe') ? { commandWindows: coreNextCommandWindows(target.coreNext, 'codex', event, hqRoot, scope) } : {}),
198
+ timeout,
199
+ };
200
+ }
182
201
  const argv = [target.engine, ...engineArgs(hqRoot, event, 'codex')];
183
202
  return { type: 'command', command: argv.map(quotePosix).join(' '), ...(target.engine.endsWith('.exe') ? { commandWindows: '& ' + argv.map(quoteWindows).join(' ') } : {}), timeout };
184
203
  }
@@ -196,6 +215,17 @@ export function addCodexHooks(doc, hqRoot, target = 'master') {
196
215
  const present = groups.some((g) => Array.isArray(g?.hooks) && g.hooks.some((h) => h.command === want.command && h.commandWindows === ('commandWindows' in want ? want.commandWindows : undefined)));
197
216
  if (present)
198
217
  continue;
218
+ // To or from the new core, the HQ entry keeps its place: Codex keys a
219
+ // user's trust of each hook by its position, so moving HQ's entry behind
220
+ // the user's own would drop the user's trust. Other target swaps keep
221
+ // today's behaviour.
222
+ const inPlace = (typeof target === 'object' && 'coreNext' in target) || groups.some((g) => Array.isArray(g?.hooks) && g.hooks.some((h) => isCoreNextEntry(h, hqRoot)));
223
+ const replaced = inPlace ? replaceInPlace(groups, want, (h) => isAdapterEntry(h, hqRoot)) : null;
224
+ if (replaced) {
225
+ hooks[event] = replaced;
226
+ changed = true;
227
+ continue;
228
+ }
199
229
  groups = removeCodexHooks({ hooks: { [event]: groups } }, hqRoot).hooks?.[event] ?? [];
200
230
  groups.push({ hooks: [want] });
201
231
  hooks[event] = groups;
@@ -1,3 +1,4 @@
1
+ import { type FallbackTarget } from '../../utils/host-registration.js';
1
2
  import { type HookTarget } from './claude-targets.js';
2
3
  /**
3
4
  * True when this user's hq daemon unit (launchd plist, systemd unit, or the
@@ -10,4 +11,6 @@ export declare function isDaemonInstalled(home: string, platform?: NodeJS.Platfo
10
11
  * the hqd shim; otherwise to master-hook.sh / the Codex adapter.
11
12
  */
12
13
  export declare function hookTargetFor(hqRoot: string, home: string, daemonInstalled?: boolean, env?: NodeJS.ProcessEnv): HookTarget;
14
+ /** The target with `core.next` off: the pinned launcher, the hqd shim, or master-hook.sh. */
15
+ export declare function legacyHookTarget(hqRoot: string, home: string, daemonInstalled?: boolean, env?: NodeJS.ProcessEnv): FallbackTarget;
13
16
  //# sourceMappingURL=hook-target.d.ts.map
@@ -12,6 +12,7 @@ import { defaultRunCommand } from '../service-manager/launchd.js';
12
12
  import { readDaemonConfig } from '../daemon/config.js';
13
13
  import { daemonPaths } from '../daemon/paths.js';
14
14
  import { registrationEngine } from '../hook-engine/registration.js';
15
+ import { coreNextTargetOrWarn } from '../../utils/host-registration.js';
15
16
  import { shimPath } from './claude-targets.js';
16
17
  /**
17
18
  * True when this user's hq daemon unit (launchd plist, systemd unit, or the
@@ -33,6 +34,16 @@ export function isDaemonInstalled(home, platform = process.platform, queryTask =
33
34
  * the hqd shim; otherwise to master-hook.sh / the Codex adapter.
34
35
  */
35
36
  export function hookTargetFor(hqRoot, home, daemonInstalled, env = process.env) {
37
+ // hq-core-rust US-017: `core.next` on registers the new core's entry point
38
+ // for the events it can take; every other event keeps the flag-off target.
39
+ // A failure to set up the new core is one warning, and install goes on
40
+ // with the flag-off target for every event.
41
+ const coreNext = coreNextTargetOrWarn(home, env);
42
+ const fallback = legacyHookTarget(hqRoot, home, daemonInstalled, env);
43
+ return coreNext ? { ...coreNext, fallback } : fallback;
44
+ }
45
+ /** The target with `core.next` off: the pinned launcher, the hqd shim, or master-hook.sh. */
46
+ export function legacyHookTarget(hqRoot, home, daemonInstalled, env = process.env) {
36
47
  const engine = registrationEngine(home, env);
37
48
  if (engine)
38
49
  return { engine };
@@ -0,0 +1,35 @@
1
+ /**
2
+ * One id per machine, with every other id the machine is known by as an alias.
3
+ *
4
+ * The canonical id is not minted here. It is the id lane placement already
5
+ * uses: the Outpost marker (`/etc/outpost/outpost-id`) on an Outpost, and the
6
+ * stable id in `~/.hq/lane-host.json` elsewhere. This module only gathers the
7
+ * aliases, from values that are already on disk. It makes no network call, so
8
+ * the EC2 instance id and the registry instance name are not listed.
9
+ *
10
+ * The list is for printing and for joining records. It includes ids taken from
11
+ * lane records, so it must not be passed back into the local matcher to decide
12
+ * which lanes count or run on this machine.
13
+ */
14
+ import type { LaneHost, LaneRecord } from "./types.js";
15
+ /** A lane record older than this no longer contributes an alias. */
16
+ export declare const HOST_ALIAS_LANE_WINDOW_DAYS = 30;
17
+ /** Most aliases listed for one host. `parseHostCapacitySnapshot` rejects a longer list. */
18
+ export declare const HOST_ALIAS_LIMIT = 64;
19
+ export interface CanonicalHost extends LaneHost {
20
+ /** Other ids this machine is recorded under. Never contains `id`. */
21
+ aliases: string[];
22
+ }
23
+ export type CanonicalHostLane = Pick<LaneRecord, "host" | "created_at" | "updated_at"> & Partial<Pick<LaneRecord, "origin_host" | "origin_host_source">>;
24
+ export declare function resolveCanonicalHost(input: {
25
+ /** The host lane placement resolved for this process. */
26
+ host: LaneHost;
27
+ hostname: string;
28
+ /** Earlier hostnames from `~/.hq/lane-host.json`, when that file was read. */
29
+ identityAliases?: readonly string[];
30
+ /** Stable local id from `~/.hq/lane-host.json` when `host` is an Outpost. */
31
+ localIdentityId?: string;
32
+ lanes?: readonly CanonicalHostLane[];
33
+ now: Date;
34
+ }): CanonicalHost;
35
+ //# sourceMappingURL=canonical-host.d.ts.map
@@ -0,0 +1,65 @@
1
+ /**
2
+ * One id per machine, with every other id the machine is known by as an alias.
3
+ *
4
+ * The canonical id is not minted here. It is the id lane placement already
5
+ * uses: the Outpost marker (`/etc/outpost/outpost-id`) on an Outpost, and the
6
+ * stable id in `~/.hq/lane-host.json` elsewhere. This module only gathers the
7
+ * aliases, from values that are already on disk. It makes no network call, so
8
+ * the EC2 instance id and the registry instance name are not listed.
9
+ *
10
+ * The list is for printing and for joining records. It includes ids taken from
11
+ * lane records, so it must not be passed back into the local matcher to decide
12
+ * which lanes count or run on this machine.
13
+ */
14
+ import { localHostIdsReferToSameMachine } from "./local-host-identity.js";
15
+ /** A lane record older than this no longer contributes an alias. */
16
+ export const HOST_ALIAS_LANE_WINDOW_DAYS = 30;
17
+ /** Most aliases listed for one host. `parseHostCapacitySnapshot` rejects a longer list. */
18
+ export const HOST_ALIAS_LIMIT = 64;
19
+ function seenInWindow(lane, sinceMs) {
20
+ const created = Date.parse(lane.created_at);
21
+ const updated = Date.parse(lane.updated_at);
22
+ return (Number.isFinite(created) && created >= sinceMs) || (Number.isFinite(updated) && updated >= sinceMs);
23
+ }
24
+ export function resolveCanonicalHost(input) {
25
+ const id = input.host.id.trim();
26
+ const hostname = input.hostname.trim();
27
+ const aliases = [];
28
+ const add = (value) => {
29
+ const trimmed = value?.trim();
30
+ if (!trimmed || trimmed === id || aliases.includes(trimmed))
31
+ return;
32
+ if (aliases.length < HOST_ALIAS_LIMIT)
33
+ aliases.push(trimmed);
34
+ };
35
+ for (const alias of input.identityAliases ?? [])
36
+ add(alias);
37
+ add(hostname);
38
+ const localId = input.host.kind === "local" ? id : input.localIdentityId?.trim();
39
+ if (input.host.kind === "outpost")
40
+ add(localId);
41
+ // A lane stamped `local` belongs to this machine when the existing local
42
+ // matcher says so. Outpost-stamped lanes carry the marker id or another
43
+ // Outpost's id, and an `imds` origin cannot be compared without a network
44
+ // read, so neither adds an alias.
45
+ const match = {
46
+ hostname,
47
+ ...(localId ? { machineId: localId } : {}),
48
+ aliases: [...aliases],
49
+ };
50
+ const sinceMs = input.now.getTime() - HOST_ALIAS_LANE_WINDOW_DAYS * 24 * 60 * 60 * 1000;
51
+ for (const lane of input.lanes ?? []) {
52
+ if (!seenInWindow(lane, sinceMs))
53
+ continue;
54
+ if (lane.host.kind === "local" && localHostIdsReferToSameMachine(lane.host.id, match)) {
55
+ add(lane.host.id);
56
+ }
57
+ if (lane.origin_host_source === "hostname" &&
58
+ typeof lane.origin_host === "string" &&
59
+ localHostIdsReferToSameMachine(lane.origin_host, match)) {
60
+ add(lane.origin_host);
61
+ }
62
+ }
63
+ return { kind: input.host.kind, id, aliases };
64
+ }
65
+ //# sourceMappingURL=canonical-host.js.map
@@ -1,5 +1,6 @@
1
1
  import { type AuthState } from "./accounts.js";
2
2
  import type { ClaudeCredentialReader } from "./claude-credential.js";
3
+ import type { LocalHostMatch } from "./local-host-identity.js";
3
4
  import { type QuotaState } from "./quota.js";
4
5
  import type { LaneHost, LaneProvider, LaneRecord, LanesConfig } from "./types.js";
5
6
  export interface HostCapacityAccount {
@@ -40,18 +41,47 @@ export interface HostCapacityProvider {
40
41
  }
41
42
  export interface HostCapacitySnapshot {
42
43
  schema_version: "hq-lanes-host-capacity.v1";
44
+ /** The canonical host. Copied into lane records, so it carries `kind` and `id` only. */
43
45
  host: LaneHost;
46
+ /**
47
+ * Other ids this machine is recorded under. Printed as `host.aliases` by
48
+ * `hostCapacitySnapshotToWire`. Absent when the producer did not resolve
49
+ * aliases (older CLIs, and snapshots built for placement only).
50
+ */
51
+ host_aliases?: string[];
44
52
  sampled_at: string;
45
53
  providers: Record<LaneProvider, HostCapacityProvider>;
46
54
  }
55
+ /** The printed form: `hq runners capacity --json` and the remote capacity probe. */
56
+ export type HostCapacitySnapshotWire = Omit<HostCapacitySnapshot, "host" | "host_aliases"> & {
57
+ host: LaneHost & {
58
+ aliases?: string[];
59
+ };
60
+ };
47
61
  export interface HostPlacementChoice {
48
62
  host: LaneHost;
49
63
  account: string;
50
64
  queued: boolean;
51
65
  }
66
+ /** Move `host_aliases` under `host` for printing. `parseHostCapacitySnapshot` reverses it. */
67
+ export declare function hostCapacitySnapshotToWire(snapshot: HostCapacitySnapshot): HostCapacitySnapshotWire;
52
68
  /** Snapshot the same per-host running-slot predicate used by lane admission. */
53
69
  export declare function buildHostCapacitySnapshot(input: {
54
70
  host: LaneHost;
71
+ /**
72
+ * Other ids of this machine (see `resolveCanonicalHost`). Printed only: the
73
+ * list includes ids taken from lane records, and it never decides which
74
+ * lanes count.
75
+ */
76
+ aliases?: readonly string[];
77
+ /**
78
+ * What lane admission matches a local lane against on this machine: the
79
+ * hostname, the stable id and the hostnames in `~/.hq/lane-host.json`. When
80
+ * `host` is local, a lane that admission would run here also counts here.
81
+ * Ignored when `host` is an Outpost, whose counting rule is unchanged: the
82
+ * marker id, plus a local lane stamped with the exact box hostname.
83
+ */
84
+ localMatch?: LocalHostMatch;
55
85
  lanes: readonly LaneRecord[];
56
86
  config: LanesConfig;
57
87
  existsSync: (path: string) => boolean;
@@ -1,6 +1,7 @@
1
1
  import { accountStatus } from "./accounts.js";
2
2
  import { accountMaxRunning } from "./config.js";
3
3
  import { laneOccupiesRunningSlot, laneRunsOnHost, } from "./admission.js";
4
+ import { HOST_ALIAS_LIMIT } from "./canonical-host.js";
4
5
  import { LanesError } from "./errors.js";
5
6
  import { quotaBlockFor, quotaHitInfo } from "./quota.js";
6
7
  function admissionHost(host) {
@@ -8,11 +9,24 @@ function admissionHost(host) {
8
9
  ? { hostname: "", outpostId: host.id }
9
10
  : { hostname: host.id, outpostId: null };
10
11
  }
12
+ /** Move `host_aliases` under `host` for printing. `parseHostCapacitySnapshot` reverses it. */
13
+ export function hostCapacitySnapshotToWire(snapshot) {
14
+ const { host, host_aliases: aliases, ...rest } = snapshot;
15
+ return {
16
+ ...rest,
17
+ host: { kind: host.kind, id: host.id, ...(aliases !== undefined ? { aliases: [...aliases] } : {}) },
18
+ };
19
+ }
11
20
  /** Snapshot the same per-host running-slot predicate used by lane admission. */
12
21
  export function buildHostCapacitySnapshot(input) {
13
22
  const at = input.now.getTime();
14
23
  const localHostname = input.hostname?.trim();
15
- const onHost = input.lanes.filter((lane) => laneRunsOnHost(lane, admissionHost(input.host)) ||
24
+ const countedHost = admissionHost(input.host);
25
+ const localAdmission = input.host.kind === "local" && input.localMatch !== undefined
26
+ ? { ...input.localMatch, outpostId: null }
27
+ : undefined;
28
+ const onHost = input.lanes.filter((lane) => laneRunsOnHost(lane, countedHost) ||
29
+ (localAdmission !== undefined && laneRunsOnHost(lane, localAdmission)) ||
16
30
  (input.host.kind === "outpost" &&
17
31
  localHostname !== undefined &&
18
32
  localHostname !== "" &&
@@ -73,7 +87,8 @@ export function buildHostCapacitySnapshot(input) {
73
87
  }
74
88
  return {
75
89
  schema_version: "hq-lanes-host-capacity.v1",
76
- host: input.host,
90
+ host: { kind: input.host.kind, id: input.host.id },
91
+ ...(input.aliases !== undefined ? { host_aliases: [...input.aliases] } : {}),
77
92
  sampled_at: input.now.toISOString(),
78
93
  providers,
79
94
  };
@@ -108,6 +123,16 @@ export function parseHostCapacitySnapshot(raw) {
108
123
  providersRaw === undefined) {
109
124
  throw new LanesError("host_capacity_invalid", "Malformed host capacity snapshot", {});
110
125
  }
126
+ // Absent on snapshots from older CLIs. A present list is kept for printing
127
+ // and must be a bounded list of non-empty strings. Nothing counts lanes or
128
+ // places work by it.
129
+ const aliasesRaw = hostRaw.aliases;
130
+ if (aliasesRaw !== undefined && (!Array.isArray(aliasesRaw) ||
131
+ aliasesRaw.length > HOST_ALIAS_LIMIT ||
132
+ aliasesRaw.some((alias) => typeof alias !== "string" || alias.trim() === ""))) {
133
+ throw new LanesError("host_capacity_invalid", "Malformed host capacity snapshot", { field: "host.aliases" });
134
+ }
135
+ const hostAliases = aliasesRaw === undefined ? undefined : [...aliasesRaw];
111
136
  const providers = {};
112
137
  for (const provider of ["claude", "codex", "grok"]) {
113
138
  const row = objectValue(providersRaw[provider]);
@@ -171,6 +196,7 @@ export function parseHostCapacitySnapshot(raw) {
171
196
  return {
172
197
  schema_version: "hq-lanes-host-capacity.v1",
173
198
  host: { kind: hostRaw.kind, id: hostRaw.id },
199
+ ...(hostAliases !== undefined ? { host_aliases: hostAliases } : {}),
174
200
  sampled_at: root.sampled_at,
175
201
  providers,
176
202
  };
@@ -253,7 +279,7 @@ export function chooseHostForLane(snapshots, request) {
253
279
  if (!hasRunningSlot && !hasQueueSlot)
254
280
  continue;
255
281
  candidates.push({
256
- host: snapshot.host,
282
+ host: { kind: snapshot.host.kind, id: snapshot.host.id },
257
283
  account: accountId,
258
284
  queued: !hasRunningSlot,
259
285
  score: provider.running / provider.max_running +
@@ -47,6 +47,9 @@ import { applyDefaultQuotaHold, clearAccountQuotaAfterSuccessfulTurnBestEffort,
47
47
  import { deliverQuotaNotice as deliverQuotaNoticeToSenior, quotaLaneNotice } from "./quota-notice.js";
48
48
  import { PROVIDER_REJECTED_REASON, QUOTA_STATUS, isProviderLoginFailure, providerRejectionDetails, readProviderRejection, } from "./provider-rejection.js";
49
49
  import { appendDropboxMessageAtPath, dropboxInboxHasMessages, readToolActivity, toolActivityPath } from "./dropbox.js";
50
+ import { usageLimitWindow } from "../bot/runtime-failure.js";
51
+ import { recordRefusalForHome } from "../capacity/refusal.js";
52
+ import { effectiveAccountHome } from "./account-home.js";
50
53
  import { loadLanesConfig, providerProgressEventMinIntervalMs, providerQuotaDefaultHoldMs } from "./config.js";
51
54
  import { resolveAdmissionHost as resolveProcessAdmissionHost } from "./admission-host.js";
52
55
  import { createLaneMesh, emitLaneDecisionEvents, emitLaneProgressEvent, emitLaneTerminalStateEvent, laneStoryStatusSuppressionKey, progressEventDue, } from "./mesh-events.js";
@@ -356,6 +359,36 @@ export function clearLaneStalled(hqRoot, laneId) {
356
359
  return { ...current, stalled: undefined, stalled_at: undefined, stalled_reason: undefined };
357
360
  });
358
361
  }
362
+ /**
363
+ * A lane the provider refused corrects the ledger. Only these classified reasons
364
+ * count: a timeout or a crash says nothing about the account's usage. The quota
365
+ * signal's `quota_reset_at` is the lane's own capped hold, so the provider's reset
366
+ * comes first. A rate limit lasts the provider's configured hold.
367
+ */
368
+ function recordLaneRefusal(hqRoot, lane, classification, quota) {
369
+ const quotaExhausted = classification.reason === "account_quota_exhausted";
370
+ if (!quotaExhausted && classification.reason !== "provider_rate_limited")
371
+ return;
372
+ if (!lane.provider || !lane.account)
373
+ return;
374
+ try {
375
+ const provider = loadLanesConfig(hqRoot).providers[lane.provider];
376
+ const account = provider?.accounts?.[lane.account];
377
+ if (!provider || !account)
378
+ return;
379
+ recordRefusalForHome({
380
+ provider: lane.provider,
381
+ home: effectiveAccountHome(account).home,
382
+ window: quotaExhausted ? usageLimitWindow(quota?.provider_text) : { kind: "rate_limit" },
383
+ // Kept when the text names a window. With none, recordRefusalForHome uses it only on a repeat.
384
+ resetsAt: quotaExhausted ? quota?.provider_reset_at ?? quota?.quota_reset_at : undefined,
385
+ holdMs: providerQuotaDefaultHoldMs(provider),
386
+ });
387
+ }
388
+ catch (err) {
389
+ process.stderr.write(`hq lanes watcher: refusal not recorded for ${lane.lane_id}: ${err instanceof Error ? err.message : String(err)}\n`);
390
+ }
391
+ }
359
392
  export function applyTerminalToLane(hqRoot, laneId, classification, opts = {}) {
360
393
  return applyTerminalToLaneWithResult(hqRoot, laneId, classification, opts).record;
361
394
  }
@@ -573,6 +606,8 @@ function applyTerminalToLaneWithResult(hqRoot, laneId, classification, opts = {}
573
606
  provider: updated.provider,
574
607
  account: updated.account,
575
608
  });
609
+ if (changed)
610
+ recordLaneRefusal(hqRoot, updated, effectiveClassification, opts.quota);
576
611
  return {
577
612
  record: updated,
578
613
  changed,
@@ -100,6 +100,8 @@ export interface DaemonRunDeps {
100
100
  * probe defers; it does not clear the company. Defaults to isMachineIdentity().
101
101
  */
102
102
  machineIdentity?: boolean;
103
+ /** Reporting gate (tests). Defaults to one createReportingGate for the daemon's lifetime. */
104
+ reportingAllowed?: () => Promise<boolean>;
103
105
  /** Test seam immediately before a device-default revocation's guarded commit. */
104
106
  beforeDeviceDefaultRevocationCommit?: () => void;
105
107
  log?: (dir: string, line: string) => void;
@@ -1,4 +1,4 @@
1
- import { reportingRuntimeAllowed } from "../reporting-privacy.js";
1
+ import { createReportingGate } from "../reporting-privacy.js";
2
2
  /**
3
3
  * hq mesh daemon run — single-instance resident process.
4
4
  *
@@ -373,6 +373,9 @@ export async function runMeshDaemon(deps = {}) {
373
373
  }
374
374
  };
375
375
  const shutdownController = new AbortController();
376
+ // One gate for the daemon's lifetime: the person setting is read from the
377
+ // server once and on change, not on every flush.
378
+ const reportingAllowed = deps.reportingAllowed ?? createReportingGate(machineIdentity, env, { home });
376
379
  const flushFn = deps.flush ??
377
380
  (async (signal) => {
378
381
  const t = await getToken();
@@ -382,7 +385,7 @@ export async function runMeshDaemon(deps = {}) {
382
385
  });
383
386
  return flushSessionEvents({
384
387
  env,
385
- reportingAllowed: () => reportingRuntimeAllowed(machineIdentity, env),
388
+ reportingAllowed,
386
389
  workMeshRoot: meshRoot,
387
390
  workContextRoot: ctxRoot,
388
391
  poster,
@@ -24,7 +24,11 @@ export declare const HELD_MAX_LINES = 20000;
24
24
  export declare const PROJECT_REBIND_INTERVAL_MS = 60000;
25
25
  export type HeldReason = "STATE_ABSENT" | "NEEDS_COMPANY" | "COMPANY_CONFLICT" | "NEEDS_PROJECT" | "HELD_EXPIRED" | "HELD_OVERFLOW";
26
26
  export interface FlushDeps {
27
- /** Production callers re-read the shared person preference before each flush. */
27
+ /**
28
+ * Whether this process may report. Asked before anything is claimed or sent,
29
+ * and only when the flush has something to look at. The daemon passes a gate
30
+ * that keeps the person setting between flushes (createReportingGate).
31
+ */
28
32
  reportingAllowed?: () => Promise<boolean>;
29
33
  workMeshRoot: string;
30
34
  workContextRoot: string;
@@ -24,7 +24,7 @@ import { LOCAL_ONLY_FIELDS, stripLocalOnlyFields } from "./format-spool-line.js"
24
24
  import { enrichSessionEndEvent } from "./report-summary.js";
25
25
  import { createWorkLocationResolver, withWorkLocation, } from "./work-location.js";
26
26
  import { SESSION_EVENTS_BATCH_MAX, WRITABLE_CONTEXT_STATUSES, isSessionOwnerMismatch, parseSessionEventsBatchAck, SESSION_OWNER_MISMATCH, } from "./session-events-client.js";
27
- import { appendDeadLetterLine, appendDroppedReceipt, appendHeldLinesIfAbsent, appendSpoolLine, claimHeld, claimSpool, countDistinctHeldEvents, countJsonlLines, recoverOrphanClaims, removeClaimFile, } from "./spool.js";
27
+ import { appendDeadLetterLine, appendDroppedReceipt, appendHeldLinesIfAbsent, appendSpoolLine, claimHeld, claimSpool, countDistinctHeldEvents, countJsonlLines, hasPendingFlushWork, recoverOrphanClaims, removeClaimFile, } from "./spool.js";
28
28
  import { workMeshHeldPath, workMeshRoot } from "./paths.js";
29
29
  /** Bound a replayed session backlog so one flush cannot burst hundreds of events. */
30
30
  const SESSION_EVENTS_MAX_PER_SESSION_PER_FLUSH = 25;
@@ -174,11 +174,17 @@ async function postBatchWithRetries(poster, body, deps) {
174
174
  */
175
175
  export async function flushSessionEvents(inputDeps) {
176
176
  const env = inputDeps.env ?? process.env;
177
- if (reportingLocallyDisabled(env) ||
178
- (inputDeps.reportingAllowed && !(await inputDeps.reportingAllowed()))) {
179
- return { claimed: 0, posted: 0, held: 0, dropped: 0, deadLettered: 0,
180
- restored: 0, batches: 0, heldClaimed: false, heldOverflow: 0 };
181
- }
177
+ const nothingDone = () => ({ claimed: 0, posted: 0, held: 0, dropped: 0, deadLettered: 0,
178
+ restored: 0, batches: 0, heldClaimed: false, heldOverflow: 0 });
179
+ if (reportingLocallyDisabled(env))
180
+ return nothingDone();
181
+ // Idle machine: with nothing spooled, held or orphaned there is nothing to
182
+ // report, so do not ask whether reporting is allowed. The gate still runs
183
+ // before anything is claimed or sent whenever there is something.
184
+ if (!hasPendingFlushWork(inputDeps.workMeshRoot))
185
+ return nothingDone();
186
+ if (inputDeps.reportingAllowed && !(await inputDeps.reportingAllowed()))
187
+ return nothingDone();
182
188
  // One resolver per flush: git lookups are cached per cwd for this flush only.
183
189
  const deps = {
184
190
  ...inputDeps,
@@ -4,4 +4,36 @@ export declare function reportingLocallyDisabled(env?: NodeJS.ProcessEnv): boole
4
4
  export declare function mayEmitConversation(event: Record<string, unknown>, env?: NodeJS.ProcessEnv): boolean;
5
5
  /** Fleet identities have no person preference; operator and local controls still apply. */
6
6
  export declare function reportingRuntimeAllowed(machine: boolean, env?: NodeJS.ProcessEnv): Promise<boolean>;
7
+ /**
8
+ * Local state that moves when the person's HQ Anywhere answer may have moved:
9
+ * whether the hq daemon's revocation marker exists, which flips when that
10
+ * daemon's own decision flips, and the person token cache, which is replaced
11
+ * on sign-in, sign-out and account switch. Nothing on this machine writes the
12
+ * setting itself; the desktop app writes it to the server.
13
+ *
14
+ * The marker only prompts a re-read. It is never taken as the answer: it also
15
+ * covers the operator flag, the hq daemon keeps its last value for a while
16
+ * when its own read fails, and it goes stale when that daemon is not running.
17
+ * Only its presence counts, because the hq daemon rewrites it on every poll
18
+ * while off.
19
+ */
20
+ export declare function reportingSettingChangeSignal(env?: NodeJS.ProcessEnv, home?: string): string;
21
+ export interface ReportingGateOptions {
22
+ home?: string;
23
+ /** Reads the person setting from the server; null when it cannot be read. */
24
+ readSetting?: () => Promise<boolean | null>;
25
+ changeSignal?: () => string;
26
+ refreshMs?: number;
27
+ failureRetryMs?: number;
28
+ /** Monotonic milliseconds. */
29
+ now?: () => number;
30
+ }
31
+ /**
32
+ * The reporting gate for a long-running process (the Work Mesh Live daemon).
33
+ * Same answer as reportingRuntimeAllowed, but the person setting is read from
34
+ * the server once and kept: it is re-read when local state signals a change
35
+ * and on a slow safety refresh, never per call. Local switches and the
36
+ * operator flag are still checked on every call. Unknown stays closed.
37
+ */
38
+ export declare function createReportingGate(machine: boolean, env?: NodeJS.ProcessEnv, options?: ReportingGateOptions): () => Promise<boolean>;
7
39
  //# sourceMappingURL=reporting-privacy.d.ts.map