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

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 (34) hide show
  1. package/README.md +9 -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-runtime-lease.d.ts +1 -1
  7. package/dist/runtime/host-runtime-lease.js +8 -7
  8. package/dist/runtime/host-runtime-promotion.d.ts +23 -0
  9. package/dist/runtime/host-runtime-promotion.js +36 -0
  10. package/dist/session/phase-completion.schemas.js +22 -12
  11. package/dist/session/pre-publication-pass.d.ts +60 -0
  12. package/dist/session/pre-publication-pass.js +145 -0
  13. package/dist/session/pre-publication-validation.d.ts +21 -11
  14. package/dist/session/pre-publication-validation.js +149 -104
  15. package/dist/session/provider-cli/claude-background-work.d.ts +66 -0
  16. package/dist/session/provider-cli/claude-background-work.js +180 -0
  17. package/dist/session/provider-cli/pre-publication-repair.d.ts +40 -0
  18. package/dist/session/provider-cli/pre-publication-repair.js +243 -0
  19. package/dist/session/provider-cli/provider-cli.process.d.ts +7 -6
  20. package/dist/session/provider-cli/provider-cli.process.js +14 -54
  21. package/dist/session/provider-cli/provider-cli.prompts.d.ts +2 -0
  22. package/dist/session/provider-cli/provider-cli.prompts.js +45 -8
  23. package/dist/session/provider-cli/provider-cli.runtime.js +7 -0
  24. package/dist/session/provider-cli/provider-cli.service.d.ts +4 -7
  25. package/dist/session/provider-cli/provider-cli.service.js +66 -243
  26. package/dist/session/provider-cli/provider-in-flight-work.d.ts +4 -0
  27. package/dist/session/provider-cli/provider-in-flight-work.js +45 -0
  28. package/dist/session/provider-cli/provider-output-state.d.ts +2 -0
  29. package/dist/session/provider-cli/provider-output-state.js +6 -0
  30. package/dist/session/session.types.js +1 -1
  31. package/dist/shared/provider-capabilities.js +5 -6
  32. package/dist/version.d.ts +1 -1
  33. package/dist/version.js +1 -1
  34. package/package.json +2 -2
