@loucompanion/forge-bridge 0.1.3-dev.fbe15023cdfe → 0.1.4-dev.028808a841c8

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 (185) hide show
  1. package/README.md +89 -3
  2. package/dist/bridge/bridge-chat.types.d.ts +111 -0
  3. package/dist/bridge/bridge-chat.types.js +401 -0
  4. package/dist/bridge/bridge.base.d.ts +4 -1
  5. package/dist/bridge/bridge.service.d.ts +83 -3
  6. package/dist/bridge/bridge.service.js +1609 -152
  7. package/dist/bridge/bridge.types.d.ts +52 -1
  8. package/dist/bridge/dispatch-result-outbox.d.ts +35 -0
  9. package/dist/bridge/dispatch-result-outbox.js +87 -0
  10. package/dist/bridge/dispatch-result-worker.d.ts +2 -0
  11. package/dist/bridge/dispatch-result-worker.js +122 -0
  12. package/dist/bridge/internals.d.ts +2 -0
  13. package/dist/bridge/internals.js +1 -0
  14. package/dist/bridge/readiness-result-outbox.d.ts +21 -0
  15. package/dist/bridge/readiness-result-outbox.js +54 -0
  16. package/dist/bridge/readiness-result-worker.d.ts +2 -0
  17. package/dist/bridge/readiness-result-worker.js +121 -0
  18. package/dist/bridge/runner-host-capabilities.d.ts +15 -0
  19. package/dist/bridge/runner-host-capabilities.js +93 -0
  20. package/dist/cleanup/cleanup.service.d.ts +1 -0
  21. package/dist/cleanup/cleanup.service.js +70 -9
  22. package/dist/cli/cli.help.js +4 -4
  23. package/dist/cli/cli.service.d.ts +14 -6
  24. package/dist/cli/cli.service.js +75 -16
  25. package/dist/cli/local-config.d.ts +1 -0
  26. package/dist/cli/local-config.js +4 -0
  27. package/dist/runtime/aspnet-runtime-prebuild.d.ts +36 -0
  28. package/dist/runtime/aspnet-runtime-prebuild.js +341 -0
  29. package/dist/runtime/attempt-database-broker.d.ts +89 -0
  30. package/dist/runtime/attempt-database-broker.js +390 -0
  31. package/dist/runtime/attempt-node-runtime-launcher.d.ts +2 -1
  32. package/dist/runtime/attempt-node-runtime-launcher.js +57 -18
  33. package/dist/runtime/attempt-path-operation.d.ts +21 -0
  34. package/dist/runtime/attempt-path-operation.js +94 -0
  35. package/dist/runtime/attempt-private-directory.d.ts +6 -0
  36. package/dist/runtime/attempt-private-directory.js +54 -0
  37. package/dist/runtime/attempt-process-supervisor.d.ts +35 -0
  38. package/dist/runtime/attempt-process-supervisor.js +144 -23
  39. package/dist/runtime/canonical-source-file.d.ts +3 -0
  40. package/dist/runtime/canonical-source-file.js +54 -0
  41. package/dist/runtime/docker-engine-probe.d.ts +90 -0
  42. package/dist/runtime/docker-engine-probe.js +333 -0
  43. package/dist/runtime/generated-output-reset.d.ts +10 -0
  44. package/dist/runtime/generated-output-reset.js +62 -8
  45. package/dist/runtime/host-database-capability-boundary.d.ts +16 -0
  46. package/dist/runtime/host-database-capability-boundary.js +63 -0
  47. package/dist/runtime/host-diagnostics.d.ts +11 -0
  48. package/dist/runtime/host-diagnostics.js +192 -0
  49. package/dist/runtime/host-execution-root.d.ts +4 -0
  50. package/dist/runtime/host-execution-root.js +39 -0
  51. package/dist/runtime/host-facts.d.ts +35 -0
  52. package/dist/runtime/host-facts.js +95 -0
  53. package/dist/runtime/host-listener-inspector.d.ts +8 -1
  54. package/dist/runtime/host-listener-inspector.js +121 -60
  55. package/dist/runtime/host-load-sampler.d.ts +83 -0
  56. package/dist/runtime/host-load-sampler.js +164 -0
  57. package/dist/runtime/host-pressure-stall.d.ts +41 -0
  58. package/dist/runtime/host-pressure-stall.js +121 -0
  59. package/dist/runtime/host-runtime-contract.d.ts +13 -1
  60. package/dist/runtime/host-runtime-contract.js +170 -55
  61. package/dist/runtime/host-runtime-lease.d.ts +92 -8
  62. package/dist/runtime/host-runtime-lease.js +1193 -120
  63. package/dist/runtime/host-runtime-promotion.d.ts +12 -3
  64. package/dist/runtime/host-runtime-promotion.js +59 -12
  65. package/dist/runtime/managed-command-teardown.d.ts +62 -0
  66. package/dist/runtime/managed-command-teardown.js +607 -0
  67. package/dist/runtime/memory-capacity.d.ts +70 -0
  68. package/dist/runtime/memory-capacity.js +123 -0
  69. package/dist/runtime/native-test-postgres-fallback.d.ts +25 -0
  70. package/dist/runtime/native-test-postgres-fallback.js +91 -0
  71. package/dist/runtime/node-host-runtime-adapter.d.ts +3 -0
  72. package/dist/runtime/node-host-runtime-adapter.js +29 -11
  73. package/dist/runtime/pinned-directory-process.d.ts +9 -0
  74. package/dist/runtime/pinned-directory-process.js +61 -0
  75. package/dist/runtime/pinned-source-directory.d.ts +17 -0
  76. package/dist/runtime/pinned-source-directory.js +94 -0
  77. package/dist/runtime/playwright-browser-cache.d.ts +39 -0
  78. package/dist/runtime/playwright-browser-cache.js +227 -0
  79. package/dist/runtime/playwright-host-runtime-adapter.d.ts +12 -0
  80. package/dist/runtime/playwright-host-runtime-adapter.js +100 -58
  81. package/dist/runtime/prepared-runtime-identity.d.ts +6 -0
  82. package/dist/runtime/prepared-runtime-identity.js +218 -0
  83. package/dist/runtime/prepared-runtime-readiness.d.ts +30 -0
  84. package/dist/runtime/prepared-runtime-readiness.js +285 -0
  85. package/dist/runtime/runtime-isolation-lease.js +4 -1
  86. package/dist/runtime/workspace-resource-estimator.d.ts +17 -0
  87. package/dist/runtime/workspace-resource-estimator.js +174 -0
  88. package/dist/sandbox/preflight.d.ts +31 -1
  89. package/dist/sandbox/preflight.js +237 -51
  90. package/dist/sandbox/repository-lock.d.ts +2 -1
  91. package/dist/sandbox/repository-lock.js +19 -9
  92. package/dist/sandbox/runtime.d.ts +6 -1
  93. package/dist/sandbox/runtime.js +137 -107
  94. package/dist/sandbox/sandbox.types.d.ts +7 -0
  95. package/dist/sandbox/workspace.service.js +2 -0
  96. package/dist/session/managed-attempt-tools.d.ts +42 -1
  97. package/dist/session/managed-attempt-tools.js +692 -40
  98. package/dist/session/managed-build-coordinator.d.ts +5 -0
  99. package/dist/session/managed-build-coordinator.js +109 -0
  100. package/dist/session/managed-build-receipt.d.ts +21 -0
  101. package/dist/session/managed-build-receipt.js +337 -0
  102. package/dist/session/managed-verification-timeouts.d.ts +8 -0
  103. package/dist/session/managed-verification-timeouts.js +17 -0
  104. package/dist/session/phase-completion.artifacts.d.ts +17 -0
  105. package/dist/session/phase-completion.artifacts.js +228 -22
  106. package/dist/session/phase-completion.d.ts +11 -1
  107. package/dist/session/phase-completion.helpers.d.ts +5 -0
  108. package/dist/session/phase-completion.helpers.js +30 -7
  109. package/dist/session/phase-completion.js +14 -3
  110. package/dist/session/phase-completion.prompts.js +17 -18
  111. package/dist/session/phase-completion.runtime.d.ts +3 -1
  112. package/dist/session/phase-completion.runtime.js +148 -34
  113. package/dist/session/phase-completion.schemas.js +49 -2
  114. package/dist/session/phase-completion.validation.d.ts +1 -0
  115. package/dist/session/phase-completion.validation.js +111 -21
  116. package/dist/session/pre-publication-process.d.ts +20 -0
  117. package/dist/session/pre-publication-process.js +97 -0
  118. package/dist/session/pre-publication-skipped-tests.d.ts +21 -0
  119. package/dist/session/pre-publication-skipped-tests.js +109 -0
  120. package/dist/session/pre-publication-validation.d.ts +75 -0
  121. package/dist/session/pre-publication-validation.js +631 -0
  122. package/dist/session/provider-cli/bridge-cli.conformance-fixtures.d.ts +72 -0
  123. package/dist/session/provider-cli/bridge-cli.conformance-fixtures.js +462 -0
  124. package/dist/session/provider-cli/ci-repair-readiness.d.ts +8 -0
  125. package/dist/session/provider-cli/ci-repair-readiness.js +23 -3
  126. package/dist/session/provider-cli/provider-cli.artifacts.d.ts +6 -3
  127. package/dist/session/provider-cli/provider-cli.artifacts.js +62 -22
  128. package/dist/session/provider-cli/provider-cli.deterministic.js +34 -2
  129. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
  130. package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
  131. package/dist/session/provider-cli/provider-cli.process.d.ts +80 -0
  132. package/dist/session/provider-cli/provider-cli.process.js +694 -28
  133. package/dist/session/provider-cli/provider-cli.prompts.d.ts +10 -0
  134. package/dist/session/provider-cli/provider-cli.prompts.js +151 -16
  135. package/dist/session/provider-cli/provider-cli.repair-epoch.d.ts +6 -0
  136. package/dist/session/provider-cli/provider-cli.repair-epoch.js +11 -0
  137. package/dist/session/provider-cli/provider-cli.runtime.d.ts +14 -1
  138. package/dist/session/provider-cli/provider-cli.runtime.js +54 -3
  139. package/dist/session/provider-cli/provider-cli.service.d.ts +30 -5
  140. package/dist/session/provider-cli/provider-cli.service.js +858 -77
  141. package/dist/session/provider-cli/provider-cli.types.d.ts +2 -0
  142. package/dist/session/provider-cli/provider-in-flight-work.d.ts +6 -0
  143. package/dist/session/provider-cli/provider-in-flight-work.js +47 -0
  144. package/dist/session/provider-cli/provider-output-state.d.ts +16 -0
  145. package/dist/session/provider-cli/provider-output-state.js +370 -17
  146. package/dist/session/provider-cli/provider-usage.d.ts +9 -1
  147. package/dist/session/provider-cli/provider-usage.js +28 -5
  148. package/dist/session/publishable-worktree-changes.d.ts +54 -0
  149. package/dist/session/publishable-worktree-changes.js +193 -0
  150. package/dist/session/session-redaction.js +434 -9
  151. package/dist/session/session.service.js +145 -23
  152. package/dist/session/session.types.d.ts +147 -2
  153. package/dist/session/session.types.js +599 -7
  154. package/dist/session/unreferenced-exports.d.ts +12 -0
  155. package/dist/session/unreferenced-exports.js +59 -0
  156. package/dist/shared/format/format-bytes.d.ts +1 -0
  157. package/dist/shared/format/format-bytes.js +9 -0
  158. package/dist/shared/git/git.js +2 -1
  159. package/dist/shared/path/path.d.ts +1 -0
  160. package/dist/shared/path/path.js +18 -0
  161. package/dist/shared/process/dotnet-toolchain.d.ts +17 -0
  162. package/dist/shared/process/dotnet-toolchain.js +307 -0
  163. package/dist/shared/process/host-process-recovery.js +3 -2
  164. package/dist/shared/process/host-process-supervisor.d.ts +2 -0
  165. package/dist/shared/process/host-process-supervisor.js +60 -11
  166. package/dist/shared/process/process.d.ts +2 -0
  167. package/dist/shared/process/process.js +12 -7
  168. package/dist/shared/provider-capabilities.d.ts +3 -0
  169. package/dist/shared/provider-capabilities.js +85 -0
  170. package/dist/shared/redaction/redaction.d.ts +1 -0
  171. package/dist/shared/redaction/redaction.js +39 -3
  172. package/dist/shared/time/monotonic.d.ts +1 -0
  173. package/dist/shared/time/monotonic.js +8 -0
  174. package/dist/version.d.ts +1 -1
  175. package/dist/version.js +1 -1
  176. package/dist/worktree/dependency-warmer.d.ts +41 -9
  177. package/dist/worktree/dependency-warmer.js +571 -22
  178. package/dist/worktree/index.d.ts +1 -1
  179. package/dist/worktree/story-qa-reference-hydrator.d.ts +4 -0
  180. package/dist/worktree/story-qa-reference-hydrator.js +253 -0
  181. package/dist/worktree/worktree.service.d.ts +7 -0
  182. package/dist/worktree/worktree.service.js +253 -21
  183. package/dist/worktree/worktree.types.d.ts +7 -1
  184. package/package.json +7 -5
  185. package/runtime/windows-job-supervisor.ps1 +380 -14
