@indigoai-us/hq-cli 5.345.215 → 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 (135) hide show
  1. package/CHANGELOG.md +141 -0
  2. package/README.md +45 -0
  3. package/assets/scaffold/core/scripts/lib/epochrealtime.sh +30 -0
  4. package/assets/scaffold/core/scripts/lib/work-mesh-enqueue.sh +12 -5
  5. package/dist/command-catalog.generated.d.ts +59 -4
  6. package/dist/command-catalog.generated.js +74 -4
  7. package/dist/command-help.js +3 -1
  8. package/dist/command-registration-plan.d.ts +6 -0
  9. package/dist/command-registration-plan.js +1 -0
  10. package/dist/commands/auth.d.ts +1 -1
  11. package/dist/commands/auth.js +11 -52
  12. package/dist/commands/bot.js +11 -4
  13. package/dist/commands/cloud-demote.d.ts +19 -4
  14. package/dist/commands/cloud-demote.js +85 -12
  15. package/dist/commands/cloud-provision.d.ts +5 -1
  16. package/dist/commands/cloud-provision.js +6 -2
  17. package/dist/commands/cloud.d.ts +36 -0
  18. package/dist/commands/cloud.js +109 -26
  19. package/dist/commands/core.js +1 -0
  20. package/dist/commands/daemon.js +4 -1
  21. package/dist/commands/dm.js +7 -0
  22. package/dist/commands/doctor-usage.d.ts +8 -0
  23. package/dist/commands/doctor-usage.js +20 -0
  24. package/dist/commands/doctor.js +7 -1
  25. package/dist/commands/env.d.ts +18 -0
  26. package/dist/commands/env.js +82 -0
  27. package/dist/commands/install-global.js +2 -2
  28. package/dist/commands/lanes.js +100 -24
  29. package/dist/commands/logout.d.ts +7 -0
  30. package/dist/commands/logout.js +41 -34
  31. package/dist/commands/sources.d.ts +8 -2
  32. package/dist/commands/sources.js +65 -9
  33. package/dist/commands/whoami.js +26 -1
  34. package/dist/data/command-states.json +15 -0
  35. package/dist/index.js +52 -4
  36. package/dist/lazy-commands.js +2 -1
  37. package/dist/lib/anywhere-person-setting.d.ts +2 -0
  38. package/dist/lib/anywhere-person-setting.js +6 -3
  39. package/dist/lib/billing/usage-card.d.ts +25 -4
  40. package/dist/lib/billing/usage-card.js +76 -9
  41. package/dist/lib/billing/usage-cost.d.ts +3 -3
  42. package/dist/lib/billing/usage-cost.js +35 -13
  43. package/dist/lib/billing/usage-only.js +4 -2
  44. package/dist/lib/billing/usage-rate-card.d.ts +2 -2
  45. package/dist/lib/billing/usage-rate-card.js +3 -0
  46. package/dist/lib/bot/fleet-cron.js +93 -6
  47. package/dist/lib/bot/inflight.d.ts +9 -0
  48. package/dist/lib/bot/inflight.js +10 -0
  49. package/dist/lib/bot/jobs/hot-signal-sync.js +12 -1
  50. package/dist/lib/bot/runtime/grok-acp.d.ts +1 -0
  51. package/dist/lib/bot/runtime/grok-acp.js +26 -11
  52. package/dist/lib/bot/runtime/grok.js +1 -1
  53. package/dist/lib/daemon/flag-monitor.d.ts +8 -0
  54. package/dist/lib/daemon/flag-monitor.js +17 -6
  55. package/dist/lib/daemon/flag.d.ts +65 -1
  56. package/dist/lib/daemon/flag.js +190 -40
  57. package/dist/lib/daemon/ops/policy.js +62 -5
  58. package/dist/lib/daemon/paths.d.ts +72 -2
  59. package/dist/lib/daemon/paths.js +154 -3
  60. package/dist/lib/daemon/run.js +25 -20
  61. package/dist/lib/daemon/selfcheck.d.ts +22 -0
  62. package/dist/lib/daemon/selfcheck.js +40 -1
  63. package/dist/lib/daemon/server.d.ts +3 -1
  64. package/dist/lib/daemon/server.js +7 -22
  65. package/dist/lib/daemon/state-file-switch.d.ts +57 -0
  66. package/dist/lib/daemon/state-file-switch.js +88 -0
  67. package/dist/lib/daemon/state-file.d.ts +198 -0
  68. package/dist/lib/daemon/state-file.js +419 -0
  69. package/dist/lib/daemon/timed-flag-monitors.d.ts +47 -0
  70. package/dist/lib/daemon/timed-flag-monitors.js +75 -0
  71. package/dist/lib/doctor/checks/host-core.d.ts +50 -0
  72. package/dist/lib/doctor/checks/host-core.js +269 -0
  73. package/dist/lib/doctor/checks/replay-recorder.d.ts +39 -0
  74. package/dist/lib/doctor/checks/replay-recorder.js +261 -0
  75. package/dist/lib/doctor/registry.js +4 -0
  76. package/dist/lib/environment/profile.d.ts +239 -0
  77. package/dist/lib/environment/profile.js +251 -0
  78. package/dist/lib/hook-engine/reconcile.js +39 -13
  79. package/dist/lib/hook-engine/registration.d.ts +9 -0
  80. package/dist/lib/hook-engine/registration.js +19 -0
  81. package/dist/lib/hot-channels/adapters/slack.d.ts +21 -5
  82. package/dist/lib/hot-channels/adapters/slack.js +64 -21
  83. package/dist/lib/hot-channels/alert.d.ts +2 -0
  84. package/dist/lib/hot-channels/alert.js +8 -1
  85. package/dist/lib/hot-channels/contract.d.ts +12 -0
  86. package/dist/lib/hot-channels/contract.js +7 -0
  87. package/dist/lib/hot-channels/loop.js +1 -0
  88. package/dist/lib/hot-channels/run.d.ts +6 -0
  89. package/dist/lib/hot-channels/run.js +4 -0
  90. package/dist/lib/hot-channels/signals-pass.d.ts +64 -1
  91. package/dist/lib/hot-channels/signals-pass.js +21 -49
  92. package/dist/lib/install/claude-targets.d.ts +12 -1
  93. package/dist/lib/install/claude-targets.js +57 -5
  94. package/dist/lib/install/codex-targets.d.ts +2 -2
  95. package/dist/lib/install/codex-targets.js +36 -6
  96. package/dist/lib/install/hook-target.d.ts +3 -0
  97. package/dist/lib/install/hook-target.js +11 -0
  98. package/dist/lib/lanes/canonical-host.d.ts +35 -0
  99. package/dist/lib/lanes/canonical-host.js +65 -0
  100. package/dist/lib/lanes/host-capacity.d.ts +30 -0
  101. package/dist/lib/lanes/host-capacity.js +29 -3
  102. package/dist/lib/mesh/live/daemon/run.d.ts +2 -0
  103. package/dist/lib/mesh/live/daemon/run.js +5 -2
  104. package/dist/lib/mesh/live/flush.d.ts +5 -1
  105. package/dist/lib/mesh/live/flush.js +12 -6
  106. package/dist/lib/mesh/live/reporting-privacy.d.ts +32 -0
  107. package/dist/lib/mesh/live/reporting-privacy.js +56 -1
  108. package/dist/lib/mesh/live/spool.d.ts +7 -0
  109. package/dist/lib/mesh/live/spool.js +25 -0
  110. package/dist/lib/person-setting-cache.d.ts +38 -0
  111. package/dist/lib/person-setting-cache.js +98 -0
  112. package/dist/lib/safe-store.d.ts +245 -0
  113. package/dist/lib/safe-store.js +777 -0
  114. package/dist/lib/signals/engine.d.ts +29 -2
  115. package/dist/lib/signals/engine.js +103 -4
  116. package/dist/lib/signals/reply.js +73 -18
  117. package/dist/lib/signals/steps/adapters.js +7 -2
  118. package/dist/lib/signals/steps/extract.d.ts +13 -0
  119. package/dist/lib/signals/steps/extract.js +84 -4
  120. package/dist/main.js +46 -3
  121. package/dist/schemas/hq-environment-profile.v1.schema.json +438 -0
  122. package/dist/utils/auth-expiry.d.ts +8 -0
  123. package/dist/utils/auth-expiry.js +53 -0
  124. package/dist/utils/cli-telemetry.d.ts +21 -0
  125. package/dist/utils/cli-telemetry.js +34 -0
  126. package/dist/utils/command-usage.d.ts +275 -0
  127. package/dist/utils/command-usage.js +797 -0
  128. package/dist/utils/hook-trust.d.ts +7 -0
  129. package/dist/utils/hook-trust.js +31 -4
  130. package/dist/utils/host-registration.d.ts +126 -0
  131. package/dist/utils/host-registration.js +378 -0
  132. package/dist/utils/resident-package-preload.js +2 -0
  133. package/package.json +10 -8
  134. package/scripts/bench-core.mjs +1096 -0
  135. package/scripts/check-function-manifest.mjs +702 -0
