@aiwg/cli 2026.10.15 → 2026.10.16

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 (180) hide show
  1. package/agentic/code/providers/pi/aiwg-bridge.ts +45 -7
  2. package/dist/src/artifacts/citation-parser.js +7 -6
  3. package/dist/src/artifacts/corpus-tools/citation-densify.js +4 -2
  4. package/dist/src/artifacts/corpus-tools/cli.js +8 -3
  5. package/dist/src/artifacts/corpus-tools/discovery-log.js +26 -24
  6. package/dist/src/artifacts/corpus-tools/expand-cli.js +3 -2
  7. package/dist/src/artifacts/corpus-tools/expand-dates.js +107 -0
  8. package/dist/src/artifacts/corpus-tools/expand-queue.js +4 -1
  9. package/dist/src/artifacts/corpus-tools/expand-review.js +104 -0
  10. package/dist/src/artifacts/corpus-tools/expand-state.js +17 -1
  11. package/dist/src/artifacts/corpus-tools/expand.js +16 -17
  12. package/dist/src/artifacts/corpus-tools/induction-audit.js +7 -6
  13. package/dist/src/artifacts/corpus-tools/integrity-scan.js +3 -3
  14. package/dist/src/artifacts/corpus-tools/radar-shared.js +7 -9
  15. package/dist/src/artifacts/corpus-tools/ref-files.js +11 -0
  16. package/dist/src/artifacts/corpus-tools/resolve-cli.js +11 -3
  17. package/dist/src/artifacts/corpus-tools/resolve.js +23 -9
  18. package/dist/src/artifacts/corpus-tools/retrieval-lab.js +2 -1
  19. package/dist/src/artifacts/corpus-tools/sidecar-lint.js +4 -4
  20. package/dist/src/artifacts/corpus-tools/sidecar-repair.js +2 -1
  21. package/dist/src/artifacts/corpus-views/ref-parser.js +3 -17
  22. package/dist/src/artifacts/graph-query.js +5 -3
  23. package/dist/src/artifacts/hybrid-query.js +11 -2
  24. package/dist/src/artifacts/index-refresh.js +2 -0
  25. package/dist/src/cli/handlers/daemon.js +17 -1
  26. package/dist/src/cli/handlers/doctor-args.js +10 -5
  27. package/dist/src/cli/handlers/doctor-help.js +4 -1
  28. package/dist/src/cli/handlers/index.js +2 -2
  29. package/dist/src/cli/handlers/models-resource-sample.js +10 -0
  30. package/dist/src/cli/handlers/models.js +3 -2
  31. package/dist/src/cli/handlers/regenerate.js +8 -16
  32. package/dist/src/cli/handlers/sessions.js +7 -7
  33. package/dist/src/cli/handlers/subcommands.js +8 -0
  34. package/dist/src/cli/handlers/update.js +157 -0
  35. package/dist/src/cli/handlers/use.js +14 -4
  36. package/dist/src/cli/handlers/utilities.js +3 -560
  37. package/dist/src/cli/handlers/utility-doctor.js +412 -0
  38. package/dist/src/cli/services/deployment-verification.js +0 -1
  39. package/dist/src/config/aiwg-config.js +2 -1
  40. package/dist/src/config/authorization-cli.js +7 -3
  41. package/dist/src/config/dispatch-thresholds-runtime.d.mts +3 -2
  42. package/dist/src/config/dispatch-thresholds-runtime.mjs +17 -7
  43. package/dist/src/config/framework-aliases.js +12 -0
  44. package/dist/src/config/host-resource-report.d.mts +19 -0
  45. package/dist/src/config/host-resource-report.mjs +80 -0
  46. package/dist/src/config/host-resource-runtime.d.mts +34 -0
  47. package/dist/src/config/host-resource-runtime.mjs +293 -0
  48. package/dist/src/config/installed-selection.js +22 -0
  49. package/dist/src/config/worker-invocation-marker.d.mts +1 -0
  50. package/dist/src/config/worker-invocation-marker.mjs +2 -0
  51. package/dist/src/decision/heldout/access.js +74 -0
  52. package/dist/src/decision/heldout/calibration.js +1 -0
  53. package/dist/src/decision/heldout/collector.js +8 -1
  54. package/dist/src/effects/verifiers/file.js +22 -5
  55. package/dist/src/extensions/claude-attribution.js +82 -0
  56. package/dist/src/extensions/claude-hooks-installer.js +115 -69
  57. package/dist/src/extensions/commands/daemon.js +109 -0
  58. package/dist/src/extensions/commands/definitions.js +5 -89
  59. package/dist/src/gates/heldout.js +17 -7
  60. package/dist/src/lint/check-patterns.js +163 -0
  61. package/dist/src/lint/checks.js +268 -0
  62. package/dist/src/lint/reference-resolution.js +54 -0
  63. package/dist/src/lint/runner.js +3 -465
  64. package/dist/src/mcp/helpers.mjs +11 -1
  65. package/dist/src/memory/project-registry.js +44 -4
  66. package/dist/src/models/worker-plan.js +36 -5
  67. package/dist/src/models/wrapper-deployment.js +25 -12
  68. package/dist/src/models/wrapper-enforcement.js +47 -7
  69. package/dist/src/network-analysis/research.js +2 -1
  70. package/dist/src/policy/hitl-check.js +14 -4
  71. package/dist/src/policy/hitl-consume.js +54 -0
  72. package/dist/src/policy/hitl-receipt.js +2 -0
  73. package/dist/src/policy/hitl.js +11 -3
  74. package/dist/src/providers/provider-context-contracts.js +162 -0
  75. package/dist/src/providers/provider-definition-schema.js +136 -0
  76. package/dist/src/providers/provider-definitions.js +8 -1298
  77. package/dist/src/providers/provider-seeds-1.js +360 -0
  78. package/dist/src/providers/provider-seeds-2.js +387 -0
  79. package/dist/src/providers/provider-seeds-3.js +262 -0
  80. package/dist/src/research/clients/arxiv.js +4 -30
  81. package/dist/src/research/clients/base.js +48 -22
  82. package/dist/src/research/identity.js +34 -2
  83. package/dist/src/research/query-cli.js +3 -87
  84. package/dist/src/research/query-options.js +87 -0
  85. package/dist/src/research/reference-match.js +70 -24
  86. package/dist/src/research/services/acquisition.js +9 -7
  87. package/dist/src/research/services/citation.js +5 -2
  88. package/dist/src/research/types.js +2 -0
  89. package/dist/src/serve/mission-conductor.js +48 -4
  90. package/dist/src/sessions/adapters/grok-build-native.js +23 -0
  91. package/dist/src/sessions/adapters/grok-build.js +14 -7
  92. package/dist/src/sessions/workspace-discovery.js +5 -5
  93. package/dist/src/smiths/context-pipeline/aiwg-md.js +16 -46
  94. package/dist/src/smiths/context-pipeline/claude-hook.js +1 -1
  95. package/dist/src/smiths/context-pipeline/code-regions.js +28 -0
  96. package/dist/src/smiths/context-pipeline/finalization.js +81 -51
  97. package/dist/src/smiths/context-pipeline/generator.js +9 -10
  98. package/dist/src/smiths/context-pipeline/managed-hook.js +1 -1
  99. package/dist/src/smiths/context-pipeline/muse-bridge.js +2 -2
  100. package/dist/src/smiths/context-pipeline/provider-policy.js +6 -12
  101. package/dist/src/smiths/context-pipeline/workspace-audit.js +299 -0
  102. package/dist/src/smiths/context-pipeline/workspace-bootstrap.js +148 -0
  103. package/dist/src/smiths/context-pipeline/workspace-context-shared.js +111 -0
  104. package/dist/src/smiths/context-pipeline/workspace-context.js +8 -1373
  105. package/dist/src/smiths/context-pipeline/workspace-doctor.js +192 -0
  106. package/dist/src/smiths/context-pipeline/workspace-document.js +201 -0
  107. package/dist/src/smiths/context-pipeline/workspace-extraction.js +205 -0
  108. package/dist/src/smiths/context-pipeline/workspace-migration.js +250 -0
  109. package/package.json +10 -1
  110. package/schemas/decision/D29Study.v10.schema.json +65 -0
  111. package/tools/agents/deploy-agents.mjs +10 -0
  112. package/tools/agents/providers/claude-post-deploy.mjs +12 -1
  113. package/tools/agents/providers/context-write.mjs +4 -0
  114. package/tools/agents/providers/pi.mjs +3 -1
  115. package/tools/agents/providers/rule-delivery-surface.mjs +332 -0
  116. package/tools/agents/providers/rule-delivery.mjs +20 -1144
  117. package/tools/agents/providers/rule-deployment-commit.mjs +144 -0
  118. package/tools/agents/providers/rule-deployment-prepare.mjs +452 -0
  119. package/tools/agents/providers/rule-deployment-state.mjs +300 -0
  120. package/tools/daemon/README.md +511 -0
  121. package/tools/daemon/adapters/base-adapter.mjs +84 -0
  122. package/tools/daemon/adapters/webhook-adapter.mjs +107 -0
  123. package/tools/daemon/agent-supervisor.mjs +299 -0
  124. package/tools/daemon/automation-engine.mjs +310 -0
  125. package/tools/daemon/autonomous-engine.mjs +346 -0
  126. package/tools/daemon/behavior-loader.mjs +316 -0
  127. package/tools/daemon/behavior.mjs +174 -0
  128. package/tools/daemon/concierge/intent-router.mjs +401 -0
  129. package/tools/daemon/concierge/orchestrator.mjs +272 -0
  130. package/tools/daemon/concierge/response-translator.mjs +462 -0
  131. package/tools/daemon/config.mjs +377 -0
  132. package/tools/daemon/cron-scheduler.mjs +178 -0
  133. package/tools/daemon/daemon-main.mjs +1169 -0
  134. package/tools/daemon/event-router.mjs +84 -0
  135. package/tools/daemon/file-watcher.mjs +383 -0
  136. package/tools/daemon/index.mjs +1181 -0
  137. package/tools/daemon/init-profile.mjs +124 -0
  138. package/tools/daemon/ipc-client.mjs +197 -0
  139. package/tools/daemon/ipc-ops-handlers.mjs +236 -0
  140. package/tools/daemon/ipc-server.mjs +275 -0
  141. package/tools/daemon/maintenance-owner.mjs +79 -0
  142. package/tools/daemon/memory-manager.mjs +386 -0
  143. package/tools/daemon/message-router.mjs +194 -0
  144. package/tools/daemon/provider-watcher.mjs +585 -0
  145. package/tools/daemon/pty-adapter.mjs +420 -0
  146. package/tools/daemon/repl-chat.mjs +359 -0
  147. package/tools/daemon/resource-bounds.mjs +88 -0
  148. package/tools/daemon/sandbox-transport.mjs +295 -0
  149. package/tools/daemon/scheduled-task-runner.mjs +535 -0
  150. package/tools/daemon/task-store.mjs +450 -0
  151. package/tools/daemon/tmux-manager.mjs +324 -0
  152. package/tools/daemon/update-policy.mjs +517 -0
  153. package/tools/daemon/web-server.mjs +399 -0
  154. package/tools/daemon/web-ui/index.html +585 -0
  155. package/tools/daemon/web-ui/styles.css +156 -0
  156. package/tools/docker/Dockerfile.daemon +35 -0
  157. package/tools/docker/container-manager.mjs +291 -0
  158. package/tools/messaging/adapter-registry.mjs +230 -0
  159. package/tools/messaging/adapters/base.mjs +326 -0
  160. package/tools/messaging/adapters/discord.mjs +462 -0
  161. package/tools/messaging/adapters/slack.mjs +402 -0
  162. package/tools/messaging/adapters/telegram.mjs +552 -0
  163. package/tools/messaging/chat-handler.mjs +297 -0
  164. package/tools/messaging/command-router.mjs +269 -0
  165. package/tools/messaging/event-bus.mjs +199 -0
  166. package/tools/messaging/index.mjs +456 -0
  167. package/tools/messaging/message-formatter.mjs +320 -0
  168. package/tools/messaging/room-manager.mjs +277 -0
  169. package/tools/messaging/types.mjs +94 -0
  170. package/tools/providers/pi-bridge-policy.mjs +4 -0
  171. package/tools/ralph-external/daemon-supervisor.mjs +394 -0
  172. package/tools/ralph-external/lib/behavior-registry.mjs +270 -0
  173. package/tools/ralph-external/lib/worker-invocation-processes.mjs +3 -2
  174. package/tools/ralph-external/lib/worker-isolation-args.mjs +217 -0
  175. package/tools/ralph-external/lib/worker-isolation-status.mjs +19 -0
  176. package/tools/ralph-external/lib/worker-isolation.mjs +11 -237
  177. package/tools/ralph-external/lib/worker-overflow.mjs +10 -2
  178. package/tools/ralph-external/lib/worker-unit-cleanup.mjs +72 -0
  179. package/tools/ralph-external/session-launcher.mjs +7 -7
  180. package/tools/scripts/resource-preflight.mjs +3 -242
