@loucompanion/forge-bridge 0.1.4-dev.e83e5bc6ecce → 0.1.4-dev.ec3460040366

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 (212) 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 +88 -14
  16. package/dist/bridge/bridge.service.js +406 -345
  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 +11 -1
  31. package/dist/cleanup/cleanup.service.js +80 -62
  32. package/dist/cleanup/cleanup.types.d.ts +2 -0
  33. package/dist/cleanup/host-runtime-ledger.d.ts +2 -0
  34. package/dist/cleanup/host-runtime-ledger.js +30 -9
  35. package/dist/cli/cli.help.js +74 -12
  36. package/dist/cli/cli.service.d.ts +19 -10
  37. package/dist/cli/cli.service.js +142 -185
  38. package/dist/cli/idle-status.d.ts +84 -0
  39. package/dist/cli/idle-status.js +181 -0
  40. package/dist/cli/local-config.d.ts +6 -0
  41. package/dist/cli/local-config.js +32 -4
  42. package/dist/cli/provider-cli-detection.d.ts +10 -0
  43. package/dist/cli/provider-cli-detection.js +160 -0
  44. package/dist/runtime/aspnet-runtime-prebuild.d.ts +20 -0
  45. package/dist/runtime/aspnet-runtime-prebuild.js +184 -18
  46. package/dist/runtime/attempt-database-broker.d.ts +1 -1
  47. package/dist/runtime/attempt-node-runtime-launcher.js +9 -0
  48. package/dist/runtime/attempt-process-supervisor.d.ts +2 -0
  49. package/dist/runtime/attempt-process-supervisor.js +12 -6
  50. package/dist/runtime/docker-engine-probe.d.ts +5 -0
  51. package/dist/runtime/docker-engine-probe.js +7 -0
  52. package/dist/runtime/dotnet-build-outputs.d.ts +107 -0
  53. package/dist/runtime/dotnet-build-outputs.js +402 -0
  54. package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
  55. package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
  56. package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
  57. package/dist/runtime/ephemeral-test-postgres.js +303 -0
  58. package/dist/runtime/host-facts.d.ts +2 -1
  59. package/dist/runtime/host-load-admission.d.ts +18 -3
  60. package/dist/runtime/host-load-admission.js +19 -4
  61. package/dist/runtime/host-load-child-environment.d.ts +11 -6
  62. package/dist/runtime/host-load-child-environment.js +22 -11
  63. package/dist/runtime/host-load-governor-config.d.ts +19 -1
  64. package/dist/runtime/host-load-governor-config.js +37 -0
  65. package/dist/runtime/host-load-governor.d.ts +14 -0
  66. package/dist/runtime/host-load-governor.js +139 -26
  67. package/dist/runtime/host-load-ledger-lock.js +6 -4
  68. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  69. package/dist/runtime/host-load-runtime-settings.js +80 -0
  70. package/dist/runtime/host-load-sampler.d.ts +34 -4
  71. package/dist/runtime/host-load-sampler.js +73 -7
  72. package/dist/runtime/host-load-step-class.d.ts +3 -1
  73. package/dist/runtime/host-load-step-class.js +60 -5
  74. package/dist/runtime/host-load-test-slot.d.ts +43 -0
  75. package/dist/runtime/host-load-test-slot.js +81 -0
  76. package/dist/runtime/host-load-token-ledger.d.ts +26 -0
  77. package/dist/runtime/host-load-token-ledger.js +93 -61
  78. package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
  79. package/dist/runtime/host-load-windows-cpu.js +85 -0
  80. package/dist/runtime/host-runtime-contract.d.ts +12 -0
  81. package/dist/runtime/host-runtime-contract.js +29 -1
  82. package/dist/runtime/host-runtime-lease.d.ts +62 -4
  83. package/dist/runtime/host-runtime-lease.js +235 -168
  84. package/dist/runtime/host-runtime-ledger-recovery.d.ts +20 -0
  85. package/dist/runtime/host-runtime-ledger-recovery.js +134 -0
  86. package/dist/runtime/host-runtime-promotion.d.ts +23 -0
  87. package/dist/runtime/host-runtime-promotion.js +36 -0
  88. package/dist/runtime/managed-command-teardown.js +5 -16
  89. package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
  90. package/dist/runtime/native-test-postgres-fallback.js +60 -8
  91. package/dist/runtime/playwright-host-runtime-adapter.d.ts +7 -0
  92. package/dist/runtime/playwright-host-runtime-adapter.js +13 -1
  93. package/dist/runtime/runner-settings.d.ts +104 -0
  94. package/dist/runtime/runner-settings.js +236 -0
  95. package/dist/runtime/supervised-runtime-build-guard.d.ts +45 -0
  96. package/dist/runtime/supervised-runtime-build-guard.js +112 -0
  97. package/dist/sandbox/host-capacity-broker.d.ts +10 -2
  98. package/dist/sandbox/host-capacity-broker.js +27 -6
  99. package/dist/sandbox/managed-branch.d.ts +13 -0
  100. package/dist/sandbox/managed-branch.js +90 -0
  101. package/dist/sandbox/provider-auth/codex.js +11 -11
  102. package/dist/sandbox/runtime.js +2 -6
  103. package/dist/session/architect-waits.d.ts +2 -0
  104. package/dist/session/architect-waits.js +138 -0
  105. package/dist/session/managed-attempt-tools.d.ts +0 -7
  106. package/dist/session/managed-attempt-tools.js +58 -91
  107. package/dist/session/managed-build-coordinator.d.ts +16 -0
  108. package/dist/session/managed-build-coordinator.js +10 -0
  109. package/dist/session/managed-build-receipt.d.ts +5 -0
  110. package/dist/session/managed-build-receipt.js +8 -3
  111. package/dist/session/managed-command-host-load.d.ts +2 -0
  112. package/dist/session/managed-command-host-load.js +2 -1
  113. package/dist/session/phase-completion.artifacts.js +2 -1
  114. package/dist/session/phase-completion.d.ts +8 -0
  115. package/dist/session/phase-completion.js +1 -0
  116. package/dist/session/phase-completion.mcp-args.d.ts +9 -0
  117. package/dist/session/phase-completion.mcp-args.js +156 -0
  118. package/dist/session/phase-completion.runtime.d.ts +0 -8
  119. package/dist/session/phase-completion.runtime.js +43 -197
  120. package/dist/session/phase-completion.schemas.js +25 -23
  121. package/dist/session/phase-completion.validation.js +3 -1
  122. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  123. package/dist/session/pre-publication-native-postgres.js +111 -0
  124. package/dist/session/pre-publication-pass.d.ts +61 -0
  125. package/dist/session/pre-publication-pass.js +148 -0
  126. package/dist/session/pre-publication-process.js +10 -10
  127. package/dist/session/pre-publication-step-execution.d.ts +2 -1
  128. package/dist/session/pre-publication-step-execution.js +6 -5
  129. package/dist/session/pre-publication-validation.d.ts +30 -14
  130. package/dist/session/pre-publication-validation.js +207 -134
  131. package/dist/session/provider-cli/claude-background-work.d.ts +67 -0
  132. package/dist/session/provider-cli/claude-background-work.js +181 -0
  133. package/dist/session/provider-cli/host-build-lock.d.ts +18 -0
  134. package/dist/session/provider-cli/host-build-lock.js +30 -0
  135. package/dist/session/provider-cli/pre-publication-repair.d.ts +56 -0
  136. package/dist/session/provider-cli/pre-publication-repair.js +276 -0
  137. package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
  138. package/dist/session/provider-cli/provider-cli.child-environment.js +75 -0
  139. package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
  140. package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
  141. package/dist/session/provider-cli/provider-cli.process.d.ts +15 -36
  142. package/dist/session/provider-cli/provider-cli.process.js +39 -430
  143. package/dist/session/provider-cli/provider-cli.prompts.d.ts +5 -0
  144. package/dist/session/provider-cli/provider-cli.prompts.js +71 -31
  145. package/dist/session/provider-cli/provider-cli.runtime.d.ts +8 -0
  146. package/dist/session/provider-cli/provider-cli.runtime.js +29 -1
  147. package/dist/session/provider-cli/provider-cli.service.d.ts +7 -1
  148. package/dist/session/provider-cli/provider-cli.service.js +78 -171
  149. package/dist/session/provider-cli/provider-cli.types.d.ts +26 -0
  150. package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
  151. package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
  152. package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
  153. package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
  154. package/dist/session/provider-cli/provider-in-flight-work.d.ts +4 -0
  155. package/dist/session/provider-cli/provider-in-flight-work.js +45 -0
  156. package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
  157. package/dist/session/provider-cli/provider-output-pipes.js +67 -0
  158. package/dist/session/provider-cli/provider-output-state.d.ts +2 -0
  159. package/dist/session/provider-cli/provider-output-state.js +6 -0
  160. package/dist/session/provider-cli/provider-user-config-isolation.d.ts +69 -0
  161. package/dist/session/provider-cli/provider-user-config-isolation.js +164 -0
  162. package/dist/session/qa-sidecar-validation.d.ts +6 -0
  163. package/dist/session/qa-sidecar-validation.js +28 -0
  164. package/dist/session/sandbox-host-capacity-gate.d.ts +22 -1
  165. package/dist/session/sandbox-host-capacity-gate.js +42 -14
  166. package/dist/session/session-redaction.js +31 -181
  167. package/dist/session/session.base.d.ts +6 -1
  168. package/dist/session/session.service.d.ts +9 -2
  169. package/dist/session/session.service.js +169 -66
  170. package/dist/session/session.types.js +4 -4
  171. package/dist/session/sidecar-json-shape.d.ts +31 -0
  172. package/dist/session/sidecar-json-shape.js +217 -0
  173. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  174. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  175. package/dist/shared/fs/file-identity.d.ts +10 -0
  176. package/dist/shared/fs/file-identity.js +15 -0
  177. package/dist/shared/fs/replace-file.d.ts +7 -0
  178. package/dist/shared/fs/replace-file.js +33 -0
  179. package/dist/shared/process/host-process-recovery.d.ts +14 -3
  180. package/dist/shared/process/host-process-recovery.js +23 -3
  181. package/dist/shared/process/host-process-supervisor.d.ts +13 -1
  182. package/dist/shared/process/host-process-supervisor.js +66 -14
  183. package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
  184. package/dist/shared/process/windows-app-execution-alias.js +45 -0
  185. package/dist/shared/process/windows-launch.d.ts +18 -0
  186. package/dist/shared/process/windows-launch.js +68 -0
  187. package/dist/shared/provider-capabilities.js +14 -7
  188. package/dist/version.d.ts +1 -1
  189. package/dist/version.js +1 -1
  190. package/dist/worktree/orphan-relink.d.ts +19 -0
  191. package/dist/worktree/orphan-relink.js +106 -0
  192. package/dist/worktree/wip-git.d.ts +33 -0
  193. package/dist/worktree/wip-git.js +122 -0
  194. package/dist/worktree/wip-refs.d.ts +62 -0
  195. package/dist/worktree/wip-refs.js +119 -0
  196. package/dist/worktree/wip-restore.d.ts +38 -0
  197. package/dist/worktree/wip-restore.js +190 -0
  198. package/dist/worktree/wip-snapshot.d.ts +50 -0
  199. package/dist/worktree/wip-snapshot.js +268 -0
  200. package/dist/worktree/worktree-inputs.d.ts +8 -0
  201. package/dist/worktree/worktree-inputs.js +134 -0
  202. package/dist/worktree/worktree-origin-sync.d.ts +34 -0
  203. package/dist/worktree/worktree-origin-sync.js +127 -0
  204. package/dist/worktree/worktree-wip-events.d.ts +18 -0
  205. package/dist/worktree/worktree-wip-events.js +98 -0
  206. package/dist/worktree/worktree-wip.d.ts +50 -0
  207. package/dist/worktree/worktree-wip.js +185 -0
  208. package/dist/worktree/worktree.base.d.ts +7 -1
  209. package/dist/worktree/worktree.service.d.ts +27 -5
  210. package/dist/worktree/worktree.service.js +110 -181
  211. package/dist/worktree/worktree.types.d.ts +31 -0
  212. package/package.json +2 -2
