@loucompanion/forge-bridge 0.1.4-dev.fb770705136a → 0.2.1-dev.1a5cf93b48a1

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 (267) hide show
  1. package/README.md +144 -3
  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 +40 -0
  5. package/dist/bridge/bridge-chat-provider-command.js +230 -0
  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 +11 -0
  11. package/dist/bridge/bridge-state-io.js +50 -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.base.d.ts +9 -0
  17. package/dist/bridge/bridge.service.d.ts +92 -14
  18. package/dist/bridge/bridge.service.js +446 -380
  19. package/dist/bridge/bridge.types.d.ts +21 -0
  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.d.ts +36 -0
  56. package/dist/runtime/attempt-node-runtime-launcher.js +169 -0
  57. package/dist/runtime/attempt-process-supervisor.d.ts +2 -0
  58. package/dist/runtime/attempt-process-supervisor.js +12 -6
  59. package/dist/runtime/docker-engine-probe.d.ts +5 -0
  60. package/dist/runtime/docker-engine-probe.js +7 -0
  61. package/dist/runtime/dotnet-build-outputs.d.ts +107 -0
  62. package/dist/runtime/dotnet-build-outputs.js +402 -0
  63. package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
  64. package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
  65. package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
  66. package/dist/runtime/ephemeral-test-postgres.js +303 -0
  67. package/dist/runtime/host-facts.d.ts +2 -1
  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 +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 +75 -2
  85. package/dist/runtime/host-load-sampler.js +142 -8
  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 +21 -1
  99. package/dist/runtime/host-pressure-stall.js +48 -1
  100. package/dist/runtime/host-runtime-contract.d.ts +15 -0
  101. package/dist/runtime/host-runtime-contract.js +33 -2
  102. package/dist/runtime/host-runtime-lease.d.ts +101 -6
  103. package/dist/runtime/host-runtime-lease.js +408 -294
  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 +101 -2
  107. package/dist/runtime/host-runtime-promotion.js +355 -14
  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.js +5 -16
  113. package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
  114. package/dist/runtime/native-test-postgres-fallback.js +60 -8
  115. package/dist/runtime/playwright-host-runtime-adapter.d.ts +7 -0
  116. package/dist/runtime/playwright-host-runtime-adapter.js +13 -1
  117. package/dist/runtime/prepared-runtime-identity.d.ts +4 -0
  118. package/dist/runtime/prepared-runtime-identity.js +130 -9
  119. package/dist/runtime/prepared-runtime-readiness.d.ts +13 -1
  120. package/dist/runtime/prepared-runtime-readiness.js +63 -16
  121. package/dist/runtime/runner-settings.d.ts +104 -0
  122. package/dist/runtime/runner-settings.js +236 -0
  123. package/dist/runtime/supervised-runtime-build-guard.d.ts +45 -0
  124. package/dist/runtime/supervised-runtime-build-guard.js +112 -0
  125. package/dist/sandbox/host-capacity-broker.d.ts +115 -0
  126. package/dist/sandbox/host-capacity-broker.js +336 -0
  127. package/dist/sandbox/managed-branch.d.ts +13 -0
  128. package/dist/sandbox/managed-branch.js +90 -0
  129. package/dist/sandbox/provider-auth/codex.js +11 -11
  130. package/dist/sandbox/runtime.d.ts +10 -1
  131. package/dist/sandbox/runtime.js +47 -8
  132. package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
  133. package/dist/sandbox/sandbox-cgroups.js +42 -0
  134. package/dist/session/architect-waits.d.ts +2 -0
  135. package/dist/session/architect-waits.js +138 -0
  136. package/dist/session/managed-attempt-tools.d.ts +2 -7
  137. package/dist/session/managed-attempt-tools.js +207 -121
  138. package/dist/session/managed-build-coordinator.d.ts +16 -0
  139. package/dist/session/managed-build-coordinator.js +10 -0
  140. package/dist/session/managed-build-receipt.d.ts +5 -0
  141. package/dist/session/managed-build-receipt.js +8 -3
  142. package/dist/session/managed-command-host-load.d.ts +47 -0
  143. package/dist/session/managed-command-host-load.js +83 -0
  144. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  145. package/dist/session/mcp-argument-coercion.js +121 -0
  146. package/dist/session/phase-completion.artifacts.d.ts +7 -0
  147. package/dist/session/phase-completion.artifacts.js +96 -26
  148. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  149. package/dist/session/phase-completion.command-validation.js +77 -0
  150. package/dist/session/phase-completion.d.ts +12 -0
  151. package/dist/session/phase-completion.helpers.js +13 -12
  152. package/dist/session/phase-completion.js +5 -0
  153. package/dist/session/phase-completion.mcp-args.d.ts +9 -0
  154. package/dist/session/phase-completion.mcp-args.js +156 -0
  155. package/dist/session/phase-completion.prompts.js +6 -1
  156. package/dist/session/phase-completion.runtime.d.ts +5 -11
  157. package/dist/session/phase-completion.runtime.js +91 -215
  158. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  159. package/dist/session/phase-completion.schema-parts.js +188 -0
  160. package/dist/session/phase-completion.schemas.d.ts +3 -3
  161. package/dist/session/phase-completion.schemas.js +208 -231
  162. package/dist/session/phase-completion.validation.d.ts +2 -3
  163. package/dist/session/phase-completion.validation.js +49 -93
  164. package/dist/session/pre-publication-host-load.d.ts +27 -0
  165. package/dist/session/pre-publication-host-load.js +111 -0
  166. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  167. package/dist/session/pre-publication-native-postgres.js +111 -0
  168. package/dist/session/pre-publication-pass.d.ts +61 -0
  169. package/dist/session/pre-publication-pass.js +148 -0
  170. package/dist/session/pre-publication-process.d.ts +3 -0
  171. package/dist/session/pre-publication-process.js +31 -19
  172. package/dist/session/pre-publication-step-execution.d.ts +12 -0
  173. package/dist/session/pre-publication-step-execution.js +50 -0
  174. package/dist/session/pre-publication-validation.d.ts +37 -21
  175. package/dist/session/pre-publication-validation.js +221 -182
  176. package/dist/session/provider-cli/claude-background-work.d.ts +67 -0
  177. package/dist/session/provider-cli/claude-background-work.js +181 -0
  178. package/dist/session/provider-cli/host-build-lock.d.ts +18 -0
  179. package/dist/session/provider-cli/host-build-lock.js +30 -0
  180. package/dist/session/provider-cli/pre-publication-repair.d.ts +56 -0
  181. package/dist/session/provider-cli/pre-publication-repair.js +276 -0
  182. package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
  183. package/dist/session/provider-cli/provider-cli.child-environment.js +75 -0
  184. package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
  185. package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
  186. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +6 -3
  187. package/dist/session/provider-cli/provider-cli.merge-integrity.js +28 -8
  188. package/dist/session/provider-cli/provider-cli.process.d.ts +15 -36
  189. package/dist/session/provider-cli/provider-cli.process.js +41 -432
  190. package/dist/session/provider-cli/provider-cli.prompts.d.ts +5 -0
  191. package/dist/session/provider-cli/provider-cli.prompts.js +72 -32
  192. package/dist/session/provider-cli/provider-cli.runtime.d.ts +8 -0
  193. package/dist/session/provider-cli/provider-cli.runtime.js +29 -1
  194. package/dist/session/provider-cli/provider-cli.service.d.ts +7 -1
  195. package/dist/session/provider-cli/provider-cli.service.js +98 -173
  196. package/dist/session/provider-cli/provider-cli.types.d.ts +30 -0
  197. package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
  198. package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
  199. package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
  200. package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
  201. package/dist/session/provider-cli/provider-in-flight-work.d.ts +4 -0
  202. package/dist/session/provider-cli/provider-in-flight-work.js +45 -0
  203. package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
  204. package/dist/session/provider-cli/provider-output-pipes.js +67 -0
  205. package/dist/session/provider-cli/provider-output-state.d.ts +2 -0
  206. package/dist/session/provider-cli/provider-output-state.js +6 -0
  207. package/dist/session/provider-cli/provider-user-config-isolation.d.ts +69 -0
  208. package/dist/session/provider-cli/provider-user-config-isolation.js +164 -0
  209. package/dist/session/qa-sidecar-validation.d.ts +6 -0
  210. package/dist/session/qa-sidecar-validation.js +28 -0
  211. package/dist/session/sandbox-host-capacity-gate.d.ts +51 -0
  212. package/dist/session/sandbox-host-capacity-gate.js +257 -0
  213. package/dist/session/session-redaction.js +31 -181
  214. package/dist/session/session.base.d.ts +9 -1
  215. package/dist/session/session.service.d.ts +15 -2
  216. package/dist/session/session.service.js +246 -88
  217. package/dist/session/session.types.d.ts +4 -0
  218. package/dist/session/session.types.js +7 -7
  219. package/dist/session/sidecar-json-shape.d.ts +31 -0
  220. package/dist/session/sidecar-json-shape.js +217 -0
  221. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  222. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  223. package/dist/shared/fs/file-identity.d.ts +10 -0
  224. package/dist/shared/fs/file-identity.js +15 -0
  225. package/dist/shared/fs/replace-file.d.ts +7 -0
  226. package/dist/shared/fs/replace-file.js +33 -0
  227. package/dist/shared/process/host-process-recovery.d.ts +14 -3
  228. package/dist/shared/process/host-process-recovery.js +23 -3
  229. package/dist/shared/process/host-process-supervisor.d.ts +14 -1
  230. package/dist/shared/process/host-process-supervisor.js +67 -15
  231. package/dist/shared/process/process-tree.d.ts +52 -0
  232. package/dist/shared/process/process-tree.js +144 -0
  233. package/dist/shared/process/process.d.ts +67 -0
  234. package/dist/shared/process/process.js +213 -11
  235. package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
  236. package/dist/shared/process/windows-app-execution-alias.js +45 -0
  237. package/dist/shared/process/windows-launch.d.ts +18 -0
  238. package/dist/shared/process/windows-launch.js +68 -0
  239. package/dist/shared/provider-capabilities.js +14 -7
  240. package/dist/version.d.ts +1 -1
  241. package/dist/version.js +1 -1
  242. package/dist/worktree/dependency-warmer.d.ts +25 -0
  243. package/dist/worktree/dependency-warmer.js +46 -10
  244. package/dist/worktree/orphan-relink.d.ts +19 -0
  245. package/dist/worktree/orphan-relink.js +106 -0
  246. package/dist/worktree/wip-git.d.ts +42 -0
  247. package/dist/worktree/wip-git.js +139 -0
  248. package/dist/worktree/wip-refs.d.ts +77 -0
  249. package/dist/worktree/wip-refs.js +146 -0
  250. package/dist/worktree/wip-restore.d.ts +46 -0
  251. package/dist/worktree/wip-restore.js +280 -0
  252. package/dist/worktree/wip-snapshot.d.ts +53 -0
  253. package/dist/worktree/wip-snapshot.js +270 -0
  254. package/dist/worktree/worktree-inputs.d.ts +8 -0
  255. package/dist/worktree/worktree-inputs.js +134 -0
  256. package/dist/worktree/worktree-origin-sync.d.ts +35 -0
  257. package/dist/worktree/worktree-origin-sync.js +128 -0
  258. package/dist/worktree/worktree-wip-events.d.ts +18 -0
  259. package/dist/worktree/worktree-wip-events.js +115 -0
  260. package/dist/worktree/worktree-wip.d.ts +51 -0
  261. package/dist/worktree/worktree-wip.js +190 -0
  262. package/dist/worktree/worktree.base.d.ts +7 -1
  263. package/dist/worktree/worktree.service.d.ts +36 -5
  264. package/dist/worktree/worktree.service.js +126 -155
  265. package/dist/worktree/worktree.types.d.ts +42 -0
  266. package/package.json +2 -2
  267. package/runtime/windows-listener-owner.ps1 +12 -1
