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

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 (45) 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.js +2 -9
  37. package/dist/session/provider-cli/provider-cli.process.d.ts +4 -1
  38. package/dist/session/provider-cli/provider-cli.process.js +88 -10
  39. package/dist/session/provider-cli/provider-cli.service.js +61 -10
  40. package/dist/session/publishable-worktree-changes.d.ts +45 -0
  41. package/dist/session/publishable-worktree-changes.js +177 -0
  42. package/dist/session/session.types.js +3 -0
  43. package/dist/version.d.ts +1 -1
  44. package/dist/version.js +1 -1
  45. 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,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.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);
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,7 +72,8 @@ 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
- constructor(terminalExitGraceMs?: number);
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. */
@@ -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
- constructor(terminalExitGraceMs = PROVIDER_TERMINAL_EXIT_GRACE_MS) {
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();
@@ -369,14 +374,21 @@ export class StreamingProviderProcessRunner {
369
374
  let settled = false;
370
375
  let closed = false;
371
376
  let cancellationRequested = false;
377
+ let cancelledBeforeClose = false;
372
378
  let terminalTerminationStarted = false;
373
379
  let terminalExitTimer = null;
380
+ let terminalCeilingTimer = null;
381
+ let latestTurnFailed = false;
374
382
  let readiness = null;
375
383
  const cleanup = () => {
376
384
  if (terminalExitTimer) {
377
385
  clearTimeout(terminalExitTimer);
378
386
  terminalExitTimer = null;
379
387
  }
388
+ if (terminalCeilingTimer) {
389
+ clearTimeout(terminalCeilingTimer);
390
+ terminalCeilingTimer = null;
391
+ }
380
392
  signal?.removeEventListener("abort", abort);
381
393
  };
382
394
  const fail = (error) => {
@@ -390,6 +402,8 @@ export class StreamingProviderProcessRunner {
390
402
  void terminate().then(() => reject(error), terminationError => reject(new AggregateError([error, terminationError], "Provider process failed and its process tree could not be proven stopped.")));
391
403
  };
392
404
  const abort = () => {
405
+ if (!closed)
406
+ cancelledBeforeClose = true;
393
407
  cancellationRequested = true;
394
408
  // Cancellation is not a launch failure when the supervised tree can be
395
409
  // proven stopped. Let the close handler settle the command after exact
@@ -476,19 +490,46 @@ export class StreamingProviderProcessRunner {
476
490
  });
477
491
  }
478
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
+ };
479
510
  const readers = [
480
511
  readProcessLines(childStdout, (line) => {
481
512
  if (request.captureOutput !== false)
482
513
  stdout.appendLine(line);
483
514
  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?.();
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
+ }
492
533
  }
493
534
  return handled;
494
535
  }),
@@ -535,16 +576,53 @@ export class StreamingProviderProcessRunner {
535
576
  // that event, terminate the supervised tree after a short grace
536
577
  // period and preserve the successful handoff so the existing
537
578
  // artifact, commit, and publication gates can run.
538
- exitCode: terminalTerminationStarted && !cancellationRequested ? 0 : code ?? 1,
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,
539
584
  stdout: stdout.toString(),
540
585
  stderr: stderr.toString(),
541
586
  ...(memory ?? {}),
587
+ ...(cancelledBeforeClose ? { cancelled: true } : {}),
542
588
  });
543
589
  }).catch(fail);
544
590
  });
545
591
  });
546
592
  }
