@loucompanion/forge-bridge 0.1.4-dev.8901ba056f68 → 0.1.4-dev.91ee995ac965

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 (210) hide show
  1. package/README.md +142 -1
  2. package/dist/bridge/bridge-chat-provider-command.d.ts +19 -0
  3. package/dist/bridge/bridge-chat-provider-command.js +132 -0
  4. package/dist/bridge/bridge-chat.types.d.ts +10 -0
  5. package/dist/bridge/bridge-chat.types.js +16 -1
  6. package/dist/bridge/bridge-state-file.d.ts +161 -0
  7. package/dist/bridge/bridge-state-file.js +376 -0
  8. package/dist/bridge/bridge-state-io.d.ts +11 -0
  9. package/dist/bridge/bridge-state-io.js +50 -0
  10. package/dist/bridge/bridge-state-lock.d.ts +11 -0
  11. package/dist/bridge/bridge-state-lock.js +102 -0
  12. package/dist/bridge/bridge-state-unpublished.d.ts +17 -0
  13. package/dist/bridge/bridge-state-unpublished.js +111 -0
  14. package/dist/bridge/bridge.base.d.ts +9 -0
  15. package/dist/bridge/bridge.service.d.ts +87 -14
  16. package/dist/bridge/bridge.service.js +394 -338
  17. package/dist/bridge/bridge.types.d.ts +16 -0
  18. package/dist/bridge/in-flight-registry.d.ts +62 -0
  19. package/dist/bridge/in-flight-registry.js +207 -0
  20. package/dist/bridge/local-yield-flag.d.ts +6 -0
  21. package/dist/bridge/local-yield-flag.js +34 -0
  22. package/dist/bridge/readiness-result-outbox.d.ts +5 -1
  23. package/dist/bridge/readiness-result-outbox.js +20 -0
  24. package/dist/bridge/runner-host-capabilities.d.ts +3 -0
  25. package/dist/bridge/runner-host-capabilities.js +13 -0
  26. package/dist/bridge/sandbox-resource-accounting.d.ts +16 -0
  27. package/dist/bridge/sandbox-resource-accounting.js +150 -0
  28. package/dist/cleanup/cleanup-wip.d.ts +12 -0
  29. package/dist/cleanup/cleanup-wip.js +66 -0
  30. package/dist/cleanup/cleanup.service.d.ts +20 -1
  31. package/dist/cleanup/cleanup.service.js +154 -153
  32. package/dist/cleanup/cleanup.types.d.ts +6 -0
  33. package/dist/cleanup/forge-owned-paths.d.ts +9 -0
  34. package/dist/cleanup/forge-owned-paths.js +53 -0
  35. package/dist/cleanup/host-runtime-ledger.d.ts +5 -0
  36. package/dist/cleanup/host-runtime-ledger.js +109 -0
  37. package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
  38. package/dist/cleanup/managed-branch-sweep.js +111 -0
  39. package/dist/cli/cli.help.js +74 -12
  40. package/dist/cli/cli.service.d.ts +19 -10
  41. package/dist/cli/cli.service.js +149 -186
  42. package/dist/cli/idle-status.d.ts +84 -0
  43. package/dist/cli/idle-status.js +181 -0
  44. package/dist/cli/local-config.d.ts +6 -0
  45. package/dist/cli/local-config.js +32 -4
  46. package/dist/cli/provider-cli-detection.d.ts +10 -0
  47. package/dist/cli/provider-cli-detection.js +160 -0
  48. package/dist/runtime/aspnet-runtime-prebuild.d.ts +5 -0
  49. package/dist/runtime/aspnet-runtime-prebuild.js +140 -7
  50. package/dist/runtime/attempt-database-broker.d.ts +1 -1
  51. package/dist/runtime/docker-engine-probe.d.ts +5 -0
  52. package/dist/runtime/docker-engine-probe.js +7 -0
  53. package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
  54. package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
  55. package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
  56. package/dist/runtime/ephemeral-test-postgres.js +303 -0
  57. package/dist/runtime/host-facts.d.ts +2 -1
  58. package/dist/runtime/host-load-admission.d.ts +18 -3
  59. package/dist/runtime/host-load-admission.js +19 -4
  60. package/dist/runtime/host-load-child-environment.d.ts +11 -6
  61. package/dist/runtime/host-load-child-environment.js +22 -11
  62. package/dist/runtime/host-load-governor-config.d.ts +19 -1
  63. package/dist/runtime/host-load-governor-config.js +37 -0
  64. package/dist/runtime/host-load-governor.d.ts +14 -0
  65. package/dist/runtime/host-load-governor.js +139 -26
  66. package/dist/runtime/host-load-ledger-lock.js +6 -4
  67. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  68. package/dist/runtime/host-load-runtime-settings.js +80 -0
  69. package/dist/runtime/host-load-sampler.d.ts +34 -4
  70. package/dist/runtime/host-load-sampler.js +73 -7
  71. package/dist/runtime/host-load-step-class.d.ts +3 -1
  72. package/dist/runtime/host-load-step-class.js +60 -5
  73. package/dist/runtime/host-load-test-slot.d.ts +43 -0
  74. package/dist/runtime/host-load-test-slot.js +81 -0
  75. package/dist/runtime/host-load-token-ledger.d.ts +26 -0
  76. package/dist/runtime/host-load-token-ledger.js +93 -61
  77. package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
  78. package/dist/runtime/host-load-windows-cpu.js +85 -0
  79. package/dist/runtime/host-runtime-contract.d.ts +12 -0
  80. package/dist/runtime/host-runtime-contract.js +29 -1
  81. package/dist/runtime/host-runtime-lease.d.ts +59 -3
  82. package/dist/runtime/host-runtime-lease.js +209 -58
  83. package/dist/runtime/host-runtime-promotion.d.ts +23 -0
  84. package/dist/runtime/host-runtime-promotion.js +36 -0
  85. package/dist/runtime/managed-command-teardown.js +5 -16
  86. package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
  87. package/dist/runtime/native-test-postgres-fallback.js +60 -8
  88. package/dist/runtime/playwright-host-runtime-adapter.d.ts +7 -0
  89. package/dist/runtime/playwright-host-runtime-adapter.js +13 -1
  90. package/dist/runtime/runner-settings.d.ts +104 -0
  91. package/dist/runtime/runner-settings.js +236 -0
  92. package/dist/sandbox/host-capacity-broker.d.ts +10 -2
  93. package/dist/sandbox/host-capacity-broker.js +27 -6
  94. package/dist/sandbox/managed-branch.d.ts +13 -0
  95. package/dist/sandbox/managed-branch.js +36 -0
  96. package/dist/sandbox/provider-auth/codex.js +11 -11
  97. package/dist/sandbox/runtime.js +2 -6
  98. package/dist/session/architect-waits.d.ts +2 -0
  99. package/dist/session/architect-waits.js +138 -0
  100. package/dist/session/managed-attempt-tools.d.ts +2 -7
  101. package/dist/session/managed-attempt-tools.js +89 -99
  102. package/dist/session/managed-build-receipt.d.ts +5 -0
  103. package/dist/session/managed-build-receipt.js +8 -3
  104. package/dist/session/managed-command-host-load.d.ts +2 -0
  105. package/dist/session/managed-command-host-load.js +2 -1
  106. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  107. package/dist/session/mcp-argument-coercion.js +121 -0
  108. package/dist/session/phase-completion.artifacts.d.ts +7 -0
  109. package/dist/session/phase-completion.artifacts.js +96 -26
  110. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  111. package/dist/session/phase-completion.command-validation.js +77 -0
  112. package/dist/session/phase-completion.d.ts +10 -0
  113. package/dist/session/phase-completion.helpers.js +13 -12
  114. package/dist/session/phase-completion.js +5 -0
  115. package/dist/session/phase-completion.mcp-args.d.ts +9 -0
  116. package/dist/session/phase-completion.mcp-args.js +156 -0
  117. package/dist/session/phase-completion.prompts.js +6 -1
  118. package/dist/session/phase-completion.runtime.d.ts +4 -10
  119. package/dist/session/phase-completion.runtime.js +77 -209
  120. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  121. package/dist/session/phase-completion.schema-parts.js +188 -0
  122. package/dist/session/phase-completion.schemas.d.ts +3 -3
  123. package/dist/session/phase-completion.schemas.js +208 -231
  124. package/dist/session/phase-completion.validation.d.ts +2 -3
  125. package/dist/session/phase-completion.validation.js +49 -93
  126. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  127. package/dist/session/pre-publication-native-postgres.js +111 -0
  128. package/dist/session/pre-publication-pass.d.ts +61 -0
  129. package/dist/session/pre-publication-pass.js +148 -0
  130. package/dist/session/pre-publication-process.js +10 -10
  131. package/dist/session/pre-publication-step-execution.d.ts +2 -1
  132. package/dist/session/pre-publication-step-execution.js +6 -5
  133. package/dist/session/pre-publication-validation.d.ts +30 -14
  134. package/dist/session/pre-publication-validation.js +207 -134
  135. package/dist/session/provider-cli/claude-background-work.d.ts +67 -0
  136. package/dist/session/provider-cli/claude-background-work.js +181 -0
  137. package/dist/session/provider-cli/host-build-lock.d.ts +18 -0
  138. package/dist/session/provider-cli/host-build-lock.js +30 -0
  139. package/dist/session/provider-cli/pre-publication-repair.d.ts +56 -0
  140. package/dist/session/provider-cli/pre-publication-repair.js +276 -0
  141. package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
  142. package/dist/session/provider-cli/provider-cli.child-environment.js +75 -0
  143. package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
  144. package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
  145. package/dist/session/provider-cli/provider-cli.process.d.ts +15 -36
  146. package/dist/session/provider-cli/provider-cli.process.js +39 -430
  147. package/dist/session/provider-cli/provider-cli.prompts.d.ts +5 -0
  148. package/dist/session/provider-cli/provider-cli.prompts.js +72 -32
  149. package/dist/session/provider-cli/provider-cli.runtime.d.ts +8 -0
  150. package/dist/session/provider-cli/provider-cli.runtime.js +29 -1
  151. package/dist/session/provider-cli/provider-cli.service.d.ts +7 -1
  152. package/dist/session/provider-cli/provider-cli.service.js +78 -171
  153. package/dist/session/provider-cli/provider-cli.types.d.ts +26 -0
  154. package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
  155. package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
  156. package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
  157. package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
  158. package/dist/session/provider-cli/provider-in-flight-work.d.ts +4 -0
  159. package/dist/session/provider-cli/provider-in-flight-work.js +45 -0
  160. package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
  161. package/dist/session/provider-cli/provider-output-pipes.js +67 -0
  162. package/dist/session/provider-cli/provider-output-state.d.ts +2 -0
  163. package/dist/session/provider-cli/provider-output-state.js +6 -0
  164. package/dist/session/provider-cli/provider-user-config-isolation.d.ts +69 -0
  165. package/dist/session/provider-cli/provider-user-config-isolation.js +164 -0
  166. package/dist/session/qa-sidecar-validation.d.ts +6 -0
  167. package/dist/session/qa-sidecar-validation.js +28 -0
  168. package/dist/session/sandbox-host-capacity-gate.d.ts +22 -1
  169. package/dist/session/sandbox-host-capacity-gate.js +42 -14
  170. package/dist/session/session-redaction.js +31 -181
  171. package/dist/session/session.base.d.ts +6 -1
  172. package/dist/session/session.service.d.ts +9 -2
  173. package/dist/session/session.service.js +162 -58
  174. package/dist/session/session.types.js +4 -4
  175. package/dist/session/sidecar-json-shape.d.ts +31 -0
  176. package/dist/session/sidecar-json-shape.js +217 -0
  177. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  178. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  179. package/dist/shared/fs/file-identity.d.ts +10 -0
  180. package/dist/shared/fs/file-identity.js +15 -0
  181. package/dist/shared/fs/replace-file.d.ts +7 -0
  182. package/dist/shared/fs/replace-file.js +33 -0
  183. package/dist/shared/process/host-process-recovery.d.ts +14 -3
  184. package/dist/shared/process/host-process-recovery.js +23 -3
  185. package/dist/shared/process/host-process-supervisor.d.ts +13 -1
  186. package/dist/shared/process/host-process-supervisor.js +66 -14
  187. package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
  188. package/dist/shared/process/windows-app-execution-alias.js +45 -0
  189. package/dist/shared/process/windows-launch.d.ts +18 -0
  190. package/dist/shared/process/windows-launch.js +68 -0
  191. package/dist/shared/provider-capabilities.js +14 -7
  192. package/dist/version.d.ts +1 -1
  193. package/dist/version.js +1 -1
  194. package/dist/worktree/wip-git.d.ts +33 -0
  195. package/dist/worktree/wip-git.js +122 -0
  196. package/dist/worktree/wip-refs.d.ts +62 -0
  197. package/dist/worktree/wip-refs.js +119 -0
  198. package/dist/worktree/wip-restore.d.ts +38 -0
  199. package/dist/worktree/wip-restore.js +190 -0
  200. package/dist/worktree/wip-snapshot.d.ts +50 -0
  201. package/dist/worktree/wip-snapshot.js +268 -0
  202. package/dist/worktree/worktree-wip-events.d.ts +18 -0
  203. package/dist/worktree/worktree-wip-events.js +98 -0
  204. package/dist/worktree/worktree-wip.d.ts +49 -0
  205. package/dist/worktree/worktree-wip.js +182 -0
  206. package/dist/worktree/worktree.base.d.ts +7 -1
  207. package/dist/worktree/worktree.service.d.ts +11 -3
  208. package/dist/worktree/worktree.service.js +54 -21
  209. package/dist/worktree/worktree.types.d.ts +22 -0
  210. package/package.json +2 -2
