@loucompanion/forge-bridge 0.1.4-dev.e1b4f55fb18d → 0.1.4-dev.e3697e9f5c98

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 (53) hide show
  1. package/README.md +42 -0
  2. package/dist/bridge/bridge.base.d.ts +9 -0
  3. package/dist/bridge/bridge.service.d.ts +70 -1
  4. package/dist/bridge/bridge.service.js +278 -4
  5. package/dist/bridge/bridge.types.d.ts +11 -0
  6. package/dist/bridge/local-yield-flag.d.ts +6 -0
  7. package/dist/bridge/local-yield-flag.js +34 -0
  8. package/dist/cleanup/cleanup.service.js +15 -9
  9. package/dist/cleanup/forge-owned-paths.d.ts +9 -0
  10. package/dist/cleanup/forge-owned-paths.js +53 -0
  11. package/dist/cli/cli.help.js +18 -0
  12. package/dist/cli/cli.service.d.ts +16 -0
  13. package/dist/cli/cli.service.js +132 -14
  14. package/dist/cli/local-config.d.ts +4 -0
  15. package/dist/cli/local-config.js +26 -4
  16. package/dist/runtime/aspnet-runtime-prebuild.js +94 -6
  17. package/dist/runtime/host-load-admission.d.ts +9 -1
  18. package/dist/runtime/host-load-admission.js +19 -4
  19. package/dist/runtime/host-load-child-environment.js +3 -1
  20. package/dist/runtime/host-load-governor-config.d.ts +9 -0
  21. package/dist/runtime/host-load-governor-config.js +30 -0
  22. package/dist/runtime/host-load-governor.d.ts +2 -0
  23. package/dist/runtime/host-load-governor.js +23 -1
  24. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  25. package/dist/runtime/host-load-runtime-settings.js +78 -0
  26. package/dist/runtime/host-runtime-lease.d.ts +58 -2
  27. package/dist/runtime/host-runtime-lease.js +198 -7
  28. package/dist/runtime/host-runtime-promotion.d.ts +23 -0
  29. package/dist/runtime/host-runtime-promotion.js +36 -0
  30. package/dist/runtime/playwright-host-runtime-adapter.d.ts +7 -0
  31. package/dist/runtime/playwright-host-runtime-adapter.js +13 -1
  32. package/dist/runtime/runner-settings.d.ts +100 -0
  33. package/dist/runtime/runner-settings.js +214 -0
  34. package/dist/session/pre-publication-pass.d.ts +60 -0
  35. package/dist/session/pre-publication-pass.js +145 -0
  36. package/dist/session/pre-publication-validation.d.ts +21 -11
  37. package/dist/session/pre-publication-validation.js +149 -104
  38. package/dist/session/provider-cli/pre-publication-repair.d.ts +40 -0
  39. package/dist/session/provider-cli/pre-publication-repair.js +243 -0
  40. package/dist/session/provider-cli/provider-cli.prompts.js +4 -1
  41. package/dist/session/provider-cli/provider-cli.service.d.ts +4 -1
  42. package/dist/session/provider-cli/provider-cli.service.js +72 -143
  43. package/dist/session/provider-cli/provider-cli.types.d.ts +26 -0
  44. package/dist/session/session.base.d.ts +6 -1
  45. package/dist/session/session.service.d.ts +7 -2
  46. package/dist/session/session.service.js +100 -2
  47. package/dist/session/session.types.js +2 -2
  48. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  49. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  50. package/dist/shared/provider-capabilities.js +5 -6
  51. package/dist/version.d.ts +1 -1
  52. package/dist/version.js +1 -1
  53. package/package.json +2 -2
@@ -7,7 +7,7 @@ import { runHostGovernedValidationStep } from "./pre-publication-host-load.js";
7
7
  import { managedAttemptInvocation, supportsNativeTestPostgresFallback, validationExecutionForStep, } from "./pre-publication-step-execution.js";
8
8
  import { hostRuntimeLegacyTestPostgresEnvironment, hostRuntimeTestPostgresAdminEnvironment, hostRuntimeTestPostgresProvisionerEnvironment, } from "../runtime/host-runtime-contract.js";
9
9
  import { redactText } from "../shared/redaction/redaction.js";
10
- import { describeSkippedTests, mergeSkippedTests, readSkippedTests, } from "./pre-publication-skipped-tests.js";
10
+ import { PrePublicationPass, PrePublicationValidationError, SkippedTestTally, skippedCheckEvent, validationEvent, } from "./pre-publication-pass.js";
11
11
  import { ProcessPrePublicationCommandRunner, pnpmDirectoryLaunch } from "./pre-publication-process.js";
