@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
@@ -1,14 +1,31 @@
1
1
  /**
2
2
  * `hq env`: environment profiles (hq-environment-profile.v1).
3
3
  *
4
- * This release has one subcommand, `hq env validate <file>`. It reads one
5
- * file and checks it against the schema. The command itself writes nothing,
6
- * calls no service and needs no sign-in; the CLI's usual start-up state files
7
- * are still written, as for every hq command.
4
+ * `hq env validate <file>` reads one file and checks it against the schema.
5
+ * It writes nothing, calls no service and needs no sign-in; the CLI's usual
6
+ * start-up state files are still written, as for every hq command.
7
+ *
8
+ * `hq env probe` runs access probes by name (vault grant, repo, secret,
9
+ * integration, local data, and optionally `hq agent probe`) and prints them
10
+ * as readings.access entries. A secret is resolved only inside a child of
11
+ * `hq secrets exec`, which checks its length and prints nothing; no value
12
+ * reaches this process. `--write-profile <file>` stores the readings in an
13
+ * existing profile after validating the result.
14
+ *
15
+ * `hq env match --requirements <file> --profiles <dir>` runs the matcher
16
+ * (src/lib/placement/match.ts): it filters the profiles for one piece of work
17
+ * and prints a first ranking, which the conductor engine reads. It is not a
18
+ * placement; the conductor makes and records the choice. It writes nothing,
19
+ * calls no service and needs no sign-in.
8
20
  */
