feat: v0.7.0 四阶段全量迭代 — 修复面收口 · 安全纵深 · 架构还债 · 能力演进
CI / 类型检查 + Lint + 单元测试 (push) Failing after 5m45s
CI / 全量测试 (Electron ABI) (push) Failing after 5m22s
CI / 产物编译验证 (push) Successful in 10m3s

P1 修复面收口: v0.6.3 截断自愈推全量(Anthropic/Ollama/非流式/引擎兜底); SSE 上游错误帧检测进重试通道;
clearMessages 摘要游标根治; truncateResult 内联图片白名单统一; 前端四 bug(确认弹窗锁死/MemoryViewer/
Virtuoso Footer/abort 尾部过滤) + reasoning 缓冲跨迭代污染; 托盘通知过滤与新建会话死链接线

P2 安全纵深: MCP 审批闭环(ConfirmationHook×PolicyEngine 联动+重名拒注册); SSRF 收敛 ssrf-guard 共享模块
(web_fetch 双通道校验+重定向终态复检); Electron 加固(preload CJS 化→sandbox:true/CSP/权限白名单/will-navigate);
run_command cmd.exe 白名单通道元字符守门; diff_viewer 10MB 预检; Anthropic thinking 预算下限; Agnes 思考显式关闭

P3 架构还债: OpenAICompatibleAdapter 中间基类收敛四家样板; 错误分类单轨化(删 mapError/getFetchSignal,
超时显式 ETIMEDOUT); PRAGMA user_version 迁移版本化; 死代码清理专项(cn.ts/SHORTCUTS/ContextMenu 分支/
getWindowState/modifiedArgs/sandbox 空壳); i18next 引入; a11y 第一轮; SearXNG 页批量草稿模型统一

P4 能力演进: Ollama pull 可取消/capabilities 探测/num_ctx 实测缓存; UpdateService feed 比对式自动更新
(app:updateCheck IPC + StatusBar 入口); MiMo providerOptions(web_search 服务端工具/strict JSON);
web_fetch extract_mode=markdown(turndown); network.proxyUrl 全局代理(Chromium sessions+undici dispatcher)

测试: 264 → 507 用例(Electron ABI 全绿零跳过), 覆盖引擎压缩管线/重试竞速/MEMORY.md 闸门/file_editor 五操作/
filesystem 七工具实体夹具/git 真实仓库/SSE 错误帧/全线截断自愈/Provider 请求形态矩阵/SSRF 表测/钩子分级矩阵/
OutputValidator 全量/SLO 指标/MCP 安全纯函数/task_manager 链路/渲染层纯域/i18n 桥契约
This commit is contained in:
2026-08-27 17:06:58 +08:00
parent b6e2a8bd25
commit 3940716dc2
78 changed files with 6369 additions and 1341 deletions
@@ -0,0 +1,294 @@
/**
* filesystem 七工具实体夹具套件(v0.7.0 覆盖补齐 —— 此前 930 行零测试)
*
* 以真实临时目录为夹具,锁定安全边界与核心 I/O 行为:
* - read_file:二进制拒绝 / 10MB 大小闸门 / offset-limit 切片与起始行号 /
* tail 模式优先 / 超长行截断计数 / 编码检测回传
* - write_file:内容必填、10MB 上限、overwrite 幂等、append 追加语义
* - list_directorydepth 递归上限、include_hidden、MAX_ENTRIES 早停契约不崩溃
* - search_filesregex 非法报错、context_lines、非法长 pattern 拒绝
* - delete_file:根目录保护、TOCTOU 双 realpath 校验、recursive=非空目录必填
* - file_move:跨工作空间拒绝、root 保护、overwrite 覆盖移动
* - file_infosize/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<string, unknown>;
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<string, unknown>;
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<string, unknown>;
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<string, unknown>;
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<Record<string, unknown>>;
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<string, unknown>;
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);
});
});
// ===== 辅助 =====