@loucompanion/forge-bridge 0.1.4-dev.f22f5e3d01fe → 0.2.1-dev.0f07274d438b

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 (260) hide show
  1. package/README.md +128 -4
  2. package/dist/bridge/bridge-chat-giphy-look.d.ts +48 -0
  3. package/dist/bridge/bridge-chat-giphy-look.js +55 -0
  4. package/dist/bridge/bridge-chat-provider-command.d.ts +27 -3
  5. package/dist/bridge/bridge-chat-provider-command.js +131 -26
  6. package/dist/bridge/bridge-chat.types.d.ts +20 -0
  7. package/dist/bridge/bridge-chat.types.js +28 -1
  8. package/dist/bridge/bridge-state-file.d.ts +161 -0
  9. package/dist/bridge/bridge-state-file.js +376 -0
  10. package/dist/bridge/bridge-state-io.d.ts +15 -0
  11. package/dist/bridge/bridge-state-io.js +68 -0
  12. package/dist/bridge/bridge-state-lock.d.ts +11 -0
  13. package/dist/bridge/bridge-state-lock.js +102 -0
  14. package/dist/bridge/bridge-state-unpublished.d.ts +17 -0
  15. package/dist/bridge/bridge-state-unpublished.js +111 -0
  16. package/dist/bridge/bridge.service.d.ts +29 -12
  17. package/dist/bridge/bridge.service.js +215 -380
  18. package/dist/bridge/bridge.types.d.ts +21 -0
  19. package/dist/bridge/bridge.types.js +2 -1
  20. package/dist/bridge/default-session-service.d.ts +13 -0
  21. package/dist/bridge/default-session-service.js +22 -0
  22. package/dist/bridge/dispatch-offer-policy.d.ts +22 -0
  23. package/dist/bridge/dispatch-offer-policy.js +58 -0
  24. package/dist/bridge/in-flight-registry.d.ts +62 -0
  25. package/dist/bridge/in-flight-registry.js +207 -0
  26. package/dist/bridge/readiness-result-outbox.d.ts +5 -1
  27. package/dist/bridge/readiness-result-outbox.js +20 -0
  28. package/dist/bridge/runner-host-capabilities.js +14 -1
  29. package/dist/bridge/sandbox-resource-accounting.d.ts +16 -0
  30. package/dist/bridge/sandbox-resource-accounting.js +150 -0
  31. package/dist/bridge/windows-bash-resolution.d.ts +31 -0
  32. package/dist/bridge/windows-bash-resolution.js +153 -0
  33. package/dist/cleanup/cleanup-wip.d.ts +12 -0
  34. package/dist/cleanup/cleanup-wip.js +66 -0
  35. package/dist/cleanup/cleanup.service.d.ts +11 -1
  36. package/dist/cleanup/cleanup.service.js +80 -62
  37. package/dist/cleanup/cleanup.types.d.ts +2 -0
  38. package/dist/cleanup/forge-owned-paths.d.ts +2 -0
  39. package/dist/cleanup/forge-owned-paths.js +9 -0
  40. package/dist/cleanup/host-runtime-ledger.d.ts +2 -0
  41. package/dist/cleanup/host-runtime-ledger.js +30 -9
  42. package/dist/cli/cli.help.js +57 -13
  43. package/dist/cli/cli.service.d.ts +3 -10
  44. package/dist/cli/cli.service.js +20 -213
  45. package/dist/cli/idle-status.d.ts +84 -0
  46. package/dist/cli/idle-status.js +181 -0
  47. package/dist/cli/local-config.d.ts +14 -1
  48. package/dist/cli/local-config.js +42 -2
  49. package/dist/cli/provider-cli-advertising.d.ts +24 -0
  50. package/dist/cli/provider-cli-advertising.js +88 -0
  51. package/dist/cli/provider-cli-detection.d.ts +10 -0
  52. package/dist/cli/provider-cli-detection.js +160 -0
  53. package/dist/runtime/aspnet-runtime-prebuild.d.ts +20 -0
  54. package/dist/runtime/aspnet-runtime-prebuild.js +104 -26
  55. package/dist/runtime/attempt-database-broker.d.ts +1 -1
  56. package/dist/runtime/attempt-node-runtime-launcher.d.ts +36 -0
  57. package/dist/runtime/attempt-node-runtime-launcher.js +169 -0
  58. package/dist/runtime/attempt-process-supervisor.d.ts +2 -0
  59. package/dist/runtime/attempt-process-supervisor.js +12 -6
  60. package/dist/runtime/docker-engine-probe.d.ts +5 -0
  61. package/dist/runtime/docker-engine-probe.js +7 -0
  62. package/dist/runtime/dotnet-build-outputs.d.ts +107 -0
  63. package/dist/runtime/dotnet-build-outputs.js +402 -0
  64. package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
  65. package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
  66. package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
  67. package/dist/runtime/ephemeral-test-postgres.js +303 -0
  68. package/dist/runtime/host-listener-inspector.d.ts +26 -0
  69. package/dist/runtime/host-listener-inspector.js +84 -3
  70. package/dist/runtime/host-load-admission.d.ts +5 -0
  71. package/dist/runtime/host-load-capacity.d.ts +198 -0
  72. package/dist/runtime/host-load-capacity.js +353 -0
  73. package/dist/runtime/host-load-child-environment.d.ts +13 -0
  74. package/dist/runtime/host-load-child-environment.js +35 -1
  75. package/dist/runtime/host-load-governor-config.d.ts +33 -3
  76. package/dist/runtime/host-load-governor-config.js +24 -3
  77. package/dist/runtime/host-load-governor.d.ts +91 -2
  78. package/dist/runtime/host-load-governor.js +217 -18
  79. package/dist/runtime/host-load-ledger-lock.js +6 -4
  80. package/dist/runtime/host-load-live-test-slots.d.ts +61 -0
  81. package/dist/runtime/host-load-live-test-slots.js +193 -0
  82. package/dist/runtime/host-load-runtime-settings.js +4 -2
  83. package/dist/runtime/host-load-sampler.d.ts +25 -1
  84. package/dist/runtime/host-load-sampler.js +38 -7
  85. package/dist/runtime/host-load-step-run.d.ts +37 -3
  86. package/dist/runtime/host-load-step-run.js +63 -7
  87. package/dist/runtime/host-load-test-slot.d.ts +3 -0
  88. package/dist/runtime/host-load-test-slot.js +26 -7
  89. package/dist/runtime/host-runtime-contract.d.ts +12 -0
  90. package/dist/runtime/host-runtime-contract.js +35 -5
  91. package/dist/runtime/host-runtime-lease.d.ts +28 -3
  92. package/dist/runtime/host-runtime-lease.js +140 -296
  93. package/dist/runtime/host-runtime-ledger-recovery.d.ts +20 -0
  94. package/dist/runtime/host-runtime-ledger-recovery.js +134 -0
  95. package/dist/runtime/host-runtime-promotion.d.ts +78 -2
  96. package/dist/runtime/host-runtime-promotion.js +307 -14
  97. package/dist/runtime/managed-command-teardown.js +5 -16
  98. package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
  99. package/dist/runtime/native-test-postgres-fallback.js +60 -8
  100. package/dist/runtime/prepared-runtime-identity.d.ts +4 -0
  101. package/dist/runtime/prepared-runtime-identity.js +130 -9
  102. package/dist/runtime/prepared-runtime-readiness.d.ts +23 -1
  103. package/dist/runtime/prepared-runtime-readiness.js +89 -18
  104. package/dist/runtime/runner-settings.d.ts +4 -0
  105. package/dist/runtime/runner-settings.js +22 -0
  106. package/dist/runtime/supervised-runtime-build-guard.d.ts +45 -0
  107. package/dist/runtime/supervised-runtime-build-guard.js +112 -0
  108. package/dist/sandbox/host-capacity-broker.d.ts +3 -1
  109. package/dist/sandbox/host-capacity-broker.js +4 -2
  110. package/dist/sandbox/managed-branch.d.ts +13 -0
  111. package/dist/sandbox/managed-branch.js +90 -0
  112. package/dist/sandbox/provider-auth/codex.js +11 -11
  113. package/dist/sandbox/runtime.d.ts +1 -2
  114. package/dist/sandbox/runtime.js +9 -19
  115. package/dist/sandbox/sandbox-input.d.ts +22 -0
  116. package/dist/sandbox/sandbox-input.js +49 -0
  117. package/dist/sandbox/workspace.service.js +15 -2
  118. package/dist/session/managed-attempt-tools.d.ts +0 -7
  119. package/dist/session/managed-attempt-tools.js +54 -109
  120. package/dist/session/managed-build-coordinator.d.ts +16 -0
  121. package/dist/session/managed-build-coordinator.js +10 -0
  122. package/dist/session/managed-build-receipt.d.ts +7 -0
  123. package/dist/session/managed-build-receipt.js +11 -3
  124. package/dist/session/managed-command-environment.d.ts +8 -0
  125. package/dist/session/managed-command-environment.js +28 -0
  126. package/dist/session/managed-command-host-load.d.ts +10 -5
  127. package/dist/session/managed-command-host-load.js +18 -14
  128. package/dist/session/phase-completion.artifact-bundle.d.ts +20 -0
  129. package/dist/session/phase-completion.artifact-bundle.js +167 -0
  130. package/dist/session/phase-completion.artifacts.d.ts +2 -17
  131. package/dist/session/phase-completion.artifacts.js +65 -166
  132. package/dist/session/phase-completion.d.ts +27 -2
  133. package/dist/session/phase-completion.helpers.js +5 -53
  134. package/dist/session/phase-completion.js +15 -32
  135. package/dist/session/phase-completion.mcp-args.d.ts +9 -0
  136. package/dist/session/phase-completion.mcp-args.js +195 -0
  137. package/dist/session/phase-completion.phase-aliases.d.ts +5 -0
  138. package/dist/session/phase-completion.phase-aliases.js +43 -0
  139. package/dist/session/phase-completion.pr-review-schema.d.ts +1 -0
  140. package/dist/session/phase-completion.pr-review-schema.js +75 -0
  141. package/dist/session/phase-completion.pr-review-validation.d.ts +11 -0
  142. package/dist/session/phase-completion.pr-review-validation.js +212 -0
  143. package/dist/session/phase-completion.pr-review.d.ts +36 -0
  144. package/dist/session/phase-completion.pr-review.js +294 -0
  145. package/dist/session/phase-completion.prompts.d.ts +1 -1
  146. package/dist/session/phase-completion.prompts.js +14 -0
  147. package/dist/session/phase-completion.runtime.d.ts +8 -9
  148. package/dist/session/phase-completion.runtime.js +65 -196
  149. package/dist/session/phase-completion.schemas.js +12 -2
  150. package/dist/session/phase-completion.validation.d.ts +1 -0
  151. package/dist/session/phase-completion.validation.js +9 -1
  152. package/dist/session/pr-review-diff-base.d.ts +18 -0
  153. package/dist/session/pr-review-diff-base.js +44 -0
  154. package/dist/session/pr-review-placement.d.ts +50 -0
  155. package/dist/session/pr-review-placement.js +91 -0
  156. package/dist/session/pre-publication-change-set.d.ts +62 -0
  157. package/dist/session/pre-publication-change-set.js +166 -0
  158. package/dist/session/pre-publication-host-load.js +6 -5
  159. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  160. package/dist/session/pre-publication-native-postgres.js +111 -0
  161. package/dist/session/pre-publication-process.js +13 -12
  162. package/dist/session/pre-publication-step-execution.d.ts +2 -1
  163. package/dist/session/pre-publication-step-execution.js +6 -5
  164. package/dist/session/pre-publication-validation.d.ts +9 -4
  165. package/dist/session/pre-publication-validation.js +62 -65
  166. package/dist/session/provider-cli/claude-background-work.d.ts +3 -2
  167. package/dist/session/provider-cli/claude-background-work.js +4 -3
  168. package/dist/session/provider-cli/dispatch-target-branch.d.ts +7 -0
  169. package/dist/session/provider-cli/dispatch-target-branch.js +8 -0
  170. package/dist/session/provider-cli/host-build-lock.d.ts +18 -0
  171. package/dist/session/provider-cli/host-build-lock.js +30 -0
  172. package/dist/session/provider-cli/pr-review-credential-isolation.d.ts +83 -0
  173. package/dist/session/provider-cli/pr-review-credential-isolation.js +144 -0
  174. package/dist/session/provider-cli/pr-review-guardrails.d.ts +70 -0
  175. package/dist/session/provider-cli/pr-review-guardrails.js +360 -0
  176. package/dist/session/provider-cli/pr-review-prompt.d.ts +2 -0
  177. package/dist/session/provider-cli/pr-review-prompt.js +119 -0
  178. package/dist/session/provider-cli/pre-publication-repair.d.ts +16 -0
  179. package/dist/session/provider-cli/pre-publication-repair.js +41 -3
  180. package/dist/session/provider-cli/provider-cli.base.d.ts +1 -0
  181. package/dist/session/provider-cli/provider-cli.child-environment.js +4 -2
  182. package/dist/session/provider-cli/provider-cli.deterministic.d.ts +1 -0
  183. package/dist/session/provider-cli/provider-cli.deterministic.js +5 -0
  184. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +6 -3
  185. package/dist/session/provider-cli/provider-cli.merge-integrity.js +29 -10
  186. package/dist/session/provider-cli/provider-cli.pr-review.d.ts +23 -0
  187. package/dist/session/provider-cli/provider-cli.pr-review.js +213 -0
  188. package/dist/session/provider-cli/provider-cli.process.d.ts +2 -14
  189. package/dist/session/provider-cli/provider-cli.process.js +4 -94
  190. package/dist/session/provider-cli/provider-cli.prompts.d.ts +13 -3
  191. package/dist/session/provider-cli/provider-cli.prompts.js +137 -84
  192. package/dist/session/provider-cli/provider-cli.reapply-conflicts.d.ts +10 -0
  193. package/dist/session/provider-cli/provider-cli.reapply-conflicts.js +37 -0
  194. package/dist/session/provider-cli/provider-cli.runtime.d.ts +15 -0
  195. package/dist/session/provider-cli/provider-cli.runtime.js +37 -2
  196. package/dist/session/provider-cli/provider-cli.service-support.d.ts +37 -0
  197. package/dist/session/provider-cli/provider-cli.service-support.js +146 -0
  198. package/dist/session/provider-cli/provider-cli.service.d.ts +15 -18
  199. package/dist/session/provider-cli/provider-cli.service.js +59 -190
  200. package/dist/session/provider-cli/provider-cli.types.d.ts +7 -2
  201. package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
  202. package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
  203. package/dist/session/provider-cli/provider-user-config-isolation.d.ts +69 -0
  204. package/dist/session/provider-cli/provider-user-config-isolation.js +164 -0
  205. package/dist/session/qa-sidecar-validation.d.ts +6 -0
  206. package/dist/session/qa-sidecar-validation.js +28 -0
  207. package/dist/session/sandbox-host-capacity-gate.d.ts +22 -1
  208. package/dist/session/sandbox-host-capacity-gate.js +63 -22
  209. package/dist/session/session-host-project.d.ts +22 -0
  210. package/dist/session/session-host-project.js +98 -0
  211. package/dist/session/session-redaction.js +31 -181
  212. package/dist/session/session.parse-helpers.d.ts +10 -0
  213. package/dist/session/session.parse-helpers.js +84 -0
  214. package/dist/session/session.runtime-refresh.d.ts +46 -0
  215. package/dist/session/session.runtime-refresh.js +116 -0
  216. package/dist/session/session.service.d.ts +8 -1
  217. package/dist/session/session.service.js +177 -239
  218. package/dist/session/session.types.d.ts +5 -0
  219. package/dist/session/session.types.js +9 -79
  220. package/dist/session/session.types.pr-review.d.ts +48 -0
  221. package/dist/session/session.types.pr-review.js +51 -0
  222. package/dist/session/sidecar-json-shape.d.ts +31 -0
  223. package/dist/session/sidecar-json-shape.js +217 -0
  224. package/dist/shared/fs/file-identity.d.ts +10 -0
  225. package/dist/shared/fs/file-identity.js +15 -0
  226. package/dist/shared/fs/replace-file.d.ts +7 -0
  227. package/dist/shared/fs/replace-file.js +33 -0
  228. package/dist/shared/process/host-process-recovery.d.ts +14 -3
  229. package/dist/shared/process/host-process-recovery.js +23 -3
  230. package/dist/shared/process/host-process-supervisor.d.ts +13 -1
  231. package/dist/shared/process/host-process-supervisor.js +66 -14
  232. package/dist/shared/provider-capabilities.d.ts +2 -0
  233. package/dist/shared/provider-capabilities.js +18 -1
  234. package/dist/version.d.ts +1 -1
  235. package/dist/version.js +1 -1
  236. package/dist/worktree/artifact-injector.js +24 -0
  237. package/dist/worktree/orphan-relink.d.ts +19 -0
  238. package/dist/worktree/orphan-relink.js +106 -0
  239. package/dist/worktree/wip-git.d.ts +58 -0
  240. package/dist/worktree/wip-git.js +182 -0
  241. package/dist/worktree/wip-refs.d.ts +85 -0
  242. package/dist/worktree/wip-refs.js +169 -0
  243. package/dist/worktree/wip-restore.d.ts +51 -0
  244. package/dist/worktree/wip-restore.js +324 -0
  245. package/dist/worktree/wip-snapshot.d.ts +53 -0
  246. package/dist/worktree/wip-snapshot.js +270 -0
  247. package/dist/worktree/worktree-inputs.d.ts +8 -0
  248. package/dist/worktree/worktree-inputs.js +134 -0
  249. package/dist/worktree/worktree-origin-sync.d.ts +35 -0
  250. package/dist/worktree/worktree-origin-sync.js +128 -0
  251. package/dist/worktree/worktree-wip-events.d.ts +20 -0
  252. package/dist/worktree/worktree-wip-events.js +148 -0
  253. package/dist/worktree/worktree-wip.d.ts +57 -0
  254. package/dist/worktree/worktree-wip.js +200 -0
  255. package/dist/worktree/worktree.base.d.ts +7 -1
  256. package/dist/worktree/worktree.service.d.ts +49 -5
  257. package/dist/worktree/worktree.service.js +223 -187
  258. package/dist/worktree/worktree.types.d.ts +47 -0
  259. package/package.json +1 -1
  260. package/runtime/windows-listener-owner.ps1 +12 -1
