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

@@ -27,7 +27,7 @@ import type {
WorkspaceStateView, WorkspaceActivityEvent, WorkspaceTask,
Artifact, RelatedSearchResult,
Agent, AgentTrace, Automation, AutomationLog, EngineStatus, PendingApprovalItem,
MemoryTrace,
MemoryTrace, MemoryCapabilitiesResponse,
} from './types';
import type {
Command, CommandResult, WorkspaceType,
@@ -215,13 +215,13 @@ function unwrapArray<T>(data: any): T[] {
return [];
}
/** Map backend frameType codes to frontend type names */
const FRAME_TYPE_MAP: Record<string, string> = {
I: 'insight', F: 'fact', E: 'event', D: 'decision', T: 'task', N: 'entity',
insight: 'insight', fact: 'fact', event: 'event', decision: 'decision', task: 'task', entity: 'entity',
};
/** Memory kinds of the memory contract; anything else reads as a fact. */
const MEMORY_FRAME_KINDS: ReadonlySet<string> = new Set<MemoryFrame['type']>([
'fact', 'event', 'preference', 'profile', 'decision', 'summary', 'note',
]);
/** Contract importance (and the Tauri command's low/high) on the 1-4 scale. */
const IMPORTANCE_MAP: Record<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. */
@@ -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 {
const content = raw.content ?? '';
const kind = raw.kind ?? raw.type;
return {
id: String(raw.id),
type: (FRAME_TYPE_MAP[raw.frameType] ?? FRAME_TYPE_MAP[raw.type] ?? 'fact') as MemoryFrame['type'],
type: (MEMORY_FRAME_KINDS.has(kind) ? kind : 'fact') as MemoryFrame['type'],
title: content.split('\n')[0].slice(0, 80),
content,
importance: typeof raw.importance === 'number' ? raw.importance : (IMPORTANCE_MAP[raw.importance] ?? 2),
timestamp: raw.timestamp ?? raw.created_at ?? '',
workspaceId: raw.mind ?? raw.workspaceId ?? '',
workspaceId: raw.workspaceId ?? '',
metadata: {
source: raw.source,
gop: raw.gop,
accessCount: raw.accessCount,
mind: raw.mind,
// Lifecycle status — consumers (e.g. briefing highlights) must keep
// deprecated/archived frames off hero surfaces.
// archived frames off hero surfaces.
status: raw.status ?? raw.metadata?.status,
},
};
@@ -1187,7 +1187,7 @@ class LocalAdapter {
// --- Memory ---
async getMemoryFrames(workspaceId: string, limit = 50): Promise<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);
}
@@ -1220,36 +1220,50 @@ class LocalAdapter {
await this.fetch(`/api/memory/frames/${id}`, { method: 'DELETE' });
}
async incrementFrameAccess(id: string, workspaceId?: string): Promise<{ accessCount: number }> {
const qs = workspaceId ? `?workspace=${encodeURIComponent(workspaceId)}` : '';
const res = await this.fetch(`/api/memory/frames/${id}/access${qs}`, { method: 'PATCH' });
const body = await res.json() as { accessCount?: number };
return { accessCount: typeof body.accessCount === 'number' ? body.accessCount : 0 };
}
async searchMemory(query: string, scope?: string): Promise<MemoryFrame[]> {
/**
* Ranked memory search. `scope`: 'personal', 'workspace' (the given
* workspace), 'all' (personal plus the given workspace, the default) or
* 'global' (personal plus every workspace).
*/
async searchMemory(
query: string,
scope?: 'all' | 'personal' | 'workspace' | 'global',
workspaceId?: string,
): Promise<MemoryFrame[]> {
// CC Sesija A §2.2 — Tauri IPC path for desktop builds.
if (isTauri()) {
const resp = await tauriRecallMemory({
query,
scope: scope as 'all' | 'personal' | 'workspace' | 'global' | undefined,
});
const resp = await tauriRecallMemory({ query, scope, ...(workspaceId && { workspaceId }) });
return resp.results.map((r) => normalizeFrame(r as Record<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);
}
/** 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) ---
// These hit the new bare /api/memory* routes (memory-center.ts) and return the
// shared `Memory` shape (kind/confidence/scope/status/evidence/...), distinct
// from the legacy frame methods above. HTTP path works in web + desktop (the
// sidecar is bundled), so no Tauri IPC branch is needed.
// These hit the bare /api/memory* routes (memory-center.ts) and return the
// shared `Memory` shape. Memory ids are unique across personal and workspace
// memory, so the single-memory calls need no scope.
async listMemories(opts: {
workspaceId?: string; kind?: string; status?: string; scope?: string;
q?: string; minConfidence?: number; limit?: number;
/** P3/D2 two-mind split — select a single mind; omit for the legacy merge. */
workspaceId?: string; kind?: string; status?: string; q?: string; limit?: number;
/** Read one scope; omit to merge personal memory and the workspace's. */
mind?: 'personal' | 'workspace';
} = {}): Promise<Memory[]> {
const p = new URLSearchParams();
@@ -1257,9 +1271,7 @@ class LocalAdapter {
if (opts.workspaceId) p.set('workspace', opts.workspaceId);
if (opts.kind) p.set('kind', opts.kind);
if (opts.status) p.set('status', opts.status);
if (opts.scope) p.set('scope', opts.scope);
if (opts.q) p.set('q', opts.q);
if (typeof opts.minConfidence === 'number') p.set('minConfidence', String(opts.minConfidence));
if (typeof opts.limit === 'number') p.set('limit', String(opts.limit));
const qs = p.toString();
const res = await this.fetch(`/api/memory${qs ? `?${qs}` : ''}`);
@@ -1271,31 +1283,18 @@ class LocalAdapter {
return body.results ?? [];
}
/** Query string for the single-memory routes. `mind` makes server-side store
* resolution STRICT (P3/D2): frame ids collide across the per-mind SQLite
* DBs, so a workspace-scoped mutation must never fall through to (and
* destroy) a colliding personal frame. Callers that know the mind — the
* Memory Center always does — should pass it. */
private memoryScopeQs(workspaceId?: string, mind?: 'personal' | 'workspace'): string {
const p = new URLSearchParams();
if (workspaceId) p.set('workspace', workspaceId);
if (mind) p.set('mind', mind);
const s = p.toString();
return s ? `?${s}` : '';
}
async getMemory(id: string, workspaceId?: string, mind?: 'personal' | 'workspace'): Promise<Memory | null> {
async getMemory(id: string): Promise<Memory | null> {
// P1b D3: fetchRaw preserves the documented 404→null contract (the
// throwing fetch would reject before the status check).
const res = await this.fetchRaw(`/api/memory/${encodeURIComponent(id)}${this.memoryScopeQs(workspaceId, mind)}`);
const res = await this.fetchRaw(`/api/memory/${encodeURIComponent(id)}`);
if (res.status === 404) return null;
if (!res.ok) throw new AdapterHttpError(res.status, res.statusText, await res.clone().json().catch(() => undefined));
return res.json();
}
async createMemory(input: {
content: string; kind?: string; scope?: string; tags?: string[];
importance?: string; title?: string; confidence?: number; workspaceId?: string;
content: string; kind?: string; tags?: string[];
importance?: string; title?: string; workspaceId?: string;
}): Promise<Memory> {
const res = await this.fetch('/api/memory', { method: 'POST', body: JSON.stringify(input) });
return res.json();
@@ -1303,105 +1302,55 @@ class LocalAdapter {
async patchMemory(
id: string,
patch: { content?: string; importance?: string; kind?: string; scope?: string; tags?: string[]; status?: string; title?: string; evidence?: string[] },
workspaceId?: string,
mind?: 'personal' | 'workspace',
patch: { content?: string; importance?: string; kind?: string; tags?: string[]; status?: 'active' | 'archived'; title?: string; evidence?: string[] },
): Promise<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();
}
async archiveMemory(id: string, workspaceId?: string, mind?: 'personal' | 'workspace'): Promise<Memory> {
const res = await this.fetch(`/api/memory/${encodeURIComponent(id)}/archive${this.memoryScopeQs(workspaceId, mind)}`, { method: 'POST' });
/** Reversible archive: hidden from recall until unarchived. */
async archiveMemory(id: string): Promise<Memory> {
const res = await this.fetch(`/api/memory/${encodeURIComponent(id)}/archive`, { method: 'POST' });
return res.json();
}
/** Hard delete (A8) via the bare-id route — distinct from deleteMemoryFrame. */
async deleteMemoryById(id: string, workspaceId?: string, mind?: 'personal' | 'workspace'): Promise<void> {
await this.fetch(`/api/memory/${encodeURIComponent(id)}${this.memoryScopeQs(workspaceId, mind)}`, { method: 'DELETE' });
async deleteMemoryById(id: string): Promise<void> {
await this.fetch(`/api/memory/${encodeURIComponent(id)}`, { method: 'DELETE' });
}
/** PR3.5 Memory-Trust: clear the 'unreviewed' lifecycle state (status→active). */
async confirmMemory(id: string, workspaceId?: string, mind?: 'personal' | 'workspace'): Promise<Memory> {
const res = await this.fetch(`/api/memory/${encodeURIComponent(id)}/confirm${this.memoryScopeQs(workspaceId, mind)}`, { method: 'POST' });
/** PR3.5 Memory-Trust: confirm a memory extracted in the background (status→active). */
async confirmMemory(id: string): Promise<Memory> {
const res = await this.fetch(`/api/memory/${encodeURIComponent(id)}/confirm`, { method: 'POST' });
return res.json();
}
/** PR3.5 "Why did you do that?": resolve the execution trace that wrote a
* memory (via the metadata.trace_id backlink). Returns { trace: null } when
* the frame has no linked trace — the caller shows an honest empty state. */
async getMemoryTrace(id: string, workspaceId?: string, mind?: 'personal' | 'workspace'): Promise<{ trace: MemoryTrace | null }> {
const res = await this.fetch(`/api/memory/${encodeURIComponent(id)}/trace${this.memoryScopeQs(workspaceId, mind)}`);
* the memory has no linked trace — the caller shows an honest empty state. */
async getMemoryTrace(id: string): Promise<{ trace: MemoryTrace | null }> {
const res = await this.fetch(`/api/memory/${encodeURIComponent(id)}/trace`);
return res.json();
}
/** #7 "View original source": resolve the immutable verbatim raw_archive row(s)
* a memory was distilled from (via metadata.archiveUids — one frame can link
* several sources). 404 = no linked source (manual / pre-archive frames) →
* { archiveRows: [] } for a friendly empty state, mirroring getMemory's
* documented 404→null contract rather than the throwing fetch. */
async getMemoryOriginalSource(
id: string,
workspaceId?: string,
mind?: 'personal' | 'workspace',
): Promise<{ archiveRows: Array<{ content: string; source: string; sourceRef: string | null; injectionFlagged: boolean; injectionFlags: string }> }> {
const res = await this.fetchRaw(`/api/memory/${encodeURIComponent(id)}/source${this.memoryScopeQs(workspaceId, mind)}`);
if (res.status === 404) return { archiveRows: [] };
if (!res.ok) throw new AdapterHttpError(res.status, res.statusText, await res.clone().json().catch(() => undefined));
const body = await res.json();
return { archiveRows: Array.isArray(body?.archiveRows) ? body.archiveRows : [] };
}
/** #7 P1 GDPR Art.17 per-subject erasure — runs the FULL sweep (raw_archive
* provenance redaction + frame delete from every retrieval store + orphaned-KG
* hard-delete +, in subject mode, verbatim raw-turn / B-frame reach). Distinct
* from the A8 frame-only deleteMemoryById AND from eraseData (whole-datadir
* account wipe). Frame mode by default; pass {source, sourceRef} to sweep an
* entire harvested source. Returns the erasure breakdown for the UI receipt. */
/** Forget one memory ({ id }) or every memory saved from one chat session
* ({ sessionId }), in personal and workspace memory. */
async eraseMemory(
target: { frameId: string } | { source: string; sourceRef: string },
opts: { reason?: string; workspaceId?: string; mind?: 'personal' | 'workspace' } = {},
): Promise<{
erased: boolean;
mind: string;
result: { framesDeleted: number; archiveRedacted: number; chunkVectorsPurged: number; entitiesErased: number; relationsErased: number };
}> {
const res = await this.fetch(`/api/memory/erase${this.memoryScopeQs(opts.workspaceId, opts.mind)}`, {
target: { id: string } | { sessionId: string },
opts: { reason?: string } = {},
): Promise<{ erased: boolean; deleted: number }> {
const res = await this.fetch('/api/memory/erase', {
method: 'POST',
body: JSON.stringify({ ...target, reason: opts.reason }),
});
return res.json();
}
/** #7 sticky erasure — list the (source, sourceRef) subjects on the erased-subject
* suppression list. A re-import of any of these is skipped, so an Art.17 erasure
* survives a later re-export/re-sync. The re-consent UI lists + clears them. */
async listSuppression(
opts: { workspaceId?: string; mind?: 'personal' | 'workspace' } = {},
): Promise<{ mind: string; suppressed: Array<{ source: string; sourceRef: string; erasedAt: string; reason: string | null }> }> {
const res = await this.fetchRaw(`/api/memory/suppression${this.memoryScopeQs(opts.workspaceId, opts.mind)}`);
if (!res.ok) return { mind: opts.mind ?? 'personal', suppressed: [] };
const body = await res.json();
return { mind: body?.mind ?? 'personal', suppressed: Array.isArray(body?.suppressed) ? body.suppressed : [] };
}
/** #7 sticky erasure — re-consent: lift the suppression on a subject so it may be
* re-imported again. Idempotent (removed:false if it wasn't suppressed). */
async allowReimport(
subject: { source: string; sourceRef: string },
opts: { workspaceId?: string; mind?: 'personal' | 'workspace' } = {},
): Promise<{ removed: boolean; mind: string }> {
const res = await this.fetch(`/api/memory/suppression/allow${this.memoryScopeQs(opts.workspaceId, opts.mind)}`, {
method: 'POST',
body: JSON.stringify(subject),
});
return res.json();
}
async mergeMemories(ids: string[], opts: { workspaceId?: string; title?: string; mind?: 'personal' | 'workspace' } = {}): Promise<Memory> {
/** Join memories of one scope into one; the originals are archived. */
async mergeMemories(ids: string[], opts: { title?: string } = {}): Promise<Memory> {
const res = await this.fetch('/api/memory/merge', {
method: 'POST',
body: JSON.stringify({ ids, workspaceId: opts.workspaceId, title: opts.title, mind: opts.mind }),
body: JSON.stringify({ ids, title: opts.title }),
});
return res.json();
}
@@ -3089,28 +3038,6 @@ class LocalAdapter {
} catch { return { byType: {}, total: 0 }; }
}
// --- Weaver ---
// Mirrors GET /api/weaver/status (packages/server/src/local/routes/weaver.ts):
// the domain shape consumers (WeaverPanel, CockpitApp) read directly. On error
// we return a valid-but-empty object of the SAME shape rather than a fake
// success status, so callers never crash dereferencing missing fields.
async getWeaverStatus(): Promise<{
personalMind: { lastConsolidation: string | null; lastDecay: string | null; timerActive: boolean };
workspaces: Array<{ id: string; lastConsolidation: string | null; timerActive: boolean }>;
checkedAt: string;
}> {
try {
const res = await this.fetch('/api/weaver/status');
return res.json();
} catch {
return {
personalMind: { lastConsolidation: null, lastDecay: null, timerActive: false },
workspaces: [],
checkedAt: new Date().toISOString(),
};
}
}
// --- Audit ---
async getAuditInstalls(): Promise<unknown[]> {
const res = await this.fetch('/api/audit/installs');
@@ -3620,17 +3547,7 @@ class LocalAdapter {
}
}
// --- Import ---
async importPreview(data: unknown, source: string): Promise<{ knowledgeExtracted: unknown[] }> {
const res = await this.fetch('/api/import/preview', { method: 'POST', body: JSON.stringify({ data, source }) });
return res.json();
}
async importCommit(data: unknown, source: string): Promise<void> {
await this.fetch('/api/import/commit', { method: 'POST', body: JSON.stringify({ data, source }) });
}
// --- Harvest ---
// --- Harvest (hidden in v1, ADR-0002; the sidecar routes are removed) ---
async harvestPreview(data: unknown, source: string): Promise<any> {
const res = await this.fetch('/api/harvest/preview', { method: 'POST', body: JSON.stringify({ data, source }) });
return res.json();
@@ -3756,11 +3673,6 @@ class LocalAdapter {
return res.json();
}
async getWikiWatermark(): Promise<any> {
const res = await this.fetch('/api/wiki/watermark');
return res.json();
}
/**
* M-12: export all compiled wiki pages to an Obsidian-shaped directory.
* `outDir` must be an absolute path. Writes `_index.md` at the root and