@indigoai-us/hq-cli 5.345.220 → 5.345.222

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 (184) hide show
  1. package/CHANGELOG.md +164 -0
  2. package/dist/command-catalog.generated.d.ts +175 -2
  3. package/dist/command-catalog.generated.js +213 -2
  4. package/dist/commands/auth.js +6 -2
  5. package/dist/commands/bot-runtime.d.ts +18 -5
  6. package/dist/commands/bot-runtime.js +29 -12
  7. package/dist/commands/bot.d.ts +39 -2
  8. package/dist/commands/bot.js +140 -11
  9. package/dist/commands/core-delegate-w1b.js +9 -3
  10. package/dist/commands/core-stop-autosave.d.ts +21 -0
  11. package/dist/commands/core-stop-autosave.js +300 -0
  12. package/dist/commands/core.js +2 -0
  13. package/dist/commands/daemon.d.ts +6 -0
  14. package/dist/commands/daemon.js +46 -8
  15. package/dist/commands/doctor-usage.d.ts +5 -0
  16. package/dist/commands/doctor-usage.js +25 -0
  17. package/dist/commands/env.d.ts +49 -4
  18. package/dist/commands/env.js +355 -5
  19. package/dist/commands/lanes-shared.d.ts +3 -0
  20. package/dist/commands/lanes.d.ts +3 -0
  21. package/dist/commands/lanes.js +87 -3
  22. package/dist/commands/link.d.ts +2 -0
  23. package/dist/commands/link.js +14 -2
  24. package/dist/commands/mesh.js +23 -3
  25. package/dist/commands/sources.js +3 -3
  26. package/dist/commands/sync-core.d.ts +7 -0
  27. package/dist/commands/sync-core.js +132 -3
  28. package/dist/commands/whoami.js +96 -80
  29. package/dist/data/command-states.json +3 -0
  30. package/dist/lib/bot/config.d.ts +17 -0
  31. package/dist/lib/bot/config.js +13 -0
  32. package/dist/lib/bot/fleet-cron.js +24 -2
  33. package/dist/lib/bot/fleet-local.d.ts +30 -2
  34. package/dist/lib/bot/fleet-local.js +60 -1
  35. package/dist/lib/bot/grok-login-scope.d.ts +36 -0
  36. package/dist/lib/bot/grok-login-scope.js +93 -0
  37. package/dist/lib/bot/legacy-provider-login.d.ts +32 -9
  38. package/dist/lib/bot/legacy-provider-login.js +28 -22
  39. package/dist/lib/bot/runtime-sign-in-check.js +6 -1
  40. package/dist/lib/bot/runtime-sign-in.d.ts +2 -0
  41. package/dist/lib/core-utils/sentry-report.js +2 -0
  42. package/dist/lib/daemon/catalog.js +2 -0
  43. package/dist/lib/daemon/install.d.ts +2 -1
  44. package/dist/lib/daemon/install.js +9 -0
  45. package/dist/lib/daemon/legacy.d.ts +1 -0
  46. package/dist/lib/daemon/legacy.js +5 -2
  47. package/dist/lib/daemon/machine-check-owner.d.ts +2 -0
  48. package/dist/lib/daemon/machine-check-owner.js +6 -1
  49. package/dist/lib/daemon/machine-checks.d.ts +29 -2
  50. package/dist/lib/daemon/machine-checks.js +64 -13
  51. package/dist/lib/daemon/mesh-owner.d.ts +45 -0
  52. package/dist/lib/daemon/mesh-owner.js +166 -0
  53. package/dist/lib/daemon/native-notice-ledger.d.ts +27 -0
  54. package/dist/lib/daemon/native-notice-ledger.js +113 -0
  55. package/dist/lib/daemon/run.d.ts +15 -0
  56. package/dist/lib/daemon/run.js +137 -11
  57. package/dist/lib/daemon/selfcheck.d.ts +35 -2
  58. package/dist/lib/daemon/selfcheck.js +118 -9
  59. package/dist/lib/daemon/stop-autosave-lock.d.ts +19 -0
  60. package/dist/lib/daemon/stop-autosave-lock.js +166 -0
  61. package/dist/lib/daemon/stop-autosave.d.ts +28 -0
  62. package/dist/lib/daemon/stop-autosave.js +111 -0
  63. package/dist/lib/daemon/stop-diagnostics.d.ts +11 -0
  64. package/dist/lib/daemon/stop-diagnostics.js +136 -0
  65. package/dist/lib/daemon/stop-job-executor.d.ts +19 -0
  66. package/dist/lib/daemon/stop-job-executor.js +126 -0
  67. package/dist/lib/daemon/stop-jobs.d.ts +93 -0
  68. package/dist/lib/daemon/stop-jobs.js +599 -0
  69. package/dist/lib/doctor/checks/fleet-hook-core.js +1 -1
  70. package/dist/lib/doctor/checks/host-core.js +1 -1
  71. package/dist/lib/environment/access-probes.d.ts +234 -0
  72. package/dist/lib/environment/access-probes.js +918 -0
  73. package/dist/lib/environment/profile.d.ts +15 -2
  74. package/dist/lib/environment/profile.js +55 -20
  75. package/dist/lib/environment/rfc3339.d.ts +8 -0
  76. package/dist/lib/environment/rfc3339.js +26 -0
  77. package/dist/lib/environment/work-requirements.d.ts +169 -0
  78. package/dist/lib/environment/work-requirements.js +389 -0
  79. package/dist/lib/hook-engine/coverage.d.ts +146 -7
  80. package/dist/lib/hook-engine/coverage.js +1480 -4
  81. package/dist/lib/hook-engine/fleet-registration.js +2 -2
  82. package/dist/lib/hook-engine/git-stop-config.json +513 -0
  83. package/dist/lib/hook-engine/native-stop-compatibility.json +362 -0
  84. package/dist/lib/hook-engine/reconcile.js +2 -2
  85. package/dist/lib/hot-channels/alert.d.ts +2 -2
  86. package/dist/lib/hot-channels/alert.js +8 -5
  87. package/dist/lib/hot-channels/signals-pass.d.ts +126 -17
  88. package/dist/lib/hot-channels/signals-pass.js +296 -17
  89. package/dist/lib/hot-channels/signals-runtime.d.ts +30 -0
  90. package/dist/lib/hot-channels/signals-runtime.js +82 -0
  91. package/dist/lib/install/hook-target.js +1 -1
  92. package/dist/lib/lanes/host-capacity.d.ts +26 -2
  93. package/dist/lib/lanes/host-capacity.js +17 -2
  94. package/dist/lib/lanes/host-compute.d.ts +90 -0
  95. package/dist/lib/lanes/host-compute.js +185 -0
  96. package/dist/lib/lanes/index.d.ts +2 -0
  97. package/dist/lib/lanes/index.js +1 -0
  98. package/dist/lib/lanes/reconcile.js +22 -1
  99. package/dist/lib/lanes/resource-usage.d.ts +155 -0
  100. package/dist/lib/lanes/resource-usage.js +589 -0
  101. package/dist/lib/lanes/run-size.d.ts +46 -0
  102. package/dist/lib/lanes/run-size.js +197 -0
  103. package/dist/lib/lanes/store.js +27 -0
  104. package/dist/lib/lanes/throttle.d.ts +36 -1
  105. package/dist/lib/lanes/throttle.js +47 -10
  106. package/dist/lib/lanes/types.d.ts +40 -0
  107. package/dist/lib/lanes/types.js +2 -2
  108. package/dist/lib/lanes/watcher.js +13 -4
  109. package/dist/lib/lanes/worker-process.d.ts +25 -2
  110. package/dist/lib/lanes/worker-process.js +71 -19
  111. package/dist/lib/mesh/live/daemon/config.d.ts +8 -1
  112. package/dist/lib/mesh/live/daemon/config.js +16 -0
  113. package/dist/lib/mesh/live/daemon/install.d.ts +31 -2
  114. package/dist/lib/mesh/live/daemon/install.js +142 -1
  115. package/dist/lib/mesh/live/daemon/login-home.d.ts +5 -0
  116. package/dist/lib/mesh/live/daemon/login-home.js +27 -0
  117. package/dist/lib/mesh/live/daemon/unit-home.d.ts +49 -0
  118. package/dist/lib/mesh/live/daemon/unit-home.js +134 -0
  119. package/dist/lib/placement/match.d.ts +192 -0
  120. package/dist/lib/placement/match.js +667 -0
  121. package/dist/lib/registry/registry.d.ts +35 -7
  122. package/dist/lib/registry/registry.js +88 -13
  123. package/dist/lib/safe-store.d.ts +14 -0
  124. package/dist/lib/safe-store.js +77 -4
  125. package/dist/lib/scan-packages/index.js +24 -2
  126. package/dist/lib/search-index/index.d.ts +88 -4
  127. package/dist/lib/search-index/index.js +288 -24
  128. package/dist/lib/search-index/max-doc-bytes.d.ts +17 -6
  129. package/dist/lib/search-index/max-doc-bytes.js +49 -23
  130. package/dist/lib/service-manager/startup-migration.d.ts +1 -0
  131. package/dist/lib/service-manager/startup-migration.js +3 -0
  132. package/dist/lib/signals/codex-lockdown.d.ts +79 -0
  133. package/dist/lib/signals/codex-lockdown.js +271 -0
  134. package/dist/lib/signals/codex-login.d.ts +37 -0
  135. package/dist/lib/signals/codex-login.js +83 -0
  136. package/dist/lib/signals/engine.d.ts +27 -0
  137. package/dist/lib/signals/engine.js +70 -0
  138. package/dist/lib/signals/reply.js +22 -1
  139. package/dist/lib/signals/run-record.js +6 -1
  140. package/dist/lib/signals/settings.d.ts +5 -0
  141. package/dist/lib/signals/settings.js +2 -0
  142. package/dist/lib/signals/steps/extract.d.ts +85 -9
  143. package/dist/lib/signals/steps/extract.js +317 -68
  144. package/dist/lib/signals/steps/types.d.ts +2 -0
  145. package/dist/lib/sync-core/engine-holds.d.ts +14 -0
  146. package/dist/lib/sync-core/engine-holds.js +60 -0
  147. package/dist/lib/sync-core/engine-home.d.ts +37 -1
  148. package/dist/lib/sync-core/engine-home.js +119 -16
  149. package/dist/lib/sync-core/reconcile.js +8 -0
  150. package/dist/lib/sync-core/rollout-state.d.ts +2 -1
  151. package/dist/lib/sync-core/rollout-state.js +5 -2
  152. package/dist/lib/sync-core/vault-settings.d.ts +21 -0
  153. package/dist/lib/sync-core/vault-settings.js +131 -0
  154. package/dist/lib/sync-core/vault-uid.d.ts +2 -0
  155. package/dist/lib/sync-core/vault-uid.js +4 -0
  156. package/dist/lib/windows/install-followup.d.ts +2 -0
  157. package/dist/lib/windows/install-followup.js +4 -1
  158. package/dist/schemas/hq-work-requirements.v1.schema.json +145 -0
  159. package/dist/utils/auth-session-check.d.ts +16 -0
  160. package/dist/utils/auth-session-check.js +16 -0
  161. package/dist/utils/client-health-contract.d.ts +6 -0
  162. package/dist/utils/client-health-contract.js +13 -0
  163. package/dist/utils/client-health.d.ts +7 -0
  164. package/dist/utils/client-health.js +22 -1
  165. package/dist/utils/command-usage.d.ts +40 -0
  166. package/dist/utils/command-usage.js +61 -0
  167. package/dist/utils/duplicate-command-usage.d.ts +72 -0
  168. package/dist/utils/duplicate-command-usage.js +125 -0
  169. package/dist/utils/host-registration.js +5 -2
  170. package/dist/utils/pack-contributions.d.ts +3 -0
  171. package/dist/utils/pack-contributions.js +110 -23
  172. package/dist/utils/resident-package-preload.js +4 -0
  173. package/dist/utils/self-update.d.ts +3 -1
  174. package/dist/utils/self-update.js +56 -11
  175. package/dist/utils/sentry-fingerprint.js +9 -0
  176. package/dist/utils/update-lock.d.ts +151 -14
  177. package/dist/utils/update-lock.js +782 -46
  178. package/dist/utils/version-gate.js +12 -2
  179. package/dist/utils/windows-bash.d.ts +2 -0
  180. package/dist/utils/windows-bash.js +2 -1
  181. package/package.json +9 -8
  182. package/scripts/bench-core-compare.mjs +313 -0
  183. package/scripts/bench-core.mjs +399 -12
  184. package/scripts/check-function-manifest.mjs +116 -3
