@loucompanion/forge-bridge 0.1.4-dev.f22f5e3d01fe → 0.2.1-dev.0f07274d438b

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 (260) hide show
  1. package/README.md +128 -4
  2. package/dist/bridge/bridge-chat-giphy-look.d.ts +48 -0
  3. package/dist/bridge/bridge-chat-giphy-look.js +55 -0
  4. package/dist/bridge/bridge-chat-provider-command.d.ts +27 -3
  5. package/dist/bridge/bridge-chat-provider-command.js +131 -26
  6. package/dist/bridge/bridge-chat.types.d.ts +20 -0
  7. package/dist/bridge/bridge-chat.types.js +28 -1
  8. package/dist/bridge/bridge-state-file.d.ts +161 -0
  9. package/dist/bridge/bridge-state-file.js +376 -0
  10. package/dist/bridge/bridge-state-io.d.ts +15 -0
  11. package/dist/bridge/bridge-state-io.js +68 -0
  12. package/dist/bridge/bridge-state-lock.d.ts +11 -0
  13. package/dist/bridge/bridge-state-lock.js +102 -0
  14. package/dist/bridge/bridge-state-unpublished.d.ts +17 -0
  15. package/dist/bridge/bridge-state-unpublished.js +111 -0
  16. package/dist/bridge/bridge.service.d.ts +29 -12
  17. package/dist/bridge/bridge.service.js +215 -380
  18. package/dist/bridge/bridge.types.d.ts +21 -0
  19. package/dist/bridge/bridge.types.js +2 -1
  20. package/dist/bridge/default-session-service.d.ts +13 -0
  21. package/dist/bridge/default-session-service.js +22 -0
  22. package/dist/bridge/dispatch-offer-policy.d.ts +22 -0
  23. package/dist/bridge/dispatch-offer-policy.js +58 -0
  24. package/dist/bridge/in-flight-registry.d.ts +62 -0
  25. package/dist/bridge/in-flight-registry.js +207 -0
  26. package/dist/bridge/readiness-result-outbox.d.ts +5 -1
  27. package/dist/bridge/readiness-result-outbox.js +20 -0
  28. package/dist/bridge/runner-host-capabilities.js +14 -1
  29. package/dist/bridge/sandbox-resource-accounting.d.ts +16 -0
  30. package/dist/bridge/sandbox-resource-accounting.js +150 -0
  31. package/dist/bridge/windows-bash-resolution.d.ts +31 -0
  32. package/dist/bridge/windows-bash-resolution.js +153 -0
  33. package/dist/cleanup/cleanup-wip.d.ts +12 -0
  34. package/dist/cleanup/cleanup-wip.js +66 -0
  35. package/dist/cleanup/cleanup.service.d.ts +11 -1
  36. package/dist/cleanup/cleanup.service.js +80 -62
  37. package/dist/cleanup/cleanup.types.d.ts +2 -0
  38. package/dist/cleanup/forge-owned-paths.d.ts +2 -0
  39. package/dist/cleanup/forge-owned-paths.js +9 -0
  40. package/dist/cleanup/host-runtime-ledger.d.ts +2 -0
  41. package/dist/cleanup/host-runtime-ledger.js +30 -9
  42. package/dist/cli/cli.help.js +57 -13
  43. package/dist/cli/cli.service.d.ts +3 -10
  44. package/dist/cli/cli.service.js +20 -213
  45. package/dist/cli/idle-status.d.ts +84 -0
  46. package/dist/cli/idle-status.js +181 -0
  47. package/dist/cli/local-config.d.ts +14 -1
  48. package/dist/cli/local-config.js +42 -2
  49. package/dist/cli/provider-cli-advertising.d.ts +24 -0
  50. package/dist/cli/provider-cli-advertising.js +88 -0
  51. package/dist/cli/provider-cli-detection.d.ts +10 -0
  52. package/dist/cli/provider-cli-detection.js +160 -0
  53. package/dist/runtime/aspnet-runtime-prebuild.d.ts +20 -0
  54. package/dist/runtime/aspnet-runtime-prebuild.js +104 -26
  55. package/dist/runtime/attempt-database-broker.d.ts +1 -1
  56. package/dist/runtime/attempt-node-runtime-launcher.d.ts +36 -0
  57. package/dist/runtime/attempt-node-runtime-launcher.js +169 -0
  58. package/dist/runtime/attempt-process-supervisor.d.ts +2 -0
  59. package/dist/runtime/attempt-process-supervisor.js +12 -6
  60. package/dist/runtime/docker-engine-probe.d.ts +5 -0
  61. package/dist/runtime/docker-engine-probe.js +7 -0
  62. package/dist/runtime/dotnet-build-outputs.d.ts +107 -0
  63. package/dist/runtime/dotnet-build-outputs.js +402 -0
  64. package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
  65. package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
  66. package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
  67. package/dist/runtime/ephemeral-test-postgres.js +303 -0
  68. package/dist/runtime/host-listener-inspector.d.ts +26 -0
  69. package/dist/runtime/host-listener-inspector.js +84 -3
  70. package/dist/runtime/host-load-admission.d.ts +5 -0
  71. package/dist/runtime/host-load-capacity.d.ts +198 -0
  72. package/dist/runtime/host-load-capacity.js +353 -0
  73. package/dist/runtime/host-load-child-environment.d.ts +13 -0
  74. package/dist/runtime/host-load-child-environment.js +35 -1
  75. package/dist/runtime/host-load-governor-config.d.ts +33 -3
  76. package/dist/runtime/host-load-governor-config.js +24 -3
  77. package/dist/runtime/host-load-governor.d.ts +91 -2
  78. package/dist/runtime/host-load-governor.js +217 -18
  79. package/dist/runtime/host-load-ledger-lock.js +6 -4
  80. package/dist/runtime/host-load-live-test-slots.d.ts +61 -0
  81. package/dist/runtime/host-load-live-test-slots.js +193 -0
  82. package/dist/runtime/host-load-runtime-settings.js +4 -2
  83. package/dist/runtime/host-load-sampler.d.ts +25 -1
  84. package/dist/runtime/host-load-sampler.js +38 -7
  85. package/dist/runtime/host-load-step-run.d.ts +37 -3
  86. package/dist/runtime/host-load-step-run.js +63 -7
  87. package/dist/runtime/host-load-test-slot.d.ts +3 -0
  88. package/dist/runtime/host-load-test-slot.js +26 -7
  89. package/dist/runtime/host-runtime-contract.d.ts +12 -0
  90. package/dist/runtime/host-runtime-contract.js +35 -5
  91. package/dist/runtime/host-runtime-lease.d.ts +28 -3
  92. package/dist/runtime/host-runtime-lease.js +140 -296
  93. package/dist/runtime/host-runtime-ledger-recovery.d.ts +20 -0
  94. package/dist/runtime/host-runtime-ledger-recovery.js +134 -0
  95. package/dist/runtime/host-runtime-promotion.d.ts +78 -2
  96. package/dist/runtime/host-runtime-promotion.js +307 -14
  97. package/dist/runtime/managed-command-teardown.js +5 -16
  98. package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
  99. package/dist/runtime/native-test-postgres-fallback.js +60 -8
  100. package/dist/runtime/prepared-runtime-identity.d.ts +4 -0
  101. package/dist/runtime/prepared-runtime-identity.js +130 -9
  102. package/dist/runtime/prepared-runtime-readiness.d.ts +23 -1
  103. package/dist/runtime/prepared-runtime-readiness.js +89 -18
  104. package/dist/runtime/runner-settings.d.ts +4 -0
  105. package/dist/runtime/runner-settings.js +22 -0
  106. package/dist/runtime/supervised-runtime-build-guard.d.ts +45 -0
  107. package/dist/runtime/supervised-runtime-build-guard.js +112 -0
  108. package/dist/sandbox/host-capacity-broker.d.ts +3 -1
  109. package/dist/sandbox/host-capacity-broker.js +4 -2
  110. package/dist/sandbox/managed-branch.d.ts +13 -0
  111. package/dist/sandbox/managed-branch.js +90 -0
  112. package/dist/sandbox/provider-auth/codex.js +11 -11
  113. package/dist/sandbox/runtime.d.ts +1 -2
  114. package/dist/sandbox/runtime.js +9 -19
  115. package/dist/sandbox/sandbox-input.d.ts +22 -0
  116. package/dist/sandbox/sandbox-input.js +49 -0
  117. package/dist/sandbox/workspace.service.js +15 -2
  118. package/dist/session/managed-attempt-tools.d.ts +0 -7
  119. package/dist/session/managed-attempt-tools.js +54 -109
  120. package/dist/session/managed-build-coordinator.d.ts +16 -0
  121. package/dist/session/managed-build-coordinator.js +10 -0
  122. package/dist/session/managed-build-receipt.d.ts +7 -0
  123. package/dist/session/managed-build-receipt.js +11 -3
  124. package/dist/session/managed-command-environment.d.ts +8 -0
  125. package/dist/session/managed-command-environment.js +28 -0
  126. package/dist/session/managed-command-host-load.d.ts +10 -5
  127. package/dist/session/managed-command-host-load.js +18 -14
  128. package/dist/session/phase-completion.artifact-bundle.d.ts +20 -0
  129. package/dist/session/phase-completion.artifact-bundle.js +167 -0
  130. package/dist/session/phase-completion.artifacts.d.ts +2 -17
  131. package/dist/session/phase-completion.artifacts.js +65 -166
  132. package/dist/session/phase-completion.d.ts +27 -2
  133. package/dist/session/phase-completion.helpers.js +5 -53
  134. package/dist/session/phase-completion.js +15 -32
  135. package/dist/session/phase-completion.mcp-args.d.ts +9 -0
  136. package/dist/session/phase-completion.mcp-args.js +195 -0
  137. package/dist/session/phase-completion.phase-aliases.d.ts +5 -0
  138. package/dist/session/phase-completion.phase-aliases.js +43 -0
  139. package/dist/session/phase-completion.pr-review-schema.d.ts +1 -0
  140. package/dist/session/phase-completion.pr-review-schema.js +75 -0
  141. package/dist/session/phase-completion.pr-review-validation.d.ts +11 -0
  142. package/dist/session/phase-completion.pr-review-validation.js +212 -0
  143. package/dist/session/phase-completion.pr-review.d.ts +36 -0
  144. package/dist/session/phase-completion.pr-review.js +294 -0
  145. package/dist/session/phase-completion.prompts.d.ts +1 -1
  146. package/dist/session/phase-completion.prompts.js +14 -0
  147. package/dist/session/phase-completion.runtime.d.ts +8 -9
  148. package/dist/session/phase-completion.runtime.js +65 -196
  149. package/dist/session/phase-completion.schemas.js +12 -2
  150. package/dist/session/phase-completion.validation.d.ts +1 -0
  151. package/dist/session/phase-completion.validation.js +9 -1
  152. package/dist/session/pr-review-diff-base.d.ts +18 -0
  153. package/dist/session/pr-review-diff-base.js +44 -0
  154. package/dist/session/pr-review-placement.d.ts +50 -0
  155. package/dist/session/pr-review-placement.js +91 -0
  156. package/dist/session/pre-publication-change-set.d.ts +62 -0
  157. package/dist/session/pre-publication-change-set.js +166 -0
  158. package/dist/session/pre-publication-host-load.js +6 -5
  159. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  160. package/dist/session/pre-publication-native-postgres.js +111 -0
  161. package/dist/session/pre-publication-process.js +13 -12
  162. package/dist/session/pre-publication-step-execution.d.ts +2 -1
  163. package/dist/session/pre-publication-step-execution.js +6 -5
  164. package/dist/session/pre-publication-validation.d.ts +9 -4
  165. package/dist/session/pre-publication-validation.js +62 -65
  166. package/dist/session/provider-cli/claude-background-work.d.ts +3 -2
  167. package/dist/session/provider-cli/claude-background-work.js +4 -3
  168. package/dist/session/provider-cli/dispatch-target-branch.d.ts +7 -0
  169. package/dist/session/provider-cli/dispatch-target-branch.js +8 -0
  170. package/dist/session/provider-cli/host-build-lock.d.ts +18 -0
  171. package/dist/session/provider-cli/host-build-lock.js +30 -0
  172. package/dist/session/provider-cli/pr-review-credential-isolation.d.ts +83 -0
  173. package/dist/session/provider-cli/pr-review-credential-isolation.js +144 -0
  174. package/dist/session/provider-cli/pr-review-guardrails.d.ts +70 -0
  175. package/dist/session/provider-cli/pr-review-guardrails.js +360 -0
  176. package/dist/session/provider-cli/pr-review-prompt.d.ts +2 -0
  177. package/dist/session/provider-cli/pr-review-prompt.js +119 -0
  178. package/dist/session/provider-cli/pre-publication-repair.d.ts +16 -0
  179. package/dist/session/provider-cli/pre-publication-repair.js +41 -3
  180. package/dist/session/provider-cli/provider-cli.base.d.ts +1 -0
  181. package/dist/session/provider-cli/provider-cli.child-environment.js +4 -2
  182. package/dist/session/provider-cli/provider-cli.deterministic.d.ts +1 -0
  183. package/dist/session/provider-cli/provider-cli.deterministic.js +5 -0
  184. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +6 -3
  185. package/dist/session/provider-cli/provider-cli.merge-integrity.js +29 -10
  186. package/dist/session/provider-cli/provider-cli.pr-review.d.ts +23 -0
  187. package/dist/session/provider-cli/provider-cli.pr-review.js +213 -0
  188. package/dist/session/provider-cli/provider-cli.process.d.ts +2 -14
  189. package/dist/session/provider-cli/provider-cli.process.js +4 -94
  190. package/dist/session/provider-cli/provider-cli.prompts.d.ts +13 -3
  191. package/dist/session/provider-cli/provider-cli.prompts.js +137 -84
  192. package/dist/session/provider-cli/provider-cli.reapply-conflicts.d.ts +10 -0
  193. package/dist/session/provider-cli/provider-cli.reapply-conflicts.js +37 -0
  194. package/dist/session/provider-cli/provider-cli.runtime.d.ts +15 -0
  195. package/dist/session/provider-cli/provider-cli.runtime.js +37 -2
  196. package/dist/session/provider-cli/provider-cli.service-support.d.ts +37 -0
  197. package/dist/session/provider-cli/provider-cli.service-support.js +146 -0
  198. package/dist/session/provider-cli/provider-cli.service.d.ts +15 -18
  199. package/dist/session/provider-cli/provider-cli.service.js +59 -190
  200. package/dist/session/provider-cli/provider-cli.types.d.ts +7 -2
  201. package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
  202. package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
  203. package/dist/session/provider-cli/provider-user-config-isolation.d.ts +69 -0
  204. package/dist/session/provider-cli/provider-user-config-isolation.js +164 -0
  205. package/dist/session/qa-sidecar-validation.d.ts +6 -0
  206. package/dist/session/qa-sidecar-validation.js +28 -0
  207. package/dist/session/sandbox-host-capacity-gate.d.ts +22 -1
  208. package/dist/session/sandbox-host-capacity-gate.js +63 -22
  209. package/dist/session/session-host-project.d.ts +22 -0
  210. package/dist/session/session-host-project.js +98 -0
  211. package/dist/session/session-redaction.js +31 -181
  212. package/dist/session/session.parse-helpers.d.ts +10 -0
  213. package/dist/session/session.parse-helpers.js +84 -0
  214. package/dist/session/session.runtime-refresh.d.ts +46 -0
  215. package/dist/session/session.runtime-refresh.js +116 -0
  216. package/dist/session/session.service.d.ts +8 -1
  217. package/dist/session/session.service.js +177 -239
  218. package/dist/session/session.types.d.ts +5 -0
  219. package/dist/session/session.types.js +9 -79
  220. package/dist/session/session.types.pr-review.d.ts +48 -0
  221. package/dist/session/session.types.pr-review.js +51 -0
  222. package/dist/session/sidecar-json-shape.d.ts +31 -0
  223. package/dist/session/sidecar-json-shape.js +217 -0
  224. package/dist/shared/fs/file-identity.d.ts +10 -0
  225. package/dist/shared/fs/file-identity.js +15 -0
  226. package/dist/shared/fs/replace-file.d.ts +7 -0
  227. package/dist/shared/fs/replace-file.js +33 -0
  228. package/dist/shared/process/host-process-recovery.d.ts +14 -3
  229. package/dist/shared/process/host-process-recovery.js +23 -3
  230. package/dist/shared/process/host-process-supervisor.d.ts +13 -1
  231. package/dist/shared/process/host-process-supervisor.js +66 -14
  232. package/dist/shared/provider-capabilities.d.ts +2 -0
  233. package/dist/shared/provider-capabilities.js +18 -1
  234. package/dist/version.d.ts +1 -1
  235. package/dist/version.js +1 -1
  236. package/dist/worktree/artifact-injector.js +24 -0
  237. package/dist/worktree/orphan-relink.d.ts +19 -0
  238. package/dist/worktree/orphan-relink.js +106 -0
  239. package/dist/worktree/wip-git.d.ts +58 -0
  240. package/dist/worktree/wip-git.js +182 -0
  241. package/dist/worktree/wip-refs.d.ts +85 -0
  242. package/dist/worktree/wip-refs.js +169 -0
  243. package/dist/worktree/wip-restore.d.ts +51 -0
  244. package/dist/worktree/wip-restore.js +324 -0
  245. package/dist/worktree/wip-snapshot.d.ts +53 -0
  246. package/dist/worktree/wip-snapshot.js +270 -0
  247. package/dist/worktree/worktree-inputs.d.ts +8 -0
  248. package/dist/worktree/worktree-inputs.js +134 -0
  249. package/dist/worktree/worktree-origin-sync.d.ts +35 -0
  250. package/dist/worktree/worktree-origin-sync.js +128 -0
  251. package/dist/worktree/worktree-wip-events.d.ts +20 -0
  252. package/dist/worktree/worktree-wip-events.js +148 -0
  253. package/dist/worktree/worktree-wip.d.ts +57 -0
  254. package/dist/worktree/worktree-wip.js +200 -0
  255. package/dist/worktree/worktree.base.d.ts +7 -1
  256. package/dist/worktree/worktree.service.d.ts +49 -5
  257. package/dist/worktree/worktree.service.js +223 -187
  258. package/dist/worktree/worktree.types.d.ts +47 -0
  259. package/package.json +1 -1
  260. package/runtime/windows-listener-owner.ps1 +12 -1
