@loucompanion/forge-bridge 0.1.3-dev.0bd9fb991b79 → 0.1.3-dev.0d26c10244e1

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 (127) hide show
  1. package/README.md +35 -0
  2. package/dist/bridge/bridge.base.d.ts +4 -1
  3. package/dist/bridge/bridge.service.d.ts +39 -3
  4. package/dist/bridge/bridge.service.js +585 -56
  5. package/dist/bridge/bridge.types.d.ts +59 -1
  6. package/dist/cleanup/cleanup.service.d.ts +14 -2
  7. package/dist/cleanup/cleanup.service.js +469 -3
  8. package/dist/cleanup/cleanup.types.d.ts +10 -0
  9. package/dist/cleanup/index.d.ts +1 -1
  10. package/dist/cleanup/index.js +1 -1
  11. package/dist/cleanup/internals.d.ts +2 -2
  12. package/dist/cleanup/internals.js +1 -1
  13. package/dist/cli/cli.help.js +37 -3
  14. package/dist/cli/cli.service.d.ts +30 -2
  15. package/dist/cli/cli.service.js +191 -27
  16. package/dist/cli/local-config.d.ts +4 -0
  17. package/dist/cli/local-config.js +41 -1
  18. package/dist/runtime/aspnet-runtime-prebuild.d.ts +35 -0
  19. package/dist/runtime/aspnet-runtime-prebuild.js +168 -0
  20. package/dist/runtime/attempt-node-runtime-launcher.d.ts +17 -0
  21. package/dist/runtime/attempt-node-runtime-launcher.js +105 -0
  22. package/dist/runtime/attempt-process-supervisor-registry.d.ts +20 -0
  23. package/dist/runtime/attempt-process-supervisor-registry.js +64 -0
  24. package/dist/runtime/attempt-process-supervisor.d.ts +86 -0
  25. package/dist/runtime/attempt-process-supervisor.js +350 -0
  26. package/dist/runtime/generated-output-reset.d.ts +10 -0
  27. package/dist/runtime/generated-output-reset.js +103 -0
  28. package/dist/runtime/host-listener-inspector.d.ts +46 -0
  29. package/dist/runtime/host-listener-inspector.js +349 -0
  30. package/dist/runtime/host-port-broker.d.ts +76 -0
  31. package/dist/runtime/host-port-broker.js +333 -0
  32. package/dist/runtime/host-runtime-contract.d.ts +47 -0
  33. package/dist/runtime/host-runtime-contract.js +700 -0
  34. package/dist/runtime/host-runtime-lease.d.ts +179 -0
  35. package/dist/runtime/host-runtime-lease.js +1990 -0
  36. package/dist/runtime/host-runtime-promotion.d.ts +23 -0
  37. package/dist/runtime/host-runtime-promotion.js +159 -0
  38. package/dist/runtime/node-host-runtime-adapter.d.ts +54 -0
  39. package/dist/runtime/node-host-runtime-adapter.js +284 -0
  40. package/dist/runtime/playwright-host-runtime-adapter.d.ts +20 -0
  41. package/dist/runtime/playwright-host-runtime-adapter.js +220 -0
  42. package/dist/runtime/runtime-isolation-lease.d.ts +67 -0
  43. package/dist/runtime/runtime-isolation-lease.js +158 -0
  44. package/dist/runtime/workspace-resource-estimator.d.ts +16 -0
  45. package/dist/runtime/workspace-resource-estimator.js +165 -0
  46. package/dist/sandbox/preflight.d.ts +15 -0
  47. package/dist/sandbox/preflight.js +100 -13
  48. package/dist/sandbox/process.js +125 -40
  49. package/dist/sandbox/repository-lock.js +37 -1
  50. package/dist/sandbox/runtime.d.ts +66 -3
  51. package/dist/sandbox/runtime.js +670 -105
  52. package/dist/sandbox/sandbox.types.d.ts +3 -0
  53. package/dist/sandbox/smoke.d.ts +76 -0
  54. package/dist/sandbox/smoke.js +380 -0
  55. package/dist/sandbox/worker-supervisor.js +1 -1
  56. package/dist/sandbox/worker.js +2 -5
  57. package/dist/sandbox/workspace.service.d.ts +1 -0
  58. package/dist/sandbox/workspace.service.js +28 -5
  59. package/dist/session/managed-attempt-tools.d.ts +18 -0
  60. package/dist/session/managed-attempt-tools.js +797 -0
  61. package/dist/session/managed-build-coordinator.d.ts +5 -0
  62. package/dist/session/managed-build-coordinator.js +105 -0
  63. package/dist/session/phase-completion.artifacts.js +21 -3
  64. package/dist/session/phase-completion.d.ts +11 -2
  65. package/dist/session/phase-completion.helpers.d.ts +5 -0
  66. package/dist/session/phase-completion.helpers.js +51 -10
  67. package/dist/session/phase-completion.js +12 -3
  68. package/dist/session/phase-completion.prompts.d.ts +3 -3
  69. package/dist/session/phase-completion.prompts.js +21 -6
  70. package/dist/session/phase-completion.runtime.d.ts +13 -1
  71. package/dist/session/phase-completion.runtime.js +187 -8
  72. package/dist/session/phase-completion.schemas.js +108 -3
  73. package/dist/session/phase-completion.validation.d.ts +4 -1
  74. package/dist/session/phase-completion.validation.js +150 -21
  75. package/dist/session/provider-cli/ci-repair-readiness.d.ts +14 -0
  76. package/dist/session/provider-cli/ci-repair-readiness.js +105 -0
  77. package/dist/session/provider-cli/provider-cli.artifacts.d.ts +3 -2
  78. package/dist/session/provider-cli/provider-cli.artifacts.js +65 -7
  79. package/dist/session/provider-cli/provider-cli.deterministic.js +47 -1
  80. package/dist/session/provider-cli/provider-cli.process.d.ts +16 -0
  81. package/dist/session/provider-cli/provider-cli.process.js +212 -25
  82. package/dist/session/provider-cli/provider-cli.prompts.d.ts +4 -1
  83. package/dist/session/provider-cli/provider-cli.prompts.js +99 -19
  84. package/dist/session/provider-cli/provider-cli.qa-sidecars.js +1 -0
  85. package/dist/session/provider-cli/provider-cli.runtime.d.ts +1 -1
  86. package/dist/session/provider-cli/provider-cli.runtime.js +3 -2
  87. package/dist/session/provider-cli/provider-cli.service.d.ts +20 -2
  88. package/dist/session/provider-cli/provider-cli.service.js +464 -102
  89. package/dist/session/provider-cli/provider-cli.types.d.ts +5 -0
  90. package/dist/session/provider-cli/provider-output-state.d.ts +2 -0
  91. package/dist/session/provider-cli/provider-output-state.js +69 -7
  92. package/dist/session/session-redaction.d.ts +3 -0
  93. package/dist/session/session-redaction.js +38 -0
  94. package/dist/session/session.base.d.ts +6 -1
  95. package/dist/session/session.service.d.ts +8 -2
  96. package/dist/session/session.service.js +482 -41
  97. package/dist/session/session.types.d.ts +70 -0
  98. package/dist/session/session.types.js +76 -4
  99. package/dist/shared/format/format-bytes.d.ts +1 -0
  100. package/dist/shared/format/format-bytes.js +9 -0
  101. package/dist/shared/path/path.js +3 -1
  102. package/dist/shared/process/host-process-recovery.d.ts +12 -0
  103. package/dist/shared/process/host-process-recovery.js +78 -0
  104. package/dist/shared/process/host-process-supervisor.d.ts +57 -0
  105. package/dist/shared/process/host-process-supervisor.js +282 -0
  106. package/dist/shared/process/process.d.ts +1 -0
  107. package/dist/shared/process/process.js +1 -0
  108. package/dist/shared/redaction/redaction.js +6 -1
  109. package/dist/version.d.ts +1 -1
  110. package/dist/version.js +1 -1
  111. package/dist/worktree/artifact-injector.d.ts +3 -2
  112. package/dist/worktree/artifact-injector.js +43 -4
  113. package/dist/worktree/dependency-warmer.d.ts +10 -1
  114. package/dist/worktree/dependency-warmer.js +94 -5
  115. package/dist/worktree/index.d.ts +1 -0
  116. package/dist/worktree/index.js +1 -0
  117. package/dist/worktree/prior-phase-artifact-hydrator.d.ts +2 -0
  118. package/dist/worktree/prior-phase-artifact-hydrator.js +136 -0
  119. package/dist/worktree/worktree-paths.d.ts +4 -0
  120. package/dist/worktree/worktree-paths.js +30 -0
  121. package/dist/worktree/worktree.base.d.ts +3 -0
  122. package/dist/worktree/worktree.service.d.ts +8 -2
  123. package/dist/worktree/worktree.service.js +206 -43
  124. package/dist/worktree/worktree.types.d.ts +4 -1
  125. package/package.json +3 -2
  126. package/runtime/windows-job-supervisor.ps1 +356 -0
  127. package/runtime/windows-listener-owner.ps1 +33 -0