@@ -18,16 +18,34 @@ export interface HostOwnCgroupLoad {
18
18
  /** All memory charged to the unit (`memory.current`), including page cache. */
19
19
  readonly memoryChargedBytes: number | null;
20
20
  }
21
+ /**
22
+ * Where `systemPressure` comes from: Linux PSI, or (decision 0021) an estimate
23
+ * of CPU `some` pressure from whole-host CPU use on Windows, which has no PSI.
24
+ */
25
+ export type HostLoadPressureSource = "psi" | "windows_estimate";
21
26
  /** Live host load. Reported in every heartbeat but never a material capability signal. */
22
27
  export interface HostLoadSnapshot {
23
28
  readonly sampledAt: string;
29
+ /**
30
+ * True when `systemPressure` carries a CPU pressure signal the governor gates on.
31
+ * The wire name predates decision 0021: on Windows the signal is an estimate
32
+ * (see `pressureSource`), and the static host fact `psiAvailable` stays false.
33
+ */
24
34
  readonly psiAvailable: boolean;
35
+ /** Null exactly when `psiAvailable` is false. */
36
+ readonly pressureSource: HostLoadPressureSource | null;
25
37
  readonly systemPressure: HostSystemPressure | null;
26
38
  /** True only when the bridge runs in a cgroup of its own (see isDedicatedBridgeUnit). */
27
39
  readonly ownCgroupDedicated: boolean;
28
40
  /** Reported only for a dedicated unit; never a shared terminal/session/app scope. */
29
41
  readonly ownCgroup: HostOwnCgroupLoad | null;
30
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;
31
49
  }
