@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
@@ -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
@@ -297,6 +297,44 @@ export async function waitForApprovalTerminal(token, companyUid, queueId, option
297
297
  }
298
298
  return null;
299
299
  }
300
+ /**
301
+ * True when the gateway says the call ran but its result was not kept. An
302
+ * explicit `resultAvailable` is authoritative (true can pair with a null
303
+ * result: a call may legitimately return null). Only gateways that omit it
304
+ * fall back to `callAlreadyRan` with no result.
305
+ */
306
+ function resultNotKept(r) {
307
+ if (r.resultAvailable !== undefined)
308
+ return r.resultAvailable === false;
309
+ return r.callAlreadyRan === true && (r.result === null || r.result === undefined);
310
+ }
311
+ /** Detail suffix such as " (reason: x, 12 bytes)"; empty when the gateway sent neither. */
312
+ function resultOmittedDetail(r) {
313
+ const parts = [];
314
+ if (typeof r.resultOmittedReason === "string" && r.resultOmittedReason) {
315
+ parts.push(`reason: ${terminalSafeText(r.resultOmittedReason)}`);
316
+ }
317
+ if (typeof r.resultBytes === "number")
318
+ parts.push(`${r.resultBytes} bytes`);
319
+ return parts.length ? ` (${parts.join(", ")})` : "";
320
+ }
321
+ /** Plain-text notice for a finished call whose result was not kept. */
322
+ function resultNotKeptNotice(r) {
323
+ const message = typeof r.message === "string" && r.message.trim()
324
+ ? terminalSafeText(r.message)
325
+ : "The call ran and will not run again, but its result was not kept.";
326
+ return `${message}${resultOmittedDetail(r)}`;
327
+ }
328
+ /**
329
+ * Server note printed after a result that is present: the live-result shape
330
+ * (the row did not keep it, so this response is the only copy). Undefined
331
+ * when the gateway sent no message.
332
+ */
333
+ function resultPresentNote(r) {
334
+ if (typeof r.message !== "string" || !r.message.trim())
335
+ return undefined;
336
+ return `${terminalSafeText(r.message)}${resultOmittedDetail(r)}`;
337
+ }
300
338
  /**
301
339
  * Read the stored result of an approved call that already ran. The confirm
302
340
  * route answers an approve for a `resumed` row from the queue row
@@ -316,7 +354,19 @@ async function fetchStoredApprovalResult(token, companyUid, connectionId, queueI
316
354
  const body = (await res.json().catch(() => ({})));
317
355
  if (body.status !== "resumed" || body.alreadyResumed !== true)
318
356
  return undefined;
319
- return { result: body.result };
357
+ const stored = { result: body.result };
358
+ // Newer gateways say why a finished call has no result to show.
359
+ if (body.callAlreadyRan !== undefined)
360
+ stored.callAlreadyRan = body.callAlreadyRan;
361
+ if (body.resultAvailable !== undefined)
362
+ stored.resultAvailable = body.resultAvailable;
363
+ if (body.resultOmittedReason !== undefined)
364
+ stored.resultOmittedReason = body.resultOmittedReason;
365
+ if (body.resultBytes !== undefined)
366
+ stored.resultBytes = body.resultBytes;
367
+ if (body.message !== undefined)
368
+ stored.message = body.message;
369
+ return stored;
320
370
  }
321
371
  catch {
322
372
  return undefined;
@@ -644,7 +694,17 @@ export function registerIntegrationsCommand(program) {
644
694
  ? await fetchStoredApprovalResult(token, companyUid, connection.id, queueId)
645
695
  : undefined;
646
696
  if (opts.json) {
647
- printJson(stored && stored.result !== undefined ? { ...terminal, result: stored.result } : terminal);
697
+ printJson(stored
698
+ ? {
699
+ ...terminal,
700
+ ...(stored.result !== undefined ? { result: stored.result } : {}),
701
+ ...(stored.callAlreadyRan !== undefined ? { callAlreadyRan: stored.callAlreadyRan } : {}),
702
+ ...(stored.resultAvailable !== undefined ? { resultAvailable: stored.resultAvailable } : {}),
703
+ ...(stored.resultOmittedReason !== undefined ? { resultOmittedReason: stored.resultOmittedReason } : {}),
704
+ ...(stored.resultBytes !== undefined ? { resultBytes: stored.resultBytes } : {}),
705
+ ...(stored.message !== undefined ? { message: stored.message } : {}),
706
+ }
707
+ : terminal);
648
708
  }
649
709
  else if (approvalOutcomeFailed(terminal)) {
650
710
  const unknown = terminal.status === "write_unknown" || terminal.outcome === "unknown";
@@ -658,6 +718,16 @@ export function registerIntegrationsCommand(program) {
658
718
  console.log(chalk.green("Approved — the call completed."));
659
719
  if (stored && stored.result !== undefined && stored.result !== null) {
660
720
  printJson(unwrapGatewayResult(stored.result));
721
+ const note = resultPresentNote(stored);
722
+ if (note)
723
+ console.log(chalk.yellow(note));
724
+ }
725
+ else if (stored && resultNotKept(stored)) {
726
+ console.log(chalk.yellow(resultNotKeptNotice(stored)));
727
+ }
728
+ else if (stored && stored.resultAvailable === true) {
729
+ // The call legitimately returned null; same as the sync path.
730
+ printJson(stored.result ?? null);
661
731
  }
662
732
  else if (ran) {
663
733
  console.log(chalk.yellow(`The call's result could not be read back. Run \`hq integrations approve ${queueId} --provider ${bareProvider(connection.provider)}${opts.company ? ` --company ${opts.company}` : ""}\` again to fetch it; the call will not run twice.`));
@@ -705,8 +775,19 @@ export function registerIntegrationsCommand(program) {
705
775
  else {
706
776
  console.log(chalk.yellow(`Approval ended with status ${body.status ?? "unknown"}.`));
707
777
  }
708
- if (result !== undefined)
778
+ if (result !== undefined && result !== null) {
709
779
  printJson(result);
780
+ const note = resultPresentNote(body);
781
+ if (note)
782
+ console.log(chalk.yellow(note));
783
+ }
784
+ else if (resultNotKept(body)) {
785
+ console.log(chalk.yellow(resultNotKeptNotice(body)));
786
+ }
787
+ else if (result === null) {
788
+ // Older gateways, or a call that legitimately returned null.
789
+ printJson(result);
790
+ }
710
791
  });
711
792
  }
712
793
  registerConnectCommands(integrations);
@@ -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. */