Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

Route the chunk, entity, graph, admin and cleanup reads onto the memory contract

Shanu5828ad9d2235
diff --git a/Cargo.lock b/Cargo.lock
index 4a792d65a9..e72749a48b 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -6553,7 +6553,7 @@ dependencies = [
[[package]]
name = "tinymemory"
-version = "1.4.0"
+version = "1.3.0"
dependencies = [
"anyhow",
"async-trait",
diff --git a/app/src-tauri/vendor/tauri-cef b/app/src-tauri/vendor/tauri-cef
new file mode 160000
index 0000000000..11ef51edbe
--- /dev/null
+++ b/app/src-tauri/vendor/tauri-cef
@@ -0,0 +1 @@
+Subproject commit 11ef51edbeadcca4517b18a037fff858a5dfae0f
diff --git a/app/src-tauri/vendor/tauri-plugin-notification b/app/src-tauri/vendor/tauri-plugin-notification
new file mode 160000
index 0000000000..5f61969018
--- /dev/null
+++ b/app/src-tauri/vendor/tauri-plugin-notification
@@ -0,0 +1 @@
+Subproject commit 5f619690188c6dbad58ceb170e9a86d61971c334
diff --git a/plan-5560.md b/plan-5560.md
new file mode 100644
index 0000000000..59fe4ff072
--- /dev/null
+++ b/plan-5560.md
@@ -0,0 +1,349 @@
+# openhuman#5560 — remaining work, host side
+
+**Audience:** whoever finishes `#5560` in the **openhuman** repo.
+**Boundary:** the upstream half (tinycortex + tinymemory) is **written, tested and pushed** — see *Upstream, not yours* below. What is left upstream is two merges and a release tag, none of which is code. Everything in "Your work" assumes those have happened.
+
+Every file:line in this document was verified against the trees on 2026-08-25. Where a claim was inherited from an earlier session and turned out to be wrong, it is corrected here and marked.
+
+---
+
+## 1. Where the issue actually stands
+
+`#5560`'s own acceptance criteria, measured at `0410ce73a` + the two commits after it:
+
+| # | Criterion | Status |
+|---|---|---|
+| 1 | `grep -r 'tinymemory_core::' src/` clean outside the seam | ❌ **236 non-comment refs across 113 files** |
+| 2 | Crate out of the build (`cargo tree -i tinymemory-core`) | ❌ still resolves at the product feature set |
+| 3 | Kernel floor ratcheted down | ❌ blocked on 2 |
+| 4 | cargo-machete `ignored` entries removed | ❌ `Cargo.toml:35` |
+| 5 | Behaviour unchanged + coverage on the bus path | ✅ for everything migrated so far |
+| 6 | `AGENTS.md` memory section updated | ❌ — and **currently wrong**: line 941 claims "~71 lines across 38 production files"; actual is 236/113 |
+
+**1 of 6.** Criteria 2–4 are one gate: they all fall together on the day the last reference goes, and not before. Progress before that day does not move the table, which is why the count dropping 285 → 236 shows up nowhere above.
+
+### What is already done (do not redo)
+
+Every call site whose fix was *"add a contract member and route the caller"* is migrated, and this is now proven rather than asserted — all 86 distinct engine symbols were classified: **15 EXACT** (migrated), **9 SHAPE_DIFFERS**, **44 NO_MEMBER** (they hand out a handle, not data). The `SeamExpressible` bucket in the ratchet is empty.
+
+Shipped: the diagnostics seam, recency recall, reset/flush, the archivist's episodic pivot, preferences, the safety scrubbers, the CLI read paths, and the type/alias surface.
+
+### The remaining 236, by bucket
+
+| Bucket | Refs | Nature |
+|---|---|---|
+| chunk-store (`store::chunks`, `content`, `fts5`, `segments`, `profile`, `namespace_store`) | 93 | the big one — needs the new members below |
+| engine-handle (`global::*`, `MemoryClient`, `UnifiedMemory`, `factories`) | 27 | **structurally last** — they *construct* the engine |
+| tree / ingest (`tree`, `ingest_pipeline`, `ingestion`) | 22 | partly covered by #99's `summary_forest` / `recent_leaves` |
+| chat-seam (`chat::`) | 19 | host-side provider construction; mostly `#[cfg(test)]` |
+| sync-pipeline (`sync::`, `tinycortex::`) | 12 | composio sync + sources registry |
+| queue (`queue::start`, `drain_until_idle`) | 5 | see H3 — cannot go until the module owns a pool |
+
+Top production files: `memory/host_impls.rs` (15 — the host→engine seam, **never leaves**), `memory/sources/rpc.rs` (10), `memory/store_golden.rs` (7, allowlisted fixture), `agent/experience/ops.rs` (5), `memory/tree/retrieval/rpc.rs` (4, all `#[cfg(test)]`), `memory/ops/sync.rs` (4).
+
+---
+
+## 2. Upstream, not yours
+
+In flight, being finished separately. **Do not start Phase E until Phase D is done.**
+
+**All upstream code is written, verified and pushed as of 2026-08-25.** Nothing below is left to implement. Three non-code steps remain, and the first one needs a permission the author of this branch does not have.
+
+| Repo | PR / artifact | State |
+|---|---|---|
+| tinycortex (`neocortex`) | **#157** `feat/5560-filtered-chunk-count` @ `ef09f09` | open, **all checks green**, review threads answered and resolved, ⛔ **needs a maintainer merge** |
+| tinymemory | **#99** `feat/5560-close-every-gap` @ `38e03fb` | open, CI green, gitlink points at #157 @ `ef09f09` |
+| tinymemory | v1.4.0 (`346fe4e`) | released — what the host pins today |
+| tinymemory | **v1.5.0** | ⛔ not cut yet; cannot be cut until #157 then #99 merge |
+
+> ⛔ **The one hard blocker.** `gh pr merge 157 -R tinyhumansai/tinycortex` is refused —
+> the branch author's permissions on that repo are `{"admin":false,"maintain":false,"pull":true,"push":false}`.
+> Someone with merge rights has to press the button. Everything downstream — #99's gitlink
+> re-point, #99's merge, the v1.5.0 tag, and this entire plan's Phase D — is queued behind
+> that single click. Nothing else is blocking.
+
+**#99 already adds** (do not re-request): `MemoryChunks::count_chunks`, `MemoryEntities::{top_entities, chunk_entities, entity_chunk_ids}`, `MemoryTree::{summary_forest, recent_leaves}`, and `CONTRACT_VERSION` (2,2) → (3,0).
+
+**Everything below is LANDED** on the two branches above. It is listed so you can code against the real names without reading the diffs.
+
+*Group 1 — unblocks Phase E.* ✅ landed in #99 + #157. Reduced from an original ~14 asks down to **4 new bus methods + 1 amendment + 6 additive `ChunkQuery` fields**:
+
+- `MemoryChunks::list_chunk_details(query, scope) -> Vec<ChunkListRow>` — one SELECT; explicitly *not* `chunk_detail` in a loop (that is 5 engine reads per chunk → a 1000-row page would be 5000 queries)
+- `MemoryChunks::source_totals(limit, scope) -> Vec<SourceTotal>`
+- `MemorySourceSink::forget_matching(&ForgetSelector) -> ForgetOutcome` — one door, four selectors (Chunk / Source / SourcePrefix / Owner)
+- `MemoryMaintenance::purge_all() -> PurgeOutcome`
+- **amend** `MemoryEntities::chunk_entities` to take `chunk_ids: &[String]` + `kinds` (legitimate only because #99 is unreleased; the `METHODS` sequence is untouched)
+- `ChunkQuery` gains `ids`, `source_kinds`, `source_ids`, `entity_ids`, `entity_kinds`, `content_contains` — all six land in one place (`append_filters`), so page / total / detail-list inherit them and cannot drift
+
+*Group 2 — unblocks Phase F.* ✅ landed in #99. Without these, deleting the host's second engine would be **data-loss-adjacent**, not merely incomplete (see H3):
+
+- **the module starts its own queue worker pool.** *(Done — `tinymemory-module/src/lib.rs`, `start_queue_pool`.)* `services.rs:256` in the host was the only caller of `queue::worker::start` in any tree; the module owns one now. It also carries `claim_queue_pool`, because `queue::start`'s `Once` is process-global while a pool is bound to one workspace — a second workspace in one process is not a second pool, it is a store with nothing draining its queue, and that now logs as an error instead of being invisible.
+ - Known degradation, stated rather than hidden: the pool consults the scheduler gate and registers a shutdown hook, and the module serves neither seam. So in module mode it runs **unthrottled** (ignores battery/CPU pressure) and its graceful lock-release hook is dropped — locks are recovered by lease expiry at startup instead, which `worker.rs` already documents as the hard-kill path. If throttling matters to the product, that needs a real `SchedulerGate` bus interface, which is a separate piece of work.
+- **`tinycortex/contacts` enabled in the module** *(Done — it replaces `people`, since upstream declares `contacts = ["people", ...]`.)* Otherwise Phase F silently loses macOS address-book seeding (H4b). Verified live: the locked release build links `objc2-contacts`.
+- **the two silently-degrading seams made loud** — `scheduler_gate` and `shutdown` now report once per process through the already-installed `ErrorReporter` instead of quietly doing nothing. *(Done.)*
+
+### 2a. The as-landed contract — code against these exact names
+
+Copied from the merged source, not paraphrased. All four new trait members are **defaulted to `Unsupported`**, so nothing that exists today stops compiling.
+
+```rust
+// tinymemory_api::provider::chunks
+pub trait MemoryChunks {
+ async fn list_chunk_details(&self, query: &ChunkQuery, scope: Option<&SourceScope>)
+ -> Result<Vec<ChunkListRow>, MemoryError>;
+ async fn source_totals(&self, limit: usize, scope: Option<&SourceScope>)
+ -> Result<Vec<SourceTotal>, MemoryError>;
+}
+
+pub struct ChunkListRow { // ChunkDetail MINUS `body`, deliberately
+ pub chunk: Chunk,
+ pub content_path: Option<String>,
+ pub lifecycle_status: Option<String>,
+ pub has_embedding: bool,
+}
+
+pub struct SourceTotal {
+ pub source_kind: SourceKind, // decoded enum, not a raw String
+ pub source_id: String,
+ pub chunk_count: u64,
+ pub most_recent_ms: i64, // rows are ordered by this, DESC
+}
+
+// the six additive ChunkQuery fields — every one #[serde(default, skip_serializing_if = ...)]
+pub struct ChunkQuery {
+ /* ...existing... */
+ pub ids: Vec<String>,
+ pub source_kinds: Vec<SourceKind>,
+ pub source_ids: Vec<String>,
+ pub entity_ids: Vec<String>,
+ pub entity_kinds: Vec<String>,
+ pub content_contains: Option<String>,
+}
+
+// tinymemory_api::provider::records / mod
+async fn forget_matching(&self, selector: &ForgetSelector) -> Result<ForgetOutcome, MemoryError>;
+async fn purge_all(&self) -> Result<PurgeOutcome, MemoryError>;
+
+// tinymemory_api::provider::knowledge — AMENDED, not added
+async fn chunk_entities(&self, chunk_ids: &[String], kinds: Option<&[String]>)
+ -> Result<Vec<ChunkEntityOccurrence>, MemoryError>; // was: (chunk_id, ) -> [EntityOccurrence]
+```
+
+Five things about this surface that will save you a debugging session:
+
+- **An empty `Vec` predicate means UNFILTERED, not match-nothing.** Forced by `Default` + `#[serde(default)]`. The footgun is real: a caller that *computed* a candidate set and got nothing must short-circuit and skip the query, because the query will happily return everything.
+- **`entity_ids` and `entity_kinds` are two independent `EXISTS` clauses.** Setting both asks for a chunk with some listed entity *and* some entity of a listed kind — not for one index row satisfying both.
+- **`ChunkListRow` has no body, on purpose.** `ChunkDetail::body`'s docs promise `None` means the vault read *failed*; a listing can only honour that by reading every file or by lying. If you need bodies, that is `chunk_detail`, per row, knowingly.
+- **`content_contains` folds case for ASCII only** and scans the text the driver holds *inline* — for a chunk whose body went to the content vault that is the stored preview, not the whole document. It narrows a browse; it does not replace `MemoryRecall`.
+- **`chunk_entities` rows each name their own chunk.** Group by `row.chunk_id`; never index the result by position against the ids you sent.
+
+**`PurgeOutcome::rows_deleted` is a cross-table sum, matching what `wipe_all_rpc` already reports.** This was a real disagreement between the engine and the contract during implementation and it was settled in favour of the host's existing wire shape: `WipeAllResponse.rows_deleted` has always been the sum over its nine tables, so returning only chunk rows would have shrunk a number the user already reads without anything having changed about what was forgotten. The engine's scoped deletes still return chunk counts — that asymmetry is deliberate and documented at `purge_all`.
+
+**Upstream verification actually run** (not "should pass"): both `cargo check --workspace --all-targets` trees; `cargo test --workspace` (1919 pass) and `--all-features` (1781 pass); the full CI feature matrix, all 13 rows; `cargo clippy --all-targets --all-features -D warnings` on the root and the module workspace; `cargo fmt --check` on both; `cargo doc --no-deps --all-features` with `-D warnings`; `cargo deny check` (advisories/bans/licenses/sources ok); `engine-containment.sh` and `dependency-budget.sh`; production-source coverage 81.89% and module coverage 86.81% lines, both over the 80% gate; the `--locked` release cdylib build; and the loader E2E, all 12 cases, one process per test, against that release artifact. `cargo hack --feature-powerset` is the one CI lane not run locally — `cargo-hack` is not installed on this machine.
+
+**Deliberately dropped, with reasons** (so nobody re-raises them): `chunk_score` / `DEFAULT_DROP_THRESHOLD` (engine-internal ranking the contract excludes by design); a per-chunk `delete_chunk` (folded into `forget_matching`); an Obsidian vault-registration member (host desktop policy — move the code like `redact`/`safety` did); a doctor chunk-count member (already covered by `store_stats().chunks`); a `delete_source` member (covered by existing `forget_source`).
+
+---
+
+## 3. The ordering — this is the part that bites
+
+Nothing in the host refuses a contract-version mismatch, so the usual "bump and see" instinct is unsafe here.
+
+```
+PHASE A merge tinycortex #157 ← code done, green; needs a MAINTAINER click
+PHASE B re-point #99's vendor/tinycortex to A's merge SHA, merge #99
+PHASE C tag + release tinymemory v1.5.0 ← MUST precede any host change
+PHASE D ONE host commit, five pins move together ← YOUR FIRST TASK
+PHASE E route the new members, strike ALLOWED entries in the same commit
+PHASE F delete the second engine — LAST; the gate is open once v1.5.0 ships Group 2
+```
+
+Phases A–C are not development work. A is one click by someone with merge rights on
+tinycortex. B is a one-line gitlink bump (`git -C vendor/tinycortex checkout <A's merge SHA>`,
+commit, push to the fork branch backing #99) plus a second click. C is the repo's normal
+release flow. Only then does Phase D — your first task — become safe.
+
+#157 holds every engine-side query the new members forward to, not just
+`count_chunks_matching`: the six filter predicates, `list_chunk_details`, `source_totals`,
+the by-id delete arm, and `purge_all`. Merging #99 without it does not compile.
+
+**Phase F is where the issue actually closes.** Phases D and E clear roughly 13 of the 133 production references; the other ~120 — the engine handles, the queue boot, the sync and chat seams — only go in F. Anyone reading D+E as "done" will be surprised by the checkbox table.
+
+### Phase D — one commit, all five or none
+
+1. `vendor/tinycortex` `b7cf121` → merged tinycortex SHA — **without this the host does not compile** (see H4a)
+2. `vendor/tinymemory` `346fe4e` → merged #99 SHA
+3. `src/openhuman/modules/registry.rs:205-262` — version, `release_url`, all 11 archive names, all 11 sha256, **taken verbatim from the release's `checksum.toml`**, never recomputed locally
+4. `src/openhuman/modules/memory.rs:51` `ARTIFACT_CAPABILITIES_PIN` `"1.4.0"` → `"1.5.0"` — else `the_capability_list_matches_the_pinned_release` goes red
+5. All four CI download sites: `ci-full.yml:132`, `ci-lite.yml:749`, `e2e-reusable.yml:167` and `:365`
+
+> There is a re-pin helper that reads the release's own `checksum.toml` and rewrites `registry.rs`; it self-tests to byte-identical output when pointed at the already-pinned tag. Ask for it rather than hand-editing 11 digests.
+
+**The only safe half-state is "release cut, host untouched."** Never "gitlink bumped, registry still on the old version."
+
+---
+
+## 4. Hazards — verified, with evidence
+
+### H1 — a version mismatch is not caught by anything *(mechanism corrected)*
+
+The earlier framing was "bind refused → silent empty." That is **wrong, and the truth is worse**: `is_compatible` (`tinymemory-bus/src/version.rs:86`) is major-equality as documented, but it has **zero call sites in the entire graph** — every hit is a re-export. The host's `PeerManifest` never declares the memory interface.
+
+The only cross-check is `ModuleMemoryProvider::verify` (`src/openhuman/modules/memory.rs:388-406`), which compares **capabilities only**, and capabilities are family-granular. #99's six new methods all land inside `Chunks` / `Entities` / `Tree` — families v1.4.0 already advertises. So `verify()` stays green, `as_chunks()` returns `Some`, the call goes out, and the module answers `UnknownMethod` → `MemoryError::Other`.
+
+CI would not catch it either: `modules/memory_tests.rs:237-254` compares a version **string**, `:45-81` asserts `capabilities_for(false) == Capabilities::all()` (no new family → green), and all four CI lanes download the **released** artifact rather than building `vendor/tinymemory`.
+
+**Consequence:** Phase C is not a formality. The release must exist before the host learns the new contract.
+
+### H2 — the host boots two engines *(confirmed verbatim)*
+
+`src/core/runtime/context.rs:608` calls `global::init(cfg.workspace_dir)`, and `:621` binds the module driver — same `if plan.memory` block, and both resolve to `<workspace>/memory/memory.db`. Two live `MemoryClient`s over one SQLite file.
+
+**Delete:** `context.rs:606-614` (the `global::init` arm) and its `:640` skip-log twin.
+**18 sites depend on it**, each its own migration to `CoreContext::memory_binding` / `MemoryProvider`:
+`store_golden.rs:145,:520` · `ops/documents.rs:381` · `ops/sync.rs:212,:253` · `ops/helpers.rs:391,:395` · `ops/test_support.rs:49` · `security/credentials/ops.rs:595,:835` · `desktop/app_state/ops.rs:526` · `agent/experience/ops.rs:78,:84,:116,:118` · `agent/learning/startup.rs:32` · `agent/harness/session/builder/factory.rs:266` · `integrations/composio/schemas.rs:937` · `core/memory_cli.rs:633`
+
+The deletion is already the tree's stated intent — `binding.rs:16-24` and `context.rs:310-319` both argue the workspace-keyed map supersedes the global slot. It was argued and never executed.
+
+### H3 — deleting the second engine breaks the queue *(this is the sequencing crux)*
+
+`flush_pending` is **not** a no-op today — the host starts the only worker pool that exists (`services.rs:256`, the sole caller of `queue::worker::start` in any tree).
+
+But **every enqueue in the released driver depends on that host-started pool**: `retry_failed`, `ensure_reembed_backfill`, and the ingest `extract_chunk` enqueue — that last one is how ingested content becomes retrievable at all. Delete H2's second engine and all of them become permanent no-ops.
+
+This cannot be fixed by any host change. **The module must start its own pool** — done, in #99 (`tinymemory-module/src/lib.rs`, `start_queue_pool`). Verify before you delete anything: the release you pin must contain the module-owned pool, not just the Group 1 members. Grep the tag, not the working tree.
+
+Accept the two degradations that come with it, or fix them first: in module mode the pool runs **unthrottled** and its shutdown hook is dropped. Both are stated at the function and in §2 — neither loses work, but the first is a real battery/CPU behaviour change on desktop.
+
+### H3b — the composio sync loop has no home once the engine goes *(found 2026-08-25; NOT in the original plan)*
+
+Same class as H3, found the same way, and it is on the critical path for criteria 1 and 2.
+
+The engine reaches its host through nine seam traits installed as process globals. In module
+mode the module installs **seven** (`error_reporter`, `event_sink`, `nlp_host`,
+`scheduler_gate`, `shutdown_host`, `chat_host`, `embedding_host`). The host installs **eight**
+(`memory/host_impls.rs`). The two the module does *not* install are **`ComposioHost`** and
+**`ConfigLoader`**.
+
+That is not academic, because composio sync is **engine code running in the host process**:
+
+```
+core/runtime/services.rs:265 integrations::composio::start_periodic_sync()
+integrations/composio/mod.rs:66 → memory::sync::composio::periodic
+memory/sync/composio/mod.rs:8 → pub use tinymemory_core::sync::composio::*
+```
+
+So the host starts the *engine's* periodic loop against the host's own engine handle. Delete
+that engine and the loop has no engine to run against; keep the loop and the engine crate can
+never leave the build — which is criterion 2.
+
+**It fails quietly, which is why it has to be designed against rather than discovered.**
+`composio_host::require_composio_host()` returns `Err` and `is_available()` returns `false`
+when unset. Nothing panics, nothing logs by default: composio sync would simply stop, and the
+first symptom is a user noticing their Slack or Gmail memory went stale.
+
+**Being fixed upstream now**, in the same PR (#99) and following the pattern that already
+works: `ChatHost` and `EmbeddingHost` are served *by the host* over the bus
+(`modules/memory_host.rs`) and consumed by the module (`chat.rs`, `embedding.rs`).
+`ComposioHost` gets the same treatment — 4 methods, small trait. `ConfigLoader` is answered
+module-side from the `ModuleConfig` the module is already handed, because proxying it would
+mean asking the host to re-read a config the module already has, and the two could disagree.
+Ownership of the periodic loop moves to the module, following `start_queue_pool`'s precedent
+including its process-global guard.
+
+**Order this imposes on Phase F:** the host-side `pub use tinymemory_core::sync::composio::*`
+shim and the `services.rs:265` start come out **together with** the in-process engine, never
+before. Removing them earlier stops composio sync in a tree that still boots that engine.
+
+### H4a — a build break nobody has hit yet
+
+The host resolves tinycortex through `[patch.crates-io] tinycortex = { path = "vendor/tinycortex" }` (`Cargo.toml:1237`) — its **own** top-level submodule, currently `b7cf121`, *not* the copy inside `vendor/tinymemory`. `Cargo.toml:223-225` says so explicitly.
+
+`git show b7cf121:src/memory/chunks/store_list.rs | grep -c count_chunks_matching` → **0**. So bumping only `vendor/tinymemory` fails to compile. Both gitlinks move in Phase D or neither does.
+
+### H4b — `contacts` was off in the module *(fixed upstream — keep reading, the reason still matters)*
+
+`crates/tinymemory-module/Cargo.toml:39` enabled `people` but not `contacts`. #99 now enables `contacts` there (it supersedes `people`, which upstream declares as a subset), and the locked release build was checked to link `objc2-contacts`. The reason is worth keeping in front of you anyway, because it is the shape of every remaining Phase F hazard: the shipping desktop build turns `contacts` **on** (`app/src-tauri/Cargo.toml:186` → `Cargo.toml:975` → `tinymemory-core/Cargo.toml:129`), and the whole people domain is a glob re-export of the in-process engine (`memory/people/mod.rs:8`). macOS address-book seeding works today *because* the second engine exists. Phase F must not land before a **released** module carries `contacts` — the code is on #99, so this closes when v1.5.0 ships, not when #99 merges.
+
+### H4c — the tree's own tripwires fire during the cutover
+
+Defuse them **in the commit that causes them**, never after:
+
+1. `direct_engine_refs_tests.rs:730-742` `direct_reference_scanner_is_not_vacuous` asserts `found.len() > 20` and that `memory/mod.rs` is in the set — the final cutover drives both to zero **by design**. Rewrite it with the last removal.
+2. `:825-841` `the_blocked_set_matches_the_engine_still_being_linked` is the deliberate "day the engine leaves" tripwire, **and its failure message is the closing checklist**: drop the path deps (`Cargo.toml:241-260` + the dev-dep at `:657`), remove the machete `ignored` entry (`:35`), ratchet `scripts/kernel-floor.limits`, rewrite the module docs.
+3. `:804-816` `nothing_is_left_migratable` fails on **any** `Verdict::SeamExpressible`. `ALLOWED` is currently 22 `HostSide` + 56 `NeedsWiderSeam` + 0 `SeamExpressible`; the new members make some of those 56 seam-expressible. The test's own doc calls re-labelling-to-silence *"the one edit that would make the lint lie."* **Strike each routed file from `ALLOWED` in the commit that routes it.**
+4. Same discipline on `bypass_allowlist_tests.rs:544-557` and `:567-578` — and `docs/specs/memory-guard-allowlist.md` moves in step. That allowlist's rule is *may shrink, never grow*; if you need a test-only fixture, put it under a `test_support/` directory, which the scanner skips by path.
+
+---
+
+## 5. Your work — Phase E, site by site
+
+Each row is one migration. The RPC response fields are listed because **wire shape must not change** — these are read by `MemoryControls`, `OverviewPanel` and `MedullaDemoGraph`.
+
+| Site | Operation | Member to use |
+|---|---|---|
+| `read_rpc/chunks.rs:54` `list_chunks_blocking` | paged list + unpaged total | `list_chunk_details` + `count_chunks`, with the six new `ChunkQuery` fields |
+| `read_rpc/chunks.rs:208` `list_sources_blocking` | `GROUP BY source_kind, source_id` | `source_totals` (`display_name` stays host-side) |
+| `read_rpc/chunks.rs:268` `search_rpc` | content search | `list_chunk_details` with `content_contains` only |
+| `read_rpc/chunks.rs:354` `recall_rpc` hydrate | N ids → rows | `list_chunk_details` with `ids` — one call, re-map by id to preserve leaf order |
+| `read_rpc/entities.rs:30` `entity_index_for` | entities of a chunk | `chunk_entities(&[id], None)` — **already available from #99** |
+| `read_rpc/entities.rs:74` `chunks_for_entity` | chunk ids for an entity | `entity_chunk_ids` — **#99**. Note it *requires* a limit; the SQL has none. Use `MAX_LIST_LIMIT` (`read_rpc/types.rs`) |
+| `read_rpc/entities.rs:110` `top_entities` | ranked entities | `top_entities` — **#99**. ⚠️ behaviour delta: the member returns `MemoryError::Invalid` for an unknown kind; the RPC currently returns an empty list |
+| `read_rpc/entities.rs:236` `delete_chunk_rpc` | delete + side rows | `forget_matching(ForgetSelector::Chunk)` |
+| `read_rpc/graph.rs:109,:250` `collect_tree_graph` | summary forest + leaves | `summary_forest` + `recent_leaves` — **#99**, field-for-field |
+| `read_rpc/graph.rs:352` `collect_contacts_graph` | person-kind chunks + edges | `ChunkQuery.entity_kinds` + amended `chunk_entities(ids, kinds)` — **one call, not 1500** |
+| `read_rpc/admin.rs:33` `wipe_all` | truncate 9 tables | `purge_all` (host keeps the content-dir removal and `dirs_removed`) |
+| `read_rpc/admin.rs:110` `clear_composio_sync_state` | raw `Connection::open` | `kv_list` + `kv_delete` — this is a **second unpoliced door** beside `with_connection` |
+| `read_rpc/admin.rs` `delete_source_rpc` | chunks + orphan tree | `forget_matching(Source)` — returns `trees_cleaned`, so `DeleteSourceResponse` keeps its shape |
+| `read_rpc/vault.rs:5` | Obsidian registration | **move the code host-side**; do not widen the contract |
+| `platform/doctor/core.rs:834` | `SELECT COUNT(*)` | `store_stats().chunks` — the file's own comment already says so; the blocker is that `run` is sync and `store_stats` is async, so hoist the probe into the caller |
+| `channels/controllers/ops/connect.rs:240` | clear channel memory | `forget_matching(Source + SourcePrefix, Chat)` |
+| `integrations/composio/ops/memory_cleanup.rs:21,:24,:31` | exact / prefix / owner deletes | `forget_matching`, all three arms |
+
+**Not gaps — do not touch:** `read_rpc/mod.rs:54` (the `with_connection` re-export is `#[cfg(test)]`-gated at `:53`), `tree/retrieval/rpc.rs:510-534` (all inside `#[cfg(test)]`), `store_golden.rs` (deliberately outside the contract; its module doc explains the escape hatches).
+
+**Stale comments to delete as you go:** `read_rpc/entities.rs:13-20` claims those three handlers have no member — #99 added all three. And the `ALLOWED` verdicts for all eleven target files say *"MemoryChunks is read-only … with no write or transaction door"*, which still holds for the write sites but not the reads.
+
+---
+
+## 6. Verification
+
+Four scopes, because the default commands miss three of them:
+
+```bash
+export RUST_MIN_STACK=16777216
+export GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0=commit.gpgsign GIT_CONFIG_VALUE_0=false # macOS: temp-repo tests hang on pinentry otherwise
+F="$(bash scripts/ci/product-features.sh)"
+
+cargo check --all-targets --features "$F" # tests/ targets are NOT covered by --lib
+cargo clippy -p openhuman --features "$F" -- -D warnings
+cargo clippy -p openhuman -- -D warnings # CI lints the DEFAULT set too
+cargo test --lib --features "$F"
+cargo metadata --locked # and again for app/src-tauri — two Cargo worlds
+```
+
+Also: `crates/tinymemory-module` is its own workspace with its own lockfile; the root `cargo fmt --all` does not reach it.
+
+**One local-only caveat:** `cargo test --lib` hangs on `tree_e2e_tests::full_pipeline_ingest_to_retrieval`. It does not set `embeddings_provider = "none"` the way its sibling does, so it calls the live embedding service. Pre-existing, unrelated to this work, fine in CI.
+
+**Module-backed tests** need `TINYMEMORY_TEST_MODULE` pointing at a built cdylib, and must run **one process per test** — tinybus binds broker tasks to the creating runtime and never unloads, so a second module-loading test in one process *hangs rather than fails*.
+
+---
+
+## 7. Definition of done
+
+The closing checklist is not this document's invention — it is the failure message of `the_blocked_set_matches_the_engine_still_being_linked`:
+
+- [ ] `grep -rn 'tinymemory_core::' src/` returns nothing outside `memory/host_impls.rs` and the binding
+- [ ] `Cargo.toml:241-260` path deps dropped, plus the dev-dependency at `:657`
+- [ ] cargo-machete `ignored` entry removed (`Cargo.toml:35`)
+- [ ] `scripts/assert-shed.sh` proves the crate gone from the product graph
+- [ ] `scripts/kernel-floor.limits` ratcheted — **measure on Linux**; macOS resolves +1/+1 from `core-foundation` / `security-framework`
+- [ ] `AGENTS.md` memory section rewritten (its current figure is 3× off)
+- [ ] both ratchets rewritten rather than silenced (H4c)
+
+**Honest estimate:** Phase D is an afternoon. Phase E is a few days. **Phase F is the long one** — 18 `global::` consumers plus the sync, chat and queue seams, each its own migration, and it is the phase that actually flips the checkboxes. Its upstream gate (module-owned pool + `contacts`) is being closed now, so it is no longer blocked, but it is not a day's work either. Anyone promising #5560 closes this week has not read §4.
+
+**Scope note:** every upstream dependency in §2 is **already written and pushed** — both groups. If you hit something that needs a *new* contract member, that is a bug in this plan; say so rather than widening the contract yourself, because a member added host-side cannot ship (the host pins a released, digest-verified artifact, and §4 H1 explains why the mismatch would be silent rather than loud).
+
+**Housekeeping:** a stray copy of the tinymemory branch was pushed to `tinyhumansai/tinymemory` as `feat/5560-close-every-gap` before being pushed to the fork where PR #99 actually lives. It is byte-identical to the fork branch and harmless, but it should be deleted — `git push origin --delete feat/5560-close-every-gap` from a checkout whose `origin` is upstream.
diff --git a/src/core/runtime/services.rs b/src/core/runtime/services.rs
index 3ec849d5cf..65024a860b 100644
--- a/src/core/runtime/services.rs
+++ b/src/core/runtime/services.rs
@@ -260,6 +260,42 @@ pub fn start_bootstrap_jobs(services: ServiceSet, config: &Config) {
// Integrations — Composio periodic connection sync + one-shot source
// reconcile. Both no-op without active Composio connections.
+ //
+ // ── This call comes out with the in-process engine, and not before ──────
+ //
+ // `start_periodic_sync` is not host code. It re-exports through
+ // `integrations::composio::mod.rs` to `memory::sync::composio::periodic`,
+ // and that module is `pub use tinymemory_core::sync::composio::*` — so the
+ // loop this line starts is engine code running in the host process against
+ // the engine this binary still compiles in. `ensure_composio_sources` below
+ // reaches `tinymemory_core::sources` the same way.
+ //
+ // openhuman#5560 deletes that second, in-process engine and leaves the
+ // loaded TinyMemory module as the only one. Deleting this line before then
+ // stops Composio sync outright; leaving it after would run a loop against
+ // an engine that is no longer there. Both are silent — the sync layer
+ // reports "no connections", which is indistinguishable from a user who has
+ // none — so the removal is ordered, and every step before the last has to
+ // land first:
+ //
+ // 1. The host serves `ai.tinyhumans.tinymemory.ComposioHost` over the
+ // module bus. Done — `modules/memory_host.rs`.
+ // 2. The module installs a bus-backed `ComposioHost` seam, so engine code
+ // running *inside* the module can reach this host's Composio client.
+ // Without it `require_composio_host()` returns `Err` and `is_available`
+ // reads `false`, which is the quiet failure above.
+ // 3. The module starts the sync loop itself at load, because nothing in
+ // the host will be able to. `tinymemory-module`'s `install_unserved_
+ // seams` names this explicitly: the module starts none of the
+ // background loops today; `queue::start`, `start_periodic_sync` and
+ // `start_workspace_periodic_sync` are all called host-side.
+ // 4. A `tinymemory` **release** carrying 2 and 3, and a re-pin of
+ // `modules::registry` to its digest. The registry pins a released,
+ // SHA-256-verified artifact, so until the re-pin the loaded module has
+ // neither, however far ahead `vendor/tinymemory` is.
+ // 5. Only then: delete this line, delete the shim at
+ // `memory/sync/composio/mod.rs`, and delete the host's in-process
+ // engine.
if plan.composio_integration_sync {
log::debug!("[runtime.bootstrap] starting composio integration sync + source reconcile");
crate::openhuman::integrations::composio::start_periodic_sync();
diff --git a/src/openhuman/agent/harness/archivist/mod.rs b/src/openhuman/agent/harness/archivist/mod.rs
index 9bd14b510c..4d1c412ae5 100644
--- a/src/openhuman/agent/harness/archivist/mod.rs
+++ b/src/openhuman/agent/harness/archivist/mod.rs
@@ -34,13 +34,7 @@ pub(crate) use crate::openhuman::agent::hooks::PostTurnHook;
#[cfg(test)]
pub(crate) use helpers::extract_profile_key;
#[cfg(test)]
-pub(crate) use parking_lot::Mutex;
-#[cfg(test)]
-pub(crate) use rusqlite::Connection;
-#[cfg(test)]
pub(crate) use std::sync::Arc;
-#[cfg(test)]
-pub(crate) use tinymemory_core::store::profile;
#[cfg(test)]
#[path = "../archivist_tests.rs"]
diff --git a/src/openhuman/agent/harness/archivist/tree_ingest.rs b/src/openhuman/agent/harness/archivist/tree_ingest.rs
index 677d59a679..dc9a372e8b 100644
--- a/src/openhuman/agent/harness/archivist/tree_ingest.rs
+++ b/src/openhuman/agent/harness/archivist/tree_ingest.rs
@@ -107,6 +107,12 @@ impl ArchivistHook {
path_scope: None,
author: Some(e.role.clone()),
channel_label: Some(session_id.to_string()),
+ // Mail-only fields; this source is not mail, and the contract
+ // documents empty/absent as the same statement as "not mail".
+ to: Vec::new(),
+ cc: Vec::new(),
+ subject: None,
+ list_unsubscribe: None,
platform: Some("agent".into()),
})
})
diff --git a/src/openhuman/agent/harness/archivist_tests.rs b/src/openhuman/agent/harness/archivist_tests.rs
index a740d34077..31f51ab834 100644
--- a/src/openhuman/agent/harness/archivist_tests.rs
+++ b/src/openhuman/agent/harness/archivist_tests.rs
@@ -1,6 +1,6 @@
use super::*;
use crate::openhuman::agent::hooks::{ToolCallRecord, TurnContext};
-use crate::openhuman::memory::api::provider::{MemoryEpisodic as _, MemoryProvider};
+use crate::openhuman::memory::api::provider::MemoryProvider;
use std::sync::OnceLock;
use tinymemory_core::chat::ChatPrompt;
// Assertion reads go straight at the engine's tables through the same client
@@ -738,7 +738,6 @@ async fn phase2_exactly_one_tree_ingest_per_segment_close() {
async fn phase2_exactly_one_tree_ingest_per_segment_close_inner() {
let (_tmp, cfg) = test_config_with_tree();
let (client, provider) = provider_over(&cfg.workspace_dir);
- let conn = client.profile_conn();
let hook = hook_with_stubs_and_tree_config(provider.clone(), cfg.clone());
let session = "phase2-one-ingest";
@@ -921,7 +920,6 @@ async fn phase2_ingested_content_is_raw_prose_not_recap() {
async fn phase2_ingested_content_is_raw_prose_not_recap_inner() {
let (_tmp, cfg) = test_config_with_tree();
let (client, provider) = provider_over(&cfg.workspace_dir);
- let conn = client.profile_conn();
let hook = hook_with_stubs_and_tree_config(provider.clone(), cfg.clone());
let session = "phase2-raw-prose";
@@ -990,7 +988,6 @@ async fn phase2_flush_also_triggers_tree_ingest() {
async fn phase2_flush_also_triggers_tree_ingest_inner() {
let (_tmp, cfg) = test_config_with_tree();
let (client, provider) = provider_over(&cfg.workspace_dir);
- let conn = client.profile_conn();
let hook = hook_with_stubs_and_tree_config(provider.clone(), cfg.clone());
let session = "phase2-flush-tree";
diff --git a/src/openhuman/channels/controllers/ops/connect.rs b/src/openhuman/channels/controllers/ops/connect.rs
index a053cf14b9..095f377a97 100644
--- a/src/openhuman/channels/controllers/ops/connect.rs
+++ b/src/openhuman/channels/controllers/ops/connect.rs
@@ -9,7 +9,7 @@ use crate::openhuman::config::{Config, DiscordConfig, IMessageConfig, TelegramCo
use crate::openhuman::security::credentials;
use crate::rpc::RpcOutcome;
use tinymemory_api::chunks::SourceKind;
-use tinymemory_core::store::chunks::store as memory_tree_store;
+use tinymemory_api::provider::ForgetSelector;
use super::super::definitions::{
all_channel_definitions, find_channel_definition, ChannelAuthMode, ChannelDefinition,
@@ -236,14 +236,73 @@ pub(super) async fn persist_email_config(
Ok(())
}
-fn clear_channel_memory(config: &Config, channel_id: &str) -> anyhow::Result<usize> {
- let exact = memory_tree_store::delete_chunks_by_source(config, SourceKind::Chat, channel_id)?;
- let prefixed = memory_tree_store::delete_chunks_by_source_prefix(
+/// Drop everything this channel put into memory, and report how many chunks
+/// went.
+///
+/// Two selectors because a channel files content under two shapes: the bare
+/// `channel_id` (the channel itself) and `channel_id:<conversation>` (each
+/// thread inside it). [`ForgetSelector::Source`] is exact by contract, so the
+/// first would leave every per-conversation source behind on its own; the
+/// prefix arm is matched literally, so a provider id containing `%` or `_`
+/// means itself.
+///
+/// No `spawn_blocking`: the driver owns whether its own reads and writes
+/// block, and the module's do not run on this thread at all.
+async fn clear_channel_memory(config: &Config, channel_id: &str) -> anyhow::Result<usize> {
+ let kind = SourceKind::Chat.as_str().to_string();
+ let exact = forget_matching(
+ config,
+ &ForgetSelector::Source {
+ source_kind: kind.clone(),
+ source_id: channel_id.to_string(),
+ },
+ )
+ .await?;
+ let prefixed = forget_matching(
config,
- SourceKind::Chat,
- &format!("{channel_id}:"),
- )?;
- Ok(exact + prefixed)
+ &ForgetSelector::SourcePrefix {
+ source_kind: kind,
+ source_id_prefix: format!("{channel_id}:"),
+ },
+ )
+ .await?;
+ Ok(exact.saturating_add(prefixed))
+}
+
+/// Run one [`ForgetSelector`] through the bound memory driver and return the
+/// chunk count it removed.
+///
+/// A driver without the `Sources` family is **refused**, not degraded to zero.
+/// The read paths elsewhere answer empty for a missing family because "this
+/// driver holds nothing" is a true answer to what they were asked; this is a
+/// delete, and its only empty answer — zero chunks removed — is
+/// byte-identical to a successful delete of nothing. The caller renders that
+/// number as `memory_chunks_deleted` in the disconnect reply, so degrading
+/// here would tell a user their channel's history was cleared when it is
+/// still on disk.
+///
+/// `trees_cleaned` is dropped on purpose: `memory_chunks_deleted` has always
+/// been a chunk count, and the disconnect reply's shape does not change here.
+async fn forget_matching(config: &Config, selector: &ForgetSelector) -> anyhow::Result<usize> {
+ let binding = crate::openhuman::memory::binding::for_config(config)
+ .map_err(|e| anyhow::anyhow!("forget_matching: {e}"))?;
+ let Some(sources) = binding.provider().as_sources() else {
+ return Err(anyhow::anyhow!(
+ "forget_matching: driver '{}' does not serve Sources",
+ binding.driver_id()
+ ));
+ };
+ let outcome = sources
+ .forget_matching(selector)
+ .await
+ .map_err(|e| anyhow::anyhow!("forget_matching: {e}"))?;
+ log::debug!(
+ "[channels][memory] forget_matching removed chunks={} trees={} (driver='{}')",
+ outcome.chunks_removed,
+ outcome.trees_cleaned,
+ binding.driver_id()
+ );
+ Ok(usize::try_from(outcome.chunks_removed).unwrap_or(usize::MAX))
}
/// List all available channel definitions.
@@ -642,9 +701,11 @@ pub async fn disconnect_channel(
}
let memory_chunks_deleted = if clear_memory {
- clear_channel_memory(config, channel_id).map_err(|e| {
- format!("channel disconnected, but failed to clear memory chunks: {e:#}")
- })?
+ clear_channel_memory(config, channel_id)
+ .await
+ .map_err(|e| {
+ format!("channel disconnected, but failed to clear memory chunks: {e:#}")
+ })?
} else {
0
};
diff --git a/src/openhuman/channels/controllers/ops_tests.rs b/src/openhuman/channels/controllers/ops_tests.rs
index 7bbd85dd64..e7f754f629 100644
--- a/src/openhuman/channels/controllers/ops_tests.rs
+++ b/src/openhuman/channels/controllers/ops_tests.rs
@@ -231,9 +231,16 @@ async fn disconnect_discord_bot_token_clears_runtime_config() {
);
}
+/// The clear-memory half of disconnect goes through the bound driver's
+/// `MemorySourceSink::forget_matching` now, so the workspace needs a driver
+/// that serves `Sources` — the null driver a unit-test workspace otherwise
+/// resolves to does not, and the handler refuses rather than reporting a
+/// delete of nothing. Seeding and reading back still go straight to the store,
+/// which is what makes this an end-to-end assertion rather than a mock.
#[tokio::test]
async fn disconnect_channel_clear_memory_deletes_matching_chat_sources() {
let (_tmp, mut config) = isolated_test_config();
+ crate::openhuman::memory::test_support::install_tinycortex_for_test(&config);
config.channels_config.discord = Some(DiscordConfig {
bot_token: "discord-token-abc".to_string(),
guild_id: Some("guild-1".to_string()),
diff --git a/src/openhuman/hosted/orchestration/effect_executor.rs b/src/openhuman/hosted/orchestration/effect_executor.rs
index 2bbcde4b97..60d7197f14 100644
--- a/src/openhuman/hosted/orchestration/effect_executor.rs
+++ b/src/openhuman/hosted/orchestration/effect_executor.rs
@@ -828,6 +828,12 @@ pub async fn execute_evict(effect: &EvictEffect) -> Result<(), String> {
author: None,
channel_label: None,
platform: None,
+ // Mail-only fields; this source is not mail, and the contract
+ // documents empty/absent as the same statement as "not mail".
+ to: Vec::new(),
+ cc: Vec::new(),
+ subject: None,
+ list_unsubscribe: None,
// The chunk tier cannot carry a non-default taint and the driver
// rejects an item that claims one, so `Internal` is the only value
// ingest accepts. It is also the true one: this is the hosted
diff --git a/src/openhuman/integrations/composio/README.md b/src/openhuman/integrations/composio/README.md
index 27550ffc4a..64a5a1b640 100644
--- a/src/openhuman/integrations/composio/README.md
+++ b/src/openhuman/integrations/composio/README.md
@@ -105,7 +105,8 @@ Published from `ops.rs`: `DomainEvent::ComposioConnectionCreated` (authorize), `
- `crate::openhuman::integrations` — shared `IntegrationClient` (Bearer JWT, timeouts, envelope parsing, proxy) backing backend-mode calls.
- `crate::openhuman::config` — `Config` / `ComposioConfig` (`mode`, `entity_id`), `config::rpc` config loading.
-- `crate::openhuman::memory`, `memory_store`, `memory_tree` — memory client + chunk store/tree for ingestion and connection-scoped memory cleanup.
+- `crate::openhuman::memory` — the memory client used for ingestion and for reading a provider's sync state during cleanup-target discovery.
+- `crate::openhuman::memory::binding` — the workspace's bound memory driver. Connection-scoped cleanup deletes through `MemorySourceSink::forget_matching` (the `Source` / `SourcePrefix` / `Owner` selectors), not through the engine's chunk store (#5560). A driver that does not serve `Sources` is refused per target, and the refusal is reported beside `memory_chunks_deleted` rather than read as a delete of nothing.
- `crate::openhuman::memory::sync::composio` — the actual home of providers, periodic sync, and bus subscribers (this module re-exports them via shims).
- `crate::openhuman::agent::harness` — sandbox mode (`current_sandbox_mode` / `SandboxMode`) for tool gating.
- `crate::openhuman::tools::traits` — `Tool`, `ToolResult`, `ToolCategory`, `PermissionLevel`, `ToolCallOptions`.
diff --git a/src/openhuman/integrations/composio/ops/connections.rs b/src/openhuman/integrations/composio/ops/connections.rs
index c10b048f3a..6dbee2d2bf 100644
--- a/src/openhuman/integrations/composio/ops/connections.rs
+++ b/src/openhuman/integrations/composio/ops/connections.rs
@@ -188,7 +188,7 @@ pub async fn composio_delete_connection(
let mut memory_chunks_deleted = 0;
let mut memory_clear_errors = Vec::new();
for target in &memory_targets {
- match target.delete(config) {
+ match target.delete(config).await {
Ok(deleted) => {
memory_chunks_deleted += deleted;
}
diff --git a/src/openhuman/integrations/composio/ops/memory_cleanup.rs b/src/openhuman/integrations/composio/ops/memory_cleanup.rs
index 266261777e..29dd677b51 100644
--- a/src/openhuman/integrations/composio/ops/memory_cleanup.rs
+++ b/src/openhuman/integrations/composio/ops/memory_cleanup.rs
@@ -4,9 +4,18 @@ use std::sync::Arc;
use crate::openhuman::config::Config;
use tinymemory_api::chunks::SourceKind;
-use tinymemory_core::store::chunks::store as memory_tree_store;
+use tinymemory_api::provider::ForgetSelector;
use tinymemory_core::store::MemoryClientRef;
+/// One thing a connection delete has to remove from memory.
+///
+/// The three variants are the three [`ForgetSelector`] arms this domain needs,
+/// named in this domain's own vocabulary: a Composio connection files content
+/// under an exact source id, under a family of derived ids sharing a prefix,
+/// and — for a mailbox shared with other connections — under an owner. They
+/// stay a local enum rather than becoming `ForgetSelector` directly because
+/// `label` is what a partial-failure message shows the user, and that wording
+/// is this host's.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum MemoryCleanupTarget {
Exact(SourceKind, String),
@@ -15,24 +24,71 @@ pub(crate) enum MemoryCleanupTarget {
}
impl MemoryCleanupTarget {
- pub(super) fn delete(&self, config: &Config) -> anyhow::Result<usize> {
+ /// The contract selector this target names.
+ ///
+ /// `source_kind` crosses as a wire string because the set of source kinds
+ /// belongs to the host's sync machinery and grows without a contract
+ /// change; `SourceKind::as_str` is the same spelling `label` already
+ /// shows.
+ fn selector(&self) -> ForgetSelector {
match self {
- Self::Exact(source_kind, source_id) => {
- memory_tree_store::delete_chunks_by_source(config, *source_kind, source_id)
- }
- Self::Prefix(source_kind, source_id_prefix) => {
- memory_tree_store::delete_chunks_by_source_prefix(
- config,
- *source_kind,
- source_id_prefix,
- )
- }
- Self::Owner(source_kind, owner) => {
- memory_tree_store::delete_chunks_by_owner(config, *source_kind, owner)
- }
+ Self::Exact(source_kind, source_id) => ForgetSelector::Source {
+ source_kind: source_kind.as_str().to_string(),
+ source_id: source_id.clone(),
+ },
+ Self::Prefix(source_kind, source_id_prefix) => ForgetSelector::SourcePrefix {
+ source_kind: source_kind.as_str().to_string(),
+ source_id_prefix: source_id_prefix.clone(),
+ },
+ Self::Owner(source_kind, owner) => ForgetSelector::Owner {
+ source_kind: source_kind.as_str().to_string(),
+ owner: owner.clone(),
+ },
}
}
+ /// Remove this target through the bound memory driver, returning the chunk
+ /// count it took with it.
+ ///
+ /// A driver without the `Sources` family is **refused**, not degraded to
+ /// zero: this is a delete, and its only empty answer — zero chunks
+ /// removed — is byte-identical to a successful delete of nothing. The
+ /// caller sums these into `memory_chunks_deleted` on the delete-connection
+ /// reply, so a silent zero would tell the user a disconnected account's
+ /// mail had left memory while it is still on disk. The caller already
+ /// collects per-target failures and reports them beside the count, so a
+ /// refusal here is surfaced rather than fatal.
+ ///
+ /// `ForgetOutcome::trees_cleaned` is dropped on purpose —
+ /// `memory_chunks_deleted` has always been a chunk count, and this does
+ /// not change the reply's shape.
+ ///
+ /// No `spawn_blocking`: the driver owns whether its own writes block, and
+ /// the module's do not run on this thread at all.
+ pub(super) async fn delete(&self, config: &Config) -> anyhow::Result<usize> {
+ let binding = crate::openhuman::memory::binding::for_config(config)
+ .map_err(|e| anyhow::anyhow!("forget_matching: {e}"))?;
+ let Some(sources) = binding.provider().as_sources() else {
+ return Err(anyhow::anyhow!(
+ "forget_matching: driver '{}' does not serve Sources",
+ binding.driver_id()
+ ));
+ };
+ let selector = self.selector();
+ let outcome = sources
+ .forget_matching(&selector)
+ .await
+ .map_err(|e| anyhow::anyhow!("forget_matching: {e}"))?;
+ log::debug!(
+ "[composio][memory] forget_matching target={} removed chunks={} trees={} (driver='{}')",
+ self.label(),
+ outcome.chunks_removed,
+ outcome.trees_cleaned,
+ binding.driver_id()
+ );
+ Ok(usize::try_from(outcome.chunks_removed).unwrap_or(usize::MAX))
+ }
+
pub(super) fn label(&self) -> String {
match self {
Self::Exact(source_kind, source_id) => {
diff --git a/src/openhuman/integrations/composio/ops_tests.rs b/src/openhuman/integrations/composio/ops_tests.rs
index 9481cdbaf9..c12c075c72 100644
--- a/src/openhuman/integrations/composio/ops_tests.rs
+++ b/src/openhuman/integrations/composio/ops_tests.rs
@@ -549,6 +549,11 @@ async fn composio_delete_connection_clear_memory_deletes_slack_source() {
let base = start_mock_backend(app).await;
let tmp = tempfile::tempdir().unwrap();
let config = config_with_backend(&tmp, base);
+ // The memory clear-out runs through the bound driver now that it is routed
+ // onto `forget_matching`, so the test has to bind one. TinyCortex is the
+ // engine the loadable module wraps, and unlike the module it is not a
+ // process singleton, so several of these can share one test binary.
+ crate::openhuman::memory::test_support::install_tinycortex_for_test(&config);
let target = sample_memory_chunk(SourceKind::Chat, "slack:c1", 0);
let unrelated = sample_memory_chunk(SourceKind::Chat, "slack:c2", 0);
memory_tree_store::upsert_chunks(&config, &[target, unrelated]).expect("chunks should seed");
@@ -604,6 +609,11 @@ async fn composio_delete_connection_clear_memory_cascades_source_tree_and_conten
let base = start_mock_backend(app).await;
let tmp = tempfile::tempdir().unwrap();
let config = config_with_backend(&tmp, base);
+ // The memory clear-out runs through the bound driver now that it is routed
+ // onto `forget_matching`, so the test has to bind one. TinyCortex is the
+ // engine the loadable module wraps, and unlike the module it is not a
+ // process singleton, so several of these can share one test binary.
+ crate::openhuman::memory::test_support::install_tinycortex_for_test(&config);
// One slack chunk for connection c1 → source_id `slack:c1`.
let chunk = sample_memory_chunk(SourceKind::Chat, "slack:c1", 0);
@@ -727,6 +737,11 @@ async fn composio_delete_connection_clear_memory_cascades_live_sealed_tree_and_f
let base = start_mock_backend(app).await;
let tmp = tempfile::tempdir().unwrap();
let mut config = config_with_backend(&tmp, base);
+ // The memory clear-out runs through the bound driver now that it is routed
+ // onto `forget_matching`, so the test has to bind one. TinyCortex is the
+ // engine the loadable module wraps, and unlike the module it is not a
+ // process singleton, so several of these can share one test binary.
+ crate::openhuman::memory::test_support::install_tinycortex_for_test(&config);
// Force the inert embedder so the real seal's summary-embed step doesn't
// reach a live endpoint. `config_with_backend` stores a cloud session +
// api_url, so the factory would otherwise build a *cloud* embedder against
@@ -844,6 +859,11 @@ async fn composio_delete_connection_clear_memory_keeps_other_gmail_connections()
let base = start_mock_backend(app).await;
let tmp = tempfile::tempdir().unwrap();
let config = config_with_backend(&tmp, base);
+ // The memory clear-out runs through the bound driver now that it is routed
+ // onto `forget_matching`, so the test has to bind one. TinyCortex is the
+ // engine the loadable module wraps, and unlike the module it is not a
+ // process singleton, so several of these can share one test binary.
+ crate::openhuman::memory::test_support::install_tinycortex_for_test(&config);
let c1_account = sample_memory_chunk_with_owner(
SourceKind::Email,
"gmail:pilot-at-example-dot-com",
diff --git a/src/openhuman/memory/api.rs b/src/openhuman/memory/api.rs
index d60afdd34c..f5f02e7de2 100644
--- a/src/openhuman/memory/api.rs
+++ b/src/openhuman/memory/api.rs
@@ -78,18 +78,28 @@ pub use tinymemory_api::{
wire, CONTRACT_VERSION,
};
-/// The inbound half of the seam: the only two `tinymemory_api::host` types that
-/// cross the bus, rather than the whole engine-embedding namespace.
+/// The inbound half of the seam: the `tinymemory_api::host` types that cross
+/// the bus, named one at a time rather than as the whole engine-embedding
+/// namespace.
///
-/// `modules/memory_host.rs` serves two of them — [`MemoryEvent`] is what the
-/// module publishes back into the host's event bus, and [`SpacyResponse`]
-/// answers the module's NLP callback. [`EvidenceRef`] joined them with the
-/// `Profile` capability family: it is not a callback type, but it is a field of
-/// `provider::profile::ProfileFacet`, so it crosses the bus in both directions
-/// whenever a facet does. That is the same rule the rest of this list follows —
-/// what actually crosses — and it is why the entry is here rather than being
-/// named on the crate at each call site. The rest of `tinymemory_api::host` is
-/// the in-process engine seam and must still be named on the crate.
+/// `modules/memory_host.rs` serves the callbacks two of them belong to —
+/// [`MemoryEvent`] is what the module publishes back into the host's event bus,
+/// and [`SpacyResponse`] answers the module's NLP callback. [`EvidenceRef`]
+/// joined them with the `Profile` capability family: it is not a callback type,
+/// but it is a field of `provider::profile::ProfileFacet`, so it crosses the bus
+/// in both directions whenever a facet does. [`ComposioConnection`] and
+/// [`ComposioExecuteResponse`] joined them with the `ComposioHost` interface:
+/// they are what `ListConnections` and `Execute` reply with once Composio is
+/// reached over the bus instead of through the in-process engine.
+///
+/// That is the same rule the rest of this list follows — what actually crosses
+/// — and it is why these entries are here rather than being named on the crate
+/// at each call site. It is also why `host::composio` is *not* re-exported
+/// whole: that namespace carries toolkits, catalog entries, GitHub repos and
+/// trigger payloads, none of which this seam moves. The rest of
+/// `tinymemory_api::host` is the in-process engine seam and must still be named
+/// on the crate.
pub mod host {
+ pub use tinymemory_api::host::composio::{ComposioConnection, ComposioExecuteResponse};
pub use tinymemory_api::host::{EvidenceRef, MemoryEvent, SpacyResponse};
}
diff --git a/src/openhuman/memory/api_identity_tests.rs b/src/openhuman/memory/api_identity_tests.rs
index abcf087b3c..4675a7e986 100644
--- a/src/openhuman/memory/api_identity_tests.rs
+++ b/src/openhuman/memory/api_identity_tests.rs
@@ -82,13 +82,14 @@ fn provider_contract_is_the_contract_crates() {
}
/// The **inbound** half of the seam. `memory::api::host` deliberately re-exports
-/// two types rather than the whole `tinymemory_api::host` namespace: that
+/// named types rather than the whole `tinymemory_api::host` namespace: that
/// namespace is the in-process engine-embedding seam (the persisted
/// `MemoryConfig` sections, `MemoryHostConfig`, `EmbeddingProvider`,
-/// `MemoryEventSink`), none of which touches the bus. These two do —
+/// `MemoryEventSink`), none of which touches the bus. These do —
/// `modules/memory_host.rs` publishes `MemoryEvent` back onto the host's event
-/// bus and answers the module's NLP callback with `SpacyResponse` — so these
-/// two are contract, and must be the crate's types rather than lookalikes.
+/// bus, answers the module's NLP callback with `SpacyResponse`, and replies to
+/// the module's `ComposioHost` calls with the two Composio types — so each is
+/// contract, and must be the crate's type rather than a lookalike.
#[test]
fn host_seam_types_are_the_contract_crates() {
fn event(
@@ -104,6 +105,23 @@ fn host_seam_types_are_the_contract_crates() {
s
}
let _ = spacy as fn(_) -> _;
+
+ fn connection(
+ c: crate::openhuman::memory::api::host::ComposioConnection,
+ ) -> tinymemory_api::host::composio::ComposioConnection {
+ c
+ }
+ let _ = connection as fn(_) -> _;
+
+ // Also the type `integrations::composio::types` re-exports, which is what
+ // makes the bus reply and the host's own Composio client one type rather
+ // than two that serialise the same today.
+ fn execute(
+ r: crate::openhuman::memory::api::host::ComposioExecuteResponse,
+ ) -> crate::openhuman::integrations::composio::types::ComposioExecuteResponse {
+ r
+ }
+ let _ = execute as fn(_) -> _;
}
/// Version negotiation is contract. `memory::binding` and `memory::ops::provider`
diff --git a/src/openhuman/memory/direct_engine_refs_tests.rs b/src/openhuman/memory/direct_engine_refs_tests.rs
index 7ff79a3979..ffc304a81d 100644
--- a/src/openhuman/memory/direct_engine_refs_tests.rs
+++ b/src/openhuman/memory/direct_engine_refs_tests.rs
@@ -133,17 +133,22 @@
//! SQLite contract wearing a trait.
//! - **Host policy reached through the engine crate** — **drained.** The
//! scrubbers (`store::safety::{sanitize_text, sanitize_json,
-//! has_likely_secret}`), `util::redact::redact` and `source_scope::*` all
-//! live host-side now, in `memory::safety`, `util::redact` and
-//! `memory::source_scope`. The route each took is the shape to reuse, and it
-//! is **not** "move it to `tinymemory-api`": a scrubber costs `regex` +
-//! `serde_json` and `util::redact` costs `sha2` in a crate whose whole point
-//! is that a caller can depend on it and compile almost nothing, and
-//! `source_scope` is a `tokio::task_local`, which would put tokio there too.
-//! None of the three is contract vocabulary — nothing crosses the bus as a
-//! `SanitizationReport` or a log hash — so each is simply the host's, with
-//! the engine keeping its own copy for its own writes. Independent copies are
-//! the design: neither side reads the other's output.
+//! has_likely_secret}`), `util::redact::redact`, `source_scope::*` and the
+//! Obsidian vault-registration probe (`store::content::obsidian_registry`)
+//! all live host-side now, in `memory::safety`, `util::redact`,
+//! `memory::source_scope` and `memory::obsidian_registry`. The route each
+//! took is the shape to reuse, and it is **not** "move it to
+//! `tinymemory-api`": a scrubber costs `regex` + `serde_json`,
+//! `util::redact` costs `sha2`, and the vault probe costs `dirs` +
+//! `serde_json`, in a crate whose whole point is that a caller can depend on
+//! it and compile almost nothing — and `source_scope` is a
+//! `tokio::task_local`, which would put tokio there too. None of the four is
+//! contract vocabulary — nothing crosses the bus as a `SanitizationReport`,
+//! a log hash or a `VaultRegistration`, and "is my content root a registered
+//! Obsidian vault" is not a capability a second driver would answer
+//! differently — so each is simply the host's, with the engine keeping its
+//! own copy for its own callers. Independent copies are the design: neither
+//! side reads the other's output.
//! - **The re-embed queue** (~8 files) — `queue::{start, store, types,
//! ensure_reembed_backfill, requeue_failed_after_provider_change,
//! drain_until_idle, wake_workers, backfill_in_progress}`. No family.
@@ -314,11 +319,6 @@ const ALLOWED: &[(&str, Verdict, &str)] = &[
Verdict::NeedsWiderSeam,
"reaches engine storage below the contract (store::events, store::fts5::EpisodicEntry, store::profile, store::segments, chat::build_chat_provider); MemoryChunks is read-only (list_chunks/get_chunk/chunk_detail/storage_kinds/chunk_embeddings) with no write or transaction door",
),
- (
- "src/openhuman/agent/harness/archivist/mod.rs",
- Verdict::NeedsWiderSeam,
- "reaches engine storage below the contract (store::profile); MemoryChunks is read-only (list_chunks/get_chunk/chunk_detail/storage_kinds/chunk_embeddings) with no write or transaction door",
- ),
(
"src/openhuman/agent/harness/archivist/recap.rs",
Verdict::NeedsWiderSeam,
@@ -359,11 +359,6 @@ const ALLOWED: &[(&str, Verdict, &str)] = &[
Verdict::NeedsWiderSeam,
"holds or boots the in-process engine handle (global::client_if_ready, store::MemoryClient); driver construction belongs to memory::binding and the seam has no door onto the live client",
),
- (
- "src/openhuman/channels/controllers/ops/connect.rs",
- Verdict::NeedsWiderSeam,
- "reaches engine storage below the contract (store::chunks::store, store::chunks::types::SourceKind); MemoryChunks is read-only (list_chunks/get_chunk/chunk_detail/storage_kinds/chunk_embeddings) with no write or transaction door",
- ),
(
"src/openhuman/channels/runtime/startup.rs",
Verdict::NeedsWiderSeam,
@@ -397,7 +392,7 @@ const ALLOWED: &[(&str, Verdict, &str)] = &[
(
"src/openhuman/integrations/composio/ops/memory_cleanup.rs",
Verdict::NeedsWiderSeam,
- "reaches engine storage below the contract (store::chunks::store, store::chunks::types::SourceKind, tinycortex::HostSyncAdapter); MemoryChunks is read-only (list_chunks/get_chunk/chunk_detail/storage_kinds/chunk_embeddings) with no write or transaction door",
+ "two blockers, both Phase F: the in-process engine handle (store::MemoryClientRef), which belongs to memory::binding; and engine internals (tinycortex::HostSyncAdapter, the reader for notion sync state), which are tinycortex-shaped so no engine-neutral family can express them. The three chunk deletes this entry also used to name are gone — they are MemorySourceSink::forget_matching now",
),
(
"src/openhuman/integrations/composio/ops/mod.rs",
@@ -442,33 +437,13 @@ const ALLOWED: &[(&str, Verdict, &str)] = &[
(
"src/openhuman/memory/read_rpc/admin.rs",
Verdict::NeedsWiderSeam,
- "reaches engine storage below the contract (queue::store, queue::types, queue::wake_workers, store::chunks::store); MemoryChunks is read-only (list_chunks/get_chunk/chunk_detail/storage_kinds/chunk_embeddings) with no write or transaction door",
- ),
- (
- "src/openhuman/memory/read_rpc/chunks.rs",
- Verdict::NeedsWiderSeam,
- "reaches engine storage below the contract (store::chunks::store::with_connection); MemoryChunks is read-only (list_chunks/get_chunk/chunk_detail/storage_kinds/chunk_embeddings) with no write or transaction door",
- ),
- (
- "src/openhuman/memory/read_rpc/entities.rs",
- Verdict::NeedsWiderSeam,
- "reaches engine storage below the contract (store::chunks::store::with_connection, util::redact::redact); MemoryChunks is read-only (list_chunks/get_chunk/chunk_detail/storage_kinds/chunk_embeddings) with no write or transaction door",
- ),
- (
- "src/openhuman/memory/read_rpc/graph.rs",
- Verdict::NeedsWiderSeam,
- "reaches engine storage below the contract (store::chunks::store::with_connection, util::redact::redact); MemoryChunks is read-only (list_chunks/get_chunk/chunk_detail/storage_kinds/chunk_embeddings) with no write or transaction door",
+ "one call left: flush_source_tree wants a live source-tree handle (tree_source::get_or_create_source_tree) to feed the host's TreeFactory label strategy and force_flush_tree, and MemoryTree is namespace-addressed (append/query_source/drill_down/seal/cascade/summary_forest/recent_leaves) with no door onto a tree object. wipe_all, clear_composio_sync_state and delete_source have left for purge_all, kv_list+kv_delete and forget_matching(Source)",
),
(
"src/openhuman/memory/read_rpc/mod.rs",
Verdict::NeedsWiderSeam,
"reaches engine storage below the contract (store::chunks::store::with_connection, store::chunks::types::SourceKind); MemoryChunks is read-only (list_chunks/get_chunk/chunk_detail/storage_kinds/chunk_embeddings) with no write or transaction door",
),
- (
- "src/openhuman/memory/read_rpc/vault.rs",
- Verdict::NeedsWiderSeam,
- "reaches engine storage below the contract (store::content::obsidian_registry, util::redact::redact); MemoryChunks is read-only (list_chunks/get_chunk/chunk_detail/storage_kinds/chunk_embeddings) with no write or transaction door",
- ),
(
"src/openhuman/memory/sources/rpc.rs",
Verdict::NeedsWiderSeam,
@@ -514,11 +489,6 @@ const ALLOWED: &[(&str, Verdict, &str)] = &[
Verdict::NeedsWiderSeam,
"ingest_pipeline and the chunk store's list/read helpers have no capability family; the queue reads left for the Maintenance members in tinymemory#85/#86/#89",
),
- (
- "src/openhuman/platform/doctor/core.rs",
- Verdict::NeedsWiderSeam,
- "reaches engine storage below the contract (store::chunks::store::with_connection, store::factories::effective_embedding_settings); MemoryChunks is read-only (list_chunks/get_chunk/chunk_detail/storage_kinds/chunk_embeddings) with no write or transaction door",
- ),
(
"src/openhuman/security/credentials/ops.rs",
Verdict::NeedsWiderSeam,
diff --git a/src/openhuman/memory/mod.rs b/src/openhuman/memory/mod.rs
index 7c9cd8057a..c46b7b27e3 100644
--- a/src/openhuman/memory/mod.rs
+++ b/src/openhuman/memory/mod.rs
@@ -30,6 +30,10 @@ pub mod driver;
pub mod guard;
pub mod host;
pub mod host_impls;
+/// Host desktop policy: is the memory content root a vault Obsidian already
+/// knows about? See the module docs for why this is OpenHuman's and not the
+/// engine's.
+pub mod obsidian_registry;
pub mod ops;
pub mod preferences;
pub mod sync_events_bridge;
diff --git a/src/openhuman/memory/obsidian_registry.rs b/src/openhuman/memory/obsidian_registry.rs
new file mode 100644
index 0000000000..64f06c6675
--- /dev/null
+++ b/src/openhuman/memory/obsidian_registry.rs
@@ -0,0 +1,232 @@
+//! Obsidian vault-*registration* detection for the memory content root.
+//!
+//! `obsidian://open?path=<abs>` only resolves against vaults already recorded
+//! in Obsidian's `obsidian.json` registry — it can **not** register a new
+//! vault, and a `.obsidian/` folder on disk is not enough. So before the
+//! Memory tab fires that deep link, [`vault_registration_status`] answers
+//! whether the content root (or an ancestor) is a vault Obsidian already
+//! knows about. If it is not, the UI guides the user to add it once ("Open
+//! folder as vault") instead of firing a link Obsidian rejects with *"Unable
+//! to find a vault for the URL"*.
+//!
+//! Detection is **best-effort**: Obsidian can live in non-standard locations
+//! (Flatpak, Snap, custom `$XDG_CONFIG_HOME`, portable). A negative result must
+//! never block the user — the caller still offers "open anyway" + "reveal
+//! folder" + a config-dir override that feeds back in here as `extra`.
+//!
+//! # Why this is OpenHuman's and not the engine's
+//!
+//! Same reasoning as [`crate::openhuman::memory::safety`] and
+//! [`crate::openhuman::util::redact`] before it, and the same route: this is
+//! **host desktop policy** that happened to live in the engine crate. Which
+//! third-party note-taking app this host deep-links into, and where that app
+//! keeps its config on each desktop OS, is a fact about the shipped desktop
+//! product — not about how memory is stored. Its one caller
+//! ([`crate::openhuman::memory::read_rpc::vault`]) is an RPC that reads the
+//! filesystem and never touches a chunk.
+//!
+//! Widening `tinymemory-api` to carry it instead would be the wrong trade for
+//! the reason `util::redact` records: the contract crate's manifest documents
+//! that it stays dependency-light so a caller can depend on it and compile
+//! almost nothing, and this policy costs `dirs` plus `serde_json`. Nor is it
+//! contract vocabulary — nothing crosses the bus as a [`VaultRegistration`],
+//! and "is my content root a registered Obsidian vault" is not a capability a
+//! second memory driver would answer differently. A driver that stores chunks
+//! in the cloud has no content root at all, and this probe would still be
+//! asked of the same local directory.
+//!
+//! The engine keeps its own copy for its own callers. The two are independent
+//! by design: neither reads the other's output, and both answer from the same
+//! on-disk `obsidian.json`, which is Obsidian's file rather than a wire value
+//! that has to agree across a boundary.
+//!
+//! # Ported verbatim
+//!
+//! Same candidate-path order, the same lexical (never canonicalising)
+//! normalisation, the same component-boundary ancestor test, the same
+//! empty-vault-path guard, and the same `config_found`-on-parse-failure
+//! semantics — so the RPC above answers exactly what it always answered. The
+//! engine's `types` submodule is inlined here because nothing outside the
+//! module ever named it; every item keeps its name, so the two copies stay
+//! diffable line for line. Only the log prefix changed, to this host's
+//! `[memory]` grep convention.
+
+use std::collections::HashMap;
+use std::path::{Path, PathBuf};
+
+use serde::Deserialize;
+
+use crate::openhuman::util::redact::redact;
+
+/// Outcome of a registration probe.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct VaultRegistration {
+ /// `true` when some registered Obsidian vault's path equals or is an
+ /// ancestor of the content root.
+ pub registered: bool,
+ /// `true` when at least one candidate `obsidian.json` was found/read (even
+ /// if parsing it later fails — see the parse-error branch, which still
+ /// counts the file as found). Lets the UI distinguish "Obsidian is set up,
+ /// vault just not added yet" from "couldn't find Obsidian at all" (offer
+ /// install vs. offer add-as-vault).
+ pub config_found: bool,
+}
+
+/// Minimal shape of Obsidian's `obsidian.json`. We only need each vault's
+/// `path`; `ts`/`open` and any future keys are ignored by `serde`.
+#[derive(Debug, Deserialize)]
+struct ObsidianConfig {
+ #[serde(default)]
+ vaults: HashMap<String, VaultEntry>,
+}
+
+/// One `vaults` entry of `obsidian.json`.
+#[derive(Debug, Deserialize)]
+struct VaultEntry {
+ path: String,
+}
+
+/// Candidate `obsidian.json` locations, in priority order. `extra` (a
+/// user-supplied override pointing at Obsidian's *config dir*) is checked
+/// first so a power user can correct a non-standard install.
+fn candidate_config_files(extra: Option<&Path>) -> Vec<PathBuf> {
+ let mut out = Vec::new();
+
+ if let Some(dir) = extra {
+ // Accept either the config dir itself or its parent (users often
+ // can't tell whether the path should end in `obsidian/`).
+ out.push(dir.join("obsidian.json"));
+ out.push(dir.join("obsidian").join("obsidian.json"));
+ }
+
+ // Standard per-OS config dir: `~/.config` (Linux), `~/Library/Application
+ // Support` (macOS), `%APPDATA%` (Windows).
+ if let Some(cfg) = dirs::config_dir() {
+ out.push(cfg.join("obsidian").join("obsidian.json"));
+ }
+
+ // Linux sandbox installs keep their own config tree. Harmless to probe on
+ // other OSes — the paths simply won't exist.
+ if let Some(home) = dirs::home_dir() {
+ out.push(home.join(".var/app/md.obsidian.Obsidian/config/obsidian/obsidian.json")); // Flatpak
+ out.push(home.join("snap/obsidian/current/.config/obsidian/obsidian.json"));
+ // Snap
+ }
+
+ log::debug!(
+ "[memory][obsidian_registry] candidate config files: n={}",
+ out.len()
+ );
+ out
+}
+
+/// Best-effort: is `content_root` (or an ancestor) a registered Obsidian
+/// vault? `extra_config_dir` optionally points at Obsidian's config dir for
+/// non-standard installs. Never errors — probe failures report
+/// `registered = false`.
+#[must_use]
+pub fn vault_registration_status(
+ content_root: &Path,
+ extra_config_dir: Option<&Path>,
+) -> VaultRegistration {
+ registration_in_files(content_root, &candidate_config_files(extra_config_dir))
+}
+
+/// Core of [`vault_registration_status`], split out so tests can supply an
+/// explicit, isolated set of `obsidian.json` paths instead of depending on
+/// whatever Obsidian config happens to exist on the host.
+fn registration_in_files(content_root: &Path, files: &[PathBuf]) -> VaultRegistration {
+ // Absolutize the content root against the current directory (lexically,
+ // without touching the filesystem) so a relative content root compares
+ // equal to the absolute vault paths Obsidian records in `obsidian.json`.
+ // Without this, a relative root can never be a prefix of an absolute vault
+ // path and an already-registered vault is always reported unregistered.
+ let target = std::path::absolute(content_root)
+ .map(|abs| lexically_normalize(&abs))
+ .unwrap_or_else(|_| lexically_normalize(content_root));
+ let mut config_found = false;
+
+ for path in files {
+ let body = match std::fs::read_to_string(path) {
+ Ok(b) => b,
+ Err(_) => continue, // missing/unreadable candidate — try the next.
+ };
+ config_found = true;
+
+ let parsed: ObsidianConfig = match serde_json::from_str(&body) {
+ Ok(p) => p,
+ Err(err) => {
+ // Redact the path — it embeds the user's home/username.
+ log::warn!(
+ "[memory][obsidian_registry] parse {} failed: {err} — skipping",
+ redact(&path.display().to_string())
+ );
+ continue;
+ }
+ };
+
+ for entry in parsed.vaults.values() {
+ let vault = lexically_normalize(Path::new(&entry.path));
+ // A malformed/empty vault path normalizes to "" and would otherwise
+ // match every content root (empty ancestor ⊂ anything) — skip it.
+ if vault.as_os_str().is_empty() {
+ continue;
+ }
+ if is_ancestor_or_equal(&vault, &target) {
+ log::debug!(
+ "[memory][obsidian_registry] content root is a registered vault \
+ (matched in {})",
+ redact(&path.display().to_string())
+ );
+ return VaultRegistration {
+ registered: true,
+ config_found: true,
+ };
+ }
+ }
+ }
+
+ log::debug!(
+ "[memory][obsidian_registry] content root NOT registered (config_found={config_found})"
+ );
+ VaultRegistration {
+ registered: false,
+ config_found,
+ }
+}
+
+/// Strip trailing separators so `/a/b` and `/a/b/` compare equal. Lexical
+/// only — we deliberately do not canonicalize: the vault path may be on an
+/// unmounted volume or use a symlink, and canonicalize would error or rewrite
+/// it. Both inputs come from trusted local sources, so a textual compare is
+/// the safe, dependency-free choice.
+fn lexically_normalize(p: &Path) -> PathBuf {
+ let s = p.to_string_lossy();
+ let trimmed = s.trim_end_matches(['/', '\\']);
+ if trimmed.is_empty() {
+ // Was a pure root like "/" — keep it.
+ PathBuf::from(s.as_ref())
+ } else {
+ PathBuf::from(trimmed)
+ }
+}
+
+/// `true` when `ancestor == descendant`, or `ancestor` is a path-prefix of
+/// `descendant` on component boundaries (so `/a/b` contains `/a/b/c` but not
+/// `/a/bc`). Case-sensitive — adequate for the Linux target; a false negative
+/// on case-insensitive volumes only makes detection conservative (the caller
+/// still offers "open anyway").
+fn is_ancestor_or_equal(ancestor: &Path, descendant: &Path) -> bool {
+ let a: Vec<_> = ancestor.components().collect();
+ let d: Vec<_> = descendant.components().collect();
+ // An empty ancestor must not match (it would otherwise be a prefix of
+ // everything); also bail when the ancestor is longer than the descendant.
+ if a.is_empty() || a.len() > d.len() {
+ return false;
+ }
+ a.iter().zip(d.iter()).all(|(x, y)| x == y)
+}
+
+#[cfg(test)]
+#[path = "obsidian_registry_tests.rs"]
+mod tests;
diff --git a/src/openhuman/memory/obsidian_registry_tests.rs b/src/openhuman/memory/obsidian_registry_tests.rs
new file mode 100644
index 0000000000..368adecedf
--- /dev/null
+++ b/src/openhuman/memory/obsidian_registry_tests.rs
@@ -0,0 +1,184 @@
+//! Ported alongside [`super`] from the engine's `obsidian_registry_tests.rs`,
+//! assertion for assertion, so the host copy is held to the same behaviour the
+//! engine copy was — including the two regressions the engine's suite pins
+//! (an empty vault path must not match every root, and a sibling directory
+//! sharing a name prefix is not a match).
+
+use super::*;
+use std::io::Write;
+
+/// Write an `obsidian.json` containing `vault_paths` and return its path.
+fn write_config(dir: &Path, vault_paths: &[&str]) -> PathBuf {
+ let entries: Vec<String> = vault_paths
+ .iter()
+ .enumerate()
+ .map(|(i, p)| {
+ format!(
+ "\"id{i}\": {{ \"path\": {}, \"ts\": 1700000000000, \"open\": true }}",
+ serde_json::to_string(p).unwrap()
+ )
+ })
+ .collect();
+ let body = format!("{{ \"vaults\": {{ {} }} }}", entries.join(", "));
+ let path = dir.join("obsidian.json");
+ let mut f = std::fs::File::create(&path).unwrap();
+ f.write_all(body.as_bytes()).unwrap();
+ path
+}
+
+#[test]
+fn exact_match_is_registered() {
+ let tmp = tempfile::tempdir().unwrap();
+ let root = tmp.path().join("memory_tree/content");
+ let cfg = write_config(tmp.path(), &[root.to_str().unwrap()]);
+ let got = registration_in_files(&root, &[cfg]);
+ assert_eq!(
+ got,
+ VaultRegistration {
+ registered: true,
+ config_found: true
+ }
+ );
+}
+
+#[test]
+fn ancestor_vault_is_registered() {
+ // A vault rooted at the parent still "contains" the content root.
+ let tmp = tempfile::tempdir().unwrap();
+ let parent = tmp.path().join("workspace");
+ let root = parent.join("memory_tree/content");
+ let cfg = write_config(tmp.path(), &[parent.to_str().unwrap()]);
+ assert!(registration_in_files(&root, &[cfg]).registered);
+}
+
+#[test]
+fn trailing_slash_does_not_matter() {
+ let tmp = tempfile::tempdir().unwrap();
+ let root = tmp.path().join("memory_tree/content");
+ let with_slash = format!("{}/", root.to_str().unwrap());
+ let cfg = write_config(tmp.path(), &[&with_slash]);
+ assert!(registration_in_files(&root, &[cfg]).registered);
+}
+
+#[test]
+fn relative_content_root_matches_absolute_vault() {
+ // A relative content root must be absolutized against the CWD before the
+ // prefix comparison, or an already-registered vault is always reported
+ // unregistered.
+ let tmp = tempfile::tempdir().unwrap();
+ let cwd = std::env::current_dir().unwrap();
+ let abs_root = cwd.join("memory_tree/content");
+ let cfg = write_config(tmp.path(), &[abs_root.to_str().unwrap()]);
+ let got = registration_in_files(Path::new("memory_tree/content"), &[cfg]);
+ assert!(
+ got.registered,
+ "relative content root must be absolutized against the CWD before matching"
+ );
+}
+
+#[test]
+fn unrelated_vault_is_not_registered_but_config_found() {
+ let tmp = tempfile::tempdir().unwrap();
+ let root = tmp.path().join("memory_tree/content");
+ let cfg = write_config(tmp.path(), &["/some/other/vault"]);
+ let got = registration_in_files(&root, &[cfg]);
+ assert_eq!(
+ got,
+ VaultRegistration {
+ registered: false,
+ config_found: true
+ }
+ );
+}
+
+#[test]
+fn empty_vault_path_does_not_match_every_root() {
+ // Regression: a malformed entry with an empty `path` must not
+ // normalize to "" and match every content root as an ancestor.
+ let tmp = tempfile::tempdir().unwrap();
+ let root = tmp.path().join("memory_tree/content");
+ let cfg = write_config(tmp.path(), &[""]);
+ let got = registration_in_files(&root, &[cfg]);
+ assert_eq!(
+ got,
+ VaultRegistration {
+ registered: false,
+ config_found: true
+ }
+ );
+}
+
+#[test]
+fn sibling_prefix_is_not_a_false_match() {
+ // `/a/b/content` must NOT match a vault at `/a/b/content-archive`.
+ let tmp = tempfile::tempdir().unwrap();
+ let root = tmp.path().join("content");
+ let decoy = format!("{}-archive", root.to_str().unwrap());
+ let cfg = write_config(tmp.path(), &[&decoy]);
+ assert!(!registration_in_files(&root, &[cfg]).registered);
+}
+
+#[test]
+fn missing_config_reports_not_found() {
+ let tmp = tempfile::tempdir().unwrap();
+ let root = tmp.path().join("memory_tree/content");
+ let missing = tmp.path().join("does-not-exist.json");
+ let got = registration_in_files(&root, &[missing]);
+ assert_eq!(
+ got,
+ VaultRegistration {
+ registered: false,
+ config_found: false
+ }
+ );
+}
+
+#[test]
+fn malformed_config_is_skipped_not_fatal() {
+ let tmp = tempfile::tempdir().unwrap();
+ let root = tmp.path().join("memory_tree/content");
+ let bad = tmp.path().join("obsidian.json");
+ std::fs::write(&bad, b"{ this is not json ").unwrap();
+ // config_found is true (we read it) but parse fails → not registered.
+ let got = registration_in_files(&root, &[bad]);
+ assert_eq!(
+ got,
+ VaultRegistration {
+ registered: false,
+ config_found: true
+ }
+ );
+}
+
+#[test]
+fn second_candidate_wins_when_first_missing() {
+ let tmp = tempfile::tempdir().unwrap();
+ let root = tmp.path().join("memory_tree/content");
+ let missing = tmp.path().join("nope.json");
+ let real = write_config(tmp.path(), &[root.to_str().unwrap()]);
+ assert!(registration_in_files(&root, &[missing, real]).registered);
+}
+
+/// The override arm is the host's own reason for keeping this code: a user
+/// with a non-standard Obsidian install points at their config dir and the
+/// probe has to look there *first*. Both spellings are accepted because users
+/// cannot tell whether the path should end in `obsidian/`.
+#[test]
+fn extra_config_dir_is_probed_before_the_standard_locations() {
+ let tmp = tempfile::tempdir().unwrap();
+ let files = candidate_config_files(Some(tmp.path()));
+ assert_eq!(files[0], tmp.path().join("obsidian.json"));
+ assert_eq!(files[1], tmp.path().join("obsidian").join("obsidian.json"));
+}
+
+/// No override means no override-derived candidates — the probe must not
+/// invent a relative `./obsidian.json`, which would make the answer depend on
+/// the process working directory.
+#[test]
+fn no_extra_config_dir_adds_no_relative_candidate() {
+ let files = candidate_config_files(None);
+ assert!(
+ files.iter().all(|p| p.is_absolute()),
+ "every candidate must be absolute; got {files:?}"
+ );
+}
diff --git a/src/openhuman/memory/read_rpc/admin.rs b/src/openhuman/memory/read_rpc/admin.rs
index fb8276a324..d0bf730427 100644
--- a/src/openhuman/memory/read_rpc/admin.rs
+++ b/src/openhuman/memory/read_rpc/admin.rs
@@ -1,12 +1,10 @@
use anyhow::{Context, Result};
-use rusqlite::params;
use crate::openhuman::config::Config;
+use crate::openhuman::memory::api::provider::ForgetSelector;
+use crate::openhuman::memory::sync::composio::providers::sync_state::KV_NAMESPACE;
use crate::rpc::RpcOutcome;
use tinymemory_api::chunks::SourceKind;
-use tinymemory_core::store::chunks::store::{
- delete_chunks_by_source, delete_orphaned_source_tree, with_connection,
-};
use super::types::{
DeleteSourceResponse, FlushNowResponse, FlushSourceTreeResponse, ResetTreeResponse,
@@ -15,52 +13,56 @@ use super::types::{
// ── wipe_all ─────────────────────────────────────────────────────────────
+/// Erase the whole memory store, then remove the content directories this host
+/// wrote beside it.
+///
+/// Two halves that read like one operation and deliberately are not.
+///
+/// The **store** wipe is the driver's: it owns which tables exist and what a
+/// row is. It comes back as `PurgeOutcome::rows_deleted`, a sum across every
+/// table the driver emptied — which is exactly what this response's
+/// `rows_deleted` has always reported (the handler used to sum it here, over
+/// nine hand-written `DELETE`s). So the number maps straight across and is
+/// deliberately neither re-derived nor re-scaled.
+///
+/// The **content directories** are this host's: it created them, its config
+/// decides where they live, and `purge_all`'s own contract says a driver must
+/// not reach into a host-owned path. `dirs_removed` therefore stays here,
+/// unchanged, and stays outside the driver call.
pub async fn wipe_all_rpc(config: &Config) -> Result<RpcOutcome<WipeAllResponse>, String> {
- let cfg = config.clone();
- let (rows_deleted, sync_state_cleared) =
- tokio::task::spawn_blocking(move || -> Result<(u64, u64)> {
- const TABLES: &[&str] = &[
- "mem_tree_score",
- "mem_tree_entity_index",
- "mem_tree_entity_hotness",
- "mem_tree_jobs",
- "mem_tree_buffers",
- "mem_tree_summaries",
- "mem_tree_trees",
- "mem_tree_chunks",
- "mem_tree_ingested_sources",
- ];
- let rows_deleted: u64 = with_connection(&cfg, |conn| {
- let tx = conn.unchecked_transaction()?;
- let mut total: u64 = 0;
- for table in TABLES {
- let n = tx
- .execute(&format!("DELETE FROM {table}"), [])
- .with_context(|| format!("delete from {table}"))?;
- total += n as u64;
- }
- tx.commit()?;
- Ok(total)
- })?;
-
- let sync_state_cleared: u64 = {
- let unified_db = cfg.workspace_dir.join("memory").join("memory.db");
- if !unified_db.exists() {
- log::debug!(
- "[memory_tree::read::wipe] unified memory DB not present — skipping sync-state clear"
- );
- 0
- } else {
- clear_composio_sync_state(&unified_db)
- .context("clear composio-sync-state during wipe_all")?
- }
- };
-
- Ok((rows_deleted, sync_state_cleared))
- })
+ // No `spawn_blocking` around either driver call — the driver owns whether
+ // its own reads block, and the module's do not run on this thread at all
+ // (the same reasoning `flush_now_rpc` below already carries). The directory
+ // removal further down was always async `tokio::fs` and never sat inside
+ // the wrapper the table deletes did, so the wrapper leaves with them.
+ let binding = crate::openhuman::memory::binding::for_config(config)?;
+ let Some(maintenance) = binding.provider().as_maintenance() else {
+ // Refused, not reported as a wipe that deleted nothing. The caller's
+ // next act is telling a user their memory is gone; that is the same
+ // reason the contract defaults `purge_all` to `Unsupported` rather than
+ // to a zero outcome.
+ return Err(format!(
+ "wipe_all: driver '{}' does not serve Maintenance",
+ binding.driver_id()
+ ));
+ };
+ log::debug!(
+ "[memory_tree::read::wipe] purge_all driver={}",
+ binding.driver_id()
+ );
+ let rows_deleted = maintenance
+ .purge_all()
.await
- .map_err(|e| format!("wipe_all join error: {e}"))?
- .map_err(|e| format!("wipe_all: {e:#}"))?;
+ .map_err(|e| format!("wipe_all: {e}"))?
+ .rows_deleted;
+ log::debug!("[memory_tree::read::wipe] purge_all rows_deleted={rows_deleted}");
+
+ // Ordered after the purge exactly as it was when both halves ran inside one
+ // `spawn_blocking`: sync cursors are only safe to drop once the content they
+ // point at has gone.
+ let sync_state_cleared = clear_composio_sync_state(config)
+ .await
+ .map_err(|e| format!("wipe_all: {e}"))?;
const DIRS: &[&str] = &["raw", "wiki", "chat", "document", "email", "summaries"];
let content_root = config.memory_tree_content_root();
@@ -110,17 +112,83 @@ pub async fn wipe_all_rpc(config: &Config) -> Result<RpcOutcome<WipeAllResponse>
Ok(RpcOutcome::single_log(resp, log))
}
-pub(crate) fn clear_composio_sync_state(db_path: &std::path::Path) -> Result<u64> {
- use tinymemory_core::tinycortex::HOST_SYNC_STATE_NAMESPACE;
- let conn = rusqlite::Connection::open(db_path)
- .with_context(|| format!("open unified memory db {}", db_path.display()))?;
- let n = conn
- .execute(
- "DELETE FROM kv_namespace WHERE namespace = ?1",
- params![HOST_SYNC_STATE_NAMESPACE],
- )
- .context("delete composio-sync-state rows")?;
- Ok(n as u64)
+/// Clear the composio sync-state namespace from the bound driver's key/value
+/// tier, reporting how many records went.
+///
+/// # What this replaced
+///
+/// A `rusqlite::Connection` opened directly on a path rebuilt from
+/// `workspace_dir` — a second, unpoliced door into the store alongside
+/// `with_connection`, and one that hard-coded both the file layout and the
+/// `kv_namespace` table name. Both are the driver's business; the namespace is
+/// read with `MemoryGraph::kv_list` and each record removed with
+/// `MemoryGraph::kv_delete`.
+///
+/// # What replaced the "database file is missing" skip
+///
+/// The old code checked `path.exists()` first and returned `0` when it did not,
+/// because opening a `Connection` on a missing file would have *created* an
+/// empty database as a side effect of asking. Over the contract there is no
+/// file to ask about — the driver owns its storage and when it comes into
+/// being — so the equivalent question is asked of the driver instead, and it
+/// has two answers that both land on the same `0`:
+///
+/// - a driver serving no `Graph` family has no key/value tier to clear, which
+/// is reported here rather than refused (nothing was stored through this
+/// host's kv path either, so "nothing removed" is true of it); and
+/// - a driver whose namespace is empty lists nothing and deletes nothing.
+///
+/// # Not atomic, unlike the single `DELETE` it replaces
+///
+/// The contract addresses key/value records one at a time, so this is a list
+/// followed by N deletes rather than one statement, and a record written into
+/// the namespace between the two survives. That is acceptable here and only
+/// here: the sole caller is a whole-store wipe, which has already stopped
+/// meaning anything if a sync is still writing into the store it is erasing.
+pub(crate) async fn clear_composio_sync_state(config: &Config) -> Result<u64, String> {
+ let binding = crate::openhuman::memory::binding::for_config(config)?;
+ let Some(graph) = binding.provider().as_graph() else {
+ log::debug!(
+ "[memory_tree::read::wipe] clear_composio_sync_state: driver '{}' \
+ does not serve Graph; nothing to clear",
+ binding.driver_id()
+ );
+ return Ok(0);
+ };
+
+ // `usize::MAX` because the whole namespace is the target — the same
+ // unbounded listing `memory::ops::kv_graph::kv_list_namespace` already
+ // does. There is no prefix: the namespace *is* the filter, matching the
+ // `WHERE namespace = ?1` the single `DELETE` used.
+ let records = graph
+ .kv_list(Some(KV_NAMESPACE), None, usize::MAX)
+ .await
+ .map_err(|e| format!("clear_composio_sync_state: kv_list: {e}"))?;
+ log::debug!(
+ "[memory_tree::read::wipe] clear_composio_sync_state namespace={} listed={}",
+ KV_NAMESPACE,
+ records.len()
+ );
+
+ let mut removed: u64 = 0;
+ for record in &records {
+ // Counted from the driver's answer rather than from the listing, so the
+ // number stays "records actually removed" — exactly what the single
+ // `DELETE`'s changed-row count fed into `sync_state_cleared`.
+ if graph
+ .kv_delete(Some(KV_NAMESPACE), &record.key)
+ .await
+ .map_err(|e| format!("clear_composio_sync_state: kv_delete: {e}"))?
+ {
+ removed += 1;
+ }
+ }
+ log::debug!(
+ "[memory_tree::read::wipe] clear_composio_sync_state namespace={} removed={}",
+ KV_NAMESPACE,
+ removed
+ );
+ Ok(removed)
}
// ── reset_tree ───────────────────────────────────────────────────────────
@@ -314,33 +382,35 @@ pub async fn flush_now_rpc(config: &Config) -> Result<RpcOutcome<FlushNowRespons
/// Fully delete one document source by its **exact** `source_id`.
///
-/// Unlike [`super::entities::delete_chunk_rpc`] (which removes a single chunk and
-/// leaves the source tree intact), this wraps
-/// [`delete_chunks_by_source`] so the whole logical source is purged: every
-/// chunk plus its score / entity-index / embedding / reembed-skip side rows and
-/// chunk content files, the ingest dedup gate, and — when the source becomes
-/// fully orphaned — its source summary tree via `delete_tree_cascade_tx`
-/// (summaries, summary embeddings + reembed-skip, tree-keyed entity-index,
-/// buffers, the tree row, and summary content files). This prevents stale
-/// summaries of a deleted note/event/meeting from resurfacing in semantic
-/// recall.
+/// Unlike [`super::entities::delete_chunk_rpc`] (which removes a single chunk
+/// and leaves the source tree intact), this asks the bound driver to forget
+/// everything filed under one `(source_kind, source_id)` pair, so the whole
+/// logical source is purged: every chunk plus its score / entity-index /
+/// embedding / reembed-skip side rows and chunk content files, the ingest
+/// dedup gate, and — when the source becomes fully orphaned — its source
+/// summary tree (summaries, summary embeddings + reembed-skip, tree-keyed
+/// entity-index, buffers, the tree row, and summary content files). This
+/// prevents stale summaries of a deleted note/event/meeting from resurfacing
+/// in semantic recall.
///
-/// Matching is **exact** (never a prefix), so sibling sources sharing a prefix
-/// are untouched. Idempotent: an unknown `source_id` removes nothing and returns
-/// `deleted = false`.
+/// Matching is **exact** (never a prefix) — that is what distinguishes
+/// [`ForgetSelector::Source`] from [`ForgetSelector::SourcePrefix`] — so
+/// sibling sources sharing a prefix are untouched. Idempotent: an unknown
+/// `source_id` removes nothing and returns `deleted = false`.
///
-/// Legacy cleanup: a source whose chunks were already removed earlier by the
-/// per-chunk path keeps a now-stale summary tree (which `delete_chunks_by_source`
-/// won't touch, since it only cascades trees for chunks it deletes in the same
-/// call). After the chunk delete we therefore also run
-/// [`delete_orphaned_source_tree`], which cascades the source-scoped tree and
-/// clears the bare + versioned (`{source_id}@{version_ms}`) ingest gates iff zero
-/// chunks remain — so calling delete_source over such a source finishes the job.
+/// Legacy cleanup is part of the same selector rather than a second host call.
+/// A source whose chunks were already removed earlier by the per-chunk path
+/// keeps a now-stale summary tree, which a chunk delete will not touch because
+/// it only cascades trees for chunks it deletes in the same call. The driver's
+/// exact-source arm sweeps that orphaned tree afterwards and reports it
+/// separately as `ForgetOutcome::trees_cleaned`, which is why the two counts
+/// are kept apart: a call that removes no chunk can still have done real work.
///
-/// Scope: this deletes the exact document source and its **source-scoped** orphan
-/// tree. It intentionally does NOT tear down shared collection / `path_scope`
-/// trees (e.g. Notion `notion:{connection}`), which may summarise many documents;
-/// per-document pruning inside a shared collection summary is out of scope here.
+/// Scope: this deletes the exact document source and its **source-scoped**
+/// orphan tree. It intentionally does NOT tear down shared collection /
+/// `path_scope` trees (e.g. Notion `notion:{connection}`), which may summarise
+/// many documents; per-document pruning inside a shared collection summary is
+/// out of scope here.
pub async fn delete_source_rpc(
config: &Config,
source_id: String,
@@ -349,37 +419,50 @@ pub async fn delete_source_rpc(
if source_id.is_empty() {
return Err("delete_source: source_id must be a non-empty string".to_string());
}
- let cfg = config.clone();
- let id = source_id.clone();
- let (chunks_removed, tree_cleaned) =
- tokio::task::spawn_blocking(move || -> Result<(usize, bool)> {
- // Exact-match document delete; cascade logic lives in the store.
- let removed = delete_chunks_by_source(&cfg, SourceKind::Document, &id)
- .context("delete_chunks_by_source during delete_source")?;
- // Finish off any legacy partial delete: cascade a now-orphaned tree
- // (no-op when chunks were just deleted — the tree is already gone —
- // or when there is no stale tree).
- let tree_cleaned = delete_orphaned_source_tree(&cfg, SourceKind::Document, &id)
- .context("delete_orphaned_source_tree during delete_source")?;
- Ok((removed, tree_cleaned))
+
+ // No `spawn_blocking`: the driver owns whether its own deletes block, and
+ // the module's do not run on this thread at all.
+ let binding = crate::openhuman::memory::binding::for_config(config)?;
+ let Some(sources) = binding.provider().as_sources() else {
+ // Refused rather than answered `deleted: false`. On a delete, a caller
+ // that reads "nothing matched" concludes the content was already gone;
+ // that is the same reason the contract refuses an unrecognised
+ // `source_kind` instead of returning an outcome of zero.
+ return Err(format!(
+ "delete_source: driver '{}' does not serve Sources",
+ binding.driver_id()
+ ));
+ };
+ let outcome = sources
+ .forget_matching(&ForgetSelector::Source {
+ // A wire string, not the enum: the set of source kinds belongs to
+ // this host's sync machinery and grows without a contract change.
+ source_kind: SourceKind::Document.as_str().to_string(),
+ source_id: source_id.clone(),
})
.await
- .map_err(|e| format!("delete_source join error: {e}"))?
- .map_err(|e| format!("delete_source: {e:#}"))?;
+ .map_err(|e| format!("delete_source: {e}"))?;
let resp = DeleteSourceResponse {
- // `deleted` is true if we removed chunks OR cleaned a stale orphaned tree
- // (the legacy-cleanup case has chunks_removed == 0 but still did work).
- deleted: chunks_removed > 0 || tree_cleaned,
- chunks_removed: chunks_removed as u64,
+ // `deleted` is true if we removed chunks OR cleaned a stale orphaned
+ // tree (the legacy-cleanup case has chunks_removed == 0 but still did
+ // work). `trees_cleaned` is a count where this used to read a `bool`,
+ // because a prefix or owner selector can strand several trees; for the
+ // exact-source arm here it is still only ever 0 or 1.
+ deleted: outcome.chunks_removed > 0 || outcome.trees_cleaned > 0,
+ chunks_removed: outcome.chunks_removed,
};
let log = format!(
// Redact the source id: it can embed user-linked identifiers.
- "memory_tree::read: delete_source source_id_hash={} deleted={} chunks_removed={} tree_cleaned={}",
+ "memory_tree::read: delete_source source_id_hash={} deleted={} chunks_removed={} trees_cleaned={}",
crate::openhuman::util::redact::redact(&source_id),
resp.deleted,
resp.chunks_removed,
- tree_cleaned
+ outcome.trees_cleaned
);
Ok(RpcOutcome::single_log(resp, log))
}
+
+#[cfg(test)]
+#[path = "admin_tests.rs"]
+mod tests;
diff --git a/src/openhuman/memory/read_rpc/admin_tests.rs b/src/openhuman/memory/read_rpc/admin_tests.rs
new file mode 100644
index 0000000000..f61b718ec3
--- /dev/null
+++ b/src/openhuman/memory/read_rpc/admin_tests.rs
@@ -0,0 +1,158 @@
+//! Sibling tests for the admin read-RPCs, covering what moved onto the memory
+//! contract in #5560.
+//!
+//! The three handlers here are the destructive ones, so what is worth pinning
+//! host-side is not that a delete deleted — that is the driver's, and the
+//! conformance suite proves it against a real store — but **how this host
+//! answers when the bound driver cannot serve the family at all**. On a read,
+//! a missing family degrades to an honest empty answer; on a wipe or a delete
+//! it must not, because a caller reading "nothing was removed" concludes the
+//! content was already gone. Each refusal below is that distinction.
+
+use super::{clear_composio_sync_state, delete_source_rpc, wipe_all_rpc};
+use crate::openhuman::config::Config;
+use crate::openhuman::memory::api::provider::MemoryProvider;
+use crate::openhuman::memory::binding;
+use std::sync::Arc;
+use tempfile::TempDir;
+use tinymemory_api::null::NullMemoryProvider;
+
+fn test_config() -> (TempDir, Config) {
+ let tmp = TempDir::new().unwrap();
+ let mut cfg = Config::default();
+ cfg.workspace_dir = tmp.path().to_path_buf();
+ // Keep any persistence these handlers trigger inside the disposable
+ // workspace, exactly as `read_rpc_tests::test_config` does.
+ cfg.config_path = tmp.path().join("config.toml");
+ cfg.memory_tree.embedding_endpoint = None;
+ cfg.memory_tree.embedding_model = None;
+ cfg.memory_tree.embedding_strict = false;
+ (tmp, cfg)
+}
+
+/// Bind the placeholder driver, which advertises the mandatory three families
+/// and returns `None` from every optional `as_*` accessor. That absence is the
+/// whole point of the driver, and it is what these tests are about.
+fn install_null_driver(cfg: &Config) {
+ binding::install_for_test(
+ &cfg.workspace_dir,
+ &cfg.subsystems.memory,
+ Arc::new(NullMemoryProvider::new()) as Arc<dyn MemoryProvider>,
+ );
+}
+
+/// A wipe a driver cannot perform is an error, never a `rows_deleted: 0`
+/// success — the caller's next act is telling a user their memory is gone.
+/// This mirrors the contract's own choice to default `purge_all` to
+/// `Unsupported` while the rest of its family defaults to an empty result.
+#[tokio::test]
+async fn wipe_all_refuses_a_driver_that_does_not_serve_maintenance() {
+ let (_tmp, cfg) = test_config();
+ install_null_driver(&cfg);
+
+ let err = wipe_all_rpc(&cfg)
+ .await
+ .expect_err("a driver with no Maintenance family cannot report a completed wipe");
+ assert!(
+ err.contains("does not serve Maintenance"),
+ "the refusal must name the missing family: {err}"
+ );
+ assert!(
+ err.contains("null"),
+ "the refusal must name the driver that refused: {err}"
+ );
+}
+
+/// The opposite call in the same handler, and deliberately not a refusal.
+///
+/// This replaced a `path.exists()` check that skipped silently, and the number
+/// it returned then is the number it returns now: a driver with no key/value
+/// tier has nothing of this host's to clear, so zero is a true statement about
+/// it rather than a fault a caller can act on.
+#[tokio::test]
+async fn clear_composio_sync_state_reports_zero_without_a_graph_family() {
+ let (_tmp, cfg) = test_config();
+ install_null_driver(&cfg);
+
+ assert_eq!(
+ clear_composio_sync_state(&cfg)
+ .await
+ .expect("a driver with no Graph family is not an error"),
+ 0
+ );
+}
+
+/// Same reasoning as the wipe: on a delete, a zero the caller reads as
+/// "already gone" is worse than a refusal.
+#[tokio::test]
+async fn delete_source_refuses_a_driver_that_does_not_serve_sources() {
+ let (_tmp, cfg) = test_config();
+ install_null_driver(&cfg);
+
+ let err = delete_source_rpc(&cfg, "notion:page-a".to_string())
+ .await
+ .expect_err("a driver with no Sources family cannot report a completed delete");
+ assert!(
+ err.contains("does not serve Sources"),
+ "the refusal must name the missing family: {err}"
+ );
+}
+
+/// Argument validation stays ahead of the driver lookup, so a blank id is a
+/// caller error naming itself rather than a round trip that deletes nothing.
+/// No driver is installed here on purpose — reaching one would be the failure.
+#[tokio::test]
+async fn delete_source_rejects_a_blank_source_id_before_touching_a_driver() {
+ let (_tmp, cfg) = test_config();
+
+ let err = delete_source_rpc(&cfg, " ".to_string())
+ .await
+ .expect_err("a blank source id is a caller error");
+ assert!(
+ err.contains("must be a non-empty string"),
+ "unexpected error: {err}"
+ );
+}
+
+/// An unknown source removes nothing and cleans no tree, and the host maps that
+/// all-zero `ForgetOutcome` onto `deleted: false`.
+///
+/// The mapping is the whole point of the assertion: `deleted` is now an OR over
+/// **two** counts, and a source that matched nothing must not read as one whose
+/// stranded summary tree was swept.
+#[tokio::test]
+async fn delete_source_is_idempotent_for_an_unknown_source_id() {
+ let (_tmp, cfg) = test_config();
+ crate::openhuman::memory::test_support::install_tinycortex_for_test(&cfg);
+
+ let outcome = delete_source_rpc(&cfg, "notion:never-ingested".to_string())
+ .await
+ .expect("an unknown source is not an error")
+ .value;
+ assert!(!outcome.deleted);
+ assert_eq!(outcome.chunks_removed, 0);
+}
+
+/// The source id can embed user-linked identifiers, so it is hashed into the
+/// log line rather than written out. Pinned here because the log is assembled
+/// beside the response and is easy to "improve" into a leak.
+#[tokio::test]
+async fn delete_source_never_logs_the_raw_source_id() {
+ let (_tmp, cfg) = test_config();
+ crate::openhuman::memory::test_support::install_tinycortex_for_test(&cfg);
+
+ let source_id = "notion:[email protected]/private-page";
+ let outcome = delete_source_rpc(&cfg, source_id.to_string())
+ .await
+ .expect("an unknown source is not an error");
+ assert!(
+ !outcome.logs[0].contains(source_id),
+ "log leaked the source id: {}",
+ outcome.logs[0]
+ );
+ assert!(
+ outcome.logs[0].contains("source_id_hash="),
+ "log should carry the redacted id: {}",
+ outcome.logs[0]
+ );
+}
diff --git a/src/openhuman/memory/read_rpc/chunks.rs b/src/openhuman/memory/read_rpc/chunks.rs
index 366838170b..cc28585a06 100644
--- a/src/openhuman/memory/read_rpc/chunks.rs
+++ b/src/openhuman/memory/read_rpc/chunks.rs
@@ -1,9 +1,11 @@
-use anyhow::{Context, Result};
+use anyhow::Result;
+use std::collections::{HashMap, HashSet};
use crate::openhuman::config::Config;
+use crate::openhuman::memory::api::provider::{ChunkListRow, ChunkQuery};
use crate::openhuman::memory::tree::retrieval::types::NodeKind;
use crate::rpc::RpcOutcome;
-use tinymemory_core::store::chunks::store::with_connection;
+use tinymemory_api::chunks::SourceKind;
use super::types::{
ChunkFilter, ChunkRow, ListChunksResponse, RecallResponse, Source, DEFAULT_LIST_LIMIT,
@@ -16,13 +18,7 @@ pub async fn list_chunks_rpc(
config: &Config,
filter: ChunkFilter,
) -> Result<RpcOutcome<ListChunksResponse>, String> {
- let cfg = config.clone();
- let resp = tokio::task::spawn_blocking(move || -> Result<ListChunksResponse> {
- list_chunks_blocking(&cfg, &filter)
- })
- .await
- .map_err(|e| format!("list_chunks join error: {e}"))?
- .map_err(|e| format!("list_chunks: {e:#}"))?;
+ let resp = list_chunks_page(config, &filter).await?;
let n = resp.chunks.len();
let total = resp.total;
@@ -32,170 +28,208 @@ pub async fn list_chunks_rpc(
))
}
-/// The list query stays in SQL because `MemoryChunks::list_chunks` cannot
-/// express it.
+/// One page of chunks plus the unpaged total that labels it, both read through
+/// the bound driver's `Chunks` family.
///
-/// Three of this filter's inputs have no `ChunkQuery` counterpart: the
-/// `mem_tree_entity_index` join behind `entity_ids`, the *sets* behind
-/// `source_kinds` / `source_ids` (the contract narrows to one of each), and the
-/// `content LIKE` scan behind `query`. The response also carries `total`, a
-/// count over the unpaged result — no member answers it, and deriving it
-/// host-side would mean a second, unbounded list on every page.
-pub(super) fn list_chunks_blocking(
+/// This was raw SQL, and its doc comment used to enumerate three filters the
+/// contract could not express: the `mem_tree_entity_index` join behind
+/// `entity_ids`, the *sets* behind `source_kinds` / `source_ids` (the old
+/// `ChunkQuery` narrowed to one of each), and the `content LIKE` scan behind
+/// `query`. All three are `ChunkQuery` fields now, and `count_chunks` answers
+/// the total that comment said no member could.
+///
+/// **The page and the total are built from the same [`ChunkQuery`] value, and
+/// that is the point.** `count_chunks` differs from `list_chunk_details` only
+/// in dropping the page bounds — the `WHERE` clause is one builder, driver-side
+/// — so a total can no longer disagree with the page it labels. The SQL this
+/// replaces derived its count statement by string-replacing the select list out
+/// of the listing statement, which is the same guarantee held together by
+/// whichever edit touched the string last.
+async fn list_chunks_page(
config: &Config,
filter: &ChunkFilter,
-) -> Result<ListChunksResponse> {
+) -> Result<ListChunksResponse, String> {
let limit = filter
.limit
.unwrap_or(DEFAULT_LIST_LIMIT)
.clamp(1, MAX_LIST_LIMIT);
let offset = filter.offset.unwrap_or(0);
- with_connection(config, |conn| {
- let mut sql = String::from(
- "SELECT DISTINCT
- c.id, c.source_kind, c.source_id, c.source_ref, c.owner,
- c.timestamp_ms, c.token_count, c.lifecycle_status,
- c.content_path, c.content, c.tags_json,
- CASE WHEN c.embedding IS NULL THEN 0 ELSE 1 END AS has_embedding
- FROM mem_tree_chunks c",
+ let Some(query) = chunk_query_from_filter(filter, limit, offset) else {
+ // Not an empty query — a query that cannot match. See
+ // [`chunk_query_from_filter`]: sending it would ask for the whole
+ // store.
+ log::debug!("[memory_tree::read] list_chunks: filter matches nothing; query skipped");
+ return Ok(ListChunksResponse {
+ chunks: Vec::new(),
+ total: 0,
+ });
+ };
+
+ // No `spawn_blocking`: the driver owns whether its own reads block, and the
+ // module's do not run on this thread at all.
+ let binding = crate::openhuman::memory::binding::for_config(config)?;
+ let Some(chunks) = binding.provider().as_chunks() else {
+ // Read-only, so an empty page is the honest answer: a driver with no
+ // chunk tier holds no rows to list, and no rows to count either.
+ log::debug!(
+ "[memory_tree::read] list_chunks: driver '{}' does not serve Chunks; reporting empty",
+ binding.driver_id()
);
- let mut where_clauses: Vec<String> = vec![];
- let mut params_owned: Vec<Box<dyn rusqlite::ToSql>> = Vec::new();
-
- if let Some(eids) = &filter.entity_ids {
- if !eids.is_empty() {
- sql.push_str(" INNER JOIN mem_tree_entity_index ei ON ei.node_id = c.id");
- let placeholders: Vec<String> = (0..eids.len()).map(|_| "?".to_string()).collect();
- where_clauses.push(format!("ei.entity_id IN ({})", placeholders.join(", ")));
- for eid in eids {
- params_owned.push(Box::new(eid.clone()));
- }
- }
- }
- if let Some(kinds) = &filter.source_kinds {
- if !kinds.is_empty() {
- let placeholders: Vec<String> = (0..kinds.len()).map(|_| "?".to_string()).collect();
- where_clauses.push(format!("c.source_kind IN ({})", placeholders.join(", ")));
- for k in kinds {
- params_owned.push(Box::new(k.clone()));
- }
- }
- }
- if let Some(sids) = &filter.source_ids {
- if !sids.is_empty() {
- let placeholders: Vec<String> = (0..sids.len()).map(|_| "?".to_string()).collect();
- where_clauses.push(format!("c.source_id IN ({})", placeholders.join(", ")));
- for s in sids {
- params_owned.push(Box::new(s.clone()));
- }
- }
- }
- if let Some(since) = filter.since_ms {
- where_clauses.push("c.timestamp_ms >= ?".into());
- params_owned.push(Box::new(since));
- }
- if let Some(until) = filter.until_ms {
- where_clauses.push("c.timestamp_ms <= ?".into());
- params_owned.push(Box::new(until));
- }
- if let Some(query) = &filter.query {
- let q = query.trim();
- if !q.is_empty() {
- where_clauses.push("c.content LIKE ?".into());
- params_owned.push(Box::new(format!("%{}%", q)));
+ return Ok(ListChunksResponse {
+ chunks: Vec::new(),
+ total: 0,
+ });
+ };
+
+ // `scope` is `None` here because this listing has never been source-scoped:
+ // the SQL it replaces had no allowlist clause at all. Passing the ambient
+ // scope would be a new restriction on the Memory tab, not a translation of
+ // one.
+ let rows = chunks
+ .list_chunk_details(&query, None)
+ .await
+ .map_err(|e| format!("list_chunk_details: {e}"))?;
+ let total = chunks
+ .count_chunks(&query, None)
+ .await
+ .map_err(|e| format!("count_chunks: {e}"))?;
+
+ log::debug!(
+ "[memory_tree::read] list_chunks: limit={limit} offset={offset} rows={} total={total}",
+ rows.len()
+ );
+
+ Ok(ListChunksResponse {
+ chunks: rows.into_iter().map(chunk_row_from_list_row).collect(),
+ total,
+ })
+}
+
+/// Translate the RPC's [`ChunkFilter`] into the contract's [`ChunkQuery`].
+///
+/// `None` means **this filter can match nothing, so skip the query entirely**.
+/// That is not the same as an unconstrained query, and the difference is the
+/// one footgun `ChunkQuery` carries: every `Vec` predicate defaults to empty
+/// and an empty predicate is *unfiltered*, so handing over the empty result of
+/// a narrowing computation asks for the whole store rather than for nothing.
+///
+/// Exactly one field here narrows: `source_kinds` arrives as free text and the
+/// contract carries a decoded enum, so kinds this build does not know drop out.
+/// Dropping them reproduces the old SQL, where an unrecognised value sat in
+/// `source_kind IN (…)` and simply matched no row — `["chat", "bogus"]` still
+/// returns the chat rows. When *every* value is unrecognised the old clause
+/// matched nothing, and `None` is how that answer is spelled here; leaving the
+/// vec empty instead would return the whole store.
+///
+/// An empty `Some(vec![])` is *not* that case: the old SQL skipped the clause
+/// for an empty list, so it is unfiltered here too, which is what the empty vec
+/// already means.
+fn chunk_query_from_filter(filter: &ChunkFilter, limit: u32, offset: u32) -> Option<ChunkQuery> {
+ let mut source_kinds: Vec<SourceKind> = Vec::new();
+ if let Some(requested) = filter.source_kinds.as_ref() {
+ for raw in requested {
+ match SourceKind::parse(raw) {
+ Ok(kind) => source_kinds.push(kind),
+ Err(e) => log::debug!(
+ "[memory_tree::read] list_chunks: dropping unknown source_kind {raw:?} ({e})"
+ ),
}
}
-
- if !where_clauses.is_empty() {
- sql.push_str(" WHERE ");
- sql.push_str(&where_clauses.join(" AND "));
+ if source_kinds.is_empty() && !requested.is_empty() {
+ return None;
}
- let count_sql = format!(
- "SELECT COUNT(*) FROM ({}) AS sub",
- sql.replacen(
- "SELECT DISTINCT\n c.id, c.source_kind, c.source_id, c.source_ref, c.owner,\n c.timestamp_ms, c.token_count, c.lifecycle_status,\n c.content_path, c.content, c.tags_json,\n CASE WHEN c.embedding IS NULL THEN 0 ELSE 1 END AS has_embedding",
- "SELECT DISTINCT c.id",
- 1
- )
- );
+ }
- sql.push_str(" ORDER BY c.timestamp_ms DESC, c.seq_in_source ASC LIMIT ? OFFSET ?");
- params_owned.push(Box::new(limit as i64));
- params_owned.push(Box::new(offset as i64));
+ let content_contains = filter.query.as_deref().and_then(content_predicate);
- let count_params: Vec<&dyn rusqlite::ToSql> = params_owned
- .iter()
- .take(params_owned.len() - 2)
- .map(|b| b.as_ref() as &dyn rusqlite::ToSql)
- .collect();
- let total: i64 = conn
- .query_row(&count_sql, count_params.as_slice(), |r| r.get(0))
- .context("count chunks")?;
-
- let mut stmt = conn.prepare(&sql).context("prepare list_chunks")?;
- let param_refs: Vec<&dyn rusqlite::ToSql> = params_owned
- .iter()
- .map(|b| b.as_ref() as &dyn rusqlite::ToSql)
- .collect();
- let rows = stmt
- .query_map(param_refs.as_slice(), |row| {
- let id: String = row.get(0)?;
- let source_kind: String = row.get(1)?;
- let source_id: String = row.get(2)?;
- let source_ref: Option<String> = row.get(3)?;
- let owner: String = row.get(4)?;
- let timestamp_ms: i64 = row.get(5)?;
- let token_count: i64 = row.get(6)?;
- let lifecycle_status: String = row.get(7)?;
- let content_path: Option<String> = row.get(8)?;
- let content: String = row.get(9)?;
- let tags_json: String = row.get(10)?;
- let has_embedding: i64 = row.get(11)?;
- let preview: String = content.chars().take(PREVIEW_MAX_CHARS).collect();
- let tags: Vec<String> = serde_json::from_str(&tags_json).unwrap_or_default();
- Ok(ChunkRow {
- id,
- source_kind,
- source_id,
- source_ref,
- owner,
- timestamp_ms,
- token_count: token_count.max(0) as u32,
- lifecycle_status,
- content_path,
- content_preview: if preview.is_empty() {
- None
- } else {
- Some(preview)
- },
- has_embedding: has_embedding != 0,
- tags,
- })
- })?
- .collect::<rusqlite::Result<Vec<_>>>()
- .context("collect list_chunks rows")?;
-
- Ok(ListChunksResponse {
- chunks: rows,
- total: total.max(0) as u64,
- })
+ Some(ChunkQuery {
+ source_ids: filter.source_ids.clone().unwrap_or_default(),
+ entity_ids: filter.entity_ids.clone().unwrap_or_default(),
+ source_kinds,
+ since_ms: filter.since_ms,
+ until_ms: filter.until_ms,
+ content_contains,
+ limit: Some(limit as usize),
+ offset: Some(offset as usize),
+ // The predicates this filter does not carry. `exclude_dropped` stays
+ // false because the SQL had no lifecycle clause: the Memory tab lists
+ // dropped rows and renders their status.
+ ..Default::default()
})
}
+/// The `content_contains` predicate for a caller-supplied query string, or
+/// `None` when the caller typed only whitespace.
+///
+/// One function because two call sites need the same rule and a drifted pair
+/// would show as a search that filters differently from the listing behind it.
+///
+/// Two things it deliberately does not do. It does not wrap the value in
+/// `%…%` — that is the driver's, and so is escaping any `%` or `_` the user
+/// typed, which the `format!("%{}%", q)` this replaces did not do at all: a
+/// query containing `_` silently matched any character in that position. And a
+/// blank query places no predicate rather than matching nothing, which is what
+/// the old `if !q.is_empty()` guard did and is why a cleared search box lists
+/// the newest rows instead of emptying the table.
+fn content_predicate(query: &str) -> Option<String> {
+ let trimmed = query.trim();
+ if trimmed.is_empty() {
+ None
+ } else {
+ Some(trimmed.to_string())
+ }
+}
+
+/// Render one contract listing row as the wire [`ChunkRow`] the Memory tab
+/// reads.
+///
+/// [`ChunkListRow`] carries no body, deliberately — `ChunkDetail::body`
+/// promises `None` means the vault read *failed*, which a page of rows can only
+/// honour by reading every file or by lying. Nothing is lost here: the preview
+/// has always come from the stored `content` column, which is a ≤500-char
+/// preview for a chunk whose body went to the content vault and the whole body
+/// for an inline one, and that column is `Chunk::content`. The truncation below
+/// is therefore a no-op on already-previewed rows and identical to the SQL's on
+/// inline ones.
+fn chunk_row_from_list_row(row: ChunkListRow) -> ChunkRow {
+ let ChunkListRow {
+ chunk,
+ content_path,
+ lifecycle_status,
+ has_embedding,
+ } = row;
+ let preview: String = chunk.content.chars().take(PREVIEW_MAX_CHARS).collect();
+ ChunkRow {
+ id: chunk.id,
+ source_kind: chunk.metadata.source_kind.as_str().to_string(),
+ source_id: chunk.metadata.source_id,
+ source_ref: chunk.metadata.source_ref.map(|r| r.value),
+ owner: chunk.metadata.owner,
+ timestamp_ms: chunk.metadata.timestamp.timestamp_millis(),
+ token_count: chunk.token_count,
+ // Matches `read_chunk_row` below. The column is `NOT NULL DEFAULT
+ // 'admitted'`, so `None` is unreachable through the engine driver; a
+ // driver with no lifecycle concept at all is what the `Option` is for.
+ lifecycle_status: lifecycle_status.unwrap_or_else(|| "unknown".to_string()),
+ content_path,
+ content_preview: if preview.is_empty() {
+ None
+ } else {
+ Some(preview)
+ },
+ has_embedding,
+ tags: chunk.metadata.tags,
+ }
+}
+
// ── list_sources ─────────────────────────────────────────────────────────
pub async fn list_sources_rpc(
config: &Config,
user_email_hint: Option<String>,
) -> Result<RpcOutcome<Vec<Source>>, String> {
- let cfg = config.clone();
- let sources = tokio::task::spawn_blocking(move || -> Result<Vec<Source>> {
- list_sources_blocking(&cfg, user_email_hint.as_deref())
- })
- .await
- .map_err(|e| format!("list_sources join error: {e}"))?
- .map_err(|e| format!("list_sources: {e:#}"))?;
+ let sources = list_sources(config, user_email_hint.as_deref()).await?;
let n = sources.len();
Ok(RpcOutcome::single_log(
@@ -204,33 +238,60 @@ pub async fn list_sources_rpc(
))
}
-fn list_sources_blocking(config: &Config, user_email_hint: Option<&str>) -> Result<Vec<Source>> {
- with_connection(config, |conn| {
- let mut stmt = conn.prepare(
- "SELECT source_kind, source_id, COUNT(*) AS n, MAX(timestamp_ms) AS most_recent
- FROM mem_tree_chunks
- GROUP BY source_kind, source_id
- ORDER BY most_recent DESC",
- )?;
- let rows = stmt
- .query_map([], |row| {
- let source_kind: String = row.get(0)?;
- let source_id: String = row.get(1)?;
- let n: i64 = row.get(2)?;
- let most_recent: i64 = row.get(3)?;
- let display_name = display_name_for_source(&source_id, user_email_hint);
- Ok(Source {
- source_id,
- display_name,
- source_kind,
- chunk_count: n.max(0) as u32,
- most_recent_ms: most_recent,
- })
- })?
- .collect::<rusqlite::Result<Vec<_>>>()
- .context("collect list_sources rows")?;
- Ok(rows)
- })
+/// The `(source_kind, source_id)` rollup, read through the driver's
+/// `source_totals` rather than a host-side `GROUP BY`.
+///
+/// `display_name` stays here because it is presentation, not storage: turning
+/// know which address is the user's, which is host state. The contract's
+/// `SourceTotal` deliberately carries no such field.
+async fn list_sources(
+ config: &Config,
+ user_email_hint: Option<&str>,
+) -> Result<Vec<Source>, String> {
+ let binding = crate::openhuman::memory::binding::for_config(config)?;
+ let Some(chunks) = binding.provider().as_chunks() else {
+ log::debug!(
+ "[memory_tree::read] list_sources: driver '{}' does not serve Chunks; reporting empty",
+ binding.driver_id()
+ );
+ return Ok(Vec::new());
+ };
+
+ // No host-imposed cap. The `GROUP BY` this replaces had no `LIMIT`, so the
+ // only ceiling that ever applied was the store's own, and `usize::MAX` asks
+ // for exactly that one instead of inventing a smaller number here.
+ // `MAX_LIST_LIMIT` bounds a *page of chunks* and is the wrong unit: for a
+ // mailbox every thread is its own source, so a thousand groups is a number
+ // real workspaces pass. `scope` is `None` for the same reason the listing's
+ // is — this rollup has never been source-scoped.
+ let totals = chunks
+ .source_totals(usize::MAX, None)
+ .await
+ .map_err(|e| format!("source_totals: {e}"))?;
+
+ log::debug!(
+ "[memory_tree::read] list_sources: groups={} hint={}",
+ totals.len(),
+ user_email_hint.is_some()
+ );
+
+ Ok(totals
+ .into_iter()
+ .map(|total| {
+ let display_name = display_name_for_source(&total.source_id, user_email_hint);
+ Source {
+ source_id: total.source_id,
+ display_name,
+ source_kind: total.source_kind.as_str().to_string(),
+ // Saturating rather than wrapping. The wire field is `u32` and
+ // the count is `u64`; a store that ever reached the ceiling
+ // should render as "very many", not as a small number.
+ chunk_count: u32::try_from(total.chunk_count).unwrap_or(u32::MAX),
+ most_recent_ms: total.most_recent_ms,
+ }
+ })
+ .collect())
}
/// Compute the display name for a source.
@@ -265,29 +326,63 @@ pub fn display_name_for_source(source_id: &str, user_email_hint: Option<&str>) -
// ── search / recall ──────────────────────────────────────────────────────
+/// Substring browse over the chunk tier.
+///
+/// Straight to `list_chunk_details` with `content_contains` and a limit, and
+/// nothing else — the old path built a full [`ChunkFilter`], ran the listing,
+/// and threw the total away, which is a `COUNT(*)` over the whole match set per
+/// keystroke.
+///
+/// **What this actually scans is the text the driver holds inline**, which for
+/// a chunk whose body went to the content vault is the stored ≤500-char
+/// preview and not the whole document. That is not a narrowing: the SQL this
+/// replaces scanned `mem_tree_chunks.content`, the same column. It is worth
+/// stating because the RPC is named `search` — this narrows a browse, and
+/// "search my memory" is `MemoryRecall`, which [`recall_rpc`] below uses.
pub async fn search_rpc(
config: &Config,
query: String,
k: u32,
) -> Result<RpcOutcome<Vec<ChunkRow>>, String> {
let limit = k.clamp(1, MAX_LIST_LIMIT);
- let filter = ChunkFilter {
- query: Some(query.clone()),
- limit: Some(limit),
- ..ChunkFilter::default()
+ let content_contains = content_predicate(&query);
+ // Captured before `query` is shadowed by the `ChunkQuery` below. The log
+ // line reports the length of the search TEXT, never of the built query, and
+ // it is deliberately the length rather than the text itself — a search term
+ // is user-authored content and does not belong in a log.
+ let query_len = query.len();
+
+ let binding = crate::openhuman::memory::binding::for_config(config)?;
+ let Some(chunks) = binding.provider().as_chunks() else {
+ log::debug!(
+ "[memory_tree::read] search: driver '{}' does not serve Chunks; reporting empty",
+ binding.driver_id()
+ );
+ return Ok(RpcOutcome::single_log(
+ Vec::new(),
+ format!("memory_tree::read: search query_len={query_len} n=0"),
+ ));
};
- let cfg = config.clone();
- let chunks = tokio::task::spawn_blocking(move || -> Result<Vec<ChunkRow>> {
- Ok(list_chunks_blocking(&cfg, &filter)?.chunks)
- })
- .await
- .map_err(|e| format!("search join error: {e}"))?
- .map_err(|e| format!("search: {e:#}"))?;
- let n = chunks.len();
+ // `content_contains` and a limit, and nothing else: no source predicate, no
+ // time window, no offset. `scope` is `None` for the same reason the listing
+ // passes `None` — the SQL this replaces carried no allowlist clause.
+ let query = ChunkQuery {
+ content_contains,
+ limit: Some(limit as usize),
+ ..Default::default()
+ };
+ let rows = chunks
+ .list_chunk_details(&query, None)
+ .await
+ .map_err(|e| format!("list_chunk_details: {e}"))?;
+
+ let hits: Vec<ChunkRow> = rows.into_iter().map(chunk_row_from_list_row).collect();
+ let n = hits.len();
+ log::debug!("[memory_tree::read] search: limit={limit} n={n}");
Ok(RpcOutcome::single_log(
- chunks,
- format!("memory_tree::read: search query_len={} n={n}", query.len()),
+ hits,
+ format!("memory_tree::read: search query_len={query_len} n={n}"),
))
}
@@ -296,8 +391,6 @@ pub async fn recall_rpc(
query: String,
k: u32,
) -> Result<RpcOutcome<RecallResponse>, String> {
- use rusqlite::params;
-
let limit = k.clamp(1, MAX_LIST_LIMIT) as usize;
log::debug!(
"[memory_tree::read::recall] query_len={} k={}",
@@ -328,7 +421,6 @@ pub async fn recall_rpc(
let mut chunk_rows: Vec<ChunkRow> = Vec::new();
let mut scores: Vec<f32> = Vec::new();
- let cfg = config.clone();
let leaves: Vec<(String, f32)> = resp
.hits
.into_iter()
@@ -340,80 +432,82 @@ pub async fn recall_rpc(
.collect::<Vec<_>>()
})
.collect();
- // Hydrated row by row here rather than through `MemoryChunks::chunk_detail`
- // — which `read_chunk_row` below does use — because the two shapes line up
- // field for field save one. `has_embedding` on this path is the legacy
- // `mem_tree_chunks.embedding` column; `chunk_detail` asks the sidecar
- // `mem_tree_chunk_embeddings` table whether a vector exists under the
- // *active* model signature. Nothing has written the inline column since the
- // sidecar migration, so swapping the call flips the flag to true on every
- // embedded chunk — a visible change to what the Memory tab renders, not a
- // routing swap.
+ // Hydrated in ONE call, not one per leaf: `list_chunk_details` takes the ids
+ // as a predicate. Three things about that result are load-bearing.
+ //
+ // The empty case is skipped rather than sent. An empty `ChunkQuery::ids` is
+ // *unfiltered*, so asking for no ids would hydrate the whole store.
+ //
+ // The result may be SHORTER than the ids sent — an id the store does not
+ // hold contributes no row, exactly as the per-id `query_row(…).ok()` this
+ // replaces skipped a miss — and it arrives in the query's own newest-first
+ // order, not in leaf order. So it is re-mapped by id below. Indexing it by
+ // position against the input would silently re-order the recall response
+ // and mis-pair every row with a neighbour's score.
+ //
+ // `has_embedding` changes meaning here, and it is worth being loud about.
+ // The row-by-row SQL read `mem_tree_chunks.embedding`, the inline column the
+ // sidecar migration left behind — nothing has written it since, so the flag
+ // was false for every chunk whether or not it had been embedded. The
+ // contract's flag is an `EXISTS` over `mem_tree_chunk_embeddings` and is
+ // signature-blind, so an embedded chunk now reports true. It is the same
+ // flag `read_chunk_row` below already returns through `chunk_detail`, so
+ // the list and the single-row read stop disagreeing about one chunk.
if !leaves.is_empty() {
- let collected = tokio::task::spawn_blocking(move || -> Result<Vec<(ChunkRow, f32)>> {
- with_connection(&cfg, |conn| {
- let mut out = Vec::with_capacity(leaves.len());
- for (chunk_id, score) in leaves {
- let row = conn
- .query_row(
- "SELECT id, source_kind, source_id, source_ref, owner,
- timestamp_ms, token_count, lifecycle_status,
- content_path, content, tags_json,
- CASE WHEN embedding IS NULL THEN 0 ELSE 1 END
- FROM mem_tree_chunks WHERE id = ?1",
- params![chunk_id],
- |r| {
- let id: String = r.get(0)?;
- let source_kind: String = r.get(1)?;
- let source_id: String = r.get(2)?;
- let source_ref: Option<String> = r.get(3)?;
- let owner: String = r.get(4)?;
- let timestamp_ms: i64 = r.get(5)?;
- let token_count: i64 = r.get(6)?;
- let lifecycle_status: String = r.get(7)?;
- let content_path: Option<String> = r.get(8)?;
- let content: String = r.get(9)?;
- let tags_json: String = r.get(10)?;
- let has_emb: i64 = r.get(11)?;
- let preview: String =
- content.chars().take(PREVIEW_MAX_CHARS).collect();
- let tags: Vec<String> =
- serde_json::from_str(&tags_json).unwrap_or_default();
- Ok(ChunkRow {
- id,
- source_kind,
- source_id,
- source_ref,
- owner,
- timestamp_ms,
- token_count: token_count.max(0) as u32,
- lifecycle_status,
- content_path,
- content_preview: if preview.is_empty() {
- None
- } else {
- Some(preview)
- },
- has_embedding: has_emb != 0,
- tags,
- })
- },
- )
- .ok();
- if let Some(r) = row {
- out.push((r, score));
- }
+ // Deduped, because two level-1 summaries can point at one chunk and the
+ // predicate only needs to name it once — but order-preserving, so the
+ // log below reads against the leaves it came from. Scoped so the borrow
+ // of `leaves` ends here; the walk that pairs rows with scores consumes
+ // it.
+ let ids: Vec<String> = {
+ let mut seen: HashSet<&str> = HashSet::with_capacity(leaves.len());
+ let mut ids = Vec::with_capacity(leaves.len());
+ for (id, _) in &leaves {
+ if seen.insert(id.as_str()) {
+ ids.push(id.clone());
}
- Ok(out)
- })
- })
- .await
- .map_err(|e| format!("recall join error: {e}"))?
- .map_err(|e| format!("recall hydrate: {e:#}"))?;
- for (row, sc) in collected {
- chunk_rows.push(row);
- scores.push(sc);
- }
+ }
+ ids
+ };
+ let id_count = ids.len();
+ let query = ChunkQuery {
+ // Sized to the ids asked for. Left unset, the driver applies its
+ // own default page, which would drop leaves past it — and the page
+ // order is not leaf order, so which ones it dropped would look
+ // arbitrary.
+ limit: Some(id_count),
+ ids,
+ ..Default::default()
+ };
+
+ let binding = crate::openhuman::memory::binding::for_config(config)?;
+ let rows = match binding.provider().as_chunks() {
+ Some(chunks) => chunks
+ .list_chunk_details(&query, None)
+ .await
+ .map_err(|e| format!("list_chunk_details: {e}"))?,
+ None => {
+ log::debug!(
+ "[memory_tree::read::recall] driver '{}' does not serve Chunks; no hydration",
+ binding.driver_id()
+ );
+ Vec::new()
+ }
+ };
+
+ let by_id: HashMap<String, ChunkRow> = rows
+ .into_iter()
+ .map(chunk_row_from_list_row)
+ .map(|row| (row.id.clone(), row))
+ .collect();
+ log::debug!(
+ "[memory_tree::read::recall] hydrate: leaves={} ids={id_count} rows={}",
+ leaves.len(),
+ by_id.len()
+ );
+ let (paired_rows, paired_scores) = pair_leaves_with_rows(&leaves, &by_id);
+ chunk_rows = paired_rows;
+ scores = paired_scores;
}
chunk_rows.truncate(limit);
scores.truncate(limit);
@@ -428,6 +522,33 @@ pub async fn recall_rpc(
))
}
+/// Pair hydrated rows back to the leaves that asked for them, in **leaf order**.
+///
+/// The driver answers in its own newest-first order and may answer with fewer
+/// rows than ids were sent, so the pairing has to go through the id. Walking
+/// `leaves` rather than `rows` is what keeps three promises at once: the order
+/// recall documents, the `chunks[i]` / `scores[i]` alignment the response shape
+/// implies, and one row per leaf for a chunk that two level-1 summaries both
+/// point at — which is what the per-id loop this replaces produced.
+///
+/// Extracted rather than inlined because indexing the driver's answer by
+/// position against the input is the failure this exists to prevent, and an
+/// invariant worth naming is worth being able to test.
+fn pair_leaves_with_rows(
+ leaves: &[(String, f32)],
+ by_id: &HashMap<String, ChunkRow>,
+) -> (Vec<ChunkRow>, Vec<f32>) {
+ let mut rows = Vec::with_capacity(leaves.len());
+ let mut scores = Vec::with_capacity(leaves.len());
+ for (chunk_id, score) in leaves {
+ if let Some(row) = by_id.get(chunk_id) {
+ rows.push(row.clone());
+ scores.push(*score);
+ }
+ }
+ (rows, scores)
+}
+
// ── small helpers ───────────────────────────────────────────────────────
/// One chunk rendered for inspection.
@@ -437,6 +558,9 @@ pub async fn recall_rpc(
/// presence in **one** call. It used to make four separate engine calls in
/// process; four bus round trips per rendered row would have been the direct
/// translation, and this is used to render lists.
+///
+/// [`MemoryChunks::chunk_detail`]:
+/// crate::openhuman::memory::api::provider::MemoryChunks::chunk_detail
pub async fn read_chunk_row(chunk_id: &str) -> Result<Option<ChunkRow>> {
use crate::openhuman::memory::api::provider::MemoryProvider;
@@ -478,3 +602,7 @@ pub async fn read_chunk_row(chunk_id: &str) -> Result<Option<ChunkRow>> {
tags: chunk.metadata.tags,
}))
}
+
+#[cfg(test)]
+#[path = "chunks_tests.rs"]
+mod tests;
diff --git a/src/openhuman/memory/read_rpc/chunks_tests.rs b/src/openhuman/memory/read_rpc/chunks_tests.rs
new file mode 100644
index 0000000000..e4ec87fa80
--- /dev/null
+++ b/src/openhuman/memory/read_rpc/chunks_tests.rs
@@ -0,0 +1,337 @@
+//! Sibling tests for the chunk read-RPCs, covering what moved onto the memory
+//! contract in #5560.
+//!
+//! Three things are worth pinning host-side, and none of them is "the driver
+//! returned the right rows" — that is the driver's, and its own conformance
+//! suite proves it against a real store.
+//!
+//! 1. **An empty `ChunkQuery` predicate means unfiltered, not match-nothing.**
+//! Every `Vec` on that type defaults to empty because `Default` has to mean
+//! "everything", so a caller that *narrowed* a set down to nothing and sent
+//! it anyway asks for the whole store. Only one field here can narrow, and
+//! the tests below are the difference between an empty page and a leak.
+//! 2. **The driver's answer is re-mapped by id, never indexed by position.**
+//! It comes back newest-first and may be shorter than the ids sent, so the
+//! recall response's chunk/score alignment depends on walking the leaves.
+//! 3. **A driver with no chunk family degrades to empty rather than erroring.**
+//! These are reads: "this driver stores no chunks" is a true answer to what
+//! they were asked, unlike the destructive handlers in `admin_tests.rs`.
+
+use super::{
+ chunk_query_from_filter, chunk_row_from_list_row, content_predicate, list_chunks_rpc,
+ list_sources_rpc, pair_leaves_with_rows, search_rpc,
+};
+use chrono::TimeZone;
+
+use crate::openhuman::config::Config;
+use crate::openhuman::memory::api::provider::{ChunkListRow, MemoryProvider};
+use crate::openhuman::memory::binding;
+use std::collections::HashMap;
+use std::sync::Arc;
+use tempfile::TempDir;
+use tinymemory_api::chunks::{Chunk, Metadata, SourceKind, SourceRef};
+use tinymemory_api::null::NullMemoryProvider;
+
+use super::super::types::{ChunkFilter, ChunkRow, PREVIEW_MAX_CHARS};
+
+fn test_config() -> (TempDir, Config) {
+ let tmp = TempDir::new().unwrap();
+ let mut cfg = Config::default();
+ cfg.workspace_dir = tmp.path().to_path_buf();
+ // Keep any persistence these handlers trigger inside the disposable
+ // workspace, exactly as `admin_tests::test_config` does.
+ cfg.config_path = tmp.path().join("config.toml");
+ cfg.memory_tree.embedding_endpoint = None;
+ cfg.memory_tree.embedding_model = None;
+ cfg.memory_tree.embedding_strict = false;
+ (tmp, cfg)
+}
+
+/// Bind the placeholder driver. It implements `MemoryChunks` but does not
+/// override `as_chunks`, so the accessor answers `None` — which is the state
+/// these degrade tests are about.
+fn install_null_driver(cfg: &Config) {
+ binding::install_for_test(
+ &cfg.workspace_dir,
+ &cfg.subsystems.memory,
+ Arc::new(NullMemoryProvider::new()) as Arc<dyn MemoryProvider>,
+ );
+}
+
+fn sample_row(id: &str, content: &str) -> ChunkListRow {
+ let timestamp = chrono::Utc
+ .timestamp_millis_opt(1_700_000_000_000)
+ .single()
+ .expect("a valid fixture timestamp");
+ let mut metadata = Metadata::point_in_time(SourceKind::Chat, "slack:#eng", "alice", timestamp);
+ metadata.tags = vec!["ingested".to_string()];
+ metadata.source_ref = Some(SourceRef::new("slack://archives/C123/1"));
+ ChunkListRow {
+ chunk: Chunk {
+ id: id.to_string(),
+ content: content.to_string(),
+ metadata,
+ token_count: 7,
+ seq_in_source: 0,
+ created_at: timestamp,
+ partial_message: false,
+ },
+ content_path: Some("chat/slack/eng/0.md".to_string()),
+ lifecycle_status: Some("admitted".to_string()),
+ has_embedding: true,
+ }
+}
+
+fn row_named(id: &str) -> ChunkRow {
+ chunk_row_from_list_row(sample_row(id, "body"))
+}
+
+// ── the empty-predicate footgun ──────────────────────────────────────────
+
+/// An absent list and an explicitly empty one both mean "do not filter on
+/// this", which is what the SQL did — it skipped the clause for an empty list —
+/// and what an empty `Vec` on `ChunkQuery` already means.
+#[test]
+fn absent_and_empty_filter_lists_are_unfiltered() {
+ for filter in [
+ ChunkFilter::default(),
+ ChunkFilter {
+ source_kinds: Some(vec![]),
+ source_ids: Some(vec![]),
+ entity_ids: Some(vec![]),
+ query: Some(" ".into()),
+ ..ChunkFilter::default()
+ },
+ ] {
+ let query = chunk_query_from_filter(&filter, 10, 0).expect("an unfiltered query, not None");
+ assert!(query.source_kinds.is_empty());
+ assert!(query.source_ids.is_empty());
+ assert!(query.entity_ids.is_empty());
+ assert!(query.ids.is_empty());
+ assert_eq!(query.content_contains, None);
+ }
+}
+
+/// The one field that can narrow to nothing, and the reason this function
+/// returns an `Option` at all.
+///
+/// `source_kind IN ('bogus')` matched no row; an empty `source_kinds` vec would
+/// match every row in the store. Those are opposite answers, so the caller has
+/// to be told to skip the query rather than handed a query that cannot say it.
+#[test]
+fn a_wholly_unrecognised_source_kind_set_short_circuits() {
+ let filter = ChunkFilter {
+ source_kinds: Some(vec!["bogus".into(), "also-bogus".into()]),
+ ..ChunkFilter::default()
+ };
+ assert!(
+ chunk_query_from_filter(&filter, 10, 0).is_none(),
+ "a set of kinds this build cannot decode matches nothing; sending an empty \
+ predicate would return the whole store"
+ );
+}
+
+/// One unknown value beside a known one is dropped, not fatal — exactly what
+/// `source_kind IN ('chat', 'bogus')` did.
+#[test]
+fn an_unrecognised_source_kind_beside_a_known_one_is_dropped() {
+ let filter = ChunkFilter {
+ source_kinds: Some(vec!["chat".into(), "bogus".into()]),
+ ..ChunkFilter::default()
+ };
+ let query = chunk_query_from_filter(&filter, 10, 0).expect("the known kind still filters");
+ assert_eq!(query.source_kinds, vec![SourceKind::Chat]);
+}
+
+/// The page bounds travel on the same value the total is counted from, which is
+/// the whole reason the two cannot drift: `count_chunks` drops these and keeps
+/// every predicate beside them.
+#[test]
+fn the_page_bounds_and_predicates_ride_one_query() {
+ let filter = ChunkFilter {
+ source_ids: Some(vec!["slack:#eng".into()]),
+ entity_ids: Some(vec!["email:[email protected]".into()]),
+ since_ms: Some(1_700_000_000_000),
+ until_ms: Some(1_700_000_000_500),
+ query: Some("phoenix".into()),
+ ..ChunkFilter::default()
+ };
+ let query = chunk_query_from_filter(&filter, 25, 50).expect("a filtered query");
+ assert_eq!(query.limit, Some(25));
+ assert_eq!(query.offset, Some(50));
+ assert_eq!(query.source_ids, vec!["slack:#eng".to_string()]);
+ assert_eq!(
+ query.entity_ids,
+ vec!["email:[email protected]".to_string()]
+ );
+ assert_eq!(query.since_ms, Some(1_700_000_000_000));
+ assert_eq!(query.until_ms, Some(1_700_000_000_500));
+ assert_eq!(query.content_contains.as_deref(), Some("phoenix"));
+ // The Memory tab lists dropped rows and renders their status, so the
+ // lifecycle predicate the SQL never had must stay off.
+ assert!(!query.exclude_dropped);
+}
+
+/// The substring travels bare. Wrapping it in `%…%` host-side would double the
+/// driver's own wrapping and match nothing.
+#[test]
+fn the_content_predicate_is_trimmed_and_unwrapped() {
+ assert_eq!(content_predicate(" phoenix ").as_deref(), Some("phoenix"));
+ assert_eq!(content_predicate(" "), None);
+ assert_eq!(content_predicate(""), None);
+ // `%` and `_` are the user's text; escaping them is the driver's job, so
+ // they must arrive intact rather than pre-mangled here.
+ assert_eq!(content_predicate("50%_off").as_deref(), Some("50%_off"));
+}
+
+// ── the wire shape ───────────────────────────────────────────────────────
+
+/// `ChunkListRow` carries no body, and nothing is lost: the preview has always
+/// come from the stored `content` column, which is what `Chunk::content` is.
+#[test]
+fn a_listing_row_renders_every_wire_field() {
+ let row = chunk_row_from_list_row(sample_row("chunk-1", "phoenix migration"));
+ assert_eq!(row.id, "chunk-1");
+ assert_eq!(row.source_kind, "chat");
+ assert_eq!(row.source_id, "slack:#eng");
+ assert_eq!(row.source_ref.as_deref(), Some("slack://archives/C123/1"));
+ assert_eq!(row.owner, "alice");
+ assert_eq!(row.timestamp_ms, 1_700_000_000_000);
+ assert_eq!(row.token_count, 7);
+ assert_eq!(row.lifecycle_status, "admitted");
+ assert_eq!(row.content_path.as_deref(), Some("chat/slack/eng/0.md"));
+ assert_eq!(row.content_preview.as_deref(), Some("phoenix migration"));
+ assert!(row.has_embedding);
+ assert_eq!(row.tags, vec!["ingested".to_string()]);
+}
+
+/// An empty body is `None`, not `Some("")` — the frontend reads the absence.
+#[test]
+fn an_empty_body_renders_no_preview() {
+ assert_eq!(
+ chunk_row_from_list_row(sample_row("c", "")).content_preview,
+ None
+ );
+}
+
+/// The cap is applied in characters, as it always was, and is a no-op on a row
+/// whose stored column is already the vault preview.
+#[test]
+fn the_preview_is_capped_in_characters() {
+ let long = "é".repeat(PREVIEW_MAX_CHARS + 10);
+ let row = chunk_row_from_list_row(sample_row("c", &long));
+ assert_eq!(
+ row.content_preview.as_deref().map(|p| p.chars().count()),
+ Some(PREVIEW_MAX_CHARS)
+ );
+}
+
+/// A driver with no lifecycle concept reports `None`; the engine's column is
+/// `NOT NULL`, so this is the contract's slack rather than a reachable state —
+/// and it renders the same word `read_chunk_row` renders.
+#[test]
+fn an_unrecorded_lifecycle_renders_as_unknown() {
+ let mut source = sample_row("c", "body");
+ source.lifecycle_status = None;
+ assert_eq!(chunk_row_from_list_row(source).lifecycle_status, "unknown");
+}
+
+// ── recall hydration ─────────────────────────────────────────────────────
+
+/// The driver answers newest-first and the leaves are score-ordered, so pairing
+/// by position would silently re-order recall and mis-pair every score.
+#[test]
+fn hydrated_rows_follow_leaf_order_not_driver_order() {
+ let leaves = vec![
+ ("c-3".to_string(), 0.9_f32),
+ ("c-1".to_string(), 0.5_f32),
+ ("c-2".to_string(), 0.1_f32),
+ ];
+ // Deliberately a different order from the leaves, which is what the
+ // driver's own `ORDER BY timestamp_ms DESC` produces.
+ let by_id: HashMap<String, ChunkRow> = ["c-1", "c-2", "c-3"]
+ .into_iter()
+ .map(|id| (id.to_string(), row_named(id)))
+ .collect();
+
+ let (rows, scores) = pair_leaves_with_rows(&leaves, &by_id);
+ assert_eq!(
+ rows.iter().map(|r| r.id.as_str()).collect::<Vec<_>>(),
+ vec!["c-3", "c-1", "c-2"]
+ );
+ assert_eq!(scores, vec![0.9_f32, 0.5, 0.1]);
+}
+
+/// An id the store does not hold contributes no row, so the answer is shorter
+/// than the input — and the scores must shorten with it, not slide.
+#[test]
+fn an_id_the_store_does_not_hold_drops_its_score_too() {
+ let leaves = vec![
+ ("missing".to_string(), 0.9_f32),
+ ("c-1".to_string(), 0.4_f32),
+ ];
+ let by_id: HashMap<String, ChunkRow> = HashMap::from([("c-1".to_string(), row_named("c-1"))]);
+
+ let (rows, scores) = pair_leaves_with_rows(&leaves, &by_id);
+ assert_eq!(rows.len(), 1);
+ assert_eq!(rows[0].id, "c-1");
+ assert_eq!(scores, vec![0.4_f32]);
+}
+
+/// Two level-1 summaries can both point at one chunk. The per-id loop this
+/// replaced emitted it once per leaf, and the deduped `ids` predicate must not
+/// change that.
+#[test]
+fn a_chunk_two_summaries_share_appears_once_per_leaf() {
+ let leaves = vec![("c-1".to_string(), 0.9_f32), ("c-1".to_string(), 0.2_f32)];
+ let by_id: HashMap<String, ChunkRow> = HashMap::from([("c-1".to_string(), row_named("c-1"))]);
+
+ let (rows, scores) = pair_leaves_with_rows(&leaves, &by_id);
+ assert_eq!(rows.len(), 2);
+ assert_eq!(scores, vec![0.9_f32, 0.2]);
+}
+
+// ── degrading on a driver with no chunk family ───────────────────────────
+
+/// A read, so empty is the honest answer: a driver holding no chunks has none
+/// to list and none to count. The total must degrade with the page — a page of
+/// nothing labelled "of 431" is worse than either half alone.
+#[tokio::test]
+async fn list_chunks_reports_empty_without_a_chunks_family() {
+ let (_tmp, cfg) = test_config();
+ install_null_driver(&cfg);
+
+ let outcome = list_chunks_rpc(&cfg, ChunkFilter::default())
+ .await
+ .expect("a driver without the chunk family is not an error");
+ assert!(outcome.value.chunks.is_empty());
+ assert_eq!(outcome.value.total, 0);
+ assert!(
+ outcome.logs[0].contains("n=0 total=0"),
+ "log: {}",
+ outcome.logs[0]
+ );
+}
+
+#[tokio::test]
+async fn list_sources_reports_empty_without_a_chunks_family() {
+ let (_tmp, cfg) = test_config();
+ install_null_driver(&cfg);
+
+ let outcome = list_sources_rpc(&cfg, None)
+ .await
+ .expect("a driver without the chunk family is not an error");
+ assert!(outcome.value.is_empty());
+}
+
+#[tokio::test]
+async fn search_reports_empty_without_a_chunks_family() {
+ let (_tmp, cfg) = test_config();
+ install_null_driver(&cfg);
+
+ let outcome = search_rpc(&cfg, "phoenix".into(), 10)
+ .await
+ .expect("a driver without the chunk family is not an error");
+ assert!(outcome.value.is_empty());
+ assert!(outcome.logs[0].contains("n=0"), "log: {}", outcome.logs[0]);
+}
diff --git a/src/openhuman/memory/read_rpc/entities.rs b/src/openhuman/memory/read_rpc/entities.rs
index 772835a8e0..8f8fd328b6 100644
--- a/src/openhuman/memory/read_rpc/entities.rs
+++ b/src/openhuman/memory/read_rpc/entities.rs
@@ -1,61 +1,91 @@
-use anyhow::{Context, Result};
-use rusqlite::params;
+use anyhow::Result;
use crate::openhuman::config::Config;
+use crate::openhuman::memory::binding::MemoryBinding;
use crate::openhuman::memory::tree::score::store as score_store;
use crate::rpc::RpcOutcome;
-use tinymemory_core::store::chunks::store::with_connection;
+use tinymemory_api::error::MemoryError;
+use tinymemory_api::provider::types::{EntityOccurrence, ForgetSelector};
use super::types::{DeleteChunkResponse, EntityRef, ScoreBreakdown, ScoreSignal, MAX_LIST_LIMIT};
// ── entity index lookups ────────────────────────────────────────────────
+//
+// All three read the driver's entity index through `MemoryEntities`, and each
+// uses the member written for the *browser's* reading of that index rather than
+// the agent's: `top_entities` for what the store holds at all, `chunk_entities`
+// for what one chunk is about, `entity_chunk_ids` for the content behind one
+// entity. `MemoryEntities::entities` is deliberately not the member for any of
+// them — it is namespace-scoped where these are store-wide, hotness-ranked
+// where these rank by observation count, and its `EntityHit` carries a
+// canonical name where these carry the index's `surface` sample.
+//
+// None of the three needs `spawn_blocking`: the driver owns whether its own
+// reads block, and the module's do not run on this thread at all.
-// These three read `mem_tree_entity_index` directly, and the contract's entity
-// family does not cover them. `MemoryEntities::entities` looks like a fit for
-// `top_entities` and is not: it is namespace-scoped where this is store-wide,
-// ranks by hotness where this ranks by mention count, and the `EntityRef::name`
-// on its `EntityHit` is a canonical name, not the `MAX(surface)` sample this
-// handler's own `EntityRef` carries.
-// `entity_index_for` (the entities of one chunk) and `chunks_for_entity` (the
-// chunk ids of one entity) have no member at all — `entity_edges` answers
-// entity-to-entity, never entity-to-chunk.
+/// One occurrence row in the shape this RPC surface has always returned.
+///
+/// Field for field, including the one rename: the index's `mentions` is the
+/// `COUNT(*)` this handler's `count` has always carried.
+fn entity_ref(occurrence: EntityOccurrence) -> EntityRef {
+ EntityRef {
+ entity_id: occurrence.entity_id,
+ kind: occurrence.kind,
+ surface: occurrence.surface,
+ count: occurrence.mentions,
+ }
+}
+
+/// Every entity indexed against one chunk, most-observed first.
+///
+/// Shared by [`entity_index_for_rpc`], which reports the rows, and
+/// [`delete_chunk_rpc`], which counts the ones a delete is about to take with
+/// it. `op` is the caller's name, so an error still reads as that handler's.
+///
+/// The batch is one id long on purpose. `chunk_entities` names the chunk on
+/// every row precisely because a wider batch answers as one flat list and
+/// grouping becomes the caller's job — with a single id every row is this
+/// chunk's by construction, so there is nothing to group and nothing that could
+/// be mis-indexed by position.
+///
+/// A driver with no entity tier reports no rows rather than failing: both
+/// callers are describing what the index holds, and it holds nothing.
+async fn chunk_entity_rows(
+ binding: &MemoryBinding,
+ chunk_id: &str,
+ op: &str,
+) -> Result<Vec<EntityOccurrence>, String> {
+ let Some(entities) = binding.provider().as_entities() else {
+ log::debug!(
+ "[memory_tree::read::entity_index] {op}: driver '{}' does not serve Entities; \
+ reporting empty",
+ binding.driver_id()
+ );
+ return Ok(Vec::new());
+ };
+ let ids = [chunk_id.to_string()];
+ let rows = entities
+ .chunk_entities(&ids, None)
+ .await
+ .map_err(|e| format!("{op}: {e}"))?;
+ log::debug!(
+ "[memory_tree::read::entity_index] {op}: driver '{}' rows={} chunk_id={chunk_id}",
+ binding.driver_id(),
+ rows.len()
+ );
+ Ok(rows.into_iter().map(|row| row.occurrence).collect())
+}
pub async fn entity_index_for_rpc(
config: &Config,
chunk_id: String,
) -> Result<RpcOutcome<Vec<EntityRef>>, String> {
- let cfg = config.clone();
- let id = chunk_id.clone();
- let refs = tokio::task::spawn_blocking(move || -> Result<Vec<EntityRef>> {
- with_connection(&cfg, |conn| {
- let mut stmt = conn.prepare(
- "SELECT entity_id, entity_kind, surface, COUNT(*) AS n
- FROM mem_tree_entity_index
- WHERE node_id = ?1
- GROUP BY entity_id, entity_kind, surface
- ORDER BY n DESC, entity_id ASC",
- )?;
- let rows = stmt
- .query_map(params![id], |row| {
- let entity_id: String = row.get(0)?;
- let kind: String = row.get(1)?;
- let surface: String = row.get(2)?;
- let n: i64 = row.get(3)?;
- Ok(EntityRef {
- entity_id,
- kind,
- surface,
- count: n.max(0) as u32,
- })
- })?
- .collect::<rusqlite::Result<Vec<_>>>()
- .context("collect entity_index_for rows")?;
- Ok(rows)
- })
- })
- .await
- .map_err(|e| format!("entity_index_for join error: {e}"))?
- .map_err(|e| format!("entity_index_for: {e:#}"))?;
+ let binding = crate::openhuman::memory::binding::for_config(config)?;
+ let refs: Vec<EntityRef> = chunk_entity_rows(&binding, &chunk_id, "entity_index_for")
+ .await?
+ .into_iter()
+ .map(entity_ref)
+ .collect();
let n = refs.len();
Ok(RpcOutcome::single_log(
@@ -68,31 +98,46 @@ pub async fn chunks_for_entity_rpc(
config: &Config,
entity_id: String,
) -> Result<RpcOutcome<Vec<String>>, String> {
- let cfg = config.clone();
- let eid = entity_id.clone();
- let chunk_ids = tokio::task::spawn_blocking(move || -> Result<Vec<String>> {
- with_connection(&cfg, |conn| {
- let mut stmt = conn.prepare(
- "SELECT DISTINCT node_id
- FROM mem_tree_entity_index
- WHERE entity_id = ?1 AND node_kind = 'leaf'
- ORDER BY timestamp_ms DESC",
- )?;
- let rows = stmt
- .query_map(params![eid], |row| {
- let node_id: String = row.get(0)?;
- Ok(node_id)
- })?
- .collect::<rusqlite::Result<Vec<_>>>()
- .context("collect chunks_for_entity rows")?;
- Ok(rows)
- })
- })
- .await
- .map_err(|e| format!("chunks_for_entity join error: {e}"))?
- .map_err(|e| format!("chunks_for_entity: {e:#}"))?;
+ let binding = crate::openhuman::memory::binding::for_config(config)?;
+ let chunk_ids = match binding.provider().as_entities() {
+ // A bound appears where the SQL had none, because `entity_chunk_ids`
+ // requires one and the contract gives a driver no way to say
+ // "unbounded". That is the right shape for a member reached over a bus:
+ // the previous query would happily stream every chunk an entity was
+ // ever seen in, as one RPC response, over a wire the caller cannot
+ // interrupt.
+ //
+ // `MAX_LIST_LIMIT` is the cap this module already applies to every
+ // other list it serves, so the ceiling is the surface's own rather than
+ // a number invented here. It is a ceiling and not a page: this handler
+ // has never taken a `limit` and its response is a bare `Vec<String>`
+ // with nowhere to report truncation, so widening the wire to say
+ // "there were more" is a change this migration has no mandate to make.
+ // An entity observed in more than a thousand chunks is a graph query,
+ // not a list.
+ Some(entities) => entities
+ .entity_chunk_ids(&entity_id, MAX_LIST_LIMIT as usize)
+ .await
+ .map_err(|e| format!("chunks_for_entity: {e}"))?,
+ // Read-only, so an empty list is the honest answer: a driver with no
+ // entity tier indexed this entity nowhere, which is a true statement
+ // about it rather than a fault the caller can act on.
+ None => {
+ log::debug!(
+ "[memory_tree::read::chunks_for_entity] driver '{}' does not serve Entities; \
+ reporting empty",
+ binding.driver_id()
+ );
+ Vec::new()
+ }
+ };
let n = chunk_ids.len();
+ log::debug!(
+ "[memory_tree::read::chunks_for_entity] driver '{}' entity_id={entity_id} n={n} limit={}",
+ binding.driver_id(),
+ MAX_LIST_LIMIT
+ );
Ok(RpcOutcome::single_log(
chunk_ids,
format!("memory_tree::read: chunks_for_entity entity_id={entity_id} n={n}"),
@@ -105,52 +150,57 @@ pub async fn top_entities_rpc(
limit: u32,
) -> Result<RpcOutcome<Vec<EntityRef>>, String> {
let limit = limit.clamp(1, MAX_LIST_LIMIT);
- let cfg = config.clone();
- let refs = tokio::task::spawn_blocking(move || -> Result<Vec<EntityRef>> {
- with_connection(&cfg, |conn| {
- let mut sql = String::from(
- "SELECT entity_id, entity_kind, MAX(surface) AS surface_sample, COUNT(*) AS n
- FROM mem_tree_entity_index",
- );
- let mut params_owned: Vec<Box<dyn rusqlite::ToSql>> = Vec::new();
- if let Some(k) = kind {
- sql.push_str(" WHERE entity_kind = ?");
- params_owned.push(Box::new(k));
+ let binding = crate::openhuman::memory::binding::for_config(config)?;
+ let refs: Vec<EntityRef> = match binding.provider().as_entities() {
+ Some(entities) => {
+ let answered = entities.top_entities(kind.as_deref(), limit as usize).await;
+ match answered {
+ Ok(rows) => rows.into_iter().map(entity_ref).collect(),
+ // The one behaviour delta this migration was warned about, and
+ // it is decided in favour of the wire this handler already has.
+ // The member validates `kind` and answers `Invalid` for one it
+ // does not recognise; the SQL it replaces compared the string
+ // against the stored column, so an unknown kind matched no rows
+ // and the handler returned an empty list. A migration that
+ // turns a quiet empty result into a user-visible error is
+ // changing the product, not moving a call, so the variant is
+ // mapped back — narrowly, and never silently.
+ //
+ // Narrowly means two things. Only `Invalid` degrades, so a
+ // backend failure still propagates. And only when a `kind` was
+ // actually supplied: `Invalid` with no filter to be invalid
+ // about is a driver fault, and swallowing that is exactly what
+ // this map-back is careful not to do.
+ Err(MemoryError::Invalid(reason)) if kind.is_some() => {
+ log::debug!(
+ "[memory_tree::read::top_entities] driver '{}' rejected kind={:?} \
+ ({reason}); reporting empty, which is what the SQL this replaced returned",
+ binding.driver_id(),
+ kind
+ );
+ Vec::new()
+ }
+ Err(e) => return Err(format!("top_entities: {e}")),
}
- sql.push_str(
- " GROUP BY entity_id, entity_kind
- ORDER BY n DESC, MAX(timestamp_ms) DESC
- LIMIT ?",
+ }
+ // Read-only, so an empty ranking is the honest answer: a driver with no
+ // entity tier has nothing indexed to rank.
+ None => {
+ log::debug!(
+ "[memory_tree::read::top_entities] driver '{}' does not serve Entities; \
+ reporting empty",
+ binding.driver_id()
);
- params_owned.push(Box::new(limit as i64));
- let mut stmt = conn.prepare(&sql)?;
- let param_refs: Vec<&dyn rusqlite::ToSql> = params_owned
- .iter()
- .map(|b| b.as_ref() as &dyn rusqlite::ToSql)
- .collect();
- let rows = stmt
- .query_map(param_refs.as_slice(), |row| {
- let entity_id: String = row.get(0)?;
- let kind: String = row.get(1)?;
- let surface: String = row.get(2)?;
- let n: i64 = row.get(3)?;
- Ok(EntityRef {
- entity_id,
- kind,
- surface,
- count: n.max(0) as u32,
- })
- })?
- .collect::<rusqlite::Result<Vec<_>>>()
- .context("collect top_entities rows")?;
- Ok(rows)
- })
- })
- .await
- .map_err(|e| format!("top_entities join error: {e}"))?
- .map_err(|e| format!("top_entities: {e:#}"))?;
+ Vec::new()
+ }
+ };
let n = refs.len();
+ log::debug!(
+ "[memory_tree::read::top_entities] driver '{}' kind={:?} limit={limit} n={n}",
+ binding.driver_id(),
+ kind
+ );
Ok(RpcOutcome::single_log(
refs,
format!("memory_tree::read: top_entities n={n}"),
@@ -158,6 +208,10 @@ pub async fn top_entities_rpc(
}
// ── chunk_score ─────────────────────────────────────────────────────────
+//
+// Still the engine's scorer, and deliberately so: `chunk_score` and
+// `DEFAULT_DROP_THRESHOLD` are engine-internal ranking that the contract
+// excludes by design, so there is no member to route this onto (#5560).
pub async fn chunk_score_rpc(
config: &Config,
@@ -226,56 +280,94 @@ pub async fn chunk_score_rpc(
// ── delete_chunk ────────────────────────────────────────────────────────
+/// Whether `mem_tree_score` holds a row for this chunk, as a rowcount.
+///
+/// The table is keyed by chunk id, so "is there a row" *is* the number the
+/// `DELETE` this replaced returned. It is read through the same
+/// `tree::score::store` door [`chunk_score_rpc`] above already uses — the
+/// scorer is engine-internal ranking the contract excludes by design, so there
+/// is no member to reach for and no second door being opened here.
+///
+/// `spawn_blocking` stays because this one genuinely still blocks: it is a
+/// synchronous SQLite read on the calling thread, unlike the driver calls
+/// around it.
+async fn score_row_count(config: &Config, chunk_id: &str) -> Result<u32, String> {
+ let cfg = config.clone();
+ let id = chunk_id.to_string();
+ let row = tokio::task::spawn_blocking(move || score_store::get_score(&cfg, &id))
+ .await
+ .map_err(|e| format!("delete_chunk join error: {e}"))?
+ .map_err(|e| format!("delete_chunk: {e:#}"))?;
+ Ok(u32::from(row.is_some()))
+}
+
pub async fn delete_chunk_rpc(
config: &Config,
chunk_id: String,
) -> Result<RpcOutcome<DeleteChunkResponse>, String> {
- let cfg = config.clone();
- let id = chunk_id.clone();
- let resp = tokio::task::spawn_blocking(move || -> Result<DeleteChunkResponse> {
- with_connection(&cfg, |conn| {
- let tx = conn.unchecked_transaction()?;
- let content_path: Option<String> = tx
- .query_row(
- "SELECT content_path FROM mem_tree_chunks WHERE id = ?1",
- params![id],
- |r| r.get::<_, Option<String>>(0),
- )
- .ok()
- .flatten();
- let removed_score =
- tx.execute("DELETE FROM mem_tree_score WHERE chunk_id = ?1", params![id])?;
- let removed_index = tx.execute(
- "DELETE FROM mem_tree_entity_index WHERE node_id = ?1",
- params![id],
- )?;
- let removed_chunk =
- tx.execute("DELETE FROM mem_tree_chunks WHERE id = ?1", params![id])?;
- tx.commit()?;
- if let Some(rel) = content_path {
- let mut path = cfg.memory_tree_content_root();
- for component in rel.split('/') {
- path.push(component);
- }
- if let Err(e) = std::fs::remove_file(&path) {
- if e.kind() != std::io::ErrorKind::NotFound {
- log::warn!(
- "[memory_tree::read::delete] failed to remove chunk file path_hash={}: {e}",
- crate::openhuman::util::redact::redact(&rel),
- );
- }
- }
- }
- Ok(DeleteChunkResponse {
- deleted: removed_chunk > 0,
- score_rows_removed: removed_score as u32,
- entity_index_rows_removed: removed_index as u32,
- })
- })
- })
- .await
- .map_err(|e| format!("delete_chunk join error: {e}"))?
- .map_err(|e| format!("delete_chunk: {e:#}"))?;
+ let binding = crate::openhuman::memory::binding::for_config(config)?;
+
+ // Resolved on `provider()` and **refused** when the family is absent, not
+ // degraded. The read handlers above answer empty for a missing family
+ // because "this driver indexes nothing" is a true answer to what they were
+ // asked; this is a delete, and its empty answer — `deleted: false` — is
+ // byte-identical to "that chunk was already gone". The contract makes the
+ // same call in `forget_matching`'s own errors: on a delete, a zero the
+ // caller reads as "already gone" is worse than a refusal.
+ let Some(sources) = binding.provider().as_sources() else {
+ return Err(format!(
+ "delete_chunk: driver '{}' does not serve Sources",
+ binding.driver_id()
+ ));
+ };
+
+ // Both side-row counts are observed BEFORE the delete, because
+ // `ForgetOutcome` does not carry them: it reports `chunks_removed` and
+ // `trees_cleaned`, and its own docs say the per-chunk side rows go
+ // *together with* the chunk rather than being counted apart from it.
+ // `DeleteChunkResponse` has reported these two numbers since it existed and
+ // the frontend logs both, so they are read here rather than dropped to
+ // zero — a zero after a successful delete reads as "there was nothing to
+ // clean up", which is a different claim from "nobody counted".
+ //
+ // The cost, stated rather than hidden: these are a pre-delete observation,
+ // not the transactional rowcounts the hand-written SQL returned. A writer
+ // landing between the read and the delete would move them. Both are
+ // diagnostics about one chunk a user is looking at, so a race no user can
+ // provoke is the cheaper price than a number that stops being reported.
+ let entity_index_rows_removed = chunk_entity_rows(&binding, &chunk_id, "delete_chunk")
+ .await?
+ .iter()
+ .map(|occurrence| occurrence.mentions)
+ .fold(0u32, u32::saturating_add);
+ let score_rows_removed = score_row_count(config, &chunk_id).await?;
+
+ let selector = ForgetSelector::Chunk {
+ chunk_id: chunk_id.clone(),
+ };
+ let outcome = sources
+ .forget_matching(&selector)
+ .await
+ .map_err(|e| format!("delete_chunk: {e}"))?;
+
+ // No host-side file removal any more, and no `spawn_blocking` to host it.
+ // The driver's by-id delete collects `content_path` inside the transaction
+ // and unlinks after the commit, together with the chunk's embedding row,
+ // its reembed-skipped row, and any raw-ref files nothing else points at —
+ // the last three of which the hand-written SQL this replaces left behind.
+ let resp = DeleteChunkResponse {
+ deleted: outcome.chunks_removed > 0,
+ score_rows_removed,
+ entity_index_rows_removed,
+ };
+ log::debug!(
+ "[memory_tree::read::delete] driver '{}' id={chunk_id} chunks_removed={} \
+ trees_cleaned={} score_rows={score_rows_removed} \
+ entity_rows={entity_index_rows_removed}",
+ binding.driver_id(),
+ outcome.chunks_removed,
+ outcome.trees_cleaned
+ );
Ok(RpcOutcome::single_log(
resp.clone(),
format!(
diff --git a/src/openhuman/memory/read_rpc/graph.rs b/src/openhuman/memory/read_rpc/graph.rs
index 7b8527efa4..e4f061f1b7 100644
--- a/src/openhuman/memory/read_rpc/graph.rs
+++ b/src/openhuman/memory/read_rpc/graph.rs
@@ -1,16 +1,30 @@
-use anyhow::{Context, Result};
-use rusqlite::params;
use serde::{Deserialize, Serialize};
use crate::openhuman::config::Config;
+use crate::openhuman::memory::api::provider::ChunkQuery;
+use crate::openhuman::memory::api::tree::{TreeLeaf, TreeSummary};
use crate::rpc::RpcOutcome;
-use tinymemory_core::store::chunks::store::with_connection;
// `MemoryGraph` in the contract is the key/value and relation tier, a different
-// graph from the one exported here: the summary tree and its leaf chunks, laid
-// out for the Memory tab. No family walks a whole store's summaries, and none
-// exposes the entity-mention edges `contacts` mode draws, so both collectors
-// below read the engine's tables.
+// graph from the one exported here: the summary forest and its leaf chunks,
+// laid out for the Memory tab. Both collectors below are ordinary contract
+// reads — `MemoryTree::{summary_forest, recent_leaves}` for the forest, and
+// `MemoryChunks::list_chunks` + `MemoryEntities::chunk_entities` for the
+// contacts view — so neither reaches the engine's tables any more (#5560).
+//
+// **Three of those four members need a host-side forwarder that does not exist
+// yet**, and this is the same hazard `tree::rpc::ingest_rpc` documents for
+// `IngestEmail`. `ModuleMemoryProvider` — the driver every shipped build
+// binds — implements `MemoryTree` without `summary_forest` / `recent_leaves`
+// and `MemoryEntities` without `chunk_entities`, so those calls fall to the
+// trait's default body and answer `Unsupported`. The errors are propagated
+// rather than degraded to an empty graph, deliberately: `summary_forest`'s own
+// contract refuses to answer an empty forest for exactly this reason, and a
+// Memory tab that renders "no memories" because a method is missing is the
+// failure nobody chases. Closing it is three things in order, none of them
+// here: a forwarder per member in `modules::memory`, a `tinymemory` release
+// carrying them, and the `modules::registry` + `ARTIFACT_CAPABILITIES_PIN`
+// re-pin onto it.
// ── wire types ────────────────────────────────────────────────────────────
@@ -63,28 +77,35 @@ pub struct GraphExportResponse {
pub content_root_abs: String,
}
+/// Label cap for a chunk node, in characters. Unchanged by the move onto the
+/// contract: `TreeLeaf::preview` is capped at 200 by the driver, so this is
+/// still the cut the UI sees.
+const CHUNK_LABEL_CHARS: usize = 72;
+
// ── graph_export ────────────────────────────────────────────────────────
pub async fn graph_export_rpc(
config: &Config,
mode: GraphMode,
) -> Result<RpcOutcome<GraphExportResponse>, String> {
- let cfg = config.clone();
- let resp = tokio::task::spawn_blocking(move || -> Result<GraphExportResponse> {
- let content_root = cfg.memory_tree_content_root();
- let resp = match mode {
- GraphMode::Tree => collect_tree_graph(&cfg)?,
- GraphMode::Contacts => collect_contacts_graph(&cfg)?,
- };
- Ok(GraphExportResponse {
- nodes: resp.0,
- edges: resp.1,
- content_root_abs: content_root.to_string_lossy().to_string(),
- })
- })
- .await
- .map_err(|e| format!("graph_export join error: {e}"))?
- .map_err(|e| format!("graph_export: {e:#}"))?;
+ log::debug!("[memory_tree::read::graph_export] mode={mode:?}");
+
+ // No `spawn_blocking`: every read below is a driver call, the driver owns
+ // whether its own reads block, and the module's do not run on this thread
+ // at all. The only other work here is `memory_tree_content_root`, which is
+ // a path join.
+ let content_root = config.memory_tree_content_root();
+ let (nodes, edges) = match mode {
+ GraphMode::Tree => collect_tree_graph(config).await,
+ GraphMode::Contacts => collect_contacts_graph(config).await,
+ }
+ .map_err(|e| format!("graph_export: {e}"))?;
+
+ let resp = GraphExportResponse {
+ nodes,
+ edges,
+ content_root_abs: content_root.to_string_lossy().to_string(),
+ };
let log = format!(
"memory_tree::read: graph_export mode={:?} nodes={} edges={} root_hash={}",
mode,
@@ -97,7 +118,7 @@ pub async fn graph_export_rpc(
// ── collect_tree_graph ───────────────────────────────────────────────────
-fn collect_tree_graph(cfg: &Config) -> Result<(Vec<GraphNode>, Vec<GraphEdge>)> {
+async fn collect_tree_graph(cfg: &Config) -> Result<(Vec<GraphNode>, Vec<GraphEdge>), String> {
const MAX_TREE_NODES: usize = 10_000;
struct SummaryRow {
@@ -106,55 +127,90 @@ fn collect_tree_graph(cfg: &Config) -> Result<(Vec<GraphNode>, Vec<GraphEdge>)>
child_ids: Vec<String>,
}
- let summary_rows = with_connection(cfg, |conn| {
- let mut stmt = conn.prepare(
- "SELECT s.id, s.tree_id, s.tree_kind, t.scope, s.level, s.parent_id,
- s.child_ids_json, s.time_range_start_ms, s.time_range_end_ms
- FROM mem_tree_summaries s
- JOIN mem_tree_trees t ON t.id = s.tree_id
- WHERE s.deleted = 0
- ORDER BY s.tree_id, s.level, s.sealed_at_ms",
- )?;
- let rows = stmt
- .query_map([], |row| {
- let id: String = row.get(0)?;
- let tree_id: String = row.get(1)?;
- let tree_kind: String = row.get(2)?;
- let tree_scope: String = row.get(3)?;
- let level: i64 = row.get(4)?;
- let parent_id: Option<String> = row.get(5)?;
- let child_ids_json: String = row.get(6)?;
- let time_range_start_ms: i64 = row.get(7)?;
- let time_range_end_ms: i64 = row.get(8)?;
- let child_ids: Vec<String> =
- serde_json::from_str(&child_ids_json).unwrap_or_default();
- let child_count = child_ids.len() as u32;
- let file_basename = sanitize_basename(&id);
- let label = format!("L{} · {}", level.max(0), tree_scope);
- Ok(SummaryRow {
- node: GraphNode {
- kind: "summary".into(),
- id,
- label,
- tree_kind: Some(tree_kind),
- tree_scope: Some(tree_scope.clone()),
- tree_id: Some(tree_id),
- level: Some(level.max(0) as u32),
- parent_id,
- child_count: Some(child_count),
- time_range_start_ms: Some(time_range_start_ms),
- time_range_end_ms: Some(time_range_end_ms),
- file_basename: Some(file_basename),
- entity_kind: None,
- },
- tree_scope,
- child_ids,
- })
- })?
- .collect::<rusqlite::Result<Vec<_>>>()
- .context("collect tree-mode summary rows")?;
- Ok(rows)
- })?;
+ let binding = crate::openhuman::memory::binding::for_config(cfg)?;
+ // Resolved once and held across both calls: the forest skeleton and its
+ // bottom edge are two members of the same family, and re-resolving between
+ // them could straddle a rebind.
+ let tree = binding.provider().as_tree();
+ if tree.is_none() {
+ // Read-only, so an empty graph is the honest answer: a driver with no
+ // tree tier holds no forest to walk. Contrast `summary_forest`'s own
+ // `Unsupported`, which is propagated below — a driver that *has* trees
+ // and reports none would be a lie rendered as an empty store.
+ log::debug!(
+ "[memory_tree::read::graph_tree] driver '{}' does not serve Tree; reporting empty",
+ binding.driver_id()
+ );
+ }
+
+ // `MAX_TREE_NODES` is the whole graph's node budget, so it is also the only
+ // honest ceiling to ask the forest for: summaries are emitted before the
+ // document and leaf tails, and anything past the budget could not be
+ // rendered anyway. The driver clamps further to its own cap.
+ let forest = match tree {
+ Some(tree) => tree
+ .summary_forest(MAX_TREE_NODES, None)
+ .await
+ .map_err(|e| format!("summary_forest: {e}"))?,
+ None => Default::default(),
+ };
+ if forest.truncated {
+ // Worth saying out loud: the walk is tree-major, so a truncated forest
+ // is missing whole trees off the tail rather than being thinned evenly.
+ log::debug!(
+ "[memory_tree::read::graph_tree] summary_forest truncated at limit={MAX_TREE_NODES}; whole trees are missing from the tail"
+ );
+ }
+ log::debug!(
+ "[memory_tree::read::graph_tree] summaries={} truncated={}",
+ forest.summaries.len(),
+ forest.truncated
+ );
+
+ // Destructured exhaustively rather than field-picked: a field added to
+ // `TreeSummary` upstream then fails to compile here instead of silently
+ // going unrendered.
+ let summary_rows: Vec<SummaryRow> = forest
+ .summaries
+ .into_iter()
+ .map(|summary| {
+ let TreeSummary {
+ id,
+ tree_id,
+ tree_kind,
+ tree_scope,
+ level,
+ parent_id,
+ child_ids,
+ time_range_start,
+ time_range_end,
+ } = summary;
+ let child_count = child_ids.len() as u32;
+ let file_basename = sanitize_basename(&id);
+ let label = format!("L{level} · {tree_scope}");
+ SummaryRow {
+ node: GraphNode {
+ kind: "summary".into(),
+ id,
+ label,
+ tree_kind: Some(tree_kind),
+ tree_scope: Some(tree_scope.clone()),
+ tree_id: Some(tree_id),
+ level: Some(level),
+ // Already empty-filtered by the driver; the reassignment
+ // below treats an unresolvable parent as a root either way.
+ parent_id,
+ child_count: Some(child_count),
+ time_range_start_ms: Some(time_range_start.timestamp_millis()),
+ time_range_end_ms: Some(time_range_end.timestamp_millis()),
+ file_basename: Some(file_basename),
+ entity_kind: None,
+ },
+ tree_scope,
+ child_ids,
+ }
+ })
+ .collect();
let mut scopes: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
for sr in &summary_rows {
@@ -246,56 +302,50 @@ fn collect_tree_graph(cfg: &Config) -> Result<(Vec<GraphNode>, Vec<GraphEdge>)>
}
let chunk_budget = MAX_TREE_NODES.saturating_sub(nodes.len());
+ // The guard is load-bearing, not cosmetic: the driver clamps a listing
+ // limit into `1..=cap`, so asking for zero leaves would return one.
if chunk_budget > 0 {
- let chunk_nodes = with_connection(cfg, |conn| {
- let mut stmt = conn.prepare(
- "SELECT c.id, c.parent_summary_id, c.content,
- c.time_range_start_ms, c.time_range_end_ms, c.source_id
- FROM mem_tree_chunks c
- ORDER BY c.timestamp_ms DESC
- LIMIT ?1",
- )?;
- let rows = stmt
- .query_map(params![chunk_budget as i64], |row| {
- let id: String = row.get(0)?;
- let parent_id: Option<String> = row.get(1)?;
- let content: String = row.get(2)?;
- let time_range_start_ms: i64 = row.get(3)?;
- let time_range_end_ms: i64 = row.get(4)?;
- let source_id: String = row.get(5)?;
- let label = content
- .lines()
- .next()
- .unwrap_or("")
- .chars()
- .take(72)
- .collect::<String>();
- Ok((
- GraphNode {
- kind: "chunk".into(),
- id,
- label,
- tree_kind: None,
- tree_scope: None,
- tree_id: None,
- level: None,
- parent_id: parent_id.filter(|s| !s.is_empty()),
- child_count: None,
- time_range_start_ms: Some(time_range_start_ms),
- time_range_end_ms: Some(time_range_end_ms),
- file_basename: None,
- entity_kind: None,
- },
- source_id,
- ))
- })?
- .collect::<rusqlite::Result<Vec<_>>>()
- .context("collect tree-mode leaf chunk rows")?;
- Ok(rows)
- })?;
-
- for (chunk, _source_id) in chunk_nodes {
- nodes.push(chunk);
+ let leaves = match tree {
+ Some(tree) => tree
+ .recent_leaves(chunk_budget, None)
+ .await
+ .map_err(|e| format!("recent_leaves: {e}"))?,
+ None => Vec::new(),
+ };
+ log::debug!(
+ "[memory_tree::read::graph_tree] leaves={} budget={chunk_budget}",
+ leaves.len()
+ );
+ for leaf in leaves {
+ let TreeLeaf {
+ chunk_id,
+ parent_summary_id,
+ // Selected by the read this replaced and discarded there too:
+ // a leaf node draws its edge from its summary, not its source.
+ source_id: _,
+ preview,
+ time_range_start,
+ time_range_end,
+ } = leaf;
+ let label = preview.chars().take(CHUNK_LABEL_CHARS).collect::<String>();
+ nodes.push(GraphNode {
+ kind: "chunk".into(),
+ id: chunk_id,
+ label,
+ tree_kind: None,
+ tree_scope: None,
+ tree_id: None,
+ level: None,
+ // The contract's driver already drops the empty string; kept
+ // here so a driver that does not cannot draw an edge to a node
+ // named "".
+ parent_id: parent_summary_id.filter(|s| !s.is_empty()),
+ child_count: None,
+ time_range_start_ms: Some(time_range_start.timestamp_millis()),
+ time_range_end_ms: Some(time_range_end.timestamp_millis()),
+ file_basename: None,
+ entity_kind: None,
+ });
}
}
@@ -345,124 +395,165 @@ pub(super) fn source_id_to_scope(source_id: &str) -> String {
// ── collect_contacts_graph ───────────────────────────────────────────────
-fn collect_contacts_graph(cfg: &Config) -> Result<(Vec<GraphNode>, Vec<GraphEdge>)> {
+async fn collect_contacts_graph(cfg: &Config) -> Result<(Vec<GraphNode>, Vec<GraphEdge>), String> {
const MAX_CHUNK_NODES: usize = 1500;
const MAX_EDGES: usize = 4000;
-
- with_connection(cfg, |conn| {
- let mut chunk_stmt = conn.prepare(
- "SELECT c.id, c.timestamp_ms, c.content
- FROM mem_tree_chunks c
- WHERE c.id IN (
- SELECT DISTINCT node_id
- FROM mem_tree_entity_index
- WHERE entity_kind = 'person'
- )
- ORDER BY c.timestamp_ms DESC
- LIMIT ?1",
- )?;
- let chunks: Vec<(String, i64, String)> = chunk_stmt
- .query_map(params![MAX_CHUNK_NODES as i64], |row| {
- Ok((
- row.get::<_, String>(0)?,
- row.get::<_, i64>(1)?,
- row.get::<_, String>(2)?,
- ))
- })?
- .collect::<rusqlite::Result<_>>()
- .context("collect contacts-mode chunk rows")?;
-
- let chunk_ids: Vec<String> = chunks.iter().map(|(id, _, _)| id.clone()).collect();
-
- let edges: Vec<(String, String, String)> = if chunk_ids.is_empty() {
- Vec::new()
- } else {
- let placeholders = std::iter::repeat_n("?", chunk_ids.len())
- .collect::<Vec<_>>()
- .join(",");
- let sql = format!(
- "SELECT entity_id, node_id, surface
- FROM mem_tree_entity_index
- WHERE entity_kind = 'person'
- AND node_kind = 'leaf'
- AND node_id IN ({placeholders})
- ORDER BY timestamp_ms DESC
- LIMIT ?"
+ const PERSON_KIND: &str = "person";
+
+ let binding = crate::openhuman::memory::binding::for_config(cfg)?;
+
+ // `entity_kinds` alone, and that is a deliberate choice rather than the
+ // only one available. `entity_ids` is a *second, independent* `EXISTS`
+ // clause, so setting both would ask for a chunk holding one of the listed
+ // entities **and** one entity of a listed kind — two index rows that need
+ // not be the same observation. The question here is simply "does this
+ // chunk mention a person", which is this predicate on its own.
+ let query = ChunkQuery {
+ entity_kinds: vec![PERSON_KIND.to_string()],
+ limit: Some(MAX_CHUNK_NODES),
+ // `exclude_dropped` stays at its `false` default: the read this
+ // replaces had no lifecycle filter. It is moot in practice — a dropped
+ // chunk has its entity rows cleared, so it cannot match the predicate
+ // above — but "moot" is not a reason to change what is asked for.
+ ..Default::default()
+ };
+ let chunks = match binding.provider().as_chunks() {
+ Some(chunks) => chunks
+ .list_chunks(&query, None)
+ .await
+ .map_err(|e| format!("list_chunks: {e}"))?,
+ None => {
+ log::debug!(
+ "[memory_tree::read::graph_contacts] driver '{}' does not serve Chunks; reporting empty",
+ binding.driver_id()
);
- let mut bind: Vec<rusqlite::types::Value> = chunk_ids
- .iter()
- .map(|s| rusqlite::types::Value::Text(s.clone()))
- .collect();
- bind.push(rusqlite::types::Value::Integer(MAX_EDGES as i64));
- let mut mention_stmt = conn.prepare(&sql)?;
- let rows = mention_stmt
- .query_map(rusqlite::params_from_iter(bind), |row| {
- Ok((
- row.get::<_, String>(0)?,
- row.get::<_, String>(1)?,
- row.get::<_, String>(2)?,
- ))
- })?
- .collect::<rusqlite::Result<Vec<_>>>()
- .context("collect contacts-mode mentions")?;
- rows
- };
+ Vec::new()
+ }
+ };
+ let chunk_ids: Vec<String> = chunks.iter().map(|chunk| chunk.id.clone()).collect();
+
+ // One batched call for every edge, not one per chunk: at `MAX_CHUNK_NODES`
+ // the per-chunk shape is 1 500 round trips over a bus to read one index,
+ // which is the fan-out the batch amendment exists to kill.
+ //
+ // The empty case short-circuits rather than sending an empty list. Nothing
+ // in the contract promises what an empty batch selects, and the sibling
+ // rule for `ChunkQuery`'s plural predicates is that empty means
+ // *unfiltered* — a computed candidate set that came back empty must skip
+ // the query, never hand it over as "no constraint".
+ let person_kinds = [PERSON_KIND.to_string()];
+ let occurrences = if chunk_ids.is_empty() {
+ Vec::new()
+ } else {
+ match binding.provider().as_entities() {
+ Some(entities) => entities
+ .chunk_entities(&chunk_ids, Some(&person_kinds[..]))
+ .await
+ .map_err(|e| format!("chunk_entities: {e}"))?,
+ None => {
+ log::debug!(
+ "[memory_tree::read::graph_contacts] driver '{}' does not serve Entities; reporting no edges",
+ binding.driver_id()
+ );
+ Vec::new()
+ }
+ }
+ };
+ log::debug!(
+ "[memory_tree::read::graph_contacts] chunks={} occurrences={}",
+ chunk_ids.len(),
+ occurrences.len()
+ );
- let mut edges_out: Vec<GraphEdge> = Vec::with_capacity(edges.len());
- let mut contacts: std::collections::HashMap<String, String> =
- std::collections::HashMap::new();
- for (entity_id, node_id, surface) in edges {
+ // The result is FLAT and every row names its own chunk, so it is grouped by
+ // `row.chunk_id` and never indexed by position against the ids sent: a
+ // chunk the extractor has not reached contributes no row at all, and one
+ // chunk contributes a row per distinct `(entity, surface)`.
+ let mut by_chunk: std::collections::HashMap<String, Vec<(String, String)>> =
+ std::collections::HashMap::new();
+ for row in occurrences {
+ by_chunk
+ .entry(row.chunk_id)
+ .or_default()
+ .push((row.occurrence.entity_id, row.occurrence.surface));
+ }
+
+ // Walked in the order the listing returned — newest chunk first — so the
+ // `MAX_EDGES` cut keeps the most recent mentions, which is what the
+ // `ORDER BY timestamp_ms DESC LIMIT` this replaces did. That equivalence is
+ // exact rather than approximate: an index row is stamped with its own
+ // chunk's timestamp, so ordering by chunk recency *is* ordering by mention
+ // time. `chunk_entities` itself sorts by chunk id, which would otherwise
+ // have made the cut arbitrary.
+ let mut edges_out: Vec<GraphEdge> = Vec::new();
+ let mut contacts: std::collections::HashMap<String, String> = std::collections::HashMap::new();
+ 'walk: for chunk in &chunks {
+ let Some(rows) = by_chunk.remove(&chunk.id) else {
+ continue;
+ };
+ for (entity_id, surface) in rows {
+ if edges_out.len() >= MAX_EDGES {
+ log::debug!(
+ "[memory_tree::read::graph_contacts] edge budget {MAX_EDGES} reached; older mentions dropped"
+ );
+ break 'walk;
+ }
contacts.entry(entity_id.clone()).or_insert(surface);
edges_out.push(GraphEdge {
- from: node_id,
+ from: chunk.id.clone(),
to: entity_id,
});
}
+ }
- let mut nodes: Vec<GraphNode> = Vec::with_capacity(chunks.len() + contacts.len());
- for (id, ts, preview) in chunks {
- let label = preview
- .lines()
- .next()
- .unwrap_or("")
- .chars()
- .take(72)
- .collect::<String>();
- nodes.push(GraphNode {
- kind: "chunk".into(),
- id,
- label,
- tree_kind: None,
- tree_scope: None,
- tree_id: None,
- level: None,
- parent_id: None,
- child_count: None,
- time_range_start_ms: Some(ts),
- time_range_end_ms: Some(ts),
- file_basename: None,
- entity_kind: None,
- });
- }
- for (entity_id, surface) in contacts {
- nodes.push(GraphNode {
- kind: "contact".into(),
- id: entity_id,
- label: surface,
- tree_kind: None,
- tree_scope: None,
- tree_id: None,
- level: None,
- parent_id: None,
- child_count: None,
- time_range_start_ms: None,
- time_range_end_ms: None,
- file_basename: None,
- entity_kind: Some("person".into()),
- });
- }
- Ok((nodes, edges_out))
- })
+ let mut nodes: Vec<GraphNode> = Vec::with_capacity(chunks.len() + contacts.len());
+ for chunk in chunks {
+ // The same `content` column the read this replaces selected, so the
+ // label is byte-identical: `MemoryChunks` hands back the stored body,
+ // or its ≤500-char preview for a chunk whose body went to the vault.
+ let label = chunk
+ .content
+ .lines()
+ .next()
+ .unwrap_or("")
+ .chars()
+ .take(CHUNK_LABEL_CHARS)
+ .collect::<String>();
+ let ts = chunk.metadata.timestamp.timestamp_millis();
+ nodes.push(GraphNode {
+ kind: "chunk".into(),
+ id: chunk.id,
+ label,
+ tree_kind: None,
+ tree_scope: None,
+ tree_id: None,
+ level: None,
+ parent_id: None,
+ child_count: None,
+ time_range_start_ms: Some(ts),
+ time_range_end_ms: Some(ts),
+ file_basename: None,
+ entity_kind: None,
+ });
+ }
+ for (entity_id, surface) in contacts {
+ nodes.push(GraphNode {
+ kind: "contact".into(),
+ id: entity_id,
+ label: surface,
+ tree_kind: None,
+ tree_scope: None,
+ tree_id: None,
+ level: None,
+ parent_id: None,
+ child_count: None,
+ time_range_start_ms: None,
+ time_range_end_ms: None,
+ file_basename: None,
+ entity_kind: Some(PERSON_KIND.into()),
+ });
+ }
+ Ok((nodes, edges_out))
}
pub fn sanitize_basename(id: &str) -> String {
diff --git a/src/openhuman/memory/read_rpc/vault.rs b/src/openhuman/memory/read_rpc/vault.rs
index eeb4703f05..10ed1c8c37 100644
--- a/src/openhuman/memory/read_rpc/vault.rs
+++ b/src/openhuman/memory/read_rpc/vault.rs
@@ -1,8 +1,21 @@
+//! Vault RPCs: is the memory content root reachable, writable, and known to
+//! Obsidian?
+//!
+//! Both handlers are filesystem probes, so both keep their
+//! [`tokio::task::spawn_blocking`] hop — unlike the driver reads elsewhere in
+//! [`super`], where the hop went away because the driver owns whether its own
+//! reads block. `std::fs` does not, on this thread.
+//!
+//! The registration probe itself is [`crate::openhuman::memory::obsidian_registry`],
+//! a host module. It used to be `tinymemory_core::store::content::obsidian_registry`;
+//! its module docs record why deep-linking policy for a third-party desktop app
+//! is this host's and not the memory engine's (#5560).
+
use anyhow::Result;
use crate::openhuman::config::Config;
+use crate::openhuman::memory::obsidian_registry;
use crate::rpc::RpcOutcome;
-use tinymemory_core::store::content::obsidian_registry;
use super::types::{ObsidianVaultStatusResponse, VaultHealthCheckResponse};
diff --git a/src/openhuman/memory/read_rpc_tests.rs b/src/openhuman/memory/read_rpc_tests.rs
index 3481488951..8120cb9ae6 100644
--- a/src/openhuman/memory/read_rpc_tests.rs
+++ b/src/openhuman/memory/read_rpc_tests.rs
@@ -139,6 +139,12 @@ fn insert_raw_chunk(
#[tokio::test]
async fn list_chunks_returns_seeded_chunk() {
let (_tmp, cfg) = test_config();
+ // These handlers read through the bound driver now that the raw SQL is
+ // gone, so the test has to bind one. TinyCortex is the engine the
+ // loadable module wraps, so this exercises the same code production
+ // reaches over the bus — and unlike the module it is not a process
+ // singleton, which is what lets these run in one test binary.
+ crate::openhuman::memory::test_support::install_tinycortex_for_test(&cfg);
seed_chat_chunk(&cfg, "slack:#eng", "hello @alice phoenix migration").await;
let resp = list_chunks_rpc(&cfg, ChunkFilter::default())
.await
@@ -151,6 +157,12 @@ async fn list_chunks_returns_seeded_chunk() {
#[tokio::test]
async fn list_chunks_filters_by_source_id() {
let (_tmp, cfg) = test_config();
+ // These handlers read through the bound driver now that the raw SQL is
+ // gone, so the test has to bind one. TinyCortex is the engine the
+ // loadable module wraps, so this exercises the same code production
+ // reaches over the bus — and unlike the module it is not a process
+ // singleton, which is what lets these run in one test binary.
+ crate::openhuman::memory::test_support::install_tinycortex_for_test(&cfg);
seed_chat_chunk(&cfg, "slack:#a", "alpha").await;
seed_chat_chunk(&cfg, "slack:#b", "beta").await;
let only_a = list_chunks_rpc(
@@ -170,6 +182,12 @@ async fn list_chunks_filters_by_source_id() {
#[tokio::test]
async fn list_chunks_query_substring_works() {
let (_tmp, cfg) = test_config();
+ // These handlers read through the bound driver now that the raw SQL is
+ // gone, so the test has to bind one. TinyCortex is the engine the
+ // loadable module wraps, so this exercises the same code production
+ // reaches over the bus — and unlike the module it is not a process
+ // singleton, which is what lets these run in one test binary.
+ crate::openhuman::memory::test_support::install_tinycortex_for_test(&cfg);
seed_chat_chunk(&cfg, "slack:#eng", "phoenix migration ships friday").await;
seed_chat_chunk(&cfg, "slack:#eng", "different unrelated text").await;
let resp = list_chunks_rpc(
@@ -193,6 +211,12 @@ async fn list_chunks_query_substring_works() {
#[tokio::test]
async fn list_chunks_filters_by_source_kind_and_applies_limit_offset() {
let (_tmp, cfg) = test_config();
+ // These handlers read through the bound driver now that the raw SQL is
+ // gone, so the test has to bind one. TinyCortex is the engine the
+ // loadable module wraps, so this exercises the same code production
+ // reaches over the bus — and unlike the module it is not a process
+ // singleton, which is what lets these run in one test binary.
+ crate::openhuman::memory::test_support::install_tinycortex_for_test(&cfg);
seed_chat_chunk(&cfg, "slack:#a", "first chat").await;
seed_chat_chunk(&cfg, "slack:#b", "second chat").await;
@@ -216,6 +240,12 @@ async fn list_chunks_filters_by_source_kind_and_applies_limit_offset() {
#[tokio::test]
async fn list_chunks_filters_by_entity_id_and_time_window() {
let (_tmp, cfg) = test_config();
+ // These handlers read through the bound driver now that the raw SQL is
+ // gone, so the test has to bind one. TinyCortex is the engine the
+ // loadable module wraps, so this exercises the same code production
+ // reaches over the bus — and unlike the module it is not a process
+ // singleton, which is what lets these run in one test binary.
+ crate::openhuman::memory::test_support::install_tinycortex_for_test(&cfg);
seed_chat_chunk(&cfg, "slack:#eng", "[email protected] handles phoenix").await;
seed_chat_chunk(&cfg, "slack:#eng", "[email protected] handles atlas").await;
@@ -269,6 +299,12 @@ async fn list_chunks_filters_by_entity_id_and_time_window() {
#[tokio::test]
async fn list_chunks_ignores_empty_filter_lists_and_blank_query() {
let (_tmp, cfg) = test_config();
+ // These handlers read through the bound driver now that the raw SQL is
+ // gone, so the test has to bind one. TinyCortex is the engine the
+ // loadable module wraps, so this exercises the same code production
+ // reaches over the bus — and unlike the module it is not a process
+ // singleton, which is what lets these run in one test binary.
+ crate::openhuman::memory::test_support::install_tinycortex_for_test(&cfg);
seed_chat_chunk(&cfg, "slack:#a", "alpha").await;
seed_chat_chunk(&cfg, "slack:#b", "beta").await;
@@ -294,6 +330,12 @@ async fn list_chunks_ignores_empty_filter_lists_and_blank_query() {
#[tokio::test]
async fn list_chunks_normalizes_invalid_tags_negative_tokens_and_empty_content() {
let (_tmp, cfg) = test_config();
+ // These handlers read through the bound driver now that the raw SQL is
+ // gone, so the test has to bind one. TinyCortex is the engine the
+ // loadable module wraps, so this exercises the same code production
+ // reaches over the bus — and unlike the module it is not a process
+ // singleton, which is what lets these run in one test binary.
+ crate::openhuman::memory::test_support::install_tinycortex_for_test(&cfg);
insert_raw_chunk(
&cfg,
"raw-empty",
@@ -324,6 +366,12 @@ async fn list_chunks_normalizes_invalid_tags_negative_tokens_and_empty_content()
#[tokio::test]
async fn list_sources_aggregates() {
let (_tmp, cfg) = test_config();
+ // These handlers read through the bound driver now that the raw SQL is
+ // gone, so the test has to bind one. TinyCortex is the engine the
+ // loadable module wraps, so this exercises the same code production
+ // reaches over the bus — and unlike the module it is not a process
+ // singleton, which is what lets these run in one test binary.
+ crate::openhuman::memory::test_support::install_tinycortex_for_test(&cfg);
seed_chat_chunk(&cfg, "slack:#a", "x").await;
seed_chat_chunk(&cfg, "slack:#a", "y").await;
seed_chat_chunk(&cfg, "slack:#b", "z").await;
@@ -343,6 +391,12 @@ async fn list_sources_aggregates() {
#[tokio::test]
async fn list_sources_formats_email_threads_with_trimmed_user_hint() {
let (_tmp, cfg) = test_config();
+ // These handlers read through the bound driver now that the raw SQL is
+ // gone, so the test has to bind one. TinyCortex is the engine the
+ // loadable module wraps, so this exercises the same code production
+ // reaches over the bus — and unlike the module it is not a process
+ // singleton, which is what lets these run in one test binary.
+ crate::openhuman::memory::test_support::install_tinycortex_for_test(&cfg);
insert_raw_chunk(
&cfg,
"email-thread",
@@ -368,6 +422,9 @@ async fn list_sources_formats_email_threads_with_trimmed_user_hint() {
#[tokio::test]
async fn entity_index_for_returns_extracted_entities() {
let (_tmp, cfg) = test_config();
+ // The entity index is read through `MemoryEntities::chunk_entities`, so the
+ // handler needs a driver that serves that family — the null fallback does not.
+ crate::openhuman::memory::test_support::install_tinycortex_for_test(&cfg);
seed_chat_chunk(&cfg, "slack:#eng", "[email protected] owns it").await;
// Find the chunk we just seeded.
let chunks = list_chunks_rpc(&cfg, ChunkFilter::default())
@@ -386,6 +443,9 @@ async fn entity_index_for_returns_extracted_entities() {
#[tokio::test]
async fn chunks_for_entity_returns_leaf_chunk_ids_only() {
let (_tmp, cfg) = test_config();
+ // `MemoryEntities::entity_chunk_ids` answers this one; the null fallback
+ // serves no entity tier and would report an empty list.
+ crate::openhuman::memory::test_support::install_tinycortex_for_test(&cfg);
seed_chat_chunk(&cfg, "slack:#eng", "[email protected] owns it").await;
let chunk_id = list_chunks_rpc(&cfg, ChunkFilter::default())
.await
@@ -405,6 +465,9 @@ async fn chunks_for_entity_returns_leaf_chunk_ids_only() {
#[tokio::test]
async fn top_entities_returns_most_frequent() {
let (_tmp, cfg) = test_config();
+ // `MemoryEntities::top_entities` answers this one; the null fallback
+ // serves no entity tier and would report an empty ranking.
+ crate::openhuman::memory::test_support::install_tinycortex_for_test(&cfg);
seed_chat_chunk(&cfg, "slack:#a", "[email protected] x").await;
seed_chat_chunk(&cfg, "slack:#b", "[email protected] y").await;
seed_chat_chunk(&cfg, "slack:#c", "[email protected] z").await;
@@ -420,6 +483,9 @@ async fn top_entities_returns_most_frequent() {
#[tokio::test]
async fn delete_chunk_removes_chunk_and_dependent_rows() {
let (_tmp, cfg) = test_config();
+ // The delete goes through `MemorySourceSink::forget_matching`, which the null
+ // fallback does not serve — and this handler refuses rather than degrades.
+ crate::openhuman::memory::test_support::install_tinycortex_for_test(&cfg);
seed_chat_chunk(&cfg, "slack:#eng", "[email protected] owns it").await;
let chunks = list_chunks_rpc(&cfg, ChunkFilter::default())
.await
@@ -440,6 +506,9 @@ async fn delete_chunk_removes_chunk_and_dependent_rows() {
#[tokio::test]
async fn delete_missing_chunk_is_idempotent() {
let (_tmp, cfg) = test_config();
+ // Idempotence is the driver's, so this needs a driver: without one the handler
+ // refuses outright, which is a different answer from "that chunk was not there".
+ crate::openhuman::memory::test_support::install_tinycortex_for_test(&cfg);
let resp = delete_chunk_rpc(&cfg, "does-not-exist".into())
.await
.unwrap()
@@ -448,9 +517,77 @@ async fn delete_missing_chunk_is_idempotent() {
assert_eq!(resp.score_rows_removed, 0);
}
+/// The one named behaviour delta of the move onto `MemoryEntities::top_entities`,
+/// pinned in both directions.
+///
+/// The member validates `kind` and answers `MemoryError::Invalid` for one it does
+/// not recognise. The SQL this handler used to run compared the string against the
+/// stored column, so an unknown kind matched nothing and the caller got an empty
+/// list. A migration must not turn that quiet empty result into a user-visible
+/// error, so the variant is mapped back — and the second half of this test is what
+/// keeps the map-back narrow rather than a blanket swallow.
+#[tokio::test]
+async fn top_entities_reports_empty_for_an_unknown_kind() {
+ let (_tmp, cfg) = test_config();
+ crate::openhuman::memory::test_support::install_tinycortex_for_test(&cfg);
+ seed_chat_chunk(&cfg, "slack:#eng", "[email protected] owns it").await;
+
+ let unknown = top_entities_rpc(&cfg, Some("not-a-kind".into()), 10)
+ .await
+ .expect("an unrecognised kind is an empty ranking, not an error")
+ .value;
+ assert!(unknown.is_empty(), "got: {unknown:?}");
+
+ let known = top_entities_rpc(&cfg, Some("email".into()), 10)
+ .await
+ .unwrap()
+ .value;
+ assert!(
+ !known.is_empty(),
+ "a recognised kind must still rank rows; the Invalid map-back is narrow"
+ );
+}
+
+/// `ForgetOutcome` reports `chunks_removed` and `trees_cleaned` and nothing about
+/// the per-chunk side rows, so `DeleteChunkResponse`'s two counts are observed
+/// before the delete rather than read off the outcome. This pins that they are
+/// still real numbers — dropping them to zero would read as "there was nothing to
+/// clean up", which is a different claim from "nobody counted".
+#[tokio::test]
+async fn delete_chunk_still_reports_its_side_row_counts() {
+ let (_tmp, cfg) = test_config();
+ crate::openhuman::memory::test_support::install_tinycortex_for_test(&cfg);
+ seed_chat_chunk(&cfg, "slack:#eng", "[email protected] owns it").await;
+ let id = list_chunks_rpc(&cfg, ChunkFilter::default())
+ .await
+ .unwrap()
+ .value
+ .chunks[0]
+ .id
+ .clone();
+
+ let indexed = entity_index_for_rpc(&cfg, id.clone()).await.unwrap().value;
+ let indexed_rows: u32 = indexed.iter().map(|entity| entity.count).sum();
+ assert!(
+ indexed_rows > 0,
+ "expected entity-index rows, got: {indexed:?}"
+ );
+
+ let resp = delete_chunk_rpc(&cfg, id).await.unwrap().value;
+ assert!(resp.deleted);
+ assert_eq!(resp.entity_index_rows_removed, indexed_rows);
+ assert_eq!(resp.score_rows_removed, 1, "ingest writes one score row");
+}
+
#[tokio::test]
async fn chunk_score_returns_breakdown_after_ingest() {
let (_tmp, cfg) = test_config();
+ // These handlers read through the bound driver now that the raw SQL is
+ // gone, so the test has to bind one. TinyCortex is the engine the
+ // loadable module wraps, so this exercises the same code production
+ // reaches over the bus — and unlike the module it is not a process
+ // singleton, which is what lets these run in one test binary.
+ crate::openhuman::memory::test_support::install_tinycortex_for_test(&cfg);
seed_chat_chunk(
&cfg,
"slack:#eng",
@@ -473,6 +610,12 @@ async fn chunk_score_returns_breakdown_after_ingest() {
#[tokio::test]
async fn search_returns_matching_chunks() {
let (_tmp, cfg) = test_config();
+ // These handlers read through the bound driver now that the raw SQL is
+ // gone, so the test has to bind one. TinyCortex is the engine the
+ // loadable module wraps, so this exercises the same code production
+ // reaches over the bus — and unlike the module it is not a process
+ // singleton, which is what lets these run in one test binary.
+ crate::openhuman::memory::test_support::install_tinycortex_for_test(&cfg);
seed_chat_chunk(&cfg, "slack:#eng", "phoenix migration scheduled friday").await;
seed_chat_chunk(&cfg, "slack:#eng", "different unrelated text").await;
let hits = search_rpc(&cfg, "phoenix".into(), 10).await.unwrap().value;
@@ -713,11 +856,18 @@ fn parse_source_kind_str_accepts_known_values_only() {
assert_eq!(parse_source_kind_str("unknown"), None);
}
-#[test]
-fn clear_composio_sync_state_removes_only_target_namespace() {
- let tmp = TempDir::new().unwrap();
- let _memory = UnifiedMemory::new(tmp.path(), Arc::new(NoopEmbedding), None).unwrap();
- let db_path = tmp.path().join("memory").join("memory.db");
+/// The namespace clear is routed through the bound driver's key/value tier
+/// (`kv_list` + `kv_delete`) instead of a `rusqlite::Connection` this handler
+/// opened on a path it built itself. The claim is unchanged and is what the
+/// raw read-back below still checks: only the composio namespace goes.
+#[tokio::test]
+async fn clear_composio_sync_state_removes_only_target_namespace() {
+ let (_tmp, cfg) = test_config();
+ // Created up front so the raw fixture rows below have a schema to land in;
+ // the driver installed further down opens this same store.
+ let _memory =
+ UnifiedMemory::new(cfg.workspace_dir.as_path(), Arc::new(NoopEmbedding), None).unwrap();
+ let db_path = cfg.workspace_dir.join("memory").join("memory.db");
let conn = rusqlite::Connection::open(&db_path).unwrap();
conn.execute(
@@ -734,7 +884,8 @@ fn clear_composio_sync_state_removes_only_target_namespace() {
.unwrap();
drop(conn);
- let removed = clear_composio_sync_state(&db_path).unwrap();
+ crate::openhuman::memory::test_support::install_tinycortex_for_test(&cfg);
+ let removed = clear_composio_sync_state(&cfg).await.unwrap();
assert_eq!(removed, 1);
let conn = rusqlite::Connection::open(&db_path).unwrap();
@@ -805,6 +956,9 @@ fn insert_chunk_with_parent(
#[tokio::test]
async fn tree_graph_includes_leaf_chunks_linked_to_their_summary() {
let (_tmp, cfg) = test_config();
+ // The forest and its leaves are read through `MemoryTree`, so the graph
+ // needs a driver that serves that family — the null fallback does not.
+ crate::openhuman::memory::test_support::install_tinycortex_for_test(&cfg);
insert_tree_summary(&cfg, "tree-1", "slack:#eng", "summary:1:L1-aaa", 1);
insert_chunk_with_parent(
&cfg,
@@ -855,6 +1009,7 @@ async fn tree_graph_includes_leaf_chunks_linked_to_their_summary() {
#[tokio::test]
async fn tree_graph_keeps_summaries_first_then_chunks() {
let (_tmp, cfg) = test_config();
+ crate::openhuman::memory::test_support::install_tinycortex_for_test(&cfg);
insert_tree_summary(&cfg, "tree-1", "slack:#eng", "summary:1:L1-aaa", 1);
insert_chunk_with_parent(
&cfg,
@@ -872,6 +1027,173 @@ async fn tree_graph_keeps_summaries_first_then_chunks() {
assert!(resp.nodes.iter().any(|n| n.kind == "chunk"));
}
+/// Insert one `mem_tree_entity_index` row.
+///
+/// Seeded directly because the `person` kind only ever comes from the LLM
+/// extractor, which these tests deliberately do not run — the mechanical
+/// extractor emits `email`/`url`/`handle`/`hashtag` and nothing else.
+fn insert_entity_row(
+ cfg: &Config,
+ entity_id: &str,
+ node_id: &str,
+ entity_kind: &str,
+ surface: &str,
+ timestamp_ms: i64,
+) {
+ with_connection(cfg, |conn| {
+ conn.execute(
+ "INSERT OR REPLACE INTO mem_tree_entity_index (
+ entity_id, node_id, node_kind, entity_kind, surface,
+ score, timestamp_ms, tree_id, is_user
+ ) VALUES (?1, ?2, 'leaf', ?3, ?4, 1.0, ?5, NULL, 0)",
+ params![entity_id, node_id, entity_kind, surface, timestamp_ms],
+ )?;
+ Ok(())
+ })
+ .unwrap();
+}
+
+/// Contacts mode selects chunks by entity *kind* and labels them from one
+/// batched entity read.
+///
+/// The two chunks carry a different number of person rows on purpose. A reader
+/// that indexed the flat `chunk_entities` result by position against the ids it
+/// sent — the trap the contract's docs call out — would attribute the second
+/// chunk's row to the first and still produce two edges, so an asymmetric
+/// fixture is what makes the grouping observable.
+#[tokio::test]
+async fn contacts_graph_selects_person_chunks_and_groups_edges_by_chunk() {
+ let (_tmp, cfg) = test_config();
+ crate::openhuman::memory::test_support::install_tinycortex_for_test(&cfg);
+
+ insert_chunk_with_parent(
+ &cfg,
+ "chunk-a",
+ None,
+ 1_700_000_000_002,
+ "alice and bob met",
+ );
+ insert_chunk_with_parent(&cfg, "chunk-b", None, 1_700_000_000_001, "carol shipped it");
+ // No person row: this chunk must not reach the graph at all.
+ insert_chunk_with_parent(&cfg, "chunk-c", None, 1_700_000_000_000, "no people here");
+
+ insert_entity_row(
+ &cfg,
+ "person:alice",
+ "chunk-a",
+ "person",
+ "Alice",
+ 1_700_000_000_002,
+ );
+ insert_entity_row(
+ &cfg,
+ "person:bob",
+ "chunk-a",
+ "person",
+ "Bob",
+ 1_700_000_000_002,
+ );
+ insert_entity_row(
+ &cfg,
+ "person:carol",
+ "chunk-b",
+ "person",
+ "Carol",
+ 1_700_000_000_001,
+ );
+ // A non-person row on a person-bearing chunk: it must not become an edge.
+ insert_entity_row(
+ &cfg,
+ "topic:shipping",
+ "chunk-b",
+ "topic",
+ "shipping",
+ 1_700_000_000_001,
+ );
+
+ let resp = graph_export_rpc(&cfg, GraphMode::Contacts)
+ .await
+ .unwrap()
+ .value;
+
+ let chunk_ids: Vec<&str> = resp
+ .nodes
+ .iter()
+ .filter(|n| n.kind == "chunk")
+ .map(|n| n.id.as_str())
+ .collect();
+ assert_eq!(
+ chunk_ids,
+ vec!["chunk-a", "chunk-b"],
+ "only person-bearing chunks, newest first"
+ );
+
+ let mut edges: Vec<(&str, &str)> = resp
+ .edges
+ .iter()
+ .map(|e| (e.from.as_str(), e.to.as_str()))
+ .collect();
+ edges.sort_unstable();
+ assert_eq!(
+ edges,
+ vec![
+ ("chunk-a", "person:alice"),
+ ("chunk-a", "person:bob"),
+ ("chunk-b", "person:carol"),
+ ],
+ "every edge names the chunk its row came from, and the topic row is filtered out"
+ );
+
+ let contacts: std::collections::BTreeSet<(&str, &str)> = resp
+ .nodes
+ .iter()
+ .filter(|n| n.kind == "contact")
+ .map(|n| (n.id.as_str(), n.label.as_str()))
+ .collect();
+ let expected: std::collections::BTreeSet<(&str, &str)> = [
+ ("person:alice", "Alice"),
+ ("person:bob", "Bob"),
+ ("person:carol", "Carol"),
+ ]
+ .into_iter()
+ .collect();
+ assert_eq!(contacts, expected);
+ assert!(resp
+ .nodes
+ .iter()
+ .filter(|n| n.kind == "contact")
+ .all(|n| n.entity_kind.as_deref() == Some("person")));
+}
+
+/// An empty candidate set must short-circuit, not become an unfiltered read.
+///
+/// The failure this pins is quiet: an empty predicate means *unfiltered* on
+/// this seam, so a batch read handed the empty id list could answer with every
+/// row in the store and the graph would fill with contacts for chunks it never
+/// selected.
+#[tokio::test]
+async fn contacts_graph_with_no_person_chunks_is_empty() {
+ let (_tmp, cfg) = test_config();
+ crate::openhuman::memory::test_support::install_tinycortex_for_test(&cfg);
+ insert_chunk_with_parent(&cfg, "chunk-a", None, 1_700_000_000_000, "no people here");
+ insert_entity_row(
+ &cfg,
+ "topic:shipping",
+ "chunk-a",
+ "topic",
+ "shipping",
+ 1_700_000_000_000,
+ );
+
+ let resp = graph_export_rpc(&cfg, GraphMode::Contacts)
+ .await
+ .unwrap()
+ .value;
+
+ assert!(resp.nodes.is_empty(), "nodes: {:?}", resp.nodes);
+ assert!(resp.edges.is_empty(), "edges: {:?}", resp.edges);
+}
+
#[tokio::test]
async fn obsidian_status_registered_when_override_config_lists_content_root() {
let (_tmp, cfg) = test_config();
@@ -1061,6 +1383,10 @@ async fn wipe_all_clears_ingest_gate() {
use tinymemory_core::store::chunks::store as chunk_store;
let (_tmp, cfg) = test_config();
+ // `wipe_all` asks the bound driver to purge; without one bound the workspace
+ // resolves to the placeholder, which serves no Maintenance family and
+ // refuses rather than reporting a wipe it did not do.
+ crate::openhuman::memory::test_support::install_tinycortex_for_test(&cfg);
let gate_key = "notion:conn-1:page-abc@1700000000000";
// Claim the gate exactly as a document ingest does.
diff --git a/src/openhuman/memory/sync/composio/mod.rs b/src/openhuman/memory/sync/composio/mod.rs
index 8533e0289e..7f59225867 100644
--- a/src/openhuman/memory/sync/composio/mod.rs
+++ b/src/openhuman/memory/sync/composio/mod.rs
@@ -4,6 +4,29 @@
//! JSON-RPC surface — handlers and controller schemas name OpenHuman's
//! `RpcOutcome` and `ControllerSchema`, which the engine crate cannot see.
//! The glob re-export keeps every historical `memory::sync::composio::…` path resolving.
+//!
+//! # This shim outlives its usefulness the day the in-process engine goes
+//!
+//! The glob below is what makes `integrations::composio::start_periodic_sync`
+//! resolve, and therefore what lets `core/runtime/services.rs` start an engine
+//! sync loop inside the host process. openhuman#5560 deletes the second,
+//! in-process engine and leaves the loaded TinyMemory module as the only one;
+//! after that this re-export names a crate the host no longer has a live engine
+//! for, and the periodic loop it exposes has nothing to run against.
+//!
+//! It must not be deleted first, and the ordering is the point. Composio sync
+//! degrades **quietly** — an unwired `ComposioHost` makes `is_available` read
+//! `false` and a sync run report zero connections, which nobody can tell apart
+//! from a user with none. So a half-removed loop looks like a working one for
+//! as long as it takes someone to notice their mail stopped being indexed.
+//!
+//! The full ordered list lives next to the call site it protects, in
+//! `core/runtime/services.rs`'s `start_bootstrap_jobs`. In short: the host
+//! serves `ComposioHost` on the module bus (done — `modules/memory_host.rs`),
+//! the module installs a bus-backed seam for it and starts the loop itself, a
+//! `tinymemory` release carries both and `modules::registry` is re-pinned to
+//! its digest — **then** this file and that call go, together with the
+//! in-process engine.
pub use tinymemory_core::sync::composio::*;
diff --git a/src/openhuman/memory/tools/raw_store/raw_chunks.rs b/src/openhuman/memory/tools/raw_store/raw_chunks.rs
index f4c0491aca..75341929fc 100644
--- a/src/openhuman/memory/tools/raw_store/raw_chunks.rs
+++ b/src/openhuman/memory/tools/raw_store/raw_chunks.rs
@@ -100,6 +100,10 @@ impl Tool for MemoryStoreRawChunksTool {
limit: parsed.limit,
offset: None,
exclude_dropped: false,
+ // The filtered-listing predicates this caller does not use. An
+ // empty predicate is unfiltered, so the defaults leave the query
+ // exactly as narrow as the fields above already make it.
+ ..Default::default()
};
let guard = active_memory_guard()
.await
diff --git a/src/openhuman/memory/tools/search/vector_search.rs b/src/openhuman/memory/tools/search/vector_search.rs
index 65f756d608..23770074b5 100644
--- a/src/openhuman/memory/tools/search/vector_search.rs
+++ b/src/openhuman/memory/tools/search/vector_search.rs
@@ -171,6 +171,10 @@ impl Tool for MemoryVectorSearchTool {
limit: Some(1000),
offset: None,
exclude_dropped: false,
+ // The filtered-listing predicates this caller does not use. An
+ // empty predicate is unfiltered, so the defaults leave the query
+ // exactly as narrow as the fields above already make it.
+ ..Default::default()
};
let chunks = chunk_reader
diff --git a/src/openhuman/memory/tree/tree/rpc.rs b/src/openhuman/memory/tree/tree/rpc.rs
index 36391d93e6..a3ab0dd5b4 100644
--- a/src/openhuman/memory/tree/tree/rpc.rs
+++ b/src/openhuman/memory/tree/tree/rpc.rs
@@ -239,6 +239,12 @@ fn chat_items(source_id: &str, owner: &str, tags: &[String], batch: ChatBatch) -
path_scope: None,
author: Some(message.author),
channel_label: Some(channel_label.clone()),
+ // Mail-only fields; this source is not mail, and the contract
+ // documents empty/absent as the same statement as "not mail".
+ to: Vec::new(),
+ cc: Vec::new(),
+ subject: None,
+ list_unsubscribe: None,
platform: Some(platform.clone()),
})
.collect()
@@ -268,6 +274,12 @@ fn document_item(source_id: &str, owner: &str, tags: &[String], doc: DocumentInp
path_scope: None,
author: None,
channel_label: None,
+ // Mail-only fields; this source is not mail, and the contract
+ // documents empty/absent as the same statement as "not mail".
+ to: Vec::new(),
+ cc: Vec::new(),
+ subject: None,
+ list_unsubscribe: None,
platform: None,
}
}
@@ -488,6 +500,10 @@ pub async fn list_chunks_rpc(
limit: req.limit,
offset: None,
exclude_dropped: false,
+ // The filtered-listing predicates this request does not carry. An empty
+ // predicate is unfiltered, so the defaults leave the query exactly as
+ // narrow as the fields above already make it.
+ ..Default::default()
};
// No `spawn_blocking`: the driver owns whether its own reads block, and the
diff --git a/src/openhuman/modules/memory.rs b/src/openhuman/modules/memory.rs
index 05f04435e5..d61e228c1a 100644
--- a/src/openhuman/modules/memory.rs
+++ b/src/openhuman/modules/memory.rs
@@ -148,23 +148,24 @@ use tinymemory_api::error::MemoryError;
use tinymemory_api::goals::GoalsDoc;
use tinymemory_api::health::MemoryHealth;
use tinymemory_api::provider::types::{
- DiffReport, EntityHit, ExportPage, ExportRecord, FlushOutcome, ImportOutcome, IngestItem,
- IngestOutcome, MaintenanceReport, QueueFailure, QueueStats, ResetOutcome, SnapshotRef,
+ ChunkEntityOccurrence, DiffReport, EntityHit, EntityOccurrence, ExportPage, ExportRecord,
+ FlushOutcome, ForgetOutcome, ForgetSelector, ImportOutcome, IngestItem, IngestOutcome,
+ MaintenanceReport, PurgeOutcome, QueueFailure, QueueStats, ResetOutcome, SnapshotRef,
SourceItem, SourceScope, StoreStats,
};
use tinymemory_api::provider::{
- AddressBookSeedOutcome, ChunkDetail, ChunkEmbedding, ChunkQuery, ConversationSegment,
- CoverWindowQuery, EntityMatch, EpisodicEvent, EpisodicTurn, FacetType, FastRetrieveQuery,
- MemoryChunks, MemoryCore, MemoryDiff, MemoryDocuments, MemoryEntities, MemoryEpisodic,
- MemoryGoals, MemoryGraph, MemoryIngest, MemoryMaintenance, MemoryPeople, MemoryPortability,
- MemoryProfile, MemoryProvider, MemoryRecall, MemoryRetrieval, MemorySourceSink,
- MemoryToolMemory, MemoryTree, PersonHandle, PersonInteraction, PersonRecord, PersonScore,
- ProfileFacet, RankedPerson, ResolvedPerson, RetrievalHit, RetrievalResponse,
- SourceRetrievalQuery, UserState,
+ AddressBookSeedOutcome, ChunkDetail, ChunkEmbedding, ChunkListRow, ChunkQuery,
+ ConversationSegment, CoverWindowQuery, EntityMatch, EpisodicEvent, EpisodicTurn, FacetType,
+ FastRetrieveQuery, MemoryChunks, MemoryCore, MemoryDiff, MemoryDocuments, MemoryEntities,
+ MemoryEpisodic, MemoryGoals, MemoryGraph, MemoryIngest, MemoryMaintenance, MemoryPeople,
+ MemoryPortability, MemoryProfile, MemoryProvider, MemoryRecall, MemoryRetrieval,
+ MemorySourceSink, MemoryToolMemory, MemoryTree, PersonHandle, PersonInteraction, PersonRecord,
+ PersonScore, ProfileFacet, RankedPerson, ResolvedPerson, RetrievalHit, RetrievalResponse,
+ SourceRetrievalQuery, SourceTotal, UserState,
};
use tinymemory_api::recall::OwnedRecallOpts;
use tinymemory_api::tool_memory::ToolMemoryRule;
-use tinymemory_api::tree::{IngestRequest, QueryResult, TreeStatus};
+use tinymemory_api::tree::{IngestRequest, QueryResult, SummaryForest, TreeLeaf, TreeStatus};
use tinymemory_api::types::{
GraphRelationRecord, MemoryCategory, MemoryEntry, MemoryKvRecord, MemoryTaint,
NamespaceDocumentInput, NamespaceMemoryHit, NamespaceRetrievalContext, NamespaceSummary,
@@ -769,6 +770,20 @@ impl MemoryTree for ModuleMemoryProvider {
async fn cascade(&self, namespace: &str) -> Result<TreeStatus, MemoryError> {
module_call!(self, "cascade", "Cascade", (namespace,))
}
+ async fn summary_forest(
+ &self,
+ limit: usize,
+ scope: Option<&SourceScope>,
+ ) -> Result<SummaryForest, MemoryError> {
+ module_call!(self, "summary_forest", "SummaryForest", (limit, scope))
+ }
+ async fn recent_leaves(
+ &self,
+ limit: usize,
+ scope: Option<&SourceScope>,
+ ) -> Result<Vec<TreeLeaf>, MemoryError> {
+ module_call!(self, "recent_leaves", "RecentLeaves", (limit, scope))
+ }
}
#[async_trait]
@@ -811,6 +826,32 @@ impl MemoryEntities for ModuleMemoryProvider {
(namespace, entity_ids.to_vec())
)
}
+ async fn top_entities(
+ &self,
+ kind: Option<&str>,
+ limit: usize,
+ ) -> Result<Vec<EntityOccurrence>, MemoryError> {
+ module_call!(self, "top_entities", "TopEntities", (kind, limit))
+ }
+ async fn chunk_entities(
+ &self,
+ chunk_ids: &[String],
+ kinds: Option<&[String]>,
+ ) -> Result<Vec<ChunkEntityOccurrence>, MemoryError> {
+ module_call!(self, "chunk_entities", "ChunkEntities", (chunk_ids, kinds))
+ }
+ async fn entity_chunk_ids(
+ &self,
+ entity_id: &str,
+ limit: usize,
+ ) -> Result<Vec<String>, MemoryError> {
+ module_call!(
+ self,
+ "entity_chunk_ids",
+ "EntityChunkIds",
+ (entity_id, limit)
+ )
+ }
}
#[async_trait]
@@ -963,6 +1004,12 @@ impl MemorySourceSink for ModuleMemoryProvider {
async fn forget_source(&self, source_id: &str) -> Result<u64, MemoryError> {
module_call!(self, "forget_source", "ForgetSource", (source_id,))
}
+ async fn forget_matching(
+ &self,
+ selector: &ForgetSelector,
+ ) -> Result<ForgetOutcome, MemoryError> {
+ module_call!(self, "forget_matching", "ForgetMatching", (selector,))
+ }
}
#[async_trait]
@@ -1000,6 +1047,9 @@ impl MemoryMaintenance for ModuleMemoryProvider {
async fn reset_derived_index(&self) -> Result<ResetOutcome, MemoryError> {
module_call!(self, "reset_derived_index", "ResetDerivedIndex", ())
}
+ async fn purge_all(&self) -> Result<PurgeOutcome, MemoryError> {
+ module_call!(self, "purge_all", "PurgeAll", ())
+ }
}
#[async_trait]
@@ -1177,6 +1227,32 @@ impl MemoryChunks for ModuleMemoryProvider {
(chunk_ids, model_signature)
)
}
+ async fn count_chunks(
+ &self,
+ query: &ChunkQuery,
+ scope: Option<&SourceScope>,
+ ) -> Result<u64, MemoryError> {
+ module_call!(self, "count_chunks", "CountChunks", (query, scope))
+ }
+ async fn list_chunk_details(
+ &self,
+ query: &ChunkQuery,
+ scope: Option<&SourceScope>,
+ ) -> Result<Vec<ChunkListRow>, MemoryError> {
+ module_call!(
+ self,
+ "list_chunk_details",
+ "ListChunkDetails",
+ (query, scope)
+ )
+ }
+ async fn source_totals(
+ &self,
+ limit: usize,
+ scope: Option<&SourceScope>,
+ ) -> Result<Vec<SourceTotal>, MemoryError> {
+ module_call!(self, "source_totals", "SourceTotals", (limit, scope))
+ }
}
#[async_trait]
diff --git a/src/openhuman/modules/memory_host.rs b/src/openhuman/modules/memory_host.rs
index f402d06d0e..49692d0b04 100644
--- a/src/openhuman/modules/memory_host.rs
+++ b/src/openhuman/modules/memory_host.rs
@@ -1,16 +1,51 @@
//! Host-owned callbacks used by the separately compiled TinyMemory module.
+//!
+//! This file is the bus-served twin of `memory/host_impls.rs`. That file
+//! installs the engine's seam traits as process globals, which only works while
+//! the engine is compiled into this binary; these interfaces serve the same
+//! capabilities to an engine that is *not*, over the module's connection.
+//!
+//! # Which seams are here, and why only these
+//!
+//! A seam earns an interface here when the capability genuinely belongs to the
+//! host and the module cannot answer it from anything it was handed at load
+//! time. Embedding and chat qualify because the credential, the provider
+//! routing and the cost accounting all live here (see `tinymemory-module`'s
+//! `embedding.rs` for the long form of that argument). Event publishing, error
+//! reporting and spaCy qualify because their destinations are host subsystems.
+//! Composio qualifies for the same reason one size up: the client is a *host
+//! agent tool*, mode dispatch reads host config, and the OAuth session it
+//! depends on is refreshed by host code.
+//!
+//! Seams that are *not* here are not omissions to be filled in later. The
+//! module answers `ConfigLoader` from the `ModuleConfig` it was handed —
+//! proxying it would mean asking the host to re-read a config the module
+//! already has, with two answers free to disagree — and the scheduler gate and
+//! the shutdown sequencer cannot cross a bus at all: one is synchronous, one
+//! hands back a `tokio::sync::Notify`, and one takes a Rust closure.
+//!
+//! # The interfaces are the whole contract
+//!
+//! Nothing here is discoverable by the module except through the well-known
+//! name it proxies. A module built against a newer contract that asks for an
+//! interface an older host never served gets a name-resolution failure, which
+//! is why the module side reports that failure by name rather than degrading to
+//! a plausible-looking empty answer.
use crate::core::bus::BUS;
use crate::openhuman::config::Config;
use std::sync::Arc;
use tinyagents::harness::model::{ModelRequest, ModelResponse};
use tinybus::ObjectPath;
+use tinymemory_api::host::composio::{ComposioConnection, ComposioExecuteResponse};
use tinymemory_api::host::{MemoryEvent, SpacyResponse};
const EMBEDDING_NAME: &str = "ai.tinyhumans.tinymemory.EmbeddingHost";
const EMBEDDING_PATH: &str = "/ai/tinyhumans/tinymemory/EmbeddingHost";
const CHAT_NAME: &str = "ai.tinyhumans.tinymemory.ChatHost";
const CHAT_PATH: &str = "/ai/tinyhumans/tinymemory/ChatHost";
+const COMPOSIO_NAME: &str = "ai.tinyhumans.tinymemory.ComposioHost";
+const COMPOSIO_PATH: &str = "/ai/tinyhumans/tinymemory/ComposioHost";
const RUNTIME_NAME: &str = "ai.tinyhumans.tinymemory.RuntimeHost";
const RUNTIME_PATH: &str = "/ai/tinyhumans/tinymemory/RuntimeHost";
@@ -64,6 +99,181 @@ impl ChatCallbacks {
}
}
+/// Composio, as the engine's sync pipelines need it.
+///
+/// # Why the `&Config` argument is not on the wire
+///
+/// `ComposioHost`'s four trait methods each take a `&tinymemory_core::Config`.
+/// That argument does not appear on any method below, and it must not: in
+/// module mode it is the *engine's* config, built from the `ModuleConfig` the
+/// module was loaded with, and it is not this process's `Config`. Sending it
+/// would mean the host resolving a Composio client against a config the host
+/// did not write and cannot trust to be current. `ChatHost` made the same call
+/// — `Complete` takes a role and a request, and nothing else — and the module
+/// side of that proxy simply drops the ambient context on the floor.
+///
+/// So the config each method here works from is the host's own, and the only
+/// question is *which* host config.
+///
+/// # Why every method re-reads the config from disk
+///
+/// The install-time snapshot is the wrong answer, and quietly so. Composio's
+/// state changes underneath a running process on the two events that matter
+/// most: an OAuth completion in the browser, and a `set_api_key` RPC. Both
+/// write config and credentials and neither restarts anything. An
+/// `IsAvailable` answered from a snapshot taken at launch reports "not signed
+/// in" for the rest of the session to a user who signed in a minute ago, and
+/// the sync layer treats that as *skip silently* — the exact
+/// looks-empty-rather-than-broken failure the seam exists to prevent.
+///
+/// `memory/host_impls.rs` gets liveness a cheaper way: its async methods
+/// re-read from disk, and its two synchronous probes recover the caller's
+/// config, which the engine's own loops keep fresh. With no caller config to
+/// recover, a fresh read is what "current as of the call" costs here. It is
+/// bounded — the probes sit on periodic sync paths, a handful of reads per
+/// tick, next to network calls that dominate them.
+///
+/// The two probes cannot fail, so a config that will not load falls back to the
+/// install-time snapshot rather than inventing a "no" — an unreadable config
+/// file is not evidence that the user disconnected Composio.
+#[derive(Clone)]
+struct ComposioCallbacks(Arc<Config>);
+
+#[tinybus::interface(name = "ai.tinyhumans.tinymemory.ComposioHost")]
+impl ComposioCallbacks {
+ async fn list_connections(&self) -> tinybus::Result<Vec<ComposioConnection>> {
+ use crate::openhuman::integrations::composio::client::{
+ create_composio_client, direct_list_connections, ComposioClientKind,
+ };
+ let config = self.live_config().await.map_err(method_error)?;
+ let response = match create_composio_client(&config)
+ .map_err(|e| method_error(format!("create_composio_client: {e:#}")))?
+ {
+ ComposioClientKind::Backend(client) => client
+ .list_connections()
+ .await
+ .map_err(|e| method_error(format!("list_connections (backend): {e:#}")))?,
+ ComposioClientKind::Direct(direct) => {
+ direct_list_connections(&direct).await.map_err(|e| {
+ // [#1166 / Sentry TAURI-RUST-X9] The v3 `/connected_accounts`
+ // 401 shape has to reach the observability classifier, and it
+ // only fires on a message carrying the `[composio-direct]`
+ // anchor. Report it here rather than relying on the caller:
+ // by the time this reaches the module it is wrapped in a
+ // `MethodFailed` envelope, and the classifier that keys on
+ // the anchor runs in this process, not that one.
+ let rendered = format!("[composio-direct] list_connections (direct): {e:#}");
+ crate::openhuman::integrations::composio::ops::report_composio_op_error(
+ "list_connections",
+ &rendered,
+ );
+ method_error(rendered)
+ })?
+ }
+ };
+ Ok(response.connections)
+ }
+
+ /// Run one Composio tool.
+ ///
+ /// `entity_id` and `connection_id` travel even though backend mode ignores
+ /// both: which mode is in force is resolved on this side, at call time, and
+ /// a caller that omitted them would silently lose the connection pin the
+ /// moment a user switched to direct mode.
+ async fn execute(
+ &self,
+ tool: String,
+ arguments: Option<serde_json::Value>,
+ entity_id: String,
+ connection_id: Option<String>,
+ ) -> tinybus::Result<ComposioExecuteResponse> {
+ use crate::openhuman::integrations::composio::client::{
+ create_composio_client, direct_execute, ComposioClientKind,
+ };
+ let config = self.live_config().await.map_err(method_error)?;
+ match create_composio_client(&config).map_err(|e| method_error(format!("{e:#}")))? {
+ ComposioClientKind::Backend(client) => client
+ .execute_tool(&tool, arguments)
+ .await
+ .map_err(|e| method_error(format!("{e:#}"))),
+ ComposioClientKind::Direct(direct) => direct_execute(
+ &direct,
+ &tool,
+ arguments,
+ &entity_id,
+ connection_id.as_deref(),
+ )
+ .await
+ .map_err(|e| method_error(format!("{e:#}"))),
+ }
+ }
+
+ /// The direct-mode Composio API key, or `None` when direct mode is unset.
+ ///
+ /// This is the one method here that hands a credential to the module, and
+ /// it is worth being explicit about: `EmbeddingHost` deliberately refuses
+ /// to, and keeps the key on this side of `Embed` instead. The difference is
+ /// that the engine's `composio_config` builds its *own* HTTP client from
+ /// this key, so a `None` here is not a degraded answer the caller routes
+ /// around — it is a hard "direct-mode sync cannot run".
+ ///
+ /// Narrowing that would mean moving the direct-mode sync client behind an
+ /// `Execute`-shaped method, which is a change to the engine's contract and
+ /// not something to smuggle in through its host half.
+ async fn api_key(&self) -> tinybus::Result<Option<String>> {
+ let config = self.live_config_or_installed().await;
+ Ok(
+ crate::openhuman::security::credentials::get_composio_api_key(config.as_ref())
+ .ok()
+ .flatten(),
+ )
+ }
+
+ /// Whether *some* viable Composio client resolves right now.
+ ///
+ /// Deliberately the factory probe rather than a session-token check: a
+ /// direct-mode user has no backend session, and testing for one would read
+ /// as signed-out and skip them (#1710).
+ async fn is_available(&self) -> tinybus::Result<bool> {
+ use crate::openhuman::integrations::composio::client::create_composio_client;
+ let config = self.live_config_or_installed().await;
+ Ok(create_composio_client(config.as_ref()).is_ok())
+ }
+}
+
+impl ComposioCallbacks {
+ /// The host config as it is on disk right now.
+ ///
+ /// Addressed by the install-time config's paths rather than by the ambient
+ /// ones, so a workspace-scoped process re-reads its own config and not the
+ /// default profile's.
+ async fn live_config(&self) -> Result<Config, String> {
+ crate::openhuman::config::rpc::reload_config_from_paths(
+ &self.0.config_path,
+ &self.0.workspace_dir,
+ )
+ .await
+ }
+
+ /// [`Self::live_config`], falling back to the install-time snapshot.
+ ///
+ /// For the two probes only. They return a bare `Option`/`bool` with no room
+ /// for "could not tell", and answering "no" on a transient read failure
+ /// would stop a sync run that was working a minute ago.
+ async fn live_config_or_installed(&self) -> Arc<Config> {
+ match self.live_config().await {
+ Ok(config) => Arc::new(config),
+ Err(error) => {
+ log::debug!(
+ "[memory:composio-host] config re-read failed, answering the probe from the \
+ install-time snapshot: {error}"
+ );
+ Arc::clone(&self.0)
+ }
+ }
+ }
+}
+
#[derive(Clone)]
struct RuntimeCallbacks(Arc<Config>);
@@ -120,30 +330,53 @@ pub(super) async fn install(
) -> tinybus::Result<()> {
static INSTALLED: tokio::sync::OnceCell<()> = tokio::sync::OnceCell::const_new();
INSTALLED
- .get_or_try_init(|| async move {
- connection
- .serve_at(
- ObjectPath::new(EMBEDDING_PATH)?,
- EmbeddingCallbacks(Arc::clone(&config)),
- )
- .await?;
- connection
- .serve_at(
- ObjectPath::new(CHAT_PATH)?,
- ChatCallbacks(Arc::clone(&config)),
- )
- .await?;
- connection
- .serve_at(ObjectPath::new(RUNTIME_PATH)?, RuntimeCallbacks(config))
- .await?;
- connection.request_name(EMBEDDING_NAME).await?;
- connection.request_name(CHAT_NAME).await?;
- connection.request_name(RUNTIME_NAME).await
- })
+ .get_or_try_init(|| serve_interfaces(connection, config))
.await
.map(|_| ())
}
+/// Serve every host interface on `connection` and claim its well-known name.
+///
+/// Split out of [`install`] so the served set can be exercised against a
+/// throwaway broker. The latch there is process-wide by necessity — the module
+/// runtime is a singleton — and a test that went through it would either be the
+/// only one that could ever run or would silently assert against whichever
+/// connection happened to win the race.
+///
+/// The claim order is serve-then-name for every interface: a name that resolves
+/// before its object is exported would let a module land a call on a path that
+/// is not there yet.
+async fn serve_interfaces(
+ connection: &tinybus::Connection,
+ config: Arc<Config>,
+) -> tinybus::Result<()> {
+ connection
+ .serve_at(
+ ObjectPath::new(EMBEDDING_PATH)?,
+ EmbeddingCallbacks(Arc::clone(&config)),
+ )
+ .await?;
+ connection
+ .serve_at(
+ ObjectPath::new(CHAT_PATH)?,
+ ChatCallbacks(Arc::clone(&config)),
+ )
+ .await?;
+ connection
+ .serve_at(
+ ObjectPath::new(COMPOSIO_PATH)?,
+ ComposioCallbacks(Arc::clone(&config)),
+ )
+ .await?;
+ connection
+ .serve_at(ObjectPath::new(RUNTIME_PATH)?, RuntimeCallbacks(config))
+ .await?;
+ connection.request_name(EMBEDDING_NAME).await?;
+ connection.request_name(CHAT_NAME).await?;
+ connection.request_name(COMPOSIO_NAME).await?;
+ connection.request_name(RUNTIME_NAME).await
+}
+
fn into_domain_event(event: MemoryEvent) -> Option<crate::core::events::DomainEvent> {
use crate::core::events::DomainEvent;
Some(match event {
@@ -290,3 +523,7 @@ fn into_domain_event(event: MemoryEvent) -> Option<crate::core::events::DomainEv
}
})
}
+
+#[cfg(test)]
+#[path = "memory_host_tests.rs"]
+mod tests;
diff --git a/src/openhuman/modules/memory_host_tests.rs b/src/openhuman/modules/memory_host_tests.rs
new file mode 100644
index 0000000000..9b457ad975
--- /dev/null
+++ b/src/openhuman/modules/memory_host_tests.rs
@@ -0,0 +1,258 @@
+//! Tests for the host half of the TinyMemory module's callbacks.
+//!
+//! Two things are worth asserting here and a third is not.
+//!
+//! Worth asserting: that the interfaces are actually *reachable* — served at
+//! the path the module proxies, under the name the module resolves — and that
+//! each Composio method reaches the host's own Composio client rather than
+//! answering from something local. Both are failures that no compiler catches:
+//! a name that is never claimed surfaces as `NameHasNoOwner` at the first sync
+//! tick, in the field, and a method that quietly answers "nothing here" is the
+//! looks-empty-rather-than-broken outcome this whole seam exists to prevent.
+//!
+//! Not worth asserting: what Composio replies. Every method below is driven
+//! against a workspace with no session and no stored key, so the interesting
+//! answer is always the *shape* of the failure — which factory it came from —
+//! never a connection list. The round trips themselves are covered where they
+//! can be honest, in `tinymemory`'s own module E2E against a real module.
+
+use super::{
+ serve_interfaces, ComposioCallbacks, CHAT_NAME, CHAT_PATH, COMPOSIO_NAME, COMPOSIO_PATH,
+ EMBEDDING_NAME, EMBEDDING_PATH, RUNTIME_NAME, RUNTIME_PATH,
+};
+use crate::openhuman::config::Config;
+use crate::openhuman::integrations::composio::client::create_composio_client;
+use serde_json::json;
+use std::path::Path;
+use std::sync::Arc;
+use tinybus::broker::Broker;
+use tinybus::service::Interface;
+use tinybus::transport::memory::MemoryBus;
+use tinybus::{Connection, MemberName};
+
+/// The host error name every method in this file fails under.
+const HOST_ERROR: &str = "ai.tinyhumans.tinymemory.Error.Host";
+
+/// A config scoped to `dir`, so nothing here reads the developer's own install.
+///
+/// Both paths matter and for different reasons: `config_path` is what the
+/// callbacks re-read on every call, and it is also what the credential store
+/// resolves against (its *parent*, not the workspace). Setting only one gives a
+/// test that looks hermetic and answers from the real keychain.
+fn scoped_config(dir: &Path) -> Arc<Config> {
+ let mut config = Config::default();
+ config.workspace_dir = dir.join("workspace");
+ config.config_path = dir.join("config.toml");
+ Arc::new(config)
+}
+
+/// Dispatch `member` against `callbacks` the way the connection would.
+async fn call(
+ callbacks: &ComposioCallbacks,
+ member: &str,
+ args: serde_json::Value,
+) -> tinybus::Result<serde_json::Value> {
+ callbacks
+ .call(&MemberName::new(member).expect("member name"), args)
+ .await
+}
+
+#[test]
+fn the_composio_interface_is_the_engines_four_contract_methods_in_order() {
+ // The engine's `ComposioHost` trait has exactly these four, and the module
+ // side proxies each by name. A method renamed on this side is not a compile
+ // error over there — it is a `MethodFailed: UnknownMethod` the first time a
+ // sync run reaches for it.
+ let dir = tempfile::tempdir().expect("tempdir");
+ let callbacks = ComposioCallbacks(scoped_config(dir.path()));
+
+ assert_eq!(callbacks.name().as_str(), COMPOSIO_NAME);
+ let members: Vec<String> = callbacks
+ .members()
+ .iter()
+ .map(|member| member.as_str().to_string())
+ .collect();
+ assert_eq!(
+ members,
+ ["ListConnections", "Execute", "ApiKey", "IsAvailable"]
+ );
+}
+
+#[tokio::test]
+async fn install_claims_composios_name_beside_the_other_three() {
+ // `install` is latched process-wide, so this drives the function it
+ // delegates to. The assertion is name resolution, not behaviour: a bogus
+ // member reaching `UnknownMethod` proves the name is owned *and* an object
+ // is exported at that path, which together are the whole precondition for
+ // the module ever getting a real answer.
+ let dir = tempfile::tempdir().expect("tempdir");
+ let bus = MemoryBus::new();
+ Broker::new().spawn(bus.clone());
+
+ let service = Connection::connect(bus.connect().await.expect("service transport"))
+ .await
+ .expect("service connection");
+ serve_interfaces(&service, scoped_config(dir.path()))
+ .await
+ .expect("serve every host interface");
+
+ let client = Connection::connect(bus.connect().await.expect("client transport"))
+ .await
+ .expect("client connection");
+
+ for (name, path) in [
+ (EMBEDDING_NAME, EMBEDDING_PATH),
+ (CHAT_NAME, CHAT_PATH),
+ (COMPOSIO_NAME, COMPOSIO_PATH),
+ (RUNTIME_NAME, RUNTIME_PATH),
+ ] {
+ let proxy = client.proxy(name, path, name).expect("proxy");
+ let error = proxy
+ .call::<serde_json::Value>("NoSuchMember", ())
+ .await
+ .expect_err("a member that does not exist cannot succeed");
+ assert_eq!(
+ error.wire_name(),
+ tinybus::Error::UNKNOWN_METHOD,
+ "{name} is not served at {path}: {error}"
+ );
+ }
+}
+
+#[tokio::test]
+async fn composio_answers_over_the_bus_and_not_only_in_process() {
+ // The narrow version of the test above: one real method, end to end,
+ // through a proxy addressed exactly as the module addresses it.
+ let dir = tempfile::tempdir().expect("tempdir");
+ let config = scoped_config(dir.path());
+ let bus = MemoryBus::new();
+ Broker::new().spawn(bus.clone());
+
+ let service = Connection::connect(bus.connect().await.expect("service transport"))
+ .await
+ .expect("service connection");
+ serve_interfaces(&service, Arc::clone(&config))
+ .await
+ .expect("serve every host interface");
+
+ let client = Connection::connect(bus.connect().await.expect("client transport"))
+ .await
+ .expect("client connection");
+ let proxy = client
+ .proxy(COMPOSIO_NAME, COMPOSIO_PATH, COMPOSIO_NAME)
+ .expect("proxy");
+
+ let available: bool = proxy.call("IsAvailable", ()).await.expect("IsAvailable");
+ assert_eq!(available, create_composio_client(config.as_ref()).is_ok());
+}
+
+#[tokio::test]
+async fn is_available_is_the_hosts_own_factory_probe() {
+ // Equality with the factory rather than a hardcoded `false`: the point is
+ // delegation, and a literal would pass just as well against a stub that
+ // always said no — which is exactly the bug worth catching.
+ let dir = tempfile::tempdir().expect("tempdir");
+ let config = scoped_config(dir.path());
+ let callbacks = ComposioCallbacks(Arc::clone(&config));
+
+ let answer = call(&callbacks, "IsAvailable", json!([]))
+ .await
+ .expect("IsAvailable never fails");
+ assert_eq!(
+ answer,
+ json!(create_composio_client(config.as_ref()).is_ok())
+ );
+}
+
+#[tokio::test]
+async fn api_key_is_the_hosts_own_credential_store() {
+ let dir = tempfile::tempdir().expect("tempdir");
+ let config = scoped_config(dir.path());
+ let callbacks = ComposioCallbacks(Arc::clone(&config));
+
+ let expected = crate::openhuman::security::credentials::get_composio_api_key(config.as_ref())
+ .ok()
+ .flatten();
+ let answer = call(&callbacks, "ApiKey", json!([]))
+ .await
+ .expect("ApiKey never fails");
+ assert_eq!(answer, json!(expected));
+}
+
+#[tokio::test]
+async fn a_probe_survives_a_config_it_cannot_read() {
+ // The two probes have nowhere to put "could not tell", and answering "no"
+ // on an unreadable config would stop a sync run that was working a minute
+ // ago. Point them at a path that cannot resolve and they must still answer.
+ let callbacks = ComposioCallbacks(scoped_config(Path::new("/nonexistent/openhuman")));
+
+ assert!(call(&callbacks, "IsAvailable", json!([])).await.is_ok());
+ assert!(call(&callbacks, "ApiKey", json!([])).await.is_ok());
+}
+
+#[tokio::test]
+async fn list_connections_stops_inside_the_hosts_composio_stack() {
+ // With no session and no key there is no client to build, so the failure
+ // must be the host's — carrying this file's error name, not a bus-level
+ // one. A stub that answered `Ok(vec![])` would be indistinguishable from a
+ // user with no connections, which is the failure mode being designed out.
+ let dir = tempfile::tempdir().expect("tempdir");
+ let callbacks = ComposioCallbacks(scoped_config(dir.path()));
+
+ let error = call(&callbacks, "ListConnections", json!([]))
+ .await
+ .expect_err("no client can be built for an empty workspace");
+ assert_eq!(error.wire_name(), HOST_ERROR);
+}
+
+#[tokio::test]
+async fn execute_takes_its_four_arguments_in_the_order_the_engine_sends_them() {
+ // Positional arguments are the part of a bus contract that has no compiler
+ // behind it. The pair below is the cheapest honest check: the right arity
+ // gets far enough to fail inside the host, the wrong one is refused before
+ // any host code runs.
+ let dir = tempfile::tempdir().expect("tempdir");
+ let callbacks = ComposioCallbacks(scoped_config(dir.path()));
+
+ let error = call(
+ &callbacks,
+ "Execute",
+ json!(["GMAIL_FETCH_EMAILS", { "max_results": 1 }, "default", null]),
+ )
+ .await
+ .expect_err("no client can be built for an empty workspace");
+ assert_eq!(
+ error.wire_name(),
+ HOST_ERROR,
+ "a well-formed call must reach the host's client factory: {error}"
+ );
+
+ let error = call(&callbacks, "Execute", json!([]))
+ .await
+ .expect_err("Execute takes four arguments");
+ assert_eq!(
+ error.wire_name(),
+ "ai.tinyhumans.tinybus.Error.BadArguments",
+ "a malformed call must be refused at decode, not inside the host: {error}"
+ );
+}
+
+#[tokio::test]
+async fn execute_forwards_an_absent_connection_pin_as_absent() {
+ // `connection_id` is `Option`, and JSON `null` is how the module spells
+ // "unpinned". Decoding it as a missing argument instead would make every
+ // unpinned execute fail arity rather than run.
+ let dir = tempfile::tempdir().expect("tempdir");
+ let callbacks = ComposioCallbacks(scoped_config(dir.path()));
+
+ for pin in [json!(null), json!("ca_abc123")] {
+ let error = call(
+ &callbacks,
+ "Execute",
+ json!(["GMAIL_FETCH_EMAILS", null, "default", pin]),
+ )
+ .await
+ .expect_err("no client can be built for an empty workspace");
+ assert_eq!(error.wire_name(), HOST_ERROR, "{error}");
+ }
+}
diff --git a/src/openhuman/platform/doctor/README.md b/src/openhuman/platform/doctor/README.md
index 2dd9cf1c39..5383c3a710 100644
--- a/src/openhuman/platform/doctor/README.md
+++ b/src/openhuman/platform/doctor/README.md
@@ -8,7 +8,7 @@ Diagnostic / self-check domain for OpenHuman. Runs a synchronous battery of prob
- Check workspace integrity: directory existence, write probe (create/write/delete a temp probe file), `memory/` dir, `SYSTEM.md` prompt, and best-effort free disk space (warns under 512 MB; uses `df -m` on Unix, PowerShell `Get-PSDrive` on Windows).
- Inspect daemon state file: presence, JSON validity, heartbeat freshness (stale > 30s = error), scheduler component health (stale > 120s), and per-channel component freshness (stale > 300s).
- Probe environment commands: `git --version`, `curl --version`, `$SHELL`, and `$HOME`/`$USERPROFILE`.
-- Probe memory-tree DB: warn on stale `-shm`/`-wal` SQLite side-files or not-yet-created DB; otherwise open the DB and run `SELECT COUNT(*) FROM mem_tree_chunks`.
+- Probe memory-tree DB: warn on stale `-shm`/`-wal` SQLite side-files or not-yet-created DB; otherwise report the chunk count the bound memory driver answered with (`MemoryMaintenance::store_stats`), taken by `ops::memory_chunk_count` before the blocking hop.
- Probe embedding-model health: if provider is `ollama`, do a 3s blocking HTTP GET to `<base_url>/api/tags` and verify the configured model is installed; non-ollama providers report OK without a local probe.
- Probe the Claude Agent SDK: if enabled, run `<binary> --version`.
- Probe provider model availability via `run_models` (currently a stub — see Notes).
@@ -28,7 +28,8 @@ Diagnostic / self-check domain for OpenHuman. Runs a synchronous battery of prob
From `mod.rs` re-exports (`core::*`):
- Types: `Severity` (`Ok`/`Warn`/`Error`), `DiagnosticItem`, `DoctorSummary`, `DoctorReport`, `ModelProbeOutcome`, `ModelProbeEntry`, `ModelProbeSummary`, `ModelProbeReport`.
-- Functions: `run(&Config) -> Result<DoctorReport>` (blocking-only — keep no `.await` inside), `run_models(&Config, use_cache) -> Result<ModelProbeReport>`.
+- Functions: `run(&Config, MemoryChunkCount) -> Result<DoctorReport>` (blocking-only — keep no `.await` inside; async probes are resolved by the caller and passed in), `run_models(&Config, use_cache) -> Result<ModelProbeReport>`.
+- Type alias: `MemoryChunkCount = Result<u64, String>` — the hoisted chunk-count probe.
From `ops` (also re-exported as `doctor::rpc`):
@@ -64,7 +65,8 @@ None of its own (no `store.rs`). It only **reads** existing state owned by other
- `crate::openhuman::config::{Config, rpc}` — reads the live config for all probes; `config_rpc::load_config_with_timeout` in the handlers.
- `crate::openhuman::platform::service::daemon` — `state_file_path` for the daemon heartbeat/component snapshot.
-- `tinymemory_core::store::{chunks::store, factories}` — `with_connection` for the DB probe; `effective_embedding_settings` to resolve the intended embedding provider/model.
+- `crate::openhuman::memory::binding` — resolves the workspace's bound memory driver so `ops::memory_chunk_count` can ask `MemoryMaintenance::store_stats` for the chunk count. The engine crate is no longer named here (#5560).
+- `crate::openhuman::inference::embeddings::effective_embedding_settings` — resolves the intended embedding provider/model.
- `crate::openhuman::inference::{provider, local}` — `provider::list_providers` (model targets) and `local::ollama_base_url` (embedding probe).
- `crate::api::{config, jwt}` — `effective_api_url` fallback resolution and `get_session_token` for sign-in state.
- `crate::core::all::{ControllerFuture, RegisteredController}`, `crate::core::{ControllerSchema, FieldSchema, TypeSchema}` — controller/schema plumbing.
@@ -78,6 +80,8 @@ None of its own (no `store.rs`). It only **reads** existing state owned by other
## Notes / gotchas
- `run()` is **strictly blocking** by contract (file system, sqlite, blocking HTTP). `reqwest::blocking::Client` panics inside a tokio runtime, so `ops::doctor_report` runs the whole thing in `tokio::task::spawn_blocking`. Do not add `.await` inside `core::run`.
+- An async probe therefore arrives as an **argument**, resolved in `ops` before the blocking hop — `MemoryChunkCount` is the first of them. Do not reach for `Handle::block_on` inside `core`: it panics on a current-thread runtime and deadlocks the multi-thread one whose worker it is already occupying.
+- The chunk count comes from the bound driver, and a driver that does not serve `Maintenance` is reported as a **failed probe** rather than as zero. That is the opposite of what the `memory_tree` status RPCs do with a missing family, and deliberately so: a status panel is better off showing an empty store than an error, while the doctor exists to name what is wrong — and "0 chunks" from a driver that cannot count is indistinguishable from a store the user has just watched themselves fill.
- `run_models` / `doctor.models` is effectively a **stub**: it enumerates providers from `inference::provider::list_providers` but marks every entry `Skipped` with message "model catalog refresh removed" (catalog refresh was removed). It never actually probes auth/availability despite the schema description.
- The embedding probe is capped at a 3s timeout to avoid stalling on a slow Ollama daemon; non-ollama providers short-circuit to OK.
- `model_matches` treats `name` vs `name:tag` as a match only when at most one side is tagged; two differently-tagged names are not considered equal.
diff --git a/src/openhuman/platform/doctor/core.rs b/src/openhuman/platform/doctor/core.rs
index a0c38fdf41..9375041213 100644
--- a/src/openhuman/platform/doctor/core.rs
+++ b/src/openhuman/platform/doctor/core.rs
@@ -65,20 +65,38 @@ pub struct DoctorReport {
// ── Public entry point ───────────────────────────────────────────
+/// How many chunks the bound memory driver holds, or why the count could not
+/// be taken.
+///
+/// The one probe [`run`] cannot take for itself. The count comes from
+/// `MemoryMaintenance::store_stats` — driver-neutral, and the reason this
+/// check no longer opens the store's SQLite file directly (#5560) — and that
+/// member is `async`, while [`run`] is blocking by contract. Blocking on it
+/// from inside [`run`] is not an option in either direction: a
+/// `Handle::block_on` panics on a current-thread runtime and deadlocks the
+/// multi-thread one it is already occupying a worker of.
+///
+/// So the caller awaits it and hands the answer down. `Err` carries the
+/// driver's own message and becomes the `Error` item this check has always
+/// pushed when the probe failed.
+pub type MemoryChunkCount = Result<u64, String>;
+
/// Build the full doctor report.
///
/// `ops::doctor_report` runs this in `tokio::task::spawn_blocking` because the
/// checks are synchronous and may touch the file system, sqlite, or local HTTP
/// endpoints. Keep this function blocking-only; add async probes in the caller
-/// or behind their own runtime boundary instead of introducing `.await` here.
-pub fn run(config: &Config) -> Result<DoctorReport> {
+/// or behind their own runtime boundary instead of introducing `.await` here —
+/// `memory_chunks` is the first probe to take that route, and `ops`'
+/// `memory_chunk_count` is the shape to copy for the next one.
+pub fn run(config: &Config, memory_chunks: MemoryChunkCount) -> Result<DoctorReport> {
let mut items: Vec<DiagnosticItem> = Vec::new();
check_config_semantics(config, &mut items);
check_workspace(config, &mut items);
check_daemon_state(config, &mut items);
check_environment(&mut items);
- check_memory_tree_db(config, &mut items);
+ check_memory_tree_db(config, &memory_chunks, &mut items);
check_embedding_model_health(config, &mut items);
check_claude_agent_sdk(config, &mut items);
@@ -786,9 +804,23 @@ fn check_command_available(
///
/// - If the DB directory / file does not exist yet: `Warn` (not yet created).
/// - If a stale `.db-shm` file is present alongside the DB: `Warn`.
-/// - If we can open the DB and run a basic probe query: `Ok`.
-/// - If the probe fails: `Error`.
-fn check_memory_tree_db(config: &Config, items: &mut Vec<DiagnosticItem>) {
+/// - If the driver answered with a chunk count: `Ok`.
+/// - If it did not: `Error`.
+///
+/// The file checks are this function's own — they are `std::fs` calls about a
+/// path, and a driver has nothing to say about them. The count is
+/// `memory_chunks`, taken by the async caller: see [`MemoryChunkCount`] for
+/// why it arrives as an argument rather than being read here.
+///
+/// The two are ordered, not independent: an absent file short-circuits before
+/// the count is consulted at all, exactly as it short-circuited before the
+/// connection was opened. A workspace that has never ingested anything must
+/// keep reading as "not yet created" rather than as a failed probe.
+fn check_memory_tree_db(
+ config: &Config,
+ memory_chunks: &MemoryChunkCount,
+ items: &mut Vec<DiagnosticItem>,
+) {
let cat = "memory_tree_db";
let db_path = config.workspace_dir.join("memory_tree").join("chunks.db");
@@ -824,27 +856,30 @@ fn check_memory_tree_db(config: &Config, items: &mut Vec<DiagnosticItem>) {
return;
}
- // ── Probe connection ─────────────────────────────────────────────
- // Still counts the rows directly, and cannot stop until `run` can await.
- // `MemoryMaintenance::store_stats` answers this exactly — a driver-neutral
- // chunk count — but it is `async`, and this function's own module doc is
- // explicit that `run` stays blocking-only with async probes hoisted into
- // the caller. Hoisting one probe is that restructure, not a side effect of
- // moving a read behind the contract.
- match tinymemory_core::store::chunks::store::with_connection(config, |conn| {
- let n: i64 = conn.query_row("SELECT COUNT(*) FROM mem_tree_chunks", [], |r| r.get(0))?;
- Ok(n)
- }) {
+ // ── Driver probe ────────────────────────────────────────────────
+ // The count used to be a `SELECT COUNT(*) FROM mem_tree_chunks` through
+ // the engine's own connection helper. It is the bound driver's answer now,
+ // which is what lets this check mean something on a workspace whose memory
+ // is not SQLite at all — and what takes the engine crate out of this file.
+ match memory_chunks {
Ok(count) => {
+ log::debug!(
+ "[doctor] check_memory_tree_db: driver reported {count} chunks at {}",
+ db_path.display()
+ );
items.push(DiagnosticItem::ok(
cat,
format!("DB accessible at {} ({count} chunks)", db_path.display()),
));
}
Err(err) => {
+ log::debug!(
+ "[doctor] check_memory_tree_db: chunk-count probe failed at {}: {err}",
+ db_path.display()
+ );
items.push(DiagnosticItem::error(
cat,
- format!("DB probe failed at {}: {err:#}", db_path.display()),
+ format!("DB probe failed at {}: {err}", db_path.display()),
));
}
}
diff --git a/src/openhuman/platform/doctor/core_tests.rs b/src/openhuman/platform/doctor/core_tests.rs
index c1688d052e..7a4ef2bcd2 100644
--- a/src/openhuman/platform/doctor/core_tests.rs
+++ b/src/openhuman/platform/doctor/core_tests.rs
@@ -85,7 +85,10 @@ fn check_memory_tree_db_warns_when_db_missing() {
let cfg = test_config_in(&tmp);
let mut items = vec![];
- check_memory_tree_db(&cfg, &mut items);
+ // A count is supplied and must go unread: an absent file short-circuits
+ // before the driver's answer is consulted, so a workspace that has never
+ // ingested anything reads as "not yet created" and not as a failed probe.
+ check_memory_tree_db(&cfg, &Ok(7), &mut items);
assert_eq!(items.len(), 1, "expected exactly one diagnostic item");
assert_eq!(items[0].severity, Severity::Warn);
@@ -96,19 +99,23 @@ fn check_memory_tree_db_warns_when_db_missing() {
);
}
-/// After `with_connection` has successfully initialised the DB, the probe
-/// should push an `Ok` item.
+/// With the DB file present and the driver's chunk count in hand, the probe
+/// should push an `Ok` item carrying that count.
+///
+/// The file is created directly rather than by opening a store: the count is
+/// the async caller's now (`ops::memory_chunk_count`), so this check only ever
+/// asks the filesystem whether the path exists.
#[test]
fn check_memory_tree_db_ok_when_accessible() {
let tmp = TempDir::new().expect("tempdir");
let cfg = test_config_in(&tmp);
- // Trigger DB creation.
- tinymemory_core::store::chunks::store::with_connection(&cfg, |_conn| Ok(()))
- .expect("DB init must succeed");
+ let db_dir = cfg.workspace_dir.join("memory_tree");
+ std::fs::create_dir_all(&db_dir).expect("create memory_tree dir");
+ std::fs::write(db_dir.join("chunks.db"), b"").expect("create chunks.db");
let mut items = vec![];
- check_memory_tree_db(&cfg, &mut items);
+ check_memory_tree_db(&cfg, &Ok(42), &mut items);
// There may be a Warn about the SHM file on some platforms; there must
// be at least one Ok item about the DB being accessible.
@@ -125,4 +132,50 @@ fn check_memory_tree_db_ok_when_accessible() {
"unexpected ok message: {}",
ok_items[0].message
);
+ assert!(
+ ok_items[0].message.contains("(42 chunks)"),
+ "the driver's count must reach the message: {}",
+ ok_items[0].message
+ );
+}
+
+/// A driver that could not answer is an `Error` item, not a silent zero: "0
+/// chunks" from a store nobody could count reads exactly like an empty store.
+#[test]
+fn check_memory_tree_db_errors_when_the_driver_could_not_count() {
+ let tmp = TempDir::new().expect("tempdir");
+ let cfg = test_config_in(&tmp);
+
+ let db_dir = cfg.workspace_dir.join("memory_tree");
+ std::fs::create_dir_all(&db_dir).expect("create memory_tree dir");
+ std::fs::write(db_dir.join("chunks.db"), b"").expect("create chunks.db");
+
+ let mut items = vec![];
+ check_memory_tree_db(
+ &cfg,
+ &Err("driver 'null' does not serve Maintenance".to_string()),
+ &mut items,
+ );
+
+ let error_items: Vec<_> = items
+ .iter()
+ .filter(|i| i.severity == Severity::Error && i.category == "memory_tree_db")
+ .collect();
+ assert_eq!(
+ error_items.len(),
+ 1,
+ "expected exactly one Error memory_tree_db item; got: {items:?}"
+ );
+ assert!(
+ error_items[0].message.contains("DB probe failed at"),
+ "unexpected error message: {}",
+ error_items[0].message
+ );
+ assert!(
+ error_items[0]
+ .message
+ .contains("does not serve Maintenance"),
+ "the driver's own reason must survive into the report: {}",
+ error_items[0].message
+ );
}
diff --git a/src/openhuman/platform/doctor/ops.rs b/src/openhuman/platform/doctor/ops.rs
index 005d8e601e..7b15019153 100644
--- a/src/openhuman/platform/doctor/ops.rs
+++ b/src/openhuman/platform/doctor/ops.rs
@@ -1,21 +1,64 @@
//! JSON-RPC / CLI controller surface for diagnostics.
+//!
+//! Also the home of the async probes [`doctor::run`] cannot take itself. It is
+//! blocking by contract (see its docs), so anything that has to be `await`ed
+//! is resolved here and passed down as a value.
use crate::openhuman::config::Config;
-use crate::openhuman::platform::doctor::{self, DoctorReport, ModelProbeReport};
+use crate::openhuman::platform::doctor::{self, DoctorReport, MemoryChunkCount, ModelProbeReport};
use crate::rpc::RpcOutcome;
pub async fn doctor_report(config: &Config) -> Result<RpcOutcome<DoctorReport>, String> {
+ // Awaited before the blocking hop, not inside it: `doctor::run` may not
+ // `.await`, and the driver call may not be blocked on from a runtime
+ // worker. See `MemoryChunkCount`.
+ let memory_chunks = memory_chunk_count(config).await;
+
// `doctor::run` calls `check_embedding_model_health` which uses
// `reqwest::blocking::Client` — that panics inside a tokio runtime.
// Move the entire sync `run()` onto a blocking thread.
let config_clone = config.clone();
- let report = tokio::task::spawn_blocking(move || doctor::run(&config_clone))
+ let report = tokio::task::spawn_blocking(move || doctor::run(&config_clone, memory_chunks))
.await
.map_err(|e| format!("doctor task join error: {e}"))?
.map_err(|e| e.to_string())?;
Ok(RpcOutcome::single_log(report, "doctor report generated"))
}
+/// How many chunks the workspace's bound memory driver holds.
+///
+/// `MemoryMaintenance::store_stats` is the driver-neutral answer to the
+/// question `check_memory_tree_db` used to put to the engine's SQLite
+/// connection directly (#5560).
+///
+/// A driver that does not serve `Maintenance` is reported as a **failed
+/// probe**, not as zero — and that is the one judgement call in here. The
+/// sibling status surfaces (`memory_tree`'s `store_stats`/`queue_stats`)
+/// degrade a missing family to an empty snapshot, because a status panel that
+/// errors tells the user less than one showing an empty store. The doctor is
+/// the opposite surface: it exists to name what is wrong, and "0 chunks" from
+/// a driver that cannot count is indistinguishable from a memory store the
+/// user has just watched themselves fill.
+async fn memory_chunk_count(config: &Config) -> MemoryChunkCount {
+ let binding = crate::openhuman::memory::binding::for_config(config)?;
+ let Some(maintenance) = binding.provider().as_maintenance() else {
+ return Err(format!(
+ "driver '{}' does not serve Maintenance",
+ binding.driver_id()
+ ));
+ };
+ let stats = maintenance
+ .store_stats()
+ .await
+ .map_err(|e| format!("store_stats: {e}"))?;
+ log::debug!(
+ "[doctor] memory_chunk_count: driver='{}' chunks={}",
+ binding.driver_id(),
+ stats.chunks
+ );
+ Ok(stats.chunks)
+}
+
pub async fn doctor_models(
config: &Config,
use_cache: bool,
diff --git a/vendor/tinycortex b/vendor/tinycortex
index b7cf1213b6..84c994b71e 160000
--- a/vendor/tinycortex
+++ b/vendor/tinycortex
@@ -1 +1 @@
-Subproject commit b7cf1213b6093af136797670a9682839bc909781
+Subproject commit 84c994b71eeeb1df1dd5669253353e19e2c2b62c
diff --git a/vendor/tinymemory b/vendor/tinymemory
index 346fe4eba1..38e03fb90d 160000
--- a/vendor/tinymemory
+++ b/vendor/tinymemory
@@ -1 +1 @@
-Subproject commit 346fe4eba15bdef29007cbfc5eef5b4a25a143b1
+Subproject commit 38e03fb90db769b5ce987927d603b0e53bf6c0c8