@loucompanion/forge-bridge 0.1.4-dev.41da3780c451 → 0.1.4-dev.4677bbd22f17
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 +3 -3
- package/dist/bridge/bridge.service.d.ts +12 -1
- package/dist/bridge/bridge.service.js +51 -5
- package/dist/bridge/bridge.types.d.ts +6 -0
- package/dist/bridge/dispatch-result-outbox.d.ts +11 -1
- package/dist/bridge/dispatch-result-outbox.js +31 -6
- package/dist/cli/cli.help.js +2 -2
- package/dist/runtime/attempt-process-supervisor.d.ts +24 -0
- package/dist/runtime/attempt-process-supervisor.js +74 -1
- package/dist/runtime/host-database-capability-boundary.d.ts +1 -1
- package/dist/runtime/host-database-capability-boundary.js +1 -0
- package/dist/runtime/host-facts.d.ts +35 -0
- package/dist/runtime/host-facts.js +95 -0
- package/dist/runtime/host-load-sampler.d.ts +83 -0
- package/dist/runtime/host-load-sampler.js +164 -0
- package/dist/runtime/host-pressure-stall.d.ts +41 -0
- package/dist/runtime/host-pressure-stall.js +121 -0
- package/dist/runtime/host-runtime-contract.d.ts +1 -0
- package/dist/runtime/host-runtime-contract.js +2 -0
- package/dist/runtime/host-runtime-lease.js +55 -9
- package/dist/runtime/managed-command-teardown.d.ts +62 -0
- package/dist/runtime/managed-command-teardown.js +607 -0
- package/dist/runtime/playwright-browser-cache.d.ts +39 -0
- package/dist/runtime/playwright-browser-cache.js +227 -0
- package/dist/runtime/playwright-host-runtime-adapter.d.ts +11 -0
- package/dist/runtime/playwright-host-runtime-adapter.js +48 -54
- package/dist/session/managed-attempt-tools.d.ts +25 -0
- package/dist/session/managed-attempt-tools.js +212 -15
- package/dist/session/managed-build-coordinator.d.ts +1 -1
- package/dist/session/managed-build-coordinator.js +4 -1
- package/dist/session/phase-completion.artifacts.js +4 -0
- package/dist/session/phase-completion.runtime.js +22 -17
- package/dist/session/pre-publication-process.d.ts +20 -0
- package/dist/session/pre-publication-process.js +97 -0
- package/dist/session/pre-publication-skipped-tests.d.ts +21 -0
- package/dist/session/pre-publication-skipped-tests.js +109 -0
- package/dist/session/pre-publication-validation.js +27 -57
- 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 +37 -1
- package/dist/session/provider-cli/provider-cli.process.js +297 -23
- package/dist/session/provider-cli/provider-cli.prompts.d.ts +5 -0
- package/dist/session/provider-cli/provider-cli.prompts.js +15 -0
- package/dist/session/provider-cli/provider-cli.service.js +112 -22
- 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/provider-cli/provider-usage.d.ts +2 -1
- package/dist/session/publishable-worktree-changes.d.ts +54 -0
- package/dist/session/publishable-worktree-changes.js +193 -0
- package/dist/session/session.types.js +12 -0
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/dist/worktree/dependency-warmer.js +74 -0
- package/package.json +1 -1
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import fs from "node:fs/promises";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { isSubPath } from "../shared/path/path.js";
|
|
4
|
+
const emptySummary = { count: 0, reasons: [] };
|
|
5
|
+
/** The attempt-owned output root a managed attempt's tests write under, outside the worktree. */
|
|
6
|
+
export const attemptTestOutputEnvironment = "FORGE_TEST_OUTPUT_DIR";
|
|
7
|
+
const resultsDirectoryFlags = new Set(["-resultsdirectory", "--results-directory"]);
|
|
8
|
+
const maxTrxBytes = 64 * 1024 * 1024;
|
|
9
|
+
const maxTrxFiles = 64;
|
|
10
|
+
const maxReasonLength = 400;
|
|
11
|
+
const maxReasons = 10;
|
|
12
|
+
export function resultsDirectoryArgument(args) {
|
|
13
|
+
const index = args.findIndex(arg => resultsDirectoryFlags.has(arg.toLowerCase()));
|
|
14
|
+
const value = index >= 0 ? args[index + 1] : undefined;
|
|
15
|
+
return value && !value.startsWith("-") ? value : undefined;
|
|
16
|
+
}
|
|
17
|
+
export async function readSkippedTests(cwd, args, sinceMs, environment) {
|
|
18
|
+
const declared = resultsDirectoryArgument(args);
|
|
19
|
+
if (!declared)
|
|
20
|
+
return emptySummary;
|
|
21
|
+
const root = await realDirectory(path.resolve(cwd, declared));
|
|
22
|
+
if (!root)
|
|
23
|
+
return emptySummary;
|
|
24
|
+
const attemptOutput = environment?.[attemptTestOutputEnvironment]?.trim();
|
|
25
|
+
const allowedRoots = (await Promise.all([cwd, ...(attemptOutput && path.isAbsolute(attemptOutput) ? [attemptOutput] : [])]
|
|
26
|
+
.map(realDirectory))).filter((allowed) => allowed !== undefined);
|
|
27
|
+
if (!allowedRoots.some(allowed => isSubPath(allowed, root)))
|
|
28
|
+
return emptySummary;
|
|
29
|
+
const files = await recentTrxFiles(root, sinceMs);
|
|
30
|
+
const counts = new Map();
|
|
31
|
+
let count = 0;
|
|
32
|
+
for (const file of files) {
|
|
33
|
+
for (const reason of skippedReasons(await fs.readFile(file, "utf8"))) {
|
|
34
|
+
count += 1;
|
|
35
|
+
counts.set(reason, (counts.get(reason) ?? 0) + 1);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
return { count, reasons: [...counts].map(([reason, n]) => ({ reason, count: n })) };
|
|
39
|
+
}
|
|
40
|
+
export function mergeSkippedTests(left, right) {
|
|
41
|
+
const counts = new Map(left.reasons.map(entry => [entry.reason, entry.count]));
|
|
42
|
+
for (const entry of right.reasons)
|
|
43
|
+
counts.set(entry.reason, (counts.get(entry.reason) ?? 0) + entry.count);
|
|
44
|
+
return { count: left.count + right.count, reasons: [...counts].map(([reason, count]) => ({ reason, count })) };
|
|
45
|
+
}
|
|
46
|
+
export function describeSkippedTests(summary) {
|
|
47
|
+
const shown = [...summary.reasons].sort((a, b) => b.count - a.count).slice(0, maxReasons);
|
|
48
|
+
const more = summary.reasons.length - shown.length;
|
|
49
|
+
return `${summary.count} skipped test${summary.count === 1 ? "" : "s"} (${shown
|
|
50
|
+
.map(entry => `${entry.count}x ${entry.reason}`).join("; ")}${more > 0 ? `; ${more} more reasons` : ""})`;
|
|
51
|
+
}
|
|
52
|
+
/** Each NotExecuted result's skip reason, from its ErrorInfo message (VSTest's TRX shape). */
|
|
53
|
+
export function skippedReasons(trx) {
|
|
54
|
+
const reasons = [];
|
|
55
|
+
const result = /<UnitTestResult\b([^>]*?)(?:\/>|>([\s\S]*?)<\/UnitTestResult>)/gu;
|
|
56
|
+
for (const match of trx.matchAll(result)) {
|
|
57
|
+
if (!/\boutcome="NotExecuted"/u.test(match[1] ?? ""))
|
|
58
|
+
continue;
|
|
59
|
+
const message = /<Message>([\s\S]*?)<\/Message>/u.exec(match[2] ?? "")?.[1];
|
|
60
|
+
const reason = message ? decodeXml(message).replace(/\s+/gu, " ").trim() : "";
|
|
61
|
+
reasons.push(reason.length === 0 ? "no reason recorded"
|
|
62
|
+
: reason.length > maxReasonLength ? `${reason.slice(0, maxReasonLength)}...` : reason);
|
|
63
|
+
}
|
|
64
|
+
return reasons;
|
|
65
|
+
}
|
|
66
|
+
async function realDirectory(candidate) {
|
|
67
|
+
try {
|
|
68
|
+
const real = await fs.realpath(candidate);
|
|
69
|
+
return (await fs.stat(real)).isDirectory() ? real : undefined;
|
|
70
|
+
}
|
|
71
|
+
catch {
|
|
72
|
+
return undefined;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
async function recentTrxFiles(root, sinceMs) {
|
|
76
|
+
const found = [];
|
|
77
|
+
const pending = [root];
|
|
78
|
+
while (pending.length > 0 && found.length < maxTrxFiles) {
|
|
79
|
+
const directory = pending.pop();
|
|
80
|
+
let entries;
|
|
81
|
+
try {
|
|
82
|
+
entries = await fs.readdir(directory, { withFileTypes: true });
|
|
83
|
+
}
|
|
84
|
+
catch {
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
87
|
+
for (const entry of entries) {
|
|
88
|
+
const full = path.join(directory, entry.name);
|
|
89
|
+
if (entry.isDirectory())
|
|
90
|
+
pending.push(full);
|
|
91
|
+
else if (entry.isFile() && entry.name.toLowerCase().endsWith(".trx")) {
|
|
92
|
+
const stat = await fs.stat(full).catch(() => null);
|
|
93
|
+
if (stat && stat.mtimeMs >= sinceMs && stat.size <= maxTrxBytes)
|
|
94
|
+
found.push(full);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
return found.sort();
|
|
99
|
+
}
|
|
100
|
+
function decodeXml(value) {
|
|
101
|
+
return value.replace(/&(#x[0-9a-f]+|#[0-9]+|lt|gt|amp|quot|apos);/giu, (entity, name) => {
|
|
102
|
+
const lower = name.toLowerCase();
|
|
103
|
+
if (lower.startsWith("#x"))
|
|
104
|
+
return String.fromCodePoint(Number.parseInt(lower.slice(2), 16));
|
|
105
|
+
if (lower.startsWith("#"))
|
|
106
|
+
return String.fromCodePoint(Number.parseInt(lower.slice(1), 10));
|
|
107
|
+
return { lt: "<", gt: ">", amp: "&", quot: "\"", apos: "'" }[lower] ?? entity;
|
|
108
|
+
});
|
|
109
|
+
}
|
|
@@ -1,16 +1,15 @@
|
|
|
1
|
-
import { execFile } from "node:child_process";
|
|
2
1
|
import { createHash, randomUUID } from "node:crypto";
|
|
3
2
|
import fs from "node:fs/promises";
|
|
4
3
|
import path from "node:path";
|
|
5
|
-
import { promisify } from "node:util";
|
|
6
4
|
import { attemptDatabaseCapabilityEnvironment, attemptDatabaseCapabilitySecrets, } from "../runtime/attempt-database-broker.js";
|
|
7
5
|
import { assertHostDatabaseCapabilityBoundary } from "../runtime/host-database-capability-boundary.js";
|
|
8
6
|
import { nativeTestPostgresFallbackEnvironment, parseNativeTestPostgresFallback, } from "../runtime/native-test-postgres-fallback.js";
|
|
9
|
-
import { hostRuntimeLegacyTestPostgresEnvironment, hostRuntimeTestPostgresAdminEnvironment, } from "../runtime/host-runtime-contract.js";
|
|
7
|
+
import { hostRuntimeLegacyTestPostgresEnvironment, hostRuntimeTestPostgresAdminEnvironment, hostRuntimeTestPostgresProvisionerEnvironment, } from "../runtime/host-runtime-contract.js";
|
|
10
8
|
import { redactText } from "../shared/redaction/redaction.js";
|
|
9
|
+
import { describeSkippedTests, mergeSkippedTests, readSkippedTests, } from "./pre-publication-skipped-tests.js";
|
|
10
|
+
import { ProcessPrePublicationCommandRunner, pnpmDirectoryLaunch } from "./pre-publication-process.js";
|
|
11
11
|
import { findUnreferencedNewExports } from "./unreferenced-exports.js";
|
|
12
12
|
import { ForgeFailureError, sanitizeFailureError, } from "./session.types.js";
|
|
13
|
-
const execFileAsync = promisify(execFile);
|
|
14
13
|
const contractRelativePath = ".forge/validation/ci-parity.v1.json";
|
|
15
14
|
const requiredCheckIds = new Set([
|
|
16
15
|
"file-size-inventory",
|
|
@@ -81,54 +80,6 @@ export class PrePublicationInfrastructureError extends ForgeFailureError {
|
|
|
81
80
|
this.name = "PrePublicationInfrastructureError";
|
|
82
81
|
}
|
|
83
82
|
}
|
|
84
|
-
class ProcessPrePublicationCommandRunner {
|
|
85
|
-
async run(command, args, cwd, signal, environment) {
|
|
86
|
-
try {
|
|
87
|
-
const windowsBatch = process.platform === "win32" && (command === "npm" || command === "pnpm");
|
|
88
|
-
const executable = windowsBatch ? (process.env.ComSpec ?? "cmd.exe") : command;
|
|
89
|
-
const commandArgs = windowsBatch
|
|
90
|
-
? ["/d", "/s", "/c", [`${command}.cmd`, ...args].map(quoteWindowsCommandArgument).join(" ")]
|
|
91
|
-
: [...args];
|
|
92
|
-
const result = await execFileAsync(executable, commandArgs, {
|
|
93
|
-
cwd,
|
|
94
|
-
encoding: "utf8",
|
|
95
|
-
maxBuffer: 4 * 1024 * 1024,
|
|
96
|
-
signal,
|
|
97
|
-
env: prePublicationChildEnvironment(environment),
|
|
98
|
-
});
|
|
99
|
-
return { exitCode: 0, stdout: result.stdout, stderr: result.stderr };
|
|
100
|
-
}
|
|
101
|
-
catch (error) {
|
|
102
|
-
const failure = error;
|
|
103
|
-
if (failure.name === "AbortError")
|
|
104
|
-
throw error;
|
|
105
|
-
if (failure.code === "ENOENT") {
|
|
106
|
-
return { exitCode: 127, stderr: `executable_not_found: ${command}` };
|
|
107
|
-
}
|
|
108
|
-
return {
|
|
109
|
-
exitCode: typeof failure.code === "number" ? failure.code : 1,
|
|
110
|
-
stdout: failure.stdout,
|
|
111
|
-
stderr: failure.stderr ?? failure.message,
|
|
112
|
-
};
|
|
113
|
-
}
|
|
114
|
-
}
|
|
115
|
-
}
|
|
116
|
-
function quoteWindowsCommandArgument(value) {
|
|
117
|
-
return /^[A-Za-z0-9_./:@=-]+$/u.test(value) ? value : `"${value.replaceAll('"', '""')}"`;
|
|
118
|
-
}
|
|
119
|
-
function prePublicationChildEnvironment(environment) {
|
|
120
|
-
const child = {};
|
|
121
|
-
const privilegedNames = new Set([
|
|
122
|
-
hostRuntimeTestPostgresAdminEnvironment.toLowerCase(),
|
|
123
|
-
hostRuntimeLegacyTestPostgresEnvironment.toLowerCase(),
|
|
124
|
-
]);
|
|
125
|
-
for (const [name, value] of Object.entries(process.env)) {
|
|
126
|
-
if (typeof value === "string" && !privilegedNames.has(name.toLowerCase())) {
|
|
127
|
-
child[name] = value;
|
|
128
|
-
}
|
|
129
|
-
}
|
|
130
|
-
return { ...child, ...environment };
|
|
131
|
-
}
|
|
132
83
|
export class PrePublicationValidator {
|
|
133
84
|
commands;
|
|
134
85
|
dockerEngineProbe;
|
|
@@ -176,7 +127,9 @@ export class PrePublicationValidator {
|
|
|
176
127
|
}
|
|
177
128
|
const postgresAdminConnection = await this.ensurePrerequisite(check, scoped.execution?.environment, scoped.postgresAdminConnection, emit) ?? scoped.postgresAdminConnection;
|
|
178
129
|
await emit?.(validationEvent("prepublication_validation_started", check.id, `Running pre-publication CI parity check '${check.id}'.`));
|
|
130
|
+
let skipped = { count: 0, reasons: [] };
|
|
179
131
|
for (const step of check.steps) {
|
|
132
|
+
const stepStartedMs = Date.now() - 1000;
|
|
180
133
|
let result = await this.runStep(check.id, step, worktreePath, signal, scoped.execution, postgresAdminConnection);
|
|
181
134
|
await this.throwIfPrerequisiteWasLost(check, result, scoped.execution?.environment, postgresAdminConnection, emit);
|
|
182
135
|
if (isTimeoutOnlyClientTestFailure(check.id, step, result)) {
|
|
@@ -222,9 +175,17 @@ export class PrePublicationValidator {
|
|
|
222
175
|
await emit?.(validationEvent("prepublication_validation_failed", check.id, `Pre-publication CI parity check '${check.id}' exited ${result.exitCode}${detail ? `: ${detail}` : "."}`));
|
|
223
176
|
throw new PrePublicationValidationError(check.id, result.exitCode, result.command, result.args, detail);
|
|
224
177
|
}
|
|
178
|
+
// The invocation's own arguments: a managed attempt may direct results to its test-output root.
|
|
179
|
+
skipped = mergeSkippedTests(skipped, await readSkippedTests(worktreePath, result.args, stepStartedMs, scoped.execution?.environment));
|
|
225
180
|
}
|
|
226
181
|
completed.push(check.id);
|
|
227
|
-
|
|
182
|
+
// A pass that skipped tests says so, with each reason, instead of reading as a plain pass.
|
|
183
|
+
const secrets = validationExactSecrets(scoped.execution?.environment);
|
|
184
|
+
skipped = { ...skipped, reasons: skipped.reasons.map(entry => ({ ...entry, reason: redactText(entry.reason, secrets) })) };
|
|
185
|
+
const skippedDetail = skipped.count > 0 ? describeSkippedTests(skipped) : undefined;
|
|
186
|
+
await emit?.(validationEvent("prepublication_validation_passed", check.id, skippedDetail
|
|
187
|
+
? `Pre-publication CI parity check '${check.id}' passed with ${skippedDetail}.`
|
|
188
|
+
: `Pre-publication CI parity check '${check.id}' passed.`, skipped.count > 0 ? { skippedTests: skipped.count, skippedReasons: skipped.reasons } : undefined));
|
|
228
189
|
}
|
|
229
190
|
return completed;
|
|
230
191
|
}
|
|
@@ -361,10 +322,11 @@ export class PrePublicationValidator {
|
|
|
361
322
|
const exactSecrets = validationExactSecrets(execution?.environment);
|
|
362
323
|
try {
|
|
363
324
|
if (execution?.processRunner) {
|
|
325
|
+
const launch = await pnpmDirectoryLaunch(command, args, cwd);
|
|
364
326
|
const result = await execution.processRunner.run({
|
|
365
327
|
command,
|
|
366
|
-
args,
|
|
367
|
-
cwd,
|
|
328
|
+
args: launch.args,
|
|
329
|
+
cwd: launch.cwd,
|
|
368
330
|
env: execution.environment,
|
|
369
331
|
captureOutput: true,
|
|
370
332
|
failureRedactionValues: exactSecrets,
|
|
@@ -455,6 +417,7 @@ function validationExactSecrets(environment) {
|
|
|
455
417
|
return [
|
|
456
418
|
environment?.[hostRuntimeTestPostgresAdminEnvironment]?.trim() ?? "",
|
|
457
419
|
environment?.[hostRuntimeLegacyTestPostgresEnvironment]?.trim() ?? "",
|
|
420
|
+
environment?.[hostRuntimeTestPostgresProvisionerEnvironment]?.trim() ?? "",
|
|
458
421
|
...attemptDatabaseCapabilitySecrets(environment?.[attemptDatabaseCapabilityEnvironment]),
|
|
459
422
|
].filter((value, index, values) => value.length > 0 && values.indexOf(value) === index);
|
|
460
423
|
}
|
|
@@ -587,6 +550,7 @@ function withoutPrivilegedPostgresEnvironment(environment) {
|
|
|
587
550
|
const privilegedNames = new Set([
|
|
588
551
|
hostRuntimeTestPostgresAdminEnvironment.toLowerCase(),
|
|
589
552
|
hostRuntimeLegacyTestPostgresEnvironment.toLowerCase(),
|
|
553
|
+
hostRuntimeTestPostgresProvisionerEnvironment.toLowerCase(),
|
|
590
554
|
]);
|
|
591
555
|
return Object.fromEntries(Object.entries(environment)
|
|
592
556
|
.filter(([name]) => !privilegedNames.has(name.toLowerCase())));
|
|
@@ -656,6 +620,12 @@ function canonicalizeJson(value) {
|
|
|
656
620
|
}
|
|
657
621
|
return value;
|
|
658
622
|
}
|
|
659
|
-
function validationEvent(eventType, checkId, content) {
|
|
660
|
-
return {
|
|
623
|
+
function validationEvent(eventType, checkId, content, detail) {
|
|
624
|
+
return {
|
|
625
|
+
role: "runner",
|
|
626
|
+
kind: "checkpoint",
|
|
627
|
+
content,
|
|
628
|
+
eventType,
|
|
629
|
+
data: JSON.stringify({ checkId, contractId: "forge-ci-parity-v1", ...detail }),
|
|
630
|
+
};
|
|
661
631
|
}
|
|
@@ -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 {};
|