@loucompanion/forge-bridge 0.1.4-dev.c1ae24134918 → 0.1.4-dev.ccffca94938b

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 (128) hide show
  1. package/README.md +55 -0
  2. package/dist/bridge/bridge-chat-provider-command.d.ts +16 -0
  3. package/dist/bridge/bridge-chat-provider-command.js +137 -0
  4. package/dist/bridge/bridge-chat.types.d.ts +10 -0
  5. package/dist/bridge/bridge-chat.types.js +16 -1
  6. package/dist/bridge/bridge.base.d.ts +9 -0
  7. package/dist/bridge/bridge.service.d.ts +71 -2
  8. package/dist/bridge/bridge.service.js +283 -115
  9. package/dist/bridge/bridge.types.d.ts +11 -0
  10. package/dist/bridge/local-yield-flag.d.ts +6 -0
  11. package/dist/bridge/local-yield-flag.js +34 -0
  12. package/dist/bridge/runner-host-capabilities.d.ts +3 -0
  13. package/dist/bridge/runner-host-capabilities.js +13 -0
  14. package/dist/cleanup/cleanup.service.d.ts +9 -0
  15. package/dist/cleanup/cleanup.service.js +72 -109
  16. package/dist/cleanup/cleanup.types.d.ts +4 -0
  17. package/dist/cleanup/forge-owned-paths.d.ts +9 -0
  18. package/dist/cleanup/forge-owned-paths.js +53 -0
  19. package/dist/cleanup/host-runtime-ledger.d.ts +5 -0
  20. package/dist/cleanup/host-runtime-ledger.js +109 -0
  21. package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
  22. package/dist/cleanup/managed-branch-sweep.js +111 -0
  23. package/dist/cli/cli.help.js +18 -0
  24. package/dist/cli/cli.service.d.ts +16 -0
  25. package/dist/cli/cli.service.js +139 -15
  26. package/dist/cli/local-config.d.ts +4 -0
  27. package/dist/cli/local-config.js +26 -4
  28. package/dist/runtime/aspnet-runtime-prebuild.js +94 -6
  29. package/dist/runtime/host-facts.d.ts +2 -1
  30. package/dist/runtime/host-load-admission.d.ts +18 -3
  31. package/dist/runtime/host-load-admission.js +19 -4
  32. package/dist/runtime/host-load-child-environment.d.ts +11 -6
  33. package/dist/runtime/host-load-child-environment.js +22 -11
  34. package/dist/runtime/host-load-governor-config.d.ts +19 -1
  35. package/dist/runtime/host-load-governor-config.js +37 -0
  36. package/dist/runtime/host-load-governor.d.ts +12 -0
  37. package/dist/runtime/host-load-governor.js +139 -26
  38. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  39. package/dist/runtime/host-load-runtime-settings.js +78 -0
  40. package/dist/runtime/host-load-sampler.d.ts +34 -4
  41. package/dist/runtime/host-load-sampler.js +73 -7
  42. package/dist/runtime/host-load-step-class.d.ts +3 -1
  43. package/dist/runtime/host-load-step-class.js +60 -5
  44. package/dist/runtime/host-load-test-slot.d.ts +43 -0
  45. package/dist/runtime/host-load-test-slot.js +81 -0
  46. package/dist/runtime/host-load-token-ledger.d.ts +26 -0
  47. package/dist/runtime/host-load-token-ledger.js +93 -61
  48. package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
  49. package/dist/runtime/host-load-windows-cpu.js +85 -0
  50. package/dist/runtime/host-runtime-lease.d.ts +59 -3
  51. package/dist/runtime/host-runtime-lease.js +199 -8
  52. package/dist/runtime/host-runtime-promotion.d.ts +23 -0
  53. package/dist/runtime/host-runtime-promotion.js +36 -0
  54. package/dist/runtime/playwright-host-runtime-adapter.d.ts +7 -0
  55. package/dist/runtime/playwright-host-runtime-adapter.js +13 -1
  56. package/dist/runtime/runner-settings.d.ts +100 -0
  57. package/dist/runtime/runner-settings.js +214 -0
  58. package/dist/sandbox/host-capacity-broker.d.ts +7 -1
  59. package/dist/sandbox/host-capacity-broker.js +23 -4
  60. package/dist/session/architect-waits.d.ts +2 -0
  61. package/dist/session/architect-waits.js +138 -0
  62. package/dist/session/managed-attempt-tools.d.ts +2 -0
  63. package/dist/session/managed-attempt-tools.js +44 -22
  64. package/dist/session/managed-command-host-load.d.ts +2 -0
  65. package/dist/session/managed-command-host-load.js +2 -1
  66. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  67. package/dist/session/mcp-argument-coercion.js +121 -0
  68. package/dist/session/phase-completion.artifacts.d.ts +7 -0
  69. package/dist/session/phase-completion.artifacts.js +94 -25
  70. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  71. package/dist/session/phase-completion.command-validation.js +77 -0
  72. package/dist/session/phase-completion.d.ts +2 -0
  73. package/dist/session/phase-completion.helpers.js +13 -12
  74. package/dist/session/phase-completion.js +4 -0
  75. package/dist/session/phase-completion.prompts.js +6 -1
  76. package/dist/session/phase-completion.runtime.d.ts +4 -2
  77. package/dist/session/phase-completion.runtime.js +35 -13
  78. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  79. package/dist/session/phase-completion.schema-parts.js +188 -0
  80. package/dist/session/phase-completion.schemas.d.ts +3 -3
  81. package/dist/session/phase-completion.schemas.js +208 -231
  82. package/dist/session/phase-completion.validation.d.ts +2 -3
  83. package/dist/session/phase-completion.validation.js +49 -93
  84. package/dist/session/pre-publication-pass.d.ts +61 -0
  85. package/dist/session/pre-publication-pass.js +148 -0
  86. package/dist/session/pre-publication-validation.d.ts +23 -11
  87. package/dist/session/pre-publication-validation.js +178 -107
  88. package/dist/session/provider-cli/claude-background-work.d.ts +66 -0
  89. package/dist/session/provider-cli/claude-background-work.js +180 -0
  90. package/dist/session/provider-cli/pre-publication-repair.d.ts +40 -0
  91. package/dist/session/provider-cli/pre-publication-repair.js +243 -0
  92. package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
  93. package/dist/session/provider-cli/provider-cli.child-environment.js +73 -0
  94. package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
  95. package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
  96. package/dist/session/provider-cli/provider-cli.process.d.ts +13 -22
  97. package/dist/session/provider-cli/provider-cli.process.js +36 -337
  98. package/dist/session/provider-cli/provider-cli.prompts.d.ts +2 -0
  99. package/dist/session/provider-cli/provider-cli.prompts.js +50 -10
  100. package/dist/session/provider-cli/provider-cli.runtime.js +7 -0
  101. package/dist/session/provider-cli/provider-cli.service.d.ts +4 -1
  102. package/dist/session/provider-cli/provider-cli.service.js +74 -151
  103. package/dist/session/provider-cli/provider-cli.types.d.ts +26 -0
  104. package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
  105. package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
  106. package/dist/session/provider-cli/provider-in-flight-work.d.ts +4 -0
  107. package/dist/session/provider-cli/provider-in-flight-work.js +45 -0
  108. package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
  109. package/dist/session/provider-cli/provider-output-pipes.js +67 -0
  110. package/dist/session/provider-cli/provider-output-state.d.ts +2 -0
  111. package/dist/session/provider-cli/provider-output-state.js +6 -0
  112. package/dist/session/sandbox-host-capacity-gate.js +12 -3
  113. package/dist/session/session.base.d.ts +6 -1
  114. package/dist/session/session.service.d.ts +7 -2
  115. package/dist/session/session.service.js +100 -2
  116. package/dist/session/session.types.js +3 -3
  117. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  118. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  119. package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
  120. package/dist/shared/process/windows-app-execution-alias.js +45 -0
  121. package/dist/shared/process/windows-launch.d.ts +18 -0
  122. package/dist/shared/process/windows-launch.js +68 -0
  123. package/dist/shared/provider-capabilities.js +5 -6
  124. package/dist/version.d.ts +1 -1
  125. package/dist/version.js +1 -1
  126. package/dist/worktree/worktree.service.d.ts +5 -1
  127. package/dist/worktree/worktree.service.js +29 -1
  128. package/package.json +2 -2
