@loucompanion/forge-bridge 0.1.4-dev.c1ae24134918 → 0.1.4-dev.cabe9c22da46

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 (191) hide show
  1. package/README.md +142 -1
  2. package/dist/bridge/bridge-chat-provider-command.d.ts +19 -0
  3. package/dist/bridge/bridge-chat-provider-command.js +132 -0
  4. package/dist/bridge/bridge-chat.types.d.ts +10 -0
  5. package/dist/bridge/bridge-chat.types.js +16 -1
  6. package/dist/bridge/bridge-state-file.d.ts +161 -0
  7. package/dist/bridge/bridge-state-file.js +376 -0
  8. package/dist/bridge/bridge-state-io.d.ts +11 -0
  9. package/dist/bridge/bridge-state-io.js +50 -0
  10. package/dist/bridge/bridge-state-lock.d.ts +11 -0
  11. package/dist/bridge/bridge-state-lock.js +102 -0
  12. package/dist/bridge/bridge-state-unpublished.d.ts +17 -0
  13. package/dist/bridge/bridge-state-unpublished.js +111 -0
  14. package/dist/bridge/bridge.base.d.ts +9 -0
  15. package/dist/bridge/bridge.service.d.ts +87 -14
  16. package/dist/bridge/bridge.service.js +394 -338
  17. package/dist/bridge/bridge.types.d.ts +16 -0
  18. package/dist/bridge/in-flight-registry.d.ts +62 -0
  19. package/dist/bridge/in-flight-registry.js +207 -0
  20. package/dist/bridge/local-yield-flag.d.ts +6 -0
  21. package/dist/bridge/local-yield-flag.js +34 -0
  22. package/dist/bridge/readiness-result-outbox.d.ts +5 -1
  23. package/dist/bridge/readiness-result-outbox.js +20 -0
  24. package/dist/bridge/runner-host-capabilities.d.ts +3 -0
  25. package/dist/bridge/runner-host-capabilities.js +13 -0
  26. package/dist/bridge/sandbox-resource-accounting.d.ts +16 -0
  27. package/dist/bridge/sandbox-resource-accounting.js +150 -0
  28. package/dist/cleanup/cleanup.service.d.ts +9 -0
  29. package/dist/cleanup/cleanup.service.js +76 -115
  30. package/dist/cleanup/cleanup.types.d.ts +4 -0
  31. package/dist/cleanup/forge-owned-paths.d.ts +9 -0
  32. package/dist/cleanup/forge-owned-paths.js +53 -0
  33. package/dist/cleanup/host-runtime-ledger.d.ts +5 -0
  34. package/dist/cleanup/host-runtime-ledger.js +109 -0
  35. package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
  36. package/dist/cleanup/managed-branch-sweep.js +111 -0
  37. package/dist/cli/cli.help.js +74 -12
  38. package/dist/cli/cli.service.d.ts +19 -10
  39. package/dist/cli/cli.service.js +149 -186
  40. package/dist/cli/idle-status.d.ts +84 -0
  41. package/dist/cli/idle-status.js +181 -0
  42. package/dist/cli/local-config.d.ts +6 -0
  43. package/dist/cli/local-config.js +32 -4
  44. package/dist/cli/provider-cli-detection.d.ts +10 -0
  45. package/dist/cli/provider-cli-detection.js +160 -0
  46. package/dist/runtime/aspnet-runtime-prebuild.d.ts +5 -0
  47. package/dist/runtime/aspnet-runtime-prebuild.js +140 -7
  48. package/dist/runtime/attempt-database-broker.d.ts +1 -1
  49. package/dist/runtime/docker-engine-probe.d.ts +5 -0
  50. package/dist/runtime/docker-engine-probe.js +7 -0
  51. package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
  52. package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
  53. package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
  54. package/dist/runtime/ephemeral-test-postgres.js +303 -0
  55. package/dist/runtime/host-facts.d.ts +2 -1
  56. package/dist/runtime/host-load-admission.d.ts +18 -3
  57. package/dist/runtime/host-load-admission.js +19 -4
  58. package/dist/runtime/host-load-child-environment.d.ts +11 -6
  59. package/dist/runtime/host-load-child-environment.js +22 -11
  60. package/dist/runtime/host-load-governor-config.d.ts +19 -1
  61. package/dist/runtime/host-load-governor-config.js +37 -0
  62. package/dist/runtime/host-load-governor.d.ts +12 -0
  63. package/dist/runtime/host-load-governor.js +139 -26
  64. package/dist/runtime/host-load-ledger-lock.js +6 -4
  65. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  66. package/dist/runtime/host-load-runtime-settings.js +80 -0
  67. package/dist/runtime/host-load-sampler.d.ts +34 -4
  68. package/dist/runtime/host-load-sampler.js +73 -7
  69. package/dist/runtime/host-load-step-class.d.ts +3 -1
  70. package/dist/runtime/host-load-step-class.js +60 -5
  71. package/dist/runtime/host-load-test-slot.d.ts +43 -0
  72. package/dist/runtime/host-load-test-slot.js +81 -0
  73. package/dist/runtime/host-load-token-ledger.d.ts +26 -0
  74. package/dist/runtime/host-load-token-ledger.js +93 -61
  75. package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
  76. package/dist/runtime/host-load-windows-cpu.js +85 -0
  77. package/dist/runtime/host-runtime-contract.d.ts +12 -0
  78. package/dist/runtime/host-runtime-contract.js +29 -1
  79. package/dist/runtime/host-runtime-lease.d.ts +59 -3
  80. package/dist/runtime/host-runtime-lease.js +209 -58
  81. package/dist/runtime/host-runtime-promotion.d.ts +23 -0
  82. package/dist/runtime/host-runtime-promotion.js +36 -0
  83. package/dist/runtime/managed-command-teardown.js +5 -16
  84. package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
  85. package/dist/runtime/native-test-postgres-fallback.js +60 -8
  86. package/dist/runtime/playwright-host-runtime-adapter.d.ts +7 -0
  87. package/dist/runtime/playwright-host-runtime-adapter.js +13 -1
  88. package/dist/runtime/runner-settings.d.ts +104 -0
  89. package/dist/runtime/runner-settings.js +236 -0
  90. package/dist/sandbox/host-capacity-broker.d.ts +10 -2
  91. package/dist/sandbox/host-capacity-broker.js +27 -6
  92. package/dist/sandbox/provider-auth/codex.js +11 -11
  93. package/dist/session/architect-waits.d.ts +2 -0
  94. package/dist/session/architect-waits.js +138 -0
  95. package/dist/session/managed-attempt-tools.d.ts +2 -7
  96. package/dist/session/managed-attempt-tools.js +89 -99
  97. package/dist/session/managed-build-receipt.d.ts +5 -0
  98. package/dist/session/managed-build-receipt.js +8 -3
  99. package/dist/session/managed-command-host-load.d.ts +2 -0
  100. package/dist/session/managed-command-host-load.js +2 -1
  101. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  102. package/dist/session/mcp-argument-coercion.js +121 -0
  103. package/dist/session/phase-completion.artifacts.d.ts +7 -0
  104. package/dist/session/phase-completion.artifacts.js +96 -26
  105. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  106. package/dist/session/phase-completion.command-validation.js +77 -0
  107. package/dist/session/phase-completion.d.ts +10 -0
  108. package/dist/session/phase-completion.helpers.js +13 -12
  109. package/dist/session/phase-completion.js +5 -0
  110. package/dist/session/phase-completion.mcp-args.d.ts +9 -0
  111. package/dist/session/phase-completion.mcp-args.js +156 -0
  112. package/dist/session/phase-completion.prompts.js +6 -1
  113. package/dist/session/phase-completion.runtime.d.ts +4 -10
  114. package/dist/session/phase-completion.runtime.js +77 -209
  115. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  116. package/dist/session/phase-completion.schema-parts.js +188 -0
  117. package/dist/session/phase-completion.schemas.d.ts +3 -3
  118. package/dist/session/phase-completion.schemas.js +208 -231
  119. package/dist/session/phase-completion.validation.d.ts +2 -3
  120. package/dist/session/phase-completion.validation.js +49 -93
  121. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  122. package/dist/session/pre-publication-native-postgres.js +111 -0
  123. package/dist/session/pre-publication-pass.d.ts +61 -0
  124. package/dist/session/pre-publication-pass.js +148 -0
  125. package/dist/session/pre-publication-process.js +10 -10
  126. package/dist/session/pre-publication-step-execution.d.ts +2 -1
  127. package/dist/session/pre-publication-step-execution.js +6 -5
  128. package/dist/session/pre-publication-validation.d.ts +30 -14
  129. package/dist/session/pre-publication-validation.js +207 -134
  130. package/dist/session/provider-cli/claude-background-work.d.ts +67 -0
  131. package/dist/session/provider-cli/claude-background-work.js +181 -0
  132. package/dist/session/provider-cli/host-build-lock.d.ts +18 -0
  133. package/dist/session/provider-cli/host-build-lock.js +30 -0
  134. package/dist/session/provider-cli/pre-publication-repair.d.ts +56 -0
  135. package/dist/session/provider-cli/pre-publication-repair.js +276 -0
  136. package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
  137. package/dist/session/provider-cli/provider-cli.child-environment.js +75 -0
  138. package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
  139. package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
  140. package/dist/session/provider-cli/provider-cli.process.d.ts +15 -36
  141. package/dist/session/provider-cli/provider-cli.process.js +39 -430
  142. package/dist/session/provider-cli/provider-cli.prompts.d.ts +5 -0
  143. package/dist/session/provider-cli/provider-cli.prompts.js +72 -32
  144. package/dist/session/provider-cli/provider-cli.runtime.d.ts +8 -0
  145. package/dist/session/provider-cli/provider-cli.runtime.js +29 -1
  146. package/dist/session/provider-cli/provider-cli.service.d.ts +7 -1
  147. package/dist/session/provider-cli/provider-cli.service.js +78 -171
  148. package/dist/session/provider-cli/provider-cli.types.d.ts +26 -0
  149. package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
  150. package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
  151. package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
  152. package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
  153. package/dist/session/provider-cli/provider-in-flight-work.d.ts +4 -0
  154. package/dist/session/provider-cli/provider-in-flight-work.js +45 -0
  155. package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
  156. package/dist/session/provider-cli/provider-output-pipes.js +67 -0
  157. package/dist/session/provider-cli/provider-output-state.d.ts +2 -0
  158. package/dist/session/provider-cli/provider-output-state.js +6 -0
  159. package/dist/session/provider-cli/provider-user-config-isolation.d.ts +69 -0
  160. package/dist/session/provider-cli/provider-user-config-isolation.js +164 -0
  161. package/dist/session/qa-sidecar-validation.d.ts +6 -0
  162. package/dist/session/qa-sidecar-validation.js +28 -0
  163. package/dist/session/sandbox-host-capacity-gate.d.ts +22 -1
  164. package/dist/session/sandbox-host-capacity-gate.js +42 -14
  165. package/dist/session/session-redaction.js +31 -181
  166. package/dist/session/session.base.d.ts +6 -1
  167. package/dist/session/session.service.d.ts +7 -2
  168. package/dist/session/session.service.js +100 -2
  169. package/dist/session/session.types.js +4 -4
  170. package/dist/session/sidecar-json-shape.d.ts +31 -0
  171. package/dist/session/sidecar-json-shape.js +217 -0
  172. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  173. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  174. package/dist/shared/fs/file-identity.d.ts +10 -0
  175. package/dist/shared/fs/file-identity.js +15 -0
  176. package/dist/shared/fs/replace-file.d.ts +7 -0
  177. package/dist/shared/fs/replace-file.js +33 -0
  178. package/dist/shared/process/host-process-recovery.d.ts +14 -3
  179. package/dist/shared/process/host-process-recovery.js +23 -3
  180. package/dist/shared/process/host-process-supervisor.d.ts +13 -1
  181. package/dist/shared/process/host-process-supervisor.js +66 -14
  182. package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
  183. package/dist/shared/process/windows-app-execution-alias.js +45 -0
  184. package/dist/shared/process/windows-launch.d.ts +18 -0
  185. package/dist/shared/process/windows-launch.js +68 -0
  186. package/dist/shared/provider-capabilities.js +14 -7
  187. package/dist/version.d.ts +1 -1
  188. package/dist/version.js +1 -1
  189. package/dist/worktree/worktree.service.d.ts +5 -1
  190. package/dist/worktree/worktree.service.js +29 -1
  191. package/package.json +2 -2
