xonecas.io
64875
Mc

mini-coder / commit 1c45800

Refactor: Resolve remaining JSCPD code clones

- Extract common test workspace setup into `src/tools/test-helpers.ts`.
- Deduplicate test setup in `insert.test.ts` and `replace.test.ts`.
- Deduplicate `repoDir` and `sessionId` state in `snapshot.test.ts`.
- Use `processModelsList` for `fetchZenModels` and `fetchOllamaModels` in `src/llm-api/model-info.ts`.
- Include `ralph-jscpd.md` prompt definition.

xonecas2026-03-08 1c458006d468f3c4bca98b67230ad7f31dad0663 parent 65e50ca

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.

AGENTS.md+2−2
@@ -5,9 +5,9 @@
55 - README.md is cosmetic for users, don't edit unless asked to.
66 - Write minimal tests, focused on our code's logic. Never test dependencies. Never use mock servers or stubs.
77 - Keep the repo pristine: no failing tests, no lint, no build issues, no `nolint:` comments.
8-- Use `bun run knip && bun run typecheck && bun run format && bun run lint && bun test` to check your changes.
8+- Use `bun run jscpd && bun run knip && bun run typecheck && bun run format && bun run lint && bun test` to check your changes.
99 - We care about performance.
1010 - Don't worry about formatting issues, formatting happens automatically on mutations. (see .agents/hooks)
1111 - Do not inline `import` calls. Don't duplicate code. Don't leave dead code behind.
1212 - Don't make random test files, if you need to test something, write a propper unit test.
13-- If you make temp files, clean them up when you are done.
13+- If you make temp files, clean them up when you are done.
package.json+3−1
@@ -14,7 +14,8 @@
1414 "lint": "biome check src",
1515 "format": "biome format --write src",
1616 "knip": "knip",
17- "test": "bun test"
17+ "test": "bun test",
18+ "jscpd": "jscpd src"
1819 },
1920 "dependencies": {
2021 "@ai-sdk/anthropic": "^3.0.46",
@@ -31,6 +32,7 @@
3132 "devDependencies": {
3233 "@biomejs/biome": "^1.9.4",
3334 "@types/bun": "latest",
35+ "jscpd": "^4.0.8",
3436 "knip": "^5.86.0",
3537 "typescript": "^5.8.3"
3638 },
ralph-jscpd.md+21−0
@@ -0,0 +1,21 @@
1+# Agent Task: Resolve JSCPD Clones
2+
3+Your goal is to eliminate all code duplication reported by `jscpd` in the `src/` directory.
4+
5+## Instructions:
6+1. Run `bun run jscpd` to identify code clones.
7+2. Pick **one** duplication issue reported by the tool.
8+3. Refactor the code to eliminate the clone. This might involve:
9+ - Extracting shared logic into a common utility function.
10+ - Using loops or higher-order functions.
11+ - Abstracting classes or types.
12+4. Run `bun run knip && bun run typecheck && bun run format && bun run lint && bun test` to ensure your changes did not break the project.
13+5. If the tests or checks fail, fix them before moving on.
14+6. Re-run `bun run jscpd`.
15+7. Repeat steps 2-6 until `bun run jscpd` reports 0 clones.
16+8. When 0 clones are reported, state "All jscpd clones resolved." and finish the loop.
17+
18+**Important rules**:
19+- Keep your refactoring clean and targeted. Do not rewrite large chunks of unaffected code.
20+- Ensure you do not leave dead code behind.
21+- Respect existing project style and architecture.
src/cli/input.ts+24−21
@@ -276,29 +276,33 @@ export function pasteLabel(text: string): string {
276276 return `[pasted: "${preview}"${more}]`;
277277 }
278278
279-export function renderInputBuffer(
279+function processInputBuffer(
280280 buf: string,
281281 pasteTokens: ReadonlyMap<string, string>,
282+ replacer: (ch: string, pasted: string | undefined) => string,
282283 ): string {
283284 let out = "";
284285 for (let i = 0; i < buf.length; i++) {
285286 const ch = buf[i] ?? "";
286- const pasted = pasteTokens.get(ch);
287- out += pasted ? pasteLabel(pasted) : ch;
287+ out += replacer(ch, pasteTokens.get(ch));
288288 }
289289 return out;
290290 }
291291
292+export function renderInputBuffer(
293+ buf: string,
294+ pasteTokens: ReadonlyMap<string, string>,
295+): string {
296+ return processInputBuffer(buf, pasteTokens, (ch, pasted) =>
297+ pasted ? pasteLabel(pasted) : ch,
298+ );
299+}
300+
292301 export function expandInputBuffer(
293302 buf: string,
294303 pasteTokens: ReadonlyMap<string, string>,
295304 ): string {
296- let out = "";
297- for (let i = 0; i < buf.length; i++) {
298- const ch = buf[i] ?? "";
299- out += pasteTokens.get(ch) ?? ch;
300- }
301- return out;
305+ return processInputBuffer(buf, pasteTokens, (ch, pasted) => pasted ?? ch);
302306 }
303307
304308 export function pruneInputPasteTokens(
@@ -389,6 +393,15 @@ export async function readline(opts: {
389393 cursor += text.length;
390394 }
391395
396+ function deleteWordBackward(): void {
397+ const end = cursor;
398+ while (cursor > 0 && buf[cursor - 1] === " ") cursor--;
399+ while (cursor > 0 && buf[cursor - 1] !== " ") cursor--;
400+ buf = buf.slice(0, cursor) + buf.slice(end);
401+ prunePasteTokens();
402+ renderPrompt();
403+ }
404+
392405 function insertPasteToken(text: string): void {
393406 const token = createPasteToken(buf, pasteTokens);
394407 pasteTokens.set(token, text);
@@ -557,12 +570,7 @@ export async function readline(opts: {
557570 }
558571 // Alt+Backspace (delete word backward): ESC DEL
559572 if (raw === `${ESC}${BACKSPACE}`) {
560- const end = cursor;
561- while (cursor > 0 && buf[cursor - 1] === " ") cursor--;
562- while (cursor > 0 && buf[cursor - 1] !== " ") cursor--;
563- buf = buf.slice(0, cursor) + buf.slice(end);
564- prunePasteTokens();
565- renderPrompt();
573+ deleteWordBackward();
566574 continue;
567575 }
568576 if (raw === ESC) {
@@ -596,12 +604,7 @@ export async function readline(opts: {
596604
597605 if (raw === CTRL_W) {
598606 // Delete word before cursor
599- const end = cursor;
600- while (cursor > 0 && buf[cursor - 1] === " ") cursor--;
601- while (cursor > 0 && buf[cursor - 1] !== " ") cursor--;
602- buf = buf.slice(0, cursor) + buf.slice(end);
603- prunePasteTokens();
604- renderPrompt();
607+ deleteWordBackward();
605608 continue;
606609 }
607610
src/cli/tool-render.ts+30−31
@@ -129,6 +129,28 @@ function renderDiff(diff: string): void {
129129 }
130130 }
131131
132+function formatErrorBadge(result: unknown): string {
133+ const msg =
134+ typeof result === "string"
135+ ? result
136+ : result instanceof Error
137+ ? result.message
138+ : JSON.stringify(result);
139+ const oneLiner = msg.split("\n")[0] ?? msg;
140+ return `${G.err} ${c.red(oneLiner)}`;
141+}
142+
143+function formatShellBadge(r: {
144+ timedOut: boolean;
145+ success: boolean;
146+ exitCode: number;
147+}): string {
148+ return r.timedOut
149+ ? c.yellow("timeout")
150+ : r.success
151+ ? c.green(`✔ ${r.exitCode}`)
152+ : c.red(`✖ ${r.exitCode}`);
153+}
132154 function renderToolResultInline(
133155 toolName: string,
134156 result: unknown,
@@ -136,23 +158,16 @@ function renderToolResultInline(
136158 indent: string,
137159 ): void {
138160 if (isError) {
139- const msg =
140- typeof result === "string"
141- ? result
142- : result instanceof Error
143- ? result.message
144- : JSON.stringify(result);
145- const oneLiner = msg.split("\n")[0] ?? msg;
146- writeln(`${indent}${G.err} ${c.red(oneLiner)}`);
161+ writeln(`${indent}${formatErrorBadge(result)}`);
147162 return;
148163 }
149164
150165 if (toolName === "glob") {
151- const r = result as { files?: string[]; truncated?: boolean };
152- if (Array.isArray(r?.files)) {
153- const n = r.files.length;
166+ const res = result as { files?: string[]; truncated?: boolean };
167+ if (Array.isArray(res?.files)) {
168+ const n = res.files.length;
154169 writeln(
155- `${indent}${G.info} ${c.dim(n === 0 ? "no matches" : `${n} file${n === 1 ? "" : "s"}${r.truncated ? " (capped)" : ""}`)}`,
170+ `${indent}${G.info} ${c.dim(n === 0 ? "no matches" : `${n} file${n === 1 ? "" : "s"}${res.truncated ? " (capped)" : ""}`)}`,
156171 );
157172 return;
158173 }
@@ -198,11 +213,7 @@ function renderToolResultInline(
198213 success: boolean;
199214 timedOut: boolean;
200215 };
201- const badge = r.timedOut
202- ? c.yellow("timeout")
203- : r.success
204- ? c.green(`✔ ${r.exitCode}`)
205- : c.red(`✖ ${r.exitCode}`);
216+ const badge = formatShellBadge(r);
206217 writeln(`${indent}${badge}`);
207218 return;
208219 }
@@ -260,15 +271,7 @@ export function renderToolResult(
260271 isError: boolean,
261272 ): void {
262273 if (isError) {
263- const msg =
264- typeof result === "string"
265- ? result
266- : result instanceof Error
267- ? result.message
268- : JSON.stringify(result);
269- // Trim to one line for error summaries
270- const oneLiner = msg.split("\n")[0] ?? msg;
271- writeln(` ${G.err} ${c.red(oneLiner)}`);
274+ writeln(` ${formatErrorBadge(result)}`);
272275 return;
273276 }
274277
@@ -384,11 +387,7 @@ export function renderToolResult(
384387 timedOut: boolean;
385388 };
386389
387- const badge = r.timedOut
388- ? c.yellow("timeout")
389- : r.success
390- ? c.green(`✔ ${r.exitCode}`)
391- : c.red(`✖ ${r.exitCode}`);
390+ const badge = formatShellBadge(r);
392391
393392 writeln(` ${badge}`);
394393
src/llm-api/model-info.ts+45−59
@@ -428,32 +428,44 @@ async function fetchZenModels(): Promise<ProviderModelCandidate[] | null> {
428428 { headers: { Authorization: `Bearer ${key}` } },
429429 8_000,
430430 );
431- if (!isRecord(payload)) return null;
432- const data = payload.data;
433- if (!Array.isArray(data)) return null;
434- const out: ProviderModelCandidate[] = [];
435- for (const item of data) {
436- if (!isRecord(item) || typeof item.id !== "string") continue;
437- const modelId = normalizeModelId(item.id);
438- if (!modelId) continue;
431+ return processModelsList(payload, "data", "id", (item, modelId) => {
439432 const contextWindow =
440433 typeof item.context_window === "number" &&
441434 Number.isFinite(item.context_window)
442435 ? Math.max(0, Math.trunc(item.context_window))
443436 : null;
444- out.push({
437+ return {
445438 providerModelId: modelId,
446- displayName: item.id,
439+ displayName: item.id as string,
447440 contextWindow,
448441 free:
449- item.id.endsWith("-free") ||
442+ (item.id as string).endsWith("-free") ||
450443 item.id === "gpt-5-nano" ||
451444 item.id === "big-pickle",
452- });
445+ };
446+ });
447+}
448+
449+function processModelsList(
450+ payload: unknown,
451+ arrayKey: string,
452+ idKey: string,
453+ mapper: (
454+ item: Record<string, unknown>,
455+ modelId: string,
456+ ) => ProviderModelCandidate | null,
457+): ProviderModelCandidate[] | null {
458+ if (!isRecord(payload) || !Array.isArray(payload[arrayKey])) return null;
459+ const out: ProviderModelCandidate[] = [];
460+ for (const item of payload[arrayKey] as unknown[]) {
461+ if (!isRecord(item) || typeof item[idKey] !== "string") continue;
462+ const modelId = normalizeModelId(item[idKey] as string);
463+ if (!modelId) continue;
464+ const mapped = mapper(item as Record<string, unknown>, modelId);
465+ if (mapped) out.push(mapped);
453466 }
454467 return out;
455468 }
456-
457469 async function fetchOpenAIModels(): Promise<ProviderModelCandidate[] | null> {
458470 const key = process.env.OPENAI_API_KEY;
459471 if (!key) return null;
@@ -462,20 +474,12 @@ async function fetchOpenAIModels(): Promise<ProviderModelCandidate[] | null> {
462474 { headers: { Authorization: `Bearer ${key}` } },
463475 6_000,
464476 );
465- if (!isRecord(payload) || !Array.isArray(payload.data)) return null;
466- const out: ProviderModelCandidate[] = [];
467- for (const item of payload.data) {
468- if (!isRecord(item) || typeof item.id !== "string") continue;
469- const modelId = normalizeModelId(item.id);
470- if (!modelId) continue;
471- out.push({
472- providerModelId: modelId,
473- displayName: item.id,
474- contextWindow: null,
475- free: false,
476- });
477- }
478- return out;
477+ return processModelsList(payload, "data", "id", (item, modelId) => ({
478+ providerModelId: modelId,
479+ displayName: item.id as string,
480+ contextWindow: null,
481+ free: false,
482+ }));
479483 }
480484
481485 async function fetchAnthropicModels(): Promise<
@@ -493,25 +497,19 @@ async function fetchAnthropicModels(): Promise<
493497 },
494498 6_000,
495499 );
496- if (!isRecord(payload) || !Array.isArray(payload.data)) return null;
497- const out: ProviderModelCandidate[] = [];
498- for (const item of payload.data) {
499- if (!isRecord(item) || typeof item.id !== "string") continue;
500- const modelId = normalizeModelId(item.id);
501- if (!modelId) continue;
500+ return processModelsList(payload, "data", "id", (item, modelId) => {
502501 const displayName =
503502 typeof item.display_name === "string" &&
504503 item.display_name.trim().length > 0
505504 ? item.display_name
506- : item.id;
507- out.push({
505+ : (item.id as string);
506+ return {
508507 providerModelId: modelId,
509508 displayName,
510509 contextWindow: null,
511510 free: false,
512- });
513- }
514- return out;
511+ };
512+ });
515513 }
516514
517515 async function fetchGoogleModels(): Promise<ProviderModelCandidate[] | null> {
@@ -522,12 +520,7 @@ async function fetchGoogleModels(): Promise<ProviderModelCandidate[] | null> {
522520 {},
523521 6_000,
524522 );
525- if (!isRecord(payload) || !Array.isArray(payload.models)) return null;
526- const out: ProviderModelCandidate[] = [];
527- for (const item of payload.models) {
528- if (!isRecord(item) || typeof item.name !== "string") continue;
529- const modelId = normalizeModelId(item.name);
530- if (!modelId) continue;
523+ return processModelsList(payload, "models", "name", (item, modelId) => {
531524 const displayName =
532525 typeof item.displayName === "string" && item.displayName.trim().length > 0
533526 ? item.displayName
@@ -537,38 +530,31 @@ async function fetchGoogleModels(): Promise<ProviderModelCandidate[] | null> {
537530 Number.isFinite(item.inputTokenLimit)
538531 ? Math.max(0, Math.trunc(item.inputTokenLimit))
539532 : null;
540- out.push({
533+ return {
541534 providerModelId: modelId,
542535 displayName,
543536 contextWindow,
544537 free: false,
545- });
546- }
547- return out;
538+ };
539+ });
548540 }
549541
550542 async function fetchOllamaModels(): Promise<ProviderModelCandidate[] | null> {
551543 const base = process.env.OLLAMA_BASE_URL ?? "http://localhost:11434";
552544 const payload = await fetchJson(`${base}/api/tags`, {}, 3_000);
553- if (!isRecord(payload) || !Array.isArray(payload.models)) return null;
554- const out: ProviderModelCandidate[] = [];
555- for (const item of payload.models) {
556- if (!isRecord(item) || typeof item.name !== "string") continue;
557- const modelId = normalizeModelId(item.name);
558- if (!modelId) continue;
545+ return processModelsList(payload, "models", "name", (item, modelId) => {
559546 const details = item.details;
560547 let sizeSuffix = "";
561548 if (isRecord(details) && typeof details.parameter_size === "string") {
562549 sizeSuffix = ` (${details.parameter_size})`;
563550 }
564- out.push({
551+ return {
565552 providerModelId: modelId,
566- displayName: `${item.name}${sizeSuffix}`,
553+ displayName: `${item.name as string}${sizeSuffix}`,
567554 contextWindow: null,
568555 free: false,
569- });
570- }
571- return out;
556+ };
557+ });
572558 }
573559
574560 async function fetchProviderCandidates(
src/tools/create.ts+3−7
@@ -1,8 +1,9 @@
11 import { existsSync, mkdirSync } from "node:fs";
2-import { dirname, join, relative } from "node:path";
2+import { dirname } from "node:path";
33 import { z } from "zod";
44 import type { ToolDef } from "../llm-api/types.ts";
55 import { generateDiff } from "./diff.ts";
6+import { resolvePath } from "./shared.ts";
67
78 const CreateSchema = z.object({
89 path: z.string().describe("File path to write (absolute or relative to cwd)"),
@@ -25,12 +26,7 @@ export const createTool: ToolDef<CreateInput, CreateOutput> = {
2526 "For targeted line edits on existing files, **use `replace` or `insert` instead**.",
2627 schema: CreateSchema,
2728 execute: async (input) => {
28- const cwd = input.cwd ?? process.cwd();
29- const filePath = input.path.startsWith("/")
30- ? input.path
31- : join(cwd, input.path);
32-
33- const relPath = relative(cwd, filePath);
29+ const { filePath, relPath } = resolvePath(input.cwd, input.path);
3430
3531 const dir = dirname(filePath);
3632 if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
src/tools/exa.ts+33−50
@@ -5,6 +5,31 @@ const ExaSearchSchema = z.object({
55 query: z.string().describe("The search query"),
66 });
77
8+async function fetchExa(endpoint: string, body: unknown) {
9+ const apiKey = process.env.EXA_API_KEY;
10+ if (!apiKey) {
11+ throw new Error("EXA_API_KEY is not set.");
12+ }
13+
14+ const response = await fetch(`https://api.exa.ai/${endpoint}`, {
15+ method: "POST",
16+ headers: {
17+ "Content-Type": "application/json",
18+ "x-api-key": apiKey,
19+ },
20+ body: JSON.stringify(body),
21+ });
22+
23+ if (!response.ok) {
24+ const errorBody = await response.text();
25+ throw new Error(
26+ `Exa API error: ${response.status} ${response.statusText} - ${errorBody}`,
27+ );
28+ }
29+
30+ return await response.json();
31+}
32+
833 export const webSearchTool: ToolDef<
934 z.infer<typeof ExaSearchSchema>,
1035 unknown
@@ -13,33 +38,12 @@ export const webSearchTool: ToolDef<
1338 description: "Search the web for a query using Exa.",
1439 schema: ExaSearchSchema,
1540 execute: async (input) => {
16- const apiKey = process.env.EXA_API_KEY;
17- if (!apiKey) {
18- throw new Error("EXA_API_KEY is not set.");
19- }
20-
21- const response = await fetch("https://api.exa.ai/search", {
22- method: "POST",
23- headers: {
24- "Content-Type": "application/json",
25- "x-api-key": apiKey,
26- },
27- body: JSON.stringify({
28- query: input.query,
29- type: "auto",
30- numResults: 10,
31- contents: { text: { maxCharacters: 4000 } },
32- }),
41+ return fetchExa("search", {
42+ query: input.query,
43+ type: "auto",
44+ numResults: 10,
45+ contents: { text: { maxCharacters: 4000 } },
3346 });
34-
35- if (!response.ok) {
36- const errorBody = await response.text();
37- throw new Error(
38- `Exa API error: ${response.status} ${response.statusText} - ${errorBody}`,
39- );
40- }
41-
42- return await response.json();
4347 },
4448 };
4549
@@ -58,30 +62,9 @@ export const webContentTool: ToolDef<
5862 description: "Get the full content of specific URLs using Exa.",
5963 schema: ExaContentSchema,
6064 execute: async (input) => {
61- const apiKey = process.env.EXA_API_KEY;
62- if (!apiKey) {
63- throw new Error("EXA_API_KEY is not set.");
64- }
65-
66- const response = await fetch("https://api.exa.ai/contents", {
67- method: "POST",
68- headers: {
69- "Content-Type": "application/json",
70- "x-api-key": apiKey,
71- },
72- body: JSON.stringify({
73- urls: input.urls,
74- text: { maxCharacters: 10000 },
75- }),
65+ return fetchExa("contents", {
66+ urls: input.urls,
67+ text: { maxCharacters: 10000 },
7668 });
77-
78- if (!response.ok) {
79- const errorBody = await response.text();
80- throw new Error(
81- `Exa API error: ${response.status} ${response.statusText} - ${errorBody}`,
82- );
83- }
84-
85- return await response.json();
8669 },
8770 };
src/tools/insert.test.ts+15−34
@@ -1,39 +1,20 @@
11 import { afterEach, beforeEach, describe, 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";
62 import { insertTool } from "./insert.ts";
73
8-// ---------------------------------------------------------------------------
9-// Helpers
10-// ---------------------------------------------------------------------------
11-
12-let dir: string;
13-
14-async function write(name: string, content: string): Promise<string> {
15- await writeFile(join(dir, name), content);
16- return name;
17-}
18-
19-async function read(name: string): Promise<string> {
20- return Bun.file(join(dir, name)).text();
21-}
4+import { createTestHelpers } from "./test-helpers.ts";
225
23-function anchor(lineNum: number, lineContent: string): string {
24- return `${lineNum}:${hashLine(lineContent)}`;
25-}
6+const { setup, teardown, write, read, anchor, getDir } = createTestHelpers();
267
278 // ---------------------------------------------------------------------------
289 // Setup / teardown
2910 // ---------------------------------------------------------------------------
3011
3112 beforeEach(async () => {
32- dir = await mkdtemp(join(tmpdir(), "mc-insert-test-"));
13+ await setup("mc-insert-test-");
3314 });
3415
3516 afterEach(async () => {
36- await rm(dir, { recursive: true, force: true });
17+ await teardown();
3718 });
3819
3920 // ---------------------------------------------------------------------------
@@ -45,7 +26,7 @@ describe("insertTool", () => {
4526 const name = await write("f.txt", "a\nb\nc\n");
4627 const result = await insertTool.execute({
4728 path: name,
48- cwd: dir,
29+ cwd: getDir(),
4930 anchor: anchor(1, "a"),
5031 position: "after",
5132 content: "X",
@@ -61,7 +42,7 @@ describe("insertTool", () => {
6142 const name = await write("f.txt", "a\nb\nc\n");
6243 const result = await insertTool.execute({
6344 path: name,
64- cwd: dir,
45+ cwd: getDir(),
6546 anchor: anchor(2, "b"),
6647 position: "before",
6748 content: "X",
@@ -76,7 +57,7 @@ describe("insertTool", () => {
7657 const name = await write("f.txt", "a\nb\n");
7758 await insertTool.execute({
7859 path: name,
79- cwd: dir,
60+ cwd: getDir(),
8061 anchor: anchor(1, "a"),
8162 position: "after",
8263 content: "X\nY\nZ",
@@ -89,7 +70,7 @@ describe("insertTool", () => {
8970 const name = await write("f.txt", "a\nb\n");
9071 await insertTool.execute({
9172 path: name,
92- cwd: dir,
73+ cwd: getDir(),
9374 anchor: anchor(1, "a"),
9475 position: "before",
9576 content: "FIRST",
@@ -102,7 +83,7 @@ describe("insertTool", () => {
10283 const name = await write("f.txt", "a\nb\n");
10384 await insertTool.execute({
10485 path: name,
105- cwd: dir,
86+ cwd: getDir(),
10687 anchor: anchor(2, "b"),
10788 position: "after",
10889 content: "LAST",
@@ -115,7 +96,7 @@ describe("insertTool", () => {
11596 const name = await write("f.txt", "a\nb\n");
11697 const result = await insertTool.execute({
11798 path: name,
118- cwd: dir,
99+ cwd: getDir(),
119100 anchor: anchor(1, "a"),
120101 position: "after",
121102 content: "X",
@@ -128,7 +109,7 @@ describe("insertTool", () => {
128109 const name = await write("f.txt", "a\nb\nc\n");
129110 const result = await insertTool.execute({
130111 path: name,
131- cwd: dir,
112+ cwd: getDir(),
132113 anchor: anchor(2, "b"),
133114 position: "after",
134115 content: "NEW",
@@ -142,7 +123,7 @@ describe("insertTool", () => {
142123 await expect(
143124 insertTool.execute({
144125 path: "missing.txt",
145- cwd: dir,
126+ cwd: getDir(),
146127 anchor: "1:00",
147128 position: "after",
148129 content: "X",
@@ -155,7 +136,7 @@ describe("insertTool", () => {
155136 await expect(
156137 insertTool.execute({
157138 path: name,
158- cwd: dir,
139+ cwd: getDir(),
159140 anchor: "2:ff", // wrong hash for "b"
160141 position: "after",
161142 content: "X",
@@ -168,7 +149,7 @@ describe("insertTool", () => {
168149 await expect(
169150 insertTool.execute({
170151 path: name,
171- cwd: dir,
152+ cwd: getDir(),
172153 anchor: "not-an-anchor",
173154 position: "before",
174155 content: "X",
@@ -179,7 +160,7 @@ describe("insertTool", () => {
179160 const name = await write("f.txt", "a\nb\nc\n");
180161 await insertTool.execute({
181162 path: name,
182- cwd: dir,
163+ cwd: getDir(),
183164 anchor: `${anchor(2, "b")}|`,
184165 position: "after",
185166 content: "X",
src/tools/insert.ts+5−45
@@ -1,8 +1,8 @@
1-import { join, relative } from "node:path";
21 import { z } from "zod";
32 import type { ToolDef } from "../llm-api/types.ts";
43 import { generateDiff } from "./diff.ts";
54 import { findLineByHash } from "./hashline.ts";
5+import { parseAnchor, resolveExistingFile } from "./shared.ts";
66
77 const InsertSchema = z.object({
88 path: z.string().describe("File path to edit (absolute or relative to cwd)"),
@@ -34,19 +34,10 @@ export const insertTool: ToolDef<InsertInput, InsertOutput> = {
3434 "To replace or delete lines use `replace`. To create a file use `create`.",
3535 schema: InsertSchema,
3636 execute: async (input) => {
37- const cwd = input.cwd ?? process.cwd();
38- const filePath = input.path.startsWith("/")
39- ? input.path
40- : join(cwd, input.path);
41-
42- const relPath = relative(cwd, filePath);
43-
44- const file = Bun.file(filePath);
45- if (!(await file.exists())) {
46- throw new Error(
47- `File not found: "${relPath}". To create a new file use the \`create\` tool.`,
48- );
49- }
37+ const { file, filePath, relPath } = await resolveExistingFile(
38+ input.cwd,
39+ input.path,
40+ );
5041
5142 const parsed = parseAnchor(input.anchor);
5243
@@ -72,34 +63,3 @@ export const insertTool: ToolDef<InsertInput, InsertOutput> = {
7263 return { path: relPath, diff };
7364 },
7465 };
75-
76-interface ParsedAnchor {
77- line: number;
78- hash: string;
79-}
80-
81-function parseAnchor(value: string): ParsedAnchor {
82- const normalized = value.trim().endsWith("|")
83- ? value.trim().slice(0, -1)
84- : value;
85- const match = /^\s*(\d+):([0-9a-fA-F]{2})\s*$/.exec(normalized);
86- if (!match) {
87- throw new Error(
88- `Invalid anchor. Expected format: "line:hh" (e.g. "11:a3").`,
89- );
90- }
91-
92- const line = Number(match[1]);
93- if (!Number.isInteger(line) || line < 1) {
94- throw new Error("Invalid anchor line number.");
95- }
96-
97- const hash = match[2];
98- if (!hash) {
99- throw new Error(
100- `Invalid anchor. Expected format: "line:hh" (e.g. "11:a3").`,
101- );
102- }
103-
104- return { line, hash: hash.toLowerCase() };
105-}
src/tools/read.ts+3−6
@@ -1,7 +1,7 @@
1-import { join, relative } from "node:path";
21 import { z } from "zod";
32 import type { ToolDef } from "../llm-api/types.ts";
43 import { formatHashLine } from "./hashline.ts";
4+import { resolvePath } from "./shared.ts";
55
66 const ReadSchema = z.object({
77 path: z.string().describe("File path to read (absolute or relative to cwd)"),
@@ -42,10 +42,7 @@ export const readTool: ToolDef<ReadInput, ReadOutput> = {
4242 "paginate by incrementing `line`.",
4343 schema: ReadSchema,
4444 execute: async (input) => {
45- const cwd = input.cwd ?? process.cwd();
46- const filePath = input.path.startsWith("/")
47- ? input.path
48- : join(cwd, input.path);
45+ const { filePath, relPath } = resolvePath(input.cwd, input.path);
4946
5047 const file = Bun.file(filePath);
5148 const exists = await file.exists();
@@ -77,7 +74,7 @@ export const readTool: ToolDef<ReadInput, ReadOutput> = {
7774 .join("\n");
7875
7976 return {
80- path: relative(cwd, filePath),
77+ path: relPath,
8178 content,
8279 totalLines,
8380 line: clampedStart,
src/tools/replace.test.ts+15−37
@@ -1,42 +1,20 @@
11 import { afterEach, beforeEach, describe, 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";
62 import { replaceTool } from "./replace.ts";
73
8-// ---------------------------------------------------------------------------
9-// Helpers
10-// ---------------------------------------------------------------------------
11-
12-let dir: string;
13-
14-/** Write a file into the temp dir and return its basename. */
15-async function write(name: string, content: string): Promise<string> {
16- await writeFile(join(dir, name), content);
17- return name;
18-}
19-
20-/** Read a file from the temp dir. */
21-async function read(name: string): Promise<string> {
22- return Bun.file(join(dir, name)).text();
23-}
4+import { createTestHelpers } from "./test-helpers.ts";
245
25-/** Build an anchor string "line:hash" for the given line content. */
26-function anchor(lineNum: number, lineContent: string): string {
27- return `${lineNum}:${hashLine(lineContent)}`;
28-}
6+const { setup, teardown, write, read, anchor, getDir } = createTestHelpers();
297
308 // ---------------------------------------------------------------------------
319 // Setup / teardown
3210 // ---------------------------------------------------------------------------
3311
3412 beforeEach(async () => {
35- dir = await mkdtemp(join(tmpdir(), "mc-replace-test-"));
13+ await setup("mc-replace-test-");
3614 });
3715
3816 afterEach(async () => {
39- await rm(dir, { recursive: true, force: true });
17+ await teardown();
4018 });
4119
4220 // ---------------------------------------------------------------------------
@@ -48,7 +26,7 @@ describe("replaceTool", () => {
4826 const name = await write("f.txt", "a\nb\nc\n");
4927 const result = await replaceTool.execute({
5028 path: name,
51- cwd: dir,
29+ cwd: getDir(),
5230 startAnchor: anchor(2, "b"),
5331 newContent: "B",
5432 });
@@ -62,7 +40,7 @@ describe("replaceTool", () => {
6240 const name = await write("f.txt", "a\nb\nc\nd\ne\n");
6341 const result = await replaceTool.execute({
6442 path: name,
65- cwd: dir,
43+ cwd: getDir(),
6644 startAnchor: anchor(2, "b"),
6745 endAnchor: anchor(4, "d"),
6846 newContent: "X\nY",
@@ -80,7 +58,7 @@ describe("replaceTool", () => {
8058 const name = await write("f.txt", "a\nb\nc\n");
8159 const result = await replaceTool.execute({
8260 path: name,
83- cwd: dir,
61+ cwd: getDir(),
8462 startAnchor: anchor(2, "b"),
8563 });
8664
@@ -93,7 +71,7 @@ describe("replaceTool", () => {
9371 const name = await write("f.txt", "a\nb\nc\nd\n");
9472 await replaceTool.execute({
9573 path: name,
96- cwd: dir,
74+ cwd: getDir(),
9775 startAnchor: anchor(2, "b"),
9876 endAnchor: anchor(3, "c"),
9977 newContent: "",
@@ -106,7 +84,7 @@ describe("replaceTool", () => {
10684 const name = await write("f.txt", "a\nb\nc\n");
10785 const result = await replaceTool.execute({
10886 path: name,
109- cwd: dir,
87+ cwd: getDir(),
11088 startAnchor: anchor(2, "b"),
11189 newContent: "b",
11290 });
@@ -118,7 +96,7 @@ describe("replaceTool", () => {
11896 const name = await write("f.txt", "a\nb\n");
11997 const result = await replaceTool.execute({
12098 path: name,
121- cwd: dir,
99+ cwd: getDir(),
122100 startAnchor: anchor(1, "a"),
123101 newContent: "A",
124102 });
@@ -130,7 +108,7 @@ describe("replaceTool", () => {
130108 await expect(
131109 replaceTool.execute({
132110 path: "missing.txt",
133- cwd: dir,
111+ cwd: getDir(),
134112 startAnchor: "1:00",
135113 }),
136114 ).rejects.toThrow("File not found");
@@ -141,7 +119,7 @@ describe("replaceTool", () => {
141119 await expect(
142120 replaceTool.execute({
143121 path: name,
144- cwd: dir,
122+ cwd: getDir(),
145123 startAnchor: "2:ff", // wrong hash for "b"
146124 }),
147125 ).rejects.toThrow("Hash not found");
@@ -152,7 +130,7 @@ describe("replaceTool", () => {
152130 await expect(
153131 replaceTool.execute({
154132 path: name,
155- cwd: dir,
133+ cwd: getDir(),
156134 startAnchor: anchor(3, "c"),
157135 endAnchor: anchor(1, "a"),
158136 }),
@@ -164,7 +142,7 @@ describe("replaceTool", () => {
164142 await expect(
165143 replaceTool.execute({
166144 path: name,
167- cwd: dir,
145+ cwd: getDir(),
168146 startAnchor: "not-an-anchor",
169147 }),
170148 ).rejects.toThrow("Invalid startAnchor");
@@ -173,7 +151,7 @@ describe("replaceTool", () => {
173151 const name = await write("f.txt", "a\nb\nc\n");
174152 await replaceTool.execute({
175153 path: name,
176- cwd: dir,
154+ cwd: getDir(),
177155 startAnchor: `${anchor(2, "b")}|`,
178156 newContent: "B",
179157 });
src/tools/replace.ts+5−46
@@ -1,8 +1,8 @@
1-import { join, relative } from "node:path";
21 import { z } from "zod";
32 import type { ToolDef } from "../llm-api/types.ts";
43 import { generateDiff } from "./diff.ts";
54 import { findLineByHash } from "./hashline.ts";
5+import { parseAnchor, resolveExistingFile } from "./shared.ts";
66
77 const ReplaceSchema = z.object({
88 path: z.string().describe("File path to edit (absolute or relative to cwd)"),
@@ -44,20 +44,10 @@ export const replaceTool: ToolDef<ReplaceInput, ReplaceOutput> = {
4444 "To create a file use `create`. To insert without replacing any lines use `insert`.",
4545 schema: ReplaceSchema,
4646 execute: async (input) => {
47- const cwd = input.cwd ?? process.cwd();
48- const filePath = input.path.startsWith("/")
49- ? input.path
50- : join(cwd, input.path);
51-
52- const relPath = relative(cwd, filePath);
53-
54- const file = Bun.file(filePath);
55- if (!(await file.exists())) {
56- throw new Error(
57- `File not found: "${relPath}". To create a new file use the \`create\` tool.`,
58- );
59- }
60-
47+ const { file, filePath, relPath } = await resolveExistingFile(
48+ input.cwd,
49+ input.path,
50+ );
6151 const start = parseAnchor(input.startAnchor, "startAnchor");
6252 const end = input.endAnchor
6353 ? parseAnchor(input.endAnchor, "endAnchor")
@@ -103,34 +93,3 @@ export const replaceTool: ToolDef<ReplaceInput, ReplaceOutput> = {
10393 return { path: relPath, diff, deleted: replacement.length === 0 };
10494 },
10595 };
106-
107-interface ParsedAnchor {
108- line: number;
109- hash: string;
110-}
111-
112-function parseAnchor(value: string, name: string): ParsedAnchor {
113- const normalized = value.trim().endsWith("|")
114- ? value.trim().slice(0, -1)
115- : value;
116- const match = /^\s*(\d+):([0-9a-fA-F]{2})\s*$/.exec(normalized);
117- if (!match) {
118- throw new Error(
119- `Invalid ${name}. Expected format: "line:hh" (e.g. "11:a3").`,
120- );
121- }
122-
123- const line = Number(match[1]);
124- if (!Number.isInteger(line) || line < 1) {
125- throw new Error(`Invalid ${name} line number.`);
126- }
127-
128- const hash = match[2];
129- if (!hash) {
130- throw new Error(
131- `Invalid ${name}. Expected format: "line:hh" (e.g. "11:a3").`,
Cut short: this commit's diff is over 1000 lines.
src/tools/shared.ts+53−0
Cut short: this commit's diff is over 1000 lines.
src/tools/snapshot.test.ts+54−61
Cut short: this commit's diff is over 1000 lines.
src/tools/test-helpers.ts+38−0
Cut short: this commit's diff is over 1000 lines.
src/tools/worktree.test.ts+16−35
Cut short: this commit's diff is over 1000 lines.