xonecas.io
64875
Mc

mini-coder / commit 3851567

Fix write diffs after tool hooks

xonecas2026-03-11 3851567c0698cdad5353cebaa309b645c68f147b parent fdcd3a5

6 files changed

src/agent/tools.test.ts+103−0
@@ -0,0 +1,103 @@
1+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
2+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
3+import { tmpdir } from "node:os";
4+import { join } from "node:path";
5+import { hashLine } from "../tools/hashline.ts";
6+import { buildToolSet } from "./tools.ts";
7+
8+let cwd = "";
9+
10+beforeEach(() => {
11+ cwd = mkdtempSync(join(tmpdir(), "agent-tools-test-"));
12+});
13+
14+afterEach(() => {
15+ rmSync(cwd, { recursive: true, force: true });
16+});
17+
18+function makeHook(toolName: string, body: string): void {
19+ const hooksDir = join(cwd, ".agents", "hooks");
20+ mkdirSync(hooksDir, { recursive: true });
21+ writeFileSync(join(hooksDir, `post-${toolName}`), body, { mode: 0o755 });
22+}
23+
24+function getTool(name: string) {
25+ const tool = buildToolSet({
26+ cwd,
27+ runSubagent: async () => {
28+ throw new Error("subagent should not run in this test");
29+ },
30+ onHook: () => {},
31+ availableAgents: new Map(),
32+ }).find((candidate) => candidate.name === name);
33+ if (!tool) throw new Error(`Tool not found: ${name}`);
34+ return tool;
35+}
36+
37+describe("buildToolSet write hooks", () => {
38+ test("create returns a diff for the post-hook file state", async () => {
39+ makeHook("create", '#!/bin/bash\nprintf "formatted\\n" > "$FILEPATH"\n');
40+
41+ const result = await getTool("create").execute({
42+ path: "f.txt",
43+ content: "draft\n",
44+ });
45+
46+ expect(await Bun.file(join(cwd, "f.txt")).text()).toBe("formatted\n");
47+ expect(result).toMatchObject({ path: "f.txt", created: true });
48+ expect(result).not.toHaveProperty("_before");
49+ expect(result).not.toHaveProperty("_filePath");
50+ expect((result as { diff: string }).diff).toContain("+formatted");
51+ expect((result as { diff: string }).diff).not.toContain("+draft");
52+ });
53+
54+ test("replace returns a diff for hook-mutated file contents", async () => {
55+ writeFileSync(join(cwd, "f.txt"), "a\nb\n");
56+ makeHook(
57+ "replace",
58+ '#!/bin/bash\nprintf "a\\nB\\nformatted\\n" > "$FILEPATH"\n',
59+ );
60+
61+ const result = await getTool("replace").execute({
62+ path: "f.txt",
63+ startAnchor: `2:${hashLine("b")}`,
64+ newContent: "B",
65+ });
66+
67+ expect(await Bun.file(join(cwd, "f.txt")).text()).toBe("a\nB\nformatted\n");
68+ expect((result as { diff: string }).diff).toContain("+formatted");
69+ expect((result as { diff: string }).diff).not.toBe("(no changes)");
70+ });
71+
72+ test("insert returns a diff for hook-mutated file contents", async () => {
73+ writeFileSync(join(cwd, "f.txt"), "a\nb\n");
74+ makeHook(
75+ "insert",
76+ '#!/bin/bash\nprintf "a\\nnew\\nb\\nformatted\\n" > "$FILEPATH"\n',
77+ );
78+
79+ const result = await getTool("insert").execute({
80+ path: "f.txt",
81+ anchor: `1:${hashLine("a")}`,
82+ position: "after",
83+ content: "new",
84+ });
85+
86+ expect(await Bun.file(join(cwd, "f.txt")).text()).toBe(
87+ "a\nnew\nb\nformatted\n",
88+ );
89+ expect((result as { diff: string }).diff).toContain("+formatted");
90+ expect((result as { diff: string }).diff).not.toMatch(/^-b$/m);
91+ });
92+
93+ test("write tools still return the expected diff when no hook exists", async () => {
94+ const result = await getTool("create").execute({
95+ path: "plain.txt",
96+ content: "plain\n",
97+ });
98+
99+ expect(await Bun.file(join(cwd, "plain.txt")).text()).toBe("plain\n");
100+ expect((result as { diff: string }).diff).toContain("+plain");
101+ expect(result).not.toHaveProperty("_before");
102+ });
103+});
src/agent/tools.ts+32−9
@@ -1,5 +1,5 @@
11 import type { ToolDef } from "../llm-api/types.ts";
2-import type { CreateOutput } from "../tools/create.ts";
2+import type { CreateToolOutput } from "../tools/create.ts";
33 import { createTool } from "../tools/create.ts";
44 import { webContentTool, webSearchTool } from "../tools/exa.ts";
55 import type { GlobOutput } from "../tools/glob.ts";
@@ -17,11 +17,11 @@ import {
1717 hookEnvForShell,
1818 runHook,
1919 } from "../tools/hooks.ts";
20-import type { InsertOutput } from "../tools/insert.ts";
20+import type { InsertToolOutput } from "../tools/insert.ts";
2121 import { insertTool } from "../tools/insert.ts";
2222 import type { ReadOutput } from "../tools/read.ts";
2323 import { readTool } from "../tools/read.ts";
24-import type { ReplaceOutput } from "../tools/replace.ts";
24+import type { ReplaceToolOutput } from "../tools/replace.ts";
2525 import { replaceTool } from "../tools/replace.ts";
2626 import type { ShellOutput } from "../tools/shell.ts";
2727 import { shellTool } from "../tools/shell.ts";
@@ -30,6 +30,10 @@ import {
3030 createSubagentTool,
3131 type SubagentOutput,
3232 } from "../tools/subagent.ts";
33+import {
34+ finalizeWriteResult,
35+ stripWriteResultMeta,
36+} from "../tools/write-result.ts";
3337
3438 // ─── Tool wrappers ────────────────────────────────────────────────────────────
3539
@@ -55,19 +59,28 @@ type EnvBuilder<TInput, TOutput> = (
5559 input: TInput,
5660 ) => Record<string, string>;
5761
62+type ResultFinalizer<TOutput, TFinalOutput> = (
63+ result: TOutput,
64+) => Promise<TFinalOutput>;
65+
5866 /**
5967 * Wrap a tool to fire its post-hook (if one exists) after each successful execute.
6068 * Hooks are looked up via the session-scoped cache — no filesystem access per call.
6169 * Errors are always swallowed. onHook is called with the result so the caller can
6270 * render a UI line.
6371 */
64-function withHooks<TInput extends { cwd?: string }, TOutput>(
72+function withHooks<
73+ TInput extends { cwd?: string },
74+ TOutput,
75+ TFinalOutput = TOutput,
76+>(
6577 tool: ToolDef<TInput, TOutput>,
6678 lookupHook: (toolName: string) => string | null,
6779 cwd: string,
6880 buildEnv: EnvBuilder<TInput, TOutput>,
6981 onHook: (toolName: string, scriptPath: string, success: boolean) => void,
70-): ToolDef<TInput, TOutput> {
82+ finalizeResult?: ResultFinalizer<TOutput, TFinalOutput>,
83+): ToolDef<TInput, TFinalOutput> {
7184 const originalExecute = tool.execute;
7285 return {
7386 ...tool,
@@ -78,8 +91,15 @@ function withHooks<TInput extends { cwd?: string }, TOutput>(
7891 const env = buildEnv(result, input);
7992 const success = await runHook(hookScript, env, cwd);
8093 onHook(tool.name, hookScript, success);
94+ if (finalizeResult) return finalizeResult(result);
95+ return result as TFinalOutput;
96+ }
97+ if (finalizeResult) {
98+ return stripWriteResultMeta(
99+ result as TOutput & { _filePath: string; _before: string },
100+ ) as TFinalOutput;
81101 }
82- return result;
102+ return result as TFinalOutput;
83103 },
84104 };
85105 }
@@ -149,32 +169,35 @@ export function buildToolSet(opts: {
149169 withHooks(
150170 withCwdDefault(createTool as ToolDef, cwd) as ToolDef<
151171 { cwd?: string },
152- CreateOutput
172+ CreateToolOutput
153173 >,
154174 lookupHook,
155175 cwd,
156176 (result) => hookEnvForCreate(result, cwd),
157177 onHook,
178+ finalizeWriteResult,
158179 ) as ToolDef,
159180 withHooks(
160181 withCwdDefault(replaceTool as ToolDef, cwd) as ToolDef<
161182 { cwd?: string },
162- ReplaceOutput
183+ ReplaceToolOutput
163184 >,
164185 lookupHook,
165186 cwd,
166187 (result) => hookEnvForReplace(result, cwd),
167188 onHook,
189+ finalizeWriteResult,
168190 ) as ToolDef,
169191 withHooks(
170192 withCwdDefault(insertTool as ToolDef, cwd) as ToolDef<
171193 { cwd?: string },
172- InsertOutput
194+ InsertToolOutput
173195 >,
174196 lookupHook,
175197 cwd,
176198 (result) => hookEnvForInsert(result, cwd),
177199 onHook,
200+ finalizeWriteResult,
178201 ) as ToolDef,
179202 // Shell and subagent
180203 withHooks(
src/tools/create.ts+12−3
@@ -4,6 +4,7 @@ import { z } from "zod";
44 import type { ToolDef } from "../llm-api/types.ts";
55 import { generateDiff } from "./diff.ts";
66 import { resolvePath } from "./shared.ts";
7+import type { WriteResultMeta } from "./write-result.ts";
78
89 const CreateSchema = z.object({
910 path: z.string().describe("File path to write (absolute or relative to cwd)"),
@@ -12,13 +13,15 @@ const CreateSchema = z.object({
1213
1314 type CreateInput = z.infer<typeof CreateSchema> & { cwd?: string };
1415
15-export interface CreateOutput {
16+interface CreateOutput {
1617 path: string;
1718 diff: string;
1819 created: boolean;
1920 }
2021
21-export const createTool: ToolDef<CreateInput, CreateOutput> = {
22+export interface CreateToolOutput extends CreateOutput, WriteResultMeta {}
23+
24+export const createTool: ToolDef<CreateInput, CreateToolOutput> = {
2225 name: "create",
2326 description:
2427 "Write a file at the given path, creating it or fully replacing its content. " +
@@ -37,6 +40,12 @@ export const createTool: ToolDef<CreateInput, CreateOutput> = {
3740 await Bun.write(filePath, input.content);
3841
3942 const diff = generateDiff(relPath, before, input.content);
40- return { path: relPath, diff, created };
43+ return {
44+ path: relPath,
45+ diff,
46+ created,
47+ _filePath: filePath,
48+ _before: before,
49+ };
4150 },
4251 };
src/tools/insert.ts+11−3
@@ -3,6 +3,7 @@ import type { ToolDef } from "../llm-api/types.ts";
33 import { generateDiff } from "./diff.ts";
44 import { findLineByHash } from "./hashline.ts";
55 import { parseAnchor, resolveExistingFile } from "./shared.ts";
6+import type { WriteResultMeta } from "./write-result.ts";
67
78 const InsertSchema = z.object({
89 path: z.string().describe("File path to edit (absolute or relative to cwd)"),
@@ -17,15 +18,17 @@ const InsertSchema = z.object({
1718
1819 type InsertInput = z.infer<typeof InsertSchema> & { cwd?: string };
1920
20-export interface InsertOutput {
21+interface InsertOutput {
2122 path: string;
2223 diff: string;
2324 }
2425
26+export interface InsertToolOutput extends InsertOutput, WriteResultMeta {}
27+
2528 const HASH_NOT_FOUND_ERROR =
2629 "Hash not found. Re-read the file to get current anchors.";
2730
28-export const insertTool: ToolDef<InsertInput, InsertOutput> = {
31+export const insertTool: ToolDef<InsertInput, InsertToolOutput> = {
2932 name: "insert",
3033 description:
3134 "Insert new lines before or after an anchor line in an existing file. " +
@@ -60,6 +63,11 @@ export const insertTool: ToolDef<InsertInput, InsertOutput> = {
6063 await Bun.write(filePath, updated);
6164
6265 const diff = generateDiff(relPath, original, updated);
63- return { path: relPath, diff };
66+ return {
67+ path: relPath,
68+ diff,
69+ _filePath: filePath,
70+ _before: original,
71+ };
6472 },
6573 };
src/tools/replace.ts+12−3
@@ -3,6 +3,7 @@ import type { ToolDef } from "../llm-api/types.ts";
33 import { generateDiff } from "./diff.ts";
44 import { findLineByHash } from "./hashline.ts";
55 import { parseAnchor, resolveExistingFile } from "./shared.ts";
6+import type { WriteResultMeta } from "./write-result.ts";
67
78 const ReplaceSchema = z.object({
89 path: z.string().describe("File path to edit (absolute or relative to cwd)"),
@@ -25,16 +26,18 @@ const ReplaceSchema = z.object({
2526
2627 type ReplaceInput = z.infer<typeof ReplaceSchema> & { cwd?: string };
2728
28-export interface ReplaceOutput {
29+interface ReplaceOutput {
2930 path: string;
3031 diff: string;
3132 deleted: boolean;
3233 }
3334
35+export interface ReplaceToolOutput extends ReplaceOutput, WriteResultMeta {}
36+
3437 const HASH_NOT_FOUND_ERROR =
3538 "Hash not found. Re-read the file to get current anchors.";
3639
37-export const replaceTool: ToolDef<ReplaceInput, ReplaceOutput> = {
40+export const replaceTool: ToolDef<ReplaceInput, ReplaceToolOutput> = {
3841 name: "replace",
3942 description:
4043 "Replace or delete a range of lines in an existing file using hashline anchors. " +
@@ -90,6 +93,12 @@ export const replaceTool: ToolDef<ReplaceInput, ReplaceOutput> = {
9093 await Bun.write(filePath, updated);
9194
9295 const diff = generateDiff(relPath, original, updated);
93- return { path: relPath, diff, deleted: replacement.length === 0 };
96+ return {
97+ path: relPath,
98+ diff,
99+ deleted: replacement.length === 0,
100+ _filePath: filePath,
101+ _before: original,
102+ };
94103 },
95104 };
src/tools/write-result.ts+30−0
@@ -0,0 +1,30 @@
1+import { generateDiff } from "./diff.ts";
2+
3+export interface WriteResultMeta {
4+ _filePath: string;
5+ _before: string;
6+}
7+
8+interface FinalizableWriteResult extends WriteResultMeta {
9+ path: string;
10+ diff: string;
11+}
12+
13+export function stripWriteResultMeta<T extends WriteResultMeta>(
14+ result: T,
15+): Omit<T, keyof WriteResultMeta> {
16+ const { _filePath, _before, ...publicResult } = result;
17+ return publicResult;
18+}
19+
20+export async function finalizeWriteResult<T extends FinalizableWriteResult>(
21+ result: T,
22+): Promise<Omit<T, keyof WriteResultMeta>> {
23+ const file = Bun.file(result._filePath);
24+ const after = (await file.exists()) ? await file.text() : "";
25+
26+ return {
27+ ...stripWriteResultMeta(result),
28+ diff: generateDiff(result.path, result._before, after),
29+ };
30+}