@loucompanion/forge-bridge 0.1.3-dev.fbe15023cdfe → 0.1.4-dev.028808a841c8

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 (185) hide show
  1. package/README.md +89 -3
  2. package/dist/bridge/bridge-chat.types.d.ts +111 -0
  3. package/dist/bridge/bridge-chat.types.js +401 -0
  4. package/dist/bridge/bridge.base.d.ts +4 -1
  5. package/dist/bridge/bridge.service.d.ts +83 -3
  6. package/dist/bridge/bridge.service.js +1609 -152
  7. package/dist/bridge/bridge.types.d.ts +52 -1
  8. package/dist/bridge/dispatch-result-outbox.d.ts +35 -0
  9. package/dist/bridge/dispatch-result-outbox.js +87 -0
  10. package/dist/bridge/dispatch-result-worker.d.ts +2 -0
  11. package/dist/bridge/dispatch-result-worker.js +122 -0
  12. package/dist/bridge/internals.d.ts +2 -0
  13. package/dist/bridge/internals.js +1 -0
  14. package/dist/bridge/readiness-result-outbox.d.ts +21 -0
  15. package/dist/bridge/readiness-result-outbox.js +54 -0
  16. package/dist/bridge/readiness-result-worker.d.ts +2 -0
  17. package/dist/bridge/readiness-result-worker.js +121 -0
  18. package/dist/bridge/runner-host-capabilities.d.ts +15 -0
  19. package/dist/bridge/runner-host-capabilities.js +93 -0
  20. package/dist/cleanup/cleanup.service.d.ts +1 -0
  21. package/dist/cleanup/cleanup.service.js +70 -9
  22. package/dist/cli/cli.help.js +4 -4
  23. package/dist/cli/cli.service.d.ts +14 -6
  24. package/dist/cli/cli.service.js +75 -16
  25. package/dist/cli/local-config.d.ts +1 -0
  26. package/dist/cli/local-config.js +4 -0
  27. package/dist/runtime/aspnet-runtime-prebuild.d.ts +36 -0
  28. package/dist/runtime/aspnet-runtime-prebuild.js +341 -0
  29. package/dist/runtime/attempt-database-broker.d.ts +89 -0
  30. package/dist/runtime/attempt-database-broker.js +390 -0
  31. package/dist/runtime/attempt-node-runtime-launcher.d.ts +2 -1
  32. package/dist/runtime/attempt-node-runtime-launcher.js +57 -18
  33. package/dist/runtime/attempt-path-operation.d.ts +21 -0
  34. package/dist/runtime/attempt-path-operation.js +94 -0
  35. package/dist/runtime/attempt-private-directory.d.ts +6 -0
  36. package/dist/runtime/attempt-private-directory.js +54 -0
  37. package/dist/runtime/attempt-process-supervisor.d.ts +35 -0
  38. package/dist/runtime/attempt-process-supervisor.js +144 -23
  39. package/dist/runtime/canonical-source-file.d.ts +3 -0
  40. package/dist/runtime/canonical-source-file.js +54 -0
  41. package/dist/runtime/docker-engine-probe.d.ts +90 -0
  42. package/dist/runtime/docker-engine-probe.js +333 -0
  43. package/dist/runtime/generated-output-reset.d.ts +10 -0
  44. package/dist/runtime/generated-output-reset.js +62 -8
  45. package/dist/runtime/host-database-capability-boundary.d.ts +16 -0
  46. package/dist/runtime/host-database-capability-boundary.js +63 -0
  47. package/dist/runtime/host-diagnostics.d.ts +11 -0
  48. package/dist/runtime/host-diagnostics.js +192 -0
  49. package/dist/runtime/host-execution-root.d.ts +4 -0
  50. package/dist/runtime/host-execution-root.js +39 -0
  51. package/dist/runtime/host-facts.d.ts +35 -0
  52. package/dist/runtime/host-facts.js +95 -0
  53. package/dist/runtime/host-listener-inspector.d.ts +8 -1
  54. package/dist/runtime/host-listener-inspector.js +121 -60
  55. package/dist/runtime/host-load-sampler.d.ts +83 -0
  56. package/dist/runtime/host-load-sampler.js +164 -0
  57. package/dist/runtime/host-pressure-stall.d.ts +41 -0
  58. package/dist/runtime/host-pressure-stall.js +121 -0
  59. package/dist/runtime/host-runtime-contract.d.ts +13 -1
  60. package/dist/runtime/host-runtime-contract.js +170 -55
  61. package/dist/runtime/host-runtime-lease.d.ts +92 -8
  62. package/dist/runtime/host-runtime-lease.js +1193 -120
  63. package/dist/runtime/host-runtime-promotion.d.ts +12 -3
  64. package/dist/runtime/host-runtime-promotion.js +59 -12
  65. package/dist/runtime/managed-command-teardown.d.ts +62 -0
  66. package/dist/runtime/managed-command-teardown.js +607 -0
  67. package/dist/runtime/memory-capacity.d.ts +70 -0
  68. package/dist/runtime/memory-capacity.js +123 -0
  69. package/dist/runtime/native-test-postgres-fallback.d.ts +25 -0
  70. package/dist/runtime/native-test-postgres-fallback.js +91 -0
  71. package/dist/runtime/node-host-runtime-adapter.d.ts +3 -0
  72. package/dist/runtime/node-host-runtime-adapter.js +29 -11
  73. package/dist/runtime/pinned-directory-process.d.ts +9 -0
  74. package/dist/runtime/pinned-directory-process.js +61 -0
  75. package/dist/runtime/pinned-source-directory.d.ts +17 -0
  76. package/dist/runtime/pinned-source-directory.js +94 -0
  77. package/dist/runtime/playwright-browser-cache.d.ts +39 -0
  78. package/dist/runtime/playwright-browser-cache.js +227 -0
  79. package/dist/runtime/playwright-host-runtime-adapter.d.ts +12 -0
  80. package/dist/runtime/playwright-host-runtime-adapter.js +100 -58
  81. package/dist/runtime/prepared-runtime-identity.d.ts +6 -0
  82. package/dist/runtime/prepared-runtime-identity.js +218 -0
  83. package/dist/runtime/prepared-runtime-readiness.d.ts +30 -0
  84. package/dist/runtime/prepared-runtime-readiness.js +285 -0
  85. package/dist/runtime/runtime-isolation-lease.js +4 -1
  86. package/dist/runtime/workspace-resource-estimator.d.ts +17 -0
  87. package/dist/runtime/workspace-resource-estimator.js +174 -0
  88. package/dist/sandbox/preflight.d.ts +31 -1
  89. package/dist/sandbox/preflight.js +237 -51
  90. package/dist/sandbox/repository-lock.d.ts +2 -1
  91. package/dist/sandbox/repository-lock.js +19 -9
  92. package/dist/sandbox/runtime.d.ts +6 -1
  93. package/dist/sandbox/runtime.js +137 -107
  94. package/dist/sandbox/sandbox.types.d.ts +7 -0
  95. package/dist/sandbox/workspace.service.js +2 -0
  96. package/dist/session/managed-attempt-tools.d.ts +42 -1
  97. package/dist/session/managed-attempt-tools.js +692 -40
  98. package/dist/session/managed-build-coordinator.d.ts +5 -0
  99. package/dist/session/managed-build-coordinator.js +109 -0
  100. package/dist/session/managed-build-receipt.d.ts +21 -0
  101. package/dist/session/managed-build-receipt.js +337 -0
  102. package/dist/session/managed-verification-timeouts.d.ts +8 -0
  103. package/dist/session/managed-verification-timeouts.js +17 -0
  104. package/dist/session/phase-completion.artifacts.d.ts +17 -0
  105. package/dist/session/phase-completion.artifacts.js +228 -22
  106. package/dist/session/phase-completion.d.ts +11 -1
  107. package/dist/session/phase-completion.helpers.d.ts +5 -0
  108. package/dist/session/phase-completion.helpers.js +30 -7
  109. package/dist/session/phase-completion.js +14 -3
  110. package/dist/session/phase-completion.prompts.js +17 -18
  111. package/dist/session/phase-completion.runtime.d.ts +3 -1
  112. package/dist/session/phase-completion.runtime.js +148 -34
  113. package/dist/session/phase-completion.schemas.js +49 -2
  114. package/dist/session/phase-completion.validation.d.ts +1 -0
  115. package/dist/session/phase-completion.validation.js +111 -21
  116. package/dist/session/pre-publication-process.d.ts +20 -0
  117. package/dist/session/pre-publication-process.js +97 -0
  118. package/dist/session/pre-publication-skipped-tests.d.ts +21 -0
  119. package/dist/session/pre-publication-skipped-tests.js +109 -0
  120. package/dist/session/pre-publication-validation.d.ts +75 -0
  121. package/dist/session/pre-publication-validation.js +631 -0
  122. package/dist/session/provider-cli/bridge-cli.conformance-fixtures.d.ts +72 -0
  123. package/dist/session/provider-cli/bridge-cli.conformance-fixtures.js +462 -0
  124. package/dist/session/provider-cli/ci-repair-readiness.d.ts +8 -0
  125. package/dist/session/provider-cli/ci-repair-readiness.js +23 -3
  126. package/dist/session/provider-cli/provider-cli.artifacts.d.ts +6 -3
  127. package/dist/session/provider-cli/provider-cli.artifacts.js +62 -22
  128. package/dist/session/provider-cli/provider-cli.deterministic.js +34 -2
  129. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
  130. package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
  131. package/dist/session/provider-cli/provider-cli.process.d.ts +80 -0
  132. package/dist/session/provider-cli/provider-cli.process.js +694 -28
  133. package/dist/session/provider-cli/provider-cli.prompts.d.ts +10 -0
  134. package/dist/session/provider-cli/provider-cli.prompts.js +151 -16
  135. package/dist/session/provider-cli/provider-cli.repair-epoch.d.ts +6 -0
  136. package/dist/session/provider-cli/provider-cli.repair-epoch.js +11 -0
  137. package/dist/session/provider-cli/provider-cli.runtime.d.ts +14 -1
  138. package/dist/session/provider-cli/provider-cli.runtime.js +54 -3
  139. package/dist/session/provider-cli/provider-cli.service.d.ts +30 -5
  140. package/dist/session/provider-cli/provider-cli.service.js +858 -77
  141. package/dist/session/provider-cli/provider-cli.types.d.ts +2 -0
  142. package/dist/session/provider-cli/provider-in-flight-work.d.ts +6 -0
  143. package/dist/session/provider-cli/provider-in-flight-work.js +47 -0
  144. package/dist/session/provider-cli/provider-output-state.d.ts +16 -0
  145. package/dist/session/provider-cli/provider-output-state.js +370 -17
  146. package/dist/session/provider-cli/provider-usage.d.ts +9 -1
  147. package/dist/session/provider-cli/provider-usage.js +28 -5
  148. package/dist/session/publishable-worktree-changes.d.ts +54 -0
  149. package/dist/session/publishable-worktree-changes.js +193 -0
  150. package/dist/session/session-redaction.js +434 -9
  151. package/dist/session/session.service.js +145 -23
  152. package/dist/session/session.types.d.ts +147 -2
  153. package/dist/session/session.types.js +599 -7
  154. package/dist/session/unreferenced-exports.d.ts +12 -0
  155. package/dist/session/unreferenced-exports.js +59 -0
  156. package/dist/shared/format/format-bytes.d.ts +1 -0
  157. package/dist/shared/format/format-bytes.js +9 -0
  158. package/dist/shared/git/git.js +2 -1
  159. package/dist/shared/path/path.d.ts +1 -0
  160. package/dist/shared/path/path.js +18 -0
  161. package/dist/shared/process/dotnet-toolchain.d.ts +17 -0
  162. package/dist/shared/process/dotnet-toolchain.js +307 -0
  163. package/dist/shared/process/host-process-recovery.js +3 -2
  164. package/dist/shared/process/host-process-supervisor.d.ts +2 -0
  165. package/dist/shared/process/host-process-supervisor.js +60 -11
  166. package/dist/shared/process/process.d.ts +2 -0
  167. package/dist/shared/process/process.js +12 -7
  168. package/dist/shared/provider-capabilities.d.ts +3 -0
  169. package/dist/shared/provider-capabilities.js +85 -0
  170. package/dist/shared/redaction/redaction.d.ts +1 -0
  171. package/dist/shared/redaction/redaction.js +39 -3
  172. package/dist/shared/time/monotonic.d.ts +1 -0
  173. package/dist/shared/time/monotonic.js +8 -0
  174. package/dist/version.d.ts +1 -1
  175. package/dist/version.js +1 -1
  176. package/dist/worktree/dependency-warmer.d.ts +41 -9
  177. package/dist/worktree/dependency-warmer.js +571 -22
  178. package/dist/worktree/index.d.ts +1 -1
  179. package/dist/worktree/story-qa-reference-hydrator.d.ts +4 -0
  180. package/dist/worktree/story-qa-reference-hydrator.js +253 -0
  181. package/dist/worktree/worktree.service.d.ts +7 -0
  182. package/dist/worktree/worktree.service.js +253 -21
  183. package/dist/worktree/worktree.types.d.ts +7 -1
  184. package/package.json +7 -5
  185. package/runtime/windows-job-supervisor.ps1 +380 -14
