@loucompanion/forge-bridge 0.2.1-dev.4f11ffc822f9 → 0.2.1-dev.eac6976df5e9

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 (31) hide show
  1. package/dist/runtime/host-load-admission.d.ts +5 -0
  2. package/dist/runtime/host-load-governor-config.d.ts +10 -1
  3. package/dist/runtime/host-load-governor-config.js +4 -1
  4. package/dist/runtime/host-load-governor.d.ts +8 -1
  5. package/dist/runtime/host-load-governor.js +33 -3
  6. package/dist/runtime/host-load-test-slot.js +7 -0
  7. package/dist/sandbox/runtime.js +1 -1
  8. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +6 -3
  9. package/dist/session/provider-cli/provider-cli.merge-integrity.js +28 -8
  10. package/dist/session/sandbox-host-capacity-gate.js +1 -1
  11. package/dist/session/session.service.js +8 -4
  12. package/dist/session/session.types.d.ts +1 -0
  13. package/dist/session/session.types.js +2 -2
  14. package/dist/version.d.ts +1 -1
  15. package/dist/version.js +1 -1
  16. package/dist/worktree/wip-git.d.ts +9 -0
  17. package/dist/worktree/wip-git.js +21 -4
  18. package/dist/worktree/wip-refs.d.ts +15 -0
  19. package/dist/worktree/wip-refs.js +29 -2
  20. package/dist/worktree/wip-restore.d.ts +8 -0
  21. package/dist/worktree/wip-restore.js +115 -25
  22. package/dist/worktree/wip-snapshot.d.ts +5 -2
  23. package/dist/worktree/wip-snapshot.js +15 -13
  24. package/dist/worktree/worktree-origin-sync.d.ts +1 -0
  25. package/dist/worktree/worktree-origin-sync.js +1 -0
  26. package/dist/worktree/worktree-wip-events.js +19 -2
  27. package/dist/worktree/worktree-wip.d.ts +1 -0
  28. package/dist/worktree/worktree-wip.js +6 -1
  29. package/dist/worktree/worktree.service.js +2 -0
  30. package/dist/worktree/worktree.types.d.ts +4 -0
  31. package/package.json +1 -1
@@ -55,6 +55,11 @@ export interface HostLoadAdmissionDecision {
55
55
  readonly reservedCpuCores: number;
56
56
  readonly reservedMemoryBytes: number;
57
57
  readonly detail: string;
58
+ /**
59
+ * Set on a host test slot wait whose holders are all healthy (owner alive, lease renewed, not retained):
60
+ * the queue is moving, so the wait does not count toward the stalled-wait limit.
61
+ */
62
+ readonly progressing?: boolean;
58
63
  }
59
64
  /**
60
65
  * Decision 0013 admission rule. A step is admitted when the reserved cost of
@@ -18,8 +18,17 @@ export interface HostLoadGovernorConfig {
18
18
  readonly backpressureSamples: number;
19
19
  /** Host memory PSI `full avg10` (percent) above which admission is a hard stop. */
20
20
  readonly memoryFullThreshold: number;
21
- /** Maximum queue wait before a retryable host_capacity_timeout. */
21
+ /**
22
+ * FORGE_HOST_LOAD_MAX_WAIT_MS: the longest a step waits while its queue is stalled before a retryable
23
+ * host_capacity_timeout. Time spent behind holders of the host test slot that are all healthy (owner
24
+ * alive, lease renewed, not retained) does not count: their steps are making progress.
25
+ */
22
26
  readonly maxWaitMs: number;
27
+ /**
28
+ * FORGE_HOST_LOAD_MAX_TOTAL_WAIT_MS: the longest a step may queue in all, healthy holders or not; the
29
+ * backstop for a holder that is alive but never finishes. Never below maxWaitMs.
30
+ */
31
+ readonly maxTotalWaitMs: number;
23
32
  /** Steps allowed at once when PSI is unavailable (the per-host semaphore fallback). */
24
33
  readonly fallbackSlots: number;
25
34
  /** After this long at the head of the queue, later waiters may no longer overtake it. */
