@loucompanion/forge-bridge 0.1.4-dev.63db04bcffca → 0.1.4-dev.724427ea7be8

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 (271) hide show
  1. package/README.md +144 -3
  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 +101 -15
  16. package/dist/bridge/bridge.service.js +472 -345
  17. package/dist/bridge/bridge.types.d.ts +27 -0
  18. package/dist/bridge/dispatch-result-outbox.d.ts +11 -1
  19. package/dist/bridge/dispatch-result-outbox.js +31 -6
  20. package/dist/bridge/in-flight-registry.d.ts +62 -0
  21. package/dist/bridge/in-flight-registry.js +207 -0
  22. package/dist/bridge/local-yield-flag.d.ts +6 -0
  23. package/dist/bridge/local-yield-flag.js +34 -0
  24. package/dist/bridge/readiness-result-outbox.d.ts +5 -1
  25. package/dist/bridge/readiness-result-outbox.js +20 -0
  26. package/dist/bridge/runner-host-capabilities.d.ts +5 -0
  27. package/dist/bridge/runner-host-capabilities.js +17 -0
  28. package/dist/bridge/sandbox-resource-accounting.d.ts +16 -0
  29. package/dist/bridge/sandbox-resource-accounting.js +150 -0
  30. package/dist/bridge/test-postgres-capability.d.ts +14 -0
  31. package/dist/bridge/test-postgres-capability.js +120 -0
  32. package/dist/cleanup/cleanup-wip.d.ts +12 -0
  33. package/dist/cleanup/cleanup-wip.js +66 -0
  34. package/dist/cleanup/cleanup.service.d.ts +20 -1
  35. package/dist/cleanup/cleanup.service.js +150 -169
  36. package/dist/cleanup/cleanup.types.d.ts +6 -0
  37. package/dist/cleanup/forge-owned-paths.d.ts +9 -0
  38. package/dist/cleanup/forge-owned-paths.js +53 -0
  39. package/dist/cleanup/host-runtime-ledger.d.ts +7 -0
  40. package/dist/cleanup/host-runtime-ledger.js +130 -0
  41. package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
  42. package/dist/cleanup/managed-branch-sweep.js +111 -0
  43. package/dist/cli/cli.help.js +74 -12
  44. package/dist/cli/cli.service.d.ts +19 -10
  45. package/dist/cli/cli.service.js +152 -187
  46. package/dist/cli/idle-status.d.ts +84 -0
  47. package/dist/cli/idle-status.js +181 -0
  48. package/dist/cli/local-config.d.ts +6 -0
  49. package/dist/cli/local-config.js +32 -4
  50. package/dist/cli/provider-cli-detection.d.ts +10 -0
  51. package/dist/cli/provider-cli-detection.js +160 -0
  52. package/dist/runtime/aspnet-runtime-prebuild.d.ts +20 -0
  53. package/dist/runtime/aspnet-runtime-prebuild.js +184 -18
  54. package/dist/runtime/attempt-database-broker.d.ts +1 -1
  55. package/dist/runtime/attempt-node-runtime-launcher.js +9 -0
  56. package/dist/runtime/attempt-process-supervisor.d.ts +21 -0
  57. package/dist/runtime/attempt-process-supervisor.js +62 -6
  58. package/dist/runtime/docker-engine-probe.d.ts +5 -0
  59. package/dist/runtime/docker-engine-probe.js +7 -0
  60. package/dist/runtime/dotnet-build-outputs.d.ts +107 -0
  61. package/dist/runtime/dotnet-build-outputs.js +402 -0
  62. package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
  63. package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
  64. package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
  65. package/dist/runtime/ephemeral-test-postgres.js +303 -0
  66. package/dist/runtime/host-database-capability-boundary.d.ts +1 -1
  67. package/dist/runtime/host-database-capability-boundary.js +1 -0
  68. package/dist/runtime/host-facts.d.ts +36 -0
  69. package/dist/runtime/host-facts.js +95 -0
  70. package/dist/runtime/host-load-admission.d.ts +67 -0
  71. package/dist/runtime/host-load-admission.js +99 -0
  72. package/dist/runtime/host-load-child-environment.d.ts +27 -0
  73. package/dist/runtime/host-load-child-environment.js +76 -0
  74. package/dist/runtime/host-load-forge-cgroups.d.ts +49 -0
  75. package/dist/runtime/host-load-forge-cgroups.js +140 -0
  76. package/dist/runtime/host-load-governor-config.d.ts +52 -0
  77. package/dist/runtime/host-load-governor-config.js +83 -0
  78. package/dist/runtime/host-load-governor.d.ts +186 -0
  79. package/dist/runtime/host-load-governor.js +632 -0
  80. package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
  81. package/dist/runtime/host-load-ledger-lock.js +187 -0
  82. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  83. package/dist/runtime/host-load-runtime-settings.js +80 -0
  84. package/dist/runtime/host-load-sampler.d.ts +156 -0
  85. package/dist/runtime/host-load-sampler.js +298 -0
  86. package/dist/runtime/host-load-step-class.d.ts +70 -0
  87. package/dist/runtime/host-load-step-class.js +161 -0
  88. package/dist/runtime/host-load-step-reaper.d.ts +27 -0
  89. package/dist/runtime/host-load-step-reaper.js +95 -0
  90. package/dist/runtime/host-load-step-run.d.ts +73 -0
  91. package/dist/runtime/host-load-step-run.js +102 -0
  92. package/dist/runtime/host-load-test-slot.d.ts +43 -0
  93. package/dist/runtime/host-load-test-slot.js +81 -0
  94. package/dist/runtime/host-load-token-ledger.d.ts +200 -0
  95. package/dist/runtime/host-load-token-ledger.js +453 -0
  96. package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
  97. package/dist/runtime/host-load-windows-cpu.js +85 -0
  98. package/dist/runtime/host-pressure-stall.d.ts +61 -0
  99. package/dist/runtime/host-pressure-stall.js +168 -0
  100. package/dist/runtime/host-runtime-contract.d.ts +16 -0
  101. package/dist/runtime/host-runtime-contract.js +35 -2
  102. package/dist/runtime/host-runtime-lease.d.ts +76 -5
  103. package/dist/runtime/host-runtime-lease.js +322 -129
  104. package/dist/runtime/host-runtime-ledger-recovery.d.ts +20 -0
  105. package/dist/runtime/host-runtime-ledger-recovery.js +134 -0
  106. package/dist/runtime/host-runtime-promotion.d.ts +23 -0
  107. package/dist/runtime/host-runtime-promotion.js +48 -0
  108. package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
  109. package/dist/runtime/host-runtime-requirements-check.js +29 -0
  110. package/dist/runtime/host-runtime-requirements.d.ts +36 -0
  111. package/dist/runtime/host-runtime-requirements.js +117 -0
  112. package/dist/runtime/managed-command-teardown.d.ts +62 -0
  113. package/dist/runtime/managed-command-teardown.js +596 -0
  114. package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
  115. package/dist/runtime/native-test-postgres-fallback.js +60 -8
  116. package/dist/runtime/playwright-browser-cache.d.ts +39 -0
  117. package/dist/runtime/playwright-browser-cache.js +227 -0
  118. package/dist/runtime/playwright-host-runtime-adapter.d.ts +18 -0
  119. package/dist/runtime/playwright-host-runtime-adapter.js +61 -55
  120. package/dist/runtime/runner-settings.d.ts +104 -0
  121. package/dist/runtime/runner-settings.js +236 -0
  122. package/dist/runtime/supervised-runtime-build-guard.d.ts +45 -0
  123. package/dist/runtime/supervised-runtime-build-guard.js +112 -0
  124. package/dist/sandbox/host-capacity-broker.d.ts +115 -0
  125. package/dist/sandbox/host-capacity-broker.js +336 -0
  126. package/dist/sandbox/managed-branch.d.ts +13 -0
  127. package/dist/sandbox/managed-branch.js +90 -0
  128. package/dist/sandbox/provider-auth/codex.js +11 -11
  129. package/dist/sandbox/runtime.d.ts +10 -1
  130. package/dist/sandbox/runtime.js +47 -8
  131. package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
  132. package/dist/sandbox/sandbox-cgroups.js +42 -0
  133. package/dist/session/architect-waits.d.ts +2 -0
  134. package/dist/session/architect-waits.js +138 -0
  135. package/dist/session/managed-attempt-tools.d.ts +27 -7
  136. package/dist/session/managed-attempt-tools.js +406 -123
  137. package/dist/session/managed-build-coordinator.d.ts +17 -1
  138. package/dist/session/managed-build-coordinator.js +14 -1
  139. package/dist/session/managed-build-receipt.d.ts +5 -0
  140. package/dist/session/managed-build-receipt.js +8 -3
  141. package/dist/session/managed-command-host-load.d.ts +47 -0
  142. package/dist/session/managed-command-host-load.js +83 -0
  143. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  144. package/dist/session/mcp-argument-coercion.js +121 -0
  145. package/dist/session/phase-completion.artifacts.d.ts +7 -0
  146. package/dist/session/phase-completion.artifacts.js +100 -26
  147. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  148. package/dist/session/phase-completion.command-validation.js +77 -0
  149. package/dist/session/phase-completion.d.ts +12 -0
  150. package/dist/session/phase-completion.helpers.js +13 -12
  151. package/dist/session/phase-completion.js +5 -0
  152. package/dist/session/phase-completion.mcp-args.d.ts +9 -0
  153. package/dist/session/phase-completion.mcp-args.js +156 -0
  154. package/dist/session/phase-completion.prompts.js +6 -1
  155. package/dist/session/phase-completion.runtime.d.ts +5 -11
  156. package/dist/session/phase-completion.runtime.js +111 -230
  157. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  158. package/dist/session/phase-completion.schema-parts.js +188 -0
  159. package/dist/session/phase-completion.schemas.d.ts +3 -3
  160. package/dist/session/phase-completion.schemas.js +208 -231
  161. package/dist/session/phase-completion.validation.d.ts +2 -3
  162. package/dist/session/phase-completion.validation.js +49 -93
  163. package/dist/session/pre-publication-host-load.d.ts +27 -0
  164. package/dist/session/pre-publication-host-load.js +111 -0
  165. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  166. package/dist/session/pre-publication-native-postgres.js +111 -0
  167. package/dist/session/pre-publication-pass.d.ts +61 -0
  168. package/dist/session/pre-publication-pass.js +148 -0
  169. package/dist/session/pre-publication-process.d.ts +23 -0
  170. package/dist/session/pre-publication-process.js +109 -0
  171. package/dist/session/pre-publication-skipped-tests.d.ts +21 -0
  172. package/dist/session/pre-publication-skipped-tests.js +109 -0
  173. package/dist/session/pre-publication-step-execution.d.ts +12 -0
  174. package/dist/session/pre-publication-step-execution.js +50 -0
  175. package/dist/session/pre-publication-validation.d.ts +37 -21
  176. package/dist/session/pre-publication-validation.js +228 -219
  177. package/dist/session/provider-cli/claude-background-work.d.ts +67 -0
  178. package/dist/session/provider-cli/claude-background-work.js +181 -0
  179. package/dist/session/provider-cli/host-build-lock.d.ts +18 -0
  180. package/dist/session/provider-cli/host-build-lock.js +30 -0
  181. package/dist/session/provider-cli/pre-publication-repair.d.ts +56 -0
  182. package/dist/session/provider-cli/pre-publication-repair.js +276 -0
  183. package/dist/session/provider-cli/provider-cli.artifacts.d.ts +2 -1
  184. package/dist/session/provider-cli/provider-cli.artifacts.js +21 -15
  185. package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
  186. package/dist/session/provider-cli/provider-cli.child-environment.js +75 -0
  187. package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
  188. package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
  189. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
  190. package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
  191. package/dist/session/provider-cli/provider-cli.process.d.ts +46 -31
  192. package/dist/session/provider-cli/provider-cli.process.js +286 -403
  193. package/dist/session/provider-cli/provider-cli.prompts.d.ts +10 -0
  194. package/dist/session/provider-cli/provider-cli.prompts.js +87 -32
  195. package/dist/session/provider-cli/provider-cli.runtime.d.ts +8 -0
  196. package/dist/session/provider-cli/provider-cli.runtime.js +29 -1
  197. package/dist/session/provider-cli/provider-cli.service.d.ts +7 -1
  198. package/dist/session/provider-cli/provider-cli.service.js +207 -192
  199. package/dist/session/provider-cli/provider-cli.types.d.ts +30 -0
  200. package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
  201. package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
  202. package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
  203. package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
  204. package/dist/session/provider-cli/provider-in-flight-work.d.ts +10 -0
  205. package/dist/session/provider-cli/provider-in-flight-work.js +92 -0
  206. package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
  207. package/dist/session/provider-cli/provider-output-pipes.js +67 -0
  208. package/dist/session/provider-cli/provider-output-state.d.ts +8 -0
  209. package/dist/session/provider-cli/provider-output-state.js +15 -0
  210. package/dist/session/provider-cli/provider-user-config-isolation.d.ts +69 -0
  211. package/dist/session/provider-cli/provider-user-config-isolation.js +164 -0
  212. package/dist/session/publishable-worktree-changes.d.ts +54 -0
  213. package/dist/session/publishable-worktree-changes.js +193 -0
  214. package/dist/session/qa-sidecar-validation.d.ts +6 -0
  215. package/dist/session/qa-sidecar-validation.js +28 -0
  216. package/dist/session/sandbox-host-capacity-gate.d.ts +51 -0
  217. package/dist/session/sandbox-host-capacity-gate.js +257 -0
  218. package/dist/session/session-redaction.js +31 -181
  219. package/dist/session/session.base.d.ts +9 -1
  220. package/dist/session/session.service.d.ts +11 -2
  221. package/dist/session/session.service.js +189 -69
  222. package/dist/session/session.types.d.ts +3 -0
  223. package/dist/session/session.types.js +15 -3
  224. package/dist/session/sidecar-json-shape.d.ts +31 -0
  225. package/dist/session/sidecar-json-shape.js +217 -0
  226. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  227. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  228. package/dist/shared/fs/file-identity.d.ts +10 -0
  229. package/dist/shared/fs/file-identity.js +15 -0
  230. package/dist/shared/fs/replace-file.d.ts +7 -0
  231. package/dist/shared/fs/replace-file.js +33 -0
  232. package/dist/shared/process/host-process-recovery.d.ts +14 -3
  233. package/dist/shared/process/host-process-recovery.js +23 -3
  234. package/dist/shared/process/host-process-supervisor.d.ts +14 -1
  235. package/dist/shared/process/host-process-supervisor.js +67 -15
  236. package/dist/shared/process/process-tree.d.ts +52 -0
  237. package/dist/shared/process/process-tree.js +144 -0
  238. package/dist/shared/process/process.d.ts +67 -0
  239. package/dist/shared/process/process.js +213 -11
  240. package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
  241. package/dist/shared/process/windows-app-execution-alias.js +45 -0
  242. package/dist/shared/process/windows-launch.d.ts +18 -0
  243. package/dist/shared/process/windows-launch.js +68 -0
  244. package/dist/shared/provider-capabilities.js +14 -7
  245. package/dist/version.d.ts +1 -1
  246. package/dist/version.js +1 -1
  247. package/dist/worktree/dependency-warmer.d.ts +25 -0
  248. package/dist/worktree/dependency-warmer.js +46 -10
  249. package/dist/worktree/orphan-relink.d.ts +19 -0
  250. package/dist/worktree/orphan-relink.js +106 -0
  251. package/dist/worktree/wip-git.d.ts +33 -0
  252. package/dist/worktree/wip-git.js +122 -0
  253. package/dist/worktree/wip-refs.d.ts +62 -0
  254. package/dist/worktree/wip-refs.js +119 -0
  255. package/dist/worktree/wip-restore.d.ts +38 -0
  256. package/dist/worktree/wip-restore.js +190 -0
  257. package/dist/worktree/wip-snapshot.d.ts +50 -0
  258. package/dist/worktree/wip-snapshot.js +268 -0
  259. package/dist/worktree/worktree-inputs.d.ts +8 -0
  260. package/dist/worktree/worktree-inputs.js +134 -0
  261. package/dist/worktree/worktree-origin-sync.d.ts +34 -0
  262. package/dist/worktree/worktree-origin-sync.js +127 -0
  263. package/dist/worktree/worktree-wip-events.d.ts +18 -0
  264. package/dist/worktree/worktree-wip-events.js +98 -0
  265. package/dist/worktree/worktree-wip.d.ts +50 -0
  266. package/dist/worktree/worktree-wip.js +185 -0
  267. package/dist/worktree/worktree.base.d.ts +7 -1
  268. package/dist/worktree/worktree.service.d.ts +36 -5
  269. package/dist/worktree/worktree.service.js +124 -155
  270. package/dist/worktree/worktree.types.d.ts +38 -0
  271. package/package.json +2 -2