@@ -0,0 +1,190 @@
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, re-applying it with a 3-way merge
12
+ // when the branch has moved since (wip-restore.ts);
13
+ // - a checkout that lost only its `.git` link is reattached to Git's admin directory for it, which
14
+ // holds its index and MERGE_HEAD, instead of being recreated (orphan-relink.ts).
15
+ export { relinkOrphanedWorktree } from "./orphan-relink.js";
16
+ /** Lanes whose work the bridge publishes, and so whose snapshots a later pass may apply by itself. */
17
+ const restoreLanes = new Set(["develop", "debug", "conflict_resolve", "ci_repair"]);
18
+ function isWipRestoreLane(lane) {
19
+ return restoreLanes.has((lane ?? "").trim().toLowerCase());
20
+ }
21
+ /**
22
+ * Saves uncommitted work before `git reset --hard` / `git clean` on an existing worktree; a later
23
+ * pass may apply it by itself only when it came from a publishing lane.
24
+ * Throws when it could not be saved: losing work is worse than a failed prepare.
25
+ */
26
+ export async function guardWorktreeReset(worktreePath, branchName, owner) {
27
+ try {
28
+ return await preserveWorktreeWip({
29
+ worktreePath,
30
+ branchName,
31
+ reason: "pre_reset",
32
+ sessionId: owner.sessionId,
33
+ lane: owner.lane,
34
+ attempt: owner.wipAttempt,
35
+ autoRestore: isWipRestoreLane(owner.lane),
36
+ });
37
+ }
38
+ catch (error) {
39
+ 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 });
40
+ }
41
+ }
42
+ /**
43
+ * Before a local branch is re-pointed at a new start point (`worktree add -B`), saves any commits
44
+ * on it that neither the start point nor origin has, as a `forge.wip.v1` snapshot like any other:
45
+ * its tree is the tip's, its first parent the tip (so the commits are `<ref>^1` and its ancestors),
46
+ * and it is never applied automatically. Throws when they could not be saved.
47
+ */
48
+ export async function guardBranchReset(git, repoPath, branchName, startPoint) {
49
+ const tip = (await git.run(repoPath, ["rev-parse", "-q", "--verify", `refs/heads/${branchName}^{commit}`]).catch(() => "")).trim();
50
+ if (!tip)
51
+ return;
52
+ const onStartPoint = await git.run(repoPath, ["merge-base", "--is-ancestor", tip, startPoint]).then(() => true, () => false);
53
+ if (onStartPoint)
54
+ return;
55
+ const onOrigin = (await git.run(repoPath, ["branch", "-r", "--contains", tip]).catch(() => "")).trim().length > 0;
56
+ if (onOrigin)
57
+ return;
58
+ const now = new Date();
59
+ const ref = wipRefName(branchName, wipRefId("pre_branch_reset", null, now));
60
+ const origin = (await git.run(repoPath, ["remote", "get-url", "origin"]).catch(() => "")).trim();
61
+ try {
62
+ const snapshot = await branchTipSnapshot(repoPath, branchName, tip, now);
63
+ await git.run(repoPath, origin ? ["push", "--porcelain", "origin", `${snapshot}:${ref}`] : ["update-ref", ref, snapshot]);
64
+ }
65
+ catch (error) {
66
+ 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 });
67
+ }
68
+ }
69
+ /** A snapshot commit holding a branch tip: nothing uncommitted, so its tree and index are the tip's. */
70
+ async function branchTipSnapshot(repoPath, branchName, tip, now) {
71
+ const git = new WipGit();
72
+ const tree = (await git.run(repoPath, ["rev-parse", `${tip}^{tree}`])).trim();
73
+ const indexCommit = (await git.run(repoPath, ["commit-tree", tree, "-p", tip, "-m", "forge wip index snapshot"])).trim();
74
+ const message = formatWipCommitMessage({
75
+ schema: wipMetadataSchema,
76
+ branch: branchName,
77
+ baseHead: tip,
78
+ sessionId: null,
79
+ lane: null,
80
+ reason: "pre_branch_reset",
81
+ attempt: unorderedWipAttempt,
82
+ autoRestore: false,
83
+ createdAt: now.toISOString(),
84
+ createdAtMs: now.getTime(),
85
+ mergeHead: null,
86
+ mergeMessage: null,
87
+ mergeMode: null,
88
+ unmerged: [],
89
+ reapplyConflicts: [],
90
+ changedPaths: 0,
91
+ bytes: 0,
92
+ });
93
+ return (await git.run(repoPath, ["commit-tree", tree, "-p", tip, "-p", indexCommit, "-m", message])).trim();
94
+ }
95
+ /** Puts the newest restorable snapshot back on a freshly prepared worktree of a publishing lane. */
96
+ export async function restoreWorktreeWip(input) {
97
+ if (!input.sessionId || !isWipRestoreLane(input.lane))
98
+ return undefined;
99
+ return await restoreLatestWip(input);
100
+ }
101
+ /**
102
+ * Saves a worktree that is about to be deleted. Its snapshot is never applied automatically (a
103
+ * session that ended without succeeding has already saved its own work under its id; what is
104
+ * left after a successful pass was deliberately not published). Throws when it could not be saved.
105
+ */
106
+ export async function guardWorktreeRelease(handle) {
107
+ // A readiness probe never runs an agent; its checkout only ever holds the app's own output.
108
+ if (isRuntimeReadinessBranch(handle.branchName))
109
+ return { status: "clean" };
110
+ return await preserveWorktreeWip({
111
+ worktreePath: handle.worktreePath,
112
+ branchName: handle.branchName,
113
+ reason: "pre_release",
114
+ sessionId: handle.sessionId,
115
+ lane: handle.lane,
116
+ attempt: handle.wipAttempt,
117
+ autoRestore: false,
118
+ });
119
+ }
120
+ /** Forgets what this process saved for a worktree once it is gone. */
121
+ export function worktreeReleased(handle) {
122
+ forgetPreservedWip(handle.worktreePath);
123
+ }
124
+ /**
125
+ * At the end of a session: saves its uncommitted work unless it succeeded, and deletes the
126
+ * snapshot it started from once that work is safe elsewhere: saved again here, or (after a
127
+ * success) published, which is only certain when nothing is left uncommitted. Leftovers keep the
128
+ * ref; the release's own snapshot of them is never applied automatically.
129
+ * Never throws; a failure is reported in the result.
130
+ */
131
+ export async function settleSessionWip(handle, outcome) {
132
+ let snapshot;
133
+ if (outcome.reason) {
134
+ try {
135
+ snapshot = await preserveWorktreeWip({
136
+ worktreePath: handle.worktreePath,
137
+ branchName: handle.branchName,
138
+ reason: outcome.reason,
139
+ sessionId: handle.sessionId,
140
+ lane: handle.lane,
141
+ attempt: handle.wipAttempt,
142
+ autoRestore: isWipRestoreLane(handle.lane),
143
+ });
144
+ }
145
+ catch (error) {
146
+ return {
147
+ error: {
148
+ code: error instanceof WipPreservationError ? error.code : "wip_snapshot_failed",
149
+ message: errorMessage(error),
150
+ },
151
+ };
152
+ }
153
+ }
154
+ const restored = handle.wipRestore?.status === "restored" ? handle.wipRestore.ref : null;
155
+ // A failed session that left a clean worktree may have thrown the restored work away; keep its ref.
156
+ const supersededBy = snapshot && snapshot.status !== "clean" ? snapshot.ref : null;
157
+ const safeElsewhere = outcome.reason === null
158
+ ? await hasNoUnsavedWork(handle.worktreePath).catch(() => false)
159
+ : Boolean(supersededBy && supersededBy !== restored);
160
+ const retire = restored && safeElsewhere ? restored : null;
161
+ if (retire)
162
+ forgetPreservedWipRef(retire);
163
+ const retiredRef = retire && await deleteWipRef(handle.repoPath, retire) ? retire : null;
164
+ return { ...(snapshot ? { snapshot } : {}), retiredRef };
165
+ }
166
+ /**
167
+ * After a release: deletes the readiness probe's branch, and other Forge branches whose work is
168
+ * already on the base. Branches of live leases are kept; when the ledger can't be read, nothing is.
169
+ */
170
+ export async function sweepBranchesAfterRelease(git, handle, leaseStateRoot, limit) {
171
+ const protectedBranches = await readHostRuntimeLeases(leaseStateRoot)
172
+ .then(liveLeaseBranches)
173
+ .catch(() => null);
174
+ if (!protectedBranches)
175
+ return;
176
+ let budget = limit;
177
+ if (isRuntimeReadinessBranch(handle.branchName) && !protectedBranches.has(handle.branchName)
178
+ && await deleteBranchIfUnused(git, handle.repoPath, handle.branchName)) {
179
+ budget -= 1;
180
+ }
181
+ await sweepManagedBranches(git, handle.repoPath, {
182
+ baseBranch: handle.baseBranch,
183
+ includeMergedWorkBranches: true,
184
+ protectedBranches,
185
+ limit: budget,
186
+ }).catch(() => undefined);
187
+ }
188
+ function errorMessage(error) {
189
+ return error instanceof Error ? error.message : String(error);
190
+ }
@@ -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 {};
@@ -4,17 +4,34 @@ import path from "node:path";
4
4
  import { RepositoryCoordinatorLock } from "../sandbox/repository-lock.js";
