@loucompanion/forge-bridge 0.1.4-dev.bfa11ebe98c6 → 0.1.4-dev.c2f22d1dd395

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 (62) hide show
  1. package/README.md +1 -1
  2. package/dist/bridge/bridge.service.d.ts +12 -1
  3. package/dist/bridge/bridge.service.js +53 -6
  4. package/dist/bridge/bridge.types.d.ts +6 -0
  5. package/dist/bridge/dispatch-result-outbox.d.ts +11 -1
  6. package/dist/bridge/dispatch-result-outbox.js +31 -6
  7. package/dist/cli/cli.help.js +2 -2
  8. package/dist/runtime/attempt-database-broker.d.ts +89 -0
  9. package/dist/runtime/attempt-database-broker.js +390 -0
  10. package/dist/runtime/attempt-process-supervisor.d.ts +24 -0
  11. package/dist/runtime/attempt-process-supervisor.js +77 -3
  12. package/dist/runtime/host-database-capability-boundary.d.ts +1 -1
  13. package/dist/runtime/host-database-capability-boundary.js +1 -0
  14. package/dist/runtime/host-diagnostics.js +4 -3
  15. package/dist/runtime/host-facts.d.ts +35 -0
  16. package/dist/runtime/host-facts.js +95 -0
  17. package/dist/runtime/host-load-sampler.d.ts +83 -0
  18. package/dist/runtime/host-load-sampler.js +164 -0
  19. package/dist/runtime/host-pressure-stall.d.ts +41 -0
  20. package/dist/runtime/host-pressure-stall.js +121 -0
  21. package/dist/runtime/host-runtime-contract.d.ts +1 -0
  22. package/dist/runtime/host-runtime-contract.js +71 -10
  23. package/dist/runtime/host-runtime-lease.d.ts +4 -2
  24. package/dist/runtime/host-runtime-lease.js +108 -24
  25. package/dist/runtime/managed-command-teardown.d.ts +62 -0
  26. package/dist/runtime/managed-command-teardown.js +607 -0
  27. package/dist/runtime/node-host-runtime-adapter.js +5 -4
  28. package/dist/runtime/playwright-browser-cache.d.ts +39 -0
  29. package/dist/runtime/playwright-browser-cache.js +227 -0
  30. package/dist/runtime/playwright-host-runtime-adapter.d.ts +11 -0
  31. package/dist/runtime/playwright-host-runtime-adapter.js +48 -54
  32. package/dist/sandbox/repository-lock.js +3 -2
  33. package/dist/sandbox/runtime.js +5 -4
  34. package/dist/session/managed-attempt-tools.d.ts +25 -0
  35. package/dist/session/managed-attempt-tools.js +222 -20
  36. package/dist/session/managed-build-coordinator.d.ts +1 -1
  37. package/dist/session/managed-build-coordinator.js +8 -4
  38. package/dist/session/phase-completion.artifacts.js +4 -0
  39. package/dist/session/phase-completion.runtime.js +30 -18
  40. package/dist/session/pre-publication-process.d.ts +20 -0
  41. package/dist/session/pre-publication-process.js +97 -0
  42. package/dist/session/pre-publication-skipped-tests.d.ts +21 -0
  43. package/dist/session/pre-publication-skipped-tests.js +109 -0
  44. package/dist/session/pre-publication-validation.js +32 -58
  45. package/dist/session/provider-cli/provider-cli.artifacts.js +2 -9
  46. package/dist/session/provider-cli/provider-cli.process.d.ts +6 -1
  47. package/dist/session/provider-cli/provider-cli.process.js +198 -16
  48. package/dist/session/provider-cli/provider-cli.runtime.d.ts +6 -0
  49. package/dist/session/provider-cli/provider-cli.runtime.js +14 -0
  50. package/dist/session/provider-cli/provider-cli.service.js +64 -12
  51. package/dist/session/provider-cli/provider-usage.d.ts +2 -1
  52. package/dist/session/publishable-worktree-changes.d.ts +45 -0
  53. package/dist/session/publishable-worktree-changes.js +177 -0
  54. package/dist/session/session.types.js +3 -0
  55. package/dist/shared/process/host-process-recovery.js +3 -2
  56. package/dist/shared/process/host-process-supervisor.js +5 -4
  57. package/dist/shared/time/monotonic.d.ts +1 -0
  58. package/dist/shared/time/monotonic.js +8 -0
  59. package/dist/version.d.ts +1 -1
  60. package/dist/version.js +1 -1
  61. package/dist/worktree/dependency-warmer.js +74 -0
  62. package/package.json +1 -1
@@ -7,18 +7,45 @@ import { isGeneratedOutputDirectoryName } from "./generated-output-reset.js";
7
7
  export const hostRuntimeContractPath = ".forge/forge.runtime.yml";
8
8
  export const hostRuntimeTestPostgresAdminEnvironment = "FORGE_TEST_POSTGRES_ADMIN_CONNECTION_STRING";
9
9
  export const hostRuntimeLegacyTestPostgresEnvironment = "FORGE_TEST_POSTGRES_CONNECTION_STRING";
10
+ // Optional superuser login for operator-run .NET fixtures. Never reaches attempt, validation or provider processes.
11
+ export const hostRuntimeTestPostgresProvisionerEnvironment = "FORGE_TEST_POSTGRES_PROVISIONER_CONNECTION_STRING";
10
12
  const maximumContractBytes = 64 * 1024;
