import { countTextTokens } from '../context/tokenCounter.js'; import { DEFAULT_REVIEW_WINDOWS } from './constants.js'; import type { MemoryRecordV2, MemorySettings, MemorySnapshot, } from './types.js'; import { BM25_DOCUMENT_THRESHOLD, Bm25Index, recordSearchIndexBuild, recordSearchIndexCacheHit, recordSearchIndexFallback, recordSearchStrategy, searchTerms, } from './searchIndex.js'; const snapshotIndexes = new WeakMap(); export function memoryTerms(query: string): string[] { return searchTerms(query); } /** * Stable personal facts keep their force however old they are. A preference * like "always answer in Chinese" does not expire by calendar: age used to * relabel it "待复核,不能当作当前已确认事实" after the review window, and * restating it never refreshed the clock, so a standing preference silently * stopped binding after six months. Project/decision/topic records change with * the work, so for them age is a real signal. Only the injected label and the * ranking penalty use this; `isReviewDue` still feeds the user's review queue. */ export function agingDowngrades(record: MemoryRecordV2): boolean { return record.category !== 'preference' && record.category !== 'profile'; } /** The label and ranking view of staleness: explicit marks always count, age only where it is evidence. */ export function isUnconfirmed( record: MemoryRecordV2, settings: MemorySettings, now = Date.now(), ): boolean { return record.status === 'needs_review' || (agingDowngrades(record) && isReviewDue(record, settings, now)); } export function isReviewDue( record: MemoryRecordV2, settings: MemorySettings, now = Date.now(), ): boolean { const days = settings.reviewAfterDays?.[record.category] ?? DEFAULT_REVIEW_WINDOWS[record.category]; return now - record.lastConfirmedAt > days * 86_400_000; } export function scoreMemory( record: MemoryRecordV2, query: string, settings: MemorySettings, ): number { if (record.status === 'superseded' || (record.validUntil !== undefined && record.validUntil <= Date.now())) return Number.NEGATIVE_INFINITY; const stalePenalty = isUnconfirmed(record, settings) ? 8 : 0; const { terms, phrase } = substringParts(record, query); return terms + phrase - stalePenalty + record.lastConfirmedAt / 1e13; } /** Substring evidence: 10 per matching query term, 25 for the whole phrase. */ function substringParts(record: MemoryRecordV2, query: string): { terms: number; phrase: number } { const haystack = `${record.category} ${record.subject} ${record.topicKey} ${record.aliases.join(' ')} ${record.statement}`.normalize('NFKC').toLocaleLowerCase(); const lexical = memoryTerms(query).reduce( (sum, term) => sum + (haystack.includes(term) ? 10 : 0), 0, ); const phrase = query.trim() && haystack.includes(query.trim().normalize('NFKC').toLocaleLowerCase()) ? 25 : 0; return { terms: lexical, phrase }; } export function recallFromSnapshot( snapshot: MemorySnapshot, query: string, settings: MemorySettings, limit: number, /** * 注入资格谓词在**限额之前**应用。调用方若先取 N 条再过滤,前 N 条全是 * 偏好/画像/敏感记录时,真正可用的事实就永远排不进候选,等于限额在过滤前生效。 */ filter?: (record: MemoryRecordV2) => boolean, ): MemoryRecordV2[] { const eligible = snapshot.records.filter((record) => record.status !== 'superseded' && (record.validUntil === undefined || record.validUntil > Date.now())); if (!query.trim() || eligible.length < BM25_DOCUMENT_THRESHOLD) { recordSearchStrategy('lexical', eligible.length); return snapshot.records .map((record) => ({ record, score: scoreMemory(record, query, settings) })) .filter( (item) => Number.isFinite(item.score) && (!query.trim() || item.score >= 2), ) .filter((item) => !filter || filter(item.record)) .sort((a, b) => b.score - a.score) .slice(0, Math.min(100, Math.max(1, limit))) .map((item) => item.record); } try { let index = snapshotIndexes.get(snapshot); if (!index) { index = new Bm25Index(eligible.map((record) => ({ id: record.id, fields: [ { text: record.subject, weight: 4 }, { text: record.aliases.join(' '), weight: 3 }, { text: `${record.topicKey} ${record.category}`, weight: 2 }, { text: record.statement, weight: 1 }, ], }))); snapshotIndexes.set(snapshot, index); recordSearchIndexBuild(); } else { recordSearchIndexCacheHit(); } recordSearchStrategy('bm25', eligible.length); const bm25 = index.search(query); // BM25 only knows whole tokens, so `postgres` never reaches a record that // says `PostgreSQL`; the small-corpus path finds it by substring. Growing // past the threshold must not make a findable record vanish, so substring // hits stay candidates. A token hit keeps its original score (BM25's IDF // is what puts a rare word above two common ones, and the flat per-term // substring bonus would flatten it); substring evidence only scores the // records BM25 could not see. return eligible .map((record) => { const { terms, phrase } = substringParts(record, query); const tokens = bm25.get(record.id) ?? 0; const stalePenalty = isUnconfirmed(record, settings) ? 8 : 0; return { record, hit: tokens > 0 || terms + phrase >= 2, score: (tokens > 0 ? tokens * 10 + phrase : terms + phrase) - stalePenalty + record.lastConfirmedAt / 1e13, }; }) .filter((item) => item.hit) .filter((item) => !filter || filter(item.record)) .sort((a, b) => b.score - a.score) .slice(0, Math.min(100, Math.max(1, limit))) .map((item) => item.record); } catch { recordSearchIndexFallback(); recordSearchStrategy('lexical', eligible.length); return snapshot.records .map((record) => ({ record, score: scoreMemory(record, query, settings) })) .filter((item) => Number.isFinite(item.score) && item.score >= 2) .filter((item) => !filter || filter(item.record)) .sort((a, b) => b.score - a.score) .slice(0, Math.min(100, Math.max(1, limit))) .map((item) => item.record); } } export function takeTokenBudget(lines: string[], maxTokens: number): string[] { const result: string[] = []; let used = 0; for (const line of lines) { const tokens = countTextTokens(line); if (used + tokens > maxTokens) break; result.push(line); used += tokens; } return result; } export function truncateTokenBudget(text: string, maxTokens: number): string { if (countTextTokens(text) <= maxTokens) return text; let low = 0; let high = text.length; while (low < high) { const middle = Math.ceil((low + high) / 2); if (countTextTokens(text.slice(0, middle)) <= maxTokens) low = middle; else high = middle - 1; } return `${text.slice(0, low).trimEnd()}…`; }