@@ -0,0 +1,190 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import fs from "node:fs/promises";
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";
6
+ export async function restoreLatestWip(request) {
7
+ const git = new WipGit(request.processRunner);
8
+ let candidates;
9
+ try {
10
+ candidates = await listWipCandidates(git, request);
11
+ }
12
+ catch (error) {
13
+ return { status: "unavailable", detail: errorMessage(error) };
14
+ }
15
+ const newest = newestRestorable(candidates, request.branchName);
16
+ if (!newest)
17
+ return { status: "none" };
18
+ if (!await isCleanWorktree(git, request.worktreePath)) {
19
+ return { status: "skipped_dirty", ref: newest.ref, commitSha: newest.commitSha };
20
+ }
21
+ // Clean again (the reset after a failed restore): its later snapshots may be applied as usual.
22
+ await fs.rm(await partialRestoreMarkerPath(git, request.worktreePath), { force: true });
23
+ const currentHead = (await git.run(request.worktreePath, ["rev-parse", "HEAD"])).trim();
24
+ const notRestored = (reason, detail) => ({
25
+ status: "not_restored", ref: newest.ref, commitSha: newest.commitSha, reason,
26
+ baseHead: newest.metadata.baseHead, currentHead, detail,
27
+ });
28
+ 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)}.`);
30
+ }
31
+ try {
32
+ const changedPaths = await applySnapshot(git, request.worktreePath, newest);
33
+ return {
34
+ status: "restored",
35
+ ref: newest.ref,
36
+ commitSha: newest.commitSha,
37
+ baseHead: currentHead,
38
+ sourceSessionId: newest.metadata.sessionId,
39
+ changedPaths,
40
+ mergeInProgress: Boolean(newest.metadata.mergeHead),
41
+ };
42
+ }
43
+ catch (error) {
44
+ // A pass must never start on a half-applied snapshot: when the partial apply can't be undone,
45
+ // the prepare fails. Nothing is lost; the ref stays, and the next prepare saves this worktree
46
+ // before it resets it. That snapshot holds the mixed state, so it is marked never to be applied
47
+ // automatically (partialRestoreMarkerPath): the next pass restores the original ref instead.
48
+ await rollBack(git, request.worktreePath, newest).catch(async (rollbackError) => {
49
+ await partialRestoreMarkerPath(git, request.worktreePath)
50
+ .then(marker => fs.writeFile(marker, `${newest.ref}\n`, "utf8"))
51
+ .catch(() => undefined);
52
+ throw new Error(`Could not apply ${newest.ref} to ${request.worktreePath} (${errorMessage(error)}), and could not undo the partial apply `
53
+ + `(${errorMessage(rollbackError)}); the worktree is not in a known state, so the provider will not start on it.`, { cause: rollbackError });
54
+ });
55
+ return notRestored("apply_failed", errorMessage(error));
56
+ }
57
+ }
58
+ /** Deletes a WIP ref (on origin, or locally when there is no origin). Never throws. */
59
+ export async function deleteWipRef(repoPath, ref, processRunner) {
60
+ if (!ref.startsWith(`${wipRefRoot}/`))
61
+ return false;
62
+ const git = new WipGit(processRunner);
63
+ const origin = (await git.tryRun(repoPath, ["remote", "get-url", "origin"]))?.trim();
64
+ const deleted = origin
65
+ ? await git.tryRun(repoPath, ["push", "--porcelain", "origin", `:${ref}`])
66
+ : await git.tryRun(repoPath, ["update-ref", "-d", ref]);
67
+ return deleted !== null;
68
+ }
69
+ /** Every snapshot for the branch: origin's (fetched into a private namespace) and any kept locally. */
70
+ async function listWipCandidates(git, request) {
71
+ const prefix = wipRefPrefix(request.branchName);
72
+ const staging = `refs/forge/wip-restore/${randomUUID()}/`;
73
+ const origin = (await git.tryRun(request.repoPath, ["remote", "get-url", "origin"]))?.trim();
74
+ try {
75
+ if (origin) {
76
+ await git.run(request.repoPath, ["fetch", "--no-tags", "--no-write-fetch-head", "origin", `+${prefix}*:${staging}*`]);
77
+ }
78
+ const fetched = await readRefs(git, request.repoPath, staging, prefix);
79
+ const local = await readRefs(git, request.repoPath, prefix, prefix);
80
+ const byRef = new Map([...local, ...fetched].map(candidate => [candidate.ref, candidate]));
81
+ return [...byRef.values()];
82
+ }
83
+ finally {
84
+ const staged = splitLines(await git.tryRun(request.repoPath, ["for-each-ref", "--format=%(refname)", staging]) ?? "");
85
+ for (const ref of staged)
86
+ await git.tryRun(request.repoPath, ["update-ref", "-d", ref]);
87
+ }
88
+ }
89
+ async function readRefs(git, repoPath, namespace, wipPrefix) {
90
+ const listing = await git.run(repoPath, ["for-each-ref", "--format=%(refname) %(objectname)", namespace]);
91
+ const candidates = [];
92
+ for (const line of splitLines(listing)) {
93
+ const [refName, commitSha] = line.split(" ");
94
+ if (!refName || !commitSha)
95
+ continue;
96
+ const raw = await git.tryRun(repoPath, ["cat-file", "commit", commitSha]);
97
+ const metadata = raw === null ? null : parseWipCommitMessage(commitMessageOf(raw));
98
+ if (metadata)
99
+ candidates.push({ ref: `${wipPrefix}${refName.slice(namespace.length)}`, commitSha, metadata });
100
+ }
101
+ return candidates;
102
+ }
103
+ /** The newest snapshot of this branch a pass may apply; one recorded for any other branch never is. */
104
+ function newestRestorable(candidates, branchName) {
105
+ const branch = branchRefName(branchName);
106
+ return [...candidates]
107
+ .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]
109
+ ?? null;
110
+ }
111
+ /** True when the worktree holds nothing a snapshot would save (Forge runtime output aside), and no merge. */
112
+ export async function hasNoUnsavedWork(worktreePath, processRunner) {
113
+ return await isCleanWorktree(new WipGit(processRunner), worktreePath);
114
+ }
115
+ async function isCleanWorktree(git, worktreePath) {
116
+ if (await git.tryRun(worktreePath, ["rev-parse", "-q", "--verify", "MERGE_HEAD"]) !== null)
117
+ return false;
118
+ const forgePaths = await baseTrackedForgePaths(git, worktreePath, "HEAD");
119
+ const status = splitNul(await git.run(worktreePath, ["status", "--porcelain=v1", "-z", "--untracked-files=all", "--no-renames"]));
120
+ return status.every(entry => isWipExcludedPath(entry.slice(3), forgePaths));
121
+ }
122
+ /** Writes the snapshot's files and index (and merge state) onto the clean worktree. */
123
+ async function applySnapshot(git, worktreePath, candidate) {
124
+ const { commitSha, metadata } = candidate;
125
+ const changes = await snapshotChanges(git, worktreePath, metadata.baseHead, commitSha);
126
+ const tempDir = await makeWipTempDir();
127
+ try {
128
+ const snapshotIndex = git.with({ GIT_INDEX_FILE: path.join(tempDir, "snapshot.index") });
129
+ await snapshotIndex.run(worktreePath, ["read-tree", commitSha]);
130
+ const written = changes.filter(change => change.status !== "D").map(change => change.path);
131
+ await snapshotIndex.runForPaths(worktreePath, ["checkout-index", "-f"], written, false);
132
+ }
133
+ finally {
134
+ await fs.rm(tempDir, { recursive: true, force: true }).catch(() => undefined);
135
+ }
136
+ for (const change of changes.filter(entry => entry.status === "D")) {
137
+ await fs.rm(path.join(worktreePath, change.path), { force: true });
138
+ }
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
+ return changes.length;
146
+ }
147
+ async function snapshotChanges(git, worktreePath, base, commitSha) {
148
+ const fields = splitNul(await git.run(worktreePath, ["diff-tree", "-r", "-z", "--no-renames", "--name-status", base, commitSha]));
149
+ const changes = [];
150
+ for (let index = 0; index + 1 < fields.length; index += 2) {
151
+ changes.push({ status: fields[index].trim(), path: fields[index + 1] });
152
+ }
153
+ return changes;
154
+ }
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))];
159
+ const records = [
160
+ ...conflicted.map(filePath => `0 ${zero} 0\t${filePath}`),
161
+ ...metadata.unmerged.map(entry => `${entry.mode} ${entry.sha} ${entry.stage}\t${entry.path}`),
162
+ ];
163
+ await git.runWithInput(worktreePath, ["update-index", "-z", "--index-info"], `${records.join("\0")}\0`);
164
+ }
165
+ async function writeMergeState(git, worktreePath, metadata) {
166
+ await fs.writeFile(await gitPath(git, worktreePath, "MERGE_HEAD"), `${metadata.mergeHead}\n`, "utf8");
167
+ await fs.writeFile(await gitPath(git, worktreePath, "MERGE_MSG"), metadata.mergeMessage ?? `Merge ${metadata.mergeHead}\n`, "utf8");
168
+ if (metadata.mergeMode)
169
+ await fs.writeFile(await gitPath(git, worktreePath, "MERGE_MODE"), `${metadata.mergeMode}\n`, "utf8");
170
+ }
171
+ /** Undoes a partial apply: the worktree was clean at the base before it started. */
172
+ async function rollBack(git, worktreePath, candidate) {
173
+ for (const name of ["MERGE_HEAD", "MERGE_MSG", "MERGE_MODE"]) {
174
+ await fs.rm(await gitPath(git, worktreePath, name), { force: true });
175
+ }
176
+ await git.run(worktreePath, ["read-tree", "--reset", "-u", candidate.metadata.baseHead]);
177
+ const changes = await snapshotChanges(git, worktreePath, candidate.metadata.baseHead, candidate.commitSha);
178
+ for (const change of changes.filter(entry => entry.status === "A")) {
179
+ await fs.rm(path.join(worktreePath, change.path), { force: true });
180
+ }
181
+ }
182
+ function branchRefName(branchName) {
183
+ return branchName.trim().replace(/^refs\/heads\//u, "");
184
+ }
185
+ function splitLines(value) {
186
+ return value.split(/\r?\n/u).map(line => line.trim()).filter(Boolean);
187
+ }
188
+ function errorMessage(error) {
189
+ return error instanceof Error ? error.message : String(error);
190
+ }
@@ -0,0 +1,50 @@
1
+ import type { ProcessRunner } from "../shared/process/process.js";
2
+ import { type WipSnapshotReason } from "./wip-refs.js";
3
+ export interface WipSnapshotRequest {
4
+ readonly worktreePath: string;
5
+ readonly branchName: string;
6
+ readonly reason: WipSnapshotReason;
7
+ readonly sessionId?: string | null;
8
+ readonly lane?: string | null;
9
+ /** Forge's attempt number for the story; unorderedWipAttempt until the server sends one. */
10
+ readonly attempt?: number;
11
+ /** Whether a later pass may apply this snapshot by itself (wip-restore.ts). */
12
+ readonly autoRestore: boolean;
13
+ /** Overrides FORGE_WIP_SNAPSHOT_MAX_BYTES. */
14
+ readonly maxBytes?: number;
15
+ /**
16
+ * A checkout whose Git administrative directory is gone, so Git no longer knows its HEAD or
17
+ * index: it is read through the shared repository against `baseRef` instead.
18
+ */
19
+ readonly orphan?: {
20
+ readonly repoPath: string;
21
+ readonly baseRef: string;
22
+ };
23
+ readonly processRunner?: ProcessRunner;
24
+ readonly now?: () => Date;
25
+ }
26
+ export type WipSnapshotResult = {
27
+ readonly status: "clean";
28
+ } | {
29
+ readonly status: "saved" | "already_saved";
30
+ readonly ref: string;
31
+ readonly commitSha: string;
32
+ readonly baseHead: string;
33
+ readonly changedPaths: number;
34
+ readonly bytes: number;
35
+ /** False when the repository has no origin and the ref was kept in the local repository. */
36
+ readonly pushed: boolean;
37
+ };
38
+ /**
39
+ * Saves the worktree's uncommitted work to a WIP ref. Returns `clean` (and pushes nothing) when
40
+ * there is nothing to save. Throws {@link WipPreservationError} when the work could not be saved,
41
+ * including when it is over the size cap: the caller must then not destroy the worktree.
42
+ */
43
+ export declare function preserveWorktreeWip(requested: WipSnapshotRequest): Promise<WipSnapshotResult>;
44
+ /** Forgets what this process pushed for a worktree, e.g. once the worktree is gone. */
45
+ export declare function forgetPreservedWip(worktreePath: string): void;
46
+ /**
47
+ * Forgets every snapshot this process pushed to `ref`, before that ref is deleted: a later guard
48
+ * that finds the same state must push it again rather than report it saved in a ref that is gone.
49
+ */
50
+ export declare function forgetPreservedWipRef(ref: string): void;
@@ -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,8 @@
1
+ import type { GitClient } from "../shared/git/git.js";
2
+ import type { WorktreePrepareRequest } from "./worktree.types.js";
3
+ /** Materializes the run's inputs into a prepared worktree (outside the repository lock). */
4
+ export declare function materializeWorktreeInputs(worktreePath: string, request: WorktreePrepareRequest, git: GitClient): Promise<{
5
+ readonly hydratedPriorPhaseArtifactCount: number;
6
+ readonly qaReworkPacketPath?: string;
7
+ }>;
8
+ export declare function clearRunArtifactRoots(worktreePath: string, request: WorktreePrepareRequest): Promise<void>;
@@ -0,0 +1,134 @@
1
+ import fs from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { isSubPath, safeSegment } from "../shared/path/path.js";
4
+ import { filterArtifactsForLane, injectWorktreeArtifacts } from "./artifact-injector.js";
5
+ import { hydratePriorPhaseArtifacts } from "./prior-phase-artifact-hydrator.js";
6
+ import { materializeStoryQaReferences } from "./story-qa-reference-hydrator.js";
7
+ // What a prepared worktree is given before the provider starts, once its source is in place:
8
+ // the Story QA reference inputs, a clean artifact root for this run, the prior phases' artifacts,
9
+ // the QA rework packet and the lane's resolved artifacts.
10
+ /** Materializes the run's inputs into a prepared worktree (outside the repository lock). */
11
+ export async function materializeWorktreeInputs(worktreePath, request, git) {
12
+ // Reference inputs and an exact-tree local repair checkpoint must survive output cleanup.
13
+ await materializeStoryQaReferences(worktreePath, request, git);
14
+ if (!request.preserveExistingState) {
15
+ await clearRunArtifactRoots(worktreePath, request);
16
+ }
17
+ const hydratedPriorPhaseArtifactCount = await hydratePriorPhaseArtifacts(worktreePath, request.priorPhaseArtifacts);
18
+ const qaReworkPacketPath = await materializeQaReworkPacket(worktreePath, request);
19
+ const artifacts = filterArtifactsForLane(request.artifacts, request.lane, request.phase);
20
+ if (artifacts.length > 0) {
21
+ await injectWorktreeArtifacts(worktreePath, artifacts, await trackedForgePaths(git, worktreePath));
22
+ }
23
+ return { hydratedPriorPhaseArtifactCount, qaReworkPacketPath };
24
+ }
25
+ async function trackedForgePaths(git, worktreePath) {
26
+ const output = await git.run(worktreePath, ["ls-files", "-z", "--", ".forge"]);
27
+ return new Set(output.split("\0").filter(Boolean).map(value => value.replaceAll("\\", "/")));
28
+ }
29
+ export async function clearRunArtifactRoots(worktreePath, request) {
30
+ const roots = new Set();
31
+ roots.add(workItemArtifactRoot(worktreePath, request.workItem.id));
32
+ for (const artifact of request.priorPhaseArtifacts ?? []) {
33
+ roots.add(workItemArtifactRoot(worktreePath, artifact.workItemId));
34
+ }
35
+ const ownerType = normalizeOwnerType(request.ownerType);
36
+ const ownerId = request.ownerId?.trim();
37
+ if (ownerType && ownerId) {
38
+ roots.add(ownerArtifactRoot(worktreePath, ownerType, ownerId));
39
+ }
40
+ for (const root of roots) {
41
+ const resolvedRoot = path.resolve(root);
42
+ if (!isSubPath(worktreePath, resolvedRoot)) {
43
+ throw new Error(`Artifact root must stay under ${worktreePath}.`);
44
+ }
45
+ await ensureNoSymlinkPathSegments(worktreePath, resolvedRoot, "Artifact root must not traverse symlinked path segments.");
46
+ await fs.rm(resolvedRoot, { recursive: true, force: true });
47
+ await fs.mkdir(resolvedRoot, { recursive: true });
48
+ }
49
+ }
50
+ async function materializeQaReworkPacket(worktreePath, request) {
51
+ const qaRework = request.qaRework;
52
+ if (!qaRework) {
53
+ return undefined;
54
+ }
55
+ const artifactRoot = artifactRootForRequest(worktreePath, request);
56
+ const packetFileName = qaReworkPacketFileName(qaRework.packetPath);
57
+ const packetPath = path.join(artifactRoot, packetFileName);
58
+ const paths = new Set([packetPath, path.join(artifactRoot, "qa-rework-packet.json")]);
59
+ const packetJson = qaRework.packetJson.endsWith("\n") ? qaRework.packetJson : `${qaRework.packetJson}\n`;
60
+ for (const target of paths) {
61
+ const resolvedTarget = path.resolve(target);
62
+ if (!isSubPath(worktreePath, resolvedTarget)) {
63
+ throw new Error(`QA rework packet path must stay under ${worktreePath}.`);
64
+ }
65
+ await ensureNoSymlinkPathSegments(worktreePath, path.dirname(resolvedTarget), "QA rework packet path must not traverse symlinked path segments.");
66
+ await fs.mkdir(path.dirname(resolvedTarget), { recursive: true });
67
+ await fs.writeFile(resolvedTarget, packetJson, "utf8");
68
+ }
69
+ return path.resolve(packetPath);
70
+ }
71
+ function artifactRootForRequest(worktreePath, request) {
72
+ const ownerType = normalizeOwnerType(request.ownerType);
73
+ const ownerId = request.ownerId?.trim();
74
+ if (ownerType && ownerId) {
75
+ return ownerArtifactRoot(worktreePath, ownerType, ownerId);
76
+ }
77
+ return workItemArtifactRoot(worktreePath, request.workItem.id);
78
+ }
79
+ function workItemArtifactRoot(worktreePath, workItemId) {
80
+ return path.join(worktreePath, ".forge", "work-items", safeSegment(workItemId, "work item id"), "artifacts");
81
+ }
82
+ function ownerArtifactRoot(worktreePath, ownerType, ownerId) {
83
+ return path.join(worktreePath, ".forge", ownerType === "story" ? "stories" : "work-items", safeSegment(ownerId, "owner id"), "artifacts");
84
+ }
85
+ function normalizeOwnerType(value) {
86
+ const normalized = (value ?? "").trim().toLowerCase().replace(/-/g, "_");
87
+ if (normalized === "story") {
88
+ return "story";
89
+ }
90
+ if (normalized === "work_item" || normalized === "workitem" || normalized === "work item") {
91
+ return "work_item";
92
+ }
93
+ return null;
94
+ }
95
+ function qaReworkPacketFileName(packetPath) {
96
+ const normalized = packetPath.trim().replace(/\\/g, "/");
97
+ const fileName = normalized.split("/").filter(Boolean).at(-1) ?? "";
98
+ return /^qa-rework-packet(?:\.attempt-\d+)?\.json$/i.test(fileName)
99
+ ? fileName
100
+ : "qa-rework-packet.json";
101
+ }
102
+ async function ensureNoSymlinkPathSegments(root, targetPath, errorMessage) {
103
+ const resolvedRoot = path.resolve(root);
104
+ const resolvedTarget = path.resolve(targetPath);
105
+ const relative = path.relative(resolvedRoot, resolvedTarget);
106
+ if (relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {
107
+ throw new Error(errorMessage);
108
+ }
109
+ let current = resolvedRoot;
110
+ const rootStat = await fs.lstat(current);
111
+ if (rootStat.isSymbolicLink()) {
112
+ throw new Error(errorMessage);
113
+ }
114
+ if (!relative) {
115
+ return;
116
+ }
117
+ for (const segment of relative.split(path.sep)) {
118
+ if (!segment) {
119
+ continue;
120
+ }
121
+ current = path.join(current, segment);
122
+ const stat = await fs.lstat(current).catch((error) => {
123
+ if (error.code === "ENOENT")
124
+ return null;
125
+ throw error;
126
+ });
127
+ if (!stat) {
128
+ return;
129
+ }
130
+ if (stat.isSymbolicLink()) {
131
+ throw new Error(errorMessage);
132
+ }
133
+ }
134
+ }