@loucompanion/forge-bridge 0.1.3-dev.fbe15023cdfe → 0.1.4-dev.03584818ede5

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 (275) hide show
  1. package/README.md +146 -5
  2. package/dist/bridge/bridge-chat-provider-command.d.ts +16 -0
  3. package/dist/bridge/bridge-chat-provider-command.js +137 -0
  4. package/dist/bridge/bridge-chat.types.d.ts +121 -0
  5. package/dist/bridge/bridge-chat.types.js +416 -0
  6. package/dist/bridge/bridge.base.d.ts +13 -1
  7. package/dist/bridge/bridge.service.d.ts +155 -4
  8. package/dist/bridge/bridge.service.js +1805 -155
  9. package/dist/bridge/bridge.types.d.ts +68 -1
  10. package/dist/bridge/dispatch-result-outbox.d.ts +35 -0
  11. package/dist/bridge/dispatch-result-outbox.js +87 -0
  12. package/dist/bridge/dispatch-result-worker.d.ts +2 -0
  13. package/dist/bridge/dispatch-result-worker.js +122 -0
  14. package/dist/bridge/internals.d.ts +2 -0
  15. package/dist/bridge/internals.js +1 -0
  16. package/dist/bridge/local-yield-flag.d.ts +6 -0
  17. package/dist/bridge/local-yield-flag.js +34 -0
  18. package/dist/bridge/readiness-result-outbox.d.ts +21 -0
  19. package/dist/bridge/readiness-result-outbox.js +54 -0
  20. package/dist/bridge/readiness-result-worker.d.ts +2 -0
  21. package/dist/bridge/readiness-result-worker.js +121 -0
  22. package/dist/bridge/runner-host-capabilities.d.ts +20 -0
  23. package/dist/bridge/runner-host-capabilities.js +110 -0
  24. package/dist/bridge/test-postgres-capability.d.ts +14 -0
  25. package/dist/bridge/test-postgres-capability.js +120 -0
  26. package/dist/cleanup/cleanup.service.d.ts +10 -0
  27. package/dist/cleanup/cleanup.service.js +128 -104
  28. package/dist/cleanup/cleanup.types.d.ts +4 -0
  29. package/dist/cleanup/forge-owned-paths.d.ts +9 -0
  30. package/dist/cleanup/forge-owned-paths.js +53 -0
  31. package/dist/cleanup/host-runtime-ledger.d.ts +5 -0
  32. package/dist/cleanup/host-runtime-ledger.js +109 -0
  33. package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
  34. package/dist/cleanup/managed-branch-sweep.js +111 -0
  35. package/dist/cli/cli.help.js +22 -4
  36. package/dist/cli/cli.service.d.ts +30 -6
  37. package/dist/cli/cli.service.js +216 -31
  38. package/dist/cli/local-config.d.ts +5 -0
  39. package/dist/cli/local-config.js +30 -4
  40. package/dist/runtime/aspnet-runtime-prebuild.d.ts +36 -0
  41. package/dist/runtime/aspnet-runtime-prebuild.js +429 -0
  42. package/dist/runtime/attempt-database-broker.d.ts +89 -0
  43. package/dist/runtime/attempt-database-broker.js +390 -0
  44. package/dist/runtime/attempt-node-runtime-launcher.d.ts +2 -1
  45. package/dist/runtime/attempt-node-runtime-launcher.js +57 -18
  46. package/dist/runtime/attempt-path-operation.d.ts +21 -0
  47. package/dist/runtime/attempt-path-operation.js +94 -0
  48. package/dist/runtime/attempt-private-directory.d.ts +6 -0
  49. package/dist/runtime/attempt-private-directory.js +54 -0
  50. package/dist/runtime/attempt-process-supervisor.d.ts +35 -0
  51. package/dist/runtime/attempt-process-supervisor.js +144 -23
  52. package/dist/runtime/canonical-source-file.d.ts +3 -0
  53. package/dist/runtime/canonical-source-file.js +54 -0
  54. package/dist/runtime/docker-engine-probe.d.ts +90 -0
  55. package/dist/runtime/docker-engine-probe.js +333 -0
  56. package/dist/runtime/generated-output-reset.d.ts +10 -0
  57. package/dist/runtime/generated-output-reset.js +62 -8
  58. package/dist/runtime/host-database-capability-boundary.d.ts +16 -0
  59. package/dist/runtime/host-database-capability-boundary.js +63 -0
  60. package/dist/runtime/host-diagnostics.d.ts +11 -0
  61. package/dist/runtime/host-diagnostics.js +192 -0
  62. package/dist/runtime/host-execution-root.d.ts +4 -0
  63. package/dist/runtime/host-execution-root.js +39 -0
  64. package/dist/runtime/host-facts.d.ts +36 -0
  65. package/dist/runtime/host-facts.js +95 -0
  66. package/dist/runtime/host-listener-inspector.d.ts +8 -1
  67. package/dist/runtime/host-listener-inspector.js +121 -60
  68. package/dist/runtime/host-load-admission.d.ts +67 -0
  69. package/dist/runtime/host-load-admission.js +99 -0
  70. package/dist/runtime/host-load-child-environment.d.ts +27 -0
  71. package/dist/runtime/host-load-child-environment.js +76 -0
  72. package/dist/runtime/host-load-forge-cgroups.d.ts +49 -0
  73. package/dist/runtime/host-load-forge-cgroups.js +140 -0
  74. package/dist/runtime/host-load-governor-config.d.ts +52 -0
  75. package/dist/runtime/host-load-governor-config.js +83 -0
  76. package/dist/runtime/host-load-governor.d.ts +184 -0
  77. package/dist/runtime/host-load-governor.js +632 -0
  78. package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
  79. package/dist/runtime/host-load-ledger-lock.js +185 -0
  80. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  81. package/dist/runtime/host-load-runtime-settings.js +78 -0
  82. package/dist/runtime/host-load-sampler.d.ts +149 -0
  83. package/dist/runtime/host-load-sampler.js +291 -0
  84. package/dist/runtime/host-load-step-class.d.ts +70 -0
  85. package/dist/runtime/host-load-step-class.js +161 -0
  86. package/dist/runtime/host-load-step-reaper.d.ts +27 -0
  87. package/dist/runtime/host-load-step-reaper.js +95 -0
  88. package/dist/runtime/host-load-step-run.d.ts +73 -0
  89. package/dist/runtime/host-load-step-run.js +102 -0
  90. package/dist/runtime/host-load-test-slot.d.ts +43 -0
  91. package/dist/runtime/host-load-test-slot.js +81 -0
  92. package/dist/runtime/host-load-token-ledger.d.ts +200 -0
  93. package/dist/runtime/host-load-token-ledger.js +453 -0
  94. package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
  95. package/dist/runtime/host-load-windows-cpu.js +85 -0
  96. package/dist/runtime/host-pressure-stall.d.ts +61 -0
  97. package/dist/runtime/host-pressure-stall.js +168 -0
  98. package/dist/runtime/host-runtime-contract.d.ts +16 -1
  99. package/dist/runtime/host-runtime-contract.js +174 -56
  100. package/dist/runtime/host-runtime-lease.d.ts +163 -9
  101. package/dist/runtime/host-runtime-lease.js +1464 -121
  102. package/dist/runtime/host-runtime-promotion.d.ts +35 -3
  103. package/dist/runtime/host-runtime-promotion.js +107 -12
  104. package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
  105. package/dist/runtime/host-runtime-requirements-check.js +29 -0
  106. package/dist/runtime/host-runtime-requirements.d.ts +36 -0
  107. package/dist/runtime/host-runtime-requirements.js +117 -0
  108. package/dist/runtime/managed-command-teardown.d.ts +62 -0
  109. package/dist/runtime/managed-command-teardown.js +607 -0
  110. package/dist/runtime/memory-capacity.d.ts +70 -0
  111. package/dist/runtime/memory-capacity.js +123 -0
  112. package/dist/runtime/native-test-postgres-fallback.d.ts +25 -0
  113. package/dist/runtime/native-test-postgres-fallback.js +91 -0
  114. package/dist/runtime/node-host-runtime-adapter.d.ts +3 -0
  115. package/dist/runtime/node-host-runtime-adapter.js +29 -11
  116. package/dist/runtime/pinned-directory-process.d.ts +9 -0
  117. package/dist/runtime/pinned-directory-process.js +61 -0
  118. package/dist/runtime/pinned-source-directory.d.ts +17 -0
  119. package/dist/runtime/pinned-source-directory.js +94 -0
  120. package/dist/runtime/playwright-browser-cache.d.ts +39 -0
  121. package/dist/runtime/playwright-browser-cache.js +227 -0
  122. package/dist/runtime/playwright-host-runtime-adapter.d.ts +19 -0
  123. package/dist/runtime/playwright-host-runtime-adapter.js +113 -59
  124. package/dist/runtime/prepared-runtime-identity.d.ts +6 -0
  125. package/dist/runtime/prepared-runtime-identity.js +218 -0
  126. package/dist/runtime/prepared-runtime-readiness.d.ts +30 -0
  127. package/dist/runtime/prepared-runtime-readiness.js +285 -0
  128. package/dist/runtime/runner-settings.d.ts +100 -0
  129. package/dist/runtime/runner-settings.js +214 -0
  130. package/dist/runtime/runtime-isolation-lease.js +4 -1
  131. package/dist/runtime/workspace-resource-estimator.d.ts +17 -0
  132. package/dist/runtime/workspace-resource-estimator.js +174 -0
  133. package/dist/sandbox/host-capacity-broker.d.ts +113 -0
  134. package/dist/sandbox/host-capacity-broker.js +334 -0
  135. package/dist/sandbox/preflight.d.ts +31 -1
  136. package/dist/sandbox/preflight.js +237 -51
  137. package/dist/sandbox/repository-lock.d.ts +2 -1
  138. package/dist/sandbox/repository-lock.js +19 -9
  139. package/dist/sandbox/runtime.d.ts +16 -2
  140. package/dist/sandbox/runtime.js +182 -109
  141. package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
  142. package/dist/sandbox/sandbox-cgroups.js +42 -0
  143. package/dist/sandbox/sandbox.types.d.ts +7 -0
  144. package/dist/sandbox/workspace.service.js +2 -0
  145. package/dist/session/architect-waits.d.ts +2 -0
  146. package/dist/session/architect-waits.js +138 -0
  147. package/dist/session/managed-attempt-tools.d.ts +44 -1
  148. package/dist/session/managed-attempt-tools.js +816 -46
  149. package/dist/session/managed-build-coordinator.d.ts +5 -0
  150. package/dist/session/managed-build-coordinator.js +109 -0
  151. package/dist/session/managed-build-receipt.d.ts +21 -0
  152. package/dist/session/managed-build-receipt.js +337 -0
  153. package/dist/session/managed-command-host-load.d.ts +47 -0
  154. package/dist/session/managed-command-host-load.js +83 -0
  155. package/dist/session/managed-verification-timeouts.d.ts +8 -0
  156. package/dist/session/managed-verification-timeouts.js +17 -0
  157. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  158. package/dist/session/mcp-argument-coercion.js +121 -0
  159. package/dist/session/phase-completion.artifacts.d.ts +24 -0
  160. package/dist/session/phase-completion.artifacts.js +319 -44
  161. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  162. package/dist/session/phase-completion.command-validation.js +77 -0
  163. package/dist/session/phase-completion.d.ts +15 -1
  164. package/dist/session/phase-completion.helpers.d.ts +5 -0
  165. package/dist/session/phase-completion.helpers.js +43 -19
  166. package/dist/session/phase-completion.js +18 -3
  167. package/dist/session/phase-completion.prompts.js +22 -18
  168. package/dist/session/phase-completion.runtime.d.ts +6 -2
  169. package/dist/session/phase-completion.runtime.js +191 -47
  170. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  171. package/dist/session/phase-completion.schema-parts.js +188 -0
  172. package/dist/session/phase-completion.schemas.d.ts +3 -3
  173. package/dist/session/phase-completion.schemas.js +250 -226
  174. package/dist/session/phase-completion.validation.d.ts +3 -3
  175. package/dist/session/phase-completion.validation.js +135 -89
  176. package/dist/session/pre-publication-host-load.d.ts +27 -0
  177. package/dist/session/pre-publication-host-load.js +111 -0
  178. package/dist/session/pre-publication-pass.d.ts +61 -0
  179. package/dist/session/pre-publication-pass.js +148 -0
  180. package/dist/session/pre-publication-process.d.ts +23 -0
  181. package/dist/session/pre-publication-process.js +109 -0
  182. package/dist/session/pre-publication-skipped-tests.d.ts +21 -0
  183. package/dist/session/pre-publication-skipped-tests.js +109 -0
  184. package/dist/session/pre-publication-step-execution.d.ts +11 -0
  185. package/dist/session/pre-publication-step-execution.js +49 -0
  186. package/dist/session/pre-publication-validation.d.ts +87 -0
  187. package/dist/session/pre-publication-validation.js +668 -0
  188. package/dist/session/provider-cli/bridge-cli.conformance-fixtures.d.ts +72 -0
  189. package/dist/session/provider-cli/bridge-cli.conformance-fixtures.js +462 -0
  190. package/dist/session/provider-cli/ci-repair-readiness.d.ts +8 -0
  191. package/dist/session/provider-cli/ci-repair-readiness.js +23 -3
  192. package/dist/session/provider-cli/claude-background-work.d.ts +66 -0
  193. package/dist/session/provider-cli/claude-background-work.js +180 -0
  194. package/dist/session/provider-cli/pre-publication-repair.d.ts +40 -0
  195. package/dist/session/provider-cli/pre-publication-repair.js +243 -0
  196. package/dist/session/provider-cli/provider-cli.artifacts.d.ts +6 -3
  197. package/dist/session/provider-cli/provider-cli.artifacts.js +62 -22
  198. package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
  199. package/dist/session/provider-cli/provider-cli.child-environment.js +73 -0
  200. package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
  201. package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
  202. package/dist/session/provider-cli/provider-cli.deterministic.js +34 -2
  203. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
  204. package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
  205. package/dist/session/provider-cli/provider-cli.process.d.ts +92 -14
  206. package/dist/session/provider-cli/provider-cli.process.js +583 -210
  207. package/dist/session/provider-cli/provider-cli.prompts.d.ts +12 -0
  208. package/dist/session/provider-cli/provider-cli.prompts.js +200 -25
  209. package/dist/session/provider-cli/provider-cli.repair-epoch.d.ts +6 -0
  210. package/dist/session/provider-cli/provider-cli.repair-epoch.js +11 -0
  211. package/dist/session/provider-cli/provider-cli.runtime.d.ts +14 -1
  212. package/dist/session/provider-cli/provider-cli.runtime.js +61 -3
  213. package/dist/session/provider-cli/provider-cli.service.d.ts +33 -5
  214. package/dist/session/provider-cli/provider-cli.service.js +819 -84
  215. package/dist/session/provider-cli/provider-cli.types.d.ts +32 -0
  216. package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
  217. package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
  218. package/dist/session/provider-cli/provider-in-flight-work.d.ts +10 -0
  219. package/dist/session/provider-cli/provider-in-flight-work.js +92 -0
  220. package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
  221. package/dist/session/provider-cli/provider-output-pipes.js +67 -0
  222. package/dist/session/provider-cli/provider-output-state.d.ts +18 -0
  223. package/dist/session/provider-cli/provider-output-state.js +376 -17
  224. package/dist/session/provider-cli/provider-usage.d.ts +9 -1
  225. package/dist/session/provider-cli/provider-usage.js +28 -5
  226. package/dist/session/publishable-worktree-changes.d.ts +54 -0
  227. package/dist/session/publishable-worktree-changes.js +193 -0
  228. package/dist/session/sandbox-host-capacity-gate.d.ts +30 -0
  229. package/dist/session/sandbox-host-capacity-gate.js +238 -0
  230. package/dist/session/session-redaction.js +434 -9
  231. package/dist/session/session.base.d.ts +9 -1
  232. package/dist/session/session.service.d.ts +9 -2
  233. package/dist/session/session.service.js +264 -27
  234. package/dist/session/session.types.d.ts +150 -2
  235. package/dist/session/session.types.js +599 -7
  236. package/dist/session/unreferenced-exports.d.ts +12 -0
  237. package/dist/session/unreferenced-exports.js +59 -0
  238. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  239. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  240. package/dist/shared/format/format-bytes.d.ts +1 -0
  241. package/dist/shared/format/format-bytes.js +9 -0
  242. package/dist/shared/git/git.js +2 -1
  243. package/dist/shared/path/path.d.ts +1 -0
  244. package/dist/shared/path/path.js +18 -0
  245. package/dist/shared/process/dotnet-toolchain.d.ts +17 -0
  246. package/dist/shared/process/dotnet-toolchain.js +307 -0
  247. package/dist/shared/process/host-process-recovery.js +3 -2
  248. package/dist/shared/process/host-process-supervisor.d.ts +3 -0
  249. package/dist/shared/process/host-process-supervisor.js +61 -12
  250. package/dist/shared/process/process-tree.d.ts +52 -0
  251. package/dist/shared/process/process-tree.js +144 -0
  252. package/dist/shared/process/process.d.ts +69 -0
  253. package/dist/shared/process/process.js +223 -16
  254. package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
  255. package/dist/shared/process/windows-app-execution-alias.js +45 -0
  256. package/dist/shared/process/windows-launch.d.ts +18 -0
  257. package/dist/shared/process/windows-launch.js +68 -0
  258. package/dist/shared/provider-capabilities.d.ts +3 -0
  259. package/dist/shared/provider-capabilities.js +84 -0
  260. package/dist/shared/redaction/redaction.d.ts +1 -0
  261. package/dist/shared/redaction/redaction.js +39 -3
  262. package/dist/shared/time/monotonic.d.ts +1 -0
  263. package/dist/shared/time/monotonic.js +8 -0
  264. package/dist/version.d.ts +1 -1
  265. package/dist/version.js +1 -1
  266. package/dist/worktree/dependency-warmer.d.ts +66 -9
  267. package/dist/worktree/dependency-warmer.js +609 -24
  268. package/dist/worktree/index.d.ts +1 -1
  269. package/dist/worktree/story-qa-reference-hydrator.d.ts +4 -0
  270. package/dist/worktree/story-qa-reference-hydrator.js +253 -0
  271. package/dist/worktree/worktree.service.d.ts +17 -1
  272. package/dist/worktree/worktree.service.js +293 -21
  273. package/dist/worktree/worktree.types.d.ts +14 -1
  274. package/package.json +8 -6
  275. package/runtime/windows-job-supervisor.ps1 +380 -14
