@loucompanion/forge-bridge 0.1.4-dev.8f4846c6e7a9 → 0.1.4-dev.91ee995ac965

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (227) hide show
  1. package/README.md +142 -1
  2. package/dist/bridge/bridge-chat-provider-command.d.ts +19 -0
  3. package/dist/bridge/bridge-chat-provider-command.js +132 -0
  4. package/dist/bridge/bridge-chat.types.d.ts +10 -0
  5. package/dist/bridge/bridge-chat.types.js +16 -1
  6. package/dist/bridge/bridge-state-file.d.ts +161 -0
  7. package/dist/bridge/bridge-state-file.js +376 -0
  8. package/dist/bridge/bridge-state-io.d.ts +11 -0
  9. package/dist/bridge/bridge-state-io.js +50 -0
  10. package/dist/bridge/bridge-state-lock.d.ts +11 -0
  11. package/dist/bridge/bridge-state-lock.js +102 -0
  12. package/dist/bridge/bridge-state-unpublished.d.ts +17 -0
  13. package/dist/bridge/bridge-state-unpublished.js +111 -0
  14. package/dist/bridge/bridge.base.d.ts +9 -0
  15. package/dist/bridge/bridge.service.d.ts +87 -14
  16. package/dist/bridge/bridge.service.js +403 -341
  17. package/dist/bridge/bridge.types.d.ts +16 -0
  18. package/dist/bridge/in-flight-registry.d.ts +62 -0
  19. package/dist/bridge/in-flight-registry.js +207 -0
  20. package/dist/bridge/local-yield-flag.d.ts +6 -0
  21. package/dist/bridge/local-yield-flag.js +34 -0
  22. package/dist/bridge/readiness-result-outbox.d.ts +5 -1
  23. package/dist/bridge/readiness-result-outbox.js +20 -0
  24. package/dist/bridge/runner-host-capabilities.d.ts +3 -0
  25. package/dist/bridge/runner-host-capabilities.js +13 -0
  26. package/dist/bridge/sandbox-resource-accounting.d.ts +16 -0
  27. package/dist/bridge/sandbox-resource-accounting.js +150 -0
  28. package/dist/cleanup/cleanup-wip.d.ts +12 -0
  29. package/dist/cleanup/cleanup-wip.js +66 -0
  30. package/dist/cleanup/cleanup.service.d.ts +20 -1
  31. package/dist/cleanup/cleanup.service.js +154 -153
  32. package/dist/cleanup/cleanup.types.d.ts +6 -0
  33. package/dist/cleanup/forge-owned-paths.d.ts +9 -0
  34. package/dist/cleanup/forge-owned-paths.js +53 -0
  35. package/dist/cleanup/host-runtime-ledger.d.ts +5 -0
  36. package/dist/cleanup/host-runtime-ledger.js +109 -0
  37. package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
  38. package/dist/cleanup/managed-branch-sweep.js +111 -0
  39. package/dist/cli/cli.help.js +74 -12
  40. package/dist/cli/cli.service.d.ts +19 -10
  41. package/dist/cli/cli.service.js +150 -187
  42. package/dist/cli/idle-status.d.ts +84 -0
  43. package/dist/cli/idle-status.js +181 -0
  44. package/dist/cli/local-config.d.ts +6 -0
  45. package/dist/cli/local-config.js +32 -4
  46. package/dist/cli/provider-cli-detection.d.ts +10 -0
  47. package/dist/cli/provider-cli-detection.js +160 -0
  48. package/dist/runtime/aspnet-runtime-prebuild.d.ts +5 -0
  49. package/dist/runtime/aspnet-runtime-prebuild.js +140 -7
  50. package/dist/runtime/attempt-database-broker.d.ts +1 -1
  51. package/dist/runtime/docker-engine-probe.d.ts +5 -0
  52. package/dist/runtime/docker-engine-probe.js +7 -0
  53. package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
  54. package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
  55. package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
  56. package/dist/runtime/ephemeral-test-postgres.js +303 -0
  57. package/dist/runtime/host-facts.d.ts +2 -1
  58. package/dist/runtime/host-load-admission.d.ts +18 -3
  59. package/dist/runtime/host-load-admission.js +19 -4
  60. package/dist/runtime/host-load-child-environment.d.ts +27 -0
  61. package/dist/runtime/host-load-child-environment.js +76 -0
  62. package/dist/runtime/host-load-forge-cgroups.d.ts +41 -0
  63. package/dist/runtime/host-load-forge-cgroups.js +93 -4
  64. package/dist/runtime/host-load-governor-config.d.ts +19 -1
  65. package/dist/runtime/host-load-governor-config.js +37 -0
  66. package/dist/runtime/host-load-governor.d.ts +74 -11
  67. package/dist/runtime/host-load-governor.js +284 -67
  68. package/dist/runtime/host-load-ledger-lock.js +6 -4
  69. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  70. package/dist/runtime/host-load-runtime-settings.js +80 -0
  71. package/dist/runtime/host-load-sampler.d.ts +39 -4
  72. package/dist/runtime/host-load-sampler.js +83 -9
  73. package/dist/runtime/host-load-step-class.d.ts +37 -0
  74. package/dist/runtime/host-load-step-class.js +117 -2
  75. package/dist/runtime/host-load-step-reaper.d.ts +27 -0
  76. package/dist/runtime/host-load-step-reaper.js +95 -0
  77. package/dist/runtime/host-load-step-run.d.ts +73 -0
  78. package/dist/runtime/host-load-step-run.js +102 -0
  79. package/dist/runtime/host-load-test-slot.d.ts +43 -0
  80. package/dist/runtime/host-load-test-slot.js +81 -0
  81. package/dist/runtime/host-load-token-ledger.d.ts +82 -17
  82. package/dist/runtime/host-load-token-ledger.js +187 -79
  83. package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
  84. package/dist/runtime/host-load-windows-cpu.js +85 -0
  85. package/dist/runtime/host-runtime-contract.d.ts +12 -0
  86. package/dist/runtime/host-runtime-contract.js +29 -1
  87. package/dist/runtime/host-runtime-lease.d.ts +62 -3
  88. package/dist/runtime/host-runtime-lease.js +262 -57
  89. package/dist/runtime/host-runtime-promotion.d.ts +23 -0
  90. package/dist/runtime/host-runtime-promotion.js +36 -0
  91. package/dist/runtime/managed-command-teardown.js +5 -16
  92. package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
  93. package/dist/runtime/native-test-postgres-fallback.js +60 -8
  94. package/dist/runtime/playwright-host-runtime-adapter.d.ts +7 -0
  95. package/dist/runtime/playwright-host-runtime-adapter.js +13 -1
  96. package/dist/runtime/runner-settings.d.ts +104 -0
  97. package/dist/runtime/runner-settings.js +236 -0
  98. package/dist/sandbox/host-capacity-broker.d.ts +115 -0
  99. package/dist/sandbox/host-capacity-broker.js +336 -0
  100. package/dist/sandbox/managed-branch.d.ts +13 -0
  101. package/dist/sandbox/managed-branch.js +36 -0
  102. package/dist/sandbox/provider-auth/codex.js +11 -11
  103. package/dist/sandbox/runtime.d.ts +10 -1
  104. package/dist/sandbox/runtime.js +47 -8
  105. package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
  106. package/dist/sandbox/sandbox-cgroups.js +42 -0
  107. package/dist/session/architect-waits.d.ts +2 -0
  108. package/dist/session/architect-waits.js +138 -0
  109. package/dist/session/managed-attempt-tools.d.ts +2 -7
  110. package/dist/session/managed-attempt-tools.js +202 -116
  111. package/dist/session/managed-build-receipt.d.ts +5 -0
  112. package/dist/session/managed-build-receipt.js +8 -3
  113. package/dist/session/managed-command-host-load.d.ts +47 -0
  114. package/dist/session/managed-command-host-load.js +83 -0
  115. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  116. package/dist/session/mcp-argument-coercion.js +121 -0
  117. package/dist/session/phase-completion.artifacts.d.ts +7 -0
  118. package/dist/session/phase-completion.artifacts.js +96 -26
  119. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  120. package/dist/session/phase-completion.command-validation.js +77 -0
  121. package/dist/session/phase-completion.d.ts +12 -0
  122. package/dist/session/phase-completion.helpers.js +13 -12
  123. package/dist/session/phase-completion.js +5 -0
  124. package/dist/session/phase-completion.mcp-args.d.ts +9 -0
  125. package/dist/session/phase-completion.mcp-args.js +156 -0
  126. package/dist/session/phase-completion.prompts.js +6 -1
  127. package/dist/session/phase-completion.runtime.d.ts +5 -11
  128. package/dist/session/phase-completion.runtime.js +91 -215
  129. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  130. package/dist/session/phase-completion.schema-parts.js +188 -0
  131. package/dist/session/phase-completion.schemas.d.ts +3 -3
  132. package/dist/session/phase-completion.schemas.js +208 -231
  133. package/dist/session/phase-completion.validation.d.ts +2 -3
  134. package/dist/session/phase-completion.validation.js +49 -93
  135. package/dist/session/pre-publication-host-load.js +31 -16
  136. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  137. package/dist/session/pre-publication-native-postgres.js +111 -0
  138. package/dist/session/pre-publication-pass.d.ts +61 -0
  139. package/dist/session/pre-publication-pass.js +148 -0
  140. package/dist/session/pre-publication-process.d.ts +3 -0
  141. package/dist/session/pre-publication-process.js +31 -19
  142. package/dist/session/pre-publication-step-execution.d.ts +2 -1
  143. package/dist/session/pre-publication-step-execution.js +6 -5
  144. package/dist/session/pre-publication-validation.d.ts +30 -14
  145. package/dist/session/pre-publication-validation.js +211 -134
  146. package/dist/session/provider-cli/claude-background-work.d.ts +67 -0
  147. package/dist/session/provider-cli/claude-background-work.js +181 -0
  148. package/dist/session/provider-cli/host-build-lock.d.ts +18 -0
  149. package/dist/session/provider-cli/host-build-lock.js +30 -0
  150. package/dist/session/provider-cli/pre-publication-repair.d.ts +56 -0
  151. package/dist/session/provider-cli/pre-publication-repair.js +276 -0
  152. package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
  153. package/dist/session/provider-cli/provider-cli.child-environment.js +75 -0
  154. package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
  155. package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
  156. package/dist/session/provider-cli/provider-cli.process.d.ts +15 -36
  157. package/dist/session/provider-cli/provider-cli.process.js +41 -432
  158. package/dist/session/provider-cli/provider-cli.prompts.d.ts +5 -0
  159. package/dist/session/provider-cli/provider-cli.prompts.js +72 -32
  160. package/dist/session/provider-cli/provider-cli.runtime.d.ts +8 -0
  161. package/dist/session/provider-cli/provider-cli.runtime.js +29 -1
  162. package/dist/session/provider-cli/provider-cli.service.d.ts +7 -1
  163. package/dist/session/provider-cli/provider-cli.service.js +97 -182
  164. package/dist/session/provider-cli/provider-cli.types.d.ts +30 -0
  165. package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
  166. package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
  167. package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
  168. package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
  169. package/dist/session/provider-cli/provider-in-flight-work.d.ts +4 -0
  170. package/dist/session/provider-cli/provider-in-flight-work.js +45 -0
  171. package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
  172. package/dist/session/provider-cli/provider-output-pipes.js +67 -0
  173. package/dist/session/provider-cli/provider-output-state.d.ts +2 -0
  174. package/dist/session/provider-cli/provider-output-state.js +6 -0
  175. package/dist/session/provider-cli/provider-user-config-isolation.d.ts +69 -0
  176. package/dist/session/provider-cli/provider-user-config-isolation.js +164 -0
  177. package/dist/session/qa-sidecar-validation.d.ts +6 -0
  178. package/dist/session/qa-sidecar-validation.js +28 -0
  179. package/dist/session/sandbox-host-capacity-gate.d.ts +51 -0
  180. package/dist/session/sandbox-host-capacity-gate.js +257 -0
  181. package/dist/session/session-redaction.js +31 -181
  182. package/dist/session/session.base.d.ts +6 -1
  183. package/dist/session/session.service.d.ts +9 -2
  184. package/dist/session/session.service.js +177 -61
  185. package/dist/session/session.types.js +4 -4
  186. package/dist/session/sidecar-json-shape.d.ts +31 -0
  187. package/dist/session/sidecar-json-shape.js +217 -0
  188. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  189. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  190. package/dist/shared/fs/file-identity.d.ts +10 -0
  191. package/dist/shared/fs/file-identity.js +15 -0
  192. package/dist/shared/fs/replace-file.d.ts +7 -0
  193. package/dist/shared/fs/replace-file.js +33 -0
  194. package/dist/shared/process/host-process-recovery.d.ts +14 -3
  195. package/dist/shared/process/host-process-recovery.js +23 -3
  196. package/dist/shared/process/host-process-supervisor.d.ts +14 -1
  197. package/dist/shared/process/host-process-supervisor.js +67 -15
  198. package/dist/shared/process/process-tree.d.ts +52 -0
  199. package/dist/shared/process/process-tree.js +144 -0
  200. package/dist/shared/process/process.d.ts +67 -0
  201. package/dist/shared/process/process.js +213 -11
  202. package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
  203. package/dist/shared/process/windows-app-execution-alias.js +45 -0
  204. package/dist/shared/process/windows-launch.d.ts +18 -0
  205. package/dist/shared/process/windows-launch.js +68 -0
  206. package/dist/shared/provider-capabilities.js +14 -7
  207. package/dist/version.d.ts +1 -1
  208. package/dist/version.js +1 -1
  209. package/dist/worktree/dependency-warmer.d.ts +25 -0
  210. package/dist/worktree/dependency-warmer.js +46 -10
  211. package/dist/worktree/wip-git.d.ts +33 -0
  212. package/dist/worktree/wip-git.js +122 -0
  213. package/dist/worktree/wip-refs.d.ts +62 -0
  214. package/dist/worktree/wip-refs.js +119 -0
  215. package/dist/worktree/wip-restore.d.ts +38 -0
  216. package/dist/worktree/wip-restore.js +190 -0
  217. package/dist/worktree/wip-snapshot.d.ts +50 -0
  218. package/dist/worktree/wip-snapshot.js +268 -0
  219. package/dist/worktree/worktree-wip-events.d.ts +18 -0
  220. package/dist/worktree/worktree-wip-events.js +98 -0
  221. package/dist/worktree/worktree-wip.d.ts +49 -0
  222. package/dist/worktree/worktree-wip.js +182 -0
  223. package/dist/worktree/worktree.base.d.ts +7 -1
  224. package/dist/worktree/worktree.service.d.ts +16 -3
  225. package/dist/worktree/worktree.service.js +58 -13
  226. package/dist/worktree/worktree.types.d.ts +29 -0
  227. package/package.json +2 -2
