@loucompanion/forge-bridge 0.1.4-dev.41da3780c451 → 0.1.4-dev.494233aa2e50
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 +1 -1
- 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.js +2 -9
- package/dist/session/provider-cli/provider-cli.process.d.ts +6 -1
- package/dist/session/provider-cli/provider-cli.process.js +198 -16
- package/dist/session/provider-cli/provider-cli.service.js +61 -10
- package/dist/session/provider-cli/provider-usage.d.ts +2 -1
- package/dist/session/publishable-worktree-changes.d.ts +45 -0
- package/dist/session/publishable-worktree-changes.js +177 -0
- package/dist/session/session.types.js +3 -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,12 +2,12 @@ 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 { stagePublishableWorktreeChangeSet } from "../publishable-worktree-changes.js";
|
|
5
6
|
import { hasLaunchTarget } from "./provider-cli.qa-sidecars.js";
|
|
6
7
|
import { clip, isNodeError, messageFromError, normalizedString, parseJsonLine, stringField } from "./provider-output-state.js";
|
|
7
8
|
const maxTransportedQaSidecarBytes = 8 * 1024 * 1024;
|
|
8
9
|
const maxTransportedQaSidecarsTotalBytes = 16 * 1024 * 1024;
|
|
9
10
|
const developCyclePhaseOrder = ["implementation", "self_review", "validation"];
|
|
10
|
-
const nonPublishableWorktreePaths = [".forge", ".local"];
|
|
11
11
|
export async function emitDraftGateArtifacts(emit, worktreePath, workItemId) {
|
|
12
12
|
const draftArtifactFiles = {
|
|
13
13
|
draft_intent: "draft.intent.json",
|
|
@@ -157,14 +157,7 @@ export async function commitWorktreeChanges(git, worktreePath, workItemId, alrea
|
|
|
157
157
|
return { commitSha, changedFiles };
|
|
158
158
|
}
|
|
159
159
|
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);
|
|
160
|
+
return (await stagePublishableWorktreeChangeSet(git, worktreePath)).publishable;
|
|
168
161
|
}
|
|
169
162
|
export function phaseCompleteEventType(phase) {
|
|
170
163
|
return phase === "implementation" ? "implementation_complete" : `${phase}_complete`;
|
|
@@ -23,6 +23,8 @@ export interface ProviderProcessRunResult {
|
|
|
23
23
|
readonly memorySampleCount?: number;
|
|
24
24
|
readonly memorySource?: string;
|
|
25
25
|
readonly memoryObservedAt?: string;
|
|
26
|
+
/** Present when the caller's cancellation stopped the process before it exited on its own. */
|
|
27
|
+
readonly cancelled?: true;
|
|
26
28
|
}
|
|
27
29
|
export interface ProviderProcessRunner {
|
|
28
30
|
run(request: ProviderProcessRunRequest, handlers?: ProviderProcessHandlers, signal?: AbortSignal): Promise<ProviderProcessRunResult>;
|
|
@@ -70,11 +72,14 @@ interface ProviderChildEnvironmentOptions {
|
|
|
70
72
|
export declare function buildProviderChildEnvironment(requestEnv?: Readonly<Record<string, string>>, options?: ProviderChildEnvironmentOptions): NodeJS.ProcessEnv;
|
|
71
73
|
export declare class StreamingProviderProcessRunner implements ProviderProcessRunner {
|
|
72
74
|
private readonly terminalExitGraceMs;
|
|
73
|
-
|
|
75
|
+
private readonly terminalSuccessCeilingMs;
|
|
76
|
+
constructor(terminalExitGraceMs?: number, terminalSuccessCeilingMs?: number);
|
|
74
77
|
run(request: ProviderProcessRunRequest, handlers?: ProviderProcessHandlers, signal?: AbortSignal): Promise<ProviderProcessRunResult>;
|
|
75
78
|
}
|
|
76
79
|
/** Returns aggregate resident bytes for the exact supervised Unix process group. */
|
|
77
80
|
export declare function processGroupResidentMemoryBytes(processGroupId: number, platform?: NodeJS.Platform, procRoot?: string): number | null;
|
|
81
|
+
export declare const UNIX_PROVIDER_START_GRANT_LINE = "forge-provider-start-granted\n";
|
|
82
|
+
export declare function buildUnixProviderStartGateLaunch(command: string, args: readonly string[]): LaunchCommand;
|
|
78
83
|
export declare function resolveCodexNpmDirectLaunch(commandPath: string, args: readonly string[]): LaunchCommand | null;
|
|
79
84
|
/**
|
|
80
85
|
* npm installs of Claude Code (`npm i -g @anthropic-ai/claude-code`) put a `claude.cmd` shim on
|
|
@@ -16,6 +16,9 @@ const execFileAsync = promisify(execFile);
|
|
|
16
16
|
// only needs a bounded diagnostic tail for failure classification.
|
|
17
17
|
export const PROVIDER_OUTPUT_CAPTURE_LIMIT_CHARS = 128 * 1024;
|
|
18
18
|
const PROVIDER_TERMINAL_EXIT_GRACE_MS = 15_000;
|
|
19
|
+
// A provider that keeps starting turns after its first successful one (background-task
|
|
20
|
+
// notifications) is still stopped this long after that first success.
|
|
21
|
+
const PROVIDER_TERMINAL_SUCCESS_CEILING_MS = 10 * 60_000;
|
|
19
22
|
const maximumRecoverableCodexModelsCacheBytes = 16 * 1024 * 1024;
|
|
20
23
|
/** Recovery must wrap the attempt coordinator, never its raw OS runner. Each
|
|
21
24
|
* relaunch needs a new fenced child generation and exclusive launch files. */
|
|
@@ -313,8 +316,10 @@ function setEnvironmentValueIfMissing(env, name, value) {
|
|
|
313
316
|
}
|
|
314
317
|
export class StreamingProviderProcessRunner {
|
|
315
318
|
terminalExitGraceMs;
|
|
316
|
-
|
|
319
|
+
terminalSuccessCeilingMs;
|
|
320
|
+
constructor(terminalExitGraceMs = PROVIDER_TERMINAL_EXIT_GRACE_MS, terminalSuccessCeilingMs = PROVIDER_TERMINAL_SUCCESS_CEILING_MS) {
|
|
317
321
|
this.terminalExitGraceMs = terminalExitGraceMs;
|
|
322
|
+
this.terminalSuccessCeilingMs = terminalSuccessCeilingMs;
|
|
318
323
|
}
|
|
319
324
|
async run(request, handlers = {}, signal) {
|
|
320
325
|
assertHostDatabaseCapabilityBoundary();
|
|
@@ -323,12 +328,29 @@ export class StreamingProviderProcessRunner {
|
|
|
323
328
|
// An unsupervised Unix provider still gets a dedicated process group so a
|
|
324
329
|
// cancellation can stop descendants instead of only the CLI root.
|
|
325
330
|
const launch = supervisedLaunch ?? { ...providerLaunch, detached: process.platform !== "win32" };
|
|
331
|
+
const childEnvironment = buildProviderChildEnvironment(request.env);
|
|
332
|
+
// A piped prompt must reach the provider promptly (Claude Code abandons a
|
|
333
|
+
// silent stdin after ~3s), but the provider must not run before Forge has
|
|
334
|
+
// recorded its start. Off Windows, hold the launch behind a start gate in
|
|
335
|
+
// the same process: the prompt is written immediately and buffers in the
|
|
336
|
+
// pipe, and the gate execs the provider only once onStarted succeeds.
|
|
337
|
+
const startGated = process.platform !== "win32"
|
|
338
|
+
&& supervisedLaunch?.strategy !== "windows_job_object"
|
|
339
|
+
&& request.stdin !== undefined
|
|
340
|
+
&& fs.existsSync(UNIX_PROVIDER_START_GATE_SHELL)
|
|
341
|
+
&& isUnixExecutableAvailable(launch.command, childEnvironment.PATH, request.cwd);
|
|
342
|
+
const spawnLaunch = startGated
|
|
343
|
+
? buildUnixProviderStartGateLaunch(launch.command, launch.args)
|
|
344
|
+
: launch;
|
|
326
345
|
return await new Promise((resolve, reject) => {
|
|
327
346
|
const rootCreatedAt = new Date().toISOString();
|
|
328
|
-
const
|
|
347
|
+
const stdinMode = request.stdin === undefined ? "ignore" : "pipe";
|
|
348
|
+
const child = spawn(spawnLaunch.command, spawnLaunch.args, {
|
|
329
349
|
cwd: request.cwd,
|
|
330
|
-
env:
|
|
331
|
-
stdio:
|
|
350
|
+
env: childEnvironment,
|
|
351
|
+
stdio: startGated
|
|
352
|
+
? [stdinMode, "pipe", "pipe", "pipe"]
|
|
353
|
+
: [stdinMode, "pipe", "pipe"],
|
|
332
354
|
windowsHide: true,
|
|
333
355
|
detached: launch.detached,
|
|
334
356
|
});
|
|
@@ -352,14 +374,21 @@ export class StreamingProviderProcessRunner {
|
|
|
352
374
|
let settled = false;
|
|
353
375
|
let closed = false;
|
|
354
376
|
let cancellationRequested = false;
|
|
377
|
+
let cancelledBeforeClose = false;
|
|
355
378
|
let terminalTerminationStarted = false;
|
|
356
379
|
let terminalExitTimer = null;
|
|
380
|
+
let terminalCeilingTimer = null;
|
|
381
|
+
let latestTurnFailed = false;
|
|
357
382
|
let readiness = null;
|
|
358
383
|
const cleanup = () => {
|
|
359
384
|
if (terminalExitTimer) {
|
|
360
385
|
clearTimeout(terminalExitTimer);
|
|
361
386
|
terminalExitTimer = null;
|
|
362
387
|
}
|
|
388
|
+
if (terminalCeilingTimer) {
|
|
389
|
+
clearTimeout(terminalCeilingTimer);
|
|
390
|
+
terminalCeilingTimer = null;
|
|
391
|
+
}
|
|
363
392
|
signal?.removeEventListener("abort", abort);
|
|
364
393
|
};
|
|
365
394
|
const fail = (error) => {
|
|
@@ -373,6 +402,8 @@ export class StreamingProviderProcessRunner {
|
|
|
373
402
|
void terminate().then(() => reject(error), terminationError => reject(new AggregateError([error, terminationError], "Provider process failed and its process tree could not be proven stopped.")));
|
|
374
403
|
};
|
|
375
404
|
const abort = () => {
|
|
405
|
+
if (!closed)
|
|
406
|
+
cancelledBeforeClose = true;
|
|
376
407
|
cancellationRequested = true;
|
|
377
408
|
// Cancellation is not a launch failure when the supervised tree can be
|
|
378
409
|
// proven stopped. Let the close handler settle the command after exact
|
|
@@ -386,6 +417,27 @@ export class StreamingProviderProcessRunner {
|
|
|
386
417
|
signal?.addEventListener("abort", abort, { once: true });
|
|
387
418
|
}
|
|
388
419
|
child.on("error", fail);
|
|
420
|
+
const startGrant = startGated ? child.stdio[3] : null;
|
|
421
|
+
if (startGated && !startGrant) {
|
|
422
|
+
fail(new Error("Provider start-grant stream was not piped."));
|
|
423
|
+
return;
|
|
424
|
+
}
|
|
425
|
+
startGrant?.on("error", error => {
|
|
426
|
+
// A broken grant pipe means the gate already exited (terminated before
|
|
427
|
+
// its grant, or it died on its own). Its close event carries the real
|
|
428
|
+
// exit status, so an EPIPE here must not replace that result.
|
|
429
|
+
if (isBrokenPipeError(error))
|
|
430
|
+
return;
|
|
431
|
+
fail(error);
|
|
432
|
+
});
|
|
433
|
+
const grantUnixProviderStart = () => {
|
|
434
|
+
if (!startGrant)
|
|
435
|
+
return;
|
|
436
|
+
// Never release a provider whose launch was cancelled or already failed.
|
|
437
|
+
if (closed || settled || cancellationRequested || signal?.aborted)
|
|
438
|
+
return;
|
|
439
|
+
startGrant.end(UNIX_PROVIDER_START_GRANT_LINE, "utf8");
|
|
440
|
+
};
|
|
389
441
|
child.once("spawn", () => {
|
|
390
442
|
readiness = (async () => {
|
|
391
443
|
const providerReady = supervisedLaunch?.strategy === "windows_job_object"
|
|
@@ -398,6 +450,9 @@ export class StreamingProviderProcessRunner {
|
|
|
398
450
|
if (supervisedLaunch?.strategy === "windows_job_object") {
|
|
399
451
|
grantWindowsProviderStart(supervisedLaunch);
|
|
400
452
|
}
|
|
453
|
+
else if (startGated) {
|
|
454
|
+
grantUnixProviderStart();
|
|
455
|
+
}
|
|
401
456
|
})();
|
|
402
457
|
void readiness.catch(error => {
|
|
403
458
|
if (!closed && !signal?.aborted)
|
|
@@ -413,15 +468,20 @@ export class StreamingProviderProcessRunner {
|
|
|
413
468
|
return;
|
|
414
469
|
}
|
|
415
470
|
child.stdin.on("error", (error) => {
|
|
471
|
+
// A prompt still buffered when Forge stops the process (cancellation,
|
|
472
|
+
// or a refused start grant) cannot be delivered; that broken pipe is
|
|
473
|
+
// not a failure. Any other stdin error still is.
|
|
474
|
+
if ((cancellationRequested || termination) && isBrokenPipeError(error))
|
|
475
|
+
return;
|
|
416
476
|
void terminate();
|
|
417
477
|
fail(error);
|
|
418
478
|
});
|
|
419
479
|
child.stdin.end(request.stdin, "utf8");
|
|
420
480
|
};
|
|
421
481
|
if (request.stdin !== undefined) {
|
|
422
|
-
if (supervisedLaunch?.strategy === "windows_job_object") {
|
|
423
|
-
// The outer supervisor must receive stdin before it
|
|
424
|
-
//
|
|
482
|
+
if (supervisedLaunch?.strategy === "windows_job_object" || startGated) {
|
|
483
|
+
// The outer supervisor / Unix start gate must receive stdin before it
|
|
484
|
+
// can launch the provider. Its start grant fences prompt processing.
|
|
425
485
|
writeProviderInput();
|
|
426
486
|
}
|
|
427
487
|
else {
|
|
@@ -430,19 +490,46 @@ export class StreamingProviderProcessRunner {
|
|
|
430
490
|
});
|
|
431
491
|
}
|
|
432
492
|
}
|
|
493
|
+
const finishAfterTerminalSuccess = () => {
|
|
494
|
+
if (closed || settled || cancellationRequested || terminalTerminationStarted)
|
|
495
|
+
return;
|
|
496
|
+
terminalTerminationStarted = true;
|
|
497
|
+
void terminate().catch(fail);
|
|
498
|
+
};
|
|
499
|
+
const armTerminalExit = () => {
|
|
500
|
+
if (terminalExitTimer)
|
|
501
|
+
clearTimeout(terminalExitTimer);
|
|
502
|
+
terminalExitTimer = setTimeout(finishAfterTerminalSuccess, this.terminalExitGraceMs);
|
|
503
|
+
terminalExitTimer.unref?.();
|
|
504
|
+
// Later turns may postpone the grace period, but never past this ceiling.
|
|
505
|
+
if (!terminalCeilingTimer) {
|
|
506
|
+
terminalCeilingTimer = setTimeout(finishAfterTerminalSuccess, this.terminalSuccessCeilingMs);
|
|
507
|
+
terminalCeilingTimer.unref?.();
|
|
508
|
+
}
|
|
509
|
+
};
|
|
433
510
|
const readers = [
|
|
434
511
|
readProcessLines(childStdout, (line) => {
|
|
435
512
|
if (request.captureOutput !== false)
|
|
436
513
|
stdout.appendLine(line);
|
|
437
514
|
const handled = handlers.onStdoutLine?.(line);
|
|
438
|
-
if (!
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
515
|
+
if (!terminalTerminationStarted) {
|
|
516
|
+
if (isProviderTerminalSuccess(line)) {
|
|
517
|
+
latestTurnFailed = false;
|
|
518
|
+
armTerminalExit();
|
|
519
|
+
}
|
|
520
|
+
else if (isProviderTerminalFailure(line)) {
|
|
521
|
+
// A later turn that fails reports its failure even after an earlier success.
|
|
522
|
+
latestTurnFailed = true;
|
|
523
|
+
}
|
|
524
|
+
else if (terminalExitTimer && isProviderTurnActivity(line)) {
|
|
525
|
+
// A terminal event ends a turn, not necessarily the provider. Claude Code
|
|
526
|
+
// stays resident while background tasks it started are pending and begins a
|
|
527
|
+
// new turn when one reports (and a resumed session can replay a queued
|
|
528
|
+
// notification turn first). A provider that is working again is not finished;
|
|
529
|
+
// the grace period restarts at its next terminal event.
|
|
530
|
+
clearTimeout(terminalExitTimer);
|
|
531
|
+
terminalExitTimer = null;
|
|
532
|
+
}
|
|
446
533
|
}
|
|
447
534
|
return handled;
|
|
448
535
|
}),
|
|
@@ -489,16 +576,53 @@ export class StreamingProviderProcessRunner {
|
|
|
489
576
|
// that event, terminate the supervised tree after a short grace
|
|
490
577
|
// period and preserve the successful handoff so the existing
|
|
491
578
|
// artifact, commit, and publication gates can run.
|
|
492
|
-
|
|
579
|
+
// A provider stopped after a successful turn keeps that success. Whenever the
|
|
580
|
+
// most recent turn failed, the run fails, however the process ended.
|
|
581
|
+
exitCode: latestTurnFailed
|
|
582
|
+
? code && code !== 0 ? code : 1
|
|
583
|
+
: terminalTerminationStarted && !cancellationRequested ? 0 : code ?? 1,
|
|
493
584
|
stdout: stdout.toString(),
|
|
494
585
|
stderr: stderr.toString(),
|
|
495
586
|
...(memory ?? {}),
|
|
587
|
+
...(cancelledBeforeClose ? { cancelled: true } : {}),
|
|
496
588
|
});
|
|
497
589
|
}).catch(fail);
|
|
498
590
|
});
|
|
499
591
|
});
|
|
500
592
|
}
|
|
501
593
|
}
|
|
594
|
+
/** A stream event that shows the provider is working on a turn: model output or a tool result. */
|
|
595
|
+
function isProviderTurnActivity(line) {
|
|
596
|
+
const trimmed = line.trim();
|
|
597
|
+
if (!trimmed.startsWith("{"))
|
|
598
|
+
return false;
|
|
599
|
+
try {
|
|
600
|
+
const event = JSON.parse(trimmed);
|
|
601
|
+
return event.type === "assistant"
|
|
602
|
+
|| event.type === "user"
|
|
603
|
+
|| (event.type === "system" && event.subtype === "init")
|
|
604
|
+
|| event.type === "turn.started"
|
|
605
|
+
|| event.type === "item.started";
|
|
606
|
+
}
|
|
607
|
+
catch {
|
|
608
|
+
return false;
|
|
609
|
+
}
|
|
610
|
+
}
|
|
611
|
+
function isProviderTerminalFailure(line) {
|
|
612
|
+
const trimmed = line.trim();
|
|
613
|
+
if (!trimmed.startsWith("{"))
|
|
614
|
+
return false;
|
|
615
|
+
try {
|
|
616
|
+
const event = JSON.parse(trimmed);
|
|
617
|
+
// The same events the output parsers report as provider errors.
|
|
618
|
+
return event.type === "turn.failed"
|
|
619
|
+
|| event.type === "error"
|
|
620
|
+
|| (event.type === "result" && (event.subtype !== "success" || event.is_error === true));
|
|
621
|
+
}
|
|
622
|
+
catch {
|
|
623
|
+
return false;
|
|
624
|
+
}
|
|
625
|
+
}
|
|
502
626
|
function isProviderTerminalSuccess(line) {
|
|
503
627
|
const trimmed = line.trim();
|
|
504
628
|
if (!trimmed.startsWith("{"))
|
|
@@ -682,6 +806,64 @@ async function resolveProviderProcessLaunch(command, args) {
|
|
|
682
806
|
?? resolvePackageManagerDirectLaunch(resolved, args)
|
|
683
807
|
?? buildWindowsLaunchCommand(resolved, args);
|
|
684
808
|
}
|
|
809
|
+
const UNIX_PROVIDER_START_GATE_SHELL = "/bin/sh";
|
|
810
|
+
const UNIX_PROVIDER_START_GATE_NAME = "forge-provider-start-gate";
|
|
811
|
+
export const UNIX_PROVIDER_START_GRANT_LINE = "forge-provider-start-granted\n";
|
|
812
|
+
/**
|
|
813
|
+
* Blocks on fd 3 until the bridge writes the exact grant line, then replaces
|
|
814
|
+
* itself with the provider (`exec`), so the supervised root PID, process group
|
|
815
|
+
* and birth identity stay the provider's. The provider command and arguments
|
|
816
|
+
* are passed positionally and expanded only as "$@"; nothing is interpolated
|
|
817
|
+
* into the script. EOF, a read error, or any other content on fd 3 exits
|
|
818
|
+
* without running the provider. fd 3 is closed before exec so the provider and
|
|
819
|
+
* its descendants never inherit the grant channel. stdin is not touched, so
|
|
820
|
+
* the prompt stays buffered in its pipe for the provider.
|
|
821
|
+
*/
|
|
822
|
+
const UNIX_PROVIDER_START_GATE_SCRIPT = [
|
|
823
|
+
"IFS= read -r forge_start_grant <&3 || { echo \"$0: provider start was not granted\" >&2; exit 125; }",
|
|
824
|
+
`[ "$forge_start_grant" = "${UNIX_PROVIDER_START_GRANT_LINE.trim()}" ] || { echo "$0: provider start grant was invalid" >&2; exit 125; }`,
|
|
825
|
+
"exec \"$@\" 3<&-",
|
|
826
|
+
].join("\n");
|
|
827
|
+
export function buildUnixProviderStartGateLaunch(command, args) {
|
|
828
|
+
return {
|
|
829
|
+
command: UNIX_PROVIDER_START_GATE_SHELL,
|
|
830
|
+
args: ["-c", UNIX_PROVIDER_START_GATE_SCRIPT, UNIX_PROVIDER_START_GATE_NAME, command, ...args],
|
|
831
|
+
};
|
|
832
|
+
}
|
|
833
|
+
/**
|
|
834
|
+
* Mirrors the executable lookup the gate's `exec` will perform. A command that
|
|
835
|
+
* cannot be found is spawned directly instead so it keeps failing as a spawn
|
|
836
|
+
* ENOENT before any start is recorded; nothing can run in that case. The check
|
|
837
|
+
* is advisory: if the executable disappears between this lookup and the gated
|
|
838
|
+
* `exec`, the gate exits 127 with the shell's "not found" message after the
|
|
839
|
+
* start was recorded, which surfaces as an ordinary provider failure.
|
|
840
|
+
*/
|
|
841
|
+
function isUnixExecutableAvailable(command, pathValue, cwd) {
|
|
842
|
+
if (!command || command.startsWith("-"))
|
|
843
|
+
return false;
|
|
844
|
+
const candidates = command.includes("/")
|
|
845
|
+
? [path.resolve(cwd, command)]
|
|
846
|
+
: pathValue === undefined
|
|
847
|
+
? null
|
|
848
|
+
: pathValue.split(path.delimiter).map(directory => path.resolve(cwd, directory || ".", command));
|
|
849
|
+
if (candidates === null)
|
|
850
|
+
return true;
|
|
851
|
+
return candidates.some(candidate => {
|
|
852
|
+
try {
|
|
853
|
+
if (!fs.statSync(candidate).isFile())
|
|
854
|
+
return false;
|
|
855
|
+
fs.accessSync(candidate, fs.constants.X_OK);
|
|
856
|
+
return true;
|
|
857
|
+
}
|
|
858
|
+
catch {
|
|
859
|
+
return false;
|
|
860
|
+
}
|
|
861
|
+
});
|
|
862
|
+
}
|
|
863
|
+
function isBrokenPipeError(error) {
|
|
864
|
+
const code = error?.code;
|
|
865
|
+
return code === "EPIPE" || code === "ERR_STREAM_DESTROYED" || code === "ECONNRESET";
|
|
866
|
+
}
|
|
685
867
|
function grantWindowsProviderStart(launch) {
|
|
686
868
|
if (!launch.startGrantPath) {
|
|
687
869
|
throw new Error("host_process_supervisor_invalid: Windows provider start-grant path was not assigned.");
|