@loucompanion/forge-bridge 0.1.4-dev.e83e5bc6ecce → 0.1.4-dev.ec3460040366

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 (212) 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 +88 -14
  16. package/dist/bridge/bridge.service.js +406 -345
  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 +11 -1
  31. package/dist/cleanup/cleanup.service.js +80 -62
  32. package/dist/cleanup/cleanup.types.d.ts +2 -0
  33. package/dist/cleanup/host-runtime-ledger.d.ts +2 -0
  34. package/dist/cleanup/host-runtime-ledger.js +30 -9
  35. package/dist/cli/cli.help.js +74 -12
  36. package/dist/cli/cli.service.d.ts +19 -10
  37. package/dist/cli/cli.service.js +142 -185
  38. package/dist/cli/idle-status.d.ts +84 -0
  39. package/dist/cli/idle-status.js +181 -0
  40. package/dist/cli/local-config.d.ts +6 -0
  41. package/dist/cli/local-config.js +32 -4
  42. package/dist/cli/provider-cli-detection.d.ts +10 -0
  43. package/dist/cli/provider-cli-detection.js +160 -0
  44. package/dist/runtime/aspnet-runtime-prebuild.d.ts +20 -0
  45. package/dist/runtime/aspnet-runtime-prebuild.js +184 -18
  46. package/dist/runtime/attempt-database-broker.d.ts +1 -1
  47. package/dist/runtime/attempt-node-runtime-launcher.js +9 -0
  48. package/dist/runtime/attempt-process-supervisor.d.ts +2 -0
  49. package/dist/runtime/attempt-process-supervisor.js +12 -6
  50. package/dist/runtime/docker-engine-probe.d.ts +5 -0
  51. package/dist/runtime/docker-engine-probe.js +7 -0
  52. package/dist/runtime/dotnet-build-outputs.d.ts +107 -0
  53. package/dist/runtime/dotnet-build-outputs.js +402 -0
  54. package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
  55. package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
  56. package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
  57. package/dist/runtime/ephemeral-test-postgres.js +303 -0
  58. package/dist/runtime/host-facts.d.ts +2 -1
  59. package/dist/runtime/host-load-admission.d.ts +18 -3
  60. package/dist/runtime/host-load-admission.js +19 -4
  61. package/dist/runtime/host-load-child-environment.d.ts +11 -6
  62. package/dist/runtime/host-load-child-environment.js +22 -11
  63. package/dist/runtime/host-load-governor-config.d.ts +19 -1
  64. package/dist/runtime/host-load-governor-config.js +37 -0
  65. package/dist/runtime/host-load-governor.d.ts +14 -0
  66. package/dist/runtime/host-load-governor.js +139 -26
  67. package/dist/runtime/host-load-ledger-lock.js +6 -4
  68. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  69. package/dist/runtime/host-load-runtime-settings.js +80 -0
  70. package/dist/runtime/host-load-sampler.d.ts +34 -4
  71. package/dist/runtime/host-load-sampler.js +73 -7
  72. package/dist/runtime/host-load-step-class.d.ts +3 -1
  73. package/dist/runtime/host-load-step-class.js +60 -5
  74. package/dist/runtime/host-load-test-slot.d.ts +43 -0
  75. package/dist/runtime/host-load-test-slot.js +81 -0
  76. package/dist/runtime/host-load-token-ledger.d.ts +26 -0
  77. package/dist/runtime/host-load-token-ledger.js +93 -61
  78. package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
  79. package/dist/runtime/host-load-windows-cpu.js +85 -0
  80. package/dist/runtime/host-runtime-contract.d.ts +12 -0
  81. package/dist/runtime/host-runtime-contract.js +29 -1
  82. package/dist/runtime/host-runtime-lease.d.ts +62 -4
  83. package/dist/runtime/host-runtime-lease.js +235 -168
  84. package/dist/runtime/host-runtime-ledger-recovery.d.ts +20 -0
  85. package/dist/runtime/host-runtime-ledger-recovery.js +134 -0
  86. package/dist/runtime/host-runtime-promotion.d.ts +23 -0
  87. package/dist/runtime/host-runtime-promotion.js +36 -0
  88. package/dist/runtime/managed-command-teardown.js +5 -16
  89. package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
  90. package/dist/runtime/native-test-postgres-fallback.js +60 -8
  91. package/dist/runtime/playwright-host-runtime-adapter.d.ts +7 -0
  92. package/dist/runtime/playwright-host-runtime-adapter.js +13 -1
  93. package/dist/runtime/runner-settings.d.ts +104 -0
  94. package/dist/runtime/runner-settings.js +236 -0
  95. package/dist/runtime/supervised-runtime-build-guard.d.ts +45 -0
  96. package/dist/runtime/supervised-runtime-build-guard.js +112 -0
  97. package/dist/sandbox/host-capacity-broker.d.ts +10 -2
  98. package/dist/sandbox/host-capacity-broker.js +27 -6
  99. package/dist/sandbox/managed-branch.d.ts +13 -0
  100. package/dist/sandbox/managed-branch.js +90 -0
  101. package/dist/sandbox/provider-auth/codex.js +11 -11
  102. package/dist/sandbox/runtime.js +2 -6
  103. package/dist/session/architect-waits.d.ts +2 -0
  104. package/dist/session/architect-waits.js +138 -0
  105. package/dist/session/managed-attempt-tools.d.ts +0 -7
  106. package/dist/session/managed-attempt-tools.js +58 -91
  107. package/dist/session/managed-build-coordinator.d.ts +16 -0
  108. package/dist/session/managed-build-coordinator.js +10 -0
  109. package/dist/session/managed-build-receipt.d.ts +5 -0
  110. package/dist/session/managed-build-receipt.js +8 -3
  111. package/dist/session/managed-command-host-load.d.ts +2 -0
  112. package/dist/session/managed-command-host-load.js +2 -1
  113. package/dist/session/phase-completion.artifacts.js +2 -1
  114. package/dist/session/phase-completion.d.ts +8 -0
  115. package/dist/session/phase-completion.js +1 -0
  116. package/dist/session/phase-completion.mcp-args.d.ts +9 -0
  117. package/dist/session/phase-completion.mcp-args.js +156 -0
  118. package/dist/session/phase-completion.runtime.d.ts +0 -8
  119. package/dist/session/phase-completion.runtime.js +43 -197
  120. package/dist/session/phase-completion.schemas.js +25 -23
  121. package/dist/session/phase-completion.validation.js +3 -1
  122. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  123. package/dist/session/pre-publication-native-postgres.js +111 -0
  124. package/dist/session/pre-publication-pass.d.ts +61 -0
  125. package/dist/session/pre-publication-pass.js +148 -0
  126. package/dist/session/pre-publication-process.js +10 -10
  127. package/dist/session/pre-publication-step-execution.d.ts +2 -1
  128. package/dist/session/pre-publication-step-execution.js +6 -5
  129. package/dist/session/pre-publication-validation.d.ts +30 -14
  130. package/dist/session/pre-publication-validation.js +207 -134
  131. package/dist/session/provider-cli/claude-background-work.d.ts +67 -0
  132. package/dist/session/provider-cli/claude-background-work.js +181 -0
  133. package/dist/session/provider-cli/host-build-lock.d.ts +18 -0
  134. package/dist/session/provider-cli/host-build-lock.js +30 -0
  135. package/dist/session/provider-cli/pre-publication-repair.d.ts +56 -0
  136. package/dist/session/provider-cli/pre-publication-repair.js +276 -0
  137. package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
  138. package/dist/session/provider-cli/provider-cli.child-environment.js +75 -0
  139. package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
  140. package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
  141. package/dist/session/provider-cli/provider-cli.process.d.ts +15 -36
  142. package/dist/session/provider-cli/provider-cli.process.js +39 -430
  143. package/dist/session/provider-cli/provider-cli.prompts.d.ts +5 -0
  144. package/dist/session/provider-cli/provider-cli.prompts.js +71 -31
  145. package/dist/session/provider-cli/provider-cli.runtime.d.ts +8 -0
  146. package/dist/session/provider-cli/provider-cli.runtime.js +29 -1
  147. package/dist/session/provider-cli/provider-cli.service.d.ts +7 -1
  148. package/dist/session/provider-cli/provider-cli.service.js +78 -171
  149. package/dist/session/provider-cli/provider-cli.types.d.ts +26 -0
  150. package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
  151. package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
  152. package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
  153. package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
  154. package/dist/session/provider-cli/provider-in-flight-work.d.ts +4 -0
  155. package/dist/session/provider-cli/provider-in-flight-work.js +45 -0
  156. package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
  157. package/dist/session/provider-cli/provider-output-pipes.js +67 -0
  158. package/dist/session/provider-cli/provider-output-state.d.ts +2 -0
  159. package/dist/session/provider-cli/provider-output-state.js +6 -0
  160. package/dist/session/provider-cli/provider-user-config-isolation.d.ts +69 -0
  161. package/dist/session/provider-cli/provider-user-config-isolation.js +164 -0
  162. package/dist/session/qa-sidecar-validation.d.ts +6 -0
  163. package/dist/session/qa-sidecar-validation.js +28 -0
  164. package/dist/session/sandbox-host-capacity-gate.d.ts +22 -1
  165. package/dist/session/sandbox-host-capacity-gate.js +42 -14
  166. package/dist/session/session-redaction.js +31 -181
  167. package/dist/session/session.base.d.ts +6 -1
  168. package/dist/session/session.service.d.ts +9 -2
  169. package/dist/session/session.service.js +169 -66
  170. package/dist/session/session.types.js +4 -4
  171. package/dist/session/sidecar-json-shape.d.ts +31 -0
  172. package/dist/session/sidecar-json-shape.js +217 -0
  173. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  174. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  175. package/dist/shared/fs/file-identity.d.ts +10 -0
  176. package/dist/shared/fs/file-identity.js +15 -0
  177. package/dist/shared/fs/replace-file.d.ts +7 -0
  178. package/dist/shared/fs/replace-file.js +33 -0
  179. package/dist/shared/process/host-process-recovery.d.ts +14 -3
  180. package/dist/shared/process/host-process-recovery.js +23 -3
  181. package/dist/shared/process/host-process-supervisor.d.ts +13 -1
  182. package/dist/shared/process/host-process-supervisor.js +66 -14
  183. package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
  184. package/dist/shared/process/windows-app-execution-alias.js +45 -0
  185. package/dist/shared/process/windows-launch.d.ts +18 -0
  186. package/dist/shared/process/windows-launch.js +68 -0
  187. package/dist/shared/provider-capabilities.js +14 -7
  188. package/dist/version.d.ts +1 -1
  189. package/dist/version.js +1 -1
  190. package/dist/worktree/orphan-relink.d.ts +19 -0
  191. package/dist/worktree/orphan-relink.js +106 -0
  192. package/dist/worktree/wip-git.d.ts +33 -0
  193. package/dist/worktree/wip-git.js +122 -0
  194. package/dist/worktree/wip-refs.d.ts +62 -0
  195. package/dist/worktree/wip-refs.js +119 -0
  196. package/dist/worktree/wip-restore.d.ts +38 -0
  197. package/dist/worktree/wip-restore.js +190 -0
  198. package/dist/worktree/wip-snapshot.d.ts +50 -0
  199. package/dist/worktree/wip-snapshot.js +268 -0
  200. package/dist/worktree/worktree-inputs.d.ts +8 -0
  201. package/dist/worktree/worktree-inputs.js +134 -0
  202. package/dist/worktree/worktree-origin-sync.d.ts +34 -0
  203. package/dist/worktree/worktree-origin-sync.js +127 -0
  204. package/dist/worktree/worktree-wip-events.d.ts +18 -0
  205. package/dist/worktree/worktree-wip-events.js +98 -0
  206. package/dist/worktree/worktree-wip.d.ts +50 -0
  207. package/dist/worktree/worktree-wip.js +185 -0
  208. package/dist/worktree/worktree.base.d.ts +7 -1
  209. package/dist/worktree/worktree.service.d.ts +27 -5
  210. package/dist/worktree/worktree.service.js +110 -181
  211. package/dist/worktree/worktree.types.d.ts +31 -0
  212. package/package.json +2 -2
