@loucompanion/forge-bridge 0.1.4-dev.f22f5e3d01fe → 0.2.1-dev.0fedbc5c9ef7

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 (182) hide show
  1. package/README.md +89 -1
  2. package/dist/bridge/bridge-chat-giphy-look.d.ts +48 -0
  3. package/dist/bridge/bridge-chat-giphy-look.js +55 -0
  4. package/dist/bridge/bridge-chat-provider-command.d.ts +27 -3
  5. package/dist/bridge/bridge-chat-provider-command.js +131 -26
  6. package/dist/bridge/bridge-chat.types.d.ts +20 -0
  7. package/dist/bridge/bridge-chat.types.js +28 -1
  8. package/dist/bridge/bridge-state-file.d.ts +161 -0
  9. package/dist/bridge/bridge-state-file.js +376 -0
  10. package/dist/bridge/bridge-state-io.d.ts +11 -0
  11. package/dist/bridge/bridge-state-io.js +50 -0
  12. package/dist/bridge/bridge-state-lock.d.ts +11 -0
  13. package/dist/bridge/bridge-state-lock.js +102 -0
  14. package/dist/bridge/bridge-state-unpublished.d.ts +17 -0
  15. package/dist/bridge/bridge-state-unpublished.js +111 -0
  16. package/dist/bridge/bridge.service.d.ts +19 -12
  17. package/dist/bridge/bridge.service.js +155 -282
  18. package/dist/bridge/bridge.types.d.ts +5 -0
  19. package/dist/bridge/in-flight-registry.d.ts +62 -0
  20. package/dist/bridge/in-flight-registry.js +207 -0
  21. package/dist/bridge/readiness-result-outbox.d.ts +5 -1
  22. package/dist/bridge/readiness-result-outbox.js +20 -0
  23. package/dist/bridge/runner-host-capabilities.js +14 -1
  24. package/dist/bridge/sandbox-resource-accounting.d.ts +16 -0
  25. package/dist/bridge/sandbox-resource-accounting.js +150 -0
  26. package/dist/bridge/windows-bash-resolution.d.ts +31 -0
  27. package/dist/bridge/windows-bash-resolution.js +153 -0
  28. package/dist/cleanup/cleanup-wip.d.ts +12 -0
  29. package/dist/cleanup/cleanup-wip.js +66 -0
  30. package/dist/cleanup/cleanup.service.d.ts +11 -1
  31. package/dist/cleanup/cleanup.service.js +80 -62
  32. package/dist/cleanup/cleanup.types.d.ts +2 -0
  33. package/dist/cleanup/host-runtime-ledger.d.ts +2 -0
  34. package/dist/cleanup/host-runtime-ledger.js +30 -9
  35. package/dist/cli/cli.help.js +56 -12
  36. package/dist/cli/cli.service.d.ts +3 -10
  37. package/dist/cli/cli.service.js +10 -171
  38. package/dist/cli/idle-status.d.ts +84 -0
  39. package/dist/cli/idle-status.js +181 -0
  40. package/dist/cli/local-config.d.ts +2 -0
  41. package/dist/cli/local-config.js +7 -1
  42. package/dist/cli/provider-cli-detection.d.ts +10 -0
  43. package/dist/cli/provider-cli-detection.js +160 -0
  44. package/dist/runtime/aspnet-runtime-prebuild.d.ts +20 -0
  45. package/dist/runtime/aspnet-runtime-prebuild.js +104 -26
  46. package/dist/runtime/attempt-database-broker.d.ts +1 -1
  47. package/dist/runtime/attempt-node-runtime-launcher.d.ts +36 -0
  48. package/dist/runtime/attempt-node-runtime-launcher.js +169 -0
  49. package/dist/runtime/attempt-process-supervisor.d.ts +2 -0
  50. package/dist/runtime/attempt-process-supervisor.js +12 -6
  51. package/dist/runtime/docker-engine-probe.d.ts +5 -0
  52. package/dist/runtime/docker-engine-probe.js +7 -0
  53. package/dist/runtime/dotnet-build-outputs.d.ts +107 -0
  54. package/dist/runtime/dotnet-build-outputs.js +402 -0
  55. package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
  56. package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
  57. package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
  58. package/dist/runtime/ephemeral-test-postgres.js +303 -0
  59. package/dist/runtime/host-listener-inspector.d.ts +26 -0
  60. package/dist/runtime/host-listener-inspector.js +84 -3
  61. package/dist/runtime/host-load-admission.d.ts +5 -0
  62. package/dist/runtime/host-load-governor-config.d.ts +10 -1
  63. package/dist/runtime/host-load-governor-config.js +4 -1
  64. package/dist/runtime/host-load-governor.d.ts +10 -1
  65. package/dist/runtime/host-load-governor.js +33 -3
  66. package/dist/runtime/host-load-ledger-lock.js +6 -4
  67. package/dist/runtime/host-load-runtime-settings.js +4 -2
  68. package/dist/runtime/host-load-sampler.d.ts +8 -1
  69. package/dist/runtime/host-load-sampler.js +14 -7
  70. package/dist/runtime/host-load-test-slot.js +7 -0
  71. package/dist/runtime/host-runtime-contract.d.ts +12 -0
  72. package/dist/runtime/host-runtime-contract.js +29 -1
  73. package/dist/runtime/host-runtime-lease.d.ts +28 -3
  74. package/dist/runtime/host-runtime-lease.js +140 -296
  75. package/dist/runtime/host-runtime-ledger-recovery.d.ts +20 -0
  76. package/dist/runtime/host-runtime-ledger-recovery.js +134 -0
  77. package/dist/runtime/host-runtime-promotion.d.ts +78 -2
  78. package/dist/runtime/host-runtime-promotion.js +307 -14
  79. package/dist/runtime/managed-command-teardown.js +5 -16
  80. package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
  81. package/dist/runtime/native-test-postgres-fallback.js +60 -8
  82. package/dist/runtime/prepared-runtime-identity.d.ts +4 -0
  83. package/dist/runtime/prepared-runtime-identity.js +130 -9
  84. package/dist/runtime/prepared-runtime-readiness.d.ts +13 -1
  85. package/dist/runtime/prepared-runtime-readiness.js +63 -16
  86. package/dist/runtime/runner-settings.d.ts +4 -0
  87. package/dist/runtime/runner-settings.js +22 -0
  88. package/dist/runtime/supervised-runtime-build-guard.d.ts +45 -0
  89. package/dist/runtime/supervised-runtime-build-guard.js +112 -0
  90. package/dist/sandbox/host-capacity-broker.d.ts +3 -1
  91. package/dist/sandbox/host-capacity-broker.js +4 -2
  92. package/dist/sandbox/managed-branch.d.ts +13 -0
  93. package/dist/sandbox/managed-branch.js +90 -0
  94. package/dist/sandbox/provider-auth/codex.js +11 -11
  95. package/dist/sandbox/runtime.js +3 -7
  96. package/dist/session/managed-attempt-tools.d.ts +0 -7
  97. package/dist/session/managed-attempt-tools.js +50 -82
  98. package/dist/session/managed-build-coordinator.d.ts +16 -0
  99. package/dist/session/managed-build-coordinator.js +10 -0
  100. package/dist/session/managed-build-receipt.d.ts +5 -0
  101. package/dist/session/managed-build-receipt.js +8 -3
  102. package/dist/session/phase-completion.artifacts.js +2 -1
  103. package/dist/session/phase-completion.d.ts +8 -0
  104. package/dist/session/phase-completion.js +1 -0
  105. package/dist/session/phase-completion.mcp-args.d.ts +9 -0
  106. package/dist/session/phase-completion.mcp-args.js +156 -0
  107. package/dist/session/phase-completion.runtime.d.ts +0 -8
  108. package/dist/session/phase-completion.runtime.js +43 -197
  109. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  110. package/dist/session/pre-publication-native-postgres.js +111 -0
  111. package/dist/session/pre-publication-process.js +10 -10
  112. package/dist/session/pre-publication-step-execution.d.ts +2 -1
  113. package/dist/session/pre-publication-step-execution.js +6 -5
  114. package/dist/session/pre-publication-validation.d.ts +7 -3
  115. package/dist/session/pre-publication-validation.js +32 -30
  116. package/dist/session/provider-cli/claude-background-work.d.ts +3 -2
  117. package/dist/session/provider-cli/claude-background-work.js +4 -3
  118. package/dist/session/provider-cli/host-build-lock.d.ts +18 -0
  119. package/dist/session/provider-cli/host-build-lock.js +30 -0
  120. package/dist/session/provider-cli/pre-publication-repair.d.ts +16 -0
  121. package/dist/session/provider-cli/pre-publication-repair.js +33 -0
  122. package/dist/session/provider-cli/provider-cli.child-environment.js +4 -2
  123. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +6 -3
  124. package/dist/session/provider-cli/provider-cli.merge-integrity.js +28 -8
  125. package/dist/session/provider-cli/provider-cli.process.d.ts +2 -14
  126. package/dist/session/provider-cli/provider-cli.process.js +4 -94
  127. package/dist/session/provider-cli/provider-cli.prompts.d.ts +3 -0
  128. package/dist/session/provider-cli/provider-cli.prompts.js +27 -27
  129. package/dist/session/provider-cli/provider-cli.runtime.d.ts +8 -0
  130. package/dist/session/provider-cli/provider-cli.runtime.js +23 -2
  131. package/dist/session/provider-cli/provider-cli.service.d.ts +4 -1
  132. package/dist/session/provider-cli/provider-cli.service.js +27 -43
  133. package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
  134. package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
  135. package/dist/session/provider-cli/provider-user-config-isolation.d.ts +69 -0
  136. package/dist/session/provider-cli/provider-user-config-isolation.js +164 -0
  137. package/dist/session/qa-sidecar-validation.d.ts +6 -0
  138. package/dist/session/qa-sidecar-validation.js +28 -0
  139. package/dist/session/sandbox-host-capacity-gate.d.ts +22 -1
  140. package/dist/session/sandbox-host-capacity-gate.js +35 -16
  141. package/dist/session/session-redaction.js +31 -181
  142. package/dist/session/session.service.d.ts +6 -0
  143. package/dist/session/session.service.js +131 -88
  144. package/dist/session/session.types.d.ts +1 -0
  145. package/dist/session/session.types.js +3 -3
  146. package/dist/session/sidecar-json-shape.d.ts +31 -0
  147. package/dist/session/sidecar-json-shape.js +217 -0
  148. package/dist/shared/fs/file-identity.d.ts +10 -0
  149. package/dist/shared/fs/file-identity.js +15 -0
  150. package/dist/shared/fs/replace-file.d.ts +7 -0
  151. package/dist/shared/fs/replace-file.js +33 -0
  152. package/dist/shared/process/host-process-recovery.d.ts +14 -3
  153. package/dist/shared/process/host-process-recovery.js +23 -3
  154. package/dist/shared/process/host-process-supervisor.d.ts +13 -1
  155. package/dist/shared/process/host-process-supervisor.js +66 -14
  156. package/dist/shared/provider-capabilities.js +9 -1
  157. package/dist/version.d.ts +1 -1
  158. package/dist/version.js +1 -1
  159. package/dist/worktree/orphan-relink.d.ts +19 -0
  160. package/dist/worktree/orphan-relink.js +106 -0
  161. package/dist/worktree/wip-git.d.ts +42 -0
  162. package/dist/worktree/wip-git.js +139 -0
  163. package/dist/worktree/wip-refs.d.ts +77 -0
  164. package/dist/worktree/wip-refs.js +146 -0
  165. package/dist/worktree/wip-restore.d.ts +46 -0
  166. package/dist/worktree/wip-restore.js +280 -0
  167. package/dist/worktree/wip-snapshot.d.ts +53 -0
  168. package/dist/worktree/wip-snapshot.js +270 -0
  169. package/dist/worktree/worktree-inputs.d.ts +8 -0
  170. package/dist/worktree/worktree-inputs.js +134 -0
  171. package/dist/worktree/worktree-origin-sync.d.ts +35 -0
  172. package/dist/worktree/worktree-origin-sync.js +128 -0
  173. package/dist/worktree/worktree-wip-events.d.ts +18 -0
  174. package/dist/worktree/worktree-wip-events.js +115 -0
  175. package/dist/worktree/worktree-wip.d.ts +51 -0
  176. package/dist/worktree/worktree-wip.js +190 -0
  177. package/dist/worktree/worktree.base.d.ts +7 -1
  178. package/dist/worktree/worktree.service.d.ts +27 -5
  179. package/dist/worktree/worktree.service.js +112 -181
  180. package/dist/worktree/worktree.types.d.ts +35 -0
  181. package/package.json +1 -1
  182. package/runtime/windows-listener-owner.ps1 +12 -1
