import { sha256, containsForbiddenSecret } from './codec.js'; import { userWrittenSegments } from './userWritten.js'; /** Local, evidence-based guards shared by live and historical extraction. * Flags from the model can narrow eligibility, never override the source. */ export interface AutomaticClaim { statement: string; evidenceQuote: string; lifetime?: 'temporary' | 'durable'; validUntil?: number; sensitivity?: 'normal' | 'sensitive'; } /** A stand-alone affirmation is evidence of agreement, not of the actual proposition. */ export function hasExplicitAffirmation(text: string): boolean { const value = text.normalize('NFKC').trim(); return /^(?:我)?(?:是的?|对的?|没错|同意|确认|按这个|就这样|可以|yes|correct|agree|confirm)(?:采用(?:这个方案)?|这个方案|以上|这样做)?[,。!!.\s]*$/i.test(value); } /** Historical raw memories do not carry an independently authorized antecedent. */ export function isBareHistoricalEvidence(quote: string): boolean { return hasExplicitAffirmation(quote) || /^(?:好的?|行|继续|嗯+|ok(?:ay)?|continue|go on|sure)[。!!.\s]*$/i.test(quote.trim()); } /** Narrow fail-closed guard for the user-fact partition, not a classifier. * A technology name is not an architecture decision; the grammatical subject * must be the project/repository or its explicit engineering convention. */ export function isProjectDecisionInUserFact(statement: string, quote: string, source: string): boolean { const split = (s: string) => s.normalize('NFKC').split(/[。!?;;!?,,\n]+|\.(?=\s|$)/u).map(x => x.trim()).filter(Boolean); const project = (s: string) => /^(?:(?:(?:我们(?:的)?|这个|本|当前|该)?(?:项目|仓库)(?:的)?)(?:(?:默认|始终|统一|必须|决定|确定|已经|只|一律|将)\s*)*(?:使用|采用|用|改用|切换到|依赖|部署在|要求)|(?:(?:本项目|本仓库|项目|仓库)(?:的)?)?(?:技术栈|项目架构|架构方案|测试入口|构建入口|部署方式)(?:统一|默认)?(?:为|是|定为|采用|使用))/.test(s) || /^(?:(?:this|the|our) (?:project|repo(?:sitory)?|codebase) (?:always |only |must |will |now |exclusively )*(?:uses?|adopts?|requires?|runs? on|depends? on|(?:is )?deployed (?:to|on))\b|(?:our|the) (?:project architecture|tech stack|build command|test command|deployment target) is\b)/i.test(s); if (split(statement).some(project) || split(quote).some(project)) return true; // A short quote such as "use Bun" must not strip "this repo must" from // its own clause. Equally, a neighboring project's decision is not evidence // about a separate preference; fail closed only on unambiguous matches. const needle = quote.normalize('NFKC').trim().replace(/[。.!!??]+$/u, ''); const clauses = needle ? userWrittenSegments(source).flatMap(split).filter(s => s.includes(needle)) : []; return clauses.length > 0 && clauses.every(project); } export function evidenceContext(text: string, quote: string): string { const needle = quote.trim().replace(/[。!?;;!?.]+$/u, ''); const parts = userWrittenSegments(text).flatMap((s) => s.split(/[。!?;;!?\n]+|\.(?=\s|$)/u), ); const context = parts.filter((s) => needle && s.includes(needle)); return context.length ? context.join('\n') : quote; } export function sourceAnchor( session: string, message: string, quote: string, text = quote, ): string | undefined { if ( !session || !message || session === 'unknown' || message === 'unknown' || !quote.trim() ) return undefined; // Never bind two clauses from the same message merely because they share an ID. const q = quote.trim().replace(/[。!?;;!?.]+$/u, ''); if (!q || /^(?:好的?|是的?|同意|确认|没错|对|可以|yes|ok|correct|agree)$/i.test(q)) return undefined; const clauses = userWrittenSegments(text) .flatMap((s) => s.split(/[。!?;;!?,,\n]+|\.(?=\s|$)/u)) .map((s) => s.trim()) .filter((s) => q && s.includes(q)); // Only expand a short quote across a known speaker/frequency prefix. An // arbitrary neighboring assertion in the same sentence is not its identity. const clause = clauses.length === 1 ? clauses[0] : undefined; const prefix = clause?.endsWith(q) ? clause.slice(0, clause.length - q.length) : undefined; const anchor = clause && prefix !== undefined && /^(?:我(?:们)?|长期|通常|一直|一般|默认|\bI\s+|\bwe\s+|usually\s+|always\s+)*$/i.test(prefix) ? clause : q; return sha256( JSON.stringify([ session, message, anchor.normalize('NFKC').toLowerCase().trim(), ]), ); } export function automaticClaimIssue( claim: AutomaticClaim, text: string, now = Date.now(), sourceAt = now, ): string | undefined { const context = evidenceContext(text, claim.evidenceQuote); if ( claim.sensitivity === 'sensitive' || containsForbiddenSecret(context + '\n' + claim.statement) || /身份证号|银行卡号|家庭住址|确诊|诊断为|social security number|diagnosed with/i.test( context + '\n' + claim.statement, ) ) return '敏感信息不自动保存'; if ( claim.validUntil !== undefined && (!Number.isFinite(claim.validUntil) || claim.validUntil <= now) ) return '来源已过期'; // A backfill may run days later. Validate explicit relative windows against // the date of the statement, not the model's clock or the processing date. const duration = /(?:接下来|未来|这|仅限)\s*(\d{1,3}|[一二两三四五六七八九十])\s*(天|周|星期)/.exec( context, ); if (duration && claim.validUntil !== undefined) { const numeral = duration[1]!.replace('两', '二'); const amount = Number(numeral) || '零一二三四五六七八九十'.indexOf(numeral); const days = amount * (duration[2] === '天' ? 1 : 7); if (days > 0 && claim.validUntil > sourceAt + days * 86_400_000) return '到期时间超出原话限定的期间'; } if ( (duration || claim.lifetime === 'temporary' || /这一次|仅这次|这次只|本次只|仅限|这[一二两三四五六七八九十\d]*(?:天|周|星期|个月)|本周|本月|暂时|this (?:time|week|month) only|for (?:this|the next) (?:week|month)/i.test( context, )) && claim.validUntil === undefined ) return '临时状态无有效期限'; return undefined; } export const automaticPolicyPrompt = '敏感信息不自动保存。临时约束必须标 lifetime=temporary 和用户原话支持的 validUntil(Unix毫秒);不明确则跳过。项目决定归项目知识,不当作全局偏好。';