@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,66 @@
1
+ import path from "node:path";
2
+ import { preserveWorktreeWip } from "../worktree/wip-snapshot.js";
3
+ import { isRuntimeReadinessName } from "./forge-owned-paths.js";
4
+ import { isForgeManagedWorkBranch } from "./managed-branch-sweep.js";
5
+ // Cleanup removes stale Forge worktrees: folders whose Git registration is gone (or prunable) and
6
+ // that no lease owns. Such a folder can still hold a session's uncommitted work (the #558 loss:
7
+ // six staged review fixes in a story worktree that cleanup deleted). Before one is removed, its
8
+ // work is saved to the branch's WIP ref; when that fails, the folder is kept and the reason given.
9
+ const releaseSuffix = /\.forge-release-[0-9a-f-]{36}$/u;
10
+ /** Saves a stale candidate's uncommitted work. Never throws: a failure means "keep the folder". */
11
+ export async function saveStaleWorktreeWork(git, repoPath, worktreeRoot, candidate) {
12
+ const branchName = candidateBranch(worktreeRoot, candidate);
13
+ // A readiness probe never runs an agent: there is no work of anyone's in it.
14
+ if (isRuntimeReadinessName(branchName))
15
+ return { status: "exempt" };
16
+ try {
17
+ const result = await snapshotCandidate(git, repoPath, candidate, branchName);
18
+ return result.status === "clean" ? { status: "clean" } : { status: "saved", ref: result.ref };
19
+ }
20
+ catch (error) {
21
+ return { status: "failed", reason: error instanceof Error ? error.message : String(error) };
22
+ }
23
+ }
24
+ async function snapshotCandidate(git, repoPath, candidate, branchName) {
25
+ const restorable = isForgeManagedWorkBranch(branchName) && /^(?:story|task|bug)\//u.test(branchName);
26
+ // A checkout Git still recognizes (a prunable registration) keeps its own HEAD, index and merge state.
27
+ if (await isOwnGitCheckout(git, candidate)) {
28
+ return await preserveWorktreeWip({
29
+ worktreePath: candidate, branchName, reason: "pre_cleanup", autoRestore: restorable,
30
+ });
31
+ }
32
+ // Otherwise only the files are left; compare them with the branch the folder was created for:
33
+ // its local branch, else its branch on origin. Either way the snapshot is based on the branch's
34
+ // own commit, so a later pass can apply it (restore still requires that exact HEAD). Compared
35
+ // with the repository's HEAD instead, it is saved for inspection only.
36
+ const branchRef = await existingRef(git, repoPath, `refs/heads/${branchName}`)
37
+ ?? await existingRef(git, repoPath, `refs/remotes/origin/${branchName}`);
38
+ const baseRef = branchRef ?? await existingRef(git, repoPath, "HEAD");
39
+ if (!baseRef)
40
+ throw new Error(`no base commit to compare ${candidate} with.`);
41
+ return await preserveWorktreeWip({
42
+ worktreePath: candidate,
43
+ branchName,
44
+ reason: "pre_cleanup",
45
+ autoRestore: restorable && branchRef !== null,
46
+ orphan: { repoPath, baseRef },
47
+ });
48
+ }
49
+ /** The branch Forge created the folder for: its path under the managed root, without a release suffix. */
50
+ function candidateBranch(worktreeRoot, candidate) {
51
+ return path.relative(worktreeRoot, candidate).split(/[\\/]+/u).filter(Boolean).join("/").replace(releaseSuffix, "");
52
+ }
53
+ async function isOwnGitCheckout(git, candidate) {
54
+ const topLevel = await git.run(candidate, ["rev-parse", "--show-toplevel"]).catch(() => "");
55
+ if (!topLevel.trim())
56
+ return false;
57
+ const normalize = (value) => {
58
+ const resolved = path.resolve(value.trim());
59
+ return process.platform === "win32" ? resolved.toLowerCase() : resolved;
60
+ };
61
+ return normalize(topLevel) === normalize(candidate);
62
+ }
63
+ async function existingRef(git, repoPath, ref) {
64
+ const resolved = await git.run(repoPath, ["rev-parse", "-q", "--verify", `${ref}^{commit}`]).catch(() => "");
65
+ return resolved.trim() ? ref : null;
66
+ }
@@ -6,9 +6,28 @@ export declare class ManagedWorktreeCleanupService implements CleanupService {
6
6
  private readonly stateRoot;
7
7
  private readonly git;
8
8
  private readonly coordinator;
9
- constructor(stateRoot?: string, git?: GitClient, coordinator?: WorktreeLifecycleCoordinator);
9
+ /** Where cleanup explains each worktree it kept because its work could not be saved. */
10
+ private readonly warn;
11
+ constructor(stateRoot?: string, git?: GitClient, coordinator?: WorktreeLifecycleCoordinator,
12
+ /** Where cleanup explains each worktree it kept because its work could not be saved. */
13
+ warn?: (message: string) => void);
10
14
  run(request: CleanupRequest): Promise<CleanupResult>;
11
15
  private runLocked;
16
+ /** All mode: removes the managed root itself once nothing in it is active, unowned or unsaved. */
17
+ private removeWholeRoot;
18
+ /** Re-reads registrations and leases: a candidate may have become active since the scan. */
19
+ private isProtectedNow;
20
+ /** Saves each candidate's uncommitted work to a WIP ref; returns how many could not be saved. */
21
+ private saveCandidatesWork;
22
+ private sweepReadinessBranches;
23
+ /**
24
+ * The branch merged work lands on: origin/HEAD when it points at a remote-tracking ref that
25
+ * exists, otherwise the only one of origin/develop, origin/main and origin/master that exists.
26
+ * Null when that's ambiguous or none exist, so the merged sweep is skipped (and reported)
27
+ * rather than measured against the wrong base.
28
+ */
29
+ private remoteBaseBranch;
30
+ private remoteBranchExists;
12
31
  private listWorktrees;
13
32
  private staleRuntimeReadinessPaths;
14
33
  private scanManagedCandidates;
@@ -1,21 +1,28 @@
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 { saveStaleWorktreeWork } from "./cleanup-wip.js";
10
+ import { isForgeOwnedWorktreePath, isForgeWorktreeContainer, isRuntimeReadinessName } from "./forge-owned-paths.js";
11
+ import { liveLeaseBranches, readHostRuntimeLeases } from "./host-runtime-ledger.js";
12
+ import { sweepManagedBranches } from "./managed-branch-sweep.js";
10
13
  const staleRuntimeReadinessAgeMs = 30 * 60 * 1000;
11
14
  export class ManagedWorktreeCleanupService {
12
15
  stateRoot;
13
16
  git;
14
17
  coordinator;
15
- constructor(stateRoot = defaultWorktreeCoordinatorStateRoot(), git = new GitClient(), coordinator = new RepositoryCoordinatorLock(stateRoot)) {
18
+ warn;
19
+ constructor(stateRoot = defaultWorktreeCoordinatorStateRoot(), git = new GitClient(), coordinator = new RepositoryCoordinatorLock(stateRoot),
20
+ /** Where cleanup explains each worktree it kept because its work could not be saved. */
21
+ warn = message => process.stderr.write(`${message}\n`)) {
16
22
  this.stateRoot = stateRoot;
17
23
  this.git = git;
18
24
  this.coordinator = coordinator;
25
+ this.warn = warn;
19
26
  }
20
27
  async run(request) {
21
28
  const [repoPath, allowedRepoRoot] = await Promise.all([
@@ -31,15 +38,30 @@ export class ManagedWorktreeCleanupService {
31
38
  }
32
39
  async runLocked(repoPath, worktreeRoot, request) {
33
40
  if (request.mode === "merged") {
34
- if (request.force)
35
- await this.git.run(repoPath, ["worktree", "prune"]);
36
- return emptyResult(worktreeRoot, request.force);
41
+ if (!request.force)
42
+ return emptyResult(worktreeRoot, request.force);
43
+ await this.git.run(repoPath, ["worktree", "prune"]);
44
+ // Forge branches whose work is already on the base, and leftover readiness branches.
45
+ const baseBranch = await this.remoteBaseBranch(repoPath);
46
+ const sweep = await sweepManagedBranches(this.git, repoPath, {
47
+ ...(baseBranch ? { baseBranch } : {}),
48
+ includeMergedWorkBranches: baseBranch !== null,
49
+ protectedBranches: liveLeaseBranches(await this.readRuntimeLeases()),
50
+ });
51
+ return {
52
+ ...emptyResult(worktreeRoot, request.force),
53
+ deletedBranches: sweep.deletedBranches.length,
54
+ ...(baseBranch ? {} : { mergedBaseUnresolved: true }),
55
+ };
37
56
  }
38
57
  const safeRoot = await resolveSafeManagedRoot(worktreeRoot);
39
58
  if (!safeRoot) {
40
- if (request.force)
41
- await this.git.run(repoPath, ["worktree", "prune"]);
42
- return emptyResult(worktreeRoot, request.force);
59
+ if (!request.force)
60
+ return emptyResult(worktreeRoot, request.force);
61
+ await this.git.run(repoPath, ["worktree", "prune"]);
62
+ // No managed root left, but readiness branches can outlive it.
63
+ const sweep = await this.sweepReadinessBranches(repoPath);
64
+ return { ...emptyResult(worktreeRoot, request.force), deletedBranches: sweep.deletedBranches.length };
43
65
  }
44
66
  const [listedWorktrees, runtimeLeases] = await Promise.all([
45
67
  this.listWorktrees(repoPath),
@@ -49,34 +71,11 @@ export class ManagedWorktreeCleanupService {
49
71
  .filter(lease => lease.state !== "released")
50
72
  .map(lease => resolveRuntimeLeasePath(lease.worktreePath)));
51
73
  const metadataRoot = await this.worktreeMetadataRoot(repoPath);
52
- const staleReadinessPaths = await this.staleRuntimeReadinessPaths(listedWorktrees, activeRuntimePaths);
74
+ const staleReadinessPaths = await this.staleRuntimeReadinessPaths(safeRoot, listedWorktrees, activeRuntimePaths);
53
75
  const activeWorktrees = activePaths(listedWorktrees)
54
76
  .filter(activePath => !staleReadinessPaths.some(stalePath => samePath(stalePath, activePath)));
55
77
  if (request.mode === "all") {
56
- const protectedPaths = uniquePaths([
57
- ...activeWorktrees.filter(activePath => isSubPath(safeRoot, activePath)),
58
- ...activeRuntimePaths.filter(activePath => isSubPath(safeRoot, activePath)),
59
- ]);
60
- if (protectedPaths.length > 0) {
61
- throw new Error(`Refusing to remove managed worktree root ${safeRoot}; ${protectedPaths.length} active worktree or runtime lease(s) remain.`);
62
- }
63
- const scan = await this.scanManagedCandidates(metadataRoot, safeRoot, activeWorktrees, activeRuntimePaths);
64
- if (request.force && !scan.rootRemovalSafe) {
65
- throw new Error(`Refusing to remove managed worktree root ${safeRoot}; unowned content remains (${scan.skippedUnownedDirectories} skipped director${scan.skippedUnownedDirectories === 1 ? "y" : "ies"}).`);
66
- }
67
- if (request.force) {
68
- await quarantineAndRemoveRoot(safeRoot);
69
- await this.git.run(repoPath, ["worktree", "prune"]);
70
- }
71
- return {
72
- worktreeRoot: safeRoot,
73
- removedWorktrees: request.force ? scan.candidates.length : 0,
74
- candidateWorktrees: scan.candidates.length,
75
- protectedWorktrees: scan.protectedWorktrees,
76
- skippedUnownedDirectories: scan.skippedUnownedDirectories,
77
- removedRoot: request.force,
78
- dryRun: !request.force,
79
- };
78
+ return await this.removeWholeRoot(repoPath, safeRoot, metadataRoot, activeWorktrees, activeRuntimePaths, request.force);
80
79
  }
81
80
  const scan = await this.scanManagedCandidates(metadataRoot, safeRoot, activeWorktrees, activeRuntimePaths);
82
81
  if (!request.force) {
@@ -91,32 +90,27 @@ export class ManagedWorktreeCleanupService {
91
90
  };
92
91
  }
93
92
  let removedWorktrees = 0;
93
+ let preservedWorktrees = 0;
94
94
  for (const candidate of scan.candidates) {
95
- const [currentWorktrees, currentLeases] = await Promise.all([
96
- this.listWorktrees(repoPath),
97
- this.readRuntimeLeases(),
98
- ]);
99
- const currentRuntimePaths = await Promise.all(currentLeases
100
- .filter(lease => lease.state !== "released")
101
- .map(lease => resolveRuntimeLeasePath(lease.worktreePath)));
102
- const currentStaleReadinessPaths = await this.staleRuntimeReadinessPaths(currentWorktrees, currentRuntimePaths);
103
- const currentlyProtected = [
104
- ...activePaths(currentWorktrees)
105
- .filter(activePath => !currentStaleReadinessPaths.some(stalePath => samePath(stalePath, activePath))),
106
- ...currentRuntimePaths,
107
- ];
108
- if (worktreePathState(candidate, currentlyProtected) !== "none") {
95
+ if (await this.isProtectedNow(repoPath, safeRoot, candidate)) {
109
96
  continue;
110
97
  }
111
98
  const candidateIdentity = await forgeManagedCandidateIdentity(metadataRoot, candidate);
112
99
  if (!candidateIdentity) {
113
100
  continue;
114
101
  }
102
+ // Never delete uncommitted work that could not be saved first.
103
+ if (await this.saveCandidatesWork(repoPath, safeRoot, [candidate]) > 0) {
104
+ preservedWorktrees += 1;
105
+ continue;
106
+ }
115
107
  if (await quarantineAndRemoveCandidate(safeRoot, candidate, candidateIdentity)) {
116
108
  removedWorktrees += 1;
117
109
  }
118
110
  }
119
111
  await this.git.run(repoPath, ["worktree", "prune"]);
112
+ // A readiness branch goes with its worktree; this also clears ones whose worktree is long gone.
113
+ const sweep = await this.sweepReadinessBranches(repoPath);
120
114
  return {
121
115
  worktreeRoot: safeRoot,
122
116
  removedWorktrees,
@@ -125,16 +119,112 @@ export class ManagedWorktreeCleanupService {
125
119
  skippedUnownedDirectories: scan.skippedUnownedDirectories,
126
120
  removedRoot: false,
127
121
  dryRun: false,
122
+ deletedBranches: sweep.deletedBranches.length,
123
+ preservedWorktrees,
124
+ };
125
+ }
126
+ /** All mode: removes the managed root itself once nothing in it is active, unowned or unsaved. */
127
+ async removeWholeRoot(repoPath, safeRoot, metadataRoot, activeWorktrees, activeRuntimePaths, force) {
128
+ const protectedPaths = uniquePaths([
129
+ ...activeWorktrees.filter(activePath => isSubPath(safeRoot, activePath)),
130
+ ...activeRuntimePaths.filter(activePath => isSubPath(safeRoot, activePath)),
131
+ ]);
132
+ if (protectedPaths.length > 0) {
133
+ throw new Error(`Refusing to remove managed worktree root ${safeRoot}; ${protectedPaths.length} active worktree or runtime lease(s) remain.`);
134
+ }
135
+ const scan = await this.scanManagedCandidates(metadataRoot, safeRoot, activeWorktrees, activeRuntimePaths);
136
+ if (force && !scan.rootRemovalSafe) {
137
+ throw new Error(`Refusing to remove managed worktree root ${safeRoot}; unowned content remains (${scan.skippedUnownedDirectories} skipped director${scan.skippedUnownedDirectories === 1 ? "y" : "ies"}).`);
138
+ }
139
+ if (force) {
140
+ // Every candidate's work is saved first; one that can't be saved keeps the whole root.
141
+ const kept = await this.saveCandidatesWork(repoPath, safeRoot, scan.candidates);
142
+ if (kept > 0) {
143
+ throw new Error(`Refusing to remove managed worktree root ${safeRoot}; ${kept} worktree(s) hold uncommitted work that could not be saved to a WIP ref.`);
144
+ }
145
+ await quarantineAndRemoveRoot(safeRoot);
146
+ await this.git.run(repoPath, ["worktree", "prune"]);
147
+ }
148
+ return {
149
+ worktreeRoot: safeRoot,
150
+ removedWorktrees: force ? scan.candidates.length : 0,
151
+ candidateWorktrees: scan.candidates.length,
152
+ protectedWorktrees: scan.protectedWorktrees,
153
+ skippedUnownedDirectories: scan.skippedUnownedDirectories,
154
+ removedRoot: force,
155
+ dryRun: !force,
128
156
  };
129
157
  }
158
+ /** Re-reads registrations and leases: a candidate may have become active since the scan. */
159
+ async isProtectedNow(repoPath, safeRoot, candidate) {
160
+ const [currentWorktrees, currentLeases] = await Promise.all([
161
+ this.listWorktrees(repoPath),
162
+ this.readRuntimeLeases(),
163
+ ]);
164
+ const currentRuntimePaths = await Promise.all(currentLeases
165
+ .filter(lease => lease.state !== "released")
166
+ .map(lease => resolveRuntimeLeasePath(lease.worktreePath)));
167
+ const currentStaleReadinessPaths = await this.staleRuntimeReadinessPaths(safeRoot, currentWorktrees, currentRuntimePaths);
168
+ const currentlyProtected = [
169
+ ...activePaths(currentWorktrees)
170
+ .filter(activePath => !currentStaleReadinessPaths.some(stalePath => samePath(stalePath, activePath))),
171
+ ...currentRuntimePaths,
172
+ ];
173
+ return worktreePathState(candidate, currentlyProtected) !== "none";
174
+ }
175
+ /** Saves each candidate's uncommitted work to a WIP ref; returns how many could not be saved. */
176
+ async saveCandidatesWork(repoPath, safeRoot, candidates) {
177
+ let kept = 0;
178
+ for (const candidate of candidates) {
179
+ const outcome = await saveStaleWorktreeWork(this.git, repoPath, safeRoot, candidate);
180
+ if (outcome.status === "saved") {
181
+ this.warn(`Saved uncommitted work in stale worktree ${candidate} to ${outcome.ref} before removing it.`);
182
+ }
183
+ else if (outcome.status === "failed") {
184
+ kept += 1;
185
+ this.warn(`Kept stale worktree ${candidate}: its uncommitted work could not be saved to a WIP ref (${outcome.reason}).`);
186
+ }
187
+ }
188
+ return kept;
189
+ }
190
+ async sweepReadinessBranches(repoPath) {
191
+ return await sweepManagedBranches(this.git, repoPath, {
192
+ includeMergedWorkBranches: false,
193
+ protectedBranches: liveLeaseBranches(await this.readRuntimeLeases()),
194
+ });
195
+ }
196
+ /**
197
+ * The branch merged work lands on: origin/HEAD when it points at a remote-tracking ref that
198
+ * exists, otherwise the only one of origin/develop, origin/main and origin/master that exists.
199
+ * Null when that's ambiguous or none exist, so the merged sweep is skipped (and reported)
200
+ * rather than measured against the wrong base.
201
+ */
202
+ async remoteBaseBranch(repoPath) {
203
+ const originHead = await this.git.run(repoPath, ["symbolic-ref", "--quiet", "--short", "refs/remotes/origin/HEAD"])
204
+ .catch(() => "");
205
+ const headBranch = originHead.trim().replace(/^origin\//, "");
206
+ // A stale origin/HEAD can name a branch whose remote-tracking ref has been pruned.
207
+ if (headBranch && await this.remoteBranchExists(repoPath, headBranch))
208
+ return headBranch;
209
+ const present = [];
210
+ for (const candidate of ["develop", "main", "master"]) {
211
+ if (await this.remoteBranchExists(repoPath, candidate))
212
+ present.push(candidate);
213
+ }
214
+ return present.length === 1 ? present[0] : null;
215
+ }
216
+ async remoteBranchExists(repoPath, branch) {
217
+ return await this.git.run(repoPath, ["rev-parse", "--verify", "--quiet", `refs/remotes/origin/${branch}^{commit}`])
218
+ .then(() => true, () => false);
219
+ }
130
220
  async listWorktrees(repoPath) {
131
221
  const output = await this.git.run(repoPath, ["worktree", "list", "--porcelain", "-z"]);
132
222
  return parseWorktreeListing(repoPath, output);
133
223
  }
134
- async staleRuntimeReadinessPaths(worktrees, runtimePaths) {
224
+ async staleRuntimeReadinessPaths(worktreeRoot, worktrees, runtimePaths) {
135
225
  const stale = [];
136
226
  for (const worktree of worktrees) {
137
- if (worktree.prunable || !isRuntimeReadinessWorktree(worktree))
227
+ if (worktree.prunable || !isRuntimeReadinessWorktree(worktreeRoot, worktree))
138
228
  continue;
139
229
  if (worktreePathState(worktree.worktreePath, runtimePaths) !== "none")
140
230
  continue;
@@ -199,12 +289,13 @@ export class ManagedWorktreeCleanupService {
199
289
  containsManagedDirectory = await visit(realEntry) || containsManagedDirectory;
200
290
  continue;
201
291
  }
202
- if (await forgeManagedCandidateIdentity(metadataRoot, realEntry)) {
292
+ const relativePath = path.relative(worktreeRoot, realEntry);
293
+ if (isForgeOwnedWorktreePath(relativePath) && await forgeManagedCandidateIdentity(metadataRoot, realEntry)) {
203
294
  candidates.push(realEntry);
204
295
  containsManagedDirectory = true;
205
296
  continue;
206
297
  }
207
- if (await visit(realEntry)) {
298
+ if (isForgeWorktreeContainer(relativePath) && await visit(realEntry)) {
208
299
  containsManagedDirectory = true;
209
300
  continue;
210
301
  }
@@ -217,28 +308,7 @@ export class ManagedWorktreeCleanupService {
217
308
  return { candidates, protectedWorktrees, skippedUnownedDirectories, rootRemovalSafe };
218
309
  }
219
310
  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;
311
+ return await readHostRuntimeLeases(this.stateRoot);
242
312
  }
243
313
  async worktreeMetadataRoot(repoPath) {
244
314
  const commonDirRaw = (await this.git.run(repoPath, ["rev-parse", "--git-common-dir"])).trim();
@@ -248,7 +318,7 @@ export class ManagedWorktreeCleanupService {
248
318
  }
249
319
  async function resolveRuntimeLeasePath(leasePath) {
250
320
  const resolved = path.resolve(leasePath);
251
- const before = await fs.lstat(resolved).catch(error => {
321
+ const before = await fs.lstat(resolved, { bigint: true }).catch(error => {
252
322
  if (isEnoent(error))
253
323
  return null;
254
324
  throw error;
@@ -259,82 +329,12 @@ async function resolveRuntimeLeasePath(leasePath) {
259
329
  throw new Error(`Refusing managed worktree cleanup because runtime lease path ${resolved} is redirected or is not a directory.`);
260
330
  }
261
331
  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))) {
332
+ const after = await fs.lstat(resolved, { bigint: true });
333
+ if (after.isSymbolicLink() || !after.isDirectory() || fileIdentityChanged(before, after)) {
267
334
  throw new Error(`Refusing managed worktree cleanup because runtime lease path ${resolved} changed while being resolved.`);
268
335
  }
269
336
  return real;
270
337
  }
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
338
  function emptyResult(worktreeRoot, force) {
339
339
  return {
340
340
  worktreeRoot: path.resolve(worktreeRoot),
@@ -466,9 +466,13 @@ function parseWorktreeListing(repoPath, output) {
466
466
  worktrees.push(current);
467
467
  return worktrees;
468
468
  }
469
- function isRuntimeReadinessWorktree(worktree) {
470
- return worktree.branchName?.startsWith("refs/heads/runtime-readiness-") === true
471
- || path.basename(worktree.worktreePath).startsWith("runtime-readiness-");
469
+ // A registered worktree counts as a readiness probe only when Forge made it: its folder sits
470
+ // directly in the managed root under the probe's exact name, and it has the probe's exact branch.
471
+ function isRuntimeReadinessWorktree(worktreeRoot, worktree) {
472
+ const folderName = path.basename(worktree.worktreePath);
473
+ return samePath(path.dirname(worktree.worktreePath), worktreeRoot)
474
+ && isRuntimeReadinessName(folderName)
475
+ && worktree.branchName === `refs/heads/${folderName}`;
472
476
  }
473
477
  function activePaths(worktrees) {
474
478
  return worktrees.filter(entry => !entry.prunable).map(entry => entry.worktreePath);
@@ -493,6 +497,3 @@ function samePath(left, right) {
493
497
  function isEnoent(error) {
494
498
  return error?.code === "ENOENT";
495
499
  }
496
- function isRecord(value) {
497
- return typeof value === "object" && value !== null && !Array.isArray(value);
498
- }
@@ -13,4 +13,10 @@ 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;
20
+ /** Stale mode only: stale worktrees kept because their uncommitted work could not be saved first. */
21
+ readonly preservedWorktrees?: number;
16
22
  }
@@ -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>;