@@ -0,0 +1,218 @@
1
+ import { createHash } from "node:crypto";
2
+ import fs from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { GitClient } from "../shared/git/git.js";
5
+ import { hostRuntimeContractPath, loadHostRuntimeContract } from "./host-runtime-contract.js";
6
+ import { hostRuntimeContractFingerprint } from "./host-runtime-promotion.js";
7
+ import { readCanonicalSourceFile } from "./canonical-source-file.js";
8
+ import { assertCanonicalDirectory } from "./attempt-private-directory.js";
9
+ import { generatedOutputRootForPath } from "./generated-output-reset.js";
10
+ import { readPinnedSourceDirectory } from "./pinned-source-directory.js";
11
+ /** Bind evidence to the prepared source, including unstaged replacements, not just HEAD. */
12
+ export async function preparedRuntimeIdentity(worktreePath, signal, diagnostics) {
13
+ diagnostics?.entries.clear();
14
+ const root = await fs.realpath(worktreePath);
15
+ const rootIdentity = (await assertCanonicalDirectory(root));
16
+ const sourceKey = (target) => process.platform === "win32" ? target.toLowerCase() : target;
17
+ const expectedEntries = new Map();
18
+ const directories = new Map();
19
+ const containedRelative = (target) => {
20
+ const relative = path.relative(root, path.resolve(target));
21
+ if (relative.startsWith("..") || path.isAbsolute(relative)) {
22
+ throw new Error("host_runtime_source_invalid: source path escapes the worktree.");
23
+ }
24
+ return relative.replaceAll("\\", "/");
25
+ };
26
+ const directorySnapshot = async (target) => {
27
+ const resolved = path.resolve(target);
28
+ containedRelative(resolved);
29
+ const key = sourceKey(resolved);
30
+ let captured = directories.get(key);
31
+ if (!captured) {
32
+ captured = (async () => {
33
+ let identity;
34
+ if (key === sourceKey(root))
35
+ identity = rootIdentity;
36
+ else {
37
+ const parent = await expectedEntry(resolved);
38
+ if (!parent || parent.kind !== "directory") {
39
+ throw new Error("host_runtime_source_changed: discovery directory identity changed.");
40
+ }
41
+ identity = parent.identity;
42
+ }
43
+ const entries = await readPinnedSourceDirectory(resolved, identity);
44
+ for (const entry of entries)
45
+ expectedEntries.set(sourceKey(path.join(resolved, entry.name)), entry);
46
+ return { path: resolved, identity, entries };
47
+ })();
48
+ directories.set(key, captured);
49
+ }
50
+ return (await captured).entries.map(entry => ({
51
+ name: entry.name,
52
+ isDirectory: entry.kind === "directory",
53
+ isFile: entry.kind === "file",
54
+ }));
55
+ };
56
+ const expectedEntry = async (target) => {
57
+ const resolved = path.resolve(target);
58
+ containedRelative(resolved);
59
+ if (sourceKey(resolved) === sourceKey(root)) {
60
+ return { name: path.basename(root), kind: "directory", identity: rootIdentity, size: 0n };
61
+ }
62
+ const parentPath = path.dirname(resolved);
63
+ if (sourceKey(parentPath) !== sourceKey(root)) {
64
+ const parent = await expectedEntry(parentPath);
65
+ if (!parent)
66
+ return undefined;
67
+ if (parent.kind !== "directory") {
68
+ throw new Error("host_runtime_source_changed: discovery ancestor is not a directory.");
69
+ }
70
+ }
71
+ await directorySnapshot(parentPath);
72
+ return expectedEntries.get(sourceKey(resolved));
73
+ };
74
+ // Pin the worktree before Git or discovery uses it. Every child directory is
75
+ // subsequently reached through an identity captured from its pinned parent.
76
+ await directorySnapshot(root);
77
+ const git = new GitClient();
78
+ const head = (await git.run(root, ["rev-parse", "HEAD"])).trim();
79
+ const inventory = async () => {
80
+ const included = (name) => name && (!name.startsWith(".forge/") || name === ".forge/forge.runtime.yml");
81
+ // ls-files --deleted loses a deletion once staged. HEAD-relative tombstones
82
+ // keep the same prepared source identity before and after git add -u.
83
+ const deleted = [...new Set((await git.run(root, ["ls-files", "-z", "--deleted"]))
84
+ .split("\0").concat((await git.run(root, ["diff", "--name-only", "--diff-filter=D", "-z", "HEAD", "--"]))
85
+ .split("\0")).filter(included))].sort();
86
+ const tracked = (await git.run(root, ["ls-files", "-z", "--cached"]))
87
+ .split("\0").filter(included);
88
+ const untracked = (await git.run(root, ["ls-files", "-z", "--others", "--exclude-standard"]))
89
+ .split("\0").filter(included);
90
+ const generatedRoots = [...new Set(untracked
91
+ .map(generatedOutputRootForPath)
92
+ .filter((candidate) => candidate !== null))];
93
+ const comparisonKey = (value) => process.platform === "win32" ? value.toLowerCase() : value;
94
+ const containedBy = (name, candidate) => {
95
+ const key = comparisonKey(name);
96
+ const rootKey = comparisonKey(candidate);
97
+ return key === rootKey || key.startsWith(`${rootKey}/`);
98
+ };
99
+ // resetGeneratedOutputs only quarantines a generated directory when Git
100
+ // confirms it contains no tracked files. Mirror that boundary here so the
101
+ // cleanup performed by runtime.start cannot invalidate its own foreground
102
+ // proof, while tracked or mixed-content directories remain source-bound.
103
+ const resettableRoots = generatedRoots.filter(candidate => !tracked.some(name => containedBy(name, candidate)));
104
+ const names = [...new Set(tracked.concat(untracked.filter(name => !resettableRoots.some(candidate => containedBy(name, candidate))), deleted, hostRuntimeContractPath).filter(included))].sort();
105
+ return { names, deleted };
106
+ };
107
+ const source = await inventory();
108
+ const { names } = source;
109
+ if (names.length > 100_000)
110
+ throw new Error("host_runtime_source_invalid: source inventory exceeds the file limit.");
111
+ const deleted = new Set(source.deleted);
112
+ const hash = createHash("sha256");
113
+ const snapshot = new Map();
114
+ const additional = new Map();
115
+ let discoveryCapture = Promise.resolve();
116
+ let bytes = 0;
117
+ for (const name of names) {
118
+ signal?.throwIfAborted();
119
+ const target = path.resolve(root, name);
120
+ const relative = path.relative(root, target);
121
+ if (relative.startsWith("..") || path.isAbsolute(relative)) {
122
+ throw new Error("host_runtime_source_invalid: source path escapes the worktree.");
123
+ }
124
+ hash.update(JSON.stringify(name));
125
+ try {
126
+ const expected = await expectedEntry(target);
127
+ if (!expected || expected.kind !== "file") {
128
+ throw Object.assign(new Error("host_runtime_source_changed: source inventory no longer names an ordinary file."), { code: "ENOENT" });
129
+ }
130
+ const sourceBytes = await readCanonicalSourceFile(target, 256 * 1024 * 1024 - bytes, expected.identity);
131
+ bytes += sourceBytes.length;
132
+ const digest = createHash("sha256").update(sourceBytes).digest();
133
+ hash.update(digest);
134
+ diagnostics?.entries.set(name, digest.toString("hex"));
135
+ snapshot.set(sourceKey(target), Promise.resolve(sourceBytes));
136
+ }
137
+ catch (error) {
138
+ if (error.code !== "ENOENT" || (!deleted.has(name) && name !== hostRuntimeContractPath))
139
+ throw error;
140
+ const disposition = deleted.has(name) ? "deleted" : "absent";
141
+ hash.update(disposition);
142
+ diagnostics?.entries.set(name, disposition);
143
+ snapshot.set(sourceKey(target), Promise.resolve(null));
144
+ }
145
+ }
146
+ const contract = await loadHostRuntimeContract(root, target => {
147
+ const key = sourceKey(path.resolve(target));
148
+ const captured = snapshot.get(key);
149
+ if (captured)
150
+ return captured;
151
+ // Discovery also consumes ignored lockfiles and launch metadata. Capture
152
+ // those once, too; omission from Git's inventory must not change discovery.
153
+ const capture = discoveryCapture.then(async () => {
154
+ signal?.throwIfAborted();
155
+ const relative = path.relative(root, target).replaceAll("\\", "/");
156
+ if (relative.startsWith("..") || path.isAbsolute(relative)) {
157
+ throw new Error("host_runtime_source_invalid: discovery input escapes the worktree.");
158
+ }
159
+ let sourceBytes;
160
+ try {
161
+ const expected = await expectedEntry(target);
162
+ if (!expected)
163
+ sourceBytes = null;
164
+ else if (expected.kind !== "file") {
165
+ throw new Error("host_runtime_source_changed: discovery input is not an ordinary file.");
166
+ }
167
+ else {
168
+ sourceBytes = await readCanonicalSourceFile(target, 256 * 1024 * 1024 - bytes, expected.identity);
169
+ }
170
+ if (sourceBytes !== null) {
171
+ bytes += sourceBytes.length;
172
+ if (bytes > 256 * 1024 * 1024)
173
+ throw new Error("host_runtime_source_invalid: discovery exceeds the byte limit.");
174
+ }
175
+ }
176
+ catch (error) {
177
+ if (error.code !== "ENOENT")
178
+ throw error;
179
+ sourceBytes = null;
180
+ }
181
+ additional.set(relative, sourceBytes);
182
+ return sourceBytes;
183
+ });
184
+ // Discovery walks in parallel, but reads share one total byte budget.
185
+ discoveryCapture = capture.then(() => undefined, () => undefined);
186
+ snapshot.set(key, capture);
187
+ return capture;
188
+ }, directorySnapshot);
189
+ for (const [name, sourceBytes] of [...additional].sort(([left], [right]) => left.localeCompare(right))) {
190
+ hash.update(JSON.stringify(["runtime-discovery", name]));
191
+ const digest = sourceBytes === null
192
+ ? null
193
+ : createHash("sha256").update(sourceBytes).digest();
194
+ hash.update(digest ?? "absent");
195
+ diagnostics?.entries.set(`runtime-discovery:${name}`, digest?.toString("hex") ?? "absent");
196
+ }
197
+ if (head !== (await git.run(root, ["rev-parse", "HEAD"])).trim()
198
+ || JSON.stringify(source) !== JSON.stringify(await inventory())) {
199
+ throw new Error("host_runtime_source_changed: prepared source changed during verification.");
200
+ }
201
+ for (const captured of await Promise.all([...directories.values()])) {
202
+ const current = await readPinnedSourceDirectory(captured.path, captured.identity);
203
+ if (directoryInventory(current) !== directoryInventory(captured.entries)) {
204
+ throw new Error("host_runtime_source_changed: runtime discovery inventory changed during verification.");
205
+ }
206
+ }
207
+ return {
208
+ inputCommitSha: head,
209
+ runtimeContractFingerprint: hostRuntimeContractFingerprint(contract),
210
+ sourceFingerprint: `sha256:${hash.digest("hex")}`,
211
+ };
212
+ }
213
+ function directoryInventory(entries) {
214
+ return JSON.stringify(entries.map(entry => ({
215
+ name: entry.name,
216
+ kind: entry.kind,
217
+ })));
218
+ }
@@ -0,0 +1,30 @@
1
+ import type { RunOnceDispatchPacket } from "../session/session.types.js";
2
+ import type { HostRuntimeAdmissionCheckpointHandler, HostRuntimeLeaseRuntime } from "./host-runtime-lease.js";
3
+ import { HostParallelPromotionStore, type HostParallelProofIdentity } from "./host-runtime-promotion.js";
4
+ export interface PreparedRuntimePendingSnapshot {
5
+ readonly repoId: string;
6
+ readonly dispatchAttemptId: string;
7
+ readonly fencingToken: string;
8
+ readonly probeDispatchAttemptId?: string;
9
+ readonly probeFencingToken?: string;
10
+ }
11
+ /** Foreground barrier: prepare a wave, verify its exact runtimes, then release agents. */
12
+ export declare class PreparedRuntimeReadiness {
13
+ private readonly runtime;
14
+ private readonly store;
15
+ private readonly releasePreparation;
16
+ private readonly admissionExpired;
17
+ private readonly preparations;
18
+ private readonly draining;
19
+ constructor(runtime: HostRuntimeLeaseRuntime, store: HostParallelPromotionStore, releasePreparation: (id: string, fence: string) => Promise<unknown>, admissionExpired: () => Error);
20
+ acquire(dispatch: RunOnceDispatchPacket, signal?: AbortSignal): Promise<readonly string[]>;
21
+ has(id: string): boolean;
22
+ hasPending(): boolean;
23
+ pendingSnapshots(): readonly PreparedRuntimePendingSnapshot[];
24
+ verify(dispatch: RunOnceDispatchPacket, worktree: string, checkpoint?: HostRuntimeAdmissionCheckpointHandler): Promise<HostParallelProofIdentity | undefined>;
25
+ renew(id: string, fence: string, expiresAt: string): Promise<void>;
26
+ cancel(id: string, fence: string, reason?: Error): void;
27
+ private drain;
28
+ private scheduleDeadline;
29
+ private check;
30
+ }
@@ -0,0 +1,285 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { GitClient } from "../shared/git/git.js";
3
+ import { loadHostRuntimeContract } from "./host-runtime-contract.js";
4
+ import { configuredLaunchPortNames, hostRuntimeContractFingerprint, hostRuntimeParallelEligible } from "./host-runtime-promotion.js";
5
+ import { preparedRuntimeIdentity } from "./prepared-runtime-identity.js";
6
+ /** Foreground barrier: prepare a wave, verify its exact runtimes, then release agents. */
7
+ export class PreparedRuntimeReadiness {
8
+ runtime;
9
+ store;
10
+ releasePreparation;
11
+ admissionExpired;
12
+ preparations = new Map();
13
+ draining = new Set();
14
+ constructor(runtime, store, releasePreparation, admissionExpired) {
15
+ this.runtime = runtime;
16
+ this.store = store;
17
+ this.releasePreparation = releasePreparation;
18
+ this.admissionExpired = admissionExpired;
19
+ }
20
+ async acquire(dispatch, signal) {
21
+ const id = dispatch.sandbox.dispatchAttemptId;
22
+ if (this.preparations.has(id))
23
+ throw new Error("host_runtime_preparation_conflict: duplicate preparation.");
24
+ const controller = new AbortController();
25
+ const abort = () => this.cancel(id, dispatch.lease.fencingToken);
26
+ const entry = { dispatch, controller, phase: "preparing", expiresAt: dispatch.lease.expiresAt,
27
+ removeAbort: () => signal?.removeEventListener("abort", abort) };
28
+ this.preparations.set(id, entry);
29
+ this.scheduleDeadline(entry);
30
+ signal?.addEventListener("abort", abort, { once: true });
31
+ if (signal?.aborted)
32
+ abort();
33
+ try {
34
+ // Preparation consumes normal capacity, but no project-runtime claim.
35
+ return await this.runtime.acquire({ ...dispatch,
36
+ runtimeIntent: { ...dispatch.runtimeIntent, executionClass: "analysis_only", applicationRuntimeRequired: false },
37
+ }, controller.signal);
38
+ }
39
+ catch (error) {
40
+ const failure = controller.signal.aborted ? controller.signal.reason : error;
41
+ this.cancel(id, dispatch.lease.fencingToken);
42
+ throw failure;
43
+ }
44
+ }
45
+ has(id) { return this.preparations.has(id); }
46
+ hasPending() { return this.preparations.size > 0; }
47
+ pendingSnapshots() {
48
+ return [...this.preparations.values()].map(entry => ({
49
+ repoId: entry.dispatch.repo.id,
50
+ dispatchAttemptId: entry.dispatch.sandbox.dispatchAttemptId,
51
+ fencingToken: entry.dispatch.lease.fencingToken,
52
+ ...(entry.probe
53
+ ? {
54
+ probeDispatchAttemptId: entry.probe.sandbox.dispatchAttemptId,
55
+ probeFencingToken: entry.probe.lease.fencingToken,
56
+ }
57
+ : {}),
58
+ }));
59
+ }
60
+ async verify(dispatch, worktree, checkpoint) {
61
+ const id = dispatch.sandbox.dispatchAttemptId;
62
+ const entry = this.preparations.get(id);
63
+ if (!entry || entry.dispatch.lease.fencingToken !== dispatch.lease.fencingToken) {
64
+ throw new Error("host_runtime_preparation_missing: preparation ownership changed.");
65
+ }
66
+ // Release preparation headroom before waiting for peers; otherwise a one-slot
67
+ // host would deadlock while the rest of the wave tries to prepare.
68
+ await this.releasePreparation(id, dispatch.lease.fencingToken);
69
+ entry.controller.signal.throwIfAborted();
70
+ const completion = new Promise((resolve, reject) => {
71
+ entry.resolve = resolve;
72
+ entry.reject = reject;
73
+ });
74
+ entry.check = () => this.check(entry, worktree, checkpoint);
75
+ entry.phase = "queued";
76
+ void this.drain(dispatch.repo.id);
77
+ return await completion;
78
+ }
79
+ async renew(id, fence, expiresAt) {
80
+ const entry = this.preparations.get(id);
81
+ if (!entry || entry.dispatch.lease.fencingToken !== fence || Date.parse(expiresAt) <= Date.parse(entry.expiresAt))
82
+ return;
83
+ entry.expiresAt = expiresAt;
84
+ this.scheduleDeadline(entry);
85
+ if (entry.probe)
86
+ await this.runtime.updateLease(entry.probe.sandbox.dispatchAttemptId, entry.probe.lease.fencingToken, expiresAt);
87
+ }
88
+ cancel(id, fence, reason = new Error("host_runtime_preparation_cancelled: prepared readiness was cancelled.")) {
89
+ const entry = this.preparations.get(id);
90
+ if (!entry || entry.dispatch.lease.fencingToken !== fence)
91
+ return;
92
+ if (entry.deadline)
93
+ clearTimeout(entry.deadline);
94
+ entry.controller.abort(reason);
95
+ // Do not return to session teardown while a supervised probe still owns the worktree.
96
+ if (entry.phase === "checking")
97
+ return;
98
+ entry.reject?.(entry.controller.signal.reason);
99
+ entry.removeAbort();
100
+ this.preparations.delete(id);
101
+ void this.drain(entry.dispatch.repo.id);
102
+ }
103
+ async drain(repoId) {
104
+ if (this.draining.has(repoId))
105
+ return;
106
+ const entries = () => [...this.preparations.values()].filter(entry => entry.dispatch.repo.id === repoId);
107
+ if (entries().some(entry => entry.phase === "preparing"))
108
+ return;
109
+ this.draining.add(repoId);
110
+ const completed = [];
111
+ try {
112
+ for (const entry of entries()) {
113
+ if (entry.phase !== "queued")
114
+ continue;
115
+ entry.phase = "checking";
116
+ try {
117
+ completed.push({ entry, identity: await entry.check() });
118
+ }
119
+ catch (error) {
120
+ completed.push({ entry, error });
121
+ }
122
+ }
123
+ // No provider from this wave can start while a sibling proof is running.
124
+ for (const result of completed) {
125
+ const { entry } = result;
126
+ this.preparations.delete(entry.dispatch.sandbox.dispatchAttemptId);
127
+ if (entry.deadline)
128
+ clearTimeout(entry.deadline);
129
+ entry.removeAbort();
130
+ if (entry.controller.signal.aborted)
131
+ entry.reject?.(entry.controller.signal.reason);
132
+ else if (result.error)
133
+ entry.reject?.(result.error);
134
+ else
135
+ entry.resolve?.(result.identity);
136
+ }
137
+ }
138
+ finally {
139
+ this.draining.delete(repoId);
140
+ if (entries().some(entry => entry.phase === "queued"))
141
+ void this.drain(repoId);
142
+ }
143
+ }
144
+ scheduleDeadline(entry) {
145
+ if (entry.deadline)
146
+ clearTimeout(entry.deadline);
147
+ const delay = Date.parse(entry.expiresAt) - Date.now();
148
+ entry.deadline = setTimeout(() => this.cancel(entry.dispatch.sandbox.dispatchAttemptId, entry.dispatch.lease.fencingToken, this.admissionExpired()), Number.isFinite(delay) ? Math.max(0, Math.min(delay, 2_147_483_647)) : 0);
149
+ entry.deadline.unref();
150
+ }
151
+ async check(entry, worktree, checkpoint) {
152
+ const { dispatch, controller } = entry;
153
+ if (!dispatch.runtimeIntent.applicationRuntimeRequired)
154
+ return undefined;
155
+ const contract = await loadHostRuntimeContract(worktree);
156
+ if (!hostRuntimeParallelEligible(contract))
157
+ return undefined;
158
+ const preparedDiagnostics = { entries: new Map() };
159
+ const identity = await preparedRuntimeIdentity(worktree, controller.signal, preparedDiagnostics);
160
+ if (hostRuntimeContractFingerprint(contract) !== identity.runtimeContractFingerprint) {
161
+ throw new Error("host_runtime_prepared_source_changed: runtime contract changed while capturing its source identity.");
162
+ }
163
+ if (await this.store.load(dispatch.repo.id, identity))
164
+ return identity;
165
+ await checkpoint?.({ code: "host_runtime_prepared_probe_started", expiresAt: entry.expiresAt,
166
+ message: `Verifying prepared runtime ${identity.inputCommitSha.slice(0, 12)} before agent admission; project-default readiness is not a substitute.` });
167
+ const probeId = randomUUID();
168
+ const probe = { ...dispatch,
169
+ cycleRun: { ...dispatch.cycleRun, phase: "prepared_readiness" },
170
+ lease: { ...dispatch.lease, id: probeId, fencingToken: randomUUID(), expiresAt: entry.expiresAt },
171
+ sandbox: { ...dispatch.sandbox, dispatchAttemptId: probeId, executionLeaseId: probeId,
172
+ inputCommitSha: identity.inputCommitSha },
173
+ };
174
+ entry.probe = probe;
175
+ const stopPreparedHeadMonitor = new AbortController();
176
+ const preparedHeadMonitor = monitorPreparedHead(worktree, identity.inputCommitSha, controller, stopPreparedHeadMonitor.signal);
177
+ let cleanupConfirmed;
178
+ let verifiedRuntimeContractFingerprint;
179
+ let verifiedPorts;
180
+ try {
181
+ controller.signal.throwIfAborted();
182
+ await this.runtime.acquire(probe, controller.signal);
183
+ const prepared = await this.runtime.start(probe, worktree, controller.signal);
184
+ if (hostRuntimeContractFingerprint(prepared.runtimeContract) !== identity.runtimeContractFingerprint) {
185
+ throw new Error("host_runtime_prepared_source_changed: probe loaded a different runtime contract; application was not started.");
186
+ }
187
+ const started = await this.runtime.startConfiguredProject(probeId, probe.lease.fencingToken, controller.signal, progress => checkpoint?.({ code: "host_runtime_prepared_probe_progress", expiresAt: entry.expiresAt,
188
+ message: progress.message }));
189
+ verifiedRuntimeContractFingerprint = hostRuntimeContractFingerprint(started.runtimeContract);
190
+ verifiedPorts = started.lease.resources.ports.map(port => port.name).sort();
191
+ }
192
+ finally {
193
+ stopPreparedHeadMonitor.abort();
194
+ await preparedHeadMonitor;
195
+ // A failed teardown must not publish reusable evidence.
196
+ cleanupConfirmed = Boolean(await this.runtime.release(probeId, probe.lease.fencingToken));
197
+ entry.probe = undefined;
198
+ }
199
+ if (!cleanupConfirmed) {
200
+ throw new Error("host_runtime_prepared_probe_cleanup_unconfirmed: matching probe teardown was not confirmed.");
201
+ }
202
+ // Probe-owned processes may create transient, untracked files while they
203
+ // are alive. Verify the prepared source only after matching teardown is
204
+ // confirmed: persistent source edits still fail closed, while files that
205
+ // belong to the probe lifecycle cannot create a false source-change loop.
206
+ const currentDiagnostics = { entries: new Map() };
207
+ const currentIdentity = await preparedRuntimeIdentity(worktree, controller.signal, currentDiagnostics);
208
+ const changed = [];
209
+ if (verifiedRuntimeContractFingerprint !== identity.runtimeContractFingerprint
210
+ || currentIdentity.runtimeContractFingerprint !== identity.runtimeContractFingerprint) {
211
+ changed.push("runtime contract");
212
+ }
213
+ if (currentIdentity.inputCommitSha !== identity.inputCommitSha)
214
+ changed.push("HEAD");
215
+ if (currentIdentity.sourceFingerprint !== identity.sourceFingerprint) {
216
+ const paths = changedIdentityPaths(preparedDiagnostics.entries, currentDiagnostics.entries);
217
+ changed.push(paths.length > 0
218
+ ? `source fingerprint (${paths.join(", ")})`
219
+ : "source fingerprint");
220
+ }
221
+ if (changed.length > 0) {
222
+ throw new Error(`host_runtime_prepared_source_changed: ${changed.join(", ")} changed during isolation verification.`);
223
+ }
224
+ if (JSON.stringify(verifiedPorts) !== JSON.stringify(configuredLaunchPortNames(contract))) {
225
+ throw new Error("host_runtime_prepared_probe_incomplete: assigned-port verification did not confirm every configured launch port.");
226
+ }
227
+ controller.signal.throwIfAborted();
228
+ await this.store.observe(dispatch.repo.id, contract, probeId, configuredLaunchPortNames(contract), identity.inputCommitSha, identity.sourceFingerprint);
229
+ await checkpoint?.({ code: "host_runtime_prepared_probe_completed", expiresAt: entry.expiresAt,
230
+ message: `Prepared runtime ${identity.inputCommitSha.slice(0, 12)} passed isolation verification; its source-bound proof is retained independently.` });
231
+ return identity;
232
+ }
233
+ }
234
+ const preparedHeadPollIntervalMs = 1_000;
235
+ async function monitorPreparedHead(worktree, expectedCommitSha, preparationController, stopSignal) {
236
+ const git = new GitClient();
237
+ while (!stopSignal.aborted && !preparationController.signal.aborted) {
238
+ try {
239
+ const currentCommitSha = (await git.run(worktree, ["rev-parse", "--verify", "HEAD^{commit}"]))
240
+ .trim()
241
+ .toLowerCase();
242
+ if (currentCommitSha !== expectedCommitSha.toLowerCase()) {
243
+ throw new Error("host_runtime_prepared_source_changed: HEAD changed during isolation verification; the obsolete probe was cancelled.");
244
+ }
245
+ }
246
+ catch (error) {
247
+ if (!stopSignal.aborted && !preparationController.signal.aborted) {
248
+ const failure = error instanceof Error && error.message.startsWith("host_runtime_prepared_source_changed:")
249
+ ? error
250
+ : new Error(`host_runtime_prepared_source_changed: HEAD could not be revalidated during isolation verification: ${errorMessage(error)}`);
251
+ preparationController.abort(failure);
252
+ }
253
+ return;
254
+ }
255
+ await waitForPreparedHeadPoll(stopSignal);
256
+ }
257
+ }
258
+ async function waitForPreparedHeadPoll(signal) {
259
+ if (signal.aborted)
260
+ return;
261
+ await new Promise(resolve => {
262
+ const complete = () => {
263
+ clearTimeout(timer);
264
+ signal.removeEventListener("abort", complete);
265
+ resolve();
266
+ };
267
+ const timer = setTimeout(complete, preparedHeadPollIntervalMs);
268
+ timer.unref();
269
+ signal.addEventListener("abort", complete, { once: true });
270
+ if (signal.aborted)
271
+ complete();
272
+ });
273
+ }
274
+ function errorMessage(error) {
275
+ return error instanceof Error ? error.message : String(error);
276
+ }
277
+ function changedIdentityPaths(before, after) {
278
+ const paths = new Set([...before.keys(), ...after.keys()]);
279
+ const changed = [...paths]
280
+ .filter(path => before.get(path) !== after.get(path))
281
+ .sort((left, right) => left.localeCompare(right));
282
+ if (changed.length <= 8)
283
+ return changed;
284
+ return [...changed.slice(0, 8), `+${changed.length - 8} more`];
285
+ }
@@ -57,7 +57,10 @@ export function transitionRuntimeIsolationLease(lease, nextState, occurredAt = n
57
57
  return transitioned;
58
58
  }
