@loucompanion/forge-bridge 0.1.4-dev.fb770705136a → 0.2.1-dev.0fedbc5c9ef7

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 (269) hide show
  1. package/README.md +146 -3
  2. package/dist/bridge/bridge-chat-giphy-look.d.ts +48 -0
  3. package/dist/bridge/bridge-chat-giphy-look.js +55 -0
  4. package/dist/bridge/bridge-chat-provider-command.d.ts +40 -0
  5. package/dist/bridge/bridge-chat-provider-command.js +230 -0
  6. package/dist/bridge/bridge-chat.types.d.ts +20 -0
  7. package/dist/bridge/bridge-chat.types.js +28 -1
  8. package/dist/bridge/bridge-state-file.d.ts +161 -0
  9. package/dist/bridge/bridge-state-file.js +376 -0
  10. package/dist/bridge/bridge-state-io.d.ts +11 -0
  11. package/dist/bridge/bridge-state-io.js +50 -0
  12. package/dist/bridge/bridge-state-lock.d.ts +11 -0
  13. package/dist/bridge/bridge-state-lock.js +102 -0
  14. package/dist/bridge/bridge-state-unpublished.d.ts +17 -0
  15. package/dist/bridge/bridge-state-unpublished.js +111 -0
  16. package/dist/bridge/bridge.base.d.ts +9 -0
  17. package/dist/bridge/bridge.service.d.ts +92 -14
  18. package/dist/bridge/bridge.service.js +446 -380
  19. package/dist/bridge/bridge.types.d.ts +21 -0
  20. package/dist/bridge/in-flight-registry.d.ts +62 -0
  21. package/dist/bridge/in-flight-registry.js +207 -0
  22. package/dist/bridge/local-yield-flag.d.ts +6 -0
  23. package/dist/bridge/local-yield-flag.js +34 -0
  24. package/dist/bridge/readiness-result-outbox.d.ts +5 -1
  25. package/dist/bridge/readiness-result-outbox.js +20 -0
  26. package/dist/bridge/runner-host-capabilities.d.ts +5 -0
  27. package/dist/bridge/runner-host-capabilities.js +31 -1
  28. package/dist/bridge/sandbox-resource-accounting.d.ts +16 -0
  29. package/dist/bridge/sandbox-resource-accounting.js +150 -0
  30. package/dist/bridge/test-postgres-capability.d.ts +14 -0
  31. package/dist/bridge/test-postgres-capability.js +120 -0
  32. package/dist/bridge/windows-bash-resolution.d.ts +31 -0
  33. package/dist/bridge/windows-bash-resolution.js +153 -0
  34. package/dist/cleanup/cleanup-wip.d.ts +12 -0
  35. package/dist/cleanup/cleanup-wip.js +66 -0
  36. package/dist/cleanup/cleanup.service.d.ts +20 -1
  37. package/dist/cleanup/cleanup.service.js +150 -169
  38. package/dist/cleanup/cleanup.types.d.ts +6 -0
  39. package/dist/cleanup/forge-owned-paths.d.ts +9 -0
  40. package/dist/cleanup/forge-owned-paths.js +53 -0
  41. package/dist/cleanup/host-runtime-ledger.d.ts +7 -0
  42. package/dist/cleanup/host-runtime-ledger.js +130 -0
  43. package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
  44. package/dist/cleanup/managed-branch-sweep.js +111 -0
  45. package/dist/cli/cli.help.js +74 -12
  46. package/dist/cli/cli.service.d.ts +19 -10
  47. package/dist/cli/cli.service.js +152 -187
  48. package/dist/cli/idle-status.d.ts +84 -0
  49. package/dist/cli/idle-status.js +181 -0
  50. package/dist/cli/local-config.d.ts +6 -0
  51. package/dist/cli/local-config.js +32 -4
  52. package/dist/cli/provider-cli-detection.d.ts +10 -0
  53. package/dist/cli/provider-cli-detection.js +160 -0
  54. package/dist/runtime/aspnet-runtime-prebuild.d.ts +20 -0
  55. package/dist/runtime/aspnet-runtime-prebuild.js +184 -18
  56. package/dist/runtime/attempt-database-broker.d.ts +1 -1
  57. package/dist/runtime/attempt-node-runtime-launcher.d.ts +36 -0
  58. package/dist/runtime/attempt-node-runtime-launcher.js +169 -0
  59. package/dist/runtime/attempt-process-supervisor.d.ts +2 -0
  60. package/dist/runtime/attempt-process-supervisor.js +12 -6
  61. package/dist/runtime/docker-engine-probe.d.ts +5 -0
  62. package/dist/runtime/docker-engine-probe.js +7 -0
  63. package/dist/runtime/dotnet-build-outputs.d.ts +107 -0
  64. package/dist/runtime/dotnet-build-outputs.js +402 -0
  65. package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
  66. package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
  67. package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
  68. package/dist/runtime/ephemeral-test-postgres.js +303 -0
  69. package/dist/runtime/host-facts.d.ts +2 -1
  70. package/dist/runtime/host-listener-inspector.d.ts +26 -0
  71. package/dist/runtime/host-listener-inspector.js +84 -3
  72. package/dist/runtime/host-load-admission.d.ts +72 -0
  73. package/dist/runtime/host-load-admission.js +99 -0
  74. package/dist/runtime/host-load-child-environment.d.ts +27 -0
  75. package/dist/runtime/host-load-child-environment.js +76 -0
  76. package/dist/runtime/host-load-forge-cgroups.d.ts +49 -0
  77. package/dist/runtime/host-load-forge-cgroups.js +140 -0
  78. package/dist/runtime/host-load-governor-config.d.ts +61 -0
  79. package/dist/runtime/host-load-governor-config.js +86 -0
  80. package/dist/runtime/host-load-governor.d.ts +193 -0
  81. package/dist/runtime/host-load-governor.js +662 -0
  82. package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
  83. package/dist/runtime/host-load-ledger-lock.js +187 -0
  84. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  85. package/dist/runtime/host-load-runtime-settings.js +80 -0
  86. package/dist/runtime/host-load-sampler.d.ts +75 -2
  87. package/dist/runtime/host-load-sampler.js +142 -8
  88. package/dist/runtime/host-load-step-class.d.ts +70 -0
  89. package/dist/runtime/host-load-step-class.js +161 -0
  90. package/dist/runtime/host-load-step-reaper.d.ts +27 -0
  91. package/dist/runtime/host-load-step-reaper.js +95 -0
  92. package/dist/runtime/host-load-step-run.d.ts +73 -0
  93. package/dist/runtime/host-load-step-run.js +102 -0
  94. package/dist/runtime/host-load-test-slot.d.ts +43 -0
  95. package/dist/runtime/host-load-test-slot.js +88 -0
  96. package/dist/runtime/host-load-token-ledger.d.ts +200 -0
  97. package/dist/runtime/host-load-token-ledger.js +453 -0
  98. package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
  99. package/dist/runtime/host-load-windows-cpu.js +85 -0
  100. package/dist/runtime/host-pressure-stall.d.ts +21 -1
  101. package/dist/runtime/host-pressure-stall.js +48 -1
  102. package/dist/runtime/host-runtime-contract.d.ts +15 -0
  103. package/dist/runtime/host-runtime-contract.js +33 -2
  104. package/dist/runtime/host-runtime-lease.d.ts +101 -6
  105. package/dist/runtime/host-runtime-lease.js +408 -294
  106. package/dist/runtime/host-runtime-ledger-recovery.d.ts +20 -0
  107. package/dist/runtime/host-runtime-ledger-recovery.js +134 -0
  108. package/dist/runtime/host-runtime-promotion.d.ts +101 -2
  109. package/dist/runtime/host-runtime-promotion.js +355 -14
  110. package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
  111. package/dist/runtime/host-runtime-requirements-check.js +29 -0
  112. package/dist/runtime/host-runtime-requirements.d.ts +36 -0
  113. package/dist/runtime/host-runtime-requirements.js +117 -0
  114. package/dist/runtime/managed-command-teardown.js +5 -16
  115. package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
  116. package/dist/runtime/native-test-postgres-fallback.js +60 -8
  117. package/dist/runtime/playwright-host-runtime-adapter.d.ts +7 -0
  118. package/dist/runtime/playwright-host-runtime-adapter.js +13 -1
  119. package/dist/runtime/prepared-runtime-identity.d.ts +4 -0
  120. package/dist/runtime/prepared-runtime-identity.js +130 -9
  121. package/dist/runtime/prepared-runtime-readiness.d.ts +13 -1
  122. package/dist/runtime/prepared-runtime-readiness.js +63 -16
  123. package/dist/runtime/runner-settings.d.ts +104 -0
  124. package/dist/runtime/runner-settings.js +236 -0
  125. package/dist/runtime/supervised-runtime-build-guard.d.ts +45 -0
  126. package/dist/runtime/supervised-runtime-build-guard.js +112 -0
  127. package/dist/sandbox/host-capacity-broker.d.ts +115 -0
  128. package/dist/sandbox/host-capacity-broker.js +336 -0
  129. package/dist/sandbox/managed-branch.d.ts +13 -0
  130. package/dist/sandbox/managed-branch.js +90 -0
  131. package/dist/sandbox/provider-auth/codex.js +11 -11
  132. package/dist/sandbox/runtime.d.ts +10 -1
  133. package/dist/sandbox/runtime.js +47 -8
  134. package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
  135. package/dist/sandbox/sandbox-cgroups.js +42 -0
  136. package/dist/session/architect-waits.d.ts +2 -0
  137. package/dist/session/architect-waits.js +138 -0
  138. package/dist/session/managed-attempt-tools.d.ts +2 -7
  139. package/dist/session/managed-attempt-tools.js +207 -121
  140. package/dist/session/managed-build-coordinator.d.ts +16 -0
  141. package/dist/session/managed-build-coordinator.js +10 -0
  142. package/dist/session/managed-build-receipt.d.ts +5 -0
  143. package/dist/session/managed-build-receipt.js +8 -3
  144. package/dist/session/managed-command-host-load.d.ts +47 -0
  145. package/dist/session/managed-command-host-load.js +83 -0
  146. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  147. package/dist/session/mcp-argument-coercion.js +121 -0
  148. package/dist/session/phase-completion.artifacts.d.ts +7 -0
  149. package/dist/session/phase-completion.artifacts.js +96 -26
  150. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  151. package/dist/session/phase-completion.command-validation.js +77 -0
  152. package/dist/session/phase-completion.d.ts +12 -0
  153. package/dist/session/phase-completion.helpers.js +13 -12
  154. package/dist/session/phase-completion.js +5 -0
  155. package/dist/session/phase-completion.mcp-args.d.ts +9 -0
  156. package/dist/session/phase-completion.mcp-args.js +156 -0
  157. package/dist/session/phase-completion.prompts.js +6 -1
  158. package/dist/session/phase-completion.runtime.d.ts +5 -11
  159. package/dist/session/phase-completion.runtime.js +91 -215
  160. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  161. package/dist/session/phase-completion.schema-parts.js +188 -0
  162. package/dist/session/phase-completion.schemas.d.ts +3 -3
  163. package/dist/session/phase-completion.schemas.js +208 -231
  164. package/dist/session/phase-completion.validation.d.ts +2 -3
  165. package/dist/session/phase-completion.validation.js +49 -93
  166. package/dist/session/pre-publication-host-load.d.ts +27 -0
  167. package/dist/session/pre-publication-host-load.js +111 -0
  168. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  169. package/dist/session/pre-publication-native-postgres.js +111 -0
  170. package/dist/session/pre-publication-pass.d.ts +61 -0
  171. package/dist/session/pre-publication-pass.js +148 -0
  172. package/dist/session/pre-publication-process.d.ts +3 -0
  173. package/dist/session/pre-publication-process.js +31 -19
  174. package/dist/session/pre-publication-step-execution.d.ts +12 -0
  175. package/dist/session/pre-publication-step-execution.js +50 -0
  176. package/dist/session/pre-publication-validation.d.ts +37 -21
  177. package/dist/session/pre-publication-validation.js +221 -182
  178. package/dist/session/provider-cli/claude-background-work.d.ts +67 -0
  179. package/dist/session/provider-cli/claude-background-work.js +181 -0
  180. package/dist/session/provider-cli/host-build-lock.d.ts +18 -0
  181. package/dist/session/provider-cli/host-build-lock.js +30 -0
  182. package/dist/session/provider-cli/pre-publication-repair.d.ts +56 -0
  183. package/dist/session/provider-cli/pre-publication-repair.js +276 -0
  184. package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
  185. package/dist/session/provider-cli/provider-cli.child-environment.js +75 -0
  186. package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
  187. package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
  188. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +6 -3
  189. package/dist/session/provider-cli/provider-cli.merge-integrity.js +28 -8
  190. package/dist/session/provider-cli/provider-cli.process.d.ts +15 -36
  191. package/dist/session/provider-cli/provider-cli.process.js +41 -432
  192. package/dist/session/provider-cli/provider-cli.prompts.d.ts +5 -0
  193. package/dist/session/provider-cli/provider-cli.prompts.js +72 -32
  194. package/dist/session/provider-cli/provider-cli.runtime.d.ts +8 -0
  195. package/dist/session/provider-cli/provider-cli.runtime.js +29 -1
  196. package/dist/session/provider-cli/provider-cli.service.d.ts +7 -1
  197. package/dist/session/provider-cli/provider-cli.service.js +98 -173
  198. package/dist/session/provider-cli/provider-cli.types.d.ts +30 -0
  199. package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
  200. package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
  201. package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
  202. package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
  203. package/dist/session/provider-cli/provider-in-flight-work.d.ts +4 -0
  204. package/dist/session/provider-cli/provider-in-flight-work.js +45 -0
  205. package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
  206. package/dist/session/provider-cli/provider-output-pipes.js +67 -0
  207. package/dist/session/provider-cli/provider-output-state.d.ts +2 -0
  208. package/dist/session/provider-cli/provider-output-state.js +6 -0
  209. package/dist/session/provider-cli/provider-user-config-isolation.d.ts +69 -0
  210. package/dist/session/provider-cli/provider-user-config-isolation.js +164 -0
  211. package/dist/session/qa-sidecar-validation.d.ts +6 -0
  212. package/dist/session/qa-sidecar-validation.js +28 -0
  213. package/dist/session/sandbox-host-capacity-gate.d.ts +51 -0
  214. package/dist/session/sandbox-host-capacity-gate.js +257 -0
  215. package/dist/session/session-redaction.js +31 -181
  216. package/dist/session/session.base.d.ts +9 -1
  217. package/dist/session/session.service.d.ts +15 -2
  218. package/dist/session/session.service.js +246 -88
  219. package/dist/session/session.types.d.ts +4 -0
  220. package/dist/session/session.types.js +7 -7
  221. package/dist/session/sidecar-json-shape.d.ts +31 -0
  222. package/dist/session/sidecar-json-shape.js +217 -0
  223. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  224. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  225. package/dist/shared/fs/file-identity.d.ts +10 -0
  226. package/dist/shared/fs/file-identity.js +15 -0
  227. package/dist/shared/fs/replace-file.d.ts +7 -0
  228. package/dist/shared/fs/replace-file.js +33 -0
  229. package/dist/shared/process/host-process-recovery.d.ts +14 -3
  230. package/dist/shared/process/host-process-recovery.js +23 -3
  231. package/dist/shared/process/host-process-supervisor.d.ts +14 -1
  232. package/dist/shared/process/host-process-supervisor.js +67 -15
  233. package/dist/shared/process/process-tree.d.ts +52 -0
  234. package/dist/shared/process/process-tree.js +144 -0
  235. package/dist/shared/process/process.d.ts +67 -0
  236. package/dist/shared/process/process.js +213 -11
  237. package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
  238. package/dist/shared/process/windows-app-execution-alias.js +45 -0
  239. package/dist/shared/process/windows-launch.d.ts +18 -0
  240. package/dist/shared/process/windows-launch.js +68 -0
  241. package/dist/shared/provider-capabilities.js +14 -7
  242. package/dist/version.d.ts +1 -1
  243. package/dist/version.js +1 -1
  244. package/dist/worktree/dependency-warmer.d.ts +25 -0
  245. package/dist/worktree/dependency-warmer.js +46 -10
  246. package/dist/worktree/orphan-relink.d.ts +19 -0
  247. package/dist/worktree/orphan-relink.js +106 -0
  248. package/dist/worktree/wip-git.d.ts +42 -0
  249. package/dist/worktree/wip-git.js +139 -0
  250. package/dist/worktree/wip-refs.d.ts +77 -0
  251. package/dist/worktree/wip-refs.js +146 -0
  252. package/dist/worktree/wip-restore.d.ts +46 -0
  253. package/dist/worktree/wip-restore.js +280 -0
  254. package/dist/worktree/wip-snapshot.d.ts +53 -0
  255. package/dist/worktree/wip-snapshot.js +270 -0
  256. package/dist/worktree/worktree-inputs.d.ts +8 -0
  257. package/dist/worktree/worktree-inputs.js +134 -0
  258. package/dist/worktree/worktree-origin-sync.d.ts +35 -0
  259. package/dist/worktree/worktree-origin-sync.js +128 -0
  260. package/dist/worktree/worktree-wip-events.d.ts +18 -0
  261. package/dist/worktree/worktree-wip-events.js +115 -0
  262. package/dist/worktree/worktree-wip.d.ts +51 -0
  263. package/dist/worktree/worktree-wip.js +190 -0
  264. package/dist/worktree/worktree.base.d.ts +7 -1
  265. package/dist/worktree/worktree.service.d.ts +36 -5
  266. package/dist/worktree/worktree.service.js +126 -155
  267. package/dist/worktree/worktree.types.d.ts +42 -0
  268. package/package.json +2 -2
  269. package/runtime/windows-listener-owner.ps1 +12 -1
