@loucompanion/forge-bridge 0.1.4-dev.acacfdecaad2 → 0.1.4-dev.acc3b2f67cc7

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 (58) hide show
  1. package/README.md +22 -0
  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.service.d.ts +1 -1
  5. package/dist/bridge/bridge.service.js +4 -110
  6. package/dist/runtime/host-facts.d.ts +2 -1
  7. package/dist/runtime/host-load-admission.d.ts +9 -2
  8. package/dist/runtime/host-load-child-environment.d.ts +11 -6
  9. package/dist/runtime/host-load-child-environment.js +19 -10
  10. package/dist/runtime/host-load-governor-config.d.ts +10 -1
  11. package/dist/runtime/host-load-governor-config.js +7 -0
  12. package/dist/runtime/host-load-governor.d.ts +10 -0
  13. package/dist/runtime/host-load-governor.js +125 -34
  14. package/dist/runtime/host-load-sampler.d.ts +26 -3
  15. package/dist/runtime/host-load-sampler.js +61 -2
  16. package/dist/runtime/host-load-step-class.d.ts +3 -1
  17. package/dist/runtime/host-load-step-class.js +60 -5
  18. package/dist/runtime/host-load-test-slot.d.ts +43 -0
  19. package/dist/runtime/host-load-test-slot.js +81 -0
  20. package/dist/runtime/host-load-token-ledger.d.ts +26 -0
  21. package/dist/runtime/host-load-token-ledger.js +93 -61
  22. package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
  23. package/dist/runtime/host-load-windows-cpu.js +85 -0
  24. package/dist/runtime/host-runtime-lease.d.ts +2 -2
  25. package/dist/runtime/host-runtime-lease.js +9 -8
  26. package/dist/runtime/host-runtime-promotion.d.ts +23 -0
  27. package/dist/runtime/host-runtime-promotion.js +36 -0
  28. package/dist/sandbox/host-capacity-broker.d.ts +7 -1
  29. package/dist/sandbox/host-capacity-broker.js +23 -4
  30. package/dist/session/managed-attempt-tools.js +7 -8
  31. package/dist/session/managed-command-host-load.d.ts +2 -0
  32. package/dist/session/managed-command-host-load.js +2 -1
  33. package/dist/session/phase-completion.schemas.js +22 -12
  34. package/dist/session/pre-publication-pass.d.ts +61 -0
  35. package/dist/session/pre-publication-pass.js +148 -0
  36. package/dist/session/pre-publication-validation.d.ts +23 -11
  37. package/dist/session/pre-publication-validation.js +178 -107
  38. package/dist/session/provider-cli/claude-background-work.d.ts +66 -0
  39. package/dist/session/provider-cli/claude-background-work.js +180 -0
  40. package/dist/session/provider-cli/pre-publication-repair.d.ts +40 -0
  41. package/dist/session/provider-cli/pre-publication-repair.js +243 -0
  42. package/dist/session/provider-cli/provider-cli.process.d.ts +7 -6
  43. package/dist/session/provider-cli/provider-cli.process.js +14 -54
  44. package/dist/session/provider-cli/provider-cli.prompts.d.ts +2 -0
  45. package/dist/session/provider-cli/provider-cli.prompts.js +45 -8
  46. package/dist/session/provider-cli/provider-cli.runtime.js +7 -0
  47. package/dist/session/provider-cli/provider-cli.service.d.ts +4 -7
  48. package/dist/session/provider-cli/provider-cli.service.js +66 -243
  49. package/dist/session/provider-cli/provider-in-flight-work.d.ts +4 -0
  50. package/dist/session/provider-cli/provider-in-flight-work.js +45 -0
  51. package/dist/session/provider-cli/provider-output-state.d.ts +2 -0
  52. package/dist/session/provider-cli/provider-output-state.js +6 -0
  53. package/dist/session/sandbox-host-capacity-gate.js +12 -3
  54. package/dist/session/session.types.js +1 -1
  55. package/dist/shared/provider-capabilities.js +5 -6
  56. package/dist/version.d.ts +1 -1
  57. package/dist/version.js +1 -1
  58. 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";
@@ -23,16 +23,21 @@ const requiredCheckIds = new Set([
23
23
  "playwright-e2e",
24
24
  "github-provider-policy",
25
25
  ]);