@@ -0,0 +1,134 @@
1
+ import fs from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { readCanonicalSourceFile } from "./canonical-source-file.js";
4
+ import { assertHostAttemptRootIdentity } from "./host-diagnostics.js";
5
+ import { terminateAttemptManagedCommands } from "./managed-command-teardown.js";
6
+ import { readPinnedSourceDirectory } from "./pinned-source-directory.js";
7
+ // Host runtime ledger persistence and recovery helpers shared by HostRuntimeLeaseManager.
8
+ const maximumProcessRecoveryMetadataBytes = 1024 * 1024;
9
+ const ledgerReplaceAttempts = 40;
10
+ const transientLedgerReplaceCodes = new Set(["EPERM", "EACCES", "EBUSY"]);
11
+ /**
12
+ * Replaces a host runtime ledger with its fully written temporary file. Windows refuses
13
+ * to replace a file another handle has open (EPERM), for example while a recovery pass
14
+ * reads the same ledger, so a transient refusal is retried for about a second, as the
15
+ * attempt supervisor does for its own ledger.
16
+ */
17
+ export async function replaceHostRuntimeLedgerFile(temporary, target, retryMs = 25) {
18
+ for (let attempt = 1;; attempt += 1) {
19
+ try {
20
+ await fs.rename(temporary, target);
21
+ return;
22
+ }
23
+ catch (error) {
24
+ const code = error.code;
25
+ if (attempt >= ledgerReplaceAttempts || !code || !transientLedgerReplaceCodes.has(code))
26
+ throw error;
27
+ await new Promise(resolve => setTimeout(resolve, retryMs));
28
+ }
29
+ }
30
+ }
31
+ /**
32
+ * Maintenance retry of a degraded lease's fenced release. The release frees the slot only
33
+ * after its teardown proves the attempt's supervised process tree stopped (the supervisor
34
+ * is stopped with no live child or managed command); otherwise the lease stays degraded
35
+ * and the log says why. Returns whether the lease was released.
36
+ */
37
+ export async function retryDegradedHostRelease(lease, release, log) {
38
+ const subject = `host runtime lease ${lease.leaseId} of attempt ${lease.dispatchAttemptId}`;
39
+ try {
40
+ const released = await release();
41
+ if (released?.state === "released") {
42
+ log(`Released degraded ${subject}: teardown proved its supervised process tree stopped, so its project runtime slot is free.`);
43
+ return true;
44
+ }
45
+ log(`Degraded ${subject} stays degraded: its fencing token no longer owns the attempt.`);
46
+ }
47
+ catch (error) {
48
+ log(`Degraded ${subject} stays degraded: ${error instanceof Error ? error.message : String(error)}`);
49
+ }
50
+ return false;
51
+ }
52
+ export function logHostRuntimeStatus(message) {
53
+ process.stderr.write(`[${new Date().toISOString()}] ${message}\n`);
54
+ }
55
+ /** Exact, fenced recovery of the process trees a lease's attempt recorded under its attempt root. */
56
+ export async function recoverPersistedHostProcesses(lease, attemptRoot, expectedAttemptRoot, attemptRootIdentity, processRecovery) {
57
+ const logsRoot = path.join(attemptRoot, "logs");
58
+ if (path.resolve(attemptRoot) !== path.resolve(expectedAttemptRoot)) {
59
+ throw new Error("host_runtime_reaper_invalid: attempt path is outside the fenced attempt root.");
60
+ }
61
+ await assertHostAttemptRootIdentity(attemptRoot, attemptRootIdentity);
62
+ const rootEntries = await readPinnedSourceDirectory(attemptRoot, attemptRootIdentity);
63
+ const logsEntry = rootEntries.find(entry => entry.name === "logs");
64
+ if (!logsEntry)
65
+ return [];
66
+ if (logsEntry.kind !== "directory") {
67
+ throw new Error("host_runtime_reaper_invalid: process ownership log path is not an ordinary directory.");
68
+ }
69
+ const outcomes = [];
70
+ const failures = [];
71
+ try {
72
+ const entries = await readPinnedSourceDirectory(logsRoot, logsEntry.identity);
73
+ for (const entry of entries) {
74
+ if (entry.kind !== "file" || !/^process-supervisor\.[a-z][a-z0-9_-]{0,31}\.\d+\.json$/u.test(entry.name))
75
+ continue;
76
+ const metadataPath = path.join(logsRoot, entry.name);
77
+ const value = JSON.parse((await readCanonicalSourceFile(metadataPath, maximumProcessRecoveryMetadataBytes, entry.identity)).toString("utf8"));
78
+ if (!validHostProcessSupervisorMetadata(value, lease)) {
79
+ throw new Error("host_runtime_reaper_invalid: process ownership metadata did not match the runtime lease.");
80
+ }
81
+ outcomes.push(await processRecovery.recover(value));
82
+ }
83
+ }
84
+ catch (error) {
85
+ failures.push(error);
86
+ }
87
+ // Managed commands run in their own process groups and record their ownership apart
88
+ // from the attempt's supervised children. They are recovered even when recovering a
89
+ // supervised child failed, and both failures are reported together.
90
+ try {
91
+ const managed = await terminateAttemptManagedCommands({
92
+ logDirectory: logsRoot,
93
+ dispatchAttemptId: lease.dispatchAttemptId,
94
+ runtimeLeaseId: lease.executionLeaseId,
95
+ pinnedLogDirectory: logsEntry.identity,
96
+ }, { reason: "attempt_teardown" });
97
+ for (const command of managed) {
98
+ if (command.outcome === "terminated" || command.outcome === "pid_reused")
99
+ outcomes.push(command.outcome);
100
+ }
101
+ }
102
+ catch (error) {
103
+ failures.push(error);
104
+ }
105
+ if (failures.length === 1)
106
+ throw failures[0];
107
+ if (failures.length > 1)
108
+ throw new AggregateError(failures, "host_runtime_reaper_recovery_failed");
109
+ return outcomes;
110
+ }
111
+ function validHostProcessSupervisorMetadata(value, lease) {
112
+ if (typeof value !== "object" || value === null)
113
+ return false;
114
+ const metadata = value;
115
+ return metadata.schemaVersion === 1
116
+ && /^host-[0-9a-f]{32}$/u.test(metadata.supervisorId)
117
+ && (metadata.strategy === "windows_job_object" || metadata.strategy === "unix_process_group")
118
+ && Number.isSafeInteger(metadata.rootPid)
119
+ && metadata.rootPid > 0
120
+ && Number.isFinite(Date.parse(metadata.rootCreatedAt))
121
+ && (metadata.rootIdentity == null
122
+ || (typeof metadata.rootIdentity === "string" && metadata.rootIdentity.length <= 256))
123
+ && /^[0-9a-f]{64}$/u.test(metadata.commandDigest)
124
+ && containedMetadataWorktreePath(lease.worktreePath, metadata.worktreePath)
125
+ && metadata.runtimeLeaseId === lease.executionLeaseId
126
+ && metadata.dispatchAttemptId === lease.dispatchAttemptId
127
+ && metadata.fencingToken === lease.fencingToken
128
+ && Number.isSafeInteger(metadata.bridgePid)
129
+ && metadata.bridgePid > 0;
130
+ }
131
+ function containedMetadataWorktreePath(worktreePath, metadataWorktreePath) {
132
+ const relative = path.relative(path.resolve(worktreePath), path.resolve(metadataWorktreePath));
133
+ return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
134
+ }
@@ -28,5 +28,28 @@ export declare class HostParallelPromotionStore {
28
28
  private recordPath;
29
29
  }