547
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
+ }
548
626
  function isProviderTerminalSuccess(line) {
549
627
  const trimmed = line.trim();
550
628
  if (!trimmed.startsWith("{"))
@@ -6,7 +6,8 @@ import { buildSpecBody, selectLaneCommand } from "../../worktree/artifact-inject
6
6
  import { defaultWorktreeCoordinatorStateRoot } from "../../worktree/worktree-paths.js";
7
7
  import { completionPhaseFromDispatch, prepareCompletionToolRuntime, readCompletionArtifact, usesDebugCycleCompletion, usesDevelopCycleCompletion } from "../phase-completion.js";
8
8
  import { ForgeFailureError } from "../session.types.js";
9
- import { cleanupCompletionTools, commitWorktreeChanges, completionPhaseFromArtifact, emitArchitectStructuredEvents, emitCompletionArtifactRecorded, emitDecomposeGateArtifacts, emitDraftGateArtifacts, emitPhaseCompletionEvent, emitPhaseGateEvents, emitQaArtifactRecorded, emitQaStructuredEvents, enforceQaBrowserLaunchTargetGate, LiveArchitectArtifactEmitter, LiveCompletionArtifactEmitter, LiveQaArtifactEmitter, readCompletionArtifactsForRun, readQaCompletionArtifactBundle, stagePublishableWorktreeChanges, waitForCompletionArtifact } from "./provider-cli.artifacts.js";
9
+ import { cleanupCompletionTools, commitWorktreeChanges, completionPhaseFromArtifact, emitArchitectStructuredEvents, emitCompletionArtifactRecorded, emitDecomposeGateArtifacts, emitDraftGateArtifacts, emitPhaseCompletionEvent, emitPhaseGateEvents, emitQaArtifactRecorded, emitQaStructuredEvents, enforceQaBrowserLaunchTargetGate, LiveArchitectArtifactEmitter, LiveCompletionArtifactEmitter, LiveQaArtifactEmitter, readCompletionArtifactsForRun, readQaCompletionArtifactBundle, waitForCompletionArtifact } from "./provider-cli.artifacts.js";
10
+ import { diffClaimedChangedFiles, findUnpublishedWorktreePaths, normalizeChangedFilePath, stagePublishableWorktreeChangeSet, } from "../publishable-worktree-changes.js";
10
11
  import { DeterministicProviderCliService } from "./provider-cli.deterministic.js";
11
12
  import { buildArchitectPrompt, buildConflictResolvePrompt, buildDebugCyclePrompt, buildDevelopCyclePrompt, buildDraftPrompt, buildDraftSpec, buildImplementationPrompt, buildProviderCliPrompt, buildProviderCliCommand, durableDraftInput, buildPullRequestCheckRepairPrompt, buildPullRequestCommentsPrompt, buildQaPrompt, formatProviderCliCommandForCheckpoint, isDecomposeDraftDispatch, isPullRequestCheckRepairDispatch, isPullRequestCommentsDispatch } from "./provider-cli.prompts.js";
12
13
  import { isTransientCodexProviderNotFoundFailure, recoveringProviderProcessRunner, StreamingProviderProcessRunner } from "./provider-cli.process.js";
@@ -68,12 +69,54 @@ function assertCommentRepairArtifactMatchesChanges(artifact, actualChangedFiles)
68
69
  const claimed = [...new Set(claimedChangedFiles)].sort();
69
70
  const actual = [...new Set(normalizedActual)].sort();
70
71
  if (hasFixedDisposition && actual.length === 0) {
71
- throw new Error("Comment repair fixed dispositions require an actual publishable source diff.");
72
+ throw commentRepairChangedFilesMismatch("Comment repair fixed dispositions require an actual publishable source diff.");
72
73
  }
73
74
  if (claimed.length !== actual.length || claimed.some((value, index) => value !== actual[index])) {
74
- throw new Error("Comment repair changed_files must exactly match the publishable staged source diff.");
75
+ const { missing, unexpected } = diffClaimedChangedFiles(claimed, actual);
76
+ throw commentRepairChangedFilesMismatch(`Comment repair changed_files must exactly match the publishable staged source diff${formatChangedFilesDelta(missing, unexpected)}.`);
75
77
  }
76
78
  }