11
13
  const maximumDepth = 12;
14
+ // Every discovery scan stops after this many directory entries. A monorepo needs a few
15
+ // thousand; the bound only keeps a pathological tree from stalling attempt preparation.
16
+ const maximumDiscoveryEntries = 20_000;
17
+ /**
18
+ * A discovery scan reached its entry budget before seeing the whole tree, so what it did not
19
+ * find may still exist. Discovery must not treat that as absence: a partial runtime (for
20
+ * example a web app without its API) would send the attempt's traffic to the wrong server.
21
+ */
22
+ class IncompleteRuntimeDiscoveryError extends Error {
23
+ }
24
+ // Dependency, build and editor folders never hold an application entrypoint, and counting
25
+ // them would exhaust the budget and serialize a repository for no reason.
12
26
  const ignoredDiscoveryDirectories = new Set([
13
27
  ".forge",
14
28
  ".forge-designer",
15
29
  ".git",
30
+ ".gradle",
31
+ ".idea",
16
32
  ".local",
33
+ ".next",
34
+ ".pnpm",
35
+ ".turbo",
36
+ ".venv",
37
+ ".vs",
38
+ ".vscode",
39
+ ".yarn",
17
40
  "bin",
41
+ "build",
18
42
  "coverage",
19
43
  "dist",
20
44
  "node_modules",
21
45
  "obj",
46
+ "target",
47
+ "vendor",
48
+ "venv",
22
49
  ]);
23
50
  const topLevelKeys = new Set(["schemaVersion", "runtime"]);
24
51
  const runtimeKeys = new Set(["hostConcurrency", "ports", "playwright", "browserProfile", "singletonResources"]);
@@ -47,10 +74,19 @@ export async function loadHostRuntimeContract(worktreePath, snapshot, directoryS
47
74
  }
48
75
  async function discoverHostRuntimeContract(worktreePath, snapshot, directorySnapshot) {
49
76
  const root = path.resolve(worktreePath);
50
- const [nodeDiscovery, aspNetDiscovery] = await Promise.all([
51
- discoverNodeRuntimes(root, snapshot, directorySnapshot),
52
- discoverAspNetRuntimes(root, snapshot, directorySnapshot),
53
- ]);
77
+ let nodeDiscovery;
78
+ let aspNetDiscovery;
79
+ try {
80
+ [nodeDiscovery, aspNetDiscovery] = await Promise.all([
81
+ discoverNodeRuntimes(root, snapshot, directorySnapshot),
82
+ discoverAspNetRuntimes(root, snapshot, directorySnapshot),
83
+ ]);
84
+ }
85
+ catch (error) {
86
+ if (error instanceof IncompleteRuntimeDiscoveryError)
87
+ return incompleteRuntimeDiscovery();
88
+ throw error;
89
+ }
54
90
  if (nodeDiscovery.ambiguous || aspNetDiscovery.ambiguous) {
55
91
  return ambiguousRuntimeDiscovery();
56
92
  }
@@ -102,7 +138,7 @@ async function discoverHostRuntimeContract(worktreePath, snapshot, directorySnap
102
138
  async function discoverNodeRuntimes(root, snapshot, directorySnapshot) {
103
139
  const manifests = [...new Set([
104
140
  path.join(root, "package.json"),
105
- ...await findFiles(root, file => path.basename(file).toLowerCase() === "package.json", 4, 500, directorySnapshot),
141
+ ...await findFiles(root, file => path.basename(file).toLowerCase() === "package.json", 4, maximumDiscoveryEntries, directorySnapshot),
106
142
  ])];
107
143
  const candidates = (await Promise.all(manifests.map(async (manifestPath) => await discoverNodeRuntime(root, manifestPath, snapshot, directorySnapshot)))).filter((candidate) => candidate !== null);
108
144
  return { candidates: candidates.length === 1 ? candidates : [], ambiguous: candidates.length > 1 };
@@ -138,7 +174,7 @@ async function discoverNodeRuntime(root, manifestPath, snapshot, directorySnapsh
138
174
  ...["playwright.config.ts", "playwright.config.js", "playwright.config.mjs", "playwright.config.cjs"]
139
175
  .flatMap(file => [file, `e2e/${file}`, `tests/e2e/${file}`])
140
176
  .map(async (candidate) => await optionalFileExists(path.join(root, candidate), snapshot) ? path.join(root, candidate) : null),
141
- findFiles(root, file => /^playwright\.config\.(?:ts|js|mjs|cjs)$/iu.test(path.basename(file)), 4, 2_000, directorySnapshot),
177
+ findFiles(root, file => /^playwright\.config\.(?:ts|js|mjs|cjs)$/iu.test(path.basename(file)), 4, maximumDiscoveryEntries, directorySnapshot),
142
178
  ])).flat().filter((value) => value !== null))]
143
179
  .map(config => portableRelativePath(root, config));
144
180
  const playwright = playwrightConfigs.length === 1
@@ -183,7 +219,9 @@ async function discoverNodeRuntime(root, manifestPath, snapshot, directorySnapsh
183
219
  };
184
220
  }