@@ -0,0 +1,145 @@
1
+ import { redactText } from "../shared/redaction/redaction.js";
2
+ import { describeSkippedTests, mergeSkippedTests, readSkippedTests, } from "./pre-publication-skipped-tests.js";
3
+ import { ForgeFailureError, failureFactsFromError } from "./session.types.js";
4
+ // One pre-publication validation pass. A failed check no longer ends the pass: the remaining checks
5
+ // that can still meaningfully run keep going, so one in-place repair turn sees every independent
6
+ // failure at once instead of one per turn. The pass records each failure, says which checks it
7
+ // could not run because a check they depend on failed, and reports them all as one failure.
8
+ /** The check id a failed restart of the attempt's runtime stack before the pass is reported under. */
9
+ export const runtimeRestartCheckId = "host-runtime-restart";
10
+ const dotnetBuildCheckId = "dotnet-build-and-unit";
11
+ // Checks that build the .NET solution themselves and would only repeat the compiler errors once its
12
+ // compile step fails: the OpenAPI export builds Forge.Api and the E2E suite publishes it.
13
+ const dotnetBuildConsumers = new Set(["openapi-and-generated-types", "playwright-e2e"]);
14
+ // Checks that run against the attempt's application stack, which a failed restart left stopped.
15
+ const runtimeStackConsumers = new Set(["playwright-e2e"]);
16
+ // The diagnostics of each further failure that the error message carries; the repair prompt
17
+ // carries every failure's diagnostics in full.
18
+ const additionalFailureMessageDetail = 1500;
19
+ /**
20
+ * A failed validation pass. The single-check fields name the first failure, as they always have;
21
+ * `failures` lists every check that failed in the pass, in the order the checks ran.
22
+ */
23
+ export class PrePublicationValidationError extends ForgeFailureError {
24
+ checkId;
25
+ exitCode;
26
+ command;
27
+ args;
28
+ detail;
29
+ code = "prepublication_validation_failed";
30
+ failures;
31
+ constructor(checkId, exitCode, command, args, detail, additionalFailures = []) {
32
+ super("prepublication_validation_failed", validationFailureMessage([{ checkId, exitCode, command, args, detail }, ...additionalFailures]), "bridge");
33
+ this.checkId = checkId;
34
+ this.exitCode = exitCode;
35
+ this.command = command;
36
+ this.args = args;
37
+ this.detail = detail;
38
+ this.name = "PrePublicationValidationError";
39
+ this.failures = [{ checkId, exitCode, command, args, detail }, ...additionalFailures];
40
+ }
41
+ /** Every failed check's id, first failure first. */
42
+ get checkIds() {
43
+ return this.failures.map(failure => failure.checkId);
44
+ }
45
+ }
46
+ function validationFailureMessage(failures) {
47
+ const [first, ...others] = failures;
48
+ const summary = (failure, detail) => `${failure.checkId} exited ${failure.exitCode}${detail ? `: ${detail}` : ""}`;
49
+ if (others.length === 0)
50
+ return `prepublication_validation_failed: ${summary(first, first.detail)}`;
51
+ // The other check ids come before the first detail, so a clipped failure message still names them.
52
+ const also = `[also failed: ${others.map(failure => failure.checkId).join(", ")}]`;
53
+ const more = others.map(failure => summary(failure, clipDetail(failure.detail)));
54
+ return `prepublication_validation_failed: ${first.checkId} exited ${first.exitCode} ${also}${first.detail ? `: ${first.detail}` : ""}`
55
+ + `\n\nAlso failed in the same validation pass: ${more.join("\n\n")}`;
56
+ }
57
+ function clipDetail(detail) {
58
+ return detail.length <= additionalFailureMessageDetail
59
+ ? detail
60
+ : `${detail.slice(0, additionalFailureMessageDetail)}… (clipped)`;
61
+ }
62
+ export class PrePublicationPass {
63
+ runtimeRestartFailure;
64
+ failures = [];
65
+ dotnetCompileFailed = false;
66
+ /** A failed runtime restart before the pass is its first failure. */
67
+ constructor(runtimeRestartFailure) {
68
+ this.runtimeRestartFailure = runtimeRestartFailure;
69
+ this.failures.push(...runtimeRestartFailure?.failures ?? []);
70
+ }
71
+ record(failure, failedStep) {
72
+ this.failures.push(failure);
73
+ if (failure.checkId === dotnetBuildCheckId && failedStep?.command === "dotnet" && failedStep.args[0] === "build") {
74
+ this.dotnetCompileFailed = true;
75
+ }
76
+ }
77
+ /** The failed checks that keep this check from running meaningfully in this pass. */
78
+ blockers(checkId) {
79
+ return [
80
+ ...(this.dotnetCompileFailed && dotnetBuildConsumers.has(checkId) ? [dotnetBuildCheckId] : []),
81
+ ...(this.runtimeRestartFailure && runtimeStackConsumers.has(checkId) ? [runtimeRestartCheckId] : []),
82
+ ];
83
+ }
84
+ /**
85
+ * Whether an error ends the pass with the failures it already found. Only a classified retryable
86
+ * failure (a resource hold, lost infrastructure, a supervisor that did not start) does, once the
87
+ * pass has found a failure: the repair turn can fix those failures now, and the next pass meets
88
+ * the condition again. Any other error, or cancellation, still ends the attempt as it did.
89
+ */
90
+ stopsAt(error, signal) {
91
+ if (this.failures.length === 0 || signal?.aborted || !(error instanceof ForgeFailureError))
92
+ return false;
93
+ return failureFactsFromError(error).retryability === "retryable";
94
+ }
95
+ stoppedEvent(checkId, error) {
96
+ const failedCheckIds = this.failures.map(failure => failure.checkId);
97
+ return validationEvent("prepublication_validation_pass_stopped", checkId, `Stopped this pre-publication pass at '${checkId}' (${error.failureCode}). Reporting the ${failedCheckIds.length} failed check${failedCheckIds.length === 1 ? "" : "s"} it already found (${failedCheckIds.join(", ")}) for repair; the next pass runs '${checkId}' again.`, { failureCode: error.failureCode, failedCheckIds });
98
+ }
99
+ /** Throws every failure the pass found as one validation failure. */
100
+ throwIfFailed() {
101
+ const [first, ...others] = this.failures;
102
+ if (!first)
103
+ return;
104
+ throw new PrePublicationValidationError(first.checkId, first.exitCode, first.command, first.args, first.detail, others);
105
+ }
106
+ }
107
+ export function skippedCheckEvent(checkId, blockedBy) {
108
+ const reason = blockedBy.map(blocker => blocker === runtimeRestartCheckId
109
+ ? "the attempt's runtime stack, whose restart failed"
110
+ : `the .NET build, which failed in '${blocker}'`).join(" and ");
111
+ return validationEvent("prepublication_validation_skipped", checkId, `Skipped pre-publication CI parity check '${checkId}' in this pass: it needs ${reason}. The next pass runs it again.`, { blockedBy });
112
+ }
113
+ /** The tests a check's steps skipped, so a check that passed with skips says so with each reason. */
114
+ export class SkippedTestTally {
115
+ worktreePath;
116
+ environment;
117
+ summary = { count: 0, reasons: [] };
118
+ constructor(worktreePath, environment) {
119
+ this.worktreePath = worktreePath;
120
+ this.environment = environment;
121
+ }
122
+ /** The invocation's own arguments: a managed attempt may direct results to its test-output root. */
123
+ async add(args, stepStartedMs) {
124
+ this.summary = mergeSkippedTests(this.summary, await readSkippedTests(this.worktreePath, args, stepStartedMs, this.environment));
125
+ }
126
+ passedEvent(checkId, secrets) {
127
+ const skipped = {
128
+ ...this.summary,
129
+ reasons: this.summary.reasons.map(entry => ({ ...entry, reason: redactText(entry.reason, secrets) })),
130
+ };
131
+ if (skipped.count === 0) {
132
+ return validationEvent("prepublication_validation_passed", checkId, `Pre-publication CI parity check '${checkId}' passed.`);
133
+ }
134
+ return validationEvent("prepublication_validation_passed", checkId, `Pre-publication CI parity check '${checkId}' passed with ${describeSkippedTests(skipped)}.`, { skippedTests: skipped.count, skippedReasons: skipped.reasons });
135
+ }
136
+ }
137
+ export function validationEvent(eventType, checkId, content, detail) {
138
+ return {
139
+ role: "runner",
140
+ kind: "checkpoint",
141
+ content,
142
+ eventType,
143
+ data: JSON.stringify({ checkId, contractId: "forge-ci-parity-v1", ...detail }),
144
+ };
145
+ }
@@ -3,6 +3,7 @@ import type { NativeTestPostgresFallback } from "../runtime/native-test-postgres
3
3
  import type { HostLoadStepGate } from "../runtime/host-load-governor.js";
