Skip to content

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

feat(memory): route five engine surfaces over the bus; re-pin module v1.13.5

Shanu1b8ec191f6aa
diff --git a/.github/workflows/ci-full.yml b/.github/workflows/ci-full.yml
index 5f82cfb0d2..495f73addf 100644
--- a/.github/workflows/ci-full.yml
+++ b/.github/workflows/ci-full.yml
@@ -132,8 +132,8 @@ jobs:
# and leave a stale digest that only fails after the download. Both values
# are the ubuntu-22.04-x86_64 row of `src/openhuman/modules/registry.rs`,
# which is the authoritative pin — copy them from there, never recompute.
- memory_version="1.13.3"
- memory_sha256="cc902b653b33386519cc8f49b33b6467d4ef8171e1bedadf71307eca03ad8aa4"
+ memory_version="1.13.5"
+ memory_sha256="d00289fc14fcdc072a34e5ecaccc634cc9831f37631a55330075659daddfb2f0"
module_root="/opt/openhuman-test-modules/${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}"
memory_dir="$module_root/tinymemory"
juice_dir="$module_root/tinyjuice"
diff --git a/.github/workflows/ci-lite.yml b/.github/workflows/ci-lite.yml
index 1b6a0f4ec1..e268c34945 100644
--- a/.github/workflows/ci-lite.yml
+++ b/.github/workflows/ci-lite.yml
@@ -793,8 +793,8 @@ jobs:
# and leave a stale digest that only fails after the download. Both values
# are the ubuntu-22.04-x86_64 row of `src/openhuman/modules/registry.rs`,
# which is the authoritative pin — copy them from there, never recompute.
- memory_version="1.13.3"
- memory_sha256="cc902b653b33386519cc8f49b33b6467d4ef8171e1bedadf71307eca03ad8aa4"
+ memory_version="1.13.5"
+ memory_sha256="d00289fc14fcdc072a34e5ecaccc634cc9831f37631a55330075659daddfb2f0"
module_root="/opt/openhuman-test-modules/${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}"
memory_dir="$module_root/tinymemory"
juice_dir="$module_root/tinyjuice"
diff --git a/.github/workflows/e2e-reusable.yml b/.github/workflows/e2e-reusable.yml
index 7f17dd86b5..c85b56f3c3 100644
--- a/.github/workflows/e2e-reusable.yml
+++ b/.github/workflows/e2e-reusable.yml
@@ -168,8 +168,8 @@ jobs:
# and leave a stale digest that only fails after the download. Both values
# are the ubuntu-22.04-x86_64 row of `src/openhuman/modules/registry.rs`,
# which is the authoritative pin — copy them from there, never recompute.
- memory_version="1.13.3"
- memory_sha256="cc902b653b33386519cc8f49b33b6467d4ef8171e1bedadf71307eca03ad8aa4"
+ memory_version="1.13.5"
+ memory_sha256="d00289fc14fcdc072a34e5ecaccc634cc9831f37631a55330075659daddfb2f0"
module_root="/opt/openhuman-test-modules/${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}"
memory_dir="$module_root/tinymemory"
memory_archive="$memory_dir/tinymemory-module-${memory_version}-ubuntu-22.04-x86_64.tar.gz"
@@ -374,8 +374,8 @@ jobs:
# and leave a stale digest that only fails after the download. Both values
# are the ubuntu-22.04-x86_64 row of `src/openhuman/modules/registry.rs`,
# which is the authoritative pin — copy them from there, never recompute.
- memory_version="1.13.3"
- memory_sha256="cc902b653b33386519cc8f49b33b6467d4ef8171e1bedadf71307eca03ad8aa4"
+ memory_version="1.13.5"
+ memory_sha256="d00289fc14fcdc072a34e5ecaccc634cc9831f37631a55330075659daddfb2f0"
module_root="/opt/openhuman-test-modules/${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}"
memory_dir="$module_root/tinymemory"
memory_archive="$memory_dir/tinymemory-module-${memory_version}-ubuntu-22.04-x86_64.tar.gz"
diff --git a/Cargo.lock b/Cargo.lock
index 3bcfc515a2..703681c637 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -6749,7 +6749,7 @@ dependencies = [
[[package]]
name = "tinymemory"
-version = "1.13.4"
+version = "1.13.5"
dependencies = [
"anyhow",
"async-trait",
diff --git a/src/openhuman/agent/harness/archivist/recap.rs b/src/openhuman/agent/harness/archivist/recap.rs
index 16289b506a..feda88c392 100644
--- a/src/openhuman/agent/harness/archivist/recap.rs
+++ b/src/openhuman/agent/harness/archivist/recap.rs
@@ -2,15 +2,20 @@
use super::store::session_entries;
use super::types::ArchivistHook;
-use crate::openhuman::memory::api::provider::{ConversationSegment, EpisodicTurn};
-use crate::openhuman::memory::tree::summarise::{summarise, SummaryContext, SummaryInput};
-// `SummaryContext::tree_kind` is the engine's own enum. It is reached here
-// through the host's `memory::tree` shim — the same door `summarise`,
-// `SummaryContext` and `SummaryInput` on the line above already come through —
-// rather than by naming the engine crate. Every hop on that path
-// (`memory::tree::tree` → `tinymemory_core::tree::tree` → `store::trees` →
-// `engine::backend::tree::store`) is a re-export of one item, so this is the
-// same type under a shorter name, not a conversion (#5560).
+use crate::openhuman::memory::api::provider::{
+ ConversationSegment, EpisodicTurn, SummaryContext, SummaryInput,
+};
+// The fold itself is `MemoryTree::summarise` now, so the DTOs are the
+// contract's owned ones and `tree_kind` is the wire string the driver
+// validates rather than the engine's `TreeKind` enum (#5560).
+//
+// The engine `summarise` survives under `cfg(test)` only, where the recap
+// tests install a deterministic chat provider through the engine's own
+// task-local; see [`ArchivistHook::summarize_entries`] for why that arm cannot
+// go through the driver.
+#[cfg(test)]
+use crate::openhuman::memory::tree::summarise::summarise;
+#[cfg(test)]
use crate::openhuman::memory::tree::tree::TreeKind;
#[cfg(test)]
use std::sync::Arc;
@@ -33,6 +38,45 @@ const INPUT_TOKEN_BUDGET: u32 = 50_000;
/// See [`INPUT_TOKEN_BUDGET`] for why this is a copy.
const SUMMARY_OVERHEAD_RESERVE_TOKENS: u32 = 2_048;
+/// Fold one segment's corpus through the **guarded** driver's tree family.
+///
+/// The guard rather than the archivist's own provider handle, because
+/// `MemoryTree::summarise` is the one member of that family which sends prose
+/// out of the process — to the driver's chat provider — and the guard's egress
+/// step is what covers that. Resolved through
+/// [`active_memory_guard`](crate::openhuman::memory::ops::guard::active_memory_guard)
+/// the way every other guarded call site does; the fold reads and writes no
+/// store, so the shared binding answers a profile session's fold identically to
+/// its own subtree's.
+///
+/// # Errors
+///
+/// [`MemoryError::Unsupported`] when the bound driver serves no tree family,
+/// [`MemoryError::Backend`] when no workspace can be named, otherwise whatever
+/// the fold itself failed with. Every one of them lands on the caller's
+/// existing error arm — the heuristic bookend — which is exactly where an
+/// engine error landed before.
+#[cfg(not(test))]
+async fn fold_through_driver(
+ inputs: &[SummaryInput],
+ context: &SummaryContext,
+) -> Result<
+ crate::openhuman::memory::api::provider::SummaryOutput,
+ crate::openhuman::memory::api::error::MemoryError,
+> {
+ use crate::openhuman::memory::api::capabilities::Capability;
+ use crate::openhuman::memory::api::error::MemoryError;
+ use crate::openhuman::memory::api::provider::MemoryProvider;
+
+ let guard = crate::openhuman::memory::ops::guard::active_memory_guard()
+ .await
+ .map_err(MemoryError::Backend)?;
+ let tree = guard
+ .as_tree()
+ .ok_or_else(|| MemoryError::unsupported(Capability::Tree))?;
+ tree.summarise(inputs, context).await
+}
+
/// An episodic entry paired with the stable identity exposed by its backing
/// store. The md archivist uses a per-session sequence while the legacy FTS5
/// store uses a row id.
@@ -206,8 +250,11 @@ impl ArchivistHook {
.collect();
let summary_ctx = SummaryContext {
- tree_id: segment_id,
- tree_kind: TreeKind::Source,
+ tree_id: segment_id.to_string(),
+ // The wire spelling of what was `TreeKind::Source`. The driver
+ // validates it and answers `Invalid` for a kind it does not know,
+ // which is why it is stated rather than defaulted.
+ tree_kind: "source".to_string(),
target_level: 0,
token_budget: 2_000,
input_token_budget: INPUT_TOKEN_BUDGET,
@@ -223,27 +270,63 @@ impl ArchivistHook {
// recorded as the boolean it always was. See `lifecycle::with_config`.
if self.summariser_available {
if let Some(ref config) = self.config {
+ // Read only by the `cfg(test)` arm below, now that production
+ // folds through the driver. The `Some` gate stays because it is
+ // the one this function has always had: no config, no LLM
+ // recap, heuristic bookend instead.
+ #[cfg(not(test))]
+ let _ = config;
tracing::debug!(
"[archivist] summarize_entries: LLM recap segment={segment_id} entries={}",
entries.len()
);
- // Test-only: `summarise` builds its own chat provider, and
- // `build_chat_runtime` consults this task-local before building
- // one. Scoping the call is what keeps the recap tests off the
- // network. Production has no such override and never names the
- // engine's chat module (#5560).
+ // Test-only: the engine's `summarise` builds its own chat
+ // provider, and `build_chat_runtime` consults this task-local
+ // before building one. Scoping the call is what keeps the recap
+ // tests off the network, and it is why this arm cannot go
+ // through the driver: the override is a static inside the
+ // engine crate this binary links for tests, which a module in
+ // its own process would not see. Production has no such
+ // override and never names the engine's chat module (#5560).
#[cfg(test)]
- let summary_result = if let Some(provider) = self.chat_provider.as_ref() {
- tinymemory_core::chat::test_override::with_provider(
- Arc::clone(provider),
- summarise(config, &corpus_inputs, &summary_ctx),
- )
- .await
- } else {
- summarise(config, &corpus_inputs, &summary_ctx).await
+ let summary_result = {
+ let engine_inputs: Vec<_> = corpus_inputs
+ .iter()
+ .map(
+ |input| crate::openhuman::memory::tree::summarise::SummaryInput {
+ id: input.id.clone(),
+ content: input.content.clone(),
+ token_count: input.token_count,
+ entities: input.entities.clone(),
+ topics: input.topics.clone(),
+ time_range_start: input.time_range_start,
+ time_range_end: input.time_range_end,
+ score: input.score,
+ },
+ )
+ .collect();
+ let engine_ctx = crate::openhuman::memory::tree::summarise::SummaryContext {
+ tree_id: &summary_ctx.tree_id,
+ tree_kind: TreeKind::parse(&summary_ctx.tree_kind)
+ .expect("summarize_entries builds a tree_kind the engine knows"),
+ target_level: summary_ctx.target_level,
+ token_budget: summary_ctx.token_budget,
+ input_token_budget: summary_ctx.input_token_budget,
+ overhead_reserve_tokens: summary_ctx.overhead_reserve_tokens,
+ ask: summary_ctx.ask.as_deref(),
+ };
+ if let Some(provider) = self.chat_provider.as_ref() {
+ tinymemory_core::chat::test_override::with_provider(
+ Arc::clone(provider),
+ summarise(config, &engine_inputs, &engine_ctx),
+ )
+ .await
+ } else {
+ summarise(config, &engine_inputs, &engine_ctx).await
+ }
};
#[cfg(not(test))]
- let summary_result = summarise(config, &corpus_inputs, &summary_ctx).await;
+ let summary_result = fold_through_driver(&corpus_inputs, &summary_ctx).await;
match summary_result {
Ok(output) if !output.content.is_empty() => {
diff --git a/src/openhuman/agent/harness/session/turn/context.rs b/src/openhuman/agent/harness/session/turn/context.rs
index 9281bb440b..da59b7e777 100644
--- a/src/openhuman/agent/harness/session/turn/context.rs
+++ b/src/openhuman/agent/harness/session/turn/context.rs
@@ -234,9 +234,10 @@ impl Agent {
// Pull every namespace's root-level summary from the tree
// summarizer. This is the densest user memory we can hand the
// orchestrator: each root holds up to 20 000 tokens of distilled
- // long-term context. Done synchronously here because the calls
- // are filesystem reads, not provider/network round-trips, and
- // happen exactly once per session (only on the first turn).
+ // long-term context. Awaited inline, alongside the four memory reads
+ // above: the shared tree's roots come from the bound driver now
+ // (#5560) rather than from a host-side filesystem scan, and this
+ // happens exactly once per session (only on the first turn).
//
// Per-namespace + total caps come from the user-facing memory
// window preset on `AgentConfig` so changing the slider in the
@@ -247,7 +248,8 @@ impl Agent {
&self.memory_subdir,
limits.per_namespace_max_chars,
limits.total_tree_max_chars,
- );
+ )
+ .await;
LearnedContextData {
observations: obs_entries
diff --git a/src/openhuman/agent/harness/session/turn/mod.rs b/src/openhuman/agent/harness/session/turn/mod.rs
index 801cfb3e32..6e80bbbc31 100644
--- a/src/openhuman/agent/harness/session/turn/mod.rs
+++ b/src/openhuman/agent/harness/session/turn/mod.rs
@@ -151,24 +151,46 @@ Do not attempt to run them with `run_skill` — they have been removed. Tell the
))
}
-/// Wrapper around
-/// [`crate::openhuman::memory::tree::tree_runtime::store::collect_root_summaries_with_caps`]
-/// that takes user-resolved per-namespace and total caps. The actual
-/// limits are derived from the active
+/// Every namespace's root summary, under user-resolved per-namespace and total
+/// caps. The limits are derived from the active
/// [`crate::openhuman::config::schema::agent::MemoryContextWindow`]
/// preset by [`crate::openhuman::config::schema::agent::AgentConfig::resolved_memory_limits`].
-pub(super) fn collect_tree_root_summaries(
+///
+/// # The shared tree is the driver's now (#5560)
+///
+/// `memory_subdir == "memory"` goes through
+/// `MemoryTree::root_summaries_with_caps` instead of
+/// `tree_runtime::store::collect_root_summaries_with_caps`. Same files, same
+/// two caps, same `[... truncated]` marker: the embedded driver's member is
+/// that function, called with its own `config.workspace_dir`, so the block the
+/// prompt renders is unchanged.
+///
+/// The `memory-<id>` arm stays host-local and untouched. The contract member
+/// takes **no path** — deliberately, since a workspace argument would be
+/// configuration crossing the bus — and the driver reachable here is bound to
+/// the shared subtree, so a dedicated profile's tree still has to be scanned
+/// directly by [`collect_profile_tree_root_summaries`].
+///
+/// # Why `async` is the whole bridge
+///
+/// The only caller, `turn::context::fetch_learned_context`, is already an
+/// `async fn` and awaits four memory reads immediately above this one, so the
+/// driver call is awaited rather than bridged. `block_in_place` — the pattern
+/// `session::builder::helpers` uses for a genuinely synchronous caller —
+/// panics on a current-thread runtime and would buy nothing here.
+///
+/// An unresolvable binding, a driver with no tree family, or a failed read all
+/// yield no summaries. That is what this returned before as well: the engine's
+/// scan swallowed its own failures into an empty vector, and the prompt simply
+/// carries no memory block.
+pub(super) async fn collect_tree_root_summaries(
workspace_dir: &std::path::Path,
memory_subdir: &str,
per_namespace_cap: usize,
total_cap: usize,
) -> Vec<crate::openhuman::agent::context::prompt::NamespaceSummary> {
let rows = if memory_subdir == "memory" {
- crate::openhuman::memory::tree::tree_runtime::store::collect_root_summaries_with_caps(
- workspace_dir,
- per_namespace_cap,
- total_cap,
- )
+ driver_tree_root_summaries(per_namespace_cap, total_cap).await
} else {
collect_profile_tree_root_summaries(
&workspace_dir.join(memory_subdir),
@@ -187,6 +209,46 @@ pub(super) fn collect_tree_root_summaries(
.collect()
}
+/// The shared subtree's root summaries, read from the guarded driver.
+///
+/// Returns the same positional `(namespace, body, updated_at)` triple the
+/// engine scan did, so [`collect_tree_root_summaries`]'s mapping is shared with
+/// the profile arm rather than written twice.
+async fn driver_tree_root_summaries(
+ per_namespace_cap: usize,
+ total_cap: usize,
+) -> Vec<(String, String, chrono::DateTime<chrono::Utc>)> {
+ use crate::openhuman::memory::api::provider::MemoryProvider;
+
+ let guard = match crate::openhuman::memory::ops::guard::active_memory_guard().await {
+ Ok(guard) => guard,
+ Err(error) => {
+ log::debug!("[session::turn] tree root summaries: no bound driver ({error})");
+ return Vec::new();
+ }
+ };
+ let Some(tree) = guard.as_tree() else {
+ log::debug!(
+ "[session::turn] tree root summaries: driver '{}' does not serve Tree",
+ guard.driver_id()
+ );
+ return Vec::new();
+ };
+ match tree
+ .root_summaries_with_caps(per_namespace_cap, total_cap)
+ .await
+ {
+ Ok(rows) => rows
+ .into_iter()
+ .map(|row| (row.namespace, row.body, row.updated_at))
+ .collect(),
+ Err(error) => {
+ log::warn!("[session::turn] tree root summaries: {error}");
+ Vec::new()
+ }
+ }
+}
+
/// Read summary-tree root summaries from an already-resolved `memory-*` subtree.
/// The engine's compatibility helper hardcodes `<workspace>/memory`; dedicated
/// profiles instead supply `<workspace>/memory-<id>`, so scan that equivalent
diff --git a/src/openhuman/agent/harness/session/turn_tests_part_01_tests.rs b/src/openhuman/agent/harness/session/turn_tests_part_01_tests.rs
index 295f6a416c..d62fb73cd9 100644
--- a/src/openhuman/agent/harness/session/turn_tests_part_01_tests.rs
+++ b/src/openhuman/agent/harness/session/turn_tests_part_01_tests.rs
@@ -76,8 +76,8 @@ fn trim_history_snaps_past_orphaned_tool_results() {
assert_eq!(agent.history.len(), 3);
}
-#[test]
-fn build_parent_context_and_sanitize_helpers_cover_snapshot_paths() {
+#[tokio::test]
+async fn build_parent_context_and_sanitize_helpers_cover_snapshot_paths() {
let mut agent = make_agent(None);
agent.last_memory_context = Some("remember this".into());
agent.workflows = vec![crate::openhuman::skills::Workflow {
@@ -100,7 +100,14 @@ fn build_parent_context_and_sanitize_helpers_cover_snapshot_paths() {
);
let long = "x".repeat(500);
assert_eq!(sanitize_learned_entry(&long).chars().count(), 200);
- assert!(collect_tree_root_summaries(agent.workspace_dir(), "memory", 8_000, 32_000).is_empty());
+ // A profile subtree that was never written. Named rather than `"memory"`
+ // because the shared subtree is the driver's now (#5560), and what this
+ // line is here to cover is the host-local scan's empty answer.
+ assert!(
+ collect_tree_root_summaries(agent.workspace_dir(), "memory-absent", 8_000, 32_000)
+ .await
+ .is_empty()
+ );
}
#[test]
@@ -145,10 +152,15 @@ fn build_parent_context_has_no_descriptor_without_profile_or_parent() {
assert!(parent.workspace_descriptor.is_none());
}
-#[test]
-fn collect_tree_root_summaries_maps_namespace_body_and_timestamp() {
+#[tokio::test]
+async fn collect_tree_root_summaries_maps_namespace_body_and_timestamp() {
// #2944: the wrapper must carry the root node's `updated_at` from the
// store tuple into the `NamespaceSummary` the prompt renderer stamps.
+ //
+ // Asserted over a **profile** subtree since #5560: the mapping is the same
+ // one both arms share, and the profile arm is the one that still scans a
+ // caller-named workspace. The shared `"memory"` arm now answers from the
+ // bound driver, which has no way to be pointed at this temp directory.
use crate::openhuman::config::Config;
use crate::openhuman::memory::tree::tree_runtime::store::write_node;
use tinycortex::memory::tree::runtime::{
@@ -180,16 +192,19 @@ fn collect_tree_root_summaries_maps_namespace_body_and_timestamp() {
metadata: None,
};
write_node(&config, &node).unwrap();
+ // `write_node` only knows `<workspace>/memory`; rename it into the profile
+ // layout the host-local arm reads.
+ std::fs::rename(workspace.join("memory"), workspace.join("memory-alice")).unwrap();
- let summaries = collect_tree_root_summaries(&workspace, "memory", 8_000, 32_000);
+ let summaries = collect_tree_root_summaries(&workspace, "memory-alice", 8_000, 32_000).await;
assert_eq!(summaries.len(), 1);
assert_eq!(summaries[0].namespace, "activities");
assert_eq!(summaries[0].body, summary);
assert_eq!(summaries[0].updated_at, updated_at);
}
-#[test]
-fn collect_tree_root_summaries_reads_only_profile_memory_subtree() {
+#[tokio::test]
+async fn collect_tree_root_summaries_reads_only_profile_memory_subtree() {
use crate::openhuman::config::Config;
use crate::openhuman::memory::tree::tree_runtime::store::write_node;
use tinycortex::memory::tree::runtime::{
@@ -219,8 +234,16 @@ fn collect_tree_root_summaries_reads_only_profile_memory_subtree() {
write_node(&config, &node).unwrap();
std::fs::rename(workspace.join("memory"), workspace.join("memory-alice")).unwrap();
- assert!(collect_tree_root_summaries(&workspace, "memory", 8_000, 32_000).is_empty());
- let summaries = collect_tree_root_summaries(&workspace, "memory-alice", 8_000, 32_000);
+ // A *different* profile's subtree, not `"memory"`: since #5560 the shared
+ // arm answers from the bound driver rather than from this temp workspace,
+ // so asking it here would be asserting about a store this test never
+ // wrote. Bob is the isolation the assertion is actually about.
+ assert!(
+ collect_tree_root_summaries(&workspace, "memory-bob", 8_000, 32_000)
+ .await
+ .is_empty()
+ );
+ let summaries = collect_tree_root_summaries(&workspace, "memory-alice", 8_000, 32_000).await;
assert_eq!(summaries.len(), 1);
assert_eq!(summaries[0].body, "Alice-only context");
}
diff --git a/src/openhuman/memory/direct_engine_refs_tests.rs b/src/openhuman/memory/direct_engine_refs_tests.rs
index 76c316c43e..86816eb122 100644
--- a/src/openhuman/memory/direct_engine_refs_tests.rs
+++ b/src/openhuman/memory/direct_engine_refs_tests.rs
@@ -287,7 +287,7 @@ const ALLOWED: &[(&str, Verdict, &str)] = &[
(
"src/openhuman/agent/harness/archivist/recap.rs",
Verdict::NeedsWiderSeam,
- "reaches engine storage below the contract (store::fts5, store::segments::ConversationSegment, store::chunks::types::approx_token_count); MemoryChunks is read-only (list_chunks/get_chunk/chunk_detail/storage_kinds/chunk_embeddings) with no write or transaction door",
+ "the engine-side chat provider seam (chat::test_override), named only from the `#[cfg(test)]` recap arm: the deterministic provider those tests install is a task-local inside this binary's copy of the engine, which a module in its own process cannot see. The production fold is MemoryTree::summarise",
),
(
"src/openhuman/agent/harness/archivist/test_constructors.rs",
@@ -324,20 +324,15 @@ const ALLOWED: &[(&str, Verdict, &str)] = &[
// These are the historical-path aliases `memory/mod.rs` documents. They
// name the crate once each and call nothing. Removing them is the
// re-export problem, not the direct-call problem.
- (
- "src/openhuman/memory/sources/mod.rs",
- Verdict::HostSide,
- "re-export shim: pub use tinymemory_core::sources::*",
- ),
(
"src/openhuman/memory/tree/health/mod.rs",
Verdict::HostSide,
- "re-export shim: pub use tinymemory_core::tree::health::*",
+ "re-export shim: pub use tinymemory_core::tree::health::*; no production caller left — the doctor and the degradation snapshot are MemoryMaintenance::{diagnose, degraded_state} — so what it carries is `test_guard` and the flag setters four *_tests.rs files drive",
),
(
"src/openhuman/memory/tree/mod.rs",
Verdict::HostSide,
- "re-export shim: pub use tinymemory_core::tree::*",
+ "re-export shim: pub use tinymemory_core::tree::*; no production caller left — `score` is MemoryChunks::chunk_score and `summarise` is MemoryTree::summarise — so what it carries is `score::*`, `summarise::*` and `ingest` for this crate's *_tests.rs and tests/raw_coverage/",
),
(
"src/openhuman/memory/tree/tree/mod.rs",
diff --git a/src/openhuman/memory/guard/families_part_01.rs b/src/openhuman/memory/guard/families_part_01.rs
index 47f4dfff10..b02f388892 100644
--- a/src/openhuman/memory/guard/families_part_01.rs
+++ b/src/openhuman/memory/guard/families_part_01.rs
@@ -1,3 +1,4 @@
+use std::borrow::Cow;
use std::sync::Arc;
use crate::openhuman::memory::api::capabilities::Capability;
@@ -5,8 +6,13 @@ use crate::openhuman::memory::api::chunks::Chunk;
use crate::openhuman::memory::api::error::MemoryError;
use crate::openhuman::memory::api::goals::GoalsDoc;
use crate::openhuman::memory::api::provider::chunks::{
- ChunkDetail, ChunkEmbedding, ChunkListRow, ChunkQuery, MemoryChunks, SourceTotal,
+ ChunkDetail, ChunkEmbedding, ChunkListRow, ChunkQuery, ChunkScore, MemoryChunks,
+ SourceIngestQuery, SourceIngestStatus, SourceTotal,
};
+use crate::openhuman::memory::api::provider::content::{
+ RootSummary, SummaryContext, SummaryInput, SummaryOutput,
+};
+use crate::openhuman::memory::api::provider::diagnosis::{DegradedCapabilities, Diagnosis};
use crate::openhuman::memory::api::provider::episodic::{
ConversationSegment, EpisodicTurn, MemoryEpisodic,
};
@@ -525,6 +531,73 @@ impl MemoryTree for GuardedTree {
.recent_leaves(limit, effective.as_ref())
.await
}
+
+ /// A **read** tier check even though the fold costs a provider call: it
+ /// writes nothing. `seal` and `cascade` take the write tier because they
+ /// persist the nodes they produce; this hands the summary back and leaves
+ /// the tree exactly as it found it, so refusing it under `readonly` would
+ /// stop a recap that stores nothing.
+ ///
+ /// It is nevertheless the only member of this family besides
+ /// [`Self::append`] that carries prose *outbound* — every input's body
+ /// crosses to the driver's own chat provider — so it declares
+ /// `carries_content: true` and applies `append`'s scrub to each of them.
+ /// Admitted against [`SummaryContext::tree_id`] rather than
+ /// `NO_NAMESPACE` for the reason [`Self::flush_source_tree`] gives: it
+ /// names the tree it acts on.
+ async fn summarise(
+ &self,
+ inputs: &[SummaryInput],
+ context: &SummaryContext,
+ ) -> Result<SummaryOutput, MemoryError> {
+ self.policy
+ .admit_read(Capability::Tree, "tree.summarise", &context.tree_id, true)?;
+ // `redact_outbound` borrows for every driver class but `External`, so
+ // the re-owned slice is built only when the scrubber actually rewrote
+ // something — a recap folds every turn of a segment, and cloning them
+ // to hand back the same bytes is the one cost this can avoid.
+ let mut scrubbed: Option<Vec<SummaryInput>> = None;
+ for (index, input) in inputs.iter().enumerate() {
+ if let Cow::Owned(content) = self.policy.redact_outbound(&input.content) {
+ scrubbed.get_or_insert_with(|| inputs.to_vec())[index].content = content;
+ }
+ }
+ let effective = scrubbed.as_deref().unwrap_or(inputs);
+ trace_allowed(
+ &self.policy,
+ "tree.summarise",
+ &context.tree_id,
+ effective
+ .iter()
+ .map(|input| input.content.chars().count())
+ .sum(),
+ );
+ self.family()?.summarise(effective, context).await
+ }
+
+ /// The markdown time tree's roots, one body per namespace.
+ ///
+ /// Takes no [`SourceScope`], so unlike [`Self::summary_forest`] there is
+ /// nothing here to intersect with the ambient allowlist — the contract
+ /// member has no scope parameter and the guard does not invent one. Both
+ /// caps are the caller's and cross unchanged: they bound the *response*,
+ /// and clipping them here would produce a body the driver did not choose
+ /// the truncation point of.
+ async fn root_summaries_with_caps(
+ &self,
+ per_namespace_cap: usize,
+ total_cap: usize,
+ ) -> Result<Vec<RootSummary>, MemoryError> {
+ self.policy.admit_read(
+ Capability::Tree,
+ "tree.root_summaries_with_caps",
+ NO_NAMESPACE,
+ false,
+ )?;
+ self.family()?
+ .root_summaries_with_caps(per_namespace_cap, total_cap)
+ .await
+ }
}
// ── Entities ─────────────────────────────────────────────────────────────────
diff --git a/src/openhuman/memory/guard/families_part_02.rs b/src/openhuman/memory/guard/families_part_02.rs
index 51fb5c2991..fdd2c8a0de 100644
--- a/src/openhuman/memory/guard/families_part_02.rs
+++ b/src/openhuman/memory/guard/families_part_02.rs
@@ -305,6 +305,39 @@ impl MemoryMaintenance for GuardedMaintenance {
)?;
self.family()?.purge_all().await
}
+
+ /// [`Self::doctor`]'s findings in full, and read-only on the same terms —
+ /// it inspects configuration, persisted state and counters and mutates
+ /// nothing, so it takes the read tier for the reason `doctor` gives.
+ ///
+ /// Forwarded here rather than left to the trait's default: a defaulted
+ /// method on a decorator answers `Unsupported` even when the driver below
+ /// serves it, so the default would refuse every diagnosis reached through
+ /// the guard.
+ async fn diagnose(&self) -> Result<Diagnosis, MemoryError> {
+ self.policy.admit_read(
+ Capability::Maintenance,
+ "maintenance.diagnose",
+ NO_NAMESPACE,
+ false,
+ )?;
+ self.family()?.diagnose().await
+ }
+
+ /// The degradation flags without the diagnosis around them — three
+ /// booleans and at most one cause. Read tier for the same reason
+ /// [`Self::doctor`] takes it, and for one more: this is what a status
+ /// light polls, so refusing it under `readonly` would leave the surface
+ /// that reports a reduced pipeline unable to say so.
+ async fn degraded_state(&self) -> Result<DegradedCapabilities, MemoryError> {
+ self.policy.admit_read(
+ Capability::Maintenance,
+ "maintenance.degraded_state",
+ NO_NAMESPACE,
+ false,
+ )?;
+ self.family()?.degraded_state().await
+ }
}
// ── People ───────────────────────────────────────────────────────────────────
@@ -535,4 +568,38 @@ impl MemoryChunks for GuardedChunks {
.chunk_embeddings(chunk_ids, model_signature)
.await
}
+
+ /// One chunk's admission verdict, read by chunk id exactly as
+ /// [`Self::chunk_detail`] is — so it takes that member's check, not
+ /// [`Self::list_chunks`]'s scope intersection. There is no scope to narrow:
+ /// the caller already holds the id.
+ async fn chunk_score(&self, chunk_id: &str) -> Result<Option<ChunkScore>, MemoryError> {
+ self.policy.admit_read(
+ Capability::Chunks,
+ "chunks.chunk_score",
+ NO_NAMESPACE,
+ false,
+ )?;
+ self.family()?.chunk_score(chunk_id).await
+ }
+
+ /// Ingest progress for the sources the caller names, one row per query.
+ ///
+ /// Unlike [`Self::source_totals`], which enumerates the groups that exist
+ /// and therefore has to be narrowed to the ambient allowlist, this answers
+ /// only about prefixes the caller supplied — it discloses no source the
+ /// caller did not already name — and the contract member carries no
+ /// [`SourceScope`] for the guard to intersect anything into.
+ async fn source_ingest_status(
+ &self,
+ source_prefixes: &[SourceIngestQuery],
+ ) -> Result<Vec<SourceIngestStatus>, MemoryError> {
+ self.policy.admit_read(
+ Capability::Chunks,
+ "chunks.source_ingest_status",
+ NO_NAMESPACE,
+ false,
+ )?;
+ self.family()?.source_ingest_status(source_prefixes).await
+ }
}
diff --git a/src/openhuman/memory/guard/families_tests.rs b/src/openhuman/memory/guard/families_tests.rs
index 2fa98924db..b7cff66f9b 100644
--- a/src/openhuman/memory/guard/families_tests.rs
+++ b/src/openhuman/memory/guard/families_tests.rs
@@ -506,3 +506,132 @@ async fn episodic_writes_are_not_redacted_for_an_embedded_driver() {
.expect("insert_event");
assert_eq!(driver.only_call().content.as_deref(), Some(secrety));
}
+
+// ── The defaulted doors ─────────────────────────────────────────────────────
+//
+// Every method a family trait *defaults* is a method a decorator can silently
+// fail to forward: the impl compiles, and the default answers `Unsupported`
+// however capable the driver below is. `RecordingProvider` overrides the five
+// #5560 doors and `diagnose`, so a decorator that dropped one is the only way
+// these can come back unsupported.
+
+/// One summary context, so the fold tests read as the two things they differ
+/// in rather than as seven repeated budget fields.
+fn summary_context() -> crate::openhuman::memory::api::provider::content::SummaryContext {
+ crate::openhuman::memory::api::provider::content::SummaryContext {
+ tree_id: "segment-1".into(),
+ tree_kind: "source".into(),
+ target_level: 0,
+ token_budget: 2_000,
+ input_token_budget: 50_000,
+ overhead_reserve_tokens: 2_048,
+ ask: None,
+ }
+}
+
+fn summary_input(content: &str) -> crate::openhuman::memory::api::provider::content::SummaryInput {
+ let at = chrono::Utc::now();
+ crate::openhuman::memory::api::provider::content::SummaryInput {
+ id: "turn-1".into(),
+ content: content.into(),
+ token_count: 4,
+ entities: Vec::new(),
+ topics: Vec::new(),
+ time_range_start: at,
+ time_range_end: at,
+ score: 0.5,
+ }
+}
+
+#[tokio::test]
+async fn the_defaulted_doors_are_forwarded_rather_than_refused() {
+ let (driver, guard) = guarded(embedded_policy());
+
+ guard
+ .as_tree()
+ .expect("tree family")
+ .summarise(&[summary_input("hello")], &summary_context())
+ .await
+ .expect("summarise must reach the driver, not the trait default");
+ guard
+ .as_tree()
+ .expect("tree family")
+ .root_summaries_with_caps(8_000, 32_000)
+ .await
+ .expect("root_summaries_with_caps must reach the driver");
+ guard
+ .as_chunks()
+ .expect("chunks family")
+ .chunk_score("chunk-1")
+ .await
+ .expect("chunk_score must reach the driver");
+ guard
+ .as_chunks()
+ .expect("chunks family")
+ .source_ingest_status(&[])
+ .await
+ .expect("source_ingest_status must reach the driver");
+ guard
+ .as_maintenance()
+ .expect("maintenance family")
+ .degraded_state()
+ .await
+ .expect("degraded_state must reach the driver");
+ guard
+ .as_maintenance()
+ .expect("maintenance family")
+ .diagnose()
+ .await
+ .expect("diagnose must reach the driver");
+
+ let methods: Vec<String> = driver.calls().into_iter().map(|call| call.method).collect();
+ assert_eq!(
+ methods,
+ vec![
+ "tree.summarise",
+ "tree.root_summaries_with_caps",
+ "chunks.chunk_score",
+ "chunks.source_ingest_status",
+ "maintenance.degraded_state",
+ "maintenance.diagnose",
+ ]
+ );
+}
+
+/// `summarise` is the only member of the tree family besides `append` that
+/// hands prose *out* of the host — to the driver's own chat provider — so it
+/// takes `append`'s outbound scrub.
+#[tokio::test]
+async fn summarise_inputs_are_redacted_for_a_foreign_driver() {
+ let secrety = "Authorization: Bearer abcdefghijklmnop";
+
+ let (driver, guard) = guarded(external_policy("trusted"));
+ guard
+ .as_tree()
+ .expect("tree family")
+ .summarise(&[summary_input(secrety)], &summary_context())
+ .await
+ .expect("summarise");
+ assert_ne!(
+ driver.only_call().content.as_deref(),
+ Some(secrety),
+ "the bearer token reached a foreign driver's summariser verbatim"
+ );
+}
+
+/// The other half: an embedded driver is the same address space, so scrubbing
+/// there would cost the fold fidelity for no privacy gain — and the borrowed
+/// slice must be forwarded untouched rather than re-owned.
+#[tokio::test]
+async fn summarise_inputs_are_not_redacted_for_an_embedded_driver() {
+ let secrety = "Authorization: Bearer abcdefghijklmnop";
+
+ let (driver, guard) = guarded(embedded_policy());
+ guard
+ .as_tree()
+ .expect("tree family")
+ .summarise(&[summary_input(secrety)], &summary_context())
+ .await
+ .expect("summarise");
+ assert_eq!(driver.only_call().content.as_deref(), Some(secrety));
+}
diff --git a/src/openhuman/memory/guard/test_support_part_01.rs b/src/openhuman/memory/guard/test_support_part_01.rs
index 28eae794b9..d868f44433 100644
--- a/src/openhuman/memory/guard/test_support_part_01.rs
+++ b/src/openhuman/memory/guard/test_support_part_01.rs
@@ -463,6 +463,38 @@ impl MemoryTree for RecordingProvider {
self.record(Call::plain("tree.cascade"));
Ok(tree_status(namespace))
}
+
+ /// Records the folded bodies as one blob, so a redaction test can assert on
+ /// what the driver's summariser would have been handed.
+ async fn summarise(
+ &self,
+ inputs: &[crate::openhuman::memory::api::provider::content::SummaryInput],
+ _context: &crate::openhuman::memory::api::provider::content::SummaryContext,
+ ) -> Result<crate::openhuman::memory::api::provider::content::SummaryOutput, MemoryError> {
+ self.record(Call {
+ method: "tree.summarise".into(),
+ content: Some(
+ inputs
+ .iter()
+ .map(|input| input.content.clone())
+ .collect::<Vec<_>>()
+ .join("|"),
+ ),
+ taint: None,
+ scoped: None,
+ });
+ Ok(Default::default())
+ }
+
+ async fn root_summaries_with_caps(
+ &self,
+ _per_namespace_cap: usize,
+ _total_cap: usize,
+ ) -> Result<Vec<crate::openhuman::memory::api::provider::content::RootSummary>, MemoryError>
+ {
+ self.record(Call::plain("tree.root_summaries_with_caps"));
+ Ok(Vec::new())
+ }
}
#[async_trait]
@@ -662,4 +694,21 @@ impl MemoryMaintenance for RecordingProvider {
self.record(Call::plain("maintenance.doctor"));
Ok(MaintenanceReport::default())
}
+
+ async fn diagnose(
+ &self,
+ ) -> Result<crate::openhuman::memory::api::provider::diagnosis::Diagnosis, MemoryError> {
+ self.record(Call::plain("maintenance.diagnose"));
+ Ok(Default::default())
+ }
+
+ async fn degraded_state(
+ &self,
+ ) -> Result<
+ crate::openhuman::memory::api::provider::diagnosis::DegradedCapabilities,
+ MemoryError,
+ > {
+ self.record(Call::plain("maintenance.degraded_state"));
+ Ok(Default::default())
+ }
}
diff --git a/src/openhuman/memory/guard/test_support_part_02.rs b/src/openhuman/memory/guard/test_support_part_02.rs
index d74022b660..33282616b5 100644
--- a/src/openhuman/memory/guard/test_support_part_02.rs
+++ b/src/openhuman/memory/guard/test_support_part_02.rs
@@ -358,6 +358,26 @@ impl MemoryChunks for RecordingProvider {
self.record(Call::plain("chunks.chunk_embeddings"));
Ok(vec![])
}
+
+ async fn chunk_score(
+ &self,
+ _chunk_id: &str,
+ ) -> Result<Option<crate::openhuman::memory::api::provider::chunks::ChunkScore>, MemoryError>
+ {
+ self.record(Call::plain("chunks.chunk_score"));
+ Ok(None)
+ }
+
+ async fn source_ingest_status(
+ &self,
+ _source_prefixes: &[crate::openhuman::memory::api::provider::chunks::SourceIngestQuery],
+ ) -> Result<
+ Vec<crate::openhuman::memory::api::provider::chunks::SourceIngestStatus>,
+ MemoryError,
+ > {
+ self.record(Call::plain("chunks.source_ingest_status"));
+ Ok(vec![])
+ }
}
#[async_trait]
diff --git a/src/openhuman/memory/read_rpc/entities.rs b/src/openhuman/memory/read_rpc/entities.rs
index 8f8fd328b6..ac972af966 100644
--- a/src/openhuman/memory/read_rpc/entities.rs
+++ b/src/openhuman/memory/read_rpc/entities.rs
@@ -2,9 +2,9 @@ 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_api::error::MemoryError;
+use tinymemory_api::provider::chunks::ChunkScore;
use tinymemory_api::provider::types::{EntityOccurrence, ForgetSelector};
use super::types::{DeleteChunkResponse, EntityRef, ScoreBreakdown, ScoreSignal, MAX_LIST_LIMIT};
@@ -209,69 +209,112 @@ 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).
+// The admission verdict is the driver's and only the driver's: it is a row the
+// scorer wrote at ingest, under the policy in force *then*, and re-deriving it
+// today would answer under today's policy. `MemoryChunks::chunk_score` is that
+// door, and `DEFAULT_DROP_THRESHOLD` crosses on the contract beside it rather
+// than being copied here — a host-side `0.3` is the kind of copy that goes
+// wrong silently, leaving a stale line drawn under freshly-labelled rows.
+//
+// No `spawn_blocking` on either of the two handlers below: the driver owns
+// whether its own reads block, and the module's do not run on this thread at
+// all.
+
+/// One chunk's score row, or `None` when the scorer never wrote one.
+///
+/// Shared by [`chunk_score_rpc`], which renders it, and [`score_row_count`],
+/// which only counts it — the same split [`chunk_entity_rows`] makes for the
+/// entity index, and for the same reason: one read, two readings. `op` is the
+/// caller's name, so an error still reads as that handler's.
+///
+/// A driver with no chunk tier reports no row rather than failing: both callers
+/// are describing what the store recorded about one chunk, and it recorded
+/// nothing. A driver that *has* the tier but keeps no admission record answers
+/// `Unsupported`, which propagates — "this driver does not score" is not the
+/// same claim as "this chunk was not scored", and only the second is what
+/// `None` means here.
+async fn chunk_score_row(
+ binding: &MemoryBinding,
+ chunk_id: &str,
+ op: &str,
+) -> Result<Option<ChunkScore>, String> {
+ let Some(chunks) = binding.provider().as_chunks() else {
+ log::debug!(
+ "[memory_tree::read::chunk_score] {op}: driver '{}' does not serve Chunks; \
+ reporting no score",
+ binding.driver_id()
+ );
+ return Ok(None);
+ };
+ chunks
+ .chunk_score(chunk_id)
+ .await
+ .map_err(|e| format!("{op}: {e}"))
+}
+
+/// The seven signals the score panel renders, in the order it renders them.
+///
+/// The weights are **this handler's**, not the driver's: no contract member
+/// reports them, and they are what the panel has always shown beside each
+/// signal, so they stay written out here exactly as they were. `weight` on
+/// `llm_importance` is the one that varies, and it varies on the same predicate
+/// the response's `llm_consulted` carries.
+fn score_breakdown(row: ChunkScore) -> ScoreBreakdown {
+ let llm_consulted = row.signals.llm_importance > 0.0;
+ let signals = vec![
+ ScoreSignal {
+ name: "token_count".into(),
+ weight: 1.0,
+ value: row.signals.token_count,
+ },
+ ScoreSignal {
+ name: "unique_words".into(),
+ weight: 1.0,
+ value: row.signals.unique_words,
+ },
+ ScoreSignal {
+ name: "metadata_weight".into(),
+ weight: 1.5,
+ value: row.signals.metadata_weight,
+ },
+ ScoreSignal {
+ name: "source_weight".into(),
+ weight: 1.5,
+ value: row.signals.source_weight,
+ },
+ ScoreSignal {
+ name: "interaction".into(),
+ weight: 3.0,
+ value: row.signals.interaction,
+ },
+ ScoreSignal {
+ name: "entity_density".into(),
+ weight: 1.0,
+ value: row.signals.entity_density,
+ },
+ ScoreSignal {
+ name: "llm_importance".into(),
+ weight: if llm_consulted { 2.0 } else { 0.0 },
+ value: row.signals.llm_importance,
+ },
+ ];
+ ScoreBreakdown {
+ signals,
+ total: row.total,
+ threshold: tinymemory_bus::provider::chunks::DEFAULT_DROP_THRESHOLD,
+ kept: !row.dropped,
+ llm_consulted,
+ }
+}
pub async fn chunk_score_rpc(
config: &Config,
chunk_id: String,
) -> Result<RpcOutcome<Option<ScoreBreakdown>>, String> {
- let cfg = config.clone();
- let id = chunk_id.clone();
- let result = tokio::task::spawn_blocking(move || -> Result<Option<ScoreBreakdown>> {
- let row = score_store::get_score(&cfg, &id)?;
- Ok(row.map(|r| {
- let llm_consulted = r.signals.llm_importance > 0.0;
- let signals = vec![
- ScoreSignal {
- name: "token_count".into(),
- weight: 1.0,
- value: r.signals.token_count,
- },
- ScoreSignal {
- name: "unique_words".into(),
- weight: 1.0,
- value: r.signals.unique_words,
- },
- ScoreSignal {
- name: "metadata_weight".into(),
- weight: 1.5,
- value: r.signals.metadata_weight,
- },
- ScoreSignal {
- name: "source_weight".into(),
- weight: 1.5,
- value: r.signals.source_weight,
- },
- ScoreSignal {
- name: "interaction".into(),
- weight: 3.0,
- value: r.signals.interaction,
- },
- ScoreSignal {
- name: "entity_density".into(),
- weight: 1.0,
- value: r.signals.entity_density,
- },
- ScoreSignal {
- name: "llm_importance".into(),
- weight: if llm_consulted { 2.0 } else { 0.0 },
- value: r.signals.llm_importance,
- },
- ];
- ScoreBreakdown {
- signals,
- total: r.total,
- threshold: crate::openhuman::memory::tree::score::DEFAULT_DROP_THRESHOLD,
- kept: !r.dropped,
- llm_consulted,
- }
- }))
- })
- .await
- .map_err(|e| format!("chunk_score join error: {e}"))?
- .map_err(|e| format!("chunk_score: {e:#}"))?;
+ let binding = crate::openhuman::memory::binding::for_config(config)?;
+ let result = chunk_score_row(&binding, &chunk_id, "chunk_score")
+ .await?
+ .map(score_breakdown);
Ok(RpcOutcome::single_log(
result,
format!("memory_tree::read: chunk_score id={chunk_id}"),
@@ -280,24 +323,14 @@ pub async fn chunk_score_rpc(
// ── delete_chunk ────────────────────────────────────────────────────────
-/// Whether `mem_tree_score` holds a row for this chunk, as a rowcount.
+/// Whether the driver holds a score 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:#}"))?;
+/// The admission record is keyed by chunk id, so "is there a row" *is* the
+/// number the `DELETE` this replaced returned. Read through the same
+/// [`chunk_score_row`] door [`chunk_score_rpc`] uses, so the panel and the
+/// delete cannot disagree about whether one chunk was ever scored.
+async fn score_row_count(binding: &MemoryBinding, chunk_id: &str) -> Result<u32, String> {
+ let row = chunk_score_row(binding, chunk_id, "delete_chunk").await?;
Ok(u32::from(row.is_some()))
}
@@ -340,7 +373,7 @@ pub async fn delete_chunk_rpc(
.iter()
.map(|occurrence| occurrence.mentions)
.fold(0u32, u32::saturating_add);
- let score_rows_removed = score_row_count(config, &chunk_id).await?;
+ let score_rows_removed = score_row_count(&binding, &chunk_id).await?;
let selector = ForgetSelector::Chunk {
chunk_id: chunk_id.clone(),
diff --git a/src/openhuman/memory/sources/mod.rs b/src/openhuman/memory/sources/mod.rs
index 3392ae5b82..5f0facd6b1 100644
--- a/src/openhuman/memory/sources/mod.rs
+++ b/src/openhuman/memory/sources/mod.rs
@@ -17,37 +17,33 @@
//! `twitter` were implemented in the engine crate but named nothing
//! engine-shaped, so they came home unchanged. See [`readers`].
//! 3. **`sync` and `status` are wired into pieces that have not moved.** This
-//! one still stands, and is why those two are still reached from the engine
-//! by name below rather than through a glob. `reconcile` was on this line as
-//! well and has since come home — see below.
+//! one is settled too — see below. `reconcile` was on this line as well and
+//! came home first.
//!
-//! ## What is still the engine's, and why each one
+//! ## How `sync` and `status` were resolved
//!
-//! - [`sync`] reaches `engine::run_source_pipeline`, `engine::{needs_rebuild,
+//! Neither was ported wholesale; each was split along the line between what the
+//! host knows and what only a driver can answer.
+//!
+//! - [`sync`] reached `engine::run_source_pipeline`, `engine::{needs_rebuild,
//! rebuild_tree_from_raw}`, `queue::store::retry_all_failed`,
-//! `sync::composio` and `sync::audit` — the ingest pipeline, the re-embed
-//! queue and the Composio sync half. Only `derive_scopes` is reached from
-//! production today (`rpc::reconcile_rpc`); `sync_source` itself has no
-//! caller left in `src/`, because the sync the product runs goes over the bus
-//! through `MemorySourceSync`. The module is kept whole rather than narrowed
-//! to the one live function: a re-export that hides which half is dead would
-//! make the next audit harder, not easier.
-//! - [`status`] reaches `store::chunks::store::with_connection`, the raw SQLite
-//! chunk door, and is live in production behind
-//! `memory_sources.status_list`. **`MemoryChunks::source_totals` is not a
-//! substitute**, and this is worth stating because it looks like one:
-//! `SourceTotal` carries `chunk_count` and `most_recent_ms` but no
-//! `chunks_pending`, and pending — "has no embedding, was not dropped, was
-//! not skipped for re-embed" — is the whole point of a sync-status row.
-//! `source_totals` also omits a source with zero chunks entirely, where
-//! `status_list` returns a row per *configured* source. Migrating onto it
-//! would compile and quietly report a healthy store. The ask upstream is a
-//! pending count.
+//! `sync::composio` and `sync::audit`. All of that stayed upstream, and none
+//! of it was reached from production here: `sync_source` has had no caller
+//! left in `src/` since the sync the product runs went over the bus through
+//! `MemorySourceSync`. The single live item, `derive_scopes`, is registry
+//! fields plus a scan of a directory this host owns, so it came home.
+//! - [`status`] reached `store::chunks::store::with_connection`, the raw SQLite
+//! chunk door. That half is `MemoryChunks::source_ingest_status` now — the
+//! upstream ask this file used to record, a **pending** count per configured
+//! source, which `source_totals` still cannot answer (`SourceTotal` has no
+//! pending column and omits a source with zero chunks entirely). What stayed
+//! host-side is the half that was always the host's: the chunk-key prefix,
+//! derived from the registry entry, and the freshness label, which is
+//! arithmetic over a timestamp and this process's clock.
//!
-//! Porting those two as they stand would move the ingest pipeline and the raw
-//! chunk door *into* the host rather than behind the bus, which is the opposite
-//! of what #5560 is for: a second unpoliced door spelled differently is still a
-//! second unpoliced door.
+//! What was *not* done in either case is porting the pipeline or the raw chunk
+//! door into the host, which would be the opposite of what #5560 is for: a
+//! second unpoliced door spelled differently is still a second unpoliced door.
//!
//! ## What came home, and why it was different
//!
@@ -84,11 +80,13 @@ pub use registry::{
};
pub use types::{ContentType, MemorySourceEntry, SourceContent, SourceItem, SourceKind};
-// ── Still the engine's ──────────────────────────────────────────────────────
-//
-// Named rather than globbed, so `grep tinymemory_core` in this domain is an
-// honest inventory of what is left. See the module docs for what blocks each.
-pub use tinymemory_core::sources::{status, sync};
+// `status` and `sync` were the last two names this domain reached out of the
+// engine crate for, and both are home now — see each module's own docs for
+// which half moved and which half stayed upstream. The paths are unchanged
+// (`sources::status::status_list`, `sources::sync::derive_scopes`), so no call
+// site moved with them.
+pub mod status;
+pub mod sync;
// `reconcile` used to be entirely the engine's. tinymemory v1.13.4 deleted
// `ensure_composio_sources` along with the rest of the in-process Composio
diff --git a/src/openhuman/memory/sources/status.rs b/src/openhuman/memory/sources/status.rs
new file mode 100644
index 0000000000..2ba65478fe
--- /dev/null
+++ b/src/openhuman/memory/sources/status.rs
@@ -0,0 +1,235 @@
+//! Per-source sync status — chunks ingested, freshness, in-flight progress.
+//!
+//! # Two halves, and which side each one belongs on (#5560)
+//!
+//! This used to be `tinymemory_core::sources::status`, one function that read
+//! the host's source registry and then ran `SELECT … FROM mem_tree_chunks`
+//! against the engine's SQLite. That is two questions with two owners:
+//!
+//! - **Which key does this configured source stamp on its chunks?**
+//! [`source_id_prefix`] — pure string formatting over the registry entry's
+//! kind, toolkit and connection id. The registry is *this host's* file, so
+//! only this host can answer it; a driver asked to derive the prefix would
+//! need the registry, which is precisely the coupling the contract removes.
+//! - **How many rows sit under that key, and how many are still in flight?**
+//! `MemoryChunks::source_ingest_status`, because `chunks_pending` spans the
+//! embedding sidecar and the re-embed skip ledger as well as the chunk row's
+//! own lifecycle column, and nothing outside the driver can see those.
+//!
+//! [`FreshnessLabel`] is the third piece and it is the caller's, deliberately:
+//! it is arithmetic over `last_chunk_at_ms` and a clock, so answering it
+//! driver-side would freeze the driver's clock into the reply and a panel
+//! rendering the label a minute later would show how fresh the source was when
+//! the driver looked.
+//!
+//! **`MemoryChunks::source_totals` is not a substitute**, and it is worth
+//! restating because it looks like one: `SourceTotal` carries `chunk_count` and
+//! `most_recent_ms` but no pending count, and it returns the groups that
+//! *exist*, so a configured source that has never synced vanishes from the
+//! answer rather than appearing idle.
+
+use serde::{Deserialize, Serialize};
+
+use crate::openhuman::config::Config;
+use crate::openhuman::memory::api::provider::chunks::SourceIngestQuery;
+use crate::openhuman::memory::binding::MemoryBinding;
+use crate::openhuman::memory::sources::types::{MemorySourceEntry, SourceKind};
+
+/// How fresh a source's sync is, judged from its newest chunk.
+///
+/// A verbatim port of the engine's enum, thresholds and all. The serde
+/// spelling is `snake_case` and must stay that way: it is what the memory
+/// sources panel matches on, and this is a wire type in a response that is
+/// otherwise unchanged.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum FreshnessLabel {
+ /// Newest chunk is under 30 seconds old.
+ Active,
+ /// Newest chunk is under 5 minutes old.
+ Recent,
+ /// Anything older, or nothing synced yet.
+ Idle,
+}
+
+impl FreshnessLabel {
+ /// Label for a source whose newest chunk landed at `last_chunk_at_ms`,
+ /// judged at `now_ms`.
+ ///
+ /// `saturating_sub` rather than `-`: a chunk stamped in the future (a
+ /// skewed remote clock on an imported item) yields a non-positive age
+ /// rather than an overflow, and reads as [`Self::Active`].
+ pub fn from_age_ms(last_chunk_at_ms: Option<i64>, now_ms: i64) -> Self {
+ match last_chunk_at_ms {
+ None => Self::Idle,
+ Some(timestamp) => match now_ms.saturating_sub(timestamp) {
+ age if age <= 30_000 => Self::Active,
+ age if age <= 5 * 60_000 => Self::Recent,
+ _ => Self::Idle,
+ },
+ }
+ }
+}
+
+/// One configured source's ingest progress, as the `memory_sources.status_list`
+/// RPC has always returned it.
+///
+/// Field for field and name for name the engine's `SourceStatus`, so the
+/// response JSON is unchanged by the move.
+#[derive(Clone, Debug, Serialize)]
+pub struct SourceStatus {
+ pub source_id: String,
+ pub chunks_synced: u64,
+ pub chunks_pending: u64,
+ pub last_chunk_at_ms: Option<i64>,
+ pub freshness: FreshnessLabel,
+}
+
+impl SourceStatus {
+ /// The zero row: a source the store could not be asked about.
+ ///
+ /// The engine's loop pushed exactly this for a per-source query failure,
+ /// and it is what a degraded read answers here too — see [`status_list`].
+ fn idle(source_id: String) -> Self {
+ Self {
+ source_id,
+ chunks_synced: 0,
+ chunks_pending: 0,
+ last_chunk_at_ms: None,
+ freshness: FreshnessLabel::Idle,
+ }
+ }
+}
+
+/// The literal prefix of the chunk-ingest key a source's rows carry.
+///
+/// The scheme is set by the ingest paths, not chosen here: reader-backed kinds
+/// key chunks `mem_src:{source.id}:{item}`, and the Composio sync keys them
+/// `{toolkit}:{connection_id}:{document_id}`.
+///
+/// Matching a Composio source on its toolkit alone would sweep in every *other*
+/// connection of that toolkit — two Gmail accounts would each report the
+/// other's chunks as their own — so the connection narrows it. A Composio entry
+/// without a connection id does not pass validation; the toolkit-only fallback
+/// is there so a malformed row degrades to a wide match rather than to no match
+/// at all.
+///
+/// # No `%`, unlike the engine's twin
+///
+/// The engine's `source_id_prefix` returned a `LIKE` pattern (`mem_src:{id}:%`)
+/// because its caller passed it straight to SQL. [`SourceIngestQuery`] takes a
+/// **literal** prefix — the driver places its own wildcard and escapes any
+/// metacharacter in what it was given — so the trailing `%` is dropped and the
+/// trailing separator, which is what stops `mem_src:src_a:` also counting
+/// `mem_src:src_ab:`, is kept.
+pub(crate) fn source_id_prefix(source: &MemorySourceEntry) -> String {
+ match source.kind {
+ SourceKind::Composio => {
+ match (source.toolkit.as_deref(), source.connection_id.as_deref()) {
+ (Some(toolkit), Some(connection_id)) => format!("{toolkit}:{connection_id}:"),
+ (Some(toolkit), None) => format!("{toolkit}:"),
+ (None, _) => "__no_toolkit__:".to_string(),
+ }
+ }
+ _ => format!("mem_src:{}:", source.id),
+ }
+}
+
+/// Status for every configured source, in registry order.
+///
+/// One driver call for the whole batch where the engine ran one SQL round trip
+/// per source. That is the shape the contract member is built for — it echoes
+/// [`SourceIngestQuery::source_id`] on every row so the pairing is by value
+/// rather than by position — and it removes the per-source connection open the
+/// old loop paid.
+///
+/// **Every configured source gets a row**, including one that has never synced:
+/// the driver zero-fills a prefix that matches nothing, which is the whole
+/// reason this is not `source_totals`. Disabled sources are included too,
+/// exactly as the engine's loop included them — the panel renders them and
+/// filtering them here would empty rows the user can still see.
+///
+/// # Errors
+///
+/// Only when the source registry itself cannot be read. A driver with no chunk
+/// tier, and a read that fails, both degrade to a zero row per source with a
+/// warning — the engine's loop degraded the same way, per source, and a status
+/// surface that errors tells the user less than one reporting an idle store.
+pub async fn status_list(config: &Config) -> Result<Vec<SourceStatus>, String> {
+ let sources = super::registry::list_sources().await?;
+ if sources.is_empty() {
+ return Ok(Vec::new());
+ }
+
+ let queries: Vec<SourceIngestQuery> = sources
+ .iter()
+ .map(|source| SourceIngestQuery {
+ source_id: source.id.clone(),
+ chunk_id_prefix: source_id_prefix(source),
+ })
+ .collect();
+
+ let binding = crate::openhuman::memory::binding::for_config(config)?;
+ let rows = ingest_rows(&binding, &queries).await;
+
+ // The clock is read once for the whole batch, so two sources synced in the
+ // same instant cannot be labelled differently by the time the loop reached
+ // the second one.
+ let now_ms = chrono::Utc::now().timestamp_millis();
+ Ok(sources
+ .into_iter()
+ .map(|source| {
+ // Paired by `source_id`, not by position: the member echoes the id
+ // precisely so a caller need not trust the order, and a mis-indexed
+ // row here would report one connector's progress under another's
+ // name.
+ match rows.iter().find(|row| row.source_id == source.id) {
+ Some(row) => SourceStatus {
+ source_id: source.id,
+ chunks_synced: row.chunks_synced,
+ chunks_pending: row.chunks_pending,
+ last_chunk_at_ms: row.last_chunk_at_ms,
+ freshness: FreshnessLabel::from_age_ms(row.last_chunk_at_ms, now_ms),
+ },
+ None => SourceStatus::idle(source.id),
+ }
+ })
+ .collect())
+}
+
+/// The driver's answer for one batch of queries, degraded to no rows on any
+/// failure.
+///
+/// Split out so [`status_list`] reads as the mapping it is. Returning an empty
+/// vector rather than an error is what turns every source into
+/// [`SourceStatus::idle`] above, which is the engine loop's own degrade.
+async fn ingest_rows(
+ binding: &MemoryBinding,
+ queries: &[SourceIngestQuery],
+) -> Vec<crate::openhuman::memory::api::provider::chunks::SourceIngestStatus> {
+ let Some(chunks) = binding.provider().as_chunks() else {
+ tracing::warn!(
+ driver = %binding.driver_id(),
+ "[memory_sources:status] driver does not serve Chunks; reporting every source idle"
+ );
+ return Vec::new();
+ };
+ match chunks.source_ingest_status(queries).await {
+ Ok(rows) => rows,
+ Err(error) => {
+ // The batch fails as one — the counts come from a single store, so
+ // a read that fails fails for all of them — where the engine failed
+ // per source. Same outcome for the reader either way: a zero row.
+ tracing::warn!(
+ error = %error,
+ sources = queries.len(),
+ "[memory_sources:status] ingest status read failed"
+ );
+ Vec::new()
+ }
+ }
+}
+
+#[cfg(test)]
+#[path = "status_tests.rs"]
+mod tests;
diff --git a/src/openhuman/memory/sources/status_tests.rs b/src/openhuman/memory/sources/status_tests.rs
new file mode 100644
index 0000000000..140d2c353d
--- /dev/null
+++ b/src/openhuman/memory/sources/status_tests.rs
@@ -0,0 +1,131 @@
+//! Tests for the surrounding module.
+
+use super::*;
+
+/// A folder source, the shape the prefix tests start from.
+fn folder_entry(id: &str) -> MemorySourceEntry {
+ MemorySourceEntry {
+ id: id.into(),
+ kind: SourceKind::Folder,
+ label: "x".into(),
+ enabled: true,
+ toolkit: None,
+ connection_id: None,
+ path: Some("/tmp".into()),
+ glob: None,
+ url: None,
+ branch: None,
+ paths: Vec::new(),
+ query: None,
+ since_days: None,
+ max_items: None,
+ max_commits: None,
+ max_issues: None,
+ max_prs: None,
+ selector: None,
+ max_tokens_per_sync: None,
+ max_cost_per_sync_usd: None,
+ sync_depth_days: None,
+ }
+}
+
+/// The four branches of the prefix scheme, ported from the engine's own test.
+///
+/// The one deliberate difference from that test is the missing `%`: the driver
+/// places its own wildcard now, so what crosses is a literal prefix. Everything
+/// left of it — including the trailing separator — is unchanged, which is what
+/// keeps `mem_src:src_a:` from also counting `mem_src:src_ab:`.
+#[test]
+fn source_id_prefix_dispatch() {
+ let mut entry = folder_entry("src_abc");
+ assert_eq!(source_id_prefix(&entry), "mem_src:src_abc:");
+
+ // A Composio source is matched on its connection, not just its toolkit: a
+ // second Gmail account must not count the first's chunks.
+ entry.kind = SourceKind::Composio;
+ entry.toolkit = Some("gmail".into());
+ entry.connection_id = Some("conn-1".into());
+ assert_eq!(source_id_prefix(&entry), "gmail:conn-1:");
+
+ entry.connection_id = None;
+ assert_eq!(source_id_prefix(&entry), "gmail:");
+
+ entry.toolkit = None;
+ assert_eq!(source_id_prefix(&entry), "__no_toolkit__:");
+}
+
+/// The thresholds, at and either side of each boundary.
+///
+/// `<=` on both, so 30 000 ms is still `Active` and 300 000 ms is still
+/// `Recent` — the engine's own comparison, kept because a panel that flips a
+/// label one millisecond earlier than it used to is a behaviour change nobody
+/// asked for.
+#[test]
+fn freshness_thresholds_match_the_engine() {
+ let now = 1_000_000_000_i64;
+ assert_eq!(FreshnessLabel::from_age_ms(None, now), FreshnessLabel::Idle);
+ assert_eq!(
+ FreshnessLabel::from_age_ms(Some(now), now),
+ FreshnessLabel::Active
+ );
+ assert_eq!(
+ FreshnessLabel::from_age_ms(Some(now - 30_000), now),
+ FreshnessLabel::Active
+ );
+ assert_eq!(
+ FreshnessLabel::from_age_ms(Some(now - 30_001), now),
+ FreshnessLabel::Recent
+ );
+ assert_eq!(
+ FreshnessLabel::from_age_ms(Some(now - 300_000), now),
+ FreshnessLabel::Recent
+ );
+ assert_eq!(
+ FreshnessLabel::from_age_ms(Some(now - 300_001), now),
+ FreshnessLabel::Idle
+ );
+ // A chunk stamped in the future (a skewed remote clock on an imported
+ // item) reads as fresh rather than overflowing.
+ assert_eq!(
+ FreshnessLabel::from_age_ms(Some(now + 60_000), now),
+ FreshnessLabel::Active
+ );
+}
+
+/// The serde spelling the memory-sources panel matches on. It is `snake_case`
+/// in the engine's copy and has to stay `snake_case` here, because this rides a
+/// response whose shape is otherwise unchanged by the move.
+#[test]
+fn freshness_serialises_snake_case() {
+ assert_eq!(
+ serde_json::to_string(&FreshnessLabel::Active).unwrap(),
+ "\"active\""
+ );
+ assert_eq!(
+ serde_json::to_string(&FreshnessLabel::Recent).unwrap(),
+ "\"recent\""
+ );
+ assert_eq!(
+ serde_json::to_string(&FreshnessLabel::Idle).unwrap(),
+ "\"idle\""
+ );
+}
+
+/// The five fields, their names, and the fact that `last_chunk_at_ms` is
+/// carried as `null` rather than omitted — the engine's `SourceStatus` had no
+/// `skip_serializing_if`, and a field that disappears is a field a client
+/// reading `row.last_chunk_at_ms` sees as `undefined`.
+#[test]
+fn source_status_serde_shape_is_unchanged() {
+ let json = serde_json::to_value(SourceStatus::idle("src_a".into())).unwrap();
+ assert_eq!(
+ json,
+ serde_json::json!({
+ "source_id": "src_a",
+ "chunks_synced": 0,
+ "chunks_pending": 0,
+ "last_chunk_at_ms": null,
+ "freshness": "idle",
+ })
+ );
+}
diff --git a/src/openhuman/memory/sources/sync.rs b/src/openhuman/memory/sources/sync.rs
new file mode 100644
index 0000000000..6921f22bf3
--- /dev/null
+++ b/src/openhuman/memory/sources/sync.rs
@@ -0,0 +1,119 @@
+//! Scope derivation for a configured source: which tree scope, and which
+//! raw-archive id, a registry entry maps onto.
+//!
+//! # What came home and what did not (#5560)
+//!
+//! `tinymemory_core::sources::sync` was the whole ingest pipeline — the source
+//! run, the tree rebuild, the re-embed queue and the Composio sync half — and
+//! exactly one item of it was reached from production here:
+//! [`derive_scopes`], called by `rpc::reconcile_rpc`. That one is not pipeline
+//! at all. It reads the registry entry's `kind` and `url`, formats them through
+//! `tinymemory_sources::readers::github` (an engine-neutral crate this host
+//! already depends on), and for a Gmail connector scans
+//! `<content root>/raw/gmail-*/_source.md` for the scope the archiver wrote.
+//! Registry fields, a filesystem scan under a path the host owns, and no store
+//! access — so it is host work that happened to live upstream, the same line
+//! [`super::reconcile`] came home along.
+//!
+//! Everything else in that module stayed where it is. `sync_source` had no
+//! caller left in `src/` — the sync the product runs goes over the bus through
+//! `MemorySourceSync` — and porting the pipeline would move it *into* the host
+//! rather than behind the module, which is the opposite of the point.
+
+use crate::openhuman::config::Config;
+use crate::openhuman::memory::sources::types::{MemorySourceEntry, SourceKind};
+
+/// A source's tree scope paired with its raw-archive source id.
+///
+/// The two slugify to **different** directories for GitHub
+/// (`github:owner/repo` vs `github.com/owner/repo`); conflating them makes
+/// reconcile scan an empty directory while the real archive sits uncovered.
+///
+/// Not to be confused with `tinymemory_api::provider::types::SourceScope`,
+/// which is the recall allowlist that crosses the bus. Same name, unrelated
+/// shapes — check which one a call site means before moving it.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct SourceScope {
+ /// Tree registry key, e.g. `"github:owner/repo"`.
+ pub tree_scope: String,
+ /// Raw-archive id whose slug names `raw/<slug>/`, e.g.
+ /// `"github.com/owner/repo"`. Equal to `tree_scope` for sources that
+ /// archive under their scope (gmail).
+ pub archive_source_id: String,
+}
+
+/// Derive the tree scope(s) + raw-archive id(s) that a source maps to.
+///
+/// A verbatim port of the engine's function: same match arms, same
+/// `gmail-` directory prefix, same `scope:` line parse, same empty answer for
+/// every kind that has no raw archive to reconcile yet.
+pub fn derive_scopes(source: &MemorySourceEntry, config: &Config) -> Vec<SourceScope> {
+ use crate::openhuman::memory::sources::readers::github;
+
+ match source.kind {
+ SourceKind::GithubRepo => {
+ let Some(url) = source.url.as_deref() else {
+ return Vec::new();
+ };
+ match (
+ github::repo_chunk_scope(url),
+ github::repo_archive_source_id(url),
+ ) {
+ (Some(tree_scope), Some(archive_source_id)) => vec![SourceScope {
+ tree_scope,
+ archive_source_id,
+ }],
+ _ => Vec::new(),
+ }
+ }
+ SourceKind::Composio => {
+ // Composio sources scope by toolkit + connection email.
+ // Gmail: "gmail:<slug_account_email>" — archive dir shares
+ // the scope. Others: no raw archive to reconcile yet.
+ let toolkit = source.toolkit.as_deref().unwrap_or("unknown");
+ match toolkit {
+ "gmail" | "GMAIL" => {
+ // The scope for gmail is "gmail:<slugified_email>".
+ // We scan the raw directory to find it.
+ let content_root = config.memory_tree_content_root();
+ let raw_dir = content_root.join("raw");
+ if let Ok(entries) = std::fs::read_dir(&raw_dir) {
+ entries
+ .filter_map(|e| e.ok())
+ .filter(|e| {
+ e.file_name()
+ .to_str()
+ .map(|n| n.starts_with("gmail-"))
+ .unwrap_or(false)
+ })
+ .filter_map(|e| {
+ // Read _source.md to get the scope.
+ let source_md = e.path().join("_source.md");
+ let content = std::fs::read_to_string(&source_md).ok()?;
+ content.lines().find(|l| l.starts_with("scope:")).map(|l| {
+ let scope = l
+ .trim_start_matches("scope:")
+ .trim()
+ .trim_matches('"')
+ .to_string();
+ SourceScope {
+ tree_scope: scope.clone(),
+ archive_source_id: scope,
+ }
+ })
+ })
+ .collect()
+ } else {
+ Vec::new()
+ }
+ }
+ _ => Vec::new(),
+ }
+ }
+ _ => Vec::new(),
+ }
+}
+
+#[cfg(test)]
+#[path = "sync_tests.rs"]
+mod tests;
diff --git a/src/openhuman/memory/sources/sync_tests.rs b/src/openhuman/memory/sources/sync_tests.rs
new file mode 100644
index 0000000000..a751c5df51
--- /dev/null
+++ b/src/openhuman/memory/sources/sync_tests.rs
@@ -0,0 +1,102 @@
+//! Tests for the surrounding module.
+
+use super::*;
+
+/// The two GitHub coordinate helpers are re-exported from `tinymemory-sources`
+/// and they deliberately differ: `tree_scope` slugifies to
+/// `github-tinyhumansai-openhuman` while `archive_source_id` slugifies to
+/// `github-com-tinyhumansai-openhuman`. Swapping the two still compiles and
+/// still type-checks — it just makes reconcile scan an empty directory at
+/// runtime. Pin both spellings, as the engine's own test did.
+#[test]
+fn derive_scopes_keeps_github_tree_and_archive_ids_distinct() {
+ let source: MemorySourceEntry = serde_json::from_value(serde_json::json!({
+ "id": "gh-scope",
+ "kind": "github_repo",
+ "label": "Repo",
+ "url": "https://github.com/tinyhumansai/openhuman",
+ }))
+ .expect("github source entry");
+
+ let scopes = derive_scopes(&source, &Config::default());
+
+ assert_eq!(scopes.len(), 1);
+ assert_eq!(scopes[0].tree_scope, "github:tinyhumansai/openhuman");
+ assert_eq!(
+ scopes[0].archive_source_id,
+ "github.com/tinyhumansai/openhuman"
+ );
+}
+
+/// A GitHub entry with no URL has no coordinates to derive, and a kind with no
+/// raw archive has nothing to reconcile. Both answer with no scopes rather than
+/// with a guessed one.
+#[test]
+fn derive_scopes_is_empty_without_coordinates() {
+ let mut source: MemorySourceEntry = serde_json::from_value(serde_json::json!({
+ "id": "gh-no-url",
+ "kind": "github_repo",
+ "label": "Repo",
+ }))
+ .expect("github source entry");
+ assert!(derive_scopes(&source, &Config::default()).is_empty());
+
+ source.url = Some("not-a-url".into());
+ assert!(derive_scopes(&source, &Config::default()).is_empty());
+
+ let folder: MemorySourceEntry = serde_json::from_value(serde_json::json!({
+ "id": "folder",
+ "kind": "folder",
+ "label": "Folder",
+ "path": "/tmp",
+ }))
+ .expect("folder source entry");
+ assert!(derive_scopes(&folder, &Config::default()).is_empty());
+}
+
+/// A Gmail connector's scope is read off the archive the sync wrote, so an
+/// absent `raw/` directory yields nothing rather than failing, and a toolkit
+/// with no raw archive yet yields nothing either.
+#[test]
+fn derive_scopes_reads_the_gmail_scope_from_the_raw_archive() {
+ let tmp = tempfile::TempDir::new().expect("temp workspace");
+ let config = Config {
+ workspace_dir: tmp.path().to_path_buf(),
+ ..Config::default()
+ };
+ let source: MemorySourceEntry = serde_json::from_value(serde_json::json!({
+ "id": "gmail-src",
+ "kind": "composio",
+ "label": "Gmail",
+ "toolkit": "gmail",
+ "connection_id": "conn-1",
+ }))
+ .expect("composio source entry");
+
+ // Nothing on disk yet.
+ assert!(derive_scopes(&source, &config).is_empty());
+
+ let raw = config
+ .memory_tree_content_root()
+ .join("raw")
+ .join("gmail-me");
+ std::fs::create_dir_all(&raw).expect("raw dir");
+ std::fs::write(raw.join("_source.md"), "scope: \"gmail:me-example-com\"\n")
+ .expect("source marker");
+
+ let scopes = derive_scopes(&source, &config);
+ assert_eq!(scopes.len(), 1);
+ assert_eq!(scopes[0].tree_scope, "gmail:me-example-com");
+ assert_eq!(scopes[0].archive_source_id, "gmail:me-example-com");
+
+ // A toolkit with no raw archive convention is not guessed at.
+ let notion: MemorySourceEntry = serde_json::from_value(serde_json::json!({
+ "id": "notion-src",
+ "kind": "composio",
+ "label": "Notion",
+ "toolkit": "notion",
+ "connection_id": "conn-2",
+ }))
+ .expect("composio source entry");
+ assert!(derive_scopes(&notion, &config).is_empty());
+}
diff --git a/src/openhuman/memory/tools/doctor.rs b/src/openhuman/memory/tools/doctor.rs
index 99a03e00dd..d4b241bcec 100644
--- a/src/openhuman/memory/tools/doctor.rs
+++ b/src/openhuman/memory/tools/doctor.rs
@@ -1,13 +1,19 @@
//! Agent tool: diagnose the memory pipeline (#002 FR-009).
//!
-//! Thin wrapper over [`health::run_doctor`] so the agent can self-diagnose an
-//! empty / stalled wiki and tell the user the single first blocking cause +
-//! how to fix it — the same report the `memory_tree_doctor` RPC and CLI
-//! return. Read-only: takes no arguments and mutates nothing, so it carries no
-//! security-gate (matching the read-only memory tools).
+//! Thin wrapper over
+//! [`health::report::run_doctor`](crate::openhuman::memory::tree::health::report::run_doctor)
+//! so the agent can self-diagnose an empty / stalled wiki and tell the user the
+//! single first blocking cause + how to fix it — the same report the
+//! `memory_tree_doctor` RPC and CLI return. Read-only: takes no arguments and
+//! mutates nothing, so it carries no security-gate (matching the read-only
+//! memory tools).
+//!
+//! The pass itself is the bound driver's since #5560
+//! (`MemoryMaintenance::diagnose`): the counters and the degradation flags only
+//! exist in the process that ran the pipeline, and that is the module.
use crate::openhuman::config::Config;
-use crate::openhuman::memory::tree::health::async_run_doctor;
+use crate::openhuman::memory::tree::health::report::run_doctor;
use crate::openhuman::tools::traits::{Tool, ToolResult};
use async_trait::async_trait;
use serde_json::json;
@@ -42,7 +48,7 @@ impl Tool for MemoryDoctorTool {
}
async fn execute(&self, _args: serde_json::Value) -> anyhow::Result<ToolResult> {
- let report = async_run_doctor(self.config.as_ref()).await;
+ let report = run_doctor(self.config.as_ref()).await;
// Serialize the structured report so the model gets the typed stages +
// first_blocking_cause + counters verbatim (it can summarize for the
// user from there). serde of a plain struct can't fail here.
diff --git a/src/openhuman/memory/tree/health/mod.rs b/src/openhuman/memory/tree/health/mod.rs
index 14105e26cf..3f0a7a1fc4 100644
--- a/src/openhuman/memory/tree/health/mod.rs
+++ b/src/openhuman/memory/tree/health/mod.rs
@@ -50,18 +50,26 @@ pub use tinycortex::memory::health::{
// The half that genuinely pins the engine crate: the process-global
// degradation flags (`mark_*` / `clear_*` / `current_degraded_state`, plus the
-// `test_guard` that serialises tests touching them) and the `doctor` report,
-// all *defined in* `tinymemory-core`. Left as a glob deliberately — narrowing
-// it would enumerate the flag set here and go stale the first time one is
-// added, and it carries nothing else.
+// `test_guard` that serialises tests touching them) and the engine's own
+// `doctor` report, all *defined in* `tinymemory-core`. Left as a glob
+// deliberately — narrowing it would enumerate the flag set here and go stale
+// the first time one is added, and it carries nothing else.
//
-// `MemoryMaintenance::diagnose()` on the pinned v1.7.0 contract is the
-// structural twin of `DoctorReport` (`healthy` / `stages` / `first_blocking_cause`
-// / `degraded` / `counters`, with `FailureCode` and `FailureClass` widened to
-// open strings), so it is what the doctor eventually routes through — but
-// **not yet**: neither `ModuleMemoryProvider` nor `GuardedMaintenance` overrides
-// it, so a call today falls through to the trait's default and answers
-// `Unsupported` at run time. See `tree::tree::rpc::doctor_rpc`.
+// **Nothing in production reads this glob any more.** `current_degraded_state`
+// and `async_run_doctor` were its two live callers and both went to the driver
+// in #5560 — see [`report`]. What is left is `test_guard`, which four test
+// files use to serialise the process statics, and the flag setters those tests
+// drive. So this line is now a test-only pin, and it goes when those tests stop
+// needing an in-process engine to mark a flag on.
pub use tinymemory_core::tree::health::*;
+/// The doctor report and the degradation snapshot, read from the bound driver
+/// rather than from this process's copy of the engine.
+///
+/// Its [`DoctorReport`](report::DoctorReport) shadows nothing: it is reached as
+/// `health::report::DoctorReport`, deliberately kept out of this module's own
+/// namespace so that "the host's response type" and "the engine's struct the
+/// glob above still carries" cannot be confused for one another at a call site.
+pub mod report;
+
pub(crate) mod user_error;
diff --git a/src/openhuman/memory/tree/health/report.rs b/src/openhuman/memory/tree/health/report.rs
new file mode 100644
index 0000000000..081c459715
--- /dev/null
+++ b/src/openhuman/memory/tree/health/report.rs
@@ -0,0 +1,265 @@
+//! The doctor report and the degradation snapshot, read from the **driver**.
+//!
+//! # What moved, and what deliberately did not (#5560)
+//!
+//! `tinymemory_core::tree::health` answered both of these in-process:
+//! `current_degraded_state()` read three atomics and `async_run_doctor()`
+//! wrapped a blocking pass over the routing config, the scheduler gate, the job
+//! queue and the chunk table. Neither is answerable from outside the engine —
+//! the degradation flags are set by the embed and extract stages as they run,
+//! and the counters are a read of the driver's own database — so both are
+//! contract members now: `MemoryMaintenance::degraded_state` and
+//! `MemoryMaintenance::diagnose`.
+//!
+//! That was not a cosmetic move. The flags are **process statics**, and the
+//! loaded module links its own copy of `tinymemory-core`: a degradation the
+//! module observed never reached the statics this host was reading, so
+//! `current_degraded_state()` answered all-clear here forever. Asking the
+//! driver is what makes the answer true again.
+//!
+//! # The response types are host-side, and their serde shape is pinned
+//!
+//! [`DoctorReport`], [`StageHealth`] and [`DoctorCounters`] are field-for-field
+//! the engine's, including the two `skip_serializing_if`s and the one
+//! `#[serde(default)]` **without** one — `DoctorCounters::extraction_coverage`
+//! is serialised as `null` rather than omitted, which the contract's
+//! `DiagnosisCounters` does not do. `report_tests` pins every one of those
+//! against the JSON this RPC has always emitted.
+//!
+//! The failure taxonomy is **not** redefined here. [`PipelineFailure`],
+//! [`FailureCode`] and [`FailureClass`] stay `tinycortex`'s — the same items
+//! [`super`] already re-exports, and the same ones
+//! `pipeline_status.first_blocking_cause` is built from out of a
+//! `QueueFailure`. Two copies of that vocabulary is exactly how the two halves
+//! of one response start disagreeing about a code.
+
+use serde::{Deserialize, Serialize};
+
+use crate::openhuman::config::Config;
+use crate::openhuman::memory::api::provider::diagnosis::{
+ DegradedCapabilities, Diagnosis, DiagnosisFailure,
+};
+use crate::openhuman::memory::api::provider::MemoryProvider;
+
+use super::{DegradedState, FailureClass, FailureCode, PipelineFailure};
+
+/// Health of one named pipeline stage.
+///
+/// The stage set is the **driver's** — a second engine has different stages —
+/// and the order is meaningful: the stages run in it, so the first unhealthy
+/// one is the one to fix first. Rendered as given rather than sorted.
+#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
+pub struct StageHealth {
+ /// Stable stage id: `routing`, `scheduler_gate`, `embeddings`,
+ /// `extraction`, `queue`, `summary_tree`.
+ pub stage: String,
+ /// True when this stage is healthy / not blocking.
+ pub ok: bool,
+ /// Typed failure when `ok == false`; `None` when healthy. Carries the
+ /// i18n remediation key the surfaces render.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub failure: Option<PipelineFailure>,
+ /// Short non-localized human note for logs / CLI (never a secret).
+ pub note: String,
+}
+
+/// Current pipeline counters, mirrored from the status surface so the doctor
+/// is a one-call snapshot.
+// No `Eq`: `extraction_coverage` is `Option<f32>` — `f32` never implements `Eq`.
+#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
+pub struct DoctorCounters {
+ pub total_chunks: u64,
+ pub jobs_ready: u64,
+ pub jobs_running: u64,
+ pub jobs_failed: u64,
+ /// #002 (FR-010 / US5): fraction of chunks with ≥1 indexed entity, in
+ /// `[0.0, 1.0]`. Near 0 with `total_chunks > 0` means extraction is
+ /// producing no structure. `None` when the metric could not be measured
+ /// (DB read error) — deliberately distinct from a genuine `0.0` so a
+ /// broken measurement is never misreported as a structure failure.
+ ///
+ /// `#[serde(default)]` and **no** `skip_serializing_if`: the field is
+ /// emitted as `null`, which is what this RPC has always sent and what the
+ /// CLI and the agent tool read.
+ #[serde(default)]
+ pub extraction_coverage: Option<f32>,
+}
+
+/// The full diagnostic. `first_blocking_cause` is the failure of the first
+/// non-ok stage in pipeline order (`stages` is already ordered), so a caller
+/// can act on one thing; `healthy` is the convenience roll-up.
+// No `Eq`: transitively contains `DoctorCounters` (Option<f32> — f32: !Eq).
+#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
+pub struct DoctorReport {
+ pub healthy: bool,
+ pub stages: Vec<StageHealth>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub first_blocking_cause: Option<PipelineFailure>,
+ pub degraded: DegradedState,
+ pub counters: DoctorCounters,
+}
+
+/// Carry one of the driver's classified failures across as this host's typed
+/// one.
+///
+/// [`DiagnosisFailure::code`] and `class` are open-vocabulary strings on the
+/// contract, and they are exactly the snake_case spellings [`FailureCode`] and
+/// [`FailureClass`] serialise to — the driver builds them with the engine's own
+/// `as_str`. So this is a parse, not a translation.
+///
+/// A code this build has no variant for yields `None`, which is the rule
+/// `pipeline_status`'s own `blocking_cause` already applies to a queue
+/// failure's reason: a cause this host cannot name is a cause it cannot render,
+/// and inventing a nearest-wrong-variant would put the wrong remediation text
+/// in front of the user.
+///
+/// `remediation_key` is taken from the driver rather than re-derived from the
+/// code. The two agree for this engine — both come from
+/// `FailureCode::remediation_key` — and the driver's is the authority for one
+/// that retunes.
+fn pipeline_failure(failure: &DiagnosisFailure) -> Option<PipelineFailure> {
+ let code = FailureCode::from_str(&failure.code)?;
+ let mut out = PipelineFailure::new(code);
+ // Trust the driver's class when it stated one and this build knows the
+ // spelling; otherwise keep the class derived from the code, which is what
+ // an engine that classifies without deciding a retry policy leaves absent.
+ match failure.class.as_deref() {
+ Some("transient") => out.class = FailureClass::Transient,
+ Some("unrecoverable") => out.class = FailureClass::Unrecoverable,
+ _ => {}
+ }
+ if !failure.remediation_key.is_empty() {
+ out.remediation_key = failure.remediation_key.clone();
+ }
+ // Already bounded driver-side by the same truncation this host would apply,
+ // so it is carried rather than re-truncated.
+ out.detail = failure.detail.clone();
+ Some(out)
+}
+
+/// The contract's degradation snapshot as this host's [`DegradedState`].
+///
+/// Three booleans and at most one cause, one for one. `DegradedCapabilities`
+/// is open-vocabulary only in its `cause`; the flags themselves are the same
+/// three the engine set.
+fn degraded_state_from(capabilities: &DegradedCapabilities) -> DegradedState {
+ DegradedState {
+ semantic_recall: capabilities.semantic_recall,
+ structure: capabilities.structure,
+ storage: capabilities.storage,
+ cause: capabilities.cause.as_ref().and_then(pipeline_failure),
+ }
+}
+
+/// Which capabilities the bound driver is currently running in a reduced mode.
+///
+/// # Errors
+///
+/// Whatever the driver's read failed with, and a binding that cannot be
+/// resolved. A driver with no `Maintenance` family is **not** an error: it
+/// reports no degradation, matching this RPC's other family reads
+/// (`store_stats`, `queue_stats`, `backfill_in_progress`), which all answer
+/// empty rather than failing a surface whose job is to describe the store.
+pub async fn current_degraded_state(config: &Config) -> Result<DegradedState, String> {
+ let binding = crate::openhuman::memory::binding::for_config(config)?;
+ let guard = binding.guard();
+ let Some(maintenance) = guard.as_maintenance() else {
+ log::debug!(
+ "[memory-tree][health] degraded_state: driver '{}' does not serve Maintenance; \
+ reporting no degradation",
+ binding.driver_id()
+ );
+ return Ok(DegradedState::default());
+ };
+ maintenance
+ .degraded_state()
+ .await
+ .map(|capabilities| degraded_state_from(&capabilities))
+ .map_err(|error| format!("degraded_state: {error}"))
+}
+
+/// The one-shot pipeline diagnostic, run by the bound driver.
+///
+/// Infallible by construction, the way the engine's `async_run_doctor` was: the
+/// callers are an agent tool and an RPC that both owe the user a report, and a
+/// diagnostic that refuses to answer is the least useful failure mode
+/// available. A driver that cannot be reached, does not serve `Maintenance`, or
+/// fails the call yields [`unavailable`] — the same shape the engine produced
+/// when its own blocking task died.
+pub async fn run_doctor(config: &Config) -> DoctorReport {
+ let binding = match crate::openhuman::memory::binding::for_config(config) {
+ Ok(binding) => binding,
+ Err(error) => return unavailable(&format!("memory binding unavailable: {error}")),
+ };
+ let guard = binding.guard();
+ let Some(maintenance) = guard.as_maintenance() else {
+ return unavailable(&format!(
+ "driver '{}' does not serve Maintenance",
+ binding.driver_id()
+ ));
+ };
+ match maintenance.diagnose().await {
+ Ok(diagnosis) => doctor_report(diagnosis),
+ Err(error) => {
+ log::warn!("[memory-tree][health] doctor: diagnosis failed: {error}");
+ unavailable(&error.to_string())
+ }
+ }
+}
+
+/// The driver's [`Diagnosis`] in the shape this RPC has always returned.
+fn doctor_report(diagnosis: Diagnosis) -> DoctorReport {
+ DoctorReport {
+ healthy: diagnosis.healthy,
+ stages: diagnosis
+ .stages
+ .into_iter()
+ .map(|stage| StageHealth {
+ stage: stage.stage,
+ ok: stage.ok,
+ failure: stage.failure.as_ref().and_then(pipeline_failure),
+ note: stage.note,
+ })
+ .collect(),
+ first_blocking_cause: diagnosis
+ .first_blocking_cause
+ .as_ref()
+ .and_then(pipeline_failure),
+ degraded: degraded_state_from(&diagnosis.degraded),
+ counters: DoctorCounters {
+ total_chunks: diagnosis.counters.total_chunks,
+ jobs_ready: diagnosis.counters.jobs_ready,
+ jobs_running: diagnosis.counters.jobs_running,
+ jobs_failed: diagnosis.counters.jobs_failed,
+ extraction_coverage: diagnosis.counters.extraction_coverage,
+ },
+ }
+}
+
+/// The report for a diagnosis that could not be run at all.
+///
+/// `healthy: false` with a transient cause and no stages, which is what the
+/// engine's own `async_run_doctor` answered when its blocking task died — a
+/// shaped report rather than an error, because every caller expects one. The
+/// degradation snapshot is left at its default: the flags belong to the same
+/// driver, so one that could not answer the diagnosis cannot answer them
+/// either, and a second round trip on a failure path would only fail again.
+fn unavailable(reason: &str) -> DoctorReport {
+ DoctorReport {
+ healthy: false,
+ stages: Vec::new(),
+ // The reason rides `detail`, which is the field that exists for exactly
+ // this — non-localised, operator-facing, never a secret. The engine's
+ // fallback carried none, so the surfaces that resolve `remediation_key`
+ // are unaffected either way.
+ first_blocking_cause: Some(
+ PipelineFailure::new(FailureCode::Transient).with_detail(reason),
+ ),
+ degraded: DegradedState::default(),
+ counters: DoctorCounters::default(),
+ }
+}
+
+#[cfg(test)]
+#[path = "report_tests.rs"]
+mod tests;
diff --git a/src/openhuman/memory/tree/health/report_tests.rs b/src/openhuman/memory/tree/health/report_tests.rs
new file mode 100644
index 0000000000..a34cd54882
--- /dev/null
+++ b/src/openhuman/memory/tree/health/report_tests.rs
@@ -0,0 +1,216 @@
+//! Tests for the surrounding module.
+//!
+//! These pin **wire bytes**, not behaviour: the doctor report and the
+//! degradation snapshot moved from the engine's types to this host's in #5560,
+//! and the whole point of the move was that nothing downstream could tell.
+//! Every JSON literal below is what the engine's `DoctorReport` /
+//! `DegradedState` serialised to before the swap.
+
+use super::*;
+use crate::openhuman::memory::api::provider::diagnosis::{DiagnosisCounters, DiagnosisStage};
+
+/// A healthy report: `first_blocking_cause` is **omitted** (the engine's
+/// `skip_serializing_if`), `stages` is present and empty, and
+/// `counters.extraction_coverage` is present as `null` — that last one is the
+/// asymmetry with the contract's `DiagnosisCounters`, which skips it.
+#[test]
+fn healthy_report_serde_shape_is_unchanged() {
+ let report = doctor_report(Diagnosis {
+ healthy: true,
+ stages: Vec::new(),
+ first_blocking_cause: None,
+ degraded: DegradedCapabilities::default(),
+ counters: DiagnosisCounters::default(),
+ });
+
+ assert_eq!(
+ serde_json::to_value(&report).unwrap(),
+ serde_json::json!({
+ "healthy": true,
+ "stages": [],
+ "degraded": {
+ "semantic_recall": false,
+ "structure": false,
+ "storage": false,
+ },
+ "counters": {
+ "total_chunks": 0,
+ "jobs_ready": 0,
+ "jobs_running": 0,
+ "jobs_failed": 0,
+ "extraction_coverage": null,
+ },
+ })
+ );
+}
+
+/// An unhealthy one, with every optional field populated. `code` and `class`
+/// are the snake_case enum spellings, `remediation_key` is verbatim, `detail`
+/// appears only because it is `Some`, and the degradation `cause` nests the
+/// same object.
+#[test]
+fn unhealthy_report_serde_shape_is_unchanged() {
+ let failure = DiagnosisFailure {
+ code: "embeddings_unconfigured".into(),
+ class: Some("unrecoverable".into()),
+ remediation_key: "memory.health.remediation.embeddings_unconfigured".into(),
+ detail: Some("no provider".into()),
+ };
+ let report = doctor_report(Diagnosis {
+ healthy: false,
+ stages: vec![
+ DiagnosisStage {
+ stage: "storage".into(),
+ ok: true,
+ failure: None,
+ note: "memory storage path is writable".into(),
+ },
+ DiagnosisStage {
+ stage: "embeddings".into(),
+ ok: false,
+ failure: Some(failure.clone()),
+ note: "no embeddings provider".into(),
+ },
+ ],
+ first_blocking_cause: Some(failure.clone()),
+ degraded: DegradedCapabilities {
+ semantic_recall: true,
+ structure: false,
+ storage: false,
+ cause: Some(failure),
+ },
+ counters: DiagnosisCounters {
+ total_chunks: 4,
+ jobs_ready: 1,
+ jobs_running: 2,
+ jobs_failed: 3,
+ extraction_coverage: Some(0.25),
+ },
+ });
+
+ let cause = serde_json::json!({
+ "code": "embeddings_unconfigured",
+ "class": "unrecoverable",
+ "remediation_key": "memory.health.remediation.embeddings_unconfigured",
+ "detail": "no provider",
+ });
+ assert_eq!(
+ serde_json::to_value(&report).unwrap(),
+ serde_json::json!({
+ "healthy": false,
+ "stages": [
+ {
+ "stage": "storage",
+ "ok": true,
+ "note": "memory storage path is writable",
+ },
+ {
+ "stage": "embeddings",
+ "ok": false,
+ "failure": cause,
+ "note": "no embeddings provider",
+ },
+ ],
+ "first_blocking_cause": cause,
+ "degraded": {
+ "semantic_recall": true,
+ "structure": false,
+ "storage": false,
+ "cause": cause,
+ },
+ "counters": {
+ "total_chunks": 4,
+ "jobs_ready": 1,
+ "jobs_running": 2,
+ "jobs_failed": 3,
+ "extraction_coverage": 0.25,
+ },
+ })
+ );
+}
+
+/// The degradation snapshot on its own — the object
+/// `pipeline_status.degraded` carries. Its `cause` is omitted when absent, and
+/// `storage` is always present (the engine's `#[serde(default)]` has no
+/// `skip_serializing_if`).
+#[test]
+fn degraded_snapshot_serde_shape_is_unchanged() {
+ let clear = degraded_state_from(&DegradedCapabilities::default());
+ assert_eq!(
+ serde_json::to_value(&clear).unwrap(),
+ serde_json::json!({
+ "semantic_recall": false,
+ "structure": false,
+ "storage": false,
+ })
+ );
+ assert!(!clear.is_degraded());
+
+ let degraded = degraded_state_from(&DegradedCapabilities {
+ semantic_recall: false,
+ structure: false,
+ storage: true,
+ cause: Some(DiagnosisFailure {
+ code: "storage_unavailable".into(),
+ class: None,
+ remediation_key: "memory.health.remediation.storage_unavailable".into(),
+ detail: None,
+ }),
+ });
+ assert_eq!(
+ serde_json::to_value(&degraded).unwrap(),
+ serde_json::json!({
+ "semantic_recall": false,
+ "structure": false,
+ "storage": true,
+ "cause": {
+ "code": "storage_unavailable",
+ "class": "unrecoverable",
+ "remediation_key": "memory.health.remediation.storage_unavailable",
+ },
+ })
+ );
+}
+
+/// A class the driver did not state falls back to the one this build derives
+/// from the code, and a code this build has no variant for drops the cause
+/// entirely rather than rendering a nearest-wrong remediation.
+#[test]
+fn failure_parse_falls_back_on_class_and_refuses_an_unknown_code() {
+ let derived = pipeline_failure(&DiagnosisFailure {
+ code: "extraction_timeout".into(),
+ class: None,
+ remediation_key: "memory.health.remediation.extraction_timeout".into(),
+ detail: None,
+ })
+ .expect("a known code parses");
+ assert_eq!(derived.code, FailureCode::ExtractionTimeout);
+ assert_eq!(derived.class, FailureClass::Transient);
+
+ assert!(pipeline_failure(&DiagnosisFailure {
+ code: "a_cause_this_build_has_never_heard_of".into(),
+ class: Some("transient".into()),
+ remediation_key: "whatever".into(),
+ detail: None,
+ })
+ .is_none());
+}
+
+/// A diagnosis that could not be run answers with a report rather than an
+/// error — the shape the engine's own blocking-task fallback produced, plus the
+/// reason on `detail`.
+#[test]
+fn unavailable_report_is_shaped_not_empty() {
+ let report = unavailable("driver 'null' does not serve Maintenance");
+ assert!(!report.healthy);
+ assert!(report.stages.is_empty());
+ let cause = report.first_blocking_cause.expect("a transient cause");
+ assert_eq!(cause.code, FailureCode::Transient);
+ assert_eq!(cause.class, FailureClass::Transient);
+ assert!(cause
+ .detail
+ .as_deref()
+ .is_some_and(|detail| detail.contains("does not serve Maintenance")));
+ assert_eq!(report.degraded, DegradedState::default());
+ assert_eq!(report.counters, DoctorCounters::default());
+}
diff --git a/src/openhuman/memory/tree/mod.rs b/src/openhuman/memory/tree/mod.rs
index 85db4f8301..ebbc773912 100644
--- a/src/openhuman/memory/tree/mod.rs
+++ b/src/openhuman/memory/tree/mod.rs
@@ -11,27 +11,34 @@
//! `tree_runtime`) are shadowed by the `pub mod` declarations below — an
//! explicit item beats a glob import — so its live contribution is narrower
//! than it looks. **Measured by deleting the line and reading the compiler**,
-//! rather than by grepping for the paths, the production surface is now two
-//! names in two files:
+//! rather than by grepping for the paths, the production surface is now
+//! **empty**. The two names that pinned it are both gone:
//!
-//! - `score` — `read_rpc::entities` reaches `score::store` and
-//! `score::DEFAULT_DROP_THRESHOLD` for the chunk-score RPC.
-//! - `summarise` — `agent::harness::archivist::recap` reaches
-//! `summarise::{summarise, SummaryContext, SummaryInput}`.
+//! - `score` — `read_rpc::entities` reached `score::store` and
+//! `score::DEFAULT_DROP_THRESHOLD` for the chunk-score RPC. That is
+//! `MemoryChunks::chunk_score` and the contract's own
+//! `DEFAULT_DROP_THRESHOLD` since #5560.
+//! - `summarise` — `agent::harness::archivist::recap` reached
+//! `summarise::{summarise, SummaryContext, SummaryInput}`. That is
+//! `MemoryTree::summarise` and the contract's owned DTOs now; only the
+//! recap's `#[cfg(test)]` arm still names the engine's, because the
+//! deterministic chat provider those tests install is a task-local *inside*
+//! the engine crate this binary links for tests.
//!
-//! Everything else the glob carries is now test-only or unreferenced.
-//! `ingest` (`ingest_summary` / `SummaryIngestInput`) survives for
+//! So everything the glob still carries is test-only. `ingest`
+//! (`ingest_summary` / `SummaryIngestInput`) survives for
//! `tests/memory_sync_pipeline_e2e.rs`, `score::{embed, extract, resolver,
-//! signals}` and `summarise::fallback_summary` for the raw-coverage suites,
-//! and `nlp` and `graph` have no caller under this path at all — `nlp`
-//! **used** to be reached from `retrieval/rpc.rs` and no longer is. A glob is
-//! all-or-nothing, so the unused names ride along with the two that are left.
+//! signals, store}` and `summarise::{summarise, fallback_summary}` for the
+//! raw-coverage suites and this crate's own `*_tests.rs`, and `nlp` and
+//! `graph` have no caller under this path at all — `nlp` **used** to be
+//! reached from `retrieval/rpc.rs` and no longer is. A glob is all-or-nothing,
+//! so the unused names ride along.
//!
-//! Neither survivor has a contract equivalent: `tinymemory_api::tree` is the
-//! summary-node vocabulary, not an embedder and not an entity extractor. So
-//! this shim is pinned by the engine's *scoring and summarisation* internals
-//! reached from two files outside this directory, and it goes when those two
-//! move — not before.
+//! Nothing left here has a contract equivalent, and none is wanted:
+//! `tinymemory_api::tree` is the summary-node vocabulary, not an embedder and
+//! not an entity extractor. This shim is now pinned purely by test targets, and
+//! it goes when those stop asserting against an in-process engine — which is a
+//! decision about how the raw-coverage suites are written, not a routing pass.
//!
//! The seven `Tree{LabelStrategy, LeafPayload, ReadHit, ReadRequest,
//! ReadResult, WriteOutcome, WriteRequest}` I/O types were re-exported here
@@ -48,7 +55,8 @@
// `graph`, which the glob carries because a glob is all-or-nothing.
// `tinymemory_api::tree` is the summary-node vocabulary — not an embedder and
// not an entity extractor — so there is nothing on the contract to route these
-// at. Two production files pin it; see the module docs above for which.
+// at. **No production file pins it any more**; see the module docs above for
+// what does.
pub use tinymemory_core::tree::*;
pub mod health;
diff --git a/src/openhuman/memory/tree/tree/rpc_part_02.rs b/src/openhuman/memory/tree/tree/rpc_part_02.rs
index c28d0b291e..e59322c66f 100644
--- a/src/openhuman/memory/tree/tree/rpc_part_02.rs
+++ b/src/openhuman/memory/tree/tree/rpc_part_02.rs
@@ -342,14 +342,31 @@ pub async fn pipeline_status_rpc(
let is_paused = config.scheduler_gate.mode == SchedulerGateMode::Off;
let is_syncing = pipeline_jobs.running > 0;
- // #002: read the process-global degradation snapshot (set by the embed /
- // extract stages) so a half-working sync surfaces as `degraded` with a
- // cause rather than a misleading `running`. The structure-degraded latch is
- // a liveness signal ("the extraction model is timing out") kept honest at
- // its source in `extract::llm` — it self-clears on the next *completed*
+ // #002: read the degradation snapshot (set by the embed / extract stages)
+ // so a half-working sync surfaces as `degraded` with a cause rather than a
+ // misleading `running`. The structure-degraded latch is a liveness signal
+ // ("the extraction model is timing out") kept honest at its source in the
+ // driver's `extract::llm` — it self-clears on the next *completed*
// extraction (#3365), so the status surface never consults the unrelated
// `extraction_coverage` metric to second-guess it here.
- let degraded = crate::openhuman::memory::tree::health::current_degraded_state();
+ //
+ // Asked of the driver rather than of this process's statics (#5560). Those
+ // flags live inside whichever process ran the embed and extract stages, and
+ // that is the module — a `cdylib` with its own statics — so the host-side
+ // read answered all-clear no matter what the pipeline had done. Same class
+ // of bug, and same fix, as `backfill_in_progress` above.
+ //
+ // Degraded to all-clear on a read failure, matching the two other reads
+ // this handler must not fail on (`backfill_in_progress` and
+ // `latest_failed_job_failure`): a status surface that errors tells the user
+ // less than one reporting an undegraded store, and all-clear is what the
+ // host-side read answered anyway.
+ let degraded = crate::openhuman::memory::tree::health::report::current_degraded_state(config)
+ .await
+ .unwrap_or_else(|error| {
+ log::warn!("[memory-tree][rpc] pipeline_status: degraded state read failed: {error}");
+ Default::default()
+ });
let (status, reason) = derive_pipeline_status(
is_paused,
@@ -441,16 +458,20 @@ pub async fn pipeline_status_rpc(
}
/// `memory_tree_doctor` RPC handler (#002 FR-009). Runs the one-shot
-/// pipeline diagnostic and returns the [`DoctorReport`] — per-stage health,
-/// the first blocking cause, the degraded snapshot, and counters. Exposed for
-/// the agent tool + CLI so the agent can self-diagnose an empty/stalled wiki.
-/// Synchronous + cheap (config + queue counters + degraded flags), so no
-/// blocking-pool dispatch is needed.
+/// pipeline diagnostic and returns the
+/// [`DoctorReport`](crate::openhuman::memory::tree::health::report::DoctorReport)
+/// — per-stage health, the first blocking cause, the degraded snapshot, and
+/// counters. Exposed for the agent tool + CLI so the agent can self-diagnose an
+/// empty/stalled wiki.
+///
+/// The pass runs inside the driver now (`MemoryMaintenance::diagnose`), which
+/// is also where the blocking SQLite reads it makes have always been — this
+/// host no longer dispatches a blocking task for them, and the report's shape
+/// is unchanged.
pub async fn doctor_rpc(
config: &Config,
-) -> Result<RpcOutcome<crate::openhuman::memory::tree::health::DoctorReport>, String> {
- // Offload the doctor's blocking SQLite reads off the async runtime thread.
- let report = crate::openhuman::memory::tree::health::async_run_doctor(config).await;
+) -> Result<RpcOutcome<crate::openhuman::memory::tree::health::report::DoctorReport>, String> {
+ let report = crate::openhuman::memory::tree::health::report::run_doctor(config).await;
let summary = if report.healthy {
"memory_tree: doctor — healthy".to_string()
} else {
diff --git a/src/openhuman/modules/memory_part_01.rs b/src/openhuman/modules/memory_part_01.rs
index bb24b1d508..36056b228c 100644
--- a/src/openhuman/modules/memory_part_01.rs
+++ b/src/openhuman/modules/memory_part_01.rs
@@ -7,7 +7,7 @@ use tinymemory_api::capabilities::{Capabilities, Capability};
/// Checked against the registry pin by `the_capability_list_matches_the_pinned_release`,
/// so bumping the pin without re-reading the list is a red test rather than a
/// silent over-claim.
-pub(crate) const ARTIFACT_CAPABILITIES_PIN: &str = "1.13.3";
+pub(crate) const ARTIFACT_CAPABILITIES_PIN: &str = "1.13.5";
/// The capability families the **pinned artifact** actually serves.
///
@@ -138,15 +138,16 @@ use tinymemory_api::provider::types::{
SourceItem, SourceScope, StoreStats,
};
use tinymemory_api::provider::{
- AddressBookSeedOutcome, ChunkDetail, ChunkEmbedding, ChunkListRow, ChunkQuery,
- ConversationSegment, CoverWindowQuery, Diagnosis, EntityMatch, EpisodicEvent, EpisodicTurn,
- FacetType, FastRetrieveQuery, MemoryChunks, MemoryCodingSessions, MemoryCore, MemoryDiff,
- MemoryDocuments, MemoryEntities, MemoryEpisodic, MemoryGoals, MemoryGraph, MemoryIngest,
- MemoryMaintenance, MemoryPeople, MemoryPortability, MemoryProfile, MemoryProvider,
- MemoryRecall, MemoryRetrieval, MemoryScoring, MemorySourceSink, MemorySourceSync,
- MemoryToolMemory, MemoryTree, PersonHandle, PersonInteraction, PersonRecord, PersonScore,
- ProfileFacet, RankedPerson, ResolvedPerson, RetrievalHit, RetrievalResponse,
- SourceRetrievalQuery, SourceTotal, UserState,
+ AddressBookSeedOutcome, ChunkDetail, ChunkEmbedding, ChunkListRow, ChunkQuery, ChunkScore,
+ ConversationSegment, CoverWindowQuery, DegradedCapabilities, Diagnosis, EntityMatch,
+ EpisodicEvent, EpisodicTurn, FacetType, FastRetrieveQuery, MemoryChunks, MemoryCodingSessions,
+ MemoryCore, MemoryDiff, MemoryDocuments, MemoryEntities, MemoryEpisodic, MemoryGoals,
+ MemoryGraph, MemoryIngest, MemoryMaintenance, MemoryPeople, MemoryPortability, MemoryProfile,
+ MemoryProvider, MemoryRecall, MemoryRetrieval, MemoryScoring, MemorySourceSink,
+ MemorySourceSync, MemoryToolMemory, MemoryTree, PersonHandle, PersonInteraction, PersonRecord,
+ PersonScore, ProfileFacet, RankedPerson, ResolvedPerson, RetrievalHit, RetrievalResponse,
+ RootSummary, SourceIngestQuery, SourceIngestStatus, SourceRetrievalQuery, SourceTotal,
+ SummaryContext, SummaryInput, SummaryOutput, UserState,
};
use tinymemory_api::recall::OwnedRecallOpts;
use tinymemory_api::tool_memory::ToolMemoryRule;
diff --git a/src/openhuman/modules/memory_part_02.rs b/src/openhuman/modules/memory_part_02.rs
index 5dab4a6cd5..5e2498e528 100644
--- a/src/openhuman/modules/memory_part_02.rs
+++ b/src/openhuman/modules/memory_part_02.rs
@@ -118,6 +118,33 @@ impl MemoryTree for ModuleMemoryProvider {
) -> Result<Vec<TreeLeaf>, MemoryError> {
module_call!(self, "recent_leaves", "RecentLeaves", (limit, scope))
}
+ /// The one member here that costs a provider call rather than a store read,
+ /// so it is also the one whose bus deadline could bind. It rides the
+ /// default: the module clamps the fold to the `token_budget` this caller
+ /// supplied, and a summariser that outruns the deadline is the same failure
+ /// a caller must already handle — `summarise` documents a deterministic
+ /// fallback as the expected response to a model that errors or times out.
+ async fn summarise(
+ &self,
+ inputs: &[SummaryInput],
+ context: &SummaryContext,
+ ) -> Result<SummaryOutput, MemoryError> {
+ module_call!(self, "summarise", "Summarise", (inputs, context))
+ }
+ /// The wire member is `RootSummaries`; the caps are in the signature on
+ /// both sides, so the name carries only what distinguishes the call.
+ async fn root_summaries_with_caps(
+ &self,
+ per_namespace_cap: usize,
+ total_cap: usize,
+ ) -> Result<Vec<RootSummary>, MemoryError> {
+ module_call!(
+ self,
+ "root_summaries_with_caps",
+ "RootSummaries",
+ (per_namespace_cap, total_cap)
+ )
+ }
}
#[async_trait]
@@ -387,6 +414,14 @@ impl MemoryMaintenance for ModuleMemoryProvider {
async fn diagnose(&self) -> Result<Diagnosis, MemoryError> {
module_call!(self, "diagnose", "Diagnose", ())
}
+ /// The degradation flags alone — three booleans and at most one cause,
+ /// read from the atomics the module's own embed/extract/storage stages set.
+ /// Deliberately not answered from [`Self::diagnose`]'s payload: a status
+ /// light polls this, and `Diagnose` runs an aggregate scan of the chunk
+ /// table.
+ async fn degraded_state(&self) -> Result<DegradedCapabilities, MemoryError> {
+ module_call!(self, "degraded_state", "DegradedState", ())
+ }
}
/// Bus deadline for the three calls that run a whole source sync inside the
diff --git a/src/openhuman/modules/memory_part_03.rs b/src/openhuman/modules/memory_part_03.rs
index 457513dd1e..7b3bf0dba1 100644
--- a/src/openhuman/modules/memory_part_03.rs
+++ b/src/openhuman/modules/memory_part_03.rs
@@ -103,6 +103,26 @@ impl MemoryChunks for ModuleMemoryProvider {
) -> Result<Vec<SourceTotal>, MemoryError> {
module_call!(self, "source_totals", "SourceTotals", (limit, scope))
}
+ /// `Ok(None)` for a chunk the module never scored — a different fact from a
+ /// chunk that scored zero, which is why the response is an `Option` rather
+ /// than a zeroed row.
+ async fn chunk_score(&self, chunk_id: &str) -> Result<Option<ChunkScore>, MemoryError> {
+ module_call!(self, "chunk_score", "ChunkScore", (chunk_id,))
+ }
+ /// One row per query, in the order asked. The prefixes are derived from the
+ /// **host's** source registry — the module has no access to it — so they
+ /// cross as values rather than being re-derived on the far side.
+ async fn source_ingest_status(
+ &self,
+ source_prefixes: &[SourceIngestQuery],
+ ) -> Result<Vec<SourceIngestStatus>, MemoryError> {
+ module_call!(
+ self,
+ "source_ingest_status",
+ "SourceIngestStatus",
+ (source_prefixes,)
+ )
+ }
}
#[async_trait]
diff --git a/src/openhuman/modules/memory_tests.rs b/src/openhuman/modules/memory_tests.rs
index 7c3536b22b..c30cfd6e23 100644
--- a/src/openhuman/modules/memory_tests.rs
+++ b/src/openhuman/modules/memory_tests.rs
@@ -475,6 +475,54 @@ async fn the_defaulted_members_dispatch_to_the_module_instead_of_refusing() {
.await
.expect_err("a disabled host cannot succeed"),
);
+
+ // The five doors tinymemory added for the openhuman engine shed. Each is
+ // defaulted upstream, so a missing `module_call!` arm here is invisible at
+ // compile time and turns a working feature into a runtime
+ // `unsupported capability`.
+ use tinymemory_api::provider::{MemoryChunks, MemoryTree, SummaryContext};
+ refused(
+ "summarise",
+ MemoryTree::summarise(
+ &provider,
+ &[],
+ &SummaryContext {
+ tree_id: "t".into(),
+ tree_kind: "source".into(),
+ target_level: 0,
+ token_budget: 1,
+ input_token_budget: 1,
+ overhead_reserve_tokens: 0,
+ ask: None,
+ },
+ )
+ .await
+ .expect_err("a disabled host cannot succeed"),
+ );
+ refused(
+ "root_summaries_with_caps",
+ MemoryTree::root_summaries_with_caps(&provider, 1, 1)
+ .await
+ .expect_err("a disabled host cannot succeed"),
+ );
+ refused(
+ "chunk_score",
+ MemoryChunks::chunk_score(&provider, "chunk_whatever")
+ .await
+ .expect_err("a disabled host cannot succeed"),
+ );
+ refused(
+ "source_ingest_status",
+ MemoryChunks::source_ingest_status(&provider, &[])
+ .await
+ .expect_err("a disabled host cannot succeed"),
+ );
+ refused(
+ "degraded_state",
+ MemoryMaintenance::degraded_state(&provider)
+ .await
+ .expect_err("a disabled host cannot succeed"),
+ );
}
#[test]
diff --git a/src/openhuman/modules/registry_part_01.rs b/src/openhuman/modules/registry_part_01.rs
index e2b44eb724..e3028f8fc4 100644
--- a/src/openhuman/modules/registry_part_01.rs
+++ b/src/openhuman/modules/registry_part_01.rs
@@ -175,63 +175,63 @@ const TINYMEMORY: ModuleRecord = ModuleRecord {
description: "Local memory engine: store, ranked recall, and portable export",
bus_name: "ai.tinyhumans.tinymemory.Memory",
object_path: "/ai/tinyhumans/tinymemory/Memory",
- version: "1.13.3",
- release_url: "https://github.com/tinyhumansai/tinymemory/releases/tag/v1.13.3",
+ version: "1.13.5",
+ release_url: "https://github.com/tinyhumansai/tinymemory/releases/tag/v1.13.5",
assets: &[
PlatformAsset {
host_key: "ubuntu-24.04-x86_64",
- archive: "tinymemory-module-1.13.3-ubuntu-24.04-x86_64.tar.gz",
- sha256: "5a5707416c236f7240cd4c2ad721afbd21fbb96a908a7bf2ae8d0ec6a34f0804",
+ archive: "tinymemory-module-1.13.5-ubuntu-24.04-x86_64.tar.gz",
+ sha256: "3dbaf496ac2f4c19e345a5f26a1f16a7ae093304411ffb78713f12fd0e0395e0",
},
PlatformAsset {
host_key: "ubuntu-24.04-arm64",
- archive: "tinymemory-module-1.13.3-ubuntu-24.04-arm64.tar.gz",
- sha256: "8f433f77162d41197230ef79e494450c2a1f2006c79038eb51f6e097f23d374a",
+ archive: "tinymemory-module-1.13.5-ubuntu-24.04-arm64.tar.gz",
+ sha256: "c53e59be83d3b96d4b996c60071ca2bb54d941c046ef749184b1f782abdbde96",
},
PlatformAsset {
host_key: "ubuntu-22.04-x86_64",
- archive: "tinymemory-module-1.13.3-ubuntu-22.04-x86_64.tar.gz",
- sha256: "cc902b653b33386519cc8f49b33b6467d4ef8171e1bedadf71307eca03ad8aa4",
+ archive: "tinymemory-module-1.13.5-ubuntu-22.04-x86_64.tar.gz",
+ sha256: "d00289fc14fcdc072a34e5ecaccc634cc9831f37631a55330075659daddfb2f0",
},
PlatformAsset {
host_key: "ubuntu-22.04-arm64",
- archive: "tinymemory-module-1.13.3-ubuntu-22.04-arm64.tar.gz",
- sha256: "0e30b792fc196e0a61d0ccb6f3add8898eadf77258aec05bc3bf8b69a9a57055",
+ archive: "tinymemory-module-1.13.5-ubuntu-22.04-arm64.tar.gz",
+ sha256: "d0b2966aea250ca8c2c3edc2ba1c5d4504414375563c8877a2376cd9d1ecc61e",
},
PlatformAsset {
host_key: "macos-26-arm64",
- archive: "tinymemory-module-1.13.3-macos-26-arm64.tar.gz",
- sha256: "b479f72907d86024c715fa3e854cf4316ea79db5b6b21a0f144d9e0f7a0312c9",
+ archive: "tinymemory-module-1.13.5-macos-26-arm64.tar.gz",
+ sha256: "e4a300bcabca945b10f71fbe00f63104e34e7bfcd09de733e0a9aeda768221a3",
},
PlatformAsset {
host_key: "macos-26-x86_64",
- archive: "tinymemory-module-1.13.3-macos-26-x86_64.tar.gz",
- sha256: "afdb53aaf13a93733a2f347255f3840c97cc340c587193ddfc3676a3fc279b6f",
+ archive: "tinymemory-module-1.13.5-macos-26-x86_64.tar.gz",
+ sha256: "76f5b764c98cf36ae1c76604c78a699fc0c13a9abf2247479b9409c2a10d7eb8",
},
PlatformAsset {
host_key: "macos-15-arm64",
- archive: "tinymemory-module-1.13.3-macos-15-arm64.tar.gz",
- sha256: "1dc8c9efc7e46e5f0ff3703e870b8e9e8d33e3113d65c04635253de4b08df327",
+ archive: "tinymemory-module-1.13.5-macos-15-arm64.tar.gz",
+ sha256: "31bcd89fef60d83ea47aac72ff781f6657c449945a139c3e127e215b7523b4ec",
},
PlatformAsset {
host_key: "macos-15-x86_64",
- archive: "tinymemory-module-1.13.3-macos-15-x86_64.tar.gz",
- sha256: "a4d69f524da29ca1a54f8c740987419e3e718f50a2158c356d924d4f1bd3d1f6",
+ archive: "tinymemory-module-1.13.5-macos-15-x86_64.tar.gz",
+ sha256: "43b67e6b400d6a9eb7c1c74d6e4f9b7c2f0776c0f7c9a8bf87f06141716fd9f1",
},
PlatformAsset {
host_key: "windows-2025-x86_64",
- archive: "tinymemory-module-1.13.3-windows-2025-x86_64.zip",
- sha256: "f29645643fc7edc80248469db0a2974402e23e5da990daa0809815300f33e26c",
+ archive: "tinymemory-module-1.13.5-windows-2025-x86_64.zip",
+ sha256: "a793baad1e1f349cadc72d83e37ca78e239e7f566f7bdec03c4864f9e7cdf4ac",
},
PlatformAsset {
host_key: "windows-2022-x86_64",
- archive: "tinymemory-module-1.13.3-windows-2022-x86_64.zip",
- sha256: "c0ee9417f8a1b48e88ad8279cc476b79bea30343a04e735d508882e13d852361",
+ archive: "tinymemory-module-1.13.5-windows-2022-x86_64.zip",
+ sha256: "066acda50ca726b42dade90f8e665b28dd498fdc842484b253f88b4425448783",
},
PlatformAsset {
host_key: "windows-11-arm64",
- archive: "tinymemory-module-1.13.3-windows-11-arm64.zip",
- sha256: "5fd49bca118791457faf47eee26f6b955f42e4117e4dbe1c5d91bc6f8d593593",
+ archive: "tinymemory-module-1.13.5-windows-11-arm64.zip",
+ sha256: "c1f05fefcf2ba81aa0aafb07de260bb14bd389285cdb7e4bb8a3dd22220d0f98",
},
],
// Eager, unlike the two codecs above. A codec that is never asked for should
diff --git a/tests/memory_sync_pipeline_e2e.rs b/tests/memory_sync_pipeline_e2e.rs
index 07060b6179..7d2ad7b965 100644
--- a/tests/memory_sync_pipeline_e2e.rs
+++ b/tests/memory_sync_pipeline_e2e.rs
@@ -43,9 +43,12 @@ use chrono::Utc;
use tempfile::TempDir;
use openhuman_core::openhuman::config::Config;
-use openhuman_core::openhuman::memory::sources::sync::sync_source;
+// The engine's own source pipeline. `memory::sources::sync` is host-side now and
+// carries only `derive_scopes`; `sync_source` stayed upstream because nothing in
+// `src/` calls it any more (#5560).
use openhuman_core::openhuman::memory::sources::types::{MemorySourceEntry, SourceKind};
use openhuman_core::openhuman::memory::tree::ingest::{ingest_summary, SummaryIngestInput};
+use tinymemory_core::sources::sync::sync_source;
use tinymemory_core::store::content::raw::{raw_kind_dir, raw_source_dir, RawKind};
use tinymemory_core::store::trees::store as tree_store;
use tinymemory_core::store::trees::types::SUMMARY_FANOUT;
diff --git a/tests/raw_coverage/app_credentials_threads_memory_sources_raw_coverage_e2e.rs b/tests/raw_coverage/app_credentials_threads_memory_sources_raw_coverage_e2e.rs
index a1309778b2..6d9be1bc06 100644
--- a/tests/raw_coverage/app_credentials_threads_memory_sources_raw_coverage_e2e.rs
+++ b/tests/raw_coverage/app_credentials_threads_memory_sources_raw_coverage_e2e.rs
@@ -701,7 +701,7 @@ async fn round19_memory_sources_registry_readers_sync_and_reconcile_edges() {
.len(),
0
);
- let disabled_sync = memory_sources::sync::sync_source(updated.clone(), Arc::new(config.clone()))
+ let disabled_sync = tinymemory_core::sources::sync::sync_source(updated.clone(), Arc::new(config.clone()))
.await
.expect_err("disabled source rejected");
assert!(disabled_sync.contains("disabled"));
@@ -724,7 +724,7 @@ async fn round19_memory_sources_registry_readers_sync_and_reconcile_edges() {
assert!(traversal.contains("path traversal") || traversal.contains("file not found"));
let twitter = source_entry("src-twitter", SourceKind::TwitterQuery, "Tweets");
- let twitter_sync = memory_sources::sync::sync_source(
+ let twitter_sync = tinymemory_core::sources::sync::sync_source(
MemorySourceEntry {
query: Some("openhuman".to_string()),
..twitter
diff --git a/tests/raw_coverage/memory_raw_coverage_e2e.rs b/tests/raw_coverage/memory_raw_coverage_e2e.rs
index 86df008427..5038b1daa1 100644
--- a/tests/raw_coverage/memory_raw_coverage_e2e.rs
+++ b/tests/raw_coverage/memory_raw_coverage_e2e.rs
@@ -17,7 +17,10 @@ use openhuman_core::openhuman::memory::{
// test (#5560). Named on the crate directly, exactly as `upsert_chunks` below
// already is — `tinymemory-core` is a dev-dependency, which this target links.
use tinymemory_core::ingestion::IngestionState;
-use openhuman_core::openhuman::memory::sources::status::{source_status, FreshnessLabel};
+// The engine's per-source SQL read, which is what this suite seeds a store for.
+// `memory::sources::status` is host-side now and asks the bound driver, which an
+// integration test has no module to load (#5560).
+use tinymemory_core::sources::status::{source_status, FreshnessLabel};
use openhuman_core::openhuman::memory::sources::{MemorySourceEntry, SourceKind};
use tinymemory_core::store::chunks::store::upsert_chunks;
use tinymemory_core::store::chunks::types::{
diff --git a/tests/raw_coverage/memory_sources_closure_round23_raw_coverage_e2e.rs b/tests/raw_coverage/memory_sources_closure_round23_raw_coverage_e2e.rs
index 33928c3603..711813396a 100644
--- a/tests/raw_coverage/memory_sources_closure_round23_raw_coverage_e2e.rs
+++ b/tests/raw_coverage/memory_sources_closure_round23_raw_coverage_e2e.rs
@@ -231,14 +231,14 @@ async fn round23_memory_sources_status_registry_and_readers_cover_remaining_edge
)
.await
.expect("enable composio source");
- let status = memory_sources::status::source_status(&config, &composio)
+ let status = tinymemory_core::sources::status::source_status(&config, &composio)
.await
.expect("composio status");
assert_eq!(status.source_id, composio.id);
assert_eq!(status.chunks_synced, 0);
assert_eq!(
status.freshness,
- memory_sources::status::FreshnessLabel::Idle
+ tinymemory_core::sources::status::FreshnessLabel::Idle
);
let statuses = memory_sources::status::status_list(&config)
diff --git a/tests/raw_coverage/memory_threads_raw_coverage_e2e.rs b/tests/raw_coverage/memory_threads_raw_coverage_e2e.rs
index ddda395567..6f13e08b9d 100644
--- a/tests/raw_coverage/memory_threads_raw_coverage_e2e.rs
+++ b/tests/raw_coverage/memory_threads_raw_coverage_e2e.rs
@@ -32,8 +32,14 @@ use openhuman_core::openhuman::memory::query::{
use openhuman_core::openhuman::memory::sources::readers::reader_for;
use openhuman_core::openhuman::memory::sources::registry;
use openhuman_core::openhuman::memory::sources::rpc as memory_sources_rpc;
-use openhuman_core::openhuman::memory::sources::status::{source_status, FreshnessLabel};
-use openhuman_core::openhuman::memory::sources::sync::sync_source;
+// The engine's per-source SQL read, which is what this suite seeds a store for.
+// `memory::sources::status` is host-side now and asks the bound driver, which an
+// integration test has no module to load (#5560).
+use tinymemory_core::sources::status::{source_status, FreshnessLabel};
+// The engine's own source pipeline. `memory::sources::sync` is host-side now and
+// carries only `derive_scopes`; `sync_source` stayed upstream because nothing in
+// `src/` calls it any more (#5560).
+use tinymemory_core::sources::sync::sync_source;
use openhuman_core::openhuman::memory::sources::types::{
ContentType, MemorySourceEntry, SourceContent, SourceItem, SourceKind,
};
diff --git a/tests/raw_coverage/near90_closure_raw_coverage_e2e.rs b/tests/raw_coverage/near90_closure_raw_coverage_e2e.rs
index 6e9f6b11ea..4f9eecab47 100644
--- a/tests/raw_coverage/near90_closure_raw_coverage_e2e.rs
+++ b/tests/raw_coverage/near90_closure_raw_coverage_e2e.rs
@@ -30,7 +30,10 @@ use openhuman_core::openhuman::memory::{
RecallContextRequest, RecallMemoriesRequest, RecallNamespaceParams, WriteMemoryFileRequest,
};
use openhuman_core::openhuman::memory::sources::readers::SourceReader;
-use openhuman_core::openhuman::memory::sources::sync::sync_source;
+// The engine's own source pipeline. `memory::sources::sync` is host-side now and
+// carries only `derive_scopes`; `sync_source` stayed upstream because nothing in
+// `src/` calls it any more (#5560).
+use tinymemory_core::sources::sync::sync_source;
use openhuman_core::openhuman::memory::sources::{ContentType, MemorySourceEntry, SourceKind};
use openhuman_core::openhuman::threads::ops as thread_ops;
use openhuman_core::openhuman::threads::welcome_migration::migrate_welcome_agent_artifacts;
diff --git a/vendor/tinymemory b/vendor/tinymemory
index 97d3e08dfc..28d9092783 160000
--- a/vendor/tinymemory
+++ b/vendor/tinymemory
@@ -1 +1 @@
-Subproject commit 97d3e08dfc57334468e27b012922ba8996c5e306
+Subproject commit 28d9092783a5ccb997b9369e75e14937c37fe01c