79
+ /**
80
+ * A finding resolved as fixed must not point at a file whose edit Forge leaves out of the
81
+ * published commit; otherwise the thread would be resolved without its fix. That covers
82
+ * runtime output Forge unstaged and untracked or git-ignored files it never stages.
83
+ */
84
+ async function assertFixedFindingsArePublished(git, worktreePath, dispatch, artifact, changeSet) {
85
+ const findingPaths = new Map((dispatch.pullRequest?.reviewFindings ?? []).map(finding => [
86
+ `${finding.kind.trim().toLowerCase()}:${finding.claimId}:${finding.bodySha256.trim().toLowerCase()}`,
87
+ finding.path ? normalizeChangedFilePath(finding.path) : "",
88
+ ]));
89
+ const payload = JSON.parse(artifact.verdictJson);
90
+ const dispositions = Array.isArray(payload.dispositions) ? payload.dispositions : [];
91
+ const fixed = dispositions.flatMap(value => {
92
+ const record = value;
93
+ if (record.disposition !== "fixed")
94
+ return [];
95
+ const identity = `${String(record.kind ?? "").trim().toLowerCase()}:${String(record.claim_id ?? "")}:${String(record.body_sha256 ?? "").trim().toLowerCase()}`;
96
+ const findingPath = findingPaths.get(identity);
97
+ return findingPath ? [{ claimId: String(record.claim_id ?? ""), path: findingPath }] : [];
98
+ });
99
+ if (fixed.length === 0)
100
+ return;
101
+ const unpublished = new Set([
102
+ ...changeSet.excluded.map(normalizeChangedFilePath),
103
+ ...await findUnpublishedWorktreePaths(git, worktreePath, fixed.map(entry => entry.path), changeSet.publishable),
104
+ ]);
105
+ const dropped = fixed.filter(entry => unpublished.has(entry.path)).map(entry => `${entry.claimId} (${entry.path})`);
106
+ if (dropped.length > 0) {
107
+ throw commentRepairChangedFilesMismatch(`Comment repair marked ${dropped.join(", ")} fixed, but Forge does not publish that file (runtime output, untracked, or git-ignored); Forge did not publish or resolve review findings.`);
108
+ }
109
+ }
110
+ function commentRepairChangedFilesMismatch(message) {
111
+ return new ForgeFailureError("comment_repair_changed_files_mismatch", message);
112
+ }
113
+ function formatChangedFilesDelta(missing, unexpected) {
114
+ const parts = [
115
+ missing.length > 0 ? `missing from changed_files: ${missing.join(", ")}` : "",
116
+ unexpected.length > 0 ? `not in the publishable diff: ${unexpected.join(", ")}` : "",
117
+ ].filter(Boolean);
118
+ return parts.length > 0 ? ` (${parts.join("; ")})` : "";
119
+ }
77
120
  async function finalizeCommentRepairChangedFiles(artifact, baselineChangedFiles, actualChangedFiles) {
78
121
  const payload = JSON.parse(artifact.verdictJson);
79
122
  const claimedRecords = Array.isArray(payload.changed_files)
@@ -90,11 +133,11 @@ async function finalizeCommentRepairChangedFiles(artifact, baselineChangedFiles,
90
133
  const dispositions = Array.isArray(payload.dispositions) ? payload.dispositions : [];
91
134
  const hasFixedDisposition = dispositions.some(value => value.disposition === "fixed");
92
135
  if (hasFixedDisposition && authoritativePaths.length === 0) {
93
- throw new Error("Comment repair fixed dispositions require an actual publishable source diff.");
136
+ throw commentRepairChangedFilesMismatch("Comment repair fixed dispositions require an actual publishable source diff.");
94
137
  }
95
138
  for (const baselinePath of baselineChangedFiles.map(value => value.trim().replaceAll("\\", "/"))) {
96
139
  if (baselinePath && !authoritative.has(baselinePath)) {
97
- throw new Error(`Comment repair pre-publication repair removed '${baselinePath}' from the publishable staged source diff.`);
140
+ throw commentRepairChangedFilesMismatch(`Comment repair pre-publication repair removed '${baselinePath}' from the publishable staged source diff.`);
98
141
  }
99
142
  }
100
143
  payload.changed_files = authoritativePaths.map(filePath => {
@@ -1220,7 +1263,9 @@ export class ProcessBackedProviderCliService {
1220
1263
  }
1221
1264
  let commentRepairBaselineChangedFiles = null;
1222
1265
  if (addressComments && repairArtifact) {
1223
- commentRepairBaselineChangedFiles = await stagePublishableWorktreeChanges(this.git, worktree.worktreePath);
1266
+ const baseline = await stagePublishableWorktreeChangeSet(this.git, worktree.worktreePath);
1267
+ commentRepairBaselineChangedFiles = baseline.publishable;
1268
+ await assertFixedFindingsArePublished(this.git, worktree.worktreePath, dispatch, repairArtifact, baseline);
1224
1269
  assertCommentRepairArtifactMatchesChanges(repairArtifact, commentRepairBaselineChangedFiles);
1225
1270
  }
1226
1271
  const validationProfile = repairChecks
@@ -1236,8 +1281,10 @@ export class ProcessBackedProviderCliService {
1236
1281
  preparedHeadSha,
1237
1282
  repairScope: "pull_request",
1238
1283
  });
1239
- const stagedChangedFiles = await stagePublishableWorktreeChanges(this.git, worktree.worktreePath);
1284
+ const stagedChangeSet = await stagePublishableWorktreeChangeSet(this.git, worktree.worktreePath);
1285
+ const stagedChangedFiles = stagedChangeSet.publishable;
1240
1286
  if (addressComments && repairArtifact && commentRepairBaselineChangedFiles) {
1287
+ await assertFixedFindingsArePublished(this.git, worktree.worktreePath, dispatch, repairArtifact, stagedChangeSet);
1241
1288
  repairArtifact = await finalizeCommentRepairChangedFiles(repairArtifact, commentRepairBaselineChangedFiles, stagedChangedFiles);
1242
1289
  }
1243
1290
  const committed = await commitWorktreeChanges(this.git, worktree.worktreePath, dispatch.workItem.id, stagedChangedFiles);
@@ -1397,10 +1444,14 @@ export class ProcessBackedProviderCliService {
1397
1444
  session: { ...dispatch.session, resumeProviderThreadId: providerThreadId },
1398
1445
  };
1399
1446
  const recoveryPrompt = [
1400
- "Forge did not receive the required forge.complete_comment_repair call from your previous turn.",
1447
+ "Forge did not receive the required forge.complete_comment_repair call from your previous turn, so the provider process exited.",
1448
+ "Background watchers, monitors and notifications from that turn did not survive and will never report back,",
1449
+ "and Forge stopped any managed command that process was still running; its receipt reports that.",
1401
1450
  "Resume the existing work exactly where it is. Do not reimplement or discard the prepared changes.",
1402
- "Review the current diff and the durable review snapshot, preserve the validation evidence already gathered,",
1403
- "then call forge.complete_comment_repair with an evidence-backed disposition for every actionable finding.",
1451
+ "Review the current diff and the durable review snapshot and preserve the validation evidence already gathered.",
1452
+ "Check each managed command with forge.get_managed_command, restart any that were interrupted,",
1453
+ "and block on long commands with forge.wait_managed_command, calling it again while command_continues is true.",
1454
+ "Do not end your turn until you have called forge.complete_comment_repair with an evidence-backed disposition for every actionable finding.",
1404
1455
  "Do not commit or push; Forge owns publication after the completion gate succeeds.",
1405
1456
  ].join(" ");
1406
1457
  const providerPrompt = buildProviderCliPrompt(recoveryDispatch, recoveryPrompt, repairEnvironment);
@@ -0,0 +1,45 @@
1
+ import { GitClient } from "../shared/git/git.js";
2
+ import { type ProcessRunner } from "../shared/process/process.js";
3
+ export interface PublishableWorktreeChangeSet {
4
+ /** Paths staged for publication, as `git diff --cached --name-only` reports them. */
5
+ readonly publishable: readonly string[];
6
+ /** Worktree changes Forge treats as runtime output and leaves unstaged. */
7
+ readonly excluded: readonly string[];
8
+ }
9
+ /**
10
+ * Decides whether a staged change is Forge runtime output rather than an author edit.
11
+ *
12
+ * `.local/`, `.forge/work-items/` and `.forge/stories/` are always runtime output. Any
13
+ * other `.forge/` path is runtime output only when HEAD does not track it (status `A`):
14
+ * that covers injected managed commands, hooks and skills. The injector never overwrites a
15
+ * tracked `.forge/` file and restores one that matches the managed body, so a tracked
16
+ * `.forge/` file that differs from HEAD is an author edit and must be published.
17
+ */
18
+ export declare function isNonPublishableWorktreeChange(relativePath: string, status: string): boolean;
19
+ /** Stages every publishable worktree change in the real index and returns both sets. */
20
+ export declare function stagePublishableWorktreeChangeSet(git: Pick<GitClient, "run">, worktreePath: string): Promise<PublishableWorktreeChangeSet>;
21
+ /**
22
+ * Computes the same change set as {@link stagePublishableWorktreeChangeSet} without
23
+ * touching the worktree's index, using a throwaway copy of it. Returns null when
24
+ * `worktreePath` is not the root of a git worktree.
25
+ */
26
+ export declare function readPublishableWorktreeChangeSet(worktreePath: string, processRunner?: ProcessRunner): Promise<PublishableWorktreeChangeSet | null>;
27
+ /** Compares claimed `changed_files` paths with the publishable diff. */
28
+ export declare function diffClaimedChangedFiles(claimedPaths: readonly string[], publishablePaths: readonly string[]): {
29
+ readonly missing: readonly string[];
30
+ readonly unexpected: readonly string[];
31
+ };
32
+ export declare function normalizeChangedFilePath(value: string): string;
33
+ /**
34
+ * In-tool check for `forge.complete_comment_repair`: rejects a pass payload whose
35
+ * `changed_files` differs from what Forge would publish, so the agent can correct it
36
+ * in the same turn instead of failing at publication.
37
+ */
38
+ export declare function assertClaimedChangedFilesMatchPublishableDiff(worktreePath: string, payload: Record<string, unknown>, toolName: string, processRunner?: ProcessRunner): Promise<void>;
39
+ /**
40
+ * Returns the given paths whose worktree content differs from HEAD but is not in the
41
+ * publishable set: excluded runtime output, and untracked or git-ignored files that are
42
+ * never staged at all (for example an injected `.forge/` file in a repository that ignores
43
+ * `.forge/`). A review finding on such a path cannot be fixed by the published commit.
44
+ */
45
+ export declare function findUnpublishedWorktreePaths(git: Pick<GitClient, "run">, worktreePath: string, paths: readonly string[], publishablePaths: readonly string[]): Promise<readonly string[]>;