9
- import { readFileSync, statSync } from "node:fs";
21
+ import { randomBytes } from "node:crypto";
22
+ import { chmodSync, lstatSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
23
+ import * as path from "node:path";
10
24
  /** A profile is a few kilobytes; nothing larger than this is read. */
11
25
  export const ENV_VALIDATE_MAX_BYTES = 5 * 1024 * 1024;
26
+ function collect(value, previous = []) {
27
+ return [...previous, ...value.split(",").map((part) => part.trim()).filter(Boolean)];
28
+ }
12
29
  export function registerEnvCommand(program, overrides = {}) {
13
30
  const deps = {
14
31
  print: (line) => console.log(line),
@@ -77,6 +94,339 @@ export function registerEnvCommand(program, overrides = {}) {
77
94
  }
78
95
  deps.setExitCode(1);
79
96
  });
97
+ env
98
+ .command("probe")
99
+ .description("Run access probes by name and print them as hq-environment-profile.v1 readings.access entries: " +
100
+ "company vault grant, repos, secrets (exists by HEAD, and resolvable inside hq secrets exec; the value is never printed or stored), " +
101
+ "integrations and local data (exit 1 when a probe does not pass)")
102
+ .option("--company <slug>", "Company whose vault, secrets and integrations are probed (required)")
103
+ .option("--repo <name>", "Checkout name under repos/private or repos/public; its origin must answer git ls-remote (repeatable, comma-separated)", collect)
104
+ .option("--secret <NAME>", "Secret name to probe: exists, then resolvable by this identity (repeatable, comma-separated)", collect)
105
+ .option("--integration <slug>", "App that must be connected and shared with this identity (repeatable, comma-separated)", collect)
106
+ .option("--data <path>", "Path relative to the HQ root that must be present and not empty (repeatable, comma-separated)", collect)
107
+ .option("--agent", "Also run hq agent probe (identity, vault, presence, DMs); it sends a self-DM and reports to the console")
108
+ .option("--write-profile <file>", "Store the readings in this profile's readings.access, replacing entries with the same names; the profile must validate afterwards")
109
+ .option("--json", "Print the result as JSON")
110
+ .action(async (opts) => {
111
+ const probes = await import("../lib/environment/access-probes.js");
112
+ const { validateEnvironmentAccessProbe, parseEnvironmentProfile } = await import("../lib/environment/profile.js");
113
+ const environment = deps.env ?? process.env;
114
+ const refuse = (code, message, exit = 2) => {
115
+ if (opts.json)
116
+ deps.print(JSON.stringify({ ok: false, code, message, probes: [] }, null, 2));
117
+ else
118
+ deps.printError(message);
119
+ deps.setExitCode(exit);
120
+ };
121
+ if (!opts.company) {
122
+ refuse("invalid_request", "--company <slug> is required");
123
+ return;
124
+ }
125
+ const company = opts.company;
126
+ const request = {
127
+ company,
128
+ repos: opts.repo ?? [],
129
+ secrets: opts.secret ?? [],
130
+ integrations: opts.integration ?? [],
131
+ data: opts.data ?? [],
132
+ agent: Boolean(opts.agent),
133
+ };
134
+ const problems = probes.requestProblems(request);
135
+ if (problems.length > 0) {
136
+ refuse("invalid_request", problems.join("; "));
137
+ return;
138
+ }
139
+ // A session locked to a company set may not probe a company outside it.
140
+ // The session id comes from the caller's environment only, never from
141
+ // the global workspace/sessions/.current fallback. No lock: no check.
142
+ const { sessionIdFromEnv } = await import("../lib/core-utils/session-id.js");
143
+ if (sessionIdFromEnv(environment)) {
144
+ const { readSessionCompanyLock } = await import("../lib/session-company-lock.js");
145
+ let lock;
146
+ try {
147
+ lock = readSessionCompanyLock(environment);
148
+ }
149
+ catch (error) {
150
+ refuse("session_lock_unreadable", error instanceof Error ? error.message : String(error));
151
+ return;
152
+ }
153
+ // Fail closed: a session id with no readable lock (missing or invalid
154
+ // metadata, a missing or symlinked primary folder) is refused, not
155
+ // treated as unlocked. The shared reader is unchanged, so hq secrets
156
+ // exec keeps its own behaviour.
157
+ if (!lock || lock.companies.length === 0) {
158
+ refuse("session_lock_empty", "An HQ session with no company lock cannot run hq env probe. This session has an id but no readable company lock. " +
159
+ `Bind it with core/scripts/hq-session.sh add company ${company}, then run the probe again.`);
160
+ return;
161
+ }
162
+ if (!lock.companies.includes(company)) {
163
+ refuse("outside_session_lock", `Company '${company}' is outside this session's locked company set.`);
164
+ return;
165
+ }
166
+ }
167
+ // hq agent probe runs on this host's agent kit credentials, whatever
168
+ // --company says. A kit enrolled for another company would act as that
169
+ // company (token, vault listing, secret list, DM, console report), so
170
+ // --agent runs only when the kit belongs to the probed company. The
171
+ // other company's name is not printed.
172
+ if (opts.agent) {
173
+ const agentCompany = await (deps.agentCompany ?? (() => probes.agentKitCompany(environment)))();
174
+ if (agentCompany !== company) {
175
+ refuse("agent_company_mismatch", agentCompany
176
+ ? `this host's agent kit is enrolled for a different company, so hq agent probe was not run for ${company}; nothing was probed`
177
+ : `this host has no external agent kit enrolled for ${company}, so --agent cannot run; nothing was probed`);
178
+ return;
179
+ }
180
+ }
181
+ let hqRoot;
182
+ try {
183
+ hqRoot = deps.hqRoot
184
+ ? deps.hqRoot()
185
+ : (await import("../utils/hq-root-resolver.js")).resolveDefaultHqRoot({ env: environment, onMissing: "fallback" });
186
+ }
187
+ catch (error) {
188
+ refuse("no_hq_root", error instanceof Error ? error.message : String(error));
189
+ return;
190
+ }
191
+ // Read the profile before probing, so a bad --write-profile costs no probe.
192
+ // It is read again just before the write (readProfile below).
193
+ const readProfile = (stage) => {
194
+ const file = opts.writeProfile;
195
+ if (probes.pathInOtherCompany(hqRoot, company, file)) {
196
+ refuse("profile_outside_company", `${file} is inside another company's folder; probes for ${company} are not stored there`);
197
+ return null;
198
+ }
199
+ let text;
200
+ let mode;
201
+ try {
202
+ const link = lstatSync(file);
203
+ if (link.isSymbolicLink()) {
204
+ refuse("profile_is_symlink", `${file} is a symlink; hq env probe writes only to a regular profile file`);
205
+ return null;
206
+ }
207
+ if (link.size > ENV_VALIDATE_MAX_BYTES) {
208
+ refuse("too_large", `${file} is too large: ${link.size} bytes`);
209
+ return null;
210
+ }
211
+ mode = link.mode & 0o777;
212
+ text = readFileSync(file, "utf8");
213
+ }
214
+ catch (error) {
215
+ refuse(stage === "before" ? "unreadable" : "write_failed", `cannot read ${file} (${error.code ?? "error"})${stage === "write" ? "; it was not changed" : ""}`);
216
+ return null;
217
+ }
218
+ const parsed = parseEnvironmentProfile(text);
219
+ if (!parsed.ok) {
220
+ refuse("profile_invalid", `${file} is not a valid profile${stage === "before" ? " before probing" : " now; it was not changed"}: ${parsed.message}`, stage === "before" ? 2 : 1);
221
+ return null;
222
+ }
223
+ if (parsed.profile.view.company !== company) {
224
+ refuse("company_mismatch", `${file} is a profile for a different company; probes for ${company} are not stored in it`);
225
+ return null;
226
+ }
227
+ if (parsed.profile.declared.state === "template") {
228
+ refuse("profile_is_template", `${file} is a template profile, which carries no access readings; nothing was ${stage === "before" ? "probed" : "written"}`);
229
+ return null;
230
+ }
231
+ return { text, mode };
232
+ };
233
+ if (opts.writeProfile && !readProfile("before"))
234
+ return;
235
+ const probeDeps = deps.probeDeps ? deps.probeDeps(hqRoot) : probes.defaultAccessProbeDeps(hqRoot, environment);
236
+ // The runner installs the interrupt cleanup around the probes that start children only.
237
+ const report = await probes.runAccessProbes(request, probeDeps);
238
+ const access = report.probes.map(probes.toAccessReading);
239
+ // Every reading is checked against $defs/probe before it is printed or stored.
240
+ const invalid = access.flatMap((reading, index) => validateEnvironmentAccessProbe(reading).map((issue) => `probe ${index}${issue.path}: ${issue.message}`));
241
+ if (invalid.length > 0) {
242
+ refuse("reading_invalid", `a probe reading does not match readings.access: ${invalid.slice(0, 5).join("; ")}`, 1);
243
+ return;
244
+ }
245
+ let written;
246
+ if (opts.writeProfile) {
247
+ // Merge onto the profile as it is now, not as it was before probing.
248
+ const fresh = readProfile("write");
249
+ if (!fresh)
250
+ return;
251
+ const profileText = fresh.text;
252
+ const profileMode = fresh.mode;
253
+ const document = JSON.parse(profileText.charCodeAt(0) === 0xfeff ? profileText.slice(1) : profileText);
254
+ const replaced = new Set(access.flatMap((reading) => probes.supersededNames(reading.name)));
255
+ document.readings.access = [
256
+ ...document.readings.access.filter((reading) => !replaced.has(reading.name)),
257
+ ...access,
258
+ ];
259
+ const text = `${JSON.stringify(document, null, 2)}\n`;
260
+ const after = parseEnvironmentProfile(text);
261
+ if (!after.ok) {
262
+ refuse("profile_invalid", `${opts.writeProfile} would not validate with these readings, so it was not changed: ${after.message}`, 1);
263
+ return;
264
+ }
265
+ // An unpredictable name, created exclusively: a planted file or
266
+ // symlink at the temp path makes the write fail instead of being followed.
267
+ const temporary = path.join(path.dirname(opts.writeProfile), `.${path.basename(opts.writeProfile)}.probe-${randomBytes(12).toString("hex")}.tmp`);
268
+ try {
269
+ writeFileSync(temporary, text, { mode: profileMode, flag: "wx" });
270
+ // The mode given to writeFileSync is narrowed by the umask; set it exactly.
271
+ chmodSync(temporary, profileMode);
272
+ renameSync(temporary, opts.writeProfile);
273
+ }
274
+ catch (error) {
275
+ try {
276
+ rmSync(temporary, { force: true });
277
+ }
278
+ catch { /* nothing to clean */ }
279
+ refuse("write_failed", `could not write ${opts.writeProfile} (${error.code ?? "error"}); it was not changed`);
280
+ return;
281
+ }
282
+ written = opts.writeProfile;
283
+ }
284
+ if (opts.json) {
285
+ deps.print(JSON.stringify({
286
+ ok: report.ok,
287
+ company: report.company,
288
+ observed_at: report.observed_at,
289
+ probes: report.probes,
290
+ readings: { access },
291
+ ...(written ? { written } : {}),
292
+ }, null, 2));
293
+ }
294
+ else {
295
+ for (const entry of report.probes) {
296
+ const tag = entry.ok ? "PASS" : entry.result === "unknown" ? "UNKNOWN" : "FAIL";
297
+ deps.print(`${tag} ${entry.probe} ${entry.test} ${entry.ok ? entry.checks : entry.reason ?? entry.checks}`);
298
+ }
299
+ if (written)
300
+ deps.print(`stored ${access.length} readings in ${written}`);
301
+ }
302
+ deps.setExitCode(report.ok ? 0 : 1);
303
+ });
304
+ env
305
+ .command("match")
306
+ .description("First ranking of environments for one piece of work: rules R1-R9 with one reason per rejection, then scores (read-only; not a placement, the conductor engine chooses)")
307
+ .requiredOption("--requirements <file>", "hq-work-requirements.v1 JSON file")
308
+ .requiredOption("--profiles <dir>", "Directory of hq-environment-profile.v1 JSON files (every *.json in it, not recursive)")
309
+ .option("--now <date-time>", "Match time every reading is aged against (RFC 3339; default: the current time)")
310
+ .option("--json", "Print the result as JSON")
311
+ .action(async (opts) => {
312
+ const result = await runEnvMatch(opts);
313
+ if (!result.ok) {
314
+ if (opts.json)
315
+ deps.print(JSON.stringify({ ok: false, code: result.code, message: result.message, issues: result.issues }, null, 2));
316
+ else {
317
+ deps.printError(result.message);
318
+ for (const issue of result.issues)
319
+ deps.printError(` ${issue}`);
320
+ }
321
+ deps.setExitCode(1);
322
+ return;
323
+ }
324
+ const read = result.profilesRead === 0
325
+ ? `no profiles read from ${opts.profiles}`
326
+ : `${result.profilesRead} profile${result.profilesRead === 1 ? "" : "s"} read from ${opts.profiles}`;
327
+ if (opts.json) {
328
+ // stdout carries the library result unchanged; the count goes to stderr.
329
+ deps.printError(`hq env match: ${read}`);
330
+ deps.print(JSON.stringify(result.match, null, 2));
331
+ return;
332
+ }
333
+ for (const line of formatMatch(result.match, read))
334
+ deps.print(line);
335
+ });
80
336
  return env;
81
337
  }
