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

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

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

View File

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

View File

@@ -1,7 +1,7 @@
// Pure display mapping for the canonical PRD §15.2 `MemoryKind` vocabulary (B6).
//
// `MemoryKind` is the single source of truth for memory typing (defined once in
// `@waggle/shared`). This module maps each kind to (a) a human label for Memory
// `@waggle/shared`, mirroring the memory contract's kinds). This module maps each kind to (a) a human label for Memory
// Center filter chips / cards (S04) and (b) an onboarding Memory Review grouping
// bucket (S16). The server-side `ImportItemType → MemoryKind` normalization lives
// in the sidecar harvest layer (Phase 2B), NOT here — the build order forbids
@@ -25,13 +25,12 @@ interface MemoryKindMeta {
export const MEMORY_KIND_META: Record<MemoryKind, MemoryKindMeta> = {
fact: { label: 'Fact', category: 'Memories' },
decision: { label: 'Decision', category: 'Decisions' },
task: { label: 'Task', category: 'Tasks' },
event: { label: 'Event', category: 'Memories' },
preference: { label: 'Preference', category: 'Memories' },
strategy: { label: 'Strategy', category: 'Projects' },
learning: { label: 'Learning', category: 'Memories' },
goal: { label: 'Goal', category: 'Projects' },
entity: { label: 'Entity', category: 'Memories' },
profile: { label: 'About you', category: 'Memories' },
decision: { label: 'Decision', category: 'Decisions' },
summary: { label: 'Summary', category: 'Projects' },
note: { label: 'Note', category: 'Tasks' },
};
export function memoryKindLabel(kind: MemoryKind): string {

View File

@@ -1,11 +1,16 @@
/**
* Memory features the UI may show (ADR-0002).
*
* v1 memory is facts, search and the user profile. The features below are
* hidden, not deleted: their screens stay in the code and every surface that
* offers one checks this map first. A later work package fills the map from
* the server's memory capability map, so read it only through this module.
* v1 memory is facts, search and the user profile. The knowledge graph follows
* the server's memory capability map (`GET /api/memory/capabilities`), which
* reports it unavailable in v1. History import, wiki, coding-agent hooks, Room
* and the memory MCP server are hidden in v1 by decision, whatever the store
* supports. Their screens stay in the code and every surface that offers one
* checks this module first.
*/
import { useEffect, useSyncExternalStore } from 'react';
import { adapter } from '@/lib/adapter';
import type { MemoryCapabilitiesResponse } from '@/lib/types';
export interface MemoryFeatures {
/** Knowledge graph (entities and relations). Deferred to a later release. */
@@ -24,8 +29,8 @@ export interface MemoryFeatures {
export type MemoryFeature = keyof MemoryFeatures;
const MEMORY_FEATURES: Readonly<MemoryFeatures> = {
knowledgeGraph: false,
/** Hidden in v1 (ADR-0002) regardless of the memory store. */
const HIDDEN_IN_V1: Readonly<Record<Exclude<MemoryFeature, 'knowledgeGraph'>, false>> = {
importHistory: false,
wiki: false,
agentHooks: false,
@@ -33,8 +38,14 @@ const MEMORY_FEATURES: Readonly<MemoryFeatures> = {
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 {
return MEMORY_FEATURES[feature];
if (feature === 'knowledgeGraph') return current?.capabilities.knowledgeGraph === true;
return HIDDEN_IN_V1[feature];
}
/** Memory Center views (`?tab=`) that belong to a hidden feature. */
@@ -49,3 +60,40 @@ export function isMemoryViewAvailable(view: string): boolean {
const feature = MEMORY_VIEW_FEATURE[view];
return feature === undefined || hasMemoryFeature(feature);
}
/** Store a capability report (after a load, or the response of a settings change). */
export function setMemoryCapabilities(next: MemoryCapabilitiesResponse | null): void {
current = next;
for (const listener of listeners) listener();
}
/** Fetch the capability report once; a failed fetch is retried on the next call. */
export function loadMemoryCapabilities(): Promise<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
* 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
* MemoryFrame shape is owned by adapter.ts which performs camelCase + frameType
* code mapping. Keep bindings raw to prevent two normalization paths drifting.
* MemoryFrame shape is owned by adapter.ts, which maps kind and importance.
* Keep bindings raw to prevent two normalization paths drifting.
*/
export interface RecallMemoryResponse {
results: Array<Record<string, unknown>>;

View File

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