12
12
  import { ProcessTreeTerminationError } from "../shared/process/process.js";
13
13
  import { findUnreferencedNewExports } from "./unreferenced-exports.js";
@@ -48,23 +48,31 @@ const approvedContractDigests = new Set([
48
48
  ...compatibleApprovedContractDigests,
49
49
  ]);
50
50
  const ansiColorSequence = new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*m`, "gu");
51
- export class PrePublicationValidationError extends ForgeFailureError {
52
- checkId;
53
- exitCode;
54
- command;
55
- args;
56
- detail;
57
- code = "prepublication_validation_failed";
58
- constructor(checkId, exitCode, command, args, detail) {
59
- super("prepublication_validation_failed", `prepublication_validation_failed: ${checkId} exited ${exitCode}${detail ? `: ${detail}` : ""}`, "bridge");
60
- this.checkId = checkId;
61
- this.exitCode = exitCode;
62
- this.command = command;
63
- this.args = args;
64
- this.detail = detail;
65
- this.name = "PrePublicationValidationError";
66
- }
67
- }
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 };
68
76
  export class PrePublicationInfrastructureError extends ForgeFailureError {
69
77
  checkId;
70
78
  exitCode;
@@ -93,110 +101,155 @@ export class PrePublicationValidator {
93
101
  this.nativeTestPostgresFallback = nativeTestPostgresFallback;
94
102
  this.hostLoad = hostLoad;
95
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
+ */
96
109
  async validate(worktreePath, profile, capabilities, emit, signal, execution) {
97
110
  const checksExports = profile === "implementation" || profile === "comment_repair";
111
+ const pass = new PrePublicationPass(execution?.runtimeRestartFailure);
98
112
  const contract = await loadValidationContract(worktreePath);
99
113
  if (contract === null) {
100
114
  await emit?.(validationEvent("prepublication_validation_legacy_contract", "legacy-provider-validation", `This checkout predates ${contractRelativePath}; Bridge preserved legacy provider validation without source mutation.`));
101
115
  if (checksExports) {
102
116
  const legacy = await prepareValidationExecution(execution);
103
117
  try {
104
- await this.assertNoTestOnlyExports(worktreePath, emit, signal, legacy.execution);
118
+ await this.checkTestOnlyExports(pass, worktreePath, emit, signal, legacy.execution);
105
119
  }
106
120
  finally {
107
121
  await legacy.cleanup();
108
122
  }
109
123
  }
124
+ pass.throwIfFailed();
110
125
  return [];
111
126
  }
112
127
  const scoped = await prepareValidationExecution(execution);
113
128
  try {
114
129
  if (checksExports)
115
- await this.assertNoTestOnlyExports(worktreePath, emit, signal, scoped.execution);
130
+ await this.checkTestOnlyExports(pass, worktreePath, emit, signal, scoped.execution);
116
131
  const contractDigest = validationContractDigest(contract);
117
132
  await this.assertContractMatchesDispatchBaseline(worktreePath, contractDigest, signal, scoped.execution);
118
133
  if (contractDigest !== currentApprovedContractDigest) {
119
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}.`));
120
135
  }
121
136
  const changedPaths = await this.changedPaths(worktreePath, signal, scoped.execution);