338
+ function readBounded(file) {
339
+ try {
340
+ const { size } = statSync(file);
341
+ if (size > ENV_VALIDATE_MAX_BYTES) {
342
+ return { ok: false, code: "too_large", message: `${file} is too large: ${size} bytes; hq env match reads files up to ${ENV_VALIDATE_MAX_BYTES} bytes` };
343
+ }
344
+ return { ok: true, text: readFileSync(file, "utf8") };
345
+ }
346
+ catch (error) {
347
+ return { ok: false, code: "unreadable", message: `cannot read ${file} (${error.code ?? "error"})` };
348
+ }
349
+ }
350
+ /**
351
+ * Load the requirements and every profile in the directory, then call the
352
+ * matcher library. All I/O for `hq env match` is here; match() itself reads
353
+ * nothing.
354
+ */
355
+ export async function runEnvMatch(opts) {
356
+ const { parseWorkRequirements } = await import("../lib/environment/work-requirements.js");
357
+ const { parseEnvironmentProfile } = await import("../lib/environment/profile.js");
358
+ const { isRfc3339DateTime } = await import("../lib/environment/rfc3339.js");
359
+ const { match } = await import("../lib/placement/match.js");
360
+ let now = new Date();
361
+ if (opts.now !== undefined) {
362
+ if (!isRfc3339DateTime(opts.now))
363
+ return { ok: false, code: "invalid_now", message: "--now must be an RFC 3339 date-time", issues: [] };
364
+ now = new Date(opts.now);
365
+ }
366
+ const requirementsText = readBounded(opts.requirements);
367
+ if (!requirementsText.ok)
368
+ return { ...requirementsText, issues: [] };
369
+ const requirements = parseWorkRequirements(requirementsText.text);
370
+ if (!requirements.ok) {
371
+ return {
372
+ ok: false,
373
+ code: "invalid_requirements",
374
+ message: `${opts.requirements}: ${requirements.message}`,
375
+ issues: requirements.issues.map((issue) => `${issue.path || "/"}: ${issue.message}`),
376
+ };
377
+ }
378
+ let names;
379
+ try {
380
+ // Dotfiles, including macOS AppleDouble "._name.json" files, are not profiles.
381
+ names = readdirSync(opts.profiles).filter(isProfileFileName).sort();
382
+ }
383
+ catch (error) {
384
+ return { ok: false, code: "unreadable", message: `cannot read ${opts.profiles} (${error.code ?? "error"})`, issues: [] };
385
+ }
386
+ const profiles = [];
387
+ for (const name of names) {
388
+ const file = path.join(opts.profiles, name);
389
+ const text = readBounded(file);
390
+ if (!text.ok)
391
+ return { ...text, issues: [] };
392
+ const parsed = parseEnvironmentProfile(text.text);
393
+ if (!parsed.ok) {
394
+ return {
395
+ ok: false,
396
+ code: "invalid_profile",
397
+ message: `${file}: ${parsed.message}`,
398
+ issues: parsed.issues.map((issue) => `${issue.path || "/"}: ${issue.message}`),
399
+ };
400
+ }
401
+ profiles.push(parsed.profile);
402
+ }
403
+ return { ok: true, match: match(requirements.requirements, profiles, { now }), profilesRead: profiles.length };
404
+ }
405
+ /** A profile file: *.json, not a dotfile (which covers AppleDouble "._*" files). */
406
+ export function isProfileFileName(name) {
407
+ return name.endsWith(".json") && !name.startsWith(".");
408
+ }
409
+ function formatMatch(result, read) {
410
+ const lines = [
411
+ `${result.notice}`,
412
+ `work ${result.work_id} (company ${result.company}), readings aged at ${result.now}; ${read}`,
413
+ "",
414
+ result.ranked.length === 0 ? "No feasible pair." : "Ranked pairs:",
415
+ ];
416
+ for (const pair of result.ranked) {
417
+ const login = pair.account_id === null ? `${pair.engine} (template, login injected at start)` : `${pair.engine} ${pair.account_id}`;
418
+ const owner = pair.owning_company === null ? "" : `, owning company ${pair.owning_company}`;
419
+ lines.push(` ${pair.rank}. ${pair.score.toFixed(2)} ${pair.environment_id} ${login}${owner}, room ${pair.room.basis}`);
420
+ }
421
+ if (result.rejected.length > 0) {
422
+ lines.push("", "Rejected:");
423
+ for (const entry of result.rejected) {
424
+ const subject = entry.subject === "environment"
425
+ ? entry.environment_id
426
+ : `${entry.environment_id} ${entry.engine} ${entry.account_id ?? `(held by ${entry.holder})`}`;
427
+ lines.push(` ${subject}: ${entry.reason.rule} ${entry.reason.field}: ${entry.reason.detail}`);
428
+ }
429
+ }
430
+ return lines;
431
+ }
82
432
  //# sourceMappingURL=env.js.map
