@loucompanion/forge-bridge 0.2.1-dev.4f11ffc822f9 → 0.2.1-dev.7171bf414613

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 (152) hide show
  1. package/README.md +41 -3
  2. package/dist/bridge/bridge-state-io.d.ts +6 -2
  3. package/dist/bridge/bridge-state-io.js +22 -4
  4. package/dist/bridge/bridge.service.d.ts +10 -0
  5. package/dist/bridge/bridge.service.js +63 -101
  6. package/dist/bridge/bridge.types.d.ts +16 -0
  7. package/dist/bridge/bridge.types.js +2 -1
  8. package/dist/bridge/default-session-service.d.ts +13 -0
  9. package/dist/bridge/default-session-service.js +22 -0
  10. package/dist/bridge/dispatch-offer-policy.d.ts +22 -0
  11. package/dist/bridge/dispatch-offer-policy.js +58 -0
  12. package/dist/bridge/runner-host-capabilities.js +14 -1
  13. package/dist/bridge/windows-bash-resolution.d.ts +31 -0
  14. package/dist/bridge/windows-bash-resolution.js +153 -0
  15. package/dist/cleanup/cleanup-wip.js +3 -3
  16. package/dist/cleanup/forge-owned-paths.d.ts +2 -0
  17. package/dist/cleanup/forge-owned-paths.js +9 -0
  18. package/dist/cli/cli.help.js +1 -1
  19. package/dist/cli/cli.service.js +11 -43
  20. package/dist/cli/local-config.d.ts +12 -1
  21. package/dist/cli/local-config.js +35 -1
  22. package/dist/cli/provider-cli-advertising.d.ts +24 -0
  23. package/dist/cli/provider-cli-advertising.js +88 -0
  24. package/dist/runtime/host-load-admission.d.ts +5 -0
  25. package/dist/runtime/host-load-capacity.d.ts +198 -0
  26. package/dist/runtime/host-load-capacity.js +353 -0
  27. package/dist/runtime/host-load-child-environment.d.ts +13 -0
  28. package/dist/runtime/host-load-child-environment.js +35 -1
  29. package/dist/runtime/host-load-governor-config.d.ts +33 -3
  30. package/dist/runtime/host-load-governor-config.js +24 -3
  31. package/dist/runtime/host-load-governor.d.ts +89 -2
  32. package/dist/runtime/host-load-governor.js +217 -18
  33. package/dist/runtime/host-load-live-test-slots.d.ts +61 -0
  34. package/dist/runtime/host-load-live-test-slots.js +193 -0
  35. package/dist/runtime/host-load-sampler.d.ts +17 -0
  36. package/dist/runtime/host-load-sampler.js +24 -0
  37. package/dist/runtime/host-load-step-run.d.ts +37 -3
  38. package/dist/runtime/host-load-step-run.js +63 -7
  39. package/dist/runtime/host-load-test-slot.d.ts +3 -0
  40. package/dist/runtime/host-load-test-slot.js +26 -7
  41. package/dist/runtime/host-runtime-contract.js +6 -4
  42. package/dist/runtime/prepared-runtime-readiness.d.ts +12 -2
  43. package/dist/runtime/prepared-runtime-readiness.js +35 -11
  44. package/dist/sandbox/runtime.d.ts +1 -2
  45. package/dist/sandbox/runtime.js +8 -14
  46. package/dist/sandbox/sandbox-input.d.ts +22 -0
  47. package/dist/sandbox/sandbox-input.js +49 -0
  48. package/dist/sandbox/workspace.service.js +15 -2
  49. package/dist/session/managed-attempt-tools.js +6 -29
  50. package/dist/session/managed-build-receipt.d.ts +3 -1
  51. package/dist/session/managed-build-receipt.js +5 -2
  52. package/dist/session/managed-command-environment.d.ts +8 -0
  53. package/dist/session/managed-command-environment.js +28 -0
  54. package/dist/session/managed-command-host-load.d.ts +10 -5
  55. package/dist/session/managed-command-host-load.js +18 -14
  56. package/dist/session/phase-completion.artifact-bundle.d.ts +20 -0
  57. package/dist/session/phase-completion.artifact-bundle.js +167 -0
  58. package/dist/session/phase-completion.artifacts.d.ts +2 -17
  59. package/dist/session/phase-completion.artifacts.js +63 -165
  60. package/dist/session/phase-completion.d.ts +25 -2
  61. package/dist/session/phase-completion.helpers.js +5 -53
  62. package/dist/session/phase-completion.js +15 -32
  63. package/dist/session/phase-completion.mcp-args.js +69 -2
  64. package/dist/session/phase-completion.phase-aliases.d.ts +5 -0
  65. package/dist/session/phase-completion.phase-aliases.js +43 -0
  66. package/dist/session/phase-completion.pr-review-schema.d.ts +1 -0
  67. package/dist/session/phase-completion.pr-review-schema.js +75 -0
  68. package/dist/session/phase-completion.pr-review-threads.d.ts +34 -0
  69. package/dist/session/phase-completion.pr-review-threads.js +90 -0
  70. package/dist/session/phase-completion.pr-review-validation.d.ts +11 -0
  71. package/dist/session/phase-completion.pr-review-validation.js +215 -0
  72. package/dist/session/phase-completion.pr-review.d.ts +36 -0
  73. package/dist/session/phase-completion.pr-review.js +294 -0
  74. package/dist/session/phase-completion.prompts.d.ts +1 -1
  75. package/dist/session/phase-completion.prompts.js +14 -0
  76. package/dist/session/phase-completion.runtime.js +9 -3
  77. package/dist/session/phase-completion.schemas.js +12 -2
  78. package/dist/session/phase-completion.validation.d.ts +1 -0
  79. package/dist/session/phase-completion.validation.js +9 -1
  80. package/dist/session/pr-review-diff-base.d.ts +18 -0
  81. package/dist/session/pr-review-diff-base.js +45 -0
  82. package/dist/session/pr-review-placement.d.ts +50 -0
  83. package/dist/session/pr-review-placement.js +91 -0
  84. package/dist/session/pre-publication-change-set.d.ts +62 -0
  85. package/dist/session/pre-publication-change-set.js +166 -0
  86. package/dist/session/pre-publication-host-load.js +6 -5
  87. package/dist/session/pre-publication-process.js +3 -2
  88. package/dist/session/pre-publication-validation.d.ts +2 -1
  89. package/dist/session/pre-publication-validation.js +31 -36
  90. package/dist/session/provider-cli/dispatch-target-branch.d.ts +7 -0
  91. package/dist/session/provider-cli/dispatch-target-branch.js +8 -0
  92. package/dist/session/provider-cli/pr-review-credential-isolation.d.ts +83 -0
  93. package/dist/session/provider-cli/pr-review-credential-isolation.js +144 -0
  94. package/dist/session/provider-cli/pr-review-guardrails.d.ts +70 -0
  95. package/dist/session/provider-cli/pr-review-guardrails.js +360 -0
  96. package/dist/session/provider-cli/pr-review-prompt.d.ts +11 -0
  97. package/dist/session/provider-cli/pr-review-prompt.js +132 -0
  98. package/dist/session/provider-cli/pre-publication-repair.js +8 -3
  99. package/dist/session/provider-cli/provider-cli.base.d.ts +1 -0
  100. package/dist/session/provider-cli/provider-cli.deterministic.d.ts +1 -0
  101. package/dist/session/provider-cli/provider-cli.deterministic.js +5 -0
  102. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +6 -3
  103. package/dist/session/provider-cli/provider-cli.merge-integrity.js +29 -10
  104. package/dist/session/provider-cli/provider-cli.pr-review.d.ts +23 -0
  105. package/dist/session/provider-cli/provider-cli.pr-review.js +213 -0
  106. package/dist/session/provider-cli/provider-cli.prompts.d.ts +10 -3
  107. package/dist/session/provider-cli/provider-cli.prompts.js +123 -70
  108. package/dist/session/provider-cli/provider-cli.reapply-conflicts.d.ts +10 -0
  109. package/dist/session/provider-cli/provider-cli.reapply-conflicts.js +37 -0
  110. package/dist/session/provider-cli/provider-cli.runtime.d.ts +7 -0
  111. package/dist/session/provider-cli/provider-cli.runtime.js +14 -0
  112. package/dist/session/provider-cli/provider-cli.service-support.d.ts +37 -0
  113. package/dist/session/provider-cli/provider-cli.service-support.js +146 -0
  114. package/dist/session/provider-cli/provider-cli.service.d.ts +11 -17
  115. package/dist/session/provider-cli/provider-cli.service.js +33 -148
  116. package/dist/session/provider-cli/provider-cli.types.d.ts +7 -2
  117. package/dist/session/sandbox-host-capacity-gate.js +29 -7
  118. package/dist/session/session-host-project.d.ts +22 -0
  119. package/dist/session/session-host-project.js +98 -0
  120. package/dist/session/session.parse-helpers.d.ts +10 -0
  121. package/dist/session/session.parse-helpers.js +84 -0
  122. package/dist/session/session.runtime-refresh.d.ts +46 -0
  123. package/dist/session/session.runtime-refresh.js +116 -0
  124. package/dist/session/session.service.d.ts +2 -1
  125. package/dist/session/session.service.js +57 -158
  126. package/dist/session/session.types.d.ts +5 -0
  127. package/dist/session/session.types.js +8 -78
  128. package/dist/session/session.types.pr-review.d.ts +59 -0
  129. package/dist/session/session.types.pr-review.js +53 -0
  130. package/dist/shared/provider-capabilities.d.ts +2 -0
  131. package/dist/shared/provider-capabilities.js +9 -0
  132. package/dist/version.d.ts +1 -1
  133. package/dist/version.js +1 -1
  134. package/dist/worktree/artifact-injector.js +24 -0
  135. package/dist/worktree/wip-git.d.ts +25 -0
  136. package/dist/worktree/wip-git.js +64 -4
  137. package/dist/worktree/wip-refs.d.ts +23 -0
  138. package/dist/worktree/wip-refs.js +52 -2
  139. package/dist/worktree/wip-restore.d.ts +13 -0
  140. package/dist/worktree/wip-restore.js +159 -25
  141. package/dist/worktree/wip-snapshot.d.ts +5 -2
  142. package/dist/worktree/wip-snapshot.js +15 -13
  143. package/dist/worktree/worktree-origin-sync.d.ts +1 -0
  144. package/dist/worktree/worktree-origin-sync.js +1 -0
  145. package/dist/worktree/worktree-wip-events.d.ts +2 -0
  146. package/dist/worktree/worktree-wip-events.js +53 -3
  147. package/dist/worktree/worktree-wip.d.ts +7 -0
  148. package/dist/worktree/worktree-wip.js +17 -2
  149. package/dist/worktree/worktree.service.d.ts +23 -1
  150. package/dist/worktree/worktree.service.js +122 -15
  151. package/dist/worktree/worktree.types.d.ts +16 -0
  152. package/package.json +1 -1
