@loucompanion/forge-bridge 0.1.4-dev.138b79c6feb3 → 0.1.4-dev.176dfdaf5020

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 (207) hide show
  1. package/README.md +142 -1
  2. package/dist/bridge/bridge-chat-provider-command.d.ts +19 -0
  3. package/dist/bridge/bridge-chat-provider-command.js +132 -0
  4. package/dist/bridge/bridge-chat.types.d.ts +10 -0
  5. package/dist/bridge/bridge-chat.types.js +16 -1
  6. package/dist/bridge/bridge-state-file.d.ts +161 -0
  7. package/dist/bridge/bridge-state-file.js +376 -0
  8. package/dist/bridge/bridge-state-io.d.ts +11 -0
  9. package/dist/bridge/bridge-state-io.js +50 -0
  10. package/dist/bridge/bridge-state-lock.d.ts +11 -0
  11. package/dist/bridge/bridge-state-lock.js +102 -0
  12. package/dist/bridge/bridge-state-unpublished.d.ts +17 -0
  13. package/dist/bridge/bridge-state-unpublished.js +111 -0
  14. package/dist/bridge/bridge.base.d.ts +9 -0
  15. package/dist/bridge/bridge.service.d.ts +87 -14
  16. package/dist/bridge/bridge.service.js +393 -337
  17. package/dist/bridge/bridge.types.d.ts +16 -0
  18. package/dist/bridge/in-flight-registry.d.ts +62 -0
  19. package/dist/bridge/in-flight-registry.js +207 -0
  20. package/dist/bridge/local-yield-flag.d.ts +6 -0
  21. package/dist/bridge/local-yield-flag.js +34 -0
  22. package/dist/bridge/readiness-result-outbox.d.ts +5 -1
  23. package/dist/bridge/readiness-result-outbox.js +20 -0
  24. package/dist/bridge/runner-host-capabilities.d.ts +3 -0
  25. package/dist/bridge/runner-host-capabilities.js +13 -0
  26. package/dist/bridge/sandbox-resource-accounting.d.ts +16 -0
  27. package/dist/bridge/sandbox-resource-accounting.js +150 -0
  28. package/dist/cleanup/cleanup-wip.d.ts +12 -0
  29. package/dist/cleanup/cleanup-wip.js +66 -0
  30. package/dist/cleanup/cleanup.service.d.ts +11 -1
  31. package/dist/cleanup/cleanup.service.js +80 -62
  32. package/dist/cleanup/cleanup.types.d.ts +2 -0
  33. package/dist/cleanup/host-runtime-ledger.d.ts +2 -0
  34. package/dist/cleanup/host-runtime-ledger.js +30 -9
  35. package/dist/cli/cli.help.js +74 -12
  36. package/dist/cli/cli.service.d.ts +19 -10
  37. package/dist/cli/cli.service.js +142 -185
  38. package/dist/cli/idle-status.d.ts +84 -0
  39. package/dist/cli/idle-status.js +181 -0
  40. package/dist/cli/local-config.d.ts +6 -0
  41. package/dist/cli/local-config.js +32 -4
  42. package/dist/cli/provider-cli-detection.d.ts +10 -0
  43. package/dist/cli/provider-cli-detection.js +160 -0
  44. package/dist/runtime/aspnet-runtime-prebuild.d.ts +20 -0
  45. package/dist/runtime/aspnet-runtime-prebuild.js +104 -26
  46. package/dist/runtime/attempt-database-broker.d.ts +1 -1
  47. package/dist/runtime/attempt-node-runtime-launcher.js +9 -0
  48. package/dist/runtime/attempt-process-supervisor.d.ts +2 -0
  49. package/dist/runtime/attempt-process-supervisor.js +12 -6
  50. package/dist/runtime/docker-engine-probe.d.ts +5 -0
  51. package/dist/runtime/docker-engine-probe.js +7 -0
  52. package/dist/runtime/dotnet-build-outputs.d.ts +107 -0
  53. package/dist/runtime/dotnet-build-outputs.js +402 -0
  54. package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
  55. package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
  56. package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
  57. package/dist/runtime/ephemeral-test-postgres.js +303 -0
  58. package/dist/runtime/host-facts.d.ts +2 -1
  59. package/dist/runtime/host-load-admission.d.ts +18 -3
  60. package/dist/runtime/host-load-admission.js +19 -4
  61. package/dist/runtime/host-load-child-environment.d.ts +11 -6
  62. package/dist/runtime/host-load-child-environment.js +22 -11
  63. package/dist/runtime/host-load-governor-config.d.ts +19 -1
  64. package/dist/runtime/host-load-governor-config.js +37 -0
  65. package/dist/runtime/host-load-governor.d.ts +14 -0
  66. package/dist/runtime/host-load-governor.js +139 -26
  67. package/dist/runtime/host-load-ledger-lock.js +6 -4
  68. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  69. package/dist/runtime/host-load-runtime-settings.js +80 -0
  70. package/dist/runtime/host-load-sampler.d.ts +34 -4
  71. package/dist/runtime/host-load-sampler.js +73 -7
  72. package/dist/runtime/host-load-step-class.d.ts +3 -1
  73. package/dist/runtime/host-load-step-class.js +60 -5
  74. package/dist/runtime/host-load-test-slot.d.ts +43 -0
  75. package/dist/runtime/host-load-test-slot.js +81 -0
  76. package/dist/runtime/host-load-token-ledger.d.ts +26 -0
  77. package/dist/runtime/host-load-token-ledger.js +93 -61
  78. package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
  79. package/dist/runtime/host-load-windows-cpu.js +85 -0
  80. package/dist/runtime/host-runtime-contract.d.ts +12 -0
  81. package/dist/runtime/host-runtime-contract.js +29 -1
  82. package/dist/runtime/host-runtime-lease.d.ts +32 -4
  83. package/dist/runtime/host-runtime-lease.js +109 -173
  84. package/dist/runtime/host-runtime-ledger-recovery.d.ts +20 -0
  85. package/dist/runtime/host-runtime-ledger-recovery.js +134 -0
  86. package/dist/runtime/host-runtime-promotion.d.ts +23 -0
  87. package/dist/runtime/host-runtime-promotion.js +36 -0
  88. package/dist/runtime/managed-command-teardown.js +5 -16
  89. package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
  90. package/dist/runtime/native-test-postgres-fallback.js +60 -8
  91. package/dist/runtime/runner-settings.d.ts +104 -0
  92. package/dist/runtime/runner-settings.js +236 -0
  93. package/dist/runtime/supervised-runtime-build-guard.d.ts +45 -0
  94. package/dist/runtime/supervised-runtime-build-guard.js +112 -0
  95. package/dist/sandbox/host-capacity-broker.d.ts +10 -2
  96. package/dist/sandbox/host-capacity-broker.js +27 -6
  97. package/dist/sandbox/managed-branch.d.ts +13 -0
  98. package/dist/sandbox/managed-branch.js +90 -0
  99. package/dist/sandbox/provider-auth/codex.js +11 -11
  100. package/dist/sandbox/runtime.js +2 -6
  101. package/dist/session/architect-waits.d.ts +2 -0
  102. package/dist/session/architect-waits.js +138 -0
  103. package/dist/session/managed-attempt-tools.d.ts +0 -7
  104. package/dist/session/managed-attempt-tools.js +58 -91
  105. package/dist/session/managed-build-coordinator.d.ts +16 -0
  106. package/dist/session/managed-build-coordinator.js +10 -0
  107. package/dist/session/managed-build-receipt.d.ts +5 -0
  108. package/dist/session/managed-build-receipt.js +8 -3
  109. package/dist/session/managed-command-host-load.d.ts +2 -0
  110. package/dist/session/managed-command-host-load.js +2 -1
  111. package/dist/session/phase-completion.artifacts.js +2 -1
  112. package/dist/session/phase-completion.d.ts +8 -0
  113. package/dist/session/phase-completion.js +1 -0
  114. package/dist/session/phase-completion.mcp-args.d.ts +9 -0
  115. package/dist/session/phase-completion.mcp-args.js +156 -0
  116. package/dist/session/phase-completion.runtime.d.ts +0 -8
  117. package/dist/session/phase-completion.runtime.js +43 -197
  118. package/dist/session/phase-completion.schemas.js +25 -23
  119. package/dist/session/phase-completion.validation.js +3 -1
  120. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  121. package/dist/session/pre-publication-native-postgres.js +111 -0
  122. package/dist/session/pre-publication-pass.d.ts +61 -0
  123. package/dist/session/pre-publication-pass.js +148 -0
  124. package/dist/session/pre-publication-process.js +10 -10
  125. package/dist/session/pre-publication-step-execution.d.ts +2 -1
  126. package/dist/session/pre-publication-step-execution.js +6 -5
  127. package/dist/session/pre-publication-validation.d.ts +30 -14
  128. package/dist/session/pre-publication-validation.js +207 -134
  129. package/dist/session/provider-cli/claude-background-work.d.ts +67 -0
  130. package/dist/session/provider-cli/claude-background-work.js +181 -0
  131. package/dist/session/provider-cli/host-build-lock.d.ts +18 -0
  132. package/dist/session/provider-cli/host-build-lock.js +30 -0
  133. package/dist/session/provider-cli/pre-publication-repair.d.ts +56 -0
  134. package/dist/session/provider-cli/pre-publication-repair.js +276 -0
  135. package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
  136. package/dist/session/provider-cli/provider-cli.child-environment.js +75 -0
  137. package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
  138. package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
  139. package/dist/session/provider-cli/provider-cli.process.d.ts +15 -36
  140. package/dist/session/provider-cli/provider-cli.process.js +39 -430
  141. package/dist/session/provider-cli/provider-cli.prompts.d.ts +5 -0
  142. package/dist/session/provider-cli/provider-cli.prompts.js +68 -31
  143. package/dist/session/provider-cli/provider-cli.runtime.d.ts +8 -0
  144. package/dist/session/provider-cli/provider-cli.runtime.js +29 -1
  145. package/dist/session/provider-cli/provider-cli.service.d.ts +5 -5
  146. package/dist/session/provider-cli/provider-cli.service.js +70 -263
  147. package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
  148. package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
  149. package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
  150. package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
  151. package/dist/session/provider-cli/provider-in-flight-work.d.ts +4 -0
  152. package/dist/session/provider-cli/provider-in-flight-work.js +45 -0
  153. package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
  154. package/dist/session/provider-cli/provider-output-pipes.js +67 -0
  155. package/dist/session/provider-cli/provider-output-state.d.ts +2 -0
  156. package/dist/session/provider-cli/provider-output-state.js +6 -0
  157. package/dist/session/provider-cli/provider-user-config-isolation.d.ts +69 -0
  158. package/dist/session/provider-cli/provider-user-config-isolation.js +164 -0
  159. package/dist/session/qa-sidecar-validation.d.ts +6 -0
  160. package/dist/session/qa-sidecar-validation.js +28 -0
  161. package/dist/session/sandbox-host-capacity-gate.d.ts +22 -1
  162. package/dist/session/sandbox-host-capacity-gate.js +42 -14
  163. package/dist/session/session-redaction.js +31 -181
  164. package/dist/session/session.base.d.ts +6 -1
  165. package/dist/session/session.service.d.ts +6 -1
  166. package/dist/session/session.service.js +75 -64
  167. package/dist/session/session.types.js +3 -3
  168. package/dist/session/sidecar-json-shape.d.ts +31 -0
  169. package/dist/session/sidecar-json-shape.js +217 -0
  170. package/dist/shared/fs/file-identity.d.ts +10 -0
  171. package/dist/shared/fs/file-identity.js +15 -0
  172. package/dist/shared/fs/replace-file.d.ts +7 -0
  173. package/dist/shared/fs/replace-file.js +33 -0
  174. package/dist/shared/process/host-process-recovery.d.ts +14 -3
  175. package/dist/shared/process/host-process-recovery.js +23 -3
  176. package/dist/shared/process/host-process-supervisor.d.ts +13 -1
  177. package/dist/shared/process/host-process-supervisor.js +66 -14
  178. package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
  179. package/dist/shared/process/windows-app-execution-alias.js +45 -0
  180. package/dist/shared/process/windows-launch.d.ts +18 -0
  181. package/dist/shared/process/windows-launch.js +68 -0
  182. package/dist/shared/provider-capabilities.js +14 -7
  183. package/dist/version.d.ts +1 -1
  184. package/dist/version.js +1 -1
  185. package/dist/worktree/orphan-relink.d.ts +19 -0
  186. package/dist/worktree/orphan-relink.js +106 -0
  187. package/dist/worktree/wip-git.d.ts +33 -0
  188. package/dist/worktree/wip-git.js +122 -0
  189. package/dist/worktree/wip-refs.d.ts +62 -0
  190. package/dist/worktree/wip-refs.js +119 -0
  191. package/dist/worktree/wip-restore.d.ts +38 -0
  192. package/dist/worktree/wip-restore.js +190 -0
  193. package/dist/worktree/wip-snapshot.d.ts +50 -0
  194. package/dist/worktree/wip-snapshot.js +268 -0
  195. package/dist/worktree/worktree-inputs.d.ts +8 -0
  196. package/dist/worktree/worktree-inputs.js +134 -0
  197. package/dist/worktree/worktree-origin-sync.d.ts +34 -0
  198. package/dist/worktree/worktree-origin-sync.js +127 -0
  199. package/dist/worktree/worktree-wip-events.d.ts +18 -0
  200. package/dist/worktree/worktree-wip-events.js +98 -0
  201. package/dist/worktree/worktree-wip.d.ts +50 -0
  202. package/dist/worktree/worktree-wip.js +185 -0
  203. package/dist/worktree/worktree.base.d.ts +7 -1
  204. package/dist/worktree/worktree.service.d.ts +27 -5
  205. package/dist/worktree/worktree.service.js +110 -181
  206. package/dist/worktree/worktree.types.d.ts +31 -0
  207. package/package.json +2 -2
