@loucompanion/forge-bridge 0.2.1-dev.17ad6c965e41 → 0.2.1-dev.1a5cf93b48a1
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.
- package/dist/bridge/bridge-chat-giphy-look.d.ts +48 -0
- package/dist/bridge/bridge-chat-giphy-look.js +55 -0
- package/dist/bridge/bridge-chat-provider-command.d.ts +22 -1
- package/dist/bridge/bridge-chat-provider-command.js +102 -4
- package/dist/bridge/bridge-chat.types.d.ts +10 -0
- package/dist/bridge/bridge-chat.types.js +12 -0
- package/dist/bridge/bridge.service.d.ts +2 -0
- package/dist/bridge/bridge.service.js +11 -31
- package/dist/runtime/attempt-node-runtime-launcher.d.ts +36 -0
- package/dist/runtime/attempt-node-runtime-launcher.js +160 -0
- package/dist/runtime/host-listener-inspector.d.ts +26 -0
- package/dist/runtime/host-listener-inspector.js +84 -3
- package/dist/runtime/host-runtime-lease.d.ts +25 -2
- package/dist/runtime/host-runtime-lease.js +105 -137
- package/dist/runtime/host-runtime-promotion.d.ts +78 -2
- package/dist/runtime/host-runtime-promotion.js +307 -14
- package/dist/runtime/prepared-runtime-identity.d.ts +4 -0
- package/dist/runtime/prepared-runtime-identity.js +130 -9
- package/dist/runtime/prepared-runtime-readiness.d.ts +13 -1
- package/dist/runtime/prepared-runtime-readiness.js +63 -16
- package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +6 -3
- package/dist/session/provider-cli/provider-cli.merge-integrity.js +28 -8
- package/dist/session/session.service.d.ts +4 -0
- package/dist/session/session.service.js +62 -24
- package/dist/session/session.types.d.ts +1 -0
- package/dist/session/session.types.js +2 -2
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/dist/worktree/wip-git.d.ts +9 -0
- package/dist/worktree/wip-git.js +21 -4
- package/dist/worktree/wip-refs.d.ts +15 -0
- package/dist/worktree/wip-refs.js +29 -2
- package/dist/worktree/wip-restore.d.ts +8 -0
- package/dist/worktree/wip-restore.js +115 -25
- package/dist/worktree/wip-snapshot.d.ts +5 -2
- package/dist/worktree/wip-snapshot.js +15 -13
- package/dist/worktree/worktree-origin-sync.d.ts +1 -0
- package/dist/worktree/worktree-origin-sync.js +1 -0
- package/dist/worktree/worktree-wip-events.js +19 -2
- package/dist/worktree/worktree-wip.d.ts +1 -0
- package/dist/worktree/worktree-wip.js +6 -1
- package/dist/worktree/worktree.service.js +2 -0
- package/dist/worktree/worktree.types.d.ts +4 -0
- package/package.json +1 -1
- package/runtime/windows-listener-owner.ps1 +12 -1
|
@@ -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>;
|
package/dist/worktree/wip-git.js
CHANGED
|
@@ -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
|
-
|
|
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
|
|
11
|
-
//
|
|
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
|
-
|
|
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 =
|
|
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
|
-
/**
|
|
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
|
|
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
|
|
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",
|
|
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
|
-
/**
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
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
|
-
...
|
|
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
|
-
/**
|
|
172
|
-
|
|
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",
|
|
177
|
-
const changes = await snapshotChanges(git, worktreePath,
|
|
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
|
-
/**
|
|
10
|
-
|
|
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,
|
|
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,
|
|
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,
|
|
147
|
-
const conflicted = [...new Set(
|
|
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
|
|
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.
|
|
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
|
-
|
|
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);
|
|
@@ -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
|
|
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
|
|
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
|
}
|