@@ -3,14 +3,15 @@ import fs from "node:fs/promises";
3
3
  import path from "node:path";
4
4
  import { RepositoryCoordinatorLock } from "../sandbox/repository-lock.js";
5
5
  import { GitClient } from "../shared/git/git.js";
6
- import { liveLeaseBranches, readHostRuntimeLeases } from "../cleanup/host-runtime-ledger.js";
7
- import { deleteBranchIfUnused, isRuntimeReadinessBranch, sweepManagedBranches } from "../cleanup/managed-branch-sweep.js";
8
6
  import { ensureDirectory, isSubPath, resolveExistingDirectoryPath, safeSegment } from "../shared/path/path.js";
9
- import { filterArtifactsForLane, injectWorktreeArtifacts } from "./artifact-injector.js";
10
- import { hydratePriorPhaseArtifacts } from "./prior-phase-artifact-hydrator.js";
11
- import { materializeStoryQaReferences } from "./story-qa-reference-hydrator.js";
12
7
  import { warmWorktreeDependencies } from "./dependency-warmer.js";
8
+ import { materializeWorktreeInputs } from "./worktree-inputs.js";
9
+ import { guardBranchReset, guardWorktreeRelease, guardWorktreeReset, relinkOrphanedWorktree, restoreWorktreeWip, settleSessionWip, sweepBranchesAfterRelease, worktreeReleased, } from "./worktree-wip.js";
13
10
  import { defaultWorktreeCoordinatorStateRoot, managedRepoRoot, resolveManagedWorktreeRoot, } from "./worktree-paths.js";
