@loucompanion/forge-bridge 0.1.4-dev.9e8a5b93cbcb → 0.1.4-dev.a690038a6849

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/dist/bridge/bridge.service.d.ts +12 -1
  2. package/dist/bridge/bridge.service.js +51 -5
  3. package/dist/bridge/bridge.types.d.ts +6 -0
  4. package/dist/bridge/dispatch-result-outbox.d.ts +11 -1
  5. package/dist/bridge/dispatch-result-outbox.js +31 -6
  6. package/dist/runtime/attempt-process-supervisor.d.ts +19 -0
  7. package/dist/runtime/attempt-process-supervisor.js +50 -0
  8. package/dist/runtime/host-database-capability-boundary.d.ts +1 -1
  9. package/dist/runtime/host-database-capability-boundary.js +1 -0
  10. package/dist/runtime/host-facts.d.ts +35 -0
  11. package/dist/runtime/host-facts.js +95 -0
  12. package/dist/runtime/host-load-sampler.d.ts +83 -0
  13. package/dist/runtime/host-load-sampler.js +164 -0
  14. package/dist/runtime/host-pressure-stall.d.ts +41 -0
  15. package/dist/runtime/host-pressure-stall.js +121 -0
  16. package/dist/runtime/host-runtime-contract.d.ts +1 -0
  17. package/dist/runtime/host-runtime-contract.js +2 -0
  18. package/dist/runtime/host-runtime-lease.js +55 -9
  19. package/dist/runtime/managed-command-teardown.d.ts +62 -0
  20. package/dist/runtime/managed-command-teardown.js +607 -0
  21. package/dist/runtime/playwright-browser-cache.d.ts +39 -0
  22. package/dist/runtime/playwright-browser-cache.js +227 -0
  23. package/dist/runtime/playwright-host-runtime-adapter.d.ts +11 -0
  24. package/dist/runtime/playwright-host-runtime-adapter.js +48 -54
  25. package/dist/session/managed-attempt-tools.d.ts +25 -0
  26. package/dist/session/managed-attempt-tools.js +212 -15
  27. package/dist/session/managed-build-coordinator.d.ts +1 -1
  28. package/dist/session/managed-build-coordinator.js +4 -1
  29. package/dist/session/phase-completion.artifacts.js +4 -0
  30. package/dist/session/phase-completion.runtime.js +22 -17
  31. package/dist/session/pre-publication-process.d.ts +20 -0
  32. package/dist/session/pre-publication-process.js +97 -0
  33. package/dist/session/pre-publication-skipped-tests.d.ts +21 -0
  34. package/dist/session/pre-publication-skipped-tests.js +109 -0
  35. package/dist/session/pre-publication-validation.js +27 -57
  36. package/dist/session/provider-cli/provider-cli.artifacts.d.ts +2 -1
  37. package/dist/session/provider-cli/provider-cli.artifacts.js +7 -13
  38. package/dist/session/provider-cli/provider-cli.process.d.ts +28 -1
  39. package/dist/session/provider-cli/provider-cli.process.js +177 -15
  40. package/dist/session/provider-cli/provider-cli.prompts.d.ts +5 -0
  41. package/dist/session/provider-cli/provider-cli.prompts.js +13 -0
  42. package/dist/session/provider-cli/provider-cli.service.js +99 -22
  43. package/dist/session/provider-cli/provider-in-flight-work.d.ts +6 -0
  44. package/dist/session/provider-cli/provider-in-flight-work.js +47 -0
  45. package/dist/session/provider-cli/provider-output-state.d.ts +6 -0
  46. package/dist/session/provider-cli/provider-output-state.js +9 -0
  47. package/dist/session/publishable-worktree-changes.d.ts +45 -0
  48. package/dist/session/publishable-worktree-changes.js +177 -0
  49. package/dist/session/session.types.js +9 -0
  50. package/dist/version.d.ts +1 -1
  51. package/dist/version.js +1 -1
  52. 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
- await emit?.(validationEvent("prepublication_validation_passed", check.id, `Pre-publication CI parity check '${check.id}' passed.`));
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 { role: "runner", kind: "checkpoint", content, eventType, data: JSON.stringify({ checkId, contractId: "forge-ci-parity-v1" }) };
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,13 @@ 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";
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";
7
9
  const maxTransportedQaSidecarBytes = 8 * 1024 * 1024;