@@ -0,0 +1,20 @@
1
+ import type { BridgeServiceConfig, BridgeToolchainCapabilities } from "./bridge.types.js";
2
+ import { type BridgeTestPostgresCapability } from "./test-postgres-capability.js";
3
+ export interface RunnerHostCapabilitySnapshot {
4
+ readonly toolchains: BridgeToolchainCapabilities;
5
+ readonly playwrightProjects: readonly string[];
6
+ readonly browserLaunch: boolean;
7
+ readonly providerConnectivity: Readonly<Record<string, boolean>>;
8
+ readonly testPostgres: BridgeTestPostgresCapability;
9
+ }
10
+ export interface RunnerHostCapabilityProbe {
11
+ detect(config: BridgeServiceConfig): Promise<RunnerHostCapabilitySnapshot>;
12
+ }
13
+ export declare class ProcessRunnerHostCapabilityProbe implements RunnerHostCapabilityProbe {
14
+ private readonly warn;
15
+ private readonly providerEnvironment;
16
+ constructor(warn?: (message: string) => void, providerEnvironment?: () => NodeJS.ProcessEnv);
17
+ detect(config: BridgeServiceConfig): Promise<RunnerHostCapabilitySnapshot>;
18
+ }
19
+ export declare function isUnavailablePlaywrightConfigError(error: unknown): boolean;
20
+ export declare function emptyRunnerHostCapabilitySnapshot(): RunnerHostCapabilitySnapshot;
@@ -0,0 +1,110 @@
1
+ import { execFile } from "node:child_process";
2
+ import fs from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { promisify } from "node:util";
5
+ import { probeTestPostgresCapability } from "./test-postgres-capability.js";
6
+ import { appExecutionAliasWarning } from "../shared/process/windows-app-execution-alias.js";
7
+ import { buildProviderChildEnvironment } from "../session/provider-cli/provider-cli.process.js";
8
+ const execFileAsync = promisify(execFile);
9
+ export class ProcessRunnerHostCapabilityProbe {
10
+ warn;
11
+ providerEnvironment;
12
+ constructor(warn = message => process.stderr.write(`[${new Date().toISOString()}] ${message}\n`), providerEnvironment = () => buildProviderChildEnvironment()) {
13
+ this.warn = warn;
14
+ this.providerEnvironment = providerEnvironment;
15
+ }
16
+ async detect(config) {
17
+ // Readiness, not a capability: the bridge still settles an attempt whose descendant escaped
18
+ // the Job Object (see OutputPipeRelease), but the host should not hand out aliases.
19
+ const aliasWarning = appExecutionAliasWarning(this.providerEnvironment());
20
+ if (aliasWarning)
21
+ this.warn(aliasWarning);
22
+ const [pnpm, dotnet, git, bash, pwsh, windowsPowerShell] = await Promise.all([
23
+ probe("pnpm", ["--version"]),
24
+ probe("dotnet", ["--version"]),
25
+ probe("git", ["--version"]),
26
+ probe("bash", ["--version"]),
27
+ probe("pwsh", ["-NoProfile", "-Command", "$PSVersionTable.PSVersion.ToString()"]),
28
+ process.platform === "win32"
29
+ ? probe("powershell.exe", ["-NoProfile", "-Command", "$PSVersionTable.PSVersion.ToString()"])
30
+ : Promise.resolve(unavailable("powershell.exe")),
31
+ ]);
32
+ const playwrightProjects = await detectPlaywrightProjects(config.repoMappings);
33
+ const testPostgres = await probeTestPostgresCapability();
34
+ const browserLaunch = playwrightProjects.length > 0
35
+ || config.repoMappings.some(mapping => Boolean(mapping.qaAppLaunchTarget?.url
36
+ || mapping.qaAppLaunchTarget?.command
37
+ || mapping.qaAppLaunchTarget?.managed_runtime_port));
38
+ return {
39
+ toolchains: {
40
+ node: { available: true, executable: process.execPath, version: process.version },
41
+ pnpm,
42
+ dotnet,
43
+ git,
44
+ bash,
45
+ powershell: pwsh.available ? pwsh : windowsPowerShell,
46
+ },
47
+ playwrightProjects,
48
+ browserLaunch,
49
+ providerConnectivity: Object.fromEntries(Object.entries(config.providerStatuses)
50
+ .map(([provider, status]) => [provider, status.signedIn === true])),
51
+ testPostgres,
52
+ };
53
+ }
54
+ }
55
+ async function probe(executable, args) {
56
+ try {
57
+ const result = await execFileAsync(executable, [...args], { encoding: "utf8", timeout: 5_000 });
58
+ const version = `${result.stdout || result.stderr}`.trim().split(/\r?\n/u)[0] ?? "";
59
+ return { available: true, executable, version };
60
+ }
61
+ catch {
62
+ return unavailable(executable);
63
+ }
64
+ }
65
+ function unavailable(executable) {
66
+ return { available: false, executable, version: null };
67
+ }
68
+ async function detectPlaywrightProjects(repoMappings) {
69
+ const projects = new Set();
70
+ for (const mapping of repoMappings) {
71
+ if (!mapping.localPath)
72
+ continue;
73
+ const candidates = [
74
+ "playwright.config.ts", "playwright.config.js", "playwright.config.mjs",
75
+ "tests/e2e/playwright.config.ts", "tests/e2e/playwright.config.js", "tests/e2e/playwright.config.mjs",
76
+ ];
77
+ for (const relative of candidates) {
78
+ try {
79
+ const source = await fs.readFile(path.join(mapping.localPath, relative), "utf8");
80
+ for (const match of source.matchAll(/\bname\s*:\s*["']([^"']+)["']/gu))
81
+ projects.add(match[1]);
82
+ }
83
+ catch (error) {
84
+ if (!isUnavailablePlaywrightConfigError(error))
85
+ throw error;
86
+ }
87
+ }
88
+ }
89
+ return [...projects].sort((left, right) => left.localeCompare(right));
90
+ }
91
+ export function isUnavailablePlaywrightConfigError(error) {
92
+ const code = error?.code;
93
+ return code === "ENOENT" || code === "EACCES" || code === "EPERM" || code === "ENOTDIR";
94
+ }
95
+ export function emptyRunnerHostCapabilitySnapshot() {
96
+ return {
97
+ toolchains: {
98
+ node: { available: true, executable: process.execPath, version: process.version },
99
+ pnpm: unavailable("pnpm"),
100
+ dotnet: unavailable("dotnet"),
101
+ git: unavailable("git"),
102
+ bash: unavailable("bash"),
103
+ powershell: unavailable(process.platform === "win32" ? "powershell.exe" : "pwsh"),
104
+ },
105
+ playwrightProjects: [],
106
+ browserLaunch: false,
107
+ providerConnectivity: {},
108
+ testPostgres: { available: false, superuser: null },
109
+ };
110
+ }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Whether this host offers a native test PostgreSQL and whether its role is a superuser
3
+ * (decision 0013 placement). Suites that need `session_replication_role`, `CREATE ROLE` or
4
+ * similar can only run on a superuser test database or on Docker-backed Testcontainers.
5
+ */
6
+ export interface BridgeTestPostgresCapability {
7
+ readonly available: boolean;
8
+ /** Null when the cluster is configured but the role could not be checked. */
9
+ readonly superuser: boolean | null;
10
+ }
11
+ export type PsqlRunner = (args: readonly string[], env: NodeJS.ProcessEnv) => Promise<string>;
12
+ export declare function probeTestPostgresCapability(environment?: NodeJS.ProcessEnv, runPsql?: PsqlRunner, readFallback?: () => string | null): Promise<BridgeTestPostgresCapability>;
13
+ /** Maps an Npgsql-style connection string or a postgres:// URI to libpq environment. */
14
+ export declare function psqlTarget(connection: string): Record<string, string> | null;
@@ -0,0 +1,120 @@
1
+ import { execFile } from "node:child_process";
2
+ import { promisify } from "node:util";
3
+ import { hostRuntimeTestPostgresAdminEnvironment } from "../runtime/host-runtime-contract.js";
4
+ import { readNativeTestPostgresFallback } from "../runtime/native-test-postgres-fallback.js";
5
+ const execFileAsync = promisify(execFile);
6
+ const superuserQuery = "select rolsuper from pg_roles where rolname = current_user";
7
+ export async function probeTestPostgresCapability(environment = process.env, runPsql = defaultPsql, readFallback = configuredFallbackConnection) {
8
+ // Same sources pre-publication validation uses: the environment, else the operator's
9
+ // native test cluster file.
10
+ const connection = environment[hostRuntimeTestPostgresAdminEnvironment]?.trim() || readFallback()?.trim();
11
+ if (!connection)
12
+ return { available: false, superuser: null };
13
+ const target = psqlTarget(connection);
14
+ if (!target)
15
+ return { available: true, superuser: null };
16
+ try {
17
+ // The secret travels only in the child's environment, never in argv or logs.
18
+ const output = await runPsql(["-X", "-A", "-t", "-w", "-c", superuserQuery], { ...process.env, ...target, PGCONNECT_TIMEOUT: "5" });
19
+ const value = output.trim().toLowerCase();
20
+ return { available: true, superuser: value === "t" ? true : value === "f" ? false : null };
21
+ }
22
+ catch {
23
+ return { available: true, superuser: null };
24
+ }
25
+ }
26
+ /** Maps an Npgsql-style connection string or a postgres:// URI to libpq environment. */
27
+ export function psqlTarget(connection) {
28
+ // libpq reads PGDATABASE as a database name only, so a URI is split into PG* variables
29
+ // rather than passed whole (and not as psql's argument, which would put the secret in argv).
30
+ if (/^postgres(?:ql)?:\/\//iu.test(connection))
31
+ return uriTarget(connection);
32
+ const keys = {
33
+ host: "PGHOST", server: "PGHOST", port: "PGPORT", database: "PGDATABASE",
34
+ username: "PGUSER", "user id": "PGUSER", userid: "PGUSER", user: "PGUSER", password: "PGPASSWORD",
35
+ };
36
+ const target = {};
37
+ for (const part of connection.split(";")) {
38
+ const separator = part.indexOf("=");
39
+ if (separator <= 0)
40
+ continue;
41
+ const name = keys[part.slice(0, separator).trim().toLowerCase()];
42
+ const value = part.slice(separator + 1).trim();
43
+ if (name && value)
44
+ target[name] = value;
45
+ }
46
+ return target.PGHOST || target.PGUSER ? target : null;
47
+ }
48
+ /** libpq URI query parameters that have a PG* environment equivalent. */
49
+ const uriParameterEnvironment = {
50
+ host: "PGHOST", hostaddr: "PGHOSTADDR", port: "PGPORT", dbname: "PGDATABASE", user: "PGUSER",
51
+ password: "PGPASSWORD", passfile: "PGPASSFILE", options: "PGOPTIONS", application_name: "PGAPPNAME",
52
+ sslmode: "PGSSLMODE", sslrootcert: "PGSSLROOTCERT", sslcert: "PGSSLCERT", sslkey: "PGSSLKEY",
53
+ sslcrl: "PGSSLCRL", gssencmode: "PGGSSENCMODE", target_session_attrs: "PGTARGETSESSIONATTRS",
54
+ };
55
+ /**
56
+ * Parses `postgres[ql]://[user[:password]@][host[:port][,...]][/dbname][?param=value&...]`
57
+ * (libpq's URI form, including comma-separated hosts, bracketed IPv6 and percent-encoding).
58
+ */
59
+ function uriTarget(connection) {
60
+ const match = /^postgres(?:ql)?:\/\/([^/?#]*)(?:\/([^?#]*))?(?:\?([^#]*))?/iu.exec(connection);
61
+ if (!match)
62
+ return null;
63
+ try {
64
+ const [, authority = "", path, query] = match;
65
+ const target = {};
66
+ const at = authority.lastIndexOf("@");
67
+ if (at >= 0) {
68
+ const userInfo = authority.slice(0, at);
69
+ const colon = userInfo.indexOf(":");
70
+ const user = decodeURIComponent(colon >= 0 ? userInfo.slice(0, colon) : userInfo);
71
+ if (user)
72
+ target.PGUSER = user;
73
+ if (colon >= 0)
74
+ target.PGPASSWORD = decodeURIComponent(userInfo.slice(colon + 1));
75
+ }
76
+ const hosts = [];
77
+ const ports = [];
78
+ for (const entry of authority.slice(at + 1).split(",")) {
79
+ const ipv6 = /^\[([^\]]*)\](?::(.*))?$/u.exec(entry);
80
+ const colon = entry.lastIndexOf(":");
81
+ const host = ipv6 ? ipv6[1] ?? "" : colon >= 0 ? entry.slice(0, colon) : entry;
82
+ const port = ipv6 ? ipv6[2] ?? "" : colon >= 0 ? entry.slice(colon + 1) : "";
83
+ hosts.push(decodeURIComponent(host));
84
+ ports.push(port);
85
+ }
86
+ if (hosts.some(Boolean))
87
+ target.PGHOST = hosts.join(",");
88
+ if (ports.some(Boolean))
89
+ target.PGPORT = ports.join(",");
90
+ const database = path ? decodeURIComponent(path) : "";
91
+ if (database)
92
+ target.PGDATABASE = database;
93
+ for (const parameter of (query ?? "").split("&")) {
94
+ const separator = parameter.indexOf("=");
95
+ if (separator <= 0)
96
+ continue;
97
+ const name = uriParameterEnvironment[decodeURIComponent(parameter.slice(0, separator))];
98
+ const value = decodeURIComponent(parameter.slice(separator + 1));
99
+ if (name && value)
100
+ target[name] = value;
101
+ }
102
+ return target;
103
+ }
104
+ catch {
105
+ // Malformed percent-encoding: the role cannot be checked.
106
+ return null;
107
+ }
108
+ }
109
+ function configuredFallbackConnection() {
110
+ try {
111
+ return readNativeTestPostgresFallback()?.connectionString ?? null;
112
+ }
113
+ catch {
114
+ return null;
115
+ }
116
+ }
117
+ async function defaultPsql(args, env) {
118
+ const result = await execFileAsync("psql", [...args], { encoding: "utf8", timeout: 10_000, env });
119
+ return result.stdout;
120
+ }
@@ -9,7 +9,17 @@ export declare class ManagedWorktreeCleanupService implements CleanupService {
9
9
  constructor(stateRoot?: string, git?: GitClient, coordinator?: WorktreeLifecycleCoordinator);
10
10
  run(request: CleanupRequest): Promise<CleanupResult>;
11
11
  private runLocked;
12
+ private sweepReadinessBranches;
13
+ /**
14
+ * The branch merged work lands on: origin/HEAD when it points at a remote-tracking ref that
15
+ * exists, otherwise the only one of origin/develop, origin/main and origin/master that exists.
16
+ * Null when that's ambiguous or none exist, so the merged sweep is skipped (and reported)
17
+ * rather than measured against the wrong base.
18
+ */
19
+ private remoteBaseBranch;
20
+ private remoteBranchExists;
12
21
  private listWorktrees;
22
+ private staleRuntimeReadinessPaths;
13
23
  private scanManagedCandidates;
14
24
  private readRuntimeLeases;
15
25
  private worktreeMetadataRoot;
@@ -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";
6
5
  import { GitClient } from "../shared/git/git.js";
7
- import { isSubPath, resolveExistingDirectoryPath } from "../shared/path/path.js";
8
- import { validRuntimeIsolationLease } from "../runtime/runtime-isolation-lease.js";
6
+ import { isSubPath, resolveExistingDirectoryPath, resolvePathIdentity } from "../shared/path/path.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";
11
+ const staleRuntimeReadinessAgeMs = 30 * 60 * 1000;
10
12
  export class ManagedWorktreeCleanupService {
11
13
  stateRoot;
12
14
  git;
@@ -17,33 +19,55 @@ export class ManagedWorktreeCleanupService {
17
19
  this.coordinator = coordinator;
18
20
  }
19
21
  async run(request) {
20
- const repoPath = await resolveExistingDirectoryPath(request.repoRoot);
21
- const worktreeRoot = resolveManagedWorktreeRootForRepo(repoPath, request.allowedRepoRoot);
22
+ const [repoPath, allowedRepoRoot] = await Promise.all([
23
+ resolveExistingDirectoryPath(request.repoRoot),
24
+ request.allowedRepoRoot
25
+ ? resolvePathIdentity(request.allowedRepoRoot)
26
+ : Promise.resolve(undefined),
27
+ ]);
28
+ const worktreeRoot = resolveManagedWorktreeRootForRepo(repoPath, allowedRepoRoot);
22
29
  return await this.coordinator.withLock(repoPath, async () => {
23
30
  return await this.runLocked(repoPath, worktreeRoot, request);
24
31
  });
25
32
  }
26
33
  async runLocked(repoPath, worktreeRoot, request) {
27
34
  if (request.mode === "merged") {
28
- if (request.force)
29
- await this.git.run(repoPath, ["worktree", "prune"]);
30
- 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
+ };
31
50
  }
32
51
  const safeRoot = await resolveSafeManagedRoot(worktreeRoot);
33
52
  if (!safeRoot) {
34
- if (request.force)
35
- await this.git.run(repoPath, ["worktree", "prune"]);
36
- 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 };
37
59
  }
38
60
  const [listedWorktrees, runtimeLeases] = await Promise.all([
39
61
  this.listWorktrees(repoPath),
40
62
  this.readRuntimeLeases(),
41
63
  ]);
42
- const metadataRoot = await this.worktreeMetadataRoot(repoPath);
43
- const activeWorktrees = activePaths(listedWorktrees);
44
- const activeRuntimePaths = runtimeLeases
64
+ const activeRuntimePaths = await Promise.all(runtimeLeases
45
65
  .filter(lease => lease.state !== "released")
46
- .map(lease => path.resolve(lease.worktreePath));
66
+ .map(lease => resolveRuntimeLeasePath(lease.worktreePath)));
67
+ const metadataRoot = await this.worktreeMetadataRoot(repoPath);
68
+ const staleReadinessPaths = await this.staleRuntimeReadinessPaths(safeRoot, listedWorktrees, activeRuntimePaths);
69
+ const activeWorktrees = activePaths(listedWorktrees)
70
+ .filter(activePath => !staleReadinessPaths.some(stalePath => samePath(stalePath, activePath)));
47
71
  if (request.mode === "all") {
48
72
  const protectedPaths = uniquePaths([
49
73
  ...activeWorktrees.filter(activePath => isSubPath(safeRoot, activePath)),
@@ -88,9 +112,14 @@ export class ManagedWorktreeCleanupService {
88
112
  this.listWorktrees(repoPath),
89
113
  this.readRuntimeLeases(),
90
114
  ]);
115
+ const currentRuntimePaths = await Promise.all(currentLeases
116
+ .filter(lease => lease.state !== "released")
117
+ .map(lease => resolveRuntimeLeasePath(lease.worktreePath)));
118
+ const currentStaleReadinessPaths = await this.staleRuntimeReadinessPaths(safeRoot, currentWorktrees, currentRuntimePaths);
91
119
  const currentlyProtected = [
92
- ...activePaths(currentWorktrees),
93
- ...currentLeases.filter(lease => lease.state !== "released").map(lease => path.resolve(lease.worktreePath)),
120
+ ...activePaths(currentWorktrees)
121
+ .filter(activePath => !currentStaleReadinessPaths.some(stalePath => samePath(stalePath, activePath))),
122
+ ...currentRuntimePaths,
94
123
  ];
95
124
  if (worktreePathState(candidate, currentlyProtected) !== "none") {
96
125
  continue;
@@ -104,6 +133,8 @@ export class ManagedWorktreeCleanupService {
104
133
  }
105
134
  }
106
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);
107
138
  return {
108
139
  worktreeRoot: safeRoot,
109
140
  removedWorktrees,
@@ -112,12 +143,61 @@ export class ManagedWorktreeCleanupService {
112
143
  skippedUnownedDirectories: scan.skippedUnownedDirectories,
113
144
  removedRoot: false,
114
145
  dryRun: false,
146
+ deletedBranches: sweep.deletedBranches.length,
115
147
  };
116
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
+ }
117
179
  async listWorktrees(repoPath) {
118
180
  const output = await this.git.run(repoPath, ["worktree", "list", "--porcelain", "-z"]);
119
181
  return parseWorktreeListing(repoPath, output);
120
182
  }
183
+ async staleRuntimeReadinessPaths(worktreeRoot, worktrees, runtimePaths) {
184
+ const stale = [];
185
+ for (const worktree of worktrees) {
186
+ if (worktree.prunable || !isRuntimeReadinessWorktree(worktreeRoot, worktree))
187
+ continue;
188
+ if (worktreePathState(worktree.worktreePath, runtimePaths) !== "none")
189
+ continue;
190
+ const stat = await fs.stat(worktree.worktreePath).catch(error => {
191
+ if (isEnoent(error))
192
+ return null;
193
+ throw error;
194
+ });
195
+ if (stat && Date.now() - stat.mtimeMs >= staleRuntimeReadinessAgeMs) {
196
+ stale.push(worktree.worktreePath);
197
+ }
198
+ }
199
+ return stale;
200
+ }
121
201
  async scanManagedCandidates(metadataRoot, worktreeRoot, activeWorktrees, runtimePaths) {
122
202
  const candidates = [];
123
203
  let protectedWorktrees = 0;
@@ -168,12 +248,13 @@ export class ManagedWorktreeCleanupService {
168
248
  containsManagedDirectory = await visit(realEntry) || containsManagedDirectory;
169
249
  continue;
170
250
  }
171
- if (await forgeManagedCandidateIdentity(metadataRoot, realEntry)) {
251
+ const relativePath = path.relative(worktreeRoot, realEntry);
252
+ if (isForgeOwnedWorktreePath(relativePath) && await forgeManagedCandidateIdentity(metadataRoot, realEntry)) {
172
253
  candidates.push(realEntry);
173
254
  containsManagedDirectory = true;
174
255
  continue;
175
256
  }
176
- if (await visit(realEntry)) {
257
+ if (isForgeWorktreeContainer(relativePath) && await visit(realEntry)) {
177
258
  containsManagedDirectory = true;
178
259
  continue;
179
260
  }
@@ -186,28 +267,7 @@ export class ManagedWorktreeCleanupService {
186
267
  return { candidates, protectedWorktrees, skippedUnownedDirectories, rootRemovalSafe };
187
268
  }
188
269
  async readRuntimeLeases() {
189
- const ledgerRoot = path.join(this.stateRoot, "runtime-ledger", "host");
190
- const entries = await fs.readdir(ledgerRoot, { withFileTypes: true }).catch(error => {
191
- if (isEnoent(error))
192
- return [];
193
- throw error;
194
- });
195
- const leases = [];
196
- for (const entry of entries) {
197
- if (!entry.name.endsWith(".json"))
198
- continue;
199
- if (!entry.isFile() || entry.isSymbolicLink()) {
200
- throw new Error(`Refusing managed worktree cleanup because runtime ledger ${entry.name} is not a regular file.`);
201
- }
202
- const target = path.join(ledgerRoot, entry.name);
203
- const value = await readRuntimeLedger(target, entry.name);
204
- const runtimeLease = isRecord(value) ? value.runtimeLease : null;
205
- if (!validRuntimeIsolationLease(runtimeLease) || runtimeLease.mode !== "host") {
206
- throw new Error(`Refusing managed worktree cleanup because runtime ledger ${entry.name} has no trustworthy host lease.`);
207
- }
208
- leases.push(runtimeLease);
209
- }
210
- return leases;
270
+ return await readHostRuntimeLeases(this.stateRoot);
211
271
  }
212
272
  async worktreeMetadataRoot(repoPath) {
213
273
  const commonDirRaw = (await this.git.run(repoPath, ["rev-parse", "--git-common-dir"])).trim();
@@ -215,72 +275,27 @@ export class ManagedWorktreeCleanupService {
215
275
  return path.join(await fs.realpath(commonDirPath), "worktrees");
216
276
  }
217
277
  }
218
- async function readRuntimeLedger(target, entryName) {
219
- const pathStat = await fs.lstat(target).catch(error => {
278
+ async function resolveRuntimeLeasePath(leasePath) {
279
+ const resolved = path.resolve(leasePath);
280
+ const before = await fs.lstat(resolved).catch(error => {
220
281
  if (isEnoent(error))
221
282
  return null;
222
283
  throw error;
223
284
  });
224
- if (!pathStat) {
225
- throw new Error(`Refusing managed worktree cleanup because runtime ledger ${entryName} disappeared.`);
226
- }
227
- validateRuntimeLedgerStat(entryName, pathStat);
228
- let handle;
229
- try {
230
- handle = await fs.open(target, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW);
285
+ if (!before)
286
+ return await resolvePathIdentity(resolved);
287
+ if (before.isSymbolicLink() || !before.isDirectory()) {
288
+ throw new Error(`Refusing managed worktree cleanup because runtime lease path ${resolved} is redirected or is not a directory.`);
231
289
  }
232
- catch (error) {
233
- if (isEnoent(error) || errorCode(error) === "ELOOP") {
234
- throw new Error(`Refusing managed worktree cleanup because runtime ledger ${entryName} is not a regular file.`, { cause: error });
235
- }
236
- throw new Error(`Refusing managed worktree cleanup because runtime ledger ${entryName} could not be opened safely.`, { cause: error });
237
- }
238
- try {
239
- const openedStat = await handle.stat();
240
- const reopenedPathStat = await fs.lstat(target);
241
- validateRuntimeLedgerStat(entryName, openedStat);
242
- validateRuntimeLedgerStat(entryName, reopenedPathStat);
243
- validateSameRuntimeLedgerFile(entryName, pathStat, openedStat);
244
- validateSameRuntimeLedgerFile(entryName, openedStat, reopenedPathStat);
245
- const content = await handle.readFile("utf8");
246
- const afterStat = await handle.stat();
247
- const afterPathStat = await fs.lstat(target);
248
- validateRuntimeLedgerStat(entryName, afterStat);
249
- validateRuntimeLedgerStat(entryName, afterPathStat);
250
- validateSameRuntimeLedgerFile(entryName, openedStat, afterStat);
251
- validateSameRuntimeLedgerFile(entryName, afterStat, afterPathStat);
252
- if (openedStat.size !== afterStat.size || Buffer.byteLength(content, "utf8") !== afterStat.size) {
253
- throw new Error(`Refusing managed worktree cleanup because runtime ledger ${entryName} changed while being read.`);
254
- }
255
- try {
256
- return JSON.parse(content);
257
- }
258
- catch (error) {
259
- throw new Error(`Refusing managed worktree cleanup because runtime ledger ${entryName} is invalid.`, { cause: error });
260
- }
261
- }
262
- finally {
263
- await handle.close();
264
- }
265
- }
266
- function validateRuntimeLedgerStat(entryName, stat) {
267
- if (stat.isSymbolicLink() || !stat.isFile()) {
268
- throw new Error(`Refusing managed worktree cleanup because runtime ledger ${entryName} is not a regular file.`);
269
- }
270
- if (stat.size > 256 * 1024) {
271
- throw new Error(`Refusing managed worktree cleanup because runtime ledger ${entryName} is oversized.`);
290
+ const real = await fs.realpath(resolved);
291
+ const after = await fs.lstat(resolved);
292
+ if (after.isSymbolicLink()
293
+ || !after.isDirectory()
294
+ || (before.dev !== 0 && before.ino !== 0 && after.dev !== 0 && after.ino !== 0
295
+ && (before.dev !== after.dev || before.ino !== after.ino))) {
296
+ throw new Error(`Refusing managed worktree cleanup because runtime lease path ${resolved} changed while being resolved.`);
272
297
  }
273
- }
274
- function validateSameRuntimeLedgerFile(entryName, before, after) {
275
- if (before.dev !== 0 && before.ino !== 0 && after.dev !== 0 && after.ino !== 0
276
- && (before.dev !== after.dev || before.ino !== after.ino)) {
277
- throw new Error(`Refusing managed worktree cleanup because runtime ledger ${entryName} changed while being read.`);
278
- }
279
- }
280
- function errorCode(error) {
281
- return typeof error === "object" && error !== null && "code" in error
282
- ? String(error.code)
283
- : undefined;
298
+ return real;
284
299
  }
285
300
  function emptyResult(worktreeRoot, force) {
286
301
  return {
@@ -399,16 +414,28 @@ function parseWorktreeListing(repoPath, output) {
399
414
  current = {
400
415
  worktreePath: path.resolve(path.isAbsolute(rawPath) ? rawPath : path.join(repoPath, rawPath)),
401
416
  prunable: false,
417
+ branchName: null,
402
418
  };
403
419
  }
404
420
  else if (field.startsWith("prunable") && current) {
405
421
  current.prunable = true;
406
422
  }
423
+ else if (field.startsWith("branch ") && current) {
424
+ current.branchName = field.slice("branch ".length).trim();
425
+ }
407
426
  }
408
427
  if (current)
409
428
  worktrees.push(current);
410
429
  return worktrees;
411
430
  }
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}`;
438
+ }
412
439
  function activePaths(worktrees) {
413
440
  return worktrees.filter(entry => !entry.prunable).map(entry => entry.worktreePath);
414
441
  }
@@ -432,6 +459,3 @@ function samePath(left, right) {
432
459
  function isEnoent(error) {
433
460
  return error?.code === "ENOENT";
434
461
  }
435
- function isRecord(value) {
436
- return typeof value === "object" && value !== null && !Array.isArray(value);
437
- }
@@ -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 {};