@loucompanion/forge-bridge 0.1.4-dev.8901ba056f68 → 0.1.4-dev.91ee995ac965

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 (210) hide show
  1. package/README.md +142 -1
  2. package/dist/bridge/bridge-chat-provider-command.d.ts +19 -0
  3. package/dist/bridge/bridge-chat-provider-command.js +132 -0
  4. package/dist/bridge/bridge-chat.types.d.ts +10 -0
  5. package/dist/bridge/bridge-chat.types.js +16 -1
  6. package/dist/bridge/bridge-state-file.d.ts +161 -0
  7. package/dist/bridge/bridge-state-file.js +376 -0
  8. package/dist/bridge/bridge-state-io.d.ts +11 -0
  9. package/dist/bridge/bridge-state-io.js +50 -0
  10. package/dist/bridge/bridge-state-lock.d.ts +11 -0
  11. package/dist/bridge/bridge-state-lock.js +102 -0
  12. package/dist/bridge/bridge-state-unpublished.d.ts +17 -0
  13. package/dist/bridge/bridge-state-unpublished.js +111 -0
  14. package/dist/bridge/bridge.base.d.ts +9 -0
  15. package/dist/bridge/bridge.service.d.ts +87 -14
  16. package/dist/bridge/bridge.service.js +394 -338
  17. package/dist/bridge/bridge.types.d.ts +16 -0
  18. package/dist/bridge/in-flight-registry.d.ts +62 -0
  19. package/dist/bridge/in-flight-registry.js +207 -0
  20. package/dist/bridge/local-yield-flag.d.ts +6 -0
  21. package/dist/bridge/local-yield-flag.js +34 -0
  22. package/dist/bridge/readiness-result-outbox.d.ts +5 -1
  23. package/dist/bridge/readiness-result-outbox.js +20 -0
  24. package/dist/bridge/runner-host-capabilities.d.ts +3 -0
  25. package/dist/bridge/runner-host-capabilities.js +13 -0
  26. package/dist/bridge/sandbox-resource-accounting.d.ts +16 -0
  27. package/dist/bridge/sandbox-resource-accounting.js +150 -0
  28. package/dist/cleanup/cleanup-wip.d.ts +12 -0
  29. package/dist/cleanup/cleanup-wip.js +66 -0
  30. package/dist/cleanup/cleanup.service.d.ts +20 -1
  31. package/dist/cleanup/cleanup.service.js +154 -153
  32. package/dist/cleanup/cleanup.types.d.ts +6 -0
  33. package/dist/cleanup/forge-owned-paths.d.ts +9 -0
  34. package/dist/cleanup/forge-owned-paths.js +53 -0
  35. package/dist/cleanup/host-runtime-ledger.d.ts +5 -0
  36. package/dist/cleanup/host-runtime-ledger.js +109 -0
  37. package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
  38. package/dist/cleanup/managed-branch-sweep.js +111 -0
  39. package/dist/cli/cli.help.js +74 -12
  40. package/dist/cli/cli.service.d.ts +19 -10
  41. package/dist/cli/cli.service.js +149 -186
  42. package/dist/cli/idle-status.d.ts +84 -0
  43. package/dist/cli/idle-status.js +181 -0
  44. package/dist/cli/local-config.d.ts +6 -0
  45. package/dist/cli/local-config.js +32 -4
  46. package/dist/cli/provider-cli-detection.d.ts +10 -0
  47. package/dist/cli/provider-cli-detection.js +160 -0
  48. package/dist/runtime/aspnet-runtime-prebuild.d.ts +5 -0
  49. package/dist/runtime/aspnet-runtime-prebuild.js +140 -7
  50. package/dist/runtime/attempt-database-broker.d.ts +1 -1
  51. package/dist/runtime/docker-engine-probe.d.ts +5 -0
  52. package/dist/runtime/docker-engine-probe.js +7 -0
  53. package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
  54. package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
  55. package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
  56. package/dist/runtime/ephemeral-test-postgres.js +303 -0
  57. package/dist/runtime/host-facts.d.ts +2 -1
  58. package/dist/runtime/host-load-admission.d.ts +18 -3
  59. package/dist/runtime/host-load-admission.js +19 -4
  60. package/dist/runtime/host-load-child-environment.d.ts +11 -6
  61. package/dist/runtime/host-load-child-environment.js +22 -11
  62. package/dist/runtime/host-load-governor-config.d.ts +19 -1
  63. package/dist/runtime/host-load-governor-config.js +37 -0
  64. package/dist/runtime/host-load-governor.d.ts +14 -0
  65. package/dist/runtime/host-load-governor.js +139 -26
  66. package/dist/runtime/host-load-ledger-lock.js +6 -4
  67. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  68. package/dist/runtime/host-load-runtime-settings.js +80 -0
  69. package/dist/runtime/host-load-sampler.d.ts +34 -4
  70. package/dist/runtime/host-load-sampler.js +73 -7
  71. package/dist/runtime/host-load-step-class.d.ts +3 -1
  72. package/dist/runtime/host-load-step-class.js +60 -5
  73. package/dist/runtime/host-load-test-slot.d.ts +43 -0
  74. package/dist/runtime/host-load-test-slot.js +81 -0
  75. package/dist/runtime/host-load-token-ledger.d.ts +26 -0
  76. package/dist/runtime/host-load-token-ledger.js +93 -61
  77. package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
  78. package/dist/runtime/host-load-windows-cpu.js +85 -0
  79. package/dist/runtime/host-runtime-contract.d.ts +12 -0
  80. package/dist/runtime/host-runtime-contract.js +29 -1
  81. package/dist/runtime/host-runtime-lease.d.ts +59 -3
  82. package/dist/runtime/host-runtime-lease.js +209 -58
  83. package/dist/runtime/host-runtime-promotion.d.ts +23 -0
  84. package/dist/runtime/host-runtime-promotion.js +36 -0
  85. package/dist/runtime/managed-command-teardown.js +5 -16
  86. package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
  87. package/dist/runtime/native-test-postgres-fallback.js +60 -8
  88. package/dist/runtime/playwright-host-runtime-adapter.d.ts +7 -0
  89. package/dist/runtime/playwright-host-runtime-adapter.js +13 -1
  90. package/dist/runtime/runner-settings.d.ts +104 -0
  91. package/dist/runtime/runner-settings.js +236 -0
  92. package/dist/sandbox/host-capacity-broker.d.ts +10 -2
  93. package/dist/sandbox/host-capacity-broker.js +27 -6
  94. package/dist/sandbox/managed-branch.d.ts +13 -0
  95. package/dist/sandbox/managed-branch.js +36 -0
  96. package/dist/sandbox/provider-auth/codex.js +11 -11
  97. package/dist/sandbox/runtime.js +2 -6
  98. package/dist/session/architect-waits.d.ts +2 -0
  99. package/dist/session/architect-waits.js +138 -0
  100. package/dist/session/managed-attempt-tools.d.ts +2 -7
  101. package/dist/session/managed-attempt-tools.js +89 -99
  102. package/dist/session/managed-build-receipt.d.ts +5 -0
  103. package/dist/session/managed-build-receipt.js +8 -3
  104. package/dist/session/managed-command-host-load.d.ts +2 -0
  105. package/dist/session/managed-command-host-load.js +2 -1
  106. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  107. package/dist/session/mcp-argument-coercion.js +121 -0
  108. package/dist/session/phase-completion.artifacts.d.ts +7 -0
  109. package/dist/session/phase-completion.artifacts.js +96 -26
  110. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  111. package/dist/session/phase-completion.command-validation.js +77 -0
  112. package/dist/session/phase-completion.d.ts +10 -0
  113. package/dist/session/phase-completion.helpers.js +13 -12
  114. package/dist/session/phase-completion.js +5 -0
  115. package/dist/session/phase-completion.mcp-args.d.ts +9 -0
  116. package/dist/session/phase-completion.mcp-args.js +156 -0
  117. package/dist/session/phase-completion.prompts.js +6 -1
  118. package/dist/session/phase-completion.runtime.d.ts +4 -10
  119. package/dist/session/phase-completion.runtime.js +77 -209
  120. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  121. package/dist/session/phase-completion.schema-parts.js +188 -0
  122. package/dist/session/phase-completion.schemas.d.ts +3 -3
  123. package/dist/session/phase-completion.schemas.js +208 -231
  124. package/dist/session/phase-completion.validation.d.ts +2 -3
  125. package/dist/session/phase-completion.validation.js +49 -93
  126. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  127. package/dist/session/pre-publication-native-postgres.js +111 -0
  128. package/dist/session/pre-publication-pass.d.ts +61 -0
  129. package/dist/session/pre-publication-pass.js +148 -0
  130. package/dist/session/pre-publication-process.js +10 -10
  131. package/dist/session/pre-publication-step-execution.d.ts +2 -1
  132. package/dist/session/pre-publication-step-execution.js +6 -5
  133. package/dist/session/pre-publication-validation.d.ts +30 -14
  134. package/dist/session/pre-publication-validation.js +207 -134
  135. package/dist/session/provider-cli/claude-background-work.d.ts +67 -0
  136. package/dist/session/provider-cli/claude-background-work.js +181 -0
  137. package/dist/session/provider-cli/host-build-lock.d.ts +18 -0
  138. package/dist/session/provider-cli/host-build-lock.js +30 -0
  139. package/dist/session/provider-cli/pre-publication-repair.d.ts +56 -0
  140. package/dist/session/provider-cli/pre-publication-repair.js +276 -0
  141. package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
  142. package/dist/session/provider-cli/provider-cli.child-environment.js +75 -0
  143. package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
  144. package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
  145. package/dist/session/provider-cli/provider-cli.process.d.ts +15 -36
  146. package/dist/session/provider-cli/provider-cli.process.js +39 -430
  147. package/dist/session/provider-cli/provider-cli.prompts.d.ts +5 -0
  148. package/dist/session/provider-cli/provider-cli.prompts.js +72 -32
  149. package/dist/session/provider-cli/provider-cli.runtime.d.ts +8 -0
  150. package/dist/session/provider-cli/provider-cli.runtime.js +29 -1
  151. package/dist/session/provider-cli/provider-cli.service.d.ts +7 -1
  152. package/dist/session/provider-cli/provider-cli.service.js +78 -171
  153. package/dist/session/provider-cli/provider-cli.types.d.ts +26 -0
  154. package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
  155. package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
  156. package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
  157. package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
  158. package/dist/session/provider-cli/provider-in-flight-work.d.ts +4 -0
  159. package/dist/session/provider-cli/provider-in-flight-work.js +45 -0
  160. package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
  161. package/dist/session/provider-cli/provider-output-pipes.js +67 -0
  162. package/dist/session/provider-cli/provider-output-state.d.ts +2 -0
  163. package/dist/session/provider-cli/provider-output-state.js +6 -0
  164. package/dist/session/provider-cli/provider-user-config-isolation.d.ts +69 -0
  165. package/dist/session/provider-cli/provider-user-config-isolation.js +164 -0
  166. package/dist/session/qa-sidecar-validation.d.ts +6 -0
  167. package/dist/session/qa-sidecar-validation.js +28 -0
  168. package/dist/session/sandbox-host-capacity-gate.d.ts +22 -1
  169. package/dist/session/sandbox-host-capacity-gate.js +42 -14
  170. package/dist/session/session-redaction.js +31 -181
  171. package/dist/session/session.base.d.ts +6 -1
  172. package/dist/session/session.service.d.ts +9 -2
  173. package/dist/session/session.service.js +162 -58
  174. package/dist/session/session.types.js +4 -4
  175. package/dist/session/sidecar-json-shape.d.ts +31 -0
  176. package/dist/session/sidecar-json-shape.js +217 -0
  177. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  178. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  179. package/dist/shared/fs/file-identity.d.ts +10 -0
  180. package/dist/shared/fs/file-identity.js +15 -0
  181. package/dist/shared/fs/replace-file.d.ts +7 -0
  182. package/dist/shared/fs/replace-file.js +33 -0
  183. package/dist/shared/process/host-process-recovery.d.ts +14 -3
  184. package/dist/shared/process/host-process-recovery.js +23 -3
  185. package/dist/shared/process/host-process-supervisor.d.ts +13 -1
  186. package/dist/shared/process/host-process-supervisor.js +66 -14
  187. package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
  188. package/dist/shared/process/windows-app-execution-alias.js +45 -0
  189. package/dist/shared/process/windows-launch.d.ts +18 -0
  190. package/dist/shared/process/windows-launch.js +68 -0
  191. package/dist/shared/provider-capabilities.js +14 -7
  192. package/dist/version.d.ts +1 -1
  193. package/dist/version.js +1 -1
  194. package/dist/worktree/wip-git.d.ts +33 -0
  195. package/dist/worktree/wip-git.js +122 -0
  196. package/dist/worktree/wip-refs.d.ts +62 -0
  197. package/dist/worktree/wip-refs.js +119 -0
  198. package/dist/worktree/wip-restore.d.ts +38 -0
  199. package/dist/worktree/wip-restore.js +190 -0
  200. package/dist/worktree/wip-snapshot.d.ts +50 -0
  201. package/dist/worktree/wip-snapshot.js +268 -0
  202. package/dist/worktree/worktree-wip-events.d.ts +18 -0
  203. package/dist/worktree/worktree-wip-events.js +98 -0
  204. package/dist/worktree/worktree-wip.d.ts +49 -0
  205. package/dist/worktree/worktree-wip.js +182 -0
  206. package/dist/worktree/worktree.base.d.ts +7 -1
  207. package/dist/worktree/worktree.service.d.ts +11 -3
  208. package/dist/worktree/worktree.service.js +54 -21
  209. package/dist/worktree/worktree.types.d.ts +22 -0
  210. package/package.json +2 -2