@@ -0,0 +1,193 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import fs from "node:fs/promises";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import { reportsAvailableMemory } from "./host-load-capacity.js";
6
+ import { currentHostLoadTokenOwner, processHostLoadOwnerLiveness, } from "./host-load-token-ledger.js";
7
+ /** The sampler's fresh history as host readings; a stale history adds nothing. */
8
+ export function hostLiveReadings(context) {
9
+ const { load } = context;
10
+ const latest = load.current();
11
+ const latestAtMs = latest ? Date.parse(latest.sampledAt) : Number.NaN;
12
+ if (!latest || !Number.isFinite(latestAtMs) || context.nowMs - latestAtMs > context.sampleStaleMs)
13
+ return [];
14
+ const history = load.recent();
15
+ const samples = history.at(-1)?.sampledAt === latest.sampledAt ? history : [...history, latest];
16
+ // Each sample's own attribution, which counts Docker sandboxes as Forge's own CPU too.
17
+ const attributions = new Map();
18
+ for (const attribution of load.recentCpuAttributions?.() ?? [])
19
+ attributions.set(attribution.sampledAt, attribution);
20
+ const latestAttribution = load.cpuAttribution?.() ?? null;
21
+ if (latestAttribution)
22
+ attributions.set(latestAttribution.sampledAt, latestAttribution);
23
+ // macOS reports free pages only, which reads most of its memory as in use.
24
+ const memoryReadable = reportsAvailableMemory(load.facts()?.platform ?? process.platform);
25
+ return samples.flatMap(sample => {
26
+ const reading = liveReading(context, sample, attributions.get(sample.sampledAt) ?? null, memoryReadable);
27
+ return reading ? [reading] : [];
28
+ });
29
+ }
30
+ /**
31
+ * One sample as a host reading, stamped with the sampler's monotonic clock when it keeps one.
32
+ * With a dedicated cgroup, Forge's CPU comes from the sample's attribution (bridge and sandbox
33
+ * cgroups); a sample without one is left out rather than read with its sandboxes counted as
34
+ * other work. Forge's memory is the cgroup's anonymous memory above its idle baseline, when both
35
+ * are known.
36
+ */
37
+ function liveReading(context, sample, attribution, memoryReadable) {
38
+ const dedicated = sample.ownCgroupDedicated;
39
+ if (dedicated && !attribution)
40
+ return null;
41
+ const sampledAtMs = context.load.sampleMonotonicMs
42
+ ? context.load.sampleMonotonicMs(sample.sampledAt)
43
+ : Date.parse(sample.sampledAt);
44
+ if (sampledAtMs === null)
45
+ return null;
46
+ const ownMemory = dedicated ? sample.ownCgroup?.memoryAnonBytes ?? null : null;
47
+ return {
48
+ sampledAtMs,
49
+ hostCoresInUse: sample.hostCpuPercent === null ? null : (sample.hostCpuPercent / 100) * context.logicalCpus,
50
+ externalCoresInUse: dedicated ? attribution?.externalCoresInUse ?? null : null,
51
+ memoryAvailableBytes: memoryReadable ? sample.memoryAvailableBytes : null,
52
+ forgeMemoryBytes: ownMemory === null || context.idleOwnMemoryBytes === null
53
+ ? null
54
+ : Math.max(0, ownMemory - context.idleOwnMemoryBytes),
55
+ };
56
+ }
57
+ export function liveTestSlotsDirectory(stateRoot) {
58
+ return path.join(stateRoot, "host-load-governor", "live-test-slots");
59
+ }
60
+ /** A lowered count is rewritten this often while it holds; readers drop one older than the TTL. */
61
+ export const liveTestSlotsRefreshMs = 30_000;
62
+ export const liveTestSlotsTtlMs = 90_000;
63
+ /** A file this old belongs to a governor that is gone: any reader removes it. */
64
+ const abandonedMs = 10 * 60_000;
65
+ /** The most published counts read in one pass. */
66
+ const maximumEntries = 64;
67
+ /**
68
+ * This governor's lowered count, shared with every governor on the state root, and theirs read
69
+ * back. Each governor writes a file of its own (no two processes write one file); it is
70
+ * written while the count is lowered (when it changes, and every refresh period while the
71
+ * controller takes in fresh readings) and removed once the count is back. A file whose writer
72
+ * stopped refreshing it lapses after the TTL: a writer whose sampler went quiet stops
73
+ * refreshing, so a reduction nothing confirms any more does not hold every governor back.
74
+ * A reader skips a file another host wrote and removes one whose writer is gone. Times are
75
+ * wall-clock: they are compared across processes.
76
+ */
77
+ export class LiveTestSlotsBoard {
78
+ directory;
79
+ fileName = `${randomUUID()}.json`;
80
+ now;
81
+ liveness;
82
+ hostname;
83
+ published = null;
84
+ /** When a pass last took in a fresh reading for this governor's count. */
85
+ freshAtMs = null;
86
+ writing = Promise.resolve();
87
+ constructor(stateRoot, options = {}) {
88
+ this.directory = liveTestSlotsDirectory(stateRoot);
89
+ this.now = options.now ?? Date.now;
90
+ this.liveness = options.liveness ?? processHostLoadOwnerLiveness;
91
+ this.hostname = options.hostname ?? os.hostname();
92
+ }
93
+ /**
94
+ * Publishes this governor's own count (never one it adopted from another). `freshReading` says
95
+ * whether the pass behind it took in a new reading: an unchanged count is rewritten only while
96
+ * one came in within the TTL, so it lapses once the sampler goes quiet.
97
+ */
98
+ publish(own, configured, freshReading) {
99
+ const nowMs = this.now();
100
+ if (freshReading)
101
+ this.freshAtMs = nowMs;
102
+ const filePath = path.join(this.directory, this.fileName);
103
+ if (own.slots >= configured) {
104
+ if (this.published === null)
105
+ return;
106
+ this.published = null;
107
+ this.enqueue(async () => await fs.rm(filePath, { force: true }));
108
+ return;
109
+ }
110
+ const previous = this.published;
111
+ if (previous?.slots === own.slots && previous.detail === own.detail) {
112
+ const confirmed = this.freshAtMs !== null && nowMs - this.freshAtMs <= liveTestSlotsTtlMs;
113
+ if (!confirmed || nowMs - previous.atMs < liveTestSlotsRefreshMs)
114
+ return;
115
+ }
116
+ this.published = { slots: own.slots, detail: own.detail, atMs: nowMs };
117
+ const entry = {
118
+ schemaVersion: 1,
119
+ writer: currentHostLoadTokenOwner(),
120
+ hostname: this.hostname,
121
+ slots: own.slots,
122
+ detail: own.detail,
123
+ writtenAt: new Date(nowMs).toISOString(),
124
+ };
125
+ this.enqueue(async () => {
126
+ await fs.mkdir(this.directory, { recursive: true, mode: 0o700 });
127
+ const temporary = `${filePath}.${process.pid}.${randomUUID()}.tmp`;
128
+ try {
129
+ await fs.writeFile(temporary, `${JSON.stringify(entry)}\n`, { mode: 0o600 });
130
+ await fs.rename(temporary, filePath);
131
+ }
132
+ catch (error) {
133
+ await fs.rm(temporary, { force: true }).catch(() => undefined);
134
+ throw error;
135
+ }
136
+ });
137
+ }
138
+ /** The lowest count another governor on this state root has in force; null when none is lowered. */
139
+ async lowest() {
140
+ const names = await fs.readdir(this.directory).catch(() => []);
141
+ const nowMs = this.now();
142
+ let lowest = null;
143
+ for (const name of names.filter(entry => entry.endsWith(".json") && entry !== this.fileName).slice(0, maximumEntries)) {
144
+ const filePath = path.join(this.directory, name);
145
+ const entry = await fs.readFile(filePath, "utf8").then(parseEntry).catch(() => null);
146
+ const ageMs = entry ? nowMs - Date.parse(entry.writtenAt) : Number.NaN;
147
+ // Another host's pid cannot be checked here, and its load is not this host's.
148
+ if (entry && entry.hostname !== this.hostname)
149
+ continue;
150
+ const writerGone = entry !== null && !this.liveness.isLive(entry.writer);
151
+ if (ageMs > abandonedMs || writerGone)
152
+ void fs.rm(filePath, { force: true }).catch(() => undefined);
153
+ // A clock stepped far back makes an entry look written in the future: it is not trusted either.
154
+ if (!entry || writerGone || !(Math.abs(ageMs) <= liveTestSlotsTtlMs))
155
+ continue;
156
+ if (!lowest || entry.slots < lowest.slots)
157
+ lowest = { slots: entry.slots, detail: entry.detail };
158
+ }
159
+ return lowest;
160
+ }
161
+ /** Settles once every publish so far is on disk (tests). */
162
+ async flushed() {
163
+ await this.writing;
164
+ }
165
+ enqueue(write) {
166
+ this.writing = this.writing.then(write).catch(() => undefined);
167
+ }
168
+ }
169
+ function parseEntry(content) {
170
+ const raw = JSON.parse(content);
171
+ if (!raw || raw.schemaVersion !== 1 || typeof raw.writtenAt !== "string" || typeof raw.hostname !== "string")
172
+ return null;
173
+ const writer = parseWriter(raw.writer);
174
+ const slots = raw.slots;
175
+ if (!writer || typeof slots !== "number" || !Number.isInteger(slots) || slots < 1)
176
+ return null;
177
+ return {
178
+ schemaVersion: 1,
179
+ writer,
180
+ hostname: raw.hostname,
181
+ slots: Math.min(8, slots),
182
+ detail: typeof raw.detail === "string" ? raw.detail.slice(0, 500) : "",
183
+ writtenAt: raw.writtenAt,
184
+ };
185
+ }
186
+ function parseWriter(raw) {
187
+ if (!raw || typeof raw !== "object")
188
+ return null;
189
+ const { pid, processIdentity, processInstanceId } = raw;
190
+ if (typeof pid !== "number" || !Number.isSafeInteger(pid) || pid <= 0 || typeof processInstanceId !== "string")
191
+ return null;
192
+ return { pid, processIdentity: typeof processIdentity === "string" ? processIdentity : null, processInstanceId };
193
+ }
@@ -1,6 +1,7 @@
1
1
  import fs from "node:fs/promises";
