@indigoai-us/hq-cli 5.345.219 → 5.345.221

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 (199) hide show
  1. package/CHANGELOG.md +170 -0
  2. package/dist/command-catalog.generated.d.ts +169 -3
  3. package/dist/command-catalog.generated.js +206 -3
  4. package/dist/commands/auth.js +4 -1
  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 +85 -0
  8. package/dist/commands/bot.js +245 -16
  9. package/dist/commands/cloud.d.ts +16 -0
  10. package/dist/commands/cloud.js +112 -102
  11. package/dist/commands/core-checkpoint-native.d.ts +13 -0
  12. package/dist/commands/core-checkpoint-native.js +167 -52
  13. package/dist/commands/core-hook-registration-plan.js +5 -4
  14. package/dist/commands/core-stop-autosave.d.ts +21 -0
  15. package/dist/commands/core-stop-autosave.js +300 -0
  16. package/dist/commands/core.js +2 -0
  17. package/dist/commands/daemon.d.ts +5 -0
  18. package/dist/commands/daemon.js +52 -9
  19. package/dist/commands/doctor-usage.d.ts +5 -0
  20. package/dist/commands/doctor-usage.js +25 -0
  21. package/dist/commands/env.d.ts +49 -4
  22. package/dist/commands/env.js +355 -5
  23. package/dist/commands/integrations.js +84 -3
  24. package/dist/commands/lanes-shared.d.ts +3 -0
  25. package/dist/commands/lanes.d.ts +3 -0
  26. package/dist/commands/lanes.js +87 -3
  27. package/dist/commands/packs.js +23 -0
  28. package/dist/commands/pkg-update.d.ts +6 -0
  29. package/dist/commands/pkg-update.js +15 -7
  30. package/dist/commands/run.js +55 -45
  31. package/dist/commands/sources.js +4 -3
  32. package/dist/commands/sync-core.d.ts +1 -0
  33. package/dist/commands/sync-core.js +77 -3
  34. package/dist/commands/whoami.js +96 -80
  35. package/dist/lib/bot/config.d.ts +17 -0
  36. package/dist/lib/bot/config.js +13 -0
  37. package/dist/lib/bot/fleet-cron.js +29 -4
  38. package/dist/lib/bot/fleet-local.d.ts +30 -2
  39. package/dist/lib/bot/fleet-local.js +60 -1
  40. package/dist/lib/bot/grok-login-scope.d.ts +36 -0
  41. package/dist/lib/bot/grok-login-scope.js +93 -0
  42. package/dist/lib/bot/inflight.d.ts +9 -0
  43. package/dist/lib/bot/jobs/hot-signal-sync.d.ts +51 -0
  44. package/dist/lib/bot/jobs/hot-signal-sync.js +90 -9
  45. package/dist/lib/bot/legacy-provider-login.d.ts +32 -9
  46. package/dist/lib/bot/legacy-provider-login.js +28 -22
  47. package/dist/lib/bot/run.d.ts +29 -5
  48. package/dist/lib/bot/run.js +203 -1
  49. package/dist/lib/bot/runtime-sign-in-check.js +6 -1
  50. package/dist/lib/bot/runtime-sign-in.d.ts +2 -0
  51. package/dist/lib/bot/signals-try-now.d.ts +76 -0
  52. package/dist/lib/bot/signals-try-now.js +111 -0
  53. package/dist/lib/capacity/collectors/claude-oauth.d.ts +22 -3
  54. package/dist/lib/capacity/collectors/claude-oauth.js +78 -22
  55. package/dist/lib/capacity/scheduler.d.ts +8 -0
  56. package/dist/lib/capacity/scheduler.js +5 -2
  57. package/dist/lib/core-utils/sentry-report.js +2 -0
  58. package/dist/lib/daemon/machine-checks.d.ts +22 -1
  59. package/dist/lib/daemon/machine-checks.js +54 -12
  60. package/dist/lib/daemon/run.js +71 -8
  61. package/dist/lib/daemon/runtime-notifications.d.ts +7 -0
  62. package/dist/lib/daemon/runtime-notifications.js +50 -0
  63. package/dist/lib/daemon/stop-autosave-lock.d.ts +19 -0
  64. package/dist/lib/daemon/stop-autosave-lock.js +166 -0
  65. package/dist/lib/daemon/stop-autosave.d.ts +28 -0
  66. package/dist/lib/daemon/stop-autosave.js +111 -0
  67. package/dist/lib/daemon/stop-diagnostics.d.ts +11 -0
  68. package/dist/lib/daemon/stop-diagnostics.js +136 -0
  69. package/dist/lib/daemon/stop-job-executor.d.ts +19 -0
  70. package/dist/lib/daemon/stop-job-executor.js +126 -0
  71. package/dist/lib/daemon/stop-jobs.d.ts +93 -0
  72. package/dist/lib/daemon/stop-jobs.js +599 -0
  73. package/dist/lib/doctor/checks/fleet-hook-core.d.ts +9 -1
  74. package/dist/lib/doctor/checks/fleet-hook-core.js +39 -15
  75. package/dist/lib/doctor/checks/host-core.js +1 -1
  76. package/dist/lib/environment/access-probes.d.ts +234 -0
  77. package/dist/lib/environment/access-probes.js +918 -0
  78. package/dist/lib/environment/profile.d.ts +15 -2
  79. package/dist/lib/environment/profile.js +55 -20
  80. package/dist/lib/environment/rfc3339.d.ts +8 -0
  81. package/dist/lib/environment/rfc3339.js +26 -0
  82. package/dist/lib/environment/work-requirements.d.ts +169 -0
  83. package/dist/lib/environment/work-requirements.js +389 -0
  84. package/dist/lib/hook-engine/coverage.d.ts +137 -7
  85. package/dist/lib/hook-engine/coverage.js +1424 -4
  86. package/dist/lib/hook-engine/fleet-registration.d.ts +17 -5
  87. package/dist/lib/hook-engine/fleet-registration.js +53 -17
  88. package/dist/lib/hook-engine/git-stop-config.json +513 -0
  89. package/dist/lib/hook-engine/native-stop-compatibility.json +311 -0
  90. package/dist/lib/hook-engine/reconcile.js +2 -2
  91. package/dist/lib/hot-channels/alert.d.ts +10 -1
  92. package/dist/lib/hot-channels/alert.js +38 -8
  93. package/dist/lib/hot-channels/signals-claude-login.d.ts +53 -0
  94. package/dist/lib/hot-channels/signals-claude-login.js +96 -0
  95. package/dist/lib/hot-channels/signals-pass.d.ts +143 -17
  96. package/dist/lib/hot-channels/signals-pass.js +324 -17
  97. package/dist/lib/hot-channels/signals-runtime.d.ts +30 -0
  98. package/dist/lib/hot-channels/signals-runtime.js +82 -0
  99. package/dist/lib/install/hook-target.js +1 -1
  100. package/dist/lib/lanes/host-capacity.d.ts +26 -2
  101. package/dist/lib/lanes/host-capacity.js +17 -2
  102. package/dist/lib/lanes/host-compute.d.ts +90 -0
  103. package/dist/lib/lanes/host-compute.js +185 -0
  104. package/dist/lib/lanes/index.d.ts +2 -0
  105. package/dist/lib/lanes/index.js +1 -0
  106. package/dist/lib/lanes/reconcile.js +22 -1
  107. package/dist/lib/lanes/resource-usage.d.ts +155 -0
  108. package/dist/lib/lanes/resource-usage.js +589 -0
  109. package/dist/lib/lanes/run-size.d.ts +46 -0
  110. package/dist/lib/lanes/run-size.js +197 -0
  111. package/dist/lib/lanes/store.js +27 -0
  112. package/dist/lib/lanes/throttle.d.ts +36 -1
  113. package/dist/lib/lanes/throttle.js +47 -10
  114. package/dist/lib/lanes/types.d.ts +40 -0
  115. package/dist/lib/lanes/types.js +2 -2
  116. package/dist/lib/lanes/watcher.js +13 -4
  117. package/dist/lib/lanes/worker-process.d.ts +25 -2
  118. package/dist/lib/lanes/worker-process.js +71 -19
  119. package/dist/lib/placement/match.d.ts +192 -0
  120. package/dist/lib/placement/match.js +667 -0
  121. package/dist/lib/safe-store.d.ts +14 -0
  122. package/dist/lib/safe-store.js +77 -4
  123. package/dist/lib/search-index/index.d.ts +88 -4
  124. package/dist/lib/search-index/index.js +299 -25
  125. package/dist/lib/search-index/max-doc-bytes.d.ts +17 -6
  126. package/dist/lib/search-index/max-doc-bytes.js +48 -23
  127. package/dist/lib/signals/codex-lockdown.d.ts +79 -0
  128. package/dist/lib/signals/codex-lockdown.js +271 -0
  129. package/dist/lib/signals/codex-login.d.ts +37 -0
  130. package/dist/lib/signals/codex-login.js +83 -0
  131. package/dist/lib/signals/engine.d.ts +28 -0
  132. package/dist/lib/signals/engine.js +77 -0
  133. package/dist/lib/signals/reply.d.ts +48 -0
  134. package/dist/lib/signals/reply.js +94 -12
  135. package/dist/lib/signals/run-record.js +6 -1
  136. package/dist/lib/signals/settings.d.ts +5 -0
  137. package/dist/lib/signals/settings.js +2 -0
  138. package/dist/lib/signals/steps/adapters.js +6 -0
  139. package/dist/lib/signals/steps/extract.d.ts +135 -12
  140. package/dist/lib/signals/steps/extract.js +416 -84
  141. package/dist/lib/signals/steps/types.d.ts +21 -0
  142. package/dist/lib/sync-core/engine-home.d.ts +41 -2
  143. package/dist/lib/sync-core/engine-home.js +132 -19
  144. package/dist/lib/sync-core/reconcile.js +1 -1
  145. package/dist/lib/sync-core/release-compare.d.ts +7 -0
  146. package/dist/lib/sync-core/release-compare.js +16 -0
  147. package/dist/lib/sync-core/release.d.ts +2 -1
  148. package/dist/lib/sync-core/release.js +2 -10
  149. package/dist/lib/sync-core/rollout-state.d.ts +2 -1
  150. package/dist/lib/sync-core/rollout-state.js +5 -2
  151. package/dist/lib/sync-core/vault-uid.d.ts +2 -0
  152. package/dist/lib/sync-core/vault-uid.js +4 -0
  153. package/dist/run/schema-env-overrides.d.ts +24 -0
  154. package/dist/run/schema-env-overrides.js +72 -0
  155. package/dist/schemas/hq-work-requirements.v1.schema.json +145 -0
  156. package/dist/utils/auth-session-check.d.ts +16 -0
  157. package/dist/utils/auth-session-check.js +16 -0
  158. package/dist/utils/client-health-contract.d.ts +6 -0
  159. package/dist/utils/client-health-contract.js +13 -0
  160. package/dist/utils/client-health.d.ts +7 -0
  161. package/dist/utils/client-health.js +22 -1
  162. package/dist/utils/command-usage.d.ts +40 -0
  163. package/dist/utils/command-usage.js +61 -0
  164. package/dist/utils/duplicate-command-usage.d.ts +72 -0
  165. package/dist/utils/duplicate-command-usage.js +125 -0
  166. package/dist/utils/host-registration.d.ts +1 -1
  167. package/dist/utils/host-registration.js +6 -1
  168. package/dist/utils/resident-package-preload.js +4 -0
  169. package/dist/utils/sentry-fingerprint.js +9 -0
  170. package/dist/utils/windows-bash.d.ts +2 -0
  171. package/dist/utils/windows-bash.js +2 -1
  172. package/package.json +15 -10
  173. package/scripts/bench-core-compare.mjs +313 -0
  174. package/scripts/bench-core.mjs +399 -12
  175. package/scripts/check-function-manifest.mjs +121 -7
  176. package/dist/commands/__fixtures__/access-vault.d.ts +0 -95
  177. package/dist/commands/__fixtures__/access-vault.js +0 -166
  178. package/dist/commands/__fixtures__/make-tar.d.ts +0 -38
  179. package/dist/commands/__fixtures__/make-tar.js +0 -102
  180. package/dist/commands/secrets-public-types.test-d.d.ts +0 -2
  181. package/dist/commands/secrets-public-types.test-d.js +0 -18
  182. package/dist/lib/decisions/fixtures/us001.d.ts +0 -137
  183. package/dist/lib/decisions/fixtures/us001.js +0 -21
  184. package/dist/lib/doctor/__testing__/fake-hq-tree.d.ts +0 -226
  185. package/dist/lib/doctor/__testing__/fake-hq-tree.js +0 -408
  186. package/dist/lib/doctor/__testing__/run-doctor.d.ts +0 -8
  187. package/dist/lib/doctor/__testing__/run-doctor.js +0 -69
  188. package/dist/lib/fingerprint/fixtures.d.ts +0 -19
  189. package/dist/lib/fingerprint/fixtures.js +0 -61
  190. package/dist/lib/hot-channels/adapters/__fixtures__/dummy.d.ts +0 -33
  191. package/dist/lib/hot-channels/adapters/__fixtures__/dummy.js +0 -53
  192. package/dist/lib/hot-channels/adapters/__fixtures__/meeting-providers.d.ts +0 -38
  193. package/dist/lib/hot-channels/adapters/__fixtures__/meeting-providers.js +0 -64
  194. package/dist/lib/mesh/live/daemon/mqtt-events.test-d.d.ts +0 -2
  195. package/dist/lib/mesh/live/daemon/mqtt-events.test-d.js +0 -10
  196. package/dist/lib/test-utils/isolated-flag-company-context.d.ts +0 -3
  197. package/dist/lib/test-utils/isolated-flag-company-context.js +0 -18
  198. package/scripts/hook-engine-manifest.mjs +0 -22
  199. package/scripts/mesh-daemon-if-stale.mjs +0 -20