@@ -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 +
@@ -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
@@ -1,4 +1,8 @@
1
- import { anywhereRuntimeAllowed } from "../../anywhere-person-setting.js";
1
+ import * as fs from "node:fs";
2
+ import * as os from "node:os";
3
+ import { anywhereRuntimeAllowed, personTokenCachePath, readHqAnywherePersonSetting } from "../../anywhere-person-setting.js";
4
+ import { anywhereRuntimeRevocationMarkerPath } from "../../anywhere-runtime-revocation-marker.js";
5
+ import { cachedPersonSettingReader } from "../../person-setting-cache.js";
2
6
  import { anywhereRuntimeEnabledFromSnapshot } from "../../anywhere-runtime-fast-flag.js";
3
7
  import { hqAnywhereRuntimeLocallyDisabled } from "../../anywhere-runtime-flag-key.js";
4
8
  import { isNonCloudCompanySlug } from "../../work-context/company-rebind.js";
@@ -44,4 +48,55 @@ export async function reportingRuntimeAllowed(machine, env = process.env) {
44
48
  return false;
45
49
  return machine ? anywhereRuntimeEnabledFromSnapshot(env) : anywhereRuntimeAllowed(env);
46
50
  }
51
+ function fileFingerprint(file) {
52
+ try {
53
+ const stat = fs.statSync(file);
54
+ return [stat.ino, stat.size, stat.mtimeMs].join(":");
55
+ }
56
+ catch (error) {
57
+ return "none:" + (error?.code ?? "unknown");
58
+ }
59
+ }
60
+ /**
61
+ * Local state that moves when the person's HQ Anywhere answer may have moved:
62
+ * whether the hq daemon's revocation marker exists, which flips when that
63
+ * daemon's own decision flips, and the person token cache, which is replaced
64
+ * on sign-in, sign-out and account switch. Nothing on this machine writes the
65
+ * setting itself; the desktop app writes it to the server.
66
+ *
67
+ * The marker only prompts a re-read. It is never taken as the answer: it also
68
+ * covers the operator flag, the hq daemon keeps its last value for a while
69
+ * when its own read fails, and it goes stale when that daemon is not running.
70
+ * Only its presence counts, because the hq daemon rewrites it on every poll
71
+ * while off.
72
+ */
73
+ export function reportingSettingChangeSignal(env = process.env, home) {
74
+ const resolvedHome = home ?? (env.HOME?.trim() || os.homedir());
75
+ return [
76
+ fs.existsSync(anywhereRuntimeRevocationMarkerPath(resolvedHome, env)) ? "revoked" : "clear",
77
+ fileFingerprint(personTokenCachePath(env, resolvedHome)),
78
+ ].join("|");
79
+ }
80
+ /**
81
+ * The reporting gate for a long-running process (the Work Mesh Live daemon).
82
+ * Same answer as reportingRuntimeAllowed, but the person setting is read from
83
+ * the server once and kept: it is re-read when local state signals a change
84
+ * and on a slow safety refresh, never per call. Local switches and the
85
+ * operator flag are still checked on every call. Unknown stays closed.
86
+ */
87
+ export function createReportingGate(machine, env = process.env, options = {}) {
88
+ const readSetting = cachedPersonSettingReader(options.readSetting ?? (() => readHqAnywherePersonSetting({ env, home: options.home })), {
89
+ refreshMs: options.refreshMs,
90
+ failureRetryMs: options.failureRetryMs,
91
+ now: options.now,
92
+ changeSignal: options.changeSignal ?? (() => reportingSettingChangeSignal(env, options.home)),
93
+ });
94
+ return async () => {
95
+ if (reportingLocallyDisabled(env))
96
+ return false;
97
+ if (machine)
98
+ return anywhereRuntimeEnabledFromSnapshot(env);
99
+ return anywhereRuntimeAllowed(env, { readSetting });
100
+ };
101
+ }
47
102
  //# sourceMappingURL=reporting-privacy.js.map
