import { createHash, randomUUID } from 'node:crypto'; import { open, readFile, readdir, stat, unlink } from 'node:fs/promises'; import { dirname, basename, join } from 'node:path'; import { agentStateDir } from '../context/agentHome.js'; import { safeSlice } from '../utils/safeText.js'; import { containsForbiddenSecret, sha256 } from './codec.js'; import { acquireFileLock, appendPrivateLine, atomicWriteFile, ensurePrivateDir, pathExists, } from './fileStore.js'; import { memoryTerms } from './retrieval.js'; import { indexEpisodeTimes } from './episodeTimeIndex.js'; import { BM25_DOCUMENT_THRESHOLD, Bm25Index, recordSearchIndexBuild, recordSearchIndexCacheHit, recordSearchIndexFallback, recordSearchStrategy, } from './searchIndex.js'; import type { ConversationEpisode, ConversationSearchOptions, ConversationSearchResult, ConversationSearchPage, } from './types.js'; const MAX_EPISODE_CHARS = 8_000; /** A longer message keeps this many leading and trailing episodes, never the whole. */ const KEPT_EDGE_PARTS = 2; const MAX_SEARCH_FILES = 200; const MAX_SEARCH_LINES = 20_000; const MAX_SNIPPET_CHARS = 500; /** * 已解析 episode 常驻内存的上限。 * * ⚠️ `episodeFileCache` 缓存的是**整个文件解析出的全部 episode**,而日志本身是只增不减的 * (每条 user/assistant 消息 ≤8000 字符)。没有上限时,Desktop 这种长驻进程搜一次历史就把 * 几十 MB 对话原文永久钉在堆上。按 episode 条数做 LRU,逐出最久未用的文件。 */ const MAX_CACHED_EPISODES = 20_000; /** 两次保留清理之间的最小间隔——清理是尽力而为的后台动作,不该每条消息都扫盘。 */ const RETENTION_SWEEP_INTERVAL_MS = 5 * 60_000; interface CachedEpisodeFile { ino: number; size: number; mtimeMs: number; trailing: string; episodes: ConversationEpisode[]; /** 单调递增的使用序号,用于 LRU 逐出(不用时间戳,避免同毫秒并列)。 */ usedAt: number; } interface CachedEpisodeIndex { signature: string; index: Bm25Index; } const episodeFileCache = new Map(); const episodeIndexCache = new Map(); const episodeDiagnostics = { fullFileReads: 0, incrementalFileReads: 0, unchangedFileHits: 0, cacheEvictions: 0, retentionSweeps: 0, }; export function episodeSearchDiagnostics(): Readonly { return { ...episodeDiagnostics }; } export function resetEpisodeSearchDiagnostics(): void { episodeDiagnostics.fullFileReads = 0; episodeDiagnostics.incrementalFileReads = 0; episodeDiagnostics.unchangedFileHits = 0; episodeDiagnostics.cacheEvictions = 0; episodeDiagnostics.retentionSweeps = 0; episodeFileCache.clear(); episodeIndexCache.clear(); cacheClock = 0; retentionSweepStates.clear(); } let cacheClock = 0; interface RetentionSweepState { lastStartedAt: number; lastUsedAt: number; inFlight: boolean; } const retentionSweepStates = new Map(); const MAX_RETENTION_SWEEP_STATES = 128; function cachedEpisodeCount(): number { let total = 0; for (const entry of episodeFileCache.values()) total += entry.episodes.length; return total; } /** 超出 MAX_CACHED_EPISODES 就按最久未用逐出整份文件缓存,直到回到上限之内。 */ function evictEpisodeCache(): void { if (cachedEpisodeCount() <= MAX_CACHED_EPISODES) return; const byAge = [...episodeFileCache.entries()].sort((a, b) => a[1].usedAt - b[1].usedAt); for (const [path] of byAge) { if (cachedEpisodeCount() <= MAX_CACHED_EPISODES) break; episodeFileCache.delete(path); episodeDiagnostics.cacheEvictions += 1; } // 文件缓存变了,基于它建的 BM25 语料签名也就失效了。 episodeIndexCache.clear(); } function episodeRoot(): string { return join(agentStateDir(), 'episodes'); } function validPart(value: string): string { if ( !/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/.test(value) || value.includes('..') ) { throw new Error('会话记忆标识无效'); } return value; } function episodePath(workspaceId: string, sessionId: string): string { return join( episodeRoot(), `workspace-${validPart(workspaceId)}--${validPart(sessionId)}.jsonl`, ); } function backfillMarkerPath(workspaceId: string): string { return join(episodeRoot(), `.backfill-${validPart(workspaceId)}.json`); } function workspaceJournalLockPath(workspaceId: string): string { return join(episodeRoot(), `.workspace-${validPart(workspaceId)}.journal`); } export function sanitizeEpisodeContent(content: string, maxChars = MAX_EPISODE_CHARS): string | null { const normalized = safeSlice( content .replace(/data:[^;\s]+;base64,[A-Za-z0-9+/=]{80,}/g, '[binary omitted]') .replace( /-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/gi, '[secret omitted]', ) .trim(), 0, maxChars, ); if (!normalized || containsForbiddenSecret(normalized)) return null; return normalized; } /** * One message → consecutive episodes of at most MAX_EPISODE_CHARS each. The * per-episode cap is what bounds search memory (the file cache is counted in * episodes), so it stays; but cutting the message itself at the cap lost the * end of long discussions, which is where the decision, the correction and the * acceptance conclusion are. A message longer than the kept edges stores its * head and its tail and says how much of the middle is gone. */ export function splitEpisodeContent(content: string): { text: string; part?: ConversationEpisode['part'] }[] { if (content.length <= MAX_EPISODE_CHARS) return [{ text: content }]; const parts: string[] = []; for (let at = 0; at < content.length; at += MAX_EPISODE_CHARS) parts.push(content.slice(at, at + MAX_EPISODE_CHARS)); const edges = KEPT_EDGE_PARTS * 2; if (parts.length <= edges) return parts.map((text, index) => ({ text, part: { index, total: parts.length } })); const kept = [...parts.slice(0, KEPT_EDGE_PARTS), ...parts.slice(-KEPT_EDGE_PARTS)]; const omittedChars = content.length - kept.reduce((sum, text) => sum + text.length, 0); return kept.map((text, index) => ({ text, part: { index, total: kept.length, ...(index === KEPT_EDGE_PARTS ? { omittedChars } : {}) }, })); } /** Keeps the head and tail of a pathologically large message for the splitter. */ const MAX_MESSAGE_INTAKE_CHARS = 2_000_000; export async function appendConversationEpisode(input: { confirmationEligible?: boolean; pendingLearningToken?: string; learningEligible?: boolean; workspaceId: string; sessionId: string; messageId?: string; role: 'user' | 'assistant'; content: string; createdAt?: number; }, signal?: AbortSignal): Promise { signal?.throwIfAborted(); // Head + tail of an absurd paste are enough for the splitter to keep both edges. const raw = input.content.length > MAX_MESSAGE_INTAKE_CHARS ? `${input.content.slice(0, MAX_MESSAGE_INTAKE_CHARS / 2)}${input.content.slice(-MAX_MESSAGE_INTAKE_CHARS / 2)}` : input.content; const content = sanitizeEpisodeContent(raw, Number.POSITIVE_INFINITY); if (!content) return null; const createdAt = input.createdAt ?? Date.now(); const messageId = input.messageId || randomUUID(); const path = episodePath(input.workspaceId, input.sessionId); await ensurePrivateDir(dirname(path)); let first: ConversationEpisode | null = null; for (const { text, part } of splitEpisodeContent(content)) { const episode: ConversationEpisode = { ...(input.confirmationEligible === true && input.role === 'assistant' ? { confirmationEligible: true } : {}), learningEligible: input.learningEligible === true, ...(input.pendingLearningToken ? { pendingLearningToken: input.pendingLearningToken } : {}), id: randomUUID(), workspaceId: input.workspaceId, sessionId: input.sessionId, messageId, role: input.role, content: text, createdAt, contentHash: sha256(`${input.role}\0${text}`), ...(part ? { part } : {}), }; await appendPrivateLine(path, JSON.stringify(episode), { signal }); first ??= episode; } return first; } // A crash or cancelled turn leaves searchable history but no learning grant. // A random per-attempt token prevents retries sharing a message ID from // authorizing one another. Control lines are not messages in the search index. export async function commitEpisodeLearning(workspaceId: string, sessionId: string, token: string, createdAt: number) { await appendPrivateLine(episodePath(workspaceId, sessionId), JSON.stringify({ learningCommit: token, createdAt })); } function learningCommit(line: string): { learningCommit: string; createdAt: number } | undefined { if (!line.startsWith('{"learningCommit":')) return; try { const row = JSON.parse(line); if (typeof row.learningCommit === 'string' && Number.isFinite(row.createdAt)) return row; } catch { /* incomplete line confers no grant */ } } /** * 显式清空的结构化结果。后台保留期清理(applyEpisodeRetention)仍是 best-effort, * 不走这个类型;只有用户主动「永久清空」需要逐文件/标记的成败回执,避免表面成功、 * 原文却留存或 backfill 标记缺失导致旧会话被重新导入。 */ export interface EpisodeClearResult { /** 成功删除的会话文件数。 */ removed: number; /** 删除失败的文件及原因(典型:Windows 上文件持续忙,重试耗尽)。 */ failed: Array<{ path: string; error: string }>; /** 防回填标记是否已确认在位(无 workspaceId 的全局清空不写标记,记 true)。 */ markerWritten: boolean; } /** 删除某工作区(缺省为全部)的会话原文日志。供 Desktop「清空记忆」一并调用。 */ export async function clearConversationEpisodes( workspaceId?: string, ): Promise { let release: (() => Promise) | null = null; try { release = workspaceId ? await acquireFileLock(workspaceJournalLockPath(workspaceId)) : null; } catch (error) { // 连锁都拿不到(例如目录被占/权限异常)时同样不能假装清空成功。 return { removed: 0, failed: [ { path: episodeRoot(), error: `EPISODE_LOCK_FAILED:${(error as Error).message}`, }, ], markerWritten: false, }; } try { return await clearConversationEpisodesUnlocked(workspaceId); } finally { await release?.(); } } async function clearConversationEpisodesUnlocked( workspaceId?: string, ): Promise { let removed = 0; const failed: EpisodeClearResult['failed'] = []; // 目录枚举失败不能降级成"没有文件":那会让一次读目录错误变成"清空成功", // 而原文其实一条都没动。显式清空必须把它当成失败上报。 let files: string[] = []; try { files = await episodeFiles(workspaceId); } catch (error) { failed.push({ path: episodeRoot(), error: `EPISODE_ENUMERATION_FAILED:${(error as Error).message}`, }); } for (const path of files) { try { const result = await mutateEpisodeFile(path, () => ({ kind: 'delete' })); if (result.changed) removed += 1; // 重试耗尽仍读不稳/改不动:文件还在,必须算失败而不是"已删除"。 else if (result.unstable) { failed.push({ path, error: 'EPISODE_FILE_UNSTABLE:文件持续变化,重试耗尽后未能确认删除', }); } } catch (error) { // 不再吞掉:文件忙/权限问题必须进入回执,让调用方知道原文可能仍在磁盘上。 failed.push({ path, error: (error as Error).message }); } } // ⚠️ backfill 标记必须**留下(没有就补写)**,绝不能删。 // backfillLegacyHistory 会从 `sessions/*.json` 一次性导入旧会话;标记一旦消失, // 下一次 SearchConversations 就会把刚刚清掉的对话原文整批重新导回来 —— 用户点了 // "永久清空",转头又能搜到,等于清空是假的。 let markerWritten = true; if (workspaceId) { try { await atomicWriteFile( backfillMarkerPath(workspaceId), `${JSON.stringify( { version: 1, workspaceId, sources: 0, completedAt: Date.now(), reason: 'cleared-by-user' }, null, 2, )}\n`, ); } catch (error) { markerWritten = false; failed.push({ path: backfillMarkerPath(workspaceId), error: (error as Error).message }); } } episodeIndexCache.clear(); return { removed, failed, markerWritten }; } interface StableEpisodeFile { raw: string; ino: number; size: number; mtimeMs: number; } type EpisodeFileMutation = | { kind: 'unchanged' } | { kind: 'write'; content: string } | { kind: 'delete' }; interface EpisodeFileMutationResult { changed: boolean; bytes: number; /** * 重试耗尽仍未落定(文件持续被追加/替换)。清空场景必须把它当失败上报, * 否则原文还在磁盘上、调用方却收到成功。保留期清理仍可忽略此标志。 */ unstable?: boolean; } function sameEpisodeFile( left: Pick, right: Pick, ): boolean { return left.ino === right.ino && left.size === right.size && left.mtimeMs === right.mtimeMs; } /** 「文件本来就没了」与「文件一直在变、读不稳」必须分开:前者删除已完成,后者是失败。 */ type StableEpisodeRead = | { kind: 'ok'; file: StableEpisodeFile } | { kind: 'gone' } | { kind: 'unstable' }; async function readStableEpisodeFile(path: string): Promise { for (let attempt = 0; attempt < 2; attempt += 1) { const before = await stat(path).catch((error) => { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null; throw error; }); if (!before) return { kind: 'gone' }; const raw = await readFile(path, 'utf8'); const after = await stat(path).catch(() => null); if (!after) return { kind: 'gone' }; if ( before.ino === after.ino && before.size === after.size && before.mtimeMs === after.mtimeMs && Buffer.byteLength(raw, 'utf8') === after.size ) { return { kind: 'ok', file: { raw, ino: after.ino, size: after.size, mtimeMs: after.mtimeMs }, }; } } return { kind: 'unstable' }; } /** * 与 appendPrivateLine 共用同一把 `.lock`。大文件的解析在锁外完成, * 获锁后只验证文件代际并提交;如果这期间有追加,就重读重算,绝不覆盖新行。 */ async function mutateEpisodeFile( path: string, plan: (raw: string) => EpisodeFileMutation, ): Promise { for (let attempt = 0; attempt < 3; attempt += 1) { const source = await readStableEpisodeFile(path); // 文件已经不存在:删除目标已达成,不算失败。 if (source.kind === 'gone') return { changed: false, bytes: 0 }; // 文件读不稳:立刻进入下一次尝试;三次都读不稳由循环外统一标记失败。 if (source.kind === 'unstable') continue; const mutation = plan(source.file.raw); if (mutation.kind === 'unchanged') return { changed: false, bytes: source.file.size }; const release = await acquireFileLock(path); try { const live = await stat(path).catch(() => null); if (!live || !sameEpisodeFile(source.file, live)) continue; if (mutation.kind === 'delete') await unlink(path); else await atomicWriteFile(path, mutation.content); episodeFileCache.delete(path); episodeIndexCache.clear(); return { changed: true, bytes: mutation.kind === 'write' ? Buffer.byteLength(mutation.content, 'utf8') : 0, }; } finally { await release(); } } // 文件持续变化时跳过本轮维护;保留扫描下次会再处理。 const current = await stat(path).catch(() => null); // 此刻已消失,说明目标其实达成了。 if (!current) return { changed: false, bytes: 0 }; return { changed: false, bytes: current.size, unstable: true }; } /** 列出某工作区(或全部)的会话原文日志文件。 */ async function episodeFiles(workspaceId?: string): Promise { const prefix = workspaceId ? `workspace-${validPart(workspaceId)}--` : 'workspace-'; try { return (await readdir(episodeRoot(), { withFileTypes: true })) .filter((entry) => entry.isFile() && entry.name.endsWith('.jsonl') && entry.name.startsWith(prefix)) .map((entry) => join(episodeRoot(), entry.name)); } catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return []; throw error; } } export interface SessionActivitySummary { sessionId: string; /** 该会话最后一条有效记录的时间。 */ lastActivityAt: number; /** 去重后的消息条数;一条长消息拆成多段只算一条。 */ messageCount: number; } /** * 列出某工作区里可用于记忆提炼的历史会话。 * * 不经过搜索缓存:后台提炼是长驻进程里的周期性动作,不能为了算最后活动时间 * 把几十 MB 原文钉进堆里。按 mtime 先剪枝——mtime 一定不早于文件内任何一条 * `createdAt`,所以「比窗口更旧」的文件不必读。 */ export async function listConversationSessions( workspaceId: string, options: { since?: number; signal?: AbortSignal } = {}, ): Promise { options.signal?.throwIfAborted(); const prefix = `workspace-${validPart(workspaceId)}--`; const sessions: SessionActivitySummary[] = []; for (const path of await episodeFiles(workspaceId)) { options.signal?.throwIfAborted(); const name = basename(path); if (!name.startsWith(prefix) || !name.endsWith('.jsonl')) continue; const sessionId = name.slice(prefix.length, -'.jsonl'.length); if (!sessionId) continue; const info = await stat(path).catch(() => null); if (!info) continue; if (options.since !== undefined && info.mtimeMs < options.since) continue; const read = await readStableEpisodeFile(path).catch(() => null); // 读不稳或刚好被删:本轮跳过,下次维护再说。 if (!read || read.kind !== 'ok') continue; let lastActivityAt = 0; const messageIds = new Set(); for (const line of read.file.raw.split('\n')) { const episode = line ? parseEpisode(line) : null; if (!episode) continue; messageIds.add(episode.messageId); if (episode.createdAt > lastActivityAt) lastActivityAt = episode.createdAt; } if (!messageIds.size) continue; sessions.push({ sessionId, lastActivityAt, messageCount: messageIds.size }); } return sessions.sort( (a, b) => b.lastActivityAt - a.lastActivityAt || a.sessionId.localeCompare(b.sessionId), ); } export interface TranscriptMessage { messageId: string; role: 'user' | 'assistant'; text: string; /** 这条消息自身的时间。遗忘屏障用它比较,不能用整个会话的最后活动时间。 */ createdAt: number; } export interface ConversationTranscript { messages: TranscriptMessage[]; /** 拼给模型的纯文本;超限时只保留最近的对话。 */ text: string; truncated: boolean; } /** Resolve only a single authorized answer. Never substitute an older answer * for a disabled, deleted, truncated or ambiguously replayed source. */ export async function readConfirmationContext( workspaceId: string, sessionId: string, messageId: string, cutoff: number, ): Promise<{ text: string; createdAt: number } | undefined> { const read = await readStableEpisodeFile(episodePath(workspaceId, sessionId)); if (read.kind === 'gone') return; if (read.kind === 'unstable') throw new Error('确认来源正在变化,稍后重试'); let tail = ''; let createdAt = 0; let count = 0; let expected = 0; for (const line of read.file.raw.split('\n')) { const episode = line && parseEpisode(line); if (!episode || episode.messageId !== messageId) continue; if (episode.workspaceId !== workspaceId || episode.sessionId !== sessionId || episode.role !== 'assistant' || episode.confirmationEligible !== true || episode.pendingLearningToken || episode.createdAt < cutoff || containsForbiddenSecret(episode.content)) return; if (!count) { expected = episode.part?.total ?? 1; createdAt = episode.createdAt; } else if (episode.createdAt !== createdAt) return; if ((episode.part?.index ?? 0) !== count || (episode.part?.total ?? 1) !== expected) return; // Omission means the next part is not adjacent to what precedes it. if (episode.part?.omittedChars) tail = ''; tail = (tail + episode.content).slice(-4000); count++; } return count && count === expected && !containsForbiddenSecret(tail) ? {text: tail, createdAt} : undefined; } /** * 把一次历史会话的原文还原成按消息分组的顺序文本。 * * 超长会话只保留最近部分:更早的回合通常已被后续对话覆盖,而且截断必须 * 整条消息地丢,不能把一句话切成两半——否则证据引用校验会失真。 */ export async function readConversationTranscript( workspaceId: string, sessionId: string, options: { maxChars?: number; signal?: AbortSignal; learningOnly?: boolean } = {}, ): Promise { options.signal?.throwIfAborted(); const read = await readStableEpisodeFile(episodePath(workspaceId, sessionId)); if (read.kind === 'gone') return { messages: [], text: '', truncated: false }; if (read.kind === 'unstable') throw new Error('CONVERSATION_TRANSCRIPT_UNSTABLE:会话原文持续变化,本轮不提炼'); const maxChars = options.maxChars ?? 60_000; const messages: TranscriptMessage[] = []; const byId = new Map(); const lines = read.file.raw.split('\n'); const grants = options.learningOnly ? new Set(lines.flatMap(line => { const grant = learningCommit(line); return grant ? [grant.learningCommit] : []; })) : undefined; for (const line of lines) { const episode = line ? parseEpisode(line) : null; if (!episode) continue; if (grants && (episode.learningEligible !== true || (episode.pendingLearningToken && !grants.has(episode.pendingLearningToken)))) continue; const existing = byId.get(episode.messageId); if (existing && existing.role === episode.role) { // 同一条长消息被拆成多段落盘,按原顺序拼回去。中段被丢弃时插入显式 // 省略标记:直接拼接会制造出原文里根本不存在的「逐字引文」。 if (episode.part?.omittedChars) existing.text += `\n[…中间省略 ${episode.part.omittedChars} 字…]\n`; existing.text += episode.content; continue; } const message: TranscriptMessage = { messageId: episode.messageId, role: episode.role, text: episode.content, createdAt: episode.createdAt, }; byId.set(episode.messageId, message); messages.push(message); } const render = (m: TranscriptMessage) => options.learningOnly ? `[${m.role} at ${new Date(m.createdAt).toISOString()}] ${m.text}` : `[${m.role}] ${m.text}`; let total = 0; let start = messages.length; while (start > 0) { const size = render(messages[start - 1]!).length + (start < messages.length ? 2 : 0); // 至少保留最后一条,哪怕它自己就超过预算。 if (total + size > maxChars && (options.learningOnly || start < messages.length)) break; total += size; start -= 1; } const kept = messages.slice(start); return { messages: kept, text: kept.map(render).join('\n\n'), truncated: start > 0, }; } /** 按龄清理一个文件;返回清理后的字节数(文件被清空则删除并返回 0)。 */ async function pruneFileByAge(path: string, cutoff: number): Promise { const result = await mutateEpisodeFile(path, (raw) => { const lines = raw.split('\n').filter((line) => line.trim().length > 0); const kept = lines.filter((line) => { const episode = parseEpisode(line); // 解析不出来的行按"保留"处理:清理是维护动作,不该顺手吞掉看不懂的数据。 const row = episode ?? learningCommit(line); return row ? row.createdAt >= cutoff : true; }); if (kept.length === lines.length) return { kind: 'unchanged' }; if (kept.length === 0) return { kind: 'delete' }; return { kind: 'write', content: `${kept.join('\n')}\n` }; }); return result.bytes; } /** * 会话原文保留策略:先按龄清理,仍超体积上限就从**最旧的文件**整份删起。 * * 全程 best-effort:清理失败绝不能影响正在进行的对话(这是维护动作,不是功能)。 * 与 records 的删除语义严格区分——records 只有用户能删,这里删的是为检索而留的对话副本。 */ export async function applyEpisodeRetention( workspaceId: string, retention: { episodeDays: number; episodeMaxMegabytes: number }, now = Date.now(), ): Promise { const files = await episodeFiles(workspaceId).catch(() => []); if (!files.length) return; episodeDiagnostics.retentionSweeps += 1; const cutoff = now - retention.episodeDays * 86_400_000; const sized: Array<{ path: string; bytes: number; mtimeMs: number }> = []; for (const path of files) { const bytes = await pruneFileByAge(path, cutoff).catch(() => -1); if (bytes <= 0) continue; const info = await stat(path).catch(() => null); sized.push({ path, bytes, mtimeMs: info?.mtimeMs ?? 0 }); } const limit = retention.episodeMaxMegabytes * 1024 * 1024; let total = sized.reduce((sum, item) => sum + item.bytes, 0); if (total <= limit) return; // 从最旧的文件开始按**条目**裁剪,而不是整份删除: // 一个工作区常常只有一个长期会话文件,整份删会让全部历史在某次追加后突然消失(悬崖), // 而按条目裁剪的结果是"最旧的对话先被丢掉",与按龄清理的语义一致。 for (const item of sized.sort((a, b) => a.mtimeMs - b.mtimeMs)) { if (total <= limit) break; const keepBytes = Math.max(0, item.bytes - (total - limit)); const remaining = await trimFileToNewestBytes(item.path, keepBytes).catch(() => item.bytes); total -= item.bytes - remaining; } episodeIndexCache.clear(); } /** 只保留文件末尾(最新)能放进 keepBytes 的整行;keepBytes 为 0 时删除文件。返回剩余字节数。 */ async function trimFileToNewestBytes(path: string, keepBytes: number): Promise { const result = await mutateEpisodeFile(path, (raw) => { if (keepBytes <= 0) return { kind: 'delete' }; const lines = raw.split('\n').filter((line) => line.trim().length > 0); const kept: string[] = []; let bytes = 0; for (let index = lines.length - 1; index >= 0; index -= 1) { const size = Buffer.byteLength(`${lines[index]}\n`, 'utf8'); if (bytes + size > keepBytes) break; kept.unshift(lines[index]!); bytes += size; } if (!kept.length) return { kind: 'delete' }; if (kept.length === lines.length) return { kind: 'unchanged' }; return { kind: 'write', content: `${kept.join('\n')}\n` }; }); return result.bytes; } /** * 是否该跑一次保留清理(同一进程内每 RETENTION_SWEEP_INTERVAL_MS 最多一次)。 * * 本模块**不自己去读设置**:那需要 `import('./memoryService.js')`,而 memoryService 正好 * 静态 import 本模块,绕一圈会变成动态 import 的循环依赖——dev 下能跑,但 `bun --compile` * 的绿色版打包期解析动态 import 的行为另算,不值得赌(见 GREEN-BUILD 相关教训)。 * 由知道设置的那一层(turnJournal)来问「该扫了吗」,本模块只保留纯粹的存储职责。 */ export function shouldSweepRetention(workspaceId: string, now = Date.now()): boolean { const current = retentionSweepStates.get(workspaceId); if (current?.inFlight || (current && now - current.lastStartedAt < RETENTION_SWEEP_INTERVAL_MS)) { if (current) current.lastUsedAt = now; return false; } retentionSweepStates.set(workspaceId, { lastStartedAt: now, lastUsedAt: now, inFlight: true }); if (retentionSweepStates.size > MAX_RETENTION_SWEEP_STATES) { const victims = [...retentionSweepStates.entries()] .filter(([, state]) => !state.inFlight) .sort((a, b) => a[1].lastUsedAt - b[1].lastUsedAt) .slice(0, retentionSweepStates.size - MAX_RETENTION_SWEEP_STATES); for (const [key] of victims) retentionSweepStates.delete(key); } return true; } export function finishRetentionSweep(workspaceId: string): void { const state = retentionSweepStates.get(workspaceId); if (state) { state.inFlight = false; state.lastUsedAt = Date.now(); } } function parseEpisode(line: string): ConversationEpisode | null { try { const value = JSON.parse(line) as Partial; if ( typeof value.id !== 'string' || typeof value.workspaceId !== 'string' || typeof value.sessionId !== 'string' || typeof value.messageId !== 'string' || (value.role !== 'user' && value.role !== 'assistant') || typeof value.content !== 'string' || typeof value.createdAt !== 'number' || typeof value.contentHash !== 'string' ) return null; return value as ConversationEpisode; } catch { return null; } } function parseEpisodeChunk( chunk: string, trailing = '', ): { episodes: ConversationEpisode[]; trailing: string } { const combined = `${trailing}${chunk}`; const lines = combined.split('\n'); const nextTrailing = lines.pop() ?? ''; return { episodes: lines.flatMap((line) => { const episode = line ? parseEpisode(line) : null; return episode ? [episode] : []; }), trailing: nextTrailing, }; } async function readEpisodeBytes(path: string, offset: number, length: number): Promise { if (length <= 0) return ''; const handle = await open(path, 'r'); try { const buffer = Buffer.alloc(length); const { bytesRead } = await handle.read(buffer, 0, length, offset); return buffer.subarray(0, bytesRead).toString('utf8'); } finally { await handle.close(); } } async function loadEpisodeFile(path: string): Promise { const info = await stat(path); const cached = episodeFileCache.get(path); cacheClock += 1; if ( cached && cached.ino === info.ino && cached.size === info.size && cached.mtimeMs === info.mtimeMs ) { cached.usedAt = cacheClock; episodeDiagnostics.unchangedFileHits += 1; return cached; } if (cached && cached.ino === info.ino && info.size > cached.size) { const chunk = await readEpisodeBytes(path, cached.size, info.size - cached.size); const parsed = parseEpisodeChunk(chunk, cached.trailing); const next = { ino: info.ino, size: info.size, mtimeMs: info.mtimeMs, trailing: parsed.trailing, episodes: [...cached.episodes, ...parsed.episodes], usedAt: cacheClock, }; episodeFileCache.set(path, next); episodeDiagnostics.incrementalFileReads += 1; evictEpisodeCache(); return next; } const raw = await readFile(path, 'utf8'); const parsed = parseEpisodeChunk(raw); const next = { ino: info.ino, size: info.size, mtimeMs: info.mtimeMs, trailing: parsed.trailing, episodes: parsed.episodes, usedAt: cacheClock, }; episodeFileCache.set(path, next); episodeDiagnostics.fullFileReads += 1; evictEpisodeCache(); return next; } function persistedMessageText(message: unknown): { role: 'user' | 'assistant'; content: string; messageId?: string; createdAt?: number; } | null { if (!message || typeof message !== 'object') return null; const item = message as Record; if (item.role !== 'user' && item.role !== 'assistant') return null; let content = ''; if (typeof item.content === 'string') content = item.content; else if (Array.isArray(item.content)) { content = item.content .filter((part): part is { type: 'text'; text: string } => Boolean( part && typeof part === 'object' && (part as { type?: unknown }).type === 'text' && typeof (part as { text?: unknown }).text === 'string', ), ) .map((part) => part.text) .join('\n'); } if (!content.trim()) return null; return { role: item.role, content, ...(typeof item.id === 'string' ? { messageId: item.id } : {}), ...(typeof item.timestamp === 'number' ? { createdAt: item.timestamp } : {}), }; } async function workspaceArchiveDirs(workspaceId: string): Promise { try { const index = JSON.parse( await readFile(join(agentStateDir(), 'workspace-index.json'), 'utf8'), ) as { workspaces?: Array<{ id?: string; canonicalPath?: string; displayPath?: string; pathAliases?: string[]; }>; }; const workspace = index.workspaces?.find((item) => item.id === workspaceId); if (!workspace) return []; const paths = [ workspace.canonicalPath, workspace.displayPath, ...(workspace.pathAliases ?? []), ].filter((value): value is string => typeof value === 'string'); return Array.from( new Set( paths.map((path) => join( agentStateDir(), 'archive', createHash('sha1').update(path).digest('hex').slice(0, 12), ), ), ), ); } catch { return []; } } async function backfillLegacyHistory(workspaceId: string, signal?: AbortSignal): Promise { const release = await acquireFileLock(workspaceJournalLockPath(workspaceId), signal); try { await backfillLegacyHistoryUnlocked(workspaceId, signal); } finally { await release(); } } async function backfillLegacyHistoryUnlocked(workspaceId: string, signal?: AbortSignal): Promise { signal?.throwIfAborted(); const marker = backfillMarkerPath(workspaceId); try { const previous = JSON.parse(await readFile(marker, { encoding: 'utf8', signal })); // Never resurrect history explicitly cleared by the user. Older completed // migrations may have silently stopped after 200 files; finish those once. if (previous.version === 2 || previous.reason === 'cleared-by-user') return; } catch { signal?.throwIfAborted(); /* Missing or corrupt migration marker: rebuild from source. */ } const sources: Array<{ path: string; sessionId: string }> = []; const sessionsDir = join(agentStateDir(), 'sessions'); try { for (const entry of await readdir(sessionsDir, { withFileTypes: true })) { signal?.throwIfAborted(); const prefix = `workspace-${validPart(workspaceId)}--`; if ( entry.isFile() && entry.name.startsWith(prefix) && entry.name.endsWith('.json') ) { sources.push({ path: join(sessionsDir, entry.name), sessionId: entry.name.slice(prefix.length, -'.json'.length), }); } } } catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; } for (const dir of await workspaceArchiveDirs(workspaceId)) { signal?.throwIfAborted(); try { for (const entry of await readdir(dir, { withFileTypes: true })) { if (entry.isFile() && entry.name.endsWith('.json')) { sources.push({ path: join(dir, entry.name), sessionId: `archive-${entry.name.slice(0, -5)}`, }); } } } catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; } } // Stable order makes interrupted migrations resume predictably across filesystems. sources.sort((a, b) => a.path.localeCompare(b.path)); for (const source of sources) { signal?.throwIfAborted(); let parsed: { messages?: unknown[] }; try { parsed = JSON.parse(await readFile(source.path, { encoding: 'utf8', signal })) as { messages?: unknown[]; }; } catch { signal?.throwIfAborted(); continue; } if (!Array.isArray(parsed.messages)) continue; // A canceled migration keeps completed appends. Match existing message IDs // and consume legacy content occurrences so resuming does not duplicate them. const existing = await loadEpisodeFile(episodePath(workspaceId, source.sessionId)).catch(error => { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null; throw error; }); const ids = new Set(existing?.episodes.map(episode => episode.messageId)); const occurrences = new Map(); for (const episode of existing?.episodes ?? []) { occurrences.set(episode.contentHash, (occurrences.get(episode.contentHash) ?? 0) + 1); } for (const [index, message] of parsed.messages.entries()) { signal?.throwIfAborted(); const extracted = persistedMessageText(message); if (!extracted) continue; const content = sanitizeEpisodeContent(extracted.content); if (!content) continue; const contentHash = sha256(`${extracted.role}\0${content}`); const messageId = extracted.messageId || `legacy-${sha256(`${source.sessionId}:${index}`)}`; const remaining = occurrences.get(contentHash) ?? 0; if (ids.has(messageId) || (!extracted.messageId && remaining > 0)) { if (remaining > 0) occurrences.set(contentHash, remaining - 1); continue; } await appendConversationEpisode({ workspaceId, sessionId: source.sessionId, ...extracted, messageId, }, signal); ids.add(messageId); } } signal?.throwIfAborted(); await atomicWriteFile( marker, `${JSON.stringify( { version: 2, workspaceId, sources: sources.length, completedAt: Date.now(), }, null, 2, )}\n`, ); } function searchScore(episode: ConversationEpisode, query: string): number { const haystack = episode.content.toLocaleLowerCase(); const normalized = query.trim().toLocaleLowerCase(); const terms = memoryTerms(query); const coverage = terms.length ? terms.filter((term) => haystack.includes(term)).length / terms.length : 0; const phrase = normalized && haystack.includes(normalized) ? 35 : 0; const roleWeight = episode.role === 'user' ? 4 : 0; return phrase + coverage * 30 + roleWeight + episode.createdAt / 1e13; } export async function searchConversationEpisodes(query: string, options: ConversationSearchOptions): Promise { return (await searchConversationPage(query, options)).results; } interface EpisodeCursor { contract: string; snapshot: string; file: number; line: number; offset: number } export async function searchConversationPage(query: string, options: ConversationSearchOptions): Promise { options.signal?.throwIfAborted(); if (options.scope === 'all' && !options.explicitCrossWorkspace) { throw new Error('跨工作区历史检索需要当前用户明确授权'); } if (options.scope === 'all') { try { const index = JSON.parse( await readFile(join(agentStateDir(), 'workspace-index.json'), 'utf8'), ) as { workspaces?: Array<{ id?: string }> }; for (const workspace of index.workspaces ?? []) { if (typeof workspace.id === 'string') await backfillLegacyHistory(workspace.id, options.signal); } } catch { options.signal?.throwIfAborted(); await backfillLegacyHistory(options.workspaceId, options.signal); } } else { await backfillLegacyHistory(options.workspaceId, options.signal); } const root = episodeRoot(); const names = (await readdir(root, { withFileTypes: true }).catch(error => { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return []; throw error; })).filter(entry => entry.isFile() && entry.name.endsWith('.jsonl')) .map(entry => entry.name) .filter(name => options.scope === 'all' || name.startsWith(`workspace-${validPart(options.workspaceId)}--`)) .filter(name => !options.sessionId || name.endsWith(`--${validPart(options.sessionId)}.jsonl`)) .sort(); const indexed = await indexEpisodeTimes(root, names, loadEpisodeFile, options.signal); const entries = indexed.entries.filter(entry => entry.count > 0 && (options.after === undefined || entry.newest >= options.after) && (options.before === undefined || entry.oldest <= options.before)) .sort((a, b) => b.newest - a.newest || a.name.localeCompare(b.name)); const contract = sha256(JSON.stringify([query, options.scope ?? 'workspace', options.workspaceId, options.sessionId ?? null, options.after ?? null, options.before ?? null])); const snapshot = sha256(JSON.stringify([entries, indexed.failed])); let start: EpisodeCursor = { contract, snapshot, file: 0, line: 0, offset: 0 }; if (options.cursor) { try { const cursor = JSON.parse(Buffer.from(options.cursor, 'base64url').toString('utf8')); if (cursor.contract !== contract || cursor.snapshot !== snapshot || ![cursor.file, cursor.line, cursor.offset].every(n => Number.isSafeInteger(n) && n >= 0) || cursor.file > entries.length) throw new Error(); start = cursor; } catch { throw new Error('历史分页游标失效或查询条件已改变,请不带 cursor 重新搜索;不能继续旧快照。'); } } const encode = (position: Pick) => Buffer.from(JSON.stringify({ contract, snapshot, ...position })).toString('base64url'); const episodes: ConversationEpisode[] = []; const dedupe = new Set(); let file = start.file; let line = start.line; let searchedFiles = 0; while (file < entries.length && searchedFiles < MAX_SEARCH_FILES && episodes.length < MAX_SEARCH_LINES) { options.signal?.throwIfAborted(); const entry = entries[file]!; const cached = indexed.loaded.get(entry.name) ?? await loadEpisodeFile(join(root, entry.name)); if (cached.ino !== entry.ino || cached.size !== entry.size || cached.mtimeMs !== entry.mtimeMs) { throw new Error('历史文件在检索中发生变化,请不带 cursor 重新搜索。'); } const candidates = cached.episodes.filter(episode => (!options.sessionId || episode.sessionId === options.sessionId) && (options.after === undefined || episode.createdAt >= options.after) && (options.before === undefined || episode.createdAt <= options.before)) .sort((a, b) => b.createdAt - a.createdAt || a.id.localeCompare(b.id)); searchedFiles++; for (; line < candidates.length && episodes.length < MAX_SEARCH_LINES; line++) { const episode = candidates[line]!; const identity = `${episode.workspaceId}/${episode.sessionId}/${episode.id}`; if (!dedupe.has(identity)) { dedupe.add(identity); episodes.push(episode); } } if (line >= candidates.length) { file++; line = 0; } } const batchIdentity = `${start.file}:${start.line}`; const ranked = rankConversationEpisodes(episodes, query, options, snapshot, batchIdentity); const limit = Math.min(20, Math.max(1, options.limit ?? 8)); const results = ranked.slice(start.offset, start.offset + limit); const offset = start.offset + results.length; const nextCursor = offset < ranked.length ? encode({ file: start.file, line: start.line, offset }) : file < entries.length ? encode({ file, line, offset: 0 }) : null; return { results, nextCursor, coverage: { candidateFiles: entries.length, searchedFiles, searchedMessages: episodes.length, unreadableFiles: indexed.failed, exhausted: nextCursor === null } }; } function rankConversationEpisodes(episodes: ConversationEpisode[], query: string, options: ConversationSearchOptions, signature: string, batchIdentity: string): ConversationSearchResult[] { if (!query.trim()) return episodes.sort((a, b) => b.createdAt - a.createdAt) .map(episode => conversationResult(episode, 0, query)); if (episodes.length < BM25_DOCUMENT_THRESHOLD) { recordSearchStrategy('lexical', episodes.length); return episodes .map((episode) => ({ episode, score: searchScore(episode, query) })) .filter((item) => item.score >= 6) .sort((a, b) => b.score - a.score) .map(({ episode, score }) => conversationResult(episode, score, query)); } try { const corpusKey = JSON.stringify([ options.scope ?? 'workspace', options.workspaceId, options.sessionId ?? '', options.after ?? null, options.before ?? null, batchIdentity, ]); let cachedIndex = episodeIndexCache.get(corpusKey); if (!cachedIndex || cachedIndex.signature !== signature) { cachedIndex = { signature, index: new Bm25Index(episodes.map((episode) => ({ id: episode.id, fields: [{ text: episode.content, weight: 1 }], }))), }; episodeIndexCache.set(corpusKey, cachedIndex); if (episodeIndexCache.size > 4) episodeIndexCache.delete(episodeIndexCache.keys().next().value!); recordSearchIndexBuild(); } else { recordSearchIndexCacheHit(); } recordSearchStrategy('bm25', episodes.length); const scores = cachedIndex.index.search(query); const normalized = query.trim().toLocaleLowerCase(); return episodes .map((episode) => { const bm25 = scores.get(episode.id) ?? 0; const phrase = normalized && episode.content.toLocaleLowerCase().includes(normalized) ? 35 : 0; const roleWeight = episode.role === 'user' ? 4 : 0; // Same rule as memory records: BM25 matches whole tokens only, so a // substring hit (`postgres` in `postgresql`) that the small-corpus // path finds must not vanish once the corpus passes the threshold. const substring = bm25 > 0 ? 0 : searchScore(episode, query); return { episode, bm25, substring, score: bm25 * 10 + phrase + roleWeight + episode.createdAt / 1e13 + substring }; }) .filter((item) => item.bm25 > 0 || item.substring >= 6) .sort((a, b) => b.score - a.score) .map(({ episode, score }) => conversationResult(episode, score, query)); } catch { recordSearchIndexFallback(); recordSearchStrategy('lexical', episodes.length); return episodes .map((episode) => ({ episode, score: searchScore(episode, query) })) .filter((item) => item.score >= 6) .sort((a, b) => b.score - a.score) .map(({ episode, score }) => conversationResult(episode, score, query)); } } function conversationResult( episode: ConversationEpisode, score: number, query: string, ): ConversationSearchResult { const lower = episode.content.toLocaleLowerCase(); const hits = [query.trim().toLocaleLowerCase(), ...memoryTerms(query)] .filter(Boolean).map(term => lower.indexOf(term)).filter(index => index >= 0); const start = Math.max(0, (hits.length ? Math.min(...hits) : 0) - 120); const end = Math.min(episode.content.length, start + MAX_SNIPPET_CHARS); return { ...episode, score, snippet: `${start ? '…' : ''}${episode.content.slice(start, end)}${end < episode.content.length ? '…' : ''}`, }; } /** Open a precise search hit; neighbor IDs support focused context expansion. * This is the persisted text journal, not a promise of full tool/image history. */ export async function readConversationEpisode(workspaceId: string, sessionId: string, episodeId: string, signal?: AbortSignal) { await backfillLegacyHistory(workspaceId, signal); signal?.throwIfAborted(); const file = await loadEpisodeFile(episodePath(workspaceId, sessionId)).catch(error => { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null; throw error; }); const index = file?.episodes.findIndex(episode => episode.id === episodeId) ?? -1; if (!file || index < 0) return null; return { episode: file.episodes[index]!, previousId: file.episodes[index - 1]?.id ?? null, nextId: file.episodes[index + 1]?.id ?? null, sourceKind: 'persisted-conversation-text' as const, limitation: `这是持久化会话文本,不含工具和图片原文;超过 ${MAX_EPISODE_CHARS} 字符的消息会拆成相邻的多段(episode.part 标出序号),过长时只保留开头和结尾、part.omittedChars 标出丢掉的中段;不保证完整原始消息。`, }; } export const episodicMemoryService = { append: appendConversationEpisode, search: searchConversationEpisodes, searchPage: searchConversationPage, read: readConversationEpisode, clear: clearConversationEpisodes, applyRetention: applyEpisodeRetention, };