@@ -20,6 +20,7 @@ import type { SessionCopyResult } from "../lib/lanes/move-account.js";
20
20
  import type { WorkerProfile } from "../lib/lanes/profile.js";
21
21
  import type { OutpostHireGrantContext } from "../lib/lanes/hire-grant-dispatch.js";
22
22
  import { LanesError } from "../lib/lanes/errors.js";
23
+ import type { deriveWorkRequirements } from "../lib/environment/work-requirements.js";
23
24
  export type { LaneCompanyRef, LaneRecord } from "../lib/lanes/index.js";
24
25
  export interface LaneAccountMove {
25
26
  lane: LaneRecord;
@@ -343,6 +344,8 @@ export interface Ctx {
343
344
  }) => Promise<boolean>;
344
345
  /** Test seam for the default-off project focus guard flag. */
345
346
  focusGuardEnabled?: (company?: LaneCompanyRef) => Promise<boolean>;
347
+ /** Test seam for the hq-work-requirements.v1 derivation run by lane create. */
348
+ deriveWorkRequirements?: typeof deriveWorkRequirements;
346
349
  storyLedgerEnabled: () => boolean;
347
350
  isSsmOwnerDispatch: () => boolean;
348
351
  withGrantHireLocks: typeof withLaneHireLocks;
@@ -12,6 +12,7 @@ export type { OutpostIdentity } from "../lib/lanes/admission-host.js";
12
12
  import { type OutpostDispatchResult } from "../lib/lanes/outpost-dispatch.js";
13
13
  import { emitLaneDecisionEvents } from "../lib/lanes/mesh-events.js";
