@loucompanion/forge-bridge 0.1.3-dev.8687c5099dce → 0.1.3-dev.88e93f53db5b

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 (75) hide show
  1. package/README.md +18 -1
  2. package/dist/bridge/bridge.base.d.ts +2 -0
  3. package/dist/bridge/bridge.service.d.ts +25 -1
  4. package/dist/bridge/bridge.service.js +341 -74
  5. package/dist/bridge/bridge.types.d.ts +4 -0
  6. package/dist/cleanup/cleanup.service.d.ts +1 -0
  7. package/dist/cleanup/cleanup.service.js +70 -9
  8. package/dist/cli/cli.service.js +9 -4
  9. package/dist/runtime/aspnet-runtime-prebuild.d.ts +36 -0
  10. package/dist/runtime/aspnet-runtime-prebuild.js +340 -0
  11. package/dist/runtime/attempt-node-runtime-launcher.js +5 -1
  12. package/dist/runtime/attempt-process-supervisor.d.ts +11 -0
  13. package/dist/runtime/attempt-process-supervisor.js +36 -2
  14. package/dist/runtime/host-listener-inspector.d.ts +2 -0
  15. package/dist/runtime/host-listener-inspector.js +25 -0
  16. package/dist/runtime/host-runtime-lease.d.ts +66 -5
  17. package/dist/runtime/host-runtime-lease.js +714 -38
  18. package/dist/runtime/memory-capacity.d.ts +68 -0
  19. package/dist/runtime/memory-capacity.js +121 -0
  20. package/dist/runtime/node-host-runtime-adapter.d.ts +3 -0
  21. package/dist/runtime/node-host-runtime-adapter.js +24 -8
  22. package/dist/runtime/playwright-host-runtime-adapter.d.ts +1 -0
  23. package/dist/runtime/playwright-host-runtime-adapter.js +5 -0
  24. package/dist/runtime/workspace-resource-estimator.d.ts +17 -0
  25. package/dist/runtime/workspace-resource-estimator.js +174 -0
  26. package/dist/sandbox/preflight.d.ts +31 -1
  27. package/dist/sandbox/preflight.js +237 -51
  28. package/dist/sandbox/repository-lock.js +4 -2
  29. package/dist/sandbox/sandbox.types.d.ts +7 -0
  30. package/dist/session/managed-attempt-tools.d.ts +7 -1
  31. package/dist/session/managed-attempt-tools.js +257 -13
  32. package/dist/session/managed-build-coordinator.d.ts +5 -0
  33. package/dist/session/managed-build-coordinator.js +105 -0
  34. package/dist/session/managed-build-receipt.d.ts +21 -0
  35. package/dist/session/managed-build-receipt.js +335 -0
  36. package/dist/session/phase-completion.artifacts.d.ts +17 -0
  37. package/dist/session/phase-completion.artifacts.js +224 -22
  38. package/dist/session/phase-completion.prompts.js +2 -2
  39. package/dist/session/phase-completion.runtime.js +10 -3
  40. package/dist/session/phase-completion.schemas.js +1 -1
  41. package/dist/session/phase-completion.validation.js +7 -3
  42. package/dist/session/provider-cli/ci-repair-readiness.d.ts +6 -0
  43. package/dist/session/provider-cli/ci-repair-readiness.js +12 -2
  44. package/dist/session/provider-cli/provider-cli.artifacts.d.ts +2 -1
  45. package/dist/session/provider-cli/provider-cli.artifacts.js +37 -3
  46. package/dist/session/provider-cli/provider-cli.process.d.ts +7 -0
  47. package/dist/session/provider-cli/provider-cli.process.js +218 -17
  48. package/dist/session/provider-cli/provider-cli.prompts.js +17 -4
  49. package/dist/session/provider-cli/provider-cli.runtime.js +3 -1
  50. package/dist/session/provider-cli/provider-cli.service.d.ts +5 -2
  51. package/dist/session/provider-cli/provider-cli.service.js +83 -34
  52. package/dist/session/provider-cli/provider-output-state.js +61 -14
  53. package/dist/session/provider-cli/provider-usage.d.ts +7 -0
  54. package/dist/session/provider-cli/provider-usage.js +28 -5
  55. package/dist/session/session-redaction.js +16 -1
  56. package/dist/session/session.service.js +81 -9
  57. package/dist/session/session.types.d.ts +15 -0
  58. package/dist/session/session.types.js +3 -1
  59. package/dist/shared/format/format-bytes.d.ts +1 -0
  60. package/dist/shared/format/format-bytes.js +9 -0
  61. package/dist/shared/path/path.d.ts +1 -0
  62. package/dist/shared/path/path.js +18 -0
  63. package/dist/shared/process/host-process-supervisor.d.ts +2 -0
  64. package/dist/shared/process/host-process-supervisor.js +57 -9
  65. package/dist/shared/redaction/redaction.js +6 -1
  66. package/dist/version.d.ts +1 -1
  67. package/dist/version.js +1 -1
  68. package/dist/worktree/dependency-warmer.d.ts +18 -0
  69. package/dist/worktree/dependency-warmer.js +218 -8
  70. package/dist/worktree/index.d.ts +1 -1
  71. package/dist/worktree/worktree.service.d.ts +2 -0
  72. package/dist/worktree/worktree.service.js +158 -17
  73. package/dist/worktree/worktree.types.d.ts +2 -0
  74. package/package.json +3 -2
  75. package/runtime/windows-job-supervisor.ps1 +89 -1
