@loucompanion/forge-bridge 0.1.4-dev.d2d83bc81b6a → 0.1.4-dev.e83e5bc6ecce

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 (130) hide show
  1. package/README.md +2 -2
  2. package/dist/bridge/bridge.service.d.ts +5 -1
  3. package/dist/bridge/bridge.service.js +40 -6
  4. package/dist/bridge/bridge.types.d.ts +11 -0
  5. package/dist/bridge/runner-host-capabilities.d.ts +2 -0
  6. package/dist/bridge/runner-host-capabilities.js +4 -0
  7. package/dist/bridge/test-postgres-capability.d.ts +14 -0
  8. package/dist/bridge/test-postgres-capability.js +120 -0
  9. package/dist/cleanup/cleanup.service.d.ts +9 -0
  10. package/dist/cleanup/cleanup.service.js +72 -109
  11. package/dist/cleanup/cleanup.types.d.ts +4 -0
  12. package/dist/cleanup/forge-owned-paths.d.ts +9 -0
  13. package/dist/cleanup/forge-owned-paths.js +53 -0
  14. package/dist/cleanup/host-runtime-ledger.d.ts +5 -0
  15. package/dist/cleanup/host-runtime-ledger.js +109 -0
  16. package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
  17. package/dist/cleanup/managed-branch-sweep.js +111 -0
  18. package/dist/cli/cli.service.js +10 -2
  19. package/dist/runtime/host-database-capability-boundary.d.ts +1 -1
  20. package/dist/runtime/host-database-capability-boundary.js +1 -0
  21. package/dist/runtime/host-facts.d.ts +35 -0
  22. package/dist/runtime/host-facts.js +95 -0
  23. package/dist/runtime/host-load-admission.d.ts +52 -0
  24. package/dist/runtime/host-load-admission.js +84 -0
  25. package/dist/runtime/host-load-child-environment.d.ts +22 -0
  26. package/dist/runtime/host-load-child-environment.js +65 -0
  27. package/dist/runtime/host-load-forge-cgroups.d.ts +49 -0
  28. package/dist/runtime/host-load-forge-cgroups.js +140 -0
  29. package/dist/runtime/host-load-governor-config.d.ts +34 -0
  30. package/dist/runtime/host-load-governor-config.js +46 -0
  31. package/dist/runtime/host-load-governor.d.ts +172 -0
  32. package/dist/runtime/host-load-governor.js +519 -0
  33. package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
  34. package/dist/runtime/host-load-ledger-lock.js +185 -0
  35. package/dist/runtime/host-load-sampler.d.ts +126 -0
  36. package/dist/runtime/host-load-sampler.js +232 -0
  37. package/dist/runtime/host-load-step-class.d.ts +68 -0
  38. package/dist/runtime/host-load-step-class.js +106 -0
  39. package/dist/runtime/host-load-step-reaper.d.ts +27 -0
  40. package/dist/runtime/host-load-step-reaper.js +95 -0
  41. package/dist/runtime/host-load-step-run.d.ts +73 -0
  42. package/dist/runtime/host-load-step-run.js +102 -0
  43. package/dist/runtime/host-load-token-ledger.d.ts +174 -0
  44. package/dist/runtime/host-load-token-ledger.js +421 -0
  45. package/dist/runtime/host-pressure-stall.d.ts +61 -0
  46. package/dist/runtime/host-pressure-stall.js +168 -0
  47. package/dist/runtime/host-runtime-contract.d.ts +4 -0
  48. package/dist/runtime/host-runtime-contract.js +6 -1
  49. package/dist/runtime/host-runtime-lease.d.ts +17 -3
  50. package/dist/runtime/host-runtime-lease.js +83 -4
  51. package/dist/runtime/host-runtime-promotion.js +12 -0
  52. package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
  53. package/dist/runtime/host-runtime-requirements-check.js +29 -0
  54. package/dist/runtime/host-runtime-requirements.d.ts +36 -0
  55. package/dist/runtime/host-runtime-requirements.js +117 -0
  56. package/dist/sandbox/host-capacity-broker.d.ts +107 -0
  57. package/dist/sandbox/host-capacity-broker.js +315 -0
  58. package/dist/sandbox/runtime.d.ts +10 -1
  59. package/dist/sandbox/runtime.js +45 -2
  60. package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
  61. package/dist/sandbox/sandbox-cgroups.js +42 -0
  62. package/dist/session/managed-attempt-tools.d.ts +2 -0
  63. package/dist/session/managed-attempt-tools.js +156 -37
  64. package/dist/session/managed-command-host-load.d.ts +45 -0
  65. package/dist/session/managed-command-host-load.js +82 -0
  66. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  67. package/dist/session/mcp-argument-coercion.js +121 -0
  68. package/dist/session/phase-completion.artifacts.d.ts +7 -0
  69. package/dist/session/phase-completion.artifacts.js +98 -25
  70. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  71. package/dist/session/phase-completion.command-validation.js +77 -0
  72. package/dist/session/phase-completion.d.ts +4 -0
  73. package/dist/session/phase-completion.helpers.js +13 -12
  74. package/dist/session/phase-completion.js +4 -0
  75. package/dist/session/phase-completion.prompts.js +6 -1
  76. package/dist/session/phase-completion.runtime.d.ts +5 -3
  77. package/dist/session/phase-completion.runtime.js +49 -19
  78. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  79. package/dist/session/phase-completion.schema-parts.js +188 -0
  80. package/dist/session/phase-completion.schemas.d.ts +3 -3
  81. package/dist/session/phase-completion.schemas.js +184 -209
  82. package/dist/session/phase-completion.validation.d.ts +2 -3
  83. package/dist/session/phase-completion.validation.js +46 -92
  84. package/dist/session/pre-publication-host-load.d.ts +27 -0
  85. package/dist/session/pre-publication-host-load.js +111 -0
  86. package/dist/session/pre-publication-process.d.ts +3 -0
  87. package/dist/session/pre-publication-process.js +25 -12
  88. package/dist/session/pre-publication-skipped-tests.d.ts +21 -0
  89. package/dist/session/pre-publication-skipped-tests.js +109 -0
  90. package/dist/session/pre-publication-step-execution.d.ts +11 -0
  91. package/dist/session/pre-publication-step-execution.js +49 -0
  92. package/dist/session/pre-publication-validation.d.ts +9 -9
  93. package/dist/session/pre-publication-validation.js +44 -59
  94. package/dist/session/provider-cli/provider-cli.artifacts.d.ts +2 -1
  95. package/dist/session/provider-cli/provider-cli.artifacts.js +21 -15
  96. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
  97. package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
  98. package/dist/session/provider-cli/provider-cli.process.d.ts +32 -1
  99. package/dist/session/provider-cli/provider-cli.process.js +122 -30
  100. package/dist/session/provider-cli/provider-cli.prompts.d.ts +5 -0
  101. package/dist/session/provider-cli/provider-cli.prompts.js +16 -1
  102. package/dist/session/provider-cli/provider-cli.service.js +134 -30
  103. package/dist/session/provider-cli/provider-cli.types.d.ts +4 -0
  104. package/dist/session/provider-cli/provider-in-flight-work.d.ts +6 -0
  105. package/dist/session/provider-cli/provider-in-flight-work.js +47 -0
  106. package/dist/session/provider-cli/provider-output-state.d.ts +6 -0
  107. package/dist/session/provider-cli/provider-output-state.js +9 -0
  108. package/dist/session/publishable-worktree-changes.d.ts +54 -0
  109. package/dist/session/publishable-worktree-changes.js +193 -0
  110. package/dist/session/sandbox-host-capacity-gate.d.ts +30 -0
  111. package/dist/session/sandbox-host-capacity-gate.js +229 -0
  112. package/dist/session/session.base.d.ts +3 -0
  113. package/dist/session/session.service.d.ts +2 -0
  114. package/dist/session/session.service.js +21 -4
  115. package/dist/session/session.types.d.ts +3 -0
  116. package/dist/session/session.types.js +14 -2
  117. package/dist/shared/process/host-process-supervisor.d.ts +1 -0
  118. package/dist/shared/process/host-process-supervisor.js +1 -1
  119. package/dist/shared/process/process-tree.d.ts +52 -0
  120. package/dist/shared/process/process-tree.js +144 -0
  121. package/dist/shared/process/process.d.ts +67 -0
  122. package/dist/shared/process/process.js +213 -11
  123. package/dist/version.d.ts +1 -1
  124. package/dist/version.js +1 -1
  125. package/dist/worktree/dependency-warmer.d.ts +25 -0
  126. package/dist/worktree/dependency-warmer.js +46 -10
  127. package/dist/worktree/worktree.service.d.ts +10 -1
  128. package/dist/worktree/worktree.service.js +42 -2
  129. package/dist/worktree/worktree.types.d.ts +7 -0
  130. package/package.json +1 -1
