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);
if (!query) return;
let cancelled = false;
const scope = workspaceId ?? 'global';
adapter.searchMemory(query, scope).then(frames => {
const search = workspaceId
? adapter.searchMemory(query, 'all', workspaceId)
: adapter.searchMemory(query, 'global');
search.then(frames => {
if (cancelled) return;
const top = frames[0];
if (!top?.content) return;

View File

@@ -11,7 +11,6 @@ const mocks = vi.hoisted(() => ({
getCapabilitiesStatus: vi.fn(),
getAuditInstalls: vi.fn(),
getCostSummary: vi.fn(),
getWeaverStatus: vi.fn(),
getEventStats: vi.fn(),
},
}));
@@ -29,11 +28,6 @@ beforeEach(() => {
mocks.adapter.getCapabilitiesStatus.mockResolvedValue({});
mocks.adapter.getAuditInstalls.mockResolvedValue([]);
mocks.adapter.getCostSummary.mockResolvedValue({ totalTokens: 0, estimatedCost: 0 });
mocks.adapter.getWeaverStatus.mockResolvedValue({
personalMind: { lastConsolidation: null, lastDecay: null, timerActive: false },
workspaces: [],
checkedAt: new Date().toISOString(),
});
mocks.adapter.getEventStats.mockResolvedValue({ byType: {}, total: 0 });
});

View File

@@ -1,7 +1,6 @@
import { useState, useEffect } from 'react';
import { Activity, Server, DollarSign, Clock, Plug, RefreshCw, Timer, Brain, Shield, Network, FileText, ChevronDown, AlertTriangle } from 'lucide-react';
import { adapter } from '@/lib/adapter';
import { DATE_LOCALE } from '@/lib/date-locale';
import type { CronJob } from '@/lib/types';
import { describeCronExpr } from '@/lib/cron-presets';
@@ -15,11 +14,6 @@ interface CockpitData {
vault?: unknown;
capStatus?: unknown;
auditTrail?: unknown[];
weaver?: {
personalMind: { lastConsolidation: string | null; lastDecay: string | null; timerActive: boolean };
workspaces: Array<{ id: string; lastConsolidation: string | null; timerActive: boolean }>;
checkedAt: string;
};
eventStats?: { byType: Record<string, number>; total: number };
}
@@ -32,7 +26,7 @@ const CockpitApp = () => {
const refresh = async () => {
setLoading(true);
try {
const [health, cost, connectors, crons, vault, capStatus, audit, costSum, weaver, evStats] = await Promise.allSettled([
const [health, cost, connectors, crons, vault, capStatus, audit, costSum, evStats] = await Promise.allSettled([
adapter.getSystemHealth(),
adapter.getAgentCost(),
adapter.getConnectors(),
@@ -41,7 +35,6 @@ const CockpitApp = () => {
adapter.getCapabilitiesStatus(),
adapter.getAuditInstalls(),
adapter.getCostSummary(),
adapter.getWeaverStatus(),
adapter.getEventStats(),
]);
setData({
@@ -53,7 +46,6 @@ const CockpitApp = () => {
vault: vault.status === 'fulfilled' ? vault.value : undefined,
capStatus: capStatus.status === 'fulfilled' ? capStatus.value : undefined,
auditTrail: audit.status === 'fulfilled' ? audit.value : undefined,
weaver: weaver.status === 'fulfilled' ? weaver.value : undefined,
eventStats: evStats.status === 'fulfilled' ? evStats.value : undefined,
});
const allFailed = [health, cost, connectors, crons, vault, capStatus, audit].every(r => r.status === 'rejected');
@@ -149,24 +141,6 @@ const CockpitApp = () => {
</p>
</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 */}
{data.eventStats && data.eventStats.total > 0 && (
<div className="p-3 rounded-xl bg-secondary/30 border border-border/30">

View File

@@ -1,6 +1,6 @@
import { useState } from 'react';
import { motion, useReducedMotion } from 'framer-motion';
import { Brain, Clock, Network, Download, Activity, BookOpen, User, Briefcase, ShieldCheck, SlidersHorizontal, ChevronDown } from 'lucide-react';
import { Brain, Clock, Network, Download, BookOpen, User, Briefcase, ShieldCheck, SlidersHorizontal, ChevronDown } from 'lucide-react';
import type { KGNode, KGEdge } from '@/lib/types';
import { HintTooltip } from '@/components/ui/hint-tooltip';
import { SPRING } from '@/lib/motion/tokens';
@@ -8,13 +8,12 @@ import { cn } from '@/lib/utils';
import MemoryTrust from './MemoryTrust';
import KnowledgeGraphViewer from './memory/KnowledgeGraphViewer';
import HarvestTab from './memory/HarvestTab';
import WeaverPanel from './memory/WeaverPanel';
import WikiTab from './memory/WikiTab';
import MemoryCenterTab from './memory/MemoryCenterTab';
import TimelineTab, { type TimelineTabProps } from './memory/TimelineTab';
import ImportReminderBanner from './memory/ImportReminderBanner';
import { useOnboarding } from '@/hooks/useOnboarding';
import { hasMemoryFeature, isMemoryViewAvailable } from '@/lib/memory-features';
import { hasMemoryFeature, isMemoryViewAvailable, useMemoryCapabilities } from '@/lib/memory-features';
/**
* Memory Center (P3/D2) — the standalone memory surface (ArtifactCenterApp
@@ -23,9 +22,10 @@ import { hasMemoryFeature, isMemoryViewAvailable } from '@/lib/memory-features';
* Top-level structure is the ratified TWO-MIND SPLIT: "About you" reads the
* Personal Mind; "About this work" reads the active workspace's Mind. The
* per-mind list is MemoryCenterTab (reused, parameterized — D2). The legacy
* MemoryApp views (Timeline / Graph / Harvest / Weaver / Wiki)
* survive as secondary tabs after a divider — capability preserved, entry
* restructured. Mind pills render only on the Memories tab: the legacy tabs
* MemoryApp views (Timeline / Graph / Harvest / Wiki) survive as secondary
* tabs after a divider; Graph, Harvest and Wiki are hidden in v1 (ADR-0002).
* The Weaver maintenance view is gone: mem0 indexes on write and nothing
* consolidates in the background. Mind pills render only on the Memories tab: the legacy tabs
* keep their own scoping (Graph has a scope selector; Harvest writes to the
* personal mind by design).
*
@@ -35,12 +35,12 @@ import { hasMemoryFeature, isMemoryViewAvailable } from '@/lib/memory-features';
*/
export type MindScope = 'personal' | 'workspace';
export type MemoryView = 'trust' | 'memories' | 'timeline' | 'graph' | 'harvest' | 'weaver' | 'wiki';
export type MemoryView = 'trust' | 'memories' | 'timeline' | 'graph' | 'harvest' | 'wiki';
// PR3.5: 'trust' (screen 19) is the new PRIMARY front door — first + default;
// the legacy views demote to secondary (after the divider).
export const MEMORY_VIEWS: readonly MemoryView[] = [
'trust', 'memories', 'timeline', 'graph', 'harvest', 'weaver', 'wiki',
'trust', 'memories', 'timeline', 'graph', 'harvest', 'wiki',
];
interface MemoryTabDef {
@@ -50,9 +50,9 @@ interface MemoryTabDef {
tooltip: string;
}
// UX gold-standard H1: 7 equal-weight tabs regrouped into 4 primary + an
// "Advanced" flyout (display-level IA only — every view id, route and
// ?tab= deep-link is unchanged; MEMORY_VIEWS still validates all 7).
// UX gold-standard H1: the tabs are regrouped into 4 primary + an "Advanced"
// flyout (display-level IA only — every view id, route and ?tab= deep-link is
// unchanged; MEMORY_VIEWS validates them all).
const PRIMARY_TABS: MemoryTabDef[] = [
{ id: 'trust', label: 'Trust', icon: ShieldCheck, tooltip: 'Memory Trust — confidence & freshness, forget / correct / confirm, and "why did you do that?"' },
{ id: 'memories', label: 'Memories', icon: Brain, tooltip: 'Memory Center — inspect, edit, review, merge' },
@@ -62,7 +62,6 @@ const PRIMARY_TABS: MemoryTabDef[] = [
const ADVANCED_TABS: MemoryTabDef[] = [
{ id: 'harvest', label: 'Imports', icon: Download, tooltip: 'Import conversations from other AIs' },
{ id: 'weaver', label: 'Maintenance', icon: Activity, tooltip: 'Memory distillation and consolidation' },
{ id: 'wiki', label: 'Wiki', icon: BookOpen, tooltip: 'Compiled knowledge pages' },
];
@@ -93,6 +92,8 @@ const MemoryCenterApp = ({
}: MemoryCenterAppProps) => {
// Reminder-banner eligibility (carried over from the retired MemoryApp shell).
const { state: onboardingState } = useOnboarding();
// Re-render once the server's capability map arrives (graph visibility).
useMemoryCapabilities();
// ADR-0002: views of hidden memory features (graph, imports, wiki) are not
// offered; a hidden view requested anyway falls back to the default.
@@ -286,8 +287,6 @@ const MemoryCenterApp = ({
}} />
) : view === 'harvest' ? (
<HarvestTab />
) : view === 'weaver' ? (
<WeaverPanel />
) : view === 'wiki' ? (
<WikiTab />
) : null}

View File

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

View File

@@ -3,7 +3,7 @@ import { useSearchParams } from 'react-router-dom';
import {
Cpu, Shield, Palette, Save, Loader2, Database,
Download, Upload, Wrench, DollarSign, Key, Lock, BarChart3, Trash2,
RotateCcw, GraduationCap, HelpCircle, AlertTriangle, MessageCircle,
RotateCcw, GraduationCap, HelpCircle, AlertTriangle, MessageCircle, Brain,
} from 'lucide-react';
import { useToast } from '@/hooks/use-toast';
import { adapter } from '@/lib/adapter';
@@ -25,7 +25,7 @@ import {
} from '@/lib/settings-tier-filter';
import { requiresYoloConfirm } from '@/lib/autonomy-confirm';
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 ModelPilotCard from '@/components/os/ModelPilotCard';
import EmbeddingRoutingCard from '@/components/os/EmbeddingRoutingCard';
@@ -166,6 +166,23 @@ const SettingsApp = () => {
const [backupBusy, setBackupBusy] = useState(false);
const [pendingApproval, setPendingApproval] = useState<SettingsApproval | null>(null);
const [approvalBusy, setApprovalBusy] = useState(false);
// Background fact extraction from chats (ADR-0007, decision 6).
const memoryCaps = useMemoryCapabilities();
const extractionAvailable = memoryCaps?.capabilities.extraction === true;
const extractionOn = extractionAvailable && memoryCaps?.settings.extraction === true;
const [extractionSaving, setExtractionSaving] = useState(false);
const [extractionError, setExtractionError] = useState<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
useEffect(() => {
@@ -435,6 +452,45 @@ const SettingsApp = () => {
</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
§"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

View File

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

View File

@@ -40,7 +40,8 @@ interface MemoryCardProps {
export function MemoryCard({ memory, onClick, selected, onSelect, className, duplicateCount }: MemoryCardProps) {
const status = statusMeta(memory.status);
const isProvisional = memory.importance === 'temporary';
// Archiving also sets importance 'temporary' (hidden from recall); that is not provisional.
const isProvisional = memory.importance === 'temporary' && memory.status !== 'archived';
const showTitle = memory.title && memory.title !== memory.content;
const selectionLabel = memory.title || memory.content.slice(0, 80) || memory.id;

View File

@@ -1,6 +1,6 @@
import { useState, useEffect, useCallback, useRef, useMemo } from 'react';
import { useReducedMotion } from 'framer-motion';
import { Search, Loader2, Brain, Archive, Trash2, GitMerge, RotateCcw, Check, Save, AlertTriangle, ShieldOff } from 'lucide-react';
import { Search, Loader2, Brain, Archive, Trash2, GitMerge, RotateCcw, Check, Save, ShieldOff } from 'lucide-react';
import { adapter } from '@/lib/adapter';
import { DATE_LOCALE } from '@/lib/date-locale';
import { consumeDeepLink } from '@/lib/app-deeplink';
@@ -20,16 +20,15 @@ import { cn } from '@/lib/utils';
/**
* Memory Center (UX-Refactor Phase 2, S04). Self-contained tab (like HarvestTab):
* fetches the shared Memory entity via the new /api/memory* adapter methods and
* exposes source / confidence / evidence / scope + edit / archive / delete / merge
* (PRD §12.4, DoD #4; C11 merge). The 'Needs review' filter surfaces C33 imports
* (status=unreviewed).
* fetches the shared Memory entity via the /api/memory* adapter methods and
* exposes source / evidence / scope + edit / archive / delete / erase / merge
* (PRD §12.4, DoD #4; C11 merge). The 'Needs review' filter surfaces facts
* extracted from chats in the background and not yet confirmed (status=unreviewed).
*
* P3/D2 two-mind split: the tab is the per-mind LIST, parameterized by `mind`
* (+ `workspaceId` for the workspace mind). Defaults to personal — the J08 deep
* link and pre-P3 call sites keep their behavior. Workspace-mind mutations MUST
* carry workspaceId or the server's candidateStores lookup misses the frame
* (personal-store-only search → 404).
* link and pre-P3 call sites keep their behavior. Memory ids are unique across
* scopes, so mutations need only the id.
*/
export interface MemoryCenterTabProps {
@@ -52,13 +51,6 @@ const STATUS_FILTERS: { value: '' | MemoryStatus; label: string }[] = [
{ value: 'unreviewed', label: 'Needs review' },
{ value: 'active', label: 'Active' },
{ value: 'archived', label: 'Archived' },
{ value: 'deprecated', label: 'Deprecated' },
];
const CONFIDENCE_FILTERS: { value: number; label: string }[] = [
{ value: 0, label: 'Any confidence' },
{ value: 40, label: 'Medium+' },
{ value: 75, label: 'High only' },
];
const CONTROL_FOCUS_CLASS = 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)] focus-visible:ring-offset-1 focus-visible:ring-offset-background';
@@ -68,7 +60,7 @@ export default function MemoryCenterTab({
workspaceId,
consumeDeepLinks = true,
}: MemoryCenterTabProps = {}) {
// Workspace-mind ops carry the workspace param; personal ops must not.
// The workspace list reads the workspace's memory; the personal list must not.
const wsParam = mind === 'workspace' ? workspaceId : undefined;
const reduceMotion = !!useReducedMotion();
// Wave T Lane D (item 2): seed the initial list from the session cache so a
@@ -76,7 +68,7 @@ export default function MemoryCenterTab({
// spinning (R13-V1 finding). A fresh remount always lands on the default
// filters, so the initial seed keys on those; the live key (below) also folds
// in the active filters for the mid-session mind-switch path.
const initialCacheKey = memoryListCacheKey(['mc', mind, wsParam, '', '', 0, '']);
const initialCacheKey = memoryListCacheKey(['mc', mind, wsParam, '', '', '']);
const [memories, setMemories] = useState<Memory[]>(() => readMemoryListCache(initialCacheKey) ?? []);
const [loading, setLoading] = useState(() => readMemoryListCache(initialCacheKey) === undefined);
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
// default; the curated 'active' view stays one click away as a labeled chip.
const [status, setStatus] = useState<'' | MemoryStatus>('');
const [minConfidence, setMinConfidence] = useState(0);
// Wave T Lane D (item 2): the live cache key folds in the server-side filters
// (this list fetches filtered). Held in a ref (updated every render) so the
// mind-switch reset effect can reseed without taking a filter dependency —
// reseeding on every keystroke would fight the debounced fetch.
const cacheKey = memoryListCacheKey(['mc', mind, wsParam, status, kind, minConfidence, q.trim()]);
const cacheKey = memoryListCacheKey(['mc', mind, wsParam, status, kind, q.trim()]);
const cacheKeyRef = useRef(cacheKey);
cacheKeyRef.current = cacheKey;
@@ -104,36 +95,15 @@ export default function MemoryCenterTab({
const [draftContent, setDraftContent] = useState('');
const [draftKind, setDraftKind] = useState<MemoryKind>('fact');
// #7 "View original source": inline expandable verbatim-source view in the
// detail drawer (not a nested modal). A frame can link MULTIPLE verbatim
// sources (metadata.archiveUids) → render each in its own escaped block;
// sourceRows is empty when the frame has no linked source → friendly empty state.
type ArchiveRow = { content: string; source: string; sourceRef: string | null; injectionFlagged: boolean; injectionFlags: string };
const [sourceExpanded, setSourceExpanded] = useState(false);
const [sourceRows, setSourceRows] = useState<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).
// Erase receipt: a transient, dismissible confirmation of how many memories
// the last erase removed (the drawer closes on success, so the receipt lives
// at the list level).
const [eraseNotice, setEraseNotice] = useState<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 =
| { kind: 'delete'; memory: Memory }
| { kind: 'erase'; memory: Memory }
| { kind: 'allow-reimport'; row: SuppressedRow };
const [suppressionOpen, setSuppressionOpen] = useState(false);
const [suppressed, setSuppressed] = useState<SuppressedRow[]>([]);
const [suppressionLoading, setSuppressionLoading] = useState(false);
| { kind: 'erase'; memory: Memory; sessionId: string };
const [pendingApproval, setPendingApproval] = useState<PendingApproval | null>(null);
const [approvalBusy, setApprovalBusy] = useState(false);
// Latest source-fetch token: the id whose fetch is allowed to write state. A
// selection change (reset effect → undefined) or a newer fetch invalidates any
// in-flight request so a stale result can't land on the wrong memory.
const sourceReqIdRef = useRef<string | undefined>(undefined);
// J08: Home's "N memories need review" banner deep-links here with
// {appId:'memory', filter:'unreviewed'}. Two paths (AutomationCenterApp
@@ -192,7 +162,6 @@ export default function MemoryCenterTab({
q: q.trim() || undefined,
kind: kind || undefined,
status: status || undefined,
minConfidence: minConfidence || undefined,
limit: 200,
});
if (seq === loadSeq.current) { setMemories(res); writeMemoryListCache(cacheKey, res); }
@@ -201,7 +170,7 @@ export default function MemoryCenterTab({
} finally {
if (seq === loadSeq.current) setLoading(false);
}
}, [q, kind, status, minConfidence, mind, wsParam, cacheKey]);
}, [q, kind, status, mind, wsParam, cacheKey]);
useEffect(() => {
const t = setTimeout(load, q ? 250 : 0); // debounce text search only
@@ -210,8 +179,8 @@ export default function MemoryCenterTab({
// Mind switch invalidates EVERYTHING in flight and on screen (keyed on the
// EFFECTIVE scope, so personal-mind instances ignore workspace churn):
// - selection/checklist: a drawer or merge set carried across minds would
// mutate the wrong store (ids collide across the per-mind SQLite DBs);
// - selection/checklist: a drawer or merge set from the other list must not
// act on memories that are no longer shown;
// - the list: stale rows must not render under the new mind's pill;
// - loadSeq: an in-flight old-mind response must not commit into the window
// between this reset and the (debounced) next load starting;
@@ -229,8 +198,6 @@ export default function MemoryCenterTab({
setMemories(cached ?? []);
setLoading(cached === undefined);
setEraseNotice(null); // a receipt for the prior mind must not persist across the switch
setSuppressionOpen(false); // the erased-source list is per-mind — collapse + drop stale rows
setSuppressed([]);
setPendingApproval(null);
setApprovalBusy(false);
}, [mind, wsParam]);
@@ -241,37 +208,6 @@ export default function MemoryCenterTab({
setDraftKind(m.kind);
};
// Reset the verbatim-source view whenever the selected memory changes (incl.
// closing the drawer) so a previously-opened source can't leak into another row.
useEffect(() => {
setSourceExpanded(false);
setSourceRows([]);
setSourceError(null);
setSourceLoading(false);
sourceReqIdRef.current = undefined; // invalidate any in-flight fetch for the prior memory
}, [selected?.id]);
// Toggle the inline source view; lazy-fetch the verbatim row on first open.
const viewOriginalSource = async () => {
if (!selected) return;
if (sourceExpanded) { setSourceExpanded(false); return; }
const reqId = selected.id;
sourceReqIdRef.current = reqId;
setSourceExpanded(true);
setSourceLoading(true);
setSourceError(null);
try {
const res = await adapter.getMemoryOriginalSource(reqId, wsParam, mind);
if (sourceReqIdRef.current !== reqId) return; // selection changed mid-flight — drop stale result
setSourceRows(res.archiveRows);
} catch (e) {
if (sourceReqIdRef.current !== reqId) return;
setSourceError(e instanceof Error ? e.message : 'Failed to load original source');
} finally {
if (sourceReqIdRef.current === reqId) setSourceLoading(false);
}
};
const toggleChecked = (id: string, on: boolean) => {
setChecked((prev) => {
const next = new Set(prev);
@@ -281,7 +217,7 @@ export default function MemoryCenterTab({
};
const mutate = async (fn: () => Promise<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);
try {
await fn();
@@ -302,48 +238,27 @@ export default function MemoryCenterTab({
if (draftContent !== selected.content) patch.content = draftContent;
if (draftKind !== selected.kind) patch.kind = draftKind;
if (Object.keys(patch).length === 0) { setSelected(null); return; }
void mutate(() => adapter.patchMemory(selected.id, patch, wsParam, mind), true);
void mutate(() => adapter.patchMemory(selected.id, patch), true);
};
const archive = (m: Memory) => void mutate(() => adapter.archiveMemory(m.id, wsParam, mind), true);
const unarchive = (m: Memory) => void mutate(() => adapter.patchMemory(m.id, { status: 'active' }, wsParam, mind), true);
const markReviewed = (m: Memory) => void mutate(() => adapter.patchMemory(m.id, { status: 'active' }, wsParam, mind), true);
const archive = (m: Memory) => void mutate(() => adapter.archiveMemory(m.id), true);
const unarchive = (m: Memory) => void mutate(() => adapter.patchMemory(m.id, { status: 'active' }), true);
const markReviewed = (m: Memory) => void mutate(() => adapter.patchMemory(m.id, { status: 'active' }), true);
const remove = (m: Memory) => setPendingApproval({ kind: 'delete', memory: m });
// #7 P1 GDPR Art.17 "right to erasure" — the FULL sweep (this memory + its
// original source text + every search-index entry + knowledge-graph facts
// derived solely from it + the verbatim conversation turns behind it). Runs
// server-side in one atomic transaction. Distinct from Delete (removes just
// this one record) and Archive (hides it). Irreversible → strong confirm +
// a receipt of exactly what was purged.
const erase = (m: Memory) => setPendingApproval({ kind: 'erase', memory: m });
// Erase: forget every memory saved from the chat this memory came from.
// Offered only for memories with a chat session; Delete covers the rest.
const erase = (m: Memory) => {
if (m.sessionId) setPendingApproval({ kind: 'erase', memory: m, sessionId: m.sessionId });
};
const mergeSelected = () => {
const ids = [...checked];
if (ids.length < 2) return;
void mutate(async () => {
await adapter.mergeMemories(ids, { workspaceId: wsParam, mind });
await adapter.mergeMemories(ids);
setChecked(new Set());
});
};
// #7 sticky erasure re-consent surface — lazy-loaded when the panel opens.
const loadSuppression = useCallback(async () => {
setSuppressionLoading(true);
try {
const res = await adapter.listSuppression({ workspaceId: wsParam, mind });
setSuppressed(res.suppressed);
} catch {
setSuppressed([]);
} finally {
setSuppressionLoading(false);
}
}, [wsParam, mind]);
const toggleSuppression = () => {
const next = !suppressionOpen;
setSuppressionOpen(next);
if (next) void loadSuppression();
};
const allowReimport = (row: SuppressedRow) => setPendingApproval({ kind: 'allow-reimport', row });
const approvalRequest = useMemo<ApprovalRequest | null>(() => {
if (!pendingApproval) return null;
if (pendingApproval.kind === 'delete') {
@@ -357,32 +272,20 @@ export default function MemoryCenterTab({
riskLevel: 'high',
};
}
if (pendingApproval.kind === 'erase') {
return {
action: `Erase memory and derived data: ${pendingApproval.memory.title}`,
scope: [
'This permanently removes the memory, its original source text, search index entries, related conversation turns, and derived knowledge facts.',
'This is a GDPR Art.17 erasure action and cannot be undone.',
'Use Archive to hide it, or Delete to remove only this one record.',
],
riskLevel: 'critical',
};
}
return {
action: `Allow source to be re-imported: ${pendingApproval.row.sourceRef}`,
action: 'Erase everything remembered from this chat',
scope: [
`Source: ${pendingApproval.row.source} / ${pendingApproval.row.sourceRef}`,
'This lifts the GDPR Art.17 erasure suppression for this source.',
'A future import can re-materialize it; use this only when the data subject has re-consented.',
'This removes this memory and every other memory Waggle saved from the same chat, in personal and workspace memory, so it no longer recalls them.',
'The chat transcript itself is kept.',
'This cannot be undone. Use Delete to remove only this memory.',
],
riskLevel: 'high',
riskLevel: 'critical',
};
}, [pendingApproval]);
const approvalLabel =
pendingApproval?.kind === 'delete' ? (approvalBusy ? 'Deleting...' : 'Delete memory')
: pendingApproval?.kind === 'erase' ? (approvalBusy ? 'Erasing...' : 'Erase memory')
: approvalBusy ? 'Allowing...' : 'Allow re-import';
: approvalBusy ? 'Erasing...' : 'Erase memories';
const confirmTrustAction = async () => {
if (!pendingApproval) return;
@@ -390,37 +293,20 @@ export default function MemoryCenterTab({
setApprovalBusy(true);
setEraseNotice(null);
try {
setBusy(true);
if (current.kind === 'delete') {
setBusy(true);
await adapter.deleteMemoryById(current.memory.id, wsParam, mind);
setSelected(null);
setPendingApproval(null);
setReloadTick((t) => t + 1);
return;
await adapter.deleteMemoryById(current.memory.id);
} else {
const { deleted } = await adapter.eraseMemory({ sessionId: current.sessionId });
setEraseNotice(`Erased ${deleted} ${deleted === 1 ? 'memory' : 'memories'} from that chat.`);
}
if (current.kind === 'erase') {
setBusy(true);
const { result } = await adapter.eraseMemory({ frameId: current.memory.id }, { workspaceId: wsParam, mind });
const parts = [
`${result.framesDeleted} ${result.framesDeleted === 1 ? 'memory' : 'memories'} erased`,
result.archiveRedacted > 0 ? `${result.archiveRedacted} source ${result.archiveRedacted === 1 ? 'record' : 'records'} redacted` : null,
result.entitiesErased > 0 ? `${result.entitiesErased} knowledge ${result.entitiesErased === 1 ? 'entity' : 'entities'} removed` : null,
].filter(Boolean);
setEraseNotice(`Erased "${current.memory.title}": ${parts.join(' · ')}.`);
setSelected(null);
setPendingApproval(null);
setReloadTick((t) => t + 1);
return;
}
setSuppressionLoading(true);
await adapter.allowReimport({ source: current.row.source, sourceRef: current.row.sourceRef }, { workspaceId: wsParam, mind });
setSelected(null);
setPendingApproval(null);
await loadSuppression();
setReloadTick((t) => t + 1);
} catch (e) {
setError(e instanceof Error ? e.message : 'Action failed');
} finally {
if (current.kind === 'allow-reimport') setSuppressionLoading(false);
else setBusy(false);
setBusy(false);
setApprovalBusy(false);
}
};
@@ -437,12 +323,10 @@ export default function MemoryCenterTab({
const statusLabel = STATUS_FILTERS.find((s) => s.value === status)?.label;
if (status && statusLabel) parts.push(statusLabel);
if (kind) parts.push(memoryKindLabel(kind));
const confLabel = CONFIDENCE_FILTERS.find((c) => c.value === minConfidence)?.label;
if (minConfidence && confLabel) parts.push(confLabel);
const query = q.trim();
if (query) parts.push(`matching "${query}"`);
return parts.join(' · ');
}, [status, kind, minConfidence, q]);
}, [status, kind, q]);
return (
// Wave U Lane E (item 4): a ~150ms fade-slide when this panel mounts on the
@@ -467,16 +351,6 @@ export default function MemoryCenterTab({
className="flex-1 bg-transparent text-xs h-auto border-0 p-0 focus-visible:ring-0 focus-visible:ring-offset-0"
/>
</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 className="flex flex-wrap gap-1">
@@ -527,7 +401,7 @@ export default function MemoryCenterTab({
)}
</div>
{/* #7 P1 GDPR erasure receipt — dismissible confirmation of what was purged. */}
{/* Erase receipt — dismissible confirmation of what was removed. */}
{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">
<Check className="w-3.5 h-3.5 mt-0.5 shrink-0 text-honey" />
@@ -536,42 +410,6 @@ export default function MemoryCenterTab({
</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
only when there are rows to frame; the skeleton / empty / error branches
own the empty-list surface below. When a background refresh is in flight
@@ -627,11 +465,11 @@ export default function MemoryCenterTab({
<p className="text-xs text-muted-foreground">
{mind === 'workspace' && !workspaceId
? 'No workspace selected — open a workspace to see what it has learned.'
: q || kind || status || minConfidence
: q || kind || status
? 'No memories match these filters.'
: mind === 'workspace'
? 'Nothing learned in this workspace yet — memories appear here as you work.'
: 'No memories yet — import or capture some to get started.'}
: 'No memories yet. They appear here as you chat, or when you capture a note.'}
</p>
</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)}>
<Trash2 className="w-3 h-3" /> Delete
</button>
<button
onClick={() => erase(selected)}
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."
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
</button>
{selected.sessionId && (
<button
onClick={() => erase(selected)}
disabled={busy}
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)}
>
<ShieldOff className="w-3 h-3" /> Erase chat memories
</button>
)}
</div>
) : 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>
<EvidencePanel source={selected.source} sourceId={selected.sourceId} sourceUrl={selected.sourceUrl} evidence={selected.evidence} onViewOriginalSource={viewOriginalSource} hasOriginalSource={selected.hasOriginalSource} expanded={sourceExpanded} busy={sourceLoading} />
{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>
)}
<EvidencePanel source={selected.source} sourceId={selected.sourceId} sourceUrl={selected.sourceUrl} evidence={selected.evidence} />
<p className="text-[11px] text-muted-foreground">
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 { renderChatMarkdown } from '@/lib/render-markdown';
import { cn } from '@/lib/utils';
import { memoryLabel } from './memory-label';
/**
* Memory-Trust "Manage" view (screen 19 §3–§5, PR3.5 Phase B+C). The editorial
@@ -21,8 +22,8 @@ import { cn } from '@/lib/utils';
* stat bar → search + filter chips → native confidence-ring rows with the
* 3-segment ⬡ provenance line and real forget / correct / confirm actions.
*
* No-fabrication contract: confidence is harvest-only → the ring shows "—" and
* the "High confidence & fresh" stat gates to "—" when absent; freshness is
* No-fabrication contract: the memory contract stores no confidence in v1 → no
* ring is drawn and the "high confidence" stat gates to "—" when absent; freshness is
* derived as honest AGE (never a stored %); the "Forgotten" filter is gated off
* (hard delete leaves no tombstone). Stats are computed from the fetched
* working set (single-mind; cap-aware "500+") — never a cross-mind count.
@@ -236,9 +237,8 @@ function MemoryRow({ memory, onOpen, onForget, onConfirm, busy, duplicateCount,
const srcLabel = frameSourceLabel(memory.source);
const stale = isStale(memory);
const needsConfirm = memory.status === 'unreviewed';
// Round-6 fix 2b: the ring renders only when a confidence actually exists;
// the unscored state is a single quiet inline badge on the provenance row
// (the old stacked "unscored / CONF" micro-label was illegible).
// Round-6 fix 2b: the ring renders only when a confidence actually exists.
// The memory contract stores none in v1, so unscored rows show no badge.
const scored = typeof memory.confidence === 'number' && Number.isFinite(memory.confidence);
// Round-5..9: raw harvest strings read as log output — buildMemoryPreview
// leads with the first line as a title, clamps the rest as a muted excerpt,
@@ -281,7 +281,7 @@ function MemoryRow({ memory, onOpen, onForget, onConfirm, busy, duplicateCount,
neutral tier. Wave X Lane B: --text-dim is 4.09:1 on --surface-2
at 12px (sub-AA) and this is the memory's correction HANDLE, not
decoration — matched to its row's --text-muted (5.6:1). */}
<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
(short label at rest, full provenance in the tooltip). */}
{provShort && (
@@ -293,14 +293,6 @@ function MemoryRow({ memory, onOpen, onForget, onConfirm, busy, duplicateCount,
{provShort}
</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)]'}>
● {fresh.label}
</span>
@@ -352,7 +344,7 @@ function MemoryRow({ memory, onOpen, onForget, onConfirm, busy, duplicateCount,
onClick={onConfirm}
disabled={busy}
title="Confirm this memory"
aria-label={`Confirm memory M-${memory.id}`}
aria-label={`Confirm memory ${memoryLabel(memory.id)}`}
className="relative grid h-[30px] w-[30px] place-items-center rounded-[8px] border border-[var(--line-soft)] bg-[var(--surface-2)] text-[var(--text-muted)] before:absolute before:left-1/2 before:top-1/2 before:h-10 before:w-10 before:-translate-x-1/2 before:-translate-y-1/2 before:content-[''] hover:border-[var(--healthy)] hover:text-[var(--healthy)] disabled:opacity-50"
>
<Check className="h-[15px] w-[15px]" strokeWidth={1.8} />
@@ -362,7 +354,7 @@ function MemoryRow({ memory, onOpen, onForget, onConfirm, busy, duplicateCount,
type="button"
onClick={onOpen}
title="Edit / correct"
aria-label={`Edit or correct memory M-${memory.id}`}
aria-label={`Edit or correct memory ${memoryLabel(memory.id)}`}
className="relative grid h-[30px] w-[30px] place-items-center rounded-[8px] border border-[var(--line-soft)] bg-[var(--surface-2)] text-[var(--text-muted)] before:absolute before:left-1/2 before:top-1/2 before:h-10 before:w-10 before:-translate-x-1/2 before:-translate-y-1/2 before:content-[''] hover:border-[var(--honey-line)] hover:text-[var(--honey-text)]"
>
<Pencil className="h-[15px] w-[15px]" strokeWidth={1.8} />
@@ -372,7 +364,7 @@ function MemoryRow({ memory, onOpen, onForget, onConfirm, busy, duplicateCount,
onClick={onForget}
disabled={busy}
title="Forget this"
aria-label={`Forget memory M-${memory.id}`}
aria-label={`Forget memory ${memoryLabel(memory.id)}`}
className="relative grid h-[30px] w-[30px] place-items-center rounded-[8px] border border-[var(--line-soft)] bg-[var(--surface-2)] text-[var(--text-muted)] before:absolute before:left-1/2 before:top-1/2 before:h-10 before:w-10 before:-translate-x-1/2 before:-translate-y-1/2 before:content-[''] hover:border-[color-mix(in_srgb,var(--risk)_45%,transparent)] hover:text-[var(--risk)] disabled:opacity-50"
>
<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
// (review M).
const forget = (m: Memory, closeDrawer = false) =>
void mutate(() => adapter.deleteMemoryById(m.id, wsParam, mind), `Forgotten M-${m.id} — removed from recall`, closeDrawer);
void mutate(() => adapter.deleteMemoryById(m.id), `Forgotten ${memoryLabel(m.id)} — removed from recall`, closeDrawer);
const confirmMemory = (m: Memory, closeDrawer = false) =>
void mutate(() => adapter.confirmMemory(m.id, wsParam, mind), `Confirmed M-${m.id} — marked reviewed`, closeDrawer);
void mutate(() => adapter.confirmMemory(m.id), `Confirmed ${memoryLabel(m.id)} — marked reviewed`, closeDrawer);
const saveCorrection = () => {
if (!selected) return;
if (draft === selected.content) { setSelected(null); return; }
void mutate(() => adapter.patchMemory(selected.id, { content: draft }, wsParam, mind), `Corrected M-${selected.id}`, true);
void mutate(() => adapter.patchMemory(selected.id, { content: draft }), `Corrected ${memoryLabel(selected.id)}`, true);
};
const openDetail = (m: Memory) => { setSelected(m); setDraft(m.content); };
@@ -731,7 +723,7 @@ export default function MemoryTrustManage({ mind, workspaceId, onToast, onWhy, o
open={!!selected}
onOpenChange={(o) => { if (!o) setSelected(null); }}
title={selected?.title ?? 'Memory'}
subtitle={selected ? `M-${selected.id} · ${selected.scope}` : undefined}
subtitle={selected ? `${memoryLabel(selected.id)} · ${selected.scope}` : undefined}
footer={selected ? (
<div className="flex w-full items-center gap-2">
<button

View File

@@ -2,6 +2,7 @@ import { useState, useEffect, type ReactNode } from 'react';
import { Loader2, Info, Sparkles } from 'lucide-react';
import { adapter } from '@/lib/adapter';
import type { MemoryTrace } from '@/lib/types';
import { memoryLabel } from './memory-label';
import { HexAvatar, DotLive, type WarmTone } from '../../warm';
/**
@@ -16,8 +17,6 @@ import { HexAvatar, DotLive, type WarmTone } from '../../warm';
*/
interface MemoryTrustWhyProps {
mind: 'personal' | 'workspace';
workspaceId?: string;
/** The memory whose trace to explain (set from the Manage view). Null → pick-one prompt. */
memoryId: string | null;
onToast: (msg: string) => void;
@@ -67,8 +66,7 @@ function Shell({ children }: { children: ReactNode }) {
);
}
export default function MemoryTrustWhy({ mind, workspaceId, memoryId, onToast, onCorrect, onForget }: MemoryTrustWhyProps) {
const wsParam = mind === 'workspace' ? workspaceId : undefined;
export default function MemoryTrustWhy({ memoryId, onToast, onCorrect, onForget }: MemoryTrustWhyProps) {
const [trace, setTrace] = useState<MemoryTrace | null>(null);
const [loading, setLoading] = useState(false);
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; }
let alive = true;
setLoading(true); setError(null); setTrace(null);
adapter.getMemoryTrace(memoryId, wsParam, mind)
adapter.getMemoryTrace(memoryId)
.then((r) => { if (alive) setTrace(r.trace); })
.catch((e) => { if (alive) setError(e instanceof Error ? e.message : 'Failed to load trace'); })
.finally(() => { if (alive) setLoading(false); });
return () => { alive = false; };
}, [memoryId, wsParam, mind]);
}, [memoryId]);
// No memory chosen yet — point the user at the Manage view.
if (!memoryId) {
@@ -102,7 +100,7 @@ export default function MemoryTrustWhy({ mind, workspaceId, memoryId, onToast, o
return (
<Shell>
<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>
);
}
@@ -120,7 +118,7 @@ export default function MemoryTrustWhy({ mind, workspaceId, memoryId, onToast, o
return (
<Shell>
<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)]">
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.
@@ -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">
<HexAvatar label="Trace" size={36} />
<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)]">
{[trace.model, OUTCOME_LABEL[trace.outcome], trace.sessionId ? `session ${trace.sessionId.slice(0, 8)}` : null].filter(Boolean).join(' · ')}
</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">
<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]"
>
Looks right
@@ -179,7 +177,7 @@ export default function MemoryTrustWhy({ mind, workspaceId, memoryId, onToast, o
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)]"
>
Forget M-{memoryId} &amp; redo
Forget {memoryLabel(memoryId)} &amp; redo
</button>
<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

View File

@@ -1,5 +1,5 @@
import { useState } from 'react';
import { Brain, Search, Clock, Trash2, Edit3, Filter, Eye, Copy, Loader2, AlertTriangle, ClipboardList, Calendar, Lightbulb, Scale, CheckSquare, Tag, FileText, type LucideIcon } from 'lucide-react';
import { Brain, Search, Clock, Trash2, Edit3, Filter, Eye, Copy, Loader2, AlertTriangle, ClipboardList, Calendar, Heart, User, Scale, StickyNote, FileText, type LucideIcon } from 'lucide-react';
import { AnimatePresence } from 'framer-motion';
import { Input } from '@/components/ui/input';
import { DATE_LOCALE } from '@/lib/date-locale';
@@ -17,11 +17,11 @@ import { HintTooltip } from '@/components/ui/hint-tooltip';
*/
// Lucide, not emoji — one icon language across the chrome (2026-07-06 P2).
const frameTypeIcons: Record<string, LucideIcon> = {
fact: ClipboardList, event: Calendar, insight: Lightbulb, decision: Scale, task: CheckSquare, entity: Tag,
const frameTypeIcons: Record<MemoryFrame['type'], LucideIcon> = {
fact: ClipboardList, event: Calendar, preference: Heart, profile: User, decision: Scale, summary: FileText, note: StickyNote,
};
const FRAME_TYPES = ['fact', 'event', 'insight', 'decision', 'task', 'entity'];
const FRAME_TYPES = Object.keys(frameTypeIcons) as MemoryFrame['type'][];
const importanceColors = ['text-muted-foreground', 'text-muted-foreground', 'text-foreground', 'text-honey', 'text-amber-400', 'text-destructive'];
@@ -82,7 +82,7 @@ const TimelineTab = ({
});
};
const toggleTypeFilter = (type: string) => {
const toggleTypeFilter = (type: MemoryFrame['type']) => {
if (!onTypeFiltersChange) return;
if (typeFilters.includes(type)) {
onTypeFiltersChange(typeFilters.filter(t => t !== type));
@@ -163,10 +163,7 @@ const TimelineTab = ({
<div className="flex-1 overflow-auto p-1.5 space-y-0.5">
{frames.map(f => (
<button
// Frame ids collide across minds (separate per-mind SQLite
// 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}`}
key={f.id}
onClick={() => {
onSelectFrame(f);
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 { EvidenceChip } from './evidence-chip';
@@ -13,22 +12,10 @@ interface EvidencePanelProps {
sourceId?: string | null;
sourceUrl?: string | null;
evidence?: string[];
/** #7 "View original source": when supplied (and a linked archive exists, i.e.
* hasOriginalSource), renders an Eye button that opens the verbatim source view
* in the detail drawer. */
onViewOriginalSource?: () => void;
/** Whether a verbatim raw_archive row is actually linked. Gates the Eye button so
* a sourceId-only frame (e.g. an auto-synced summary) never shows a View-original
* affordance that would 404 — see Memory.hasOriginalSource. */
hasOriginalSource?: boolean;
/** Whether the source view is currently open (drives aria-expanded). */
expanded?: boolean;
/** Whether the source fetch is in flight (drives aria-busy + disables the button). */
busy?: boolean;
className?: string;
}
export function EvidencePanel({ source, sourceId, sourceUrl, evidence, onViewOriginalSource, hasOriginalSource, expanded, busy, className }: EvidencePanelProps) {
export function EvidencePanel({ source, sourceId, sourceUrl, evidence, className }: EvidencePanelProps) {
const hasEvidence = Array.isArray(evidence) && evidence.length > 0;
if (!source && !sourceId && !sourceUrl && !hasEvidence) return null;
@@ -42,20 +29,6 @@ export function EvidencePanel({ source, sourceId, sourceUrl, evidence, onViewOri
<div className="flex flex-wrap gap-1.5">
{source && <EvidenceChip label={`source: ${source}`} />}
{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} />}
</div>
{hasEvidence && (