@@ -1,18 +1,75 @@
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;
8
+ /**
9
+ * Repositories whose full invalidation has started but not been confirmed on disk. They
10
+ * have no proof until a retried invalidation succeeds, so a failed delete cannot leave
11
+ * stale records admitting shared runs. A tombstone file beside the records carries the same
12
+ * state to other store instances and across restarts.
13
+ */
14
+ revoked = new Set();
15
+ /** Bumped by every full invalidation, so a read that raced one is discarded. */
16
+ revocations = new Map();
17
+ /** How long an isolation violation keeps its runtime contract from earning parallel proof again. */
18
+ quarantineMs = 24 * 60 * 60 * 1000;
19
+ /** Quarantines this instance holds whether or not they reached disk: a failed write cannot lift one. */
20
+ heldQuarantines = new Map();
21
+ /** Per repository, so concurrent invalidations and quarantine writes cannot lose each other's entries. */
22
+ serialQueues = new Map();
7
23
  constructor(stateRoot) {
8
24
  this.stateRoot = stateRoot;
9
25
  }
26
+ /**
27
+ * With an identity, returns proof for it: first a proof observed for the same isolation
28
+ * inputs (runtime contract plus launch-relevant files) at any commit, then a proof for the
29
+ * exact prepared source. The record keeps the commit it was observed at for audit.
30
+ */
10
31
  async load(repoId, identity) {
11
32
  const normalizedRepoId = normalizeRepoId(repoId);
33
+ if (await this.isRevoked(normalizedRepoId)) {
34
+ // Retry the revocation; whatever its outcome, nothing on disk may be trusted yet.
35
+ await this.invalidate(normalizedRepoId).catch(() => undefined);
36
+ return null;
37
+ }
38
+ const generation = this.revocations.get(normalizedRepoId) ?? 0;
39
+ const record = await this.readProof(normalizedRepoId, identity);
40
+ // A full invalidation that started while the records were being read revokes what was read.
41
+ if (!record || (this.revocations.get(normalizedRepoId) ?? 0) !== generation
42
+ || await this.isRevoked(normalizedRepoId)
43
+ || await this.isQuarantined(normalizedRepoId, record.runtimeContractFingerprint))
44
+ return null;
45
+ return record;
46
+ }
47
+ async readProof(normalizedRepoId, identity) {
48
+ if (identity?.isolationFingerprint) {
49
+ const reusable = await this.readRecord(this.isolationRecordPath(normalizedRepoId, identity.runtimeContractFingerprint, identity.isolationFingerprint), normalizedRepoId);
50
+ if (reusable && matchesIsolation(reusable, identity))
51
+ return reusable;
52
+ }
53
+ const parsed = await this.readRecord(this.recordPath(normalizedRepoId, identity), normalizedRepoId);
54
+ return parsed && (!identity || matchesIdentity(parsed, identity)) ? parsed : null;
55
+ }
56
+ async isRevoked(normalizedRepoId) {
57
+ if (this.revoked.has(normalizedRepoId))
58
+ return true;
59
+ try {
60
+ await fs.access(this.tombstonePath(normalizedRepoId));
61
+ return true;
62
+ }
63
+ catch (error) {
64
+ if (error.code === "ENOENT")
65
+ return false;
66
+ throw error;
67
+ }
68
+ }
69
+ async readRecord(target, normalizedRepoId) {
12
70
  try {
13
- const parsed = JSON.parse(await fs.readFile(this.recordPath(normalizedRepoId, identity), "utf8"));
14
- return validRecord(parsed, normalizedRepoId)
15
- && (!identity || matchesIdentity(parsed, identity)) ? parsed : null;
71
+ const parsed = JSON.parse(await fs.readFile(target, "utf8"));
72
+ return validRecord(parsed, normalizedRepoId) ? parsed : null;
16
73
  }
17
74
  catch (error) {
18
75
  if (error.code === "ENOENT" || error instanceof SyntaxError)
@@ -31,12 +88,15 @@ export class HostParallelPromotionStore {
31
88
  return [];
32
89
  throw error;
33
90
  }
91
+ const tombstones = new Set(entries.filter(value => /^[0-9a-f]{64}\.revoked$/u.test(value))
92
+ .map(value => value.slice(0, 64)));
34
93
  const records = [];
35
94
  for (const entry of entries.filter(value => /^[0-9a-f]{64}\.json$/u.test(value)).slice(0, 4096)) {
36
95
  try {
37
96
  const parsed = JSON.parse(await fs.readFile(path.join(root, entry), "utf8"));
38
97
  const repoId = typeof parsed.repoId === "string" ? normalizeRepoId(parsed.repoId) : "";
39
- if (repoId && validRecord(parsed, repoId))
98
+ if (repoId && !this.revoked.has(repoId) && !tombstones.has(repoKey(repoId))
99
+ && validRecord(parsed, repoId))
40
100
  records.push(parsed);
41
101
  }
42
102
  catch (error) {
@@ -46,10 +106,16 @@ export class HostParallelPromotionStore {
46
106
  }
47
107
  return records.sort((left, right) => left.repoId.localeCompare(right.repoId));
48
108
  }
49
- async observe(repoId, runtimeContract, dispatchAttemptId, verifiedPortNames, inputCommitSha, sourceFingerprint) {
109
+ async observe(repoId, runtimeContract, dispatchAttemptId, verifiedPortNames, inputCommitSha, sourceFingerprint, isolationFingerprint, revocationGeneration) {
50
110
  if (!hostRuntimeParallelEligible(runtimeContract)) {
51
111
  throw new Error("host_parallel_promotion_ineligible: the runtime contract is not eligible for parallel host execution.");
52
112
  }
113
+ if (await this.revokedSince(normalizeRepoId(repoId), revocationGeneration)) {
114
+ throw new Error("host_parallel_promotion_revoked: the repository was revoked, or its previous proofs could not be confirmed deleted.");
115
+ }
116
+ if (await this.isQuarantined(normalizeRepoId(repoId), hostRuntimeContractFingerprint(runtimeContract))) {
117
+ throw new Error("host_parallel_promotion_revoked: this runtime contract bound an unbrokered listener recently, so it is quarantined from parallel proof.");
118
+ }
53
119
  const requiredPorts = configuredLaunchPortNames(runtimeContract);
54
120
  const observedPorts = [...new Set(verifiedPortNames)].sort((left, right) => left.localeCompare(right));
55
121
  if (requiredPorts.length !== observedPorts.length
@@ -63,20 +129,148 @@ export class HostParallelPromotionStore {
63
129
  runtimeContractFingerprint: hostRuntimeContractFingerprint(runtimeContract),
64
130
  inputCommitSha: inputCommitSha ?? null,
65
131
  ...(sourceFingerprint ? { sourceFingerprint } : {}),
132
+ ...(isolationFingerprint ? { isolationFingerprint } : {}),
66
133
  runtimeContractSource: runtimeContract.source === "project" ? "project" : "derived",
67
134
  observedAt: new Date().toISOString(),
68
135
  observedDispatchAttemptId: normalizedUuid(dispatchAttemptId, "dispatch attempt"),
69
136
  verifiedPortNames: observedPorts,
70
137
  };
71
- if (inputCommitSha) {
72
- await this.writeRecord(this.recordPath(normalizedRepoId, {
73
- runtimeContractFingerprint: record.runtimeContractFingerprint, inputCommitSha, sourceFingerprint,
74
- }), record);
75
- }
76
- await this.writeRecord(this.recordPath(normalizedRepoId), record);
138
+ const written = [
139
+ ...(inputCommitSha ? [this.recordPath(normalizedRepoId, {
140
+ runtimeContractFingerprint: record.runtimeContractFingerprint, inputCommitSha, sourceFingerprint
141
+ })] : []),
142
+ ...(isolationFingerprint ? [this.isolationRecordPath(normalizedRepoId, record.runtimeContractFingerprint, isolationFingerprint)] : []),
143
+ this.recordPath(normalizedRepoId),
144
+ ];
145
+ for (const target of written)
146
+ await this.writeRecord(target, record);
77
147
  await this.pruneVersions(normalizedRepoId);
148
+ // A revocation that landed while the records were written may have deleted before them. Only this
149
+ // call's own records are withdrawn: a full invalidation here would bump the epoch and delete fresh
150
+ // proofs recorded since the revocation. If they cannot be withdrawn, fall back to revoking all.
151
+ if (await this.revokedSince(normalizedRepoId, revocationGeneration)) {
152
+ await this.withdrawRecords(written, record).catch(async () => await this.invalidate(normalizedRepoId).catch(() => undefined));
153
+ throw new Error("host_parallel_promotion_revoked: the repository was revoked while its proof was being recorded.");
154
+ }
78
155
  return record;
79
156
  }
157
+ /** Deletes each record file that still holds this record; one a newer proof has since replaced is left alone. */
158
+ async withdrawRecords(targets, record) {
159
+ for (const target of targets) {
160
+ const current = await this.readRecord(target, record.repoId);
161
+ if (current?.observedDispatchAttemptId === record.observedDispatchAttemptId && current.observedAt === record.observedAt) {
162
+ await fs.rm(target, { force: true });
163
+ }
164
+ }
165
+ }
166
+ /**
167
+ * The repository's revocation generation. A probe captures it at admission and passes it to
168
+ * observe, which then refuses to record if any full invalidation happened since: a violation by
169
+ * the probe itself or by a sibling means the run it watched does not prove isolation. It joins this
170
+ * instance's counter (bumped before any record is touched) with the repository's durable epoch, which
171
+ * every full invalidation bumps before deleting records, so one by another instance fences it too.
172
+ */
173
+ async revocationGeneration(repoId) {
174
+ const normalizedRepoId = normalizeRepoId(repoId);
175
+ return `${this.revocations.get(normalizedRepoId) ?? 0}:${await this.readEpoch(normalizedRepoId)}`;
176
+ }
177
+ /** A missing epoch is "0"; an unreadable one throws, so a caller fails closed rather than fencing nothing. */
178
+ async readEpoch(normalizedRepoId) {
179
+ try {
180
+ const epoch = (await fs.readFile(this.epochPath(normalizedRepoId), "utf8")).trim();
181
+ if (!/^[0-9a-f-]{1,64}$/u.test(epoch))
182
+ throw new Error("host_parallel_promotion_invalid: revocation epoch is malformed.");
183
+ return epoch;
184
+ }
185
+ catch (error) {
186
+ if (error.code === "ENOENT")
187
+ return "0";
188
+ throw error;
189
+ }
190
+ }
191
+ /** A fresh random epoch rather than a read-modify-write, so concurrent bumps by two processes cannot cancel out. */
192
+ async bumpEpoch(normalizedRepoId) {
193
+ const target = this.epochPath(normalizedRepoId), next = randomUUID();
194
+ await ensurePrivateDirectory(path.dirname(target));
195
+ const temporary = `${target}.${randomUUID()}.tmp`;
196
+ await fs.writeFile(temporary, `${next}
197
+ `, { encoding: "utf8", mode: 0o600, flag: "wx" });
198
+ await fs.rename(temporary, target).catch(async (error) => {
199
+ await fs.rm(temporary, { force: true }).catch(() => undefined);
200
+ throw error;
201
+ });
202
+ }
203
+ epochPath(normalizedRepoId) {
204
+ return path.join(this.stateRoot, "runtime-promotion", "host", `${repoKey(normalizedRepoId)}.epoch`);
205
+ }
206
+ /**
207
+ * Called on an isolation violation, before the proofs are revoked. A launch-time audit cannot see
208
+ * a listener bound later, and ordinary source is not an isolation input, so without this the next
209
+ * exclusive run of the same contract would re-earn proof at launch and readmit the shared runs that
210
+ * just collided. A quarantine lasts quarantineMs, or until the runtime contract changes.
211
+ */
212
+ async quarantine(repoId, runtimeContractFingerprint) {
213
+ const normalizedRepoId = normalizeRepoId(repoId);
214
+ const entry = this.holdQuarantine(normalizedRepoId, runtimeContractFingerprint);
215
+ await this.serialized(normalizedRepoId, () => this.persistQuarantine(normalizedRepoId, entry));
216
+ }
217
+ /** Whether the contract is quarantined, so callers can skip a probe or launch that could never earn proof. */
218
+ async quarantined(repoId, runtimeContractFingerprint) {
219
+ return await this.isQuarantined(normalizeRepoId(repoId), runtimeContractFingerprint);
220
+ }
221
+ async serialized(normalizedRepoId, operation) {
222
+ const run = (this.serialQueues.get(normalizedRepoId) ?? Promise.resolve()).catch(() => undefined).then(operation);
223
+ this.serialQueues.set(normalizedRepoId, run);
224
+ try {
225
+ return await run;
226
+ }
227
+ finally {
228
+ if (this.serialQueues.get(normalizedRepoId) === run)
229
+ this.serialQueues.delete(normalizedRepoId);
230
+ }
231
+ }
232
+ holdQuarantine(normalizedRepoId, runtimeContractFingerprint) {
233
+ const entry = { [runtimeContractFingerprint]: Date.now() + this.quarantineMs };
234
+ this.heldQuarantines.set(normalizedRepoId, { ...this.heldQuarantines.get(normalizedRepoId), ...entry });
235
+ return entry;
236
+ }
237
+ async persistQuarantine(normalizedRepoId, added) {
238
+ const entries = { ...await this.readQuarantine(normalizedRepoId), ...added };
239
+ const live = Object.fromEntries(Object.entries(entries).filter(([, until]) => until > Date.now()).slice(-64));
240
+ const target = this.quarantinePath(normalizedRepoId);
241
+ await ensurePrivateDirectory(path.dirname(target));
242
+ const temporary = `${target}.${randomUUID()}.tmp`;
243
+ await fs.writeFile(temporary, `${JSON.stringify(live)}\n`, { encoding: "utf8", mode: 0o600, flag: "wx" });
244
+ await fs.rename(temporary, target).catch(async (error) => {
245
+ await fs.rm(temporary, { force: true }).catch(() => undefined);
246
+ throw error;
247
+ });
248
+ }
249
+ async isQuarantined(normalizedRepoId, runtimeContractFingerprint) {
250
+ const until = Math.max(this.heldQuarantines.get(normalizedRepoId)?.[runtimeContractFingerprint] ?? 0, (await this.readQuarantine(normalizedRepoId))[runtimeContractFingerprint] ?? 0);
251
+ return until > Date.now();
252
+ }
253
+ /** Unreadable or malformed quarantine state reads as empty; a missing file is the normal case. */
254
+ async readQuarantine(normalizedRepoId) {
255
+ try {
256
+ const parsed = JSON.parse(await fs.readFile(this.quarantinePath(normalizedRepoId), "utf8"));
257
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
258
+ return {};
259
+ return Object.fromEntries(Object.entries(parsed).filter((entry) => typeof entry[1] === "number"));
260
+ }
261
+ catch (error) {
262
+ if (error.code === "ENOENT" || error instanceof SyntaxError)
263
+ return {};
264
+ throw error;
265
+ }
266
+ }
267
+ quarantinePath(normalizedRepoId) {
268
+ return path.join(this.stateRoot, "runtime-promotion", "host", `${repoKey(normalizedRepoId)}.quarantine`);
269
+ }
270
+ async revokedSince(normalizedRepoId, generation) {
271
+ return (generation !== undefined && await this.revocationGeneration(normalizedRepoId) !== generation)
272
+ || await this.isRevoked(normalizedRepoId);
273
+ }
80
274
  async writeRecord(target, record) {
81
275
  const root = path.dirname(target);
82
276
  await ensurePrivateDirectory(root);
@@ -111,8 +305,76 @@ export class HostParallelPromotionStore {
111
305
  await fs.rm(path.join(root, entry.name), { force: true });
112
306
  }
113
307
  }
114
- async invalidate(repoId, scope = "all") {
115
- const target = this.recordPath(normalizeRepoId(repoId));
308
+ /**
309
+ * Deletes the repository's proofs. A full invalidation revokes them in memory first and
310
+ * lifts that only once every record is confirmed deleted, so it fails closed: until then
311
+ * load and list return nothing for the repository and observe refuses to record.
312
+ */
313
+ async invalidate(repoId, scope = "all", quarantineFingerprints = []) {
314
+ const normalizedRepoId = normalizeRepoId(repoId);
315
+ if (scope === "discovery") {
316
+ await this.removeRecords(normalizedRepoId, scope);
317
+ return;
318
+ }
319
+ this.revoked.add(normalizedRepoId);
320
+ this.revocations.set(normalizedRepoId, (this.revocations.get(normalizedRepoId) ?? 0) + 1);
321
+ for (const fingerprint of quarantineFingerprints)
322
+ this.holdQuarantine(normalizedRepoId, fingerprint);
323
+ // Serialized, so a concurrent invalidation can neither drop this one's tombstone quarantine nor
324
+ // lift the revocation while this one still depends on it.
325
+ await this.serialized(normalizedRepoId, () => this.revokeAll(normalizedRepoId));
326
+ }
327
+ async revokeAll(normalizedRepoId) {
328
+ this.revoked.add(normalizedRepoId);
329
+ // The tombstone goes down before any record is deleted, so a restart part-way through still
330
+ // finds the repository revoked. If it cannot be written, deleting the records still revokes.
331
+ // It also carries any quarantine not yet on disk (this one, or one an earlier attempt left in
332
+ // it), and is lifted only once that quarantine is written: until then every instance and a
333
+ // restarted bridge find the repository revoked, so the quarantined contract cannot re-earn proof.
334
+ const tombstone = this.tombstonePath(normalizedRepoId);
335
+ const pending = Object.fromEntries(Object.entries({ ...await this.readTombstoneQuarantine(tombstone),
336
+ ...this.heldQuarantines.get(normalizedRepoId) }).filter(([, until]) => until > Date.now()));
337
+ await this.writeTombstone(tombstone, pending).catch(() => undefined);
338
+ // Before any record is deleted, so another instance's lease admitted earlier sees the change even
339
+ // once this invalidation completes and the tombstone is gone. A failed bump keeps the revocation.
340
+ await this.bumpEpoch(normalizedRepoId);
341
+ await this.removeRecords(normalizedRepoId, "all");
342
+ if (Object.keys(pending).length > 0)
343
+ await this.persistQuarantine(normalizedRepoId, pending);
344
+ await fs.rm(tombstone, { force: true });
345
+ this.revoked.delete(normalizedRepoId);
346
+ }
347
+ async writeTombstone(target, quarantine) {
348
+ await ensurePrivateDirectory(path.dirname(target));
349
+ const handle = await fs.open(target, "w", 0o600);
350
+ try {
351
+ await handle.writeFile(`${JSON.stringify({ revokedAt: new Date().toISOString(), quarantine })}\n`, "utf8");
352
+ await handle.sync();
353
+ }
354
+ finally {
355
+ await handle.close();
356
+ }
357
+ }
358
+ /** The quarantine a tombstone carries; an older plain-timestamp tombstone, or none, carries nothing. */
359
+ async readTombstoneQuarantine(target) {
360
+ try {
361
+ const parsed = JSON.parse(await fs.readFile(target, "utf8"));
362
+ const quarantine = parsed && typeof parsed === "object" ? parsed.quarantine : undefined;
363
+ if (!quarantine || typeof quarantine !== "object" || Array.isArray(quarantine))
364
+ return {};
365
+ return Object.fromEntries(Object.entries(quarantine).filter((entry) => typeof entry[1] === "number"));
366
+ }
367
+ catch (error) {
368
+ if (error.code === "ENOENT" || error instanceof SyntaxError)
369
+ return {};
370
+ throw error;
371
+ }
372
+ }
373
+ tombstonePath(normalizedRepoId) {
374
+ return path.join(this.stateRoot, "runtime-promotion", "host", `${repoKey(normalizedRepoId)}.revoked`);
375
+ }
376
+ async removeRecords(normalizedRepoId, scope) {
377
+ const target = this.recordPath(normalizedRepoId);
116
378
  await fs.rm(target, { force: true });
117
379
  // Background/default-branch discovery must not erase proofs bound to other
118
380
  // prepared sources. Actual containment/cleanup degradation invalidates all.
@@ -135,22 +397,101 @@ export class HostParallelPromotionStore {
135
397
  ])).digest("hex")}` : "";
136
398
  return path.join(this.stateRoot, "runtime-promotion", "host", `${key}${version}.json`);
137
399
  }
400
+ // Same <repo>.<version>.json shape as exact proofs, so pruning and invalidation cover it.
401
+ isolationRecordPath(normalizedRepoId, runtimeContractFingerprint, isolationFingerprint) {
402
+ const key = createHash("sha256").update(normalizedRepoId).digest("hex");
403
+ const version = createHash("sha256").update(JSON.stringify([
404
+ "isolation", runtimeContractFingerprint, isolationFingerprint,
405
+ ])).digest("hex");
406
+ return path.join(this.stateRoot, "runtime-promotion", "host", `${key}.${version}.json`);
407
+ }
408
+ }
409
+ function repoKey(normalizedRepoId) {
410
+ return createHash("sha256").update(normalizedRepoId).digest("hex");
138
411
  }
139
412
  function matchesIdentity(record, identity) {
413
+ // An identity that carries isolation inputs needs a record proven with the same ones: an
414
+ // ignored launch input can change while commit and source stay the same, and a legacy record
415
+ // (no isolation fingerprint) says nothing about those inputs.
140
416
  return record.runtimeContractFingerprint === identity.runtimeContractFingerprint
141
417
  && record.inputCommitSha === identity.inputCommitSha
142
- && record.sourceFingerprint === identity.sourceFingerprint;
418
+ && record.sourceFingerprint === identity.sourceFingerprint
419
+ && (identity.isolationFingerprint === undefined || record.isolationFingerprint === identity.isolationFingerprint);
420
+ }
421
+ function matchesIsolation(record, identity) {
422
+ return Boolean(identity.isolationFingerprint)
423
+ && record.runtimeContractFingerprint === identity.runtimeContractFingerprint
424
+ && record.isolationFingerprint === identity.isolationFingerprint;
425
+ }
426
+ /**
427
+ * Whether a stored proof admits this identity. An identity with isolation inputs (a prepared
428
+ * proof) needs the same isolation inputs, at any commit; one without them (an unprepared run)
429
+ * needs the same commit.
430
+ */
431
+ export function hostParallelPromotionMatches(record, identity) {
432
+ if (!record || record.runtimeContractFingerprint !== identity.runtimeContractFingerprint)
433
+ return false;
434
+ return identity.isolationFingerprint !== undefined
435
+ ? matchesIsolation(record, identity)
436
+ : record.inputCommitSha === identity.inputCommitSha;
143
437
  }
144
438
  export function hostRuntimeContractFingerprint(runtimeContract) {
145
439
  const canonical = JSON.stringify({
146
440
  schemaVersion: runtimeContract.contract.schemaVersion,
147
441
  runtime: runtimeContract.contract.runtime,
442
+ // Requirements join the fingerprint only when declared, so fingerprints of contracts
443
+ // written before decision 0013 (and their stored promotions) stay unchanged.
444
+ ...requirementsFingerprintPart(runtimeContract.contract.requires),
148
445
  derivedCandidateFingerprint: runtimeContract.source === "derived"
149
446
  ? runtimeContract.discovery?.candidateFingerprint ?? null
150
447
  : null,
151
448
  });
152
449
  return `sha256:${createHash("sha256").update(canonical).digest("hex")}`;
153
450
  }
451
+ /**
452
+ * Decides whether a restart may run the workspace's current runtime contract under the admission
453
+ * granted at start. A restart relaunches from the workspace in any case, so a contract whose only
454
+ * change is the values its ports launch with (launch environment, or discovery inputs that leave
455
+ * the contract itself unchanged) is adopted. This is how a conflict repair survives its own merge:
456
+ * merging the target branch can rename a variable in a derived launch profile, or change a
457
+ * manifest or project file, without changing anything admission granted. Every other part of the
458
+ * contract is admission: source, concurrency, ports (names, adapters, environment names, URL
459
+ * formats, and the command, arguments and working directory that launch them), Playwright, browser
460
+ * profile, singleton resources and declared requirements. Changing any of those throws the
461
+ * retryable host_runtime_contract_changed, so only a fresh attempt runs that contract. An attempt
462
+ * admitted to run in parallel keeps that admission, as it does when a merge changes only source;
463
+ * a restart never promotes, so the adopted contract earns no parallel-safety proof of its own here.
464
+ */
465
+ export function readmitHostRuntimeContract(admitted, current) {
466
+ const runtimeContractFingerprint = hostRuntimeContractFingerprint(current);
467
+ // The fingerprint leaves out the source of a project or default contract, but parallel
468
+ // eligibility depends on it, so an unchanged fingerprint alone does not prove the same admission.
469
+ if (runtimeContractFingerprint === admitted.runtimeContractFingerprint && current.source === admitted.runtimeContract.source) {
470
+ return { runtimeContract: admitted.runtimeContract, runtimeContractFingerprint, changed: false };
471
+ }
472
+ if (hostRuntimeAdmissionShape(current) !== hostRuntimeAdmissionShape(admitted.runtimeContract)) {
473
+ 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.");
474
+ }
475
+ return { runtimeContract: current, runtimeContractFingerprint, changed: true };
476
+ }
477
+ function hostRuntimeAdmissionShape(runtimeContract) {
478
+ const runtime = runtimeContract.contract.runtime;
479
+ return JSON.stringify({
480
+ source: runtimeContract.source,
481
+ schemaVersion: runtimeContract.contract.schemaVersion,
482
+ runtime: { ...runtime, ports: runtime.ports.map(port => ({ ...port, launch: port.launch && { ...port.launch, environment: undefined } })) },
483
+ ...requirementsFingerprintPart(runtimeContract.contract.requires),
484
+ });
485
+ }
486
+ // Cost hints are estimates, not placement constraints: they never change the fingerprint.
487
+ function requirementsFingerprintPart(requires) {
488
+ if (!requires)
489
+ return {};
490
+ const { costHints: _costHints, ...constraints } = requires;
491
+ const declared = constraints.minThreads !== null || constraints.minMemoryGiB !== null || constraints.toolchains.length > 0
492
+ || constraints.docker || constraints.playwright !== null || constraints.testPostgres !== null;
493
+ return declared ? { requires: constraints } : {};
494
+ }
154
495
  export function hostRuntimeParallelEligible(runtimeContract) {
155
496
  const runtime = runtimeContract.contract.runtime;
156
497
  const launchedPorts = runtime.ports.filter(port => port.launch !== null);
@@ -0,0 +1,17 @@
1
+ import type { HostRuntimeRequirements } from "./host-runtime-requirements.js";
2
+ /** What this bridge host offers, for the accept-time requirements recheck (decision 0013). */
3
+ export interface HostRequirementFacts {
4
+ readonly logicalThreads: number;
5
+ readonly totalMemoryBytes: number;
6
+ readonly availableToolchains: readonly string[];
7
+ readonly dockerAvailable: boolean;
8
+ readonly browserLaunch: boolean;
9
+ readonly testPostgresSuperuser: boolean | null;
10
+ }
11
+ export type HostRequirementsCheck = (requires: HostRuntimeRequirements | null | undefined) => readonly string[];
12
+ /**
13
+ * Reasons this host fails a host-mode attempt's declared requirements. The API filters on
14
+ * stored requirements; this recheck closes the gap when they were not reported yet or the
15
+ * attempt's contract differs from the probed one. Mirrors the API's wording.
16
+ */
17
+ export declare function unmetHostRuntimeRequirements(requires: HostRuntimeRequirements | null | undefined, facts: HostRequirementFacts): readonly string[];
@@ -0,0 +1,29 @@
1
+ const gib = 1024 * 1024 * 1024;
2
+ /**
3
+ * Reasons this host fails a host-mode attempt's declared requirements. The API filters on
4
+ * stored requirements; this recheck closes the gap when they were not reported yet or the
5
+ * attempt's contract differs from the probed one. Mirrors the API's wording.
6
+ */
7
+ export function unmetHostRuntimeRequirements(requires, facts) {
8
+ if (!requires)
9
+ return [];
10
+ const unmet = [];
11
+ if (requires.minThreads !== null && facts.logicalThreads < requires.minThreads) {
12
+ unmet.push(`needs ≥ ${requires.minThreads} threads; this host has ${facts.logicalThreads}`);
13
+ }
14
+ if (requires.minMemoryGiB !== null && facts.totalMemoryBytes / gib < requires.minMemoryGiB) {
15
+ unmet.push(`needs ≥ ${requires.minMemoryGiB} GiB; this host has ${(Math.floor(facts.totalMemoryBytes / gib * 100) / 100)}`);
16
+ }
17
+ const available = new Set(facts.availableToolchains.map(name => name.toLowerCase()));
18
+ const missing = requires.toolchains.filter(name => !available.has(name));
19
+ if (missing.length > 0)
20
+ unmet.push(`needs ${missing.join(", ")}; this host does not have ${missing.length === 1 ? "it" : "them"}`);
21
+ if (requires.docker && !facts.dockerAvailable)
22
+ unmet.push("needs Docker; this host does not have it");
23
+ if (requires.testPostgres?.superuser && !facts.dockerAvailable && facts.testPostgresSuperuser !== true) {
24
+ unmet.push("needs Docker or a superuser test database; this host has neither");
25
+ }
26
+ if (requires.playwright && !facts.browserLaunch)
27
+ unmet.push("needs Playwright browsers; this host cannot launch them");
28
+ return unmet;
29
+ }
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Project host requirements declared in `.forge/forge.runtime.yml` (decision 0013 §3).
3
+ *
4
+ * The bridge parses them with the runtime contract and reports them, with the contract
5
+ * fingerprint, in its readiness payload. The API stores them per fingerprint and uses them
6
+ * as hard placement filters. A contract without a `requires` section has no requirements.
7
+ */
8
+ export interface HostRuntimePlaywrightRequirement {
9
+ /** Pinned Playwright revision. Recorded; enforced once bridges probe browser revisions. */
10
+ readonly revision: string | null;
11
+ }
12
+ export interface HostRuntimeTestPostgresRequirement {
13
+ readonly extensions: readonly string[];
14
+ /** Suites need a superuser role (or Docker-backed Testcontainers). */
15
+ readonly superuser: boolean;
16
+ }
17
+ export interface HostRuntimeCostHint {
18
+ readonly cores: number | null;
19
+ readonly memoryGiB: number | null;
20
+ }
21
+ export interface HostRuntimeRequirements {
22
+ readonly minThreads: number | null;
23
+ readonly minMemoryGiB: number | null;
24
+ readonly toolchains: readonly string[];
25
+ /** Suites need a Docker engine (for example Testcontainers). */
26
+ readonly docker: boolean;
27
+ readonly playwright: HostRuntimePlaywrightRequirement | null;
28
+ readonly testPostgres: HostRuntimeTestPostgresRequirement | null;
29
+ /** Accepted and reported, not yet used for placement. */
30
+ readonly costHints: Readonly<Record<string, HostRuntimeCostHint>>;
31
+ }
32
+ /**
33
+ * Validates the optional top-level `requires` and `costHints` sections. Returns null when
34
+ * neither section is present, so contracts written before decision 0013 keep their meaning.
35
+ */
36
+ export declare function parseHostRuntimeRequirements(requires: unknown, costHints: unknown): HostRuntimeRequirements | null;
@@ -0,0 +1,117 @@
1
+ const requiresKeys = new Set(["minThreads", "minMemoryGiB", "toolchains", "docker", "playwright", "testPostgres"]);
2
+ const playwrightKeys = new Set(["revision"]);
3
+ const testPostgresKeys = new Set(["extensions", "superuser"]);
4
+ const costHintKeys = new Set(["cores", "memoryGiB"]);
5
+ const toolchainPattern = /^[a-z][a-z0-9_.-]{0,63}$/u;
6
+ const extensionPattern = /^[a-z][a-z0-9_]{0,62}$/u;
7
+ const stepClassPattern = /^[a-z][a-z0-9_.:-]{0,127}$/u;
8
+ const revisionPattern = /^[A-Za-z0-9][A-Za-z0-9._+-]{0,63}$/u;
9
+ /**
10
+ * Validates the optional top-level `requires` and `costHints` sections. Returns null when
11
+ * neither section is present, so contracts written before decision 0013 keep their meaning.
12
+ */
13
+ export function parseHostRuntimeRequirements(requires, costHints) {
14
+ if (isAbsent(requires) && isAbsent(costHints))
15
+ return null;
16
+ const section = isAbsent(requires) ? {} : object(requires, "requires");
17
+ rejectUnknownKeys(section, requiresKeys, "requires");
18
+ return {
19
+ minThreads: optionalNumber(section.minThreads, "requires.minThreads", 1, 1024, true),
20
+ minMemoryGiB: optionalNumber(section.minMemoryGiB, "requires.minMemoryGiB", 0.125, 4096, false),
21
+ toolchains: nameList(section.toolchains, "requires.toolchains", toolchainPattern, 32),
22
+ docker: optionalBoolean(section.docker, "requires.docker"),
23
+ playwright: parsePlaywright(section.playwright),
24
+ testPostgres: parseTestPostgres(section.testPostgres),
25
+ costHints: parseCostHints(costHints),
26
+ };
27
+ }
28
+ function parsePlaywright(value) {
29
+ if (isAbsent(value) || value === false)
30
+ return null;
31
+ if (value === true)
32
+ return { revision: null };
33
+ const playwright = object(value, "requires.playwright");
34
+ rejectUnknownKeys(playwright, playwrightKeys, "requires.playwright");
35
+ if (isAbsent(playwright.revision))
36
+ return { revision: null };
37
+ if (typeof playwright.revision !== "string" || !revisionPattern.test(playwright.revision.trim())) {
38
+ throw invalid("requires.playwright.revision must be a version or revision string.");
39
+ }
40
+ return { revision: playwright.revision.trim() };
41
+ }
42
+ function parseTestPostgres(value) {
43
+ if (isAbsent(value))
44
+ return null;
45
+ const testPostgres = object(value, "requires.testPostgres");
46
+ rejectUnknownKeys(testPostgres, testPostgresKeys, "requires.testPostgres");
47
+ return {
48
+ extensions: nameList(testPostgres.extensions, "requires.testPostgres.extensions", extensionPattern, 16),
49
+ superuser: optionalBoolean(testPostgres.superuser, "requires.testPostgres.superuser"),
50
+ };
51
+ }
52
+ function parseCostHints(value) {
53
+ if (isAbsent(value))
54
+ return {};
55
+ const hints = object(value, "costHints");
56
+ const entries = Object.entries(hints);
57
+ if (entries.length > 32)
58
+ throw invalid("costHints may declare at most 32 step classes.");
59
+ const parsed = {};
60
+ for (const [stepClass, hint] of entries.sort(([left], [right]) => left.localeCompare(right))) {
61
+ if (!stepClassPattern.test(stepClass))
62
+ throw invalid(`costHints step class '${stepClass}' is invalid.`);
63
+ const entry = object(hint, `costHints.${stepClass}`);
64
+ rejectUnknownKeys(entry, costHintKeys, `costHints.${stepClass}`);
65
+ parsed[stepClass] = {
66
+ cores: optionalNumber(entry.cores, `costHints.${stepClass}.cores`, 0.01, 1024, false),
67
+ memoryGiB: optionalNumber(entry.memoryGiB, `costHints.${stepClass}.memoryGiB`, 0.01, 4096, false),
68
+ };
69
+ }
70
+ return parsed;
71
+ }
72
+ function optionalNumber(value, label, minimum, maximum, integer) {
73
+ if (isAbsent(value))
74
+ return null;
75
+ if (typeof value !== "number" || !Number.isFinite(value) || value < minimum || value > maximum
76
+ || (integer && !Number.isSafeInteger(value))) {
77
+ throw invalid(`${label} must be ${integer ? "an integer" : "a number"} between ${minimum} and ${maximum}.`);
78
+ }
79
+ return value;
80
+ }
81
+ function nameList(value, label, pattern, maximum) {
82
+ if (isAbsent(value))
83
+ return [];
84
+ if (!Array.isArray(value) || value.length > maximum) {
85
+ throw invalid(`${label} must be a list with at most ${maximum} entries.`);
86
+ }
87
+ const names = value.map((entry, index) => {
88
+ const name = typeof entry === "string" ? entry.trim().toLowerCase() : "";
89
+ if (!pattern.test(name))
90
+ throw invalid(`${label}[${index}] is invalid.`);
91
+ return name;
92
+ });
93
+ return [...new Set(names)].sort((left, right) => left.localeCompare(right));
94
+ }
95
+ function optionalBoolean(value, label) {
96
+ if (isAbsent(value))
97
+ return false;
98
+ if (typeof value !== "boolean")
99
+ throw invalid(`${label} must be true or false.`);
100
+ return value;
101
+ }
102
+ function isAbsent(value) {
103
+ return value === undefined || value === null;
104
+ }
105
+ function object(value, label) {
106
+ if (!value || typeof value !== "object" || Array.isArray(value))
107
+ throw invalid(`${label} must be an object.`);
108
+ return value;
109
+ }
110
+ function rejectUnknownKeys(value, allowed, label) {
111
+ const unknown = Object.keys(value).find(key => !allowed.has(key));
112
+ if (unknown)
113
+ throw invalid(`unknown ${label} key '${unknown}'.`);
114
+ }
115
+ function invalid(message) {
116
+ return new Error(`runtime_contract_invalid: ${message}`);
117
+ }