@@ -1,10 +1,11 @@
1
1
  import fs from "node:fs/promises";
2
2
  import path from "node:path";
3
3
  import { completionPhaseFromDispatch, completionPhaseOrder, completionRedactionSecretsEnv, completionToolNamesForDebugGate, completionToolNamesForDecomposeGate, completionToolNamesForDraftGate, completionToolNamesForPhase, completionToolNamesForQaGate, debugCompletionPhaseOrder, decomposeCompletionGateOrder, draftCompletionGateOrder, qaCompletionGateOrder, toolServerName, usesArchitectCycleCompletion, usesDebugCycleCompletion, usesDevelopCycleCompletion, usesQaCycleCompletion } from "./phase-completion.js";
4
- import { asDebugCompletionPhase, asJsonRpcMessage, asMutableRecord, asRecord, decomposeGateFromToolName, draftGateFromToolName, errorMessage, forgeBridgeCliBinPath, isDebugCompletionPhase, isDecomposeDispatch, isDevelopCompletionPhase, normalizedOwnerType, parseCompletionRedactionSecrets, parseOptionalJsonObject, parseStrictCompletionPhase, phaseFromToolName, qaGateFromToolName, requiredString, rpcError, tomlString, tomlStringArray, writeFileAtomic, writeJsonRpc } from "./phase-completion.validation.js";
4
+ import { CompletionPayloadValidationError, asDebugCompletionPhase, asJsonRpcMessage, asMutableRecord, asRecord, artifactOwnerRelativeRoot, decomposeGateFromToolName, draftGateFromToolName, errorMessage, forgeBridgeCliBinPath, isDebugCompletionPhase, isDecomposeDispatch, isDevelopCompletionPhase, normalizedOwnerType, parseCompletionRedactionSecrets, parseOptionalJsonObject, parseStrictCompletionPhase, phaseFromToolName, qaGateFromToolName, requiredString, rpcError, tomlString, tomlStringArray, writeFileAtomic, writeJsonRpc } from "./phase-completion.validation.js";
5
5
  import { completionPromptForDebugCycle, completionPromptForDecomposeCycle, completionPromptForDevelopCycle, completionPromptForDraftCycle, completionPromptForPhase, completionPromptForQaCycle, completionToolNextInstruction, completionToolNextInstructionForDebugGate, completionToolNextInstructionForDecomposeGate, completionToolNextInstructionForDraftGate, completionToolNextInstructionForQaGate, nextDebugPhaseAfter, nextPhaseAfter } from "./phase-completion.prompts.js";