@@ -2,16 +2,24 @@ import { createHash, randomUUID } from "node:crypto";
2
2
  import fs from "node:fs/promises";
3
3
  import path from "node:path";
4
4
  import { resetGeneratedOutputs } from "../runtime/generated-output-reset.js";
5
+ import { ManagedBuildCoordinator } from "./managed-build-coordinator.js";
6
+ import { managedBuildConfiguration, publishManagedBuildReceipt, verifyManagedBuildReceipt, } from "./managed-build-receipt.js";
5
7
  import { StreamingProviderProcessRunner } from "./provider-cli/provider-cli.process.js";
6
8
  const managedCommandNames = new Set(["forge.run_managed_command", "run_managed_command"]);
7
9
  const startManagedCommandNames = new Set(["forge.start_managed_command", "start_managed_command"]);
8
10
  const getManagedCommandNames = new Set(["forge.get_managed_command", "get_managed_command"]);
9
11
  const waitManagedCommandNames = new Set(["forge.wait_managed_command", "wait_managed_command"]);
12
+ const startManagedVerificationNames = new Set(["forge.start_managed_verification", "start_managed_verification"]);
10
13
  const resetGeneratedOutputNames = new Set(["forge.reset_generated_outputs", "reset_generated_outputs"]);
11
14
  const maximumCapturedCharacters = 200_000;
12
15
  const maximumReturnedOutputCharacters = 4_000;
13
16
  const maximumReportedFailedTests = 50;
14
- const maximumSynchronousWaitMs = 240_000;
17
+ // Keep a wait slice comfortably below the MCP transport deadline. The managed
18
+ // process remains supervised and its durable receipt continues to update after
19
+ // this call returns, so a shorter slice avoids converting healthy long-running
20
+ // commands into ambiguous MCP failures.
21
+ const maximumSynchronousWaitMs = 45_000;
22
+ const managedCommandRetryAfterMs = 60_000;
15
23
  const managedCommandLaunchTimeoutMs = 60_000;
16
24
  const managedCommandProgressPersistIntervalMs = 5_000;
17
25
  const managedCommandReceiptPollIntervalMs = 1_000;
@@ -24,6 +32,7 @@ const terminalManagedCommandStatuses = new Set([
24
32
  "timeout_termination_failed",
25
33
  "runner_error",
26
34
  ]);
35
+ const managedVerificationBuildCoverage = "forge_dotnet_test_graph_v1";
27
36
  const managedCommandTasks = new Map();
