@loucompanion/forge-bridge 0.1.4-dev.494233aa2e50 → 0.1.4-dev.4e7855579f82

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 (217) 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 +89 -14
  16. package/dist/bridge/bridge.service.js +423 -342
  17. package/dist/bridge/bridge.types.d.ts +21 -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 +5 -0
  25. package/dist/bridge/runner-host-capabilities.js +17 -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/bridge/test-postgres-capability.d.ts +14 -0
  29. package/dist/bridge/test-postgres-capability.js +120 -0
  30. package/dist/cleanup/cleanup.service.d.ts +9 -0
  31. package/dist/cleanup/cleanup.service.js +72 -109
  32. package/dist/cleanup/cleanup.types.d.ts +4 -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 +152 -187
  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 +138 -6
  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 +67 -0
  59. package/dist/runtime/host-load-admission.js +99 -0
  60. package/dist/runtime/host-load-child-environment.d.ts +27 -0
  61. package/dist/runtime/host-load-child-environment.js +76 -0
  62. package/dist/runtime/host-load-forge-cgroups.d.ts +49 -0
  63. package/dist/runtime/host-load-forge-cgroups.js +140 -0
  64. package/dist/runtime/host-load-governor-config.d.ts +52 -0
  65. package/dist/runtime/host-load-governor-config.js +83 -0
  66. package/dist/runtime/host-load-governor.d.ts +184 -0
  67. package/dist/runtime/host-load-governor.js +632 -0
  68. package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
  69. package/dist/runtime/host-load-ledger-lock.js +185 -0
  70. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  71. package/dist/runtime/host-load-runtime-settings.js +78 -0
  72. package/dist/runtime/host-load-sampler.d.ts +75 -2
  73. package/dist/runtime/host-load-sampler.js +142 -8
  74. package/dist/runtime/host-load-step-class.d.ts +70 -0
  75. package/dist/runtime/host-load-step-class.js +161 -0
  76. package/dist/runtime/host-load-step-reaper.d.ts +27 -0
  77. package/dist/runtime/host-load-step-reaper.js +95 -0
  78. package/dist/runtime/host-load-step-run.d.ts +73 -0
  79. package/dist/runtime/host-load-step-run.js +102 -0
  80. package/dist/runtime/host-load-test-slot.d.ts +43 -0
  81. package/dist/runtime/host-load-test-slot.js +81 -0
  82. package/dist/runtime/host-load-token-ledger.d.ts +200 -0
  83. package/dist/runtime/host-load-token-ledger.js +453 -0
  84. package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
  85. package/dist/runtime/host-load-windows-cpu.js +85 -0
  86. package/dist/runtime/host-pressure-stall.d.ts +21 -1
  87. package/dist/runtime/host-pressure-stall.js +48 -1
  88. package/dist/runtime/host-runtime-contract.d.ts +15 -0
  89. package/dist/runtime/host-runtime-contract.js +33 -2
  90. package/dist/runtime/host-runtime-lease.d.ts +74 -4
  91. package/dist/runtime/host-runtime-lease.js +285 -55
  92. package/dist/runtime/host-runtime-promotion.d.ts +23 -0
  93. package/dist/runtime/host-runtime-promotion.js +48 -0
  94. package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
  95. package/dist/runtime/host-runtime-requirements-check.js +29 -0
  96. package/dist/runtime/host-runtime-requirements.d.ts +36 -0
  97. package/dist/runtime/host-runtime-requirements.js +117 -0
  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/playwright-host-runtime-adapter.d.ts +7 -0
  101. package/dist/runtime/playwright-host-runtime-adapter.js +13 -1
  102. package/dist/runtime/runner-settings.d.ts +104 -0
  103. package/dist/runtime/runner-settings.js +236 -0
  104. package/dist/sandbox/host-capacity-broker.d.ts +113 -0
  105. package/dist/sandbox/host-capacity-broker.js +334 -0
  106. package/dist/sandbox/runtime.d.ts +10 -1
  107. package/dist/sandbox/runtime.js +45 -2
  108. package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
  109. package/dist/sandbox/sandbox-cgroups.js +42 -0
  110. package/dist/session/architect-waits.d.ts +2 -0
  111. package/dist/session/architect-waits.js +138 -0
  112. package/dist/session/managed-attempt-tools.d.ts +2 -7
  113. package/dist/session/managed-attempt-tools.js +200 -92
  114. package/dist/session/managed-command-host-load.d.ts +47 -0
  115. package/dist/session/managed-command-host-load.js +83 -0
  116. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  117. package/dist/session/mcp-argument-coercion.js +121 -0
  118. package/dist/session/phase-completion.artifacts.d.ts +7 -0
  119. package/dist/session/phase-completion.artifacts.js +96 -26
  120. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  121. package/dist/session/phase-completion.command-validation.js +77 -0
  122. package/dist/session/phase-completion.d.ts +12 -0
  123. package/dist/session/phase-completion.helpers.js +13 -12
  124. package/dist/session/phase-completion.js +5 -0
  125. package/dist/session/phase-completion.mcp-args.d.ts +9 -0
  126. package/dist/session/phase-completion.mcp-args.js +156 -0
  127. package/dist/session/phase-completion.prompts.js +6 -1
  128. package/dist/session/phase-completion.runtime.d.ts +5 -11
  129. package/dist/session/phase-completion.runtime.js +91 -215
  130. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  131. package/dist/session/phase-completion.schema-parts.js +188 -0
  132. package/dist/session/phase-completion.schemas.d.ts +3 -3
  133. package/dist/session/phase-completion.schemas.js +208 -231
  134. package/dist/session/phase-completion.validation.d.ts +2 -3
  135. package/dist/session/phase-completion.validation.js +49 -93
  136. package/dist/session/pre-publication-host-load.d.ts +27 -0
  137. package/dist/session/pre-publication-host-load.js +111 -0
  138. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  139. package/dist/session/pre-publication-native-postgres.js +111 -0
  140. package/dist/session/pre-publication-pass.d.ts +61 -0
  141. package/dist/session/pre-publication-pass.js +148 -0
  142. package/dist/session/pre-publication-process.d.ts +3 -0
  143. package/dist/session/pre-publication-process.js +23 -11
  144. package/dist/session/pre-publication-step-execution.d.ts +12 -0
  145. package/dist/session/pre-publication-step-execution.js +50 -0
  146. package/dist/session/pre-publication-validation.d.ts +37 -21
  147. package/dist/session/pre-publication-validation.js +221 -182
  148. package/dist/session/provider-cli/claude-background-work.d.ts +67 -0
  149. package/dist/session/provider-cli/claude-background-work.js +181 -0
  150. package/dist/session/provider-cli/host-build-lock.d.ts +18 -0
  151. package/dist/session/provider-cli/host-build-lock.js +30 -0
  152. package/dist/session/provider-cli/pre-publication-repair.d.ts +56 -0
  153. package/dist/session/provider-cli/pre-publication-repair.js +276 -0
  154. package/dist/session/provider-cli/provider-cli.artifacts.d.ts +2 -1
  155. package/dist/session/provider-cli/provider-cli.artifacts.js +20 -7
  156. package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
  157. package/dist/session/provider-cli/provider-cli.child-environment.js +75 -0
  158. package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
  159. package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
  160. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
  161. package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
  162. package/dist/session/provider-cli/provider-cli.process.d.ts +41 -31
  163. package/dist/session/provider-cli/provider-cli.process.js +139 -438
  164. package/dist/session/provider-cli/provider-cli.prompts.d.ts +10 -0
  165. package/dist/session/provider-cli/provider-cli.prompts.js +87 -32
  166. package/dist/session/provider-cli/provider-cli.runtime.d.ts +8 -0
  167. package/dist/session/provider-cli/provider-cli.runtime.js +29 -1
  168. package/dist/session/provider-cli/provider-cli.service.d.ts +7 -1
  169. package/dist/session/provider-cli/provider-cli.service.js +146 -182
  170. package/dist/session/provider-cli/provider-cli.types.d.ts +30 -0
  171. package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
  172. package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
  173. package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
  174. package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
  175. package/dist/session/provider-cli/provider-in-flight-work.d.ts +10 -0
  176. package/dist/session/provider-cli/provider-in-flight-work.js +92 -0
  177. package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
  178. package/dist/session/provider-cli/provider-output-pipes.js +67 -0
  179. package/dist/session/provider-cli/provider-output-state.d.ts +8 -0
  180. package/dist/session/provider-cli/provider-output-state.js +15 -0
  181. package/dist/session/provider-cli/provider-user-config-isolation.d.ts +69 -0
  182. package/dist/session/provider-cli/provider-user-config-isolation.js +164 -0
  183. package/dist/session/publishable-worktree-changes.d.ts +10 -1
  184. package/dist/session/publishable-worktree-changes.js +21 -5
  185. package/dist/session/qa-sidecar-validation.d.ts +6 -0
  186. package/dist/session/qa-sidecar-validation.js +28 -0
  187. package/dist/session/sandbox-host-capacity-gate.d.ts +30 -0
  188. package/dist/session/sandbox-host-capacity-gate.js +238 -0
  189. package/dist/session/session-redaction.js +31 -181
  190. package/dist/session/session.base.d.ts +9 -1
  191. package/dist/session/session.service.d.ts +9 -2
  192. package/dist/session/session.service.js +120 -5
  193. package/dist/session/session.types.d.ts +3 -0
  194. package/dist/session/session.types.js +13 -4
  195. package/dist/session/sidecar-json-shape.d.ts +31 -0
  196. package/dist/session/sidecar-json-shape.js +217 -0
  197. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  198. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  199. package/dist/shared/process/host-process-supervisor.d.ts +1 -0
  200. package/dist/shared/process/host-process-supervisor.js +1 -1
  201. package/dist/shared/process/process-tree.d.ts +52 -0
  202. package/dist/shared/process/process-tree.js +144 -0
  203. package/dist/shared/process/process.d.ts +67 -0
  204. package/dist/shared/process/process.js +213 -11
  205. package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
  206. package/dist/shared/process/windows-app-execution-alias.js +45 -0
  207. package/dist/shared/process/windows-launch.d.ts +18 -0
  208. package/dist/shared/process/windows-launch.js +68 -0
  209. package/dist/shared/provider-capabilities.js +14 -7
  210. package/dist/version.d.ts +1 -1
  211. package/dist/version.js +1 -1
  212. package/dist/worktree/dependency-warmer.d.ts +25 -0
  213. package/dist/worktree/dependency-warmer.js +46 -10
  214. package/dist/worktree/worktree.service.d.ts +10 -1
  215. package/dist/worktree/worktree.service.js +42 -2
  216. package/dist/worktree/worktree.types.d.ts +7 -0
  217. package/package.json +2 -2