5
5
  import { GitClient } from "../shared/git/git.js";
6
6
  import { ensureDirectory, isSubPath, resolveExistingDirectoryPath, safeSegment } from "../shared/path/path.js";
7
- import { filterArtifactsForLane, injectWorktreeArtifacts } from "./artifact-injector.js";
8
- import { hydratePriorPhaseArtifacts } from "./prior-phase-artifact-hydrator.js";
9
- import { materializeStoryQaReferences } from "./story-qa-reference-hydrator.js";
10
7
  import { warmWorktreeDependencies } from "./dependency-warmer.js";
8
+ import { materializeWorktreeInputs } from "./worktree-inputs.js";
9
+ import { guardBranchReset, guardWorktreeRelease, guardWorktreeReset, relinkOrphanedWorktree, restoreWorktreeWip, settleSessionWip, sweepBranchesAfterRelease, worktreeReleased, } from "./worktree-wip.js";
11
10
  import { defaultWorktreeCoordinatorStateRoot, managedRepoRoot, resolveManagedWorktreeRoot, } from "./worktree-paths.js";
11
+ import { describeNewWorktreeStart, refuseStaleFallbackAfterFetchFailure, syncReusedWorktreeToOrigin, writeBridgeLog, } from "./worktree-origin-sync.js";
12
+ export { emitWipRestoreEvent, sessionWipOutcome, settleWorktree } from "./worktree-wip-events.js";
13
+ export { emitWorktreePreparedEvents } from "./worktree-origin-sync.js";
14
+ export { clearRunArtifactRoots } from "./worktree-inputs.js";
15
+ // Bounds the branch sweep that runs after each release, so one release never holds the repository lock long.
16
+ const releaseSweepLimit = 25;
12
17
  export class GitWorktreeService {
13
18
  git;
14
19
  coordinator;
15
- constructor(git = new GitClient(), coordinator = new RepositoryCoordinatorLock(defaultWorktreeCoordinatorStateRoot())) {
20
+ hostLoadGate;
21
+ leaseStateRoot;
22
+ log;
23
+ constructor(git = new GitClient(), coordinator = new RepositoryCoordinatorLock(defaultWorktreeCoordinatorStateRoot()),
24
+ /** Gates dependency install fallbacks; inert unless the governor is on. */
25
+ hostLoadGate,
26
+ /** Holds the host runtime lease ledger; branches of live leases are never swept on release. */
27
+ leaseStateRoot = defaultWorktreeCoordinatorStateRoot(),
28
+ /** The bridge log: prepare records its start point and what it did to a reused worktree. */
29
+ log = writeBridgeLog) {
16
30
  this.git = git;
17
31
  this.coordinator = coordinator;
32
+ this.hostLoadGate = hostLoadGate;
33
+ this.leaseStateRoot = leaseStateRoot;
34
+ this.log = log;
18
35
  }
19
36
  async prepare(request) {
20
37
  const allowedRoot = await ensureDirectory(request.allowedRepoRoot);
@@ -29,9 +46,9 @@ export class GitWorktreeService {
29
46
  const repoPath = await this.coordinator.withLock(creationCoordinationPath, async () => {
30
47
  return await this.resolveRepoPath(request.repo, allowedRoot, baseBranch);
31
48
  });
32
- const resolvedWorktreePath = await this.coordinator.withLock(repoPath, async () => {
49
+ const { worktreePath: resolvedWorktreePath, ...preparedState } = await this.coordinator.withLock(repoPath, async () => {
33
50
  await this.ensureGitIdentity(repoPath);
34
- const baseStartPoint = await this.resolveBaseStartPoint(repoPath, baseBranch);
51
+ const baseStartPoint = await this.resolveBaseStartPoint(repoPath, baseBranch, branchName);
35
52
  const worktreeRoot = resolveManagedWorktreeRoot(allowedRoot, repoPath);
36
53
  const worktreePath = path.join(worktreeRoot, ...worktreeSegments);
37
54
  const resolvedWorktreeParent = await ensureDirectory(path.dirname(worktreePath));
@@ -46,17 +63,8 @@ export class GitWorktreeService {
46
63
  await this.git.run(repoPath, ["worktree", "prune", "--expire", "now"]);
47
64
  const registeredWorktreePath = await this.registeredManagedWorktreePath(repoPath, branchName, allowedRoot, worktreeSegments);
48
65
  if (!registeredWorktreePath) {
49
- const branchRef = `refs/heads/${branchName}`;
50
- if (request.preserveExistingState && await this.gitRefExists(repoPath, branchRef)) {
51
- // The checkout directory can disappear while its branch still
52
- // contains completed agent work. Reattach that branch verbatim;
53
- // `-B ... baseStartPoint` would silently reset it and lose progress.
54
- await this.git.run(repoPath, ["worktree", "add", worktreePath, branchName]);
55
- }
56
- else {
57
- await this.git.run(repoPath, ["worktree", "add", "-B", branchName, worktreePath, baseStartPoint]);
58
- }
59
- return await resolveExistingDirectoryPath(worktreePath);
66
+ const originSync = await this.addWorktree(request, repoPath, branchName, worktreePath, baseStartPoint);
67
+ return await this.withRestoredWip(request, repoPath, branchName, await resolveExistingDirectoryPath(worktreePath), originSync);
60
68
  }
61
69
  // The selected checkout can change when a Bridge reconnects or a local
62
70
  // runner takes over. Its managed root therefore changes even though the
@@ -81,30 +89,11 @@ export class GitWorktreeService {
81
89
  if (currentBranch !== branchName) {
82
90
  throw new Error(`Existing worktree ${existingWorktreePath} is on branch '${currentBranch}', expected '${branchName}'.`);
83
91
  }
84
- if (!request.preserveExistingState && shouldResetExistingWorktree(request)) {
85
- await this.resetWorktreeToBase(existingWorktreePath, baseStartPoint);
86
- }
87
- return existingWorktreePath;
92
+ const originSync = await this.refreshReusedWorktree(request, existingWorktreePath, branchName, baseStartPoint);
93
+ return await this.withRestoredWip(request, repoPath, branchName, existingWorktreePath, originSync);
88
94
  });
89
- // Reference inputs and an exact-tree local repair checkpoint must survive output cleanup.
90
- await materializeStoryQaReferences(resolvedWorktreePath, request, this.git);
91
- if (!request.preserveExistingState) {
92
- await clearRunArtifactRoots(resolvedWorktreePath, request);
93
- }
94
- const hydratedPriorPhaseArtifactCount = await hydratePriorPhaseArtifacts(resolvedWorktreePath, request.priorPhaseArtifacts);
95
- const qaReworkPacketPath = await materializeQaReworkPacket(resolvedWorktreePath, request);
96
- const artifacts = filterArtifactsForLane(request.artifacts, request.lane, request.phase);
97
- if (artifacts.length > 0) {
98
- await injectWorktreeArtifacts(resolvedWorktreePath, artifacts, await this.trackedForgePaths(resolvedWorktreePath));
99
- }
100
- const dependencyWarm = requiresMutableEnvironmentPreparation(request)
101
- ? await warmWorktreeDependencies({
102
- baseCheckoutPath: repoPath,
103
- worktreePath: resolvedWorktreePath,
104
- allowedRoot,
105
- warmPathOverrides: request.warmPathOverrides
106
- })
107
- : undefined;
95
+ const { hydratedPriorPhaseArtifactCount, qaReworkPacketPath } = await materializeWorktreeInputs(resolvedWorktreePath, request, this.git);
96
+ const dependencyWarm = await this.warmDependencies(request, repoPath, resolvedWorktreePath, allowedRoot);
108
97
  return {
109
98
  repoPath,
110
99
  worktreePath: resolvedWorktreePath,
@@ -113,12 +102,79 @@ export class GitWorktreeService {
113
102
  cleanupWorktrees: request.cleanupWorktrees,
114
103
  dependencyWarm,
115
104
  qaReworkPacketPath,
116
- hydratedPriorPhaseArtifactCount
105
+ hydratedPriorPhaseArtifactCount,
106
+ sessionId: request.sessionId ?? null,
107
+ lane: request.lane,
108
+ wipAttempt: request.wipAttempt ?? null,
109
+ ...preparedState,
117
110
  };
118
111
  }
119
- async trackedForgePaths(worktreePath) {
120
- const output = await this.git.run(worktreePath, ["ls-files", "-z", "--", ".forge"]);
121
- return new Set(output.split("\0").filter(Boolean).map(value => value.replaceAll("\\", "/")));
112
+ async warmDependencies(request, repoPath, worktreePath, allowedRoot) {
113
+ if (!requiresMutableEnvironmentPreparation(request))
114
+ return undefined;
115
+ return await warmWorktreeDependencies({
116
+ baseCheckoutPath: repoPath,
117
+ worktreePath,
118
+ allowedRoot,
119
+ warmPathOverrides: request.warmPathOverrides,
120
+ hostLoad: this.hostLoadGate?.enabled
121
+ ? {
122
+ gate: this.hostLoadGate,
123
+ dispatchAttemptId: request.hostLoadOwner?.dispatchAttemptId ?? null,
124
+ priority: request.hostLoadOwner?.priority ?? "foreground",
125
+ }
126
+ : undefined,
127
+ signal: request.signal,
128
+ });
129
+ }
130
+ /** Restores the story's saved WIP (still under the repository lock, before the provider starts). */
131
+ async withRestoredWip(request, repoPath, branchName, worktreePath, originSync) {
132
+ const wipRestore = await restoreWorktreeWip({ worktreePath, repoPath, branchName, sessionId: request.sessionId, lane: request.lane });
133
+ return { worktreePath, ...(wipRestore ? { wipRestore } : {}), ...(originSync ? { originSync } : {}) };
134
+ }
135
+ /** Creates the lease's worktree; see describeNewWorktreeStart for what it reports. */
136
+ async addWorktree(request, repoPath, branchName, worktreePath, baseStartPoint) {
137
+ if (request.preserveExistingState && await this.gitRefExists(repoPath, `refs/heads/${branchName}`)) {
138
+ // The checkout directory can disappear while its branch still
139
+ // contains completed agent work. Reattach that branch verbatim;
140
+ // `-B ... baseStartPoint` would silently reset it and lose progress.
141
+ this.log(`Worktree prepare: reattaching '${branchName}' verbatim at ${worktreePath} for a resumed session.`);
142
+ await this.git.run(repoPath, ["worktree", "add", worktreePath, branchName]);
143
+ return undefined;
144
+ }
145
+ const originSync = await describeNewWorktreeStart(this.git, repoPath, branchName, baseStartPoint, this.log);
146
+ await guardBranchReset(this.git, repoPath, branchName, baseStartPoint);
147
+ await this.git.run(repoPath, ["worktree", "add", "-B", branchName, worktreePath, baseStartPoint]);
148
+ return originSync;
149
+ }
150
+ /**
151
+ * Readies a surviving worktree for this pass: lanes that start from their base are reset to it;
152
+ * the others keep their state but are brought up to origin's head when only behind it
153
+ * (worktree-origin-sync.ts). A resumed session keeps its worktree exactly as it was.
154
+ */
155
+ async refreshReusedWorktree(request, worktreePath, branchName, baseStartPoint) {
156
+ if (request.preserveExistingState) {
157
+ this.log(`Worktree prepare: reattaching ${worktreePath} on '${branchName}' unchanged for a resumed session.`);
158
+ return undefined;
159
+ }
160
+ if (shouldResetExistingWorktree(request)) {
161
+ await guardWorktreeReset(worktreePath, branchName, request);
162
+ await this.resetWorktreeToBase(worktreePath, baseStartPoint);
163
+ this.log(`Worktree prepare: reset reused worktree ${worktreePath} on '${branchName}' to ${baseStartPoint}.`);
164
+ return undefined;
165
+ }
166
+ return await syncReusedWorktreeToOrigin({
167
+ git: this.git,
168
+ worktreePath,
169
+ branchName,
170
+ sessionId: request.sessionId,
171
+ lane: request.lane,
172
+ wipAttempt: request.wipAttempt,
173
+ log: this.log,
174
+ });
175
+ }
176
+ async settleWip(handle, outcome) {
177
+ return await settleSessionWip(handle, outcome);
122
178
  }
123
179
  async registeredManagedWorktreePath(repoPath, branchName, allowedRoot, worktreeSegments) {
124
180
  const listing = await this.git.run(repoPath, ["worktree", "list", "--porcelain", "-z"]);
@@ -145,6 +201,8 @@ export class GitWorktreeService {
145
201
  }
146
202
  await this.coordinator.withLock(handle.repoPath, async () => {
147
203
  if (await directoryExists(handle.worktreePath)) {
204
+ // Never delete work that could not be saved: this throws and keeps the worktree.
205
+ await guardWorktreeRelease(handle);
148
206
  // On Windows, `git worktree remove` can delete the `.git` link and then
149
207
  // fail on a locked build output. That leaves a full source tree which is
150
208
  // no longer a Git worktree and makes every retry fail during prepare.
@@ -164,6 +222,12 @@ export class GitWorktreeService {
164
222
  // directory is fully materialized (or after an external cleanup removes it).
165
223
  // Always prune so those missing-directory registrations do not accumulate.
166
224
  await this.git.run(handle.repoPath, ["worktree", "prune", "--expire", "now"]).catch(() => undefined);
225
+ worktreeReleased(handle);
226
+ // A readiness probe's branch goes with its worktree. Other Forge branches on this device
227
+ // whose work is already merged into the base go too; branches with unmerged work stay.
228
+ // A lease can be live while its worktree is briefly missing, so its branch is protected
229
+ // even when no worktree has it checked out. If the ledger can't be read, sweep nothing.
230
+ await sweepBranchesAfterRelease(this.git, handle, this.leaseStateRoot, releaseSweepLimit);
167
231
  });
168
232
  }
169
233
  async restoreOrphanedWorktree(input) {
@@ -171,10 +235,15 @@ export class GitWorktreeService {
171
235
  if (orphanStat.isSymbolicLink() || !orphanStat.isDirectory()) {
172
236
  throw new Error(`Refusing to recover redirected or non-directory worktree ${input.worktreePath}.`);
173
237
  }
238
+ // Git still has this checkout's admin directory (its index and MERGE_HEAD): point the checkout
239
+ // back at it rather than recreating the checkout, which would prune it.
240
+ if (await relinkOrphanedWorktree(this.git, input))
241
+ return;
174
242
  const quarantinePath = `${input.worktreePath}.forge-orphan-${randomUUID()}`;
175
243
  if (!isSubPath(input.allowedRoot, quarantinePath)) {
176
244
  throw new Error(`Worktree recovery path must stay under ${input.allowedRoot}.`);
177
245
  }
246
+ await guardBranchReset(this.git, input.repoPath, input.branchName, input.baseStartPoint);
178
247
  await fs.rename(input.worktreePath, quarantinePath);
179
248
  try {
180
249
  await this.git.run(input.repoPath, ["worktree", "prune", "--expire", "now"]);
@@ -285,7 +354,12 @@ export class GitWorktreeService {
285
354
  const resolved = await resolveExistingDirectoryPath(candidate);
286
355
  return isSubPath(allowedRoot, resolved) ? resolved : null;
287
356
  }
288
- async resolveBaseStartPoint(repoPath, baseBranch) {
357
+ /**
358
+ * The start point for the lease's base: origin's freshly fetched head when origin has the
359
+ * branch, else the local branch. When the fetch fails, the local branch is used only if origin
360
+ * has never had the base or the lease branch: otherwise the worktree could run on stale code.
361
+ */
362
+ async resolveBaseStartPoint(repoPath, baseBranch, branchName) {
289
363
  if (baseBranch === "HEAD") {
290
364
  const head = (await this.git.run(repoPath, ["rev-parse", "--verify", "HEAD^{commit}"])).trim();
291
365
  if (!/^[0-9a-f]{40,64}$/iu.test(head)) {
@@ -297,14 +371,17 @@ export class GitWorktreeService {
297
371
  const remoteRef = `refs/remotes/origin/${baseBranch}`;
298
372
  const origin = await this.git.run(repoPath, ["remote", "get-url", "origin"]).catch(() => "");
299
373
  if (origin.trim().length > 0) {
300
- const fetched = await this.git.run(repoPath, ["fetch", "--prune", "origin"])
301
- .then(() => true)
302
- .catch(() => false);
303
- if (fetched && await this.gitRefExists(repoPath, remoteRef)) {
374
+ const fetchError = await this.git.run(repoPath, ["fetch", "--prune", "origin"]).then(() => null, (error) => error ?? "fetch failed");
375
+ if (fetchError) {
376
+ await refuseStaleFallbackAfterFetchFailure(this.git, repoPath, [baseBranch, branchName], fetchError, this.log);
377
+ }
378
+ else if (await this.gitRefExists(repoPath, remoteRef)) {
379
+ this.log(`Worktree prepare: fetched origin in ${repoPath}; '${baseBranch}' starts from ${remoteRef}.`);
304
380
  return remoteRef;
305
381
  }
306
382
  }
307
383
  if (await this.gitRefExists(repoPath, localRef)) {
384
+ this.log(`Worktree prepare: '${baseBranch}' starts from the local ${localRef} in ${repoPath} (origin has no such branch).`);
308
385
  return localRef;
309
386
  }
310
387
  throw new Error(`Base branch '${baseBranch}' was not found locally or on origin.`);
@@ -357,72 +434,6 @@ function isCloneableRemote(remoteUrl) {
357
434
  }
358
435
  return trimmed.startsWith("git@") || trimmed.includes("://") || path.isAbsolute(trimmed);
359
436
  }
360
- export async function clearRunArtifactRoots(worktreePath, request) {
361
- const roots = new Set();
362
- roots.add(workItemArtifactRoot(worktreePath, request.workItem.id));
363
- for (const artifact of request.priorPhaseArtifacts ?? []) {
364
- roots.add(workItemArtifactRoot(worktreePath, artifact.workItemId));
365
- }
366
- const ownerType = normalizeOwnerType(request.ownerType);
367
- const ownerId = request.ownerId?.trim();
368
- if (ownerType && ownerId) {
369
- roots.add(ownerArtifactRoot(worktreePath, ownerType, ownerId));
370
- }
371
- for (const root of roots) {
372
- const resolvedRoot = path.resolve(root);
373
- if (!isSubPath(worktreePath, resolvedRoot)) {
374
- throw new Error(`Artifact root must stay under ${worktreePath}.`);
375
- }
376
- await ensureNoSymlinkPathSegments(worktreePath, resolvedRoot, "Artifact root must not traverse symlinked path segments.");
377
- await fs.rm(resolvedRoot, { recursive: true, force: true });
378
- await fs.mkdir(resolvedRoot, { recursive: true });
379
- }
380
- }
381
- async function materializeQaReworkPacket(worktreePath, request) {
382
- const qaRework = request.qaRework;
383
- if (!qaRework) {
384
- return undefined;
385
- }
386
- const artifactRoot = artifactRootForRequest(worktreePath, request);
387
- const packetFileName = qaReworkPacketFileName(qaRework.packetPath);
388
- const packetPath = path.join(artifactRoot, packetFileName);
389
- const paths = new Set([packetPath, path.join(artifactRoot, "qa-rework-packet.json")]);
390
- const packetJson = qaRework.packetJson.endsWith("\n") ? qaRework.packetJson : `${qaRework.packetJson}\n`;
391
- for (const target of paths) {
392
- const resolvedTarget = path.resolve(target);
393
- if (!isSubPath(worktreePath, resolvedTarget)) {
394
- throw new Error(`QA rework packet path must stay under ${worktreePath}.`);
395
- }
396
- await ensureNoSymlinkPathSegments(worktreePath, path.dirname(resolvedTarget), "QA rework packet path must not traverse symlinked path segments.");
397
- await fs.mkdir(path.dirname(resolvedTarget), { recursive: true });
398
- await fs.writeFile(resolvedTarget, packetJson, "utf8");
399
- }
400
- return path.resolve(packetPath);
401
- }
402
- function artifactRootForRequest(worktreePath, request) {
403
- const ownerType = normalizeOwnerType(request.ownerType);
404
- const ownerId = request.ownerId?.trim();
405
- if (ownerType && ownerId) {
406
- return ownerArtifactRoot(worktreePath, ownerType, ownerId);
407
- }
408
- return workItemArtifactRoot(worktreePath, request.workItem.id);
409
- }
410
- function workItemArtifactRoot(worktreePath, workItemId) {
411
- return path.join(worktreePath, ".forge", "work-items", safeSegment(workItemId, "work item id"), "artifacts");
412
- }
413
- function ownerArtifactRoot(worktreePath, ownerType, ownerId) {
414
- return path.join(worktreePath, ".forge", ownerType === "story" ? "stories" : "work-items", safeSegment(ownerId, "owner id"), "artifacts");
415
- }
416
- function normalizeOwnerType(value) {
417
- const normalized = (value ?? "").trim().toLowerCase().replace(/-/g, "_");
418
- if (normalized === "story") {
419
- return "story";
420
- }
421
- if (normalized === "work_item" || normalized === "workitem" || normalized === "work item") {
422
- return "work_item";
423
- }
424
- return null;
425
- }
426
437
  function shouldResetExistingWorktree(request) {
427
438
  const lane = request.lane.trim().toLowerCase();
428
439
  const phase = request.phase.trim().toLowerCase().replace(/-/g, "_");
@@ -549,13 +560,6 @@ async function overlayEntry(input) {
549
560
  backupPath: preservedBasePath,
550
561
  });
551
562
  }
552
- function qaReworkPacketFileName(packetPath) {
553
- const normalized = packetPath.trim().replace(/\\/g, "/");
554
- const fileName = normalized.split("/").filter(Boolean).at(-1) ?? "";
555
- return /^qa-rework-packet(?:\.attempt-\d+)?\.json$/i.test(fileName)
556
- ? fileName
557
- : "qa-rework-packet.json";
558
- }
559
563
  export function normalizeBranchName(value, fallback) {
560
564
  const branch = (value?.trim() || fallback).trim();
561
565
  if (branch.length === 0 ||
@@ -605,39 +609,6 @@ async function gitMetadataExists(repoPath, allowedRoot) {
605
609
  const resolvedGitDir = await resolveExistingDirectoryPath(gitDirPath);
606
610
  return isSubPath(allowedRoot, resolvedGitDir);
607
611
  }
608
- async function ensureNoSymlinkPathSegments(root, targetPath, errorMessage) {
609
- const resolvedRoot = path.resolve(root);
610
- const resolvedTarget = path.resolve(targetPath);
611
- const relative = path.relative(resolvedRoot, resolvedTarget);
612
- if (relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {
613
- throw new Error(errorMessage);
614
- }
615
- let current = resolvedRoot;
616
- const rootStat = await fs.lstat(current);
617
- if (rootStat.isSymbolicLink()) {
618
- throw new Error(errorMessage);
619
- }
620
- if (!relative) {
621
- return;
622
- }
623
- for (const segment of relative.split(path.sep)) {
624
- if (!segment) {
625
- continue;
626
- }
627
- current = path.join(current, segment);
628
- const stat = await fs.lstat(current).catch((error) => {
629
- if (error.code === "ENOENT")
630
- return null;
631
- throw error;
632
- });
633
- if (!stat) {
634
- return;
635
- }
636
- if (stat.isSymbolicLink()) {
637
- throw new Error(errorMessage);
638
- }
639
- }
640
- }
641
612
  async function pathExists(inputPath) {
642
613
  return fs.stat(inputPath).then(() => true).catch(() => false);
643
614
  }