32
50
  /** What the bridge service needs: static facts plus the latest cached load sample. */
33
51
  export interface HostLoadSource {
@@ -48,7 +66,7 @@ export interface HostLoadSource {
48
66
  */
49
67
  export interface HostCpuAttribution {
50
68
  readonly sampledAt: string;
51
- /** Busy cores on the whole host, from /proc/stat deltas. */
69
+ /** Busy cores on the whole host, from /proc/stat deltas (os.cpus() deltas on Windows). */
52
70
  readonly hostCoresInUse: number;
53
71
  /** Cores used by the bridge's dedicated cgroup; null when the cgroup is not dedicated. */
54
72
  readonly ownCoresInUse: number | null;
@@ -80,8 +98,9 @@ export interface HostLoadSamplerOptions {
80
98
  export declare const defaultHostLoadSampleIntervalMs = 5000;
81
99
  /**
82
100
  * Samples Linux PSI and the bridge's own cgroup on an interval and caches the
83
- * latest snapshot. Every read is async and failure-tolerant: a host without PSI
84
- * (non-Linux, old kernel, `psi=0`) reports `psiAvailable: false` and no pressure.
101
+ * latest snapshot. Every read is async and failure-tolerant: a Linux host without
102
+ * PSI (old kernel, `psi=0`) or another non-Windows host reports `psiAvailable: false`
103
+ * and no pressure. Windows reports a CPU pressure estimate instead (decision 0021).
85
104
  */
86
105
  export declare class HostLoadSampler implements HostLoadSource {
87
106
  private readonly environment;
@@ -100,6 +119,8 @@ export declare class HostLoadSampler implements HostLoadSource {
100
119
  private hostCpuMark;
101
120
  private latestCpuAttribution;
102
121
  private latestMemoryHeadroom;
122
+ private windowsCpuMark;
123
+ private readonly windowsCpuPressure;
103
124
  private readonly forgeCgroups;
104
125
  private readonly sandboxCpu;
105
126
  constructor(options?: HostLoadSamplerOptions);
@@ -115,11 +136,20 @@ export declare class HostLoadSampler implements HostLoadSource {
115
136
  sample(): Promise<HostLoadSnapshot>;
116
137
  private startOnce;
117
138
  private readSnapshot;
139
+ /**
140
+ * Decision 0021: Windows has no PSI or cgroups. CPU pressure is estimated from
141
+ * whole-host CPU use between samples, and memory is available physical memory.
142
+ * The bridge's own share is not attributed, so external load stays unknown and
143
+ * Forge's work counts through reserved cost and the pressure gate (as on a Linux
144
+ * host whose bridge has no dedicated cgroup).
145
+ */
146
+ private readWindowsSnapshot;
118
147
  private readCgroupMemoryHeadroom;
119
148
  private readSystemPressure;
120
149
  private readOwnCgroup;
121
150
  private coresInUse;
122
- private readHostCoresInUse;
151
+ /** Busy share (0-1) of all logical CPUs since the last /proc/stat reading. */
152
+ private readHostCpuUse;
123
153
  private readMemoryAvailable;
124
154
  private fallbackFreeMemory;
125
155
  private readPressure;
@@ -2,13 +2,15 @@ import path from "node:path";
2
2
  import { defaultHostEnvironment, detectHostFacts, readOptional, } from "./host-facts.js";
3
3
  import { cgroupLeafName, isDedicatedBridgeUnit, parseCgroupCpuUsageUsec, parseCgroupMemoryAnonBytes, parseMemAvailableBytes, parseNonNegativeInteger, parsePressureStall, parseProcStatCpuTotals, parseUnifiedCgroupMembership, parseUnifiedCgroupPath, } from "./host-pressure-stall.js";
4
4
  import { ForgeCgroupCpuMeter, readCgroupMemoryHeadroomBytes, } from "./host-load-forge-cgroups.js";
5
+ import { cpuTimeTotals, cpuUtilisation, WindowsCpuPressureEstimator, } from "./host-load-windows-cpu.js";
5
6
  export const defaultHostLoadSampleIntervalMs = 5_000;
6
7
  /** Samples kept for the governor's pressure streak (FORGE_HOST_LOAD_BACKPRESSURE_SAMPLES is at most 60). */
7
8
  const retainedSampleCount = 64;
8
9
  /**
9
10
  * Samples Linux PSI and the bridge's own cgroup on an interval and caches the
10
- * latest snapshot. Every read is async and failure-tolerant: a host without PSI
11
- * (non-Linux, old kernel, `psi=0`) reports `psiAvailable: false` and no pressure.
11
+ * latest snapshot. Every read is async and failure-tolerant: a Linux host without
12
+ * PSI (old kernel, `psi=0`) or another non-Windows host reports `psiAvailable: false`
13
+ * and no pressure. Windows reports a CPU pressure estimate instead (decision 0021).
12
14
  */
13
15
  export class HostLoadSampler {
14
16
  environment;
@@ -27,6 +29,8 @@ export class HostLoadSampler {
27
29
  hostCpuMark = null;
28
30
  latestCpuAttribution = null;
29
31
  latestMemoryHeadroom = null;
32
+ windowsCpuMark = null;
33
+ windowsCpuPressure = new WindowsCpuPressureEstimator();
30
34
  forgeCgroups;
31
35
  sandboxCpu;
32
36
  constructor(options = {}) {
@@ -77,6 +81,9 @@ export class HostLoadSampler {
77
81
  sample() {
78
82
  this.inFlight ??= this.readSnapshot()
79
83
  .then(snapshot => {
84
+ // A Windows reading that did not advance the CPU window returns the last snapshot.
85
+ if (snapshot === this.latest)
86
+ return snapshot;
80
87
  this.latest = snapshot;
81
88
  this.history.push(snapshot);
82
89
  if (this.history.length > retainedSampleCount)
@@ -104,13 +111,15 @@ export class HostLoadSampler {
104
111
  async readSnapshot() {
105
112
  const sampledAtMs = this.now();
106
113
  const monotonicMs = this.monotonicNow();
114
+ if (this.environment.platform === "win32")
115
+ return this.readWindowsSnapshot(sampledAtMs, monotonicMs);
107
116
  const linux = this.environment.platform === "linux";
108
- const [systemPressure, ownCgroup, memoryAvailableBytes, hostCoresInUse, cgroupMemoryHeadroomBytes, sandboxCores] = linux
117
+ const [systemPressure, ownCgroup, memoryAvailableBytes, hostCpu, cgroupMemoryHeadroomBytes, sandboxCores] = linux
109
118
  ? await Promise.all([
110
119
  this.readSystemPressure(),
111
120
  this.readOwnCgroup(monotonicMs),
112
121
  this.readMemoryAvailable(),
113
- this.readHostCoresInUse(),
122
+ this.readHostCpuUse(),
114
123
  this.readCgroupMemoryHeadroom(),
115
124
  Promise.resolve(this.forgeCgroups?.paths() ?? [])
116
125
  .then(paths => this.sandboxCpu.coresInUse(paths, monotonicMs)).catch(() => 0),
@@ -120,16 +129,54 @@ export class HostLoadSampler {
120
129
  // Docker sandbox CPU is Forge's own work, already counted through reserved cost.
121
130
  const ownCores = ownCgroup?.cpuCoresInUse ?? null;
122
131
  this.latestMemoryHeadroom = cgroupMemoryHeadroomBytes;
123
- this.latestCpuAttribution = hostCpuAttribution(sampledAt, hostCoresInUse, ownCores === null ? null : ownCores + sandboxCores);
132
+ this.latestCpuAttribution = hostCpuAttribution(sampledAt, hostCpu === null ? null : roundCores(hostCpu.utilisation * hostCpu.cpuCount), ownCores === null ? null : ownCores + sandboxCores);
124
133
  return {
125
134
  sampledAt,
126
135
  psiAvailable: systemPressure !== null,
136
+ pressureSource: systemPressure !== null ? "psi" : null,
127
137
  systemPressure,
128
138
  ownCgroupDedicated: ownCgroup !== null,
129
139
  ownCgroup,
130
140
  memoryAvailableBytes,
141
+ hostCpuPercent: hostCpu === null ? null : hostCpuPercent(hostCpu.utilisation),
131
142
  };
132
143
  }
144
+ /**
145
+ * Decision 0021: Windows has no PSI or cgroups. CPU pressure is estimated from
146
+ * whole-host CPU use between samples, and memory is available physical memory.
147
+ * The bridge's own share is not attributed, so external load stays unknown and
148
+ * Forge's work counts through reserved cost and the pressure gate (as on a Linux
149
+ * host whose bridge has no dedicated cgroup).
150
+ */
151
+ readWindowsSnapshot(sampledAtMs, monotonicMs) {
152
+ let totals;
153
+ try {
154
+ totals = cpuTimeTotals(this.environment.cpus());
155
+ }
156
+ catch {
157
+ totals = null;
158
+ }
159
+ const previous = this.windowsCpuMark;
160
+ const sampledAt = new Date(sampledAtMs).toISOString();
161
+ if (this.latest && totals && previous && previous.totals.cpuCount === totals.cpuCount
162
+ && monotonicMs - previous.atMs < minimumWindowsCpuWindowMs) {
163
+ // Too soon after the last reading (start() right after a sample) for a stable delta:
164
+ // the window stays open and the last snapshot is returned as is. sample() does not
165
+ // record it again, so it never counts as another sample in the pressure streak.
166
+ return this.latest;
167
+ }
168
+ this.windowsCpuMark = totals ? { totals, atMs: monotonicMs } : null;
169
+ const elapsedMs = previous ? monotonicMs - previous.atMs : 0;
170
+ const utilisation = previous && elapsedMs > 0 ? cpuUtilisation(previous.totals, totals) : null;
171
+ // The first sample, or a break in readings (no times, a CPU count change, a counter
172
+ // reset), reports no pressure and restarts the averages from the next window.
173
+ if (utilisation === null)
174
+ this.windowsCpuPressure.reset();
175
+ const cpu = utilisation === null ? null : this.windowsCpuPressure.update(utilisation, elapsedMs);
176
+ this.latestMemoryHeadroom = null;
177
+ this.latestCpuAttribution = hostCpuAttribution(sampledAt, utilisation !== null && totals ? roundCores(utilisation * totals.cpuCount) : null, null);
178
+ return windowsSnapshot(sampledAt, cpu, this.fallbackFreeMemory(), utilisation === null ? null : hostCpuPercent(utilisation));
179
+ }
133
180
  async readCgroupMemoryHeadroom() {
134
181
  const membership = await readOptional(this.environment, path.posix.join(this.environment.procRoot, "self", "cgroup"));
135
182
  const cgroupPath = membership ? parseUnifiedCgroupMembership(membership) : null;
@@ -185,7 +232,8 @@ export class HostLoadSampler {
185
232
  return null;
186
233
  return roundCores(usedUsec / elapsedUsec);
187
234
  }
188
- async readHostCoresInUse() {
235
+ /** Busy share (0-1) of all logical CPUs since the last /proc/stat reading. */
236
+ async readHostCpuUse() {
189
237
  const content = await readOptional(this.environment, path.posix.join(this.environment.procRoot, "stat"));
190
238
  const totals = content ? parseProcStatCpuTotals(content) : null;
191
239
  const previous = this.hostCpuMark;
@@ -196,7 +244,7 @@ export class HostLoadSampler {
196
244
  const busyDelta = totals.busyTicks - previous.busyTicks;
197
245
  if (totalDelta <= 0 || busyDelta < 0)
198
246
  return null;
199
- return roundCores((busyDelta / totalDelta) * totals.cpuCount);
247
+ return { utilisation: Math.min(1, busyDelta / totalDelta), cpuCount: totals.cpuCount };
200
248
  }
201
249
  async readMemoryAvailable() {
202
250
  const meminfo = await readOptional(this.environment, path.posix.join(this.environment.procRoot, "meminfo"));
@@ -216,9 +264,27 @@ export class HostLoadSampler {
216
264
  return content ? parsePressureStall(content) : null;
217
265
  }
218
266
  }
267
+ /** Windows CPU deltas shorter than this are too noisy to fold into the pressure estimate. */
268
+ const minimumWindowsCpuWindowMs = 250;
269
+ function windowsSnapshot(sampledAt, cpu, memoryAvailableBytes, cpuPercent) {
270
+ return {
271
+ sampledAt,
272
+ psiAvailable: cpu !== null,
273
+ pressureSource: cpu !== null ? "windows_estimate" : null,
274
+ systemPressure: cpu ? { cpu, memory: null, io: null } : null,
275
+ ownCgroupDedicated: false,
276
+ ownCgroup: null,
277
+ memoryAvailableBytes,
278
+ hostCpuPercent: cpuPercent,
279
+ };
280
+ }
219
281
  function roundCores(value) {
220
282
  return Math.round(value * 100) / 100;
221
283
  }
284
+ /** A 0-1 busy share as a percentage with two decimals. */
285
+ function hostCpuPercent(utilisation) {
286
+ return Math.round(Math.min(1, Math.max(0, utilisation)) * 10_000) / 100;
287
+ }
222
288
  function hostCpuAttribution(sampledAt, hostCoresInUse, ownCoresInUse) {
223
289
  if (hostCoresInUse === null)
224
290
  return null;
@@ -58,7 +58,9 @@ export interface ManagedCommandStepInput {
58
58
  /**
59
59
  * Maps a managed command to its class: `managed.<profile>` for verification
60
60
  * profiles (a .NET tier's cost per parallel shard), `managed.playwright`,
61
- * `managed.build` for build-producing commands, and `managed.command` otherwise.
61
+ * `managed.build` for build-producing commands, `managed.test` for a test run
62
+ * that reuses an earlier build, and `managed.command` otherwise. Only
63
+ * `managed.command` skips the host test slot (decision 0018).
62
64
  */
63
65
  export declare function classifyManagedCommand(input: ManagedCommandStepInput): HostLoadStepClassification;
64
66
  /**
@@ -1,5 +1,4 @@
1
- // Step classes and conservative default costs for governed heavy steps
2
- // (decision 0013). Step 4 replaces the defaults with P75 estimates from history.
1
+ import path from "node:path";
3
2
  const gib = 1024 ** 3;
4
3
  export const defaultHostLoadStepCosts = {
5
4
  dotnetTier: { cpuCores: 2, memoryBytes: 3 * gib },
@@ -60,7 +59,9 @@ function stepClassSegment(value) {
60
59
  /**
61
60
  * Maps a managed command to its class: `managed.<profile>` for verification
62
61
  * profiles (a .NET tier's cost per parallel shard), `managed.playwright`,
63
- * `managed.build` for build-producing commands, and `managed.command` otherwise.
62
+ * `managed.build` for build-producing commands, `managed.test` for a test run
63
+ * that reuses an earlier build, and `managed.command` otherwise. Only
64
+ * `managed.command` skips the host test slot (decision 0018).
64
65
  */
65
66
  export function classifyManagedCommand(input) {
66
67
  if (input.verificationProfile) {
@@ -74,14 +75,68 @@ export function classifyManagedCommand(input) {
74
75
  },
75
76
  };
76
77
  }
77
- const invocation = [input.command, ...input.args].map(argument => argument.toLowerCase());
78
- if (invocation.some(argument => argument.includes("playwright"))) {
78
+ const invocation = [input.command, ...input.args].map(argument => argument.toLowerCase().replaceAll("\\", "/"));
79
+ const programs = programsRun(invocation);
80
+ if (programs.some(program => path.posix.basename(program).includes("playwright"))) {
79
81
  return { stepClass: "managed.playwright", cost: defaultHostLoadStepCosts.playwright };
80
82
  }
81
83
  if (input.buildProducing)
82
84
  return { stepClass: "managed.build", cost: defaultHostLoadStepCosts.managedBuild };
85
+ if (isTestRun(invocation, programs))
86
+ return { stepClass: "managed.test", cost: defaultHostLoadStepCosts.dotnetTier };
83
87
  return { stepClass: "managed.command", cost: defaultHostLoadStepCosts.generic };
84
88
  }
89
+ const testRunScripts = [...dotnetTierScripts, affectedDotnetScript].map(script => script.toLowerCase());
90
+ const packageManagers = new Set(["npm", "pnpm", "yarn", "npx"]);
91
+ const scriptHosts = new Set(["node", "pwsh", "powershell", "bash", "sh", "tsx"]);
92
+ const programName = (argument) => path.posix.basename(argument).replace(/\.(exe|cmd)$/u, "");
93
+ // Package-manager options that take a value (`pnpm --dir tests/e2e`, `npm --prefix x`), in
94
+ // lower case like the invocation, so `-c` and `-f` are pnpm's `-C` and `-F`.
95
+ const packageManagerValueOptions = new Set(["--dir", "-c", "--prefix", "--filter", "-f", "--workspace", "--cwd", "--config"]);
96
+ /** The operands of an invocation, without options and, for a package manager, the values its options take. */
97
+ function operandsOf(command, args) {
98
+ const operands = [];
99
+ for (let index = 0; index < args.length; index += 1) {
100
+ const argument = args[index];
101
+ if (!argument.startsWith("-"))
102
+ operands.push(argument);
103
+ else if (packageManagers.has(command) && packageManagerValueOptions.has(argument))
104
+ index += 1;
105
+ }
106
+ return operands;
107
+ }
108
+ /**
109
+ * The programs an invocation runs: the executable and, for a script host or a
110
+ * package manager's exec, the script or tool it starts. Arguments after that
111
+ * (a search pattern, a file to read) never classify the command, so
112
+ * `rg vitest src` or `cat playwright.config.ts` stays a plain command.
113
+ */
114
+ function programsRun(invocation) {
115
+ const command = programName(invocation[0] ?? "");
116
+ const operands = operandsOf(command, invocation.slice(1));
117
+ if (scriptHosts.has(command))
118
+ return [command, ...operands.slice(0, 1)];
119
+ if (command === "npx")
120
+ return [command, ...operands.slice(0, 1)];
121
+ if (packageManagers.has(command) && ["exec", "dlx"].includes(operands[0] ?? ""))
122
+ return [command, ...operands.slice(1, 2)];
123
+ // `pnpm vitest`, `yarn playwright test`: these run a package's binary by name.
124
+ if (command === "pnpm" || command === "yarn")
125
+ return [command, ...operands.slice(0, 1)];
126
+ return [command];
127
+ }
128
+ /** `dotnet test`, the tier and affected scripts, Vitest, or a package manager's test script. */
129
+ function isTestRun(invocation, programs) {
130
+ const command = programs[0] ?? "";
131
+ const operands = operandsOf(command, invocation.slice(1));
132
+ if (command === "dotnet" && operands[0] === "test")
133
+ return true;
134
+ if (programs.some(program => testRunScripts.some(script => program.endsWith(script))))
135
+ return true;
136
+ if (programs.some(program => programName(program) === "vitest"))
137
+ return true;
138
+ return packageManagers.has(command) && (operands[0] === "test" || (operands[0] === "run" && operands[1] === "test"));
139
+ }
85
140
  /**
86
141
  * The default cost of a step class, for a step whose cost the requester does
87
142
  * not get to choose (a Docker sandbox asking the host bridge for admission).
@@ -0,0 +1,43 @@
1
+ import type { HostLoadAdmissionDecision } from "./host-load-admission.js";
2
+ import type { HostLoadToken, HostLoadTokenOwner, HostLoadTokenPriority } from "./host-load-token-ledger.js";
3
+ /** Every governed step class takes the slot unless it is known to be light. */
4
+ export declare function takesHostTestSlot(stepClass: string): boolean;
5
+ /** A step waiting for the slot, as its owner records it in the ledger. */
6
+ export interface HostTestSlotTicketRequest {
7
+ readonly ticketId: string;
8
+ readonly stepClass: string;
9
+ readonly label: string;
10
+ readonly dispatchAttemptId: string | null;
11
+ readonly priority: HostLoadTokenPriority;
12
+ /** Wall clock (ISO): every process on the host orders by the same clock. */
13
+ readonly enqueuedAt: string;
14
+ }
15
+ /** A ticket in the ledger: its owner renews `expiresAt` on every transaction while it waits. */
16
+ export interface HostTestSlotTicket extends HostTestSlotTicketRequest {
17
+ readonly owner: HostLoadTokenOwner;
18
+ readonly expiresAt: string;
19
+ }
20
+ /**
21
+ * The host queue in admission order: foreground first, except background that has
22
+ * waited past the anti-starvation window, then oldest first.
23
+ */
24
+ export declare function orderHostTestSlotQueue(tickets: readonly HostTestSlotTicketRequest[], nowMs: number, antiStarvationMs: number): HostTestSlotTicketRequest[];
25
+ export interface HostTestSlotInput {
26
+ readonly ticket: HostTestSlotTicketRequest;
27
+ /** Every live ticket on the host, this one included or not. */
28
+ readonly queue: readonly HostTestSlotTicketRequest[];
29
+ /** Every live token on the host; fenced and degraded ones still hold their slot. */
30
+ readonly tokens: readonly HostLoadToken[];
31
+ readonly testSlots: number;
32
+ readonly nowMs: number;
33
+ readonly antiStarvationMs: number;
34
+ }
35
+ /**
36
+ * Admitted once the slots the holders leave free reach this ticket's place in the
37
+ * host queue. A token kept until its attempt's teardown (`retainedAt`) holds the slot
38
+ * against every other attempt, but not against its own: that attempt's next step
39
+ * would otherwise wait for its own teardown.
40
+ */
41
+ export declare function decideHostTestSlot(input: HostTestSlotInput): HostLoadAdmissionDecision;
42
+ /** A ticket read back from the ledger; a malformed one is dropped, never trusted. */
43
+ export declare function validHostTestSlotTicket(value: unknown): value is HostTestSlotTicket;
@@ -0,0 +1,81 @@
1
+ // The host test slot (decision 0018): two Forge sessions on one host share it, so
2
+ // their builds, test runs, Playwright runs and runtime builds take turns instead of
3
+ // competing for the CPU and memory. Waiters queue host-wide in the shared ledger,
4
+ // foreground before background and first come, first served within a class, so a
5
+ // step in another process (the completion MCP server) is never overtaken by the
6
+ // bridge's own steps. A slot holder that crashed keeps its slot only until the
7
+ // ledger reclaims its token (dead owner, process tree stopped, or lease fenced).
8
+ /** Steps that never take the slot: plain managed commands (git, ls, cat) and dependency installs. */
9
+ const slotFreeStepClasses = new Set(["managed.command", "deps.install"]);
10
+ /** Every governed step class takes the slot unless it is known to be light. */
11
+ export function takesHostTestSlot(stepClass) {
12
+ return !slotFreeStepClasses.has(stepClass);
13
+ }
14
+ /**
15
+ * The host queue in admission order: foreground first, except background that has
16
+ * waited past the anti-starvation window, then oldest first.
17
+ */
18
+ export function orderHostTestSlotQueue(tickets, nowMs, antiStarvationMs) {
19
+ const rank = (ticket) => ticket.priority === "foreground" || nowMs - Date.parse(ticket.enqueuedAt) >= antiStarvationMs ? 0 : 1;
20
+ return [...tickets].sort((a, b) => rank(a) - rank(b)
21
+ || Date.parse(a.enqueuedAt) - Date.parse(b.enqueuedAt)
22
+ || a.ticketId.localeCompare(b.ticketId));
23
+ }
24
+ /**
25
+ * Admitted once the slots the holders leave free reach this ticket's place in the
26
+ * host queue. A token kept until its attempt's teardown (`retainedAt`) holds the slot
27
+ * against every other attempt, but not against its own: that attempt's next step
28
+ * would otherwise wait for its own teardown.
29
+ */
30
+ export function decideHostTestSlot(input) {
31
+ const ownRetained = (token) => Boolean(token.retainedAt)
32
+ && token.dispatchAttemptId !== null && token.dispatchAttemptId === input.ticket.dispatchAttemptId;
33
+ const holders = input.tokens.filter(token => takesHostTestSlot(token.stepClass) && !ownRetained(token));
34
+ const queue = input.queue.some(entry => entry.ticketId === input.ticket.ticketId)
35
+ ? input.queue
36
+ : [...input.queue, input.ticket];
37
+ const ahead = orderHostTestSlotQueue(queue, input.nowMs, input.antiStarvationMs)
38
+ .findIndex(entry => entry.ticketId === input.ticket.ticketId);
39
+ const free = Math.max(0, input.testSlots - holders.length);
40
+ const admitted = ahead < free;
41
+ const reserved = {
42
+ reservedCpuCores: input.tokens.reduce((sum, token) => sum + token.cost.cpuCores, 0),
43
+ reservedMemoryBytes: input.tokens.reduce((sum, token) => sum + token.cost.memoryBytes, 0),
44
+ cpuBudgetCores: null,
45
+ memoryBudgetBytes: null,
46
+ };
47
+ if (admitted) {
48
+ return { ...reserved, admitted, reason: "admitted_test_slot", detail: "The host test slot is free." };
49
+ }
50
+ const heldBy = holders.length > 0
51
+ ? `held by ${holders.map(describeHolder).join("; ")}`
52
+ : "the steps ahead of this one take it first";
53
+ return {
54
+ ...reserved,
55
+ admitted,
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.`,
58
+ };
59
+ }
60
+ function describeHolder(token) {
61
+ const attempt = token.dispatchAttemptId ? `, attempt ${token.dispatchAttemptId}` : "";
62
+ 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})`;
67
+ }
68
+ /** A ticket read back from the ledger; a malformed one is dropped, never trusted. */
69
+ export function validHostTestSlotTicket(value) {
70
+ const ticket = value;
71
+ return Boolean(ticket)
72
+ && typeof ticket.ticketId === "string"
73
+ && typeof ticket.stepClass === "string"
74
+ && typeof ticket.label === "string"
75
+ && (ticket.dispatchAttemptId === null || typeof ticket.dispatchAttemptId === "string")
76
+ && (ticket.priority === "foreground" || ticket.priority === "background")
77
+ && Number.isFinite(Date.parse(String(ticket.enqueuedAt)))
78
+ && Number.isFinite(Date.parse(String(ticket.expiresAt)))
79
+ && Number.isSafeInteger(ticket.owner?.pid)
80
+ && typeof ticket.owner?.processInstanceId === "string";
81
+ }
@@ -1,5 +1,6 @@
1
1
  import { ForgeFailureError } from "../session/session.types.js";
2
2
  import type { HostLoadStepCost } from "./host-load-step-class.js";
3
+ import { type HostTestSlotTicket, type HostTestSlotTicketRequest } from "./host-load-test-slot.js";
3
4
  import { type HostLoadStepProcess, type HostLoadStepTerminator } from "./host-load-step-reaper.js";
4
5
  /**
5
6
  * File-backed token ledger for the host load governor (decision 0013). Every
@@ -40,6 +41,12 @@ export interface HostLoadToken {
40
41
  readonly degradedAt?: string | null;
41
42
  /** Set when the lease lapsed while the owner was still live: cost kept, renewal refused. */
42
43
  readonly fencedAt?: string | null;
44
+ /**
45
+ * Set when the step ended but part of its process tree could not be proven
46
+ * stopped: the token is kept until it is (or until attempt teardown), and the
47
+ * attempt's own later steps do not wait for it (decision 0018).
48
+ */
49
+ readonly retainedAt?: string | null;
43
50
  }
44
51
  export interface HostLoadTokenRequest {
45
52
  readonly stepClass: string;
@@ -56,11 +63,17 @@ export interface HostLoadLedgerTransaction {
56
63
  * restoring the reservations it lost, so no new step may be admitted yet.
57
64
  */
58
65
  readonly recoveringUntil: string | null;
66
+ /** Live host test slot tickets of every owner (decision 0018). */
67
+ readonly queue: readonly HostTestSlotTicket[];
59
68
  issue(request: HostLoadTokenRequest): HostLoadToken;
69
+ /** Takes an admitted step's ticket out of the queue in the same commit as its token. */
70
+ removeTicket(ticketId: string): void;
60
71
  renew(tokenId: string, fencingToken: number): HostLoadToken | null;
61
72
  remove(tokenId: string, fencingToken: number): boolean;
62
73
  /** Records the step's process tree on its token; null when the token is fenced. */
63
74
  attach(tokenId: string, fencingToken: number, stepProcess: HostLoadStepProcess): HostLoadToken | null;
75
+ /** Marks the token kept after its step ended (`retainedAt`), fenced or not; null when it is gone. */
76
+ retain(tokenId: string, fencingToken: number): HostLoadToken | null;
64
77
  }
65
78
  export interface HostLoadTransactionOutcome<T> {
66
79
  readonly result: T;
@@ -91,6 +104,11 @@ export interface HostLoadTokenLedgerOptions {
91
104
  * cost: it is put back (fenced, unless a quarantine is still recovering).
92
105
  */
93
106
  readonly heldTokens?: () => readonly HostLoadToken[];
107
+ /**
108
+ * The steps this owner still waits on for the host test slot (decision 0018). Each
109
+ * transaction renews their tickets and drops the owner's other tickets.
110
+ */
111
+ readonly waitingTickets?: () => readonly HostTestSlotTicketRequest[];
94
112
  /** Stops a reclaimed token's step; defaults to the exact process-tree reaper. */
95
113
  readonly terminateStep?: HostLoadStepTerminator;
96
114
  /** Host suspend counter (test seam); defaults to hostSuspendedMs. */
@@ -145,6 +163,14 @@ export declare class HostLoadTokenLedger {
145
163
  */
146
164
  release(tokenId: string, fencingToken: number): Promise<void>;
147
165
  private lockedTransaction;
166
+ /** The live token set and host test slot queue one locked transaction reads and changes. */
167
+ private transactionView;
168
+ /**
169
+ * The host test slot queue (decision 0018): other owners' tickets while their owner
170
+ * lives and renews them, and this owner's current waiters, renewed. A ticket this
171
+ * owner no longer waits on (admitted, cancelled, timed out) leaves the queue here.
172
+ */
173
+ private liveQueue;
148
174
  /**
149
175
  * Decides every token another owner can no longer vouch for (decision 0013):
150
176
  * - owner alive but its lease lapsed (it stalled): the token is fenced, never