/** * Where agent-run results land in memory: a short index entry in personal * memory and the full result in the workspace's memory (ADR-0007). */ import { PERSONAL_SCOPE, RESERVED_METADATA_KEYS, workspaceScope, type MemoryStore, } from '@waggle/memory-contract'; import type { CollaborationRunMemoryRefs } from '@waggle/shared'; export interface RunResultMemoryInput { workspaceId: string; /** Short index entry kept in personal memory. */ personalText: string; /** The full result, kept in the workspace's memory. */ workspaceText: string; /** Run identifiers (runId, roomId…). Keys the contract reserves get a `run_` prefix. */ metadata: Record; } function runMetadata(metadata: Record): Record { const reserved: readonly string[] = RESERVED_METADATA_KEYS; return Object.fromEntries( Object.entries(metadata).map(([key, value]) => [reserved.includes(key) ? `run_${key}` : key, value]), ); } /** Writes both entries; a failed write is reflected in the returned status. */ export async function recordRunResult( memory: MemoryStore, input: RunResultMemoryInput, ): Promise { const personalFrameIds: string[] = []; const workspaceFrameIds: Record = {}; const metadata = runMetadata(input.metadata); try { const [change] = await memory.remember({ scope: PERSONAL_SCOPE, text: input.personalText, kind: 'note', source: 'agent_inferred', origin: 'agent-runs', metadata, }); if (change) personalFrameIds.push(change.record.id); } catch { /* workspace result remains authoritative */ } try { const [change] = await memory.remember({ scope: workspaceScope(input.workspaceId), text: input.workspaceText, kind: 'note', source: 'agent_inferred', origin: 'agent-runs', metadata, }); if (change) workspaceFrameIds[input.workspaceId] = [change.record.id]; } catch { /* reflected in the status below */ } const personalOk = personalFrameIds.length > 0; const workspaceOk = (workspaceFrameIds[input.workspaceId]?.length ?? 0) > 0; return { status: personalOk && workspaceOk ? 'complete' : personalOk || workspaceOk ? 'partial' : 'failed', personalFrameIds, workspaceFrameIds, }; }