@loucompanion/forge-bridge 0.1.4-dev.e847c8c66ea9 → 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.
@@ -16,7 +16,6 @@ import { hostPortEnvironment, loadHostRuntimeContract, newAttemptApiMasterKey, w
16
16
  import { HostPortBroker, } from "./host-port-broker.js";
17
17
  import { NodeHostRuntimeAdapter, } from "./node-host-runtime-adapter.js";
18
18
  import { AttemptProcessSupervisorRegistry } from "./attempt-process-supervisor-registry.js";
19
- import { terminateAttemptManagedCommands } from "./managed-command-teardown.js";
20
19
  import { attemptDatabaseCapabilityEnvironment, attemptDatabaseCapabilitySecrets, } from "./attempt-database-broker.js";
21
20
  import { AttemptNodeRuntimeLauncher } from "./attempt-node-runtime-launcher.js";
22
21
  import { HostListenerInspector } from "./host-listener-inspector.js";
@@ -26,17 +25,15 @@ import { HostParallelPromotionStore, configuredLaunchPortNames, hostRuntimeContr
26
25
  import { ExactHostProcessRecovery, } from "../shared/process/host-process-recovery.js";
27
26
  import { resetGeneratedOutputs } from "./generated-output-reset.js";
28
27
  import { assertCanonicalDirectory, createCanonicalDirectory } from "./attempt-private-directory.js";
29
- import { readCanonicalSourceFile } from "./canonical-source-file.js";
30
- import { readPinnedSourceDirectory } from "./pinned-source-directory.js";
28
+ import { logHostRuntimeStatus, recoverPersistedHostProcesses, replaceHostRuntimeLedgerFile, retryDegradedHostRelease, } from "./host-runtime-ledger-recovery.js";
31
29
  import { architectMinimumWorkspaceEstimateBytes } from "./workspace-resource-estimator.js";
32
- import { createAspNetRuntimePrebuildPlan, ensureAspNetRuntimePrebuilt, executeAspNetRuntimeBuild, resolveWorktreeCommitSha, } from "./aspnet-runtime-prebuild.js";
30
+ import { createAspNetRuntimePrebuildPlan, ensureAspNetRuntimePrebuilt, executeAspNetRuntimeBuild, resolveWorktreeCommitSha, supervisedRuntimeLaunchArguments, } from "./aspnet-runtime-prebuild.js";
33
31
  import { HostLoadGovernor } from "./host-load-governor.js";
34
32
  import { hostLoadChildEnvironment } from "./host-load-child-environment.js";
35
33
  import { aspNetPrebuildStepClass } from "./host-load-step-class.js";
36
34
  import { attachSupervisedStepProcess, runHostGovernedStep } from "./host-load-step-run.js";
37
35
  import { HostLoadSampler } from "./host-load-sampler.js";
38
36
  const hostCapacityWaiterScanLimit = 64;
39
- const maximumProcessRecoveryMetadataBytes = 1024 * 1024;
40
37
  export class HostRuntimeLeaseManager {
41
38
  stateRoot;
42
39
  processSupervisors;
@@ -162,19 +159,16 @@ export class HostRuntimeLeaseManager {
162
159
  }
163
160
  const active = this.active.get(lease.dispatchAttemptId);
164
161
  if (active) {
162
+ // A live lease is never released here, however long past its expiry; a degraded one
163
+ // is retried under its own fence until teardown proves its process tree stopped.
165
164
  if (active.lease.state !== "degraded")
166
165
  continue;
167
166
  report.examined += 1;
168
- try {
169
- const released = await this.release(lease.dispatchAttemptId, lease.fencingToken);
170
- if (released?.state === "released")
171
- report.reaped += 1;
172
- else
173
- report.degraded += 1;
174
- }
175
- catch {
167
+ const released = await retryDegradedHostRelease(active.lease, () => this.release(lease.dispatchAttemptId, lease.fencingToken), options.log ?? logHostRuntimeStatus);
168
+ if (released)
169
+ report.reaped += 1;
170
+ else
176
171
  report.degraded += 1;
177
- }
178
172
  continue;
179
173
  }
180
174
  const staleInstance = lease.runnerInstanceId !== options.runnerInstanceId;
@@ -189,18 +183,16 @@ export class HostRuntimeLeaseManager {
189
183
  if (!attemptRootIdentity) {
190
184
  throw new Error("host_runtime_reaper_invalid: original attempt-root identity is unavailable.");
191
185
  }
192
- outcomes = await this.recoverPersistedProcesses(lease, attemptRoot, attemptRootIdentity);
186
+ outcomes = await recoverPersistedHostProcesses(lease, attemptRoot, this.attemptRoot(lease.dispatchAttemptId), attemptRootIdentity, this.processRecovery);
193
187
  }
194
188
  catch {
195
- await this.markLedgerDegraded(ledger);
196
- report.degraded += 1;
189
+ await this.markLedgerDegraded(ledger, report);
197
190
  continue;
198
191
  }
199
192
  report.processesTerminated += outcomes.filter(outcome => outcome === "terminated").length;
200
193
  report.reusedPidsProtected += outcomes.filter(outcome => outcome === "pid_reused").length;
201
194
  if (outcomes.includes("unverifiable")) {
202
- await this.markLedgerDegraded(ledger);
203
- report.degraded += 1;
195
+ await this.markLedgerDegraded(ledger, report);
204
196
  continue;
205
197
  }
206
198
  // The runtime has already been released. Keep the over-budget original
@@ -247,8 +239,7 @@ export class HostRuntimeLeaseManager {
247
239
  report.reaped += 1;
248
240
  }
249
241
  catch {
250
- await this.markLedgerDegraded(ledger);
251
- report.degraded += 1;
242
+ await this.markLedgerDegraded(ledger, report);
252
243
  }
253
244
  }
254
245
  // Databases issued to attempts that ended without a clean release (a Bridge crash, or a
@@ -1286,7 +1277,7 @@ export class HostRuntimeLeaseManager {
1286
1277
  };
1287
1278
  const prebuild = createAspNetRuntimePrebuildPlan({
1288
1279
  command: configuredPort.launch.command,
1289
- args: configuredPort.launch.args,
1280
+ args: supervisedRuntimeLaunchArguments(configuredPort),
1290
1281
  cwd: workingDirectory,
1291
1282
  worktreePath: active.lease.worktreePath,
1292
1283
  environment: buildEnvironment,
@@ -1297,7 +1288,7 @@ export class HostRuntimeLeaseManager {
1297
1288
  await onProjectCheckpoint?.({
1298
1289
  code: "host_runtime_build_started",
1299
1290
  message: `Preparing the ASP.NET runtime for commit ${active.inputCommitSha.slice(0, 12)} before binding its assigned port.`,
1300
- data: { input_commit_sha: active.inputCommitSha, project_path: prebuild.projectPath },
1291
+ data: { input_commit_sha: active.inputCommitSha, project_path: prebuild.projectPath, output_directory: prebuild.outputDirectory },
1301
1292
  });
1302
1293
  let hostLoadWaitMs = null;
1303
1294
  const build = await ensureAspNetRuntimePrebuilt(prebuild,
@@ -1337,7 +1328,7 @@ export class HostRuntimeLeaseManager {
1337
1328
  }
1338
1329
  await this.launchNodeRuntime(dispatchAttemptId, fencingToken, configuredPort.name, {
1339
1330
  command: configuredPort.launch.command,
1340
- args: configuredPort.launch.args,
1331
+ args: supervisedRuntimeLaunchArguments(configuredPort),
1341
1332
  cwd: workingDirectory,
1342
1333
  environment: withAttemptApiMasterKey(configuredPort, buildEnvironment, apiMasterKey),
1343
1334
  }, launcher, signal);
@@ -1632,10 +1623,14 @@ export class HostRuntimeLeaseManager {
1632
1623
  await restart.promise.catch(() => undefined);
1633
1624
  }
1634
1625
  await active.databaseProvision?.catch(() => undefined);
1635
- let releasing = transitionRuntimeIsolationLease(active.lease, "releasing");
1636
- active.lease = releasing;
1637
- await this.writeLedger(releasing);
1626
+ // The releasing write is part of the fenced teardown: when it fails (Windows can refuse
1627
+ // to replace a ledger another handle is reading), the lease must end degraded so
1628
+ // maintenance retries it, never left nonterminal in memory where nothing retries it.
1629
+ let releasing = active.lease;
1638
1630
  try {
1631
+ releasing = transitionRuntimeIsolationLease(active.lease, "releasing");
1632
+ active.lease = releasing;
1633
+ await this.writeLedger(releasing);
1639
1634
  if (!active.runtimeResourcesReleased) {
1640
1635
  await active.processSupervisor.stopAll(fencingToken, "Host runtime lease released.");
1641
1636
  // The attempt's MCP servers and process trees are stopped now; tokens they held
@@ -1691,13 +1686,12 @@ export class HostRuntimeLeaseManager {
1691
1686
  if (!evidenceRetainedAtAttemptRoot) {
1692
1687
  await fs.rm(this.ledgerPath(dispatchAttemptId), { force: true });
1693
1688
  }
1694
- releasing = released;
1695
1689
  this.active.delete(dispatchAttemptId);
1696
1690
  this.processSupervisors.unregister(dispatchAttemptId, fencingToken);
1697
1691
  this.releaseSingletonKeys(dispatchAttemptId, fencingToken);
1698
1692
  this.releaseParallelProjects(dispatchAttemptId, fencingToken);
1699
1693
  this.deleteAdmission(dispatchAttemptId, fencingToken);
1700
- return releasing;
1694
+ return released;
1701
1695
  }
1702
1696
  catch (error) {
1703
1697
  const degraded = transitionRuntimeIsolationLease(releasing, "degraded");
@@ -1732,66 +1726,12 @@ export class HostRuntimeLeaseManager {
1732
1726
  }
1733
1727
  return ledgers;
1734
1728
  }
1735
- async recoverPersistedProcesses(lease, attemptRoot, attemptRootIdentity) {
1736
- const logsRoot = path.join(attemptRoot, "logs");
1737
- const expectedAttemptRoot = path.resolve(this.attemptRoot(lease.dispatchAttemptId));
1738
- if (path.resolve(attemptRoot) !== expectedAttemptRoot) {
1739
- throw new Error("host_runtime_reaper_invalid: attempt path is outside the fenced attempt root.");
1740
- }
1741
- await assertHostAttemptRootIdentity(attemptRoot, attemptRootIdentity);
1742
- const rootEntries = await readPinnedSourceDirectory(attemptRoot, attemptRootIdentity);
1743
- const logsEntry = rootEntries.find(entry => entry.name === "logs");
1744
- if (!logsEntry)
1745
- return [];
1746
- if (logsEntry.kind !== "directory") {
1747
- throw new Error("host_runtime_reaper_invalid: process ownership log path is not an ordinary directory.");
1748
- }
1749
- const outcomes = [];
1750
- const failures = [];
1751
- try {
1752
- const entries = await readPinnedSourceDirectory(logsRoot, logsEntry.identity);
1753
- for (const entry of entries) {
1754
- if (entry.kind !== "file" || !/^process-supervisor\.[a-z][a-z0-9_-]{0,31}\.\d+\.json$/u.test(entry.name))
1755
- continue;
1756
- const metadataPath = path.join(logsRoot, entry.name);
1757
- const value = JSON.parse((await readCanonicalSourceFile(metadataPath, maximumProcessRecoveryMetadataBytes, entry.identity)).toString("utf8"));
1758
- if (!validHostProcessSupervisorMetadata(value, lease)) {
1759
- throw new Error("host_runtime_reaper_invalid: process ownership metadata did not match the runtime lease.");
1760
- }
1761
- outcomes.push(await this.processRecovery.recover(value));
1762
- }
1763
- }
1764
- catch (error) {
1765
- failures.push(error);
1766
- }
1767
- // Managed commands run in their own process groups and record their ownership apart
1768
- // from the attempt's supervised children. They are recovered even when recovering a
1769
- // supervised child failed, and both failures are reported together.
1770
- try {
1771
- const managed = await terminateAttemptManagedCommands({
1772
- logDirectory: logsRoot,
1773
- dispatchAttemptId: lease.dispatchAttemptId,
1774
- runtimeLeaseId: lease.executionLeaseId,
1775
- pinnedLogDirectory: logsEntry.identity,
1776
- }, { reason: "attempt_teardown" });
1777
- for (const command of managed) {
1778
- if (command.outcome === "terminated" || command.outcome === "pid_reused")
1779
- outcomes.push(command.outcome);
1780
- }
1781
- }
1782
- catch (error) {
1783
- failures.push(error);
1784
- }
1785
- if (failures.length === 1)
1786
- throw failures[0];
1787
- if (failures.length > 1)
1788
- throw new AggregateError(failures, "host_runtime_reaper_recovery_failed");
1789
- return outcomes;
1790
- }
1791
- async markLedgerDegraded(ledger) {
1729
+ /** Degrades and counts a ledger whose runtime may still be live. A retained released ledger owns no slot, so it is neither changed nor counted. */
1730
+ async markLedgerDegraded(ledger, report) {
1792
1731
  const lease = ledger.runtimeLease;
1793
1732
  if (lease.state === "released")
1794
1733
  return;
1734
+ report.degraded += 1;
1795
1735
  const degraded = transitionHostLeaseForCleanup(lease, "degraded");
1796
1736
  const repoId = ledger.repoId ?? repoIdFromProjectSingletonKeys(lease.resources.singletonKeys);
1797
1737
  this.rememberDegraded(degraded, repoId);
@@ -1860,7 +1800,7 @@ export class HostRuntimeLeaseManager {
1860
1800
  finally {
1861
1801
  await handle.close();
1862
1802
  }
1863
- await fs.rename(temporary, target);
1803
+ await replaceHostRuntimeLedgerFile(temporary, target);
1864
1804
  }
1865
1805
  catch (error) {
1866
1806
  await fs.rm(temporary, { force: true }).catch(() => undefined);
@@ -2685,30 +2625,6 @@ function deserializeHostAttemptRootIdentity(identity) {
2685
2625
  ? { dev: BigInt(identity.dev), ino: BigInt(identity.ino) }
2686
2626
  : null;
2687
2627
  }
2688
- function validHostProcessSupervisorMetadata(value, lease) {
2689
- if (typeof value !== "object" || value === null)
2690
- return false;
2691
- const metadata = value;
2692
- return metadata.schemaVersion === 1
2693
- && /^host-[0-9a-f]{32}$/u.test(metadata.supervisorId)
2694
- && (metadata.strategy === "windows_job_object" || metadata.strategy === "unix_process_group")
2695
- && Number.isSafeInteger(metadata.rootPid)
2696
- && metadata.rootPid > 0
2697
- && Number.isFinite(Date.parse(metadata.rootCreatedAt))
2698
- && (metadata.rootIdentity == null
2699
- || (typeof metadata.rootIdentity === "string" && metadata.rootIdentity.length <= 256))
2700
- && /^[0-9a-f]{64}$/u.test(metadata.commandDigest)
2701
- && containedMetadataWorktreePath(lease.worktreePath, metadata.worktreePath)
2702
- && metadata.runtimeLeaseId === lease.executionLeaseId
2703
- && metadata.dispatchAttemptId === lease.dispatchAttemptId
2704
- && metadata.fencingToken === lease.fencingToken
2705
- && Number.isSafeInteger(metadata.bridgePid)
2706
- && metadata.bridgePid > 0;
2707
- }
2708
- function containedMetadataWorktreePath(worktreePath, metadataWorktreePath) {
2709
- const relative = path.relative(path.resolve(worktreePath), path.resolve(metadataWorktreePath));
2710
- return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
2711
- }
2712
2628
  function transitionHostLeaseForCleanup(lease, state) {
2713
2629
  if (lease.state === state || lease.state === "released")
2714
2630
  return lease;
@@ -0,0 +1,20 @@
1
+ import type { HostProcessRecovery, HostProcessRecoveryOutcome } from "../shared/process/host-process-recovery.js";
2
+ import type { PinnedDirectoryIdentity } from "./pinned-directory-process.js";
3
+ import type { RuntimeIsolationLease } from "./runtime-isolation-lease.js";
4
+ /**
5
+ * Replaces a host runtime ledger with its fully written temporary file. Windows refuses
6
+ * to replace a file another handle has open (EPERM), for example while a recovery pass
7
+ * reads the same ledger, so a transient refusal is retried for about a second, as the
8
+ * attempt supervisor does for its own ledger.
9
+ */
10
+ export declare function replaceHostRuntimeLedgerFile(temporary: string, target: string, retryMs?: number): Promise<void>;
11
+ /**
12
+ * Maintenance retry of a degraded lease's fenced release. The release frees the slot only
13
+ * after its teardown proves the attempt's supervised process tree stopped (the supervisor
14
+ * is stopped with no live child or managed command); otherwise the lease stays degraded
15
+ * and the log says why. Returns whether the lease was released.
16
+ */
17
+ export declare function retryDegradedHostRelease(lease: RuntimeIsolationLease, release: () => Promise<RuntimeIsolationLease | null>, log: (message: string) => void): Promise<boolean>;
18
+ export declare function logHostRuntimeStatus(message: string): void;
19
+ /** Exact, fenced recovery of the process trees a lease's attempt recorded under its attempt root. */
20
+ export declare function recoverPersistedHostProcesses(lease: RuntimeIsolationLease, attemptRoot: string, expectedAttemptRoot: string, attemptRootIdentity: PinnedDirectoryIdentity, processRecovery: HostProcessRecovery): Promise<readonly HostProcessRecoveryOutcome[]>;
@@ -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
+ }
@@ -0,0 +1,45 @@
1
+ import { type DotnetPathPlatform, type DotnetProjectFiles } from "./dotnet-build-outputs.js";
2
+ /** What a supervised project runtime runs, recorded in the attempt log directory at launch. */
3
+ export interface SupervisedRuntimeDescriptor {
4
+ readonly schemaVersion: 1;
5
+ /** The runtime contract's port name, for example `api`. */
6
+ readonly role: string;
7
+ /** The attempt supervisor child, for example `project-api`. */
8
+ readonly childName: string;
9
+ readonly command: string;
10
+ readonly args: readonly string[];
11
+ readonly cwd: string;
12
+ }
13
+ export interface SupervisedRuntimeCollision {
14
+ readonly childName: string;
15
+ readonly role: string;
16
+ /** The runtime's supervised process (the `dotnet run` the supervisor started), when recorded. */
17
+ readonly pid: number | null;
18
+ readonly project: string;
19
+ readonly outputDirectory: string;
20
+ /** The running file the build would have to replace. */
21
+ readonly lockedPath: string;
22
+ }
23
+ export interface SupervisedRuntimeBuildCheck {
24
+ readonly command: string;
25
+ readonly args: readonly string[];
26
+ readonly cwd: string;
27
+ readonly worktreePath: string;
28
+ /** The attempt's FORGE_LOG_DIR, which holds the supervisor ledger and runtime descriptors. */
29
+ readonly logDirectory: string;
30
+ /** A runner-authored script that builds the worktree's solution (a managed verification tier). */
31
+ readonly buildsWorktreeSolution?: boolean;
32
+ readonly platform?: DotnetPathPlatform;
33
+ readonly files?: DotnetProjectFiles;
34
+ }
35
+ export declare function supervisedRuntimeDescriptorPath(logDirectory: string, childName: string): string;
36
+ export declare function writeSupervisedRuntimeDescriptor(logDirectory: string, descriptor: Omit<SupervisedRuntimeDescriptor, "schemaVersion">): Promise<void>;
37
+ /**
38
+ * Finds the first running supervised runtime of this attempt whose build output the command
39
+ * would write. Only the project graph and output directory decide a collision: a build of an
40
+ * unrelated project, into another output, or a test run without a build never matches.
41
+ */
42
+ export declare function findSupervisedRuntimeCollision(check: SupervisedRuntimeBuildCheck): Promise<SupervisedRuntimeCollision | null>;
43
+ export declare function supervisedRuntimeCollisionMessage(collision: SupervisedRuntimeCollision): string;
44
+ /** Fails fast, naming the runtime, instead of letting the build hit the runtime's locked files. */
45
+ export declare function assertBuildSparesSupervisedRuntimes(check: SupervisedRuntimeBuildCheck): Promise<void>;
@@ -0,0 +1,112 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import fs from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { replaceFile } from "../shared/fs/replace-file.js";
5
+ import { attemptProcessSupervisorLedgerPath } from "./attempt-process-supervisor.js";
6
+ import { canonicalExistingPath, fileSystemProjectFiles, findDotnetOutputCollisions, hostPathPlatform, isDotnetExecutable, parseDotnetOutputCommand, } from "./dotnet-build-outputs.js";
7
+ const activeChildStatuses = new Set(["starting", "running", "stopping"]);
8
+ export function supervisedRuntimeDescriptorPath(logDirectory, childName) {
9
+ return path.join(logDirectory, `${childName}.runtime.json`);
10
+ }
11
+ export async function writeSupervisedRuntimeDescriptor(logDirectory, descriptor) {
12
+ const target = supervisedRuntimeDescriptorPath(logDirectory, descriptor.childName);
13
+ const temporary = `${target}.${randomUUID()}.tmp`;
14
+ await fs.writeFile(temporary, `${JSON.stringify({ schemaVersion: 1, ...descriptor })}\n`, { encoding: "utf8", mode: 0o600 });
15
+ try {
16
+ await replaceFile(temporary, target);
17
+ }
18
+ finally {
19
+ await fs.rm(temporary, { force: true }).catch(() => undefined);
20
+ }
21
+ }
22
+ /**
23
+ * Finds the first running supervised runtime of this attempt whose build output the command
24
+ * would write. Only the project graph and output directory decide a collision: a build of an
25
+ * unrelated project, into another output, or a test run without a build never matches.
26
+ */
27
+ export async function findSupervisedRuntimeCollision(check) {
28
+ const platform = check.platform ?? hostPathPlatform();
29
+ const files = check.files ?? fileSystemProjectFiles;
30
+ const writer = await buildingCommand(check, platform);
31
+ if (!writer)
32
+ return null;
33
+ const ledger = await readJson(attemptProcessSupervisorLedgerPath(check.logDirectory));
34
+ for (const child of ledger?.children ?? []) {
35
+ if (!child.name.startsWith("project-") || !activeChildStatuses.has(child.status))
36
+ continue;
37
+ const descriptor = await readJson(supervisedRuntimeDescriptorPath(check.logDirectory, child.name));
38
+ if (descriptor?.schemaVersion !== 1 || !Array.isArray(descriptor.args))
39
+ continue;
40
+ const holder = parseDotnetOutputCommand(descriptor.command, descriptor.args, await canonicalPath(descriptor.cwd), { platform, holder: true });
41
+ if (!holder)
42
+ continue;
43
+ const [collision] = await findDotnetOutputCollisions(writer, holder, files, platform);
44
+ if (!collision)
45
+ continue;
46
+ const metadata = await readJson(child.metadataPath);
47
+ const pid = [metadata?.providerPid, metadata?.rootPid].find(value => Number.isSafeInteger(value) && value > 0);
48
+ // A default output's framework folder is the wildcard `*` until the project names it.
49
+ const framework = await projectTargetFramework(collision.project, files);
50
+ const outputDirectory = framework ? collision.outputDirectory.replace(/(?<=[\\/])\*(?=[\\/]|$)/u, framework) : collision.outputDirectory;
51
+ return {
52
+ childName: child.name,
53
+ role: descriptor.role,
54
+ pid: pid ?? null,
55
+ project: collision.project,
56
+ outputDirectory,
57
+ lockedPath: lockedOutputPath(collision.project, outputDirectory, await runtimeProject(holder, files), platform),
58
+ };
59
+ }
60
+ return null;
61
+ }
62
+ /** A single-targeted project's TargetFramework, which names the default output's framework folder. */
63
+ async function projectTargetFramework(project, files) {
64
+ const content = await files.read(project);
65
+ return content?.match(/<TargetFramework>\s*([^<;\s]+)\s*<\/TargetFramework>/u)?.[1]?.toLowerCase() ?? null;
66
+ }
67
+ async function buildingCommand(check, platform) {
68
+ const parsed = parseDotnetOutputCommand(check.command, check.args, await canonicalPath(check.cwd), { platform });
69
+ if (parsed || isDotnetExecutable(check.command, platform) || !check.buildsWorktreeSolution)
70
+ return parsed;
71
+ // The verification scripts build the worktree's solution with its default output.
72
+ return parseDotnetOutputCommand("dotnet", ["build"], await canonicalPath(check.worktreePath), { platform });
73
+ }
74
+ /** Both sides compare canonical paths: a junction, symlink, or 8.3 alias must not hide a collision. */
75
+ async function canonicalPath(directory) {
76
+ return await canonicalExistingPath(directory);
77
+ }
78
+ /** The project the runtime runs, at its real location like the collision's project. */
79
+ async function runtimeProject(holder, files) {
80
+ const target = holder.targets[0];
81
+ return target === undefined || !files.canonical ? target : await files.canonical(target);
82
+ }
83
+ /** The runtime's own executable when the colliding project is the one it runs, otherwise that project's assembly. */
84
+ function lockedOutputPath(project, outputDirectory, runtimeProject, platform) {
85
+ const p = platform === "win32" ? path.win32 : path.posix;
86
+ const name = p.basename(project).replace(/\.(?:cs|fs|vb)proj$/iu, "");
87
+ const isRuntimeProject = runtimeProject !== undefined
88
+ && (platform === "win32" ? runtimeProject.toLowerCase() === project.toLowerCase() : runtimeProject === project);
89
+ const fileName = isRuntimeProject ? `${name}${platform === "win32" ? ".exe" : ""}` : `${name}.dll`;
90
+ return p.join(outputDirectory, fileName);
91
+ }
92
+ export function supervisedRuntimeCollisionMessage(collision) {
93
+ return `managed_command_runtime_output_collision: this command would build ${collision.project} into ${collision.outputDirectory}, `
94
+ + `the output the attempt's running supervised runtime ${collision.childName} (role ${collision.role}, PID ${collision.pid ?? "unknown"}) `
95
+ + `executes from; ${collision.lockedPath} is in use. Forge refused it before launch, because the build would fail on the locked file `
96
+ + "(MSB3027 on Windows) or replace files under the running runtime. Build into a different output directory: the runtime runs from its "
97
+ + "own output, so the project's default output is free. Forge rebuilds and restarts the runtime from the current source when validation needs it.";
98
+ }
99
+ /** Fails fast, naming the runtime, instead of letting the build hit the runtime's locked files. */
100
+ export async function assertBuildSparesSupervisedRuntimes(check) {
101
+ const collision = await findSupervisedRuntimeCollision(check);
102
+ if (collision)
103
+ throw new Error(supervisedRuntimeCollisionMessage(collision));
104
+ }
105
+ async function readJson(file) {
106
+ try {
107
+ return JSON.parse(await fs.readFile(file, "utf8"));
108
+ }
109
+ catch {
110
+ return null;
111
+ }
112
+ }
@@ -8,7 +8,7 @@ import { assertHostDatabaseCapabilityBoundary } from "../runtime/host-database-c
8
8
  import { managedVerificationDatabase, noManagedVerificationDatabase, releaseManagedVerificationDatabase, setUpWithManagedVerificationDatabase } from "../runtime/ephemeral-test-postgres-grant.js";
9
9
  import { redactText } from "../shared/redaction/redaction.js";
10
10
  import { emptyToolInputHint, isEmptyToolInput } from "./mcp-argument-coercion.js";
11
- import { ManagedBuildCoordinator } from "./managed-build-coordinator.js";
11
+ import { assertManagedBuildSparesSupervisedRuntimes, ManagedBuildCoordinator } from "./managed-build-coordinator.js";
12
12
  import { attachManagedCommandProcess, ManagedCommandHostCapacity, } from "./managed-command-host-load.js";
13
13
  import { HostCapacityLedgerUnavailableError } from "../runtime/host-load-ledger-lock.js";
14
14
  import { isProcessTreeTerminationUnproven } from "../shared/process/process.js";
@@ -292,6 +292,9 @@ async function launchManagedCommand(record, worktreePath, forceAsync, verificati
292
292
  buildReceiptReuse,
293
293
  controller: new AbortController(),
294
294
  };
295
+ // A build aimed at the output a running supervised runtime executes from fails here, naming
296
+ // that runtime, instead of failing on its locked files after the build-slot and capacity waits.
297
+ await assertManagedBuildSparesSupervisedRuntimes(invocation);
295
298
  if (forceAsync || timeoutMs > maximumSynchronousWaitMs) {
296
299
  const started = managedCommandResult({
297
300
  ...invocation,
@@ -1117,10 +1120,7 @@ export function isBuildProducingManagedCommand(command, args) {
1117
1120
  if (["powershell", "powershell.exe", "pwsh", "pwsh.exe"].includes(executable)) {
1118
1121
  const fileIndex = args.findIndex(argument => argument.toLowerCase() === "-file");
1119
1122
  const script = fileIndex >= 0 ? path.basename(args[fileIndex + 1] ?? "").toLowerCase() : "";
1120
- if (script === "run-dotnet-test-tier-set.ps1" || script === "run-dotnet-test-suite.ps1") {
1121
- return !args.some(argument => argument.toLowerCase() === "-nobuild");
1122
- }
1123
- if (script === "run-dotnet-test-tier.ps1") {
1123
+ if (["run-dotnet-test-tier.ps1", "run-dotnet-test-tier-set.ps1", "run-dotnet-test-suite.ps1"].includes(script)) {
1124
1124
  return !args.some(argument => argument.toLowerCase() === "-nobuild");
1125
1125
  }
1126
1126
  }
@@ -1,3 +1,19 @@
1
+ /** The managed command a build check needs: what it runs, where, and for which attempt. */
2
+ export interface ManagedBuildCandidate {
3
+ readonly command: string;
4
+ readonly args: readonly string[];
5
+ readonly cwd: string;
6
+ readonly worktreePath: string;
7
+ readonly logDirectory: string;
8
+ readonly buildProducing: boolean;
9
+ }
10
+ /**
11
+ * Refuses, before launch, a managed command that would build into the output one of the
12
+ * attempt's running supervised runtimes executes from. The build slot below orders builds
13
+ * against each other; a running runtime cannot wait its turn, so the collision fails fast
14
+ * with an error naming the runtime instead of a build stuck on its locked files.
15
+ */
16
+ export declare function assertManagedBuildSparesSupervisedRuntimes(candidate: ManagedBuildCandidate): Promise<void>;
1
17
  export declare class ManagedBuildCoordinator {
2
18
  private readonly stateRoot;
3
19
  constructor(stateRoot?: string);
@@ -3,10 +3,20 @@ import fs from "node:fs/promises";
3
3
  import path from "node:path";
4
4
  import { defaultWorktreeCoordinatorStateRoot } from "../worktree/worktree-paths.js";
5
5
  import { monotonicNowMs } from "../shared/time/monotonic.js";
6
+ import { assertBuildSparesSupervisedRuntimes } from "../runtime/supervised-runtime-build-guard.js";
6
7
  const heartbeatIntervalMs = 30_000;
7
8
  const staleAfterMs = 2 * 60_000;
8
9
  const acquisitionTimeoutMs = 2 * 60 * 60_000;
9
10
  const pollIntervalMs = 100;
11
+ /**
12
+ * Refuses, before launch, a managed command that would build into the output one of the
13
+ * attempt's running supervised runtimes executes from. The build slot below orders builds
14
+ * against each other; a running runtime cannot wait its turn, so the collision fails fast
15
+ * with an error naming the runtime instead of a build stuck on its locked files.
16
+ */
17
+ export async function assertManagedBuildSparesSupervisedRuntimes(candidate) {
18
+ await assertBuildSparesSupervisedRuntimes({ ...candidate, buildsWorktreeSolution: candidate.buildProducing });
19
+ }
10
20
  export class ManagedBuildCoordinator {
11
21
  stateRoot;
12
22
  constructor(stateRoot = defaultWorktreeCoordinatorStateRoot()) {
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const forgeBridgeVersion = "0.1.4-dev.e847c8c66ea9";
1
+ export declare const forgeBridgeVersion = "0.1.4-dev.ec3460040366";
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const forgeBridgeVersion = "0.1.4-dev.e847c8c66ea9";
1
+ export const forgeBridgeVersion = "0.1.4-dev.ec3460040366";