11
+ import { describeNewWorktreeStart, refuseStaleFallbackAfterFetchFailure, syncReusedWorktreeToOrigin, writeBridgeLog, } from "./worktree-origin-sync.js";
12
+ export { emitWipRestoreEvent, sessionWipOutcome, settleWorktree } from "./worktree-wip-events.js";
13
+ export { emitWorktreePreparedEvents } from "./worktree-origin-sync.js";
14
+ export { clearRunArtifactRoots } from "./worktree-inputs.js";
14
15
  // Bounds the branch sweep that runs after each release, so one release never holds the repository lock long.
15
16
  const releaseSweepLimit = 25;
16
17
  export class GitWorktreeService {
@@ -18,15 +19,19 @@ export class GitWorktreeService {
18
19
  coordinator;
19
20
  hostLoadGate;
20
21
  leaseStateRoot;
22
+ log;
21
23
  constructor(git = new GitClient(), coordinator = new RepositoryCoordinatorLock(defaultWorktreeCoordinatorStateRoot()),
22
24
  /** Gates dependency install fallbacks; inert unless the governor is on. */
23
25
  hostLoadGate,
24
26
  /** Holds the host runtime lease ledger; branches of live leases are never swept on release. */
25
- leaseStateRoot = defaultWorktreeCoordinatorStateRoot()) {
27
+ leaseStateRoot = defaultWorktreeCoordinatorStateRoot(),
28
+ /** The bridge log: prepare records its start point and what it did to a reused worktree. */
29
+ log = writeBridgeLog) {
26
30
  this.git = git;
27
31
  this.coordinator = coordinator;
28
32
  this.hostLoadGate = hostLoadGate;
29
33
  this.leaseStateRoot = leaseStateRoot;
34
+ this.log = log;
30
35
  }
31
36
  async prepare(request) {
32
37
  const allowedRoot = await ensureDirectory(request.allowedRepoRoot);
@@ -41,9 +46,9 @@ export class GitWorktreeService {
41
46
  const repoPath = await this.coordinator.withLock(creationCoordinationPath, async () => {
42
47
  return await this.resolveRepoPath(request.repo, allowedRoot, baseBranch);
43
48
  });
44
- const resolvedWorktreePath = await this.coordinator.withLock(repoPath, async () => {
49
+ const { worktreePath: resolvedWorktreePath, ...preparedState } = await this.coordinator.withLock(repoPath, async () => {
45
50
  await this.ensureGitIdentity(repoPath);
46
- const baseStartPoint = await this.resolveBaseStartPoint(repoPath, baseBranch);
51
+ const baseStartPoint = await this.resolveBaseStartPoint(repoPath, baseBranch, branchName);
47
52
  const worktreeRoot = resolveManagedWorktreeRoot(allowedRoot, repoPath);
48
53
  const worktreePath = path.join(worktreeRoot, ...worktreeSegments);
49
54
  const resolvedWorktreeParent = await ensureDirectory(path.dirname(worktreePath));
@@ -58,17 +63,8 @@ export class GitWorktreeService {
58
63
  await this.git.run(repoPath, ["worktree", "prune", "--expire", "now"]);
59
64
  const registeredWorktreePath = await this.registeredManagedWorktreePath(repoPath, branchName, allowedRoot, worktreeSegments);
60
65
  if (!registeredWorktreePath) {
61
- const branchRef = `refs/heads/${branchName}`;
62
- if (request.preserveExistingState && await this.gitRefExists(repoPath, branchRef)) {
63
- // The checkout directory can disappear while its branch still
64
- // contains completed agent work. Reattach that branch verbatim;
65
- // `-B ... baseStartPoint` would silently reset it and lose progress.
66
- await this.git.run(repoPath, ["worktree", "add", worktreePath, branchName]);
67
- }
68
- else {
69
- await this.git.run(repoPath, ["worktree", "add", "-B", branchName, worktreePath, baseStartPoint]);
70
- }
71
- return await resolveExistingDirectoryPath(worktreePath);
66
+ const originSync = await this.addWorktree(request, repoPath, branchName, worktreePath, baseStartPoint);
67
+ return await this.withRestoredWip(request, repoPath, branchName, await resolveExistingDirectoryPath(worktreePath), originSync);
72
68
  }
73
69
  // The selected checkout can change when a Bridge reconnects or a local
74
70
  // runner takes over. Its managed root therefore changes even though the
@@ -93,38 +89,11 @@ export class GitWorktreeService {
93
89
  if (currentBranch !== branchName) {
94
90
  throw new Error(`Existing worktree ${existingWorktreePath} is on branch '${currentBranch}', expected '${branchName}'.`);
95
91
  }
96
- if (!request.preserveExistingState && shouldResetExistingWorktree(request)) {
97
- await this.resetWorktreeToBase(existingWorktreePath, baseStartPoint);
98
- }
99
- return existingWorktreePath;
92
+ const originSync = await this.refreshReusedWorktree(request, existingWorktreePath, branchName, baseStartPoint);
93
+ return await this.withRestoredWip(request, repoPath, branchName, existingWorktreePath, originSync);
100
94
  });
101
- // Reference inputs and an exact-tree local repair checkpoint must survive output cleanup.
102
- await materializeStoryQaReferences(resolvedWorktreePath, request, this.git);
103
- if (!request.preserveExistingState) {
104
- await clearRunArtifactRoots(resolvedWorktreePath, request);
105
- }
106
- const hydratedPriorPhaseArtifactCount = await hydratePriorPhaseArtifacts(resolvedWorktreePath, request.priorPhaseArtifacts);
107
- const qaReworkPacketPath = await materializeQaReworkPacket(resolvedWorktreePath, request);
108
- const artifacts = filterArtifactsForLane(request.artifacts, request.lane, request.phase);
109
- if (artifacts.length > 0) {
110
- await injectWorktreeArtifacts(resolvedWorktreePath, artifacts, await this.trackedForgePaths(resolvedWorktreePath));
111
- }
112
- const dependencyWarm = requiresMutableEnvironmentPreparation(request)
113
- ? await warmWorktreeDependencies({
114
- baseCheckoutPath: repoPath,
115
- worktreePath: resolvedWorktreePath,
116
- allowedRoot,
117
- warmPathOverrides: request.warmPathOverrides,
118
- hostLoad: this.hostLoadGate?.enabled
119
- ? {
120
- gate: this.hostLoadGate,
121
- dispatchAttemptId: request.hostLoadOwner?.dispatchAttemptId ?? null,
122
- priority: request.hostLoadOwner?.priority ?? "foreground",
123
- }
124
- : undefined,
125
- signal: request.signal,
126
- })
127
- : undefined;
95
+ const { hydratedPriorPhaseArtifactCount, qaReworkPacketPath } = await materializeWorktreeInputs(resolvedWorktreePath, request, this.git);
96
+ const dependencyWarm = await this.warmDependencies(request, repoPath, resolvedWorktreePath, allowedRoot);
128
97
  return {
129
98
  repoPath,
130
99
  worktreePath: resolvedWorktreePath,
@@ -133,12 +102,79 @@ export class GitWorktreeService {
133
102
  cleanupWorktrees: request.cleanupWorktrees,
134
103
  dependencyWarm,
135
104
  qaReworkPacketPath,
136
- hydratedPriorPhaseArtifactCount
105
+ hydratedPriorPhaseArtifactCount,
106
+ sessionId: request.sessionId ?? null,
107
+ lane: request.lane,
108
+ wipAttempt: request.wipAttempt ?? null,
109
+ ...preparedState,
137
110
  };
138
111
  }
139
- async trackedForgePaths(worktreePath) {
140
- const output = await this.git.run(worktreePath, ["ls-files", "-z", "--", ".forge"]);
141
- return new Set(output.split("\0").filter(Boolean).map(value => value.replaceAll("\\", "/")));
112
+ async warmDependencies(request, repoPath, worktreePath, allowedRoot) {
113
+ if (!requiresMutableEnvironmentPreparation(request))
114
+ return undefined;
115
+ return await warmWorktreeDependencies({
116
+ baseCheckoutPath: repoPath,
117
+ worktreePath,
118
+ allowedRoot,
119
+ warmPathOverrides: request.warmPathOverrides,
120
+ hostLoad: this.hostLoadGate?.enabled
121
+ ? {
122
+ gate: this.hostLoadGate,
123
+ dispatchAttemptId: request.hostLoadOwner?.dispatchAttemptId ?? null,
124
+ priority: request.hostLoadOwner?.priority ?? "foreground",
125
+ }
126
+ : undefined,
127
+ signal: request.signal,
128
+ });
129
+ }
130
+ /** Restores the story's saved WIP (still under the repository lock, before the provider starts). */
131
+ async withRestoredWip(request, repoPath, branchName, worktreePath, originSync) {
132
+ const wipRestore = await restoreWorktreeWip({ worktreePath, repoPath, branchName, sessionId: request.sessionId, lane: request.lane });
133
+ return { worktreePath, ...(wipRestore ? { wipRestore } : {}), ...(originSync ? { originSync } : {}) };
134
+ }
135
+ /** Creates the lease's worktree; see describeNewWorktreeStart for what it reports. */
136
+ async addWorktree(request, repoPath, branchName, worktreePath, baseStartPoint) {
137
+ if (request.preserveExistingState && await this.gitRefExists(repoPath, `refs/heads/${branchName}`)) {
138
+ // The checkout directory can disappear while its branch still
139
+ // contains completed agent work. Reattach that branch verbatim;
140
+ // `-B ... baseStartPoint` would silently reset it and lose progress.
141
+ this.log(`Worktree prepare: reattaching '${branchName}' verbatim at ${worktreePath} for a resumed session.`);
142
+ await this.git.run(repoPath, ["worktree", "add", worktreePath, branchName]);
143
+ return undefined;
144
+ }
145
+ const originSync = await describeNewWorktreeStart(this.git, repoPath, branchName, baseStartPoint, this.log);
146
+ await guardBranchReset(this.git, repoPath, branchName, baseStartPoint);
147
+ await this.git.run(repoPath, ["worktree", "add", "-B", branchName, worktreePath, baseStartPoint]);
148
+ return originSync;
149
+ }
150
+ /**
151
+ * Readies a surviving worktree for this pass: lanes that start from their base are reset to it;
152
+ * the others keep their state but are brought up to origin's head when only behind it
153
+ * (worktree-origin-sync.ts). A resumed session keeps its worktree exactly as it was.
154
+ */
155
+ async refreshReusedWorktree(request, worktreePath, branchName, baseStartPoint) {
156
+ if (request.preserveExistingState) {
157
+ this.log(`Worktree prepare: reattaching ${worktreePath} on '${branchName}' unchanged for a resumed session.`);
158
+ return undefined;
159
+ }
160
+ if (shouldResetExistingWorktree(request)) {
161
+ await guardWorktreeReset(worktreePath, branchName, request);
162
+ await this.resetWorktreeToBase(worktreePath, baseStartPoint);
163
+ this.log(`Worktree prepare: reset reused worktree ${worktreePath} on '${branchName}' to ${baseStartPoint}.`);
164
+ return undefined;
165
+ }
166
+ return await syncReusedWorktreeToOrigin({
167
+ git: this.git,
168
+ worktreePath,
169
+ branchName,
170
+ sessionId: request.sessionId,
171
+ lane: request.lane,
172
+ wipAttempt: request.wipAttempt,
173
+ log: this.log,
174
+ });
175
+ }
176
+ async settleWip(handle, outcome) {
177
+ return await settleSessionWip(handle, outcome);
142
178
  }
143
179
  async registeredManagedWorktreePath(repoPath, branchName, allowedRoot, worktreeSegments) {
144
180
  const listing = await this.git.run(repoPath, ["worktree", "list", "--porcelain", "-z"]);
@@ -165,6 +201,8 @@ export class GitWorktreeService {
165
201
  }
166
202
  await this.coordinator.withLock(handle.repoPath, async () => {
167
203
  if (await directoryExists(handle.worktreePath)) {
204
+ // Never delete work that could not be saved: this throws and keeps the worktree.
205
+ await guardWorktreeRelease(handle);
168
206
  // On Windows, `git worktree remove` can delete the `.git` link and then
169
207
  // fail on a locked build output. That leaves a full source tree which is
170
208
  // no longer a Git worktree and makes every retry fail during prepare.
@@ -184,26 +222,12 @@ export class GitWorktreeService {
184
222
  // directory is fully materialized (or after an external cleanup removes it).
185
223
  // Always prune so those missing-directory registrations do not accumulate.
186
224
  await this.git.run(handle.repoPath, ["worktree", "prune", "--expire", "now"]).catch(() => undefined);
225
+ worktreeReleased(handle);
187
226
  // A readiness probe's branch goes with its worktree. Other Forge branches on this device
188
227
  // whose work is already merged into the base go too; branches with unmerged work stay.
189
228
  // A lease can be live while its worktree is briefly missing, so its branch is protected
190
229
  // even when no worktree has it checked out. If the ledger can't be read, sweep nothing.
191
- const protectedBranches = await readHostRuntimeLeases(this.leaseStateRoot)
192
- .then(liveLeaseBranches)
193
- .catch(() => null);
194
- if (!protectedBranches)
195
- return;
196
- let budget = releaseSweepLimit;
197
- if (isRuntimeReadinessBranch(handle.branchName) && !protectedBranches.has(handle.branchName)
198
- && await deleteBranchIfUnused(this.git, handle.repoPath, handle.branchName)) {
199
- budget -= 1;
200
- }
201
- await sweepManagedBranches(this.git, handle.repoPath, {
202
- baseBranch: handle.baseBranch,
203
- includeMergedWorkBranches: true,
204
- protectedBranches,
205
- limit: budget,
206
- }).catch(() => undefined);
230
+ await sweepBranchesAfterRelease(this.git, handle, this.leaseStateRoot, releaseSweepLimit);
207
231
  });
208
232
  }
209
233
  async restoreOrphanedWorktree(input) {
@@ -211,10 +235,15 @@ export class GitWorktreeService {
211
235
  if (orphanStat.isSymbolicLink() || !orphanStat.isDirectory()) {
212
236
  throw new Error(`Refusing to recover redirected or non-directory worktree ${input.worktreePath}.`);
213
237
  }
238
+ // Git still has this checkout's admin directory (its index and MERGE_HEAD): point the checkout
239
+ // back at it rather than recreating the checkout, which would prune it.
240
+ if (await relinkOrphanedWorktree(this.git, input))
241
+ return;
214
242
  const quarantinePath = `${input.worktreePath}.forge-orphan-${randomUUID()}`;
215
243
  if (!isSubPath(input.allowedRoot, quarantinePath)) {
216
244
  throw new Error(`Worktree recovery path must stay under ${input.allowedRoot}.`);
217
245
  }
246
+ await guardBranchReset(this.git, input.repoPath, input.branchName, input.baseStartPoint);
218
247
  await fs.rename(input.worktreePath, quarantinePath);
219
248
  try {
220
249
  await this.git.run(input.repoPath, ["worktree", "prune", "--expire", "now"]);
@@ -325,7 +354,12 @@ export class GitWorktreeService {
325
354
  const resolved = await resolveExistingDirectoryPath(candidate);
326
355
  return isSubPath(allowedRoot, resolved) ? resolved : null;
327
356
  }
328
- async resolveBaseStartPoint(repoPath, baseBranch) {
357
+ /**
358
+ * The start point for the lease's base: origin's freshly fetched head when origin has the
359
+ * branch, else the local branch. When the fetch fails, the local branch is used only if origin
360
+ * has never had the base or the lease branch: otherwise the worktree could run on stale code.
361
+ */
362
+ async resolveBaseStartPoint(repoPath, baseBranch, branchName) {
329
363
  if (baseBranch === "HEAD") {
330
364
  const head = (await this.git.run(repoPath, ["rev-parse", "--verify", "HEAD^{commit}"])).trim();
331
365
  if (!/^[0-9a-f]{40,64}$/iu.test(head)) {
@@ -337,14 +371,17 @@ export class GitWorktreeService {
337
371
  const remoteRef = `refs/remotes/origin/${baseBranch}`;
338
372
  const origin = await this.git.run(repoPath, ["remote", "get-url", "origin"]).catch(() => "");
339
373
  if (origin.trim().length > 0) {
340
- const fetched = await this.git.run(repoPath, ["fetch", "--prune", "origin"])
341
- .then(() => true)
342
- .catch(() => false);
343
- if (fetched && await this.gitRefExists(repoPath, remoteRef)) {
374
+ const fetchError = await this.git.run(repoPath, ["fetch", "--prune", "origin"]).then(() => null, (error) => error ?? "fetch failed");
375
+ if (fetchError) {
376
+ await refuseStaleFallbackAfterFetchFailure(this.git, repoPath, [baseBranch, branchName], fetchError, this.log);
377
+ }
378
+ else if (await this.gitRefExists(repoPath, remoteRef)) {
379
+ this.log(`Worktree prepare: fetched origin in ${repoPath}; '${baseBranch}' starts from ${remoteRef}.`);
344
380
  return remoteRef;
345
381
  }
346
382
  }
347
383
  if (await this.gitRefExists(repoPath, localRef)) {
384
+ this.log(`Worktree prepare: '${baseBranch}' starts from the local ${localRef} in ${repoPath} (origin has no such branch).`);
348
385
  return localRef;
349
386
  }
350
387
  throw new Error(`Base branch '${baseBranch}' was not found locally or on origin.`);
@@ -397,72 +434,6 @@ function isCloneableRemote(remoteUrl) {
397
434
  }
398
435
  return trimmed.startsWith("git@") || trimmed.includes("://") || path.isAbsolute(trimmed);
399
436
  }
400
- export async function clearRunArtifactRoots(worktreePath, request) {
401
- const roots = new Set();
402
- roots.add(workItemArtifactRoot(worktreePath, request.workItem.id));
403
- for (const artifact of request.priorPhaseArtifacts ?? []) {
404
- roots.add(workItemArtifactRoot(worktreePath, artifact.workItemId));
405
- }
406
- const ownerType = normalizeOwnerType(request.ownerType);
407
- const ownerId = request.ownerId?.trim();
408
- if (ownerType && ownerId) {
409
- roots.add(ownerArtifactRoot(worktreePath, ownerType, ownerId));
410
- }
411
- for (const root of roots) {
412
- const resolvedRoot = path.resolve(root);
413
- if (!isSubPath(worktreePath, resolvedRoot)) {
414
- throw new Error(`Artifact root must stay under ${worktreePath}.`);
415
- }
416
- await ensureNoSymlinkPathSegments(worktreePath, resolvedRoot, "Artifact root must not traverse symlinked path segments.");
417
- await fs.rm(resolvedRoot, { recursive: true, force: true });
418
- await fs.mkdir(resolvedRoot, { recursive: true });
419
- }
420
- }
421
- async function materializeQaReworkPacket(worktreePath, request) {
422
- const qaRework = request.qaRework;
423
- if (!qaRework) {
424
- return undefined;
425
- }
426
- const artifactRoot = artifactRootForRequest(worktreePath, request);
427
- const packetFileName = qaReworkPacketFileName(qaRework.packetPath);
428
- const packetPath = path.join(artifactRoot, packetFileName);
429
- const paths = new Set([packetPath, path.join(artifactRoot, "qa-rework-packet.json")]);
430
- const packetJson = qaRework.packetJson.endsWith("\n") ? qaRework.packetJson : `${qaRework.packetJson}\n`;
431
- for (const target of paths) {
432
- const resolvedTarget = path.resolve(target);
433
- if (!isSubPath(worktreePath, resolvedTarget)) {
434
- throw new Error(`QA rework packet path must stay under ${worktreePath}.`);
435
- }
436
- await ensureNoSymlinkPathSegments(worktreePath, path.dirname(resolvedTarget), "QA rework packet path must not traverse symlinked path segments.");
437
- await fs.mkdir(path.dirname(resolvedTarget), { recursive: true });
438
- await fs.writeFile(resolvedTarget, packetJson, "utf8");
439
- }
440
- return path.resolve(packetPath);
441
- }
442
- function artifactRootForRequest(worktreePath, request) {
443
- const ownerType = normalizeOwnerType(request.ownerType);
444
- const ownerId = request.ownerId?.trim();
445
- if (ownerType && ownerId) {
446
- return ownerArtifactRoot(worktreePath, ownerType, ownerId);
447
- }
448
- return workItemArtifactRoot(worktreePath, request.workItem.id);
449
- }
450
- function workItemArtifactRoot(worktreePath, workItemId) {
451
- return path.join(worktreePath, ".forge", "work-items", safeSegment(workItemId, "work item id"), "artifacts");
452
- }
453
- function ownerArtifactRoot(worktreePath, ownerType, ownerId) {
454
- return path.join(worktreePath, ".forge", ownerType === "story" ? "stories" : "work-items", safeSegment(ownerId, "owner id"), "artifacts");
455
- }
456
- function normalizeOwnerType(value) {
457
- const normalized = (value ?? "").trim().toLowerCase().replace(/-/g, "_");
458
- if (normalized === "story") {
459
- return "story";
460
- }
461
- if (normalized === "work_item" || normalized === "workitem" || normalized === "work item") {
462
- return "work_item";
463
- }
464
- return null;
465
- }
466
437
  function shouldResetExistingWorktree(request) {
467
438
  const lane = request.lane.trim().toLowerCase();
468
439
  const phase = request.phase.trim().toLowerCase().replace(/-/g, "_");
@@ -589,13 +560,6 @@ async function overlayEntry(input) {
589
560
  backupPath: preservedBasePath,
590
561
  });
591
562
  }
592
- function qaReworkPacketFileName(packetPath) {
593
- const normalized = packetPath.trim().replace(/\\/g, "/");
594
- const fileName = normalized.split("/").filter(Boolean).at(-1) ?? "";
595
- return /^qa-rework-packet(?:\.attempt-\d+)?\.json$/i.test(fileName)
596
- ? fileName
597
- : "qa-rework-packet.json";
598
- }
599
563
  export function normalizeBranchName(value, fallback) {
600
564
  const branch = (value?.trim() || fallback).trim();
601
565
  if (branch.length === 0 ||
@@ -645,39 +609,6 @@ async function gitMetadataExists(repoPath, allowedRoot) {
645
609
  const resolvedGitDir = await resolveExistingDirectoryPath(gitDirPath);
646
610
  return isSubPath(allowedRoot, resolvedGitDir);
647
611
  }
648
- async function ensureNoSymlinkPathSegments(root, targetPath, errorMessage) {
649
- const resolvedRoot = path.resolve(root);
650
- const resolvedTarget = path.resolve(targetPath);
651
- const relative = path.relative(resolvedRoot, resolvedTarget);
652
- if (relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {
653
- throw new Error(errorMessage);
654
- }
655
- let current = resolvedRoot;
656
- const rootStat = await fs.lstat(current);
657
- if (rootStat.isSymbolicLink()) {
658
- throw new Error(errorMessage);
659
- }
660
- if (!relative) {
661
- return;
662
- }
663
- for (const segment of relative.split(path.sep)) {
664
- if (!segment) {
665
- continue;
666
- }
667
- current = path.join(current, segment);
668
- const stat = await fs.lstat(current).catch((error) => {
669
- if (error.code === "ENOENT")
670
- return null;
671
- throw error;
672
- });
673
- if (!stat) {
674
- return;
675
- }
676
- if (stat.isSymbolicLink()) {
677
- throw new Error(errorMessage);
678
- }
679
- }
680
- }
681
612
  async function pathExists(inputPath) {
682
613
  return fs.stat(inputPath).then(() => true).catch(() => false);
683
614
  }
@@ -1,5 +1,8 @@
1
1
  import type { DispatchQaReworkContext, DispatchPriorPhaseArtifact, DispatchRepo, DispatchWorkItem, DispatchResolvedArtifact, DispatchStoryQaContext } from "../session/session.types.js";
2
2
  import type { WarmDependenciesResult } from "./dependency-warmer.js";
3
+ import type { WipSnapshotReason } from "./wip-refs.js";
4
+ import type { WipRestoreOutcome } from "./wip-restore.js";
5
+ import type { WipSnapshotResult } from "./wip-snapshot.js";
3
6
  export interface WorktreePrepareRequest {
4
7
  readonly repo: DispatchRepo;
5
8
  readonly workItem: DispatchWorkItem;
@@ -21,6 +24,10 @@ export interface WorktreePrepareRequest {
21
24
  readonly warmPathOverrides?: readonly string[];
22
25
  readonly applicationRuntimeRequired?: boolean;
23
26
  readonly preserveExistingState?: boolean;
27
+ /** The session this worktree is prepared for; names its WIP snapshots and enables restoring one. */
28
+ readonly sessionId?: string | null;
29
+ /** Forge's issued attempt for this dispatch (sandbox.wipAttempt), stamped on its WIP refs: newest work wins. */
30
+ readonly wipAttempt?: number | null;
24
31
  /** The attempt dependency installs reserve host capacity for (decision 0013). */
25
32
  readonly hostLoadOwner?: {
26
33
  readonly dispatchAttemptId: string | null;
@@ -38,4 +45,32 @@ export interface WorktreeHandle {
38
45
  readonly dependencyWarm?: WarmDependenciesResult;
39
46
  readonly qaReworkPacketPath?: string;
40
47
  readonly hydratedPriorPhaseArtifactCount?: number;
48
+ readonly sessionId?: string | null;
49
+ readonly lane?: string;
50
+ /** Forge's issued attempt for the dispatch the worktree was prepared for; null from older servers. */
51
+ readonly wipAttempt?: number | null;
52
+ /** What happened to the story's saved WIP when this worktree was prepared. */
53
+ readonly wipRestore?: WipRestoreOutcome;
54
+ /** Set when prepare moved a stale local branch or reused worktree up to origin's head. */
55
+ readonly originSync?: OriginSync;
56
+ }
57
+ /** A move of a prepared worktree's branch from a stale local commit to origin's head. */
58
+ export interface OriginSync {
59
+ readonly from: string;
60
+ readonly to: string;
61
+ /** Where the reused worktree's uncommitted work was saved before the move; null when it had none. */
62
+ readonly wipRef: string | null;
63
+ }
64
+ /** How a session ended, for its WIP snapshot: null when it succeeded. */
65
+ export interface WipSessionOutcome {
66
+ readonly reason: WipSnapshotReason | null;
67
+ }
68
+ export interface WipSettlement {
69
+ readonly snapshot?: WipSnapshotResult;
70
+ readonly error?: {
71
+ readonly code: string;
72
+ readonly message: string;
73
+ };
74
+ /** The restored snapshot's ref, deleted because this session's work supersedes it. */
75
+ readonly retiredRef?: string | null;
41
76
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@loucompanion/forge-bridge",
3
- "version": "0.1.4-dev.f22f5e3d01fe",
3
+ "version": "0.2.1-dev.0fedbc5c9ef7",
4
4
  "description": "Forge runner bridge CLI for connecting local developer machines to Forge dispatch.",
5
5
  "license": "UNLICENSED",
6
6
  "type": "module",
@@ -7,8 +7,10 @@ param(
7
7
 
8
8
  $ErrorActionPreference = "Stop"
9
9
  $parents = @{}
10
+ $created = @{}
10
11
  Get-CimInstance Win32_Process | ForEach-Object {
11
12
  $parents[[int]$_.ProcessId] = [int]$_.ParentProcessId
13
+ $created[[int]$_.ProcessId] = $_.CreationDate
12
14
  }
13
15
 
14
16
  $results = @()
@@ -25,7 +27,16 @@ foreach ($listenerText in $ListenerProcessIds.Split(',')) {
25
27
  if (-not $parents.ContainsKey($current)) {
26
28
  break
27
29
  }
28
- $current = [int]$parents[$current]
30
+ $parent = [int]$parents[$current]
31
+ # Windows keeps a child's ParentProcessId after the parent exits, and PIDs are reused. A
32
+ # "parent" created after the child is a different process that took the dead parent's PID,
33
+ # so the chain ends here; following it could attribute a foreign listener to the root.
34
+ if ($created.ContainsKey($parent) -and $created.ContainsKey($current) `
35
+ -and $null -ne $created[$parent] -and $null -ne $created[$current] `
36
+ -and $created[$parent] -gt $created[$current]) {
37
+ break
38
+ }
39
+ $current = $parent
29
40
  }
30
41
  $results += $owned
31
42
  }