@loucompanion/forge-bridge 0.1.3-dev.b6be5e7f9668 → 0.1.3-dev.ba293ccf876b

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 (196) hide show
  1. package/README.md +127 -0
  2. package/dist/bridge/bridge.base.d.ts +8 -1
  3. package/dist/bridge/bridge.service.d.ts +98 -3
  4. package/dist/bridge/bridge.service.js +1445 -48
  5. package/dist/bridge/bridge.types.d.ts +209 -1
  6. package/dist/bridge/readiness-result-outbox.d.ts +21 -0
  7. package/dist/bridge/readiness-result-outbox.js +54 -0
  8. package/dist/bridge/readiness-result-worker.d.ts +2 -0
  9. package/dist/bridge/readiness-result-worker.js +100 -0
  10. package/dist/bridge/runner-host-capabilities.d.ts +15 -0
  11. package/dist/bridge/runner-host-capabilities.js +93 -0
  12. package/dist/cleanup/cleanup.service.d.ts +14 -2
  13. package/dist/cleanup/cleanup.service.js +496 -3
  14. package/dist/cleanup/cleanup.types.d.ts +10 -0
  15. package/dist/cleanup/index.d.ts +1 -1
  16. package/dist/cleanup/index.js +1 -1
  17. package/dist/cleanup/internals.d.ts +2 -2
  18. package/dist/cleanup/internals.js +1 -1
  19. package/dist/cli/cli.help.d.ts +2 -0
  20. package/dist/cli/cli.help.js +217 -0
  21. package/dist/cli/cli.service.d.ts +45 -2
  22. package/dist/cli/cli.service.js +383 -209
  23. package/dist/cli/local-config.d.ts +7 -0
  24. package/dist/cli/local-config.js +51 -3
  25. package/dist/runtime/aspnet-runtime-prebuild.d.ts +36 -0
  26. package/dist/runtime/aspnet-runtime-prebuild.js +340 -0
  27. package/dist/runtime/attempt-node-runtime-launcher.d.ts +17 -0
  28. package/dist/runtime/attempt-node-runtime-launcher.js +105 -0
  29. package/dist/runtime/attempt-path-operation.d.ts +21 -0
  30. package/dist/runtime/attempt-path-operation.js +94 -0
  31. package/dist/runtime/attempt-private-directory.d.ts +6 -0
  32. package/dist/runtime/attempt-private-directory.js +54 -0
  33. package/dist/runtime/attempt-process-supervisor-registry.d.ts +20 -0
  34. package/dist/runtime/attempt-process-supervisor-registry.js +64 -0
  35. package/dist/runtime/attempt-process-supervisor.d.ts +97 -0
  36. package/dist/runtime/attempt-process-supervisor.js +386 -0
  37. package/dist/runtime/canonical-source-file.d.ts +3 -0
  38. package/dist/runtime/canonical-source-file.js +54 -0
  39. package/dist/runtime/docker-engine-probe.d.ts +83 -0
  40. package/dist/runtime/docker-engine-probe.js +300 -0
  41. package/dist/runtime/generated-output-reset.d.ts +10 -0
  42. package/dist/runtime/generated-output-reset.js +103 -0
  43. package/dist/runtime/host-diagnostics.d.ts +4 -0
  44. package/dist/runtime/host-diagnostics.js +95 -0
  45. package/dist/runtime/host-listener-inspector.d.ts +46 -0
  46. package/dist/runtime/host-listener-inspector.js +349 -0
  47. package/dist/runtime/host-port-broker.d.ts +76 -0
  48. package/dist/runtime/host-port-broker.js +333 -0
  49. package/dist/runtime/host-runtime-contract.d.ts +56 -0
  50. package/dist/runtime/host-runtime-contract.js +709 -0
  51. package/dist/runtime/host-runtime-lease.d.ts +201 -0
  52. package/dist/runtime/host-runtime-lease.js +2314 -0
  53. package/dist/runtime/host-runtime-promotion.d.ts +32 -0
  54. package/dist/runtime/host-runtime-promotion.js +206 -0
  55. package/dist/runtime/memory-capacity.d.ts +68 -0
  56. package/dist/runtime/memory-capacity.js +121 -0
  57. package/dist/runtime/node-host-runtime-adapter.d.ts +54 -0
  58. package/dist/runtime/node-host-runtime-adapter.js +284 -0
  59. package/dist/runtime/pinned-directory-process.d.ts +4 -0
  60. package/dist/runtime/pinned-directory-process.js +20 -0
  61. package/dist/runtime/pinned-source-directory.d.ts +9 -0
  62. package/dist/runtime/pinned-source-directory.js +56 -0
  63. package/dist/runtime/playwright-host-runtime-adapter.d.ts +21 -0
  64. package/dist/runtime/playwright-host-runtime-adapter.js +268 -0
  65. package/dist/runtime/prepared-runtime-identity.d.ts +3 -0
  66. package/dist/runtime/prepared-runtime-identity.js +191 -0
  67. package/dist/runtime/prepared-runtime-readiness.d.ts +22 -0
  68. package/dist/runtime/prepared-runtime-readiness.js +191 -0
  69. package/dist/runtime/runtime-isolation-lease.d.ts +67 -0
  70. package/dist/runtime/runtime-isolation-lease.js +158 -0
  71. package/dist/runtime/workspace-resource-estimator.d.ts +17 -0
  72. package/dist/runtime/workspace-resource-estimator.js +174 -0
  73. package/dist/sandbox/command-runner.d.ts +4 -0
  74. package/dist/sandbox/command-runner.js +47 -0
  75. package/dist/sandbox/contract.d.ts +5 -0
  76. package/dist/sandbox/contract.js +276 -0
  77. package/dist/sandbox/event-budget.d.ts +11 -0
  78. package/dist/sandbox/event-budget.js +27 -0
  79. package/dist/sandbox/image-policy.d.ts +35 -0
  80. package/dist/sandbox/image-policy.js +247 -0
  81. package/dist/sandbox/index.d.ts +5 -0
  82. package/dist/sandbox/index.js +5 -0
  83. package/dist/sandbox/lease-watchdog.d.ts +18 -0
  84. package/dist/sandbox/lease-watchdog.js +67 -0
  85. package/dist/sandbox/preflight.d.ts +84 -0
  86. package/dist/sandbox/preflight.js +521 -0
  87. package/dist/sandbox/process.d.ts +20 -0
  88. package/dist/sandbox/process.js +209 -0
  89. package/dist/sandbox/provider-auth/codex.d.ts +26 -0
  90. package/dist/sandbox/provider-auth/codex.js +212 -0
  91. package/dist/sandbox/repository-lock.d.ts +5 -0
  92. package/dist/sandbox/repository-lock.js +121 -0
  93. package/dist/sandbox/runtime.d.ts +297 -0
  94. package/dist/sandbox/runtime.js +2338 -0
  95. package/dist/sandbox/sandbox.types.d.ts +93 -0
  96. package/dist/sandbox/sandbox.types.js +1 -0
  97. package/dist/sandbox/smoke.d.ts +76 -0
  98. package/dist/sandbox/smoke.js +380 -0
  99. package/dist/sandbox/worker-supervisor.d.ts +13 -0
  100. package/dist/sandbox/worker-supervisor.js +36 -0
  101. package/dist/sandbox/worker.d.ts +1 -0
  102. package/dist/sandbox/worker.js +225 -0
  103. package/dist/sandbox/workspace.service.d.ts +13 -0
  104. package/dist/sandbox/workspace.service.js +72 -0
  105. package/dist/session/managed-attempt-tools.d.ts +21 -0
  106. package/dist/session/managed-attempt-tools.js +912 -0
  107. package/dist/session/managed-build-coordinator.d.ts +5 -0
  108. package/dist/session/managed-build-coordinator.js +105 -0
  109. package/dist/session/managed-build-receipt.d.ts +21 -0
  110. package/dist/session/managed-build-receipt.js +335 -0
  111. package/dist/session/phase-completion.artifacts.d.ts +27 -0
  112. package/dist/session/phase-completion.artifacts.js +829 -0
  113. package/dist/session/phase-completion.d.ts +44 -46
  114. package/dist/session/phase-completion.helpers.d.ts +117 -0
  115. package/dist/session/phase-completion.helpers.js +701 -0
  116. package/dist/session/phase-completion.js +42 -3488
  117. package/dist/session/phase-completion.prompts.d.ts +14 -0
  118. package/dist/session/phase-completion.prompts.js +236 -0
  119. package/dist/session/phase-completion.runtime.d.ts +48 -0
  120. package/dist/session/phase-completion.runtime.js +790 -0
  121. package/dist/session/phase-completion.schemas.d.ts +3 -0
  122. package/dist/session/phase-completion.schemas.js +820 -0
  123. package/dist/session/phase-completion.validation.d.ts +37 -0
  124. package/dist/session/phase-completion.validation.js +855 -0
  125. package/dist/session/pre-publication-validation.d.ts +47 -0
  126. package/dist/session/pre-publication-validation.js +249 -0
  127. package/dist/session/provider-cli/ci-repair-readiness.d.ts +16 -0
  128. package/dist/session/provider-cli/ci-repair-readiness.js +110 -0
  129. package/dist/session/provider-cli/provider-cli.artifacts.d.ts +94 -0
  130. package/dist/session/provider-cli/provider-cli.artifacts.js +812 -0
  131. package/dist/session/provider-cli/provider-cli.base.d.ts +1 -0
  132. package/dist/session/provider-cli/provider-cli.deterministic-payloads.d.ts +12 -0
  133. package/dist/session/provider-cli/provider-cli.deterministic-payloads.js +279 -0
  134. package/dist/session/provider-cli/provider-cli.deterministic.d.ts +14 -0
  135. package/dist/session/provider-cli/provider-cli.deterministic.js +377 -0
  136. package/dist/session/provider-cli/provider-cli.process.d.ts +57 -0
  137. package/dist/session/provider-cli/provider-cli.process.js +716 -0
  138. package/dist/session/provider-cli/provider-cli.prompts.d.ts +47 -0
  139. package/dist/session/provider-cli/provider-cli.prompts.js +611 -0
  140. package/dist/session/provider-cli/provider-cli.qa-sidecars.d.ts +11 -0
  141. package/dist/session/provider-cli/provider-cli.qa-sidecars.js +66 -0
  142. package/dist/session/provider-cli/provider-cli.repair-epoch.d.ts +6 -0
  143. package/dist/session/provider-cli/provider-cli.repair-epoch.js +11 -0
  144. package/dist/session/provider-cli/provider-cli.runtime.d.ts +9 -0
  145. package/dist/session/provider-cli/provider-cli.runtime.js +43 -0
  146. package/dist/session/provider-cli/provider-cli.service.d.ts +29 -53
  147. package/dist/session/provider-cli/provider-cli.service.js +640 -2581
  148. package/dist/session/provider-cli/provider-cli.types.d.ts +6 -0
  149. package/dist/session/provider-cli/provider-output-state.d.ts +22 -0
  150. package/dist/session/provider-cli/provider-output-state.js +520 -0
  151. package/dist/session/provider-cli/provider-usage.d.ts +7 -0
  152. package/dist/session/provider-cli/provider-usage.js +28 -5
  153. package/dist/session/session-redaction.d.ts +3 -0
  154. package/dist/session/session-redaction.js +38 -0
  155. package/dist/session/session.base.d.ts +6 -1
  156. package/dist/session/session.service.d.ts +8 -2
  157. package/dist/session/session.service.js +550 -58
  158. package/dist/session/session.types.d.ts +180 -1
  159. package/dist/session/session.types.js +323 -4
  160. package/dist/shared/format/format-bytes.d.ts +1 -0
  161. package/dist/shared/format/format-bytes.js +9 -0
  162. package/dist/shared/git/git.js +2 -1
  163. package/dist/shared/path/path.d.ts +1 -0
  164. package/dist/shared/path/path.js +21 -1
  165. package/dist/shared/process/dotnet-toolchain.d.ts +14 -0
  166. package/dist/shared/process/dotnet-toolchain.js +179 -0
  167. package/dist/shared/process/host-process-recovery.d.ts +12 -0
  168. package/dist/shared/process/host-process-recovery.js +78 -0
  169. package/dist/shared/process/host-process-supervisor.d.ts +59 -0
  170. package/dist/shared/process/host-process-supervisor.js +330 -0
  171. package/dist/shared/process/process.d.ts +2 -0
  172. package/dist/shared/process/process.js +11 -6
  173. package/dist/shared/process/windows-launch.d.ts +8 -0
  174. package/dist/shared/process/windows-launch.js +41 -0
  175. package/dist/shared/provider-capabilities.d.ts +1 -0
  176. package/dist/shared/provider-capabilities.js +3 -0
  177. package/dist/shared/redaction/redaction.js +16 -4
  178. package/dist/version.d.ts +1 -1
  179. package/dist/version.js +1 -1
  180. package/dist/worktree/artifact-injector.d.ts +3 -2
  181. package/dist/worktree/artifact-injector.js +82 -10
  182. package/dist/worktree/dependency-warmer.d.ts +39 -1
  183. package/dist/worktree/dependency-warmer.js +351 -8
  184. package/dist/worktree/index.d.ts +2 -1
  185. package/dist/worktree/index.js +1 -0
  186. package/dist/worktree/prior-phase-artifact-hydrator.d.ts +2 -0
  187. package/dist/worktree/prior-phase-artifact-hydrator.js +136 -0
  188. package/dist/worktree/worktree-paths.d.ts +4 -0
  189. package/dist/worktree/worktree-paths.js +30 -0
  190. package/dist/worktree/worktree.base.d.ts +3 -0
  191. package/dist/worktree/worktree.service.d.ts +16 -3
  192. package/dist/worktree/worktree.service.js +323 -54
  193. package/dist/worktree/worktree.types.d.ts +5 -1
  194. package/package.json +8 -4
  195. package/runtime/windows-job-supervisor.ps1 +444 -0
  196. package/runtime/windows-listener-owner.ps1 +33 -0