@@ -57,12 +57,12 @@ import { buildWorkerInvocationEnvironment, WORKER_INVOCATION_MARKER } from './li
57
57
  import { resolveRetryReference } from './lib/worker-launch-cli.mjs';
58
58
  import { launcherRecoveryEvidence, observeLauncherRecoveryOutcome, recordLauncherRecoveryHint } from './lib/launcher-recovery-evidence.mjs';
59
59
  export { observeLauncherRecoveryOutcome } from './lib/launcher-recovery-evidence.mjs';
60
+ import { publishWorkerUnitExit, readRecordedWorkerUnitStop } from './lib/worker-unit-cleanup.mjs';
60
61
  import { workerNeedsNativeNamespaces, probeWorkerNativeSandbox, nativeSandboxFailure, nativeSandboxProbeMessage, NATIVE_SANDBOX_UNAVAILABLE, checkWorkerDispatch, detectWorkerIsolation, launchIsolatedWorker, getWorkerIsolationStatus, stopWorkerUnit, readUnitControlGroup } from './lib/worker-isolation.mjs';
61
62
  const { signalChild } = await importImpl(import.meta.url, 'process/signal-child.mjs');
62
63
 
63
64
  // Resolve the same installation owner as CLI/MCP inputs in source and packaged layouts.
