import { nanoid } from 'nanoid' import type { Database } from 'bun:sqlite' import { error as logError } from '../../logger' import { getDb } from '../../db/sqlite' import { MEMORY_TYPES, MemoryError, type CreateMemoryParams, type MemoryMeta, type MemoryRow, type UpdateMemoryParams, } from './types' /** * Memory store — the storage layer (写入检索) for SQLite memories. * * Single responsibility: rows + the FTS index that accelerates them. There * is NO user-identity or permission concept in this module — every export * is a trusted primitive. Callers fall into exactly two categories: * * - User-facing paths (web routes): MUST gate through permissions.ts * before calling anything here. * - Server-derived identity paths (writeback.ts, pack.ts): trusted because * the actor is resolved server-side from the session, never from caller * input (anti-forgery). * * Upper layers should import from '../services/memory' (the facade), not * from this file directly — store exports are the subsystem's internal * building blocks. */ function nowIso(): string { return new Date().toISOString() } export function toMeta(row: MemoryRow): MemoryMeta { const { content: _content, ...meta } = row return meta } /** FTS5 write — insert on create, delete+insert on update (id-stable). */ function upsertFts(db: Database, row: MemoryRow): void { try { db.query('DELETE FROM memories_fts WHERE memory_id = $id').run({ $id: row.id, }) db.query( `INSERT INTO memories_fts (name, description, content, memory_id) VALUES ($name, $description, $content, $id)`, ).run({ $name: row.name, $description: row.description ?? '', $content: row.content, $id: row.id, }) } catch (err) { // FTS is an accelerator, not a source of truth — a failed index write // must not break the memory write itself. logError(`[memories] fts upsert failed id=${row.id}:`, err) } } function removeFts(db: Database, id: string): void { try { db.query('DELETE FROM memories_fts WHERE memory_id = $id').run({ $id: id }) } catch (err) { logError(`[memories] fts delete failed id=${id}:`, err) } } function getMemoryRowInner(db: Database, id: string): MemoryRow | null { const row = db .query('SELECT * FROM memories WHERE id = $id') .get({ $id: id }) as MemoryRow | null return row ?? null } /** Fetch a memory; archived rows read as missing (soft delete). */ export function getMemoryRow(id: string): MemoryRow | null { try { const row = getMemoryRowInner(getDb(), id) if (!row || row.status === 'archived') return null return row } catch (err) { logError(`[memories] getMemoryRow failed id=${id}:`, err) return null } } export function createMemory(params: CreateMemoryParams): MemoryRow { const db = getDb() const name = params.name.trim() if (!name) throw new MemoryError('invalid_name', 'name is required') if (!params.content.trim()) { throw new MemoryError('invalid_content', 'content is required') } if (!MEMORY_TYPES.includes(params.type)) { throw new MemoryError( 'invalid_type', `type must be one of ${MEMORY_TYPES.join(', ')}`, ) } const now = nowIso() const id = nanoid(21) const ownerUserId = params.scopeKind === 'personal' ? (params.ownerUserId ?? null) : null const teamId = params.scopeKind === 'team' ? (params.teamId ?? null) : null try { db.query( `INSERT INTO memories (id, scope_kind, owner_user_id, team_id, name, description, type, layer, content, status, source_session_id, version, created_by, created_at, updated_at) VALUES ($id, $scope_kind, $owner_user_id, $team_id, $name, $description, $type, $layer, $content, 'active', $source_session_id, 1, $created_by, $now, $now)`, ).run({ $id: id, $scope_kind: params.scopeKind, $owner_user_id: ownerUserId, $team_id: teamId, $name: name, $description: params.description?.trim() || null, $type: params.type, $layer: params.layer ?? 'semantic', $content: params.content, $source_session_id: params.sourceSessionId ?? null, $created_by: params.createdBy ?? null, $now: now, }) } catch (err) { // CHECK violation (missing owner column) or similar — surface as typed error. throw new MemoryError( 'invalid_scope', `createMemory failed: ${err instanceof Error ? err.message : String(err)}`, ) } const row = getMemoryRowInner(db, id) if (!row) throw new MemoryError('insert_failed', 'memory row missing after insert') upsertFts(db, row) return row } /** Edit an existing memory. Bumps version and refreshes FTS. */ export function updateMemory( id: string, params: UpdateMemoryParams, ): MemoryRow | null { const db = getDb() const row = getMemoryRowInner(db, id) if (!row || row.status === 'archived') return null const name = params.name?.trim() || row.name const description = params.description !== undefined ? params.description.trim() || null : row.description const content = params.content ?? row.content if (!content.trim()) { throw new MemoryError('invalid_content', 'content is required') } const type = params.type ?? row.type if (!MEMORY_TYPES.includes(type)) { throw new MemoryError( 'invalid_type', `type must be one of ${MEMORY_TYPES.join(', ')}`, ) } const layer = params.layer ?? row.layer db.query( `UPDATE memories SET name = $name, description = $description, content = $content, type = $type, layer = $layer, version = version + 1, updated_at = $now WHERE id = $id`, ).run({ $id: id, $name: name, $description: description, $content: content, $type: type, $layer: layer, $now: nowIso(), }) const updated = getMemoryRowInner(db, id) if (updated) upsertFts(db, updated) return updated } /** Soft delete — archived reads as missing everywhere. */ export function archiveMemory(id: string): boolean { const db = getDb() try { const result = db .query( `UPDATE memories SET status = 'archived', updated_at = $now WHERE id = $id AND status != 'archived'`, ) .run({ $id: id, $now: nowIso() }) const changed = (result as unknown as { changes?: number }).changes === 1 if (changed) removeFts(db, id) return changed } catch (err) { logError(`[memories] archiveMemory failed id=${id}:`, err) return false } } /** * Storage-level personal→team scope transition: clears the owner, sets the * team, bumps the version, refreshes FTS. Provenance columns * (created_by, source_session_id) are intentionally untouched. * * Permission enforcement (owner-only, target-team membership) lives in * scopes.promoteMemoryToTeam — never call this directly from a route. */ export function transitionToTeamScope(id: string, teamId: string): MemoryRow { const db = getDb() db.query( `UPDATE memories SET scope_kind = 'team', owner_user_id = NULL, team_id = $teamId, version = version + 1, updated_at = $now WHERE id = $id`, ).run({ $id: id, $teamId: teamId, $now: nowIso() }) const updated = getMemoryRowInner(db, id) if (!updated) throw new MemoryError('update_failed', 'promote failed') upsertFts(db, updated) return updated } /** Dedup recall: exact-name match first, then FTS name match, owner-scoped. * Write-back ingest uses this to update instead of near-duplicating. */ export function findSimilarPersonalMemory( db: Database, userId: string, name: string, ): MemoryRow | null { const exact = db .query( `SELECT * FROM memories WHERE scope_kind = 'personal' AND owner_user_id = $uid AND status = 'active' AND name = $name LIMIT 1`, ) .get({ $uid: userId, $name: name }) as MemoryRow | null if (exact) return exact try { const hit = db .query( `SELECT m.* FROM memories m JOIN memories_fts f ON f.memory_id = m.id WHERE memories_fts MATCH $query AND m.scope_kind = 'personal' AND m.owner_user_id = $uid AND m.status = 'active' LIMIT 1`, ) .get({ $query: `"${name.replace(/"/g, '""')}"`, $uid: userId, }) as MemoryRow | null return hit ?? null } catch (err) { logError('[memories] dedup fts lookup failed:', err) return null } } /** * Retrieval telemetry write — mark rows as recalled (pack inclusion). * Mirrors the CLI memdir index's boostConfidenceOnAccess + access_count * increment: confidence = MIN(1.0, confidence + 0.02), access_count + 1, * last_accessed_at = now. updated_at is intentionally untouched — access * is not a content change. */ export function bumpMemoryAccess(db: Database, ids: string[]): void { if (ids.length === 0) return const now = nowIso() try { db.query( `UPDATE memories SET confidence = MIN(1.0, confidence + $delta), access_count = access_count + 1, last_accessed_at = $now WHERE id IN (${ids.map((_, i) => `$id${i}`).join(', ')})`, ).run( Object.fromEntries([ ['$delta', 0.02], ['$now', now], ...ids.map((id, i) => [`$id${i}`, id] as const), ]), ) } catch (err) { // Telemetry must never fail the pack build that reports it. logError('[memories] bumpMemoryAccess failed:', err) } } /** Active personal rows of a user (pack assembly input). */ export function listActivePersonalMemories( db: Database, userId: string, ): MemoryRow[] { return db .query( `SELECT * FROM memories WHERE scope_kind = 'personal' AND owner_user_id = $uid AND status = 'active' ORDER BY updated_at DESC LIMIT 100`, ) .all({ $uid: userId }) as unknown as MemoryRow[] } /** Active team rows of a team (pack assembly input). */ export function listActiveTeamMemories( db: Database, teamId: string, ): MemoryRow[] { return db .query( `SELECT * FROM memories WHERE scope_kind = 'team' AND team_id = $tid AND status = 'active' ORDER BY updated_at DESC LIMIT 100`, ) .all({ $tid: teamId }) as unknown as MemoryRow[] }