@@ -0,0 +1,98 @@
1
+ /** Reports what the prepare did with the story's saved WIP, before the provider starts. */
2
+ export async function emitWipRestoreEvent(worktree, emit) {
3
+ const outcome = worktree.wipRestore;
4
+ if (!outcome || outcome.status === "none")
5
+ return;
6
+ if (outcome.status === "restored") {
7
+ await emit(checkpoint("worktree_wip_restored", `Restored uncommitted work saved in ${outcome.ref}${outcome.sourceSessionId ? ` by session ${outcome.sourceSessionId}` : ""} `
8
+ + `(${outcome.changedPaths} path(s)${outcome.mergeInProgress ? ", with its merge still in progress" : ""}) onto ${worktree.branchName} before the provider started.`, outcome));
9
+ }
10
+ else if (outcome.status === "not_restored") {
11
+ await emit(checkpoint("worktree_wip_not_restored", `Did not restore the uncommitted work saved in ${outcome.ref}: ${outcome.reason === "branch_moved" ? "the story branch has moved since it was saved" : "it could not be applied"}. `
12
+ + `${outcome.detail} This pass starts from a clean worktree; the ref is kept on origin.`, outcome));
13
+ }
14
+ else if (outcome.status === "skipped_dirty") {
15
+ await emit(checkpoint("worktree_wip_restore_skipped", `${worktree.branchName} already has uncommitted changes in its reattached worktree, so ${outcome.ref} was not applied on top of them.`, outcome));
16
+ }
17
+ else {
18
+ await emit(checkpoint("worktree_wip_restore_unavailable", `Could not check origin for saved uncommitted work on ${worktree.branchName}: ${outcome.detail}`, outcome));
19
+ }
20
+ }
21
+ /** How a session ended, for the snapshot it leaves behind. */
22
+ export function sessionWipOutcome(signal, events, succeeded) {
23
+ if (succeeded)
24
+ return { reason: null };
25
+ if (signal?.aborted)
26
+ return { reason: isPauseRequested(signal) ? "session_paused" : "session_stopped" };
27
+ const repairLimit = events.some(event => event.eventType === "prepublication_repair_exhausted");
28
+ return { reason: repairLimit ? "repair_limit" : "session_failed" };
29
+ }
30
+ /**
31
+ * Ends a session's use of its worktree: first saves its WIP (or retires the snapshot it started
32
+ * from) and reports that, then, as a separate step, releases the worktree unless the session
33
+ * paused or its WIP could not be saved. Nothing here throws over the session's own result or
34
+ * failure: a release that refuses to delete unsaved work, or that fails (a Windows process still
35
+ * holding a cwd in the worktree makes the rename fail), keeps the worktree on this runner and is
36
+ * reported as a cleanup failure.
37
+ */
38
+ export async function settleWorktree(worktrees, worktree, outcome, signal, emit) {
39
+ const settlement = await worktrees.settleWip?.(worktree, outcome)
40
+ .catch((error) => ({ error: { code: "wip_snapshot_failed", message: messageOf(error) } }));
41
+ if (settlement)
42
+ await emitSettlement(worktree, outcome, settlement, emit).catch(() => undefined);
43
+ // A paused session keeps its worktree for the resume, exactly as before. So does a session whose
44
+ // work could not be saved: the release's own snapshot is never applied automatically, so letting
45
+ // it succeed after this one failed would delete the only copy a later pass would restore.
46
+ if (isPauseRequested(signal) || settlement?.error)
47
+ return;
48
+ try {
49
+ await worktrees.release(worktree);
50
+ }
51
+ catch (error) {
52
+ if (!(error instanceof Error) || error.name !== "WipPreservationError") {
53
+ await emit({
54
+ role: "runner",
55
+ kind: "error",
56
+ content: `Could not remove the worktree ${worktree.worktreePath} after the session (${messageOf(error)}); it stays on this runner.`,
57
+ eventType: "worktree_release_failed",
58
+ data: JSON.stringify({ stage: "release", worktreePath: worktree.worktreePath, message: messageOf(error) }),
59
+ }).catch(() => undefined);
60
+ return;
61
+ }
62
+ await emit({
63
+ role: "runner",
64
+ kind: "error",
65
+ content: `Kept the worktree ${worktree.worktreePath} on this runner instead of removing it: its uncommitted work could not be saved (${error.message}).`,
66
+ eventType: "worktree_wip_snapshot_failed",
67
+ data: JSON.stringify({ code: error.code ?? "wip_snapshot_failed", stage: "release", worktreePath: worktree.worktreePath }),
68
+ }).catch(() => undefined);
69
+ }
70
+ }
71
+ async function emitSettlement(worktree, outcome, settlement, emit) {
72
+ const snapshot = settlement.snapshot;
73
+ if (snapshot && snapshot.status !== "clean") {
74
+ await emit(checkpoint("worktree_wip_saved", `Saved this session's uncommitted work (${snapshot.changedPaths} path(s)) to ${snapshot.ref}${snapshot.pushed ? " on origin" : " in the runner's repository (it has no origin)"} `
75
+ + `before the session ended (${outcome.reason}). The next pass on ${worktree.branchName} restores it when the branch has not moved.`, { ...snapshot, reason: outcome.reason, lane: worktree.lane ?? null }));
76
+ }
77
+ if (settlement.error) {
78
+ await emit({
79
+ role: "runner",
80
+ kind: "error",
81
+ content: `Could not save this session's uncommitted work to a WIP ref (${settlement.error.message}). Forge will not delete the worktree ${worktree.worktreePath}; the work stays on this runner only.`,
82
+ eventType: "worktree_wip_snapshot_failed",
83
+ data: JSON.stringify({ ...settlement.error, stage: "session_end", reason: outcome.reason, worktreePath: worktree.worktreePath }),
84
+ });
85
+ }
86
+ if (settlement.retiredRef) {
87
+ await emit(checkpoint("worktree_wip_retired", `Deleted ${settlement.retiredRef}: the work restored from it is now ${outcome.reason ? "saved again by this session" : "published by this session"}.`, { ref: settlement.retiredRef }));
88
+ }
89
+ }
90
+ function isPauseRequested(signal) {
91
+ return signal?.aborted === true && String(signal.reason ?? "").trim().toLowerCase() === "session pause requested";
92
+ }
93
+ function checkpoint(eventType, content, data) {
94
+ return { role: "runner", kind: "checkpoint", content, eventType, data: JSON.stringify(data) };
95
+ }
96
+ function messageOf(error) {
97
+ return error instanceof Error ? error.message : String(error);
98
+ }
@@ -0,0 +1,50 @@
1
+ import { GitClient } from "../shared/git/git.js";
2
+ import { type WipRestoreOutcome } from "./wip-restore.js";
3
+ import { type WipSnapshotResult } from "./wip-snapshot.js";
4
+ import type { WipSessionOutcome, WipSettlement, WorktreeHandle } from "./worktree.types.js";
5
+ export { relinkOrphanedWorktree } from "./orphan-relink.js";
6
+ /**
7
+ * Saves uncommitted work before `git reset --hard` / `git clean` on an existing worktree; a later
8
+ * pass may apply it by itself only when it came from a publishing lane.
9
+ * Throws when it could not be saved: losing work is worse than a failed prepare.
10
+ */
11
+ export declare function guardWorktreeReset(worktreePath: string, branchName: string, owner: {
12
+ readonly sessionId?: string | null;
13
+ readonly lane: string;
14
+ }): Promise<WipSnapshotResult>;
15
+ /**
16
+ * Before a local branch is re-pointed at a new start point (`worktree add -B`), saves any commits
17
+ * on it that neither the start point nor origin has, as a `forge.wip.v1` snapshot like any other:
18
+ * its tree is the tip's, its first parent the tip (so the commits are `<ref>^1` and its ancestors),
19
+ * and it is never applied automatically. Throws when they could not be saved.
20
+ */
21
+ export declare function guardBranchReset(git: GitClient, repoPath: string, branchName: string, startPoint: string): Promise<void>;
22
+ /** Puts the newest restorable snapshot back on a freshly prepared worktree of a publishing lane. */
23
+ export declare function restoreWorktreeWip(input: {
24
+ readonly worktreePath: string;
25
+ readonly repoPath: string;
26
+ readonly branchName: string;
27
+ readonly sessionId?: string | null;
28
+ readonly lane: string;
29
+ }): Promise<WipRestoreOutcome | undefined>;
30
+ /**
31
+ * Saves a worktree that is about to be deleted. Its snapshot is never applied automatically (a
32
+ * session that ended without succeeding has already saved its own work under its id; what is
33
+ * left after a successful pass was deliberately not published). Throws when it could not be saved.
34
+ */
35
+ export declare function guardWorktreeRelease(handle: WorktreeHandle): Promise<WipSnapshotResult>;
36
+ /** Forgets what this process saved for a worktree once it is gone. */
37
+ export declare function worktreeReleased(handle: WorktreeHandle): void;
38
+ /**
39
+ * At the end of a session: saves its uncommitted work unless it succeeded, and deletes the
40
+ * snapshot it started from once that work is safe elsewhere: saved again here, or (after a
41
+ * success) published, which is only certain when nothing is left uncommitted. Leftovers keep the
42
+ * ref; the release's own snapshot of them is never applied automatically.
43
+ * Never throws; a failure is reported in the result.
44
+ */
45
+ export declare function settleSessionWip(handle: WorktreeHandle, outcome: WipSessionOutcome): Promise<WipSettlement>;
46
+ /**
47
+ * After a release: deletes the readiness probe's branch, and other Forge branches whose work is
48
+ * already on the base. Branches of live leases are kept; when the ledger can't be read, nothing is.
49
+ */
50
+ export declare function sweepBranchesAfterRelease(git: GitClient, handle: WorktreeHandle, leaseStateRoot: string, limit: number): Promise<void>;
@@ -0,0 +1,185 @@
1
+ import { liveLeaseBranches, readHostRuntimeLeases } from "../cleanup/host-runtime-ledger.js";
2
+ import { deleteBranchIfUnused, isRuntimeReadinessBranch, sweepManagedBranches } from "../cleanup/managed-branch-sweep.js";
3
+ import { WipGit } from "./wip-git.js";
4
+ import { formatWipCommitMessage, unorderedWipAttempt, wipMetadataSchema, WipPreservationError, wipRefId, wipRefName, } from "./wip-refs.js";
5
+ import { deleteWipRef, hasNoUnsavedWork, restoreLatestWip } from "./wip-restore.js";
6
+ import { forgetPreservedWip, forgetPreservedWipRef, preserveWorktreeWip } from "./wip-snapshot.js";
7
+ // How the worktree lifecycle keeps uncommitted work (see wip-refs.ts for the ref layout):
8
+ // - every path that could destroy it (a reset to the base, re-pointing the branch, a release that
9
+ // deletes the checkout) saves it to a WIP ref first and does not run when that fails;
10
+ // - a session that ends without succeeding saves it under the session's id;
11
+ // - a publishing lane's next pass puts the newest snapshot back when the branch has not moved;
12
+ // - a checkout that lost only its `.git` link is reattached to Git's admin directory for it, which
13
+ // holds its index and MERGE_HEAD, instead of being recreated (orphan-relink.ts).
14
+ export { relinkOrphanedWorktree } from "./orphan-relink.js";
15
+ /** Lanes whose work the bridge publishes, and so whose snapshots a later pass may apply by itself. */
16
+ const restoreLanes = new Set(["develop", "debug", "conflict_resolve", "ci_repair"]);
17
+ function isWipRestoreLane(lane) {
18
+ return restoreLanes.has((lane ?? "").trim().toLowerCase());
19
+ }
20
+ /**
21
+ * Saves uncommitted work before `git reset --hard` / `git clean` on an existing worktree; a later
22
+ * pass may apply it by itself only when it came from a publishing lane.
23
+ * Throws when it could not be saved: losing work is worse than a failed prepare.
24
+ */
25
+ export async function guardWorktreeReset(worktreePath, branchName, owner) {
26
+ try {
27
+ return await preserveWorktreeWip({
28
+ worktreePath,
29
+ branchName,
30
+ reason: "pre_reset",
31
+ sessionId: owner.sessionId,
32
+ lane: owner.lane,
33
+ autoRestore: isWipRestoreLane(owner.lane),
34
+ });
35
+ }
36
+ catch (error) {
37
+ throw new Error(`Refusing to reset ${worktreePath} to its base: its uncommitted work could not be saved to a WIP ref (${errorMessage(error)}).`, { cause: error });
38
+ }
39
+ }
40
+ /**
41
+ * Before a local branch is re-pointed at a new start point (`worktree add -B`), saves any commits
42
+ * on it that neither the start point nor origin has, as a `forge.wip.v1` snapshot like any other:
43
+ * its tree is the tip's, its first parent the tip (so the commits are `<ref>^1` and its ancestors),
44
+ * and it is never applied automatically. Throws when they could not be saved.
45
+ */
46
+ export async function guardBranchReset(git, repoPath, branchName, startPoint) {
47
+ const tip = (await git.run(repoPath, ["rev-parse", "-q", "--verify", `refs/heads/${branchName}^{commit}`]).catch(() => "")).trim();
48
+ if (!tip)
49
+ return;
50
+ const onStartPoint = await git.run(repoPath, ["merge-base", "--is-ancestor", tip, startPoint]).then(() => true, () => false);
51
+ if (onStartPoint)
52
+ return;
53
+ const onOrigin = (await git.run(repoPath, ["branch", "-r", "--contains", tip]).catch(() => "")).trim().length > 0;
54
+ if (onOrigin)
55
+ return;
56
+ const now = new Date();
57
+ const ref = wipRefName(branchName, wipRefId("pre_branch_reset", null, now));
58
+ const origin = (await git.run(repoPath, ["remote", "get-url", "origin"]).catch(() => "")).trim();
59
+ try {
60
+ const snapshot = await branchTipSnapshot(repoPath, branchName, tip, now);
61
+ await git.run(repoPath, origin ? ["push", "--porcelain", "origin", `${snapshot}:${ref}`] : ["update-ref", ref, snapshot]);
62
+ }
63
+ catch (error) {
64
+ throw new Error(`Refusing to re-point ${branchName} at ${startPoint}: its unpublished commits (${tip.slice(0, 12)}) could not be saved to ${ref} (${errorMessage(error)}).`, { cause: error });
65
+ }
66
+ }
67
+ /** A snapshot commit holding a branch tip: nothing uncommitted, so its tree and index are the tip's. */
68
+ async function branchTipSnapshot(repoPath, branchName, tip, now) {
69
+ const git = new WipGit();
70
+ const tree = (await git.run(repoPath, ["rev-parse", `${tip}^{tree}`])).trim();
71
+ const indexCommit = (await git.run(repoPath, ["commit-tree", tree, "-p", tip, "-m", "forge wip index snapshot"])).trim();
72
+ const message = formatWipCommitMessage({
73
+ schema: wipMetadataSchema,
74
+ branch: branchName,
75
+ baseHead: tip,
76
+ sessionId: null,
77
+ lane: null,
78
+ reason: "pre_branch_reset",
79
+ attempt: unorderedWipAttempt,
80
+ autoRestore: false,
81
+ createdAt: now.toISOString(),
82
+ createdAtMs: now.getTime(),
83
+ mergeHead: null,
84
+ mergeMessage: null,
85
+ mergeMode: null,
86
+ unmerged: [],
87
+ changedPaths: 0,
88
+ bytes: 0,
89
+ });
90
+ return (await git.run(repoPath, ["commit-tree", tree, "-p", tip, "-p", indexCommit, "-m", message])).trim();
91
+ }
92
+ /** Puts the newest restorable snapshot back on a freshly prepared worktree of a publishing lane. */
93
+ export async function restoreWorktreeWip(input) {
94
+ if (!input.sessionId || !isWipRestoreLane(input.lane))
95
+ return undefined;
96
+ return await restoreLatestWip(input);
97
+ }
98
+ /**
99
+ * Saves a worktree that is about to be deleted. Its snapshot is never applied automatically (a
100
+ * session that ended without succeeding has already saved its own work under its id; what is
101
+ * left after a successful pass was deliberately not published). Throws when it could not be saved.
102
+ */
103
+ export async function guardWorktreeRelease(handle) {
104
+ // A readiness probe never runs an agent; its checkout only ever holds the app's own output.
105
+ if (isRuntimeReadinessBranch(handle.branchName))
106
+ return { status: "clean" };
107
+ return await preserveWorktreeWip({
108
+ worktreePath: handle.worktreePath,
109
+ branchName: handle.branchName,
110
+ reason: "pre_release",
111
+ sessionId: handle.sessionId,
112
+ lane: handle.lane,
113
+ autoRestore: false,
114
+ });
115
+ }
116
+ /** Forgets what this process saved for a worktree once it is gone. */
117
+ export function worktreeReleased(handle) {
118
+ forgetPreservedWip(handle.worktreePath);
119
+ }
120
+ /**
121
+ * At the end of a session: saves its uncommitted work unless it succeeded, and deletes the
122
+ * snapshot it started from once that work is safe elsewhere: saved again here, or (after a
123
+ * success) published, which is only certain when nothing is left uncommitted. Leftovers keep the
124
+ * ref; the release's own snapshot of them is never applied automatically.
125
+ * Never throws; a failure is reported in the result.
126
+ */
127
+ export async function settleSessionWip(handle, outcome) {
128
+ let snapshot;
129
+ if (outcome.reason) {
130
+ try {
131
+ snapshot = await preserveWorktreeWip({
132
+ worktreePath: handle.worktreePath,
133
+ branchName: handle.branchName,
134
+ reason: outcome.reason,
135
+ sessionId: handle.sessionId,
136
+ lane: handle.lane,
137
+ autoRestore: isWipRestoreLane(handle.lane),
138
+ });
139
+ }
140
+ catch (error) {
141
+ return {
142
+ error: {
143
+ code: error instanceof WipPreservationError ? error.code : "wip_snapshot_failed",
144
+ message: errorMessage(error),
145
+ },
146
+ };
147
+ }
148
+ }
149
+ const restored = handle.wipRestore?.status === "restored" ? handle.wipRestore.ref : null;
150
+ // A failed session that left a clean worktree may have thrown the restored work away; keep its ref.
151
+ const supersededBy = snapshot && snapshot.status !== "clean" ? snapshot.ref : null;
152
+ const safeElsewhere = outcome.reason === null
153
+ ? await hasNoUnsavedWork(handle.worktreePath).catch(() => false)
154
+ : Boolean(supersededBy && supersededBy !== restored);
155
+ const retire = restored && safeElsewhere ? restored : null;
156
+ if (retire)
157
+ forgetPreservedWipRef(retire);
158
+ const retiredRef = retire && await deleteWipRef(handle.repoPath, retire) ? retire : null;
159
+ return { ...(snapshot ? { snapshot } : {}), retiredRef };
160
+ }
161
+ /**
162
+ * After a release: deletes the readiness probe's branch, and other Forge branches whose work is
163
+ * already on the base. Branches of live leases are kept; when the ledger can't be read, nothing is.
164
+ */
165
+ export async function sweepBranchesAfterRelease(git, handle, leaseStateRoot, limit) {
166
+ const protectedBranches = await readHostRuntimeLeases(leaseStateRoot)
167
+ .then(liveLeaseBranches)
168
+ .catch(() => null);
169
+ if (!protectedBranches)
170
+ return;
171
+ let budget = limit;
172
+ if (isRuntimeReadinessBranch(handle.branchName) && !protectedBranches.has(handle.branchName)
173
+ && await deleteBranchIfUnused(git, handle.repoPath, handle.branchName)) {
174
+ budget -= 1;
175
+ }
176
+ await sweepManagedBranches(git, handle.repoPath, {
177
+ baseBranch: handle.baseBranch,
178
+ includeMergedWorkBranches: true,
179
+ protectedBranches,
180
+ limit: budget,
181
+ }).catch(() => undefined);
182
+ }
183
+ function errorMessage(error) {
184
+ return error instanceof Error ? error.message : String(error);
185
+ }
@@ -1,7 +1,13 @@
1
- import type { WorktreeHandle, WorktreePrepareRequest } from "./worktree.types.js";
1
+ import type { WipSessionOutcome, WipSettlement, WorktreeHandle, WorktreePrepareRequest } from "./worktree.types.js";
2
2
  export interface WorktreeService {
3
3
  prepare(request: WorktreePrepareRequest): Promise<WorktreeHandle>;
4
+ /**
5
+ * Must not delete uncommitted work it could not save first: it keeps the worktree and throws a
6
+ * WipPreservationError instead.
7
+ */
4
8
  release(handle: WorktreeHandle): Promise<void>;
9
+ /** Saves (or retires) the session's WIP when it ends; never throws. */
10
+ settleWip?(handle: WorktreeHandle, outcome: WipSessionOutcome): Promise<WipSettlement>;
5
11
  }