@@ -9,6 +9,7 @@ export const defaultHostLoadGovernorConfig = {
9
9
  backpressureSamples: 2,
10
10
  memoryFullThreshold: 5,
11
11
  maxWaitMs: 30 * 60_000,
12
+ maxTotalWaitMs: 4 * 60 * 60_000,
12
13
  fallbackSlots: 1,
13
14
  antiStarvationMs: 2 * 60_000,
14
15
  leaseMs: 2 * 60_000,
@@ -27,6 +28,7 @@ export function hostLoadGovernorEnabled(config) {
27
28
  }
28
29
  export function loadHostLoadGovernorConfig(environment = process.env) {
29
30
  const defaults = defaultHostLoadGovernorConfig;
31
+ const maxWaitMs = bounded(environment.FORGE_HOST_LOAD_MAX_WAIT_MS, defaults.maxWaitMs, 1_000, 24 * 60 * 60_000);
30
32
  return {
31
33
  mode: parseHostLoadGovernorMode(environment.FORGE_HOST_LOAD_GOVERNOR),
32
34
  testSlots: Math.round(bounded(environment.FORGE_HOST_LOAD_TEST_SLOTS, defaults.testSlots, 0, 8)),
@@ -35,7 +37,8 @@ export function loadHostLoadGovernorConfig(environment = process.env) {
35
37
  cpuPressureThreshold: bounded(environment.FORGE_HOST_LOAD_CPU_PRESSURE_THRESHOLD, defaults.cpuPressureThreshold, 1, 100),
36
38
  backpressureSamples: Math.round(bounded(environment.FORGE_HOST_LOAD_BACKPRESSURE_SAMPLES, defaults.backpressureSamples, 1, 60)),
37
39
  memoryFullThreshold: bounded(environment.FORGE_HOST_LOAD_MEMORY_FULL_THRESHOLD, defaults.memoryFullThreshold, 0, 100),
38
- maxWaitMs: bounded(environment.FORGE_HOST_LOAD_MAX_WAIT_MS, defaults.maxWaitMs, 1_000, 24 * 60 * 60_000),
40
+ maxWaitMs,
41
+ maxTotalWaitMs: Math.max(maxWaitMs, bounded(environment.FORGE_HOST_LOAD_MAX_TOTAL_WAIT_MS, defaults.maxTotalWaitMs, 1_000, 24 * 60 * 60_000)),
39
42
  fallbackSlots: Math.round(bounded(environment.FORGE_HOST_LOAD_FALLBACK_SLOTS, defaults.fallbackSlots, 1, 64)),
40
43
  antiStarvationMs: defaults.antiStarvationMs,
41
44
  leaseMs: defaults.leaseMs,
@@ -51,7 +51,7 @@ export interface HostLoadAdmission {
51
51
  /** The gate heavy steps call before launching. */
52
52
  export interface HostLoadStepGate {
53
53
  readonly enabled: boolean;
54
- /** The longest a step may queue before host_capacity_timeout, when the gate knows it. */
54
+ /** The longest a step may queue in all before host_capacity_timeout, when the gate knows it. */
55
55
  readonly maxWaitMs?: number;
56
56
  acquire(request: HostLoadStepRequest, options?: HostLoadAcquireOptions): Promise<HostLoadAdmission>;
57
57
  }
@@ -150,6 +150,13 @@ export declare class HostLoadGovernor implements HostLoadStepGate {
150
150
  */
151
151
  private runningStepsMemoryBytes;
152
152
  private logicalCpus;
153
+ /**
154
+ * Waiting behind healthy holders of the host test slot is progress: their steps run, and the slot passes
155
+ * down the queue as they finish. Any other wait (a holder past its lease or whose owner is gone, the
156
+ * budget, a recovering ledger) counts toward maxWaitMs from the last time the queue made progress.
157
+ */
158
+ private checkStalled;
159
+ private timeOut;
153
160
  private settle;
154
161
  /** Renewed tokens reset their lease clock; fenced ones stop their steps (they keep their cost until released). */
155
162
  private applyHeldOutcome;
@@ -66,7 +66,7 @@ export class HostLoadGovernor {
66
66
  });
67
67
  }
68
68
  get maxWaitMs() {
69
- return this.config.maxWaitMs;
69
+ return this.config.maxTotalWaitMs;
70
70
  }
71
71
  async acquire(request, options = {}) {
72
72
  if (!this.enabled) {
@@ -85,15 +85,17 @@ export class HostLoadGovernor {
85
85
  if (signal?.aborted)
86
86
  throw abortError(signal);
87
87
  return await new Promise((resolve, reject) => {
88
+ const enqueuedAtMs = monotonicNowMs();
88
89
  const waiter = {
89
90
  request,
90
- enqueuedAtMs: monotonicNowMs(),
91
+ enqueuedAtMs,
91
92
  signal,
92
93
  onWaiting: options.onWaiting,
93
94
  resolve,
94
95
  reject,
95
96
  abort: () => this.settle(waiter, () => reject(abortError(signal))),
96
97
  deadline: null,
98
+ progressAtMs: enqueuedAtMs,
97
99
  lastDecision: null,
98
100
  settled: false,
99
101
  ticket: this.config.testSlots > 0 && takesHostTestSlot(request.stepClass)
@@ -107,7 +109,8 @@ export class HostLoadGovernor {
107
109
  }
108
110
  : null,
109
111
  };
110
- waiter.deadline = setTimeout(() => this.settle(waiter, () => reject(new HostCapacityTimeoutError(request.stepClass, request.label, monotonicNowMs() - waiter.enqueuedAtMs, waiter.lastDecision?.detail ?? "the host stayed at capacity."))), this.config.maxWaitMs);
112
+ // The backstop: even behind healthy holders, a step queues no longer than maxTotalWaitMs.
113
+ waiter.deadline = setTimeout(() => this.timeOut(waiter, `${waiter.lastDecision?.detail ?? "The host stayed at capacity."} It reached the longest a step may queue (${minutes(this.config.maxTotalWaitMs)}).`), this.config.maxTotalWaitMs);
111
114
  waiter.deadline.unref?.();
112
115
  signal?.addEventListener("abort", waiter.abort, { once: true });
113
116
  // Foreground goes ahead of background, except background that has already
@@ -233,6 +236,7 @@ export class HostLoadGovernor {
233
236
  waiter.lastDecision = decision;
234
237
  if (first && !waiter.settled)
235
238
  void Promise.resolve(waiter.onWaiting?.(decision)).catch(() => undefined);
239
+ this.checkStalled(waiter, decision);
236
240
  continue;
237
241
  }
238
242
  const entry = {
@@ -310,6 +314,7 @@ export class HostLoadGovernor {
310
314
  return {
311
315
  ...decision,
312
316
  admitted: false,
317
+ progressing: false,
313
318
  reason: "ledger_recovering",
314
319
  detail: `The host load ledger was corrupt and was quarantined; admissions resume at ${transaction.recoveringUntil}, once running steps have restored their reservations.`,
315
320
  };
@@ -387,6 +392,26 @@ export class HostLoadGovernor {
387
392
  return reported;
388
393
  return Math.max(1, typeof os.availableParallelism === "function" ? os.availableParallelism() : os.cpus().length);
389
394
  }
395
+ /**
396
+ * Waiting behind healthy holders of the host test slot is progress: their steps run, and the slot passes
397
+ * down the queue as they finish. Any other wait (a holder past its lease or whose owner is gone, the
398
+ * budget, a recovering ledger) counts toward maxWaitMs from the last time the queue made progress.
399
+ */
400
+ checkStalled(waiter, decision) {
401
+ if (waiter.settled)
402
+ return;
403
+ const nowMs = monotonicNowMs();
404
+ if (decision.reason === "host_test_slot" && decision.progressing === true) {
405
+ waiter.progressAtMs = nowMs;
406
+ return;
407
+ }
408
+ if (nowMs - waiter.progressAtMs < this.config.maxWaitMs)
409
+ return;
410
+ this.timeOut(waiter, `${decision.detail} The queue made no progress for ${minutes(nowMs - waiter.progressAtMs)}.`);
411
+ }
412
+ timeOut(waiter, detail) {
413
+ this.settle(waiter, () => waiter.reject(new HostCapacityTimeoutError(waiter.request.stepClass, waiter.request.label, monotonicNowMs() - waiter.enqueuedAtMs, detail)));
414
+ }
390
415
  settle(waiter, complete) {
391
416
  if (waiter.settled)
392
417
  return;
@@ -592,6 +617,11 @@ function tighterMemory(hostAvailable, cgroupHeadroom) {
592
617
  return hostAvailable;
593
618
  return hostAvailable === null ? cgroupHeadroom : Math.min(hostAvailable, cgroupHeadroom);
594
619
  }
620
+ /** Whole minutes for messages (at least 1); sub-minute limits only occur in tests and tuning. */
621
+ function minutes(ms) {
622
+ const whole = Math.max(1, Math.round(ms / 60_000));
623
+ return whole === 1 ? "1 minute" : `${whole} minutes`;
624
+ }
595
625
  function abortError(signal) {
596
626
  if (signal.reason instanceof Error)
597
627
  return signal.reason;
@@ -55,8 +55,15 @@ export function decideHostTestSlot(input) {
55
55
  admitted,
56
56
  reason: "host_test_slot",
57
57
  detail: `Waiting for the host test slot (${input.testSlots} at once): ${heldBy}; ${ahead} step(s) ahead in the host queue.`,
58
+ // Only a running, healthy holder is progress. With no holder the steps ahead are waiting too (for
59
+ // the budget, say), and that wait must count as stalled, not reset the clock.
60
+ progressing: holders.length > 0 && holders.every(healthyHolder),
58
61
  };
59
62
  }
63
+ /** A holder whose step is still running under a live, renewed lease; the ledger reclaims the rest. */
64
+ function healthyHolder(token) {
65
+ return !token.degradedAt && !token.fencedAt && !token.retainedAt;
66
+ }
60
67
  function describeHolder(token) {
61
68
  const attempt = token.dispatchAttemptId ? `, attempt ${token.dispatchAttemptId}` : "";
62
69
  const state = token.degradedAt
@@ -170,7 +170,7 @@ export class DockerSandboxRuntime {
170
170
  const brokered = this.hostLoadGate?.enabled === true;
171
171
  const workerArgs = workerCreateArgs(runtimeDispatch, validated, resources, labels, imageDigest, securityOptions);
172
172
  const createArgs = brokered
173
- ? withSandboxHostCapacityBroker(workerArgs, imageDigest, this.hostLoadGate.maxWaitMs ?? defaultHostLoadGovernorConfig.maxWaitMs)
173
+ ? withSandboxHostCapacityBroker(workerArgs, imageDigest, this.hostLoadGate.maxWaitMs ?? defaultHostLoadGovernorConfig.maxTotalWaitMs)
174
174
  : workerArgs;
175
175
  const createdContainer = await this.docker(createArgs, 60_000, runtimeSignal);
176
176
  const containerId = dockerObjectId(createdContainer.stdout, "container");
@@ -57,17 +57,20 @@ export declare class MergeResolutionUnresolvedConflictError extends ForgeFailure
57
57
  export declare function isMergeInProgress(git: GitRunner, worktreePath: string): Promise<boolean>;
58
58
  export declare function readInProgressMerge(git: GitRunner, worktreePath: string): Promise<InProgressMerge | null>;
59
59
  /**
60
- * Fails before `git add -A` can silently resolve a conflict:
60
+ * Fails before `git add -A` can silently resolve a conflict, during a merge or whenever the index
61
+ * holds unmerged paths without one (a WIP snapshot re-applied across a branch move that conflicted,
62
+ * see wip-restore.ts):
61
63
  * - a modify/delete conflict, by keeping whatever is on disk;
62
64
  * - a binary (or other marker-less) conflict, by staging whichever side is on disk;
63
65
  * - a content conflict, by staging its conflict markers. This includes markers
64
66
  * the provider already staged, which clears the unmerged stages, so every path
65
- * both sides changed is checked too.
67
+ * both sides of the merge changed is checked too, or without a merge every path
68
+ * the worktree's WIP re-apply conflict record lists.
66
69
  * A text conflict the agent resolved in the working tree without `git add` is
67
70
  * still unmerged here and is accepted once its markers are gone.
68
71
  */
69
72
  export declare function assertNoUnresolvedMergeConflicts(git: GitRunner, worktreePath: string): Promise<void>;
70
- export declare function readUnresolvedMergeConflicts(git: GitRunner, worktreePath: string, merge: InProgressMerge): Promise<readonly UnresolvedMergeConflict[]>;
73
+ export declare function readUnresolvedMergeConflicts(git: GitRunner, worktreePath: string, merge: InProgressMerge | null): Promise<readonly UnresolvedMergeConflict[]>;
71
74
  /**
72
75
  * Staging excludes some worktree changes (Forge runtime output) by unstaging them
73
76
  * back to HEAD. During a merge HEAD is the story side, so an excluded path the merge
@@ -1,5 +1,6 @@
1
1
  import fs from "node:fs/promises";
2
2
  import path from "node:path";
3
+ import { parseReapplyConflictRecord, wipReapplyConflictRecordName } from "../../worktree/wip-refs.js";
3
4
  import { ForgeFailureError } from "../session.types.js";
4
5
  const maxListedPaths = 20;
5
6
  const pathArgumentChunkSize = 100;
@@ -61,19 +62,20 @@ export async function readInProgressMerge(git, worktreePath) {
61
62
  return { headSha, mergeHeadSha, mergeBaseSha };
62
63
  }
63
64
  /**
64
- * Fails before `git add -A` can silently resolve a conflict:
65
+ * Fails before `git add -A` can silently resolve a conflict, during a merge or whenever the index
66
+ * holds unmerged paths without one (a WIP snapshot re-applied across a branch move that conflicted,
67
+ * see wip-restore.ts):
65
68
  * - a modify/delete conflict, by keeping whatever is on disk;
66
69
  * - a binary (or other marker-less) conflict, by staging whichever side is on disk;
67
70
  * - a content conflict, by staging its conflict markers. This includes markers
68
71
  * the provider already staged, which clears the unmerged stages, so every path
69
- * both sides changed is checked too.
72
+ * both sides of the merge changed is checked too, or without a merge every path
73
+ * the worktree's WIP re-apply conflict record lists.
70
74
  * A text conflict the agent resolved in the working tree without `git add` is
71
75
  * still unmerged here and is accepted once its markers are gone.
72
76
  */
73
77
  export async function assertNoUnresolvedMergeConflicts(git, worktreePath) {
74
78
  const merge = await readInProgressMerge(git, worktreePath);
75
- if (!merge)
76
- return;
77
79
  const conflicts = await readUnresolvedMergeConflicts(git, worktreePath, merge);
78
80
  if (conflicts.length > 0) {
79
81
  throw new MergeResolutionUnresolvedConflictError(conflicts);
@@ -117,16 +119,34 @@ export async function readUnresolvedMergeConflicts(git, worktreePath, merge) {
117
119
  else if (hasConflictMarkers(content))
118
120
  conflicts.push({ path: filePath, kind: "conflict_markers" });
119
121
  }
122
+ const unmergedPaths = new Set(stagesByPath.keys());
123
+ conflicts.push(...await markerConflicts(worktreePath, unmergedPaths, merge
124
+ ? await bothChangedPaths(git, worktreePath, merge)
125
+ : await reapplyConflictPaths(git, worktreePath)));
126
+ return conflicts.sort((left, right) => left.path.localeCompare(right.path));
127
+ }
128
+ /** Paths both sides of the merge changed. */
129
+ async function bothChangedPaths(git, worktreePath, merge) {
120
130
  const storyChanged = new Set(await diffNames(git, worktreePath, [merge.mergeBaseSha, merge.headSha]));
121
- const bothChanged = (await diffNames(git, worktreePath, [merge.mergeBaseSha, merge.mergeHeadSha]))
122
- .filter(filePath => storyChanged.has(filePath) && !stagesByPath.has(filePath));
123
- for (const filePath of bothChanged) {
131
+ return (await diffNames(git, worktreePath, [merge.mergeBaseSha, merge.mergeHeadSha]))
132
+ .filter(filePath => storyChanged.has(filePath));
133
+ }
134
+ /** Paths a WIP re-apply left conflicted, from the worktree's record (wip-refs.ts); [] without one. */
135
+ async function reapplyConflictPaths(git, worktreePath) {
136
+ const raw = (await git.run(worktreePath, ["rev-parse", "--git-path", wipReapplyConflictRecordName])).trim();
137
+ const record = path.isAbsolute(raw) ? raw : path.resolve(worktreePath, raw);
138
+ return parseReapplyConflictRecord(await fs.readFile(record, "utf8").catch(() => null));
139
+ }
140
+ /** Candidate conflict paths whose markers the provider already staged (no unmerged stages left). */
141
+ async function markerConflicts(worktreePath, unmergedPaths, candidates) {
142
+ const conflicts = [];
143
+ for (const filePath of candidates.filter(candidate => !unmergedPaths.has(candidate))) {
124
144
  const content = await readWorkingFile(worktreePath, filePath);
125
145
  if (content && !isBinary(content) && hasConflictMarkers(content)) {
126
146
  conflicts.push({ path: filePath, kind: "conflict_markers" });
127
147
  }
128
148
  }
129
- return conflicts.sort((left, right) => left.path.localeCompare(right.path));
149
+ return conflicts;
130
150
  }
131
151
  /**
132
152
  * Staging excludes some worktree changes (Forge runtime output) by unstaging them
@@ -39,7 +39,7 @@ export class SandboxBrokeredHostLoadGate {
39
39
  this.pollMs = options.pollMs ?? 250;
40
40
  this.replyOwnership = options.replyOwnership
41
41
  ?? posixReplyOwnership(options.trustedOwnerUid ?? sandboxHostCapacityResponseOwnerUid);
42
- this.maxWaitMs = options.maxWaitMs ?? defaultHostLoadGovernorConfig.maxWaitMs + 2 * 60_000;
42
+ this.maxWaitMs = options.maxWaitMs ?? defaultHostLoadGovernorConfig.maxTotalWaitMs + 2 * 60_000;
43
43
  }
44
44
  async acquire(request, options = {}) {
45
45
  const requestId = randomUUID();
@@ -251,10 +251,7 @@ export class BridgeSessionService {
251
251
  applicationRuntimeRequired: dispatch.runtimeIntent.applicationRuntimeRequired,
252
252
  preserveExistingState: Boolean(dispatch.session.resumedFromSessionId),
253
253
  sessionId: dispatch.session.id,
254
- hostLoadOwner: {
255
- dispatchAttemptId: dispatch.sandbox?.dispatchAttemptId ?? null,
256
- priority: runtimeAdmissionPriority(dispatch),
257
- },
254
+ ...preparedAttemptOwner(dispatch),
258
255
  signal,
259
256
  });
260
257
  }
@@ -776,6 +773,13 @@ function throwIfAborted(signal) {
776
773
  throw new Error(String(signal.reason ?? "Dispatch cancelled."));
777
774
  }
778
775
  }
776
+ /** The dispatch attempt a worktree is prepared for: Forge's attempt for its WIP refs, and whose host load it reserves. */
777
+ function preparedAttemptOwner(dispatch) {
778
+ return {
779
+ wipAttempt: dispatch.wipAttempt ?? null,
780
+ hostLoadOwner: { dispatchAttemptId: dispatch.sandbox?.dispatchAttemptId ?? null, priority: runtimeAdmissionPriority(dispatch) },
781
+ };
782
+ }
779
783
  function validateApiKeySecretGrant(dispatch) {
780
784
  if (!dispatch.execution.requiresApiKeySecretGrant) {
781
785
  return;
@@ -11,6 +11,7 @@ export interface RunOnceDispatchPacket {
11
11
  readonly runtimeIntent: DispatchRuntimeIntent;
12
12
  readonly serverLocal: DispatchServerLocalConfig;
13
13
  readonly sandbox?: DispatchSandboxContext | null;
14
+ readonly wipAttempt?: number | null;
14
15
  readonly pullRequest?: DispatchPullRequestContext | null;
15
16
  readonly apiKeySecretGrant?: ApiKeySecretGrant | null;
16
17
  readonly apiKeySecretGrantHandle?: ApiKeySecretGrantHandle | null;
@@ -28,6 +28,7 @@ export function parseRunOnceDispatchPacket(value) {
28
28
  runtimeIntent: parseRuntimeIntent(packet.runtimeIntent),
29
29
  serverLocal: parseServerLocal(packet.serverLocal),
30
30
  sandbox: parseSandbox(packet.sandbox, schemaVersion),
31
+ wipAttempt: optionalNonNegativeInteger(packet, "wipAttempt"),
31
32
  pullRequest: parsePullRequest(packet.pullRequest),
32
33
  apiKeySecretGrant: parseApiKeySecretGrant(packet.apiKeySecretGrant),
33
34
  apiKeySecretGrantHandle: parseApiKeySecretGrantHandle(packet.apiKeySecretGrantHandle),
@@ -1373,9 +1374,8 @@ function optionalPositiveInteger(source, key) {
1373
1374
  }
1374
1375
  function optionalNonNegativeInteger(source, key) {
1375
1376
  const value = source[key];
1376
- if (value === undefined || value === null) {
1377
+ if (value === undefined || value === null)
1377
1378
  return null;
1378
- }
1379
1379
  if (typeof value !== "number" || !Number.isInteger(value) || value < 0) {
1380
1380
  throw new Error(`${key} must be a non-negative integer when provided.`);
1381
1381
  }
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const forgeBridgeVersion = "0.2.1-dev.4f11ffc822f9";
1
+ export declare const forgeBridgeVersion = "0.2.1-dev.eac6976df5e9";
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const forgeBridgeVersion = "0.2.1-dev.4f11ffc822f9";
1
+ export const forgeBridgeVersion = "0.2.1-dev.eac6976df5e9";
@@ -6,6 +6,12 @@ export declare class WipGit {
6
6
  /** The same client with more environment, e.g. GIT_INDEX_FILE for a throwaway index. */
7
7
  with(env: NodeJS.ProcessEnv): WipGit;
8
8
  run(cwd: string, args: readonly string[]): Promise<string>;
9
+ /** Runs git and returns its exit code with its output, for commands whose non-zero exit is an answer. */
10
+ runWithStatus(cwd: string, args: readonly string[]): Promise<{
11
+ readonly exitCode: number;
12
+ readonly stdout: string;
13
+ readonly stderr: string;
14
+ }>;
9
15
  tryRun(cwd: string, args: readonly string[]): Promise<string | null>;
10
16
  /** Runs git with `input` on stdin (for `update-index --index-info`). */
11
17
  runWithInput(cwd: string, args: readonly string[], input: string): Promise<void>;
@@ -28,6 +34,9 @@ export declare function baseTrackedForgePaths(git: WipGit, cwd: string, base: st
28
34
  export declare function gitPath(git: WipGit, cwd: string, name: string): Promise<string>;
29
35
  export declare function partialRestoreMarkerPath(git: WipGit, cwd: string): Promise<string>;
30
36
  export declare function hasPartialRestoreMarker(git: WipGit, cwd: string): Promise<boolean>;
37
+ export declare function readReapplyConflictRecord(git: WipGit, cwd: string): Promise<string[]>;
38
+ /** Writes the re-apply conflict record (wip-refs.ts), or removes it when there are no paths. */
39
+ export declare function writeReapplyConflictRecord(git: WipGit, cwd: string, paths: readonly string[]): Promise<void>;
31
40
  /** A private directory for throwaway index files, removed by the caller. */
32
41
  export declare function makeWipTempDir(): Promise<string>;
33
42
  export declare function readOptionalFile(filePath: string): Promise<string | null>;
@@ -4,6 +4,7 @@ import os from "node:os";
4
4
  import path from "node:path";
5
5
  import { isRuntimeOnlyPath } from "../session/publishable-worktree-changes.js";
6
6
  import { NodeProcessRunner } from "../shared/process/process.js";
7
+ import { parseReapplyConflictRecord, wipReapplyConflictRecordName } from "./wip-refs.js";
7
8
  // Git plumbing shared by WIP snapshot and restore. Every command can carry extra environment
8
9
  // (a temporary index, or GIT_DIR/GIT_WORK_TREE for an orphaned checkout) without touching the
9
10
  // worktree's own index, HEAD or config.
@@ -26,6 +27,14 @@ export class WipGit {
26
27
  return new WipGit(this.runner, { ...this.env, ...env });
27
28
  }
28
29
  async run(cwd, args) {
30
+ const result = await this.runWithStatus(cwd, args);
31
+ if (result.exitCode !== 0) {
32
+ throw new Error(`git ${args.join(" ")} failed: ${result.stderr.trim() || result.stdout.trim()}`);
33
+ }
34
+ return result.stdout;
35
+ }
36
+ /** Runs git and returns its exit code with its output, for commands whose non-zero exit is an answer. */
37
+ async runWithStatus(cwd, args) {
29
38
  const result = await this.runner.run({
30
39
  command: "git",
31
40
  args,
@@ -33,10 +42,7 @@ export class WipGit {
33
42
  env: { ...process.env, ...wipIdentity, ...this.env },
34
43
  ...(args.includes("-z") ? { rawOutput: true } : {}),
35
44
  });
36
- if (result.exitCode !== 0) {
37
- throw new Error(`git ${args.join(" ")} failed: ${result.stderr.trim() || result.stdout.trim()}`);
38
- }
39
- return result.stdout;
45
+ return { exitCode: result.exitCode, stdout: result.stdout, stderr: result.stderr };
40
46
  }
41
47
  async tryRun(cwd, args) {
42
48
  return await this.run(cwd, args).catch(() => null);
@@ -109,6 +115,17 @@ export async function hasPartialRestoreMarker(git, cwd) {
109
115
  const marker = await partialRestoreMarkerPath(git, cwd).catch(() => null);
110
116
  return marker !== null && await fs.stat(marker).then(() => true, () => false);
111
117
  }
118
+ export async function readReapplyConflictRecord(git, cwd) {
119
+ return parseReapplyConflictRecord(await readOptionalFile(await gitPath(git, cwd, wipReapplyConflictRecordName)));
120
+ }
121
+ /** Writes the re-apply conflict record (wip-refs.ts), or removes it when there are no paths. */
122
+ export async function writeReapplyConflictRecord(git, cwd, paths) {
123
+ const record = await gitPath(git, cwd, wipReapplyConflictRecordName);
124
+ if (paths.length === 0)
125
+ await fs.rm(record, { force: true });
126
+ else
127
+ await fs.writeFile(record, [...new Set(paths)].sort().join("\0"), "utf8");
128
+ }
112
129
  /** A private directory for throwaway index files, removed by the caller. */
113
130
  export async function makeWipTempDir() {
114
131
  return await fs.mkdtemp(path.join(os.tmpdir(), "forge-wip-"));
@@ -1,5 +1,14 @@
1
1
  export declare const wipRefRoot = "refs/forge/wip";
2
2
  export declare const wipMetadataSchema = "forge.wip.v1";
3
+ /**
4
+ * Kept in a worktree's Git directory after a WIP re-apply across a branch move left conflicts
5
+ * (wip-restore.ts): the conflicted paths, NUL-separated. A re-apply writes no MERGE_HEAD, and staging
6
+ * a conflicted file clears its index stages but keeps its markers, so publication reads this to keep
7
+ * refusing those markers (provider-cli.merge-integrity.ts). Snapshots carry it (reapplyConflicts) and
8
+ * a restore writes it back; a restore that finds the worktree clean removes it.
9
+ */
10
+ export declare const wipReapplyConflictRecordName = "forge-wip-reapply-conflicts";
11
+ export declare function parseReapplyConflictRecord(content: string | null): string[];
3
12
  /** The attempt of a snapshot taken without a Forge-issued attempt number. */
4
13
  export declare const unorderedWipAttempt = 0;
5
14
  /** Why a snapshot was taken. Session reasons name the session; the others are guards. */
@@ -27,6 +36,8 @@ export interface WipSnapshotMetadata {
27
36
  readonly mergeMessage: string | null;
28
37
  readonly mergeMode: string | null;
29
38
  readonly unmerged: readonly WipUnmergedEntry[];
39
+ /** The worktree's re-apply conflict record when it was taken (see wipReapplyConflictRecordName); [] before it existed. */
40
+ readonly reapplyConflicts: readonly string[];
30
41
  readonly changedPaths: number;
31
42
  readonly bytes: number;
32
43
  }
@@ -53,6 +64,10 @@ export declare function wipRefName(branchName: string, id: string): string;
53
64
  * for a guard snapshot.
54
65
  */
55
66
  export declare function wipRefId(reason: WipSnapshotReason, sessionId: string | null | undefined, now: Date, attempt?: number): string;
67
+ /** A Forge-issued attempt usable in a ref name; anything else (missing, out of range) is unorderedWipAttempt. */
68
+ export declare function issuedWipAttempt(value: number | null | undefined): number;
69
+ /** The attempt a WIP ref belongs to: its ten-digit id prefix, or unorderedWipAttempt without one. */
70
+ export declare function wipRefAttempt(ref: string): number;
56
71
  /** The cap on a snapshot's size, from FORGE_WIP_SNAPSHOT_MAX_BYTES when that is a positive integer. */
57
72
  export declare function wipSnapshotMaxBytes(env?: NodeJS.ProcessEnv): number;
58
73
  export declare function formatWipCommitMessage(metadata: WipSnapshotMetadata): string;
@@ -7,8 +7,11 @@
7
7
  //
8
8
  // refs/forge/wip/<owner key>/<attempt>-<session id | [session id-]reason-timestamp-nonce>
9
9
  //
10
- // <attempt> is ten zero-padded digits, so refs sort by it. It is reserved for Forge's per-story
11
- // attempt number (newest work wins); until the server sends one, snapshots carry attempt 0.
10
+ // <attempt> is ten zero-padded digits, so refs sort by it: the dispatch's wipAttempt, which Forge
11
+ // issues from a database sequence when it admits the dispatch attempt, so a later attempt on a story
12
+ // always has a larger one. Newest work wins: a restore takes the highest attempt first. Snapshots
13
+ // taken without an issued attempt (older servers, attempts admitted before it existed, cleanup and
14
+ // branch-reset guards) carry attempt 0.
12
15
  //
13
16
  // The owner key is the story's short id for a `story/<12 hex>` branch, and `b_` plus the branch
14
17
  // name with `_` → `_u` and `/` → `_s` for any other branch (`b_task_s0123456789ab`), so it is
@@ -26,6 +29,17 @@ const defaultWipSnapshotMaxBytes = 100 * 1024 * 1024;
26
29
  const wipSnapshotMaxBytesEnv = "FORGE_WIP_SNAPSHOT_MAX_BYTES";
27
30
  const storyBranchPattern = /^story\/([0-9a-f]{12})$/u;
28
31
  const refSegmentPattern = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u;
32
+ /**
33
+ * Kept in a worktree's Git directory after a WIP re-apply across a branch move left conflicts
34
+ * (wip-restore.ts): the conflicted paths, NUL-separated. A re-apply writes no MERGE_HEAD, and staging
35
+ * a conflicted file clears its index stages but keeps its markers, so publication reads this to keep
36
+ * refusing those markers (provider-cli.merge-integrity.ts). Snapshots carry it (reapplyConflicts) and
37
+ * a restore writes it back; a restore that finds the worktree clean removes it.
38
+ */
39
+ export const wipReapplyConflictRecordName = "forge-wip-reapply-conflicts";
40
+ export function parseReapplyConflictRecord(content) {
41
+ return content ? [...new Set(content.split("\0").filter(Boolean))].sort() : [];
42
+ }
29
43
  /** The attempt of a snapshot taken without a Forge-issued attempt number. */
30
44
  export const unorderedWipAttempt = 0;
31
45
  const maxWipAttempt = 9_999_999_999;
@@ -82,6 +96,16 @@ function isSessionReason(reason) {
82
96
  return reason === "session_failed" || reason === "repair_limit"
83
97
  || reason === "session_paused" || reason === "session_stopped";
84
98
  }
99
+ /** A Forge-issued attempt usable in a ref name; anything else (missing, out of range) is unorderedWipAttempt. */
100
+ export function issuedWipAttempt(value) {
101
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 && value <= maxWipAttempt ? value : unorderedWipAttempt;
102
+ }
103
+ /** The attempt a WIP ref belongs to: its ten-digit id prefix, or unorderedWipAttempt without one. */
104
+ export function wipRefAttempt(ref) {
105
+ const id = ref.slice(ref.lastIndexOf("/") + 1);
106
+ const match = /^(\d{10})-/u.exec(id);
107
+ return match ? Number(match[1]) : unorderedWipAttempt;
108
+ }
85
109
  /** The cap on a snapshot's size, from FORGE_WIP_SNAPSHOT_MAX_BYTES when that is a positive integer. */
86
110
  export function wipSnapshotMaxBytes(env = process.env) {
87
111
  const configured = Number.parseInt(env[wipSnapshotMaxBytesEnv] ?? "", 10);
@@ -106,6 +130,9 @@ export function parseWipCommitMessage(message) {
106
130
  ...parsed,
107
131
  unmerged: Array.isArray(parsed.unmerged) ? parsed.unmerged : [],
108
132
  autoRestore: parsed.autoRestore === true,
133
+ reapplyConflicts: Array.isArray(parsed.reapplyConflicts)
134
+ ? parsed.reapplyConflicts.filter(conflict => typeof conflict === "string")
135
+ : [],
109
136
  };
110
137
  }
111
138
  catch {
@@ -15,6 +15,8 @@ export type WipRestoreOutcome = {
15
15
  readonly sourceSessionId: string | null;
16
16
  readonly changedPaths: number;
17
17
  readonly mergeInProgress: boolean;
18
+ /** Set when the branch had moved and the snapshot was re-applied onto its new HEAD with a 3-way merge. */
19
+ readonly reapplied: WipReapply | null;
18
20
  } | {
19
21
  readonly status: "not_restored";
20
22
  readonly ref: string;
@@ -31,6 +33,12 @@ export type WipRestoreOutcome = {
31
33
  readonly status: "unavailable";
32
34
  readonly detail: string;
33
35
  };
36
+ export interface WipReapply {
37
+ /** The HEAD the snapshot was taken on, used as the merge base. */
38
+ readonly snapshotBaseHead: string;
39
+ /** Paths the merge left unmerged, with conflict markers where Git writes them, for the agent to resolve. */
40
+ readonly conflictedPaths: readonly string[];
41
+ }
34
42
  export declare function restoreLatestWip(request: WipRestoreRequest): Promise<WipRestoreOutcome>;
35
43
  /** Deletes a WIP ref (on origin, or locally when there is no origin). Never throws. */
36
44
  export declare function deleteWipRef(repoPath: string, ref: string, processRunner?: ProcessRunner): Promise<boolean>;
@@ -1,8 +1,8 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import fs from "node:fs/promises";
3
3
  import path from "node:path";
4
- import { baseTrackedForgePaths, gitPath, isWipExcludedPath, makeWipTempDir, partialRestoreMarkerPath, splitNul, WipGit, } from "./wip-git.js";
5
- import { commitMessageOf, parseWipCommitMessage, wipRefPrefix, wipRefRoot, } from "./wip-refs.js";
4
+ import { baseTrackedForgePaths, gitPath, isWipExcludedPath, makeWipTempDir, partialRestoreMarkerPath, splitNul, WipGit, writeReapplyConflictRecord, } from "./wip-git.js";
5
+ import { commitMessageOf, issuedWipAttempt, parseWipCommitMessage, wipRefAttempt, wipRefPrefix, wipRefRoot, } from "./wip-refs.js";
6
6
  export async function restoreLatestWip(request) {
7
7
  const git = new WipGit(request.processRunner);
8
8
  let candidates;
@@ -18,18 +18,34 @@ export async function restoreLatestWip(request) {
18
18
  if (!await isCleanWorktree(git, request.worktreePath)) {
19
19
  return { status: "skipped_dirty", ref: newest.ref, commitSha: newest.commitSha };
20
20
  }
21
- // Clean again (the reset after a failed restore): its later snapshots may be applied as usual.
21
+ // Clean again (the reset after a failed restore): its later snapshots may be applied as usual, and
22
+ // no earlier re-apply's conflicts are left.
22
23
  await fs.rm(await partialRestoreMarkerPath(git, request.worktreePath), { force: true });
24
+ await writeReapplyConflictRecord(git, request.worktreePath, []);
23
25
  const currentHead = (await git.run(request.worktreePath, ["rev-parse", "HEAD"])).trim();
24
26
  const notRestored = (reason, detail) => ({
25
27
  status: "not_restored", ref: newest.ref, commitSha: newest.commitSha, reason,
26
28
  baseHead: newest.metadata.baseHead, currentHead, detail,
27
29
  });
30
+ let plan = null;
28
31
  if (newest.metadata.baseHead !== currentHead) {
29
- return notRestored("branch_moved", `${request.branchName} is at ${currentHead.slice(0, 12)}, but the snapshot was taken on ${newest.metadata.baseHead.slice(0, 12)}.`);
32
+ const moved = `${request.branchName} is at ${currentHead.slice(0, 12)}, but the snapshot was taken on ${newest.metadata.baseHead.slice(0, 12)}.`;
33
+ if (newest.metadata.mergeHead || newest.metadata.unmerged.length > 0) {
34
+ return notRestored("branch_moved", `${moved} It was taken during a merge, so it is not re-applied onto the moved branch.`);
35
+ }
36
+ try {
37
+ plan = await planReapply(git, request.worktreePath, newest, currentHead);
38
+ }
39
+ catch (error) {
40
+ return notRestored("branch_moved", `${moved} It could not be re-applied onto the new HEAD (${errorMessage(error)}).`);
41
+ }
30
42
  }
31
43
  try {
32
- const changedPaths = await applySnapshot(git, request.worktreePath, newest);
44
+ const changedPaths = plan
45
+ ? await applyReapply(git, request.worktreePath, currentHead, plan)
46
+ : await applySnapshot(git, request.worktreePath, newest);
47
+ // Conflicts with no MERGE_HEAD to show them: this re-apply's, and any the snapshot carried.
48
+ await writeReapplyConflictRecord(git, request.worktreePath, [...newest.metadata.reapplyConflicts, ...(plan?.unmerged ?? []).map(entry => entry.path)]);
33
49
  return {
34
50
  status: "restored",
35
51
  ref: newest.ref,
@@ -38,6 +54,9 @@ export async function restoreLatestWip(request) {
38
54
  sourceSessionId: newest.metadata.sessionId,
39
55
  changedPaths,
40
56
  mergeInProgress: Boolean(newest.metadata.mergeHead),
57
+ reapplied: plan
58
+ ? { snapshotBaseHead: newest.metadata.baseHead, conflictedPaths: [...new Set(plan.unmerged.map(entry => entry.path))].sort() }
59
+ : null,
41
60
  };
42
61
  }
43
62
  catch (error) {
@@ -45,7 +64,7 @@ export async function restoreLatestWip(request) {
45
64
  // the prepare fails. Nothing is lost; the ref stays, and the next prepare saves this worktree
46
65
  // before it resets it. That snapshot holds the mixed state, so it is marked never to be applied
47
66
  // automatically (partialRestoreMarkerPath): the next pass restores the original ref instead.
48
- await rollBack(git, request.worktreePath, newest).catch(async (rollbackError) => {
67
+ await rollBack(git, request.worktreePath, currentHead, plan?.worktreeTree ?? newest.commitSha).catch(async (rollbackError) => {
49
68
  await partialRestoreMarkerPath(git, request.worktreePath)
50
69
  .then(marker => fs.writeFile(marker, `${newest.ref}\n`, "utf8"))
51
70
  .catch(() => undefined);
@@ -100,14 +119,24 @@ async function readRefs(git, repoPath, namespace, wipPrefix) {
100
119
  }
101
120
  return candidates;
102
121
  }
103
- /** The newest snapshot of this branch a pass may apply; one recorded for any other branch never is. */
122
+ /**
123
+ * The newest snapshot of this branch a pass may apply; one recorded for any other branch never is.
124
+ * Newest work wins: Forge's attempt number first (a later dispatch attempt always has a larger one,
125
+ * and a snapshot without one is attempt 0), then the snapshot's own time within an attempt.
126
+ */
104
127
  function newestRestorable(candidates, branchName) {
105
128
  const branch = branchRefName(branchName);
106
129
  return [...candidates]
107
130
  .filter(candidate => candidate.metadata.autoRestore && branchRefName(candidate.metadata.branch) === branch)
108
- .sort((left, right) => right.metadata.createdAtMs - left.metadata.createdAtMs || right.ref.localeCompare(left.ref))[0]
131
+ .sort((left, right) => candidateAttempt(right) - candidateAttempt(left)
132
+ || right.metadata.createdAtMs - left.metadata.createdAtMs || right.ref.localeCompare(left.ref))[0]
109
133
  ?? null;
110
134
  }
135
+ // The metadata attempt counts only when it is one Forge could have issued (0 through the ref's ten digits);
136
+ // anything else is attempt 0, so a malformed snapshot can never outrank a real one.
137
+ function candidateAttempt(candidate) {
138
+ return Math.max(wipRefAttempt(candidate.ref), issuedWipAttempt(candidate.metadata.attempt));
139
+ }
111
140
  /** True when the worktree holds nothing a snapshot would save (Forge runtime output aside), and no merge. */
112
141
  export async function hasNoUnsavedWork(worktreePath, processRunner) {
113
142
  return await isCleanWorktree(new WipGit(processRunner), worktreePath);
@@ -122,11 +151,72 @@ async function isCleanWorktree(git, worktreePath) {
122
151
  /** Writes the snapshot's files and index (and merge state) onto the clean worktree. */
123
152
  async function applySnapshot(git, worktreePath, candidate) {
124
153
  const { commitSha, metadata } = candidate;
125
- const changes = await snapshotChanges(git, worktreePath, metadata.baseHead, commitSha);
154
+ const changedPaths = await writeWorktreeTree(git, worktreePath, metadata.baseHead, commitSha);
155
+ await git.run(worktreePath, ["read-tree", `${commitSha}^2^{tree}`]);
156
+ if (metadata.unmerged.length > 0)
157
+ await writeUnmergedEntries(git, worktreePath, metadata.unmerged, metadata.baseHead.length);
158
+ if (metadata.mergeHead)
159
+ await writeMergeState(git, worktreePath, metadata);
160
+ await git.tryRun(worktreePath, ["update-index", "-q", "--refresh"]);
161
+ return changedPaths;
162
+ }
163
+ /**
164
+ * Merges the snapshot onto the moved branch without touching the worktree. The worktree's tree is
165
+ * `git merge-tree` of the snapshot's base, the new HEAD and the snapshot (W); the index is the same
166
+ * merge of the snapshot's staged state (W^2) when that is clean, else the new HEAD's tree (all the
167
+ * content is in the worktree either way). A conflict comes back as the merge's stage 1-3 entries.
168
+ */
169
+ async function planReapply(git, worktreePath, candidate, currentHead) {
170
+ const base = candidate.metadata.baseHead;
171
+ const worktree = await mergeTree(git, worktreePath, base, currentHead, candidate.commitSha);
172
+ const index = await mergeTree(git, worktreePath, base, currentHead, `${candidate.commitSha}^2`);
173
+ return {
174
+ worktreeTree: worktree.tree,
175
+ indexTree: index.unmerged.length === 0 ? index.tree : `${currentHead}^{tree}`,
176
+ unmerged: worktree.unmerged,
177
+ };
178
+ }
179
+ /** Writes a re-apply's merged files, index and conflict stages onto the clean worktree at `currentHead`. */
180
+ async function applyReapply(git, worktreePath, currentHead, plan) {
181
+ const changedPaths = await writeWorktreeTree(git, worktreePath, currentHead, plan.worktreeTree);
182
+ await git.run(worktreePath, ["read-tree", plan.indexTree]);
183
+ if (plan.unmerged.length > 0)
184
+ await writeUnmergedEntries(git, worktreePath, plan.unmerged, currentHead.length);
185
+ await git.tryRun(worktreePath, ["update-index", "-q", "--refresh"]);
186
+ return changedPaths;
187
+ }
188
+ /** `git merge-tree --write-tree` (Git 2.40+): the merged tree, with its conflict stages when it conflicts. */
189
+ async function mergeTree(git, worktreePath, base, ours, theirs) {
190
+ const args = ["merge-tree", "--write-tree", "-z", "--no-messages", `--merge-base=${base}`, ours, theirs];
191
+ const result = await git.runWithStatus(worktreePath, args);
192
+ if (result.exitCode !== 0 && result.exitCode !== 1) {
193
+ throw new Error(`git ${args.join(" ")} failed: ${result.stderr.trim() || result.stdout.trim()}`);
194
+ }
195
+ // <tree> NUL, then one "<mode> <object> <stage>\t<path>" NUL per conflict stage, then an empty field.
196
+ const [tree = "", ...records] = result.stdout.split("\0");
197
+ const unmerged = [];
198
+ for (const record of records) {
199
+ const match = /^(\d{6}) ([0-9a-f]+) ([123])\t([\s\S]+)$/u.exec(record);
200
+ if (!match)
201
+ break;
202
+ unmerged.push({ mode: match[1], sha: match[2], stage: Number(match[3]), path: match[4] });
203
+ }
204
+ if (!/^[0-9a-f]+$/u.test(tree.trim()))
205
+ throw new Error(`git merge-tree returned no tree (${result.stderr.trim()})`);
206
+ if (result.exitCode === 1 && unmerged.length === 0)
207
+ throw new Error("git merge-tree reported a conflict without conflict stages");
208
+ return { tree: tree.trim(), unmerged };
209
+ }
210
+ /**
211
+ * Turns a clean worktree at `from` into the tree `to` (files only; the caller sets the index): writes
212
+ * the paths `to` adds or changes and deletes the ones it drops. Returns how many paths changed.
213
+ */
214
+ async function writeWorktreeTree(git, worktreePath, from, to) {
215
+ const changes = await snapshotChanges(git, worktreePath, from, to);
126
216
  const tempDir = await makeWipTempDir();
127
217
  try {
128
218
  const snapshotIndex = git.with({ GIT_INDEX_FILE: path.join(tempDir, "snapshot.index") });
129
- await snapshotIndex.run(worktreePath, ["read-tree", commitSha]);
219
+ await snapshotIndex.run(worktreePath, ["read-tree", to]);
130
220
  const written = changes.filter(change => change.status !== "D").map(change => change.path);
131
221
  await snapshotIndex.runForPaths(worktreePath, ["checkout-index", "-f"], written, false);
132
222
  }
@@ -136,12 +226,6 @@ async function applySnapshot(git, worktreePath, candidate) {
136
226
  for (const change of changes.filter(entry => entry.status === "D")) {
137
227
  await fs.rm(path.join(worktreePath, change.path), { force: true });
138
228
  }
139
- await git.run(worktreePath, ["read-tree", `${commitSha}^2^{tree}`]);
140
- if (metadata.unmerged.length > 0)
141
- await restoreUnmergedEntries(git, worktreePath, metadata);
142
- if (metadata.mergeHead)
143
- await writeMergeState(git, worktreePath, metadata);
144
- await git.tryRun(worktreePath, ["update-index", "-q", "--refresh"]);
145
229
  return changes.length;
146
230
  }
147
231
  async function snapshotChanges(git, worktreePath, base, commitSha) {
@@ -152,13 +236,16 @@ async function snapshotChanges(git, worktreePath, base, commitSha) {
152
236
  }
153
237
  return changes;
154
238
  }
155
- /** Puts the conflict stages back, so a half-done merge resumes exactly where it stopped. */
156
- async function restoreUnmergedEntries(git, worktreePath, metadata) {
157
- const zero = "0".repeat(metadata.baseHead.length);
158
- const conflicted = [...new Set(metadata.unmerged.map(entry => entry.path))];
239
+ /**
240
+ * Puts conflict stages into the index: a restored half-done merge resumes exactly where it stopped,
241
+ * and a conflicting re-apply is left unmerged for the agent.
242
+ */
243
+ async function writeUnmergedEntries(git, worktreePath, unmerged, hashLength) {
244
+ const zero = "0".repeat(hashLength);
245
+ const conflicted = [...new Set(unmerged.map(entry => entry.path))];
159
246
  const records = [
160
247
  ...conflicted.map(filePath => `0 ${zero} 0\t${filePath}`),
161
- ...metadata.unmerged.map(entry => `${entry.mode} ${entry.sha} ${entry.stage}\t${entry.path}`),
248
+ ...unmerged.map(entry => `${entry.mode} ${entry.sha} ${entry.stage}\t${entry.path}`),
162
249
  ];
163
250
  await git.runWithInput(worktreePath, ["update-index", "-z", "--index-info"], `${records.join("\0")}\0`);
164
251
  }
@@ -168,13 +255,16 @@ async function writeMergeState(git, worktreePath, metadata) {
168
255
  if (metadata.mergeMode)
169
256
  await fs.writeFile(await gitPath(git, worktreePath, "MERGE_MODE"), `${metadata.mergeMode}\n`, "utf8");
170
257
  }
171
- /** Undoes a partial apply: the worktree was clean at the base before it started. */
172
- async function rollBack(git, worktreePath, candidate) {
258
+ /**
259
+ * Undoes a partial apply of `target` (the snapshot, or a re-apply's merged tree): the worktree was
260
+ * clean at `head` before it started.
261
+ */
262
+ async function rollBack(git, worktreePath, head, target) {
173
263
  for (const name of ["MERGE_HEAD", "MERGE_MSG", "MERGE_MODE"]) {
174
264
  await fs.rm(await gitPath(git, worktreePath, name), { force: true });
175
265
  }
176
- await git.run(worktreePath, ["read-tree", "--reset", "-u", candidate.metadata.baseHead]);
177
- const changes = await snapshotChanges(git, worktreePath, candidate.metadata.baseHead, candidate.commitSha);
266
+ await git.run(worktreePath, ["read-tree", "--reset", "-u", head]);
267
+ const changes = await snapshotChanges(git, worktreePath, head, target);
178
268
  for (const change of changes.filter(entry => entry.status === "A")) {
179
269
  await fs.rm(path.join(worktreePath, change.path), { force: true });
180
270
  }
@@ -6,8 +6,11 @@ export interface WipSnapshotRequest {
6
6
  readonly reason: WipSnapshotReason;
7
7
  readonly sessionId?: string | null;
8
8
  readonly lane?: string | null;
9
- /** Forge's attempt number for the story; unorderedWipAttempt until the server sends one. */
10
- readonly attempt?: number;
9
+ /**
10
+ * Forge's attempt number for the dispatch (sandbox.wipAttempt), stamped on the ref and metadata so
11
+ * the newest work wins on restore; without one (or out of range) the snapshot is attempt 0.
12
+ */
13
+ readonly attempt?: number | null;
11
14
  /** Whether a later pass may apply this snapshot by itself (wip-restore.ts). */
12
15
  readonly autoRestore: boolean;
13
16
  /** Overrides FORGE_WIP_SNAPSHOT_MAX_BYTES. */
@@ -1,7 +1,7 @@
1
1
  import fs from "node:fs/promises";
2
2
  import path from "node:path";
3
- import { baseTrackedForgePaths, gitPath, hasPartialRestoreMarker, isWipExcludedPath, makeWipTempDir, readOptionalFile, splitNul, WipGit, } from "./wip-git.js";
4
- import { formatWipCommitMessage, unorderedWipAttempt, WipPreservationError, wipMetadataSchema, wipRefId, wipRefName, wipSnapshotMaxBytes, } from "./wip-refs.js";
3
+ import { baseTrackedForgePaths, gitPath, hasPartialRestoreMarker, isWipExcludedPath, makeWipTempDir, readOptionalFile, readReapplyConflictRecord, splitNul, WipGit, } from "./wip-git.js";
4
+ import { formatWipCommitMessage, issuedWipAttempt, WipPreservationError, wipMetadataSchema, wipRefId, wipRefName, wipSnapshotMaxBytes, } from "./wip-refs.js";
5
5
  const mergeMessageLimit = 16 * 1024;
6
6
  // Snapshots this process already pushed, keyed by worktree: a guard that finds the same state
7
7
  // (for example the release right after a failed session's snapshot) does not push it twice. An
@@ -73,6 +73,8 @@ async function captureWorktree(request, context) {
73
73
  const base = (await git.run(cwd, ["rev-parse", "--verify", `${request.orphan?.baseRef ?? "HEAD"}^{commit}`])).trim();
74
74
  const baseTree = (await git.run(cwd, ["rev-parse", `${base}^{tree}`])).trim();
75
75
  const merge = request.orphan ? null : await readMergeState(git, cwd);
76
+ const unmerged = request.orphan ? [] : splitNul(await git.run(cwd, ["ls-files", "-u", "-z"])).map(parseUnmergedEntry);
77
+ const reapplyConflicts = request.orphan ? [] : await readReapplyConflictRecord(git, cwd);
76
78
  const forgePaths = await baseTrackedForgePaths(git, cwd, base);
77
79
  const excluded = (filePath) => isWipExcludedPath(filePath, forgePaths);
78
80
  const worktreeIndex = path.join(context.tempDir, "worktree.index");
@@ -83,13 +85,13 @@ async function captureWorktree(request, context) {
83
85
  await copyIndex(worktreeIndex, stagedIndex);
84
86
  const indexTree = request.orphan
85
87
  ? baseTree
86
- : await writeStagedTree(git.with({ GIT_INDEX_FILE: stagedIndex }), cwd, base, merge, excluded);
88
+ : await writeStagedTree(git.with({ GIT_INDEX_FILE: stagedIndex }), cwd, base, unmerged, excluded);
87
89
  await indexGit.run(cwd, ["add", "-A"]);
88
90
  const changed = await resetExcluded(indexGit, cwd, base, excluded);
89
91
  const worktreeTree = (await indexGit.run(cwd, ["write-tree"])).trim();
90
- if (worktreeTree === baseTree && indexTree === baseTree && !merge)
92
+ if (worktreeTree === baseTree && indexTree === baseTree && !merge && unmerged.length === 0)
91
93
  return null;
92
- return { base, worktreeTree, indexTree, merge, changedPaths: changed.length, bytes };
94
+ return { base, worktreeTree, indexTree, merge, unmerged, reapplyConflicts, changedPaths: changed.length, bytes };
93
95
  }
94
96
  /** A copy of the worktree's real index; the base tree when it has none or the checkout is orphaned. */
95
97
  async function seedIndex(context, request, base, target) {
@@ -143,8 +145,8 @@ async function measureChanges(git, cwd, base, excluded, maxBytes) {
143
145
  return total;
144
146
  }
145
147
  /** The staged state: the real index with unresolved conflicts and runtime output put back to the base. */
146
- async function writeStagedTree(git, cwd, base, merge, excluded) {
147
- const conflicted = [...new Set((merge?.unmerged ?? []).map(entry => entry.path))];
148
+ async function writeStagedTree(git, cwd, base, unmerged, excluded) {
149
+ const conflicted = [...new Set(unmerged.map(entry => entry.path))];
148
150
  await git.runForPaths(cwd, ["reset", "-q", base], conflicted);
149
151
  await resetExcluded(git, cwd, base, excluded);
150
152
  return (await git.run(cwd, ["write-tree"])).trim();
@@ -165,12 +167,10 @@ async function readMergeState(git, cwd) {
165
167
  return null;
166
168
  const message = await readOptionalFile(await gitPath(git, cwd, "MERGE_MSG"));
167
169
  const mode = await readOptionalFile(await gitPath(git, cwd, "MERGE_MODE"));
168
- const unmerged = splitNul(await git.run(cwd, ["ls-files", "-u", "-z"])).map(parseUnmergedEntry);
169
170
  return {
170
171
  head,
171
172
  message: message === null ? null : message.slice(0, mergeMessageLimit),
172
173
  mode: mode?.trim() || null,
173
- unmerged,
174
174
  };
175
175
  }
176
176
  function parseUnmergedEntry(record) {
@@ -191,14 +191,15 @@ async function writeSnapshotCommits(request, capture, context) {
191
191
  sessionId: request.sessionId?.trim() || null,
192
192
  lane: request.lane?.trim() || null,
193
193
  reason: request.reason,
194
- attempt: request.attempt ?? unorderedWipAttempt,
194
+ attempt: issuedWipAttempt(request.attempt),
195
195
  autoRestore: request.autoRestore,
196
196
  createdAt: now.toISOString(),
197
197
  createdAtMs: now.getTime(),
198
198
  mergeHead: capture.merge?.head ?? null,
199
199
  mergeMessage: capture.merge?.message ?? null,
200
200
  mergeMode: capture.merge?.mode ?? null,
201
- unmerged: capture.merge?.unmerged ?? [],
201
+ unmerged: capture.unmerged,
202
+ reapplyConflicts: capture.reapplyConflicts,
202
203
  changedPaths: capture.changedPaths,
203
204
  bytes: capture.bytes,
204
205
  };
@@ -214,7 +215,7 @@ async function writeSnapshotCommits(request, capture, context) {
214
215
  */
215
216
  async function publishSnapshot(git, repoPath, request, commitSha) {
216
217
  const now = (request.now ?? (() => new Date()))();
217
- const ref = wipRefName(request.branchName, wipRefId(request.reason, request.sessionId, now, request.attempt));
218
+ const ref = wipRefName(request.branchName, wipRefId(request.reason, request.sessionId, now, issuedWipAttempt(request.attempt)));
218
219
  const origin = (await git.tryRun(repoPath, ["remote", "get-url", "origin"]))?.trim();
219
220
  if (!origin) {
220
221
  await git.run(repoPath, ["update-ref", ref, commitSha]);
@@ -239,7 +240,8 @@ async function commonGitDir(git, repoPath) {
239
240
  return path.isAbsolute(raw) ? raw : path.resolve(repoPath, raw);
240
241
  }
241
242
  function captureFingerprint(capture) {
242
- return [capture.base, capture.worktreeTree, capture.indexTree, capture.merge?.head ?? ""].join(":");
243
+ const stages = capture.unmerged.map(entry => `${entry.stage}${entry.sha}${entry.path}`).join(",");
244
+ return [capture.base, capture.worktreeTree, capture.indexTree, capture.merge?.head ?? "", stages, capture.reapplyConflicts.join(",")].join(":");
243
245
  }
244
246
  function snapshotKey(worktreePath) {
245
247
  const resolved = path.resolve(worktreePath);
@@ -9,6 +9,7 @@ export interface ReusedWorktreeSyncRequest {
9
9
  readonly branchName: string;
10
10
  readonly sessionId?: string | null;
11
11
  readonly lane: string;
12
+ readonly wipAttempt?: number | null;
12
13
  readonly log: BridgeLog;
13
14
  }
14
15
  /**
@@ -44,6 +44,7 @@ export async function syncReusedWorktreeToOrigin(request) {
44
44
  reason: "pre_sync",
45
45
  sessionId: request.sessionId,
46
46
  lane: request.lane,
47
+ attempt: request.wipAttempt,
47
48
  // It was based on the old head, so a later pass must never apply it on the new one by itself.
48
49
  autoRestore: false,
49
50
  }).catch((error) => {
@@ -3,7 +3,10 @@ export async function emitWipRestoreEvent(worktree, emit) {
3
3
  const outcome = worktree.wipRestore;
4
4
  if (!outcome || outcome.status === "none")
5
5
  return;
6
- if (outcome.status === "restored") {
6
+ if (outcome.status === "restored" && outcome.reapplied) {
7
+ await emit(checkpoint("worktree_wip_restored", reappliedSummary(worktree.branchName, outcome, outcome.reapplied), outcome));
8
+ }
9
+ else if (outcome.status === "restored") {
7
10
  await emit(checkpoint("worktree_wip_restored", `Restored uncommitted work saved in ${outcome.ref}${outcome.sourceSessionId ? ` by session ${outcome.sourceSessionId}` : ""} `
8
11
  + `(${outcome.changedPaths} path(s)${outcome.mergeInProgress ? ", with its merge still in progress" : ""}) onto ${worktree.branchName} before the provider started.`, outcome));
9
12
  }
@@ -18,6 +21,20 @@ export async function emitWipRestoreEvent(worktree, emit) {
18
21
  await emit(checkpoint("worktree_wip_restore_unavailable", `Could not check origin for saved uncommitted work on ${worktree.branchName}: ${outcome.detail}`, outcome));
19
22
  }
20
23
  }
24
+ /** The checkpoint for a snapshot re-applied across a branch move: clean, or with the paths left for the agent. */
25
+ function reappliedSummary(branchName, outcome, reapplied) {
26
+ const moved = `${branchName} had moved from ${reapplied.snapshotBaseHead.slice(0, 12)} to ${outcome.baseHead.slice(0, 12)} since it was saved`;
27
+ if (reapplied.conflictedPaths.length === 0) {
28
+ return `Re-applied the uncommitted work saved in ${outcome.ref} across a branch move (${moved}): a 3-way merge onto the new HEAD `
29
+ + `was clean (${outcome.changedPaths} path(s)) and is restored before the provider started.`;
30
+ }
31
+ const listed = reapplied.conflictedPaths.slice(0, maxListedConflicts).join(", ");
32
+ const more = reapplied.conflictedPaths.length > maxListedConflicts ? ` and ${reapplied.conflictedPaths.length - maxListedConflicts} more` : "";
33
+ return `Re-applied the uncommitted work saved in ${outcome.ref} across a branch move with ${reapplied.conflictedPaths.length} conflict(s) `
34
+ + `left for the agent to resolve: ${listed}${more}. ${moved}; the conflicted paths are unmerged with conflict markers, `
35
+ + `Forge will not publish them unresolved, and the ref is kept on origin.`;
36
+ }
37
+ const maxListedConflicts = 20;
21
38
  /** How a session ended, for the snapshot it leaves behind. */
22
39
  export function sessionWipOutcome(signal, events, succeeded) {
23
40
  if (succeeded)
@@ -72,7 +89,7 @@ async function emitSettlement(worktree, outcome, settlement, emit) {
72
89
  const snapshot = settlement.snapshot;
73
90
  if (snapshot && snapshot.status !== "clean") {
74
91
  await emit(checkpoint("worktree_wip_saved", `Saved this session's uncommitted work (${snapshot.changedPaths} path(s)) to ${snapshot.ref}${snapshot.pushed ? " on origin" : " in the runner's repository (it has no origin)"} `
75
- + `before the session ended (${outcome.reason}). The next pass on ${worktree.branchName} restores it when the branch has not moved.`, { ...snapshot, reason: outcome.reason, lane: worktree.lane ?? null }));
92
+ + `before the session ended (${outcome.reason}). The next pass on ${worktree.branchName} restores it, re-applying it if the branch has moved.`, { ...snapshot, reason: outcome.reason, lane: worktree.lane ?? null }));
76
93
  }
77
94
  if (settlement.error) {
78
95
  await emit({
@@ -11,6 +11,7 @@ export { relinkOrphanedWorktree } from "./orphan-relink.js";
11
11
  export declare function guardWorktreeReset(worktreePath: string, branchName: string, owner: {
12
12
  readonly sessionId?: string | null;
13
13
  readonly lane: string;
14
+ readonly wipAttempt?: number | null;
14
15
  }): Promise<WipSnapshotResult>;
15
16
  /**
16
17
  * Before a local branch is re-pointed at a new start point (`worktree add -B`), saves any commits
@@ -8,7 +8,8 @@ import { forgetPreservedWip, forgetPreservedWipRef, preserveWorktreeWip } from "
8
8
  // - every path that could destroy it (a reset to the base, re-pointing the branch, a release that
9
9
  // deletes the checkout) saves it to a WIP ref first and does not run when that fails;
10
10
  // - a session that ends without succeeding saves it under the session's id;
11
- // - a publishing lane's next pass puts the newest snapshot back when the branch has not moved;
11
+ // - a publishing lane's next pass puts the newest snapshot back, re-applying it with a 3-way merge
12
+ // when the branch has moved since (wip-restore.ts);
12
13
  // - a checkout that lost only its `.git` link is reattached to Git's admin directory for it, which
13
14
  // holds its index and MERGE_HEAD, instead of being recreated (orphan-relink.ts).
14
15
  export { relinkOrphanedWorktree } from "./orphan-relink.js";
@@ -30,6 +31,7 @@ export async function guardWorktreeReset(worktreePath, branchName, owner) {
30
31
  reason: "pre_reset",
31
32
  sessionId: owner.sessionId,
32
33
  lane: owner.lane,
34
+ attempt: owner.wipAttempt,
33
35
  autoRestore: isWipRestoreLane(owner.lane),
34
36
  });
35
37
  }
@@ -84,6 +86,7 @@ async function branchTipSnapshot(repoPath, branchName, tip, now) {
84
86
  mergeMessage: null,
85
87
  mergeMode: null,
86
88
  unmerged: [],
89
+ reapplyConflicts: [],
87
90
  changedPaths: 0,
88
91
  bytes: 0,
89
92
  });
@@ -110,6 +113,7 @@ export async function guardWorktreeRelease(handle) {
110
113
  reason: "pre_release",
111
114
  sessionId: handle.sessionId,
112
115
  lane: handle.lane,
116
+ attempt: handle.wipAttempt,
113
117
  autoRestore: false,
114
118
  });
115
119
  }
@@ -134,6 +138,7 @@ export async function settleSessionWip(handle, outcome) {
134
138
  reason: outcome.reason,
135
139
  sessionId: handle.sessionId,
136
140
  lane: handle.lane,
141
+ attempt: handle.wipAttempt,
137
142
  autoRestore: isWipRestoreLane(handle.lane),
138
143
  });
139
144
  }
@@ -105,6 +105,7 @@ export class GitWorktreeService {
105
105
  hydratedPriorPhaseArtifactCount,
106
106
  sessionId: request.sessionId ?? null,
107
107
  lane: request.lane,
108
+ wipAttempt: request.wipAttempt ?? null,
108
109
  ...preparedState,
109
110
  };
110
111
  }
@@ -168,6 +169,7 @@ export class GitWorktreeService {
168
169
  branchName,
169
170
  sessionId: request.sessionId,
170
171
  lane: request.lane,
172
+ wipAttempt: request.wipAttempt,
171
173
  log: this.log,
172
174
  });
173
175
  }
@@ -26,6 +26,8 @@ export interface WorktreePrepareRequest {
26
26
  readonly preserveExistingState?: boolean;
27
27
  /** The session this worktree is prepared for; names its WIP snapshots and enables restoring one. */
28
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;
29
31
  /** The attempt dependency installs reserve host capacity for (decision 0013). */
30
32
  readonly hostLoadOwner?: {
31
33
  readonly dispatchAttemptId: string | null;
@@ -45,6 +47,8 @@ export interface WorktreeHandle {
45
47
  readonly hydratedPriorPhaseArtifactCount?: number;
46
48
  readonly sessionId?: string | null;
47
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;
48
52
  /** What happened to the story's saved WIP when this worktree was prepared. */
49
53
  readonly wipRestore?: WipRestoreOutcome;
50
54
  /** Set when prepare moved a stale local branch or reused worktree up to origin's head. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@loucompanion/forge-bridge",
3
- "version": "0.2.1-dev.4f11ffc822f9",
3
+ "version": "0.2.1-dev.eac6976df5e9",
4
4
  "description": "Forge runner bridge CLI for connecting local developer machines to Forge dispatch.",
5
5
  "license": "UNLICENSED",
6
6
  "type": "module",