@loucompanion/forge-bridge 0.1.4-dev.bfa11ebe98c6 → 0.1.4-dev.c03d3c89ec4a

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 (174) hide show
  1. package/README.md +45 -3
  2. package/dist/bridge/bridge.base.d.ts +9 -0
  3. package/dist/bridge/bridge.service.d.ts +84 -2
  4. package/dist/bridge/bridge.service.js +358 -12
  5. package/dist/bridge/bridge.types.d.ts +22 -0
  6. package/dist/bridge/dispatch-result-outbox.d.ts +11 -1
  7. package/dist/bridge/dispatch-result-outbox.js +31 -6
  8. package/dist/bridge/local-yield-flag.d.ts +6 -0
  9. package/dist/bridge/local-yield-flag.js +34 -0
  10. package/dist/bridge/runner-host-capabilities.d.ts +2 -0
  11. package/dist/bridge/runner-host-capabilities.js +4 -0
  12. package/dist/bridge/test-postgres-capability.d.ts +14 -0
  13. package/dist/bridge/test-postgres-capability.js +120 -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 +20 -2
  24. package/dist/cli/cli.service.d.ts +16 -0
  25. package/dist/cli/cli.service.js +142 -16
  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/attempt-database-broker.d.ts +89 -0
  30. package/dist/runtime/attempt-database-broker.js +390 -0
  31. package/dist/runtime/attempt-process-supervisor.d.ts +24 -0
  32. package/dist/runtime/attempt-process-supervisor.js +77 -3
  33. package/dist/runtime/host-database-capability-boundary.d.ts +1 -1
  34. package/dist/runtime/host-database-capability-boundary.js +1 -0
  35. package/dist/runtime/host-diagnostics.js +4 -3
  36. package/dist/runtime/host-facts.d.ts +35 -0
  37. package/dist/runtime/host-facts.js +95 -0
  38. package/dist/runtime/host-load-admission.d.ts +60 -0
  39. package/dist/runtime/host-load-admission.js +99 -0
  40. package/dist/runtime/host-load-child-environment.d.ts +22 -0
  41. package/dist/runtime/host-load-child-environment.js +67 -0
  42. package/dist/runtime/host-load-forge-cgroups.d.ts +49 -0
  43. package/dist/runtime/host-load-forge-cgroups.js +140 -0
  44. package/dist/runtime/host-load-governor-config.d.ts +43 -0
  45. package/dist/runtime/host-load-governor-config.js +76 -0
  46. package/dist/runtime/host-load-governor.d.ts +174 -0
  47. package/dist/runtime/host-load-governor.js +541 -0
  48. package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
  49. package/dist/runtime/host-load-ledger-lock.js +185 -0
  50. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  51. package/dist/runtime/host-load-runtime-settings.js +78 -0
  52. package/dist/runtime/host-load-sampler.d.ts +126 -0
  53. package/dist/runtime/host-load-sampler.js +232 -0
  54. package/dist/runtime/host-load-step-class.d.ts +68 -0
  55. package/dist/runtime/host-load-step-class.js +106 -0
  56. package/dist/runtime/host-load-step-reaper.d.ts +27 -0
  57. package/dist/runtime/host-load-step-reaper.js +95 -0
  58. package/dist/runtime/host-load-step-run.d.ts +73 -0
  59. package/dist/runtime/host-load-step-run.js +102 -0
  60. package/dist/runtime/host-load-token-ledger.d.ts +174 -0
  61. package/dist/runtime/host-load-token-ledger.js +421 -0
  62. package/dist/runtime/host-pressure-stall.d.ts +61 -0
  63. package/dist/runtime/host-pressure-stall.js +168 -0
  64. package/dist/runtime/host-runtime-contract.d.ts +4 -0
  65. package/dist/runtime/host-runtime-contract.js +75 -11
  66. package/dist/runtime/host-runtime-lease.d.ts +76 -4
  67. package/dist/runtime/host-runtime-lease.js +386 -32
  68. package/dist/runtime/host-runtime-promotion.d.ts +23 -0
  69. package/dist/runtime/host-runtime-promotion.js +48 -0
  70. package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
  71. package/dist/runtime/host-runtime-requirements-check.js +29 -0
  72. package/dist/runtime/host-runtime-requirements.d.ts +36 -0
  73. package/dist/runtime/host-runtime-requirements.js +117 -0
  74. package/dist/runtime/managed-command-teardown.d.ts +62 -0
  75. package/dist/runtime/managed-command-teardown.js +607 -0
  76. package/dist/runtime/node-host-runtime-adapter.js +5 -4
  77. package/dist/runtime/playwright-browser-cache.d.ts +39 -0
  78. package/dist/runtime/playwright-browser-cache.js +227 -0
  79. package/dist/runtime/playwright-host-runtime-adapter.d.ts +18 -0
  80. package/dist/runtime/playwright-host-runtime-adapter.js +61 -55
  81. package/dist/runtime/runner-settings.d.ts +100 -0
  82. package/dist/runtime/runner-settings.js +214 -0
  83. package/dist/sandbox/host-capacity-broker.d.ts +107 -0
  84. package/dist/sandbox/host-capacity-broker.js +315 -0
  85. package/dist/sandbox/repository-lock.js +3 -2
  86. package/dist/sandbox/runtime.d.ts +10 -1
  87. package/dist/sandbox/runtime.js +50 -6
  88. package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
  89. package/dist/sandbox/sandbox-cgroups.js +42 -0
  90. package/dist/session/managed-attempt-tools.d.ts +27 -0
  91. package/dist/session/managed-attempt-tools.js +366 -45
  92. package/dist/session/managed-build-coordinator.d.ts +1 -1
  93. package/dist/session/managed-build-coordinator.js +8 -4
  94. package/dist/session/managed-command-host-load.d.ts +45 -0
  95. package/dist/session/managed-command-host-load.js +82 -0
  96. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  97. package/dist/session/mcp-argument-coercion.js +121 -0
  98. package/dist/session/phase-completion.artifacts.d.ts +7 -0
  99. package/dist/session/phase-completion.artifacts.js +98 -25
  100. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  101. package/dist/session/phase-completion.command-validation.js +77 -0
  102. package/dist/session/phase-completion.d.ts +4 -0
  103. package/dist/session/phase-completion.helpers.js +13 -12
  104. package/dist/session/phase-completion.js +4 -0
  105. package/dist/session/phase-completion.prompts.js +6 -1
  106. package/dist/session/phase-completion.runtime.d.ts +5 -3
  107. package/dist/session/phase-completion.runtime.js +78 -36
  108. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  109. package/dist/session/phase-completion.schema-parts.js +188 -0
  110. package/dist/session/phase-completion.schemas.d.ts +3 -3
  111. package/dist/session/phase-completion.schemas.js +206 -221
  112. package/dist/session/phase-completion.validation.d.ts +2 -3
  113. package/dist/session/phase-completion.validation.js +46 -92
  114. package/dist/session/pre-publication-host-load.d.ts +27 -0
  115. package/dist/session/pre-publication-host-load.js +111 -0
  116. package/dist/session/pre-publication-pass.d.ts +60 -0
  117. package/dist/session/pre-publication-pass.js +145 -0
  118. package/dist/session/pre-publication-process.d.ts +23 -0
  119. package/dist/session/pre-publication-process.js +109 -0
  120. package/dist/session/pre-publication-skipped-tests.d.ts +21 -0
  121. package/dist/session/pre-publication-skipped-tests.js +109 -0
  122. package/dist/session/pre-publication-step-execution.d.ts +11 -0
  123. package/dist/session/pre-publication-step-execution.js +49 -0
  124. package/dist/session/pre-publication-validation.d.ts +30 -20
  125. package/dist/session/pre-publication-validation.js +178 -193
  126. package/dist/session/provider-cli/pre-publication-repair.d.ts +40 -0
  127. package/dist/session/provider-cli/pre-publication-repair.js +243 -0
  128. package/dist/session/provider-cli/provider-cli.artifacts.d.ts +2 -1
  129. package/dist/session/provider-cli/provider-cli.artifacts.js +21 -15
  130. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
  131. package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
  132. package/dist/session/provider-cli/provider-cli.process.d.ts +37 -1
  133. package/dist/session/provider-cli/provider-cli.process.js +299 -25
  134. package/dist/session/provider-cli/provider-cli.prompts.d.ts +7 -0
  135. package/dist/session/provider-cli/provider-cli.prompts.js +62 -9
  136. package/dist/session/provider-cli/provider-cli.runtime.d.ts +6 -0
  137. package/dist/session/provider-cli/provider-cli.runtime.js +14 -0
  138. package/dist/session/provider-cli/provider-cli.service.d.ts +4 -1
  139. package/dist/session/provider-cli/provider-cli.service.js +200 -162
  140. package/dist/session/provider-cli/provider-cli.types.d.ts +30 -0
  141. package/dist/session/provider-cli/provider-in-flight-work.d.ts +6 -0
  142. package/dist/session/provider-cli/provider-in-flight-work.js +47 -0
  143. package/dist/session/provider-cli/provider-output-state.d.ts +6 -0
  144. package/dist/session/provider-cli/provider-output-state.js +9 -0
  145. package/dist/session/provider-cli/provider-usage.d.ts +2 -1
  146. package/dist/session/publishable-worktree-changes.d.ts +54 -0
  147. package/dist/session/publishable-worktree-changes.js +193 -0
  148. package/dist/session/sandbox-host-capacity-gate.d.ts +30 -0
  149. package/dist/session/sandbox-host-capacity-gate.js +229 -0
  150. package/dist/session/session.base.d.ts +9 -1
  151. package/dist/session/session.service.d.ts +9 -2
  152. package/dist/session/session.service.js +120 -5
  153. package/dist/session/session.types.d.ts +3 -0
  154. package/dist/session/session.types.js +15 -3
  155. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  156. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  157. package/dist/shared/process/host-process-recovery.js +3 -2
  158. package/dist/shared/process/host-process-supervisor.d.ts +1 -0
  159. package/dist/shared/process/host-process-supervisor.js +6 -5
  160. package/dist/shared/process/process-tree.d.ts +52 -0
  161. package/dist/shared/process/process-tree.js +144 -0
  162. package/dist/shared/process/process.d.ts +67 -0
  163. package/dist/shared/process/process.js +213 -11
  164. package/dist/shared/provider-capabilities.js +5 -6
  165. package/dist/shared/time/monotonic.d.ts +1 -0
  166. package/dist/shared/time/monotonic.js +8 -0
  167. package/dist/version.d.ts +1 -1
  168. package/dist/version.js +1 -1
  169. package/dist/worktree/dependency-warmer.d.ts +25 -0
  170. package/dist/worktree/dependency-warmer.js +120 -10
  171. package/dist/worktree/worktree.service.d.ts +10 -1
  172. package/dist/worktree/worktree.service.js +42 -2
  173. package/dist/worktree/worktree.types.d.ts +7 -0
  174. package/package.json +2 -2
