/** Forget barriers contain hashes, never the forgotten statement. Shared by * explicit deletion and background commits, including separate host processes. */ import { join } from 'node:path'; import { readFile } from 'node:fs/promises'; import { z } from 'zod'; import { deriveTopicKey, sha256 } from './codec.js'; import { acquireFileLock, atomicWriteFile, scopeDirectory, } from './fileStore.js'; import type { MemoryRecord, MemoryScope } from './types.js'; const schema = z.object({ clearedAt: z.number().default(0), blocked: z.array(z.string()).default([]), identities: z .array( z.object({ id: z.string(), category: z.string(), subject: z.string(), aliases: z.array(z.string()), }), ) .default([]), }); type Barriers = z.infer; type Identity = Pick< MemoryRecord, | 'topicKey' | 'category' | 'subject' | 'statement' | 'sourceSessionId' | 'sourceMessageId' > & Partial>; function keys(record: Identity): string[] { const normalize = (value: string) => value.normalize('NFKC').trim().toLowerCase().replace(/\s+/g, ''); return [ ...(record.sourceAnchor ? ['anchor:' + record.sourceAnchor] : []), ...(record.priorSourceAnchors ?? []).map(key => 'anchor:' + key), sha256(`topic:${normalize(record.topicKey ?? deriveTopicKey(record))}`), sha256(`statement:${normalize(record.statement)}`), ...[record.subject, ...(record.aliases ?? [])].map((value) => sha256(`alias:${record.category}:${normalize(value)}`), ), ...(record.id ? [sha256(`id:${record.id}`)] : []), // The sentence the fact was drawn from is part of what "forgotten" means: a // later pass over the same conversation may reword the subject and statement // (new topic/alias keys), but it is still the sentence the user asked to // forget. Keyed on the evidence quote, not the whole message: another fact // from a different sentence of the same message stays allowed. ...(record.sourceSessionId && record.sourceMessageId && record.evidenceQuote ? [sha256(`quote:${record.sourceSessionId}:${record.sourceMessageId}:${normalize(record.evidenceQuote)}`)] : []), ]; } export async function withFactBarriers( scope: MemoryScope, workspaceId: string | undefined, operation: (barriers: Barriers, save: () => Promise) => Promise, ): Promise { const path = join(scopeDirectory(scope, workspaceId), 'fact-barriers.json'); const release = await acquireFileLock(path); try { const raw = await readFile(path, 'utf8').catch((error) => { if (error.code !== 'ENOENT') throw error; return '{}'; }); const barriers = schema.parse(JSON.parse(raw)); return await operation(barriers, () => atomicWriteFile(path, JSON.stringify(barriers) + '\n'), ); } finally { await release(); } } export function blockFact(barriers: Barriers, record: Identity): void { barriers.blocked = [...new Set([...barriers.blocked, ...keys(record)])]; if (record.id && !barriers.identities.some((item) => item.id === record.id)) barriers.identities.push({ id: record.id, category: record.category, subject: record.subject, aliases: record.aliases ?? [], }); } export async function forgottenFactIdentities(workspaceId: string) { const personal = await withFactBarriers( 'personal', undefined, async (barriers) => barriers.identities.map((item) => ({ ...item, scope: 'personal' as const, })), ); const workspace = await withFactBarriers( 'workspace', workspaceId, async (barriers) => barriers.identities.map((item) => ({ ...item, scope: 'workspace' as const, })), ); return [...personal, ...workspace]; } export function assertAutomaticFactAllowed( barriers: Barriers, record: Identity, startedAt: number, ): void { if ( startedAt <= barriers.clearedAt || keys(record).some((key) => barriers.blocked.includes(key)) ) throw new Error( 'FACT_FORGOTTEN:自动提炼不得恢复已遗忘的主题或来源;需用户明确重新保存', ); } /** A shared source must not be revived by classifying it into another scope. * Scope-local topic names (and scope-wide clears) are deliberately not global. */ export function assertSourceAllowed(barriers: Barriers, anchor?: string) { if (anchor && barriers.blocked.includes('anchor:' + anchor)) throw new Error('FACT_FORGOTTEN:已遗忘来源,不能通过改变范围恢复'); } /** Order is always workspace -> personal -> records. Keep the locks until * commit so forgetting an origin cannot race a write in a different scope. */ export function withDestinationBarrier(scope: MemoryScope, workspaceId: string | undefined, source: string | undefined, operation: (barriers: Barriers) => Promise): Promise { return withFactBarriers(scope, workspaceId, local => { if (scope !== 'workspace' || !source) return operation(local); return withFactBarriers('personal', undefined, personal => { assertSourceAllowed(personal, source); return operation(local); }); }); }