@@ -2,6 +2,7 @@ import { accountStatus } from "./accounts.js";
2
2
  import { accountMaxRunning } from "./config.js";
3
3
  import { laneOccupiesRunningSlot, laneRunsOnHost, } from "./admission.js";
4
4
  import { HOST_ALIAS_LIMIT } from "./canonical-host.js";
5
+ import { computeReadingIsStale, parseHostComputeReading, } from "./host-compute.js";
5
6
  import { LanesError } from "./errors.js";
6
7
  import { quotaBlockFor, quotaHitInfo } from "./quota.js";
7
8
  function admissionHost(host) {
@@ -91,6 +92,9 @@ export function buildHostCapacitySnapshot(input) {
91
92
  ...(input.aliases !== undefined ? { host_aliases: [...input.aliases] } : {}),
92
93
  sampled_at: input.now.toISOString(),
93
94
  providers,
95
+ ...(input.compute
96
+ ? { compute: input.compute, compute_stale: computeReadingIsStale(input.compute, input.now) }
97
+ : {}),
94
98
  };
95
99
  }
96
100
  function objectValue(value) {
@@ -109,8 +113,15 @@ function requireCount(value, field, positive = false) {
109
113
  }
110
114
  return value;
111
115
  }
112
- /** Reject malformed remote snapshots before they can influence host selection. */
113
- export function parseHostCapacitySnapshot(raw) {
116
+ /**
117
+ * Reject malformed remote snapshots before they can influence host selection.
118
+ *
119
+ * A compute block that breaks the schema's rules is dropped rather than
120
+ * failing the snapshot: placement does not read it, so it must not make a host
121
+ * unavailable. A kept block is marked stale when the producer said so or when
122
+ * it is past its ttl at `now`.
123
+ */
124
+ export function parseHostCapacitySnapshot(raw, now = new Date()) {
114
125
  const root = objectValue(raw);
115
126
  const hostRaw = objectValue(root?.host);
116
127
  const providersRaw = objectValue(root?.providers);
@@ -193,12 +204,16 @@ export function parseHostCapacitySnapshot(raw) {
193
204
  accounts,
194
205
  };
195
206
  }
207
+ const compute = root.compute === undefined ? null : parseHostComputeReading(root.compute);
196
208
  return {
197
209
  schema_version: "hq-lanes-host-capacity.v1",
198
210
  host: { kind: hostRaw.kind, id: hostRaw.id },
199
211
  ...(hostAliases !== undefined ? { host_aliases: hostAliases } : {}),
200
212
  sampled_at: root.sampled_at,
201
213
  providers,
214
+ ...(compute !== null
215
+ ? { compute, compute_stale: root.compute_stale === true || computeReadingIsStale(compute, now) }
216
+ : {}),
202
217
  };
203
218
  }
