The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
fix(providers): correct identity flip logic in CoreStateProvider
Steven Enamakel1f7f794fd8ed
diff --git a/app/src/components/settings/panels/useReembedBackfillModal.test.tsx b/app/src/components/settings/panels/useReembedBackfillModal.test.tsxdeleted file mode 100644index fd59574e68..0000000000--- a/app/src/components/settings/panels/useReembedBackfillModal.test.tsx+++ /dev/null@@ -1,111 +0,0 @@-import { act, renderHook } from '@testing-library/react';-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';--import { callCoreRpc } from '../../../services/coreRpcClient';-import { useReembedBackfillModal } from './useReembedBackfillModal';--vi.mock('../../../services/coreRpcClient', () => ({ callCoreRpc: vi.fn() }));--const status = vi.mocked(callCoreRpc);--beforeEach(() => {- vi.clearAllMocks();-});-afterEach(() => {- vi.useRealTimers();-});--describe('useReembedBackfillModal (#1574 §4b)', () => {- it('does not check status or open the modal when save fails', async () => {- const save = vi.fn().mockResolvedValue(false);- const { result } = renderHook(() => useReembedBackfillModal(save));-- await act(async () => {- await result.current.handleSave();- });-- expect(save).toHaveBeenCalledTimes(1);- expect(status).not.toHaveBeenCalled();- expect(result.current.reembed).toEqual({ open: false, pending: 0 });- });-- it('opens the modal when save succeeds and a backfill is in progress', async () => {- const save = vi.fn().mockResolvedValue(true);- status.mockResolvedValue({ in_progress: true, pending_jobs: 7 });- const { result } = renderHook(() => useReembedBackfillModal(save));-- await act(async () => {- await result.current.handleSave();- });-- expect(result.current.reembed).toEqual({ open: true, pending: 7 });- });-- it('stays closed when save succeeds but no backfill is in progress', async () => {- const save = vi.fn().mockResolvedValue(true);- status.mockResolvedValue({ in_progress: false, pending_jobs: 0 });- const { result } = renderHook(() => useReembedBackfillModal(save));-- await act(async () => {- await result.current.handleSave();- });-- expect(result.current.reembed.open).toBe(false);- });-- it('swallows a status-check error and stays closed', async () => {- const save = vi.fn().mockResolvedValue(true);- status.mockRejectedValue(new Error('rpc down'));- const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});- const { result } = renderHook(() => useReembedBackfillModal(save));-- await act(async () => {- await result.current.handleSave();- });-- expect(result.current.reembed.open).toBe(false);- expect(warn).toHaveBeenCalled();- warn.mockRestore();- });-- it('polls while open: updates pending, then auto-closes when the backfill drains', async () => {- vi.useFakeTimers();- const save = vi.fn().mockResolvedValue(true);- status- .mockResolvedValueOnce({ in_progress: true, pending_jobs: 9 }) // handleSave open- .mockResolvedValueOnce({ in_progress: true, pending_jobs: 4 }) // poll #1- .mockResolvedValueOnce({ in_progress: false, pending_jobs: 0 }); // poll #2 → close- const { result } = renderHook(() => useReembedBackfillModal(save));-- await act(async () => {- await result.current.handleSave();- });- expect(result.current.reembed).toEqual({ open: true, pending: 9 });-- await act(async () => {- await vi.advanceTimersByTimeAsync(2000);- });- expect(result.current.reembed.pending).toBe(4);-- await act(async () => {- await vi.advanceTimersByTimeAsync(2000);- });- expect(result.current.reembed.open).toBe(false);- });-- it('dismissReembed closes the modal (background backfill unaffected)', async () => {- const save = vi.fn().mockResolvedValue(true);- status.mockResolvedValue({ in_progress: true, pending_jobs: 2 });- const { result } = renderHook(() => useReembedBackfillModal(save));-- await act(async () => {- await result.current.handleSave();- });- expect(result.current.reembed.open).toBe(true);-- act(() => {- result.current.dismissReembed();- });- expect(result.current.reembed).toEqual({ open: false, pending: 0 });- });-});diff --git a/app/src/components/settings/panels/useReembedBackfillModal.ts b/app/src/components/settings/panels/useReembedBackfillModal.tsdeleted file mode 100644index c4feb52dbc..0000000000--- a/app/src/components/settings/panels/useReembedBackfillModal.ts+++ /dev/null@@ -1,103 +0,0 @@-/**- * #1574 §4b: advisory re-embed-backfill modal state, driven entirely by the- * backend status RPC.- *- * After a settings save, the core's coverage-gated `ensure_reembed_backfill`- * has already decided whether the embedder change needs a re-embed; this hook- * just surfaces its progress (no fragile frontend "did the embedder change"- * detection). Extracted from `AIPanel` so the logic is unit-testable in- * isolation rather than only via a full 2000-line component render.- */-import { useCallback, useEffect, useState } from 'react';--import { callCoreRpc } from '../../../services/coreRpcClient';--/** `openhuman.memory_tree_backfill_status` — the core's re-embed progress. */-interface BackfillStatus {- in_progress: boolean;- pending_jobs: number;-}--/**- * Read the core's re-embed backfill progress. Kept local to this hook: it is- * the embeddings panel's only consumer, and the v1 memory-tree client that- * used to wrap it was retired with Memory v2. A core without the method makes- * this reject, which `handleSave` treats as "nothing to surface".- */-async function memoryTreeBackfillStatus(): Promise<BackfillStatus> {- const raw = await callCoreRpc<BackfillStatus | { result: BackfillStatus }>({- method: 'openhuman.memory_tree_backfill_status',- });- return raw && typeof raw === 'object' && 'result' in raw ? raw.result : raw;-}--interface ReembedState {- open: boolean;- pending: number;-}--interface ReembedBackfillModal {- reembed: ReembedState;- /** Wrap a settings-save: persist, then (only on success) surface re-embed progress. */- handleSave: () => Promise<void>;- /** Close the advisory modal (re-embed continues in the background). */- dismissReembed: () => void;-}--const POLL_MS = 2000;--/**- * @param save Persists settings; resolves `true` only on a successful write- * (a failed save did not change the embedder, so nothing to surface).- */-export function useReembedBackfillModal(save: () => Promise<boolean>): ReembedBackfillModal {- const [reembed, setReembed] = useState<ReembedState>({ open: false, pending: 0 });-- const handleSave = useCallback(async () => {- const ok = await save();- if (!ok) return;- try {- const st = await memoryTreeBackfillStatus();- if (st.in_progress) {- setReembed({ open: true, pending: st.pending_jobs });- }- } catch (e) {- console.warn('[ai-panel] backfill status check failed', e);- }- }, [save]);-- const dismissReembed = useCallback(() => setReembed({ open: false, pending: 0 }), []);-- useEffect(() => {- if (!reembed.open) return;- let cancelled = false;- // Serialize polls — if a status call takes >POLL_MS, skip the next tick- // rather than overlapping requests.- let inFlight = false;- const id = window.setInterval(() => {- if (inFlight) return;- inFlight = true;- void (async () => {- try {- const st = await memoryTreeBackfillStatus();- if (cancelled) return;- if (!st.in_progress) {- setReembed({ open: false, pending: 0 });- } else {- setReembed(r => ({ ...r, pending: st.pending_jobs }));- }- } catch (e) {- console.warn('[ai-panel] backfill poll failed', e);- } finally {- inFlight = false;- }- })();- }, POLL_MS);- return () => {- cancelled = true;- window.clearInterval(id);- };- }, [reembed.open]);-- return { reembed, handleSave, dismissReembed };-}diff --git a/app/src/providers/CoreStateProvider.tsx b/app/src/providers/CoreStateProvider.tsxindex 89f86eafa8..762a6f43a2 100644--- a/app/src/providers/CoreStateProvider.tsx+++ b/app/src/providers/CoreStateProvider.tsx@@ -40,7 +40,6 @@ import {restartApp,setOnboardingCompleted,storeSession,- syncMemoryClientToken,logout as tauriLogout,} from '../utils/tauriCommands';import { CoreStateContext, type CoreStateContextValue } from './coreStateContext';@@ -266,7 +265,6 @@ export default function CoreStateProvider({ children }: { children: ReactNode })const [state, setState] = useState<CoreState>(() => getCoreStateSnapshot());const snapshotRequestIdRef = useRef(0);const teamsRequestIdRef = useRef(0);- const memoryTokenRef = useRef<string | null>(state.snapshot.sessionToken);const logoutGuardUntilRef = useRef(0);const bootstrapFailCountRef = useRef(0);const refreshInFlightRef = useRef<Promise<void> | null>(null);@@ -456,19 +454,6 @@ export default function CoreStateProvider({ children }: { children: ReactNode })// right namespace and the active user id is already correct.syncAnalyticsConsent(snapshot.analyticsEnabled);- if (!snapshot.sessionToken) {- memoryTokenRef.current = null;- return;- }-- if (memoryTokenRef.current !== snapshot.sessionToken) {- try {- await syncMemoryClientToken(snapshot.sessionToken);- memoryTokenRef.current = snapshot.sessionToken;- } catch (error) {- console.warn('[core-state] memory client sync failed during refresh:', error);- }- }}, [commitState, t]);/** Serialized refresh — all callers share the same in-flight promise. */@@ -698,12 +683,6 @@ export default function CoreStateProvider({ children }: { children: ReactNode })sessionTokenBeingStoredRef.current = token;try {await storeSession(token, user ?? {});- try {- await syncMemoryClientToken(token);- memoryTokenRef.current = token;- } catch (error) {- console.warn('[core-state] memory client sync failed after session store:', error);- }// refresh() drives refreshCore, which now owns identity-flip detection// and dispatches handleIdentityFlip when both prev and next are// authenticated and identities differ. The previous standalone@@ -778,7 +757,6 @@ export default function CoreStateProvider({ children }: { children: ReactNode })teamInvitesById: {},snapshot: toSignedOutSnapshot(previous.snapshot),}));- memoryTokenRef.current = null;// Keep `OPENHUMAN_ACTIVE_USER_ID` pointing at the last user. The next// refresh's `getActiveUserId()` seed comparison decides whether the// upcoming login is a same-user re-login (no restart) or a different-diff --git a/app/src/providers/__tests__/CoreStateProvider.identityFlip.test.tsx b/app/src/providers/__tests__/CoreStateProvider.identityFlip.test.tsxindex 88ba9b5906..50cae67d34 100644--- a/app/src/providers/__tests__/CoreStateProvider.identityFlip.test.tsx+++ b/app/src/providers/__tests__/CoreStateProvider.identityFlip.test.tsx@@ -20,7 +20,6 @@ vi.mock('../../utils/tauriCommands', () => ({restartApp: vi.fn().mockResolvedValue(undefined),setOnboardingCompleted: vi.fn(),storeSession: vi.fn().mockResolvedValue(undefined),- syncMemoryClientToken: vi.fn().mockResolvedValue(undefined),logout: vi.fn().mockResolvedValue(undefined),}));diff --git a/app/src/providers/__tests__/CoreStateProvider.test.tsx b/app/src/providers/__tests__/CoreStateProvider.test.tsxindex ef660c7aba..571c552163 100644--- a/app/src/providers/__tests__/CoreStateProvider.test.tsx+++ b/app/src/providers/__tests__/CoreStateProvider.test.tsx@@ -916,8 +916,6 @@ describe('CoreStateProvider — identity-change cache clearing', () => {listTeams.mockResolvedValue([]);vi.mocked(tauriCommands.storeSession).mockReset();vi.mocked(tauriCommands.storeSession).mockResolvedValue(undefined as never);- vi.mocked(tauriCommands.syncMemoryClientToken).mockReset();- vi.mocked(tauriCommands.syncMemoryClientToken).mockResolvedValue(undefined as never);let ctx: CoreStateContextValue | undefined;render(diff --git a/app/src/test/setup.ts b/app/src/test/setup.tsindex 7fb49a5577..e8653227b4 100644--- a/app/src/test/setup.ts+++ b/app/src/test/setup.ts@@ -252,7 +252,6 @@ vi.mock('../utils/tauriCommands', () => ({getSessionToken: vi.fn().mockResolvedValue(null),getAuthState: vi.fn().mockResolvedValue({ is_authenticated: false }),logout: vi.fn().mockResolvedValue(undefined),- syncMemoryClientToken: vi.fn().mockResolvedValue(undefined),openhumanServiceInstall: vi.fn().mockResolvedValue({ result: { state: 'Running' }, logs: [] }),openhumanServiceStart: vi.fn().mockResolvedValue({ result: { state: 'Running' }, logs: [] }),openhumanServiceStop: vi.fn().mockResolvedValue({ result: { state: 'Stopped' }, logs: [] }),diff --git a/app/src/utils/__tests__/tauriCommandsMemory.test.ts b/app/src/utils/__tests__/tauriCommandsMemory.test.tsdeleted file mode 100644index 47d0d1dbc4..0000000000--- a/app/src/utils/__tests__/tauriCommandsMemory.test.ts+++ /dev/null@@ -1,118 +0,0 @@-import { describe, expect, it, vi } from 'vitest';--import { memoryDocIngest, memoryGraphQuery } from '../tauriCommands';--// The global setup mocks isTauri to return false by default.-// We need to selectively override it for these tests.--// Re-mock tauriCommands so we can test the actual implementations-// rather than the blanket mock from setup.ts.-vi.mock('../tauriCommands', async () => {- const actual = await vi.importActual<Record<string, unknown>>('../tauriCommands');- return actual;-});--// Mock @tauri-apps/api/core — isTauri controls the guard in each function-const mockIsTauri = vi.fn(() => false);-vi.mock('@tauri-apps/api/core', () => ({ invoke: vi.fn(), isTauri: () => mockIsTauri() }));--// Mock callCoreRpc — the underlying transport for all memory commands-const mockCallCoreRpc = vi.fn();-vi.mock('../../services/coreRpcClient', () => ({- callCoreRpc: (...args: unknown[]) => mockCallCoreRpc(...args),-}));--describe('memoryGraphQuery', () => {- it('calls core RPC when not running in Tauri', async () => {- mockIsTauri.mockReturnValue(false);- mockCallCoreRpc.mockResolvedValue([]);- await memoryGraphQuery();- expect(mockCallCoreRpc).toHaveBeenCalled();- });-- it('calls core RPC with memory.graph.query method and optional params', async () => {- mockIsTauri.mockReturnValue(true);- const mockRelations = [- {- namespace: 'team',- subject: 'Alice',- predicate: 'OWNS',- object: 'Atlas',- attrs: {},- updatedAt: 1700000000,- evidenceCount: 2,- orderIndex: null,- documentIds: ['doc-1'],- chunkIds: ['doc-1#chunk-1'],- },- ];- mockCallCoreRpc.mockResolvedValue(mockRelations);-- const result = await memoryGraphQuery('team', 'Alice', 'OWNS');-- expect(mockCallCoreRpc).toHaveBeenCalledWith({- method: 'openhuman.memory_graph_query',- params: { namespace: 'team', subject: 'Alice', predicate: 'OWNS' },- });- expect(result).toEqual(mockRelations);- });-- it('passes undefined params when called with no arguments', async () => {- mockIsTauri.mockReturnValue(true);- mockCallCoreRpc.mockResolvedValue([]);-- await memoryGraphQuery();-- expect(mockCallCoreRpc).toHaveBeenCalledWith({- method: 'openhuman.memory_graph_query',- params: { namespace: undefined, subject: undefined, predicate: undefined },- });- });-});--describe('memoryDocIngest', () => {- it('calls core RPC when not running in Tauri', async () => {- mockIsTauri.mockReturnValue(false);- mockCallCoreRpc.mockResolvedValue([]);- await memoryDocIngest({ namespace: 'ns', key: 'k', title: 't', content: 'c' });- expect(mockCallCoreRpc).toHaveBeenCalled();- });-- it('calls core RPC with memory.doc.ingest and forwards all params', async () => {- mockIsTauri.mockReturnValue(true);- const ingestResult = {- document_id: 'doc-123',- entity_count: 3,- relation_count: 2,- chunk_count: 5,- };- mockCallCoreRpc.mockResolvedValue(ingestResult);-- const params = {- namespace: 'research',- key: 'paper-1',- title: 'Memory Paper',- content: 'Some content about memory systems',- source_type: 'paper',- priority: 'high',- tags: ['memory', 'ai'],- metadata: { author: 'Alice' },- category: 'research',- };-- const result = await memoryDocIngest(params);-- expect(mockCallCoreRpc).toHaveBeenCalledWith({ method: 'openhuman.memory_doc_ingest', params });- expect(result).toEqual(ingestResult);- });-- it('sends only required fields when optional fields are omitted', async () => {- mockIsTauri.mockReturnValue(true);- mockCallCoreRpc.mockResolvedValue({});-- const params = { namespace: 'ns', key: 'k', title: 't', content: 'c' };- await memoryDocIngest(params);-- expect(mockCallCoreRpc).toHaveBeenCalledWith({ method: 'openhuman.memory_doc_ingest', params });- });-});diff --git a/app/src/utils/tauriCommands/index.ts b/app/src/utils/tauriCommands/index.tsindex 07f8553169..17fa86f444 100644--- a/app/src/utils/tauriCommands/index.ts+++ b/app/src/utils/tauriCommands/index.ts@@ -5,7 +5,6 @@ export * from './common';export * from './auth';export * from './window';export * from './core';-export * from './memory';export * from './composio';export * from './conscious';export * from './localAi';diff --git a/app/src/utils/tauriCommands/memory.test.ts b/app/src/utils/tauriCommands/memory.test.tsdeleted file mode 100644index e242632b30..0000000000--- a/app/src/utils/tauriCommands/memory.test.ts+++ /dev/null@@ -1,159 +0,0 @@-/**- * Unit tests for memory RPC wrappers: memorySyncChannel, memorySyncAll, memoryLearnAll.- */-import { beforeEach, describe, expect, type Mock, test, vi } from 'vitest';--import { callCoreRpc } from '../../services/coreRpcClient';-import { isTauri } from './common';-import { aiListMemoryFiles, memoryLearnAll, memorySyncAll, memorySyncChannel } from './memory';--vi.mock('../../services/coreRpcClient', () => ({ callCoreRpc: vi.fn() }));-vi.mock('./common', () => ({ isTauri: vi.fn(() => true), safeInvoke: vi.fn() }));--const mockCallCoreRpc = callCoreRpc as Mock;-const mockIsTauri = isTauri as Mock;--beforeEach(() => {- vi.clearAllMocks();- mockIsTauri.mockReturnValue(true);-});--describe('memorySyncChannel', () => {- test('calls core RPC outside Tauri', async () => {- mockIsTauri.mockReturnValue(false);- mockCallCoreRpc.mockResolvedValue({});- await memorySyncChannel('ch-1');- expect(mockCallCoreRpc).toHaveBeenCalled();- });-- test('calls memory_sync_channel with correct channel_id', async () => {- const mockResp = { requested: true, channel_id: 'ch-1' };- mockCallCoreRpc.mockResolvedValueOnce(mockResp);-- const result = await memorySyncChannel('ch-1');-- expect(mockCallCoreRpc).toHaveBeenCalledWith({- method: 'openhuman.memory_sync_channel',- params: { channel_id: 'ch-1' },- });- expect(result).toEqual(mockResp);- });-});--describe('memorySyncAll', () => {- test('calls core RPC outside Tauri', async () => {- mockIsTauri.mockReturnValue(false);- mockCallCoreRpc.mockResolvedValue({});- await memorySyncAll();- expect(mockCallCoreRpc).toHaveBeenCalled();- });-- test('calls memory_sync_all and returns result', async () => {- mockCallCoreRpc.mockResolvedValueOnce({ requested: true });-- const result = await memorySyncAll();-- expect(mockCallCoreRpc).toHaveBeenCalledWith({ method: 'openhuman.memory_sync_all' });- expect(result).toEqual({ requested: true });- });-});--describe('memoryLearnAll', () => {- test('calls core RPC outside Tauri', async () => {- mockIsTauri.mockReturnValue(false);- mockCallCoreRpc.mockResolvedValue({});- await memoryLearnAll();- expect(mockCallCoreRpc).toHaveBeenCalled();- });-- test('calls memory_learn_all without namespaces param when none provided', async () => {- const mockResp = { namespaces_processed: 0, results: [] };- mockCallCoreRpc.mockResolvedValueOnce(mockResp);-- const result = await memoryLearnAll();-- expect(mockCallCoreRpc).toHaveBeenCalledWith({- method: 'openhuman.memory_learn_all',- params: {},- });- expect(result.namespaces_processed).toBe(0);- });-- test('includes namespaces param when provided', async () => {- const mockResp = {- namespaces_processed: 1,- results: [{ namespace: 'research', status: 'ok' }],- };- mockCallCoreRpc.mockResolvedValueOnce(mockResp);-- const result = await memoryLearnAll(['research']);-- expect(mockCallCoreRpc).toHaveBeenCalledWith({- method: 'openhuman.memory_learn_all',- params: { namespaces: ['research'] },- });- expect(result.namespaces_processed).toBe(1);- expect(result.results[0].status).toBe('ok');- });-- test('returns aggregated error results without throwing', async () => {- const mockResp = {- namespaces_processed: 2,- results: [- { namespace: 'ns-a', status: 'ok' },- { namespace: 'ns-b', status: 'error', error: 'local AI not enabled' },- ],- };- mockCallCoreRpc.mockResolvedValueOnce(mockResp);-- const result = await memoryLearnAll();-- expect(result.namespaces_processed).toBe(2);- const errEntry = result.results.find(r => r.status === 'error');- expect(errEntry?.namespace).toBe('ns-b');- expect(errEntry?.error).toContain('local AI');- });-});--describe('aiListMemoryFiles', () => {- test('defaults relative_dir to empty string (list memory root)', async () => {- // Regression guard: the wrapper used to default to 'memory', and- // the Rust resolver joined that onto `<workspace>/memory/`,- // producing the doomed `<workspace>/memory/memory` path. Empty- // string is the resolver's "the memory root" sentinel.- mockCallCoreRpc.mockResolvedValueOnce({ data: { files: ['a.md', 'b.md'] } });-- const files = await aiListMemoryFiles();-- expect(mockCallCoreRpc).toHaveBeenCalledWith({- method: 'openhuman.memory_list_files',- params: { relative_dir: '' },- });- expect(files).toEqual(['a.md', 'b.md']);- });-- test('forwards an explicit relativeDir verbatim', async () => {- mockCallCoreRpc.mockResolvedValueOnce({ files: ['nested.md'] });- const files = await aiListMemoryFiles('subdir');- expect(mockCallCoreRpc).toHaveBeenCalledWith({- method: 'openhuman.memory_list_files',- params: { relative_dir: 'subdir' },- });- expect(files).toEqual(['nested.md']);- });-- test('returns [] when the response has no recognisable files array', async () => {- mockCallCoreRpc.mockResolvedValueOnce(null);- expect(await aiListMemoryFiles()).toEqual([]);-- mockCallCoreRpc.mockResolvedValueOnce({ unrelated: 'shape' });- expect(await aiListMemoryFiles()).toEqual([]);- });-- test('calls core RPC when not running in Tauri', async () => {- mockIsTauri.mockReturnValue(false);- mockCallCoreRpc.mockResolvedValue({});- await aiListMemoryFiles();- expect(mockCallCoreRpc).toHaveBeenCalled();- });-});diff --git a/app/src/utils/tauriCommands/memory.ts b/app/src/utils/tauriCommands/memory.tsdeleted file mode 100644index 85a06d47d7..0000000000--- a/app/src/utils/tauriCommands/memory.ts+++ /dev/null@@ -1,302 +0,0 @@-/**- * Memory subsystem commands.- */-import { callCoreRpc } from '../../services/coreRpcClient';--export interface MemoryDebugDocument {- documentId: string;- namespace: string;- title?: string;- raw: unknown;-}--/** A single entity returned in the structured retrieval context. */-export interface MemoryRetrievalEntity {- id?: string;- name: string;- entity_type?: string;- score?: number;- metadata?: unknown;-}--/** Structured retrieval context returned alongside `llm_context_message`. */-export interface MemoryRetrievalContext {- entities: MemoryRetrievalEntity[];- relations: { subject: string; predicate: string; object: string; score?: number }[];- chunks: { content: string; score: number; chunk_id?: string; document_id?: string }[];-}--/** Result of a memory query or recall, combining text and structured data. */-export interface MemoryQueryResult {- text: string;- entities: MemoryRetrievalEntity[];-}--/**- * Raw envelope shape returned by `openhuman.memory_query_namespace` and- * `openhuman.memory_recall_context` via the registry-based RPC handler.- */-interface MemoryQueryEnvelope {- data?: { llm_context_message?: string | null; context?: MemoryRetrievalContext | null };- llm_context_message?: string | null;- context?: MemoryRetrievalContext | null;-}--/** Extract text + entities from the envelope returned by query/recall RPCs. */-function unwrapMemoryQueryResult(resp: unknown): MemoryQueryResult {- // If the response is already a plain string, return it directly.- if (typeof resp === 'string') {- return { text: resp, entities: [] };- }-- const envelope = resp as MemoryQueryEnvelope | null;- if (!envelope || typeof envelope !== 'object') {- return { text: '', entities: [] };- }-- // Envelope may be `{ data: { llm_context_message, context } }` or flat.- const inner = envelope.data ?? envelope;- const text = inner.llm_context_message ?? '';- const entities = inner.context?.entities ?? [];-- return { text, entities };-}--export interface GraphRelation {- namespace: string | null;- subject: string;- predicate: string;- object: string;- attrs: Record<string, unknown>;- updatedAt: number;- evidenceCount: number;- orderIndex: number | null;- documentIds: string[];- chunkIds: string[];-}--/**- * Initialise the local-only (SQLite) memory subsystem in the Rust core.- */-export async function syncMemoryClientToken(token: string): Promise<void> {- console.debug('[memory] syncMemoryClientToken: entry (token_present=%s)', !!token);- try {- console.debug('[memory] syncMemoryClientToken: payload → memory.init (local-only)');- // jwt_token is passed for backward compatibility but ignored by the core.- await callCoreRpc<boolean>({ method: 'openhuman.memory_init', params: { jwt_token: token } });- console.info('[memory] syncMemoryClientToken: exit — ok');- } catch (err) {- console.warn('[memory] syncMemoryClientToken: exit — error:', err);- }-}--export async function memoryListDocuments(namespace?: string): Promise<unknown> {- const resp = await callCoreRpc<unknown>({- method: 'openhuman.memory_list_documents',- params: { namespace },- });- // Unwrap envelope: registry returns { data: { documents: [...] }, meta: {...} }- if (resp && typeof resp === 'object' && !Array.isArray(resp) && 'data' in resp) {- return (resp as Record<string, unknown>).data;- }- return resp;-}--export async function memoryListNamespaces(): Promise<string[]> {- const resp = await callCoreRpc<{ data?: { namespaces?: string[] }; namespaces?: string[] }>({- method: 'openhuman.memory_list_namespaces',- });- if (resp && typeof resp === 'object') {- if (Array.isArray(resp)) return resp;- const ns = resp.data?.namespaces ?? resp.namespaces;- if (Array.isArray(ns)) return ns;- }- return [];-}--export async function memoryDeleteDocument(- documentId: string,- namespace: string-): Promise<unknown> {- return await callCoreRpc<unknown>({- method: 'openhuman.memory_delete_document',- params: { document_id: documentId, namespace },- });-}--export async function memoryClearNamespace(- namespace: string-): Promise<{ cleared: boolean; namespace: string }> {- const response = await callCoreRpc<{ result: { cleared: boolean; namespace: string } }>({- method: 'openhuman.memory_clear_namespace',- params: { namespace },- });- return response.result;-}--export async function memoryQueryNamespace(- namespace: string,- query: string,- maxChunks?: number-): Promise<MemoryQueryResult> {- const resp = await callCoreRpc<unknown>({- method: 'openhuman.memory_query_namespace',- params: { namespace, query, max_chunks: maxChunks },- });- return unwrapMemoryQueryResult(resp);-}--export async function memoryRecallNamespace(- namespace: string,- maxChunks?: number-): Promise<MemoryQueryResult> {- const resp = await callCoreRpc<unknown>({- method: 'openhuman.memory_recall_context',- params: { namespace, max_chunks: maxChunks },- });- return unwrapMemoryQueryResult(resp);-}--export async function memoryGraphQuery(- namespace?: string,- subject?: string,- predicate?: string-): Promise<GraphRelation[]> {- const raw = await callCoreRpc<GraphRelation[] | { result: GraphRelation[] }>({- method: 'openhuman.memory_graph_query',- params: { namespace, subject, predicate },- });- // Outcome wraps with { result, logs } when logs are present — unwrap if needed.- if (Array.isArray(raw)) return raw;- if (raw && typeof raw === 'object' && 'result' in raw && Array.isArray(raw.result))- return raw.result;- console.debug(- '[memoryGraphQuery] unexpected response shape, returning empty array. Raw response:',- raw- );- return [];-}--export async function memoryDocIngest(params: {- namespace: string;- key: string;- title: string;- content: string;- source_type?: string;- priority?: string;- tags?: string[];- metadata?: Record<string, unknown>;- category?: string;- session_id?: string;- document_id?: string;-}): Promise<unknown> {- return await callCoreRpc<unknown>({ method: 'openhuman.memory_doc_ingest', params });-}--/**- * List files inside the workspace memory root. `relativeDir` is- * resolved relative to `<workspace>/memory/`, so an empty string- * means "list the memory root" — which is what most callers want.- *- * Historical bug (pre-#TBD): the default was `'memory'`, which the- * Rust side then joined onto the already-rooted memory subdir,- * yielding `<workspace>/memory/memory` and a "No such file" error- * the moment the hook polled. The Rust resolver intentionally- * accepts `""` as "the memory root", so default to that.- */-export async function aiListMemoryFiles(relativeDir = ''): Promise<string[]> {- const resp = await callCoreRpc<{ data?: { files?: string[] }; files?: string[] }>({- method: 'openhuman.memory_list_files',- params: { relative_dir: relativeDir },- });- // Unwrap envelope: registry returns { data: { files: [...] } }- if (resp && typeof resp === 'object') {- if (Array.isArray(resp)) return resp;- const files = resp.data?.files ?? resp.files;- if (Array.isArray(files)) return files;- }- return [];-}--export async function aiReadMemoryFile(relativePath: string): Promise<string> {- const resp = await callCoreRpc<{ data?: { content?: string }; content?: string } | string>({- method: 'openhuman.memory_read_file',- params: { relative_path: relativePath },- });- if (typeof resp === 'string') return resp;- if (resp && typeof resp === 'object') {- return resp.data?.content ?? resp.content ?? '';- }- return '';-}--export async function aiWriteMemoryFile(relativePath: string, content: string): Promise<void> {- await callCoreRpc<boolean>({- method: 'openhuman.memory_write_file',- params: { relative_path: relativePath, content },- });-}--export interface MemorySyncChannelResult {- requested: boolean;- channel_id: string;-}--export interface MemorySyncAllResult {- requested: boolean;-}--export interface NamespaceLearnResult {- namespace: string;- status: 'ok' | 'skipped' | 'error';- error?: string;-}--export interface MemoryLearnAllResult {- namespaces_processed: number;- results: NamespaceLearnResult[];-}--/**- * Request a memory sync for a specific channel.- * Publishes MemorySyncRequested on the core event bus and returns confirmation.- * No ingestion runs synchronously — future subscribers will react.- */-export async function memorySyncChannel(channelId: string): Promise<MemorySyncChannelResult> {- console.debug('[memory.sync] memorySyncChannel: entry channel_id=%s', channelId);- const resp = await callCoreRpc<MemorySyncChannelResult>({- method: 'openhuman.memory_sync_channel',- params: { channel_id: channelId },- });- console.debug('[memory.sync] memorySyncChannel: exit result=%o', resp);- return resp;-}--/**- * Request a memory sync for all channels.- * Publishes MemorySyncRequested { channel_id: None } on the core event bus.- */-export async function memorySyncAll(): Promise<MemorySyncAllResult> {- console.debug('[memory.sync] memorySyncAll: entry');- const resp = await callCoreRpc<MemorySyncAllResult>({ method: 'openhuman.memory_sync_all' });- console.debug('[memory.sync] memorySyncAll: exit result=%o', resp);- return resp;-}--/**- * Run the tree summarizer over all memory namespaces (or a subset).- * Processes sequentially; a failing namespace is recorded, not fatal.- */-export async function memoryLearnAll(namespaces?: string[]): Promise<MemoryLearnAllResult> {- console.debug('[memory.learn] memoryLearnAll: entry namespaces=%o', namespaces);- const params: Record<string, unknown> = {};- if (namespaces && namespaces.length > 0) {- params.namespaces = namespaces;- }- const resp = await callCoreRpc<MemoryLearnAllResult>({- method: 'openhuman.memory_learn_all',- params,- });- console.debug('[memory.learn] memoryLearnAll: exit processed=%d', resp?.namespaces_processed);- return resp;-}