14
14
  import { MAX_LANE_DEPTH, withLaneAdmissionLock, withLaneHireLocks, type LaneCompanyRef, type QuestionBody, type LaneRecord, type QuestionRecord, type ResolvedLaneWorker, type SeniorRef, type LivenessDeps, type MachineIdentity, type MonitorEvidenceReader, type RunCommand, type ThrottleDeps } from "../lib/lanes/index.js";
15
+ import { deriveWorkRequirements } from "../lib/environment/work-requirements.js";
15
16
  import { questionBodyAbsPath } from "../lib/lanes/questions.js";
16
17
  import { type RunCompactionFn } from "../lib/lanes/compaction.js";
17
18
  import { type ResolvedEffort } from "../lib/lanes/effort.js";
@@ -116,6 +117,8 @@ export interface LanesCommandDeps {
116
117
  storyLedgerEnabled?: () => boolean;
117
118
  /** Test seam for the default-off focus guard flag. */
118
119
  focusGuardEnabled?: (company?: LaneCompanyRef) => Promise<boolean>;
120
+ /** Test seam for the hq-work-requirements.v1 derivation run by lane create. */
121
+ deriveWorkRequirements?: typeof deriveWorkRequirements;
119
122
  /** Test seam for the SSM-only Outpost owner grant path. */
120
123
  isSsmOwnerDispatch?: () => boolean;
121
124
  /** Test seam for changing a lane between pre-lock and locked grant reads. */
@@ -67,7 +67,9 @@ export { OUTPOST_DIR, OUTPOST_ID_PATH, readOutpostIdentity } from "../lib/lanes/
67
67
  import { buildOutpostCapacityCommand, buildOutpostIdentityBackfillCommand, buildOutpostLaneCommand, buildOutpostQuestionListCommand, buildOutpostPickupCommand, createOutpostsClient, dispatchErrorMessage, dispatchOutpostPickup, buildOutpostLaneListCommand, buildOutpostLegacyLaneUlidListCommand, REMOTE_LANE_READ_ENV, outpostRejectedEffortOption, parseOutpostPickupPayload, PICKUP_WAIT_MS, stageOutpostPayload, } from "../lib/lanes/outpost-dispatch.js";
68
68
  import { outpostHireSummaryCacheKey, OUTPOST_HIRE_SUMMARY_CACHE_TTL_MS, readOutpostHireSummaryCache, readOutpostHireSummaryCacheIncludingStale, writeOutpostHireSummaryCache, } from "../lib/lanes/outpost-hire-cache.js";
69
69
  import { buildHostCapacitySnapshot, chooseHostForLane, hostCapacitySnapshotToWire, parseHostCapacitySnapshot, } from "../lib/lanes/host-capacity.js";
70
+ import { readHostCompute } from "../lib/lanes/host-compute.js";
70
71
  import { resolveCanonicalHost } from "../lib/lanes/canonical-host.js";
72
+ import { parseLaneRunSize, runSizeMediansByRepo } from "../lib/lanes/run-size.js";
71
73
  import { readInstanceIdFromDisk } from "../lib/lanes/machine-identity.js";
72
74
  import { BALANCE_MOVABLE_STATES, selectClaudeAccount, } from "../lib/lanes/claude-balance.js";
73
75
  import { parseUserYaml } from "../utils/user-yaml-error.js";
@@ -84,11 +86,12 @@ import { applyLoopDisposition, loopDispositionSnapshot } from "../lib/lanes/loop
84
86
  import { listLaneReviews } from "../lib/lanes/reviews.js";
85
87
  import { effectiveAccountHome } from "../lib/lanes/account-home.js";
86
88
  import { remoteControlSelectionConfig, remoteControlSessionHome } from "../lib/lanes/remote-control-lane.js";
87
- import { AccountResolutionError, compareLaneQueueOrder, LANE_PROVIDERS, LANE_STATES, QUESTION_STATUSES, SENIOR_KINDS, accountStatus, appendCappedHistory, canonicalizeHome, createLane, decideAdmission, defaultLivenessDeps, defaultSystemdUserDir, defaultThrottleDeps, installReconcileTimer, providerPathEnv, probeDrainHookRegistration, isLanesError, isLaneVersionConflict, isTerminalLaneState, isFinishedResumableHireChild, childrenHoldingHireGrantCarve, laneHoldsHireGrantCarve, assignedChildHireGrants, hireGrantCapacityError, planHireGrantBackfill, terminalChildResumeHireGrantError, withHireGrantAdmission, laneStoryLedgerEnabled, syncLaneToProjectStoryLedger, removeLaneFromProjectStoryLedger, validateProjectStories, buildLaneStatusSnapshot, formatLaneStatusHuman, expandLocalLaneIdPrefix, listLaneIds, listQuestionIds, loadLanesConfig, laneRunsHere, MAX_LANE_DEPTH, MONITOR_ERROR_EXIT_CODE, readLiveMonitorEvidence, resolveMachineIdentity as lookupMachineIdentity, loadLivenessIndex, parseLaneProvider, isLaneProvider, parseLaneRecord, parseLaneState, parseQuestionRecord, parseSeniorKind, readAllLanes, readLane, sanitizeHostComponent, retryUpdateLane, syncLaneRecordFromOwner, readQuestion, resolveAccount, resolveLaneWorker, ignoredWorkerProfileFields, loadWorkerProfile, loadWorkerProfileWithRegistry, registryWorkerRecord, runReconcilePass, DEAD_HOST_MS, sessionLiveness, tryReadLane, uninstallReconcileTimer, updateLane, updateQuestion, dropboxDir, laneDeliveryMechanism, hasActiveAdmissionReservation, hasActivePendingResume, hasRecordedSessionId, hasEarlierEligibleQueuedLane, laneAdmissionCapReason, providerSupportsSessionResume, providerSessionPortable, isFailedQuotaKeepAliveLane, sessionNotPortableMessage, withLaneAdmissionLock, withAllLaneAdmissionLocks, readWorkerRunResult, resumeCommandRefusal, withLaneHireLocks, raiseLaneQuestion, sha256Text, } from "../lib/lanes/index.js";
89
+ import { AccountResolutionError, compareLaneQueueOrder, LANE_PROVIDERS, LANE_STATES, QUESTION_STATUSES, SENIOR_KINDS, accountStatus, appendCappedHistory, canonicalizeHome, createLane, mintLaneId, decideAdmission, defaultLivenessDeps, defaultSystemdUserDir, defaultThrottleDeps, installReconcileTimer, providerPathEnv, probeDrainHookRegistration, isLanesError, isLaneVersionConflict, isTerminalLaneState, isFinishedResumableHireChild, childrenHoldingHireGrantCarve, laneHoldsHireGrantCarve, assignedChildHireGrants, hireGrantCapacityError, planHireGrantBackfill, terminalChildResumeHireGrantError, withHireGrantAdmission, laneStoryLedgerEnabled, syncLaneToProjectStoryLedger, removeLaneFromProjectStoryLedger, validateProjectStories, buildLaneStatusSnapshot, formatLaneStatusHuman, expandLocalLaneIdPrefix, listLaneIds, listQuestionIds, loadLanesConfig, laneRunsHere, MAX_LANE_DEPTH, MONITOR_ERROR_EXIT_CODE, readLiveMonitorEvidence, resolveMachineIdentity as lookupMachineIdentity, loadLivenessIndex, parseLaneProvider, isLaneProvider, parseLaneRecord, parseLaneState, parseQuestionRecord, parseSeniorKind, readAllLanes, readLane, sanitizeHostComponent, retryUpdateLane, syncLaneRecordFromOwner, readQuestion, resolveAccount, resolveLaneWorker, ignoredWorkerProfileFields, loadWorkerProfile, loadWorkerProfileWithRegistry, registryWorkerRecord, runReconcilePass, DEAD_HOST_MS, sessionLiveness, tryReadLane, uninstallReconcileTimer, updateLane, updateQuestion, dropboxDir, laneDeliveryMechanism, hasActiveAdmissionReservation, hasActivePendingResume, hasRecordedSessionId, hasEarlierEligibleQueuedLane, laneAdmissionCapReason, providerSupportsSessionResume, providerSessionPortable, isFailedQuotaKeepAliveLane, sessionNotPortableMessage, withLaneAdmissionLock, withAllLaneAdmissionLocks, readWorkerRunResult, resumeCommandRefusal, withLaneHireLocks, raiseLaneQuestion, sha256Text, } from "../lib/lanes/index.js";
88
90
  import { admitQueuedNow } from "../lib/lanes/reconcile.js";
89
91
  import { laneStories, storyWarning, } from "../lib/lanes/stories.js";
90
92
  import { resolveLaneKeepAlive } from "../lib/lanes/profile.js";
91
93
  import { laneCompanyUidSource, resolveLaneCompany } from "../lib/lanes/lane-company.js";
94
+ import { deriveWorkRequirements, withRepairedCompany } from "../lib/environment/work-requirements.js";
92
95
  import { doneKeepAliveVerdict, hasPendingKeepAliveWork, keepAliveNextCheckAtMs, keepAliveExclusion, keepAliveSupersededBy, loadRetiredLaneEntries, matchesRetiredLaneEntry, LANE_SUPERSESSION_LINEAGE_AWARE_FLAG, loadRetiredLaneIds, } from "../lib/lanes/keep-alive.js";
93
96
  import { questionBodyAbsPath, resolveQuestionCompanyWithFallback, resolveProjectQuestionCompany, } from "../lib/lanes/questions.js";
94
97
  import { assertQuestionBodySecretSafe } from "../lib/lanes/questions.js";
@@ -422,6 +425,49 @@ function defaultSleep(ms) {
422
425
  function resolveCallerPath(callerCwd, filePath) {
423
426
  return path.resolve(callerCwd, filePath);
424
427
  }
428
+ /**
429
+ * hq-work-requirements.v1 for a lane created with no declaration (PS-002):
430
+ * the lane's company as resolveLaneCompany resolves it (company, mesh
431
+ * company, project company), else the caller's session lock, engines any,
432
+ * the repo the caller is in, on_no_fit conductor-harness.
433
+ *
434
+ * The derivation never breaks lane create: on any failure the lane is
435
+ * created without work_requirements and a warning is written to stderr.
436
+ */
437
+ function derivedLaneWorkRequirements(ctx, hqRoot, lane) {
438
+ try {
439
+ const resolved = resolveLaneCompany(hqRoot, lane);
440
+ const derive = ctx.deriveWorkRequirements ?? deriveWorkRequirements;
441
+ return {
442
+ work_requirements: derive({
443
+ hqRoot,
444
+ cwd: ctx.callerCwd(),
445
+ env: ctx.env,
446
+ origin: { kind: "lane", ref: lane.lane_id },
447
+ company: resolved.company?.slug ?? null,
448
+ }),
449
+ work_requirements_source: "derived",
450
+ };
451
+ }
452
+ catch (error) {
453
+ process.stderr.write(`${JSON.stringify({
454
+ event: "lanes.work_requirements.derive_failed",
455
+ lane_id: lane.lane_id,
456
+ error: error instanceof Error ? error.name : "UnknownError",
457
+ action: "lane created without work_requirements",
458
+ })}\n`);
459
+ return {};
460
+ }
461
+ }
462
+ /**
463
+ * The derived requirements after hq lanes repair-company sets the lane's
464
+ * company. A declared document is left as it is.
465
+ */
466
+ function repairedWorkRequirements(current, company) {
467
+ if (current.work_requirements_source !== "derived" || !current.work_requirements)
468
+ return {};
469
+ return { work_requirements: withRepairedCompany(current.work_requirements, company.slug) };
470
+ }
425
471
  function resolveDeps(deps = {}) {
426
472
  const env = deps.env ?? process.env;
427
473
  const cwd = deps.cwd ?? (() => process.cwd());
@@ -511,6 +557,7 @@ function resolveDeps(deps = {}) {
511
557
  lanePlacementEnabled: deps.lanePlacementEnabled ?? defaultLanePlacementEnabled,
512
558
  storyLedgerEnabled: deps.storyLedgerEnabled ?? laneStoryLedgerEnabled,
513
559
  focusGuardEnabled: deps.focusGuardEnabled,
560
+ deriveWorkRequirements: deps.deriveWorkRequirements,
514
561
  isSsmOwnerDispatch: deps.isSsmOwnerDispatch ?? (() => isSsmRunCommandProcess()),
515
562
  withGrantHireLocks: deps.withGrantHireLocks ?? withLaneHireLocks,
516
563
  withAdmissionLock: deps.withAdmissionLock ?? withLaneAdmissionLock,
@@ -1600,7 +1647,7 @@ async function readOutpostCapacityUncached(ctx, outpostId, waitMs = CAPACITY_PRO
1600
1647
  catch (err) {
1601
1648
  throw new LanesError("outpost_capacity_unavailable", `Outpost ${outpostId} returned invalid capacity JSON: ${dispatchErrorMessage(err)}`, { outpost_id: outpostId });
1602
1649
  }
1603
- const snapshot = parseHostCapacitySnapshot(raw);
1650
+ const snapshot = parseHostCapacitySnapshot(raw, ctx.now());
1604
1651
  if (snapshot.host.kind !== "outpost" || snapshot.host.id !== outpostId) {
1605
1652
  throw new LanesError("outpost_capacity_identity_mismatch", `Capacity response from Outpost ${outpostId} identified a different host`, { requested_outpost_id: outpostId, reported_host: snapshot.host });
1606
1653
  }
@@ -2000,6 +2047,7 @@ async function refreshRemoteLaneMirrors(ctx, hqRoot, records, parentLaneIds, opt
2000
2047
  const envelopeSummary = isTerminalLaneState(owner.state)
2001
2048
  ? owner.envelope_summary
2002
2049
  : undefined;
2050
+ const ownerRunSize = parseLaneRunSize(owner.run_size);
2003
2051
  const before = readLane(hqRoot, mirror.lane_id);
2004
2052
  if (before.host.kind !== "outpost" || before.host.id !== outpostId ||
2005
2053
  !originMatchesThisHost(before) ||
@@ -2031,7 +2079,10 @@ async function refreshRemoteLaneMirrors(ctx, hqRoot, records, parentLaneIds, opt
2031
2079
  before.story_complete !== owner.story_complete ||
2032
2080
  before.story_complete_reason !== owner.story_complete_reason ||
2033
2081
  before.story_status !== owner.story_status ||
2034
- before.terminal_reason !== owner.terminal_reason));
2082
+ before.terminal_reason !== owner.terminal_reason ||
2083
+ // A missing or malformed owner size never forces a rewrite: the
2084
+ // update below keeps the mirror's size in that case.
2085
+ (ownerRunSize !== undefined && JSON.stringify(before.run_size) !== JSON.stringify(ownerRunSize))));
2035
2086
  if (!needsUpdate) {
2036
2087
  result.updated.set(mirror.lane_id, before);
2037
2088
  continue;
@@ -2063,6 +2114,8 @@ async function refreshRemoteLaneMirrors(ctx, hqRoot, records, parentLaneIds, opt
2063
2114
  story_status: owner.story_status,
2064
2115
  terminal_reason: owner.terminal_reason,
2065
2116
  terminal_details: owner.terminal_details,
2117
+ // PS-011: the owner host measured the runs; the mirror keeps its size.
2118
+ ...(ownerRunSize !== undefined ? { run_size: ownerRunSize } : {}),
2066
2119
  } : {}),
2067
2120
  };
2068
2121
  });
@@ -4536,7 +4589,10 @@ async function runCreate(ctx, opts) {
4536
4589
  }
4537
4590
  const queuedReason = admission.action === "queue" ? admission.reason : undefined;
4538
4591
  const admissionReservedAt = admission.action === "start" ? ctx.now().toISOString() : undefined;
4592
+ // Minted here, as createLane would, so the derived requirements can name the lane.
4593
+ const laneId = mintLaneId();
4539
4594
  const laneInit = {
4595
+ lane_id: laneId,
4540
4596
  company,
4541
4597
  ...(opts.signalMetadata ? { signal: opts.signalMetadata, signal_link: opts.signalLink } : {}),
4542
4598
  ...(company === null && meshCompany
@@ -4632,6 +4688,12 @@ async function runCreate(ctx, opts) {
4632
4688
  ...(originHostSource !== undefined
4633
4689
  ? { origin_host_source: originHostSource }
4634
4690
  : {}),
4691
+ ...derivedLaneWorkRequirements(ctx, hqRoot, {
4692
+ lane_id: laneId,
4693
+ company,
4694
+ mesh_company: company === null && meshCompany ? meshCompany : undefined,
4695
+ project_id: project,
4696
+ }),
4635
4697
  attribution_history: [],
4636
4698
  };
4637
4699
  if (senior.kind === "lane" && senior.id) {
@@ -6410,6 +6472,7 @@ async function runList(ctx, opts) {
6410
6472
  ? (await loadHostCapacitySnapshots(ctx, hqRoot, undefined, allLanes)).entries
6411
6473
  .map((entry) => "schema_version" in entry ? hostCapacitySnapshotToWire(entry) : entry)
6412
6474
  : undefined;
6475
+ const runSizeByRepo = runSizeMediansByRepo(selectedLanes);
6413
6476
  const result = {
6414
6477
  ok: true,
6415
6478
  action: "list",
@@ -6418,6 +6481,8 @@ async function runList(ctx, opts) {
6418
6481
  ? { unverified_remote_lanes: [...remoteRefresh.unverifiedRemote.keys()] }
6419
6482
  : {}),
6420
6483
  ...(host_capacity !== undefined ? { host_capacity } : {}),
6484
+ // PS-011: per-repo medians over the listed lanes that carry a run_size.
6485
+ ...(runSizeByRepo.length > 0 ? { run_size_by_repo: runSizeByRepo } : {}),
6421
6486
  };
6422
6487
  if (opts.human)
6423
6488
  console.log(formatLaneListHuman(lanes));
@@ -6571,6 +6636,14 @@ async function runCapacity(ctx) {
6571
6636
  hostname,
6572
6637
  now,
6573
6638
  quotaState: loadQuotaState(hqRoot),
6639
+ // Read only, like the rest of this command: os.cpus, loadavg, the memory
6640
+ // gate's reading and statfs on the HQ root.
6641
+ compute: readHostCompute({
6642
+ deps: ctx.throttleDeps,
6643
+ diskPath: hqRoot,
6644
+ ...(ctx.statfs !== undefined ? { statfs: ctx.statfs } : {}),
6645
+ now,
6646
+ }),
6574
6647
  });
6575
6648
  printJson({
6576
6649
  ...hostCapacitySnapshotToWire(snapshot),
@@ -6837,6 +6910,8 @@ async function runShow(ctx, laneId, hasPendingQuestionForLane, resolveLaneTarget
6837
6910
  failed_resume_history: lane.failed_resume_history ?? [],
6838
6911
  pending_resume: lane.pending_resume ?? null,
6839
6912
  last_run_usage: lane.last_run_usage ?? null,
6913
+ // PS-011: work size and placement summed over the lane's measured runs.
6914
+ run_size: lane.run_size ?? null,
6840
6915
  model: lane.model ?? null,
6841
6916
  effort: lane.effort ?? null,
6842
6917
  effort_source: lane.effort_source ?? null,
@@ -8871,6 +8946,7 @@ async function repairCompanyOnOwner(ctx, laneId, opts, emitResult = true) {
8871
8946
  return {
8872
8947
  ...current,
8873
8948
  company,
8949
+ ...repairedWorkRequirements(current, company),
8874
8950
  company_history: appendCappedHistory(current.company_history ?? [], {
8875
8951
  from: null,
8876
8952
  to: company,
@@ -9543,7 +9619,9 @@ async function runCreateSubagent(ctx, opts) {
9543
9619
  }
9544
9620
  const taskBrief = fs.readFileSync(briefAbs, "utf8");
9545
9621
  const createdAt = ctx.now().toISOString();
9622
+ const laneId = mintLaneId();
9546
9623
  const lane = createLane(hqRoot, {
9624
+ lane_id: laneId,
9547
9625
  company,
9548
9626
  ...(opts.signalMetadata ? { signal: opts.signalMetadata, signal_link: opts.signalLink } : {}),
9549
9627
  ...(company === null && meshCompany ? { mesh_company: meshCompany } : {}),
@@ -9574,6 +9652,12 @@ async function runCreateSubagent(ctx, opts) {
9574
9652
  ...(cliEffort !== undefined ? { effort: cliEffort } : {}),
9575
9653
  effort_source: cliEffort !== undefined ? "cli" : "none",
9576
9654
  host: subagentLaneHost(ctx),
9655
+ ...derivedLaneWorkRequirements(ctx, hqRoot, {
9656
+ lane_id: laneId,
9657
+ company,
9658
+ mesh_company: company === null && meshCompany ? meshCompany : undefined,
9659
+ project_id: project,
9660
+ }),
9577
9661
  attribution_history: [],
9578
9662
  created_at: createdAt,
9579
9663
  updated_at: createdAt,
@@ -14,6 +14,8 @@ export interface LinkDeps {
14
14
  /** Active memberships for the signed-in user (reuses GET /membership/me). */
15
15
  listMemberships?: () => Promise<MembershipCompany[]>;
16
16
  now?: () => Date;
17
+ /** HQ root for the companies/<slug> layout fallback (default: $HQ_ROOT). */
18
+ hqRoot?: string;
17
19
  }
18
20
  export interface LinkCommandDeps {
19
21
  /** Test seam for the combined hq-flags and person-setting gate. */