@loucompanion/forge-bridge 0.1.4-dev.fb770705136a → 0.2.1-dev.0fedbc5c9ef7

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 (269) hide show
  1. package/README.md +146 -3
  2. package/dist/bridge/bridge-chat-giphy-look.d.ts +48 -0
  3. package/dist/bridge/bridge-chat-giphy-look.js +55 -0
  4. package/dist/bridge/bridge-chat-provider-command.d.ts +40 -0
  5. package/dist/bridge/bridge-chat-provider-command.js +230 -0
  6. package/dist/bridge/bridge-chat.types.d.ts +20 -0
  7. package/dist/bridge/bridge-chat.types.js +28 -1
  8. package/dist/bridge/bridge-state-file.d.ts +161 -0
  9. package/dist/bridge/bridge-state-file.js +376 -0
  10. package/dist/bridge/bridge-state-io.d.ts +11 -0
  11. package/dist/bridge/bridge-state-io.js +50 -0
  12. package/dist/bridge/bridge-state-lock.d.ts +11 -0
  13. package/dist/bridge/bridge-state-lock.js +102 -0
  14. package/dist/bridge/bridge-state-unpublished.d.ts +17 -0
  15. package/dist/bridge/bridge-state-unpublished.js +111 -0
  16. package/dist/bridge/bridge.base.d.ts +9 -0
  17. package/dist/bridge/bridge.service.d.ts +92 -14
  18. package/dist/bridge/bridge.service.js +446 -380
  19. package/dist/bridge/bridge.types.d.ts +21 -0
  20. package/dist/bridge/in-flight-registry.d.ts +62 -0
  21. package/dist/bridge/in-flight-registry.js +207 -0
  22. package/dist/bridge/local-yield-flag.d.ts +6 -0
  23. package/dist/bridge/local-yield-flag.js +34 -0
  24. package/dist/bridge/readiness-result-outbox.d.ts +5 -1
  25. package/dist/bridge/readiness-result-outbox.js +20 -0
  26. package/dist/bridge/runner-host-capabilities.d.ts +5 -0
  27. package/dist/bridge/runner-host-capabilities.js +31 -1
  28. package/dist/bridge/sandbox-resource-accounting.d.ts +16 -0
  29. package/dist/bridge/sandbox-resource-accounting.js +150 -0
  30. package/dist/bridge/test-postgres-capability.d.ts +14 -0
  31. package/dist/bridge/test-postgres-capability.js +120 -0
  32. package/dist/bridge/windows-bash-resolution.d.ts +31 -0
  33. package/dist/bridge/windows-bash-resolution.js +153 -0
  34. package/dist/cleanup/cleanup-wip.d.ts +12 -0
  35. package/dist/cleanup/cleanup-wip.js +66 -0
  36. package/dist/cleanup/cleanup.service.d.ts +20 -1
  37. package/dist/cleanup/cleanup.service.js +150 -169
  38. package/dist/cleanup/cleanup.types.d.ts +6 -0
  39. package/dist/cleanup/forge-owned-paths.d.ts +9 -0
  40. package/dist/cleanup/forge-owned-paths.js +53 -0
  41. package/dist/cleanup/host-runtime-ledger.d.ts +7 -0
  42. package/dist/cleanup/host-runtime-ledger.js +130 -0
  43. package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
  44. package/dist/cleanup/managed-branch-sweep.js +111 -0
  45. package/dist/cli/cli.help.js +74 -12
  46. package/dist/cli/cli.service.d.ts +19 -10
  47. package/dist/cli/cli.service.js +152 -187
  48. package/dist/cli/idle-status.d.ts +84 -0
  49. package/dist/cli/idle-status.js +181 -0
  50. package/dist/cli/local-config.d.ts +6 -0
  51. package/dist/cli/local-config.js +32 -4
  52. package/dist/cli/provider-cli-detection.d.ts +10 -0
  53. package/dist/cli/provider-cli-detection.js +160 -0
  54. package/dist/runtime/aspnet-runtime-prebuild.d.ts +20 -0
  55. package/dist/runtime/aspnet-runtime-prebuild.js +184 -18
  56. package/dist/runtime/attempt-database-broker.d.ts +1 -1
  57. package/dist/runtime/attempt-node-runtime-launcher.d.ts +36 -0
  58. package/dist/runtime/attempt-node-runtime-launcher.js +169 -0
  59. package/dist/runtime/attempt-process-supervisor.d.ts +2 -0
  60. package/dist/runtime/attempt-process-supervisor.js +12 -6
  61. package/dist/runtime/docker-engine-probe.d.ts +5 -0
  62. package/dist/runtime/docker-engine-probe.js +7 -0
  63. package/dist/runtime/dotnet-build-outputs.d.ts +107 -0
  64. package/dist/runtime/dotnet-build-outputs.js +402 -0
  65. package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
  66. package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
  67. package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
  68. package/dist/runtime/ephemeral-test-postgres.js +303 -0
  69. package/dist/runtime/host-facts.d.ts +2 -1
  70. package/dist/runtime/host-listener-inspector.d.ts +26 -0
  71. package/dist/runtime/host-listener-inspector.js +84 -3
  72. package/dist/runtime/host-load-admission.d.ts +72 -0
  73. package/dist/runtime/host-load-admission.js +99 -0
  74. package/dist/runtime/host-load-child-environment.d.ts +27 -0
  75. package/dist/runtime/host-load-child-environment.js +76 -0
  76. package/dist/runtime/host-load-forge-cgroups.d.ts +49 -0
  77. package/dist/runtime/host-load-forge-cgroups.js +140 -0
  78. package/dist/runtime/host-load-governor-config.d.ts +61 -0
  79. package/dist/runtime/host-load-governor-config.js +86 -0
  80. package/dist/runtime/host-load-governor.d.ts +193 -0
  81. package/dist/runtime/host-load-governor.js +662 -0
  82. package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
  83. package/dist/runtime/host-load-ledger-lock.js +187 -0
  84. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  85. package/dist/runtime/host-load-runtime-settings.js +80 -0
  86. package/dist/runtime/host-load-sampler.d.ts +75 -2
  87. package/dist/runtime/host-load-sampler.js +142 -8
  88. package/dist/runtime/host-load-step-class.d.ts +70 -0
  89. package/dist/runtime/host-load-step-class.js +161 -0
  90. package/dist/runtime/host-load-step-reaper.d.ts +27 -0
  91. package/dist/runtime/host-load-step-reaper.js +95 -0
  92. package/dist/runtime/host-load-step-run.d.ts +73 -0
  93. package/dist/runtime/host-load-step-run.js +102 -0
  94. package/dist/runtime/host-load-test-slot.d.ts +43 -0
  95. package/dist/runtime/host-load-test-slot.js +88 -0
  96. package/dist/runtime/host-load-token-ledger.d.ts +200 -0
  97. package/dist/runtime/host-load-token-ledger.js +453 -0
  98. package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
  99. package/dist/runtime/host-load-windows-cpu.js +85 -0
  100. package/dist/runtime/host-pressure-stall.d.ts +21 -1
  101. package/dist/runtime/host-pressure-stall.js +48 -1
  102. package/dist/runtime/host-runtime-contract.d.ts +15 -0
  103. package/dist/runtime/host-runtime-contract.js +33 -2
  104. package/dist/runtime/host-runtime-lease.d.ts +101 -6
  105. package/dist/runtime/host-runtime-lease.js +408 -294
  106. package/dist/runtime/host-runtime-ledger-recovery.d.ts +20 -0
  107. package/dist/runtime/host-runtime-ledger-recovery.js +134 -0
  108. package/dist/runtime/host-runtime-promotion.d.ts +101 -2
  109. package/dist/runtime/host-runtime-promotion.js +355 -14
  110. package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
  111. package/dist/runtime/host-runtime-requirements-check.js +29 -0
  112. package/dist/runtime/host-runtime-requirements.d.ts +36 -0
  113. package/dist/runtime/host-runtime-requirements.js +117 -0
  114. package/dist/runtime/managed-command-teardown.js +5 -16
  115. package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
  116. package/dist/runtime/native-test-postgres-fallback.js +60 -8
  117. package/dist/runtime/playwright-host-runtime-adapter.d.ts +7 -0
  118. package/dist/runtime/playwright-host-runtime-adapter.js +13 -1
  119. package/dist/runtime/prepared-runtime-identity.d.ts +4 -0
  120. package/dist/runtime/prepared-runtime-identity.js +130 -9
  121. package/dist/runtime/prepared-runtime-readiness.d.ts +13 -1
  122. package/dist/runtime/prepared-runtime-readiness.js +63 -16
  123. package/dist/runtime/runner-settings.d.ts +104 -0
  124. package/dist/runtime/runner-settings.js +236 -0
  125. package/dist/runtime/supervised-runtime-build-guard.d.ts +45 -0
  126. package/dist/runtime/supervised-runtime-build-guard.js +112 -0
  127. package/dist/sandbox/host-capacity-broker.d.ts +115 -0
  128. package/dist/sandbox/host-capacity-broker.js +336 -0
  129. package/dist/sandbox/managed-branch.d.ts +13 -0
  130. package/dist/sandbox/managed-branch.js +90 -0
  131. package/dist/sandbox/provider-auth/codex.js +11 -11
  132. package/dist/sandbox/runtime.d.ts +10 -1
  133. package/dist/sandbox/runtime.js +47 -8
  134. package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
  135. package/dist/sandbox/sandbox-cgroups.js +42 -0
  136. package/dist/session/architect-waits.d.ts +2 -0
  137. package/dist/session/architect-waits.js +138 -0
  138. package/dist/session/managed-attempt-tools.d.ts +2 -7
  139. package/dist/session/managed-attempt-tools.js +207 -121
  140. package/dist/session/managed-build-coordinator.d.ts +16 -0
  141. package/dist/session/managed-build-coordinator.js +10 -0
  142. package/dist/session/managed-build-receipt.d.ts +5 -0
  143. package/dist/session/managed-build-receipt.js +8 -3
  144. package/dist/session/managed-command-host-load.d.ts +47 -0
  145. package/dist/session/managed-command-host-load.js +83 -0
  146. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  147. package/dist/session/mcp-argument-coercion.js +121 -0
  148. package/dist/session/phase-completion.artifacts.d.ts +7 -0
  149. package/dist/session/phase-completion.artifacts.js +96 -26
  150. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  151. package/dist/session/phase-completion.command-validation.js +77 -0
  152. package/dist/session/phase-completion.d.ts +12 -0
  153. package/dist/session/phase-completion.helpers.js +13 -12
  154. package/dist/session/phase-completion.js +5 -0
  155. package/dist/session/phase-completion.mcp-args.d.ts +9 -0
  156. package/dist/session/phase-completion.mcp-args.js +156 -0
  157. package/dist/session/phase-completion.prompts.js +6 -1
  158. package/dist/session/phase-completion.runtime.d.ts +5 -11
  159. package/dist/session/phase-completion.runtime.js +91 -215
  160. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  161. package/dist/session/phase-completion.schema-parts.js +188 -0
  162. package/dist/session/phase-completion.schemas.d.ts +3 -3
  163. package/dist/session/phase-completion.schemas.js +208 -231
  164. package/dist/session/phase-completion.validation.d.ts +2 -3
  165. package/dist/session/phase-completion.validation.js +49 -93
  166. package/dist/session/pre-publication-host-load.d.ts +27 -0
  167. package/dist/session/pre-publication-host-load.js +111 -0
  168. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  169. package/dist/session/pre-publication-native-postgres.js +111 -0
  170. package/dist/session/pre-publication-pass.d.ts +61 -0
  171. package/dist/session/pre-publication-pass.js +148 -0
  172. package/dist/session/pre-publication-process.d.ts +3 -0
  173. package/dist/session/pre-publication-process.js +31 -19
  174. package/dist/session/pre-publication-step-execution.d.ts +12 -0
  175. package/dist/session/pre-publication-step-execution.js +50 -0
  176. package/dist/session/pre-publication-validation.d.ts +37 -21
  177. package/dist/session/pre-publication-validation.js +221 -182
  178. package/dist/session/provider-cli/claude-background-work.d.ts +67 -0
  179. package/dist/session/provider-cli/claude-background-work.js +181 -0
  180. package/dist/session/provider-cli/host-build-lock.d.ts +18 -0
  181. package/dist/session/provider-cli/host-build-lock.js +30 -0
  182. package/dist/session/provider-cli/pre-publication-repair.d.ts +56 -0
  183. package/dist/session/provider-cli/pre-publication-repair.js +276 -0
  184. package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
  185. package/dist/session/provider-cli/provider-cli.child-environment.js +75 -0
  186. package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
  187. package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
  188. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +6 -3
  189. package/dist/session/provider-cli/provider-cli.merge-integrity.js +28 -8
  190. package/dist/session/provider-cli/provider-cli.process.d.ts +15 -36
  191. package/dist/session/provider-cli/provider-cli.process.js +41 -432
  192. package/dist/session/provider-cli/provider-cli.prompts.d.ts +5 -0
  193. package/dist/session/provider-cli/provider-cli.prompts.js +72 -32
  194. package/dist/session/provider-cli/provider-cli.runtime.d.ts +8 -0
  195. package/dist/session/provider-cli/provider-cli.runtime.js +29 -1
  196. package/dist/session/provider-cli/provider-cli.service.d.ts +7 -1
  197. package/dist/session/provider-cli/provider-cli.service.js +98 -173
  198. package/dist/session/provider-cli/provider-cli.types.d.ts +30 -0
  199. package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
  200. package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
  201. package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
  202. package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
  203. package/dist/session/provider-cli/provider-in-flight-work.d.ts +4 -0
  204. package/dist/session/provider-cli/provider-in-flight-work.js +45 -0
  205. package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
  206. package/dist/session/provider-cli/provider-output-pipes.js +67 -0
  207. package/dist/session/provider-cli/provider-output-state.d.ts +2 -0
  208. package/dist/session/provider-cli/provider-output-state.js +6 -0
  209. package/dist/session/provider-cli/provider-user-config-isolation.d.ts +69 -0
  210. package/dist/session/provider-cli/provider-user-config-isolation.js +164 -0
  211. package/dist/session/qa-sidecar-validation.d.ts +6 -0
  212. package/dist/session/qa-sidecar-validation.js +28 -0
  213. package/dist/session/sandbox-host-capacity-gate.d.ts +51 -0
  214. package/dist/session/sandbox-host-capacity-gate.js +257 -0
  215. package/dist/session/session-redaction.js +31 -181
  216. package/dist/session/session.base.d.ts +9 -1
  217. package/dist/session/session.service.d.ts +15 -2
  218. package/dist/session/session.service.js +246 -88
  219. package/dist/session/session.types.d.ts +4 -0
  220. package/dist/session/session.types.js +7 -7
  221. package/dist/session/sidecar-json-shape.d.ts +31 -0
  222. package/dist/session/sidecar-json-shape.js +217 -0
  223. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  224. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  225. package/dist/shared/fs/file-identity.d.ts +10 -0
  226. package/dist/shared/fs/file-identity.js +15 -0
  227. package/dist/shared/fs/replace-file.d.ts +7 -0
  228. package/dist/shared/fs/replace-file.js +33 -0
  229. package/dist/shared/process/host-process-recovery.d.ts +14 -3
  230. package/dist/shared/process/host-process-recovery.js +23 -3
  231. package/dist/shared/process/host-process-supervisor.d.ts +14 -1
  232. package/dist/shared/process/host-process-supervisor.js +67 -15
  233. package/dist/shared/process/process-tree.d.ts +52 -0
  234. package/dist/shared/process/process-tree.js +144 -0
  235. package/dist/shared/process/process.d.ts +67 -0
  236. package/dist/shared/process/process.js +213 -11
  237. package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
  238. package/dist/shared/process/windows-app-execution-alias.js +45 -0
  239. package/dist/shared/process/windows-launch.d.ts +18 -0
  240. package/dist/shared/process/windows-launch.js +68 -0
  241. package/dist/shared/provider-capabilities.js +14 -7
  242. package/dist/version.d.ts +1 -1
  243. package/dist/version.js +1 -1
  244. package/dist/worktree/dependency-warmer.d.ts +25 -0
  245. package/dist/worktree/dependency-warmer.js +46 -10
  246. package/dist/worktree/orphan-relink.d.ts +19 -0
  247. package/dist/worktree/orphan-relink.js +106 -0
  248. package/dist/worktree/wip-git.d.ts +42 -0
  249. package/dist/worktree/wip-git.js +139 -0
  250. package/dist/worktree/wip-refs.d.ts +77 -0
  251. package/dist/worktree/wip-refs.js +146 -0
  252. package/dist/worktree/wip-restore.d.ts +46 -0
  253. package/dist/worktree/wip-restore.js +280 -0
  254. package/dist/worktree/wip-snapshot.d.ts +53 -0
  255. package/dist/worktree/wip-snapshot.js +270 -0
  256. package/dist/worktree/worktree-inputs.d.ts +8 -0
  257. package/dist/worktree/worktree-inputs.js +134 -0
  258. package/dist/worktree/worktree-origin-sync.d.ts +35 -0
  259. package/dist/worktree/worktree-origin-sync.js +128 -0
  260. package/dist/worktree/worktree-wip-events.d.ts +18 -0
  261. package/dist/worktree/worktree-wip-events.js +115 -0
  262. package/dist/worktree/worktree-wip.d.ts +51 -0
  263. package/dist/worktree/worktree-wip.js +190 -0
  264. package/dist/worktree/worktree.base.d.ts +7 -1
  265. package/dist/worktree/worktree.service.d.ts +36 -5
  266. package/dist/worktree/worktree.service.js +126 -155
  267. package/dist/worktree/worktree.types.d.ts +42 -0
  268. package/package.json +2 -2
  269. package/runtime/windows-listener-owner.ps1 +12 -1
