@loucompanion/forge-bridge 0.1.4-dev.9ddc336f8a9d → 0.1.4-dev.a5a3a7ab2f02
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.
- package/README.md +35 -2
- package/dist/bridge/bridge.base.d.ts +9 -0
- package/dist/bridge/bridge.service.d.ts +72 -1
- package/dist/bridge/bridge.service.js +308 -9
- package/dist/bridge/bridge.types.d.ts +16 -0
- package/dist/bridge/local-yield-flag.d.ts +6 -0
- package/dist/bridge/local-yield-flag.js +34 -0
- package/dist/bridge/runner-host-capabilities.d.ts +2 -0
- package/dist/bridge/runner-host-capabilities.js +4 -0
- package/dist/bridge/test-postgres-capability.d.ts +14 -0
- package/dist/bridge/test-postgres-capability.js +120 -0
- package/dist/cleanup/cleanup.service.d.ts +9 -0
- package/dist/cleanup/cleanup.service.js +72 -109
- package/dist/cleanup/cleanup.types.d.ts +4 -0
- package/dist/cleanup/forge-owned-paths.d.ts +9 -0
- package/dist/cleanup/forge-owned-paths.js +53 -0
- package/dist/cleanup/host-runtime-ledger.d.ts +5 -0
- package/dist/cleanup/host-runtime-ledger.js +109 -0
- package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
- package/dist/cleanup/managed-branch-sweep.js +111 -0
- package/dist/cli/cli.help.js +18 -0
- package/dist/cli/cli.service.d.ts +16 -0
- package/dist/cli/cli.service.js +142 -16
- package/dist/cli/local-config.d.ts +4 -0
- package/dist/cli/local-config.js +26 -4
- package/dist/runtime/aspnet-runtime-prebuild.js +94 -6
- package/dist/runtime/host-load-admission.d.ts +60 -0
- package/dist/runtime/host-load-admission.js +99 -0
- package/dist/runtime/host-load-child-environment.d.ts +22 -0
- package/dist/runtime/host-load-child-environment.js +67 -0
- package/dist/runtime/host-load-forge-cgroups.d.ts +49 -0
- package/dist/runtime/host-load-forge-cgroups.js +140 -0
- package/dist/runtime/host-load-governor-config.d.ts +43 -0
- package/dist/runtime/host-load-governor-config.js +76 -0
- package/dist/runtime/host-load-governor.d.ts +174 -0
- package/dist/runtime/host-load-governor.js +541 -0
- package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
- package/dist/runtime/host-load-ledger-lock.js +185 -0
- package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
- package/dist/runtime/host-load-runtime-settings.js +78 -0
- package/dist/runtime/host-load-sampler.d.ts +43 -0
- package/dist/runtime/host-load-sampler.js +74 -6
- package/dist/runtime/host-load-step-class.d.ts +68 -0
- package/dist/runtime/host-load-step-class.js +106 -0
- package/dist/runtime/host-load-step-reaper.d.ts +27 -0
- package/dist/runtime/host-load-step-reaper.js +95 -0
- package/dist/runtime/host-load-step-run.d.ts +73 -0
- package/dist/runtime/host-load-step-run.js +102 -0
- package/dist/runtime/host-load-token-ledger.d.ts +174 -0
- package/dist/runtime/host-load-token-ledger.js +421 -0
- package/dist/runtime/host-pressure-stall.d.ts +21 -1
- package/dist/runtime/host-pressure-stall.js +48 -1
- package/dist/runtime/host-runtime-contract.d.ts +3 -0
- package/dist/runtime/host-runtime-contract.js +4 -1
- package/dist/runtime/host-runtime-lease.d.ts +74 -4
- package/dist/runtime/host-runtime-lease.js +281 -11
- package/dist/runtime/host-runtime-promotion.d.ts +23 -0
- package/dist/runtime/host-runtime-promotion.js +48 -0
- package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
- package/dist/runtime/host-runtime-requirements-check.js +29 -0
- package/dist/runtime/host-runtime-requirements.d.ts +36 -0
- package/dist/runtime/host-runtime-requirements.js +117 -0
- package/dist/runtime/playwright-host-runtime-adapter.d.ts +7 -0
- package/dist/runtime/playwright-host-runtime-adapter.js +13 -1
- package/dist/runtime/runner-settings.d.ts +100 -0
- package/dist/runtime/runner-settings.js +214 -0
- package/dist/sandbox/host-capacity-broker.d.ts +107 -0
- package/dist/sandbox/host-capacity-broker.js +315 -0
- package/dist/sandbox/runtime.d.ts +10 -1
- package/dist/sandbox/runtime.js +45 -2
- package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
- package/dist/sandbox/sandbox-cgroups.js +42 -0
- package/dist/session/managed-attempt-tools.d.ts +2 -0
- package/dist/session/managed-attempt-tools.js +156 -37
- package/dist/session/managed-command-host-load.d.ts +45 -0
- package/dist/session/managed-command-host-load.js +82 -0
- package/dist/session/mcp-argument-coercion.d.ts +23 -0
- package/dist/session/mcp-argument-coercion.js +121 -0
- package/dist/session/phase-completion.artifacts.d.ts +7 -0
- package/dist/session/phase-completion.artifacts.js +98 -25
- package/dist/session/phase-completion.command-validation.d.ts +7 -0
- package/dist/session/phase-completion.command-validation.js +77 -0
- package/dist/session/phase-completion.d.ts +4 -0
- package/dist/session/phase-completion.helpers.js +13 -12
- package/dist/session/phase-completion.js +4 -0
- package/dist/session/phase-completion.prompts.js +6 -1
- package/dist/session/phase-completion.runtime.d.ts +5 -3
- package/dist/session/phase-completion.runtime.js +49 -19
- package/dist/session/phase-completion.schema-parts.d.ts +19 -0
- package/dist/session/phase-completion.schema-parts.js +188 -0
- package/dist/session/phase-completion.schemas.d.ts +3 -3
- package/dist/session/phase-completion.schemas.js +184 -209
- package/dist/session/phase-completion.validation.d.ts +2 -3
- package/dist/session/phase-completion.validation.js +46 -92
- package/dist/session/pre-publication-host-load.d.ts +27 -0
- package/dist/session/pre-publication-host-load.js +111 -0
- package/dist/session/pre-publication-process.d.ts +3 -0
- package/dist/session/pre-publication-process.js +23 -11
- package/dist/session/pre-publication-step-execution.d.ts +11 -0
- package/dist/session/pre-publication-step-execution.js +49 -0
- package/dist/session/pre-publication-validation.d.ts +9 -9
- package/dist/session/pre-publication-validation.js +21 -55
- package/dist/session/provider-cli/provider-cli.artifacts.d.ts +2 -1
- package/dist/session/provider-cli/provider-cli.artifacts.js +21 -15
- package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
- package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
- package/dist/session/provider-cli/provider-cli.process.d.ts +32 -1
- package/dist/session/provider-cli/provider-cli.process.js +122 -30
- package/dist/session/provider-cli/provider-cli.prompts.d.ts +5 -0
- package/dist/session/provider-cli/provider-cli.prompts.js +20 -2
- package/dist/session/provider-cli/provider-cli.service.d.ts +6 -0
- package/dist/session/provider-cli/provider-cli.service.js +237 -33
- package/dist/session/provider-cli/provider-cli.types.d.ts +30 -0
- package/dist/session/provider-cli/provider-in-flight-work.d.ts +6 -0
- package/dist/session/provider-cli/provider-in-flight-work.js +47 -0
- package/dist/session/provider-cli/provider-output-state.d.ts +6 -0
- package/dist/session/provider-cli/provider-output-state.js +9 -0
- package/dist/session/publishable-worktree-changes.d.ts +54 -0
- package/dist/session/publishable-worktree-changes.js +193 -0
- package/dist/session/sandbox-host-capacity-gate.d.ts +30 -0
- package/dist/session/sandbox-host-capacity-gate.js +229 -0
- package/dist/session/session.base.d.ts +9 -1
- package/dist/session/session.service.d.ts +9 -2
- package/dist/session/session.service.js +120 -5
- package/dist/session/session.types.d.ts +3 -0
- package/dist/session/session.types.js +15 -3
- package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
- package/dist/session/workspace-runtime-fingerprint.js +138 -0
- package/dist/shared/process/host-process-supervisor.d.ts +1 -0
- package/dist/shared/process/host-process-supervisor.js +1 -1
- package/dist/shared/process/process-tree.d.ts +52 -0
- package/dist/shared/process/process-tree.js +144 -0
- package/dist/shared/process/process.d.ts +67 -0
- package/dist/shared/process/process.js +213 -11
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/dist/worktree/dependency-warmer.d.ts +25 -0
- package/dist/worktree/dependency-warmer.js +46 -10
- package/dist/worktree/worktree.service.d.ts +10 -1
- package/dist/worktree/worktree.service.js +42 -2
- package/dist/worktree/worktree.types.d.ts +7 -0
- package/package.json +2 -2
|
@@ -3,11 +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 {
|
|
6
|
+
import { runHostGovernedValidationStep } from "./pre-publication-host-load.js";
|
|
7
|
+
import { managedAttemptInvocation, supportsNativeTestPostgresFallback, validationExecutionForStep, } from "./pre-publication-step-execution.js";
|
|
7
8
|
import { hostRuntimeLegacyTestPostgresEnvironment, hostRuntimeTestPostgresAdminEnvironment, hostRuntimeTestPostgresProvisionerEnvironment, } from "../runtime/host-runtime-contract.js";
|
|
8
9
|
import { redactText } from "../shared/redaction/redaction.js";
|
|
9
10
|
import { describeSkippedTests, mergeSkippedTests, readSkippedTests, } from "./pre-publication-skipped-tests.js";
|
|
10
11
|
import { ProcessPrePublicationCommandRunner, pnpmDirectoryLaunch } from "./pre-publication-process.js";
|
|
12
|
+
import { ProcessTreeTerminationError } from "../shared/process/process.js";
|
|
11
13
|
import { findUnreferencedNewExports } from "./unreferenced-exports.js";
|
|
12
14
|
import { ForgeFailureError, sanitizeFailureError, } from "./session.types.js";
|
|
13
15
|
const contractRelativePath = ".forge/validation/ci-parity.v1.json";
|
|
@@ -84,10 +86,12 @@ export class PrePublicationValidator {
|
|
|
84
86
|
commands;
|
|
85
87
|
dockerEngineProbe;
|
|
86
88
|
nativeTestPostgresFallback;
|
|
87
|
-
|
|
89
|
+
hostLoad;
|
|
90
|
+
constructor(commands = new ProcessPrePublicationCommandRunner(), dockerEngineProbe, nativeTestPostgresFallback = () => null, hostLoad) {
|
|
88
91
|
this.commands = commands;
|
|
89
92
|
this.dockerEngineProbe = dockerEngineProbe;
|
|
90
93
|
this.nativeTestPostgresFallback = nativeTestPostgresFallback;
|
|
94
|
+
this.hostLoad = hostLoad;
|
|
91
95
|
}
|
|
92
96
|
async validate(worktreePath, profile, capabilities, emit, signal, execution) {
|
|
93
97
|
const checksExports = profile === "implementation" || profile === "comment_repair";
|
|
@@ -130,11 +134,11 @@ export class PrePublicationValidator {
|
|
|
130
134
|
let skipped = { count: 0, reasons: [] };
|
|
131
135
|
for (const step of check.steps) {
|
|
132
136
|
const stepStartedMs = Date.now() - 1000;
|
|
133
|
-
let result = await this.runStep(check.id, step, worktreePath, signal, scoped.execution, postgresAdminConnection);
|
|
137
|
+
let result = await this.runStep(check.id, step, worktreePath, signal, scoped.execution, postgresAdminConnection, emit);
|
|
134
138
|
await this.throwIfPrerequisiteWasLost(check, result, scoped.execution?.environment, postgresAdminConnection, emit);
|
|
135
139
|
if (isTimeoutOnlyClientTestFailure(check.id, step, result)) {
|
|
136
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."));
|
|
137
|
-
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);
|
|
138
142
|
await this.throwIfPrerequisiteWasLost(check, result, scoped.execution?.environment, postgresAdminConnection, emit);
|
|
139
143
|
await emit?.(validationEvent(result.exitCode === 0
|
|
140
144
|
? "prepublication_validation_timeout_confirmation_passed"
|
|
@@ -144,7 +148,7 @@ export class PrePublicationValidator {
|
|
|
144
148
|
}
|
|
145
149
|
if (isTransientBridgeCleanupFailure(check.id, step, result)) {
|
|
146
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."));
|
|
147
|
-
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);
|
|
148
152
|
await this.throwIfPrerequisiteWasLost(check, result, scoped.execution?.environment, postgresAdminConnection, emit);
|
|
149
153
|
await emit?.(validationEvent(result.exitCode === 0
|
|
150
154
|
? "prepublication_validation_cleanup_confirmation_passed"
|
|
@@ -154,7 +158,7 @@ export class PrePublicationValidator {
|
|
|
154
158
|
}
|
|
155
159
|
if (isTransientShellInfrastructureFailure(result)) {
|
|
156
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."));
|
|
157
|
-
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);
|
|
158
162
|
await this.throwIfPrerequisiteWasLost(check, result, scoped.execution?.environment, postgresAdminConnection, emit);
|
|
159
163
|
const infrastructureFailed = isTransientShellInfrastructureFailure(result);
|
|
160
164
|
await emit?.(validationEvent(infrastructureFailed
|
|
@@ -213,7 +217,7 @@ export class PrePublicationValidator {
|
|
|
213
217
|
const snapshot = await this.dockerEngineProbe.ensureAvailableForRequiredWork();
|
|
214
218
|
if (!snapshot.available) {
|
|
215
219
|
const detail = `Docker prerequisite unavailable (${snapshot.unavailableCode ?? "docker_engine_unavailable"}): ${snapshot.unavailableReason ?? "the daemon did not pass a fresh readiness probe"}`;
|
|
216
|
-
const fallback = check.requiredPrerequisite === "isolated_postgres" && supportsNativeTestPostgresFallback(check)
|
|
220
|
+
const fallback = check.requiredPrerequisite === "isolated_postgres" && supportsNativeTestPostgresFallback(check.id)
|
|
217
221
|
? this.nativeTestPostgresFallback()
|
|
218
222
|
: null;
|
|
219
223
|
if (fallback) {
|
|
@@ -299,8 +303,14 @@ export class PrePublicationValidator {
|
|
|
299
303
|
throw new ForgeFailureError("prepublication_contract_invalid", `prepublication_contract_invalid: the CI parity contract changed after dispatch (baseline ${baselineDigest}, worktree ${contractDigest}).`, "bridge");
|
|
300
304
|
}
|
|
301
305
|
}
|
|
302
|
-
async runStep(checkId, step, cwd, signal, execution, postgresAdminConnection) {
|
|
306
|
+
async runStep(checkId, step, cwd, signal, execution, postgresAdminConnection, emit) {
|
|
303
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) {
|
|
304
314
|
const stepExecution = validationExecutionForStep(checkId, step, execution, postgresAdminConnection);
|
|
305
315
|
const before = await readValidationFiles(cwd, step.assertUnchangedPaths ?? []);
|
|
306
316
|
const result = await this.runCommand(invocation.command, invocation.args, cwd, signal, stepExecution);
|
|
@@ -345,57 +355,13 @@ export class PrePublicationValidator {
|
|
|
345
355
|
};
|
|
346
356
|
}
|
|
347
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;
|
|
348
361
|
throw sanitizeFailureError(error, exactSecrets);
|
|
349
362
|
}
|
|
350
363
|
}
|
|
351
364
|
}
|
|
352
|
-
function managedAttemptInvocation(checkId, step, environment) {
|
|
353
|
-
const playwrightConfig = environment?.FORGE_PLAYWRIGHT_CONFIG?.trim();
|
|
354
|
-
const attemptOwned = environment?.FORGE_E2E_OWNERSHIP_MODE === "attempt"
|
|
355
|
-
|| Boolean(environment?.FORGE_DISPATCH_ATTEMPT_ID?.trim());
|
|
356
|
-
if (checkId !== "playwright-e2e" || !attemptOwned) {
|
|
357
|
-
return step;
|
|
358
|
-
}
|
|
359
|
-
if (!playwrightConfig) {
|
|
360
|
-
throw new ForgeFailureError("prepublication_capability_unavailable", "prepublication_capability_unavailable: playwright-e2e requires the Bridge-generated FORGE_PLAYWRIGHT_CONFIG for a managed attempt.", "bridge");
|
|
361
|
-
}
|
|
362
|
-
return {
|
|
363
|
-
command: "pnpm",
|
|
364
|
-
args: ["--dir", "tests/e2e", "exec", "playwright", "test", "--config", playwrightConfig],
|
|
365
|
-
};
|
|
366
|
-
}
|
|
367
|
-
const nativeFallbackCheckIds = new Set([
|
|
368
|
-
"owned-suite-registration",
|
|
369
|
-
"dotnet-build-and-unit",
|
|
370
|
-
"comment-repair-dotnet-regression",
|
|
371
|
-
]);
|
|
372
|
-
const nativeFallbackDotnetTierScripts = [
|
|
373
|
-
"scripts/run-dotnet-test-tier.ps1",
|
|
374
|
-
"scripts/run-dotnet-test-tier-set.ps1",
|
|
375
|
-
"scripts/run-affected-dotnet-tests.mjs",
|
|
376
|
-
];
|
|
377
|
-
function supportsNativeTestPostgresFallback(check) {
|
|
378
|
-
return nativeFallbackCheckIds.has(check.id);
|
|
379
|
-
}
|
|
380
|
-
function validationExecutionForStep(checkId, step, execution, postgresAdminConnection) {
|
|
381
|
-
// The connection only exists when Docker is unavailable and the operator
|
|
382
|
-
// provisioned a dedicated native test cluster. Only the runner-authored
|
|
383
|
-
// .NET test tiers and the suite-identity check receive it; build, client,
|
|
384
|
-
// Bridge, and E2E steps never do.
|
|
385
|
-
if (!postgresAdminConnection || !nativeFallbackCheckIds.has(checkId))
|
|
386
|
-
return execution;
|
|
387
|
-
const runsDotnetTier = step.args.some(argument => nativeFallbackDotnetTierScripts
|
|
388
|
-
.some(script => argument.replaceAll("\\", "/").endsWith(script)));
|
|
389
|
-
if (checkId !== "owned-suite-registration" && !runsDotnetTier)
|
|
390
|
-
return execution;
|
|
391
|
-
return {
|
|
392
|
-
...execution,
|
|
393
|
-
environment: {
|
|
394
|
-
...execution?.environment,
|
|
395
|
-
...nativeTestPostgresFallbackEnvironment(parseNativeTestPostgresFallback(postgresAdminConnection)),
|
|
396
|
-
},
|
|
397
|
-
};
|
|
398
|
-
}
|
|
399
365
|
function environmentValue(environment, name) {
|
|
400
366
|
return Object.prototype.hasOwnProperty.call(environment ?? {}, name)
|
|
401
367
|
? environment?.[name]?.trim() ?? ""
|
|
@@ -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
|
-
|
|
154
|
-
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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 {};
|
|
@@ -0,0 +1,310 @@
|
|
|
1
|
+
import fs from "node:fs/promises";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { ForgeFailureError } from "../session.types.js";
|
|
4
|
+
const maxListedPaths = 20;
|
|
5
|
+
const pathArgumentChunkSize = 100;
|
|
6
|
+
const objectIdPattern = /^[0-9a-f]{40}(?:[0-9a-f]{24})?$/iu;
|
|
7
|
+
/**
|
|
8
|
+
* The publication would re-add files that the target branch deleted, or revert
|
|
9
|
+
* target-branch edits, on paths the story never changed. Forge refuses to commit
|
|
10
|
+
* or push such a merge.
|
|
11
|
+
*/
|
|
12
|
+
export class MergeResolutionRevertsUpstreamChangesError extends ForgeFailureError {
|
|
13
|
+
merge;
|
|
14
|
+
resurrectedPaths;
|
|
15
|
+
revertedPaths;
|
|
16
|
+
code = "merge_resolution_reverts_upstream_changes";
|
|
17
|
+
constructor(merge, resurrectedPaths, revertedPaths) {
|
|
18
|
+
super("merge_resolution_reverts_upstream_changes", describeRevertedUpstreamChanges(merge, resurrectedPaths, revertedPaths), "bridge");
|
|
19
|
+
this.merge = merge;
|
|
20
|
+
this.resurrectedPaths = resurrectedPaths;
|
|
21
|
+
this.revertedPaths = revertedPaths;
|
|
22
|
+
this.name = "MergeResolutionRevertsUpstreamChangesError";
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* A conflict is still unresolved when Forge would stage the merge: a
|
|
27
|
+
* modify/delete conflict nobody decided (`git add -A` would silently keep the
|
|
28
|
+
* modified side), or a content conflict whose file still has conflict markers
|
|
29
|
+
* (`git add -A` would commit them).
|
|
30
|
+
*/
|
|
31
|
+
export class MergeResolutionUnresolvedConflictError extends ForgeFailureError {
|
|
32
|
+
conflicts;
|
|
33
|
+
code = "merge_resolution_unresolved_conflict";
|
|
34
|
+
constructor(conflicts) {
|
|
35
|
+
super("merge_resolution_unresolved_conflict", `merge_resolution_unresolved_conflict: ${conflicts.length} merge conflict(s) were left unresolved: ${listPaths(conflicts.map(conflict => `${conflict.path} (${conflict.kind.replaceAll("_", " ")})`))}. Resolve content conflicts by removing every conflict marker, and resolve each modify/delete or binary conflict explicitly with \`git rm <path>\` to accept the deletion or \`git add <path>\` to stage the chosen file; Forge did not commit or push the merge.`, "bridge");
|
|
36
|
+
this.conflicts = conflicts;
|
|
37
|
+
this.name = "MergeResolutionUnresolvedConflictError";
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
/** True while MERGE_HEAD exists, whether or not the histories share a merge base. */
|
|
41
|
+
export async function isMergeInProgress(git, worktreePath) {
|
|
42
|
+
return await tryRevParse(git, worktreePath, "MERGE_HEAD") !== null;
|
|
43
|
+
}
|
|
44
|
+
export async function readInProgressMerge(git, worktreePath) {
|
|
45
|
+
const mergeHeadSha = await tryRevParse(git, worktreePath, "MERGE_HEAD");
|
|
46
|
+
if (!mergeHeadSha)
|
|
47
|
+
return null;
|
|
48
|
+
const headSha = await tryRevParse(git, worktreePath, "HEAD");
|
|
49
|
+
if (!headSha)
|
|
50
|
+
return null;
|
|
51
|
+
let mergeBaseSha;
|
|
52
|
+
try {
|
|
53
|
+
mergeBaseSha = (await git.run(worktreePath, ["merge-base", headSha, mergeHeadSha])).trim();
|
|
54
|
+
}
|
|
55
|
+
catch {
|
|
56
|
+
// Unrelated histories have no merge base, so there is no upstream deletion to protect.
|
|
57
|
+
return null;
|
|
58
|
+
}
|
|
59
|
+
if (!objectIdPattern.test(mergeBaseSha))
|
|
60
|
+
return null;
|
|
61
|
+
return { headSha, mergeHeadSha, mergeBaseSha };
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Fails before `git add -A` can silently resolve a conflict:
|
|
65
|
+
* - a modify/delete conflict, by keeping whatever is on disk;
|
|
66
|
+
* - a binary (or other marker-less) conflict, by staging whichever side is on disk;
|
|
67
|
+
* - a content conflict, by staging its conflict markers. This includes markers
|
|
68
|
+
* the provider already staged, which clears the unmerged stages, so every path
|
|
69
|
+
* both sides changed is checked too.
|
|
70
|
+
* A text conflict the agent resolved in the working tree without `git add` is
|
|
71
|
+
* still unmerged here and is accepted once its markers are gone.
|
|
72
|
+
*/
|
|
73
|
+
export async function assertNoUnresolvedMergeConflicts(git, worktreePath) {
|
|
74
|
+
const merge = await readInProgressMerge(git, worktreePath);
|
|
75
|
+
if (!merge)
|
|
76
|
+
return;
|
|
77
|
+
const conflicts = await readUnresolvedMergeConflicts(git, worktreePath, merge);
|
|
78
|
+
if (conflicts.length > 0) {
|
|
79
|
+
throw new MergeResolutionUnresolvedConflictError(conflicts);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
export async function readUnresolvedMergeConflicts(git, worktreePath, merge) {
|
|
83
|
+
const stagesByPath = new Map();
|
|
84
|
+
for (const record of splitNul(await git.run(worktreePath, ["ls-files", "--unmerged", "-z"]))) {
|
|
85
|
+
const tab = record.indexOf("\t");
|
|
86
|
+
if (tab < 0)
|
|
87
|
+
continue;
|
|
88
|
+
const stage = record.slice(0, tab).trim().split(/\s+/u).at(-1) ?? "";
|
|
89
|
+
const filePath = record.slice(tab + 1);
|
|
90
|
+
const stages = stagesByPath.get(filePath) ?? new Set();
|
|
91
|
+
stages.add(stage);
|
|
92
|
+
stagesByPath.set(filePath, stages);
|
|
93
|
+
}
|
|
94
|
+
const conflicts = [];
|
|
95
|
+
const contentConflicts = [];
|
|
96
|
+
for (const [filePath, stages] of stagesByPath) {
|
|
97
|
+
const ours = stages.has("2");
|
|
98
|
+
const theirs = stages.has("3");
|
|
99
|
+
if (stages.has("1") && ours && !theirs)
|
|
100
|
+
conflicts.push({ path: filePath, kind: "deleted_by_upstream" });
|
|
101
|
+
else if (stages.has("1") && theirs && !ours)
|
|
102
|
+
conflicts.push({ path: filePath, kind: "deleted_by_story" });
|
|
103
|
+
else
|
|
104
|
+
contentConflicts.push(filePath);
|
|
105
|
+
}
|
|
106
|
+
const binaryByAttributes = await readBinaryByAttributes(git, worktreePath, contentConflicts);
|
|
107
|
+
for (const filePath of contentConflicts) {
|
|
108
|
+
const content = await readWorkingFile(worktreePath, filePath);
|
|
109
|
+
// `git add -A` would stage a missing file as a deletion and clear the conflict
|
|
110
|
+
// stages; only an explicit `git rm` or `git add` resolves it.
|
|
111
|
+
if (!content)
|
|
112
|
+
conflicts.push({ path: filePath, kind: "missing_while_unmerged" });
|
|
113
|
+
// Git writes no markers into a binary conflict (by content, or via `-merge` /
|
|
114
|
+
// `merge=binary`, as the `binary` macro sets), so only an explicit `git add` resolves it.
|
|
115
|
+
else if (binaryByAttributes.has(filePath) || isBinary(content))
|
|
116
|
+
conflicts.push({ path: filePath, kind: "unresolved_binary" });
|
|
117
|
+
else if (hasConflictMarkers(content))
|
|
118
|
+
conflicts.push({ path: filePath, kind: "conflict_markers" });
|
|
119
|
+
}
|
|
120
|
+
const storyChanged = new Set(await diffNames(git, worktreePath, [merge.mergeBaseSha, merge.headSha]));
|
|
121
|
+
const bothChanged = (await diffNames(git, worktreePath, [merge.mergeBaseSha, merge.mergeHeadSha]))
|
|
122
|
+
.filter(filePath => storyChanged.has(filePath) && !stagesByPath.has(filePath));
|
|
123
|
+
for (const filePath of bothChanged) {
|
|
124
|
+
const content = await readWorkingFile(worktreePath, filePath);
|
|
125
|
+
if (content && !isBinary(content) && hasConflictMarkers(content)) {
|
|
126
|
+
conflicts.push({ path: filePath, kind: "conflict_markers" });
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
return conflicts.sort((left, right) => left.path.localeCompare(right.path));
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* Staging excludes some worktree changes (Forge runtime output) by unstaging them
|
|
133
|
+
* back to HEAD. During a merge HEAD is the story side, so an excluded path the merge
|
|
134
|
+
* itself changed would lose the target's change. Given the excluded candidate
|
|
135
|
+
* paths, put the merge-owned ones back into the index: the target branch's version
|
|
136
|
+
* where the story never touched the path, and the agent's working-tree resolution
|
|
137
|
+
* where both sides changed it. Returns the restored paths; the rest stay excluded.
|
|
138
|
+
*/
|
|
139
|
+
export async function restoreMergeOwnedPaths(git, worktreePath, candidatePaths) {
|
|
140
|
+
if (candidatePaths.length === 0)
|
|
141
|
+
return [];
|
|
142
|
+
const merge = await readInProgressMerge(git, worktreePath);
|
|
143
|
+
if (!merge)
|
|
144
|
+
return [];
|
|
145
|
+
const candidates = new Set(candidatePaths);
|
|
146
|
+
const upstreamChanged = (await diffNames(git, worktreePath, [merge.mergeBaseSha, merge.mergeHeadSha]))
|
|
147
|
+
.filter(filePath => candidates.has(filePath));
|
|
148
|
+
if (upstreamChanged.length === 0)
|
|
149
|
+
return [];
|
|
150
|
+
const storyChanged = new Set(await diffNames(git, worktreePath, [merge.mergeBaseSha, merge.headSha]));
|
|
151
|
+
const upstreamOnly = upstreamChanged.filter(filePath => !storyChanged.has(filePath));
|
|
152
|
+
const bothChanged = upstreamChanged.filter(filePath => storyChanged.has(filePath));
|
|
153
|
+
for (const chunk of chunks(upstreamOnly)) {
|
|
154
|
+
// Resetting from MERGE_HEAD also removes index entries the target branch deleted.
|
|
155
|
+
await git.run(worktreePath, ["--literal-pathspecs", "reset", "-q", merge.mergeHeadSha, "--", ...chunk]);
|
|
156
|
+
}
|
|
157
|
+
const indexed = new Set();
|
|
158
|
+
for (const chunk of chunks(bothChanged)) {
|
|
159
|
+
for (const filePath of splitNul(await git.run(worktreePath, ["--literal-pathspecs", "ls-files", "-z", "--", ...chunk]))) {
|
|
160
|
+
indexed.add(filePath);
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
const stageable = [];
|
|
164
|
+
for (const filePath of bothChanged) {
|
|
165
|
+
if (indexed.has(filePath) || await existsOnDisk(worktreePath, filePath))
|
|
166
|
+
stageable.push(filePath);
|
|
167
|
+
}
|
|
168
|
+
for (const chunk of chunks(stageable)) {
|
|
169
|
+
await git.run(worktreePath, ["--literal-pathspecs", "add", "-A", "--", ...chunk]);
|
|
170
|
+
}
|
|
171
|
+
return [...upstreamOnly, ...stageable].sort();
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* Final check on the index Forge is about to commit. Throws when the merge
|
|
175
|
+
* resolution re-adds a path the target branch deleted, or drops a target-branch
|
|
176
|
+
* edit, on a path the story never changed.
|
|
177
|
+
*/
|
|
178
|
+
export async function assertMergeResolutionPreservesUpstreamChanges(git, worktreePath, options = {}) {
|
|
179
|
+
const merge = await readInProgressMerge(git, worktreePath);
|
|
180
|
+
if (!merge)
|
|
181
|
+
return { keptOverUpstreamDeletion: [] };
|
|
182
|
+
const upstream = await diffNameStatus(git, worktreePath, [merge.mergeBaseSha, merge.mergeHeadSha]);
|
|
183
|
+
if (upstream.size === 0)
|
|
184
|
+
return { keptOverUpstreamDeletion: [] };
|
|
185
|
+
const storyChanged = new Set(await diffNames(git, worktreePath, [merge.mergeBaseSha, merge.headSha]));
|
|
186
|
+
// Index compared with the merge base: a path absent here is identical to the base.
|
|
187
|
+
const indexVersusBase = await diffNameStatus(git, worktreePath, ["--cached", merge.mergeBaseSha]);
|
|
188
|
+
const resurrectedPaths = [];
|
|
189
|
+
const revertedPaths = [];
|
|
190
|
+
const keptOverUpstreamDeletion = [];
|
|
191
|
+
for (const [filePath, status] of upstream) {
|
|
192
|
+
// Runtime-only paths are never published, so the story's version stays by design.
|
|
193
|
+
if (options.ignorePath?.(filePath))
|
|
194
|
+
continue;
|
|
195
|
+
const indexStatus = indexVersusBase.get(filePath);
|
|
196
|
+
if (status === "D") {
|
|
197
|
+
const presentInIndex = indexStatus !== "D";
|
|
198
|
+
if (!presentInIndex)
|
|
199
|
+
continue;
|
|
200
|
+
if (storyChanged.has(filePath))
|
|
201
|
+
keptOverUpstreamDeletion.push(filePath);
|
|
202
|
+
else
|
|
203
|
+
resurrectedPaths.push(filePath);
|
|
204
|
+
continue;
|
|
205
|
+
}
|
|
206
|
+
// Equal to the base (undefined) or deleted: the target's edit is discarded. Other
|
|
207
|
+
// index content is a post-merge fixup on top of the target's version and is allowed.
|
|
208
|
+
if (!storyChanged.has(filePath) && (indexStatus === undefined || indexStatus === "D")) {
|
|
209
|
+
revertedPaths.push(filePath);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
if (resurrectedPaths.length > 0 || revertedPaths.length > 0) {
|
|
213
|
+
throw new MergeResolutionRevertsUpstreamChangesError(merge, resurrectedPaths.sort(), revertedPaths.sort());
|
|
214
|
+
}
|
|
215
|
+
return { keptOverUpstreamDeletion: keptOverUpstreamDeletion.sort() };
|
|
216
|
+
}
|
|
217
|
+
export function mergeResolutionCommitNotes(report) {
|
|
218
|
+
if (report.keptOverUpstreamDeletion.length === 0)
|
|
219
|
+
return [];
|
|
220
|
+
return [
|
|
221
|
+
`Kept ${report.keptOverUpstreamDeletion.length} story-modified path(s) that the target branch deleted (modify/delete conflicts resolved by the agent):\n${report.keptOverUpstreamDeletion.map(filePath => `- ${filePath}`).join("\n")}`,
|
|
222
|
+
];
|
|
223
|
+
}
|
|
224
|
+
function describeRevertedUpstreamChanges(merge, resurrectedPaths, revertedPaths) {
|
|
225
|
+
const parts = [];
|
|
226
|
+
if (resurrectedPaths.length > 0) {
|
|
227
|
+
parts.push(`re-adds ${resurrectedPaths.length} path(s) that ${merge.mergeHeadSha.slice(0, 12)} deleted and the story never changed: ${listPaths(resurrectedPaths)}`);
|
|
228
|
+
}
|
|
229
|
+
if (revertedPaths.length > 0) {
|
|
230
|
+
parts.push(`reverts or deletes ${revertedPaths.length} upstream edit(s) on path(s) the story never changed: ${listPaths(revertedPaths)}`);
|
|
231
|
+
}
|
|
232
|
+
return `merge_resolution_reverts_upstream_changes: the merge resolution ${parts.join("; and ")} (merge base ${merge.mergeBaseSha.slice(0, 12)}). Forge did not commit or push the merge.`;
|
|
233
|
+
}
|
|
234
|
+
function listPaths(paths) {
|
|
235
|
+
const listed = paths.slice(0, maxListedPaths).join(", ");
|
|
236
|
+
return paths.length > maxListedPaths ? `${listed}, and ${paths.length - maxListedPaths} more` : listed;
|
|
237
|
+
}
|
|
238
|
+
async function tryRevParse(git, worktreePath, ref) {
|
|
239
|
+
try {
|
|
240
|
+
const sha = (await git.run(worktreePath, ["rev-parse", "-q", "--verify", `${ref}^{commit}`])).trim();
|
|
241
|
+
return objectIdPattern.test(sha) ? sha : null;
|
|
242
|
+
}
|
|
243
|
+
catch {
|
|
244
|
+
return null;
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
async function diffNames(git, worktreePath, args) {
|
|
248
|
+
return splitNul(await git.run(worktreePath, ["diff", "--no-renames", "--name-only", "-z", ...args]));
|
|
249
|
+
}
|
|
250
|
+
async function diffNameStatus(git, worktreePath, args) {
|
|
251
|
+
const fields = splitNul(await git.run(worktreePath, ["diff", "--no-renames", "--name-status", "-z", ...args]));
|
|
252
|
+
const statuses = new Map();
|
|
253
|
+
for (let index = 0; index + 1 < fields.length; index += 2) {
|
|
254
|
+
statuses.set(fields[index + 1], fields[index].charAt(0));
|
|
255
|
+
}
|
|
256
|
+
return statuses;
|
|
257
|
+
}
|
|
258
|
+
function splitNul(output) {
|
|
259
|
+
return output.split("\0").filter(entry => entry.length > 0);
|
|
260
|
+
}
|
|
261
|
+
function chunks(paths) {
|
|
262
|
+
const result = [];
|
|
263
|
+
for (let index = 0; index < paths.length; index += pathArgumentChunkSize) {
|
|
264
|
+
result.push(paths.slice(index, index + pathArgumentChunkSize));
|
|
265
|
+
}
|
|
266
|
+
return result;
|
|
267
|
+
}
|
|
268
|
+
const conflictMarkerPattern = /^<{7}(?: |$)[\s\S]*^>{7}(?: |$)/mu;
|
|
269
|
+
function hasConflictMarkers(content) {
|
|
270
|
+
return conflictMarkerPattern.test(content.toString("utf8"));
|
|
271
|
+
}
|
|
272
|
+
/**
|
|
273
|
+
* Paths whose effective `merge` attribute selects Git's binary merge driver, which
|
|
274
|
+
* writes no conflict markers: `merge` unset (`-merge`, part of the `binary` macro) or
|
|
275
|
+
* `merge=binary`. `-text` and `-diff` do not change how Git merges, so they are ignored.
|
|
276
|
+
*/
|
|
277
|
+
async function readBinaryByAttributes(git, worktreePath, filePaths) {
|
|
278
|
+
const binary = new Set();
|
|
279
|
+
for (const chunk of chunks(filePaths)) {
|
|
280
|
+
const fields = splitNul(await git.run(worktreePath, ["check-attr", "-z", "merge", "--", ...chunk]));
|
|
281
|
+
for (let index = 0; index + 2 < fields.length; index += 3) {
|
|
282
|
+
const [filePath, value] = [fields[index], fields[index + 2]];
|
|
283
|
+
if (value === "unset" || value === "binary")
|
|
284
|
+
binary.add(filePath);
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
return binary;
|
|
288
|
+
}
|
|
289
|
+
function isBinary(content) {
|
|
290
|
+
// Git's own heuristic: a NUL byte in the first 8000 bytes.
|
|
291
|
+
return content.subarray(0, 8000).includes(0);
|
|
292
|
+
}
|
|
293
|
+
async function readWorkingFile(worktreePath, filePath) {
|
|
294
|
+
try {
|
|
295
|
+
return await fs.readFile(path.join(worktreePath, ...filePath.split("/")));
|
|
296
|
+
}
|
|
297
|
+
catch {
|
|
298
|
+
// Missing on disk: `git add -A` stages a deletion, which the upstream-change guard checks.
|
|
299
|
+
return null;
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
async function existsOnDisk(worktreePath, filePath) {
|
|
303
|
+
try {
|
|
304
|
+
await fs.lstat(path.join(worktreePath, ...filePath.split("/")));
|
|
305
|
+
return true;
|
|
306
|
+
}
|
|
307
|
+
catch {
|
|
308
|
+
return false;
|
|
309
|
+
}
|
|
310
|
+
}
|