@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 CHANGED
@@ -7,13 +7,15 @@ Review per-turn, session-wide, and Git changes in a fullscreen TUI inside [pi](h
7
7
  ## Features
8
8
 
9
9
  - **Review at different scopes:** inspect the latest task, session total, or Git changes, with file counts and added/removed line totals.
10
+ - **See what each task changed:** the task summary shows changed files and line counts. Use `/diff last` to inspect the latest task directly.
11
+ - **Find the next edit:** jump between changes with `n` / `p`, expand folded context as needed, and switch files without losing your place in the current scope.
10
12
  - **Keep your history:** recorded task diffs remain available after reloading pi, resuming a session, or switching session branches.
11
13
  - **Use either language:** switch between English and Simplified Chinese with `l` / `L`; your choice is remembered.
12
14
  - **Review safely:** viewing diffs does not stage, commit, or revert files. Task and session views also work outside Git repositories.
13
15
 
14
16
  ### Unified and split views
15
17
 
16
- Read changes in one column or compare old and new content side by side. Press `v` / `V` or click the view toggle to switch. Long lines wrap automatically, and colors follow your pi theme. Added/deleted files and narrow windows use unified view.
18
+ Read changes in one column or compare old and new content side by side. Press `v` / `V` or click the view toggle to switch. Supported code files use pi's syntax highlighting, focused in-place edits show word-level emphasis, long lines wrap automatically, and colors follow your pi theme. Added/deleted files and narrow windows use unified view.
17
19
 
18
20
  <table>
19
21
  <tr>
@@ -40,6 +42,12 @@ Click either image to view it at full size.
40
42
  </tr>
41
43
  </table>
42
44
 
45
+ ### Task change summary
46
+
47
+ On Pi hosts with entry rendering, a summary appears when the task ends, including interrupted tasks and tasks with no recorded changes. The card shows up to 12 files and a count of any remaining files. Use `/diff last` to see the full list and inspect each diff.
48
+
49
+ <a href="https://github.com/lyrumu/pi-diff/blob/main/docs/images/task-summary.png"><img src="https://raw.githubusercontent.com/lyrumu/pi-diff/main/docs/images/task-summary.png" width="720" alt="Task change summary showing five changed files, line counts, and the /diff last command. File names are obscured."></a>
50
+
43
51
  ### Inspired by opencode
44
52
 
45
53
  Inspired by [opencode](https://github.com/anomalyco/opencode), pi-diff brings its terminal diff review experience into pi through `/diff`.
@@ -92,7 +100,7 @@ Git scopes also include untracked files. Outside a Git repository, only the firs
92
100
 
93
101
  ### Keyboard and mouse
94
102
 
95
- <a href="https://github.com/lyrumu/pi-diff/blob/main/docs/images/keyboard-shortcuts.en.png"><img src="https://raw.githubusercontent.com/lyrumu/pi-diff/main/docs/images/keyboard-shortcuts.en.png" width="100%" alt="English shortcut bar: l/L language, brackets for focus, Tab/Shift+Tab scope, v/V view, arrows or wheel and j/k for scrolling, Esc/q to close"></a>
103
+ <a href="https://github.com/lyrumu/pi-diff/blob/main/docs/images/keyboard-shortcuts.en.png"><img src="https://raw.githubusercontent.com/lyrumu/pi-diff/main/docs/images/keyboard-shortcuts.en.png" width="100%" alt="English shortcut bar: l/L language, brackets for focus, n/p changes, Tab scope, v/V layout, j/k scroll or files, Esc/q to close"></a>
96
104
 
97
105
  The shortcut bar follows the current focus: `j` / `k` select files when the tree is focused and scroll when the diff is focused.
98
106
 
@@ -104,17 +112,26 @@ The shortcut bar follows the current focus: `j` / `k` select files when the tree
104
112
  | Resize / hide the file tree | Drag the divider; drag to the left edge to hide; double-click to reset the width |
105
113
  | Show the hidden file tree | `[` or click `[Show files]` at the top |
106
114
  | Scroll the diff | Mouse wheel, `↑↓`, `j` / `k`, `PageUp` / `PageDown`; `Home` / `End` jump to the start / end |
115
+ | Jump to the next / previous change in this file | `n` / `p` while the diff is focused |
116
+ | Expand / fold unchanged context in this file | Click a folded block to expand it, or click `[Expand all]` / `[Fold context]` in the file bar |
107
117
  | Switch unified / split view | `v` / `V`, or click the view toggle at the top |
108
118
  | Switch English / Simplified Chinese | `l` / `L` |
109
119
  | Close | `Esc` / `q` |
110
120
 
111
121
  In narrow windows, `[` / `]` switch between the file tree and diff pages.
112
122
 
123
+ The viewer folds runs of more than 12 unchanged lines by default, keeping three context lines next to each change. Click any folded row to expand that section, or click `[Expand all]` / `[Fold context]` in the file bar to toggle all folded sections in the current file. The file bar shows change and scroll progress when applicable. Wider views also show a scrollbar. Switching between files within the same scope remembers each file's scroll position and expanded context.
124
+
113
125
  ## Data and limitations
114
126
 
115
- - Task and session history only covers changes recorded after enabling the extension, within the project directory. Git scopes can show existing changes.
116
- - Outside Git repositories, shell changes may show `Previous contents unknown`. If a complete session total cannot be restored, the viewer says so.
117
- - Binary files and diffs exceeding 10 MB show a notice instead of their contents.
127
+ - Task cards use persisted diffs, stay out of model context, and share the viewer's language preference. Hosts without an entry renderer retain the viewer and show an upgrade notice.
128
+ - Task and session history covers changes recorded after enabling the extension. Explicit `edit`/`write` targets and identified literal shell file targets can be outside the workspace; external paths remain absolute and appear under **External files**. Git scopes remain repository-local.
129
+ - Task history includes only explicit Pi write targets: edit/write and identified shell redirections, copies/moves/removals, touch/chmod/tee, simple `sed -i` and `ln` forms. Capture occurs immediately before the first write and is frozen at tool completion; verified net-zero changes disappear. Reads alone never count as writes.
130
+ - Task capture no longer scans the workspace or attributes unrelated filesystem changes to Pi. Concurrent Codex/editor changes to other files stay outside task and session scopes. This works without Git and for explicit external paths; the three Git scopes still describe repository-wide state.
131
+ - Shell code is never evaluated to infer paths. Scripts, custom tools and recursive directory operations with unidentified targets are not automatically included. Relative targets are skipped when a directory change such as `popd` leaves the working directory uncertain. Detected interference between Pi writes prevents a precise merged patch. Broken content continuity between tasks falls back to the latest own turn in session totals. Concurrent writes to the same target during a single tool execution cannot be reliably separated.
132
+ - Cards omit generic tracking paragraphs and use `?` / `—` for unavailable results; details remain in the viewer. Previously persisted history is not rewritten.
133
+ - Binary files and diffs exceeding 10 MB show a notice instead of their contents. Task capture checks both file versions for non-UTF-8 bytes. Git scopes check the bytes emitted in the patch, including its configured context. Images have no visual preview. SVG files show source changes.
134
+ - Symlink targets and executable-bit changes are tracked; file mode changes appear in the diff.
118
135
 
119
136
  ## License
120
137
 
package/README.zh-CN.md CHANGED
@@ -7,13 +7,15 @@
7
7
  ## 功能特性
8
8
 
9
9
  - **按需查看改动**:查看最近一次任务、整个会话或 Git 改动,同时了解文件数和增删行数。
10
+ - **任务结束就能看到变更**:摘要卡片列出改动文件和增删行数。输入 `/diff last` 直接打开最近一次任务的差异。
11
+ - **快速定位改动**:用 `n`/`p` 跳转,按需展开折叠的上下文。在同一范围内切换文件时会记住阅读位置。
10
12
  - **随时接着看**:已记录的任务改动随会话保存,重载 pi、恢复会话或切换会话分支后仍可查看。
11
13
  - **中英双语**:按 `l`/`L` 切换英语与简体中文,记住你的语言选择。
12
14
  - **只读审阅**:查看差异不会暂存、提交或回退文件;没有 Git 仓库也能看任务与会话改动。
13
15
 
14
16
  ### 合并与拆分视图
15
17
 
16
- 在同一列中阅读改动,或左右对照修改前后的内容。按 `v`/`V` 或点击顶部按钮切换。长行自动换行,配色跟随 pi 主题;新增/删除文件和较窄的窗口使用合并视图。
18
+ 在同一列中阅读改动,或左右对照修改前后的内容。按 `v`/`V` 或点击顶部按钮切换。常见源码文件自动使用 pi 语法高亮,局部修改支持行内词级强调;长行自动换行,配色跟随 pi 主题;新增/删除文件和较窄的窗口使用合并视图。
17
19
 
18
20
  <table>
19
21
  <tr>
@@ -40,6 +42,12 @@
40
42
  </tr>
41
43
  </table>
42
44
 
45
+ ### 任务变更摘要
46
+
47
+ 支持记录渲染的 Pi 宿主会在任务结束后显示摘要卡片,包含中止和没有记录到改动的任务。卡片最多列出 12 个文件,超出时显示剩余数量。用 `/diff last` 查看完整文件列表和各文件的差异。
48
+
49
+ <a href="https://github.com/lyrumu/pi-diff/blob/main/docs/images/task-summary.png"><img src="https://raw.githubusercontent.com/lyrumu/pi-diff/main/docs/images/task-summary.png" width="720" alt="任务变更摘要:五个改动文件、增删行数和 /diff last 命令,文件名已打码。"></a>
50
+
43
51
  ### 灵感来自 opencode
44
52
 
45
53
  参照 [opencode](https://github.com/anomalyco/opencode) 的终端差异审阅体验,通过 `/diff` 在 pi 中直接查看改动。
@@ -92,7 +100,7 @@ Git 范围也包含未跟踪文件;没有 Git 仓库时只显示前两项。
92
100
 
93
101
  ### 快捷键与鼠标
94
102
 
95
- <a href="https://github.com/lyrumu/pi-diff/blob/main/docs/images/keyboard-shortcuts.zh-CN.png"><img src="https://raw.githubusercontent.com/lyrumu/pi-diff/main/docs/images/keyboard-shortcuts.zh-CN.png" width="100%" alt="中文快捷键栏:l/L 切换语言,方括号切换焦点,Tab/Shift+Tab 切换范围,v/V 切换视图,方向键或滚轮及 j/k 滚动,Esc/q 关闭"></a>
103
+ <a href="https://github.com/lyrumu/pi-diff/blob/main/docs/images/keyboard-shortcuts.zh-CN.png"><img src="https://raw.githubusercontent.com/lyrumu/pi-diff/main/docs/images/keyboard-shortcuts.zh-CN.png" width="100%" alt="中文快捷键栏:l/L 切换语言,方括号切换焦点,n/p 跳转改动,Tab 切换范围,v/V 切换布局,j/k 滚动或切文件,Esc/q 关闭"></a>
96
104
 
97
105
  底部快捷键提示随焦点变化:文件树聚焦时,`j`/`k` 选择文件;内容区聚焦时,`j`/`k` 滚动内容。
98
106
 
@@ -104,17 +112,26 @@ Git 范围也包含未跟踪文件;没有 Git 仓库时只显示前两项。
104
112
  | 调整/收起文件树 | 拖动分隔线;拖到最左边缘收起,双击恢复默认宽度 |
105
113
  | 展开已收起的文件树 | `[` 或点击顶部 `[展开文件树]` |
106
114
  | 滚动内容 | 滚轮、`↑↓`、`j`/`k`、`PageUp`/`PageDown`;`Home`/`End` 到首尾 |
115
+ | 跳到同一文件的下一处/上一处改动 | 内容区聚焦时按 `n`/`p` |
116
+ | 展开/折叠同一文件的未修改上下文 | 点击单条折叠提示展开该块,或点击文件信息栏的 `[展开全部]`/`[折叠上下文]` |
107
117
  | 切换合并/拆分视图 | `v`/`V`,或点击顶部“切换视图” |
108
118
  | 切换英语/简体中文 | `l`/`L` |
109
119
  | 退出 | `Esc`/`q` |
110
120
 
111
121
  窗口较窄时,用 `[`/`]` 在文件树和内容页之间切换。
112
122
 
123
+ 查看器默认折叠连续超过 12 行的未修改内容,在改动旁保留 3 行上下文。点击任意折叠提示条可单独展开该块,点击文件信息栏的 `[展开全部]`/`[折叠上下文]` 可切换当前文件的全部折叠块。文件信息栏按需显示改动和滚动进度,宽屏下还会显示滚动条。在同一范围内切换文件再切回时,会记住各文件的滚动位置与展开状态。
124
+
113
125
  ## 数据与限制
114
126
 
115
- - 任务和会话历史仅包含扩展启用后记录的项目目录内改动;Git 范围可以查看已有改动。
116
- - 没有 Git 时,shell 改动可能提示“修改前内容未知”;无法完整恢复会话累计时,界面会明确提示。
117
- - 二进制文件和超过 10 MB 的差异仅显示提示,不展示内容。
127
+ - 任务卡片复用已保存的差异,不进入模型上下文,沿用查看器的语言偏好。缺少记录渲染接口的宿主仍可使用查看器,并会显示升级提示。
128
+ - 任务和会话历史包含扩展启用后的记录。`edit`/`write` 明确目标及可识别的 shell 字面量文件目标支持项目外路径;外部文件使用绝对路径并归入“项目外文件”。Git 范围仍限制在当前仓库。
129
+ - 只记录 Pi 明确写入目标:edit/write 以及可识别的 shell 重定向、复制/移动/删除、touch/chmod/tee、简单 `sed -i` 与 `ln`。首次写入前捕获旧侧,在工具返回时冻结新侧;已确认恢复原样的变更会被排除。单纯读取不计为改动。
130
+ - 不再扫描整个工作目录并将期间变化归入任务;同时运行 Codex 或其他程序修改的非目标文件不会进入本轮与累计。无需 Git,明确目标也支持项目外路径;Git 三个范围依然展示仓库整体状态。
131
+ - 不执行 shell 代码来解析参数。无法识别目标的脚本、自定义工具和目录递归写入不自动收录。`popd` 等操作使工作目录无法确定时,跳过受影响的相对目标。两次 Pi 写入之间出现同文件干扰时不合成精确差异。任务间内容链中断时,会话累计退回最近自身一轮。若其他进程在同一次工具执行期间同时写入同一目标,无法可靠隔离写入来源。
132
+ - 卡片不显示通用追踪说明;无法确认的文件用 `?` 和 `—` 标记,原因在差异详情中展示。历史已经保存的记录不自动改写。
133
+ - 二进制文件和超过 10 MB 的差异仅显示提示。本轮追踪检查文件的前后版本是否含非 UTF-8 字节。Git 范围检查实际输出的补丁及其上下文。图片不提供可视预览,SVG 展示源码改动。
134
+ - 追踪符号链接目标与可执行位变化;文件模式变化在 diff 中显示。
118
135
 
119
136
  ## 许可
120
137
 
package/index.ts CHANGED
@@ -7,10 +7,12 @@ import { cycleScope, type DiffScope } from "./src/tui/scopes.ts";
7
7
  import { DiffScreen, FULLSCREEN_OPTIONS } from "./src/tui/diff-screen.ts";
8
8
  import { loadViewPreference, saveViewPreference, VIEW_PREFERENCE_PATH, loadLanguagePreference, saveLanguagePreference, LANGUAGE_PREFERENCE_PATH } from "./src/preferences.ts";
9
9
  import { messages, type Language, type LocalizedText } from "./src/language.ts";
10
- import { hasUnavailableTurnDiffs } from "./src/store.ts";
10
+ import { CUSTOM_TYPE, hasUnavailableTurnDiffs } from "./src/store.ts";
11
+ import { taskSummary } from "./src/tui/task-summary.ts";
11
12
 
12
13
  const SHELL_TOOLS = new Set(["bash", "powershell"]);
13
14
  const FILE_TOOLS = new Set(["edit", "write"]);
15
+ const READ_TOOLS = new Set(["read", "grep", "find", "ls"]);
14
16
 
15
17
  /**
16
18
  * pi-diff — `/diff` command.
@@ -28,54 +30,70 @@ const FILE_TOOLS = new Set(["edit", "write"]);
28
30
  */
29
31
  export default function (pi: ExtensionAPI) {
30
32
  const tracker = new Tracker(pi);
33
+ let summaryLanguage: Language = "en";
34
+ const summarySupported = typeof pi.registerEntryRenderer === "function";
35
+ if (summarySupported) pi.registerEntryRenderer(CUSTOM_TYPE, (entry, _options, theme) => taskSummary(entry.data, theme, summaryLanguage));
31
36
 
32
37
  pi.on("session_start", async (_event, ctx) => {
33
38
  // Rebuild in-memory turn-diff state from persisted custom entries on the
34
39
  // active branch (session reload / resume / branch switch), then purge
35
40
  // stale snapshot caches (30-day LRU, see AGENTS.md).
36
41
  tracker.restoreFromSession(ctx.sessionManager);
42
+ summaryLanguage = await loadLanguagePreference(LANGUAGE_PREFERENCE_PATH);
43
+ if (!summarySupported && ctx.hasUI) ctx.ui.notify(messages[summaryLanguage].summaryRequiresUpgrade, "warning");
37
44
  await tracker.cleanupCaches();
38
45
  });
39
46
 
40
- pi.on("session_tree", (_event, ctx) => {
47
+ pi.on("session_tree", async (_event, ctx) => {
48
+ await tracker.dispose();
41
49
  tracker.restoreFromSession(ctx.sessionManager);
42
50
  });
43
51
 
44
- pi.on("before_agent_start", async () => {
45
- // Turn start: bump the turn counter and take the workspace baseline.
46
- await tracker.onTurnStart();
52
+ pi.on("session_shutdown", async () => { await tracker.dispose(); });
53
+
54
+ pi.on("before_agent_start", async (_event, ctx) => {
55
+ // Task start: establish the capture root without attributing workspace churn.
56
+ await tracker.onTurnStart(ctx.cwd);
47
57
  });
48
58
 
49
- pi.on("tool_call", async (event) => {
59
+ pi.on("tool_call", async (event, ctx) => {
50
60
  const e = event as ToolCallEvent;
51
61
  if (SHELL_TOOLS.has(e.toolName)) {
52
- // Shell boundary (before): record the workspace marker.
53
- await tracker.onBashStart(e.toolCallId);
54
- } else if (FILE_TOOLS.has(e.toolName)) {
55
- // edit/write (before execution, so disk still holds the old side):
56
- // register the target file through the single entry point.
62
+ // Capture only identifiable write targets before the shell executes.
63
+ const command = (e.input as { command?: string }).command;
64
+ await tracker.onBashStart(e.toolCallId, typeof command === "string" ? command : undefined, ctx.cwd, e.toolName);
65
+ } else if (FILE_TOOLS.has(e.toolName) || e.toolName === "read") {
66
+ // Capture explicit writes before execution. Reads do not establish ownership.
57
67
  const path = (e.input as { path?: string }).path;
58
- if (typeof path === "string") await tracker.recordFileChange(path, { fromToolEvent: true });
68
+ if (typeof path === "string") await tracker.recordFileChange(path, { fromToolEvent: true, followSymlinks: true, cwd: ctx.cwd, toolPath: true, observeOnly: e.toolName === "read", toolCallId: e.toolCallId });
69
+ } else if (!READ_TOOLS.has(e.toolName) && e.toolName !== "codemode" && !pi.getAllTools?.().find((tool) => tool.name === e.toolName)?.annotations?.readOnlyHint) {
70
+ // Native codemode's child calls emit the same tool_call/tool_result events.
71
+ tracker.noteUntrackedTool();
59
72
  }
60
73
  });
61
74
 
62
75
  pi.on("tool_result", async (event) => {
63
76
  const e = event as { toolName: string; toolCallId: string };
64
77
  if (SHELL_TOOLS.has(e.toolName)) {
65
- // Shell boundary (after): scan for files the command changed.
78
+ // Freeze explicit target contents at the execution boundary.
66
79
  await tracker.onBashEnd(e.toolCallId);
67
- }
80
+ } else if (FILE_TOOLS.has(e.toolName)) await tracker.onToolEnd(e.toolCallId);
68
81
  });
69
82
 
70
- pi.on("agent_settled", async () => {
83
+ pi.on("agent_settled", async (event, ctx) => {
71
84
  // End of the user-prompt run: compute patches for every registered file
72
85
  // and persist them as a self-contained `pi-diff.turn` custom entry.
73
- await tracker.finalizeTurn();
86
+ try {
87
+ summaryLanguage = await loadLanguagePreference(LANGUAGE_PREFERENCE_PATH);
88
+ await tracker.finalizeTurn({ language: summaryLanguage, aborted: event.aborted === true });
89
+ } catch (error) {
90
+ ctx.ui.notify(messages[summaryLanguage].error(error instanceof Error ? error.message : String(error)), "error");
91
+ }
74
92
  });
75
93
 
76
94
  pi.registerCommand("diff", {
77
95
  description: "Review per-turn, session-wide and Git changes",
78
- handler: async (_args, ctx) => {
96
+ handler: async (args, ctx) => {
79
97
  const initialLanguage = await loadLanguagePreference(LANGUAGE_PREFERENCE_PATH);
80
98
  let language = initialLanguage;
81
99
  if (ctx.mode !== "tui" || !ctx.hasUI) {
@@ -89,7 +107,7 @@ export default function (pi: ExtensionAPI) {
89
107
  const turns = tracker.turns();
90
108
  const gitAvailable = await Git.isAvailable(ctx.cwd);
91
109
  const unavailableHistory = hasUnavailableTurnDiffs(ctx.sessionManager.getBranch());
92
- let scope: DiffScope = gitAvailable ? { kind: "git", mode: "unstaged" } : { kind: "turn", turn: turns.at(-1)?.turn };
110
+ let scope: DiffScope = gitAvailable && args.trim() !== "last" ? { kind: "git", mode: "unstaged" } : { kind: "turn", turn: turns.at(-1)?.turn };
93
111
  const initialView = await loadViewPreference(VIEW_PREFERENCE_PATH);
94
112
  let view = initialView;
95
113
  let request = 0;
@@ -105,10 +123,13 @@ export default function (pi: ExtensionAPI) {
105
123
  files = turns.find((turn) => turn.turn === turnNumber)?.patches ?? [];
106
124
  emptyMessage = (language) => messages[language][turnNumber === undefined ? (unavailableHistory ? "noHistory" : "noTurns") : "emptyTurn"];
107
125
  } else if (source.kind === "session") {
108
- files = await tracker.sessionPatches();
126
+ files = await tracker.sessionPatches(ctx.cwd);
109
127
  emptyMessage = (language) => messages[language][unavailableHistory ? "unavailableTotal" : "emptySession"];
110
128
  } else files = await Git.diff(ctx.cwd, source.mode);
111
- return { title: scopeTitle(source), files, emptyMessage, notice: source.kind !== "git" && unavailableHistory ? (language: Language) => messages[language].incompleteHistory : undefined };
129
+ const issues = source.kind === "git" ? [] : [...new Set((source.kind === "turn" ? turns.filter((turn) => turn.turn === source.turn) : turns).flatMap((turn) => turn.summary?.issues ?? []))];
130
+ const notice: LocalizedText | undefined = source.kind !== "git" && (unavailableHistory || issues.length)
131
+ ? (language) => [unavailableHistory ? messages[language].incompleteHistory : "", ...issues.map((issue) => messages[language].trackingIssue(issue))].filter(Boolean).join(" · ") : undefined;
132
+ return { title: scopeTitle(source), files, emptyMessage, notice };
112
133
  };
113
134
  const initial = await loadScope(scope);
114
135
  try {
@@ -140,6 +161,7 @@ export default function (pi: ExtensionAPI) {
140
161
  } finally {
141
162
  closed = true;
142
163
  request++;
164
+ summaryLanguage = language;
143
165
  await Promise.all([
144
166
  view && view !== initialView ? saveViewPreference(VIEW_PREFERENCE_PATH, view) : undefined,
145
167
  language !== initialLanguage ? saveLanguagePreference(LANGUAGE_PREFERENCE_PATH, language) : undefined,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lyrumu/pi-diff",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "pi extension: /diff — view per-turn, per-session and git changes in a fullscreen TUI",
5
5
  "type": "module",
6
6
  "main": "index.ts",
@@ -14,20 +14,33 @@
14
14
  "bugs": {
15
15
  "url": "https://github.com/lyrumu/pi-diff/issues"
16
16
  },
17
- "keywords": ["pi-package", "pi-extension", "diff"],
17
+ "keywords": [
18
+ "pi-package",
19
+ "pi-extension",
20
+ "diff"
21
+ ],
18
22
  "engines": {
19
23
  "node": ">=22.19.0"
20
24
  },
21
- "files": ["index.ts", "src/", "README.zh-CN.md", "LICENSE", "NOTICE.md", "THIRD_PARTY_LICENSES.md"],
25
+ "files": [
26
+ "index.ts",
27
+ "src/",
28
+ "README.zh-CN.md",
29
+ "LICENSE",
30
+ "NOTICE.md",
31
+ "THIRD_PARTY_LICENSES.md"
32
+ ],
22
33
  "publishConfig": {
23
34
  "access": "public"
24
35
  },
25
36
  "pi": {
26
- "extensions": ["./index.ts"]
37
+ "extensions": [
38
+ "./index.ts"
39
+ ]
27
40
  },
28
41
  "scripts": {
29
42
  "typecheck": "tsc --noEmit",
30
- "test": "node tests/selftest.ts && node tests/git-selftest.ts && node tests/tui-selftest.ts && node tests/extension-selftest.ts && node tests/reliability-selftest.ts",
43
+ "test": "node tests/selftest.ts && node tests/git-selftest.ts && node tests/tui-selftest.ts && node tests/extension-selftest.ts && node tests/reliability-selftest.ts && node tests/task-summary-selftest.ts",
31
44
  "sync:opencode": "bash scripts/sync-opencode.sh"
32
45
  },
33
46
  "dependencies": {
@@ -38,8 +51,8 @@
38
51
  "@earendil-works/pi-tui": "*"
39
52
  },
40
53
  "devDependencies": {
41
- "@earendil-works/pi-coding-agent": "1.2.0",
42
- "@earendil-works/pi-tui": "1.2.0",
54
+ "@earendil-works/pi-coding-agent": ">=1.2.0",
55
+ "@earendil-works/pi-tui": ">=1.2.0",
43
56
  "@types/diff": "^8.0.0",
44
57
  "@types/node": "^22.0.0",
45
58
  "typescript": "^5.7.0"
@@ -1,3 +1,4 @@
1
+ import { isUtf8 } from "node:buffer";
1
2
  import { formatPatch, structuredPatch } from "diff";
2
3
 
3
4
  /**
@@ -128,6 +129,7 @@ export const chunksByFile = (patch: Patch, fallback: (index: number) => string |
128
129
 
129
130
  /** Status of a changed file, mirroring opencode `FileStatus["status"]`. */
130
131
  export type FileStatus = "added" | "modified" | "deleted";
132
+ export type FileMode = "100644" | "100755" | "120000";
131
133
 
132
134
  /**
133
135
  * A single changed-file patch for one scope (turn / session / git). The
@@ -135,7 +137,7 @@ export type FileStatus = "added" | "modified" | "deleted";
135
137
  * content-addressed cache hints for the session-cumulative recompute.
136
138
  */
137
139
  export interface FilePatch {
138
- /** Project-relative posix path. */
140
+ /** Workspace-relative posix path, or an absolute path for external files. */
139
141
  file: string;
140
142
  status: FileStatus;
141
143
  /** Unified diff text; empty for binary / capped files. */
@@ -156,11 +158,14 @@ export interface FilePatch {
156
158
  oldHash?: string | null;
157
159
  /** sha256 of new-side bytes; null = file does not exist on the new side. */
158
160
  newHash?: string | null;
161
+ /** Git file modes; null = absent side, undefined = unknown/legacy record. */
162
+ oldMode?: FileMode | null;
163
+ newMode?: FileMode | null;
159
164
  }
160
165
 
161
- /** Detect binary content the way git does: a NUL byte anywhere in the buffer. */
166
+ /** Avoid lossy UTF-8 decoding as well as NUL-containing binary content. */
162
167
  export function isBinary(content: Buffer): boolean {
163
- return content.includes(0);
168
+ return content.includes(0) || !isUtf8(content);
164
169
  }
165
170
 
166
171
  /**
@@ -172,7 +177,7 @@ export function makeFilePatch(
172
177
  file: string,
173
178
  oldContent: Buffer | null,
174
179
  newContent: Buffer | null,
175
- opts: { oldHash?: string | null; newHash?: string | null; baselineUnknown?: boolean } = {},
180
+ opts: { oldHash?: string | null; newHash?: string | null; baselineUnknown?: boolean; oldMode?: FileMode | null; newMode?: FileMode | null } = {},
176
181
  ): FilePatch {
177
182
  const status: FileStatus =
178
183
  oldContent === null ? "added" : newContent === null ? "deleted" : "modified";
@@ -186,6 +191,8 @@ export function makeFilePatch(
186
191
  newHash: opts.newHash ?? null,
187
192
  };
188
193
  if (opts.baselineUnknown) base.baselineUnknown = true;
194
+ if (opts.oldMode !== undefined) base.oldMode = opts.oldMode;
195
+ if (opts.newMode !== undefined) base.newMode = opts.newMode;
189
196
 
190
197
  const binary = (oldContent !== null && isBinary(oldContent)) || (newContent !== null && isBinary(newContent));
191
198
  if (binary) {
package/src/git.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { isUtf8 } from "node:buffer";
1
2
  import { execFile, spawn } from "node:child_process";
2
3
  import { promisify } from "node:util";
3
4
  import {
@@ -6,6 +7,7 @@ import {
6
7
  MAX_PATCH_BYTES,
7
8
  MAX_TOTAL_PATCH_BYTES,
8
9
  type FilePatch,
10
+ type FileMode,
9
11
  type FileStatus,
10
12
  type Patch,
11
13
  } from "./diff-engine.ts";
@@ -49,7 +51,7 @@ interface Stat {
49
51
 
50
52
  /** Drain capped output without retaining more than the byte budget. */
51
53
  function run(cwd: string, args: readonly string[], maxOutputBytes = 64 * 1024 * 1024) {
52
- return new Promise<{ text: string; truncated: boolean; exitCode: number }>((resolve) => {
54
+ return new Promise<{ text: string; truncated: boolean; invalidUtf8: boolean; exitCode: number }>((resolve) => {
53
55
  const child = spawn("git", [...BASE_ARGS, ...args], { cwd, stdio: ["ignore", "pipe", "pipe"] });
54
56
  const chunks: Buffer[] = [];
55
57
  let size = 0;
@@ -64,8 +66,14 @@ function run(cwd: string, args: readonly string[], maxOutputBytes = 64 * 1024 *
64
66
  }
65
67
  });
66
68
  child.stderr.resume();
67
- child.on("error", () => resolve({ text: "", truncated: false, exitCode: 1 }));
68
- child.on("close", (code) => resolve({ text: Buffer.concat(chunks).toString("utf8"), truncated, exitCode: code ?? 1 }));
69
+ child.on("error", () => resolve({ text: "", truncated: false, invalidUtf8: false, exitCode: 1 }));
70
+ child.on("close", (code) => {
71
+ const output = Buffer.concat(chunks);
72
+ // The trailing partial patch may end in the middle of a valid UTF-8 character.
73
+ const complete = truncated && args.includes("--patch")
74
+ ? output.subarray(0, Math.max(0, output.lastIndexOf("\ndiff --git "))) : output;
75
+ resolve({ text: output.toString("utf8"), truncated, invalidUtf8: !isUtf8(complete), exitCode: code ?? 1 });
76
+ });
69
77
  });
70
78
  }
71
79
 
@@ -130,7 +138,7 @@ async function mergeBase(cwd: string, base: string) {
130
138
  return result.exitCode === 0 ? result.text.trim() || undefined : undefined;
131
139
  }
132
140
 
133
- async function nativePatch(root: string, ref: string | undefined, item: Item, context: number, target?: "HEAD"): Promise<Patch> {
141
+ async function nativePatch(root: string, ref: string | undefined, item: Item, context: number, target?: "HEAD"): Promise<Patch & { binary: boolean }> {
134
142
  const result = await run(root, [
135
143
  "--literal-pathspecs", "diff",
136
144
  ...(item.code === "??" || ref === undefined ? ["--no-index"] : []),
@@ -141,7 +149,11 @@ async function nativePatch(root: string, ref: string | undefined, item: Item, co
141
149
  if (result.exitCode !== 0 && !(result.exitCode === 1 && (item.code === "??" || ref === undefined))) {
142
150
  throw new Error(`Unable to read Git patch for ${item.file}`);
143
151
  }
144
- return { text: result.truncated ? "" : result.text, truncated: result.truncated };
152
+ const binary = !result.truncated && result.invalidUtf8;
153
+ const text = result.truncated ? "" : binary
154
+ ? (result.text.match(/^(?:old mode|new mode|new file mode|deleted file mode) (?:100644|100755|120000)$/gm) ?? []).join("\n")
155
+ : result.text;
156
+ return { text, truncated: result.truncated, binary };
145
157
  }
146
158
 
147
159
  async function statUntracked(root: string, file: string): Promise<Stat | undefined> {
@@ -155,7 +167,7 @@ async function files(
155
167
  ref: string | undefined,
156
168
  list: Item[],
157
169
  stats: Map<string, Stat>,
158
- batch: { patches: Map<string, string>; capped: boolean },
170
+ batch: { patches: Map<string, string>; capped: boolean; retry?: ReadonlySet<string> },
159
171
  context: number,
160
172
  target?: "HEAD",
161
173
  ): Promise<FilePatch[]> {
@@ -166,13 +178,15 @@ async function files(
166
178
  const stat = stats.get(item.file) ?? (!target && item.status === "added" ? await statUntracked(root, item.file) : undefined);
167
179
  let patch = emptyPatch(item.file);
168
180
  let tooLarge = capped;
181
+ let binary = stat?.binary ?? false;
169
182
  if (!capped) {
170
183
  const batched = batch.patches.get(item.file);
171
184
  if (batched !== undefined) patch = batched;
172
- else if (item.code !== "??" && batch.capped) tooLarge = true;
185
+ else if (item.code !== "??" && batch.capped && !batch.retry?.has(item.file)) tooLarge = true;
173
186
  else {
174
187
  const result = await nativePatch(root, ref, item, context, target);
175
188
  tooLarge = result.truncated;
189
+ binary ||= result.binary;
176
190
  if (!result.truncated && result.text) patch = result.text;
177
191
  }
178
192
  if (Buffer.byteLength(patch) > MAX_PATCH_BYTES) tooLarge = true;
@@ -187,15 +201,23 @@ async function files(
187
201
  capped = total >= MAX_TOTAL_PATCH_BYTES;
188
202
  }
189
203
  }
190
- const binary = stat?.binary || /^Binary files .+ differ$/m.test(patch);
204
+ binary ||= /^Binary files .+ differ$/m.test(patch);
205
+ const modes: Pick<FilePatch, "oldMode" | "newMode"> = {};
206
+ for (const [, header, mode] of patch.matchAll(/^(old mode|new mode|new file mode|deleted file mode) (100644|100755|120000)$/gm)) {
207
+ if (header === "old mode" || header === "deleted file mode") modes.oldMode = mode as FileMode;
208
+ if (header === "new mode" || header === "new file mode") modes.newMode = mode as FileMode;
209
+ if (header === "new file mode") modes.oldMode ??= null;
210
+ if (header === "deleted file mode") modes.newMode ??= null;
211
+ }
191
212
  next.push({
192
213
  file: item.file,
193
214
  status: item.status,
194
215
  patch: binary ? "" : patch,
195
- additions: stat?.additions ?? 0,
196
- deletions: stat?.deletions ?? 0,
216
+ additions: binary ? 0 : stat?.additions ?? 0,
217
+ deletions: binary ? 0 : stat?.deletions ?? 0,
197
218
  ...(binary ? { binary: true } : {}),
198
219
  ...(tooLarge ? { tooLarge: true } : {}),
220
+ ...modes,
199
221
  });
200
222
  }
201
223
  return next;
@@ -246,14 +268,25 @@ export const Git = {
246
268
  const file = tokens[idx + 1];
247
269
  return idx % 2 === 0 && file ? [{ file, code, status: kind(code) }] : [];
248
270
  });
249
- const result = list.length === 0 ? { text: "", truncated: false, exitCode: 0 }
271
+ const result = list.length === 0 ? { text: "", truncated: false, invalidUtf8: false, exitCode: 0 }
250
272
  : await run(cwd, [...args, "--patch", `--unified=${context}`, ...revisions], MAX_TOTAL_PATCH_BYTES);
251
273
  if (result.exitCode !== 0) throw new Error("Unable to read Git changes");
252
274
  const merged = new Map(list.map((item) => [item.file, item]));
253
275
  for (const item of extra) if (item.code === "??" && !merged.has(item.file)) merged.set(item.file, item);
276
+ const patches = chunksByFile(result, (index) => list[index]?.file);
277
+ const retry = new Set<string>();
278
+ if (result.invalidUtf8) {
279
+ // The trailing partial chunk is already gone. Re-read only chunks with possible decoding loss.
280
+ for (const [file, patch] of patches) {
281
+ if (!patch.includes("\uFFFD")) continue;
282
+ patches.delete(file);
283
+ retry.add(file);
284
+ }
285
+ }
254
286
  return files(root, ref, [...merged.values()], new Map(numstat(counts.text).map((stat) => [stat.file, stat])), {
255
- patches: chunksByFile(result, (index) => list[index]?.file),
287
+ patches,
256
288
  capped: result.truncated,
289
+ retry,
257
290
  }, context, target);
258
291
  },
259
292
 
@@ -375,4 +408,14 @@ export const Git = {
375
408
  return null;
376
409
  }
377
410
  },
411
+
412
+ /** Git tree mode at the pinned revision; null only when the path is absent. */
413
+ async revisionMode(cwd: string, rev: string, path: string): Promise<FileMode | null> {
414
+ const result = await run(cwd, ["--literal-pathspecs", "ls-tree", "--full-tree", "-z", rev, "--", path]);
415
+ if (result.exitCode !== 0 || result.truncated) throw new Error(`Unable to read Git mode for ${path}`);
416
+ if (!result.text) return null;
417
+ const entry = /^(100644|100755|120000) blob [a-f0-9]+\t([^\0]+)\0$/.exec(result.text);
418
+ if (!entry || entry[2] !== path) throw new Error(`Unsupported Git file type for ${path}`);
419
+ return entry[1] as FileMode;
420
+ },
378
421
  } as const;