@@ -0,0 +1,37 @@
1
+ import { type EphemeralTestPostgresCluster, type EphemeralTestPostgresOptions } from "./ephemeral-test-postgres.js";
2
+ import { type NativeTestPostgresFallback, type NativeTestPostgresGrant } from "./native-test-postgres-fallback.js";
3
+ export type StartEphemeralTestPostgres = (options: EphemeralTestPostgresOptions) => Promise<EphemeralTestPostgresCluster>;
4
+ /** The bin directory an ephemeral cluster runs from: the file's `postgresBin`, else the one holding psql. */
5
+ export declare function ephemeralTestPostgresBinDirectory(fallback: Pick<NativeTestPostgresFallback, "postgresBin">, psqlPath?: () => string | null): string;
6
+ /**
7
+ * Starts a throwaway cluster for one check and returns its grant. The grant's mode keeps the
8
+ * Docker semantics of the shared cluster: with Docker up, pinned-engine tests still start their
9
+ * own containers; with Docker down, they are skipped. The caller must call `release`.
10
+ */
11
+ export declare function startEphemeralTestPostgresGrant(fallback: Pick<NativeTestPostgresFallback, "postgresBin">, dockerAvailable: boolean, start?: StartEphemeralTestPostgres): Promise<NativeTestPostgresGrant>;
12
+ /** A managed verification command's database environment, and what to release when the command ends. */
13
+ export interface ManagedVerificationDatabase {
14
+ readonly environment: Readonly<Record<string, string>>;
15
+ /** The connection strings and their passwords, for redaction; never the mode or the cluster id. */
16
+ readonly secrets: readonly string[];
17
+ readonly release: () => Promise<void>;
18
+ }
19
+ /** A command that runs no verification profile gets no database. */
20
+ export declare const noManagedVerificationDatabase: ManagedVerificationDatabase;
21
+ /**
22
+ * Builds a command's setup from its database. If the setup throws, the command never starts and
23
+ * no caller holds the database, so it is released here before the error is rethrown.
24
+ */
25
+ export declare function setUpWithManagedVerificationDatabase<T>(database: Pick<ManagedVerificationDatabase, "release">, setUp: () => T): Promise<T>;
26
+ /**
27
+ * Releases a command's database once the command has ended. A cluster that would not stop is left
28
+ * disowned for the next start's reap; the failure goes to `report` instead of being dropped.
29
+ */
30
+ export declare function releaseManagedVerificationDatabase(database: Pick<ManagedVerificationDatabase, "release">, report: (message: string) => Promise<void>): Promise<void>;
31
+ /**
32
+ * Managed verification on an `ephemeral` host gets a throwaway cluster for the command's
33
+ * lifetime; every other host keeps managedVerificationDatabaseEnvironment's rules. A cluster
34
+ * that cannot start fails the command rather than silently handing it Docker or the shared
35
+ * cluster's narrower login.
36
+ */
37
+ export declare function managedVerificationDatabase(dockerAvailable?: () => Promise<boolean>, readFallback?: () => NativeTestPostgresFallback | null, start?: StartEphemeralTestPostgres): Promise<ManagedVerificationDatabase>;
@@ -0,0 +1,85 @@
1
+ import path from "node:path";
2
+ import { attemptDatabaseCapabilitySecrets, resolvePsqlPath } from "./attempt-database-broker.js";
3
+ import { EphemeralTestPostgresError, ephemeralTestPostgresClusterEnvironment, startEphemeralTestPostgres, } from "./ephemeral-test-postgres.js";
4
+ import { DockerEngineProbe } from "./docker-engine-probe.js";
5
+ import { managedVerificationDatabaseEnvironment, nativeTestPostgresFallbackConfigEnvironment, nativeTestPostgresFallbackDatabaseMode, nativeTestPostgresFallbackEnvironment, nativeTestPostgresPreferredDatabaseMode, readNativeTestPostgresFallback, } from "./native-test-postgres-fallback.js";
6
+ /** The bin directory an ephemeral cluster runs from: the file's `postgresBin`, else the one holding psql. */
7
+ export function ephemeralTestPostgresBinDirectory(fallback, psqlPath = resolvePsqlPath) {
8
+ if (fallback.postgresBin)
9
+ return fallback.postgresBin;
10
+ const psql = psqlPath();
11
+ if (!psql) {
12
+ throw new EphemeralTestPostgresError("no PostgreSQL install was found; set 'postgresBin' in native-test-postgres.json or FORGE_NATIVE_TEST_POSTGRES_PSQL.");
13
+ }
14
+ return path.dirname(psql);
15
+ }
16
+ /**
17
+ * Starts a throwaway cluster for one check and returns its grant. The grant's mode keeps the
18
+ * Docker semantics of the shared cluster: with Docker up, pinned-engine tests still start their
19
+ * own containers; with Docker down, they are skipped. The caller must call `release`.
20
+ */
21
+ export async function startEphemeralTestPostgresGrant(fallback, dockerAvailable, start = startEphemeralTestPostgres) {
22
+ const cluster = await start({ binDirectory: ephemeralTestPostgresBinDirectory(fallback) });
23
+ return {
24
+ connectionString: cluster.connectionString,
25
+ endpoint: cluster.endpoint,
26
+ mode: dockerAvailable ? nativeTestPostgresPreferredDatabaseMode : nativeTestPostgresFallbackDatabaseMode,
27
+ ephemeralClusterId: cluster.id,
28
+ release: cluster.release,
29
+ };
30
+ }
31
+ /** A command that runs no verification profile gets no database. */
32
+ export const noManagedVerificationDatabase = {
33
+ environment: {},
34
+ secrets: [],
35
+ release: async () => undefined,
36
+ };
37
+ /**
38
+ * Builds a command's setup from its database. If the setup throws, the command never starts and
39
+ * no caller holds the database, so it is released here before the error is rethrown.
40
+ */
41
+ export async function setUpWithManagedVerificationDatabase(database, setUp) {
42
+ try {
43
+ return setUp();
44
+ }
45
+ catch (error) {
46
+ await database.release().catch(() => undefined);
47
+ throw error;
48
+ }
49
+ }
50
+ /**
51
+ * Releases a command's database once the command has ended. A cluster that would not stop is left
52
+ * disowned for the next start's reap; the failure goes to `report` instead of being dropped.
53
+ */
54
+ export async function releaseManagedVerificationDatabase(database, report) {
55
+ try {
56
+ await database.release();
57
+ }
58
+ catch (error) {
59
+ await report(error instanceof Error ? error.message : String(error)).catch(() => undefined);
60
+ }
61
+ }
62
+ function databaseSecrets(environment) {
63
+ return Object.entries(environment)
64
+ .filter(([name]) => name !== "FORGE_MANAGED_VERIFICATION_DATABASE_MODE" && name !== ephemeralTestPostgresClusterEnvironment)
65
+ .flatMap(([, value]) => attemptDatabaseCapabilitySecrets(value));
66
+ }
67
+ /**
68
+ * Managed verification on an `ephemeral` host gets a throwaway cluster for the command's
69
+ * lifetime; every other host keeps managedVerificationDatabaseEnvironment's rules. A cluster
70
+ * that cannot start fails the command rather than silently handing it Docker or the shared
71
+ * cluster's narrower login.
72
+ */
73
+ export async function managedVerificationDatabase(dockerAvailable = async () => (await new DockerEngineProbe().probeWithoutRecovery()).available, readFallback = () => {
74
+ const configPath = process.env[nativeTestPostgresFallbackConfigEnvironment]?.trim();
75
+ return configPath ? readNativeTestPostgresFallback(configPath) : null;
76
+ }, start = startEphemeralTestPostgres) {
77
+ const fallback = readFallback();
78
+ if (fallback?.use !== "ephemeral") {
79
+ const environment = await managedVerificationDatabaseEnvironment(dockerAvailable, () => fallback);
80
+ return { environment, secrets: databaseSecrets(environment), release: async () => undefined };
81
+ }
82
+ const grant = await startEphemeralTestPostgresGrant(fallback, await dockerAvailable(), start);
83
+ const environment = nativeTestPostgresFallbackEnvironment(grant);
84
+ return { environment, secrets: databaseSecrets(environment), release: grant.release ?? (async () => undefined) };
85
+ }
@@ -0,0 +1,57 @@
1
+ /** Set for a test run on an ephemeral cluster: its id, which the server reports as `forge.ephemeral_cluster`. */
2
+ export declare const ephemeralTestPostgresClusterEnvironment = "FORGE_TEST_POSTGRES_EPHEMERAL_CLUSTER";
3
+ export declare const ephemeralTestPostgresMarkerSetting = "forge.ephemeral_cluster";
4
+ export declare class EphemeralTestPostgresError extends Error {
5
+ readonly code = "ephemeral_test_postgres_unavailable";
6
+ constructor(detail: string);
7
+ }
8
+ export interface EphemeralTestPostgresCluster {
9
+ readonly id: string;
10
+ readonly connectionString: string;
11
+ readonly endpoint: string;
12
+ readonly password: string;
13
+ /**
14
+ * Stops the server and deletes its directory. Safe to call more than once. Rejects, keeping the
15
+ * directory, when the server is still running after the stop.
16
+ */
17
+ release(): Promise<void>;
18
+ }
19
+ export interface ToolResult {
20
+ readonly code: number | null;
21
+ readonly output: string;
22
+ }
23
+ /** Runs one PostgreSQL program. `detached` programs (pg_ctl start) leave a server running, so their output goes to its log. */
24
+ export type EphemeralToolRunner = (file: string, args: readonly string[], options: {
25
+ readonly env: Readonly<Record<string, string>>;
26
+ readonly timeoutMs: number;
27
+ readonly detached?: boolean;
28
+ }) => Promise<ToolResult>;
29
+ export interface EphemeralTestPostgresOptions {
30
+ /** The directory holding initdb, pg_ctl and psql of the PostgreSQL install to run. */
31
+ readonly binDirectory: string;
32
+ readonly root?: string;
33
+ readonly ownerPid?: number;
34
+ readonly runTool?: EphemeralToolRunner;
35
+ readonly isProcessAlive?: (pid: number) => boolean;
36
+ readonly freePort?: () => Promise<number>;
37
+ readonly now?: () => number;
38
+ }
39
+ export declare function defaultEphemeralTestPostgresRoot(): string;
40
+ /**
41
+ * A superuser of a cluster run by the `postgres` OS user can read every cluster that user runs,
42
+ * including live ones (Debian and Ubuntu packages run them all as `postgres`). An ephemeral
43
+ * cluster therefore runs only as an ordinary user, the same one that already runs the attempt.
44
+ */
45
+ export declare function assertEphemeralClusterOsUser(userName?: string, uid?: number | undefined): void;
46
+ /** Creates, starts and prepares one cluster. On any failure nothing of it is left behind. */
47
+ export declare function startEphemeralTestPostgres(options: EphemeralTestPostgresOptions): Promise<EphemeralTestPostgresCluster>;
48
+ /**
49
+ * Removes clusters whose owning Bridge process is gone. Only directories named like a cluster
50
+ * id inside the root are considered, and a live owner's clusters are never touched.
51
+ */
52
+ export declare function reapEphemeralTestPostgres(options: EphemeralTestPostgresOptions): Promise<readonly string[]>;
53
+ /**
54
+ * On Windows a started postgres inherits pg_ctl's standard handles, so a pipe would stay open for
55
+ * the server's lifetime; a detached program gets no pipes and settles when it exits.
56
+ */
57
+ export declare const runPostgresTool: EphemeralToolRunner;
@@ -0,0 +1,303 @@
1
+ import { spawn } from "node:child_process";
2
+ import { randomBytes, randomUUID } from "node:crypto";
3
+ import fs from "node:fs/promises";
4
+ import net from "node:net";
5
+ import os from "node:os";
6
+ import path from "node:path";
7
+ // A throwaway PostgreSQL cluster for one test run (owner policy 2026-11-17: native PostgreSQL
8
+ // for every tier, made safe per attempt). The Bridge runs initdb in a fresh directory, starts
9
+ // the server on a free loopback port as its own OS user, and hands the test run the cluster's
10
+ // bootstrap superuser. The run is superuser of that cluster only: the cluster holds nothing but
11
+ // what the run creates, and it is stopped and deleted when the run ends. A Bridge that died
12
+ // before its release leaves a directory whose owner process is gone; the next start reaps it.
13
+ /** Set for a test run on an ephemeral cluster: its id, which the server reports as `forge.ephemeral_cluster`. */
14
+ export const ephemeralTestPostgresClusterEnvironment = "FORGE_TEST_POSTGRES_EPHEMERAL_CLUSTER";
15
+ export const ephemeralTestPostgresMarkerSetting = "forge.ephemeral_cluster";
16
+ const superuserName = "forge_ephemeral";
17
+ const ownerFileName = "owner.json";
18
+ const clusterDirectoryPattern = /^[0-9a-f]{32}$/u;
19
+ // A directory without a readable owner file is a start that is still writing it, or one that
20
+ // died before it could; only the second is old.
21
+ const unownedDirectoryGraceMs = 10 * 60_000;
22
+ const startAttempts = 3;
23
+ export class EphemeralTestPostgresError extends Error {
24
+ code = "ephemeral_test_postgres_unavailable";
25
+ constructor(detail) {
26
+ super(`ephemeral_test_postgres_unavailable: ${detail}`);
27
+ this.name = "EphemeralTestPostgresError";
28
+ }
29
+ }
30
+ export function defaultEphemeralTestPostgresRoot() {
31
+ if (process.platform === "win32") {
32
+ const localAppData = process.env.LOCALAPPDATA?.trim() || path.join(os.homedir(), "AppData", "Local");
33
+ return path.join(localAppData, "forge", "ephemeral-test-postgres");
34
+ }
35
+ const stateHome = process.env.XDG_STATE_HOME?.trim() || path.join(os.homedir(), ".local", "state");
36
+ return path.join(stateHome, "forge", "ephemeral-test-postgres");
37
+ }
38
+ function resolveOptions(options) {
39
+ return {
40
+ binDirectory: options.binDirectory,
41
+ root: options.root ?? defaultEphemeralTestPostgresRoot(),
42
+ ownerPid: options.ownerPid ?? process.pid,
43
+ runTool: options.runTool ?? runPostgresTool,
44
+ isProcessAlive: options.isProcessAlive ?? processIsAlive,
45
+ freePort: options.freePort ?? freeLoopbackPort,
46
+ now: options.now ?? Date.now,
47
+ };
48
+ }
49
+ function program(options, name) {
50
+ return path.join(options.binDirectory, process.platform === "win32" ? `${name}.exe` : name);
51
+ }
52
+ /**
53
+ * A superuser of a cluster run by the `postgres` OS user can read every cluster that user runs,
54
+ * including live ones (Debian and Ubuntu packages run them all as `postgres`). An ephemeral
55
+ * cluster therefore runs only as an ordinary user, the same one that already runs the attempt.
56
+ */
57
+ export function assertEphemeralClusterOsUser(userName = os.userInfo().username, uid = process.getuid?.()) {
58
+ if (uid === 0 || userName.toLowerCase() === "postgres") {
59
+ throw new EphemeralTestPostgresError(`ephemeral test clusters do not run as the '${uid === 0 ? "root" : userName}' OS user; run the Bridge as an ordinary user.`);
60
+ }
61
+ }
62
+ /** Creates, starts and prepares one cluster. On any failure nothing of it is left behind. */
63
+ export async function startEphemeralTestPostgres(options) {
64
+ assertEphemeralClusterOsUser();
65
+ const resolved = resolveOptions(options);
66
+ await reapEphemeralTestPostgres(options);
67
+ await fs.mkdir(resolved.root, { recursive: true });
68
+ const id = randomUUID().replaceAll("-", "");
69
+ const directory = path.join(resolved.root, id);
70
+ await fs.mkdir(directory);
71
+ const release = once(async () => await stopAndRemove(resolved, directory));
72
+ try {
73
+ await fs.writeFile(path.join(directory, ownerFileName), JSON.stringify({
74
+ schemaVersion: 1,
75
+ ownerPid: resolved.ownerPid,
76
+ createdAt: new Date(resolved.now()).toISOString(),
77
+ }));
78
+ const password = randomBytes(24).toString("hex");
79
+ await initializeCluster(resolved, directory, password);
80
+ const port = await startServer(resolved, directory, id);
81
+ await prepareCluster(resolved, port, password, id);
82
+ const endpoint = `127.0.0.1:${port}`;
83
+ return {
84
+ id,
85
+ endpoint,
86
+ password,
87
+ connectionString: `Host=127.0.0.1;Port=${port};Database=postgres;Username=${superuserName};Password=${password}`,
88
+ release,
89
+ };
90
+ }
91
+ catch (error) {
92
+ await release().catch(() => undefined);
93
+ throw error instanceof EphemeralTestPostgresError
94
+ ? error
95
+ : new EphemeralTestPostgresError(error instanceof Error ? error.message : String(error));
96
+ }
97
+ }
98
+ async function initializeCluster(options, directory, password) {
99
+ const passwordFile = path.join(directory, "bootstrap-password");
100
+ await fs.writeFile(passwordFile, password, { mode: 0o600 });
101
+ try {
102
+ const result = await options.runTool(program(options, "initdb"), [
103
+ "-D", path.join(directory, "data"),
104
+ "-U", superuserName,
105
+ "-A", "scram-sha-256",
106
+ `--pwfile=${passwordFile}`,
107
+ "-E", "UTF8",
108
+ "--locale=C",
109
+ // The cluster is deleted with its run, so durability buys nothing.
110
+ "--no-sync",
111
+ "--no-instructions",
112
+ ], { env: toolEnvironment(), timeoutMs: 120_000 });
113
+ if (result.code !== 0)
114
+ throw new EphemeralTestPostgresError(`initdb exited ${result.code}: ${tail(result.output)}`);
115
+ }
116
+ finally {
117
+ await fs.rm(passwordFile, { force: true });
118
+ }
119
+ }
120
+ function serverSettings(port, id) {
121
+ return [
122
+ "",
123
+ "# Forge ephemeral test cluster: loopback only, deleted with its test run.",
124
+ "listen_addresses = '127.0.0.1'",
125
+ `port = ${port}`,
126
+ "unix_socket_directories = ''",
127
+ // Each live test collection holds an API host's pools and a cloned database.
128
+ "max_connections = 300",
129
+ "fsync = off",
130
+ "synchronous_commit = off",
131
+ "full_page_writes = off",
132
+ `${ephemeralTestPostgresMarkerSetting} = '${id}'`,
133
+ "",
134
+ ].join("\n");
135
+ }
136
+ /** Starts the server on a free loopback port, choosing another if a racing process took it. */
137
+ async function startServer(options, directory, id) {
138
+ const data = path.join(directory, "data");
139
+ const configuration = path.join(data, "postgresql.conf");
140
+ const original = await fs.readFile(configuration, "utf8");
141
+ let lastFailure = "";
142
+ for (let attempt = 1; attempt <= startAttempts; attempt += 1) {
143
+ const port = await options.freePort();
144
+ await fs.writeFile(configuration, original + serverSettings(port, id));
145
+ const result = await options.runTool(program(options, "pg_ctl"), [
146
+ "-D", data, "-l", path.join(directory, "postgres.log"), "-w", "-t", "60", "start",
147
+ ], { env: toolEnvironment(), timeoutMs: 90_000, detached: true });
148
+ if (result.code === 0)
149
+ return port;
150
+ lastFailure = `pg_ctl start exited ${result.code}: ${await logTail(directory)}`;
151
+ }
152
+ throw new EphemeralTestPostgresError(lastFailure);
153
+ }
154
+ /** pgvector is not a trusted extension; installing it in template1 gives every test database the type. */
155
+ async function prepareCluster(options, port, password, id) {
156
+ const result = await options.runTool(program(options, "psql"), [
157
+ "-X", "-q", "-A", "-t", "-w", "-v", "ON_ERROR_STOP=1",
158
+ "-h", "127.0.0.1", "-p", String(port), "-U", superuserName, "-d", "template1",
159
+ "-c", "CREATE EXTENSION IF NOT EXISTS vector",
160
+ "-c", `SELECT current_setting('${ephemeralTestPostgresMarkerSetting}')`,
161
+ ], { env: { ...toolEnvironment(), PGPASSWORD: password, PGCONNECT_TIMEOUT: "10" }, timeoutMs: 60_000 });
162
+ if (result.code !== 0) {
163
+ throw new EphemeralTestPostgresError(`preparing the cluster failed: ${tail(result.output.replaceAll(password, "[redacted]"))}`);
164
+ }
165
+ if (result.output.trim() !== id) {
166
+ throw new EphemeralTestPostgresError("the started server did not report this cluster's marker.");
167
+ }
168
+ }
169
+ async function stopAndRemove(options, directory) {
170
+ const data = path.join(directory, "data");
171
+ if (await exists(path.join(data, "postmaster.pid"))) {
172
+ // Immediate: nothing in the cluster is worth a checkpoint.
173
+ const stopped = await options.runTool(program(options, "pg_ctl"), ["-D", data, "-m", "immediate", "-w", "-t", "30", "stop"], {
174
+ env: toolEnvironment(),
175
+ timeoutMs: 60_000,
176
+ });
177
+ if (stopped.code !== 0 && await serverStillRuns(options, data)) {
178
+ // Never delete a live server's directory. Disowning it lets the next start's reap try again.
179
+ await fs.writeFile(path.join(directory, ownerFileName), JSON.stringify({ schemaVersion: 1, ownerPid: null }))
180
+ .catch(() => undefined);
181
+ throw new EphemeralTestPostgresError(`pg_ctl stop exited ${stopped.code}; the cluster is left for the next reap: ${tail(stopped.output)}`);
182
+ }
183
+ }
184
+ await fs.rm(directory, { recursive: true, force: true, maxRetries: 10, retryDelay: 200 });
185
+ }
186
+ /** pg_ctl status exits 3 when no server runs in the directory; anything else counts as running. */
187
+ async function serverStillRuns(options, data) {
188
+ const status = await options.runTool(program(options, "pg_ctl"), ["-D", data, "status"], {
189
+ env: toolEnvironment(),
190
+ timeoutMs: 30_000,
191
+ }).catch(() => ({ code: null, output: "" }));
192
+ return status.code !== 3;
193
+ }
194
+ /**
195
+ * Removes clusters whose owning Bridge process is gone. Only directories named like a cluster
196
+ * id inside the root are considered, and a live owner's clusters are never touched.
197
+ */
198
+ export async function reapEphemeralTestPostgres(options) {
199
+ const resolved = resolveOptions(options);
200
+ let entries;
201
+ try {
202
+ entries = await fs.readdir(resolved.root);
203
+ }
204
+ catch (error) {
205
+ if (error.code === "ENOENT")
206
+ return [];
207
+ throw error;
208
+ }
209
+ const reaped = [];
210
+ for (const entry of entries.filter(name => clusterDirectoryPattern.test(name))) {
211
+ const directory = path.join(resolved.root, entry);
212
+ if (!await isAbandoned(resolved, directory))
213
+ continue;
214
+ try {
215
+ await stopAndRemove(resolved, directory);
216
+ reaped.push(entry);
217
+ }
218
+ catch {
219
+ // One stuck directory does not stop the rest; the next start tries again.
220
+ }
221
+ }
222
+ return reaped;
223
+ }
224
+ async function isAbandoned(options, directory) {
225
+ try {
226
+ const owner = JSON.parse(await fs.readFile(path.join(directory, ownerFileName), "utf8"));
227
+ return typeof owner.ownerPid !== "number" || !options.isProcessAlive(owner.ownerPid);
228
+ }
229
+ catch {
230
+ const stat = await fs.stat(directory).catch(() => null);
231
+ return stat !== null && options.now() - stat.mtimeMs > unownedDirectoryGraceMs;
232
+ }
233
+ }
234
+ function processIsAlive(pid) {
235
+ try {
236
+ process.kill(pid, 0);
237
+ return true;
238
+ }
239
+ catch (error) {
240
+ // EPERM: the process exists but belongs to someone else.
241
+ return error.code === "EPERM";
242
+ }
243
+ }
244
+ async function freeLoopbackPort() {
245
+ return await new Promise((resolve, reject) => {
246
+ const server = net.createServer();
247
+ server.once("error", reject);
248
+ server.listen(0, "127.0.0.1", () => {
249
+ const address = server.address();
250
+ server.close(() => typeof address === "object" && address
251
+ ? resolve(address.port)
252
+ : reject(new EphemeralTestPostgresError("no free loopback port")));
253
+ });
254
+ });
255
+ }
256
+ /** Only what the PostgreSQL programs need: never the Bridge's own environment. */
257
+ function toolEnvironment() {
258
+ const names = ["PATH", "SystemRoot", "TEMP", "TMP", "TMPDIR", "HOME", "USERPROFILE", "LANG"];
259
+ return Object.fromEntries(names.flatMap(name => process.env[name] ? [[name, process.env[name]]] : []));
260
+ }
261
+ /**
262
+ * On Windows a started postgres inherits pg_ctl's standard handles, so a pipe would stay open for
263
+ * the server's lifetime; a detached program gets no pipes and settles when it exits.
264
+ */
265
+ export const runPostgresTool = (file, args, options) => new Promise((resolve, reject) => {
266
+ const child = spawn(file, [...args], {
267
+ env: { ...options.env },
268
+ stdio: options.detached ? "ignore" : ["ignore", "pipe", "pipe"],
269
+ windowsHide: true,
270
+ });
271
+ let output = "";
272
+ child.stdout?.setEncoding("utf8").on("data", chunk => { output += chunk; });
273
+ child.stderr?.setEncoding("utf8").on("data", chunk => { output += chunk; });
274
+ const timer = setTimeout(() => child.kill(), options.timeoutMs);
275
+ child.once("error", error => {
276
+ clearTimeout(timer);
277
+ reject(error);
278
+ });
279
+ child.once(options.detached ? "exit" : "close", code => {
280
+ clearTimeout(timer);
281
+ resolve({ code, output });
282
+ });
283
+ });
284
+ async function logTail(directory) {
285
+ return tail(await fs.readFile(path.join(directory, "postgres.log"), "utf8").catch(() => ""));
286
+ }
287
+ function tail(text) {
288
+ return text.trim().slice(-1_500);
289
+ }
290
+ async function exists(file) {
291
+ return await fs.access(file).then(() => true, () => false);
292
+ }
293
+ function once(action) {
294
+ let running = null;
295
+ return async () => {
296
+ // A failed release may be retried; a successful one is not repeated.
297
+ running ??= action().catch(error => {
298
+ running = null;
299
+ throw error;
300
+ });
301
+ await running;
302
+ };
303
+ }
@@ -18,7 +18,8 @@ export interface HostEnvironment {
18
18
  readonly etcRoot: string;
19
19
  readonly cgroupRoot: string;
20
20
  readonly readFile: HostFileReader;
21
- readonly cpus: () => readonly Pick<os.CpuInfo, "model">[];
21
+ /** CPU models (host facts) and, where reported, cumulative CPU times (the Windows load sampler). */
22
+ readonly cpus: () => readonly (Pick<os.CpuInfo, "model"> & Partial<Pick<os.CpuInfo, "times">>)[];
22
23
  readonly totalMemoryBytes: () => number;
23
24
  readonly freeMemoryBytes: () => number;
24
25
  readonly architecture: () => string;
@@ -0,0 +1,67 @@
1
+ import type { HostLoadGovernorConfig } from "./host-load-governor-config.js";
2
+ import type { HostLoadStepCost } from "./host-load-step-class.js";
3
+ /** Measured host load the admission rule reads. Null means PSI is unavailable or stale. */
4
+ export interface HostLoadSignals {
5
+ /**
6
+ * Host-wide CPU PSI `some avg10`, used as is (never split per cgroup). On Windows,
7
+ * the estimate from host CPU use in the same shape (decision 0021).
8
+ */
9
+ readonly cpuSomeAvg10: number;
10
+ /** Consecutive samples, ending with the latest, at or above the CPU pressure threshold. */
11
+ readonly cpuPressuredSamples: number;
12
+ /** Host-wide memory PSI `full avg10`; a hard stop above its threshold. */
13
+ readonly memoryFullAvg10: number | null;
14
+ readonly memoryAvailableBytes: number | null;
15
+ /**
16
+ * Host CPU from /proc/stat minus the bridge's dedicated cgroup over the same
17
+ * window. Null when the bridge's cgroup is not dedicated: Forge's own work is
18
+ * then counted only through reserved cost and the host PSI gate.
19
+ */
20
+ readonly externalCpuCores: number | null;
21
+ }
22
+ export type HostLoadAdmissionReason = "admitted" | "admitted_alone" | "admitted_fallback" | "cpu_budget" | "memory_budget" | "cpu_pressure" | "memory_pressure" | "fallback_slots"
23
+ /** Decision 0014: the host already runs the owner's maximum number of heavy steps. */
24
+ | "heavy_step_limit"
25
+ /** A corrupt ledger was quarantined; admissions wait one lease while owners restore their reservations. */
26
+ | "ledger_recovering"
27
+ /** Decision 0018: the host test slot is free and this step is next in the host queue. */
28
+ | "admitted_test_slot"
29
+ /** Decision 0018: the host test slot is taken, or steps ahead in the host queue take it first. */
30
+ | "host_test_slot";
31
+ export interface HostLoadAdmissionInput {
32
+ readonly request: HostLoadStepCost;
33
+ /** Reserved cost of every live token on this host (all processes). */
34
+ readonly running: readonly HostLoadStepCost[];
35
+ /**
36
+ * Memory the running steps already use. MemAvailable already excludes it, so
37
+ * it is added back to the budget (capped at their reservations) instead of
38
+ * being counted twice.
39
+ */
40
+ readonly runningMemoryBytes?: number;
41
+ readonly logicalCpus: number;
42
+ readonly signals: HostLoadSignals | null;
43
+ readonly config: Pick<HostLoadGovernorConfig, "cpuBudgetFraction" | "memoryReserveBytes" | "cpuPressureThreshold" | "backpressureSamples" | "memoryFullThreshold" | "fallbackSlots">;
44
+ /**
45
+ * Decision 0014 "Max concurrent heavy steps": a host-wide count limit on top of
46
+ * the budget. Null or absent means the budget alone decides.
47
+ */
48
+ readonly maxHeavySteps?: number | null;
49
+ }
50
+ export interface HostLoadAdmissionDecision {
51
+ readonly admitted: boolean;
52
+ readonly reason: HostLoadAdmissionReason;
53
+ readonly cpuBudgetCores: number | null;
54
+ readonly memoryBudgetBytes: number | null;
55
+ readonly reservedCpuCores: number;
56
+ readonly reservedMemoryBytes: number;
57
+ readonly detail: string;
58
+ }
59
+ /**
60
+ * Decision 0013 admission rule. A step is admitted when the reserved cost of
61
+ * running steps plus its own cost fits the budget and host pressure is under
62
+ * the backpressure threshold. Memory `full` pressure is a hard stop. A step
63
+ * too large for the budget on its own runs only when nothing else does. An
64
+ * optional count limit (decision 0014) caps how many heavy steps run at once.
65
+ * Without PSI, a simple per-host semaphore applies instead.
66
+ */
67
+ export declare function decideHostLoadAdmission(input: HostLoadAdmissionInput): HostLoadAdmissionDecision;
@@ -0,0 +1,99 @@
1
+ const epsilon = 1e-9;
2
+ /**
3
+ * Decision 0013 admission rule. A step is admitted when the reserved cost of
4
+ * running steps plus its own cost fits the budget and host pressure is under
5
+ * the backpressure threshold. Memory `full` pressure is a hard stop. A step
6
+ * too large for the budget on its own runs only when nothing else does. An
7
+ * optional count limit (decision 0014) caps how many heavy steps run at once.
8
+ * Without PSI, a simple per-host semaphore applies instead.
9
+ */
10
+ export function decideHostLoadAdmission(input) {
11
+ const { request, running, signals, config } = input;
12
+ const reservedCpuCores = running.reduce((sum, cost) => sum + cost.cpuCores, 0);
13
+ const reservedMemoryBytes = running.reduce((sum, cost) => sum + cost.memoryBytes, 0);
14
+ const base = { reservedCpuCores, reservedMemoryBytes };
15
+ const maxHeavySteps = input.maxHeavySteps ?? null;
16
+ if (!signals) {
17
+ // The count limit narrows the semaphore: min(fallback slots, max heavy steps).
18
+ const limited = maxHeavySteps !== null && maxHeavySteps < config.fallbackSlots;
19
+ const slots = limited ? maxHeavySteps : config.fallbackSlots;
20
+ const admitted = running.length < slots;
21
+ return {
22
+ ...base,
23
+ admitted,
24
+ reason: admitted ? "admitted_fallback" : limited ? "heavy_step_limit" : "fallback_slots",
25
+ cpuBudgetCores: null,
26
+ memoryBudgetBytes: null,
27
+ detail: admitted
28
+ ? "Host pressure data is unavailable; admitted under the per-host step semaphore."
29
+ : limited
30
+ ? `Host pressure data is unavailable; ${running.length} of ${slots} heavy step(s) allowed at once are running (max heavy steps).`
31
+ : `Host pressure data is unavailable; ${running.length} of ${config.fallbackSlots} heavy step slot(s) are in use.`,
32
+ };
33
+ }
34
+ const cpuBudgetCores = Math.max(0, input.logicalCpus * config.cpuBudgetFraction - (signals.externalCpuCores ?? 0));
35
+ const usedByRunning = Math.min(reservedMemoryBytes, Math.max(0, input.runningMemoryBytes ?? 0));
36
+ const memoryBudgetBytes = signals.memoryAvailableBytes === null
37
+ ? null
38
+ : Math.max(0, signals.memoryAvailableBytes + usedByRunning - config.memoryReserveBytes);
39
+ const budget = { ...base, cpuBudgetCores, memoryBudgetBytes };
40
+ if (signals.memoryFullAvg10 !== null && signals.memoryFullAvg10 > config.memoryFullThreshold) {
41
+ return {
42
+ ...budget,
43
+ admitted: false,
44
+ reason: "memory_pressure",
45
+ detail: `Host memory pressure (full avg10 ${signals.memoryFullAvg10}%) is above ${config.memoryFullThreshold}%; no heavy step may start.`,
46
+ };
47
+ }
48
+ if (signals.cpuPressuredSamples >= config.backpressureSamples) {
49
+ return {
50
+ ...budget,
51
+ admitted: false,
52
+ reason: "cpu_pressure",
53
+ detail: `Host CPU pressure (some avg10 ${signals.cpuSomeAvg10}%) has been at or above ${config.cpuPressureThreshold}% for ${signals.cpuPressuredSamples} sample(s).`,
54
+ };
55
+ }
56
+ if (maxHeavySteps !== null && running.length >= maxHeavySteps) {
57
+ return {
58
+ ...budget,
59
+ admitted: false,
60
+ reason: "heavy_step_limit",
61
+ detail: `${running.length} heavy step(s) are running and the host allows at most ${maxHeavySteps} at once.`,
62
+ };
63
+ }
64
+ if (running.length === 0) {
65
+ const oversize = request.cpuCores > cpuBudgetCores + epsilon
66
+ || (memoryBudgetBytes !== null && request.memoryBytes > memoryBudgetBytes + epsilon);
67
+ return {
68
+ ...budget,
69
+ admitted: true,
70
+ reason: oversize ? "admitted_alone" : "admitted",
71
+ detail: oversize
72
+ ? "The step exceeds the host budget on its own and runs alone because nothing else is running."
73
+ : "The step fits the host budget.",
74
+ };
75
+ }
76
+ if (reservedCpuCores + request.cpuCores > cpuBudgetCores + epsilon) {
77
+ return {
78
+ ...budget,
79
+ admitted: false,
80
+ reason: "cpu_budget",
81
+ detail: `Reserved ${round(reservedCpuCores)} + requested ${round(request.cpuCores)} cores exceed the ${round(cpuBudgetCores)}-core budget${signals.externalCpuCores ? ` (${round(signals.externalCpuCores)} cores of external load)` : ""}.`,
82
+ };
83
+ }
84
+ if (memoryBudgetBytes !== null && reservedMemoryBytes + request.memoryBytes > memoryBudgetBytes + epsilon) {
85
+ return {
86
+ ...budget,
87
+ admitted: false,
88
+ reason: "memory_budget",
89
+ detail: `Reserved ${gib(reservedMemoryBytes)} + requested ${gib(request.memoryBytes)} GiB exceed the ${gib(memoryBudgetBytes)} GiB memory budget.`,
90
+ };
91
+ }
92
+ return { ...budget, admitted: true, reason: "admitted", detail: "The step fits the host budget." };
93
+ }
94
+ function round(value) {
95
+ return Math.round(value * 100) / 100;
96
+ }
97
+ function gib(bytes) {
98
+ return round(bytes / 1024 ** 3);
99
+ }