@@ -34,6 +34,13 @@ export interface ClaimResult {
34
34
  export declare function claimJsonlByRename(sourcePath: string, claimPath: string): ClaimResult;
35
35
  export declare function claimSpool(root: string, ts?: string): ClaimResult;
36
36
  export declare function claimHeld(root: string, ts?: string): ClaimResult;
37
+ /**
38
+ * True when a flush has anything to look at: an orphan claim, or bytes in the
39
+ * spool or held file. Reads nothing and moves nothing, so a flush can stop
40
+ * here on an idle machine before it asks the server whether it may report.
41
+ * Any doubt answers true.
42
+ */
43
+ export declare function hasPendingFlushWork(root: string): boolean;
37
44
  /**
38
45
  * Recover orphaned claim files: read their lines and return paths to unlink
39
46
  * after the flush dispositions them.
@@ -278,6 +278,31 @@ function listOrphanClaimFiles(root) {
278
278
  }
279
279
  return out.sort();
280
280
  }
281
+ function jsonlHasBytes(file) {
282
+ try {
283
+ return fs.statSync(file).size > 0;
284
+ }
285
+ catch (err) {
286
+ // Only a missing file is known to be empty; anything else goes to the flush.
287
+ return err?.code !== "ENOENT";
288
+ }
289
+ }
290
+ /**
291
+ * True when a flush has anything to look at: an orphan claim, or bytes in the
292
+ * spool or held file. Reads nothing and moves nothing, so a flush can stop
293
+ * here on an idle machine before it asks the server whether it may report.
294
+ * Any doubt answers true.
295
+ */
296
+ export function hasPendingFlushWork(root) {
297
+ try {
298
+ if (listOrphanClaimFiles(root).length > 0)
299
+ return true;
300
+ }
301
+ catch {
302
+ return true;
303
+ }
304
+ return jsonlHasBytes(workMeshSpoolPath(root)) || jsonlHasBytes(workMeshHeldPath(root));
305
+ }
281
306
  function readClaimFileLines(claimPath) {
282
307
  if (!fs.existsSync(claimPath))
283
308
  return [];
@@ -0,0 +1,38 @@
1
+ /**
2
+ * How long a long-running process may keep using a person setting it read.
3
+ * The setting changes rarely, so the process reads it once and re-reads on a
4
+ * local change signal. This interval is the safety refresh for a change the
5
+ * process cannot be told about: one made on another device, or on a machine
6
+ * where nothing local records the change. It is the longest a remote opt-out
7
+ * can go unnoticed. Age is measured on the monotonic clock and on the wall
8
+ * clock, and the value is dropped when either says it is too old, so time
9
+ * spent suspended counts.
10
+ */
11
+ export declare const PERSON_SETTING_REFRESH_MS: number;
12
+ /** A failed read is not retried before this; the answer stays closed meanwhile. */
13
+ export declare const PERSON_SETTING_FAILURE_RETRY_MS = 60000;
14
+ export interface CachedPersonSettingReaderOptions {
15
+ refreshMs?: number;
16
+ failureRetryMs?: number;
17
+ /** Monotonic milliseconds. Tests inject a clock. */
18
+ now?: () => number;
19
+ /** Wall-clock milliseconds. Covers time the monotonic clock does not count while suspended. */
20
+ wallNow?: () => number;
21
+ /**
22
+ * Fingerprint of local state that changes when the setting or the signed-in
23
+ * person may have changed. A different fingerprint discards the stored value.
24
+ */
25
+ changeSignal?: () => string;
26
+ }
27
+ /**
28
+ * Wrap a person-setting reader so a long-running caller reads the server once
29
+ * per refresh interval instead of once per call.
30
+ *
31
+ * Fails closed: the result is null (unknown) until a read succeeds, after a
32
+ * failed read, and whenever the stored value is older than the refresh
33
+ * interval and its refresh failed. A stored `true` is never returned past the
34
+ * interval or after the change signal moved. Concurrent callers share one
35
+ * in-flight read.
36
+ */
37
+ export declare function cachedPersonSettingReader(read: () => Promise<boolean | null>, options?: CachedPersonSettingReaderOptions): () => Promise<boolean | null>;
38
+ //# sourceMappingURL=person-setting-cache.d.ts.map