8
10
  const maxTransportedQaSidecarsTotalBytes = 16 * 1024 * 1024;
9
11
  const developCyclePhaseOrder = ["implementation", "self_review", "validation"];
10
- const nonPublishableWorktreePaths = [".forge", ".local"];
11
12
  export async function emitDraftGateArtifacts(emit, worktreePath, workItemId) {
12
13
  const draftArtifactFiles = {
13
14
  draft_intent: "draft.intent.json",
@@ -157,14 +158,7 @@ export async function commitWorktreeChanges(git, worktreePath, workItemId, alrea
157
158
  return { commitSha, changedFiles };
158
159
  }
159
160
  export async function stagePublishableWorktreeChanges(git, worktreePath) {
160
- await git.run(worktreePath, ["add", "-A"]);
161
- for (const reservedPath of nonPublishableWorktreePaths) {
162
- await git.run(worktreePath, ["reset", "--", reservedPath]).catch(() => "");
163
- }
164
- return (await git.run(worktreePath, ["diff", "--cached", "--name-only"]))
165
- .split(/\r?\n/)
166
- .map((line) => line.trim())
167
- .filter(Boolean);
161
+ return (await stagePublishableWorktreeChangeSet(git, worktreePath)).publishable;
168
162
  }
169
163
  export function phaseCompleteEventType(phase) {
170
164
  return phase === "implementation" ? "implementation_complete" : `${phase}_complete`;
@@ -779,11 +773,11 @@ export class LiveCompletionArtifactEmitter {
779
773
  }
780
774
  }
781
775
  }
782
- export async function readCompletionArtifactsForRun(worktreePath, workItemId, phase, developCycle, debugCycle) {
776
+ export async function readCompletionArtifactsForRun(worktreePath, workItemId, phase, developCycle, debugCycle, providerResult) {
783
777
  if (!developCycle && !debugCycle) {
784
778
  const artifact = await readCompletionArtifact(worktreePath, workItemId, phase);
785
779
  if (!artifact) {
786
- throw new Error(`Provider CLI completed but did not call the Forge ${phase} completion tool.`);
780
+ throw providerCompletionToolMissingFailure(`Provider CLI completed but did not call the Forge ${phase} completion tool.`, providerResult);
787
781
  }
788
782
  return [artifact];
789
783
  }
@@ -795,11 +789,11 @@ export async function readCompletionArtifactsForRun(worktreePath, workItemId, ph
795
789
  const artifact = await readCompletionArtifact(worktreePath, workItemId, expectedPhase);
796
790
  if (!artifact) {
797
791
  if (artifacts.length === 0) {
798
- throw new Error(`Provider CLI completed but did not call the Forge ${expectedPhase} completion tool.`);
792
+ throw providerCompletionToolMissingFailure(`Provider CLI completed but did not call the Forge ${expectedPhase} completion tool.`, providerResult);
799
793
  }
800
794
  const previous = artifacts[artifacts.length - 1];
801
795
  if ((previous.status ?? "").trim().toLowerCase() === "pass") {
802
- throw new Error(`Provider CLI completed after ${previous.phase} passed but did not call the Forge ${expectedPhase} completion tool.`);
796
+ throw providerCompletionToolMissingFailure(`Provider CLI completed after ${previous.phase} passed but did not call the Forge ${expectedPhase} completion tool.`, providerResult);
803
797
  }
804
798
  return artifacts;
805
799
  }
@@ -1,4 +1,5 @@
1
1
  import { type LaunchCommand } from "../../shared/process/windows-launch.js";
2
+ import { ForgeFailureError } from "../session.types.js";
2
3
  export declare const PROVIDER_OUTPUT_CAPTURE_LIMIT_CHARS: number;
3
4
  export type ProviderCliCommand = LaunchCommand;
4
5
  export interface ProviderProcessRunRequest {
@@ -14,7 +15,15 @@ export interface ProviderProcessRunRequest {
14
15
  * supervisor and is never forwarded to the child process.
15
16
  */
16
17
  readonly failureRedactionValues?: readonly string[];
18
+ /**
19
+ * The run resumes an existing provider thread. Such a run can replay a queued
20
+ * notification turn before the prompt's turn, and that replayed turn must not
21
+ * start the success ceiling.
22
+ */
23
+ readonly resumesProviderThread?: boolean;
17
24
  }
25
+ /** Why Forge stopped a provider that was still resident after a successful turn. */
26
+ export type ProviderTerminalStopReason = "turn_exit_grace" | "success_ceiling";
18
27
  export interface ProviderProcessRunResult {
19
28
  readonly exitCode: number;
20
29
  readonly stdout: string;
@@ -23,6 +32,10 @@ export interface ProviderProcessRunResult {
23
32
  readonly memorySampleCount?: number;
24
33
  readonly memorySource?: string;
25
34
  readonly memoryObservedAt?: string;
35
+ /** Present when the caller's cancellation stopped the process before it exited on its own. */
36
+ readonly cancelled?: true;
37
+ /** Present when Forge stopped a provider that stayed resident after a successful turn. */
38
+ readonly terminalStopReason?: ProviderTerminalStopReason;
26
39
  }
27
40
  export interface ProviderProcessRunner {
28
41
  run(request: ProviderProcessRunRequest, handlers?: ProviderProcessHandlers, signal?: AbortSignal): Promise<ProviderProcessRunResult>;
@@ -31,6 +44,12 @@ export interface ProviderProcessHandlers {
31
44
  onStarted?(): Promise<void> | void;
32
45
  onStdoutLine?(line: string): Promise<void> | void;
33
46
  onStderrLine?(line: string): Promise<void> | void;
47
+ /**
48
+ * True while the provider has a tool call (such as an MCP tool call) in flight. While it
49
+ * is, or while an attempt-owned managed command is non-terminal, Forge suspends the
50
+ * end-of-turn exit grace and the success ceiling.
51
+ */
52
+ isToolCallInFlight?(): boolean;
34
53
  }
35
54
  /** Recovery must wrap the attempt coordinator, never its raw OS runner. Each
36
55
  * relaunch needs a new fenced child generation and exclusive launch files. */
@@ -70,9 +89,17 @@ interface ProviderChildEnvironmentOptions {
70
89
  export declare function buildProviderChildEnvironment(requestEnv?: Readonly<Record<string, string>>, options?: ProviderChildEnvironmentOptions): NodeJS.ProcessEnv;
71
90
  export declare class StreamingProviderProcessRunner implements ProviderProcessRunner {
72
91
  private readonly terminalExitGraceMs;
73
- constructor(terminalExitGraceMs?: number);
92
+ private readonly terminalSuccessCeilingMs;
93
+ private readonly terminalWorkPollMs;
94
+ constructor(terminalExitGraceMs?: number, terminalSuccessCeilingMs?: number, terminalWorkPollMs?: number);
74
95
  run(request: ProviderProcessRunRequest, handlers?: ProviderProcessHandlers, signal?: AbortSignal): Promise<ProviderProcessRunResult>;
75
96
  }
97
+ /**
98
+ * The typed failure for a provider run that ended without calling its required Forge
99
+ * completion tool. A run Forge stopped at the success ceiling is reported as such, so it
100
+ * is not mistaken for an agent that simply ended its turn.
101
+ */
102
+ export declare function providerCompletionToolMissingFailure(message: string, result?: Pick<ProviderProcessRunResult, "terminalStopReason"> | null): ForgeFailureError;
76
103
  /** Returns aggregate resident bytes for the exact supervised Unix process group. */
77
104
  export declare function processGroupResidentMemoryBytes(processGroupId: number, platform?: NodeJS.Platform, procRoot?: string): number | null;
78
105
  export declare const UNIX_PROVIDER_START_GRANT_LINE = "forge-provider-start-granted\n";
@@ -10,12 +10,19 @@ import { persistHostProcessSupervisorMetadata, resolveHostProcessSupervisedLaunc
10
10
  import { buildWindowsLaunchCommand } from "../../shared/process/windows-launch.js";
11
11
  import { assertHostDatabaseCapabilityBoundary } from "../../runtime/host-database-capability-boundary.js";
12
12
  import { ForgeFailureError } from "../session.types.js";
13
+ import { hasNonterminalManagedCommand } from "./provider-in-flight-work.js";
13
14
  const execFileAsync = promisify(execFile);
14
15
  // Provider processes can emit many gigabytes over a long-running session. The
15
16
  // line handlers stream that output to Forge as it arrives; the completed result
16
17
  // only needs a bounded diagnostic tail for failure classification.
17
18
  export const PROVIDER_OUTPUT_CAPTURE_LIMIT_CHARS = 128 * 1024;
18
19
  const PROVIDER_TERMINAL_EXIT_GRACE_MS = 15_000;
20
+ // A provider that keeps starting turns after its first successful one (background-task
21
+ // notifications) is still stopped once this much time without supervised work in flight
22
+ // has passed since that first success.
23
+ const PROVIDER_TERMINAL_SUCCESS_CEILING_MS = 10 * 60_000;
24
+ // How often the end-of-turn timers re-check whether supervised work is still in flight.
25
+ const PROVIDER_TERMINAL_WORK_POLL_MS = 1_000;
19
26
  const maximumRecoverableCodexModelsCacheBytes = 16 * 1024 * 1024;
20
27
  /** Recovery must wrap the attempt coordinator, never its raw OS runner. Each
21
28
  * relaunch needs a new fenced child generation and exclusive launch files. */
@@ -313,8 +320,12 @@ function setEnvironmentValueIfMissing(env, name, value) {
313
320
  }
314
321
  export class StreamingProviderProcessRunner {
315
322
  terminalExitGraceMs;
316
- constructor(terminalExitGraceMs = PROVIDER_TERMINAL_EXIT_GRACE_MS) {
323
+ terminalSuccessCeilingMs;
324
+ terminalWorkPollMs;
325
+ constructor(terminalExitGraceMs = PROVIDER_TERMINAL_EXIT_GRACE_MS, terminalSuccessCeilingMs = PROVIDER_TERMINAL_SUCCESS_CEILING_MS, terminalWorkPollMs = PROVIDER_TERMINAL_WORK_POLL_MS) {
317
326
  this.terminalExitGraceMs = terminalExitGraceMs;
327
+ this.terminalSuccessCeilingMs = terminalSuccessCeilingMs;
328
+ this.terminalWorkPollMs = terminalWorkPollMs;
318
329
  }
319
330
  async run(request, handlers = {}, signal) {
320
331
  assertHostDatabaseCapabilityBoundary();
@@ -369,14 +380,24 @@ export class StreamingProviderProcessRunner {
369
380
  let settled = false;
370
381
  let closed = false;
371
382
  let cancellationRequested = false;
383
+ let cancelledBeforeClose = false;
372
384
  let terminalTerminationStarted = false;
373
- let terminalExitTimer = null;
385
+ let terminalStopReason = null;
386
+ // Idle time (no supervised work in flight) accrued against the end-of-turn grace and
387
+ // the success ceiling; null while that timer is not armed.
388
+ let graceIdleMs = null;
389
+ let ceilingIdleMs = null;
390
+ let terminalSuccessCount = 0;
391
+ let replayedTurnCeilingSkipped = false;
392
+ let terminalWorkTimer = null;
393
+ let terminalWorkTickAt = 0;
394
+ let terminalWorkTickRunning = false;
395
+ let latestTurnFailed = false;
374
396
  let readiness = null;
375
397
  const cleanup = () => {
376
- if (terminalExitTimer) {
377
- clearTimeout(terminalExitTimer);
378
- terminalExitTimer = null;
379
- }
398
+ stopTerminalWorkTimer();
399
+ graceIdleMs = null;
400
+ ceilingIdleMs = null;
380
401
  signal?.removeEventListener("abort", abort);
381
402
  };
382
403
  const fail = (error) => {
@@ -390,6 +411,8 @@ export class StreamingProviderProcessRunner {
390
411
  void terminate().then(() => reject(error), terminationError => reject(new AggregateError([error, terminationError], "Provider process failed and its process tree could not be proven stopped.")));
391
412
  };
392
413
  const abort = () => {
414
+ if (!closed)
415
+ cancelledBeforeClose = true;
393
416
  cancellationRequested = true;
394
417
  // Cancellation is not a launch failure when the supervised tree can be
395
418
  // proven stopped. Let the close handler settle the command after exact
@@ -476,19 +499,109 @@ export class StreamingProviderProcessRunner {
476
499
  });
477
500
  }
478
501
  }
502
+ const finishAfterTerminalSuccess = (reason) => {
503
+ if (closed || settled || cancellationRequested || terminalTerminationStarted)
504
+ return;
505
+ terminalTerminationStarted = true;
506
+ terminalStopReason = reason;
507
+ stopTerminalWorkTimer();
508
+ void terminate().catch(fail);
509
+ };
510
+ const workInFlight = async () => {
511
+ try {
512
+ if (handlers.isToolCallInFlight?.())
513
+ return true;
514
+ }
515
+ catch {
516
+ // A failing probe must not keep the provider open or stop it early on its own.
517
+ }
518
+ return await hasNonterminalManagedCommand(request.env?.FORGE_LOG_DIR).catch(() => false);
519
+ };
520
+ // The grace and the ceiling only count time in which no supervised work is in flight:
521
+ // a provider waiting on an MCP tool call or on a managed command it started is not
522
+ // finished, even when its turn has ended. The grace restarts once that work is done.
523
+ const terminalWorkTick = async () => {
524
+ if (terminalWorkTickRunning)
525
+ return;
526
+ terminalWorkTickRunning = true;
527
+ try {
528
+ const inFlight = await workInFlight();
529
+ const now = performance.now();
530
+ const elapsed = Math.max(0, now - terminalWorkTickAt);
531
+ terminalWorkTickAt = now;
532
+ if (closed || settled || terminalTerminationStarted)
533
+ return;
534
+ if (inFlight) {
535
+ if (graceIdleMs !== null)
536
+ graceIdleMs = 0;
537
+ return;
538
+ }
539
+ if (graceIdleMs !== null)
540
+ graceIdleMs += elapsed;
541
+ if (ceilingIdleMs !== null)
542
+ ceilingIdleMs += elapsed;
543
+ if (graceIdleMs !== null && graceIdleMs >= this.terminalExitGraceMs) {
544
+ finishAfterTerminalSuccess("turn_exit_grace");
545
+ }
546
+ else if (ceilingIdleMs !== null && ceilingIdleMs >= this.terminalSuccessCeilingMs) {
547
+ finishAfterTerminalSuccess("success_ceiling");
548
+ }
549
+ }
550
+ finally {
551
+ terminalWorkTickRunning = false;
552
+ if (graceIdleMs === null && ceilingIdleMs === null)
553
+ stopTerminalWorkTimer();
554
+ }
555
+ };
556
+ function stopTerminalWorkTimer() {
557
+ if (terminalWorkTimer) {
558
+ clearInterval(terminalWorkTimer);
559
+ terminalWorkTimer = null;
560
+ }
561
+ }
562
+ const startTerminalWorkTimer = () => {
563
+ if (terminalWorkTimer)
564
+ return;
565
+ terminalWorkTickAt = performance.now();
566
+ const intervalMs = Math.max(1, Math.min(this.terminalWorkPollMs, this.terminalExitGraceMs, this.terminalSuccessCeilingMs));
567
+ terminalWorkTimer = setInterval(() => { void terminalWorkTick().catch(fail); }, intervalMs);
568
+ terminalWorkTimer.unref?.();
569
+ };
570
+ const armTerminalExit = () => {
571
+ terminalSuccessCount += 1;
572
+ graceIdleMs = 0;
573
+ // Later turns may postpone the grace period, but never past this ceiling.
574
+ ceilingIdleMs ??= 0;
575
+ startTerminalWorkTimer();
576
+ };
479
577
  const readers = [
480
578
  readProcessLines(childStdout, (line) => {
481
579
  if (request.captureOutput !== false)
482
580
  stdout.appendLine(line);
483
581
  const handled = handlers.onStdoutLine?.(line);
484
- if (!terminalExitTimer && isProviderTerminalSuccess(line)) {
485
- terminalExitTimer = setTimeout(() => {
486
- if (closed || settled || cancellationRequested)
487
- return;
488
- terminalTerminationStarted = true;
489
- void terminate().catch(fail);
490
- }, this.terminalExitGraceMs);
491
- terminalExitTimer.unref?.();
582
+ if (!terminalTerminationStarted) {
583
+ if (isProviderTerminalSuccess(line)) {
584
+ latestTurnFailed = false;
585
+ armTerminalExit();
586
+ }
587
+ else if (isProviderTerminalFailure(line)) {
588
+ // A later turn that fails reports its failure even after an earlier success.
589
+ latestTurnFailed = true;
590
+ }
591
+ else if (graceIdleMs !== null && isProviderTurnActivity(line)) {
592
+ // A terminal event ends a turn, not necessarily the provider. Claude Code
593
+ // stays resident while background tasks it started are pending and begins a
594
+ // new turn when one reports. A provider that is working again is not finished;
595
+ // the grace period restarts at its next terminal event.
596
+ graceIdleMs = null;
597
+ // A resumed session can replay a queued notification turn before the
598
+ // prompt's own turn. That replayed turn must not start the ceiling, or the
599
+ // resumed agent is stopped mid-work; the prompt's turn arms it instead.
600
+ if (request.resumesProviderThread && terminalSuccessCount === 1 && !replayedTurnCeilingSkipped) {
601
+ replayedTurnCeilingSkipped = true;
602
+ ceilingIdleMs = null;
603
+ }
604
+ }
492
605
  }
493
606
  return handled;
494
607
  }),
@@ -535,16 +648,65 @@ export class StreamingProviderProcessRunner {
535
648
  // that event, terminate the supervised tree after a short grace
536
649
  // period and preserve the successful handoff so the existing
537
650
  // artifact, commit, and publication gates can run.
538
- exitCode: terminalTerminationStarted && !cancellationRequested ? 0 : code ?? 1,
651
+ // A provider stopped after a successful turn keeps that success. Whenever the
652
+ // most recent turn failed, the run fails, however the process ended.
653
+ exitCode: latestTurnFailed
654
+ ? code && code !== 0 ? code : 1
655
+ : terminalTerminationStarted && !cancellationRequested ? 0 : code ?? 1,
539
656
  stdout: stdout.toString(),
540
657
  stderr: stderr.toString(),
541
658
  ...(memory ?? {}),
659
+ ...(cancelledBeforeClose ? { cancelled: true } : {}),
660
+ ...(terminalStopReason && !cancellationRequested ? { terminalStopReason } : {}),
542
661
  });
543
662
  }).catch(fail);
544
663
  });
545
664
  });
546
665
  }
547
666
  }
667
+ /**
668
+ * The typed failure for a provider run that ended without calling its required Forge
669
+ * completion tool. A run Forge stopped at the success ceiling is reported as such, so it
670
+ * is not mistaken for an agent that simply ended its turn.
671
+ */
672
+ export function providerCompletionToolMissingFailure(message, result) {
673
+ if (result?.terminalStopReason === "success_ceiling") {
674
+ return new ForgeFailureError("provider_terminated_at_turn_ceiling", `${message} Forge stopped the provider at its post-turn success ceiling while it was still working.`);
675
+ }
676
+ return new ForgeFailureError("provider_completion_tool_missing", message);
677
+ }
678
+ /** A stream event that shows the provider is working on a turn: model output or a tool result. */
679
+ function isProviderTurnActivity(line) {
680
+ const trimmed = line.trim();
681
+ if (!trimmed.startsWith("{"))
682
+ return false;
683
+ try {
684
+ const event = JSON.parse(trimmed);
685
+ return event.type === "assistant"
686
+ || event.type === "user"
687
+ || (event.type === "system" && event.subtype === "init")
688
+ || event.type === "turn.started"
689
+ || event.type === "item.started";
690
+ }
691
+ catch {
692
+ return false;
693
+ }
694
+ }
695
+ function isProviderTerminalFailure(line) {
696
+ const trimmed = line.trim();
697
+ if (!trimmed.startsWith("{"))
698
+ return false;
699
+ try {
700
+ const event = JSON.parse(trimmed);
701
+ // The same events the output parsers report as provider errors.
702
+ return event.type === "turn.failed"
703
+ || event.type === "error"
704
+ || (event.type === "result" && (event.subtype !== "success" || event.is_error === true));
705
+ }
706
+ catch {
707
+ return false;
708
+ }
709
+ }
548
710
  function isProviderTerminalSuccess(line) {
549
711
  const trimmed = line.trim();
550
712
  if (!trimmed.startsWith("{"))