30
30
  export declare function hostRuntimeContractFingerprint(runtimeContract: LoadedHostRuntimeContract): string;
31
+ export interface ReadmittedHostRuntimeContract {
32
+ readonly runtimeContract: LoadedHostRuntimeContract;
33
+ readonly runtimeContractFingerprint: string;
34
+ readonly changed: boolean;
35
+ }
36
+ /**
37
+ * Decides whether a restart may run the workspace's current runtime contract under the admission
38
+ * granted at start. A restart relaunches from the workspace in any case, so a contract whose only
39
+ * change is the values its ports launch with (launch environment, or discovery inputs that leave
40
+ * the contract itself unchanged) is adopted. This is how a conflict repair survives its own merge:
41
+ * merging the target branch can rename a variable in a derived launch profile, or change a
42
+ * manifest or project file, without changing anything admission granted. Every other part of the
43
+ * contract is admission: source, concurrency, ports (names, adapters, environment names, URL
44
+ * formats, and the command, arguments and working directory that launch them), Playwright, browser
45
+ * profile, singleton resources and declared requirements. Changing any of those throws the
46
+ * retryable host_runtime_contract_changed, so only a fresh attempt runs that contract. An attempt
47
+ * admitted to run in parallel keeps that admission, as it does when a merge changes only source;
48
+ * a restart never promotes, so the adopted contract earns no parallel-safety proof of its own here.
49
+ */
50
+ export declare function readmitHostRuntimeContract(admitted: {
51
+ readonly runtimeContract: LoadedHostRuntimeContract;
52
+ readonly runtimeContractFingerprint: string;
53
+ }, current: LoadedHostRuntimeContract): ReadmittedHostRuntimeContract;
31
54
  export declare function hostRuntimeParallelEligible(runtimeContract: LoadedHostRuntimeContract): boolean;