@@ -1,12 +1,14 @@
1
1
  import { randomUUID } from "node:crypto";
2
- import { constants as fsConstants } from "node:fs";
3
2
  import fs from "node:fs/promises";
4
3
  import path from "node:path";
5
4
  import { RepositoryCoordinatorLock } from "../sandbox/repository-lock.js";
5
+ import { fileIdentityChanged } from "../shared/fs/file-identity.js";
6
6
  import { GitClient } from "../shared/git/git.js";
7
7
  import { isSubPath, resolveExistingDirectoryPath, resolvePathIdentity } from "../shared/path/path.js";
8
- import { validRuntimeIsolationLease } from "../runtime/runtime-isolation-lease.js";
9
8
  import { defaultWorktreeCoordinatorStateRoot, resolveManagedWorktreeRootForRepo, } from "../worktree/worktree-paths.js";
9
+ import { isForgeOwnedWorktreePath, isForgeWorktreeContainer, isRuntimeReadinessName } from "./forge-owned-paths.js";
10
+ import { liveLeaseBranches, readHostRuntimeLeases } from "./host-runtime-ledger.js";
11
+ import { sweepManagedBranches } from "./managed-branch-sweep.js";
10
12
  const staleRuntimeReadinessAgeMs = 30 * 60 * 1000;