@@ -0,0 +1,197 @@
1
+ /**
2
+ * Work size and placement facts on a lane record (PS-011).
3
+ *
4
+ * Each worker run writes `resource_usage` into logs/worker-exit.json
5
+ * (worker-process.ts, resource-usage.ts). When the watcher records the run's
6
+ * end it adds that run to the lane's `run_size`:
7
+ *
8
+ * - active_seconds, cpu_seconds, disk_written_mb: summed over the lane's
9
+ * runs. Time between runs (blocked, waiting on a question, queued) has no
10
+ * worker process and is never counted.
11
+ * - active_seconds_basis: "worker" when active_seconds is worker run time.
12
+ * A Remote Control lane (remote_control: true) keeps its claude process up
13
+ * while it waits for the user, so its run time includes that idle wait; its
14
+ * basis is "wall", and it is left out of the per-repo medians (counted in
15
+ * `wall_clock_lanes_excluded`) rather than mixed in with worker time.
16
+ * - peak_rss_mb: the largest peak of any run.
17
+ * - host_id, engine, account: where and on what the last run ran. host_id is
18
+ * the canonical host id lane placement uses (PS-003): the Outpost marker on
19
+ * an Outpost, else the stable id in ~/.hq/lane-host.json, else the hostname.
20
+ * - repo: the repo the lane works in (work_requirements.needs.repos[0]), so
21
+ * `hq runners list --json` can group sizes per repo.
22
+ *
23
+ * A value is null when no run measured it (an older CLI, a platform without
24
+ * the sampler's tools). A lane record without run_size is valid: records
25
+ * written before PS-011 never carry it.
26
+ */
27
+ import * as fs from "node:fs";
28
+ import * as path from "node:path";
29
+ import { resolveAdmissionHost } from "./admission-host.js";
30
+ const isObj = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
31
+ const nonNegative = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0;
32
+ const numOrNull = (v) => (nonNegative(v) ? v : null);
33
+ const strOrNull = (v) => (typeof v === "string" && v.trim() !== "" ? v : null);
34
+ /** A worker-exit.json `resource_usage` block, or null when absent or malformed. */
35
+ export function parseWorkerResourceUsage(raw) {
36
+ if (!isObj(raw))
37
+ return null;
38
+ if (typeof raw.started_at !== "string" || !Number.isFinite(Date.parse(raw.started_at)))
39
+ return null;
40
+ if (typeof raw.ended_at !== "string" || !Number.isFinite(Date.parse(raw.ended_at)))
41
+ return null;
42
+ if (!nonNegative(raw.active_seconds))
43
+ return null;
44
+ const method = isObj(raw.method) ? raw.method : {};
45
+ return {
46
+ started_at: raw.started_at,
47
+ ended_at: raw.ended_at,
48
+ active_seconds: raw.active_seconds,
49
+ peak_rss_mb: numOrNull(raw.peak_rss_mb),
50
+ cpu_seconds: numOrNull(raw.cpu_seconds),
51
+ disk_written_mb: numOrNull(raw.disk_written_mb),
52
+ samples: nonNegative(raw.samples) ? raw.samples : 0,
53
+ sample_interval_ms: nonNegative(raw.sample_interval_ms) ? raw.sample_interval_ms : 0,
54
+ method: {
55
+ rss: (strOrNull(method.rss) ?? "none"),
56
+ cpu: (strOrNull(method.cpu) ?? "none"),
57
+ disk: (strOrNull(method.disk) ?? "none"),
58
+ },
59
+ };
60
+ }
61
+ /** Reads the last run's resource use from the lane's run dir. */
62
+ export function readWorkerResourceUsage(runDir) {
63
+ try {
64
+ const parsed = JSON.parse(fs.readFileSync(path.join(runDir, "logs", "worker-exit.json"), "utf8"));
65
+ return parseWorkerResourceUsage(parsed.resource_usage);
66
+ }
67
+ catch {
68
+ return null;
69
+ }
70
+ }
71
+ /**
72
+ * A stored run_size, or undefined when it is malformed. Read leniently: a
73
+ * bad size must never make the lane unreadable.
74
+ */
75
+ export function parseLaneRunSize(raw) {
76
+ if (!isObj(raw))
77
+ return undefined;
78
+ if (!nonNegative(raw.active_seconds) || !Number.isSafeInteger(raw.runs) || raw.runs < 0)
79
+ return undefined;
80
+ if (typeof raw.last_run_started_at !== "string" || typeof raw.measured_at !== "string")
81
+ return undefined;
82
+ return {
83
+ active_seconds: raw.active_seconds,
84
+ active_seconds_basis: raw.active_seconds_basis === "wall" ? "wall" : "worker",
85
+ peak_rss_mb: numOrNull(raw.peak_rss_mb),
86
+ cpu_seconds: numOrNull(raw.cpu_seconds),
87
+ disk_written_mb: numOrNull(raw.disk_written_mb),
88
+ host_id: strOrNull(raw.host_id),
89
+ engine: strOrNull(raw.engine),
90
+ account: strOrNull(raw.account),
91
+ repo: strOrNull(raw.repo),
92
+ runs: raw.runs,
93
+ last_run_started_at: raw.last_run_started_at,
94
+ measured_at: raw.measured_at,
95
+ };
96
+ }
97
+ /** The canonical id of the machine this process runs on (PS-003). */
98
+ export function canonicalHostIdHere(deps = {}) {
99
+ try {
100
+ const host = resolveAdmissionHost(deps);
101
+ return strOrNull(host.outpostId) ?? strOrNull(host.machineId) ?? strOrNull(host.hostname.trim());
102
+ }
103
+ catch {
104
+ return null;
105
+ }
106
+ }
107
+ /** The repo the lane works in, from its work requirements. */
108
+ export function laneRepo(lane) {
109
+ const repos = lane.work_requirements?.needs?.repos;
110
+ return Array.isArray(repos) ? strOrNull(repos[0]) : null;
111
+ }
112
+ const add = (a, b, places) => {
113
+ if (a === null && b === null)
114
+ return null;
115
+ const f = 10 ** places;
116
+ return Math.round(((a ?? 0) + (b ?? 0)) * f) / f;
117
+ };
118
+ const max = (a, b) => (a === null ? b : b === null ? a : Math.max(a, b));
119
+ /**
120
+ * The lane's run_size with one more run added, or null when the run was
121
+ * already added (same started_at) or carries no usage.
122
+ */
123
+ export function addRunToSize(lane, usage, input) {
124
+ if (!usage)
125
+ return null;
126
+ const prior = lane.run_size;
127
+ if (prior && prior.last_run_started_at === usage.started_at)
128
+ return null;
129
+ return {
130
+ active_seconds: add(prior?.active_seconds ?? 0, usage.active_seconds, 1) ?? 0,
131
+ active_seconds_basis: lane.remote_control === true || prior?.active_seconds_basis === "wall" ? "wall" : "worker",
132
+ peak_rss_mb: max(prior?.peak_rss_mb ?? null, usage.peak_rss_mb),
133
+ cpu_seconds: add(prior?.cpu_seconds ?? null, usage.cpu_seconds, 2),
134
+ disk_written_mb: add(prior?.disk_written_mb ?? null, usage.disk_written_mb, 2),
135
+ host_id: input.hostId ?? prior?.host_id ?? null,
136
+ engine: lane.provider ?? null,
137
+ account: strOrNull(lane.account) ?? null,
138
+ repo: laneRepo(lane) ?? prior?.repo ?? null,
139
+ runs: (prior?.runs ?? 0) + 1,
140
+ last_run_started_at: usage.started_at,
141
+ measured_at: input.at,
142
+ };
143
+ }
144
+ /** The watcher's patch for a run that just ended: `{ run_size }` or nothing. */
145
+ export function runSizeFields(runDir, lane, at, hostId = () => canonicalHostIdHere()) {
146
+ const usage = readWorkerResourceUsage(runDir);
147
+ if (!usage)
148
+ return {};
149
+ const next = addRunToSize(lane, usage, { hostId: hostId(), at });
150
+ return next ? { run_size: next } : {};
151
+ }
152
+ export function median(values) {
153
+ if (values.length === 0)
154
+ return null;
155
+ const sorted = [...values].sort((a, b) => a - b);
156
+ const mid = Math.floor(sorted.length / 2);
157
+ const value = sorted.length % 2 === 1 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;
158
+ return Math.round(value * 100) / 100;
159
+ }
160
+ /** Key used for lanes whose repo is not known. */
161
+ export const UNKNOWN_REPO = "(unknown)";
162
+ /**
163
+ * Per-repo medians of active_seconds and peak_rss_mb over lanes that carry a
164
+ * run_size. Lanes without one (older records, runs not yet measured) are left
165
+ * out, and so are lanes whose active_seconds is wall time (Remote Control),
166
+ * which are counted in wall_clock_lanes_excluded. Sorted by repo.
167
+ */
168
+ export function runSizeMediansByRepo(lanes) {
169
+ const groups = new Map();
170
+ for (const lane of lanes) {
171
+ const size = lane.run_size;
172
+ if (!size || size.runs < 1)
173
+ continue;
174
+ const repo = size.repo ?? laneRepo(lane) ?? UNKNOWN_REPO;
175
+ const group = groups.get(repo) ?? { active: [], rss: [], lanes: 0, wall: 0 };
176
+ groups.set(repo, group);
177
+ if (size.active_seconds_basis === "wall") {
178
+ group.wall += 1;
179
+ continue;
180
+ }
181
+ group.lanes += 1;
182
+ group.active.push(size.active_seconds);
183
+ if (size.peak_rss_mb !== null)
184
+ group.rss.push(size.peak_rss_mb);
185
+ groups.set(repo, group);
186
+ }
187
+ return [...groups.entries()]
188
+ .sort(([a], [b]) => a.localeCompare(b))
189
+ .map(([repo, g]) => ({
190
+ repo,
191
+ lanes: g.lanes,
192
+ active_seconds_median: median(g.active),
193
+ peak_rss_mb_median: median(g.rss),
194
+ wall_clock_lanes_excluded: g.wall,
195
+ }));
196
+ }
197
+ //# sourceMappingURL=run-size.js.map
@@ -20,6 +20,7 @@ import { LaneNotFoundError, LaneSchemaError, LaneVersionConflict, LanesError, is
20
20
  import { HISTORY_CAP, HOST_KINDS, LANE_STORY_STATUSES, LANE_SCHEMA_VERSION, QUESTION_SCHEMA_VERSION, SENIOR_KINDS, isHostKind, isLaneProvider, isQueuedReason, isLaneState, isQuestionStatus, isSeniorKind, isTerminalLaneState, parseMajorSchema, REQUIRED_LANE_RECORD_FIELDS, LANE_FIELD_WRITERS, LANE_RUNNERS, LANE_WRITERS, } from "./types.js";
21
21
  import { laneStories } from "./stories.js";
22
22
  import { parseLaneOutcomeShape } from "./outcome.js";
23
+ import { parseLaneRunSize } from "./run-size.js";
23
24
  import { laneStoryLedgerEnabled, syncLaneToProjectStoryLedger, validateProjectStories, } from "./story-ledger.js";
24
25
  import { liveOwnerMaxMs, reclaimStaleLock } from "./stale-lock.js";
25
26
  import { HQ_CLI_NPM_UPDATE_COMMAND } from "../../utils/npm-install-flags.js";
@@ -517,6 +518,26 @@ export function parseLaneRecord(raw, filePath) {
517
518
  value: raw.remote_control,
518
519
  });