@@ -1,15 +1,17 @@
1
- import { execFile } from "node:child_process";
2
1
  import { createHash, randomUUID } from "node:crypto";
3
2
  import fs from "node:fs/promises";
4
3
  import path from "node:path";
5
- import { promisify } from "node:util";
4
+ import { attemptDatabaseCapabilityEnvironment, attemptDatabaseCapabilitySecrets, } from "../runtime/attempt-database-broker.js";
6
5
  import { assertHostDatabaseCapabilityBoundary } from "../runtime/host-database-capability-boundary.js";
7
- import { nativeTestPostgresFallbackEnvironment, parseNativeTestPostgresFallback, } from "../runtime/native-test-postgres-fallback.js";
8
- import { hostRuntimeLegacyTestPostgresEnvironment, hostRuntimeTestPostgresAdminEnvironment, } from "../runtime/host-runtime-contract.js";
6
+ import { runHostGovernedValidationStep } from "./pre-publication-host-load.js";
7
+ import { managedAttemptInvocation, supportsNativeTestPostgresFallback, validationExecutionForStep, } from "./pre-publication-step-execution.js";
8
+ import { hostRuntimeLegacyTestPostgresEnvironment, hostRuntimeTestPostgresAdminEnvironment, hostRuntimeTestPostgresProvisionerEnvironment, } from "../runtime/host-runtime-contract.js";
9
9
  import { redactText } from "../shared/redaction/redaction.js";