11
13
  export class ManagedWorktreeCleanupService {
12
14
  stateRoot;
@@ -31,15 +33,30 @@ export class ManagedWorktreeCleanupService {
31
33
  }
32
34
  async runLocked(repoPath, worktreeRoot, request) {
33
35
  if (request.mode === "merged") {
34
- if (request.force)
35
- await this.git.run(repoPath, ["worktree", "prune"]);
36
- return emptyResult(worktreeRoot, request.force);
36
+ if (!request.force)
37
+ return emptyResult(worktreeRoot, request.force);
38
+ await this.git.run(repoPath, ["worktree", "prune"]);
39
+ // Forge branches whose work is already on the base, and leftover readiness branches.
40
+ const baseBranch = await this.remoteBaseBranch(repoPath);
41
+ const sweep = await sweepManagedBranches(this.git, repoPath, {
42
+ ...(baseBranch ? { baseBranch } : {}),
43
+ includeMergedWorkBranches: baseBranch !== null,
44
+ protectedBranches: liveLeaseBranches(await this.readRuntimeLeases()),
45
+ });
46
+ return {
47
+ ...emptyResult(worktreeRoot, request.force),
48
+ deletedBranches: sweep.deletedBranches.length,
49
+ ...(baseBranch ? {} : { mergedBaseUnresolved: true }),
50
+ };
37
51
  }
38
52
  const safeRoot = await resolveSafeManagedRoot(worktreeRoot);
39
53
  if (!safeRoot) {
40
- if (request.force)
41
- await this.git.run(repoPath, ["worktree", "prune"]);
42
- return emptyResult(worktreeRoot, request.force);
54
+ if (!request.force)
55
+ return emptyResult(worktreeRoot, request.force);
56
+ await this.git.run(repoPath, ["worktree", "prune"]);
57
+ // No managed root left, but readiness branches can outlive it.
58
+ const sweep = await this.sweepReadinessBranches(repoPath);
59
+ return { ...emptyResult(worktreeRoot, request.force), deletedBranches: sweep.deletedBranches.length };
43
60
  }
44
61
  const [listedWorktrees, runtimeLeases] = await Promise.all([
45
62
  this.listWorktrees(repoPath),
@@ -49,7 +66,7 @@ export class ManagedWorktreeCleanupService {
49
66
  .filter(lease => lease.state !== "released")
50
67
  .map(lease => resolveRuntimeLeasePath(lease.worktreePath)));
51
68
  const metadataRoot = await this.worktreeMetadataRoot(repoPath);
52
- const staleReadinessPaths = await this.staleRuntimeReadinessPaths(listedWorktrees, activeRuntimePaths);
69
+ const staleReadinessPaths = await this.staleRuntimeReadinessPaths(safeRoot, listedWorktrees, activeRuntimePaths);
53
70
  const activeWorktrees = activePaths(listedWorktrees)
54
71
  .filter(activePath => !staleReadinessPaths.some(stalePath => samePath(stalePath, activePath)));
55
72
  if (request.mode === "all") {
@@ -99,7 +116,7 @@ export class ManagedWorktreeCleanupService {
99
116
  const currentRuntimePaths = await Promise.all(currentLeases
100
117
  .filter(lease => lease.state !== "released")
101
118
  .map(lease => resolveRuntimeLeasePath(lease.worktreePath)));
102
- const currentStaleReadinessPaths = await this.staleRuntimeReadinessPaths(currentWorktrees, currentRuntimePaths);
119
+ const currentStaleReadinessPaths = await this.staleRuntimeReadinessPaths(safeRoot, currentWorktrees, currentRuntimePaths);
103
120
  const currentlyProtected = [
104
121
  ...activePaths(currentWorktrees)
105
122
  .filter(activePath => !currentStaleReadinessPaths.some(stalePath => samePath(stalePath, activePath))),
@@ -117,6 +134,8 @@ export class ManagedWorktreeCleanupService {
117
134
  }
118
135
  }
119
136
  await this.git.run(repoPath, ["worktree", "prune"]);
137
+ // A readiness branch goes with its worktree; this also clears ones whose worktree is long gone.
138
+ const sweep = await this.sweepReadinessBranches(repoPath);
120
139
  return {
121
140
  worktreeRoot: safeRoot,
122
141
  removedWorktrees,
@@ -125,16 +144,47 @@ export class ManagedWorktreeCleanupService {
125
144
  skippedUnownedDirectories: scan.skippedUnownedDirectories,
126
145
  removedRoot: false,
127
146
  dryRun: false,
147
+ deletedBranches: sweep.deletedBranches.length,
128
148
  };
129
149
  }
150
+ async sweepReadinessBranches(repoPath) {
151
+ return await sweepManagedBranches(this.git, repoPath, {
152
+ includeMergedWorkBranches: false,
153
+ protectedBranches: liveLeaseBranches(await this.readRuntimeLeases()),
154
+ });
155
+ }
156
+ /**
157
+ * The branch merged work lands on: origin/HEAD when it points at a remote-tracking ref that
158
+ * exists, otherwise the only one of origin/develop, origin/main and origin/master that exists.
159
+ * Null when that's ambiguous or none exist, so the merged sweep is skipped (and reported)
160
+ * rather than measured against the wrong base.
161
+ */
162
+ async remoteBaseBranch(repoPath) {
163
+ const originHead = await this.git.run(repoPath, ["symbolic-ref", "--quiet", "--short", "refs/remotes/origin/HEAD"])
164
+ .catch(() => "");
165
+ const headBranch = originHead.trim().replace(/^origin\//, "");
166
+ // A stale origin/HEAD can name a branch whose remote-tracking ref has been pruned.
167
+ if (headBranch && await this.remoteBranchExists(repoPath, headBranch))
168
+ return headBranch;
169
+ const present = [];
170
+ for (const candidate of ["develop", "main", "master"]) {
171
+ if (await this.remoteBranchExists(repoPath, candidate))
172
+ present.push(candidate);
173
+ }
174
+ return present.length === 1 ? present[0] : null;
175
+ }
176
+ async remoteBranchExists(repoPath, branch) {
177
+ return await this.git.run(repoPath, ["rev-parse", "--verify", "--quiet", `refs/remotes/origin/${branch}^{commit}`])
178
+ .then(() => true, () => false);
179
+ }
130
180
  async listWorktrees(repoPath) {
131
181
  const output = await this.git.run(repoPath, ["worktree", "list", "--porcelain", "-z"]);
132
182
  return parseWorktreeListing(repoPath, output);
133
183
  }
134
- async staleRuntimeReadinessPaths(worktrees, runtimePaths) {
184
+ async staleRuntimeReadinessPaths(worktreeRoot, worktrees, runtimePaths) {
135
185
  const stale = [];
136
186
  for (const worktree of worktrees) {
137
- if (worktree.prunable || !isRuntimeReadinessWorktree(worktree))
187
+ if (worktree.prunable || !isRuntimeReadinessWorktree(worktreeRoot, worktree))
138
188
  continue;
139
189
  if (worktreePathState(worktree.worktreePath, runtimePaths) !== "none")
140
190
  continue;
@@ -199,12 +249,13 @@ export class ManagedWorktreeCleanupService {
199
249
  containsManagedDirectory = await visit(realEntry) || containsManagedDirectory;
200
250
  continue;
201
251
  }
202
- if (await forgeManagedCandidateIdentity(metadataRoot, realEntry)) {
252
+ const relativePath = path.relative(worktreeRoot, realEntry);
253
+ if (isForgeOwnedWorktreePath(relativePath) && await forgeManagedCandidateIdentity(metadataRoot, realEntry)) {
203
254
  candidates.push(realEntry);
204
255
  containsManagedDirectory = true;
205
256
  continue;
206
257
  }
207
- if (await visit(realEntry)) {
258
+ if (isForgeWorktreeContainer(relativePath) && await visit(realEntry)) {
208
259
  containsManagedDirectory = true;
209
260
  continue;
210
261
  }
@@ -217,28 +268,7 @@ export class ManagedWorktreeCleanupService {
217
268
  return { candidates, protectedWorktrees, skippedUnownedDirectories, rootRemovalSafe };
218
269
  }
219
270
  async readRuntimeLeases() {
220
- const ledgerRoot = path.join(this.stateRoot, "runtime-ledger", "host");
221
- const entries = await fs.readdir(ledgerRoot, { withFileTypes: true }).catch(error => {
222
- if (isEnoent(error))
223
- return [];
224
- throw error;
225
- });
226
- const leases = [];
227
- for (const entry of entries) {
228
- if (!entry.name.endsWith(".json"))
229
- continue;
230
- if (!entry.isFile() || entry.isSymbolicLink()) {
231
- throw new Error(`Refusing managed worktree cleanup because runtime ledger ${entry.name} is not a regular file.`);
232
- }
233
- const target = path.join(ledgerRoot, entry.name);
234
- const value = await readRuntimeLedger(target, entry.name);
235
- const runtimeLease = isRecord(value) ? value.runtimeLease : null;
236
- if (!validRuntimeIsolationLease(runtimeLease) || runtimeLease.mode !== "host") {
237
- throw new Error(`Refusing managed worktree cleanup because runtime ledger ${entry.name} has no trustworthy host lease.`);
238
- }
239
- leases.push(runtimeLease);
240
- }
241
- return leases;
271
+ return await readHostRuntimeLeases(this.stateRoot);
242
272
  }
243
273
  async worktreeMetadataRoot(repoPath) {
244
274
  const commonDirRaw = (await this.git.run(repoPath, ["rev-parse", "--git-common-dir"])).trim();
@@ -248,7 +278,7 @@ export class ManagedWorktreeCleanupService {
248
278
  }
249
279
  async function resolveRuntimeLeasePath(leasePath) {
250
280
  const resolved = path.resolve(leasePath);
251
- const before = await fs.lstat(resolved).catch(error => {
281
+ const before = await fs.lstat(resolved, { bigint: true }).catch(error => {
252
282
  if (isEnoent(error))
253
283
  return null;
254
284
  throw error;
@@ -259,82 +289,12 @@ async function resolveRuntimeLeasePath(leasePath) {
259
289
  throw new Error(`Refusing managed worktree cleanup because runtime lease path ${resolved} is redirected or is not a directory.`);
260
290
  }
261
291
  const real = await fs.realpath(resolved);
262
- const after = await fs.lstat(resolved);
263
- if (after.isSymbolicLink()
264
- || !after.isDirectory()
265
- || (before.dev !== 0 && before.ino !== 0 && after.dev !== 0 && after.ino !== 0
266
- && (before.dev !== after.dev || before.ino !== after.ino))) {
292
+ const after = await fs.lstat(resolved, { bigint: true });
293
+ if (after.isSymbolicLink() || !after.isDirectory() || fileIdentityChanged(before, after)) {
267
294
  throw new Error(`Refusing managed worktree cleanup because runtime lease path ${resolved} changed while being resolved.`);
268
295
  }
269
296
  return real;
270
297
  }
271
- async function readRuntimeLedger(target, entryName) {
272
- const pathStat = await fs.lstat(target).catch(error => {
273
- if (isEnoent(error))
274
- return null;
275
- throw error;
276
- });
277
- if (!pathStat) {
278
- throw new Error(`Refusing managed worktree cleanup because runtime ledger ${entryName} disappeared.`);
279
- }
280
- validateRuntimeLedgerStat(entryName, pathStat);
281
- let handle;
282
- try {
283
- handle = await fs.open(target, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW);
284
- }
285
- catch (error) {
286
- if (isEnoent(error) || errorCode(error) === "ELOOP") {
287
- throw new Error(`Refusing managed worktree cleanup because runtime ledger ${entryName} is not a regular file.`, { cause: error });
288
- }
289
- throw new Error(`Refusing managed worktree cleanup because runtime ledger ${entryName} could not be opened safely.`, { cause: error });
290
- }
291
- try {
292
- const openedStat = await handle.stat();
293
- const reopenedPathStat = await fs.lstat(target);
294
- validateRuntimeLedgerStat(entryName, openedStat);
295
- validateRuntimeLedgerStat(entryName, reopenedPathStat);
296
- validateSameRuntimeLedgerFile(entryName, pathStat, openedStat);
297
- validateSameRuntimeLedgerFile(entryName, openedStat, reopenedPathStat);
298
- const content = await handle.readFile("utf8");
299
- const afterStat = await handle.stat();
300
- const afterPathStat = await fs.lstat(target);
301
- validateRuntimeLedgerStat(entryName, afterStat);
302
- validateRuntimeLedgerStat(entryName, afterPathStat);
303
- validateSameRuntimeLedgerFile(entryName, openedStat, afterStat);
304
- validateSameRuntimeLedgerFile(entryName, afterStat, afterPathStat);
305
- if (openedStat.size !== afterStat.size || Buffer.byteLength(content, "utf8") !== afterStat.size) {
306
- throw new Error(`Refusing managed worktree cleanup because runtime ledger ${entryName} changed while being read.`);
307
- }
308
- try {
309
- return JSON.parse(content);
310
- }
311
- catch (error) {
312
- throw new Error(`Refusing managed worktree cleanup because runtime ledger ${entryName} is invalid.`, { cause: error });
313
- }
314
- }
315
- finally {
316
- await handle.close();
317
- }
318
- }
319
- function validateRuntimeLedgerStat(entryName, stat) {
320
- if (stat.isSymbolicLink() || !stat.isFile()) {
321
- throw new Error(`Refusing managed worktree cleanup because runtime ledger ${entryName} is not a regular file.`);
322
- }
323
- if (stat.size > 256 * 1024) {
324
- throw new Error(`Refusing managed worktree cleanup because runtime ledger ${entryName} is oversized.`);
325
- }
326
- }
327
- function validateSameRuntimeLedgerFile(entryName, before, after) {
328
- if (before.dev !== 0 && before.ino !== 0 && after.dev !== 0 && after.ino !== 0
329
- && (before.dev !== after.dev || before.ino !== after.ino)) {
330
- throw new Error(`Refusing managed worktree cleanup because runtime ledger ${entryName} changed while being read.`);
331
- }
332
- }
333
- function errorCode(error) {
334
- return typeof error === "object" && error !== null && "code" in error
335
- ? String(error.code)
336
- : undefined;
337
- }
338
298
  function emptyResult(worktreeRoot, force) {
339
299
  return {
340
300
  worktreeRoot: path.resolve(worktreeRoot),
@@ -466,9 +426,13 @@ function parseWorktreeListing(repoPath, output) {
466
426
  worktrees.push(current);
467
427
  return worktrees;
468
428
  }
469
- function isRuntimeReadinessWorktree(worktree) {
470
- return worktree.branchName?.startsWith("refs/heads/runtime-readiness-") === true
471
- || path.basename(worktree.worktreePath).startsWith("runtime-readiness-");
429
+ // A registered worktree counts as a readiness probe only when Forge made it: its folder sits
430
+ // directly in the managed root under the probe's exact name, and it has the probe's exact branch.
431
+ function isRuntimeReadinessWorktree(worktreeRoot, worktree) {
432
+ const folderName = path.basename(worktree.worktreePath);
433
+ return samePath(path.dirname(worktree.worktreePath), worktreeRoot)
434
+ && isRuntimeReadinessName(folderName)
435
+ && worktree.branchName === `refs/heads/${folderName}`;
472
436
  }
473
437
  function activePaths(worktrees) {
474
438
  return worktrees.filter(entry => !entry.prunable).map(entry => entry.worktreePath);
@@ -493,6 +457,3 @@ function samePath(left, right) {
493
457
  function isEnoent(error) {
494
458
  return error?.code === "ENOENT";
495
459
  }
496
- function isRecord(value) {
497
- return typeof value === "object" && value !== null && !Array.isArray(value);
498
- }
@@ -13,4 +13,8 @@ export interface CleanupResult {
13
13
  readonly skippedUnownedDirectories: number;
14
14
  readonly removedRoot: boolean;
15
15
  readonly dryRun: boolean;
16
+ /** Forge-created local branches deleted by this run: readiness branches, and in merged mode also merged work branches. */
17
+ readonly deletedBranches?: number;
18
+ /** Merged mode only: origin/HEAD was unset or stale and origin had none or several of develop, main and master, so merged work branches were left alone. */
19
+ readonly mergedBaseUnresolved?: boolean;
16
20
  }
@@ -0,0 +1,9 @@
1
+ import path from "node:path";
2
+ type PathSeparator = typeof path.posix.sep | typeof path.win32.sep;
3
+ /** True when `relativePath` (relative to the managed root) is a worktree path Forge creates. */
4
+ export declare function isForgeOwnedWorktreePath(relativePath: string, separator?: PathSeparator): boolean;
5
+ /** True when `relativePath` is one of the folders Forge groups its worktrees in. */
6
+ export declare function isForgeWorktreeContainer(relativePath: string, separator?: PathSeparator): boolean;
7
+ /** True for a readiness probe's exact folder or branch name: runtime-readiness-<UUID>. */
8
+ export declare function isRuntimeReadinessName(name: string): boolean;
9
+ export {};
@@ -0,0 +1,53 @@
1
+ // Cleanup may delete a worktree folder only when Forge itself created it for one of its own
2
+ // attempts. Forge places every such worktree at an exact path under the repository's managed root
3
+ // (`<repo parent>/.forge-worktrees/<repo name>`), built from the lease's worktree key:
4
+ // <kind>/<12 hex> a work item (story, task, bug, feature, work_order) or
5
+ // its Architect phase (architect)
6
+ // decompose/<feature|work_order>/<12 hex> a decompose session
7
+ // runtime-readiness-<UUID> a runtime readiness probe (session.service.ts)
8
+ // draft-<32 hex> a drafting session (DraftingService on the server)
9
+ // A release that couldn't finish deleting can leave `<one of those>.forge-release-<UUID>` beside it.
10
+ // Anything else under the root, such as a folder a person or another tool made there, is never
11
+ // removed, even if it is a Git worktree of the same repository.
12
+ import path from "node:path";
13
+ const hex12 = "[0-9a-f]{12}";
14
+ const uuid = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
15
+ const releaseSuffix = `(?:\\.forge-release-${uuid})?`;
16
+ const forgeOwnedWorktreePathPattern = new RegExp("^(?:"
17
+ + `(?:story|task|bug|feature|work_order|architect)/${hex12}`
18
+ + `|decompose/(?:feature|work_order)/${hex12}`
19
+ + `|runtime-readiness-${uuid}`
20
+ + "|draft-[0-9a-f]{32}"
21
+ + `)${releaseSuffix}$`);
22
+ const runtimeReadinessNamePattern = new RegExp(`^runtime-readiness-${uuid}$`);
23
+ // Folders that only group Forge's worktrees; cleanup may look inside them but never removes them.
24
+ const forgeWorktreeContainers = new Set([
25
+ "story",
26
+ "task",
27
+ "bug",
28
+ "feature",
29
+ "work_order",
30
+ "architect",
31
+ "decompose",
32
+ "decompose/feature",
33
+ "decompose/work_order",
34
+ ]);
35
+ // Split only on the separators the filesystem itself uses. On POSIX a backslash is an ordinary
36
+ // filename character, so a folder a person named `story\0123456789ab` must not read as Forge's
37
+ // `story/0123456789ab`. Windows accepts both `\` and `/`.
38
+ function normalizeRelativePath(relativePath, separator) {
39
+ const separators = separator === path.win32.sep ? /[\\/]+/u : /\/+/u;
40
+ return relativePath.split(separators).filter(segment => segment.length > 0).join("/");
41
+ }
42
+ /** True when `relativePath` (relative to the managed root) is a worktree path Forge creates. */
43
+ export function isForgeOwnedWorktreePath(relativePath, separator = path.sep) {
44
+ return forgeOwnedWorktreePathPattern.test(normalizeRelativePath(relativePath, separator));
45
+ }
46
+ /** True when `relativePath` is one of the folders Forge groups its worktrees in. */
47
+ export function isForgeWorktreeContainer(relativePath, separator = path.sep) {
48
+ return forgeWorktreeContainers.has(normalizeRelativePath(relativePath, separator));
49
+ }
50
+ /** True for a readiness probe's exact folder or branch name: runtime-readiness-<UUID>. */
51
+ export function isRuntimeReadinessName(name) {
52
+ return runtimeReadinessNamePattern.test(name);
53
+ }
@@ -0,0 +1,5 @@
1
+ import { type RuntimeIsolationLease } from "../runtime/runtime-isolation-lease.js";
2
+ /** Reads every host runtime lease, or throws if any ledger file can't be trusted. */
3
+ export declare function readHostRuntimeLeases(stateRoot: string): Promise<readonly RuntimeIsolationLease[]>;
4
+ /** Branches that a lease which isn't released yet may still use. */
5
+ export declare function liveLeaseBranches(leases: readonly RuntimeIsolationLease[]): ReadonlySet<string>;
@@ -0,0 +1,109 @@
1
+ import { constants as fsConstants } from "node:fs";
2
+ import fs from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { validRuntimeIsolationLease } from "../runtime/runtime-isolation-lease.js";
5
+ import { fileIdentityChanged } from "../shared/fs/file-identity.js";
6
+ // The host runtime ledger (<state root>/runtime-ledger/host/*.json) records every runtime lease this
7
+ // bridge holds. Cleanup reads it to keep live leases' worktrees and branches; any ledger it can't
8
+ // trust stops the cleanup rather than guessing.
9
+ /** Reads every host runtime lease, or throws if any ledger file can't be trusted. */
10
+ export async function readHostRuntimeLeases(stateRoot) {
11
+ const ledgerRoot = path.join(stateRoot, "runtime-ledger", "host");
12
+ const entries = await fs.readdir(ledgerRoot, { withFileTypes: true }).catch(error => {
13
+ if (isEnoent(error))
14
+ return [];
15
+ throw error;
16
+ });
17
+ const leases = [];
18
+ for (const entry of entries) {
19
+ if (!entry.name.endsWith(".json"))
20
+ continue;
21
+ if (!entry.isFile() || entry.isSymbolicLink()) {
22
+ throw new Error(`Refusing managed worktree cleanup because runtime ledger ${entry.name} is not a regular file.`);
23
+ }
24
+ const target = path.join(ledgerRoot, entry.name);
25
+ const value = await readRuntimeLedger(target, entry.name);
26
+ const runtimeLease = isRecord(value) ? value.runtimeLease : null;
27
+ if (!validRuntimeIsolationLease(runtimeLease) || runtimeLease.mode !== "host") {
28
+ throw new Error(`Refusing managed worktree cleanup because runtime ledger ${entry.name} has no trustworthy host lease.`);
29
+ }
30
+ leases.push(runtimeLease);
31
+ }
32
+ return leases;
33
+ }
34
+ async function readRuntimeLedger(target, entryName) {
35
+ const pathStat = await fs.lstat(target, { bigint: true }).catch(error => {
36
+ if (isEnoent(error))
37
+ return null;
38
+ throw error;
39
+ });
40
+ if (!pathStat) {
41
+ throw new Error(`Refusing managed worktree cleanup because runtime ledger ${entryName} disappeared.`);
42
+ }
43
+ validateRuntimeLedgerStat(entryName, pathStat);
44
+ let handle;
45
+ try {
46
+ handle = await fs.open(target, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW);
47
+ }
48
+ catch (error) {
49
+ if (isEnoent(error) || errorCode(error) === "ELOOP") {
50
+ throw new Error(`Refusing managed worktree cleanup because runtime ledger ${entryName} is not a regular file.`, { cause: error });
51
+ }
52
+ throw new Error(`Refusing managed worktree cleanup because runtime ledger ${entryName} could not be opened safely.`, { cause: error });
53
+ }
54
+ try {
55
+ const openedStat = await handle.stat({ bigint: true });
56
+ const reopenedPathStat = await fs.lstat(target, { bigint: true });
57
+ validateRuntimeLedgerStat(entryName, openedStat);
58
+ validateRuntimeLedgerStat(entryName, reopenedPathStat);
59
+ validateSameRuntimeLedgerFile(entryName, pathStat, openedStat);
60
+ validateSameRuntimeLedgerFile(entryName, openedStat, reopenedPathStat);
61
+ const content = await handle.readFile("utf8");
62
+ const afterStat = await handle.stat({ bigint: true });
63
+ const afterPathStat = await fs.lstat(target, { bigint: true });
64
+ validateRuntimeLedgerStat(entryName, afterStat);
65
+ validateRuntimeLedgerStat(entryName, afterPathStat);
66
+ validateSameRuntimeLedgerFile(entryName, openedStat, afterStat);
67
+ validateSameRuntimeLedgerFile(entryName, afterStat, afterPathStat);
68
+ if (openedStat.size !== afterStat.size || BigInt(Buffer.byteLength(content, "utf8")) !== afterStat.size) {
69
+ throw new Error(`Refusing managed worktree cleanup because runtime ledger ${entryName} changed while being read.`);
70
+ }
71
+ try {
72
+ return JSON.parse(content);
73
+ }
74
+ catch (error) {
75
+ throw new Error(`Refusing managed worktree cleanup because runtime ledger ${entryName} is invalid.`, { cause: error });
76
+ }
77
+ }
78
+ finally {
79
+ await handle.close();
80
+ }
81
+ }
82
+ function validateRuntimeLedgerStat(entryName, stat) {
83
+ if (stat.isSymbolicLink() || !stat.isFile()) {
84
+ throw new Error(`Refusing managed worktree cleanup because runtime ledger ${entryName} is not a regular file.`);
85
+ }
86
+ if (stat.size > 256n * 1024n) {
87
+ throw new Error(`Refusing managed worktree cleanup because runtime ledger ${entryName} is oversized.`);
88
+ }
89
+ }
90
+ function validateSameRuntimeLedgerFile(entryName, before, after) {
91
+ if (fileIdentityChanged(before, after)) {
92
+ throw new Error(`Refusing managed worktree cleanup because runtime ledger ${entryName} changed while being read.`);
93
+ }
94
+ }
95
+ function errorCode(error) {
96
+ return typeof error === "object" && error !== null && "code" in error
97
+ ? String(error.code)
98
+ : undefined;
99
+ }
100
+ /** Branches that a lease which isn't released yet may still use. */
101
+ export function liveLeaseBranches(leases) {
102
+ return new Set(leases.filter(lease => lease.state !== "released").map(lease => lease.worktreeKey));
103
+ }
104
+ function isEnoent(error) {
105
+ return error?.code === "ENOENT";
106
+ }
107
+ function isRecord(value) {
108
+ return typeof value === "object" && value !== null && !Array.isArray(value);
109
+ }
@@ -0,0 +1,27 @@
1
+ import { GitClient } from "../shared/git/git.js";
2
+ /** A readiness probe's branch: scratch that nothing reads once its worktree is gone. */
3
+ export declare function isRuntimeReadinessBranch(branchName: string): boolean;
4
+ /** A branch Forge named for a work item, Feature or Work Order. */
5
+ export declare function isForgeManagedWorkBranch(branchName: string): boolean;
6
+ export interface ManagedBranchSweepOptions {
7
+ /** Branch whose remote-tracking ref (origin/<base>) decides what counts as merged. */
8
+ readonly baseBranch?: string;
9
+ /** Also delete managed work branches whose changes are already on the base. */
10
+ readonly includeMergedWorkBranches: boolean;
11
+ /** Branches to keep whatever their state, e.g. ones a live lease is about to use. */
12
+ readonly protectedBranches?: ReadonlySet<string>;
13
+ /** Upper bound on branches deleted in one sweep, to keep the repository lock short. */
14
+ readonly limit?: number;
15
+ }
16
+ export interface ManagedBranchSweepResult {
17
+ readonly deletedBranches: readonly string[];
18
+ }
19
+ /**
20
+ * Deletes branches Forge created that no worktree has checked out: every readiness branch, and,
21
+ * when asked, every managed work branch whose changes are already on origin/<base> (as an ancestor,
22
+ * or because merging it into the base would change nothing, as after a squash merge). Branches with work that is not on the base
23
+ * are kept. Must run under the repository coordinator lock, like worktree creation.
24
+ */
25
+ export declare function sweepManagedBranches(git: GitClient, repoPath: string, options: ManagedBranchSweepOptions): Promise<ManagedBranchSweepResult>;
26
+ /** Deletes one branch unless a worktree still has it checked out. Never throws. */
27
+ export declare function deleteBranchIfUnused(git: GitClient, repoPath: string, branchName: string): Promise<boolean>;
@@ -0,0 +1,111 @@
1
+ // Every environment Forge spawns an agent in gets its own local branch: runtime-readiness-<request
2
+ // UUID> for a readiness probe (session.service.ts), <kind>/<12 hex> for a work item (story/, task/,
3
+ // bug/, and architect/ for its Architect phase), and decompose/<feature|work_order>/<12 hex> for a
4
+ // decompose session (ManagedWorkItemBranchNames on the server). Only those exact shapes count, so a
5
+ // person's branch such as fix/0123456789ab or runtime-readiness-hotfix is never touched. The server
6
+ // removes the ones in its own checkout when a pull request merges; this sweep lets every device
7
+ // remove its own, so nothing piles up wherever a bridge runs.
8
+ const runtimeReadinessBranchPattern = /^runtime-readiness-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
9
+ const managedWorkBranchPattern = /^(?:(?:story|task|bug|architect)|decompose\/(?:feature|work_order))\/[0-9a-f]{12}$/;
10
+ /** A readiness probe's branch: scratch that nothing reads once its worktree is gone. */
11
+ export function isRuntimeReadinessBranch(branchName) {
12
+ return runtimeReadinessBranchPattern.test(branchName);
13
+ }
14
+ /** A branch Forge named for a work item, Feature or Work Order. */
15
+ export function isForgeManagedWorkBranch(branchName) {
16
+ return managedWorkBranchPattern.test(branchName);
17
+ }
18
+ /**
19
+ * Deletes branches Forge created that no worktree has checked out: every readiness branch, and,
20
+ * when asked, every managed work branch whose changes are already on origin/<base> (as an ancestor,
21
+ * or because merging it into the base would change nothing, as after a squash merge). Branches with work that is not on the base
22
+ * are kept. Must run under the repository coordinator lock, like worktree creation.
23
+ */
24
+ export async function sweepManagedBranches(git, repoPath, options) {
25
+ const limit = options.limit ?? Number.POSITIVE_INFINITY;
26
+ const checkedOut = await checkedOutBranches(git, repoPath);
27
+ const baseRef = options.includeMergedWorkBranches && options.baseBranch
28
+ ? await existingRef(git, repoPath, `refs/remotes/origin/${options.baseBranch}`)
29
+ : null;
30
+ const branches = (await git.run(repoPath, ["for-each-ref", "--format=%(refname:short)", "refs/heads"]))
31
+ .split("\n")
32
+ .map(line => line.trim())
33
+ .filter(Boolean);
34
+ const deletedBranches = [];
35
+ for (const branch of branches) {
36
+ if (deletedBranches.length >= limit)
37
+ break;
38
+ if (checkedOut.has(branch) || options.protectedBranches?.has(branch))
39
+ continue;
40
+ const readiness = isRuntimeReadinessBranch(branch);
41
+ if (!readiness) {
42
+ if (!baseRef || !isForgeManagedWorkBranch(branch))
43
+ continue;
44
+ if (!(await changesAreOnBase(git, repoPath, branch, baseRef)))
45
+ continue;
46
+ }
47
+ try {
48
+ await git.run(repoPath, ["branch", "-D", "--", branch]);
49
+ deletedBranches.push(branch);
50
+ }
51
+ catch {
52
+ // A branch another process just checked out or removed is not ours to fight over.
53
+ }
54
+ }
55
+ return { deletedBranches };
56
+ }
57
+ /** Deletes one branch unless a worktree still has it checked out. Never throws. */
58
+ export async function deleteBranchIfUnused(git, repoPath, branchName) {
59
+ try {
60
+ if ((await checkedOutBranches(git, repoPath)).has(branchName))
61
+ return false;
62
+ if (!(await existingRef(git, repoPath, `refs/heads/${branchName}`)))
63
+ return false;
64
+ await git.run(repoPath, ["branch", "-D", "--", branchName]);
65
+ return true;
66
+ }
67
+ catch {
68
+ return false;
69
+ }
70
+ }
71
+ async function checkedOutBranches(git, repoPath) {
72
+ const output = await git.run(repoPath, ["worktree", "list", "--porcelain", "-z"]);
73
+ const branches = new Set();
74
+ for (const field of output.split("\0")) {
75
+ if (field.startsWith("branch refs/heads/"))
76
+ branches.add(field.slice("branch refs/heads/".length).trim());
77
+ }
78
+ return branches;
79
+ }
80
+ async function existingRef(git, repoPath, ref) {
81
+ try {
82
+ await git.run(repoPath, ["rev-parse", "--verify", "--quiet", `${ref}^{commit}`]);
83
+ return ref;
84
+ }
85
+ catch {
86
+ return null;
87
+ }
88
+ }
89
+ // A branch's changes are on the base when it is an ancestor of the base, or when merging it into the
90
+ // base would change nothing: the merge result's tree is the base's own tree. That covers squash
91
+ // merges, and merges followed by unrelated work on the base, without making commits: merge-tree
92
+ // writes only content-addressed trees, so repeated sweeps reuse the same objects. A conflict, an
93
+ // unreadable ref or a git without `merge-tree --write-tree` (before 2.38) keeps the branch.
94
+ async function changesAreOnBase(git, repoPath, branch, baseRef) {
95
+ try {
96
+ await git.run(repoPath, ["merge-base", "--is-ancestor", branch, baseRef]);
97
+ return true;
98
+ }
99
+ catch {
100
+ // Not an ancestor; it may have been squash-merged.
101
+ }
102
+ try {
103
+ const merged = (await git.run(repoPath, ["merge-tree", "--write-tree", "--no-messages", baseRef, branch]))
104
+ .split("\n")[0].trim();
105
+ const baseTree = (await git.run(repoPath, ["rev-parse", `${baseRef}^{tree}`])).trim();
106
+ return merged.length > 0 && merged === baseTree;
107
+ }
108
+ catch {
109
+ return false;
110
+ }
111
+ }