@@ -0,0 +1,54 @@
1
+ import fs from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { runAttemptPathOperation } from "./attempt-path-operation.js";
4
+ /** Validate every existing ancestor before creating anything through a pathname. */
5
+ export async function assertCanonicalDirectory(target, allowMissing = false) {
6
+ const resolved = path.resolve(target);
7
+ const parent = path.dirname(resolved);
8
+ if (parent !== resolved)
9
+ await assertCanonicalDirectory(parent, allowMissing);
10
+ try {
11
+ const stat = await fs.lstat(resolved, { bigint: true });
12
+ const real = await fs.realpath(resolved);
13
+ const realStat = await fs.lstat(real, { bigint: true });
14
+ if (stat.isSymbolicLink() || !stat.isDirectory() || !samePath(real, resolved)
15
+ || stat.dev !== realStat.dev || stat.ino !== realStat.ino) {
16
+ throw new Error("playwright_runtime_adapter_invalid: writable paths must be canonical, link-free directories.");
17
+ }
18
+ return realStat;
19
+ }
20
+ catch (error) {
21
+ if (allowMissing && error.code === "ENOENT")
22
+ return;
23
+ throw error;
24
+ }
25
+ }
26
+ export async function createCanonicalDirectory(target) {
27
+ if (await assertCanonicalDirectory(target, true))
28
+ return;
29
+ const resolved = path.resolve(target);
30
+ let parent = path.dirname(resolved);
31
+ let identity = await assertCanonicalDirectory(parent, true);
32
+ while (!identity) {
33
+ parent = path.dirname(parent);
34
+ identity = await assertCanonicalDirectory(parent, true);
35
+ }
36
+ await runAttemptPathOperation(parent, identity, { kind: "mkdir", segments: path.relative(parent, resolved).split(path.sep) });
37
+ await assertCanonicalDirectory(resolved);
38
+ }
39
+ export async function createPrivateCanonicalDirectory(target) {
40
+ await createCanonicalDirectory(target);
41
+ await restorePrivateDirectoryMode(target);
42
+ }
43
+ export async function restorePrivateDirectoryMode(target) {
44
+ if (process.platform === "win32")
45
+ return;
46
+ const resolved = path.resolve(target);
47
+ const parent = path.dirname(resolved);
48
+ const identity = await assertCanonicalDirectory(parent);
49
+ await runAttemptPathOperation(parent, identity, { kind: "private-directory-mode", segments: [path.basename(resolved)] });
50
+ await assertCanonicalDirectory(resolved);
51
+ }
52
+ function samePath(left, right) {
53
+ return process.platform === "win32" ? left.toLowerCase() === right.toLowerCase() : left === right;
54
+ }
@@ -1,4 +1,5 @@
1
1
  import type { ProviderProcessHandlers, ProviderProcessRunRequest, ProviderProcessRunner, ProviderProcessRunResult } from "../session/provider-cli/provider-cli.process.js";
