@loucompanion/forge-bridge 0.1.4-dev.63db04bcffca → 0.1.4-dev.724427ea7be8

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 (271) hide show
  1. package/README.md +144 -3
  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 +101 -15
  16. package/dist/bridge/bridge.service.js +472 -345
  17. package/dist/bridge/bridge.types.d.ts +27 -0
  18. package/dist/bridge/dispatch-result-outbox.d.ts +11 -1
  19. package/dist/bridge/dispatch-result-outbox.js +31 -6
  20. package/dist/bridge/in-flight-registry.d.ts +62 -0
  21. package/dist/bridge/in-flight-registry.js +207 -0
  22. package/dist/bridge/local-yield-flag.d.ts +6 -0
  23. package/dist/bridge/local-yield-flag.js +34 -0
  24. package/dist/bridge/readiness-result-outbox.d.ts +5 -1
  25. package/dist/bridge/readiness-result-outbox.js +20 -0
  26. package/dist/bridge/runner-host-capabilities.d.ts +5 -0
  27. package/dist/bridge/runner-host-capabilities.js +17 -0
  28. package/dist/bridge/sandbox-resource-accounting.d.ts +16 -0
  29. package/dist/bridge/sandbox-resource-accounting.js +150 -0
  30. package/dist/bridge/test-postgres-capability.d.ts +14 -0
  31. package/dist/bridge/test-postgres-capability.js +120 -0
  32. package/dist/cleanup/cleanup-wip.d.ts +12 -0
  33. package/dist/cleanup/cleanup-wip.js +66 -0
  34. package/dist/cleanup/cleanup.service.d.ts +20 -1
  35. package/dist/cleanup/cleanup.service.js +150 -169
  36. package/dist/cleanup/cleanup.types.d.ts +6 -0
  37. package/dist/cleanup/forge-owned-paths.d.ts +9 -0
  38. package/dist/cleanup/forge-owned-paths.js +53 -0
  39. package/dist/cleanup/host-runtime-ledger.d.ts +7 -0
  40. package/dist/cleanup/host-runtime-ledger.js +130 -0
  41. package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
  42. package/dist/cleanup/managed-branch-sweep.js +111 -0
  43. package/dist/cli/cli.help.js +74 -12
  44. package/dist/cli/cli.service.d.ts +19 -10
  45. package/dist/cli/cli.service.js +152 -187
  46. package/dist/cli/idle-status.d.ts +84 -0
  47. package/dist/cli/idle-status.js +181 -0
  48. package/dist/cli/local-config.d.ts +6 -0
  49. package/dist/cli/local-config.js +32 -4
  50. package/dist/cli/provider-cli-detection.d.ts +10 -0
  51. package/dist/cli/provider-cli-detection.js +160 -0
  52. package/dist/runtime/aspnet-runtime-prebuild.d.ts +20 -0
  53. package/dist/runtime/aspnet-runtime-prebuild.js +184 -18
  54. package/dist/runtime/attempt-database-broker.d.ts +1 -1
  55. package/dist/runtime/attempt-node-runtime-launcher.js +9 -0
  56. package/dist/runtime/attempt-process-supervisor.d.ts +21 -0
  57. package/dist/runtime/attempt-process-supervisor.js +62 -6
  58. package/dist/runtime/docker-engine-probe.d.ts +5 -0
  59. package/dist/runtime/docker-engine-probe.js +7 -0
  60. package/dist/runtime/dotnet-build-outputs.d.ts +107 -0
  61. package/dist/runtime/dotnet-build-outputs.js +402 -0
  62. package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
  63. package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
  64. package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
  65. package/dist/runtime/ephemeral-test-postgres.js +303 -0
  66. package/dist/runtime/host-database-capability-boundary.d.ts +1 -1
  67. package/dist/runtime/host-database-capability-boundary.js +1 -0
  68. package/dist/runtime/host-facts.d.ts +36 -0
  69. package/dist/runtime/host-facts.js +95 -0
  70. package/dist/runtime/host-load-admission.d.ts +67 -0
  71. package/dist/runtime/host-load-admission.js +99 -0
  72. package/dist/runtime/host-load-child-environment.d.ts +27 -0
  73. package/dist/runtime/host-load-child-environment.js +76 -0
  74. package/dist/runtime/host-load-forge-cgroups.d.ts +49 -0
  75. package/dist/runtime/host-load-forge-cgroups.js +140 -0
  76. package/dist/runtime/host-load-governor-config.d.ts +52 -0
  77. package/dist/runtime/host-load-governor-config.js +83 -0
  78. package/dist/runtime/host-load-governor.d.ts +186 -0
  79. package/dist/runtime/host-load-governor.js +632 -0
  80. package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
  81. package/dist/runtime/host-load-ledger-lock.js +187 -0
  82. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  83. package/dist/runtime/host-load-runtime-settings.js +80 -0
  84. package/dist/runtime/host-load-sampler.d.ts +156 -0
  85. package/dist/runtime/host-load-sampler.js +298 -0
  86. package/dist/runtime/host-load-step-class.d.ts +70 -0
  87. package/dist/runtime/host-load-step-class.js +161 -0
  88. package/dist/runtime/host-load-step-reaper.d.ts +27 -0
  89. package/dist/runtime/host-load-step-reaper.js +95 -0
  90. package/dist/runtime/host-load-step-run.d.ts +73 -0
  91. package/dist/runtime/host-load-step-run.js +102 -0
  92. package/dist/runtime/host-load-test-slot.d.ts +43 -0
  93. package/dist/runtime/host-load-test-slot.js +81 -0
  94. package/dist/runtime/host-load-token-ledger.d.ts +200 -0
  95. package/dist/runtime/host-load-token-ledger.js +453 -0
  96. package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
  97. package/dist/runtime/host-load-windows-cpu.js +85 -0
  98. package/dist/runtime/host-pressure-stall.d.ts +61 -0
  99. package/dist/runtime/host-pressure-stall.js +168 -0
  100. package/dist/runtime/host-runtime-contract.d.ts +16 -0
  101. package/dist/runtime/host-runtime-contract.js +35 -2
  102. package/dist/runtime/host-runtime-lease.d.ts +76 -5
  103. package/dist/runtime/host-runtime-lease.js +322 -129
  104. package/dist/runtime/host-runtime-ledger-recovery.d.ts +20 -0
  105. package/dist/runtime/host-runtime-ledger-recovery.js +134 -0
  106. package/dist/runtime/host-runtime-promotion.d.ts +23 -0
  107. package/dist/runtime/host-runtime-promotion.js +48 -0
  108. package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
  109. package/dist/runtime/host-runtime-requirements-check.js +29 -0
  110. package/dist/runtime/host-runtime-requirements.d.ts +36 -0
  111. package/dist/runtime/host-runtime-requirements.js +117 -0
  112. package/dist/runtime/managed-command-teardown.d.ts +62 -0
  113. package/dist/runtime/managed-command-teardown.js +596 -0
  114. package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
  115. package/dist/runtime/native-test-postgres-fallback.js +60 -8
  116. package/dist/runtime/playwright-browser-cache.d.ts +39 -0
  117. package/dist/runtime/playwright-browser-cache.js +227 -0
  118. package/dist/runtime/playwright-host-runtime-adapter.d.ts +18 -0
  119. package/dist/runtime/playwright-host-runtime-adapter.js +61 -55
  120. package/dist/runtime/runner-settings.d.ts +104 -0
  121. package/dist/runtime/runner-settings.js +236 -0
  122. package/dist/runtime/supervised-runtime-build-guard.d.ts +45 -0
  123. package/dist/runtime/supervised-runtime-build-guard.js +112 -0
  124. package/dist/sandbox/host-capacity-broker.d.ts +115 -0
  125. package/dist/sandbox/host-capacity-broker.js +336 -0
  126. package/dist/sandbox/managed-branch.d.ts +13 -0
  127. package/dist/sandbox/managed-branch.js +90 -0
  128. package/dist/sandbox/provider-auth/codex.js +11 -11
  129. package/dist/sandbox/runtime.d.ts +10 -1
  130. package/dist/sandbox/runtime.js +47 -8
  131. package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
  132. package/dist/sandbox/sandbox-cgroups.js +42 -0
  133. package/dist/session/architect-waits.d.ts +2 -0
  134. package/dist/session/architect-waits.js +138 -0
  135. package/dist/session/managed-attempt-tools.d.ts +27 -7
  136. package/dist/session/managed-attempt-tools.js +406 -123
  137. package/dist/session/managed-build-coordinator.d.ts +17 -1
  138. package/dist/session/managed-build-coordinator.js +14 -1
  139. package/dist/session/managed-build-receipt.d.ts +5 -0
  140. package/dist/session/managed-build-receipt.js +8 -3
  141. package/dist/session/managed-command-host-load.d.ts +47 -0
  142. package/dist/session/managed-command-host-load.js +83 -0
  143. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  144. package/dist/session/mcp-argument-coercion.js +121 -0
  145. package/dist/session/phase-completion.artifacts.d.ts +7 -0
  146. package/dist/session/phase-completion.artifacts.js +100 -26
  147. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  148. package/dist/session/phase-completion.command-validation.js +77 -0
  149. package/dist/session/phase-completion.d.ts +12 -0
  150. package/dist/session/phase-completion.helpers.js +13 -12
  151. package/dist/session/phase-completion.js +5 -0
  152. package/dist/session/phase-completion.mcp-args.d.ts +9 -0
  153. package/dist/session/phase-completion.mcp-args.js +156 -0
  154. package/dist/session/phase-completion.prompts.js +6 -1
  155. package/dist/session/phase-completion.runtime.d.ts +5 -11
  156. package/dist/session/phase-completion.runtime.js +111 -230
  157. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  158. package/dist/session/phase-completion.schema-parts.js +188 -0
  159. package/dist/session/phase-completion.schemas.d.ts +3 -3
  160. package/dist/session/phase-completion.schemas.js +208 -231
  161. package/dist/session/phase-completion.validation.d.ts +2 -3
  162. package/dist/session/phase-completion.validation.js +49 -93
  163. package/dist/session/pre-publication-host-load.d.ts +27 -0
  164. package/dist/session/pre-publication-host-load.js +111 -0
  165. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  166. package/dist/session/pre-publication-native-postgres.js +111 -0
  167. package/dist/session/pre-publication-pass.d.ts +61 -0
  168. package/dist/session/pre-publication-pass.js +148 -0
  169. package/dist/session/pre-publication-process.d.ts +23 -0
  170. package/dist/session/pre-publication-process.js +109 -0
  171. package/dist/session/pre-publication-skipped-tests.d.ts +21 -0
  172. package/dist/session/pre-publication-skipped-tests.js +109 -0
  173. package/dist/session/pre-publication-step-execution.d.ts +12 -0
  174. package/dist/session/pre-publication-step-execution.js +50 -0
  175. package/dist/session/pre-publication-validation.d.ts +37 -21
  176. package/dist/session/pre-publication-validation.js +228 -219
  177. package/dist/session/provider-cli/claude-background-work.d.ts +67 -0
  178. package/dist/session/provider-cli/claude-background-work.js +181 -0
  179. package/dist/session/provider-cli/host-build-lock.d.ts +18 -0
  180. package/dist/session/provider-cli/host-build-lock.js +30 -0
  181. package/dist/session/provider-cli/pre-publication-repair.d.ts +56 -0
  182. package/dist/session/provider-cli/pre-publication-repair.js +276 -0
  183. package/dist/session/provider-cli/provider-cli.artifacts.d.ts +2 -1
  184. package/dist/session/provider-cli/provider-cli.artifacts.js +21 -15
  185. package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
  186. package/dist/session/provider-cli/provider-cli.child-environment.js +75 -0
  187. package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
  188. package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
  189. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
  190. package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
  191. package/dist/session/provider-cli/provider-cli.process.d.ts +46 -31
  192. package/dist/session/provider-cli/provider-cli.process.js +286 -403
  193. package/dist/session/provider-cli/provider-cli.prompts.d.ts +10 -0
  194. package/dist/session/provider-cli/provider-cli.prompts.js +87 -32
  195. package/dist/session/provider-cli/provider-cli.runtime.d.ts +8 -0
  196. package/dist/session/provider-cli/provider-cli.runtime.js +29 -1
  197. package/dist/session/provider-cli/provider-cli.service.d.ts +7 -1
  198. package/dist/session/provider-cli/provider-cli.service.js +207 -192
  199. package/dist/session/provider-cli/provider-cli.types.d.ts +30 -0
  200. package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
  201. package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
  202. package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
  203. package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
  204. package/dist/session/provider-cli/provider-in-flight-work.d.ts +10 -0
  205. package/dist/session/provider-cli/provider-in-flight-work.js +92 -0
  206. package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
  207. package/dist/session/provider-cli/provider-output-pipes.js +67 -0
  208. package/dist/session/provider-cli/provider-output-state.d.ts +8 -0
  209. package/dist/session/provider-cli/provider-output-state.js +15 -0
  210. package/dist/session/provider-cli/provider-user-config-isolation.d.ts +69 -0
  211. package/dist/session/provider-cli/provider-user-config-isolation.js +164 -0
  212. package/dist/session/publishable-worktree-changes.d.ts +54 -0
  213. package/dist/session/publishable-worktree-changes.js +193 -0
  214. package/dist/session/qa-sidecar-validation.d.ts +6 -0
  215. package/dist/session/qa-sidecar-validation.js +28 -0
  216. package/dist/session/sandbox-host-capacity-gate.d.ts +51 -0
  217. package/dist/session/sandbox-host-capacity-gate.js +257 -0
  218. package/dist/session/session-redaction.js +31 -181
  219. package/dist/session/session.base.d.ts +9 -1
  220. package/dist/session/session.service.d.ts +11 -2
  221. package/dist/session/session.service.js +189 -69
  222. package/dist/session/session.types.d.ts +3 -0
  223. package/dist/session/session.types.js +15 -3
  224. package/dist/session/sidecar-json-shape.d.ts +31 -0
  225. package/dist/session/sidecar-json-shape.js +217 -0
  226. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  227. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  228. package/dist/shared/fs/file-identity.d.ts +10 -0
  229. package/dist/shared/fs/file-identity.js +15 -0
  230. package/dist/shared/fs/replace-file.d.ts +7 -0
  231. package/dist/shared/fs/replace-file.js +33 -0
  232. package/dist/shared/process/host-process-recovery.d.ts +14 -3
  233. package/dist/shared/process/host-process-recovery.js +23 -3
  234. package/dist/shared/process/host-process-supervisor.d.ts +14 -1
  235. package/dist/shared/process/host-process-supervisor.js +67 -15
  236. package/dist/shared/process/process-tree.d.ts +52 -0
  237. package/dist/shared/process/process-tree.js +144 -0
  238. package/dist/shared/process/process.d.ts +67 -0
  239. package/dist/shared/process/process.js +213 -11
  240. package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
  241. package/dist/shared/process/windows-app-execution-alias.js +45 -0
  242. package/dist/shared/process/windows-launch.d.ts +18 -0
  243. package/dist/shared/process/windows-launch.js +68 -0
  244. package/dist/shared/provider-capabilities.js +14 -7
  245. package/dist/version.d.ts +1 -1
  246. package/dist/version.js +1 -1
  247. package/dist/worktree/dependency-warmer.d.ts +25 -0
  248. package/dist/worktree/dependency-warmer.js +46 -10
  249. package/dist/worktree/orphan-relink.d.ts +19 -0
  250. package/dist/worktree/orphan-relink.js +106 -0
  251. package/dist/worktree/wip-git.d.ts +33 -0
  252. package/dist/worktree/wip-git.js +122 -0
  253. package/dist/worktree/wip-refs.d.ts +62 -0
  254. package/dist/worktree/wip-refs.js +119 -0
  255. package/dist/worktree/wip-restore.d.ts +38 -0
  256. package/dist/worktree/wip-restore.js +190 -0
  257. package/dist/worktree/wip-snapshot.d.ts +50 -0
  258. package/dist/worktree/wip-snapshot.js +268 -0
  259. package/dist/worktree/worktree-inputs.d.ts +8 -0
  260. package/dist/worktree/worktree-inputs.js +134 -0
  261. package/dist/worktree/worktree-origin-sync.d.ts +34 -0
  262. package/dist/worktree/worktree-origin-sync.js +127 -0
  263. package/dist/worktree/worktree-wip-events.d.ts +18 -0
  264. package/dist/worktree/worktree-wip-events.js +98 -0
  265. package/dist/worktree/worktree-wip.d.ts +50 -0
  266. package/dist/worktree/worktree-wip.js +185 -0
  267. package/dist/worktree/worktree.base.d.ts +7 -1
  268. package/dist/worktree/worktree.service.d.ts +36 -5
  269. package/dist/worktree/worktree.service.js +124 -155
  270. package/dist/worktree/worktree.types.d.ts +38 -0
  271. package/package.json +2 -2