32
55
  export declare function configuredLaunchPortNames(runtimeContract: LoadedHostRuntimeContract): readonly string[];
@@ -1,6 +1,7 @@
1
1
  import { createHash, randomUUID } from "node:crypto";
2
2
  import fs from "node:fs/promises";
3
3
  import path from "node:path";
4
+ import { ForgeFailureError } from "../session/session.types.js";
4
5
  /** Persists only observed, contract-bound host parallel-safety evidence. */
5
6
  export class HostParallelPromotionStore {
6
7
  stateRoot;
@@ -154,6 +155,41 @@ export function hostRuntimeContractFingerprint(runtimeContract) {
154
155
  });
155
156
  return `sha256:${createHash("sha256").update(canonical).digest("hex")}`;
156
157
  }
158
+ /**
159
+ * Decides whether a restart may run the workspace's current runtime contract under the admission
160
+ * granted at start. A restart relaunches from the workspace in any case, so a contract whose only
161
+ * change is the values its ports launch with (launch environment, or discovery inputs that leave
162
+ * the contract itself unchanged) is adopted. This is how a conflict repair survives its own merge:
163
+ * merging the target branch can rename a variable in a derived launch profile, or change a
164
+ * manifest or project file, without changing anything admission granted. Every other part of the
165
+ * contract is admission: source, concurrency, ports (names, adapters, environment names, URL
166
+ * formats, and the command, arguments and working directory that launch them), Playwright, browser
167
+ * profile, singleton resources and declared requirements. Changing any of those throws the
168
+ * retryable host_runtime_contract_changed, so only a fresh attempt runs that contract. An attempt
169
+ * admitted to run in parallel keeps that admission, as it does when a merge changes only source;
170
+ * a restart never promotes, so the adopted contract earns no parallel-safety proof of its own here.
171
+ */
172
+ export function readmitHostRuntimeContract(admitted, current) {
173
+ const runtimeContractFingerprint = hostRuntimeContractFingerprint(current);
174
+ // The fingerprint leaves out the source of a project or default contract, but parallel
175
+ // eligibility depends on it, so an unchanged fingerprint alone does not prove the same admission.
176
+ if (runtimeContractFingerprint === admitted.runtimeContractFingerprint && current.source === admitted.runtimeContract.source) {
177
+ return { runtimeContract: admitted.runtimeContract, runtimeContractFingerprint, changed: false };
178
+ }
179
+ if (hostRuntimeAdmissionShape(current) !== hostRuntimeAdmissionShape(admitted.runtimeContract)) {
180
+ throw new ForgeFailureError("host_runtime_contract_changed", "host_runtime_contract_changed: the workspace's runtime contract changed after this attempt's runtime was admitted; a fresh attempt is needed to run it.");
181
+ }
182
+ return { runtimeContract: current, runtimeContractFingerprint, changed: true };
183
+ }
184
+ function hostRuntimeAdmissionShape(runtimeContract) {
185
+ const runtime = runtimeContract.contract.runtime;
186
+ return JSON.stringify({
187
+ source: runtimeContract.source,
188
+ schemaVersion: runtimeContract.contract.schemaVersion,
189
+ runtime: { ...runtime, ports: runtime.ports.map(port => ({ ...port, launch: port.launch && { ...port.launch, environment: undefined } })) },
190
+ ...requirementsFingerprintPart(runtimeContract.contract.requires),
191
+ });
192
+ }
157
193
  // Cost hints are estimates, not placement constraints: they never change the fingerprint.