26
- const currentApprovedContractDigest = "378c767c7977c850140ffb19d69db41da62d0187c37a33828d6cda8803a61c83";
26
+ // Every gate profile runs the affected .NET tests; only CI runs the whole tiers (decision 0017).
27
+ const currentApprovedContractDigest = "9cf3a3070de56f3d3bc2c013dfa45b0fd463d257722849087e6743fb9cb1fd0d";
28
+ // Only comment repair ran the affected tests; the other profiles ran Unit, Contract and
29
+ // Infrastructure whole. Story branches cut before decision 0017 still carry it.
30
+ const commentRepairOnlyAffectedContractDigest = "378c767c7977c850140ffb19d69db41da62d0187c37a33828d6cda8803a61c83";
27
31
  // Comment repair ran the whole ApiComponent and Orchestration tiers under this contract.
28
- // Story branches cut before the affected-tests contract still carry it.
29
32
  const wholeTierCommentRepairContractDigest = "024de3648c907db9c0eab13def9a4f91e81148433e0a2ba7f44776446421054a";
30
33
  // Contracts that declare the comment-repair-dotnet-regression check.
31
34
  const commentRepairRegressionContractDigests = new Set([
32
35
  currentApprovedContractDigest,
36
+ commentRepairOnlyAffectedContractDigest,
33
37
  wholeTierCommentRepairContractDigest,
34
38
  ]);
