@loucompanion/forge-bridge 0.1.4-dev.63db04bcffca → 0.1.4-dev.800627ea0931

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 (170) hide show
  1. package/README.md +54 -2
  2. package/dist/bridge/bridge-chat-provider-command.d.ts +16 -0
  3. package/dist/bridge/bridge-chat-provider-command.js +125 -0
  4. package/dist/bridge/bridge.base.d.ts +9 -0
  5. package/dist/bridge/bridge.service.d.ts +85 -3
  6. package/dist/bridge/bridge.service.js +361 -122
  7. package/dist/bridge/bridge.types.d.ts +22 -0
  8. package/dist/bridge/dispatch-result-outbox.d.ts +11 -1
  9. package/dist/bridge/dispatch-result-outbox.js +31 -6
  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 +2 -0
  13. package/dist/bridge/runner-host-capabilities.js +4 -0
  14. package/dist/bridge/test-postgres-capability.d.ts +14 -0
  15. package/dist/bridge/test-postgres-capability.js +120 -0
  16. package/dist/cleanup/cleanup.service.d.ts +9 -0
  17. package/dist/cleanup/cleanup.service.js +72 -109
  18. package/dist/cleanup/cleanup.types.d.ts +4 -0
  19. package/dist/cleanup/forge-owned-paths.d.ts +9 -0
  20. package/dist/cleanup/forge-owned-paths.js +53 -0
  21. package/dist/cleanup/host-runtime-ledger.d.ts +5 -0
  22. package/dist/cleanup/host-runtime-ledger.js +109 -0
  23. package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
  24. package/dist/cleanup/managed-branch-sweep.js +111 -0
  25. package/dist/cli/cli.help.js +18 -0
  26. package/dist/cli/cli.service.d.ts +16 -0
  27. package/dist/cli/cli.service.js +142 -16
  28. package/dist/cli/local-config.d.ts +4 -0
  29. package/dist/cli/local-config.js +26 -4
  30. package/dist/runtime/aspnet-runtime-prebuild.js +94 -6
  31. package/dist/runtime/attempt-process-supervisor.d.ts +19 -0
  32. package/dist/runtime/attempt-process-supervisor.js +50 -0
  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-facts.d.ts +35 -0
  36. package/dist/runtime/host-facts.js +95 -0
  37. package/dist/runtime/host-load-admission.d.ts +64 -0
  38. package/dist/runtime/host-load-admission.js +99 -0
  39. package/dist/runtime/host-load-child-environment.d.ts +27 -0
  40. package/dist/runtime/host-load-child-environment.js +76 -0
  41. package/dist/runtime/host-load-forge-cgroups.d.ts +49 -0
  42. package/dist/runtime/host-load-forge-cgroups.js +140 -0
  43. package/dist/runtime/host-load-governor-config.d.ts +52 -0
  44. package/dist/runtime/host-load-governor-config.js +83 -0
  45. package/dist/runtime/host-load-governor.d.ts +184 -0
  46. package/dist/runtime/host-load-governor.js +632 -0
  47. package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
  48. package/dist/runtime/host-load-ledger-lock.js +185 -0
  49. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  50. package/dist/runtime/host-load-runtime-settings.js +78 -0
  51. package/dist/runtime/host-load-sampler.d.ts +126 -0
  52. package/dist/runtime/host-load-sampler.js +232 -0
  53. package/dist/runtime/host-load-step-class.d.ts +70 -0
  54. package/dist/runtime/host-load-step-class.js +161 -0
  55. package/dist/runtime/host-load-step-reaper.d.ts +27 -0
  56. package/dist/runtime/host-load-step-reaper.js +95 -0
  57. package/dist/runtime/host-load-step-run.d.ts +73 -0
  58. package/dist/runtime/host-load-step-run.js +102 -0
  59. package/dist/runtime/host-load-test-slot.d.ts +43 -0
  60. package/dist/runtime/host-load-test-slot.js +81 -0
  61. package/dist/runtime/host-load-token-ledger.d.ts +200 -0
  62. package/dist/runtime/host-load-token-ledger.js +453 -0
  63. package/dist/runtime/host-pressure-stall.d.ts +61 -0
  64. package/dist/runtime/host-pressure-stall.js +168 -0
  65. package/dist/runtime/host-runtime-contract.d.ts +4 -0
  66. package/dist/runtime/host-runtime-contract.js +6 -1
  67. package/dist/runtime/host-runtime-lease.d.ts +74 -4
  68. package/dist/runtime/host-runtime-lease.js +336 -20
  69. package/dist/runtime/host-runtime-promotion.d.ts +23 -0
  70. package/dist/runtime/host-runtime-promotion.js +48 -0
  71. package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
  72. package/dist/runtime/host-runtime-requirements-check.js +29 -0
  73. package/dist/runtime/host-runtime-requirements.d.ts +36 -0
  74. package/dist/runtime/host-runtime-requirements.js +117 -0
  75. package/dist/runtime/managed-command-teardown.d.ts +62 -0
  76. package/dist/runtime/managed-command-teardown.js +607 -0
  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 +113 -0
  84. package/dist/sandbox/host-capacity-broker.js +334 -0
  85. package/dist/sandbox/runtime.d.ts +10 -1
  86. package/dist/sandbox/runtime.js +45 -2
  87. package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
  88. package/dist/sandbox/sandbox-cgroups.js +42 -0
  89. package/dist/session/managed-attempt-tools.d.ts +27 -0
  90. package/dist/session/managed-attempt-tools.js +356 -41
  91. package/dist/session/managed-build-coordinator.d.ts +1 -1
  92. package/dist/session/managed-build-coordinator.js +4 -1
  93. package/dist/session/managed-command-host-load.d.ts +47 -0
  94. package/dist/session/managed-command-host-load.js +83 -0
  95. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  96. package/dist/session/mcp-argument-coercion.js +121 -0
  97. package/dist/session/phase-completion.artifacts.d.ts +7 -0
  98. package/dist/session/phase-completion.artifacts.js +98 -25
  99. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  100. package/dist/session/phase-completion.command-validation.js +77 -0
  101. package/dist/session/phase-completion.d.ts +4 -0
  102. package/dist/session/phase-completion.helpers.js +13 -12
  103. package/dist/session/phase-completion.js +4 -0
  104. package/dist/session/phase-completion.prompts.js +6 -1
  105. package/dist/session/phase-completion.runtime.d.ts +5 -3
  106. package/dist/session/phase-completion.runtime.js +70 -35
  107. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  108. package/dist/session/phase-completion.schema-parts.js +188 -0
  109. package/dist/session/phase-completion.schemas.d.ts +3 -3
  110. package/dist/session/phase-completion.schemas.js +206 -221
  111. package/dist/session/phase-completion.validation.d.ts +2 -3
  112. package/dist/session/phase-completion.validation.js +46 -92
  113. package/dist/session/pre-publication-host-load.d.ts +27 -0
  114. package/dist/session/pre-publication-host-load.js +111 -0
  115. package/dist/session/pre-publication-pass.d.ts +60 -0
  116. package/dist/session/pre-publication-pass.js +145 -0
  117. package/dist/session/pre-publication-process.d.ts +23 -0
  118. package/dist/session/pre-publication-process.js +109 -0
  119. package/dist/session/pre-publication-skipped-tests.d.ts +21 -0
  120. package/dist/session/pre-publication-skipped-tests.js +109 -0
  121. package/dist/session/pre-publication-step-execution.d.ts +11 -0
  122. package/dist/session/pre-publication-step-execution.js +49 -0
  123. package/dist/session/pre-publication-validation.d.ts +30 -20
  124. package/dist/session/pre-publication-validation.js +173 -192
  125. package/dist/session/provider-cli/claude-background-work.d.ts +66 -0
  126. package/dist/session/provider-cli/claude-background-work.js +180 -0
  127. package/dist/session/provider-cli/pre-publication-repair.d.ts +40 -0
  128. package/dist/session/provider-cli/pre-publication-repair.js +243 -0
  129. package/dist/session/provider-cli/provider-cli.artifacts.d.ts +2 -1
  130. package/dist/session/provider-cli/provider-cli.artifacts.js +21 -15
  131. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
  132. package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
  133. package/dist/session/provider-cli/provider-cli.process.d.ts +39 -2
  134. package/dist/session/provider-cli/provider-cli.process.js +276 -42
  135. package/dist/session/provider-cli/provider-cli.prompts.d.ts +7 -0
  136. package/dist/session/provider-cli/provider-cli.prompts.js +65 -10
  137. package/dist/session/provider-cli/provider-cli.runtime.js +7 -0
  138. package/dist/session/provider-cli/provider-cli.service.d.ts +4 -1
  139. package/dist/session/provider-cli/provider-cli.service.js +203 -172
  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 +10 -0
  142. package/dist/session/provider-cli/provider-in-flight-work.js +92 -0
  143. package/dist/session/provider-cli/provider-output-state.d.ts +8 -0
  144. package/dist/session/provider-cli/provider-output-state.js +15 -0
  145. package/dist/session/publishable-worktree-changes.d.ts +54 -0
  146. package/dist/session/publishable-worktree-changes.js +193 -0
  147. package/dist/session/sandbox-host-capacity-gate.d.ts +30 -0
  148. package/dist/session/sandbox-host-capacity-gate.js +231 -0
  149. package/dist/session/session.base.d.ts +9 -1
  150. package/dist/session/session.service.d.ts +9 -2
  151. package/dist/session/session.service.js +120 -5
  152. package/dist/session/session.types.d.ts +3 -0
  153. package/dist/session/session.types.js +15 -3
  154. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  155. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  156. package/dist/shared/process/host-process-supervisor.d.ts +1 -0
  157. package/dist/shared/process/host-process-supervisor.js +1 -1
  158. package/dist/shared/process/process-tree.d.ts +52 -0
  159. package/dist/shared/process/process-tree.js +144 -0
  160. package/dist/shared/process/process.d.ts +67 -0
  161. package/dist/shared/process/process.js +213 -11
  162. package/dist/shared/provider-capabilities.js +5 -6
  163. package/dist/version.d.ts +1 -1
  164. package/dist/version.js +1 -1
  165. package/dist/worktree/dependency-warmer.d.ts +25 -0
  166. package/dist/worktree/dependency-warmer.js +46 -10
  167. package/dist/worktree/worktree.service.d.ts +10 -1
  168. package/dist/worktree/worktree.service.js +42 -2
  169. package/dist/worktree/worktree.types.d.ts +7 -0
  170. package/package.json +2 -2