2
2
  import path from "node:path";
3
3
  import { randomUUID } from "node:crypto";
4
+ import { fileIdentityKey } from "../shared/fs/file-identity.js";
4
5
  export function hostLoadRuntimeSettingsPath(stateRoot) {
5
6
  return path.join(stateRoot, "host-load-governor", "runner-settings.v1.json");
6
7
  }
@@ -45,8 +46,9 @@ export class HostLoadRuntimeSettingsReader {
45
46
  async read() {
46
47
  let key;
47
48
  try {
48
- const stat = await fs.stat(this.filePath);
49
- key = `${stat.mtimeMs}:${stat.ctimeMs}:${stat.size}:${stat.ino}`;
49
+ // Exact (bigint) stats: a replaced file whose rounded Windows id matched would read as unchanged.
50
+ const stat = await fs.stat(this.filePath, { bigint: true });
51
+ key = `${stat.mtimeNs}:${stat.ctimeNs}:${stat.size}:${fileIdentityKey(stat)}`;
50
52
  }
51
53
  catch {
52
54
  this.cachedKey = null;
@@ -40,6 +40,12 @@ export interface HostLoadSnapshot {
40
40
  /** Reported only for a dedicated unit; never a shared terminal/session/app scope. */
41
41
  readonly ownCgroup: HostOwnCgroupLoad | null;
42
42
  readonly memoryAvailableBytes: number | null;
43
+ /**
44
+ * Busy share (0-100) of all logical CPUs over the last sampling window: /proc/stat deltas
45
+ * on Linux, os.cpus() deltas on Windows. Null on the first sample, after a break in
46
+ * readings, and on other platforms. For display only; the governor gates on pressure.
47
+ */
48
+ readonly hostCpuPercent: number | null;
43
49
  }
44
50
  /** What the bridge service needs: static facts plus the latest cached load sample. */
45
51
  export interface HostLoadSource {
@@ -70,6 +76,17 @@ export interface HostCpuAttribution {
70
76
  /** The governor's view: the load sample plus the CPU attribution from the same window. */
71
77
  export interface HostLoadGovernorSource extends Pick<HostLoadSource, "start" | "facts" | "current" | "recent"> {
72
78
  cpuAttribution?(): HostCpuAttribution | null;
79
+ /**
80
+ * The CPU attribution of each sample in recent(), oldest first, matched by sampledAt. It
81
+ * counts the Docker sandbox cgroups as Forge's own, which the snapshots' ownCgroup does not.
82
+ */
83
+ recentCpuAttributions?(): readonly HostCpuAttribution[];
84
+ /**
85
+ * When a sample in recent() was taken on the sampler's monotonic clock (ms), matched by
86
+ * sampledAt; null for one it does not know. Readings are ordered and timed by it, so a
87
+ * wall-clock step (NTP, resume) cannot reorder them.
88
+ */
89
+ sampleMonotonicMs?(sampledAt: string): number | null;
73
90
  /**
74
91
  * Free memory under the tightest cgroup `memory.max` on the bridge's path
75
92
  * (null when none is set), from the latest sample. The governor budgets
@@ -109,6 +126,10 @@ export declare class HostLoadSampler implements HostLoadSource {
109
126
  private hostFacts;
110
127
  private latest;
111
128
  private readonly history;
129
+ private readonly attributionHistory;
130
+ /** Each kept sample's monotonic time, by sampledAt (insertion order is sample order). */
131
+ private readonly monotonicStamps;
132
+ private readMonotonicMs;
112
133
  private cpuMark;
113
134
  private hostCpuMark;
114
135
  private latestCpuAttribution;
@@ -123,6 +144,8 @@ export declare class HostLoadSampler implements HostLoadSource {
123
144
  cpuAttribution(): HostCpuAttribution | null;
124
145
  cgroupMemoryHeadroomBytes(): number | null;
125
146
  recent(): readonly HostLoadSnapshot[];
147
+ recentCpuAttributions(): readonly HostCpuAttribution[];
148
+ sampleMonotonicMs(sampledAt: string): number | null;
126
149
  /** Detects static facts once, takes a first sample, then samples on the interval. Idempotent. */
127
150
  start(): Promise<void>;
128
151
  stop(): void;
@@ -142,7 +165,8 @@ export declare class HostLoadSampler implements HostLoadSource {
142
165
  private readSystemPressure;
143
166
  private readOwnCgroup;
144
167
  private coresInUse;
145
- private readHostCoresInUse;
168
+ /** Busy share (0-1) of all logical CPUs since the last /proc/stat reading. */
169
+ private readHostCpuUse;
146
170
  private readMemoryAvailable;
147
171
  private fallbackFreeMemory;
148
172
  private readPressure;
@@ -25,6 +25,10 @@ export class HostLoadSampler {
25
25
  hostFacts = null;
26
26
  latest = null;
27
27
  history = [];
28
+ attributionHistory = [];
29
+ /** Each kept sample's monotonic time, by sampledAt (insertion order is sample order). */
30
+ monotonicStamps = new Map();
31
+ readMonotonicMs = 0;
28
32
  cpuMark = null;
29
33
  hostCpuMark = null;
30
34
  latestCpuAttribution = null;
@@ -61,6 +65,12 @@ export class HostLoadSampler {
61
65
  recent() {
62
66
  return [...this.history];
63
67
  }
68
+ recentCpuAttributions() {
69
+ return [...this.attributionHistory];
70
+ }
71
+ sampleMonotonicMs(sampledAt) {
72
+ return this.monotonicStamps.get(sampledAt) ?? null;
73
+ }
64
74
  /** Detects static facts once, takes a first sample, then samples on the interval. Idempotent. */
65
75
  start() {
66
76
  if (this.timer)
@@ -88,6 +98,19 @@ export class HostLoadSampler {
88
98
  this.history.push(snapshot);
89
99
  if (this.history.length > retainedSampleCount)
90
100
  this.history.splice(0, this.history.length - retainedSampleCount);
101
+ this.monotonicStamps.set(snapshot.sampledAt, this.readMonotonicMs);
102
+ for (const stamp of this.monotonicStamps.keys()) {
103
+ if (this.monotonicStamps.size <= retainedSampleCount)
104
+ break;
105
+ this.monotonicStamps.delete(stamp);
106
+ }
107
+ const attribution = this.latestCpuAttribution;
108
+ if (attribution?.sampledAt === snapshot.sampledAt) {
109
+ this.attributionHistory.push(attribution);
110
+ if (this.attributionHistory.length > retainedSampleCount) {
111
+ this.attributionHistory.splice(0, this.attributionHistory.length - retainedSampleCount);
112
+ }
113
+ }
91
114
  return snapshot;
92
115
  })
93
116
  .finally(() => {
@@ -111,15 +134,16 @@ export class HostLoadSampler {
111
134
  async readSnapshot() {
112
135
  const sampledAtMs = this.now();
113
136
  const monotonicMs = this.monotonicNow();
137
+ this.readMonotonicMs = monotonicMs;
114
138
  if (this.environment.platform === "win32")
115
139
  return this.readWindowsSnapshot(sampledAtMs, monotonicMs);
116
140
  const linux = this.environment.platform === "linux";
117
- const [systemPressure, ownCgroup, memoryAvailableBytes, hostCoresInUse, cgroupMemoryHeadroomBytes, sandboxCores] = linux
141
+ const [systemPressure, ownCgroup, memoryAvailableBytes, hostCpu, cgroupMemoryHeadroomBytes, sandboxCores] = linux
118
142
  ? await Promise.all([
119
143
  this.readSystemPressure(),
120
144
  this.readOwnCgroup(monotonicMs),
121
145
  this.readMemoryAvailable(),
122
- this.readHostCoresInUse(),
146
+ this.readHostCpuUse(),
123
147
  this.readCgroupMemoryHeadroom(),
124
148
  Promise.resolve(this.forgeCgroups?.paths() ?? [])
125
149
  .then(paths => this.sandboxCpu.coresInUse(paths, monotonicMs)).catch(() => 0),
@@ -129,7 +153,7 @@ export class HostLoadSampler {
129
153
  // Docker sandbox CPU is Forge's own work, already counted through reserved cost.
130
154
  const ownCores = ownCgroup?.cpuCoresInUse ?? null;
131
155
  this.latestMemoryHeadroom = cgroupMemoryHeadroomBytes;
132
- this.latestCpuAttribution = hostCpuAttribution(sampledAt, hostCoresInUse, ownCores === null ? null : ownCores + sandboxCores);
156
+ this.latestCpuAttribution = hostCpuAttribution(sampledAt, hostCpu === null ? null : roundCores(hostCpu.utilisation * hostCpu.cpuCount), ownCores === null ? null : ownCores + sandboxCores);
133
157
  return {
134
158
  sampledAt,
135
159
  psiAvailable: systemPressure !== null,
@@ -138,6 +162,7 @@ export class HostLoadSampler {
138
162
  ownCgroupDedicated: ownCgroup !== null,
139
163
  ownCgroup,
140
164
  memoryAvailableBytes,
165
+ hostCpuPercent: hostCpu === null ? null : hostCpuPercent(hostCpu.utilisation),
141
166
  };
142
167
  }
143
168
  /**
@@ -174,7 +199,7 @@ export class HostLoadSampler {
174
199
  const cpu = utilisation === null ? null : this.windowsCpuPressure.update(utilisation, elapsedMs);
175
200
  this.latestMemoryHeadroom = null;
176
201
  this.latestCpuAttribution = hostCpuAttribution(sampledAt, utilisation !== null && totals ? roundCores(utilisation * totals.cpuCount) : null, null);
177
- return windowsSnapshot(sampledAt, cpu, this.fallbackFreeMemory());
202
+ return windowsSnapshot(sampledAt, cpu, this.fallbackFreeMemory(), utilisation === null ? null : hostCpuPercent(utilisation));
178
203
  }
179
204
  async readCgroupMemoryHeadroom() {
180
205
  const membership = await readOptional(this.environment, path.posix.join(this.environment.procRoot, "self", "cgroup"));
@@ -231,7 +256,8 @@ export class HostLoadSampler {
231
256
  return null;
232
257
  return roundCores(usedUsec / elapsedUsec);
233
258
  }
234
- async readHostCoresInUse() {
259
+ /** Busy share (0-1) of all logical CPUs since the last /proc/stat reading. */
260
+ async readHostCpuUse() {
235
261
  const content = await readOptional(this.environment, path.posix.join(this.environment.procRoot, "stat"));
236
262
  const totals = content ? parseProcStatCpuTotals(content) : null;
237
263
  const previous = this.hostCpuMark;
@@ -242,7 +268,7 @@ export class HostLoadSampler {
242
268
  const busyDelta = totals.busyTicks - previous.busyTicks;
243
269
  if (totalDelta <= 0 || busyDelta < 0)
244
270
  return null;
245
- return roundCores((busyDelta / totalDelta) * totals.cpuCount);
271
+ return { utilisation: Math.min(1, busyDelta / totalDelta), cpuCount: totals.cpuCount };
246
272
  }
247
273
  async readMemoryAvailable() {
248
274
  const meminfo = await readOptional(this.environment, path.posix.join(this.environment.procRoot, "meminfo"));
@@ -264,7 +290,7 @@ export class HostLoadSampler {
264
290
  }
265
291
  /** Windows CPU deltas shorter than this are too noisy to fold into the pressure estimate. */
266
292
  const minimumWindowsCpuWindowMs = 250;
267
- function windowsSnapshot(sampledAt, cpu, memoryAvailableBytes) {
293
+ function windowsSnapshot(sampledAt, cpu, memoryAvailableBytes, cpuPercent) {
268
294
  return {
269
295
  sampledAt,
270
296
  psiAvailable: cpu !== null,
@@ -273,11 +299,16 @@ function windowsSnapshot(sampledAt, cpu, memoryAvailableBytes) {
273
299
  ownCgroupDedicated: false,
274
300
  ownCgroup: null,
275
301
  memoryAvailableBytes,
302
+ hostCpuPercent: cpuPercent,
276
303
  };
277
304
  }
278
305
  function roundCores(value) {
279
306
  return Math.round(value * 100) / 100;
280
307
  }
308
+ /** A 0-1 busy share as a percentage with two decimals. */
309
+ function hostCpuPercent(utilisation) {
310
+ return Math.round(Math.min(1, Math.max(0, utilisation)) * 10_000) / 100;
311
+ }
281
312
  function hostCpuAttribution(sampledAt, hostCoresInUse, ownCoresInUse) {
282
313
  if (hostCoresInUse === null)
283
314
  return null;
@@ -1,5 +1,5 @@
1
1
  import type { HostLoadAdmissionDecision } from "./host-load-admission.js";
2
- import type { HostLoadAdmission, HostLoadStepGate } from "./host-load-governor.js";
2
+ import { type HostLoadAdmission, type HostLoadStepGate } from "./host-load-governor.js";
3
3
  import type { HostLoadStepProcess } from "./host-load-step-reaper.js";
4
4
  import type { HostLoadStepClassification } from "./host-load-step-class.js";
5
5
  import type { HostLoadTokenPriority } from "./host-load-token-ledger.js";
@@ -10,8 +10,8 @@ export interface HostGovernedStep {
10
10
  readonly dispatchAttemptId: string | null;
11
11
  readonly priority: HostLoadTokenPriority;
12
12
  readonly signal?: AbortSignal;
13
- /** Called once, when the step first has to wait for capacity. */
14
- readonly onWaiting?: (decision: HostLoadAdmissionDecision) => void | Promise<void>;
13
+ /** Called when the step first has to wait for capacity, and again whenever that wait changes. */
14
+ readonly onWaiting?: (decision: HostLoadAdmissionDecision, fence: WaitReportFence) => void | Promise<void>;
15
15
  /**
16
16
  * The step records its own fenced outcome (a managed command's receipt). Otherwise a
17
17
  * step whose token was reclaimed while it ran fails with host_capacity_token_fenced.
@@ -53,6 +53,40 @@ export declare function retentionFor(error: unknown): HostLoadRetention | null;
53
53
  * is returned when `run` settles, whether it succeeded, failed or was stopped.
54
54
  */
55
55
  export declare function runHostGovernedStep<T>(gate: HostLoadStepGate | undefined, step: HostGovernedStep, run: (hostLoadWaitMs: HostLoadWait, control: HostLoadStepControl) => Promise<T>): Promise<T>;
56
+ /** A step's wait reports, run in order; see orderedWaitReports. */
57
+ export interface OrderedWaitReports {
58
+ readonly onWaiting: ((decision: HostLoadAdmissionDecision) => void) | undefined;
59
+ /**
60
+ * Resolves once every report made so far has landed, or after the governor's drain bound
61
+ * (afterNotified) at the latest. Either way the reports are then closed: one still queued, or
62
+ * made later, is dropped as stale and never runs, and one still running can no longer commit
63
+ * (WaitReportFence). A commit already under way is awaited, so it lands before what follows.
64
+ */
65
+ drained(): Promise<void>;
66
+ }
67
+ /**
68
+ * Handed to each wait report. The bound in `drained` stops waiting for a report, not the report
69
+ * itself, so a slow write that finally succeeds would land after the step's own state. A report
70
+ * that replaces durable state (a receipt) makes that last replace through `commit`: it then runs
71
+ * only while the reports are open, and never after the step's state is written.
72
+ */
73
+ export interface WaitReportFence {
74
+ /** False once the reports are closed. */
75
+ readonly current: boolean;
76
+ /** Runs `replace` only while the reports are open; false when it was skipped as stale. */
77
+ commit(replace: () => Promise<void>): Promise<boolean>;
78
+ }
79
+ /**
80
+ * Runs a step's wait reports one at a time, in the order they were made, and hands the governor a
81
+ * callback that returns at once. The governor waits only a few seconds for a report (afterNotified),
82
+ * so a report it waited on could still land after the step's admitted or failed state. The step
83
+ * awaits `drained` before writing that state instead, so a late "waiting" can never replace it.
84
+ * `drained` keeps the governor's bound, so a report that never settles (a stuck checkpoint or
85
+ * event) cannot hold the step's admission, or its failure, back for longer than that. A report
86
+ * still running after the bound can no longer replace a receipt (WaitReportFence.commit); an
87
+ * appended event it already sent stays in the log as history of the wait, which it was.
88
+ */
89
+ export declare function orderedWaitReports(report: ((decision: HostLoadAdmissionDecision, fence: WaitReportFence) => void | Promise<void>) | undefined): OrderedWaitReports;
56
90
  /**
57
91
  * Returns a step's token, unless part of its process tree could not be proven
58
92
  * gone: the token (and its cost) is then kept until the tree is.
@@ -1,5 +1,6 @@
1
1
  import fs from "node:fs/promises";
2
2
  import { isProcessTreeTerminationUnproven, ProcessTreeTerminationError } from "../shared/process/process.js";
3
+ import { afterNotified } from "./host-load-governor.js";
3
4
  /**
4
5
  * The retention a step's failure calls for: a tree that could not be proven gone,
5
6
  * whether the runner said so with its own check (ProcessTreeTerminationError) or a
@@ -21,13 +22,21 @@ export function retentionFor(error) {
21
22
  export async function runHostGovernedStep(gate, step, run) {
22
23
  if (!gate?.enabled)
23
24
  return await run(null, {});
24
- const admission = await gate.acquire({
25
- stepClass: step.classification.stepClass,
26
- label: step.label,
27
- cost: step.classification.cost,
28
- dispatchAttemptId: step.dispatchAttemptId,
29
- priority: step.priority,
30
- }, { signal: step.signal, onWaiting: step.onWaiting });
25
+ const reports = orderedWaitReports(step.onWaiting);
26
+ let admission;
27
+ try {
28
+ admission = await gate.acquire({
29
+ stepClass: step.classification.stepClass,
30
+ label: step.label,
31
+ cost: step.classification.cost,
32
+ dispatchAttemptId: step.dispatchAttemptId,
33
+ priority: step.priority,
34
+ }, { signal: step.signal, onWaiting: reports.onWaiting });
35
+ }
36
+ finally {
37
+ // Every wait report lands before the step's own outcome (its launch, or why it was never admitted).
38
+ await reports.drained();
39
+ }
31
40
  let retention = null;
32
41
  try {
33
42
  let outcome;
@@ -55,6 +64,53 @@ export async function runHostGovernedStep(gate, step, run) {
55
64
  await returnHostLoadToken(admission, retention, step.onReleaseFailed);
56
65
  }
57
66
  }
67
+ /**
68
+ * Runs a step's wait reports one at a time, in the order they were made, and hands the governor a
69
+ * callback that returns at once. The governor waits only a few seconds for a report (afterNotified),
70
+ * so a report it waited on could still land after the step's admitted or failed state. The step
71
+ * awaits `drained` before writing that state instead, so a late "waiting" can never replace it.
72
+ * `drained` keeps the governor's bound, so a report that never settles (a stuck checkpoint or
73
+ * event) cannot hold the step's admission, or its failure, back for longer than that. A report
74
+ * still running after the bound can no longer replace a receipt (WaitReportFence.commit); an
75
+ * appended event it already sent stays in the log as history of the wait, which it was.
76
+ */
77
+ export function orderedWaitReports(report) {
78
+ let chain = Promise.resolve();
79
+ let closed = false;
80
+ let committing = Promise.resolve();
81
+ const fence = {
82
+ get current() { return !closed; },
83
+ commit: async (replace) => {
84
+ if (closed)
85
+ return false;
86
+ // Started while open: `drained` waits for it, so it cannot land after the step's state.
87
+ const replaced = replace();
88
+ committing = replaced.catch(() => undefined);
89
+ await replaced;
90
+ return true;
91
+ },
92
+ };
93
+ return {
94
+ onWaiting: report ? decision => {
95
+ if (closed)
96
+ return;
97
+ chain = chain.then(async () => { if (!closed)
98
+ await report(decision, fence); }).catch(() => undefined);
99
+ } : undefined,
100
+ drained: async () => {
101
+ // Once closed nothing new runs or commits: a report still in flight was already given its bound.
102
+ if (closed)
103
+ return;
104
+ try {
105
+ await afterNotified(chain);
106
+ }
107
+ finally {
108
+ closed = true;
109
+ }
110
+ await committing;
111
+ },
112
+ };
113
+ }
58
114
  /**
59
115
  * Returns a step's token, unless part of its process tree could not be proven
60
116
  * gone: the token (and its cost) is then kept until the tree is.
@@ -28,7 +28,10 @@ export interface HostTestSlotInput {
28
28
  readonly queue: readonly HostTestSlotTicketRequest[];
29
29
  /** Every live token on the host; fenced and degraded ones still hold their slot. */
30
30
  readonly tokens: readonly HostLoadToken[];
31
+ /** The count in force: the configured count, or lower while other work needs the host. */
31
32
  readonly testSlots: number;
33
+ /** Why testSlots is below the configured count (host-load-capacity.ts); empty or absent when it is not. */
34
+ readonly testSlotsDetail?: string;
32
35
  readonly nowMs: number;
33
36
  readonly antiStarvationMs: number;
34
37
  }
@@ -48,22 +48,41 @@ export function decideHostTestSlot(input) {
48
48
  return { ...reserved, admitted, reason: "admitted_test_slot", detail: "The host test slot is free." };
49
49
  }
50
50
  const heldBy = holders.length > 0
51
- ? `held by ${holders.map(describeHolder).join("; ")}`
51
+ ? `held by ${holders.map(token => describeHolder(token, input.ticket.dispatchAttemptId)).join("; ")}`
52
52
  : "the steps ahead of this one take it first";
53
53
  return {
54
54
  ...reserved,
55
55
  admitted,
56
56
  reason: "host_test_slot",
57
- detail: `Waiting for the host test slot (${input.testSlots} at once): ${heldBy}; ${ahead} step(s) ahead in the host queue.`,
57
+ detail: `Waiting for the host test slot (${input.testSlots} at once${input.testSlotsDetail ? `, ${input.testSlotsDetail}` : ""}): ${heldBy}; ${ahead} step(s) ahead in the host queue.`,
58
+ // Only a running, healthy holder is progress. With no holder the steps ahead are waiting too (for
59
+ // the budget, say), and that wait must count as stalled, not reset the clock.
60
+ progressing: holders.length > 0 && holders.every(healthyHolder),
58
61
  };
59
62
  }
60
- function describeHolder(token) {
63
+ /** A holder whose step is still running under a live, renewed lease; the ledger reclaims the rest. */
64
+ function healthyHolder(token) {
65
+ return !token.degradedAt && !token.fencedAt && !token.retainedAt;
66
+ }
67
+ /**
68
+ * Names the holder for the waiting step's agent: whose step it is and since when. A step
69
+ * label alone reads like the agent's own: an agent that saw "held by dotnet_api_component"
70
+ * took another session's live test run for its own finished one and gave up the wait.
71
+ */
72
+ function describeHolder(token, waiterAttemptId) {
61
73
  const attempt = token.dispatchAttemptId ? `, attempt ${token.dispatchAttemptId}` : "";
74
+ const whose = !token.dispatchAttemptId ? ""
75
+ : token.dispatchAttemptId === waiterAttemptId ? ", this session's own step" : ", another session's step";
76
+ const admittedAtMs = Date.parse(token.admittedAt);
77
+ const since = Number.isFinite(admittedAtMs)
78
+ ? ` since ${new Date(admittedAtMs).toISOString().replace(/\.\d{3}Z$/u, "Z")}`
79
+ : "";
62
80
  const state = token.degradedAt
63
- ? ", whose owner is gone; it is returned once its processes are stopped"
64
- : token.fencedAt ? ", which is past its lease"
65
- : token.retainedAt ? ", whose processes could not be proven stopped; it is returned at attempt teardown" : "";
66
- return `${token.label} (${token.stepClass}${attempt}${state})`;
81
+ ? `, held${since}; its owner is gone, and it is returned once its processes are stopped`
82
+ : token.fencedAt ? `, held${since} and past its lease`
83
+ : token.retainedAt ? `, held${since}; its processes could not be proven stopped, and it is returned at attempt teardown`
84
+ : `, still running${since}`;
85
+ return `${token.label} (${token.stepClass}${attempt}${whose}${state})`;
67
86
  }
68
87
  /** A ticket read back from the ledger; a malformed one is dropped, never trusted. */
69
88
  export function validHostTestSlotTicket(value) {
@@ -57,6 +57,18 @@ export interface HostRuntimeDirectoryEntry {
57
57
  /** Returns one identity-bound directory inventory for runtime discovery. */
58
58
  export type HostRuntimeDirectorySnapshot = (target: string) => Promise<readonly HostRuntimeDirectoryEntry[]>;
59
59
  export declare function loadHostRuntimeContract(worktreePath: string, snapshot?: HostRuntimeSourceSnapshot, directorySnapshot?: HostRuntimeDirectorySnapshot): Promise<LoadedHostRuntimeContract>;
60
+ /** A managed attempt's own API master key: 32 random bytes, base64-encoded, as Security:MasterKey expects. */
61
+ export declare function newAttemptApiMasterKey(): string;
62
+ /**
63
+ * The environment a managed attempt's ASP.NET API launches with. When neither the launch profile
64
+ * nor the runtime contract configures Security__MasterKey or Security__MasterKeyFile, the API gets
65
+ * the attempt's own key. Otherwise ASP.NET Development falls back to the host user's dotnet
66
+ * user-secrets: the host's own key where they exist, and a failed secret write wherever they do not.
67
+ * The caller keeps one key for the attempt's whole life, so a restart against the same attempt
68
+ * database can still decrypt what was stored before it. The key is a secret: it is for the API
69
+ * process only, never for the environment handed to checks or providers.
70
+ */
71
+ export declare function withAttemptApiMasterKey(port: HostRuntimePortConfig, environment: Readonly<Record<string, string>>, attemptMasterKey: string): Readonly<Record<string, string>>;
60
72
  export declare function defaultHostRuntimeContract(): HostRuntimeContract;
61
73
  export declare function validateHostRuntimeContract(source: string): HostRuntimeContract;
62
74
  export declare function hostPortEnvironment(config: HostRuntimePortConfig, hostIp: "127.0.0.1", hostPort: number): Readonly<Record<string, string>>;