35
39
  const compatibleApprovedContractDigests = new Set([
40
+ commentRepairOnlyAffectedContractDigest,
36
41
  wholeTierCommentRepairContractDigest,
37
42
  // Preserve dispatches pinned before comment repair gained all .NET regression tiers.
38
43
  "c0014ce6abc0e0b2e66dd2bcf6cb14c47d28506444c73f87d1b76b3d1c06027b",
@@ -48,23 +53,31 @@ const approvedContractDigests = new Set([
48
53
  ...compatibleApprovedContractDigests,
49
54
  ]);
50
55
  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
- }
56
+ const timeoutConfirmation = {
57
+ started: [
58
+ "prepublication_validation_timeout_confirmation_started",
59
+ "The full client test step reported only Vitest timeouts; confirming once with the same command and attempt environment.",
60
+ ],
61
+ passed: [
62
+ "prepublication_validation_timeout_confirmation_passed",
63
+ "The complete client test step passed on its single timeout confirmation run.",
64
+ ],
65
+ failedEvent: "prepublication_validation_timeout_confirmation_failed",
66
+ failedContent: exitCode => `The complete client test step failed on its single timeout confirmation run (exit ${exitCode}).`,
67
+ };
68
+ const cleanupConfirmation = {
69
+ started: [
70
+ "prepublication_validation_cleanup_confirmation_started",
71
+ "The Bridge suite hit the known Windows temporary-worktree cleanup race; confirming once with the same command and attempt environment.",
72
+ ],
73
+ passed: [
74
+ "prepublication_validation_cleanup_confirmation_passed",
75
+ "The complete Bridge test step passed on its single cleanup confirmation run.",
76
+ ],
77
+ failedEvent: "prepublication_validation_cleanup_confirmation_failed",
78
+ failedContent: exitCode => `The complete Bridge test step failed on its single cleanup confirmation run (exit ${exitCode}).`,
79
+ };
80
+ export { PrePublicationValidationError };
68
81
  export class PrePublicationInfrastructureError extends ForgeFailureError {
69
82
  checkId;
70
83
  exitCode;
@@ -93,110 +106,155 @@ export class PrePublicationValidator {
93
106
  this.nativeTestPostgresFallback = nativeTestPostgresFallback;
94
107
  this.hostLoad = hostLoad;
95
108
  }
109
+ /**
110
+ * Runs one pre-publication pass. A failed check does not end the pass: every remaining check that
111
+ * can still meaningfully run keeps going, and the pass then throws all of its failures as one
112
+ * PrePublicationValidationError.
113
+ */
96
114
  async validate(worktreePath, profile, capabilities, emit, signal, execution) {
97
115
  const checksExports = profile === "implementation" || profile === "comment_repair";
116
+ const pass = new PrePublicationPass(execution?.runtimeRestartFailure);
98
117
  const contract = await loadValidationContract(worktreePath);
99
118
  if (contract === null) {
100
119
  await emit?.(validationEvent("prepublication_validation_legacy_contract", "legacy-provider-validation", `This checkout predates ${contractRelativePath}; Bridge preserved legacy provider validation without source mutation.`));
101
120
  if (checksExports) {
102
121
  const legacy = await prepareValidationExecution(execution);
103
122
  try {
104
- await this.assertNoTestOnlyExports(worktreePath, emit, signal, legacy.execution);
123
+ await this.checkTestOnlyExports(pass, worktreePath, emit, signal, legacy.execution);
105
124
  }
106
125
  finally {
107
126
  await legacy.cleanup();
108
127
  }
109
128
  }
129
+ pass.throwIfFailed();
110
130
  return [];
111
131
  }
112
132
  const scoped = await prepareValidationExecution(execution);
113
133
  try {
114
134
  if (checksExports)
115
- await this.assertNoTestOnlyExports(worktreePath, emit, signal, scoped.execution);
135
+ await this.checkTestOnlyExports(pass, worktreePath, emit, signal, scoped.execution);
116
136
  const contractDigest = validationContractDigest(contract);
117
137
  await this.assertContractMatchesDispatchBaseline(worktreePath, contractDigest, signal, scoped.execution);
118
138
  if (contractDigest !== currentApprovedContractDigest) {
119
139
  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
140
  }
121
141
  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;
142
+ const run = {
143
+ worktreePath,
144
+ capabilities,
145
+ emit,
146
+ signal,
147
+ execution: withValidationBaseRevision(scoped.execution),
148
+ postgresAdminConnection: scoped.postgresAdminConnection,
149
+ };
150
+ return await this.runChecks(applicableChecks(contract, profile, changedPaths), run, pass);
195
151
  }
196
152
  finally {
197
153
  await scoped.cleanup();
198
154
  }
199
155
  }
156
+ async runChecks(checks, run, pass) {
157
+ const completed = [];
158
+ for (const check of checks) {
159
+ if (check.providerOnly) {
160
+ await run.emit?.(validationEvent("prepublication_validation_provider_only", check.id, `Preserved provider-only validation '${check.id}' for the provider check run.`));
161
+ continue;
162
+ }
163
+ const blockedBy = pass.blockers(check.id);
164
+ if (blockedBy.length > 0) {
165
+ await run.emit?.(skippedCheckEvent(check.id, blockedBy));
166
+ continue;
167
+ }
168
+ try {
169
+ const failed = await this.runCheck(check, run);
170
+ // A cancelled step may settle with an exit code rather than throw; the pass ends either way.
171
+ run.signal?.throwIfAborted();
172
+ if (failed)
173
+ pass.record(failed.failure, failed.step);
174
+ else
175
+ completed.push(check.id);
176
+ }
177
+ catch (error) {
178
+ if (!pass.stopsAt(error, run.signal))
179
+ throw error;
180
+ await run.emit?.(pass.stoppedEvent(check.id, error));
181
+ break;
182
+ }
183
+ }
184
+ pass.throwIfFailed();
185
+ return completed;
186
+ }
187
+ /** Runs one check's steps in order; the first failed step ends the check, since later steps use its output. */
188
+ async runCheck(check, run) {
189
+ if (check.requiredCapability && !run.capabilities.has(check.requiredCapability)) {
190
+ throw new ForgeFailureError("prepublication_capability_unavailable", `prepublication_capability_unavailable: ${check.id} requires ${check.requiredCapability}; publication is holding until a capable runner is available.`, "bridge");
191
+ }
192
+ const postgresAdminConnection = await this.ensurePrerequisite(check, run.execution?.environment, run.postgresAdminConnection, run.emit) ?? run.postgresAdminConnection;
193
+ const stepRun = { ...run, check, postgresAdminConnection };
194
+ await run.emit?.(validationEvent("prepublication_validation_started", check.id, `Running pre-publication CI parity check '${check.id}'.`));
195
+ const skipped = new SkippedTestTally(run.worktreePath, run.execution?.environment);
196
+ for (const step of check.steps) {
197
+ const stepStartedMs = Date.now() - 1000;
198
+ const result = await this.runConfirmedStep(stepRun, step);
199
+ if (result.exitCode !== 0) {
200
+ const detail = diagnosticDetail(result);
201
+ await run.emit?.(validationEvent("prepublication_validation_failed", check.id, `Pre-publication CI parity check '${check.id}' exited ${result.exitCode}${detail ? `: ${detail}` : "."}`));
202
+ return {
203
+ failure: { checkId: check.id, exitCode: result.exitCode, command: result.command, args: result.args, detail },
204
+ step,
205
+ };
206
+ }
207
+ await skipped.add(result.args, stepStartedMs);
208
+ }
209
+ await run.emit?.(skipped.passedEvent(check.id, validationExactSecrets(run.execution?.environment)));
210
+ return null;
211
+ }
212
+ /** Runs a step, confirming once a failure that matches a known transient pattern. */
213
+ async runConfirmedStep(run, step) {
214
+ let result = await this.runCheckedStep(run, step);
215
+ if (isTimeoutOnlyClientTestFailure(run.check.id, step, result)) {
216
+ result = await this.confirmStep(run, step, timeoutConfirmation);
217
+ }
218
+ if (isTransientBridgeCleanupFailure(run.check.id, step, result)) {
219
+ result = await this.confirmStep(run, step, cleanupConfirmation);
220
+ }
221
+ if (isTransientShellInfrastructureFailure(result)) {
222
+ result = await this.confirmInfrastructure(run, step);
223
+ }
224
+ return result;
225
+ }
226
+ async runCheckedStep(run, step) {
227
+ const { check, worktreePath, signal, execution, postgresAdminConnection, emit } = run;
228
+ const result = await this.runStep(check.id, step, worktreePath, signal, execution, postgresAdminConnection, emit);
229
+ await this.throwIfPrerequisiteWasLost(check, result, execution?.environment, postgresAdminConnection, emit);
230
+ return result;
231
+ }
232
+ async confirmStep(run, step, confirmation) {
233
+ await run.emit?.(validationEvent(confirmation.started[0], run.check.id, confirmation.started[1]));
234
+ const result = await this.runCheckedStep(run, step);
235
+ await run.emit?.(result.exitCode === 0
236
+ ? validationEvent(confirmation.passed[0], run.check.id, confirmation.passed[1])
237
+ : validationEvent(confirmation.failedEvent, run.check.id, confirmation.failedContent(result.exitCode)));
238
+ return result;
239
+ }
240
+ async confirmInfrastructure(run, step) {
241
+ const checkId = run.check.id;
242
+ 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."));
243
+ const result = await this.runCheckedStep(run, step);
244
+ const infrastructureFailed = isTransientShellInfrastructureFailure(result);
245
+ await run.emit?.(validationEvent(infrastructureFailed
246
+ ? "prepublication_infrastructure_confirmation_failed"
247
+ : "prepublication_infrastructure_confirmation_passed", checkId, infrastructureFailed
248
+ ? `The validation shell failed again on its single infrastructure confirmation run (exit ${result.exitCode}).`
249
+ : result.exitCode === 0
250
+ ? "The validation step recovered on its single infrastructure confirmation run."
251
+ : "The host-runtime failure did not recur; continuing with normal validation failure handling."));
252
+ if (!infrastructureFailed)
253
+ return result;
254
+ const detail = diagnosticDetail(result);
255
+ await run.emit?.(validationEvent("prepublication_infrastructure_failed", checkId, `Pre-publication infrastructure for '${checkId}' remained unavailable${detail ? `: ${detail}` : "."}`));
256
+ throw new PrePublicationInfrastructureError(checkId, result.exitCode, result.command, result.args, detail);
257
+ }
200
258
  /** Returns the native fallback connection when this check must use it instead of Docker. */
201
259
  async ensurePrerequisite(check, environment, postgresAdminConnection, emit) {
202
260
  if (check.requiredPrerequisite === "isolated_postgres"
@@ -245,7 +303,8 @@ export class PrePublicationValidator {
245
303
  throw new PrePublicationInfrastructureError(check.id, result.exitCode, result.command, result.args, detail);
246
304
  }
247
305
  // Runs for every target repository, with or without a CI parity contract: it only reads the worktree.
248
- async assertNoTestOnlyExports(worktreePath, emit, signal, execution) {
306
+ // A failure joins the pass's failures; the contract's checks still run.
307
+ async checkTestOnlyExports(pass, worktreePath, emit, signal, execution) {
249
308
  const found = await findUnreferencedNewExports(args => this.runCommand("git", args, worktreePath, signal, execution), worktreePath, execution?.baselineRevision);
250
309
  const unused = found.filter(row => !row.testOnly);
251
310
  if (unused.length > 0) {
@@ -256,7 +315,7 @@ export class PrePublicationValidator {
256
315
  return;
257
316
  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
317
  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);
318
+ pass.record({ checkId: "unreferenced-exports", exitCode: 1, command: "git", args: ["grep"], detail });
260
319
  }
261
320
  async changedPaths(worktreePath, signal, execution) {
262
321
  const baselineRevision = execution?.baselineRevision?.trim();
@@ -299,10 +358,24 @@ export class PrePublicationValidator {
299
358
  if (!approvedContractDigests.has(baselineDigest)) {
300
359
  throw new ForgeFailureError("prepublication_contract_invalid", `prepublication_contract_invalid: the dispatch baseline uses unapproved CI parity contract ${baselineDigest}.`, "bridge");
301
360
  }
302
- if (baselineDigest !== contractDigest) {
361
+ // A conflict repair's uncommitted merge brings the target branch's contract with it.
362
+ if (baselineDigest !== contractDigest && await this.mergedInContractDigest(worktreePath, signal, execution) !== contractDigest) {
303
363
  throw new ForgeFailureError("prepublication_contract_invalid", `prepublication_contract_invalid: the CI parity contract changed after dispatch (baseline ${baselineDigest}, worktree ${contractDigest}).`, "bridge");
304
364
  }
305
365
  }
366
+ /** The approved contract of the branch an in-progress merge brings in (MERGE_HEAD), else null. */
367
+ async mergedInContractDigest(worktreePath, signal, execution) {
368
+ const merged = await this.runCommand("git", ["show", `MERGE_HEAD:${contractRelativePath}`], worktreePath, signal, execution);
369
+ if (merged.exitCode !== 0)
370
+ return null;
371
+ try {
372
+ const digest = validationContractDigest(JSON.parse(merged.stdout ?? ""));
373
+ return approvedContractDigests.has(digest) ? digest : null;
374
+ }
375
+ catch {
376
+ return null;
377
+ }
378
+ }
306
379
  async runStep(checkId, step, cwd, signal, execution, postgresAdminConnection, emit) {
307
380
  const invocation = managedAttemptInvocation(checkId, step, execution?.environment);
308
381
  // Every launch, including confirmation reruns, is admitted by the host load governor first.
@@ -572,6 +645,13 @@ export async function loadValidationContract(worktreePath) {
572
645
  }
573
646
  return contract;
574
647
  }
648
+ /** The affected .NET tests measure the attempt's change against its dispatch baseline (run-affected-dotnet-tests.mjs). */
649
+ function withValidationBaseRevision(execution) {
650
+ const baseline = execution?.baselineRevision?.trim();
651
+ if (!baseline)
652
+ return execution;
653
+ return { ...execution, environment: { ...execution?.environment, FORGE_VALIDATION_BASE_REVISION: baseline } };
654
+ }
575
655
  function validationContractDigest(contract) {
576
656
  return createHash("sha256")
577
657
  .update(JSON.stringify(canonicalizeJson(contract)))
@@ -586,12 +666,3 @@ function canonicalizeJson(value) {
586
666
  }
587
667
  return value;
588
668
  }
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,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
+ }
@@ -0,0 +1,180 @@
1
+ /**
2
+ * Headless Claude Code runs must not start work that outlives the turn.
3
+ *
4
+ * Forge runs `claude -p` and treats the turn's terminal `result` event as the end of the run.
5
+ * When background work is still live at the end of a turn (a background subagent or shell, a
6
+ * Monitor watch, a scheduled wakeup), Claude Code withholds that `result` and keeps the process
7
+ * open for the work, so Forge sees a silent provider instead of a finished one. The launch
8
+ * restrictions below remove the ways to start such work; `ClaudeBackgroundTurnEndWatch` is the
9
+ * backstop for anything that still gets through.
10
+ */
11
+ import path from "node:path";
12
+ import { ForgeFailureError } from "../session.types.js";
13
+ /**
14
+ * Removes the `run_in_background` parameter from Bash, PowerShell and the Agent tool, runs
15
+ * forked subagents and forked skills in the foreground, and stops Claude Code from moving long
16
+ * shell commands, subagents and MCP calls to the background on its own. Cron disables the
17
+ * session-scoped scheduled tasks (`CronCreate`, `/loop`). Applied last, so a project's runtime
18
+ * environment cannot turn them back on.
19
+ */
20
+ export const claudeHeadlessEnvironment = Object.freeze({
21
+ CLAUDE_CODE_DISABLE_BACKGROUND_TASKS: "1",
22
+ CLAUDE_CODE_DISABLE_CRON: "1",
23
+ });
24
+ /**
25
+ * Tools whose only purpose is work that reports after the turn. `CLAUDE_CODE_DISABLE_BACKGROUND_TASKS`
26
+ * leaves Monitor running in the background, so it is removed here, together with self-paced
27
+ * wakeups, workflows (which run their agents in the background), cloud routines, cron
28
+ * (also disabled by environment), SendMessage, which resumes an earlier subagent in the
29
+ * background, and agent teams, whose teammates run alongside the turn. Foreground subagents
30
+ * stay available: they block the turn until they finish.
31
+ */
32
+ export const claudeHeadlessDisallowedTools = Object.freeze([
33
+ "Monitor",
34
+ "ScheduleWakeup",
35
+ "Workflow",
36
+ "RemoteTrigger",
37
+ "CronCreate",
38
+ "SendMessage",
39
+ "TeamCreate",
40
+ ]);
41
+ /**
42
+ * The Claude Code arguments that apply the restrictions: the tool deny list, and the environment
43
+ * again as flag settings, which outrank a user's or repository's settings `env` block.
44
+ */
45
+ export function claudeHeadlessToolArgs() {
46
+ return [
47
+ "--disallowedTools", claudeHeadlessDisallowedTools.join(","),
48
+ "--settings", JSON.stringify({ env: claudeHeadlessEnvironment }),
49
+ ];
50
+ }
51
+ /**
52
+ * The provider ended its turn while background work it started (a background subagent or
53
+ * shell, a Monitor watch, a wakeup) was still live. Claude Code withholds the turn's terminal
54
+ * result for such work, and nothing started in the background reports to Forge, so Forge stops
55
+ * the provider at once instead of waiting for an idle watchdog. Retryable: the harness, not the
56
+ * task, ended the run.
57
+ */
58
+ export function providerTurnEndedWithBackgroundWorkFailure(message) {
59
+ return new ForgeFailureError("provider_turn_ended_with_background_work", `${message} The provider ended its turn while background work it started was still running, so it never delivered a terminal result; Forge stopped it instead of waiting.`);
60
+ }
61
+ /**
62
+ * Fails every provider run Forge stopped because its turn ended with background work still live,
63
+ * whether or not the turn recorded a completion first: the stop cut that work short, so nothing
64
+ * may validate, commit or publish the worktree it left behind.
65
+ */
66
+ export class BackgroundWorkStopFailingRunner {
67
+ inner;
68
+ constructor(inner) {
69
+ this.inner = inner;
70
+ }
71
+ async run(request, handlers, signal) {
72
+ const result = await this.inner.run(request, handlers, signal);
73
+ if (result.terminalStopReason === "turn_ended_with_background_work") {
74
+ throw providerTurnEndedWithBackgroundWorkFailure("The provider turn did not finish.");
75
+ }
76
+ return result;
77
+ }
78
+ }
79
+ /**
80
+ * Recognizes a main-conversation turn that ended while background tasks it started were still
81
+ * live, the case in which Claude Code withholds the turn's `result`. The turn end is Claude
82
+ * Code's `post_turn_summary` event; the live set is the documented `background_tasks_changed`
83
+ * event (Claude Code's own `ambient` tasks and `awaited` ones do not count). After `graceMs`
84
+ * without the result or new main-conversation activity, it calls `onTurnEndedWithBackgroundWork`
85
+ * once, so the runner can stop the provider instead of waiting on work no one will collect.
86
+ */
87
+ export class ClaudeBackgroundTurnEndWatch {
88
+ graceMs;
89
+ onTurnEndedWithBackgroundWork;
90
+ liveBackgroundTasks = 0;
91
+ terminalSinceMainActivity = false;
92
+ mainTurnEnded = false;
93
+ timer = null;
94
+ stopped = false;
95
+ enabled;
96
+ /** Watches only Claude Code, by its executable `command`; other output is left alone. */
97
+ constructor(command, graceMs, onTurnEndedWithBackgroundWork) {
98
+ this.graceMs = graceMs;
99
+ this.onTurnEndedWithBackgroundWork = onTurnEndedWithBackgroundWork;
100
+ this.enabled = path.parse(command).name.toLowerCase() === "claude";
101
+ }
102
+ consume(line) {
103
+ if (!this.enabled || this.stopped)
104
+ return;
105
+ const event = parseStreamEvent(line);
106
+ if (!event)
107
+ return;
108
+ if (isTerminalEvent(event)) {
109
+ this.terminalSinceMainActivity = true;
110
+ this.cancel();
111
+ }
112
+ else if (event.type === "system" && event.subtype === "background_tasks_changed") {
113
+ this.liveBackgroundTasks = liveBackgroundTaskCount(event.tasks);
114
+ // The work settled: Claude Code now delivers the result or starts a turn for it, and a
115
+ // follow-up turn can think for a while before its first event.
116
+ if (this.liveBackgroundTasks === 0)
117
+ this.cancel();
118
+ // A task can be reported just after the turn summary, as the turn ends.
119
+ else if (this.mainTurnEnded)
120
+ this.armIfTurnEndedWithBackgroundWork();
121
+ }
122
+ else if (event.type === "system" && event.subtype === "post_turn_summary") {
123
+ this.mainTurnEnded = true;
124
+ this.armIfTurnEndedWithBackgroundWork();
125
+ }
126
+ else if ((event.type === "assistant" || event.type === "user") && !event.parent_tool_use_id) {
127
+ // The main conversation is working again (a new turn, or a turn that is still going).
128
+ this.terminalSinceMainActivity = false;
129
+ this.mainTurnEnded = false;
130
+ this.cancel();
131
+ }
132
+ }
133
+ stop() {
134
+ this.stopped = true;
135
+ this.cancel();
136
+ }
137
+ armIfTurnEndedWithBackgroundWork() {
138
+ if (this.timer || this.terminalSinceMainActivity || this.liveBackgroundTasks === 0)
139
+ return;
140
+ this.timer = setTimeout(() => {
141
+ this.timer = null;
142
+ this.stopped = true;
143
+ this.onTurnEndedWithBackgroundWork();
144
+ }, this.graceMs);
145
+ this.timer.unref?.();
146
+ }
147
+ cancel() {
148
+ if (!this.timer)
149
+ return;
150
+ clearTimeout(this.timer);
151
+ this.timer = null;
152
+ }
153
+ }
154
+ function parseStreamEvent(line) {
155
+ const trimmed = line.trim();
156
+ if (!trimmed.startsWith("{"))
157
+ return null;
158
+ try {
159
+ const parsed = JSON.parse(trimmed);
160
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
161
+ }
162
+ catch {
163
+ return null;
164
+ }
165
+ }
166
+ function isTerminalEvent(event) {
167
+ return event.type === "result" || event.type === "error";
168
+ }
169
+ /**
170
+ * Tasks that keep the turn's result back: not Claude Code's own `ambient` tasks, and not
171
+ * `awaited` ones, which a still-running tool call of the turn waits for.
172
+ */
173
+ function liveBackgroundTaskCount(tasks) {
174
+ if (!Array.isArray(tasks))
175
+ return 0;
176
+ return tasks.filter(task => {
177
+ const entry = task && typeof task === "object" ? task : {};
178
+ return entry.ambient !== true && entry.awaited !== true;
179
+ }).length;
180
+ }