@@ -1,61 +1,99 @@
1
+ import { randomUUID } from "node:crypto";
1
2
  import fs from "node:fs/promises";
2
3
  import path from "node:path";
4
+ import { RepositoryCoordinatorLock } from "../sandbox/repository-lock.js";
3
5
  import { GitClient } from "../shared/git/git.js";
4
6
  import { ensureDirectory, isSubPath, resolveExistingDirectoryPath, safeSegment } from "../shared/path/path.js";
5
7
  import { filterArtifactsForLane, injectWorktreeArtifacts } from "./artifact-injector.js";
8
+ import { hydratePriorPhaseArtifacts } from "./prior-phase-artifact-hydrator.js";
6
9
  import { warmWorktreeDependencies } from "./dependency-warmer.js";
10
+ import { defaultWorktreeCoordinatorStateRoot, managedRepoRoot, resolveManagedWorktreeRoot, } from "./worktree-paths.js";
7
11
  export class GitWorktreeService {
8
12
  git;
9
- constructor(git = new GitClient()) {
13
+ coordinator;
14
+ constructor(git = new GitClient(), coordinator = new RepositoryCoordinatorLock(defaultWorktreeCoordinatorStateRoot())) {
10
15
  this.git = git;
16
+ this.coordinator = coordinator;
11
17
  }
12
18
  async prepare(request) {
13
19
  const allowedRoot = await ensureDirectory(request.allowedRepoRoot);
14
20
  const baseBranch = normalizeBranchName(request.baseBranch, "develop");
15
- const repoPath = await this.resolveRepoPath(request.repo, allowedRoot, baseBranch);
16
- await this.ensureGitIdentity(repoPath);
17
- await this.ensureBaseBranch(repoPath, baseBranch);
18
21
  const shortId = request.workItem.id.replace(/-/g, "").slice(0, 12);
19
22
  const kind = safeSegment(request.workItem.kind, "work-item");
20
23
  const fallbackWorktreeKey = `${kind}/${shortId}`;
21
24
  const worktreeKey = request.worktreeKey?.trim() || fallbackWorktreeKey;
22
25
  const worktreeSegments = worktreeKeySegments(worktreeKey, kind, shortId);
23
26
  const branchName = normalizeBranchName(worktreeSegments.join("/"), "work-item/unknown");
24
- const worktreeRoot = resolveWorktreeRoot(allowedRoot, repoPath);
25
- const worktreePath = path.join(worktreeRoot, ...worktreeSegments);
26
- const resolvedWorktreeParent = await ensureDirectory(path.dirname(worktreePath));
27
- if (!isSubPath(allowedRoot, resolvedWorktreeParent)) {
28
- throw new Error(`Worktree path must stay under ${allowedRoot}.`);
29
- }
30
- const exists = await directoryExists(worktreePath);
31
- let resolvedWorktreePath;
32
- if (!exists) {
33
- await this.git.run(repoPath, ["worktree", "add", "-B", branchName, worktreePath, baseBranch]);
34
- resolvedWorktreePath = await resolveExistingDirectoryPath(worktreePath);
35
- }
36
- else {
37
- resolvedWorktreePath = await resolveExistingDirectoryPath(worktreePath);
38
- if (!isSubPath(allowedRoot, resolvedWorktreePath)) {
27
+ const creationCoordinationPath = this.repoCreationCoordinationPath(request.repo, allowedRoot);
28
+ const repoPath = await this.coordinator.withLock(creationCoordinationPath, async () => {
29
+ return await this.resolveRepoPath(request.repo, allowedRoot, baseBranch);
30
+ });
31
+ const resolvedWorktreePath = await this.coordinator.withLock(repoPath, async () => {
32
+ await this.ensureGitIdentity(repoPath);
33
+ const baseStartPoint = await this.resolveBaseStartPoint(repoPath, baseBranch);
34
+ const worktreeRoot = resolveManagedWorktreeRoot(allowedRoot, repoPath);
35
+ const worktreePath = path.join(worktreeRoot, ...worktreeSegments);
36
+ const resolvedWorktreeParent = await ensureDirectory(path.dirname(worktreePath));
37
+ if (!isSubPath(allowedRoot, resolvedWorktreeParent)) {
38
+ throw new Error(`Worktree path must stay under ${allowedRoot}.`);
39
+ }
40
+ let selectedWorktreePath = worktreePath;
41
+ if (!(await directoryExists(worktreePath))) {
42
+ // A prior runner can disappear after Git registers its worktree but before
43
+ // normal cleanup completes. Release that missing-directory registration
44
+ // immediately so retrying the same lease remains idempotent.
45
+ await this.git.run(repoPath, ["worktree", "prune", "--expire", "now"]);
46
+ const registeredWorktreePath = await this.registeredManagedWorktreePath(repoPath, branchName, allowedRoot, worktreeSegments);
47
+ if (!registeredWorktreePath) {
48
+ await this.git.run(repoPath, ["worktree", "add", "-B", branchName, worktreePath, baseStartPoint]);
49
+ return await resolveExistingDirectoryPath(worktreePath);
50
+ }
51
+ // The selected checkout can change when a Bridge reconnects or a local
52
+ // runner takes over. Its managed root therefore changes even though the
53
+ // deterministic lease branch does not. Reattach to the registered,
54
+ // Forge-owned worktree instead of trying to check out that branch twice.
55
+ selectedWorktreePath = registeredWorktreePath;
56
+ }
57
+ const existingWorktreePath = await resolveExistingDirectoryPath(selectedWorktreePath);
58
+ if (!isSubPath(allowedRoot, existingWorktreePath)) {
39
59
  throw new Error(`Worktree path must stay under ${allowedRoot}.`);
40
60
  }
41
- const currentBranch = await this.currentBranch(resolvedWorktreePath);
61
+ if (!(await gitMetadataExists(existingWorktreePath, allowedRoot))) {
62
+ await this.restoreOrphanedWorktree({
63
+ repoPath,
64
+ worktreePath: existingWorktreePath,
65
+ branchName,
66
+ baseStartPoint,
67
+ allowedRoot,
68
+ });
69
+ }
70
+ const currentBranch = await this.currentBranch(existingWorktreePath);
42
71
  if (currentBranch !== branchName) {
43
- throw new Error(`Existing worktree ${resolvedWorktreePath} is on branch '${currentBranch}', expected '${branchName}'.`);
72
+ throw new Error(`Existing worktree ${existingWorktreePath} is on branch '${currentBranch}', expected '${branchName}'.`);
44
73
  }
45
- }
74
+ if (!request.preserveExistingState && shouldResetExistingWorktree(request)) {
75
+ await this.resetWorktreeToBase(existingWorktreePath, baseStartPoint);
76
+ }
77
+ return existingWorktreePath;
78
+ });
46
79
  await this.ensureGitIdentity(resolvedWorktreePath);
47
- await clearRunArtifactRoots(resolvedWorktreePath, request);
80
+ if (!request.preserveExistingState) {
81
+ await clearRunArtifactRoots(resolvedWorktreePath, request);
82
+ }
83
+ const hydratedPriorPhaseArtifactCount = await hydratePriorPhaseArtifacts(resolvedWorktreePath, request.priorPhaseArtifacts);
48
84
  const qaReworkPacketPath = await materializeQaReworkPacket(resolvedWorktreePath, request);
49
85
  const artifacts = filterArtifactsForLane(request.artifacts, request.lane, request.phase);
50
86
  if (artifacts.length > 0) {
51
- await injectWorktreeArtifacts(resolvedWorktreePath, artifacts);
87
+ await injectWorktreeArtifacts(resolvedWorktreePath, artifacts, await this.trackedForgePaths(resolvedWorktreePath));
52
88
  }
53
- const dependencyWarm = await warmWorktreeDependencies({
54
- baseCheckoutPath: repoPath,
55
- worktreePath: resolvedWorktreePath,
56
- allowedRoot,
57
- warmPathOverrides: request.warmPathOverrides
58
- });
89
+ const dependencyWarm = requiresMutableEnvironmentPreparation(request)
90
+ ? await warmWorktreeDependencies({
91
+ baseCheckoutPath: repoPath,
92
+ worktreePath: resolvedWorktreePath,
93
+ allowedRoot,
94
+ warmPathOverrides: request.warmPathOverrides
95
+ })
96
+ : undefined;
59
97
  return {
60
98
  repoPath,
61
99
  worktreePath: resolvedWorktreePath,
@@ -63,19 +101,88 @@ export class GitWorktreeService {
63
101
  baseBranch,
64
102
  cleanupWorktrees: request.cleanupWorktrees,
65
103
  dependencyWarm,
66
- qaReworkPacketPath
104
+ qaReworkPacketPath,
105
+ hydratedPriorPhaseArtifactCount
67
106
  };
68
107
  }
108
+ async trackedForgePaths(worktreePath) {
109
+ const output = await this.git.run(worktreePath, ["ls-files", "-z", "--", ".forge"]);
110
+ return new Set(output.split("\0").filter(Boolean).map(value => value.replaceAll("\\", "/")));
111
+ }
112
+ async registeredManagedWorktreePath(repoPath, branchName, allowedRoot, worktreeSegments) {
113
+ const listing = await this.git.run(repoPath, ["worktree", "list", "--porcelain", "-z"]);
114
+ const registered = parseRegisteredWorktrees(repoPath, listing)
115
+ .find(entry => entry.branchName === `refs/heads/${branchName}`);
116
+ if (!registered) {
117
+ return null;
118
+ }
119
+ const resolved = await resolveExistingDirectoryPath(registered.worktreePath);
120
+ if (!isManagedLeaseWorktreePath(allowedRoot, resolved, worktreeSegments)) {
121
+ throw new Error(`Branch '${branchName}' is already checked out outside its Forge-managed lease path at ${resolved}.`);
122
+ }
123
+ return resolved;
124
+ }
125
+ repoCreationCoordinationPath(repo, allowedRoot) {
126
+ if (repo.serverLocalPath && repo.serverLocalPath.trim().length > 0) {
127
+ return path.resolve(repo.serverLocalPath);
128
+ }
129
+ return this.managedRepoPath(repo, allowedRoot);
130
+ }
69
131
  async release(handle) {
70
- if (!handle.cleanupWorktrees || !(await directoryExists(handle.worktreePath))) {
132
+ if (!handle.cleanupWorktrees) {
71
133
  return;
72
134
  }
135
+ await this.coordinator.withLock(handle.repoPath, async () => {
136
+ if (await directoryExists(handle.worktreePath)) {
137
+ // On Windows, `git worktree remove` can delete the `.git` link and then
138
+ // fail on a locked build output. That leaves a full source tree which is
139
+ // no longer a Git worktree and makes every retry fail during prepare.
140
+ // Move the tree out of its stable lease path first. If the rename fails,
141
+ // leave the valid worktree untouched rather than partially unregistering it.
142
+ const releasePath = `${handle.worktreePath}.forge-release-${randomUUID()}`;
143
+ await renameWorktreeForRelease(handle.worktreePath, releasePath);
144
+ await this.git.run(handle.repoPath, ["worktree", "prune", "--expire", "now"]);
145
+ await fs.rm(releasePath, {
146
+ recursive: true,
147
+ force: true,
148
+ maxRetries: 10,
149
+ retryDelay: 100,
150
+ }).catch(() => undefined);
151
+ }
152
+ // The process can disappear after Git registers a worktree but before the
153
+ // directory is fully materialized (or after an external cleanup removes it).
154
+ // Always prune so those missing-directory registrations do not accumulate.
155
+ await this.git.run(handle.repoPath, ["worktree", "prune", "--expire", "now"]).catch(() => undefined);
156
+ });
157
+ }
158
+ async restoreOrphanedWorktree(input) {
159
+ const orphanStat = await fs.lstat(input.worktreePath);
160
+ if (orphanStat.isSymbolicLink() || !orphanStat.isDirectory()) {
161
+ throw new Error(`Refusing to recover redirected or non-directory worktree ${input.worktreePath}.`);
162
+ }
163
+ const quarantinePath = `${input.worktreePath}.forge-orphan-${randomUUID()}`;
164
+ if (!isSubPath(input.allowedRoot, quarantinePath)) {
165
+ throw new Error(`Worktree recovery path must stay under ${input.allowedRoot}.`);
166
+ }
167
+ await fs.rename(input.worktreePath, quarantinePath);
73
168
  try {
74
- await this.git.run(handle.repoPath, ["worktree", "remove", "--force", handle.worktreePath]);
75
- await this.git.run(handle.repoPath, ["worktree", "prune"]);
169
+ await this.git.run(input.repoPath, ["worktree", "prune", "--expire", "now"]);
170
+ await this.git.run(input.repoPath, [
171
+ "worktree",
172
+ "add",
173
+ "-B",
174
+ input.branchName,
175
+ input.worktreePath,
176
+ input.baseStartPoint,
177
+ ]);
178
+ await overlayOrphanedWorktree(input.worktreePath, quarantinePath);
179
+ await fs.rm(quarantinePath, { recursive: true, force: true });
76
180
  }
77
- catch {
78
- await fs.rm(handle.worktreePath, { recursive: true, force: true });
181
+ catch (error) {
182
+ await this.git.run(input.repoPath, ["worktree", "remove", "--force", input.worktreePath]).catch(() => undefined);
183
+ await fs.rm(input.worktreePath, { recursive: true, force: true }).catch(() => undefined);
184
+ await fs.rename(quarantinePath, input.worktreePath).catch(() => undefined);
185
+ throw new Error(`Failed to recover orphaned worktree ${input.worktreePath}.`, { cause: error });
79
186
  }
80
187
  }
81
188
  async resolveRepoPath(repo, allowedRoot, baseBranch) {
@@ -93,7 +200,7 @@ export class GitWorktreeService {
93
200
  if (discovered) {
94
201
  return discovered;
95
202
  }
96
- const repoPath = path.join(managedRepoRoot(allowedRoot), `${safeSegment(repo.name, "repo")}-${repo.id.replace(/-/g, "")}`);
203
+ const repoPath = this.managedRepoPath(repo, allowedRoot);
97
204
  if (!(await gitMetadataExists(repoPath, allowedRoot))) {
98
205
  const repoPathExists = await pathExists(repoPath);
99
206
  if (repoPathExists) {
@@ -124,6 +231,9 @@ export class GitWorktreeService {
124
231
  }
125
232
  return resolved;
126
233
  }
234
+ managedRepoPath(repo, allowedRoot) {
235
+ return path.join(managedRepoRoot(allowedRoot), `${safeSegment(repo.name, "repo")}-${repo.id.replace(/-/g, "")}`);
236
+ }
127
237
  async findExistingRepoPath(repo, allowedRoot) {
128
238
  const expectedRemote = normalizeRemote(repo.remoteUrl);
129
239
  const rawName = repo.name.trim();
@@ -164,21 +274,34 @@ export class GitWorktreeService {
164
274
  const resolved = await resolveExistingDirectoryPath(candidate);
165
275
  return isSubPath(allowedRoot, resolved) ? resolved : null;
166
276
  }
167
- async ensureBaseBranch(repoPath, baseBranch) {
168
- if (await this.gitRefExists(repoPath, `refs/heads/${baseBranch}`)) {
169
- return;
277
+ async resolveBaseStartPoint(repoPath, baseBranch) {
278
+ if (baseBranch === "HEAD") {
279
+ const head = (await this.git.run(repoPath, ["rev-parse", "--verify", "HEAD^{commit}"])).trim();
280
+ if (!/^[0-9a-f]{40,64}$/iu.test(head)) {
281
+ throw new Error("The repository checkout does not have a valid committed HEAD revision.");
282
+ }
283
+ return head;
170
284
  }
285
+ const localRef = `refs/heads/${baseBranch}`;
286
+ const remoteRef = `refs/remotes/origin/${baseBranch}`;
171
287
  const origin = await this.git.run(repoPath, ["remote", "get-url", "origin"]).catch(() => "");
172
- if (origin.trim().length === 0) {
173
- throw new Error(`Base branch '${baseBranch}' was not found in the local checkout.`);
288
+ if (origin.trim().length > 0) {
289
+ const fetched = await this.git.run(repoPath, ["fetch", "--prune", "origin"])
290
+ .then(() => true)
291
+ .catch(() => false);
292
+ if (fetched && await this.gitRefExists(repoPath, remoteRef)) {
293
+ return remoteRef;
294
+ }
174
295
  }
175
- await this.git.run(repoPath, ["fetch", "origin", `${baseBranch}:refs/remotes/origin/${baseBranch}`]).catch(() => "");
176
- if (await this.gitRefExists(repoPath, `refs/remotes/origin/${baseBranch}`)) {
177
- await this.git.run(repoPath, ["branch", baseBranch, `refs/remotes/origin/${baseBranch}`]);
178
- return;
296
+ if (await this.gitRefExists(repoPath, localRef)) {
297
+ return localRef;
179
298
  }
180
299
  throw new Error(`Base branch '${baseBranch}' was not found locally or on origin.`);
181
300
  }
301
+ async resetWorktreeToBase(worktreePath, baseStartPoint) {
302
+ await this.git.run(worktreePath, ["reset", "--hard", baseStartPoint]);
303
+ await this.git.run(worktreePath, ["clean", "-fd"]);
304
+ }
182
305
  async gitRefExists(repoPath, gitRef) {
183
306
  return this.git.run(repoPath, ["show-ref", "--verify", "--quiet", gitRef]).then(() => true).catch(() => false);
184
307
  }
@@ -190,14 +313,31 @@ export class GitWorktreeService {
190
313
  await this.git.run(repoPath, ["config", "user.name", "Forge Bridge"]);
191
314
  }
192
315
  }
193
- function managedRepoRoot(allowedRoot) {
194
- return path.join(allowedRoot, ".forge-worktrees", "_repos");
316
+ export async function renameWorktreeForRelease(source, destination, rename = fs.rename, wait = milliseconds => new Promise(resolve => setTimeout(resolve, milliseconds)), maxAttempts = 8) {
317
+ const attempts = Number.isFinite(maxAttempts) && maxAttempts > 0
318
+ ? Math.max(1, Math.floor(maxAttempts))
319
+ : 1;
320
+ for (let attempt = 1; attempt <= attempts; attempt += 1) {
321
+ try {
322
+ await rename(source, destination);
323
+ return;
324
+ }
325
+ catch (error) {
326
+ if (!isTransientWorktreeRenameError(error) || attempt === attempts)
327
+ throw error;
328
+ await wait(Math.min(1_000, 100 * (2 ** (attempt - 1))));
329
+ }
330
+ }
331
+ }
332
+ function isTransientWorktreeRenameError(error) {
333
+ if (!error || typeof error !== "object" || !("code" in error))
334
+ return false;
335
+ const code = String(error.code ?? "").toUpperCase();
336
+ return code === "EPERM" || code === "EACCES" || code === "EBUSY" || code === "ENOTEMPTY";
195
337
  }
196
- function resolveWorktreeRoot(allowedRoot, repoPath) {
197
- const baseName = path.basename(repoPath);
198
- return isSubPath(managedRepoRoot(allowedRoot), repoPath)
199
- ? path.join(allowedRoot, ".forge-worktrees", baseName)
200
- : path.join(path.dirname(repoPath), ".forge-worktrees", baseName);
338
+ export function requiresMutableEnvironmentPreparation(request) {
339
+ // Missing runtime intent is treated conservatively for older dispatch packets.
340
+ return request.applicationRuntimeRequired !== false;
201
341
  }
202
342
  function isCloneableRemote(remoteUrl) {
203
343
  const trimmed = remoteUrl?.trim() ?? "";
@@ -206,9 +346,12 @@ function isCloneableRemote(remoteUrl) {
206
346
  }
207
347
  return trimmed.startsWith("git@") || trimmed.includes("://") || path.isAbsolute(trimmed);
208
348
  }
209
- async function clearRunArtifactRoots(worktreePath, request) {
349
+ export async function clearRunArtifactRoots(worktreePath, request) {
210
350
  const roots = new Set();
211
351
  roots.add(workItemArtifactRoot(worktreePath, request.workItem.id));
352
+ for (const artifact of request.priorPhaseArtifacts ?? []) {
353
+ roots.add(workItemArtifactRoot(worktreePath, artifact.workItemId));
354
+ }
212
355
  const ownerType = normalizeOwnerType(request.ownerType);
213
356
  const ownerId = request.ownerId?.trim();
214
357
  if (ownerType && ownerId) {
@@ -269,6 +412,132 @@ function normalizeOwnerType(value) {
269
412
  }
270
413
  return null;
271
414
  }
415
+ function shouldResetExistingWorktree(request) {
416
+ const lane = request.lane.trim().toLowerCase();
417
+ const phase = request.phase.trim().toLowerCase().replace(/-/g, "_");
418
+ if (lane === "develop" && (phase === "implementation" || phase === "self_review" || phase === "validation")) {
419
+ return false;
420
+ }
421
+ if (lane === "qa" || phase === "qa") {
422
+ return false;
423
+ }
424
+ return true;
425
+ }
426
+ function parseRegisteredWorktrees(repoPath, output) {
427
+ const worktrees = [];
428
+ let current = null;
429
+ for (const field of output.split("\0")) {
430
+ if (field.startsWith("worktree ")) {
431
+ if (current)
432
+ worktrees.push(current);
433
+ const rawPath = field.slice("worktree ".length);
434
+ current = {
435
+ worktreePath: path.resolve(path.isAbsolute(rawPath) ? rawPath : path.join(repoPath, rawPath)),
436
+ branchName: null,
437
+ };
438
+ }
439
+ else if (field.startsWith("branch ") && current) {
440
+ current.branchName = field.slice("branch ".length).trim();
441
+ }
442
+ }
443
+ if (current)
444
+ worktrees.push(current);
445
+ return worktrees;
446
+ }
447
+ function isManagedLeaseWorktreePath(allowedRoot, candidate, worktreeSegments) {
448
+ if (!isSubPath(allowedRoot, candidate)) {
449
+ return false;
450
+ }
451
+ const relativeSegments = path.relative(path.resolve(allowedRoot), path.resolve(candidate))
452
+ .split(path.sep)
453
+ .filter(Boolean);
454
+ const normalize = (value) => process.platform === "win32" ? value.toLowerCase() : value;
455
+ if (normalize(relativeSegments[0] ?? "") !== ".forge-worktrees"
456
+ || relativeSegments.length !== 2 + worktreeSegments.length) {
457
+ return false;
458
+ }
459
+ const suffix = relativeSegments.slice(-worktreeSegments.length).map(normalize);
460
+ return suffix.every((segment, index) => segment === normalize(worktreeSegments[index] ?? ""));
461
+ }
462
+ async function overlayOrphanedWorktree(worktreePath, orphanPath) {
463
+ // A failed Windows cleanup can remove only part of a worktree before its
464
+ // `.git` link disappears. Start from Git's clean checkout so missing tracked
465
+ // files are restored, then overlay every surviving agent file. Moving entries
466
+ // on the same volume preserves pnpm junctions without requiring symlink
467
+ // privileges, unlike fs.cp.
468
+ const backupRoot = `${worktreePath}.forge-base-${randomUUID()}`;
469
+ const moves = [];
470
+ try {
471
+ await fs.mkdir(backupRoot, { recursive: true });
472
+ const orphanEntries = await fs.readdir(orphanPath, { withFileTypes: true });
473
+ for (const entry of orphanEntries) {
474
+ if (entry.name === ".git") {
475
+ continue;
476
+ }
477
+ await overlayEntry({
478
+ sourcePath: path.join(orphanPath, entry.name),
479
+ destinationPath: path.join(worktreePath, entry.name),
480
+ backupPath: path.join(backupRoot, entry.name),
481
+ moves,
482
+ });
483
+ }
484
+ await fs.rm(backupRoot, { recursive: true, force: true });
485
+ }
486
+ catch (error) {
487
+ for (const move of moves.reverse()) {
488
+ await fs.mkdir(path.dirname(move.sourcePath), { recursive: true }).catch(() => undefined);
489
+ await fs.rename(move.destinationPath, move.sourcePath).catch(() => undefined);
490
+ if (move.backupPath) {
491
+ await fs.mkdir(path.dirname(move.destinationPath), { recursive: true }).catch(() => undefined);
492
+ await fs.rename(move.backupPath, move.destinationPath).catch(() => undefined);
493
+ }
494
+ }
495
+ await fs.rm(backupRoot, { recursive: true, force: true }).catch(() => undefined);
496
+ throw error;
497
+ }
498
+ }
499
+ async function overlayEntry(input) {
500
+ const sourceStat = await fs.lstat(input.sourcePath);
501
+ const destinationStat = await fs.lstat(input.destinationPath).catch(() => null);
502
+ if (sourceStat.isDirectory() &&
503
+ !sourceStat.isSymbolicLink() &&
504
+ destinationStat?.isDirectory() &&
505
+ !destinationStat.isSymbolicLink()) {
506
+ const entries = await fs.readdir(input.sourcePath, { withFileTypes: true });
507
+ for (const entry of entries) {
508
+ await overlayEntry({
509
+ sourcePath: path.join(input.sourcePath, entry.name),
510
+ destinationPath: path.join(input.destinationPath, entry.name),
511
+ backupPath: path.join(input.backupPath, entry.name),
512
+ moves: input.moves,
513
+ });
514
+ }
515
+ return;
516
+ }
517
+ let preservedBasePath;
518
+ if (destinationStat) {
519
+ await fs.mkdir(path.dirname(input.backupPath), { recursive: true });
520
+ await fs.rename(input.destinationPath, input.backupPath);
521
+ preservedBasePath = input.backupPath;
522
+ }
523
+ else {
524
+ await fs.mkdir(path.dirname(input.destinationPath), { recursive: true });
525
+ }
526
+ try {
527
+ await fs.rename(input.sourcePath, input.destinationPath);
528
+ }
529
+ catch (error) {
530
+ if (preservedBasePath) {
531
+ await fs.rename(preservedBasePath, input.destinationPath).catch(() => undefined);
532
+ }
533
+ throw error;
534
+ }
535
+ input.moves.push({
536
+ sourcePath: input.sourcePath,
537
+ destinationPath: input.destinationPath,
538
+ backupPath: preservedBasePath,
539
+ });
540
+ }
272
541
  function qaReworkPacketFileName(packetPath) {
273
542
  const normalized = packetPath.trim().replace(/\\/g, "/");
274
543
  const fileName = normalized.split("/").filter(Boolean).at(-1) ?? "";
@@ -1,4 +1,4 @@
1
- import type { DispatchQaReworkContext, DispatchRepo, DispatchWorkItem, DispatchResolvedArtifact } from "../session/session.types.js";
1
+ import type { DispatchQaReworkContext, DispatchPriorPhaseArtifact, DispatchRepo, DispatchWorkItem, DispatchResolvedArtifact } from "../session/session.types.js";
2
2
  import type { WarmDependenciesResult } from "./dependency-warmer.js";
3
3
  export interface WorktreePrepareRequest {
4
4
  readonly repo: DispatchRepo;
@@ -12,8 +12,11 @@ export interface WorktreePrepareRequest {
12
12
  readonly allowedRepoRoot: string;
13
13
  readonly cleanupWorktrees: boolean;
14
14
  readonly artifacts: readonly DispatchResolvedArtifact[];
15
+ readonly priorPhaseArtifacts?: readonly DispatchPriorPhaseArtifact[];
15
16
  readonly qaRework?: DispatchQaReworkContext | null;
16
17
  readonly warmPathOverrides?: readonly string[];
18
+ readonly applicationRuntimeRequired?: boolean;
19
+ readonly preserveExistingState?: boolean;
17
20
  }
18
21
  export interface WorktreeHandle {
19
22
  readonly repoPath: string;
@@ -23,4 +26,5 @@ export interface WorktreeHandle {
23
26
  readonly cleanupWorktrees: boolean;
24
27
  readonly dependencyWarm?: WarmDependenciesResult;
25
28
  readonly qaReworkPacketPath?: string;
29
+ readonly hydratedPriorPhaseArtifactCount?: number;
26
30
  }
package/package.json CHANGED
@@ -1,10 +1,11 @@
1
1
  {
2
2
  "name": "@loucompanion/forge-bridge",
3
- "version": "0.1.3-dev.b6be5e7f9668",
3
+ "version": "0.1.3-dev.ba293ccf876b",
4
4
  "description": "Forge runner bridge CLI for connecting local developer machines to Forge dispatch.",
5
5
  "license": "UNLICENSED",
6
6
  "type": "module",
7
7
  "bin": {
8
+ "forge": "dist/cli/bin.js",
8
9
  "forge-bridge": "dist/cli/bin.js"
9
10
  },
10
11
  "main": "./dist/index.js",
@@ -18,6 +19,7 @@
18
19
  },
19
20
  "files": [
20
21
  "dist",
22
+ "runtime",
21
23
  "README.md"
22
24
  ],
23
25
  "repository": {
@@ -37,13 +39,15 @@
37
39
  },
38
40
  "scripts": {
39
41
  "build": "tsc -p tsconfig.json",
40
- "test": "vitest run",
42
+ "test": "node scripts/run-owned-tests.mjs",
43
+ "test:residue": "node scripts/run-owned-residue-gate.mjs",
41
44
  "test:watch": "vitest",
42
45
  "smoke:package": "npm run build && node scripts/smoke-package.mjs",
43
- "lint": "eslint \"src/**/*.ts\" \"scripts/**/*.mjs\" \"vitest.config.ts\""
46
+ "lint": "eslint \"src/**/*.ts\" \"scripts/**/*.mjs\" \"vitest.config.ts\" \"vitest.setup.ts\""
44
47
  },
45
48
  "dependencies": {
46
- "@microsoft/signalr": "^8.0.17"
49
+ "@microsoft/signalr": "^8.0.17",
50
+ "yaml": "^2.9.0"
47
51
  },
48
52
  "devDependencies": {
49
53
  "@eslint/js": "^10.0.1",