refactor(web): move the Memory screens onto the memory contract API (P1.5)

- adapter: memory ids are strings; single-memory calls take only the id
  (no ?mind= disambiguation). searchMemory takes the workspace as its own
  parameter. New getMemoryCapabilities / setMemoryExtraction. Removed:
  incrementFrameAccess, getMemoryOriginalSource, listSuppression,
  allowReimport, getWeaverStatus, and the dead importPreview, importCommit
  and getWikiWatermark. eraseMemory takes { id } or { sessionId }.
- memory-features reads GET /api/memory/capabilities for the knowledge
  graph; history import, wiki, hooks, Room and the memory MCP stay hidden
  (ADR-0002). useMemoryCapabilities re-renders the Memory screens.
- Settings > General has a Memory toggle for background fact extraction.
- Memory Center: the confidence filter, the erased-sources panel, the
  original-source view and the Deprecated chip are gone; Erase forgets
  every memory saved from the chat a memory came from and is offered only
  for memories with a chat session. Memory kinds follow the contract.
- Trust views show short memory labels for the new string ids and drop the
  per-row "not scored yet" badge (v1 stores no confidence).
- The Weaver maintenance view and the Cockpit weaver card are removed
  (the weaver package and its routes are deleted).
- Timeline uses the contract kinds and maps important/temporary
  importance.

Logs UF-033 (search scope sent as the workspace id), UF-034 (importance
mapping) and UF-035 (restore over open databases, open).
This commit is contained in:
shumeiko.it
2026-10-24 12:39:17 +02:00
parent 06d4532598
commit d433dca857
33 changed files with 480 additions and 847 deletions

View File

@@ -651,8 +651,10 @@ const ChatApp = ({
const query = buildRecallQuery(messages); const query = buildRecallQuery(messages);
if (!query) return; if (!query) return;
let cancelled = false; let cancelled = false;
const scope = workspaceId ?? 'global'; const search = workspaceId
adapter.searchMemory(query, scope).then(frames => { ? adapter.searchMemory(query, 'all', workspaceId)
: adapter.searchMemory(query, 'global');
search.then(frames => {
if (cancelled) return; if (cancelled) return;
const top = frames[0]; const top = frames[0];
if (!top?.content) return; if (!top?.content) return;

View File

@@ -11,7 +11,6 @@ const mocks = vi.hoisted(() => ({
getCapabilitiesStatus: vi.fn(), getCapabilitiesStatus: vi.fn(),
getAuditInstalls: vi.fn(), getAuditInstalls: vi.fn(),
getCostSummary: vi.fn(), getCostSummary: vi.fn(),
getWeaverStatus: vi.fn(),
getEventStats: vi.fn(), getEventStats: vi.fn(),
}, },
})); }));
@@ -29,11 +28,6 @@ beforeEach(() => {
mocks.adapter.getCapabilitiesStatus.mockResolvedValue({}); mocks.adapter.getCapabilitiesStatus.mockResolvedValue({});
mocks.adapter.getAuditInstalls.mockResolvedValue([]); mocks.adapter.getAuditInstalls.mockResolvedValue([]);
mocks.adapter.getCostSummary.mockResolvedValue({ totalTokens: 0, estimatedCost: 0 }); 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 }); mocks.adapter.getEventStats.mockResolvedValue({ byType: {}, total: 0 });
}); });

View File

