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 the quarantine notice durable and replayable
Shanu5c0b7f76fe70
diff --git a/.claude/memory.md b/.claude/memory.mdindex 8242074e32..b13d462683 100644--- a/.claude/memory.md+++ b/.claude/memory.md@@ -259,6 +259,7 @@ Quick reference for anyone starting with Claude on this project. Updated by the- **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.+- **Module source-registry path (the #5820 "no memory source registered" strand)** — the module must read the host's `<root>/config.toml` (beside `workspace/`), not `workspace_dir/config.toml`; the host sends `config_path` in the module config JSON (`modules/ops.rs`) and tinymemory ≥ v1.13.1 honours it with a sibling-file fallback. Test a module fix before its release with `OPENHUMAN_MODULE_PATH=<dir holding libtinymemory_module.dylib>` (build in `vendor/tinymemory/crates/tinymemory-module` with `cargo build --release`; it is its own cargo workspace).- **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`.- **Re-pinning the TinyMemory module moves five things in one commit** — gitlink → release tag commit, `modules/registry.rs` (version, release_url, 11 digests from the release's `checksum.toml`), the four workflow `memory_version`/`memory_sha256` pairs (ubuntu-22.04-x86_64 row), and `ARTIFACT_CAPABILITIES_PIN` in `modules/memory.rs` after diffing the capability surface between tags. Guards: `modules/memory_tests.rs` (workflow digests, capability pin). Run `cargo test --lib -- modules::memory modules::registry`. The version bump also dirties BOTH `Cargo.lock`s (root + `app/src-tauri`) and CI is `--locked`: `cargo metadata --locked --manifest-path <each>` then commit both.diff --git a/app/src/components/intelligence/MemoryTreeStatusPanel.tsx b/app/src/components/intelligence/MemoryTreeStatusPanel.tsxindex e65792a706..5030ca07e6 100644--- a/app/src/components/intelligence/MemoryTreeStatusPanel.tsx+++ b/app/src/components/intelligence/MemoryTreeStatusPanel.tsx@@ -23,7 +23,7 @@ import { useCallback, useEffect, useState } from 'react';import { useNavigate } from 'react-router-dom';import { useT } from '../../lib/i18n/I18nContext';-import { reportMemoryPipelineFailure } from '../../lib/userErrors/report';+import { reportMemoryPipelineFailure, reportMemoryQuarantine } from '../../lib/userErrors/report';import { useAppDispatch } from '../../store/hooks';import type { ToastNotification } from '../../types/intelligence';import { memoryTreeRetryFailed, memoryTreeSetEnabled } from '../../utils/tauriCommands';@@ -79,6 +79,16 @@ export function MemoryTreeStatusPanel({ onToast }: MemoryTreeStatusPanelProps) {useEffect(() => {reportMemoryPipelineFailure(dispatch, blockingCauseCode);}, [dispatch, blockingCauseCode]);+ // openhuman#5820: this panel polls faster than the shell, so a re-sync+ // retires the quarantine notice as soon as the first chunk lands.+ const quarantine = status?.quarantine ?? null;+ const quarantineKey = quarantine+ ? `${quarantine.quarantined_at_ms}:${quarantine.resynced}`+ : null;+ useEffect(() => {+ reportMemoryQuarantine(dispatch, quarantine);+ // eslint-disable-next-line react-hooks/exhaustive-deps -- keyed on the fields that matter+ }, [dispatch, quarantineKey]);const handleToggle = useCallback(async () => {if (!status || toggleBusy) return;diff --git a/app/src/components/notices/__tests__/useMemoryQuarantinePoll.test.tsx b/app/src/components/notices/__tests__/useMemoryQuarantinePoll.test.tsxnew file mode 100644index 0000000000..f017bc441f--- /dev/null+++ b/app/src/components/notices/__tests__/useMemoryQuarantinePoll.test.tsx@@ -0,0 +1,98 @@+import { act, renderHook } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { MEMORY_QUARANTINE_POLL_MS, useMemoryQuarantinePoll } from '../useMemoryQuarantinePoll';++const mockStatus = vi.fn();+const mockDispatch = vi.fn();+let mockAuthenticated = true;++vi.mock('../../../utils/tauriCommands/memoryTree', async importOriginal => {+ const actual = await importOriginal<typeof import('../../../utils/tauriCommands/memoryTree')>();+ return { ...actual, memoryTreePipelineStatus: (...args: unknown[]) => mockStatus(...args) };+});+vi.mock('../../../store/hooks', () => ({ useAppDispatch: () => mockDispatch }));+vi.mock('../../../providers/CoreStateProvider', () => ({+ useCoreState: () => ({ snapshot: { auth: { isAuthenticated: mockAuthenticated } } }),+}));++function statusWith(quarantine: unknown) {+ return {+ status: 'idle',+ reason: null,+ last_sync_ms: 0,+ total_chunks: 0,+ wiki_size_bytes: 0,+ pipeline_jobs: { ready: 0, running: 0, failed: 0, done: 0 },+ is_syncing: false,+ is_paused: false,+ quarantine,+ };+}++describe('useMemoryQuarantinePoll', () => {+ beforeEach(() => {+ vi.useFakeTimers();+ mockStatus.mockReset();+ mockDispatch.mockReset();+ mockAuthenticated = true;+ });+ afterEach(() => {+ vi.useRealTimers();+ });++ it('reports an outstanding quarantine on mount and again on the interval', async () => {+ mockStatus.mockResolvedValue(+ statusWith({ quarantined_at_ms: 1, quarantined_path: '/x', resynced: false })+ );+ renderHook(() => useMemoryQuarantinePoll());+ await act(async () => {+ await Promise.resolve();+ });+ expect(mockStatus).toHaveBeenCalledTimes(1);+ expect(mockDispatch).toHaveBeenCalledWith(+ expect.objectContaining({+ type: 'userErrors/reportUserError',+ payload: expect.objectContaining({+ descriptor: expect.objectContaining({ kind: 'memory_store_corrupt' }),+ }),+ })+ );++ await act(async () => {+ vi.advanceTimersByTime(MEMORY_QUARANTINE_POLL_MS);+ await Promise.resolve();+ });+ expect(mockStatus).toHaveBeenCalledTimes(2);+ });++ it('resolves the notice once the store has been re-synced', async () => {+ mockStatus.mockResolvedValue(+ statusWith({ quarantined_at_ms: 1, quarantined_path: '/x', resynced: true })+ );+ renderHook(() => useMemoryQuarantinePoll());+ await act(async () => {+ await Promise.resolve();+ });+ expect(mockDispatch).toHaveBeenCalledWith(+ expect.objectContaining({ type: 'userErrors/resolveUserError' })+ );+ });++ it('does nothing while signed out, and swallows a failed status read', async () => {+ mockAuthenticated = false;+ renderHook(() => useMemoryQuarantinePoll());+ await act(async () => {+ await Promise.resolve();+ });+ expect(mockStatus).not.toHaveBeenCalled();++ mockAuthenticated = true;+ mockStatus.mockRejectedValue(new Error('core restarting'));+ renderHook(() => useMemoryQuarantinePoll());+ await act(async () => {+ await Promise.resolve();+ });+ expect(mockDispatch).not.toHaveBeenCalled();+ });+});diff --git a/app/src/components/notices/useAppNotices.ts b/app/src/components/notices/useAppNotices.tsindex 3efe9fe088..f823de7981 100644--- a/app/src/components/notices/useAppNotices.ts+++ b/app/src/components/notices/useAppNotices.ts@@ -32,6 +32,7 @@ import type { UserActionableError, UserErrorAction } from '../../types/userErrorimport { PRICING_URL } from '../../utils/links';import { openUrl } from '../../utils/openUrl';import { dismissBanner, shouldShowBanner } from '../upsell/upsellDismissState';+import { useMemoryQuarantinePoll } from './useMemoryQuarantinePoll';export type NoticeSeverity = 'error' | 'warning' | 'info';@@ -119,6 +120,8 @@ export function useAppNotices(): AppNotice[] {const navigate = useNavigate();const active = useAppSelector(selectActiveUserErrors);const { level: budgetLevel, pct: budgetPct } = useEmbeddingBudgetState();+ // openhuman#5820: durable, app-wide replay of a corrupt-store quarantine.+ useMemoryQuarantinePoll();const {teamUsage,isLoading: usageLoading,diff --git a/app/src/components/notices/useMemoryQuarantinePoll.ts b/app/src/components/notices/useMemoryQuarantinePoll.tsnew file mode 100644index 0000000000..13628141c6--- /dev/null+++ b/app/src/components/notices/useMemoryQuarantinePoll.ts@@ -0,0 +1,51 @@+import { useEffect } from 'react';++import { reportMemoryQuarantine } from '../../lib/userErrors/report';+import { useCoreState } from '../../providers/CoreStateProvider';+import { useAppDispatch } from '../../store/hooks';+import { memoryTreePipelineStatus } from '../../utils/tauriCommands/memoryTree';++/**+ * How often the shell asks the core whether a corrupt-store quarantine is+ * outstanding. The condition changes on the order of a sync, not a keystroke,+ * and the status call is a handful of counters plus a directory walk.+ */+export const MEMORY_QUARANTINE_POLL_MS = 60_000;++/**+ * App-wide replay of the corrupt-store notice (openhuman#5820).+ *+ * The live `memory_store_corrupt` socket broadcast reaches only a renderer+ * that is connected when the quarantine happens; a boot-time integrity check+ * fires before that socket exists, and the broadcast has no replay. The+ * core derives the quarantine from disk in `memory_tree_pipeline_status`, so+ * polling it from the shell — not just from the Brain panel — puts the notice+ * in front of a user who never opens Brain, and retires it once they have+ * re-synced. Same descriptor id as the socket path, so the two never stack.+ */+export function useMemoryQuarantinePoll(): void {+ const dispatch = useAppDispatch();+ const { snapshot } = useCoreState();+ const isAuthenticated = snapshot.auth.isAuthenticated;++ useEffect(() => {+ if (!isAuthenticated) return;+ let cancelled = false;+ const tick = async () => {+ try {+ const status = await memoryTreePipelineStatus();+ if (!cancelled) reportMemoryQuarantine(dispatch, status.quarantine);+ } catch (err) {+ // Signed out mid-poll, core restarting: nothing to report, try again+ // next tick.+ console.debug('[memory-quarantine-poll] status read failed: %o', err);+ }+ };+ void tick();+ const id = window.setInterval(() => void tick(), MEMORY_QUARANTINE_POLL_MS);+ return () => {+ cancelled = true;+ window.clearInterval(id);+ };+ }, [dispatch, isAuthenticated]);+}diff --git a/app/src/lib/userErrors/__tests__/classify.test.ts b/app/src/lib/userErrors/__tests__/classify.test.tsindex f35586bffa..47dc244a2f 100644--- a/app/src/lib/userErrors/__tests__/classify.test.ts+++ b/app/src/lib/userErrors/__tests__/classify.test.ts@@ -2,6 +2,7 @@ import { describe, expect, it } from 'vitest';import {classifyMemoryPipelineFailure,+ classifyMemoryQuarantine,classifyUserActionableError,userErrorId,} from '../classify';@@ -158,6 +159,26 @@ describe('classifyUserActionableError', () => {// ── #5324: memory pipeline budget exhaustion ────────────────────────────────+describe('classifyMemoryQuarantine', () => {+ it('reports an outstanding quarantine under the same id as the socket path', () => {+ const fromPoll = classifyMemoryQuarantine({ resynced: false });+ const fromSocket = classifyUserActionableError({+ errorType: 'memory_store_corrupt',+ scope: 'memory',+ sourceDomain: 'memory',+ });+ expect(fromPoll?.kind).toBe('memory_store_corrupt');+ expect(fromPoll?.action).toBe('open_memory_sync');+ expect(fromPoll?.id).toBe(fromSocket?.id);+ });++ it('is null once the store has been re-synced, and for no quarantine at all', () => {+ expect(classifyMemoryQuarantine({ resynced: true })).toBeNull();+ expect(classifyMemoryQuarantine(null)).toBeNull();+ expect(classifyMemoryQuarantine(undefined)).toBeNull();+ });+});+describe('classifyMemoryPipelineFailure', () => {it('promotes a budget-exhausted memory pipeline to a user-actionable error', () => {const d = classifyMemoryPipelineFailure('budget_exhausted');diff --git a/app/src/lib/userErrors/classify.ts b/app/src/lib/userErrors/classify.tsindex 2831c263c6..b2dad07116 100644--- a/app/src/lib/userErrors/classify.ts+++ b/app/src/lib/userErrors/classify.ts@@ -34,6 +34,32 @@ export interface RuntimeErrorSignal {provider?: string;}+/**+ * The durable form of the corrupt-store notice (openhuman#5820).+ *+ * Same kind, scope and therefore the same descriptor id as the live+ * `memory_store_corrupt` socket broadcast, so the two paths collapse into+ * one NoticeCenter entry: the socket reaches a connected renderer instantly,+ * and the status poll replays it for a renderer that was not connected when+ * the quarantine happened (a boot-time integrity check). `null` once the+ * user has re-synced — the caller resolves the entry then.+ */+export function classifyMemoryQuarantine(+ quarantine: { resynced: boolean } | null | undefined+): UserErrorDescriptor | null {+ if (!quarantine || quarantine.resynced) return null;+ return {+ id: userErrorId('memory_store_corrupt', 'memory'),+ kind: 'memory_store_corrupt',+ severity: 'error',+ scope: 'memory',+ sourceDomain: 'memory',+ titleKey: 'userErrors.memoryStoreCorrupt.title',+ bodyKey: 'userErrors.memoryStoreCorrupt.body',+ action: 'open_memory_sync',+ };+}+/*** #5324: the memory pipeline's typed `budget_exhausted` cause, promoted to a* first-class user-actionable error.diff --git a/app/src/lib/userErrors/report.ts b/app/src/lib/userErrors/report.tsindex 79aa6e04b6..d59d06d9a6 100644--- a/app/src/lib/userErrors/report.ts+++ b/app/src/lib/userErrors/report.ts@@ -10,11 +10,13 @@import debug from 'debug';import type { AppDispatch } from '../../store';-import { reportUserError } from '../../store/userErrorsSlice';+import { reportUserError, resolveUserError } from '../../store/userErrorsSlice';import {classifyMemoryPipelineFailure,+ classifyMemoryQuarantine,classifyUserActionableError,type RuntimeErrorSignal,+ userErrorId,} from './classify';const log = debug('openhuman:user-errors');@@ -74,3 +76,31 @@ export function reportMemoryPipelineFailure(return false;}}++/**+ * Replay a quarantine from the pipeline-status poll into the durable+ * NoticeCenter, and retire it once the store has been re-synced+ * (openhuman#5820). Never throws; returns whether a notice is active.+ */+export function reportMemoryQuarantine(+ dispatch: AppDispatch,+ quarantine: { resynced: boolean } | null | undefined+): boolean {+ try {+ const descriptor = classifyMemoryQuarantine(quarantine);+ if (descriptor) {+ log('memory quarantine active kind=%s', descriptor.kind);+ dispatch(reportUserError({ descriptor, at: Date.now() }));+ return true;+ }+ if (quarantine?.resynced) {+ dispatch(+ resolveUserError({ id: userErrorId('memory_store_corrupt', 'memory'), at: Date.now() })+ );+ }+ return false;+ } catch (err) {+ log('memory quarantine ingest failed: %o', err);+ return false;+ }+}diff --git a/app/src/utils/tauriCommands/memoryTree.ts b/app/src/utils/tauriCommands/memoryTree.tsindex 5891a7f8b7..f5a37f9184 100644--- a/app/src/utils/tauriCommands/memoryTree.ts+++ b/app/src/utils/tauriCommands/memoryTree.ts@@ -880,6 +880,22 @@ export interface MemoryTreePipelineStatus {* structure ("empty-but-built wiki"). Optional for back-compat.*/extraction_coverage?: number | null;+ /**+ * openhuman#5820: the most recent corrupt-store quarantine, derived from+ * disk by the core so it survives restarts and reaches a renderer that was+ * not connected when it happened. Absent when nothing was quarantined.+ */+ quarantine?: MemoryTreeQuarantine | null;+}++/** A corrupt-store quarantine as `memory_tree_pipeline_status` reports it. */+export interface MemoryTreeQuarantine {+ /** Epoch ms of the quarantine (from the `.corrupt-<ts>` file name). */+ quarantined_at_ms: number;+ /** Local path of the preserved damaged database. */+ quarantined_path: string;+ /** A chunk landed after the quarantine: the rebuilt store is repopulating. */+ resynced: boolean;}/**diff --git a/src/openhuman/memory/tree/tree/rpc.rs b/src/openhuman/memory/tree/tree/rpc.rsindex 135a58bcf0..ae88b5eb76 100644--- a/src/openhuman/memory/tree/tree/rpc.rs+++ b/src/openhuman/memory/tree/tree/rpc.rs@@ -898,10 +898,62 @@ pub struct PipelineStatusResponse {/// (`#[serde(default)]` → `None` for older clients).#[serde(default)]pub extraction_coverage: Option<f32>,+ /// openhuman#5820: the most recent corrupt-store quarantine in this+ /// workspace, derived from disk (`memory_tree/chunks.db.corrupt-<ts>`),+ /// so it survives restarts and reaches a renderer that was not connected+ /// when the quarantine happened. `None` when nothing was ever quarantined.+ /// Reported until a sync lands after the quarantine (`resynced`), which+ /// is when the rebuilt store stops being empty.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub quarantine: Option<QuarantineStatus>,}/// `memory_tree_pipeline_status` RPC handler (#1856 Part 1).///+/// A corrupt-store quarantine as the status surface reports it (openhuman#5820).+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]+pub struct QuarantineStatus {+ /// Epoch milliseconds of the quarantine, parsed from the file name's UTC+ /// timestamp (`chunks.db.corrupt-%Y%m%dT%H%M%SZ`).+ pub quarantined_at_ms: i64,+ /// The preserved copy of the damaged database. Local to this machine and+ /// shown only to its own user, so the user can hand it to recovery tooling.+ pub quarantined_path: String,+ /// Whether a chunk has been written since the quarantine — the rebuilt+ /// store is being repopulated, so the notice can retire.+ pub resynced: bool,+}++/// Newest `chunks.db.corrupt-<ts>` under `<workspace>/memory_tree`, if any.+///+/// Disk is the durable record: the engine's quarantine renames the damaged+/// file beside the store and never deletes it, so a status read after a+/// restart — or from a renderer that missed the live event — still finds it.+/// Side-file quarantines (`chunks.db-wal.corrupt-…`) do not match the prefix.+fn latest_quarantine(+ workspace_dir: &std::path::Path,+ most_recent_chunk_ms: i64,+) -> Option<QuarantineStatus> {+ const PREFIX: &str = "chunks.db.corrupt-";+ let dir = workspace_dir.join("memory_tree");+ let newest = std::fs::read_dir(&dir)+ .ok()?+ .filter_map(|entry| entry.ok())+ .filter_map(|entry| {+ let name = entry.file_name().to_str()?.to_owned();+ let stamp = name.strip_prefix(PREFIX)?.to_owned();+ let at = chrono::NaiveDateTime::parse_from_str(&stamp, "%Y%m%dT%H%M%SZ").ok()?;+ Some((at.and_utc().timestamp_millis(), entry.path()))+ })+ .max_by_key(|(at, _)| *at)?;+ let (quarantined_at_ms, path) = newest;+ Some(QuarantineStatus {+ quarantined_at_ms,+ quarantined_path: path.display().to_string(),+ resynced: most_recent_chunk_ms > quarantined_at_ms,+ })+}+/// Aggregates `list_sources` + `count_by_status` + a recursive disk-size/// probe into the [`PipelineStatusResponse`] the UI status panel renders./// All blocking work is dispatched onto `spawn_blocking` so the async@@ -1025,6 +1077,19 @@ pub async fn pipeline_status_rpc(// back to the active degradation cause, then `None` when healthy.let first_blocking_cause = latest_failure.or_else(|| degraded.cause.clone());+ // openhuman#5820: disk-derived so it is durable and replayable; computed+ // from the same `store` observation as `last_sync_ms` so "resynced" and+ // the tile agree.+ let quarantine = latest_quarantine(config.workspace_dir.as_path(), last_sync_ms);+ if let Some(q) = &quarantine {+ log::debug!(+ "[memory-tree][rpc] pipeline_status: quarantine at={} resynced={} path={}",+ q.quarantined_at_ms,+ q.resynced,+ q.quarantined_path+ );+ }+let payload = PipelineStatusResponse {status: status.clone(),reason: reason.clone(),@@ -1037,6 +1102,7 @@ pub async fn pipeline_status_rpc(degraded,first_blocking_cause,extraction_coverage,+ quarantine,};log::debug!(@@ -2103,6 +2169,41 @@ mod tests {/// `derive_pipeline_status` precedence is locked in here so the UI can/// rely on the wire status string without re-deriving it from the raw/// counters.+ #[test]+ fn latest_quarantine_reads_the_newest_copy_and_derives_resynced() {+ let tmp = tempfile::tempdir().unwrap();+ let dir = tmp.path().join("memory_tree");+ std::fs::create_dir_all(&dir).unwrap();+ // No quarantine file: nothing to report.+ assert!(latest_quarantine(tmp.path(), 0).is_none());++ std::fs::write(dir.join("chunks.db.corrupt-20260101T000000Z"), b"old").unwrap();+ std::fs::write(dir.join("chunks.db.corrupt-20260827T070304Z"), b"new").unwrap();+ // Side files never match the main-file prefix.+ std::fs::write(dir.join("chunks.db-wal.corrupt-20261231T235959Z"), b"wal").unwrap();+ // Garbage that starts with the prefix but has no parsable stamp is ignored.+ std::fs::write(dir.join("chunks.db.corrupt-notastamp"), b"x").unwrap();++ let at = chrono::NaiveDate::from_ymd_opt(2026, 8, 27)+ .unwrap()+ .and_hms_opt(7, 3, 4)+ .unwrap()+ .and_utc()+ .timestamp_millis();++ // A chunk written before the quarantine: the rebuilt store is still empty.+ let pending = latest_quarantine(tmp.path(), at - 1).expect("newest quarantine");+ assert_eq!(pending.quarantined_at_ms, at);+ assert!(pending+ .quarantined_path+ .ends_with("chunks.db.corrupt-20260827T070304Z"));+ assert!(!pending.resynced);++ // A chunk written after it: the user re-synced, the notice can retire.+ let done = latest_quarantine(tmp.path(), at + 1).expect("newest quarantine");+ assert!(done.resynced);+ }+#[test]fn derive_pipeline_status_precedence_matches_spec() {use crate::openhuman::memory::tree::health::{DegradedState, FailureCode, PipelineFailure};