@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.
@@ -0,0 +1,161 @@
1
+ import { visibleWidth } from "@earendil-works/pi-tui";
2
+
3
+ export type Language = "en" | "zh-CN";
4
+ export type LocalizedText = string | ((language: Language) => string);
5
+
6
+ export function localize(text: LocalizedText, language: Language): string {
7
+ return typeof text === "function" ? text(language) : text;
8
+ }
9
+
10
+ function fitFooterSegments(segments: readonly string[], maxWidth?: number): string {
11
+ if (maxWidth === undefined || segments.length <= 2) return segments.join(" · ");
12
+ let out = segments[0]!;
13
+ let used = visibleWidth(out);
14
+ for (let i = 1; i < segments.length; i++) {
15
+ const part = segments[i]!;
16
+ const nextWidth = visibleWidth(part) + 3;
17
+ // Always keep at least the first two segments (language + focus).
18
+ if (i >= 2 && used + nextWidth > maxWidth) break;
19
+ out += " · " + part;
20
+ used += nextWidth;
21
+ }
22
+ return out;
23
+ }
24
+
25
+ const en = {
26
+ lastTurn: "Last turn",
27
+ turn: (turn: number) => `Last turn · Turn ${turn}`,
28
+ session: "Session total",
29
+ unstaged: "Unstaged",
30
+ working: "Uncommitted",
31
+ branch: "All branch changes",
32
+ files: "Files",
33
+ externalFiles: "External files",
34
+ fileCount: (count: number) => `${count} ${count === 1 ? "file" : "files"}`,
35
+ moreFiles: (count: number) => `… and ${count} more ${count === 1 ? "file" : "files"}`,
36
+ switchView: "[Switch view]",
37
+ showFiles: "[Show files]",
38
+ dragDivider: "↔ Drag to resize",
39
+ unifiedOnly: "[Unified only]",
40
+ fixedUnified: "Unified view (added/deleted file)",
41
+ unified: "Unified view",
42
+ split: "Split view",
43
+ wrap: "Auto wrap",
44
+ foldedLines: (count: number) => `⋯ ${count} unchanged lines · Click to expand`,
45
+ expandContext: "[Expand all]",
46
+ foldContext: "[Fold context]",
47
+ changeProgress: (current: number | undefined, total: number) =>
48
+ current === undefined ? `${total} ${total === 1 ? "change" : "changes"}` : `Change ${current}/${total}`,
49
+ noFileToSwitch: "No file to switch views",
50
+ tooNarrow: "Diff pane too narrow; widen the terminal for split view",
51
+ noChanges: "No file changes",
52
+ unavailable: "File contents unavailable",
53
+ binary: "Binary file changed",
54
+ tooLarge: "Diff exceeds the 10 MB limit",
55
+ deletedUnknown: "File deleted; previous contents unknown",
56
+ noPatch: "No diff content available for this file",
57
+ noTextChanges: "No text changes (empty file or metadata-only change)",
58
+ baselineUnknown: "Previous contents unknown",
59
+ cumulativeFallback: "Showing last turn only; session total could not be fully restored",
60
+ noHistory: "No valid change records in this old session; past changes unavailable",
61
+ noTurns: "No turn records; only tasks after enabling the extension are recorded",
62
+ emptyTurn: "No file changes in this turn",
63
+ unavailableTotal: "No usable history; complete session total unavailable",
64
+ emptySession: "No cumulative changes in this session",
65
+ incompleteHistory: "History incomplete",
66
+ taskChanges: "This task's changes",
67
+ taskAborted: "Interrupted",
68
+ noChangesDetected: "No file changes detected",
69
+ noChangesLimited: "No recorded changes",
70
+ taskReview: "View changes /diff last",
71
+ summaryRequiresUpgrade: "pi-diff: upgrade to a host with entry rendering for automatic task receipts. /diff remains available.",
72
+ trackingIssue: (issue: "shell" | "scan" | "capture" | "tools") => ({
73
+ shell: "Some shell write targets were not identified and were not included.",
74
+ scan: "Tracking incomplete: a workspace scan failed; some changes may be missing.",
75
+ capture: "A target could not be captured reliably or another write interrupted its contents.",
76
+ tools: "Custom tools without identifiable write events are not included.",
77
+ })[issue],
78
+ loading: "Loading changes…",
79
+ loadFailed: (error: string) => `Failed to load: ${error}`,
80
+ requiresTui: "pi-diff requires an interactive TUI",
81
+ error: (error: string) => `pi-diff: ${error}`,
82
+ footer: (fixed: boolean, focus: "tree" | "diff", maxWidth?: number) => fitFooterSegments([
83
+ "l/L 中文",
84
+ `[/] Focus: ${focus === "tree" ? "Files" : "Diff"}`,
85
+ ...(focus === "diff" ? ["n/p Changes"] : []),
86
+ "Tab Scope",
87
+ fixed ? "A/D Unified only" : "v/V Layout",
88
+ `j/k ${focus === "tree" ? "Files" : "Scroll"}`,
89
+ "Esc/q Close",
90
+ ], maxWidth),
91
+ };
92
+
93
+ export const messages: Record<Language, typeof en> = {
94
+ en,
95
+ "zh-CN": {
96
+ lastTurn: "最近一轮",
97
+ turn: (turn) => `最近一轮 · 第 ${turn} 轮`,
98
+ session: "会话累计",
99
+ unstaged: "未暂存",
100
+ working: "未提交",
101
+ branch: "分支全部改动",
102
+ files: "文件",
103
+ externalFiles: "项目外文件",
104
+ fileCount: (count) => `${count} 个文件`,
105
+ moreFiles: (count) => `… 另有 ${count} 个文件`,
106
+ switchView: "[切换视图]",
107
+ showFiles: "[展开文件树]",
108
+ dragDivider: "↔ 拖动调整宽度",
109
+ unifiedOnly: "[仅合并视图]",
110
+ fixedUnified: "合并视图(新增/删除文件)",
111
+ unified: "合并视图",
112
+ split: "拆分视图",
113
+ wrap: "自动换行",
114
+ foldedLines: (count) => `⋯ 已折叠 ${count} 行未修改内容 · 点击展开`,
115
+ expandContext: "[展开全部]",
116
+ foldContext: "[折叠上下文]",
117
+ changeProgress: (current, total) => current === undefined ? `${total} 处改动` : `改动 ${current}/${total}`,
118
+ noFileToSwitch: "没有可切换的文件",
119
+ tooNarrow: "右侧宽度不足,请拉宽终端后切换拆分视图",
120
+ noChanges: "没有文件改动",
121
+ unavailable: "文件内容不可用",
122
+ binary: "二进制文件已改变",
123
+ tooLarge: "差异超过 10MB 上限",
124
+ deletedUnknown: "文件已删除;修改前内容未知",
125
+ noPatch: "此文件没有可用的差异内容",
126
+ noTextChanges: "没有文本变化(空文件或仅元数据变化)",
127
+ baselineUnknown: "修改前内容未知",
128
+ cumulativeFallback: "仅显示最后一轮,累计无法完整恢复",
129
+ noHistory: "旧会话没有有效的改动记录,无法展示当时变化",
130
+ noTurns: "没有轮次记录;仅记录插件启用后的任务",
131
+ emptyTurn: "本轮没有文件改动",
132
+ unavailableTotal: "没有可用的历史改动,无法展示完整累计",
133
+ emptySession: "当前会话没有累计改动",
134
+ incompleteHistory: "历史记录不完整",
135
+ taskChanges: "本次任务变更",
136
+ taskAborted: "任务已中止",
137
+ noChangesDetected: "未检测到文件变更",
138
+ noChangesLimited: "没有已记录的变更",
139
+ taskReview: "查看变更 /diff last",
140
+ summaryRequiresUpgrade: "pi-diff:自动任务摘要需要支持记录渲染的宿主。/diff 仍可使用。",
141
+ trackingIssue: (issue) => ({
142
+ shell: "部分 Shell 写入目标无法识别,未收录未确认的文件。",
143
+ scan: "追踪不完整:目录扫描失败,可能遗漏变更。",
144
+ capture: "部分目标无法可靠捕获,或两次写入之间发生了内容冲突。",
145
+ tools: "缺少可识别写入事件的自定义工具未计入任务。",
146
+ })[issue],
147
+ loading: "正在加载改动…",
148
+ loadFailed: (error) => `加载失败:${error}`,
149
+ requiresTui: "pi-diff 需要在交互式 TUI 中使用",
150
+ error: (error) => `pi-diff:${error}`,
151
+ footer: (fixed, focus, maxWidth) => fitFooterSegments([
152
+ "l/L English",
153
+ `[/] 焦点:${focus === "tree" ? "文件树" : "内容"}`,
154
+ ...(focus === "diff" ? ["n/p 跳转"] : []),
155
+ "Tab 范围",
156
+ fixed ? "A/D 仅合并" : "v/V 布局",
157
+ `j/k ${focus === "tree" ? "文件" : "滚动"}`,
158
+ "Esc/q 关闭",
159
+ ], maxWidth),
160
+ },
161
+ };
@@ -0,0 +1,47 @@
1
+ import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
2
+ import { randomUUID } from "node:crypto";
3
+ import { dirname, join } from "node:path";
4
+ import { DATA_DIR } from "./snapshot.ts";
5
+ import type { DiffView } from "./tui/patch-diff.ts";
6
+ import type { Language } from "./language.ts";
7
+
8
+ export const VIEW_PREFERENCE_PATH = join(DATA_DIR, "view.json");
9
+ export const LANGUAGE_PREFERENCE_PATH = join(DATA_DIR, "language.json");
10
+
11
+ export async function loadViewPreference(file: string): Promise<DiffView | undefined> {
12
+ try {
13
+ const value: unknown = JSON.parse(await readFile(file, "utf8"));
14
+ if (typeof value !== "object" || value === null || !("view" in value)) return undefined;
15
+ return value.view === "unified" || value.view === "split" ? value.view : undefined;
16
+ } catch {
17
+ return undefined;
18
+ }
19
+ }
20
+
21
+ export async function saveViewPreference(file: string, view: DiffView): Promise<void> {
22
+ await savePreference(file, { view });
23
+ }
24
+
25
+ export async function loadLanguagePreference(file: string): Promise<Language> {
26
+ try {
27
+ const value: unknown = JSON.parse(await readFile(file, "utf8"));
28
+ if (typeof value === "object" && value !== null && "language" in value && value.language === "zh-CN") return "zh-CN";
29
+ } catch {}
30
+ return "en";
31
+ }
32
+
33
+ export async function saveLanguagePreference(file: string, language: Language): Promise<void> {
34
+ await savePreference(file, { language });
35
+ }
36
+
37
+ /** Replace atomically so a failed write never destroys the previous choice. */
38
+ async function savePreference(file: string, value: { view: DiffView } | { language: Language }): Promise<void> {
39
+ const temporary = `${file}.${randomUUID()}.tmp`;
40
+ try {
41
+ await mkdir(dirname(file), { recursive: true });
42
+ await writeFile(temporary, JSON.stringify(value) + "\n");
43
+ await rename(temporary, file);
44
+ } finally {
45
+ await rm(temporary, { force: true }).catch(() => {});
46
+ }
47
+ }
@@ -0,0 +1,215 @@
1
+ import { stat } from "node:fs/promises";
2
+ import { homedir } from "node:os";
3
+ import { basename, isAbsolute, join, resolve } from "node:path";
4
+
5
+ export interface ShellTarget {
6
+ path: string;
7
+ followSymlinks: boolean;
8
+ observeOnly?: boolean;
9
+ }
10
+
11
+ interface Token {
12
+ text: string;
13
+ operator: boolean;
14
+ literal: boolean;
15
+ expandHome?: boolean;
16
+ }
17
+
18
+ /** Read literal words without evaluating shell code or expanding variables. */
19
+ function tokenize(command: string): Token[] | undefined {
20
+ const tokens: Token[] = [];
21
+ let text = "";
22
+ let started = false;
23
+ let literal = true;
24
+ let expandHome = false;
25
+ let quote = "";
26
+ const flush = () => {
27
+ if (started) tokens.push({ text, operator: false, literal, expandHome });
28
+ text = ""; started = false; literal = true; expandHome = false;
29
+ };
30
+ for (let i = 0; i < command.length; i++) {
31
+ const ch = command[i]!;
32
+ if (ch === "\\" && quote !== "'") {
33
+ const next = command[++i];
34
+ if (next === undefined) return undefined;
35
+ if (next === "\n") continue;
36
+ if (quote === '"' && !['"', "\\", "$", "`"].includes(next)) text += "\\";
37
+ text += next; started = true;
38
+ continue;
39
+ }
40
+ if (quote) {
41
+ if (ch === quote) quote = "";
42
+ else {
43
+ if (quote === '"' && (ch === "$" || ch === "`")) literal = false;
44
+ text += ch;
45
+ }
46
+ continue;
47
+ }
48
+ if (ch === "'" || ch === '"') { quote = ch; started = true; continue; }
49
+ if (ch === "#" && !started) {
50
+ while (i < command.length && command[i] !== "\n") i++;
51
+ i--; continue;
52
+ }
53
+ if (ch === "\n" || /[;&|<>]/.test(ch)) {
54
+ // A numeric word immediately before a redirect is a file descriptor.
55
+ const fd = /[<>]/.test(ch) && started && /^\d+$/.test(text) ? text : "";
56
+ if (fd) { text = ""; started = false; }
57
+ flush();
58
+ const previous = tokens.at(-1);
59
+ if (ch === "\n" && previous?.operator && ["&&", "||", "|"].includes(previous.text)) continue;
60
+ let op = ch;
61
+ if (["&&", "||", ">>", "<<", ">|", ">&", "<&", "&>"].includes(ch + command[i + 1])) op += command[++i];
62
+ tokens.push({ text: fd + op, operator: true, literal: true });
63
+ continue;
64
+ }
65
+ if (ch === " " || ch === "\t") { flush(); continue; }
66
+ // Subshells, process substitutions and heredocs require a real shell parser.
67
+ if (ch === "(" || ch === ")" || ch === "`") return undefined;
68
+ if (/[\$*?\[\]{}]/.test(ch)) literal = false;
69
+ if (!started && ch === "~") expandHome = true;
70
+ text += ch; started = true;
71
+ }
72
+ if (quote) return undefined;
73
+ flush();
74
+ return tokens;
75
+ }
76
+
77
+ /**
78
+ * Candidate files only: a target is reported as changed only after comparing bytes.
79
+ * shortcut: literal local commands only; add explicit resolvers when more command forms are needed.
80
+ */
81
+ export async function shellTargets(command: string, cwd: string): Promise<{ targets: ShellTarget[]; incomplete: boolean }> {
82
+ const tokens = tokenize(command);
83
+ if (!tokens || tokens.some((token) => token.operator && /<<|&>/.test(token.text))) return { targets: [], incomplete: true };
84
+ const targets: ShellTarget[] = [];
85
+ let incomplete = false;
86
+ let directory: string | undefined = cwd;
87
+ let conditionalDirectory = false;
88
+ const path = (token: Token) => {
89
+ if (!token.literal || !token.text) { incomplete = true; return undefined; }
90
+ const value = token.expandHome && (token.text === "~" || token.text.startsWith("~/"))
91
+ ? homedir() + token.text.slice(1) : token.text;
92
+ if (isAbsolute(value)) return resolve(value);
93
+ if (directory === undefined) { incomplete = true; return undefined; }
94
+ return resolve(directory, value);
95
+ };
96
+ const add = (token: Token, followSymlinks: boolean) => {
97
+ const value = path(token);
98
+ if (value && value !== "/dev/null") targets.push({ path: value, followSymlinks });
99
+ };
100
+ for (let start = 0; start < tokens.length;) {
101
+ const previous = tokens[start - 1]?.text;
102
+ // A successful directory change is guaranteed only for the rest of its && chain.
103
+ if (conditionalDirectory && previous !== "&&") directory = undefined;
104
+ let end = start;
105
+ while (end < tokens.length && !(tokens[end]!.operator && ["&&", "||", ";", "\n", "|", "&"].includes(tokens[end]!.text))) end++;
106
+ const separator = tokens[end]?.text;
107
+ if (separator === "||" || separator === "&") incomplete = true;
108
+ const args: Token[] = [];
109
+ for (let i = start; i < end; i++) {
110
+ const token = tokens[i]!;
111
+ if (!token.operator) { args.push(token); continue; }
112
+ const operand = tokens[++i];
113
+ if (!operand || operand.operator) { incomplete = true; continue; }
114
+ if (/^\d*[>][&]$|^\d*<[&]$/.test(token.text)) {
115
+ if (!/^\d+$|^-$/.test(operand.text)) incomplete = true;
116
+ } else if (/^\d*(>|>>|>\|)$/.test(token.text)) add(operand, true);
117
+ else if (!/^\d*<$/.test(token.text)) incomplete = true;
118
+ }
119
+ start = end + 1;
120
+ if (!args.length) continue;
121
+ if (args.some((token) => !token.literal)) incomplete = true;
122
+ const name = args.shift()!;
123
+ if (!name.literal) { incomplete = true; continue; }
124
+ const tool = basename(name.text);
125
+ const invoked = name.text === "builtin" || name.text === "command"
126
+ ? args.find((arg) => arg.text !== "--" && arg.text !== "-p")?.text : name.text;
127
+ if (invoked && ["cd", "pushd", "popd", "source", ".", "eval"].includes(invoked)) {
128
+ const target = args[0];
129
+ conditionalDirectory = true;
130
+ if (name.text === "cd" && args.length === 1 && target && !target.text.startsWith("-") && separator === "&&" && previous !== "||" && previous !== "|") {
131
+ directory = path(target);
132
+ } else {
133
+ incomplete = true;
134
+ directory = undefined;
135
+ }
136
+ continue;
137
+ }
138
+ if (["cat", "grep", "rg", "ls", "pwd", "head", "tail", "wc", "stat", "readlink", "echo", "printf", "test", "[", "true", "false"].includes(tool)) {
139
+ if (args.some((arg) => arg.text.startsWith("--pre"))) incomplete = true;
140
+ // Observed paths never establish write ownership.
141
+ if (["cat", "grep", "head", "tail", "wc", "stat", "readlink"].includes(tool)) {
142
+ for (const arg of args.filter((arg) => arg.literal && !arg.text.startsWith("-"))) {
143
+ const file = path(arg);
144
+ if (file && (tool === "cat" || await stat(file).then((info) => info.isFile(), () => false))) targets.push({ path: file, followSymlinks: true, observeOnly: true });
145
+ }
146
+ }
147
+ continue;
148
+ }
149
+ if (tool === "git" && ["status", "diff", "log", "show", "rev-parse", "ls-files", "ls-tree", "check-ignore"].includes(args[0]?.text ?? "")) {
150
+ if (args.some((arg) => /^--(?:output|ext-diff)/.test(arg.text))) incomplete = true;
151
+ continue;
152
+ }
153
+ if (tool === "find") {
154
+ if (args.some((arg) => /^-(?:exec|execdir|delete|fprint|fprintf|fls|ok|okdir)/.test(arg.text))) incomplete = true;
155
+ continue;
156
+ }
157
+ const flags: Record<string, RegExp> = {
158
+ cp: /^-[fpvn]+$|^--(?:force|preserve|verbose|no-clobber)$/,
159
+ mv: /^-[fvn]+$|^--(?:force|verbose|no-clobber)$/,
160
+ rm: /^-[frRdv]+$|^--(?:force|recursive|dir|verbose)$/,
161
+ touch: /^-[amc]+$|^--no-create$/,
162
+ chmod: /^-[vcf]+$/,
163
+ tee: /^-a$|^--append$/,
164
+ ln: /^-[sfnv]+$/,
165
+ };
166
+ if (tool === "sed") {
167
+ if (args[0]?.text !== "-i") { incomplete = true; continue; }
168
+ const inputs = args.slice(1);
169
+ if (inputs[0]?.text === "") inputs.shift(); // BSD sed's empty backup suffix.
170
+ const expression = inputs.shift();
171
+ // sed's e/w/r commands and flags can access paths hidden inside the expression.
172
+ if (!expression?.literal || !/^s([^\w\s\\]).*\1.*\1g?$/.test(expression.text)) incomplete = true;
173
+ if (!inputs.length || inputs.some((arg) => arg.text.startsWith("-"))) { incomplete = true; continue; }
174
+ for (const arg of inputs) add(arg, false);
175
+ continue;
176
+ }
177
+ const allowed = flags[tool];
178
+ if (!allowed) { incomplete = true; continue; }
179
+ let operands = args;
180
+ if (tool !== "chmod") {
181
+ let i = 0;
182
+ while (i < args.length && args[i]!.text.startsWith("-")) {
183
+ if (args[i]!.text === "--") { i++; break; }
184
+ if (!allowed.test(args[i]!.text)) { incomplete = true; break; }
185
+ i++;
186
+ }
187
+ if (i < args.length && args[i]!.text.startsWith("-") && args[i - 1]?.text !== "--") continue;
188
+ operands = args.slice(i);
189
+ } else {
190
+ while (operands[0] && allowed.test(operands[0].text)) operands = operands.slice(1);
191
+ const mode = operands.shift();
192
+ if (!mode?.literal || !/^[0-7]{3,4}$|^[ugoa]*[+=-][rwxXstugo,+=-]+$/.test(mode.text)) { incomplete = true; continue; }
193
+ if (operands[0]?.text === "--") operands.shift();
194
+ }
195
+ if (!operands.length) { incomplete = true; continue; }
196
+ if (tool === "cp" || tool === "mv" || tool === "ln") {
197
+ const target = operands.pop()!;
198
+ const destination = path(target);
199
+ if (!destination || !operands.length) { incomplete = true; continue; }
200
+ let intoDirectory = target.text.endsWith("/");
201
+ if (!intoDirectory) {
202
+ try { intoDirectory = (await stat(destination)).isDirectory(); }
203
+ catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") incomplete = true; }
204
+ }
205
+ if (operands.length > 1 && !intoDirectory) incomplete = true;
206
+ for (const source of operands) {
207
+ const from = path(source);
208
+ if (!from) continue;
209
+ if (tool === "mv") targets.push({ path: from, followSymlinks: false });
210
+ targets.push({ path: intoDirectory ? join(destination, basename(from)) : destination, followSymlinks: tool === "cp" });
211
+ }
212
+ } else for (const operand of operands) add(operand, tool === "touch" || tool === "chmod" || tool === "tee");
213
+ }
214
+ return { targets, incomplete };
215
+ }
@@ -0,0 +1,114 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { mkdir, readFile, readdir, rename, rm, rmdir, stat, unlink, utimes, writeFile } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ import { homedir } from "node:os";
5
+
6
+ export const DATA_DIR = join(homedir(), ".pi", "agent", "data", "pi-diff");
7
+
8
+ /**
9
+ * Content-addressed snapshot cache under ~/.pi/agent/data/pi-diff/.
10
+ *
11
+ * Ported from opencode `packages/core/src/snapshot.ts` with the storage base
12
+ * swapped (PLAN.md deviations): upstream keeps git snapshot trees in a data
13
+ * directory; we store raw file blobs keyed by sha256. Patches are persisted
14
+ * self-contained in the session JSONL (see store.ts); this cache only
15
+ * accelerates incremental patch computation (turn old/new sides and the
16
+ * session-cumulative recompute). Losing it never breaks `/diff` — consumers
17
+ * fall back to the persisted per-turn patch texts.
18
+ *
19
+ * Cleanup: 30-day LRU by access time at session start. Note some filesystems
20
+ * are mounted noatime (common on macOS); we fall back to mtime there.
21
+ */
22
+ export class SnapshotStore {
23
+ private readonly root: string;
24
+
25
+ constructor(root = DATA_DIR) {
26
+ this.root = root;
27
+ }
28
+
29
+ static hash(content: Buffer): string {
30
+ return createHash("sha256").update(content).digest("hex");
31
+ }
32
+
33
+ /** Store content; returns its content hash (sha256). Idempotent. */
34
+ async put(content: Buffer): Promise<string> {
35
+ const hash = SnapshotStore.hash(content);
36
+ const file = this.objectPath(hash);
37
+ try {
38
+ await stat(file);
39
+ return hash; // already stored — keep the original (older) timestamps
40
+ } catch {
41
+ // not stored yet
42
+ }
43
+ await mkdir(this.shard(hash), { recursive: true });
44
+ const temporary = `${file}.${randomUUID()}.tmp`;
45
+ try {
46
+ await writeFile(temporary, content);
47
+ await rename(temporary, file);
48
+ } finally {
49
+ await rm(temporary, { force: true }).catch(() => {});
50
+ }
51
+ return hash;
52
+ }
53
+
54
+ /** Fetch content by hash; null when unknown or unreadable. Refreshes atime. */
55
+ async get(hash: string): Promise<Buffer | null> {
56
+ if (!/^[a-f0-9]{64}$/.test(hash)) return null;
57
+ const file = this.objectPath(hash);
58
+ try {
59
+ const content = await readFile(file);
60
+ if (SnapshotStore.hash(content) !== hash) return null;
61
+ // Best-effort atime refresh for the LRU (harmless if it fails).
62
+ await utimes(file, new Date(), new Date()).catch(() => {});
63
+ return content;
64
+ } catch {
65
+ return null;
66
+ }
67
+ }
68
+
69
+ /**
70
+ * Remove objects not accessed for `maxAgeDays` days. Objects are stored in
71
+ * shard dirs (objects/ab/cdef...); empty shards are removed too.
72
+ */
73
+ async cleanup(maxAgeDays = 30): Promise<void> {
74
+ const objectsDir = join(this.root, "objects");
75
+ let shards: string[];
76
+ try {
77
+ shards = await readdir(objectsDir);
78
+ } catch {
79
+ return; // nothing cached yet
80
+ }
81
+ const cutoff = Date.now() - maxAgeDays * 24 * 60 * 60 * 1000;
82
+ for (const shard of shards) {
83
+ const shardDir = join(objectsDir, shard);
84
+ let entries: string[];
85
+ try {
86
+ entries = await readdir(shardDir);
87
+ } catch {
88
+ continue;
89
+ }
90
+ let remaining = 0;
91
+ for (const entry of entries) {
92
+ const file = join(shardDir, entry);
93
+ try {
94
+ const s = await stat(file);
95
+ const lastUse = Math.max(s.atimeMs, s.mtimeMs);
96
+ if (lastUse < cutoff) await unlink(file);
97
+ else remaining++;
98
+ } catch {
99
+ continue;
100
+ }
101
+ }
102
+ // A concurrent capture may have added a fresh object since readdir.
103
+ if (remaining === 0) await rmdir(shardDir).catch(() => {});
104
+ }
105
+ }
106
+
107
+ private objectPath(hash: string): string {
108
+ return join(this.shard(hash), hash.slice(2));
109
+ }
110
+
111
+ private shard(hash: string): string {
112
+ return join(this.root, "objects", hash.slice(0, 2));
113
+ }
114
+ }
package/src/store.ts ADDED
@@ -0,0 +1,95 @@
1
+ import type { SessionEntry } from "@earendil-works/pi-coding-agent";
2
+ import type { FilePatch } from "./diff-engine.ts";
3
+ import type { Language } from "./language.ts";
4
+ import { isAbsolute } from "node:path";
5
+
6
+ export type TrackingIssue = "shell" | "scan" | "capture" | "tools";
7
+
8
+ /** Persisted shape of one turn's diff, stored as custom entry `pi-diff.turn`. */
9
+ export interface TurnDiffEntryData {
10
+ /** 1-based turn number on the current branch. */
11
+ turn: number;
12
+ /** ISO timestamp of turn end. */
13
+ endedAt: string;
14
+ /** Total changed files in this turn. */
15
+ fileCount: number;
16
+ /** Self-contained patches; the TUI renders from these alone. */
17
+ patches: FilePatch[];
18
+ /** Capture root disambiguates relative identities if the session changes cwd. */
19
+ cwd?: string;
20
+ /** Display-only task receipt metadata; absent in older records. */
21
+ summary?: { language: Language; aborted: boolean; issues: TrackingIssue[] };
22
+ }
23
+
24
+ export const CUSTOM_TYPE = "pi-diff.turn" as const;
25
+
26
+ /**
27
+ * Append a turn diff to the session JSONL via pi.appendEntry (custom entry).
28
+ * Entries participate in branching: navigating a branch replays only the
29
+ * entries on that branch, so per-turn and session totals are branch-correct.
30
+ */
31
+ export function appendTurnDiff(
32
+ appendEntry: (customType: string, data?: unknown) => void,
33
+ data: TurnDiffEntryData,
34
+ ): void {
35
+ appendEntry(CUSTOM_TYPE, data);
36
+ }
37
+
38
+ export function isTurnDiffData(value: unknown): value is TurnDiffEntryData {
39
+ if (typeof value !== "object" || value === null) return false;
40
+ const v = value as Record<string, unknown>;
41
+ return (
42
+ typeof v.turn === "number" && Number.isSafeInteger(v.turn) && v.turn > 0 &&
43
+ typeof v.endedAt === "string" && Number.isFinite(Date.parse(v.endedAt)) &&
44
+ typeof v.fileCount === "number" && Number.isSafeInteger(v.fileCount) && v.fileCount >= 0 &&
45
+ Array.isArray(v.patches) &&
46
+ v.fileCount === v.patches.length && v.patches.every(isFilePatch) &&
47
+ (v.cwd === undefined || (typeof v.cwd === "string" && isAbsolute(v.cwd) && !v.cwd.includes("\0"))) &&
48
+ (v.summary === undefined || isSummary(v.summary))
49
+ );
50
+ }
51
+
52
+ function isSummary(value: unknown): boolean {
53
+ if (typeof value !== "object" || value === null) return false;
54
+ const summary = value as Record<string, unknown>;
55
+ return (summary.language === "en" || summary.language === "zh-CN") && typeof summary.aborted === "boolean" &&
56
+ Array.isArray(summary.issues) && summary.issues.every((issue) => ["shell", "scan", "capture", "tools"].includes(issue));
57
+ }
58
+
59
+ function isFilePatch(value: unknown): value is FilePatch {
60
+ if (typeof value !== "object" || value === null) return false;
61
+ const p = value as Record<string, unknown>;
62
+ return typeof p.file === "string" && p.file.length > 0 && !p.file.includes("\0") &&
63
+ typeof p.patch === "string" &&
64
+ (p.status === "added" || p.status === "modified" || p.status === "deleted") &&
65
+ typeof p.additions === "number" && Number.isSafeInteger(p.additions) && p.additions >= 0 &&
66
+ typeof p.deletions === "number" && Number.isSafeInteger(p.deletions) && p.deletions >= 0 &&
67
+ [p.oldHash, p.newHash].every((hash) => hash === undefined || hash === null || (typeof hash === "string" && /^[a-f0-9]{64}$/.test(hash))) &&
68
+ [p.oldMode, p.newMode].every((mode) => mode === undefined || mode === null || mode === "100644" || mode === "100755" || mode === "120000") &&
69
+ [p.binary, p.tooLarge, p.baselineUnknown, p.unavailable, p.cumulativeFallback].every((flag) => flag === undefined || typeof flag === "boolean");
70
+ }
71
+
72
+ /**
73
+ * Rebuild Tracker state from `pi-diff.turn` custom entries on the active
74
+ * branch (session reload / resume / branch switch). Corrupted entries from
75
+ * older versions are skipped instead of crashing.
76
+ */
77
+ export function collectTurnDiffs(entries: readonly SessionEntry[]): TurnDiffEntryData[] {
78
+ const result: TurnDiffEntryData[] = [];
79
+ for (const entry of entries) {
80
+ if (entry.type !== "custom" || entry.customType !== CUSTOM_TYPE) continue;
81
+ if (!isTurnDiffData(entry.data)) continue;
82
+ result.push(entry.data);
83
+ }
84
+ return result;
85
+ }
86
+
87
+ /** Recognize unusable old records without treating them as successful empty turns. */
88
+ export function hasUnavailableTurnDiffs(entries: readonly SessionEntry[]): boolean {
89
+ return entries.some((entry) => {
90
+ if (entry.type !== "custom") return false;
91
+ const type: unknown = entry.customType;
92
+ if (typeof type === "object" && type !== null && "customType" in type && type.customType === CUSTOM_TYPE) return true;
93
+ return type === CUSTOM_TYPE && !isTurnDiffData(entry.data);
94
+ });
95
+ }