4
4
  import { type PrePublicationHostLoadOwner } from "./pre-publication-host-load.js";
5
5
  import { type ValidationStep } from "./pre-publication-step-execution.js";
6
+ import { PrePublicationValidationError, type PrePublicationCheckFailure } from "./pre-publication-pass.js";
6
7
  import type { ProviderProcessRunner } from "./provider-cli/provider-cli.process.js";
7
8
  import { ForgeFailureError, type RunnerDispatchEvent } from "./session.types.js";
8
9
  export type PrePublicationProfile = "implementation" | "comment_repair" | "ci_repair" | "conflict_repair";
@@ -34,16 +35,13 @@ export interface PrePublicationExecutionContext {
34
35
  readonly processRunner?: ProviderProcessRunner;
35
36
  /** The attempt governed steps reserve host capacity for (decision 0013). */
36
37
  readonly hostLoadOwner?: PrePublicationHostLoadOwner;
38
+ /**
39
+ * The failed restart of the attempt's runtime stack before this pass. The pass reports it with
40
+ * its own failures and does not run the checks that need the stopped stack.
41
+ */
42
+ readonly runtimeRestartFailure?: PrePublicationValidationError;
37
43
  }
38
- export declare class PrePublicationValidationError extends ForgeFailureError {
39
- readonly checkId: string;
40
- readonly exitCode: number;
41
- readonly command: string;
42
- readonly args: readonly string[];
43
- readonly detail: string;
44
- readonly code = "prepublication_validation_failed";
45
- constructor(checkId: string, exitCode: number, command: string, args: readonly string[], detail: string);
46
- }
44
+ export { PrePublicationValidationError, type PrePublicationCheckFailure };
47
45
  export declare class PrePublicationInfrastructureError extends ForgeFailureError {
48
46
  readonly checkId: string;
49
47
  readonly exitCode: number;
@@ -59,11 +57,24 @@ export declare class PrePublicationValidator {
59
57
  private readonly nativeTestPostgresFallback;
60
58
  private readonly hostLoad?;
61
59
  constructor(commands?: PrePublicationCommandRunner, dockerEngineProbe?: DockerEngineProbe | undefined, nativeTestPostgresFallback?: () => NativeTestPostgresFallback | null, hostLoad?: HostLoadStepGate | undefined);
60
+ /**
61
+ * Runs one pre-publication pass. A failed check does not end the pass: every remaining check that
62
+ * can still meaningfully run keeps going, and the pass then throws all of its failures as one
63
+ * PrePublicationValidationError.
64
+ */
62
65
  validate(worktreePath: string, profile: PrePublicationProfile, capabilities: ReadonlySet<string>, emit?: (event: RunnerDispatchEvent) => Promise<void>, signal?: AbortSignal, execution?: PrePublicationExecutionContext): Promise<readonly string[]>;
66
+ private runChecks;
67
+ /** Runs one check's steps in order; the first failed step ends the check, since later steps use its output. */
68
+ private runCheck;
69
+ /** Runs a step, confirming once a failure that matches a known transient pattern. */
70
+ private runConfirmedStep;
71
+ private runCheckedStep;
72
+ private confirmStep;
73
+ private confirmInfrastructure;
63
74
  /** Returns the native fallback connection when this check must use it instead of Docker. */
64
75
  private ensurePrerequisite;
65
76
  private throwIfPrerequisiteWasLost;
66
- private assertNoTestOnlyExports;
77
+ private checkTestOnlyExports;
67
78
  private changedPaths;
68
79
  private assertContractMatchesDispatchBaseline;
69
80
  private runStep;
@@ -72,4 +83,3 @@ export declare class PrePublicationValidator {
72
83
  }
73
84
  export declare function applicableChecks(contract: ValidationContract, profile: PrePublicationProfile | "github_actions", changedPaths: readonly string[]): readonly ValidationCheck[];
74
85
  export declare function loadValidationContract(worktreePath: string): Promise<ValidationContract | null>;
75
- export {};
@@ -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,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
+ }