@loucompanion/forge-bridge 0.1.4-dev.f22f5e3d01fe → 0.2.1-dev.0fedbc5c9ef7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +89 -1
- 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 +27 -3
- package/dist/bridge/bridge-chat-provider-command.js +131 -26
- package/dist/bridge/bridge-chat.types.d.ts +20 -0
- package/dist/bridge/bridge-chat.types.js +28 -1
- package/dist/bridge/bridge-state-file.d.ts +161 -0
- package/dist/bridge/bridge-state-file.js +376 -0
- package/dist/bridge/bridge-state-io.d.ts +11 -0
- package/dist/bridge/bridge-state-io.js +50 -0
- package/dist/bridge/bridge-state-lock.d.ts +11 -0
- package/dist/bridge/bridge-state-lock.js +102 -0
- package/dist/bridge/bridge-state-unpublished.d.ts +17 -0
- package/dist/bridge/bridge-state-unpublished.js +111 -0
- package/dist/bridge/bridge.service.d.ts +19 -12
- package/dist/bridge/bridge.service.js +155 -282
- package/dist/bridge/bridge.types.d.ts +5 -0
- package/dist/bridge/in-flight-registry.d.ts +62 -0
- package/dist/bridge/in-flight-registry.js +207 -0
- package/dist/bridge/readiness-result-outbox.d.ts +5 -1
- package/dist/bridge/readiness-result-outbox.js +20 -0
- package/dist/bridge/runner-host-capabilities.js +14 -1
- package/dist/bridge/sandbox-resource-accounting.d.ts +16 -0
- package/dist/bridge/sandbox-resource-accounting.js +150 -0
- package/dist/bridge/windows-bash-resolution.d.ts +31 -0
- package/dist/bridge/windows-bash-resolution.js +153 -0
- package/dist/cleanup/cleanup-wip.d.ts +12 -0
- package/dist/cleanup/cleanup-wip.js +66 -0
- package/dist/cleanup/cleanup.service.d.ts +11 -1
- package/dist/cleanup/cleanup.service.js +80 -62
- package/dist/cleanup/cleanup.types.d.ts +2 -0
- package/dist/cleanup/host-runtime-ledger.d.ts +2 -0
- package/dist/cleanup/host-runtime-ledger.js +30 -9
- package/dist/cli/cli.help.js +56 -12
- package/dist/cli/cli.service.d.ts +3 -10
- package/dist/cli/cli.service.js +10 -171
- package/dist/cli/idle-status.d.ts +84 -0
- package/dist/cli/idle-status.js +181 -0
- package/dist/cli/local-config.d.ts +2 -0
- package/dist/cli/local-config.js +7 -1
- package/dist/cli/provider-cli-detection.d.ts +10 -0
- package/dist/cli/provider-cli-detection.js +160 -0
- package/dist/runtime/aspnet-runtime-prebuild.d.ts +20 -0
- package/dist/runtime/aspnet-runtime-prebuild.js +104 -26
- package/dist/runtime/attempt-database-broker.d.ts +1 -1
- package/dist/runtime/attempt-node-runtime-launcher.d.ts +36 -0
- package/dist/runtime/attempt-node-runtime-launcher.js +169 -0
- package/dist/runtime/attempt-process-supervisor.d.ts +2 -0
- package/dist/runtime/attempt-process-supervisor.js +12 -6
- package/dist/runtime/docker-engine-probe.d.ts +5 -0
- package/dist/runtime/docker-engine-probe.js +7 -0
- package/dist/runtime/dotnet-build-outputs.d.ts +107 -0
- package/dist/runtime/dotnet-build-outputs.js +402 -0
- package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
- package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
- package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
- package/dist/runtime/ephemeral-test-postgres.js +303 -0
- package/dist/runtime/host-listener-inspector.d.ts +26 -0
- package/dist/runtime/host-listener-inspector.js +84 -3
- package/dist/runtime/host-load-admission.d.ts +5 -0
- package/dist/runtime/host-load-governor-config.d.ts +10 -1
- package/dist/runtime/host-load-governor-config.js +4 -1
- package/dist/runtime/host-load-governor.d.ts +10 -1
- package/dist/runtime/host-load-governor.js +33 -3
- package/dist/runtime/host-load-ledger-lock.js +6 -4
- package/dist/runtime/host-load-runtime-settings.js +4 -2
- package/dist/runtime/host-load-sampler.d.ts +8 -1
- package/dist/runtime/host-load-sampler.js +14 -7
- package/dist/runtime/host-load-test-slot.js +7 -0
- package/dist/runtime/host-runtime-contract.d.ts +12 -0
- package/dist/runtime/host-runtime-contract.js +29 -1
- package/dist/runtime/host-runtime-lease.d.ts +28 -3
- package/dist/runtime/host-runtime-lease.js +140 -296
- package/dist/runtime/host-runtime-ledger-recovery.d.ts +20 -0
- package/dist/runtime/host-runtime-ledger-recovery.js +134 -0
- package/dist/runtime/host-runtime-promotion.d.ts +78 -2
- package/dist/runtime/host-runtime-promotion.js +307 -14
- package/dist/runtime/managed-command-teardown.js +5 -16
- package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
- package/dist/runtime/native-test-postgres-fallback.js +60 -8
- 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/runtime/runner-settings.d.ts +4 -0
- package/dist/runtime/runner-settings.js +22 -0
- package/dist/runtime/supervised-runtime-build-guard.d.ts +45 -0
- package/dist/runtime/supervised-runtime-build-guard.js +112 -0
- package/dist/sandbox/host-capacity-broker.d.ts +3 -1
- package/dist/sandbox/host-capacity-broker.js +4 -2
- package/dist/sandbox/managed-branch.d.ts +13 -0
- package/dist/sandbox/managed-branch.js +90 -0
- package/dist/sandbox/provider-auth/codex.js +11 -11
- package/dist/sandbox/runtime.js +3 -7
- package/dist/session/managed-attempt-tools.d.ts +0 -7
- package/dist/session/managed-attempt-tools.js +50 -82
- package/dist/session/managed-build-coordinator.d.ts +16 -0
- package/dist/session/managed-build-coordinator.js +10 -0
- package/dist/session/managed-build-receipt.d.ts +5 -0
- package/dist/session/managed-build-receipt.js +8 -3
- package/dist/session/phase-completion.artifacts.js +2 -1
- package/dist/session/phase-completion.d.ts +8 -0
- package/dist/session/phase-completion.js +1 -0
- package/dist/session/phase-completion.mcp-args.d.ts +9 -0
- package/dist/session/phase-completion.mcp-args.js +156 -0
- package/dist/session/phase-completion.runtime.d.ts +0 -8
- package/dist/session/phase-completion.runtime.js +43 -197
- package/dist/session/pre-publication-native-postgres.d.ts +30 -0
- package/dist/session/pre-publication-native-postgres.js +111 -0
- package/dist/session/pre-publication-process.js +10 -10
- package/dist/session/pre-publication-step-execution.d.ts +2 -1
- package/dist/session/pre-publication-step-execution.js +6 -5
- package/dist/session/pre-publication-validation.d.ts +7 -3
- package/dist/session/pre-publication-validation.js +32 -30
- package/dist/session/provider-cli/claude-background-work.d.ts +3 -2
- package/dist/session/provider-cli/claude-background-work.js +4 -3
- package/dist/session/provider-cli/host-build-lock.d.ts +18 -0
- package/dist/session/provider-cli/host-build-lock.js +30 -0
- package/dist/session/provider-cli/pre-publication-repair.d.ts +16 -0
- package/dist/session/provider-cli/pre-publication-repair.js +33 -0
- package/dist/session/provider-cli/provider-cli.child-environment.js +4 -2
- 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/provider-cli/provider-cli.process.d.ts +2 -14
- package/dist/session/provider-cli/provider-cli.process.js +4 -94
- package/dist/session/provider-cli/provider-cli.prompts.d.ts +3 -0
- package/dist/session/provider-cli/provider-cli.prompts.js +27 -27
- package/dist/session/provider-cli/provider-cli.runtime.d.ts +8 -0
- package/dist/session/provider-cli/provider-cli.runtime.js +23 -2
- package/dist/session/provider-cli/provider-cli.service.d.ts +4 -1
- package/dist/session/provider-cli/provider-cli.service.js +27 -43
- package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
- package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
- package/dist/session/provider-cli/provider-user-config-isolation.d.ts +69 -0
- package/dist/session/provider-cli/provider-user-config-isolation.js +164 -0
- package/dist/session/qa-sidecar-validation.d.ts +6 -0
- package/dist/session/qa-sidecar-validation.js +28 -0
- package/dist/session/sandbox-host-capacity-gate.d.ts +22 -1
- package/dist/session/sandbox-host-capacity-gate.js +35 -16
- package/dist/session/session-redaction.js +31 -181
- package/dist/session/session.service.d.ts +6 -0
- package/dist/session/session.service.js +131 -88
- package/dist/session/session.types.d.ts +1 -0
- package/dist/session/session.types.js +3 -3
- package/dist/session/sidecar-json-shape.d.ts +31 -0
- package/dist/session/sidecar-json-shape.js +217 -0
- package/dist/shared/fs/file-identity.d.ts +10 -0
- package/dist/shared/fs/file-identity.js +15 -0
- package/dist/shared/fs/replace-file.d.ts +7 -0
- package/dist/shared/fs/replace-file.js +33 -0
- package/dist/shared/process/host-process-recovery.d.ts +14 -3
- package/dist/shared/process/host-process-recovery.js +23 -3
- package/dist/shared/process/host-process-supervisor.d.ts +13 -1
- package/dist/shared/process/host-process-supervisor.js +66 -14
- package/dist/shared/provider-capabilities.js +9 -1
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/dist/worktree/orphan-relink.d.ts +19 -0
- package/dist/worktree/orphan-relink.js +106 -0
- package/dist/worktree/wip-git.d.ts +42 -0
- package/dist/worktree/wip-git.js +139 -0
- package/dist/worktree/wip-refs.d.ts +77 -0
- package/dist/worktree/wip-refs.js +146 -0
- package/dist/worktree/wip-restore.d.ts +46 -0
- package/dist/worktree/wip-restore.js +280 -0
- package/dist/worktree/wip-snapshot.d.ts +53 -0
- package/dist/worktree/wip-snapshot.js +270 -0
- package/dist/worktree/worktree-inputs.d.ts +8 -0
- package/dist/worktree/worktree-inputs.js +134 -0
- package/dist/worktree/worktree-origin-sync.d.ts +35 -0
- package/dist/worktree/worktree-origin-sync.js +128 -0
- package/dist/worktree/worktree-wip-events.d.ts +18 -0
- package/dist/worktree/worktree-wip-events.js +115 -0
- package/dist/worktree/worktree-wip.d.ts +51 -0
- package/dist/worktree/worktree-wip.js +190 -0
- package/dist/worktree/worktree.base.d.ts +7 -1
- package/dist/worktree/worktree.service.d.ts +27 -5
- package/dist/worktree/worktree.service.js +112 -181
- package/dist/worktree/worktree.types.d.ts +35 -0
- package/package.json +1 -1
- package/runtime/windows-listener-owner.ps1 +12 -1
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import fs from "node:fs/promises";
|
|
3
|
+
import path from "node:path";
|
|
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
|
+
export async function restoreLatestWip(request) {
|
|
7
|
+
const git = new WipGit(request.processRunner);
|
|
8
|
+
let candidates;
|
|
9
|
+
try {
|
|
10
|
+
candidates = await listWipCandidates(git, request);
|
|
11
|
+
}
|
|
12
|
+
catch (error) {
|
|
13
|
+
return { status: "unavailable", detail: errorMessage(error) };
|
|
14
|
+
}
|
|
15
|
+
const newest = newestRestorable(candidates, request.branchName);
|
|
16
|
+
if (!newest)
|
|
17
|
+
return { status: "none" };
|
|
18
|
+
if (!await isCleanWorktree(git, request.worktreePath)) {
|
|
19
|
+
return { status: "skipped_dirty", ref: newest.ref, commitSha: newest.commitSha };
|
|
20
|
+
}
|
|
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.
|
|
23
|
+
await fs.rm(await partialRestoreMarkerPath(git, request.worktreePath), { force: true });
|
|
24
|
+
await writeReapplyConflictRecord(git, request.worktreePath, []);
|
|
25
|
+
const currentHead = (await git.run(request.worktreePath, ["rev-parse", "HEAD"])).trim();
|
|
26
|
+
const notRestored = (reason, detail) => ({
|
|
27
|
+
status: "not_restored", ref: newest.ref, commitSha: newest.commitSha, reason,
|
|
28
|
+
baseHead: newest.metadata.baseHead, currentHead, detail,
|
|
29
|
+
});
|
|
30
|
+
let plan = null;
|
|
31
|
+
if (newest.metadata.baseHead !== currentHead) {
|
|
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
|
+
}
|
|
42
|
+
}
|
|
43
|
+
try {
|
|
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)]);
|
|
49
|
+
return {
|
|
50
|
+
status: "restored",
|
|
51
|
+
ref: newest.ref,
|
|
52
|
+
commitSha: newest.commitSha,
|
|
53
|
+
baseHead: currentHead,
|
|
54
|
+
sourceSessionId: newest.metadata.sessionId,
|
|
55
|
+
changedPaths,
|
|
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,
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
catch (error) {
|
|
63
|
+
// A pass must never start on a half-applied snapshot: when the partial apply can't be undone,
|
|
64
|
+
// the prepare fails. Nothing is lost; the ref stays, and the next prepare saves this worktree
|
|
65
|
+
// before it resets it. That snapshot holds the mixed state, so it is marked never to be applied
|
|
66
|
+
// automatically (partialRestoreMarkerPath): the next pass restores the original ref instead.
|
|
67
|
+
await rollBack(git, request.worktreePath, currentHead, plan?.worktreeTree ?? newest.commitSha).catch(async (rollbackError) => {
|
|
68
|
+
await partialRestoreMarkerPath(git, request.worktreePath)
|
|
69
|
+
.then(marker => fs.writeFile(marker, `${newest.ref}\n`, "utf8"))
|
|
70
|
+
.catch(() => undefined);
|
|
71
|
+
throw new Error(`Could not apply ${newest.ref} to ${request.worktreePath} (${errorMessage(error)}), and could not undo the partial apply `
|
|
72
|
+
+ `(${errorMessage(rollbackError)}); the worktree is not in a known state, so the provider will not start on it.`, { cause: rollbackError });
|
|
73
|
+
});
|
|
74
|
+
return notRestored("apply_failed", errorMessage(error));
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
/** Deletes a WIP ref (on origin, or locally when there is no origin). Never throws. */
|
|
78
|
+
export async function deleteWipRef(repoPath, ref, processRunner) {
|
|
79
|
+
if (!ref.startsWith(`${wipRefRoot}/`))
|
|
80
|
+
return false;
|
|
81
|
+
const git = new WipGit(processRunner);
|
|
82
|
+
const origin = (await git.tryRun(repoPath, ["remote", "get-url", "origin"]))?.trim();
|
|
83
|
+
const deleted = origin
|
|
84
|
+
? await git.tryRun(repoPath, ["push", "--porcelain", "origin", `:${ref}`])
|
|
85
|
+
: await git.tryRun(repoPath, ["update-ref", "-d", ref]);
|
|
86
|
+
return deleted !== null;
|
|
87
|
+
}
|
|
88
|
+
/** Every snapshot for the branch: origin's (fetched into a private namespace) and any kept locally. */
|
|
89
|
+
async function listWipCandidates(git, request) {
|
|
90
|
+
const prefix = wipRefPrefix(request.branchName);
|
|
91
|
+
const staging = `refs/forge/wip-restore/${randomUUID()}/`;
|
|
92
|
+
const origin = (await git.tryRun(request.repoPath, ["remote", "get-url", "origin"]))?.trim();
|
|
93
|
+
try {
|
|
94
|
+
if (origin) {
|
|
95
|
+
await git.run(request.repoPath, ["fetch", "--no-tags", "--no-write-fetch-head", "origin", `+${prefix}*:${staging}*`]);
|
|
96
|
+
}
|
|
97
|
+
const fetched = await readRefs(git, request.repoPath, staging, prefix);
|
|
98
|
+
const local = await readRefs(git, request.repoPath, prefix, prefix);
|
|
99
|
+
const byRef = new Map([...local, ...fetched].map(candidate => [candidate.ref, candidate]));
|
|
100
|
+
return [...byRef.values()];
|
|
101
|
+
}
|
|
102
|
+
finally {
|
|
103
|
+
const staged = splitLines(await git.tryRun(request.repoPath, ["for-each-ref", "--format=%(refname)", staging]) ?? "");
|
|
104
|
+
for (const ref of staged)
|
|
105
|
+
await git.tryRun(request.repoPath, ["update-ref", "-d", ref]);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
async function readRefs(git, repoPath, namespace, wipPrefix) {
|
|
109
|
+
const listing = await git.run(repoPath, ["for-each-ref", "--format=%(refname) %(objectname)", namespace]);
|
|
110
|
+
const candidates = [];
|
|
111
|
+
for (const line of splitLines(listing)) {
|
|
112
|
+
const [refName, commitSha] = line.split(" ");
|
|
113
|
+
if (!refName || !commitSha)
|
|
114
|
+
continue;
|
|
115
|
+
const raw = await git.tryRun(repoPath, ["cat-file", "commit", commitSha]);
|
|
116
|
+
const metadata = raw === null ? null : parseWipCommitMessage(commitMessageOf(raw));
|
|
117
|
+
if (metadata)
|
|
118
|
+
candidates.push({ ref: `${wipPrefix}${refName.slice(namespace.length)}`, commitSha, metadata });
|
|
119
|
+
}
|
|
120
|
+
return candidates;
|
|
121
|
+
}
|
|
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
|
+
*/
|
|
127
|
+
function newestRestorable(candidates, branchName) {
|
|
128
|
+
const branch = branchRefName(branchName);
|
|
129
|
+
return [...candidates]
|
|
130
|
+
.filter(candidate => candidate.metadata.autoRestore && branchRefName(candidate.metadata.branch) === branch)
|
|
131
|
+
.sort((left, right) => candidateAttempt(right) - candidateAttempt(left)
|
|
132
|
+
|| right.metadata.createdAtMs - left.metadata.createdAtMs || right.ref.localeCompare(left.ref))[0]
|
|
133
|
+
?? null;
|
|
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
|
+
}
|
|
140
|
+
/** True when the worktree holds nothing a snapshot would save (Forge runtime output aside), and no merge. */
|
|
141
|
+
export async function hasNoUnsavedWork(worktreePath, processRunner) {
|
|
142
|
+
return await isCleanWorktree(new WipGit(processRunner), worktreePath);
|
|
143
|
+
}
|
|
144
|
+
async function isCleanWorktree(git, worktreePath) {
|
|
145
|
+
if (await git.tryRun(worktreePath, ["rev-parse", "-q", "--verify", "MERGE_HEAD"]) !== null)
|
|
146
|
+
return false;
|
|
147
|
+
const forgePaths = await baseTrackedForgePaths(git, worktreePath, "HEAD");
|
|
148
|
+
const status = splitNul(await git.run(worktreePath, ["status", "--porcelain=v1", "-z", "--untracked-files=all", "--no-renames"]));
|
|
149
|
+
return status.every(entry => isWipExcludedPath(entry.slice(3), forgePaths));
|
|
150
|
+
}
|
|
151
|
+
/** Writes the snapshot's files and index (and merge state) onto the clean worktree. */
|
|
152
|
+
async function applySnapshot(git, worktreePath, candidate) {
|
|
153
|
+
const { commitSha, metadata } = candidate;
|
|
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);
|
|
216
|
+
const tempDir = await makeWipTempDir();
|
|
217
|
+
try {
|
|
218
|
+
const snapshotIndex = git.with({ GIT_INDEX_FILE: path.join(tempDir, "snapshot.index") });
|
|
219
|
+
await snapshotIndex.run(worktreePath, ["read-tree", to]);
|
|
220
|
+
const written = changes.filter(change => change.status !== "D").map(change => change.path);
|
|
221
|
+
await snapshotIndex.runForPaths(worktreePath, ["checkout-index", "-f"], written, false);
|
|
222
|
+
}
|
|
223
|
+
finally {
|
|
224
|
+
await fs.rm(tempDir, { recursive: true, force: true }).catch(() => undefined);
|
|
225
|
+
}
|
|
226
|
+
for (const change of changes.filter(entry => entry.status === "D")) {
|
|
227
|
+
await fs.rm(path.join(worktreePath, change.path), { force: true });
|
|
228
|
+
}
|
|
229
|
+
return changes.length;
|
|
230
|
+
}
|
|
231
|
+
async function snapshotChanges(git, worktreePath, base, commitSha) {
|
|
232
|
+
const fields = splitNul(await git.run(worktreePath, ["diff-tree", "-r", "-z", "--no-renames", "--name-status", base, commitSha]));
|
|
233
|
+
const changes = [];
|
|
234
|
+
for (let index = 0; index + 1 < fields.length; index += 2) {
|
|
235
|
+
changes.push({ status: fields[index].trim(), path: fields[index + 1] });
|
|
236
|
+
}
|
|
237
|
+
return changes;
|
|
238
|
+
}
|
|
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))];
|
|
246
|
+
const records = [
|
|
247
|
+
...conflicted.map(filePath => `0 ${zero} 0\t${filePath}`),
|
|
248
|
+
...unmerged.map(entry => `${entry.mode} ${entry.sha} ${entry.stage}\t${entry.path}`),
|
|
249
|
+
];
|
|
250
|
+
await git.runWithInput(worktreePath, ["update-index", "-z", "--index-info"], `${records.join("\0")}\0`);
|
|
251
|
+
}
|
|
252
|
+
async function writeMergeState(git, worktreePath, metadata) {
|
|
253
|
+
await fs.writeFile(await gitPath(git, worktreePath, "MERGE_HEAD"), `${metadata.mergeHead}\n`, "utf8");
|
|
254
|
+
await fs.writeFile(await gitPath(git, worktreePath, "MERGE_MSG"), metadata.mergeMessage ?? `Merge ${metadata.mergeHead}\n`, "utf8");
|
|
255
|
+
if (metadata.mergeMode)
|
|
256
|
+
await fs.writeFile(await gitPath(git, worktreePath, "MERGE_MODE"), `${metadata.mergeMode}\n`, "utf8");
|
|
257
|
+
}
|
|
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) {
|
|
263
|
+
for (const name of ["MERGE_HEAD", "MERGE_MSG", "MERGE_MODE"]) {
|
|
264
|
+
await fs.rm(await gitPath(git, worktreePath, name), { force: true });
|
|
265
|
+
}
|
|
266
|
+
await git.run(worktreePath, ["read-tree", "--reset", "-u", head]);
|
|
267
|
+
const changes = await snapshotChanges(git, worktreePath, head, target);
|
|
268
|
+
for (const change of changes.filter(entry => entry.status === "A")) {
|
|
269
|
+
await fs.rm(path.join(worktreePath, change.path), { force: true });
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
function branchRefName(branchName) {
|
|
273
|
+
return branchName.trim().replace(/^refs\/heads\//u, "");
|
|
274
|
+
}
|
|
275
|
+
function splitLines(value) {
|
|
276
|
+
return value.split(/\r?\n/u).map(line => line.trim()).filter(Boolean);
|
|
277
|
+
}
|
|
278
|
+
function errorMessage(error) {
|
|
279
|
+
return error instanceof Error ? error.message : String(error);
|
|
280
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import type { ProcessRunner } from "../shared/process/process.js";
|
|
2
|
+
import { type WipSnapshotReason } from "./wip-refs.js";
|
|
3
|
+
export interface WipSnapshotRequest {
|
|
4
|
+
readonly worktreePath: string;
|
|
5
|
+
readonly branchName: string;
|
|
6
|
+
readonly reason: WipSnapshotReason;
|
|
7
|
+
readonly sessionId?: string | null;
|
|
8
|
+
readonly lane?: string | null;
|
|
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;
|
|
14
|
+
/** Whether a later pass may apply this snapshot by itself (wip-restore.ts). */
|
|
15
|
+
readonly autoRestore: boolean;
|
|
16
|
+
/** Overrides FORGE_WIP_SNAPSHOT_MAX_BYTES. */
|
|
17
|
+
readonly maxBytes?: number;
|
|
18
|
+
/**
|
|
19
|
+
* A checkout whose Git administrative directory is gone, so Git no longer knows its HEAD or
|
|
20
|
+
* index: it is read through the shared repository against `baseRef` instead.
|
|
21
|
+
*/
|
|
22
|
+
readonly orphan?: {
|
|
23
|
+
readonly repoPath: string;
|
|
24
|
+
readonly baseRef: string;
|
|
25
|
+
};
|
|
26
|
+
readonly processRunner?: ProcessRunner;
|
|
27
|
+
readonly now?: () => Date;
|
|
28
|
+
}
|
|
29
|
+
export type WipSnapshotResult = {
|
|
30
|
+
readonly status: "clean";
|
|
31
|
+
} | {
|
|
32
|
+
readonly status: "saved" | "already_saved";
|
|
33
|
+
readonly ref: string;
|
|
34
|
+
readonly commitSha: string;
|
|
35
|
+
readonly baseHead: string;
|
|
36
|
+
readonly changedPaths: number;
|
|
37
|
+
readonly bytes: number;
|
|
38
|
+
/** False when the repository has no origin and the ref was kept in the local repository. */
|
|
39
|
+
readonly pushed: boolean;
|
|
40
|
+
};
|
|
41
|
+
/**
|
|
42
|
+
* Saves the worktree's uncommitted work to a WIP ref. Returns `clean` (and pushes nothing) when
|
|
43
|
+
* there is nothing to save. Throws {@link WipPreservationError} when the work could not be saved,
|
|
44
|
+
* including when it is over the size cap: the caller must then not destroy the worktree.
|
|
45
|
+
*/
|
|
46
|
+
export declare function preserveWorktreeWip(requested: WipSnapshotRequest): Promise<WipSnapshotResult>;
|
|
47
|
+
/** Forgets what this process pushed for a worktree, e.g. once the worktree is gone. */
|
|
48
|
+
export declare function forgetPreservedWip(worktreePath: string): void;
|
|
49
|
+
/**
|
|
50
|
+
* Forgets every snapshot this process pushed to `ref`, before that ref is deleted: a later guard
|
|
51
|
+
* that finds the same state must push it again rather than report it saved in a ref that is gone.
|
|
52
|
+
*/
|
|
53
|
+
export declare function forgetPreservedWipRef(ref: string): void;
|
|
@@ -0,0 +1,270 @@
|
|
|
1
|
+
import fs from "node:fs/promises";
|
|
2
|
+
import path from "node:path";
|
|
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
|
+
const mergeMessageLimit = 16 * 1024;
|
|
6
|
+
// Snapshots this process already pushed, keyed by worktree: a guard that finds the same state
|
|
7
|
+
// (for example the release right after a failed session's snapshot) does not push it twice. An
|
|
8
|
+
// entry is reused only for the same branch, only when it is at least as restorable as the request
|
|
9
|
+
// asks for, and only while its ref still points at it (wip-snapshot cache checks below).
|
|
10
|
+
const savedSnapshots = new Map();
|
|
11
|
+
/**
|
|
12
|
+
* Saves the worktree's uncommitted work to a WIP ref. Returns `clean` (and pushes nothing) when
|
|
13
|
+
* there is nothing to save. Throws {@link WipPreservationError} when the work could not be saved,
|
|
14
|
+
* including when it is over the size cap: the caller must then not destroy the worktree.
|
|
15
|
+
*/
|
|
16
|
+
export async function preserveWorktreeWip(requested) {
|
|
17
|
+
const baseGit = new WipGit(requested.processRunner);
|
|
18
|
+
const git = requested.orphan
|
|
19
|
+
? baseGit.with({ GIT_DIR: await commonGitDir(baseGit, requested.orphan.repoPath), GIT_WORK_TREE: requested.worktreePath })
|
|
20
|
+
: baseGit;
|
|
21
|
+
// A half-applied restore is saved like any other state, but never for a later pass to apply.
|
|
22
|
+
const degraded = requested.autoRestore && !requested.orphan && await hasPartialRestoreMarker(git, requested.worktreePath);
|
|
23
|
+
const request = degraded ? { ...requested, autoRestore: false } : requested;
|
|
24
|
+
const repoPath = request.orphan?.repoPath ?? request.worktreePath;
|
|
25
|
+
const tempDir = await makeWipTempDir();
|
|
26
|
+
try {
|
|
27
|
+
const capture = await captureWorktree(request, { git, cwd: request.worktreePath, repoPath, tempDir })
|
|
28
|
+
.catch(error => { throw asPreservationError(error, "wip_snapshot_failed"); });
|
|
29
|
+
if (!capture)
|
|
30
|
+
return { status: "clean" };
|
|
31
|
+
const fingerprint = captureFingerprint(capture);
|
|
32
|
+
const cached = savedSnapshots.get(snapshotKey(request.worktreePath));
|
|
33
|
+
if (cached && await cachedSnapshotServes(baseGit, repoPath, cached, fingerprint, request)) {
|
|
34
|
+
const { fingerprint: _fingerprint, branchName: _branch, autoRestore: _autoRestore, ...saved } = cached;
|
|
35
|
+
return { ...saved, status: "already_saved" };
|
|
36
|
+
}
|
|
37
|
+
const commitSha = await writeSnapshotCommits(request, capture, { git, cwd: request.worktreePath, repoPath, tempDir })
|
|
38
|
+
.catch(error => { throw asPreservationError(error, "wip_snapshot_failed"); });
|
|
39
|
+
const published = await publishSnapshot(baseGit, repoPath, request, commitSha);
|
|
40
|
+
const result = {
|
|
41
|
+
status: "saved",
|
|
42
|
+
...published,
|
|
43
|
+
commitSha,
|
|
44
|
+
baseHead: capture.base,
|
|
45
|
+
changedPaths: capture.changedPaths,
|
|
46
|
+
bytes: capture.bytes,
|
|
47
|
+
};
|
|
48
|
+
savedSnapshots.set(snapshotKey(request.worktreePath), {
|
|
49
|
+
...result, fingerprint, branchName: request.branchName, autoRestore: request.autoRestore,
|
|
50
|
+
});
|
|
51
|
+
return result;
|
|
52
|
+
}
|
|
53
|
+
finally {
|
|
54
|
+
await fs.rm(tempDir, { recursive: true, force: true }).catch(() => undefined);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
/** Forgets what this process pushed for a worktree, e.g. once the worktree is gone. */
|
|
58
|
+
export function forgetPreservedWip(worktreePath) {
|
|
59
|
+
savedSnapshots.delete(snapshotKey(worktreePath));
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Forgets every snapshot this process pushed to `ref`, before that ref is deleted: a later guard
|
|
63
|
+
* that finds the same state must push it again rather than report it saved in a ref that is gone.
|
|
64
|
+
*/
|
|
65
|
+
export function forgetPreservedWipRef(ref) {
|
|
66
|
+
for (const [key, saved] of savedSnapshots) {
|
|
67
|
+
if (saved.ref === ref)
|
|
68
|
+
savedSnapshots.delete(key);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
async function captureWorktree(request, context) {
|
|
72
|
+
const { git, cwd } = context;
|
|
73
|
+
const base = (await git.run(cwd, ["rev-parse", "--verify", `${request.orphan?.baseRef ?? "HEAD"}^{commit}`])).trim();
|
|
74
|
+
const baseTree = (await git.run(cwd, ["rev-parse", `${base}^{tree}`])).trim();
|
|
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);
|
|
78
|
+
const forgePaths = await baseTrackedForgePaths(git, cwd, base);
|
|
79
|
+
const excluded = (filePath) => isWipExcludedPath(filePath, forgePaths);
|
|
80
|
+
const worktreeIndex = path.join(context.tempDir, "worktree.index");
|
|
81
|
+
await seedIndex(context, request, base, worktreeIndex);
|
|
82
|
+
const indexGit = git.with({ GIT_INDEX_FILE: worktreeIndex });
|
|
83
|
+
const bytes = await measureChanges(indexGit, cwd, base, excluded, request.maxBytes ?? wipSnapshotMaxBytes());
|
|
84
|
+
const stagedIndex = path.join(context.tempDir, "staged.index");
|
|
85
|
+
await copyIndex(worktreeIndex, stagedIndex);
|
|
86
|
+
const indexTree = request.orphan
|
|
87
|
+
? baseTree
|
|
88
|
+
: await writeStagedTree(git.with({ GIT_INDEX_FILE: stagedIndex }), cwd, base, unmerged, excluded);
|
|
89
|
+
await indexGit.run(cwd, ["add", "-A"]);
|
|
90
|
+
const changed = await resetExcluded(indexGit, cwd, base, excluded);
|
|
91
|
+
const worktreeTree = (await indexGit.run(cwd, ["write-tree"])).trim();
|
|
92
|
+
if (worktreeTree === baseTree && indexTree === baseTree && !merge && unmerged.length === 0)
|
|
93
|
+
return null;
|
|
94
|
+
return { base, worktreeTree, indexTree, merge, unmerged, reapplyConflicts, changedPaths: changed.length, bytes };
|
|
95
|
+
}
|
|
96
|
+
/** A copy of the worktree's real index; the base tree when it has none or the checkout is orphaned. */
|
|
97
|
+
async function seedIndex(context, request, base, target) {
|
|
98
|
+
if (!request.orphan) {
|
|
99
|
+
const realIndex = await gitPath(context.git, context.cwd, "index");
|
|
100
|
+
const copied = await copyIndex(realIndex, target).then(() => true, (error) => {
|
|
101
|
+
if (error.code === "ENOENT")
|
|
102
|
+
return false;
|
|
103
|
+
throw error;
|
|
104
|
+
});
|
|
105
|
+
if (copied)
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
await context.git.with({ GIT_INDEX_FILE: target }).run(context.cwd, ["read-tree", base]);
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Copies an index file with its modification time. Git treats an entry whose file changed in the
|
|
112
|
+
* same second the index was written as "racily clean" and compares its content; a copy stamped
|
|
113
|
+
* with a later time would hide such a change behind matching stat data (same size, same second).
|
|
114
|
+
*/
|
|
115
|
+
async function copyIndex(source, target) {
|
|
116
|
+
await fs.copyFile(source, target);
|
|
117
|
+
const stat = await fs.stat(source);
|
|
118
|
+
await fs.utimes(target, stat.atime, stat.mtime);
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* Sums the size of every changed file that would be saved and refuses a snapshot over the cap,
|
|
122
|
+
* before any of it is hashed into the object store.
|
|
123
|
+
*/
|
|
124
|
+
async function measureChanges(git, cwd, base, excluded, maxBytes) {
|
|
125
|
+
const [untracked, modified, staged] = await Promise.all([
|
|
126
|
+
git.run(cwd, ["ls-files", "-o", "--exclude-standard", "-z"]),
|
|
127
|
+
git.run(cwd, ["diff", "--name-only", "--no-renames", "-z"]),
|
|
128
|
+
git.run(cwd, ["diff", "--cached", "--name-only", "--no-renames", "-z", base]),
|
|
129
|
+
]);
|
|
130
|
+
const paths = [...new Set([...splitNul(untracked), ...splitNul(modified), ...splitNul(staged)])]
|
|
131
|
+
.filter(filePath => !excluded(filePath));
|
|
132
|
+
const sizes = [];
|
|
133
|
+
for (const filePath of paths) {
|
|
134
|
+
const stat = await fs.lstat(path.join(cwd, filePath)).catch(() => null);
|
|
135
|
+
if (stat?.isFile())
|
|
136
|
+
sizes.push({ path: filePath, bytes: stat.size });
|
|
137
|
+
}
|
|
138
|
+
const total = sizes.reduce((sum, entry) => sum + entry.bytes, 0);
|
|
139
|
+
if (total > maxBytes) {
|
|
140
|
+
const largest = sizes.sort((left, right) => right.bytes - left.bytes).slice(0, 5)
|
|
141
|
+
.map(entry => `${entry.path} (${entry.bytes} bytes)`).join(", ");
|
|
142
|
+
throw new WipPreservationError("wip_snapshot_too_large", `uncommitted work in ${cwd} is ${total} bytes across ${sizes.length} file(s), over the ${maxBytes}-byte WIP snapshot cap `
|
|
143
|
+
+ `(${"FORGE_WIP_SNAPSHOT_MAX_BYTES"}); largest: ${largest}. Nothing was saved, so the worktree is kept as it is.`);
|
|
144
|
+
}
|
|
145
|
+
return total;
|
|
146
|
+
}
|
|
147
|
+
/** The staged state: the real index with unresolved conflicts and runtime output put back to the base. */
|
|
148
|
+
async function writeStagedTree(git, cwd, base, unmerged, excluded) {
|
|
149
|
+
const conflicted = [...new Set(unmerged.map(entry => entry.path))];
|
|
150
|
+
await git.runForPaths(cwd, ["reset", "-q", base], conflicted);
|
|
151
|
+
await resetExcluded(git, cwd, base, excluded);
|
|
152
|
+
return (await git.run(cwd, ["write-tree"])).trim();
|
|
153
|
+
}
|
|
154
|
+
/** Puts excluded paths back to the base in this index and returns the paths that still differ. */
|
|
155
|
+
async function resetExcluded(git, cwd, base, excluded) {
|
|
156
|
+
const listChanged = async () => splitNul(await git.run(cwd, ["diff", "--cached", "--name-only", "--no-renames", "-z", base]));
|
|
157
|
+
const changed = await listChanged();
|
|
158
|
+
const toReset = changed.filter(excluded);
|
|
159
|
+
if (toReset.length === 0)
|
|
160
|
+
return changed;
|
|
161
|
+
await git.runForPaths(cwd, ["reset", "-q", base], toReset);
|
|
162
|
+
return await listChanged();
|
|
163
|
+
}
|
|
164
|
+
async function readMergeState(git, cwd) {
|
|
165
|
+
const head = (await git.tryRun(cwd, ["rev-parse", "-q", "--verify", "MERGE_HEAD^{commit}"]))?.trim();
|
|
166
|
+
if (!head)
|
|
167
|
+
return null;
|
|
168
|
+
const message = await readOptionalFile(await gitPath(git, cwd, "MERGE_MSG"));
|
|
169
|
+
const mode = await readOptionalFile(await gitPath(git, cwd, "MERGE_MODE"));
|
|
170
|
+
return {
|
|
171
|
+
head,
|
|
172
|
+
message: message === null ? null : message.slice(0, mergeMessageLimit),
|
|
173
|
+
mode: mode?.trim() || null,
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
function parseUnmergedEntry(record) {
|
|
177
|
+
const tab = record.indexOf("\t");
|
|
178
|
+
const [mode, sha, stage] = record.slice(0, tab).split(" ");
|
|
179
|
+
return { mode: mode, sha: sha, stage: Number(stage), path: record.slice(tab + 1) };
|
|
180
|
+
}
|
|
181
|
+
async function writeSnapshotCommits(request, capture, context) {
|
|
182
|
+
const { git, cwd, tempDir } = context;
|
|
183
|
+
const indexCommit = (await git.run(cwd, [
|
|
184
|
+
"commit-tree", capture.indexTree, "-p", capture.base, "-m", "forge wip index snapshot",
|
|
185
|
+
])).trim();
|
|
186
|
+
const now = (request.now ?? (() => new Date()))();
|
|
187
|
+
const metadata = {
|
|
188
|
+
schema: wipMetadataSchema,
|
|
189
|
+
branch: request.branchName,
|
|
190
|
+
baseHead: capture.base,
|
|
191
|
+
sessionId: request.sessionId?.trim() || null,
|
|
192
|
+
lane: request.lane?.trim() || null,
|
|
193
|
+
reason: request.reason,
|
|
194
|
+
attempt: issuedWipAttempt(request.attempt),
|
|
195
|
+
autoRestore: request.autoRestore,
|
|
196
|
+
createdAt: now.toISOString(),
|
|
197
|
+
createdAtMs: now.getTime(),
|
|
198
|
+
mergeHead: capture.merge?.head ?? null,
|
|
199
|
+
mergeMessage: capture.merge?.message ?? null,
|
|
200
|
+
mergeMode: capture.merge?.mode ?? null,
|
|
201
|
+
unmerged: capture.unmerged,
|
|
202
|
+
reapplyConflicts: capture.reapplyConflicts,
|
|
203
|
+
changedPaths: capture.changedPaths,
|
|
204
|
+
bytes: capture.bytes,
|
|
205
|
+
};
|
|
206
|
+
const messageFile = path.join(tempDir, "message.txt");
|
|
207
|
+
await fs.writeFile(messageFile, formatWipCommitMessage(metadata), "utf8");
|
|
208
|
+
const parents = [capture.base, indexCommit, ...(capture.merge ? [capture.merge.head] : [])]
|
|
209
|
+
.flatMap(parent => ["-p", parent]);
|
|
210
|
+
return (await git.run(cwd, ["commit-tree", capture.worktreeTree, ...parents, "-F", messageFile])).trim();
|
|
211
|
+
}
|
|
212
|
+
/**
|
|
213
|
+
* Pushes the snapshot to origin. A repository without an origin keeps the ref locally instead,
|
|
214
|
+
* since there is nowhere else it could go and the repository itself outlives the worktree.
|
|
215
|
+
*/
|
|
216
|
+
async function publishSnapshot(git, repoPath, request, commitSha) {
|
|
217
|
+
const now = (request.now ?? (() => new Date()))();
|
|
218
|
+
const ref = wipRefName(request.branchName, wipRefId(request.reason, request.sessionId, now, issuedWipAttempt(request.attempt)));
|
|
219
|
+
const origin = (await git.tryRun(repoPath, ["remote", "get-url", "origin"]))?.trim();
|
|
220
|
+
if (!origin) {
|
|
221
|
+
await git.run(repoPath, ["update-ref", ref, commitSha]);
|
|
222
|
+
return { ref, pushed: false };
|
|
223
|
+
}
|
|
224
|
+
try {
|
|
225
|
+
await git.run(repoPath, ["push", "--porcelain", "origin", `${commitSha}:${ref}`]);
|
|
226
|
+
return { ref, pushed: true };
|
|
227
|
+
}
|
|
228
|
+
catch (error) {
|
|
229
|
+
// A session's ref can already exist when the same session was snapshotted before (a retried
|
|
230
|
+
// dispatch); keep both rather than overwrite one.
|
|
231
|
+
const retryRef = `${ref}-${now.getTime().toString(36)}`;
|
|
232
|
+
const retried = await git.tryRun(repoPath, ["push", "--porcelain", "origin", `${commitSha}:${retryRef}`]);
|
|
233
|
+
if (retried !== null)
|
|
234
|
+
return { ref: retryRef, pushed: true };
|
|
235
|
+
throw asPreservationError(error, "wip_push_failed");
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
async function commonGitDir(git, repoPath) {
|
|
239
|
+
const raw = (await git.run(repoPath, ["rev-parse", "--git-common-dir"])).trim();
|
|
240
|
+
return path.isAbsolute(raw) ? raw : path.resolve(repoPath, raw);
|
|
241
|
+
}
|
|
242
|
+
function captureFingerprint(capture) {
|
|
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(":");
|
|
245
|
+
}
|
|
246
|
+
function snapshotKey(worktreePath) {
|
|
247
|
+
const resolved = path.resolve(worktreePath);
|
|
248
|
+
return process.platform === "win32" ? resolved.toLowerCase() : resolved;
|
|
249
|
+
}
|
|
250
|
+
/**
|
|
251
|
+
* Whether a snapshot this process pushed can stand in for the one requested: the same state of the
|
|
252
|
+
* same branch, restorable whenever the request must be, and still at its ref (it may have been
|
|
253
|
+
* retired, or deleted on origin by the server's cleanup). A ref that can't be confirmed is pushed again.
|
|
254
|
+
*/
|
|
255
|
+
async function cachedSnapshotServes(git, repoPath, cached, fingerprint, request) {
|
|
256
|
+
if (cached.fingerprint !== fingerprint || cached.branchName !== request.branchName)
|
|
257
|
+
return false;
|
|
258
|
+
if (request.autoRestore && !cached.autoRestore)
|
|
259
|
+
return false;
|
|
260
|
+
const listed = cached.pushed
|
|
261
|
+
? await git.tryRun(repoPath, ["ls-remote", "--refs", "origin", cached.ref])
|
|
262
|
+
: await git.tryRun(repoPath, ["rev-parse", "-q", "--verify", `${cached.ref}^{commit}`]);
|
|
263
|
+
return (listed?.trim().split(/\s+/u)[0] ?? "") === cached.commitSha;
|
|
264
|
+
}
|
|
265
|
+
function asPreservationError(error, code) {
|
|
266
|
+
if (error instanceof WipPreservationError)
|
|
267
|
+
return error;
|
|
268
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
269
|
+
return new WipPreservationError(code, message, { cause: error });
|
|
270
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { GitClient } from "../shared/git/git.js";
|
|
2
|
+
import type { WorktreePrepareRequest } from "./worktree.types.js";
|
|
3
|
+
/** Materializes the run's inputs into a prepared worktree (outside the repository lock). */
|
|
4
|
+
export declare function materializeWorktreeInputs(worktreePath: string, request: WorktreePrepareRequest, git: GitClient): Promise<{
|
|
5
|
+
readonly hydratedPriorPhaseArtifactCount: number;
|
|
6
|
+
readonly qaReworkPacketPath?: string;
|
|
7
|
+
}>;
|
|
8
|
+
export declare function clearRunArtifactRoots(worktreePath: string, request: WorktreePrepareRequest): Promise<void>;
|