diff --git a/apps/web/src/components/os/apps/ChatApp.tsx b/apps/web/src/components/os/apps/ChatApp.tsx index 6d89a9c..39ae2a0 100644 --- a/apps/web/src/components/os/apps/ChatApp.tsx +++ b/apps/web/src/components/os/apps/ChatApp.tsx @@ -651,8 +651,10 @@ const ChatApp = ({ const query = buildRecallQuery(messages); if (!query) return; let cancelled = false; - const scope = workspaceId ?? 'global'; - adapter.searchMemory(query, scope).then(frames => { + const search = workspaceId + ? adapter.searchMemory(query, 'all', workspaceId) + : adapter.searchMemory(query, 'global'); + search.then(frames => { if (cancelled) return; const top = frames[0]; if (!top?.content) return; diff --git a/apps/web/src/components/os/apps/CockpitApp.test.tsx b/apps/web/src/components/os/apps/CockpitApp.test.tsx index 5a59b22..6110f12 100644 --- a/apps/web/src/components/os/apps/CockpitApp.test.tsx +++ b/apps/web/src/components/os/apps/CockpitApp.test.tsx @@ -11,7 +11,6 @@ const mocks = vi.hoisted(() => ({ getCapabilitiesStatus: vi.fn(), getAuditInstalls: vi.fn(), getCostSummary: vi.fn(), - getWeaverStatus: vi.fn(), getEventStats: vi.fn(), }, })); @@ -29,11 +28,6 @@ beforeEach(() => { mocks.adapter.getCapabilitiesStatus.mockResolvedValue({}); mocks.adapter.getAuditInstalls.mockResolvedValue([]); mocks.adapter.getCostSummary.mockResolvedValue({ totalTokens: 0, estimatedCost: 0 }); - mocks.adapter.getWeaverStatus.mockResolvedValue({ - personalMind: { lastConsolidation: null, lastDecay: null, timerActive: false }, - workspaces: [], - checkedAt: new Date().toISOString(), - }); mocks.adapter.getEventStats.mockResolvedValue({ byType: {}, total: 0 }); }); diff --git a/apps/web/src/components/os/apps/CockpitApp.tsx b/apps/web/src/components/os/apps/CockpitApp.tsx index 4bc23b7..0969264 100644 --- a/apps/web/src/components/os/apps/CockpitApp.tsx +++ b/apps/web/src/components/os/apps/CockpitApp.tsx @@ -1,7 +1,6 @@ import { useState, useEffect } from 'react'; import { Activity, Server, DollarSign, Clock, Plug, RefreshCw, Timer, Brain, Shield, Network, FileText, ChevronDown, AlertTriangle } from 'lucide-react'; import { adapter } from '@/lib/adapter'; -import { DATE_LOCALE } from '@/lib/date-locale'; import type { CronJob } from '@/lib/types'; import { describeCronExpr } from '@/lib/cron-presets'; @@ -15,11 +14,6 @@ interface CockpitData { vault?: unknown; capStatus?: unknown; auditTrail?: unknown[]; - weaver?: { - personalMind: { lastConsolidation: string | null; lastDecay: string | null; timerActive: boolean }; - workspaces: Array<{ id: string; lastConsolidation: string | null; timerActive: boolean }>; - checkedAt: string; - }; eventStats?: { byType: Record; total: number }; } @@ -32,7 +26,7 @@ const CockpitApp = () => { const refresh = async () => { setLoading(true); try { - const [health, cost, connectors, crons, vault, capStatus, audit, costSum, weaver, evStats] = await Promise.allSettled([ + const [health, cost, connectors, crons, vault, capStatus, audit, costSum, evStats] = await Promise.allSettled([ adapter.getSystemHealth(), adapter.getAgentCost(), adapter.getConnectors(), @@ -41,7 +35,6 @@ const CockpitApp = () => { adapter.getCapabilitiesStatus(), adapter.getAuditInstalls(), adapter.getCostSummary(), - adapter.getWeaverStatus(), adapter.getEventStats(), ]); setData({ @@ -53,7 +46,6 @@ const CockpitApp = () => { vault: vault.status === 'fulfilled' ? vault.value : undefined, capStatus: capStatus.status === 'fulfilled' ? capStatus.value : undefined, auditTrail: audit.status === 'fulfilled' ? audit.value : undefined, - weaver: weaver.status === 'fulfilled' ? weaver.value : undefined, eventStats: evStats.status === 'fulfilled' ? evStats.value : undefined, }); const allFailed = [health, cost, connectors, crons, vault, capStatus, audit].every(r => r.status === 'rejected'); @@ -149,24 +141,6 @@ const CockpitApp = () => {

- {/* 2b. Memory Weaver */} - {data.weaver && ( -
-
- - Memory Weaver -
-

- Status: {data.weaver.personalMind?.timerActive ? 'Active' : 'Idle'} -

- {data.weaver.personalMind?.lastConsolidation && ( -

- Last consolidation: {new Date(data.weaver.personalMind.lastConsolidation).toLocaleDateString(DATE_LOCALE)} -

- )} -
- )} - {/* 2c. Event Activity */} {data.eventStats && data.eventStats.total > 0 && (
diff --git a/apps/web/src/components/os/apps/MemoryCenterApp.tsx b/apps/web/src/components/os/apps/MemoryCenterApp.tsx index 6832fbf..c053747 100644 --- a/apps/web/src/components/os/apps/MemoryCenterApp.tsx +++ b/apps/web/src/components/os/apps/MemoryCenterApp.tsx @@ -1,6 +1,6 @@ import { useState } from 'react'; import { motion, useReducedMotion } from 'framer-motion'; -import { Brain, Clock, Network, Download, Activity, BookOpen, User, Briefcase, ShieldCheck, SlidersHorizontal, ChevronDown } from 'lucide-react'; +import { Brain, Clock, Network, Download, BookOpen, User, Briefcase, ShieldCheck, SlidersHorizontal, ChevronDown } from 'lucide-react'; import type { KGNode, KGEdge } from '@/lib/types'; import { HintTooltip } from '@/components/ui/hint-tooltip'; import { SPRING } from '@/lib/motion/tokens'; @@ -8,13 +8,12 @@ import { cn } from '@/lib/utils'; import MemoryTrust from './MemoryTrust'; import KnowledgeGraphViewer from './memory/KnowledgeGraphViewer'; import HarvestTab from './memory/HarvestTab'; -import WeaverPanel from './memory/WeaverPanel'; import WikiTab from './memory/WikiTab'; import MemoryCenterTab from './memory/MemoryCenterTab'; import TimelineTab, { type TimelineTabProps } from './memory/TimelineTab'; import ImportReminderBanner from './memory/ImportReminderBanner'; import { useOnboarding } from '@/hooks/useOnboarding'; -import { hasMemoryFeature, isMemoryViewAvailable } from '@/lib/memory-features'; +import { hasMemoryFeature, isMemoryViewAvailable, useMemoryCapabilities } from '@/lib/memory-features'; /** * Memory Center (P3/D2) — the standalone memory surface (ArtifactCenterApp @@ -23,9 +22,10 @@ import { hasMemoryFeature, isMemoryViewAvailable } from '@/lib/memory-features'; * Top-level structure is the ratified TWO-MIND SPLIT: "About you" reads the * Personal Mind; "About this work" reads the active workspace's Mind. The * per-mind list is MemoryCenterTab (reused, parameterized — D2). The legacy - * MemoryApp views (Timeline / Graph / Harvest / Weaver / Wiki) - * survive as secondary tabs after a divider — capability preserved, entry - * restructured. Mind pills render only on the Memories tab: the legacy tabs + * MemoryApp views (Timeline / Graph / Harvest / Wiki) survive as secondary + * tabs after a divider; Graph, Harvest and Wiki are hidden in v1 (ADR-0002). + * The Weaver maintenance view is gone: mem0 indexes on write and nothing + * consolidates in the background. Mind pills render only on the Memories tab: the legacy tabs * keep their own scoping (Graph has a scope selector; Harvest writes to the * personal mind by design). * @@ -35,12 +35,12 @@ import { hasMemoryFeature, isMemoryViewAvailable } from '@/lib/memory-features'; */ export type MindScope = 'personal' | 'workspace'; -export type MemoryView = 'trust' | 'memories' | 'timeline' | 'graph' | 'harvest' | 'weaver' | 'wiki'; +export type MemoryView = 'trust' | 'memories' | 'timeline' | 'graph' | 'harvest' | 'wiki'; // PR3.5: 'trust' (screen 19) is the new PRIMARY front door — first + default; // the legacy views demote to secondary (after the divider). export const MEMORY_VIEWS: readonly MemoryView[] = [ - 'trust', 'memories', 'timeline', 'graph', 'harvest', 'weaver', 'wiki', + 'trust', 'memories', 'timeline', 'graph', 'harvest', 'wiki', ]; interface MemoryTabDef { @@ -50,9 +50,9 @@ interface MemoryTabDef { tooltip: string; } -// UX gold-standard H1: 7 equal-weight tabs regrouped into 4 primary + an -// "Advanced" flyout (display-level IA only — every view id, route and -// ?tab= deep-link is unchanged; MEMORY_VIEWS still validates all 7). +// UX gold-standard H1: the tabs are regrouped into 4 primary + an "Advanced" +// flyout (display-level IA only — every view id, route and ?tab= deep-link is +// unchanged; MEMORY_VIEWS validates them all). const PRIMARY_TABS: MemoryTabDef[] = [ { id: 'trust', label: 'Trust', icon: ShieldCheck, tooltip: 'Memory Trust — confidence & freshness, forget / correct / confirm, and "why did you do that?"' }, { id: 'memories', label: 'Memories', icon: Brain, tooltip: 'Memory Center — inspect, edit, review, merge' }, @@ -62,7 +62,6 @@ const PRIMARY_TABS: MemoryTabDef[] = [ const ADVANCED_TABS: MemoryTabDef[] = [ { id: 'harvest', label: 'Imports', icon: Download, tooltip: 'Import conversations from other AIs' }, - { id: 'weaver', label: 'Maintenance', icon: Activity, tooltip: 'Memory distillation and consolidation' }, { id: 'wiki', label: 'Wiki', icon: BookOpen, tooltip: 'Compiled knowledge pages' }, ]; @@ -93,6 +92,8 @@ const MemoryCenterApp = ({ }: MemoryCenterAppProps) => { // Reminder-banner eligibility (carried over from the retired MemoryApp shell). const { state: onboardingState } = useOnboarding(); + // Re-render once the server's capability map arrives (graph visibility). + useMemoryCapabilities(); // ADR-0002: views of hidden memory features (graph, imports, wiki) are not // offered; a hidden view requested anyway falls back to the default. @@ -286,8 +287,6 @@ const MemoryCenterApp = ({ }} /> ) : view === 'harvest' ? ( - ) : view === 'weaver' ? ( - ) : view === 'wiki' ? ( ) : null} diff --git a/apps/web/src/components/os/apps/MemoryTrust.tsx b/apps/web/src/components/os/apps/MemoryTrust.tsx index da9e0cc..43c26c2 100644 --- a/apps/web/src/components/os/apps/MemoryTrust.tsx +++ b/apps/web/src/components/os/apps/MemoryTrust.tsx @@ -3,6 +3,7 @@ import { ShieldCheck, Info } from 'lucide-react'; import { adapter } from '@/lib/adapter'; import MemoryTrustManage from './memory/MemoryTrustManage'; import MemoryTrustWhy from './memory/MemoryTrustWhy'; +import { memoryLabel } from './memory/memory-label'; import { cn } from '@/lib/utils'; /** @@ -137,7 +138,6 @@ export default function MemoryTrust({ mind, workspaceId }: MemoryTrustProps) { const [traceMemoryId, setTraceMemoryId] = useState(null); const [pendingOpenId, setPendingOpenId] = useState(null); const toastTimer = useRef | undefined>(undefined); - const wsParam = mind === 'workspace' ? workspaceId : undefined; const showToast = useCallback((msg: string) => { setToast(msg); @@ -154,14 +154,14 @@ export default function MemoryTrust({ mind, workspaceId }: MemoryTrustProps) { const correctFromTrace = useCallback((id: string) => { setPendingOpenId(id); setView('manage'); }, []); const forgetFromTrace = useCallback(async (id: string) => { try { - await adapter.deleteMemoryById(id, wsParam, mind); - showToast(`Forgotten M-${id} — removed from recall`); + await adapter.deleteMemoryById(id); + showToast(`Forgotten ${memoryLabel(id)} — removed from recall`); setTraceMemoryId(null); setView('manage'); } catch { showToast('Could not forget that memory'); } - }, [wsParam, mind, showToast]); + }, [showToast]); // Segmented Manage/Why switch — rendered INLINE on the hero eyebrow row (one // register; the old labelled strip + helper sentence doubled what the hero and @@ -213,8 +213,6 @@ export default function MemoryTrust({ mind, workspaceId }: MemoryTrustProps) { <> { const [backupBusy, setBackupBusy] = useState(false); const [pendingApproval, setPendingApproval] = useState(null); const [approvalBusy, setApprovalBusy] = useState(false); + // Background fact extraction from chats (ADR-0007, decision 6). + const memoryCaps = useMemoryCapabilities(); + const extractionAvailable = memoryCaps?.capabilities.extraction === true; + const extractionOn = extractionAvailable && memoryCaps?.settings.extraction === true; + const [extractionSaving, setExtractionSaving] = useState(false); + const [extractionError, setExtractionError] = useState(null); + const toggleExtraction = async () => { + setExtractionSaving(true); + setExtractionError(null); + try { + setMemoryCapabilities(await adapter.setMemoryExtraction(!extractionOn)); + } catch { + setExtractionError('Could not save the memory setting. Try again.'); + } finally { + setExtractionSaving(false); + } + }; // Load settings useEffect(() => { @@ -435,6 +452,45 @@ const SettingsApp = () => {
+ {/* Memory: background fact extraction from chats (ADR-0007). Shown at + every level, because it decides what Waggle keeps about the user. */} +
+

+ + Memory +

+

+ While you chat, Waggle can pick out facts about you, like your role or how you like answers, and save them to your personal memory. It does this every few messages or when a chat goes quiet, with the model you chat with. You can confirm, correct or forget these facts in Memory. +

+
+
+

Learn facts about me from chats

+

+ {!memoryCaps + ? 'Checking memory settings...' + : !extractionAvailable + ? 'Not available: no model is set up for it.' + : extractionOn + ? 'On' + : 'Off. Waggle keeps only what you or the agent save on purpose.'} +

+
+ +
+ {extractionError && ( +

{extractionError}

+ )} +
+ {/* M2-7: Privacy & Telemetry — Phase 4.1: hidden at Essential per ux-disclosure-levels.md §"Settings at Essential" (telemetry surfaced only at Standard+, where the user is already opting into more advanced surface area). ADR-0006: shown at every level diff --git a/apps/web/src/components/os/apps/memory/MemoryCard.test.tsx b/apps/web/src/components/os/apps/memory/MemoryCard.test.tsx index 41251c8..08db28e 100644 --- a/apps/web/src/components/os/apps/memory/MemoryCard.test.tsx +++ b/apps/web/src/components/os/apps/memory/MemoryCard.test.tsx @@ -18,7 +18,6 @@ const memory: Memory = { confidence: 91, tags: ['research'], evidence: [], - hasOriginalSource: false, createdAt: '2026-07-08T08:00:00.000Z', updatedAt: '2026-07-08T09:00:00.000Z', }; diff --git a/apps/web/src/components/os/apps/memory/MemoryCard.tsx b/apps/web/src/components/os/apps/memory/MemoryCard.tsx index bea67a3..c160544 100644 --- a/apps/web/src/components/os/apps/memory/MemoryCard.tsx +++ b/apps/web/src/components/os/apps/memory/MemoryCard.tsx @@ -40,7 +40,8 @@ interface MemoryCardProps { export function MemoryCard({ memory, onClick, selected, onSelect, className, duplicateCount }: MemoryCardProps) { const status = statusMeta(memory.status); - const isProvisional = memory.importance === 'temporary'; + // Archiving also sets importance 'temporary' (hidden from recall); that is not provisional. + const isProvisional = memory.importance === 'temporary' && memory.status !== 'archived'; const showTitle = memory.title && memory.title !== memory.content; const selectionLabel = memory.title || memory.content.slice(0, 80) || memory.id; diff --git a/apps/web/src/components/os/apps/memory/MemoryCenterTab.tsx b/apps/web/src/components/os/apps/memory/MemoryCenterTab.tsx index 1ec1934..5b4746b 100644 --- a/apps/web/src/components/os/apps/memory/MemoryCenterTab.tsx +++ b/apps/web/src/components/os/apps/memory/MemoryCenterTab.tsx @@ -1,6 +1,6 @@ import { useState, useEffect, useCallback, useRef, useMemo } from 'react'; import { useReducedMotion } from 'framer-motion'; -import { Search, Loader2, Brain, Archive, Trash2, GitMerge, RotateCcw, Check, Save, AlertTriangle, ShieldOff } from 'lucide-react'; +import { Search, Loader2, Brain, Archive, Trash2, GitMerge, RotateCcw, Check, Save, ShieldOff } from 'lucide-react'; import { adapter } from '@/lib/adapter'; import { DATE_LOCALE } from '@/lib/date-locale'; import { consumeDeepLink } from '@/lib/app-deeplink'; @@ -20,16 +20,15 @@ import { cn } from '@/lib/utils'; /** * Memory Center (UX-Refactor Phase 2, S04). Self-contained tab (like HarvestTab): - * fetches the shared Memory entity via the new /api/memory* adapter methods and - * exposes source / confidence / evidence / scope + edit / archive / delete / merge - * (PRD §12.4, DoD #4; C11 merge). The 'Needs review' filter surfaces C33 imports - * (status=unreviewed). + * fetches the shared Memory entity via the /api/memory* adapter methods and + * exposes source / evidence / scope + edit / archive / delete / erase / merge + * (PRD §12.4, DoD #4; C11 merge). The 'Needs review' filter surfaces facts + * extracted from chats in the background and not yet confirmed (status=unreviewed). * * P3/D2 two-mind split: the tab is the per-mind LIST, parameterized by `mind` * (+ `workspaceId` for the workspace mind). Defaults to personal — the J08 deep - * link and pre-P3 call sites keep their behavior. Workspace-mind mutations MUST - * carry workspaceId or the server's candidateStores lookup misses the frame - * (personal-store-only search → 404). + * link and pre-P3 call sites keep their behavior. Memory ids are unique across + * scopes, so mutations need only the id. */ export interface MemoryCenterTabProps { @@ -52,13 +51,6 @@ const STATUS_FILTERS: { value: '' | MemoryStatus; label: string }[] = [ { value: 'unreviewed', label: 'Needs review' }, { value: 'active', label: 'Active' }, { value: 'archived', label: 'Archived' }, - { value: 'deprecated', label: 'Deprecated' }, -]; - -const CONFIDENCE_FILTERS: { value: number; label: string }[] = [ - { value: 0, label: 'Any confidence' }, - { value: 40, label: 'Medium+' }, - { value: 75, label: 'High only' }, ]; const CONTROL_FOCUS_CLASS = 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)] focus-visible:ring-offset-1 focus-visible:ring-offset-background'; @@ -68,7 +60,7 @@ export default function MemoryCenterTab({ workspaceId, consumeDeepLinks = true, }: MemoryCenterTabProps = {}) { - // Workspace-mind ops carry the workspace param; personal ops must not. + // The workspace list reads the workspace's memory; the personal list must not. const wsParam = mind === 'workspace' ? workspaceId : undefined; const reduceMotion = !!useReducedMotion(); // Wave T Lane D (item 2): seed the initial list from the session cache so a @@ -76,7 +68,7 @@ export default function MemoryCenterTab({ // spinning (R13-V1 finding). A fresh remount always lands on the default // filters, so the initial seed keys on those; the live key (below) also folds // in the active filters for the mid-session mind-switch path. - const initialCacheKey = memoryListCacheKey(['mc', mind, wsParam, '', '', 0, '']); + const initialCacheKey = memoryListCacheKey(['mc', mind, wsParam, '', '', '']); const [memories, setMemories] = useState(() => readMemoryListCache(initialCacheKey) ?? []); const [loading, setLoading] = useState(() => readMemoryListCache(initialCacheKey) === undefined); const [error, setError] = useState(null); @@ -88,13 +80,12 @@ export default function MemoryCenterTab({ // fresh open reading as "one card in a dark field". 'All' is now the honest // default; the curated 'active' view stays one click away as a labeled chip. const [status, setStatus] = useState<'' | MemoryStatus>(''); - const [minConfidence, setMinConfidence] = useState(0); // Wave T Lane D (item 2): the live cache key folds in the server-side filters // (this list fetches filtered). Held in a ref (updated every render) so the // mind-switch reset effect can reseed without taking a filter dependency — // reseeding on every keystroke would fight the debounced fetch. - const cacheKey = memoryListCacheKey(['mc', mind, wsParam, status, kind, minConfidence, q.trim()]); + const cacheKey = memoryListCacheKey(['mc', mind, wsParam, status, kind, q.trim()]); const cacheKeyRef = useRef(cacheKey); cacheKeyRef.current = cacheKey; @@ -104,36 +95,15 @@ export default function MemoryCenterTab({ const [draftContent, setDraftContent] = useState(''); const [draftKind, setDraftKind] = useState('fact'); - // #7 "View original source": inline expandable verbatim-source view in the - // detail drawer (not a nested modal). A frame can link MULTIPLE verbatim - // sources (metadata.archiveUids) → render each in its own escaped block; - // sourceRows is empty when the frame has no linked source → friendly empty state. - type ArchiveRow = { content: string; source: string; sourceRef: string | null; injectionFlagged: boolean; injectionFlags: string }; - const [sourceExpanded, setSourceExpanded] = useState(false); - const [sourceRows, setSourceRows] = useState([]); - const [sourceLoading, setSourceLoading] = useState(false); - const [sourceError, setSourceError] = useState(null); - // #7 P1 GDPR erasure receipt — a transient, dismissible confirmation of what - // the last Art.17 erase actually purged (compliance-grade transparency; the - // drawer closes on success, so the receipt lives at the list level). + // Erase receipt: a transient, dismissible confirmation of how many memories + // the last erase removed (the drawer closes on success, so the receipt lives + // at the list level). const [eraseNotice, setEraseNotice] = useState(null); - // #7 sticky erasure — the re-consent surface. A collapsible panel listing the - // (source, sourceRef) subjects a prior Art.17 erasure recorded; a re-import of any - // of them is skipped. "Allow re-import" lifts the suppression (deliberate re-consent). - type SuppressedRow = { source: string; sourceRef: string; erasedAt: string; reason: string | null }; type PendingApproval = | { kind: 'delete'; memory: Memory } - | { kind: 'erase'; memory: Memory } - | { kind: 'allow-reimport'; row: SuppressedRow }; - const [suppressionOpen, setSuppressionOpen] = useState(false); - const [suppressed, setSuppressed] = useState([]); - const [suppressionLoading, setSuppressionLoading] = useState(false); + | { kind: 'erase'; memory: Memory; sessionId: string }; const [pendingApproval, setPendingApproval] = useState(null); const [approvalBusy, setApprovalBusy] = useState(false); - // Latest source-fetch token: the id whose fetch is allowed to write state. A - // selection change (reset effect → undefined) or a newer fetch invalidates any - // in-flight request so a stale result can't land on the wrong memory. - const sourceReqIdRef = useRef(undefined); // J08: Home's "N memories need review" banner deep-links here with // {appId:'memory', filter:'unreviewed'}. Two paths (AutomationCenterApp @@ -192,7 +162,6 @@ export default function MemoryCenterTab({ q: q.trim() || undefined, kind: kind || undefined, status: status || undefined, - minConfidence: minConfidence || undefined, limit: 200, }); if (seq === loadSeq.current) { setMemories(res); writeMemoryListCache(cacheKey, res); } @@ -201,7 +170,7 @@ export default function MemoryCenterTab({ } finally { if (seq === loadSeq.current) setLoading(false); } - }, [q, kind, status, minConfidence, mind, wsParam, cacheKey]); + }, [q, kind, status, mind, wsParam, cacheKey]); useEffect(() => { const t = setTimeout(load, q ? 250 : 0); // debounce text search only @@ -210,8 +179,8 @@ export default function MemoryCenterTab({ // Mind switch invalidates EVERYTHING in flight and on screen (keyed on the // EFFECTIVE scope, so personal-mind instances ignore workspace churn): - // - selection/checklist: a drawer or merge set carried across minds would - // mutate the wrong store (ids collide across the per-mind SQLite DBs); + // - selection/checklist: a drawer or merge set from the other list must not + // act on memories that are no longer shown; // - the list: stale rows must not render under the new mind's pill; // - loadSeq: an in-flight old-mind response must not commit into the window // between this reset and the (debounced) next load starting; @@ -229,8 +198,6 @@ export default function MemoryCenterTab({ setMemories(cached ?? []); setLoading(cached === undefined); setEraseNotice(null); // a receipt for the prior mind must not persist across the switch - setSuppressionOpen(false); // the erased-source list is per-mind — collapse + drop stale rows - setSuppressed([]); setPendingApproval(null); setApprovalBusy(false); }, [mind, wsParam]); @@ -241,37 +208,6 @@ export default function MemoryCenterTab({ setDraftKind(m.kind); }; - // Reset the verbatim-source view whenever the selected memory changes (incl. - // closing the drawer) so a previously-opened source can't leak into another row. - useEffect(() => { - setSourceExpanded(false); - setSourceRows([]); - setSourceError(null); - setSourceLoading(false); - sourceReqIdRef.current = undefined; // invalidate any in-flight fetch for the prior memory - }, [selected?.id]); - - // Toggle the inline source view; lazy-fetch the verbatim row on first open. - const viewOriginalSource = async () => { - if (!selected) return; - if (sourceExpanded) { setSourceExpanded(false); return; } - const reqId = selected.id; - sourceReqIdRef.current = reqId; - setSourceExpanded(true); - setSourceLoading(true); - setSourceError(null); - try { - const res = await adapter.getMemoryOriginalSource(reqId, wsParam, mind); - if (sourceReqIdRef.current !== reqId) return; // selection changed mid-flight — drop stale result - setSourceRows(res.archiveRows); - } catch (e) { - if (sourceReqIdRef.current !== reqId) return; - setSourceError(e instanceof Error ? e.message : 'Failed to load original source'); - } finally { - if (sourceReqIdRef.current === reqId) setSourceLoading(false); - } - }; - const toggleChecked = (id: string, on: boolean) => { setChecked((prev) => { const next = new Set(prev); @@ -281,7 +217,7 @@ export default function MemoryCenterTab({ }; const mutate = async (fn: () => Promise, closeDrawer = false) => { - setEraseNotice(null); // drop any stale receipt; erase()'s own fn re-sets it on success + setEraseNotice(null); // drop any stale erase receipt setBusy(true); try { await fn(); @@ -302,48 +238,27 @@ export default function MemoryCenterTab({ if (draftContent !== selected.content) patch.content = draftContent; if (draftKind !== selected.kind) patch.kind = draftKind; if (Object.keys(patch).length === 0) { setSelected(null); return; } - void mutate(() => adapter.patchMemory(selected.id, patch, wsParam, mind), true); + void mutate(() => adapter.patchMemory(selected.id, patch), true); }; - const archive = (m: Memory) => void mutate(() => adapter.archiveMemory(m.id, wsParam, mind), true); - const unarchive = (m: Memory) => void mutate(() => adapter.patchMemory(m.id, { status: 'active' }, wsParam, mind), true); - const markReviewed = (m: Memory) => void mutate(() => adapter.patchMemory(m.id, { status: 'active' }, wsParam, mind), true); + const archive = (m: Memory) => void mutate(() => adapter.archiveMemory(m.id), true); + const unarchive = (m: Memory) => void mutate(() => adapter.patchMemory(m.id, { status: 'active' }), true); + const markReviewed = (m: Memory) => void mutate(() => adapter.patchMemory(m.id, { status: 'active' }), true); const remove = (m: Memory) => setPendingApproval({ kind: 'delete', memory: m }); - // #7 P1 GDPR Art.17 "right to erasure" — the FULL sweep (this memory + its - // original source text + every search-index entry + knowledge-graph facts - // derived solely from it + the verbatim conversation turns behind it). Runs - // server-side in one atomic transaction. Distinct from Delete (removes just - // this one record) and Archive (hides it). Irreversible → strong confirm + - // a receipt of exactly what was purged. - const erase = (m: Memory) => setPendingApproval({ kind: 'erase', memory: m }); + // Erase: forget every memory saved from the chat this memory came from. + // Offered only for memories with a chat session; Delete covers the rest. + const erase = (m: Memory) => { + if (m.sessionId) setPendingApproval({ kind: 'erase', memory: m, sessionId: m.sessionId }); + }; const mergeSelected = () => { const ids = [...checked]; if (ids.length < 2) return; void mutate(async () => { - await adapter.mergeMemories(ids, { workspaceId: wsParam, mind }); + await adapter.mergeMemories(ids); setChecked(new Set()); }); }; - // #7 sticky erasure re-consent surface — lazy-loaded when the panel opens. - const loadSuppression = useCallback(async () => { - setSuppressionLoading(true); - try { - const res = await adapter.listSuppression({ workspaceId: wsParam, mind }); - setSuppressed(res.suppressed); - } catch { - setSuppressed([]); - } finally { - setSuppressionLoading(false); - } - }, [wsParam, mind]); - const toggleSuppression = () => { - const next = !suppressionOpen; - setSuppressionOpen(next); - if (next) void loadSuppression(); - }; - const allowReimport = (row: SuppressedRow) => setPendingApproval({ kind: 'allow-reimport', row }); - const approvalRequest = useMemo(() => { if (!pendingApproval) return null; if (pendingApproval.kind === 'delete') { @@ -357,32 +272,20 @@ export default function MemoryCenterTab({ riskLevel: 'high', }; } - if (pendingApproval.kind === 'erase') { - return { - action: `Erase memory and derived data: ${pendingApproval.memory.title}`, - scope: [ - 'This permanently removes the memory, its original source text, search index entries, related conversation turns, and derived knowledge facts.', - 'This is a GDPR Art.17 erasure action and cannot be undone.', - 'Use Archive to hide it, or Delete to remove only this one record.', - ], - riskLevel: 'critical', - }; - } return { - action: `Allow source to be re-imported: ${pendingApproval.row.sourceRef}`, + action: 'Erase everything remembered from this chat', scope: [ - `Source: ${pendingApproval.row.source} / ${pendingApproval.row.sourceRef}`, - 'This lifts the GDPR Art.17 erasure suppression for this source.', - 'A future import can re-materialize it; use this only when the data subject has re-consented.', + 'This removes this memory and every other memory Waggle saved from the same chat, in personal and workspace memory, so it no longer recalls them.', + 'The chat transcript itself is kept.', + 'This cannot be undone. Use Delete to remove only this memory.', ], - riskLevel: 'high', + riskLevel: 'critical', }; }, [pendingApproval]); const approvalLabel = pendingApproval?.kind === 'delete' ? (approvalBusy ? 'Deleting...' : 'Delete memory') - : pendingApproval?.kind === 'erase' ? (approvalBusy ? 'Erasing...' : 'Erase memory') - : approvalBusy ? 'Allowing...' : 'Allow re-import'; + : approvalBusy ? 'Erasing...' : 'Erase memories'; const confirmTrustAction = async () => { if (!pendingApproval) return; @@ -390,37 +293,20 @@ export default function MemoryCenterTab({ setApprovalBusy(true); setEraseNotice(null); try { + setBusy(true); if (current.kind === 'delete') { - setBusy(true); - await adapter.deleteMemoryById(current.memory.id, wsParam, mind); - setSelected(null); - setPendingApproval(null); - setReloadTick((t) => t + 1); - return; + await adapter.deleteMemoryById(current.memory.id); + } else { + const { deleted } = await adapter.eraseMemory({ sessionId: current.sessionId }); + setEraseNotice(`Erased ${deleted} ${deleted === 1 ? 'memory' : 'memories'} from that chat.`); } - if (current.kind === 'erase') { - setBusy(true); - const { result } = await adapter.eraseMemory({ frameId: current.memory.id }, { workspaceId: wsParam, mind }); - const parts = [ - `${result.framesDeleted} ${result.framesDeleted === 1 ? 'memory' : 'memories'} erased`, - result.archiveRedacted > 0 ? `${result.archiveRedacted} source ${result.archiveRedacted === 1 ? 'record' : 'records'} redacted` : null, - result.entitiesErased > 0 ? `${result.entitiesErased} knowledge ${result.entitiesErased === 1 ? 'entity' : 'entities'} removed` : null, - ].filter(Boolean); - setEraseNotice(`Erased "${current.memory.title}": ${parts.join(' · ')}.`); - setSelected(null); - setPendingApproval(null); - setReloadTick((t) => t + 1); - return; - } - setSuppressionLoading(true); - await adapter.allowReimport({ source: current.row.source, sourceRef: current.row.sourceRef }, { workspaceId: wsParam, mind }); + setSelected(null); setPendingApproval(null); - await loadSuppression(); + setReloadTick((t) => t + 1); } catch (e) { setError(e instanceof Error ? e.message : 'Action failed'); } finally { - if (current.kind === 'allow-reimport') setSuppressionLoading(false); - else setBusy(false); + setBusy(false); setApprovalBusy(false); } }; @@ -437,12 +323,10 @@ export default function MemoryCenterTab({ const statusLabel = STATUS_FILTERS.find((s) => s.value === status)?.label; if (status && statusLabel) parts.push(statusLabel); if (kind) parts.push(memoryKindLabel(kind)); - const confLabel = CONFIDENCE_FILTERS.find((c) => c.value === minConfidence)?.label; - if (minConfidence && confLabel) parts.push(confLabel); const query = q.trim(); if (query) parts.push(`matching "${query}"`); return parts.join(' · '); - }, [status, kind, minConfidence, q]); + }, [status, kind, q]); return ( // Wave U Lane E (item 4): a ~150ms fade-slide when this panel mounts on the @@ -467,16 +351,6 @@ export default function MemoryCenterTab({ className="flex-1 bg-transparent text-xs h-auto border-0 p-0 focus-visible:ring-0 focus-visible:ring-offset-0" /> -
@@ -527,7 +401,7 @@ export default function MemoryCenterTab({ )}
- {/* #7 P1 GDPR erasure receipt — dismissible confirmation of what was purged. */} + {/* Erase receipt — dismissible confirmation of what was removed. */} {eraseNotice && (
@@ -536,42 +410,6 @@ export default function MemoryCenterTab({
)} - {/* #7 sticky erasure — re-consent surface: erased sources kept from re-importing. */} -
- - {suppressionOpen && ( -
- {suppressionLoading ? ( -
Loading…
- ) : suppressed.length === 0 ? ( -
- No erased sources are suppressed. Erasing a source keeps it from re-materializing if it's re-imported later. -
- ) : ( - suppressed.map((row) => ( -
- {row.source} - {row.sourceRef} - -
- )) - )} -
- )} -
- {/* Wave V Lane A (item 2): result-count header — Trust-hero parity. Rendered only when there are rows to frame; the skeleton / empty / error branches own the empty-list surface below. When a background refresh is in flight @@ -627,11 +465,11 @@ export default function MemoryCenterTab({

{mind === 'workspace' && !workspaceId ? 'No workspace selected — open a workspace to see what it has learned.' - : q || kind || status || minConfidence + : q || kind || status ? 'No memories match these filters.' : mind === 'workspace' ? 'Nothing learned in this workspace yet — memories appear here as you work.' - : 'No memories yet — import or capture some to get started.'} + : 'No memories yet. They appear here as you chat, or when you capture a note.'}

) : ( @@ -683,14 +521,16 @@ export default function MemoryCenterTab({ - + {selected.sessionId && ( + + )} ) : undefined} > @@ -736,49 +576,7 @@ export default function MemoryCenterTab({
- - - {sourceExpanded && ( -
- {sourceLoading ? ( -
- Loading original source… -
- ) : sourceError ? ( -
{sourceError}
- ) : sourceRows.length > 0 ? ( - /* One frame can be distilled from MULTIPLE verbatim sources — render - each in its own React-escaped
 (NEVER dangerouslySetInnerHTML:
-                     the archive is hostile-by-assumption) with its own provenance label
-                     and advisory injection badge. */
-                  sourceRows.map((row, i) => (
-                    
0 && 'border-t border-border/60 pt-2')}> -
- - Original source{sourceRows.length > 1 ? ` ${i + 1} of ${sourceRows.length}` : ''} - - {row.injectionFlagged && ( - - Injection flagged - - )} -
-

- {row.source}{row.sourceRef ? ` · ${row.sourceRef}` : ''} -

-
-                        {row.content}
-                      
-
- )) - ) : ( -

No original source recorded for this memory.

- )} -
- )} +

Created {new Date(selected.createdAt).toLocaleString(DATE_LOCALE)} diff --git a/apps/web/src/components/os/apps/memory/MemoryTrustManage.tsx b/apps/web/src/components/os/apps/memory/MemoryTrustManage.tsx index cf698d2..fcf2e58 100644 --- a/apps/web/src/components/os/apps/memory/MemoryTrustManage.tsx +++ b/apps/web/src/components/os/apps/memory/MemoryTrustManage.tsx @@ -14,6 +14,7 @@ import { DetailDrawer } from '@/components/ui/detail-drawer'; import { EvidencePanel } from '@/components/ui/evidence-panel'; import { renderChatMarkdown } from '@/lib/render-markdown'; import { cn } from '@/lib/utils'; +import { memoryLabel } from './memory-label'; /** * Memory-Trust "Manage" view (screen 19 §3–§5, PR3.5 Phase B+C). The editorial @@ -21,8 +22,8 @@ import { cn } from '@/lib/utils'; * stat bar → search + filter chips → native confidence-ring rows with the * 3-segment ⬡ provenance line and real forget / correct / confirm actions. * - * No-fabrication contract: confidence is harvest-only → the ring shows "—" and - * the "High confidence & fresh" stat gates to "—" when absent; freshness is + * No-fabrication contract: the memory contract stores no confidence in v1 → no + * ring is drawn and the "high confidence" stat gates to "—" when absent; freshness is * derived as honest AGE (never a stored %); the "Forgotten" filter is gated off * (hard delete leaves no tombstone). Stats are computed from the fetched * working set (single-mind; cap-aware "500+") — never a cross-mind count. @@ -236,9 +237,8 @@ function MemoryRow({ memory, onOpen, onForget, onConfirm, busy, duplicateCount, const srcLabel = frameSourceLabel(memory.source); const stale = isStale(memory); const needsConfirm = memory.status === 'unreviewed'; - // Round-6 fix 2b: the ring renders only when a confidence actually exists; - // the unscored state is a single quiet inline badge on the provenance row - // (the old stacked "unscored / CONF" micro-label was illegible). + // Round-6 fix 2b: the ring renders only when a confidence actually exists. + // The memory contract stores none in v1, so unscored rows show no badge. const scored = typeof memory.confidence === 'number' && Number.isFinite(memory.confidence); // Round-5..9: raw harvest strings read as log output — buildMemoryPreview // leads with the first line as a title, clamps the rest as a muted excerpt, @@ -281,7 +281,7 @@ function MemoryRow({ memory, onOpen, onForget, onConfirm, busy, duplicateCount, neutral tier. Wave X Lane B: --text-dim is 4.09:1 on --surface-2 at 12px (sub-AA) and this is the memory's correction HANDLE, not decoration — matched to its row's --text-muted (5.6:1). */} - ⬡ M-{memory.id} + ⬡ {memoryLabel(memory.id)} {/* Wave-S Lane C: handoff meta + source folded into one glyph chip (short label at rest, full provenance in the tooltip). */} {provShort && ( @@ -293,14 +293,6 @@ function MemoryRow({ memory, onOpen, onForget, onConfirm, busy, duplicateCount, {provShort} )} - {!scored && ( - - not scored yet - - )} ● {fresh.label} @@ -352,7 +344,7 @@ function MemoryRow({ memory, onOpen, onForget, onConfirm, busy, duplicateCount, onClick={onConfirm} disabled={busy} title="Confirm this memory" - aria-label={`Confirm memory M-${memory.id}`} + aria-label={`Confirm memory ${memoryLabel(memory.id)}`} className="relative grid h-[30px] w-[30px] place-items-center rounded-[8px] border border-[var(--line-soft)] bg-[var(--surface-2)] text-[var(--text-muted)] before:absolute before:left-1/2 before:top-1/2 before:h-10 before:w-10 before:-translate-x-1/2 before:-translate-y-1/2 before:content-[''] hover:border-[var(--healthy)] hover:text-[var(--healthy)] disabled:opacity-50" > @@ -362,7 +354,7 @@ function MemoryRow({ memory, onOpen, onForget, onConfirm, busy, duplicateCount, type="button" onClick={onOpen} title="Edit / correct" - aria-label={`Edit or correct memory M-${memory.id}`} + aria-label={`Edit or correct memory ${memoryLabel(memory.id)}`} className="relative grid h-[30px] w-[30px] place-items-center rounded-[8px] border border-[var(--line-soft)] bg-[var(--surface-2)] text-[var(--text-muted)] before:absolute before:left-1/2 before:top-1/2 before:h-10 before:w-10 before:-translate-x-1/2 before:-translate-y-1/2 before:content-[''] hover:border-[var(--honey-line)] hover:text-[var(--honey-text)]" > @@ -372,7 +364,7 @@ function MemoryRow({ memory, onOpen, onForget, onConfirm, busy, duplicateCount, onClick={onForget} disabled={busy} title="Forget this" - aria-label={`Forget memory M-${memory.id}`} + aria-label={`Forget memory ${memoryLabel(memory.id)}`} className="relative grid h-[30px] w-[30px] place-items-center rounded-[8px] border border-[var(--line-soft)] bg-[var(--surface-2)] text-[var(--text-muted)] before:absolute before:left-1/2 before:top-1/2 before:h-10 before:w-10 before:-translate-x-1/2 before:-translate-y-1/2 before:content-[''] hover:border-[color-mix(in_srgb,var(--risk)_45%,transparent)] hover:text-[var(--risk)] disabled:opacity-50" > @@ -588,13 +580,13 @@ export default function MemoryTrustManage({ mind, workspaceId, onToast, onWhy, o // closeDrawer=true so the editor doesn't strand on a deleted/confirmed memory // (review M). const forget = (m: Memory, closeDrawer = false) => - void mutate(() => adapter.deleteMemoryById(m.id, wsParam, mind), `Forgotten M-${m.id} — removed from recall`, closeDrawer); + void mutate(() => adapter.deleteMemoryById(m.id), `Forgotten ${memoryLabel(m.id)} — removed from recall`, closeDrawer); const confirmMemory = (m: Memory, closeDrawer = false) => - void mutate(() => adapter.confirmMemory(m.id, wsParam, mind), `Confirmed M-${m.id} — marked reviewed`, closeDrawer); + void mutate(() => adapter.confirmMemory(m.id), `Confirmed ${memoryLabel(m.id)} — marked reviewed`, closeDrawer); const saveCorrection = () => { if (!selected) return; if (draft === selected.content) { setSelected(null); return; } - void mutate(() => adapter.patchMemory(selected.id, { content: draft }, wsParam, mind), `Corrected M-${selected.id}`, true); + void mutate(() => adapter.patchMemory(selected.id, { content: draft }), `Corrected ${memoryLabel(selected.id)}`, true); }; const openDetail = (m: Memory) => { setSelected(m); setDraft(m.content); }; @@ -731,7 +723,7 @@ export default function MemoryTrustManage({ mind, workspaceId, onToast, onWhy, o open={!!selected} onOpenChange={(o) => { if (!o) setSelected(null); }} title={selected?.title ?? 'Memory'} - subtitle={selected ? `M-${selected.id} · ${selected.scope}` : undefined} + subtitle={selected ? `${memoryLabel(selected.id)} · ${selected.scope}` : undefined} footer={selected ? (

real execution trace diff --git a/apps/web/src/components/os/apps/memory/TimelineTab.tsx b/apps/web/src/components/os/apps/memory/TimelineTab.tsx index b743dba..8b0a43f 100644 --- a/apps/web/src/components/os/apps/memory/TimelineTab.tsx +++ b/apps/web/src/components/os/apps/memory/TimelineTab.tsx @@ -1,5 +1,5 @@ import { useState } from 'react'; -import { Brain, Search, Clock, Trash2, Edit3, Filter, Eye, Copy, Loader2, AlertTriangle, ClipboardList, Calendar, Lightbulb, Scale, CheckSquare, Tag, FileText, type LucideIcon } from 'lucide-react'; +import { Brain, Search, Clock, Trash2, Edit3, Filter, Eye, Copy, Loader2, AlertTriangle, ClipboardList, Calendar, Heart, User, Scale, StickyNote, FileText, type LucideIcon } from 'lucide-react'; import { AnimatePresence } from 'framer-motion'; import { Input } from '@/components/ui/input'; import { DATE_LOCALE } from '@/lib/date-locale'; @@ -17,11 +17,11 @@ import { HintTooltip } from '@/components/ui/hint-tooltip'; */ // Lucide, not emoji — one icon language across the chrome (2026-07-06 P2). -const frameTypeIcons: Record = { - fact: ClipboardList, event: Calendar, insight: Lightbulb, decision: Scale, task: CheckSquare, entity: Tag, +const frameTypeIcons: Record = { + fact: ClipboardList, event: Calendar, preference: Heart, profile: User, decision: Scale, summary: FileText, note: StickyNote, }; -const FRAME_TYPES = ['fact', 'event', 'insight', 'decision', 'task', 'entity']; +const FRAME_TYPES = Object.keys(frameTypeIcons) as MemoryFrame['type'][]; const importanceColors = ['text-muted-foreground', 'text-muted-foreground', 'text-foreground', 'text-honey', 'text-amber-400', 'text-destructive']; @@ -82,7 +82,7 @@ const TimelineTab = ({ }); }; - const toggleTypeFilter = (type: string) => { + const toggleTypeFilter = (type: MemoryFrame['type']) => { if (!onTypeFiltersChange) return; if (typeFilters.includes(type)) { onTypeFiltersChange(typeFilters.filter(t => t !== type)); @@ -163,10 +163,7 @@ const TimelineTab = ({
{frames.map(f => ( -
- - {/* F24: plain-language explainer so the panel isn't opaque jargon. */} -

- The Weaver tidies your memory in the background — it merges duplicate facts, links related - ones, and lets stale details fade so what surfaces stays sharp. Run Now does that pass immediately instead of waiting for the next scheduled sweep. -

- -
-
-
- - Last Consolidation -
-

{timeAgo(personalMind.lastConsolidation)}

-
-
-
- - Last Decay - - - -
-

{timeAgo(personalMind.lastDecay)}

-
-
-
- - Active Timers -
-

- {personalMind.timerActive ? 1 : 0} personal + {activeWorkspaces} workspace{activeWorkspaces !== 1 ? 's' : ''} -

-
-
- - {workspaces.length > 0 && ( -
-

Workspace Health

-
- {workspaces.map(ws => ( -
- {wsNames[ws.id] ?? ws.id} -
- {timeAgo(ws.lastConsolidation)} - -
-
- ))} -
-
- )} - - {lastResult && ( -
-

- Last Run Results -

- {lastResult.results.map(r => ( -
- {wsNames[r.target] ?? r.target} - +{r.framesConsolidated} consolidated - {r.framesDecayed} decayed - {r.framesStrengthened} strengthened -
- ))} -
- )} -
- ); -} diff --git a/apps/web/src/components/os/apps/memory/memory-label.ts b/apps/web/src/components/os/apps/memory/memory-label.ts new file mode 100644 index 0000000..5085604 --- /dev/null +++ b/apps/web/src/components/os/apps/memory/memory-label.ts @@ -0,0 +1,4 @@ +/** Short display label of a memory id ("M-" plus the first 8 characters of the id). */ +export function memoryLabel(id: string): string { + return `M-${id.slice(0, 8)}`; +} diff --git a/apps/web/src/components/ui/evidence-panel.tsx b/apps/web/src/components/ui/evidence-panel.tsx index cac0fd1..3fc1598 100644 --- a/apps/web/src/components/ui/evidence-panel.tsx +++ b/apps/web/src/components/ui/evidence-panel.tsx @@ -1,4 +1,3 @@ -import { Eye } from 'lucide-react'; import { cn } from '@/lib/utils'; import { EvidenceChip } from './evidence-chip'; @@ -13,22 +12,10 @@ interface EvidencePanelProps { sourceId?: string | null; sourceUrl?: string | null; evidence?: string[]; - /** #7 "View original source": when supplied (and a linked archive exists, i.e. - * hasOriginalSource), renders an Eye button that opens the verbatim source view - * in the detail drawer. */ - onViewOriginalSource?: () => void; - /** Whether a verbatim raw_archive row is actually linked. Gates the Eye button so - * a sourceId-only frame (e.g. an auto-synced summary) never shows a View-original - * affordance that would 404 — see Memory.hasOriginalSource. */ - hasOriginalSource?: boolean; - /** Whether the source view is currently open (drives aria-expanded). */ - expanded?: boolean; - /** Whether the source fetch is in flight (drives aria-busy + disables the button). */ - busy?: boolean; className?: string; } -export function EvidencePanel({ source, sourceId, sourceUrl, evidence, onViewOriginalSource, hasOriginalSource, expanded, busy, className }: EvidencePanelProps) { +export function EvidencePanel({ source, sourceId, sourceUrl, evidence, className }: EvidencePanelProps) { const hasEvidence = Array.isArray(evidence) && evidence.length > 0; if (!source && !sourceId && !sourceUrl && !hasEvidence) return null; @@ -42,20 +29,6 @@ export function EvidencePanel({ source, sourceId, sourceUrl, evidence, onViewOri
{source && } {sourceId && } - {hasOriginalSource && onViewOriginalSource && ( - - )} {sourceUrl && }
{hasEvidence && ( diff --git a/apps/web/src/hooks/useMemory.ts b/apps/web/src/hooks/useMemory.ts index cffd4a5..2a9dcb8 100644 --- a/apps/web/src/hooks/useMemory.ts +++ b/apps/web/src/hooks/useMemory.ts @@ -21,8 +21,9 @@ export const useMemory = (workspaceId: string | null) => { if (!workspaceId) return; setLoading(true); try { + // Search covers what the list shows: personal memory plus this workspace's. const data = filters.searchQuery - ? await adapter.searchMemory(filters.searchQuery, workspaceId) + ? await adapter.searchMemory(filters.searchQuery, 'all', workspaceId) : await adapter.getMemoryFrames(workspaceId); setFrames(data); setError(null); @@ -54,15 +55,6 @@ export const useMemory = (workspaceId: string | null) => { setFrames(prev => prev.map(f => f.id === id ? updated : f)); }, []); - const incrementAccess = useCallback(async (id: string) => { - try { - const { accessCount } = await adapter.incrementFrameAccess(id, workspaceId ?? undefined); - setFrames(prev => prev.map(f => f.id === id ? { ...f, metadata: { ...f.metadata, accessCount } } : f)); - } catch (err) { - console.error('[useMemory] incrementAccess failed:', err); - } - }, [workspaceId]); - const deleteFrame = useCallback(async (id: string) => { await adapter.deleteMemoryFrame(id); setFrames(prev => prev.filter(f => f.id !== id)); @@ -78,7 +70,7 @@ export const useMemory = (workspaceId: string | null) => { return { frames: filteredFrames, selectedFrame, setSelectedFrame, loading, error, filters, setFilters, - addFrame, editFrame, deleteFrame, incrementAccess, refresh: fetchFrames, + addFrame, editFrame, deleteFrame, refresh: fetchFrames, stats: { total: frames.length, filtered: filteredFrames.length, entities: entityCount, relations: relationCount }, }; }; diff --git a/apps/web/src/lib/adapter.tauri-branch.test.ts b/apps/web/src/lib/adapter.tauri-branch.test.ts index f068a55..09e92f5 100644 --- a/apps/web/src/lib/adapter.tauri-branch.test.ts +++ b/apps/web/src/lib/adapter.tauri-branch.test.ts @@ -64,7 +64,7 @@ describe('adapter isTauri() branch routing', () => { }); await adapter.addMemoryFrame({ - type: 'insight', + type: 'fact', title: 'test', content: 'saved', importance: 3, // numeric → 'high' via IMPORTANCE_NUM_TO_STRING diff --git a/apps/web/src/lib/adapter.ts b/apps/web/src/lib/adapter.ts index ad406b8..88bb97e 100644 --- a/apps/web/src/lib/adapter.ts +++ b/apps/web/src/lib/adapter.ts @@ -27,7 +27,7 @@ import type { WorkspaceStateView, WorkspaceActivityEvent, WorkspaceTask, Artifact, RelatedSearchResult, Agent, AgentTrace, Automation, AutomationLog, EngineStatus, PendingApprovalItem, - MemoryTrace, + MemoryTrace, MemoryCapabilitiesResponse, } from './types'; import type { Command, CommandResult, WorkspaceType, @@ -215,13 +215,13 @@ function unwrapArray(data: any): T[] { return []; } -/** Map backend frameType codes to frontend type names */ -const FRAME_TYPE_MAP: Record = { - I: 'insight', F: 'fact', E: 'event', D: 'decision', T: 'task', N: 'entity', - insight: 'insight', fact: 'fact', event: 'event', decision: 'decision', task: 'task', entity: 'entity', -}; +/** Memory kinds of the memory contract; anything else reads as a fact. */ +const MEMORY_FRAME_KINDS: ReadonlySet = new Set([ + 'fact', 'event', 'preference', 'profile', 'decision', 'summary', 'note', +]); +/** Contract importance (and the Tauri command's low/high) on the 1-4 scale. */ const IMPORTANCE_MAP: Record = { - low: 1, normal: 2, high: 3, critical: 4, + temporary: 1, low: 1, normal: 2, important: 3, high: 3, critical: 4, }; /** Normalize a backend cron schedule row to the frontend CronJob shape. */ @@ -242,23 +242,23 @@ function normalizeCronJob(raw: Record): CronJob { }; } -/** Normalize a backend memory frame to the frontend MemoryFrame shape */ +/** Normalize a memory from `/api/memory/search|frames` to the frontend MemoryFrame shape */ function normalizeFrame(raw: any): MemoryFrame { const content = raw.content ?? ''; + const kind = raw.kind ?? raw.type; return { id: String(raw.id), - type: (FRAME_TYPE_MAP[raw.frameType] ?? FRAME_TYPE_MAP[raw.type] ?? 'fact') as MemoryFrame['type'], + type: (MEMORY_FRAME_KINDS.has(kind) ? kind : 'fact') as MemoryFrame['type'], title: content.split('\n')[0].slice(0, 80), content, importance: typeof raw.importance === 'number' ? raw.importance : (IMPORTANCE_MAP[raw.importance] ?? 2), timestamp: raw.timestamp ?? raw.created_at ?? '', - workspaceId: raw.mind ?? raw.workspaceId ?? '', + workspaceId: raw.workspaceId ?? '', metadata: { source: raw.source, - gop: raw.gop, - accessCount: raw.accessCount, + mind: raw.mind, // Lifecycle status — consumers (e.g. briefing highlights) must keep - // deprecated/archived frames off hero surfaces. + // archived frames off hero surfaces. status: raw.status ?? raw.metadata?.status, }, }; @@ -1187,7 +1187,7 @@ class LocalAdapter { // --- Memory --- async getMemoryFrames(workspaceId: string, limit = 50): Promise { - const res = await this.fetch(`/api/memory/frames?limit=${limit}&workspace=${workspaceId}`); + const res = await this.fetch(`/api/memory/frames?limit=${limit}&workspace=${encodeURIComponent(workspaceId)}`); return unwrapArray(await res.json()).map(normalizeFrame); } @@ -1220,36 +1220,50 @@ class LocalAdapter { await this.fetch(`/api/memory/frames/${id}`, { method: 'DELETE' }); } - async incrementFrameAccess(id: string, workspaceId?: string): Promise<{ accessCount: number }> { - const qs = workspaceId ? `?workspace=${encodeURIComponent(workspaceId)}` : ''; - const res = await this.fetch(`/api/memory/frames/${id}/access${qs}`, { method: 'PATCH' }); - const body = await res.json() as { accessCount?: number }; - return { accessCount: typeof body.accessCount === 'number' ? body.accessCount : 0 }; - } - - async searchMemory(query: string, scope?: string): Promise { + /** + * Ranked memory search. `scope`: 'personal', 'workspace' (the given + * workspace), 'all' (personal plus the given workspace, the default) or + * 'global' (personal plus every workspace). + */ + async searchMemory( + query: string, + scope?: 'all' | 'personal' | 'workspace' | 'global', + workspaceId?: string, + ): Promise { // CC Sesija A §2.2 — Tauri IPC path for desktop builds. if (isTauri()) { - const resp = await tauriRecallMemory({ - query, - scope: scope as 'all' | 'personal' | 'workspace' | 'global' | undefined, - }); + const resp = await tauriRecallMemory({ query, scope, ...(workspaceId && { workspaceId }) }); return resp.results.map((r) => normalizeFrame(r as Record)); } - const res = await this.fetch(`/api/memory/search?q=${encodeURIComponent(query)}${scope ? `&scope=${scope}` : ''}`); + const p = new URLSearchParams({ q: query }); + if (scope) p.set('scope', scope); + if (workspaceId) p.set('workspace', workspaceId); + const res = await this.fetch(`/api/memory/search?${p}`); return unwrapArray(await res.json()).map(normalizeFrame); } + /** What the memory store supports, and whether background fact extraction is on. */ + async getMemoryCapabilities(): Promise { + const res = await this.fetch('/api/memory/capabilities'); + if (!res.ok) throw new Error(`getMemoryCapabilities failed: ${res.status}`); + return res.json(); + } + + /** Turn background fact extraction from chats on or off. */ + async setMemoryExtraction(enabled: boolean): Promise { + const res = await this.fetch('/api/memory/settings', { method: 'PUT', body: JSON.stringify({ extraction: enabled }) }); + if (!res.ok) throw new Error(`setMemoryExtraction failed: ${res.status}`); + return res.json(); + } + // --- Memory Center (UX-Refactor Phase 2 — shared Memory entity, S04) --- - // These hit the new bare /api/memory* routes (memory-center.ts) and return the - // shared `Memory` shape (kind/confidence/scope/status/evidence/...), distinct - // from the legacy frame methods above. HTTP path works in web + desktop (the - // sidecar is bundled), so no Tauri IPC branch is needed. + // These hit the bare /api/memory* routes (memory-center.ts) and return the + // shared `Memory` shape. Memory ids are unique across personal and workspace + // memory, so the single-memory calls need no scope. async listMemories(opts: { - workspaceId?: string; kind?: string; status?: string; scope?: string; - q?: string; minConfidence?: number; limit?: number; - /** P3/D2 two-mind split — select a single mind; omit for the legacy merge. */ + workspaceId?: string; kind?: string; status?: string; q?: string; limit?: number; + /** Read one scope; omit to merge personal memory and the workspace's. */ mind?: 'personal' | 'workspace'; } = {}): Promise { const p = new URLSearchParams(); @@ -1257,9 +1271,7 @@ class LocalAdapter { if (opts.workspaceId) p.set('workspace', opts.workspaceId); if (opts.kind) p.set('kind', opts.kind); if (opts.status) p.set('status', opts.status); - if (opts.scope) p.set('scope', opts.scope); if (opts.q) p.set('q', opts.q); - if (typeof opts.minConfidence === 'number') p.set('minConfidence', String(opts.minConfidence)); if (typeof opts.limit === 'number') p.set('limit', String(opts.limit)); const qs = p.toString(); const res = await this.fetch(`/api/memory${qs ? `?${qs}` : ''}`); @@ -1271,31 +1283,18 @@ class LocalAdapter { return body.results ?? []; } - /** Query string for the single-memory routes. `mind` makes server-side store - * resolution STRICT (P3/D2): frame ids collide across the per-mind SQLite - * DBs, so a workspace-scoped mutation must never fall through to (and - * destroy) a colliding personal frame. Callers that know the mind — the - * Memory Center always does — should pass it. */ - private memoryScopeQs(workspaceId?: string, mind?: 'personal' | 'workspace'): string { - const p = new URLSearchParams(); - if (workspaceId) p.set('workspace', workspaceId); - if (mind) p.set('mind', mind); - const s = p.toString(); - return s ? `?${s}` : ''; - } - - async getMemory(id: string, workspaceId?: string, mind?: 'personal' | 'workspace'): Promise { + async getMemory(id: string): Promise { // P1b D3: fetchRaw preserves the documented 404→null contract (the // throwing fetch would reject before the status check). - const res = await this.fetchRaw(`/api/memory/${encodeURIComponent(id)}${this.memoryScopeQs(workspaceId, mind)}`); + const res = await this.fetchRaw(`/api/memory/${encodeURIComponent(id)}`); if (res.status === 404) return null; if (!res.ok) throw new AdapterHttpError(res.status, res.statusText, await res.clone().json().catch(() => undefined)); return res.json(); } async createMemory(input: { - content: string; kind?: string; scope?: string; tags?: string[]; - importance?: string; title?: string; confidence?: number; workspaceId?: string; + content: string; kind?: string; tags?: string[]; + importance?: string; title?: string; workspaceId?: string; }): Promise { const res = await this.fetch('/api/memory', { method: 'POST', body: JSON.stringify(input) }); return res.json(); @@ -1303,105 +1302,55 @@ class LocalAdapter { async patchMemory( id: string, - patch: { content?: string; importance?: string; kind?: string; scope?: string; tags?: string[]; status?: string; title?: string; evidence?: string[] }, - workspaceId?: string, - mind?: 'personal' | 'workspace', + patch: { content?: string; importance?: string; kind?: string; tags?: string[]; status?: 'active' | 'archived'; title?: string; evidence?: string[] }, ): Promise { - const res = await this.fetch(`/api/memory/${encodeURIComponent(id)}${this.memoryScopeQs(workspaceId, mind)}`, { method: 'PATCH', body: JSON.stringify(patch) }); + const res = await this.fetch(`/api/memory/${encodeURIComponent(id)}`, { method: 'PATCH', body: JSON.stringify(patch) }); return res.json(); } - async archiveMemory(id: string, workspaceId?: string, mind?: 'personal' | 'workspace'): Promise { - const res = await this.fetch(`/api/memory/${encodeURIComponent(id)}/archive${this.memoryScopeQs(workspaceId, mind)}`, { method: 'POST' }); + /** Reversible archive: hidden from recall until unarchived. */ + async archiveMemory(id: string): Promise { + const res = await this.fetch(`/api/memory/${encodeURIComponent(id)}/archive`, { method: 'POST' }); return res.json(); } /** Hard delete (A8) via the bare-id route — distinct from deleteMemoryFrame. */ - async deleteMemoryById(id: string, workspaceId?: string, mind?: 'personal' | 'workspace'): Promise { - await this.fetch(`/api/memory/${encodeURIComponent(id)}${this.memoryScopeQs(workspaceId, mind)}`, { method: 'DELETE' }); + async deleteMemoryById(id: string): Promise { + await this.fetch(`/api/memory/${encodeURIComponent(id)}`, { method: 'DELETE' }); } - /** PR3.5 Memory-Trust: clear the 'unreviewed' lifecycle state (status→active). */ - async confirmMemory(id: string, workspaceId?: string, mind?: 'personal' | 'workspace'): Promise { - const res = await this.fetch(`/api/memory/${encodeURIComponent(id)}/confirm${this.memoryScopeQs(workspaceId, mind)}`, { method: 'POST' }); + /** PR3.5 Memory-Trust: confirm a memory extracted in the background (status→active). */ + async confirmMemory(id: string): Promise { + const res = await this.fetch(`/api/memory/${encodeURIComponent(id)}/confirm`, { method: 'POST' }); return res.json(); } /** PR3.5 "Why did you do that?": resolve the execution trace that wrote a * memory (via the metadata.trace_id backlink). Returns { trace: null } when - * the frame has no linked trace — the caller shows an honest empty state. */ - async getMemoryTrace(id: string, workspaceId?: string, mind?: 'personal' | 'workspace'): Promise<{ trace: MemoryTrace | null }> { - const res = await this.fetch(`/api/memory/${encodeURIComponent(id)}/trace${this.memoryScopeQs(workspaceId, mind)}`); + * the memory has no linked trace — the caller shows an honest empty state. */ + async getMemoryTrace(id: string): Promise<{ trace: MemoryTrace | null }> { + const res = await this.fetch(`/api/memory/${encodeURIComponent(id)}/trace`); return res.json(); } - /** #7 "View original source": resolve the immutable verbatim raw_archive row(s) - * a memory was distilled from (via metadata.archiveUids — one frame can link - * several sources). 404 = no linked source (manual / pre-archive frames) → - * { archiveRows: [] } for a friendly empty state, mirroring getMemory's - * documented 404→null contract rather than the throwing fetch. */ - async getMemoryOriginalSource( - id: string, - workspaceId?: string, - mind?: 'personal' | 'workspace', - ): Promise<{ archiveRows: Array<{ content: string; source: string; sourceRef: string | null; injectionFlagged: boolean; injectionFlags: string }> }> { - const res = await this.fetchRaw(`/api/memory/${encodeURIComponent(id)}/source${this.memoryScopeQs(workspaceId, mind)}`); - if (res.status === 404) return { archiveRows: [] }; - if (!res.ok) throw new AdapterHttpError(res.status, res.statusText, await res.clone().json().catch(() => undefined)); - const body = await res.json(); - return { archiveRows: Array.isArray(body?.archiveRows) ? body.archiveRows : [] }; - } - - /** #7 P1 GDPR Art.17 per-subject erasure — runs the FULL sweep (raw_archive - * provenance redaction + frame delete from every retrieval store + orphaned-KG - * hard-delete +, in subject mode, verbatim raw-turn / B-frame reach). Distinct - * from the A8 frame-only deleteMemoryById AND from eraseData (whole-datadir - * account wipe). Frame mode by default; pass {source, sourceRef} to sweep an - * entire harvested source. Returns the erasure breakdown for the UI receipt. */ + /** Forget one memory ({ id }) or every memory saved from one chat session + * ({ sessionId }), in personal and workspace memory. */ async eraseMemory( - target: { frameId: string } | { source: string; sourceRef: string }, - opts: { reason?: string; workspaceId?: string; mind?: 'personal' | 'workspace' } = {}, - ): Promise<{ - erased: boolean; - mind: string; - result: { framesDeleted: number; archiveRedacted: number; chunkVectorsPurged: number; entitiesErased: number; relationsErased: number }; - }> { - const res = await this.fetch(`/api/memory/erase${this.memoryScopeQs(opts.workspaceId, opts.mind)}`, { + target: { id: string } | { sessionId: string }, + opts: { reason?: string } = {}, + ): Promise<{ erased: boolean; deleted: number }> { + const res = await this.fetch('/api/memory/erase', { method: 'POST', body: JSON.stringify({ ...target, reason: opts.reason }), }); return res.json(); } - /** #7 sticky erasure — list the (source, sourceRef) subjects on the erased-subject - * suppression list. A re-import of any of these is skipped, so an Art.17 erasure - * survives a later re-export/re-sync. The re-consent UI lists + clears them. */ - async listSuppression( - opts: { workspaceId?: string; mind?: 'personal' | 'workspace' } = {}, - ): Promise<{ mind: string; suppressed: Array<{ source: string; sourceRef: string; erasedAt: string; reason: string | null }> }> { - const res = await this.fetchRaw(`/api/memory/suppression${this.memoryScopeQs(opts.workspaceId, opts.mind)}`); - if (!res.ok) return { mind: opts.mind ?? 'personal', suppressed: [] }; - const body = await res.json(); - return { mind: body?.mind ?? 'personal', suppressed: Array.isArray(body?.suppressed) ? body.suppressed : [] }; - } - - /** #7 sticky erasure — re-consent: lift the suppression on a subject so it may be - * re-imported again. Idempotent (removed:false if it wasn't suppressed). */ - async allowReimport( - subject: { source: string; sourceRef: string }, - opts: { workspaceId?: string; mind?: 'personal' | 'workspace' } = {}, - ): Promise<{ removed: boolean; mind: string }> { - const res = await this.fetch(`/api/memory/suppression/allow${this.memoryScopeQs(opts.workspaceId, opts.mind)}`, { - method: 'POST', - body: JSON.stringify(subject), - }); - return res.json(); - } - - async mergeMemories(ids: string[], opts: { workspaceId?: string; title?: string; mind?: 'personal' | 'workspace' } = {}): Promise { + /** Join memories of one scope into one; the originals are archived. */ + async mergeMemories(ids: string[], opts: { title?: string } = {}): Promise { const res = await this.fetch('/api/memory/merge', { method: 'POST', - body: JSON.stringify({ ids, workspaceId: opts.workspaceId, title: opts.title, mind: opts.mind }), + body: JSON.stringify({ ids, title: opts.title }), }); return res.json(); } @@ -3089,28 +3038,6 @@ class LocalAdapter { } catch { return { byType: {}, total: 0 }; } } - // --- Weaver --- - // Mirrors GET /api/weaver/status (packages/server/src/local/routes/weaver.ts): - // the domain shape consumers (WeaverPanel, CockpitApp) read directly. On error - // we return a valid-but-empty object of the SAME shape rather than a fake - // success status, so callers never crash dereferencing missing fields. - async getWeaverStatus(): Promise<{ - personalMind: { lastConsolidation: string | null; lastDecay: string | null; timerActive: boolean }; - workspaces: Array<{ id: string; lastConsolidation: string | null; timerActive: boolean }>; - checkedAt: string; - }> { - try { - const res = await this.fetch('/api/weaver/status'); - return res.json(); - } catch { - return { - personalMind: { lastConsolidation: null, lastDecay: null, timerActive: false }, - workspaces: [], - checkedAt: new Date().toISOString(), - }; - } - } - // --- Audit --- async getAuditInstalls(): Promise { const res = await this.fetch('/api/audit/installs'); @@ -3620,17 +3547,7 @@ class LocalAdapter { } } - // --- Import --- - async importPreview(data: unknown, source: string): Promise<{ knowledgeExtracted: unknown[] }> { - const res = await this.fetch('/api/import/preview', { method: 'POST', body: JSON.stringify({ data, source }) }); - return res.json(); - } - - async importCommit(data: unknown, source: string): Promise { - await this.fetch('/api/import/commit', { method: 'POST', body: JSON.stringify({ data, source }) }); - } - - // --- Harvest --- + // --- Harvest (hidden in v1, ADR-0002; the sidecar routes are removed) --- async harvestPreview(data: unknown, source: string): Promise { const res = await this.fetch('/api/harvest/preview', { method: 'POST', body: JSON.stringify({ data, source }) }); return res.json(); @@ -3756,11 +3673,6 @@ class LocalAdapter { return res.json(); } - async getWikiWatermark(): Promise { - const res = await this.fetch('/api/wiki/watermark'); - return res.json(); - } - /** * M-12: export all compiled wiki pages to an Obsidian-shaped directory. * `outDir` must be an absolute path. Writes `_index.md` at the root and diff --git a/apps/web/src/lib/context-rail-fetch.ts b/apps/web/src/lib/context-rail-fetch.ts index 1e548ca..15e8423 100644 --- a/apps/web/src/lib/context-rail-fetch.ts +++ b/apps/web/src/lib/context-rail-fetch.ts @@ -33,7 +33,7 @@ export interface ContextRailItem { } export interface ContextRailAdapter { - searchMemory: (query: string, scope?: string) => Promise; + searchMemory: (query: string, scope?: 'all' | 'personal' | 'workspace' | 'global', workspaceId?: string) => Promise; getKnowledgeGraph: ( workspaceId: string, scope?: 'current' | 'personal' | 'all', @@ -188,7 +188,7 @@ export async function fetchContextRailItems( // Memory pass — every target type benefits from this. try { - const frames = await adapter.searchMemory(buildMemoryQuery(target), 'all'); + const frames = await adapter.searchMemory(buildMemoryQuery(target), 'all', target.workspaceId); for (const f of frames.slice(0, memoryLimit)) push(frameToItem(f)); } catch { // Leave whatever we already gathered from the graph pass. diff --git a/apps/web/src/lib/harvest-kind-map.ts b/apps/web/src/lib/harvest-kind-map.ts index 0a12a2d..82f2830 100644 --- a/apps/web/src/lib/harvest-kind-map.ts +++ b/apps/web/src/lib/harvest-kind-map.ts @@ -1,7 +1,7 @@ // Pure display mapping for the canonical PRD §15.2 `MemoryKind` vocabulary (B6). // // `MemoryKind` is the single source of truth for memory typing (defined once in -// `@waggle/shared`). This module maps each kind to (a) a human label for Memory +// `@waggle/shared`, mirroring the memory contract's kinds). This module maps each kind to (a) a human label for Memory // Center filter chips / cards (S04) and (b) an onboarding Memory Review grouping // bucket (S16). The server-side `ImportItemType → MemoryKind` normalization lives // in the sidecar harvest layer (Phase 2B), NOT here — the build order forbids @@ -25,13 +25,12 @@ interface MemoryKindMeta { export const MEMORY_KIND_META: Record = { fact: { label: 'Fact', category: 'Memories' }, - decision: { label: 'Decision', category: 'Decisions' }, - task: { label: 'Task', category: 'Tasks' }, + event: { label: 'Event', category: 'Memories' }, preference: { label: 'Preference', category: 'Memories' }, - strategy: { label: 'Strategy', category: 'Projects' }, - learning: { label: 'Learning', category: 'Memories' }, - goal: { label: 'Goal', category: 'Projects' }, - entity: { label: 'Entity', category: 'Memories' }, + profile: { label: 'About you', category: 'Memories' }, + decision: { label: 'Decision', category: 'Decisions' }, + summary: { label: 'Summary', category: 'Projects' }, + note: { label: 'Note', category: 'Tasks' }, }; export function memoryKindLabel(kind: MemoryKind): string { diff --git a/apps/web/src/lib/memory-features.ts b/apps/web/src/lib/memory-features.ts index 9647ba3..d125afc 100644 --- a/apps/web/src/lib/memory-features.ts +++ b/apps/web/src/lib/memory-features.ts @@ -1,11 +1,16 @@ /** * Memory features the UI may show (ADR-0002). * - * v1 memory is facts, search and the user profile. The features below are - * hidden, not deleted: their screens stay in the code and every surface that - * offers one checks this map first. A later work package fills the map from - * the server's memory capability map, so read it only through this module. + * v1 memory is facts, search and the user profile. The knowledge graph follows + * the server's memory capability map (`GET /api/memory/capabilities`), which + * reports it unavailable in v1. History import, wiki, coding-agent hooks, Room + * and the memory MCP server are hidden in v1 by decision, whatever the store + * supports. Their screens stay in the code and every surface that offers one + * checks this module first. */ +import { useEffect, useSyncExternalStore } from 'react'; +import { adapter } from '@/lib/adapter'; +import type { MemoryCapabilitiesResponse } from '@/lib/types'; export interface MemoryFeatures { /** Knowledge graph (entities and relations). Deferred to a later release. */ @@ -24,8 +29,8 @@ export interface MemoryFeatures { export type MemoryFeature = keyof MemoryFeatures; -const MEMORY_FEATURES: Readonly = { - knowledgeGraph: false, +/** Hidden in v1 (ADR-0002) regardless of the memory store. */ +const HIDDEN_IN_V1: Readonly, false>> = { importHistory: false, wiki: false, agentHooks: false, @@ -33,8 +38,14 @@ const MEMORY_FEATURES: Readonly = { memoryMcp: false, }; +let current: MemoryCapabilitiesResponse | null = null; +let pending: Promise | null = null; +const listeners = new Set<() => void>(); + +/** False until the server has reported the feature as available. */ export function hasMemoryFeature(feature: MemoryFeature): boolean { - return MEMORY_FEATURES[feature]; + if (feature === 'knowledgeGraph') return current?.capabilities.knowledgeGraph === true; + return HIDDEN_IN_V1[feature]; } /** Memory Center views (`?tab=`) that belong to a hidden feature. */ @@ -49,3 +60,40 @@ export function isMemoryViewAvailable(view: string): boolean { const feature = MEMORY_VIEW_FEATURE[view]; return feature === undefined || hasMemoryFeature(feature); } + +/** Store a capability report (after a load, or the response of a settings change). */ +export function setMemoryCapabilities(next: MemoryCapabilitiesResponse | null): void { + current = next; + for (const listener of listeners) listener(); +} + +/** Fetch the capability report once; a failed fetch is retried on the next call. */ +export function loadMemoryCapabilities(): Promise { + pending ??= Promise.resolve() + .then(() => adapter.getMemoryCapabilities()) + .then((report) => { + setMemoryCapabilities(report); + return report; + }) + .catch(() => { + pending = null; + return null; + }); + return pending; +} + +function subscribe(listener: () => void): () => void { + listeners.add(listener); + return () => listeners.delete(listener); +} + +const snapshot = (): MemoryCapabilitiesResponse | null => current; + +/** The capability report; null until loaded. Re-renders when it changes. */ +export function useMemoryCapabilities(): MemoryCapabilitiesResponse | null { + const report = useSyncExternalStore(subscribe, snapshot, snapshot); + useEffect(() => { + void loadMemoryCapabilities(); + }, []); + return report; +} diff --git a/apps/web/src/lib/tauri-bindings.ts b/apps/web/src/lib/tauri-bindings.ts index 47463aa..11a5cf1 100644 --- a/apps/web/src/lib/tauri-bindings.ts +++ b/apps/web/src/lib/tauri-bindings.ts @@ -43,10 +43,10 @@ export interface RecallMemoryArgs { /** * Sidecar /api/memory/search returns `{ results, count }` where each result is a - * normalized frame from `normalizeFrame()` in routes/memory.ts. Frames are + * memory from `toFrameResponse()` in routes/memory.ts. Results are * intentionally typed as `Record` here — the canonical - * MemoryFrame shape is owned by adapter.ts which performs camelCase + frameType - * code mapping. Keep bindings raw to prevent two normalization paths drifting. + * MemoryFrame shape is owned by adapter.ts, which maps kind and importance. + * Keep bindings raw to prevent two normalization paths drifting. */ export interface RecallMemoryResponse { results: Array>; diff --git a/apps/web/src/lib/types.ts b/apps/web/src/lib/types.ts index bbeb6db..e9e0c69 100644 --- a/apps/web/src/lib/types.ts +++ b/apps/web/src/lib/types.ts @@ -491,7 +491,8 @@ export interface ApprovalRequest { export interface MemoryFrame { id: string; - type: 'fact' | 'event' | 'insight' | 'decision' | 'task' | 'entity'; + /** The memory's kind in the memory contract. */ + type: MemoryKind; title: string; content: string; importance: number; @@ -500,13 +501,18 @@ export interface MemoryFrame { metadata?: Record; } +/** `GET /api/memory/capabilities` and `PUT /api/memory/settings`. */ +export interface MemoryCapabilitiesResponse { + /** What the memory store supports (`MemoryCapabilities` of the memory contract). */ + capabilities: { extraction: boolean; semanticSearch: boolean; history: boolean; knowledgeGraph: boolean }; + /** `extraction`: facts are extracted from chats in the background. */ + settings: { extraction: boolean }; +} + /** - * Memory Center FE view-model (S04) — the shared `Memory` entity (PRD §15.4, - * carrying kind/confidence/scope/source/evidence/status) plus FE-derived display - * fields. The legacy `MemoryFrame` above is kept for back-compat with existing - * `/api/memory/frames` consumers; Memory Center components migrate onto `Memory` - * in Phase 2B. `MemoryKind` (PRD §15.2) is the canonical type vocabulary (B6) — - * do NOT widen `MemoryFrame.type`; map it via `lib/harvest-kind-map.ts`. + * Memory Center FE view-model (S04) — the shared `Memory` entity (PRD §15.4) + * plus FE-derived display fields. The `MemoryFrame` above serves the + * `/api/memory/search|frames` consumers (Timeline, recall toasts, briefing). */ export interface Memory extends SharedMemory { /** FE-derived recall relevance for ranked lists (0-1); not persisted. */ diff --git a/apps/web/src/routes/MemoryRoute.tsx b/apps/web/src/routes/MemoryRoute.tsx index 856e8ea..2c1be3f 100644 --- a/apps/web/src/routes/MemoryRoute.tsx +++ b/apps/web/src/routes/MemoryRoute.tsx @@ -27,7 +27,7 @@ import { useShell } from '@/providers/ShellContext'; import { useMemory } from '@/hooks/useMemory'; import { useKnowledgeGraph } from '@/hooks/useKnowledgeGraph'; import { stashDeepLink } from '@/lib/app-deeplink'; -import { hasMemoryFeature, isMemoryViewAvailable } from '@/lib/memory-features'; +import { hasMemoryFeature, isMemoryViewAvailable, useMemoryCapabilities } from '@/lib/memory-features'; const MemoryRoute = () => { const { mindScope } = useParams(); @@ -35,6 +35,8 @@ const MemoryRoute = () => { const navigate = useNavigate(); const mind: MindScope = mindScope === 'workspace' ? 'workspace' : 'personal'; + // Re-render once the server's capability map arrives (graph visibility). + useMemoryCapabilities(); const tabParam = searchParams.get('tab'); // PR3.5: 'trust' (screen 19) is the new default landing; ?tab= still selects // any view (incl. the legacy 'memories' list and the 6 secondary views), diff --git a/apps/web/src/test/lane-hm-hero-morph.test.tsx b/apps/web/src/test/lane-hm-hero-morph.test.tsx index dfa600d..16d72ab 100644 --- a/apps/web/src/test/lane-hm-hero-morph.test.tsx +++ b/apps/web/src/test/lane-hm-hero-morph.test.tsx @@ -94,7 +94,6 @@ vi.mock('@/components/os/apps/memory/MemoryCenterTab', () => ({ default: () => < vi.mock('@/components/os/apps/memory/TimelineTab', () => ({ default: () =>
})); vi.mock('@/components/os/apps/memory/KnowledgeGraphViewer', () => ({ default: () =>
})); vi.mock('@/components/os/apps/memory/HarvestTab', () => ({ default: () =>
})); -vi.mock('@/components/os/apps/memory/WeaverPanel', () => ({ default: () =>
})); vi.mock('@/components/os/apps/memory/WikiTab', () => ({ default: () =>
})); vi.mock('@/components/os/apps/memory/ImportReminderBanner', () => ({ default: () => null })); diff --git a/apps/web/src/test/memory-center-trust.test.tsx b/apps/web/src/test/memory-center-trust.test.tsx index eec3de0..45887f8 100644 --- a/apps/web/src/test/memory-center-trust.test.tsx +++ b/apps/web/src/test/memory-center-trust.test.tsx @@ -10,10 +10,7 @@ const mocks = vi.hoisted(() => ({ archiveMemory: vi.fn(), deleteMemoryById: vi.fn(), mergeMemories: vi.fn(), - getMemoryOriginalSource: vi.fn(), eraseMemory: vi.fn(), - listSuppression: vi.fn(), - allowReimport: vi.fn(), }, })); @@ -36,7 +33,7 @@ const memory: Memory = { confidence: 91, tags: ['research'], evidence: [], - hasOriginalSource: false, + sessionId: null, createdAt: '2026-07-08T08:00:00.000Z', updatedAt: '2026-07-08T09:00:00.000Z', }; @@ -53,21 +50,7 @@ beforeEach(() => { mocks.adapter.archiveMemory.mockResolvedValue({ ...memory, status: 'archived' }); mocks.adapter.deleteMemoryById.mockResolvedValue(undefined); mocks.adapter.mergeMemories.mockResolvedValue(memory); - mocks.adapter.getMemoryOriginalSource.mockResolvedValue({ archiveRows: [] }); - mocks.adapter.eraseMemory.mockResolvedValue({ - erased: true, - result: { framesDeleted: 1, archiveRedacted: 1, entitiesErased: 1 }, - }); - mocks.adapter.listSuppression.mockResolvedValue({ - mind: 'personal', - suppressed: [{ - source: 'chatgpt', - sourceRef: 'research-export.json', - erasedAt: '2026-07-08T09:30:00.000Z', - reason: 'GDPR Art.17 erasure', - }], - }); - mocks.adapter.allowReimport.mockResolvedValue({ removed: true }); + mocks.adapter.eraseMemory.mockResolvedValue({ erased: true, deleted: 3 }); }); afterEach(() => { @@ -86,11 +69,8 @@ describe('Memory Center trust flows', () => { expect(search.parentElement?.className).toContain('focus-within:ring-2'); expect(search.parentElement?.className).toContain('focus-within:ring-[var(--focus-ring)]'); - const confidence = screen.getByRole('combobox', { name: /filter by confidence/i }); - expect(confidence).toHaveAttribute('name', 'memoryConfidenceFilter'); - expect(confidence).toHaveAttribute('autocomplete', 'off'); - expect(confidence.className).toContain('focus-visible:ring-2'); - expect(confidence.className).toContain('focus-visible:ring-[var(--focus-ring)]'); + // v1 stores no confidence, so there is no confidence filter. + expect(screen.queryByRole('combobox', { name: /filter by confidence/i })).toBeNull(); for (const name of [/needs review/i, /active/i, /all kinds/i, /fact/i]) { expect(screen.getByRole('button', { name }).className).toContain('focus-visible:ring-2'); @@ -128,55 +108,41 @@ describe('Memory Center trust flows', () => { fireEvent.click(screen.getByTestId('approval-modal-approve')); - await waitFor(() => expect(mocks.adapter.deleteMemoryById).toHaveBeenCalledWith('memory-research-note', undefined, 'personal')); + await waitFor(() => expect(mocks.adapter.deleteMemoryById).toHaveBeenCalledWith('memory-research-note')); }); - it('asks in-app before erasing a memory and derived data', async () => { + it('offers Erase only for a memory saved from a chat', async () => { + renderMemoryCenter(); + fireEvent.click(await screen.findByLabelText('Research Note')); + await screen.findByRole('button', { name: /^delete$/i }); + expect(screen.queryByRole('button', { name: /erase chat memories/i })).toBeNull(); + }); + + it('asks in-app before erasing every memory of the chat a memory came from', async () => { + mocks.adapter.listMemories.mockResolvedValue([{ ...memory, sessionId: 'chat-42' }]); const confirmSpy = vi.spyOn(window, 'confirm').mockReturnValue(true); renderMemoryCenter(); fireEvent.click(await screen.findByLabelText('Research Note')); - fireEvent.click(await screen.findByRole('button', { name: /^erase$/i })); + fireEvent.click(await screen.findByRole('button', { name: /erase chat memories/i })); expect(confirmSpy).not.toHaveBeenCalled(); expect(mocks.adapter.eraseMemory).not.toHaveBeenCalled(); const modal = await screen.findByTestId('approval-modal'); - expect(modal).toHaveTextContent(/erase memory and derived data/i); - expect(modal).toHaveTextContent(/research note/i); + expect(modal).toHaveTextContent(/erase everything remembered from this chat/i); + expect(modal).toHaveTextContent(/transcript itself is kept/i); expect(modal).toHaveTextContent(/cannot be undone/i); - expect(modal).toHaveTextContent(/original source/i); fireEvent.click(screen.getByTestId('approval-modal-approve')); - await waitFor(() => expect(mocks.adapter.eraseMemory).toHaveBeenCalledWith( - { frameId: 'memory-research-note' }, - { workspaceId: undefined, mind: 'personal' }, - )); - await screen.findByText(/erased "research note"/i); + await waitFor(() => expect(mocks.adapter.eraseMemory).toHaveBeenCalledWith({ sessionId: 'chat-42' })); + await screen.findByText(/erased 3 memories from that chat/i); }); - it('asks in-app before allowing an erased source to be re-imported', async () => { - const confirmSpy = vi.spyOn(window, 'confirm').mockReturnValue(true); + it('no longer shows the erased-sources panel of the old harvest import', async () => { renderMemoryCenter(); - - fireEvent.click(await screen.findByRole('button', { name: /erased sources/i })); - await screen.findByText('research-export.json'); - fireEvent.click(await screen.findByRole('button', { name: /allow re-import/i })); - - expect(confirmSpy).not.toHaveBeenCalled(); - expect(mocks.adapter.allowReimport).not.toHaveBeenCalled(); - - const modal = await screen.findByTestId('approval-modal'); - expect(modal).toHaveTextContent(/allow source to be re-imported/i); - expect(modal).toHaveTextContent(/research-export\.json/i); - expect(modal).toHaveTextContent(/re-consented/i); - - fireEvent.click(screen.getByTestId('approval-modal-approve')); - - await waitFor(() => expect(mocks.adapter.allowReimport).toHaveBeenCalledWith( - { source: 'chatgpt', sourceRef: 'research-export.json' }, - { workspaceId: undefined, mind: 'personal' }, - )); + await screen.findByLabelText('Research Note'); + expect(screen.queryByRole('button', { name: /erased sources/i })).toBeNull(); }); }); diff --git a/apps/web/src/test/memory-features.test.tsx b/apps/web/src/test/memory-features.test.tsx index b81492e..b74639b 100644 --- a/apps/web/src/test/memory-features.test.tsx +++ b/apps/web/src/test/memory-features.test.tsx @@ -1,9 +1,18 @@ /** - * ADR-0002: the v1 memory feature map and the onboarding import step it hides. + * ADR-0002: the v1 memory feature map, its capability source, and the + * onboarding import step it hides. */ import { describe, it, expect, vi, afterEach } from 'vitest'; -import { render, screen, cleanup, waitFor } from '@testing-library/react'; -import { hasMemoryFeature, isMemoryViewAvailable, type MemoryFeature } from '@/lib/memory-features'; +import { render, screen, cleanup, waitFor, renderHook } from '@testing-library/react'; +import { + hasMemoryFeature, + isMemoryViewAvailable, + loadMemoryCapabilities, + setMemoryCapabilities, + useMemoryCapabilities, + type MemoryFeature, +} from '@/lib/memory-features'; +import type { MemoryCapabilitiesResponse } from '@/lib/types'; const mocks = vi.hoisted(() => ({ adapter: { @@ -11,9 +20,15 @@ const mocks = vi.hoisted(() => ({ getProfile: vi.fn(), trackTelemetry: vi.fn(), scanClaudeCode: vi.fn(), + getMemoryCapabilities: vi.fn(), }, })); +const report = (knowledgeGraph: boolean): MemoryCapabilitiesResponse => ({ + capabilities: { extraction: true, semanticSearch: true, history: true, knowledgeGraph }, + settings: { extraction: true }, +}); + vi.mock('@/lib/adapter', () => ({ adapter: mocks.adapter, default: vi.fn() })); vi.mock('@/hooks/useOfflineStatus', () => ({ useOfflineStatus: () => false })); vi.mock('@/lib/posthog', () => ({ captureOnboardingComplete: vi.fn() })); @@ -21,6 +36,7 @@ vi.mock('@/lib/posthog', () => ({ captureOnboardingComplete: vi.fn() })); afterEach(() => { cleanup(); vi.clearAllMocks(); + setMemoryCapabilities(null); }); describe('memory feature map (v1 defaults)', () => { @@ -32,7 +48,7 @@ describe('memory feature map (v1 defaults)', () => { ); it('keeps the v1 Memory Center views and hides Graph, Imports and Wiki', () => { - for (const view of ['trust', 'memories', 'timeline', 'weaver']) { + for (const view of ['trust', 'memories', 'timeline']) { expect(isMemoryViewAvailable(view), view).toBe(true); } for (const view of ['graph', 'harvest', 'wiki']) { @@ -41,6 +57,32 @@ describe('memory feature map (v1 defaults)', () => { }); }); +describe('memory feature map from the server capabilities', () => { + it('shows the graph only when the memory store reports it', () => { + setMemoryCapabilities(report(false)); + expect(hasMemoryFeature('knowledgeGraph')).toBe(false); + setMemoryCapabilities(report(true)); + expect(hasMemoryFeature('knowledgeGraph')).toBe(true); + expect(isMemoryViewAvailable('graph')).toBe(true); + }); + + it('keeps import, wiki, hooks, Room and the memory MCP hidden whatever the store reports', () => { + setMemoryCapabilities(report(true)); + for (const feature of ['importHistory', 'wiki', 'agentHooks', 'room', 'memoryMcp'] as const) { + expect(hasMemoryFeature(feature), feature).toBe(false); + } + }); + + it('useMemoryCapabilities loads GET /api/memory/capabilities once and re-renders', async () => { + mocks.adapter.getMemoryCapabilities.mockResolvedValue(report(false)); + const { result } = renderHook(() => useMemoryCapabilities()); + expect(result.current).toBeNull(); + await waitFor(() => expect(result.current).toEqual(report(false))); + await loadMemoryCapabilities(); + expect(mocks.adapter.getMemoryCapabilities).toHaveBeenCalledTimes(1); + }); +}); + describe('OnboardingWizard without history import', () => { it('resumes a persisted import step on the template step and never scans Claude Code', async () => { mocks.adapter.connect.mockResolvedValue(undefined); diff --git a/apps/web/src/test/p3-memory-center-app.test.tsx b/apps/web/src/test/p3-memory-center-app.test.tsx index 68c7041..ed74adf 100644 --- a/apps/web/src/test/p3-memory-center-app.test.tsx +++ b/apps/web/src/test/p3-memory-center-app.test.tsx @@ -82,7 +82,6 @@ vi.mock('@/components/os/apps/memory/MemoryCenterTab', () => ({ vi.mock('@/components/os/apps/memory/TimelineTab', () => ({ default: () =>
})); vi.mock('@/components/os/apps/memory/KnowledgeGraphViewer', () => ({ default: () =>
})); vi.mock('@/components/os/apps/memory/HarvestTab', () => ({ default: () =>
})); -vi.mock('@/components/os/apps/memory/WeaverPanel', () => ({ default: () =>
})); vi.mock('@/components/os/apps/memory/WikiTab', () => ({ default: () =>
})); vi.mock('@/components/os/apps/memory/ImportReminderBanner', () => ({ default: () => null })); @@ -160,7 +159,6 @@ describe('MemoryRoute + MemoryCenterApp URL wiring (P3/D2)', () => { it.each([ ['timeline', 'stub-timeline'], ['harvest', 'stub-harvest'], - ['weaver', 'stub-weaver'], ['wiki', 'stub-wiki'], ])('?tab=%s mounts its legacy view (capability preserved)', async (tabId, testId) => { await renderRoute(`/memory?tab=${tabId}`); @@ -228,20 +226,17 @@ describe('v1 memory features (ADR-0002): Graph, Imports and Wiki are hidden', () expect(screen.queryByTestId(`stub-${tabId}`)).toBeNull(); }); - it('offers no Graph tab and keeps only Maintenance under Advanced', async () => { + it('offers no Graph tab and no Advanced menu', async () => { features.enabled = false; await renderRoute('/memory'); expect(screen.queryByRole('tab', { name: /graph/i })).toBeNull(); - fireEvent.click(screen.getByTestId('memory-tab-advanced')); - const menu = screen.getByTestId('memory-tab-advanced-menu'); - expect(menu).toHaveTextContent('Maintenance'); - expect(menu).not.toHaveTextContent(/imports|wiki/i); + expect(screen.queryByTestId('memory-tab-advanced')).toBeNull(); }); - it('?tab=weaver still mounts Maintenance', async () => { + it('the removed Maintenance view (?tab=weaver) falls back to the Trust default', async () => { features.enabled = false; await renderRoute('/memory?tab=weaver'); - expect(screen.getByTestId('stub-weaver')).toBeTruthy(); + expect(screen.getByTestId('stub-trust')).toBeTruthy(); }); }); diff --git a/apps/web/src/test/p3-two-mind-memory.test.tsx b/apps/web/src/test/p3-two-mind-memory.test.tsx index f78c9fd..89d7e31 100644 --- a/apps/web/src/test/p3-two-mind-memory.test.tsx +++ b/apps/web/src/test/p3-two-mind-memory.test.tsx @@ -92,7 +92,7 @@ describe('MemoryCenterTab two-mind parameterization (P3/D2)', () => { expect(mocks.adapter.listMemories).not.toHaveBeenCalled(); }); - it('merge on the workspace mind carries workspaceId', async () => { + it('merge on the workspace mind sends only the ids (ids are unique across scopes)', async () => { mocks.adapter.listMemories.mockResolvedValue([mem({ id: '1' }), mem({ id: '2', title: 'Second' })]); mocks.adapter.mergeMemories.mockResolvedValue(mem({ id: '3' })); await renderTab({ mind: 'workspace', workspaceId: 'w1', consumeDeepLinks: false }); @@ -102,11 +102,11 @@ describe('MemoryCenterTab two-mind parameterization (P3/D2)', () => { fireEvent.click(screen.getByText(/Merge 2 memories/)); await waitFor(() => { - expect(mocks.adapter.mergeMemories).toHaveBeenCalledWith(['1', '2'], { workspaceId: 'w1', mind: 'workspace' }); + expect(mocks.adapter.mergeMemories).toHaveBeenCalledWith(['1', '2']); }); }); - it('archive from the detail drawer on the workspace mind carries workspaceId', async () => { + it('archive from the detail drawer on the workspace mind sends only the id', async () => { mocks.adapter.listMemories.mockResolvedValue([mem({ id: '9' })]); mocks.adapter.archiveMemory.mockResolvedValue(mem({ id: '9', status: 'archived' })); await renderTab({ mind: 'workspace', workspaceId: 'w1', consumeDeepLinks: false }); @@ -117,13 +117,11 @@ describe('MemoryCenterTab two-mind parameterization (P3/D2)', () => { fireEvent.click(archiveBtn); await waitFor(() => { - // mind rides along so server-side store resolution is STRICT (no - // cross-mind fall-through on colliding ids — P3 review HIGH). - expect(mocks.adapter.archiveMemory).toHaveBeenCalledWith('9', 'w1', 'workspace'); + expect(mocks.adapter.archiveMemory).toHaveBeenCalledWith('9'); }); }); - it('personal-mind mutations keep the workspace param off (no cross-mind shadowing)', async () => { + it('personal-mind archive sends only the id', async () => { mocks.adapter.listMemories.mockResolvedValue([mem({ id: '4', workspaceId: undefined, scope: 'personal' })]); mocks.adapter.archiveMemory.mockResolvedValue(mem({ id: '4', status: 'archived' })); await renderTab(); @@ -133,7 +131,7 @@ describe('MemoryCenterTab two-mind parameterization (P3/D2)', () => { fireEvent.click(await screen.findByText('Archive')); await waitFor(() => { - expect(mocks.adapter.archiveMemory).toHaveBeenCalledWith('4', undefined, 'personal'); + expect(mocks.adapter.archiveMemory).toHaveBeenCalledWith('4'); }); }); diff --git a/apps/web/src/test/pr35-memory-trust-manage.test.tsx b/apps/web/src/test/pr35-memory-trust-manage.test.tsx index dd19abf..4d7b88c 100644 --- a/apps/web/src/test/pr35-memory-trust-manage.test.tsx +++ b/apps/web/src/test/pr35-memory-trust-manage.test.tsx @@ -110,7 +110,7 @@ describe('MemoryTrustManage stats + filters + actions (PR3.5 Phase B+C)', () => render(); await waitFor(() => expect(screen.getByText('⬡ M-5')).toBeTruthy()); fireEvent.click(screen.getByTitle('Forget this')); - await waitFor(() => expect(mocks.adapter.deleteMemoryById).toHaveBeenCalledWith('5', undefined, 'personal')); + await waitFor(() => expect(mocks.adapter.deleteMemoryById).toHaveBeenCalledWith('5')); expect(onToast).toHaveBeenCalledWith(expect.stringContaining('Forgotten M-5')); }); @@ -137,7 +137,7 @@ describe('MemoryTrustManage stats + filters + actions (PR3.5 Phase B+C)', () => render(); await waitFor(() => expect(screen.getByText('⬡ M-8')).toBeTruthy()); fireEvent.click(screen.getByTitle('Confirm this memory')); - await waitFor(() => expect(mocks.adapter.confirmMemory).toHaveBeenCalledWith('8', undefined, 'personal')); + await waitFor(() => expect(mocks.adapter.confirmMemory).toHaveBeenCalledWith('8')); expect(onToast).toHaveBeenCalledWith(expect.stringContaining('Confirmed M-8')); }); @@ -193,11 +193,11 @@ describe('MemoryTrustManage stats + filters + actions (PR3.5 Phase B+C)', () => } }); - it('workspace mind passes the workspace param to mutations', async () => { + it('workspace mind mutations send only the id (ids are unique across scopes)', async () => { mocks.adapter.listMemories.mockResolvedValue([mem({ id: '9', createdAt: iso(1) })]); render( {}} />); await waitFor(() => expect(screen.getByText('⬡ M-9')).toBeTruthy()); fireEvent.click(screen.getByTitle('Forget this')); - await waitFor(() => expect(mocks.adapter.deleteMemoryById).toHaveBeenCalledWith('9', 'w1', 'workspace')); + await waitFor(() => expect(mocks.adapter.deleteMemoryById).toHaveBeenCalledWith('9')); }); }); diff --git a/apps/web/src/test/pr35-memory-trust-why.test.tsx b/apps/web/src/test/pr35-memory-trust-why.test.tsx index e107f33..813e753 100644 --- a/apps/web/src/test/pr35-memory-trust-why.test.tsx +++ b/apps/web/src/test/pr35-memory-trust-why.test.tsx @@ -33,20 +33,20 @@ afterEach(() => { cleanup(); vi.clearAllMocks(); }); describe('MemoryTrustWhy (PR3.5 Phase D)', () => { it('with no memory selected, prompts the user to open one (no fetch)', () => { - render( {}} onCorrect={() => {}} onForget={() => {}} />); + render( {}} onCorrect={() => {}} onForget={() => {}} />); expect(screen.getByText(/Open a memory.+trace to see why/i)).toBeTruthy(); expect(mocks.adapter.getMemoryTrace).not.toHaveBeenCalled(); }); it('renders an honest "no trace linked" state when the frame has no backlink', async () => { mocks.adapter.getMemoryTrace.mockResolvedValue({ trace: null }); - render( {}} onCorrect={() => {}} onForget={() => {}} />); + render( {}} onCorrect={() => {}} onForget={() => {}} />); await waitFor(() => expect(screen.getByText(/No trace is linked to M-204/)).toBeTruthy()); }); it('renders the real trace chain: goal → tool calls → acted + footer', async () => { mocks.adapter.getMemoryTrace.mockResolvedValue({ trace: TRACE }); - render( {}} onCorrect={() => {}} onForget={() => {}} />); + render( {}} onCorrect={() => {}} onForget={() => {}} />); await waitFor(() => expect(screen.getByText('Goal received')).toBeTruthy()); expect(screen.getByText(/tighten the board narrative/)).toBeTruthy(); expect(screen.getByText('Recalled memories')).toBeTruthy(); // auto_recall humanized @@ -59,7 +59,7 @@ describe('MemoryTrustWhy (PR3.5 Phase D)', () => { it('footer actions fire the right callbacks', async () => { mocks.adapter.getMemoryTrace.mockResolvedValue({ trace: TRACE }); const onToast = vi.fn(); const onCorrect = vi.fn(); const onForget = vi.fn(); - render(); + render(); await waitFor(() => expect(screen.getByText('Looks right')).toBeTruthy()); fireEvent.click(screen.getByText('Looks right')); diff --git a/apps/web/src/test/settings-trust.test.tsx b/apps/web/src/test/settings-trust.test.tsx index ca4478b..e083502 100644 --- a/apps/web/src/test/settings-trust.test.tsx +++ b/apps/web/src/test/settings-trust.test.tsx @@ -15,12 +15,20 @@ const mocks = vi.hoisted(() => ({ probeProvider: vi.fn(), toggleTelemetry: vi.fn(), clearTelemetry: vi.fn(), + getMemoryCapabilities: vi.fn(), + setMemoryExtraction: vi.fn(), }, })); vi.mock('@/lib/adapter', () => ({ adapter: mocks.adapter, default: vi.fn() })); import SettingsApp from '@/components/os/apps/SettingsApp'; +import { setMemoryCapabilities } from '@/lib/memory-features'; + +const memoryReport = (extraction: boolean) => ({ + capabilities: { extraction: true, semanticSearch: true, history: true, knowledgeGraph: false }, + settings: { extraction }, +}); function renderSettings(initialEntry = '/settings') { return render( @@ -56,6 +64,9 @@ beforeEach(() => { mocks.adapter.probeProvider.mockResolvedValue({ configured: false, valid: false, verified: false }); mocks.adapter.toggleTelemetry.mockResolvedValue({ enabled: false }); mocks.adapter.clearTelemetry.mockResolvedValue({ ok: true }); + mocks.adapter.getMemoryCapabilities.mockResolvedValue(memoryReport(true)); + mocks.adapter.setMemoryExtraction.mockImplementation(async (enabled: boolean) => memoryReport(enabled)); + setMemoryCapabilities(memoryReport(true)); }); afterEach(() => { @@ -64,6 +75,26 @@ afterEach(() => { }); describe('Settings trust flows', () => { + it('turns background fact extraction off and on from General', async () => { + renderSettings(); + fireEvent.click(await screen.findByRole('tab', { name: /^general$/i })); + const section = await screen.findByTestId('settings-memory'); + expect(section).toHaveTextContent(/learn facts about me from chats/i); + expect(section.textContent).not.toMatch(/\u2014/); + + const toggle = within(section).getByRole('button', { name: /stop learning facts from chats/i }); + expect(toggle).toHaveAttribute('aria-pressed', 'true'); + fireEvent.click(toggle); + + await waitFor(() => expect(mocks.adapter.setMemoryExtraction).toHaveBeenCalledWith(false)); + const off = await within(section).findByRole('button', { name: /learn facts about me from chats/i }); + expect(off).toHaveAttribute('aria-pressed', 'false'); + expect(section).toHaveTextContent(/only what you or the agent save on purpose/i); + + fireEvent.click(off); + await waitFor(() => expect(mocks.adapter.setMemoryExtraction).toHaveBeenCalledWith(true)); + }); + it('labels high-traffic model and privacy controls for assistive tech', async () => { renderSettings(); diff --git a/docs/oss/upstream-fixes.md b/docs/oss/upstream-fixes.md index 4a97117..a67a75d 100644 --- a/docs/oss/upstream-fixes.md +++ b/docs/oss/upstream-fixes.md @@ -63,6 +63,9 @@ Baseline: commit `b20b138` of `git.os-dev.tech/oleg.m/waggle-os`. | UF-032 | Team capability policies are always read from the team "default" | Open | Team mode, governance | | UF-033 | Command palette memory search uses whichever workspace the Memory app opened last | Fixed | Sidecar, command palette | | UF-034 | Artifact Center "related sessions" never finds a chat session | Fixed | Sidecar, Artifact Center | +| UF-035 | Timeline search and the chat recall toast send the workspace id as the search scope | Fixed | Web UI, memory, privacy | +| UF-036 | The web client reads "important" and "temporary" memories as normal importance | Fixed | Web UI, memory | +| UF-037 | Restore overwrites database files the running sidecar holds open | Open | Sidecar, backup | ## Entries @@ -344,3 +347,30 @@ Entries UF-010 to UF-019 come from the UI audit `anti-slop/audit-001-2026-10-14. - Cause: the route matches the query against the memory engine's session rows (`SessionStore.getActive()`, their `summary` and `gop_id`). Those rows are named write buckets such as 'harvest', 'agent-runs' or 'loop', not chat sessions; chat transcripts are JSONL files under `/workspaces//sessions/`. - What we did: the route runs `searchSessions()` over each workspace's chat session files, the same search as `GET /api/workspaces/:id/sessions/search`, and returns the session id, title, workspace and the first matching snippet. - Recommendation: do the same in the main project. + +### UF-035. Timeline search and the chat recall toast send the workspace id as the search scope +- Status: Fixed +- Found: 2026-10-24 +- Where: at commit `b20b138`, `apps/web/src/hooks/useMemory.ts:25` (`searchMemory(filters.searchQuery, workspaceId)`), `apps/web/src/components/os/apps/ChatApp.tsx:670` (`scope = workspaceId ?? 'global'`), `packages/server/src/local/routes/memory.ts:259-278` (`/api/memory/search`) +- Symptom: a search in Memory → Timeline, and the "I just remembered something relevant" toast in a workspace chat, do not search the open workspace. They return personal memories plus those of whichever workspace mind the sidecar attached last, which can belong to another workspace. +- Cause: both callers pass the workspace id as `scope` and send no `workspace` parameter. The route treats an unknown scope as 'all' and, without a `workspace` parameter, searches `multiMind` with the workspace mind it still holds from an earlier request. +- What we did: the client sends `scope=all&workspace=`; the memory contract version of the route searches exactly the scopes it is asked for (personal memory plus the named workspace, personal only when none is named). +- Recommendation: pass the workspace as its own parameter in both callers, and make the route resolve an unknown scope to personal memory only instead of reusing a previously attached workspace mind. + +### UF-036. The web client reads "important" and "temporary" memories as normal importance +- Status: Fixed +- Found: 2026-10-24 +- Where: at commit `b20b138`, `apps/web/src/lib/adapter.ts:223` (`IMPORTANCE_MAP`) and `:252` (`normalizeFrame`) +- Symptom: the Timeline shows important memories with the same importance dots as normal ones, its minimum-importance filter cannot separate them, and the login briefing, which ranks highlights by importance, ranks important memories like normal ones. +- Cause: the sidecar returns the frame-store importance values (critical, important, normal, temporary), but the client maps only low, normal, high and critical, so 'important' and 'temporary' fall back to 2 (normal). +- What we did: the map now covers temporary (1) and important (3), and keeps low and high for the Tauri command. +- Recommendation: map the importance values the sidecar actually returns. + +### UF-037. Restore overwrites database files the running sidecar holds open +- Status: Open +- Found: 2026-10-24 +- Where: at commit `b20b138`, `packages/server/src/local/routes/backup.ts:380-542` (`POST /api/restore`) +- Symptom: restoring a backup while Waggle runs writes `personal.mind`, the workspace minds and the other SQLite files over the files the sidecar has open. The running process keeps its old view of the data and can write over the restored files, or leave a WAL file that no longer matches them. +- Cause: the restore writes every file of the archive in place (only `marketplace.db` is skipped) without closing the open databases first. +- What we did: nothing yet. In the community edition the same applies to `waggle.db` and the mem0 files in `/memory/`. +- Recommendation: stage the restored files and apply them at the next start, before any database opens, as the data-erase marker does; or close the databases, restore, and restart the sidecar.