158
194
  function requirementsFingerprintPart(requires) {
159
195
  if (!requires)
@@ -3,6 +3,7 @@ import fs from "node:fs/promises";
3
3
  import path from "node:path";
4
4
  import { readCanonicalSourceFile } from "./canonical-source-file.js";
5
5
  import { readPinnedSourceDirectory } from "./pinned-source-directory.js";
6
+ import { replaceFile } from "../shared/fs/replace-file.js";
6
7
  import { ExactHostProcessRecovery } from "../shared/process/host-process-recovery.js";
7
8
  import { captureHostProcessIdentity, } from "../shared/process/host-process-supervisor.js";
8
9
  import { monotonicNowMs } from "../shared/time/monotonic.js";
@@ -14,8 +15,7 @@ const maximumReceiptBytes = 16 * 1024 * 1024;
14
15
  const maximumCapturedCharacters = 200_000;
15
16
  const defaultGraceMs = 2_000;
16
17
  const receiptReadAttempts = 5;
17
- const receiptReplaceAttempts = 40;
18
- const receiptReplaceRetryMs = 25;
18
+ const receiptReadRetryMs = 25;
19
19
  const invalidMetadata = Symbol("invalid managed-command metadata");
20
20
  let procRoot = "/proc";
21
21
  /** Test support: points the Linux process inventory at another directory (null restores /proc). */
@@ -363,7 +363,7 @@ async function readReceipt(store, name) {
363
363
  }
364
364
  catch {
365
365
  if (attempt < receiptReadAttempts)
366
- await delay(receiptReplaceRetryMs);
366
+ await delay(receiptReadRetryMs);
367
367
  }
368
368
  }
369
369
  return null;