10
+ import { PrePublicationPass, PrePublicationValidationError, SkippedTestTally, skippedCheckEvent, validationEvent, } from "./pre-publication-pass.js";
11
+ import { ProcessPrePublicationCommandRunner, pnpmDirectoryLaunch } from "./pre-publication-process.js";
12
+ import { ProcessTreeTerminationError } from "../shared/process/process.js";
10
13
  import { findUnreferencedNewExports } from "./unreferenced-exports.js";
11
14
  import { ForgeFailureError, sanitizeFailureError, } from "./session.types.js";
12
- const execFileAsync = promisify(execFile);
13
15
  const contractRelativePath = ".forge/validation/ci-parity.v1.json";
14
16
  const requiredCheckIds = new Set([
15
17
  "file-size-inventory",
@@ -46,23 +48,31 @@ const approvedContractDigests = new Set([
46
48
  ...compatibleApprovedContractDigests,
47
49
  ]);
48
50
  const ansiColorSequence = new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*m`, "gu");
49
- export class PrePublicationValidationError extends ForgeFailureError {
50
- checkId;
51
- exitCode;
52
- command;
53
- args;
54
- detail;
55
- code = "prepublication_validation_failed";
56
- constructor(checkId, exitCode, command, args, detail) {
57
- super("prepublication_validation_failed", `prepublication_validation_failed: ${checkId} exited ${exitCode}${detail ? `: ${detail}` : ""}`, "bridge");
58
- this.checkId = checkId;
59
- this.exitCode = exitCode;
60
- this.command = command;
61
- this.args = args;
62
- this.detail = detail;
63
- this.name = "PrePublicationValidationError";
64
- }
65
- }
51
+ const timeoutConfirmation = {
52
+ started: [
53
+ "prepublication_validation_timeout_confirmation_started",
54
+ "The full client test step reported only Vitest timeouts; confirming once with the same command and attempt environment.",
55
+ ],
56
+ passed: [
57
+ "prepublication_validation_timeout_confirmation_passed",
58
+ "The complete client test step passed on its single timeout confirmation run.",
59
+ ],
60
+ failedEvent: "prepublication_validation_timeout_confirmation_failed",
61
+ failedContent: exitCode => `The complete client test step failed on its single timeout confirmation run (exit ${exitCode}).`,
62
+ };
63
+ const cleanupConfirmation = {
64
+ started: [
65
+ "prepublication_validation_cleanup_confirmation_started",
66
+ "The Bridge suite hit the known Windows temporary-worktree cleanup race; confirming once with the same command and attempt environment.",
67
+ ],
68
+ passed: [
69
+ "prepublication_validation_cleanup_confirmation_passed",
70
+ "The complete Bridge test step passed on its single cleanup confirmation run.",
71
+ ],
72
+ failedEvent: "prepublication_validation_cleanup_confirmation_failed",
73
+ failedContent: exitCode => `The complete Bridge test step failed on its single cleanup confirmation run (exit ${exitCode}).`,
74
+ };
75
+ export { PrePublicationValidationError };
66
76
  export class PrePublicationInfrastructureError extends ForgeFailureError {
67
77
  checkId;
68
78
  exitCode;
@@ -80,157 +90,166 @@ export class PrePublicationInfrastructureError extends ForgeFailureError {
80
90
  this.name = "PrePublicationInfrastructureError";
81
91
  }
82
92
  }
83
- class ProcessPrePublicationCommandRunner {
84
- async run(command, args, cwd, signal, environment) {
85
- try {
86
- const windowsBatch = process.platform === "win32" && (command === "npm" || command === "pnpm");
87
- const executable = windowsBatch ? (process.env.ComSpec ?? "cmd.exe") : command;
88
- const commandArgs = windowsBatch
89
- ? ["/d", "/s", "/c", [`${command}.cmd`, ...args].map(quoteWindowsCommandArgument).join(" ")]
90
- : [...args];
91
- const result = await execFileAsync(executable, commandArgs, {
92
- cwd,
93
- encoding: "utf8",
94
- maxBuffer: 4 * 1024 * 1024,
95
- signal,
96
- env: prePublicationChildEnvironment(environment),
97
- });
98
- return { exitCode: 0, stdout: result.stdout, stderr: result.stderr };
99
- }
100
- catch (error) {
101
- const failure = error;
102
- if (failure.name === "AbortError")
103
- throw error;
104
- if (failure.code === "ENOENT") {
105
- return { exitCode: 127, stderr: `executable_not_found: ${command}` };
106
- }
107
- return {
108
- exitCode: typeof failure.code === "number" ? failure.code : 1,
109
- stdout: failure.stdout,
110
- stderr: failure.stderr ?? failure.message,
111
- };
112
- }
113
- }
114
- }
115
- function quoteWindowsCommandArgument(value) {
116
- return /^[A-Za-z0-9_./:@=-]+$/u.test(value) ? value : `"${value.replaceAll('"', '""')}"`;
117
- }
118
- function prePublicationChildEnvironment(environment) {
119
- const child = {};
120
- const privilegedNames = new Set([
121
- hostRuntimeTestPostgresAdminEnvironment.toLowerCase(),
122
- hostRuntimeLegacyTestPostgresEnvironment.toLowerCase(),
123
- ]);
124
- for (const [name, value] of Object.entries(process.env)) {
125
- if (typeof value === "string" && !privilegedNames.has(name.toLowerCase())) {
126
- child[name] = value;
127
- }
128
- }
129
- return { ...child, ...environment };
130
- }
131
93
  export class PrePublicationValidator {
132
94
  commands;
133
95
  dockerEngineProbe;
134
96
  nativeTestPostgresFallback;
135
- constructor(commands = new ProcessPrePublicationCommandRunner(), dockerEngineProbe, nativeTestPostgresFallback = () => null) {
97
+ hostLoad;
98
+ constructor(commands = new ProcessPrePublicationCommandRunner(), dockerEngineProbe, nativeTestPostgresFallback = () => null, hostLoad) {
136
99
  this.commands = commands;
137
100
  this.dockerEngineProbe = dockerEngineProbe;
138
101
  this.nativeTestPostgresFallback = nativeTestPostgresFallback;
102
+ this.hostLoad = hostLoad;
139
103
  }
104
+ /**
105
+ * Runs one pre-publication pass. A failed check does not end the pass: every remaining check that
106
+ * can still meaningfully run keeps going, and the pass then throws all of its failures as one
107
+ * PrePublicationValidationError.
108
+ */
140
109
  async validate(worktreePath, profile, capabilities, emit, signal, execution) {
141
110
  const checksExports = profile === "implementation" || profile === "comment_repair";
111
+ const pass = new PrePublicationPass(execution?.runtimeRestartFailure);
142
112
  const contract = await loadValidationContract(worktreePath);
143
113
  if (contract === null) {
144
114
  await emit?.(validationEvent("prepublication_validation_legacy_contract", "legacy-provider-validation", `This checkout predates ${contractRelativePath}; Bridge preserved legacy provider validation without source mutation.`));
145
115
  if (checksExports) {
146
116
  const legacy = await prepareValidationExecution(execution);
147
117
  try {
148
- await this.assertNoTestOnlyExports(worktreePath, emit, signal, legacy.execution);
118
+ await this.checkTestOnlyExports(pass, worktreePath, emit, signal, legacy.execution);
149
119
  }
150
120
  finally {
151
121
  await legacy.cleanup();
152
122
  }
153
123
  }
124
+ pass.throwIfFailed();
154
125
  return [];
155
126
  }
156
127
  const scoped = await prepareValidationExecution(execution);
157
128
  try {
158
129
  if (checksExports)
159
- await this.assertNoTestOnlyExports(worktreePath, emit, signal, scoped.execution);
130
+ await this.checkTestOnlyExports(pass, worktreePath, emit, signal, scoped.execution);
160
131
  const contractDigest = validationContractDigest(contract);
161
132
  await this.assertContractMatchesDispatchBaseline(worktreePath, contractDigest, signal, scoped.execution);
162
133
  if (contractDigest !== currentApprovedContractDigest) {
163
134
  await emit?.(validationEvent("prepublication_validation_compatible_contract", "validation-contract", `This checkout is pinned to approved compatible CI parity contract ${contractDigest}; the host's current contract is ${currentApprovedContractDigest}.`));
164
135
  }
165
136
  const changedPaths = await this.changedPaths(worktreePath, signal, scoped.execution);
166
- const selected = applicableChecks(contract, profile, changedPaths);
167
- const completed = [];
168
- for (const check of selected) {
169
- if (check.providerOnly) {
170
- await emit?.(validationEvent("prepublication_validation_provider_only", check.id, `Preserved provider-only validation '${check.id}' for the provider check run.`));
171
- continue;
172
- }
173
- if (check.requiredCapability && !capabilities.has(check.requiredCapability)) {
174
- throw new ForgeFailureError("prepublication_capability_unavailable", `prepublication_capability_unavailable: ${check.id} requires ${check.requiredCapability}; publication is holding until a capable runner is available.`, "bridge");
175
- }
176
- const postgresAdminConnection = await this.ensurePrerequisite(check, scoped.execution?.environment, scoped.postgresAdminConnection, emit) ?? scoped.postgresAdminConnection;
177
- await emit?.(validationEvent("prepublication_validation_started", check.id, `Running pre-publication CI parity check '${check.id}'.`));
178
- for (const step of check.steps) {
179
- let result = await this.runStep(check.id, step, worktreePath, signal, scoped.execution, postgresAdminConnection);
180
- await this.throwIfPrerequisiteWasLost(check, result, scoped.execution?.environment, postgresAdminConnection, emit);
181
- if (isTimeoutOnlyClientTestFailure(check.id, step, result)) {
182
- await emit?.(validationEvent("prepublication_validation_timeout_confirmation_started", check.id, "The full client test step reported only Vitest timeouts; confirming once with the same command and attempt environment."));
183
- result = await this.runStep(check.id, step, worktreePath, signal, scoped.execution, postgresAdminConnection);
184
- await this.throwIfPrerequisiteWasLost(check, result, scoped.execution?.environment, postgresAdminConnection, emit);
185
- await emit?.(validationEvent(result.exitCode === 0
186
- ? "prepublication_validation_timeout_confirmation_passed"
187
- : "prepublication_validation_timeout_confirmation_failed", check.id, result.exitCode === 0
188
- ? "The complete client test step passed on its single timeout confirmation run."
189
- : `The complete client test step failed on its single timeout confirmation run (exit ${result.exitCode}).`));
190
- }
191
- if (isTransientBridgeCleanupFailure(check.id, step, result)) {
192
- await emit?.(validationEvent("prepublication_validation_cleanup_confirmation_started", check.id, "The Bridge suite hit the known Windows temporary-worktree cleanup race; confirming once with the same command and attempt environment."));
193
- result = await this.runStep(check.id, step, worktreePath, signal, scoped.execution, postgresAdminConnection);
194
- await this.throwIfPrerequisiteWasLost(check, result, scoped.execution?.environment, postgresAdminConnection, emit);
195
- await emit?.(validationEvent(result.exitCode === 0
196
- ? "prepublication_validation_cleanup_confirmation_passed"
197
- : "prepublication_validation_cleanup_confirmation_failed", check.id, result.exitCode === 0
198
- ? "The complete Bridge test step passed on its single cleanup confirmation run."
199
- : `The complete Bridge test step failed on its single cleanup confirmation run (exit ${result.exitCode}).`));
200
- }
201
- if (isTransientShellInfrastructureFailure(result)) {
202
- await emit?.(validationEvent("prepublication_infrastructure_confirmation_started", check.id, "The validation shell reported a known host-runtime failure; confirming once with the same command and attempt environment."));
203
- result = await this.runStep(check.id, step, worktreePath, signal, scoped.execution, postgresAdminConnection);
204
- await this.throwIfPrerequisiteWasLost(check, result, scoped.execution?.environment, postgresAdminConnection, emit);
205
- const infrastructureFailed = isTransientShellInfrastructureFailure(result);
206
- await emit?.(validationEvent(infrastructureFailed
207
- ? "prepublication_infrastructure_confirmation_failed"
208
- : "prepublication_infrastructure_confirmation_passed", check.id, infrastructureFailed
209
- ? `The validation shell failed again on its single infrastructure confirmation run (exit ${result.exitCode}).`
210
- : result.exitCode === 0
211
- ? "The validation step recovered on its single infrastructure confirmation run."
212
- : "The host-runtime failure did not recur; continuing with normal validation failure handling."));
213
- if (infrastructureFailed) {
214
- const detail = diagnosticDetail(result);
215
- await emit?.(validationEvent("prepublication_infrastructure_failed", check.id, `Pre-publication infrastructure for '${check.id}' remained unavailable${detail ? `: ${detail}` : "."}`));
216
- throw new PrePublicationInfrastructureError(check.id, result.exitCode, result.command, result.args, detail);
217
- }
218
- }
219
- if (result.exitCode !== 0) {
220
- const detail = diagnosticDetail(result);
221
- await emit?.(validationEvent("prepublication_validation_failed", check.id, `Pre-publication CI parity check '${check.id}' exited ${result.exitCode}${detail ? `: ${detail}` : "."}`));
222
- throw new PrePublicationValidationError(check.id, result.exitCode, result.command, result.args, detail);
223
- }
224
- }
225
- completed.push(check.id);
226
- await emit?.(validationEvent("prepublication_validation_passed", check.id, `Pre-publication CI parity check '${check.id}' passed.`));
227
- }
228
- return completed;
137
+ const run = {
138
+ worktreePath,
139
+ capabilities,
140
+ emit,
141
+ signal,
142
+ execution: scoped.execution,
143
+ postgresAdminConnection: scoped.postgresAdminConnection,
144
+ };
145
+ return await this.runChecks(applicableChecks(contract, profile, changedPaths), run, pass);
229
146
  }
230
147
  finally {
231
148
  await scoped.cleanup();
232
149
  }
233
150
  }
151
+ async runChecks(checks, run, pass) {
152
+ const completed = [];
153
+ for (const check of checks) {
154
+ if (check.providerOnly) {
155
+ await run.emit?.(validationEvent("prepublication_validation_provider_only", check.id, `Preserved provider-only validation '${check.id}' for the provider check run.`));
156
+ continue;
157
+ }
158
+ const blockedBy = pass.blockers(check.id);
159
+ if (blockedBy.length > 0) {
160
+ await run.emit?.(skippedCheckEvent(check.id, blockedBy));
161
+ continue;
162
+ }
163
+ try {
164
+ const failed = await this.runCheck(check, run);
165
+ // A cancelled step may settle with an exit code rather than throw; the pass ends either way.
166
+ run.signal?.throwIfAborted();
167
+ if (failed)
168
+ pass.record(failed.failure, failed.step);
169
+ else
170
+ completed.push(check.id);
171
+ }
172
+ catch (error) {
173
+ if (!pass.stopsAt(error, run.signal))
174
+ throw error;
175
+ await run.emit?.(pass.stoppedEvent(check.id, error));
176
+ break;
177
+ }
178
+ }
179
+ pass.throwIfFailed();
180
+ return completed;
181
+ }
182
+ /** Runs one check's steps in order; the first failed step ends the check, since later steps use its output. */
183
+ async runCheck(check, run) {
184
+ if (check.requiredCapability && !run.capabilities.has(check.requiredCapability)) {
185
+ throw new ForgeFailureError("prepublication_capability_unavailable", `prepublication_capability_unavailable: ${check.id} requires ${check.requiredCapability}; publication is holding until a capable runner is available.`, "bridge");
186
+ }
187
+ const postgresAdminConnection = await this.ensurePrerequisite(check, run.execution?.environment, run.postgresAdminConnection, run.emit) ?? run.postgresAdminConnection;
188
+ const stepRun = { ...run, check, postgresAdminConnection };
189
+ await run.emit?.(validationEvent("prepublication_validation_started", check.id, `Running pre-publication CI parity check '${check.id}'.`));
190
+ const skipped = new SkippedTestTally(run.worktreePath, run.execution?.environment);
191
+ for (const step of check.steps) {
192
+ const stepStartedMs = Date.now() - 1000;
193
+ const result = await this.runConfirmedStep(stepRun, step);
194
+ if (result.exitCode !== 0) {
195
+ const detail = diagnosticDetail(result);
196
+ await run.emit?.(validationEvent("prepublication_validation_failed", check.id, `Pre-publication CI parity check '${check.id}' exited ${result.exitCode}${detail ? `: ${detail}` : "."}`));
197
+ return {
198
+ failure: { checkId: check.id, exitCode: result.exitCode, command: result.command, args: result.args, detail },
199
+ step,
200
+ };
201
+ }
202
+ await skipped.add(result.args, stepStartedMs);
203
+ }
204
+ await run.emit?.(skipped.passedEvent(check.id, validationExactSecrets(run.execution?.environment)));
205
+ return null;
206
+ }
207
+ /** Runs a step, confirming once a failure that matches a known transient pattern. */
208
+ async runConfirmedStep(run, step) {
209
+ let result = await this.runCheckedStep(run, step);
210
+ if (isTimeoutOnlyClientTestFailure(run.check.id, step, result)) {
211
+ result = await this.confirmStep(run, step, timeoutConfirmation);
212
+ }
213
+ if (isTransientBridgeCleanupFailure(run.check.id, step, result)) {
214
+ result = await this.confirmStep(run, step, cleanupConfirmation);
215
+ }
216
+ if (isTransientShellInfrastructureFailure(result)) {
217
+ result = await this.confirmInfrastructure(run, step);
218
+ }
219
+ return result;
220
+ }
221
+ async runCheckedStep(run, step) {
222
+ const { check, worktreePath, signal, execution, postgresAdminConnection, emit } = run;
223
+ const result = await this.runStep(check.id, step, worktreePath, signal, execution, postgresAdminConnection, emit);
224
+ await this.throwIfPrerequisiteWasLost(check, result, execution?.environment, postgresAdminConnection, emit);
225
+ return result;
226
+ }
227
+ async confirmStep(run, step, confirmation) {
228
+ await run.emit?.(validationEvent(confirmation.started[0], run.check.id, confirmation.started[1]));
229
+ const result = await this.runCheckedStep(run, step);
230
+ await run.emit?.(result.exitCode === 0
231
+ ? validationEvent(confirmation.passed[0], run.check.id, confirmation.passed[1])
232
+ : validationEvent(confirmation.failedEvent, run.check.id, confirmation.failedContent(result.exitCode)));
233
+ return result;
234
+ }
235
+ async confirmInfrastructure(run, step) {
236
+ const checkId = run.check.id;
237
+ await run.emit?.(validationEvent("prepublication_infrastructure_confirmation_started", checkId, "The validation shell reported a known host-runtime failure; confirming once with the same command and attempt environment."));
238
+ const result = await this.runCheckedStep(run, step);
239
+ const infrastructureFailed = isTransientShellInfrastructureFailure(result);
240
+ await run.emit?.(validationEvent(infrastructureFailed
241
+ ? "prepublication_infrastructure_confirmation_failed"
242
+ : "prepublication_infrastructure_confirmation_passed", checkId, infrastructureFailed
243
+ ? `The validation shell failed again on its single infrastructure confirmation run (exit ${result.exitCode}).`
244
+ : result.exitCode === 0
245
+ ? "The validation step recovered on its single infrastructure confirmation run."
246
+ : "The host-runtime failure did not recur; continuing with normal validation failure handling."));
247
+ if (!infrastructureFailed)
248
+ return result;
249
+ const detail = diagnosticDetail(result);
250
+ await run.emit?.(validationEvent("prepublication_infrastructure_failed", checkId, `Pre-publication infrastructure for '${checkId}' remained unavailable${detail ? `: ${detail}` : "."}`));
251
+ throw new PrePublicationInfrastructureError(checkId, result.exitCode, result.command, result.args, detail);
252
+ }
234
253
  /** Returns the native fallback connection when this check must use it instead of Docker. */
235
254
  async ensurePrerequisite(check, environment, postgresAdminConnection, emit) {
236
255
  if (check.requiredPrerequisite === "isolated_postgres"
@@ -251,7 +270,7 @@ export class PrePublicationValidator {
251
270
  const snapshot = await this.dockerEngineProbe.ensureAvailableForRequiredWork();
252
271
  if (!snapshot.available) {
253
272
  const detail = `Docker prerequisite unavailable (${snapshot.unavailableCode ?? "docker_engine_unavailable"}): ${snapshot.unavailableReason ?? "the daemon did not pass a fresh readiness probe"}`;
254
- const fallback = check.requiredPrerequisite === "isolated_postgres" && supportsNativeTestPostgresFallback(check)
273
+ const fallback = check.requiredPrerequisite === "isolated_postgres" && supportsNativeTestPostgresFallback(check.id)
255
274
  ? this.nativeTestPostgresFallback()
256
275
  : null;
257
276
  if (fallback) {
@@ -279,7 +298,8 @@ export class PrePublicationValidator {
279
298
  throw new PrePublicationInfrastructureError(check.id, result.exitCode, result.command, result.args, detail);
280
299
  }
281
300
  // Runs for every target repository, with or without a CI parity contract: it only reads the worktree.
282
- async assertNoTestOnlyExports(worktreePath, emit, signal, execution) {
301
+ // A failure joins the pass's failures; the contract's checks still run.
302
+ async checkTestOnlyExports(pass, worktreePath, emit, signal, execution) {
283
303
  const found = await findUnreferencedNewExports(args => this.runCommand("git", args, worktreePath, signal, execution), worktreePath, execution?.baselineRevision);
284
304
  const unused = found.filter(row => !row.testOnly);
285
305
  if (unused.length > 0) {
@@ -290,7 +310,7 @@ export class PrePublicationValidator {
290
310
  return;
291
311
  const detail = `only tests use ${testOnly.map(row => `${row.name} (${row.path})`).join(", ")}. Wire each to a real caller in this Story, or move the export and its test to the Story that first uses it. Do not delete assertions to pass.`;
292
312
  await emit?.(validationEvent("prepublication_validation_failed", "unreferenced-exports", `New code is tested but never called: ${detail}`));
293
- throw new PrePublicationValidationError("unreferenced-exports", 1, "git", ["grep"], detail);
313
+ pass.record({ checkId: "unreferenced-exports", exitCode: 1, command: "git", args: ["grep"], detail });
294
314
  }
295
315
  async changedPaths(worktreePath, signal, execution) {
296
316
  const baselineRevision = execution?.baselineRevision?.trim();
@@ -337,8 +357,14 @@ export class PrePublicationValidator {
337
357
  throw new ForgeFailureError("prepublication_contract_invalid", `prepublication_contract_invalid: the CI parity contract changed after dispatch (baseline ${baselineDigest}, worktree ${contractDigest}).`, "bridge");
338
358
  }
339
359
  }
340
- async runStep(checkId, step, cwd, signal, execution, postgresAdminConnection) {
360
+ async runStep(checkId, step, cwd, signal, execution, postgresAdminConnection, emit) {
341
361
  const invocation = managedAttemptInvocation(checkId, step, execution?.environment);
362
+ // Every launch, including confirmation reruns, is admitted by the host load governor first.
363
+ return await runHostGovernedValidationStep(this.hostLoad, {
364
+ checkId, command: invocation.command, args: invocation.args, owner: execution?.hostLoadOwner, signal, emit,
365
+ }, async (stepSignal) => await this.launchStep(checkId, step, invocation, cwd, stepSignal, execution, postgresAdminConnection));
366
+ }
367
+ async launchStep(checkId, step, invocation, cwd, signal, execution, postgresAdminConnection) {
342
368
  const stepExecution = validationExecutionForStep(checkId, step, execution, postgresAdminConnection);
343
369
  const before = await readValidationFiles(cwd, step.assertUnchangedPaths ?? []);
344
370
  const result = await this.runCommand(invocation.command, invocation.args, cwd, signal, stepExecution);
@@ -360,10 +386,11 @@ export class PrePublicationValidator {
360
386
  const exactSecrets = validationExactSecrets(execution?.environment);
361
387
  try {
362
388
  if (execution?.processRunner) {
389
+ const launch = await pnpmDirectoryLaunch(command, args, cwd);
363
390
  const result = await execution.processRunner.run({
364
391
  command,
365
- args,
366
- cwd,
392
+ args: launch.args,
393
+ cwd: launch.cwd,
367
394
  env: execution.environment,
368
395
  captureOutput: true,
369
396
  failureRedactionValues: exactSecrets,
@@ -382,57 +409,13 @@ export class PrePublicationValidator {
382
409
  };
383
410
  }
384
411
  catch (error) {
412
+ // Carries the check its host capacity token waits on; it names only the executable.
413
+ if (error instanceof ProcessTreeTerminationError)
414
+ throw error;
385
415
  throw sanitizeFailureError(error, exactSecrets);
386
416
  }
387
417
  }
388
418
  }
389
- function managedAttemptInvocation(checkId, step, environment) {
390
- const playwrightConfig = environment?.FORGE_PLAYWRIGHT_CONFIG?.trim();
391
- const attemptOwned = environment?.FORGE_E2E_OWNERSHIP_MODE === "attempt"
392
- || Boolean(environment?.FORGE_DISPATCH_ATTEMPT_ID?.trim());
393
- if (checkId !== "playwright-e2e" || !attemptOwned) {
394
- return step;
395
- }
396
- if (!playwrightConfig) {
397
- throw new ForgeFailureError("prepublication_capability_unavailable", "prepublication_capability_unavailable: playwright-e2e requires the Bridge-generated FORGE_PLAYWRIGHT_CONFIG for a managed attempt.", "bridge");
398
- }
399
- return {
400
- command: "pnpm",
401
- args: ["--dir", "tests/e2e", "exec", "playwright", "test", "--config", playwrightConfig],
402
- };
403
- }
404
- const nativeFallbackCheckIds = new Set([
405
- "owned-suite-registration",
406
- "dotnet-build-and-unit",
407
- "comment-repair-dotnet-regression",
408
- ]);
409
- const nativeFallbackDotnetTierScripts = [
410
- "scripts/run-dotnet-test-tier.ps1",
411
- "scripts/run-dotnet-test-tier-set.ps1",
412
- "scripts/run-affected-dotnet-tests.mjs",
413
- ];
414
- function supportsNativeTestPostgresFallback(check) {
415
- return nativeFallbackCheckIds.has(check.id);
416
- }
417
- function validationExecutionForStep(checkId, step, execution, postgresAdminConnection) {
418
- // The connection only exists when Docker is unavailable and the operator
419
- // provisioned a dedicated native test cluster. Only the runner-authored
420
- // .NET test tiers and the suite-identity check receive it; build, client,
421
- // Bridge, and E2E steps never do.
422
- if (!postgresAdminConnection || !nativeFallbackCheckIds.has(checkId))
423
- return execution;
424
- const runsDotnetTier = step.args.some(argument => nativeFallbackDotnetTierScripts
425
- .some(script => argument.replaceAll("\\", "/").endsWith(script)));
426
- if (checkId !== "owned-suite-registration" && !runsDotnetTier)
427
- return execution;
428
- return {
429
- ...execution,
430
- environment: {
431
- ...execution?.environment,
432
- ...nativeTestPostgresFallbackEnvironment(parseNativeTestPostgresFallback(postgresAdminConnection)),
433
- },
434
- };
435
- }
436
419
  function environmentValue(environment, name) {
437
420
  return Object.prototype.hasOwnProperty.call(environment ?? {}, name)
438
421
  ? environment?.[name]?.trim() ?? ""
@@ -444,7 +427,9 @@ function isolatedPostgresProvided(checkId, environment, postgresAdminConnection)
444
427
  return (environmentValue(environment, "FORGE_E2E_OWNERSHIP_MODE") === "attempt"
445
428
  || /^[0-9a-f-]{36}$/iu.test(attemptId))
446
429
  && /^forge_attempt_[0-9a-f]{32}$/u.test(environmentValue(environment, "FORGE_ATTEMPT_DATABASE_SCHEMA"))
447
- && path.isAbsolute(environmentValue(environment, "FORGE_ATTEMPT_DATABASE_READINESS_PATH"));
430
+ && path.isAbsolute(environmentValue(environment, "FORGE_ATTEMPT_DATABASE_READINESS_PATH"))
431
+ // The attempt owns a database only once the Bridge's broker has issued it one.
432
+ && environmentValue(environment, attemptDatabaseCapabilityEnvironment).length > 0;
448
433
  }
449
434
  return Boolean(postgresAdminConnection);
450
435
  }
@@ -452,6 +437,8 @@ function validationExactSecrets(environment) {
452
437
  return [
453
438
  environment?.[hostRuntimeTestPostgresAdminEnvironment]?.trim() ?? "",
454
439
  environment?.[hostRuntimeLegacyTestPostgresEnvironment]?.trim() ?? "",
440
+ environment?.[hostRuntimeTestPostgresProvisionerEnvironment]?.trim() ?? "",
441
+ ...attemptDatabaseCapabilitySecrets(environment?.[attemptDatabaseCapabilityEnvironment]),
455
442
  ].filter((value, index, values) => value.length > 0 && values.indexOf(value) === index);
456
443
  }
457
444
  function diagnosticDetail(result) {
@@ -583,6 +570,7 @@ function withoutPrivilegedPostgresEnvironment(environment) {
583
570
  const privilegedNames = new Set([
584
571
  hostRuntimeTestPostgresAdminEnvironment.toLowerCase(),
585
572
  hostRuntimeLegacyTestPostgresEnvironment.toLowerCase(),
573
+ hostRuntimeTestPostgresProvisionerEnvironment.toLowerCase(),
586
574
  ]);
587
575
  return Object.fromEntries(Object.entries(environment)
588
576
  .filter(([name]) => !privilegedNames.has(name.toLowerCase())));
@@ -652,6 +640,3 @@ function canonicalizeJson(value) {
652
640
  }
653
641
  return value;
654
642
  }
655
- function validationEvent(eventType, checkId, content) {
656
- return { role: "runner", kind: "checkpoint", content, eventType, data: JSON.stringify({ checkId, contractId: "forge-ci-parity-v1" }) };
657
- }
@@ -0,0 +1,40 @@
1
+ import { PrePublicationValidationError, type PrePublicationProfile, type PrePublicationValidator } from "../pre-publication-validation.js";
2
+ import type { ProviderProcessRunner } from "./provider-cli.process.js";
3
+ import type { ProviderCliRunContext } from "./provider-cli.types.js";
4
+ import { type ProviderOutputState } from "./provider-output-state.js";
5
+ /**
6
+ * The in-place repair budget: FORGE_PREPUBLICATION_REPAIR_TURNS when it is a whole number from 1
7
+ * (capped at 10), otherwise 4.
8
+ */
9
+ export declare function prePublicationRepairTurnsFromEnvironment(environment?: Readonly<Record<string, string | undefined>>): number;
10
+ export interface PrePublicationRepairOptions {
11
+ readonly context: ProviderCliRunContext;
12
+ readonly validationProfile: PrePublicationProfile;
13
+ readonly repairEnvironment: Readonly<Record<string, string>> | undefined;
14
+ readonly outputState: ProviderOutputState;
15
+ readonly preparedHeadSha: string;
16
+ readonly repairScope: "implementation" | "pull_request";
17
+ /**
18
+ * Derives the repair environment from a refreshed runtime environment. CI repair
19
+ * rewrites its readiness manifest so the attempt URLs it records stay current.
20
+ */
21
+ readonly onRuntimeEnvironmentRefreshed?: (runtimeEnvironment: Readonly<Record<string, string>>) => Promise<Readonly<Record<string, string>>>;
22
+ }
23
+ /** One resumed provider turn that repairs a failed pass in place. */
24
+ export interface PrePublicationRepairTurn {
25
+ readonly prompt: string;
26
+ readonly repairTurn: number;
27
+ readonly maxRepairTurns: number;
28
+ readonly providerThreadId: string;
29
+ readonly repairEnvironment: Readonly<Record<string, string>> | undefined;
30
+ readonly environment: Readonly<Record<string, string>>;
31
+ readonly failure: PrePublicationValidationError;
32
+ }
33
+ export interface PrePublicationRepairDependencies {
34
+ readonly validator: PrePublicationValidator;
35
+ readonly defaultProcessRunner: ProviderProcessRunner;
36
+ readonly maxRepairTurns: number;
37
+ readonly runRepairTurn: (turn: PrePublicationRepairTurn) => Promise<void>;
38
+ }
39
+ export declare function validatePrePublicationWithRepair(options: PrePublicationRepairOptions, dependencies: PrePublicationRepairDependencies): Promise<void>;
40
+ export declare function buildPrePublicationRepairPrompt(error: PrePublicationValidationError, repairTurn: number, maxRepairTurns: number, repairScope: "implementation" | "pull_request"): string;