xonecas.io
64875
Mc

mini-coder / commit a7f4fdf

feat: add human-readable mc-edit output

xonecas2026-03-15 a7f4fdfca84590f43a6908b6fa27abdee60a3a92 parent 9759449

14 files changed

This diff is too big to show in full. The first 1000 lines are below, and every file is listed with its counts.

docs/file-helper-plan.md+0−295
@@ -1,295 +0,0 @@
1-# File Helper Refactor Plan
2-
3-## Status at a glance
4-
5-This refactor is complete on this branch.
6-
7-mini-coder now follows the intended shell-first model:
8-
9-- `mc-edit` exists as a dedicated helper binary
10-- shared file-edit logic lives under `src/internal/file-edit/`
11-- shell exposes `mc-edit` as the targeted edit path
12-- the system prompt and tool surface are simplified around shell usage
13-- old model-facing local file tools are removed
14-- hook support is removed
15-- `/undo` is conversation-turn undo only
16-
17-`/undo` no longer tries to restore filesystem state, which keeps the architecture honest with the real shell + `mc-edit` edit path.
18-
19----
20-
21-## Why this refactor exists
22-
23-The old hashline editing protocol (`read` + `replace` / `insert`) was too fragile for normal model use.
24-
25-Problems with the old approach:
26-
27-- `read` returned decorated `line:hash|` output instead of plain file text
28-- edits depended on exact protocol choreography across multiple tool calls
29-- models had to carry stale anchors and hashes across turns
30-- semantically correct edits often failed because the payload shape or anchor state was slightly wrong
31-- failures regularly degraded into reread-and-repair loops
32-- when that happened, shell was already the practical fallback
33-
34-The point of this refactor was **not** to improve that protocol.
35-The point was to replace it with a simpler contract that matches how models already work best:
36-
37-- inspect with shell
38-- edit with a narrow helper
39-- verify with shell
40-
41-That is why `mc-edit` exists.
42-
43----
44-
45-## Target architecture
46-
47-### Final model-facing tool surface
48-
49-The steady state is:
50-
51-- connected **MCP tools**
52-- **`shell`**
53-- **`subagent`**
54-- **`listSkills`**
55-- **`readSkill`**
56-- **`webSearch`** and **`webContent`** when Exa is configured
57-
58-Removed local runtime tools:
59-
60-- `read`
61-- `create`
62-- `replace`
63-- `insert`
64-- hook-related runtime tooling
65-
66-### Final file workflow
67-
68-The intended workflow is:
69-
70-1. inspect/search with shell
71-2. mutate files with `mc-edit`
72-3. verify with shell
73-
74-`mc-edit` is intentionally narrow:
75-
76-- exact-text edits only
77-- deterministic failure on stale or ambiguous state
78-- machine-friendly output
79-- no broad file-management abstraction beyond the edit helper itself
80-
81----
82-
83-## What landed on this branch
84-
85-### 1. Shared file-edit internals were extracted
86-
87-Implemented under:
88-
89-- `src/internal/file-edit/cli.ts`
90-- `src/internal/file-edit/exact-text.ts`
91-- `src/internal/file-edit/path.ts`
92-- `src/internal/file-edit/command.ts`
93-
94-### 2. `mc-edit` was added as its own binary
95-
96-Implemented via:
97-
98-- `src/mc-edit.ts`
99-- `package.json`
100-- `scripts/build.ts`
101-
102-### 3. The agent was moved to a shell-first editing model
103-
104-Implemented via:
105-
106-- shell prelude injection in `src/tools/shell.ts`
107-- prompt guidance in `src/agent/system-prompt.ts`
108-- shell tests covering `mc-edit` wiring
109-
110-### 4. The old structured edit path was removed
111-
112-Implemented by removing the hashline edit flow built around `replace` and `insert`, and by collapsing the surrounding plumbing that only existed to support that protocol.
113-
114-### 5. The local tool surface was reduced
115-
116-The local runtime surface is now centered on:
117-
118-- `shell`
119-- `subagent`
120-- `listSkills`
121-- `readSkill`
122-- optional Exa tools
123-
124-### 6. Hook support was removed instead of redesigned
125-
126-This cleanup was part of the refactor because hooks were tied to the old, heavier local tool story and were not worth carrying forward in the middle of this architecture change.
127-
128-### 7. CLI and docs cleanup was completed
129-
130-Prompt text, tool rendering, help text, and docs now consistently reflect the shell-first model and the conversation-only `/undo` behavior.
131-
132----
133-
134-## Key decisions
135-
136-### 1. Shell is the primary interface for repo work
137-
138-Shell is the default for:
139-
140-- reading files
141-- searching
142-- running tests/builds
143-- git inspection
144-- verification
145-- invoking `mc-edit`
146-
147-We are no longer optimizing around a large local file-tool API.
148-
149-### 2. `mc-edit` is the safe path for targeted edits
150-
151-We want one narrow edit helper instead of several model-facing edit tools.
152-
153-That keeps the contract simpler:
154-
155-- shell handles orchestration
156-- `mc-edit` handles exact mutation
157-
158-### 3. `listSkills` and `readSkill` stay
159-
160-These are not general-purpose file tools. They are support tools for community/project config and should remain available.
161-
162-### 4. `read` and `create` should not remain as compatibility tools
163-
164-If file inspection is shell-driven and edits are shell + `mc-edit`, keeping old local file tools around only muddies the contract.
165-
166-### 5. Hooks are out for this refactor
167-
168-The correct choice here is deletion, not redesign.
169-
170-If hooks ever come back, that should happen as a separate effort with a clear use case.
171-
172-### 6. `/undo` should stay aligned with the real edit path
173-
174-The old snapshot model was built around tool-managed writes.
175-That no longer matches reality.
176-
177-The correct result for this refactor is to keep `/undo` as conversation history undo only, not a filesystem restoration feature for shell-driven edits.
178-
179-### 7. MCP descriptions matter more now
180-
181-With fewer local tools, MCP tools take up a larger share of the model-visible surface.
182-Their names and descriptions should stay concise and easy to distinguish from shell work.
183-
184----
185-
186-## Completion status
187-
188-### 1. Redesign `/undo`
189-
190-This work is done.
191-
192-#### What changed
193-
194-Undo no longer depends on the old snapshot path.
195-The snapshot-specific pieces were removed, including:
196-
197-- `src/tools/snapshot.ts`
198-- `src/agent/undo-snapshot.ts`
199-- `src/session/db/snapshot-repo.ts`
200-
201-`/undo` now removes only the most recent conversation turn from session history.
202-It does not try to infer or restore filesystem state from shell-driven edits.
203-
204-#### Result
205-
206-- `/undo` doesn't manage filesystem changes
207-- snapshotting is removed from runtime code and docs
208-
209----
210-
211-### 2. Finish the docs and help-text consistency pass
212-
213-This work is done.
214-
215-README, config/docs pages, bundled commands/skills guidance, and `mini-coder-idea.md` consistently describe the shell-first model, name `mc-edit` as the targeted edit path, and keep `/undo` scoped to conversation history only.
216-
217-#### Done when
218-
219-- docs match implementation
220-- examples reinforce shell + `mc-edit`
221-- there are no stale references to removed tools or hooks
222-- `/undo` is consistently described as conversation-history undo only
223-
224----
225-
226-### 3. Final prompt, CLI, and rendering polish
227-
228-This work is done.
229-
230-The system prompt names the final built-in tool surface explicitly, `/help` keeps `/undo` aligned with the conversation-only guarantee, MCP tool descriptions are tighter, and skill-tool call/result rendering is compact and readable.
231-
232-#### Done when
233-
234-- prompt text exactly matches runtime behavior
235-- CLI output reflects only the remaining architecture
236-- MCP descriptions are concise and distinguishable
237-
238----
239-
240-### 4. Verify the cleanup end-to-end
241-
242-This work is done on this branch.
243-
244-The runtime tool set is reduced to the intended surface, the bundled hook example files were removed, and the full repo verification command passes.
245-
246-#### Repo verification command
247-
248-Run:
249-
250-```bash
251-bun run jscpd && bun run knip && bun run typecheck && bun run format && bun run lint && bun run test
252-```
253-
254-Status on this branch: this command passes after the full shell-first cleanup.
255-
256----
257-
258-## Completion checklist
259-
260-This refactor is complete when all of the following are true:
261-
262-- the model-visible tool surface is shell, subagent, listSkills, readSkill, connected MCP tools, and optional Exa tools
263-- `mc-edit` is the clear targeted edit path
264-- the old hashline edit path is fully gone
265-- hooks are fully gone from runtime, UI, and docs/examples
266-- `/undo` is aligned with the shell-first architecture by only undoing conversation history
267-- prompt, CLI, and docs all describe the same architecture
268-- bundled commands/skills/examples reinforce the shell-first workflow
269-
270----
271-
272-## Non-goals
273-
274-This effort is not trying to:
275-
276-- improve the old hashline edit protocol
277-- keep old local edit tools as fallback paths
278-- redesign a new hook framework right now
279-- guarantee undo for arbitrary raw shell file operations
280-- turn `mc-edit` into a broad file-management CLI
281-
282----
283-
284-## Practical conclusion
285-
286-Compared to `main`, this branch completed the hard architectural shift: `mc-edit` exists, shell is the primary path, the old local edit model is gone, hooks are gone, and `/undo` is aligned with conversation history rather than filesystem restoration.
287-
288-At this point, the refactor is complete in the intended sense:
289-
290-- the model-visible tool surface is small and shell-first
291-- `mc-edit` is the clear targeted edit path
292-- prompt, CLI, docs, and bundled examples describe the same architecture
293-- verification passes on the branch
294-
295-Future work can build on this baseline, but the file-helper refactor itself has reached its intended end state.
docs/mini-coder.1.md+4−0
@@ -109,6 +109,10 @@ The agent has access to the following tools:
109109 * **webContent**: Fetch full page content from a URL (requires EXA key).
110110 * **MCP tools**: Connected external tools attached dynamically from configured MCP servers.
111111
112+## FILE EDIT HELPER
113+**mc-edit**
114+: Helper command used from shell for one exact-text edit on an existing file. On success it prints a human-readable colored unified diff to stdout followed by a short metadata block (`ok`, `path`, `changed`). If the edit is a no-op, it prints `(no changes)` plus the same metadata. Errors are written to stderr.
115+
112116 ## ENVIRONMENT
113117 **OPENCODE_API_KEY**
114118 : OpenCode Zen API key (Recommended provider).
mini-coder-idea.md+1−1
@@ -34,7 +34,7 @@ conventions and not introduce more specs. (`.agents` / `AGENTS.md`, while also s
3434 - Feature parity with community configs like custom agents, skill and commands.
3535 - Shell-first tool surface for LLMs: `shell`, `subagent`, `listSkills`, and `readSkill`, plus connected MCP tools. Keep the core surface small and easy to use so it actually reduces friction for the LLMs.
3636 - File work should follow a simple flow: inspect with shell, mutate with `mc-edit`, verify with shell.
37-- `mc-edit` should stay narrow and reliable: exact-text edits only, deterministic failures on stale or ambiguous state, machine-friendly output.
37+- `mc-edit` should stay narrow and reliable: exact-text edits only, deterministic failures on stale or ambiguous state, diff and machine-friendly output while staying human readable.
3838 - Optional `webSearch` and `webContent` tools when `EXA_API_KEY` is set.
3939 - `subagent` tool spawns a fresh `mc` subprocess in one shot mode.
4040 - Commands in CLI prompt:
package.json+1−0
@@ -26,6 +26,7 @@
2626 "@ai-sdk/openai-compatible": "^2.0.36",
2727 "@modelcontextprotocol/sdk": "^1.27.1",
2828 "ai": "^6.0.127",
29+ "diff": "^8.0.3",
2930 "yoctocolors": "^2.1.2",
3031 "zod": "^4.3.6"
3132 },
src/cli/output.ts+0−3
@@ -76,9 +76,6 @@ export const G = {
7676 err: c.red("✖"),
7777 warn: c.yellow("!"),
7878 info: c.dim("·"),
79- diff_add: c.green("+"),
80- diff_del: c.red("-"),
81- diff_hdr: c.cyan("@"),
8279 };
8380
8481 export const PREFIX = {
src/cli/structured-output.test.ts+56−0
@@ -0,0 +1,56 @@
1+import { describe, expect, test } from "bun:test";
2+import { renderUnifiedDiff, writeJsonLine } from "./structured-output.ts";
3+
4+function stripAnsi(text: string): string {
5+ const esc = String.fromCharCode(0x1b);
6+ return text.replace(new RegExp(`${esc}\\[[0-9;]*m`, "g"), "");
7+}
8+
9+describe("renderUnifiedDiff", () => {
10+ test("renders a colored unified diff without legacy index headers", () => {
11+ const output = renderUnifiedDiff("f.txt", "a\nb\nc\n", "a\nB\nc\n");
12+
13+ expect(stripAnsi(output)).toBe(
14+ [
15+ "--- f.txt",
16+ "+++ f.txt",
17+ "@@ -1,3 +1,3 @@",
18+ " a",
19+ "-b",
20+ "+B",
21+ " c",
22+ ].join("\n"),
23+ );
24+ });
25+
26+ test("renders valid hunk headers when deleting all file contents", () => {
27+ const output = renderUnifiedDiff("f.txt", "x\n", "");
28+
29+ expect(stripAnsi(output)).toBe(
30+ ["--- f.txt", "+++ f.txt", "@@ -1,1 +0,0 @@", "-x"].join("\n"),
31+ );
32+ });
33+
34+ test("renders valid hunk headers when inserting at the start of a file", () => {
35+ const output = renderUnifiedDiff("f.txt", "", "x\n");
36+
37+ expect(stripAnsi(output)).toBe(
38+ ["--- f.txt", "+++ f.txt", "@@ -0,0 +1,1 @@", "+x"].join("\n"),
39+ );
40+ });
41+});
42+
43+describe("writeJsonLine", () => {
44+ test("writes one compact newline-delimited JSON object", () => {
45+ let output = "";
46+
47+ writeJsonLine(
48+ (text) => {
49+ output += text;
50+ },
51+ { ok: true, value: [1, 2, 3] },
52+ );
53+
54+ expect(output).toBe('{"ok":true,"value":[1,2,3]}\n');
55+ });
56+});
src/cli/structured-output.ts+121−0
@@ -0,0 +1,121 @@
1+import { createTwoFilesPatch } from "diff";
2+import * as c from "yoctocolors";
3+import type {
4+ ApplyExactTextEditResult,
5+ FileEditErrorCode,
6+} from "../internal/file-edit/exact-text.ts";
7+
8+export interface StructuredOutputWriter {
9+ stdout: (text: string) => void;
10+ stderr: (text: string) => void;
11+}
12+
13+type FileEditCliSuccess = { ok: true } & ApplyExactTextEditResult;
14+
15+export interface FileEditCliFailure {
16+ ok: false;
17+ code: FileEditErrorCode | "invalid_args";
18+ message: string;
19+ path?: string;
20+}
21+
22+export function writeJsonLine(
23+ write: (text: string) => void,
24+ payload: unknown,
25+): void {
26+ write(`${JSON.stringify(payload)}\n`);
27+}
28+
29+function normalizePatchLines(patchText: string): string[] {
30+ const patchLines = patchText.split("\n");
31+ while (patchLines.at(-1) === "") {
32+ patchLines.pop();
33+ }
34+
35+ const diffLines = patchLines.filter(
36+ (line) =>
37+ !line.startsWith("Index: ") &&
38+ line !==
39+ "===================================================================",
40+ );
41+
42+ return diffLines.map((line) => {
43+ if (line.startsWith("--- ") || line.startsWith("+++ ")) {
44+ return line.split("\t", 1)[0] ?? line;
45+ }
46+ return line;
47+ });
48+}
49+
50+export function renderUnifiedDiff(
51+ filePath: string,
52+ before: string,
53+ after: string,
54+): string {
55+ if (before === after) {
56+ return c.dim("(no changes)");
57+ }
58+
59+ const patchText = createTwoFilesPatch(
60+ filePath,
61+ filePath,
62+ before,
63+ after,
64+ "",
65+ "",
66+ {
67+ context: 3,
68+ },
69+ );
70+ const lines = normalizePatchLines(patchText);
71+
72+ return lines
73+ .map((line) => {
74+ if (line.startsWith("+++ ") || line.startsWith("+")) {
75+ return c.green(line);
76+ }
77+ if (line.startsWith("--- ") || line.startsWith("-")) {
78+ return c.red(line);
79+ }
80+ if (line.startsWith("@@ ")) {
81+ return c.cyan(line);
82+ }
83+ if (line.startsWith("\\")) {
84+ return c.dim(line);
85+ }
86+ return line;
87+ })
88+ .join("\n");
89+}
90+
91+function renderMetadataBlock(
92+ result: FileEditCliSuccess | FileEditCliFailure,
93+): string {
94+ const lines = [`ok: ${result.ok}`];
95+ if ("path" in result && result.path) {
96+ lines.push(`path: ${result.path}`);
97+ }
98+ if (result.ok) {
99+ lines.push(`changed: ${result.changed}`);
100+ } else {
101+ lines.push(`code: ${result.code}`);
102+ lines.push(`message: ${result.message}`);
103+ }
104+ return lines.join("\n");
105+}
106+
107+export function writeFileEditResult(
108+ io: StructuredOutputWriter,
109+ result: FileEditCliSuccess | FileEditCliFailure,
110+): void {
111+ if (result.ok) {
112+ const sections = [
113+ renderUnifiedDiff(result.path, result.before, result.after),
114+ renderMetadataBlock(result),
115+ ];
116+ io.stdout(`${sections.join("\n\n")}\n`);
117+ return;
118+ }
119+
120+ io.stderr(`${renderMetadataBlock(result)}\n`);
121+}
src/index.ts+12−4
@@ -21,6 +21,7 @@ import {
2121 writeln,
2222 } from "./cli/output.ts";
2323 import { resolvePromptInput } from "./cli/stdin-prompt.ts";
24+import { writeJsonLine } from "./cli/structured-output.ts";
2425 import { terminal } from "./cli/terminal-io.ts";
2526 import { initApiLog } from "./llm-api/api-log.ts";
2627 import {
@@ -146,13 +147,20 @@ async function main(): Promise<void> {
146147 };
147148
148149 if (args.outputFd !== null && summary) {
149- const json = `${JSON.stringify(summary)}\n`;
150- writeSync(args.outputFd, Buffer.from(json));
150+ const outputFd = args.outputFd;
151+ writeJsonLine((text) => {
152+ writeSync(outputFd, Buffer.from(text));
153+ }, summary);
151154 }
152155 } catch (err) {
153156 if (args.outputFd !== null) {
154- const json = `${JSON.stringify({ error: String(err) })}\n`;
155- writeSync(args.outputFd, Buffer.from(json));
157+ const outputFd = args.outputFd;
158+ writeJsonLine(
159+ (text) => {
160+ writeSync(outputFd, Buffer.from(text));
161+ },
162+ { error: String(err) },
163+ );
156164 }
157165 process.exit(1);
158166 }
src/internal/file-edit/cli.test.ts+55−12
@@ -34,8 +34,13 @@ function createIo() {
3434 };
3535 }
3636
37+function stripAnsi(text: string): string {
38+ const esc = String.fromCharCode(0x1b);
39+ return text.replace(new RegExp(`${esc}\\[[0-9;]*m`, "g"), "");
40+}
41+
3742 describe("runFileEditCli", () => {
38- test("applies one edit from temp files and emits compact json", async () => {
43+ test("renders a unified diff and metadata for a changed file", async () => {
3944 await writeFile(join(cwd, "f.txt"), "before\nOLD\nafter\n");
4045 await writeFile(join(cwd, "old.txt"), "OLD\n");
4146 await writeFile(join(cwd, "new.txt"), "NEW\n");
@@ -56,17 +61,51 @@ describe("runFileEditCli", () => {
5661
5762 expect(exitCode).toBe(0);
5863 expect(capture.getStderr()).toBe("");
59- expect(JSON.parse(capture.getStdout())).toEqual({
60- ok: true,
61- path: "f.txt",
62- changed: true,
63- });
64+ expect(stripAnsi(capture.getStdout())).toBe(
65+ [
66+ "--- f.txt",
67+ "+++ f.txt",
68+ "@@ -1,3 +1,3 @@",
69+ " before",
70+ "-OLD",
71+ "+NEW",
72+ " after",
73+ "",
74+ "ok: true",
75+ "path: f.txt",
76+ "changed: true",
77+ "",
78+ ].join("\n"),
79+ );
6480 expect(await Bun.file(join(cwd, "f.txt")).text()).toBe(
6581 "before\nNEW\nafter\n",
6682 );
6783 });
6884
69- test("returns a structured invalid_args error", async () => {
85+ test("renders a no-op result without a fake diff", async () => {
86+ await writeFile(join(cwd, "f.txt"), "same\n");
87+ const capture = createIo();
88+
89+ const exitCode = await runFileEditCli(
90+ ["f.txt", "--cwd", cwd, "--old", "same\n", "--new", "same\n"],
91+ capture.io,
92+ );
93+
94+ expect(exitCode).toBe(0);
95+ expect(capture.getStderr()).toBe("");
96+ expect(stripAnsi(capture.getStdout())).toBe(
97+ [
98+ "(no changes)",
99+ "",
100+ "ok: true",
101+ "path: f.txt",
102+ "changed: false",
103+ "",
104+ ].join("\n"),
105+ );
106+ });
107+
108+ test("renders invalid argument errors to stderr", async () => {
70109 const capture = createIo();
71110
72111 const exitCode = await runFileEditCli(
@@ -75,10 +114,14 @@ describe("runFileEditCli", () => {
75114 );
76115
77116 expect(exitCode).toBe(1);
78- expect(JSON.parse(capture.getStdout())).toEqual({
79- ok: false,
80- code: "invalid_args",
81- message: "Provide exactly one of --old or --old-file.",
82- });
117+ expect(capture.getStdout()).toBe("");
118+ expect(stripAnsi(capture.getStderr())).toBe(
119+ [
120+ "ok: false",
121+ "code: invalid_args",
122+ "message: Provide exactly one of --old or --old-file.",
123+ "",
124+ ].join("\n"),
125+ );
83126 });
84127 });
src/internal/file-edit/cli.ts+27−48
@@ -1,8 +1,9 @@
11 import {
2- applyExactTextEdit,
3- FileEditError,
4- type FileEditErrorCode,
5-} from "./exact-text.ts";
2+ type FileEditCliFailure,
3+ type StructuredOutputWriter,
4+ writeFileEditResult,
5+} from "../../cli/structured-output.ts";
6+import { applyExactTextEdit, FileEditError } from "./exact-text.ts";
67
78 interface FileEditCliArgs {
89 cwd: string;
@@ -11,30 +12,12 @@ interface FileEditCliArgs {
1112 newText: string;
1213 }
1314
14-interface FileEditCliIo {
15- stdout: (text: string) => void;
16- stderr: (text: string) => void;
17-}
18-
19-type FileEditCliSuccess = {
20- ok: true;
21- path: string;
22- changed: boolean;
23-};
24-
25-type FileEditCliFailure = {
26- ok: false;
27- code: FileEditErrorCode | "invalid_args";
28- message: string;
29- path?: string;
30-};
31-
3215 const HELP = `Usage: mc-edit <path> (--old <text> | --old-file <path>) [--new <text> | --new-file <path>] [--cwd <path>]
3316
3417 Apply one safe exact-text edit to an existing file.
3518 - The expected old text must match exactly once.
3619 - Omit --new / --new-file to delete the matched text.
37-- Output is a single JSON object on stdout.`;
20+- Success output is human-oriented: unified diff first, metadata second.`;
3821
3922 async function readArgText(
4023 flag: "--old-file" | "--new-file",
@@ -112,54 +95,50 @@ async function parseFileEditCliArgs(
11295 };
11396 }
11497
115-function writeJson(
116- io: FileEditCliIo,
117- payload: FileEditCliSuccess | FileEditCliFailure,
118-) {
119- io.stdout(`${JSON.stringify(payload)}\n`);
98+function buildCliFailure(
99+ code: FileEditCliFailure["code"],
100+ message: string,
101+ path?: string,
102+): FileEditCliFailure {
103+ return {
104+ ok: false,
105+ code,
106+ message,
107+ ...(path ? { path } : {}),
108+ };
120109 }
121110
122-function normalizeCliError(error: unknown): FileEditCliFailure {
111+function normalizeCliError(error: unknown, path?: string): FileEditCliFailure {
123112 if (error instanceof FileEditError) {
124- return {
125- ok: false,
126- code: error.code,
127- message: error.message,
128- };
113+ return buildCliFailure(error.code, error.message, path);
129114 }
130115 if (error instanceof Error) {
131- return {
132- ok: false,
133- code: "invalid_args",
134- message: error.message,
135- };
116+ return buildCliFailure("invalid_args", error.message, path);
136117 }
137- return {
138- ok: false,
139- code: "invalid_args",
140- message: "Unknown error.",
141- };
118+ return buildCliFailure("invalid_args", "Unknown error.", path);
142119 }
143120
144121 export async function runFileEditCli(
145122 argv: string[],
146- io: FileEditCliIo = {
123+ io: StructuredOutputWriter = {
147124 stdout: (text) => process.stdout.write(text),
148125 stderr: (text) => process.stderr.write(text),
149126 },
150127 ): Promise<number> {
128+ let parsed: FileEditCliArgs | null = null;
129+
151130 try {
152- const parsed = await parseFileEditCliArgs(argv);
131+ parsed = await parseFileEditCliArgs(argv);
153132 if (parsed === null) {
154133 io.stderr(`${HELP}\n`);
155134 return 0;
156135 }
157136
158137 const result = await applyExactTextEdit(parsed);
159- writeJson(io, { ok: true, ...result });
138+ writeFileEditResult(io, { ok: true, ...result });
160139 return 0;
161140 } catch (error) {
162- writeJson(io, normalizeCliError(error));
141+ writeFileEditResult(io, normalizeCliError(error, parsed?.path));
163142 return 1;
164143 }
165144 }
src/internal/file-edit/exact-text.test.ts+12−2
@@ -59,7 +59,12 @@ describe("applyExactTextEdit", () => {
5959 newText: "B\n",
6060 });
6161
62- expect(result).toEqual({ path: "f.txt", changed: true });
62+ expect(result).toEqual({
63+ path: "f.txt",
64+ changed: true,
65+ before: "a\nb\nc\n",
66+ after: "a\nB\nc\n",
67+ });
6368 expect(await Bun.file(join(cwd, "f.txt")).text()).toBe("a\nB\nc\n");
6469 });
6570
@@ -73,7 +78,12 @@ describe("applyExactTextEdit", () => {
7378 newText: "same\n",
7479 });
7580
76- expect(result).toEqual({ path: "f.txt", changed: false });
81+ expect(result).toEqual({
82+ path: "f.txt",
83+ changed: false,
84+ before: "same\n",
85+ after: "same\n",
86+ });
7787 expect(await Bun.file(join(cwd, "f.txt")).text()).toBe("same\n");
7888 });
7989
src/internal/file-edit/exact-text.ts+5−1
@@ -28,9 +28,11 @@ interface ApplyExactTextEditInput {
2828 newText: string;
2929 }
3030
31-interface ApplyExactTextEditResult {
31+export interface ApplyExactTextEditResult {
3232 path: string;
3333 changed: boolean;
34+ before: string;
35+ after: string;
3436 }
3537
3638 function findExactMatchOffsets(source: string, target: string): number[] {
@@ -101,5 +103,7 @@ export async function applyExactTextEdit(
101103 return {
102104 path: relPath,
103105 changed: plan.changed,
106+ before: original,
107+ after: plan.updated,
104108 };
105109 }
src/tools/diff.test.ts+0−123
@@ -1,123 +0,0 @@
1-import { describe, expect, test } from "bun:test";
2-import { generateDiff } from "./diff.ts";
3-
4-describe("generateDiff", () => {
5- test("returns (no changes) when before and after are identical", () => {
6- const content = "line1\nline2\nline3\n";
7- expect(generateDiff("file.txt", content, content)).toBe("(no changes)");
8- });
9-
10- test("handles empty before (new file)", () => {
11- const after = "alpha\nbeta\ngamma\n";
12- const result = generateDiff("new.txt", "", after);
13- expect(result).toContain("+alpha");
14- expect(result).toContain("+beta");
15- expect(result).toContain("+gamma");
16- // No lines should be marked as removed (--- header is expected, diff lines are not)
17- expect(result).not.toMatch(/^-[^-]/m);
18- // New-file hunk header must use start=0 for the before side
19- expect(result).toMatch(/@@ -0,0 \+1,\d+ @@/);
20- });
21-
22- test("handles empty after (file deleted / cleared)", () => {
23- const before = "alpha\nbeta\ngamma\n";
24- const result = generateDiff("old.txt", before, "");
25- expect(result).toContain("-alpha");
26- expect(result).toContain("-beta");
27- expect(result).toContain("-gamma");
28- expect(result).not.toMatch(/^\+[^+]/m);
29- // Cleared-file hunk header must use start=0 for the after side
30- expect(result).toMatch(/@@ -1,\d+ \+0,0 @@/);
31- });
32-
33- test("appending lines shows only added lines as +", () => {
34- const before = "a\nb\nc\n";
35- const after = "a\nb\nc\nd\ne\n";
36- const result = generateDiff("f.txt", before, after);
37- expect(result).toContain("+d");
38- expect(result).toContain("+e");
39- // 'a', 'b', 'c' must not appear as removed
40- expect(result).not.toContain("-a");
41- expect(result).not.toContain("-b");
42- expect(result).not.toContain("-c");
43- });
44-
45- test("deleting lines from the middle shows only removed lines as -", () => {
46- const before = "a\nb\nc\nd\ne\n";
47- const after = "a\nd\ne\n";
48- const result = generateDiff("f.txt", before, after);
49- expect(result).toContain("-b");
50- expect(result).toContain("-c");
51- // unchanged lines must not appear as added
52- expect(result).not.toContain("+a");
53- expect(result).not.toContain("+d");
54- expect(result).not.toContain("+e");
55- });
56-
57- test("replacing a middle line does not mark surrounding unchanged lines as changed", () => {
58- // This was the core bug: lines after the change were shown as both - and +
59- const lines = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"];
60- const before = lines.join("\n");
61- const after = [
62- "1",
63- "2",
64- "3",
65- "CHANGED",
66- "5",
67- "6",
68- "7",
69- "8",
70- "9",
71- "10",
72- ].join("\n");
73- const result = generateDiff("f.txt", before, after);
74-
75- expect(result).toContain("-4");
76- expect(result).toContain("+CHANGED");
77- // Lines 5-10 are unchanged and must not appear as - or +
78- for (const line of ["5", "6", "7", "8", "9", "10"]) {
79- expect(result).not.toMatch(new RegExp(`^-${line}$`, "m"));
80- expect(result).not.toMatch(new RegExp(`^\\+${line}$`, "m"));
81- }
82- });
83-
84- test("two disjoint changes produce two separate hunks", () => {
85- // Change line 1 and line 20, with 14+ unchanged lines between them
86- const beforeLines = Array.from({ length: 22 }, (_, i) => `line${i + 1}`);
87- const afterLines = [...beforeLines];
88- afterLines[0] = "FIRST";
89- afterLines[21] = "LAST";
90- const before = beforeLines.join("\n");
91- const after = afterLines.join("\n");
92-
93- const result = generateDiff("f.txt", before, after);
94- // Two @@ hunk headers expected
95- const hunkCount = (result.match(/^@@/gm) ?? []).length;
96- expect(hunkCount).toBe(2);
97-
98- expect(result).toContain("-line1");
99- expect(result).toContain("+FIRST");
100- expect(result).toContain("-line22");
101- expect(result).toContain("+LAST");
102- });
103-
104- test("hunk header has correct --- / +++ file path", () => {
105- const result = generateDiff("src/foo.ts", "old\n", "new\n");
106- expect(result).toContain("--- src/foo.ts");
107- expect(result).toContain("+++ src/foo.ts");
108- });
109-
110- test("hunk @@ line counts are accurate", () => {
111- // Replace one line in a 5-line file; hunk should cover all 5 lines
112- // with context (3 before + changed + 1 after, but clamped to file size)
113- const before = "a\nb\nc\nd\ne";
114- const after = "a\nb\nX\nd\ne";
115- const result = generateDiff("f.txt", before, after);
116- // Extract the @@ line
117- const match = result.match(/@@ -(\d+),(\d+) \+(\d+),(\d+) @@/);
118- expect(match).not.toBeNull();
119- const [, , beforeCount, , afterCount] = match ?? [];
120- expect(Number(beforeCount)).toBe(5);
121- expect(Number(afterCount)).toBe(5);
122- });
123-});
src/tools/diff.ts+0−190
@@ -1,190 +0,0 @@
1-export function generateDiff(
2- filePath: string,
3- before: string,
4- after: string,
5-): string {
6- const beforeLines = before === "" ? [] : before.split("\n");
7- const afterLines = after === "" ? [] : after.split("\n");
8-
9- const diff = computeUnifiedDiff(beforeLines, afterLines);
10-
11- if (diff.length === 0) return "(no changes)";
12-
13- return `--- ${filePath}\n+++ ${filePath}\n${diff}`;
14-}
15-
16-// ---------------------------------------------------------------------------
17-// Myers diff algorithm (Eugene Myers, 1986)
18-// O(n * d) time and space where n = max(m, n_after), d = edit distance.
19-// For typical small-edit cases this is far more memory-efficient than the
20-// previous LCS approach which always allocated O(m * n) space.
21-// ---------------------------------------------------------------------------
22-
23-type EditKind = "eq" | "del" | "ins";
24-type EditOp = { kind: EditKind; line: string };
25-
26-/**
27- * Produce a minimal edit script (sequence of eq/del/ins operations) using the
28- * Myers diff algorithm with trace-based backtracking.
29- */
30-function editScript(before: string[], after: string[]): EditOp[] {
31- const m = before.length;
32- const n = after.length;
33-
34- if (m === 0) return after.map((line) => ({ kind: "ins" as const, line }));
35- if (n === 0) return before.map((line) => ({ kind: "del" as const, line }));
36-
37- const max = m + n;
38- const offset = max; // shift so negative diagonal indices are valid array indices
39- // V[k + offset] = furthest x reached on diagonal k
40- const V = new Int32Array(2 * max + 2);
41- // Snapshot of V at the start of each edit-distance iteration d, used for
42- // backtracking. trace[d] is the state when d edits have already been applied.
43- const trace: Int32Array[] = [];
44-
45- outer: for (let d = 0; d <= max; d++) {
46- trace.push(V.slice());
47- for (let k = -d; k <= d; k += 2) {
48- // Decide whether to move down (insert from after) or right (delete from before).
49- const fromInsert =
50- k === -d ||
51- (k !== d &&
52- (V[k - 1 + offset] as number) < (V[k + 1 + offset] as number));
53- let x = fromInsert
54- ? (V[k + 1 + offset] as number)
55- : (V[k - 1 + offset] as number) + 1;
56- let y = x - k;
57- // Follow the snake: advance while lines are equal.
58- while (x < m && y < n && before[x] === after[y]) {
59- x++;
60- y++;
61- }
62- V[k + offset] = x;
63- if (x >= m && y >= n) break outer;
64- }
65- }
Cut short: this commit's diff is over 1000 lines.