@loucompanion/forge-bridge 0.1.3-dev.0bd9fb991b79 → 0.1.3-dev.0d26c10244e1

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 (127) hide show
  1. package/README.md +35 -0
  2. package/dist/bridge/bridge.base.d.ts +4 -1
  3. package/dist/bridge/bridge.service.d.ts +39 -3
  4. package/dist/bridge/bridge.service.js +585 -56
  5. package/dist/bridge/bridge.types.d.ts +59 -1
  6. package/dist/cleanup/cleanup.service.d.ts +14 -2
  7. package/dist/cleanup/cleanup.service.js +469 -3
  8. package/dist/cleanup/cleanup.types.d.ts +10 -0
  9. package/dist/cleanup/index.d.ts +1 -1
  10. package/dist/cleanup/index.js +1 -1
  11. package/dist/cleanup/internals.d.ts +2 -2
  12. package/dist/cleanup/internals.js +1 -1
  13. package/dist/cli/cli.help.js +37 -3
  14. package/dist/cli/cli.service.d.ts +30 -2
  15. package/dist/cli/cli.service.js +191 -27
  16. package/dist/cli/local-config.d.ts +4 -0
  17. package/dist/cli/local-config.js +41 -1
  18. package/dist/runtime/aspnet-runtime-prebuild.d.ts +35 -0
  19. package/dist/runtime/aspnet-runtime-prebuild.js +168 -0
  20. package/dist/runtime/attempt-node-runtime-launcher.d.ts +17 -0
  21. package/dist/runtime/attempt-node-runtime-launcher.js +105 -0
  22. package/dist/runtime/attempt-process-supervisor-registry.d.ts +20 -0
  23. package/dist/runtime/attempt-process-supervisor-registry.js +64 -0
  24. package/dist/runtime/attempt-process-supervisor.d.ts +86 -0
  25. package/dist/runtime/attempt-process-supervisor.js +350 -0
  26. package/dist/runtime/generated-output-reset.d.ts +10 -0
  27. package/dist/runtime/generated-output-reset.js +103 -0
  28. package/dist/runtime/host-listener-inspector.d.ts +46 -0
  29. package/dist/runtime/host-listener-inspector.js +349 -0
  30. package/dist/runtime/host-port-broker.d.ts +76 -0
  31. package/dist/runtime/host-port-broker.js +333 -0
  32. package/dist/runtime/host-runtime-contract.d.ts +47 -0
  33. package/dist/runtime/host-runtime-contract.js +700 -0
  34. package/dist/runtime/host-runtime-lease.d.ts +179 -0
  35. package/dist/runtime/host-runtime-lease.js +1990 -0
  36. package/dist/runtime/host-runtime-promotion.d.ts +23 -0
  37. package/dist/runtime/host-runtime-promotion.js +159 -0
  38. package/dist/runtime/node-host-runtime-adapter.d.ts +54 -0
  39. package/dist/runtime/node-host-runtime-adapter.js +284 -0
  40. package/dist/runtime/playwright-host-runtime-adapter.d.ts +20 -0
  41. package/dist/runtime/playwright-host-runtime-adapter.js +220 -0
  42. package/dist/runtime/runtime-isolation-lease.d.ts +67 -0
  43. package/dist/runtime/runtime-isolation-lease.js +158 -0
  44. package/dist/runtime/workspace-resource-estimator.d.ts +16 -0
  45. package/dist/runtime/workspace-resource-estimator.js +165 -0
  46. package/dist/sandbox/preflight.d.ts +15 -0
  47. package/dist/sandbox/preflight.js +100 -13
  48. package/dist/sandbox/process.js +125 -40
  49. package/dist/sandbox/repository-lock.js +37 -1
  50. package/dist/sandbox/runtime.d.ts +66 -3
  51. package/dist/sandbox/runtime.js +670 -105
  52. package/dist/sandbox/sandbox.types.d.ts +3 -0
  53. package/dist/sandbox/smoke.d.ts +76 -0
  54. package/dist/sandbox/smoke.js +380 -0
  55. package/dist/sandbox/worker-supervisor.js +1 -1
  56. package/dist/sandbox/worker.js +2 -5
  57. package/dist/sandbox/workspace.service.d.ts +1 -0
  58. package/dist/sandbox/workspace.service.js +28 -5
  59. package/dist/session/managed-attempt-tools.d.ts +18 -0
  60. package/dist/session/managed-attempt-tools.js +797 -0
  61. package/dist/session/managed-build-coordinator.d.ts +5 -0
  62. package/dist/session/managed-build-coordinator.js +105 -0
  63. package/dist/session/phase-completion.artifacts.js +21 -3
  64. package/dist/session/phase-completion.d.ts +11 -2
  65. package/dist/session/phase-completion.helpers.d.ts +5 -0
  66. package/dist/session/phase-completion.helpers.js +51 -10
  67. package/dist/session/phase-completion.js +12 -3
  68. package/dist/session/phase-completion.prompts.d.ts +3 -3
  69. package/dist/session/phase-completion.prompts.js +21 -6
  70. package/dist/session/phase-completion.runtime.d.ts +13 -1
  71. package/dist/session/phase-completion.runtime.js +187 -8
  72. package/dist/session/phase-completion.schemas.js +108 -3
  73. package/dist/session/phase-completion.validation.d.ts +4 -1
  74. package/dist/session/phase-completion.validation.js +150 -21
  75. package/dist/session/provider-cli/ci-repair-readiness.d.ts +14 -0
  76. package/dist/session/provider-cli/ci-repair-readiness.js +105 -0
  77. package/dist/session/provider-cli/provider-cli.artifacts.d.ts +3 -2
  78. package/dist/session/provider-cli/provider-cli.artifacts.js +65 -7
  79. package/dist/session/provider-cli/provider-cli.deterministic.js +47 -1
  80. package/dist/session/provider-cli/provider-cli.process.d.ts +16 -0
  81. package/dist/session/provider-cli/provider-cli.process.js +212 -25
  82. package/dist/session/provider-cli/provider-cli.prompts.d.ts +4 -1
  83. package/dist/session/provider-cli/provider-cli.prompts.js +99 -19
  84. package/dist/session/provider-cli/provider-cli.qa-sidecars.js +1 -0
  85. package/dist/session/provider-cli/provider-cli.runtime.d.ts +1 -1
  86. package/dist/session/provider-cli/provider-cli.runtime.js +3 -2
  87. package/dist/session/provider-cli/provider-cli.service.d.ts +20 -2
  88. package/dist/session/provider-cli/provider-cli.service.js +464 -102
  89. package/dist/session/provider-cli/provider-cli.types.d.ts +5 -0
  90. package/dist/session/provider-cli/provider-output-state.d.ts +2 -0
  91. package/dist/session/provider-cli/provider-output-state.js +69 -7
  92. package/dist/session/session-redaction.d.ts +3 -0
  93. package/dist/session/session-redaction.js +38 -0
  94. package/dist/session/session.base.d.ts +6 -1
  95. package/dist/session/session.service.d.ts +8 -2
  96. package/dist/session/session.service.js +482 -41
  97. package/dist/session/session.types.d.ts +70 -0
  98. package/dist/session/session.types.js +76 -4
  99. package/dist/shared/format/format-bytes.d.ts +1 -0
  100. package/dist/shared/format/format-bytes.js +9 -0
  101. package/dist/shared/path/path.js +3 -1
  102. package/dist/shared/process/host-process-recovery.d.ts +12 -0
  103. package/dist/shared/process/host-process-recovery.js +78 -0
  104. package/dist/shared/process/host-process-supervisor.d.ts +57 -0
  105. package/dist/shared/process/host-process-supervisor.js +282 -0
  106. package/dist/shared/process/process.d.ts +1 -0
  107. package/dist/shared/process/process.js +1 -0
  108. package/dist/shared/redaction/redaction.js +6 -1
  109. package/dist/version.d.ts +1 -1
  110. package/dist/version.js +1 -1
  111. package/dist/worktree/artifact-injector.d.ts +3 -2
  112. package/dist/worktree/artifact-injector.js +43 -4
  113. package/dist/worktree/dependency-warmer.d.ts +10 -1
  114. package/dist/worktree/dependency-warmer.js +94 -5
  115. package/dist/worktree/index.d.ts +1 -0
  116. package/dist/worktree/index.js +1 -0
  117. package/dist/worktree/prior-phase-artifact-hydrator.d.ts +2 -0
  118. package/dist/worktree/prior-phase-artifact-hydrator.js +136 -0
  119. package/dist/worktree/worktree-paths.d.ts +4 -0
  120. package/dist/worktree/worktree-paths.js +30 -0
  121. package/dist/worktree/worktree.base.d.ts +3 -0
  122. package/dist/worktree/worktree.service.d.ts +8 -2
  123. package/dist/worktree/worktree.service.js +206 -43
  124. package/dist/worktree/worktree.types.d.ts +4 -1
  125. package/package.json +3 -2
  126. package/runtime/windows-job-supervisor.ps1 +356 -0
  127. package/runtime/windows-listener-owner.ps1 +33 -0