@@ -462,19 +462,8 @@ async function persistReceipt(receiptPath, receipt) {
462
462
  const temporaryPath = `${receiptPath}.${randomUUID()}.tmp`;
463
463
  try {
464
464
  await fs.writeFile(temporaryPath, `${JSON.stringify(receipt, null, 2)}\n`, { encoding: "utf8", mode: 0o600, flag: "wx" });
465
- for (let attempt = 1;; attempt += 1) {
466
- try {
467
- await fs.rename(temporaryPath, receiptPath);
468
- return;
469
- }
470
- catch (error) {
471
- const code = error.code;
472
- // Windows refuses to replace a file another process briefly holds open.
473
- if (attempt >= receiptReplaceAttempts || (code !== "EPERM" && code !== "EBUSY" && code !== "EACCES"))
474
- throw error;
475
- await delay(receiptReplaceRetryMs);
476
- }
477
- }
465
+ // Windows refuses to replace a file another process briefly holds open.
466
+ await replaceFile(temporaryPath, receiptPath);
478
467
  }
479
468
  finally {
480
469
  await fs.rm(temporaryPath, { force: true }).catch(() => undefined);
@@ -2,15 +2,51 @@ export declare const nativeTestPostgresFallbackConfigEnvironment = "FORGE_NATIVE
2
2
  export declare const nativeTestPostgresFallbackFileName = "native-test-postgres.json";
3
3
  export declare const nativeTestPostgresFallbackDatabaseMode = "native_fallback";
4
4
  /**
5
- * A dedicated, operator-provisioned PostgreSQL cluster that runner-authored .NET
6
- * test tiers may use only while the Docker engine is unavailable. The cluster
7
- * must hold nothing but disposable test databases, so its capability carries no
8
- * more authority than the attempt-private container it replaces.
5
+ * The cluster serves the shared test server while Docker is up, so tests that need a
6
+ * pinned engine container still start one. Owner policy (2026-11-16): native PostgreSQL
7
+ * first, which keeps test databases out of the Docker VM and saves RAM.
8
+ */
9
+ export declare const nativeTestPostgresPreferredDatabaseMode = "native_preferred";
10
+ export type NativeTestPostgresDatabaseMode = typeof nativeTestPostgresFallbackDatabaseMode | typeof nativeTestPostgresPreferredDatabaseMode;
11
+ /**
12
+ * What runner-authored .NET test tiers get: `preferred` (the default) the provisioned
13
+ * cluster whenever it is configured; `docker_unavailable` that cluster only after a
14
+ * Docker probe fails; `ephemeral` a throwaway cluster of their own for each check, whose
15
+ * bootstrap superuser they hold (owner policy 2026-11-17). The provisioned cluster still
16
+ * hosts the attempt database broker in every mode.
17
+ */
18
+ export type NativeTestPostgresUse = "preferred" | "docker_unavailable" | "ephemeral";
19
+ /**
20
+ * A dedicated, operator-provisioned PostgreSQL cluster for runner-authored .NET
21
+ * test tiers, preferred over Docker unless its file says `docker_unavailable`.
22
+ * The cluster must hold nothing but disposable test databases, so its capability
23
+ * carries no more authority than the attempt-private container it replaces.
9
24
  */
10
25
  export interface NativeTestPostgresFallback {
11
26
  readonly connectionString: string;
12
27
  readonly endpoint: string;
28
+ readonly use: NativeTestPostgresUse;
29
+ /** The PostgreSQL bin directory an ephemeral cluster runs from; defaults to the one beside psql. */
30
+ readonly postgresBin?: string;
13
31
  }
32
+ /** The cluster as handed to one test process, with the mode its fixtures run in. */
33
+ export interface NativeTestPostgresGrant {
34
+ readonly connectionString: string;
35
+ readonly endpoint: string;
36
+ readonly mode: NativeTestPostgresDatabaseMode;
37
+ /** Set when the grant is a throwaway cluster of its own; the server reports it as `forge.ephemeral_cluster`. */
38
+ readonly ephemeralClusterId?: string;
39
+ /** Stops and deletes an ephemeral cluster once its check has finished. */
40
+ readonly release?: () => Promise<void>;
41
+ }
42
+ /**
43
+ * The provisioned cluster's grant for a check that can use it, or null to use Docker. A
44
+ * preferred cluster is granted whether or not Docker is up; the mode says which, because
45
+ * only the fallback mode excludes Docker for pinned-engine tests. An `ephemeral` host
46
+ * normally gets its own cluster instead (ephemeral-test-postgres-grant.ts); if that cannot
47
+ * start, the provisioned cluster serves only while Docker is down, as for `docker_unavailable`.
48
+ */
49
+ export declare function nativeTestPostgresGrant(fallback: NativeTestPostgresFallback | null, dockerAvailable: boolean): NativeTestPostgresGrant | null;
14
50
  export declare class NativeTestPostgresFallbackError extends Error {
15
51
  readonly code = "native_test_postgres_fallback_invalid";
16
52
  constructor(detail: string);
@@ -20,6 +56,14 @@ export declare function resolveNativeTestPostgresFallbackPath(): string;
20
56
  export declare function configuredNativeTestPostgresFallbackPath(): string | null;
21
57
  /** Returns null when no fallback is configured; throws when one is configured unsafely. */
22
58
  export declare function readNativeTestPostgresFallback(configPath?: string): NativeTestPostgresFallback | null;
23
- export declare function parseNativeTestPostgresFallback(connectionString: string): NativeTestPostgresFallback;
24
- /** Environment for one runner-authored .NET test process using the fallback. */
25
- export declare function nativeTestPostgresFallbackEnvironment(fallback: NativeTestPostgresFallback): Readonly<Record<string, string>>;
59
+ export declare function parseNativeTestPostgresFallback(connectionString: string, use?: NativeTestPostgresUse): NativeTestPostgresFallback;
60
+ /** Environment for one runner-authored .NET test process using the cluster. */
61
+ export declare function nativeTestPostgresFallbackEnvironment(grant: Pick<NativeTestPostgresGrant, "connectionString" | "mode" | "ephemeralClusterId">): Readonly<Record<string, string>>;
62
+ /**
63
+ * Runner-authored verification uses the operator-provisioned native test cluster,
64
+ * which holds no real data, whenever its file prefers it (the default); Docker then
65
+ * only starts pinned-engine containers. A `docker_unavailable` cluster is used only
66
+ * when the Docker engine is unavailable; otherwise the attempt-owned Testcontainers
67
+ * database serves.
68
+ */
69
+ export declare function managedVerificationDatabaseEnvironment(dockerAvailable?: () => Promise<boolean>, readFallback?: () => NativeTestPostgresFallback | null): Promise<Readonly<Record<string, string>>>;
@@ -1,12 +1,37 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import { resolveLocalConfigPath } from "../cli/local-config.js";
4
+ import { DockerEngineProbe } from "./docker-engine-probe.js";
5
+ import { ephemeralTestPostgresClusterEnvironment } from "./ephemeral-test-postgres.js";
4
6
  import { hostRuntimeLegacyTestPostgresEnvironment, hostRuntimeTestPostgresAdminEnvironment, } from "./host-runtime-contract.js";
5
7
  export const nativeTestPostgresFallbackConfigEnvironment = "FORGE_NATIVE_TEST_POSTGRES_CONFIG";
6
8
  export const nativeTestPostgresFallbackFileName = "native-test-postgres.json";
7
9
  export const nativeTestPostgresFallbackDatabaseMode = "native_fallback";
10
+ /**
11
+ * The cluster serves the shared test server while Docker is up, so tests that need a
12
+ * pinned engine container still start one. Owner policy (2026-11-16): native PostgreSQL
13
+ * first, which keeps test databases out of the Docker VM and saves RAM.
14
+ */
15
+ export const nativeTestPostgresPreferredDatabaseMode = "native_preferred";
16
+ const nativeTestPostgresUses = ["preferred", "docker_unavailable", "ephemeral"];
8
17
  const defaultPostgresPort = 5432;
9
18
  const loopbackHosts = new Set(["127.0.0.1", "localhost", "::1", "[::1]"]);
19
+ /**
20
+ * The provisioned cluster's grant for a check that can use it, or null to use Docker. A
21
+ * preferred cluster is granted whether or not Docker is up; the mode says which, because
22
+ * only the fallback mode excludes Docker for pinned-engine tests. An `ephemeral` host
23
+ * normally gets its own cluster instead (ephemeral-test-postgres-grant.ts); if that cannot
24
+ * start, the provisioned cluster serves only while Docker is down, as for `docker_unavailable`.
25
+ */
26
+ export function nativeTestPostgresGrant(fallback, dockerAvailable) {
27
+ if (!fallback || (dockerAvailable && fallback.use !== "preferred"))
28
+ return null;
29
+ return {
30
+ connectionString: fallback.connectionString,
31
+ endpoint: fallback.endpoint,
32
+ mode: dockerAvailable ? nativeTestPostgresPreferredDatabaseMode : nativeTestPostgresFallbackDatabaseMode,
33
+ };
34
+ }
10
35
  export class NativeTestPostgresFallbackError extends Error {
11
36
  code = "native_test_postgres_fallback_invalid";
12
37
  constructor(detail) {
@@ -46,9 +71,17 @@ export function readNativeTestPostgresFallback(configPath = resolveNativeTestPos
46
71
  if (document.schemaVersion !== 1 || typeof document.connectionString !== "string") {
47
72
  throw new NativeTestPostgresFallbackError(`${configPath} must contain schemaVersion 1 and a connectionString.`);
48
73
  }
49
- return parseNativeTestPostgresFallback(document.connectionString);
74
+ if (document.use !== undefined && !nativeTestPostgresUses.includes(document.use)) {
75
+ throw new NativeTestPostgresFallbackError(`${configPath} 'use' must be 'preferred', 'docker_unavailable' or 'ephemeral'.`);
76
+ }
77
+ if (document.postgresBin !== undefined
78
+ && (typeof document.postgresBin !== "string" || !path.isAbsolute(document.postgresBin))) {
79
+ throw new NativeTestPostgresFallbackError(`${configPath} 'postgresBin' must be an absolute path.`);
80
+ }
81
+ const fallback = parseNativeTestPostgresFallback(document.connectionString, document.use ?? "preferred");
82
+ return typeof document.postgresBin === "string" ? { ...fallback, postgresBin: document.postgresBin } : fallback;
50
83
  }
51
- export function parseNativeTestPostgresFallback(connectionString) {
84
+ export function parseNativeTestPostgresFallback(connectionString, use = "preferred") {
52
85
  const fields = new Map();
53
86
  for (const segment of connectionString.split(";")) {
54
87
  const separator = segment.indexOf("=");
@@ -79,13 +112,32 @@ export function parseNativeTestPostgresFallback(connectionString) {
79
112
  if (!(fields.get("username") ?? fields.get("userid") ?? fields.get("user"))) {
80
113
  throw new NativeTestPostgresFallbackError("the fallback must name a dedicated test role.");
81
114
  }
82
- return { connectionString: connectionString.trim(), endpoint: `${host}:${port}` };
115
+ return { connectionString: connectionString.trim(), endpoint: `${host}:${port}`, use };
83
116
  }
84
- /** Environment for one runner-authored .NET test process using the fallback. */
85
- export function nativeTestPostgresFallbackEnvironment(fallback) {
117
+ /** Environment for one runner-authored .NET test process using the cluster. */
118
+ export function nativeTestPostgresFallbackEnvironment(grant) {
86
119
  return {
87
- [hostRuntimeTestPostgresAdminEnvironment]: fallback.connectionString,
88
- [hostRuntimeLegacyTestPostgresEnvironment]: fallback.connectionString,
89
- FORGE_MANAGED_VERIFICATION_DATABASE_MODE: nativeTestPostgresFallbackDatabaseMode,
120
+ [hostRuntimeTestPostgresAdminEnvironment]: grant.connectionString,
121
+ [hostRuntimeLegacyTestPostgresEnvironment]: grant.connectionString,
122
+ FORGE_MANAGED_VERIFICATION_DATABASE_MODE: grant.mode,
123
+ // The fixtures accept a superuser login only on the cluster that reports this id.
124
+ ...(grant.ephemeralClusterId ? { [ephemeralTestPostgresClusterEnvironment]: grant.ephemeralClusterId } : {}),
90
125
  };
91
126
  }
127
+ /**
128
+ * Runner-authored verification uses the operator-provisioned native test cluster,
129
+ * which holds no real data, whenever its file prefers it (the default); Docker then
130
+ * only starts pinned-engine containers. A `docker_unavailable` cluster is used only
131
+ * when the Docker engine is unavailable; otherwise the attempt-owned Testcontainers
132
+ * database serves.
133
+ */
134
+ export async function managedVerificationDatabaseEnvironment(dockerAvailable = async () => (await new DockerEngineProbe().probeWithoutRecovery()).available, readFallback = () => {
135
+ const configPath = process.env[nativeTestPostgresFallbackConfigEnvironment]?.trim();
136
+ return configPath ? readNativeTestPostgresFallback(configPath) : null;
137
+ }) {
138
+ const fallback = readFallback();
139
+ if (!fallback)
140
+ return {};
141
+ const grant = nativeTestPostgresGrant(fallback, await dockerAvailable());
142
+ return grant ? nativeTestPostgresFallbackEnvironment(grant) : {};
143
+ }
@@ -28,5 +28,12 @@ export declare class PlaywrightHostRuntimeAdapter {
28
28
  */
29
29
  assertBrowserCacheReady(config: HostRuntimePlaywrightConfig, worktreePath: string): Promise<void>;
30
30
  private readyBrowserCache;
31
+ /**
32
+ * Removes the generated config, which names the base URL of the stack it was prepared for. A
33
+ * stopped stack's config must not survive: its port may be reassigned to another attempt, and a
34
+ * provider that remembers the config's path would otherwise run Playwright against that port.
35
+ * The next `prepare` writes a fresh one.
36
+ */
37
+ discardOverlay(temporaryDirectory: string): Promise<void>;
31
38
  prepare(config: HostRuntimePlaywrightConfig, context: PlaywrightHostRuntimeContext): Promise<PreparedPlaywrightHostRuntime>;
32
39
  }
@@ -35,6 +35,17 @@ export class PlaywrightHostRuntimeAdapter {
35
35
  }
36
36
  return { cache: resolution.cache, installCommand };
37
37
  }
38
+ /**
39
+ * Removes the generated config, which names the base URL of the stack it was prepared for. A
40
+ * stopped stack's config must not survive: its port may be reassigned to another attempt, and a
41
+ * provider that remembers the config's path would otherwise run Playwright against that port.
42
+ * The next `prepare` writes a fresh one.
43
+ */
44
+ async discardOverlay(temporaryDirectory) {
45
+ if (!await assertCanonicalDirectory(temporaryDirectory, true))
46
+ return;
47
+ await fs.rm(path.join(path.resolve(temporaryDirectory), playwrightOverlayFileName), { force: true });
48
+ }
38
49
  async prepare(config, context) {
39
50
  const { realWorktree, realSource } = await projectConfigLocation(config, context.worktreePath);
40
51
  const sourceConfig = path.resolve(path.resolve(context.worktreePath), config.config);
@@ -62,7 +73,7 @@ export class PlaywrightHostRuntimeAdapter {
62
73
  if (!/^[0-9a-f]{32}$/u.test(context.ownershipToken)) {
63
74
  throw new Error("playwright_runtime_adapter_invalid: ownership token must be a normalized dispatch attempt UUID.");
64
75
  }
65
- const overlayPath = path.join(temporaryDirectory, "forge.playwright.config.mjs");
76
+ const overlayPath = path.join(temporaryDirectory, playwrightOverlayFileName);
66
77
  const { cache: readyCache, installCommand: browserInstallCommand } = await this.readyBrowserCache(context.worktreePath, realWorktree, path.dirname(realSource));
67
78
  const browserCache = readyCache
68
79
  ? { path: readyCache, ready: true }
@@ -135,6 +146,7 @@ async function ensureAttemptWritableDirectories(targets, realWorktree) {
135
146
  for (const target of resolvedTargets)
136
147
  await createPrivateCanonicalDirectory(target);
137
148
  }
149
+ const playwrightOverlayFileName = "forge.playwright.config.mjs";
138
150
  async function writeAttemptOverlay(target, content) {
139
151
  const parent = path.dirname(target);
140
152
  const identity = await assertCanonicalDirectory(parent);
@@ -0,0 +1,104 @@
1
+ import { type HostLoadGovernorMode } from "./host-load-governor-config.js";
2
+ export declare const runnerSettingKeys: readonly ["maxConcurrentAttempts", "cpuBudgetPercent", "yieldCpuBudgetPercent", "memoryReserveBytes", "maxHeavySteps", "yieldToForeground"];
3
+ export type RunnerSettingKey = typeof runnerSettingKeys[number];
4
+ /** The `ApplySettings` hub message. Null numeric fields mean "no server value": keep today's env/default behaviour. */
5
+ export interface RunnerSettingsDocument {
6
+ readonly runnerId: string | null;
7
+ readonly version: number;
8
+ readonly maxConcurrentAttempts: number | null;
9
+ readonly cpuBudgetPercent: number | null;
10
+ readonly yieldCpuBudgetPercent: number | null;
11
+ readonly memoryReserveBytes: number | null;
12
+ readonly maxHeavySteps: number | null;
13
+ readonly yieldToForeground: boolean;
14
+ }
15
+ export interface RunnerSettingsValues {
16
+ readonly maxConcurrentAttempts: number;
17
+ readonly cpuBudgetPercent: number;
18
+ readonly yieldCpuBudgetPercent: number;
19
+ readonly memoryReserveBytes: number;
20
+ /** Null: the governor's budget alone limits heavy steps (no count limit). */
21
+ readonly maxHeavySteps: number | null;
22
+ readonly yieldToForeground: boolean;
23
+ }
24
+ /**
25
+ * Where an effective value came from: the server's value as is, the bridge default,
26
+ * an env var that capped/floored the server value or supplied it, or the host's
27
+ * `forge-bridge yield on` flag.
28
+ */
29
+ export type RunnerSettingSource = "server" | "default" | "host_env" | "host_local";
30
+ export interface RunnerSettingBound {
31
+ readonly key: RunnerSettingKey;
32
+ readonly envVar: string;
33
+ readonly value: number;
34
+ readonly kind: "ceiling" | "floor";
35
+ }
36
+ /**
37
+ * Why a key was rejected. `invalid`: the server value is outside the contract, so
38
+ * the host default applies (version skew; it never holds placement). `apply_failed`:
39
+ * the host could not put the value in force, so the previous value stays in force
40
+ * and the server holds placement until a later apply succeeds. Clamping by an env
41
+ * bound is neither: it is a `bound` and a `host_env` source.
42
+ */
43
+ export type RunnerSettingRejectionKind = "invalid" | "apply_failed";
44
+ export interface RunnerSettingRejection {
45
+ readonly key: RunnerSettingKey;
46
+ readonly reason: string;
47
+ readonly kind: RunnerSettingRejectionKind;
48
+ }
49
+ /** The `SettingsApplied` report; also carried in the capabilities `settings` block (schema 8). */
50
+ export interface RunnerSettingsReport {
51
+ /** The applied document version, or null before any ApplySettings was applied. */
52
+ readonly version: number | null;
53
+ /** FORGE_HOST_LOAD_GOVERNOR: CPU budget, yield budget and heavy steps only take effect when on. */
54
+ readonly governor: HostLoadGovernorMode;
55
+ readonly values: RunnerSettingsValues;
56
+ readonly sources: Readonly<Record<RunnerSettingKey, RunnerSettingSource>>;
57
+ readonly bounds: readonly RunnerSettingBound[];
58
+ readonly rejected: readonly RunnerSettingRejection[];
59
+ }
60
+ /** Today's bridge defaults for the keys whose default depends on the host. */
61
+ export interface RunnerHostDefaults {
62
+ /** floor(threads / 2) capped at 8 (at least 1). */
63
+ readonly maxConcurrentAttempts: number;
64
+ /** The adaptive reserve: 12.5% of RAM within 1–4 GiB, before FORGE_HOST_MEMORY_RESERVE_BYTES. */
65
+ readonly memoryReserveBytes: number;
66
+ }
67
+ export interface EffectiveRunnerSettings {
68
+ readonly report: RunnerSettingsReport;
69
+ /** Effective yield (server OR local flag). */
70
+ readonly yielding: boolean;
71
+ /**
72
+ * The governor CPU budget in force, as a fraction of logical CPUs: the CPU budget,
73
+ * or min(yield budget, CPU budget) while yielding.
74
+ */
75
+ readonly governorCpuBudgetFraction: number;
76
+ }
77
+ export declare const defaultCpuBudgetPercent = 80;
78
+ export declare const defaultYieldCpuBudgetPercent = 50;
79
+ /**
80
+ * Computes every effective value (decision 0014 precedence):
81
+ * - ceiling keys: server != null ? min(server, ceiling ?? +inf) : (ceiling ?? default);
82
+ * - memory reserve (floor): server != null ? max(server, floor ?? 0) : (floor ?? adaptive default);
83
+ * - yield: server OR the local `forge-bridge yield on` flag.
84
+ * With no document at all (and the local flag off) the values equal today's env/default behaviour.
85
+ */
86
+ export declare function computeEffectiveRunnerSettings(document: RunnerSettingsDocument | null, environment: Readonly<Record<string, string | undefined>>, hostDefaults: RunnerHostDefaults, localYield: boolean): EffectiveRunnerSettings;
87
+ /**
88
+ * Parses the `ApplySettings` argument. Returns null when it has no usable version
89
+ * (the bridge then ignores it); malformed values become null so the host default applies.
90
+ */
91
+ export declare function parseRunnerSettingsDocument(raw: unknown): RunnerSettingsDocument | null;
92
+ /**
93
+ * The report for what is actually in force after an apply in which the host
94
+ * failed to put some keys in force: each failed key keeps the value (and source)
95
+ * that was in force before, and its failure is reported as an `apply_failed`
96
+ * rejection, so the server never reads a desired value as applied.
97
+ */
98
+ export declare function runnerSettingsInForce(report: RunnerSettingsReport, previous: RunnerSettingsReport, failures: readonly RunnerSettingRejection[]): RunnerSettingsReport;
99
+ /** True when two reports say the same thing (version included), so an unchanged recompute is not re-sent. */
100
+ export declare function sameRunnerSettingsReport(left: RunnerSettingsReport, right: RunnerSettingsReport): boolean;
101
+ /** The offer refusal message while the runner yields to foreground work. */
102
+ export declare function runnerYieldingMessage(report: RunnerSettingsReport): string;
103
+ /** One line describing the effective settings, for the bridge log. */
104
+ export declare function describeRunnerSettings(report: RunnerSettingsReport): string;