@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/src/language.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import { visibleWidth } from "@earendil-works/pi-tui";
2
+
1
3
  export type Language = "en" | "zh-CN";
2
4
  export type LocalizedText = string | ((language: Language) => string);
3
5
 
@@ -5,6 +7,21 @@ export function localize(text: LocalizedText, language: Language): string {
5
7
  return typeof text === "function" ? text(language) : text;
6
8
  }
7
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
+
8
25
  const en = {
9
26
  lastTurn: "Last turn",
10
27
  turn: (turn: number) => `Last turn · Turn ${turn}`,
@@ -13,7 +30,9 @@ const en = {
13
30
  working: "Uncommitted",
14
31
  branch: "All branch changes",
15
32
  files: "Files",
33
+ externalFiles: "External files",
16
34
  fileCount: (count: number) => `${count} ${count === 1 ? "file" : "files"}`,
35
+ moreFiles: (count: number) => `… and ${count} more ${count === 1 ? "file" : "files"}`,
17
36
  switchView: "[Switch view]",
18
37
  showFiles: "[Show files]",
19
38
  dragDivider: "↔ Drag to resize",
@@ -22,6 +41,11 @@ const en = {
22
41
  unified: "Unified view",
23
42
  split: "Split view",
24
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}`,
25
49
  noFileToSwitch: "No file to switch views",
26
50
  tooNarrow: "Diff pane too narrow; widen the terminal for split view",
27
51
  noChanges: "No file changes",
@@ -39,11 +63,31 @@ const en = {
39
63
  unavailableTotal: "No usable history; complete session total unavailable",
40
64
  emptySession: "No cumulative changes in this session",
41
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],
42
78
  loading: "Loading changes…",
43
79
  loadFailed: (error: string) => `Failed to load: ${error}`,
44
80
  requiresTui: "pi-diff requires an interactive TUI",
45
81
  error: (error: string) => `pi-diff: ${error}`,
46
- footer: (fixed: boolean, focus: "tree" | "diff") => `l/L 中文 · [/] Focus: ${focus === "tree" ? "Files" : "Diff"} · Tab/Shift+Tab Scope · ${fixed ? "A/D Unified only" : "v/V Unified/Split"} · ↑↓/Wheel Scroll · j/k ${focus === "tree" ? "Files" : "Scroll"} · Esc/q Close`,
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),
47
91
  };
48
92
 
49
93
  export const messages: Record<Language, typeof en> = {
@@ -56,7 +100,9 @@ export const messages: Record<Language, typeof en> = {
56
100
  working: "未提交",
57
101
  branch: "分支全部改动",
58
102
  files: "文件",
103
+ externalFiles: "项目外文件",
59
104
  fileCount: (count) => `${count} 个文件`,
105
+ moreFiles: (count) => `… 另有 ${count} 个文件`,
60
106
  switchView: "[切换视图]",
61
107
  showFiles: "[展开文件树]",
62
108
  dragDivider: "↔ 拖动调整宽度",
@@ -65,6 +111,10 @@ export const messages: Record<Language, typeof en> = {
65
111
  unified: "合并视图",
66
112
  split: "拆分视图",
67
113
  wrap: "自动换行",
114
+ foldedLines: (count) => `⋯ 已折叠 ${count} 行未修改内容 · 点击展开`,
115
+ expandContext: "[展开全部]",
116
+ foldContext: "[折叠上下文]",
117
+ changeProgress: (current, total) => current === undefined ? `${total} 处改动` : `改动 ${current}/${total}`,
68
118
  noFileToSwitch: "没有可切换的文件",
69
119
  tooNarrow: "右侧宽度不足,请拉宽终端后切换拆分视图",
70
120
  noChanges: "没有文件改动",
@@ -82,10 +132,30 @@ export const messages: Record<Language, typeof en> = {
82
132
  unavailableTotal: "没有可用的历史改动,无法展示完整累计",
83
133
  emptySession: "当前会话没有累计改动",
84
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],
85
147
  loading: "正在加载改动…",
86
148
  loadFailed: (error) => `加载失败:${error}`,
87
149
  requiresTui: "pi-diff 需要在交互式 TUI 中使用",
88
150
  error: (error) => `pi-diff:${error}`,
89
- footer: (fixed, focus) => `l/L English · [/] 焦点:${focus === "tree" ? "文件树" : "内容"} · Tab/Shift+Tab 范围 · ${fixed ? "A/D 仅合并" : "v/V 合并/拆分"} · ↑↓/滚轮 滚动 · j/k ${focus === "tree" ? "文件" : "滚动"} · Esc/q 关闭`,
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),
90
160
  },
91
161
  };
@@ -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
+ }
package/src/store.ts CHANGED
@@ -1,5 +1,9 @@
1
1
  import type { SessionEntry } from "@earendil-works/pi-coding-agent";
2
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";
3
7
 
4
8
  /** Persisted shape of one turn's diff, stored as custom entry `pi-diff.turn`. */
5
9
  export interface TurnDiffEntryData {
@@ -11,6 +15,10 @@ export interface TurnDiffEntryData {
11
15
  fileCount: number;
12
16
  /** Self-contained patches; the TUI renders from these alone. */
13
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[] };
14
22
  }
15
23
 
16
24
  export const CUSTOM_TYPE = "pi-diff.turn" as const;
@@ -27,7 +35,7 @@ export function appendTurnDiff(
27
35
  appendEntry(CUSTOM_TYPE, data);
28
36
  }
29
37
 
30
- function isTurnDiffData(value: unknown): value is TurnDiffEntryData {
38
+ export function isTurnDiffData(value: unknown): value is TurnDiffEntryData {
31
39
  if (typeof value !== "object" || value === null) return false;
32
40
  const v = value as Record<string, unknown>;
33
41
  return (
@@ -35,10 +43,19 @@ function isTurnDiffData(value: unknown): value is TurnDiffEntryData {
35
43
  typeof v.endedAt === "string" && Number.isFinite(Date.parse(v.endedAt)) &&
36
44
  typeof v.fileCount === "number" && Number.isSafeInteger(v.fileCount) && v.fileCount >= 0 &&
37
45
  Array.isArray(v.patches) &&
38
- v.fileCount === v.patches.length && v.patches.every(isFilePatch)
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))
39
49
  );
40
50
  }
41
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
+
42
59
  function isFilePatch(value: unknown): value is FilePatch {
43
60
  if (typeof value !== "object" || value === null) return false;
44
61
  const p = value as Record<string, unknown>;
@@ -48,6 +65,7 @@ function isFilePatch(value: unknown): value is FilePatch {
48
65
  typeof p.additions === "number" && Number.isSafeInteger(p.additions) && p.additions >= 0 &&
49
66
  typeof p.deletions === "number" && Number.isSafeInteger(p.deletions) && p.deletions >= 0 &&
50
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") &&
51
69
  [p.binary, p.tooLarge, p.baselineUnknown, p.unavailable, p.cumulativeFallback].every((flag) => flag === undefined || typeof flag === "boolean");
52
70
  }
53
71