@trans-ai/trans-code 0.1.4 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,133 @@
1
+ import { afterEach, describe, expect, test } from 'bun:test';
2
+ import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
3
+ import { tmpdir } from 'node:os';
4
+ import path from 'node:path';
5
+ import { editFileTool, readFileTool, writeFileTool } from './files.js';
6
+ import { createToolSession, hasFileBeenRead, type ToolSession } from './session.js';
7
+ import type { ToolContext } from './types.js';
8
+
9
+ const cleanups: Array<() => void> = [];
10
+ afterEach(() => {
11
+ while (cleanups.length) cleanups.pop()!();
12
+ });
13
+
14
+ function workspace(): string {
15
+ const dir = mkdtempSync(path.join(tmpdir(), 'transcode-files-'));
16
+ cleanups.push(() => rmSync(dir, { recursive: true, force: true }));
17
+ return dir;
18
+ }
19
+
20
+ function ctx(session: ToolSession): ToolContext {
21
+ return { cwd: session.cwd, session };
22
+ }
23
+
24
+ async function read(session: ToolSession, file: string) {
25
+ return readFileTool.execute({ path: file }, ctx(session));
26
+ }
27
+
28
+ async function write(session: ToolSession, file: string, content: string) {
29
+ return writeFileTool.execute({ path: file, content }, ctx(session));
30
+ }
31
+
32
+ async function edit(session: ToolSession, file: string, old_string: string, new_string: string) {
33
+ return editFileTool.execute({ path: file, old_string, new_string }, ctx(session));
34
+ }
35
+
36
+ describe('read_file', () => {
37
+ test('records the file as read in the session', async () => {
38
+ const dir = workspace();
39
+ const session = createToolSession(dir);
40
+ writeFileSync(path.join(dir, 'a.txt'), 'hello\n');
41
+
42
+ await read(session, 'a.txt');
43
+ expect(hasFileBeenRead(session, path.join(dir, 'a.txt'))).toBe(true);
44
+ });
45
+
46
+ test('truncates lines longer than 2000 characters', async () => {
47
+ const dir = workspace();
48
+ const session = createToolSession(dir);
49
+ writeFileSync(path.join(dir, 'long.txt'), `${'x'.repeat(3000)}\nshort\n`);
50
+
51
+ const output = await read(session, 'long.txt');
52
+ expect(output).toContain('[line truncated]');
53
+ expect(output).toContain('short');
54
+ expect(output.length).toBeLessThan(2400);
55
+ });
56
+ });
57
+
58
+ describe('write_file', () => {
59
+ test('allows creating a new file', async () => {
60
+ const dir = workspace();
61
+ const session = createToolSession(dir);
62
+
63
+ const result = await write(session, 'new.txt', 'content\n');
64
+ expect(result.output).toContain('Wrote');
65
+ expect(readFileSync(path.join(dir, 'new.txt'), 'utf8')).toBe('content\n');
66
+ });
67
+
68
+ test('refuses to overwrite an existing file that was not read this session', async () => {
69
+ const dir = workspace();
70
+ writeFileSync(path.join(dir, 'a.txt'), 'original\n');
71
+ const session = createToolSession(dir);
72
+
73
+ await expect(write(session, 'a.txt', 'clobbered\n')).rejects.toThrow(/read_file first/);
74
+ expect(readFileSync(path.join(dir, 'a.txt'), 'utf8')).toBe('original\n');
75
+ });
76
+
77
+ test('allows overwriting after the file was read', async () => {
78
+ const dir = workspace();
79
+ writeFileSync(path.join(dir, 'a.txt'), 'original\n');
80
+ const session = createToolSession(dir);
81
+
82
+ await read(session, 'a.txt');
83
+ await write(session, 'a.txt', 'replaced\n');
84
+ expect(readFileSync(path.join(dir, 'a.txt'), 'utf8')).toBe('replaced\n');
85
+ });
86
+ });
87
+
88
+ describe('edit_file', () => {
89
+ test('refuses to edit a file that was not read this session', async () => {
90
+ const dir = workspace();
91
+ writeFileSync(path.join(dir, 'a.txt'), 'original\n');
92
+ const session = createToolSession(dir);
93
+
94
+ await expect(edit(session, 'a.txt', 'original', 'changed')).rejects.toThrow(
95
+ /read_file first/,
96
+ );
97
+ expect(readFileSync(path.join(dir, 'a.txt'), 'utf8')).toBe('original\n');
98
+ });
99
+
100
+ test('applies an exact replacement after reading', async () => {
101
+ const dir = workspace();
102
+ writeFileSync(path.join(dir, 'a.txt'), 'alpha\nbeta\ngamma\n');
103
+ const session = createToolSession(dir);
104
+
105
+ await read(session, 'a.txt');
106
+ const result = await edit(session, 'a.txt', 'beta', 'BETA');
107
+ expect(readFileSync(path.join(dir, 'a.txt'), 'utf8')).toBe('alpha\nBETA\ngamma\n');
108
+ expect(result.output).toContain('Replaced 1 occurrence');
109
+ });
110
+
111
+ test('falls back to quote normalization when the file uses curly quotes', async () => {
112
+ const dir = workspace();
113
+ writeFileSync(path.join(dir, 'prose.md'), 'He said “don’t stop” loudly\n');
114
+ const session = createToolSession(dir);
115
+
116
+ await read(session, 'prose.md');
117
+ await edit(session, 'prose.md', 'He said "don\'t stop" loudly', 'She said "go" now');
118
+ expect(readFileSync(path.join(dir, 'prose.md'), 'utf8')).toBe('She said "go" now\n');
119
+ });
120
+
121
+ test('returns a line-numbered snippet around the edit', async () => {
122
+ const dir = workspace();
123
+ const lines = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight'];
124
+ writeFileSync(path.join(dir, 'n.txt'), `${lines.join('\n')}\n`);
125
+ const session = createToolSession(dir);
126
+
127
+ await read(session, 'n.txt');
128
+ const result = await edit(session, 'n.txt', 'four', 'CHANGED');
129
+ expect(result.output).toContain('CHANGED');
130
+ expect(result.output).toMatch(/4\tCHANGED/);
131
+ expect(result.output).toMatch(/8\teight/);
132
+ });
133
+ });
@@ -0,0 +1,240 @@
1
+ import { promises as fs } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { z } from 'zod';
4
+ import type { AgentTool } from './types.js';
5
+ import { hasFileBeenRead, markFileRead, type ToolSession } from './session.js';
6
+ import { MAX_LINE_LENGTH, MAX_READ_BYTES, displayPath, resolveInsideWorkspace, truncate } from './fs-utils.js';
7
+ import { lineDiff } from './diff.js';
8
+
9
+ const SNIPPET_CONTEXT_LINES = 4;
10
+ const NEW_FILE_DIFF_LINES = 20;
11
+
12
+ // Claude-style quote normalization: models emit straight quotes, files often
13
+ // contain curly ones. Both sides are normalized before matching.
14
+ const LEFT_SINGLE_CURLY_QUOTE = '‘';
15
+ const RIGHT_SINGLE_CURLY_QUOTE = '’';
16
+ const LEFT_DOUBLE_CURLY_QUOTE = '“';
17
+ const RIGHT_DOUBLE_CURLY_QUOTE = '”';
18
+
19
+ function normalizeQuotes(str: string): string {
20
+ return str
21
+ .replaceAll(LEFT_SINGLE_CURLY_QUOTE, "'")
22
+ .replaceAll(RIGHT_SINGLE_CURLY_QUOTE, "'")
23
+ .replaceAll(LEFT_DOUBLE_CURLY_QUOTE, '"')
24
+ .replaceAll(RIGHT_DOUBLE_CURLY_QUOTE, '"');
25
+ }
26
+
27
+ /**
28
+ * Finds the actual string in the file content matching the search string,
29
+ * falling back to quote normalization when the exact match fails.
30
+ * Ported from Claude Code's FileEditTool findActualString.
31
+ */
32
+ function findActualString(fileContent: string, searchString: string): string | null {
33
+ if (fileContent.includes(searchString)) {
34
+ return searchString;
35
+ }
36
+
37
+ const normalizedSearch = normalizeQuotes(searchString);
38
+ const normalizedFile = normalizeQuotes(fileContent);
39
+
40
+ const searchIndex = normalizedFile.indexOf(normalizedSearch);
41
+ if (searchIndex !== -1) {
42
+ return fileContent.substring(searchIndex, searchIndex + searchString.length);
43
+ }
44
+
45
+ return null;
46
+ }
47
+
48
+ /** Renders a numbered window around an edit so the model can verify it. */
49
+ function snippetAfterEdit(
50
+ original: string,
51
+ oldString: string,
52
+ newString: string,
53
+ startLine: number,
54
+ ): string {
55
+ const updatedLines = original.split(oldString).join(newString).split(/\r?\n/);
56
+ const lines = updatedLines.slice(startLine, startLine + SNIPPET_CONTEXT_LINES * 2 + Math.max(1, newString.split(/\r?\n/).length) + 2);
57
+ return lines
58
+ .map((line, index) => `${String(startLine + index + 1).padStart(6)}\t${line}`)
59
+ .join('\n');
60
+ }
61
+
62
+ function requireRead(session: ToolSession, absolute: string, display: string): void {
63
+ if (!hasFileBeenRead(session, absolute)) {
64
+ throw new Error(
65
+ `File has not been read this session: ${display}. Read it with read_file first ` +
66
+ 'so edits and overwrites are made against known content.',
67
+ );
68
+ }
69
+ }
70
+
71
+ export const readFileTool: AgentTool = {
72
+ name: 'read_file',
73
+ description:
74
+ 'Read a UTF-8 text file from the workspace. Returns line-numbered content. ' +
75
+ 'Use offset (1-based line) and limit to read large files in chunks.',
76
+ kind: 'read',
77
+ isMutating: false,
78
+ schema: z.object({
79
+ path: z.string().describe('File path, relative to the workspace root'),
80
+ offset: z.number().int().min(1).nullable().optional().describe('First line to read (1-based)'),
81
+ limit: z.number().int().min(1).max(5000).nullable().optional().describe('Maximum number of lines'),
82
+ }),
83
+ title: (input) => `read: ${String(input.path ?? '')}`,
84
+ async execute(input, ctx) {
85
+ const absolute = resolveInsideWorkspace(ctx.cwd, String(input.path));
86
+ const stat = await fs.stat(absolute);
87
+ if (!stat.isFile()) throw new Error(`Not a file: ${input.path}`);
88
+ if (stat.size > 5_000_000) {
89
+ throw new Error(
90
+ `File is ${stat.size} bytes, which exceeds the 5 MB read limit. ` +
91
+ 'Use grep or bash (head/tail) to inspect it.',
92
+ );
93
+ }
94
+ if (stat.size > MAX_READ_BYTES && !input.offset && !input.limit) {
95
+ throw new Error(
96
+ `File is ${stat.size} bytes. Pass offset/limit to read it in chunks.`,
97
+ );
98
+ }
99
+
100
+ const content = await fs.readFile(absolute, 'utf8');
101
+ markFileRead(ctx.session, absolute);
102
+
103
+ const lines = content.split('\n');
104
+ const offset = Math.max(1, Number(input.offset ?? 1));
105
+ const limit = Math.min(Number(input.limit ?? 2000), 5000);
106
+ const selected = lines.slice(offset - 1, offset - 1 + limit);
107
+ const numbered = selected
108
+ .map((line, index) => {
109
+ const clipped =
110
+ line.length > MAX_LINE_LENGTH
111
+ ? `${line.slice(0, MAX_LINE_LENGTH)}... [line truncated]`
112
+ : line;
113
+ return `${String(offset + index).padStart(6)}\t${clipped}`;
114
+ })
115
+ .join('\n');
116
+
117
+ const more = offset - 1 + selected.length < lines.length;
118
+ return truncate(
119
+ numbered + (more ? `\n... (${lines.length} lines total)` : ''),
120
+ MAX_READ_BYTES,
121
+ );
122
+ },
123
+ };
124
+
125
+ export const writeFileTool: AgentTool = {
126
+ name: 'write_file',
127
+ description:
128
+ 'Create or overwrite a file in the workspace with the given content. ' +
129
+ 'Existing files must be read with read_file first. ' +
130
+ 'Prefer edit_file for existing files so unrelated content is preserved.',
131
+ kind: 'edit',
132
+ isMutating: true,
133
+ schema: z.object({
134
+ path: z.string().describe('File path, relative to the workspace root'),
135
+ content: z.string().describe('Full file content to write'),
136
+ }),
137
+ title: (input) => `write: ${String(input.path ?? '')}`,
138
+ async execute(input, ctx) {
139
+ const absolute = resolveInsideWorkspace(ctx.cwd, String(input.path));
140
+ let exists = true;
141
+ try {
142
+ await fs.access(absolute);
143
+ } catch {
144
+ exists = false;
145
+ }
146
+ if (exists) {
147
+ requireRead(ctx.session, absolute, displayPath(ctx.cwd, absolute));
148
+ }
149
+
150
+ let previous: string | null = null;
151
+ if (exists) {
152
+ previous = await fs.readFile(absolute, 'utf8').catch(() => null);
153
+ }
154
+
155
+ await fs.mkdir(path.dirname(absolute), { recursive: true });
156
+ const content = String(input.content);
157
+ await fs.writeFile(absolute, content, 'utf8');
158
+ markFileRead(ctx.session, absolute);
159
+
160
+ const summary = `Wrote ${Buffer.byteLength(content, 'utf8')} bytes to ${displayPath(
161
+ ctx.cwd,
162
+ absolute,
163
+ )}`;
164
+ if (previous !== null) {
165
+ return { output: summary, diff: lineDiff(previous, content) || undefined };
166
+ }
167
+
168
+ const lines = content.split('\n');
169
+ if (lines[lines.length - 1] === '') lines.pop();
170
+ const shown = lines.slice(0, NEW_FILE_DIFF_LINES);
171
+ const diffParts = shown.map((line) => `+${line}`);
172
+ if (lines.length > NEW_FILE_DIFF_LINES) {
173
+ diffParts.push(`... (+${lines.length - NEW_FILE_DIFF_LINES} more lines)`);
174
+ }
175
+ return {
176
+ output: summary,
177
+ diff: lines.length === 0 ? undefined : `@@ -0,0 +1,${lines.length} @@\n${diffParts.join('\n')}`,
178
+ };
179
+ },
180
+ };
181
+
182
+ export const editFileTool: AgentTool = {
183
+ name: 'edit_file',
184
+ description:
185
+ 'Replace an exact string in an existing file. The old_string must appear exactly once ' +
186
+ 'unless replace_all is true. Read the file first to get exact text. ' +
187
+ 'Straight/curly quote differences are normalized automatically.',
188
+ kind: 'edit',
189
+ isMutating: true,
190
+ schema: z.object({
191
+ path: z.string().describe('File path, relative to the workspace root'),
192
+ old_string: z.string().describe('Exact text to replace'),
193
+ new_string: z.string().describe('Replacement text'),
194
+ replace_all: z.boolean().nullable().optional().describe('Replace every occurrence'),
195
+ }),
196
+ title: (input) => `patch: ${String(input.path ?? '')}`,
197
+ async execute(input, ctx) {
198
+ const absolute = resolveInsideWorkspace(ctx.cwd, String(input.path));
199
+ requireRead(ctx.session, absolute, displayPath(ctx.cwd, absolute));
200
+
201
+ const oldString = String(input.old_string);
202
+ const newString = String(input.new_string);
203
+ if (oldString === newString) throw new Error('old_string and new_string are identical');
204
+
205
+ const original = await fs.readFile(absolute, 'utf8');
206
+
207
+ const actualOld = findActualString(original, oldString);
208
+ if (actualOld === null) {
209
+ throw new Error('old_string was not found in the file. Read it again and use exact text.');
210
+ }
211
+ const occurrences = actualOld === '' ? 0 : original.split(actualOld).length - 1;
212
+ if (occurrences === 0) {
213
+ throw new Error('old_string was not found in the file. Read it again and use exact text.');
214
+ }
215
+ if (occurrences > 1 && input.replace_all !== true) {
216
+ throw new Error(
217
+ `old_string appears ${occurrences} times. Pass replace_all=true or include more context.`,
218
+ );
219
+ }
220
+
221
+ const updated =
222
+ input.replace_all === true
223
+ ? original.split(actualOld).join(newString)
224
+ : original.replace(actualOld, () => newString);
225
+ await fs.writeFile(absolute, updated, 'utf8');
226
+
227
+ const replacedCount = input.replace_all === true ? occurrences : 1;
228
+ const before = original.split(actualOld)[0] ?? '';
229
+ const replacementLine = before.split(/\r?\n/).length - 1;
230
+ const snippetStart = Math.max(0, replacementLine - SNIPPET_CONTEXT_LINES);
231
+ const snippet = snippetAfterEdit(original, actualOld, newString, snippetStart);
232
+
233
+ return {
234
+ output:
235
+ `Replaced ${replacedCount} occurrence(s) in ${displayPath(ctx.cwd, absolute)}\n\n` +
236
+ `${snippet}`,
237
+ diff: lineDiff(original, updated) || undefined,
238
+ };
239
+ },
240
+ };
@@ -0,0 +1,117 @@
1
+ import { promises as fs } from 'node:fs';
2
+ import path from 'node:path';
3
+
4
+ export const MAX_READ_BYTES = 100_000;
5
+ export const MAX_GREP_MATCHES = 200;
6
+ export const MAX_GLOB_FILES = 200;
7
+ export const MAX_LINE_LENGTH = 2_000;
8
+
9
+ export const SKIP_DIRS = new Set([
10
+ '.git',
11
+ 'node_modules',
12
+ '.turbo',
13
+ 'dist',
14
+ 'build',
15
+ '.next',
16
+ 'target',
17
+ '__pycache__',
18
+ '.venv',
19
+ 'venv',
20
+ '.cache',
21
+ ]);
22
+
23
+ export function truncate(text: string, max: number): string {
24
+ if (text.length <= max) return text;
25
+ return `${text.slice(0, max)}\n... (truncated, ${text.length - max} chars omitted)`;
26
+ }
27
+
28
+ export function resolveInsideWorkspace(cwd: string, inputPath: string): string {
29
+ const absolute = path.resolve(cwd, inputPath || '.');
30
+ if (process.env.TRANSCODE_ALLOW_OUTSIDE_CWD === '1') return absolute;
31
+
32
+ const relative = path.relative(cwd, absolute);
33
+ const inside =
34
+ relative === '' ||
35
+ (!relative.startsWith('..' + path.sep) && relative !== '..' && !path.isAbsolute(relative));
36
+ if (!inside) {
37
+ throw new Error(
38
+ `Path escapes the workspace: ${inputPath}. ` +
39
+ `Set TRANSCODE_ALLOW_OUTSIDE_CWD=1 to allow it.`,
40
+ );
41
+ }
42
+ return absolute;
43
+ }
44
+
45
+ export function displayPath(cwd: string, absolute: string): string {
46
+ const relative = path.relative(cwd, absolute);
47
+ return relative && !relative.startsWith('..') ? relative : absolute;
48
+ }
49
+
50
+ export async function walkFiles(root: string, signal?: AbortSignal): Promise<string[]> {
51
+ const files: string[] = [];
52
+ const stack: string[] = [root];
53
+
54
+ while (stack.length > 0) {
55
+ if (signal?.aborted) throw new Error('Aborted');
56
+ const dir = stack.pop()!;
57
+ let entries;
58
+ try {
59
+ entries = await fs.readdir(dir, { withFileTypes: true });
60
+ } catch {
61
+ continue;
62
+ }
63
+ for (const entry of entries) {
64
+ const full = path.join(dir, entry.name);
65
+ if (entry.isDirectory()) {
66
+ if (SKIP_DIRS.has(entry.name)) continue;
67
+ stack.push(full);
68
+ } else if (entry.isFile()) {
69
+ files.push(full);
70
+ }
71
+ }
72
+ }
73
+
74
+ return files;
75
+ }
76
+
77
+ function escapeRegex(value: string): string {
78
+ return value.replace(/[.+^${}()|[\]\\]/g, '\\$&');
79
+ }
80
+
81
+ export function globToRegExp(pattern: string): RegExp {
82
+ let p = pattern.replace(/\\/g, '/').replace(/^\.\//, '');
83
+ p = escapeRegex(p);
84
+ // `**/` should also match zero directories.
85
+ p = p.replace(/\*\*\//g, '\u0001');
86
+ p = p.replace(/\*\*/g, '\u0002');
87
+ p = p.replace(/\*/g, '[^/]*');
88
+ p = p.replace(/\?/g, '[^/]');
89
+ p = p.replace(/\u0001/g, '(?:.*/)?');
90
+ p = p.replace(/\u0002/g, '.*');
91
+ return new RegExp(`^${p}$`);
92
+ }
93
+
94
+ export function matchesGlob(pattern: string, relativePath: string): boolean {
95
+ const normalized = relativePath.replace(/\\/g, '/');
96
+ const re = globToRegExp(pattern);
97
+ if (!pattern.includes('/')) {
98
+ return re.test(path.posix.basename(normalized));
99
+ }
100
+ return re.test(normalized);
101
+ }
102
+
103
+ export async function readTextIfTextFile(file: string): Promise<string | null> {
104
+ const stat = await fs.stat(file);
105
+ if (stat.size > 2_000_000) return null;
106
+
107
+ const handle = await fs.open(file, 'r');
108
+ try {
109
+ const buffer = Buffer.alloc(8192);
110
+ const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
111
+ const sample = buffer.subarray(0, bytesRead);
112
+ if (sample.includes(0)) return null;
113
+ return await fs.readFile(file, 'utf8');
114
+ } finally {
115
+ await handle.close();
116
+ }
117
+ }
@@ -0,0 +1,59 @@
1
+ import { tool as langChainTool } from '@langchain/core/tools';
2
+ import type { StructuredToolInterface } from '@langchain/core/tools';
3
+ import type { AgentTool, InvokeResult, ToolContext } from './types.js';
4
+ import { bashTool } from './bash.js';
5
+ import { editFileTool, readFileTool, writeFileTool } from './files.js';
6
+ import { globTool, grepTool } from './search.js';
7
+
8
+ export const AGENT_TOOLS: AgentTool[] = [
9
+ readFileTool,
10
+ writeFileTool,
11
+ editFileTool,
12
+ globTool,
13
+ grepTool,
14
+ bashTool,
15
+ ];
16
+
17
+ export function findAgentTool(name: string): AgentTool | undefined {
18
+ return AGENT_TOOLS.find((item) => item.name === name);
19
+ }
20
+
21
+ /** Tool definitions bound to the model. Execution happens locally via invokeTool. */
22
+ export function bindableTools(tools: AgentTool[] = AGENT_TOOLS): StructuredToolInterface[] {
23
+ return tools.map((item) =>
24
+ langChainTool(async () => '', {
25
+ name: item.name,
26
+ description: item.description,
27
+ schema: item.schema,
28
+ }),
29
+ );
30
+ }
31
+
32
+ export async function invokeTool(
33
+ item: AgentTool,
34
+ input: Record<string, unknown>,
35
+ ctx: ToolContext,
36
+ ): Promise<InvokeResult> {
37
+ const parsed = item.schema.safeParse(input);
38
+ if (!parsed.success) {
39
+ return {
40
+ ok: false,
41
+ output: `Invalid input for ${item.name}: ${parsed.error.issues
42
+ .map((issue) => `${issue.path.join('.') || '(root)'}: ${issue.message}`)
43
+ .join('; ')}`,
44
+ };
45
+ }
46
+
47
+ try {
48
+ const result = await item.execute(parsed.data as Record<string, unknown>, ctx);
49
+ if (typeof result === 'string') {
50
+ return { ok: true, output: result || '(no output)' };
51
+ }
52
+ return { ok: true, output: result.output || '(no output)', diff: result.diff };
53
+ } catch (error) {
54
+ return { ok: false, output: `Error: ${(error as Error).message}` };
55
+ }
56
+ }
57
+
58
+ export * from './types.js';
59
+ export * from './session.js';
@@ -0,0 +1,55 @@
1
+ import { afterEach, describe, expect, test } from 'bun:test';
2
+ import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
3
+ import { tmpdir } from 'node:os';
4
+ import path from 'node:path';
5
+ import { globTool, grepTool } from './search.js';
6
+ import { createToolSession, type ToolSession } from './session.js';
7
+ import type { ToolContext } from './types.js';
8
+
9
+ const cleanups: Array<() => void> = [];
10
+ afterEach(() => {
11
+ while (cleanups.length) cleanups.pop()!();
12
+ });
13
+
14
+ function workspace(): string {
15
+ const dir = mkdtempSync(path.join(tmpdir(), 'transcode-search-'));
16
+ cleanups.push(() => rmSync(dir, { recursive: true, force: true }));
17
+ return dir;
18
+ }
19
+
20
+ function ctx(session: ToolSession): ToolContext {
21
+ return { cwd: session.cwd, session };
22
+ }
23
+
24
+ describe('glob', () => {
25
+ test('finds files by pattern with workspace-relative paths', async () => {
26
+ const dir = workspace();
27
+ writeFileSync(path.join(dir, 'a.ts'), 'x');
28
+ writeFileSync(path.join(dir, 'b.txt'), 'x');
29
+
30
+ const session = createToolSession(dir);
31
+ const output = await globTool.execute({ pattern: '**/*.ts' }, ctx(session));
32
+ expect(output).toContain('a.ts');
33
+ expect(output).not.toContain('b.txt');
34
+ });
35
+ });
36
+
37
+ describe('grep', () => {
38
+ test('returns path:line matches', async () => {
39
+ const dir = workspace();
40
+ writeFileSync(path.join(dir, 'code.ts'), 'const alpha = 1;\nconst beta = 2;\n');
41
+
42
+ const session = createToolSession(dir);
43
+ const output = await grepTool.execute({ pattern: 'beta' }, ctx(session));
44
+ expect(output).toContain('code.ts:2: const beta = 2;');
45
+ });
46
+
47
+ test('reports when nothing matches', async () => {
48
+ const dir = workspace();
49
+ writeFileSync(path.join(dir, 'code.ts'), 'const alpha = 1;\n');
50
+
51
+ const session = createToolSession(dir);
52
+ const output = await grepTool.execute({ pattern: 'nope-xyz' }, ctx(session));
53
+ expect(output).toContain('No matches');
54
+ });
55
+ });