204
219
  function parseLaneCounts(value, field) {
@@ -0,0 +1,90 @@
1
+ /**
2
+ * The compute reading in a host capacity snapshot (PS-004): vCPU count, load
3
+ * per vCPU, memory total and available, and disk total and free on the HQ
4
+ * root's filesystem, with observed_at and ttl_seconds.
5
+ *
6
+ * The fields are those of `readings.compute` in hq-environment-profile.v1
7
+ * (src/schemas/hq-environment-profile.v1.schema.json), so a block printed by
8
+ * `hq runners capacity --json` can be copied into a profile unchanged.
9
+ *
10
+ * Every value comes from a sampler lane admission already uses: os.cpus()
11
+ * through ThrottleDeps for the vCPU count, readMemorySignal for available
12
+ * memory (MemAvailable on Linux; on darwin vm_stat free + inactive +
13
+ * speculative pages, the figure the PS-001 profile records, then the
14
+ * memory_pressure sysctls only if vm_stat fails), and measureDiskSpace
15
+ * (statfs) for the disk. This module adds no sampler of its own. Lane
16
+ * admission's memory gate is unchanged and still reads memory_pressure first
17
+ * on darwin.
18
+ *
19
+ * A reading older than its ttl_seconds is stale. A stale reading is still
20
+ * printed, marked stale, and `computeHeadroom` returns null for it, so it is
21
+ * never counted as room on a host.
22
+ */
23
+ import { type StatFs } from "./disk-guard.js";
24
+ import { type ThrottleDeps } from "./throttle.js";
25
+ /** How long a compute reading counts as current. */
26
+ export declare const HOST_COMPUTE_TTL_SECONDS = 60;
27
+ /**
28
+ * The compute block. Field names and types follow `$defs/compute` in the
29
+ * PS-001 schema; that definition allows no other properties, so staleness is
30
+ * carried beside the block (`compute_stale`), not inside it.
31
+ *
32
+ * Units: memory in MiB, disk in GiB (what `df -h` prints as G).
33
+ */
34
+ export interface HostComputeReading {
35
+ observed_at: string;
36
+ ttl_seconds: number;
37
+ source: string;
38
+ vcpu_online: number;
39
+ load_1m: number | null;
40
+ load_per_vcpu: number | null;
41
+ mem_total_mb?: number;
42
+ mem_available_mb: number;
43
+ /** Absent only on a block from another host that left it out. */
44
+ disk_total_gb?: number;
45
+ disk_free_gb: number;
46
+ }
47
+ export type HostComputeDeps = Pick<ThrottleDeps, "cpus" | "readFileSync" | "freemem" | "platform" | "execFileSync" | "loadavg" | "totalmem">;
48
+ /**
49
+ * Read this host's compute block, or null when the vCPU count, available
50
+ * memory or disk cannot be read. Those three are required by the schema; a
51
+ * block without them is not printed at all.
52
+ */
53
+ export declare function readHostCompute(input: {
54
+ deps: HostComputeDeps;
55
+ /** The filesystem to measure: the HQ root, where lane worktrees live. */
56
+ diskPath: string;
57
+ statfs?: StatFs;
58
+ now: Date;
59
+ ttlSeconds?: number;
60
+ }): HostComputeReading | null;
61
+ /**
62
+ * Whether a reading is past its ttl at `now`. A reading whose observed_at
63
+ * cannot be parsed, or lies further in the future than its ttl (a skewed
64
+ * clock), is stale too.
65
+ */
66
+ export declare function computeReadingIsStale(reading: Pick<HostComputeReading, "observed_at" | "ttl_seconds">, now: Date): boolean;
67
+ /** What a current compute reading says is free on a host. */
68
+ export interface HostComputeHeadroom {
69
+ vcpu_online: number;
70
+ load_per_vcpu: number | null;
71
+ mem_available_mb: number;
72
+ disk_free_gb: number;
73
+ }
74
+ /**
75
+ * The room a compute reading reports, or null when there is no reading, the
76
+ * snapshot marked it stale, or it is past its ttl at `now`. A stale reading is
77
+ * never room.
78
+ */
79
+ export declare function computeHeadroom(snapshot: {
80
+ compute?: HostComputeReading;
81
+ compute_stale?: boolean;
82
+ }, now: Date): HostComputeHeadroom | null;
83
+ /**
84
+ * Check a compute block from another host against the rules of the schema's
85
+ * `$defs/compute`, without loading the schema validator on the placement path.
86
+ * `host-compute.test.ts` checks this function and the schema agree. Returns
87
+ * null for a block either would reject.
88
+ */
89
+ export declare function parseHostComputeReading(raw: unknown): HostComputeReading | null;
90
+ //# sourceMappingURL=host-compute.d.ts.map
@@ -0,0 +1,185 @@
1
+ /**
2
+ * The compute reading in a host capacity snapshot (PS-004): vCPU count, load
3
+ * per vCPU, memory total and available, and disk total and free on the HQ
4
+ * root's filesystem, with observed_at and ttl_seconds.
5
+ *
6
+ * The fields are those of `readings.compute` in hq-environment-profile.v1
7
+ * (src/schemas/hq-environment-profile.v1.schema.json), so a block printed by
8
+ * `hq runners capacity --json` can be copied into a profile unchanged.
9
+ *
10
+ * Every value comes from a sampler lane admission already uses: os.cpus()
11
+ * through ThrottleDeps for the vCPU count, readMemorySignal for available
12
+ * memory (MemAvailable on Linux; on darwin vm_stat free + inactive +
13
+ * speculative pages, the figure the PS-001 profile records, then the
14
+ * memory_pressure sysctls only if vm_stat fails), and measureDiskSpace
15
+ * (statfs) for the disk. This module adds no sampler of its own. Lane
16
+ * admission's memory gate is unchanged and still reads memory_pressure first
17
+ * on darwin.
18
+ *
19
+ * A reading older than its ttl_seconds is stale. A stale reading is still
20
+ * printed, marked stale, and `computeHeadroom` returns null for it, so it is
21
+ * never counted as room on a host.
22
+ */
23
+ import * as os from "node:os";
24
+ import { measureDiskSpace } from "./disk-guard.js";
25
+ import { isRfc3339DateTime } from "../environment/rfc3339.js";
26
+ import { readMemorySignal, readMemoryTotal } from "./throttle.js";
27
+ /** How long a compute reading counts as current. */
28
+ export const HOST_COMPUTE_TTL_SECONDS = 60;
29
+ const GIB = 1024 ** 3;
30
+ function round(value, places) {
31
+ const factor = 10 ** places;
32
+ return Math.round(value * factor) / factor;
33
+ }
34
+ /**
35
+ * Read this host's compute block, or null when the vCPU count, available
36
+ * memory or disk cannot be read. Those three are required by the schema; a
37
+ * block without them is not printed at all.
38
+ */
39
+ export function readHostCompute(input) {
40
+ const { deps } = input;
41
+ let vcpu;
42
+ try {
43
+ vcpu = deps.cpus().length;
44
+ }
45
+ catch {
46
+ return null;
47
+ }
48
+ if (!Number.isInteger(vcpu) || vcpu < 1)
49
+ return null;
50
+ const memory = readMemorySignal(deps, { darwinPrimary: "vm_stat" });
51
+ if (memory === null || !Number.isFinite(memory.available_mb) || memory.available_mb < 0)
52
+ return null;
53
+ const total = readMemoryTotal(deps);
54
+ let disk;
55
+ try {
56
+ disk = input.statfs
57
+ ? measureDiskSpace(input.diskPath, input.statfs)
58
+ : measureDiskSpace(input.diskPath);
59
+ }
60
+ catch {
61
+ return null;
62
+ }
63
+ // os.loadavg() is always [0, 0, 0] on Windows, which is not a reading.
64
+ let load1m = null;
65
+ if (deps.platform() !== "win32") {
66
+ try {
67
+ const value = (deps.loadavg ?? os.loadavg)()[0];
68
+ load1m = typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : null;
69
+ }
70
+ catch {
71
+ load1m = null;
72
+ }
73
+ }
74
+ const sources = [
75
+ "os.cpus",
76
+ ...(load1m !== null ? ["os.loadavg"] : []),
77
+ `memory available: ${memory.source}`,
78
+ ...(total !== null ? [`memory total: ${total.source}`] : []),
79
+ "disk: statfs(hq root)",
80
+ ];
81
+ return {
82
+ observed_at: input.now.toISOString(),
83
+ ttl_seconds: input.ttlSeconds ?? HOST_COMPUTE_TTL_SECONDS,
84
+ source: sources.join("; "),
85
+ vcpu_online: vcpu,
86
+ load_1m: load1m === null ? null : round(load1m, 2),
87
+ load_per_vcpu: load1m === null ? null : round(load1m / vcpu, 3),
88
+ ...(total !== null ? { mem_total_mb: Math.round(total.total_mb) } : {}),
89
+ mem_available_mb: Math.floor(memory.available_mb),
90
+ disk_total_gb: round(disk.total_bytes / GIB, 1),
91
+ disk_free_gb: round(disk.free_bytes / GIB, 1),
92
+ };
93
+ }
94
+ /**
95
+ * Whether a reading is past its ttl at `now`. A reading whose observed_at
96
+ * cannot be parsed, or lies further in the future than its ttl (a skewed
97
+ * clock), is stale too.
98
+ */
99
+ export function computeReadingIsStale(reading, now) {
100
+ const observed = Date.parse(reading.observed_at);
101
+ if (!Number.isFinite(observed) || !Number.isInteger(reading.ttl_seconds) || reading.ttl_seconds < 0)
102
+ return true;
103
+ const ttlMs = reading.ttl_seconds * 1000;
104
+ const age = now.getTime() - observed;
105
+ return age > ttlMs || age < -ttlMs;
106
+ }
107
+ /**
108
+ * The room a compute reading reports, or null when there is no reading, the
109
+ * snapshot marked it stale, or it is past its ttl at `now`. A stale reading is
110
+ * never room.
111
+ */
112
+ export function computeHeadroom(snapshot, now) {
113
+ const reading = snapshot.compute;
114
+ if (reading === undefined || snapshot.compute_stale === true || computeReadingIsStale(reading, now))
115
+ return null;
116
+ return {
117
+ vcpu_online: reading.vcpu_online,
118
+ load_per_vcpu: reading.load_per_vcpu,
119
+ mem_available_mb: reading.mem_available_mb,
120
+ disk_free_gb: reading.disk_free_gb,
121
+ };
122
+ }
123
+ const COMPUTE_FIELDS = new Set([
124
+ "observed_at",
125
+ "ttl_seconds",
126
+ "source",
127
+ "vcpu_online",
128
+ "load_1m",
129
+ "load_per_vcpu",
130
+ "mem_total_mb",
131
+ "mem_available_mb",
132
+ "disk_total_gb",
133
+ "disk_free_gb",
134
+ ]);
135
+ function nonNegativeInteger(value) {
136
+ return typeof value === "number" && Number.isInteger(value) && value >= 0;
137
+ }
138
+ function nonNegativeNumber(value) {
139
+ return typeof value === "number" && Number.isFinite(value) && value >= 0;
140
+ }
141
+ function nullableNonNegativeNumber(value) {
142
+ return value === null || nonNegativeNumber(value);
143
+ }
144
+ /**
145
+ * Check a compute block from another host against the rules of the schema's
146
+ * `$defs/compute`, without loading the schema validator on the placement path.
147
+ * `host-compute.test.ts` checks this function and the schema agree. Returns
148
+ * null for a block either would reject.
149
+ */
150
+ export function parseHostComputeReading(raw) {
151
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw))
152
+ return null;
153
+ const value = raw;
154
+ if (Object.keys(value).some((key) => !COMPUTE_FIELDS.has(key)))
155
+ return null;
156
+ if (
157
+ // The schema's date-time rule, so a real calendar date is required. A leap
158
+ // second (:60) passes it but not Date.parse, so computeReadingIsStale
159
+ // reports such a reading stale.
160
+ typeof value.observed_at !== "string" || !isRfc3339DateTime(value.observed_at) ||
161
+ !nonNegativeInteger(value.ttl_seconds) ||
162
+ typeof value.source !== "string" || value.source === "" ||
163
+ !nonNegativeInteger(value.vcpu_online) || value.vcpu_online < 1 ||
164
+ !nonNegativeInteger(value.mem_available_mb) ||
165
+ !nonNegativeNumber(value.disk_free_gb) ||
166
+ (value.load_1m !== undefined && !nullableNonNegativeNumber(value.load_1m)) ||
167
+ (value.load_per_vcpu !== undefined && !nullableNonNegativeNumber(value.load_per_vcpu)) ||
168
+ (value.mem_total_mb !== undefined && !nonNegativeInteger(value.mem_total_mb)) ||
169
+ (value.disk_total_gb !== undefined && !nonNegativeNumber(value.disk_total_gb))) {
170
+ return null;
171
+ }
172
+ return {
173
+ observed_at: value.observed_at,
174
+ ttl_seconds: value.ttl_seconds,
175
+ source: value.source,
176
+ vcpu_online: value.vcpu_online,
177
+ load_1m: value.load_1m ?? null,
178
+ load_per_vcpu: value.load_per_vcpu ?? null,
179
+ ...(value.mem_total_mb !== undefined ? { mem_total_mb: value.mem_total_mb } : {}),
180
+ mem_available_mb: value.mem_available_mb,
181
+ ...(value.disk_total_gb !== undefined ? { disk_total_gb: value.disk_total_gb } : {}),
182
+ disk_free_gb: value.disk_free_gb,
183
+ };
184
+ }
185
+ //# sourceMappingURL=host-compute.js.map
@@ -9,6 +9,8 @@ export { compareLaneQueueOrder, hasActiveAdmissionReservation, hasActivePendingR
9
9
  export type { AdmissionCapReason, AdmissionHost } from "./admission.js";
10
10
  export { buildHostCapacitySnapshot, chooseHostForLane, parseHostCapacitySnapshot, } from "./host-capacity.js";
11
11
  export type { HostCapacityAccount, HostCapacityProvider, HostCapacitySnapshot, HostPlacementChoice, } from "./host-capacity.js";
12
+ export { computeHeadroom, computeReadingIsStale, HOST_COMPUTE_TTL_SECONDS, parseHostComputeReading, readHostCompute, } from "./host-compute.js";
13
+ export type { HostComputeHeadroom, HostComputeReading } from "./host-compute.js";
12
14
  export { CONFIG_SCHEMA_VERSION, ENVELOPE_DECISIONS, ENVELOPE_SCHEMA_VERSION, HISTORY_CAP, HOST_KINDS, LANE_PROVIDERS, LANE_SCHEMA_VERSION, LANE_STORY_STATUSES, LANE_STATES, LIVENESS_STATES, QUESTION_BODY_STORES, QUESTION_SCHEMA_VERSION, QUESTION_STATUSES, QUEUED_REASONS, RAISED_VIA, ROUTING_REASONS, SENIOR_KINDS, STORY_STATUSES, TERMINAL_LANE_STATES, isEnvelopeDecision, isHostKind, isLaneProvider, isLaneState, isLivenessState, isQuestionStatus, isSeniorKind, isTerminalLaneState, parseLaneEnvelope, parseLaneProvider, parseLaneState, parseLivenessState, parseMajorSchema, parseQuestionStatus, parseSeniorKind, } from "./types.js";
13
15
  export type { AccountConfig, AttributionHistoryEntry, EnvelopeDecision, EnvelopeQuestion, HostKind, LaneCompanyRef, LaneAccountSelection, LaneAccountSelectionConsidered, LaneAccountSelectionHostCount, LaneEnvelope, LaneHost, LaneProvider, LanePlacementPolicy, LaneRecord, LaneStory, LaneStoryStatus, PendingResume, AccountHistoryEntry, LaneState, LanesConfig, LastEnvelopeRef, LivenessState, LivenessWindows, ProviderConfig, QuestionAnswer, QuestionBodyRef, QuestionPriority, QuestionRecord, QuestionStatus, QueuedReason, RaisedVia, RoutingHistoryEntry, RoutingReason, SeniorHistoryEntry, SeniorKind, SeniorRef, WorkerProfileRepinHistoryEntry, LaneSettingsHistoryEntry, StoryStatus, TerminalLaneState, ThrottleConfig, } from "./types.js";
14
16
  export { ACTIVE_LANE_STORY_STATUSES, activeLaneStories, laneStories, laneStory, storyKey, storyStatusForEnvelope, storyWarning, withCurrentStory, withLaneStories, } from "./stories.js";
@@ -6,6 +6,7 @@ export { MAX_LANE_DEPTH } from "./constants.js";
6
6
  export { assignedChildHireGrants, childrenHoldingHireGrantCarve, isFinishedResumableHireChild, laneHoldsHireGrantCarve, hireGrantCapacityError, planHireGrantBackfill, terminalChildResumeHireGrantError, withHireGrantAdmission, } from "./grants.js";
7
7
  export { compareLaneQueueOrder, hasActiveAdmissionReservation, hasActivePendingResume, hasEarlierEligibleQueuedLane, laneOccupiesRunningSlot, laneAdmissionCapReason, laneRunsOnHost, withAllLaneAdmissionLocks, withLaneAdmissionLock, } from "./admission.js";
8
8
  export { buildHostCapacitySnapshot, chooseHostForLane, parseHostCapacitySnapshot, } from "./host-capacity.js";
9
+ export { computeHeadroom, computeReadingIsStale, HOST_COMPUTE_TTL_SECONDS, parseHostComputeReading, readHostCompute, } from "./host-compute.js";
9
10
  export { CONFIG_SCHEMA_VERSION, ENVELOPE_DECISIONS, ENVELOPE_SCHEMA_VERSION, HISTORY_CAP, HOST_KINDS, LANE_PROVIDERS, LANE_SCHEMA_VERSION, LANE_STORY_STATUSES, LANE_STATES, LIVENESS_STATES, QUESTION_BODY_STORES, QUESTION_SCHEMA_VERSION, QUESTION_STATUSES, QUEUED_REASONS, RAISED_VIA, ROUTING_REASONS, SENIOR_KINDS, STORY_STATUSES, TERMINAL_LANE_STATES, isEnvelopeDecision, isHostKind, isLaneProvider, isLaneState, isLivenessState, isQuestionStatus, isSeniorKind, isTerminalLaneState, parseLaneEnvelope, parseLaneProvider, parseLaneState, parseLivenessState, parseMajorSchema, parseQuestionStatus, parseSeniorKind, } from "./types.js";
10
11
  export { ACTIVE_LANE_STORY_STATUSES, activeLaneStories, laneStories, laneStory, storyKey, storyStatusForEnvelope, storyWarning, withCurrentStory, withLaneStories, } from "./stories.js";
11
12
  export { DEFAULT_ACCOUNT_HOMES, DEFAULT_AUTO_COMPACT_TOKENS, DEFAULT_COMPACT_AFTER_MS, DEFAULT_LIVE_WITHIN_MS, DEFAULT_LIVENESS_WINDOWS, DEFAULT_MAX_QUEUED, DEFAULT_PROVIDER_MAX_RUNNING, DEFAULT_SILENT_LOST_MS, DEFAULT_TURN_START_LOST_MS, LANES_CONFIG_REL, accountMaxRunning, canonicalizeHome, documentedDefaultConfig, expandHome, lanesConfigPath, loadLanesConfig, parseLanesConfig, providerCompactAfterMs, providerAutoCompactTokens, providerQuotaDefaultHoldMs, DEFAULT_QUOTA_HOLD_MS, writeLanesConfig, } from "./config.js";
@@ -16,6 +16,7 @@ import { enforceRegistryApprovalGate } from "./approval-gate.js";
16
16
  import { inspectLoopRecovery, loopControllerIsAlive, loopLaneIsIdle, loopStatus } from "./loop.js";
17
17
  import { loadLanesConfig, providerQuotaDefaultHoldMs } from "./config.js";
18
18
  import { MAX_LANE_DEPTH } from "./constants.js";
19
+ import { runSizeFields } from "./run-size.js";
19
20
  import { laneDepthCap } from "./depth-cap.js";
20
21
  import { AccountResolutionError, LanesError, isLaneVersionConflict } from "./errors.js";
21
22
  import { isQuestionImported } from "./imported-question.js";
@@ -1814,7 +1815,25 @@ async function heartbeatAndDeadHosts(hqRoot, lanes, summary, deps, now) {
1814
1815
  accountRetryReason &&
1815
1816
  classified.account) {
1816
1817
  try {
1817
- const recovered = await retryLaneOnAlternateAccount(hqRoot, classified, accountRetryReason, "reconcile", {
1818
+ // PS-011: the respawn below deletes worker-exit.json, so this
1819
+ // run's size is recorded first. A run already added is skipped.
1820
+ // A failed measurement write is logged and never stops the failover.
1821
+ let retryLane = classified;
1822
+ try {
1823
+ if (runSizeFields(laneRunDir(hqRoot, classified.lane_id), classified, nowIso).run_size) {
1824
+ retryLane = retryUpdateLane(hqRoot, classified.lane_id, "reconcile", (current) => {
1825
+ const size = runSizeFields(laneRunDir(hqRoot, current.lane_id), current, nowIso);
1826
+ return size.run_size ? { ...current, ...size } : current;
1827
+ });
1828
+ }
1829
+ }
1830
+ catch (sizeErr) {
1831
+ const sizeMessage = sizeErr instanceof Error ? sizeErr.message : String(sizeErr);
1832
+ process.stderr.write(`hq lanes reconcile: run size not recorded before account failover for ${lane.lane_id}: ${sizeMessage}\n`);
1833
+ // The write did not land, so the classified record is still current.
1834
+ retryLane = classified;
1835
+ }
1836
+ const recovered = await retryLaneOnAlternateAccount(hqRoot, retryLane, accountRetryReason, "reconcile", {
1818
1837
  ...spawnDepsForHost(deps),
1819
1838
  });
1820
1839
  summary.dead_host.push({
@@ -1867,6 +1886,8 @@ async function heartbeatAndDeadHosts(hqRoot, lanes, summary, deps, now) {
1867
1886
  : repairedClassification;
1868
1887
  const next = {
1869
1888
  ...current,
1889
+ // PS-011: the worker's exit record is read before a later spawn deletes it.
1890
+ ...runSizeFields(laneRunDir(hqRoot, current.lane_id), current, nowIso),
1870
1891
  state: terminalClassification.state,
1871
1892
  queued_reason: undefined,
1872
1893
  queued_details: undefined,
@@ -0,0 +1,155 @@
1
+ export declare const RESOURCE_SAMPLE_INTERVAL_MS_DEFAULT = 5000;
2
+ export declare const RESOURCE_SAMPLE_INTERVAL_ENV = "HQ_LANE_RESOURCE_SAMPLE_MS";
3
+ /** The longest stop() waits for a sample that is still running before it gives up on it. */
4
+ export declare const RESOURCE_STOP_WAIT_MS = 250;
5
+ /** The Command Line Tools / Xcode python3. /usr/bin/python3 is a stub that can open an install dialog. */
6
+ export declare const DARWIN_PYTHON_CANDIDATES: readonly ["/Library/Developer/CommandLineTools/usr/bin/python3", "/Applications/Xcode.app/Contents/Developer/usr/bin/python3"];
7
+ export type ResourceMethod = "proc" | "ps" | "libproc" | "proc+children" | "ps+libproc" | "none";
8
+ export interface WorkerResourceUsage {
9
+ started_at: string;
10
+ ended_at: string;
11
+ active_seconds: number;
12
+ peak_rss_mb: number | null;
13
+ cpu_seconds: number | null;
14
+ disk_written_mb: number | null;
15
+ samples: number;
16
+ sample_interval_ms: number;
17
+ method: {
18
+ rss: ResourceMethod;
19
+ cpu: ResourceMethod;
20
+ disk: ResourceMethod;
21
+ };
22
+ }
23
+ export interface ProcessSample {
24
+ pid: number;
25
+ ppid: number;
26
+ pgid: number;
27
+ rssBytes: number;
28
+ /** The process's own user + system CPU. */
29
+ cpuSeconds: number;
30
+ /** CPU of the children this process has waited for, when the platform reports it. */
31
+ childCpuSeconds?: number | null;
32
+ diskWrittenBytes: number | null;
33
+ /** True when diskWrittenBytes already includes waited-for children (Linux). */
34
+ diskIncludesChildren?: boolean;
35
+ /**
36
+ * True when the process may have exited and been waited for while the
37
+ * sample was being taken: its parent's reaped-children counters may then
38
+ * already hold it, so it is left out of that sample's inclusive totals.
39
+ */
40
+ inclusiveExcluded?: boolean;
41
+ }
42
+ export type SamplerExecFile = (cmd: string, args: string[], timeoutMs: number, signal: AbortSignal) => Promise<string>;
43
+ export interface ResourceSamplerDeps {
44
+ platform?: NodeJS.Platform;
45
+ readFile?: (p: string) => string;
46
+ readdir?: (p: string) => string[];
47
+ existsSync?: (p: string) => boolean;
48
+ execFile?: SamplerExecFile;
49
+ /** Linux page size in bytes, or null when it cannot be read. */
50
+ pageSize?: () => number | null;
51
+ }
52
+ /** `KernelPageSize: 4 kB` from /proc/self/smaps, in bytes. */
53
+ export declare function parseSmapsPageSize(text: string): number | null;
54
+ /** Linux page size: `getconf PAGESIZE` once, else /proc/self/smaps, cached for the process. */
55
+ export declare function linuxPageSize(run?: () => string, readSmaps?: () => string): number | null;
56
+ /** Test hook: forget the cached page size. */
57
+ export declare function _resetLinuxPageSizeForTests(): void;
58
+ /** `[[DD-]HH:]MM:SS[.cc]` (ps `time` on macOS and Linux) to seconds; null when unreadable. */
59
+ export declare function parsePsCpuTime(value: string): number | null;
60
+ /** Parses `ps -A -o pid=,ppid=,pgid=,rss=,time=` output (rss in KiB). */
61
+ export declare function parsePsSnapshot(text: string): ProcessSample[];
62
+ /** Parses /proc/<pid>/stat: fields after the parenthesised comm. */
63
+ export declare function parseProcStat(text: string, pageSize: number | null): (Omit<ProcessSample, "diskWrittenBytes"> & {
64
+ childCpuSeconds: number;
65
+ rssKnown: boolean;
66
+ starttime: number;
67
+ }) | null;
68
+ /** write_bytes from /proc/<pid>/io, or null. */
69
+ export declare function parseProcIoWriteBytes(text: string): number | null;
70
+ /**
71
+ * The worker's processes: descendants of the wrapper (`rootPid`) plus the
72
+ * members of its process group, without the wrapper itself. When the worker's
73
+ * pid is known, the wrapper's other children (the sampler's own ps and
74
+ * python3) and their descendants are left out.
75
+ */
76
+ export declare function selectTree(all: readonly ProcessSample[], rootPid: number, rootPgid: number | null, workerPid?: number | null): ProcessSample[];
77
+ /**
78
+ * proc_pid_rusage per pid: prints `pid disk_bytes own_cpu_s child_cpu_s`.
79
+ * CPU times are mach absolute time units, converted with mach_timebase_info.
80
+ */
81
+ export declare const DARWIN_RUSAGE_SCRIPT: string;
82
+ export interface DarwinRusage {
83
+ diskBytes: number;
84
+ cpuSeconds: number;
85
+ childCpuSeconds: number;
86
+ }
87
+ /** Parses `pid disk own child` lines from the macOS rusage helper. */
88
+ export declare function parseDarwinRusage(text: string): Map<number, DarwinRusage>;
89
+ /**
90
+ * Accumulates samples of one worker tree. Feed it with `record`; read the
91
+ * totals with `totals`. Kept separate from the I/O so it can be tested with
92
+ * plain arrays.
93
+ */
94
+ export declare class ResourceAccumulator {
95
+ private readonly live;
96
+ private retiredCpu;
97
+ private retiredDisk;
98
+ private sawExclusiveDisk;
99
+ /** Largest per-sample sum of own + reaped-children CPU over live processes. */
100
+ private inclusiveCpu;
101
+ /** Largest per-sample sum of disk counters that already include reaped children. */
102
+ private inclusiveDisk;
103
+ peakRssBytes: number;
104
+ samples: number;
105
+ record(tree: readonly ProcessSample[]): void;
106
+ totals(): {
107
+ peakRssBytes: number;
108
+ cpuSeconds: number;
109
+ diskWrittenBytes: number | null;
110
+ usedChildCpu: boolean;
111
+ };
112
+ }
113
+ /**
114
+ * Samples the process tree under `rootPid` until `stop()` is called, then
115
+ * returns the run's `WorkerResourceUsage`. Sampling never throws: a failed
116
+ * sample is skipped, and a run with no successful sample reports null values.
117
+ */
118
+ export declare class WorkerResourceSampler {
119
+ private readonly rootPid;
120
+ private readonly startedAt;
121
+ private readonly intervalMs;
122
+ private readonly stopWaitMs;
123
+ private readonly deps;
124
+ private readonly acc;
125
+ private readonly abort;
126
+ private timer;
127
+ private inFlight;
128
+ private stopped;
129
+ private rootPgid;
130
+ private workerPid;
131
+ private pythonPath;
132
+ private rssMethod;
133
+ private cpuMethod;
134
+ private diskMethod;
135
+ constructor(rootPid: number, startedAt: Date, intervalMs: number, deps?: ResourceSamplerDeps, stopWaitMs?: number);
136
+ /** The worker process the wrapper started; the wrapper's other children are the sampler's own tools. */
137
+ setWorkerPid(pid: number | undefined): void;
138
+ start(): void;
139
+ /** One sample, skipped while the previous one is still running. */
140
+ tick(): Promise<void>;
141
+ private sample;
142
+ private sampleLinux;
143
+ private samplePs;
144
+ private darwinPython;
145
+ /** Linux only: CPU and disk of the wrapper's waited-for descendants, read from its own /proc entry. */
146
+ private linuxReapedChildren;
147
+ /**
148
+ * Stops sampling and returns the run's usage. Waits at most stopWaitMs for
149
+ * a sample already running; past that the sample's ps or python3 is killed
150
+ * and the totals so far are used.
151
+ */
152
+ stop(endedAt: Date): Promise<WorkerResourceUsage>;
153
+ }
154
+ export declare function resourceSampleIntervalMs(env: NodeJS.ProcessEnv): number;
155
+ //# sourceMappingURL=resource-usage.d.ts.map