@loucompanion/forge-bridge 0.2.1-dev.c3166221b6e7 → 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 (39) hide show
  1. package/dist/bridge/bridge-chat-giphy-look.d.ts +48 -0
  2. package/dist/bridge/bridge-chat-giphy-look.js +55 -0
  3. package/dist/bridge/bridge-chat-provider-command.d.ts +22 -1
  4. package/dist/bridge/bridge-chat-provider-command.js +102 -4
  5. package/dist/bridge/bridge-chat.types.d.ts +10 -0
  6. package/dist/bridge/bridge-chat.types.js +12 -0
  7. package/dist/bridge/bridge.service.d.ts +2 -0
  8. package/dist/bridge/bridge.service.js +11 -31
  9. package/dist/runtime/host-load-admission.d.ts +5 -0
  10. package/dist/runtime/host-load-governor-config.d.ts +10 -1
  11. package/dist/runtime/host-load-governor-config.js +4 -1
  12. package/dist/runtime/host-load-governor.d.ts +8 -1
  13. package/dist/runtime/host-load-governor.js +33 -3
  14. package/dist/runtime/host-load-test-slot.js +7 -0
  15. package/dist/sandbox/runtime.js +1 -1
  16. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +6 -3
  17. package/dist/session/provider-cli/provider-cli.merge-integrity.js +28 -8
  18. package/dist/session/sandbox-host-capacity-gate.js +1 -1
  19. package/dist/session/session.service.js +8 -4
  20. package/dist/session/session.types.d.ts +1 -0
  21. package/dist/session/session.types.js +2 -2
  22. package/dist/version.d.ts +1 -1
  23. package/dist/version.js +1 -1
  24. package/dist/worktree/wip-git.d.ts +9 -0
  25. package/dist/worktree/wip-git.js +21 -4
  26. package/dist/worktree/wip-refs.d.ts +15 -0
  27. package/dist/worktree/wip-refs.js +29 -2
  28. package/dist/worktree/wip-restore.d.ts +8 -0
  29. package/dist/worktree/wip-restore.js +115 -25
  30. package/dist/worktree/wip-snapshot.d.ts +5 -2
  31. package/dist/worktree/wip-snapshot.js +15 -13
  32. package/dist/worktree/worktree-origin-sync.d.ts +1 -0
  33. package/dist/worktree/worktree-origin-sync.js +1 -0
  34. package/dist/worktree/worktree-wip-events.js +19 -2
  35. package/dist/worktree/worktree-wip.d.ts +1 -0
  36. package/dist/worktree/worktree-wip.js +6 -1
  37. package/dist/worktree/worktree.service.js +2 -0
  38. package/dist/worktree/worktree.types.d.ts +4 -0
  39. package/package.json +1 -1
@@ -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.c3166221b6e7";
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.c3166221b6e7";
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. */