@@ -0,0 +1,49 @@
1
+ import { GitClient } from "../shared/git/git.js";
2
+ import { type WipRestoreOutcome } from "./wip-restore.js";
3
+ import { type WipSnapshotResult } from "./wip-snapshot.js";
4
+ import type { WipSessionOutcome, WipSettlement, WorktreeHandle } from "./worktree.types.js";
5
+ /**
6
+ * Saves uncommitted work before `git reset --hard` / `git clean` on an existing worktree; a later
7
+ * pass may apply it by itself only when it came from a publishing lane.
8
+ * Throws when it could not be saved: losing work is worse than a failed prepare.
9
+ */
10
+ export declare function guardWorktreeReset(worktreePath: string, branchName: string, owner: {
11
+ readonly sessionId?: string | null;
12
+ readonly lane: string;
13
+ }): Promise<WipSnapshotResult>;
14
+ /**
15
+ * Before a local branch is re-pointed at a new start point (`worktree add -B`), saves any commits
16
+ * on it that neither the start point nor origin has, as a `forge.wip.v1` snapshot like any other:
17
+ * its tree is the tip's, its first parent the tip (so the commits are `<ref>^1` and its ancestors),
18
+ * and it is never applied automatically. Throws when they could not be saved.
19
+ */
20
+ export declare function guardBranchReset(git: GitClient, repoPath: string, branchName: string, startPoint: string): Promise<void>;
21
+ /** Puts the newest restorable snapshot back on a freshly prepared worktree of a publishing lane. */
22
+ export declare function restoreWorktreeWip(input: {
23
+ readonly worktreePath: string;
24
+ readonly repoPath: string;
25
+ readonly branchName: string;
26
+ readonly sessionId?: string | null;
27
+ readonly lane: string;
28
+ }): Promise<WipRestoreOutcome | undefined>;
29
+ /**
30
+ * Saves a worktree that is about to be deleted. Its snapshot is never applied automatically (a
31
+ * session that ended without succeeding has already saved its own work under its id; what is
32
+ * left after a successful pass was deliberately not published). Throws when it could not be saved.
33
+ */
34
+ export declare function guardWorktreeRelease(handle: WorktreeHandle): Promise<WipSnapshotResult>;
35
+ /** Forgets what this process saved for a worktree once it is gone. */
36
+ export declare function worktreeReleased(handle: WorktreeHandle): void;
37
+ /**
38
+ * At the end of a session: saves its uncommitted work unless it succeeded, and deletes the
39
+ * snapshot it started from once that work is safe elsewhere: saved again here, or (after a
40
+ * success) published, which is only certain when nothing is left uncommitted. Leftovers keep the
41
+ * ref; the release's own snapshot of them is never applied automatically.
42
+ * Never throws; a failure is reported in the result.
43
+ */
44
+ export declare function settleSessionWip(handle: WorktreeHandle, outcome: WipSessionOutcome): Promise<WipSettlement>;
45
+ /**
46
+ * After a release: deletes the readiness probe's branch, and other Forge branches whose work is
47
+ * already on the base. Branches of live leases are kept; when the ledger can't be read, nothing is.
48
+ */
49
+ export declare function sweepBranchesAfterRelease(git: GitClient, handle: WorktreeHandle, leaseStateRoot: string, limit: number): Promise<void>;
@@ -0,0 +1,182 @@
1
+ import { liveLeaseBranches, readHostRuntimeLeases } from "../cleanup/host-runtime-ledger.js";
2
+ import { deleteBranchIfUnused, isRuntimeReadinessBranch, sweepManagedBranches } from "../cleanup/managed-branch-sweep.js";
3
+ import { WipGit } from "./wip-git.js";
4
+ import { formatWipCommitMessage, unorderedWipAttempt, wipMetadataSchema, WipPreservationError, wipRefId, wipRefName, } from "./wip-refs.js";
5
+ import { deleteWipRef, hasNoUnsavedWork, restoreLatestWip } from "./wip-restore.js";
6
+ import { forgetPreservedWip, forgetPreservedWipRef, preserveWorktreeWip } from "./wip-snapshot.js";
7
+ // How the worktree lifecycle keeps uncommitted work (see wip-refs.ts for the ref layout):
8
+ // - every path that could destroy it (a reset to the base, re-pointing the branch, a release that
9
+ // deletes the checkout) saves it to a WIP ref first and does not run when that fails;
10
+ // - a session that ends without succeeding saves it under the session's id;
11
+ // - a publishing lane's next pass puts the newest snapshot back when the branch has not moved.
12
+ /** Lanes whose work the bridge publishes, and so whose snapshots a later pass may apply by itself. */
13
+ const restoreLanes = new Set(["develop", "debug", "conflict_resolve", "ci_repair"]);
14
+ function isWipRestoreLane(lane) {
15
+ return restoreLanes.has((lane ?? "").trim().toLowerCase());
16
+ }
17
+ /**
18
+ * Saves uncommitted work before `git reset --hard` / `git clean` on an existing worktree; a later
19
+ * pass may apply it by itself only when it came from a publishing lane.
20
+ * Throws when it could not be saved: losing work is worse than a failed prepare.
21
+ */
22
+ export async function guardWorktreeReset(worktreePath, branchName, owner) {
23
+ try {
24
+ return await preserveWorktreeWip({
25
+ worktreePath,
26
+ branchName,
27
+ reason: "pre_reset",
28
+ sessionId: owner.sessionId,
29
+ lane: owner.lane,
30
+ autoRestore: isWipRestoreLane(owner.lane),
31
+ });
32
+ }
33
+ catch (error) {
34
+ throw new Error(`Refusing to reset ${worktreePath} to its base: its uncommitted work could not be saved to a WIP ref (${errorMessage(error)}).`, { cause: error });
35
+ }
36
+ }
37
+ /**
38
+ * Before a local branch is re-pointed at a new start point (`worktree add -B`), saves any commits
39
+ * on it that neither the start point nor origin has, as a `forge.wip.v1` snapshot like any other:
40
+ * its tree is the tip's, its first parent the tip (so the commits are `<ref>^1` and its ancestors),
41
+ * and it is never applied automatically. Throws when they could not be saved.
42
+ */
43
+ export async function guardBranchReset(git, repoPath, branchName, startPoint) {
44
+ const tip = (await git.run(repoPath, ["rev-parse", "-q", "--verify", `refs/heads/${branchName}^{commit}`]).catch(() => "")).trim();
45
+ if (!tip)
46
+ return;
47
+ const onStartPoint = await git.run(repoPath, ["merge-base", "--is-ancestor", tip, startPoint]).then(() => true, () => false);
48
+ if (onStartPoint)
49
+ return;
50
+ const onOrigin = (await git.run(repoPath, ["branch", "-r", "--contains", tip]).catch(() => "")).trim().length > 0;
51
+ if (onOrigin)
52
+ return;
53
+ const now = new Date();
54
+ const ref = wipRefName(branchName, wipRefId("pre_branch_reset", null, now));
55
+ const origin = (await git.run(repoPath, ["remote", "get-url", "origin"]).catch(() => "")).trim();
56
+ try {
57
+ const snapshot = await branchTipSnapshot(repoPath, branchName, tip, now);
58
+ await git.run(repoPath, origin ? ["push", "--porcelain", "origin", `${snapshot}:${ref}`] : ["update-ref", ref, snapshot]);
59
+ }
60
+ catch (error) {
61
+ throw new Error(`Refusing to re-point ${branchName} at ${startPoint}: its unpublished commits (${tip.slice(0, 12)}) could not be saved to ${ref} (${errorMessage(error)}).`, { cause: error });
62
+ }
63
+ }
64
+ /** A snapshot commit holding a branch tip: nothing uncommitted, so its tree and index are the tip's. */
65
+ async function branchTipSnapshot(repoPath, branchName, tip, now) {
66
+ const git = new WipGit();
67
+ const tree = (await git.run(repoPath, ["rev-parse", `${tip}^{tree}`])).trim();
68
+ const indexCommit = (await git.run(repoPath, ["commit-tree", tree, "-p", tip, "-m", "forge wip index snapshot"])).trim();
69
+ const message = formatWipCommitMessage({
70
+ schema: wipMetadataSchema,
71
+ branch: branchName,
72
+ baseHead: tip,
73
+ sessionId: null,
74
+ lane: null,
75
+ reason: "pre_branch_reset",
76
+ attempt: unorderedWipAttempt,
77
+ autoRestore: false,
78
+ createdAt: now.toISOString(),
79
+ createdAtMs: now.getTime(),
80
+ mergeHead: null,
81
+ mergeMessage: null,
82
+ mergeMode: null,
83
+ unmerged: [],
84
+ changedPaths: 0,
85
+ bytes: 0,
86
+ });
87
+ return (await git.run(repoPath, ["commit-tree", tree, "-p", tip, "-p", indexCommit, "-m", message])).trim();
88
+ }
89
+ /** Puts the newest restorable snapshot back on a freshly prepared worktree of a publishing lane. */
90
+ export async function restoreWorktreeWip(input) {
91
+ if (!input.sessionId || !isWipRestoreLane(input.lane))
92
+ return undefined;
93
+ return await restoreLatestWip(input);
94
+ }
95
+ /**
96
+ * Saves a worktree that is about to be deleted. Its snapshot is never applied automatically (a
97
+ * session that ended without succeeding has already saved its own work under its id; what is
98
+ * left after a successful pass was deliberately not published). Throws when it could not be saved.
99
+ */
100
+ export async function guardWorktreeRelease(handle) {
101
+ // A readiness probe never runs an agent; its checkout only ever holds the app's own output.
102
+ if (isRuntimeReadinessBranch(handle.branchName))
103
+ return { status: "clean" };
104
+ return await preserveWorktreeWip({
105
+ worktreePath: handle.worktreePath,
106
+ branchName: handle.branchName,
107
+ reason: "pre_release",
108
+ sessionId: handle.sessionId,
109
+ lane: handle.lane,
110
+ autoRestore: false,
111
+ });
112
+ }
113
+ /** Forgets what this process saved for a worktree once it is gone. */
114
+ export function worktreeReleased(handle) {
115
+ forgetPreservedWip(handle.worktreePath);
116
+ }
117
+ /**
118
+ * At the end of a session: saves its uncommitted work unless it succeeded, and deletes the
119
+ * snapshot it started from once that work is safe elsewhere: saved again here, or (after a
120
+ * success) published, which is only certain when nothing is left uncommitted. Leftovers keep the
121
+ * ref; the release's own snapshot of them is never applied automatically.
122
+ * Never throws; a failure is reported in the result.
123
+ */
124
+ export async function settleSessionWip(handle, outcome) {
125
+ let snapshot;
126
+ if (outcome.reason) {
127
+ try {
128
+ snapshot = await preserveWorktreeWip({
129
+ worktreePath: handle.worktreePath,
130
+ branchName: handle.branchName,
131
+ reason: outcome.reason,
132
+ sessionId: handle.sessionId,
133
+ lane: handle.lane,
134
+ autoRestore: isWipRestoreLane(handle.lane),
135
+ });
136
+ }
137
+ catch (error) {
138
+ return {
139
+ error: {
140
+ code: error instanceof WipPreservationError ? error.code : "wip_snapshot_failed",
141
+ message: errorMessage(error),
142
+ },
143
+ };
144
+ }
145
+ }
146
+ const restored = handle.wipRestore?.status === "restored" ? handle.wipRestore.ref : null;
147
+ // A failed session that left a clean worktree may have thrown the restored work away; keep its ref.
148
+ const supersededBy = snapshot && snapshot.status !== "clean" ? snapshot.ref : null;
149
+ const safeElsewhere = outcome.reason === null
150
+ ? await hasNoUnsavedWork(handle.worktreePath).catch(() => false)
151
+ : Boolean(supersededBy && supersededBy !== restored);
152
+ const retire = restored && safeElsewhere ? restored : null;
153
+ if (retire)
154
+ forgetPreservedWipRef(retire);
155
+ const retiredRef = retire && await deleteWipRef(handle.repoPath, retire) ? retire : null;
156
+ return { ...(snapshot ? { snapshot } : {}), retiredRef };
157
+ }
158
+ /**
159
+ * After a release: deletes the readiness probe's branch, and other Forge branches whose work is
160
+ * already on the base. Branches of live leases are kept; when the ledger can't be read, nothing is.
161
+ */
162
+ export async function sweepBranchesAfterRelease(git, handle, leaseStateRoot, limit) {
163
+ const protectedBranches = await readHostRuntimeLeases(leaseStateRoot)
164
+ .then(liveLeaseBranches)
165
+ .catch(() => null);
166
+ if (!protectedBranches)
167
+ return;
168
+ let budget = limit;
169
+ if (isRuntimeReadinessBranch(handle.branchName) && !protectedBranches.has(handle.branchName)
170
+ && await deleteBranchIfUnused(git, handle.repoPath, handle.branchName)) {
171
+ budget -= 1;
172
+ }
173
+ await sweepManagedBranches(git, handle.repoPath, {
174
+ baseBranch: handle.baseBranch,
175
+ includeMergedWorkBranches: true,
176
+ protectedBranches,
177
+ limit: budget,
178
+ }).catch(() => undefined);
179
+ }
180
+ function errorMessage(error) {
181
+ return error instanceof Error ? error.message : String(error);
182
+ }
@@ -1,7 +1,13 @@
1
- import type { WorktreeHandle, WorktreePrepareRequest } from "./worktree.types.js";
1
+ import type { WipSessionOutcome, WipSettlement, WorktreeHandle, WorktreePrepareRequest } from "./worktree.types.js";
2
2
  export interface WorktreeService {
3
3
  prepare(request: WorktreePrepareRequest): Promise<WorktreeHandle>;
4
+ /**
5
+ * Must not delete uncommitted work it could not save first: it keeps the worktree and throws a
6
+ * WipPreservationError instead.
7
+ */
4
8
  release(handle: WorktreeHandle): Promise<void>;
9
+ /** Saves (or retires) the session's WIP when it ends; never throws. */
10
+ settleWip?(handle: WorktreeHandle, outcome: WipSessionOutcome): Promise<WipSettlement>;
5
11
  }