@@ -0,0 +1,136 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import fs from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { isSubPath } from "../shared/path/path.js";
5
+ const MAX_ARTIFACT_COUNT = 128;
6
+ const MAX_CONTENT_BYTES = 2 * 1024 * 1024;
7
+ const MAX_TOTAL_BYTES = 12 * 1024 * 1024;
8
+ const phaseFiles = {
9
+ implementation: {
10
+ verdict: "implementation.completeness.json",
11
+ report: "implementation.report.md"
12
+ },
13
+ self_review: {
14
+ verdict: "self-review.report.json",
15
+ report: "self-review.summary.md"
16
+ },
17
+ validation: {
18
+ verdict: "validation.verdict.json",
19
+ report: "validation.report.md"
20
+ }
21
+ };
22
+ export async function hydratePriorPhaseArtifacts(worktreePath, artifacts = []) {
23
+ if (artifacts.length === 0)
24
+ return 0;
25
+ if (artifacts.length > MAX_ARTIFACT_COUNT) {
26
+ throw new Error(`Prior phase artifact handoff exceeds ${MAX_ARTIFACT_COUNT} artifacts.`);
27
+ }
28
+ const targets = new Set();
29
+ let totalBytes = 0;
30
+ for (const artifact of artifacts) {
31
+ const workItemId = safeArtifactSegment(artifact.workItemId, "work item id");
32
+ const files = phaseFiles[artifact.phase];
33
+ if (!files) {
34
+ throw new Error(`Unsupported prior phase artifact phase '${artifact.phase}'.`);
35
+ }
36
+ const verdictBytes = Buffer.byteLength(artifact.verdictJson, "utf8");
37
+ const reportBytes = Buffer.byteLength(artifact.report, "utf8");
38
+ if (verdictBytes > MAX_CONTENT_BYTES || reportBytes > MAX_CONTENT_BYTES) {
39
+ throw new Error(`Prior phase artifact '${artifact.artifactId}' exceeds the per-file hydration limit.`);
40
+ }
41
+ totalBytes += verdictBytes + reportBytes;
42
+ if (totalBytes > MAX_TOTAL_BYTES) {
43
+ throw new Error("Prior phase artifact handoff exceeds the total hydration limit.");
44
+ }
45
+ verifyContentHash(artifact.verdictJson, artifact.verdictContentHash, artifact.artifactId, "verdict");
46
+ verifyContentHash(artifact.report, artifact.reportContentHash, artifact.artifactId, "report");
47
+ validateVerdict(artifact);
48
+ const artifactRoot = path.resolve(worktreePath, ".forge", "work-items", workItemId, "artifacts");
49
+ if (!isSubPath(worktreePath, artifactRoot)) {
50
+ throw new Error("Prior phase artifact target must stay under the worktree.");
51
+ }
52
+ await ensureNoSymlinkPathSegments(worktreePath, artifactRoot);
53
+ await fs.mkdir(artifactRoot, { recursive: true });
54
+ await ensureNoSymlinkPathSegments(worktreePath, artifactRoot);
55
+ const verdictPath = path.join(artifactRoot, files.verdict);
56
+ const reportPath = path.join(artifactRoot, files.report);
57
+ const targetKey = verdictPath.toLowerCase();
58
+ if (targets.has(targetKey)) {
59
+ throw new Error(`Duplicate prior phase artifact target for work item '${workItemId}' phase '${artifact.phase}'.`);
60
+ }
61
+ targets.add(targetKey);
62
+ await writeAtomic(verdictPath, artifact.verdictJson);
63
+ await writeAtomic(reportPath, artifact.report);
64
+ }
65
+ return artifacts.length;
66
+ }
67
+ function validateVerdict(artifact) {
68
+ let parsed;
69
+ try {
70
+ parsed = JSON.parse(artifact.verdictJson);
71
+ }
72
+ catch {
73
+ throw new Error(`Prior phase artifact '${artifact.artifactId}' verdict is not valid JSON.`);
74
+ }
75
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
76
+ throw new Error(`Prior phase artifact '${artifact.artifactId}' verdict must be a JSON object.`);
77
+ }
78
+ const recordedPhase = parsed["phase"];
79
+ const normalizedPhase = typeof recordedPhase === "string"
80
+ ? recordedPhase.trim().toLowerCase().replace(/-/g, "_")
81
+ : "";
82
+ if (normalizedPhase !== artifact.phase) {
83
+ throw new Error(`Prior phase artifact '${artifact.artifactId}' phase does not match its verdict.`);
84
+ }
85
+ }
86
+ function verifyContentHash(content, expected, artifactId, label) {
87
+ const normalizedExpected = expected.trim().toLowerCase().replace(/^sha256:/, "");
88
+ if (!/^[0-9a-f]{64}$/.test(normalizedExpected)) {
89
+ throw new Error(`Prior phase artifact '${artifactId}' ${label} hash is invalid.`);
90
+ }
91
+ const actual = createHash("sha256").update(content, "utf8").digest("hex");
92
+ if (actual !== normalizedExpected) {
93
+ throw new Error(`Prior phase artifact '${artifactId}' ${label} content_hash mismatch.`);
94
+ }
95
+ }
96
+ function safeArtifactSegment(value, label) {
97
+ const trimmed = value.trim();
98
+ if (!/^[a-zA-Z0-9_-]{1,128}$/.test(trimmed)) {
99
+ throw new Error(`Prior phase artifact ${label} is not a safe path segment.`);
100
+ }
101
+ return trimmed;
102
+ }
103
+ async function writeAtomic(targetPath, content) {
104
+ const temporaryPath = `${targetPath}.tmp-${randomUUID()}`;
105
+ try {
106
+ await fs.writeFile(temporaryPath, content, { encoding: "utf8", mode: 0o600, flag: "wx" });
107
+ await fs.rename(temporaryPath, targetPath);
108
+ }
109
+ finally {
110
+ await fs.rm(temporaryPath, { force: true }).catch(() => undefined);
111
+ }
112
+ }
113
+ async function ensureNoSymlinkPathSegments(root, targetPath) {
114
+ const resolvedRoot = path.resolve(root);
115
+ const resolvedTarget = path.resolve(targetPath);
116
+ const relative = path.relative(resolvedRoot, resolvedTarget);
117
+ if (relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {
118
+ throw new Error("Prior phase artifact path must stay under the worktree.");
119
+ }
120
+ let current = resolvedRoot;
121
+ for (const segment of relative.split(path.sep)) {
122
+ if (!segment)
123
+ continue;
124
+ current = path.join(current, segment);
125
+ const stat = await fs.lstat(current).catch((error) => {
126
+ if (error.code === "ENOENT")
127
+ return null;
128
+ throw error;
129
+ });
130
+ if (!stat)
131
+ return;
132
+ if (stat.isSymbolicLink()) {
133
+ throw new Error("Prior phase artifact path must not traverse symlinked path segments.");
134
+ }
135
+ }
136
+ }
@@ -0,0 +1,4 @@
1
+ export declare function managedRepoRoot(allowedRoot: string): string;
2
+ export declare function resolveManagedWorktreeRoot(allowedRoot: string, repoPath: string): string;
3
+ export declare function resolveManagedWorktreeRootForRepo(repoPath: string, allowedRoot?: string): string;
4
+ export declare function defaultWorktreeCoordinatorStateRoot(): string;
@@ -0,0 +1,30 @@
1
+ import os from "node:os";
2
+ import path from "node:path";
3
+ import { isSubPath } from "../shared/path/path.js";
4
+ export function managedRepoRoot(allowedRoot) {
5
+ return path.join(path.resolve(allowedRoot), ".forge-worktrees", "_repos");
6
+ }
7
+ export function resolveManagedWorktreeRoot(allowedRoot, repoPath) {
8
+ const resolvedAllowedRoot = path.resolve(allowedRoot);
9
+ const resolvedRepoPath = path.resolve(repoPath);
10
+ const baseName = path.basename(resolvedRepoPath);
11
+ return isSubPath(managedRepoRoot(resolvedAllowedRoot), resolvedRepoPath)
12
+ ? path.join(resolvedAllowedRoot, ".forge-worktrees", baseName)
13
+ : path.join(path.dirname(resolvedRepoPath), ".forge-worktrees", baseName);
14
+ }
15
+ export function resolveManagedWorktreeRootForRepo(repoPath, allowedRoot) {
16
+ const resolvedRepoPath = path.resolve(repoPath);
17
+ if (allowedRoot && isSubPath(path.resolve(allowedRoot), resolvedRepoPath)) {
18
+ return resolveManagedWorktreeRoot(allowedRoot, resolvedRepoPath);
19
+ }
20
+ const repoParent = path.dirname(resolvedRepoPath);
21
+ const managedRoot = path.dirname(repoParent);
22
+ if (path.basename(repoParent) === "_repos" && path.basename(managedRoot) === ".forge-worktrees") {
23
+ return path.join(managedRoot, path.basename(resolvedRepoPath));
24
+ }
25
+ return path.join(repoParent, ".forge-worktrees", path.basename(resolvedRepoPath));
26
+ }
27
+ export function defaultWorktreeCoordinatorStateRoot() {
28
+ return process.env.FORGE_SANDBOX_STATE_ROOT
29
+ ?? path.join(os.homedir(), ".forge", "bridge", "sandboxes");
30
+ }
@@ -3,3 +3,6 @@ export interface WorktreeService {
3
3
  prepare(request: WorktreePrepareRequest): Promise<WorktreeHandle>;
4
4
  release(handle: WorktreeHandle): Promise<void>;
5
5
  }
6
+ export interface WorktreeLifecycleCoordinator {
7
+ withLock<T>(repoPath: string, action: () => Promise<T>, signal?: AbortSignal): Promise<T>;
8
+ }
@@ -1,12 +1,17 @@
1
1
  import { GitClient } from "../shared/git/git.js";
2
- import type { WorktreeService } from "./worktree.base.js";
2
+ import type { WorktreeLifecycleCoordinator, WorktreeService } from "./worktree.base.js";
3
3
  import type { WorktreeHandle, WorktreePrepareRequest } from "./worktree.types.js";
4
4
  export declare class GitWorktreeService implements WorktreeService {
5
5
  private readonly git;
6
- constructor(git?: GitClient);
6
+ private readonly coordinator;
7
+ constructor(git?: GitClient, coordinator?: WorktreeLifecycleCoordinator);
7
8
  prepare(request: WorktreePrepareRequest): Promise<WorktreeHandle>;
9
+ private trackedForgePaths;
10
+ private repoCreationCoordinationPath;
8
11
  release(handle: WorktreeHandle): Promise<void>;
12
+ private restoreOrphanedWorktree;
9
13
  private resolveRepoPath;
14
+ private managedRepoPath;
10
15
  private findExistingRepoPath;
11
16
  private resolveMatchingRepo;
12
17
  private resolveBaseStartPoint;
@@ -15,4 +20,5 @@ export declare class GitWorktreeService implements WorktreeService {
15
20
  private currentBranch;
16
21
  private ensureGitIdentity;
17
22
  }
23
+ export declare function clearRunArtifactRoots(worktreePath: string, request: WorktreePrepareRequest): Promise<void>;
18
24
  export declare function normalizeBranchName(value: string | null | undefined, fallback: string): string;
@@ -1,57 +1,81 @@
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
- const baseStartPoint = await this.resolveBaseStartPoint(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, baseStartPoint]);
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
+ if (!(await directoryExists(worktreePath))) {
41
+ // A prior runner can disappear after Git registers its worktree but before
42
+ // normal cleanup completes. Release that missing-directory registration
43
+ // immediately so retrying the same lease remains idempotent.
44
+ await this.git.run(repoPath, ["worktree", "prune", "--expire", "now"]);
45
+ await this.git.run(repoPath, ["worktree", "add", "-B", branchName, worktreePath, baseStartPoint]);
46
+ return await resolveExistingDirectoryPath(worktreePath);
47
+ }
48
+ const existingWorktreePath = await resolveExistingDirectoryPath(worktreePath);
49
+ if (!isSubPath(allowedRoot, existingWorktreePath)) {
39
50
  throw new Error(`Worktree path must stay under ${allowedRoot}.`);
40
51
  }
41
- const currentBranch = await this.currentBranch(resolvedWorktreePath);
52
+ if (!(await gitMetadataExists(existingWorktreePath, allowedRoot))) {
53
+ await this.restoreOrphanedWorktree({
54
+ repoPath,
55
+ worktreePath: existingWorktreePath,
56
+ branchName,
57
+ baseStartPoint,
58
+ allowedRoot,
59
+ });
60
+ }
61
+ const currentBranch = await this.currentBranch(existingWorktreePath);
42
62
  if (currentBranch !== branchName) {
43
- throw new Error(`Existing worktree ${resolvedWorktreePath} is on branch '${currentBranch}', expected '${branchName}'.`);
63
+ throw new Error(`Existing worktree ${existingWorktreePath} is on branch '${currentBranch}', expected '${branchName}'.`);
44
64
  }
45
- if (shouldResetExistingWorktree(request)) {
46
- await this.resetWorktreeToBase(resolvedWorktreePath, baseStartPoint);
65
+ if (!request.preserveExistingState && shouldResetExistingWorktree(request)) {
66
+ await this.resetWorktreeToBase(existingWorktreePath, baseStartPoint);
47
67
  }
48
- }
68
+ return existingWorktreePath;
69
+ });
49
70
  await this.ensureGitIdentity(resolvedWorktreePath);