@@ -1,8 +1,8 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import fs from "node:fs/promises";
3
3
  import path from "node:path";
4
- import { baseTrackedForgePaths, gitPath, isWipExcludedPath, makeWipTempDir, partialRestoreMarkerPath, splitNul, WipGit, } from "./wip-git.js";
5
- import { commitMessageOf, parseWipCommitMessage, wipRefPrefix, wipRefRoot, } from "./wip-refs.js";
4
+ import { baseTrackedForgePaths, gitPath, isWipExcludedPath, makeWipTempDir, partialRestoreMarkerPath, readOptionalFile, splitNul, WipGit, writeReapplyConflictRecord, } from "./wip-git.js";
5
+ import { commitMessageOf, hasConflictMarkerLines, hasNewConflictBlocks, issuedWipAttempt, parseWipCommitMessage, wipRefAttempt, wipRefPrefix, wipRefRoot, } from "./wip-refs.js";
6
6
  export async function restoreLatestWip(request) {
7
7
  const git = new WipGit(request.processRunner);
8
8
  let candidates;
@@ -18,18 +18,35 @@ export async function restoreLatestWip(request) {
18
18
  if (!await isCleanWorktree(git, request.worktreePath)) {
19
19
  return { status: "skipped_dirty", ref: newest.ref, commitSha: newest.commitSha };
20
20
  }
21
- // Clean again (the reset after a failed restore): its later snapshots may be applied as usual.
21
+ // Clean again (the reset after a failed restore): its later snapshots may be applied as usual, and
22
+ // no earlier re-apply's conflicts are left.
22
23
  await fs.rm(await partialRestoreMarkerPath(git, request.worktreePath), { force: true });
24
+ await writeReapplyConflictRecord(git, request.worktreePath, []);
23
25
  const currentHead = (await git.run(request.worktreePath, ["rev-parse", "HEAD"])).trim();
24
26
  const notRestored = (reason, detail) => ({
25
27
  status: "not_restored", ref: newest.ref, commitSha: newest.commitSha, reason,
26
28
  baseHead: newest.metadata.baseHead, currentHead, detail,
27
29
  });
30
+ let plan = null;
28
31
  if (newest.metadata.baseHead !== currentHead) {
29
- return notRestored("branch_moved", `${request.branchName} is at ${currentHead.slice(0, 12)}, but the snapshot was taken on ${newest.metadata.baseHead.slice(0, 12)}.`);
32
+ const moved = `${request.branchName} is at ${currentHead.slice(0, 12)}, but the snapshot was taken on ${newest.metadata.baseHead.slice(0, 12)}.`;
33
+ if (newest.metadata.mergeHead || newest.metadata.unmerged.length > 0) {
34
+ return notRestored("branch_moved", `${moved} It was taken during a merge, so it is not re-applied onto the moved branch.`);
35
+ }
36
+ try {
37
+ plan = await planReapply(git, request.worktreePath, newest, currentHead);
38
+ }
39
+ catch (error) {
40
+ return notRestored("branch_moved", `${moved} It could not be re-applied onto the new HEAD (${errorMessage(error)}).`);
41
+ }
30
42
  }
31
43
  try {
32
- const changedPaths = await applySnapshot(git, request.worktreePath, newest);
44
+ const changedPaths = plan
45
+ ? await applyReapply(git, request.worktreePath, currentHead, plan)
46
+ : await applySnapshot(git, request.worktreePath, newest);
47
+ // Conflicts with no MERGE_HEAD to show them: this re-apply's, and any the snapshot carried.
48
+ const reapplyConflicts = await restoredReapplyConflicts(git, request.worktreePath, newest, plan);
49
+ await writeReapplyConflictRecord(git, request.worktreePath, reapplyConflicts);
33
50
  return {
34
51
  status: "restored",
35
52
  ref: newest.ref,
@@ -38,6 +55,10 @@ export async function restoreLatestWip(request) {
38
55
  sourceSessionId: newest.metadata.sessionId,
39
56
  changedPaths,
40
57
  mergeInProgress: Boolean(newest.metadata.mergeHead),
58
+ reapplied: plan
59
+ ? { snapshotBaseHead: newest.metadata.baseHead, conflictedPaths: [...new Set(plan.unmerged.map(entry => entry.path))].sort() }
60
+ : null,
61
+ reapplyConflicts,
41
62
  };
42
63
  }
43
64
  catch (error) {
@@ -45,7 +66,7 @@ export async function restoreLatestWip(request) {
45
66
  // the prepare fails. Nothing is lost; the ref stays, and the next prepare saves this worktree
46
67
  // before it resets it. That snapshot holds the mixed state, so it is marked never to be applied
47
68
  // automatically (partialRestoreMarkerPath): the next pass restores the original ref instead.
48
- await rollBack(git, request.worktreePath, newest).catch(async (rollbackError) => {
69
+ await rollBack(git, request.worktreePath, currentHead, plan?.worktreeTree ?? newest.commitSha).catch(async (rollbackError) => {
49
70
  await partialRestoreMarkerPath(git, request.worktreePath)
50
71
  .then(marker => fs.writeFile(marker, `${newest.ref}\n`, "utf8"))
51
72
  .catch(() => undefined);
@@ -100,14 +121,24 @@ async function readRefs(git, repoPath, namespace, wipPrefix) {
100
121
  }
101
122
  return candidates;
102
123
  }
103
- /** The newest snapshot of this branch a pass may apply; one recorded for any other branch never is. */
124
+ /**
125
+ * The newest snapshot of this branch a pass may apply; one recorded for any other branch never is.
126
+ * Newest work wins: Forge's attempt number first (a later dispatch attempt always has a larger one,
127
+ * and a snapshot without one is attempt 0), then the snapshot's own time within an attempt.
128
+ */
104
129
  function newestRestorable(candidates, branchName) {
105
130
  const branch = branchRefName(branchName);
106
131
  return [...candidates]
107
132
  .filter(candidate => candidate.metadata.autoRestore && branchRefName(candidate.metadata.branch) === branch)
108
- .sort((left, right) => right.metadata.createdAtMs - left.metadata.createdAtMs || right.ref.localeCompare(left.ref))[0]
133
+ .sort((left, right) => candidateAttempt(right) - candidateAttempt(left)
134
+ || right.metadata.createdAtMs - left.metadata.createdAtMs || right.ref.localeCompare(left.ref))[0]
109
135
  ?? null;
110
136
  }
137
+ // The metadata attempt counts only when it is one Forge could have issued (0 through the ref's ten digits);
138
+ // anything else is attempt 0, so a malformed snapshot can never outrank a real one.
139
+ function candidateAttempt(candidate) {
140
+ return Math.max(wipRefAttempt(candidate.ref), issuedWipAttempt(candidate.metadata.attempt));
141
+ }
111
142
  /** True when the worktree holds nothing a snapshot would save (Forge runtime output aside), and no merge. */
112
143
  export async function hasNoUnsavedWork(worktreePath, processRunner) {
113
144
  return await isCleanWorktree(new WipGit(processRunner), worktreePath);
@@ -119,14 +150,117 @@ async function isCleanWorktree(git, worktreePath) {
119
150
  const status = splitNul(await git.run(worktreePath, ["status", "--porcelain=v1", "-z", "--untracked-files=all", "--no-renames"]));
120
151
  return status.every(entry => isWipExcludedPath(entry.slice(3), forgePaths));
121
152
  }
153
+ /**
154
+ * The re-apply conflicts the restored worktree holds: the snapshot's record, and this re-apply's
155
+ * conflicts. A snapshot taken outside a merge can only hold conflict stages or markers that an
156
+ * earlier re-apply left (the agent never got to resolve them, as when a prepare step failed before
157
+ * it started), so its stages count too. One with no record and no stages (taken before snapshots
158
+ * carried the record), restored as it was or re-applied across a move, counts the paths whose
159
+ * snapshot version added conflict blocks its base did not have and whose restored file still has
160
+ * markers: Git merges marker text as ordinary content, so a re-apply can carry them over cleanly.
161
+ */
162
+ async function restoredReapplyConflicts(git, worktreePath, candidate, plan) {
163
+ const { metadata } = candidate;
164
+ const paths = new Set([...metadata.reapplyConflicts, ...(plan?.unmerged ?? []).map(entry => entry.path)]);
165
+ if (metadata.mergeHead)
166
+ return [...paths].sort();
167
+ if (!plan)
168
+ for (const entry of metadata.unmerged)
169
+ paths.add(entry.path);
170
+ if (metadata.reapplyConflicts.length === 0 && metadata.unmerged.length === 0) {
171
+ for (const filePath of await newConflictMarkerPaths(git, worktreePath, candidate))
172
+ paths.add(filePath);
173
+ }
174
+ return [...paths].sort();
175
+ }
176
+ /** Paths whose snapshot version added conflict blocks to its base version, still marked in the worktree. */
177
+ async function newConflictMarkerPaths(git, worktreePath, candidate) {
178
+ const { baseHead } = candidate.metadata;
179
+ const changes = await snapshotChanges(git, worktreePath, baseHead, candidate.commitSha);
180
+ const found = [];
181
+ for (const change of changes.filter(entry => entry.status !== "D")) {
182
+ const saved = await git.tryRun(worktreePath, ["cat-file", "blob", `${candidate.commitSha}:${change.path}`]);
183
+ if (saved === null || !hasConflictMarkerLines(saved))
184
+ continue;
185
+ const base = await git.tryRun(worktreePath, ["cat-file", "blob", `${baseHead}:${change.path}`]);
186
+ if (!hasNewConflictBlocks(saved, base))
187
+ continue;
188
+ // Only an absent file has no markers; any other read failure fails the restore (rolled back).
189
+ const restored = await readOptionalFile(path.join(worktreePath, change.path));
190
+ if (restored !== null && hasConflictMarkerLines(restored))
191
+ found.push(change.path);
192
+ }
193
+ return found;
194
+ }
122
195
  /** Writes the snapshot's files and index (and merge state) onto the clean worktree. */
123
196
  async function applySnapshot(git, worktreePath, candidate) {
124
197
  const { commitSha, metadata } = candidate;
125
- const changes = await snapshotChanges(git, worktreePath, metadata.baseHead, commitSha);
198
+ const changedPaths = await writeWorktreeTree(git, worktreePath, metadata.baseHead, commitSha);
199
+ await git.run(worktreePath, ["read-tree", `${commitSha}^2^{tree}`]);
200
+ if (metadata.unmerged.length > 0)
201
+ await writeUnmergedEntries(git, worktreePath, metadata.unmerged, metadata.baseHead.length);
202
+ if (metadata.mergeHead)
203
+ await writeMergeState(git, worktreePath, metadata);
204
+ await git.tryRun(worktreePath, ["update-index", "-q", "--refresh"]);
205
+ return changedPaths;
206
+ }
207
+ /**
208
+ * Merges the snapshot onto the moved branch without touching the worktree. The worktree's tree is
209
+ * `git merge-tree` of the snapshot's base, the new HEAD and the snapshot (W); the index is the same
210
+ * merge of the snapshot's staged state (W^2) when that is clean, else the new HEAD's tree (all the
211
+ * content is in the worktree either way). A conflict comes back as the merge's stage 1-3 entries.
212
+ */
213
+ async function planReapply(git, worktreePath, candidate, currentHead) {
214
+ const base = candidate.metadata.baseHead;
215
+ const worktree = await mergeTree(git, worktreePath, base, currentHead, candidate.commitSha);
216
+ const index = await mergeTree(git, worktreePath, base, currentHead, `${candidate.commitSha}^2`);
217
+ return {
218
+ worktreeTree: worktree.tree,
219
+ indexTree: index.unmerged.length === 0 ? index.tree : `${currentHead}^{tree}`,
220
+ unmerged: worktree.unmerged,
221
+ };
222
+ }
223
+ /** Writes a re-apply's merged files, index and conflict stages onto the clean worktree at `currentHead`. */
224
+ async function applyReapply(git, worktreePath, currentHead, plan) {
225
+ const changedPaths = await writeWorktreeTree(git, worktreePath, currentHead, plan.worktreeTree);
226
+ await git.run(worktreePath, ["read-tree", plan.indexTree]);
227
+ if (plan.unmerged.length > 0)
228
+ await writeUnmergedEntries(git, worktreePath, plan.unmerged, currentHead.length);
229
+ await git.tryRun(worktreePath, ["update-index", "-q", "--refresh"]);
230
+ return changedPaths;
231
+ }
232
+ /** `git merge-tree --write-tree` (Git 2.40+): the merged tree, with its conflict stages when it conflicts. */
233
+ async function mergeTree(git, worktreePath, base, ours, theirs) {
234
+ const args = ["merge-tree", "--write-tree", "-z", "--no-messages", `--merge-base=${base}`, ours, theirs];
235
+ const result = await git.runWithStatus(worktreePath, args);
236
+ if (result.exitCode !== 0 && result.exitCode !== 1) {
237
+ throw new Error(`git ${args.join(" ")} failed: ${result.stderr.trim() || result.stdout.trim()}`);
238
+ }
239
+ // <tree> NUL, then one "<mode> <object> <stage>\t<path>" NUL per conflict stage, then an empty field.
240
+ const [tree = "", ...records] = result.stdout.split("\0");
241
+ const unmerged = [];
242
+ for (const record of records) {
243
+ const match = /^(\d{6}) ([0-9a-f]+) ([123])\t([\s\S]+)$/u.exec(record);
244
+ if (!match)
245
+ break;
246
+ unmerged.push({ mode: match[1], sha: match[2], stage: Number(match[3]), path: match[4] });
247
+ }
248
+ if (!/^[0-9a-f]+$/u.test(tree.trim()))
249
+ throw new Error(`git merge-tree returned no tree (${result.stderr.trim()})`);
250
+ if (result.exitCode === 1 && unmerged.length === 0)
251
+ throw new Error("git merge-tree reported a conflict without conflict stages");
252
+ return { tree: tree.trim(), unmerged };
253
+ }
254
+ /**
255
+ * Turns a clean worktree at `from` into the tree `to` (files only; the caller sets the index): writes
256
+ * the paths `to` adds or changes and deletes the ones it drops. Returns how many paths changed.
257
+ */
258
+ async function writeWorktreeTree(git, worktreePath, from, to) {
259
+ const changes = await snapshotChanges(git, worktreePath, from, to);
126
260
  const tempDir = await makeWipTempDir();
127
261
  try {
128
262
  const snapshotIndex = git.with({ GIT_INDEX_FILE: path.join(tempDir, "snapshot.index") });
129
- await snapshotIndex.run(worktreePath, ["read-tree", commitSha]);
263
+ await snapshotIndex.run(worktreePath, ["read-tree", to]);
130
264
  const written = changes.filter(change => change.status !== "D").map(change => change.path);
131
265
  await snapshotIndex.runForPaths(worktreePath, ["checkout-index", "-f"], written, false);
132
266
  }
@@ -136,12 +270,6 @@ async function applySnapshot(git, worktreePath, candidate) {
136
270
  for (const change of changes.filter(entry => entry.status === "D")) {
137
271
  await fs.rm(path.join(worktreePath, change.path), { force: true });
138
272
  }
139
- await git.run(worktreePath, ["read-tree", `${commitSha}^2^{tree}`]);
140
- if (metadata.unmerged.length > 0)
141
- await restoreUnmergedEntries(git, worktreePath, metadata);
142
- if (metadata.mergeHead)
143
- await writeMergeState(git, worktreePath, metadata);
144
- await git.tryRun(worktreePath, ["update-index", "-q", "--refresh"]);
145
273
  return changes.length;
146
274
  }
147
275
  async function snapshotChanges(git, worktreePath, base, commitSha) {
@@ -152,13 +280,16 @@ async function snapshotChanges(git, worktreePath, base, commitSha) {
152
280
  }
153
281
  return changes;
154
282
  }
155
- /** Puts the conflict stages back, so a half-done merge resumes exactly where it stopped. */
156
- async function restoreUnmergedEntries(git, worktreePath, metadata) {
157
- const zero = "0".repeat(metadata.baseHead.length);
158
- const conflicted = [...new Set(metadata.unmerged.map(entry => entry.path))];
283
+ /**
284
+ * Puts conflict stages into the index: a restored half-done merge resumes exactly where it stopped,
285
+ * and a conflicting re-apply is left unmerged for the agent.
286
+ */
287
+ async function writeUnmergedEntries(git, worktreePath, unmerged, hashLength) {
288
+ const zero = "0".repeat(hashLength);
289
+ const conflicted = [...new Set(unmerged.map(entry => entry.path))];
159
290
  const records = [
160
291
  ...conflicted.map(filePath => `0 ${zero} 0\t${filePath}`),
161
- ...metadata.unmerged.map(entry => `${entry.mode} ${entry.sha} ${entry.stage}\t${entry.path}`),
292
+ ...unmerged.map(entry => `${entry.mode} ${entry.sha} ${entry.stage}\t${entry.path}`),
162
293
  ];
163
294
  await git.runWithInput(worktreePath, ["update-index", "-z", "--index-info"], `${records.join("\0")}\0`);
164
295
  }
@@ -168,13 +299,16 @@ async function writeMergeState(git, worktreePath, metadata) {
168
299
  if (metadata.mergeMode)
169
300
  await fs.writeFile(await gitPath(git, worktreePath, "MERGE_MODE"), `${metadata.mergeMode}\n`, "utf8");
170
301
  }
171
- /** Undoes a partial apply: the worktree was clean at the base before it started. */
172
- async function rollBack(git, worktreePath, candidate) {
302
+ /**
303
+ * Undoes a partial apply of `target` (the snapshot, or a re-apply's merged tree): the worktree was
304
+ * clean at `head` before it started.
305
+ */
306
+ async function rollBack(git, worktreePath, head, target) {
173
307
  for (const name of ["MERGE_HEAD", "MERGE_MSG", "MERGE_MODE"]) {
174
308
  await fs.rm(await gitPath(git, worktreePath, name), { force: true });
175
309
  }
176
- await git.run(worktreePath, ["read-tree", "--reset", "-u", candidate.metadata.baseHead]);
177
- const changes = await snapshotChanges(git, worktreePath, candidate.metadata.baseHead, candidate.commitSha);
310
+ await git.run(worktreePath, ["read-tree", "--reset", "-u", head]);
311
+ const changes = await snapshotChanges(git, worktreePath, head, target);
178
312
  for (const change of changes.filter(entry => entry.status === "A")) {
179
313
  await fs.rm(path.join(worktreePath, change.path), { force: true });
180
314
  }
@@ -6,8 +6,11 @@ export interface WipSnapshotRequest {
6
6
  readonly reason: WipSnapshotReason;
7
7
  readonly sessionId?: string | null;
8
8
  readonly lane?: string | null;
9
- /** Forge's attempt number for the story; unorderedWipAttempt until the server sends one. */
10
- readonly attempt?: number;
9
+ /**
10
+ * Forge's attempt number for the dispatch (sandbox.wipAttempt), stamped on the ref and metadata so
11
+ * the newest work wins on restore; without one (or out of range) the snapshot is attempt 0.
12
+ */
13
+ readonly attempt?: number | null;
11
14
  /** Whether a later pass may apply this snapshot by itself (wip-restore.ts). */
12
15
  readonly autoRestore: boolean;
13
16
  /** Overrides FORGE_WIP_SNAPSHOT_MAX_BYTES. */
@@ -1,7 +1,7 @@
1
1
  import fs from "node:fs/promises";
2
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";
3
+ import { baseTrackedForgePaths, gitPath, hasPartialRestoreMarker, isWipExcludedPath, makeWipTempDir, readOptionalFile, readReapplyConflictRecord, splitNul, WipGit, } from "./wip-git.js";
4
+ import { formatWipCommitMessage, issuedWipAttempt, WipPreservationError, wipMetadataSchema, wipRefId, wipRefName, wipSnapshotMaxBytes, } from "./wip-refs.js";
5
5
  const mergeMessageLimit = 16 * 1024;
6
6
  // Snapshots this process already pushed, keyed by worktree: a guard that finds the same state
7
7
  // (for example the release right after a failed session's snapshot) does not push it twice. An
@@ -73,6 +73,8 @@ async function captureWorktree(request, context) {
73
73
  const base = (await git.run(cwd, ["rev-parse", "--verify", `${request.orphan?.baseRef ?? "HEAD"}^{commit}`])).trim();
74
74
  const baseTree = (await git.run(cwd, ["rev-parse", `${base}^{tree}`])).trim();
75
75
  const merge = request.orphan ? null : await readMergeState(git, cwd);
76
+ const unmerged = request.orphan ? [] : splitNul(await git.run(cwd, ["ls-files", "-u", "-z"])).map(parseUnmergedEntry);
77
+ const reapplyConflicts = request.orphan ? [] : await readReapplyConflictRecord(git, cwd);
76
78
  const forgePaths = await baseTrackedForgePaths(git, cwd, base);
77
79
  const excluded = (filePath) => isWipExcludedPath(filePath, forgePaths);
78
80
  const worktreeIndex = path.join(context.tempDir, "worktree.index");
@@ -83,13 +85,13 @@ async function captureWorktree(request, context) {
83
85
  await copyIndex(worktreeIndex, stagedIndex);
84
86
  const indexTree = request.orphan
85
87
  ? baseTree
86
- : await writeStagedTree(git.with({ GIT_INDEX_FILE: stagedIndex }), cwd, base, merge, excluded);
88
+ : await writeStagedTree(git.with({ GIT_INDEX_FILE: stagedIndex }), cwd, base, unmerged, excluded);
87
89
  await indexGit.run(cwd, ["add", "-A"]);
88
90
  const changed = await resetExcluded(indexGit, cwd, base, excluded);
89
91
  const worktreeTree = (await indexGit.run(cwd, ["write-tree"])).trim();
90
- if (worktreeTree === baseTree && indexTree === baseTree && !merge)
92
+ if (worktreeTree === baseTree && indexTree === baseTree && !merge && unmerged.length === 0)
91
93
  return null;
92
- return { base, worktreeTree, indexTree, merge, changedPaths: changed.length, bytes };
94
+ return { base, worktreeTree, indexTree, merge, unmerged, reapplyConflicts, changedPaths: changed.length, bytes };
93
95
  }
94
96
  /** A copy of the worktree's real index; the base tree when it has none or the checkout is orphaned. */
95
97
  async function seedIndex(context, request, base, target) {
@@ -143,8 +145,8 @@ async function measureChanges(git, cwd, base, excluded, maxBytes) {
143
145
  return total;
144
146
  }
145
147
  /** 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
+ async function writeStagedTree(git, cwd, base, unmerged, excluded) {
149
+ const conflicted = [...new Set(unmerged.map(entry => entry.path))];
148
150
  await git.runForPaths(cwd, ["reset", "-q", base], conflicted);
149
151
  await resetExcluded(git, cwd, base, excluded);
150
152
  return (await git.run(cwd, ["write-tree"])).trim();
@@ -165,12 +167,10 @@ async function readMergeState(git, cwd) {
165
167
  return null;
166
168
  const message = await readOptionalFile(await gitPath(git, cwd, "MERGE_MSG"));
167
169
  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
170
  return {
170
171
  head,
171
172
  message: message === null ? null : message.slice(0, mergeMessageLimit),
172
173
  mode: mode?.trim() || null,
173
- unmerged,
174
174
  };
175
175
  }
176
176
  function parseUnmergedEntry(record) {
@@ -191,14 +191,15 @@ async function writeSnapshotCommits(request, capture, context) {
191
191
  sessionId: request.sessionId?.trim() || null,
192
192
  lane: request.lane?.trim() || null,
193
193
  reason: request.reason,
194
- attempt: request.attempt ?? unorderedWipAttempt,
194
+ attempt: issuedWipAttempt(request.attempt),
195
195
  autoRestore: request.autoRestore,
196
196
  createdAt: now.toISOString(),
197
197
  createdAtMs: now.getTime(),
198
198
  mergeHead: capture.merge?.head ?? null,
199
199
  mergeMessage: capture.merge?.message ?? null,
200
200
  mergeMode: capture.merge?.mode ?? null,
201
- unmerged: capture.merge?.unmerged ?? [],
201
+ unmerged: capture.unmerged,
202
+ reapplyConflicts: capture.reapplyConflicts,
202
203
  changedPaths: capture.changedPaths,
203
204
  bytes: capture.bytes,
204
205
  };
@@ -214,7 +215,7 @@ async function writeSnapshotCommits(request, capture, context) {
214
215
  */
215
216
  async function publishSnapshot(git, repoPath, request, commitSha) {
216
217
  const now = (request.now ?? (() => new Date()))();
217
- const ref = wipRefName(request.branchName, wipRefId(request.reason, request.sessionId, now, request.attempt));
218
+ const ref = wipRefName(request.branchName, wipRefId(request.reason, request.sessionId, now, issuedWipAttempt(request.attempt)));
218
219
  const origin = (await git.tryRun(repoPath, ["remote", "get-url", "origin"]))?.trim();
219
220
  if (!origin) {
220
221
  await git.run(repoPath, ["update-ref", ref, commitSha]);
@@ -239,7 +240,8 @@ async function commonGitDir(git, repoPath) {
239
240
  return path.isAbsolute(raw) ? raw : path.resolve(repoPath, raw);
240
241
  }
241
242
  function captureFingerprint(capture) {
242
- return [capture.base, capture.worktreeTree, capture.indexTree, capture.merge?.head ?? ""].join(":");
243
+ const stages = capture.unmerged.map(entry => `${entry.stage}${entry.sha}${entry.path}`).join(",");
244
+ return [capture.base, capture.worktreeTree, capture.indexTree, capture.merge?.head ?? "", stages, capture.reapplyConflicts.join(",")].join(":");
243
245
  }
244
246
  function snapshotKey(worktreePath) {
245
247
  const resolved = path.resolve(worktreePath);
@@ -9,6 +9,7 @@ export interface ReusedWorktreeSyncRequest {
9
9
  readonly branchName: string;
10
10
  readonly sessionId?: string | null;
11
11
  readonly lane: string;
12
+ readonly wipAttempt?: number | null;
12
13
  readonly log: BridgeLog;
13
14
  }
14
15
  /**
@@ -44,6 +44,7 @@ export async function syncReusedWorktreeToOrigin(request) {
44
44
  reason: "pre_sync",
45
45
  sessionId: request.sessionId,
46
46
  lane: request.lane,
47
+ attempt: request.wipAttempt,
47
48
  // It was based on the old head, so a later pass must never apply it on the new one by itself.
48
49
  autoRestore: false,
49
50
  }).catch((error) => {
@@ -15,4 +15,6 @@ export declare function sessionWipOutcome(signal: AbortSignal | undefined, event
15
15
  * reported as a cleanup failure.
16
16
  */
17
17
  export declare function settleWorktree(worktrees: WorktreeService, worktree: WorktreeHandle, outcome: WipSessionOutcome, signal: AbortSignal | undefined, emit: Emit): Promise<void>;
18
+ /** The checkpoint for a project start held back until the agent resolves the re-apply conflicts. */
19
+ export declare function deferredProjectStartEvent(paths: readonly string[]): RunnerDispatchEvent;
18
20
  export {};
@@ -3,9 +3,13 @@ export async function emitWipRestoreEvent(worktree, emit) {
3
3
  const outcome = worktree.wipRestore;
4
4
  if (!outcome || outcome.status === "none")
5
5
  return;
6
- if (outcome.status === "restored") {
6
+ if (outcome.status === "restored" && outcome.reapplied) {
7
+ await emit(checkpoint("worktree_wip_restored", reappliedSummary(worktree.branchName, outcome, outcome.reapplied), outcome));
8
+ }
9
+ else if (outcome.status === "restored") {
7
10
  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));
11
+ + `(${outcome.changedPaths} path(s)${outcome.mergeInProgress ? ", with its merge still in progress" : ""}) onto ${worktree.branchName} before the provider started.`
12
+ + carriedConflictsText(outcome.reapplyConflicts), outcome));
9
13
  }
10
14
  else if (outcome.status === "not_restored") {
11
15
  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"}. `
@@ -18,6 +22,28 @@ export async function emitWipRestoreEvent(worktree, emit) {
18
22
  await emit(checkpoint("worktree_wip_restore_unavailable", `Could not check origin for saved uncommitted work on ${worktree.branchName}: ${outcome.detail}`, outcome));
19
23
  }
20
24
  }
25
+ /** The checkpoint for a snapshot re-applied across a branch move: clean, or with the paths left for the agent. */
26
+ function reappliedSummary(branchName, outcome, reapplied) {
27
+ const moved = `${branchName} had moved from ${reapplied.snapshotBaseHead.slice(0, 12)} to ${outcome.baseHead.slice(0, 12)} since it was saved`;
28
+ if (reapplied.conflictedPaths.length === 0) {
29
+ return `Re-applied the uncommitted work saved in ${outcome.ref} across a branch move (${moved}): a 3-way merge onto the new HEAD `
30
+ + `was clean (${outcome.changedPaths} path(s)) and is restored before the provider started.`;
31
+ }
32
+ const listed = reapplied.conflictedPaths.slice(0, maxListedConflicts).join(", ");
33
+ const more = reapplied.conflictedPaths.length > maxListedConflicts ? ` and ${reapplied.conflictedPaths.length - maxListedConflicts} more` : "";
34
+ return `Re-applied the uncommitted work saved in ${outcome.ref} across a branch move with ${reapplied.conflictedPaths.length} conflict(s) `
35
+ + `left for the agent to resolve: ${listed}${more}. ${moved}; the conflicted paths are unmerged with conflict markers, `
36
+ + `Forge will not publish them unresolved, and the ref is kept on origin.`;
37
+ }
38
+ const maxListedConflicts = 20;
39
+ /** For a snapshot restored as it was: the unresolved conflicts an earlier re-apply left in it. */
40
+ function carriedConflictsText(paths) {
41
+ if (paths.length === 0)
42
+ return "";
43
+ const more = paths.length > maxListedConflicts ? ` and ${paths.length - maxListedConflicts} more` : "";
44
+ return ` It still holds ${paths.length} conflict(s) from an earlier re-apply for the agent to resolve: `
45
+ + `${paths.slice(0, maxListedConflicts).join(", ")}${more}.`;
46
+ }
21
47
  /** How a session ended, for the snapshot it leaves behind. */
22
48
  export function sessionWipOutcome(signal, events, succeeded) {
23
49
  if (succeeded)
@@ -72,7 +98,7 @@ async function emitSettlement(worktree, outcome, settlement, emit) {
72
98
  const snapshot = settlement.snapshot;
73
99
  if (snapshot && snapshot.status !== "clean") {
74
100
  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 }));
101
+ + `before the session ended (${outcome.reason}). The next pass on ${worktree.branchName} restores it, re-applying it if the branch has moved.`, { ...snapshot, reason: outcome.reason, lane: worktree.lane ?? null }));
76
102
  }
77
103
  if (settlement.error) {
78
104
  await emit({
@@ -96,3 +122,27 @@ function checkpoint(eventType, content, data) {
96
122
  function messageOf(error) {
97
123
  return error instanceof Error ? error.message : String(error);
98
124
  }
125
+ // A WIP re-apply across a branch move can leave conflicts for the agent to resolve (wip-restore.ts):
126
+ // unmerged paths with conflict markers, kept in the worktree's re-apply conflict record. Those
127
+ // markers break any build of the worktree, so a host-runtime project start (the ASP.NET prebuild)
128
+ // would fail in prepare, before the agent could ever resolve them; the failure would be saved into
129
+ // the next snapshot, re-applied, and fail the same way on every retry. So while recorded conflicts
130
+ // are unresolved the session does not start the project stack: the agent runs first, is told which
131
+ // paths to resolve, and pre-publication validation then starts the stack from the resolved source
132
+ // (a failure there is a repair turn, not a prepare failure). The prepared-readiness probe skips such
133
+ // a worktree too (prepared-runtime-readiness.ts), and the prompt names the paths
134
+ // (withReapplyConflictInstruction in provider-cli.prompts.ts).
135
+ /** The checkpoint for a project start held back until the agent resolves the re-apply conflicts. */
136
+ export function deferredProjectStartEvent(paths) {
137
+ const listed = paths.slice(0, maxListedConflicts).join(", ");
138
+ const more = paths.length > maxListedConflicts ? ` and ${paths.length - maxListedConflicts} more` : "";
139
+ return {
140
+ role: "runner",
141
+ kind: "checkpoint",
142
+ content: `Deferred the attempt's application stack start: ${paths.length} path(s) restored from saved work still have unresolved `
143
+ + `re-apply conflicts (${listed}${more}), which would fail its build. The agent resolves them first; Forge starts the stack `
144
+ + "before pre-publication validation.",
145
+ eventType: "host_runtime_project_start_deferred",
146
+ data: JSON.stringify({ reason: "wip_reapply_conflicts", reapply_conflicts: paths }),
147
+ };
148
+ }
@@ -11,6 +11,7 @@ export { relinkOrphanedWorktree } from "./orphan-relink.js";
11
11
  export declare function guardWorktreeReset(worktreePath: string, branchName: string, owner: {
12
12
  readonly sessionId?: string | null;
13
13
  readonly lane: string;
14
+ readonly wipAttempt?: number | null;
14
15
  }): Promise<WipSnapshotResult>;
15
16
  /**
16
17
  * Before a local branch is re-pointed at a new start point (`worktree add -B`), saves any commits
@@ -27,6 +28,12 @@ export declare function restoreWorktreeWip(input: {
27
28
  readonly sessionId?: string | null;
28
29
  readonly lane: string;
29
30
  }): Promise<WipRestoreOutcome | undefined>;
31
+ /**
32
+ * The worktree's recorded WIP re-apply conflicts that still have conflict stages or markers (see
33
+ * wipReapplyConflictRecordName); [] when there are none. Throws when the record or the index cannot
34
+ * be read: an unknown conflict state is never treated as conflict-free.
35
+ */
36
+ export declare function unresolvedWorktreeReapplyConflicts(worktreePath: string): Promise<readonly string[]>;
30
37
  /**
31
38
  * Saves a worktree that is about to be deleted. Its snapshot is never applied automatically (a
32
39
  * session that ended without succeeding has already saved its own work under its id; what is
@@ -1,6 +1,6 @@
1
1
  import { liveLeaseBranches, readHostRuntimeLeases } from "../cleanup/host-runtime-ledger.js";
2
2
  import { deleteBranchIfUnused, isRuntimeReadinessBranch, sweepManagedBranches } from "../cleanup/managed-branch-sweep.js";
3
- import { WipGit } from "./wip-git.js";
3
+ import { unresolvedReapplyConflicts, WipGit } from "./wip-git.js";
4
4
  import { formatWipCommitMessage, unorderedWipAttempt, wipMetadataSchema, WipPreservationError, wipRefId, wipRefName, } from "./wip-refs.js";
5
5
  import { deleteWipRef, hasNoUnsavedWork, restoreLatestWip } from "./wip-restore.js";
6
6
  import { forgetPreservedWip, forgetPreservedWipRef, preserveWorktreeWip } from "./wip-snapshot.js";
@@ -8,7 +8,8 @@ import { forgetPreservedWip, forgetPreservedWipRef, preserveWorktreeWip } from "
8
8
  // - every path that could destroy it (a reset to the base, re-pointing the branch, a release that
9
9
  // deletes the checkout) saves it to a WIP ref first and does not run when that fails;
10
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;
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);
12
13
  // - a checkout that lost only its `.git` link is reattached to Git's admin directory for it, which
13
14
  // holds its index and MERGE_HEAD, instead of being recreated (orphan-relink.ts).
14
15
  export { relinkOrphanedWorktree } from "./orphan-relink.js";
@@ -30,6 +31,7 @@ export async function guardWorktreeReset(worktreePath, branchName, owner) {
30
31
  reason: "pre_reset",
31
32
  sessionId: owner.sessionId,
32
33
  lane: owner.lane,
34
+ attempt: owner.wipAttempt,
33
35
  autoRestore: isWipRestoreLane(owner.lane),
34
36
  });
35
37
  }
@@ -84,6 +86,7 @@ async function branchTipSnapshot(repoPath, branchName, tip, now) {
84
86
  mergeMessage: null,
85
87
  mergeMode: null,
86
88
  unmerged: [],
89
+ reapplyConflicts: [],
87
90
  changedPaths: 0,
88
91
  bytes: 0,
89
92
  });
@@ -95,6 +98,16 @@ export async function restoreWorktreeWip(input) {
95
98
  return undefined;
96
99
  return await restoreLatestWip(input);
97
100
  }
101
+ /**
102
+ * The worktree's recorded WIP re-apply conflicts that still have conflict stages or markers (see
103
+ * wipReapplyConflictRecordName); [] when there are none. Throws when the record or the index cannot
104
+ * be read: an unknown conflict state is never treated as conflict-free.
105
+ */
106
+ export async function unresolvedWorktreeReapplyConflicts(worktreePath) {
107
+ return await unresolvedReapplyConflicts(new WipGit(), worktreePath).catch((error) => {
108
+ throw new Error(`the record of conflicts from re-applied saved work could not be read: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
109
+ });
110
+ }
98
111
  /**
99
112
  * Saves a worktree that is about to be deleted. Its snapshot is never applied automatically (a
100
113
  * session that ended without succeeding has already saved its own work under its id; what is
@@ -110,6 +123,7 @@ export async function guardWorktreeRelease(handle) {
110
123
  reason: "pre_release",
111
124
  sessionId: handle.sessionId,
112
125
  lane: handle.lane,
126
+ attempt: handle.wipAttempt,
113
127
  autoRestore: false,
114
128
  });
115
129
  }
@@ -134,6 +148,7 @@ export async function settleSessionWip(handle, outcome) {
134
148
  reason: outcome.reason,
135
149
  sessionId: handle.sessionId,
136
150
  lane: handle.lane,
151
+ attempt: handle.wipAttempt,
137
152
  autoRestore: isWipRestoreLane(handle.lane),
138
153
  });
139
154
  }
@@ -3,7 +3,7 @@ import type { HostLoadStepGate } from "../runtime/host-load-governor.js";
3
3
  import type { WorktreeLifecycleCoordinator, WorktreeService } from "./worktree.base.js";
4
4
  import type { WipSessionOutcome, WipSettlement, WorktreeHandle, WorktreePrepareRequest } from "./worktree.types.js";
5
5
  import { type BridgeLog } from "./worktree-origin-sync.js";
6
- export { emitWipRestoreEvent, sessionWipOutcome, settleWorktree } from "./worktree-wip-events.js";
6
+ export { deferredProjectStartEvent, emitWipRestoreEvent, sessionWipOutcome, settleWorktree } from "./worktree-wip-events.js";
7
7
  export { emitWorktreePreparedEvents } from "./worktree-origin-sync.js";
8
8
  export { clearRunArtifactRoots } from "./worktree-inputs.js";
9
9
  export declare class GitWorktreeService implements WorktreeService {
@@ -23,6 +23,23 @@ export declare class GitWorktreeService implements WorktreeService {
23
23
  /** The bridge log: prepare records its start point and what it did to a reused worktree. */
24
24
  log?: BridgeLog);
25
25
  prepare(request: WorktreePrepareRequest): Promise<WorktreeHandle>;
26
+ /**
27
+ * Creates the lease's worktree. A review's is detached at the review head: no lease branch is
28
+ * created and no WIP is restored. Any other is on the lease branch with the story's WIP restored.
29
+ */
30
+ private createWorktree;
31
+ /**
32
+ * Readies a surviving worktree. A review reads one exact commit, so whatever state a prior attempt
33
+ * left behind is discarded. Any other must still be on the lease branch; it is refreshed for this
34
+ * pass and given the story's WIP.
35
+ */
36
+ private reuseWorktree;
37
+ /**
38
+ * Finds the review head in the repository, fetching it when the local clone has not seen it
39
+ * yet, and returns the full commit id.
40
+ */
41
+ private resolveReviewHead;
42
+ private assertDetachedAtHead;
26
43
  private warmDependencies;
27
44
  /** Restores the story's saved WIP (still under the repository lock, before the provider starts). */
28
45
  private withRestoredWip;
@@ -38,6 +55,11 @@ export declare class GitWorktreeService implements WorktreeService {
38
55
  private registeredManagedWorktreePath;
39
56
  private repoCreationCoordinationPath;
40
57
  release(handle: WorktreeHandle): Promise<void>;
58
+ /**
59
+ * Removes a review worktree without saving anything from it (see settleWip). A failed removal leaves
60
+ * the folder for the next prepare of that head, which resets and cleans it, or for stale cleanup.
61
+ */
62
+ private removeReviewWorktree;
41
63
  private restoreOrphanedWorktree;
42
64
  private resolveRepoPath;
43
65
  private managedRepoPath;