185
221
  async function discoverAspNetRuntimes(root, snapshot, directorySnapshot) {
186
- const projects = await findFiles(root, file => file.toLowerCase().endsWith(".csproj"), 3, 200, directorySnapshot);
222
+ // Deep enough for nested solutions (src/<area>/<Project>/<Project>.csproj); the entry budget,
223
+ // not the depth, bounds the scan, and a scan that exceeds it is reported as incomplete.
224
+ const projects = await findFiles(root, file => file.toLowerCase().endsWith(".csproj"), 6, maximumDiscoveryEntries, directorySnapshot);
187
225
  const webProjects = [];
188
226
  for (const projectPath of projects) {
189
227
  const source = await readBoundedOptionalFile(projectPath, 512 * 1024, snapshot);
@@ -277,6 +315,17 @@ function combineBrowserAndApiRuntime(browser, api) {
277
315
  }),
278
316
  };
279
317
  }
318
+ function incompleteRuntimeDiscovery() {
319
+ return {
320
+ contract: defaultHostRuntimeContract(),
321
+ source: "default",
322
+ discovery: {
323
+ status: "ambiguous",
324
+ reasonCode: "runtime_discovery_incomplete",
325
+ summary: "Forge could not scan the whole repository within its discovery budget, so host application runs remain serialized.",
326
+ },
327
+ };
328
+ }
280
329
  function ambiguousRuntimeDiscovery() {
281
330
  return {
282
331
  contract: defaultHostRuntimeContract(),
@@ -339,7 +388,13 @@ async function discoverAspNetLaunchProfile(root, projectRelativePath, snapshot)
339
388
  return { name: null, source, environment: {} };
340
389
  }
341
390
  }
391
+ // A project's "forge-attempt" profile configures its API for managed attempts. The
392
+ // attempt's pre-publication checks then run against the same settings the project's own
393
+ // e2e suite uses, instead of the developer's "http" profile.
394
+ const attemptLaunchProfileName = "forge-attempt";
342
395
  function aspNetProfilePriority(name) {
396
+ if (name.toLowerCase() === attemptLaunchProfileName)
397
+ return -1;
343
398
  if (name.toLowerCase() === "http")
344
399
  return 0;
345
400
  if (name.toLowerCase() === "https")
@@ -373,7 +428,7 @@ async function findFiles(root, accepts, maximumDepth, maximumEntries, snapshot)
373
428
  const results = [];
374
429
  let examined = 0;
375
430
  const directories = [{ directory: root, depth: 0 }];
376
- while (directories.length > 0 && examined < maximumEntries) {
431
+ while (directories.length > 0) {
377
432
  const current = directories.shift();
378
433
  if (current.depth > maximumDepth)
379
434
  continue;
@@ -383,14 +438,20 @@ async function findFiles(root, accepts, maximumDepth, maximumEntries, snapshot)
383
438
  name: entry.name,
384
439
  isDirectory: entry.isDirectory(),
385
440
  isFile: entry.isFile(),
386
- }))).catch(() => []);
441
+ }))).catch((error) => {
442
+ // A directory removed since it was listed holds nothing; one that cannot be read
443
+ // (permissions, open-file limits) may hold the entrypoint discovery is looking for.
444
+ if (isFileNotFound(error))
445
+ return [];
446
+ throw new IncompleteRuntimeDiscoveryError();
447
+ });
387
448
  const orderedEntries = [...entries].sort((left, right) => left.name < right.name ? -1 : left.name > right.name ? 1 : 0);
