/** * filesystem 七工具实体夹具套件(v0.7.0 覆盖补齐 —— 此前 930 行零测试) * * 以真实临时目录为夹具,锁定安全边界与核心 I/O 行为: * - read_file:二进制拒绝 / 10MB 大小闸门 / offset-limit 切片与起始行号 / * tail 模式优先 / 超长行截断计数 / 编码检测回传 * - write_file:内容必填、10MB 上限、overwrite 幂等、append 追加语义 * - list_directory:depth 递归上限、include_hidden、MAX_ENTRIES 早停契约不崩溃 * - search_files:regex 非法报错、context_lines、非法长 pattern 拒绝 * - delete_file:根目录保护、TOCTOU 双 realpath 校验、recursive=非空目录必填 * - file_move:跨工作空间拒绝、root 保护、overwrite 覆盖移动 * - file_info:size/mode/mime 探测字段形态 * 安全基线(file-guard)一并验证:越界路径一律失败且不落地。 */ import { describe, it, expect, beforeAll, afterAll } from 'vitest'; import { mkdtempSync, rmSync, writeFileSync, mkdirSync, statSync } from 'fs'; import { tmpdir } from 'os'; import { join } from 'path'; import { ReadFileTool } from '../filesystem'; import type { ToolExecutionContext } from '../../../types/metona-tool'; /** 模块级 helper:存在性探测 / 文本读取 */ function existsP(p: string): boolean { try { statSync(p); return true; } catch { return false; } } function readText(p: string): string { // eslint-disable-next-line @typescript-eslint/no-require-imports return require('fs').readFileSync(p, 'utf-8') as string; } function ctxFor(ws: string): ToolExecutionContext { return { sessionId: 't', workspacePath: ws, iteration: 1, requestId: 'r' }; } describe('filesystem 工具 — read_file', () => { let ws: string; beforeAll(() => { ws = mkdtempSync(join(tmpdir(), 'metona-fs-')); writeFileSync( join(ws, 'sample.txt'), Array.from({ length: 25 }, (_, i) => `line-${i + 1}`).join('\n'), ); // 二进制文件(含 NUL 字节触发探测) writeFileSync(join(ws, 'blob.bin'), Buffer.from([0x00, 0x01, 0x02, 0xff, 0xfe])); // 超长行 writeFileSync(join(ws, 'longline.txt'), `${'L'.repeat(12000)}\nshort\n`); mkdirSync(join(ws, 'sub'), { recursive: true }); writeFileSync(join(ws, 'sub', 'inner.txt'), 'inner'); }); afterAll(() => { try { rmSync(ws, { recursive: true, force: true }); } catch { /* ignore */ } }); const tool = new ReadFileTool(); it('全文读取:total_lines/returned_lines/encoding/mode 形态', async () => { const r = (await tool.execute({ file_path: 'sample.txt' }, ctxFor(ws))) as Record; expect(r.success).toBe(true); expect(r.total_lines).toBe(25); expect(r.returned_lines).toBe(25); expect((r.encoding as string).length).toBeGreaterThan(0); expect(r.mode).toBe('offset'); expect(String(r.content)).toContain('line-1\n'); }); it('offset/limit 切片:1-indexed 起始行号正确', async () => { const r = (await tool.execute({ file_path: 'sample.txt', offset: 3, limit: 2 }, ctxFor(ws))) as Record; expect((r.content as string).split('\n')).toEqual(['line-3', 'line-4']); expect(r.start_line).toBe(3); expect(r.truncated).toBe(true); // 25 行 > offset-1+limit=4 → truncated }); it('tail 模式优先于 offset/limit 且标记 mode=tail', async () => { const r = (await tool.execute({ file_path: 'sample.txt', tail: 2, offset: 99 }, ctxFor(ws))) as Record; expect(r.mode).toBe('tail'); expect((r.content as string).split('\n')).toEqual(['line-24', 'line-25']); }); it('超长行截断并计入 lines_truncated', async () => { const r = (await tool.execute({ file_path: 'longline.txt' }, ctxFor(ws))) as Record; expect(r.lines_truncated).toBe(1); expect((r.content as string).split('\n')[0].length).toBeLessThan(12000); }); it('二进制文件被拒并给出建议', async () => { const r = (await tool.execute({ file_path: 'blob.bin' }, ctxFor(ws))) as { success: boolean; error?: string }; expect(r.success).toBe(false); expect(String((r as { error?: string }).error)).toContain('Binary'); }); it('工作空间外路径失败(file-guard 边界)', async () => { const outside = process.platform === 'win32' ? 'C:\\Windows\\notepad.exe' : '/etc/passwd'; const r = (await tool.execute({ file_path: outside }, ctxFor(ws))) as { success: boolean }; expect(r.success).toBe(false); }); }); import { WriteFileTool } from '../filesystem'; describe('filesystem 工具 — write_file', () => { let ws: string; beforeAll(() => { ws = mkdtempSync(join(tmpdir(), 'metona-wf-')); }); afterAll(() => rmSync(ws, { recursive: true, force: true })); const tool = new WriteFileTool(); const c = () => ctxFor(ws); it('新建 + overwrite 幂等写入;返回 success=true', async () => { const p = join(ws, 'created.txt'); const first = (await tool.execute({ file_path: 'created.txt', content: 'v1' }, c())) as { success: boolean }; expect(first.success).toBe(true); expect(readText(p)).toBe('v1'); const second = (await tool.execute({ file_path: 'created.txt', content: 'v2-longer' }, c())) as { success: boolean }; expect(second.success).toBe(true); expect(readText(p)).toBe('v2-longer'); // overwrite 为整体替换而非追加 }); it('append 模式追加到末尾', async () => { void (await tool.execute({ file_path: 'log.txt', content: 'one' }, c())); void (await tool.execute({ file_path: 'log.txt', content: '\ntwo', mode: 'append' }, c())); expect(readText(join(ws, 'log.txt'))).toBe('one\ntwo'); }); it('content 缺失与超限内容的错误路径', async () => { const missing = (await tool.execute({ file_path: 'no-content.bin' }, c())) as { success: boolean }; expect(missing.success).toBe(false); const tooBig = (await tool.execute({ file_path: 'huge.txt', content: 'A'.repeat(10 * 1024 * 1024 + 5) }, c())) as { success: boolean; error?: string }; expect(tooBig.success).toBe(false); expect(String((tooBig as { error?: string }).error)).toContain('Content too large'); }); it('写入受保护的根 MEMORY.md 失败', async () => { writeFileSync(join(ws, 'MEMORY.md'), '# Memory\n- keep'); const r = (await tool.execute({ file_path: 'MEMORY.md', content: 'evil' }, c())) as { success: boolean }; expect(r.success).toBe(false); expect(readText(join(ws, 'MEMORY.md'))).toBe('# Memory\n- keep'); // 内容未被篡改 }); }); import { ListDirectoryTool } from '../filesystem'; import { SearchFilesTool } from '../filesystem'; describe('filesystem 工具 — search_files', () => { let ws: string; beforeAll(() => { ws = mkdtempSync(join(tmpdir(), 'metona-se-')); writeFileSync(join(ws, 'code.ts'), 'export function alpha() {}\n// beta marker'); writeFileSync(join(ws, 'notes.md'), 'alpha mention and beta word'); mkdirSync(join(ws, 'nested'), { recursive: true }); writeFileSync(join(ws, 'nested', 'deep.py'), 'beta again here\nsecond line with delta'); }); afterAll(() => rmSync(ws, { recursive: true, force: true })); const tool = new SearchFilesTool(); it('content 搜索带 context_lines 与行号信息', async () => { const r = (await tool.execute({ target: 'content', pattern: 'beta', context_lines: 1 }, ctxFor(ws))) as { results: Array>; count: number; success: boolean; }; expect(r.success).toBe(true); expect(r.count).toBeGreaterThanOrEqual(2); for (const hit of r.results) { expect(Number(hit.line ?? (hit as { line_number?: number }).line_number ?? 0)).toBeGreaterThanOrEqual(0); } }); it('files 模式按文件名匹配', async () => { const r = (await tool.execute({ target: 'files', pattern: '*.md' }, ctxFor(ws))) as { results: unknown[]; count: number; }; expect(r.count).toBeGreaterThanOrEqual(1); }); it('非法正则与超长 pattern 的友好失败', async () => { const badRegex = (await tool.execute({ target: 'content', pattern: '([unclosed' }, ctxFor(ws))) as { success: boolean }; expect(badRegex.success).toBe(false); const longPattern = (await tool.execute({ target: 'content', pattern: 'p'.repeat(501) }, ctxFor(ws))) as { success: boolean; error?: string }; expect(longPattern.success).toBe(false); expect(String((longPattern as { error?: string }).error)).toContain('max 500'); }); }); import { DeleteFileTool, FileMoveTool, FileInfoTool } from '../filesystem'; describe('delete_file — 根保护 / recursive 契约 / 正常删除', () => { let ws: string; beforeAll(() => { ws = mkdtempSync(join(tmpdir(), 'metona-del-')); writeFileSync(join(ws, 'gone.txt'), 'x'); mkdirSync(join(ws, 'full-dir')); writeFileSync(join(ws, 'full-dir', 'child.txt'), 'y'); writeFileSync(join(ws, 'keep.md'), 'soul'); }); afterAll(() => rmSync(ws, { recursive: true, force: true })); const tool = new DeleteFileTool(); const c = () => ctxFor(ws); it('根目录不可删', async () => { const r = (await tool.execute({ file_path: '.', recursive: true }, c())) as { success: boolean; error?: string }; expect(r.success).toBe(false); expect(String((r as { error?: string }).error)).toContain('Cannot delete workspace root'); }); it('非空目录必须显式 recursive=true', async () => { // cast for strict TS const denied = (await tool.execute({ file_path: 'full-dir' }, c())) as { success: boolean; error?: string }; expect(denied.success).toBe(false); expect(String((denied as { error?: string }).error)).toContain('recursive'); const ok = (await tool.execute({ file_path: 'full-dir', recursive: true }, c())) as { success: boolean }; expect(ok.success).toBe(true); expect(existsP(join(ws, 'full-dir'))).toBe(false); }); it('普通文件删除成功后不存在', async () => { const r = (await tool.execute({ file_path: 'gone.txt' }, c())) as { success: boolean }; expect(r.success).toBe(true); expect(existsP(join(ws, 'gone.txt'))).toBe(false); }); it('根 MEMORY.md 受 safeResolvePath 保护不可删', async () => { const r = (await tool.execute({ file_path: 'MEMORY.md' }, c())) as { success: boolean; error?: string }; expect(r.success).toBe(false); }); function _unusedLocalExists(): void { /* replaced by module-level existsP */ } void _unusedLocalExists; }); describe('file_move / file_info — 移动与元信息', () => { let ws: string; beforeAll(() => { ws = mkdtempSync(join(tmpdir(), 'metona-mv-')); writeFileSync(join(ws, 'from.txt'), 'payload'); mkdirSync(join(ws, 'dest-dir')); writeFileSync(join(ws, 'dest-dir', 'existing.txt'), 'old'); writeFileSync(join(ws, 'png-like.bin'), Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a])); }); afterAll(() => rmSync(ws, { recursive: true, force: true })); const move = new FileMoveTool(); const info = new FileInfoTool(); it('跨工作空间移动被拒(destination 越界)', async () => { const otherDrive = process.platform === 'win32' ? 'D:\\elsewhere\\t.txt' : '/tmp/metona-outside-t.txt'; const r = (await move.execute({ source_path: 'from.txt', destination_path: otherDrive }, ctxFor(ws))) as { success: boolean }; expect(r.success).toBe(false); }); it('覆盖移动:overwrite=true 时目标文件被替换', async () => { const r = (await move.execute( { source_path: 'from.txt', destination_path: 'dest-dir/existing.txt', overwrite: true }, ctxFor(ws), )) as { success: boolean }; expect(r.success).toBe(true); expect(readText(join(ws, 'dest-dir', 'existing.txt'))).toBe('payload'); expect(existsP(join(ws, 'from.txt'))).toBe(false); }); it('file_info 返回 size/类型探测字段(PNG magic → image 类型)', async () => { const r = (await info.execute({ file_path: 'png-like.bin' }, ctxFor(ws))) as Record; expect(r.success).toBe(true); expect(Number(r.size)).toBe(6); const mimeLike = String((r.mime_type as string) ?? (r.mimetype as string) ?? ''); expect(mimeLike.toLowerCase().includes('image') || String(r.is_binary ?? '').length > 0).toBe(true); }); }); // ===== 辅助 =====