@lyrumu/pi-diff 0.1.0 → 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/README.md +22 -5
- package/README.zh-CN.md +22 -5
- package/index.ts +42 -20
- package/package.json +20 -7
- package/src/diff-engine.ts +11 -4
- package/src/git.ts +55 -12
- package/src/language.ts +72 -2
- package/src/shell-targets.ts +215 -0
- package/src/store.ts +20 -2
- package/src/tracker.ts +262 -312
- package/src/tui/diff-screen.ts +172 -36
- package/src/tui/file-tree-utils.ts +11 -2
- package/src/tui/file-tree.ts +12 -8
- package/src/tui/patch-diff.ts +556 -44
- package/src/tui/task-summary.ts +63 -0
- package/src/tui/text.ts +60 -1
package/src/tracker.ts
CHANGED
|
@@ -1,71 +1,54 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
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";
|
|
5
7
|
import type { ExtensionAPI, SessionEntry } from "@earendil-works/pi-coding-agent";
|
|
6
|
-
import { Git } from "./git.ts";
|
|
7
8
|
import { SnapshotStore } from "./snapshot.ts";
|
|
8
9
|
import {
|
|
9
10
|
MAX_TOTAL_PATCH_BYTES,
|
|
11
|
+
MAX_PATCH_BYTES,
|
|
10
12
|
emptyPatch,
|
|
13
|
+
isBinary,
|
|
11
14
|
makeFilePatch,
|
|
12
15
|
type FilePatch,
|
|
16
|
+
type FileMode,
|
|
13
17
|
} from "./diff-engine.ts";
|
|
14
|
-
import { appendTurnDiff, collectTurnDiffs, type TurnDiffEntryData } from "./store.ts";
|
|
15
|
-
|
|
16
|
-
|
|
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
|
+
}
|
|
17
28
|
|
|
18
29
|
/** A file registered for the current turn. */
|
|
19
30
|
interface RegisteredFile {
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
/** True when the old side could not be recovered (no-git bash change). */
|
|
31
|
+
before: FileState | null;
|
|
32
|
+
/** True when capturing the pre-execution contents failed. */
|
|
23
33
|
baselineUnknown: boolean;
|
|
24
34
|
unavailable?: boolean;
|
|
35
|
+
result?: FileState | null;
|
|
25
36
|
}
|
|
26
37
|
|
|
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
|
-
*/
|
|
38
|
+
/** Only explicit write targets enter task history; workspace scans cannot prove authorship. */
|
|
50
39
|
export class Tracker {
|
|
51
40
|
readonly snapshotStore: SnapshotStore;
|
|
52
|
-
private
|
|
53
|
-
private git: boolean | null = null;
|
|
54
|
-
private gitPrefix = "";
|
|
41
|
+
private cwd = process.cwd();
|
|
55
42
|
|
|
56
43
|
private turnNumber = 0;
|
|
57
44
|
private turnFiles = new Map<string, RegisteredFile>();
|
|
58
|
-
|
|
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>();
|
|
45
|
+
private toolTargets = new Map<string, Set<string>>();
|
|
67
46
|
/** Restored / accumulated turn diffs on the current branch. */
|
|
68
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>();
|
|
69
52
|
|
|
70
53
|
private readonly pi: ExtensionAPI;
|
|
71
54
|
|
|
@@ -74,313 +57,256 @@ export class Tracker {
|
|
|
74
57
|
this.snapshotStore = snapshotStore;
|
|
75
58
|
}
|
|
76
59
|
|
|
77
|
-
//
|
|
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
|
+
}
|
|
78
70
|
|
|
79
71
|
/**
|
|
80
|
-
*
|
|
81
|
-
*
|
|
82
|
-
*
|
|
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.
|
|
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.
|
|
90
75
|
*/
|
|
91
|
-
async
|
|
92
|
-
if (
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
if (
|
|
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
|
+
}
|
|
99
87
|
}
|
|
100
|
-
|
|
88
|
+
path = resolve(opts.cwd ?? this.cwd, path);
|
|
101
89
|
try {
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
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. */ }
|
|
108
104
|
}
|
|
109
|
-
return [...changed];
|
|
110
105
|
}
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
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;
|
|
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);
|
|
133
112
|
}
|
|
134
|
-
const
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
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) {
|
|
138
117
|
try {
|
|
139
|
-
const
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
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);
|
|
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"); }
|
|
149
124
|
}
|
|
125
|
+
return;
|
|
150
126
|
}
|
|
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
127
|
|
|
185
128
|
let registered: RegisteredFile;
|
|
186
129
|
try {
|
|
187
|
-
|
|
188
|
-
|
|
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
|
-
}
|
|
130
|
+
// Capture immediately before Pi's first write, excluding earlier changes by other actors.
|
|
131
|
+
registered = { before: await this.captureFileState(file), baselineUnknown: false };
|
|
209
132
|
} catch (error) {
|
|
210
|
-
|
|
211
|
-
if ((error as NodeJS.ErrnoException).code
|
|
212
|
-
registered = {
|
|
133
|
+
this.issues.add("capture");
|
|
134
|
+
if (["EISDIR", "ENOTSUP"].includes((error as NodeJS.ErrnoException).code ?? "")) return;
|
|
135
|
+
registered = { before: null, baselineUnknown: true, unavailable: true };
|
|
213
136
|
}
|
|
214
|
-
// Parallel hooks
|
|
137
|
+
// Parallel pre-tool hooks must not overwrite the first captured baseline.
|
|
215
138
|
if (!this.turnFiles.has(file)) this.turnFiles.set(file, registered);
|
|
216
139
|
}
|
|
217
140
|
|
|
218
|
-
|
|
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;
|
|
219
145
|
try {
|
|
220
|
-
|
|
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
|
+
}
|
|
221
189
|
} catch (error) {
|
|
222
190
|
if (["ENOENT", "ENOTDIR"].includes((error as NodeJS.ErrnoException).code ?? "")) return null;
|
|
223
191
|
throw error;
|
|
224
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 } : {}) };
|
|
225
196
|
}
|
|
226
197
|
|
|
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
|
-
}
|
|
198
|
+
// ------------------------------------------------------------------ hooks
|
|
245
199
|
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
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;
|
|
250
207
|
}
|
|
251
208
|
|
|
252
|
-
|
|
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> {
|
|
209
|
+
private async startTurn(cwd: string): Promise<void> {
|
|
210
|
+
const directory = await realpath(cwd).catch(() => resolve(cwd));
|
|
211
|
+
this.cwd = directory;
|
|
260
212
|
this.turnNumber += 1;
|
|
261
213
|
this.turnFiles.clear();
|
|
262
|
-
this.
|
|
263
|
-
this.
|
|
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
|
-
}
|
|
214
|
+
this.toolTargets.clear();
|
|
215
|
+
this.issues.clear();
|
|
289
216
|
}
|
|
290
217
|
|
|
291
218
|
/** Called before every shell tool execution (tool_call of bash/powershell). */
|
|
292
|
-
async onBashStart(toolCallId: string): Promise<void> {
|
|
293
|
-
if (
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
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");
|
|
298
229
|
}
|
|
299
230
|
|
|
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
231
|
async onBashEnd(toolCallId: string): Promise<void> {
|
|
305
|
-
|
|
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);
|
|
232
|
+
await this.onToolEnd(toolCallId);
|
|
312
233
|
}
|
|
313
234
|
|
|
314
|
-
/**
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
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
|
-
}
|
|
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
|
+
}
|
|
335
242
|
|
|
243
|
+
private async finishTurn(summary?: { language: Language; aborted: boolean }): Promise<void> {
|
|
244
|
+
await this.starting;
|
|
336
245
|
const patches: FilePatch[] = [];
|
|
337
246
|
let capped = false;
|
|
338
247
|
let total = 0;
|
|
339
248
|
for (const file of [...this.turnFiles.keys()].sort()) {
|
|
340
249
|
const registered = this.turnFiles.get(file)!;
|
|
341
|
-
let
|
|
250
|
+
let after = registered.result;
|
|
251
|
+
const oldHash = registered.before?.hash ?? null;
|
|
252
|
+
const oldMode = registered.baselineUnknown ? undefined : registered.before?.mode ?? null;
|
|
342
253
|
let unavailable = registered.unavailable ?? false;
|
|
343
|
-
try {
|
|
344
|
-
|
|
345
|
-
|
|
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;
|
|
346
272
|
// No-op registration (failed edit, touch without change): drop.
|
|
347
|
-
if (!unavailable &&
|
|
273
|
+
if (!unavailable && oldHash === newHash && oldMode === newMode && !registered.baselineUnknown) continue;
|
|
348
274
|
|
|
349
275
|
let patch: FilePatch;
|
|
350
276
|
const status = registered.unavailable ? "modified"
|
|
351
|
-
:
|
|
352
|
-
: !unavailable &&
|
|
353
|
-
|
|
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) {
|
|
354
282
|
// Once the total cap is hit, remaining files degrade (opencode totalPatch).
|
|
355
283
|
patch = {
|
|
356
284
|
file,
|
|
357
285
|
status,
|
|
358
|
-
patch: emptyPatch(file),
|
|
286
|
+
patch: binary ? "" : emptyPatch(file),
|
|
359
287
|
additions: 0,
|
|
360
288
|
deletions: 0,
|
|
361
|
-
...(
|
|
289
|
+
...(binary ? { binary: true } : {}),
|
|
290
|
+
...(capped || oversized ? { tooLarge: true } : {}),
|
|
362
291
|
...(unavailable ? { unavailable: true } : {}),
|
|
363
292
|
...(registered.baselineUnknown ? { baselineUnknown: true } : {}),
|
|
364
|
-
oldHash
|
|
293
|
+
oldHash,
|
|
365
294
|
...(unavailable ? {} : { newHash }),
|
|
366
295
|
};
|
|
367
296
|
} else {
|
|
368
|
-
const oldContent =
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
unavailable: true, oldHash
|
|
373
|
-
}
|
|
374
|
-
|
|
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(() => {});
|
|
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 });
|
|
381
304
|
}
|
|
382
305
|
}
|
|
383
306
|
|
|
307
|
+
if (oldMode !== undefined) patch.oldMode = oldMode;
|
|
308
|
+
if (newMode !== undefined) patch.newMode = newMode;
|
|
309
|
+
|
|
384
310
|
const bytes = Buffer.byteLength(patch.patch, "utf8");
|
|
385
311
|
if (total + bytes > MAX_TOTAL_PATCH_BYTES) {
|
|
386
312
|
capped = true;
|
|
@@ -392,8 +318,7 @@ export class Tracker {
|
|
|
392
318
|
}
|
|
393
319
|
|
|
394
320
|
this.turnFiles.clear();
|
|
395
|
-
this.
|
|
396
|
-
this.unavailableBaseline.clear();
|
|
321
|
+
this.toolTargets.clear();
|
|
397
322
|
|
|
398
323
|
// Empty turns still carry their number so reload and Last turn remain accurate.
|
|
399
324
|
if (this.turnNumber === 0) return;
|
|
@@ -403,9 +328,23 @@ export class Tracker {
|
|
|
403
328
|
endedAt: new Date().toISOString(),
|
|
404
329
|
fileCount: patches.length,
|
|
405
330
|
patches,
|
|
331
|
+
cwd: this.cwd,
|
|
332
|
+
...(summary ? { summary: { ...summary, issues: [...this.issues] } } : {}),
|
|
406
333
|
};
|
|
407
|
-
this.turnDiffs.push(data);
|
|
408
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;
|
|
409
348
|
}
|
|
410
349
|
|
|
411
350
|
// -------------------------------------------------------------- accessors
|
|
@@ -421,13 +360,20 @@ export class Tracker {
|
|
|
421
360
|
* via makeFilePatch when both sides are available; otherwise degrades to the
|
|
422
361
|
* file's last per-turn patch.
|
|
423
362
|
*/
|
|
424
|
-
async sessionPatches(): Promise<FilePatch[]> {
|
|
363
|
+
async sessionPatches(cwd = this.cwd): Promise<FilePatch[]> {
|
|
364
|
+
const root = await realpath(cwd).catch(() => resolve(cwd));
|
|
425
365
|
const first = new Map<string, FilePatch>();
|
|
426
366
|
const last = new Map<string, FilePatch>();
|
|
367
|
+
const interrupted = new Set<string>();
|
|
427
368
|
for (const turn of this.turnDiffs) {
|
|
428
369
|
for (const fp of turn.patches) {
|
|
429
|
-
|
|
430
|
-
|
|
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);
|
|
431
377
|
}
|
|
432
378
|
}
|
|
433
379
|
const result: FilePatch[] = [];
|
|
@@ -448,14 +394,24 @@ export class Tracker {
|
|
|
448
394
|
const l = last.get(file)!;
|
|
449
395
|
const oldHash = f.oldHash;
|
|
450
396
|
const newHash = l.newHash;
|
|
451
|
-
|
|
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;
|
|
452
404
|
// One recorded change is already a self-contained cumulative patch.
|
|
453
405
|
if (f === l) {
|
|
454
406
|
append(l);
|
|
455
407
|
continue;
|
|
456
408
|
}
|
|
457
|
-
|
|
458
|
-
|
|
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);
|
|
459
415
|
continue;
|
|
460
416
|
}
|
|
461
417
|
const oldContent =
|
|
@@ -463,15 +419,17 @@ export class Tracker {
|
|
|
463
419
|
const newContent = newHash !== null ? await this.snapshotStore.get(newHash) : null;
|
|
464
420
|
if ((oldHash !== null && oldContent === null) || (newHash !== null && newContent === null)) {
|
|
465
421
|
// Cache miss (evicted / old session): degrade to the last turn patch.
|
|
466
|
-
append(
|
|
422
|
+
append(fallback);
|
|
467
423
|
continue;
|
|
468
424
|
}
|
|
469
425
|
const recomputed = makeFilePatch(file, oldContent, newContent, {
|
|
470
426
|
oldHash,
|
|
471
427
|
newHash,
|
|
428
|
+
oldMode,
|
|
429
|
+
newMode,
|
|
472
430
|
baselineUnknown: f.baselineUnknown,
|
|
473
431
|
});
|
|
474
|
-
if (recomputed.oldHash === recomputed.newHash && recomputed.status === "modified") {
|
|
432
|
+
if (recomputed.oldHash === recomputed.newHash && recomputed.oldMode === recomputed.newMode && recomputed.status === "modified") {
|
|
475
433
|
// Net-zero across the session: file added and reverted, etc.
|
|
476
434
|
continue;
|
|
477
435
|
}
|
|
@@ -488,21 +446,13 @@ export class Tracker {
|
|
|
488
446
|
this.turnDiffs = collectTurnDiffs(sessionManager.getBranch());
|
|
489
447
|
this.turnNumber = this.turnDiffs.reduce((max, t) => Math.max(max, t.turn), 0);
|
|
490
448
|
this.turnFiles.clear();
|
|
491
|
-
this.
|
|
492
|
-
this.
|
|
493
|
-
this.
|
|
494
|
-
this.
|
|
449
|
+
this.toolTargets.clear();
|
|
450
|
+
this.active = false;
|
|
451
|
+
this.starting = undefined;
|
|
452
|
+
this.finalizing = undefined;
|
|
495
453
|
}
|
|
496
454
|
|
|
497
455
|
async cleanupCaches(): Promise<void> {
|
|
498
456
|
await this.snapshotStore.cleanup();
|
|
499
457
|
}
|
|
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
458
|
}
|