import type { Database } from 'bun:sqlite' import { getDb } from '../../db/sqlite' import { resolveSessionMemoryScope } from './scopes' import { bumpMemoryAccess, listActivePersonalMemories, listActiveTeamMemories, } from './store' import { serializeMemoryFile } from './fileFormat' import type { MemoryPack, MemoryRow } from './types' /** * Memory pack — the bridge injection compiler. * * Single responsibility: turn rows into the stable-zone pack handed to a * session's worker. Layout mirrors the CLI memdir conventions so the child * process's existing loadMemoryPrompt machinery works unchanged: * * MEMORY.md — index, one line per entry (≤150 chars, ≤200 lines) * _.md — personal memory files, memdir frontmatter format * team/ — team memories (memdir team subdir layout) * * Identity comes from scopes.resolveSessionMemoryScope (server-side); * composition queries come from store.ts. No permission logic — the pack is * assembled FOR a session the caller already authenticated. */ const PACK_MAX_LINES = 200 const PACK_LINE_MAX_CHARS = 150 function slugifyName(name: string): string { const slug = name .toLowerCase() .replace(/[^a-z0-9\u4e00-\u9fff]+/g, '-') .replace(/^-+|-+$/g, '') return slug || 'memory' } function packLine(row: MemoryRow, relPath: string): string { const hook = row.description ?? row.name const line = `- [${row.name}](${relPath}) — ${hook}` return line.length > PACK_LINE_MAX_CHARS ? `${line.slice(0, PACK_LINE_MAX_CHARS - 1)}…` : line } function buildPackFromRows(rows: MemoryRow[]): MemoryPack { const files: Record = {} const lines: string[] = [] const used = new Set() for (const row of rows) { const teamPrefix = row.scope_kind === 'team' ? 'team/' : '' let rel = `${teamPrefix}${row.type}_${slugifyName(row.name)}.md` // Dedupe colliding paths deterministically. if (used.has(rel)) rel = `${teamPrefix}${row.type}_${slugifyName(row.name)}-${row.id}.md` used.add(rel) files[rel] = serializeMemoryFile({ name: row.name, description: row.description, type: row.type, content: row.content, }) lines.push(packLine(row, rel)) } const capped = lines.slice(0, PACK_MAX_LINES) if (lines.length > capped.length) { capped.push(`- … ${lines.length - capped.length} more memories omitted`) } files['MEMORY.md'] = `${capped.join('\n')}\n` return { files } } /** * Compile the injection pack for a session. Personal memories of the * session's primary user owner; team memories only when the session is * team-owned. Empty pack when the session has no user owner. */ export function buildMemoryPack(sessionId: string): MemoryPack { const db: Database = getDb() const { userId, teamId } = resolveSessionMemoryScope(db, sessionId) if (!userId) return { files: {} } const rows = listActivePersonalMemories(db, userId) if (teamId) rows.push(...listActiveTeamMemories(db, teamId)) // Pack inclusion IS the server-side recall event (the bridge fetches once // per session spawn) — count it, mirroring the memdir index's per-turn // access boost at the granularity available here. bumpMemoryAccess( db, rows.map(r => r.id), ) return buildPackFromRows(rows) }