@@ -1,5 +1,7 @@
1
1
  import path from "node:path";
2
2
  import { redactText } from "../shared/redaction/redaction.js";
3
+ import { asObject, requiredString, optionalString, requiredBoolean, optionalBoolean, optionalPositiveInteger, optionalNonNegativeInteger, requiredNumber, boundedInteger } from "./session.parse-helpers.js";
4
+ import { parsePrReview } from "./session.types.pr-review.js";
3
5
  export class ForgeFailureError extends Error {
4
6
  failureCode;
5
7
  failureSource;
@@ -28,7 +30,9 @@ export function parseRunOnceDispatchPacket(value) {
28
30
  runtimeIntent: parseRuntimeIntent(packet.runtimeIntent),
29
31
  serverLocal: parseServerLocal(packet.serverLocal),
30
32
  sandbox: parseSandbox(packet.sandbox, schemaVersion),
33
+ wipAttempt: optionalNonNegativeInteger(packet, "wipAttempt"),
31
34
  pullRequest: parsePullRequest(packet.pullRequest),
35
+ prReview: parsePrReview(packet.prReview),
32
36
  apiKeySecretGrant: parseApiKeySecretGrant(packet.apiKeySecretGrant),
33
37
  apiKeySecretGrantHandle: parseApiKeySecretGrantHandle(packet.apiKeySecretGrantHandle),
34
38
  artifacts: parseArtifacts(packet.artifacts),
@@ -481,7 +485,7 @@ function unvalidatedFailureFactsForCode(code, source) {
481
485
  if (["prepublication_validation_failed", "prepublication_contract_invalid", "prepublication_execution_scope_invalid"].includes(code)) {
482
486
  return facts(code, "domain", "validation", source, "non_retryable", "fix_input");
483
487
  }
484
- if (code === "comment_repair_changed_files_mismatch") {
488
+ if (["comment_repair_changed_files_mismatch", "runner_result_sidecar_malformed"].includes(code)) {
485
489
  return facts(code, "domain", "validation", source, "non_retryable", "inspect_failure");
486
490
  }
487
491
  if (["generated_output_reset_failed", "generated_output_reset_unverified", "worktree_prepare_failed", "host_runtime_ledger_write_failed", "host_diagnostics_temporary_unavailable", "attempt_process_supervisor_start_failed", "attempt_process_supervisor_start_timeout"].includes(code)) {
@@ -538,6 +542,9 @@ function unvalidatedFailureFactsForCode(code, source) {
538
542
  if (stableFailureFamilyCodes.has(code) && (code.startsWith("teardown") || code.startsWith("reaper"))) {
539
543
  return facts(code, "transport", "teardown", source, "retryable", "retry_with_policy");
540
544
  }
545
+ if (["pr_review.unsandboxed_host", "pr_review.sandbox_unavailable"].includes(code)) {
546
+ return facts(code, "domain", "offer", source, "non_retryable", "fix_environment");
547
+ }
541
548
  if (["invalid_dispatch"].includes(code)) {
542
549
  return facts(code, "domain", "offer", source, "non_retryable", "fix_input");
543
550
  }
@@ -551,10 +558,7 @@ function unvalidatedFailureFactsForCode(code, source) {
551
558
  ].includes(code)) {
552
559
  return facts(code, "domain", "prepare", source, "non_retryable", "reauthenticate");
553
560
  }
554
- if (code === "sandbox_idle_timeout") {
555
- return facts(code, "provider", "agent", source, "retryable", "retry_with_policy");
556
- }
557
- if (code === "sandbox_wall_timeout") {
561
+ if (["sandbox_idle_timeout", "sandbox_wall_timeout"].includes(code)) {
558
562
  return facts(code, "provider", "agent", source, "retryable", "retry_with_policy");
559
563
  }
560
564
  if (["sandbox_oom_killed", "sandbox_pid_exhausted", "sandbox_file_descriptor_exhausted", "sandbox_storage_exhausted"].includes(code)) {
@@ -1321,77 +1325,3 @@ function parsePriorPhaseArtifacts(value) {
1321
1325
  };
1322
1326
  });
1323
1327
  }
1324
- function asObject(value, label) {
1325
- if (!value || typeof value !== "object" || Array.isArray(value)) {
1326
- throw new Error(`${label} must be an object.`);
1327
- }
1328
- return value;
1329
- }
1330
- function requiredString(source, key) {
1331
- const value = source[key];
1332
- if (typeof value !== "string" || value.trim().length === 0) {
1333
- throw new Error(`${key} must be a non-empty string.`);
1334
- }
1335
- return value;
1336
- }
1337
- function optionalString(source, key) {
1338
- const value = source[key];
1339
- if (value === undefined || value === null) {
1340
- return null;
1341
- }
1342
- if (typeof value !== "string") {
1343
- throw new Error(`${key} must be a string when provided.`);
1344
- }
1345
- return value;
1346
- }
1347
- function requiredBoolean(source, key) {
1348
- const value = source[key];
1349
- if (typeof value !== "boolean") {
1350
- throw new Error(`${key} must be a boolean.`);
1351
- }
1352
- return value;
1353
- }
1354
- function optionalBoolean(source, key) {
1355
- const value = source[key];
1356
- if (value === undefined || value === null) {
1357
- return null;
1358
- }
1359
- if (typeof value !== "boolean") {
1360
- throw new Error(`${key} must be a boolean when provided.`);
1361
- }
1362
- return value;
1363
- }
1364
- function optionalPositiveInteger(source, key) {
1365
- const value = source[key];
1366
- if (value === undefined || value === null) {
1367
- return null;
1368
- }
1369
- if (typeof value !== "number" || !Number.isInteger(value) || value < 1) {
1370
- throw new Error(`${key} must be a positive integer when provided.`);
1371
- }
1372
- return value;
1373
- }
1374
- function optionalNonNegativeInteger(source, key) {
1375
- const value = source[key];
1376
- if (value === undefined || value === null) {
1377
- return null;
1378
- }
1379
- if (typeof value !== "number" || !Number.isInteger(value) || value < 0) {
1380
- throw new Error(`${key} must be a non-negative integer when provided.`);
1381
- }
1382
- return value;
1383
- }
1384
- function requiredNumber(source, key) {
1385
- const value = source[key];
1386
- if (typeof value !== "number" || !Number.isFinite(value)) {
1387
- throw new Error(`${key} must be a finite number.`);
1388
- }
1389
- return value;
1390
- }
1391
- function boundedInteger(source, key, minimum, maximum) {
1392
- const value = requiredNumber(source, key);
1393
- if (!Number.isSafeInteger(value) || value < minimum || value > maximum) {
1394
- throw new Error(`${key} must be an integer from ${minimum} through ${maximum}.`);
1395
- }
1396
- return value;
1397
- }
@@ -0,0 +1,48 @@
1
+ export interface DispatchPrReviewContext {
2
+ /** The pull request head commit the worktree is checked out at, detached. */
3
+ readonly headSha: string;
4
+ /** The commit the review diffs against: the merge base of the base branch tip and the head, once the bridge resolved it. */
5
+ readonly baseSha: string;
6
+ /** The base branch tip the provider reported, when the bridge replaced it with the merge base. */
7
+ readonly baseTipSha?: string;
8
+ readonly reviewKind: string;
9
+ /** The approved Story spec text, written verbatim to the Story's spec.md. */
10
+ readonly storySpec: string;
11
+ readonly pullRequestNumber: number;
12
+ readonly title: string;
13
+ /** The pull request description. Author-controlled text: treat it as untrusted. */
14
+ readonly description: string;
15
+ readonly baseBranch: string;
16
+ readonly storyWorkItemId: string | null;
17
+ readonly storySpecPath: string | null;
18
+ readonly priorReviews: readonly DispatchPrReviewPriorReview[];
19
+ readonly priorThreads: readonly DispatchPrReviewThread[];
20
+ }
21
+ export interface DispatchPrReviewPriorReview {
22
+ readonly cycleRunId: string;
23
+ readonly sessionId: string;
24
+ readonly headSha: string;
25
+ readonly status: string;
26
+ readonly completedAt: string | null;
27
+ }
28
+ export interface DispatchPrReviewThread {
29
+ readonly threadId: string;
30
+ readonly path: string | null;
31
+ readonly line: number | null;
32
+ readonly startLine: number | null;
33
+ readonly side: string | null;
34
+ /** The head the thread was raised on. */
35
+ readonly reviewedHeadSha: string | null;
36
+ readonly isResolved: boolean;
37
+ readonly isOutdated: boolean;
38
+ readonly comments: readonly DispatchPrReviewThreadComment[];
39
+ }
40
+ export interface DispatchPrReviewThreadComment {
41
+ readonly id: string;
42
+ readonly author: string | null;
43
+ /** Comment text. Author-controlled: treat it as untrusted. */
44
+ readonly body: string;
45
+ readonly url: string | null;
46
+ readonly createdAt: string | null;
47
+ }
48
+ export declare function parsePrReview(value: unknown): DispatchPrReviewContext | null;
@@ -0,0 +1,51 @@
1
+ import { asObject, optionalBoolean, optionalNonNegativeInteger, optionalObjectArray, optionalString, requiredString } from "./session.parse-helpers.js";
2
+ export function parsePrReview(value) {
3
+ if (value === undefined || value === null) {
4
+ return null;
5
+ }
6
+ const prReview = asObject(value, "prReview");
7
+ return {
8
+ headSha: requiredString(prReview, "headSha"),
9
+ baseSha: optionalString(prReview, "baseSha") ?? "",
10
+ ...(optionalString(prReview, "baseTipSha") ? { baseTipSha: optionalString(prReview, "baseTipSha") } : {}),
11
+ reviewKind: optionalString(prReview, "reviewKind") ?? "initial",
12
+ storySpec: optionalString(prReview, "storySpec") ?? "",
13
+ pullRequestNumber: optionalNonNegativeInteger(prReview, "pullRequestNumber") ?? 0,
14
+ title: optionalString(prReview, "title") ?? "",
15
+ description: optionalString(prReview, "description") ?? "",
16
+ baseBranch: optionalString(prReview, "baseBranch") ?? "",
17
+ storyWorkItemId: optionalString(prReview, "storyWorkItemId"),
18
+ storySpecPath: optionalString(prReview, "storySpecPath"),
19
+ priorReviews: optionalObjectArray(prReview, "priorReviews").map(parsePrReviewPriorReview),
20
+ priorThreads: optionalObjectArray(prReview, "priorThreads").map(parsePrReviewThread)
21
+ };
22
+ }
23
+ function parsePrReviewPriorReview(review) {
24
+ return {
25
+ cycleRunId: optionalString(review, "cycleRunId") ?? "",
26
+ sessionId: optionalString(review, "sessionId") ?? "",
27
+ headSha: requiredString(review, "headSha"),
28
+ status: optionalString(review, "status") ?? "",
29
+ completedAt: optionalString(review, "completedAt")
30
+ };
31
+ }
32
+ function parsePrReviewThread(thread) {
33
+ return {
34
+ // The server serializes the id as threadId; id is accepted for the review-finding shape.
35
+ threadId: optionalString(thread, "threadId") || requiredString(thread, "id"),
36
+ path: optionalString(thread, "path"),
37
+ line: optionalNonNegativeInteger(thread, "line"),
38
+ startLine: optionalNonNegativeInteger(thread, "startLine"),
39
+ side: optionalString(thread, "side"),
40
+ reviewedHeadSha: optionalString(thread, "reviewedHeadSha"),
41
+ isResolved: optionalBoolean(thread, "isResolved") ?? false,
42
+ isOutdated: optionalBoolean(thread, "isOutdated") ?? false,
43
+ comments: optionalObjectArray(thread, "comments").map((comment) => ({
44
+ id: optionalString(comment, "id") ?? "",
45
+ author: optionalString(comment, "author"),
46
+ body: optionalString(comment, "body") ?? "",
47
+ url: optionalString(comment, "url"),
48
+ createdAt: optionalString(comment, "createdAt")
49
+ }))
50
+ };
51
+ }
@@ -0,0 +1,31 @@
1
+ export declare const maximumIntegrityJsonBytes: number;
2
+ /** A JSON text that breaks a shape rule. `reason` names the rule and never quotes file content. */
3
+ export declare class JsonShapeError extends Error {
4
+ readonly reason: string;
5
+ constructor(reason: string);
6
+ }
7
+ export declare const oversizedJsonReason = "it is larger than the 8 MiB JSON inspection limit";
8
+ /**
9
+ * Checks a bounded JSON text and calls `onString` with every decoded string token (property names
10
+ * and values). Throws JsonShapeError for a shape problem; errors thrown by `onString` propagate.
11
+ */
12
+ export declare function inspectJsonText(value: string, onString?: (decoded: string) => void): void;
13
+ export declare function decodeJsonStringToken(value: string, openingQuoteIndex: number): {
14
+ readonly decoded: string;
15
+ readonly nextIndex: number;
16
+ };
17
+ /**
18
+ * Why a sidecar that looks like JSON is not acceptable JSON, or null when it is fine: valid JSON,
19
+ * plain text that does not start like JSON, or binary content that is not named *.json.
20
+ */
21
+ export declare function sidecarJsonShapeProblem(content: Uint8Array, path: string, onString?: (decoded: string) => void): string | null;
22
+ /** The instruction an agent gets when it records a sidecar that fails the shape check. */
23
+ export declare function sidecarJsonRepairInstruction(path: string, reason: string): string;
24
+ /**
25
+ * Best-effort decoding of every JSON escape in a text that failed the shape check, so a secret
26
+ * hidden behind escapes still gets the secret error rather than the malformed-sidecar error.
27
+ */
28
+ export declare function decodeJsonEscapesLeniently(value: string): string;
29
+ export declare function looksLikeJson(value: string, path: string): boolean;
30
+ export declare function isJsonWhitespace(code: number): boolean;
31
+ export declare function isJsonPunctuation(code: number): boolean;
@@ -0,0 +1,217 @@
1
+ import { TextDecoder } from "node:util";
2
+ // One set of JSON shape rules for result sidecars. The end-of-run secret check and the QA gate
3
+ // tools that record sidecars during the run both use it, so the agent is told about a malformed
4
+ // sidecar while it can still rewrite the file, and the end-of-run check never disagrees with it.
5
+ //
6
+ // Content sniffing is deliberate: any sidecar whose text starts like JSON ("{", "[" or '"') is
7
+ // held to strict JSON, whatever its file name, so JSON escapes cannot hide secret material from
8
+ // the byte scan. Only a parseable document can be checked token by token.
9
+ export const maximumIntegrityJsonBytes = 8 * 1024 * 1024;
10
+ const maximumIntegrityJsonDepth = 128;
11
+ const maximumIntegrityJsonTokens = 262_144;
12
+ const jsonEscapePattern = /\\(?:u([0-9a-fA-F]{4})|(["\\/bfnrt]))/gu;
13
+ const simpleJsonEscapes = {
14
+ "\"": "\"", "\\": "\\", "/": "/", b: "\b", f: "\f", n: "\n", r: "\r", t: "\t",
15
+ };
16
+ /** A JSON text that breaks a shape rule. `reason` names the rule and never quotes file content. */
17
+ export class JsonShapeError extends Error {
18
+ reason;
19
+ constructor(reason) {
20
+ super(reason);
21
+ this.reason = reason;
22
+ this.name = "JsonShapeError";
23
+ }
24
+ }
25
+ export const oversizedJsonReason = "it is larger than the 8 MiB JSON inspection limit";
26
+ /**
27
+ * Checks a bounded JSON text and calls `onString` with every decoded string token (property names
28
+ * and values). Throws JsonShapeError for a shape problem; errors thrown by `onString` propagate.
29
+ */
30
+ export function inspectJsonText(value, onString) {
31
+ if (Buffer.byteLength(value, "utf8") > maximumIntegrityJsonBytes)
32
+ throw new JsonShapeError(oversizedJsonReason);
33
+ if (value.trim().length === 0)
34
+ throw new JsonShapeError("the file is empty");
35
+ const containers = [];
36
+ let tokenCount = 0;
37
+ let index = 0;
38
+ while (index < value.length) {
39
+ const code = value.charCodeAt(index);
40
+ if (isJsonWhitespace(code) || code === 0x2c || code === 0x3a) {
41
+ index += 1;
42
+ continue;
43
+ }
44
+ tokenCount += 1;
45
+ if (tokenCount > maximumIntegrityJsonTokens) {
46
+ throw new JsonShapeError(`it has more than ${maximumIntegrityJsonTokens} JSON tokens`);
47
+ }
48
+ index = inspectJsonToken(value, index, containers, onString);
49
+ }
50
+ if (containers.length !== 0)
51
+ throw new JsonShapeError("a bracket or brace is never closed");
52
+ assertJsonParses(value);
53
+ }
54
+ function inspectJsonToken(value, index, containers, onString) {
55
+ const code = value.charCodeAt(index);
56
+ if (code === 0x22) {
57
+ const token = decodeJsonStringToken(value, index);
58
+ onString?.(token.decoded);
59
+ return token.nextIndex;
60
+ }
61
+ if (code === 0x7b || code === 0x5b) {
62
+ containers.push(code);
63
+ if (containers.length > maximumIntegrityJsonDepth) {
64
+ throw new JsonShapeError(`it nests deeper than ${maximumIntegrityJsonDepth} levels`);
65
+ }
66
+ return index + 1;
67
+ }
68
+ if (code === 0x7d || code === 0x5d) {
69
+ if (containers.pop() !== (code === 0x7d ? 0x7b : 0x5b)) {
70
+ throw new JsonShapeError(`an unmatched closing bracket or brace ${locationOf(value, index)}`);
71
+ }
72
+ return index + 1;
73
+ }
74
+ let end = index + 1;
75
+ while (end < value.length && !isJsonWhitespace(value.charCodeAt(end)) && !isJsonPunctuation(value.charCodeAt(end))) {
76
+ end += 1;
77
+ }
78
+ return end;
79
+ }
80
+ function assertJsonParses(value) {
81
+ try {
82
+ JSON.parse(value);
83
+ }
84
+ catch (error) {
85
+ // The parser's message can quote the offending text; keep only its position.
86
+ const message = error instanceof Error ? error.message : "";
87
+ const position = /\bposition (\d+)/u.exec(message);
88
+ const location = position ? ` ${locationOf(value, Number(position[1]))}` : "";
89
+ throw new JsonShapeError(message.includes("after JSON")
90
+ ? `unexpected text after the JSON value${location}`
91
+ : `invalid JSON syntax${location}`);
92
+ }
93
+ }
94
+ export function decodeJsonStringToken(value, openingQuoteIndex) {
95
+ const chunks = [];
96
+ let segmentStart = openingQuoteIndex + 1;
97
+ let index = segmentStart;
98
+ while (index < value.length) {
99
+ const code = value.charCodeAt(index);
100
+ if (code === 0x22) {
101
+ chunks.push(value.slice(segmentStart, index));
102
+ const decoded = chunks.join("");
103
+ if (!isWellFormedUnicode(decoded)) {
104
+ throw new JsonShapeError(`a string has an unpaired Unicode surrogate ${locationOf(value, openingQuoteIndex)}`);
105
+ }
106
+ return { decoded, nextIndex: index + 1 };
107
+ }
108
+ if (code < 0x20) {
109
+ throw new JsonShapeError(`a string contains a raw control character ${locationOf(value, index)}`);
110
+ }
111
+ if (code !== 0x5c) {
112
+ index += 1;
113
+ continue;
114
+ }
115
+ chunks.push(value.slice(segmentStart, index));
116
+ const escape = decodeJsonEscape(value, index);
117
+ chunks.push(escape.decoded);
118
+ index = escape.nextIndex;
119
+ segmentStart = index;
120
+ }
121
+ throw new JsonShapeError(`a string is never closed ${locationOf(value, openingQuoteIndex)}`);
122
+ }
123
+ function decodeJsonEscape(value, backslashIndex) {
124
+ const escaped = value[backslashIndex + 1];
125
+ const simple = escaped === undefined ? undefined : simpleJsonEscapes[escaped];
126
+ if (simple !== undefined)
127
+ return { decoded: simple, nextIndex: backslashIndex + 2 };
128
+ const hex = value.slice(backslashIndex + 2, backslashIndex + 6);
129
+ if (escaped !== "u" || !/^[0-9a-fA-F]{4}$/u.test(hex)) {
130
+ throw new JsonShapeError(`a string has an invalid escape sequence ${locationOf(value, backslashIndex)}`);
131
+ }
132
+ return { decoded: String.fromCharCode(Number.parseInt(hex, 16)), nextIndex: backslashIndex + 6 };
133
+ }
134
+ /**
135
+ * Why a sidecar that looks like JSON is not acceptable JSON, or null when it is fine: valid JSON,
136
+ * plain text that does not start like JSON, or binary content that is not named *.json.
137
+ */
138
+ export function sidecarJsonShapeProblem(content, path, onString) {
139
+ let decoded;
140
+ try {
141
+ decoded = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(content);
142
+ }
143
+ catch {
144
+ // Sniff the bytes anyway (invalid sequences decode to U+FFFD, which is not whitespace), so a
145
+ // file that starts like JSON cannot dodge the strict check with a stray invalid byte.
146
+ return looksLikeJson(Buffer.from(content).toString("utf8"), path) ? "the file is not valid UTF-8" : null;
147
+ }
148
+ if (!looksLikeJson(decoded, path))
149
+ return null;
150
+ if (content.length >= 3 && content[0] === 0xef && content[1] === 0xbb && content[2] === 0xbf) {
151
+ return "the file starts with a UTF-8 byte-order mark";
152
+ }
153
+ try {
154
+ inspectJsonText(decoded, onString);
155
+ return null;
156
+ }
157
+ catch (error) {
158
+ if (error instanceof JsonShapeError)
159
+ return error.reason;
160
+ throw error;
161
+ }
162
+ }
163
+ /** The instruction an agent gets when it records a sidecar that fails the shape check. */
164
+ export function sidecarJsonRepairInstruction(path, reason) {
165
+ const fix = isJsonFileName(path)
166
+ ? "Rewrite it as valid JSON (UTF-8, no byte-order mark), or save plain-text output under a name that does not end in .json"
167
+ : "Rewrite it as valid JSON, or as plain text that does not start with \"[\", \"{\" or a double quote (for example, put a title line first)";
168
+ return `${path} looks like JSON but is not valid JSON (${reason}). Forge rejects sidecars it cannot fully inspect. `
169
+ + `${fix}, then resubmit with the file's new bytes and content_hash.`;
170
+ }
171
+ /**
172
+ * Best-effort decoding of every JSON escape in a text that failed the shape check, so a secret
173
+ * hidden behind escapes still gets the secret error rather than the malformed-sidecar error.
174
+ */
175
+ export function decodeJsonEscapesLeniently(value) {
176
+ return value.replace(jsonEscapePattern, (_match, hex, simple) => hex !== undefined ? String.fromCharCode(Number.parseInt(hex, 16)) : simpleJsonEscapes[simple ?? ""] ?? "");
177
+ }
178
+ export function looksLikeJson(value, path) {
179
+ if (isJsonFileName(path))
180
+ return true;
181
+ const candidate = value.trimStart().replace(/^\uFEFF/u, "").trimStart();
182
+ return candidate.startsWith("{") || candidate.startsWith("[") || candidate.startsWith("\"");
183
+ }
184
+ function isJsonFileName(path) {
185
+ return path.toLowerCase().endsWith(".json");
186
+ }
187
+ function locationOf(value, index) {
188
+ let line = 1;
189
+ let lineStart = 0;
190
+ for (let cursor = value.indexOf("\n"); cursor >= 0 && cursor < index; cursor = value.indexOf("\n", cursor + 1)) {
191
+ line += 1;
192
+ lineStart = cursor + 1;
193
+ }
194
+ return `at line ${line}, column ${index - lineStart + 1}`;
195
+ }
196
+ function isWellFormedUnicode(value) {
197
+ for (let index = 0; index < value.length; index += 1) {
198
+ const code = value.charCodeAt(index);
199
+ if (code >= 0xd800 && code <= 0xdbff) {
200
+ const next = value.charCodeAt(index + 1);
201
+ if (!(next >= 0xdc00 && next <= 0xdfff))
202
+ return false;
203
+ index += 1;
204
+ }
205
+ else if (code >= 0xdc00 && code <= 0xdfff) {
206
+ return false;
207
+ }
208
+ }
209
+ return true;
210
+ }
211
+ export function isJsonWhitespace(code) {
212
+ return code === 0x20 || code === 0x09 || code === 0x0a || code === 0x0d;
213
+ }
214
+ export function isJsonPunctuation(code) {
215
+ return code === 0x7b || code === 0x7d || code === 0x5b || code === 0x5d
216
+ || code === 0x2c || code === 0x3a || code === 0x22;
217
+ }
@@ -0,0 +1,10 @@
1
+ import type { BigIntStats } from "node:fs";
2
+ export type FileIdentity = Pick<BigIntStats, "dev" | "ino">;
3
+ export declare function sameFileIdentity(left: FileIdentity, right: FileIdentity): boolean;
4
+ /**
5
+ * Whether a path now names a different file than before. A filesystem that reports no
6
+ * identity (a zero device or id) cannot show a change, so none is claimed for it.
7
+ */
8
+ export declare function fileIdentityChanged(before: FileIdentity, after: FileIdentity): boolean;
9
+ /** The identity as text, for keys and records. */
10
+ export declare function fileIdentityKey(identity: FileIdentity): string;
@@ -0,0 +1,15 @@
1
+ export function sameFileIdentity(left, right) {
2
+ return left.dev === right.dev && left.ino === right.ino;
3
+ }
4
+ /**
5
+ * Whether a path now names a different file than before. A filesystem that reports no
6
+ * identity (a zero device or id) cannot show a change, so none is claimed for it.
7
+ */
8
+ export function fileIdentityChanged(before, after) {
9
+ const known = before.dev !== 0n && before.ino !== 0n && after.dev !== 0n && after.ino !== 0n;
10
+ return known && !sameFileIdentity(before, after);
11
+ }
12
+ /** The identity as text, for keys and records. */
13
+ export function fileIdentityKey(identity) {
14
+ return `${identity.dev}:${identity.ino}`;
15
+ }
@@ -0,0 +1,7 @@
1
+ export interface ReplaceFileOptions {
2
+ readonly deadlineMs?: number;
3
+ /** Test support: the rename to retry. */
4
+ readonly rename?: (from: string, to: string) => Promise<void>;
5
+ }
6
+ /** Renames `temporaryPath` over `targetPath`, waiting out a reader that holds the target open. */
7
+ export declare function replaceFile(temporaryPath: string, targetPath: string, options?: ReplaceFileOptions): Promise<void>;
@@ -0,0 +1,33 @@
1
+ import fs from "node:fs/promises";
2
+ import { monotonicNowMs } from "../time/monotonic.js";
3
+ // Windows refuses to rename over a file any other handle has open (EPERM,
4
+ // EBUSY, or EACCES), even one opened to share delete, which is how Node opens
5
+ // every file. A receipt that agents and Forge poll is open for a moment many
6
+ // times a second, and an antivirus scan can hold it longer; fixed-interval
7
+ // retries can also fall into step with a poller of the same period. Replacing
8
+ // it therefore retries with growing, jittered delays until a deadline, so a
9
+ // reader can delay a replace but never fail it.
10
+ const replaceRetryCodes = new Set(["EACCES", "EBUSY", "EPERM"]);
11
+ const defaultReplaceDeadlineMs = 15_000;
12
+ const firstRetryDelayMs = 5;
13
+ const maximumRetryDelayMs = 250;
14
+ /** Renames `temporaryPath` over `targetPath`, waiting out a reader that holds the target open. */
15
+ export async function replaceFile(temporaryPath, targetPath, options = {}) {
16
+ const rename = options.rename ?? fs.rename;
17
+ const deadline = monotonicNowMs() + (options.deadlineMs ?? defaultReplaceDeadlineMs);
18
+ for (let attempt = 0;; attempt += 1) {
19
+ try {
20
+ await rename(temporaryPath, targetPath);
21
+ return;
22
+ }
23
+ catch (error) {
24
+ const code = error?.code;
25
+ const remainingMs = deadline - monotonicNowMs();
26
+ if (!code || !replaceRetryCodes.has(code) || remainingMs <= 0)
27
+ throw error;
28
+ const ceilingMs = Math.min(maximumRetryDelayMs, firstRetryDelayMs * 2 ** Math.min(attempt, 6));
29
+ const delayMs = Math.min(remainingMs, ceilingMs / 2 + Math.random() * ceilingMs / 2);
30
+ await new Promise(resolve => setTimeout(resolve, delayMs));
31
+ }
32
+ }
33
+ }
@@ -1,12 +1,23 @@
1
- import type { HostProcessSupervisorMetadata } from "./host-process-supervisor.js";
1
+ import type { HostProcessSupervisorMetadata, WindowsSupervisorJobGone } from "./host-process-supervisor.js";
2
+ export { waitForWindowsSupervisorJobGone, type WindowsSupervisorJobGone } from "./host-process-supervisor.js";
2
3
  export type HostProcessRecoveryOutcome = "absent" | "terminated" | "pid_reused" | "unverifiable";
3
4
  export interface HostProcessRecovery {
4
5
  recover(metadata: HostProcessSupervisorMetadata): Promise<HostProcessRecoveryOutcome>;
5
6
  }
6
- /** Exact, birth-marker-fenced recovery for a process tree left by an old bridge. */
7
+ /**
8
+ * Exact, birth-marker-fenced recovery for a process tree left by an old bridge.
9
+ *
10
+ * On Windows the recorded root is the job supervisor, which holds the only handle to a
11
+ * kill-on-close Job Object holding the whole tree. The root's exit only starts that job's
12
+ * teardown: Windows reports a process gone once its exit code is set, before its handles
13
+ * are closed, and the members are stopped after that. So a Windows tree is reported gone
14
+ * only once its Job Object no longer exists, which is when no member is left.
15
+ */
7
16
  export declare class ExactHostProcessRecovery implements HostProcessRecovery {
8
17
  private readonly platform;
9
18
  private readonly graceMs;
10
- constructor(platform?: NodeJS.Platform, graceMs?: number);
19
+ private readonly windowsJobGone;
20
+ constructor(platform?: NodeJS.Platform, graceMs?: number, windowsJobGone?: WindowsSupervisorJobGone);
11
21
  recover(metadata: HostProcessSupervisorMetadata): Promise<HostProcessRecoveryOutcome>;
22
+ private stopRoot;
12
23
  }
@@ -1,14 +1,34 @@
1
- import { captureHostProcessIdentity } from "./host-process-supervisor.js";
1
+ import { captureHostProcessIdentity, waitForWindowsSupervisorJobGone } from "./host-process-supervisor.js";
2
2
  import { monotonicNowMs } from "../time/monotonic.js";
3
- /** Exact, birth-marker-fenced recovery for a process tree left by an old bridge. */
3
+ export { waitForWindowsSupervisorJobGone } from "./host-process-supervisor.js";
4
+ /**
5
+ * Exact, birth-marker-fenced recovery for a process tree left by an old bridge.
6
+ *
7
+ * On Windows the recorded root is the job supervisor, which holds the only handle to a
8
+ * kill-on-close Job Object holding the whole tree. The root's exit only starts that job's
9
+ * teardown: Windows reports a process gone once its exit code is set, before its handles
10
+ * are closed, and the members are stopped after that. So a Windows tree is reported gone
11
+ * only once its Job Object no longer exists, which is when no member is left.
12
+ */
4
13
  export class ExactHostProcessRecovery {
5
14
  platform;
6
15
  graceMs;
7
- constructor(platform = process.platform, graceMs = 2_000) {
16
+ windowsJobGone;
17
+ constructor(platform = process.platform, graceMs = 2_000, windowsJobGone = waitForWindowsSupervisorJobGone) {
8
18
  this.platform = platform;
9
19
  this.graceMs = graceMs;
20
+ this.windowsJobGone = windowsJobGone;
10
21
  }
11
22
  async recover(metadata) {
23
+ const outcome = await this.stopRoot(metadata);
24
+ if (outcome === "unverifiable" || this.platform !== "win32" || metadata.strategy !== "windows_job_object")
25
+ return outcome;
26
+ if (!await this.windowsJobGone(metadata.supervisorId, this.graceMs)) {
27
+ throw new Error(`host_process_recovery_degraded: the Job Object of supervisor ${metadata.supervisorId} still holds processes after its root stopped.`);
28
+ }
29
+ return outcome;
30
+ }
31
+ async stopRoot(metadata) {
12
32
  if (!processExists(metadata.rootPid))
13
33
  return "absent";
14
34
  if (!metadata.rootIdentity)
@@ -56,5 +56,17 @@ export declare function persistHostProcessSupervisorMetadata(launch: HostProcess
56
56
  * at an unrelated process.
57
57
  */
58
58
  export declare function captureHostProcessIdentity(pid: number, platform?: NodeJS.Platform): string | null;
59
- export declare function terminateHostProcessTree(child: ChildProcess, launch: HostProcessSupervisedLaunch | null, graceMs?: number): Promise<void>;
59
+ export declare function terminateHostProcessTree(child: ChildProcess, launch: HostProcessSupervisedLaunch | null, graceMs?: number, windowsJobGone?: WindowsSupervisorJobGone): Promise<void>;
60
+ /**
61
+ * Resolves true once a Windows job supervisor's Job Object no longer exists, false when it
62
+ * still does at the timeout or cannot be checked.
63
+ */
64
+ export type WindowsSupervisorJobGone = (supervisorId: string, timeoutMs: number) => Promise<boolean>;
65
+ /**
66
+ * Polls for the job supervisor's named Job Object (runtime/windows-job-supervisor.ps1 names
67
+ * it Local\Forge-<supervisorId>). A job object exists while any handle or member process
68
+ * holds it, and the supervisor's handle closed with it, so its absence means no member is
69
+ * left. Any answer but "not found" (an unreadable job, a failed check) is not proof.
70
+ */
71
+ export declare const waitForWindowsSupervisorJobGone: WindowsSupervisorJobGone;
60
72
  export declare function windowsPowerShellPath(): string;