64
65
  const { getWorkerRecoveryCapabilities, workerVersionProbeEnvironment } = await importImpl(import.meta.url, 'models/worker-installation.mjs');
65
-
66
66
  /**
67
67
  * Kernel-verified containment gate for any candidate worker identity,
68
68
  * whether it came from a worker-writable disk record (`worker-identity.json`)
@@ -1135,7 +1135,7 @@ async function captureOneWorker(owner, ctx) {
1135
1135
  // Prefer the unit's retained state whenever a unit name is recorded
1136
1136
  // (#3674 round 4): launch-mode selection is unchanged, but unit (cgroup)
1137
1137
  // evidence is used wherever it is available.
1138
- const native = outcome.unit ? readNative() : null;
1138
+ const native = outcome.unit ? readNative() ?? readRecordedWorkerUnitStop(outcome, { native: true }) : null;
1139
1139
  const members = identity ? sampleWorkerGroup(identity.pgid) : null;
1140
1140
  // Require positive kernel evidence of owned containment being empty.
1141
1141
  const confirmed = (outcome.mode !== 'systemd-unit' && child.pid === undefined) || observeWorkerTermination({ mode: outcome.mode, native,
@@ -1269,7 +1269,7 @@ async function captureOneWorker(owner, ctx) {
1269
1269
  try { await recordProcess(); }
1270
1270
  catch { result.termination = 'uncertain'; result.errorCode = 'METADATA_WRITE'; }
1271
1271
  finally {
1272
- try { await publish('exit.json', result); }
1272
+ try { await publishWorkerUnitExit(publish, outcome, native, result); }
1273
1273
  catch { result.termination = 'uncertain'; result.errorCode = 'METADATA_WRITE'; }
1274
1274
  }
1275
1275
  result.health = observer.finish({ ...result, finalValid: healthFinalValid });
@@ -1292,7 +1292,7 @@ async function captureOneWorker(owner, ctx) {
1292
1292
  ? (healthAttemptFinalValid && result.errorCode !== 'METADATA_WRITE' ? 'succeeded' : 'uncertain')
1293
1293
  : processLevelOutcome;
1294
1294
  }
1295
- try { await publish('exit.json', result); }
1295
+ try { await publishWorkerUnitExit(publish, outcome, native, result); }
1296
1296
  catch {
1297
1297
  result.termination = 'uncertain'; result.errorCode = 'METADATA_WRITE'; result.health.termination = 'uncertain';
1298
1298
  // #2915 review 5 (finding 1b): the PRIOR round left this as a
@@ -1805,7 +1805,7 @@ async function captureOneWorkerBaseline(owner, ctx) {
1805
1805
  // Prefer the unit's retained state whenever a unit name is recorded
1806
1806
  // (#3674 round 4): launch-mode selection is unchanged, but unit (cgroup)
1807
1807
  // evidence is used wherever it is available.
1808
- const native = outcome.unit ? readNative() : null;
1808
+ const native = outcome.unit ? readNative() ?? readRecordedWorkerUnitStop(outcome, { native: true }) : null;
1809
1809
  const members = identity ? sampleWorkerGroup(identity.pgid) : null;
1810
1810
  const confirmed = (outcome.mode !== 'systemd-unit' && child.pid === undefined) || observeWorkerTermination({ mode: outcome.mode, native,
1811
1811
  workerExited: sawExit, identity, supervisor, invocationId }).confirmed;
@@ -1854,12 +1854,12 @@ async function captureOneWorkerBaseline(owner, ctx) {
1854
1854
  try { await recordProcess(); }
1855
1855
  catch { result.termination = 'uncertain'; result.errorCode = 'METADATA_WRITE'; }
1856
1856
  finally {
1857
- try { await publish('exit.json', result); }
1857
+ try { await publishWorkerUnitExit(publish, outcome, native, result); }
1858
1858
  catch { result.termination = 'uncertain'; result.errorCode = 'METADATA_WRITE'; }
1859
1859
  }
1860
1860
  result.health = observer.finish({ ...result, finalValid: healthFinalValid });
1861
1861
  result.healthEvidence = observer.evidence();
1862
- try { await publish('exit.json', result); }
1862
+ try { await publishWorkerUnitExit(publish, outcome, native, result); }
1863
1863
  catch { result.termination = 'uncertain'; result.errorCode = 'METADATA_WRITE'; result.health.termination = 'uncertain'; }
1864
1864
  await reportHealth();
1865
1865
  owner.emit('complete', result);
@@ -1,8 +1,7 @@
1
1
  #!/usr/bin/env node
2
- import { existsSync, readFileSync, readdirSync, statfsSync } from 'node:fs';
2
+ import { existsSync, readFileSync, statfsSync } from 'node:fs';
3
3
  import { dirname, join, resolve } from 'node:path';
4
4
  import os from 'node:os';
5
- import { spawnSync } from 'node:child_process';
6
5
  import { fileURLToPath, pathToFileURL } from 'node:url';
7
6
 
8
7
  // Installed packages ship dist/src, not src; resolve the runtime like workspace-status.mjs.
@@ -16,6 +15,8 @@ const [
16
15
  import(pathToFileURL(join(packageRoot, runtimeRoot, 'config/project-artifacts-runtime.mjs')).href),
17
16
  ]);
18
17
 
18
+ const { parseMemAvailableGb, parseMemoryPsi, parseLoadAverages, countWorkerUnits, defaultCountWorkers, readLiveHostResources, evaluateDispatchGate } = await import(pathToFileURL(join(packageRoot, runtimeRoot, 'config/host-resource-runtime.mjs')).href);
19
+
19
20
  const BYTES_PER_GB = 1024 ** 3;
20
21
 
21
22
  const DEFAULT_AUTO_REQUIREMENTS = {
@@ -164,251 +165,11 @@ function evaluatePreflight(config, hostResources) {
164
165
  };
165
166
  }
166
167
 
167
- /**
168
- * Parse MemAvailable (kB) from /proc/meminfo text. Returns GiB or undefined
169
- * when the field is absent/unparsable. Pure: tests feed synthetic fixtures.
170
- */
171
- function parseMemAvailableGb(meminfoText) {
172
- if (typeof meminfoText !== 'string') return undefined;
173
- const match = meminfoText.match(/^MemAvailable:\s+(\d+)\s+kB$/m);
174
- if (!match) return undefined;
175
- const gib = Number(match[1]) / 1024 / 1024;
176
- return Number.isFinite(gib) ? gib : undefined;
177
- }
178
-
179
- /**
180
- * Parse memory pressure from /proc/pressure/memory text. Returns
181
- * `{ avg10, avg60, avg300 }` from the `some` line, or null when no `some`
182
- * line parses. Pure: tests feed synthetic fixtures.
183
- */
184
- function parseMemoryPsi(pressureText) {
185
- if (typeof pressureText !== 'string') return null;
186
- for (const line of pressureText.split('\n')) {
187
- if (!line.startsWith('some')) continue;
188
- const values = {};
189
- for (const part of line.split(/\s+/)) {
190
- const [key, raw] = part.split('=');
191
- if ((key === 'avg10' || key === 'avg60' || key === 'avg300') && raw !== undefined) {
192
- const value = Number(raw);
193
- if (Number.isFinite(value)) values[key] = value;
194
- }
195
- }
196
- if (values.avg10 !== undefined && values.avg60 !== undefined && values.avg300 !== undefined) return values;
197
- return null;
198
- }
199
- return null;
200
- }
201
-
202
- /**
203
- * Parse /proc/loadavg text. Returns `{ load1, load5, load15 }` or null.
204
- * Pure: tests feed synthetic fixtures.
205
- */
206
- function parseLoadAverages(loadavgText) {
207
- if (typeof loadavgText !== 'string') return null;
208
- const parts = loadavgText.trim().split(/\s+/);
209
- const loads = parts.slice(0, 3).map(Number);
210
- if (loads.length !== 3 || loads.some(value => !Number.isFinite(value))) return null;
211
- return { load1: loads[0], load5: loads[1], load15: loads[2] };
212
- }
213
-
214
- /** Count active current-user units with the explicit aiwg-worker- prefix. */
215
- function countWorkerUnits({ spawn = spawnSync } = {}) {
216
- try {
217
- const result = spawn('systemctl', ['--user', 'list-units', '--type=service',
218
- '--state=running,activating', '--no-legend', '--plain', 'aiwg-worker-*'],
219
- { encoding: 'utf8', timeout: 1000 });
220
- if (result.error || result.status !== 0) return undefined;
221
- return String(result.stdout ?? '').split('\n')
222
- .filter(line => /^aiwg-worker-[^\s]+\.service\s/.test(line.trim())).length;
223
- } catch { return undefined; }
224
- }
225
-
226
- /**
227
- * Current UID only. Explicit worker units are authoritative when available;
228
- * otherwise count exact comm names, never shell text or arbitrary argv.
229
- */
230
- function defaultCountWorkers({
231
- readDir = readdirSync,
232
- readText = path => readFileSync(path, 'utf8'),
233
- uid = process.getuid?.(),
234
- countWorkerUnits: readUnits = countWorkerUnits,
235
- } = {}) {
236
- if (process.platform !== 'linux' || uid === undefined) return undefined;
237
- // Units cover launched workers; process names cover degraded launches and other
238
- // conductors. Take the larger so no worker class can hide from max_workers.
239
- let units;
240
- try {
241
- const counted = readUnits();
242
- if (Number.isInteger(counted) && counted >= 0) units = counted;
243
- } catch { /* Fall back to current-user process names. */ }
244
- let entries;
245
- try { entries = readDir('/proc'); } catch { return units; }
246
- let total = 0;
247
- for (const entry of entries) {
248
- if (!/^\d+$/.test(entry)) continue;
249
- try {
250
- const status = readText(`/proc/${entry}/status`);
251
- const owner = status.match(/^Uid:\s+(\d+)/m);
252
- if (!owner || Number(owner[1]) !== uid) continue;
253
- const comm = readText(`/proc/${entry}/comm`).trim();
254
- if (comm === 'codex' || comm === 'muse-bin') total += 1;
255
- } catch { /* Processes may exit during the scan. */ }
256
- }
257
- return Math.max(units ?? 0, total);
258
- }
259
-
260
- /**
261
- * Sample live host signals. All inputs are injectable so tests use synthetic
262
- * meminfo/pressure/loadavg fixtures instead of the real /proc:
263
- * `{ readText, coreCount, countWorkers }`. Non-Linux hosts report
264
- * `{ supported: false }`; the gate turns that into an explicit diagnostic
265
- * (MVP qualifies Linux per NFR-OG-008) rather than an implicit pass.
266
- */
267
- /**
268
- * Convert one statfs result to GiB. Non-finite or negative samples are
269
- * rejected (fail closed): a NaN/Infinity/-1 reading must never become a
270
- * passing number downstream.
271
- */
272
- function toFreeDiskGb(disk) {
273
- const gb = (Number(disk?.bavail) * Number(disk?.bsize)) / BYTES_PER_GB;
274
- return Number.isFinite(gb) && gb >= 0 ? gb : undefined;
275
- }
276
-
277
- /**
278
- * Sample free disk on the caller-supplied filesystem(s): `readers.paths`
279
- * names the actual evidence root and worktree, and the gate takes the
280
- * minimum across them. Any unreadable, non-finite or negative sample — or
281
- * no supplied filesystem at all — yields undefined so the gate fails closed
282
- * instead of admitting on the conductor's process-cwd filesystem.
283
- * `readers.statfs` (zero-arg) and `readers.statfsPath` (per-path) stay as
284
- * injectable test seams; there is no process.cwd() fallback.
285
- */
286
- function sampleFreeDiskGb(readers) {
287
- if (Array.isArray(readers.paths)) {
288
- if (readers.paths.length === 0) return undefined;
289
- const statOne = typeof readers.statfsPath === 'function' ? readers.statfsPath : (path) => statfsSync(path);
290
- let minimum;
291
- for (const path of readers.paths) {
292
- let sample;
293
- try {
294
- sample = toFreeDiskGb(statOne(path));
295
- } catch {
296
- return undefined;
297
- }
298
- if (sample === undefined) return undefined;
299
- minimum = minimum === undefined ? sample : Math.min(minimum, sample);
300
- }
301
- return minimum;
302
- }
303
- if (typeof readers.statfs === 'function') {
304
- try {
305
- return toFreeDiskGb(readers.statfs());
306
- } catch {
307
- return undefined;
308
- }
309
- }
310
- return undefined;
311
- }
312
-
313
- function readLiveHostResources(readers = {}) {
314
- const readText = readers.readText ?? (path => readFileSync(path, 'utf8'));
315
- const coreCount = readers.coreCount ?? (() => os.cpus().length);
316
- const countWorkers = readers.countWorkers ?? (() => defaultCountWorkers());
317
- // 08 disk-pressure admission: free disk sampled through the same injectable
318
- // resolver path as every other live signal, so tests feed synthetic values.
319
- // Callers supply the evidence/worktree filesystems via `readers.paths`
320
- // (threaded through `checkWorkerDispatch({ paths })`); without them free
321
- // disk is unknown and the gate fails closed.
322
- if (process.platform !== 'linux' && readers.readText === undefined) {
323
- return { supported: false, reason: `live dispatch signals require Linux /proc (this host: ${process.platform})` };
324
- }
325
- const readOptional = (path) => {
326
- try {
327
- return readText(path);
328
- } catch {
329
- return undefined;
330
- }
331
- };
332
- const cores = coreCount();
333
- const load = parseLoadAverages(readOptional('/proc/loadavg') ?? '');
334
- const psi = parseMemoryPsi(readOptional('/proc/pressure/memory') ?? '');
335
- let workers;
336
- try {
337
- workers = countWorkers();
338
- } catch {
339
- workers = undefined;
340
- }
341
- return {
342
- supported: true,
343
- availMemGb: parseMemAvailableGb(readOptional('/proc/meminfo') ?? ''),
344
- load1: load?.load1,
345
- cores: Number.isFinite(cores) && cores > 0 ? cores : undefined,
346
- loadRatio: load && cores ? load.load1 / cores : undefined,
347
- memPsiAvg10: psi?.avg10,
348
- memPsiAvg60: psi?.avg60,
349
- memPsiAvg300: psi?.avg300,
350
- workers,
351
- freeDiskGb: sampleFreeDiskGb(readers),
352
- };
353
- }
354
-
355
168
  /** Adapt tool option names to the single source-owned config resolver. */