@@ -8,12 +8,13 @@ import { attemptDatabaseCapabilityEnvironment, attemptDatabaseCapabilitySecrets,
8
8
  import { assertHostDatabaseCapabilityBoundary } from "../runtime/host-database-capability-boundary.js";
9
9
  import { nativeTestPostgresFallbackConfigEnvironment, nativeTestPostgresFallbackDatabaseMode, nativeTestPostgresFallbackEnvironment, readNativeTestPostgresFallback, } from "../runtime/native-test-postgres-fallback.js";
10
10
  import { redactText } from "../shared/redaction/redaction.js";
11
+ import { emptyToolInputHint, isEmptyToolInput } from "./mcp-argument-coercion.js";
11
12
  import { ManagedBuildCoordinator } from "./managed-build-coordinator.js";
12
13
  import { attachManagedCommandProcess, ManagedCommandHostCapacity, } from "./managed-command-host-load.js";
13
14
  import { HostCapacityLedgerUnavailableError } from "../runtime/host-load-ledger-lock.js";
14
15
  import { isProcessTreeTerminationUnproven } from "../shared/process/process.js";
15
16
  import { HostCapacityTokenFencedError } from "../runtime/host-load-token-ledger.js";
16
- import { hostLoadGovernorEnvironment, hostLoadStateRootEnvironment } from "../runtime/host-load-child-environment.js";
17
+ import { withoutHostLoadGovernorVariables } from "../runtime/host-load-child-environment.js";
17
18
  import { managedBuildConfiguration, publishManagedBuildReceipt, verifyManagedBuildReceipt, } from "./managed-build-receipt.js";
18
19
  import { managedLongTierTimeoutMs, managedMaximumCommandTimeoutMs, managedVerificationTierTimeoutMs, } from "./managed-verification-timeouts.js";
19
20
  import { resolveWindowsCommandFromPath, StreamingProviderProcessRunner } from "./provider-cli/provider-cli.process.js";
@@ -148,11 +149,17 @@ export function isManagedAttemptTool(name) {
148
149
  || startManagedVerificationNames.has(name)
149
150
  || resetGeneratedOutputNames.has(name);
150
151
  }
152
+ const managedVerificationProfiles = ["dotnet_unit", "dotnet_contract", "dotnet_api_component", "dotnet_orchestration", "dotnet_infrastructure", "dotnet_solution", "dotnet_affected"];
153
+ const managedVerificationProfileHint = `Use one of: ${managedVerificationProfiles.join(", ")}. These are .NET test profiles only; run client, bridge, or Playwright e2e checks with forge.start_managed_command.`;
154
+ /** The input schema a managed-attempt tool advertises; also the shape its arguments are coerced to. */
155
+ export function managedAttemptToolInputSchema(name) {
156
+ return managedAttemptToolDefinition(name).inputSchema;
157
+ }
151
158
  export function managedAttemptToolDefinition(name) {
152
159
  if (startManagedVerificationNames.has(name)) {
153
160
  return {
154
161
  name,
155
- 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.",
162
+ description: "Start a canonical Forge .NET 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. To run every shard of a tier in one call, set run_all_shards: true with shard_count 2 or more and without no_build.",
156
163
  inputSchema: {
157
164
  type: "object",
158
165
  additionalProperties: false,
@@ -160,13 +167,14 @@ export function managedAttemptToolDefinition(name) {
160
167
  properties: {
161
168
  profile: {
162
169
  type: "string",
163
- enum: ["dotnet_unit", "dotnet_contract", "dotnet_api_component", "dotnet_orchestration", "dotnet_infrastructure", "dotnet_solution", "dotnet_affected"],
170
+ enum: [...managedVerificationProfiles],
171
+ description: "Required .NET test profile. dotnet_affected selects its own tests and owns its build: it takes no shard or no_build options. dotnet_solution takes no shard options. Client, bridge, and e2e checks are not profiles; use forge.start_managed_command for them.",
164
172
  },
165
- shard_count: { type: "integer", minimum: 1, maximum: 32, default: 1 },
166
- shard_index: { type: "integer", minimum: 0, maximum: 31, default: 0 },
167
- run_all_shards: { type: "boolean", default: false },
173
+ shard_count: { type: "integer", minimum: 1, maximum: 32, default: 1, description: "Number of shards to split the tier into. Must be at least 2 when run_all_shards is true." },
174
+ shard_index: { type: "integer", minimum: 0, maximum: 31, default: 0, description: "Which single shard to run; must be less than shard_count, and 0 when run_all_shards is true." },
175
+ run_all_shards: { type: "boolean", default: false, description: "Run every shard of the tier after one shared build. Requires shard_count of at least 2 and shard_index 0, cannot be combined with no_build, and is not supported for dotnet_solution or dotnet_affected." },
168
176
  max_parallelism: { type: "integer", minimum: 1, maximum: 4, default: 2 },
169
- no_build: { type: "boolean", default: false },
177
+ no_build: { type: "boolean", default: false, description: "Reuse the verified build from an earlier managed build instead of building. Not allowed with run_all_shards or dotnet_affected." },
170
178
  timeout_ms: { type: "integer", minimum: 1000, maximum: 7200000 },
171
179
  },
172
180
  },
@@ -183,8 +191,8 @@ export function managedAttemptToolDefinition(name) {
183
191
  additionalProperties: false,
184
192
  required: ["command", "args"],
185
193
  properties: {
186
- command: { type: "string", minLength: 1 },
187
- args: { type: "array", items: { type: "string" } },
194
+ command: { type: "string", minLength: 1, description: "Required executable only, for example pnpm, node, npm, or dotnet. Not a shell command line: shell syntax such as cd, &&, or pipes is not interpreted." },
195
+ args: { type: "array", items: { type: "string" }, description: "Required argument list, each argument its own string, for example [\"--dir\", \"client\", \"lint\"]. Send [] when there are none. Use cwd instead of cd." },
188
196
  cwd: { type: "string", description: "Worktree-relative directory; defaults to the worktree root." },
189
197
  timeout_ms: { type: "integer", minimum: 1000, maximum: 7200000, default: 2700000 },
190
198
  },
@@ -347,13 +355,13 @@ async function startManagedVerification(input, worktreePath) {
347
355
  const runAllShards = optionalBoolean(record.run_all_shards, "run_all_shards", false);
348
356
  const maxParallelism = optionalBoundedInteger(record.max_parallelism, "max_parallelism", 1, 4, 2);
349
357
  if (runAllShards && shardCount < 2) {
350
- throw new Error("managed_verification_invalid: run_all_shards requires shard_count of at least 2.");
358
+ throw new Error("managed_verification_invalid: run_all_shards requires shard_count of at least 2. Set shard_count to 2 or more to run every shard, or omit run_all_shards to run a single shard.");
351
359
  }
352
360
  if (runAllShards && shardIndex !== 0) {
353
361
  throw new Error("managed_verification_invalid: shard_index must be 0 when run_all_shards is enabled.");
354
362
  }
355
363
  if (runAllShards && noBuild) {
356
- throw new Error("managed_verification_invalid: run_all_shards owns the single prerequisite build and cannot be combined with no_build.");
364
+ throw new Error("managed_verification_invalid: run_all_shards owns the single prerequisite build and cannot be combined with no_build. Omit no_build when run_all_shards is true.");
357
365
  }
358
366
  const outputDirectory = requiredAttemptEnvironment("FORGE_TEST_OUTPUT_DIR");
359
367
  const profileCommand = buildManagedVerificationCommand(profile, outputDirectory, shardCount, shardIndex, noBuild, runAllShards, maxParallelism);
@@ -410,7 +418,7 @@ export function buildManagedVerificationCommand(profile, outputDirectory, shardC
410
418
  };
411
419
  const tier = tiers[profile];
412
420
  if (!tier)
413
- throw new Error(`managed_verification_invalid: unsupported profile ${profile}.`);
421
+ throw new Error(`managed_verification_invalid: unsupported profile ${profile}. ${managedVerificationProfileHint}`);
414
422
  const command = preferredPowerShellExecutable();
415
423
  if (runAllShards) {
416
424
  return {
@@ -439,7 +447,7 @@ export function buildManagedVerificationCommand(profile, outputDirectory, shardC
439
447
  export function preferredPowerShellExecutable(platform = process.platform, pathValue = process.env.PATH ?? "") {
440
448
  if (platform !== "win32")
441
449
  return "pwsh";
442
- return resolveWindowsCommandFromPath("pwsh.exe", pathValue) ?? "powershell.exe";
450
+ return resolveWindowsCommandFromPath("pwsh.exe", pathValue, undefined, { skipAppExecutionAliases: true }) ?? "powershell.exe";
443
451
  }
444
452
  export function validatePlaywrightProjectName(project, availableProjects) {
445
453
  if (!availableProjects.includes(project)) {
@@ -899,7 +907,7 @@ async function waitManagedCommand(input) {
899
907
  const lastOutputAt = Date.parse(String(receipt.structuredContent.last_output_at));
900
908
  const hostLoadWaitMs = receipt.structuredContent.host_load_wait_ms;
901
909
  const progress = receipt.structuredContent.status === "waiting_for_host_capacity" && typeof hostLoadWaitMs === "number"
902
- ? ` It has waited ${Math.round(hostLoadWaitMs / 1000)}s for host capacity and has not started yet; its timeout starts only once it is admitted, so queue time never counts against it. Keep waiting; a queued command is not a blocker.`
910
+ ? ` It has waited ${Math.round(hostLoadWaitMs / 1000)}s for host capacity${typeof receipt.structuredContent.host_load_wait_detail === "string" ? ` (${receipt.structuredContent.host_load_wait_detail})` : ""} and has not started yet; its timeout starts only once it is admitted, so queue time never counts against it. Keep waiting; a queued command is not a blocker.`
903
911
  : receipt.structuredContent.status === "running" && typeof elapsedMs === "number"
904
912
  ? ` It has run for ${Math.round(elapsedMs / 1000)}s`
905
913
  + (Number.isFinite(lastOutputAt) ? `, last output ${Math.max(0, Math.round((Date.now() - lastOutputAt) / 1000))}s ago` : ", with no output yet")
@@ -1025,7 +1033,7 @@ function managedCommandHostLoadReceipt(hostLoad) {
1025
1033
  return {
1026
1034
  host_load_step_class: hostLoad.stepClass,
1027
1035
  host_load_wait_ms: waiting ? Math.max(0, Date.now() - hostLoad.waitStartedAt) : hostLoad.waitMs,
1028
- ...(waiting ? { host_load_wait_started_at: new Date(hostLoad.waitStartedAt).toISOString() } : {}),
1036
+ ...(waiting ? { host_load_wait_started_at: new Date(hostLoad.waitStartedAt).toISOString(), host_load_wait_detail: hostLoad.waitDetail ?? null } : {}),
1029
1037
  };
1030
1038
  }
1031
1039
  async function annotateManagedCommandReceipt(receiptPath, fields) {
@@ -1107,11 +1115,10 @@ async function containedWorkingDirectory(worktreePath, input) {
1107
1115
  }
1108
1116
  function inheritedEnvironment(overrides) {
1109
1117
  const env = {};
1110
- for (const [key, value] of Object.entries(process.env)) {
1111
- // A nested Forge process must not join the host ledger: it would queue behind the
1112
- // token this command already holds.
1113
- if (key === hostLoadGovernorEnvironment || key === hostLoadStateRootEnvironment)
1114
- continue;
1118
+ // A nested Forge process must not join the host ledger: it would queue behind the
1119
+ // token this command already holds. Every FORGE_HOST_LOAD_* variable is dropped,
1120
+ // the test slot count too (decision 0018).
1121
+ for (const [key, value] of Object.entries(withoutHostLoadGovernorVariables(process.env))) {
1115
1122
  if (typeof value === "string" && !looksSensitiveEnvironmentName(key))
1116
1123
  env[key] = value;
1117
1124
  }
@@ -1200,8 +1207,17 @@ function asRecord(value) {
1200
1207
  throw new Error("managed_command_invalid: input must be an object.");
1201
1208
  return value;
1202
1209
  }
1210
+ const requiredInputExamples = {
1211
+ command: "Send the executable as command and each argument as its own string in args, for example {\"command\": \"pnpm\", \"args\": [\"--dir\", \"client\", \"lint\"]}.",
1212
+ profile: managedVerificationProfileHint,
1213
+ command_id: "Send the command_id returned by forge.start_managed_command or forge.start_managed_verification.",
1214
+ };
1203
1215
  function requiredInputString(record, name) {
1204
- return requiredStandaloneString(record[name], name);
1216
+ const value = record[name];
1217
+ if (typeof value === "string" && value.trim())
1218
+ return value.trim();
1219
+ const hints = [requiredInputExamples[name], isEmptyToolInput(record) ? emptyToolInputHint : undefined].filter(Boolean);
1220
+ throw new Error(`managed_command_invalid: ${name} is required.${hints.length > 0 ? ` ${hints.join(" ")}` : ""}`);
1205
1221
  }
1206
1222
  function validatedCommandId(record) {
1207
1223
  const commandId = requiredInputString(record, "command_id");
@@ -1218,7 +1234,13 @@ function requiredStandaloneString(value, name) {
1218
1234
  function requiredStringArray(record, name) {
1219
1235
  const value = record[name];
1220
1236
  if (!Array.isArray(value) || value.some(entry => typeof entry !== "string")) {
1221
- throw new Error(`managed_command_invalid: ${name} must be a string array.`);
1237
+ const shellLine = typeof record.command === "string" && /\s/u.test(record.command.trim());
1238
+ const hint = typeof value === "string"
1239
+ ? " (received a string). Put each argument in its own string, for example [\"--dir\", \"client\", \"test\"]."
1240
+ : value === undefined
1241
+ ? ` (it was omitted). Send [] when there are no arguments.${shellLine ? " command holds only the executable, so move its arguments into args; shell syntax such as cd, &&, or pipes is not interpreted, so set cwd instead of cd." : ""}`
1242
+ : " Every argument must be a string.";
1243
+ throw new Error(`managed_command_invalid: ${name} must be a string array${hint}`);
1222
1244
  }
1223
1245
  return value;
1224
1246
  }
@@ -8,6 +8,8 @@ export interface ManagedCommandHostLoadFields {
8
8
  readonly waitMs: number;
9
9
  /** Set while the command is still queued: the receipt reports the wait so far. */
10
10
  readonly waitStartedAt?: number;
11
+ /** Why it waits, for example for the host test slot and who holds it (decision 0018). */
12
+ readonly waitDetail?: string;
11
13
  /** When the command was admitted; elapsed_ms counts from here. */
12
14
  readonly executionStartedAt?: number;
13
15
  }
@@ -45,11 +45,12 @@ export class ManagedCommandHostCapacity {
45
45
  signal,
46
46
  // The receipt says host_capacity_token_fenced itself (termination_reason).
47
47
  reportsOwnFence: true,
48
- onWaiting: () => {
48
+ onWaiting: decision => {
49
49
  this.waitingWrite = this.persistWaiting({
50
50
  stepClass: this.classification.stepClass,
51
51
  waitMs: 0,
52
52
  waitStartedAt: this.requestedAtMs ?? Date.now(),
53
+ waitDetail: decision.detail,
53
54
  }).catch(() => undefined);
54
55
  },
55
56
  onReleaseFailed,
@@ -0,0 +1,23 @@
1
+ /**
2
+ * MCP clients sometimes send a structured tool argument as its JSON text, for
3
+ * example `sidecars: "[{...}]"` instead of `sidecars: [{...}]`. At the tool-call
4
+ * boundary, before any validation, this replaces such a string with its parsed
5
+ * value, but only where the tool's declared input schema says the value is an
6
+ * array or an object and the string parses to exactly that kind of value.
7
+ *
8
+ * Nothing else is coerced: a string field that happens to contain JSON stays a
9
+ * string, an undeclared field is left alone, and a malformed string is passed
10
+ * through unchanged so the validator reports it.
11
+ */
12
+ export declare function coerceJsonStringArguments(value: unknown, schema: unknown): unknown;
13
+ type StructuredKind = "array" | "object";
14
+ /**
15
+ * Explains why a value is not the expected array or object, for validator
16
+ * messages. A string gets an explicit instruction because that is the usual
17
+ * client mistake; the hint never echoes the value itself.
18
+ */
19
+ export declare function structuredTypeHint(value: unknown, expected: StructuredKind): string;
20
+ /** True when a tool call arrived with no usable arguments at all. */
21
+ export declare function isEmptyToolInput(input: unknown): boolean;
22
+ export declare const emptyToolInputHint: string;
23
+ export {};
@@ -0,0 +1,121 @@
1
+ /**
2
+ * MCP clients sometimes send a structured tool argument as its JSON text, for
3
+ * example `sidecars: "[{...}]"` instead of `sidecars: [{...}]`. At the tool-call
4
+ * boundary, before any validation, this replaces such a string with its parsed
5
+ * value, but only where the tool's declared input schema says the value is an
6
+ * array or an object and the string parses to exactly that kind of value.
7
+ *
8
+ * Nothing else is coerced: a string field that happens to contain JSON stays a
9
+ * string, an undeclared field is left alone, and a malformed string is passed
10
+ * through unchanged so the validator reports it.
11
+ */
12
+ export function coerceJsonStringArguments(value, schema) {
13
+ const node = schemaNode(schema);
14
+ if (!node)
15
+ return value;
16
+ const expected = structuredKind(node);
17
+ let current = value;
18
+ if (typeof current === "string" && expected) {
19
+ const parsed = parseStructured(current, expected);
20
+ if (parsed !== undefined)
21
+ current = parsed;
22
+ }
23
+ if (Array.isArray(current)) {
24
+ const items = schemaNode(node.items);
25
+ if (!items || !acceptsKind(node, "array"))
26
+ return current;
27
+ let changed = current !== value;
28
+ const next = current.map((entry) => {
29
+ const coerced = coerceJsonStringArguments(entry, items);
30
+ if (coerced !== entry)
31
+ changed = true;
32
+ return coerced;
33
+ });
34
+ return changed ? next : current;
35
+ }
36
+ if (isPlainRecord(current)) {
37
+ const properties = schemaNode(node.properties);
38
+ if (!properties || !acceptsKind(node, "object"))
39
+ return current;
40
+ let next = current !== value ? { ...current } : null;
41
+ for (const [key, propertySchema] of Object.entries(properties)) {
42
+ if (!Object.prototype.hasOwnProperty.call(current, key))
43
+ continue;
44
+ const original = current[key];
45
+ const coerced = coerceJsonStringArguments(original, propertySchema);
46
+ if (coerced !== original) {
47
+ next ??= { ...current };
48
+ next[key] = coerced;
49
+ }
50
+ }
51
+ return next ?? current;
52
+ }
53
+ return current;
54
+ }
55
+ function structuredKind(node) {
56
+ const type = node.type;
57
+ if (type === "array" || type === "object")
58
+ return type;
59
+ if (Array.isArray(type)) {
60
+ // A schema that also admits a string must keep the string as sent.
61
+ if (type.includes("string"))
62
+ return null;
63
+ if (type.includes("array") && !type.includes("object"))
64
+ return "array";
65
+ if (type.includes("object") && !type.includes("array"))
66
+ return "object";
67
+ }
68
+ return null;
69
+ }
70
+ function acceptsKind(node, kind) {
71
+ const type = node.type;
72
+ if (type === undefined)
73
+ return true;
74
+ return type === kind || (Array.isArray(type) && type.includes(kind));
75
+ }
76
+ function parseStructured(text, expected) {
77
+ const trimmed = text.trim();
78
+ if (!trimmed.startsWith(expected === "array" ? "[" : "{"))
79
+ return undefined;
80
+ try {
81
+ const parsed = JSON.parse(trimmed);
82
+ if (expected === "array" ? Array.isArray(parsed) : isPlainRecord(parsed))
83
+ return parsed;
84
+ }
85
+ catch {
86
+ // Leave malformed JSON text in place; the validator reports it with a hint.
87
+ }
88
+ return undefined;
89
+ }
90
+ function schemaNode(value) {
91
+ return isPlainRecord(value) ? value : null;
92
+ }
93
+ function isPlainRecord(value) {
94
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
95
+ }
96
+ /**
97
+ * Explains why a value is not the expected array or object, for validator
98
+ * messages. A string gets an explicit instruction because that is the usual
99
+ * client mistake; the hint never echoes the value itself.
100
+ */
101
+ export function structuredTypeHint(value, expected) {
102
+ if (value === undefined || value === null) {
103
+ return " (it was omitted)";
104
+ }
105
+ if (typeof value === "string") {
106
+ return expected === "array"
107
+ ? " (received a string; pass a JSON array value, not a quoted string)"
108
+ : " (received a string; pass a JSON object value, not a quoted string)";
109
+ }
110
+ if (Array.isArray(value))
111
+ return " (received an array)";
112
+ return typeof value === "object" ? " (received an object)" : ` (received a ${typeof value})`;
113
+ }
114
+ /** True when a tool call arrived with no usable arguments at all. */
115
+ export function isEmptyToolInput(input) {
116
+ return input === undefined
117
+ || input === null
118
+ || (isPlainRecord(input) && Object.keys(input).length === 0);
119
+ }
120
+ export const emptyToolInputHint = "No arguments were received: the call arrived as an empty object. "
121
+ + "If the call was large it was probably cut off before it was sent; resend it with every required field.";
@@ -2,6 +2,13 @@ import { type CompletionArtifactReference, type CompletionPhase, type Completion
2
2
  import type { RunnerDispatchArtifact } from "./session.types.js";
3
3
  export declare function writeDecomposeGateCompletionArtifact(config: CompletionToolServerConfig, gate: DecomposeCompletionGate, toolName: string, input: unknown): Promise<CompletionArtifactReference>;
4
4
  export declare function writeDraftGateCompletionArtifact(config: CompletionToolServerConfig, gate: DraftCompletionGate, toolName: string, input: unknown): Promise<CompletionArtifactReference>;
5
+ /**
6
+ * Judges a Decompose gate call before anything is written and returns its status. The gate's
7
+ * input schema advertises exactly these rules (see the completion tool schema contract test).
8
+ */
9
+ export declare function validateDecomposeGatePayload(gate: DecomposeCompletionGate, payload: Record<string, unknown>): string;
10
+ /** Judges a Draft gate call before anything is written and returns its status. */
11
+ export declare function validateDraftGatePayload(gate: DraftCompletionGate, payload: Record<string, unknown>): string;
5
12
  export declare function writeCompletionArtifact(config: CompletionToolServerConfig, toolName: string, input: unknown): Promise<CompletionArtifactReference>;
6
13
  export declare function writeArchitectCompletionArtifact(config: CompletionToolServerConfig, payload: Record<string, unknown>, status: string, producedBy: string): Promise<CompletionArtifactReference>;
7
14
  export declare function writeQaGateCompletionArtifact(config: CompletionToolServerConfig, gate: QaCompletionGate, input: unknown): Promise<CompletionArtifactReference>;
@@ -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
+ }
@@ -96,6 +96,8 @@ export declare const debugCompletionPhaseOrder: readonly DebugCompletionPhase[];
96
96
  export declare const qaCompletionGateOrder: readonly QaCompletionGate[];
97
97
  export declare const draftCompletionGateOrder: readonly DraftCompletionGate[];
98
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"];
99
101
  export declare const decomposeGateFileNames: Record<DecomposeCompletionGate, string>;
100
102
  export declare const decomposeGateToolNames: Record<DecomposeCompletionGate, string>;
101
103
  export declare const draftGateFileNames: Record<DraftCompletionGate, string>;