@loucompanion/forge-bridge 0.1.4-dev.83728c550770 → 0.1.4-dev.866b33be3065

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 (104) hide show
  1. package/README.md +32 -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.service.d.ts +1 -1
  7. package/dist/bridge/bridge.service.js +4 -110
  8. package/dist/bridge/runner-host-capabilities.d.ts +3 -0
  9. package/dist/bridge/runner-host-capabilities.js +13 -0
  10. package/dist/cli/cli.service.d.ts +11 -0
  11. package/dist/cli/cli.service.js +80 -12
  12. package/dist/cli/local-config.d.ts +2 -0
  13. package/dist/cli/local-config.js +19 -3
  14. package/dist/runtime/attempt-database-broker.d.ts +1 -1
  15. package/dist/runtime/docker-engine-probe.d.ts +5 -0
  16. package/dist/runtime/docker-engine-probe.js +7 -0
  17. package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
  18. package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
  19. package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
  20. package/dist/runtime/ephemeral-test-postgres.js +303 -0
  21. package/dist/runtime/host-facts.d.ts +2 -1
  22. package/dist/runtime/host-load-admission.d.ts +9 -2
  23. package/dist/runtime/host-load-child-environment.d.ts +11 -6
  24. package/dist/runtime/host-load-child-environment.js +19 -10
  25. package/dist/runtime/host-load-governor-config.d.ts +10 -1
  26. package/dist/runtime/host-load-governor-config.js +7 -0
  27. package/dist/runtime/host-load-governor.d.ts +10 -0
  28. package/dist/runtime/host-load-governor.js +125 -34
  29. package/dist/runtime/host-load-sampler.d.ts +34 -4
  30. package/dist/runtime/host-load-sampler.js +73 -7
  31. package/dist/runtime/host-load-step-class.d.ts +3 -1
  32. package/dist/runtime/host-load-step-class.js +60 -5
  33. package/dist/runtime/host-load-test-slot.d.ts +43 -0
  34. package/dist/runtime/host-load-test-slot.js +81 -0
  35. package/dist/runtime/host-load-token-ledger.d.ts +26 -0
  36. package/dist/runtime/host-load-token-ledger.js +93 -61
  37. package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
  38. package/dist/runtime/host-load-windows-cpu.js +85 -0
  39. package/dist/runtime/host-runtime-lease.d.ts +2 -2
  40. package/dist/runtime/host-runtime-lease.js +9 -8
  41. package/dist/runtime/host-runtime-promotion.d.ts +23 -0
  42. package/dist/runtime/host-runtime-promotion.js +36 -0
  43. package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
  44. package/dist/runtime/native-test-postgres-fallback.js +60 -8
  45. package/dist/sandbox/host-capacity-broker.d.ts +7 -1
  46. package/dist/sandbox/host-capacity-broker.js +23 -4
  47. package/dist/session/architect-waits.d.ts +2 -0
  48. package/dist/session/architect-waits.js +138 -0
  49. package/dist/session/managed-attempt-tools.d.ts +0 -7
  50. package/dist/session/managed-attempt-tools.js +51 -62
  51. package/dist/session/managed-command-host-load.d.ts +2 -0
  52. package/dist/session/managed-command-host-load.js +2 -1
  53. package/dist/session/phase-completion.artifacts.js +2 -1
  54. package/dist/session/phase-completion.runtime.js +1 -1
  55. package/dist/session/phase-completion.schemas.js +25 -23
  56. package/dist/session/phase-completion.validation.js +3 -1
  57. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  58. package/dist/session/pre-publication-native-postgres.js +111 -0
  59. package/dist/session/pre-publication-pass.d.ts +61 -0
  60. package/dist/session/pre-publication-pass.js +148 -0
  61. package/dist/session/pre-publication-step-execution.d.ts +2 -1
  62. package/dist/session/pre-publication-step-execution.js +6 -5
  63. package/dist/session/pre-publication-validation.d.ts +30 -14
  64. package/dist/session/pre-publication-validation.js +207 -134
  65. package/dist/session/provider-cli/claude-background-work.d.ts +66 -0
  66. package/dist/session/provider-cli/claude-background-work.js +180 -0
  67. package/dist/session/provider-cli/pre-publication-repair.d.ts +40 -0
  68. package/dist/session/provider-cli/pre-publication-repair.js +243 -0
  69. package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
  70. package/dist/session/provider-cli/provider-cli.child-environment.js +73 -0
  71. package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
  72. package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
  73. package/dist/session/provider-cli/provider-cli.process.d.ts +15 -36
  74. package/dist/session/provider-cli/provider-cli.process.js +39 -430
  75. package/dist/session/provider-cli/provider-cli.prompts.d.ts +2 -0
  76. package/dist/session/provider-cli/provider-cli.prompts.js +45 -8
  77. package/dist/session/provider-cli/provider-cli.runtime.js +7 -0
  78. package/dist/session/provider-cli/provider-cli.service.d.ts +4 -7
  79. package/dist/session/provider-cli/provider-cli.service.js +66 -243
  80. package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
  81. package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
  82. package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
  83. package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
  84. package/dist/session/provider-cli/provider-in-flight-work.d.ts +4 -0
  85. package/dist/session/provider-cli/provider-in-flight-work.js +45 -0
  86. package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
  87. package/dist/session/provider-cli/provider-output-pipes.js +67 -0
  88. package/dist/session/provider-cli/provider-output-state.d.ts +2 -0
  89. package/dist/session/provider-cli/provider-output-state.js +6 -0
  90. package/dist/session/qa-sidecar-validation.d.ts +6 -0
  91. package/dist/session/qa-sidecar-validation.js +28 -0
  92. package/dist/session/sandbox-host-capacity-gate.js +12 -3
  93. package/dist/session/session-redaction.js +31 -181
  94. package/dist/session/session.types.js +3 -3
  95. package/dist/session/sidecar-json-shape.d.ts +31 -0
  96. package/dist/session/sidecar-json-shape.js +217 -0
  97. package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
  98. package/dist/shared/process/windows-app-execution-alias.js +45 -0
  99. package/dist/shared/process/windows-launch.d.ts +18 -0
  100. package/dist/shared/process/windows-launch.js +68 -0
  101. package/dist/shared/provider-capabilities.js +5 -6
  102. package/dist/version.d.ts +1 -1
  103. package/dist/version.js +1 -1
  104. package/package.json +2 -2
