@lyrumu/pi-diff 0.0.0-stage → 0.2.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/src/tracker.ts ADDED
@@ -0,0 +1,458 @@
1
+ import { createHash } from "node:crypto";
2
+ import { createReadStream } from "node:fs";
3
+ import { lstat, readFile, readlink, realpath } from "node:fs/promises";
4
+ import { homedir } from "node:os";
5
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+ import type { ExtensionAPI, SessionEntry } from "@earendil-works/pi-coding-agent";
8
+ import { SnapshotStore } from "./snapshot.ts";
9
+ import {
10
+ MAX_TOTAL_PATCH_BYTES,
11
+ MAX_PATCH_BYTES,
12
+ emptyPatch,
13
+ isBinary,
14
+ makeFilePatch,
15
+ type FilePatch,
16
+ type FileMode,
17
+ } from "./diff-engine.ts";
18
+ import { appendTurnDiff, collectTurnDiffs, type TrackingIssue, type TurnDiffEntryData } from "./store.ts";
19
+ import { shellTargets } from "./shell-targets.ts";
20
+ import type { Language } from "./language.ts";
21
+
22
+ interface FileState {
23
+ hash: string;
24
+ mode: FileMode;
25
+ binary: boolean;
26
+ tooLarge?: true;
27
+ }
28
+
29
+ /** A file registered for the current turn. */
30
+ interface RegisteredFile {
31
+ before: FileState | null;
32
+ /** True when capturing the pre-execution contents failed. */
33
+ baselineUnknown: boolean;
34
+ unavailable?: boolean;
35
+ result?: FileState | null;
36
+ }
37
+
38
+ /** Only explicit write targets enter task history; workspace scans cannot prove authorship. */
39
+ export class Tracker {
40
+ readonly snapshotStore: SnapshotStore;
41
+ private cwd = process.cwd();
42
+
43
+ private turnNumber = 0;
44
+ private turnFiles = new Map<string, RegisteredFile>();
45
+ private toolTargets = new Map<string, Set<string>>();
46
+ /** Restored / accumulated turn diffs on the current branch. */
47
+ private turnDiffs: TurnDiffEntryData[] = [];
48
+ private active = false;
49
+ private starting: Promise<void> | undefined;
50
+ private finalizing: Promise<void> | undefined;
51
+ private issues = new Set<TrackingIssue>();
52
+
53
+ private readonly pi: ExtensionAPI;
54
+
55
+ constructor(pi: ExtensionAPI, snapshotStore = new SnapshotStore()) {
56
+ this.pi = pi;
57
+ this.snapshotStore = snapshotStore;
58
+ }
59
+
60
+ // ------------------------------------------------------ change recording
61
+
62
+ /** Keep workspace paths relative and external identities absolute. */
63
+ private normalize(path: string, cwd = this.cwd): string | null {
64
+ if (path.includes("\0")) return null;
65
+ const absolute = resolve(cwd, path);
66
+ const rel = relative(cwd, absolute).split(sep).join("/");
67
+ if (!rel || rel === ".") return null;
68
+ return rel.startsWith("../") || rel === ".." || isAbsolute(rel) ? absolute : rel;
69
+ }
70
+
71
+ /**
72
+ * Single change-recording entry point. First registration wins: a file
73
+ * already registered by a writer keeps its baseline. Reads can never
74
+ * establish write ownership, even if the file later changes on disk.
75
+ */
76
+ async recordFileChange(path: string, opts: { fromToolEvent?: boolean; followSymlinks?: boolean; cwd?: string; toolPath?: boolean; observeOnly?: boolean; toolCallId?: string } = {}): Promise<void> {
77
+ if (!opts.fromToolEvent || opts.observeOnly) return;
78
+ if (opts.fromToolEvent) {
79
+ // Match pi's explicit file-tool path rules, then identify symlink parents.
80
+ if (opts.toolPath) {
81
+ path = path.replace(/[\u00a0\u2000-\u200a\u202f\u205f\u3000]/g, " ").replace(/^@/, "");
82
+ if (path === "~" || path.startsWith("~/")) path = homedir() + path.slice(1);
83
+ if (path.startsWith("file://")) {
84
+ try { path = fileURLToPath(path); }
85
+ catch { this.issues.add("capture"); return; }
86
+ }
87
+ }
88
+ path = resolve(opts.cwd ?? this.cwd, path);
89
+ try {
90
+ path = opts.followSymlinks ? await realpath(path) : join(await realpath(dirname(path)), basename(path));
91
+ } catch (error) {
92
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") this.issues.add("capture");
93
+ if (opts.followSymlinks) {
94
+ // writeFile follows even a dangling final symlink and creates its target.
95
+ for (let depth = 0; depth < 40; depth++) {
96
+ try {
97
+ if (!(await lstat(path)).isSymbolicLink()) break;
98
+ path = resolve(dirname(path), await readlink(path));
99
+ } catch { break; }
100
+ }
101
+ }
102
+ // A newly created file still has a resolvable parent in the common case.
103
+ try { path = join(await realpath(dirname(path)), basename(path)); } catch { /* Keep the lexical path. */ }
104
+ }
105
+ }
106
+ const file = this.normalize(path);
107
+ if (file === null) return;
108
+ if (opts.toolCallId) {
109
+ const files = this.toolTargets.get(opts.toolCallId) ?? new Set<string>();
110
+ files.add(file);
111
+ this.toolTargets.set(opts.toolCallId, files);
112
+ }
113
+ const existing = this.turnFiles.get(file);
114
+ if (existing) {
115
+ // Intervening writes from another actor cannot be folded into this task's net patch.
116
+ if (existing.result !== undefined) {
117
+ try {
118
+ const state = await this.captureFileState(file, false);
119
+ if (state?.hash !== existing.result?.hash || state?.mode !== existing.result?.mode) {
120
+ existing.unavailable = true;
121
+ this.issues.add("capture");
122
+ }
123
+ } catch { existing.unavailable = true; this.issues.add("capture"); }
124
+ }
125
+ return;
126
+ }
127
+
128
+ let registered: RegisteredFile;
129
+ try {
130
+ // Capture immediately before Pi's first write, excluding earlier changes by other actors.
131
+ registered = { before: await this.captureFileState(file), baselineUnknown: false };
132
+ } catch (error) {
133
+ this.issues.add("capture");
134
+ if (["EISDIR", "ENOTSUP"].includes((error as NodeJS.ErrnoException).code ?? "")) return;
135
+ registered = { before: null, baselineUnknown: true, unavailable: true };
136
+ }
137
+ // Parallel pre-tool hooks must not overwrite the first captured baseline.
138
+ if (!this.turnFiles.has(file)) this.turnFiles.set(file, registered);
139
+ }
140
+
141
+ /** Freeze the tool's result before later work by another process can alter the file. */
142
+ async onToolEnd(toolCallId: string): Promise<void> {
143
+ const files = this.toolTargets.get(toolCallId);
144
+ if (!files) return;
145
+ try {
146
+ for (const file of files) {
147
+ const registered = this.turnFiles.get(file);
148
+ if (!registered) continue;
149
+ try { registered.result = await this.captureFileState(file, !registered.unavailable); }
150
+ catch (error) {
151
+ if ((error as NodeJS.ErrnoException).code === "EISDIR" && !registered.baselineUnknown && registered.before === null) registered.result = null;
152
+ else registered.unavailable = true;
153
+ this.issues.add("capture");
154
+ }
155
+ }
156
+ } finally { this.toolTargets.delete(toolCallId); }
157
+ }
158
+
159
+ /** Keep only metadata in memory between tool calls. */
160
+ private async captureFileState(file: string, cache = true): Promise<FileState | null> {
161
+ const path = resolve(this.cwd, file);
162
+ let content: Buffer;
163
+ let mode: FileMode;
164
+ try {
165
+ const info = await lstat(path);
166
+ if (info.isSymbolicLink()) {
167
+ mode = "120000";
168
+ content = await readlink(path, { encoding: "buffer" });
169
+ } else {
170
+ if (!info.isFile()) throw Object.assign(new Error(`Unsupported file type: ${file}`), { code: info.isDirectory() ? "EISDIR" : "ENOTSUP" });
171
+ mode = info.mode & 0o100 ? "100755" : "100644";
172
+ if (info.size > MAX_PATCH_BYTES) {
173
+ const hash = createHash("sha256");
174
+ let binary = false;
175
+ const decoder = new TextDecoder("utf-8", { fatal: true });
176
+ for await (const chunk of createReadStream(path)) {
177
+ hash.update(chunk);
178
+ if (binary) continue;
179
+ try { decoder.decode(chunk, { stream: true }); binary = chunk.includes(0); }
180
+ catch { binary = true; }
181
+ }
182
+ if (!binary) {
183
+ try { decoder.decode(); } catch { binary = true; }
184
+ }
185
+ return { hash: hash.digest("hex"), mode, binary, tooLarge: true };
186
+ }
187
+ content = await readFile(path);
188
+ }
189
+ } catch (error) {
190
+ if (["ENOENT", "ENOTDIR"].includes((error as NodeJS.ErrnoException).code ?? "")) return null;
191
+ throw error;
192
+ }
193
+ const tooLarge = content.byteLength > MAX_PATCH_BYTES;
194
+ const hash = cache && !tooLarge ? await this.snapshotStore.put(content) : SnapshotStore.hash(content);
195
+ return { hash, mode, binary: isBinary(content), ...(tooLarge ? { tooLarge: true } : {}) };
196
+ }
197
+
198
+ // ------------------------------------------------------------------ hooks
199
+
200
+ /** Start a task without scanning unrelated workspaces. */
201
+ async onTurnStart(cwd = this.cwd): Promise<void> {
202
+ if (this.active) return this.starting;
203
+ this.active = true;
204
+ this.finalizing = undefined;
205
+ this.starting = this.startTurn(cwd).catch(() => { this.issues.add("capture"); });
206
+ await this.starting;
207
+ }
208
+
209
+ private async startTurn(cwd: string): Promise<void> {
210
+ const directory = await realpath(cwd).catch(() => resolve(cwd));
211
+ this.cwd = directory;
212
+ this.turnNumber += 1;
213
+ this.turnFiles.clear();
214
+ this.toolTargets.clear();
215
+ this.issues.clear();
216
+ }
217
+
218
+ /** Called before every shell tool execution (tool_call of bash/powershell). */
219
+ async onBashStart(toolCallId: string, command?: string, cwd = this.cwd, shell = "bash"): Promise<void> {
220
+ if (command !== undefined && shell === "bash") {
221
+ try {
222
+ const collected = await shellTargets(command, cwd);
223
+ if (collected.incomplete) this.issues.add("shell");
224
+ for (const target of collected.targets) {
225
+ await this.recordFileChange(target.path, { fromToolEvent: true, followSymlinks: target.followSymlinks, observeOnly: target.observeOnly, toolCallId });
226
+ }
227
+ } catch { this.issues.add("shell"); }
228
+ } else this.issues.add("shell");
229
+ }
230
+
231
+ async onBashEnd(toolCallId: string): Promise<void> {
232
+ await this.onToolEnd(toolCallId);
233
+ }
234
+
235
+ /** Persist only explicit Pi write targets after the task settles. */
236
+ async finalizeTurn(summary?: { language: Language; aborted: boolean }): Promise<void> {
237
+ if (this.finalizing) return this.finalizing;
238
+ if (!this.active) return;
239
+ this.finalizing = this.finishTurn(summary).finally(() => { this.active = false; });
240
+ return this.finalizing;
241
+ }
242
+
243
+ private async finishTurn(summary?: { language: Language; aborted: boolean }): Promise<void> {
244
+ await this.starting;
245
+ const patches: FilePatch[] = [];
246
+ let capped = false;
247
+ let total = 0;
248
+ for (const file of [...this.turnFiles.keys()].sort()) {
249
+ const registered = this.turnFiles.get(file)!;
250
+ let after = registered.result;
251
+ const oldHash = registered.before?.hash ?? null;
252
+ const oldMode = registered.baselineUnknown ? undefined : registered.before?.mode ?? null;
253
+ let unavailable = registered.unavailable ?? false;
254
+ try {
255
+ const pending = [...this.toolTargets.values()].some((files) => files.has(file));
256
+ if (pending) {
257
+ this.issues.add("capture");
258
+ if (registered.result === undefined) continue;
259
+ }
260
+ if (after === undefined && !unavailable) after = await this.captureFileState(file);
261
+ }
262
+ catch (error) {
263
+ if ((error as NodeJS.ErrnoException).code === "EISDIR" && oldMode === null) {
264
+ this.issues.add("capture");
265
+ continue;
266
+ }
267
+ unavailable = true;
268
+ this.issues.add("capture");
269
+ }
270
+ const newHash = after?.hash ?? null;
271
+ const newMode = after === undefined ? undefined : after?.mode ?? null;
272
+ // No-op registration (failed edit, touch without change): drop.
273
+ if (!unavailable && oldHash === newHash && oldMode === newMode && !registered.baselineUnknown) continue;
274
+
275
+ let patch: FilePatch;
276
+ const status = registered.unavailable ? "modified"
277
+ : oldHash === null && !registered.baselineUnknown ? "added"
278
+ : !unavailable && after === null ? "deleted" : "modified";
279
+ const binary = !unavailable && !capped && (registered.before?.binary || after?.binary);
280
+ const oversized = !unavailable && !binary && (registered.before?.tooLarge || after?.tooLarge);
281
+ if (unavailable || capped || binary || oversized) {
282
+ // Once the total cap is hit, remaining files degrade (opencode totalPatch).
283
+ patch = {
284
+ file,
285
+ status,
286
+ patch: binary ? "" : emptyPatch(file),
287
+ additions: 0,
288
+ deletions: 0,
289
+ ...(binary ? { binary: true } : {}),
290
+ ...(capped || oversized ? { tooLarge: true } : {}),
291
+ ...(unavailable ? { unavailable: true } : {}),
292
+ ...(registered.baselineUnknown ? { baselineUnknown: true } : {}),
293
+ oldHash,
294
+ ...(unavailable ? {} : { newHash }),
295
+ };
296
+ } else {
297
+ const oldContent = oldHash !== null ? await this.snapshotStore.get(oldHash) : null;
298
+ const newContent = newHash !== null ? await this.snapshotStore.get(newHash) : null;
299
+ if ((oldHash !== null && oldContent === null) || (newHash !== null && newContent === null)) {
300
+ this.issues.add("capture");
301
+ patch = { file, status, patch: emptyPatch(file), additions: 0, deletions: 0, unavailable: true, oldHash, newHash };
302
+ } else {
303
+ patch = makeFilePatch(file, oldContent, newContent, { oldHash, newHash });
304
+ }
305
+ }
306
+
307
+ if (oldMode !== undefined) patch.oldMode = oldMode;
308
+ if (newMode !== undefined) patch.newMode = newMode;
309
+
310
+ const bytes = Buffer.byteLength(patch.patch, "utf8");
311
+ if (total + bytes > MAX_TOTAL_PATCH_BYTES) {
312
+ capped = true;
313
+ patch = { ...patch, patch: emptyPatch(file), additions: 0, deletions: 0, tooLarge: true };
314
+ } else {
315
+ total += bytes;
316
+ }
317
+ patches.push(patch);
318
+ }
319
+
320
+ this.turnFiles.clear();
321
+ this.toolTargets.clear();
322
+
323
+ // Empty turns still carry their number so reload and Last turn remain accurate.
324
+ if (this.turnNumber === 0) return;
325
+
326
+ const data: TurnDiffEntryData = {
327
+ turn: this.turnNumber,
328
+ endedAt: new Date().toISOString(),
329
+ fileCount: patches.length,
330
+ patches,
331
+ cwd: this.cwd,
332
+ ...(summary ? { summary: { ...summary, issues: [...this.issues] } } : {}),
333
+ };
334
+ appendTurnDiff(this.pi.appendEntry.bind(this.pi), data);
335
+ this.turnDiffs.push(data);
336
+ }
337
+
338
+ noteUntrackedTool(): void {
339
+ this.issues.add("tools");
340
+ }
341
+
342
+ /** Release unfinished task state on shutdown or branch switch. */
343
+ async dispose(): Promise<void> {
344
+ await this.starting;
345
+ if (this.finalizing) await this.finalizing.catch(() => {});
346
+ this.toolTargets.clear();
347
+ this.active = false;
348
+ }
349
+
350
+ // -------------------------------------------------------------- accessors
351
+
352
+ /** All persisted turn diffs on the current branch, in order. */
353
+ turns(): readonly TurnDiffEntryData[] {
354
+ return this.turnDiffs;
355
+ }
356
+
357
+ /**
358
+ * Session-cumulative patches per file: first appearance old side → latest
359
+ * new side (opencode session-diff semantics). Recomputed from cached blobs
360
+ * via makeFilePatch when both sides are available; otherwise degrades to the
361
+ * file's last per-turn patch.
362
+ */
363
+ async sessionPatches(cwd = this.cwd): Promise<FilePatch[]> {
364
+ const root = await realpath(cwd).catch(() => resolve(cwd));
365
+ const first = new Map<string, FilePatch>();
366
+ const last = new Map<string, FilePatch>();
367
+ const interrupted = new Set<string>();
368
+ for (const turn of this.turnDiffs) {
369
+ for (const fp of turn.patches) {
370
+ const absolute = resolve(turn.cwd ?? root, fp.file);
371
+ const file = this.normalize(absolute, root) ?? absolute;
372
+ const patch = file === fp.file ? fp : { ...fp, file };
373
+ const previous = last.get(file);
374
+ if (previous && (previous.unavailable || patch.unavailable || previous.newHash === undefined || patch.oldHash === undefined || previous.newHash !== patch.oldHash || previous.newMode !== patch.oldMode)) interrupted.add(file);
375
+ if (!first.has(file)) first.set(file, patch);
376
+ last.set(file, patch);
377
+ }
378
+ }
379
+ const result: FilePatch[] = [];
380
+ let total = 0;
381
+ let capped = false;
382
+ const append = (patch: FilePatch) => {
383
+ const bytes = Buffer.byteLength(patch.patch);
384
+ if (capped || total + bytes > MAX_TOTAL_PATCH_BYTES) {
385
+ capped = true;
386
+ result.push({ ...patch, patch: emptyPatch(patch.file), tooLarge: true });
387
+ } else {
388
+ total += bytes;
389
+ result.push(patch);
390
+ }
391
+ };
392
+ for (const file of [...first.keys()].sort()) {
393
+ const f = first.get(file)!;
394
+ const l = last.get(file)!;
395
+ const oldHash = f.oldHash;
396
+ const newHash = l.newHash;
397
+ const oldMode = f.oldMode === undefined && oldHash === null ? null : f.oldMode;
398
+ const newMode = l.newMode === undefined && newHash === null ? null : l.newMode;
399
+ if (interrupted.has(file)) {
400
+ append({ ...l, cumulativeFallback: true });
401
+ continue;
402
+ }
403
+ if (!f.baselineUnknown && !f.unavailable && !l.unavailable && oldHash !== undefined && oldHash === newHash && (oldHash === null || oldMode === newMode)) continue;
404
+ // One recorded change is already a self-contained cumulative patch.
405
+ if (f === l) {
406
+ append(l);
407
+ continue;
408
+ }
409
+ const fallback: FilePatch = { ...l, cumulativeFallback: true };
410
+ if ((l.binary || l.tooLarge) && !f.baselineUnknown && !f.unavailable && !l.unavailable && oldHash !== undefined && newHash !== undefined) {
411
+ Object.assign(fallback, { status: oldHash === null ? "added" : newHash === null ? "deleted" : "modified", oldHash, oldMode });
412
+ }
413
+ if (f.baselineUnknown || f.unavailable || l.unavailable || oldHash === undefined || newHash === undefined || (oldMode === undefined) !== (newMode === undefined)) {
414
+ append(fallback);
415
+ continue;
416
+ }
417
+ const oldContent =
418
+ oldHash !== null ? await this.snapshotStore.get(oldHash) : null;
419
+ const newContent = newHash !== null ? await this.snapshotStore.get(newHash) : null;
420
+ if ((oldHash !== null && oldContent === null) || (newHash !== null && newContent === null)) {
421
+ // Cache miss (evicted / old session): degrade to the last turn patch.
422
+ append(fallback);
423
+ continue;
424
+ }
425
+ const recomputed = makeFilePatch(file, oldContent, newContent, {
426
+ oldHash,
427
+ newHash,
428
+ oldMode,
429
+ newMode,
430
+ baselineUnknown: f.baselineUnknown,
431
+ });
432
+ if (recomputed.oldHash === recomputed.newHash && recomputed.oldMode === recomputed.newMode && recomputed.status === "modified") {
433
+ // Net-zero across the session: file added and reverted, etc.
434
+ continue;
435
+ }
436
+ append(recomputed);
437
+ }
438
+ return result;
439
+ }
440
+
441
+ /**
442
+ * Rebuild Tracker state from `pi-diff.turn` custom entries on the active
443
+ * branch (session reload / resume / branch switch).
444
+ */
445
+ restoreFromSession(sessionManager: { getBranch(): SessionEntry[] }): void {
446
+ this.turnDiffs = collectTurnDiffs(sessionManager.getBranch());
447
+ this.turnNumber = this.turnDiffs.reduce((max, t) => Math.max(max, t.turn), 0);
448
+ this.turnFiles.clear();
449
+ this.toolTargets.clear();
450
+ this.active = false;
451
+ this.starting = undefined;
452
+ this.finalizing = undefined;
453
+ }
454
+
455
+ async cleanupCaches(): Promise<void> {
456
+ await this.snapshotStore.cleanup();
457
+ }
458
+ }