122
- const selected = applicableChecks(contract, profile, changedPaths);
123
- const completed = [];
124
- for (const check of selected) {
125
- if (check.providerOnly) {
126
- await emit?.(validationEvent("prepublication_validation_provider_only", check.id, `Preserved provider-only validation '${check.id}' for the provider check run.`));
127
- continue;
128
- }
129
- if (check.requiredCapability && !capabilities.has(check.requiredCapability)) {
130
- throw new ForgeFailureError("prepublication_capability_unavailable", `prepublication_capability_unavailable: ${check.id} requires ${check.requiredCapability}; publication is holding until a capable runner is available.`, "bridge");
131
- }
132
- const postgresAdminConnection = await this.ensurePrerequisite(check, scoped.execution?.environment, scoped.postgresAdminConnection, emit) ?? scoped.postgresAdminConnection;
133
- await emit?.(validationEvent("prepublication_validation_started", check.id, `Running pre-publication CI parity check '${check.id}'.`));
134
- let skipped = { count: 0, reasons: [] };
135
- for (const step of check.steps) {
136
- const stepStartedMs = Date.now() - 1000;
137
- let result = await this.runStep(check.id, step, worktreePath, signal, scoped.execution, postgresAdminConnection, emit);
138
- await this.throwIfPrerequisiteWasLost(check, result, scoped.execution?.environment, postgresAdminConnection, emit);
139
- if (isTimeoutOnlyClientTestFailure(check.id, step, result)) {
140
- 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."));
141
- result = await this.runStep(check.id, step, worktreePath, signal, scoped.execution, postgresAdminConnection, emit);
142
- await this.throwIfPrerequisiteWasLost(check, result, scoped.execution?.environment, postgresAdminConnection, emit);
143
- await emit?.(validationEvent(result.exitCode === 0
144
- ? "prepublication_validation_timeout_confirmation_passed"
145
- : "prepublication_validation_timeout_confirmation_failed", check.id, result.exitCode === 0
146
- ? "The complete client test step passed on its single timeout confirmation run."
147
- : `The complete client test step failed on its single timeout confirmation run (exit ${result.exitCode}).`));
148
- }
149
- if (isTransientBridgeCleanupFailure(check.id, step, result)) {
150
- 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."));
151
- result = await this.runStep(check.id, step, worktreePath, signal, scoped.execution, postgresAdminConnection, emit);
152
- await this.throwIfPrerequisiteWasLost(check, result, scoped.execution?.environment, postgresAdminConnection, emit);
153
- await emit?.(validationEvent(result.exitCode === 0
154
- ? "prepublication_validation_cleanup_confirmation_passed"
155
- : "prepublication_validation_cleanup_confirmation_failed", check.id, result.exitCode === 0
156
- ? "The complete Bridge test step passed on its single cleanup confirmation run."
157
- : `The complete Bridge test step failed on its single cleanup confirmation run (exit ${result.exitCode}).`));
158
- }
159
- if (isTransientShellInfrastructureFailure(result)) {
160
- 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."));
161
- result = await this.runStep(check.id, step, worktreePath, signal, scoped.execution, postgresAdminConnection, emit);
162
- await this.throwIfPrerequisiteWasLost(check, result, scoped.execution?.environment, postgresAdminConnection, emit);
163
- const infrastructureFailed = isTransientShellInfrastructureFailure(result);
164
- await emit?.(validationEvent(infrastructureFailed
165
- ? "prepublication_infrastructure_confirmation_failed"
166
- : "prepublication_infrastructure_confirmation_passed", check.id, infrastructureFailed
167
- ? `The validation shell failed again on its single infrastructure confirmation run (exit ${result.exitCode}).`
168
- : result.exitCode === 0
169
- ? "The validation step recovered on its single infrastructure confirmation run."
170
- : "The host-runtime failure did not recur; continuing with normal validation failure handling."));
171
- if (infrastructureFailed) {
172
- const detail = diagnosticDetail(result);
173
- await emit?.(validationEvent("prepublication_infrastructure_failed", check.id, `Pre-publication infrastructure for '${check.id}' remained unavailable${detail ? `: ${detail}` : "."}`));
174
- throw new PrePublicationInfrastructureError(check.id, result.exitCode, result.command, result.args, detail);
175
- }
176
- }
177
- if (result.exitCode !== 0) {
178
- const detail = diagnosticDetail(result);
179
- await emit?.(validationEvent("prepublication_validation_failed", check.id, `Pre-publication CI parity check '${check.id}' exited ${result.exitCode}${detail ? `: ${detail}` : "."}`));
180
- throw new PrePublicationValidationError(check.id, result.exitCode, result.command, result.args, detail);
181
- }
182
- // The invocation's own arguments: a managed attempt may direct results to its test-output root.
183
- skipped = mergeSkippedTests(skipped, await readSkippedTests(worktreePath, result.args, stepStartedMs, scoped.execution?.environment));
184
- }
185
- completed.push(check.id);
186
- // A pass that skipped tests says so, with each reason, instead of reading as a plain pass.
187
- const secrets = validationExactSecrets(scoped.execution?.environment);
188
- skipped = { ...skipped, reasons: skipped.reasons.map(entry => ({ ...entry, reason: redactText(entry.reason, secrets) })) };
189
- const skippedDetail = skipped.count > 0 ? describeSkippedTests(skipped) : undefined;
190
- await emit?.(validationEvent("prepublication_validation_passed", check.id, skippedDetail
191
- ? `Pre-publication CI parity check '${check.id}' passed with ${skippedDetail}.`
192
- : `Pre-publication CI parity check '${check.id}' passed.`, skipped.count > 0 ? { skippedTests: skipped.count, skippedReasons: skipped.reasons } : undefined));
193
- }
194
- 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);
195
146
  }
