@loucompanion/forge-bridge 0.1.4-dev.4677bbd22f17 → 0.1.4-dev.60e18c3cfec6

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 (129) hide show
  1. package/README.md +33 -0
  2. package/dist/bridge/bridge.base.d.ts +9 -0
  3. package/dist/bridge/bridge.service.d.ts +72 -1
  4. package/dist/bridge/bridge.service.js +308 -9
  5. package/dist/bridge/bridge.types.d.ts +16 -0
  6. package/dist/bridge/local-yield-flag.d.ts +6 -0
  7. package/dist/bridge/local-yield-flag.js +34 -0
  8. package/dist/bridge/runner-host-capabilities.d.ts +2 -0
  9. package/dist/bridge/runner-host-capabilities.js +4 -0
  10. package/dist/bridge/test-postgres-capability.d.ts +14 -0
  11. package/dist/bridge/test-postgres-capability.js +120 -0
  12. package/dist/cleanup/cleanup.service.d.ts +9 -0
  13. package/dist/cleanup/cleanup.service.js +72 -109
  14. package/dist/cleanup/cleanup.types.d.ts +4 -0
  15. package/dist/cleanup/forge-owned-paths.d.ts +9 -0
  16. package/dist/cleanup/forge-owned-paths.js +53 -0
  17. package/dist/cleanup/host-runtime-ledger.d.ts +5 -0
  18. package/dist/cleanup/host-runtime-ledger.js +109 -0
  19. package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
  20. package/dist/cleanup/managed-branch-sweep.js +111 -0
  21. package/dist/cli/cli.help.js +18 -0
  22. package/dist/cli/cli.service.d.ts +16 -0
  23. package/dist/cli/cli.service.js +142 -16
  24. package/dist/cli/local-config.d.ts +4 -0
  25. package/dist/cli/local-config.js +26 -4
  26. package/dist/runtime/aspnet-runtime-prebuild.js +94 -6
  27. package/dist/runtime/host-load-admission.d.ts +60 -0
  28. package/dist/runtime/host-load-admission.js +99 -0
  29. package/dist/runtime/host-load-child-environment.d.ts +22 -0
  30. package/dist/runtime/host-load-child-environment.js +67 -0
  31. package/dist/runtime/host-load-forge-cgroups.d.ts +49 -0
  32. package/dist/runtime/host-load-forge-cgroups.js +140 -0
  33. package/dist/runtime/host-load-governor-config.d.ts +43 -0
  34. package/dist/runtime/host-load-governor-config.js +76 -0
  35. package/dist/runtime/host-load-governor.d.ts +174 -0
  36. package/dist/runtime/host-load-governor.js +541 -0
  37. package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
  38. package/dist/runtime/host-load-ledger-lock.js +185 -0
  39. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  40. package/dist/runtime/host-load-runtime-settings.js +78 -0
  41. package/dist/runtime/host-load-sampler.d.ts +43 -0
  42. package/dist/runtime/host-load-sampler.js +74 -6
  43. package/dist/runtime/host-load-step-class.d.ts +68 -0
  44. package/dist/runtime/host-load-step-class.js +106 -0
  45. package/dist/runtime/host-load-step-reaper.d.ts +27 -0
  46. package/dist/runtime/host-load-step-reaper.js +95 -0
  47. package/dist/runtime/host-load-step-run.d.ts +73 -0
  48. package/dist/runtime/host-load-step-run.js +102 -0
  49. package/dist/runtime/host-load-token-ledger.d.ts +174 -0
  50. package/dist/runtime/host-load-token-ledger.js +421 -0
  51. package/dist/runtime/host-pressure-stall.d.ts +21 -1
  52. package/dist/runtime/host-pressure-stall.js +48 -1
  53. package/dist/runtime/host-runtime-contract.d.ts +3 -0
  54. package/dist/runtime/host-runtime-contract.js +4 -1
  55. package/dist/runtime/host-runtime-lease.d.ts +74 -4
  56. package/dist/runtime/host-runtime-lease.js +279 -10
  57. package/dist/runtime/host-runtime-promotion.js +12 -0
  58. package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
  59. package/dist/runtime/host-runtime-requirements-check.js +29 -0
  60. package/dist/runtime/host-runtime-requirements.d.ts +36 -0
  61. package/dist/runtime/host-runtime-requirements.js +117 -0
  62. package/dist/runtime/playwright-host-runtime-adapter.d.ts +7 -0
  63. package/dist/runtime/playwright-host-runtime-adapter.js +13 -1
  64. package/dist/runtime/runner-settings.d.ts +100 -0
  65. package/dist/runtime/runner-settings.js +214 -0
  66. package/dist/sandbox/host-capacity-broker.d.ts +107 -0
  67. package/dist/sandbox/host-capacity-broker.js +315 -0
  68. package/dist/sandbox/runtime.d.ts +10 -1
  69. package/dist/sandbox/runtime.js +45 -2
  70. package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
  71. package/dist/sandbox/sandbox-cgroups.js +42 -0
  72. package/dist/session/managed-attempt-tools.d.ts +2 -0
  73. package/dist/session/managed-attempt-tools.js +156 -37
  74. package/dist/session/managed-command-host-load.d.ts +45 -0
  75. package/dist/session/managed-command-host-load.js +82 -0
  76. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  77. package/dist/session/mcp-argument-coercion.js +121 -0
  78. package/dist/session/phase-completion.artifacts.d.ts +7 -0
  79. package/dist/session/phase-completion.artifacts.js +94 -25
  80. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  81. package/dist/session/phase-completion.command-validation.js +77 -0
  82. package/dist/session/phase-completion.d.ts +4 -0
  83. package/dist/session/phase-completion.helpers.js +13 -12
  84. package/dist/session/phase-completion.js +4 -0
  85. package/dist/session/phase-completion.prompts.js +6 -1
  86. package/dist/session/phase-completion.runtime.d.ts +5 -3
  87. package/dist/session/phase-completion.runtime.js +49 -19
  88. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  89. package/dist/session/phase-completion.schema-parts.js +188 -0
  90. package/dist/session/phase-completion.schemas.d.ts +3 -3
  91. package/dist/session/phase-completion.schemas.js +184 -209
  92. package/dist/session/phase-completion.validation.d.ts +2 -3
  93. package/dist/session/phase-completion.validation.js +46 -92
  94. package/dist/session/pre-publication-host-load.d.ts +27 -0
  95. package/dist/session/pre-publication-host-load.js +111 -0
  96. package/dist/session/pre-publication-process.d.ts +3 -0
  97. package/dist/session/pre-publication-process.js +23 -11
  98. package/dist/session/pre-publication-step-execution.d.ts +11 -0
  99. package/dist/session/pre-publication-step-execution.js +49 -0
  100. package/dist/session/pre-publication-validation.d.ts +9 -9
  101. package/dist/session/pre-publication-validation.js +21 -55
  102. package/dist/session/provider-cli/provider-cli.process.js +2 -2
  103. package/dist/session/provider-cli/provider-cli.prompts.js +5 -2
  104. package/dist/session/provider-cli/provider-cli.service.d.ts +6 -0
  105. package/dist/session/provider-cli/provider-cli.service.js +132 -14
  106. package/dist/session/provider-cli/provider-cli.types.d.ts +30 -0
  107. package/dist/session/sandbox-host-capacity-gate.d.ts +30 -0
  108. package/dist/session/sandbox-host-capacity-gate.js +229 -0
  109. package/dist/session/session.base.d.ts +9 -1
  110. package/dist/session/session.service.d.ts +9 -2
  111. package/dist/session/session.service.js +120 -5
  112. package/dist/session/session.types.d.ts +3 -0
  113. package/dist/session/session.types.js +3 -3
  114. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  115. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  116. package/dist/shared/process/host-process-supervisor.d.ts +1 -0
  117. package/dist/shared/process/host-process-supervisor.js +1 -1
  118. package/dist/shared/process/process-tree.d.ts +52 -0
  119. package/dist/shared/process/process-tree.js +144 -0
  120. package/dist/shared/process/process.d.ts +67 -0
  121. package/dist/shared/process/process.js +213 -11
  122. package/dist/version.d.ts +1 -1
  123. package/dist/version.js +1 -1
  124. package/dist/worktree/dependency-warmer.d.ts +25 -0
  125. package/dist/worktree/dependency-warmer.js +46 -10
  126. package/dist/worktree/worktree.service.d.ts +10 -1
  127. package/dist/worktree/worktree.service.js +42 -2
  128. package/dist/worktree/worktree.types.d.ts +7 -0
  129. package/package.json +1 -1