28
37
  export const managedAttemptToolNames = [
29
38
  "forge.run_managed_command",
@@ -34,6 +43,8 @@ export const managedAttemptToolNames = [
34
43
  "get_managed_command",
35
44
  "forge.wait_managed_command",
36
45
  "wait_managed_command",
46
+ "forge.start_managed_verification",
47
+ "start_managed_verification",
37
48
  "forge.reset_generated_outputs",
38
49
  "reset_generated_outputs",
39
50
  ];
@@ -42,15 +53,39 @@ export function isManagedAttemptTool(name) {
42
53
  || startManagedCommandNames.has(name)
43
54
  || getManagedCommandNames.has(name)
44
55
  || waitManagedCommandNames.has(name)
56
+ || startManagedVerificationNames.has(name)
45
57
  || resetGeneratedOutputNames.has(name);
46
58
  }
47
59
  export function managedAttemptToolDefinition(name) {
60
+ if (startManagedVerificationNames.has(name)) {
61
+ return {
62
+ name,
63
+ description: "Start a canonical Forge verification profile with runner-owned cwd, arguments, attempt output, timeout, and process supervision. Prefer this over reconstructing broad .NET commands. Continue independent work, then use forge.wait_managed_command for a transport-safe terminal receipt.",
64
+ inputSchema: {
65
+ type: "object",
66
+ additionalProperties: false,
67
+ required: ["profile"],
68
+ properties: {
69
+ profile: {
70
+ type: "string",
71
+ enum: ["dotnet_unit", "dotnet_contract", "dotnet_api_component", "dotnet_orchestration", "dotnet_infrastructure", "dotnet_solution"],
72
+ },
73
+ shard_count: { type: "integer", minimum: 1, maximum: 32, default: 1 },
74
+ shard_index: { type: "integer", minimum: 0, maximum: 31, default: 0 },
75
+ run_all_shards: { type: "boolean", default: false },
76
+ max_parallelism: { type: "integer", minimum: 1, maximum: 4, default: 2 },
77
+ no_build: { type: "boolean", default: false },
78
+ timeout_ms: { type: "integer", minimum: 1000, maximum: 7200000 },
79
+ },
80
+ },
81
+ };
82
+ }
48
83
  if (managedCommandNames.has(name) || startManagedCommandNames.has(name)) {
49
84
  return {
50
85
  name,
51
86
  description: startManagedCommandNames.has(name)
52
- ? "Start a long command in an attempt-owned process tree and return a durable command ID immediately. Continue independent work, then call forge.wait_managed_command once for its terminal receipt."
53
- : "Run a short command in an attempt-owned process tree. Commands with a timeout above four minutes automatically start asynchronously; continue independent work, then call forge.wait_managed_command once for the durable result.",
87
+ ? "Start a long command in an attempt-owned process tree and return a durable command ID immediately. Continue independent work, then use forge.wait_managed_command for a transport-safe terminal receipt."
88
+ : "Run a short command in an attempt-owned process tree. Commands with a timeout above four minutes automatically start asynchronously; continue independent work, then use forge.wait_managed_command for the durable result.",
54
89
  inputSchema: {
55
90
  type: "object",
56
91
  additionalProperties: false,
@@ -81,14 +116,14 @@ export function managedAttemptToolDefinition(name) {
81
116
  if (waitManagedCommandNames.has(name)) {
82
117
  return {
83
118
  name,
84
- description: "Wait once for a command started by Forge's managed command runner to reach a terminal state. Live progress remains in the durable receipt/UI without repeated provider messages; this call returns the single terminal result.",
119
+ description: "Wait up to 45 seconds for a managed command terminal receipt. If it remains active, the call succeeds with command_continues=true and retry_after_ms; continue independent work or wait again later. Live progress remains in the durable receipt/UI; do not poll get_managed_command.",
85
120
  inputSchema: {
86
121
  type: "object",
87
122
  additionalProperties: false,
88
123
  required: ["command_id"],
89
124
  properties: {
90
125
  command_id: { type: "string", minLength: 1 },
91
- wait_timeout_ms: { type: "integer", minimum: 1000, maximum: 7200000, default: 7200000 },
126
+ wait_timeout_ms: { type: "integer", minimum: 1000, maximum: 45000, default: 45000 },
92
127
  },
93
128
  },
94
129
  };
@@ -123,10 +158,15 @@ export async function callManagedAttemptTool(name, input, worktreePath) {
123
158
  if (waitManagedCommandNames.has(name)) {
124
159
  return await waitManagedCommand(input);
125
160
  }
161
+ if (startManagedVerificationNames.has(name)) {
162
+ return await startManagedVerification(input, worktreePath);
163
+ }
126
164
  if (!managedCommandNames.has(name) && !startManagedCommandNames.has(name)) {
127
165
  throw new Error(`Unknown managed attempt tool: ${name}`);
128
166
  }
129
- const record = asRecord(input);
167
+ return await launchManagedCommand(asRecord(input), worktreePath, startManagedCommandNames.has(name));
168
+ }
169
+ async function launchManagedCommand(record, worktreePath, forceAsync, verificationProfile, buildProducingOverride, buildReceiptReuse) {
130
170
  const command = requiredInputString(record, "command");
131
171
  const args = requiredStringArray(record, "args");
132
172
  const timeoutMs = optionalTimeout(record.timeout_ms);
@@ -146,8 +186,12 @@ export async function callManagedAttemptTool(name, input, worktreePath) {
146
186
  metadataPath,
147
187
  receiptPath,
148
188
  startedAt: Date.now(),
189
+ verificationProfile,
190
+ worktreePath,
191
+ buildProducing: buildProducingOverride ?? isBuildProducingManagedCommand(command, args),
192
+ buildReceiptReuse,
149
193
  };
150
- if (startManagedCommandNames.has(name) || timeoutMs > maximumSynchronousWaitMs) {
194
+ if (forceAsync || timeoutMs > maximumSynchronousWaitMs) {
151
195
  const started = managedCommandResult({
152
196
  ...invocation,
153
197
  timedOut: false,
@@ -164,13 +208,116 @@ export async function callManagedAttemptTool(name, input, worktreePath) {
164
208
  ...managedCommandPublicResult(started),
165
209
  content: [{
166
210
  type: "text",
167
- text: `Forge managed command ${commandId} started asynchronously. Continue independent work, then call forge.wait_managed_command once with this command_id for the terminal receipt.`,
211
+ text: `Forge managed command ${commandId} started asynchronously. Continue independent work, then use forge.wait_managed_command with this command_id for a transport-safe terminal receipt.`,
168
212
  }],
169
213
  };
170
214
  }
171
215
  return await executeManagedCommand(invocation);
172
216
  }
217
+ async function startManagedVerification(input, worktreePath) {
218
+ const record = asRecord(input);
219
+ const profile = requiredInputString(record, "profile");
220
+ const shardCount = optionalBoundedInteger(record.shard_count, "shard_count", 1, 32, 1);
221
+ const shardIndex = optionalBoundedInteger(record.shard_index, "shard_index", 0, 31, 0);
222
+ if (shardIndex >= shardCount) {
223
+ throw new Error("managed_verification_invalid: shard_index must be less than shard_count.");
224
+ }
225
+ const noBuild = optionalBoolean(record.no_build, "no_build", false);
226
+ const runAllShards = optionalBoolean(record.run_all_shards, "run_all_shards", false);
227
+ const maxParallelism = optionalBoundedInteger(record.max_parallelism, "max_parallelism", 1, 4, 2);
228
+ if (runAllShards && shardCount < 2) {
229
+ throw new Error("managed_verification_invalid: run_all_shards requires shard_count of at least 2.");
230
+ }
231
+ if (runAllShards && shardIndex !== 0) {
232
+ throw new Error("managed_verification_invalid: shard_index must be 0 when run_all_shards is enabled.");
233
+ }
234
+ if (runAllShards && noBuild) {
235
+ throw new Error("managed_verification_invalid: run_all_shards owns the single prerequisite build and cannot be combined with no_build.");
236
+ }
237
+ const outputDirectory = requiredAttemptEnvironment("FORGE_TEST_OUTPUT_DIR");
238
+ const profileCommand = buildManagedVerificationCommand(profile, outputDirectory, shardCount, shardIndex, noBuild, runAllShards, maxParallelism);
239
+ const buildReceiptReuse = noBuild
240
+ ? await verifyManagedBuildReceipt({
241
+ worktreePath,
242
+ configuration: managedBuildConfiguration(profileCommand.command, profileCommand.args),
243
+ requiredCoverage: managedVerificationBuildCoverage,
244
+ })
245
+ : undefined;
246
+ return await launchManagedCommand({
247
+ command: profileCommand.command,
248
+ args: profileCommand.args,
249
+ timeout_ms: record.timeout_ms ?? profileCommand.timeoutMs,
250
+ }, worktreePath, true, profile, !noBuild, buildReceiptReuse);
251
+ }
252
+ export function buildManagedVerificationCommand(profile, outputDirectory, shardCount, shardIndex, noBuild, runAllShards = false, maxParallelism = 2) {
253
+ if (profile === "dotnet_solution") {
254
+ if (runAllShards) {
255
+ throw new Error("managed_verification_invalid: dotnet_solution does not support run_all_shards; select a test tier instead.");
256
+ }
257
+ if (shardCount !== 1 || shardIndex !== 0) {
258
+ throw new Error("managed_verification_invalid: dotnet_solution does not accept sharding; select a test tier instead.");
259
+ }
260
+ const command = process.platform === "win32" ? "powershell.exe" : "pwsh";
261
+ const args = [
262
+ "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", "scripts/run-dotnet-test-suite.ps1",
263
+ "-ResultsDirectory", outputDirectory,
264
+ "-MaxParallelism", String(maxParallelism),
265
+ ];
266
+ if (noBuild)
267
+ args.push("-NoBuild");
268
+ return { command, args, timeoutMs: 2_700_000 };
269
+ }
270
+ const tiers = {
271
+ dotnet_unit: "Unit",
272
+ dotnet_contract: "Contract",
273
+ dotnet_api_component: "ApiComponent",
274
+ dotnet_orchestration: "Orchestration",
275
+ dotnet_infrastructure: "Infrastructure",
276
+ };
277
+ const tier = tiers[profile];
278
+ if (!tier)
279
+ throw new Error(`managed_verification_invalid: unsupported profile ${profile}.`);
280
+ const command = process.platform === "win32" ? "powershell.exe" : "pwsh";
281
+ if (runAllShards) {
282
+ return {
283
+ command,
284
+ args: [
285
+ "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", "scripts/run-dotnet-test-tier-set.ps1",
286
+ "-Tier", tier,
287
+ "-ResultsDirectory", outputDirectory,
288
+ "-ShardCount", String(shardCount),
289
+ "-MaxParallelism", String(maxParallelism),
290
+ ],
291
+ timeoutMs: tier === "Unit" || tier === "Contract" ? 900_000 : 2_700_000,
292
+ };
293
+ }
294
+ const args = [
295
+ "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", "scripts/run-dotnet-test-tier.ps1",
296
+ "-Tier", tier,
297
+ "-ResultsDirectory", outputDirectory,
298
+ "-ShardCount", String(shardCount),
299
+ "-ShardIndex", String(shardIndex),
300
+ ];
301
+ if (noBuild)
302
+ args.push("-NoBuild");
303
+ return { command, args, timeoutMs: tier === "Unit" || tier === "Contract" ? 900_000 : 2_700_000 };
304
+ }
173
305
  async function executeManagedCommand(invocation) {
306
+ if (!invocation.buildProducing)
307
+ return await executeManagedCommandProcess(invocation);
308
+ return await new ManagedBuildCoordinator().withBuildSlot(invocation.worktreePath, async (buildQueueWaitMs) => await executeManagedCommandProcess({ ...invocation, buildQueueWaitMs }), async () => {
309
+ const waiting = managedCommandResult({
310
+ ...invocation,
311
+ timedOut: false,
312
+ status: "waiting_for_build_slot",
313
+ exitCode: null,
314
+ stdout: "",
315
+ stderr: "",
316
+ });
317
+ await persistManagedCommandReceipt(invocation.receiptPath, waiting.structuredContent);
318
+ });
319
+ }
320
+ async function executeManagedCommandProcess(invocation) {
174
321
  const environment = inheritedEnvironment({
175
322
  FORGE_RUNTIME_MODE: "host",
176
323
  FORGE_RESOURCE_LEASE_ID: requiredAttemptEnvironment("FORGE_RESOURCE_LEASE_ID"),
@@ -244,6 +391,16 @@ async function executeManagedCommand(invocation) {
244
391
  }, controller.signal);
245
392
  await progressPersistence;
246
393
  const status = timedOut ? "timed_out" : result.exitCode === 0 ? "pass" : "fail";
394
+ const receiptCoverage = managedBuildReceiptCoverage(invocation);
395
+ const buildReceipt = status === "pass" && receiptCoverage
396
+ ? await publishManagedBuildReceipt({
397
+ worktreePath: invocation.worktreePath,
398
+ command: invocation.command,
399
+ args: invocation.args,
400
+ configuration: managedBuildConfiguration(invocation.command, invocation.args),
401
+ coverage: receiptCoverage,
402
+ })
403
+ : invocation.buildReceiptReuse;
247
404
  const receipt = managedCommandResult({
248
405
  ...invocation,
249
406
  timedOut,
@@ -254,6 +411,8 @@ async function executeManagedCommand(invocation) {
254
411
  outputRevision,
255
412
  lastOutputAt,
256
413
  lastOutputStream,
414
+ buildReceipt,
415
+ buildReceiptReused: invocation.buildReceiptReuse !== undefined,
257
416
  });
258
417
  await persistManagedCommandReceipt(invocation.receiptPath, receipt.structuredContent);
259
418
  return managedCommandPublicResult(receipt);
@@ -321,7 +480,8 @@ async function readManagedCommand(input) {
321
480
  async function waitManagedCommand(input) {
322
481
  const record = asRecord(input);
323
482
  const commandId = validatedCommandId(record);
324
- const waitTimeoutMs = optionalWaitTimeout(record.wait_timeout_ms);
483
+ const requestedWaitTimeoutMs = optionalWaitTimeout(record.wait_timeout_ms);
484
+ const waitTimeoutMs = Math.min(requestedWaitTimeoutMs, maximumSynchronousWaitMs);
325
485
  const deadline = Date.now() + waitTimeoutMs;
326
486
  const receiptPath = managedCommandReceiptPath(requiredAttemptEnvironment("FORGE_LOG_DIR"), commandId);
327
487
  const task = managedCommandTasks.get(commandId);
@@ -345,8 +505,17 @@ async function waitManagedCommand(input) {
345
505
  ...receipt,
346
506
  content: [{
347
507
  type: "text",
348
- text: `Forge is still supervising managed command ${commandId} after waiting ${waitTimeoutMs}ms. Its durable receipt remains at ${receiptPath}.`,
508
+ text: `Forge is still supervising managed command ${commandId} after this ${waitTimeoutMs}ms transport-safe wait. Continue independent work or call forge.wait_managed_command again after ${managedCommandRetryAfterMs}ms. Its durable receipt remains at ${receiptPath}.`,
349
509
  }],
510
+ structuredContent: {
511
+ ...receipt.structuredContent,
512
+ command_continues: true,
513
+ terminal: false,
514
+ wait_timeout_ms: waitTimeoutMs,
515
+ requested_wait_timeout_ms: requestedWaitTimeoutMs,
516
+ retry_after_ms: managedCommandRetryAfterMs,
517
+ },
518
+ isError: false,
350
519
  };
351
520
  }
352
521
  function managedCommandReceiptPath(logDirectory, commandId) {
@@ -415,6 +584,20 @@ function managedCommandResult(values) {
415
584
  last_output_stream: values.lastOutputStream ?? null,
416
585
  supervisor_metadata_path: values.metadataPath,
417
586
  receipt_path: values.receiptPath,
587
+ verification_profile: values.verificationProfile ?? null,
588
+ verification_profile_runner_authored: values.verificationProfile !== undefined,
589
+ build_producing: values.buildProducing,
590
+ build_coordination: values.buildProducing ? "per_worktree_exclusive" : null,
591
+ build_queue_wait_ms: values.buildQueueWaitMs ?? 0,
592
+ build_receipt_reused: values.buildReceiptReused ?? false,
593
+ build_receipt: values.buildReceipt ? {
594
+ fingerprint: values.buildReceipt.fingerprint,
595
+ receipt_path: values.buildReceipt.receiptPath,
596
+ producer_command: values.buildReceipt.producerCommand,
597
+ configuration: values.buildReceipt.configuration,
598
+ coverage: values.buildReceipt.coverage,
599
+ output_count: values.buildReceipt.outputCount,
600
+ } : null,
418
601
  runtime_configuration: managedRuntimeConfiguration(),
419
602
  process_tree_terminated: values.status === "timed_out" ? true : values.timedOut ? false : undefined,
420
603
  },
@@ -496,6 +679,52 @@ function inheritedEnvironment(overrides) {
496
679
  }
497
680
  return { ...env, ...overrides };
498
681
  }
682
+ export function isBuildProducingManagedCommand(command, args) {
683
+ const executable = path.basename(command).toLowerCase();
684
+ if (executable === "dotnet" || executable === "dotnet.exe") {
685
+ const verb = args.find(argument => !argument.startsWith("-"))?.toLowerCase();
686
+ if (!verb || !new Set(["build", "test", "restore", "publish", "pack", "msbuild"]).has(verb))
687
+ return false;
688
+ return verb === "restore" || !args.some(argument => argument.toLowerCase() === "--no-build");
689
+ }
690
+ if (["powershell", "powershell.exe", "pwsh", "pwsh.exe"].includes(executable)) {
691
+ const fileIndex = args.findIndex(argument => argument.toLowerCase() === "-file");
692
+ const script = fileIndex >= 0 ? path.basename(args[fileIndex + 1] ?? "").toLowerCase() : "";
693
+ if (script === "run-dotnet-test-tier-set.ps1" || script === "run-dotnet-test-suite.ps1") {
694
+ return !args.some(argument => argument.toLowerCase() === "-nobuild");
695
+ }
696
+ if (script === "run-dotnet-test-tier.ps1") {
697
+ return !args.some(argument => argument.toLowerCase() === "-nobuild");
698
+ }
699
+ }
700
+ return false;
701
+ }
702
+ function managedBuildReceiptCoverage(invocation) {
703
+ if (!invocation.buildProducing)
704
+ return null;
705
+ if (invocation.verificationProfile)
706
+ return managedVerificationBuildCoverage;
707
+ const executable = path.basename(invocation.command).toLowerCase();
708
+ if (executable === "dotnet" || executable === "dotnet.exe") {
709
+ const verb = invocation.args.find(argument => !argument.startsWith("-"))?.toLowerCase();
710
+ if (!verb || !new Set(["build", "test"]).has(verb))
711
+ return null;
712
+ const target = invocation.args.find(argument => /\.(?:sln|slnx|csproj)$/iu.test(argument));
713
+ if (target && (/\.(?:sln|slnx)$/iu.test(target) || /(?:^|[\\/])Forge\.Api\.Tests\.csproj$/iu.test(target))) {
714
+ return managedVerificationBuildCoverage;
715
+ }
716
+ return null;
717
+ }
718
+ if (["powershell", "powershell.exe", "pwsh", "pwsh.exe"].includes(executable)) {
719
+ const fileIndex = invocation.args.findIndex(argument => argument.toLowerCase() === "-file");
720
+ const script = fileIndex >= 0 ? path.basename(invocation.args[fileIndex + 1] ?? "").toLowerCase() : "";
721
+ if (["run-dotnet-test-tier.ps1", "run-dotnet-test-tier-set.ps1", "run-dotnet-test-suite.ps1"].includes(script)
722
+ && !invocation.args.some(argument => argument.toLowerCase() === "-nobuild")) {
723
+ return managedVerificationBuildCoverage;
724
+ }
725
+ }
726
+ return null;
727
+ }
499
728
  function looksSensitiveEnvironmentName(name) {
500
729
  const normalized = name.trim().toUpperCase();
501
730
  return normalized.includes("SECRET")
@@ -548,12 +777,27 @@ function optionalTimeout(value) {
548
777
  }
549
778
  function optionalWaitTimeout(value) {
550
779
  if (value === undefined)
551
- return 7_200_000;
552
- if (!Number.isSafeInteger(value) || value < 1_000 || value > 7_200_000) {
553
- throw new Error("managed_command_invalid: wait_timeout_ms must be an integer from 1000 through 7200000.");
780
+ return maximumSynchronousWaitMs;
781
+ if (!Number.isSafeInteger(value) || value < 1_000 || value > maximumSynchronousWaitMs) {
782
+ throw new Error(`managed_command_invalid: wait_timeout_ms must be an integer from 1000 through ${maximumSynchronousWaitMs}.`);
554
783
  }
555
784
  return value;
556
785
  }
786
+ function optionalBoundedInteger(value, name, minimum, maximum, fallback) {
787
+ if (value === undefined)
788
+ return fallback;
789
+ if (!Number.isSafeInteger(value) || value < minimum || value > maximum) {
790
+ throw new Error(`managed_verification_invalid: ${name} must be an integer from ${minimum} through ${maximum}.`);
791
+ }
792
+ return value;
793
+ }
794
+ function optionalBoolean(value, name, fallback) {
795
+ if (value === undefined)
796
+ return fallback;
797
+ if (typeof value !== "boolean")
798
+ throw new Error(`managed_verification_invalid: ${name} must be a boolean.`);
799
+ return value;
800
+ }
557
801
  async function delay(ms) {
558
802
  await new Promise(resolve => setTimeout(resolve, ms));
559
803
  }
@@ -0,0 +1,5 @@
1
+ export declare class ManagedBuildCoordinator {
2
+ private readonly stateRoot;
3
+ constructor(stateRoot?: string);
4
+ withBuildSlot<T>(worktreePath: string, action: (queueWaitMs: number) => Promise<T>, onWaiting?: () => Promise<void>): Promise<T>;
5
+ }
@@ -0,0 +1,105 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import fs from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { defaultWorktreeCoordinatorStateRoot } from "../worktree/worktree-paths.js";
5
+ const heartbeatIntervalMs = 30_000;
6
+ const staleAfterMs = 2 * 60_000;
7
+ const acquisitionTimeoutMs = 2 * 60 * 60_000;
8
+ const pollIntervalMs = 100;
9
+ export class ManagedBuildCoordinator {
10
+ stateRoot;
11
+ constructor(stateRoot = defaultWorktreeCoordinatorStateRoot()) {
12
+ this.stateRoot = stateRoot;
13
+ }
14
+ async withBuildSlot(worktreePath, action, onWaiting) {
15
+ const resolved = path.resolve(worktreePath);
16
+ const key = createHash("sha256").update(resolved.toLowerCase()).digest("hex");
17
+ const root = path.join(this.stateRoot, "managed-build-locks");
18
+ const target = path.join(root, `${key}.lock`);
19
+ const token = randomUUID();
20
+ const startedAt = Date.now();
21
+ let waitingReported = false;
22
+ await fs.mkdir(root, { recursive: true, mode: 0o700 });
23
+ while (true) {
24
+ try {
25
+ const handle = await fs.open(target, "wx", 0o600);
26
+ try {
27
+ await handle.writeFile(`${JSON.stringify({
28
+ schemaVersion: 1,
29
+ token,
30
+ pid: process.pid,
31
+ worktreePath: resolved,
32
+ acquiredAt: new Date().toISOString(),
33
+ })}\n`);
34
+ await handle.sync();
35
+ }
36
+ finally {
37
+ await handle.close();
38
+ }
39
+ break;
40
+ }
41
+ catch (error) {
42
+ if (error.code !== "EEXIST")
43
+ throw error;
44
+ if (await staleLock(target)) {
45
+ await fs.rm(target, { force: true });
46
+ continue;
47
+ }
48
+ if (!waitingReported) {
49
+ waitingReported = true;
50
+ await onWaiting?.();
51
+ }
52
+ if (Date.now() - startedAt >= acquisitionTimeoutMs) {
53
+ throw new Error("managed_build_slot_timeout: another build held this worktree for more than two hours.", { cause: error });
54
+ }
55
+ await delay(pollIntervalMs);
56
+ }
57
+ }
58
+ const heartbeat = setInterval(() => void refreshHeartbeat(target, token), heartbeatIntervalMs);
59
+ heartbeat.unref?.();
60
+ try {
61
+ return await action(Date.now() - startedAt);
62
+ }
63
+ finally {
64
+ clearInterval(heartbeat);
65
+ const owner = await readOwner(target);
66
+ if (owner?.token === token)
67
+ await fs.rm(target, { force: true });
68
+ }
69
+ }
70
+ }
71
+ async function staleLock(target) {
72
+ const stat = await fs.lstat(target).catch(() => null);
73
+ if (!stat || stat.isSymbolicLink() || !stat.isFile() || stat.size > 16 * 1024)
74
+ return true;
75
+ if (Date.now() - stat.mtimeMs >= staleAfterMs)
76
+ return true;
77
+ const owner = await readOwner(target);
78
+ // A competing process can observe the exclusive lock file between open("wx")
79
+ // and the owner JSON being flushed. Keep a fresh unreadable lock rather than
80
+ // deleting a lock whose writer is still publishing its ownership record.
81
+ if (!owner || !Number.isInteger(owner.pid) || (owner.pid ?? 0) <= 0)
82
+ return false;
83
+ try {
84
+ process.kill(owner.pid, 0);
85
+ return false;
86
+ }
87
+ catch {
88
+ return true;
89
+ }
90
+ }
91
+ async function refreshHeartbeat(target, token) {
92
+ const owner = await readOwner(target);
93
+ if (owner?.token !== token)
94
+ return;
95
+ const now = new Date();
96
+ await fs.utimes(target, now, now).catch(() => undefined);
97
+ }
98
+ async function readOwner(target) {
99
+ return await fs.readFile(target, "utf8")
100
+ .then(value => JSON.parse(value))
101
+ .catch(() => null);
102
+ }
103
+ async function delay(ms) {
104
+ await new Promise(resolve => setTimeout(resolve, ms));
105
+ }
@@ -0,0 +1,21 @@
1
+ export interface ManagedBuildReceiptEvidence {
2
+ readonly fingerprint: string;
3
+ readonly receiptPath: string;
4
+ readonly producerCommand: readonly string[];
5
+ readonly configuration: string;
6
+ readonly coverage: string;
7
+ readonly outputCount: number;
8
+ }
9
+ export declare function publishManagedBuildReceipt(options: {
10
+ readonly worktreePath: string;
11
+ readonly command: string;
12
+ readonly args: readonly string[];
13
+ readonly configuration: string;
14
+ readonly coverage: string;
15
+ }): Promise<ManagedBuildReceiptEvidence | null>;
16
+ export declare function verifyManagedBuildReceipt(options: {
17
+ readonly worktreePath: string;
18
+ readonly configuration: string;
19
+ readonly requiredCoverage: string;
20
+ }): Promise<ManagedBuildReceiptEvidence>;
21
+ export declare function managedBuildConfiguration(command: string, args: readonly string[]): string;