import { createHash } from 'node:crypto'; import { parse as parseYaml, stringify as stringifyYaml } from 'yaml'; import { ALL_CATEGORIES, MEMORY_ID_PATTERN, PERSONA_MAX_CHARS, STATEMENT_MAX_CHARS, } from './constants.js'; import type { MemoryCategory, MemoryRecord, MemoryRecordV2, PersonaDocument, } from './types.js'; export function sha256(value: string | Uint8Array): string { return createHash('sha256').update(value).digest('hex'); } export function normalizeTopicPart(value: string): string { return value .normalize('NFKC') .toLocaleLowerCase() .replace(/[\s\p{P}\p{S}]+/gu, '-') .replace(/^-+|-+$/g, '') .slice(0, 120); } export function deriveTopicKey( record: Pick, ): string { return `${record.category}:${normalizeTopicPart(record.subject) || 'untitled'}`; } export function hydrateRecord(record: MemoryRecord): MemoryRecordV2 { const aliases = Array.isArray(record.aliases) ? Array.from( new Set(record.aliases.map((item) => item.trim()).filter(Boolean)), ).slice(0, 20) : []; return { ...record, schemaVersion: 2, topicKey: record.topicKey?.trim() || deriveTopicKey(record), aliases, status: record.status ?? 'active', revision: Number.isInteger(record.revision) && (record.revision ?? 0) > 0 ? record.revision! : 1, lastConfirmedAt: record.lastConfirmedAt ?? record.updatedAt, supersedesIds: Array.isArray(record.supersedesIds) ? Array.from( new Set( record.supersedesIds.filter((id) => MEMORY_ID_PATTERN.test(id)), ), ) : [], }; } function splitFrontmatter(raw: string): { metadata: unknown; body: string } { const normalized = raw.replace(/^\uFEFF/, '').replace(/\r\n/g, '\n'); if (!normalized.startsWith('---\n')) throw new Error('缺少 YAML frontmatter'); const end = normalized.indexOf('\n---\n', 4); if (end < 0) throw new Error('YAML frontmatter 未闭合'); return { metadata: parseYaml(normalized.slice(4, end)), body: normalized.slice(end + 5).trim(), }; } function isCategory(value: unknown): value is MemoryCategory { return ( typeof value === 'string' && ALL_CATEGORIES.includes(value as MemoryCategory) ); } export function parseMemoryRecord(raw: string, path: string): MemoryRecordV2 { const { metadata, body } = splitFrontmatter(raw); if (!metadata || typeof metadata !== 'object' || Array.isArray(metadata)) { throw new Error('frontmatter 必须是对象'); } const item = metadata as Record; const statement = body.replace(/^\[stated\]\s*/, '').trim(); const valid = typeof item.id === 'string' && MEMORY_ID_PATTERN.test(item.id) && (item.scope === 'personal' || item.scope === 'workspace') && isCategory(item.category) && typeof item.subject === 'string' && typeof item.evidenceQuote === 'string' && typeof item.sourceSessionId === 'string' && typeof item.sourceMessageId === 'string' && (item.evidence === 'user_stated' || item.evidence === 'user_confirmed') && (item.sensitivity === 'normal' || item.sensitivity === 'sensitive') && typeof item.createdAt === 'number' && typeof item.updatedAt === 'number' && statement.length > 0 && statement.length <= STATEMENT_MAX_CHARS; if (!valid) throw new Error(`记忆 frontmatter 或正文无效:${path}`); if (item.scope === 'workspace' && typeof item.workspaceId !== 'string') { throw new Error(`工作区记忆缺少 workspaceId:${path}`); } if ( item.status !== undefined && !['active', 'needs_review', 'superseded'].includes(String(item.status)) ) { throw new Error(`记忆状态无效:${path}`); } return hydrateRecord({ id: item.id as string, scope: item.scope as MemoryRecord['scope'], ...(item.scope === 'workspace' ? { workspaceId: item.workspaceId as string } : {}), category: item.category as MemoryCategory, subject: item.subject as string, statement, ...(typeof item.scopeReason === 'string' ? { scopeReason: item.scopeReason } : {}), ...(typeof item.validUntil === 'number' && Number.isFinite(item.validUntil) ? { validUntil: item.validUntil } : {}), ...(typeof item.confirmationContext === 'string' ? { confirmationContext: item.confirmationContext } : {}), evidence: item.evidence as MemoryRecord['evidence'], evidenceQuote: item.evidenceQuote as string, sourceSessionId: item.sourceSessionId as string, sourceMessageId: item.sourceMessageId as string, ...(typeof item.sourceAnchor === 'string' ? { sourceAnchor: item.sourceAnchor } : {}), ...(Array.isArray(item.priorSourceAnchors) ? {priorSourceAnchors: item.priorSourceAnchors.filter((key): key is string => typeof key === 'string' && /^[a-f0-9]{64}$/.test(key))} : {}), sensitivity: item.sensitivity as MemoryRecord['sensitivity'], createdAt: item.createdAt as number, updatedAt: item.updatedAt as number, ...(item.schemaVersion === 2 ? { schemaVersion: 2 as const } : {}), ...(typeof item.topicKey === 'string' ? { topicKey: item.topicKey } : {}), ...(Array.isArray(item.aliases) ? { aliases: item.aliases.filter( (v): v is string => typeof v === 'string', ), } : {}), ...(typeof item.status === 'string' ? { status: item.status as MemoryRecordV2['status'] } : {}), ...(typeof item.revision === 'number' ? { revision: item.revision } : {}), ...(typeof item.lastConfirmedAt === 'number' ? { lastConfirmedAt: item.lastConfirmedAt } : {}), ...(Array.isArray(item.supersedesIds) ? { supersedesIds: item.supersedesIds.filter( (v): v is string => typeof v === 'string', ), } : {}), ...(typeof item.evidenceHash === 'string' ? { evidenceHash: item.evidenceHash } : {}), }); } export function serializeMemoryRecord(record: MemoryRecord): string { const v2 = hydrateRecord(record); const metadata = { schemaVersion: 2, id: v2.id, scope: v2.scope, ...(v2.workspaceId ? { workspaceId: v2.workspaceId } : {}), category: v2.category, subject: v2.subject, topicKey: v2.topicKey, aliases: v2.aliases, status: v2.status, revision: v2.revision, lastConfirmedAt: v2.lastConfirmedAt, supersedesIds: v2.supersedesIds, evidence: v2.evidence, evidenceQuote: v2.evidenceQuote, ...(v2.evidenceHash ? { evidenceHash: v2.evidenceHash } : {}), sourceSessionId: v2.sourceSessionId, sourceMessageId: v2.sourceMessageId, ...(v2.sourceAnchor ? { sourceAnchor: v2.sourceAnchor } : {}), ...(v2.priorSourceAnchors?.length ? {priorSourceAnchors:v2.priorSourceAnchors} : {}), sensitivity: v2.sensitivity, createdAt: v2.createdAt, updatedAt: v2.updatedAt, ...(v2.scopeReason ? { scopeReason: v2.scopeReason } : {}), ...(v2.validUntil !== undefined ? { validUntil: v2.validUntil } : {}), ...(v2.confirmationContext ? { confirmationContext: v2.confirmationContext } : {}), }; return `---\n${stringifyYaml(metadata).trimEnd()}\n---\n\n[stated] ${v2.statement.trim()}\n`; } export function parsePersona(raw: string): PersonaDocument { const { metadata, body } = splitFrontmatter(raw); if (!metadata || typeof metadata !== 'object' || Array.isArray(metadata)) { throw new Error('人格文件 frontmatter 必须是对象'); } const item = metadata as Record; if ( typeof item.evidenceQuote !== 'string' || typeof item.sourceSessionId !== 'string' || typeof item.sourceMessageId !== 'string' || typeof item.updatedAt !== 'number' || !body || body.length > PERSONA_MAX_CHARS ) { throw new Error('人格文件结构无效'); } return { content: body, evidenceQuote: item.evidenceQuote, sourceSessionId: item.sourceSessionId, sourceMessageId: item.sourceMessageId, updatedAt: item.updatedAt, ...(typeof item.revision === 'number' ? { revision: item.revision } : {}), }; } export function serializePersona(persona: PersonaDocument): string { const metadata = { evidenceQuote: persona.evidenceQuote, sourceSessionId: persona.sourceSessionId, sourceMessageId: persona.sourceMessageId, updatedAt: persona.updatedAt, revision: persona.revision ?? 1, }; return `---\n${stringifyYaml(metadata).trimEnd()}\n---\n\n${persona.content.trim()}\n`; } export function containsForbiddenSecret(text: string): boolean { return [ /-----BEGIN [A-Z ]*PRIVATE KEY-----/i, /\b(?:api[_ -]?key|access[_ -]?token|refresh[_ -]?token|password|passwd|验证码|私钥|密码)\b\s*[:=:]\s*\S+/i, /\b(?:sk|tvly|ghp|github_pat|xox[baprs])[-_][A-Za-z0-9_-]{12,}\b/i, /\b\d{6}\b.*(?:otp|验证码)|(?:otp|验证码).*\b\d{6}\b/i, ].some((pattern) => pattern.test(text)); } export function validateMemoryInput( input: Pick, ): void { if (!input.subject.trim() || input.subject.length > 120) { throw new Error('记忆主题长度必须为 1-120 字符'); } if (!input.statement.trim() || input.statement.length > STATEMENT_MAX_CHARS) { throw new Error(`单条记忆长度必须为 1-${STATEMENT_MAX_CHARS} 字符`); } if ( !input.evidenceQuote.trim() || input.evidenceQuote.length > STATEMENT_MAX_CHARS ) { throw new Error(`记忆证据长度必须为 1-${STATEMENT_MAX_CHARS} 字符`); } if (containsForbiddenSecret(`${input.statement}\n${input.evidenceQuote}`)) { throw new Error('密码、Token、验证码、私钥或其他凭据不得写入记忆'); } }