Skip to content

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

Pin tinymemory v1.7.0 and route the sources, tree and flows reads through it

Shanude9972affb38
diff --git a/.github/workflows/ci-full.yml b/.github/workflows/ci-full.yml
index 23c5e47429..8f08d4e36d 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.6.0"
- memory_sha256="7b932203e56867d2c1a0cd22573bea096e664a713dddad37255f5f401affbd5e"
+ memory_version="1.7.0"
+ memory_sha256="9d45df2ea11a1207bf9ba535e32acdd5312a3256df656e21a03b6ab5da0264f4"
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 5831d6e0a2..0986db6466 100644
--- a/.github/workflows/ci-lite.yml
+++ b/.github/workflows/ci-lite.yml
@@ -749,8 +749,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.6.0"
- memory_sha256="7b932203e56867d2c1a0cd22573bea096e664a713dddad37255f5f401affbd5e"
+ memory_version="1.7.0"
+ memory_sha256="9d45df2ea11a1207bf9ba535e32acdd5312a3256df656e21a03b6ab5da0264f4"
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 5c337348e3..1d73ec37b6 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.6.0"
- memory_sha256="7b932203e56867d2c1a0cd22573bea096e664a713dddad37255f5f401affbd5e"
+ memory_version="1.7.0"
+ memory_sha256="9d45df2ea11a1207bf9ba535e32acdd5312a3256df656e21a03b6ab5da0264f4"
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.6.0"
- memory_sha256="7b932203e56867d2c1a0cd22573bea096e664a713dddad37255f5f401affbd5e"
+ memory_version="1.7.0"
+ memory_sha256="9d45df2ea11a1207bf9ba535e32acdd5312a3256df656e21a03b6ab5da0264f4"
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 4a792d65a9..0b64413edb 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -6553,7 +6553,7 @@ dependencies = [
[[package]]
name = "tinymemory"
-version = "1.4.0"
+version = "1.7.0"
dependencies = [
"anyhow",
"async-trait",
diff --git a/src/core/all_tests.rs b/src/core/all_tests.rs
index d1f2d85dde..386e5b86ae 100644
--- a/src/core/all_tests.rs
+++ b/src/core/all_tests.rs
@@ -1832,6 +1832,13 @@ fn every_capability_family_is_accounted_for_in_the_rpc_surface() {
// through `as_people()`. See
// `docs/specs/2026-08-13-memory-module-port.md` stage 2.
Capability::People => false,
+ // New in tinymemory v1.7.0, and false for the same reason as
+ // `People`: the sync and coding-session handlers still call the
+ // engine in-process rather than through `as_source_sync()` /
+ // `as_sessions()`, so gating their controllers on these families
+ // would unregister RPC methods that work today. Both flip in the
+ // change that routes those handlers through the driver.
+ Capability::SourceSync | Capability::CodingSessions => false,
// Same as `People`: the chunk-tier and retrieval primitives back
// agent tools that still call the engine in-process, so nothing is
// gated on these families yet. Both flip to reflect reality in the
diff --git a/src/core/subsystem/driver_tests.rs b/src/core/subsystem/driver_tests.rs
index bfed109867..066bf2b29c 100644
--- a/src/core/subsystem/driver_tests.rs
+++ b/src/core/subsystem/driver_tests.rs
@@ -195,11 +195,12 @@ fn every_memory_contract_capability_string_maps_into_driver_capabilities() {
assert_eq!(caps.len(), Capability::ALL.len());
// A literal, so adding a family forces a look at this test rather than
// sliding past it. 13 → 17 when the port added People, Chunks, Retrieval
- // and Profile, then 18 with Episodic. The assertion above is the
- // load-bearing one: it says the mapping is lossless, which is what makes
- // the kernel's opaque-string set able to carry the contract without
- // knowing what a memory capability is.
- assert_eq!(caps.len(), 18);
+ // and Profile, then 18 with Episodic, then 20 when tinymemory v1.7.0 added
+ // SourceSync and CodingSessions. The assertion above is the load-bearing
+ // one: it says the mapping is lossless, which is what makes the kernel's
+ // opaque-string set able to carry the contract without knowing what a
+ // memory capability is.
+ assert_eq!(caps.len(), 20);
assert!(
caps.contains("tool_memory"),
"the one non-identity snake_case family must survive"
diff --git a/src/openhuman/agent/harness/session/builder/factory.rs b/src/openhuman/agent/harness/session/builder/factory.rs
index 484005ff87..942af79613 100644
--- a/src/openhuman/agent/harness/session/builder/factory.rs
+++ b/src/openhuman/agent/harness/session/builder/factory.rs
@@ -232,6 +232,44 @@ impl Agent {
has_profile = profile.is_some(),
"[profiles] session memory subtree selected"
);
+ // ── The engine reference this file has left (#5560) ──────────────────
+ //
+ // `direct_engine_refs_tests::ALLOWED` still explains this entry as
+ // "boots the in-process engine handle (`global::init`)". That is stale:
+ // `global::init` is gone from here, and what remains is this one
+ // factory call — the *only* caller of
+ // `create_session_memory_with_local_ai` anywhere in the tree. The
+ // bypass allowlist's `.memory_handle(` entry for this file is stale for
+ // the same reason; the only `memory_handle` left below is in prose.
+ //
+ // A door onto the contract does exist —
+ // `experience::ops::DriverMemory::for_subtree(config, &memory_subdir)`
+ // hands back an `Arc<dyn Memory>` over exactly the binding
+ // `archivist_provider` resolves two statements down, so the swap is
+ // one line and would collapse two stores over one subtree into one.
+ // It is deliberately NOT taken here yet, for two reasons that need
+ // measuring rather than reasoning about:
+ //
+ // 1. **Embedder resolution differs.** This factory resolves the
+ // embedding provider from `local_embedding` + `embedding_api_key` +
+ // `embedding_routes` and applies an Ollama reachability health-gate
+ // before falling back. The bound driver resolves its own embedder
+ // from the boot policy config instead. Those two ladders are
+ // *believed* to agree; nothing here proves it, and disagreeing means
+ // vectors filed under the wrong provider signature — silent, not
+ // loud, exactly as `memory::tools::flavour` warns about the same
+ // class of mistake.
+ // 2. **The test build binds a different workspace.** Under
+ // `cfg(test)`, `binding::module_provider` pins every binding to the
+ // shared `memory::ops` test workspace and to a module that a unit
+ // test cannot `dlopen`, so a migrated session would get a driver
+ // that answers nothing where it gets a working store today. The
+ // archivist tolerates that (it degrades); a session's `Arc<dyn
+ // Memory>` is on the recall path and does not.
+ //
+ // So this is not "no contract door exists" — it is one behavioural
+ // equivalence and one test-fixture problem, both of which need the
+ // harness suite run against the change to settle.
let session_memory = memory_store::factories::create_session_memory_with_local_ai(
&config.memory,
local_embedding.as_deref(),
diff --git a/src/openhuman/agent/learning/candidate.rs b/src/openhuman/agent/learning/candidate.rs
index 57dce02b7b..b3137b7ac7 100644
--- a/src/openhuman/agent/learning/candidate.rs
+++ b/src/openhuman/agent/learning/candidate.rs
@@ -14,5 +14,31 @@
//! [`tinymemory_api::host::EvidenceRef`].
//!
//! Every existing `agent::learning::candidate::…` path keeps resolving.
+//!
+//! # The two halves, named apart (#5560)
+//!
+//! The glob below carried both, which made a contract type and a process-global
+//! look like one engine import. They are not the same ask:
+//!
+//! - the **taxonomy** ([`FacetClass`], [`CueFamily`], [`LearningCandidate`],
+//! [`EvidenceRef`]) is defined in `tinymemory-api` and merely re-exported by
+//! the engine crate, so naming the contract is the same item under a shorter
+//! chain, and these paths survive `tinymemory-core` leaving the build with no
+//! edit at any of the ~30 call sites that spell them;
+//! - the **buffer** ([`Buffer`], `global()`) is a `static`, and a `static` is
+//! not a payload. It stays where it is defined.
+
+// The taxonomy, on the contract crate. Named on `tinymemory_api` rather than
+// through `memory::api`, which deliberately re-exports only what crosses the
+// module bus — `learning` does not (see `memory::api`'s docs), and the whole
+// point of this file is that the *producer* on the far side of that bus and the
+// consumer here are not sharing a queue.
+pub use tinymemory_api::host::EvidenceRef;
+pub use tinymemory_api::learning::{CueFamily, FacetClass, LearningCandidate};
+// The buffer, still the engine's. `tinymemory-api` is dependency-light by
+// contract and the queue needs `parking_lot`, so this cannot follow the types
+// down — and it is the line that keeps this file on the direct-reference
+// allowlist. An explicit `use` shadows a glob, so the four names above win over
+// the identical ones this would supply.
pub use tinymemory_core::learning_candidate::*;
diff --git a/src/openhuman/flows/builder_tools.rs b/src/openhuman/flows/builder_tools.rs
index 469040365e..7cd59457cc 100644
--- a/src/openhuman/flows/builder_tools.rs
+++ b/src/openhuman/flows/builder_tools.rs
@@ -1463,8 +1463,16 @@ impl Tool for ListConnectableToolkitsTool {
}
async fn execute(&self, _args: Value) -> anyhow::Result<ToolResult> {
- use crate::openhuman::memory::sync::composio::providers::agent_ready_toolkits;
- tracing::debug!(target: "flows", "[flows] list_connectable_toolkits: listing toolkits + connected state (read-only)");
+ // The contract crate, not `memory::sync::composio::providers` (#5560).
+ // That host shim is `pub use tinymemory_core::sync::composio::providers::*`
+ // and the engine's `providers` module in turn re-exports this function
+ // verbatim from `tinymemory_api::composio::scopes` — so the two paths
+ // name the SAME item and this is a path change with no behaviour delta.
+ // Naming the contract directly is what lets the shim's caller list
+ // shrink to the sites that genuinely need the engine's registry and
+ // curated catalogs.
+ use tinymemory_api::composio::agent_ready_toolkits;
+ tracing::debug!(target: "flows", "[flows] list_connectable_toolkits: listing toolkits + connected state (read-only) via the memory contract");
let connected = ops::connected_toolkits(&self.config).await;
let toolkits: Vec<Value> = agent_ready_toolkits()
.into_iter()
@@ -1815,7 +1823,7 @@ const MAX_CATALOG_RESULTS: usize = 40;
/// in `query` (case-insensitive AND). When `toolkit` is set, only that
/// toolkit is scanned — this is how the builder can search ANY named app
/// (connected or not) rather than only the toolkits already
-/// [`agent_ready_toolkits`](crate::openhuman::memory::sync::composio::providers::agent_ready_toolkits);
+/// `tinymemory_api::composio::agent_ready_toolkits`;
/// with no `toolkit` filter, the search is scoped to that agent-ready set (a
/// bare keyword query with no app named would otherwise have to fan out to
/// every toolkit Composio knows about).
@@ -1901,7 +1909,9 @@ pub(crate) async fn search_catalog(
limit: usize,
) -> CatalogSearchOutcome {
use crate::openhuman::flows::tinyflows::caps::fetch_live_toolkit_catalog;
- use crate::openhuman::memory::sync::composio::providers::agent_ready_toolkits;
+ // Contract crate — same item the `memory::sync::composio::providers` shim
+ // re-exported; see `ListConnectableToolkitsTool::execute` for why (#5560).
+ use tinymemory_api::composio::agent_ready_toolkits;
let terms: Vec<String> = query
.split_whitespace()
@@ -2229,9 +2239,10 @@ impl Tool for GetToolContractTool {
Some(s) if !s.is_empty() => s.to_string(),
_ => return Ok(ToolResult::error("Missing 'slug' parameter".to_string())),
};
- let Some(toolkit) =
- crate::openhuman::memory::sync::composio::providers::toolkit_from_slug(&slug)
- else {
+ // Contract crate — `toolkit_from_slug` is defined in
+ // `tinymemory_api::composio::scopes` and only re-exported by the engine's
+ // providers module, so this names the same function (#5560).
+ let Some(toolkit) = tinymemory_api::composio::toolkit_from_slug(&slug) else {
return Ok(ToolResult::error(format!(
"Could not extract a toolkit from slug '{slug}' — it must look like \
'<TOOLKIT>_<ACTION>' (e.g. 'GMAIL_SEND_EMAIL')."
diff --git a/src/openhuman/flows/ops.rs b/src/openhuman/flows/ops.rs
index ddb8597809..d71c423622 100644
--- a/src/openhuman/flows/ops.rs
+++ b/src/openhuman/flows/ops.rs
@@ -28,8 +28,11 @@ use crate::openhuman::security::approval::{
APPROVAL_FLOW_RUN_CONTEXT,
};
use crate::rpc::RpcOutcome;
+// `MemoryProvider` brings `driver_id()` / `as_documents()` into scope for the
+// `MemoryGuard` this file's delete path clears through. Nothing here names the
+// engine crate any more — `flows_delete_impl`'s test seam took an
+// `Arc<MemoryClient>` until #5560 and takes the guard now.
use tinymemory_api::provider::MemoryProvider;
-use tinymemory_core::store::MemoryClientRef;
/// Overall safety bound on a single `flows_run` / `flows_resume`. Individual
/// capabilities have their own timeouts (HTTP, sandbox), but a hung LLM/tool
@@ -1134,7 +1137,7 @@ pub(crate) async fn graph_wiring_warnings(config: &Config, graph: &WorkflowGraph
/// a nonsense path (e.g. suggesting `.item.json.data.successful`).
async fn graph_output_field_warnings(config: &Config, graph: &WorkflowGraph) -> Vec<String> {
use crate::openhuman::flows::tinyflows::caps::fetch_live_toolkit_catalog;
- use crate::openhuman::memory::sync::composio::providers::toolkit_from_slug;
+ use tinymemory_api::composio::toolkit_from_slug;
let mut warnings = Vec::new();
for node in &graph.nodes {
@@ -1314,7 +1317,7 @@ async fn graph_split_out_path_warnings(config: &Config, graph: &WorkflowGraph) -
use crate::openhuman::flows::tinyflows::caps::{
apply_probe_override, fetch_live_toolkit_catalog,
};
- use crate::openhuman::memory::sync::composio::providers::toolkit_from_slug;
+ use tinymemory_api::composio::toolkit_from_slug;
let mut warnings = Vec::new();
for node in &graph.nodes {
@@ -2408,6 +2411,14 @@ pub(crate) async fn validate_inference_readiness(
/// builder-tool warnings (`get_tool_contract` / `search_tool_catalog`) must all
/// agree on it — one home for the check so they cannot drift.
pub(crate) fn toolkit_has_curated_catalog(toolkit: &str) -> bool {
+ // The one site in this file that still needs the engine-backed shim, and it
+ // is not an oversight (#5560). `tinymemory-bus` deliberately kept the
+ // *shapes* (`CuratedTool`, `ToolScope`) and left the **curated catalogs and
+ // the provider registry** in the engine crate — several thousand `&'static
+ // str` action slugs and a process-global map of trait objects, which is
+ // provider data rather than wire vocabulary. `toolkit_from_slug` and
+ // friends moved and are named at `tinymemory_api::composio` above; these
+ // two cannot until the registry itself goes behind the module.
use crate::openhuman::memory::sync::composio::providers::{catalog_for_toolkit, get_provider};
get_provider(toolkit)
.and_then(|p| p.curated_tools())
@@ -2419,7 +2430,7 @@ pub(crate) async fn validate_tool_contracts(config: &Config, graph: &WorkflowGra
use crate::openhuman::flows::tinyflows::caps::{
fetch_live_toolkit_catalog, missing_required_args, unsupported_arg_names,
};
- use crate::openhuman::memory::sync::composio::providers::toolkit_from_slug;
+ use tinymemory_api::composio::toolkit_from_slug;
let mut errors = Vec::new();
for node in &graph.nodes {
@@ -2673,7 +2684,7 @@ fn validate_connection_refs_against(
graph: &WorkflowGraph,
connections: Option<&[FlowConnection]>,
) -> Vec<String> {
- use crate::openhuman::memory::sync::composio::providers::toolkit_from_slug;
+ use tinymemory_api::composio::toolkit_from_slug;
let mut errors = Vec::new();
for node in &graph.nodes {
@@ -4153,20 +4164,32 @@ pub async fn flows_delete(config: &Config, id: &str) -> Result<RpcOutcome<Value>
flows_delete_impl(config, id, None).await
}
-/// Backs [`flows_delete`]. `memory_client_override`, when `Some`, is used in
-/// place of the process-global memory client for the namespace-clear step
-/// below — mirrors `bus::FlowRunDigestSubscriber`'s `with_memory` seam.
+/// Backs [`flows_delete`]. `memory_override`, when `Some`, is the guarded
+/// driver used for the namespace-clear step below in place of the one
+/// `memory::ops::guard::active_memory_guard` resolves — the same seam, and now
+/// the same type, as `bus::FlowRunDigestSubscriber`'s `with_memory`.
///
-/// The process-global client (`memory::global`) is a single shared `OnceLock`
-/// that any test in the binary may rebind to its own tempdir workspace, so a
-/// test asserting this clear step deterministically must not depend on it —
-/// injecting a directly-constructed [`MemoryClientRef`] lets the test seed
-/// and read back through the SAME instance `flows_delete` itself writes to,
-/// with no race against the global.
+/// # Why an override at all
+///
+/// `active_memory_guard` resolves the ambient `CoreContext`'s workspace, and a
+/// pre-boot unit test has no context — it falls back to the single shared test
+/// workspace that every `memory::ops` fixture writes into, not to the
+/// `tempdir` this call's `config` names. A test asserting that *this* clear
+/// step ran therefore has to be handed the binding over its own workspace, or
+/// it is asserting against a store it never wrote to.
+///
+/// # What changed (#5560)
+///
+/// This used to take a `tinymemory_core::store::MemoryClientRef` — a direct
+/// handle on the in-process engine, and the only reason this file named the
+/// engine crate at all. It is an `Arc<MemoryGuard>` now, so the injected path
+/// and the resolved path are the same type running the same policy steps; the
+/// override can no longer be a second, unguarded door into memory. Production
+/// still passes `None`.
async fn flows_delete_impl(
config: &Config,
id: &str,
- memory_client_override: Option<MemoryClientRef>,
+ memory_override: Option<Arc<crate::openhuman::memory::guard::MemoryGuard>>,
) -> Result<RpcOutcome<Value>, String> {
match store::get_flow(config, id) {
Ok(Some(flow)) => unbind_trigger(config, &flow),
@@ -4200,22 +4223,27 @@ async fn flows_delete_impl(
// entries or run digests behind. Never fails the delete itself: the flow
// row is already gone by this point regardless of what happens here.
let memory_namespace = flow_namespace(id);
- let clear_result = if let Some(client) = memory_client_override {
- client
- .clear_namespace(&memory_namespace)
- .await
- .map_err(|error| error.to_string())
- } else {
- match crate::openhuman::memory::ops::guard::active_memory_guard().await {
- Ok(guard) => match guard.as_documents() {
+ let guard = match memory_override {
+ Some(guard) => Ok(guard),
+ None => crate::openhuman::memory::ops::guard::active_memory_guard().await,
+ };
+ let clear_result = match guard {
+ Ok(guard) => {
+ tracing::debug!(target: "flows", flow_id = %id, namespace = %memory_namespace, driver = %guard.driver_id(), "[flows] flows_delete: clearing flow memory namespace through the bound driver");
+ match guard.as_documents() {
Some(documents) => documents
.clear_namespace(&memory_namespace)
.await
.map_err(|error| error.to_string()),
- None => Err("memory driver does not support the documents family".to_string()),
- },
- Err(error) => Err(error),
+ // Name the driver: "does not support" with no subject reads as
+ // a host bug, and the actual fact is which driver is bound.
+ None => Err(format!(
+ "the bound memory driver '{}' does not serve the documents family",
+ guard.driver_id()
+ )),
+ }
}
+ Err(error) => Err(error),
};
if let Err(error) = clear_result {
tracing::warn!(target: "flows", flow_id = %id, namespace = %memory_namespace, %error, "[flows] flows_delete: failed to clear flow memory namespace");
@@ -7598,7 +7626,7 @@ pub(crate) async fn connected_toolkits(config: &Config) -> std::collections::Has
/// `oh:` tools and `http_request` nodes need no Composio connection and are
/// skipped.
pub async fn compute_required_connections(config: &Config, graph: &WorkflowGraph) -> Vec<Value> {
- use crate::openhuman::memory::sync::composio::providers::toolkit_from_slug;
+ use tinymemory_api::composio::toolkit_from_slug;
// Collect required toolkits (deduped, order-preserving).
let mut required: Vec<String> = Vec::new();
@@ -7953,9 +7981,7 @@ pub async fn flows_get_tool_contract(
slug: &str,
) -> Result<RpcOutcome<Value>, String> {
let slug = slug.trim();
- let Some(toolkit) =
- crate::openhuman::memory::sync::composio::providers::toolkit_from_slug(slug)
- else {
+ let Some(toolkit) = tinymemory_api::composio::toolkit_from_slug(slug) else {
return Err(format!(
"Could not extract a toolkit from slug '{slug}' — it must look like \
'<TOOLKIT>_<ACTION>' (e.g. 'GMAIL_SEND_EMAIL')."
diff --git a/src/openhuman/flows/ops_tests.rs b/src/openhuman/flows/ops_tests.rs
index 946a126a16..d71c1a0618 100644
--- a/src/openhuman/flows/ops_tests.rs
+++ b/src/openhuman/flows/ops_tests.rs
@@ -1585,22 +1585,31 @@ async fn reconcile_schedule_triggers_on_boot_survives_a_corrupt_row() {
#[tokio::test]
async fn flows_delete_clears_flow_memory_namespace() {
use crate::openhuman::memory::{MemoryCategory, MemoryTaint};
- use tinymemory_core::store::MemoryClient;
+ use tinymemory_api::provider::MemoryCore;
let tmp = TempDir::new().unwrap();
let config = test_config(&tmp);
- crate::openhuman::memory::host_impls::install_for_tests();
- // A directly-constructed `MemoryClient`, injected via `flows_delete_impl`
- // below, instead of `memory::global` — that singleton is a single
- // process-wide `OnceLock` any other test in this binary may rebind to
- // its own tempdir workspace, which would make this test's pass/fail
- // depend on run order / thread interleaving rather than its own setup.
- // See `flows_delete_impl`'s doc comment (mirrors
- // `bus::FlowRunDigestSubscriber::with_memory`'s injection seam).
- let memory_client: MemoryClientRef =
- Arc::new(MemoryClient::from_workspace_dir(config.workspace_dir.clone()).unwrap());
- let memory = memory_client.memory_handle();
+ // Bind a real driver over *this test's own* workspace and drive both the
+ // seeding and the assertion through its guard.
+ //
+ // Two things make the binding necessary rather than incidental. An unbound
+ // config resolves to the null driver, which serves no families at all, so
+ // the clear step under test would degrade instead of running. And
+ // `active_memory_guard` — what `flows_delete` reaches for with no override
+ // — resolves the ambient `CoreContext`, which a pre-boot unit test does not
+ // have; its fallback is the single shared `memory::ops` test workspace, not
+ // this `tempdir`. Injecting the binding's guard is what keeps the store
+ // written here and the store cleared by `flows_delete_impl` the same one.
+ //
+ // This was a directly-constructed `tinymemory_core` `MemoryClient` before
+ // #5560. Same engine underneath — `install_tinycortex_for_test` builds a
+ // `TinycortexProvider` over it — but reached through the contract, so the
+ // fixture no longer holds an unguarded door into memory.
+ crate::openhuman::memory::test_support::install_tinycortex_for_test(&config);
+ let memory = crate::openhuman::memory::binding::for_config(&config)
+ .expect("bind the memory driver for this test's workspace")
+ .guard();
let created = flows_create(
&config,
@@ -1612,8 +1621,10 @@ async fn flows_delete_clears_flow_memory_namespace() {
.unwrap();
let flow_id = created.value.id.clone();
+ // `store` carries the taint on the contract — the engine trait's separate
+ // `store_with_taint` door does not exist here, and does not need to.
memory
- .store_with_taint(
+ .store(
&flow_namespace(&flow_id),
"sent_item_1",
"Sent item 1",
@@ -1629,11 +1640,11 @@ async fn flows_delete_clears_flow_memory_namespace() {
.await
.unwrap()
.is_some(),
- "precondition: flow memory entry was stored (through the SAME client flows_delete_impl \
+ "precondition: flow memory entry was stored (through the SAME driver flows_delete_impl \
is about to clear)"
);
- flows_delete_impl(&config, &flow_id, Some(memory_client))
+ flows_delete_impl(&config, &flow_id, Some(memory.clone()))
.await
.unwrap();
diff --git a/src/openhuman/integrations/composio/ops_tests.rs b/src/openhuman/integrations/composio/ops_tests.rs
index c2cf24f13e..ae4d3d9a98 100644
--- a/src/openhuman/integrations/composio/ops_tests.rs
+++ b/src/openhuman/integrations/composio/ops_tests.rs
@@ -930,6 +930,10 @@ async fn notion_cleanup_targets_include_synced_page_sources() {
MemoryClient::from_workspace_dir(config.workspace_dir.clone())
.expect("memory client should initialise"),
);
+ // `save` is the extension trait, not an inherent method: `SyncState` moved
+ // to the contract crate in v1.7.0, which stays free of I/O, so persistence
+ // stayed behind in the engine.
+ use tinymemory_core::sync::composio::providers::sync_state::PersistedSyncState;
let mut state = SyncState::new("notion", "conn-1");
state.mark_synced("page-a@2026-01-01T00:00:00Z");
state.mark_synced("page-b");
diff --git a/src/openhuman/memory/bypass_allowlist_tests.rs b/src/openhuman/memory/bypass_allowlist_tests.rs
index 62ac7a9851..abe1fe67c8 100644
--- a/src/openhuman/memory/bypass_allowlist_tests.rs
+++ b/src/openhuman/memory/bypass_allowlist_tests.rs
@@ -76,19 +76,21 @@ use std::path::{Path, PathBuf};
/// `global::init(` is deliberately absent. It binds a workspace; it does not
/// read or write memory, and every call site is a login / user-switch / boot /
/// CLI-entry lifecycle event. See `docs/specs/memory-guard-allowlist.md`.
+// Three needles were retired in #5560 rather than renamed, and the distinction
+// matters: `active_memory_client(`, `global::client(` and `.memory_handle(` all
+// named ways of getting an undecorated `MemoryClient` out of the process-global
+// engine slot. That slot is gone — the host no longer boots an in-process
+// engine at all — so there is no longer an API to rename them to. They matched
+// nothing, and a needle that matches nothing is a guard that guards nothing.
+//
+// `global::client_if_ready(` survives because it still matches: the remaining
+// callers are test fixtures, which the scanner reaches but production no longer
+// does.
const BYPASS_PATTERNS: &[(&str, &str)] = &[
- (
- "active_memory_client(",
- "resolves a MemoryClientRef with no policy decorator",
- ),
(
"global::client_if_ready(",
"process-global MemoryClient, no policy decorator",
),
- (
- "global::client(",
- "process-global MemoryClient, no policy decorator",
- ),
(
".profile_conn(",
"raw rusqlite connection — undecoratable by construction",
@@ -97,10 +99,6 @@ const BYPASS_PATTERNS: &[(&str, &str)] = &[
".profile_store(",
"typed profile store — the profile/facet tables have no capability family, so these reads and writes still skip the guard's seven steps",
),
- (
- ".memory_handle(",
- "raw Arc<dyn Memory> — bypasses the MemoryClient API surface",
- ),
(
".get_document(",
"pub(crate) read-one escape hatch, driver-only by contract",
@@ -168,21 +166,6 @@ const ALLOWED: &[(&str, &str, &str)] = &[
"the per-workspace bind site — guarding it would be a cycle",
),
// ── Needs a concrete engine type the contract does not expose ──
- (
- "src/openhuman/agent/experience/ops.rs",
- ".memory_handle(",
- "AgentExperienceStore::new takes Arc<dyn Memory>; no contract door for it",
- ),
- (
- "src/openhuman/agent/experience/ops.rs",
- "global::client_if_ready(",
- "same store; also builds a per-profile UnifiedMemory the binding cannot model",
- ),
- (
- "src/openhuman/agent/harness/session/builder/factory.rs",
- ".memory_handle(",
- "session builder needs Arc<dyn Memory>; no contract door for it",
- ),
// ── Profile/facet access ──
//
// The five `.profile_store(` / `global::client_if_ready(` entries that
@@ -229,16 +212,6 @@ const ALLOWED: &[(&str, &str, &str)] = &[
"binding::for_workspace(",
"the guarded resolver; this is where the binding becomes a guard",
),
- (
- "src/openhuman/memory/ops/helpers.rs",
- "active_memory_client(",
- "defines active_memory_client — the unguarded twin of ops::guard",
- ),
- (
- "src/openhuman/memory/ops/helpers.rs",
- "global::client_if_ready(",
- "same definition site",
- ),
(
"src/openhuman/memory/ops/provider.rs",
".memory_binding(",
@@ -254,16 +227,6 @@ const ALLOWED: &[(&str, &str, &str)] = &[
"binding::for_workspace(",
"same status surface",
),
- (
- "src/openhuman/memory/ops/sync.rs",
- "global::client_if_ready(",
- "ingestion_state().snapshot() — queue telemetry, absent from the contract",
- ),
- (
- "src/openhuman/memory/ops/sync.rs",
- "global::client(",
- "inline #[cfg(test)] module only; the scanner does not brace-track test blocks",
- ),
(
"vendor/tinymemory/crates/tinymemory-core/src/store/client.rs",
".profile_conn(",
diff --git a/src/openhuman/memory/diff/mod.rs b/src/openhuman/memory/diff/mod.rs
index 258e2302d6..869ca87d79 100644
--- a/src/openhuman/memory/diff/mod.rs
+++ b/src/openhuman/memory/diff/mod.rs
@@ -42,6 +42,28 @@
//! translating at the handler would change the RPC payloads, which is a
//! behaviour change, not a migration.
+// The eight wire types, named at the crate that defines them. They are
+// `tinycortex::memory::diff::types` — `tinymemory_core::diff` re-exports them
+// out of its `engine::backend::diff::types`, which is that same module — so
+// this is the identical item under a different crate alias, and an explicit
+// `use` shadows the glob below with itself. `rpc.rs` and `tools/diff.rs`
+// already spell them this way; saying it here too means the flat
+// `memory::diff::ChangeKind` paths keep resolving when `tinymemory-core`
+// leaves the build, with no edit at any call site.
+//
+// Ungated on both sides of `memory-git`, mirroring tinycortex's own carve-out:
+// these are serde-only values that always-on callers (the subconscious memory
+// profile renders `CrossSourceDiff` and `ChangeKind` into prompts) name in a
+// slim build too.
+pub use tinycortex::memory::diff::types::{
+ ChangeKind, Checkpoint, CrossSourceDiff, DiffResult, DiffSummary, ItemChange, Snapshot,
+ SnapshotTrigger,
+};
+
+// What is left of the glob, and all that pins it: `ops` (or its `memory-git`-off
+// stub) and `source`. Both are `tinymemory-core`'s own — see the header above
+// for why neither can come home ahead of `memory::sources`, and why
+// `MemoryDiff` covers three of `ops`' ten entry points rather than replacing it.
pub use tinymemory_core::diff::*;
#[cfg(feature = "memory-git")]
diff --git a/src/openhuman/memory/direct_engine_refs_tests.rs b/src/openhuman/memory/direct_engine_refs_tests.rs
index d36b146578..cdfed4f3ba 100644
--- a/src/openhuman/memory/direct_engine_refs_tests.rs
+++ b/src/openhuman/memory/direct_engine_refs_tests.rs
@@ -260,6 +260,26 @@ const NEEDLE: &str = "tinymemory_core::";
/// path — [`scan`] returns a `BTreeSet`, so keeping the literal in the same
/// order makes diffs readable.
const ALLOWED: &[(&str, Verdict, &str)] = &[
+ (
+ "src/openhuman/integrations/composio/ops/providers_ops.rs",
+ Verdict::NeedsWiderSeam,
+ "runs a composio connection sync (tinycortex::run_composio_connection). The contract's MemorySourceSync::run_connection_sync exists but the driver refuses BACKEND mode by design (EngineRuntimeConfig::session_token answers NO_BACKEND_SESSION), and backend is this product's default composio mode — routing here would break manual sync for every user who has not switched to direct",
+ ),
+ (
+ "src/openhuman/memory/ops/sync.rs",
+ Verdict::NeedsWiderSeam,
+ "manual 'sync now' path; same blocker as providers_ops.rs — run_connection_sync cannot serve the default backend mode, so this stays on the engine until the contract can carry a backend session",
+ ),
+ (
+ "src/openhuman/memory/sync/composio/bus.rs",
+ Verdict::NeedsWiderSeam,
+ "post-OAuth initial sync; same backend-mode blocker as ops/sync.rs",
+ ),
+ (
+ "src/openhuman/memory/sync/composio/providers/slack/rpc.rs",
+ Verdict::NeedsWiderSeam,
+ "slack sync trigger and status; same backend-mode blocker as ops/sync.rs",
+ ),
// ── Revealed by deleting the `memory/mod.rs` re-export facade ───────────
//
// This lint was calibrated against a tree where `memory/mod.rs` re-exported
@@ -284,26 +304,6 @@ const ALLOWED: &[(&str, Verdict, &str)] = &[
Verdict::NeedsWiderSeam,
"engine-internal ingest pipeline entry (ingest_pipeline::ingest_chat, queue::drain_until_idle); the ingest family covers documents and chat, not the scope-carrying pipeline variants",
),
- (
- "src/openhuman/agent/experience/ops.rs",
- Verdict::NeedsWiderSeam,
- "holds or boots the in-process engine handle (global::init, global::client_if_ready, store::UnifiedMemory::new_with_memory_dir); driver construction belongs to memory::binding and the seam has no door onto the live client",
- ),
- (
- "src/openhuman/agent/experience/store.rs",
- Verdict::NeedsWiderSeam,
- "holds or boots the in-process engine handle (store::UnifiedMemory); driver construction belongs to memory::binding and the seam has no door onto the live client",
- ),
- (
- "src/openhuman/agent/harness/archivist/hook_impl.rs",
- Verdict::NeedsWiderSeam,
- "reaches engine storage below the contract (store::fts5, tinycortex::memory_config_from); MemoryChunks is read-only (list_chunks/get_chunk/chunk_detail/storage_kinds/chunk_embeddings) with no write or transaction door",
- ),
- (
- "src/openhuman/agent/harness/archivist/lifecycle.rs",
- Verdict::NeedsWiderSeam,
- "reaches engine storage below the contract (store::events, store::fts5::EpisodicEntry, store::profile, store::segments, chat::build_chat_provider); MemoryChunks is read-only (list_chunks/get_chunk/chunk_detail/storage_kinds/chunk_embeddings) with no write or transaction door",
- ),
(
"src/openhuman/agent/harness/archivist/recap.rs",
Verdict::NeedsWiderSeam,
@@ -329,11 +329,6 @@ const ALLOWED: &[(&str, Verdict, &str)] = &[
Verdict::NeedsWiderSeam,
"holds or boots the in-process engine handle (global::init); driver construction belongs to memory::binding and the seam has no door onto the live client",
),
- (
- "src/openhuman/agent/harness/subagent_runner/ops/runner.rs",
- Verdict::NeedsWiderSeam,
- "names engine-owned types (store::trees::types::TreeKind); relocating them to tinymemory-api is the ask, not a bus method",
- ),
(
"src/openhuman/channels/tests/memory.rs",
Verdict::NeedsWiderSeam,
@@ -349,36 +344,11 @@ const ALLOWED: &[(&str, Verdict, &str)] = &[
Verdict::NeedsWiderSeam,
"holds or boots the in-process engine handle (store::UnifiedMemory); driver construction belongs to memory::binding and the seam has no door onto the live client",
),
- (
- "src/openhuman/flows/ops.rs",
- Verdict::NeedsWiderSeam,
- "holds or boots the in-process engine handle (store::MemoryClientRef); driver construction belongs to memory::binding and the seam has no door onto the live client",
- ),
(
"src/openhuman/integrations/composio/ops/mod.rs",
Verdict::NeedsWiderSeam,
"holds or boots the in-process engine handle (store::MemoryClient); driver construction belongs to memory::binding and the seam has no door onto the live client",
),
- (
- "src/openhuman/integrations/composio/ops/providers_ops.rs",
- Verdict::NeedsWiderSeam,
- "engine internals (tinycortex::run_composio_connection); tinycortex-shaped, so no engine-neutral family can express it",
- ),
- (
- "src/openhuman/memory/ops/helpers.rs",
- Verdict::NeedsWiderSeam,
- "holds or boots the in-process engine handle (global::client, global::client_if_ready, global::init, store::GraphRelationRecord); driver construction belongs to memory::binding and the seam has no door onto the live client",
- ),
- (
- "src/openhuman/memory/ops/sync.rs",
- Verdict::NeedsWiderSeam,
- "two blockers: engine internals (tinycortex::run_composio_connection, sync_events), tinycortex-shaped so no engine-neutral family can express them; and the in-process engine handle (global::client), which belongs to memory::binding",
- ),
- (
- "src/openhuman/memory/ops/test_support.rs",
- Verdict::NeedsWiderSeam,
- "holds or boots the in-process engine handle (global::init); driver construction belongs to memory::binding and the seam has no door onto the live client",
- ),
(
"src/openhuman/memory/read_rpc/admin.rs",
Verdict::NeedsWiderSeam,
@@ -389,36 +359,11 @@ const ALLOWED: &[(&str, Verdict, &str)] = &[
Verdict::NeedsWiderSeam,
"reaches engine storage below the contract (store::chunks::store::with_connection, store::chunks::types::SourceKind); MemoryChunks is read-only (list_chunks/get_chunk/chunk_detail/storage_kinds/chunk_embeddings) with no write or transaction door",
),
- (
- "src/openhuman/memory/sources/rpc.rs",
- Verdict::NeedsWiderSeam,
- "engine internals (tinycortex::CodingSession* request/response/status types, tinycortex::SyncAuditEntry); tinycortex-shaped, so no engine-neutral family can express it",
- ),
- (
- "src/openhuman/memory/sync/composio/bus.rs",
- Verdict::NeedsWiderSeam,
- "engine internals (events::MemoryEvent/publish, observability::report_error_or_expected, tinycortex::run_composio_connection); tinycortex-shaped, so no engine-neutral family can express it",
- ),
- (
- "src/openhuman/memory/sync/composio/providers/slack/rpc.rs",
- Verdict::NeedsWiderSeam,
- "engine internals (tinycortex::load_composio_sync_state, tinycortex::run_composio_connection); tinycortex-shaped, so no engine-neutral family can express it",
- ),
(
"src/openhuman/memory/sync/sync_status/rpc.rs",
Verdict::NeedsWiderSeam,
"engine internals (tinycortex::memory_config_from); tinycortex-shaped, so no engine-neutral family can express it",
),
- (
- "src/openhuman/memory/tools/flavour.rs",
- Verdict::NeedsWiderSeam,
- "engine internals (tinycortex::memory_config_from); tinycortex-shaped, so no engine-neutral family can express it",
- ),
- (
- "src/openhuman/memory/tree/retrieval/rpc.rs",
- Verdict::NeedsWiderSeam,
- "reaches engine storage below the contract (store::chunks::store::upsert_chunks, upsert_staged_chunks_tx, with_connection); MemoryChunks is read-only (list_chunks/get_chunk/chunk_detail/storage_kinds/chunk_embeddings) with no write or transaction door",
- ),
(
"src/openhuman/memory/tree/tree/rpc.rs",
Verdict::NeedsWiderSeam,
@@ -469,16 +414,6 @@ const ALLOWED: &[(&str, Verdict, &str)] = &[
Verdict::HostSide,
"re-export shim: pub use tinymemory_core::sync::composio::providers::slack::*",
),
- (
- "src/openhuman/memory/sync/mod.rs",
- Verdict::HostSide,
- "re-export shim: pub use tinymemory_core::sync::*",
- ),
- (
- "src/openhuman/memory/tool_memory/mod.rs",
- Verdict::HostSide,
- "re-export shim: pub use tinymemory_core::tool_memory::*",
- ),
(
"src/openhuman/memory/tree/health/mod.rs",
Verdict::HostSide,
diff --git a/src/openhuman/memory/guard/families.rs b/src/openhuman/memory/guard/families.rs
index 79ea0ec1cf..3c14c33e82 100644
--- a/src/openhuman/memory/guard/families.rs
+++ b/src/openhuman/memory/guard/families.rs
@@ -52,15 +52,22 @@ use crate::openhuman::memory::api::provider::retrieval::{
CoverWindowQuery, EntityMatch, FastRetrieveQuery, MemoryRetrieval, RetrievalHit,
RetrievalResponse, SourceRetrievalQuery,
};
+use crate::openhuman::memory::api::provider::sessions::{
+ CodingSessionIngestReport, CodingSessionIngestRequest, CodingSessionSource,
+};
+use crate::openhuman::memory::api::provider::sync::{
+ RawArchiveCoverage, RawRebuildOutcome, SourceSyncState, SourceSyncStatus, SyncAuditEntry,
+ SyncRunOutcome,
+};
use crate::openhuman::memory::api::provider::types::{
ChunkEntityOccurrence, DiffReport, EntityHit, EntityOccurrence, ForgetOutcome, ForgetSelector,
IngestItem, IngestOutcome, MaintenanceReport, PurgeOutcome, SnapshotRef, SourceItem,
SourceScope,
};
use crate::openhuman::memory::api::provider::{
- EpisodicEvent, MemoryDiff, MemoryDocuments, MemoryEntities, MemoryGoals, MemoryGraph,
- MemoryIngest, MemoryMaintenance, MemoryProvider, MemorySourceSink, MemoryToolMemory,
- MemoryTree,
+ EpisodicEvent, MemoryCodingSessions, MemoryDiff, MemoryDocuments, MemoryEntities, MemoryGoals,
+ MemoryGraph, MemoryIngest, MemoryMaintenance, MemoryProvider, MemorySourceSink,
+ MemorySourceSync, MemoryToolMemory, MemoryTree,
};
use crate::openhuman::memory::api::tool_memory::ToolMemoryRule;
use crate::openhuman::memory::api::tree::{
@@ -207,6 +214,20 @@ decorator!(
as_episodic,
Episodic
);
+decorator!(
+ /// Guarded [`MemorySourceSync`].
+ GuardedSourceSync,
+ dyn MemorySourceSync,
+ as_source_sync,
+ SourceSync
+);
+decorator!(
+ /// Guarded [`MemoryCodingSessions`].
+ GuardedCodingSessions,
+ dyn MemoryCodingSessions,
+ as_coding_sessions,
+ CodingSessions
+);
decorator!(
/// Guarded [`MemoryProfile`].
GuardedProfile,
@@ -1638,3 +1659,147 @@ impl MemoryProfile for GuardedProfile {
#[cfg(test)]
#[path = "families_tests.rs"]
mod tests;
+
+// ── Source sync ──────────────────────────────────────────────────────────────
+
+#[async_trait]
+impl MemorySourceSync for GuardedSourceSync {
+ /// A write: it fetches from an upstream connector and ingests what it finds.
+ /// The tier check is what stops a `readonly` operator triggering one.
+ async fn run_connection_sync(
+ &self,
+ toolkit: &str,
+ connection_id: &str,
+ ) -> Result<SyncRunOutcome, MemoryError> {
+ self.policy.admit_write(
+ Capability::SourceSync,
+ "source_sync.run_connection_sync",
+ NO_NAMESPACE,
+ false,
+ )?;
+ self.family()?
+ .run_connection_sync(toolkit, connection_id)
+ .await
+ }
+
+ async fn source_sync_state(
+ &self,
+ toolkit: &str,
+ connection_id: &str,
+ ) -> Result<Option<SourceSyncState>, MemoryError> {
+ self.policy.admit_read(
+ Capability::SourceSync,
+ "source_sync.source_sync_state",
+ NO_NAMESPACE,
+ false,
+ )?;
+ self.family()?
+ .source_sync_state(toolkit, connection_id)
+ .await
+ }
+
+ async fn sync_audit_log(
+ &self,
+ limit: Option<usize>,
+ ) -> Result<Vec<SyncAuditEntry>, MemoryError> {
+ self.policy.admit_read(
+ Capability::SourceSync,
+ "source_sync.sync_audit_log",
+ NO_NAMESPACE,
+ false,
+ )?;
+ self.family()?.sync_audit_log(limit).await
+ }
+
+ /// Arithmetic over the driver's own price table — no stored content is read,
+ /// so this is the lightest check in the family.
+ async fn estimate_sync_cost_usd(
+ &self,
+ input_tokens: u64,
+ output_tokens: u64,
+ ) -> Result<f64, MemoryError> {
+ self.policy.admit_read(
+ Capability::SourceSync,
+ "source_sync.estimate_sync_cost_usd",
+ NO_NAMESPACE,
+ false,
+ )?;
+ self.family()?
+ .estimate_sync_cost_usd(input_tokens, output_tokens)
+ .await
+ }
+
+ async fn sync_statuses(&self) -> Result<Vec<SourceSyncStatus>, MemoryError> {
+ self.policy.admit_read(
+ Capability::SourceSync,
+ "source_sync.sync_statuses",
+ NO_NAMESPACE,
+ false,
+ )?;
+ self.family()?.sync_statuses().await
+ }
+
+ async fn raw_archive_coverage(
+ &self,
+ tree_scope: &str,
+ archive_source_id: &str,
+ ) -> Result<RawArchiveCoverage, MemoryError> {
+ self.policy.admit_read(
+ Capability::SourceSync,
+ "source_sync.raw_archive_coverage",
+ NO_NAMESPACE,
+ false,
+ )?;
+ self.family()?
+ .raw_archive_coverage(tree_scope, archive_source_id)
+ .await
+ }
+
+ /// Rebuilds a summary tree from the raw archive, so it writes.
+ async fn rebuild_from_raw_archive(
+ &self,
+ tree_scope: &str,
+ archive_source_id: &str,
+ ) -> Result<RawRebuildOutcome, MemoryError> {
+ self.policy.admit_write(
+ Capability::SourceSync,
+ "source_sync.rebuild_from_raw_archive",
+ NO_NAMESPACE,
+ false,
+ )?;
+ self.family()?
+ .rebuild_from_raw_archive(tree_scope, archive_source_id)
+ .await
+ }
+}
+
+// ── Coding sessions ──────────────────────────────────────────────────────────
+
+#[async_trait]
+impl MemoryCodingSessions for GuardedCodingSessions {
+ async fn coding_session_status(&self) -> Result<Vec<CodingSessionSource>, MemoryError> {
+ self.policy.admit_read(
+ Capability::CodingSessions,
+ "coding_sessions.coding_session_status",
+ NO_NAMESPACE,
+ false,
+ )?;
+ self.family()?.coding_session_status().await
+ }
+
+ /// `carries_content: true` — the request carries the session transcripts
+ /// themselves, which is the case the egress record exists to classify
+ /// correctly.
+ async fn ingest_coding_sessions(
+ &self,
+ request: CodingSessionIngestRequest,
+ ) -> Result<CodingSessionIngestReport, MemoryError> {
+ self.policy.admit_write(
+ Capability::CodingSessions,
+ "coding_sessions.ingest_coding_sessions",
+ NO_NAMESPACE,
+ true,
+ )?;
+ self.family()?.ingest_coding_sessions(request).await
+ }
+}
diff --git a/src/openhuman/memory/guard/provider.rs b/src/openhuman/memory/guard/provider.rs
index 65a6e2bcaa..974172d3aa 100644
--- a/src/openhuman/memory/guard/provider.rs
+++ b/src/openhuman/memory/guard/provider.rs
@@ -6,16 +6,18 @@ use crate::openhuman::memory::api::capabilities::{Capabilities, Capability};
use crate::openhuman::memory::api::error::MemoryError;
use crate::openhuman::memory::api::health::MemoryHealth;
use crate::openhuman::memory::api::provider::{
- MemoryChunks, MemoryDiff, MemoryDocuments, MemoryEntities, MemoryEpisodic, MemoryGoals,
- MemoryGraph, MemoryIngest, MemoryMaintenance, MemoryPeople, MemoryProfile, MemoryProvider,
- MemoryRetrieval, MemorySourceSink, MemoryToolMemory, MemoryTree,
+ MemoryChunks, MemoryCodingSessions, MemoryDiff, MemoryDocuments, MemoryEntities,
+ MemoryEpisodic, MemoryGoals, MemoryGraph, MemoryIngest, MemoryMaintenance, MemoryPeople,
+ MemoryProfile, MemoryProvider, MemoryRetrieval, MemorySourceSink, MemorySourceSync,
+ MemoryToolMemory, MemoryTree,
};
use async_trait::async_trait;
use super::families::{
- GuardedChunks, GuardedDiff, GuardedDocuments, GuardedEntities, GuardedEpisodic, GuardedGoals,
- GuardedGraph, GuardedIngest, GuardedMaintenance, GuardedPeople, GuardedProfile,
- GuardedRetrieval, GuardedSources, GuardedToolMemory, GuardedTree,
+ GuardedChunks, GuardedCodingSessions, GuardedDiff, GuardedDocuments, GuardedEntities,
+ GuardedEpisodic, GuardedGoals, GuardedGraph, GuardedIngest, GuardedMaintenance, GuardedPeople,
+ GuardedProfile, GuardedRetrieval, GuardedSourceSync, GuardedSources, GuardedToolMemory,
+ GuardedTree,
};
use super::policy::GuardPolicy;
@@ -51,6 +53,8 @@ pub struct MemoryGuard {
retrieval: Option<GuardedRetrieval>,
profile: Option<GuardedProfile>,
episodic: Option<GuardedEpisodic>,
+ source_sync: Option<GuardedSourceSync>,
+ coding_sessions: Option<GuardedCodingSessions>,
}
impl MemoryGuard {
@@ -83,6 +87,8 @@ impl MemoryGuard {
retrieval: family!(Retrieval, GuardedRetrieval),
profile: family!(Profile, GuardedProfile),
episodic: family!(Episodic, GuardedEpisodic),
+ source_sync: family!(SourceSync, GuardedSourceSync),
+ coding_sessions: family!(CodingSessions, GuardedCodingSessions),
inner,
policy,
}
@@ -187,6 +193,18 @@ impl MemoryProvider for MemoryGuard {
fn as_episodic(&self) -> Option<&dyn MemoryEpisodic> {
self.episodic.as_ref().map(|g| g as &dyn MemoryEpisodic)
}
+
+ fn as_source_sync(&self) -> Option<&dyn MemorySourceSync> {
+ self.source_sync
+ .as_ref()
+ .map(|g| g as &dyn MemorySourceSync)
+ }
+
+ fn as_coding_sessions(&self) -> Option<&dyn MemoryCodingSessions> {
+ self.coding_sessions
+ .as_ref()
+ .map(|g| g as &dyn MemoryCodingSessions)
+ }
}
#[cfg(test)]
diff --git a/src/openhuman/memory/guard/test_support.rs b/src/openhuman/memory/guard/test_support.rs
index b77ebd8cdf..d853551083 100644
--- a/src/openhuman/memory/guard/test_support.rs
+++ b/src/openhuman/memory/guard/test_support.rs
@@ -16,18 +16,26 @@ 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::health::MemoryHealth;
+use crate::openhuman::memory::api::provider::sessions::{
+ CodingSessionIngestReport, CodingSessionIngestRequest, CodingSessionSource,
+};
+use crate::openhuman::memory::api::provider::sync::{
+ RawArchiveCoverage, RawRebuildOutcome, SourceSyncState, SourceSyncStatus, SyncAuditEntry,
+ SyncRunOutcome,
+};
use crate::openhuman::memory::api::provider::types::{
DiffReport, EntityHit, ExportPage, ExportRecord, ImportOutcome, IngestItem, IngestOutcome,
MaintenanceReport, SnapshotRef, SourceItem, SourceScope,
};
use crate::openhuman::memory::api::provider::{
AddressBookSeedOutcome, ChunkDetail, ChunkEmbedding, ChunkQuery, CoverWindowQuery, EntityMatch,
- EpisodicEvent, FacetType, FastRetrieveQuery, MemoryChunks, MemoryCore, MemoryDiff,
- MemoryDocuments, MemoryEntities, MemoryEpisodic, MemoryGoals, MemoryGraph, MemoryIngest,
- MemoryMaintenance, MemoryPeople, MemoryPortability, MemoryProfile, MemoryProvider,
- MemoryRecall, MemoryRetrieval, MemorySourceSink, MemoryToolMemory, MemoryTree, PersonHandle,
- PersonInteraction, PersonRecord, PersonScore, ProfileFacet, RankedPerson, ResolvedPerson,
- RetrievalHit, RetrievalResponse, SourceRetrievalQuery, UserState,
+ EpisodicEvent, FacetType, FastRetrieveQuery, MemoryChunks, MemoryCodingSessions, MemoryCore,
+ MemoryDiff, MemoryDocuments, MemoryEntities, MemoryEpisodic, MemoryGoals, MemoryGraph,
+ MemoryIngest, MemoryMaintenance, MemoryPeople, MemoryPortability, MemoryProfile,
+ MemoryProvider, MemoryRecall, MemoryRetrieval, MemorySourceSink, MemorySourceSync,
+ MemoryToolMemory, MemoryTree, PersonHandle, PersonInteraction, PersonRecord, PersonScore,
+ ProfileFacet, RankedPerson, ResolvedPerson, RetrievalHit, RetrievalResponse,
+ SourceRetrievalQuery, UserState,
};
use crate::openhuman::memory::api::recall::OwnedRecallOpts;
use crate::openhuman::memory::api::tool_memory::ToolMemoryRule;
@@ -726,6 +734,91 @@ impl MemoryProvider for RecordingProvider {
fn as_episodic(&self) -> Option<&dyn MemoryEpisodic> {
Some(self)
}
+ fn as_source_sync(&self) -> Option<&dyn MemorySourceSync> {
+ Some(self)
+ }
+ fn as_coding_sessions(&self) -> Option<&dyn MemoryCodingSessions> {
+ Some(self)
+ }
+}
+
+// The two families tinymemory v1.7.0 added. `capabilities()` above answers
+// `Capabilities::all()`, so a driver that advertises them and then hands back
+// `None` from the accessor is exactly the inconsistency `audit_provider`
+// exists to catch — the recorder has to serve them to stay honest.
+
+#[async_trait]
+impl MemorySourceSync for RecordingProvider {
+ async fn run_connection_sync(
+ &self,
+ toolkit: &str,
+ connection_id: &str,
+ ) -> Result<SyncRunOutcome, MemoryError> {
+ self.record(Call::plain("source_sync.run_connection_sync"));
+ let _ = (toolkit, connection_id);
+ Ok(SyncRunOutcome::default())
+ }
+ async fn source_sync_state(
+ &self,
+ toolkit: &str,
+ connection_id: &str,
+ ) -> Result<Option<SourceSyncState>, MemoryError> {
+ self.record(Call::plain("source_sync.source_sync_state"));
+ let _ = (toolkit, connection_id);
+ Ok(None)
+ }
+ async fn sync_audit_log(
+ &self,
+ _limit: Option<usize>,
+ ) -> Result<Vec<SyncAuditEntry>, MemoryError> {
+ self.record(Call::plain("source_sync.sync_audit_log"));
+ Ok(Vec::new())
+ }
+ async fn estimate_sync_cost_usd(
+ &self,
+ _input_tokens: u64,
+ _output_tokens: u64,
+ ) -> Result<f64, MemoryError> {
+ self.record(Call::plain("source_sync.estimate_sync_cost_usd"));
+ Ok(0.0)
+ }
+ async fn sync_statuses(&self) -> Result<Vec<SourceSyncStatus>, MemoryError> {
+ self.record(Call::plain("source_sync.sync_statuses"));
+ Ok(Vec::new())
+ }
+ async fn raw_archive_coverage(
+ &self,
+ tree_scope: &str,
+ archive_source_id: &str,
+ ) -> Result<RawArchiveCoverage, MemoryError> {
+ self.record(Call::plain("source_sync.raw_archive_coverage"));
+ let _ = (tree_scope, archive_source_id);
+ Ok(RawArchiveCoverage::default())
+ }
+ async fn rebuild_from_raw_archive(
+ &self,
+ tree_scope: &str,
+ archive_source_id: &str,
+ ) -> Result<RawRebuildOutcome, MemoryError> {
+ self.record(Call::plain("source_sync.rebuild_from_raw_archive"));
+ let _ = (tree_scope, archive_source_id);
+ Ok(RawRebuildOutcome::default())
+ }
+}
+
+#[async_trait]
+impl MemoryCodingSessions for RecordingProvider {
+ async fn coding_session_status(&self) -> Result<Vec<CodingSessionSource>, MemoryError> {
+ self.record(Call::plain("coding_sessions.coding_session_status"));
+ Ok(Vec::new())
+ }
+ async fn ingest_coding_sessions(
+ &self,
+ _request: CodingSessionIngestRequest,
+ ) -> Result<CodingSessionIngestReport, MemoryError> {
+ self.record(Call::plain("coding_sessions.ingest_coding_sessions"));
+ Ok(CodingSessionIngestReport::default())
+ }
}
#[async_trait]
diff --git a/src/openhuman/memory/mod.rs b/src/openhuman/memory/mod.rs
index 9e293287cf..0f00169fce 100644
--- a/src/openhuman/memory/mod.rs
+++ b/src/openhuman/memory/mod.rs
@@ -144,10 +144,35 @@ pub use schemas::{
all_tool_memory_controller_schemas as all_memory_tool_memory_controller_schemas,
all_tool_memory_registered_controllers as all_memory_tool_memory_registered_controllers,
};
+// The ingestion vocabulary, split by who actually defines it (#5560).
+//
+// It was one `pub use tinymemory_core::ingestion::{…}` line of eleven names,
+// which read as eleven engine types. Seven of them are not: `tinymemory-core`'s
+// `ingestion` module re-exports them out of `engine::backend::ingest`, which is
+// `pub use tinycortex::memory::ingest`. So the line below names the **same
+// items** at the crate that defines them — `tinycortex` stays a direct
+// dependency of this crate, `tinymemory-core` is the one being shed — and no
+// type, wire byte or call site changes. Same move as `memory::people`,
+// `memory::tool_memory` and `memory::tree::health`'s taxonomy half.
+pub use tinycortex::memory::ingest::{
+ ExtractedEntity, ExtractedRelation, ExtractionMode, MemoryIngestionConfig,
+ MemoryIngestionRequest, MemoryIngestionResult, DEFAULT_MEMORY_EXTRACTION_MODEL,
+};
+// The remaining four are genuinely `tinymemory-core`'s own: the in-process
+// ingest queue (`ingestion::queue`) and its status snapshot
+// (`ingestion::state`). They have no contract equivalent — the ingest queue is
+// named in `direct_engine_refs_tests`' upstream-gap list as one of the four
+// things with no bus representation at all — so this is what still pins the
+// engine crate here, and it is now visible as such rather than hidden in a
+// list of eleven.
+//
+// `IngestionState` is the one with a live consumer
+// (`tests/raw_coverage/memory_raw_coverage_e2e.rs`). The other three are kept
+// because they are one module's worth of a single domain and splitting a queue
+// from its own job type would leave a re-export that documents nothing; when
+// the queue moves behind the bus they go together.
pub use tinymemory_core::ingestion::{
- ExtractedEntity, ExtractedRelation, ExtractionMode, IngestionJob, IngestionQueue,
- IngestionState, IngestionStatusSnapshot, MemoryIngestionConfig, MemoryIngestionRequest,
- MemoryIngestionResult, DEFAULT_MEMORY_EXTRACTION_MODEL,
+ IngestionJob, IngestionQueue, IngestionState, IngestionStatusSnapshot,
};
// The host's own JSON-RPC request/response shapes. They lived in
// `tinymemory_core::rpc_models` and were re-exported here by a glob; nothing
diff --git a/src/openhuman/memory/ops/provider.rs b/src/openhuman/memory/ops/provider.rs
index c66025cb08..1e35dff9d9 100644
--- a/src/openhuman/memory/ops/provider.rs
+++ b/src/openhuman/memory/ops/provider.rs
@@ -172,7 +172,7 @@ mod tests {
// Previously this comment documented a narrower set (seventeen, then
// thirteen) while the host under-claimed or over-claimed; the gap is
// now closed: v1.4.0 serves all eighteen, `ModuleMemoryProvider`
- // implements all eighteen accessors including `as_episodic`, so the
+ // implements all twenty accessors including `as_episodic`, so the
// wire surface and the advertised set agree.
// `modules::memory::ARTIFACT_CAPABILITIES` is the machine-checked
// source of truth for what the pinned release serves (see its module
@@ -184,13 +184,19 @@ mod tests {
assert_eq!(
status.capabilities,
vec![
- // Widened to the full eighteen with the Episodic accessor
+ // Widened to eighteen with the Episodic accessor, then twenty when
+ // tinymemory v1.7.0 added SourceSync and CodingSessions —
// landing — the archivist writes its turns and segments
// through that family, so hiding it here would be the
// under-claim. The list stays spelled out: a NEW contract
// family must still widen this deliberately, with its
// accessor and its release.
"chunks",
+ // v1.7.0's two families. Deliberately widened here rather than
+ // derived: this list is the wire surface the frontend reads, so
+ // a new family has to be a decision someone made, not something
+ // that appeared.
+ "coding_sessions",
"core",
"diff",
"documents",
@@ -205,6 +211,7 @@ mod tests {
"profile",
"recall",
"retrieval",
+ "source_sync",
"sources",
"tool_memory",
"tree"
diff --git a/src/openhuman/memory/read_rpc/admin.rs b/src/openhuman/memory/read_rpc/admin.rs
index 4e200450a6..b880c4b98f 100644
--- a/src/openhuman/memory/read_rpc/admin.rs
+++ b/src/openhuman/memory/read_rpc/admin.rs
@@ -276,24 +276,49 @@ pub async fn reset_tree_rpc(config: &Config) -> Result<RpcOutcome<ResetTreeRespo
///
/// # The last engine reference in this module (#5560)
///
+/// **The upstream half of this is done. What is left is two host forwarders,
+/// and until they land migrating here would be a regression — read on before
+/// changing it.**
+///
/// `get_or_create_source_tree` hands back a live `Tree` **object**, and both
/// things this handler does next need the object rather than a namespace: the
/// host's `TreeFactory::from_tree(&tree).label_strategy(&cfg)` picks the
/// labelling policy from the tree's own kind/scope, and `force_flush_tree`
/// takes `&tree.id`.
///
-/// `MemoryTree` cannot express that. It is namespace-addressed end to end —
-/// `append`, `query_source`, `drill_down`, `seal`, `cascade`, `summary_forest`,
-/// `recent_leaves` — and there is no member that returns a tree handle, nor
-/// should there be: handing a driver's internal object across the bus is the
-/// thing the contract exists to prevent. `tinymemory_core::tree_source` is also
-/// genuinely engine-owned (it wraps `tree::tree::registry::get_or_create_tree`
-/// and writes the `_source.md` mirror as a side effect), so there is no
-/// tinycortex twin to repoint at either.
+/// This note used to say `MemoryTree` could not express that — namespace-addressed
+/// end to end, no member returning a tree handle — and asked upstream for
+/// "flush the tree for this source scope, using the host's label strategy".
+/// **tinymemory v1.7.0 shipped exactly that**:
+/// `MemoryTree::flush_source_tree(&self, source_scope) -> Result<u64, MemoryError>`,
+/// answering the seal count rather than a tree, with the labelling decision made
+/// driver-side (which is where it comes from anyway). The module serves it and
+/// `TinycortexProvider` implements it, so the driver behind the bus is ready.
+///
+/// What is **not** ready is this host's two forwarders onto that member:
+/// neither `modules::memory`'s `ModuleMemoryProvider` (`impl MemoryTree`) nor
+/// `memory::guard::families`' `GuardedTree` overrides it, so both inherit the
+/// trait default — `Err(Unsupported(Tree))`. Calling it today would turn a
+/// working flush into a runtime `Unsupported`, which is strictly worse than
+/// the direct call: the failure moves from compile time to run time, and this
+/// handler's caller has no fallback. That is the same trap
+/// `direct_engine_refs_tests`' module docs warn about for a method the pinned
+/// artifact does not serve; here the artifact serves it and the host does not
+/// ask.
+///
+/// So the remaining work is host-side and sits in two files this handler does
+/// not own. Once `ModuleMemoryProvider` and `GuardedTree` both forward
+/// `flush_source_tree`, this whole function collapses into the shape
+/// [`flush_now_rpc`] already has below: resolve the binding, take `as_tree()`,
+/// degrade by naming the driver when the family is absent, and map the returned
+/// count into `seals_fired`. Two behaviours have to survive that rewrite — the
+/// `ACTIVE` re-entrancy latch, and the fact that an unknown scope is a
+/// zero-count success rather than an error.
///
-/// Migrating this needs a bus member shaped like "flush the tree for this
-/// source scope, using the host's label strategy", which does not exist in the
-/// pinned release — an upstream ask, not a host change.
+/// (`tinymemory_core::tree_source` itself is genuinely engine-owned — it wraps
+/// `tree::tree::registry::get_or_create_tree` and writes the `_source.md`
+/// mirror as a side effect — so there is no tinycortex twin to repoint at in
+/// the meantime.)
pub async fn flush_source_tree_rpc(
config: &Config,
source_scope: &str,
diff --git a/src/openhuman/memory/sources/mod.rs b/src/openhuman/memory/sources/mod.rs
index af0e79956c..568132adf1 100644
--- a/src/openhuman/memory/sources/mod.rs
+++ b/src/openhuman/memory/sources/mod.rs
@@ -41,6 +41,21 @@
//! what the issue is for: a second unpoliced door spelled differently is
//! still a second unpoliced door.
//!
+//! ## What is *not* blocked, so nobody looks for it here
+//!
+//! The RPC layer above this glob no longer names the engine at all. [`rpc`]
+//! moved its coding-session, raw-archive-coverage, audit-log and sync-price
+//! calls onto `MemoryCodingSessions` / `MemorySourceSync` when tinymemory
+//! v1.7.0 added them, so the two references left in this domain are the two in
+//! *this file*. Neither is a call site anyone can reroute: they are the shim
+//! itself.
+//!
+//! The unlock for them is a **manifest** decision, not a code one, and it has
+//! not changed — `tinymemory` re-exports the types as `tinymemory::sources`
+//! behind an off-by-default `sources` feature (`sources-network` on top for the
+//! network readers) that the root `Cargo.toml` does not enable, and even with
+//! it on, points 2 and 3 above still stand.
+//!
//! So this stays until the queue and the sync pipeline go behind the module.
//! `MemorySourceSink` is not the answer either — it is `accept_source_items` +
//! `forget_source` + `forget_matching`, an *ingest* door, with no listing or
diff --git a/src/openhuman/memory/sources/rpc.rs b/src/openhuman/memory/sources/rpc.rs
index 91b4433703..23957a7fdf 100644
--- a/src/openhuman/memory/sources/rpc.rs
+++ b/src/openhuman/memory/sources/rpc.rs
@@ -1,46 +1,69 @@
//! RPC handler implementations for memory sources.
//!
-//! # The engine references in this file (#5560), by surface
+//! # How this file reaches memory (#5560)
//!
-//! This file sits on `direct_engine_refs_tests::ALLOWED` as `NeedsWiderSeam`.
-//! That verdict was re-tested on 2026-08-25 and it holds, for two independent
-//! reasons that are worth recording so the next reader does not re-derive
-//! them: **no** `MemoryProvider` member expresses any of the four surfaces
-//! below, and **every** symbol they name is defined in `tinymemory-core`
-//! itself rather than re-exported from a crate this manifest already lists, so
-//! there is no repoint available either. (Absence was checked against the
-//! contract at `vendor/tinymemory` HEAD, which leads the pinned release — an
-//! absence there is an absence in the pin.) `tinymemory_core::tinycortex` is
-//! an alias for `tinymemory_core::engine`, which is why all four read as
-//! `tinycortex::…` below.
+//! Every memory call below goes through the bound driver — never through an
+//! in-process engine handle. The four surfaces this file used to reach into
+//! `tinymemory_core::tinycortex` for became contract members in tinymemory
+//! v1.7.0, and the mapping is one-for-one:
//!
-//! - **Coding sessions** — `CodingSessionIngestRequest`,
-//! `CodingSessionIngestResponse`, `CodingSessionSourceStatus`,
-//! `coding_session_status`, `ingest_coding_sessions`. TinyCortex's persona
-//! pipeline: `walkdir` over session roots, `RawSession`, `FileStateStore`.
-//! No capability family covers any of it.
-//! - **Raw-archive coverage** — `raw_coverage`, `rebuild_tree_from_raw`. A
-//! filesystem-vs-tree crosscheck. `MemoryTree` is namespace-addressed
-//! (`append` / `query_source` / `drill_down` / `seal` / `cascade` /
-//! `summary_forest` / `recent_leaves`) and has no coverage member.
-//! - **Sync audit log** — `SyncAuditEntry`, `read_audit_log`. A host-owned log
-//! read out of `MemoryHostConfig::workspace_dir`; nothing in the contract
-//! reads it.
-//! - **Sync cost model** — `estimate_cost_usd`. Pure arithmetic, so it *looks*
-//! like a free move host-side — but the same constants back
-//! `SyncAuditEntry::effective_cost_usd` (used in `monthly_cost_summary_rpc`
-//! below) and the engine's own cost accumulator. Copying it here would be a
-//! second price that can drift from the one the audit rows were written with.
+//! | What a handler needs | Contract member |
+//! |---|---|
+//! | coding-session discovery | `MemoryCodingSessions::coding_session_status` |
+//! | coding-session ingestion | `MemoryCodingSessions::ingest_coding_sessions` |
+//! | raw-archive coverage, and its repair | `MemorySourceSync::raw_archive_coverage` / `rebuild_from_raw_archive` |
+//! | the sync audit log | `MemorySourceSync::sync_audit_log` |
+//! | the sync price | `MemorySourceSync::estimate_sync_cost_usd` |
//!
-//! Clearing this file needs all four to move, not any one of them, and the
-//! first two are the persona and sync pipelines going behind the bus — Phase F
-//! work, not a call-site migration. One thing not to do in the meantime:
-//! re-routing these through the `memory::sync` / `memory::tinycortex`
-//! re-export shims takes the path off the scanner without removing an ounce of
-//! coupling, which is exactly the edit that would make the ratchet lie.
+//! Two of those look shortcuttable and are not, so the reasons are recorded
+//! here rather than left to be re-derived:
+//!
+//! - **The audit log is not read through the `memory::sync::audit` host shim.**
+//! That path resolves, and taking it would move this file off the
+//! direct-engine-reference scanner while removing no coupling whatsoever —
+//! precisely the edit the ratchet's own docs call the one that would make the
+//! lint lie.
+//! - **The price is asked, never computed here.** The same constants behind
+//! `estimate_sync_cost_usd` stamped `estimated_cost_usd` onto every audit row
+//! the driver has already written, and `monthly_cost_summary_rpc` below totals
+//! those very rows. A host-side copy of the arithmetic becomes a second price
+//! the moment either side is retuned, and one screen would then show a
+//! projection and a history priced differently with nothing to say which.
+//!
+//! ## Refusing when the driver does not serve the family
+//!
+//! `as_source_sync()` / `as_coding_sessions()` answering `None` means the bound
+//! driver serves no such family, and every handler here **refuses, naming the
+//! driver** (see [`unserved`]). None of them reports an empty log, a zero cost
+//! or an empty source list instead.
+//!
+//! That is a deliberately different trade from the tree read handlers, which do
+//! degrade to empty. There, "no hits" is a true statement about a driver that
+//! keeps no summary tree. Here the family *is* the entire subject of the call,
+//! so an empty success is indistinguishable from "nothing has ever synced" or
+//! "no coding agent is installed" — a wrong answer the caller cannot tell from
+//! a right one, on the two screens where the number is a promise about money
+//! and about how long an import will take.
+//!
+//! ## On this file's length
+//!
+//! It is over the ~500-line guidance, and was before this change; it is not
+//! split as part of it. The seam is visible, though, and the routing made it
+//! sharper: `coding_session_status_rpc`, `ingest_coding_sessions_rpc`,
+//! `reconcile_rpc`, `sync_audit_log_rpc`, `estimate_sync_cost_rpc` and
+//! `monthly_cost_summary_rpc` are the driver-facing half — six handlers over
+//! two capability families, all sharing the binding preamble — while the
+//! registry CRUD between them talks only to `registry` and `readers` and never
+//! resolves a binding at all.
// `to_arc` / the config accessors are `MemoryHostConfig` trait methods.
use crate::openhuman::config::rpc as config_rpc;
+use crate::openhuman::config::Config;
+use crate::openhuman::memory::api::provider::sessions::{
+ CodingSessionIngestReport, CodingSessionSource,
+};
+use crate::openhuman::memory::api::provider::sync::SyncAuditEntry;
+use crate::openhuman::memory::binding::MemoryBinding;
use crate::openhuman::memory::sources::apply_kind_defaults;
use crate::openhuman::memory::sources::readers;
use crate::openhuman::memory::sources::registry::{self, MemorySourcePatch};
@@ -52,30 +75,70 @@ use tinymemory_api::host::MemoryHostConfig;
///
/// Re-exported here so `schemas.rs` can name it as
/// `rpc::CodingSessionIngestRequest`, the way every other handler adapter in
-/// that file names its request type. That is a consolidation, not a migration
-/// (#5560): the engine dependency does not go away, it stops being spread over
-/// two files — so when the persona pipeline finally moves, behind the bus or
-/// home the way `rpc_models` did, this module is the only one that has to
-/// change. The module docs above record why it has not moved yet.
-pub use tinymemory_core::tinycortex::CodingSessionIngestRequest;
+/// that file names its request type. The path behind the alias is now the
+/// contract's (`tinymemory_api::provider::sessions`) rather than the engine's,
+/// which is what lets `ingest_coding_sessions_rpc` hand the value straight to
+/// the driver with no conversion in between — the request that crosses the bus
+/// is the request `schemas.rs` deserialised.
+pub use crate::openhuman::memory::api::provider::sessions::CodingSessionIngestRequest;
+
+/// The refusal a handler returns when the bound driver serves no such family.
+///
+/// One place, so the message and the log line cannot drift between the six
+/// call sites, and so the driver id is always in both. See the module docs for
+/// why these handlers refuse rather than degrade to an empty answer.
+fn unserved(binding: &MemoryBinding, family: &str, call: &str) -> String {
+ tracing::warn!(
+ driver = %binding.driver_id(),
+ family = %family,
+ call = %call,
+ "[memory_sources] refusing: bound driver does not serve this capability family"
+ );
+ format!(
+ "the bound memory driver '{}' does not serve {family}",
+ binding.driver_id()
+ )
+}
#[derive(Debug, serde::Serialize)]
pub struct CodingSessionStatusResponse {
- pub sources: Vec<tinymemory_core::tinycortex::CodingSessionSourceStatus>,
+ pub sources: Vec<CodingSessionSource>,
}
+/// Discover what each supported coding agent's session store holds.
+///
+/// The scan happens driver-side and is bounded by the driver's own caps, which
+/// is why this no longer needs a blocking worker: the walk that used to run on
+/// this process's pool now runs behind the bus, and what comes back is counts.
+/// `CodingSessionSource::scan_truncated` is how a caller learns the counts are
+/// a floor — the same field the engine's `CodingSessionSourceStatus` carried,
+/// under the same name.
pub async fn coding_session_status_rpc() -> Result<RpcOutcome<CodingSessionStatusResponse>, String>
{
tracing::debug!("[memory_sources] coding_session_status_rpc: entry");
- let sources = tokio::task::spawn_blocking(tinymemory_core::tinycortex::coding_session_status)
+ let config = config_rpc::load_config_with_timeout().await?;
+ let binding = crate::openhuman::memory::binding::for_config(&config)?;
+ let Some(sessions) = binding.provider().as_coding_sessions() else {
+ return Err(unserved(
+ &binding,
+ "coding sessions",
+ "coding_session_status",
+ ));
+ };
+
+ let sources = sessions
+ .coding_session_status()
.await
- .map_err(|error| format!("join coding-session discovery: {error}"))?;
+ .map_err(|error| format!("coding session status: {error}"))?;
+
tracing::debug!(
+ driver = %binding.driver_id(),
sources = sources.len(),
files = sources
.iter()
.map(|source| source.session_files)
.sum::<usize>(),
+ truncated = sources.iter().any(|source| source.scan_truncated),
"[memory_sources] coding_session_status_rpc: exit"
);
Ok(RpcOutcome::new(
@@ -134,52 +197,69 @@ fn ingest_budget(max_sessions: usize) -> std::time::Duration {
std::time::Duration::from_secs(scaled.min(HARD_CAP_SECS))
}
+/// Distil local coding-agent transcripts into observations.
+///
+/// The pipeline runs driver-side now, which removes the blocking-worker hop
+/// this handler used to need: the engine's persona pass carried borrowed path
+/// state and was not `Send`, so it had to be driven from `spawn_blocking` with
+/// a `block_on` inside. The contract member is an ordinary `Send` future, so
+/// the RPC simply awaits it.
+///
+/// **The deadline stays here on purpose.** `MemoryCodingSessions` documents
+/// that it cannot bound the wall-clock cost — each session is one or more
+/// sequential model calls — and that a caller needing a deadline enforces it on
+/// its own side. [`ingest_budget`] is that deadline, unchanged; a timeout is
+/// still reported as a structured error rather than as a short report, because
+/// a report the run never finished writing is not progress the caller can keep.
pub async fn ingest_coding_sessions_rpc(
req: CodingSessionIngestRequest,
-) -> Result<RpcOutcome<tinymemory_core::tinycortex::CodingSessionIngestResponse>, String> {
- tracing::info!("[memory_sources] ingest_coding_sessions_rpc: entry");
- let config = crate::openhuman::config::Config::load_or_init()
+) -> Result<RpcOutcome<CodingSessionIngestReport>, String> {
+ tracing::info!(
+ backfill = req.backfill,
+ max_sessions = req.max_sessions,
+ "[memory_sources] ingest_coding_sessions_rpc: entry"
+ );
+ let config = Config::load_or_init()
.await
.map_err(|error| format!("load config for coding-session ingestion: {error}"))?;
- // TinyCortex's persona pipeline intentionally carries borrowed path state
- // and is not `Send`. Drive it from a blocking worker while its async I/O
- // remains attached to the ambient Tokio runtime, keeping the controller
- // future itself Send-safe for the registry.
- let runtime = tokio::runtime::Handle::current();
+ let binding = crate::openhuman::memory::binding::for_config(&config)?;
+ let Some(sessions) = binding.provider().as_coding_sessions() else {
+ return Err(unserved(
+ &binding,
+ "coding sessions",
+ "ingest_coding_sessions",
+ ));
+ };
+
// Wall-clock ceiling so a stalled provider call or a wedged session step
- // can't keep the RPC (and its blocking worker) waiting indefinitely (#4863
- // review), sized to the requested backfill so a legitimate large run isn't
- // killed mid-flight while a genuine infinite hang still terminates.
+ // can't keep the RPC waiting indefinitely (#4863 review), sized to the
+ // requested backfill so a legitimate large run isn't killed mid-flight
+ // while a genuine infinite hang still terminates. Read before `req` moves.
let ingest_timeout = ingest_budget(req.max_sessions);
- let response = tokio::task::spawn_blocking(move || {
- runtime.block_on(async move {
- tokio::time::timeout(
- ingest_timeout,
- tinymemory_core::tinycortex::ingest_coding_sessions(&config, req),
+ let report = tokio::time::timeout(ingest_timeout, sessions.ingest_coding_sessions(req))
+ .await
+ .map_err(|_elapsed| {
+ tracing::error!(
+ driver = %binding.driver_id(),
+ timeout_secs = ingest_timeout.as_secs(),
+ "[memory_sources] ingest_coding_sessions_rpc: timed out"
+ );
+ format!(
+ "ingest coding sessions: timed out after {}s",
+ ingest_timeout.as_secs()
)
- .await
- })
- })
- .await
- .map_err(|error| format!("join coding-session ingestion: {error}"))?
- .map_err(|_elapsed| {
- tracing::error!(
- timeout_secs = ingest_timeout.as_secs(),
- "[memory_sources] ingest_coding_sessions_rpc: timed out"
- );
- format!(
- "ingest coding sessions: timed out after {}s",
- ingest_timeout.as_secs()
- )
- })?
- .map_err(|error| format!("ingest coding sessions: {error:#}"))?;
+ })?
+ .map_err(|error| format!("ingest coding sessions: {error}"))?;
+
tracing::info!(
- processed = response.sessions_processed,
- failed = response.sessions_failed,
- budget_hit = response.budget_hit,
+ driver = %binding.driver_id(),
+ mode = %report.mode,
+ processed = report.sessions_processed,
+ failed = report.sessions_failed,
+ budget_hit = report.budget_hit,
"[memory_sources] ingest_coding_sessions_rpc: exit"
);
- Ok(RpcOutcome::new(response, vec![]))
+ Ok(RpcOutcome::new(report, vec![]))
}
// ── List ──
@@ -513,11 +593,18 @@ pub struct ReconcileScopeReport {
pub source_id: String,
pub tree_scope: String,
/// Raw `.md` files on disk for this scope.
- pub total_raw_files: usize,
+ pub total_raw_files: u64,
/// Files already covered by a tree summary.
- pub covered: usize,
+ pub covered: u64,
/// Files awaiting summarisation into the tree.
- pub pending: usize,
+ ///
+ /// A count the driver computed, not one this handler derived from a list.
+ /// The engine's coverage scan returned each pending file's absolute path
+ /// inside the content vault and this handler called `.len()` on it;
+ /// `RawArchiveCoverage` deliberately reports the count alone, because a
+ /// path describes the driver's storage layout and nothing here ever read
+ /// one. The number is the same number.
+ pub pending: u64,
/// True when `execute` was set and a background reconcile was started.
pub started: bool,
}
@@ -530,9 +617,12 @@ pub struct ReconcileResponse {
/// Report (and optionally repair) raw-archive → tree coverage for memory
/// sources. The same incremental reconcile runs automatically after every
/// sync; this RPC exposes it for inspection and manual triggering.
+///
+/// The scopes themselves are still derived host-side (`derive_scopes` reads the
+/// registry row); what moved is the crosscheck and the repair, which are
+/// `MemorySourceSync::raw_archive_coverage` and `rebuild_from_raw_archive`.
pub async fn reconcile_rpc(req: ReconcileRequest) -> Result<RpcOutcome<ReconcileResponse>, String> {
use crate::openhuman::memory::sources::sync::derive_scopes;
- use tinymemory_core::tinycortex::{raw_coverage, rebuild_tree_from_raw};
tracing::info!(
source_id = ?req.source_id,
@@ -541,6 +631,11 @@ pub async fn reconcile_rpc(req: ReconcileRequest) -> Result<RpcOutcome<Reconcile
);
let config = config_rpc::load_config_with_timeout().await?;
+ let binding = crate::openhuman::memory::binding::for_config(&config)?;
+ let Some(sync) = binding.provider().as_source_sync() else {
+ return Err(unserved(&binding, "source sync", "reconcile"));
+ };
+
let sources: Vec<MemorySourceEntry> = match &req.source_id {
Some(id) => vec![registry::get_source(id)
.await?
@@ -551,16 +646,34 @@ pub async fn reconcile_rpc(req: ReconcileRequest) -> Result<RpcOutcome<Reconcile
let mut reports: Vec<ReconcileScopeReport> = Vec::new();
for source in sources.iter().filter(|s| s.enabled) {
for scope in derive_scopes(source, &config) {
- let coverage = raw_coverage(&config, &scope.tree_scope, &scope.archive_source_id)
- .map_err(|e| format!("coverage for {}: {e:#}", scope.tree_scope))?;
- let pending = coverage.pending.len();
+ let coverage = sync
+ .raw_archive_coverage(&scope.tree_scope, &scope.archive_source_id)
+ .await
+ .map_err(|e| format!("coverage for {}: {e}", scope.tree_scope))?;
let mut started = false;
- if req.execute && pending > 0 {
- let cfg = config.clone();
+ if req.execute && coverage.pending > 0 {
+ // The binding, not the config: the repair is a driver call now,
+ // and the spawned task must reach the same bound driver this
+ // request resolved rather than re-deriving one.
+ let binding = std::sync::Arc::clone(&binding);
let tree_scope = scope.tree_scope.clone();
let archive = scope.archive_source_id.clone();
tokio::spawn(async move {
- match rebuild_tree_from_raw(&cfg, &tree_scope, &archive).await {
+ // Re-resolved inside the task because the borrow cannot
+ // cross the spawn. It answered `Some` a moment ago on this
+ // same binding, so `None` here would mean the driver
+ // changed underneath the request — logged loudly rather
+ // than returning as a silent no-op.
+ let Some(sync) = binding.provider().as_source_sync() else {
+ tracing::error!(
+ driver = %binding.driver_id(),
+ tree_scope = %tree_scope,
+ "[memory_sources] reconcile_rpc: background reconcile abandoned — \
+ driver stopped serving source sync between the report and the repair"
+ );
+ return;
+ };
+ match sync.rebuild_from_raw_archive(&tree_scope, &archive).await {
Ok(outcome) => tracing::info!(
tree_scope = %tree_scope,
files = outcome.files_read,
@@ -569,7 +682,7 @@ pub async fn reconcile_rpc(req: ReconcileRequest) -> Result<RpcOutcome<Reconcile
),
Err(e) => tracing::warn!(
tree_scope = %tree_scope,
- error = %format!("{e:#}"),
+ error = %e,
"[memory_sources] reconcile_rpc: background reconcile failed"
),
}
@@ -577,11 +690,12 @@ pub async fn reconcile_rpc(req: ReconcileRequest) -> Result<RpcOutcome<Reconcile
started = true;
}
tracing::debug!(
+ driver = %binding.driver_id(),
source_id = %source.id,
tree_scope = %scope.tree_scope,
total = coverage.total,
covered = coverage.covered,
- pending = pending,
+ pending = coverage.pending,
started = started,
"[memory_sources] reconcile_rpc: scope report"
);
@@ -590,7 +704,7 @@ pub async fn reconcile_rpc(req: ReconcileRequest) -> Result<RpcOutcome<Reconcile
tree_scope: scope.tree_scope,
total_raw_files: coverage.total,
covered: coverage.covered,
- pending,
+ pending: coverage.pending,
started,
});
}
@@ -661,12 +775,46 @@ pub async fn supported_toolkits_rpc() -> Result<RpcOutcome<SupportedToolkitsResp
#[derive(Debug, serde::Serialize)]
pub struct SyncAuditLogResponse {
- pub entries: Vec<tinymemory_core::tinycortex::SyncAuditEntry>,
+ pub entries: Vec<SyncAuditEntry>,
}
+/// Past sync runs, newest first.
+///
+/// # This is now the driver's most recent rows, not the whole log
+///
+/// The engine call this replaced returned every line in
+/// `<workspace>/memory_tree/sync_audit.jsonl`. `sync_audit_log` is capped:
+/// `None` means "the driver's own ceiling", explicitly **not** unbounded,
+/// because the log is append-only for the life of a workspace and an unbounded
+/// read eventually cannot cross a frame at all. The panel that renders this
+/// shows recent runs, so the cap is not a visible reduction there — but it is a
+/// real one, and `monthly_cost_summary_rpc` below is where it has to be said
+/// out loud rather than absorbed.
+///
+/// A read failure is now an error rather than an empty log. The engine wrapper
+/// ended in `unwrap_or_default()`, so an unreadable file was reported as "no
+/// syncs have run" — the one answer a caller cannot distinguish from the truth.
pub async fn sync_audit_log_rpc() -> Result<RpcOutcome<SyncAuditLogResponse>, String> {
+ tracing::debug!("[memory_sources] sync_audit_log_rpc: entry");
let config = config_rpc::load_config_with_timeout().await?;
- let entries = tinymemory_core::tinycortex::read_audit_log(&config);
+ let binding = crate::openhuman::memory::binding::for_config(&config)?;
+ let Some(sync) = binding.provider().as_source_sync() else {
+ return Err(unserved(&binding, "source sync", "sync_audit_log"));
+ };
+
+ // `None` = the driver's own cap. A caller cannot raise it by asking for
+ // more, so passing a number here would only be this host inventing a
+ // ceiling the driver then clamps anyway.
+ let entries = sync
+ .sync_audit_log(None)
+ .await
+ .map_err(|error| format!("sync audit log: {error}"))?;
+
+ tracing::debug!(
+ driver = %binding.driver_id(),
+ entries = entries.len(),
+ "[memory_sources] sync_audit_log_rpc: exit"
+ );
Ok(RpcOutcome::new(SyncAuditLogResponse { entries }, vec![]))
}
@@ -687,6 +835,14 @@ pub struct EstimateSyncCostResponse {
pub budget_max_tokens: Option<u64>,
}
+/// Project what syncing one source would cost.
+///
+/// The item count and the token estimate are this host's (they come from the
+/// reader's listing and from the per-item allowances below); the **price** is
+/// the driver's, asked through `estimate_sync_cost_usd`. That split is the
+/// whole point of the member — see the module docs. A driver that serves no
+/// sync family has no price to quote, and this refuses rather than quoting
+/// `0.0`, which would read as "syncing this is free".
pub async fn estimate_sync_cost_rpc(
req: EstimateSyncCostRequest,
) -> Result<RpcOutcome<EstimateSyncCostResponse>, String> {
@@ -697,6 +853,11 @@ pub async fn estimate_sync_cost_rpc(
.ok_or_else(|| format!("source '{}' not found", req.source_id))?;
let config = config_rpc::load_config_with_timeout().await?;
+ let binding = crate::openhuman::memory::binding::for_config(&config)?;
+ let Some(sync) = binding.provider().as_source_sync() else {
+ return Err(unserved(&binding, "source sync", "estimate_sync_cost"));
+ };
+
let reader = readers::reader_for(&source.kind);
let items = reader.list_items(&source, &config).await?;
@@ -706,11 +867,19 @@ pub async fn estimate_sync_cost_rpc(
let estimated_input_tokens = item_count as u64 * 500;
let estimated_output_tokens = item_count as u64 * 100;
let estimated_tokens = estimated_input_tokens + estimated_output_tokens;
- let estimated_cost_usd = tinymemory_core::tinycortex::estimate_cost_usd(
- estimated_input_tokens,
- estimated_output_tokens,
- );
+ let estimated_cost_usd = sync
+ .estimate_sync_cost_usd(estimated_input_tokens, estimated_output_tokens)
+ .await
+ .map_err(|error| format!("estimate sync cost: {error}"))?;
+ tracing::debug!(
+ driver = %binding.driver_id(),
+ source_id = %req.source_id,
+ item_count,
+ estimated_tokens,
+ estimated_cost_usd,
+ "[memory_sources] estimate_sync_cost_rpc: exit"
+ );
Ok(RpcOutcome::new(
EstimateSyncCostResponse {
source_id: req.source_id,
@@ -726,7 +895,7 @@ pub async fn estimate_sync_cost_rpc(
// ── Monthly Cost Summary ──
-#[derive(Debug, serde::Serialize)]
+#[derive(Debug, Clone, PartialEq, serde::Serialize)]
pub struct MonthlyCostSummaryResponse {
pub month: String,
pub total_cost_usd: f64,
@@ -734,43 +903,94 @@ pub struct MonthlyCostSummaryResponse {
pub total_items: u32,
pub total_input_tokens: u64,
pub total_output_tokens: u64,
+ /// Whether the audit read reached back past the start of `month`.
+ ///
+ /// `sync_audit_log` is capped by the driver, so a workspace that synced
+ /// more times this month than the cap allows would silently total only the
+ /// newest of them. `true` means at least one row *older* than `month` came
+ /// back, which proves every row inside `month` was in the read; `false`
+ /// means the read ran out first and the totals above are a **floor**.
+ ///
+ /// Deliberately conservative in one direction: a driver that simply has no
+ /// older rows also reports `false`, so this can say "possibly short" when
+ /// the totals are in fact exact. It never says "complete" when they are
+ /// not, which is the direction that matters for a money figure.
+ pub totals_complete: bool,
+}
+
+/// Total one month of audit rows.
+///
+/// Pure, so the cap-versus-boundary rule above is unit-testable without a
+/// driver. Order-independent on purpose: the contract promises newest-first and
+/// stopping at the first older row would be cheaper, but the list is already
+/// bounded by the driver's cap, and a scan that does not depend on the ordering
+/// cannot silently under-count if a driver ever returns rows out of order.
+fn summarise_month(entries: &[SyncAuditEntry], month: &str) -> MonthlyCostSummaryResponse {
+ let mut summary = MonthlyCostSummaryResponse {
+ month: month.to_string(),
+ total_cost_usd: 0.0,
+ total_syncs: 0,
+ total_items: 0,
+ total_input_tokens: 0,
+ total_output_tokens: 0,
+ // An empty log has no rows the cap could have hidden.
+ totals_complete: entries.is_empty(),
+ };
+
+ for entry in entries {
+ let entry_month = entry.timestamp.format("%Y-%m").to_string();
+ // `%Y-%m` is zero-padded and fixed-width, so lexicographic order is
+ // chronological order and this needs no date arithmetic.
+ if entry_month.as_str() < month {
+ summary.totals_complete = true;
+ continue;
+ }
+ // Not `else` — a row stamped in a *later* month (clock skew) is skipped
+ // rather than counted, exactly as the engine-backed filter did.
+ if entry_month != month {
+ continue;
+ }
+ summary.total_cost_usd += entry.effective_cost_usd();
+ // Saturating: the counters are `u32` on the wire and an overflow here
+ // would be a debug-build panic inside a read-only reporting RPC.
+ summary.total_syncs = summary.total_syncs.saturating_add(1);
+ summary.total_items = summary.total_items.saturating_add(entry.items_fetched);
+ summary.total_input_tokens = summary
+ .total_input_tokens
+ .saturating_add(entry.input_tokens);
+ summary.total_output_tokens = summary
+ .total_output_tokens
+ .saturating_add(entry.output_tokens);
+ }
+
+ summary
}
pub async fn monthly_cost_summary_rpc() -> Result<RpcOutcome<MonthlyCostSummaryResponse>, String> {
tracing::debug!("[memory_sources] monthly_cost_summary_rpc: entry");
let config = config_rpc::load_config_with_timeout().await?;
- let entries = tinymemory_core::tinycortex::read_audit_log(&config);
-
- let now = chrono::Utc::now();
- let month_str = now.format("%Y-%m").to_string();
-
- let mut total_cost_usd = 0.0f64;
- let mut total_syncs = 0u32;
- let mut total_items = 0u32;
- let mut total_input_tokens = 0u64;
- let mut total_output_tokens = 0u64;
-
- for entry in &entries {
- if entry.timestamp.format("%Y-%m").to_string() == month_str {
- total_cost_usd += entry.effective_cost_usd();
- total_syncs += 1;
- total_items += entry.items_fetched;
- total_input_tokens += entry.input_tokens;
- total_output_tokens += entry.output_tokens;
- }
- }
+ let binding = crate::openhuman::memory::binding::for_config(&config)?;
+ let Some(sync) = binding.provider().as_source_sync() else {
+ return Err(unserved(&binding, "source sync", "monthly_cost_summary"));
+ };
- Ok(RpcOutcome::new(
- MonthlyCostSummaryResponse {
- month: month_str,
- total_cost_usd,
- total_syncs,
- total_items,
- total_input_tokens,
- total_output_tokens,
- },
- vec![],
- ))
+ let entries = sync
+ .sync_audit_log(None)
+ .await
+ .map_err(|error| format!("sync audit log: {error}"))?;
+
+ let month = chrono::Utc::now().format("%Y-%m").to_string();
+ let summary = summarise_month(&entries, &month);
+
+ tracing::debug!(
+ driver = %binding.driver_id(),
+ month = %summary.month,
+ rows_read = entries.len(),
+ syncs = summary.total_syncs,
+ totals_complete = summary.totals_complete,
+ "[memory_sources] monthly_cost_summary_rpc: exit"
+ );
+ Ok(RpcOutcome::new(summary, vec![]))
}
// ── Apply All In ──
@@ -1091,3 +1311,129 @@ mod budget_tests {
);
}
}
+
+#[cfg(test)]
+mod monthly_summary_tests {
+ use super::*;
+ use chrono::{DateTime, Utc};
+
+ /// One audit row, dated `stamp`, costing `estimated` with no real charge.
+ fn row(stamp: &str, items: u32, input: u64, output: u64, estimated: f64) -> SyncAuditEntry {
+ SyncAuditEntry {
+ timestamp: stamp
+ .parse::<DateTime<Utc>>()
+ .expect("an RFC 3339 timestamp"),
+ source_id: "src_1".to_string(),
+ source_kind: "composio".to_string(),
+ scope: "gmail".to_string(),
+ items_fetched: items,
+ batches: 1,
+ input_tokens: input,
+ output_tokens: output,
+ estimated_cost_usd: estimated,
+ composio_actions_called: 0,
+ composio_cost_usd: 0.0,
+ actual_charged_usd: None,
+ duration_ms: 10,
+ success: true,
+ error: None,
+ }
+ }
+
+ fn close(left: f64, right: f64) -> bool {
+ (left - right).abs() < 1e-9
+ }
+
+ /// Only the requested month is totalled, and a row from an earlier month
+ /// proves the read crossed the boundary.
+ #[test]
+ fn totals_the_month_and_reports_complete_when_the_read_reached_past_it() {
+ let entries = vec![
+ row("2026-08-20T10:00:00Z", 3, 100, 20, 0.5),
+ row("2026-08-01T00:00:00Z", 2, 50, 10, 0.25),
+ // Older month — excluded from the totals, and the proof the read
+ // covered the whole of August.
+ row("2026-07-31T23:59:59Z", 99, 9_999, 9_999, 42.0),
+ ];
+ let summary = summarise_month(&entries, "2026-08");
+
+ assert_eq!(summary.month, "2026-08");
+ assert_eq!(summary.total_syncs, 2);
+ assert_eq!(summary.total_items, 5);
+ assert_eq!(summary.total_input_tokens, 150);
+ assert_eq!(summary.total_output_tokens, 30);
+ assert!(close(summary.total_cost_usd, 0.75));
+ assert!(
+ summary.totals_complete,
+ "a row older than the month proves every row inside it was read"
+ );
+ }
+
+ /// The cap case: every row the driver returned is inside the month, so the
+ /// totals may be a floor and must not claim to be complete.
+ #[test]
+ fn reports_incomplete_when_every_returned_row_is_inside_the_month() {
+ let entries = vec![
+ row("2026-08-20T10:00:00Z", 1, 10, 1, 0.1),
+ row("2026-08-19T10:00:00Z", 1, 10, 1, 0.1),
+ ];
+ let summary = summarise_month(&entries, "2026-08");
+
+ assert_eq!(summary.total_syncs, 2);
+ assert!(
+ !summary.totals_complete,
+ "the read may have been cut off at the driver's cap — totals are a floor"
+ );
+ }
+
+ /// An empty log has no rows the cap could have hidden, so zero is exact.
+ #[test]
+ fn an_empty_log_totals_zero_and_is_complete() {
+ let summary = summarise_month(&[], "2026-08");
+
+ assert_eq!(summary.total_syncs, 0);
+ assert_eq!(summary.total_items, 0);
+ assert!(close(summary.total_cost_usd, 0.0));
+ assert!(summary.totals_complete);
+ }
+
+ /// The real charge wins over the estimate, and Composio's own action cost
+ /// is added on top — the audit's own view of what a run cost, unchanged by
+ /// the move onto the contract.
+ #[test]
+ fn cost_uses_the_actual_charge_and_adds_composio() {
+ let mut charged = row("2026-08-20T10:00:00Z", 1, 10, 1, 0.10);
+ charged.actual_charged_usd = Some(0.30);
+ charged.composio_cost_usd = 0.05;
+ let estimated_only = row("2026-08-21T10:00:00Z", 1, 10, 1, 0.20);
+
+ let summary = summarise_month(&[charged, estimated_only], "2026-08");
+
+ // 0.30 (actual) + 0.05 (composio) + 0.20 (estimate) — the estimate on
+ // the charged row is not counted.
+ assert!(close(summary.total_cost_usd, 0.55));
+ }
+
+ /// A row stamped in a later month (clock skew) is skipped rather than
+ /// counted, and does not count as proof the read crossed the boundary —
+ /// the same exclusion the engine-backed month filter made.
+ #[test]
+ fn a_future_stamped_row_is_skipped_and_proves_nothing() {
+ let entries = vec![
+ row("2026-09-01T00:00:00Z", 7, 700, 70, 9.0),
+ row("2026-08-20T10:00:00Z", 1, 10, 1, 0.1),
+ ];
+ let summary = summarise_month(&entries, "2026-08");
+
+ assert_eq!(summary.total_syncs, 1, "the September row is not August's");
+ assert_eq!(summary.total_items, 1);
+ assert!(
+ !summary.totals_complete,
+ "a newer row says nothing about how far back the read reached"
+ );
+ }
+}
+
+#[cfg(test)]
+#[path = "rpc_tests.rs"]
+mod rpc_tests;
diff --git a/src/openhuman/memory/sources/rpc_tests.rs b/src/openhuman/memory/sources/rpc_tests.rs
new file mode 100644
index 0000000000..11c9872b86
--- /dev/null
+++ b/src/openhuman/memory/sources/rpc_tests.rs
@@ -0,0 +1,49 @@
+//! Tests for the driver-backed handlers in [`super`].
+//!
+//! A sibling file rather than an inline `mod tests`, because the null-driver
+//! fixture below names `NullMemoryProvider` and the memory-guard bypass scanner
+//! skips `*_tests.rs` by path but not an inline module. Constructing a null
+//! driver to prove a refusal names it is not a production bypass, and the list
+//! that scanner guards is one that may shrink and must never grow — so the
+//! honest fix is to put the test where the repo already puts tests.
+
+use super::*;
+use crate::core::subsystem::DriverClass;
+// Needed to call the family accessors on the *concrete* null provider
+// below; the handlers above reach them through `dyn MemoryProvider`, where
+// the trait is in scope by construction.
+use crate::openhuman::memory::api::provider::MemoryProvider;
+use std::sync::Arc;
+use tinymemory_api::null::{NullMemoryProvider, NULL_DRIVER_ID};
+
+/// The refusal always names the bound driver. That is the whole contract of
+/// this message: an operator reading it has to be able to tell "no driver
+/// serves sync" apart from "the sync failed", and the driver id is what
+/// carries the difference.
+#[test]
+fn the_refusal_names_the_bound_driver_and_the_family() {
+ let binding = crate::openhuman::memory::binding::bind_provider_for_test(
+ Arc::new(NullMemoryProvider::new()),
+ DriverClass::Null,
+ );
+ let message = unserved(&binding, "source sync", "sync_audit_log");
+
+ assert!(
+ message.contains(NULL_DRIVER_ID),
+ "the refusal must name the driver, got: {message}"
+ );
+ assert!(
+ message.contains("source sync"),
+ "the refusal must name the family, got: {message}"
+ );
+}
+
+/// The null driver really does serve neither family — the premise every
+/// `else` arm in this file rests on. A driver that started serving them
+/// would make those arms unreachable, and silently.
+#[test]
+fn the_null_driver_serves_neither_family() {
+ let provider = NullMemoryProvider::new();
+ assert!(provider.as_source_sync().is_none());
+ assert!(provider.as_coding_sessions().is_none());
+}
diff --git a/src/openhuman/memory/sync/composio/mod.rs b/src/openhuman/memory/sync/composio/mod.rs
index 28cd946f5f..341b307d3c 100644
--- a/src/openhuman/memory/sync/composio/mod.rs
+++ b/src/openhuman/memory/sync/composio/mod.rs
@@ -41,11 +41,34 @@
//! `SyncOutcome`, `SyncReason` — re-exported onward by
//! `integrations::composio`.
//!
-//! None has a capability family: the sync pipelines are engine-internal, and
-//! `MemorySourceSink` addresses source *records*, not provider runs. So this
-//! shim goes when the pipelines themselves move behind the bus — the same ask
-//! as `sync/composio/bus.rs` and `providers/slack/rpc.rs`, both of which call
-//! `tinycortex::run_composio_connection` directly.
+//! # What v1.7.0 took off that list, and what it did not
+//!
+//! **Running a connection is no longer on it.** `MemorySourceSync` landed in
+//! tinymemory v1.7.0, so `run_connection_sync` / `source_sync_state` are
+//! contract members and all five host call sites moved onto the bound driver:
+//! `memory::ops::sync`, `super::bus`, `providers::slack::rpc` (both the trigger
+//! and the status read) and `integrations::composio::ops::providers_ops`. None
+//! of them names the engine crate any more. The member takes no `Config` —
+//! the driver resolves its own and reads the per-source budgets from the
+//! registry it already owns.
+//!
+//! **Two of the value types moved too, and the rest did not.** `SyncOutcome`,
+//! `SyncReason`, `ProviderUserProfile`, `SyncState` and the scope/task
+//! vocabulary are defined in `tinymemory-bus` now and re-exported here through
+//! the engine, so a consumer that wants a *type* can repoint at
+//! `tinymemory_api::composio::…` instead. What stayed behind is behaviour and
+//! I/O: `ProviderContext` (an `Arc<Config>` plus host-seam dispatch), the
+//! `ComposioProvider` trait and the provider registry, `profile_md`, and
+//! `SyncState`'s `load` / `save` — the contract crate holds no traits and no
+//! I/O, so those are the engine's `PersistedSyncState` extension trait. A host
+//! site reaching for `load`/`save` is a site that should be calling
+//! `source_sync_state` instead; the four above now do.
+//!
+//! So what still pins the glob is *target discovery and scheduling*:
+//! `list_sync_targets` / `SyncTarget`, the provider registry, and `periodic`.
+//! No capability family addresses those — `MemorySourceSink` covers source
+//! *records*, not which connections exist — so this shim goes when the registry
+//! moves behind the bus, which is a design pass upstream.
//!
//! # ⚠ One host caller did not get the memo (found 2026-08-25)
//!
diff --git a/src/openhuman/memory/tree/health/mod.rs b/src/openhuman/memory/tree/health/mod.rs
index 13e93d9b90..14105e26cf 100644
--- a/src/openhuman/memory/tree/health/mod.rs
+++ b/src/openhuman/memory/tree/health/mod.rs
@@ -11,14 +11,15 @@
//! `DegradedState` — and `tinycortex::memory::health`'s own docs call the
//! confusion out by name. A swap would compile at neither end.
//!
-//! What the glob carries splits cleanly in two, which is why it cannot go yet
-//! and equally cannot be half-repointed without saying so:
+//! What this file re-exports splits cleanly in two, and the two halves are now
+//! named apart rather than mixed into one `pub use`:
//!
//! - **The taxonomy** (`FailureCode`, `FailureClass`, `PipelineFailure`,
//! `DegradedState`, `classify_embed_error{,_str}`) is `tinycortex`'s; the
-//! engine crate only re-exports it. These would follow the
-//! `memory::sync::sync_status` precedent and be named on `tinycortex`
-//! directly.
+//! engine crate only re-exported it. It follows the
+//! `memory::sync::sync_status` precedent and is named on `tinycortex`
+//! directly below — same items, so no call site changed and none has to when
+//! the engine crate leaves the build.
//! - **The process-global degradation flags** (`mark_*` / `clear_*` /
//! `current_degraded_state`), the `doctor` report and its `test_guard` are
//! defined *in* `tinymemory-core`. They have no home to be repointed at, so
@@ -32,6 +33,35 @@
//! it is the reason moving the flags host-side is a design question rather than
//! a file move.
+// The taxonomy half, named at the engine that **stays**. `tinycortex` is a
+// direct dependency of this crate and is where these are defined
+// (`tinycortex::memory::health`); `tinymemory_core::tree::health` re-exported
+// them out of its own `engine::backend::health`, which is the same
+// `pub use tinycortex::memory::health`. So this changes no item and no wire
+// byte — an explicit `use` shadows the glob below with the identical item, the
+// way `tree_runtime` already does for the contract's node model — and it
+// records which half of this shim survives `tinymemory-core` leaving the build.
+// Same precedent as `memory::people`, `memory::tool_memory` and
+// `memory::sync::sync_status`.
+pub use tinycortex::memory::health::{
+ classify_embed_error, classify_embed_error_str, DegradedState, FailureClass, FailureCode,
+ PipelineFailure,
+};
+
+// 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.
+//
+// `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`.
pub use tinymemory_core::tree::health::*;
pub(crate) mod user_error;
diff --git a/src/openhuman/memory/tree/mod.rs b/src/openhuman/memory/tree/mod.rs
index 0e7f7fb7f4..83cbd1c486 100644
--- a/src/openhuman/memory/tree/mod.rs
+++ b/src/openhuman/memory/tree/mod.rs
@@ -20,12 +20,13 @@
//! `nlp::extract_query_entities` are reached from the archivist, the
//! sub-agent runner, `read_rpc::entities`, `inference::embeddings::rpc` and
//! `retrieval/rpc.rs` in this directory.
-//! - the seven `Tree{LabelStrategy, LeafPayload, ReadHit, ReadRequest,
-//! ReadResult, WriteOutcome, WriteRequest}` I/O types, which the crate
-//! re-exports out of `engine::backend::tree`. Nothing in `src/` names them —
-//! `tests/raw_coverage/memory_threads_raw_coverage_e2e.rs` names all seven,
-//! which is why narrowing this glob to what `src/` uses would compile here
-//! and break the integration lane.
+//! The seven `Tree{LabelStrategy, LeafPayload, ReadHit, ReadRequest,
+//! ReadResult, WriteOutcome, WriteRequest}` I/O types used to be on that list
+//! too. They are **not** engine-owned — the crate re-exports them out of
+//! `engine::backend::tree`, i.e. `tinycortex` — so they are named there
+//! directly below and no longer depend on this glob. Nothing in `src/` uses
+//! them; `tests/raw_coverage/memory_threads_raw_coverage_e2e.rs` names all
+//! seven, which is why they are still re-exported at all.
//!
//! (`graph` is the fifth unshadowed name and has no caller under this path at
//! all — it is carried only because the glob is all-or-nothing.)
@@ -35,6 +36,26 @@
//! pinned by the engine's *scoring and summarisation* internals, and it goes
//! when those move behind the bus — not before.
+// The seven tree I/O contracts, named at the crate that defines them
+// (`tinycortex::memory::tree::io`). `tinymemory_core::tree` re-exports them out
+// of `engine::backend::tree`, which is `pub use tinycortex::memory::tree`, so
+// this is the same item under a different crate alias — an explicit `use`
+// shadowing the glob below with itself. Nothing in `src/` names them;
+// `tests/raw_coverage/memory_threads_raw_coverage_e2e.rs` names all seven
+// through this path, which is why they are re-exported rather than dropped, and
+// why they now keep resolving once `tinymemory-core` leaves the build.
+pub use tinycortex::memory::tree::{
+ TreeLabelStrategy, TreeLeafPayload, TreeReadHit, TreeReadRequest, TreeReadResult,
+ TreeWriteOutcome, TreeWriteRequest,
+};
+
+// What is left of the glob is the scoring and summarisation half, and it is
+// `tinymemory-core`'s own code rather than a re-export: `score` (embed /
+// extract / store / resolver), `summarise`, `nlp` and `ingest`, plus `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. This shim goes when
+// scoring and summarisation move behind the bus, not before.
pub use tinymemory_core::tree::*;
pub mod health;
diff --git a/src/openhuman/memory/tree/retrieval/mod.rs b/src/openhuman/memory/tree/retrieval/mod.rs
index 48ed15158e..8debba8cb0 100644
--- a/src/openhuman/memory/tree/retrieval/mod.rs
+++ b/src/openhuman/memory/tree/retrieval/mod.rs
@@ -8,10 +8,28 @@
// Engine-owned, and the names are a trap worth naming: `RetrievalHit`,
// `QueryResponse`, `NodeKind` and `EntityMatch` here are **not** the contract's
// `RetrievalHit`, `RetrievalResponse`, `RetrievalNodeKind` and `EntityMatch`.
-// The engine's hit carries a `tree_kind` the contract's has no field for, so
-// repointing this shim at `memory::api::provider` is a wire change and not a
+// Repointing this shim at `memory::api::provider` is a wire change and not a
// path swap. Probe the item identity before assuming a carve-out is free.
//
+// **The field that used to prove that has changed; the conclusion has not.**
+// This comment said the contract's hit "has no field for" `tree_kind`. It has
+// one as of the pinned v1.7.0 — `tree_kind: Option<String>`, `#[serde(default,
+// skip_serializing_if)]` — so re-derive the difference from the types rather
+// than from this sentence. What still separates them, checked against
+// `tinymemory-bus`'s `provider::retrieval` and tinycortex's
+// `memory::retrieval::types`:
+//
+// - `tree_kind` is an **open string** on the contract and the closed
+// `TreeKind` enum on the engine, so a hit crossing between them needs a
+// conversion that can fail in one direction and is lossy in neither;
+// - the engine's hit is non-optional there — a bare leaf reports
+// `TreeKind::Source` via `leaf_tree_placeholder`, where the contract encodes
+// the same absence as `None`. Those are different answers to "which tree did
+// this come from", and a swap would silently relabel every unsealed leaf.
+//
+// So this is still a wire change, and one whose translation has to be written
+// down at the handler rather than assumed by the type system.
+//
// What keeps this line alive (#5560): `fast_retrieve` + `FastRetrieveOptions`
// (memory::agent::ops, memory::schema::handlers), `types::{NodeKind,
// QueryResponse, RetrievalHit}` (read_rpc::chunks, the sub-agent runner),
@@ -24,6 +42,14 @@ pub use tinymemory_core::tree::retrieval::*;
pub mod rpc;
pub mod schemas;
+/// Chunk-staging fixtures for [`rpc`]'s inline tests.
+///
+/// Test-only, and in a directory both memory lints skip by path — see the
+/// module's own docs for why a genuinely dev-only engine reference had to move
+/// out of the inline `#[cfg(test)]` block to be classified as one.
+#[cfg(test)]
+pub(crate) mod test_support;
+
// The controller aggregators this domain's RPC surface defines. Aliased
// exactly as the pre-extraction module exported them.
pub use schemas::{
diff --git a/src/openhuman/memory/tree/retrieval/rpc.rs b/src/openhuman/memory/tree/retrieval/rpc.rs
index a05d248ca1..3b312e1b20 100644
--- a/src/openhuman/memory/tree/retrieval/rpc.rs
+++ b/src/openhuman/memory/tree/retrieval/rpc.rs
@@ -505,10 +505,17 @@ mod tests {
MemoryCategory, MemoryEntry, MemoryTaint, NamespaceMemoryHit, NamespaceSummary,
};
use crate::openhuman::memory::source_scope::with_source_scope;
+ // The engine-backed chunk writes these fixtures need live in
+ // `retrieval::test_support` rather than here. They are the engine's chunk
+ // store — `MemoryChunks` is read-only on the contract — and they are
+ // test-only, which is exactly the pair `direct_engine_refs_tests`'
+ // line-based scanner cannot tell apart when the reference sits inside an
+ // inline `#[cfg(test)]` module. See that module's docs.
+ use crate::openhuman::memory::tree::retrieval::test_support::{
+ stage_test_chunks, upsert_chunks,
+ };
use tinymemory_api::chunks::{chunk_id, Chunk, Metadata, SourceRef};
use tinymemory_api::null::NullMemoryProvider;
- use tinymemory_core::store::chunks::store::upsert_chunks;
- use tinymemory_core::store::content as content_store;
fn test_config() -> (TempDir, Config) {
let tmp = TempDir::new().unwrap();
@@ -522,22 +529,6 @@ mod tests {
(tmp, cfg)
}
- /// Write chunks the in-process driver can read back — both the row and the
- /// staged content body, since a hit carries the body.
- fn stage_test_chunks(cfg: &Config, chunks: &[Chunk]) {
- let content_root = cfg.memory_tree_content_root();
- std::fs::create_dir_all(&content_root).expect("create content_root for test");
- let staged = content_store::stage_chunks(&content_root, chunks)
- .expect("stage_chunks for test chunks");
- tinymemory_core::store::chunks::store::with_connection(cfg, |conn| {
- let tx = conn.unchecked_transaction()?;
- tinymemory_core::store::chunks::store::upsert_staged_chunks_tx(&tx, &staged)?;
- tx.commit()?;
- Ok(())
- })
- .expect("persist staged chunk pointers");
- }
-
fn sample_chunk(source: &str, seq: u32) -> Chunk {
let ts = Utc.timestamp_millis_opt(1_700_000_000_000).unwrap();
Chunk {
diff --git a/src/openhuman/memory/tree/retrieval/test_support/mod.rs b/src/openhuman/memory/tree/retrieval/test_support/mod.rs
new file mode 100644
index 0000000000..6709eab4e3
--- /dev/null
+++ b/src/openhuman/memory/tree/retrieval/test_support/mod.rs
@@ -0,0 +1,60 @@
+//! Chunk-staging fixtures for the retrieval handler tests.
+//!
+//! One reason this is a directory of its own, and it is a classification rather
+//! than a hiding place — the same reason
+//! [`memory::tool_memory::test_support`](crate::openhuman::memory::tool_memory)
+//! exists.
+//!
+//! `rpc.rs`'s inline `#[cfg(test)]` module needs chunk rows the **real**
+//! in-process driver can read back, because one of its tests proves the source
+//! gate end to end rather than against a recording double. Writing those rows
+//! means the engine's chunk store: `MemoryChunks` on the contract is a read
+//! family (`list_chunks` / `get_chunk` / `chunk_detail` / `storage_kinds` /
+//! `chunk_embeddings`) with no write or transaction door, and none should be
+//! added — `with_connection` hands out a `rusqlite` handle, which no
+//! engine-neutral contract can promise.
+//!
+//! So the reference is real and unavoidable, and it is also **test-only**:
+//! `cfg(test)` code links the `tinymemory-core` **dev-dependency**, which
+//! survives #5560's shed and puts no byte of the engine in the shipped binary.
+//!
+//! `memory::direct_engine_refs_tests` could not see that on its own. Its
+//! scanner reads line by line and skips only comments and whole files —
+//! deliberately, because brace-tracking inline `#[cfg(test)]` blocks is
+//! complexity its docs say it does not want — so a fixture write kept `rpc.rs`
+//! on the direct-reference allowlist under a `NeedsWiderSeam` verdict that
+//! described a *production* gap the file does not have. That made "deliberate"
+//! and "not migrated yet" look identical in the one list that exists to tell
+//! them apart.
+//!
+//! `test_support/` is the escape hatch both memory lints already honour by path
+//! (each matches on a `test_support` path *component*, which is why this is a
+//! directory and not a `test_support.rs`). Nothing about the writes changed;
+//! only where the line that names the engine lives.
+
+use tinymemory_api::chunks::Chunk;
+
+use crate::openhuman::config::Config;
+
+pub(crate) use tinymemory_core::store::chunks::store::upsert_chunks;
+
+/// Write chunks the in-process driver can read back — both the row and the
+/// staged content body, since a hit carries the body.
+pub(crate) fn stage_test_chunks(cfg: &Config, chunks: &[Chunk]) {
+ let content_root = cfg.memory_tree_content_root();
+ std::fs::create_dir_all(&content_root).expect("create content_root for test");
+ let staged = tinymemory_core::store::content::stage_chunks(&content_root, chunks)
+ .expect("stage_chunks for test chunks");
+ log::debug!(
+ "[memory-tree][retrieval][test-support] staging chunks count={} content_root={}",
+ chunks.len(),
+ content_root.display()
+ );
+ tinymemory_core::store::chunks::store::with_connection(cfg, |conn| {
+ let tx = conn.unchecked_transaction()?;
+ tinymemory_core::store::chunks::store::upsert_staged_chunks_tx(&tx, &staged)?;
+ tx.commit()?;
+ Ok(())
+ })
+ .expect("persist staged chunk pointers");
+}
diff --git a/src/openhuman/modules/memory.rs b/src/openhuman/modules/memory.rs
index 5612176bb2..be0639ef54 100644
--- a/src/openhuman/modules/memory.rs
+++ b/src/openhuman/modules/memory.rs
@@ -48,7 +48,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.6.0";
+pub(crate) const ARTIFACT_CAPABILITIES_PIN: &str = "1.7.0";
/// The capability families the **pinned artifact** actually serves.
///
@@ -96,6 +96,11 @@ const ARTIFACT_CAPABILITIES: &[Capability] = &[
Capability::Retrieval,
Capability::Profile,
Capability::Episodic,
+ // Arrived in v1.7.0 — the sync-execution and coding-session families that
+ // let the host stop reaching into the engine for them. Verified against the
+ // module's declared `methods` list at that tag, which serves all ten.
+ Capability::SourceSync,
+ Capability::CodingSessions,
];
/// Escape hatch for a locally-built module.
@@ -147,6 +152,13 @@ use tinymemory_api::chunks::Chunk;
use tinymemory_api::error::MemoryError;
use tinymemory_api::goals::GoalsDoc;
use tinymemory_api::health::MemoryHealth;
+use tinymemory_api::provider::sessions::{
+ CodingSessionIngestReport, CodingSessionIngestRequest, CodingSessionSource,
+};
+use tinymemory_api::provider::sync::{
+ RawArchiveCoverage, RawRebuildOutcome, SourceSyncState, SourceSyncStatus, SyncAuditEntry,
+ SyncRunOutcome,
+};
use tinymemory_api::provider::types::{
ChunkEntityOccurrence, DiffReport, EntityHit, EntityOccurrence, ExportPage, ExportRecord,
FlushOutcome, ForgetOutcome, ForgetSelector, ImportOutcome, IngestItem, IngestOutcome,
@@ -156,12 +168,12 @@ use tinymemory_api::provider::types::{
use tinymemory_api::provider::{
AddressBookSeedOutcome, ChunkDetail, ChunkEmbedding, ChunkListRow, ChunkQuery,
ConversationSegment, CoverWindowQuery, EntityMatch, EpisodicEvent, EpisodicTurn, FacetType,
- FastRetrieveQuery, MemoryChunks, MemoryCore, MemoryDiff, MemoryDocuments, MemoryEntities,
- MemoryEpisodic, MemoryGoals, MemoryGraph, MemoryIngest, MemoryMaintenance, MemoryPeople,
- MemoryPortability, MemoryProfile, MemoryProvider, MemoryRecall, MemoryRetrieval,
- MemorySourceSink, MemoryToolMemory, MemoryTree, PersonHandle, PersonInteraction, PersonRecord,
- PersonScore, ProfileFacet, RankedPerson, ResolvedPerson, RetrievalHit, RetrievalResponse,
- SourceRetrievalQuery, SourceTotal, UserState,
+ FastRetrieveQuery, MemoryChunks, MemoryCodingSessions, MemoryCore, MemoryDiff, MemoryDocuments,
+ MemoryEntities, MemoryEpisodic, MemoryGoals, MemoryGraph, MemoryIngest, MemoryMaintenance,
+ MemoryPeople, MemoryPortability, MemoryProfile, MemoryProvider, MemoryRecall, MemoryRetrieval,
+ MemorySourceSink, MemorySourceSync, MemoryToolMemory, MemoryTree, PersonHandle,
+ PersonInteraction, PersonRecord, PersonScore, ProfileFacet, RankedPerson, ResolvedPerson,
+ RetrievalHit, RetrievalResponse, SourceRetrievalQuery, SourceTotal, UserState,
};
use tinymemory_api::recall::OwnedRecallOpts;
use tinymemory_api::tool_memory::ToolMemoryRule;
@@ -524,6 +536,14 @@ impl MemoryProvider for ModuleMemoryProvider {
fn as_profile(&self) -> Option<&dyn MemoryProfile> {
artifact_serves(Capability::Profile).then_some(self as &dyn MemoryProfile)
}
+
+ fn as_source_sync(&self) -> Option<&dyn MemorySourceSync> {
+ artifact_serves(Capability::SourceSync).then_some(self as &dyn MemorySourceSync)
+ }
+
+ fn as_coding_sessions(&self) -> Option<&dyn MemoryCodingSessions> {
+ artifact_serves(Capability::CodingSessions).then_some(self as &dyn MemoryCodingSessions)
+ }
fn as_episodic(&self) -> Option<&dyn MemoryEpisodic> {
artifact_serves(Capability::Episodic).then_some(self as &dyn MemoryEpisodic)
}
@@ -1052,6 +1072,97 @@ impl MemoryMaintenance for ModuleMemoryProvider {
}
}
+#[async_trait]
+impl MemorySourceSync for ModuleMemoryProvider {
+ async fn run_connection_sync(
+ &self,
+ toolkit: &str,
+ connection_id: &str,
+ ) -> Result<SyncRunOutcome, MemoryError> {
+ module_call!(
+ self,
+ "run_connection_sync",
+ "RunConnectionSync",
+ (toolkit, connection_id)
+ )
+ }
+ async fn source_sync_state(
+ &self,
+ toolkit: &str,
+ connection_id: &str,
+ ) -> Result<Option<SourceSyncState>, MemoryError> {
+ module_call!(
+ self,
+ "source_sync_state",
+ "SourceSyncState",
+ (toolkit, connection_id)
+ )
+ }
+ async fn sync_audit_log(
+ &self,
+ limit: Option<usize>,
+ ) -> Result<Vec<SyncAuditEntry>, MemoryError> {
+ module_call!(self, "sync_audit_log", "SyncAuditLog", (limit,))
+ }
+ async fn estimate_sync_cost_usd(
+ &self,
+ input_tokens: u64,
+ output_tokens: u64,
+ ) -> Result<f64, MemoryError> {
+ module_call!(
+ self,
+ "estimate_sync_cost_usd",
+ "EstimateSyncCostUsd",
+ (input_tokens, output_tokens)
+ )
+ }
+ async fn sync_statuses(&self) -> Result<Vec<SourceSyncStatus>, MemoryError> {
+ module_call!(self, "sync_statuses", "SyncStatuses", ())
+ }
+ async fn raw_archive_coverage(
+ &self,
+ tree_scope: &str,
+ archive_source_id: &str,
+ ) -> Result<RawArchiveCoverage, MemoryError> {
+ module_call!(
+ self,
+ "raw_archive_coverage",
+ "RawArchiveCoverage",
+ (tree_scope, archive_source_id)
+ )
+ }
+ async fn rebuild_from_raw_archive(
+ &self,
+ tree_scope: &str,
+ archive_source_id: &str,
+ ) -> Result<RawRebuildOutcome, MemoryError> {
+ module_call!(
+ self,
+ "rebuild_from_raw_archive",
+ "RebuildFromRawArchive",
+ (tree_scope, archive_source_id)
+ )
+ }
+}
+
+#[async_trait]
+impl MemoryCodingSessions for ModuleMemoryProvider {
+ async fn coding_session_status(&self) -> Result<Vec<CodingSessionSource>, MemoryError> {
+ module_call!(self, "coding_session_status", "CodingSessionStatus", ())
+ }
+ async fn ingest_coding_sessions(
+ &self,
+ request: CodingSessionIngestRequest,
+ ) -> Result<CodingSessionIngestReport, MemoryError> {
+ module_call!(
+ self,
+ "ingest_coding_sessions",
+ "IngestCodingSessions",
+ (request,)
+ )
+ }
+}
+
#[async_trait]
impl MemoryEpisodic for ModuleMemoryProvider {
async fn insert_turn(&self, turn: &EpisodicTurn) -> Result<i64, MemoryError> {
diff --git a/src/openhuman/modules/registry.rs b/src/openhuman/modules/registry.rs
index 8680e99a1d..fca4b9f300 100644
--- a/src/openhuman/modules/registry.rs
+++ b/src/openhuman/modules/registry.rs
@@ -202,63 +202,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.6.0",
- release_url: "https://github.com/tinyhumansai/tinymemory/releases/tag/v1.6.0",
+ version: "1.7.0",
+ release_url: "https://github.com/tinyhumansai/tinymemory/releases/tag/v1.7.0",
assets: &[
PlatformAsset {
host_key: "ubuntu-24.04-x86_64",
- archive: "tinymemory-module-1.6.0-ubuntu-24.04-x86_64.tar.gz",
- sha256: "a780b495e3cf9c1f4270226001848be6efb9bc97424b377af03d67e6ab1aee3a",
+ archive: "tinymemory-module-1.7.0-ubuntu-24.04-x86_64.tar.gz",
+ sha256: "a51e0130cdcee917879c0adf83553b1d97ffbfac8cafa90db29fe6342d8727d4",
},
PlatformAsset {
host_key: "ubuntu-24.04-arm64",
- archive: "tinymemory-module-1.6.0-ubuntu-24.04-arm64.tar.gz",
- sha256: "2bc60707e0d2ecc5bd6693ad6d29ef5652c0e64efa06fc602f0972cd8e6ab887",
+ archive: "tinymemory-module-1.7.0-ubuntu-24.04-arm64.tar.gz",
+ sha256: "78048eea29e55aae3b10795364e6b95b4f81b0ef42210e13f0e4ad3bb7fcd6d2",
},
PlatformAsset {
host_key: "ubuntu-22.04-x86_64",
- archive: "tinymemory-module-1.6.0-ubuntu-22.04-x86_64.tar.gz",
- sha256: "7b932203e56867d2c1a0cd22573bea096e664a713dddad37255f5f401affbd5e",
+ archive: "tinymemory-module-1.7.0-ubuntu-22.04-x86_64.tar.gz",
+ sha256: "9d45df2ea11a1207bf9ba535e32acdd5312a3256df656e21a03b6ab5da0264f4",
},
PlatformAsset {
host_key: "ubuntu-22.04-arm64",
- archive: "tinymemory-module-1.6.0-ubuntu-22.04-arm64.tar.gz",
- sha256: "e7fef115574038317c82482e812400254634a5517554a25ed51ed23e34ff057f",
+ archive: "tinymemory-module-1.7.0-ubuntu-22.04-arm64.tar.gz",
+ sha256: "4a9adfa26f9f12cf9ba06dc186b6b25bad5729b0cdc74b28da2df67b8e692260",
},
PlatformAsset {
host_key: "macos-26-arm64",
- archive: "tinymemory-module-1.6.0-macos-26-arm64.tar.gz",
- sha256: "f14ea5685ae8560622289a4ec7aa4c1f1edc6e529f0afbbd213cdbff7d8b5a3c",
+ archive: "tinymemory-module-1.7.0-macos-26-arm64.tar.gz",
+ sha256: "9174413921f338eb1345c1ed0960eacb2c0d18e05270ae4c76b9b9f7c946cb7a",
},
PlatformAsset {
host_key: "macos-26-x86_64",
- archive: "tinymemory-module-1.6.0-macos-26-x86_64.tar.gz",
- sha256: "61f67406736d818244e751fc052aa260d33d942c9ea172df7537410f19610825",
+ archive: "tinymemory-module-1.7.0-macos-26-x86_64.tar.gz",
+ sha256: "0b0a862d5d0b8447b26bec62a6fc99e8c7f8577b63aeb98f2f463614c6ea6796",
},
PlatformAsset {
host_key: "macos-15-arm64",
- archive: "tinymemory-module-1.6.0-macos-15-arm64.tar.gz",
- sha256: "98c369b79c0bc0d41cc7692a0d6b1fbd1d151b2e7587dc7214ed0413f303f260",
+ archive: "tinymemory-module-1.7.0-macos-15-arm64.tar.gz",
+ sha256: "d1eb058f78e5559646824824c859373a2b9b9869886a99e672025371ca9e295f",
},
PlatformAsset {
host_key: "macos-15-x86_64",
- archive: "tinymemory-module-1.6.0-macos-15-x86_64.tar.gz",
- sha256: "fb87b6aa29284908ca23b4eeab80a282b0c9700aaeb768c1cfcbab63f3161522",
+ archive: "tinymemory-module-1.7.0-macos-15-x86_64.tar.gz",
+ sha256: "ce4510f57a59827163e9cdab6c530d265e61ffe1e3389f81eef0b7d70b857de4",
},
PlatformAsset {
host_key: "windows-2025-x86_64",
- archive: "tinymemory-module-1.6.0-windows-2025-x86_64.zip",
- sha256: "ddcd7cf888408f42f249b79a4b84b55151958e8733310c4d8b3cc3532eedc3ae",
+ archive: "tinymemory-module-1.7.0-windows-2025-x86_64.zip",
+ sha256: "c589f4b95b77241e66927451ceb57e63141a66a639c4d09cf8d53785a95fff6f",
},
PlatformAsset {
host_key: "windows-2022-x86_64",
- archive: "tinymemory-module-1.6.0-windows-2022-x86_64.zip",
- sha256: "19e3b1cfbfef9989782f3627952c1bbba2ba280cee65fdc4fbd7cc2e620d0b4d",
+ archive: "tinymemory-module-1.7.0-windows-2022-x86_64.zip",
+ sha256: "74b6224d60d1e3b44798976551f2c50550601ba20a63cc72eaa7a0ffa12360d5",
},
PlatformAsset {
host_key: "windows-11-arm64",
- archive: "tinymemory-module-1.6.0-windows-11-arm64.zip",
- sha256: "319b68056f62e3f295820d83138a5b485c8ed2216805480d9b3c119c12726b59",
+ archive: "tinymemory-module-1.7.0-windows-11-arm64.zip",
+ sha256: "c7c85119e7c41c1ce48e8efd95daa496c9965988701ecd1c7d23f9aef3dab2dc",
},
],
// Eager, unlike the two codecs above. A codec that is never asked for should
diff --git a/vendor/tinymemory b/vendor/tinymemory
index d85b8f9814..4020ab5fe1 160000
--- a/vendor/tinymemory
+++ b/vendor/tinymemory
@@ -1 +1 @@
-Subproject commit d85b8f98147c4706791a5e1ae1e4127d7bbdc298
+Subproject commit 4020ab5fe136d6fa6af84eaa02ac0255df8a9df8