59
59
  export function renewRuntimeIsolationLease(lease, fencingToken, expiresAt) {
60
- if (lease.fencingToken !== fencingToken || lease.state === "released" || !validTimestamp(expiresAt))
60
+ if (lease.fencingToken !== fencingToken
61
+ || lease.state === "releasing"
62
+ || lease.state === "released"
63
+ || !validTimestamp(expiresAt))
61
64
  return null;
62
65
  const renewed = { ...lease, expiresAt };
63
66
  return validRuntimeIsolationLease(renewed) ? renewed : null;
@@ -0,0 +1,17 @@
1
+ export declare const minimumWorkspaceEstimateBytes: number;
2
+ export declare const architectMinimumWorkspaceEstimateBytes: number;
3
+ export interface RepositoryWorkspaceFootprint {
4
+ readonly sourceBytes: number;
5
+ readonly hasNode: boolean;
6
+ readonly hasDotNet: boolean;
7
+ readonly hasBrowser: boolean;
8
+ readonly serviceCount: number;
9
+ }
10
+ export interface WorkspaceEstimateHints {
11
+ readonly role?: string | null;
12
+ readonly serviceCount?: number;
13
+ readonly browser?: boolean;
14
+ }
15
+ export declare function estimateWorkspaceBytesFromRepo(repoPath: string, hints?: WorkspaceEstimateHints): Promise<number>;
16
+ export declare function calculateWorkspaceBytes(footprint: RepositoryWorkspaceFootprint, role?: string | null): number;
17
+ export declare function measureRepositoryWorkspace(repoPath: string): Promise<RepositoryWorkspaceFootprint>;