196
147
  finally {
197
148
  await scoped.cleanup();
198
149
  }
199
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
+ }
200
253
  /** Returns the native fallback connection when this check must use it instead of Docker. */
201
254
  async ensurePrerequisite(check, environment, postgresAdminConnection, emit) {
202
255
  if (check.requiredPrerequisite === "isolated_postgres"
@@ -245,7 +298,8 @@ export class PrePublicationValidator {
245
298
  throw new PrePublicationInfrastructureError(check.id, result.exitCode, result.command, result.args, detail);
246
299
  }
247
300
  // Runs for every target repository, with or without a CI parity contract: it only reads the worktree.
248
- 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) {
249
303
  const found = await findUnreferencedNewExports(args => this.runCommand("git", args, worktreePath, signal, execution), worktreePath, execution?.baselineRevision);
250
304
  const unused = found.filter(row => !row.testOnly);
251
305
  if (unused.length > 0) {
@@ -256,7 +310,7 @@ export class PrePublicationValidator {
256
310
  return;
257
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.`;
258
312
  await emit?.(validationEvent("prepublication_validation_failed", "unreferenced-exports", `New code is tested but never called: ${detail}`));
259
- throw new PrePublicationValidationError("unreferenced-exports", 1, "git", ["grep"], detail);
313
+ pass.record({ checkId: "unreferenced-exports", exitCode: 1, command: "git", args: ["grep"], detail });
260
314
  }
261
315
  async changedPaths(worktreePath, signal, execution) {
262
316
  const baselineRevision = execution?.baselineRevision?.trim();
@@ -586,12 +640,3 @@ function canonicalizeJson(value) {
586
640
  }
587
641
  return value;
588
642
  }
589
- function validationEvent(eventType, checkId, content, detail) {
590
- return {
591
- role: "runner",
592
- kind: "checkpoint",
593
- content,
594
- eventType,
595
- data: JSON.stringify({ checkId, contractId: "forge-ci-parity-v1", ...detail }),
596
- };
597
- }
@@ -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;
@@ -0,0 +1,243 @@
1
+ import { HostPortCollisionError } from "../../runtime/host-port-broker.js";
2
+ import { runtimeAdmissionPriority } from "../../runtime/host-runtime-lease.js";
3
+ import { runtimeRestartCheckId } from "../pre-publication-pass.js";
4
+ import { PrePublicationValidationError, } from "../pre-publication-validation.js";
5
+ import { ForgeFailureError } from "../session.types.js";
6
+ import { prePublicationValidationEnv, providerProcessEnv } from "./provider-cli.runtime.js";
7
+ import { clip } from "./provider-output-state.js";
8
+ // Pre-publication validation with bounded in-place repair: each pass restarts the attempt's runtime
9
+ // stack when the workspace changed, runs every check that can still meaningfully run, and hands all
10
+ // of the pass's failures to one resumed provider turn, up to the repair budget.
11
+ const defaultRepairTurns = 4;
12
+ const maximumRepairTurns = 10;
13
+ const repairTurnsEnvironment = "FORGE_PREPUBLICATION_REPAIR_TURNS";
14
+ // The repair prompt's diagnostics: each failed check gets an equal share of the total, between the
15
+ // floor and the ceiling (validation already clips each check's own output to the ceiling). The
16
+ // total keeps a prompt passed as a command-line argument within Windows' 32,767-character limit.
17
+ const repairPromptDetailBudget = 18_000;
18
+ const repairPromptDetailCeiling = 6000;
19
+ const repairPromptDetailFloor = 1500;
20
+ /**
21
+ * The in-place repair budget: FORGE_PREPUBLICATION_REPAIR_TURNS when it is a whole number from 1
22
+ * (capped at 10), otherwise 4.
23
+ */
24
+ export function prePublicationRepairTurnsFromEnvironment(environment = process.env) {
25
+ const configured = environment[repairTurnsEnvironment]?.trim() ?? "";
26
+ return /^\d+$/u.test(configured) && Number(configured) >= 1
27
+ ? Math.min(Number(configured), maximumRepairTurns)
28
+ : defaultRepairTurns;
29
+ }
30
+ /** The environments a pass and its repair turn use; a runtime restart assigns new ports, so all move together. */
31
+ class RepairEnvironments {
32
+ options;
33
+ repair;
34
+ constructor(options) {
35
+ this.options = options;
36
+ this.repair = options.repairEnvironment;
37
+ }
38
+ get provider() {
39
+ return providerProcessEnv(this.options.context.dispatch, this.repair);
40
+ }
41
+ get validation() {
42
+ return prePublicationValidationEnv(this.options.context.dispatch, this.repair);
43
+ }
44
+ async refresh(runtimeEnvironment) {
45
+ this.repair = this.options.onRuntimeEnvironmentRefreshed
46
+ ? await this.options.onRuntimeEnvironmentRefreshed(runtimeEnvironment)
47
+ : runtimeEnvironment;
48
+ }
49
+ /**
50
+ * The restart stopped the stack and released its ports before it failed, so the URLs the pass and
51
+ * repair turn would inherit name ports another attempt may now hold. Both run without them; the
52
+ * next pass restarts the stack and supplies fresh ones.
53
+ */
54
+ async withdrawRuntimeStack() {
55
+ await this.refresh(withoutRuntimeStack(this.repair, this.options.context.runtimeStackEnvironmentKeys ?? []));
56
+ }
57
+ }
58
+ export async function validatePrePublicationWithRepair(options, dependencies) {
59
+ const { context, outputState } = options;
60
+ const { maxRepairTurns } = dependencies;
61
+ const environments = new RepairEnvironments(options);
62
+ for (let repairTurn = 0;; repairTurn += 1) {
63
+ const failure = await runValidationPass(options, dependencies, environments, repairTurn);
64
+ if (!failure) {
65
+ if (repairTurn > 0) {
66
+ await context.emit(repairEvent("checkpoint", "prepublication_repair_completed", `Pre-publication validation passed after ${repairTurn} in-place repair turn${repairTurn === 1 ? "" : "s"}.`, { repairTurn, maxRepairTurns }));
67
+ }
68
+ return;
69
+ }
70
+ if (repairTurn >= maxRepairTurns) {
71
+ await context.emit(repairEvent("error", "prepublication_repair_exhausted", `Pre-publication validation still fails after ${maxRepairTurns} in-place repair turns: ${clip(failure.message, 4000)}`, { checkId: failure.checkId, checkIds: failure.checkIds, repairTurns: repairTurn, maxRepairTurns }));
72
+ throw failure;
73
+ }
74
+ const providerThreadId = outputState.providerThreadId?.trim();
75
+ if (!providerThreadId) {
76
+ throw new Error(`prepublication_repair_unavailable: ${failure.message}; provider did not report a resumable thread id, so Forge preserved the dirty worktree without starting a blind replacement run.`, { cause: failure });
77
+ }
78
+ const nextRepairTurn = repairTurn + 1;
79
+ await context.emit(repairEvent("checkpoint", "prepublication_repair_started", `Resuming ${context.dispatch.execution.provider} ${outputState.sessionLabel ?? "provider thread"} for bounded pre-publication repair ${nextRepairTurn}/${maxRepairTurns} after ${describeFailedChecks(failure.checkIds)} failed.`, { checkId: failure.checkId, checkIds: failure.checkIds, repairTurn: nextRepairTurn, maxRepairTurns }));
80
+ await dependencies.runRepairTurn({
81
+ prompt: buildPrePublicationRepairPrompt(failure, nextRepairTurn, maxRepairTurns, options.repairScope),
82
+ repairTurn: nextRepairTurn,
83
+ maxRepairTurns,
84
+ providerThreadId,
85
+ repairEnvironment: environments.repair,
86
+ environment: environments.provider,
87
+ failure,
88
+ });
89
+ }
90
+ }
91
+ /** Restarts the runtime stack if needed, then validates; returns every failure of the pass, or null. */
92
+ async function runValidationPass(options, dependencies, environments, repairTurn) {
93
+ const { context, validationProfile, preparedHeadSha } = options;
94
+ let runtimeRestartFailure;
95
+ try {
96
+ const refreshed = await refreshPrePublicationRuntime(context, validationProfile, repairTurn);
97
+ if (refreshed)
98
+ await environments.refresh(refreshed);
99
+ }
100
+ catch (error) {
101
+ if (!(error instanceof PrePublicationValidationError))
102
+ throw error;
103
+ // The pass still runs the checks that do not need the stack, so the repair turn sees them too.
104
+ runtimeRestartFailure = error;
105
+ await environments.withdrawRuntimeStack();
106
+ }
107
+ try {
108
+ await dependencies.validator.validate(context.worktree.worktreePath, validationProfile, publicationCapabilities(context, environments.repair), context.emit, context.signal, {
109
+ ...prePublicationExecution(context, environments.validation, dependencies.defaultProcessRunner, preparedHeadSha),
110
+ runtimeRestartFailure,
111
+ });
112
+ // The validator reports the restart failure with its own; the restart failed either way.
113
+ return runtimeRestartFailure ?? null;
114
+ }
115
+ catch (error) {
116
+ if (!(error instanceof PrePublicationValidationError))
117
+ throw error;
118
+ return runtimeRestartFailure && !error.checkIds.includes(runtimeRestartCheckId)
119
+ ? new PrePublicationValidationError(runtimeRestartFailure.checkId, runtimeRestartFailure.exitCode, runtimeRestartFailure.command, runtimeRestartFailure.args, runtimeRestartFailure.detail, error.failures)
120
+ : error;
121
+ }
122
+ }
123
+ function describeFailedChecks(checkIds) {
124
+ const quoted = checkIds.map(checkId => `'${checkId}'`);
125
+ return quoted.length <= 1
126
+ ? quoted.join("")
127
+ : `${quoted.slice(0, -1).join(", ")} and ${quoted.at(-1)}`;
128
+ }
129
+ function repairEvent(kind, eventType, content, data) {
130
+ return { role: "runner", kind, content, eventType, data: JSON.stringify(data) };
131
+ }
132
+ export function buildPrePublicationRepairPrompt(error, repairTurn, maxRepairTurns, repairScope) {
133
+ const { failures } = error;
134
+ const several = failures.length > 1;
135
+ const detailLimit = Math.min(repairPromptDetailCeiling, Math.max(repairPromptDetailFloor, Math.floor(repairPromptDetailBudget / failures.length)));
136
+ const priorWork = repairScope === "implementation"
137
+ ? "Keep the completed implementation and its Forge-owned completion artifacts intact."
138
+ : "Keep the existing PR-comment or CI repairs intact.";
139
+ const sections = failures.map((failure, index) => [
140
+ several ? `Failed check ${index + 1}/${failures.length}: ${failure.checkId}` : `Failed check: ${failure.checkId}`,
141
+ `Command: ${[failure.command, ...failure.args].join(" ")}`,
142
+ `Exit code: ${failure.exitCode}`,
143
+ "Diagnostics:",
144
+ clip(failure.detail, detailLimit) || "The validation command returned no diagnostic output.",
145
+ ].join("\n\n"));
146
+ return [
147
+ `Forge pre-publication validation failed after your ${repairScope === "implementation" ? "implementation" : "PR repair"} turn.`,
148
+ `This is bounded in-place repair turn ${repairTurn}/${maxRepairTurns}.`,
149
+ ...(several
150
+ ? [`${failures.length} checks failed in the same validation pass: ${error.checkIds.join(", ")}. Fix every one of them in this turn.`]
151
+ : []),
152
+ ...sections,
153
+ several
154
+ ? "Fix the root cause of each failed check in the current worktree and run each focused failing check."
155
+ : "Fix the root cause in the current worktree and run the focused failing check.",
156
+ `${priorWork} Do not commit, push, rebase, or modify Forge-owned protocol artifacts.`,
157
+ `When the focused check${several ? "s pass" : " passes"}, stop; Bridge will rerun the complete required pre-publication profile and owns commit/push.`,
158
+ ].join("\n\n");
159
+ }
160
+ /**
161
+ * Restarts the attempt's runtime stack when the workspace changed since it was
162
+ * launched, before a validation pass runs against it. A build of the changed
163
+ * source that fails is a validation failure the bounded repair turn can fix.
164
+ */
165
+ async function refreshPrePublicationRuntime(context, validationProfile, repairTurn) {
166
+ if (!context.refreshRuntimeEnvironment)
167
+ return null;
168
+ let refreshed;
169
+ try {
170
+ refreshed = await context.refreshRuntimeEnvironment(context.signal);
171
+ }
172
+ catch (error) {
173
+ // A restart that fails to build, start or become ready reflects the changed source, which a
174
+ // bounded repair turn can fix; the next pass restarts again. Cancellation, a released lease
175
+ // and a changed runtime contract still end the attempt.
176
+ if (restartFailureForRepair(error)) {
177
+ throw new PrePublicationValidationError(runtimeRestartCheckId, 1, "forge-host-runtime-restart", [],
178
+ // The session's host_runtime_restart_started event records why it restarted.
179
+ `Forge restarted the attempt runtime stack before validation, and the restart failed: ${error.message}`);
180
+ }
181
+ throw error;
182
+ }
183
+ if (!refreshed)
184
+ return null;
185
+ const { environment: restarted, reason, changes } = refreshed;
186
+ const apiUrl = restarted.FORGE_E2E_API_URL ?? restarted.FORGE_API_URL ?? null;
187
+ const webUrl = restarted.FORGE_E2E_WEB_URL ?? restarted.FORGE_WEB_URL ?? restarted.FORGE_PLAYWRIGHT_BASE_URL ?? null;
188
+ await context.emit(repairEvent("checkpoint", "prepublication_runtime_restarted", `Restarted the attempt runtime stack before pre-publication validation because ${restartReasonText[reason]}; validation${repairTurn > 0 ? " and repair turns" : ""} now use${apiUrl ? ` API ${apiUrl}` : " the refreshed runtime URLs"}${webUrl ? ` and web ${webUrl}` : ""}.`, { reason, changes, validationProfile, repairTurn, apiUrl, webUrl }));
189
+ return restarted;
190
+ }
191
+ const restartReasonText = {
192
+ previous_restart_incomplete: "the previous restart did not complete",
193
+ fingerprint_unavailable: "the workspace state could not be compared with the stack's",
194
+ workspace_changed: "the workspace changed since it was launched",
195
+ };
196
+ /** The environment with the runtime stack's URLs and ports withheld and the stack marked unavailable. */
197
+ function withoutRuntimeStack(environment, stackKeys) {
198
+ const remaining = { ...(environment ?? {}) };
199
+ for (const key of stackKeys)
200
+ delete remaining[key];
201
+ remaining.FORGE_RUNTIME_STACK = "unavailable";
202
+ return remaining;
203
+ }
204
+ const restartFailuresForRepair = new Set([
205
+ "host_runtime_project_start_failed",
206
+ "host_runtime_process_exited",
207
+ "host_runtime_listener_timeout",
208
+ "host_runtime_http_readiness_timeout",
209
+ "host_port_collision",
210
+ ]);
211
+ function restartFailureForRepair(error) {
212
+ if (error instanceof ForgeFailureError)
213
+ return restartFailuresForRepair.has(error.failureCode);
214
+ // The port broker throws an untyped collision once its launch retries are exhausted.
215
+ return error instanceof HostPortCollisionError;
216
+ }
217
+ function publicationCapabilities(context, runtimeEnvironment) {
218
+ const capabilities = new Set();
219
+ const launchTarget = context.dispatch.qaBrowser?.launchTarget;
220
+ if (runtimeEnvironment?.FORGE_PLAYWRIGHT_CONFIG
221
+ || launchTarget?.url
222
+ || launchTarget?.command
223
+ || launchTarget?.managed_runtime_port) {
224
+ capabilities.add("browser_launch");
225
+ }
226
+ return capabilities;
227
+ }
228
+ function prePublicationExecution(context, environment, defaultRunner, baselineRevision) {
229
+ const hostLoadOwner = {
230
+ dispatchAttemptId: context.dispatch.sandbox?.dispatchAttemptId ?? null,
231
+ priority: runtimeAdmissionPriority(context.dispatch),
232
+ };
233
+ if (context.processRunner)
234
+ return { baselineRevision, environment, processRunner: context.processRunner, hostLoadOwner };
235
+ if (context.dispatch.sandbox?.executionMode !== "docker")
236
+ return { baselineRevision, environment, hostLoadOwner };
237
+ const expectedSandboxId = context.dispatch.sandbox.dispatchAttemptId;
238
+ const observedSandboxId = context.runtimeEnvironment?.FORGE_SANDBOX_ID ?? process.env.FORGE_SANDBOX_ID;
239
+ if (observedSandboxId !== expectedSandboxId) {
240
+ throw new ForgeFailureError("prepublication_execution_scope_invalid", `prepublication_execution_scope_invalid: Docker attempt ${expectedSandboxId} has no runner proven to execute inside that sandbox.`, "bridge");
241
+ }
242
+ return { baselineRevision, environment, processRunner: defaultRunner, hostLoadOwner };
243
+ }
@@ -280,6 +280,9 @@ function buildRuntimeContextPrompt(dispatch, prompt, runtimeEnvironment) {
280
280
  const playwright = runtimeEnvironment?.FORGE_PLAYWRIGHT_CONFIG
281
281
  ? "\n- For Playwright, use the generated `FORGE_PLAYWRIGHT_CONFIG`; it targets this attempt's verified `FORGE_PLAYWRIGHT_BASE_URL`, disables project `webServer` startup/reuse, and writes under `FORGE_TEST_OUTPUT_DIR`. Do not invoke the project Playwright config directly. Run `playwright test --config <absolute value of FORGE_PLAYWRIGHT_CONFIG>` from the Playwright project directory through `forge.start_managed_command` (in Forge: command `pnpm`, args `[\"--dir\", \"tests/e2e\", \"exec\", \"playwright\", \"test\", \"--config\", \"<path>\"]`), and append spec file paths such as `specs/<name>.spec.ts` to run only the specs you are working on. Repository wrappers that start their own disposable stack, such as Forge's `pnpm --dir tests/e2e test`, refuse to run inside a managed attempt; Forge-owned pre-publication still runs the full suite."
282
282
  : "";
283
+ const stackUnavailable = runtimeEnvironment?.FORGE_RUNTIME_STACK === "unavailable"
284
+ ? "\n- `FORGE_RUNTIME_STACK=unavailable` means Forge's restart of this attempt's application stack failed, so no attempt-owned API, web, or Playwright URLs are supplied for this turn. Do not reuse URLs or ports from an earlier turn or start the stack yourself; fix the source so the restart succeeds. Forge restarts the stack and reruns validation after this turn."
285
+ : "";
283
286
  return `${prompt.trimEnd()}
284
287
 
285
288
  # Trusted Forge runtime context
@@ -292,7 +295,7 @@ ${concurrency}
292
295
  - If a tool creates \`TestResults\`, \`test-results\`, or \`playwright-report\` beneath source, use \`forge.reset_generated_outputs\` to quarantine only those untracked generated directories. Do not issue a recursive delete.
293
296
  - Use the attempt-scoped \`FORGE_TMPDIR\`, \`FORGE_LOG_DIR\`, \`FORGE_CACHE_DIR\`, \`FORGE_BROWSER_PROFILE_DIR\`, and \`FORGE_TEST_OUTPUT_DIR\` paths instead of shared host paths.
294
297
  - Use supplied \`FORGE_*\` URLs, ports, and paths. Do not search for a free port, kill a process occupying one, or reuse an existing dev server, browser profile, database, container, network, or volume.
295
- - Never run broad process or Docker cleanup. Stop only resources you created for this resource lease.${playwright}`;
298
+ - Never run broad process or Docker cleanup. Stop only resources you created for this resource lease.${playwright}${stackUnavailable}`;
296
299
  }
297
300
  return `${prompt.trimEnd()}
298
301
 
@@ -56,7 +56,8 @@ export declare class ProcessBackedProviderCliService implements ProviderCliServi
56
56
  private readonly providerToolHeartbeatIntervalMs;
57
57
  private readonly publicationCoordinator;
58
58
  private readonly prePublicationValidator;
59
- constructor(processRunner?: ProviderProcessRunner, git?: GitClient, providerToolHeartbeatIntervalMs?: number, publicationCoordinator?: WorktreeLifecycleCoordinator, prePublicationValidator?: PrePublicationValidator);
59
+ private readonly prePublicationRepairTurns;
60
+ constructor(processRunner?: ProviderProcessRunner, git?: GitClient, providerToolHeartbeatIntervalMs?: number, publicationCoordinator?: WorktreeLifecycleCoordinator, prePublicationValidator?: PrePublicationValidator, prePublicationRepairTurns?: number);
60
61
  runDraft(context: ProviderCliDraftContext): Promise<ProviderCliRunResult>;
61
62
  runImplementation(context: ProviderCliRunContext): Promise<ProviderCliRunResult>;
62
63
  runArchitect(context: ProviderCliRunContext): Promise<ProviderCliRunResult>;
@@ -67,4 +68,6 @@ export declare class ProcessBackedProviderCliService implements ProviderCliServi
67
68
  private recoverMissingQaCompletion;
68
69
  private recoverMissingCommentRepairCompletion;
69
70
  private validatePrePublicationWithRecovery;
71
+ /** Resumes the provider thread for one in-place repair turn; the turn must leave HEAD where it was. */
72
+ private runPrePublicationRepairTurn;
70
73
  }