xonecas.io
64875
Mc

mini-coder / commit 440597b

refactor: remove hashline edit tools

xonecas2026-03-15 440597b713dfcad9b0682fc6e72f4030bc8be06c parent 09d5af4

17 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/mini-coder.1.md+1−3
@@ -103,9 +103,7 @@ Inside the interactive session, the following slash commands are available:
103103 The agent has access to the following tools:
104104 * **read**: Read file contents with line-range pagination support.
105105 * **create**: Write a new file or completely overwrite an existing one.
106-* **replace**: Replace or delete targeted lines using hashline anchors.
107-* **insert**: Insert new lines before/after an anchor without replacing existing content.
108-* **shell**: Execute bash commands and capture output.
106+* **shell**: Execute bash commands and capture output. Partial file edits are typically done here via `mc-edit`.
109107 * **subagent**: Spawn a focused mini-agent with a prompt.
110108 * **webSearch**: Search the internet (requires EXA key).
111109 * **webContent**: Fetch full page content from a URL (requires EXA key).
docs/tool-hooks.md+10−24
@@ -21,12 +21,12 @@ Local hooks take precedence over global ones. The filename must match `post-<too
2121 |---|---|
2222 | `read` | `post-read` |
2323 | `create` | `post-create` |
24-| `replace` | `post-replace` |
25-| `insert` | `post-insert` |
2624 | `shell` | `post-shell` |
2725
2826 MCP tools are not hookable.
2927
28+For partial edits, the agent now prefers shell commands that invoke `mc-edit`, so those operations are observed through `post-shell`.
29+
3030 ## Script requirements
3131
3232 The script must be executable (`chmod +x`). It can be written in any language — bash, Python, Node, etc. It receives context via environment variables and its exit code is reported in the UI (zero = success, non-zero = failure).
@@ -50,21 +50,6 @@ Plus tool-specific variables:
5050 | `DIFF` | Unified diff of the change |
5151 | `CREATED` | `true` if the file was newly created, `false` if overwritten |
5252
53-### `post-replace`
54-
55-| Variable | Description |
56-|---|---|
57-| `FILEPATH` | Absolute path of the file modified |
58-| `DIFF` | Unified diff of the change |
59-| `DELETED` | `true` if lines were deleted (no replacement content), `false` otherwise |
60-
61-### `post-insert`
62-
63-| Variable | Description |
64-|---|---|
65-| `FILEPATH` | Absolute path of the file modified |
66-| `DIFF` | Unified diff of the change |
67-
6853 ### `post-shell`
6954
7055 | Variable | Description |
@@ -83,7 +68,7 @@ Plus tool-specific variables:
8368
8469 ## Examples
8570
86-### Auto-format on write
71+### Auto-format on create/overwrite
8772
8873 `.agents/hooks/post-create`:
8974
@@ -97,8 +82,6 @@ bun run format -- "$FILEPATH"
9782 chmod +x .agents/hooks/post-create
9883 ```
9984
100-Pair with a matching `post-replace` and `post-insert` to cover all write tools.
101-
10285 ### Log every shell command
10386
10487 `~/.agents/hooks/post-shell`:
@@ -113,14 +96,17 @@ echo "$(date -u +%FT%TZ) exit=$EXIT_CODE $COMMAND" >> ~/.config/mini-coder/she
11396 chmod +x ~/.agents/hooks/post-shell
11497 ```
11598
116-### Notify on file write
99+### Notify on `mc-edit` usage
117100
118-`.agents/hooks/post-replace`:
101+`.agents/hooks/post-shell`:
119102
120103 ```bash
121104 #!/usr/bin/env bash
122-# macOS notification when the agent edits a file.
123-osascript -e "display notification \"$FILEPATH\" with title \"mini-coder wrote a file\""
105+case "$COMMAND" in
106+ *mc-edit*)
107+ osascript -e "display notification \"$COMMAND\" with title \"mini-coder ran mc-edit\""
108+ ;;
109+esac
124110 ```
125111
126112 ## Hook lookup
src/agent/tools.test.ts+3−41
@@ -2,7 +2,6 @@ import { afterEach, beforeEach, describe, expect, test } from "bun:test";
22 import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
33 import { homedir, tmpdir } from "node:os";
44 import { join } from "node:path";
5-import { hashLine } from "../tools/hashline.ts";
65 import { resolvePath } from "../tools/shared.ts";
76 import { buildToolSet } from "./tools.ts";
87
@@ -52,45 +51,6 @@ describe("buildToolSet write hooks", () => {
5251 expect((result as { diff: string }).diff).not.toContain("+draft");
5352 });
5453
55- test("replace returns a diff for hook-mutated file contents", async () => {
56- writeFileSync(join(cwd, "f.txt"), "a\nb\n");
57- makeHook(
58- "replace",
59- '#!/bin/bash\nprintf "a\\nB\\nformatted\\n" > "$FILEPATH"\n',
60- );
61-
62- const result = await getTool("replace").execute({
63- path: "f.txt",
64- startAnchor: `2:${hashLine("b")}`,
65- newContent: "B",
66- });
67-
68- expect(await Bun.file(join(cwd, "f.txt")).text()).toBe("a\nB\nformatted\n");
69- expect((result as { diff: string }).diff).toContain("+formatted");
70- expect((result as { diff: string }).diff).not.toBe("(no changes)");
71- });
72-
73- test("insert returns a diff for hook-mutated file contents", async () => {
74- writeFileSync(join(cwd, "f.txt"), "a\nb\n");
75- makeHook(
76- "insert",
77- '#!/bin/bash\nprintf "a\\nnew\\nb\\nformatted\\n" > "$FILEPATH"\n',
78- );
79-
80- const result = await getTool("insert").execute({
81- path: "f.txt",
82- anchor: `1:${hashLine("a")}`,
83- position: "after",
84- content: "new",
85- });
86-
87- expect(await Bun.file(join(cwd, "f.txt")).text()).toBe(
88- "a\nnew\nb\nformatted\n",
89- );
90- expect((result as { diff: string }).diff).toContain("+formatted");
91- expect((result as { diff: string }).diff).not.toMatch(/^-b$/m);
92- });
93-
9454 test("write tools still return the expected diff when no hook exists", async () => {
9555 const result = await getTool("create").execute({
9656 path: "plain.txt",
@@ -103,7 +63,7 @@ describe("buildToolSet write hooks", () => {
10363 });
10464 });
10565
106-describe("skills tools registration", () => {
66+describe("tool set registration", () => {
10767 test("includes listSkills and readSkill in full tool set", () => {
10868 const names = buildToolSet({
10969 cwd,
@@ -118,6 +78,8 @@ describe("skills tools registration", () => {
11878
11979 expect(names).toContain("listSkills");
12080 expect(names).toContain("readSkill");
81+ expect(names).not.toContain("replace");
82+ expect(names).not.toContain("insert");
12183 });
12284 });
12385
src/agent/tools.ts+2−34
@@ -5,18 +5,12 @@ import { webContentTool, webSearchTool } from "../tools/exa.ts";
55 import {
66 createHookCache,
77 hookEnvForCreate,
8- hookEnvForInsert,
98 hookEnvForRead,
10- hookEnvForReplace,
119 hookEnvForShell,
1210 runHook,
1311 } from "../tools/hooks.ts";
14-import type { InsertToolOutput } from "../tools/insert.ts";
15-import { insertTool } from "../tools/insert.ts";
1612 import type { ReadOutput } from "../tools/read.ts";
1713 import { readTool } from "../tools/read.ts";
18-import type { ReplaceToolOutput } from "../tools/replace.ts";
19-import { replaceTool } from "../tools/replace.ts";
2014 import type { ShellOutput } from "../tools/shell.ts";
2115 import { shellTool } from "../tools/shell.ts";
2216 import { listSkillsTool, readSkillTool } from "../tools/skills.ts";
@@ -130,7 +124,7 @@ function withHooks<
130124 // ─── Tool registry ────────────────────────────────────────────────────────────
131125
132126 // Names of all local tools that support hooks (MCP tools are excluded).
133-const HOOKABLE_TOOLS = ["read", "create", "replace", "insert", "shell"];
127+const HOOKABLE_TOOLS = ["read", "create", "shell"];
134128
135129 export function buildToolSet(opts: {
136130 cwd: string;
@@ -166,7 +160,7 @@ export function buildToolSet(opts: {
166160 ) as ToolDef,
167161 withCwdDefault(listSkillsTool as ToolDef, cwd),
168162 withCwdDefault(readSkillTool as ToolDef, cwd),
169- // Write: create/overwrite, replace/delete, insert
163+ // Write: create/overwrite only. Targeted edits go through shell + mc-edit.
170164 withHooks(
171165 withCwdDefault(
172166 createTool as ToolDef,
@@ -180,32 +174,6 @@ export function buildToolSet(opts: {
180174 finalizeWriteResult,
181175 onBeforeHook,
182176 ) as ToolDef,
183- withHooks(
184- withCwdDefault(
185- replaceTool as ToolDef,
186- cwd,
187- opts.snapshotCallback,
188- ) as ToolDef<{ cwd?: string }, ReplaceToolOutput>,
189- lookupHook,
190- cwd,
191- (result) => hookEnvForReplace(result, cwd),
192- onHook,
193- finalizeWriteResult,
194- onBeforeHook,
195- ) as ToolDef,
196- withHooks(
197- withCwdDefault(
198- insertTool as ToolDef,
199- cwd,
200- opts.snapshotCallback,
201- ) as ToolDef<{ cwd?: string }, InsertToolOutput>,
202- lookupHook,
203- cwd,
204- (result) => hookEnvForInsert(result, cwd),
205- onHook,
206- finalizeWriteResult,
207- onBeforeHook,
208- ) as ToolDef,
209177 // Shell and subagent
210178 withHooks(
211179 (onShellOutput
src/cli/tool-render.ts+1−15
@@ -9,8 +9,7 @@ const HOME = homedir();
99
1010 function toolGlyph(name: string): string {
1111 if (name === "read") return G.read;
12- if (name === "create" || name === "replace" || name === "insert")
13- return G.write;
12+ if (name === "create") return G.write;
1413 if (name === "shell") return G.run;
1514 if (name === "subagent") return G.agent;
1615 if (name.startsWith("mcp_")) return G.mcp;
@@ -44,19 +43,6 @@ export function buildToolCallLine(name: string, args: unknown): string {
4443 return `${G.write} ${c.dim("create")} ${c.bold(String(a.path ?? ""))}`;
4544 }
4645
47- if (name === "replace") {
48- const range = a.endAnchor
49- ? c.dim(` ${a.startAnchor}–${a.endAnchor}`)
50- : c.dim(` ${a.startAnchor}`);
51- const verb =
52- a.newContent === undefined || a.newContent === "" ? "delete" : "replace";
53- return `${G.write} ${c.dim(verb)} ${c.bold(String(a.path ?? ""))}${range}`;
54- }
55-
56- if (name === "insert") {
57- return `${G.write} ${c.dim(`insert ${a.position ?? ""}`)} ${c.bold(String(a.path ?? ""))}${c.dim(` @ ${a.anchor}`)}`;
58- }
59-
6046 if (name === "shell") {
6147 const cmd = String(a.command ?? "").trim();
6248 if (!cmd) return `${G.run} ${c.dim("shell")}`;
src/cli/tool-result-renderers.ts+0−15
@@ -89,19 +89,6 @@ function renderCreateResult(result: unknown): boolean {
8989 return true;
9090 }
9191
92-function renderReplaceOrInsertResult(
93- toolName: string,
94- result: unknown,
95-): boolean {
96- const r = result as { path: string; diff: string; deleted?: boolean };
97- if (!r || typeof r.path !== "string") return false;
98- const verb =
99- toolName === "insert" ? "inserted" : r.deleted ? "deleted" : "replaced";
100- writeln(` ${G.ok} ${c.dim(verb)} ${r.path}`);
101- renderDiff(r.diff);
102- return true;
103-}
104-
10592 function renderShellResult(result: unknown): boolean {
10693 const r = result as {
10794 stdout: string;
@@ -293,8 +280,6 @@ function renderMcpResult(result: unknown): boolean {
293280 const TOOL_RESULT_RENDERERS: Readonly<Record<string, ToolResultRenderer>> = {
294281 read: renderReadResult,
295282 create: renderCreateResult,
296- replace: (result) => renderReplaceOrInsertResult("replace", result),
297- insert: (result) => renderReplaceOrInsertResult("insert", result),
298283 shell: renderShellResult,
299284 subagent: renderSubagentResult,
300285 readSkill: renderReadSkillResult,
src/tools/create.ts+1−1
@@ -26,7 +26,7 @@ export const createTool: ToolDef<CreateInput, CreateToolOutput> = {
2626 name: "create",
2727 description:
2828 "Write a file at the given path, creating it or fully replacing its content. " +
29- "**For targeted line edits on existing files use `replace` or `insert` — never `create`.**",
29+ "**For partial edits to existing files, prefer the `shell` tool with `mc-edit` instead of `create`.**",
3030 schema: CreateSchema,
3131 execute: async (input) => {
3232 const { filePath, relPath } = resolvePath(input.cwd, input.path);
src/tools/hooks.test.ts+6−6
@@ -41,11 +41,11 @@ describe("createHookCache", () => {
4141 it("returns null when the hook file exists but is not executable", () => {
4242 const hooksDir = join(tmpDir, ".agents", "hooks");
4343 mkdirSync(hooksDir, { recursive: true });
44- writeFileSync(join(hooksDir, "post-replace"), "#!/bin/bash\necho hi", {
44+ writeFileSync(join(hooksDir, "post-shell"), "#!/bin/bash\necho hi", {
4545 mode: 0o644,
4646 });
47- const lookup = createHookCache(["replace"], tmpDir);
48- expect(lookup("replace")).toBeNull();
47+ const lookup = createHookCache(["shell"], tmpDir);
48+ expect(lookup("shell")).toBeNull();
4949 });
5050
5151 it("returns null for an unknown tool name not in the cache", () => {
@@ -73,8 +73,8 @@ describe("runHook", () => {
7373 });
7474
7575 it("returns false when the script exits non-zero", async () => {
76- const script = makeHook(tmpDir, "post-replace", "#!/bin/bash\nexit 1");
77- await expect(runHook(script, { TOOL: "replace" }, tmpDir)).resolves.toBe(
76+ const script = makeHook(tmpDir, "post-shell", "#!/bin/bash\nexit 1");
77+ await expect(runHook(script, { TOOL: "shell" }, tmpDir)).resolves.toBe(
7878 false,
7979 );
8080 });
@@ -88,7 +88,7 @@ describe("runHook", () => {
8888 const outFile = join(tmpDir, "out.txt");
8989 const script = makeHook(
9090 tmpDir,
91- "post-insert",
91+ "post-create",
9292 `#!/bin/bash\necho "$FILEPATH" > "${outFile}"`,
9393 );
9494 await runHook(script, { FILEPATH: "src/foo.ts" }, tmpDir);
src/tools/hooks.ts+4−28
@@ -1,6 +1,7 @@
11 import { accessSync, constants } from "node:fs";
22 import { homedir } from "node:os";
33 import { join } from "node:path";
4+import { resolvePath } from "../internal/file-edit/path.ts";
45 import { generateDiff } from "./diff.ts";
56 import type { WriteResultMeta } from "./write-result.ts";
67
@@ -72,7 +73,7 @@ export async function runHook(
7273 // ─── Env builders (one per tool) ─────────────────────────────────────────────
7374
7475 // Accept WriteResultMeta so diff is computed here (only when a hook fires)
75-// instead of being pre-computed and then discarded in applyFileEdit.
76+// instead of being pre-computed and then discarded in the write tool.
7677 type WriteResult = WriteResultMeta & { path: string };
7778
7879 export function hookEnvForCreate(
@@ -81,38 +82,13 @@ export function hookEnvForCreate(
8182 ): Record<string, string> {
8283 return {
8384 TOOL: "create",
84- FILEPATH: result.path,
85+ FILEPATH: result._filePath,
8586 DIFF: generateDiff(result.path, result._before, result._updated),
8687 CREATED: String(result.created),
8788 CWD: cwd,
8889 };
8990 }
9091
91-export function hookEnvForReplace(
92- result: WriteResult & { deleted: boolean },
93- cwd: string,
94-): Record<string, string> {
95- return {
96- TOOL: "replace",
97- FILEPATH: result.path,
98- DIFF: generateDiff(result.path, result._before, result._updated),
99- DELETED: String(result.deleted),
100- CWD: cwd,
101- };
102-}
103-
104-export function hookEnvForInsert(
105- result: WriteResult,
106- cwd: string,
107-): Record<string, string> {
108- return {
109- TOOL: "insert",
110- FILEPATH: result.path,
111- DIFF: generateDiff(result.path, result._before, result._updated),
112- CWD: cwd,
113- };
114-}
115-
11692 export function hookEnvForShell(
11793 result: {
11894 stdout: string;
@@ -140,7 +116,7 @@ export function hookEnvForRead(
140116 ): Record<string, string> {
141117 return {
142118 TOOL: "read",
143- FILEPATH: input.path,
119+ FILEPATH: resolvePath(cwd, input.path).filePath,
144120 CWD: cwd,
145121 };
146122 }
src/tools/insert.test.ts+0−169
@@ -1,169 +0,0 @@
1-import { afterEach, beforeEach, describe, expect, test } from "bun:test";
2-import { insertTool } from "./insert.ts";
3-import { createTestHelpers, registerAnchorErrorTests } from "./test-helpers.ts";
4-import { stripWriteResultMeta } from "./write-result.ts";
5-
6-const { setup, teardown, write, read, anchor, getDir } = createTestHelpers();
7-// diff is deferred; strip meta before asserting on public fields.
8-const execute = async (...args: Parameters<typeof insertTool.execute>) =>
9- stripWriteResultMeta(await insertTool.execute(...args));
10-
11-// ---------------------------------------------------------------------------
12-// Setup / teardown
13-// ---------------------------------------------------------------------------
14-
15-beforeEach(async () => {
16- await setup("mc-insert-test-");
17-});
18-
19-afterEach(async () => {
20- await teardown();
21-});
22-
23-// ---------------------------------------------------------------------------
24-// Tests
25-// ---------------------------------------------------------------------------
26-
27-describe("insertTool", () => {
28- test("inserts a single line after the anchor", async () => {
29- const name = await write("f.txt", "a\nb\nc\n");
30- const result = await execute({
31- path: name,
32- cwd: getDir(),
33- anchor: anchor(1, "a"),
34- position: "after",
35- content: "X",
36- });
37-
38- expect(await read(name)).toBe("a\nX\nb\nc\n");
39- expect(result.diff).toContain("+X");
40- // anchor line itself must not appear as changed
41- expect(result.diff).not.toContain("-a");
42- });
43-
44- test("inserts a single line before the anchor", async () => {
45- const name = await write("f.txt", "a\nb\nc\n");
46- const result = await execute({
47- path: name,
48- cwd: getDir(),
49- anchor: anchor(2, "b"),
50- position: "before",
51- content: "X",
52- });
53-
54- expect(await read(name)).toBe("a\nX\nb\nc\n");
55- expect(result.diff).toContain("+X");
56- expect(result.diff).not.toContain("-b");
57- });
58-
59- test("inserts multiple lines", async () => {
60- const name = await write("f.txt", "a\nb\n");
61- await execute({
62- path: name,
63- cwd: getDir(),
64- anchor: anchor(1, "a"),
65- position: "after",
66- content: "X\nY\nZ",
67- });
68-
69- expect(await read(name)).toBe("a\nX\nY\nZ\nb\n");
70- });
71-
72- test("inserts before the first line", async () => {
73- const name = await write("f.txt", "a\nb\n");
74- await execute({
75- path: name,
76- cwd: getDir(),
77- anchor: anchor(1, "a"),
78- position: "before",
79- content: "FIRST",
80- });
81-
82- expect(await read(name)).toBe("FIRST\na\nb\n");
83- });
84-
85- test("inserts after the last line", async () => {
86- const name = await write("f.txt", "a\nb\n");
87- await execute({
88- path: name,
89- cwd: getDir(),
90- anchor: anchor(2, "b"),
91- position: "after",
92- content: "LAST",
93- });
94-
95- expect(await read(name)).toBe("a\nb\nLAST\n");
96- });
97-
98- test("returns path relative to cwd", async () => {
99- const name = await write("f.txt", "a\nb\n");
100- const result = await execute({
101- path: name,
102- cwd: getDir(),
103- anchor: anchor(1, "a"),
104- position: "after",
105- content: "X",
106- });
107-
108- expect(result.path).toBe(name);
109- });
110-
111- test("diff contains only added lines, no removals", async () => {
112- const name = await write("f.txt", "a\nb\nc\n");
113- const result = await execute({
114- path: name,
115- cwd: getDir(),
116- anchor: anchor(2, "b"),
117- position: "after",
118- content: "NEW",
119- });
120-
121- expect(result.diff).toContain("+NEW");
122- expect(result.diff).not.toMatch(/^-[^-]/m);
123- });
124-
125- registerAnchorErrorTests({
126- missingFileCall: (a) =>
127- execute({
128- path: "missing.txt",
129- cwd: getDir(),
130- anchor: a,
131- position: "after",
132- content: "X",
133- }),
134- badAnchorCall: (name, a) =>
135- execute({
136- path: name,
137- cwd: getDir(),
138- anchor: a, // wrong hash for "b"
139- position: "after",
140- content: "X",
141- }),
142- write,
143- });
144-
145- test("throws on malformed anchor format", async () => {
146- const name = await write("f.txt", "a\n");
147- await expect(
148- execute({
149- path: name,
150- cwd: getDir(),
151- anchor: "not-an-anchor",
152- position: "before",
153- content: "X",
154- }),
155- ).rejects.toThrow("Invalid anchor");
156- });
157- test("accepts anchor with trailing pipe separator", async () => {
158- const name = await write("f.txt", "a\nb\nc\n");
159- await execute({
160- path: name,
161- cwd: getDir(),
162- anchor: `${anchor(2, "b")}|`,
163- position: "after",
164- content: "X",
165- });
166-
167- expect(await read(name)).toBe("a\nb\nX\nc\n");
168- });
169-});
src/tools/insert.ts+0−70
@@ -1,70 +0,0 @@
1-import { z } from "zod";
2-import type { ToolDef } from "../llm-api/types.ts";
3-import { findLineByHash } from "./hashline.ts";
4-import { applyFileEdit, parseAnchor, resolveExistingFile } from "./shared.ts";
5-import type { WriteResultMeta } from "./write-result.ts";
6-
7-const InsertSchema = z.object({
8- path: z.string().describe("File path to edit (absolute or relative to cwd)"),
9- anchor: z.string().describe('Anchor line from a prior read, e.g. "11:a3"'),
10- position: z
11- .enum(["before", "after"])
12- .describe('Insert the content "before" or "after" the anchor line'),
13- content: z.string().describe("Text to insert"),
14-});
15-
16-type InsertInput = z.infer<typeof InsertSchema> & {
17- cwd?: string;
18- snapshotCallback?: (filePath: string) => Promise<void>;
19-};
20-
21-interface InsertOutput {
22- path: string;
23-}
24-
25-export interface InsertToolOutput extends InsertOutput, WriteResultMeta {}
26-
27-const HASH_NOT_FOUND_ERROR =
28- "Hash not found. Re-read the file to get current anchors.";
29-
30-export const insertTool: ToolDef<InsertInput, InsertToolOutput> = {
31- name: "insert",
32- description:
33- "Insert new lines before or after an anchor line in an existing file. " +
34- "The anchor line itself is not modified. " +
35- 'Anchors come from the `read` tool (format: "line:hash", e.g. "11:a3"). ' +
36- "To replace or delete lines use `replace`. To create a file use `create`.",
37- schema: InsertSchema,
38- execute: async (input) => {
39- const { file, filePath, relPath } = await resolveExistingFile(
40- input.cwd,
41- input.path,
42- );
43-
44- const parsed = parseAnchor(input.anchor);
45-
46- const original = await file.text();
47- const lines = original.split("\n");
48-
49- const anchorLine = findLineByHash(lines, parsed.hash, parsed.line);
50- if (!anchorLine) throw new Error(HASH_NOT_FOUND_ERROR);
51-
52- const insertAt = input.position === "before" ? anchorLine - 1 : anchorLine;
53- const insertLines = input.content.split("\n");
54-
55- const updatedLines = [
56- ...lines.slice(0, insertAt),
57- ...insertLines,
58- ...lines.slice(insertAt),
59- ];
60-
61- const updated = updatedLines.join("\n");
62- return applyFileEdit(
63- input.snapshotCallback,
64- filePath,
65- relPath,
66- original,
67- updated,
68- );
69- },
70-};
src/tools/replace.test.ts+0−151
@@ -1,151 +0,0 @@
1-import { afterEach, beforeEach, describe, expect, test } from "bun:test";
2-import { replaceTool } from "./replace.ts";
3-import { createTestHelpers, registerAnchorErrorTests } from "./test-helpers.ts";
4-import { stripWriteResultMeta } from "./write-result.ts";
5-
6-const { setup, teardown, write, read, anchor, getDir } = createTestHelpers();
7-// diff is deferred; strip meta before asserting on public fields.
8-const execute = async (...args: Parameters<typeof replaceTool.execute>) =>
9- stripWriteResultMeta(await replaceTool.execute(...args));
10-
11-// ---------------------------------------------------------------------------
12-// Setup / teardown
13-// ---------------------------------------------------------------------------
14-
15-beforeEach(async () => {
16- await setup("mc-replace-test-");
17-});
18-
19-afterEach(async () => {
20- await teardown();
21-});
22-
23-// ---------------------------------------------------------------------------
24-// Tests
25-// ---------------------------------------------------------------------------
26-
27-describe("replaceTool", () => {
28- test("replaces a single line", async () => {
29- const name = await write("f.txt", "a\nb\nc\n");
30- const result = await execute({
31- path: name,
32- cwd: getDir(),
33- startAnchor: anchor(2, "b"),
34- newContent: "B",
35- });
36-
37- expect(await read(name)).toBe("a\nB\nc\n");
38- expect(result.diff).toContain("-b");
39- expect(result.diff).toContain("+B");
40- });
41-
42- test("replaces a range of lines", async () => {
43- const name = await write("f.txt", "a\nb\nc\nd\ne\n");
44- const result = await execute({
45- path: name,
46- cwd: getDir(),
47- startAnchor: anchor(2, "b"),
48- endAnchor: anchor(4, "d"),
49- newContent: "X\nY",
50- });
51-
52- expect(await read(name)).toBe("a\nX\nY\ne\n");
53- expect(result.diff).toContain("-b");
54- expect(result.diff).toContain("-c");
55- expect(result.diff).toContain("-d");
56- expect(result.diff).toContain("+X");
57- expect(result.diff).toContain("+Y");
58- });
59-
60- test("deletes a single line when newContent is omitted", async () => {
61- const name = await write("f.txt", "a\nb\nc\n");
62- const result = await execute({
63- path: name,
64- cwd: getDir(),
65- startAnchor: anchor(2, "b"),
66- });
67-
68- expect(await read(name)).toBe("a\nc\n");
69- expect(result.diff).toContain("-b");
70- expect(result.diff).not.toMatch(/^\+[^+]/m);
71- });
72-
73- test("deletes a range when newContent is empty string", async () => {
74- const name = await write("f.txt", "a\nb\nc\nd\n");
75- await execute({
76- path: name,
77- cwd: getDir(),
78- startAnchor: anchor(2, "b"),
79- endAnchor: anchor(3, "c"),
80- newContent: "",
81- });
82-
83- expect(await read(name)).toBe("a\nd\n");
84- });
85-
86- test("returns (no changes) diff when replacement is identical to original", async () => {
87- const name = await write("f.txt", "a\nb\nc\n");
88- const result = await execute({
89- path: name,
90- cwd: getDir(),
91- startAnchor: anchor(2, "b"),
92- newContent: "b",
93- });
94-
95- expect(result.diff).toBe("(no changes)");
96- });
97-
98- test("returns path relative to cwd", async () => {
99- const name = await write("f.txt", "a\nb\n");
100- const result = await execute({
101- path: name,
102- cwd: getDir(),
103- startAnchor: anchor(1, "a"),
104- newContent: "A",
105- });
106-
107- expect(result.path).toBe(name);
108- });
109-
110- registerAnchorErrorTests({
111- missingFileCall: (a) =>
112- execute({ path: "missing.txt", cwd: getDir(), startAnchor: a }),
113- badAnchorCall: (name, a) =>
114- execute({ path: name, cwd: getDir(), startAnchor: a }), // wrong hash for "b"
115- write,
116- });
117-
118- test("throws when endAnchor is before startAnchor", async () => {
119- const name = await write("f.txt", "a\nb\nc\n");
120- await expect(
121- execute({
122- path: name,
123- cwd: getDir(),
124- startAnchor: anchor(3, "c"),
125- endAnchor: anchor(1, "a"),
126- }),
127- ).rejects.toThrow();
128- });
129-
130- test("throws on malformed anchor format", async () => {
131- const name = await write("f.txt", "a\n");
132- await expect(
133- execute({
134- path: name,
135- cwd: getDir(),
136- startAnchor: "not-an-anchor",
137- }),
138- ).rejects.toThrow("Invalid startAnchor");
139- });
140- test("accepts anchors with trailing pipe separator", async () => {
141- const name = await write("f.txt", "a\nb\nc\n");
142- await execute({
143- path: name,
144- cwd: getDir(),
145- startAnchor: `${anchor(2, "b")}|`,
146- newContent: "B",
147- });
148-
149- expect(await read(name)).toBe("a\nB\nc\n");
150- });
151-});
src/tools/replace.ts+0−106
@@ -1,106 +0,0 @@
1-import { z } from "zod";
2-import type { ToolDef } from "../llm-api/types.ts";
3-import { findLineByHash } from "./hashline.ts";
4-import { applyFileEdit, parseAnchor, resolveExistingFile } from "./shared.ts";
5-import type { WriteResultMeta } from "./write-result.ts";
6-
7-const ReplaceSchema = z.object({
8- path: z.string().describe("File path to edit (absolute or relative to cwd)"),
9- startAnchor: z
10- .string()
11- .describe('Start anchor from a prior read, e.g. "11:a3"'),
12- endAnchor: z
13- .string()
14- .optional()
15- .describe(
16- 'End anchor (inclusive), e.g. "33:0e". Omit to target only the startAnchor line.',
17- ),
18- newContent: z
19- .string()
20- .optional()
21- .describe(
22- "Replacement text. Omit or pass empty string to delete the range.",
23- ),
24-});
25-
26-type ReplaceInput = z.infer<typeof ReplaceSchema> & {
27- cwd?: string;
28- snapshotCallback?: (filePath: string) => Promise<void>;
29-};
30-
31-interface ReplaceOutput {
32- path: string;
33- deleted: boolean;
34-}
35-
36-export interface ReplaceToolOutput extends ReplaceOutput, WriteResultMeta {}
37-
38-const HASH_NOT_FOUND_ERROR =
39- "Hash not found. Re-read the file to get current anchors.";
40-
41-export const replaceTool: ToolDef<ReplaceInput, ReplaceToolOutput> = {
42- name: "replace",
43- description:
44- "Replace or delete a range of lines in an existing file using hashline anchors. " +
45- 'Anchors come from the `read` tool (format: "line:hash", e.g. "11:a3"). ' +
46- "Provide startAnchor alone to target a single line, or add endAnchor for a range. " +
47- "Set newContent to the replacement text, or omit it to delete the range. " +
48- "To create a file use `create`. To insert without replacing any lines use `insert`.",
49- schema: ReplaceSchema,
50- execute: async (input) => {
51- const { file, filePath, relPath } = await resolveExistingFile(
52- input.cwd,
53- input.path,
54- );
55- const start = parseAnchor(input.startAnchor, "startAnchor");
56- const end = input.endAnchor
57- ? parseAnchor(input.endAnchor, "endAnchor")
58- : null;
59-
60- if (end && end.line < start.line) {
61- throw new Error(
62- "endAnchor line number must be >= startAnchor line number.",
63- );
64- }
65-
66- const original = await file.text();
67- const lines = original.split("\n");
68-
69- const startLine = findLineByHash(lines, start.hash, start.line);
70- if (!startLine) throw new Error(HASH_NOT_FOUND_ERROR);
71-
72- let endLine = startLine;
73- if (end) {
74- const resolvedEnd = findLineByHash(lines, end.hash, end.line);
75- if (!resolvedEnd) throw new Error(HASH_NOT_FOUND_ERROR);
76- endLine = resolvedEnd;
77- }
78- if (endLine < startLine) {
79- throw new Error("endAnchor resolves before startAnchor.");
80- }
81-
82- const replacement =
83- input.newContent === undefined || input.newContent === ""
84- ? []
85- : input.newContent.split("\n");
86-
87- const updatedLines = [
88- ...lines.slice(0, startLine - 1),
89- ...replacement,
90- ...lines.slice(endLine),
91- ];
92-
93- const updated = updatedLines.join("\n");
94- const editResult = await applyFileEdit(
95- input.snapshotCallback,
96- filePath,
97- relPath,
98- original,
99- updated,
100- );
101- return {
102- ...editResult,
103- deleted: replacement.length === 0,
104- };
105- },
106-};
src/tools/shared.ts+0−65
@@ -1,68 +1,3 @@
11 import { resolvePath } from "../internal/file-edit/path.ts";
22
33 export { resolvePath };
4-
5-export async function resolveExistingFile(
6- cwdInput: string | undefined,
7- pathInput: string,
8-) {
9- const { cwd, filePath, relPath } = resolvePath(cwdInput, pathInput);
10- const file = Bun.file(filePath);
11- if (!(await file.exists())) {
12- throw new Error(
13- `File not found: "${relPath}". To create a new file use the \`create\` tool.`,
14- );
15- }
16- return { file, filePath, relPath, cwd };
17-}
18-
19-interface ParsedAnchor {
20- line: number;
21- hash: string;
22-}
23-
24-export function parseAnchor(value: string, name = "anchor"): ParsedAnchor {
25- const normalized = value.trim().endsWith("|")
26- ? value.trim().slice(0, -1)
27- : value;
28- const match = /^\s*(\d+):([0-9a-fA-F]{2})\s*$/.exec(normalized);
29- if (!match) {
30- throw new Error(
31- `Invalid ${name}. Expected format: "line:hh" (e.g. "11:a3").`,
32- );
33- }
34-
35- const line = Number(match[1]);
36- if (!Number.isInteger(line) || line < 1) {
37- throw new Error(`Invalid ${name} line number.`);
38- }
39-
40- const hash = match[2];
41- if (!hash) {
42- throw new Error(
43- `Invalid ${name}. Expected format: "line:hh" (e.g. "11:a3").`,
44- );
45- }
46-
47- return { line, hash: hash.toLowerCase() };
48-}
49-
50-export async function applyFileEdit(
51- snapshotCallback: ((filePath: string) => Promise<void>) | undefined,
52- filePath: string,
53- relPath: string,
54- original: string,
55- updated: string,
56-) {
57- await snapshotCallback?.(filePath);
58- await Bun.write(filePath, updated);
59-
60- // diff deferred to finalizeWriteResult (hook path) or stripWriteResultMeta
61- // (no-hook path) to avoid computing it twice on every write in repos with hooks.
62- return {
63- path: relPath,
64- _filePath: filePath,
65- _before: original,
66- _updated: updated,
67- };
68-}
src/tools/shell.ts+1−1
@@ -39,7 +39,7 @@ export const shellTool: ToolDef<ShellInput, ShellOutput> = {
3939 name: "shell",
4040 description:
4141 "Execute a shell command. Returns stdout, stderr, and exit code. " +
42- "Use this for running tests, builds, git commands, and other CLI operations. " +
42+ "Use this for reading/searching code, running tests, builds, git commands, and invoking `mc-edit` for partial file edits. " +
4343 "Prefer non-interactive commands. Avoid commands that run indefinitely.",
4444 schema: ShellSchema,
4545 execute: async (input) => {
src/tools/snapshot.ts+2−2
@@ -1,8 +1,8 @@
11 /**
22 * SQLite-based turn snapshots for /undo.
33 *
4- * Before an agent makes a file modification (create, replace, insert),
5- * we hook in to snapshot the exact state of that file on disk.
4+ * Before an agent makes a tool-managed file modification, we snapshot the
5+ * exact state of that file on disk.
66 *
77 * On /undo, we restore those files from the DB and clean up the snapshot rows.
88 */
src/tools/test-helpers.ts+0−62
@@ -1,62 +0,0 @@
1-import { expect, test } from "bun:test";
2-import { mkdtemp, rm, writeFile } from "node:fs/promises";
3-import { tmpdir } from "node:os";
4-import { join } from "node:path";
5-import { hashLine } from "./hashline.ts";
6-
7-export function createTestHelpers() {
8- let dir = "";
9-
10- async function setup(prefix: string) {
11- dir = await mkdtemp(join(tmpdir(), prefix));
Cut short: this commit's diff is over 1000 lines.