/** * ============================================================ * src/infra/verification.ts —— 共享验证基础设施 * ------------------------------------------------------------ * 支持四种检查器(跨平台): * - shell: 跨平台 spawn(Windows 走 cmd /c, 其余 bash -c) * - file_exists: fs.existsSync * - file_contains:: 正则匹配文件内容 * - test_count: 跑 `bun test`,从 stdout 解析 "N pass" * * 消费者: * - workflow-runner 插件(verify 步骤类型) * - 工作流 YAML 的 type: verify 步骤 * - 未来任何需要声明式验证的插件或模块 * * 设计原则: * - 纯工具函数,无全局状态,无副作用(除了 shell 子进程) * - 不依赖任何插件代码,可被 src/ 和 plugins/ 同时导入 * - 工作目录隔离:相对路径以调用方给的 cwd 为锚,缺省 getWorkingDir() * * ⚠️ cwd 参数不是可有可无的修饰:**验收必须和写入锚在同一个目录**。 * 会话进入 session worktree 后(EnterWorktree),写文件的工具跟着 worktree 走 * (loop.ts 按 sessionState.activeWorktree 重定向 cwd),验收若仍锚原 workspace, * 就会在空目录里找产物 —— file_exists 恒 false,工作流被判失败并反复重试, * 而产物其实好好躺在 worktree 里。调用方拿得到有效 cwd 时务必传进来。 * ============================================================ */ import { existsSync, readFileSync } from 'node:fs'; import { spawn } from 'node:child_process'; import { sanitizeCredentialEnv } from '../config/configService.js'; import { CONFIG_LIMITS, normalizeLimited } from '../config/numericLimits.js'; import { getWorkingDir } from '../bootstrap/workingDir.js'; /** * `shell:` 检查的默认超时——**唯一真值**。 * * ⚠️ 这个数字此前在本文件里写了两份(`parseCheckString` 的构造处 + `runVerification` * 的 `?? 30_000` 兜底),改一处漏一处就会出现「解析时 30s、执行时 60s」这种谁都看不出 * 的分裂。边界见 `config/numericLimits.ts::CONFIG_LIMITS.verifyShellTimeoutMs`。 * * 为什么默认值不能太大:`verify()` 是工作流硬门,跑不完就阻塞整条流水线。 * 需要跑全量测试套件的场景应当缩到具体文件,或由调用方显式传 `defaultShellTimeoutMs`。 */ export const DEFAULT_SHELL_CHECK_TIMEOUT_MS = 30_000; export interface Check { type: 'shell' | 'file_contains' | 'file_exists' | 'test_count'; command?: string; file?: string; pattern?: string; minCount?: number; timeout?: number; } export interface CheckResult { check: Check; passed: boolean; output: string; } export interface VerifyResult { passed: boolean; details: CheckResult[]; summary: string; } /** 从 "type:value" 字符串解析为 Check 对象。 */ function parseVerifyArg(arg: string): Check | null { const colonIdx = arg.indexOf(':'); if (colonIdx < 0) return null; const type = arg.slice(0, colonIdx).trim().toLowerCase(); const value = arg.slice(colonIdx + 1).trim(); switch (type) { case 'shell': // ⚠️ 这里**不填** timeout:解析层只管语法,超时是策略、由 runVerification 决定。 // 曾经在这里写死 30_000,于是 `check.timeout ?? 默认值` 里的默认值永远走不到 —— // 调用方传的超时被一个「解析时顺手填上的」值静默盖掉。 return { type: 'shell', command: value }; case 'file_exists': return { type: 'file_exists', file: value }; case 'file_contains': { const sep = value.indexOf(':'); if (sep < 0) return null; return { type: 'file_contains', file: value.slice(0, sep), pattern: value.slice(sep + 1), }; } case 'test_count': { const count = parseInt(value, 10); if (isNaN(count) || count < 0) return null; return { type: 'test_count', minCount: count }; } default: return null; } } /** * 从命令行参数字符串中提取所有 --verify 项。 * 兼容两种调用方式: * - 工作流 / 命令的 args 字符串:`"goal --verify 'shell:bun test'"` * - workflow verify 步骤的 checks 数组元素:`"shell:bun test"` */ export function parseVerifyArgs(args: string): Check[] { const checks: Check[] = []; const regex = /--verify\s+("[^"]*"|\S+)/gi; let match; while ((match = regex.exec(args)) !== null) { const raw = match[1].replace(/^"|"$/g, ''); const check = parseVerifyArg(raw); if (check) checks.push(check); } return checks; } /** 从单个 check 字符串解析(workflow verify 步骤用)。 * parseVerifyArg 是底层解析器;本函数保留独立名字是因为 verify.ts:14 直接 import 它。 * parseVerifyArgs 用于从命令行参数字符串抓 --verify 项——两者职责不重叠。 */ export function parseCheckString(raw: string): Check | null { return parseVerifyArg(raw); } /** * 判断路径是否为绝对路径(POSIX / Windows drive / Windows UNC)。 * - POSIX: /usr/local/... * - Win drive: C:\Users\... 或 C:/foo * - UNC: \\server\share\... * 之前漏识别 UNC → 会被错误地拼上 workingDir 前缀,file_exists 永远查不到。 */ function isAbsolutePath(file: string): boolean { return ( file.startsWith('/') || file.startsWith('\\') || // 同时覆盖 \foo 和 \\server(前者非常规但兼容) /^[A-Za-z]:[\\/]/.test(file) // C:\ 或 C:/ ); } interface ShellRunResult { exitCode: number | null; stdout: string; stderr: string; errored: boolean; } function runShell( command: string, timeout: number, cwd: string, ): Promise { return new Promise((resolve) => { const isWin = process.platform === 'win32'; const opts = { timeout, cwd, env: sanitizeCredentialEnv() }; // ⚠️ windowsVerbatimArguments: true 是必须的,不是可选优化:Node 给 cmd.exe/ // .bat 目标默认加一层它自己的参数转义(CVE-2024-27980 之后的安全加固), // 会把 command 字符串里模型自己写好的转义(比如内嵌 PowerShell 单行脚本里的 // `\"..."`)再转义一遍,导致 cmd.exe 转交给子进程的字符串被改写、PowerShell // 解析报 UnexpectedToken——文件内容明明字节级正确,check 却稳定失败。 // 已实测:一段合法的 `powershell -Command "...; Write-Host \"x\"; ..."` // 不加这个选项必挂,加了立刻 exitCode 0;简单命令(echo/dir/bun --version) // 行为不受影响。verify() 的 shell: 检查类型专供工作流的 hard_checks 使用, // 命令来自可信的 LLM 契约草稿或用户输入,不是不可信的外部数据, // 关掉这层转义不引入新的注入面。 const child = isWin ? spawn('cmd', ['/c', command], { ...opts, windowsVerbatimArguments: true }) : spawn('bash', ['-c', command], opts); let stdout = ''; let stderr = ''; child.stdout.on('data', (d: Buffer) => { stdout += d.toString(); }); child.stderr.on('data', (d: Buffer) => { stderr += d.toString(); }); child.on('error', () => { resolve({ exitCode: null, stdout, stderr, errored: true }); }); child.on('close', (code) => { resolve({ exitCode: code, stdout, stderr, errored: false }); }); }); } export async function verifyShell( command: string, timeout: number, cwd: string = getWorkingDir(), ): Promise { const r = await runShell(command, timeout, cwd); if (r.errored) { return { check: { type: 'shell', command }, passed: false, output: `执行失败`, }; } return { check: { type: 'shell', command }, passed: r.exitCode === 0, output: r.stdout.trim() || r.stderr.trim() || `exit code ${r.exitCode}`, }; } export function verifyFileExists( file: string, cwd: string = getWorkingDir(), ): CheckResult { // 相对路径以调用方给的 cwd 为锚(绝对路径识别含 UNC) const resolved = isAbsolutePath(file) ? file : `${cwd}/${file}`; const exists = existsSync(resolved); return { check: { type: 'file_exists', file }, passed: exists, output: exists ? '文件存在' : `文件不存在: ${resolved}`, }; } export function verifyFileContains( file: string, pattern: string, cwd: string = getWorkingDir(), ): CheckResult { const resolved = isAbsolutePath(file) ? file : `${cwd}/${file}`; try { const content = readFileSync(resolved, 'utf8'); const regex = new RegExp(pattern); const matched = regex.test(content); return { check: { type: 'file_contains', file, pattern }, passed: matched, output: matched ? `文件包含 "${pattern}"` : `文件不包含 "${pattern}"`, }; } catch { return { check: { type: 'file_contains', file, pattern }, passed: false, output: `无法读取文件: ${resolved}`, }; } } async function verifyTestCount( minCount: number, cwd: string = getWorkingDir(), ): Promise { // 跨运行时:开发用 bun → bun test;npm 全局安装用 Node → npm test --silent // 用 process.versions.bun 探测比 typeof Bun !== 'undefined' 更稳(不依赖全局类型) const cmd = process.versions.bun ? 'bun test' : 'npm test --silent'; const r = await runShell(cmd, 60_000, cwd); const combined = `${r.stdout}\n${r.stderr}`; if (r.errored) { return { check: { type: 'test_count', minCount }, passed: false, output: '无法执行 bun test', }; } const matches = [...combined.matchAll(/(\d+)\s+pass/gi)]; const count = matches.length > 0 ? parseInt(matches[matches.length - 1][1], 10) : 0; const passed = count >= minCount; return { check: { type: 'test_count', minCount }, passed, output: `${count} pass (需要 >=${minCount})`, }; } /** * 执行一组检查,返回聚合结果。 * 全部通过 → passed=true;任一失败 → passed=false + summary 列出失败项。 */ export async function runVerification( checks: Check[], cwd: string = getWorkingDir(), options: { defaultShellTimeoutMs?: number } = {}, ): Promise { const shellTimeout = normalizeLimited( options.defaultShellTimeoutMs, CONFIG_LIMITS.verifyShellTimeoutMs, DEFAULT_SHELL_CHECK_TIMEOUT_MS, ); if (checks.length === 0) { return { passed: true, details: [], summary: '无验证项' }; } const results: CheckResult[] = []; for (const check of checks) { let result: CheckResult; switch (check.type) { case 'shell': result = await verifyShell( check.command ?? '', check.timeout ?? shellTimeout, cwd, ); break; case 'file_exists': result = verifyFileExists(check.file ?? '', cwd); break; case 'file_contains': result = verifyFileContains(check.file ?? '', check.pattern ?? '', cwd); break; case 'test_count': result = await verifyTestCount(check.minCount ?? 0, cwd); break; default: result = { check, passed: false, output: `未知验证类型: ${(check as { type: string }).type}`, }; } // 回填**原始** check:各 verifier 只收散参(command/file/pattern),返回时会 // 自己重建一个残缺的 check 对象,把 timeout 这类字段丢掉。details 是给人排障和 // 给工作流做卡死指纹用的,它必须如实反映「这一条到底是按什么跑的」。 results.push({ ...result, check }); } const allPassed = results.every((r) => r.passed); const failedNames = results.filter((r) => !r.passed).map((r) => formatCheckName(r.check)); let summary: string; if (allPassed) { summary = `✅ 全部通过 (${results.length}/${results.length})`; } else { summary = `❌ 验证未通过: ${failedNames.join(', ')}`; } return { passed: allPassed, details: results, summary }; } function formatCheckName(check: Check): string { switch (check.type) { case 'shell': return `shell(${(check.command ?? '').slice(0, 40)})`; case 'file_exists': return `exists(${check.file})`; case 'file_contains': return `contains(${check.file}:${check.pattern})`; case 'test_count': return `tests(>=${check.minCount})`; default: return check.type; } }