2
+ import { type ManagedCommandTeardownOptions, type ManagedCommandTeardownOutcome } from "./managed-command-teardown.js";
2
3
  export type AttemptProcessChildStatus = "starting" | "running" | "stopping" | "exited" | "failed";
3
4
  export type AttemptProcessSupervisorStatus = "active" | "stopping" | "stopped" | "degraded";
4
5
  export interface AttemptProcessSupervisorIdentity {
@@ -19,6 +20,10 @@ export interface AttemptProcessChildLedgerEntry {
19
20
  readonly settledAt?: string;
20
21
  readonly exitCode?: number;
21
22
  readonly failure?: string;
23
+ readonly peakMemoryBytes?: number;
24
+ readonly memorySampleCount?: number;
25
+ readonly memorySource?: string;
26
+ readonly memoryObservedAt?: string;
22
27
  }
23
28
  export interface AttemptProcessSupervisorLedger {
24
29
  readonly schemaVersion: 1;
@@ -28,6 +33,8 @@ export interface AttemptProcessSupervisorLedger {
28
33
  readonly status: AttemptProcessSupervisorStatus;
29
34
  readonly updatedAt: string;
30
35
  readonly children: readonly AttemptProcessChildLedgerEntry[];
36
+ /** A provider-exit managed-command cleanup that failed and was left to attempt teardown. */
37
+ readonly deferredManagedCommandTeardownFailure?: string;
31
38
  }
32
39
  export interface AttemptProcessChildHandle {
33
40
  readonly name: string;
@@ -42,6 +49,9 @@ export interface AttemptProcessChildHandle {
42
49
  export interface AttemptProcessSupervisorOptions {
43
50
  readonly metadataReadyTimeoutMs?: number;
44
51
  readonly signal?: AbortSignal;
52
+ readonly replaceLedgerFile?: (temporaryPath: string, ledgerPath: string) => Promise<void>;
53
+ readonly ledgerReplaceRetryMs?: number;
54
+ readonly managedCommandTeardownGraceMs?: number;
45
55
  }
46
56
  export interface AttemptProcessChildReadyOptions {
47
57
  readonly maxStartAttempts?: number;
@@ -58,6 +68,9 @@ export declare class AttemptProcessSupervisor {
58
68
  readonly ledgerPath: string;
59
69
  private readonly identity;
60
70
  private readonly metadataReadyTimeoutMs;
71
+ private readonly replaceLedgerFile;
72
+ private readonly ledgerReplaceRetryMs;
73
+ private readonly managedCommandTeardownGraceMs;
61
74
  private readonly records;
62
75
  private readonly currentByName;
63
76
  private readonly attemptController;
@@ -65,6 +78,8 @@ export declare class AttemptProcessSupervisor {
65
78
  private persistTail;
66
79
  private persistenceFailure;
67
80
  private stopOperation;
81
+ private managedCommandTeardownTail;
82
+ private deferredManagedCommandTeardownFailure;
68
83
  constructor(identity: AttemptProcessSupervisorIdentity, runner: ProviderProcessRunner, options?: AttemptProcessSupervisorOptions);
69
84
  startChild(name: string, request: ProviderProcessRunRequest, handlers?: ProviderProcessHandlers, signal?: AbortSignal): Promise<AttemptProcessChildHandle>;
70
85
  /**
@@ -78,9 +93,29 @@ export declare class AttemptProcessSupervisor {
78
93
  stopChild(name: string, generation: number, fencingToken: string, reason?: unknown): Promise<ProviderProcessRunResult>;
79
94
  stopAll(fencingToken: string, reason?: unknown): Promise<void>;
80
95
  private performStopAll;
96
+ /**
97
+ * Stops the managed commands this attempt's MCP servers started and finalizes their
98
+ * receipts. With `onlyOrphaned`, a command whose owning MCP server is still alive is
99
+ * left running: it survives wait slices and MCP call boundaries within a live provider.
100
+ */
101
+ terminateManagedCommands(options: Omit<ManagedCommandTeardownOptions, "graceMs">): Promise<readonly ManagedCommandTeardownOutcome[]>;
102
+ /**
103
+ * After a provider exits, stops the managed commands its MCP server left behind. It never
104
+ * fails the provider's result: a command it cannot prove stopped is recorded in the ledger
105
+ * and left to attempt teardown, which fails closed.
106
+ */
107
+ stopOrphanedManagedCommands(): Promise<void>;
81
108
  snapshot(): AttemptProcessSupervisorLedger;
109
+ providerMemoryTelemetry(): AttemptProcessTreeMemoryTelemetry | null;
82
110
  private observeChildReady;
83
111
  private settleChild;
112
+ private replaceLedger;
84
113
  private assertFence;
85
114
  private persist;
86
115
  }
116
+ export interface AttemptProcessTreeMemoryTelemetry {
117
+ readonly peakMemoryBytes: number;
118
+ readonly sampleCount: number;
119
+ readonly source: string;
120
+ readonly observedAt: string;
121
+ }
@@ -1,8 +1,16 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import fs from "node:fs/promises";
3
3
  import path from "node:path";
4
+ import { ForgeFailureError, sanitizeFailureError } from "../session/session.types.js";
5
+ import { terminateAttemptManagedCommands, } from "./managed-command-teardown.js";
6
+ import { monotonicNowMs } from "../shared/time/monotonic.js";
4
7
  const terminalChildStatuses = new Set(["exited", "failed"]);
5
8
  const defaultMetadataReadyTimeoutMs = process.platform === "win32" ? 60_000 : 10_000;
9
+ // Windows refuses to replace a file another process (a scanner or indexer) briefly holds
10
+ // open. One such refusal must not degrade the attempt, so the ledger replace is retried.
11
+ const ledgerReplaceAttempts = 40;
12
+ const defaultLedgerReplaceRetryMs = 25;
13
+ const transientLedgerReplaceCodes = new Set(["EPERM", "EACCES", "EBUSY"]);
6
14
  /**
7
15
  * Owns the independently supervised process trees that belong to one host
8
16
  * dispatch attempt. Each named child gets a distinct Windows Job Object or
@@ -14,6 +22,9 @@ export class AttemptProcessSupervisor {
14
22
  ledgerPath;
15
23
  identity;
16
24
  metadataReadyTimeoutMs;
25
+ replaceLedgerFile;
26
+ ledgerReplaceRetryMs;
27
+ managedCommandTeardownGraceMs;
17
28
  records = [];
18
29
  currentByName = new Map();
19
30
  attemptController = new AbortController();
@@ -21,10 +32,15 @@ export class AttemptProcessSupervisor {
21
32
  persistTail = Promise.resolve();
22
33
  persistenceFailure;
23
34
  stopOperation = null;
35
+ managedCommandTeardownTail = Promise.resolve();
36
+ deferredManagedCommandTeardownFailure;
24
37
  constructor(identity, runner, options = {}) {
25
38
  this.runner = runner;
26
39
  this.identity = validateIdentity(identity);
27
40
  this.metadataReadyTimeoutMs = boundedInteger(options.metadataReadyTimeoutMs ?? defaultMetadataReadyTimeoutMs, 100, 120_000, "metadataReadyTimeoutMs");
41
+ this.replaceLedgerFile = options.replaceLedgerFile ?? ((temporaryPath, ledgerPath) => fs.rename(temporaryPath, ledgerPath));
42
+ this.ledgerReplaceRetryMs = options.ledgerReplaceRetryMs ?? defaultLedgerReplaceRetryMs;
43
+ this.managedCommandTeardownGraceMs = options.managedCommandTeardownGraceMs;
28
44
  this.ledgerPath = path.join(this.identity.logDirectory, "attempt-process-supervisor.json");
29
45
  if (options.signal?.aborted) {
30
46
  this.status = "stopping";
@@ -32,9 +48,11 @@ export class AttemptProcessSupervisor {
32
48
  }
33
49
  else {
34
50
  options.signal?.addEventListener("abort", () => {
35
- void this.stopAll(this.identity.fencingToken, options.signal?.reason).catch(error => {
36
- this.persistenceFailure ??= error;
37
- });
51
+ // stopAll already persists a degraded terminal snapshot when a child
52
+ // rejects during cancellation. Do not relabel that process failure as
53
+ // a persistence failure: doing so poisons every later cleanup retry,
54
+ // even after all supervised processes have exited.
55
+ void this.stopAll(this.identity.fencingToken, options.signal?.reason).catch(() => undefined);
38
56
  }, { once: true });
39
57
  }
40
58
  }
@@ -57,8 +75,10 @@ export class AttemptProcessSupervisor {
57
75
  const combinedSignal = signal
58
76
  ? AbortSignal.any([this.attemptController.signal, controller.signal, signal])
59
77
  : AbortSignal.any([this.attemptController.signal, controller.signal]);
78
+ const failureRedactionValues = [...new Set((request.failureRedactionValues ?? []).filter(value => value.length > 0))];
79
+ const { failureRedactionValues: _failureRedactionValues, ...executableRequest } = request;
60
80
  const childRequest = {
61
- ...request,
81
+ ...executableRequest,
62
82
  env: {
63
83
  ...request.env,
64
84
  FORGE_RUNTIME_MODE: "host",
@@ -82,6 +102,7 @@ export class AttemptProcessSupervisor {
82
102
  processSupervisorId,
83
103
  metadataPath,
84
104
  controller,
105
+ failureRedactionValues,
85
106
  startedAt,
86
107
  status: "starting",
87
108
  result: Promise.resolve({ exitCode: 1, stdout: "", stderr: "not started" }),
@@ -90,7 +111,7 @@ export class AttemptProcessSupervisor {
90
111
  this.currentByName.set(name, record);
91
112
  const result = this.runner.run(childRequest, handlers, combinedSignal);
92
113
  record.result = result;
93
- void result.then(value => this.settleChild(record, "exited", value.exitCode), error => this.settleChild(record, "failed", undefined, error));
114
+ void result.then(value => this.settleChild(record, "exited", value.exitCode, undefined, value), error => this.settleChild(record, "failed", undefined, error));
94
115
  try {
95
116
  await this.persist();
96
117
  }
@@ -180,7 +201,17 @@ export class AttemptProcessSupervisor {
180
201
  record.status = "stopping";
181
202
  await this.persist();
182
203
  const results = await Promise.allSettled(active.map(record => record.result));
183
- const rejected = results.filter((result) => result.status === "rejected");
204
+ const rejected = results.flatMap((result, index) => result.status === "rejected"
205
+ ? [sanitizeFailureError(result.reason, active[index].failureRedactionValues)]
206
+ : []);
207
+ // Managed commands run in their own process groups, outside every child tree stopped
208
+ // above. The attempt is not stopped until each of them is proven stopped too.
209
+ try {
210
+ await this.terminateManagedCommands({ reason: "attempt_teardown" });
211
+ }
212
+ catch (error) {
213
+ rejected.push(error instanceof Error ? error : new Error(String(error)));
214
+ }
184
215
  const terminalStatus = rejected.length > 0 || this.persistenceFailure !== undefined ? "degraded" : "stopped";
185
216
  await this.persist({
186
217
  ...this.snapshot(),
@@ -189,11 +220,45 @@ export class AttemptProcessSupervisor {
189
220
  });
190
221
  this.status = terminalStatus;
191
222
  if (rejected.length > 0) {
192
- throw new AggregateError(rejected.map(result => result.reason), "attempt_process_supervisor_cleanup_degraded");
223
+ throw new AggregateError(rejected, "attempt_process_supervisor_cleanup_degraded");
193
224
  }
194
225
  if (this.persistenceFailure !== undefined)
195
226
  throw this.persistenceFailure;
196
227
  }
228
+ /**
229
+ * Stops the managed commands this attempt's MCP servers started and finalizes their
230
+ * receipts. With `onlyOrphaned`, a command whose owning MCP server is still alive is
231
+ * left running: it survives wait slices and MCP call boundaries within a live provider.
232
+ */
233
+ async terminateManagedCommands(options) {
234
+ // One sweep at a time: a provider-exit sweep and attempt teardown would otherwise
235
+ // signal the same groups and write the same receipts concurrently, and stopAll must
236
+ // not report the attempt stopped while an earlier sweep is still writing.
237
+ const sweep = this.managedCommandTeardownTail.then(async () => await terminateAttemptManagedCommands({
238
+ logDirectory: this.identity.logDirectory,
239
+ dispatchAttemptId: this.identity.dispatchAttemptId,
240
+ runtimeLeaseId: this.identity.executionLeaseId,
241
+ }, {
242
+ ...options,
243
+ ...(this.managedCommandTeardownGraceMs === undefined ? {} : { graceMs: this.managedCommandTeardownGraceMs }),
244
+ }));
245
+ this.managedCommandTeardownTail = sweep.catch(() => undefined);
246
+ return await sweep;
247
+ }
248
+ /**
249
+ * After a provider exits, stops the managed commands its MCP server left behind. It never
250
+ * fails the provider's result: a command it cannot prove stopped is recorded in the ledger
251
+ * and left to attempt teardown, which fails closed.
252
+ */
253
+ async stopOrphanedManagedCommands() {
254
+ try {
255
+ await this.terminateManagedCommands({ reason: "owner_exited", onlyOrphaned: true });
256
+ }
257
+ catch (error) {
258
+ this.deferredManagedCommandTeardownFailure = boundedFailure(error, []);
259
+ await this.persist().catch(() => undefined);
260
+ }
261
+ }
197
262
  snapshot() {
198
263
  return {
199
264
  schemaVersion: 1,
@@ -202,6 +267,9 @@ export class AttemptProcessSupervisor {
202
267
  executionLeaseId: this.identity.executionLeaseId,
203
268
  status: this.status,
204
269
  updatedAt: new Date().toISOString(),
270
+ ...(this.deferredManagedCommandTeardownFailure
271
+ ? { deferredManagedCommandTeardownFailure: this.deferredManagedCommandTeardownFailure }
272
+ : {}),
205
273
  children: this.records.map(record => ({
206
274
  name: record.name,
207
275
  generation: record.generation,
@@ -213,12 +281,35 @@ export class AttemptProcessSupervisor {
213
281
  ...(record.settledAt ? { settledAt: record.settledAt } : {}),
214
282
  ...(record.exitCode === undefined ? {} : { exitCode: record.exitCode }),
215
283
  ...(record.failure ? { failure: record.failure } : {}),
284
+ ...(record.peakMemoryBytes === undefined ? {} : { peakMemoryBytes: record.peakMemoryBytes }),
285
+ ...(record.memorySampleCount === undefined ? {} : { memorySampleCount: record.memorySampleCount }),
286
+ ...(record.memorySource ? { memorySource: record.memorySource } : {}),
287
+ ...(record.memoryObservedAt ? { memoryObservedAt: record.memoryObservedAt } : {}),
216
288
  })),
217
289
  };
218
290
  }
291
+ providerMemoryTelemetry() {
292
+ const observations = this.records
293
+ .filter(record => record.name === "provider"
294
+ && record.peakMemoryBytes !== undefined
295
+ && record.peakMemoryBytes > 0
296
+ && record.memorySampleCount !== undefined
297
+ && record.memorySampleCount > 0
298
+ && record.memorySource
299
+ && record.memoryObservedAt);
300
+ if (observations.length === 0)
301
+ return null;
302
+ const peak = observations.reduce((current, candidate) => (candidate.peakMemoryBytes ?? 0) > (current.peakMemoryBytes ?? 0) ? candidate : current);
303
+ return {
304
+ peakMemoryBytes: peak.peakMemoryBytes,
305
+ sampleCount: observations.reduce((total, candidate) => total + (candidate.memorySampleCount ?? 0), 0),
306
+ source: peak.memorySource,
307
+ observedAt: peak.memoryObservedAt,
308
+ };
309
+ }
219
310
  async observeChildReady(record) {
220
- const deadline = Date.now() + this.metadataReadyTimeoutMs;
221
- while (Date.now() <= deadline) {
311
+ const deadline = monotonicNowMs() + this.metadataReadyTimeoutMs;
312
+ while (monotonicNowMs() <= deadline) {
222
313
  if (await fileExists(record.metadataPath)) {
223
314
  if (record.status === "starting") {
224
315
  record.status = "running";
@@ -228,24 +319,51 @@ export class AttemptProcessSupervisor {
228
319
  }
229
320
  if (terminalChildStatuses.has(record.status)) {
230
321
  const detail = await childStartFailureDetail(record);
231
- throw new Error(`attempt_process_supervisor_start_failed: child '${record.childId}' exited before supervision metadata was produced${detail ? `: ${detail}` : "."}`);
322
+ throw new ForgeFailureError("attempt_process_supervisor_start_failed", `attempt_process_supervisor_start_failed: child '${record.childId}' exited before supervision metadata was produced${detail ? `: ${detail}` : "."}`, "bridge");
232
323
  }
233
324
  await wait(25);
234
325
  }
235
326
  record.controller.abort("Supervised child metadata was not produced before the readiness deadline.");
236
327
  const detail = await childStartFailureDetail(record);
237
- throw new Error(`attempt_process_supervisor_start_timeout: child '${record.childId}' did not become supervised${detail ? `: ${detail}` : "."}`);
328
+ throw new ForgeFailureError("attempt_process_supervisor_start_timeout", `attempt_process_supervisor_start_timeout: child '${record.childId}' did not become supervised${detail ? `: ${detail}` : "."}`, "bridge");
238
329
  }
239
- async settleChild(record, status, exitCode, failure) {
330
+ async settleChild(record, status, exitCode, failure, result) {
240
331
  record.status = status;
241
332
  record.settledAt = new Date().toISOString();
242
333
  record.exitCode = exitCode;
243
- record.failure = failure === undefined ? undefined : boundedFailure(failure);
334
+ record.failure = failure === undefined
335
+ ? undefined
336
+ : boundedFailure(failure, record.failureRedactionValues);
337
+ if (result?.peakMemoryBytes !== undefined
338
+ && result.peakMemoryBytes > 0
339
+ && result.memorySampleCount !== undefined
340
+ && result.memorySampleCount > 0
341
+ && result.memorySource
342
+ && result.memoryObservedAt) {
343
+ record.peakMemoryBytes = result.peakMemoryBytes;
344
+ record.memorySampleCount = result.memorySampleCount;
345
+ record.memorySource = result.memorySource;
346
+ record.memoryObservedAt = result.memoryObservedAt;
347
+ }
244
348
  await this.persist().catch(error => {
245
349
  this.persistenceFailure ??= error;
246
350
  this.status = "degraded";
247
351
  });
248
352
  }
353
+ async replaceLedger(temporary) {
354
+ for (let attempt = 1;; attempt += 1) {
355
+ try {
356
+ await this.replaceLedgerFile(temporary, this.ledgerPath);
357
+ return;
358
+ }
359
+ catch (error) {
360
+ const code = error.code;
361
+ if (attempt >= ledgerReplaceAttempts || !code || !transientLedgerReplaceCodes.has(code))
362
+ throw error;
363
+ await wait(this.ledgerReplaceRetryMs);
364
+ }
365
+ }
366
+ }
249
367
  assertFence(fencingToken) {
250
368
  if (fencingToken !== this.identity.fencingToken) {
251
369
  throw new Error("attempt_process_supervisor_fenced: fencing token does not own this attempt.");
@@ -264,7 +382,7 @@ export class AttemptProcessSupervisor {
264
382
  finally {
265
383
  await handle.close();
266
384
  }
267
- await fs.rename(temporary, this.ledgerPath);
385
+ await this.replaceLedger(temporary);
268
386
  }
269
387
  catch (error) {
270
388
  await fs.rm(temporary, { force: true }).catch(() => undefined);
@@ -310,29 +428,32 @@ function boundedInteger(value, minimum, maximum, name) {
310
428
  }
311
429
  return value;
312
430
  }
313
- function boundedFailure(error) {
314
- const message = error instanceof Error ? error.message : String(error);
431
+ function boundedFailure(error, exactSecrets = []) {
432
+ const message = sanitizeFailureError(error, exactSecrets).message;
315
433
  return message.replaceAll(/[\r\n\t]+/gu, " ").slice(0, 512);
316
434
  }
317
435
  async function childStartFailureDetail(record) {
318
436
  try {
319
437
  const result = await record.result;
320
- const stderr = boundedDiagnostic(result.stderr);
438
+ const stderr = boundedDiagnostic(result.stderr, record.failureRedactionValues);
321
439
  return stderr
322
440
  ? `exit ${result.exitCode}; stderr: ${stderr}`
323
441
  : `exit ${result.exitCode}`;
324
442
  }
325
443
  catch (error) {
326
- return boundedFailure(error);
444
+ return boundedFailure(error, record.failureRedactionValues);
327
445
  }
328
446
  }
329
- function boundedDiagnostic(value) {
330
- return value.replaceAll(/[\r\n\t]+/gu, " ").trim().slice(0, 512);
447
+ function boundedDiagnostic(value, exactSecrets = []) {
448
+ return sanitizeFailureError(value, exactSecrets).message
449
+ .replaceAll(/[\r\n\t]+/gu, " ")
450
+ .trim()
451
+ .slice(0, 512);
331
452
  }
332
453
  function isRetryableStartFailure(error) {
333
- return error instanceof Error
334
- && (error.message.startsWith("attempt_process_supervisor_start_failed:")
335
- || error.message.startsWith("attempt_process_supervisor_start_timeout:"));
454
+ return error instanceof ForgeFailureError
455
+ && (error.failureCode === "attempt_process_supervisor_start_failed"
456
+ || error.failureCode === "attempt_process_supervisor_start_timeout");
336
457
  }
337
458
  function cancellationError(signal) {
338
459
  return new Error(String(signal.reason ?? "Supervised child launch was cancelled."));
@@ -0,0 +1,3 @@
1
+ import type { PinnedDirectoryIdentity } from "./pinned-directory-process.js";
2
+ /** Keep the validated source inode open: reopening a checked pathname can follow a replacement. */
3
+ export declare function readCanonicalSourceFile(target: string, maximumBytes: number, expectedIdentity?: PinnedDirectoryIdentity): Promise<Buffer>;
@@ -0,0 +1,54 @@
1
+ import { constants } from "node:fs";
2
+ import fs from "node:fs/promises";
3
+ import path from "node:path";
4
+ /** Keep the validated source inode open: reopening a checked pathname can follow a replacement. */
5
+ export async function readCanonicalSourceFile(target, maximumBytes, expectedIdentity) {
6
+ const resolved = path.resolve(target);
7
+ const pathBefore = await canonicalStat(resolved);
8
+ if (expectedIdentity && !sameFile(pathBefore, expectedIdentity)) {
9
+ throw new Error("host_runtime_source_changed: source identity changed before reading.");
10
+ }
11
+ const handle = await fs.open(resolved, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0)
12
+ | (constants.O_NONBLOCK ?? 0));
13
+ try {
14
+ const before = await handle.stat({ bigint: true });
15
+ if (!before.isFile() || before.nlink !== 1n || !sameFile(pathBefore, before) || before.size > BigInt(maximumBytes)) {
16
+ throw new Error("host_runtime_source_invalid: source changed or exceeds the byte bound.");
17
+ }
18
+ if (!sameFile(before, await canonicalStat(resolved))) {
19
+ throw new Error("host_runtime_source_changed: source changed before reading.");
20
+ }
21
+ const bytes = Buffer.alloc(Number(before.size));
22
+ let offset = 0;
23
+ while (offset < bytes.length) {
24
+ const read = await handle.read(bytes, offset, bytes.length - offset, offset);
25
+ if (!read.bytesRead)
26
+ throw new Error("host_runtime_source_changed: incomplete source read.");
27
+ offset += read.bytesRead;
28
+ }
29
+ const after = await handle.stat({ bigint: true });
30
+ const pathAfter = await canonicalStat(resolved);
31
+ if (after.nlink !== 1n || !sameFile(before, after) || !sameFile(after, pathAfter) || before.size !== after.size
32
+ || before.mtimeNs !== after.mtimeNs || before.ctimeNs !== after.ctimeNs) {
33
+ throw new Error("host_runtime_source_changed: source changed while reading.");
34
+ }
35
+ return bytes;
36
+ }
37
+ finally {
38
+ await handle.close();
39
+ }
40
+ }
41
+ async function canonicalStat(target) {
42
+ const stat = await fs.lstat(target, { bigint: true });
43
+ const real = await fs.realpath(target);
44
+ const realStat = await fs.lstat(real, { bigint: true });
45
+ const samePath = process.platform === "win32" ? real.toLowerCase() === target.toLowerCase() : real === target;
46
+ if (!samePath || !stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1n || !realStat.isFile()
47
+ || realStat.isSymbolicLink() || realStat.nlink !== 1n || !sameFile(stat, realStat)) {
48
+ throw new Error("host_runtime_source_invalid: source must be a canonical regular file.");
49
+ }
50
+ return realStat;
51
+ }
52
+ function sameFile(left, right) {
53
+ return left.dev === right.dev && left.ino === right.ino;
54
+ }
@@ -0,0 +1,90 @@
1
+ import type { CommandRunner } from "../sandbox/sandbox.types.js";
2
+ export interface DockerEngineCapabilitySnapshot {
3
+ readonly available: boolean;
4
+ readonly sampledAt: string;
5
+ readonly runtimeVersion: string | null;
6
+ readonly operatingSystem: string | null;
7
+ readonly context: string;
8
+ readonly unavailableCode: string | null;
9
+ readonly unavailableReason: string | null;
10
+ }
11
+ export interface DockerEngineProbeOptions {
12
+ readonly dockerExecutable?: string;
13
+ readonly dockerContext?: string;
14
+ readonly recovery?: DockerEngineRecoveryPolicy;
15
+ readonly recoveryExecutor?: DockerEngineRecoveryExecutor;
16
+ readonly platform?: NodeJS.Platform;
17
+ readonly dockerHost?: string;
18
+ readonly now?: () => number;
19
+ readonly wait?: (delayMs: number) => Promise<void>;
20
+ readonly onStatus?: (message: string) => void;
21
+ }
22
+ export interface DockerEngineRecoveryPolicy {
23
+ readonly enabled: boolean;
24
+ readonly failureThreshold?: number;
25
+ readonly confirmationDelayMs?: number;
26
+ readonly cooldownMs?: number;
27
+ readonly startupTimeoutMs?: number;
28
+ readonly pollIntervalMs?: number;
29
+ readonly canRecover?: () => boolean;
30
+ }
31
+ export interface DockerEngineRecoveryResult {
32
+ readonly started: boolean;
33
+ readonly reason?: string;
34
+ }
35
+ export interface DockerEngineRecoveryExecutor {
36
+ restart(): Promise<DockerEngineRecoveryResult>;
37
+ }
38
+ /**
39
+ * Probes ordinary Docker-daemon access for host-run Testcontainers and project
40
+ * services. This is deliberately independent from the stricter Forge sandbox
41
+ * preflight: a usable Docker Desktop engine may satisfy docker_engine even
42
+ * when it is not approved to host an agent sandbox.
43
+ */
44
+ export declare class DockerEngineProbe {
45
+ private readonly commands;
46
+ private readonly cacheMs;
47
+ private cached;
48
+ private sampledAtMs;
49
+ private inFlight;
50
+ private requiredWorkRecoveryInFlight;
51
+ private consecutiveFailures;
52
+ private lastRecoveryAttemptAtMs;
53
+ private readonly docker;
54
+ private readonly context;
55
+ private readonly platform;
56
+ private readonly dockerHost;
57
+ private readonly now;
58
+ private readonly wait;
59
+ private readonly recovery;
60
+ private readonly recoveryExecutor;
61
+ private readonly onStatus;
62
+ constructor(options?: DockerEngineProbeOptions, commands?: CommandRunner, cacheMs?: number);
63
+ current(): DockerEngineCapabilitySnapshot | null;
64
+ refresh(force?: boolean): Promise<DockerEngineCapabilitySnapshot>;
65
+ /**
66
+ * Establishes a fresh daemon fence for work that declares Docker as a hard
67
+ * prerequisite. This remains bounded, cooldown protected and single-flight;
68
+ * it never contacts Docker unless a caller explicitly invokes this method.
69
+ */
70
+ ensureAvailableForRequiredWork(): Promise<DockerEngineCapabilitySnapshot>;
71
+ private inspectSafely;
72
+ private recoverIfEligible;
73
+ private isLocalDockerDesktopContext;
74
+ private inspect;
75
+ }
76
+ /**
77
+ * Restarts only the local Docker Desktop installation. It never targets a
78
+ * remote daemon and is used only behind the explicit bridge recovery policy.
79
+ */
80
+ export declare class WindowsDockerDesktopRecoveryExecutor implements DockerEngineRecoveryExecutor {
81
+ private readonly platform;
82
+ private readonly commands;
83
+ private readonly programFiles;
84
+ private readonly wait;
85
+ constructor(platform?: NodeJS.Platform, commands?: CommandRunner, programFiles?: string, wait?: (delayMs: number) => Promise<void>);
86
+ restart(): Promise<DockerEngineRecoveryResult>;
87
+ private readProcessState;
88
+ private cleanupOrphanedCompanions;
89
+ private startDesktop;
90
+ }