388
449
  for (const entry of orderedEntries) {
389
450
  if (entry.isDirectory
390
451
  && (ignoredDiscoveryDirectories.has(entry.name.toLowerCase()) || isGeneratedOutputDirectoryName(entry.name)))
391
452
  continue;
392
453
  if (examined++ >= maximumEntries)
393
- break;
454
+ throw new IncompleteRuntimeDiscoveryError();
394
455
  const target = path.join(current.directory, entry.name);
395
456
  if (entry.isDirectory)
396
457
  directories.push({ directory: target, depth: current.depth + 1 });
@@ -6,6 +6,7 @@ import { HostPortBroker } from "./host-port-broker.js";
6
6
  import { NodeHostRuntimeAdapter, type NodeRuntimeAdapterLaunch, type NodeRuntimeCommand, type NodeRuntimeCommandLauncher } from "./node-host-runtime-adapter.js";
7
7
  import type { AttemptProcessTreeMemoryTelemetry } from "./attempt-process-supervisor.js";
8
8
  import { AttemptProcessSupervisorRegistry } from "./attempt-process-supervisor-registry.js";
9
+ import { type AttemptDatabaseBroker } from "./attempt-database-broker.js";
9
10
  import { HostListenerInspector } from "./host-listener-inspector.js";
10
11
  import { type MemoryAdmissionDiagnostics } from "./memory-capacity.js";
11
12
  import { PlaywrightHostRuntimeAdapter } from "./playwright-host-runtime-adapter.js";
@@ -24,7 +25,7 @@ export interface HostRuntimeAdmissionCheckpoint {
24
25
  }
25
26
  export type HostRuntimeAdmissionCheckpointHandler = (checkpoint: HostRuntimeAdmissionCheckpoint) => void | Promise<void>;
26
27
  export interface HostRuntimeProjectCheckpoint {
27
- readonly code: "host_runtime_build_started" | "host_runtime_build_cached" | "host_runtime_build_completed";
28
+ readonly code: "host_runtime_build_started" | "host_runtime_build_cached" | "host_runtime_build_completed" | "host_runtime_database_provisioned";
28
29
  readonly message: string;
29
30
  readonly data?: Readonly<Record<string, unknown>>;
30
31
  }
@@ -119,6 +120,7 @@ export declare class HostRuntimeLeaseManager implements HostRuntimeLeaseRuntime
119
120
  private readonly playwrightAdapter;
120
121
  private readonly processRecovery;
121
122
  private readonly capacityResourceSample?;
123
+ private readonly databaseBroker;
122
124
  private readonly preparedReadiness;
123
125
  private readonly active;
124
126
  private readonly pendingRenewals;
@@ -141,7 +143,7 @@ export declare class HostRuntimeLeaseManager implements HostRuntimeLeaseRuntime
141
143
  private readonly capacityConfiguration;
142
144
  private readonly memoryAvailability;
143
145
  private readonly executionRoot;
144
- constructor(stateRoot: string, portBroker?: HostPortBroker, nodeAdapter?: NodeHostRuntimeAdapter, processSupervisors?: AttemptProcessSupervisorRegistry, processRunner?: ProviderProcessRunner, listenerInspector?: HostListenerInspector, promotionStore?: HostParallelPromotionStore, playwrightAdapter?: PlaywrightHostRuntimeAdapter, processRecovery?: HostProcessRecovery, capacityResourceSample?: HostCapacityResourceSample | undefined, executionRoot?: string);
146
+ constructor(stateRoot: string, portBroker?: HostPortBroker, nodeAdapter?: NodeHostRuntimeAdapter, processSupervisors?: AttemptProcessSupervisorRegistry, processRunner?: ProviderProcessRunner, listenerInspector?: HostListenerInspector, promotionStore?: HostParallelPromotionStore, playwrightAdapter?: PlaywrightHostRuntimeAdapter, processRecovery?: HostProcessRecovery, capacityResourceSample?: HostCapacityResourceSample | undefined, executionRoot?: string, databaseBroker?: AttemptDatabaseBroker | null);
145
147
  reap(options: HostRuntimeReapOptions): Promise<HostRuntimeReapReport>;
146
148
  snapshot(): HostRuntimeCapacitySnapshot;
147
149
  hasForegroundDemand(): boolean;
@@ -9,12 +9,15 @@ import { PreparedRuntimeReadiness } from "./prepared-runtime-readiness.js";
9
9
  import { preparedRuntimeIdentity } from "./prepared-runtime-identity.js";
10
10
  import { resolveExistingDirectoryPath } from "../shared/path/path.js";
11
11
  import { formatBytes } from "../shared/format/format-bytes.js";
12
+ import { redactText } from "../shared/redaction/redaction.js";
12
13
  import { StreamingProviderProcessRunner, } from "../session/provider-cli/provider-cli.process.js";
13
14
  import { createRuntimeIsolationLease, renewRuntimeIsolationLease, transitionRuntimeIsolationLease, validRuntimeIsolationLease, withRuntimeIsolationResources, } from "./runtime-isolation-lease.js";
14
15
  import { hostPortEnvironment, loadHostRuntimeContract, } from "./host-runtime-contract.js";
15
16
  import { HostPortBroker, } from "./host-port-broker.js";
16
17
  import { NodeHostRuntimeAdapter, } from "./node-host-runtime-adapter.js";
17
18
  import { AttemptProcessSupervisorRegistry } from "./attempt-process-supervisor-registry.js";
19
+ import { terminateAttemptManagedCommands } from "./managed-command-teardown.js";
20
+ import { attemptDatabaseCapabilityEnvironment, attemptDatabaseCapabilitySecrets, } from "./attempt-database-broker.js";
18
21
  import { AttemptNodeRuntimeLauncher } from "./attempt-node-runtime-launcher.js";
19
22
  import { HostListenerInspector } from "./host-listener-inspector.js";
20
23
  import { RecoveryStabilizedMemory, buildMemoryAdmissionDiagnostics, resolveAdaptiveMemoryReserveBytes, } from "./memory-capacity.js";
@@ -38,6 +41,7 @@ export class HostRuntimeLeaseManager {
38
41
  playwrightAdapter;
39
42
  processRecovery;
40
43
  capacityResourceSample;
44
+ databaseBroker;
41
45
  preparedReadiness;
42
46
  active = new Map();
43
47
  pendingRenewals = new Map();
@@ -60,7 +64,7 @@ export class HostRuntimeLeaseManager {
60
64
  capacityConfiguration;
61
65
  memoryAvailability;
62
66
  executionRoot;
63
- constructor(stateRoot, portBroker = new HostPortBroker(), nodeAdapter, processSupervisors = new AttemptProcessSupervisorRegistry(), processRunner = new StreamingProviderProcessRunner(), listenerInspector = new HostListenerInspector(), promotionStore = new HostParallelPromotionStore(stateRoot), playwrightAdapter = new PlaywrightHostRuntimeAdapter(), processRecovery = new ExactHostProcessRecovery(), capacityResourceSample, executionRoot) {
67
+ constructor(stateRoot, portBroker = new HostPortBroker(), nodeAdapter, processSupervisors = new AttemptProcessSupervisorRegistry(), processRunner = new StreamingProviderProcessRunner(), listenerInspector = new HostListenerInspector(), promotionStore = new HostParallelPromotionStore(stateRoot), playwrightAdapter = new PlaywrightHostRuntimeAdapter(), processRecovery = new ExactHostProcessRecovery(), capacityResourceSample, executionRoot, databaseBroker = null) {
64
68
  this.stateRoot = stateRoot;
65
69
  this.processSupervisors = processSupervisors;
66
70
  this.processRunner = processRunner;
@@ -69,6 +73,7 @@ export class HostRuntimeLeaseManager {
69
73
  this.playwrightAdapter = playwrightAdapter;
70
74
  this.processRecovery = processRecovery;
71
75
  this.capacityResourceSample = capacityResourceSample;
76
+ this.databaseBroker = databaseBroker;
72
77
  this.executionRoot = path.resolve(executionRoot ?? stateRoot);
73
78
  if (executionRoot !== undefined)
74
79
  assertHostExecutionRoot(this.executionRoot);
@@ -199,6 +204,10 @@ export class HostRuntimeLeaseManager {
199
204
  report.degraded += 1;
200
205
  }
201
206
  }
207
+ // Databases issued to attempts that ended without a clean release (a Bridge crash, or a
208
+ // drop that met a lingering session) are removed once no live lease holds them.
209
+ // A degraded lease may still own running processes after a restart, so its database is kept.
210
+ await this.databaseBroker?.reapOrphans(id => this.active.has(id) || this.degraded.has(id)).catch(() => undefined);
202
211
  return report;
203
212
  }
204
213
  snapshot() {
@@ -887,7 +896,7 @@ export class HostRuntimeLeaseManager {
887
896
  }
888
897
  return {
889
898
  lease: existing.lease,
890
- environment: hostRuntimeEnvironment(dispatch.session.id, existing.lease, existing.runtimeContract, existing.executionClass),
899
+ environment: hostRuntimeEnvironment(dispatch.session.id, existing.lease, existing.runtimeContract, existing.executionClass, existing.databaseCapability),
891
900
  runtimeContract: existing.runtimeContract,
892
901
  executionClass: existing.executionClass,
893
902
  };
@@ -1149,7 +1158,7 @@ export class HostRuntimeLeaseManager {
1149
1158
  if (active.executionClass === "analysis_only") {
1150
1159
  return {
1151
1160
  lease: active.lease,
1152
- environment: hostRuntimeEnvironment(active.sessionId, active.lease, active.runtimeContract, active.executionClass),
1161
+ environment: hostRuntimeEnvironment(active.sessionId, active.lease, active.runtimeContract, active.executionClass, active.databaseCapability),
1153
1162
  runtimeContract: active.runtimeContract,
1154
1163
  executionClass: active.executionClass,
1155
1164
  };
@@ -1158,21 +1167,49 @@ export class HostRuntimeLeaseManager {
1158
1167
  if (configuredPorts.length === 0) {
1159
1168
  return {
1160
1169
  lease: active.lease,
1161
- environment: hostRuntimeEnvironment(active.sessionId, active.lease, active.runtimeContract, active.executionClass),
1170
+ environment: hostRuntimeEnvironment(active.sessionId, active.lease, active.runtimeContract, active.executionClass, active.databaseCapability),
1162
1171
  runtimeContract: active.runtimeContract,
1163
1172
  executionClass: active.executionClass,
1164
1173
  };
1165
1174
  }
1175
+ const playwrightConfig = active.runtimeContract.contract.runtime.playwright;
1176
+ // A host without the project's pinned browsers fails here, before any database,
1177
+ // build, launch, or promotion work that the attempt would otherwise waste.
1178
+ if (playwrightConfig)
1179
+ await this.playwrightAdapter.assertBrowserCacheReady(playwrightConfig, active.lease.worktreePath);
1166
1180
  const owner = hostPortOwner(active.lease);
1167
1181
  const logDirectory = active.lease.resources.paths.find(entry => entry.role === "logs")?.path;
1168
1182
  if (!logDirectory)
1169
1183
  throw new Error("host_runtime_project_invalid: attempt log directory is unavailable.");
1170
- const launcher = new AttemptNodeRuntimeLauncher(active.processSupervisor, owner, logDirectory, this.listenerInspector);
1184
+ if (this.databaseBroker && !active.databaseCapability
1185
+ && configuredPorts.some(port => /^dotnet(?:\.exe)?$/iu.test(path.basename(port.launch.command)))) {
1186
+ // An ASP.NET runtime may require an isolated database (Forge.Api refuses to start in a
1187
+ // managed host attempt without one). Issue it before the first launch. Release waits for
1188
+ // an in-flight provision, so a database issued during release is still dropped.
1189
+ const provision = this.databaseBroker.provision(dispatchAttemptId, fencingToken, signal)
1190
+ .then(capability => {
1191
+ active.databaseCapability = capability;
1192
+ return capability;
1193
+ });
1194
+ active.databaseProvision = provision;
1195
+ await provision;
1196
+ if (active.releasing) {
1197
+ throw new Error("host_runtime_project_unavailable: the host runtime lease was released during database provisioning.");
1198
+ }
1199
+ await onProjectCheckpoint?.({
1200
+ code: "host_runtime_database_provisioned",
1201
+ message: `Provisioned isolated attempt database ${active.databaseCapability.databaseName} on the native test cluster.`,
1202
+ data: { database: active.databaseCapability.databaseName },
1203
+ });
1204
+ }
1205
+ // Runtime output is persisted to attempt logs; the database login it may print is redacted.
1206
+ const capabilitySecrets = attemptDatabaseCapabilitySecrets(active.databaseCapability?.connectionString);
1207
+ const launcher = new AttemptNodeRuntimeLauncher(active.processSupervisor, owner, logDirectory, this.listenerInspector, capabilitySecrets);
1171
1208
  for (const configuredPort of configuredPorts) {
1172
1209
  const workingDirectory = await containedWorkingDirectory(active.lease.worktreePath, configuredPort.launch.workingDirectory);
1173
1210
  const buildEnvironment = {
1174
1211
  ...configuredPort.launch.environment,
1175
- ...hostRuntimeEnvironment(active.sessionId, active.lease, active.runtimeContract, active.executionClass),
1212
+ ...hostRuntimeEnvironment(active.sessionId, active.lease, active.runtimeContract, active.executionClass, active.databaseCapability),
1176
1213
  };
1177
1214
  const prebuild = createAspNetRuntimePrebuildPlan({
1178
1215
  command: configuredPort.launch.command,
@@ -1189,7 +1226,7 @@ export class HostRuntimeLeaseManager {
1189
1226
  message: `Preparing the ASP.NET runtime for commit ${active.inputCommitSha.slice(0, 12)} before binding its assigned port.`,
1190
1227
  data: { input_commit_sha: active.inputCommitSha, project_path: prebuild.projectPath },
1191
1228
  });
1192
- const build = await ensureAspNetRuntimePrebuilt(prebuild, async (plan, buildSignal) => await executeAspNetRuntimeBuild(active.processSupervisor, logDirectory, plan, buildSignal), signal);
1229
+ const build = await ensureAspNetRuntimePrebuilt(prebuild, async (plan, buildSignal) => await executeAspNetRuntimeBuild(active.processSupervisor, logDirectory, plan, buildSignal, capabilitySecrets), signal);
1193
1230
  await onProjectCheckpoint?.({
1194
1231
  code: build.cacheHit ? "host_runtime_build_cached" : "host_runtime_build_completed",
1195
1232
  message: build.cacheHit
@@ -1212,7 +1249,7 @@ export class HostRuntimeLeaseManager {
1212
1249
  }, launcher, signal);
1213
1250
  }
1214
1251
  const promotedLease = await this.promoteVerifiedRuntime(active, active.lease);
1215
- const runtimeEnvironment = hostRuntimeEnvironment(active.sessionId, promotedLease, active.runtimeContract, active.executionClass);
1252
+ const runtimeEnvironment = hostRuntimeEnvironment(active.sessionId, promotedLease, active.runtimeContract, active.executionClass, active.databaseCapability);
1216
1253
  const playwright = active.runtimeContract.contract.runtime.playwright;
1217
1254
  if (!playwright) {
1218
1255
  return {
@@ -1396,6 +1433,7 @@ export class HostRuntimeLeaseManager {
1396
1433
  pending.controller.abort("Host runtime release cancelled the pending adapter launch.");
1397
1434
  }
1398
1435
  await Promise.allSettled([...active.pendingAdapterLaunches.values()].map(pending => pending.promise));
1436
+ await active.databaseProvision?.catch(() => undefined);
1399
1437
  let releasing = transitionRuntimeIsolationLease(active.lease, "releasing");
1400
1438
  active.lease = releasing;
1401
1439
  await this.writeLedger(releasing);
@@ -1403,6 +1441,10 @@ export class HostRuntimeLeaseManager {
1403
1441
  if (!active.runtimeResourcesReleased) {
1404
1442
  await active.processSupervisor.stopAll(fencingToken, "Host runtime lease released.");
1405
1443
  await releaseAdapterResources(active.adapterCleanups);
1444
+ if (active.databaseCapability && this.databaseBroker) {
1445
+ // A database the broker cannot drop now is reaped later; it must not hold host capacity.
1446
+ await this.databaseBroker.release(dispatchAttemptId, fencingToken).catch(() => "retained");
1447
+ }
1406
1448
  active.runtimeResourcesReleased = true;
1407
1449
  // Runtime admission protects live processes, listeners, ports, and their
1408
1450
  // memory commitment. Once exact process and adapter cleanup succeeds,
@@ -1496,18 +1538,46 @@ export class HostRuntimeLeaseManager {
1496
1538
  if (logsEntry.kind !== "directory") {
1497
1539
  throw new Error("host_runtime_reaper_invalid: process ownership log path is not an ordinary directory.");
1498
1540
  }
1499
- const entries = await readPinnedSourceDirectory(logsRoot, logsEntry.identity);
1500
1541
  const outcomes = [];
1501
- for (const entry of entries) {
1502
- if (entry.kind !== "file" || !/^process-supervisor\.[a-z][a-z0-9_-]{0,31}\.\d+\.json$/u.test(entry.name))
1503
- continue;
1504
- const metadataPath = path.join(logsRoot, entry.name);
1505
- const value = JSON.parse((await readCanonicalSourceFile(metadataPath, maximumProcessRecoveryMetadataBytes, entry.identity)).toString("utf8"));
1506
- if (!validHostProcessSupervisorMetadata(value, lease)) {
1507
- throw new Error("host_runtime_reaper_invalid: process ownership metadata did not match the runtime lease.");
1542
+ const failures = [];
1543
+ try {
1544
+ const entries = await readPinnedSourceDirectory(logsRoot, logsEntry.identity);
1545
+ for (const entry of entries) {
1546
+ if (entry.kind !== "file" || !/^process-supervisor\.[a-z][a-z0-9_-]{0,31}\.\d+\.json$/u.test(entry.name))
1547
+ continue;
1548
+ const metadataPath = path.join(logsRoot, entry.name);
1549
+ const value = JSON.parse((await readCanonicalSourceFile(metadataPath, maximumProcessRecoveryMetadataBytes, entry.identity)).toString("utf8"));
1550
+ if (!validHostProcessSupervisorMetadata(value, lease)) {
1551
+ throw new Error("host_runtime_reaper_invalid: process ownership metadata did not match the runtime lease.");
1552
+ }
1553
+ outcomes.push(await this.processRecovery.recover(value));
1508
1554
  }
1509
- outcomes.push(await this.processRecovery.recover(value));
1510
1555
  }
1556
+ catch (error) {
1557
+ failures.push(error);
1558
+ }
1559
+ // Managed commands run in their own process groups and record their ownership apart
1560
+ // from the attempt's supervised children. They are recovered even when recovering a
1561
+ // supervised child failed, and both failures are reported together.
1562
+ try {
1563
+ const managed = await terminateAttemptManagedCommands({
1564
+ logDirectory: logsRoot,
1565
+ dispatchAttemptId: lease.dispatchAttemptId,
1566
+ runtimeLeaseId: lease.executionLeaseId,
1567
+ pinnedLogDirectory: logsEntry.identity,
1568
+ }, { reason: "attempt_teardown" });
1569
+ for (const command of managed) {
1570
+ if (command.outcome === "terminated" || command.outcome === "pid_reused")
1571
+ outcomes.push(command.outcome);
1572
+ }
1573
+ }
1574
+ catch (error) {
1575
+ failures.push(error);
1576
+ }
1577
+ if (failures.length === 1)
1578
+ throw failures[0];
1579
+ if (failures.length > 1)
1580
+ throw new AggregateError(failures, "host_runtime_reaper_recovery_failed");
1511
1581
  return outcomes;
1512
1582
  }
1513
1583
  async markLedgerDegraded(ledger) {
@@ -1883,6 +1953,18 @@ class AttemptSupervisedProviderProcessRunner {
1883
1953
  : new Set();
1884
1954
  const child = await this.supervisor.startChildReady("provider", request, handlers, signal, { maxStartAttempts: request.stdin === undefined ? 1 : 3, retryDelayMs: 100 });
1885
1955
  this.onProcessTreeStarted();
1956
+ try {
1957
+ return await this.awaitProviderResult(child, baselineListeners, signal);
1958
+ }
1959
+ finally {
1960
+ // The provider tree, and the MCP server inside it, is gone. A managed command that
1961
+ // server started now has no supervisor and no receipt writer, so it must not keep
1962
+ // running into the next provider generation. This never rejects; a command it
1963
+ // cannot prove stopped is left to attempt teardown, which fails closed.
1964
+ await this.supervisor.stopOrphanedManagedCommands();
1965
+ }
1966
+ }
1967
+ async awaitProviderResult(child, baselineListeners, signal) {
1886
1968
  if (!this.enforceNoListeners)
1887
1969
  return await child.result;
1888
1970
  let settled = false;
@@ -1993,7 +2075,7 @@ export function hostRuntimeEventResources(lease, runtimeContract, executionClass
1993
2075
  export function hostRuntimeSingletonKeys(dispatch) {
1994
2076
  return [projectHostRuntimeSingletonKey(dispatch.repo.id)];
1995
2077
  }
1996
- function hostRuntimeEnvironment(sessionId, lease, runtimeContract, executionClass) {
2078
+ function hostRuntimeEnvironment(sessionId, lease, runtimeContract, executionClass, databaseCapability) {
1997
2079
  const pathFor = (role) => lease.resources.paths.find(entry => entry.role === role)?.path ?? "";
1998
2080
  const environment = {
1999
2081
  FORGE_SESSION_ID: sessionId,
@@ -2032,6 +2114,8 @@ function hostRuntimeEnvironment(sessionId, lease, runtimeContract, executionClas
2032
2114
  };
2033
2115
  if (lease.resources.singletonKeys.length === 0)
2034
2116
  delete environment.FORGE_SINGLETON_KEYS;
2117
+ if (databaseCapability)
2118
+ environment[attemptDatabaseCapabilityEnvironment] = databaseCapability.connectionString;
2035
2119
  const resolvedBaseUrls = [];
2036
2120
  for (const assigned of lease.resources.ports) {
2037
2121
  const configured = runtimeContract.contract.runtime.ports.find(port => port.name === assigned.name);
@@ -2056,14 +2140,14 @@ function hostRuntimeEnvironment(sessionId, lease, runtimeContract, executionClas
2056
2140
  environment.FORGE_BASE_URL = resolvedBaseUrls[0];
2057
2141
  return environment;
2058
2142
  }
2059
- async function executeAspNetRuntimeBuild(supervisor, logDirectory, plan, signal) {
2143
+ async function executeAspNetRuntimeBuild(supervisor, logDirectory, plan, signal, exactSecrets = []) {
2060
2144
  const childName = `runtime-build-${plan.fingerprint.slice(-12)}`;
2061
2145
  const stdoutLogPath = path.join(logDirectory, `${childName}.stdout.log`);
2062
2146
  const stderrLogPath = path.join(logDirectory, `${childName}.stderr.log`);
2063
2147
  let stdoutTail = "";
2064
2148
  let stderrTail = "";
2065
2149
  const append = async (target, line) => {
2066
- await fs.appendFile(target, `${line}\n`, { encoding: "utf8", mode: 0o600 });
2150
+ await fs.appendFile(target, `${redactText(line, exactSecrets)}\n`, { encoding: "utf8", mode: 0o600 });
2067
2151
  };
2068
2152
  const child = await supervisor.startChildReady(childName, {
2069
2153
  command: plan.command,
@@ -2073,19 +2157,19 @@ async function executeAspNetRuntimeBuild(supervisor, logDirectory, plan, signal)
2073
2157
  captureOutput: false,
2074
2158
  }, {
2075
2159
  onStdoutLine: async (line) => {
2076
- stdoutTail = appendRuntimeBuildTail(stdoutTail, line);
2160
+ stdoutTail = appendRuntimeBuildTail(stdoutTail, redactText(line, exactSecrets));
2077
2161
  await append(stdoutLogPath, line);
2078
2162
  },
2079
2163
  onStderrLine: async (line) => {
2080
- stderrTail = appendRuntimeBuildTail(stderrTail, line);
2164
+ stderrTail = appendRuntimeBuildTail(stderrTail, redactText(line, exactSecrets));
2081
2165
  await append(stderrLogPath, line);
2082
2166
  },
2083
2167
  }, signal, { maxStartAttempts: 2, retryDelayMs: 250 });
2084
2168
  const result = await child.result;
2085
2169
  return {
2086
2170
  exitCode: result.exitCode,
2087
- stdoutTail: appendRuntimeBuildTail(stdoutTail, result.stdout),
2088
- stderrTail: appendRuntimeBuildTail(stderrTail, result.stderr),
2171
+ stdoutTail: appendRuntimeBuildTail(stdoutTail, redactText(result.stdout, exactSecrets)),
2172
+ stderrTail: appendRuntimeBuildTail(stderrTail, redactText(result.stderr, exactSecrets)),
2089
2173
  stdoutLogPath,
2090
2174
  stderrLogPath,
2091
2175
  };
@@ -0,0 +1,62 @@
1
+ import type { PinnedDirectoryIdentity } from "./pinned-directory-process.js";
2
+ /**
3
+ * Why Forge stopped a managed command that had not finished:
4
+ * - `owner_exited`: the provider process whose MCP server started it has exited, so no
5
+ * process is left to supervise it or write its receipt.
6
+ * - `attempt_teardown`: the dispatch attempt is being torn down.
7
+ */
8
+ export type ManagedCommandTeardownReason = "owner_exited" | "attempt_teardown";
9
+ export interface ManagedCommandTeardownScope {
10
+ /** The attempt's private FORGE_LOG_DIR; managed commands record ownership under it. */
11
+ readonly logDirectory: string;
12
+ readonly dispatchAttemptId: string;
13
+ readonly runtimeLeaseId: string;
14
+ /**
15
+ * Reads the ownership records through pinned directory and file identities instead of
16
+ * pathnames. Restart recovery supplies the verified identity of the attempt's logs.
17
+ */
18
+ readonly pinnedLogDirectory?: PinnedDirectoryIdentity;
19
+ }
20
+ export interface ManagedCommandTeardownOptions {
21
+ readonly reason: ManagedCommandTeardownReason;
22
+ /**
23
+ * Stop only commands whose owning MCP server process is gone. A command whose owner is
24
+ * alive is still supervised by it and must survive wait slices and MCP call boundaries.
25
+ */
26
+ readonly onlyOrphaned?: boolean;
27
+ readonly graceMs?: number;
28
+ readonly platform?: NodeJS.Platform;
29
+ }
30
+ export type ManagedCommandTeardownOutcomeKind =
31
+ /** The recorded process tree had already exited. */
32
+ "absent"
33
+ /** Forge stopped the recorded process tree and proved it gone. */
34
+ | "terminated"
35
+ /** The recorded root PID now names another process, so the recorded tree is gone. */
36
+ | "pid_reused"
37
+ /** The command's owning MCP server is alive and still supervises it. */
38
+ | "owner_alive"
39
+ /** The command finished on its own; nothing was signalled or rewritten. */
40
+ | "already_terminal"
41
+ /** The command never recorded a process: it was queued, or its launch was interrupted. */
42
+ | "no_process_record";
43
+ export interface ManagedCommandTeardownOutcome {
44
+ readonly commandId: string;
45
+ readonly outcome: ManagedCommandTeardownOutcomeKind;
46
+ readonly receiptFinalized: boolean;
47
+ }
48
+ /** Test support: points the Linux process inventory at another directory (null restores /proc). */
49
+ export declare function setManagedCommandProcRootForTesting(root: string | null): void;
50
+ /**
51
+ * Stops managed commands that an attempt's MCP servers started and proves their process
52
+ * trees are gone. Managed commands run in their own process group (Unix) or Job Object
53
+ * (Windows), outside the provider tree that the attempt supervisor stops, so stopping the
54
+ * provider alone leaves them running. Each command's durable receipt is given a terminal
55
+ * status when its owner can no longer write one.
56
+ *
57
+ * Every signal is fenced: the recorded root must still carry the recorded birth identity
58
+ * and, on Linux, this command's supervisor and attempt identity in its environment. A
59
+ * tree that cannot be proven to be the command's own fails the teardown instead of being
60
+ * reported stopped.
61
+ */
62
+ export declare function terminateAttemptManagedCommands(scope: ManagedCommandTeardownScope, options: ManagedCommandTeardownOptions): Promise<readonly ManagedCommandTeardownOutcome[]>;