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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (182) hide show
  1. package/README.md +89 -1
  2. package/dist/bridge/bridge-chat-giphy-look.d.ts +48 -0
  3. package/dist/bridge/bridge-chat-giphy-look.js +55 -0
  4. package/dist/bridge/bridge-chat-provider-command.d.ts +27 -3
  5. package/dist/bridge/bridge-chat-provider-command.js +131 -26
  6. package/dist/bridge/bridge-chat.types.d.ts +20 -0
  7. package/dist/bridge/bridge-chat.types.js +28 -1
  8. package/dist/bridge/bridge-state-file.d.ts +161 -0
  9. package/dist/bridge/bridge-state-file.js +376 -0
  10. package/dist/bridge/bridge-state-io.d.ts +11 -0
  11. package/dist/bridge/bridge-state-io.js +50 -0
  12. package/dist/bridge/bridge-state-lock.d.ts +11 -0
  13. package/dist/bridge/bridge-state-lock.js +102 -0
  14. package/dist/bridge/bridge-state-unpublished.d.ts +17 -0
  15. package/dist/bridge/bridge-state-unpublished.js +111 -0
  16. package/dist/bridge/bridge.service.d.ts +19 -12
  17. package/dist/bridge/bridge.service.js +155 -282
  18. package/dist/bridge/bridge.types.d.ts +5 -0
  19. package/dist/bridge/in-flight-registry.d.ts +62 -0
  20. package/dist/bridge/in-flight-registry.js +207 -0
  21. package/dist/bridge/readiness-result-outbox.d.ts +5 -1
  22. package/dist/bridge/readiness-result-outbox.js +20 -0
  23. package/dist/bridge/runner-host-capabilities.js +14 -1
  24. package/dist/bridge/sandbox-resource-accounting.d.ts +16 -0
  25. package/dist/bridge/sandbox-resource-accounting.js +150 -0
  26. package/dist/bridge/windows-bash-resolution.d.ts +31 -0
  27. package/dist/bridge/windows-bash-resolution.js +153 -0
  28. package/dist/cleanup/cleanup-wip.d.ts +12 -0
  29. package/dist/cleanup/cleanup-wip.js +66 -0
  30. package/dist/cleanup/cleanup.service.d.ts +11 -1
  31. package/dist/cleanup/cleanup.service.js +80 -62
  32. package/dist/cleanup/cleanup.types.d.ts +2 -0
  33. package/dist/cleanup/host-runtime-ledger.d.ts +2 -0
  34. package/dist/cleanup/host-runtime-ledger.js +30 -9
  35. package/dist/cli/cli.help.js +56 -12
  36. package/dist/cli/cli.service.d.ts +3 -10
  37. package/dist/cli/cli.service.js +10 -171
  38. package/dist/cli/idle-status.d.ts +84 -0
  39. package/dist/cli/idle-status.js +181 -0
  40. package/dist/cli/local-config.d.ts +2 -0
  41. package/dist/cli/local-config.js +7 -1
  42. package/dist/cli/provider-cli-detection.d.ts +10 -0
  43. package/dist/cli/provider-cli-detection.js +160 -0
  44. package/dist/runtime/aspnet-runtime-prebuild.d.ts +20 -0
  45. package/dist/runtime/aspnet-runtime-prebuild.js +104 -26
  46. package/dist/runtime/attempt-database-broker.d.ts +1 -1
  47. package/dist/runtime/attempt-node-runtime-launcher.d.ts +36 -0
  48. package/dist/runtime/attempt-node-runtime-launcher.js +169 -0
  49. package/dist/runtime/attempt-process-supervisor.d.ts +2 -0
  50. package/dist/runtime/attempt-process-supervisor.js +12 -6
  51. package/dist/runtime/docker-engine-probe.d.ts +5 -0
  52. package/dist/runtime/docker-engine-probe.js +7 -0
  53. package/dist/runtime/dotnet-build-outputs.d.ts +107 -0
  54. package/dist/runtime/dotnet-build-outputs.js +402 -0
  55. package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
  56. package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
  57. package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
  58. package/dist/runtime/ephemeral-test-postgres.js +303 -0
  59. package/dist/runtime/host-listener-inspector.d.ts +26 -0
  60. package/dist/runtime/host-listener-inspector.js +84 -3
  61. package/dist/runtime/host-load-admission.d.ts +5 -0
  62. package/dist/runtime/host-load-governor-config.d.ts +10 -1
  63. package/dist/runtime/host-load-governor-config.js +4 -1
  64. package/dist/runtime/host-load-governor.d.ts +10 -1
  65. package/dist/runtime/host-load-governor.js +33 -3
  66. package/dist/runtime/host-load-ledger-lock.js +6 -4
  67. package/dist/runtime/host-load-runtime-settings.js +4 -2
  68. package/dist/runtime/host-load-sampler.d.ts +8 -1
  69. package/dist/runtime/host-load-sampler.js +14 -7
  70. package/dist/runtime/host-load-test-slot.js +7 -0
  71. package/dist/runtime/host-runtime-contract.d.ts +12 -0
  72. package/dist/runtime/host-runtime-contract.js +29 -1
  73. package/dist/runtime/host-runtime-lease.d.ts +28 -3
  74. package/dist/runtime/host-runtime-lease.js +140 -296
  75. package/dist/runtime/host-runtime-ledger-recovery.d.ts +20 -0
  76. package/dist/runtime/host-runtime-ledger-recovery.js +134 -0
  77. package/dist/runtime/host-runtime-promotion.d.ts +78 -2
  78. package/dist/runtime/host-runtime-promotion.js +307 -14
  79. package/dist/runtime/managed-command-teardown.js +5 -16
  80. package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
  81. package/dist/runtime/native-test-postgres-fallback.js +60 -8
  82. package/dist/runtime/prepared-runtime-identity.d.ts +4 -0
  83. package/dist/runtime/prepared-runtime-identity.js +130 -9
  84. package/dist/runtime/prepared-runtime-readiness.d.ts +13 -1
  85. package/dist/runtime/prepared-runtime-readiness.js +63 -16
  86. package/dist/runtime/runner-settings.d.ts +4 -0
  87. package/dist/runtime/runner-settings.js +22 -0
  88. package/dist/runtime/supervised-runtime-build-guard.d.ts +45 -0
  89. package/dist/runtime/supervised-runtime-build-guard.js +112 -0
  90. package/dist/sandbox/host-capacity-broker.d.ts +3 -1
  91. package/dist/sandbox/host-capacity-broker.js +4 -2
  92. package/dist/sandbox/managed-branch.d.ts +13 -0
  93. package/dist/sandbox/managed-branch.js +90 -0
  94. package/dist/sandbox/provider-auth/codex.js +11 -11
  95. package/dist/sandbox/runtime.js +3 -7
  96. package/dist/session/managed-attempt-tools.d.ts +0 -7
  97. package/dist/session/managed-attempt-tools.js +50 -82
  98. package/dist/session/managed-build-coordinator.d.ts +16 -0
  99. package/dist/session/managed-build-coordinator.js +10 -0
  100. package/dist/session/managed-build-receipt.d.ts +5 -0
  101. package/dist/session/managed-build-receipt.js +8 -3
  102. package/dist/session/phase-completion.artifacts.js +2 -1
  103. package/dist/session/phase-completion.d.ts +8 -0
  104. package/dist/session/phase-completion.js +1 -0
  105. package/dist/session/phase-completion.mcp-args.d.ts +9 -0
  106. package/dist/session/phase-completion.mcp-args.js +156 -0
  107. package/dist/session/phase-completion.runtime.d.ts +0 -8
  108. package/dist/session/phase-completion.runtime.js +43 -197
  109. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  110. package/dist/session/pre-publication-native-postgres.js +111 -0
  111. package/dist/session/pre-publication-process.js +10 -10
  112. package/dist/session/pre-publication-step-execution.d.ts +2 -1
  113. package/dist/session/pre-publication-step-execution.js +6 -5
  114. package/dist/session/pre-publication-validation.d.ts +7 -3
  115. package/dist/session/pre-publication-validation.js +32 -30
  116. package/dist/session/provider-cli/claude-background-work.d.ts +3 -2
  117. package/dist/session/provider-cli/claude-background-work.js +4 -3
  118. package/dist/session/provider-cli/host-build-lock.d.ts +18 -0
  119. package/dist/session/provider-cli/host-build-lock.js +30 -0
  120. package/dist/session/provider-cli/pre-publication-repair.d.ts +16 -0
  121. package/dist/session/provider-cli/pre-publication-repair.js +33 -0
  122. package/dist/session/provider-cli/provider-cli.child-environment.js +4 -2
  123. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +6 -3
  124. package/dist/session/provider-cli/provider-cli.merge-integrity.js +28 -8
  125. package/dist/session/provider-cli/provider-cli.process.d.ts +2 -14
  126. package/dist/session/provider-cli/provider-cli.process.js +4 -94
  127. package/dist/session/provider-cli/provider-cli.prompts.d.ts +3 -0
  128. package/dist/session/provider-cli/provider-cli.prompts.js +27 -27
  129. package/dist/session/provider-cli/provider-cli.runtime.d.ts +8 -0
  130. package/dist/session/provider-cli/provider-cli.runtime.js +23 -2
  131. package/dist/session/provider-cli/provider-cli.service.d.ts +4 -1
  132. package/dist/session/provider-cli/provider-cli.service.js +27 -43
  133. package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
  134. package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
  135. package/dist/session/provider-cli/provider-user-config-isolation.d.ts +69 -0
  136. package/dist/session/provider-cli/provider-user-config-isolation.js +164 -0
  137. package/dist/session/qa-sidecar-validation.d.ts +6 -0
  138. package/dist/session/qa-sidecar-validation.js +28 -0
  139. package/dist/session/sandbox-host-capacity-gate.d.ts +22 -1
  140. package/dist/session/sandbox-host-capacity-gate.js +35 -16
  141. package/dist/session/session-redaction.js +31 -181
  142. package/dist/session/session.service.d.ts +6 -0
  143. package/dist/session/session.service.js +131 -88
  144. package/dist/session/session.types.d.ts +1 -0
  145. package/dist/session/session.types.js +3 -3
  146. package/dist/session/sidecar-json-shape.d.ts +31 -0
  147. package/dist/session/sidecar-json-shape.js +217 -0
  148. package/dist/shared/fs/file-identity.d.ts +10 -0
  149. package/dist/shared/fs/file-identity.js +15 -0
  150. package/dist/shared/fs/replace-file.d.ts +7 -0
  151. package/dist/shared/fs/replace-file.js +33 -0
  152. package/dist/shared/process/host-process-recovery.d.ts +14 -3
  153. package/dist/shared/process/host-process-recovery.js +23 -3
  154. package/dist/shared/process/host-process-supervisor.d.ts +13 -1
  155. package/dist/shared/process/host-process-supervisor.js +66 -14
  156. package/dist/shared/provider-capabilities.js +9 -1
  157. package/dist/version.d.ts +1 -1
  158. package/dist/version.js +1 -1
  159. package/dist/worktree/orphan-relink.d.ts +19 -0
  160. package/dist/worktree/orphan-relink.js +106 -0
  161. package/dist/worktree/wip-git.d.ts +42 -0
  162. package/dist/worktree/wip-git.js +139 -0
  163. package/dist/worktree/wip-refs.d.ts +77 -0
  164. package/dist/worktree/wip-refs.js +146 -0
  165. package/dist/worktree/wip-restore.d.ts +46 -0
  166. package/dist/worktree/wip-restore.js +280 -0
  167. package/dist/worktree/wip-snapshot.d.ts +53 -0
  168. package/dist/worktree/wip-snapshot.js +270 -0
  169. package/dist/worktree/worktree-inputs.d.ts +8 -0
  170. package/dist/worktree/worktree-inputs.js +134 -0
  171. package/dist/worktree/worktree-origin-sync.d.ts +35 -0
  172. package/dist/worktree/worktree-origin-sync.js +128 -0
  173. package/dist/worktree/worktree-wip-events.d.ts +18 -0
  174. package/dist/worktree/worktree-wip-events.js +115 -0
  175. package/dist/worktree/worktree-wip.d.ts +51 -0
  176. package/dist/worktree/worktree-wip.js +190 -0
  177. package/dist/worktree/worktree.base.d.ts +7 -1
  178. package/dist/worktree/worktree.service.d.ts +27 -5
  179. package/dist/worktree/worktree.service.js +112 -181
  180. package/dist/worktree/worktree.types.d.ts +35 -0
  181. package/package.json +1 -1
  182. package/runtime/windows-listener-owner.ps1 +12 -1