@@ -4,15 +4,13 @@ import path from "node:path";
4
4
  import { redactSecrets } from "../shared/redaction/redaction.js";
5
5
  import { ensureNoSymbolicLinkPathSegments, isPathUnderRoot, sha256File } from "./qa-sidecar-validation.js";
6
6
  import { assertClaimedChangedFilesMatchPublishableDiff } from "./publishable-worktree-changes.js";
7
- import { artifactRootFor, artifactRootForOwner, completionArtifactJsonPath, completionArtifactReportPath, decomposeGateFileNames, draftGateFileNames, phaseFiles, qaGateFileNames } from "./phase-completion.js";
8
- import { artifactOwnerFields, artifactReferenceOwnerFields, artifactOwnerRelativeRoot, defaultQaChecklist, fallbackReport, isNodeError, jsonText, normalizeArtifactPayload, normalizeCompletionStatus, normalizeQaGateArtifactPayload, normalizeQaGateStatus, normalizedString, optionalString, numberOrDefault, parseJsonObject, parseOptionalJsonObject, phaseFromToolName, qaArray, qaArtifactRelativePath, qaArtifactRelativePathForOwner, qaEvidenceSource, qaObjectArray, qaPolicyWarnings, qaStringArray, readOptionalFile, reportMarkdown, requiredRecord, requiredString, qaGateFromToolName, sha256, stableStringify, validateOptionalWorkItemId, validatePayloadShape, validateQaGatePayloadShape, validateQaScopeRecord, writeFileAtomic, asRecord } from "./phase-completion.validation.js";
7
+ import { coerceJsonStringArguments } from "./mcp-argument-coercion.js";
8
+ import { toolInputSchema } from "./phase-completion.schemas.js";
9
+ import { artifactRootFor, artifactRootForOwner, completionArtifactJsonPath, completionArtifactReportPath, decomposeGateFileNames, draftGateFileNames, phaseFiles, qaGateFileNames, decomposeStatuses, draftStatuses } from "./phase-completion.js";
10
+ import { artifactOwnerFields, artifactReferenceOwnerFields, artifactOwnerRelativeRoot, defaultQaChecklist, fallbackReport, isNodeError, jsonText, normalizeArtifactPayload, normalizeCompletionStatus, normalizeQaGateArtifactPayload, normalizeQaGateStatus, normalizedString, optionalString, numberOrDefault, parseJsonObject, parseOptionalJsonObject, phaseFromToolName, qaArray, qaArtifactRelativePath, qaArtifactRelativePathForOwner, qaEvidenceSource, qaObjectArray, qaPolicyWarnings, qaEvidenceGates, qaStringArray, readOptionalFile, reportMarkdown, requireField, requiredRecord, requiredString, qaGateFromToolName, sha256, stableStringify, validateOptionalWorkItemId, validatePayloadShape, validateQaGatePayloadShape, validateQaScopeRecord, writeFileAtomic, asRecord } from "./phase-completion.validation.js";
9
11
  export async function writeDecomposeGateCompletionArtifact(config, gate, toolName, input) {
10
12
  const payload = asRecord(input, "Decompose completion payload");
11
- const status = normalizeDraftStatus(optionalString(payload, "status") ?? "pass");
12
- if (gate === "decompose_proposal") {
13
- const proposalJson = asRecord(payload["proposal_json"] ?? payload["decomposition_json"], "proposal_json");
14
- validateDecomposeProposalJson(proposalJson);
15
- }
13
+ const status = validateDecomposeGatePayload(gate, payload);
16
14
  const redactedPayload = redactSecrets({ ...payload, status, phase: "decompose", gate, tool_name: toolName }, config.redactionSecrets ?? []);
17
15
  assertStructuralFieldsUnchanged(payload, redactedPayload);
18
16
  if (gate === "decompose_proposal") {
@@ -45,11 +43,7 @@ ${optionalString(redactedPayload, "summary") ?? "Decompose gate recorded."}
45
43
  }
46
44
  export async function writeDraftGateCompletionArtifact(config, gate, toolName, input) {
47
45
  const payload = asRecord(input, "Draft completion payload");
48
- const status = normalizeDraftStatus(optionalString(payload, "status") ?? "pass");
49
- if (gate === "draft_proposal") {
50
- const draftJson = asRecord(payload["draft_json"], "draft_json");
51
- validateDraftProposalJson(draftJson);
52
- }
46
+ const status = validateDraftGatePayload(gate, payload);
53
47
  const redactedPayload = redactSecrets({ ...payload, status, phase: "draft", gate, tool_name: toolName }, config.redactionSecrets ?? []);
54
48
  assertStructuralFieldsUnchanged(payload, redactedPayload);
55
49
  if (gate === "draft_proposal") {
@@ -77,9 +71,48 @@ export async function writeDraftGateCompletionArtifact(config, gate, toolName, i
77
71
  producedBy: config.producedBy ?? "forge-completion-tool"
78
72
  };
79
73
  }
80
- function normalizeDraftStatus(value) {
81
- const normalized = value.trim().toLowerCase();
82
- return normalized === "blocked" || normalized === "needs_revision" || normalized === "needs_rework" ? normalized : "pass";
74
+ /**
75
+ * Judges a Decompose gate call before anything is written and returns its status. The gate's
76
+ * input schema advertises exactly these rules (see the completion tool schema contract test).
77
+ */
78
+ export function validateDecomposeGatePayload(gate, payload) {
79
+ const status = gateStatus(payload, decomposeStatuses);
80
+ if (gate === "decompose_proposal") {
81
+ validateDecomposeProposalJson(asRecord(payload["proposal_json"] ?? payload["decomposition_json"], "proposal_json"));
82
+ }
83
+ else {
84
+ // An earlier Decompose gate's evidence is its summary, and a missing status means pass, so an
85
+ // empty call would otherwise record a pass and move to the next gate.
86
+ requireField(payload, "summary");
87
+ }
88
+ return status;
89
+ }
90
+ /** Judges a Draft gate call before anything is written and returns its status. */
91
+ export function validateDraftGatePayload(gate, payload) {
92
+ const status = gateStatus(payload, draftStatuses);
93
+ if (gate === "draft_proposal") {
94
+ validateDraftProposalJson(asRecord(payload["draft_json"], "draft_json"));
95
+ }
96
+ else {
97
+ // An earlier Draft gate's only evidence is its summary, and a missing status means pass, so an
98
+ // empty call would otherwise record a pass and move to the next gate.
99
+ requireField(payload, "summary");
100
+ }
101
+ return status;
102
+ }
103
+ // Only an omitted status defaults to pass. A status that is present must be one of the advertised
104
+ // values: a typo such as "pas", a blank string or a non-string is rejected rather than advancing
105
+ // the gate as a pass.
106
+ function gateStatus(payload, allowed) {
107
+ const value = payload["status"];
108
+ if (value === undefined || value === null) {
109
+ return "pass";
110
+ }
111
+ const normalized = typeof value === "string" ? value.trim().toLowerCase() : "";
112
+ if (!allowed.includes(normalized)) {
113
+ throw new Error(`status must be one of ${allowed.join(", ")}; received ${typeof value === "string" ? `'${value}'` : JSON.stringify(value)}.`);
114
+ }
115
+ return normalized;
83
116
  }
84
117
  function validateDraftProposalJson(draftJson) {
85
118
  if (draftJson.suggested_qa_scope !== undefined && draftJson.suggested_qa_scope !== null) {
@@ -220,8 +253,10 @@ export async function writeArchitectCompletionArtifact(config, payload, status,
220
253
  const qaPlanPath = path.join(artifactRoot, "qa.plan.json");
221
254
  const verdictPath = path.join(artifactRoot, "architect.verdict.json");
222
255
  const reportPath = path.join(artifactRoot, "architect.report.md");
223
- const implementationPlan = requiredRecord(payload, "implementation_plan");
224
- const qaPlan = requiredRecord(payload, "qa_plan");
256
+ // A needs_revision or blocked verdict has no plan to approve; its schema lets
257
+ // the agent omit both plans, and the bundle still carries a file for each.
258
+ const implementationPlan = architectPlanRecord(payload, "implementation_plan", status);
259
+ const qaPlan = architectPlanRecord(payload, "qa_plan", status);
225
260
  const report = optionalString(payload, "report") ?? optionalString(payload, "report_markdown") ?? reportMarkdown(payload, "architect", status, producedBy, "pending");
226
261
  const artifactWithoutHash = normalizeArtifactPayload(payload, {
227
262
  phase: "architect",
@@ -254,13 +289,21 @@ export async function writeArchitectCompletionArtifact(config, payload, status,
254
289
  producedBy
255
290
  };
256
291
  }
292
+ function architectPlanRecord(payload, key, status) {
293
+ if (status !== "pass" && (payload[key] === undefined || payload[key] === null)) {
294
+ return {};
295
+ }
296
+ return requiredRecord(payload, key);
297
+ }
257
298
  export async function writeQaGateCompletionArtifact(config, gate, input) {
258
299
  const payload = asRecord(input, "QA gate completion payload");
259
300
  const status = normalizeQaGateStatus(requiredString(payload, "status"));
260
301
  validateQaGatePayloadShape(gate, payload, status);
261
302
  validateOptionalWorkItemId(payload, config.workItemId);
262
303
  const ownerFields = artifactOwnerFields(config);
263
- const validatedSidecars = gate === "qa_manual_web"
304
+ // Every evidence gate's sidecars are merged into the final verdict, which checks each file,
305
+ // so each gate checks its references (exists, under qa/, size and hash match) when it is called.
306
+ const validatedSidecars = qaEvidenceGates.has(gate)
264
307
  ? await validateQaSidecarReferences(config.worktreePath, config.workItemId, qaArray(payload, "sidecars", qaEvidenceSource(payload)), ownerFields.owner_type, ownerFields.owner_id)
265
308
  : null;
266
309
  const redactedPayload = redactSecrets({
@@ -273,7 +316,7 @@ export async function writeQaGateCompletionArtifact(config, gate, input) {
273
316
  validateQaGatePayloadShape(gate, redactedPayload, status);
274
317
  validateOptionalWorkItemId(redactedPayload, config.workItemId);
275
318
  });
276
- if (gate === "qa_manual_web") {
319
+ if (qaEvidenceGates.has(gate)) {
277
320
  await validateQaSidecarReferences(config.worktreePath, config.workItemId, qaArray(redactedPayload, "sidecars", qaEvidenceSource(redactedPayload)), ownerFields.owner_type, ownerFields.owner_id).catch((error) => {
278
321
  throw postRedactionValidationError(error);
279
322
  });
@@ -429,12 +472,12 @@ export async function writeQaCompletionArtifact(config, payload, status, produce
429
472
  };
430
473
  }
431
474
  async function synthesizeQaCycleVerdictPayload(config, payload, status) {
432
- const qaPlan = await readQaGateArtifact(config, "qa_plan");
433
- const qaRegression = await readQaGateArtifact(config, "qa_regression");
434
- const qaApi = await readQaGateArtifact(config, "qa_api");
435
- const qaManualWeb = await readQaGateArtifact(config, "qa_manual_web");
436
- const qaBugRepro = await readQaGateArtifact(config, "qa_bug_repro");
437
- const qaFindings = await readQaGateArtifact(config, "qa_findings");
475
+ const qaPlan = await readInheritedQaGateArtifact(config, "qa_plan");
476
+ const qaRegression = await readInheritedQaGateArtifact(config, "qa_regression");
477
+ const qaApi = await readInheritedQaGateArtifact(config, "qa_api");
478
+ const qaManualWeb = await readInheritedQaGateArtifact(config, "qa_manual_web");
479
+ const qaBugRepro = await readInheritedQaGateArtifact(config, "qa_bug_repro");
480
+ const qaFindings = await readInheritedQaGateArtifact(config, "qa_findings");
438
481
  const evidenceGates = [qaRegression, qaApi, qaManualWeb, qaBugRepro];
439
482
  const payloadEvidence = qaEvidenceSource(payload);
440
483
  const merged = { ...payload };
@@ -482,6 +525,32 @@ async function synthesizeQaCycleVerdictPayload(config, payload, status) {
482
525
  merged.candidate_bugs = mergeQaObjectArraysById(qaObjectArray(payload, "candidate_bugs"), qaObjectArray(qaFindings, "candidate_bugs"));
483
526
  return merged;
484
527
  }
528
+ /**
529
+ * Reads an earlier gate's artifact for the verdict merge. Gates recorded before
530
+ * argument coercion existed may hold a JSON-string array, so the same schema
531
+ * coercion is applied here, and any remaining shape error names the gate file
532
+ * instead of looking like a fault in the verdict payload.
533
+ */
534
+ async function readInheritedQaGateArtifact(config, gate) {
535
+ const artifact = coerceJsonStringArguments(await readQaGateArtifact(config, gate), toolInputSchema("qa", gate));
536
+ // Gates accept sidecars inside the evidence wrapper too; promote them so the verdict inherits
537
+ // them. A top-level value still takes precedence.
538
+ if (artifact.sidecars === undefined || artifact.sidecars === null) {
539
+ const nestedSidecars = qaEvidenceSource(artifact).sidecars;
540
+ if (nestedSidecars !== undefined && nestedSidecars !== null) {
541
+ artifact.sidecars = nestedSidecars;
542
+ }
543
+ }
544
+ for (const key of ["commands", "browser_checks", "sidecars", "checklist", "acceptance_criteria", "findings", "candidate_bugs"]) {
545
+ try {
546
+ qaArray(artifact, key);
547
+ }
548
+ catch (error) {
549
+ throw new Error(`${qaGateFileNames[gate]} recorded by ${gate} has an invalid ${key}: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
550
+ }
551
+ }
552
+ return artifact;
553
+ }
485
554
  export async function readQaGateArtifact(config, gate) {
486
555
  const ownerFields = artifactOwnerFields(config);
487
556
  const artifactRoot = ownerFields.owner_type && ownerFields.owner_id
@@ -0,0 +1,7 @@
1
+ export declare function validateQaGatePassingCommands(commands: readonly unknown[], options?: {
2
+ readonly allowClassifiedNonBlockingFailures?: boolean;
3
+ /** Payload field that holds these command records, for error messages. */
4
+ readonly label?: string;
5
+ /** Why a passing result is required, for error messages. */
6
+ readonly context?: string;
7
+ }): void;
@@ -0,0 +1,77 @@
1
+ /**
2
+ * Checks the command evidence records (commands, validation, narrow_validation,
3
+ * and similar fields) that a passing completion must report as passing, with
4
+ * the classified non-blocking failure exception for QA regression.
5
+ */
6
+ import { structuredTypeHint } from "./mcp-argument-coercion.js";
7
+ import { normalizedString, optionalString, requireNonEmptyStringRecord, throwCompletionPayloadIssues } from "./phase-completion.helpers.js";
8
+ export function validateQaGatePassingCommands(commands, options = {}) {
9
+ const label = options.label ?? "commands";
10
+ const context = options.context ?? "QA gate status is pass";
11
+ const issues = [];
12
+ for (const [index, command] of commands.entries()) {
13
+ if (!command || typeof command !== "object" || Array.isArray(command)) {
14
+ issues.push(`${label}[${index}] must be an object${structuredTypeHint(command, "object")}.`);
15
+ continue;
16
+ }
17
+ const record = command;
18
+ if (!optionalString(record, "command"))
19
+ issues.push(`${label}[${index}].command is required.`);
20
+ if (!optionalString(record, "status"))
21
+ issues.push(`${label}[${index}].status is required.`);
22
+ if (!optionalString(record, "summary"))
23
+ issues.push(`${label}[${index}].summary is required.`);
24
+ if (typeof record.exit_code !== "number" || !Number.isFinite(record.exit_code)) {
25
+ issues.push(`${label}[${index}].exit_code is required.`);
26
+ continue;
27
+ }
28
+ const passed = record.exit_code === 0 && normalizedString(record.status) === "pass";
29
+ if (!passed
30
+ && options.allowClassifiedNonBlockingFailures
31
+ && optionalString(record, "classification")) {
32
+ try {
33
+ validateClassifiedNonBlockingQaFailure(record, index, label);
34
+ }
35
+ catch (error) {
36
+ issues.push(error instanceof Error ? error.message : String(error));
37
+ }
38
+ continue;
39
+ }
40
+ if (record.exit_code !== 0) {
41
+ issues.push(`${label}[${index}].exit_code must be 0 when ${context}.`);
42
+ }
43
+ if (normalizedString(record.status) !== "pass") {
44
+ issues.push(`${label}[${index}].status must be pass when ${context}.`);
45
+ }
46
+ }
47
+ throwCompletionPayloadIssues(issues);
48
+ }
49
+ function validateClassifiedNonBlockingQaFailure(record, index, label) {
50
+ const prefix = `${label}[${index}]`;
51
+ const classification = normalizedString(optionalString(record, "classification"));
52
+ if (classification !== "out_of_scope_failure" && classification !== "baseline_failure") {
53
+ throw new Error(`${prefix}.classification must be out_of_scope_failure or baseline_failure: a non-passing command in a QA regression pass needs a classification with corroborating evidence.`);
54
+ }
55
+ const classified = `for a non-blocking ${classification} (also required: candidate_bug_id, scope_evidence, acceptance_criteria_independent: true, and ${classification === "out_of_scope_failure" ? "repro_command with a non-zero repro_exit_code" : "baseline_ref, a non-zero baseline_exit_code, and failure_signature_match: true"})`;
56
+ if (!optionalString(record, "candidate_bug_id"))
57
+ throw new Error(`${prefix}.candidate_bug_id is required ${classified}.`);
58
+ if (!optionalString(record, "scope_evidence"))
59
+ throw new Error(`${prefix}.scope_evidence is required ${classified}.`);
60
+ if (record.acceptance_criteria_independent !== true) {
61
+ throw new Error(`${prefix}.acceptance_criteria_independent must be true for a non-blocking QA regression failure.`);
62
+ }
63
+ if (classification === "out_of_scope_failure") {
64
+ requireNonEmptyStringRecord(record, "repro_command", `${prefix}.`);
65
+ if (typeof record.repro_exit_code !== "number" || !Number.isFinite(record.repro_exit_code) || record.repro_exit_code === 0) {
66
+ throw new Error(`${prefix}.repro_exit_code must be a non-zero number for an out-of-scope failure.`);
67
+ }
68
+ return;
69
+ }
70
+ requireNonEmptyStringRecord(record, "baseline_ref", `${prefix}.`);
71
+ if (typeof record.baseline_exit_code !== "number" || !Number.isFinite(record.baseline_exit_code) || record.baseline_exit_code === 0) {
72
+ throw new Error(`${prefix}.baseline_exit_code must be a non-zero number for a baseline failure.`);
73
+ }
74
+ if (record.failure_signature_match !== true) {
75
+ throw new Error(`${prefix}.failure_signature_match must be true for a baseline failure.`);
76
+ }
77
+ }
@@ -29,6 +29,8 @@ export interface CompletionToolRuntimeOptions {
29
29
  readonly worktree: WorktreeHandle;
30
30
  readonly phase?: CompletionPhase;
31
31
  readonly runtimeEnvironment?: Readonly<Record<string, string>>;
32
+ /** Host load governor variables; only the MCP server receives them. */
33
+ readonly hostLoadEnvironment?: Readonly<Record<string, string>>;
32
34
  }
33
35
  export interface CompletionToolServerConfig {
34
36
  readonly worktreePath: string;
@@ -94,6 +96,8 @@ export declare const debugCompletionPhaseOrder: readonly DebugCompletionPhase[];
94
96
  export declare const qaCompletionGateOrder: readonly QaCompletionGate[];
95
97
  export declare const draftCompletionGateOrder: readonly DraftCompletionGate[];
96
98
  export declare const decomposeCompletionGateOrder: readonly DecomposeCompletionGate[];
99
+ export declare const draftStatuses: readonly ["pass", "needs_revision", "needs_rework", "blocked"];
100
+ export declare const decomposeStatuses: readonly ["pass", "needs_rework", "fail", "failed", "needs_revision", "blocked"];
97
101
  export declare const decomposeGateFileNames: Record<DecomposeCompletionGate, string>;
98
102
  export declare const decomposeGateToolNames: Record<DecomposeCompletionGate, string>;
99
103
  export declare const draftGateFileNames: Record<DraftCompletionGate, string>;
@@ -3,6 +3,7 @@ import fs from "node:fs/promises";
3
3
  import path from "node:path";
4
4
  import { fileURLToPath } from "node:url";
5
5
  import { debugCompletionPhaseOrder, debugGateToolNames, decomposeCompletionGateOrder, decomposeGateToolNames, draftCompletionGateOrder, draftGateToolNames, qaCompletionGateOrder, qaGateToolNames, resolvedFindingStatuses } from "./phase-completion.js";
6
+ import { structuredTypeHint } from "./mcp-argument-coercion.js";
6
7
  export function normalizeArtifactPayload(payload, defaults) {
7
8
  const normalized = stripUndefined({ ...payload });
8
9
  delete normalized.report_markdown;
@@ -310,7 +311,7 @@ export function throwCompletionPayloadIssues(issues) {
310
311
  }
311
312
  export function requireArray(payload, key) {
312
313
  if (!Array.isArray(payload[key])) {
313
- throw new Error(`${key} must be an array.`);
314
+ throw new Error(`${key} must be an array${structuredTypeHint(payload[key], "array")}.`);
314
315
  }
315
316
  }
316
317
  export function requireNonEmptyArray(payload, key) {
@@ -332,7 +333,7 @@ export function requireAllowedStatus(payload, key, allowed) {
332
333
  export function requireObject(payload, key) {
333
334
  const value = payload[key];
334
335
  if (!value || typeof value !== "object" || Array.isArray(value)) {
335
- throw new Error(`${key} must be an object.`);
336
+ throw new Error(`${key} must be an object${structuredTypeHint(value, "object")}.`);
336
337
  }
337
338
  }
338
339
  export function requiredRecord(payload, key) {
@@ -372,12 +373,12 @@ export function validateResolvedFindings(payload) {
372
373
  return;
373
374
  }
374
375
  if (!Array.isArray(resolvedFindings)) {
375
- throw new Error("resolved_findings must be an array.");
376
+ throw new Error(`resolved_findings must be an array${structuredTypeHint(resolvedFindings, "array")}.`);
376
377
  }
377
378
  for (const [index, finding] of resolvedFindings.entries()) {
378
379
  const prefix = `resolved_findings[${index}].`;
379
380
  if (!finding || typeof finding !== "object" || Array.isArray(finding)) {
380
- throw new Error(`resolved_findings[${index}] must be an object.`);
381
+ throw new Error(`resolved_findings[${index}] must be an object${structuredTypeHint(finding, "object")}.`);
381
382
  }
382
383
  const record = finding;
383
384
  requireNonEmptyStringRecord(record, "qa_id", prefix);
@@ -409,14 +410,14 @@ export function qaArray(payload, key, fallback = {}) {
409
410
  return [];
410
411
  }
411
412
  if (!Array.isArray(value)) {
412
- throw new Error(`${key} must be an array.`);
413
+ throw new Error(`${key} must be an array${structuredTypeHint(value, "array")}.`);
413
414
  }
414
415
  return value;
415
416
  }
416
417
  export function qaObjectArray(payload, key) {
417
418
  return qaArray(payload, key).map((entry, index) => {
418
419
  if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
419
- throw new Error(`${key}[${index}] must be an object.`);
420
+ throw new Error(`${key}[${index}] must be an object${structuredTypeHint(entry, "object")}.`);
420
421
  }
421
422
  return entry;
422
423
  });
@@ -424,7 +425,7 @@ export function qaObjectArray(payload, key) {
424
425
  export function qaPolicyWarnings(payload) {
425
426
  return qaArray(payload, "policy_warnings").map((entry, index) => {
426
427
  if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
427
- throw new Error(`policy_warnings[${index}] must be an object.`);
428
+ throw new Error(`policy_warnings[${index}] must be an object${structuredTypeHint(entry, "object")}.`);
428
429
  }
429
430
  const warning = entry;
430
431
  const prefix = `policy_warnings[${index}].`;
@@ -448,7 +449,7 @@ export function qaStringArray(payload, key) {
448
449
  return [];
449
450
  }
450
451
  if (!Array.isArray(value)) {
451
- throw new Error(`${key} must be an array.`);
452
+ throw new Error(`${key} must be an array${structuredTypeHint(value, "array")}.`);
452
453
  }
453
454
  return value.map((entry, index) => {
454
455
  if (typeof entry !== "string" || entry.trim().length === 0) {
@@ -459,7 +460,7 @@ export function qaStringArray(payload, key) {
459
460
  }
460
461
  export function requireEvidenceRecord(value, label) {
461
462
  if (!value || typeof value !== "object" || Array.isArray(value)) {
462
- throw new Error(`${label} must be an object.`);
463
+ throw new Error(`${label} must be an object${structuredTypeHint(value, "object")}.`);
463
464
  }
464
465
  }
465
466
  export function requireNonEmptyStringRecord(source, key, prefix = "") {
@@ -469,7 +470,7 @@ export function requireNonEmptyStringRecord(source, key, prefix = "") {
469
470
  }
470
471
  export function requireArrayRecord(source, key, prefix = "") {
471
472
  if (!Array.isArray(source[key])) {
472
- throw new Error(`${prefix}${key} must be an array.`);
473
+ throw new Error(`${prefix}${key} must be an array${structuredTypeHint(source[key], "array")}.`);
473
474
  }
474
475
  }
475
476
  export function requireKnownStringRecord(source, key, allowed, prefix = "") {
@@ -497,7 +498,7 @@ export function requireSubstantiveValueRecord(source, key, prefix = "") {
497
498
  export function requireSubstantiveEvidenceRecord(source, prefix = "") {
498
499
  const evidence = source.evidence;
499
500
  if (!evidence || typeof evidence !== "object" || Array.isArray(evidence)) {
500
- throw new Error(`${prefix}evidence must be an object.`);
501
+ throw new Error(`${prefix}evidence must be an object${structuredTypeHint(evidence, "object")}, for example {"summary": "...", "screenshot": "..."}.`);
501
502
  }
502
503
  if (!Object.values(evidence).some(hasSubstantiveJsonValue)) {
503
504
  throw new Error(`${prefix}evidence must include at least one concrete evidence reference or summary.`);
@@ -587,7 +588,7 @@ export function parseOptionalJsonObject(content, label) {
587
588
  }
588
589
  export function asRecord(value, label) {
589
590
  if (!value || typeof value !== "object" || Array.isArray(value)) {
590
- throw new Error(`${label} must be an object.`);
591
+ throw new Error(`${label} must be an object${structuredTypeHint(value, "object")}.`);
591
592
  }
592
593
  return value;
593
594
  }
@@ -40,6 +40,10 @@ export const decomposeCompletionGateOrder = [
40
40
  "decompose_critic",
41
41
  "decompose_proposal"
42
42
  ];
43
+ // Statuses the Draft and Decompose gate tools advertise and accept. Decompose adds fail/failed;
44
+ // every status except pass records rework, never a pass.
45
+ export const draftStatuses = ["pass", "needs_revision", "needs_rework", "blocked"];
46
+ export const decomposeStatuses = ["pass", "needs_rework", "fail", "failed", "needs_revision", "blocked"];
43
47
  export const decomposeGateFileNames = {
44
48
  decompose_subject_intake: "decompose.subject-intake.json",
45
49
  decompose_context_review: "decompose.context-review.json",
@@ -76,6 +76,7 @@ Complete the Draft cycle in order inside this same provider session:
76
76
  5. Follow the returned draft-plan instruction, draft the requested final JSON shape for the current Draft kind, then call \`forge.complete_draft_work_order_plan(...)\`.
77
77
  6. Follow the returned critic instruction, critique literalism, wrong-project scope, and decomposition quality, then call \`forge.complete_draft_critic(...)\`.
78
78
  7. Follow the returned proposal instruction, then call \`forge.complete_draft_proposal(...)\` with the final Draft JSON payload in \`draft_json\`.
79
+ Every gate before the proposal needs a \`summary\` of what it checked or decided.
79
80
  The final proposal tool writes \`draft.proposal.json\` under \`.forge/work-items/{workItemId}/artifacts/\`. Reporting Draft completion in prose is not enough.`;
80
81
  }
81
82
  export function completionPromptForDecomposeCycle(currentGate = "decompose_subject_intake") {
@@ -92,6 +93,7 @@ Required order:
92
93
  5. Follow the returned dependency-graph instruction, validate keys/dependencies/order, then call \`forge.complete_decompose_dependency_graph(...)\`.
93
94
  6. Follow the returned critic instruction, critique scope, DAG safety, manual reconciliation risk, and missing acceptance detail, then call \`forge.complete_decompose_critic(...)\`.
94
95
  7. Follow the returned proposal instruction, then call \`forge.complete_decompose_proposal(...)\` with final JSON in \`proposal_json\`.
96
+ Every gate before the proposal needs a \`summary\` of what it checked or decided.
95
97
  The final proposal tool writes \`decompose.proposal.json\` under \`.forge/work-items/{workItemId}/artifacts/\`. The proposal_json object must contain summary, optional blockedReason, and candidates. Work Order-to-Feature candidates may include \`estimated_qa_scope\`; Feature-to-Story candidates should include \`qa_scope\` with schema_version 1 plus scheduleIndex, waveIndex, expectedOutput, handoffSummary, and dependencyReason for dependency handoff. Set \`qa_scope.required_capabilities\` to \`["docker_engine"]\` when implementation or validation starts containers or needs a Docker daemon; repository-specific service and image versions do not belong in the runner capability name.`;
96
98
  }
97
99
  export function completionPromptForDebugCycle(currentGate = "debug_repro") {
@@ -144,6 +146,9 @@ export function completionToolNextInstructionForDraftGate(completedGate, status,
144
146
  if (status === "blocked") {
145
147
  return `Stay in ${completedGate}; record the blocker and retry the same Draft gate when unblocked.`;
146
148
  }
149
+ if (status !== "pass") {
150
+ return `Stay in ${completedGate}; revise the work and call the same Draft gate again with status pass when it is complete.`;
151
+ }
147
152
  if (!nextGate) {
148
153
  return "Draft proposal accepted. Forge has the structured Work Order draft JSON needed to populate the form.";
149
154
  }
@@ -216,7 +221,7 @@ export function completionToolNextInstructionForDebugGate(completedGate, status,
216
221
  function qaGateInstruction(gate) {
217
222
  switch (gate) {
218
223
  case "qa_regression":
219
- return "Run or explicitly skip applicable regression/build/lint/typecheck/e2e checks, then call forge.complete_qa_regression. For normal Story QA, prefer focused checks and runner-authored forge.start_managed_verification tier profiles; reserve dotnet_solution for shared infrastructure, Feature/PR integration, or an explicit plan requirement. Use forge.start_managed_command only for other commands expected to exceed two minutes, continue independent QA, then call forge.wait_managed_command and include its terminal managed_command_id in command evidence. If the wait returns command_continues=true, continue useful work or wait again after retry_after_ms; do not poll get_managed_command. Normalize negative assertions so an expected no-match exits 0. A reproduced failure outside the current diff and acceptance criteria may remain non-blocking only when the current item has independent passing evidence: preserve it as an out_of_scope_failure with candidate_bug_id, scope_evidence, acceptance_criteria_independent: true, and a failing focused repro command/exit code. Never classify an unexplained, in-scope, or infrastructure failure this way.";
224
+ return "Run or explicitly skip applicable regression/build/lint/typecheck/e2e checks, then call forge.complete_qa_regression. For normal Story QA, prefer focused checks and runner-authored forge.start_managed_verification .NET tier profiles (run_all_shards needs shard_count of at least 2 and no no_build); run Playwright e2e through forge.start_managed_command with the attempt's FORGE_PLAYWRIGHT_CONFIG and the spec files you need; reserve dotnet_solution for shared infrastructure, Feature/PR integration, or an explicit plan requirement. Use forge.start_managed_command only for other commands expected to exceed two minutes, continue independent QA, then call forge.wait_managed_command and include its terminal managed_command_id in command evidence. If the wait returns command_continues=true, continue useful work or wait again after retry_after_ms; do not poll get_managed_command. Normalize negative assertions so an expected no-match exits 0. A reproduced failure outside the current diff and acceptance criteria may remain non-blocking only when the current item has independent passing evidence: preserve it as an out_of_scope_failure with candidate_bug_id, scope_evidence, acceptance_criteria_independent: true, and a failing focused repro command/exit code. Never classify an unexplained, in-scope, or infrastructure failure this way.";
220
225
  case "qa_api":
221
226
  return "Run or explicitly skip applicable API/backend contract checks, then call forge.complete_qa_api.";
222
227
  case "qa_manual_web":
@@ -17,7 +17,7 @@ export declare class CompletionToolServerSession {
17
17
  constructor(config: CompletionToolServerConfig);
18
18
  get instructions(): string;
19
19
  toolDefinitions(): readonly unknown[];
20
- callTool(toolName: string, input: unknown): Promise<CompletionToolCallResult | ManagedAttemptToolResult>;
20
+ callTool(toolName: string, rawInput: unknown): Promise<CompletionToolCallResult | ManagedAttemptToolResult>;
21
21
  private callDecomposeGateTool;
22
22
  private callDraftGateTool;
23
23
  private callDebugGateTool;
@@ -28,7 +28,7 @@ export declare class CompletionToolServerSession {
28
28
  private advanceAfterQaGate;
29
29
  private advanceAfterDebugGate;
30
30
  }
31
- export declare function completionToolRuntimeEnvironment(runtimeEnvironment?: Readonly<Record<string, string>>, nativeTestPostgresFallbackPath?: string | null): Readonly<Record<string, string>>;
31
+ export declare function completionToolRuntimeEnvironment(runtimeEnvironment?: Readonly<Record<string, string>>, nativeTestPostgresFallbackPath?: string | null, hostLoadEnvironment?: Readonly<Record<string, string>>): Readonly<Record<string, string>>;
32
32
  /**
33
33
  * A solution-wide Forge test is long enough that a generic provider shell can
34
34
  * expire while VSTest is still healthy. On managed host attempts, only the
@@ -46,4 +46,6 @@ export declare function parseCompletionMcpArgs(argv: readonly string[]): {
46
46
  readonly error: string;
47
47
  };
48
48
  export declare function completionRedactionEnv(secrets: readonly string[]): Readonly<Record<string, string>>;
49
- export declare function completionToolRejectedResult(toolName: string, error: unknown): Readonly<Record<string, unknown>>;
49
+ export declare function completionToolRejectedResult(toolName: string, error: unknown, input?: unknown): Readonly<Record<string, unknown>>;
50
+ /** The input schema a completion tool advertises; also the shape its arguments are coerced to. */
51
+ export declare function completionToolInputSchema(name: string): unknown;
@@ -6,9 +6,11 @@ import { completionPhaseFromDispatch, completionPhaseOrder, completionRedactionS
6
6
  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";
7
7
  import { completionPromptForDebugCycle, completionPromptForDecomposeCycle, completionPromptForDevelopCycle, completionPromptForDraftCycle, completionPromptForPhase, completionPromptForQaCycle, completionToolNextInstruction, completionToolNextInstructionForDebugGate, completionToolNextInstructionForDecomposeGate, completionToolNextInstructionForDraftGate, completionToolNextInstructionForQaGate, nextDebugPhaseAfter, nextPhaseAfter } from "./phase-completion.prompts.js";
8
8
  import { configuredNativeTestPostgresFallbackPath, nativeTestPostgresFallbackConfigEnvironment, } from "../runtime/native-test-postgres-fallback.js";
9
+ import { isHostLoadChildEnvironmentName } from "../runtime/host-load-child-environment.js";
9
10
  import { toolDescription, toolInputSchema } from "./phase-completion.schemas.js";
11
+ import { coerceJsonStringArguments, emptyToolInputHint, isEmptyToolInput } from "./mcp-argument-coercion.js";
10
12
  import { writeCompletionArtifact, writeDecomposeGateCompletionArtifact, writeDraftGateCompletionArtifact } from "./phase-completion.artifacts.js";
11
- import { callManagedAttemptTool, isManagedAttemptTool, managedAttemptToolDefinition, managedAttemptToolNames, runWithOwnerShutdown, } from "./managed-attempt-tools.js";
13
+ import { callManagedAttemptTool, isManagedAttemptTool, managedAttemptToolDefinition, managedAttemptToolInputSchema, managedAttemptToolNames, runWithOwnerShutdown, } from "./managed-attempt-tools.js";
12
14
  export async function prepareCompletionToolRuntime(options) {
13
15
  const phase = options.phase ?? completionPhaseFromDispatch(options.dispatch);
14
16
  const worktreePath = path.resolve(options.worktree.worktreePath);
@@ -36,7 +38,7 @@ export async function prepareCompletionToolRuntime(options) {
36
38
  serverName: toolServerName,
37
39
  command: process.execPath,
38
40
  args: [forgeBridgeCliBinPath(), ...mcpArgs],
39
- env: completionToolRuntimeEnvironment(options.runtimeEnvironment, configuredNativeTestPostgresFallbackPath()),
41
+ env: completionToolRuntimeEnvironment(options.runtimeEnvironment, configuredNativeTestPostgresFallbackPath(), options.hostLoadEnvironment),
40
42
  cleanup: async () => undefined
41
43
  };
42
44
  const provider = options.dispatch.execution.provider.trim().toLowerCase();
@@ -157,23 +159,26 @@ export class CompletionToolServerSession {
157
159
  : completionPromptForPhase(this.currentPhase, artifactOwnerRelativeRoot(this.config.ownerType, this.config.ownerId, this.config.workItemId));
158
160
  }
159
161
  toolDefinitions() {
160
- const completionTools = completionToolNamesForServer(this.config).map((name) => toolDefinition(name, phaseFromToolName(name), qaGateFromToolName(name), decomposeGateFromToolName(name)));
162
+ const completionTools = completionToolNamesForServer(this.config).map(toolDefinition);
161
163
  return managedAttemptToolsAvailable()
162
164
  ? [...completionTools, ...managedAttemptToolNames.map(managedAttemptToolDefinition)]
163
165
  : completionTools;
164
166
  }
165
- async callTool(toolName, input) {
167
+ async callTool(toolName, rawInput) {
166
168
  if (isManagedAttemptTool(toolName)) {
167
169
  if (!managedAttemptToolsAvailable()) {
168
170
  throw new Error("Forge managed-attempt tools require an active managed host runtime.");
169
171
  }
170
- const result = await callManagedAttemptTool(toolName, input, this.config.worktreePath);
172
+ const managedInput = coerceJsonStringArguments(rawInput, managedAttemptToolInputSchema(toolName));
173
+ const result = await callManagedAttemptTool(toolName, managedInput, this.config.worktreePath);
171
174
  if (Array.isArray(result.structuredContent.command)) {
172
175
  this.managedCommandReceipts.push(result.structuredContent);
173
176
  }
174
177
  return result;
175
178
  }
176
179
  const requestedPhase = phaseFromToolName(toolName);
180
+ // Clients sometimes send a declared array/object argument as its JSON text.
181
+ const input = coerceJsonStringArguments(rawInput, completionToolInputSchema(toolName));
177
182
  if (this.completed) {
178
183
  throw new Error("Forge completion cycle is already complete; no more completion calls are accepted.");
179
184
  }
@@ -270,15 +275,26 @@ export class CompletionToolServerSession {
270
275
  const completedGate = this.currentDraftGate;
271
276
  const reference = await writeDraftGateCompletionArtifact(this.config, completedGate, toolName, input);
272
277
  const status = reference.status.trim().toLowerCase();
273
- const nextGate = this.advanceAfterDraftGate(completedGate);
274
- const nextPhase = nextGate ? "draft" : "sign_off_ready";
275
- const nextInstruction = completionToolNextInstructionForDraftGate(completedGate, status, nextGate);
278
+ // Only a pass completes a Draft gate; needs_revision, needs_rework, and blocked keep the same
279
+ // gate selected so it is retried, never skipped.
280
+ const pass = status === "pass";
281
+ const nextGate = pass ? this.advanceAfterDraftGate(completedGate) : completedGate;
282
+ const nextPhase = pass ? (nextGate ? "draft" : "sign_off_ready") : "draft";
283
+ const nextInstruction = completionToolNextInstructionForDraftGate(completedGate, status, pass ? nextGate : null);
276
284
  return {
277
285
  content: [{ type: "text", text: `Forge recorded ${completedGate} artifact ${path.relative(reference.repoPath, reference.path)} (${reference.status}, ${reference.contentHash}). ${nextInstruction}` }],
278
286
  structuredContent: {
279
287
  ...reference,
280
288
  ...acceptedArtifactReceipt(reference),
281
- gate: { phase: "draft", draftGate: completedGate, status, allowed: status !== "blocked", reason: nextGate ? `${completedGate} artifact accepted; continue to ${nextGate}.` : `Draft proposal artifact accepted with status ${status}.` },
289
+ gate: {
290
+ phase: "draft",
291
+ draftGate: completedGate,
292
+ status,
293
+ allowed: pass,
294
+ reason: !pass
295
+ ? `${completedGate} artifact recorded with status ${status}; rework is required before continuing.`
296
+ : nextGate ? `${completedGate} artifact accepted; continue to ${nextGate}.` : `Draft proposal artifact accepted with status ${status}.`
297
+ },
282
298
  nextPhase,
283
299
  nextInstruction
284
300
  }
@@ -458,18 +474,25 @@ const completionToolRuntimeEnvironmentNames = [
458
474
  "TMP",
459
475
  "TEMP",
460
476
  ];
461
- export function completionToolRuntimeEnvironment(runtimeEnvironment, nativeTestPostgresFallbackPath) {
462
- if (!runtimeEnvironment)
463
- return {};
477
+ export function completionToolRuntimeEnvironment(runtimeEnvironment, nativeTestPostgresFallbackPath, hostLoadEnvironment) {
464
478
  const env = {};
479
+ // Without a runtime environment the server gets nothing from it, but it still
480
+ // joins the host ledger when the bridge handed it the governor's variables.
481
+ if (!runtimeEnvironment && !hostLoadEnvironment)
482
+ return env;
465
483
  for (const name of completionToolRuntimeEnvironmentNames) {
466
- const value = runtimeEnvironment[name]?.trim();
484
+ const value = runtimeEnvironment?.[name]?.trim();
467
485
  if (value)
468
486
  env[name] = value;
469
487
  }
488
+ // The host load governor's flag, state root and tuning: managed commands join its ledger.
489
+ for (const [name, value] of Object.entries(hostLoadEnvironment ?? {})) {
490
+ if (isHostLoadChildEnvironmentName(name) && value.trim())
491
+ env[name] = value.trim();
492
+ }
470
493
  // Managed verification reads the operator's native test cluster only through
471
494
  // this explicit path, and only while Docker is unavailable.
472
- if (nativeTestPostgresFallbackPath) {
495
+ if (runtimeEnvironment && nativeTestPostgresFallbackPath) {
473
496
  env[nativeTestPostgresFallbackConfigEnvironment] = nativeTestPostgresFallbackPath;
474
497
  }
475
498
  return env;
@@ -800,15 +823,18 @@ async function handleJsonRpcRequest(session, method, params) {
800
823
  catch (error) {
801
824
  if (isManagedAttemptTool(name))
802
825
  throw error;
803
- return completionToolRejectedResult(name, error);
826
+ return completionToolRejectedResult(name, error, args);
804
827
  }
805
828
  }
806
829
  throw new Error(`Unsupported MCP method: ${method}`);
807
830
  }
808
- export function completionToolRejectedResult(toolName, error) {
831
+ export function completionToolRejectedResult(toolName, error, input) {
809
832
  const issues = error instanceof CompletionPayloadValidationError
810
833
  ? [...error.issues]
811
834
  : [errorMessage(error)];
835
+ if (input !== undefined && isEmptyToolInput(input)) {
836
+ issues.push(`${emptyToolInputHint} Keep long free text such as report_markdown short.`);
837
+ }
812
838
  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.";
813
839
  return {
814
840
  content: [{
@@ -836,10 +862,14 @@ function acceptedArtifactReceipt(reference) {
836
862
  },
837
863
  };
838
864
  }
839
- function toolDefinition(name, phase, qaGate = null, decomposeGate = null) {
865
+ function toolDefinition(name) {
840
866
  return {
841
867
  name,
842
- description: toolDescription(phase, qaGate, decomposeGate),
843
- inputSchema: toolInputSchema(phase, qaGate, decomposeGate)
868
+ description: toolDescription(phaseFromToolName(name), qaGateFromToolName(name), decomposeGateFromToolName(name), draftGateFromToolName(name)),
869
+ inputSchema: completionToolInputSchema(name)
844
870
  };
845
871
  }
872
+ /** The input schema a completion tool advertises; also the shape its arguments are coerced to. */
873
+ export function completionToolInputSchema(name) {
874
+ return toolInputSchema(phaseFromToolName(name), qaGateFromToolName(name), decomposeGateFromToolName(name), draftGateFromToolName(name));
875
+ }