@@ -1,16 +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";
6
4
  import { attemptDatabaseCapabilityEnvironment, attemptDatabaseCapabilitySecrets, } from "../runtime/attempt-database-broker.js";
7
5
  import { assertHostDatabaseCapabilityBoundary } from "../runtime/host-database-capability-boundary.js";
8
- import { nativeTestPostgresFallbackEnvironment, parseNativeTestPostgresFallback, } from "../runtime/native-test-postgres-fallback.js";
9
- 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";
10
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";
11
13
  import { findUnreferencedNewExports } from "./unreferenced-exports.js";
12
14
  import { ForgeFailureError, sanitizeFailureError, } from "./session.types.js";
13
- const execFileAsync = promisify(execFile);
14
15
  const contractRelativePath = ".forge/validation/ci-parity.v1.json";
15
16
  const requiredCheckIds = new Set([
16
17
  "file-size-inventory",
@@ -47,23 +48,31 @@ const approvedContractDigests = new Set([
47
48
  ...compatibleApprovedContractDigests,
48
49
  ]);
49
50
  const ansiColorSequence = new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*m`, "gu");
50
- export class PrePublicationValidationError extends ForgeFailureError {
51
- checkId;
52
- exitCode;
53
- command;
54
- args;
55
- detail;
56
- code = "prepublication_validation_failed";
57
- constructor(checkId, exitCode, command, args, detail) {
58
- super("prepublication_validation_failed", `prepublication_validation_failed: ${checkId} exited ${exitCode}${detail ? `: ${detail}` : ""}`, "bridge");
59
- this.checkId = checkId;
60
- this.exitCode = exitCode;
61
- this.command = command;
62
- this.args = args;
63
- this.detail = detail;
64
- this.name = "PrePublicationValidationError";
65
- }
66
- }
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 };
67
76
  export class PrePublicationInfrastructureError extends ForgeFailureError {
68
77
  checkId;
69
78
  exitCode;
@@ -81,157 +90,166 @@ export class PrePublicationInfrastructureError extends ForgeFailureError {
81
90
  this.name = "PrePublicationInfrastructureError";
82
91
  }
83
92
  }
84
- class ProcessPrePublicationCommandRunner {
85
- async run(command, args, cwd, signal, environment) {
86
- try {
87
- const windowsBatch = process.platform === "win32" && (command === "npm" || command === "pnpm");
88
- const executable = windowsBatch ? (process.env.ComSpec ?? "cmd.exe") : command;
89
- const commandArgs = windowsBatch
90
- ? ["/d", "/s", "/c", [`${command}.cmd`, ...args].map(quoteWindowsCommandArgument).join(" ")]
91
- : [...args];
92
- const result = await execFileAsync(executable, commandArgs, {
93
- cwd,
94
- encoding: "utf8",
95
- maxBuffer: 4 * 1024 * 1024,
96
- signal,
97
- env: prePublicationChildEnvironment(environment),
98
- });
99
- return { exitCode: 0, stdout: result.stdout, stderr: result.stderr };
100
- }
101
- catch (error) {
102
- const failure = error;
103
- if (failure.name === "AbortError")
104
- throw error;
105
- if (failure.code === "ENOENT") {
106
- return { exitCode: 127, stderr: `executable_not_found: ${command}` };
107
- }
108
- return {
109
- exitCode: typeof failure.code === "number" ? failure.code : 1,
110
- stdout: failure.stdout,
111
- stderr: failure.stderr ?? failure.message,
112
- };
113
- }
114
- }
115
- }
116
- function quoteWindowsCommandArgument(value) {
117
- return /^[A-Za-z0-9_./:@=-]+$/u.test(value) ? value : `"${value.replaceAll('"', '""')}"`;
118
- }
119
- function prePublicationChildEnvironment(environment) {
120
- const child = {};
121
- const privilegedNames = new Set([
122
- hostRuntimeTestPostgresAdminEnvironment.toLowerCase(),
123
- hostRuntimeLegacyTestPostgresEnvironment.toLowerCase(),
124
- ]);
125
- for (const [name, value] of Object.entries(process.env)) {
126
- if (typeof value === "string" && !privilegedNames.has(name.toLowerCase())) {
127
- child[name] = value;
128
- }
129
- }
130
- return { ...child, ...environment };
131
- }
132
93
  export class PrePublicationValidator {
133
94
  commands;
134
95
  dockerEngineProbe;
135
96
  nativeTestPostgresFallback;
136
- constructor(commands = new ProcessPrePublicationCommandRunner(), dockerEngineProbe, nativeTestPostgresFallback = () => null) {
97
+ hostLoad;
98
+ constructor(commands = new ProcessPrePublicationCommandRunner(), dockerEngineProbe, nativeTestPostgresFallback = () => null, hostLoad) {
137
99
  this.commands = commands;
138
100
  this.dockerEngineProbe = dockerEngineProbe;
139
101
  this.nativeTestPostgresFallback = nativeTestPostgresFallback;
102
+ this.hostLoad = hostLoad;
140
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
+ */
141
109
  async validate(worktreePath, profile, capabilities, emit, signal, execution) {
142
110
  const checksExports = profile === "implementation" || profile === "comment_repair";
111
+ const pass = new PrePublicationPass(execution?.runtimeRestartFailure);
143
112
  const contract = await loadValidationContract(worktreePath);
144
113
  if (contract === null) {
145
114
  await emit?.(validationEvent("prepublication_validation_legacy_contract", "legacy-provider-validation", `This checkout predates ${contractRelativePath}; Bridge preserved legacy provider validation without source mutation.`));
146
115
  if (checksExports) {
147
116
  const legacy = await prepareValidationExecution(execution);
148
117
  try {
149
- await this.assertNoTestOnlyExports(worktreePath, emit, signal, legacy.execution);
118
+ await this.checkTestOnlyExports(pass, worktreePath, emit, signal, legacy.execution);
150
119
  }
151
120
  finally {
152
121
  await legacy.cleanup();
153
122
  }
154
123
  }
124
+ pass.throwIfFailed();
155
125
  return [];
156
126
  }
157
127
  const scoped = await prepareValidationExecution(execution);
158
128
  try {
159
129
  if (checksExports)
160
- await this.assertNoTestOnlyExports(worktreePath, emit, signal, scoped.execution);
130
+ await this.checkTestOnlyExports(pass, worktreePath, emit, signal, scoped.execution);
161
131
  const contractDigest = validationContractDigest(contract);
162
132
  await this.assertContractMatchesDispatchBaseline(worktreePath, contractDigest, signal, scoped.execution);
163
133
  if (contractDigest !== currentApprovedContractDigest) {
164
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}.`));
165
135
  }
166
136
  const changedPaths = await this.changedPaths(worktreePath, signal, scoped.execution);
167
- const selected = applicableChecks(contract, profile, changedPaths);
168
- const completed = [];
169
- for (const check of selected) {
170
- if (check.providerOnly) {
171
- await emit?.(validationEvent("prepublication_validation_provider_only", check.id, `Preserved provider-only validation '${check.id}' for the provider check run.`));
172
- continue;
173
- }
174
- if (check.requiredCapability && !capabilities.has(check.requiredCapability)) {
175
- throw new ForgeFailureError("prepublication_capability_unavailable", `prepublication_capability_unavailable: ${check.id} requires ${check.requiredCapability}; publication is holding until a capable runner is available.`, "bridge");
176
- }
177
- const postgresAdminConnection = await this.ensurePrerequisite(check, scoped.execution?.environment, scoped.postgresAdminConnection, emit) ?? scoped.postgresAdminConnection;
178
- await emit?.(validationEvent("prepublication_validation_started", check.id, `Running pre-publication CI parity check '${check.id}'.`));
179
- for (const step of check.steps) {
180
- let result = await this.runStep(check.id, step, worktreePath, signal, scoped.execution, postgresAdminConnection);
181
- await this.throwIfPrerequisiteWasLost(check, result, scoped.execution?.environment, postgresAdminConnection, emit);
182
- if (isTimeoutOnlyClientTestFailure(check.id, step, result)) {
183
- 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."));
184
- result = await this.runStep(check.id, step, worktreePath, signal, scoped.execution, postgresAdminConnection);
185
- await this.throwIfPrerequisiteWasLost(check, result, scoped.execution?.environment, postgresAdminConnection, emit);
186
- await emit?.(validationEvent(result.exitCode === 0
187
- ? "prepublication_validation_timeout_confirmation_passed"
188
- : "prepublication_validation_timeout_confirmation_failed", check.id, result.exitCode === 0
189
- ? "The complete client test step passed on its single timeout confirmation run."
190
- : `The complete client test step failed on its single timeout confirmation run (exit ${result.exitCode}).`));
191
- }
192
- if (isTransientBridgeCleanupFailure(check.id, step, result)) {
193
- 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."));
194
- result = await this.runStep(check.id, step, worktreePath, signal, scoped.execution, postgresAdminConnection);
195
- await this.throwIfPrerequisiteWasLost(check, result, scoped.execution?.environment, postgresAdminConnection, emit);
196
- await emit?.(validationEvent(result.exitCode === 0
197
- ? "prepublication_validation_cleanup_confirmation_passed"
198
- : "prepublication_validation_cleanup_confirmation_failed", check.id, result.exitCode === 0
199
- ? "The complete Bridge test step passed on its single cleanup confirmation run."
200
- : `The complete Bridge test step failed on its single cleanup confirmation run (exit ${result.exitCode}).`));
201
- }
202
- if (isTransientShellInfrastructureFailure(result)) {
203
- 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."));
204
- result = await this.runStep(check.id, step, worktreePath, signal, scoped.execution, postgresAdminConnection);
205
- await this.throwIfPrerequisiteWasLost(check, result, scoped.execution?.environment, postgresAdminConnection, emit);
206
- const infrastructureFailed = isTransientShellInfrastructureFailure(result);
207
- await emit?.(validationEvent(infrastructureFailed
208
- ? "prepublication_infrastructure_confirmation_failed"
209
- : "prepublication_infrastructure_confirmation_passed", check.id, infrastructureFailed
210
- ? `The validation shell failed again on its single infrastructure confirmation run (exit ${result.exitCode}).`
211
- : result.exitCode === 0
212
- ? "The validation step recovered on its single infrastructure confirmation run."
213
- : "The host-runtime failure did not recur; continuing with normal validation failure handling."));
214
- if (infrastructureFailed) {
215
- const detail = diagnosticDetail(result);
216
- await emit?.(validationEvent("prepublication_infrastructure_failed", check.id, `Pre-publication infrastructure for '${check.id}' remained unavailable${detail ? `: ${detail}` : "."}`));
217
- throw new PrePublicationInfrastructureError(check.id, result.exitCode, result.command, result.args, detail);
218
- }
219
- }
220
- if (result.exitCode !== 0) {
221
- const detail = diagnosticDetail(result);
222
- await emit?.(validationEvent("prepublication_validation_failed", check.id, `Pre-publication CI parity check '${check.id}' exited ${result.exitCode}${detail ? `: ${detail}` : "."}`));
223
- throw new PrePublicationValidationError(check.id, result.exitCode, result.command, result.args, detail);
224
- }
225
- }
226
- completed.push(check.id);
227
- await emit?.(validationEvent("prepublication_validation_passed", check.id, `Pre-publication CI parity check '${check.id}' passed.`));
228
- }
229
- 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);
230
146
  }
231
147
  finally {
232
148
  await scoped.cleanup();
233
149
  }
234
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
+ }
235
253
  /** Returns the native fallback connection when this check must use it instead of Docker. */
236
254
  async ensurePrerequisite(check, environment, postgresAdminConnection, emit) {
237
255
  if (check.requiredPrerequisite === "isolated_postgres"
@@ -252,7 +270,7 @@ export class PrePublicationValidator {
252
270
  const snapshot = await this.dockerEngineProbe.ensureAvailableForRequiredWork();
253
271
  if (!snapshot.available) {
254
272
  const detail = `Docker prerequisite unavailable (${snapshot.unavailableCode ?? "docker_engine_unavailable"}): ${snapshot.unavailableReason ?? "the daemon did not pass a fresh readiness probe"}`;
255
- const fallback = check.requiredPrerequisite === "isolated_postgres" && supportsNativeTestPostgresFallback(check)
273
+ const fallback = check.requiredPrerequisite === "isolated_postgres" && supportsNativeTestPostgresFallback(check.id)
256
274
  ? this.nativeTestPostgresFallback()
257
275
  : null;
258
276
  if (fallback) {
@@ -280,7 +298,8 @@ export class PrePublicationValidator {
280
298
  throw new PrePublicationInfrastructureError(check.id, result.exitCode, result.command, result.args, detail);
281
299
  }
282
300
  // Runs for every target repository, with or without a CI parity contract: it only reads the worktree.
283
- 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) {
284
303
  const found = await findUnreferencedNewExports(args => this.runCommand("git", args, worktreePath, signal, execution), worktreePath, execution?.baselineRevision);
285
304
  const unused = found.filter(row => !row.testOnly);
286
305
  if (unused.length > 0) {
@@ -291,7 +310,7 @@ export class PrePublicationValidator {
291
310
  return;
292
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.`;
293
312
  await emit?.(validationEvent("prepublication_validation_failed", "unreferenced-exports", `New code is tested but never called: ${detail}`));
294
- throw new PrePublicationValidationError("unreferenced-exports", 1, "git", ["grep"], detail);
313
+ pass.record({ checkId: "unreferenced-exports", exitCode: 1, command: "git", args: ["grep"], detail });
295
314
  }
296
315
  async changedPaths(worktreePath, signal, execution) {
297
316
  const baselineRevision = execution?.baselineRevision?.trim();
@@ -338,8 +357,14 @@ export class PrePublicationValidator {
338
357
  throw new ForgeFailureError("prepublication_contract_invalid", `prepublication_contract_invalid: the CI parity contract changed after dispatch (baseline ${baselineDigest}, worktree ${contractDigest}).`, "bridge");
339
358
  }
340
359
  }
341
- async runStep(checkId, step, cwd, signal, execution, postgresAdminConnection) {
360
+ async runStep(checkId, step, cwd, signal, execution, postgresAdminConnection, emit) {
342
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) {
343
368
  const stepExecution = validationExecutionForStep(checkId, step, execution, postgresAdminConnection);
344
369
  const before = await readValidationFiles(cwd, step.assertUnchangedPaths ?? []);
345
370
  const result = await this.runCommand(invocation.command, invocation.args, cwd, signal, stepExecution);
@@ -361,10 +386,11 @@ export class PrePublicationValidator {
361
386
  const exactSecrets = validationExactSecrets(execution?.environment);
362
387
  try {
363
388
  if (execution?.processRunner) {
389
+ const launch = await pnpmDirectoryLaunch(command, args, cwd);
364
390
  const result = await execution.processRunner.run({
365
391
  command,
366
- args,
367
- cwd,
392
+ args: launch.args,
393
+ cwd: launch.cwd,
368
394
  env: execution.environment,
369
395
  captureOutput: true,
370
396
  failureRedactionValues: exactSecrets,
@@ -383,57 +409,13 @@ export class PrePublicationValidator {
383
409
  };
384
410
  }
385
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;
386
415
  throw sanitizeFailureError(error, exactSecrets);
387
416
  }
388
417
  }
389
418
  }
390
- function managedAttemptInvocation(checkId, step, environment) {
391
- const playwrightConfig = environment?.FORGE_PLAYWRIGHT_CONFIG?.trim();
392
- const attemptOwned = environment?.FORGE_E2E_OWNERSHIP_MODE === "attempt"
393
- || Boolean(environment?.FORGE_DISPATCH_ATTEMPT_ID?.trim());
394
- if (checkId !== "playwright-e2e" || !attemptOwned) {
395
- return step;
396
- }
397
- if (!playwrightConfig) {
398
- throw new ForgeFailureError("prepublication_capability_unavailable", "prepublication_capability_unavailable: playwright-e2e requires the Bridge-generated FORGE_PLAYWRIGHT_CONFIG for a managed attempt.", "bridge");
399
- }
400
- return {
401
- command: "pnpm",
402
- args: ["--dir", "tests/e2e", "exec", "playwright", "test", "--config", playwrightConfig],
403
- };
404
- }
405
- const nativeFallbackCheckIds = new Set([
406
- "owned-suite-registration",
407
- "dotnet-build-and-unit",
408
- "comment-repair-dotnet-regression",
409
- ]);
410
- const nativeFallbackDotnetTierScripts = [
411
- "scripts/run-dotnet-test-tier.ps1",
412
- "scripts/run-dotnet-test-tier-set.ps1",
413
- "scripts/run-affected-dotnet-tests.mjs",
414
- ];
415
- function supportsNativeTestPostgresFallback(check) {
416
- return nativeFallbackCheckIds.has(check.id);
417
- }
418
- function validationExecutionForStep(checkId, step, execution, postgresAdminConnection) {
419
- // The connection only exists when Docker is unavailable and the operator
420
- // provisioned a dedicated native test cluster. Only the runner-authored
421
- // .NET test tiers and the suite-identity check receive it; build, client,
422
- // Bridge, and E2E steps never do.
423
- if (!postgresAdminConnection || !nativeFallbackCheckIds.has(checkId))
424
- return execution;
425
- const runsDotnetTier = step.args.some(argument => nativeFallbackDotnetTierScripts
426
- .some(script => argument.replaceAll("\\", "/").endsWith(script)));
427
- if (checkId !== "owned-suite-registration" && !runsDotnetTier)
428
- return execution;
429
- return {
430
- ...execution,
431
- environment: {
432
- ...execution?.environment,
433
- ...nativeTestPostgresFallbackEnvironment(parseNativeTestPostgresFallback(postgresAdminConnection)),
434
- },
435
- };
436
- }
437
419
  function environmentValue(environment, name) {
438
420
  return Object.prototype.hasOwnProperty.call(environment ?? {}, name)
439
421
  ? environment?.[name]?.trim() ?? ""
@@ -455,6 +437,7 @@ function validationExactSecrets(environment) {
455
437
  return [
456
438
  environment?.[hostRuntimeTestPostgresAdminEnvironment]?.trim() ?? "",
457
439
  environment?.[hostRuntimeLegacyTestPostgresEnvironment]?.trim() ?? "",
440
+ environment?.[hostRuntimeTestPostgresProvisionerEnvironment]?.trim() ?? "",
458
441
  ...attemptDatabaseCapabilitySecrets(environment?.[attemptDatabaseCapabilityEnvironment]),
459
442
  ].filter((value, index, values) => value.length > 0 && values.indexOf(value) === index);
460
443
  }
@@ -587,6 +570,7 @@ function withoutPrivilegedPostgresEnvironment(environment) {
587
570
  const privilegedNames = new Set([
588
571
  hostRuntimeTestPostgresAdminEnvironment.toLowerCase(),
589
572
  hostRuntimeLegacyTestPostgresEnvironment.toLowerCase(),
573
+ hostRuntimeTestPostgresProvisionerEnvironment.toLowerCase(),
590
574
  ]);
591
575
  return Object.fromEntries(Object.entries(environment)
592
576
  .filter(([name]) => !privilegedNames.has(name.toLowerCase())));
@@ -656,6 +640,3 @@ function canonicalizeJson(value) {
656
640
  }
657
641
  return value;
658
642
  }
659
- function validationEvent(eventType, checkId, content) {
660
- return { role: "runner", kind: "checkpoint", content, eventType, data: JSON.stringify({ checkId, contractId: "forge-ci-parity-v1" }) };
661
- }
@@ -0,0 +1,66 @@
1
+ import { ForgeFailureError } from "../session.types.js";
2
+ import type { ProviderProcessHandlers, ProviderProcessRunner, ProviderProcessRunRequest, ProviderProcessRunResult } from "./provider-cli.process.js";
3
+ /**
4
+ * Removes the `run_in_background` parameter from Bash, PowerShell and the Agent tool, runs
5
+ * forked subagents and forked skills in the foreground, and stops Claude Code from moving long
6
+ * shell commands, subagents and MCP calls to the background on its own. Cron disables the
7
+ * session-scoped scheduled tasks (`CronCreate`, `/loop`). Applied last, so a project's runtime
8
+ * environment cannot turn them back on.
9
+ */
10
+ export declare const claudeHeadlessEnvironment: Readonly<Record<string, string>>;
11
+ /**
12
+ * Tools whose only purpose is work that reports after the turn. `CLAUDE_CODE_DISABLE_BACKGROUND_TASKS`
13
+ * leaves Monitor running in the background, so it is removed here, together with self-paced
14
+ * wakeups, workflows (which run their agents in the background), cloud routines, cron
15
+ * (also disabled by environment), SendMessage, which resumes an earlier subagent in the
16
+ * background, and agent teams, whose teammates run alongside the turn. Foreground subagents
17
+ * stay available: they block the turn until they finish.
18
+ */
19
+ export declare const claudeHeadlessDisallowedTools: readonly string[];
20
+ /**
21
+ * The Claude Code arguments that apply the restrictions: the tool deny list, and the environment
22
+ * again as flag settings, which outrank a user's or repository's settings `env` block.
23
+ */
24
+ export declare function claudeHeadlessToolArgs(): readonly string[];
25
+ /**
26
+ * The provider ended its turn while background work it started (a background subagent or
27
+ * shell, a Monitor watch, a wakeup) was still live. Claude Code withholds the turn's terminal
28
+ * result for such work, and nothing started in the background reports to Forge, so Forge stops
29
+ * the provider at once instead of waiting for an idle watchdog. Retryable: the harness, not the
30
+ * task, ended the run.
31
+ */
32
+ export declare function providerTurnEndedWithBackgroundWorkFailure(message: string): ForgeFailureError;
33
+ /**
34
+ * Fails every provider run Forge stopped because its turn ended with background work still live,
35
+ * whether or not the turn recorded a completion first: the stop cut that work short, so nothing
36
+ * may validate, commit or publish the worktree it left behind.
37
+ */
38
+ export declare class BackgroundWorkStopFailingRunner implements ProviderProcessRunner {
39
+ private readonly inner;
40
+ constructor(inner: ProviderProcessRunner);
41
+ run(request: ProviderProcessRunRequest, handlers?: ProviderProcessHandlers, signal?: AbortSignal): Promise<ProviderProcessRunResult>;
42
+ }
43
+ /**
44
+ * Recognizes a main-conversation turn that ended while background tasks it started were still
45
+ * live, the case in which Claude Code withholds the turn's `result`. The turn end is Claude
46
+ * Code's `post_turn_summary` event; the live set is the documented `background_tasks_changed`
47
+ * event (Claude Code's own `ambient` tasks and `awaited` ones do not count). After `graceMs`
48
+ * without the result or new main-conversation activity, it calls `onTurnEndedWithBackgroundWork`
49
+ * once, so the runner can stop the provider instead of waiting on work no one will collect.
50
+ */
51
+ export declare class ClaudeBackgroundTurnEndWatch {
52
+ private readonly graceMs;
53
+ private readonly onTurnEndedWithBackgroundWork;
54
+ private liveBackgroundTasks;
55
+ private terminalSinceMainActivity;
56
+ private mainTurnEnded;
57
+ private timer;
58
+ private stopped;
59
+ private readonly enabled;
60
+ /** Watches only Claude Code, by its executable `command`; other output is left alone. */
61
+ constructor(command: string, graceMs: number, onTurnEndedWithBackgroundWork: () => void);
62
+ consume(line: string): void;
63
+ stop(): void;
64
+ private armIfTurnEndedWithBackgroundWork;
65
+ private cancel;
66
+ }