@lyrumu/pi-diff 0.0.0-stage → 0.1.0
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/LICENSE +21 -0
- package/NOTICE.md +8 -0
- package/README.md +120 -2
- package/README.zh-CN.md +121 -0
- package/THIRD_PARTY_LICENSES.md +33 -0
- package/index.ts +153 -0
- package/package.json +45 -4
- package/src/diff-engine.ts +218 -0
- package/src/git.ts +378 -0
- package/src/language.ts +91 -0
- package/src/preferences.ts +47 -0
- package/src/snapshot.ts +114 -0
- package/src/store.ts +77 -0
- package/src/tracker.ts +508 -0
- package/src/tui/diff-screen.ts +310 -0
- package/src/tui/file-tree-utils.ts +174 -0
- package/src/tui/file-tree.ts +99 -0
- package/src/tui/patch-diff.ts +243 -0
- package/src/tui/scopes.ts +20 -0
- package/src/tui/text.ts +15 -0
package/src/tracker.ts
ADDED
|
@@ -0,0 +1,508 @@
|
|
|
1
|
+
import { readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
|
|
2
|
+
import { tmpdir } from "node:os";
|
|
3
|
+
import { join, relative, resolve, sep } from "node:path";
|
|
4
|
+
import { randomBytes } from "node:crypto";
|
|
5
|
+
import type { ExtensionAPI, SessionEntry } from "@earendil-works/pi-coding-agent";
|
|
6
|
+
import { Git } from "./git.ts";
|
|
7
|
+
import { SnapshotStore } from "./snapshot.ts";
|
|
8
|
+
import {
|
|
9
|
+
MAX_TOTAL_PATCH_BYTES,
|
|
10
|
+
emptyPatch,
|
|
11
|
+
makeFilePatch,
|
|
12
|
+
type FilePatch,
|
|
13
|
+
} from "./diff-engine.ts";
|
|
14
|
+
import { appendTurnDiff, collectTurnDiffs, type TurnDiffEntryData } from "./store.ts";
|
|
15
|
+
|
|
16
|
+
const IGNORED_DIRS = new Set([".git", "node_modules", ".cache", "dist", "build"]);
|
|
17
|
+
|
|
18
|
+
/** A file registered for the current turn. */
|
|
19
|
+
interface RegisteredFile {
|
|
20
|
+
/** sha256 of turn-start content; null = file did not exist at turn start. */
|
|
21
|
+
oldHash: string | null;
|
|
22
|
+
/** True when the old side could not be recovered (no-git bash change). */
|
|
23
|
+
baselineUnknown: boolean;
|
|
24
|
+
unavailable?: boolean;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Tracks file changes per turn. Ported from opencode's snapshot/diff stack
|
|
29
|
+
* (packages/core/src/{snapshot,session/diff}.ts), adapted to pi's event model
|
|
30
|
+
* (PLAN.md deviations D2–D4).
|
|
31
|
+
*
|
|
32
|
+
* INVARIANT — single entry point: every file that enters a turn's diff goes
|
|
33
|
+
* through `recordFileChange()`, no matter how it was discovered:
|
|
34
|
+
* 1. tool_call of edit/write (known target file, pre-execution)
|
|
35
|
+
* 2. bash before/after workspace scan (bashMarkers)
|
|
36
|
+
* 3. turn-start baseline catch-up scan at finalizeTurn
|
|
37
|
+
* There is exactly one writer of `turnFiles`; nothing can be "changed by bash
|
|
38
|
+
* but missing from the turn diff".
|
|
39
|
+
*
|
|
40
|
+
* INVARIANT — single scan: `scanWorkspace(marker)` has one implementation;
|
|
41
|
+
* the turn-start baseline and the bash boundaries only pass different markers
|
|
42
|
+
* (git: HEAD + dirty-file signatures; no-git: file metadata + pathname inventory).
|
|
43
|
+
*
|
|
44
|
+
* Old-side recovery (git): files already dirty at turn start are snapshotted
|
|
45
|
+
* into `turnBaseline` (their turn-start content). Files clean at turn start
|
|
46
|
+
* are recovered from the *pinned turn-start HEAD* (`git show <rev>:path`),
|
|
47
|
+
* which stays correct even when bash runs `git add`/`git commit` mid-turn —
|
|
48
|
+
* using `:path` (live index) or a live `HEAD` would race those commands.
|
|
49
|
+
*/
|
|
50
|
+
export class Tracker {
|
|
51
|
+
readonly snapshotStore: SnapshotStore;
|
|
52
|
+
private readonly cwd = process.cwd();
|
|
53
|
+
private git: boolean | null = null;
|
|
54
|
+
private gitPrefix = "";
|
|
55
|
+
|
|
56
|
+
private turnNumber = 0;
|
|
57
|
+
private turnFiles = new Map<string, RegisteredFile>();
|
|
58
|
+
/** Pre-dirty files at turn start: path -> content hash or known absence. */
|
|
59
|
+
private turnBaseline = new Map<string, string | null>();
|
|
60
|
+
private unavailableBaseline = new Set<string>();
|
|
61
|
+
/** HEAD commit id pinned at turn start (git only; null = unborn). */
|
|
62
|
+
private turnStartHead: string | null = null;
|
|
63
|
+
/** Turn-level marker for the finalize catch-up scan. */
|
|
64
|
+
private turnMarker: string | null = null;
|
|
65
|
+
/** Bash-start markers keyed by toolCallId (parallel bash calls are safe). */
|
|
66
|
+
private bashMarkers = new Map<string, string>();
|
|
67
|
+
/** Restored / accumulated turn diffs on the current branch. */
|
|
68
|
+
private turnDiffs: TurnDiffEntryData[] = [];
|
|
69
|
+
|
|
70
|
+
private readonly pi: ExtensionAPI;
|
|
71
|
+
|
|
72
|
+
constructor(pi: ExtensionAPI, snapshotStore = new SnapshotStore()) {
|
|
73
|
+
this.pi = pi;
|
|
74
|
+
this.snapshotStore = snapshotStore;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// ---------------------------------------------------------------- scanning
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* THE shared workspace scan. One implementation, callers only differ in the
|
|
81
|
+
* marker they pass:
|
|
82
|
+
* - git repo: marker is a workspace signature (HEAD + porcelain entries + sha256
|
|
83
|
+
* of each dirty file's content); returns files whose signature is new or
|
|
84
|
+
* changed versus that marker, including paths that became clean. HEAD
|
|
85
|
+
* changes also include committed paths. Plain porcelain cannot see a
|
|
86
|
+
* dirty file changing again (" M" stays " M"), hence the content hashes.
|
|
87
|
+
* - no git: marker stores file metadata and paths under cwd (excluding
|
|
88
|
+
* IGNORED_DIRS); ctime/identity changes detect rewrites that preserve mtime.
|
|
89
|
+
* Returns project-relative posix paths.
|
|
90
|
+
*/
|
|
91
|
+
async scanWorkspace(marker: string): Promise<string[]> {
|
|
92
|
+
if (await this.isGit()) {
|
|
93
|
+
const before = Git.parseWorkspaceSignature(marker);
|
|
94
|
+
const currentMarker = await this.gitWorkspaceSignature();
|
|
95
|
+
const current = Git.parseWorkspaceSignature(currentMarker);
|
|
96
|
+
const changed = new Set<string>();
|
|
97
|
+
for (const file of new Set([...before.keys(), ...current.keys()])) {
|
|
98
|
+
if (before.get(file) !== current.get(file)) changed.add(file);
|
|
99
|
+
}
|
|
100
|
+
let previousHead: string | null = null;
|
|
101
|
+
try {
|
|
102
|
+
const value = JSON.parse(marker)?.head;
|
|
103
|
+
if (typeof value === "string") previousHead = value;
|
|
104
|
+
} catch { /* An invalid marker has no recoverable HEAD. */ }
|
|
105
|
+
const currentHead: string | null = JSON.parse(currentMarker).head;
|
|
106
|
+
for (const file of await Git.changedCommitFiles(this.cwd, previousHead, currentHead)) {
|
|
107
|
+
if (file.startsWith(this.gitPrefix)) changed.add(file.slice(this.gitPrefix.length));
|
|
108
|
+
}
|
|
109
|
+
return [...changed];
|
|
110
|
+
}
|
|
111
|
+
let previous: Map<string, string>;
|
|
112
|
+
try {
|
|
113
|
+
const value: unknown = JSON.parse(await readFile(marker, "utf8"));
|
|
114
|
+
if (!Array.isArray(value) || !value.every((entry) => Array.isArray(entry) && entry.length === 2 && entry.every((item) => typeof item === "string"))) return [];
|
|
115
|
+
previous = new Map(value as [string, string][]);
|
|
116
|
+
} catch {
|
|
117
|
+
return [];
|
|
118
|
+
}
|
|
119
|
+
const current = new Map<string, string>();
|
|
120
|
+
await this.walk(this.cwd, current);
|
|
121
|
+
const changed = [...current].filter(([file, signature]) => previous.get(file) !== signature).map(([file]) => file);
|
|
122
|
+
for (const file of previous.keys()) if (!current.has(file)) changed.push(file);
|
|
123
|
+
return changed;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
private async walk(dir: string, out: Map<string, string>): Promise<void> {
|
|
127
|
+
let entries: import("node:fs").Dirent[];
|
|
128
|
+
try {
|
|
129
|
+
entries = await readdir(dir, { withFileTypes: true });
|
|
130
|
+
} catch (error) {
|
|
131
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT") return;
|
|
132
|
+
throw error;
|
|
133
|
+
}
|
|
134
|
+
const files = entries.filter((entry) => entry.isFile());
|
|
135
|
+
for (let offset = 0; offset < files.length; offset += 32) {
|
|
136
|
+
await Promise.all(files.slice(offset, offset + 32).map(async (entry) => {
|
|
137
|
+
const full = join(dir, entry.name);
|
|
138
|
+
try {
|
|
139
|
+
const s = await stat(full, { bigint: true });
|
|
140
|
+
out.set(relative(this.cwd, full).split(sep).join("/"), `${s.mtimeNs}:${s.ctimeNs}:${s.size}:${s.dev}:${s.ino}`);
|
|
141
|
+
} catch (error) {
|
|
142
|
+
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
|
|
143
|
+
}
|
|
144
|
+
}));
|
|
145
|
+
}
|
|
146
|
+
for (const entry of entries) {
|
|
147
|
+
if (entry.isDirectory() && !IGNORED_DIRS.has(entry.name)) {
|
|
148
|
+
await this.walk(join(dir, entry.name), out);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** Make a metadata marker for the no-git backend of scanWorkspace(). */
|
|
154
|
+
async makeMarker(): Promise<string> {
|
|
155
|
+
const files = new Map<string, string>();
|
|
156
|
+
await this.walk(this.cwd, files);
|
|
157
|
+
const file = join(tmpdir(), `pi-diff-marker-${Date.now()}-${randomBytes(4).toString("hex")}`);
|
|
158
|
+
await writeFile(file, JSON.stringify([...files]));
|
|
159
|
+
return file;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
private async releaseMarker(path: string): Promise<void> {
|
|
163
|
+
await rm(path, { force: true }).catch(() => {});
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
// ------------------------------------------------------ change recording
|
|
167
|
+
|
|
168
|
+
/** Normalize to a project-relative posix path, or null when outside cwd. */
|
|
169
|
+
private normalize(path: string): string | null {
|
|
170
|
+
if (path.includes("\0")) return null;
|
|
171
|
+
const rel = relative(this.cwd, resolve(this.cwd, path)).split(sep).join("/");
|
|
172
|
+
if (!rel || rel.startsWith("../") || rel === ".." || rel === ".") return null;
|
|
173
|
+
return rel;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* Single change-recording entry point. First registration wins: a file
|
|
178
|
+
* already registered this turn is a no-op (a bash scan may run after the
|
|
179
|
+
* edit tool already registered the file, and vice versa).
|
|
180
|
+
*/
|
|
181
|
+
async recordFileChange(path: string, opts: { fromToolEvent?: boolean } = {}): Promise<void> {
|
|
182
|
+
const file = this.normalize(path);
|
|
183
|
+
if (file === null || this.turnFiles.has(file)) return;
|
|
184
|
+
|
|
185
|
+
let registered: RegisteredFile;
|
|
186
|
+
try {
|
|
187
|
+
if (await this.isGit()) {
|
|
188
|
+
if (this.unavailableBaseline.has(file)) {
|
|
189
|
+
registered = { oldHash: null, baselineUnknown: true, unavailable: true };
|
|
190
|
+
} else if (this.turnBaseline.has(file)) {
|
|
191
|
+
registered = { oldHash: this.turnBaseline.get(file)!, baselineUnknown: false };
|
|
192
|
+
} else {
|
|
193
|
+
// Pin the clean old side so staging or committing mid-turn cannot replace it.
|
|
194
|
+
let content = this.turnStartHead !== null
|
|
195
|
+
? await Git.showRevision(this.cwd, this.turnStartHead, this.gitPrefix + file) : null;
|
|
196
|
+
// Ignored explicit targets are absent from both porcelain and HEAD.
|
|
197
|
+
if (content === null && opts.fromToolEvent) content = await this.readFileOrNull(file);
|
|
198
|
+
const oldHash = content !== null ? await this.snapshotStore.put(content) : null;
|
|
199
|
+
registered = { oldHash, baselineUnknown: false };
|
|
200
|
+
}
|
|
201
|
+
} else if (opts.fromToolEvent) {
|
|
202
|
+
// No git: only a pre-execution tool event can capture the old side.
|
|
203
|
+
const content = await this.readFileOrNull(file);
|
|
204
|
+
const oldHash = content !== null ? await this.snapshotStore.put(content) : null;
|
|
205
|
+
registered = { oldHash, baselineUnknown: false };
|
|
206
|
+
} else {
|
|
207
|
+
registered = { oldHash: null, baselineUnknown: true };
|
|
208
|
+
}
|
|
209
|
+
} catch (error) {
|
|
210
|
+
// A rejected directory target is not a changed file; other capture failures are explicit.
|
|
211
|
+
if ((error as NodeJS.ErrnoException).code === "EISDIR") return;
|
|
212
|
+
registered = { oldHash: null, baselineUnknown: true, unavailable: true };
|
|
213
|
+
}
|
|
214
|
+
// Parallel hooks may have registered the file while this capture awaited IO.
|
|
215
|
+
if (!this.turnFiles.has(file)) this.turnFiles.set(file, registered);
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
private async readFileOrNull(file: string): Promise<Buffer | null> {
|
|
219
|
+
try {
|
|
220
|
+
return await readFile(join(this.cwd, file));
|
|
221
|
+
} catch (error) {
|
|
222
|
+
if (["ENOENT", "ENOTDIR"].includes((error as NodeJS.ErrnoException).code ?? "")) return null;
|
|
223
|
+
throw error;
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/**
|
|
228
|
+
* Git workspace signature: porcelain entries with a sha256 of each dirty
|
|
229
|
+
* file's disk content ("missing" when deleted). Two signatures differ for
|
|
230
|
+
* any file whose status code or content changed between captures.
|
|
231
|
+
*/
|
|
232
|
+
private async gitWorkspaceSignature(): Promise<string> {
|
|
233
|
+
const signature: [string, string, string][] = [];
|
|
234
|
+
const [head, status] = await Promise.all([Git.headCommit(this.cwd), this.workspaceStatus()]);
|
|
235
|
+
for (const item of status) {
|
|
236
|
+
let hash = "unreadable";
|
|
237
|
+
try {
|
|
238
|
+
const content = await this.readFileOrNull(item.file);
|
|
239
|
+
hash = content !== null ? SnapshotStore.hash(content) : "missing";
|
|
240
|
+
} catch { /* Keep the path in the signature even when unreadable. */ }
|
|
241
|
+
signature.push([item.file, item.code, hash]);
|
|
242
|
+
}
|
|
243
|
+
return JSON.stringify({ head, files: signature });
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
private async workspaceStatus() {
|
|
247
|
+
return Git.parseStatus(await Git.statusPorcelain(this.cwd)).flatMap((item) =>
|
|
248
|
+
item.file.startsWith(this.gitPrefix) ? [{ ...item, file: item.file.slice(this.gitPrefix.length) }] : [],
|
|
249
|
+
);
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
// ------------------------------------------------------------------ hooks
|
|
253
|
+
|
|
254
|
+
/**
|
|
255
|
+
* Called from before_agent_start: bump turn counter and take the turn
|
|
256
|
+
* baseline — git: workspace signature + content snapshot of already-dirty
|
|
257
|
+
* files + pinned HEAD; no-git: a metadata marker file.
|
|
258
|
+
*/
|
|
259
|
+
async onTurnStart(): Promise<void> {
|
|
260
|
+
this.turnNumber += 1;
|
|
261
|
+
this.turnFiles.clear();
|
|
262
|
+
this.turnBaseline.clear();
|
|
263
|
+
this.unavailableBaseline.clear();
|
|
264
|
+
this.bashMarkers.clear();
|
|
265
|
+
this.turnMarker = null;
|
|
266
|
+
|
|
267
|
+
if (await this.isGit()) {
|
|
268
|
+
const [head, status] = await Promise.all([Git.headCommit(this.cwd), this.workspaceStatus()]);
|
|
269
|
+
this.turnStartHead = head;
|
|
270
|
+
const signature: [string, string, string][] = [];
|
|
271
|
+
for (const item of status) {
|
|
272
|
+
// Snapshot the turn-start content of dirty files so bash-modified
|
|
273
|
+
// pre-dirty files keep a correct old side. Files already deleted on
|
|
274
|
+
// disk have no turn-start content (a later recreation is "added").
|
|
275
|
+
try {
|
|
276
|
+
const content = await this.readFileOrNull(item.file);
|
|
277
|
+
const hash = content !== null ? SnapshotStore.hash(content) : "missing";
|
|
278
|
+
this.turnBaseline.set(item.file, content !== null ? await this.snapshotStore.put(content) : null);
|
|
279
|
+
signature.push([item.file, item.code, hash]);
|
|
280
|
+
} catch {
|
|
281
|
+
signature.push([item.file, item.code, "unreadable"]);
|
|
282
|
+
this.unavailableBaseline.add(item.file);
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
this.turnMarker = JSON.stringify({ head: this.turnStartHead, files: signature });
|
|
286
|
+
} else {
|
|
287
|
+
this.turnMarker = await this.makeMarker();
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/** Called before every shell tool execution (tool_call of bash/powershell). */
|
|
292
|
+
async onBashStart(toolCallId: string): Promise<void> {
|
|
293
|
+
if (await this.isGit()) {
|
|
294
|
+
this.bashMarkers.set(toolCallId, await this.gitWorkspaceSignature());
|
|
295
|
+
} else {
|
|
296
|
+
this.bashMarkers.set(toolCallId, await this.makeMarker());
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/**
|
|
301
|
+
* Called after every shell tool execution (tool_result): scan vs the bash
|
|
302
|
+
* marker and register newly changed files through the single entry point.
|
|
303
|
+
*/
|
|
304
|
+
async onBashEnd(toolCallId: string): Promise<void> {
|
|
305
|
+
const marker = this.bashMarkers.get(toolCallId);
|
|
306
|
+
this.bashMarkers.delete(toolCallId);
|
|
307
|
+
if (marker === undefined) return;
|
|
308
|
+
let changed: string[];
|
|
309
|
+
try { changed = await this.scanWorkspace(marker); }
|
|
310
|
+
finally { if (!(await this.isGit())) await this.releaseMarker(marker); }
|
|
311
|
+
for (const file of changed) await this.recordFileChange(file);
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
/**
|
|
315
|
+
* Called from agent_settled: finalize the turn. A turn-level catch-up scan
|
|
316
|
+
* first picks up anything the tool events and bash scans missed (e.g. files
|
|
317
|
+
* written by non-builtin tools); then per-file patches are computed and
|
|
318
|
+
* persisted as one self-contained `pi-diff.turn` custom entry.
|
|
319
|
+
*/
|
|
320
|
+
async finalizeTurn(): Promise<void> {
|
|
321
|
+
const turnMarker = this.turnMarker;
|
|
322
|
+
try {
|
|
323
|
+
if (turnMarker !== null) {
|
|
324
|
+
const missed = await this.scanWorkspace(turnMarker);
|
|
325
|
+
for (const file of missed) await this.recordFileChange(file);
|
|
326
|
+
}
|
|
327
|
+
} finally {
|
|
328
|
+
if (!(await this.isGit())) {
|
|
329
|
+
if (turnMarker !== null) await this.releaseMarker(turnMarker);
|
|
330
|
+
for (const marker of this.bashMarkers.values()) await this.releaseMarker(marker);
|
|
331
|
+
}
|
|
332
|
+
this.turnMarker = null;
|
|
333
|
+
this.bashMarkers.clear();
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
const patches: FilePatch[] = [];
|
|
337
|
+
let capped = false;
|
|
338
|
+
let total = 0;
|
|
339
|
+
for (const file of [...this.turnFiles.keys()].sort()) {
|
|
340
|
+
const registered = this.turnFiles.get(file)!;
|
|
341
|
+
let newContent: Buffer | null = null;
|
|
342
|
+
let unavailable = registered.unavailable ?? false;
|
|
343
|
+
try { newContent = await this.readFileOrNull(file); }
|
|
344
|
+
catch { unavailable = true; }
|
|
345
|
+
const newHash = newContent !== null ? SnapshotStore.hash(newContent) : null;
|
|
346
|
+
// No-op registration (failed edit, touch without change): drop.
|
|
347
|
+
if (!unavailable && registered.oldHash === newHash && !registered.baselineUnknown) continue;
|
|
348
|
+
|
|
349
|
+
let patch: FilePatch;
|
|
350
|
+
const status = registered.unavailable ? "modified"
|
|
351
|
+
: registered.oldHash === null && !registered.baselineUnknown ? "added"
|
|
352
|
+
: !unavailable && newContent === null ? "deleted" : "modified";
|
|
353
|
+
if (unavailable || capped || (registered.baselineUnknown && newContent === null)) {
|
|
354
|
+
// Once the total cap is hit, remaining files degrade (opencode totalPatch).
|
|
355
|
+
patch = {
|
|
356
|
+
file,
|
|
357
|
+
status,
|
|
358
|
+
patch: emptyPatch(file),
|
|
359
|
+
additions: 0,
|
|
360
|
+
deletions: 0,
|
|
361
|
+
...(capped ? { tooLarge: true } : {}),
|
|
362
|
+
...(unavailable ? { unavailable: true } : {}),
|
|
363
|
+
...(registered.baselineUnknown ? { baselineUnknown: true } : {}),
|
|
364
|
+
oldHash: registered.oldHash,
|
|
365
|
+
...(unavailable ? {} : { newHash }),
|
|
366
|
+
};
|
|
367
|
+
} else {
|
|
368
|
+
const oldContent =
|
|
369
|
+
registered.oldHash !== null ? await this.snapshotStore.get(registered.oldHash) : null;
|
|
370
|
+
patch = registered.oldHash !== null && oldContent === null ? {
|
|
371
|
+
file, status, patch: emptyPatch(file), additions: 0, deletions: 0,
|
|
372
|
+
unavailable: true, oldHash: registered.oldHash, newHash,
|
|
373
|
+
} : makeFilePatch(file, oldContent, newContent, {
|
|
374
|
+
oldHash: registered.oldHash,
|
|
375
|
+
newHash,
|
|
376
|
+
baselineUnknown: registered.baselineUnknown,
|
|
377
|
+
});
|
|
378
|
+
// Cache the new side for the session-cumulative recompute.
|
|
379
|
+
if (newContent !== null && !patch.binary && !patch.tooLarge) {
|
|
380
|
+
await this.snapshotStore.put(newContent).catch(() => {});
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
const bytes = Buffer.byteLength(patch.patch, "utf8");
|
|
385
|
+
if (total + bytes > MAX_TOTAL_PATCH_BYTES) {
|
|
386
|
+
capped = true;
|
|
387
|
+
patch = { ...patch, patch: emptyPatch(file), additions: 0, deletions: 0, tooLarge: true };
|
|
388
|
+
} else {
|
|
389
|
+
total += bytes;
|
|
390
|
+
}
|
|
391
|
+
patches.push(patch);
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
this.turnFiles.clear();
|
|
395
|
+
this.turnBaseline.clear();
|
|
396
|
+
this.unavailableBaseline.clear();
|
|
397
|
+
|
|
398
|
+
// Empty turns still carry their number so reload and Last turn remain accurate.
|
|
399
|
+
if (this.turnNumber === 0) return;
|
|
400
|
+
|
|
401
|
+
const data: TurnDiffEntryData = {
|
|
402
|
+
turn: this.turnNumber,
|
|
403
|
+
endedAt: new Date().toISOString(),
|
|
404
|
+
fileCount: patches.length,
|
|
405
|
+
patches,
|
|
406
|
+
};
|
|
407
|
+
this.turnDiffs.push(data);
|
|
408
|
+
appendTurnDiff(this.pi.appendEntry.bind(this.pi), data);
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
// -------------------------------------------------------------- accessors
|
|
412
|
+
|
|
413
|
+
/** All persisted turn diffs on the current branch, in order. */
|
|
414
|
+
turns(): readonly TurnDiffEntryData[] {
|
|
415
|
+
return this.turnDiffs;
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
/**
|
|
419
|
+
* Session-cumulative patches per file: first appearance old side → latest
|
|
420
|
+
* new side (opencode session-diff semantics). Recomputed from cached blobs
|
|
421
|
+
* via makeFilePatch when both sides are available; otherwise degrades to the
|
|
422
|
+
* file's last per-turn patch.
|
|
423
|
+
*/
|
|
424
|
+
async sessionPatches(): Promise<FilePatch[]> {
|
|
425
|
+
const first = new Map<string, FilePatch>();
|
|
426
|
+
const last = new Map<string, FilePatch>();
|
|
427
|
+
for (const turn of this.turnDiffs) {
|
|
428
|
+
for (const fp of turn.patches) {
|
|
429
|
+
if (!first.has(fp.file)) first.set(fp.file, fp);
|
|
430
|
+
last.set(fp.file, fp);
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
const result: FilePatch[] = [];
|
|
434
|
+
let total = 0;
|
|
435
|
+
let capped = false;
|
|
436
|
+
const append = (patch: FilePatch) => {
|
|
437
|
+
const bytes = Buffer.byteLength(patch.patch);
|
|
438
|
+
if (capped || total + bytes > MAX_TOTAL_PATCH_BYTES) {
|
|
439
|
+
capped = true;
|
|
440
|
+
result.push({ ...patch, patch: emptyPatch(patch.file), tooLarge: true });
|
|
441
|
+
} else {
|
|
442
|
+
total += bytes;
|
|
443
|
+
result.push(patch);
|
|
444
|
+
}
|
|
445
|
+
};
|
|
446
|
+
for (const file of [...first.keys()].sort()) {
|
|
447
|
+
const f = first.get(file)!;
|
|
448
|
+
const l = last.get(file)!;
|
|
449
|
+
const oldHash = f.oldHash;
|
|
450
|
+
const newHash = l.newHash;
|
|
451
|
+
if (!f.baselineUnknown && oldHash !== undefined && oldHash === newHash) continue;
|
|
452
|
+
// One recorded change is already a self-contained cumulative patch.
|
|
453
|
+
if (f === l) {
|
|
454
|
+
append(l);
|
|
455
|
+
continue;
|
|
456
|
+
}
|
|
457
|
+
if (f.baselineUnknown || f.binary || l.binary || f.tooLarge || l.tooLarge || f.unavailable || l.unavailable || oldHash === undefined || newHash === undefined) {
|
|
458
|
+
append({ ...l, cumulativeFallback: true });
|
|
459
|
+
continue;
|
|
460
|
+
}
|
|
461
|
+
const oldContent =
|
|
462
|
+
oldHash !== null ? await this.snapshotStore.get(oldHash) : null;
|
|
463
|
+
const newContent = newHash !== null ? await this.snapshotStore.get(newHash) : null;
|
|
464
|
+
if ((oldHash !== null && oldContent === null) || (newHash !== null && newContent === null)) {
|
|
465
|
+
// Cache miss (evicted / old session): degrade to the last turn patch.
|
|
466
|
+
append({ ...l, cumulativeFallback: true });
|
|
467
|
+
continue;
|
|
468
|
+
}
|
|
469
|
+
const recomputed = makeFilePatch(file, oldContent, newContent, {
|
|
470
|
+
oldHash,
|
|
471
|
+
newHash,
|
|
472
|
+
baselineUnknown: f.baselineUnknown,
|
|
473
|
+
});
|
|
474
|
+
if (recomputed.oldHash === recomputed.newHash && recomputed.status === "modified") {
|
|
475
|
+
// Net-zero across the session: file added and reverted, etc.
|
|
476
|
+
continue;
|
|
477
|
+
}
|
|
478
|
+
append(recomputed);
|
|
479
|
+
}
|
|
480
|
+
return result;
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
/**
|
|
484
|
+
* Rebuild Tracker state from `pi-diff.turn` custom entries on the active
|
|
485
|
+
* branch (session reload / resume / branch switch).
|
|
486
|
+
*/
|
|
487
|
+
restoreFromSession(sessionManager: { getBranch(): SessionEntry[] }): void {
|
|
488
|
+
this.turnDiffs = collectTurnDiffs(sessionManager.getBranch());
|
|
489
|
+
this.turnNumber = this.turnDiffs.reduce((max, t) => Math.max(max, t.turn), 0);
|
|
490
|
+
this.turnFiles.clear();
|
|
491
|
+
this.turnBaseline.clear();
|
|
492
|
+
this.unavailableBaseline.clear();
|
|
493
|
+
this.bashMarkers.clear();
|
|
494
|
+
this.turnMarker = null;
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
async cleanupCaches(): Promise<void> {
|
|
498
|
+
await this.snapshotStore.cleanup();
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
private async isGit(): Promise<boolean> {
|
|
502
|
+
if (this.git === null) {
|
|
503
|
+
this.git = await Git.isAvailable(this.cwd);
|
|
504
|
+
if (this.git) this.gitPrefix = await Git.prefix(this.cwd);
|
|
505
|
+
}
|
|
506
|
+
return this.git;
|
|
507
|
+
}
|
|
508
|
+
}
|