@@ -3,10 +3,9 @@ import fs from "node:fs/promises";
3
3
  import os from "node:os";
4
4
  import path from "node:path";
5
5
  import { resetGeneratedOutputs } from "../runtime/generated-output-reset.js";
6
- import { DockerEngineProbe } from "../runtime/docker-engine-probe.js";
7
6
  import { attemptDatabaseCapabilityEnvironment, attemptDatabaseCapabilitySecrets, } from "../runtime/attempt-database-broker.js";
8
7
  import { assertHostDatabaseCapabilityBoundary } from "../runtime/host-database-capability-boundary.js";
9
- import { nativeTestPostgresFallbackConfigEnvironment, nativeTestPostgresFallbackDatabaseMode, nativeTestPostgresFallbackEnvironment, readNativeTestPostgresFallback, } from "../runtime/native-test-postgres-fallback.js";
8
+ import { managedVerificationDatabase, noManagedVerificationDatabase, releaseManagedVerificationDatabase, setUpWithManagedVerificationDatabase } from "../runtime/ephemeral-test-postgres-grant.js";
10
9
  import { redactText } from "../shared/redaction/redaction.js";
11
10
  import { emptyToolInputHint, isEmptyToolInput } from "./mcp-argument-coercion.js";
12
11
  import { ManagedBuildCoordinator } from "./managed-build-coordinator.js";
@@ -14,7 +13,7 @@ import { attachManagedCommandProcess, ManagedCommandHostCapacity, } from "./mana
14
13
  import { HostCapacityLedgerUnavailableError } from "../runtime/host-load-ledger-lock.js";
15
14
  import { isProcessTreeTerminationUnproven } from "../shared/process/process.js";
16
15
  import { HostCapacityTokenFencedError } from "../runtime/host-load-token-ledger.js";
17
- import { hostLoadGovernorEnvironment, hostLoadStateRootEnvironment } from "../runtime/host-load-child-environment.js";
16
+ import { withoutHostLoadGovernorVariables } from "../runtime/host-load-child-environment.js";
18
17
  import { managedBuildConfiguration, publishManagedBuildReceipt, verifyManagedBuildReceipt, } from "./managed-build-receipt.js";
19
18
  import { managedLongTierTimeoutMs, managedMaximumCommandTimeoutMs, managedVerificationTierTimeoutMs, } from "./managed-verification-timeouts.js";
20
19
  import { resolveWindowsCommandFromPath, StreamingProviderProcessRunner } from "./provider-cli/provider-cli.process.js";