@@ -0,0 +1,69 @@
1
+ import { ForgeFailureError } from "../session/session.types.js";
2
+ /** Who holds the ledger lock; liveness is judged by the ledger's owner rules. */
3
+ export interface HostLoadLockHolder {
4
+ readonly pid: number;
5
+ readonly processInstanceId: string;
6
+ readonly processIdentity: string | null;
7
+ }
8
+ export interface HostLoadLedgerLockOptions {
9
+ readonly lockPath: string;
10
+ readonly holder: () => HostLoadLockHolder;
11
+ readonly isLive: (holder: HostLoadLockHolder) => boolean;
12
+ readonly timeoutMs: number;
13
+ /** A lock with no readable holder is broken only after this age. */
14
+ readonly unreadableStaleAfterMs?: number;
15
+ /** Test seam: runs after a lock was judged stale and before it is broken. */
16
+ readonly beforeStaleBreak?: () => Promise<void>;
17
+ }
18
+ export declare class HostCapacityLedgerUnavailableError extends ForgeFailureError {
19
+ readonly code = "host_capacity_ledger_unavailable";
20
+ constructor(detail: string, options?: ErrorOptions);
21
+ }
22
+ /**
23
+ * Cross-process exclusive lock file for the host load ledger.
24
+ *
25
+ * Every lock file, and every break lock, is claimed with a complete
26
+ * `{ token, holder }` record: written to a private temporary file and
27
+ * hard-linked into place, which fails if the path exists. No path is ever
28
+ * renamed or replaced, so nothing anyone holds can be moved out from under them.
29
+ *
30
+ * A lock is broken only when its holder is provably dead (or it has no readable
31
+ * holder and is old). Breakers of one stale lock serialize on a chain of break
32
+ * locks named after that lock's identity: `<lock>.break-<identity>.1`, `.2`, …
33
+ * A breaker claims the first link it can; it moves on to the next only when the
34
+ * holder of the current one is dead, and never removes it. Under its link it
35
+ * re-judges the lock and unlinks it only if the path still holds that same stale
36
+ * lock. Identities never repeat, so the stale lock cannot reappear, and while
37
+ * it exists nobody can create a new lock; so at most one live breaker can ever
38
+ * act on it, and the unlink can never touch a lock someone acquired meanwhile.
39
+ */
40
+ export declare class HostLoadLedgerLock {
41
+ private readonly options;
42
+ constructor(options: HostLoadLedgerLockOptions);
43
+ acquire(): Promise<string>;
44
+ /**
45
+ * Creates `target` holding a complete `{ token, holder }` record, or fails with
46
+ * EEXIST. `link` never replaces an existing path, and the record is fully
47
+ * written before the path appears.
48
+ */
49
+ private claim;
50
+ /** True while `token` still owns the lock file. */
51
+ holds(token: string): Promise<boolean>;
52
+ release(token: string): Promise<void>;
53
+ private breakIfStale;
54
+ /**
55
+ * The lock at `lockPath` if it is stale (with an identity that never repeats:
56
+ * its token, or for an unreadable file its inode and timestamps), "absent" if
57
+ * there is none, or null if it is live or too young to judge.
58
+ */
59
+ private judgeStale;
60
+ /**
61
+ * Claims the next free link of the stale lock's break chain, held only for the
62
+ * few milliseconds the lock is re-judged and unlinked. A link whose holder is
63
+ * live means another breaker is on it; a dead holder's link is skipped, never
64
+ * removed or replaced.
65
+ */
66
+ private acquireBreaker;
67
+ /** Removes `link` if `token` holds it, or unconditionally (null) once the stale lock it guarded is gone. */
68
+ private releaseOwn;
69
+ }
@@ -0,0 +1,187 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import fs from "node:fs/promises";
3
+ import { ForgeFailureError } from "../session/session.types.js";
4
+ import { fileIdentityKey } from "../shared/fs/file-identity.js";
5
+ export class HostCapacityLedgerUnavailableError extends ForgeFailureError {
6
+ code = "host_capacity_ledger_unavailable";
7
+ constructor(detail, options) {
8
+ super("host_capacity_ledger_unavailable", `host_capacity_ledger_unavailable: ${detail}`, "bridge", options);
9
+ this.name = "HostCapacityLedgerUnavailableError";
10
+ }
11
+ }
12
+ /**
13
+ * Cross-process exclusive lock file for the host load ledger.
14
+ *
15
+ * Every lock file, and every break lock, is claimed with a complete
16
+ * `{ token, holder }` record: written to a private temporary file and
17
+ * hard-linked into place, which fails if the path exists. No path is ever
18
+ * renamed or replaced, so nothing anyone holds can be moved out from under them.
19
+ *
20
+ * A lock is broken only when its holder is provably dead (or it has no readable
21
+ * holder and is old). Breakers of one stale lock serialize on a chain of break
22
+ * locks named after that lock's identity: `<lock>.break-<identity>.1`, `.2`, …
23
+ * A breaker claims the first link it can; it moves on to the next only when the
24
+ * holder of the current one is dead, and never removes it. Under its link it
25
+ * re-judges the lock and unlinks it only if the path still holds that same stale
26
+ * lock. Identities never repeat, so the stale lock cannot reappear, and while
27
+ * it exists nobody can create a new lock; so at most one live breaker can ever
28
+ * act on it, and the unlink can never touch a lock someone acquired meanwhile.
29
+ */
30
+ export class HostLoadLedgerLock {
31
+ options;
32
+ constructor(options) {
33
+ this.options = options;
34
+ }
35
+ async acquire() {
36
+ const token = randomUUID();
37
+ const started = Date.now();
38
+ for (;;) {
39
+ try {
40
+ await this.claim(this.options.lockPath, token);
41
+ return token;
42
+ }
43
+ catch (error) {
44
+ if (error.code !== "EEXIST")
45
+ throw error;
46
+ if (await this.breakIfStale())
47
+ continue;
48
+ if (Date.now() - started >= this.options.timeoutMs) {
49
+ throw new HostCapacityLedgerUnavailableError("the host load ledger lock could not be acquired.", { cause: error });
50
+ }
51
+ await new Promise(resolve => setTimeout(resolve, 10));
52
+ }
53
+ }
54
+ }
55
+ /**
56
+ * Creates `target` holding a complete `{ token, holder }` record, or fails with
57
+ * EEXIST. `link` never replaces an existing path, and the record is fully
58
+ * written before the path appears.
59
+ */
60
+ async claim(target, token) {
61
+ const temporary = `${target}.${randomUUID()}.claim`;
62
+ try {
63
+ const handle = await fs.open(temporary, "wx", 0o600);
64
+ try {
65
+ await handle.writeFile(JSON.stringify({ token, holder: this.options.holder() }));
66
+ }
67
+ finally {
68
+ await handle.close();
69
+ }
70
+ await fs.link(temporary, target);
71
+ }
72
+ finally {
73
+ await fs.rm(temporary, { force: true }).catch(() => undefined);
74
+ }
75
+ }
76
+ /** True while `token` still owns the lock file. */
77
+ async holds(token) {
78
+ return (await readLock(this.options.lockPath))?.token === token;
79
+ }
80
+ async release(token) {
81
+ // Only a breaker removes a lock it did not take, and only a stale one: a live
82
+ // holder's file cannot change between this check and the removal.
83
+ if (await this.holds(token))
84
+ await fs.rm(this.options.lockPath, { force: true });
85
+ }
86
+ async breakIfStale() {
87
+ const observed = await this.judgeStale(this.options.lockPath);
88
+ if (observed === "absent")
89
+ return true;
90
+ if (!observed)
91
+ return false;
92
+ await this.options.beforeStaleBreak?.();
93
+ const breaker = await this.acquireBreaker(observed.identity);
94
+ if (!breaker)
95
+ return false;
96
+ let broken = false;
97
+ try {
98
+ // Re-judged under the break lock: the path must still hold the same stale lock.
99
+ const current = await this.judgeStale(this.options.lockPath);
100
+ if (current === "absent")
101
+ return true;
102
+ if (!current || current.identity !== observed.identity)
103
+ return false;
104
+ await fs.unlink(this.options.lockPath).catch(error => {
105
+ if (error.code !== "ENOENT")
106
+ throw error;
107
+ });
108
+ broken = true;
109
+ return true;
110
+ }
111
+ finally {
112
+ // Once the stale lock is gone its chain is never needed again: dead breakers'
113
+ // links are cleared too. Otherwise only this breaker's own link is returned.
114
+ const links = broken ? breaker.chain : [breaker.path];
115
+ await Promise.all(links.map(link => this.releaseOwn(link, broken ? null : breaker.token)));
116
+ }
117
+ }
118
+ /**
119
+ * The lock at `lockPath` if it is stale (with an identity that never repeats:
120
+ * its token, or for an unreadable file its inode and timestamps), "absent" if
121
+ * there is none, or null if it is live or too young to judge.
122
+ */
123
+ async judgeStale(lockPath) {
124
+ // Exact (bigint) stats: a rounded Windows file id could name a different lock file.
125
+ const stat = await fs.lstat(lockPath, { bigint: true }).catch(() => null);
126
+ if (!stat)
127
+ return "absent";
128
+ const observed = stat.isFile() && stat.size <= 16n * 1024n ? await readLock(lockPath) : null;
129
+ if (observed?.holder && validHolder(observed.holder) && typeof observed.token === "string") {
130
+ // A live holder keeps its lock however old it is.
131
+ if (this.options.isLive(observed.holder))
132
+ return null;
133
+ return { identity: `t-${observed.token}` };
134
+ }
135
+ // Unreadable (claims are atomic, so this is corruption): give it until the stale age.
136
+ if (Date.now() - Number(stat.mtimeMs) < (this.options.unreadableStaleAfterMs ?? 30_000))
137
+ return null;
138
+ return { identity: `i-${fileIdentityKey(stat).replace(":", "-")}-${stat.mtimeNs}-${stat.size}` };
139
+ }
140
+ /**
141
+ * Claims the next free link of the stale lock's break chain, held only for the
142
+ * few milliseconds the lock is re-judged and unlinked. A link whose holder is
143
+ * live means another breaker is on it; a dead holder's link is skipped, never
144
+ * removed or replaced.
145
+ */
146
+ async acquireBreaker(identity) {
147
+ const base = `${this.options.lockPath}.break-${identity.replace(/[^A-Za-z0-9-]/gu, "_")}`;
148
+ const token = randomUUID();
149
+ const chain = [];
150
+ for (let generation = 1; generation <= maximumBreakGenerations; generation += 1) {
151
+ const link = `${base}.${generation}`;
152
+ chain.push(link);
153
+ try {
154
+ await this.claim(link, token);
155
+ return { path: link, token, chain };
156
+ }
157
+ catch (error) {
158
+ if (error.code !== "EEXIST")
159
+ throw error;
160
+ }
161
+ const holder = await this.judgeStale(link);
162
+ // Live (or just written): another breaker is on it. Gone: retry from the start later.
163
+ if (holder === null || holder === "absent")
164
+ return null;
165
+ }
166
+ return null;
167
+ }
168
+ /** Removes `link` if `token` holds it, or unconditionally (null) once the stale lock it guarded is gone. */
169
+ async releaseOwn(link, token) {
170
+ if (token === null || (await readLock(link))?.token === token)
171
+ await fs.rm(link, { force: true }).catch(() => undefined);
172
+ }
173
+ }
174
+ /** A chain longer than this means breakers keep dying; the acquire times out instead. */
175
+ const maximumBreakGenerations = 16;
176
+ async function readLock(lockPath) {
177
+ return await fs.readFile(lockPath, "utf8")
178
+ .then(value => JSON.parse(value))
179
+ .catch(() => null);
180
+ }
181
+ function validHolder(value) {
182
+ const holder = value;
183
+ return Boolean(holder)
184
+ && Number.isSafeInteger(holder.pid) && holder.pid > 0
185
+ && typeof holder.processInstanceId === "string"
186
+ && (holder.processIdentity === null || typeof holder.processIdentity === "string");
187
+ }
@@ -0,0 +1,25 @@
1
+ export interface HostLoadRuntimeOverrides {
2
+ /** Share of logical CPUs heavy steps may reserve: the CPU budget, or the yield budget while yielding. */
3
+ readonly cpuBudgetFraction: number;
4
+ /** Host-wide count of heavy steps at once; null means the budget alone limits them. */
5
+ readonly maxHeavySteps: number | null;
6
+ /** For diagnostics: whether the budget above is the yield budget. */
7
+ readonly yielding: boolean;
8
+ }
9
+ export declare function hostLoadRuntimeSettingsPath(stateRoot: string): string;
10
+ /** Atomically replaces the overrides every governor on this state root reads. */
11
+ export declare function writeHostLoadRuntimeSettings(stateRoot: string, overrides: HostLoadRuntimeOverrides): Promise<void>;
12
+ /** Bridge startup: drops overrides an earlier bridge process left behind. */
13
+ export declare function resetHostLoadRuntimeSettings(stateRoot: string): Promise<void>;
14
+ /**
15
+ * Reads the overrides at admission time. The parsed file is cached by mtime and
16
+ * size, so a governor re-checking its queue every second costs one stat. A
17
+ * missing or unreadable file means no overrides.
18
+ */
19
+ export declare class HostLoadRuntimeSettingsReader {
20
+ private readonly filePath;
21
+ private cachedKey;
22
+ private cached;
23
+ constructor(stateRoot: string);
24
+ read(): Promise<HostLoadRuntimeOverrides | null>;
25
+ }
@@ -0,0 +1,80 @@
1
+ import fs from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { randomUUID } from "node:crypto";
4
+ import { fileIdentityKey } from "../shared/fs/file-identity.js";
5
+ export function hostLoadRuntimeSettingsPath(stateRoot) {
6
+ return path.join(stateRoot, "host-load-governor", "runner-settings.v1.json");
7
+ }
8
+ /** Atomically replaces the overrides every governor on this state root reads. */
9
+ export async function writeHostLoadRuntimeSettings(stateRoot, overrides) {
10
+ const filePath = hostLoadRuntimeSettingsPath(stateRoot);
11
+ const content = {
12
+ schemaVersion: 1,
13
+ cpuBudgetFraction: overrides.cpuBudgetFraction,
14
+ maxHeavySteps: overrides.maxHeavySteps,
15
+ yielding: overrides.yielding,
16
+ writtenAt: new Date().toISOString(),
17
+ writerPid: process.pid,
18
+ };
19
+ await fs.mkdir(path.dirname(filePath), { recursive: true, mode: 0o700 });
20
+ const temporary = `${filePath}.${process.pid}.${randomUUID()}.tmp`;
21
+ try {
22
+ await fs.writeFile(temporary, `${JSON.stringify(content)}\n`, { mode: 0o600 });
23
+ await fs.rename(temporary, filePath);
24
+ }
25
+ catch (error) {
26
+ await fs.rm(temporary, { force: true }).catch(() => undefined);
27
+ throw error;
28
+ }
29
+ }
30
+ /** Bridge startup: drops overrides an earlier bridge process left behind. */
31
+ export async function resetHostLoadRuntimeSettings(stateRoot) {
32
+ await fs.rm(hostLoadRuntimeSettingsPath(stateRoot), { force: true });
33
+ }
34
+ /**
35
+ * Reads the overrides at admission time. The parsed file is cached by mtime and
36
+ * size, so a governor re-checking its queue every second costs one stat. A
37
+ * missing or unreadable file means no overrides.
38
+ */
39
+ export class HostLoadRuntimeSettingsReader {
40
+ filePath;
41
+ cachedKey = null;
42
+ cached = null;
43
+ constructor(stateRoot) {
44
+ this.filePath = hostLoadRuntimeSettingsPath(stateRoot);
45
+ }
46
+ async read() {
47
+ let key;
48
+ try {
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)}`;
52
+ }
53
+ catch {
54
+ this.cachedKey = null;
55
+ this.cached = null;
56
+ return null;
57
+ }
58
+ if (key === this.cachedKey)
59
+ return this.cached;
60
+ const parsed = await fs.readFile(this.filePath, "utf8").then(parseOverrides).catch(() => null);
61
+ this.cachedKey = key;
62
+ this.cached = parsed;
63
+ return parsed;
64
+ }
65
+ }
66
+ function parseOverrides(content) {
67
+ const raw = JSON.parse(content);
68
+ if (!raw || raw.schemaVersion !== 1)
69
+ return null;
70
+ const fraction = raw.cpuBudgetFraction;
71
+ if (typeof fraction !== "number" || !Number.isFinite(fraction))
72
+ return null;
73
+ const steps = raw.maxHeavySteps;
74
+ return {
75
+ // The governor config's own bounds for the budget fraction.
76
+ cpuBudgetFraction: Math.min(1, Math.max(0.05, fraction)),
77
+ maxHeavySteps: typeof steps === "number" && Number.isInteger(steps) && steps >= 1 ? Math.min(64, steps) : null,
78
+ yielding: raw.yielding === true,
79
+ };
80
+ }
@@ -0,0 +1,156 @@
1
+ import { type HostEnvironment, type HostFacts } from "./host-facts.js";
2
+ import { type PressureStallResource } from "./host-pressure-stall.js";
3
+ import { type ForgeCgroupSource } from "./host-load-forge-cgroups.js";
4
+ export interface HostSystemPressure {
5
+ readonly cpu: PressureStallResource | null;
6
+ readonly memory: PressureStallResource | null;
7
+ readonly io: PressureStallResource | null;
8
+ }
9
+ /** Load attributed to the systemd unit (cgroup v2) the bridge itself runs in. */
10
+ export interface HostOwnCgroupLoad {
11
+ readonly unit: string;
12
+ readonly cpuPressure: PressureStallResource | null;
13
+ readonly memoryPressure: PressureStallResource | null;
14
+ /** CPU cores consumed by the unit, from `cpu.stat` usage deltas between samples. */
15
+ readonly cpuCoresInUse: number | null;
16
+ /** Anonymous memory (`memory.stat` anon): the RSS-like figure, excluding page cache. */
17
+ readonly memoryAnonBytes: number | null;
18
+ /** All memory charged to the unit (`memory.current`), including page cache. */
19
+ readonly memoryChargedBytes: number | null;
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";
26
+ /** Live host load. Reported in every heartbeat but never a material capability signal. */
27
+ export interface HostLoadSnapshot {
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
+ */
34
+ readonly psiAvailable: boolean;
35
+ /** Null exactly when `psiAvailable` is false. */
36
+ readonly pressureSource: HostLoadPressureSource | null;
37
+ readonly systemPressure: HostSystemPressure | null;
38
+ /** True only when the bridge runs in a cgroup of its own (see isDedicatedBridgeUnit). */
39
+ readonly ownCgroupDedicated: boolean;
40
+ /** Reported only for a dedicated unit; never a shared terminal/session/app scope. */
41
+ readonly ownCgroup: HostOwnCgroupLoad | null;
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;
49
+ }
50
+ /** What the bridge service needs: static facts plus the latest cached load sample. */
51
+ export interface HostLoadSource {
52
+ start(): Promise<void>;
53
+ stop(): void;
54
+ facts(): HostFacts | null;
55
+ current(): HostLoadSnapshot | null;
56
+ /**
57
+ * Recent samples, oldest first, ending with `current()`. The governor reads its
58
+ * pressure streak from them, so samples taken while no step waited still count.
59
+ */
60
+ recent(): readonly HostLoadSnapshot[];
61
+ }
62
+ /**
63
+ * Host CPU time split into the bridge's own share and everything else, over one
64
+ * sampling window (decision 0013). Kept in the bridge for the host load governor;
65
+ * it is not part of the heartbeat payload.
66
+ */
67
+ export interface HostCpuAttribution {
68
+ readonly sampledAt: string;
69
+ /** Busy cores on the whole host, from /proc/stat deltas (os.cpus() deltas on Windows). */
70
+ readonly hostCoresInUse: number;
71
+ /** Cores used by the bridge's dedicated cgroup; null when the cgroup is not dedicated. */
72
+ readonly ownCoresInUse: number | null;
73
+ /** hostCoresInUse minus ownCoresInUse; null unless the own share is known. */
74
+ readonly externalCoresInUse: number | null;
75
+ }
76
+ /** The governor's view: the load sample plus the CPU attribution from the same window. */
77
+ export interface HostLoadGovernorSource extends Pick<HostLoadSource, "start" | "facts" | "current" | "recent"> {
78
+ cpuAttribution?(): HostCpuAttribution | null;
79
+ /**
80
+ * Free memory under the tightest cgroup `memory.max` on the bridge's path
81
+ * (null when none is set), from the latest sample. The governor budgets
82
+ * against the smaller of this and MemAvailable (decision 0013).
83
+ */
84
+ cgroupMemoryHeadroomBytes?(): number | null;
85
+ }
86
+ export interface HostLoadSamplerOptions {
87
+ readonly environment?: HostEnvironment;
88
+ readonly intervalMs?: number;
89
+ /** Wall clock for `sampledAt`. */
90
+ readonly now?: () => number;
91
+ /** Monotonic clock (ms) for usage deltas, so wall-clock steps cannot skew cores in use. */
92
+ readonly monotonicNow?: () => number;
93
+ /** Systemd unit the operator dedicates to the bridge (FORGE_BRIDGE_CGROUP_UNIT). */
94
+ readonly cgroupUnit?: string | null;
95
+ /** Docker sandbox cgroups whose CPU time is Forge's own, not external load. */
96
+ readonly forgeCgroups?: ForgeCgroupSource;
97
+ }
98
+ export declare const defaultHostLoadSampleIntervalMs = 5000;
99
+ /**
100
+ * Samples Linux PSI and the bridge's own cgroup on an interval and caches the
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).
104
+ */
105
+ export declare class HostLoadSampler implements HostLoadSource {
106
+ private readonly environment;
107
+ private readonly intervalMs;
108
+ private readonly now;
109
+ private readonly monotonicNow;
110
+ private readonly cgroupUnit;
111
+ private generation;
112
+ private timer;
113
+ private starting;
114
+ private inFlight;
115
+ private hostFacts;
116
+ private latest;
117
+ private readonly history;
118
+ private cpuMark;
119
+ private hostCpuMark;
120
+ private latestCpuAttribution;
121
+ private latestMemoryHeadroom;
122
+ private windowsCpuMark;
123
+ private readonly windowsCpuPressure;
124
+ private readonly forgeCgroups;
125
+ private readonly sandboxCpu;
126
+ constructor(options?: HostLoadSamplerOptions);
127
+ facts(): HostFacts | null;
128
+ current(): HostLoadSnapshot | null;
129
+ cpuAttribution(): HostCpuAttribution | null;
130
+ cgroupMemoryHeadroomBytes(): number | null;
131
+ recent(): readonly HostLoadSnapshot[];
132
+ /** Detects static facts once, takes a first sample, then samples on the interval. Idempotent. */
133
+ start(): Promise<void>;
134
+ stop(): void;
135
+ /** Takes one sample now and caches it. Concurrent callers share one read. */
136
+ sample(): Promise<HostLoadSnapshot>;
137
+ private startOnce;
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;
147
+ private readCgroupMemoryHeadroom;
148
+ private readSystemPressure;
149
+ private readOwnCgroup;
150
+ private coresInUse;
151
+ /** Busy share (0-1) of all logical CPUs since the last /proc/stat reading. */
152
+ private readHostCpuUse;
153
+ private readMemoryAvailable;
154
+ private fallbackFreeMemory;
155
+ private readPressure;
156
+ }