@@ -0,0 +1,268 @@
1
+ import fs from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { baseTrackedForgePaths, gitPath, hasPartialRestoreMarker, isWipExcludedPath, makeWipTempDir, readOptionalFile, splitNul, WipGit, } from "./wip-git.js";
4
+ import { formatWipCommitMessage, unorderedWipAttempt, WipPreservationError, wipMetadataSchema, wipRefId, wipRefName, wipSnapshotMaxBytes, } from "./wip-refs.js";
5
+ const mergeMessageLimit = 16 * 1024;
6
+ // Snapshots this process already pushed, keyed by worktree: a guard that finds the same state
7
+ // (for example the release right after a failed session's snapshot) does not push it twice. An
8
+ // entry is reused only for the same branch, only when it is at least as restorable as the request
9
+ // asks for, and only while its ref still points at it (wip-snapshot cache checks below).
10
+ const savedSnapshots = new Map();
11
+ /**
12
+ * Saves the worktree's uncommitted work to a WIP ref. Returns `clean` (and pushes nothing) when
13
+ * there is nothing to save. Throws {@link WipPreservationError} when the work could not be saved,
14
+ * including when it is over the size cap: the caller must then not destroy the worktree.
15
+ */
16
+ export async function preserveWorktreeWip(requested) {
17
+ const baseGit = new WipGit(requested.processRunner);
18
+ const git = requested.orphan
19
+ ? baseGit.with({ GIT_DIR: await commonGitDir(baseGit, requested.orphan.repoPath), GIT_WORK_TREE: requested.worktreePath })
20
+ : baseGit;
21
+ // A half-applied restore is saved like any other state, but never for a later pass to apply.
22
+ const degraded = requested.autoRestore && !requested.orphan && await hasPartialRestoreMarker(git, requested.worktreePath);
23
+ const request = degraded ? { ...requested, autoRestore: false } : requested;
24
+ const repoPath = request.orphan?.repoPath ?? request.worktreePath;
25
+ const tempDir = await makeWipTempDir();
26
+ try {
27
+ const capture = await captureWorktree(request, { git, cwd: request.worktreePath, repoPath, tempDir })
28
+ .catch(error => { throw asPreservationError(error, "wip_snapshot_failed"); });
29
+ if (!capture)
30
+ return { status: "clean" };
31
+ const fingerprint = captureFingerprint(capture);
32
+ const cached = savedSnapshots.get(snapshotKey(request.worktreePath));
33
+ if (cached && await cachedSnapshotServes(baseGit, repoPath, cached, fingerprint, request)) {
34
+ const { fingerprint: _fingerprint, branchName: _branch, autoRestore: _autoRestore, ...saved } = cached;
35
+ return { ...saved, status: "already_saved" };
36
+ }
37
+ const commitSha = await writeSnapshotCommits(request, capture, { git, cwd: request.worktreePath, repoPath, tempDir })
38
+ .catch(error => { throw asPreservationError(error, "wip_snapshot_failed"); });
39
+ const published = await publishSnapshot(baseGit, repoPath, request, commitSha);
40
+ const result = {
41
+ status: "saved",
42
+ ...published,
43
+ commitSha,
44
+ baseHead: capture.base,
45
+ changedPaths: capture.changedPaths,
46
+ bytes: capture.bytes,
47
+ };
48
+ savedSnapshots.set(snapshotKey(request.worktreePath), {
49
+ ...result, fingerprint, branchName: request.branchName, autoRestore: request.autoRestore,
50
+ });
51
+ return result;
52
+ }
53
+ finally {
54
+ await fs.rm(tempDir, { recursive: true, force: true }).catch(() => undefined);
55
+ }
56
+ }
57
+ /** Forgets what this process pushed for a worktree, e.g. once the worktree is gone. */
58
+ export function forgetPreservedWip(worktreePath) {
59
+ savedSnapshots.delete(snapshotKey(worktreePath));
60
+ }
61
+ /**
62
+ * Forgets every snapshot this process pushed to `ref`, before that ref is deleted: a later guard
63
+ * that finds the same state must push it again rather than report it saved in a ref that is gone.
64
+ */
65
+ export function forgetPreservedWipRef(ref) {
66
+ for (const [key, saved] of savedSnapshots) {
67
+ if (saved.ref === ref)
68
+ savedSnapshots.delete(key);
69
+ }
70
+ }
71
+ async function captureWorktree(request, context) {
72
+ const { git, cwd } = context;
73
+ const base = (await git.run(cwd, ["rev-parse", "--verify", `${request.orphan?.baseRef ?? "HEAD"}^{commit}`])).trim();
74
+ const baseTree = (await git.run(cwd, ["rev-parse", `${base}^{tree}`])).trim();
75
+ const merge = request.orphan ? null : await readMergeState(git, cwd);
76
+ const forgePaths = await baseTrackedForgePaths(git, cwd, base);
77
+ const excluded = (filePath) => isWipExcludedPath(filePath, forgePaths);
78
+ const worktreeIndex = path.join(context.tempDir, "worktree.index");
79
+ await seedIndex(context, request, base, worktreeIndex);
80
+ const indexGit = git.with({ GIT_INDEX_FILE: worktreeIndex });
81
+ const bytes = await measureChanges(indexGit, cwd, base, excluded, request.maxBytes ?? wipSnapshotMaxBytes());
82
+ const stagedIndex = path.join(context.tempDir, "staged.index");
83
+ await copyIndex(worktreeIndex, stagedIndex);
84
+ const indexTree = request.orphan
85
+ ? baseTree
86
+ : await writeStagedTree(git.with({ GIT_INDEX_FILE: stagedIndex }), cwd, base, merge, excluded);
87
+ await indexGit.run(cwd, ["add", "-A"]);
88
+ const changed = await resetExcluded(indexGit, cwd, base, excluded);
89
+ const worktreeTree = (await indexGit.run(cwd, ["write-tree"])).trim();
90
+ if (worktreeTree === baseTree && indexTree === baseTree && !merge)
91
+ return null;
92
+ return { base, worktreeTree, indexTree, merge, changedPaths: changed.length, bytes };
93
+ }
94
+ /** A copy of the worktree's real index; the base tree when it has none or the checkout is orphaned. */
95
+ async function seedIndex(context, request, base, target) {
96
+ if (!request.orphan) {
97
+ const realIndex = await gitPath(context.git, context.cwd, "index");
98
+ const copied = await copyIndex(realIndex, target).then(() => true, (error) => {
99
+ if (error.code === "ENOENT")
100
+ return false;
101
+ throw error;
102
+ });
103
+ if (copied)
104
+ return;
105
+ }
106
+ await context.git.with({ GIT_INDEX_FILE: target }).run(context.cwd, ["read-tree", base]);
107
+ }
108
+ /**
109
+ * Copies an index file with its modification time. Git treats an entry whose file changed in the
110
+ * same second the index was written as "racily clean" and compares its content; a copy stamped
111
+ * with a later time would hide such a change behind matching stat data (same size, same second).
112
+ */
113
+ async function copyIndex(source, target) {
114
+ await fs.copyFile(source, target);
115
+ const stat = await fs.stat(source);
116
+ await fs.utimes(target, stat.atime, stat.mtime);
117
+ }
118
+ /**
119
+ * Sums the size of every changed file that would be saved and refuses a snapshot over the cap,
120
+ * before any of it is hashed into the object store.
121
+ */
122
+ async function measureChanges(git, cwd, base, excluded, maxBytes) {
123
+ const [untracked, modified, staged] = await Promise.all([
124
+ git.run(cwd, ["ls-files", "-o", "--exclude-standard", "-z"]),
125
+ git.run(cwd, ["diff", "--name-only", "--no-renames", "-z"]),
126
+ git.run(cwd, ["diff", "--cached", "--name-only", "--no-renames", "-z", base]),
127
+ ]);
128
+ const paths = [...new Set([...splitNul(untracked), ...splitNul(modified), ...splitNul(staged)])]
129
+ .filter(filePath => !excluded(filePath));
130
+ const sizes = [];
131
+ for (const filePath of paths) {
132
+ const stat = await fs.lstat(path.join(cwd, filePath)).catch(() => null);
133
+ if (stat?.isFile())
134
+ sizes.push({ path: filePath, bytes: stat.size });
135
+ }
136
+ const total = sizes.reduce((sum, entry) => sum + entry.bytes, 0);
137
+ if (total > maxBytes) {
138
+ const largest = sizes.sort((left, right) => right.bytes - left.bytes).slice(0, 5)
139
+ .map(entry => `${entry.path} (${entry.bytes} bytes)`).join(", ");
140
+ throw new WipPreservationError("wip_snapshot_too_large", `uncommitted work in ${cwd} is ${total} bytes across ${sizes.length} file(s), over the ${maxBytes}-byte WIP snapshot cap `
141
+ + `(${"FORGE_WIP_SNAPSHOT_MAX_BYTES"}); largest: ${largest}. Nothing was saved, so the worktree is kept as it is.`);
142
+ }
143
+ return total;
144
+ }
145
+ /** The staged state: the real index with unresolved conflicts and runtime output put back to the base. */
146
+ async function writeStagedTree(git, cwd, base, merge, excluded) {
147
+ const conflicted = [...new Set((merge?.unmerged ?? []).map(entry => entry.path))];
148
+ await git.runForPaths(cwd, ["reset", "-q", base], conflicted);
149
+ await resetExcluded(git, cwd, base, excluded);
150
+ return (await git.run(cwd, ["write-tree"])).trim();
151
+ }
152
+ /** Puts excluded paths back to the base in this index and returns the paths that still differ. */
153
+ async function resetExcluded(git, cwd, base, excluded) {
154
+ const listChanged = async () => splitNul(await git.run(cwd, ["diff", "--cached", "--name-only", "--no-renames", "-z", base]));
155
+ const changed = await listChanged();
156
+ const toReset = changed.filter(excluded);
157
+ if (toReset.length === 0)
158
+ return changed;
159
+ await git.runForPaths(cwd, ["reset", "-q", base], toReset);
160
+ return await listChanged();
161
+ }
162
+ async function readMergeState(git, cwd) {
163
+ const head = (await git.tryRun(cwd, ["rev-parse", "-q", "--verify", "MERGE_HEAD^{commit}"]))?.trim();
164
+ if (!head)
165
+ return null;
166
+ const message = await readOptionalFile(await gitPath(git, cwd, "MERGE_MSG"));
167
+ const mode = await readOptionalFile(await gitPath(git, cwd, "MERGE_MODE"));
168
+ const unmerged = splitNul(await git.run(cwd, ["ls-files", "-u", "-z"])).map(parseUnmergedEntry);
169
+ return {
170
+ head,
171
+ message: message === null ? null : message.slice(0, mergeMessageLimit),
172
+ mode: mode?.trim() || null,
173
+ unmerged,
174
+ };
175
+ }
176
+ function parseUnmergedEntry(record) {
177
+ const tab = record.indexOf("\t");
178
+ const [mode, sha, stage] = record.slice(0, tab).split(" ");
179
+ return { mode: mode, sha: sha, stage: Number(stage), path: record.slice(tab + 1) };
180
+ }
181
+ async function writeSnapshotCommits(request, capture, context) {
182
+ const { git, cwd, tempDir } = context;
183
+ const indexCommit = (await git.run(cwd, [
184
+ "commit-tree", capture.indexTree, "-p", capture.base, "-m", "forge wip index snapshot",
185
+ ])).trim();
186
+ const now = (request.now ?? (() => new Date()))();
187
+ const metadata = {
188
+ schema: wipMetadataSchema,
189
+ branch: request.branchName,
190
+ baseHead: capture.base,
191
+ sessionId: request.sessionId?.trim() || null,
192
+ lane: request.lane?.trim() || null,
193
+ reason: request.reason,
194
+ attempt: request.attempt ?? unorderedWipAttempt,
195
+ autoRestore: request.autoRestore,
196
+ createdAt: now.toISOString(),
197
+ createdAtMs: now.getTime(),
198
+ mergeHead: capture.merge?.head ?? null,
199
+ mergeMessage: capture.merge?.message ?? null,
200
+ mergeMode: capture.merge?.mode ?? null,
201
+ unmerged: capture.merge?.unmerged ?? [],
202
+ changedPaths: capture.changedPaths,
203
+ bytes: capture.bytes,
204
+ };
205
+ const messageFile = path.join(tempDir, "message.txt");
206
+ await fs.writeFile(messageFile, formatWipCommitMessage(metadata), "utf8");
207
+ const parents = [capture.base, indexCommit, ...(capture.merge ? [capture.merge.head] : [])]
208
+ .flatMap(parent => ["-p", parent]);
209
+ return (await git.run(cwd, ["commit-tree", capture.worktreeTree, ...parents, "-F", messageFile])).trim();
210
+ }
211
+ /**
212
+ * Pushes the snapshot to origin. A repository without an origin keeps the ref locally instead,
213
+ * since there is nowhere else it could go and the repository itself outlives the worktree.
214
+ */
215
+ async function publishSnapshot(git, repoPath, request, commitSha) {
216
+ const now = (request.now ?? (() => new Date()))();
217
+ const ref = wipRefName(request.branchName, wipRefId(request.reason, request.sessionId, now, request.attempt));
218
+ const origin = (await git.tryRun(repoPath, ["remote", "get-url", "origin"]))?.trim();
219
+ if (!origin) {
220
+ await git.run(repoPath, ["update-ref", ref, commitSha]);
221
+ return { ref, pushed: false };
222
+ }
223
+ try {
224
+ await git.run(repoPath, ["push", "--porcelain", "origin", `${commitSha}:${ref}`]);
225
+ return { ref, pushed: true };
226
+ }
227
+ catch (error) {
228
+ // A session's ref can already exist when the same session was snapshotted before (a retried
229
+ // dispatch); keep both rather than overwrite one.
230
+ const retryRef = `${ref}-${now.getTime().toString(36)}`;
231
+ const retried = await git.tryRun(repoPath, ["push", "--porcelain", "origin", `${commitSha}:${retryRef}`]);
232
+ if (retried !== null)
233
+ return { ref: retryRef, pushed: true };
234
+ throw asPreservationError(error, "wip_push_failed");
235
+ }
236
+ }
237
+ async function commonGitDir(git, repoPath) {
238
+ const raw = (await git.run(repoPath, ["rev-parse", "--git-common-dir"])).trim();
239
+ return path.isAbsolute(raw) ? raw : path.resolve(repoPath, raw);
240
+ }
241
+ function captureFingerprint(capture) {
242
+ return [capture.base, capture.worktreeTree, capture.indexTree, capture.merge?.head ?? ""].join(":");
243
+ }
244
+ function snapshotKey(worktreePath) {
245
+ const resolved = path.resolve(worktreePath);
246
+ return process.platform === "win32" ? resolved.toLowerCase() : resolved;
247
+ }
248
+ /**
249
+ * Whether a snapshot this process pushed can stand in for the one requested: the same state of the
250
+ * same branch, restorable whenever the request must be, and still at its ref (it may have been
251
+ * retired, or deleted on origin by the server's cleanup). A ref that can't be confirmed is pushed again.
252
+ */
253
+ async function cachedSnapshotServes(git, repoPath, cached, fingerprint, request) {
254
+ if (cached.fingerprint !== fingerprint || cached.branchName !== request.branchName)
255
+ return false;
256
+ if (request.autoRestore && !cached.autoRestore)
257
+ return false;
258
+ const listed = cached.pushed
259
+ ? await git.tryRun(repoPath, ["ls-remote", "--refs", "origin", cached.ref])
260
+ : await git.tryRun(repoPath, ["rev-parse", "-q", "--verify", `${cached.ref}^{commit}`]);
261
+ return (listed?.trim().split(/\s+/u)[0] ?? "") === cached.commitSha;
262
+ }
263
+ function asPreservationError(error, code) {
264
+ if (error instanceof WipPreservationError)
265
+ return error;
266
+ const message = error instanceof Error ? error.message : String(error);
267
+ return new WipPreservationError(code, message, { cause: error });
268
+ }
@@ -0,0 +1,18 @@
1
+ import type { RunnerDispatchEvent } from "../session/session.types.js";
2
+ import type { WorktreeService } from "./worktree.base.js";
3
+ import type { WipSessionOutcome, WorktreeHandle } from "./worktree.types.js";
4
+ type Emit = (event: RunnerDispatchEvent) => Promise<void>;
5
+ /** Reports what the prepare did with the story's saved WIP, before the provider starts. */
6
+ export declare function emitWipRestoreEvent(worktree: WorktreeHandle, emit: Emit): Promise<void>;
7
+ /** How a session ended, for the snapshot it leaves behind. */
8
+ export declare function sessionWipOutcome(signal: AbortSignal | undefined, events: readonly RunnerDispatchEvent[], succeeded: boolean): WipSessionOutcome;
9
+ /**
10
+ * Ends a session's use of its worktree: first saves its WIP (or retires the snapshot it started
11
+ * from) and reports that, then, as a separate step, releases the worktree unless the session
12
+ * paused or its WIP could not be saved. Nothing here throws over the session's own result or
13
+ * failure: a release that refuses to delete unsaved work, or that fails (a Windows process still
14
+ * holding a cwd in the worktree makes the rename fail), keeps the worktree on this runner and is
15
+ * reported as a cleanup failure.
16
+ */
17
+ export declare function settleWorktree(worktrees: WorktreeService, worktree: WorktreeHandle, outcome: WipSessionOutcome, signal: AbortSignal | undefined, emit: Emit): Promise<void>;
18
+ export {};
@@ -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,49 @@
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
+ /**
6
+ * Saves uncommitted work before `git reset --hard` / `git clean` on an existing worktree; a later
7
+ * pass may apply it by itself only when it came from a publishing lane.
8
+ * Throws when it could not be saved: losing work is worse than a failed prepare.
9
+ */
10
+ export declare function guardWorktreeReset(worktreePath: string, branchName: string, owner: {
11
+ readonly sessionId?: string | null;
12
+ readonly lane: string;
13
+ }): Promise<WipSnapshotResult>;
14
+ /**
15
+ * Before a local branch is re-pointed at a new start point (`worktree add -B`), saves any commits
16
+ * on it that neither the start point nor origin has, as a `forge.wip.v1` snapshot like any other:
17
+ * its tree is the tip's, its first parent the tip (so the commits are `<ref>^1` and its ancestors),
18
+ * and it is never applied automatically. Throws when they could not be saved.
19
+ */
20
+ export declare function guardBranchReset(git: GitClient, repoPath: string, branchName: string, startPoint: string): Promise<void>;
21
+ /** Puts the newest restorable snapshot back on a freshly prepared worktree of a publishing lane. */
22
+ export declare function restoreWorktreeWip(input: {
23
+ readonly worktreePath: string;
24
+ readonly repoPath: string;
25
+ readonly branchName: string;
26
+ readonly sessionId?: string | null;
27
+ readonly lane: string;
28
+ }): Promise<WipRestoreOutcome | undefined>;
29
+ /**
30
+ * Saves a worktree that is about to be deleted. Its snapshot is never applied automatically (a
31
+ * session that ended without succeeding has already saved its own work under its id; what is
32
+ * left after a successful pass was deliberately not published). Throws when it could not be saved.
33
+ */
34
+ export declare function guardWorktreeRelease(handle: WorktreeHandle): Promise<WipSnapshotResult>;
35
+ /** Forgets what this process saved for a worktree once it is gone. */
36
+ export declare function worktreeReleased(handle: WorktreeHandle): void;
37
+ /**
38
+ * At the end of a session: saves its uncommitted work unless it succeeded, and deletes the
39
+ * snapshot it started from once that work is safe elsewhere: saved again here, or (after a
40
+ * success) published, which is only certain when nothing is left uncommitted. Leftovers keep the
41
+ * ref; the release's own snapshot of them is never applied automatically.
42
+ * Never throws; a failure is reported in the result.
43
+ */
44
+ export declare function settleSessionWip(handle: WorktreeHandle, outcome: WipSessionOutcome): Promise<WipSettlement>;
45
+ /**
46
+ * After a release: deletes the readiness probe's branch, and other Forge branches whose work is
47
+ * already on the base. Branches of live leases are kept; when the ledger can't be read, nothing is.
48
+ */
49
+ export declare function sweepBranchesAfterRelease(git: GitClient, handle: WorktreeHandle, leaseStateRoot: string, limit: number): Promise<void>;
@@ -0,0 +1,182 @@
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
+ /** Lanes whose work the bridge publishes, and so whose snapshots a later pass may apply by itself. */
13
+ const restoreLanes = new Set(["develop", "debug", "conflict_resolve", "ci_repair"]);
14
+ function isWipRestoreLane(lane) {
15
+ return restoreLanes.has((lane ?? "").trim().toLowerCase());
16
+ }
17
+ /**
18
+ * Saves uncommitted work before `git reset --hard` / `git clean` on an existing worktree; a later
19
+ * pass may apply it by itself only when it came from a publishing lane.
20
+ * Throws when it could not be saved: losing work is worse than a failed prepare.
21
+ */
22
+ export async function guardWorktreeReset(worktreePath, branchName, owner) {
23
+ try {
24
+ return await preserveWorktreeWip({
25
+ worktreePath,
26
+ branchName,
27
+ reason: "pre_reset",
28
+ sessionId: owner.sessionId,
29
+ lane: owner.lane,
30
+ autoRestore: isWipRestoreLane(owner.lane),
31
+ });
32
+ }
33
+ catch (error) {
34
+ 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 });
35
+ }
36
+ }
37
+ /**
38
+ * Before a local branch is re-pointed at a new start point (`worktree add -B`), saves any commits
39
+ * on it that neither the start point nor origin has, as a `forge.wip.v1` snapshot like any other:
40
+ * its tree is the tip's, its first parent the tip (so the commits are `<ref>^1` and its ancestors),
41
+ * and it is never applied automatically. Throws when they could not be saved.
42
+ */
43
+ export async function guardBranchReset(git, repoPath, branchName, startPoint) {
44
+ const tip = (await git.run(repoPath, ["rev-parse", "-q", "--verify", `refs/heads/${branchName}^{commit}`]).catch(() => "")).trim();
45
+ if (!tip)
46
+ return;
47
+ const onStartPoint = await git.run(repoPath, ["merge-base", "--is-ancestor", tip, startPoint]).then(() => true, () => false);
48
+ if (onStartPoint)
49
+ return;
50
+ const onOrigin = (await git.run(repoPath, ["branch", "-r", "--contains", tip]).catch(() => "")).trim().length > 0;
51
+ if (onOrigin)
52
+ return;
53
+ const now = new Date();
54
+ const ref = wipRefName(branchName, wipRefId("pre_branch_reset", null, now));
55
+ const origin = (await git.run(repoPath, ["remote", "get-url", "origin"]).catch(() => "")).trim();
56
+ try {
57
+ const snapshot = await branchTipSnapshot(repoPath, branchName, tip, now);
58
+ await git.run(repoPath, origin ? ["push", "--porcelain", "origin", `${snapshot}:${ref}`] : ["update-ref", ref, snapshot]);
59
+ }
60
+ catch (error) {
61
+ 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 });
62
+ }
63
+ }
64
+ /** A snapshot commit holding a branch tip: nothing uncommitted, so its tree and index are the tip's. */
65
+ async function branchTipSnapshot(repoPath, branchName, tip, now) {
66
+ const git = new WipGit();
67
+ const tree = (await git.run(repoPath, ["rev-parse", `${tip}^{tree}`])).trim();
68
+ const indexCommit = (await git.run(repoPath, ["commit-tree", tree, "-p", tip, "-m", "forge wip index snapshot"])).trim();
69
+ const message = formatWipCommitMessage({
70
+ schema: wipMetadataSchema,
71
+ branch: branchName,
72
+ baseHead: tip,
73
+ sessionId: null,
74
+ lane: null,
75
+ reason: "pre_branch_reset",
76
+ attempt: unorderedWipAttempt,
77
+ autoRestore: false,
78
+ createdAt: now.toISOString(),
79
+ createdAtMs: now.getTime(),
80
+ mergeHead: null,
81
+ mergeMessage: null,
82
+ mergeMode: null,
83
+ unmerged: [],
84
+ changedPaths: 0,
85
+ bytes: 0,
86
+ });
87
+ return (await git.run(repoPath, ["commit-tree", tree, "-p", tip, "-p", indexCommit, "-m", message])).trim();
88
+ }
89
+ /** Puts the newest restorable snapshot back on a freshly prepared worktree of a publishing lane. */
90
+ export async function restoreWorktreeWip(input) {
91
+ if (!input.sessionId || !isWipRestoreLane(input.lane))
92
+ return undefined;
93
+ return await restoreLatestWip(input);
94
+ }
95
+ /**
96
+ * Saves a worktree that is about to be deleted. Its snapshot is never applied automatically (a
97
+ * session that ended without succeeding has already saved its own work under its id; what is
98
+ * left after a successful pass was deliberately not published). Throws when it could not be saved.
99
+ */
100
+ export async function guardWorktreeRelease(handle) {
101
+ // A readiness probe never runs an agent; its checkout only ever holds the app's own output.
102
+ if (isRuntimeReadinessBranch(handle.branchName))
103
+ return { status: "clean" };
104
+ return await preserveWorktreeWip({
105
+ worktreePath: handle.worktreePath,
106
+ branchName: handle.branchName,
107
+ reason: "pre_release",
108
+ sessionId: handle.sessionId,
109
+ lane: handle.lane,
110
+ autoRestore: false,
111
+ });
112
+ }
113
+ /** Forgets what this process saved for a worktree once it is gone. */
114
+ export function worktreeReleased(handle) {
115
+ forgetPreservedWip(handle.worktreePath);
116
+ }
117
+ /**
118
+ * At the end of a session: saves its uncommitted work unless it succeeded, and deletes the
119
+ * snapshot it started from once that work is safe elsewhere: saved again here, or (after a
120
+ * success) published, which is only certain when nothing is left uncommitted. Leftovers keep the
121
+ * ref; the release's own snapshot of them is never applied automatically.
122
+ * Never throws; a failure is reported in the result.
123
+ */
124
+ export async function settleSessionWip(handle, outcome) {
125
+ let snapshot;
126
+ if (outcome.reason) {
127
+ try {
128
+ snapshot = await preserveWorktreeWip({
129
+ worktreePath: handle.worktreePath,
130
+ branchName: handle.branchName,
131
+ reason: outcome.reason,
132
+ sessionId: handle.sessionId,
133
+ lane: handle.lane,
134
+ autoRestore: isWipRestoreLane(handle.lane),
135
+ });
136
+ }
137
+ catch (error) {
138
+ return {
139
+ error: {
140
+ code: error instanceof WipPreservationError ? error.code : "wip_snapshot_failed",
141
+ message: errorMessage(error),
142
+ },
143
+ };
144
+ }
145
+ }
146
+ const restored = handle.wipRestore?.status === "restored" ? handle.wipRestore.ref : null;
147
+ // A failed session that left a clean worktree may have thrown the restored work away; keep its ref.
148
+ const supersededBy = snapshot && snapshot.status !== "clean" ? snapshot.ref : null;
149
+ const safeElsewhere = outcome.reason === null
150
+ ? await hasNoUnsavedWork(handle.worktreePath).catch(() => false)
151
+ : Boolean(supersededBy && supersededBy !== restored);
152
+ const retire = restored && safeElsewhere ? restored : null;
153
+ if (retire)
154
+ forgetPreservedWipRef(retire);
155
+ const retiredRef = retire && await deleteWipRef(handle.repoPath, retire) ? retire : null;
156
+ return { ...(snapshot ? { snapshot } : {}), retiredRef };
157
+ }
158
+ /**
159
+ * After a release: deletes the readiness probe's branch, and other Forge branches whose work is
160
+ * already on the base. Branches of live leases are kept; when the ledger can't be read, nothing is.
161
+ */
162
+ export async function sweepBranchesAfterRelease(git, handle, leaseStateRoot, limit) {
163
+ const protectedBranches = await readHostRuntimeLeases(leaseStateRoot)
164
+ .then(liveLeaseBranches)
165
+ .catch(() => null);
166
+ if (!protectedBranches)
167
+ return;
168
+ let budget = limit;
169
+ if (isRuntimeReadinessBranch(handle.branchName) && !protectedBranches.has(handle.branchName)
170
+ && await deleteBranchIfUnused(git, handle.repoPath, handle.branchName)) {
171
+ budget -= 1;
172
+ }
173
+ await sweepManagedBranches(git, handle.repoPath, {
174
+ baseBranch: handle.baseBranch,
175
+ includeMergedWorkBranches: true,
176
+ protectedBranches,
177
+ limit: budget,
178
+ }).catch(() => undefined);
179
+ }
180
+ function errorMessage(error) {
181
+ return error instanceof Error ? error.message : String(error);
182
+ }
@@ -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>;