6
6
  import { toolDescription, toolInputSchema } from "./phase-completion.schemas.js";
7
7
  import { writeCompletionArtifact, writeDecomposeGateCompletionArtifact, writeDraftGateCompletionArtifact } from "./phase-completion.artifacts.js";
8
+ import { callManagedAttemptTool, isManagedAttemptTool, managedAttemptToolDefinition, managedAttemptToolNames, } from "./managed-attempt-tools.js";
8
9
  export async function prepareCompletionToolRuntime(options) {
9
10
  const phase = options.phase ?? completionPhaseFromDispatch(options.dispatch);
10
11
  const worktreePath = path.resolve(options.worktree.worktreePath);
@@ -32,7 +33,7 @@ export async function prepareCompletionToolRuntime(options) {
32
33
  serverName: toolServerName,
33
34
  command: process.execPath,
34
35
  args: [forgeBridgeCliBinPath(), ...mcpArgs],
35
- env: {},
36
+ env: completionToolRuntimeEnvironment(options.runtimeEnvironment),
36
37
  cleanup: async () => undefined
37
38
  };
38
39
  if (options.dispatch.execution.provider.trim().toLowerCase() !== "cursor") {
@@ -82,7 +83,11 @@ export function codexMcpConfigArgs(runtime) {
82
83
  "-c",
83
84
  `${prefix}.command=${tomlString(runtime.command)}`,
84
85
  "-c",
85
- `${prefix}.args=${tomlStringArray(runtime.args)}`
86
+ `${prefix}.args=${tomlStringArray(runtime.args)}`,
87
+ "-c",
88
+ `${prefix}.default_tools_approval_mode=${tomlString("approve")}`,
89
+ "-c",
90
+ `${prefix}.tool_timeout_sec=7200`
86
91
  ];
87
92
  for (const [key, value] of Object.entries(runtime.env)) {
88
93
  args.push("-c", `${prefix}.env.${key}=${tomlString(value)}`);
@@ -117,6 +122,7 @@ export class CompletionToolServerSession {
117
122
  currentQaGate = "qa_plan";
118
123
  currentDraftGate = "draft_intent";
119
124
  currentDecomposeGate = "decompose_subject_intake";
125
+ managedCommandReceipts = [];
120
126
  completed = false;
121
127
  constructor(config) {
122
128
  this.config = config;
@@ -130,15 +136,28 @@ export class CompletionToolServerSession {
130
136
  : this.config.debugCycle
131
137
  ? completionPromptForDebugCycle(asDebugCompletionPhase(this.currentPhase))
132
138
  : this.config.qaCycle
133
- ? completionPromptForQaCycle(this.currentQaGate)
139
+ ? completionPromptForQaCycle(this.currentQaGate, artifactOwnerRelativeRoot(this.config.ownerType, this.config.ownerId, this.config.workItemId))
134
140
  : this.config.developCycle
135
141
  ? completionPromptForDevelopCycle(this.currentPhase)
136
- : completionPromptForPhase(this.currentPhase);
142
+ : completionPromptForPhase(this.currentPhase, artifactOwnerRelativeRoot(this.config.ownerType, this.config.ownerId, this.config.workItemId));
137
143
  }
138
144
  toolDefinitions() {
139
- return completionToolNamesForServer(this.config).map((name) => toolDefinition(name, phaseFromToolName(name), qaGateFromToolName(name), decomposeGateFromToolName(name)));
145
+ const completionTools = completionToolNamesForServer(this.config).map((name) => toolDefinition(name, phaseFromToolName(name), qaGateFromToolName(name), decomposeGateFromToolName(name)));
146
+ return managedAttemptToolsAvailable()
147
+ ? [...completionTools, ...managedAttemptToolNames.map(managedAttemptToolDefinition)]
148
+ : completionTools;
140
149
  }
141
150
  async callTool(toolName, input) {
151
+ if (isManagedAttemptTool(toolName)) {
152
+ if (!managedAttemptToolsAvailable()) {
153
+ throw new Error("Forge managed-attempt tools require an active managed host runtime.");
154
+ }
155
+ const result = await callManagedAttemptTool(toolName, input, this.config.worktreePath);
156
+ if (Array.isArray(result.structuredContent.command)) {
157
+ this.managedCommandReceipts.push(result.structuredContent);
158
+ }
159
+ return result;
160
+ }
142
161
  const requestedPhase = phaseFromToolName(toolName);
143
162
  if (this.completed) {
144
163
  throw new Error("Forge completion cycle is already complete; no more completion calls are accepted.");
@@ -178,6 +197,7 @@ export class CompletionToolServerSession {
178
197
  ],
179
198
  structuredContent: {
180
199
  ...reference,
200
+ ...acceptedArtifactReceipt(reference),
181
201
  gate: {
182
202
  phase: completedPhase,
183
203
  status,
@@ -215,6 +235,7 @@ export class CompletionToolServerSession {
215
235
  content: [{ type: "text", text: `Forge recorded ${completedGate} artifact ${path.relative(reference.repoPath, reference.path)} (${reference.status}, ${reference.contentHash}). ${nextInstruction}` }],
216
236
  structuredContent: {
217
237
  ...reference,
238
+ ...acceptedArtifactReceipt(reference),
218
239
  gate: { phase: "decompose", decomposeGate: completedGate, status, allowed: pass, reason },
219
240
  nextPhase,
220
241
  nextInstruction
@@ -239,6 +260,7 @@ export class CompletionToolServerSession {
239
260
  content: [{ type: "text", text: `Forge recorded ${completedGate} artifact ${path.relative(reference.repoPath, reference.path)} (${reference.status}, ${reference.contentHash}). ${nextInstruction}` }],
240
261
  structuredContent: {
241
262
  ...reference,
263
+ ...acceptedArtifactReceipt(reference),
242
264
  gate: { phase: "draft", draftGate: completedGate, status, allowed: status !== "blocked", reason: nextGate ? `${completedGate} artifact accepted; continue to ${nextGate}.` : `Draft proposal artifact accepted with status ${status}.` },
243
265
  nextPhase,
244
266
  nextInstruction
@@ -272,6 +294,7 @@ export class CompletionToolServerSession {
272
294
  ],
273
295
  structuredContent: {
274
296
  ...reference,
297
+ ...acceptedArtifactReceipt(reference),
275
298
  gate: {
276
299
  phase: completedGate,
277
300
  status,
@@ -292,6 +315,9 @@ export class CompletionToolServerSession {
292
315
  throw new Error(`Tool ${toolName} is out of order. Current Forge QA gate is ${this.currentQaGate}.`);
293
316
  }
294
317
  const completedGate = this.currentQaGate;
318
+ if (completedGate === "qa_regression" && managedAttemptToolsAvailable()) {
319
+ assertManagedQaRegressionEvidence(input, this.managedCommandReceipts);
320
+ }
295
321
  const reference = await writeCompletionArtifact({ ...this.config, phase: "qa" }, toolName, input);
296
322
  const status = reference.status.trim().toLowerCase();
297
323
  const nextGate = this.advanceAfterQaGate(completedGate);
@@ -310,6 +336,7 @@ export class CompletionToolServerSession {
310
336
  ],
311
337
  structuredContent: {
312
338
  ...reference,
339
+ ...acceptedArtifactReceipt(reference),
313
340
  gate: {
314
341
  phase: "qa",
315
342
  qaGate: completedGate,
@@ -327,6 +354,10 @@ export class CompletionToolServerSession {
327
354
  this.completed = true;
328
355
  return "sign_off_ready";
329
356
  }
357
+ if (phase === "ci_repair") {
358
+ this.completed = true;
359
+ return "provider_checks_ready";
360
+ }
330
361
  if (isDebugCompletionPhase(phase)) {
331
362
  return nextDebugPhaseAfter(phase) ?? "qa_ready";
332
363
  }
@@ -382,6 +413,116 @@ export class CompletionToolServerSession {
382
413
  return null;
383
414
  }
384
415
  }
416
+ const completionToolRuntimeEnvironmentNames = [
417
+ "FORGE_RUNTIME_MODE",
418
+ "FORGE_RESOURCE_LEASE_ID",
419
+ "FORGE_DISPATCH_ATTEMPT_ID",
420
+ "FORGE_WORKTREE_PATH",
421
+ "FORGE_LOG_DIR",
422
+ "FORGE_CACHE_DIR",
423
+ "FORGE_TEST_OUTPUT_DIR",
424
+ "FORGE_ATTEMPT_DATABASE_SCHEMA",
425
+ "FORGE_ATTEMPT_DATABASE_READINESS_PATH",
426
+ "FORGE_CI_REPAIR_READINESS_PATH",
427
+ "FORGE_CI_REPAIR_HANDOFF_PATH",
428
+ "FORGE_CI_REPAIR_PROVIDER_ONLY_SPECS",
429
+ "FORGE_PLAYWRIGHT_CONFIG",
430
+ "FORGE_E2E_API_URL",
431
+ "FORGE_E2E_WEB_URL",
432
+ "PLAYWRIGHT_BROWSERS_PATH",
433
+ "FORGE_TMPDIR",
434
+ "NPM_CONFIG_CACHE",
435
+ "TMPDIR",
436
+ "TMP",
437
+ "TEMP",
438
+ ];
439
+ export function completionToolRuntimeEnvironment(runtimeEnvironment) {
440
+ if (!runtimeEnvironment)
441
+ return {};
442
+ const env = {};
443
+ for (const name of completionToolRuntimeEnvironmentNames) {
444
+ const value = runtimeEnvironment[name]?.trim();
445
+ if (value)
446
+ env[name] = value;
447
+ }
448
+ return env;
449
+ }
450
+ const minimumManagedSolutionTestTimeoutMs = 45 * 60 * 1000;
451
+ /**
452
+ * A solution-wide Forge test is long enough that a generic provider shell can
453
+ * expire while VSTest is still healthy. On managed host attempts, only the
454
+ * attempt-owned command runner can prove the exact process outcome and clean
455
+ * up its process tree. Keep this check at the completion gate so prompt drift
456
+ * cannot turn an arbitrary shell timeout into a QA blocker.
457
+ */
458
+ export function assertManagedQaRegressionEvidence(input, receipts) {
459
+ const payload = asRecord(input, "QA regression completion payload");
460
+ const nestedEvidence = asMutableRecord(payload.evidence);
461
+ const commands = payload.commands ?? nestedEvidence.commands;
462
+ if (!Array.isArray(commands))
463
+ return;
464
+ for (const [index, entry] of commands.entries()) {
465
+ if (!entry || typeof entry !== "object" || Array.isArray(entry))
466
+ continue;
467
+ const command = entry.command;
468
+ if (typeof command !== "string" || !isForgeSolutionTestCommand(command))
469
+ continue;
470
+ const managedCommandId = entry.managed_command_id;
471
+ if (typeof managedCommandId !== "string" || !managedCommandId.trim()) {
472
+ throw new Error(`qa_regression_managed_command_id_required: commands[${index}] runs the solution-wide Forge test. `
473
+ + "Run it with forge.start_managed_command, continue independent work, then call forge.wait_managed_command for a transport-safe receipt. "
474
+ + "If command_continues=true, continue useful work or wait again after retry_after_ms. Include the terminal managed_command_id in this command evidence.");
475
+ }
476
+ const matchingReceipts = receipts.filter((receipt) => {
477
+ const tokens = receipt.command;
478
+ return receipt.command_id === managedCommandId
479
+ && Array.isArray(tokens)
480
+ && tokens.every((token) => typeof token === "string")
481
+ && isForgeSolutionTestCommand(tokens.join(" "));
482
+ });
483
+ if (matchingReceipts.length === 0) {
484
+ throw new Error(`qa_regression_managed_command_required: commands[${index}] runs the solution-wide Forge test. `
485
+ + "Run it with forge.start_managed_command, continue independent work, then call forge.wait_managed_command for a transport-safe receipt. "
486
+ + "If command_continues=true, continue useful work or wait again after retry_after_ms. Include its matching terminal managed_command_id; generic-shell timeout evidence is not accepted on a managed host.");
487
+ }
488
+ const terminalReceipts = matchingReceipts.filter((receipt) => typeof receipt.status === "string" && [
489
+ "pass",
490
+ "fail",
491
+ "timed_out",
492
+ "timeout_termination_failed",
493
+ "runner_error",
494
+ ].includes(receipt.status));
495
+ if (terminalReceipts.length === 0) {
496
+ throw new Error(`qa_regression_managed_command_in_progress: commands[${index}] has not produced a terminal managed receipt. `
497
+ + "Call forge.wait_managed_command. If command_continues=true, continue useful work or wait again after retry_after_ms; resubmit this gate only after the receipt is terminal.");
498
+ }
499
+ const adequateReceipt = terminalReceipts.some((receipt) => {
500
+ if (receipt.timed_out !== true)
501
+ return true;
502
+ return typeof receipt.timeout_ms === "number"
503
+ && receipt.timeout_ms >= minimumManagedSolutionTestTimeoutMs
504
+ && receipt.process_tree_terminated === true;
505
+ });
506
+ if (!adequateReceipt) {
507
+ throw new Error(`qa_regression_managed_timeout_too_short: commands[${index}] timed out before the minimum `
508
+ + `${minimumManagedSolutionTestTimeoutMs}ms solution-test budget. Rerun it with forge.start_managed_command `
509
+ + "using at least a 45-minute timeout and resubmit this gate.");
510
+ }
511
+ }
512
+ }
513
+ function isForgeSolutionTestCommand(command) {
514
+ const normalized = command.trim().toLowerCase().replaceAll("\\", "/");
515
+ return normalized.includes("dotnet")
516
+ && /(?:^|\s)test(?:\s|$)/u.test(normalized)
517
+ && /(?:^|[\s/"'])forge\.sln(?:[\s"']|$)/u.test(normalized);
518
+ }
519
+ function managedAttemptToolsAvailable() {
520
+ return process.env.FORGE_RUNTIME_MODE === "host"
521
+ && Boolean(process.env.FORGE_RESOURCE_LEASE_ID?.trim())
522
+ && Boolean(process.env.FORGE_DISPATCH_ATTEMPT_ID?.trim())
523
+ && Boolean(process.env.FORGE_LOG_DIR?.trim())
524
+ && Boolean(process.env.FORGE_TEST_OUTPUT_DIR?.trim());
525
+ }
385
526
  export async function runCompletionMcpServer(config) {
386
527
  const session = new CompletionToolServerSession(config);
387
528
  process.stdin.setEncoding("utf8");
@@ -437,7 +578,7 @@ export function parseCompletionMcpArgs(argv) {
437
578
  const rawPhase = argv[++index];
438
579
  const parsedPhase = parseStrictCompletionPhase(rawPhase);
439
580
  if (!parsedPhase) {
440
- return { ok: false, error: "mcp --phase must be one of: implementation, self-review, validation, qa, architect, draft, debug-repro, debug-root-cause, debug-fix, debug-regression." };
581
+ return { ok: false, error: "mcp --phase must be one of: implementation, self-review, validation, qa, architect, draft, decompose, ci-repair, debug-repro, debug-root-cause, debug-fix, debug-regression." };
441
582
  }
442
583
  phase = parsedPhase;
443
584
  }
@@ -596,10 +737,48 @@ async function handleJsonRpcRequest(session, method, params) {
596
737
  const call = asRecord(params, "tools/call params");
597
738
  const name = requiredString(call, "name");
598
739
  const args = call.arguments ?? {};
599
- return await session.callTool(name, args);
740
+ try {
741
+ return await session.callTool(name, args);
742
+ }
743
+ catch (error) {
744
+ if (isManagedAttemptTool(name))
745
+ throw error;
746
+ return completionToolRejectedResult(name, error);
747
+ }
600
748
  }
601
749
  throw new Error(`Unsupported MCP method: ${method}`);
602
750
  }
751
+ export function completionToolRejectedResult(toolName, error) {
752
+ const issues = error instanceof CompletionPayloadValidationError
753
+ ? [...error.issues]
754
+ : [errorMessage(error)];
755
+ const repairInstruction = "Repair every listed issue and resubmit this same gate once. Do not inspect the artifact path: rejected calls never write or replace completion artifacts.";
756
+ return {
757
+ content: [{
758
+ type: "text",
759
+ text: `Forge rejected ${toolName}. No artifact was written.\n${issues.map(issue => `- ${issue}`).join("\n")}\n${repairInstruction}`,
760
+ }],
761
+ structuredContent: {
762
+ status: "rejected",
763
+ tool_name: toolName,
764
+ artifact_written: false,
765
+ issues,
766
+ repair_instruction: repairInstruction,
767
+ },
768
+ isError: true,
769
+ };
770
+ }
771
+ function acceptedArtifactReceipt(reference) {
772
+ return {
773
+ artifact_written: true,
774
+ artifact_receipt: {
775
+ schema_version: 1,
776
+ path: reference.path,
777
+ report_path: reference.reportPath,
778
+ content_hash: reference.contentHash,
779
+ },
780
+ };
781
+ }
603
782
  function toolDefinition(name, phase, qaGate = null, decomposeGate = null) {
604
783
  return {
605
784
  name,
@@ -16,6 +16,9 @@ export function toolDescription(phase, qaGate = null, decomposeGate = null) {
16
16
  if (phase === "implementation") {
17
17
  return "Complete Forge implementation by writing implementation.completeness.json with scoped changed-file, verification, acceptance-criteria, gap, and next-phase evidence.";
18
18
  }
19
+ if (phase === "ci_repair") {
20
+ return "Complete Forge CI repair by writing ci-repair.handoff.json with failed-check, root-cause, scoped-change, workflow-equivalence, validation, provider-state, and push-readiness evidence.";
21
+ }
19
22
  if (phase === "self_review") {
20
23
  return "Complete Forge self-review by writing self-review.report.json with diff review, findings, security, edge-case, design, deterministic-comparison, fixes, and remaining-risk evidence.";
21
24
  }
@@ -55,6 +58,94 @@ export function toolInputSchema(phase, qaGate = null, decomposeGate = null) {
55
58
  if (isDebugCompletionPhase(phase)) {
56
59
  return debugToolInputSchema(phase, baseProperties);
57
60
  }
61
+ if (phase === "ci_repair") {
62
+ return objectToolSchema({
63
+ ...baseProperties,
64
+ failed_checks: {
65
+ type: "array",
66
+ description: "Required and non-empty for pass. Provider check/job/step evidence inspected before repair.",
67
+ items: evidenceObjectSchema(["name", "provider_state"], {
68
+ name: { type: "string" },
69
+ provider_state: { type: "string" },
70
+ workflow: { type: "string" },
71
+ job: { type: "string" },
72
+ step: { type: "string" },
73
+ details_url: { type: "string" },
74
+ evidence: { type: "string" }
75
+ })
76
+ },
77
+ root_cause: {
78
+ type: "object",
79
+ description: "Required for pass. Include classification, summary, and concrete evidence.",
80
+ additionalProperties: true,
81
+ properties: {
82
+ classification: { type: "string" },
83
+ summary: { type: "string" },
84
+ evidence: { type: "array", items: { type: "string" } }
85
+ }
86
+ },
87
+ changed_files: {
88
+ type: "array",
89
+ description: "Files changed by the repair. May be empty only when no_code_action explains the provider-only action or blocker.",
90
+ items: evidenceObjectSchema(["path", "summary"], {
91
+ path: { type: "string" },
92
+ summary: { type: "string" }
93
+ })
94
+ },
95
+ no_code_action: {
96
+ type: "object",
97
+ description: "Required when changed_files is empty. Describe the evidence-backed provider action or blocker.",
98
+ additionalProperties: true,
99
+ properties: {
100
+ action: { type: "string" },
101
+ reason: { type: "string" },
102
+ evidence: { type: "string" }
103
+ }
104
+ },
105
+ narrow_validation: {
106
+ type: "array",
107
+ description: "Required and non-empty for pass. The focused failing command or evidence-backed substitute.",
108
+ items: commandEvidenceSchema()
109
+ },
110
+ workflow_validation: {
111
+ type: "array",
112
+ description: "Required and non-empty for pass. Each failed-job guard/test/drift step with local equivalence supported, substitute, or provider_only.",
113
+ items: evidenceObjectSchema(["step", "equivalence", "status"], {
114
+ step: { type: "string" },
115
+ equivalence: { type: "string", enum: ["supported", "substitute", "provider_only"] },
116
+ command: { type: "string" },
117
+ exit_code: { type: "number" },
118
+ status: { type: "string" },
119
+ summary: { type: "string" },
120
+ reason: { type: "string" },
121
+ substitute: { type: "string" }
122
+ })
123
+ },
124
+ broader_validation: {
125
+ type: "array",
126
+ description: "Required and non-empty for pass. Normal validation covering every touched compiled/tested surface.",
127
+ items: commandEvidenceSchema()
128
+ },
129
+ remaining_risks: {
130
+ type: "array",
131
+ description: "Required for pass, even when empty.",
132
+ items: evidenceObjectSchema(["summary"], {
133
+ summary: { type: "string" },
134
+ mitigation: { type: "string" },
135
+ owner: { type: "string" }
136
+ })
137
+ },
138
+ provider_state: {
139
+ type: "string",
140
+ enum: ["ready_for_rerun", "rerun_requested", "checks_pending", "still_failing", "blocked_by_provider"],
141
+ description: "Provider state after local validation and before Forge-owned publication."
142
+ },
143
+ ready_for_push: {
144
+ type: "boolean",
145
+ description: "Required for pass and must be true. Forge Bridge performs the commit/push only after this gate passes."
146
+ }
147
+ }, ["status", "summary"], "For status pass, include failed_checks, root_cause, changed_files or no_code_action, narrow_validation, workflow_validation, broader_validation, remaining_risks, provider_state, and ready_for_push: true.");
148
+ }
58
149
  if (phase === "implementation") {
59
150
  return objectToolSchema({
60
151
  ...baseProperties,
@@ -198,7 +289,7 @@ export function toolInputSchema(phase, qaGate = null, decomposeGate = null) {
198
289
  },
199
290
  sidecars: {
200
291
  type: "array",
201
- description: "Optional QA sidecar files already written under .forge/work-items/<id>/artifacts/qa/ with path/content_hash/bytes metadata.",
292
+ description: "Optional QA sidecar files already written under the dispatch-provided QA artifacts path with path/content_hash/bytes metadata.",
202
293
  items: evidenceObjectSchema(["path", "content_hash", "bytes"], {
203
294
  path: { type: "string" },
204
295
  content_hash: { type: "string" },
@@ -652,9 +743,23 @@ function qaScopeSchema(description) {
652
743
  function commandEvidenceSchema() {
653
744
  return evidenceObjectSchema(["command", "exit_code", "status", "summary"], {
654
745
  command: { type: "string" },
655
- exit_code: { type: "number" },
746
+ managed_command_id: { type: "string", description: "Receipt ID returned by forge.start_managed_command after forge.wait_managed_command reports a terminal receipt. A transport-safe wait can return command_continues=true; wait again after retry_after_ms before submitting the gate." },
747
+ exit_code: { type: ["number", "null"], description: "Process exit code, or null when the managed runner timed out or could not launch the process." },
656
748
  status: { type: "string" },
657
- summary: { type: "string" }
749
+ summary: { type: "string" },
750
+ classification: {
751
+ type: "string",
752
+ enum: ["out_of_scope_failure", "baseline_failure"],
753
+ description: "Only for a verified non-blocking failure in a passing QA regression gate. Never use for an in-scope or unexplained failure."
754
+ },
755
+ candidate_bug_id: { type: "string", description: "Required for a classified non-blocking failure; links the preserved failure to candidate_bugs." },
756
+ scope_evidence: { type: "string", description: "Required proof that the failing surface is outside the current acceptance criteria and changed-file scope." },
757
+ acceptance_criteria_independent: { type: "boolean", description: "Required and true only when the current item can be judged independently of this failure." },
758
+ repro_command: { type: "string", description: "Required for out_of_scope_failure; focused command that reproduced the unrelated failure." },
759
+ repro_exit_code: { type: "number", description: "Required non-zero focused repro exit code for out_of_scope_failure." },
760
+ baseline_ref: { type: "string", description: "Required for baseline_failure; immutable ref where the same failure was observed." },
761
+ baseline_exit_code: { type: "number", description: "Required non-zero baseline command exit code for baseline_failure." },
762
+ failure_signature_match: { type: "boolean", description: "Required and true for baseline_failure after matching failing test/error signatures." }
658
763
  });
659
764
  }
660
765
  function resolvedFindingSchema() {
@@ -2,9 +2,12 @@ import { type CompletionPhase, type DebugCompletionPhase, type QaCompletionGate
2
2
  export declare function normalizeCompletionStatus(value: string, phase?: CompletionPhase): string;
3
3
  export declare function normalizeQaGateStatus(value: string): string;
4
4
  export declare function validatePayloadShape(phase: CompletionPhase, payload: Record<string, unknown>): void;
5
+ export declare function validateCiRepairPayloadShape(payload: Record<string, unknown>): void;
5
6
  export declare function validateDebugPayloadShape(phase: DebugCompletionPhase, payload: Record<string, unknown>): void;
6
7
  export declare function validateQaGatePayloadShape(gate: QaCompletionGate, payload: Record<string, unknown>, status: string): void;
7
- export declare function validateQaGatePassingCommands(commands: readonly unknown[]): void;
8
+ export declare function validateQaGatePassingCommands(commands: readonly unknown[], options?: {
9
+ readonly allowClassifiedNonBlockingFailures?: boolean;
10
+ }): void;
8
11
  export declare function validateArchitectPayloadShape(payload: Record<string, unknown>, status: string): void;
9
12
  export declare function validateArchitectTaskDevelopScope(task: Record<string, unknown>, taskId: string): void;
10
13
  export declare function validateArchitectVerificationScope(task: Record<string, unknown>, taskId: string): void;