import { runBoundedProcess } from '../../runtime/boundedProcess.js'; import { safeSlice } from '../../utils/safeText.js'; import { resolve } from 'node:path'; import { mkdtemp, writeFile, mkdir, copyFile } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; /** * 只读审查要判断「是否由某次变更新引入」时,子任务必须拿到可读的基线。 * * 真实问题:explore 子任务没有 Bash、也读不到 `.git`,任务书却要求「对比 HEAD 与工作区、 * 判断问题是否新引入」——它只能列出当前代码里的候选风险,无法回答被问的问题。让它去 * 突破权限不对,让主 Agent 每次手写 diff 也容易漏。所以由宿主在派发时自动附带: * 任务书出现需要基线的措辞、又没给 `context.baseline` 时,取一份 `git diff HEAD` * (含未跟踪文件清单)放进委派上下文,超长时给完整快照路径;取不到明确标注限制。 */ const NEEDS_BASELINE = /新引入|是否(?:由|为).{0,12}(?:变更|改动|提交|修改)(?:引入|造成|导致)|引入了?(?:回归|缺陷|问题)|回归(?:缺陷|问题)|基线|baseline|git\s+diff|(?:对比|比较|比对).{0,16}(?:HEAD|工作区|基线|改动前)|(?:HEAD|基线).{0,16}(?:对比|比较|比对)|\bregression\b|newly introduced|introduced by/i; export interface BaselineCheckInput { prompt: string; description?: string; agent_type?: string; context?: { baseline?: string; researchQuestions?: unknown; goal?: string; acceptance?: string }; } /** A revision is a pointer, not readable evidence. Never accept Git options here. */ export function baselineRevision(value?: string): string | undefined { const match = /^(?:HEAD\s*[:=]\s*)?([0-9a-f]{7,40}|HEAD(?:[~^]\d*)?)$/i.exec(value?.trim() ?? ''); return match?.[1]; } /** 只读子任务的任务书是否需要「改动前后」基线,且调用方没有提供。 */ export function needsChangeBaseline(input: BaselineCheckInput): boolean { if (input.agent_type === 'general') return false; if (input.context?.baseline?.trim()) return baselineRevision(input.context.baseline) !== undefined; const text = [ input.prompt, input.description ?? '', input.context?.goal ?? '', input.context?.acceptance ?? '', input.context?.researchQuestions ? JSON.stringify(input.context.researchQuestions) : '', ].join('\n'); return NEEDS_BASELINE.test(text); } /** 宿主取不到 git diff 时写进 context.baseline 的说明:不拒绝派发,但要求子任务如实声明限制。 */ export const BASELINE_UNAVAILABLE = '[宿主未能取得 git diff(仓库、命令或差异读取不可用),且只读子任务读不到 .git,因此没有可用的改动前基线。' + '若任务要判断某问题是否由变更新引入,请在报告里如实说明「缺少基线、无法判断」,只报告当前代码中的候选风险,不要凭当前代码断言是新引入。]'; /** 附带基线的体量上限(字符)。超出时保留文件清单与统计,正文按文件截断并如实说明。 */ export const BASELINE_MAX_CHARS = 60_000; async function git(args: string[], cwd: string, signal?: AbortSignal, snapshotRoot?: string): Promise { try { const result = await runBoundedProcess('git', args, { cwd, timeoutMs: 30_000, signal, allowTruncatedOutput: true, env: { GIT_TERMINAL_PROMPT: '0', GIT_ASKPASS: '' }, }); if (result.exitCode !== 0) return undefined; // The process runner spools overflow losslessly. Even smaller outputs can // exceed the prompt budget: publish a read-only snapshot reference instead // of handing the child an irrecoverably truncated review baseline. let path = result.stdoutPath; if (path || result.stdout.length > BASELINE_MAX_CHARS / 4) { if (snapshotRoot) await mkdir(snapshotRoot, { recursive: true, mode: 0o700 }); const destination = join(await mkdtemp(join(snapshotRoot ?? tmpdir(), 'minimal-baseline-')), 'snapshot.txt'); if (path) await copyFile(path, destination); else await writeFile(destination, result.stdout, { mode: 0o600 }); path = destination; } return (path ? `[完整基线材料:${JSON.stringify(path)};用 Read 分页续读,不因摘要截断直接结束审查。]\n` : '') + result.stdout + (result.stdoutTruncated ? '\n…(输出已截断;不代表完整覆盖)' : ''); } catch { signal?.throwIfAborted(); return undefined; } } /** * 取 `HEAD → 工作区` 的差异作为基线文本;不是 git 仓库、没有提交或 git 不可用时返回 undefined。 * 无改动也是有效基线(明确告诉子任务「工作区与 HEAD 一致」)。 */ export async function captureGitBaseline(cwd: string, signal?: AbortSignal, revision = 'HEAD', snapshotRoot?: string): Promise { if (!baselineRevision(revision)) return undefined; const head = (await git(['rev-parse', '--verify', `${revision}^{commit}`], cwd, signal))?.trim(); if (!head) return undefined; const status = await git(['-c', 'status.relativePaths=true', '-c', 'color.status=false', 'status', '--short', '--untracked-files=all', '--', '.'], cwd, signal, snapshotRoot); const diffArgs = ['diff', '--relative', '--no-renames', '--no-ext-diff', '--no-textconv', head]; const stat = await git([...diffArgs, '--stat', '--', '.'], cwd, signal, snapshotRoot); const diff = await git([...diffArgs, '--no-color', '--', '.'], cwd, signal, snapshotRoot); if (status === undefined || stat === undefined || diff === undefined) return undefined; const untracked = status.split('\n').filter((line) => line.startsWith('??')).map((line) => line.slice(3).trim()); const header = `[宿主自动附带的基线:git diff ${revision}(基线提交=${head});子任务不能运行 git,请以此为「改动前」依据。` + `采集目录=${JSON.stringify(resolve(cwd))};仅覆盖该目录及子目录,不是运行程序的版本证明。任务审查其他工作树时,本差异不适用,须由主 Agent 补充对应基线;不得混用。` + '修改前的内容在 `-` 行与基线提交,修改后在 `+` 行与工作区。]'; const parts = [header]; parts.push(status.trim() ? `文件状态:\n${status.trim()}` : diff.trim() ? '工作区没有未提交改动;下方为相对指定基线的已提交差异。' : `工作区与 ${revision} 一致,没有未提交改动。`); if (untracked.length) parts.push(`未跟踪的新文件(不在 diff 里,请直接 Read):${untracked.join('、')}`); if (stat.trim()) parts.push(`统计:\n${stat.trim()}`); // status、未跟踪清单、stat 都可能独自达到进程上限;预算约束整个注入文本。 const clip = (value: string, limit: number): string => { const note = '\n…(已截断;不能假定未显示部分无改动)'; return value.length <= limit ? value : safeSlice(value, 0, limit - note.length) + note; }; const metadata = parts.join('\n\n'); if (!diff.trim()) return clip(metadata, BASELINE_MAX_CHARS); const separator = '\n\n差异:\n'; const metaBudget = BASELINE_MAX_CHARS - separator.length - Math.min(diff.length, BASELINE_MAX_CHARS / 2); const prefix = clip(metadata, metaBudget) + separator; return prefix + clip(diff, BASELINE_MAX_CHARS - prefix.length); }