/** Durable alternatives, not another authoritative memory store. */ import { readdir, readFile } from 'node:fs/promises'; import { join } from 'node:path'; import { memoryService } from './memoryService.js'; import { sha256, validateMemoryInput } from './codec.js'; import { acquireFileLock, atomicWriteFile, memoryRootDir, scopeDirectory, } from './fileStore.js'; import type { MemoryRecord, VersionedMemoryRecord } from './types.js'; import { assertAutomaticFactAllowed, assertSourceAllowed, withFactBarriers, } from './factGovernance.js'; export interface FactCandidate { id: string; status: 'open' | 'accepted' | 'rejected'; reason: string; createdAt: number; proposed: Omit; old?: { id: string; version: string; statement: string }; } const pathFor = (workspaceId: string) => join(scopeDirectory('workspace', workspaceId), 'fact-candidates.json'); export async function factCandidates( workspaceId: string, ): Promise { const raw = await readFile(pathFor(workspaceId), 'utf8').catch((error) => { if (error.code !== 'ENOENT') throw error; return '[]'; }); const result = JSON.parse(raw); if (!Array.isArray(result)) throw new Error('事实候选文件损坏'); for (const item of result) { if (!item.id || !['open', 'accepted', 'rejected'].includes(item.status)) throw new Error('事实候选结构错误'); validateMemoryInput(item.proposed); } return result; } export async function retainFactCandidate( workspaceId: string, proposed: FactCandidate['proposed'], reason: string, old?: VersionedMemoryRecord, startedAt = Date.now(), signal?: AbortSignal, ) { const persist = async () => { const release = await acquireFileLock(pathFor(workspaceId), signal); try { const items = await factCandidates(workspaceId); const id = sha256( JSON.stringify([ proposed.sourceSessionId, proposed.sourceMessageId, proposed.scope, proposed.subject, proposed.statement, ]), ); if (!items.some((item) => item.id === id)) { items.push({ id, status: 'open', createdAt: Date.now(), reason, proposed, old: old ? { id: old.record.id, version: old.version, statement: old.record.statement, } : undefined, }); // Keep every open review and a bounded audit tail; resolved candidates // are historical evidence, not an ever-growing queue. const open = items.filter((item) => item.status === 'open'); const resolved = items .filter((item) => item.status !== 'open') .slice(-200); items.splice(0, items.length, ...open, ...resolved); signal?.throwIfAborted(); await atomicWriteFile( pathFor(workspaceId), JSON.stringify(items) + '\n', ); } return id; } finally { await release(); } }; return withFactBarriers('workspace', workspaceId, async (barriers) => { assertAutomaticFactAllowed(barriers, proposed, startedAt); if (proposed.scope === 'personal') return withFactBarriers('personal', undefined, async (personal) => { assertAutomaticFactAllowed(personal, proposed, startedAt); return persist(); }); if (proposed.sourceAnchor) return withFactBarriers('personal',undefined,async personal => { assertSourceAllowed(personal, proposed.sourceAnchor); return persist(); }); return persist(); }); } /** * A change candidate proposes replacing one exact statement. Once the record no * longer says that — the user corrected it (to this proposal or anything else) * or forgot it — the candidate is settled history, not a pending change. * Surfacing it anyway kept "旧=npm" in every prompt and flagged the corrected * record as unconfirmed. This is the single liveness rule for prompts, status * and management views: it holds even when the correction happened in another * workspace, where the candidate file itself cannot be reached. */ export function isLiveFactCandidate( item: FactCandidate, statements: ReadonlyMap, ): boolean { if (item.status !== 'open') return false; if (!item.old) return true; const current = statements.get(item.old.id); return ( current !== undefined && current === item.old.statement && current !== item.proposed.statement ); } /** * Persist the rule above after a record changed. A reconfirmation that keeps * the statement only moves the version: refresh it so accept still works. */ export async function settleFactCandidatesFor( workspaceId: string, record: { id: string; statement: string }, version: string, ) { const release = await acquireFileLock(pathFor(workspaceId)); try { const items = await factCandidates(workspaceId); let changed = false; for (const item of items) { if (item.status !== 'open' || item.old?.id !== record.id) continue; if (record.statement === item.proposed.statement) item.status = 'accepted'; else if (record.statement !== item.old.statement) { item.status = 'rejected'; item.reason = `${item.reason};原记录已被改写为其他内容,候选失效`; } else if (item.old.version !== version) item.old.version = version; else continue; changed = true; } if (changed) await atomicWriteFile(pathFor(workspaceId), JSON.stringify(items) + '\n'); } finally { await release(); } } /** * Forgetting a record must take every candidate hanging off it too — open or * resolved — because each one stores the record's statement in plaintext. * Leaving them would let the forgotten text back into prompts and keep it on * disk, against "forget keeps no original text" (see factGovernance.ts). */ export async function purgeFactCandidatesFor( workspaceId: string, recordId: string, anchors: readonly string[] = [], ) { const release = await acquireFileLock(pathFor(workspaceId)); try { const items = await factCandidates(workspaceId); const kept = items.filter((item) => item.old?.id !== recordId && !(item.proposed.sourceAnchor && anchors.includes(item.proposed.sourceAnchor))); if (kept.length !== items.length) await atomicWriteFile(pathFor(workspaceId), JSON.stringify(kept) + '\n'); } finally { await release(); } } /** * 个人记忆没有单一所属工作区:它的事实候选由各工作区的后台学习分别写入, * 每份候选的 `old.statement` 都留存着该记录的明文。遗忘一条个人记忆时只清当前 * 工作区(旧实现甚至完全不清)会在其他工作区磁盘上留下明文。这里按记录 ID 扫遍 * 全部工作区候选文件;某个工作区清理失败不影响其他工作区,失败项如实上报。 */ export async function purgeFactCandidatesAcrossWorkspaces( recordId: string, anchors: readonly string[] = [], ): Promise<{ purgedWorkspaces: string[]; failed: Array<{ workspaceId: string; error: string }> }> { const root = join(memoryRootDir(), 'workspaces'); const entries = await readdir(root, { withFileTypes: true }).catch((error) => { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return []; throw error; }); const purgedWorkspaces: string[] = []; const failed: Array<{ workspaceId: string; error: string }> = []; for (const entry of entries) { if (!entry.isDirectory() || !/^[a-zA-Z0-9_-]{1,128}$/.test(entry.name)) continue; try { // purgeFactCandidatesFor 自带文件锁与 ENOENT 安全语义;无候选文件时为空操作。 const before = await factCandidates(entry.name).catch(() => []); await purgeFactCandidatesFor(entry.name, recordId, anchors); const derived = anchors.length && await (await import('./projectKnowledge.js')).purgeKnowledgeSource(entry.name, anchors); if (derived || before.some((item) => item.old?.id === recordId || (item.proposed.sourceAnchor && anchors.includes(item.proposed.sourceAnchor)))) purgedWorkspaces.push(entry.name); } catch (error) { failed.push({ workspaceId: entry.name, error: (error as Error).message }); } } return { purgedWorkspaces, failed }; } /** * 按记录范围选择清理面。个人记录与"没有明确工作区"的记录都必须扫全部工作区: * 只清一个工作区会留下别处的明文(旧实现正是先按 workspaceId 分支才漏的)。 */ export async function purgeCandidatesForRecord( recordId: string, scope: 'personal' | 'workspace', workspaceId?: string, anchors: readonly string[] = [], ): Promise<{ purgedWorkspaces: string[]; failed: Array<{ workspaceId: string; error: string }> }> { const sweep: { purgedWorkspaces: string[]; failed: Array<{ workspaceId: string; error: string }> } = scope === 'personal' || !workspaceId ? await purgeFactCandidatesAcrossWorkspaces(recordId, anchors) : { purgedWorkspaces: [], failed: [] }; if (scope === 'workspace' && workspaceId) { try { await purgeFactCandidatesFor(workspaceId, recordId, anchors); if (anchors.length) await (await import('./projectKnowledge.js')).purgeKnowledgeSource(workspaceId, anchors); sweep.purgedWorkspaces.push(workspaceId); } catch (error) { sweep.failed.push({ workspaceId, error: (error as Error).message }); } } if (anchors.length) try { await (await import('./projectKnowledge.js')).purgeKnowledgeSource(undefined, anchors); } catch (error) { sweep.failed.push({ workspaceId: '*global*', error: (error as Error).message }); } return sweep; } /** * 遗忘成功后记录已被删除,重试时无法再从记录反查候选。失败项必须落成一份 * 独立、持久的待办,否则"清理失败"就永久失去补救机会(旧实现只写 stderr)。 */ export interface PendingCandidatePurge { anchors?: string[]; recordId: string; scope: 'personal' | 'workspace'; workspaceId?: string; addedAt: number; attempts: number; lastError?: string; } const pendingPurgePath = () => join(memoryRootDir(), 'pending-candidate-purges.json'); async function readPendingPurges(): Promise { const raw = await readFile(pendingPurgePath(), 'utf8').catch((error) => { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return '[]'; throw error; }); const parsed = JSON.parse(raw); return Array.isArray(parsed) ? (parsed as PendingCandidatePurge[]) : []; } export async function pendingCandidatePurges(): Promise { return readPendingPurges().catch(() => []); } async function writePendingPurgesUnlocked(items: PendingCandidatePurge[]): Promise { await atomicWriteFile( pendingPurgePath(), `${JSON.stringify(items, null, 2)}\n`, ); } /** * 读-改-写必须在**同一把锁**内完成。旧实现只在写入时加锁,读取和修改都在 * 锁外:两个清理失败同时入队,或重试出队与入队交错时,后写者会覆盖另一项。 * 记录此时已被删除,丢了待办就等于丢掉了唯一补救入口。 */ async function updatePendingPurges( mutate: (items: PendingCandidatePurge[]) => void, ): Promise { const release = await acquireFileLock(`${pendingPurgePath()}.lock`); try { const items = await readPendingPurges(); mutate(items); await writePendingPurgesUnlocked(items); } finally { await release(); } } /** 记录一次仍需重试的候选清理;同一记录重复失败只累加次数。 */ export async function queueCandidatePurge( entry: Omit, ): Promise { await updatePendingPurges((items) => { const index = items.findIndex((item) => item.recordId === entry.recordId); if (index >= 0) { const existing = items[index]!; items[index] = { ...existing, attempts: existing.attempts + 1, ...(entry.lastError ? { lastError: entry.lastError } : {}), }; } else { items.push({ ...entry, addedAt: Date.now(), attempts: 1 }); } }); } async function dequeueCandidatePurge(recordId: string): Promise { await updatePendingPurges((items) => { const index = items.findIndex((item) => item.recordId === recordId); if (index >= 0) items.splice(index, 1); }); } /** 重试所有待办清理;成功的出队,失败的留在队列里并累加尝试次数。 */ export async function retryPendingCandidatePurges(): Promise<{ retried: number; stillPending: number; }> { const items = await readPendingPurges(); let retried = 0; for (const item of items) { try { const sweep = await purgeCandidatesForRecord(item.recordId, item.scope, item.workspaceId, item.anchors); if (sweep.failed.length > 0) { await queueCandidatePurge({ recordId: item.recordId, scope: item.scope, workspaceId: item.workspaceId, lastError: sweep.failed.map((entry) => `${entry.workspaceId}: ${entry.error}`).join('; '), }); continue; } await dequeueCandidatePurge(item.recordId); retried += 1; } catch (error) { await queueCandidatePurge({ recordId: item.recordId, scope: item.scope, workspaceId: item.workspaceId, lastError: (error as Error).message, }).catch(() => undefined); } } return { retried, stillPending: (await readPendingPurges()).length }; } export async function clearFactCandidates(workspaceId: string) { const release = await acquireFileLock(pathFor(workspaceId)); try { await atomicWriteFile(pathFor(workspaceId), '[]\n'); } finally { await release(); } } export async function resolveFactCandidate( workspaceId: string, id: string, decision: 'accept' | 'reject', signal?: AbortSignal, ) { // Resolve lock is distinct from candidate persistence: record mutations may // clear a workspace without an inverse records→candidates lock cycle. const release = await acquireFileLock( pathFor(workspaceId) + '.resolve', signal, ); try { signal?.throwIfAborted(); const item = (await factCandidates(workspaceId)).find( (item) => item.id === id, ); if (!item) throw new Error('候选不存在'); const status = decision === 'accept' ? 'accepted' : 'rejected'; if (item.status === status) return; if (item.status !== 'open') throw new Error('候选已结清'); if (decision === 'accept') { if (item.old) { const current = await memoryService.readWithVersion( item.old.id, item.proposed.scope, item.proposed.workspaceId, ); if (!current) throw new Error('原记忆已删除,不能从候选恢复'); const applied = current.record.statement === item.proposed.statement && current.record.sourceMessageId === item.proposed.sourceMessageId && current.record.validUntil === item.proposed.validUntil; if (!applied) { // A candidate replaces a statement, not a version: reconfirming the // same statement elsewhere must not make the proposal unacceptable. if (current.record.statement !== item.old.statement) throw new Error( 'MEMORY_VERSION_CONFLICT:原事实已改变,请重新评估', ); const updated = await memoryService.updateWithVersion( current.record.id, current.record.scope, current.version, { ...item.proposed, validUntil: item.proposed.validUntil, status: 'active', }, current.record.workspaceId, { startedAt: item.createdAt, sourceWorkspaceId: workspaceId, signal, }, ); if (!updated) throw new Error('原记忆已删除,候选未采纳'); } } else await memoryService.remember(item.proposed, { startedAt: item.createdAt, sourceWorkspaceId: workspaceId, signal, }); } const unlock = await acquireFileLock(pathFor(workspaceId)); try { const items = await factCandidates(workspaceId); const target = items.find((candidate) => candidate.id === id); if (target) target.status = status; await atomicWriteFile(pathFor(workspaceId), JSON.stringify(items) + '\n'); } finally { await unlock(); } } finally { await release(); } }