/** * ============================================================ * src/prompts/lint.ts —— 系统提示词的跨层重复检查(确定性,无 LLM) * ------------------------------------------------------------ * **为什么需要它**:`promptAssembly.ts` 把提示词分成若干层(身份/纪律层、工具编排层、 * Skills、Plugins、项目指令)。层与层之间很容易把同一条规则说两遍——写的时候各看各的段落, * 读起来都通顺,拼起来就是重复烧 token、而且两处措辞一旦漂移就会互相矛盾。 * 人工清理一次能干净,但下一次加规则又会退化,所以要把「不重复」变成**回归护栏**。 * * **分层判据(去重时按它归位,不是凭感觉)**: * 一条规则若在「该工具不存在时依然成立」→ 属身份层;否则属工具层。 * 例:「改文件前先读最新内容」没有 Edit 工具时无意义 → 工具层; * 「只在无法推断时才提问」没有 AskUserQuestion 时仍成立(约束的是判断而非调用)→ 身份层。 * * **能力边界(必须如实说)**:这是**词面**近重复检测,不是语义检测。 * 「不用正则盲改源码」与「源码编辑优先专用工具」表达同一件事但几乎不共享字面, * 本检查器**抓不到**——那类只能靠人读。它保证的是:已经清理干净的地方不会因为 * 有人复制粘贴一句旧措辞而悄悄退化。 * * **为什么按「子句」而不是整条规则比**:整条规则通常长且各带自己的补充说明, * 即使核心重复,整条的 Jaccard 也只有 0.1 量级(实测),根本触发不了。 * 拆成子句后重复的那一句会高度重合。 * * **为什么用 containment 而不是 Jaccard**:我们要问的是「这句话是不是在别处已经说过了」, * 即**包含**关系;短句被长句涵盖时 Jaccard 会被长句的其余部分稀释,containment 不会。 * ============================================================ */ import type { Tool } from '../types.js'; /** 数据型段落:内容来自用户目录/项目文件,不是我们写的策略,不参与去重。 */ const DEFAULT_IGNORED_SECTIONS = ['Skills', 'Plugins', '项目指令']; /** 子句短于这个 token 数就不参与比较——短句碰巧重合太常见,会淹没真信号。 */ const MIN_TOKENS = 6; /** containment 达到这个值即判为「已经在别处说过」。 */ const DEFAULT_THRESHOLD = 0.7; export interface PromptClause { /** 所属段落标题(`# xxx` 里的 xxx);顶部无标题内容归入 '(开头)'。 */ section: string; /** 该子句所属的完整规则行,报错时给人看上下文。 */ rule: string; /** 子句原文。 */ text: string; tokens: Set; } export interface DuplicateFinding { a: PromptClause; b: PromptClause; /** |A∩B| / min(|A|,|B|),1 表示一方被另一方完全涵盖。 */ containment: number; } /** 显式豁免。`reason` 是必填的——没有理由的豁免等于把检查器关掉。 */ export interface DedupExemption { a: string; b: string; reason: string; } export interface DedupOptions { threshold?: number; ignoredSections?: string[]; exemptions?: DedupExemption[]; /** Audit owned prose/continuation lines as well as bullet rules. */ includeProse?: boolean; /** Enable within-section checks for strict regression audits. */ checkSameSection?: boolean; } /** * 归一化:抹掉不影响语义的差异,让「先读取」和「读取」这类插字不至于把整句错开。 * 全角标点、markdown 强调、反引号代码标记一律去掉。 */ function normalize(text: string): string { return text .replace(/[`*_~]/g, '') .replace(/[,。;、:?!()【】「」《》,.;:?!()[\]{}"'/\\-]/g, '') .replace(/\s+/g, '') .toLocaleLowerCase(); } /** * 中文按 2-gram、拉丁词按整词切。中文没有空格分词,bigram 是这里最稳的近似 * (memoryService.ts::terms 出于同样理由也用 bigram,保持一致)。 */ function tokenize(normalized: string): Set { const tokens = new Set(); for (const word of normalized.match(/[a-z0-9]+/g) ?? []) { if (word.length > 1) tokens.add(word); } const cjk = normalized.replace(/[a-z0-9]+/g, ''); for (let index = 0; index + 1 < cjk.length; index += 1) { tokens.add(cjk.slice(index, index + 2)); } return tokens; } function containmentOf(a: Set, b: Set): number { const smaller = a.size <= b.size ? a : b; const larger = smaller === a ? b : a; let shared = 0; for (const token of smaller) if (larger.has(token)) shared += 1; return smaller.size === 0 ? 0 : shared / smaller.size; } /** * 把组装好的提示词拆成「段落 → 规则行 → 子句」。 * 默认检查项目符号;严格审计可纳入普通段落及续行。词面匹配不判断语义冲突。 */ export function extractPromptClauses( prompt: string, ignoredSections: string[] = DEFAULT_IGNORED_SECTIONS, includeProse = false, ): PromptClause[] { const clauses: PromptClause[] = []; let section = '(开头)'; for (const line of prompt.split(/\r?\n/)) { const heading = line.match(/^#+\s+(.*)$/); if (heading) { section = heading[1]!.trim(); continue; } if (ignoredSections.some((ignored) => section.includes(ignored))) continue; const rule = line.match(/^\s*-\s+(.*)$/)?.[1] ?? (includeProse ? line.trim() : undefined); if (!rule) continue; for (const piece of rule.split(/[;;。]/)) { const text = piece.trim(); if (!text) continue; const tokens = tokenize(normalize(text)); if (tokens.size < MIN_TOKENS) continue; clauses.push({ section, rule, text, tokens }); } } return clauses; } function isExempt(a: PromptClause, b: PromptClause, exemptions: DedupExemption[]): boolean { return exemptions.some((item) => (a.text.includes(item.a) && b.text.includes(item.b)) || (a.text.includes(item.b) && b.text.includes(item.a))); } /** * 默认寻找跨段落近重复。严格模式也检查同段落,需人工区分真正重复与必要限定。 */ export function findDuplicateClauses( prompt: string, options: DedupOptions = {}, ): DuplicateFinding[] { const threshold = options.threshold ?? DEFAULT_THRESHOLD; const exemptions = options.exemptions ?? []; const clauses = extractPromptClauses(prompt, options.ignoredSections, options.includeProse); const findings: DuplicateFinding[] = []; for (let i = 0; i < clauses.length; i += 1) { for (let j = i + 1; j < clauses.length; j += 1) { const a = clauses[i]!; const b = clauses[j]!; if (!options.checkSameSection && a.section === b.section) continue; const containment = containmentOf(a.tokens, b.tokens); if (containment < threshold) continue; if (isExempt(a, b, exemptions)) continue; findings.push({ a, b, containment }); } } return findings.sort((x, y) => y.containment - x.containment); } /** 供测试失败时打印——直接给出两处原文和所在段落,不用再去翻提示词。 */ export function formatDuplicateFindings(findings: DuplicateFinding[]): string { return findings .map((item) => `[${item.containment.toFixed(2)}] 「${item.a.section}」${item.a.text}\n` + ` ↔ 「${item.b.section}」${item.b.text}`) .join('\n'); } export interface ToolRoutingConflict { toolName: string; reason: string; } /** * Cross-surface routing guard. The three Web tools intentionally have disjoint * jobs, so stale fallback wording is a capability bug rather than style drift. */ export function findToolRoutingConflicts( prompt: string, tools: readonly Tool[], ): ToolRoutingConflict[] { const conflicts: ToolRoutingConflict[] = []; const descriptions = new Map(tools.map((tool) => [ tool.name, typeof tool.description === 'function' ? tool.description() : tool.description, ])); const browser = descriptions.get('WebBrowser') ?? ''; const combinedRouting = `${prompt}\n${browser}`; if (/(?:Search\/Fetch|WebSearch\/WebFetch)[^\n]{0,100}(?:无法|失败|cannot obtain)[^\n]{0,100}(?:降级|fallback|WebBrowser)|supported fallback/i.test(combinedRouting)) { conflicts.push({ toolName: 'WebBrowser', reason: 'WebBrowser 被描述为 Search/Fetch 失败后的普通兜底', }); } const fetch = descriptions.get('WebFetch') ?? ''; // Naming the dynamic-page tool is valid routing. Only unconditional retry of // a failed fetch is contradictory; JS/login evidence is a different contract. if (/(?:失败|cannot obtain|fails?)[^。\n]{0,60}(?:直接|总是|always|automatically)[^。\n]{0,30}WebBrowser/i.test(fetch)) { conflicts.push({ toolName: 'WebFetch', reason: 'WebFetch description 不应把失败路由到 WebBrowser', }); } if ( !/does not call another model/i.test(fetch) && /process(?:es)?[^\n]{0,40}using an AI model|takes?[^\n]{0,30}prompt as input|performs? hidden summarization/i.test(fetch) ) { conflicts.push({ toolName: 'WebFetch', reason: 'WebFetch description 声称存在实现中没有的模型处理步骤', }); } return conflicts; }