@loucompanion/forge-bridge 0.1.4-dev.04a1e5b9e484 → 0.1.4-dev.138b79c6feb3

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 (148) hide show
  1. package/README.md +3 -3
  2. package/dist/bridge/bridge.service.d.ts +14 -1
  3. package/dist/bridge/bridge.service.js +80 -9
  4. package/dist/bridge/bridge.types.d.ts +11 -0
  5. package/dist/bridge/dispatch-result-outbox.d.ts +11 -1
  6. package/dist/bridge/dispatch-result-outbox.js +31 -6
  7. package/dist/bridge/runner-host-capabilities.d.ts +2 -0
  8. package/dist/bridge/runner-host-capabilities.js +4 -0
  9. package/dist/bridge/test-postgres-capability.d.ts +14 -0
  10. package/dist/bridge/test-postgres-capability.js +120 -0
  11. package/dist/cleanup/cleanup.service.d.ts +9 -0
  12. package/dist/cleanup/cleanup.service.js +72 -109
  13. package/dist/cleanup/cleanup.types.d.ts +4 -0
  14. package/dist/cleanup/forge-owned-paths.d.ts +9 -0
  15. package/dist/cleanup/forge-owned-paths.js +53 -0
  16. package/dist/cleanup/host-runtime-ledger.d.ts +5 -0
  17. package/dist/cleanup/host-runtime-ledger.js +109 -0
  18. package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
  19. package/dist/cleanup/managed-branch-sweep.js +111 -0
  20. package/dist/cli/cli.help.js +2 -2
  21. package/dist/cli/cli.service.js +10 -2
  22. package/dist/runtime/aspnet-runtime-prebuild.js +94 -6
  23. package/dist/runtime/attempt-process-supervisor.d.ts +19 -0
  24. package/dist/runtime/attempt-process-supervisor.js +50 -0
  25. package/dist/runtime/host-database-capability-boundary.d.ts +1 -1
  26. package/dist/runtime/host-database-capability-boundary.js +1 -0
  27. package/dist/runtime/host-facts.d.ts +35 -0
  28. package/dist/runtime/host-facts.js +95 -0
  29. package/dist/runtime/host-load-admission.d.ts +52 -0
  30. package/dist/runtime/host-load-admission.js +84 -0
  31. package/dist/runtime/host-load-child-environment.d.ts +22 -0
  32. package/dist/runtime/host-load-child-environment.js +65 -0
  33. package/dist/runtime/host-load-forge-cgroups.d.ts +49 -0
  34. package/dist/runtime/host-load-forge-cgroups.js +140 -0
  35. package/dist/runtime/host-load-governor-config.d.ts +34 -0
  36. package/dist/runtime/host-load-governor-config.js +46 -0
  37. package/dist/runtime/host-load-governor.d.ts +172 -0
  38. package/dist/runtime/host-load-governor.js +519 -0
  39. package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
  40. package/dist/runtime/host-load-ledger-lock.js +185 -0
  41. package/dist/runtime/host-load-sampler.d.ts +126 -0
  42. package/dist/runtime/host-load-sampler.js +232 -0
  43. package/dist/runtime/host-load-step-class.d.ts +68 -0
  44. package/dist/runtime/host-load-step-class.js +106 -0
  45. package/dist/runtime/host-load-step-reaper.d.ts +27 -0
  46. package/dist/runtime/host-load-step-reaper.js +95 -0
  47. package/dist/runtime/host-load-step-run.d.ts +73 -0
  48. package/dist/runtime/host-load-step-run.js +102 -0
  49. package/dist/runtime/host-load-token-ledger.d.ts +174 -0
  50. package/dist/runtime/host-load-token-ledger.js +421 -0
  51. package/dist/runtime/host-pressure-stall.d.ts +61 -0
  52. package/dist/runtime/host-pressure-stall.js +168 -0
  53. package/dist/runtime/host-runtime-contract.d.ts +4 -0
  54. package/dist/runtime/host-runtime-contract.js +6 -1
  55. package/dist/runtime/host-runtime-lease.d.ts +47 -3
  56. package/dist/runtime/host-runtime-lease.js +270 -14
  57. package/dist/runtime/host-runtime-promotion.js +12 -0
  58. package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
  59. package/dist/runtime/host-runtime-requirements-check.js +29 -0
  60. package/dist/runtime/host-runtime-requirements.d.ts +36 -0
  61. package/dist/runtime/host-runtime-requirements.js +117 -0
  62. package/dist/runtime/managed-command-teardown.d.ts +62 -0
  63. package/dist/runtime/managed-command-teardown.js +607 -0
  64. package/dist/runtime/playwright-browser-cache.d.ts +39 -0
  65. package/dist/runtime/playwright-browser-cache.js +227 -0
  66. package/dist/runtime/playwright-host-runtime-adapter.d.ts +18 -0
  67. package/dist/runtime/playwright-host-runtime-adapter.js +61 -55
  68. package/dist/sandbox/host-capacity-broker.d.ts +107 -0
  69. package/dist/sandbox/host-capacity-broker.js +315 -0
  70. package/dist/sandbox/runtime.d.ts +10 -1
  71. package/dist/sandbox/runtime.js +45 -2
  72. package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
  73. package/dist/sandbox/sandbox-cgroups.js +42 -0
  74. package/dist/session/managed-attempt-tools.d.ts +27 -0
  75. package/dist/session/managed-attempt-tools.js +356 -40
  76. package/dist/session/managed-build-coordinator.d.ts +1 -1
  77. package/dist/session/managed-build-coordinator.js +4 -1
  78. package/dist/session/managed-command-host-load.d.ts +45 -0
  79. package/dist/session/managed-command-host-load.js +82 -0
  80. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  81. package/dist/session/mcp-argument-coercion.js +121 -0
  82. package/dist/session/phase-completion.artifacts.d.ts +7 -0
  83. package/dist/session/phase-completion.artifacts.js +98 -25
  84. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  85. package/dist/session/phase-completion.command-validation.js +77 -0
  86. package/dist/session/phase-completion.d.ts +4 -0
  87. package/dist/session/phase-completion.helpers.js +13 -12
  88. package/dist/session/phase-completion.js +4 -0
  89. package/dist/session/phase-completion.prompts.js +6 -1
  90. package/dist/session/phase-completion.runtime.d.ts +5 -3
  91. package/dist/session/phase-completion.runtime.js +70 -35
  92. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  93. package/dist/session/phase-completion.schema-parts.js +188 -0
  94. package/dist/session/phase-completion.schemas.d.ts +3 -3
  95. package/dist/session/phase-completion.schemas.js +184 -209
  96. package/dist/session/phase-completion.validation.d.ts +2 -3
  97. package/dist/session/phase-completion.validation.js +46 -92
  98. package/dist/session/pre-publication-host-load.d.ts +27 -0
  99. package/dist/session/pre-publication-host-load.js +111 -0
  100. package/dist/session/pre-publication-process.d.ts +23 -0
  101. package/dist/session/pre-publication-process.js +109 -0
  102. package/dist/session/pre-publication-skipped-tests.d.ts +21 -0
  103. package/dist/session/pre-publication-skipped-tests.js +109 -0
  104. package/dist/session/pre-publication-step-execution.d.ts +11 -0
  105. package/dist/session/pre-publication-step-execution.js +49 -0
  106. package/dist/session/pre-publication-validation.d.ts +9 -9
  107. package/dist/session/pre-publication-validation.js +48 -112
  108. package/dist/session/provider-cli/provider-cli.artifacts.d.ts +2 -1
  109. package/dist/session/provider-cli/provider-cli.artifacts.js +21 -15
  110. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
  111. package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
  112. package/dist/session/provider-cli/provider-cli.process.d.ts +37 -1
  113. package/dist/session/provider-cli/provider-cli.process.js +299 -25
  114. package/dist/session/provider-cli/provider-cli.prompts.d.ts +5 -0
  115. package/dist/session/provider-cli/provider-cli.prompts.js +20 -2
  116. package/dist/session/provider-cli/provider-cli.service.d.ts +6 -0
  117. package/dist/session/provider-cli/provider-cli.service.js +244 -36
  118. package/dist/session/provider-cli/provider-cli.types.d.ts +30 -0
  119. package/dist/session/provider-cli/provider-in-flight-work.d.ts +6 -0
  120. package/dist/session/provider-cli/provider-in-flight-work.js +47 -0
  121. package/dist/session/provider-cli/provider-output-state.d.ts +6 -0
  122. package/dist/session/provider-cli/provider-output-state.js +9 -0
  123. package/dist/session/provider-cli/provider-usage.d.ts +2 -1
  124. package/dist/session/publishable-worktree-changes.d.ts +54 -0
  125. package/dist/session/publishable-worktree-changes.js +193 -0
  126. package/dist/session/sandbox-host-capacity-gate.d.ts +30 -0
  127. package/dist/session/sandbox-host-capacity-gate.js +229 -0
  128. package/dist/session/session.base.d.ts +3 -0
  129. package/dist/session/session.service.d.ts +5 -1
  130. package/dist/session/session.service.js +114 -5
  131. package/dist/session/session.types.d.ts +3 -0
  132. package/dist/session/session.types.js +15 -3
  133. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  134. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  135. package/dist/shared/process/host-process-supervisor.d.ts +1 -0
  136. package/dist/shared/process/host-process-supervisor.js +1 -1
  137. package/dist/shared/process/process-tree.d.ts +52 -0
  138. package/dist/shared/process/process-tree.js +144 -0
  139. package/dist/shared/process/process.d.ts +67 -0
  140. package/dist/shared/process/process.js +213 -11
  141. package/dist/version.d.ts +1 -1
  142. package/dist/version.js +1 -1
  143. package/dist/worktree/dependency-warmer.d.ts +25 -0
  144. package/dist/worktree/dependency-warmer.js +120 -10
  145. package/dist/worktree/worktree.service.d.ts +10 -1
  146. package/dist/worktree/worktree.service.js +42 -2
  147. package/dist/worktree/worktree.types.d.ts +7 -0
  148. package/package.json +1 -1