@@ -1,7 +1,6 @@
import { useState, useEffect } from 'react'; import { useState, useEffect } from 'react';
import { Activity, Server, DollarSign, Clock, Plug, RefreshCw, Timer, Brain, Shield, Network, FileText, ChevronDown, AlertTriangle } from 'lucide-react'; import { Activity, Server, DollarSign, Clock, Plug, RefreshCw, Timer, Brain, Shield, Network, FileText, ChevronDown, AlertTriangle } from 'lucide-react';
import { adapter } from '@/lib/adapter'; import { adapter } from '@/lib/adapter';
import { DATE_LOCALE } from '@/lib/date-locale';
import type { CronJob } from '@/lib/types'; import type { CronJob } from '@/lib/types';
import { describeCronExpr } from '@/lib/cron-presets'; import { describeCronExpr } from '@/lib/cron-presets';
@@ -15,11 +14,6 @@ interface CockpitData {
vault?: unknown; vault?: unknown;
capStatus?: unknown; capStatus?: unknown;
auditTrail?: 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<string, number>; total: number }; eventStats?: { byType: Record<string, number>; total: number };
} }
@@ -32,7 +26,7 @@ const CockpitApp = () => {
const refresh = async () => { const refresh = async () => {
setLoading(true); setLoading(true);
try { 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.getSystemHealth(),
adapter.getAgentCost(), adapter.getAgentCost(),
adapter.getConnectors(), adapter.getConnectors(),
@@ -41,7 +35,6 @@ const CockpitApp = () => {
adapter.getCapabilitiesStatus(), adapter.getCapabilitiesStatus(),
adapter.getAuditInstalls(), adapter.getAuditInstalls(),
adapter.getCostSummary(), adapter.getCostSummary(),
adapter.getWeaverStatus(),
adapter.getEventStats(), adapter.getEventStats(),
]); ]);
setData({ setData({
@@ -53,7 +46,6 @@ const CockpitApp = () => {
vault: vault.status === 'fulfilled' ? vault.value : undefined, vault: vault.status === 'fulfilled' ? vault.value : undefined,
capStatus: capStatus.status === 'fulfilled' ? capStatus.value : undefined, capStatus: capStatus.status === 'fulfilled' ? capStatus.value : undefined,
auditTrail: audit.status === 'fulfilled' ? audit.value : undefined, auditTrail: audit.status === 'fulfilled' ? audit.value : undefined,
weaver: weaver.status === 'fulfilled' ? weaver.value : undefined,
eventStats: evStats.status === 'fulfilled' ? evStats.value : undefined, eventStats: evStats.status === 'fulfilled' ? evStats.value : undefined,
}); });
const allFailed = [health, cost, connectors, crons, vault, capStatus, audit].every(r => r.status === 'rejected'); const allFailed = [health, cost, connectors, crons, vault, capStatus, audit].every(r => r.status === 'rejected');
@@ -149,24 +141,6 @@ const CockpitApp = () => {
</p> </p>
</div> </div>
{/* 2b. Memory Weaver */}
{data.weaver && (
<div className="p-3 rounded-xl bg-secondary/30 border border-border/30">
<div className="flex items-center gap-2 mb-2">
<Brain className="w-4 h-4 text-muted-foreground" />
<span className="text-xs font-display font-medium text-foreground">Memory Weaver</span>
</div>
<p className="text-[11px] text-muted-foreground">
Status: <span className={data.weaver.personalMind?.timerActive ? 'text-[var(--healthy)]' : 'text-muted-foreground'}>{data.weaver.personalMind?.timerActive ? 'Active' : 'Idle'}</span>
</p>
{data.weaver.personalMind?.lastConsolidation && (
<p className="text-[11px] text-muted-foreground">
Last consolidation: {new Date(data.weaver.personalMind.lastConsolidation).toLocaleDateString(DATE_LOCALE)}
</p>
)}
</div>
)}
{/* 2c. Event Activity */} {/* 2c. Event Activity */}
{data.eventStats && data.eventStats.total > 0 && ( {data.eventStats && data.eventStats.total > 0 && (
<div className="p-3 rounded-xl bg-secondary/30 border border-border/30"> <div className="p-3 rounded-xl bg-secondary/30 border border-border/30">

View File

@@ -1,6 +1,6 @@
import { useState } from 'react'; import { useState } from 'react';
import { motion, useReducedMotion } from 'framer-motion'; 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 type { KGNode, KGEdge } from '@/lib/types';
import { HintTooltip } from '@/components/ui/hint-tooltip'; import { HintTooltip } from '@/components/ui/hint-tooltip';
import { SPRING } from '@/lib/motion/tokens'; import { SPRING } from '@/lib/motion/tokens';
@@ -8,13 +8,12 @@ import { cn } from '@/lib/utils';
import MemoryTrust from './MemoryTrust'; import MemoryTrust from './MemoryTrust';
import KnowledgeGraphViewer from './memory/KnowledgeGraphViewer'; import KnowledgeGraphViewer from './memory/KnowledgeGraphViewer';
import HarvestTab from './memory/HarvestTab'; import HarvestTab from './memory/HarvestTab';
import WeaverPanel from './memory/WeaverPanel';
import WikiTab from './memory/WikiTab'; import WikiTab from './memory/WikiTab';
import MemoryCenterTab from './memory/MemoryCenterTab'; import MemoryCenterTab from './memory/MemoryCenterTab';
import TimelineTab, { type TimelineTabProps } from './memory/TimelineTab'; import TimelineTab, { type TimelineTabProps } from './memory/TimelineTab';
import ImportReminderBanner from './memory/ImportReminderBanner'; import ImportReminderBanner from './memory/ImportReminderBanner';
import { useOnboarding } from '@/hooks/useOnboarding'; 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 * 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 * 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 * Personal Mind; "About this work" reads the active workspace's Mind. The
* per-mind list is MemoryCenterTab (reused, parameterized — D2). The legacy * per-mind list is MemoryCenterTab (reused, parameterized — D2). The legacy
* MemoryApp views (Timeline / Graph / Harvest / Weaver / Wiki) * MemoryApp views (Timeline / Graph / Harvest / Wiki) survive as secondary
* survive as secondary tabs after a divider — capability preserved, entry * tabs after a divider; Graph, Harvest and Wiki are hidden in v1 (ADR-0002).
* restructured. Mind pills render only on the Memories tab: the legacy tabs * 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 * keep their own scoping (Graph has a scope selector; Harvest writes to the
* personal mind by design). * personal mind by design).
* *
@@ -35,12 +35,12 @@ import { hasMemoryFeature, isMemoryViewAvailable } from '@/lib/memory-features';
*/ */
export type MindScope = 'personal' | 'workspace'; 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; // PR3.5: 'trust' (screen 19) is the new PRIMARY front door — first + default;
// the legacy views demote to secondary (after the divider). // the legacy views demote to secondary (after the divider).
export const MEMORY_VIEWS: readonly MemoryView[] = [ export const MEMORY_VIEWS: readonly MemoryView[] = [
'trust', 'memories', 'timeline', 'graph', 'harvest', 'weaver', 'wiki', 'trust', 'memories', 'timeline', 'graph', 'harvest', 'wiki',
]; ];
interface MemoryTabDef { interface MemoryTabDef {
@@ -50,9 +50,9 @@ interface MemoryTabDef {
tooltip: string; tooltip: string;
} }
// UX gold-standard H1: 7 equal-weight tabs regrouped into 4 primary + an // UX gold-standard H1: the tabs are regrouped into 4 primary + an "Advanced"
// "Advanced" flyout (display-level IA only — every view id, route and // flyout (display-level IA only — every view id, route and ?tab= deep-link is
// ?tab= deep-link is unchanged; MEMORY_VIEWS still validates all 7). // unchanged; MEMORY_VIEWS validates them all).
const PRIMARY_TABS: MemoryTabDef[] = [ 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: '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' }, { 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[] = [ const ADVANCED_TABS: MemoryTabDef[] = [
{ id: 'harvest', label: 'Imports', icon: Download, tooltip: 'Import conversations from other AIs' }, { 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' }, { id: 'wiki', label: 'Wiki', icon: BookOpen, tooltip: 'Compiled knowledge pages' },
]; ];
@@ -93,6 +92,8 @@ const MemoryCenterApp = ({
}: MemoryCenterAppProps) => { }: MemoryCenterAppProps) => {
// Reminder-banner eligibility (carried over from the retired MemoryApp shell). // Reminder-banner eligibility (carried over from the retired MemoryApp shell).
const { state: onboardingState } = useOnboarding(); 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 // ADR-0002: views of hidden memory features (graph, imports, wiki) are not
// offered; a hidden view requested anyway falls back to the default. // offered; a hidden view requested anyway falls back to the default.
@@ -286,8 +287,6 @@ const MemoryCenterApp = ({
}} /> }} />
) : view === 'harvest' ? ( ) : view === 'harvest' ? (
<HarvestTab /> <HarvestTab />
) : view === 'weaver' ? (
<WeaverPanel />
) : view === 'wiki' ? ( ) : view === 'wiki' ? (
<WikiTab /> <WikiTab />
) : null} ) : null}

View File

@@ -3,6 +3,7 @@ import { ShieldCheck, Info } from 'lucide-react';
import { adapter } from '@/lib/adapter'; import { adapter } from '@/lib/adapter';
import MemoryTrustManage from './memory/MemoryTrustManage'; import MemoryTrustManage from './memory/MemoryTrustManage';
import MemoryTrustWhy from './memory/MemoryTrustWhy'; import MemoryTrustWhy from './memory/MemoryTrustWhy';
import { memoryLabel } from './memory/memory-label';
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
/** /**
@@ -137,7 +138,6 @@ export default function MemoryTrust({ mind, workspaceId }: MemoryTrustProps) {
const [traceMemoryId, setTraceMemoryId] = useState<string | null>(null); const [traceMemoryId, setTraceMemoryId] = useState<string | null>(null);
const [pendingOpenId, setPendingOpenId] = useState<string | null>(null); const [pendingOpenId, setPendingOpenId] = useState<string | null>(null);
const toastTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined); const toastTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
const wsParam = mind === 'workspace' ? workspaceId : undefined;
const showToast = useCallback((msg: string) => { const showToast = useCallback((msg: string) => {
setToast(msg); setToast(msg);
@@ -154,14 +154,14 @@ export default function MemoryTrust({ mind, workspaceId }: MemoryTrustProps) {
const correctFromTrace = useCallback((id: string) => { setPendingOpenId(id); setView('manage'); }, []); const correctFromTrace = useCallback((id: string) => { setPendingOpenId(id); setView('manage'); }, []);
const forgetFromTrace = useCallback(async (id: string) => { const forgetFromTrace = useCallback(async (id: string) => {
try { try {
await adapter.deleteMemoryById(id, wsParam, mind); await adapter.deleteMemoryById(id);
showToast(`Forgotten M-${id} — removed from recall`); showToast(`Forgotten ${memoryLabel(id)} — removed from recall`);
setTraceMemoryId(null); setTraceMemoryId(null);
setView('manage'); setView('manage');
} catch { } catch {
showToast('Could not forget that memory'); showToast('Could not forget that memory');
} }
}, [wsParam, mind, showToast]); }, [showToast]);
// Segmented Manage/Why switch — rendered INLINE on the hero eyebrow row (one // Segmented Manage/Why switch — rendered INLINE on the hero eyebrow row (one
// register; the old labelled strip + helper sentence doubled what the hero and // register; the old labelled strip + helper sentence doubled what the hero and
@@ -213,8 +213,6 @@ export default function MemoryTrust({ mind, workspaceId }: MemoryTrustProps) {
<> <>
<WhyHero controls={segmented} /> <WhyHero controls={segmented} />
<MemoryTrustWhy <MemoryTrustWhy
mind={mind}
workspaceId={workspaceId}
memoryId={traceMemoryId} memoryId={traceMemoryId}
onToast={showToast} onToast={showToast}
onCorrect={correctFromTrace} onCorrect={correctFromTrace}

View File

@@ -3,7 +3,7 @@ import { useSearchParams } from 'react-router-dom';
import { import {
Cpu, Shield, Palette, Save, Loader2, Database, Cpu, Shield, Palette, Save, Loader2, Database,
Download, Upload, Wrench, DollarSign, Key, Lock, BarChart3, Trash2, Download, Upload, Wrench, DollarSign, Key, Lock, BarChart3, Trash2,
RotateCcw, GraduationCap, HelpCircle, AlertTriangle, MessageCircle, RotateCcw, GraduationCap, HelpCircle, AlertTriangle, MessageCircle, Brain,
} from 'lucide-react'; } from 'lucide-react';
import { useToast } from '@/hooks/use-toast'; import { useToast } from '@/hooks/use-toast';
import { adapter } from '@/lib/adapter'; import { adapter } from '@/lib/adapter';
@@ -25,7 +25,7 @@ import {
} from '@/lib/settings-tier-filter'; } from '@/lib/settings-tier-filter';
import { requiresYoloConfirm } from '@/lib/autonomy-confirm'; import { requiresYoloConfirm } from '@/lib/autonomy-confirm';
import { hasAnalyticsKey, isAnalyticsAllowed, setAnalyticsConsent } from '@/lib/analytics-consent'; import { hasAnalyticsKey, isAnalyticsAllowed, setAnalyticsConsent } from '@/lib/analytics-consent';
import { hasMemoryFeature } from '@/lib/memory-features'; import { hasMemoryFeature, setMemoryCapabilities, useMemoryCapabilities } from '@/lib/memory-features';
import ModelSelector from '@/components/os/ModelSelector'; import ModelSelector from '@/components/os/ModelSelector';
import ModelPilotCard from '@/components/os/ModelPilotCard'; import ModelPilotCard from '@/components/os/ModelPilotCard';
import EmbeddingRoutingCard from '@/components/os/EmbeddingRoutingCard'; import EmbeddingRoutingCard from '@/components/os/EmbeddingRoutingCard';
@@ -166,6 +166,23 @@ const SettingsApp = () => {
const [backupBusy, setBackupBusy] = useState(false); const [backupBusy, setBackupBusy] = useState(false);
const [pendingApproval, setPendingApproval] = useState<SettingsApproval | null>(null); const [pendingApproval, setPendingApproval] = useState<SettingsApproval | null>(null);
const [approvalBusy, setApprovalBusy] = useState(false); 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<string | null>(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 // Load settings
useEffect(() => { useEffect(() => {
@@ -435,6 +452,45 @@ const SettingsApp = () => {
</div> </div>
</div> </div>
{/* Memory: background fact extraction from chats (ADR-0007). Shown at
every level, because it decides what Waggle keeps about the user. */}
<div className="space-y-3" data-testid="settings-memory">
<h3 className="text-xs font-display font-semibold text-foreground flex items-center gap-2">
<Brain className="w-3.5 h-3.5 text-muted-foreground" />
Memory
</h3>
<p className="text-[11px] text-muted-foreground leading-relaxed">
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.
</p>
<div className="flex items-center justify-between gap-3 p-3 rounded-xl bg-secondary/30 border border-border/30">
<div>
<p className="text-xs font-display font-medium text-foreground">Learn facts about me from chats</p>
<p className="text-[11px] text-muted-foreground">
{!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.'}
</p>
</div>
<button
type="button"
aria-label={extractionOn ? 'Stop learning facts from chats' : 'Learn facts about me from chats'}
aria-pressed={extractionOn}
disabled={!extractionAvailable || extractionSaving}
onClick={() => { void toggleExtraction(); }}
className={`relative w-10 h-5 shrink-0 rounded-full transition-colors disabled:opacity-50 ${extractionOn ? 'bg-primary' : 'bg-muted'}`}
>
<span className={`absolute top-0.5 w-4 h-4 rounded-full bg-white transition-transform ${extractionOn ? 'left-5' : 'left-0.5'}`} />
</button>
</div>
{extractionError && (
<p role="alert" className="text-[11px] text-destructive">{extractionError}</p>
)}
</div>
{/* M2-7: Privacy & Telemetry — Phase 4.1: hidden at Essential per ux-disclosure-levels.md {/* 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 §"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 already opting into more advanced surface area). ADR-0006: shown at every level

View File

@@ -18,7 +18,6 @@ const memory: Memory = {
confidence: 91, confidence: 91,
tags: ['research'], tags: ['research'],
evidence: [], evidence: [],
hasOriginalSource: false,
createdAt: '2026-07-08T08:00:00.000Z', createdAt: '2026-07-08T08:00:00.000Z',
updatedAt: '2026-07-08T09:00:00.000Z', updatedAt: '2026-07-08T09:00:00.000Z',
}; };

View File

@@ -40,7 +40,8 @@ interface MemoryCardProps {
export function MemoryCard({ memory, onClick, selected, onSelect, className, duplicateCount }: MemoryCardProps) { export function MemoryCard({ memory, onClick, selected, onSelect, className, duplicateCount }: MemoryCardProps) {
const status = statusMeta(memory.status); 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 showTitle = memory.title && memory.title !== memory.content;
const selectionLabel = memory.title || memory.content.slice(0, 80) || memory.id; const selectionLabel = memory.title || memory.content.slice(0, 80) || memory.id;

View File

@@ -1,6 +1,6 @@
import { useState, useEffect, useCallback, useRef, useMemo } from 'react'; import { useState, useEffect, useCallback, useRef, useMemo } from 'react';
import { useReducedMotion } from 'framer-motion'; 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 { adapter } from '@/lib/adapter';
import { DATE_LOCALE } from '@/lib/date-locale'; import { DATE_LOCALE } from '@/lib/date-locale';
import { consumeDeepLink } from '@/lib/app-deeplink'; 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): * 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 * fetches the shared Memory entity via the /api/memory* adapter methods and
* exposes source / confidence / evidence / scope + edit / archive / delete / merge * exposes source / evidence / scope + edit / archive / delete / erase / merge
* (PRD §12.4, DoD #4; C11 merge). The 'Needs review' filter surfaces C33 imports * (PRD §12.4, DoD #4; C11 merge). The 'Needs review' filter surfaces facts
* (status=unreviewed). * 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` * 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 * (+ `workspaceId` for the workspace mind). Defaults to personal — the J08 deep
* link and pre-P3 call sites keep their behavior. Workspace-mind mutations MUST * link and pre-P3 call sites keep their behavior. Memory ids are unique across
* carry workspaceId or the server's candidateStores lookup misses the frame * scopes, so mutations need only the id.
* (personal-store-only search → 404).
*/ */
export interface MemoryCenterTabProps { export interface MemoryCenterTabProps {
@@ -52,13 +51,6 @@ const STATUS_FILTERS: { value: '' | MemoryStatus; label: string }[] = [
{ value: 'unreviewed', label: 'Needs review' }, { value: 'unreviewed', label: 'Needs review' },
{ value: 'active', label: 'Active' }, { value: 'active', label: 'Active' },
{ value: 'archived', label: 'Archived' }, { 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'; 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, workspaceId,
consumeDeepLinks = true, consumeDeepLinks = true,
}: MemoryCenterTabProps = {}) { }: 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 wsParam = mind === 'workspace' ? workspaceId : undefined;
const reduceMotion = !!useReducedMotion(); const reduceMotion = !!useReducedMotion();
// Wave T Lane D (item 2): seed the initial list from the session cache so a // 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 // 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 // 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. // 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<Memory[]>(() => readMemoryListCache(initialCacheKey) ?? []); const [memories, setMemories] = useState<Memory[]>(() => readMemoryListCache(initialCacheKey) ?? []);
const [loading, setLoading] = useState(() => readMemoryListCache(initialCacheKey) === undefined); const [loading, setLoading] = useState(() => readMemoryListCache(initialCacheKey) === undefined);
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
@@ -88,13 +80,12 @@ export default function MemoryCenterTab({
// fresh open reading as "one card in a dark field". 'All' is now the honest // 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. // default; the curated 'active' view stays one click away as a labeled chip.
const [status, setStatus] = useState<'' | MemoryStatus>(''); 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 // 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 // (this list fetches filtered). Held in a ref (updated every render) so the
// mind-switch reset effect can reseed without taking a filter dependency — // mind-switch reset effect can reseed without taking a filter dependency —
// reseeding on every keystroke would fight the debounced fetch. // 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); const cacheKeyRef = useRef(cacheKey);
cacheKeyRef.current = cacheKey; cacheKeyRef.current = cacheKey;
@@ -104,36 +95,15 @@ export default function MemoryCenterTab({
const [draftContent, setDraftContent] = useState(''); const [draftContent, setDraftContent] = useState('');
const [draftKind, setDraftKind] = useState<MemoryKind>('fact'); const [draftKind, setDraftKind] = useState<MemoryKind>('fact');
// #7 "View original source": inline expandable verbatim-source view in the // Erase receipt: a transient, dismissible confirmation of how many memories
// detail drawer (not a nested modal). A frame can link MULTIPLE verbatim // the last erase removed (the drawer closes on success, so the receipt lives
// sources (metadata.archiveUids) → render each in its own escaped block; // at the list level).
// 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<ArchiveRow[]>([]);
const [sourceLoading, setSourceLoading] = useState(false);
const [sourceError, setSourceError] = useState<string | null>(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).
const [eraseNotice, setEraseNotice] = useState<string | null>(null); const [eraseNotice, setEraseNotice] = useState<string | null>(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 = type PendingApproval =
| { kind: 'delete'; memory: Memory } | { kind: 'delete'; memory: Memory }
| { kind: 'erase'; memory: Memory } | { kind: 'erase'; memory: Memory; sessionId: string };
| { kind: 'allow-reimport'; row: SuppressedRow };
const [suppressionOpen, setSuppressionOpen] = useState(false);
const [suppressed, setSuppressed] = useState<SuppressedRow[]>([]);
const [suppressionLoading, setSuppressionLoading] = useState(false);
const [pendingApproval, setPendingApproval] = useState<PendingApproval | null>(null); const [pendingApproval, setPendingApproval] = useState<PendingApproval | null>(null);
const [approvalBusy, setApprovalBusy] = useState(false); 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<string | undefined>(undefined);
// J08: Home's "N memories need review" banner deep-links here with // J08: Home's "N memories need review" banner deep-links here with
// {appId:'memory', filter:'unreviewed'}. Two paths (AutomationCenterApp // {appId:'memory', filter:'unreviewed'}. Two paths (AutomationCenterApp
@@ -192,7 +162,6 @@ export default function MemoryCenterTab({
q: q.trim() || undefined, q: q.trim() || undefined,
kind: kind || undefined, kind: kind || undefined,
status: status || undefined, status: status || undefined,
minConfidence: minConfidence || undefined,
limit: 200, limit: 200,
}); });
if (seq === loadSeq.current) { setMemories(res); writeMemoryListCache(cacheKey, res); } if (seq === loadSeq.current) { setMemories(res); writeMemoryListCache(cacheKey, res); }
@@ -201,7 +170,7 @@ export default function MemoryCenterTab({
} finally { } finally {
if (seq === loadSeq.current) setLoading(false); if (seq === loadSeq.current) setLoading(false);
} }
}, [q, kind, status, minConfidence, mind, wsParam, cacheKey]); }, [q, kind, status, mind, wsParam, cacheKey]);
useEffect(() => { useEffect(() => {
const t = setTimeout(load, q ? 250 : 0); // debounce text search only 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 // Mind switch invalidates EVERYTHING in flight and on screen (keyed on the
// EFFECTIVE scope, so personal-mind instances ignore workspace churn): // EFFECTIVE scope, so personal-mind instances ignore workspace churn):
// - selection/checklist: a drawer or merge set carried across minds would // - selection/checklist: a drawer or merge set from the other list must not
// mutate the wrong store (ids collide across the per-mind SQLite DBs); // act on memories that are no longer shown;
// - the list: stale rows must not render under the new mind's pill; // - 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 // - loadSeq: an in-flight old-mind response must not commit into the window
// between this reset and the (debounced) next load starting; // between this reset and the (debounced) next load starting;
@@ -229,8 +198,6 @@ export default function MemoryCenterTab({
setMemories(cached ?? []); setMemories(cached ?? []);
setLoading(cached === undefined); setLoading(cached === undefined);
setEraseNotice(null); // a receipt for the prior mind must not persist across the switch 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); setPendingApproval(null);
setApprovalBusy(false); setApprovalBusy(false);
}, [mind, wsParam]); }, [mind, wsParam]);
@@ -241,37 +208,6 @@ export default function MemoryCenterTab({
setDraftKind(m.kind); 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) => { const toggleChecked = (id: string, on: boolean) => {
setChecked((prev) => { setChecked((prev) => {
const next = new Set(prev); const next = new Set(prev);
@@ -281,7 +217,7 @@ export default function MemoryCenterTab({
}; };
const mutate = async (fn: () => Promise<unknown>, closeDrawer = false) => { const mutate = async (fn: () => Promise<unknown>, 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); setBusy(true);
try { try {
await fn(); await fn();
@@ -302,48 +238,27 @@ export default function MemoryCenterTab({
if (draftContent !== selected.content) patch.content = draftContent; if (draftContent !== selected.content) patch.content = draftContent;
if (draftKind !== selected.kind) patch.kind = draftKind; if (draftKind !== selected.kind) patch.kind = draftKind;
if (Object.keys(patch).length === 0) { setSelected(null); return; } 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 archive = (m: Memory) => void mutate(() => adapter.archiveMemory(m.id), true);
const unarchive = (m: Memory) => void mutate(() => adapter.patchMemory(m.id, { status: 'active' }, wsParam, mind), 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' }, wsParam, mind), true); const markReviewed = (m: Memory) => void mutate(() => adapter.patchMemory(m.id, { status: 'active' }), true);
const remove = (m: Memory) => setPendingApproval({ kind: 'delete', memory: m }); const remove = (m: Memory) => setPendingApproval({ kind: 'delete', memory: m });
// #7 P1 GDPR Art.17 "right to erasure" — the FULL sweep (this memory + its // Erase: forget every memory saved from the chat this memory came from.
// original source text + every search-index entry + knowledge-graph facts // Offered only for memories with a chat session; Delete covers the rest.
// derived solely from it + the verbatim conversation turns behind it). Runs const erase = (m: Memory) => {
// server-side in one atomic transaction. Distinct from Delete (removes just if (m.sessionId) setPendingApproval({ kind: 'erase', memory: m, sessionId: m.sessionId });
// 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 });
const mergeSelected = () => { const mergeSelected = () => {
const ids = [...checked]; const ids = [...checked];
if (ids.length < 2) return; if (ids.length < 2) return;
void mutate(async () => { void mutate(async () => {
await adapter.mergeMemories(ids, { workspaceId: wsParam, mind }); await adapter.mergeMemories(ids);
setChecked(new Set()); 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<ApprovalRequest | null>(() => { const approvalRequest = useMemo<ApprovalRequest | null>(() => {
if (!pendingApproval) return null; if (!pendingApproval) return null;
if (pendingApproval.kind === 'delete') { if (pendingApproval.kind === 'delete') {
@@ -357,32 +272,20 @@ export default function MemoryCenterTab({
riskLevel: 'high', riskLevel: 'high',
}; };
} }
if (pendingApproval.kind === 'erase') {
return { return {
action: `Erase memory and derived data: ${pendingApproval.memory.title}`, action: 'Erase everything remembered from this chat',
scope: [ scope: [
'This permanently removes the memory, its original source text, search index entries, related conversation turns, and derived knowledge facts.', '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.',
'This is a GDPR Art.17 erasure action and cannot be undone.', 'The chat transcript itself is kept.',
'Use Archive to hide it, or Delete to remove only this one record.', 'This cannot be undone. Use Delete to remove only this memory.',
], ],
riskLevel: 'critical', riskLevel: 'critical',
}; };
}
return {
action: `Allow source to be re-imported: ${pendingApproval.row.sourceRef}`,
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.',
],
riskLevel: 'high',
};
}, [pendingApproval]); }, [pendingApproval]);
const approvalLabel = const approvalLabel =
pendingApproval?.kind === 'delete' ? (approvalBusy ? 'Deleting...' : 'Delete memory') pendingApproval?.kind === 'delete' ? (approvalBusy ? 'Deleting...' : 'Delete memory')
: pendingApproval?.kind === 'erase' ? (approvalBusy ? 'Erasing...' : 'Erase memory') : approvalBusy ? 'Erasing...' : 'Erase memories';
: approvalBusy ? 'Allowing...' : 'Allow re-import';
const confirmTrustAction = async () => { const confirmTrustAction = async () => {
if (!pendingApproval) return; if (!pendingApproval) return;
@@ -390,37 +293,20 @@ export default function MemoryCenterTab({
setApprovalBusy(true); setApprovalBusy(true);
setEraseNotice(null); setEraseNotice(null);
try { try {
setBusy(true);
if (current.kind === 'delete') { if (current.kind === 'delete') {
setBusy(true); await adapter.deleteMemoryById(current.memory.id);
await adapter.deleteMemoryById(current.memory.id, wsParam, mind); } else {
const { deleted } = await adapter.eraseMemory({ sessionId: current.sessionId });
setEraseNotice(`Erased ${deleted} ${deleted === 1 ? 'memory' : 'memories'} from that chat.`);
}
setSelected(null); setSelected(null);
setPendingApproval(null); setPendingApproval(null);
setReloadTick((t) => t + 1); setReloadTick((t) => t + 1);
return;
}
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 });
setPendingApproval(null);
await loadSuppression();
} catch (e) { } catch (e) {
setError(e instanceof Error ? e.message : 'Action failed'); setError(e instanceof Error ? e.message : 'Action failed');
} finally { } finally {
if (current.kind === 'allow-reimport') setSuppressionLoading(false); setBusy(false);
else setBusy(false);
setApprovalBusy(false); setApprovalBusy(false);
} }
}; };
@@ -437,12 +323,10 @@ export default function MemoryCenterTab({
const statusLabel = STATUS_FILTERS.find((s) => s.value === status)?.label; const statusLabel = STATUS_FILTERS.find((s) => s.value === status)?.label;
if (status && statusLabel) parts.push(statusLabel); if (status && statusLabel) parts.push(statusLabel);
if (kind) parts.push(memoryKindLabel(kind)); 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(); const query = q.trim();
if (query) parts.push(`matching "${query}"`); if (query) parts.push(`matching "${query}"`);
return parts.join(' · '); return parts.join(' · ');
}, [status, kind, minConfidence, q]); }, [status, kind, q]);
return ( return (
// Wave U Lane E (item 4): a ~150ms fade-slide when this panel mounts on the // 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" className="flex-1 bg-transparent text-xs h-auto border-0 p-0 focus-visible:ring-0 focus-visible:ring-offset-0"
/> />
</div> </div>
<select
value={minConfidence}
onChange={(e) => setMinConfidence(Number(e.target.value))}
name="memoryConfidenceFilter"
autoComplete="off"
className={cn('text-[11px] rounded-md border border-border bg-muted/40 px-2 py-1 text-muted-foreground', CONTROL_FOCUS_CLASS)}
aria-label="Filter by confidence"
>
{CONFIDENCE_FILTERS.map((c) => <option key={c.value} value={c.value}>{c.label}</option>)}
</select>
</div> </div>
<div className="flex flex-wrap gap-1"> <div className="flex flex-wrap gap-1">
@@ -527,7 +401,7 @@ export default function MemoryCenterTab({
)} )}
</div> </div>
{/* #7 P1 GDPR erasure receipt — dismissible confirmation of what was purged. */} {/* Erase receipt — dismissible confirmation of what was removed. */}
{eraseNotice && ( {eraseNotice && (
<div role="status" aria-live="polite" className="mx-2.5 mt-2 flex items-start gap-2 rounded-md border border-primary/30 bg-primary/10 px-2.5 py-1.5 text-xs text-foreground"> <div role="status" aria-live="polite" className="mx-2.5 mt-2 flex items-start gap-2 rounded-md border border-primary/30 bg-primary/10 px-2.5 py-1.5 text-xs text-foreground">
<Check className="w-3.5 h-3.5 mt-0.5 shrink-0 text-honey" /> <Check className="w-3.5 h-3.5 mt-0.5 shrink-0 text-honey" />
@@ -536,42 +410,6 @@ export default function MemoryCenterTab({
</div> </div>
)} )}
{/* #7 sticky erasure — re-consent surface: erased sources kept from re-importing. */}
<div className="border-b border-border/50 bg-background/40">
<button
onClick={toggleSuppression}
aria-expanded={suppressionOpen}
className={cn('w-full flex items-center gap-2 px-2.5 py-1.5 text-xs text-muted-foreground hover:text-foreground', CONTROL_FOCUS_CLASS)}
>
<span className="text-[10px] w-2">{suppressionOpen ? '▾' : '▸'}</span>
<span>Erased sources{suppressionOpen && suppressed.length > 0 ? ` (${suppressed.length})` : ''}</span>
<span className="ml-auto text-[10px] opacity-70">GDPR Art.17 — kept from re-import</span>
</button>
{suppressionOpen && (
<div className="px-2.5 pb-2 space-y-1">
{suppressionLoading ? (
<div className="text-xs text-muted-foreground py-1">Loading…</div>
) : suppressed.length === 0 ? (
<div className="text-xs text-muted-foreground py-1">
No erased sources are suppressed. Erasing a source keeps it from re-materializing if it's re-imported later.
</div>
) : (
suppressed.map((row) => (
<div key={`${row.source}::${row.sourceRef}`} className="flex items-center gap-2 text-xs bg-muted/40 rounded px-2 py-1">
<span className="font-medium shrink-0">{row.source}</span>
<span className="text-muted-foreground truncate flex-1 min-w-0" title={row.sourceRef}>{row.sourceRef}</span>
<button
onClick={() => allowReimport(row)}
disabled={suppressionLoading}
className={cn('shrink-0 text-[11px] px-1.5 py-0.5 rounded border border-border/60 hover:bg-muted disabled:opacity-50', CONTROL_FOCUS_CLASS)}
>Allow re-import</button>
</div>
))
)}
</div>
)}
</div>
{/* Wave V Lane A (item 2): result-count header — Trust-hero parity. Rendered {/* 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 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 own the empty-list surface below. When a background refresh is in flight
@@ -627,11 +465,11 @@ export default function MemoryCenterTab({
<p className="text-xs text-muted-foreground"> <p className="text-xs text-muted-foreground">
{mind === 'workspace' && !workspaceId {mind === 'workspace' && !workspaceId
? 'No workspace selected — open a workspace to see what it has learned.' ? 'No workspace selected — open a workspace to see what it has learned.'
: q || kind || status || minConfidence : q || kind || status
? 'No memories match these filters.' ? 'No memories match these filters.'
: mind === 'workspace' : mind === 'workspace'
? 'Nothing learned in this workspace yet — memories appear here as you work.' ? '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.'}
</p> </p>
</div> </div>
) : ( ) : (
@@ -683,14 +521,16 @@ export default function MemoryCenterTab({
<button onClick={() => remove(selected)} disabled={busy} className={cn('ml-auto inline-flex items-center gap-1 px-2.5 py-1 rounded-lg text-xs text-destructive hover:bg-destructive/10', CONTROL_FOCUS_CLASS)}> <button onClick={() => remove(selected)} disabled={busy} className={cn('ml-auto inline-flex items-center gap-1 px-2.5 py-1 rounded-lg text-xs text-destructive hover:bg-destructive/10', CONTROL_FOCUS_CLASS)}>
<Trash2 className="w-3 h-3" /> Delete <Trash2 className="w-3 h-3" /> Delete
</button> </button>
{selected.sessionId && (
<button <button
onClick={() => erase(selected)} onClick={() => erase(selected)}
disabled={busy} disabled={busy}
title="GDPR erasure: permanently removes this memory, its original source, the conversation turns behind it, and everything derived from it. Cannot be undone." title="Removes this memory and every other memory saved from the same chat. Cannot be undone."
className={cn('inline-flex items-center gap-1 px-2.5 py-1 rounded-lg border border-destructive/40 text-xs text-destructive hover:bg-destructive/10 disabled:opacity-50', CONTROL_FOCUS_CLASS)} className={cn('inline-flex items-center gap-1 px-2.5 py-1 rounded-lg border border-destructive/40 text-xs text-destructive hover:bg-destructive/10 disabled:opacity-50', CONTROL_FOCUS_CLASS)}
> >
<ShieldOff className="w-3 h-3" /> Erase <ShieldOff className="w-3 h-3" /> Erase chat memories
</button> </button>
)}
</div> </div>
) : undefined} ) : undefined}
> >
@@ -736,49 +576,7 @@ export default function MemoryCenterTab({
<div className="mt-2 text-xs text-muted-foreground/80 max-h-32 overflow-auto" dangerouslySetInnerHTML={{ __html: renderChatMarkdown(draftContent) }} /> <div className="mt-2 text-xs text-muted-foreground/80 max-h-32 overflow-auto" dangerouslySetInnerHTML={{ __html: renderChatMarkdown(draftContent) }} />
</div> </div>
<EvidencePanel source={selected.source} sourceId={selected.sourceId} sourceUrl={selected.sourceUrl} evidence={selected.evidence} onViewOriginalSource={viewOriginalSource} hasOriginalSource={selected.hasOriginalSource} expanded={sourceExpanded} busy={sourceLoading} /> <EvidencePanel source={selected.source} sourceId={selected.sourceId} sourceUrl={selected.sourceUrl} evidence={selected.evidence} />
{sourceExpanded && (
<div className="rounded-md border border-border bg-muted/30 p-2 space-y-2">
{sourceLoading ? (
<div role="status" aria-live="polite" className="flex items-center gap-2 text-xs text-muted-foreground">
<Loader2 className="w-3.5 h-3.5 animate-spin" /> Loading original source…
</div>
) : sourceError ? (
<div role="alert" className="text-xs text-destructive">{sourceError}</div>
) : sourceRows.length > 0 ? (
/* One frame can be distilled from MULTIPLE verbatim sources — render
each in its own React-escaped <pre> (NEVER dangerouslySetInnerHTML:
the archive is hostile-by-assumption) with its own provenance label
and advisory injection badge. */
sourceRows.map((row, i) => (
<div key={i} className={cn('space-y-2', i > 0 && 'border-t border-border/60 pt-2')}>
<div className="flex flex-wrap items-center gap-1.5">
<span className="text-[11px] font-display font-semibold uppercase tracking-wide text-muted-foreground">
Original source{sourceRows.length > 1 ? ` ${i + 1} of ${sourceRows.length}` : ''}
</span>
{row.injectionFlagged && (
<span
className="inline-flex items-center gap-1 rounded-md border border-destructive/40 bg-destructive/10 px-1.5 py-0.5 text-[10px] font-medium text-destructive"
title={`Advisory: a prompt-injection pattern was detected in a 4KB probe of this source${row.injectionFlags ? ` (${row.injectionFlags})` : ''}. This is a probe, not a full-content guarantee.`}
>
<AlertTriangle className="w-3 h-3" /> Injection flagged
</span>
)}
</div>
<p className="text-[11px] text-muted-foreground">
{row.source}{row.sourceRef ? ` · ${row.sourceRef}` : ''}
</p>
<pre className="max-h-64 overflow-auto whitespace-pre-wrap break-words rounded bg-background/60 p-2 text-[11px] font-mono leading-relaxed text-foreground">
{row.content}
</pre>
</div>
))
) : (
<p className="text-xs text-muted-foreground">No original source recorded for this memory.</p>
)}
</div>
)}
<p className="text-[11px] text-muted-foreground"> <p className="text-[11px] text-muted-foreground">
Created {new Date(selected.createdAt).toLocaleString(DATE_LOCALE)} Created {new Date(selected.createdAt).toLocaleString(DATE_LOCALE)}

View File

@@ -14,6 +14,7 @@ import { DetailDrawer } from '@/components/ui/detail-drawer';
import { EvidencePanel } from '@/components/ui/evidence-panel'; import { EvidencePanel } from '@/components/ui/evidence-panel';
import { renderChatMarkdown } from '@/lib/render-markdown'; import { renderChatMarkdown } from '@/lib/render-markdown';
import { cn } from '@/lib/utils'; 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 * 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 * stat bar → search + filter chips → native confidence-ring rows with the
* 3-segment ⬡ provenance line and real forget / correct / confirm actions. * 3-segment ⬡ provenance line and real forget / correct / confirm actions.
* *
* No-fabrication contract: confidence is harvest-only → the ring shows "—" and * No-fabrication contract: the memory contract stores no confidence in v1 → no
* the "High confidence & fresh" stat gates to "—" when absent; freshness is * 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 * derived as honest AGE (never a stored %); the "Forgotten" filter is gated off
* (hard delete leaves no tombstone). Stats are computed from the fetched * (hard delete leaves no tombstone). Stats are computed from the fetched
* working set (single-mind; cap-aware "500+") — never a cross-mind count. * 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 srcLabel = frameSourceLabel(memory.source);
const stale = isStale(memory); const stale = isStale(memory);
const needsConfirm = memory.status === 'unreviewed'; const needsConfirm = memory.status === 'unreviewed';
// Round-6 fix 2b: the ring renders only when a confidence actually exists; // 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 memory contract stores none in v1, so unscored rows show no badge.
// (the old stacked "unscored / CONF" micro-label was illegible).
const scored = typeof memory.confidence === 'number' && Number.isFinite(memory.confidence); const scored = typeof memory.confidence === 'number' && Number.isFinite(memory.confidence);
// Round-5..9: raw harvest strings read as log output — buildMemoryPreview // 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, // 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 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 at 12px (sub-AA) and this is the memory's correction HANDLE, not
decoration — matched to its row's --text-muted (5.6:1). */} decoration — matched to its row's --text-muted (5.6:1). */}
<span className="text-[var(--text-muted)]">⬡ M-{memory.id}</span> <span className="text-[var(--text-muted)]">⬡ {memoryLabel(memory.id)}</span>
{/* Wave-S Lane C: handoff meta + source folded into one glyph chip {/* Wave-S Lane C: handoff meta + source folded into one glyph chip
(short label at rest, full provenance in the tooltip). */} (short label at rest, full provenance in the tooltip). */}
{provShort && ( {provShort && (
@@ -293,14 +293,6 @@ function MemoryRow({ memory, onOpen, onForget, onConfirm, busy, duplicateCount,
{provShort} {provShort}
</span> </span>
)} )}
{!scored && (
<span
className="rounded-full border border-[var(--line-soft)] bg-[var(--surface-2)] px-2 py-0.5 font-sans text-[11px] text-[var(--text-muted)]"
title="No confidence stored for this memory — only harvested memories carry a score."
>
not scored yet
</span>
)}
<span className={fresh.state === 'fresh' ? 'text-[var(--healthy)]' : 'text-[var(--attention)]'}> <span className={fresh.state === 'fresh' ? 'text-[var(--healthy)]' : 'text-[var(--attention)]'}>
● {fresh.label} ● {fresh.label}
</span> </span>
@@ -352,7 +344,7 @@ function MemoryRow({ memory, onOpen, onForget, onConfirm, busy, duplicateCount,
onClick={onConfirm} onClick={onConfirm}
disabled={busy} disabled={busy}
title="Confirm this memory" 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" 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"
> >
<Check className="h-[15px] w-[15px]" strokeWidth={1.8} /> <Check className="h-[15px] w-[15px]" strokeWidth={1.8} />
@@ -362,7 +354,7 @@ function MemoryRow({ memory, onOpen, onForget, onConfirm, busy, duplicateCount,
type="button" type="button"
onClick={onOpen} onClick={onOpen}
title="Edit / correct" 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)]" 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)]"
> >
<Pencil className="h-[15px] w-[15px]" strokeWidth={1.8} /> <Pencil className="h-[15px] w-[15px]" strokeWidth={1.8} />
@@ -372,7 +364,7 @@ function MemoryRow({ memory, onOpen, onForget, onConfirm, busy, duplicateCount,
onClick={onForget} onClick={onForget}
disabled={busy} disabled={busy}
title="Forget this" 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" 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"
> >
<Trash2 className="h-[15px] w-[15px]" strokeWidth={1.8} /> <Trash2 className="h-[15px] w-[15px]" strokeWidth={1.8} />
@@ -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 // closeDrawer=true so the editor doesn't strand on a deleted/confirmed memory
// (review M). // (review M).
const forget = (m: Memory, closeDrawer = false) => 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) => 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 = () => { const saveCorrection = () => {
if (!selected) return; if (!selected) return;
if (draft === selected.content) { setSelected(null); 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); }; const openDetail = (m: Memory) => { setSelected(m); setDraft(m.content); };
@@ -731,7 +723,7 @@ export default function MemoryTrustManage({ mind, workspaceId, onToast, onWhy, o
open={!!selected} open={!!selected}
onOpenChange={(o) => { if (!o) setSelected(null); }} onOpenChange={(o) => { if (!o) setSelected(null); }}
title={selected?.title ?? 'Memory'} title={selected?.title ?? 'Memory'}
subtitle={selected ? `M-${selected.id} · ${selected.scope}` : undefined} subtitle={selected ? `${memoryLabel(selected.id)} · ${selected.scope}` : undefined}
footer={selected ? ( footer={selected ? (
<div className="flex w-full items-center gap-2"> <div className="flex w-full items-center gap-2">
<button <button

View File

@@ -2,6 +2,7 @@ import { useState, useEffect, type ReactNode } from 'react';
import { Loader2, Info, Sparkles } from 'lucide-react'; import { Loader2, Info, Sparkles } from 'lucide-react';
import { adapter } from '@/lib/adapter'; import { adapter } from '@/lib/adapter';
import type { MemoryTrace } from '@/lib/types'; import type { MemoryTrace } from '@/lib/types';
import { memoryLabel } from './memory-label';
import { HexAvatar, DotLive, type WarmTone } from '../../warm'; import { HexAvatar, DotLive, type WarmTone } from '../../warm';
/** /**
@@ -16,8 +17,6 @@ import { HexAvatar, DotLive, type WarmTone } from '../../warm';
*/ */
interface MemoryTrustWhyProps { interface MemoryTrustWhyProps {
mind: 'personal' | 'workspace';
workspaceId?: string;
/** The memory whose trace to explain (set from the Manage view). Null → pick-one prompt. */ /** The memory whose trace to explain (set from the Manage view). Null → pick-one prompt. */
memoryId: string | null; memoryId: string | null;
onToast: (msg: string) => void; onToast: (msg: string) => void;
@@ -67,8 +66,7 @@ function Shell({ children }: { children: ReactNode }) {
); );
} }
export default function MemoryTrustWhy({ mind, workspaceId, memoryId, onToast, onCorrect, onForget }: MemoryTrustWhyProps) { export default function MemoryTrustWhy({ memoryId, onToast, onCorrect, onForget }: MemoryTrustWhyProps) {
const wsParam = mind === 'workspace' ? workspaceId : undefined;
const [trace, setTrace] = useState<MemoryTrace | null>(null); const [trace, setTrace] = useState<MemoryTrace | null>(null);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
@@ -77,12 +75,12 @@ export default function MemoryTrustWhy({ mind, workspaceId, memoryId, onToast, o
if (!memoryId) { setTrace(null); setError(null); setLoading(false); return; } if (!memoryId) { setTrace(null); setError(null); setLoading(false); return; }
let alive = true; let alive = true;
setLoading(true); setError(null); setTrace(null); setLoading(true); setError(null); setTrace(null);
adapter.getMemoryTrace(memoryId, wsParam, mind) adapter.getMemoryTrace(memoryId)
.then((r) => { if (alive) setTrace(r.trace); }) .then((r) => { if (alive) setTrace(r.trace); })
.catch((e) => { if (alive) setError(e instanceof Error ? e.message : 'Failed to load trace'); }) .catch((e) => { if (alive) setError(e instanceof Error ? e.message : 'Failed to load trace'); })
.finally(() => { if (alive) setLoading(false); }); .finally(() => { if (alive) setLoading(false); });
return () => { alive = false; }; return () => { alive = false; };
}, [memoryId, wsParam, mind]); }, [memoryId]);
// No memory chosen yet — point the user at the Manage view. // No memory chosen yet — point the user at the Manage view.
if (!memoryId) { if (!memoryId) {
@@ -102,7 +100,7 @@ export default function MemoryTrustWhy({ mind, workspaceId, memoryId, onToast, o
return ( return (
<Shell> <Shell>
<Loader2 className="mx-auto mb-2 h-6 w-6 animate-spin text-[var(--text-dim)]" /> <Loader2 className="mx-auto mb-2 h-6 w-6 animate-spin text-[var(--text-dim)]" />
<p className="text-[13px] text-[var(--text-muted)]">Resolving the trace for M-{memoryId}…</p> <p className="text-[13px] text-[var(--text-muted)]">Resolving the trace for {memoryLabel(memoryId)}…</p>
</Shell> </Shell>
); );
} }
@@ -120,7 +118,7 @@ export default function MemoryTrustWhy({ mind, workspaceId, memoryId, onToast, o
return ( return (
<Shell> <Shell>
<Info className="mx-auto mb-3 h-6 w-6 text-[var(--text-dim)]" strokeWidth={1.8} /> <Info className="mx-auto mb-3 h-6 w-6 text-[var(--text-dim)]" strokeWidth={1.8} />
<p className="text-[14px] text-[var(--text-2)]">No trace is linked to M-{memoryId}.</p> <p className="text-[14px] text-[var(--text-2)]">No trace is linked to {memoryLabel(memoryId)}.</p>
<p className="mx-auto mt-1.5 max-w-[52ch] text-[12.5px] leading-relaxed text-[var(--text-muted)]"> <p className="mx-auto mt-1.5 max-w-[52ch] text-[12.5px] leading-relaxed text-[var(--text-muted)]">
This memory was added manually, imported, or written before traces were linked — so there&rsquo;s no This memory was added manually, imported, or written before traces were linked — so there&rsquo;s no
recorded decision behind it. Memories the agent writes from here on will carry their trace. recorded decision behind it. Memories the agent writes from here on will carry their trace.
@@ -145,7 +143,7 @@ export default function MemoryTrustWhy({ mind, workspaceId, memoryId, onToast, o
<div className="flex items-center gap-3 border-b border-[var(--line-soft)] px-5 py-4"> <div className="flex items-center gap-3 border-b border-[var(--line-soft)] px-5 py-4">
<HexAvatar label="Trace" size={36} /> <HexAvatar label="Trace" size={36} />
<div className="min-w-0 flex-1"> <div className="min-w-0 flex-1">
<p className="truncate text-[15px] font-[650] text-[var(--text)]">Why memory M-{memoryId} is here</p> <p className="truncate text-[15px] font-[650] text-[var(--text)]">Why memory {memoryLabel(memoryId)} is here</p>
<p className="truncate text-[12px] text-[var(--text-muted)]"> <p className="truncate text-[12px] text-[var(--text-muted)]">
{[trace.model, OUTCOME_LABEL[trace.outcome], trace.sessionId ? `session ${trace.sessionId.slice(0, 8)}` : null].filter(Boolean).join(' · ')} {[trace.model, OUTCOME_LABEL[trace.outcome], trace.sessionId ? `session ${trace.sessionId.slice(0, 8)}` : null].filter(Boolean).join(' · ')}
</p> </p>
@@ -162,7 +160,7 @@ export default function MemoryTrustWhy({ mind, workspaceId, memoryId, onToast, o
<div className="flex flex-wrap gap-2 border-t border-[var(--line-soft)] bg-[var(--surface)] px-5 py-4"> <div className="flex flex-wrap gap-2 border-t border-[var(--line-soft)] bg-[var(--surface)] px-5 py-4">
<button <button
type="button" type="button"
onClick={() => onToast(`Kept M-${memoryId} — looks right`)} onClick={() => onToast(`Kept ${memoryLabel(memoryId)} — looks right`)}
className="rounded-[9px] bg-[var(--honey)] px-3.5 py-2 text-[12.5px] font-[650] text-[#1a1407]" className="rounded-[9px] bg-[var(--honey)] px-3.5 py-2 text-[12.5px] font-[650] text-[#1a1407]"
> >
Looks right Looks right
@@ -179,7 +177,7 @@ export default function MemoryTrustWhy({ mind, workspaceId, memoryId, onToast, o
onClick={() => onForget(memoryId)} onClick={() => onForget(memoryId)}
className="rounded-[9px] border border-[color-mix(in_srgb,var(--risk)_35%,transparent)] bg-transparent px-3.5 py-2 text-[12.5px] font-[650] text-[var(--risk)]" className="rounded-[9px] border border-[color-mix(in_srgb,var(--risk)_35%,transparent)] bg-transparent px-3.5 py-2 text-[12.5px] font-[650] text-[var(--risk)]"
> >
Forget M-{memoryId} &amp; redo Forget {memoryLabel(memoryId)} &amp; redo
</button> </button>
<span className="ml-auto inline-flex items-center gap-1.5 text-[11.5px] text-[var(--text-dim)]"> <span className="ml-auto inline-flex items-center gap-1.5 text-[11.5px] text-[var(--text-dim)]">
<Sparkles className="h-3.5 w-3.5 text-[var(--intel)]" strokeWidth={1.8} /> real execution trace <Sparkles className="h-3.5 w-3.5 text-[var(--intel)]" strokeWidth={1.8} /> real execution trace

View File

@@ -1,5 +1,5 @@
import { useState } from 'react'; 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 { AnimatePresence } from 'framer-motion';
import { Input } from '@/components/ui/input'; import { Input } from '@/components/ui/input';
import { DATE_LOCALE } from '@/lib/date-locale'; 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). // Lucide, not emoji — one icon language across the chrome (2026-07-06 P2).
const frameTypeIcons: Record<string, LucideIcon> = { const frameTypeIcons: Record<MemoryFrame['type'], LucideIcon> = {
fact: ClipboardList, event: Calendar, insight: Lightbulb, decision: Scale, task: CheckSquare, entity: Tag, 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']; 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 (!onTypeFiltersChange) return;
if (typeFilters.includes(type)) { if (typeFilters.includes(type)) {
onTypeFiltersChange(typeFilters.filter(t => t !== type)); onTypeFiltersChange(typeFilters.filter(t => t !== type));
@@ -163,10 +163,7 @@ const TimelineTab = ({
<div className="flex-1 overflow-auto p-1.5 space-y-0.5"> <div className="flex-1 overflow-auto p-1.5 space-y-0.5">
{frames.map(f => ( {frames.map(f => (
<button <button
// Frame ids collide across minds (separate per-mind SQLite key={f.id}
// autoincrements) and the legacy frames API merges both — the id
// alone duplicated keys on real data (P3 live smoke, key `36`).
key={`${f.workspaceId ?? 'personal'}:${f.id}`}
onClick={() => { onClick={() => {
onSelectFrame(f); onSelectFrame(f);
if (onContextRail) onContextRail({ type: 'frame', id: String(f.id), label: f.content?.split('\n')[0]?.slice(0, 60) ?? 'Frame' }); if (onContextRail) onContextRail({ type: 'frame', id: String(f.id), label: f.content?.split('\n')[0]?.slice(0, 60) ?? 'Frame' });

View File

@@ -1,172 +0,0 @@
import { useState, useEffect } from 'react';
import { RefreshCw, Activity, Clock, Zap, TrendingDown, TrendingUp, Loader2, HelpCircle } from 'lucide-react';
import { adapter } from '@/lib/adapter';
import { HintTooltip } from '@/components/ui/hint-tooltip';
interface WeaverStatus {
personalMind: { lastConsolidation: string | null; lastDecay: string | null; timerActive: boolean };
workspaces: Array<{ id: string; lastConsolidation: string | null; timerActive: boolean }>;
checkedAt: string;
}
interface TriggerResult {
ok: boolean;
results: Array<{ target: string; framesConsolidated: number; framesDecayed: number; framesStrengthened: number }>;
triggeredAt: string;
}
function timeAgo(iso: string | null): string {
if (!iso) return 'Never';
const diff = Date.now() - new Date(iso).getTime();
const mins = Math.floor(diff / 60000);
if (mins < 1) return 'Just now';
if (mins < 60) return `${mins}m ago`;
const hours = Math.floor(mins / 60);
if (hours < 24) return `${hours}h ago`;
return `${Math.floor(hours / 24)}d ago`;
}
export default function WeaverPanel() {
const [status, setStatus] = useState<WeaverStatus | null>(null);
const [loading, setLoading] = useState(true);
const [triggering, setTriggering] = useState(false);
const [lastResult, setLastResult] = useState<TriggerResult | null>(null);
const [wsNames, setWsNames] = useState<Record<string, string>>({});
const fetchStatus = async () => {
try {
const data = await adapter.getWeaverStatus();
setStatus(data as unknown as WeaverStatus);
} catch { /* offline */ }
setLoading(false);
};
useEffect(() => {
fetchStatus();
adapter.getWorkspaces().then(wsList => {
const map: Record<string, string> = {};
for (const w of wsList) map[w.id] = w.name;
setWsNames(map);
}).catch(() => {});
}, []);
const triggerConsolidation = async () => {
setTriggering(true);
try {
const res = await fetch(`${adapter.getServerUrl()}/api/weaver/trigger`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{}' });
const data = await res.json();
setLastResult(data);
fetchStatus();
} catch { /* offline */ }
setTriggering(false);
};
if (loading) {
return (
<div className="flex items-center justify-center h-full text-muted-foreground">
<Loader2 className="w-4 h-4 animate-spin mr-2" /> Loading weaver status...
</div>
);
}
if (!status) {
return (
<div className="flex items-center justify-center h-full text-muted-foreground text-sm">
Weaver unavailable — connect to backend
</div>
);
}
const workspaces = status.workspaces ?? [];
const personalMind = status.personalMind ?? { lastConsolidation: null, lastDecay: null, timerActive: false };
const activeWorkspaces = workspaces.filter(w => w.timerActive).length;
return (
<div className="p-4 space-y-4 overflow-y-auto h-full">
<div className="flex items-center justify-between">
<h3 className="text-sm font-display font-semibold text-foreground flex items-center gap-2">
<Activity className="w-4 h-4 text-honey" />
Memory Weaver
</h3>
<button
onClick={triggerConsolidation}
disabled={triggering}
className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-display font-medium bg-primary/10 text-honey hover:bg-primary/20 transition-colors disabled:opacity-50"
>
{triggering ? <Loader2 className="w-3 h-3 animate-spin" /> : <Zap className="w-3 h-3" />}
{triggering ? 'Running...' : 'Run Now'}
</button>
</div>
{/* F24: plain-language explainer so the panel isn't opaque jargon. */}
<p className="text-xs text-muted-foreground leading-relaxed">
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. <span className="text-foreground/80">Run Now</span> does that pass immediately instead of waiting for the next scheduled sweep.
</p>
<div className="grid grid-cols-3 gap-3">
<div className="rounded-xl border border-border/30 p-3">
<div className="flex items-center gap-1.5 text-muted-foreground mb-1">
<Clock className="w-3 h-3" />
<span className="text-[10px] uppercase tracking-wide">Last Consolidation</span>
</div>
<p className="text-sm font-medium text-foreground">{timeAgo(personalMind.lastConsolidation)}</p>
</div>
<div className="rounded-xl border border-border/30 p-3">
<div className="flex items-center gap-1.5 text-muted-foreground mb-1">
<TrendingDown className="w-3 h-3" />
<span className="text-[10px] uppercase tracking-wide">Last Decay</span>
<HintTooltip content="Decay gradually lowers the weight of memories that haven't been reinforced recently, so stale facts surface less. Nothing is deleted — it just ranks lower.">
<button type="button" aria-label="What is decay?" className="text-muted-foreground/70 hover:text-muted-foreground">
<HelpCircle className="w-3 h-3" />
</button>
</HintTooltip>
</div>
<p className="text-sm font-medium text-foreground">{timeAgo(personalMind.lastDecay)}</p>
</div>
<div className="rounded-xl border border-border/30 p-3">
<div className="flex items-center gap-1.5 text-muted-foreground mb-1">
<RefreshCw className="w-3 h-3" />
<span className="text-[10px] uppercase tracking-wide">Active Timers</span>
</div>
<p className="text-sm font-medium text-foreground">
{personalMind.timerActive ? 1 : 0} personal + {activeWorkspaces} workspace{activeWorkspaces !== 1 ? 's' : ''}
</p>
</div>
</div>
{workspaces.length > 0 && (
<div>
<h4 className="text-xs font-display font-medium text-muted-foreground mb-2 uppercase tracking-wide">Workspace Health</h4>
<div className="space-y-1.5">
{workspaces.map(ws => (
<div key={ws.id} className="flex items-center justify-between rounded-lg border border-border/20 px-3 py-2">
<span className="text-xs text-foreground truncate max-w-[60%]">{wsNames[ws.id] ?? ws.id}</span>
<div className="flex items-center gap-2">
<span className="text-[10px] text-muted-foreground">{timeAgo(ws.lastConsolidation)}</span>
<span className={`w-1.5 h-1.5 rounded-full ${ws.timerActive ? 'bg-emerald-400' : 'bg-muted-foreground/30'}`} />
</div>
</div>
))}
</div>
</div>
)}
{lastResult && (
<div className="rounded-xl border border-primary/20 bg-primary/5 p-3">
<h4 className="text-xs font-display font-medium text-honey mb-2 flex items-center gap-1.5">
<TrendingUp className="w-3 h-3" /> Last Run Results
</h4>
{lastResult.results.map(r => (
<div key={r.target} className="flex items-center gap-3 text-xs text-foreground">
<span className="text-muted-foreground truncate">{wsNames[r.target] ?? r.target}</span>
<span className="text-emerald-400">+{r.framesConsolidated} consolidated</span>
<span className="text-amber-400">{r.framesDecayed} decayed</span>
<span className="text-honey">{r.framesStrengthened} strengthened</span>
</div>
))}
</div>
)}
</div>
);
}

View File

@@ -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)}`;
}

View File

@@ -1,4 +1,3 @@
import { Eye } from 'lucide-react';
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
import { EvidenceChip } from './evidence-chip'; import { EvidenceChip } from './evidence-chip';
@@ -13,22 +12,10 @@ interface EvidencePanelProps {
sourceId?: string | null; sourceId?: string | null;
sourceUrl?: string | null; sourceUrl?: string | null;
evidence?: string[]; 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; 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; const hasEvidence = Array.isArray(evidence) && evidence.length > 0;
if (!source && !sourceId && !sourceUrl && !hasEvidence) return null; if (!source && !sourceId && !sourceUrl && !hasEvidence) return null;
@@ -42,20 +29,6 @@ export function EvidencePanel({ source, sourceId, sourceUrl, evidence, onViewOri
<div className="flex flex-wrap gap-1.5"> <div className="flex flex-wrap gap-1.5">
{source && <EvidenceChip label={`source: ${source}`} />} {source && <EvidenceChip label={`source: ${source}`} />}
{sourceId && <EvidenceChip label={`id: ${sourceId}`} />} {sourceId && <EvidenceChip label={`id: ${sourceId}`} />}
{hasOriginalSource && onViewOriginalSource && (
<button
type="button"
onClick={onViewOriginalSource}
aria-label={expanded ? 'Hide original source' : 'View original source'}
aria-expanded={!!expanded}
aria-busy={busy || undefined}
disabled={busy}
title="View original source"
className="inline-flex items-center gap-1 rounded-md border border-border bg-muted/40 px-2 py-0.5 text-[11px] text-muted-foreground hover:bg-muted hover:text-foreground transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
>
<Eye className="w-3 h-3" /> View original
</button>
)}
{sourceUrl && <EvidenceChip label={sourceUrl} title={sourceUrl} onClick={openSource} />} {sourceUrl && <EvidenceChip label={sourceUrl} title={sourceUrl} onClick={openSource} />}
</div> </div>
{hasEvidence && ( {hasEvidence && (

View File

@@ -21,8 +21,9 @@ export const useMemory = (workspaceId: string | null) => {
if (!workspaceId) return; if (!workspaceId) return;
setLoading(true); setLoading(true);
try { try {
// Search covers what the list shows: personal memory plus this workspace's.
const data = filters.searchQuery const data = filters.searchQuery
? await adapter.searchMemory(filters.searchQuery, workspaceId) ? await adapter.searchMemory(filters.searchQuery, 'all', workspaceId)
: await adapter.getMemoryFrames(workspaceId); : await adapter.getMemoryFrames(workspaceId);
setFrames(data); setFrames(data);
setError(null); setError(null);
@@ -54,15 +55,6 @@ export const useMemory = (workspaceId: string | null) => {
setFrames(prev => prev.map(f => f.id === id ? updated : f)); 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) => { const deleteFrame = useCallback(async (id: string) => {
await adapter.deleteMemoryFrame(id); await adapter.deleteMemoryFrame(id);
setFrames(prev => prev.filter(f => f.id !== id)); setFrames(prev => prev.filter(f => f.id !== id));
@@ -78,7 +70,7 @@ export const useMemory = (workspaceId: string | null) => {
return { return {
frames: filteredFrames, selectedFrame, setSelectedFrame, frames: filteredFrames, selectedFrame, setSelectedFrame,
loading, error, filters, setFilters, 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 }, stats: { total: frames.length, filtered: filteredFrames.length, entities: entityCount, relations: relationCount },
}; };
}; };

View File

@@ -64,7 +64,7 @@ describe('adapter isTauri() branch routing', () => {
}); });
await adapter.addMemoryFrame({ await adapter.addMemoryFrame({
type: 'insight', type: 'fact',
title: 'test', title: 'test',
content: 'saved', content: 'saved',
importance: 3, // numeric → 'high' via IMPORTANCE_NUM_TO_STRING importance: 3, // numeric → 'high' via IMPORTANCE_NUM_TO_STRING

View File

@@ -27,7 +27,7 @@ import type {
WorkspaceStateView, WorkspaceActivityEvent, WorkspaceTask, WorkspaceStateView, WorkspaceActivityEvent, WorkspaceTask,
Artifact, RelatedSearchResult, Artifact, RelatedSearchResult,
Agent, AgentTrace, Automation, AutomationLog, EngineStatus, PendingApprovalItem, Agent, AgentTrace, Automation, AutomationLog, EngineStatus, PendingApprovalItem,
MemoryTrace, MemoryTrace, MemoryCapabilitiesResponse,
} from './types'; } from './types';
import type { import type {
Command, CommandResult, WorkspaceType, Command, CommandResult, WorkspaceType,
@@ -215,13 +215,13 @@ function unwrapArray<T>(data: any): T[] {
return []; return [];
} }
/** Map backend frameType codes to frontend type names */ /** Memory kinds of the memory contract; anything else reads as a fact. */
const FRAME_TYPE_MAP: Record<string, string> = { const MEMORY_FRAME_KINDS: ReadonlySet<string> = new Set<MemoryFrame['type']>([
I: 'insight', F: 'fact', E: 'event', D: 'decision', T: 'task', N: 'entity', 'fact', 'event', 'preference', 'profile', 'decision', 'summary', 'note',
insight: 'insight', fact: 'fact', event: 'event', decision: 'decision', task: 'task', entity: 'entity', ]);
}; /** Contract importance (and the Tauri command's low/high) on the 1-4 scale. */
const IMPORTANCE_MAP: Record<string, number> = { const IMPORTANCE_MAP: Record<string, number> = {
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. */ /** Normalize a backend cron schedule row to the frontend CronJob shape. */
@@ -242,23 +242,23 @@ function normalizeCronJob(raw: Record<string, unknown>): 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 { function normalizeFrame(raw: any): MemoryFrame {
const content = raw.content ?? ''; const content = raw.content ?? '';
const kind = raw.kind ?? raw.type;
return { return {
id: String(raw.id), 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), title: content.split('\n')[0].slice(0, 80),
content, content,
importance: typeof raw.importance === 'number' ? raw.importance : (IMPORTANCE_MAP[raw.importance] ?? 2), importance: typeof raw.importance === 'number' ? raw.importance : (IMPORTANCE_MAP[raw.importance] ?? 2),
timestamp: raw.timestamp ?? raw.created_at ?? '', timestamp: raw.timestamp ?? raw.created_at ?? '',
workspaceId: raw.mind ?? raw.workspaceId ?? '', workspaceId: raw.workspaceId ?? '',
metadata: { metadata: {
source: raw.source, source: raw.source,
gop: raw.gop, mind: raw.mind,
accessCount: raw.accessCount,
// Lifecycle status — consumers (e.g. briefing highlights) must keep // 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, status: raw.status ?? raw.metadata?.status,
}, },
}; };
@@ -1187,7 +1187,7 @@ class LocalAdapter {
// --- Memory --- // --- Memory ---
async getMemoryFrames(workspaceId: string, limit = 50): Promise<MemoryFrame[]> { async getMemoryFrames(workspaceId: string, limit = 50): Promise<MemoryFrame[]> {
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); return unwrapArray(await res.json()).map(normalizeFrame);
} }
@@ -1220,36 +1220,50 @@ class LocalAdapter {
await this.fetch(`/api/memory/frames/${id}`, { method: 'DELETE' }); await this.fetch(`/api/memory/frames/${id}`, { method: 'DELETE' });
} }
async incrementFrameAccess(id: string, workspaceId?: string): Promise<{ accessCount: number }> { /**
const qs = workspaceId ? `?workspace=${encodeURIComponent(workspaceId)}` : ''; * Ranked memory search. `scope`: 'personal', 'workspace' (the given
const res = await this.fetch(`/api/memory/frames/${id}/access${qs}`, { method: 'PATCH' }); * workspace), 'all' (personal plus the given workspace, the default) or
const body = await res.json() as { accessCount?: number }; * 'global' (personal plus every workspace).
return { accessCount: typeof body.accessCount === 'number' ? body.accessCount : 0 }; */
} async searchMemory(
query: string,
async searchMemory(query: string, scope?: string): Promise<MemoryFrame[]> { scope?: 'all' | 'personal' | 'workspace' | 'global',
workspaceId?: string,
): Promise<MemoryFrame[]> {
// CC Sesija A §2.2 — Tauri IPC path for desktop builds. // CC Sesija A §2.2 — Tauri IPC path for desktop builds.
if (isTauri()) { if (isTauri()) {
const resp = await tauriRecallMemory({ const resp = await tauriRecallMemory({ query, scope, ...(workspaceId && { workspaceId }) });
query,
scope: scope as 'all' | 'personal' | 'workspace' | 'global' | undefined,
});
return resp.results.map((r) => normalizeFrame(r as Record<string, any>)); return resp.results.map((r) => normalizeFrame(r as Record<string, any>));
} }
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); return unwrapArray(await res.json()).map(normalizeFrame);
} }
/** What the memory store supports, and whether background fact extraction is on. */
async getMemoryCapabilities(): Promise<MemoryCapabilitiesResponse> {
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<MemoryCapabilitiesResponse> {
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) --- // --- Memory Center (UX-Refactor Phase 2 — shared Memory entity, S04) ---
// These hit the new bare /api/memory* routes (memory-center.ts) and return the // These hit the bare /api/memory* routes (memory-center.ts) and return the
// shared `Memory` shape (kind/confidence/scope/status/evidence/...), distinct // shared `Memory` shape. Memory ids are unique across personal and workspace
// from the legacy frame methods above. HTTP path works in web + desktop (the // memory, so the single-memory calls need no scope.
// sidecar is bundled), so no Tauri IPC branch is needed.
async listMemories(opts: { async listMemories(opts: {
workspaceId?: string; kind?: string; status?: string; scope?: string; workspaceId?: string; kind?: string; status?: string; q?: string; limit?: number;
q?: string; minConfidence?: number; limit?: number; /** Read one scope; omit to merge personal memory and the workspace's. */
/** P3/D2 two-mind split — select a single mind; omit for the legacy merge. */
mind?: 'personal' | 'workspace'; mind?: 'personal' | 'workspace';
} = {}): Promise<Memory[]> { } = {}): Promise<Memory[]> {
const p = new URLSearchParams(); const p = new URLSearchParams();
@@ -1257,9 +1271,7 @@ class LocalAdapter {
if (opts.workspaceId) p.set('workspace', opts.workspaceId); if (opts.workspaceId) p.set('workspace', opts.workspaceId);
if (opts.kind) p.set('kind', opts.kind); if (opts.kind) p.set('kind', opts.kind);
if (opts.status) p.set('status', opts.status); 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 (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)); if (typeof opts.limit === 'number') p.set('limit', String(opts.limit));
const qs = p.toString(); const qs = p.toString();
const res = await this.fetch(`/api/memory${qs ? `?${qs}` : ''}`); const res = await this.fetch(`/api/memory${qs ? `?${qs}` : ''}`);
@@ -1271,31 +1283,18 @@ class LocalAdapter {
return body.results ?? []; return body.results ?? [];
} }
/** Query string for the single-memory routes. `mind` makes server-side store async getMemory(id: string): Promise<Memory | null> {
* 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<Memory | null> {
// P1b D3: fetchRaw preserves the documented 404→null contract (the // P1b D3: fetchRaw preserves the documented 404→null contract (the
// throwing fetch would reject before the status check). // 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.status === 404) return null;
if (!res.ok) throw new AdapterHttpError(res.status, res.statusText, await res.clone().json().catch(() => undefined)); if (!res.ok) throw new AdapterHttpError(res.status, res.statusText, await res.clone().json().catch(() => undefined));
return res.json(); return res.json();
} }
async createMemory(input: { async createMemory(input: {
content: string; kind?: string; scope?: string; tags?: string[]; content: string; kind?: string; tags?: string[];
importance?: string; title?: string; confidence?: number; workspaceId?: string; importance?: string; title?: string; workspaceId?: string;
}): Promise<Memory> { }): Promise<Memory> {
const res = await this.fetch('/api/memory', { method: 'POST', body: JSON.stringify(input) }); const res = await this.fetch('/api/memory', { method: 'POST', body: JSON.stringify(input) });
return res.json(); return res.json();
@@ -1303,105 +1302,55 @@ class LocalAdapter {
async patchMemory( async patchMemory(
id: string, id: string,
patch: { content?: string; importance?: string; kind?: string; scope?: string; tags?: string[]; status?: string; title?: string; evidence?: string[] }, patch: { content?: string; importance?: string; kind?: string; tags?: string[]; status?: 'active' | 'archived'; title?: string; evidence?: string[] },
workspaceId?: string,
mind?: 'personal' | 'workspace',
): Promise<Memory> { ): Promise<Memory> {
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(); return res.json();
} }
async archiveMemory(id: string, workspaceId?: string, mind?: 'personal' | 'workspace'): Promise<Memory> { /** Reversible archive: hidden from recall until unarchived. */
const res = await this.fetch(`/api/memory/${encodeURIComponent(id)}/archive${this.memoryScopeQs(workspaceId, mind)}`, { method: 'POST' }); async archiveMemory(id: string): Promise<Memory> {
const res = await this.fetch(`/api/memory/${encodeURIComponent(id)}/archive`, { method: 'POST' });
return res.json(); return res.json();
} }
/** Hard delete (A8) via the bare-id route — distinct from deleteMemoryFrame. */ /** Hard delete (A8) via the bare-id route — distinct from deleteMemoryFrame. */
async deleteMemoryById(id: string, workspaceId?: string, mind?: 'personal' | 'workspace'): Promise<void> { async deleteMemoryById(id: string): Promise<void> {
await this.fetch(`/api/memory/${encodeURIComponent(id)}${this.memoryScopeQs(workspaceId, mind)}`, { method: 'DELETE' }); await this.fetch(`/api/memory/${encodeURIComponent(id)}`, { method: 'DELETE' });
} }
/** PR3.5 Memory-Trust: clear the 'unreviewed' lifecycle state (status→active). */ /** PR3.5 Memory-Trust: confirm a memory extracted in the background (status→active). */
async confirmMemory(id: string, workspaceId?: string, mind?: 'personal' | 'workspace'): Promise<Memory> { async confirmMemory(id: string): Promise<Memory> {
const res = await this.fetch(`/api/memory/${encodeURIComponent(id)}/confirm${this.memoryScopeQs(workspaceId, mind)}`, { method: 'POST' }); const res = await this.fetch(`/api/memory/${encodeURIComponent(id)}/confirm`, { method: 'POST' });
return res.json(); return res.json();
} }
/** PR3.5 "Why did you do that?": resolve the execution trace that wrote a /** 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 * memory (via the metadata.trace_id backlink). Returns { trace: null } when
* the frame has no linked trace — the caller shows an honest empty state. */ * the memory has no linked trace — the caller shows an honest empty state. */
async getMemoryTrace(id: string, workspaceId?: string, mind?: 'personal' | 'workspace'): Promise<{ trace: MemoryTrace | null }> { async getMemoryTrace(id: string): Promise<{ trace: MemoryTrace | null }> {
const res = await this.fetch(`/api/memory/${encodeURIComponent(id)}/trace${this.memoryScopeQs(workspaceId, mind)}`); const res = await this.fetch(`/api/memory/${encodeURIComponent(id)}/trace`);
return res.json(); return res.json();
} }
/** #7 "View original source": resolve the immutable verbatim raw_archive row(s) /** Forget one memory ({ id }) or every memory saved from one chat session
* a memory was distilled from (via metadata.archiveUids — one frame can link * ({ sessionId }), in personal and workspace memory. */
* 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. */
async eraseMemory( async eraseMemory(
target: { frameId: string } | { source: string; sourceRef: string }, target: { id: string } | { sessionId: string },
opts: { reason?: string; workspaceId?: string; mind?: 'personal' | 'workspace' } = {}, opts: { reason?: string } = {},
): Promise<{ ): Promise<{ erased: boolean; deleted: number }> {
erased: boolean; const res = await this.fetch('/api/memory/erase', {
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)}`, {
method: 'POST', method: 'POST',
body: JSON.stringify({ ...target, reason: opts.reason }), body: JSON.stringify({ ...target, reason: opts.reason }),
}); });
return res.json(); return res.json();
} }
/** #7 sticky erasure — list the (source, sourceRef) subjects on the erased-subject /** Join memories of one scope into one; the originals are archived. */
* suppression list. A re-import of any of these is skipped, so an Art.17 erasure async mergeMemories(ids: string[], opts: { title?: string } = {}): Promise<Memory> {
* 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<Memory> {
const res = await this.fetch('/api/memory/merge', { const res = await this.fetch('/api/memory/merge', {
method: 'POST', 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(); return res.json();
} }
@@ -3089,28 +3038,6 @@ class LocalAdapter {
} catch { return { byType: {}, total: 0 }; } } 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 --- // --- Audit ---
async getAuditInstalls(): Promise<unknown[]> { async getAuditInstalls(): Promise<unknown[]> {
const res = await this.fetch('/api/audit/installs'); const res = await this.fetch('/api/audit/installs');
@@ -3620,17 +3547,7 @@ class LocalAdapter {
} }
} }
// --- Import --- // --- Harvest (hidden in v1, ADR-0002; the sidecar routes are removed) ---
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<void> {
await this.fetch('/api/import/commit', { method: 'POST', body: JSON.stringify({ data, source }) });
}
// --- Harvest ---
async harvestPreview(data: unknown, source: string): Promise<any> { async harvestPreview(data: unknown, source: string): Promise<any> {
const res = await this.fetch('/api/harvest/preview', { method: 'POST', body: JSON.stringify({ data, source }) }); const res = await this.fetch('/api/harvest/preview', { method: 'POST', body: JSON.stringify({ data, source }) });
return res.json(); return res.json();
@@ -3756,11 +3673,6 @@ class LocalAdapter {
return res.json(); return res.json();
} }
async getWikiWatermark(): Promise<any> {
const res = await this.fetch('/api/wiki/watermark');
return res.json();
}
/** /**
* M-12: export all compiled wiki pages to an Obsidian-shaped directory. * 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 * `outDir` must be an absolute path. Writes `_index.md` at the root and

View File

@@ -33,7 +33,7 @@ export interface ContextRailItem {
} }
export interface ContextRailAdapter { export interface ContextRailAdapter {
searchMemory: (query: string, scope?: string) => Promise<MemoryFrame[]>; searchMemory: (query: string, scope?: 'all' | 'personal' | 'workspace' | 'global', workspaceId?: string) => Promise<MemoryFrame[]>;
getKnowledgeGraph: ( getKnowledgeGraph: (
workspaceId: string, workspaceId: string,
scope?: 'current' | 'personal' | 'all', scope?: 'current' | 'personal' | 'all',
@@ -188,7 +188,7 @@ export async function fetchContextRailItems(
// Memory pass — every target type benefits from this. // Memory pass — every target type benefits from this.
try { 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)); for (const f of frames.slice(0, memoryLimit)) push(frameToItem(f));
} catch { } catch {
// Leave whatever we already gathered from the graph pass. // Leave whatever we already gathered from the graph pass.

View File

@@ -1,7 +1,7 @@
// Pure display mapping for the canonical PRD §15.2 `MemoryKind` vocabulary (B6). // 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 // `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 // Center filter chips / cards (S04) and (b) an onboarding Memory Review grouping
// bucket (S16). The server-side `ImportItemType → MemoryKind` normalization lives // bucket (S16). The server-side `ImportItemType → MemoryKind` normalization lives
// in the sidecar harvest layer (Phase 2B), NOT here — the build order forbids // 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<MemoryKind, MemoryKindMeta> = { export const MEMORY_KIND_META: Record<MemoryKind, MemoryKindMeta> = {
fact: { label: 'Fact', category: 'Memories' }, fact: { label: 'Fact', category: 'Memories' },
decision: { label: 'Decision', category: 'Decisions' }, event: { label: 'Event', category: 'Memories' },
task: { label: 'Task', category: 'Tasks' },
preference: { label: 'Preference', category: 'Memories' }, preference: { label: 'Preference', category: 'Memories' },
strategy: { label: 'Strategy', category: 'Projects' }, profile: { label: 'About you', category: 'Memories' },
learning: { label: 'Learning', category: 'Memories' }, decision: { label: 'Decision', category: 'Decisions' },
goal: { label: 'Goal', category: 'Projects' }, summary: { label: 'Summary', category: 'Projects' },
entity: { label: 'Entity', category: 'Memories' }, note: { label: 'Note', category: 'Tasks' },
}; };
export function memoryKindLabel(kind: MemoryKind): string { export function memoryKindLabel(kind: MemoryKind): string {

View File

@@ -1,11 +1,16 @@
/** /**
* Memory features the UI may show (ADR-0002). * Memory features the UI may show (ADR-0002).
* *
* v1 memory is facts, search and the user profile. The features below are * v1 memory is facts, search and the user profile. The knowledge graph follows
* hidden, not deleted: their screens stay in the code and every surface that * the server's memory capability map (`GET /api/memory/capabilities`), which
* offers one checks this map first. A later work package fills the map from * reports it unavailable in v1. History import, wiki, coding-agent hooks, Room
* the server's memory capability map, so read it only through this module. * 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 { export interface MemoryFeatures {
/** Knowledge graph (entities and relations). Deferred to a later release. */ /** Knowledge graph (entities and relations). Deferred to a later release. */
@@ -24,8 +29,8 @@ export interface MemoryFeatures {
export type MemoryFeature = keyof MemoryFeatures; export type MemoryFeature = keyof MemoryFeatures;
const MEMORY_FEATURES: Readonly<MemoryFeatures> = { /** Hidden in v1 (ADR-0002) regardless of the memory store. */
knowledgeGraph: false, const HIDDEN_IN_V1: Readonly<Record<Exclude<MemoryFeature, 'knowledgeGraph'>, false>> = {
importHistory: false, importHistory: false,
wiki: false, wiki: false,
agentHooks: false, agentHooks: false,
@@ -33,8 +38,14 @@ const MEMORY_FEATURES: Readonly<MemoryFeatures> = {
memoryMcp: false, memoryMcp: false,
}; };
let current: MemoryCapabilitiesResponse | null = null;
let pending: Promise<MemoryCapabilitiesResponse | null> | null = null;
const listeners = new Set<() => void>();
/** False until the server has reported the feature as available. */
export function hasMemoryFeature(feature: MemoryFeature): boolean { 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. */ /** 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]; const feature = MEMORY_VIEW_FEATURE[view];
return feature === undefined || hasMemoryFeature(feature); 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<MemoryCapabilitiesResponse | null> {
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;
}

View File

@@ -43,10 +43,10 @@ export interface RecallMemoryArgs {
/** /**
* Sidecar /api/memory/search returns `{ results, count }` where each result is a * 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<string, unknown>` here — the canonical * intentionally typed as `Record<string, unknown>` here — the canonical
* MemoryFrame shape is owned by adapter.ts which performs camelCase + frameType * MemoryFrame shape is owned by adapter.ts, which maps kind and importance.
* code mapping. Keep bindings raw to prevent two normalization paths drifting. * Keep bindings raw to prevent two normalization paths drifting.
*/ */
export interface RecallMemoryResponse { export interface RecallMemoryResponse {
results: Array<Record<string, unknown>>; results: Array<Record<string, unknown>>;

View File

@@ -491,7 +491,8 @@ export interface ApprovalRequest {
export interface MemoryFrame { export interface MemoryFrame {
id: string; id: string;
type: 'fact' | 'event' | 'insight' | 'decision' | 'task' | 'entity'; /** The memory's kind in the memory contract. */
type: MemoryKind;
title: string; title: string;
content: string; content: string;
importance: number; importance: number;
@@ -500,13 +501,18 @@ export interface MemoryFrame {
metadata?: Record<string, unknown>; metadata?: Record<string, unknown>;
} }
/** `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, * Memory Center FE view-model (S04) — the shared `Memory` entity (PRD §15.4)
* carrying kind/confidence/scope/source/evidence/status) plus FE-derived display * plus FE-derived display fields. The `MemoryFrame` above serves the
* fields. The legacy `MemoryFrame` above is kept for back-compat with existing * `/api/memory/search|frames` consumers (Timeline, recall toasts, briefing).
* `/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`.
*/ */
export interface Memory extends SharedMemory { export interface Memory extends SharedMemory {
/** FE-derived recall relevance for ranked lists (0-1); not persisted. */ /** FE-derived recall relevance for ranked lists (0-1); not persisted. */

View File

@@ -27,7 +27,7 @@ import { useShell } from '@/providers/ShellContext';
import { useMemory } from '@/hooks/useMemory'; import { useMemory } from '@/hooks/useMemory';
import { useKnowledgeGraph } from '@/hooks/useKnowledgeGraph'; import { useKnowledgeGraph } from '@/hooks/useKnowledgeGraph';
import { stashDeepLink } from '@/lib/app-deeplink'; import { stashDeepLink } from '@/lib/app-deeplink';
import { hasMemoryFeature, isMemoryViewAvailable } from '@/lib/memory-features'; import { hasMemoryFeature, isMemoryViewAvailable, useMemoryCapabilities } from '@/lib/memory-features';
const MemoryRoute = () => { const MemoryRoute = () => {
const { mindScope } = useParams(); const { mindScope } = useParams();
@@ -35,6 +35,8 @@ const MemoryRoute = () => {
const navigate = useNavigate(); const navigate = useNavigate();
const mind: MindScope = mindScope === 'workspace' ? 'workspace' : 'personal'; const mind: MindScope = mindScope === 'workspace' ? 'workspace' : 'personal';
// Re-render once the server's capability map arrives (graph visibility).
useMemoryCapabilities();
const tabParam = searchParams.get('tab'); const tabParam = searchParams.get('tab');
// PR3.5: 'trust' (screen 19) is the new default landing; ?tab= still selects // 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), // any view (incl. the legacy 'memories' list and the 6 secondary views),

View File

@@ -94,7 +94,6 @@ vi.mock('@/components/os/apps/memory/MemoryCenterTab', () => ({ default: () => <
vi.mock('@/components/os/apps/memory/TimelineTab', () => ({ default: () => <div data-testid="stub-timeline" /> })); vi.mock('@/components/os/apps/memory/TimelineTab', () => ({ default: () => <div data-testid="stub-timeline" /> }));
vi.mock('@/components/os/apps/memory/KnowledgeGraphViewer', () => ({ default: () => <div data-testid="stub-graph" /> })); vi.mock('@/components/os/apps/memory/KnowledgeGraphViewer', () => ({ default: () => <div data-testid="stub-graph" /> }));
vi.mock('@/components/os/apps/memory/HarvestTab', () => ({ default: () => <div data-testid="stub-harvest" /> })); vi.mock('@/components/os/apps/memory/HarvestTab', () => ({ default: () => <div data-testid="stub-harvest" /> }));
vi.mock('@/components/os/apps/memory/WeaverPanel', () => ({ default: () => <div data-testid="stub-weaver" /> }));
vi.mock('@/components/os/apps/memory/WikiTab', () => ({ default: () => <div data-testid="stub-wiki" /> })); vi.mock('@/components/os/apps/memory/WikiTab', () => ({ default: () => <div data-testid="stub-wiki" /> }));
vi.mock('@/components/os/apps/memory/ImportReminderBanner', () => ({ default: () => null })); vi.mock('@/components/os/apps/memory/ImportReminderBanner', () => ({ default: () => null }));

View File

@@ -10,10 +10,7 @@ const mocks = vi.hoisted(() => ({
archiveMemory: vi.fn(), archiveMemory: vi.fn(),
deleteMemoryById: vi.fn(), deleteMemoryById: vi.fn(),
mergeMemories: vi.fn(), mergeMemories: vi.fn(),
getMemoryOriginalSource: vi.fn(),
eraseMemory: vi.fn(), eraseMemory: vi.fn(),
listSuppression: vi.fn(),
allowReimport: vi.fn(),
}, },
})); }));
@@ -36,7 +33,7 @@ const memory: Memory = {
confidence: 91, confidence: 91,
tags: ['research'], tags: ['research'],
evidence: [], evidence: [],
hasOriginalSource: false, sessionId: null,
createdAt: '2026-07-08T08:00:00.000Z', createdAt: '2026-07-08T08:00:00.000Z',
updatedAt: '2026-07-08T09:00:00.000Z', updatedAt: '2026-07-08T09:00:00.000Z',
}; };
@@ -53,21 +50,7 @@ beforeEach(() => {
mocks.adapter.archiveMemory.mockResolvedValue({ ...memory, status: 'archived' }); mocks.adapter.archiveMemory.mockResolvedValue({ ...memory, status: 'archived' });
mocks.adapter.deleteMemoryById.mockResolvedValue(undefined); mocks.adapter.deleteMemoryById.mockResolvedValue(undefined);
mocks.adapter.mergeMemories.mockResolvedValue(memory); mocks.adapter.mergeMemories.mockResolvedValue(memory);
mocks.adapter.getMemoryOriginalSource.mockResolvedValue({ archiveRows: [] }); mocks.adapter.eraseMemory.mockResolvedValue({ erased: true, deleted: 3 });
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 });
}); });
afterEach(() => { 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-2');
expect(search.parentElement?.className).toContain('focus-within:ring-[var(--focus-ring)]'); expect(search.parentElement?.className).toContain('focus-within:ring-[var(--focus-ring)]');
const confidence = screen.getByRole('combobox', { name: /filter by confidence/i }); // v1 stores no confidence, so there is no confidence filter.
expect(confidence).toHaveAttribute('name', 'memoryConfidenceFilter'); expect(screen.queryByRole('combobox', { name: /filter by confidence/i })).toBeNull();
expect(confidence).toHaveAttribute('autocomplete', 'off');
expect(confidence.className).toContain('focus-visible:ring-2');
expect(confidence.className).toContain('focus-visible:ring-[var(--focus-ring)]');
for (const name of [/needs review/i, /active/i, /all kinds/i, /fact/i]) { 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'); 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')); 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); const confirmSpy = vi.spyOn(window, 'confirm').mockReturnValue(true);
renderMemoryCenter(); renderMemoryCenter();
fireEvent.click(await screen.findByLabelText('Research Note')); 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(confirmSpy).not.toHaveBeenCalled();
expect(mocks.adapter.eraseMemory).not.toHaveBeenCalled(); expect(mocks.adapter.eraseMemory).not.toHaveBeenCalled();
const modal = await screen.findByTestId('approval-modal'); const modal = await screen.findByTestId('approval-modal');
expect(modal).toHaveTextContent(/erase memory and derived data/i); expect(modal).toHaveTextContent(/erase everything remembered from this chat/i);
expect(modal).toHaveTextContent(/research note/i); expect(modal).toHaveTextContent(/transcript itself is kept/i);
expect(modal).toHaveTextContent(/cannot be undone/i); expect(modal).toHaveTextContent(/cannot be undone/i);
expect(modal).toHaveTextContent(/original source/i);
fireEvent.click(screen.getByTestId('approval-modal-approve')); fireEvent.click(screen.getByTestId('approval-modal-approve'));
await waitFor(() => expect(mocks.adapter.eraseMemory).toHaveBeenCalledWith( await waitFor(() => expect(mocks.adapter.eraseMemory).toHaveBeenCalledWith({ sessionId: 'chat-42' }));
{ frameId: 'memory-research-note' }, await screen.findByText(/erased 3 memories from that chat/i);
{ workspaceId: undefined, mind: 'personal' },
));
await screen.findByText(/erased "research note"/i);
}); });
it('asks in-app before allowing an erased source to be re-imported', async () => { it('no longer shows the erased-sources panel of the old harvest import', async () => {
const confirmSpy = vi.spyOn(window, 'confirm').mockReturnValue(true);
renderMemoryCenter(); renderMemoryCenter();
await screen.findByLabelText('Research Note');
fireEvent.click(await screen.findByRole('button', { name: /erased sources/i })); expect(screen.queryByRole('button', { name: /erased sources/i })).toBeNull();
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' },
));
}); });
}); });

View File

@@ -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 { describe, it, expect, vi, afterEach } from 'vitest';
import { render, screen, cleanup, waitFor } from '@testing-library/react'; import { render, screen, cleanup, waitFor, renderHook } from '@testing-library/react';
import { hasMemoryFeature, isMemoryViewAvailable, type MemoryFeature } from '@/lib/memory-features'; import {
hasMemoryFeature,
isMemoryViewAvailable,
loadMemoryCapabilities,
setMemoryCapabilities,
useMemoryCapabilities,
type MemoryFeature,
} from '@/lib/memory-features';
import type { MemoryCapabilitiesResponse } from '@/lib/types';
const mocks = vi.hoisted(() => ({ const mocks = vi.hoisted(() => ({
adapter: { adapter: {
@@ -11,9 +20,15 @@ const mocks = vi.hoisted(() => ({
getProfile: vi.fn(), getProfile: vi.fn(),
trackTelemetry: vi.fn(), trackTelemetry: vi.fn(),
scanClaudeCode: 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('@/lib/adapter', () => ({ adapter: mocks.adapter, default: vi.fn() }));
vi.mock('@/hooks/useOfflineStatus', () => ({ useOfflineStatus: () => false })); vi.mock('@/hooks/useOfflineStatus', () => ({ useOfflineStatus: () => false }));
vi.mock('@/lib/posthog', () => ({ captureOnboardingComplete: vi.fn() })); vi.mock('@/lib/posthog', () => ({ captureOnboardingComplete: vi.fn() }));
@@ -21,6 +36,7 @@ vi.mock('@/lib/posthog', () => ({ captureOnboardingComplete: vi.fn() }));
afterEach(() => { afterEach(() => {
cleanup(); cleanup();
vi.clearAllMocks(); vi.clearAllMocks();
setMemoryCapabilities(null);
}); });
describe('memory feature map (v1 defaults)', () => { 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', () => { 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); expect(isMemoryViewAvailable(view), view).toBe(true);
} }
for (const view of ['graph', 'harvest', 'wiki']) { 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', () => { describe('OnboardingWizard without history import', () => {
it('resumes a persisted import step on the template step and never scans Claude Code', async () => { it('resumes a persisted import step on the template step and never scans Claude Code', async () => {
mocks.adapter.connect.mockResolvedValue(undefined); mocks.adapter.connect.mockResolvedValue(undefined);

View File

@@ -82,7 +82,6 @@ vi.mock('@/components/os/apps/memory/MemoryCenterTab', () => ({
vi.mock('@/components/os/apps/memory/TimelineTab', () => ({ default: () => <div data-testid="stub-timeline" /> })); vi.mock('@/components/os/apps/memory/TimelineTab', () => ({ default: () => <div data-testid="stub-timeline" /> }));
vi.mock('@/components/os/apps/memory/KnowledgeGraphViewer', () => ({ default: () => <div data-testid="stub-graph" /> })); vi.mock('@/components/os/apps/memory/KnowledgeGraphViewer', () => ({ default: () => <div data-testid="stub-graph" /> }));
vi.mock('@/components/os/apps/memory/HarvestTab', () => ({ default: () => <div data-testid="stub-harvest" /> })); vi.mock('@/components/os/apps/memory/HarvestTab', () => ({ default: () => <div data-testid="stub-harvest" /> }));
vi.mock('@/components/os/apps/memory/WeaverPanel', () => ({ default: () => <div data-testid="stub-weaver" /> }));
vi.mock('@/components/os/apps/memory/WikiTab', () => ({ default: () => <div data-testid="stub-wiki" /> })); vi.mock('@/components/os/apps/memory/WikiTab', () => ({ default: () => <div data-testid="stub-wiki" /> }));
vi.mock('@/components/os/apps/memory/ImportReminderBanner', () => ({ default: () => null })); vi.mock('@/components/os/apps/memory/ImportReminderBanner', () => ({ default: () => null }));
@@ -160,7 +159,6 @@ describe('MemoryRoute + MemoryCenterApp URL wiring (P3/D2)', () => {
it.each([ it.each([
['timeline', 'stub-timeline'], ['timeline', 'stub-timeline'],
['harvest', 'stub-harvest'], ['harvest', 'stub-harvest'],
['weaver', 'stub-weaver'],
['wiki', 'stub-wiki'], ['wiki', 'stub-wiki'],
])('?tab=%s mounts its legacy view (capability preserved)', async (tabId, testId) => { ])('?tab=%s mounts its legacy view (capability preserved)', async (tabId, testId) => {
await renderRoute(`/memory?tab=${tabId}`); 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(); 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; features.enabled = false;
await renderRoute('/memory'); await renderRoute('/memory');
expect(screen.queryByRole('tab', { name: /graph/i })).toBeNull(); expect(screen.queryByRole('tab', { name: /graph/i })).toBeNull();
fireEvent.click(screen.getByTestId('memory-tab-advanced')); expect(screen.queryByTestId('memory-tab-advanced')).toBeNull();
const menu = screen.getByTestId('memory-tab-advanced-menu');
expect(menu).toHaveTextContent('Maintenance');
expect(menu).not.toHaveTextContent(/imports|wiki/i);
}); });
it('?tab=weaver still mounts Maintenance', async () => { it('the removed Maintenance view (?tab=weaver) falls back to the Trust default', async () => {
features.enabled = false; features.enabled = false;
await renderRoute('/memory?tab=weaver'); await renderRoute('/memory?tab=weaver');
expect(screen.getByTestId('stub-weaver')).toBeTruthy(); expect(screen.getByTestId('stub-trust')).toBeTruthy();
}); });
}); });

View File

@@ -92,7 +92,7 @@ describe('MemoryCenterTab two-mind parameterization (P3/D2)', () => {
expect(mocks.adapter.listMemories).not.toHaveBeenCalled(); 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.listMemories.mockResolvedValue([mem({ id: '1' }), mem({ id: '2', title: 'Second' })]);
mocks.adapter.mergeMemories.mockResolvedValue(mem({ id: '3' })); mocks.adapter.mergeMemories.mockResolvedValue(mem({ id: '3' }));
await renderTab({ mind: 'workspace', workspaceId: 'w1', consumeDeepLinks: false }); 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/)); fireEvent.click(screen.getByText(/Merge 2 memories/));
await waitFor(() => { 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.listMemories.mockResolvedValue([mem({ id: '9' })]);
mocks.adapter.archiveMemory.mockResolvedValue(mem({ id: '9', status: 'archived' })); mocks.adapter.archiveMemory.mockResolvedValue(mem({ id: '9', status: 'archived' }));
await renderTab({ mind: 'workspace', workspaceId: 'w1', consumeDeepLinks: false }); await renderTab({ mind: 'workspace', workspaceId: 'w1', consumeDeepLinks: false });
@@ -117,13 +117,11 @@ describe('MemoryCenterTab two-mind parameterization (P3/D2)', () => {
fireEvent.click(archiveBtn); fireEvent.click(archiveBtn);
await waitFor(() => { await waitFor(() => {
// mind rides along so server-side store resolution is STRICT (no expect(mocks.adapter.archiveMemory).toHaveBeenCalledWith('9');
// cross-mind fall-through on colliding ids — P3 review HIGH).
expect(mocks.adapter.archiveMemory).toHaveBeenCalledWith('9', 'w1', 'workspace');
}); });
}); });
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.listMemories.mockResolvedValue([mem({ id: '4', workspaceId: undefined, scope: 'personal' })]);
mocks.adapter.archiveMemory.mockResolvedValue(mem({ id: '4', status: 'archived' })); mocks.adapter.archiveMemory.mockResolvedValue(mem({ id: '4', status: 'archived' }));
await renderTab(); await renderTab();
@@ -133,7 +131,7 @@ describe('MemoryCenterTab two-mind parameterization (P3/D2)', () => {
fireEvent.click(await screen.findByText('Archive')); fireEvent.click(await screen.findByText('Archive'));
await waitFor(() => { await waitFor(() => {
expect(mocks.adapter.archiveMemory).toHaveBeenCalledWith('4', undefined, 'personal'); expect(mocks.adapter.archiveMemory).toHaveBeenCalledWith('4');
}); });
}); });

View File

@@ -110,7 +110,7 @@ describe('MemoryTrustManage stats + filters + actions (PR3.5 Phase B+C)', () =>
render(<MemoryTrustManage mind="personal" onToast={onToast} />); render(<MemoryTrustManage mind="personal" onToast={onToast} />);
await waitFor(() => expect(screen.getByText('⬡ M-5')).toBeTruthy()); await waitFor(() => expect(screen.getByText('⬡ M-5')).toBeTruthy());
fireEvent.click(screen.getByTitle('Forget this')); 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')); expect(onToast).toHaveBeenCalledWith(expect.stringContaining('Forgotten M-5'));
}); });
@@ -137,7 +137,7 @@ describe('MemoryTrustManage stats + filters + actions (PR3.5 Phase B+C)', () =>
render(<MemoryTrustManage mind="personal" onToast={onToast} />); render(<MemoryTrustManage mind="personal" onToast={onToast} />);
await waitFor(() => expect(screen.getByText('⬡ M-8')).toBeTruthy()); await waitFor(() => expect(screen.getByText('⬡ M-8')).toBeTruthy());
fireEvent.click(screen.getByTitle('Confirm this memory')); 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')); 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) })]); mocks.adapter.listMemories.mockResolvedValue([mem({ id: '9', createdAt: iso(1) })]);
render(<MemoryTrustManage mind="workspace" workspaceId="w1" onToast={() => {}} />); render(<MemoryTrustManage mind="workspace" workspaceId="w1" onToast={() => {}} />);
await waitFor(() => expect(screen.getByText('⬡ M-9')).toBeTruthy()); await waitFor(() => expect(screen.getByText('⬡ M-9')).toBeTruthy());
fireEvent.click(screen.getByTitle('Forget this')); fireEvent.click(screen.getByTitle('Forget this'));
await waitFor(() => expect(mocks.adapter.deleteMemoryById).toHaveBeenCalledWith('9', 'w1', 'workspace')); await waitFor(() => expect(mocks.adapter.deleteMemoryById).toHaveBeenCalledWith('9'));
}); });
}); });

View File

@@ -33,20 +33,20 @@ afterEach(() => { cleanup(); vi.clearAllMocks(); });
describe('MemoryTrustWhy (PR3.5 Phase D)', () => { describe('MemoryTrustWhy (PR3.5 Phase D)', () => {
it('with no memory selected, prompts the user to open one (no fetch)', () => { it('with no memory selected, prompts the user to open one (no fetch)', () => {
render(<MemoryTrustWhy mind="personal" memoryId={null} onToast={() => {}} onCorrect={() => {}} onForget={() => {}} />); render(<MemoryTrustWhy memoryId={null} onToast={() => {}} onCorrect={() => {}} onForget={() => {}} />);
expect(screen.getByText(/Open a memory.+trace to see why/i)).toBeTruthy(); expect(screen.getByText(/Open a memory.+trace to see why/i)).toBeTruthy();
expect(mocks.adapter.getMemoryTrace).not.toHaveBeenCalled(); expect(mocks.adapter.getMemoryTrace).not.toHaveBeenCalled();
}); });
it('renders an honest "no trace linked" state when the frame has no backlink', async () => { it('renders an honest "no trace linked" state when the frame has no backlink', async () => {
mocks.adapter.getMemoryTrace.mockResolvedValue({ trace: null }); mocks.adapter.getMemoryTrace.mockResolvedValue({ trace: null });
render(<MemoryTrustWhy mind="personal" memoryId="204" onToast={() => {}} onCorrect={() => {}} onForget={() => {}} />); render(<MemoryTrustWhy memoryId="204" onToast={() => {}} onCorrect={() => {}} onForget={() => {}} />);
await waitFor(() => expect(screen.getByText(/No trace is linked to M-204/)).toBeTruthy()); 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 () => { it('renders the real trace chain: goal → tool calls → acted + footer', async () => {
mocks.adapter.getMemoryTrace.mockResolvedValue({ trace: TRACE }); mocks.adapter.getMemoryTrace.mockResolvedValue({ trace: TRACE });
render(<MemoryTrustWhy mind="personal" memoryId="204" onToast={() => {}} onCorrect={() => {}} onForget={() => {}} />); render(<MemoryTrustWhy memoryId="204" onToast={() => {}} onCorrect={() => {}} onForget={() => {}} />);
await waitFor(() => expect(screen.getByText('Goal received')).toBeTruthy()); await waitFor(() => expect(screen.getByText('Goal received')).toBeTruthy());
expect(screen.getByText(/tighten the board narrative/)).toBeTruthy(); expect(screen.getByText(/tighten the board narrative/)).toBeTruthy();
expect(screen.getByText('Recalled memories')).toBeTruthy(); // auto_recall humanized 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 () => { it('footer actions fire the right callbacks', async () => {
mocks.adapter.getMemoryTrace.mockResolvedValue({ trace: TRACE }); mocks.adapter.getMemoryTrace.mockResolvedValue({ trace: TRACE });
const onToast = vi.fn(); const onCorrect = vi.fn(); const onForget = vi.fn(); const onToast = vi.fn(); const onCorrect = vi.fn(); const onForget = vi.fn();
render(<MemoryTrustWhy mind="personal" memoryId="204" onToast={onToast} onCorrect={onCorrect} onForget={onForget} />); render(<MemoryTrustWhy memoryId="204" onToast={onToast} onCorrect={onCorrect} onForget={onForget} />);
await waitFor(() => expect(screen.getByText('Looks right')).toBeTruthy()); await waitFor(() => expect(screen.getByText('Looks right')).toBeTruthy());
fireEvent.click(screen.getByText('Looks right')); fireEvent.click(screen.getByText('Looks right'));

View File

@@ -15,12 +15,20 @@ const mocks = vi.hoisted(() => ({
probeProvider: vi.fn(), probeProvider: vi.fn(),
toggleTelemetry: vi.fn(), toggleTelemetry: vi.fn(),
clearTelemetry: vi.fn(), clearTelemetry: vi.fn(),
getMemoryCapabilities: vi.fn(),
setMemoryExtraction: vi.fn(),
}, },
})); }));
vi.mock('@/lib/adapter', () => ({ adapter: mocks.adapter, default: vi.fn() })); vi.mock('@/lib/adapter', () => ({ adapter: mocks.adapter, default: vi.fn() }));
import SettingsApp from '@/components/os/apps/SettingsApp'; 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') { function renderSettings(initialEntry = '/settings') {
return render( return render(
@@ -56,6 +64,9 @@ beforeEach(() => {
mocks.adapter.probeProvider.mockResolvedValue({ configured: false, valid: false, verified: false }); mocks.adapter.probeProvider.mockResolvedValue({ configured: false, valid: false, verified: false });
mocks.adapter.toggleTelemetry.mockResolvedValue({ enabled: false }); mocks.adapter.toggleTelemetry.mockResolvedValue({ enabled: false });
mocks.adapter.clearTelemetry.mockResolvedValue({ ok: true }); 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(() => { afterEach(() => {
@@ -64,6 +75,26 @@ afterEach(() => {
}); });
describe('Settings trust flows', () => { 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 () => { it('labels high-traffic model and privacy controls for assistive tech', async () => {
renderSettings(); renderSettings();

View File

@@ -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-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-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-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 ## 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 `<dataDir>/workspaces/<id>/sessions/`. - 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 `<dataDir>/workspaces/<id>/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. - 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. - 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=<id>`; 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 `<dataDir>/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.