@@ -447,7 +446,7 @@ export function buildManagedVerificationCommand(profile, outputDirectory, shardC
447
446
  export function preferredPowerShellExecutable(platform = process.platform, pathValue = process.env.PATH ?? "") {
448
447
  if (platform !== "win32")
449
448
  return "pwsh";
450
- return resolveWindowsCommandFromPath("pwsh.exe", pathValue) ?? "powershell.exe";
449
+ return resolveWindowsCommandFromPath("pwsh.exe", pathValue, undefined, { skipAppExecutionAliases: true }) ?? "powershell.exe";
451
450
  }
452
451
  export function validatePlaywrightProjectName(project, availableProjects) {
453
452
  if (!availableProjects.includes(project)) {
@@ -594,41 +593,48 @@ async function executeManagedCommand(invocation) {
594
593
  return managedCommandPublicResult(receipt);
595
594
  }
596
595
  }
596
+ /** A command's environment and redaction list; a setup that throws releases the database it started. */
597
597
  async function managedCommandProcessEnvironment(invocation) {
598
598
  assertHostDatabaseCapabilityBoundary();
599
- const databaseEnvironment = invocation.verificationProfile
600
- ? await managedVerificationDatabaseEnvironment()
601
- : {};
602
- const exactSecrets = [
603
- ...Object.values(databaseEnvironment).filter(value => value !== nativeTestPostgresFallbackDatabaseMode),
604
- // The attempt's brokered database login reaches managed commands; their output never shows it.
605
- ...attemptDatabaseCapabilitySecrets(process.env[attemptDatabaseCapabilityEnvironment]),
606
- ];
607
- const environment = inheritedEnvironment({
608
- FORGE_RUNTIME_MODE: "host",
609
- FORGE_RESOURCE_LEASE_ID: requiredAttemptEnvironment("FORGE_RESOURCE_LEASE_ID"),
610
- FORGE_DISPATCH_ATTEMPT_ID: requiredAttemptEnvironment("FORGE_DISPATCH_ATTEMPT_ID"),
611
- // This nested command owns a distinct supervisor identity. A command-local
612
- // fence avoids exposing the parent attempt's fencing capability to Codex's
613
- // MCP subprocess configuration while preserving exact-tree cleanup proof.
614
- FORGE_FENCING_TOKEN: randomUUID(),
615
- FORGE_LOG_DIR: invocation.logDirectory,
616
- FORGE_TEST_OUTPUT_DIR: requiredAttemptEnvironment("FORGE_TEST_OUTPUT_DIR"),
617
- FORGE_PROCESS_SUPERVISOR_ID: `managed-${invocation.commandId.replaceAll("-", "")}`,
618
- FORGE_PROCESS_SUPERVISOR_METADATA_PATH: invocation.metadataPath,
619
- ...(invocation.verificationProfile
620
- ? {
621
- FORGE_MANAGED_VERIFICATION_PROFILE: invocation.verificationProfile,
622
- // Managed verification executes mutable worktree scripts, SDK targets,
623
- // and test assemblies. It uses an attempt-owned container, or the
624
- // dedicated native test cluster while Docker is unavailable; it never
625
- // receives a capability for a server that holds real data.
626
- FORGE_MANAGED_VERIFICATION_DATABASE_MODE: "container_only",
627
- ...databaseEnvironment,
628
- }
629
- : {}),
599
+ const database = invocation.verificationProfile ? await managedVerificationDatabase() : noManagedVerificationDatabase;
600
+ return await setUpWithManagedVerificationDatabase(database, () => {
601
+ const exactSecrets = [
602
+ ...database.secrets,
603
+ // The attempt's brokered database login reaches managed commands; their output never shows it.
604
+ ...attemptDatabaseCapabilitySecrets(process.env[attemptDatabaseCapabilityEnvironment]),
605
+ ];
606
+ const environment = inheritedEnvironment({
607
+ FORGE_RUNTIME_MODE: "host",
608
+ FORGE_RESOURCE_LEASE_ID: requiredAttemptEnvironment("FORGE_RESOURCE_LEASE_ID"),
609
+ FORGE_DISPATCH_ATTEMPT_ID: requiredAttemptEnvironment("FORGE_DISPATCH_ATTEMPT_ID"),
610
+ // This nested command owns a distinct supervisor identity. A command-local
611
+ // fence avoids exposing the parent attempt's fencing capability to Codex's
612
+ // MCP subprocess configuration while preserving exact-tree cleanup proof.
613
+ FORGE_FENCING_TOKEN: randomUUID(),
614
+ FORGE_LOG_DIR: invocation.logDirectory,
615
+ FORGE_TEST_OUTPUT_DIR: requiredAttemptEnvironment("FORGE_TEST_OUTPUT_DIR"),
616
+ FORGE_PROCESS_SUPERVISOR_ID: `managed-${invocation.commandId.replaceAll("-", "")}`,
617
+ FORGE_PROCESS_SUPERVISOR_METADATA_PATH: invocation.metadataPath,
618
+ ...(invocation.verificationProfile
619
+ ? {
620
+ FORGE_MANAGED_VERIFICATION_PROFILE: invocation.verificationProfile,
621
+ // Managed verification executes mutable worktree scripts, SDK targets,
622
+ // and test assemblies. It uses an attempt-owned container, or the
623
+ // dedicated native test cluster while Docker is unavailable; it never
624
+ // receives a capability for a server that holds real data.
625
+ FORGE_MANAGED_VERIFICATION_DATABASE_MODE: "container_only",
626
+ ...database.environment,
627
+ }
628
+ : {}),
629
+ });
630
+ return { environment, exactSecrets, release: database.release };
630
631
  });
631
- return { environment, exactSecrets };
632
+ }
633
+ function clearManagedCommandTimers(...timers) {
634
+ // clearTimeout and clearInterval share one timer table.
635
+ for (const timer of timers)
636
+ if (timer)
637
+ clearTimeout(timer);
632
638
  }
633
639
  async function executeManagedCommandProcess(invocation) {
634
640
  let prepared;
@@ -830,11 +836,9 @@ async function executeManagedCommandProcess(invocation) {
830
836
  return managedCommandPublicResult(receipt);
831
837
  }
832
838
  finally {
833
- clearTimeout(launchTimer);
834
- if (timer)
835
- clearTimeout(timer);
836
- if (progressHeartbeat)
837
- clearInterval(progressHeartbeat);
839
+ clearManagedCommandTimers(launchTimer, timer, progressHeartbeat);
840
+ // An ephemeral verification cluster lives exactly as long as its command; one that would not stop is reaped later and named in the receipt.
841
+ await releaseManagedVerificationDatabase(prepared, async (message) => await annotateManagedCommandReceipt(invocation.receiptPath, { ephemeral_cluster_release_error: redactText(message, exactSecrets) }));
838
842
  }
839
843
  }
840
844
  async function readManagedCommand(input) {
@@ -907,7 +911,7 @@ async function waitManagedCommand(input) {
907
911
  const lastOutputAt = Date.parse(String(receipt.structuredContent.last_output_at));
908
912
  const hostLoadWaitMs = receipt.structuredContent.host_load_wait_ms;
909
913
  const progress = receipt.structuredContent.status === "waiting_for_host_capacity" && typeof hostLoadWaitMs === "number"
910
- ? ` 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.`
914
+ ? ` 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.`
911
915
  : receipt.structuredContent.status === "running" && typeof elapsedMs === "number"
912
916
  ? ` It has run for ${Math.round(elapsedMs / 1000)}s`
913
917
  + (Number.isFinite(lastOutputAt) ? `, last output ${Math.max(0, Math.round((Date.now() - lastOutputAt) / 1000))}s ago` : ", with no output yet")
@@ -1033,7 +1037,7 @@ function managedCommandHostLoadReceipt(hostLoad) {
1033
1037
  return {
1034
1038
  host_load_step_class: hostLoad.stepClass,
1035
1039
  host_load_wait_ms: waiting ? Math.max(0, Date.now() - hostLoad.waitStartedAt) : hostLoad.waitMs,
1036
- ...(waiting ? { host_load_wait_started_at: new Date(hostLoad.waitStartedAt).toISOString() } : {}),
1040
+ ...(waiting ? { host_load_wait_started_at: new Date(hostLoad.waitStartedAt).toISOString(), host_load_wait_detail: hostLoad.waitDetail ?? null } : {}),
1037
1041
  };
1038
1042
  }
1039
1043
  async function annotateManagedCommandReceipt(receiptPath, fields) {
@@ -1115,30 +1119,15 @@ async function containedWorkingDirectory(worktreePath, input) {
1115
1119
  }
1116
1120
  function inheritedEnvironment(overrides) {
1117
1121
  const env = {};
1118
- for (const [key, value] of Object.entries(process.env)) {
1119
- // A nested Forge process must not join the host ledger: it would queue behind the
1120
- // token this command already holds.
1121
- if (key === hostLoadGovernorEnvironment || key === hostLoadStateRootEnvironment)
1122
- continue;
1122
+ // A nested Forge process must not join the host ledger: it would queue behind the
1123
+ // token this command already holds. Every FORGE_HOST_LOAD_* variable is dropped,
1124
+ // the test slot count too (decision 0018).
1125
+ for (const [key, value] of Object.entries(withoutHostLoadGovernorVariables(process.env))) {
1123
1126
  if (typeof value === "string" && !looksSensitiveEnvironmentName(key))
1124
1127
  env[key] = value;
1125
1128
  }
1126
1129
  return { ...env, ...overrides };
1127
1130
  }
1128
- /**
1129
- * Runner-authored verification normally uses its attempt-owned Testcontainers
1130
- * database. Only when the Docker engine is unavailable does it switch to the
1131
- * operator-provisioned native test cluster, which holds no real data.
1132
- */
1133
- export async function managedVerificationDatabaseEnvironment(dockerAvailable = async () => (await new DockerEngineProbe().refresh(true)).available, readFallback = () => {
1134
- const configPath = process.env[nativeTestPostgresFallbackConfigEnvironment]?.trim();
1135
- return configPath ? readNativeTestPostgresFallback(configPath) : null;
1136
- }) {
1137
- const fallback = readFallback();
1138
- if (!fallback || await dockerAvailable())
1139
- return {};
1140
- return nativeTestPostgresFallbackEnvironment(fallback);
1141
- }
1142
1131
  export function isBuildProducingManagedCommand(command, args) {
1143
1132
  const executable = path.basename(command).toLowerCase();
1144
1133
  if (executable === "dotnet" || executable === "dotnet.exe") {
@@ -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,
@@ -2,7 +2,7 @@ import crypto from "node:crypto";
2
2
  import fs from "node:fs/promises";
3
3
  import path from "node:path";
4
4
  import { redactSecrets } from "../shared/redaction/redaction.js";
5
- import { ensureNoSymbolicLinkPathSegments, isPathUnderRoot, sha256File } from "./qa-sidecar-validation.js";
5
+ import { assertQaSidecarJsonShape, ensureNoSymbolicLinkPathSegments, isPathUnderRoot, sha256File } from "./qa-sidecar-validation.js";
6
6
  import { assertClaimedChangedFilesMatchPublishableDiff } from "./publishable-worktree-changes.js";
7
7
  import { coerceJsonStringArguments } from "./mcp-argument-coercion.js";
8
8
  import { toolInputSchema } from "./phase-completion.schemas.js";
@@ -690,6 +690,7 @@ async function validateQaSidecarReferences(worktreePath, workItemId, sidecars, o
690
690
  if (actualHash !== normalizeSha256ContentHash(contentHash)) {
691
691
  throw new Error(`sidecars[${index}].content_hash does not match the referenced file.`);
692
692
  }
693
+ await assertQaSidecarJsonShape(fullPath, sidecarPath, `sidecars[${index}]`);
693
694
  const canonicalPath = path.relative(worktreePath, fullPath).split(path.sep).join("/");
694
695
  const duplicateKey = canonicalPath.toLowerCase();
695
696
  const existing = validatedByPath.get(duplicateKey);
@@ -491,7 +491,7 @@ export function completionToolRuntimeEnvironment(runtimeEnvironment, nativeTestP
491
491
  env[name] = value.trim();
492
492
  }
493
493
  // Managed verification reads the operator's native test cluster only through
494
- // this explicit path, and only while Docker is unavailable.
494
+ // this explicit path; the file's `use` decides whether Docker comes first.
495
495
  if (runtimeEnvironment && nativeTestPostgresFallbackPath) {
496
496
  env[nativeTestPostgresFallbackConfigEnvironment] = nativeTestPostgresFallbackPath;
497
497
  }
@@ -1,5 +1,6 @@
1
1
  import { decomposeGateFileNames, decomposeStatuses, draftStatuses, isDebugCompletionPhase, phaseFiles, qaBlockerReasons, qaGateFileNames } from "./phase-completion.js";
2
2
  import { browserCheckSchema, qaSidecarsSchema, qaEvidenceWrapperSchema, qaGateEvidenceWrapperSchema, findingEvidenceSchema, objectToolSchema, evidenceObjectSchema, qaScopeSchema, commandEvidenceSchema, resolvedFindingSchema, acceptanceCriteriaSchema, reviewSectionSchema, reviewSectionProperties } from "./phase-completion.schema-parts.js";
3
+ import { architectNonPassProperties } from "./architect-waits.js";
3
4
  export function toolDescription(phase, qaGate = null, decomposeGate = null, draftGate = null) {
4
5
  if (qaGate) {
5
6
  return qaGate === "qa_verdict"
@@ -499,17 +500,8 @@ export function toolInputSchema(phase, qaGate = null, decomposeGate = null, draf
499
500
  report_markdown: { type: "string", description: "Human-readable Architect report. Use report as an alias only when the client cannot send report_markdown." },
500
501
  report: { type: "string", description: "Alias for report_markdown." },
501
502
  blockers: baseProperties.blockers,
502
- revision_questions: {
503
- type: "array",
504
- description: "Required for needs_revision when blockers are not used.",
505
- items: { type: "string" }
506
- },
507
- revision_reasons: {
508
- type: "array",
509
- description: "Concrete reasons that prevent pass status.",
510
- items: { type: "string" }
511
- }
512
- }, ["status", "summary"], "For status pass, include implementation_plan and qa_plan at the top level of the MCP tool arguments, as JSON objects rather than quoted strings. implementation_plan.phases must be a top-level array inside implementation_plan, not nested under another object. For needs_revision or blocked, implementation_plan and qa_plan may be omitted; include blockers, revision_questions, or revision_reasons instead.");
503
+ ...architectNonPassProperties()
504
+ }, ["status", "summary"], "For status pass, include implementation_plan and qa_plan at the top level of the MCP tool arguments, as JSON objects rather than quoted strings. implementation_plan.phases must be a top-level array inside implementation_plan, not nested under another object. For needs_revision or blocked, implementation_plan and qa_plan may be omitted; include blockers, revision_questions, or revision_reasons instead. When blocked because another Story or pull request must merge first, also list it in waits_on; when the owner must choose, also set owner_decision.");
513
505
  }
514
506
  return objectToolSchema({
515
507
  ...baseProperties,
@@ -536,6 +528,27 @@ export function toolInputSchema(phase, qaGate = null, decomposeGate = null, draf
536
528
  ready_for_dev_test: { type: "boolean", default: true, description: "Required for pass and must be true." }
537
529
  }, ["status", "summary"], "For status pass, commands must include at least one passing deterministic command, acceptance criteria entries must use status: satisfied plus evidence, and ready_for_dev_test must be true.");
538
530
  }
531
+ // Feature-to-Story candidate fields: schedule order, handoff to dependents, and whether the Story
532
+ // needs a design reference before Forge builds it.
533
+ const storyCandidateScheduleProperties = {
534
+ scheduleIndex: { type: "number", description: "Feature-to-Story total schedule order for dependency-safe execution." },
535
+ schedule_index: { type: "number", description: "Snake_case alias for scheduleIndex." },
536
+ waveIndex: { type: "number", description: "Feature-to-Story parallel wave number." },
537
+ wave_index: { type: "number", description: "Snake_case alias for waveIndex." },
538
+ featureScheduleIndex: { type: "number", description: "Optional ordering within the Feature." },
539
+ feature_schedule_index: { type: "number", description: "Snake_case alias for featureScheduleIndex." },
540
+ expectedOutput: { type: "string", description: "Durable output this Story should produce for dependents." },
541
+ expected_output: { type: "string", description: "Snake_case alias for expectedOutput." },
542
+ handoffSummary: { type: "string", description: "How dependent Stories should consume this Story output." },
543
+ handoff_summary: { type: "string", description: "Snake_case alias for handoffSummary." },
544
+ dependencyReason: { type: "string", description: "Why this Story depends on its dependsOn predecessors." },
545
+ dependency_reason: { type: "string", description: "Snake_case alias for dependencyReason." },
546
+ requiresDesign: {
547
+ type: "boolean",
548
+ description: "Feature-to-Story only. True when the Story adds or changes user-visible UI; Forge holds it until a design reference is attached. False for non-visual Stories."
549
+ },
550
+ requires_design: { type: "boolean", description: "Snake_case alias for requiresDesign." }
551
+ };
539
552
  function decomposeGateToolInputSchema(gate, phaseProperties) {
540
553
  // Advertise every status the Decompose writer accepts, so the schema and the runtime agree.
541
554
  const baseProperties = {
@@ -572,18 +585,7 @@ function decomposeGateToolInputSchema(gate, phaseProperties) {
572
585
  acceptanceCriteria: { type: "string" },
573
586
  planningPacket: { type: "string" },
574
587
  sortOrder: { type: "number" },
575
- scheduleIndex: { type: "number", description: "Feature-to-Story total schedule order for dependency-safe execution." },
576
- schedule_index: { type: "number", description: "Snake_case alias for scheduleIndex." },
577
- waveIndex: { type: "number", description: "Feature-to-Story parallel wave number." },
578
- wave_index: { type: "number", description: "Snake_case alias for waveIndex." },
579
- featureScheduleIndex: { type: "number", description: "Optional ordering within the Feature." },
580
- feature_schedule_index: { type: "number", description: "Snake_case alias for featureScheduleIndex." },
581
- expectedOutput: { type: "string", description: "Durable output this Story should produce for dependents." },
582
- expected_output: { type: "string", description: "Snake_case alias for expectedOutput." },
583
- handoffSummary: { type: "string", description: "How dependent Stories should consume this Story output." },
584
- handoff_summary: { type: "string", description: "Snake_case alias for handoffSummary." },
585
- dependencyReason: { type: "string", description: "Why this Story depends on its dependsOn predecessors." },
586
- dependency_reason: { type: "string", description: "Snake_case alias for dependencyReason." },
588
+ ...storyCandidateScheduleProperties,
587
589
  points: { type: "number" },
588
590
  dependsOn: { type: "array", items: { type: "string" } },
589
591
  estimatedQaScope: qaScopeSchema("Work Order-to-Feature planning QA estimate. This is not dispatch-authoritative QA scope."),
@@ -1,5 +1,6 @@
1
1
  import { qaBlockerReasons, qaCandidateBugActions, qaFindingScopes, qaFindingSeverities, qaGateToolNames, qaScopeAuthorities, qaScopeCapabilities, qaScopeConfidence, qaScopeEvidence, qaScopeFields, qaScopeSources, qaScopeSurfaces } from "./phase-completion.js";
2
2
  import { structuredTypeHint } from "./mcp-argument-coercion.js";
3
+ import { validateArchitectWaits } from "./architect-waits.js";
3
4
  import { validateQaGatePassingCommands } from "./phase-completion.command-validation.js";
4
5
  export { validateQaGatePassingCommands } from "./phase-completion.command-validation.js";
5
6
  export const qaEvidenceGates = new Set(["qa_regression", "qa_api", "qa_manual_web", "qa_bug_repro"]);
@@ -353,6 +354,7 @@ export function validateQaGatePayloadShape(gate, payload, status) {
353
354
  }
354
355
  }
355
356
  export function validateArchitectPayloadShape(payload, status) {
357
+ validateArchitectWaits(payload, status);
356
358
  if (status !== "pass") {
357
359
  requireArchitectNonPassEvidence(payload);
358
360
  return;
@@ -706,7 +708,7 @@ export function hasArchitectDependencyCycle(edges) {
706
708
  return false;
707
709
  }
708
710
  export function requireArchitectNonPassEvidence(payload) {
709
- const evidenceKeys = ["blockers", "revision_questions", "revision_reasons", "known_gaps", "findings", "remaining_risks", "failures"];
711
+ const evidenceKeys = ["blockers", "revision_questions", "revision_reasons", "waits_on", "owner_decision", "known_gaps", "findings", "remaining_risks", "failures"];
710
712
  const hasEvidence = evidenceKeys.some((key) => {
711
713
  const value = payload[key];
712
714
  if (typeof value === "string") {
@@ -0,0 +1,30 @@
1
+ import type { DockerEngineProbe } from "../runtime/docker-engine-probe.js";
2
+ import { startEphemeralTestPostgresGrant } from "../runtime/ephemeral-test-postgres-grant.js";
3
+ import { type NativeTestPostgresFallback, type NativeTestPostgresGrant } from "../runtime/native-test-postgres-fallback.js";
4
+ import type { RunnerDispatchEvent } from "./session.types.js";
5
+ /**
6
+ * A provisioned native test cluster whose file prefers it serves this check's shared
7
+ * test server without waiting on Docker (owner policy 2026-11-16: native PostgreSQL
8
+ * first). Docker is still probed, never recovered, so the fixtures know whether
9
+ * pinned-engine tests can start their own containers. An unreadable file leaves the
10
+ * check on Docker.
11
+ */
12
+ export declare function preferredNativeTestPostgres(checkId: string, requiredPrerequisite: string | undefined, readCluster: () => NativeTestPostgresFallback | null, dockerEngineProbe: DockerEngineProbe | undefined, emit?: (event: RunnerDispatchEvent) => Promise<void>, startEphemeral?: typeof startEphemeralTestPostgresGrant): Promise<NativeTestPostgresGrant | undefined>;
13
+ /** Whether this check already has its isolated PostgreSQL without Docker. */
14
+ export declare function isolatedPostgresProvided(checkId: string, environment?: Readonly<Record<string, string>>, postgresAdminConnection?: NativeTestPostgresGrant): boolean;
15
+ /**
16
+ * The grant, when it makes its check Docker-free. A native_preferred grant still lets
17
+ * pinned-engine tests start Docker containers, so a Docker loss during its check stays
18
+ * retryable infrastructure; only a native_fallback grant (Docker was already down) does not.
19
+ */
20
+ export declare function dockerFreeGrant(grant: NativeTestPostgresGrant | undefined): NativeTestPostgresGrant | undefined;
21
+ /**
22
+ * Releases a check's ephemeral cluster once the check has ended. A cluster that would not stop
23
+ * is left disowned for the next start's reap and does not change the check's own result.
24
+ */
25
+ export declare function releaseCheckPostgres(checkId: string, grant: NativeTestPostgresGrant | undefined, emit?: (event: RunnerDispatchEvent) => Promise<void>): Promise<void>;
26
+ /** The native cluster grant for a check while Docker stays down, or null when it cannot use one. */
27
+ export declare function dockerUnavailableNativeTestPostgres(checkId: string, requiredPrerequisite: string | undefined, readCluster: () => NativeTestPostgresFallback | null): NativeTestPostgresGrant | null;
28
+ export type { NativeTestPostgresFallback, NativeTestPostgresGrant };
29
+ /** Starts a check's ephemeral cluster; injectable so tests need no PostgreSQL install. */
30
+ export type StartEphemeralTestPostgresGrant = typeof startEphemeralTestPostgresGrant;
@@ -0,0 +1,111 @@
1
+ import path from "node:path";
2
+ import { attemptDatabaseCapabilityEnvironment } from "../runtime/attempt-database-broker.js";
3
+ import { startEphemeralTestPostgresGrant } from "../runtime/ephemeral-test-postgres-grant.js";
4
+ import { nativeTestPostgresFallbackDatabaseMode, nativeTestPostgresGrant, } from "../runtime/native-test-postgres-fallback.js";
5
+ import { validationEvent } from "./pre-publication-pass.js";
6
+ import { supportsNativeTestPostgresFallback } from "./pre-publication-step-execution.js";
7
+ // Which PostgreSQL a pre-publication check's isolated_postgres prerequisite is met by,
8
+ // before the validator falls back to waiting for Docker.
9
+ /**
10
+ * A provisioned native test cluster whose file prefers it serves this check's shared
11
+ * test server without waiting on Docker (owner policy 2026-11-16: native PostgreSQL
12
+ * first). Docker is still probed, never recovered, so the fixtures know whether
13
+ * pinned-engine tests can start their own containers. An unreadable file leaves the
14
+ * check on Docker.
15
+ */
16
+ export async function preferredNativeTestPostgres(checkId, requiredPrerequisite, readCluster, dockerEngineProbe, emit, startEphemeral = startEphemeralTestPostgresGrant) {
17
+ if (requiredPrerequisite !== "isolated_postgres" || !supportsNativeTestPostgresFallback(checkId))
18
+ return undefined;
19
+ let configured;
20
+ try {
21
+ configured = readCluster();
22
+ }
23
+ catch (error) {
24
+ await emit?.(validationEvent("prepublication_prerequisite_native_invalid", checkId, `The native PostgreSQL test cluster configuration was refused, so '${checkId}' uses Docker: ${error instanceof Error ? error.message : String(error)}`));
25
+ return undefined;
26
+ }
27
+ if (configured?.use === "ephemeral") {
28
+ return await ephemeralNativeTestPostgres(checkId, configured, dockerEngineProbe, emit, startEphemeral);
29
+ }
30
+ if (configured?.use !== "preferred")
31
+ return undefined;
32
+ const dockerAvailable = dockerEngineProbe ? (await dockerEngineProbe.probeWithoutRecovery()).available : false;
33
+ const grant = nativeTestPostgresGrant(configured, dockerAvailable);
34
+ if (!grant)
35
+ return undefined;
36
+ await emit?.(validationEvent("prepublication_prerequisite_native_preferred", checkId, `Pre-publication check '${checkId}' is using the dedicated native PostgreSQL test cluster at ${grant.endpoint} with per-run owned databases${dockerAvailable
37
+ ? "; tests that need a pinned engine container still start one in Docker."
38
+ : ". Docker is unavailable, so tests that need a pinned engine container are skipped."}`));
39
+ return grant;
40
+ }
41
+ /**
42
+ * A throwaway cluster of the check's own, whose superuser it holds (owner policy 2026-11-17).
43
+ * If it cannot start, the check falls back to Docker, and to the provisioned cluster only while
44
+ * Docker is down.
45
+ */
46
+ async function ephemeralNativeTestPostgres(checkId, configured, dockerEngineProbe, emit, startEphemeral) {
47
+ const dockerAvailable = dockerEngineProbe ? (await dockerEngineProbe.probeWithoutRecovery()).available : false;
48
+ let grant;
49
+ try {
50
+ grant = await startEphemeral(configured, dockerAvailable);
51
+ }
52
+ catch (error) {
53
+ await emit?.(validationEvent("prepublication_prerequisite_ephemeral_unavailable", checkId, `An ephemeral PostgreSQL test cluster could not start for '${checkId}', so it uses Docker: ${error instanceof Error ? error.message : String(error)}`));
54
+ return undefined;
55
+ }
56
+ try {
57
+ await emit?.(validationEvent("prepublication_prerequisite_native_ephemeral", checkId, `Pre-publication check '${checkId}' is using its own ephemeral PostgreSQL test cluster at ${grant.endpoint}, deleted when the check ends${dockerAvailable
58
+ ? "; tests that need a pinned engine container still start one in Docker."
59
+ : ". Docker is unavailable, so tests that need a pinned engine container are skipped."}`));
60
+ }
61
+ catch (error) {
62
+ // The caller releases only a grant it receives, so a failed emit releases it here.
63
+ await grant.release?.().catch(() => undefined);
64
+ throw error;
65
+ }
66
+ return grant;
67
+ }
68
+ function environmentValue(environment, name) {
69
+ return Object.prototype.hasOwnProperty.call(environment ?? {}, name)
70
+ ? environment?.[name]?.trim() ?? ""
71
+ : process.env[name]?.trim() ?? "";
72
+ }
73
+ /** Whether this check already has its isolated PostgreSQL without Docker. */
74
+ export function isolatedPostgresProvided(checkId, environment, postgresAdminConnection) {
75
+ if (checkId === "playwright-e2e") {
76
+ const attemptId = environmentValue(environment, "FORGE_DISPATCH_ATTEMPT_ID");
77
+ return (environmentValue(environment, "FORGE_E2E_OWNERSHIP_MODE") === "attempt"
78
+ || /^[0-9a-f-]{36}$/iu.test(attemptId))
79
+ && /^forge_attempt_[0-9a-f]{32}$/u.test(environmentValue(environment, "FORGE_ATTEMPT_DATABASE_SCHEMA"))
80
+ && path.isAbsolute(environmentValue(environment, "FORGE_ATTEMPT_DATABASE_READINESS_PATH"))
81
+ // The attempt owns a database only once the Bridge's broker has issued it one.
82
+ && environmentValue(environment, attemptDatabaseCapabilityEnvironment).length > 0;
83
+ }
84
+ return Boolean(postgresAdminConnection);
85
+ }
86
+ /**
87
+ * The grant, when it makes its check Docker-free. A native_preferred grant still lets
88
+ * pinned-engine tests start Docker containers, so a Docker loss during its check stays
89
+ * retryable infrastructure; only a native_fallback grant (Docker was already down) does not.
90
+ */
91
+ export function dockerFreeGrant(grant) {
92
+ return grant?.mode === nativeTestPostgresFallbackDatabaseMode ? grant : undefined;
93
+ }
94
+ /**
95
+ * Releases a check's ephemeral cluster once the check has ended. A cluster that would not stop
96
+ * is left disowned for the next start's reap and does not change the check's own result.
97
+ */
98
+ export async function releaseCheckPostgres(checkId, grant, emit) {
99
+ try {
100
+ await grant?.release?.();
101
+ }
102
+ catch (error) {
103
+ await emit?.(validationEvent("prepublication_ephemeral_release_failed", checkId, `The ephemeral PostgreSQL test cluster for '${checkId}' could not be released and will be reaped later: ${error instanceof Error ? error.message : String(error)}`)).catch(() => undefined);
104
+ }
105
+ }
106
+ /** The native cluster grant for a check while Docker stays down, or null when it cannot use one. */
107
+ export function dockerUnavailableNativeTestPostgres(checkId, requiredPrerequisite, readCluster) {
108
+ return requiredPrerequisite === "isolated_postgres" && supportsNativeTestPostgresFallback(checkId)
109
+ ? nativeTestPostgresGrant(readCluster(), false)
110
+ : null;
111
+ }
@@ -0,0 +1,61 @@
1
+ import type { ValidationStep } from "./pre-publication-step-execution.js";
2
+ import { ForgeFailureError, type RunnerDispatchEvent } from "./session.types.js";
3
+ /** The check id a failed restart of the attempt's runtime stack before the pass is reported under. */
4
+ export declare const runtimeRestartCheckId = "host-runtime-restart";
5
+ /** One check that failed in a pass: the step that failed and its clipped diagnostics. */
6
+ export interface PrePublicationCheckFailure {
7
+ readonly checkId: string;
8
+ readonly exitCode: number;
9
+ readonly command: string;
10
+ readonly args: readonly string[];
11
+ readonly detail: string;
12
+ }
13
+ /**
14
+ * A failed validation pass. The single-check fields name the first failure, as they always have;
15
+ * `failures` lists every check that failed in the pass, in the order the checks ran.
16
+ */
17
+ export declare class PrePublicationValidationError extends ForgeFailureError {
18
+ readonly checkId: string;
19
+ readonly exitCode: number;
20
+ readonly command: string;
21
+ readonly args: readonly string[];
22
+ readonly detail: string;
23
+ readonly code = "prepublication_validation_failed";
24
+ readonly failures: readonly PrePublicationCheckFailure[];
25
+ constructor(checkId: string, exitCode: number, command: string, args: readonly string[], detail: string, additionalFailures?: readonly PrePublicationCheckFailure[]);
26
+ /** Every failed check's id, first failure first. */
27
+ get checkIds(): readonly string[];
28
+ }
29
+ export declare class PrePublicationPass {
30
+ private readonly runtimeRestartFailure?;
31
+ private readonly failures;
32
+ /** The check whose .NET build failed to compile in this pass, if any. */
33
+ private dotnetCompileFailedIn;
34
+ /** A failed runtime restart before the pass is its first failure. */
35
+ constructor(runtimeRestartFailure?: PrePublicationValidationError | undefined);
36
+ record(failure: PrePublicationCheckFailure, failedStep?: ValidationStep): void;
37
+ /** The failed checks that keep this check from running meaningfully in this pass. */
38
+ blockers(checkId: string): readonly string[];
39
+ /**
40
+ * Whether an error ends the pass with the failures it already found. Only a classified retryable
41
+ * failure (a resource hold, lost infrastructure, a supervisor that did not start) does, once the
42
+ * pass has found a failure: the repair turn can fix those failures now, and the next pass meets
43
+ * the condition again. Any other error, or cancellation, still ends the attempt as it did.
44
+ */
45
+ stopsAt(error: unknown, signal?: AbortSignal): error is ForgeFailureError;
46
+ stoppedEvent(checkId: string, error: ForgeFailureError): RunnerDispatchEvent;
47
+ /** Throws every failure the pass found as one validation failure. */
48
+ throwIfFailed(): void;
49
+ }
50
+ export declare function skippedCheckEvent(checkId: string, blockedBy: readonly string[]): RunnerDispatchEvent;
51
+ /** The tests a check's steps skipped, so a check that passed with skips says so with each reason. */
52
+ export declare class SkippedTestTally {
53
+ private readonly worktreePath;
54
+ private readonly environment?;
55
+ private summary;
56
+ constructor(worktreePath: string, environment?: Readonly<Record<string, string>> | undefined);
57
+ /** The invocation's own arguments: a managed attempt may direct results to its test-output root. */
58
+ add(args: readonly string[], stepStartedMs: number): Promise<void>;
59
+ passedEvent(checkId: string, secrets: readonly string[]): RunnerDispatchEvent;
60
+ }
61
+ export declare function validationEvent(eventType: string, checkId: string, content: string, detail?: Readonly<Record<string, unknown>>): RunnerDispatchEvent;