6
12
  export interface WorktreeLifecycleCoordinator {
7
13
  withLock<T>(repoPath: string, action: () => Promise<T>, signal?: AbortSignal): Promise<T>;
@@ -1,12 +1,40 @@
1
1
  import { GitClient } from "../shared/git/git.js";
2
+ import type { HostLoadStepGate } from "../runtime/host-load-governor.js";
2
3
  import type { WorktreeLifecycleCoordinator, WorktreeService } from "./worktree.base.js";
3
- import type { WorktreeHandle, WorktreePrepareRequest } from "./worktree.types.js";
4
+ import type { WipSessionOutcome, WipSettlement, WorktreeHandle, WorktreePrepareRequest } from "./worktree.types.js";
5
+ import { type BridgeLog } from "./worktree-origin-sync.js";
6
+ export { emitWipRestoreEvent, sessionWipOutcome, settleWorktree } from "./worktree-wip-events.js";
7
+ export { emitWorktreePreparedEvents } from "./worktree-origin-sync.js";
8
+ export { clearRunArtifactRoots } from "./worktree-inputs.js";
4
9
  export declare class GitWorktreeService implements WorktreeService {
5
10
  private readonly git;
6
11
  private readonly coordinator;
7
- constructor(git?: GitClient, coordinator?: WorktreeLifecycleCoordinator);
12
+ /** Gates dependency install fallbacks; inert unless the governor is on. */
13
+ private readonly hostLoadGate?;
14
+ /** Holds the host runtime lease ledger; branches of live leases are never swept on release. */
15
+ private readonly leaseStateRoot;
16
+ /** The bridge log: prepare records its start point and what it did to a reused worktree. */
17
+ private readonly log;
18
+ constructor(git?: GitClient, coordinator?: WorktreeLifecycleCoordinator,
19
+ /** Gates dependency install fallbacks; inert unless the governor is on. */
20
+ hostLoadGate?: HostLoadStepGate | undefined,
21
+ /** Holds the host runtime lease ledger; branches of live leases are never swept on release. */
22
+ leaseStateRoot?: string,
23
+ /** The bridge log: prepare records its start point and what it did to a reused worktree. */
24
+ log?: BridgeLog);
8
25
  prepare(request: WorktreePrepareRequest): Promise<WorktreeHandle>;
9
- private trackedForgePaths;
26
+ private warmDependencies;
27
+ /** Restores the story's saved WIP (still under the repository lock, before the provider starts). */
28
+ private withRestoredWip;
29
+ /** Creates the lease's worktree; see describeNewWorktreeStart for what it reports. */
30
+ private addWorktree;
31
+ /**
32
+ * Readies a surviving worktree for this pass: lanes that start from their base are reset to it;
33
+ * the others keep their state but are brought up to origin's head when only behind it
34
+ * (worktree-origin-sync.ts). A resumed session keeps its worktree exactly as it was.
35
+ */
36
+ private refreshReusedWorktree;
37
+ settleWip(handle: WorktreeHandle, outcome: WipSessionOutcome): Promise<WipSettlement>;
10
38
  private registeredManagedWorktreePath;
11
39
  private repoCreationCoordinationPath;
12
40
  release(handle: WorktreeHandle): Promise<void>;
@@ -15,6 +43,11 @@ export declare class GitWorktreeService implements WorktreeService {
15
43
  private managedRepoPath;
16
44
  private findExistingRepoPath;
17
45
  private resolveMatchingRepo;
46
+ /**
47
+ * The start point for the lease's base: origin's freshly fetched head when origin has the
48
+ * branch, else the local branch. When the fetch fails, the local branch is used only if origin
49
+ * has never had the base or the lease branch: otherwise the worktree could run on stale code.
50
+ */
18
51
  private resolveBaseStartPoint;
19
52
  private resetWorktreeToBase;
20
53
  private gitRefExists;
@@ -25,6 +58,4 @@ type WorktreeRename = (source: string, destination: string) => Promise<void>;
25
58
  type WorktreeRenameDelay = (milliseconds: number) => Promise<void>;
26
59
  export declare function renameWorktreeForRelease(source: string, destination: string, rename?: WorktreeRename, wait?: WorktreeRenameDelay, maxAttempts?: number): Promise<void>;
27
60
  export declare function requiresMutableEnvironmentPreparation(request: Pick<WorktreePrepareRequest, "applicationRuntimeRequired">): boolean;
28
- export declare function clearRunArtifactRoots(worktreePath: string, request: WorktreePrepareRequest): Promise<void>;
29
61
  export declare function normalizeBranchName(value: string | null | undefined, fallback: string): string;
30
- export {};