import type { Database } from 'bun:sqlite' import { error as logError } from '../../logger' import { getDb } from '../../db/sqlite' import { getMemoryRow, transitionToTeamScope } from './store' import { isTeamMember } from './permissions' import { MemoryError, type MemoryRow } from './types' /** * Memory scopes — space management. * * Single responsibility: resolving WHICH space an operation targets, and * moving memories between spaces. * - resolveSessionMemoryScope maps a session to its owner identity * (primary user owner + team owner) — the server-side source of truth for * pack assembly and write-back attribution. * - promoteMemoryToTeam moves a personal memory into a team space, enforcing * owner-only + target-team membership here (defense in depth — routes * check too, but the service must never trust that they did). */ /** Resolve the identity context for a session: primary user owner + team owner. */ export function resolveSessionMemoryScope( db: Database, sessionId: string, ): { userId: string | null; teamId: string | null } { try { const owners = db .query( `SELECT owner_type, owner_id FROM session_owners WHERE session_id = $sid`, ) .all({ $sid: sessionId }) as unknown as { owner_type: string owner_id: string }[] const userId = owners.find(o => o.owner_type === 'user')?.owner_id ?? null const teamId = owners.find(o => o.owner_type === 'team')?.owner_id ?? null return { userId, teamId } } catch (err) { logError( `[memories] resolveSessionMemoryScope failed session=${sessionId}:`, err, ) return { userId: null, teamId: null } } } /** * Promote a personal memory to team scope. Only the owner may promote their * own memory, and they must be a member of the target team. The move keeps * provenance (created_by, source_session_id) and bumps the version. */ export function promoteMemoryToTeam( id: string, userId: string, teamId: string, ): MemoryRow { const db = getDb() const row = getMemoryRow(id) if (!row) { throw new MemoryError('not_found', 'Memory not found') } if (row.scope_kind !== 'personal') { throw new MemoryError( 'not_personal', 'Only personal memories can be promoted', ) } if (row.owner_user_id !== userId) { throw new MemoryError('forbidden', 'Only the owner can promote this memory') } if (!isTeamMember(db, userId, teamId)) { throw new MemoryError('forbidden', 'Not a member of the target team') } return transitionToTeamScope(id, teamId) }