@@ -0,0 +1,139 @@
1
+ import { spawn } from "node:child_process";
2
+ import fs from "node:fs/promises";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import { isRuntimeOnlyPath } from "../session/publishable-worktree-changes.js";
6
+ import { NodeProcessRunner } from "../shared/process/process.js";
7
+ import { parseReapplyConflictRecord, wipReapplyConflictRecordName } from "./wip-refs.js";
8
+ // Git plumbing shared by WIP snapshot and restore. Every command can carry extra environment
9
+ // (a temporary index, or GIT_DIR/GIT_WORK_TREE for an orphaned checkout) without touching the
10
+ // worktree's own index, HEAD or config.
11
+ const wipIdentity = {
12
+ GIT_AUTHOR_NAME: "Forge Bridge",
13
+ GIT_AUTHOR_EMAIL: "forge-bridge@forge.local",
14
+ GIT_COMMITTER_NAME: "Forge Bridge",
15
+ GIT_COMMITTER_EMAIL: "forge-bridge@forge.local",
16
+ };
17
+ const pathBatchSize = 200;
18
+ export class WipGit {
19
+ runner;
20
+ env;
21
+ constructor(runner = new NodeProcessRunner(), env = {}) {
22
+ this.runner = runner;
23
+ this.env = env;
24
+ }
25
+ /** The same client with more environment, e.g. GIT_INDEX_FILE for a throwaway index. */
26
+ with(env) {
27
+ return new WipGit(this.runner, { ...this.env, ...env });
28
+ }
29
+ async run(cwd, args) {
30
+ const result = await this.runWithStatus(cwd, args);
31
+ if (result.exitCode !== 0) {
32
+ throw new Error(`git ${args.join(" ")} failed: ${result.stderr.trim() || result.stdout.trim()}`);
33
+ }
34
+ return result.stdout;
35
+ }
36
+ /** Runs git and returns its exit code with its output, for commands whose non-zero exit is an answer. */
37
+ async runWithStatus(cwd, args) {
38
+ const result = await this.runner.run({
39
+ command: "git",
40
+ args,
41
+ cwd,
42
+ env: { ...process.env, ...wipIdentity, ...this.env },
43
+ ...(args.includes("-z") ? { rawOutput: true } : {}),
44
+ });
45
+ return { exitCode: result.exitCode, stdout: result.stdout, stderr: result.stderr };
46
+ }
47
+ async tryRun(cwd, args) {
48
+ return await this.run(cwd, args).catch(() => null);
49
+ }
50
+ /** Runs git with `input` on stdin (for `update-index --index-info`). */
51
+ async runWithInput(cwd, args, input) {
52
+ await new Promise((resolve, reject) => {
53
+ const child = spawn("git", [...args], {
54
+ cwd,
55
+ env: { ...process.env, ...wipIdentity, ...this.env },
56
+ stdio: ["pipe", "ignore", "pipe"],
57
+ windowsHide: true,
58
+ });
59
+ let stderr = "";
60
+ child.stderr.on("data", chunk => { stderr += String(chunk); });
61
+ child.on("error", reject);
62
+ child.on("close", code => code === 0
63
+ ? resolve()
64
+ : reject(new Error(`git ${args.join(" ")} failed: ${stderr.trim()}`)));
65
+ child.stdin.end(input);
66
+ });
67
+ }
68
+ /**
69
+ * Runs `git <args> -- <paths>` in batches so long path lists stay under command-line limits.
70
+ * Paths are literal pathspecs unless `pathspecs` is false (for commands such as checkout-index
71
+ * that take plain file names).
72
+ */
73
+ async runForPaths(cwd, args, paths, pathspecs = true) {
74
+ for (let index = 0; index < paths.length; index += pathBatchSize) {
75
+ const batch = paths.slice(index, index + pathBatchSize).map(filePath => pathspecs ? `:(literal)${filePath}` : filePath);
76
+ await this.run(cwd, [...args, "--", ...batch]);
77
+ }
78
+ }
79
+ }
80
+ export function splitNul(output) {
81
+ return output.split("\0").filter(Boolean);
82
+ }
83
+ /**
84
+ * Forge runtime output that is never part of a snapshot, matching what publication excludes:
85
+ * `.local/`, `.forge/work-items/`, `.forge/stories/`, and any `.forge/` path the base commit does
86
+ * not track (injected commands, hooks and skills).
87
+ */
88
+ export function isWipExcludedPath(relativePath, baseTrackedForgePaths) {
89
+ const normalized = relativePath.replaceAll("\\", "/").replace(/\/$/u, "");
90
+ if (isRuntimeOnlyPath(normalized))
91
+ return true;
92
+ if (normalized === ".forge" || normalized.startsWith(".forge/"))
93
+ return !baseTrackedForgePaths.has(normalized);
94
+ return false;
95
+ }
96
+ export async function baseTrackedForgePaths(git, cwd, base) {
97
+ const output = await git.run(cwd, ["ls-tree", "-r", "-z", "--name-only", base, "--", ".forge"]);
98
+ return new Set(splitNul(output));
99
+ }
100
+ /** Resolves a `git rev-parse --git-path` answer, which may be relative to `cwd`. */
101
+ export async function gitPath(git, cwd, name) {
102
+ const raw = (await git.run(cwd, ["rev-parse", "--git-path", name])).trim();
103
+ return path.isAbsolute(raw) ? raw : path.resolve(cwd, raw);
104
+ }
105
+ /**
106
+ * Set in a worktree's Git directory when a WIP restore could neither finish nor be undone, so its
107
+ * files are a mix of the snapshot and the base. No snapshot of it is ever applied automatically
108
+ * until a restore finds the worktree clean again (wip-restore.ts).
109
+ */
110
+ const partialRestoreMarkerName = "forge-wip-partial-restore";
111
+ export async function partialRestoreMarkerPath(git, cwd) {
112
+ return await gitPath(git, cwd, partialRestoreMarkerName);
113
+ }
114
+ export async function hasPartialRestoreMarker(git, cwd) {
115
+ const marker = await partialRestoreMarkerPath(git, cwd).catch(() => null);
116
+ return marker !== null && await fs.stat(marker).then(() => true, () => false);
117
+ }
118
+ export async function readReapplyConflictRecord(git, cwd) {
119
+ return parseReapplyConflictRecord(await readOptionalFile(await gitPath(git, cwd, wipReapplyConflictRecordName)));
120
+ }
121
+ /** Writes the re-apply conflict record (wip-refs.ts), or removes it when there are no paths. */
122
+ export async function writeReapplyConflictRecord(git, cwd, paths) {
123
+ const record = await gitPath(git, cwd, wipReapplyConflictRecordName);
124
+ if (paths.length === 0)
125
+ await fs.rm(record, { force: true });
126
+ else
127
+ await fs.writeFile(record, [...new Set(paths)].sort().join("\0"), "utf8");
128
+ }
129
+ /** A private directory for throwaway index files, removed by the caller. */
130
+ export async function makeWipTempDir() {
131
+ return await fs.mkdtemp(path.join(os.tmpdir(), "forge-wip-"));
132
+ }
133
+ export async function readOptionalFile(filePath) {
134
+ return await fs.readFile(filePath, "utf8").catch((error) => {
135
+ if (error.code === "ENOENT")
136
+ return null;
137
+ throw error;
138
+ });
139
+ }
@@ -0,0 +1,77 @@
1
+ export declare const wipRefRoot = "refs/forge/wip";
2
+ export declare const wipMetadataSchema = "forge.wip.v1";
3
+ /**
4
+ * Kept in a worktree's Git directory after a WIP re-apply across a branch move left conflicts
5
+ * (wip-restore.ts): the conflicted paths, NUL-separated. A re-apply writes no MERGE_HEAD, and staging
6
+ * a conflicted file clears its index stages but keeps its markers, so publication reads this to keep
7
+ * refusing those markers (provider-cli.merge-integrity.ts). Snapshots carry it (reapplyConflicts) and
8
+ * a restore writes it back; a restore that finds the worktree clean removes it.
9
+ */
10
+ export declare const wipReapplyConflictRecordName = "forge-wip-reapply-conflicts";
11
+ export declare function parseReapplyConflictRecord(content: string | null): string[];
12
+ /** The attempt of a snapshot taken without a Forge-issued attempt number. */
13
+ export declare const unorderedWipAttempt = 0;
14
+ /** Why a snapshot was taken. Session reasons name the session; the others are guards. */
15
+ export type WipSnapshotReason = "session_failed" | "repair_limit" | "session_paused" | "session_stopped" | "pre_reset" | "pre_sync" | "pre_branch_reset" | "pre_release" | "pre_cleanup";
16
+ export interface WipUnmergedEntry {
17
+ readonly mode: string;
18
+ readonly sha: string;
19
+ readonly stage: number;
20
+ readonly path: string;
21
+ }
22
+ export interface WipSnapshotMetadata {
23
+ readonly schema: typeof wipMetadataSchema;
24
+ readonly branch: string;
25
+ readonly baseHead: string;
26
+ readonly sessionId: string | null;
27
+ readonly lane: string | null;
28
+ readonly reason: WipSnapshotReason;
29
+ /** The story attempt the snapshot belongs to (see the ref layout above). */
30
+ readonly attempt: number;
31
+ /** False for snapshots that must never be applied automatically (see wip-snapshot.ts). */
32
+ readonly autoRestore: boolean;
33
+ readonly createdAt: string;
34
+ readonly createdAtMs: number;
35
+ readonly mergeHead: string | null;
36
+ readonly mergeMessage: string | null;
37
+ readonly mergeMode: string | null;
38
+ readonly unmerged: readonly WipUnmergedEntry[];
39
+ /** The worktree's re-apply conflict record when it was taken (see wipReapplyConflictRecordName); [] before it existed. */
40
+ readonly reapplyConflicts: readonly string[];
41
+ readonly changedPaths: number;
42
+ readonly bytes: number;
43
+ }
44
+ export type WipPreservationFailureCode = "wip_snapshot_too_large" | "wip_snapshot_failed" | "wip_push_failed";
45
+ /** Snapshotting or pushing uncommitted work failed; whatever would have destroyed it must not run. */
46
+ export declare class WipPreservationError extends Error {
47
+ readonly code: WipPreservationFailureCode;
48
+ constructor(code: WipPreservationFailureCode, message: string, options?: {
49
+ readonly cause?: unknown;
50
+ });
51
+ }
52
+ /**
53
+ * `story/<12 hex>` → the 12 hex; any other branch → `b_` and its name with `_` written as `_u` and
54
+ * `/` as `_s`. The encoding is reversible and a story key never starts with `b_`, so no two branches
55
+ * share a key (`task/a-b` and `task-a/b` would under a plain `/` → `-`). GitHubWipRefCleanup.cs
56
+ * computes the same key.
57
+ */
58
+ export declare function wipOwnerKey(branchName: string): string;
59
+ /** The ref namespace holding every WIP snapshot for a branch, with a trailing slash. */
60
+ export declare function wipRefPrefix(branchName: string): string;
61
+ export declare function wipRefName(branchName: string, id: string): string;
62
+ /**
63
+ * `<attempt>-<session id>` for a session's own snapshot; `<attempt>-[<session id>-]<reason>-<time>-<nonce>`
64
+ * for a guard snapshot.
65
+ */
66
+ export declare function wipRefId(reason: WipSnapshotReason, sessionId: string | null | undefined, now: Date, attempt?: number): string;
67
+ /** A Forge-issued attempt usable in a ref name; anything else (missing, out of range) is unorderedWipAttempt. */
68
+ export declare function issuedWipAttempt(value: number | null | undefined): number;
69
+ /** The attempt a WIP ref belongs to: its ten-digit id prefix, or unorderedWipAttempt without one. */
70
+ export declare function wipRefAttempt(ref: string): number;
71
+ /** The cap on a snapshot's size, from FORGE_WIP_SNAPSHOT_MAX_BYTES when that is a positive integer. */
72
+ export declare function wipSnapshotMaxBytes(env?: NodeJS.ProcessEnv): number;
73
+ export declare function formatWipCommitMessage(metadata: WipSnapshotMetadata): string;
74
+ /** The metadata of a WIP commit message, or null when the message is not one. */
75
+ export declare function parseWipCommitMessage(message: string): WipSnapshotMetadata | null;
76
+ /** A raw commit object's message: everything after its header block. */
77
+ export declare function commitMessageOf(rawCommit: string): string;
@@ -0,0 +1,146 @@
1
+ // Private WIP refs: where Forge keeps uncommitted work it could otherwise lose.
2
+ //
3
+ // The bridge owns the only commit and push on a story branch, so unfinished work never goes there.
4
+ // Before anything could destroy uncommitted changes (a session that stops, fails, pauses or hits
5
+ // its repair limit; a reset, a release or a cleanup of the worktree), the bridge snapshots them into
6
+ // a commit and pushes it to
7
+ //
8
+ // refs/forge/wip/<owner key>/<attempt>-<session id | [session id-]reason-timestamp-nonce>
9
+ //
10
+ // <attempt> is ten zero-padded digits, so refs sort by it: the dispatch's wipAttempt, which Forge
11
+ // issues from a database sequence when it admits the dispatch attempt, so a later attempt on a story
12
+ // always has a larger one. Newest work wins: a restore takes the highest attempt first. Snapshots
13
+ // taken without an issued attempt (older servers, attempts admitted before it existed, cleanup and
14
+ // branch-reset guards) carry attempt 0.
15
+ //
16
+ // The owner key is the story's short id for a `story/<12 hex>` branch, and `b_` plus the branch
17
+ // name with `_` → `_u` and `/` → `_s` for any other branch (`b_task_s0123456789ab`), so it is
18
+ // unique per branch. The server deletes a key's refs when the pull request for that branch merges
19
+ // or closes (GitHubWipRefCleanup.cs).
20
+ //
21
+ // A snapshot is a commit W whose tree is the worktree (staged, unstaged and untracked files that
22
+ // are not ignored; never Forge runtime output). Its first parent is the HEAD it was based on, its
23
+ // second an index commit I whose tree is the staged state, and its third, when a merge was in
24
+ // progress, MERGE_HEAD. Its message carries the metadata below as JSON.
25
+ import { randomBytes } from "node:crypto";
26
+ export const wipRefRoot = "refs/forge/wip";
27
+ export const wipMetadataSchema = "forge.wip.v1";
28
+ const defaultWipSnapshotMaxBytes = 100 * 1024 * 1024;
29
+ const wipSnapshotMaxBytesEnv = "FORGE_WIP_SNAPSHOT_MAX_BYTES";
30
+ const storyBranchPattern = /^story\/([0-9a-f]{12})$/u;
31
+ const refSegmentPattern = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u;
32
+ /**
33
+ * Kept in a worktree's Git directory after a WIP re-apply across a branch move left conflicts
34
+ * (wip-restore.ts): the conflicted paths, NUL-separated. A re-apply writes no MERGE_HEAD, and staging
35
+ * a conflicted file clears its index stages but keeps its markers, so publication reads this to keep
36
+ * refusing those markers (provider-cli.merge-integrity.ts). Snapshots carry it (reapplyConflicts) and
37
+ * a restore writes it back; a restore that finds the worktree clean removes it.
38
+ */
39
+ export const wipReapplyConflictRecordName = "forge-wip-reapply-conflicts";
40
+ export function parseReapplyConflictRecord(content) {
41
+ return content ? [...new Set(content.split("\0").filter(Boolean))].sort() : [];
42
+ }
43
+ /** The attempt of a snapshot taken without a Forge-issued attempt number. */
44
+ export const unorderedWipAttempt = 0;
45
+ const maxWipAttempt = 9_999_999_999;
46
+ /** Snapshotting or pushing uncommitted work failed; whatever would have destroyed it must not run. */
47
+ export class WipPreservationError extends Error {
48
+ code;
49
+ constructor(code, message, options) {
50
+ super(`${code}: ${message}`, options);
51
+ this.code = code;
52
+ this.name = "WipPreservationError";
53
+ }
54
+ }
55
+ /**
56
+ * `story/<12 hex>` → the 12 hex; any other branch → `b_` and its name with `_` written as `_u` and
57
+ * `/` as `_s`. The encoding is reversible and a story key never starts with `b_`, so no two branches
58
+ * share a key (`task/a-b` and `task-a/b` would under a plain `/` → `-`). GitHubWipRefCleanup.cs
59
+ * computes the same key.
60
+ */
61
+ export function wipOwnerKey(branchName) {
62
+ const branch = branchName.trim().replace(/^refs\/heads\//u, "");
63
+ const story = storyBranchPattern.exec(branch);
64
+ const key = story ? story[1] : `b_${branch.replaceAll("_", "_u").replaceAll("/", "_s")}`;
65
+ if (!branch || !refSegmentPattern.test(key) || key.includes("..") || key.endsWith(".lock") || key.endsWith(".")) {
66
+ throw new WipPreservationError("wip_snapshot_failed", `branch '${branchName}' has no valid WIP ref key.`);
67
+ }
68
+ return key;
69
+ }
70
+ /** The ref namespace holding every WIP snapshot for a branch, with a trailing slash. */
71
+ export function wipRefPrefix(branchName) {
72
+ return `${wipRefRoot}/${wipOwnerKey(branchName)}/`;
73
+ }
74
+ export function wipRefName(branchName, id) {
75
+ if (!refSegmentPattern.test(id) || id.endsWith(".lock") || id.endsWith(".")) {
76
+ throw new WipPreservationError("wip_snapshot_failed", `'${id}' is not a valid WIP ref id.`);
77
+ }
78
+ return `${wipRefPrefix(branchName)}${id}`;
79
+ }
80
+ /**
81
+ * `<attempt>-<session id>` for a session's own snapshot; `<attempt>-[<session id>-]<reason>-<time>-<nonce>`
82
+ * for a guard snapshot.
83
+ */
84
+ export function wipRefId(reason, sessionId, now, attempt = unorderedWipAttempt) {
85
+ if (!Number.isSafeInteger(attempt) || attempt < 0 || attempt > maxWipAttempt) {
86
+ throw new WipPreservationError("wip_snapshot_failed", `${attempt} is not a valid WIP attempt number.`);
87
+ }
88
+ const prefix = `${String(attempt).padStart(10, "0")}-`;
89
+ const session = sessionId?.trim();
90
+ if (session && isSessionReason(reason))
91
+ return `${prefix}${session}`;
92
+ const owner = session ? `${session}-` : "";
93
+ return `${prefix}${owner}${reason.replaceAll("_", "-")}-${now.getTime().toString(36)}-${randomBytes(3).toString("hex")}`;
94
+ }
95
+ function isSessionReason(reason) {
96
+ return reason === "session_failed" || reason === "repair_limit"
97
+ || reason === "session_paused" || reason === "session_stopped";
98
+ }
99
+ /** A Forge-issued attempt usable in a ref name; anything else (missing, out of range) is unorderedWipAttempt. */
100
+ export function issuedWipAttempt(value) {
101
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 && value <= maxWipAttempt ? value : unorderedWipAttempt;
102
+ }
103
+ /** The attempt a WIP ref belongs to: its ten-digit id prefix, or unorderedWipAttempt without one. */
104
+ export function wipRefAttempt(ref) {
105
+ const id = ref.slice(ref.lastIndexOf("/") + 1);
106
+ const match = /^(\d{10})-/u.exec(id);
107
+ return match ? Number(match[1]) : unorderedWipAttempt;
108
+ }
109
+ /** The cap on a snapshot's size, from FORGE_WIP_SNAPSHOT_MAX_BYTES when that is a positive integer. */
110
+ export function wipSnapshotMaxBytes(env = process.env) {
111
+ const configured = Number.parseInt(env[wipSnapshotMaxBytesEnv] ?? "", 10);
112
+ return Number.isSafeInteger(configured) && configured > 0 ? configured : defaultWipSnapshotMaxBytes;
113
+ }
114
+ export function formatWipCommitMessage(metadata) {
115
+ return `forge wip snapshot (${metadata.reason}) of ${metadata.branch} at ${metadata.baseHead.slice(0, 12)}\n\n`
116
+ + `${JSON.stringify(metadata)}\n`;
117
+ }
118
+ /** The metadata of a WIP commit message, or null when the message is not one. */
119
+ export function parseWipCommitMessage(message) {
120
+ const start = message.indexOf("\n\n");
121
+ if (start < 0)
122
+ return null;
123
+ try {
124
+ const parsed = JSON.parse(message.slice(start + 2).trim());
125
+ if (parsed.schema !== wipMetadataSchema || typeof parsed.baseHead !== "string"
126
+ || typeof parsed.branch !== "string" || typeof parsed.createdAtMs !== "number") {
127
+ return null;
128
+ }
129
+ return {
130
+ ...parsed,
131
+ unmerged: Array.isArray(parsed.unmerged) ? parsed.unmerged : [],
132
+ autoRestore: parsed.autoRestore === true,
133
+ reapplyConflicts: Array.isArray(parsed.reapplyConflicts)
134
+ ? parsed.reapplyConflicts.filter(conflict => typeof conflict === "string")
135
+ : [],
136
+ };
137
+ }
138
+ catch {
139
+ return null;
140
+ }
141
+ }
142
+ /** A raw commit object's message: everything after its header block. */
143
+ export function commitMessageOf(rawCommit) {
144
+ const separator = rawCommit.indexOf("\n\n");
145
+ return separator < 0 ? "" : rawCommit.slice(separator + 2);
146
+ }
@@ -0,0 +1,46 @@
1
+ import type { ProcessRunner } from "../shared/process/process.js";
2
+ export interface WipRestoreRequest {
3
+ readonly worktreePath: string;
4
+ readonly repoPath: string;
5
+ readonly branchName: string;
6
+ readonly processRunner?: ProcessRunner;
7
+ }
8
+ export type WipRestoreOutcome = {
9
+ readonly status: "none";
10
+ } | {
11
+ readonly status: "restored";
12
+ readonly ref: string;
13
+ readonly commitSha: string;
14
+ readonly baseHead: string;
15
+ readonly sourceSessionId: string | null;
16
+ readonly changedPaths: number;
17
+ readonly mergeInProgress: boolean;
18
+ /** Set when the branch had moved and the snapshot was re-applied onto its new HEAD with a 3-way merge. */
19
+ readonly reapplied: WipReapply | null;
20
+ } | {
21
+ readonly status: "not_restored";
22
+ readonly ref: string;
23
+ readonly commitSha: string;
24
+ readonly reason: "branch_moved" | "apply_failed";
25
+ readonly baseHead: string;
26
+ readonly currentHead: string;
27
+ readonly detail: string;
28
+ } | {
29
+ readonly status: "skipped_dirty";
30
+ readonly ref: string;
31
+ readonly commitSha: string;
32
+ } | {
33
+ readonly status: "unavailable";
34
+ readonly detail: string;
35
+ };
36
+ export interface WipReapply {
37
+ /** The HEAD the snapshot was taken on, used as the merge base. */
38
+ readonly snapshotBaseHead: string;
39
+ /** Paths the merge left unmerged, with conflict markers where Git writes them, for the agent to resolve. */
40
+ readonly conflictedPaths: readonly string[];
41
+ }
42
+ export declare function restoreLatestWip(request: WipRestoreRequest): Promise<WipRestoreOutcome>;
43
+ /** Deletes a WIP ref (on origin, or locally when there is no origin). Never throws. */
44
+ export declare function deleteWipRef(repoPath: string, ref: string, processRunner?: ProcessRunner): Promise<boolean>;
45
+ /** True when the worktree holds nothing a snapshot would save (Forge runtime output aside), and no merge. */
46
+ export declare function hasNoUnsavedWork(worktreePath: string, processRunner?: ProcessRunner): Promise<boolean>;