@@ -8,18 +8,37 @@ import { HostCapacityTokenFencedError } from "../runtime/host-load-token-ledger.
8
8
  import { sandboxHostCapacityBrokerEnvironment, sandboxHostCapacityBrokerProtocol, sandboxHostCapacityLineType, sandboxHostCapacityMaxWaitEnvironment, sandboxHostCapacityResponseOwnerUid, sandboxHostCapacityResponseRoot, } from "../sandbox/host-capacity-broker.js";
9
9
  import { monotonicNowMs } from "../shared/time/monotonic.js";
10
10
  import { ForgeFailureError } from "./session.types.js";
11
+ /**
12
+ * Inside the Linux sandbox a reply is the bridge's when the trusted uid (root)
13
+ * owns it and no one else can write it: the sandbox user can create neither.
14
+ * Windows has no such proof in a file's stat (Node reports uid 0 for every file
15
+ * and derives the mode from the read-only attribute alone), so there no reply
16
+ * is ever trusted: the gate fails closed rather than read a read-only file as root's.
17
+ */
18
+ export function posixReplyOwnership(trustedOwnerUid, platform = process.platform) {
19
+ return stat => {
20
+ if (platform === "win32")
21
+ return "file ownership cannot be proven on Windows";
22
+ if (stat.uid !== BigInt(trustedOwnerUid))
23
+ return `it is owned by uid ${stat.uid}, not the bridge`;
24
+ if ((stat.mode & 18n) !== 0n)
25
+ return "others can write it";
26
+ return null;
27
+ };
28
+ }
11
29
  export class SandboxBrokeredHostLoadGate {
12
30
  enabled = true;
13
31
  write;
14
32
  responseRoot;
15
33
  pollMs;
16
- trustedOwnerUid;
34
+ replyOwnership;
17
35
  maxWaitMs;
18
36
  constructor(options = {}) {
19
37
  this.write = options.write ?? (line => { process.stdout.write(line); });
20
38
  this.responseRoot = options.responseRoot ?? sandboxHostCapacityResponseRoot;
21
39
  this.pollMs = options.pollMs ?? 250;
22
- this.trustedOwnerUid = options.trustedOwnerUid ?? sandboxHostCapacityResponseOwnerUid;
40
+ this.replyOwnership = options.replyOwnership
41
+ ?? posixReplyOwnership(options.trustedOwnerUid ?? sandboxHostCapacityResponseOwnerUid);
23
42
  this.maxWaitMs = options.maxWaitMs ?? defaultHostLoadGovernorConfig.maxWaitMs + 2 * 60_000;
24
43
  }
25
44
  async acquire(request, options = {}) {
@@ -32,7 +51,7 @@ export class SandboxBrokeredHostLoadGate {
32
51
  while (true) {
33
52
  if (options.signal?.aborted)
34
53
  throw options.signal.reason ?? new Error("The host capacity wait was cancelled.");
35
- const response = await readResponse(responsePath, requestId, this.trustedOwnerUid);
54
+ const response = await readResponse(responsePath, requestId, this.replyOwnership);
36
55
  if (response?.status === "waiting" && !waitingReported) {
37
56
  waitingReported = true;
38
57
  void Promise.resolve(options.onWaiting?.(decision(false, response))).catch(() => undefined);
@@ -57,7 +76,7 @@ export class SandboxBrokeredHostLoadGate {
57
76
  const fenced = new AbortController();
58
77
  // The bridge rewrites the response as "fenced" if it lost the token; the step then stops.
59
78
  const watch = setInterval(() => {
60
- void readResponse(responsePath, requestId, this.trustedOwnerUid).then(current => {
79
+ void readResponse(responsePath, requestId, this.replyOwnership).then(current => {
61
80
  if (current?.status === "fenced" && !fenced.signal.aborted) {
62
81
  fenced.abort(new HostCapacityTokenFencedError(requestId, "renew"));
63
82
  }
@@ -107,6 +126,8 @@ export class SandboxBrokeredHostLoadGate {
107
126
  holding = true;
108
127
  if (!fenced.signal.aborted)
109
128
  fenced.abort(reason);
129
+ // The bridge marks the host token retained, so this attempt's next step does not wait for it.
130
+ this.send("retain", requestId, request);
110
131
  if (!stillGone)
111
132
  return;
112
133
  let checking = false;
@@ -177,12 +198,14 @@ function responseError(request, response) {
177
198
  return new ForgeFailureError(response.code ?? "host_capacity_broker_failed", message, "bridge");
178
199
  }
179
200
  /**
180
- * The bridge's reply, or null while there is none. Only a regular file with a
181
- * single link, owned by the trusted uid and writable by no one else, is the
182
- * bridge's: the sandbox user can create none of those (see host-capacity-broker.ts).
201
+ * The bridge's reply, or null while there is none (or the one opened was just
202
+ * replaced by a newer reply). Only a regular file with a single link that the
203
+ * reply ownership rule proves the bridge's (in the sandbox: owned by the trusted
204
+ * uid and writable by no one else) is the bridge's: the sandbox user can create
205
+ * none of those (see host-capacity-broker.ts).
183
206
  * Anything else fails closed with sandbox_host_capacity_reply_untrusted.
184
207
  */
185
- async function readResponse(responsePath, requestId, trustedOwnerUid) {
208
+ async function readResponse(responsePath, requestId, replyOwnership) {
186
209
  let handle;
187
210
  try {
188
211
  handle = await fs.open(responsePath, fsConstants.O_RDONLY | (fsConstants.O_NOFOLLOW ?? 0));
@@ -194,13 +217,18 @@ async function readResponse(responsePath, requestId, trustedOwnerUid) {
194
217
  }
195
218
  let content;
196
219
  try {
197
- const stat = await handle.stat();
198
- if (!stat.isFile() || stat.nlink !== 1)
220
+ const stat = await handle.stat({ bigint: true });
221
+ // No link left: the bridge renamed a newer reply over this one after it was opened
222
+ // (waiting -> admitted, admitted -> fenced). It is not a forgery, and nothing is read
223
+ // from it; the next poll opens the newer reply. Only the bridge can replace a reply,
224
+ // since the directory is root-owned and not writable by the sandbox user.
225
+ if (stat.isFile() && stat.nlink === 0n)
226
+ return null;
227
+ if (!stat.isFile() || stat.nlink !== 1n)
199
228
  throw untrustedReply(responsePath, "it is not a regular file with a single link");
200
- if (stat.uid !== trustedOwnerUid)
201
- throw untrustedReply(responsePath, `it is owned by uid ${stat.uid}, not the bridge`);
202
- if ((stat.mode & 0o022) !== 0)
203
- throw untrustedReply(responsePath, "others can write it");
229
+ const notTheBridges = replyOwnership(stat);
230
+ if (notTheBridges !== null)
231
+ throw untrustedReply(responsePath, notTheBridges);
204
232
  content = await handle.readFile("utf8");
205
233
  }
206
234
  finally {
@@ -1,14 +1,14 @@
1
1
  import { redactText, shouldRedactJsonProperty } from "../shared/redaction/redaction.js";
2
- import { TextDecoder } from "node:util";
2
+ import { decodeJsonEscapesLeniently, decodeJsonStringToken, inspectJsonText, isJsonPunctuation, isJsonWhitespace, JsonShapeError, sidecarJsonShapeProblem, } from "./sidecar-json-shape.js";
3
+ import { ForgeFailureError } from "./session.types.js";
3
4
  const integrityProtectedEventDataTypes = new Set(["sandbox_started"]);
4
5
  const structuralSecretMessage = "runner result structural metadata contains protected secret material and cannot be redacted without changing protocol identity.";
5
6
  const sidecarSecretMessage = "runner result sidecar contains protected secret material and cannot be redacted without invalidating integrity metadata.";
6
7
  const artifactJsonMessage = "runner result artifact JSON is invalid or exceeds safe inspection limits; transport was rejected.";
7
8
  const artifactJsonKeySecretMessage = "runner result artifact JSON property name contains protected secret material and cannot be redacted without changing protocol identity.";
8
9
  const artifactJsonPrimitiveSecretMessage = "runner result artifact JSON primitive contains protected secret material and cannot be redacted without changing protocol identity.";
9
- const maximumIntegrityJsonBytes = 8 * 1024 * 1024;
10
- const maximumIntegrityJsonDepth = 128;
11
- const maximumIntegrityJsonTokens = 262_144;
10
+ // Stable failure code for a sidecar that starts like JSON but does not parse (see sidecar-json-shape.ts).
11
+ const malformedSidecarFailureCode = "runner_result_sidecar_malformed";
12
12
  export function redactRunnerDispatchEvent(event, exactSecrets = []) {
13
13
  assertStructuralFieldsDoNotContainSecrets([
14
14
  event.role,
@@ -149,7 +149,7 @@ function redactArtifactJson(value, exactSecrets) {
149
149
  }
150
150
  continue;
151
151
  }
152
- const token = decodeJsonStringToken(value, index, artifactJsonMessage);
152
+ const token = decodeArtifactJsonStringToken(value, index);
153
153
  const afterToken = skipJsonWhitespace(value, token.nextIndex);
154
154
  if (value.charCodeAt(afterToken) === 0x3a) {
155
155
  assertJsonStringDoesNotContainSecrets(token.decoded, exactSecrets, artifactJsonKeySecretMessage);
@@ -159,7 +159,7 @@ function redactArtifactJson(value, exactSecrets) {
159
159
  const valueStart = skipJsonWhitespace(value, afterToken + 1);
160
160
  const valueEnd = jsonValueEnd(value, valueStart);
161
161
  if (value[valueStart] !== '"'
162
- || decodeJsonStringToken(value, valueStart, artifactJsonMessage).decoded !== "[REDACTED]") {
162
+ || decodeArtifactJsonStringToken(value, valueStart).decoded !== "[REDACTED]") {
163
163
  replace(valueStart, valueEnd, '"[REDACTED]"');
164
164
  }
165
165
  index = valueEnd;
@@ -193,13 +193,13 @@ function skipJsonWhitespace(value, start) {
193
193
  // value (including objects/arrays) without decoding or rewriting adjacent data.
194
194
  function jsonValueEnd(value, start) {
195
195
  if (value.charCodeAt(start) === 0x22) {
196
- return decodeJsonStringToken(value, start, artifactJsonMessage).nextIndex;
196
+ return decodeArtifactJsonStringToken(value, start).nextIndex;
197
197
  }
198
198
  if (value[start] === "{" || value[start] === "[") {
199
199
  let depth = 0;
200
200
  for (let index = start; index < value.length; index += 1) {
201
201
  if (value[index] === '"') {
202
- index = decodeJsonStringToken(value, index, artifactJsonMessage).nextIndex - 1;
202
+ index = decodeArtifactJsonStringToken(value, index).nextIndex - 1;
203
203
  }
204
204
  else if (value[index] === "{" || value[index] === "[") {
205
205
  depth += 1;
@@ -248,7 +248,7 @@ function assertSidecarsDoNotContainSecrets(sidecars, exactSecrets) {
248
248
  throw new Error(sidecarSecretMessage);
249
249
  }
250
250
  }
251
- assertSidecarJsonDoesNotContainSecrets(decoded, sidecar.path, exactSecrets, sidecarSecretMessage);
251
+ assertSidecarJsonShape(decoded, sidecar.path, exactSecrets);
252
252
  }
253
253
  }
254
254
  function assertSerializedJsonDoesNotContainSecrets(value, exactSecrets, errorMessage) {
@@ -257,187 +257,37 @@ function assertSerializedJsonDoesNotContainSecrets(value, exactSecrets, errorMes
257
257
  assertJsonStringDoesNotContainSecrets(value, exactSecrets, errorMessage);
258
258
  inspectJsonStringTokens(value, exactSecrets, errorMessage);
259
259
  }
260
- function assertSidecarJsonDoesNotContainSecrets(value, path, exactSecrets, errorMessage) {
261
- let decoded;
262
- try {
263
- decoded = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(value);
264
- }
265
- catch {
266
- if (path.toLowerCase().endsWith(".json"))
267
- throw new Error(errorMessage);
260
+ function assertSidecarJsonShape(content, path, exactSecrets) {
261
+ const problem = sidecarJsonShapeProblem(content, path, decoded => assertJsonStringDoesNotContainSecrets(decoded, exactSecrets, sidecarSecretMessage));
262
+ if (problem === null)
268
263
  return;
269
- }
270
- if (!looksLikeJson(decoded, path))
271
- return;
272
- const hasUtf8Bom = value.length >= 3
273
- && value[0] === 0xef
274
- && value[1] === 0xbb
275
- && value[2] === 0xbf;
276
- if (hasUtf8Bom)
277
- throw new Error(errorMessage);
278
- inspectJsonStringTokens(decoded, exactSecrets, errorMessage);
264
+ // A malformed file cannot be read token by token, so decode its escapes leniently first: a
265
+ // secret hidden behind JSON escapes keeps the secret error instead of the malformed one.
266
+ assertJsonStringDoesNotContainSecrets(decodeJsonEscapesLeniently(content.toString("utf8")), exactSecrets, sidecarSecretMessage);
267
+ // Still fail closed: the bytes cannot be redacted, so the result is rejected either way. The
268
+ // distinct code and message say the file is malformed, not that a secret was found.
269
+ throw new ForgeFailureError(malformedSidecarFailureCode, `runner result sidecar ${path} looks like JSON but is not valid JSON (${problem}); `
270
+ + "Forge rejects sidecars it cannot fully inspect, so the result was not accepted.");
279
271
  }
280
272
  function inspectJsonStringTokens(value, exactSecrets, errorMessage) {
281
- if (Buffer.byteLength(value, "utf8") > maximumIntegrityJsonBytes) {
282
- throw new Error(errorMessage);
283
- }
284
- const containers = [];
285
- let index = 0;
286
- let tokenCount = 0;
287
- const countToken = () => {
288
- tokenCount += 1;
289
- if (tokenCount > maximumIntegrityJsonTokens)
290
- throw new Error(errorMessage);
291
- };
292
- while (index < value.length) {
293
- const code = value.charCodeAt(index);
294
- if (code === 0x22) {
295
- countToken();
296
- const token = decodeJsonStringToken(value, index, errorMessage);
297
- assertJsonStringDoesNotContainSecrets(token.decoded, exactSecrets, errorMessage);
298
- index = token.nextIndex;
299
- continue;
300
- }
301
- if (code === 0x7b || code === 0x5b) {
302
- countToken();
303
- containers.push(code);
304
- if (containers.length > maximumIntegrityJsonDepth)
305
- throw new Error(errorMessage);
306
- index += 1;
307
- continue;
308
- }
309
- if (code === 0x7d || code === 0x5d) {
310
- countToken();
311
- const expected = code === 0x7d ? 0x7b : 0x5b;
312
- if (containers.pop() !== expected)
313
- throw new Error(errorMessage);
314
- index += 1;
315
- continue;
316
- }
317
- if (code === 0x2c || code === 0x3a) {
318
- index += 1;
319
- continue;
320
- }
321
- if (isJsonWhitespace(code)) {
322
- index += 1;
323
- continue;
324
- }
325
- countToken();
326
- do {
327
- index += 1;
328
- } while (index < value.length
329
- && !isJsonWhitespace(value.charCodeAt(index))
330
- && !isJsonPunctuation(value.charCodeAt(index)));
331
- }
332
- if (containers.length !== 0)
333
- throw new Error(errorMessage);
334
273
  try {
335
- JSON.parse(value);
274
+ inspectJsonText(value, decoded => assertJsonStringDoesNotContainSecrets(decoded, exactSecrets, errorMessage));
336
275
  }
337
- catch {
338
- throw new Error(errorMessage);
276
+ catch (error) {
277
+ if (error instanceof JsonShapeError)
278
+ throw new Error(errorMessage, { cause: error });
279
+ throw error;
339
280
  }
340
281
  }
341
- function decodeJsonStringToken(value, openingQuoteIndex, errorMessage) {
342
- const chunks = [];
343
- let segmentStart = openingQuoteIndex + 1;
344
- let index = segmentStart;
345
- while (index < value.length) {
346
- const code = value.charCodeAt(index);
347
- if (code === 0x22) {
348
- chunks.push(value.slice(segmentStart, index));
349
- const decoded = chunks.join("");
350
- if (!isWellFormedUnicode(decoded))
351
- throw new Error(errorMessage);
352
- return { decoded, nextIndex: index + 1 };
353
- }
354
- if (code < 0x20)
355
- throw new Error(errorMessage);
356
- if (code !== 0x5c) {
357
- index += 1;
358
- continue;
359
- }
360
- chunks.push(value.slice(segmentStart, index));
361
- index += 1;
362
- if (index >= value.length)
363
- throw new Error(errorMessage);
364
- const escaped = value[index];
365
- switch (escaped) {
366
- case "\"":
367
- chunks.push("\"");
368
- index += 1;
369
- break;
370
- case "\\":
371
- chunks.push("\\");
372
- index += 1;
373
- break;
374
- case "/":
375
- chunks.push("/");
376
- index += 1;
377
- break;
378
- case "b":
379
- chunks.push("\b");
380
- index += 1;
381
- break;
382
- case "f":
383
- chunks.push("\f");
384
- index += 1;
385
- break;
386
- case "n":
387
- chunks.push("\n");
388
- index += 1;
389
- break;
390
- case "r":
391
- chunks.push("\r");
392
- index += 1;
393
- break;
394
- case "t":
395
- chunks.push("\t");
396
- index += 1;
397
- break;
398
- case "u": {
399
- const hex = value.slice(index + 1, index + 5);
400
- if (!/^[0-9a-fA-F]{4}$/u.test(hex))
401
- throw new Error(errorMessage);
402
- chunks.push(String.fromCharCode(Number.parseInt(hex, 16)));
403
- index += 5;
404
- break;
405
- }
406
- default: throw new Error(errorMessage);
407
- }
408
- segmentStart = index;
282
+ function decodeArtifactJsonStringToken(value, openingQuoteIndex) {
283
+ try {
284
+ return decodeJsonStringToken(value, openingQuoteIndex);
409
285
  }
410
- throw new Error(errorMessage);
411
- }
412
- function isWellFormedUnicode(value) {
413
- for (let index = 0; index < value.length; index += 1) {
414
- const code = value.charCodeAt(index);
415
- if (code >= 0xd800 && code <= 0xdbff) {
416
- if (index + 1 >= value.length)
417
- return false;
418
- const next = value.charCodeAt(index + 1);
419
- if (next < 0xdc00 || next > 0xdfff)
420
- return false;
421
- index += 1;
422
- }
423
- else if (code >= 0xdc00 && code <= 0xdfff) {
424
- return false;
425
- }
286
+ catch (error) {
287
+ if (error instanceof JsonShapeError)
288
+ throw new Error(artifactJsonMessage, { cause: error });
289
+ throw error;
426
290
  }
427
- return true;
428
- }
429
- function looksLikeJson(value, path) {
430
- if (path.toLowerCase().endsWith(".json"))
431
- return true;
432
- const candidate = value.trimStart().replace(/^\uFEFF/u, "").trimStart();
433
- return candidate.startsWith("{") || candidate.startsWith("[") || candidate.startsWith("\"");
434
- }
435
- function isJsonWhitespace(code) {
436
- return code === 0x20 || code === 0x09 || code === 0x0a || code === 0x0d;
437
- }
438
- function isJsonPunctuation(code) {
439
- return code === 0x7b || code === 0x7d || code === 0x5b || code === 0x5d
440
- || code === 0x2c || code === 0x3a || code === 0x22;
441
291
  }
442
292
  function assertJsonStringDoesNotContainSecrets(value, exactSecrets, errorMessage) {
443
293
  for (const secret of exactSecrets) {
@@ -1,6 +1,7 @@
1
1
  import type { HostRequirementsCheck } from "../runtime/host-runtime-requirements-check.js";
2
2
  import type { HostRuntimeReadinessProbeRequest, HostRuntimeReadinessProbeResult, RunOnceDispatchPacket, RunOnceResultPacket, RunnerDispatchEvent } from "./session.types.js";
3
- import type { HostRuntimeCapacitySnapshot, HostRuntimeReapOptions, HostRuntimeReapReport } from "../runtime/host-runtime-lease.js";
3
+ import type { RunnerHostDefaults } from "../runtime/runner-settings.js";
4
+ import type { HostCapacityLimits, HostRuntimeCapacitySnapshot, HostRuntimeReapOptions, HostRuntimeReapReport } from "../runtime/host-runtime-lease.js";
4
5
  export interface SessionEventSink {
5
6
  emit(event: RunnerDispatchEvent): Promise<void>;
6
7
  }
@@ -12,4 +13,8 @@ export interface SessionService {
12
13
  probeHostRuntime?(request: HostRuntimeReadinessProbeRequest, signal?: AbortSignal): Promise<HostRuntimeReadinessProbeResult>;
13
14
  /** Decision 0013: host attempts recheck the project's requirements before starting. */
14
15
  setHostRequirementsCheck?(check: HostRequirementsCheck | null): void;
16
+ /** Decision 0014: the host's max attempts and memory reserve defaults; null without host attempts. */
17
+ runnerLimitDefaults?(): RunnerHostDefaults | null;
18
+ /** Decision 0014: applies the effective max attempts and memory reserve to host attempt admission. */
19
+ applyRunnerLimits?(limits: HostCapacityLimits): void | Promise<void>;
15
20
  }
@@ -3,7 +3,8 @@ import type { ProviderCliService } from "./provider-cli/provider-cli.base.js";
3
3
  import type { SessionEventSink, SessionService } from "./session.base.js";
4
4
  import type { HostRuntimeReadinessProbeRequest, HostRuntimeReadinessProbeResult, RunOnceDispatchPacket, RunOnceResultPacket } from "./session.types.js";
5
5
  import type { WorktreeService } from "../worktree/worktree.base.js";
6
- import { type HostRuntimeCapacitySnapshot, type HostRuntimeLeaseRuntime, type HostRuntimeReapOptions, type HostRuntimeReapReport } from "../runtime/host-runtime-lease.js";
6
+ import { type HostCapacityLimits, type HostRuntimeCapacitySnapshot, type HostRuntimeLeaseRuntime, type HostRuntimeReapOptions, type HostRuntimeReapReport } from "../runtime/host-runtime-lease.js";
7
+ import type { RunnerHostDefaults } from "../runtime/runner-settings.js";
7
8
  import { type WorkspaceRuntimeFingerprintReader } from "./workspace-runtime-fingerprint.js";
8
9
  export declare class BridgeSessionService implements SessionService {
9
10
  private readonly worktrees;
@@ -12,9 +13,13 @@ export declare class BridgeSessionService implements SessionService {
12
13
  private readonly workspaceFingerprint;
13
14
  constructor(worktrees?: WorktreeService, providerCli?: ProviderCliService, hostRuntime?: HostRuntimeLeaseRuntime | undefined, workspaceFingerprint?: WorkspaceRuntimeFingerprintReader);
14
15
  setHostRequirementsCheck(check: HostRequirementsCheck | null): void;
16
+ runnerLimitDefaults(): RunnerHostDefaults | null;
17
+ applyRunnerLimits(limits: HostCapacityLimits): void;
15
18
  updateLease(dispatchAttemptId: string, fencingToken: string, expiresAt: string): Promise<void>;
16
19
  reapHostRuntime(options: HostRuntimeReapOptions): Promise<HostRuntimeReapReport | null>;
17
20
  runtimeCapacity(): HostRuntimeCapacitySnapshot | null;
18
21
  probeHostRuntime(request: HostRuntimeReadinessProbeRequest, signal?: AbortSignal): Promise<HostRuntimeReadinessProbeResult>;
19
22
  runOnce(dispatch: RunOnceDispatchPacket, sink: SessionEventSink, signal?: AbortSignal): Promise<RunOnceResultPacket>;
23
+ /** Reports the provider's peak memory and releases the attempt's host runtime lease. */
24
+ private releaseHostRuntime;
20
25
  }
@@ -2,7 +2,7 @@ import { redactRunnerDispatchEvent, redactRunOnceResultPacket } from "./session-
2
2
  import { randomUUID } from "node:crypto";
3
3
  import { RoutingProviderCliService } from "./provider-cli/provider-cli.service.js";
4
4
  import { ForgeFailureError, waitKindForEvent, waitWakeCondition } from "./session.types.js";
5
- import { GitWorktreeService } from "../worktree/worktree.service.js";
5
+ import { emitWorktreePreparedEvents, GitWorktreeService, sessionWipOutcome, settleWorktree } from "../worktree/worktree.service.js";
6
6
  import { SandboxWorkspaceService } from "../sandbox/workspace.service.js";
7
7
  import { HostRuntimeAdmissionExpiredError, hostRuntimeEventResources, hostRuntimeStackEnvironmentKeys, runtimeAdmissionPriority, } from "../runtime/host-runtime-lease.js";
8
8
  import { configuredLaunchPortNames, hostRuntimeContractFingerprint, hostRuntimeParallelEligible, } from "../runtime/host-runtime-promotion.js";
@@ -24,6 +24,12 @@ export class BridgeSessionService {
24
24
  setHostRequirementsCheck(check) {
25
25
  this.hostRuntime?.setRequirementsCheck?.(check);
26
26
  }
27
+ runnerLimitDefaults() {
28
+ return this.hostRuntime?.capacityLimitDefaults?.() ?? null;
29
+ }
30
+ applyRunnerLimits(limits) {
31
+ this.hostRuntime?.applyCapacityLimits?.(limits);
32
+ }
27
33
  async updateLease(dispatchAttemptId, fencingToken, expiresAt) {
28
34
  await this.hostRuntime?.updateLease(dispatchAttemptId, fencingToken, expiresAt);
29
35
  }
@@ -184,6 +190,7 @@ export class BridgeSessionService {
184
190
  let worktree = null;
185
191
  let hostSingletonKeys = null;
186
192
  let hostLease = null;
193
+ let succeeded = false;
187
194
  try {
188
195
  if (dispatch.sandbox?.executionMode === "host" && this.hostRuntime) {
189
196
  const capacity = this.hostRuntime.snapshot?.() ?? null;
@@ -259,6 +266,7 @@ export class BridgeSessionService {
259
266
  warmPathOverrides: dispatch.warmPathOverrides,
260
267
  applicationRuntimeRequired: dispatch.runtimeIntent.applicationRuntimeRequired,
261
268
  preserveExistingState: Boolean(dispatch.session.resumedFromSessionId),
269
+ sessionId: dispatch.session.id,
262
270
  hostLoadOwner: {
263
271
  dispatchAttemptId: dispatch.sandbox?.dispatchAttemptId ?? null,
264
272
  priority: runtimeAdmissionPriority(dispatch),
@@ -279,6 +287,7 @@ export class BridgeSessionService {
279
287
  : `Prepared worktree ${worktree.branchName}.`,
280
288
  eventType: dispatch.session.resumedFromSessionId ? "worktree_reattached" : "worktree_prepared"
281
289
  });
290
+ await emitWorktreePreparedEvents(worktree, emit);
282
291
  if ((worktree.hydratedPriorPhaseArtifactCount ?? 0) > 0) {
283
292
  await emit({
284
293
  role: "runner",
@@ -448,15 +457,16 @@ export class BridgeSessionService {
448
457
  });
449
458
  throwIfAborted(signal);
450
459
  const draftArtifacts = run.artifacts?.length ? run.artifacts : run.artifact ? [run.artifact] : [];
451
- return redactRunOnceResultPacket({
452
- schemaVersion: 2,
453
- exitCode: 0,
454
- summary: run.summary,
460
+ // Redaction can throw (a secret in a structural field); only a returned result is a success.
461
+ const draftResult = redactRunOnceResultPacket({
462
+ schemaVersion: 2, exitCode: 0, summary: run.summary,
455
463
  events,
456
464
  spec: run.spec ?? null,
457
465
  artifact: run.artifact ?? null,
458
466
  artifacts: draftArtifacts
459
467
  }, redactionSecrets);
468
+ succeeded = true;
469
+ return draftResult;
460
470
  }
461
471
  throwIfAborted(signal);
462
472
  const lane = dispatch.execution.lane.trim().toLowerCase();
@@ -502,10 +512,8 @@ export class BridgeSessionService {
502
512
  }
503
513
  throwIfAborted(signal);
504
514
  const phaseArtifacts = run.artifacts?.length ? run.artifacts : run.artifact ? [run.artifact] : [];
505
- return redactRunOnceResultPacket({
506
- schemaVersion: 2,
507
- exitCode: 0,
508
- summary: run.summary,
515
+ const result = redactRunOnceResultPacket({
516
+ schemaVersion: 2, exitCode: 0, summary: run.summary,
509
517
  resultCommitSha: run.resultCommitSha ?? null,
510
518
  publishedCommitSha: run.publishedCommitSha ?? null,
511
519
  events,
@@ -513,72 +521,79 @@ export class BridgeSessionService {
513
521
  artifact: run.artifact ?? null,
514
522
  artifacts: phaseArtifacts
515
523
  }, redactionSecrets);
524
+ succeeded = true;
525
+ return result;
516
526
  }
517
527
  finally {
518
- if (hostLease && dispatch.sandbox) {
519
- const providerMemory = this.hostRuntime?.providerMemoryTelemetry?.(dispatch.sandbox.dispatchAttemptId, dispatch.lease.fencingToken);
520
- if (providerMemory) {
521
- await emitLifecycle({
522
- role: "runner",
523
- kind: "checkpoint",
524
- content: `Observed managed-host provider process-tree peak memory ${formatMemoryBytes(providerMemory.peakMemoryBytes)} from ${providerMemory.sampleCount} sample${providerMemory.sampleCount === 1 ? "" : "s"}.`,
525
- eventType: "sandbox_peak_memory_observed",
526
- occurredAt: providerMemory.observedAt,
527
- data: JSON.stringify({
528
- peakMemoryBytes: providerMemory.peakMemoryBytes,
529
- sampleCount: providerMemory.sampleCount,
530
- source: providerMemory.source,
531
- containers: [{
532
- role: "agent",
533
- peakMemoryBytes: providerMemory.peakMemoryBytes,
534
- }],
535
- }),
536
- }).catch(() => undefined);
537
- }
538
- const teardownAt = new Date().toISOString();
528
+ await this.releaseHostRuntime(dispatch, hostLease, hostSingletonKeys, emitLifecycle);
529
+ if (worktree) {
530
+ await settleWorktree(this.worktrees, worktree, sessionWipOutcome(signal, events, succeeded), signal, emitLifecycle);
531
+ }
532
+ }
533
+ }
534
+ /** Reports the provider's peak memory and releases the attempt's host runtime lease. */
535
+ async releaseHostRuntime(dispatch, hostLease, hostSingletonKeys, emitLifecycle) {
536
+ if (hostLease && dispatch.sandbox) {
537
+ const providerMemory = this.hostRuntime?.providerMemoryTelemetry?.(dispatch.sandbox.dispatchAttemptId, dispatch.lease.fencingToken);
538
+ if (providerMemory) {
539
539
  await emitLifecycle({
540
540
  role: "runner",
541
541
  kind: "checkpoint",
542
- content: `Releasing host runtime lease ${hostLease.lease.leaseId}.`,
543
- eventType: "sandbox_teardown_started",
544
- occurredAt: teardownAt,
542
+ content: `Observed managed-host provider process-tree peak memory ${formatMemoryBytes(providerMemory.peakMemoryBytes)} from ${providerMemory.sampleCount} sample${providerMemory.sampleCount === 1 ? "" : "s"}.`,
543
+ eventType: "sandbox_peak_memory_observed",
544
+ occurredAt: providerMemory.observedAt,
545
+ data: JSON.stringify({
546
+ peakMemoryBytes: providerMemory.peakMemoryBytes,
547
+ sampleCount: providerMemory.sampleCount,
548
+ source: providerMemory.source,
549
+ containers: [{
550
+ role: "agent",
551
+ peakMemoryBytes: providerMemory.peakMemoryBytes,
552
+ }],
553
+ }),
545
554
  }).catch(() => undefined);
546
- try {
547
- const released = await this.hostRuntime?.release(dispatch.sandbox.dispatchAttemptId, dispatch.lease.fencingToken);
548
- if (!released) {
549
- await emitLifecycle({
550
- role: "runner",
551
- kind: "error",
552
- content: "Host runtime cleanup requires reconciliation: the runtime lease was not current during release.",
553
- eventType: "teardown_failed",
554
- occurredAt: new Date().toISOString(),
555
- }).catch(() => undefined);
556
- }
557
- else {
558
- await emitLifecycle({
559
- role: "runner",
560
- kind: "checkpoint",
561
- content: `Released host runtime lease ${released.leaseId}. Diagnostics remain runner-local.`,
562
- eventType: "sandbox_teardown_completed",
563
- occurredAt: released.releasedAt,
564
- }).catch(() => undefined);
565
- }
566
- }
567
- catch (error) {
555
+ }
556
+ const teardownAt = new Date().toISOString();
557
+ await emitLifecycle({
558
+ role: "runner",
559
+ kind: "checkpoint",
560
+ content: `Releasing host runtime lease ${hostLease.lease.leaseId}.`,
561
+ eventType: "sandbox_teardown_started",
562
+ occurredAt: teardownAt,
563
+ }).catch(() => undefined);
564
+ try {
565
+ const released = await this.hostRuntime?.release(dispatch.sandbox.dispatchAttemptId, dispatch.lease.fencingToken);
566
+ if (!released) {
568
567
  await emitLifecycle({
569
568
  role: "runner",
570
569
  kind: "error",
571
- content: `Host runtime cleanup requires reconciliation: ${error instanceof Error ? error.message : String(error)}`,
570
+ content: "Host runtime cleanup requires reconciliation: the runtime lease was not current during release.",
572
571
  eventType: "teardown_failed",
573
572
  occurredAt: new Date().toISOString(),
574
573
  }).catch(() => undefined);
575
574
  }
575
+ else {
576
+ await emitLifecycle({
577
+ role: "runner",
578
+ kind: "checkpoint",
579
+ content: `Released host runtime lease ${released.leaseId}. Diagnostics remain runner-local.`,
580
+ eventType: "sandbox_teardown_completed",
581
+ occurredAt: released.releasedAt,
582
+ }).catch(() => undefined);
583
+ }
576
584
  }
577
- if (!hostLease && hostSingletonKeys && dispatch.sandbox) {
578
- await this.hostRuntime?.release(dispatch.sandbox.dispatchAttemptId, dispatch.lease.fencingToken).catch(() => undefined);
585
+ catch (error) {
586
+ await emitLifecycle({
587
+ role: "runner",
588
+ kind: "error",
589
+ content: `Host runtime cleanup requires reconciliation: ${error instanceof Error ? error.message : String(error)}`,
590
+ eventType: "teardown_failed",
591
+ occurredAt: new Date().toISOString(),
592
+ }).catch(() => undefined);
579
593
  }
580
- if (worktree && !isPauseCancellation(signal))
581
- await this.worktrees.release(worktree);
594
+ }
595
+ if (!hostLease && hostSingletonKeys && dispatch.sandbox) {
596
+ await this.hostRuntime?.release(dispatch.sandbox.dispatchAttemptId, dispatch.lease.fencingToken).catch(() => undefined);
582
597
  }
583
598
  }
584
599
  }
@@ -588,10 +603,6 @@ function failureMessage(error) {
588
603
  function formatMemoryBytes(bytes) {
589
604
  return `${(bytes / (1024 ** 2)).toFixed(bytes >= 1024 ** 3 ? 0 : 1)} MiB`;
590
605
  }
591
- function isPauseCancellation(signal) {
592
- return signal?.aborted === true
593
- && String(signal.reason ?? "").trim().toLowerCase() === "session pause requested";
594
- }
595
606
  function readinessProbeDispatch(request) {
596
607
  return {
597
608
  schemaVersion: 2,