@@ -1,15 +1,11 @@
1
1
  import type { DockerEngineProbe } from "../runtime/docker-engine-probe.js";
2
- import { type NativeTestPostgresFallback } from "../runtime/native-test-postgres-fallback.js";
2
+ import type { NativeTestPostgresFallback } from "../runtime/native-test-postgres-fallback.js";
3
+ import type { HostLoadStepGate } from "../runtime/host-load-governor.js";
4
+ import { type PrePublicationHostLoadOwner } from "./pre-publication-host-load.js";
5
+ import { type ValidationStep } from "./pre-publication-step-execution.js";
3
6
  import type { ProviderProcessRunner } from "./provider-cli/provider-cli.process.js";
4
7
  import { ForgeFailureError, type RunnerDispatchEvent } from "./session.types.js";
5
8
  export type PrePublicationProfile = "implementation" | "comment_repair" | "ci_repair" | "conflict_repair";
6
- interface ValidationStep {
7
- readonly command: string;
8
- readonly fallbackCommand?: string;
9
- readonly args: readonly string[];
10
- readonly fallbackArgs?: readonly string[];
11
- readonly assertUnchangedPaths?: readonly string[];
12
- }
13
9
  interface ValidationCheck {
14
10
  readonly id: string;
15
11
  readonly profiles: readonly string[];
@@ -36,6 +32,8 @@ export interface PrePublicationExecutionContext {
36
32
  readonly baselineRevision?: string;
37
33
  readonly environment?: Readonly<Record<string, string>>;
38
34
  readonly processRunner?: ProviderProcessRunner;
35
+ /** The attempt governed steps reserve host capacity for (decision 0013). */
36
+ readonly hostLoadOwner?: PrePublicationHostLoadOwner;
39
37
  }
40
38
  export declare class PrePublicationValidationError extends ForgeFailureError {
41
39
  readonly checkId: string;
@@ -59,7 +57,8 @@ export declare class PrePublicationValidator {
59
57
  private readonly commands;
60
58
  private readonly dockerEngineProbe?;
61
59
  private readonly nativeTestPostgresFallback;
62
- constructor(commands?: PrePublicationCommandRunner, dockerEngineProbe?: DockerEngineProbe | undefined, nativeTestPostgresFallback?: () => NativeTestPostgresFallback | null);
60
+ private readonly hostLoad?;
61
+ constructor(commands?: PrePublicationCommandRunner, dockerEngineProbe?: DockerEngineProbe | undefined, nativeTestPostgresFallback?: () => NativeTestPostgresFallback | null, hostLoad?: HostLoadStepGate | undefined);
63
62
  validate(worktreePath: string, profile: PrePublicationProfile, capabilities: ReadonlySet<string>, emit?: (event: RunnerDispatchEvent) => Promise<void>, signal?: AbortSignal, execution?: PrePublicationExecutionContext): Promise<readonly string[]>;
64
63
  /** Returns the native fallback connection when this check must use it instead of Docker. */
65
64
  private ensurePrerequisite;
@@ -68,6 +67,7 @@ export declare class PrePublicationValidator {
68
67
  private changedPaths;
69
68
  private assertContractMatchesDispatchBaseline;
70
69
  private runStep;
70
+ private launchStep;
71
71
  private runCommand;
72
72
  }
73
73
  export declare function applicableChecks(contract: ValidationContract, profile: PrePublicationProfile | "github_actions", changedPaths: readonly string[]): readonly ValidationCheck[];
@@ -3,10 +3,13 @@ import fs from "node:fs/promises";
3
3
  import path from "node:path";
4
4
  import { attemptDatabaseCapabilityEnvironment, attemptDatabaseCapabilitySecrets, } from "../runtime/attempt-database-broker.js";
5
5
  import { assertHostDatabaseCapabilityBoundary } from "../runtime/host-database-capability-boundary.js";
6
- import { nativeTestPostgresFallbackEnvironment, parseNativeTestPostgresFallback, } from "../runtime/native-test-postgres-fallback.js";
7
- import { hostRuntimeLegacyTestPostgresEnvironment, hostRuntimeTestPostgresAdminEnvironment, } from "../runtime/host-runtime-contract.js";
6
+ import { runHostGovernedValidationStep } from "./pre-publication-host-load.js";
7
+ import { managedAttemptInvocation, supportsNativeTestPostgresFallback, validationExecutionForStep, } from "./pre-publication-step-execution.js";
8
+ import { hostRuntimeLegacyTestPostgresEnvironment, hostRuntimeTestPostgresAdminEnvironment, hostRuntimeTestPostgresProvisionerEnvironment, } from "../runtime/host-runtime-contract.js";
8
9
  import { redactText } from "../shared/redaction/redaction.js";
10
+ import { describeSkippedTests, mergeSkippedTests, readSkippedTests, } from "./pre-publication-skipped-tests.js";
9
11
  import { ProcessPrePublicationCommandRunner, pnpmDirectoryLaunch } from "./pre-publication-process.js";
12
+ import { ProcessTreeTerminationError } from "../shared/process/process.js";
10
13
  import { findUnreferencedNewExports } from "./unreferenced-exports.js";
11
14
  import { ForgeFailureError, sanitizeFailureError, } from "./session.types.js";
12
15
  const contractRelativePath = ".forge/validation/ci-parity.v1.json";
@@ -83,10 +86,12 @@ export class PrePublicationValidator {
83
86
  commands;
84
87
  dockerEngineProbe;
85
88
  nativeTestPostgresFallback;
86
- constructor(commands = new ProcessPrePublicationCommandRunner(), dockerEngineProbe, nativeTestPostgresFallback = () => null) {
89
+ hostLoad;
90
+ constructor(commands = new ProcessPrePublicationCommandRunner(), dockerEngineProbe, nativeTestPostgresFallback = () => null, hostLoad) {
87
91
  this.commands = commands;
88
92
  this.dockerEngineProbe = dockerEngineProbe;
89
93
  this.nativeTestPostgresFallback = nativeTestPostgresFallback;
94
+ this.hostLoad = hostLoad;
90
95
  }
91
96
  async validate(worktreePath, profile, capabilities, emit, signal, execution) {
92
97
  const checksExports = profile === "implementation" || profile === "comment_repair";
@@ -126,12 +131,14 @@ export class PrePublicationValidator {
126
131
  }
127
132
  const postgresAdminConnection = await this.ensurePrerequisite(check, scoped.execution?.environment, scoped.postgresAdminConnection, emit) ?? scoped.postgresAdminConnection;
128
133
  await emit?.(validationEvent("prepublication_validation_started", check.id, `Running pre-publication CI parity check '${check.id}'.`));
134
+ let skipped = { count: 0, reasons: [] };
129
135
  for (const step of check.steps) {
130
- let result = await this.runStep(check.id, step, worktreePath, signal, scoped.execution, postgresAdminConnection);
136
+ const stepStartedMs = Date.now() - 1000;
137
+ let result = await this.runStep(check.id, step, worktreePath, signal, scoped.execution, postgresAdminConnection, emit);
131
138
  await this.throwIfPrerequisiteWasLost(check, result, scoped.execution?.environment, postgresAdminConnection, emit);
132
139
  if (isTimeoutOnlyClientTestFailure(check.id, step, result)) {
133
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."));
134
- result = await this.runStep(check.id, step, worktreePath, signal, scoped.execution, postgresAdminConnection);
141
+ result = await this.runStep(check.id, step, worktreePath, signal, scoped.execution, postgresAdminConnection, emit);
135
142
  await this.throwIfPrerequisiteWasLost(check, result, scoped.execution?.environment, postgresAdminConnection, emit);
136
143
  await emit?.(validationEvent(result.exitCode === 0
137
144
  ? "prepublication_validation_timeout_confirmation_passed"
@@ -141,7 +148,7 @@ export class PrePublicationValidator {
141
148
  }
142
149
  if (isTransientBridgeCleanupFailure(check.id, step, result)) {
143
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."));
144
- result = await this.runStep(check.id, step, worktreePath, signal, scoped.execution, postgresAdminConnection);
151
+ result = await this.runStep(check.id, step, worktreePath, signal, scoped.execution, postgresAdminConnection, emit);
145
152
  await this.throwIfPrerequisiteWasLost(check, result, scoped.execution?.environment, postgresAdminConnection, emit);
146
153
  await emit?.(validationEvent(result.exitCode === 0
147
154
  ? "prepublication_validation_cleanup_confirmation_passed"
@@ -151,7 +158,7 @@ export class PrePublicationValidator {
151
158
  }
152
159
  if (isTransientShellInfrastructureFailure(result)) {
153
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."));
154
- result = await this.runStep(check.id, step, worktreePath, signal, scoped.execution, postgresAdminConnection);
161
+ result = await this.runStep(check.id, step, worktreePath, signal, scoped.execution, postgresAdminConnection, emit);
155
162
  await this.throwIfPrerequisiteWasLost(check, result, scoped.execution?.environment, postgresAdminConnection, emit);
156
163
  const infrastructureFailed = isTransientShellInfrastructureFailure(result);
157
164
  await emit?.(validationEvent(infrastructureFailed
@@ -172,9 +179,17 @@ export class PrePublicationValidator {
172
179
  await emit?.(validationEvent("prepublication_validation_failed", check.id, `Pre-publication CI parity check '${check.id}' exited ${result.exitCode}${detail ? `: ${detail}` : "."}`));
173
180
  throw new PrePublicationValidationError(check.id, result.exitCode, result.command, result.args, detail);
174
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));
175
184
  }
176
185
  completed.push(check.id);
177
- await emit?.(validationEvent("prepublication_validation_passed", check.id, `Pre-publication CI parity check '${check.id}' passed.`));
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));
178
193
  }
179
194
  return completed;
180
195
  }
@@ -202,7 +217,7 @@ export class PrePublicationValidator {
202
217
  const snapshot = await this.dockerEngineProbe.ensureAvailableForRequiredWork();
203
218
  if (!snapshot.available) {
204
219
  const detail = `Docker prerequisite unavailable (${snapshot.unavailableCode ?? "docker_engine_unavailable"}): ${snapshot.unavailableReason ?? "the daemon did not pass a fresh readiness probe"}`;
205
- const fallback = check.requiredPrerequisite === "isolated_postgres" && supportsNativeTestPostgresFallback(check)
220
+ const fallback = check.requiredPrerequisite === "isolated_postgres" && supportsNativeTestPostgresFallback(check.id)
206
221
  ? this.nativeTestPostgresFallback()
207
222
  : null;
208
223
  if (fallback) {
@@ -288,8 +303,14 @@ export class PrePublicationValidator {
288
303
  throw new ForgeFailureError("prepublication_contract_invalid", `prepublication_contract_invalid: the CI parity contract changed after dispatch (baseline ${baselineDigest}, worktree ${contractDigest}).`, "bridge");
289
304
  }
290
305
  }
291
- async runStep(checkId, step, cwd, signal, execution, postgresAdminConnection) {
306
+ async runStep(checkId, step, cwd, signal, execution, postgresAdminConnection, emit) {
292
307
  const invocation = managedAttemptInvocation(checkId, step, execution?.environment);
308
+ // Every launch, including confirmation reruns, is admitted by the host load governor first.
309
+ return await runHostGovernedValidationStep(this.hostLoad, {
310
+ checkId, command: invocation.command, args: invocation.args, owner: execution?.hostLoadOwner, signal, emit,
311
+ }, async (stepSignal) => await this.launchStep(checkId, step, invocation, cwd, stepSignal, execution, postgresAdminConnection));
312
+ }
313
+ async launchStep(checkId, step, invocation, cwd, signal, execution, postgresAdminConnection) {
293
314
  const stepExecution = validationExecutionForStep(checkId, step, execution, postgresAdminConnection);
294
315
  const before = await readValidationFiles(cwd, step.assertUnchangedPaths ?? []);
295
316
  const result = await this.runCommand(invocation.command, invocation.args, cwd, signal, stepExecution);
@@ -334,57 +355,13 @@ export class PrePublicationValidator {
334
355
  };
335
356
  }
336
357
  catch (error) {
358
+ // Carries the check its host capacity token waits on; it names only the executable.
359
+ if (error instanceof ProcessTreeTerminationError)
360
+ throw error;
337
361
  throw sanitizeFailureError(error, exactSecrets);
338
362
  }
339
363
  }
340
364
  }
341
- function managedAttemptInvocation(checkId, step, environment) {
342
- const playwrightConfig = environment?.FORGE_PLAYWRIGHT_CONFIG?.trim();
343
- const attemptOwned = environment?.FORGE_E2E_OWNERSHIP_MODE === "attempt"
344
- || Boolean(environment?.FORGE_DISPATCH_ATTEMPT_ID?.trim());
345
- if (checkId !== "playwright-e2e" || !attemptOwned) {
346
- return step;
347
- }
348
- if (!playwrightConfig) {
349
- throw new ForgeFailureError("prepublication_capability_unavailable", "prepublication_capability_unavailable: playwright-e2e requires the Bridge-generated FORGE_PLAYWRIGHT_CONFIG for a managed attempt.", "bridge");
350
- }
351
- return {
352
- command: "pnpm",
353
- args: ["--dir", "tests/e2e", "exec", "playwright", "test", "--config", playwrightConfig],
354
- };
355
- }
356
- const nativeFallbackCheckIds = new Set([
357
- "owned-suite-registration",
358
- "dotnet-build-and-unit",
359
- "comment-repair-dotnet-regression",
360
- ]);
361
- const nativeFallbackDotnetTierScripts = [
362
- "scripts/run-dotnet-test-tier.ps1",
363
- "scripts/run-dotnet-test-tier-set.ps1",
364
- "scripts/run-affected-dotnet-tests.mjs",
365
- ];
366
- function supportsNativeTestPostgresFallback(check) {
367
- return nativeFallbackCheckIds.has(check.id);
368
- }
369
- function validationExecutionForStep(checkId, step, execution, postgresAdminConnection) {
370
- // The connection only exists when Docker is unavailable and the operator
371
- // provisioned a dedicated native test cluster. Only the runner-authored
372
- // .NET test tiers and the suite-identity check receive it; build, client,
373
- // Bridge, and E2E steps never do.
374
- if (!postgresAdminConnection || !nativeFallbackCheckIds.has(checkId))
375
- return execution;
376
- const runsDotnetTier = step.args.some(argument => nativeFallbackDotnetTierScripts
377
- .some(script => argument.replaceAll("\\", "/").endsWith(script)));
378
- if (checkId !== "owned-suite-registration" && !runsDotnetTier)
379
- return execution;
380
- return {
381
- ...execution,
382
- environment: {
383
- ...execution?.environment,
384
- ...nativeTestPostgresFallbackEnvironment(parseNativeTestPostgresFallback(postgresAdminConnection)),
385
- },
386
- };
387
- }
388
365
  function environmentValue(environment, name) {
389
366
  return Object.prototype.hasOwnProperty.call(environment ?? {}, name)
390
367
  ? environment?.[name]?.trim() ?? ""
@@ -406,6 +383,7 @@ function validationExactSecrets(environment) {
406
383
  return [
407
384
  environment?.[hostRuntimeTestPostgresAdminEnvironment]?.trim() ?? "",
408
385
  environment?.[hostRuntimeLegacyTestPostgresEnvironment]?.trim() ?? "",
386
+ environment?.[hostRuntimeTestPostgresProvisionerEnvironment]?.trim() ?? "",
409
387
  ...attemptDatabaseCapabilitySecrets(environment?.[attemptDatabaseCapabilityEnvironment]),
410
388
  ].filter((value, index, values) => value.length > 0 && values.indexOf(value) === index);
411
389
  }
@@ -538,6 +516,7 @@ function withoutPrivilegedPostgresEnvironment(environment) {
538
516
  const privilegedNames = new Set([
539
517
  hostRuntimeTestPostgresAdminEnvironment.toLowerCase(),
540
518
  hostRuntimeLegacyTestPostgresEnvironment.toLowerCase(),
519
+ hostRuntimeTestPostgresProvisionerEnvironment.toLowerCase(),
541
520
  ]);
542
521
  return Object.fromEntries(Object.entries(environment)
543
522
  .filter(([name]) => !privilegedNames.has(name.toLowerCase())));
@@ -607,6 +586,12 @@ function canonicalizeJson(value) {
607
586
  }
608
587
  return value;
609
588
  }
610
- function validationEvent(eventType, checkId, content) {
611
- return { role: "runner", kind: "checkpoint", content, eventType, data: JSON.stringify({ checkId, contractId: "forge-ci-parity-v1" }) };
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
+ };
612
597
  }
@@ -2,6 +2,7 @@ import { GitClient } from "../../shared/git/git.js";
2
2
  import { type CompletionPhase, type CompletionToolRuntime, type DebugCompletionPhase, type QaCompletionGate } from "../phase-completion.js";
3
3
  import type { RunOnceDispatchPacket, RunnerDispatchArtifact, RunnerDispatchSidecar } from "../session.types.js";
4
4
  import type { ProviderCliRunContext } from "./provider-cli.types.js";
5
+ import { type ProviderProcessRunResult } from "./provider-cli.process.js";
5
6
  export declare function emitDraftGateArtifacts(emit: ProviderCliRunContext["emit"], worktreePath: string, workItemId: string): Promise<void>;
6
7
  export declare function emitDecomposeGateArtifacts(emit: ProviderCliRunContext["emit"], worktreePath: string, workItemId: string): Promise<void>;
7
8
  export declare function fileExists(filePath: string): Promise<boolean>;
@@ -91,5 +92,5 @@ export declare class LiveCompletionArtifactEmitter {
91
92
  private pollQueued;
92
93
  private poll;
93
94
  }
94
- export declare function readCompletionArtifactsForRun(worktreePath: string, workItemId: string, phase: CompletionPhase, developCycle: boolean, debugCycle: boolean): Promise<RunnerDispatchArtifact[]>;
95
+ export declare function readCompletionArtifactsForRun(worktreePath: string, workItemId: string, phase: CompletionPhase, developCycle: boolean, debugCycle: boolean, providerResult?: Pick<ProviderProcessRunResult, "terminalStopReason"> | null): Promise<RunnerDispatchArtifact[]>;
95
96
  export {};
@@ -2,12 +2,14 @@ import fs from "node:fs/promises";
2
2
  import path from "node:path";
3
3
  import { artifactRootFor, artifactRootForOwner, debugCompletionPhaseOrder, draftCompletionGateOrder, qaCompletionGateOrder, readCompletionArtifact } from "../phase-completion.js";
4
4
  import { ensureNoSymbolicLinkPathSegments, isPathUnderRoot, sha256File } from "../qa-sidecar-validation.js";
5
+ import { isRuntimeOnlyPath, stagePublishableWorktreeChangeSet } from "../publishable-worktree-changes.js";
6
+ import { providerCompletionToolMissingFailure } from "./provider-cli.process.js";
5
7
  import { hasLaunchTarget } from "./provider-cli.qa-sidecars.js";
6
8
  import { clip, isNodeError, messageFromError, normalizedString, parseJsonLine, stringField } from "./provider-output-state.js";
9
+ import { assertMergeResolutionPreservesUpstreamChanges, isMergeInProgress, mergeResolutionCommitNotes } from "./provider-cli.merge-integrity.js";
7
10
  const maxTransportedQaSidecarBytes = 8 * 1024 * 1024;
8
11
  const maxTransportedQaSidecarsTotalBytes = 16 * 1024 * 1024;
9
12
  const developCyclePhaseOrder = ["implementation", "self_review", "validation"];
10
- const nonPublishableWorktreePaths = [".forge", ".local"];
11
13
  export async function emitDraftGateArtifacts(emit, worktreePath, workItemId) {
12
14
  const draftArtifactFiles = {
13
15
  draft_intent: "draft.intent.json",
@@ -150,21 +152,25 @@ export async function cleanupCompletionTools(completionTools, emit) {
150
152
  }
151
153
  export async function commitWorktreeChanges(git, worktreePath, workItemId, alreadyStagedChangedFiles) {
152
154
  const changedFiles = alreadyStagedChangedFiles ?? await stagePublishableWorktreeChanges(git, worktreePath);
153
- if (changedFiles.length > 0) {
154
- await git.run(worktreePath, ["commit", "-m", `provider cli changeset for ${workItemId.slice(0, 8)}`]);
155
+ const mergeReport = await assertMergeResolutionPreservesUpstreamChanges(git, worktreePath, { ignorePath: isRuntimeOnlyPath });
156
+ // A merge is always finalized, even when every change it brought is unpublishable
157
+ // runtime output; skipping the commit would leave MERGE_HEAD dangling.
158
+ const merging = await isMergeInProgress(git, worktreePath);
159
+ if (changedFiles.length > 0 || merging) {
160
+ const notes = mergeResolutionCommitNotes(mergeReport).flatMap(note => ["-m", note]);
161
+ await git.run(worktreePath, [
162
+ "commit",
163
+ ...(changedFiles.length === 0 ? ["--allow-empty"] : []),
164
+ "-m",
165
+ `provider cli changeset for ${workItemId.slice(0, 8)}`,
166
+ ...notes,
167
+ ]);
155
168
  }
156
169
  const commitSha = (await git.run(worktreePath, ["rev-parse", "HEAD"])).trim();
157
170
  return { commitSha, changedFiles };
158
171
  }
159
172
  export async function stagePublishableWorktreeChanges(git, worktreePath) {
160
- await git.run(worktreePath, ["add", "-A"]);
161
- for (const reservedPath of nonPublishableWorktreePaths) {
162
- await git.run(worktreePath, ["reset", "--", reservedPath]).catch(() => "");
163
- }
164
- return (await git.run(worktreePath, ["diff", "--cached", "--name-only"]))
165
- .split(/\r?\n/)
166
- .map((line) => line.trim())
167
- .filter(Boolean);
173
+ return (await stagePublishableWorktreeChangeSet(git, worktreePath)).publishable;
168
174
  }
169
175
  export function phaseCompleteEventType(phase) {
170
176
  return phase === "implementation" ? "implementation_complete" : `${phase}_complete`;
@@ -779,11 +785,11 @@ export class LiveCompletionArtifactEmitter {
779
785
  }
780
786
  }
781
787
  }
782
- export async function readCompletionArtifactsForRun(worktreePath, workItemId, phase, developCycle, debugCycle) {
788
+ export async function readCompletionArtifactsForRun(worktreePath, workItemId, phase, developCycle, debugCycle, providerResult) {
783
789
  if (!developCycle && !debugCycle) {
784
790
  const artifact = await readCompletionArtifact(worktreePath, workItemId, phase);
785
791
  if (!artifact) {
786
- throw new Error(`Provider CLI completed but did not call the Forge ${phase} completion tool.`);
792
+ throw providerCompletionToolMissingFailure(`Provider CLI completed but did not call the Forge ${phase} completion tool.`, providerResult);
787
793
  }
788
794
  return [artifact];
789
795
  }
@@ -795,11 +801,11 @@ export async function readCompletionArtifactsForRun(worktreePath, workItemId, ph
795
801
  const artifact = await readCompletionArtifact(worktreePath, workItemId, expectedPhase);
796
802
  if (!artifact) {
797
803
  if (artifacts.length === 0) {
798
- throw new Error(`Provider CLI completed but did not call the Forge ${expectedPhase} completion tool.`);
804
+ throw providerCompletionToolMissingFailure(`Provider CLI completed but did not call the Forge ${expectedPhase} completion tool.`, providerResult);
799
805
  }
800
806
  const previous = artifacts[artifacts.length - 1];
801
807
  if ((previous.status ?? "").trim().toLowerCase() === "pass") {
802
- throw new Error(`Provider CLI completed after ${previous.phase} passed but did not call the Forge ${expectedPhase} completion tool.`);
808
+ throw providerCompletionToolMissingFailure(`Provider CLI completed after ${previous.phase} passed but did not call the Forge ${expectedPhase} completion tool.`, providerResult);
803
809
  }
804
810
  return artifacts;
805
811
  }
@@ -0,0 +1,89 @@
1
+ import type { GitClient } from "../../shared/git/git.js";
2
+ import { ForgeFailureError } from "../session.types.js";
3
+ /**
4
+ * Publication guards for a provider-run `git merge --no-commit` that Forge Bridge
5
+ * turns into the final merge commit (the conflict-resolve lane, and any repair
6
+ * lane that merges the target branch).
7
+ *
8
+ * Forge stages with `git add -A` and then unstages worktree-local runtime paths
9
+ * such as `.forge` and `.local`. Unstaging resets those paths to HEAD, which is
10
+ * the story side of the merge. Without these guards that silently reverted every
11
+ * upstream change under those paths and re-added files the target branch had
12
+ * deleted (issue #491: 253 files on story/829e1219ee16 and story/6ac8c6c6e704).
13
+ */
14
+ type GitRunner = Pick<GitClient, "run">;
15
+ export interface InProgressMerge {
16
+ readonly headSha: string;
17
+ readonly mergeHeadSha: string;
18
+ readonly mergeBaseSha: string;
19
+ }
20
+ export interface MergeResolutionReport {
21
+ /**
22
+ * Paths the target branch deleted that the story had changed and that the
23
+ * resolution keeps. These are deliberate modify/delete decisions, recorded in
24
+ * the merge commit message so reviewers see them.
25
+ */
26
+ readonly keptOverUpstreamDeletion: readonly string[];
27
+ }
28
+ export type UnresolvedMergeConflictKind = "deleted_by_upstream" | "deleted_by_story" | "missing_while_unmerged" | "unresolved_binary" | "conflict_markers";
29
+ export interface UnresolvedMergeConflict {
30
+ readonly path: string;
31
+ readonly kind: UnresolvedMergeConflictKind;
32
+ }
33
+ /**
34
+ * The publication would re-add files that the target branch deleted, or revert
35
+ * target-branch edits, on paths the story never changed. Forge refuses to commit
36
+ * or push such a merge.
37
+ */
38
+ export declare class MergeResolutionRevertsUpstreamChangesError extends ForgeFailureError {
39
+ readonly merge: InProgressMerge;
40
+ readonly resurrectedPaths: readonly string[];
41
+ readonly revertedPaths: readonly string[];
42
+ readonly code = "merge_resolution_reverts_upstream_changes";
43
+ constructor(merge: InProgressMerge, resurrectedPaths: readonly string[], revertedPaths: readonly string[]);
44
+ }
45
+ /**
46
+ * A conflict is still unresolved when Forge would stage the merge: a
47
+ * modify/delete conflict nobody decided (`git add -A` would silently keep the
48
+ * modified side), or a content conflict whose file still has conflict markers
49
+ * (`git add -A` would commit them).
50
+ */
51
+ export declare class MergeResolutionUnresolvedConflictError extends ForgeFailureError {
52
+ readonly conflicts: readonly UnresolvedMergeConflict[];
53
+ readonly code = "merge_resolution_unresolved_conflict";
54
+ constructor(conflicts: readonly UnresolvedMergeConflict[]);
55
+ }
56
+ /** True while MERGE_HEAD exists, whether or not the histories share a merge base. */
57
+ export declare function isMergeInProgress(git: GitRunner, worktreePath: string): Promise<boolean>;
58
+ export declare function readInProgressMerge(git: GitRunner, worktreePath: string): Promise<InProgressMerge | null>;
59
+ /**
60
+ * Fails before `git add -A` can silently resolve a conflict:
61
+ * - a modify/delete conflict, by keeping whatever is on disk;
62
+ * - a binary (or other marker-less) conflict, by staging whichever side is on disk;
63
+ * - a content conflict, by staging its conflict markers. This includes markers
64
+ * the provider already staged, which clears the unmerged stages, so every path
65
+ * both sides changed is checked too.
66
+ * A text conflict the agent resolved in the working tree without `git add` is
67
+ * still unmerged here and is accepted once its markers are gone.
68
+ */
69
+ export declare function assertNoUnresolvedMergeConflicts(git: GitRunner, worktreePath: string): Promise<void>;
70
+ export declare function readUnresolvedMergeConflicts(git: GitRunner, worktreePath: string, merge: InProgressMerge): Promise<readonly UnresolvedMergeConflict[]>;
71
+ /**
72
+ * Staging excludes some worktree changes (Forge runtime output) by unstaging them
73
+ * back to HEAD. During a merge HEAD is the story side, so an excluded path the merge
74
+ * itself changed would lose the target's change. Given the excluded candidate
75
+ * paths, put the merge-owned ones back into the index: the target branch's version
76
+ * where the story never touched the path, and the agent's working-tree resolution
77
+ * where both sides changed it. Returns the restored paths; the rest stay excluded.
78
+ */
79
+ export declare function restoreMergeOwnedPaths(git: GitRunner, worktreePath: string, candidatePaths: readonly string[]): Promise<readonly string[]>;
80
+ /**
81
+ * Final check on the index Forge is about to commit. Throws when the merge
82
+ * resolution re-adds a path the target branch deleted, or drops a target-branch
83
+ * edit, on a path the story never changed.
84
+ */
85
+ export declare function assertMergeResolutionPreservesUpstreamChanges(git: GitRunner, worktreePath: string, options?: {
86
+ readonly ignorePath?: (filePath: string) => boolean;
87
+ }): Promise<MergeResolutionReport>;
88
+ export declare function mergeResolutionCommitNotes(report: MergeResolutionReport): readonly string[];
89
+ export {};