@@ -1,12 +1,13 @@
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";
6
5
  import { GitClient } from "../shared/git/git.js";
7
6
  import { isSubPath, resolveExistingDirectoryPath, resolvePathIdentity } from "../shared/path/path.js";
8
- import { validRuntimeIsolationLease } from "../runtime/runtime-isolation-lease.js";
9
7
  import { defaultWorktreeCoordinatorStateRoot, resolveManagedWorktreeRootForRepo, } from "../worktree/worktree-paths.js";
8
+ import { isForgeOwnedWorktreePath, isForgeWorktreeContainer, isRuntimeReadinessName } from "./forge-owned-paths.js";
9
+ import { liveLeaseBranches, readHostRuntimeLeases } from "./host-runtime-ledger.js";
10
+ import { sweepManagedBranches } from "./managed-branch-sweep.js";
10
11
  const staleRuntimeReadinessAgeMs = 30 * 60 * 1000;
11
12
  export class ManagedWorktreeCleanupService {
12
13
  stateRoot;
@@ -31,15 +32,30 @@ export class ManagedWorktreeCleanupService {
31
32
  }
32
33
  async runLocked(repoPath, worktreeRoot, request) {
33
34
  if (request.mode === "merged") {
34
- if (request.force)
35
- await this.git.run(repoPath, ["worktree", "prune"]);
36
- return emptyResult(worktreeRoot, request.force);
35
+ if (!request.force)
36
+ return emptyResult(worktreeRoot, request.force);
37
+ await this.git.run(repoPath, ["worktree", "prune"]);
38
+ // Forge branches whose work is already on the base, and leftover readiness branches.
39
+ const baseBranch = await this.remoteBaseBranch(repoPath);
40
+ const sweep = await sweepManagedBranches(this.git, repoPath, {
41
+ ...(baseBranch ? { baseBranch } : {}),
42
+ includeMergedWorkBranches: baseBranch !== null,
43
+ protectedBranches: liveLeaseBranches(await this.readRuntimeLeases()),
44
+ });
45
+ return {
46
+ ...emptyResult(worktreeRoot, request.force),
47
+ deletedBranches: sweep.deletedBranches.length,
48
+ ...(baseBranch ? {} : { mergedBaseUnresolved: true }),
49
+ };
37
50
  }
38
51
  const safeRoot = await resolveSafeManagedRoot(worktreeRoot);
39
52
  if (!safeRoot) {
40
- if (request.force)
41
- await this.git.run(repoPath, ["worktree", "prune"]);
42
- return emptyResult(worktreeRoot, request.force);
53
+ if (!request.force)
54
+ return emptyResult(worktreeRoot, request.force);
55
+ await this.git.run(repoPath, ["worktree", "prune"]);
56
+ // No managed root left, but readiness branches can outlive it.
57
+ const sweep = await this.sweepReadinessBranches(repoPath);
58
+ return { ...emptyResult(worktreeRoot, request.force), deletedBranches: sweep.deletedBranches.length };
43
59
  }
44
60
  const [listedWorktrees, runtimeLeases] = await Promise.all([
45
61
  this.listWorktrees(repoPath),
@@ -49,7 +65,7 @@ export class ManagedWorktreeCleanupService {
49
65
  .filter(lease => lease.state !== "released")
50
66
  .map(lease => resolveRuntimeLeasePath(lease.worktreePath)));
51
67
  const metadataRoot = await this.worktreeMetadataRoot(repoPath);
52
- const staleReadinessPaths = await this.staleRuntimeReadinessPaths(listedWorktrees, activeRuntimePaths);
68
+ const staleReadinessPaths = await this.staleRuntimeReadinessPaths(safeRoot, listedWorktrees, activeRuntimePaths);
53
69
  const activeWorktrees = activePaths(listedWorktrees)
54
70
  .filter(activePath => !staleReadinessPaths.some(stalePath => samePath(stalePath, activePath)));
55
71
  if (request.mode === "all") {
@@ -99,7 +115,7 @@ export class ManagedWorktreeCleanupService {
99
115
  const currentRuntimePaths = await Promise.all(currentLeases
100
116
  .filter(lease => lease.state !== "released")
101
117
  .map(lease => resolveRuntimeLeasePath(lease.worktreePath)));
102
- const currentStaleReadinessPaths = await this.staleRuntimeReadinessPaths(currentWorktrees, currentRuntimePaths);
118
+ const currentStaleReadinessPaths = await this.staleRuntimeReadinessPaths(safeRoot, currentWorktrees, currentRuntimePaths);
103
119
  const currentlyProtected = [
104
120
  ...activePaths(currentWorktrees)
105
121
  .filter(activePath => !currentStaleReadinessPaths.some(stalePath => samePath(stalePath, activePath))),
@@ -117,6 +133,8 @@ export class ManagedWorktreeCleanupService {
117
133
  }
118
134
  }
119
135
  await this.git.run(repoPath, ["worktree", "prune"]);
136
+ // A readiness branch goes with its worktree; this also clears ones whose worktree is long gone.
137
+ const sweep = await this.sweepReadinessBranches(repoPath);
120
138
  return {
121
139
  worktreeRoot: safeRoot,
122
140
  removedWorktrees,
@@ -125,16 +143,47 @@ export class ManagedWorktreeCleanupService {
125
143
  skippedUnownedDirectories: scan.skippedUnownedDirectories,
126
144
  removedRoot: false,
127
145
  dryRun: false,
146
+ deletedBranches: sweep.deletedBranches.length,
128
147
  };
129
148
  }
149
+ async sweepReadinessBranches(repoPath) {
150
+ return await sweepManagedBranches(this.git, repoPath, {
151
+ includeMergedWorkBranches: false,
152
+ protectedBranches: liveLeaseBranches(await this.readRuntimeLeases()),
153
+ });
154
+ }
155
+ /**
156
+ * The branch merged work lands on: origin/HEAD when it points at a remote-tracking ref that
157
+ * exists, otherwise the only one of origin/develop, origin/main and origin/master that exists.
158
+ * Null when that's ambiguous or none exist, so the merged sweep is skipped (and reported)
159
+ * rather than measured against the wrong base.
160
+ */
161
+ async remoteBaseBranch(repoPath) {
162
+ const originHead = await this.git.run(repoPath, ["symbolic-ref", "--quiet", "--short", "refs/remotes/origin/HEAD"])
163
+ .catch(() => "");
164
+ const headBranch = originHead.trim().replace(/^origin\//, "");
165
+ // A stale origin/HEAD can name a branch whose remote-tracking ref has been pruned.
166
+ if (headBranch && await this.remoteBranchExists(repoPath, headBranch))
167
+ return headBranch;
168
+ const present = [];
169
+ for (const candidate of ["develop", "main", "master"]) {
170
+ if (await this.remoteBranchExists(repoPath, candidate))
171
+ present.push(candidate);
172
+ }
173
+ return present.length === 1 ? present[0] : null;
174
+ }
175
+ async remoteBranchExists(repoPath, branch) {
176
+ return await this.git.run(repoPath, ["rev-parse", "--verify", "--quiet", `refs/remotes/origin/${branch}^{commit}`])
177
+ .then(() => true, () => false);
178
+ }
130
179
  async listWorktrees(repoPath) {
131
180
  const output = await this.git.run(repoPath, ["worktree", "list", "--porcelain", "-z"]);
132
181
  return parseWorktreeListing(repoPath, output);
133
182
  }
134
- async staleRuntimeReadinessPaths(worktrees, runtimePaths) {
183
+ async staleRuntimeReadinessPaths(worktreeRoot, worktrees, runtimePaths) {
135
184
  const stale = [];
136
185
  for (const worktree of worktrees) {
137
- if (worktree.prunable || !isRuntimeReadinessWorktree(worktree))
186
+ if (worktree.prunable || !isRuntimeReadinessWorktree(worktreeRoot, worktree))
138
187
  continue;
139
188
  if (worktreePathState(worktree.worktreePath, runtimePaths) !== "none")
140
189
  continue;
@@ -199,12 +248,13 @@ export class ManagedWorktreeCleanupService {
199
248
  containsManagedDirectory = await visit(realEntry) || containsManagedDirectory;
200
249
  continue;
201
250
  }
202
- if (await forgeManagedCandidateIdentity(metadataRoot, realEntry)) {
251
+ const relativePath = path.relative(worktreeRoot, realEntry);
252
+ if (isForgeOwnedWorktreePath(relativePath) && await forgeManagedCandidateIdentity(metadataRoot, realEntry)) {
203
253
  candidates.push(realEntry);
204
254
  containsManagedDirectory = true;
205
255
  continue;
206
256
  }
207
- if (await visit(realEntry)) {
257
+ if (isForgeWorktreeContainer(relativePath) && await visit(realEntry)) {
208
258
  containsManagedDirectory = true;
209
259
  continue;
210
260
  }
@@ -217,28 +267,7 @@ export class ManagedWorktreeCleanupService {
217
267
  return { candidates, protectedWorktrees, skippedUnownedDirectories, rootRemovalSafe };
218
268
  }
219
269
  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;
270
+ return await readHostRuntimeLeases(this.stateRoot);
242
271
  }
243
272
  async worktreeMetadataRoot(repoPath) {
244
273
  const commonDirRaw = (await this.git.run(repoPath, ["rev-parse", "--git-common-dir"])).trim();
@@ -268,73 +297,6 @@ async function resolveRuntimeLeasePath(leasePath) {
268
297
  }
269
298
  return real;
270
299
  }
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
300
  function emptyResult(worktreeRoot, force) {
339
301
  return {
340
302
  worktreeRoot: path.resolve(worktreeRoot),
@@ -466,9 +428,13 @@ function parseWorktreeListing(repoPath, output) {
466
428
  worktrees.push(current);
467
429
  return worktrees;
468
430
  }
469
- function isRuntimeReadinessWorktree(worktree) {
470
- return worktree.branchName?.startsWith("refs/heads/runtime-readiness-") === true
471
- || path.basename(worktree.worktreePath).startsWith("runtime-readiness-");
431
+ // A registered worktree counts as a readiness probe only when Forge made it: its folder sits
432
+ // directly in the managed root under the probe's exact name, and it has the probe's exact branch.
433
+ function isRuntimeReadinessWorktree(worktreeRoot, worktree) {
434
+ const folderName = path.basename(worktree.worktreePath);
435
+ return samePath(path.dirname(worktree.worktreePath), worktreeRoot)
436
+ && isRuntimeReadinessName(folderName)
437
+ && worktree.branchName === `refs/heads/${folderName}`;
472
438
  }
473
439
  function activePaths(worktrees) {
474
440
  return worktrees.filter(entry => !entry.prunable).map(entry => entry.worktreePath);
@@ -493,6 +459,3 @@ function samePath(left, right) {
493
459
  function isEnoent(error) {
494
460
  return error?.code === "ENOENT";
495
461
  }
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
+ // The host runtime ledger (<state root>/runtime-ledger/host/*.json) records every runtime lease this
6
+ // bridge holds. Cleanup reads it to keep live leases' worktrees and branches; any ledger it can't
7
+ // trust stops the cleanup rather than guessing.
8
+ /** Reads every host runtime lease, or throws if any ledger file can't be trusted. */
9
+ export async function readHostRuntimeLeases(stateRoot) {
10
+ const ledgerRoot = path.join(stateRoot, "runtime-ledger", "host");
11
+ const entries = await fs.readdir(ledgerRoot, { withFileTypes: true }).catch(error => {
12
+ if (isEnoent(error))
13
+ return [];
14
+ throw error;
15
+ });
16
+ const leases = [];
17
+ for (const entry of entries) {
18
+ if (!entry.name.endsWith(".json"))
19
+ continue;
20
+ if (!entry.isFile() || entry.isSymbolicLink()) {
21
+ throw new Error(`Refusing managed worktree cleanup because runtime ledger ${entry.name} is not a regular file.`);
22
+ }
23
+ const target = path.join(ledgerRoot, entry.name);
24
+ const value = await readRuntimeLedger(target, entry.name);
25
+ const runtimeLease = isRecord(value) ? value.runtimeLease : null;
26
+ if (!validRuntimeIsolationLease(runtimeLease) || runtimeLease.mode !== "host") {
27
+ throw new Error(`Refusing managed worktree cleanup because runtime ledger ${entry.name} has no trustworthy host lease.`);
28
+ }
29
+ leases.push(runtimeLease);
30
+ }
31
+ return leases;
32
+ }
33
+ async function readRuntimeLedger(target, entryName) {
34
+ const pathStat = await fs.lstat(target).catch(error => {
35
+ if (isEnoent(error))
36
+ return null;
37
+ throw error;
38
+ });
39
+ if (!pathStat) {
40
+ throw new Error(`Refusing managed worktree cleanup because runtime ledger ${entryName} disappeared.`);
41
+ }
42
+ validateRuntimeLedgerStat(entryName, pathStat);
43
+ let handle;
44
+ try {
45
+ handle = await fs.open(target, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW);
46
+ }
47
+ catch (error) {
48
+ if (isEnoent(error) || errorCode(error) === "ELOOP") {
49
+ throw new Error(`Refusing managed worktree cleanup because runtime ledger ${entryName} is not a regular file.`, { cause: error });
50
+ }
51
+ throw new Error(`Refusing managed worktree cleanup because runtime ledger ${entryName} could not be opened safely.`, { cause: error });
52
+ }
53
+ try {
54
+ const openedStat = await handle.stat();
55
+ const reopenedPathStat = await fs.lstat(target);
56
+ validateRuntimeLedgerStat(entryName, openedStat);
57
+ validateRuntimeLedgerStat(entryName, reopenedPathStat);
58
+ validateSameRuntimeLedgerFile(entryName, pathStat, openedStat);
59
+ validateSameRuntimeLedgerFile(entryName, openedStat, reopenedPathStat);
60
+ const content = await handle.readFile("utf8");
61
+ const afterStat = await handle.stat();
62
+ const afterPathStat = await fs.lstat(target);
63
+ validateRuntimeLedgerStat(entryName, afterStat);
64
+ validateRuntimeLedgerStat(entryName, afterPathStat);
65
+ validateSameRuntimeLedgerFile(entryName, openedStat, afterStat);
66
+ validateSameRuntimeLedgerFile(entryName, afterStat, afterPathStat);
67
+ if (openedStat.size !== afterStat.size || Buffer.byteLength(content, "utf8") !== afterStat.size) {
68
+ throw new Error(`Refusing managed worktree cleanup because runtime ledger ${entryName} changed while being read.`);
69
+ }
70
+ try {
71
+ return JSON.parse(content);
72
+ }
73
+ catch (error) {
74
+ throw new Error(`Refusing managed worktree cleanup because runtime ledger ${entryName} is invalid.`, { cause: error });
75
+ }
76
+ }
77
+ finally {
78
+ await handle.close();
79
+ }
80
+ }
81
+ function validateRuntimeLedgerStat(entryName, stat) {
82
+ if (stat.isSymbolicLink() || !stat.isFile()) {
83
+ throw new Error(`Refusing managed worktree cleanup because runtime ledger ${entryName} is not a regular file.`);
84
+ }
85
+ if (stat.size > 256 * 1024) {
86
+ throw new Error(`Refusing managed worktree cleanup because runtime ledger ${entryName} is oversized.`);
87
+ }
88
+ }
89
+ function validateSameRuntimeLedgerFile(entryName, before, after) {
90
+ if (before.dev !== 0 && before.ino !== 0 && after.dev !== 0 && after.ino !== 0
91
+ && (before.dev !== after.dev || before.ino !== after.ino)) {
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
+ }
@@ -28,7 +28,7 @@ export function helpText() {
28
28
  "",
29
29
  "Examples:",
30
30
  " npm install -g @loucompanion/forge-bridge@next",
31
- " forge-bridge pair 1234-5678 --server https://srv1493013.tail66073d.ts.net:8443 --repo-root \"%USERPROFILE%\\ForgeRepos\"",
31
+ " forge-bridge pair 1234-5678 --server https://forge.example.ts.net:8443 --repo-root \"%USERPROFILE%\\ForgeRepos\"",
32
32
  " forge-bridge connect",
33
33
  " forge-bridge status --check-updates",
34
34
  " forge-bridge server set http://localhost:5208",
@@ -116,7 +116,7 @@ export function commandHelpText(command) {
116
116
  "",
117
117
  "Examples:",
118
118
  " forge-bridge server set http://localhost:5208",
119
- " forge-bridge server set https://srv1493013.tail66073d.ts.net:8443",
119
+ " forge-bridge server set https://forge.example.ts.net:8443",
120
120
  "",
121
121
  ].join("\n");
122
122
  case "add-repo":
@@ -30,7 +30,9 @@ export class ForgeBridgeCliService {
30
30
  pairRunner;
31
31
  cleanupFactory;
32
32
  dotNetToolchainConfigurator;
33
- constructor(sessions = new BridgeSessionService(), bridgeFactory = (config) => new ForgeBridgeService(config), pairRunner = claimBridgeRunner, cleanupFactory = stateRoot => new ManagedWorktreeCleanupService(stateRoot), dotNetToolchainConfigurator = configureDotNetToolchain) {
33
+ constructor(
34
+ // In a Docker sandbox the default chain's validator asks the host bridge for host load tokens (decision 0013).
35
+ sessions = new BridgeSessionService(), bridgeFactory = (config) => new ForgeBridgeService(config), pairRunner = claimBridgeRunner, cleanupFactory = stateRoot => new ManagedWorktreeCleanupService(stateRoot), dotNetToolchainConfigurator = configureDotNetToolchain) {
34
36
  this.sessions = sessions;
35
37
  this.bridgeFactory = bridgeFactory;
36
38
  this.pairRunner = pairRunner;
@@ -89,6 +91,8 @@ export class ForgeBridgeCliService {
89
91
  if (config.cleanupWorktrees && config.repoMappings.some(mapping => mapping.localPath?.trim())) {
90
92
  io.stdout.write("Cleaning stale managed worktrees before accepting dispatches.\n");
91
93
  await cleanupRepos(config, "stale", true, this.cleanupFactory(config.sandboxStateRoot), io);
94
+ // Forge branches on this device whose work has merged since the bridge last ran.
95
+ await cleanupRepos(config, "merged", true, this.cleanupFactory(config.sandboxStateRoot), io);
92
96
  }
93
97
  io.stdout.write(connectStartupText(config));
94
98
  await this.bridgeFactory(config).run(controller.signal);
@@ -1001,7 +1005,11 @@ async function cleanupRepos(config, mode, force, cleanup, io) {
1001
1005
  io.stdout.write(`Removed ${result.removedWorktrees} stale managed ${result.removedWorktrees === 1 ? "worktree" : "worktrees"} from ${result.worktreeRoot}\n`);
1002
1006
  }
1003
1007
  else {
1004
- io.stdout.write(`Pruned stale worktree metadata for ${repoPath}\n`);
1008
+ const deleted = result.deletedBranches ?? 0;
1009
+ io.stdout.write(`Pruned stale worktree metadata and deleted ${deleted} Forge ${deleted === 1 ? "branch" : "branches"} (merged work and leftover readiness probes) in ${repoPath}\n`);
1010
+ if (result.mergedBaseUnresolved) {
1011
+ io.stderr.write(`${repoPath}: merged work branches were kept because the base branch couldn't be determined: origin/HEAD is unset or names a branch that no longer exists, and origin has none or more than one of develop, main and master. Run \`git fetch origin && git remote set-head origin --auto\`.\n`);
1012
+ }
1005
1013
  }
1006
1014
  }
1007
1015
  catch (error) {