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(memory): make a corrupt memory-tree store fatal, visible, and recoverable
Shanu05bba7fe4d6d
diff --git a/.claude/memory.md b/.claude/memory.mdindex 72233a80b0..82175753c0 100644--- a/.claude/memory.md+++ b/.claude/memory.md@@ -253,6 +253,16 @@ Quick reference for anyone starting with Claude on this project. Updated by the- **`tauri-cef` and `tauri-plugin-notification` are git submodules** — When upstream/main updates them, fix with `git submodule update --remote --checkout`, not by manually patching the vendored crate.+## Memory Corruption Handling (Issue #5820)++- **`tinymemory-core::corruption` is the one SQLITE_CORRUPT policy** — `is_sqlite_corrupt` / `escalate_or_count` / `report_and_recover` / `startup_integrity_check`. Every detector (queue worker, both tree-ingest sinks, reconcile, boot quick_check) escalates through it; do not add a local `warn!`-and-continue arm for corruption again.+- **Type forks to remember** — two `SyncOutcome`s (core `sync::pipelines::traits` vs tinycortex) and three `SyncAuditEntry` copies (core `sync::audit`, `tinymemory-bus`, tinycortex's engine writer). Only the core one carries `tree_ingest_failures`; `engine::run_source_pipeline_core` is the boundary that keeps it, `run_source_pipeline` drops it. New audit fields must be `skip_serializing_if` so the engine writer's rows stay byte-identical (`audit_line_format_is_pinned`).+- **Garbage-file corruption fixtures self-heal** — tinycortex's cold-open path (`connection.rs`) auto-quarantines a file that fails to open, so a garbage `chunks.db` makes `store()` succeed, not fail. Test the classification arm directly (`escalate_or_count`) instead of the full stack.+- **Module-side degraded statics never reach the host** — the pinned TinyMemory cdylib has its own `tree::health` statics; host visibility comes only from `MemoryEvent` (host arms in `memory/host.rs` + `modules/memory_host.rs` → `user_error` web channel). A new variant is release-gated (tinymemory release + registry re-pin) before the product sees it.+- **Worktree submodules can be half-initialised** — a timed-out `git submodule update --init --recursive` leaves `vendor/<x>/` holding only a `.git` file while `git submodule status` shows a clean SHA. Detect with `ls vendor/<x>/Cargo.toml`; fix with `git submodule update --force --recursive <path>`. tinymemory has its own nested `vendor/tinycortex` that must be initialised from inside `vendor/tinymemory`.+- **Never trust `cmd | tail` / `cmd | grep` exit codes in background checks** — the pipeline reports the filter's status, so a failed `cargo check` (disk full, missing submodule) read as green twice this session. Use `${PIPESTATUS[0]}` or grep for `Finished`.+- **Disk full (APFS) shows up as `could not compile syn` / `No space left on device`** — reclaim by deleting other checkouts' `target/` dirs (openhuman-1's shell target alone was 27 GB), never the active worktree's.+## Pre-existing Test Failures- **`composio::action_tool::tests::factory_routes_through_direct_when_mode_is_direct` fails in `cargo test -p openhuman`** — Pre-existing failure unrelated to WhatsApp or any recent branch work. Do not attempt to fix unless explicitly tasked. Also intermittently flaky when run as part of the full suite — see "Pre-existing Flaky Tests" section.diff --git a/app/src/components/intelligence/SyncAuditPanel.test.tsx b/app/src/components/intelligence/SyncAuditPanel.test.tsxindex 988edbc609..98c2f062f1 100644--- a/app/src/components/intelligence/SyncAuditPanel.test.tsx+++ b/app/src/components/intelligence/SyncAuditPanel.test.tsx@@ -128,6 +128,36 @@ describe('<SyncAuditPanel />', () => {expect(failGlyph).toHaveTextContent('✗');});+ it('renders the partial glyph when the fetch succeeded but tree ingest failed', async () => {+ // openhuman#5820: fetched items with a failed memory-tree half must not+ // read as plain failure (nothing fetched) and MUST not read as success.+ mockAuditLog.mockResolvedValue([+ entry({+ success: false,+ items_fetched: 250,+ tree_ingest_failures: 250,+ tree_error: '250 item(s) fetched but not ingested into the memory tree',+ source_id: 'partial',+ }),+ ]);+ render(<SyncAuditPanel />);++ const partialGlyph = await screen.findByTitle(+ '250 item(s) fetched but not ingested into the memory tree',+ );+ expect(partialGlyph).toHaveTextContent('⚠');+ });++ it('falls back to the partial label when the row has no tree_error text', async () => {+ mockAuditLog.mockResolvedValue([+ entry({ success: false, tree_ingest_failures: 3, source_id: 'partial-no-text' }),+ ]);+ render(<SyncAuditPanel />);++ const partialGlyph = await screen.findByTitle('Fetched, memory ingest failed');+ expect(partialGlyph).toHaveTextContent('⚠');+ });+it('renders the success glyph for successful runs', async () => {mockAuditLog.mockResolvedValue([entry({ success: true })]);render(<SyncAuditPanel />);diff --git a/app/src/components/intelligence/SyncAuditPanel.tsx b/app/src/components/intelligence/SyncAuditPanel.tsxindex 59e31d6094..2141fa0fc8 100644--- a/app/src/components/intelligence/SyncAuditPanel.tsx+++ b/app/src/components/intelligence/SyncAuditPanel.tsx@@ -162,6 +162,19 @@ export function SyncAuditPanel() {<span className="text-sage-500" title={t('sync.status.success', 'Success')}>✓</span>+ ) : (e.tree_ingest_failures ?? 0) > 0 || e.tree_error ? (+ // openhuman#5820: the fetch committed but the memory-tree+ // half dropped items — a distinct partial verdict, not the+ // plain ✗ (which reads as "nothing was fetched"). The+ // tooltip carries the core's tree_error so the row+ // explains itself.+ <span+ className="text-amber-500"+ title={+ e.tree_error ?? t('sync.status.partial', 'Fetched, memory ingest failed')+ }>+ ⚠+ </span>) : (<spanclassName="text-coral-500"diff --git a/app/src/components/notices/useAppNotices.ts b/app/src/components/notices/useAppNotices.tsindex 7455a5b190..3efe9fe088 100644--- a/app/src/components/notices/useAppNotices.ts+++ b/app/src/components/notices/useAppNotices.ts@@ -71,6 +71,9 @@ const ACTION_ROUTE: Record<Exclude<UserErrorAction, 'dismiss'>, string> = {// Opening this screen also restarts the integration health poll, so it is// both the explanation and the retry.open_connections: '/connections?tab=skills',+ // openhuman#5820: after a corrupt-store quarantine the rebuilt tree is+ // empty; re-syncing sources from Brain's sync tab is the remediation.+ open_memory_sync: '/brain?tab=sync',};const ACTION_LABEL_KEY: Record<Exclude<UserErrorAction, 'dismiss'>, string> = {@@ -78,6 +81,7 @@ const ACTION_LABEL_KEY: Record<Exclude<UserErrorAction, 'dismiss'>, string> = {open_provider_settings: 'userErrors.action.openProviderSettings',open_embeddings_settings: 'userErrors.action.openEmbeddingsSettings',open_connections: 'userErrors.action.openConnections',+ open_memory_sync: 'userErrors.action.openMemorySync',};const SEVERITY_RANK: Record<NoticeSeverity, number> = { error: 0, warning: 1, info: 2 };diff --git a/app/src/lib/i18n/ar.ts b/app/src/lib/i18n/ar.tsindex 86585e2338..6ffe23c479 100644--- a/app/src/lib/i18n/ar.ts+++ b/app/src/lib/i18n/ar.ts@@ -554,6 +554,7 @@ const messages: TranslationMap = {'sync.timeAgo.days': 'قبل {n} ي','sync.status.success': 'نجاح','sync.status.failed': 'فشل',+ 'sync.status.partial': 'تم الجلب، وفشل الإدراج في الذاكرة','common.error': 'خطأ','common.success': 'نجاح','common.back': 'رجوع',@@ -6591,6 +6592,10 @@ const messages: TranslationMap = {'userErrors.localModelUnavailable.title': 'النموذج المحلي غير متاح','userErrors.localModelUnavailable.body':'لا يمكن الوصول إلى Ollama على النقطة الطرفية المُهيأة، أو أن النموذج المطلوب غير مثبّت عليها. شغّل Ollama ونزّل النموذج على تلك النقطة الطرفية، أو حوّل هذا العمل إلى مزوّد سحابي.',+ 'userErrors.memoryStoreCorrupt.title': 'تلف فهرس الذاكرة',+ 'userErrors.memoryStoreCorrupt.body':+ 'كانت قاعدة بيانات شجرة الذاكرة تالفة. تم الاحتفاظ بالملف التالف بجوار بيانات الذاكرة وأعيد إنشاء فهرس فارغ. أعد مزامنة مصادر الذاكرة لإعادة تعبئته.',+ 'userErrors.action.openMemorySync': 'إعادة مزامنة الذاكرة','userErrors.scope.chat': 'الدردشة','userErrors.scope.cron': 'مهمة مجدوَلة','userErrors.scope.workspace': 'مساحة العمل',diff --git a/app/src/lib/i18n/bn.ts b/app/src/lib/i18n/bn.tsindex 71ca7a7e84..f3e11708d9 100644--- a/app/src/lib/i18n/bn.ts+++ b/app/src/lib/i18n/bn.ts@@ -570,6 +570,7 @@ const messages: TranslationMap = {'sync.timeAgo.days': '{n} দি. আগে','sync.status.success': 'সফল','sync.status.failed': 'ব্যর্থ',+ 'sync.status.partial': 'আনা হয়েছে, মেমোরিতে যুক্ত হয়নি','common.error': 'ত্রুটি','common.success': 'সফল','common.back': 'পেছনে',@@ -6744,6 +6745,10 @@ const messages: TranslationMap = {'userErrors.localModelUnavailable.title': 'লোকাল মডেল অনুপলব্ধ','userErrors.localModelUnavailable.body':'কনফিগার করা এন্ডপয়েন্টে Ollama-তে পৌঁছানো যাচ্ছে না, অথবা সেখানে প্রয়োজনীয় মডেলটি ইনস্টল করা নেই। Ollama চালু করে সেই এন্ডপয়েন্টে মডেলটি পুল করুন, অথবা এই কাজটি কোনো ক্লাউড প্রোভাইডারে সরিয়ে নিন।',+ 'userErrors.memoryStoreCorrupt.title': 'মেমোরি ইনডেক্স নষ্ট হয়ে গেছে',+ 'userErrors.memoryStoreCorrupt.body':+ 'আপনার মেমোরি ট্রির ডেটাবেস নষ্ট হয়ে গিয়েছিল। নষ্ট ফাইলটি মেমোরি ডেটার পাশে সংরক্ষিত আছে এবং একটি খালি ইনডেক্স নতুন করে তৈরি হয়েছে। আবার পূরণ করতে মেমোরি উৎসগুলি পুনরায় সিঙ্ক করুন।',+ 'userErrors.action.openMemorySync': 'মেমোরি আবার সিঙ্ক করুন','userErrors.scope.chat': 'চ্যাট','userErrors.scope.cron': 'নির্ধারিত কাজ','userErrors.scope.workspace': 'ওয়ার্কস্পেস',diff --git a/app/src/lib/i18n/de.ts b/app/src/lib/i18n/de.tsindex ee6c90c284..7d6b516097 100644--- a/app/src/lib/i18n/de.ts+++ b/app/src/lib/i18n/de.ts@@ -592,6 +592,7 @@ const messages: TranslationMap = {'sync.timeAgo.days': 'vor {n} T.','sync.status.success': 'Erfolg','sync.status.failed': 'Fehlgeschlagen',+ 'sync.status.partial': 'Abgerufen, Speicherung im Gedächtnis fehlgeschlagen','common.error': 'Fehler','common.success': 'Erfolg','common.back': 'Zurück',@@ -6928,6 +6929,10 @@ const messages: TranslationMap = {'userErrors.localModelUnavailable.title': 'Lokales Modell nicht verfügbar','userErrors.localModelUnavailable.body':'Ollama ist unter dem konfigurierten Endpunkt nicht erreichbar, oder das benötigte Modell ist dort nicht installiert. Starte Ollama und lade das Modell auf diesem Endpunkt, oder verlagere diese Arbeit auf einen Cloud-Anbieter.',+ 'userErrors.memoryStoreCorrupt.title': 'Gedächtnisindex war beschädigt',+ 'userErrors.memoryStoreCorrupt.body':+ 'Die Datenbank des Gedächtnisbaums war beschädigt. Die beschädigte Datei wurde neben deinen Gedächtnisdaten aufbewahrt und ein leerer Index neu aufgebaut. Synchronisiere deine Gedächtnisquellen erneut, um ihn wieder zu füllen.',+ 'userErrors.action.openMemorySync': 'Gedächtnis neu synchronisieren','userErrors.scope.chat': 'Chat','userErrors.scope.cron': 'Geplante Aufgabe','userErrors.scope.workspace': 'Arbeitsbereich',diff --git a/app/src/lib/i18n/en.ts b/app/src/lib/i18n/en.tsindex c12e6f8d93..740a834939 100644--- a/app/src/lib/i18n/en.ts+++ b/app/src/lib/i18n/en.ts@@ -285,6 +285,7 @@ const en: TranslationMap = {'sync.timeAgo.days': '{n}d ago','sync.status.success': 'Success','sync.status.failed': 'Failed',+ 'sync.status.partial': 'Fetched, memory ingest failed','common.error': 'Error','common.success': 'Success','common.back': 'Back',@@ -7153,6 +7154,10 @@ const en: TranslationMap = {'userErrors.localModelUnavailable.title': 'Local model unavailable','userErrors.localModelUnavailable.body':'Ollama is not reachable at the configured endpoint, or the required model is not installed there. Start Ollama and pull the model at that endpoint, or switch this workload to a cloud provider.',+ 'userErrors.memoryStoreCorrupt.title': 'Memory index was corrupted',+ 'userErrors.memoryStoreCorrupt.body':+ 'The database behind your memory tree was damaged. The damaged file was preserved next to your memory data, and an empty index was rebuilt. Re-sync your memory sources to fill it again.',+ 'userErrors.action.openMemorySync': 'Re-sync memory','userErrors.scope.chat': 'Chat','userErrors.scope.cron': 'Scheduled job','userErrors.scope.workspace': 'Workspace',diff --git a/app/src/lib/i18n/es.ts b/app/src/lib/i18n/es.tsindex 2cd4017898..889b51d7da 100644--- a/app/src/lib/i18n/es.ts+++ b/app/src/lib/i18n/es.ts@@ -580,6 +580,7 @@ const messages: TranslationMap = {'sync.timeAgo.days': 'hace {n} d','sync.status.success': 'Correcto','sync.status.failed': 'Fallido',+ 'sync.status.partial': 'Obtenido, fallo al indexar en memoria','common.error': 'error','common.success': 'Éxito','common.back': 'Atrás',@@ -6886,6 +6887,10 @@ const messages: TranslationMap = {'userErrors.localModelUnavailable.title': 'Modelo local no disponible','userErrors.localModelUnavailable.body':'No se puede acceder a Ollama en el punto de conexión configurado, o el modelo necesario no está instalado allí. Inicia Ollama y descarga el modelo en ese punto de conexión, o cambia este trabajo a un proveedor en la nube.',+ 'userErrors.memoryStoreCorrupt.title': 'El índice de memoria se dañó',+ 'userErrors.memoryStoreCorrupt.body':+ 'La base de datos del árbol de memoria estaba dañada. El archivo dañado se conservó junto a tus datos de memoria y se reconstruyó un índice vacío. Vuelve a sincronizar tus fuentes de memoria para rellenarlo.',+ 'userErrors.action.openMemorySync': 'Resincronizar memoria','userErrors.scope.chat': 'Chat','userErrors.scope.cron': 'Tarea programada','userErrors.scope.workspace': 'Espacio de trabajo',diff --git a/app/src/lib/i18n/fr.ts b/app/src/lib/i18n/fr.tsindex 85cd0141be..3152a2cabc 100644--- a/app/src/lib/i18n/fr.ts+++ b/app/src/lib/i18n/fr.ts@@ -589,6 +589,7 @@ const messages: TranslationMap = {'sync.timeAgo.days': 'il y a {n} j','sync.status.success': 'Réussi','sync.status.failed': 'Échec',+ 'sync.status.partial': 'Récupéré, échec d’indexation mémoire','common.error': 'Erreur','common.success': 'Succès','common.back': 'Retour',@@ -6914,6 +6915,10 @@ const messages: TranslationMap = {'userErrors.localModelUnavailable.body':"Ollama n'est pas joignable sur le point de terminaison configuré, ou le modèle requis n'y est pas installé. Lancez Ollama et téléchargez le modèle sur ce point de terminaison, ou basculez cette charge de travail vers un fournisseur cloud.",'userErrors.scope.chat': 'Chat',+ 'userErrors.memoryStoreCorrupt.title': 'L’index mémoire a été corrompu',+ 'userErrors.memoryStoreCorrupt.body':+ 'La base de données de l’arbre mémoire était endommagée. Le fichier endommagé a été conservé à côté de vos données mémoire et un index vide a été reconstruit. Resynchronisez vos sources mémoire pour le remplir à nouveau.',+ 'userErrors.action.openMemorySync': 'Resynchroniser la mémoire','userErrors.scope.cron': 'Tâche planifiée','userErrors.scope.workspace': 'Espace de travail','userErrors.memoryBudgetExhausted.title': 'La mémoire a cessé de grandir',diff --git a/app/src/lib/i18n/hi.ts b/app/src/lib/i18n/hi.tsindex 0ff716e6c9..4d94293276 100644--- a/app/src/lib/i18n/hi.ts+++ b/app/src/lib/i18n/hi.ts@@ -570,6 +570,7 @@ const messages: TranslationMap = {'sync.timeAgo.days': '{n} दि. पहले','sync.status.success': 'सफल','sync.status.failed': 'विफल',+ 'sync.status.partial': 'प्राप्त हुआ, मेमोरी में दर्ज नहीं हुआ','common.error': 'एरर','common.success': 'सफल','common.back': 'वापस',@@ -6741,6 +6742,10 @@ const messages: TranslationMap = {'userErrors.localModelUnavailable.title': 'लोकल मॉडल उपलब्ध नहीं है','userErrors.localModelUnavailable.body':'कॉन्फ़िगर किए गए एंडपॉइंट पर Ollama तक पहुँच नहीं है, या ज़रूरी मॉडल वहाँ इंस्टॉल नहीं है। Ollama शुरू करके उसी एंडपॉइंट पर मॉडल पुल करें, या इस काम को किसी क्लाउड प्रोवाइडर पर ले जाएँ।',+ 'userErrors.memoryStoreCorrupt.title': 'मेमोरी इंडेक्स खराब हो गया',+ 'userErrors.memoryStoreCorrupt.body':+ 'आपकी मेमोरी ट्री का डेटाबेस खराब हो गया था। खराब फाइल आपके मेमोरी डेटा के पास सुरक्षित रखी गई है, और एक खाली इंडेक्स फिर से बनाया गया है। इसे दोबारा भरने के लिए अपने मेमोरी स्रोतों को फिर से सिंक करें।',+ 'userErrors.action.openMemorySync': 'मेमोरी फिर से सिंक करें','userErrors.scope.chat': 'चैट','userErrors.scope.cron': 'निर्धारित कार्य','userErrors.scope.workspace': 'वर्कस्पेस',diff --git a/app/src/lib/i18n/id.ts b/app/src/lib/i18n/id.tsindex 00bdd8f9b1..6c0445e737 100644--- a/app/src/lib/i18n/id.ts+++ b/app/src/lib/i18n/id.ts@@ -574,6 +574,7 @@ const messages: TranslationMap = {'sync.timeAgo.days': '{n} hr lalu','sync.status.success': 'Berhasil','sync.status.failed': 'Gagal',+ 'sync.status.partial': 'Terambil, gagal masuk ke memori','common.error': 'Kesalahan','common.success': 'Berhasil','common.back': 'Kembali',@@ -6776,6 +6777,10 @@ const messages: TranslationMap = {'userErrors.localModelUnavailable.title': 'Model lokal tidak tersedia','userErrors.localModelUnavailable.body':'Ollama tidak dapat dijangkau di endpoint yang dikonfigurasi, atau model yang dibutuhkan belum terpasang di sana. Jalankan Ollama dan unduh modelnya di endpoint tersebut, atau alihkan pekerjaan ini ke penyedia cloud.',+ 'userErrors.memoryStoreCorrupt.title': 'Indeks memori rusak',+ 'userErrors.memoryStoreCorrupt.body':+ 'Basis data pohon memori mengalami kerusakan. Berkas yang rusak disimpan di samping data memori Anda, dan indeks kosong telah dibangun ulang. Sinkronkan ulang sumber memori untuk mengisinya kembali.',+ 'userErrors.action.openMemorySync': 'Sinkronkan ulang memori','userErrors.scope.chat': 'Obrolan','userErrors.scope.cron': 'Tugas terjadwal','userErrors.scope.workspace': 'Ruang kerja',diff --git a/app/src/lib/i18n/it.ts b/app/src/lib/i18n/it.tsindex d966b4fd77..c1cf636dbf 100644--- a/app/src/lib/i18n/it.ts+++ b/app/src/lib/i18n/it.ts@@ -584,6 +584,7 @@ const messages: TranslationMap = {'sync.timeAgo.days': '{n} g fa','sync.status.success': 'Riuscito','sync.status.failed': 'Non riuscito',+ 'sync.status.partial': 'Recuperato, indicizzazione in memoria non riuscita','common.error': 'Errore','common.success': 'Successo','common.back': 'Indietro',@@ -6870,6 +6871,10 @@ const messages: TranslationMap = {'userErrors.localModelUnavailable.body':"Ollama non è raggiungibile sull'endpoint configurato, oppure il modello necessario non è installato lì. Avvia Ollama e scarica il modello su quell'endpoint, oppure sposta questo lavoro su un provider cloud.",'userErrors.scope.chat': 'Chat',+ 'userErrors.memoryStoreCorrupt.title': 'L’indice della memoria era corrotto',+ 'userErrors.memoryStoreCorrupt.body':+ 'Il database dell’albero della memoria era danneggiato. Il file danneggiato è stato conservato accanto ai tuoi dati di memoria ed è stato ricostruito un indice vuoto. Risincronizza le tue fonti di memoria per riempirlo di nuovo.',+ 'userErrors.action.openMemorySync': 'Risincronizza la memoria','userErrors.scope.cron': 'Attività pianificata','userErrors.scope.workspace': 'Spazio di lavoro','userErrors.memoryBudgetExhausted.title': 'La memoria ha smesso di crescere',diff --git a/app/src/lib/i18n/ko.ts b/app/src/lib/i18n/ko.tsindex 406060c7df..1bed2541ca 100644--- a/app/src/lib/i18n/ko.ts+++ b/app/src/lib/i18n/ko.ts@@ -563,6 +563,7 @@ const messages: TranslationMap = {'sync.timeAgo.days': '{n}일 전','sync.status.success': '성공','sync.status.failed': '실패',+ 'sync.status.partial': '가져왔지만 메모리 기록 실패','common.error': '오류','common.success': '성공','common.back': '뒤로',@@ -6666,6 +6667,10 @@ const messages: TranslationMap = {'userErrors.localModelUnavailable.title': '로컬 모델을 사용할 수 없음','userErrors.localModelUnavailable.body':'구성된 엔드포인트에서 Ollama에 연결할 수 없거나 필요한 모델이 그곳에 설치되어 있지 않습니다. Ollama를 실행하고 해당 엔드포인트에 모델을 내려받거나, 이 작업을 클라우드 제공업체로 전환하세요.',+ 'userErrors.memoryStoreCorrupt.title': '메모리 인덱스가 손상되었습니다',+ 'userErrors.memoryStoreCorrupt.body':+ '메모리 트리의 데이터베이스가 손상되었습니다. 손상된 파일은 메모리 데이터 옆에 보존되었고 빈 인덱스가 다시 생성되었습니다. 메모리 소스를 다시 동기화하여 채워 주세요.',+ 'userErrors.action.openMemorySync': '메모리 다시 동기화','userErrors.scope.chat': '채팅','userErrors.scope.cron': '예약된 작업','userErrors.scope.workspace': '작업 공간',diff --git a/app/src/lib/i18n/pl.ts b/app/src/lib/i18n/pl.tsindex c0fb43670d..18c7f510b1 100644--- a/app/src/lib/i18n/pl.ts+++ b/app/src/lib/i18n/pl.ts@@ -579,6 +579,7 @@ const messages: TranslationMap = {'sync.timeAgo.days': '{n} dni temu','sync.status.success': 'Sukces','sync.status.failed': 'Niepowodzenie',+ 'sync.status.partial': 'Pobrano, zapis do pamięci nie powiódł się','common.error': 'Błąd','common.success': 'Sukces','common.back': 'Wstecz',@@ -6840,6 +6841,10 @@ const messages: TranslationMap = {'userErrors.localModelUnavailable.title': 'Model lokalny niedostępny','userErrors.localModelUnavailable.body':'Ollama jest nieosiągalna pod skonfigurowanym punktem końcowym albo wymagany model nie jest tam zainstalowany. Uruchom Ollamę i pobierz model w tym punkcie końcowym lub przenieś tę pracę do dostawcy w chmurze.',+ 'userErrors.memoryStoreCorrupt.title': 'Indeks pamięci był uszkodzony',+ 'userErrors.memoryStoreCorrupt.body':+ 'Baza danych drzewa pamięci była uszkodzona. Uszkodzony plik zachowano obok danych pamięci i odbudowano pusty indeks. Zsynchronizuj ponownie źródła pamięci, aby go wypełnić.',+ 'userErrors.action.openMemorySync': 'Zsynchronizuj pamięć ponownie','userErrors.scope.chat': 'Czat','userErrors.scope.cron': 'Zaplanowane zadanie','userErrors.scope.workspace': 'Obszar roboczy',diff --git a/app/src/lib/i18n/pt.ts b/app/src/lib/i18n/pt.tsindex 540d283950..718e8e8ad2 100644--- a/app/src/lib/i18n/pt.ts+++ b/app/src/lib/i18n/pt.ts@@ -576,6 +576,7 @@ const messages: TranslationMap = {'sync.timeAgo.days': 'há {n} d','sync.status.success': 'Sucesso','sync.status.failed': 'Falhou',+ 'sync.status.partial': 'Obtido, falha ao indexar na memória','common.error': 'Erro','common.success': 'Sucesso','common.back': 'Voltar',@@ -6853,6 +6854,10 @@ const messages: TranslationMap = {'userErrors.localModelUnavailable.title': 'Modelo local indisponível','userErrors.localModelUnavailable.body':'O Ollama não está acessível no endpoint configurado, ou o modelo necessário não está instalado nele. Inicie o Ollama e baixe o modelo nesse endpoint, ou mude este trabalho para um provedor na nuvem.',+ 'userErrors.memoryStoreCorrupt.title': 'O índice de memória foi corrompido',+ 'userErrors.memoryStoreCorrupt.body':+ 'O banco de dados da árvore de memória estava danificado. O arquivo danificado foi preservado ao lado dos seus dados de memória e um índice vazio foi reconstruído. Sincronize novamente suas fontes de memória para preenchê-lo.',+ 'userErrors.action.openMemorySync': 'Ressincronizar memória','userErrors.scope.chat': 'Chat','userErrors.scope.cron': 'Tarefa agendada','userErrors.scope.workspace': 'Espaço de trabalho',diff --git a/app/src/lib/i18n/ru.ts b/app/src/lib/i18n/ru.tsindex 1358047852..c9aabb9ab3 100644--- a/app/src/lib/i18n/ru.ts+++ b/app/src/lib/i18n/ru.ts@@ -574,6 +574,7 @@ const messages: TranslationMap = {'sync.timeAgo.days': '{n} дн назад','sync.status.success': 'Успешно','sync.status.failed': 'Сбой',+ 'sync.status.partial': 'Получено, но не записано в память','common.error': 'Ошибка','common.success': 'Готово','common.back': 'Назад',@@ -6815,6 +6816,10 @@ const messages: TranslationMap = {'userErrors.localModelUnavailable.title': 'Локальная модель недоступна','userErrors.localModelUnavailable.body':'Ollama недоступен по настроенному адресу, либо нужная модель там не установлена. Запустите Ollama и загрузите модель по этому адресу или переведите эту работу на облачного провайдера.',+ 'userErrors.memoryStoreCorrupt.title': 'Индекс памяти был повреждён',+ 'userErrors.memoryStoreCorrupt.body':+ 'База данных дерева памяти была повреждена. Повреждённый файл сохранён рядом с данными памяти, а пустой индекс создан заново. Заново синхронизируйте источники памяти, чтобы заполнить его.',+ 'userErrors.action.openMemorySync': 'Пересинхронизировать память','userErrors.scope.chat': 'Чат','userErrors.scope.cron': 'Запланированная задача','userErrors.scope.workspace': 'Рабочая область',diff --git a/app/src/lib/i18n/zh-CN.ts b/app/src/lib/i18n/zh-CN.tsindex 5b342c2e37..15bbfc132c 100644--- a/app/src/lib/i18n/zh-CN.ts+++ b/app/src/lib/i18n/zh-CN.ts@@ -538,6 +538,7 @@ const messages: TranslationMap = {'sync.timeAgo.days': '{n}天前','sync.status.success': '成功','sync.status.failed': '失败',+ 'sync.status.partial': '已获取,记忆写入失败','common.error': '错误','common.success': '成功','common.back': '返回',@@ -6377,6 +6378,10 @@ const messages: TranslationMap = {'userErrors.localModelUnavailable.title': '本地模型不可用','userErrors.localModelUnavailable.body':'无法在配置的端点连接 Ollama,或所需模型未安装在该端点。请启动 Ollama 并在该端点拉取模型,或将此工作切换到云端提供商。',+ 'userErrors.memoryStoreCorrupt.title': '记忆索引已损坏',+ 'userErrors.memoryStoreCorrupt.body':+ '记忆树使用的数据库已损坏。受损文件已保留在记忆数据旁边,并已重建一个空索引。请重新同步记忆来源以重新填充。',+ 'userErrors.action.openMemorySync': '重新同步记忆','userErrors.scope.chat': '聊天','userErrors.scope.cron': '定时任务','userErrors.scope.workspace': '工作区',diff --git a/app/src/lib/userErrors/__tests__/classify.test.ts b/app/src/lib/userErrors/__tests__/classify.test.tsindex 6f0310d605..5a40445526 100644--- a/app/src/lib/userErrors/__tests__/classify.test.ts+++ b/app/src/lib/userErrors/__tests__/classify.test.ts@@ -92,6 +92,40 @@ describe('classifyUserActionableError', () => {}});+ it('classifies a quarantined corrupt memory store (memory user_error kind token)', () => {+ // Core's shared corruption recovery emits the stable STORE_CORRUPT_KIND+ // token with error_source=memory after quarantine + rebuild+ // (openhuman#5820); the CTA routes to Brain's sync tab because the+ // rebuilt store repopulates by re-syncing sources.+ const a = classifyUserActionableError({+ errorType: 'memory_store_corrupt',+ scope: 'memory',+ sourceDomain: 'memory',+ });+ expect(a?.kind).toBe('memory_store_corrupt');+ expect(a?.severity).toBe('error');+ expect(a?.scope).toBe('memory');+ expect(a?.action).toBe('open_memory_sync');+ expect(a?.titleKey).toBe('userErrors.memoryStoreCorrupt.title');+ expect(a?.bodyKey).toBe('userErrors.memoryStoreCorrupt.body');+ expect(a?.id).toBe(userErrorId('memory_store_corrupt', 'memory', undefined));+ });++ it('does NOT promote raw SQLite corruption prose relayed by another domain', () => {+ // Token-only on purpose: "database disk image is malformed" appears in+ // raw logs other domains relay, and a relayed log line must not become a+ // "your memory was quarantined" panel entry.+ expect(+ classifyUserActionableError({ message: 'database disk image is malformed' }),+ ).toBeNull();+ expect(+ classifyUserActionableError({+ message: 'sync failed: file is not a database',+ scope: 'memory',+ }),+ ).toBeNull();+ });+it('does NOT promote a bare "daemon unreachable" from another domain', () => {// Backend connection-health logs use this phrase too. Matching it loosely// would tell a user with a flaky backend link to install Ollama. The Rustdiff --git a/app/src/lib/userErrors/classify.ts b/app/src/lib/userErrors/classify.tsindex 1dab658b21..2831c263c6 100644--- a/app/src/lib/userErrors/classify.ts+++ b/app/src/lib/userErrors/classify.ts@@ -193,6 +193,28 @@ export function classifyUserActionableError(};}+ // The memory-tree store was corrupt and has been quarantined + rebuilt+ // empty (openhuman#5820). Token-only on purpose: the only producer is the+ // core's `STORE_CORRUPT_KIND` broadcast, and the underlying SQLite prose+ // ("database disk image is malformed") also appears in raw logs other+ // domains relay — promoting prose here could turn an unrelated relay into+ // a "your memory was quarantined" panel entry.+ if (text.includes('memory_store_corrupt')) {+ return {+ id: userErrorId('memory_store_corrupt', scope, signal.provider),+ kind: 'memory_store_corrupt',+ severity: 'error',+ scope,+ sourceDomain: signal.sourceDomain,+ provider: signal.provider,+ titleKey: 'userErrors.memoryStoreCorrupt.title',+ bodyKey: 'userErrors.memoryStoreCorrupt.body',+ // Re-syncing sources is the remediation — the rebuilt store is empty+ // and repopulates from there.+ action: 'open_memory_sync',+ };+ }+// The local model runtime a workload depends on is unusable — Ollama is not// running, or the configured model was never pulled (#5354). Emitted by core// as the stable `local_model_unavailable` kind token (memory embedder healthdiff --git a/app/src/types/userError.ts b/app/src/types/userError.tsindex 8b25a69f6b..49b7293651 100644--- a/app/src/types/userError.ts+++ b/app/src/types/userError.ts@@ -43,7 +43,15 @@ export type UserErrorKind =* is the whole point — a billing-worded entry would not tell the user their* connections have stopped working.*/- | 'integration_degraded';+ | 'integration_degraded'+ /**+ * The memory-tree store was corrupt and has been quarantined + rebuilt+ * empty (openhuman#5820). Mirrors the core-side `STORE_CORRUPT_KIND`+ * token. The damaged file is preserved on disk beside the store; the+ * rebuilt tree repopulates by re-syncing sources, which is why the action+ * deep-links to Brain's sync tab rather than any settings screen.+ */+ | 'memory_store_corrupt';/** Where the failure originated, for grouping/labelling (privacy-safe). */export type UserErrorScope =@@ -62,6 +70,8 @@ export type UserErrorAction =| 'open_embeddings_settings'/** The connections screen — where integration health is polled and re-read. */| 'open_connections'+ /** Brain's sync tab — where memory sources are re-synced after a store rebuild. */+ | 'open_memory_sync'| 'dismiss';export type UserErrorSeverity = 'warning' | 'error';diff --git a/app/src/utils/tauriCommands/memoryTree.ts b/app/src/utils/tauriCommands/memoryTree.tsindex 220e62809b..5891a7f8b7 100644--- a/app/src/utils/tauriCommands/memoryTree.ts+++ b/app/src/utils/tauriCommands/memoryTree.ts@@ -990,6 +990,15 @@ export interface SyncAuditEntry {duration_ms: number;success: boolean;error?: string;+ /**+ * Items fetched-and-stored whose memory-tree ingest failed+ * (openhuman#5820). Absent on rows written before the field existed and on+ * fully-healthy rows; a non-zero count with `success: false` is the+ * "fetched, not tree-ingested" partial verdict the panel renders as ⚠.+ */+ tree_ingest_failures?: number;+ /** Why the tree half failed, when it did. Never memory content. */+ tree_error?: string;}export async function memorySyncAuditLog(): Promise<SyncAuditEntry[]> {diff --git a/src/openhuman/agent/harness/archivist/tree_ingest.rs b/src/openhuman/agent/harness/archivist/tree_ingest.rsindex 162fb62340..63dc40b90b 100644--- a/src/openhuman/agent/harness/archivist/tree_ingest.rs+++ b/src/openhuman/agent/harness/archivist/tree_ingest.rs@@ -174,10 +174,34 @@ impl ArchivistHook {);}Err(e) => {- tracing::warn!(- "[archivist] tree ingest failed (non-fatal): source_id={source_id} \- session={session_id} segment={segment_id} error={e}"- );+ // Corruption is not non-fatal (openhuman#5820): a malformed+ // chunk store fails every segment identically, and this warn+ // was one of the paths that let it run silently for 34+ // minutes. The driver's engine owns the recovery (its queue+ // worker quarantines + rebuilds within one poll interval);+ // this side's job is to escalate visibility — log at ERROR and+ // put a durable notice in front of the user, once per process+ // rather than once per segment. The episodic write above is+ // still the source of truth either way, so the turn itself is+ // never failed from here.+ let rendered = e.to_string();+ if crate::openhuman::memory::tree::health::user_error::is_corrupt_store_error(+ &rendered,+ ) {+ tracing::error!(+ "[archivist] tree ingest hit a CORRUPT memory store: \+ source_id={source_id} session={session_id} segment={segment_id} \+ error={rendered}"+ );+ crate::openhuman::memory::tree::health::user_error::notice_corrupt_store_once(+ "archivist tree ingest",+ );+ } else {+ tracing::warn!(+ "[archivist] tree ingest failed (non-fatal): source_id={source_id} \+ session={session_id} segment={segment_id} error={rendered}"+ );+ }}}}diff --git a/src/openhuman/memory/host.rs b/src/openhuman/memory/host.rsindex b7eaf8a4a7..0fa46e4588 100644--- a/src/openhuman/memory/host.rs+++ b/src/openhuman/memory/host.rs@@ -205,150 +205,162 @@ pub fn install_memory_event_sink() {/// `None` means the event was handled here and has no bus equivalent — not/// that it was dropped.fn into_domain_event(event: MemoryEvent) -> Option<DomainEvent> {- let domain_event = match event {- MemoryEvent::SyncStageChanged {- trigger,- stage,- provider,- connection_id,- detail,- source_id,- } => DomainEvent::MemorySyncStageChanged {- trigger,- stage,- provider,- connection_id,- detail,- source_id,- },- MemoryEvent::IngestionStarted {- document_id,- title,- namespace,- queue_depth,- } => DomainEvent::MemoryIngestionStarted {- document_id,- title,- namespace,- queue_depth,- },- MemoryEvent::IngestionCompleted {- document_id,- namespace,- success,- elapsed_ms,- queue_depth,- } => DomainEvent::MemoryIngestionCompleted {- document_id,- namespace,- success,- elapsed_ms,- queue_depth,- },- MemoryEvent::DocumentCanonicalized {- source_id,- source_kind,- chunks_written,- chunk_ids,- canonicalized_at,- body_preview,- } => DomainEvent::DocumentCanonicalized {- source_id,- source_kind,- chunks_written,- chunk_ids,- canonicalized_at,- body_preview,- },- MemoryEvent::TreeSummarizerHourCompleted {- namespace,- node_id,- token_count,- } => DomainEvent::TreeSummarizerHourCompleted {- namespace,- node_id,- token_count,- },- MemoryEvent::TreeSummarizerPropagated {- namespace,- node_id,- level,- token_count,- } => DomainEvent::TreeSummarizerPropagated {- namespace,- node_id,- level,- token_count,- },- MemoryEvent::TreeSummarizerRebuildCompleted {- namespace,- total_nodes,- } => DomainEvent::TreeSummarizerRebuildCompleted {- namespace,- total_nodes,- },- MemoryEvent::TreeBuildProgress {- phase,- step,- tree_scope,- level,- item_count,- detail,- } => DomainEvent::MemoryTreeBuildProgress {- phase,- step,- tree_scope,- level,- item_count,- detail,- },- MemoryEvent::EmbeddingModelUnhealthy(reason) => DomainEvent::EmbeddingModelUnhealthy {- provider: reason.provider,- model: reason.model,- fallback_provider: reason.fallback_provider,- message: reason.message,- },- MemoryEvent::DriverBindFailed {- configured_driver,- bound_driver,- reason,- } => DomainEvent::MemoryDriverBindFailed {- configured_driver,- bound_driver,- reason,- },- MemoryEvent::DiffSnapshotTaken {- snapshot_id,- source_id,- source_kind,- item_count,- trigger,- } => DomainEvent::MemoryDiffSnapshotTaken {- snapshot_id,- source_id,- source_kind,- item_count,- trigger,- },- MemoryEvent::DiffMarkedRead {- source_ids,- snapshot_ids,- } => DomainEvent::MemoryDiffMarkedRead {- source_ids,- snapshot_ids,- },- MemoryEvent::ComposioIntegrationsChanged { toolkits } => {- DomainEvent::ComposioIntegrationsChanged { toolkits }- }- MemoryEvent::SyncRequested { channel_id } => {- DomainEvent::MemorySyncRequested { channel_id }- }- // Goes to the durable UserErrorCenter over the web channel, not the bus.- MemoryEvent::LocalModelUnavailable { origin } => {- crate::openhuman::memory::tree::health::user_error::+ let domain_event =+ match event {+ MemoryEvent::SyncStageChanged {+ trigger,+ stage,+ provider,+ connection_id,+ detail,+ source_id,+ } => DomainEvent::MemorySyncStageChanged {+ trigger,+ stage,+ provider,+ connection_id,+ detail,+ source_id,+ },+ MemoryEvent::IngestionStarted {+ document_id,+ title,+ namespace,+ queue_depth,+ } => DomainEvent::MemoryIngestionStarted {+ document_id,+ title,+ namespace,+ queue_depth,+ },+ MemoryEvent::IngestionCompleted {+ document_id,+ namespace,+ success,+ elapsed_ms,+ queue_depth,+ } => DomainEvent::MemoryIngestionCompleted {+ document_id,+ namespace,+ success,+ elapsed_ms,+ queue_depth,+ },+ MemoryEvent::DocumentCanonicalized {+ source_id,+ source_kind,+ chunks_written,+ chunk_ids,+ canonicalized_at,+ body_preview,+ } => DomainEvent::DocumentCanonicalized {+ source_id,+ source_kind,+ chunks_written,+ chunk_ids,+ canonicalized_at,+ body_preview,+ },+ MemoryEvent::TreeSummarizerHourCompleted {+ namespace,+ node_id,+ token_count,+ } => DomainEvent::TreeSummarizerHourCompleted {+ namespace,+ node_id,+ token_count,+ },+ MemoryEvent::TreeSummarizerPropagated {+ namespace,+ node_id,+ level,+ token_count,+ } => DomainEvent::TreeSummarizerPropagated {+ namespace,+ node_id,+ level,+ token_count,+ },+ MemoryEvent::TreeSummarizerRebuildCompleted {+ namespace,+ total_nodes,+ } => DomainEvent::TreeSummarizerRebuildCompleted {+ namespace,+ total_nodes,+ },+ MemoryEvent::TreeBuildProgress {+ phase,+ step,+ tree_scope,+ level,+ item_count,+ detail,+ } => DomainEvent::MemoryTreeBuildProgress {+ phase,+ step,+ tree_scope,+ level,+ item_count,+ detail,+ },+ MemoryEvent::EmbeddingModelUnhealthy(reason) => DomainEvent::EmbeddingModelUnhealthy {+ provider: reason.provider,+ model: reason.model,+ fallback_provider: reason.fallback_provider,+ message: reason.message,+ },+ MemoryEvent::DriverBindFailed {+ configured_driver,+ bound_driver,+ reason,+ } => DomainEvent::MemoryDriverBindFailed {+ configured_driver,+ bound_driver,+ reason,+ },+ MemoryEvent::DiffSnapshotTaken {+ snapshot_id,+ source_id,+ source_kind,+ item_count,+ trigger,+ } => DomainEvent::MemoryDiffSnapshotTaken {+ snapshot_id,+ source_id,+ source_kind,+ item_count,+ trigger,+ },+ MemoryEvent::DiffMarkedRead {+ source_ids,+ snapshot_ids,+ } => DomainEvent::MemoryDiffMarkedRead {+ source_ids,+ snapshot_ids,+ },+ MemoryEvent::ComposioIntegrationsChanged { toolkits } => {+ DomainEvent::ComposioIntegrationsChanged { toolkits }+ }+ MemoryEvent::SyncRequested { channel_id } => {+ DomainEvent::MemorySyncRequested { channel_id }+ }+ // Goes to the durable UserErrorCenter over the web channel, not the bus.+ MemoryEvent::LocalModelUnavailable { origin } => {+ crate::openhuman::memory::tree::health::user_error::publish_local_model_unavailable_user_error(&origin);- return None;- }- };+ return None;+ }+ // Also web-channel-only (openhuman#5820): the engine already+ // quarantined and rebuilt, so there is nothing for a bus subscriber to+ // do — the user needs to hear it, durably.+ MemoryEvent::StoreCorruptQuarantined {+ origin,+ quarantined_path,+ } => {+ crate::openhuman::memory::tree::health::user_error::+ publish_store_corrupt_user_error(&origin, quarantined_path.as_deref());+ return None;+ }+ };Some(domain_event)}diff --git a/src/openhuman/memory/sources/rpc.rs b/src/openhuman/memory/sources/rpc.rsindex 5c6f158de2..b693b3a148 100644--- a/src/openhuman/memory/sources/rpc.rs+++ b/src/openhuman/memory/sources/rpc.rs@@ -1018,6 +1018,64 @@ pub struct AllInResponse {pub sources: Vec<MemorySourceEntry>,/// Number of sync tasks spawned (one per enabled source).pub sync_triggered: u32,+ /// Number of enabled sources whose sync trigger FAILED (openhuman#5820).+ ///+ /// Additive: an older caller reading only `sync_triggered` behaves as+ /// before, but a total failure no longer looks like a quiet 200 — in the+ /// incident, every source failed `no memory source registered` and the+ /// response still read as success with `sync_triggered: 0`.+ #[serde(default)]+ pub sync_failed: u32,+ /// One `"<source_id>: <error>"` line per failed trigger, in sweep order.+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub sync_errors: Vec<String>,+}++/// The sweep half of [`apply_all_in_rpc`]: trigger a sync for every enabled+/// source, aggregating failures instead of laundering them (openhuman#5820 —+/// in the incident every trigger failed `no memory source registered` and the+/// RPC still answered a clean success).+///+/// Takes the trigger as a closure rather than the driver trait object so the+/// aggregation is unit-testable without a full `MemorySourceSync` stub; the+/// RPC owns config/binding resolution and the response shape.+async fn trigger_enabled_syncs<F, Fut>(+ sources: &[MemorySourceEntry],+ mut trigger: F,+) -> (u32, Vec<String>)+where+ F: FnMut(String) -> Fut,+ Fut: std::future::Future<Output = Result<(), String>>,+{+ let mut sync_triggered: u32 = 0;+ let mut sync_errors: Vec<String> = Vec::new();+ for source in sources {+ if !source.enabled {+ continue;+ }+ tracing::debug!(+ source_id = %source.id,+ kind = %source.kind.as_str(),+ "[memory_sources] apply_all_in_rpc: triggering sync"+ );+ match trigger(source.id.clone()).await {+ Ok(()) => {+ sync_triggered += 1;+ }+ Err(e) => {+ // Per-source failure stays non-fatal for the sweep, but it is+ // AGGREGATED into the response rather than laundered into a+ // clean 200.+ tracing::warn!(+ source_id = %source.id,+ error = %e,+ "[memory_sources] apply_all_in_rpc: sync trigger failed for source"+ );+ sync_errors.push(format!("{}: {e}", source.id));+ }+ }+ }+ (sync_triggered, sync_errors)}/// Enable ALL memory sources, clear all caps, and trigger a sync for@@ -1046,39 +1104,30 @@ pub async fn apply_all_in_rpc() -> Result<RpcOutcome<AllInResponse>, String> {)})?;- let mut sync_triggered: u32 = 0;-- for source in &sources {- if !source.enabled {- continue;- }- tracing::debug!(- source_id = %source.id,- kind = %source.kind.as_str(),- "[memory_sources] apply_all_in_rpc: triggering sync"- );- match sync- .run_source_sync(&source.id)+ let (sync_triggered, sync_errors) = trigger_enabled_syncs(&sources, |source_id| async move {+ sync.run_source_sync(&source_id).await+ .map(|_| ()).map_err(|error| error.to_string())- {- Ok(_) => {- sync_triggered += 1;- }- Err(e) => {- // Non-fatal: log and continue — best-effort sync trigger.- tracing::warn!(- source_id = %source.id,- error = %e,- "[memory_sources] apply_all_in_rpc: sync trigger failed for source"- );- }- }+ })+ .await;++ let sync_failed = sync_errors.len() as u32;+ if sync_failed > 0 && sync_triggered == 0 {+ // Every enabled source failed to trigger — that is a broken sweep,+ // not a best-effort one. Log at ERROR so it cannot hide at warn among+ // the per-source lines.+ tracing::error!(+ sources = sources.len(),+ sync_failed,+ "[memory_sources] apply_all_in_rpc: every sync trigger failed"+ );}tracing::info!(sources = sources.len(),sync_triggered,+ sync_failed,"[memory_sources] apply_all_in_rpc: complete");@@ -1086,6 +1135,8 @@ pub async fn apply_all_in_rpc() -> Result<RpcOutcome<AllInResponse>, String> {AllInResponse {sources,sync_triggered,+ sync_failed,+ sync_errors,},vec![],))@@ -1366,6 +1417,8 @@ mod monthly_summary_tests {duration_ms: 10,success: true,error: None,+ tree_ingest_failures: 0,+ tree_error: None,}}diff --git a/src/openhuman/memory/sources/rpc_tests.rs b/src/openhuman/memory/sources/rpc_tests.rsindex 11c9872b86..54a709f515 100644--- a/src/openhuman/memory/sources/rpc_tests.rs+++ b/src/openhuman/memory/sources/rpc_tests.rs@@ -47,3 +47,55 @@ fn the_null_driver_serves_neither_family() {assert!(provider.as_source_sync().is_none());assert!(provider.as_coding_sessions().is_none());}++/// openhuman#5820: the all-in sweep must aggregate per-source trigger+/// failures into the response instead of laundering them — in the incident+/// every source failed `no memory source registered` and the RPC still+/// answered a clean success with `sync_triggered: 0` and nothing else.+#[tokio::test]+async fn trigger_sweep_aggregates_failures_instead_of_laundering_them() {+ fn entry(id: &str, enabled: bool) -> MemorySourceEntry {+ serde_json::from_value(serde_json::json!({+ "id": id,+ "kind": "folder",+ "label": "Test",+ "enabled": enabled,+ "path": ".",+ }))+ .expect("a valid folder source entry")+ }++ let sources = vec![+ entry("ok_1", true),+ entry("src_gone", true),+ entry("disabled", false),+ entry("src_also_gone", true),+ ];++ // Succeeds for ids starting `ok`, refuses everything else the way the+ // incident did.+ let (triggered, errors) = trigger_enabled_syncs(&sources, |source_id| async move {+ if source_id.starts_with("ok") {+ Ok(())+ } else {+ Err(format!(+ "not found: no memory source registered as {source_id}"+ ))+ }+ })+ .await;++ assert_eq!(triggered, 1, "only the healthy enabled source triggers");+ assert_eq!(errors.len(), 2, "each failed enabled source is reported");+ assert!(errors[0].starts_with("src_gone: "), "got: {}", errors[0]);+ assert!(+ errors[0].contains("no memory source registered"),+ "the caller must see the real reason, got: {}",+ errors[0]+ );+ assert!(+ errors[1].starts_with("src_also_gone: "),+ "got: {}",+ errors[1]+ );+}diff --git a/src/openhuman/memory/tree/health/user_error.rs b/src/openhuman/memory/tree/health/user_error.rsindex d858c9c9bd..60e3f7d229 100644--- a/src/openhuman/memory/tree/health/user_error.rs+++ b/src/openhuman/memory/tree/health/user_error.rs@@ -8,7 +8,9 @@//! Both halves key on `LOCAL_MODEL_UNAVAILABLE_KIND`, which lives in the//! contract crate so the two cannot drift apart silently.-use tinymemory_api::host::{LOCAL_MODEL_UNAVAILABLE_KIND, MEMORY_USER_ERROR_SOURCE};+use tinymemory_api::host::{+ LOCAL_MODEL_UNAVAILABLE_KIND, MEMORY_USER_ERROR_SOURCE, STORE_CORRUPT_KIND,+};use crate::core::socketio::WebChannelEvent;@@ -44,6 +46,81 @@ pub(crate) fn publish_local_model_unavailable_user_error(origin: &str) {crate::openhuman::web_chat::publish_web_channel_event(local_model_unavailable_user_error());}+/// The metadata-only `user_error` payload for a corrupt-and-quarantined+/// memory-tree store (openhuman#5820). Same no-leak contract as the+/// local-model payload above: a stable `kind` token plus the source, never the+/// filesystem path (which is logged host-side instead).+pub(crate) fn store_corrupt_quarantined_user_error() -> WebChannelEvent {+ WebChannelEvent {+ event: "user_error".to_string(),+ // Every socket auto-joins the "system" room, so this reaches all+ // connected clients rather than one chat session.+ client_id: "system".to_string(),+ error_type: Some(STORE_CORRUPT_KIND.to_string()),+ error_source: Some(MEMORY_USER_ERROR_SOURCE.to_string()),+ ..Default::default()+ }+}++/// Text classifier for a corrupt chunk store, for errors that crossed the bus+/// and only exist as strings (a `MemoryError`'s rendered message).+///+/// The two phrases are SQLite's own renderings of `SQLITE_CORRUPT` (code 11)+/// and `SQLITE_NOTADB` (code 26) and survive every flattening the wire+/// applies. Mirrors the typed classifier inside `tinymemory-core` — the+/// module side classifies before the error is stringified; this is the+/// host-side fallback for paths that only ever see text.+pub(crate) fn is_corrupt_store_error(message: &str) -> bool {+ let msg = message.to_ascii_lowercase();+ msg.contains("database disk image is malformed") || msg.contains("file is not a database")+}++/// Once-per-process corrupt-store notice for wire-text detectors+/// (openhuman#5820).+///+/// The archivist sees the corruption as one failed call per segment — 747+/// warns in the incident — so its escalation must not become 747 notices.+/// The engine's own quarantine still publishes the authoritative+/// [`MemoryEvent::StoreCorruptQuarantined`](tinymemory_api::host::MemoryEvent)+/// notice (un-latched, once per actual quarantine); this latch only bounds the+/// early-warning duplicate from paths that detect the damage before the+/// engine's recovery runs.+pub(crate) fn notice_corrupt_store_once(origin: &str) {+ use std::sync::atomic::{AtomicBool, Ordering};+ static WIRE_CORRUPT_NOTICED: AtomicBool = AtomicBool::new(false);+ if WIRE_CORRUPT_NOTICED.swap(true, Ordering::Relaxed) {+ return;+ }+ publish_store_corrupt_user_error(origin, None);+}++/// Broadcast the corrupt-store user error and log the quarantined path+/// prominently (openhuman#5820 item 4 — 172 MB of a user's indexed memory+/// sitting on disk must never be a secret between the app and itself).+///+/// Called from the `MemoryEvent::StoreCorruptQuarantined` arms of both event+/// sinks — the in-process one in [`crate::openhuman::memory::host`] and the+/// module bridge in `crate::openhuman::modules::memory_host` — so the notice+/// fires whichever engine detected the damage. `origin` names the detecting+/// path; `quarantined_path` is the preserved copy, logged and never sent.+pub(crate) fn publish_store_corrupt_user_error(origin: &str, quarantined_path: Option<&str>) {+ match quarantined_path {+ Some(path) => log::error!(+ "[memory::host] the memory-tree store was corrupt and has been quarantined \+ (detected by {origin}). The damaged file is PRESERVED at {path} — recovery \+ tooling (e.g. `sqlite3 .recover`) can likely salvage most of it. The rebuilt \+ store is empty; re-sync memory sources to repopulate"+ ),+ None => log::error!(+ "[memory::host] the memory-tree store was corrupt and has been quarantined \+ (detected by {origin}); the damaged file is preserved beside the store as \+ chunks.db.corrupt-<timestamp>. The rebuilt store is empty; re-sync memory \+ sources to repopulate"+ ),+ }+ crate::openhuman::web_chat::publish_web_channel_event(store_corrupt_quarantined_user_error());+}+#[cfg(test)]mod tests {use super::*;@@ -89,4 +166,61 @@ mod tests {fn source_matches_frontend_scope_mapping() {assert_eq!(MEMORY_USER_ERROR_SOURCE, "memory");}++ /// Same no-leak contract for the corrupt-store payload (openhuman#5820):+ /// the stable kind token and the memory source, never the quarantined+ /// path or SQLite prose.+ #[test]+ fn corrupt_store_payload_is_metadata_only() {+ let event = store_corrupt_quarantined_user_error();++ assert_eq!(event.event, "user_error");+ assert_eq!(event.client_id, "system");+ assert_eq!(event.error_type.as_deref(), Some(STORE_CORRUPT_KIND));+ assert_eq!(+ event.error_source.as_deref(),+ Some(MEMORY_USER_ERROR_SOURCE)+ );+ assert!(event.message.is_none(), "must not carry raw error prose");+ assert!(event.full_response.is_none());+ assert!(event.thread_id.is_empty());+ }++ /// The corrupt kind token is the same cross-language contract as the+ /// local-model one: `classify.ts` keys on exactly this string.+ #[test]+ fn corrupt_kind_matches_frontend_discriminator() {+ assert_eq!(STORE_CORRUPT_KIND, "memory_store_corrupt");+ }++ /// The wire-text classifier matches SQLite's two corruption renderings —+ /// the shapes a `MemoryError` string carries after crossing the bus — and+ /// nothing else. Quarantine-adjacent decisions key on this, so a false+ /// positive would raise a "memory quarantined" notice for a healthy store.+ #[test]+ fn corrupt_text_classifier_matches_sqlite_renderings_only() {+ assert!(is_corrupt_store_error(+ "memory-tree ingest failed for source `conversations:agent`: \+ database disk image is malformed"+ ));+ assert!(is_corrupt_store_error(+ "open failed: File is NOT a Database"+ ));+ assert!(!is_corrupt_store_error("database or disk is full"));+ assert!(!is_corrupt_store_error("rate limited (429)"));+ assert!(!is_corrupt_store_error(""));+ }++ /// The once-latch bounds the archivist's per-segment detection to one+ /// notice per process — 747 failing segments in the incident must not+ /// become 747 notices. (The engine's own quarantine event is un-latched+ /// and stays the authoritative per-quarantine notice.)+ #[test]+ fn wire_notice_is_latched_once_per_process() {+ // Publishing twice must be safe and quiet; the second call returns on+ // the latch. There is no socket in unit tests, so the observable+ // contract is "no panic, no double side effects on the latch path".+ notice_corrupt_store_once("test detector");+ notice_corrupt_store_once("test detector");+ }}diff --git a/src/openhuman/modules/memory_host.rs b/src/openhuman/modules/memory_host.rsindex fd6c80874c..f16e3c2257 100644--- a/src/openhuman/modules/memory_host.rs+++ b/src/openhuman/modules/memory_host.rs@@ -554,6 +554,20 @@ fn into_domain_event(event: MemoryEvent) -> Option<crate::core::events::DomainEvcrate::openhuman::memory::tree::health::user_error::publish_local_model_unavailable_user_error(&origin);return None;}+ // Web-channel-only (openhuman#5820): the module's engine already+ // quarantined and rebuilt its store; the host's job is to make sure+ // the user durably hears it — this is the arm the incident lacked,+ // where a module-side quarantine was invisible to every host surface.+ MemoryEvent::StoreCorruptQuarantined {+ origin,+ quarantined_path,+ } => {+ crate::openhuman::memory::tree::health::user_error::publish_store_corrupt_user_error(+ &origin,+ quarantined_path.as_deref(),+ );+ return None;+ }})}diff --git a/vendor/tinymemory b/vendor/tinymemoryindex 4141ec84c8..6048582d47 160000--- a/vendor/tinymemory+++ b/vendor/tinymemory@@ -1 +1 @@-Subproject commit 4141ec84c86dd8cbc39a99cbbbf39380018017e2+Subproject commit 6048582d47bfb81a51d25cc2c574cc8e8e218488