@@ -0,0 +1,160 @@
1
+ import { execFile } from "node:child_process";
2
+ import { promisify } from "node:util";
3
+ import { resolveCursorAgentDirectLaunch } from "../shared/cursor-agent/cursor-agent.launch.js";
4
+ import { buildWindowsCmdLaunch } from "../shared/process/windows-launch.js";
5
+ // Provider CLI detection probes for `forge-bridge status`, `connect` and `pair`: which
6
+ // provider CLIs are installed, their versions and the models they list. Split out of
7
+ // cli.service.ts (file-size inventory plan).
8
+ const execFileAsync = promisify(execFile);
9
+ export async function detectCliProviders(providers) {
10
+ const results = [];
11
+ for (const provider of providers) {
12
+ let detected = null;
13
+ for (const probe of cliProbeCommandsFor(provider)) {
14
+ try {
15
+ detected = await execVersionCommand(probe, probe.timeoutMs);
16
+ break;
17
+ }
18
+ catch {
19
+ // Try the next provider-specific probe.
20
+ }
21
+ }
22
+ results.push({
23
+ provider,
24
+ found: detected !== null,
25
+ version: detected ? versionLine(`${detected.stdout || detected.stderr}`) : "",
26
+ models: detected ? await detectCliModels(provider) : []
27
+ });
28
+ }
29
+ return results;
30
+ }
31
+ function cliProbeCommandsFor(provider) {
32
+ const normalized = provider.toLowerCase();
33
+ if (normalized === "codex") {
34
+ return [
35
+ { command: "codex", args: ["-V"] },
36
+ { command: "codex", args: ["--version"] }
37
+ ];
38
+ }
39
+ if (normalized === "claude") {
40
+ return [
41
+ // Claude Code's Node startup can exceed the default 2s probe on a cold Windows host.
42
+ { command: "claude", args: ["--version"], timeoutMs: 8000 },
43
+ { command: "claude", args: ["-v"], timeoutMs: 8000 }
44
+ ];
45
+ }
46
+ if (normalized === "cursor") {
47
+ return [
48
+ { command: "cursor-agent", args: ["-v"] },
49
+ { command: "agent", args: ["-v"] },
50
+ { command: "cursor-agent", args: ["--version"] },
51
+ { command: "agent", args: ["--version"] }
52
+ ];
53
+ }
54
+ return [
55
+ { command: provider, args: ["--version"] },
56
+ { command: provider, args: ["-V"] }
57
+ ];
58
+ }
59
+ async function execVersionCommand(probe, timeout = 2000, maxBuffer) {
60
+ const directLaunch = process.platform === "win32"
61
+ ? await resolveCursorAgentDirectLaunch(probe.command, probe.args)
62
+ : null;
63
+ if (directLaunch) {
64
+ return await execFileAsync(directLaunch.command, [...directLaunch.args], { timeout, maxBuffer });
65
+ }
66
+ try {
67
+ return await execFileAsync(probe.command, probe.args, { timeout, maxBuffer });
68
+ }
69
+ catch (error) {
70
+ if (process.platform !== "win32") {
71
+ throw error;
72
+ }
73
+ const launch = buildWindowsCmdLaunch(probe.command, probe.args);
74
+ return await execFileAsync(launch.command, [...launch.args], { timeout, maxBuffer });
75
+ }
76
+ }
77
+ function versionLine(output) {
78
+ const lines = output
79
+ .trim()
80
+ .split(/\r?\n/)
81
+ .map((line) => line.trim())
82
+ .filter((line) => line.length > 0);
83
+ return lines.at(-1) ?? "";
84
+ }
85
+ async function detectCliModels(provider) {
86
+ const normalized = provider.toLowerCase();
87
+ try {
88
+ if (normalized === "codex") {
89
+ // Windows installs codex as a .cmd shim, which execFile cannot launch directly.
90
+ const result = await execVersionCommand({ command: "codex", args: ["debug", "models"] }, 10_000, 10 * 1024 * 1024);
91
+ return parseCodexModelCatalog(result.stdout);
92
+ }
93
+ if (normalized === "cursor") {
94
+ const result = await execVersionCommand({ command: "cursor-agent", args: ["models"] }, 10_000);
95
+ return parseCursorModelList(`${result.stdout || result.stderr}`);
96
+ }
97
+ if (normalized === "claude") {
98
+ // Claude Code has no model-listing command; it accepts these aliases and full model IDs.
99
+ const configured = (process.env.FORGE_CLAUDE_MODELS ?? "").split(",").map(model => model.trim()).filter(Boolean);
100
+ return configured.length > 0 ? configured : [...claudeDefaultModels];
101
+ }
102
+ }
103
+ catch {
104
+ return [];
105
+ }
106
+ return [];
107
+ }
108
+ export const claudeDefaultModels = ["sonnet", "opus", "haiku"];
109
+ export function parseCodexModelCatalog(raw) {
110
+ try {
111
+ const parsed = JSON.parse(raw);
112
+ if (!isRecord(parsed) || !Array.isArray(parsed.models)) {
113
+ return [];
114
+ }
115
+ const entries = parsed.models
116
+ .map((entry, index) => {
117
+ if (!isRecord(entry) || typeof entry.slug !== "string") {
118
+ return null;
119
+ }
120
+ const visibility = typeof entry.visibility === "string" ? entry.visibility.toLowerCase() : "list";
121
+ if (visibility !== "list") {
122
+ return null;
123
+ }
124
+ const priority = typeof entry.priority === "number" && Number.isFinite(entry.priority) ? entry.priority : index;
125
+ return { slug: entry.slug, priority, index };
126
+ })
127
+ .filter((entry) => entry !== null)
128
+ .sort((left, right) => left.priority - right.priority || left.index - right.index)
129
+ .map((entry) => entry.slug);
130
+ return uniqueModels(entries);
131
+ }
132
+ catch {
133
+ return [];
134
+ }
135
+ }
136
+ export function parseCursorModelList(raw) {
137
+ return uniqueModels(raw
138
+ .split(/\r?\n/)
139
+ .map((line) => line.trim())
140
+ .filter((line) => line.length > 0 && !line.toLowerCase().startsWith("available models"))
141
+ .map((line) => line.split(/\s+-\s+/, 1)[0]?.trim() ?? "")
142
+ .filter((model) => model.length > 0));
143
+ }
144
+ function uniqueModels(models) {
145
+ const seen = new Set();
146
+ const result = [];
147
+ for (const model of models) {
148
+ const trimmed = model.trim();
149
+ const key = trimmed.toLowerCase();
150
+ if (!trimmed || seen.has(key)) {
151
+ continue;
152
+ }
153
+ seen.add(key);
154
+ result.push(trimmed);
155
+ }
156
+ return result;
157
+ }
158
+ function isRecord(value) {
159
+ return typeof value === "object" && value !== null;
160
+ }
@@ -1,3 +1,4 @@
1
+ import type { AttemptProcessSupervisor } from "./attempt-process-supervisor.js";
1
2
  export interface AspNetRuntimePrebuildPlan {
2
3
  readonly fingerprint: string;
3
4
  readonly receiptPath: string;
@@ -6,9 +7,24 @@ export interface AspNetRuntimePrebuildPlan {
6
7
  readonly cwd: string;
7
8
  readonly environment: Readonly<Record<string, string>>;
8
9
  readonly projectPath: string;
10
+ /** Where the runtime's build output lands and what its receipt verifies: the project's `bin` unless the launch chooses an output. */
11
+ readonly outputDirectory: string;
9
12
  readonly worktreePath: string;
10
13
  readonly inputCommitSha: string;
11
14
  }
15
+ /**
16
+ * The configured launch arguments of a supervised project. An ASP.NET runtime gets its own
17
+ * build output (isolatedRuntimeOutputArguments): its prebuild and `dotnet run` both use it, so an
18
+ * agent's build of the same project writes the default output and never the running runtime's.
19
+ */
20
+ export declare function supervisedRuntimeLaunchArguments(port: {
21
+ readonly name: string;
22
+ readonly adapter: string | null;
23
+ readonly launch: {
24
+ readonly command: string;
25
+ readonly args: readonly string[];
26
+ };
27
+ }): readonly string[];
12
28
  export interface AspNetRuntimePrebuildResult {
13
29
  readonly cacheHit: boolean;
14
30
  readonly receiptPath: string;
@@ -22,6 +38,10 @@ export interface AspNetRuntimeBuildExecutionResult {
22
38
  readonly stderrLogPath: string;
23
39
  }
24
40
  export type AspNetRuntimeBuildExecutor = (plan: AspNetRuntimePrebuildPlan, signal?: AbortSignal) => Promise<AspNetRuntimeBuildExecutionResult>;
41
+ /** Runs one ASP.NET runtime build under the attempt's supervisor, logging only redacted output. */
42
+ export declare function executeAspNetRuntimeBuild(supervisor: AttemptProcessSupervisor, logDirectory: string, plan: AspNetRuntimePrebuildPlan, signal?: AbortSignal, exactSecrets?: readonly string[],
43
+ /** Once the build's supervised tree is up: records it on the build's host load token. */
44
+ onStarted?: (metadataPath: string) => Promise<void>): Promise<AspNetRuntimeBuildExecutionResult>;
25
45
  export declare function createAspNetRuntimePrebuildPlan(options: {
26
46
  readonly command: string;
27
47
  readonly args: readonly string[];
@@ -3,7 +3,63 @@ import { spawn } from "node:child_process";
3
3
  import fs from "node:fs/promises";
4
4
  import path from "node:path";
5
5
  import { ForgeFailureError } from "../session/session.types.js";
6
+ import { redactText } from "../shared/redaction/redaction.js";
7
+ import { replaceFile } from "../shared/fs/replace-file.js";
8
+ import { canonicalExistingPathSync, declaresDotnetOutput, isolatedRuntimeOutputArguments, parseDotnetOutputCommand, projectOutputRoot, projectReferenceIncludes, } from "./dotnet-build-outputs.js";
9
+ /**
10
+ * The configured launch arguments of a supervised project. An ASP.NET runtime gets its own
11
+ * build output (isolatedRuntimeOutputArguments): its prebuild and `dotnet run` both use it, so an
12
+ * agent's build of the same project writes the default output and never the running runtime's.
13
+ */
14
+ export function supervisedRuntimeLaunchArguments(port) {
15
+ return port.adapter === "aspnetcore"
16
+ ? isolatedRuntimeOutputArguments(port.launch.command, port.launch.args, port.name)
17
+ : port.launch.args;
18
+ }
6
19
  const inFlightPrebuilds = new Map();
20
+ /** Runs one ASP.NET runtime build under the attempt's supervisor, logging only redacted output. */
21
+ export async function executeAspNetRuntimeBuild(supervisor, logDirectory, plan, signal, exactSecrets = [],
22
+ /** Once the build's supervised tree is up: records it on the build's host load token. */
23
+ onStarted) {
24
+ const childName = `runtime-build-${plan.fingerprint.slice(-12)}`;
25
+ const stdoutLogPath = path.join(logDirectory, `${childName}.stdout.log`);
26
+ const stderrLogPath = path.join(logDirectory, `${childName}.stderr.log`);
27
+ let stdoutTail = "";
28
+ let stderrTail = "";
29
+ const append = async (target, line) => {
30
+ await fs.appendFile(target, `${redactText(line, exactSecrets)}\n`, { encoding: "utf8", mode: 0o600 });
31
+ };
32
+ const child = await supervisor.startChildReady(childName, {
33
+ command: plan.command,
34
+ args: plan.args,
35
+ cwd: plan.cwd,
36
+ env: plan.environment,
37
+ captureOutput: false,
38
+ }, {
39
+ onStdoutLine: async (line) => {
40
+ stdoutTail = appendRuntimeBuildTail(stdoutTail, redactText(line, exactSecrets));
41
+ await append(stdoutLogPath, line);
42
+ },
43
+ onStderrLine: async (line) => {
44
+ stderrTail = appendRuntimeBuildTail(stderrTail, redactText(line, exactSecrets));
45
+ await append(stderrLogPath, line);
46
+ },
47
+ }, signal, { maxStartAttempts: 2, retryDelayMs: 250 });
48
+ await onStarted?.(child.metadataPath);
49
+ const result = await child.result;
50
+ return {
51
+ exitCode: result.exitCode,
52
+ stdoutTail: appendRuntimeBuildTail(stdoutTail, redactText(result.stdout, exactSecrets)),
53
+ stderrTail: appendRuntimeBuildTail(stderrTail, redactText(result.stderr, exactSecrets)),
54
+ stdoutLogPath,
55
+ stderrLogPath,
56
+ };
57
+ }
58
+ function appendRuntimeBuildTail(current, value) {
59
+ if (!value)
60
+ return current;
61
+ return `${current}${current ? "\n" : ""}${value}`.slice(-4_000);
62
+ }
7
63
  export function createAspNetRuntimePrebuildPlan(options) {
8
64
  if (!isDotnetRun(options.command, options.args))
9
65
  return null;
@@ -34,18 +90,46 @@ export function createAspNetRuntimePrebuildPlan(options) {
34
90
  args: buildArgs,
35
91
  environment: buildEnvironmentContract(options.environment ?? {}),
36
92
  })).digest("hex")}`;
93
+ const outputDirectory = runtimeOutputDirectory(options, projectPath, projectDirectory, normalizedWorktree);
94
+ // A chosen output (the isolated OutDir, or the launch's own) keeps its own receipt, verifying only its own files.
95
+ const receiptName = outputDirectory === path.join(projectDirectory, "bin")
96
+ ? ".forge-runtime-build.json"
97
+ : `.forge-runtime-build.${createHash("sha256").update(path.relative(projectDirectory, outputDirectory).replaceAll("\\", "/")).digest("hex").slice(0, 12)}.json`;
37
98
  return {
38
99
  fingerprint,
39
- receiptPath: path.join(projectDirectory, "obj", ".forge-runtime-build.json"),
100
+ receiptPath: path.join(projectDirectory, "obj", receiptName),
40
101
  command: options.command,
41
102
  args: buildArgs,
42
103
  cwd: options.cwd,
43
104
  environment: options.environment ?? {},
44
105
  projectPath,
106
+ outputDirectory,
45
107
  worktreePath: normalizedWorktree,
46
108
  inputCommitSha: options.inputCommitSha,
47
109
  };
48
110
  }
111
+ /**
112
+ * Where the runtime's prebuild writes and its `dotnet run --no-build` reads: the launch's own
113
+ * output choice when it makes one (forwardBuildOptions passes it to the build unchanged), otherwise
114
+ * the project's `bin`. A choice the two commands cannot share, or one outside the worktree, is refused.
115
+ */
116
+ function runtimeOutputDirectory(options, projectPath, projectDirectory, worktreePath) {
117
+ const settings = parseDotnetOutputCommand(options.command, options.args, options.cwd, { holder: true })?.settings;
118
+ if (!settings || !declaresDotnetOutput(settings))
119
+ return path.join(projectDirectory, "bin");
120
+ if (settings.output) {
121
+ throw new Error("host_runtime_build_invalid: dotnet run has no --output option, so its prebuild and run could not share that "
122
+ + "directory. Choose the runtime's output with -p:OutDir=<dir>, -p:BaseOutputPath=<dir>, or --artifacts-path <dir> instead.");
123
+ }
124
+ const projectFile = path.extname(projectPath).toLowerCase() === ".csproj" ? projectPath : null;
125
+ const outputDirectory = projectOutputRoot(projectDirectory, projectFile, settings);
126
+ // By real location: a symlink or junction inside the worktree must not carry the output outside it.
127
+ const relative = path.relative(canonicalExistingPathSync(worktreePath), canonicalExistingPathSync(outputDirectory));
128
+ if (relative.startsWith("..") || path.isAbsolute(relative)) {
129
+ throw new Error(`host_runtime_build_invalid: the ASP.NET runtime's build output ${outputDirectory} must remain inside the managed worktree.`);
130
+ }
131
+ return outputDirectory;
132
+ }
49
133
  export async function ensureAspNetRuntimePrebuilt(plan, execute, signal) {
50
134
  const pending = inFlightPrebuilds.get(plan.receiptPath);
51
135
  if (pending)
@@ -101,7 +185,7 @@ async function ensureAspNetRuntimePrebuiltCore(plan, execute, signal) {
101
185
  };
102
186
  await fs.writeFile(temporaryReceipt, `${JSON.stringify(nextReceipt)}\n`, { encoding: "utf8", mode: 0o600 });
103
187
  try {
104
- await fs.rename(temporaryReceipt, plan.receiptPath);
188
+ await replaceFile(temporaryReceipt, plan.receiptPath);
105
189
  }
106
190
  finally {
107
191
  await fs.rm(temporaryReceipt, { force: true }).catch(() => undefined);
@@ -158,9 +242,12 @@ function readOptionValue(args, option) {
158
242
  const argument = args[index];
159
243
  return argument.startsWith(`${option}=`) ? argument.slice(option.length + 1) : args[index + 1] ?? null;
160
244
  }
245
+ /** The launch's build-shaping options, output choices included, so the prebuild writes where the run reads. */
161
246
  function forwardBuildOptions(args) {
162
247
  const forwarded = [];
163
- const optionsWithValues = new Set(["-c", "--configuration", "-f", "--framework", "-r", "--runtime", "--arch", "--os"]);
248
+ const optionsWithValues = new Set([
249
+ "-c", "--configuration", "-f", "--framework", "-r", "--runtime", "--arch", "--os", "--artifacts-path",
250
+ ]);
164
251
  for (let index = 1; index < args.length; index += 1) {
165
252
  const argument = args[index];
166
253
  if (argument === "--")
@@ -179,9 +266,9 @@ function forwardBuildOptions(args) {
179
266
  }
180
267
  continue;
181
268
  }
269
+ // Every MSBuild property spelling: -p:, --property:, /p:, and the rest that dotnet accepts.
182
270
  if ([...optionsWithValues].some(option => argument.startsWith(`${option}=`))
183
- || argument.startsWith("-p:")
184
- || argument.startsWith("/p:")) {
271
+ || /^(?:-{1,2}|\/)(?:p|property):/iu.test(argument)) {
185
272
  forwarded.push(argument);
186
273
  }
187
274
  }
@@ -236,9 +323,13 @@ async function projectSourceDigest(plan, projectDirectory) {
236
323
  const worktree = path.resolve(plan.worktreePath);
237
324
  const directories = await projectSourceDirectories(plan, projectDirectory);
238
325
  const files = new Set();
326
+ // The runtime's own output is never source, even outside bin: a per-project output sits at the same place in every project.
327
+ const relativeOutput = path.relative(projectDirectory, plan.outputDirectory);
328
+ const perProjectOutput = relativeOutput !== "" && containedIn(projectDirectory, plan.outputDirectory);
239
329
  for (const directory of directories) {
240
330
  const collected = [];
241
- await collectInputFiles(directory, directory, collected);
331
+ const excluded = new Set([path.resolve(plan.outputDirectory), ...(perProjectOutput ? [path.join(directory, relativeOutput)] : [])]);
332
+ await collectInputFiles(directory, directory, collected, excluded);
242
333
  for (const file of collected)
243
334
  files.add(file);
244
335
  for (const buildFile of await ancestorBuildFiles(directory, worktree))
@@ -290,19 +381,6 @@ async function projectFilesIn(directory) {
290
381
  .filter(entry => entry.isFile() && msbuildProjectExtensions.has(path.extname(entry.name).toLowerCase()))
291
382
  .map(entry => path.join(directory, entry.name));
292
383
  }
293
- function projectReferenceIncludes(projectXml) {
294
- const withoutComments = projectXml.replaceAll(/<!--[\s\S]*?-->/gu, "");
295
- const includes = [];
296
- for (const match of withoutComments.matchAll(/<ProjectReference\b[^>]*?\bInclude\s*=\s*(?:"([^"]*)"|'([^']*)')/giu)) {
297
- const value = match[1] ?? match[2] ?? "";
298
- for (const part of value.split(";")) {
299
- const trimmed = part.trim();
300
- if (trimmed)
301
- includes.push(trimmed);
302
- }
303
- }
304
- return includes;
305
- }
306
384
  async function ancestorBuildFiles(directory, worktree) {
307
385
  const found = [];
308
386
  let current = path.resolve(directory);
@@ -325,13 +403,13 @@ function containedIn(root, candidate) {
325
403
  const relative = path.relative(root, candidate);
326
404
  return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
327
405
  }
328
- async function collectInputFiles(root, directory, files) {
406
+ async function collectInputFiles(root, directory, files, excluded) {
329
407
  const entries = await fs.readdir(directory, { withFileTypes: true }).catch(() => []);
330
408
  for (const entry of entries) {
331
409
  const absolute = path.join(directory, entry.name);
332
410
  if (entry.isDirectory()) {
333
- if (!["bin", "obj", "node_modules", ".git", "TestResults"].includes(entry.name)) {
334
- await collectInputFiles(root, absolute, files);
411
+ if (!["bin", "obj", "node_modules", ".git", "TestResults"].includes(entry.name) && !excluded.has(absolute)) {
412
+ await collectInputFiles(root, absolute, files, excluded);
335
413
  }
336
414
  }
337
415
  else if (entry.isFile()) {
@@ -343,9 +421,8 @@ async function collectAspNetBuildOutputs(plan) {
343
421
  const projectDirectory = path.extname(plan.projectPath).toLowerCase() === ".csproj"
344
422
  ? path.dirname(plan.projectPath)
345
423
  : plan.projectPath;
346
- const outputRoot = path.join(projectDirectory, "bin");
347
424
  const outputs = [];
348
- await collectOutputFiles(outputRoot, projectDirectory, outputs);
425
+ await collectOutputFiles(plan.outputDirectory, projectDirectory, outputs);
349
426
  return outputs.sort((left, right) => left.path.localeCompare(right.path));
350
427
  }
351
428
  async function collectOutputFiles(directory, projectDirectory, outputs) {
@@ -371,9 +448,10 @@ async function aspNetOutputsMatch(plan, outputs) {
371
448
  ? path.dirname(plan.projectPath)
372
449
  : plan.projectPath;
373
450
  for (const output of outputs) {
451
+ // Paths are relative to the project, and may leave it for a launch-chosen output, never the plan's output directory.
374
452
  const absolute = path.resolve(projectDirectory, output.path);
375
- const relative = path.relative(projectDirectory, absolute);
376
- if (relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative))
453
+ const relative = path.relative(plan.outputDirectory, absolute);
454
+ if (relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative))
377
455
  return false;
378
456
  const stat = await fs.stat(absolute).catch(() => null);
379
457
  if (!stat?.isFile() || stat.size !== output.size)
@@ -75,7 +75,7 @@ export interface NativeTestClusterAdmin {
75
75
  readonly username: string;
76
76
  readonly password: string;
77
77
  }
78
- export declare function nativeTestClusterAdmin(fallback: NativeTestPostgresFallback): NativeTestClusterAdmin;
78
+ export declare function nativeTestClusterAdmin(fallback: Pick<NativeTestPostgresFallback, "connectionString" | "endpoint">): NativeTestClusterAdmin;
79
79
  /** Runs SQL through the psql that ships with the PostgreSQL install hosting the native test cluster. */
80
80
  export declare function psqlSqlRunner(admin: NativeTestClusterAdmin, psqlPath: string, timeoutMs?: number): AttemptDatabaseSqlRunner;
81
81
  /** psql beside the cluster's pg_ctl: FORGE_NATIVE_TEST_POSTGRES_PSQL, a Windows install, or PATH. */
@@ -1,7 +1,13 @@
1
+ import { ForgeFailureError } from "../session/session.types.js";
1
2
  import type { AttemptProcessChildHandle, AttemptProcessSupervisor } from "./attempt-process-supervisor.js";
2
3
  import type { HostPortLeaseOwner } from "./host-port-broker.js";
3
4
  import { HostListenerInspector } from "./host-listener-inspector.js";
5
+ import type { ProviderProcessHandlers, ProviderProcessRunner, ProviderProcessRunRequest, ProviderProcessRunResult } from "../session/provider-cli/provider-cli.process.js";
4
6
  import type { HostListenerOwnership, NodeRuntimeCommandLauncher, NodeRuntimeLaunchRequest, NodeRuntimeReadinessDiagnostics } from "./node-host-runtime-adapter.js";
7
+ export declare function brokeredHostPorts(ports: readonly {
8
+ readonly hostPort: number;
9
+ }[]): ReadonlySet<number>;
10
+ export declare function isolationViolationError(detail: string): ForgeFailureError;
5
11
  /** Launches one explicitly configured HTTP project beneath the attempt coordinator. */
6
12
  export declare class AttemptNodeRuntimeLauncher implements NodeRuntimeCommandLauncher<AttemptProcessChildHandle> {
7
13
  private readonly supervisor;
@@ -10,9 +16,39 @@ export declare class AttemptNodeRuntimeLauncher implements NodeRuntimeCommandLau
10
16
  private readonly listenerInspector;
11
17
  private readonly exactSecrets;
12
18
  private readonly diagnosticsByChild;
19
+ private readonly launchedChildren;
13
20
  constructor(supervisor: AttemptProcessSupervisor, owner: HostPortLeaseOwner, logDirectory: string, listenerInspector?: HostListenerInspector, exactSecrets?: readonly string[]);
14
21
  launch(request: NodeRuntimeLaunchRequest, signal?: AbortSignal): Promise<AttemptProcessChildHandle>;
15
22
  inspectListener(child: AttemptProcessChildHandle, request: NodeRuntimeLaunchRequest): Promise<HostListenerOwnership>;
23
+ /**
24
+ * Every loopback TCP port held by the process trees this launcher started that are still
25
+ * running, brokered or not. A launch the port broker retried leaves an exited child behind;
26
+ * it holds nothing and is skipped.
27
+ */
28
+ ownedListenerPorts(): Promise<readonly number[]>;
29
+ /**
30
+ * Why these process trees break isolation, or null when they do not: a listener the port
31
+ * broker did not assign, or listeners that could not be inspected (unproven isolation).
32
+ */
33
+ unbrokeredListenerViolation(brokered: ReadonlySet<number>): Promise<string | null>;
34
+ /**
35
+ * Re-audits these process trees on an interval until stopped, so a listener opened after
36
+ * readiness (say, a fixed admin port bound once a database connects) is caught within one
37
+ * interval. `brokered` returning null skips a tick. The first violation is reported once and
38
+ * ends the monitor. Returns the function that stops it.
39
+ */
40
+ monitorListeners(brokered: () => ReadonlySet<number> | null, onViolation: (detail: string) => Promise<void>): () => void;
16
41
  stop(child: AttemptProcessChildHandle): Promise<void>;
17
42
  readinessDiagnostics(child: AttemptProcessChildHandle): Promise<NodeRuntimeReadinessDiagnostics>;
18
43
  }
44
+ /** Runs a provider process beneath an attempt supervisor; an analysis-only provider may open no loopback listener. */
45
+ export declare class AttemptSupervisedProviderProcessRunner implements ProviderProcessRunner {
46
+ private readonly supervisor;
47
+ private readonly owner;
48
+ private readonly listenerInspector;
49
+ private readonly enforceNoListeners;
50
+ private readonly onProcessTreeStarted;
51
+ constructor(supervisor: AttemptProcessSupervisor, owner: HostPortLeaseOwner, listenerInspector: HostListenerInspector, enforceNoListeners: boolean, onProcessTreeStarted: () => void);
52
+ run(request: ProviderProcessRunRequest, handlers?: ProviderProcessHandlers, signal?: AbortSignal): Promise<ProviderProcessRunResult>;
53
+ private awaitProviderResult;
54
+ }