356
169
  function resolveDispatchThresholds({ buildDispatch, admissionHostResources, overlay } = {}) {
357
170
  return resolveDispatchHostThresholds(buildDispatch, admissionHostResources, overlay);
358
171
  }
359
172
 
360
- /**
361
- * Evaluate sampled live signals against thresholds. Every breach becomes a
362
- * BLOCK failure naming its signal. Unknown-but-required signals (threshold
363
- * configured, signal undetectable) fail closed with reason 'not detectable'.
364
- */
365
- function evaluateDispatchGate(live, thresholds) {
366
- const failures = [];
367
- if (!live || live.supported === false) {
368
- return {
369
- ok: false,
370
- failures: [{ signal: 'platform', reason: live?.reason ?? 'live host signals unavailable' }],
371
- thresholds,
372
- };
373
- }
374
- const breach = (signal, actual, threshold, reason) => failures.push({ signal, actual, threshold, reason });
375
- if (live.availMemGb === undefined) breach('avail-mem', undefined, thresholds.min_avail_mem_gb, 'MemAvailable not detectable on this host');
376
- else if (live.availMemGb < thresholds.min_avail_mem_gb) {
377
- breach('avail-mem', live.availMemGb, thresholds.min_avail_mem_gb, `available ${live.availMemGb.toFixed(1)}GB < ${thresholds.min_avail_mem_gb}GB`);
378
- }
379
- if (live.loadRatio === undefined) breach('load', undefined, thresholds.max_load_ratio, 'load average not detectable on this host');
380
- else if (live.loadRatio > thresholds.max_load_ratio) {
381
- breach('load', live.loadRatio, thresholds.max_load_ratio, `load ratio ${live.loadRatio.toFixed(2)} > ${thresholds.max_load_ratio}`);
382
- }
383
- if (live.memPsiAvg10 === undefined) breach('mem-psi-avg10', undefined, thresholds.max_mem_psi_avg10, '/proc/pressure/memory not detectable on this host');
384
- else if (live.memPsiAvg10 > thresholds.max_mem_psi_avg10) {
385
- breach('mem-psi-avg10', live.memPsiAvg10, thresholds.max_mem_psi_avg10, `memory PSI avg10 ${live.memPsiAvg10} > ${thresholds.max_mem_psi_avg10}`);
386
- }
387
- if (live.memPsiAvg60 === undefined) breach('mem-psi-avg60', undefined, thresholds.max_mem_psi_avg60, '/proc/pressure/memory not detectable on this host');
388
- else if (live.memPsiAvg60 > thresholds.max_mem_psi_avg60) {
389
- breach('mem-psi-avg60', live.memPsiAvg60, thresholds.max_mem_psi_avg60, `memory PSI avg60 ${live.memPsiAvg60} > ${thresholds.max_mem_psi_avg60}`);
390
- }
391
- if (thresholds.max_workers !== undefined) {
392
- if (live.workers === undefined) breach('workers', undefined, thresholds.max_workers, 'worker count not detectable on this host');
393
- else if (live.workers >= thresholds.max_workers) {
394
- breach('workers', live.workers, thresholds.max_workers, `${live.workers} running workers >= ${thresholds.max_workers}`);
395
- }
396
- }
397
- // 08 disk-pressure admission: unknown-but-required free disk fails closed,
398
- // like every other required signal; under-threshold free disk blocks.
399
- // Pre-sampled NaN/Infinity/negative readings are rejected here too, so a
400
- // forged or broken sample can never satisfy the gate.
401
- if (thresholds.min_free_disk_gb !== undefined && thresholds.min_free_disk_gb > 0) {
402
- const disk = live.freeDiskGb;
403
- if (disk === undefined || !Number.isFinite(disk) || disk < 0) {
404
- breach('free-disk', undefined, thresholds.min_free_disk_gb, 'free disk not detectable on this host');
405
- } else if (disk < thresholds.min_free_disk_gb) {
406
- breach('free-disk', disk, thresholds.min_free_disk_gb, `free ${disk.toFixed(1)}GB < ${thresholds.min_free_disk_gb}GB`);
407
- }
408
- }
409
- return { ok: failures.length === 0, failures, thresholds };
410
- }
411
-
412
173
  /**
413
174
  * Tier 0 consumable dispatch check (FR-OG-107, #2954). `prepareWorkerInvocation`
414
175
  * callers and the conductor procedure call this before launch; over threshold