50
- await clearRunArtifactRoots(resolvedWorktreePath, request);
71
+ if (!request.preserveExistingState) {
72
+ await clearRunArtifactRoots(resolvedWorktreePath, request);
73
+ }
74
+ const hydratedPriorPhaseArtifactCount = await hydratePriorPhaseArtifacts(resolvedWorktreePath, request.priorPhaseArtifacts);
51
75
  const qaReworkPacketPath = await materializeQaReworkPacket(resolvedWorktreePath, request);
52
76
  const artifacts = filterArtifactsForLane(request.artifacts, request.lane, request.phase);
53
77
  if (artifacts.length > 0) {
54
- await injectWorktreeArtifacts(resolvedWorktreePath, artifacts);
78
+ await injectWorktreeArtifacts(resolvedWorktreePath, artifacts, await this.trackedForgePaths(resolvedWorktreePath));
55
79
  }
56
80
  const dependencyWarm = await warmWorktreeDependencies({
57
81
  baseCheckoutPath: repoPath,
@@ -66,19 +90,75 @@ export class GitWorktreeService {
66
90
  baseBranch,
67
91
  cleanupWorktrees: request.cleanupWorktrees,
68
92
  dependencyWarm,
69
- qaReworkPacketPath
93
+ qaReworkPacketPath,
94
+ hydratedPriorPhaseArtifactCount
70
95
  };
71
96
  }
97
+ async trackedForgePaths(worktreePath) {
98
+ const output = await this.git.run(worktreePath, ["ls-files", "-z", "--", ".forge"]);
99
+ return new Set(output.split("\0").filter(Boolean).map(value => value.replaceAll("\\", "/")));
100
+ }
101
+ repoCreationCoordinationPath(repo, allowedRoot) {
102
+ if (repo.serverLocalPath && repo.serverLocalPath.trim().length > 0) {
103
+ return path.resolve(repo.serverLocalPath);
104
+ }
105
+ return this.managedRepoPath(repo, allowedRoot);
106
+ }
72
107
  async release(handle) {
73
- if (!handle.cleanupWorktrees || !(await directoryExists(handle.worktreePath))) {
108
+ if (!handle.cleanupWorktrees) {
74
109
  return;
75
110
  }
111
+ await this.coordinator.withLock(handle.repoPath, async () => {
112
+ if (await directoryExists(handle.worktreePath)) {
113
+ // On Windows, `git worktree remove` can delete the `.git` link and then
114
+ // fail on a locked build output. That leaves a full source tree which is
115
+ // no longer a Git worktree and makes every retry fail during prepare.
116
+ // Move the tree out of its stable lease path first. If the rename fails,
117
+ // leave the valid worktree untouched rather than partially unregistering it.
118
+ const releasePath = `${handle.worktreePath}.forge-release-${randomUUID()}`;
119
+ await fs.rename(handle.worktreePath, releasePath);
120
+ await this.git.run(handle.repoPath, ["worktree", "prune", "--expire", "now"]);
121
+ await fs.rm(releasePath, {
122
+ recursive: true,
123
+ force: true,
124
+ maxRetries: 10,
125
+ retryDelay: 100,
126
+ }).catch(() => undefined);
127
+ }
128
+ // The process can disappear after Git registers a worktree but before the
129
+ // directory is fully materialized (or after an external cleanup removes it).
130
+ // Always prune so those missing-directory registrations do not accumulate.
131
+ await this.git.run(handle.repoPath, ["worktree", "prune", "--expire", "now"]).catch(() => undefined);
132
+ });
133
+ }
134
+ async restoreOrphanedWorktree(input) {
135
+ const orphanStat = await fs.lstat(input.worktreePath);
136
+ if (orphanStat.isSymbolicLink() || !orphanStat.isDirectory()) {
137
+ throw new Error(`Refusing to recover redirected or non-directory worktree ${input.worktreePath}.`);
138
+ }
139
+ const quarantinePath = `${input.worktreePath}.forge-orphan-${randomUUID()}`;
140
+ if (!isSubPath(input.allowedRoot, quarantinePath)) {
141
+ throw new Error(`Worktree recovery path must stay under ${input.allowedRoot}.`);
142
+ }
143
+ await fs.rename(input.worktreePath, quarantinePath);
76
144
  try {
77
- await this.git.run(handle.repoPath, ["worktree", "remove", "--force", handle.worktreePath]);
78
- await this.git.run(handle.repoPath, ["worktree", "prune"]);
145
+ await this.git.run(input.repoPath, ["worktree", "prune", "--expire", "now"]);
146
+ await this.git.run(input.repoPath, [
147
+ "worktree",
148
+ "add",
149
+ "-B",
150
+ input.branchName,
151
+ input.worktreePath,
152
+ input.baseStartPoint,
153
+ ]);
154
+ await overlayOrphanedWorktree(input.worktreePath, quarantinePath);
155
+ await fs.rm(quarantinePath, { recursive: true, force: true });
79
156
  }
80
- catch {
81
- await fs.rm(handle.worktreePath, { recursive: true, force: true });
157
+ catch (error) {
158
+ await this.git.run(input.repoPath, ["worktree", "remove", "--force", input.worktreePath]).catch(() => undefined);
159
+ await fs.rm(input.worktreePath, { recursive: true, force: true }).catch(() => undefined);
160
+ await fs.rename(quarantinePath, input.worktreePath).catch(() => undefined);
161
+ throw new Error(`Failed to recover orphaned worktree ${input.worktreePath}.`, { cause: error });
82
162
  }
83
163
  }
84
164
  async resolveRepoPath(repo, allowedRoot, baseBranch) {
@@ -96,7 +176,7 @@ export class GitWorktreeService {
96
176
  if (discovered) {
97
177
  return discovered;
98
178
  }
99
- const repoPath = path.join(managedRepoRoot(allowedRoot), `${safeSegment(repo.name, "repo")}-${repo.id.replace(/-/g, "")}`);
179
+ const repoPath = this.managedRepoPath(repo, allowedRoot);
100
180
  if (!(await gitMetadataExists(repoPath, allowedRoot))) {
101
181
  const repoPathExists = await pathExists(repoPath);
102
182
  if (repoPathExists) {
@@ -127,6 +207,9 @@ export class GitWorktreeService {
127
207
  }
128
208
  return resolved;
129
209
  }
210
+ managedRepoPath(repo, allowedRoot) {
211
+ return path.join(managedRepoRoot(allowedRoot), `${safeSegment(repo.name, "repo")}-${repo.id.replace(/-/g, "")}`);
212
+ }
130
213
  async findExistingRepoPath(repo, allowedRoot) {
131
214
  const expectedRemote = normalizeRemote(repo.remoteUrl);
132
215
  const rawName = repo.name.trim();
@@ -168,6 +251,13 @@ export class GitWorktreeService {
168
251
  return isSubPath(allowedRoot, resolved) ? resolved : null;
169
252
  }
170
253
  async resolveBaseStartPoint(repoPath, baseBranch) {
254
+ if (baseBranch === "HEAD") {
255
+ const head = (await this.git.run(repoPath, ["rev-parse", "--verify", "HEAD^{commit}"])).trim();
256
+ if (!/^[0-9a-f]{40,64}$/iu.test(head)) {
257
+ throw new Error("The repository checkout does not have a valid committed HEAD revision.");
258
+ }
259
+ return head;
260
+ }
171
261
  const localRef = `refs/heads/${baseBranch}`;
172
262
  const remoteRef = `refs/remotes/origin/${baseBranch}`;
173
263
  const origin = await this.git.run(repoPath, ["remote", "get-url", "origin"]).catch(() => "");
@@ -199,15 +289,6 @@ export class GitWorktreeService {
199
289
  await this.git.run(repoPath, ["config", "user.name", "Forge Bridge"]);
200
290
  }
201
291
  }
202
- function managedRepoRoot(allowedRoot) {
203
- return path.join(allowedRoot, ".forge-worktrees", "_repos");
204
- }
205
- function resolveWorktreeRoot(allowedRoot, repoPath) {
206
- const baseName = path.basename(repoPath);
207
- return isSubPath(managedRepoRoot(allowedRoot), repoPath)
208
- ? path.join(allowedRoot, ".forge-worktrees", baseName)
209
- : path.join(path.dirname(repoPath), ".forge-worktrees", baseName);
210
- }
211
292
  function isCloneableRemote(remoteUrl) {
212
293
  const trimmed = remoteUrl?.trim() ?? "";
213
294
  if (trimmed.length === 0 || trimmed.startsWith("local://")) {
@@ -215,9 +296,12 @@ function isCloneableRemote(remoteUrl) {
215
296
  }
216
297
  return trimmed.startsWith("git@") || trimmed.includes("://") || path.isAbsolute(trimmed);
217
298
  }
218
- async function clearRunArtifactRoots(worktreePath, request) {
299
+ export async function clearRunArtifactRoots(worktreePath, request) {
219
300
  const roots = new Set();
220
301
  roots.add(workItemArtifactRoot(worktreePath, request.workItem.id));
302
+ for (const artifact of request.priorPhaseArtifacts ?? []) {
303
+ roots.add(workItemArtifactRoot(worktreePath, artifact.workItemId));
304
+ }
221
305
  const ownerType = normalizeOwnerType(request.ownerType);
222
306
  const ownerId = request.ownerId?.trim();
223
307
  if (ownerType && ownerId) {
@@ -289,6 +373,85 @@ function shouldResetExistingWorktree(request) {
289
373
  }
290
374
  return true;
291
375
  }
376
+ async function overlayOrphanedWorktree(worktreePath, orphanPath) {
377
+ // A failed Windows cleanup can remove only part of a worktree before its
378
+ // `.git` link disappears. Start from Git's clean checkout so missing tracked
379
+ // files are restored, then overlay every surviving agent file. Moving entries
380
+ // on the same volume preserves pnpm junctions without requiring symlink
381
+ // privileges, unlike fs.cp.
382
+ const backupRoot = `${worktreePath}.forge-base-${randomUUID()}`;
383
+ const moves = [];
384
+ try {
385
+ await fs.mkdir(backupRoot, { recursive: true });
386
+ const orphanEntries = await fs.readdir(orphanPath, { withFileTypes: true });
387
+ for (const entry of orphanEntries) {
388
+ if (entry.name === ".git") {
389
+ continue;
390
+ }
391
+ await overlayEntry({
392
+ sourcePath: path.join(orphanPath, entry.name),
393
+ destinationPath: path.join(worktreePath, entry.name),
394
+ backupPath: path.join(backupRoot, entry.name),
395
+ moves,
396
+ });
397
+ }
398
+ await fs.rm(backupRoot, { recursive: true, force: true });
399
+ }
400
+ catch (error) {
401
+ for (const move of moves.reverse()) {
402
+ await fs.mkdir(path.dirname(move.sourcePath), { recursive: true }).catch(() => undefined);
403
+ await fs.rename(move.destinationPath, move.sourcePath).catch(() => undefined);
404
+ if (move.backupPath) {
405
+ await fs.mkdir(path.dirname(move.destinationPath), { recursive: true }).catch(() => undefined);
406
+ await fs.rename(move.backupPath, move.destinationPath).catch(() => undefined);
407
+ }
408
+ }
409
+ await fs.rm(backupRoot, { recursive: true, force: true }).catch(() => undefined);
410
+ throw error;
411
+ }
412
+ }
413
+ async function overlayEntry(input) {
414
+ const sourceStat = await fs.lstat(input.sourcePath);
415
+ const destinationStat = await fs.lstat(input.destinationPath).catch(() => null);
416
+ if (sourceStat.isDirectory() &&
417
+ !sourceStat.isSymbolicLink() &&
418
+ destinationStat?.isDirectory() &&
419
+ !destinationStat.isSymbolicLink()) {
420
+ const entries = await fs.readdir(input.sourcePath, { withFileTypes: true });
421
+ for (const entry of entries) {
422
+ await overlayEntry({
423
+ sourcePath: path.join(input.sourcePath, entry.name),
424
+ destinationPath: path.join(input.destinationPath, entry.name),
425
+ backupPath: path.join(input.backupPath, entry.name),
426
+ moves: input.moves,
427
+ });
428
+ }
429
+ return;
430
+ }
431
+ let preservedBasePath;
432
+ if (destinationStat) {
433
+ await fs.mkdir(path.dirname(input.backupPath), { recursive: true });
434
+ await fs.rename(input.destinationPath, input.backupPath);
435
+ preservedBasePath = input.backupPath;
436
+ }
437
+ else {
438
+ await fs.mkdir(path.dirname(input.destinationPath), { recursive: true });
439
+ }
440
+ try {
441
+ await fs.rename(input.sourcePath, input.destinationPath);
442
+ }
443
+ catch (error) {
444
+ if (preservedBasePath) {
445
+ await fs.rename(preservedBasePath, input.destinationPath).catch(() => undefined);
446
+ }
447
+ throw error;
448
+ }
449
+ input.moves.push({
450
+ sourcePath: input.sourcePath,
451
+ destinationPath: input.destinationPath,
452
+ backupPath: preservedBasePath,
453
+ });
454
+ }
292
455
  function qaReworkPacketFileName(packetPath) {
293
456
  const normalized = packetPath.trim().replace(/\\/g, "/");
294
457
  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,10 @@ 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 preserveExistingState?: boolean;
17
19
  }
18
20
  export interface WorktreeHandle {
19
21
  readonly repoPath: string;
@@ -23,4 +25,5 @@ export interface WorktreeHandle {
23
25
  readonly cleanupWorktrees: boolean;
24
26
  readonly dependencyWarm?: WarmDependenciesResult;
25
27
  readonly qaReworkPacketPath?: string;
28
+ readonly hydratedPriorPhaseArtifactCount?: number;
26
29
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@loucompanion/forge-bridge",
3
- "version": "0.1.3-dev.0bd9fb991b79",
3
+ "version": "0.1.3-dev.0d26c10244e1",
4
4
  "description": "Forge runner bridge CLI for connecting local developer machines to Forge dispatch.",
5
5
  "license": "UNLICENSED",
6
6
  "type": "module",
@@ -19,6 +19,7 @@
19
19
  },
20
20
  "files": [
21
21
  "dist",
22
+ "runtime",
22
23
  "README.md"
23
24
  ],
24
25
  "repository": {
@@ -41,7 +42,7 @@
41
42
  "test": "vitest run",
42
43
  "test:watch": "vitest",
43
44
  "smoke:package": "npm run build && node scripts/smoke-package.mjs",
44
- "lint": "eslint \"src/**/*.ts\" \"scripts/**/*.mjs\" \"vitest.config.ts\""
45
+ "lint": "eslint \"src/**/*.ts\" \"scripts/**/*.mjs\" \"vitest.config.ts\" \"vitest.setup.ts\""
45
46
  },
46
47
  "dependencies": {
47
48
  "@microsoft/signalr": "^8.0.17",