519
520
  }
521
+ // work_requirements is advisory routing input. A malformed value (null, not
522
+ // an object, or a source without its document) is read as absent so it can
523
+ // never make the whole lane unreadable.
524
+ if (raw.work_requirements !== undefined && !isPlainObject(raw.work_requirements)) {
525
+ delete raw.work_requirements;
526
+ }
527
+ // run_size (PS-011) is a measurement, not state. Records written before it
528
+ // have none; a malformed one is read as absent, never as an unreadable lane.
529
+ if (raw.run_size !== undefined) {
530
+ const runSize = parseLaneRunSize(raw.run_size);
531
+ if (runSize === undefined)
532
+ delete raw.run_size;
533
+ else
534
+ raw.run_size = runSize;
535
+ }
536
+ if (raw.work_requirements_source !== undefined &&
537
+ ((raw.work_requirements_source !== "declared" && raw.work_requirements_source !== "derived") ||
538
+ raw.work_requirements === undefined)) {
539
+ delete raw.work_requirements_source;
540
+ }
520
541
  if (raw.runner !== undefined && raw.runner !== "subagent") {
521
542
  throw new LaneSchemaError(`Unknown lane runner ${JSON.stringify(raw.runner)}. Accepted: ${LANE_RUNNERS.join(", ")}`, {
522
543
  path: filePath,
@@ -1813,6 +1834,12 @@ export function updateLane(hqRoot, laneId, expectedVersion, writer, updater, dep
1813
1834
  if (key === "version" || key === "updated_at" || fieldUnchanged(current[key], updated[key]))
1814
1835
  continue;
1815
1836
  const allowedWriters = LANE_FIELD_WRITERS[key];
1837
+ // A declared requirements document belongs to whoever declared it;
1838
+ // only derived documents may be updated after creation.
1839
+ if ((key === "work_requirements" || key === "work_requirements_source") &&
1840
+ current.work_requirements_source === "declared" && writer !== "creator") {
1841
+ throw new LanesError("lane_writer_unauthorized", `Writer ${writer} cannot change declared lane field ${key}`, { writer, field: key });
1842
+ }
1816
1843
  const transitionClearedBlockedSince = key === "blocked_since" &&
1817
1844
  current.state === "blocked" && updated.state !== "blocked" && updated.blocked_since === undefined;
1818
1845
  // Unknown forward-version fields are preserved, never assigned an
@@ -65,11 +65,24 @@ export interface ThrottleDeps {
65
65
  timeout: number;
66
66
  }) => string;
67
67
  existsSync: (file: string) => boolean;
68
+ /**
69
+ * os.loadavg(). Read by the host compute reading only, not by admission.
70
+ * Absent on deps built before it existed; callers fall back to os.loadavg().
71
+ */
72
+ loadavg?: () => number[];
73
+ /**
74
+ * os.totalmem(): hw.memsize on darwin, sysinfo totalram on Linux. The total
75
+ * memory fallback where /proc/meminfo has no MemTotal. Absent on deps built
76
+ * before it existed; callers fall back to os.totalmem().
77
+ */
78
+ totalmem?: () => number;
68
79
  mkdirSync: typeof fs.mkdirSync;
69
80
  writeFileSync: typeof fs.writeFileSync;
70
81
  renameSync: typeof fs.renameSync;
71
82
  unlinkSync: typeof fs.unlinkSync;
72
83
  }
84
+ /** What the memory readers use from ThrottleDeps. */
85
+ export type MemoryReadDeps = Pick<ThrottleDeps, "readFileSync" | "platform" | "execFileSync" | "freemem" | "totalmem">;
73
86
  export type CpuBusySource = "interval" | "window" | "override";
74
87
  export interface CpuCumulativeSnapshot {
75
88
  idle: number;
@@ -100,6 +113,19 @@ export declare function recordCpuBusyObservation(state: ThrottleState, observati
100
113
  }): ThrottleState;
101
114
  /** Parse MemAvailable kB from /proc/meminfo. */
102
115
  export declare function parseMemAvailableKb(contents: string): number | null;
116
+ /** Parse MemTotal kB from /proc/meminfo. */
117
+ export declare function parseMemTotalKb(contents: string): number | null;
118
+ /** Where a total memory reading came from. */
119
+ export type MemoryTotalSource = "meminfo" | "totalmem";
120
+ /**
121
+ * Installed memory in MiB: MemTotal from /proc/meminfo, else os.totalmem()
122
+ * (hw.memsize on darwin). Read by the host compute reading; admission does not
123
+ * use it. Null when neither gives a positive number.
124
+ */
125
+ export declare function readMemoryTotal(deps?: MemoryReadDeps): {
126
+ source: MemoryTotalSource;
127
+ total_mb: number;
128
+ } | null;
103
129
  /**
104
130
  * Available memory in MiB from darwin `vm_stat`: free + inactive + speculative
105
131
  * pages. Only a fallback when the memory_pressure sysctls cannot be read: it
@@ -136,7 +162,16 @@ export declare function parseMemoryPressureSysctl(contents: string): MemorySigna
136
162
  * MemAvailable is absent. Returning null skips the memory gate instead of
137
163
  * holding every lane.
138
164
  */
139
- export declare function readMemorySignal(deps?: ThrottleDeps): MemorySignal | null;
165
+ export declare function readMemorySignal(deps?: MemoryReadDeps, options?: {
166
+ /**
167
+ * Which darwin reading to try first when /proc/meminfo is absent. Lane
168
+ * admission keeps the default, "memory_pressure". The host compute
169
+ * reading asks for "vm_stat" (free + inactive + speculative pages, the
170
+ * figure hq-environment-profile.v1 records) and falls back to the
171
+ * memory_pressure sysctls only when vm_stat fails.
172
+ */
173
+ darwinPrimary?: "memory_pressure" | "vm_stat";
174
+ }): MemorySignal | null;
140
175
  /** Available memory in MiB from readMemorySignal; null skips the memory gate. */
141
176
  export declare function readAvailableMemMb(deps?: ThrottleDeps): number | null;
142
177
  /** Plain explanation of a memory hold: which signal, its value, and the threshold. */
@@ -74,6 +74,8 @@ export function defaultThrottleDeps(env = process.env) {
74
74
  timeout: options.timeout,
75
75
  }),
76
76
  existsSync: (file) => fs.existsSync(file),
77
+ loadavg: () => os.loadavg(),
78
+ totalmem: () => os.totalmem(),
77
79
  mkdirSync: fs.mkdirSync.bind(fs),
78
80
  writeFileSync: fs.writeFileSync.bind(fs),
79
81
  renameSync: fs.renameSync.bind(fs),
@@ -209,10 +211,10 @@ export function recordCpuBusyObservation(state, observation, options = {}) {
209
211
  : {}),
210
212
  };