6
12
  export interface WorktreeLifecycleCoordinator {
7
13
  withLock<T>(repoPath: string, action: () => Promise<T>, signal?: AbortSignal): Promise<T>;
@@ -1,11 +1,25 @@
1
1
  import { GitClient } from "../shared/git/git.js";
2
+ import type { HostLoadStepGate } from "../runtime/host-load-governor.js";
2
3
  import type { WorktreeLifecycleCoordinator, WorktreeService } from "./worktree.base.js";
3
- import type { WorktreeHandle, WorktreePrepareRequest } from "./worktree.types.js";
4
+ import type { WipSessionOutcome, WipSettlement, WorktreeHandle, WorktreePrepareRequest } from "./worktree.types.js";
5
+ export { emitWipRestoreEvent, sessionWipOutcome, settleWorktree } from "./worktree-wip-events.js";
4
6
  export declare class GitWorktreeService implements WorktreeService {
5
7
  private readonly git;
6
8
  private readonly coordinator;
7
- constructor(git?: GitClient, coordinator?: WorktreeLifecycleCoordinator);
9
+ /** Gates dependency install fallbacks; inert unless the governor is on. */
10
+ private readonly hostLoadGate?;
11
+ /** Holds the host runtime lease ledger; branches of live leases are never swept on release. */
12
+ private readonly leaseStateRoot;
13
+ constructor(git?: GitClient, coordinator?: WorktreeLifecycleCoordinator,
14
+ /** Gates dependency install fallbacks; inert unless the governor is on. */
15
+ hostLoadGate?: HostLoadStepGate | undefined,
16
+ /** Holds the host runtime lease ledger; branches of live leases are never swept on release. */
17
+ leaseStateRoot?: string);
8
18
  prepare(request: WorktreePrepareRequest): Promise<WorktreeHandle>;
19
+ private warmDependencies;
20
+ /** Restores the story's saved WIP (still under the repository lock, before the provider starts). */
21
+ private withRestoredWip;
22
+ settleWip(handle: WorktreeHandle, outcome: WipSessionOutcome): Promise<WipSettlement>;
9
23
  private trackedForgePaths;
10
24
  private registeredManagedWorktreePath;
11
25
  private repoCreationCoordinationPath;
@@ -27,4 +41,3 @@ export declare function renameWorktreeForRelease(source: string, destination: st
27
41
  export declare function requiresMutableEnvironmentPreparation(request: Pick<WorktreePrepareRequest, "applicationRuntimeRequired">): boolean;
28
42
  export declare function clearRunArtifactRoots(worktreePath: string, request: WorktreePrepareRequest): Promise<void>;
29
43
  export declare function normalizeBranchName(value: string | null | undefined, fallback: string): string;
30
- export {};
@@ -8,13 +8,25 @@ import { filterArtifactsForLane, injectWorktreeArtifacts } from "./artifact-inje
8
8
  import { hydratePriorPhaseArtifacts } from "./prior-phase-artifact-hydrator.js";
9
9
  import { materializeStoryQaReferences } from "./story-qa-reference-hydrator.js";
10
10
  import { warmWorktreeDependencies } from "./dependency-warmer.js";
11
+ import { guardBranchReset, guardWorktreeRelease, guardWorktreeReset, restoreWorktreeWip, settleSessionWip, sweepBranchesAfterRelease, worktreeReleased, } from "./worktree-wip.js";
11
12
  import { defaultWorktreeCoordinatorStateRoot, managedRepoRoot, resolveManagedWorktreeRoot, } from "./worktree-paths.js";
13
+ export { emitWipRestoreEvent, sessionWipOutcome, settleWorktree } from "./worktree-wip-events.js";
14
+ // Bounds the branch sweep that runs after each release, so one release never holds the repository lock long.
15
+ const releaseSweepLimit = 25;
12
16
  export class GitWorktreeService {
13
17
  git;
14
18
  coordinator;
15
- constructor(git = new GitClient(), coordinator = new RepositoryCoordinatorLock(defaultWorktreeCoordinatorStateRoot())) {
19
+ hostLoadGate;
20
+ leaseStateRoot;
21
+ constructor(git = new GitClient(), coordinator = new RepositoryCoordinatorLock(defaultWorktreeCoordinatorStateRoot()),
22
+ /** Gates dependency install fallbacks; inert unless the governor is on. */
23
+ hostLoadGate,
24
+ /** Holds the host runtime lease ledger; branches of live leases are never swept on release. */
25
+ leaseStateRoot = defaultWorktreeCoordinatorStateRoot()) {
16
26
  this.git = git;
17
27
  this.coordinator = coordinator;
28
+ this.hostLoadGate = hostLoadGate;
29
+ this.leaseStateRoot = leaseStateRoot;
18
30
  }
19
31
  async prepare(request) {
20
32
  const allowedRoot = await ensureDirectory(request.allowedRepoRoot);
@@ -29,7 +41,7 @@ export class GitWorktreeService {
29
41
  const repoPath = await this.coordinator.withLock(creationCoordinationPath, async () => {
30
42
  return await this.resolveRepoPath(request.repo, allowedRoot, baseBranch);
31
43
  });
32
- const resolvedWorktreePath = await this.coordinator.withLock(repoPath, async () => {
44
+ const { worktreePath: resolvedWorktreePath, wipRestore } = await this.coordinator.withLock(repoPath, async () => {
33
45
  await this.ensureGitIdentity(repoPath);
34
46
  const baseStartPoint = await this.resolveBaseStartPoint(repoPath, baseBranch);
35
47
  const worktreeRoot = resolveManagedWorktreeRoot(allowedRoot, repoPath);
@@ -54,9 +66,10 @@ export class GitWorktreeService {
54
66
  await this.git.run(repoPath, ["worktree", "add", worktreePath, branchName]);
55
67
  }
56
68
  else {
69
+ await guardBranchReset(this.git, repoPath, branchName, baseStartPoint);
57
70
  await this.git.run(repoPath, ["worktree", "add", "-B", branchName, worktreePath, baseStartPoint]);
58
71
  }
59
- return await resolveExistingDirectoryPath(worktreePath);
72
+ return await this.withRestoredWip(request, repoPath, branchName, await resolveExistingDirectoryPath(worktreePath));
60
73
  }
61
74
  // The selected checkout can change when a Bridge reconnects or a local
62
75
  // runner takes over. Its managed root therefore changes even though the
@@ -82,9 +95,10 @@ export class GitWorktreeService {
82
95
  throw new Error(`Existing worktree ${existingWorktreePath} is on branch '${currentBranch}', expected '${branchName}'.`);
83
96
  }
84
97
  if (!request.preserveExistingState && shouldResetExistingWorktree(request)) {
98
+ await guardWorktreeReset(existingWorktreePath, branchName, request);
85
99
  await this.resetWorktreeToBase(existingWorktreePath, baseStartPoint);
86
100
  }
87
- return existingWorktreePath;
101
+ return await this.withRestoredWip(request, repoPath, branchName, existingWorktreePath);
88
102
  });
89
103
  // Reference inputs and an exact-tree local repair checkpoint must survive output cleanup.
90
104
  await materializeStoryQaReferences(resolvedWorktreePath, request, this.git);
@@ -97,14 +111,7 @@ export class GitWorktreeService {
97
111
  if (artifacts.length > 0) {
98
112
  await injectWorktreeArtifacts(resolvedWorktreePath, artifacts, await this.trackedForgePaths(resolvedWorktreePath));
99
113
  }
100
- const dependencyWarm = requiresMutableEnvironmentPreparation(request)
101
- ? await warmWorktreeDependencies({
102
- baseCheckoutPath: repoPath,
103
- worktreePath: resolvedWorktreePath,
104
- allowedRoot,
105
- warmPathOverrides: request.warmPathOverrides
106
- })
107
- : undefined;
114
+ const dependencyWarm = await this.warmDependencies(request, repoPath, resolvedWorktreePath, allowedRoot);
108
115
  return {
109
116
  repoPath,
110
117
  worktreePath: resolvedWorktreePath,
@@ -113,9 +120,38 @@ export class GitWorktreeService {
113
120
  cleanupWorktrees: request.cleanupWorktrees,
114
121
  dependencyWarm,
115
122
  qaReworkPacketPath,
116
- hydratedPriorPhaseArtifactCount
123
+ hydratedPriorPhaseArtifactCount,
124
+ sessionId: request.sessionId ?? null,
125
+ lane: request.lane,
126
+ ...(wipRestore ? { wipRestore } : {}),
117
127
  };
118
128
  }
129
+ async warmDependencies(request, repoPath, worktreePath, allowedRoot) {
130
+ if (!requiresMutableEnvironmentPreparation(request))
131
+ return undefined;
132
+ return await warmWorktreeDependencies({
133
+ baseCheckoutPath: repoPath,
134
+ worktreePath,
135
+ allowedRoot,
136
+ warmPathOverrides: request.warmPathOverrides,
137
+ hostLoad: this.hostLoadGate?.enabled
138
+ ? {
139
+ gate: this.hostLoadGate,
140
+ dispatchAttemptId: request.hostLoadOwner?.dispatchAttemptId ?? null,
141
+ priority: request.hostLoadOwner?.priority ?? "foreground",
142
+ }
143
+ : undefined,
144
+ signal: request.signal,
145
+ });
146
+ }
147
+ /** Restores the story's saved WIP (still under the repository lock, before the provider starts). */
148
+ async withRestoredWip(request, repoPath, branchName, worktreePath) {
149
+ const wipRestore = await restoreWorktreeWip({ worktreePath, repoPath, branchName, sessionId: request.sessionId, lane: request.lane });
150
+ return { worktreePath, ...(wipRestore ? { wipRestore } : {}) };
151
+ }
152
+ async settleWip(handle, outcome) {
153
+ return await settleSessionWip(handle, outcome);
154
+ }
119
155
  async trackedForgePaths(worktreePath) {
120
156
  const output = await this.git.run(worktreePath, ["ls-files", "-z", "--", ".forge"]);
121
157
  return new Set(output.split("\0").filter(Boolean).map(value => value.replaceAll("\\", "/")));
@@ -145,6 +181,8 @@ export class GitWorktreeService {
145
181
  }
146
182
  await this.coordinator.withLock(handle.repoPath, async () => {
147
183
  if (await directoryExists(handle.worktreePath)) {
184
+ // Never delete work that could not be saved: this throws and keeps the worktree.
185
+ await guardWorktreeRelease(handle);
148
186
  // On Windows, `git worktree remove` can delete the `.git` link and then
149
187
  // fail on a locked build output. That leaves a full source tree which is
150
188
  // no longer a Git worktree and makes every retry fail during prepare.
@@ -164,6 +202,12 @@ export class GitWorktreeService {
164
202
  // directory is fully materialized (or after an external cleanup removes it).
165
203
  // Always prune so those missing-directory registrations do not accumulate.
166
204
  await this.git.run(handle.repoPath, ["worktree", "prune", "--expire", "now"]).catch(() => undefined);
205
+ worktreeReleased(handle);
206
+ // A readiness probe's branch goes with its worktree. Other Forge branches on this device
207
+ // whose work is already merged into the base go too; branches with unmerged work stay.
208
+ // A lease can be live while its worktree is briefly missing, so its branch is protected
209
+ // even when no worktree has it checked out. If the ledger can't be read, sweep nothing.
210
+ await sweepBranchesAfterRelease(this.git, handle, this.leaseStateRoot, releaseSweepLimit);
167
211
  });
168
212
  }
169
213
  async restoreOrphanedWorktree(input) {
@@ -175,6 +219,7 @@ export class GitWorktreeService {
175
219
  if (!isSubPath(input.allowedRoot, quarantinePath)) {
176
220
  throw new Error(`Worktree recovery path must stay under ${input.allowedRoot}.`);
177
221
  }
222
+ await guardBranchReset(this.git, input.repoPath, input.branchName, input.baseStartPoint);
178
223
  await fs.rename(input.worktreePath, quarantinePath);
179
224
  try {
180
225
  await this.git.run(input.repoPath, ["worktree", "prune", "--expire", "now"]);
@@ -1,5 +1,8 @@
1
1
  import type { DispatchQaReworkContext, DispatchPriorPhaseArtifact, DispatchRepo, DispatchWorkItem, DispatchResolvedArtifact, DispatchStoryQaContext } from "../session/session.types.js";
2
2
  import type { WarmDependenciesResult } from "./dependency-warmer.js";
3
+ import type { WipSnapshotReason } from "./wip-refs.js";
4
+ import type { WipRestoreOutcome } from "./wip-restore.js";
5
+ import type { WipSnapshotResult } from "./wip-snapshot.js";
3
6
  export interface WorktreePrepareRequest {
4
7
  readonly repo: DispatchRepo;
5
8
  readonly workItem: DispatchWorkItem;
@@ -21,6 +24,15 @@ export interface WorktreePrepareRequest {
21
24
  readonly warmPathOverrides?: readonly string[];
22
25
  readonly applicationRuntimeRequired?: boolean;
23
26
  readonly preserveExistingState?: boolean;
27
+ /** The session this worktree is prepared for; names its WIP snapshots and enables restoring one. */
28
+ readonly sessionId?: string | null;
29
+ /** The attempt dependency installs reserve host capacity for (decision 0013). */
30
+ readonly hostLoadOwner?: {
31
+ readonly dispatchAttemptId: string | null;
32
+ readonly priority: "foreground" | "background";
33
+ };
34
+ /** The attempt's cancellation: queued installs stop waiting and running ones are stopped. */
35
+ readonly signal?: AbortSignal;
24
36
  }
25
37
  export interface WorktreeHandle {
26
38
  readonly repoPath: string;
@@ -31,4 +43,21 @@ export interface WorktreeHandle {
31
43
  readonly dependencyWarm?: WarmDependenciesResult;
32
44
  readonly qaReworkPacketPath?: string;
33
45
  readonly hydratedPriorPhaseArtifactCount?: number;
46
+ readonly sessionId?: string | null;
47
+ readonly lane?: string;
48
+ /** What happened to the story's saved WIP when this worktree was prepared. */
49
+ readonly wipRestore?: WipRestoreOutcome;
50
+ }
51
+ /** How a session ended, for its WIP snapshot: null when it succeeded. */
52
+ export interface WipSessionOutcome {
53
+ readonly reason: WipSnapshotReason | null;
54
+ }
55
+ export interface WipSettlement {
56
+ readonly snapshot?: WipSnapshotResult;
57
+ readonly error?: {
58
+ readonly code: string;
59
+ readonly message: string;
60
+ };
61
+ /** The restored snapshot's ref, deleted because this session's work supersedes it. */
62
+ readonly retiredRef?: string | null;
34
63
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@loucompanion/forge-bridge",
3
- "version": "0.1.4-dev.8f4846c6e7a9",
3
+ "version": "0.1.4-dev.91ee995ac965",
4
4
  "description": "Forge runner bridge CLI for connecting local developer machines to Forge dispatch.",
5
5
  "license": "UNLICENSED",
6
6
  "type": "module",
@@ -43,7 +43,7 @@
43
43
  "test:residue": "node scripts/run-owned-residue-gate.mjs",
44
44
  "test:watch": "vitest",
45
45
  "smoke:package": "tsc -p tsconfig.json && node scripts/smoke-package.mjs",
46
- "lint": "eslint \"src/**/*.ts\" \"scripts/**/*.mjs\" \"vitest.config.ts\" \"vitest.setup.ts\""
46
+ "lint": "eslint \"src/**/*.ts\" \"scripts/**/*.mjs\" \"vitest.config.ts\" \"vitest.setup.ts\" && node ../../scripts/class-design/check-eslint-ratchet.mjs bridge"
47
47
  },
48
48
  "dependencies": {
49
49
  "@microsoft/signalr": "^8.0.17",