211
213
  }
212
- /** Parse MemAvailable kB from /proc/meminfo. */
213
- export function parseMemAvailableKb(contents) {
214
+ function parseMeminfoKb(contents, field) {
215
+ const pattern = new RegExp(`^${field}:\\s+(\\d+)\\s+kB\\s*$`);
214
216
  for (const line of contents.split("\n")) {
215
- const match = /^MemAvailable:\s+(\d+)\s+kB\s*$/.exec(line.trimEnd());
217
+ const match = pattern.exec(line.trimEnd());
216
218
  if (match) {
217
219
  const kb = Number(match[1]);
218
220
  return Number.isFinite(kb) && kb >= 0 ? kb : null;
@@ -220,6 +222,37 @@ export function parseMemAvailableKb(contents) {
220
222
  }
221
223
  return null;
222
224
  }
225
+ /** Parse MemAvailable kB from /proc/meminfo. */
226
+ export function parseMemAvailableKb(contents) {
227
+ return parseMeminfoKb(contents, "MemAvailable");
228
+ }
229
+ /** Parse MemTotal kB from /proc/meminfo. */
230
+ export function parseMemTotalKb(contents) {
231
+ return parseMeminfoKb(contents, "MemTotal");
232
+ }
233
+ /**
234
+ * Installed memory in MiB: MemTotal from /proc/meminfo, else os.totalmem()
235
+ * (hw.memsize on darwin). Read by the host compute reading; admission does not
236
+ * use it. Null when neither gives a positive number.
237
+ */
238
+ export function readMemoryTotal(deps = defaultThrottleDeps()) {
239
+ try {
240
+ const kb = parseMemTotalKb(deps.readFileSync(PROC_MEMINFO, "utf8"));
241
+ if (kb !== null && kb > 0)
242
+ return { source: "meminfo", total_mb: kb / 1024 };
243
+ }
244
+ catch (err) {
245
+ if (err.code !== "ENOENT")
246
+ return null;
247
+ }
248
+ try {
249
+ const bytes = (deps.totalmem ?? os.totalmem)();
250
+ return Number.isFinite(bytes) && bytes > 0 ? { source: "totalmem", total_mb: bytes / (1024 * 1024) } : null;
251
+ }
252
+ catch {
253
+ return null;
254
+ }
255
+ }
223
256
  function parseVmStatPages(contents, label) {
224
257
  const match = new RegExp(`^Pages ${label}:\\s+([0-9.]+)\\s*$`, "m").exec(contents);
225
258
  if (!match)
@@ -274,7 +307,7 @@ export function parseMemoryPressureSysctl(contents) {
274
307
  pressure_level: pressureLevel,
275
308
  };
276
309
  }
277
- function readDarwinMemoryPressure(deps) {
310
+ function readDarwinMemoryPressure(deps, onFailure = "falling back to vm_stat") {
278
311
  try {
279
312
  const contents = deps.execFileSync(SYSCTL_BIN, ["-n", ...MEMORY_PRESSURE_SYSCTLS], {
280
313
  encoding: "utf8",
@@ -283,15 +316,15 @@ function readDarwinMemoryPressure(deps) {
283
316
  const signal = parseMemoryPressureSysctl(contents);
284
317
  if (signal !== null)
285
318
  return signal;
286
- process.stderr.write("lanes throttle: darwin memory_pressure sysctls were unreadable; falling back to vm_stat\n");
319
+ process.stderr.write(`lanes throttle: darwin memory_pressure sysctls were unreadable; ${onFailure}\n`);
287
320
  return null;
288
321
  }
289
322
  catch (err) {
290
- process.stderr.write(`lanes throttle: darwin memory_pressure sysctls failed: ${err instanceof Error ? err.message : String(err)}; falling back to vm_stat\n`);
323
+ process.stderr.write(`lanes throttle: darwin memory_pressure sysctls failed: ${err instanceof Error ? err.message : String(err)}; ${onFailure}\n`);
291
324
  return null;
292
325
  }
293
326
  }
294
- function readDarwinVmStat(deps) {
327
+ function readDarwinVmStat(deps, onFailure = "skipping the memory gate") {
295
328
  try {
296
329
  const contents = deps.execFileSync(VM_STAT_BIN, [], {
297
330
  encoding: "utf8",
@@ -300,11 +333,11 @@ function readDarwinVmStat(deps) {
300
333
  const mb = parseVmStatAvailableMb(contents);
301
334
  if (mb !== null)
302
335
  return { source: "vm_stat", available_mb: mb };
303
- process.stderr.write("lanes throttle: darwin vm_stat output was unreadable; skipping the memory gate\n");
336
+ process.stderr.write(`lanes throttle: darwin vm_stat output was unreadable; ${onFailure}\n`);
304
337
  return null;
305
338
  }
306
339
  catch (err) {
307
- process.stderr.write(`lanes throttle: darwin vm_stat failed: ${err instanceof Error ? err.message : String(err)}; skipping the memory gate\n`);
340
+ process.stderr.write(`lanes throttle: darwin vm_stat failed: ${err instanceof Error ? err.message : String(err)}; ${onFailure}\n`);
308
341
  return null;
309
342
  }
310
343
  }
@@ -328,7 +361,7 @@ function readFreememMb(deps) {
328
361
  * MemAvailable is absent. Returning null skips the memory gate instead of
329
362
  * holding every lane.
330
363
  */
331
- export function readMemorySignal(deps = defaultThrottleDeps()) {
364
+ export function readMemorySignal(deps = defaultThrottleDeps(), options = {}) {
332
365
  try {
333
366
  const contents = deps.readFileSync(PROC_MEMINFO, "utf8");
334
367
  const kb = parseMemAvailableKb(contents);
@@ -344,6 +377,10 @@ export function readMemorySignal(deps = defaultThrottleDeps()) {
344
377
  return null;
345
378
  }
346
379
  if (deps.platform() === "darwin") {
380
+ if (options.darwinPrimary === "vm_stat") {
381
+ return readDarwinVmStat(deps, "falling back to the memory_pressure sysctls") ??
382
+ readDarwinMemoryPressure(deps, "no darwin memory reading");
383
+ }
347
384
  return readDarwinMemoryPressure(deps) ?? readDarwinVmStat(deps);
348
385
  }
349
386
  }
@@ -3,7 +3,31 @@
3
3
  * §4, §5.5, §6.2). Finite sets are string-literal unions plus `const` arrays
4
4
  * so the command layer can validate flags explicitly.
5
5
  */
6
+ import type { WorkRequirements } from "../environment/work-requirements.js";
6
7
  import { type LaneOutcome } from "./outcome.js";
8
+ /**
9
+ * Work size and placement summed over a lane's worker runs (PS-011). Parsed
10
+ * and built in run-size.ts; declared here so this module imports no runtime
11
+ * lane code (the Windows test closure must not reach the lane store).
12
+ */
13
+ export type ActiveSecondsBasis = "worker" | "wall";
14
+ export interface LaneRunSize {
15
+ active_seconds: number;
16
+ /** "wall" for Remote Control lanes, whose worker idles while it waits for the user. */
17
+ active_seconds_basis: ActiveSecondsBasis;
18
+ peak_rss_mb: number | null;
19
+ cpu_seconds: number | null;
20
+ disk_written_mb: number | null;
21
+ host_id: string | null;
22
+ engine: string | null;
23
+ account: string | null;
24
+ repo: string | null;
25
+ /** Worker runs added to the totals. */
26
+ runs: number;
27
+ /** started_at of the last run added; a run is never added twice. */
28
+ last_run_started_at: string;
29
+ measured_at: string;
30
+ }
7
31
  export declare const LANE_SCHEMA_VERSION: "hq-lane.v1";
8
32
  export declare const QUESTION_SCHEMA_VERSION: "hq-lane-question.v1";
9
33
  export declare const ENVELOPE_SCHEMA_VERSION: "hq-lane-envelope.v1";
@@ -816,6 +840,15 @@ export interface LaneRecord {
816
840
  origin_host?: string;
817
841
  /** How `origin_host` was resolved. Required to compare like-with-like. */
818
842
  origin_host_source?: "imds" | "hostname";
843
+ /**
844
+ * hq-work-requirements.v1 document for this lane, written at creation and
845
+ * absent on lanes created before PS-002. A lane created with no declaration
846
+ * carries the derived document (company, engines any, the repo it was
847
+ * created in, on_no_fit conductor-harness).
848
+ */
849
+ work_requirements?: WorkRequirements;
850
+ /** "derived" when work_requirements came from deriveWorkRequirements(). */
851
+ work_requirements_source?: "declared" | "derived";
819
852
  version: number;
820
853
  created_at: string;
821
854
  updated_at: string;
@@ -947,6 +980,13 @@ export interface LaneRecord {
947
980
  last_run_usage?: LaneRunUsage;
948
981
  /** Completion time paired with last_run_usage; written by the watcher. */
949
982
  last_run_usage_at?: string;
983
+ /**
984
+ * Work size and placement facts summed over the lane's worker runs
985
+ * (PS-011, run-size.ts): active, CPU and disk totals, peak memory, and the
986
+ * canonical host, engine and account of the last run. Absent on records
987
+ * written before PS-011 and on lanes with no measured run.
988
+ */
989
+ run_size?: LaneRunSize;
950
990
  /**
951
991
  * Spec §4: one repair turn per expected envelope slot when the final output
952
992
  * is invalid or missing. Written before repair spawn and updated on repair
@@ -266,14 +266,14 @@ export const LANE_FIELD_WRITERS = {
266
266
  pickup_validation_pending_since: ["creator", "command", "spawn", "reconcile"],
267
267
  priority: ["command"], worker: ["creator", "command"], worker_path: ["creator", "command"], worker_pack: ["creator", "command"], worker_profile: ["creator", "command"], worker_profile_hash: ["creator", "command", "spawn"], registry_worker: ["creator", "command", "spawn"], registry_worker_approval_history: ["command", "watcher", "reconcile"], worker_profile_repin_history: ["command"], worker_profile_ignored: ["creator", "command", "spawn"], worker_policy_delivery: ["command", "spawn"],
268
268
  keep_alive: ["creator", "command"], keep_alive_standing: ["command"], keep_alive_opted_in_at: ["creator", "command"], keep_alive_blocked_reason: ["command", "reconcile"], keep_alive_resume_count: ["command", "reconcile", "spawn"], keep_alive_history: ["reconcile"], keep_alive_blocked_resume_streak: ["reconcile", "spawn", "watcher"], keep_alive_last_resume_at: ["command", "reconcile", "spawn"], keep_alive_next_eligible_at: ["command", "reconcile", "spawn"], keep_alive_exhausted_at: ["command", "reconcile", "spawn"], loop_mode: ["creator"],
269
- provider: ["creator", "command"], runner: ["creator"], remote_control: ["creator"], remote_control_title: ["creator"], provider_source: ["creator", "command"], account: ["creator", "spawn", "command", "watcher", "reconcile"], account_source: ["creator", "command"], profile_settings_pinned: ["command"], account_selection: ["creator", "command"], account_pick: ["creator"], admission_accounts: ["creator", "command"], account_history: ["command", "spawn", "watcher", "reconcile"], failed_resume_history: ["command"], fallback_question_cancellation_failures: ["command"], pending_resume: ["command", "spawn", "watcher", "reconcile"], placement_default: ["creator"], host: ["creator", "command"], origin_host: ["creator"], origin_host_source: ["creator"],
269
+ provider: ["creator", "command"], runner: ["creator"], remote_control: ["creator"], remote_control_title: ["creator"], provider_source: ["creator", "command"], account: ["creator", "spawn", "command", "watcher", "reconcile"], account_source: ["creator", "command"], profile_settings_pinned: ["command"], account_selection: ["creator", "command"], account_pick: ["creator"], admission_accounts: ["creator", "command"], account_history: ["command", "spawn", "watcher", "reconcile"], failed_resume_history: ["command"], fallback_question_cancellation_failures: ["command"], pending_resume: ["command", "spawn", "watcher", "reconcile"], placement_default: ["creator"], host: ["creator", "command"], origin_host: ["creator"], origin_host_source: ["creator"], work_requirements: ["creator", "command"], work_requirements_source: ["creator"],
270
270
  version: ["creator"], created_at: ["creator"], updated_at: ["creator"], ended_at: ["reconcile"], envelope_summary: ["reconcile"], attribution_history: ["command", "watcher", "reconcile"], story_switch_pending: ["command", "watcher", "reconcile"], story_switch_unacknowledged: ["command", "watcher", "reconcile"],
271
271
  last_envelope: ["watcher", "reconcile"], model: ["creator", "spawn", "command"], model_source: ["creator", "spawn", "command"], effort: ["creator", "spawn", "command"], effort_source: ["creator", "spawn", "command"], fast_mode: ["spawn"],
272
272
  last_message_at: ["creator", "command"], status_gate: ["spawn", "watcher"], status_gate_history: ["watcher", "reconcile"], blocker_freshness_state: ["watcher"], kr_freshness_state: ["watcher"], last_compaction: ["spawn"], story_complete: ["watcher", "reconcile"], story_complete_reason: ["watcher", "reconcile"], story_status: ["watcher", "reconcile"], outcome: ["watcher", "reconcile"],
273
273
  overdue: ["reconcile"], overdue_at: ["reconcile"], last_host_report_at: ["watcher", "spawn", "reconcile"], stalled: ["watcher"], stalled_at: ["watcher"], stalled_reason: ["watcher"],
274
274
  admitted_reason: ["command", "reconcile"], terminal_reason: ["command", "watcher", "spawn", "reconcile"], stop_history: ["command", "reconcile"], settings_history: ["command"], pending_settings: ["command", "spawn"], interrupted_at: ["command", "watcher", "reconcile", "spawn"], terminal_details: ["command", "spawn", "watcher", "reconcile"],
275
275
  quota_reset_at: ["watcher", "reconcile", "spawn", "command"], model_quota_marker: ["watcher", "reconcile"], outpost_command_id: ["command"],
276
- provider_session_id: ["watcher", "command", "spawn"], provider_session_id_absent: ["watcher", "command"], fingerprint: ["spawn"], provider_home_at_spawn: ["spawn"], working_directory_at_spawn: ["spawn"], last_resume: ["spawn"], resume_history: ["spawn", "watcher"], last_run_usage: ["watcher"], last_run_usage_at: ["watcher"], envelope_repair: ["watcher", "reconcile"], envelope_validation_errors: ["watcher"], last_progress_event_at: ["watcher"],
276
+ provider_session_id: ["watcher", "command", "spawn"], provider_session_id_absent: ["watcher", "command"], fingerprint: ["spawn"], provider_home_at_spawn: ["spawn"], working_directory_at_spawn: ["spawn"], last_resume: ["spawn"], resume_history: ["spawn", "watcher"], last_run_usage: ["watcher"], last_run_usage_at: ["watcher"], run_size: ["watcher", "reconcile"], envelope_repair: ["watcher", "reconcile"], envelope_validation_errors: ["watcher"], last_progress_event_at: ["watcher"],
277
277
  };
278
278
  function isPlainObject(value) {
279
279
  return value !== null && typeof value === "object" && !Array.isArray(value);
@@ -41,6 +41,7 @@ import { isTerminalLaneState, ENVELOPE_INVALID_REASON, parseLaneEnvelope, STORY_
41
41
  import { laneStories, terminalEnvelopeStoryStatus } from "./stories.js";
42
42
  import { applyStorySwitchEnvelope } from "./story-switch.js";
43
43
  import { appendCappedHistory, listQuestionIds, readLane, readQuestion, retryUpdateLane, withLaneHireLocks } from "./store.js";
44
+ import { runSizeFields } from "./run-size.js";
44
45
  import { enforceRegistryApprovalGate } from "./approval-gate.js";
45
46
  import { readWorkerRunResult } from "./delivery.js";
46
47
  import { applyDefaultQuotaHold, clearAccountQuotaAfterSuccessfulTurnBestEffort, quotaSignalFromFields, readQuotaSignal, recordAccountQuota, } from "./quota.js";
@@ -438,8 +439,11 @@ function applyTerminalToLaneWithResult(hqRoot, laneId, classification, opts = {}
438
439
  // A terminal state may have been recorded before the worker's final
439
440
  // report arrived. The report is durable output from work that already
440
441
  // ran, so preserve it without reopening the lane or rechecking admission.
441
- if (opts.envelope === undefined || opts.envelope === null)
442
- return current;
442
+ // The run still ran: add its measured size (PS-011). A run already added is skipped.
443
+ const terminalRunSize = runSizeFields(laneRunDir(hqRoot, current.lane_id), current, at);
444
+ if (opts.envelope === undefined || opts.envelope === null) {
445
+ return terminalRunSize.run_size ? { ...current, ...terminalRunSize } : current;
446
+ }
443
447
  const approvalGate = enforceRegistryApprovalGate(current, opts.envelope);
444
448
  effectiveEnvelope = approvalGate.envelope;
445
449
  effectiveClassification = approvalGate.violation
@@ -449,6 +453,7 @@ function applyTerminalToLaneWithResult(hqRoot, laneId, classification, opts = {}
449
453
  const storySwitch = applyStorySwitchEnvelope(current, envelope, at, envelopeRef);
450
454
  const next = {
451
455
  ...current,
456
+ ...terminalRunSize,
452
457
  last_envelope: {
453
458
  ref: envelopeRef,
454
459
  decision: envelope.decision,
@@ -500,12 +505,16 @@ function applyTerminalToLaneWithResult(hqRoot, laneId, classification, opts = {}
500
505
  return JSON.stringify(next) !== JSON.stringify(current) ? next : current;
501
506
  }
502
507
  if (current.state === "awaiting_input" || current.state === "blocked") {
503
- if (current.state === effectiveClassification.state)
504
- return current;
508
+ if (current.state === effectiveClassification.state) {
509
+ // The state is unchanged, but a worker run still ended: keep its size (PS-011).
510
+ const unchangedRunSize = runSizeFields(laneRunDir(hqRoot, current.lane_id), current, at);
511
+ return unchangedRunSize.run_size ? { ...current, ...unchangedRunSize } : current;
512
+ }
505
513
  }
506
514
  const next = {
507
515
  ...current,
508
516
  ...runResultFields(hqRoot, current, at),
517
+ ...runSizeFields(laneRunDir(hqRoot, current.lane_id), current, at),
509
518
  state: effectiveClassification.state,
510
519
  blocked_since: effectiveClassification.state === "blocked"
511
520
  ? current.state === "blocked" ? current.blocked_since ?? at : at
@@ -1,4 +1,27 @@
1
+ import { type ResourceSamplerDeps, type WorkerResourceUsage } from "./resource-usage.js";
1
2
  export declare const LANE_WORKER_EXIT_PATH_ENV = "HQ_LANE_WORKER_EXIT_PATH";
2
- /** Runs one lane worker process and persists its terminal process status. */
3
- export declare function runLaneWorkerProcess(command: string, args: string[], env?: NodeJS.ProcessEnv, cwd?: string): Promise<number>;
3
+ /**
4
+ * The longest the wrapper waits for resource figures after the worker exits.
5
+ * The sampler gives up on a running sample at RESOURCE_STOP_WAIT_MS; this is
6
+ * the backstop for a sampler that does not return at all.
7
+ */
8
+ export declare const WORKER_USAGE_WAIT_MS: number;
9
+ /** What the wrapper needs from a sampler. WorkerResourceSampler in production. */
10
+ export interface WorkerUsageSampler {
11
+ setWorkerPid(pid: number | undefined): void;
12
+ start(): void;
13
+ stop(endedAt: Date): Promise<WorkerResourceUsage>;
14
+ }
15
+ export interface LaneWorkerProcessOptions {
16
+ now?: () => Date;
17
+ /** Sampling interval; default from HQ_LANE_RESOURCE_SAMPLE_MS, else 5 s. */
18
+ sampleIntervalMs?: number;
19
+ samplerDeps?: ResourceSamplerDeps;
20
+ /** Test hook: replaces the resource sampler. */
21
+ createSampler?: (rootPid: number, startedAt: Date, intervalMs: number) => WorkerUsageSampler;
22
+ /** Test hook: backstop wait for the sampler. Default WORKER_USAGE_WAIT_MS. */
23
+ usageWaitMs?: number;
24
+ }
25
+ /** Runs one lane worker process and persists its terminal process status and resource use. */
26
+ export declare function runLaneWorkerProcess(command: string, args: string[], env?: NodeJS.ProcessEnv, cwd?: string, options?: LaneWorkerProcessOptions): Promise<number>;
4
27
  //# sourceMappingURL=worker-process.d.ts.map