The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
refactor(guard): reorganise memory guard module into family‑based sub‑modules
Steven Enamakel5ebc824bd819
diff --git a/crates/openhuman-core/src/memory/guard/budget.rs b/crates/openhuman-core/src/memory/guard/budget.rsdeleted file mode 100644index dce38c8ce3..0000000000--- a/crates/openhuman-core/src/memory/guard/budget.rs+++ /dev/null@@ -1,89 +0,0 @@-//! Char-budget truncation — step 6 of the guard's enforcement chain.-//!-//! Pure functions over already-materialised values, with no policy, no config-//! and no I/O, so the budget arithmetic is testable without constructing a-//! provider.-//!-//! ## Chars, not bytes-//!-//! Every count here is [`str::chars`], never [`str::len`]. `len()` is a byte-//! count, so a budget expressed in "chars" would truncate a Japanese or emoji-//! transcript to a third of its stated size — and, worse, `String::truncate`-//! on a byte index panics when that index is not a char boundary. Slicing at a-//! char boundary is the only form that is both correct and total.--use crate::memory::api::types::MemoryEntry;--/// Truncate `content` to at most `max_chars` characters.-///-/// Returns the input unchanged (and unallocated) when it already fits, so the-/// common case costs nothing.-pub fn truncate_content(content: &str, max_chars: usize) -> std::borrow::Cow<'_, str> {- let mut chars = content.char_indices();- match chars.nth(max_chars) {- // Fewer than `max_chars + 1` chars ⇒ it fits.- None => std::borrow::Cow::Borrowed(content),- Some((byte_idx, _)) => std::borrow::Cow::Owned(content[..byte_idx].to_string()),- }-}--/// Outcome of applying a recall budget to a result set.-#[derive(Debug, Clone)]-pub struct BudgetOutcome {- /// Entries that survived, in input order. At most one of them has had its- /// `content` shortened — the entry that straddles the budget boundary.- pub entries: Vec<MemoryEntry>,- /// How many entries were dropped whole because the budget was already- /// spent when they were reached.- pub dropped: usize,- /// How many characters of content were removed in total, across the- /// truncated entry and the dropped ones.- pub trimmed_chars: usize,-}--/// Apply a **cumulative** char budget across a ranked recall result.-///-/// The budget is spent in rank order, which is what makes truncation-/// least-destructive: recall returns most-relevant-first, so the entries that-/// lose content are the ones the caller was least likely to use. An entry that-/// straddles the boundary is kept with its content shortened rather than-/// dropped, because dropping it would silently change the hit count a caller-/// may be reporting.-///-/// A zero-length budget is not special-cased here — the caller decides whether-/// `0` means "disabled" (it does; see `GuardPolicy::recall_budget`) before-/// calling.-pub fn truncate_entries(entries: Vec<MemoryEntry>, max_chars: usize) -> BudgetOutcome {- let mut remaining = max_chars;- let mut kept: Vec<MemoryEntry> = Vec::with_capacity(entries.len());- let mut dropped = 0usize;- let mut trimmed_chars = 0usize;-- for mut entry in entries {- if remaining == 0 {- trimmed_chars += entry.content.chars().count();- dropped += 1;- continue;- }- let len = entry.content.chars().count();- if len <= remaining {- remaining -= len;- kept.push(entry);- } else {- trimmed_chars += len - remaining;- entry.content = truncate_content(&entry.content, remaining).into_owned();- remaining = 0;- kept.push(entry);- }- }-- BudgetOutcome {- entries: kept,- dropped,- trimmed_chars,- }-}--#[cfg(test)]-#[path = "budget_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/memory/guard/budget_tests.rs b/crates/openhuman-core/src/memory/guard/budget_tests.rsdeleted file mode 100644index dde18c6e74..0000000000--- a/crates/openhuman-core/src/memory/guard/budget_tests.rs+++ /dev/null@@ -1,77 +0,0 @@-//! Step 6 — the pure char-budget arithmetic.--use super::*;-use crate::memory::api::types::{MemoryCategory, MemoryEntry, MemoryTaint};--fn entry(content: &str) -> MemoryEntry {- MemoryEntry {- id: "id".into(),- key: "key".into(),- content: content.into(),- namespace: Some("ns".into()),- category: MemoryCategory::Core,- timestamp: "2026-01-01T00:00:00Z".into(),- session_id: None,- score: None,- taint: MemoryTaint::Internal,- }-}--#[test]-fn truncate_content_leaves_a_fitting_string_untouched() {- let out = truncate_content("hello", 5);- assert_eq!(out, "hello");- assert!(matches!(out, std::borrow::Cow::Borrowed(_)));-}--#[test]-fn truncate_content_cuts_to_the_budget() {- assert_eq!(truncate_content("hello world", 5), "hello");-}--#[test]-fn guard_budget_counts_chars_not_bytes() {- // Six chars, eighteen bytes. A byte-counting implementation would cut this- // to two chars — or panic on a non-char-boundary index.- let multibyte = "日本語です、はい";- assert_eq!(truncate_content(multibyte, 3), "日本語");- assert_eq!(truncate_content(multibyte, 100), multibyte);-}--#[test]-fn guard_truncates_recall_results_to_the_budget() {- let out = truncate_entries(vec![entry("aaaa"), entry("bbbb"), entry("cccc")], 6);- assert_eq!(- out.entries.len(),- 2,- "the straddling entry is kept, trimmed"- );- assert_eq!(out.entries[0].content, "aaaa");- assert_eq!(out.entries[1].content, "bb");- assert_eq!(out.dropped, 1);- assert_eq!(out.trimmed_chars, 2 + 4);-}--#[test]-fn a_budget_that_fits_changes_nothing() {- let out = truncate_entries(vec![entry("aaaa"), entry("bbbb")], 100);- assert_eq!(out.entries.len(), 2);- assert_eq!(out.dropped, 0);- assert_eq!(out.trimmed_chars, 0);-}--#[test]-fn a_zero_budget_drops_everything_when_the_caller_asks_for_one() {- // `GuardPolicy::recall_budget` never passes 0 (it reads 0 as "disabled"),- // but the pure function must still be total rather than panicking.- let out = truncate_entries(vec![entry("aaaa")], 0);- assert!(out.entries.is_empty());- assert_eq!(out.dropped, 1);-}--#[test]-fn budget_spends_in_rank_order_so_the_top_hit_survives_whole() {- let out = truncate_entries(vec![entry("top hit"), entry("second")], 7);- assert_eq!(out.entries[0].content, "top hit");- assert_eq!(out.dropped, 1);-}diff --git a/crates/openhuman-core/src/memory/guard/families.rs b/crates/openhuman-core/src/memory/guard/families.rsdeleted file mode 100644index a0fcfe0c29..0000000000--- a/crates/openhuman-core/src/memory/guard/families.rs+++ /dev/null@@ -1,49 +0,0 @@-//! The ten optional-family decorators — the load-bearing half of the guard.-//!-//! ## Why these exist at all-//!-//! [`MemoryProvider::as_tree`] and its nine siblings return a **borrow** of a-//! family trait object. If [`MemoryGuard`]'s override simply forwarded-//! `self.inner.as_tree()`, every caller that reached memory through a family-//! accessor would hold a raw, unguarded driver handle — and the guard's whole-//! reason to exist ("the only handle product code receives") would be-//! bypassable by one method call. Nine of the thirteen families are *only*-//! reachable that way.-//!-//! So each family gets its own decorator, and the accessor hands back a borrow-//! of that. Because the accessor returns a reference, the decorators cannot be-//! constructed on demand inside it — a reference to a temporary does not-//! outlive the call — so they are **fields on the guard, built once at-//! construction**. That is also what makes their presence mirror the inner-//! driver's exactly: a field exists iff `inner.provides(...)` said so, which is-//! what keeps `audit_provider` happy.-//!-//! ## Why each decorator holds the provider, not the family-//!-//! A `GuardedTree { inner: &dyn MemoryTree }` borrowed out of an-//! `Arc<dyn MemoryProvider>` the same struct owns is self-referential, and Rust-//! has no way to express that without unsafe pinning. Holding-//! `Arc<dyn MemoryProvider>` and re-deriving the family per call sidesteps it-//! entirely, at the cost of one `Option` unwrap that is structurally-//! unreachable — see [`family`](GuardedTree::family).-//!-//! [`MemoryGuard`]: super::MemoryGuard--#[cfg(test)]-#[path = "families_tests.rs"]-mod tests;--mod types;--mod graph_and_bookkeeping;-mod ingest_and_tree;-mod retrieval_and_profile;-mod typed_ingest_and_answer;--pub use types::{- GuardedAnswer, GuardedChunks, GuardedCodingSessions, GuardedConversationIngest, GuardedDiff,- GuardedDocumentIngest, GuardedDocuments, GuardedEntities, GuardedEpisodic, GuardedEventIngest,- GuardedGoals, GuardedGraph, GuardedIngest, GuardedLearningIngest, GuardedMaintenance,- GuardedPeople, GuardedProfile, GuardedRetrieval, GuardedScoring, GuardedSourceSync,- GuardedSources, GuardedToolMemory, GuardedTree,-};diff --git a/crates/openhuman-core/src/memory/guard/families/graph_and_bookkeeping.rs b/crates/openhuman-core/src/memory/guard/families/graph_and_bookkeeping.rsdeleted file mode 100644index caf88721b0..0000000000--- a/crates/openhuman-core/src/memory/guard/families/graph_and_bookkeeping.rs+++ /dev/null@@ -1,621 +0,0 @@-//! Guarded `Entities`, `Graph`, `Diff`, `Goals`, `ToolMemory`, `Sources`,-//! `Maintenance`, and `People` — the knowledge-graph and bookkeeping-//! families.-//!-//! Split out of `families.rs`; see [`super::types`] for the shared decorator-//! scaffolding these `impl` blocks build on.--use crate::memory::api::capabilities::Capability;-use crate::memory::api::error::MemoryError;-use crate::memory::api::goals::GoalsDoc;-use crate::memory::api::provider::diagnosis::{DegradedCapabilities, Diagnosis};-use crate::memory::api::provider::people::{- AddressBookSeedOutcome, PersonHandle, PersonInteraction, PersonRecord, PersonScore,- RankedPerson, ResolvedPerson,-};-use crate::memory::api::provider::types::{- BackfillTreesOutcome, BackfillTreesRequest, ChunkEntityOccurrence, DiffReport, EntityHit,- EntityOccurrence, ForgetOutcome, ForgetSelector, IngestOutcome, MaintenanceReport,- PurgeOutcome, SnapshotRef, SourceItem,-};-use crate::memory::api::provider::{- MemoryDiff, MemoryEntities, MemoryGoals, MemoryGraph, MemoryMaintenance, MemoryPeople,- MemorySourceSink, MemoryToolMemory,-};-use crate::memory::api::tool_memory::ToolMemoryRule;-use crate::memory::api::types::{GraphRelationRecord, MemoryKvRecord, MemoryTaint};-use async_trait::async_trait;--use super::super::audit::{trace_allowed, NO_NAMESPACE};-use super::types::{- GuardedDiff, GuardedEntities, GuardedGoals, GuardedGraph, GuardedMaintenance, GuardedPeople,- GuardedSources, GuardedToolMemory,-};--// ── Entities ─────────────────────────────────────────────────────────────────--#[async_trait]-impl MemoryEntities for GuardedEntities {- async fn entities(- &self,- namespace: &str,- query: Option<&str>,- limit: usize,- ) -> Result<Vec<EntityHit>, MemoryError> {- self.policy.admit_read(- Capability::Entities,- "entities.entities",- namespace,- query.is_some(),- )?;- let redacted = query.map(|q| self.policy.redact_outbound(q).into_owned());- self.family()?- .entities(namespace, redacted.as_deref(), limit)- .await- }-- async fn entity_edges(- &self,- namespace: &str,- entity_id: &str,- limit: usize,- ) -> Result<Vec<GraphRelationRecord>, MemoryError> {- self.policy.admit_read(- Capability::Entities,- "entities.entity_edges",- namespace,- false,- )?;- self.family()?- .entity_edges(namespace, entity_id, limit)- .await- }-- async fn touch_entities(- &self,- namespace: &str,- entity_ids: &[String],- ) -> Result<(), MemoryError> {- self.policy.admit_write(- Capability::Entities,- "entities.touch_entities",- namespace,- false,- )?;- self.family()?.touch_entities(namespace, entity_ids).await- }-- /// The occurrence index has no namespace and the contract gives this member- /// no scope argument, so there is nothing to intersect — the tier check is- /// the whole gate. Worth stating rather than leaving as an apparent- /// omission beside the scoped members above.- async fn top_entities(- &self,- kind: Option<&str>,- limit: usize,- ) -> Result<Vec<EntityOccurrence>, MemoryError> {- self.policy.admit_read(- Capability::Entities,- "entities.top_entities",- NO_NAMESPACE,- false,- )?;- self.family()?.top_entities(kind, limit).await- }-- /// Scoped by the chunk ids the caller already holds: it can only name- /// chunks a previous, scoped read handed it, so this adds no reach beyond- /// the read that produced them.- async fn chunk_entities(- &self,- chunk_ids: &[String],- kinds: Option<&[String]>,- ) -> Result<Vec<ChunkEntityOccurrence>, MemoryError> {- self.policy.admit_read(- Capability::Entities,- "entities.chunk_entities",- NO_NAMESPACE,- false,- )?;- self.family()?.chunk_entities(chunk_ids, kinds).await- }-- /// Returns ids only, never content. A caller still has to read those chunks- /// through [`MemoryChunks`] to see anything, and that path applies the- /// scope intersection.- async fn entity_chunk_ids(- &self,- entity_id: &str,- limit: usize,- ) -> Result<Vec<String>, MemoryError> {- self.policy.admit_read(- Capability::Entities,- "entities.entity_chunk_ids",- NO_NAMESPACE,- false,- )?;- self.family()?.entity_chunk_ids(entity_id, limit).await- }-}--// ── Graph ────────────────────────────────────────────────────────────────────--/// Namespace label for the graph family's `Option<&str>` namespace — `None`-/// addresses the global, namespace-less slice.-fn graph_ns(namespace: Option<&str>) -> &str {- namespace.unwrap_or(NO_NAMESPACE)-}--#[async_trait]-impl MemoryGraph for GuardedGraph {- async fn kv_get(- &self,- namespace: Option<&str>,- key: &str,- ) -> Result<Option<MemoryKvRecord>, MemoryError> {- self.policy.admit_read(- Capability::Graph,- "graph.kv_get",- graph_ns(namespace),- false,- )?;- self.family()?.kv_get(namespace, key).await- }-- async fn kv_put(- &self,- namespace: Option<&str>,- key: &str,- value: serde_json::Value,- ) -> Result<(), MemoryError> {- self.policy- .admit_write(Capability::Graph, "graph.kv_put", graph_ns(namespace), true)?;- let value = self.policy.redact_outbound_json(value);- self.family()?.kv_put(namespace, key, value).await- }-- async fn kv_delete(&self, namespace: Option<&str>, key: &str) -> Result<bool, MemoryError> {- self.policy.admit_write(- Capability::Graph,- "graph.kv_delete",- graph_ns(namespace),- false,- )?;- self.family()?.kv_delete(namespace, key).await- }-- async fn kv_list(- &self,- namespace: Option<&str>,- prefix: Option<&str>,- limit: usize,- ) -> Result<Vec<MemoryKvRecord>, MemoryError> {- self.policy.admit_read(- Capability::Graph,- "graph.kv_list",- graph_ns(namespace),- false,- )?;- self.family()?.kv_list(namespace, prefix, limit).await- }-- async fn relations(- &self,- namespace: Option<&str>,- subject: Option<&str>,- predicate: Option<&str>,- limit: usize,- ) -> Result<Vec<GraphRelationRecord>, MemoryError> {- self.policy.admit_read(- Capability::Graph,- "graph.relations",- graph_ns(namespace),- false,- )?;- self.family()?- .relations(namespace, subject, predicate, limit)- .await- }-- async fn put_relation(&self, relation: GraphRelationRecord) -> Result<(), MemoryError> {- self.policy.admit_write(- Capability::Graph,- "graph.put_relation",- graph_ns(relation.namespace.as_deref()),- true,- )?;- self.family()?.put_relation(relation).await- }-}--// ── Diff ─────────────────────────────────────────────────────────────────────--#[async_trait]-impl MemoryDiff for GuardedDiff {- async fn capture_snapshot(&self, source_id: &str) -> Result<SnapshotRef, MemoryError> {- self.policy.admit_write(- Capability::Diff,- "diff.capture_snapshot",- NO_NAMESPACE,- false,- )?;- self.family()?.capture_snapshot(source_id).await- }-- async fn snapshots(- &self,- source_id: &str,- limit: usize,- ) -> Result<Vec<SnapshotRef>, MemoryError> {- self.policy- .admit_read(Capability::Diff, "diff.snapshots", NO_NAMESPACE, false)?;- self.family()?.snapshots(source_id, limit).await- }-- async fn diff(- &self,- source_id: &str,- from: Option<&str>,- to: &str,- ) -> Result<DiffReport, MemoryError> {- self.policy- .admit_read(Capability::Diff, "diff.diff", NO_NAMESPACE, false)?;- self.family()?.diff(source_id, from, to).await- }-}--// ── Goals ────────────────────────────────────────────────────────────────────--#[async_trait]-impl MemoryGoals for GuardedGoals {- async fn goals(&self) -> Result<GoalsDoc, MemoryError> {- self.policy- .admit_read(Capability::Goals, "goals.goals", NO_NAMESPACE, false)?;- self.family()?.goals().await- }-- async fn set_goals(&self, goals: GoalsDoc) -> Result<(), MemoryError> {- self.policy- .admit_write(Capability::Goals, "goals.set_goals", NO_NAMESPACE, true)?;- // The goals document's own validating mutation surface (the PII and- // secret predicates) is host policy that already runs in- // `memory::goals` before a document reaches the contract, so the guard- // does not re-scrub item text here. If an external driver ever binds,- // M6 must decide whether that upstream scrub is sufficient for egress- // or whether item bodies need the same `redact_outbound` treatment the- // document and ingest paths get.- self.family()?.set_goals(goals).await- }-}--// ── Tool memory ──────────────────────────────────────────────────────────────--#[async_trait]-impl MemoryToolMemory for GuardedToolMemory {- async fn tool_rules(&self, tool_name: &str) -> Result<Vec<ToolMemoryRule>, MemoryError> {- self.policy.admit_read(- Capability::ToolMemory,- "tool_memory.tool_rules",- NO_NAMESPACE,- false,- )?;- self.family()?.tool_rules(tool_name).await- }-- async fn put_tool_rule(&self, rule: ToolMemoryRule) -> Result<(), MemoryError> {- self.policy.admit_write(- Capability::ToolMemory,- "tool_memory.put_tool_rule",- NO_NAMESPACE,- true,- )?;- self.family()?.put_tool_rule(rule).await- }-- async fn delete_tool_rule(&self, tool_name: &str, rule_id: &str) -> Result<bool, MemoryError> {- self.policy.admit_write(- Capability::ToolMemory,- "tool_memory.delete_tool_rule",- NO_NAMESPACE,- false,- )?;- self.family()?.delete_tool_rule(tool_name, rule_id).await- }-}--// ── Sources ──────────────────────────────────────────────────────────────────--#[async_trait]-impl MemorySourceSink for GuardedSources {- async fn accept_source_items(- &self,- source_id: &str,- source_kind: &str,- items: Vec<SourceItem>,- taint: MemoryTaint,- ) -> Result<IngestOutcome, MemoryError> {- self.policy.admit_write(- Capability::Sources,- "sources.accept_source_items",- NO_NAMESPACE,- true,- )?;- // Step 3: the batch taint is the guard's to decide. `stamp_taint` never- // downgrades, so a sync path that already asked for `ExternalSync` keeps- // it whether or not a source scope is active.- let taint = self.policy.stamp_taint(taint);- let items: Vec<SourceItem> = items- .into_iter()- .map(|mut item| {- item.title = self.policy.redact_outbound(&item.title).into_owned();- item.content = self.policy.redact_outbound(&item.content).into_owned();- item- })- .collect();- trace_allowed(- &self.policy,- "sources.accept_source_items",- NO_NAMESPACE,- items.iter().map(|i| i.content.chars().count()).sum(),- );- self.family()?- .accept_source_items(source_id, source_kind, items, taint)- .await- }-- async fn forget_source(&self, source_id: &str) -> Result<u64, MemoryError> {- self.policy.admit_write(- Capability::Sources,- "sources.forget_source",- NO_NAMESPACE,- false,- )?;- self.family()?.forget_source(source_id).await- }-- /// The one door for every scoped forget, so it takes the same write tier as- /// [`Self::forget_source`]. The selector names what to remove rather than- /// carrying content, which is why the egress flag is `false` — the same- /// reading its single-source sibling makes.- async fn forget_matching(- &self,- selector: &ForgetSelector,- ) -> Result<ForgetOutcome, MemoryError> {- self.policy.admit_write(- Capability::Sources,- "sources.forget_matching",- NO_NAMESPACE,- false,- )?;- self.family()?.forget_matching(selector).await- }-}--// ── Maintenance ──────────────────────────────────────────────────────────────--#[async_trait]-impl MemoryMaintenance for GuardedMaintenance {- async fn reembed(&self) -> Result<MaintenanceReport, MemoryError> {- self.policy.admit_write(- Capability::Maintenance,- "maintenance.reembed",- NO_NAMESPACE,- false,- )?;- self.family()?.reembed().await- }-- async fn compact(&self) -> Result<MaintenanceReport, MemoryError> {- self.policy.admit_write(- Capability::Maintenance,- "maintenance.compact",- NO_NAMESPACE,- false,- )?;- self.family()?.compact().await- }-- async fn consolidate(&self) -> Result<MaintenanceReport, MemoryError> {- self.policy.admit_write(- Capability::Maintenance,- "maintenance.consolidate",- NO_NAMESPACE,- false,- )?;- self.family()?.consolidate().await- }-- /// Tiered by what the call actually does, not by what the member could do.- ///- /// Executing writes memory-tree rows for documents already stored, so it- /// takes the **write** tier like every other mutating maintenance member: a- /// `readonly` operator may inspect a store, and re-filing thousands of its- /// documents is not inspection.- ///- /// A **dry run writes nothing** — it counts what a pass would examine — so- /// it takes the **read** tier, the same trade [`Self::doctor`] makes below.- /// Gating it behind the write tier would withhold the one safe way to size- /// the job from precisely the tier that should be sizing rather than- /// executing, and the preview is what the expensive control exists to be- /// asked for first (review finding).- async fn backfill_connector_trees(- &self,- request: BackfillTreesRequest,- ) -> Result<BackfillTreesOutcome, MemoryError> {- if request.dry_run {- self.policy.admit_read(- Capability::Maintenance,- "maintenance.backfill_connector_trees",- NO_NAMESPACE,- false,- )?;- } else {- self.policy.admit_write(- Capability::Maintenance,- "maintenance.backfill_connector_trees",- NO_NAMESPACE,- false,- )?;- }- self.family()?.backfill_connector_trees(request).await- }-- /// Read-only by contract, so this takes the **read** tier check: a- /// `readonly` operator must still be able to run `doctor`, which is exactly- /// the tier where diagnosing without mutating matters most.- async fn doctor(&self) -> Result<MaintenanceReport, MemoryError> {- self.policy.admit_read(- Capability::Maintenance,- "maintenance.doctor",- NO_NAMESPACE,- false,- )?;- self.family()?.doctor().await- }-- /// Empties the whole store, so it takes the write tier rather than- /// `doctor`'s read one — and deliberately carries no scope, because there- /// is no scoped reading of "purge everything". A source-restricted caller- /// that reached this would be destroying rows it is not even allowed to- /// read; the write tier is what stops it.- async fn purge_all(&self) -> Result<PurgeOutcome, MemoryError> {- self.policy.admit_write(- Capability::Maintenance,- "maintenance.purge_all",- NO_NAMESPACE,- false,- )?;- self.family()?.purge_all().await- }-- /// [`Self::doctor`]'s findings in full, and read-only on the same terms —- /// it inspects configuration, persisted state and counters and mutates- /// nothing, so it takes the read tier for the reason `doctor` gives.- ///- /// Forwarded here rather than left to the trait's default: a defaulted- /// method on a decorator answers `Unsupported` even when the driver below- /// serves it, so the default would refuse every diagnosis reached through- /// the guard.- async fn diagnose(&self) -> Result<Diagnosis, MemoryError> {- self.policy.admit_read(- Capability::Maintenance,- "maintenance.diagnose",- NO_NAMESPACE,- false,- )?;- self.family()?.diagnose().await- }-- /// The degradation flags without the diagnosis around them — three- /// booleans and at most one cause. Read tier for the same reason- /// [`Self::doctor`] takes it, and for one more: this is what a status- /// light polls, so refusing it under `readonly` would leave the surface- /// that reports a reduced pipeline unable to say so.- async fn degraded_state(&self) -> Result<DegradedCapabilities, MemoryError> {- self.policy.admit_read(- Capability::Maintenance,- "maintenance.degraded_state",- NO_NAMESPACE,- false,- )?;- self.family()?.degraded_state().await- }-}--// ── People ───────────────────────────────────────────────────────────────────--#[async_trait]-impl MemoryPeople for GuardedPeople {- async fn list_people(&self, limit: Option<usize>) -> Result<Vec<RankedPerson>, MemoryError> {- self.policy.admit_read(- Capability::People,- "people.list_people",- NO_NAMESPACE,- false,- )?;- self.family()?.list_people(limit).await- }-- async fn get_person(&self, person_id: &str) -> Result<Option<PersonRecord>, MemoryError> {- self.policy- .admit_read(Capability::People, "people.get_person", NO_NAMESPACE, false)?;- self.family()?.get_person(person_id).await- }-- /// A read *unless* it may mint a person, which is a write.- ///- /// The tier check follows what the call can actually do rather than what it- /// is named: with `create_if_missing` set this inserts a row, so a- /// `readonly` operator must be refused. Classifying the whole method as a- /// read would have handed `readonly` a working insert through the back- /// door.- async fn resolve_handle(- &self,- handle: &PersonHandle,- create_if_missing: bool,- ) -> Result<Option<ResolvedPerson>, MemoryError> {- if create_if_missing {- self.policy.admit_write(- Capability::People,- "people.resolve_handle",- NO_NAMESPACE,- true,- )?;- } else {- self.policy.admit_read(- Capability::People,- "people.resolve_handle",- NO_NAMESPACE,- false,- )?;- }- self.family()?- .resolve_handle(handle, create_if_missing)- .await- }-- async fn add_handle_alias(- &self,- person_id: &str,- handle: &PersonHandle,- ) -> Result<(), MemoryError> {- self.policy.admit_write(- Capability::People,- "people.add_handle_alias",- NO_NAMESPACE,- true,- )?;- self.family()?.add_handle_alias(person_id, handle).await- }-- async fn score_person(&self, person_id: &str) -> Result<Option<PersonScore>, MemoryError> {- self.policy.admit_read(- Capability::People,- "people.score_person",- NO_NAMESPACE,- false,- )?;- self.family()?.score_person(person_id).await- }-- async fn record_interaction(&self, interaction: &PersonInteraction) -> Result<(), MemoryError> {- self.policy.admit_write(- Capability::People,- "people.record_interaction",- NO_NAMESPACE,- true,- )?;- self.family()?.record_interaction(interaction).await- }-- /// A write: it reads the platform address book and inserts what it finds.- async fn seed_from_address_book(&self) -> Result<AddressBookSeedOutcome, MemoryError> {- self.policy.admit_write(- Capability::People,- "people.seed_from_address_book",- NO_NAMESPACE,- true,- )?;- self.family()?.seed_from_address_book().await- }-}diff --git a/crates/openhuman-core/src/memory/guard/families/ingest_and_tree.rs b/crates/openhuman-core/src/memory/guard/families/ingest_and_tree.rsdeleted file mode 100644index 711319b458..0000000000--- a/crates/openhuman-core/src/memory/guard/families/ingest_and_tree.rs+++ /dev/null@@ -1,526 +0,0 @@-//! Guarded `Ingest`, `Documents`, and `Tree` — the families that write new-//! content into memory or read back its hierarchical tree structure.-//!-//! Split out of `families.rs`; see [`super::types`] for the shared decorator-//! scaffolding these `impl` blocks build on.--use std::borrow::Cow;--use crate::memory::api::capabilities::Capability;-use crate::memory::api::error::MemoryError;-use crate::memory::api::provider::content::{- RootSummary, SummaryContext, SummaryInput, SummaryOutput,-};-use crate::memory::api::provider::types::{IngestItem, IngestOutcome, SourceScope};-use crate::memory::api::provider::{MemoryDocuments, MemoryIngest, MemoryTree};-use crate::memory::api::tree::{- IngestRequest, QueryResult, SummaryForest, TreeLeaf, TreeNode, TreeStatus,-};-use crate::memory::api::types::NamespaceRetrievalContext;-use crate::memory::api::types::{NamespaceDocumentInput, StoredMemoryDocument};-use async_trait::async_trait;--use super::super::audit::{trace_allowed, NO_NAMESPACE};-use super::types::{GuardedDocuments, GuardedIngest, GuardedTree};--// ── Ingest ───────────────────────────────────────────────────────────────────--impl GuardedIngest {- /// Steps 3 + 4 over one ingest item: stamp provenance, redact on egress.- fn admit(&self, mut item: IngestItem) -> IngestItem {- item.taint = self.policy.stamp_taint(item.taint);- item.content = self.policy.redact_outbound(&item.content).into_owned();- item- }-}--#[async_trait]-impl MemoryIngest for GuardedIngest {- async fn ingest_document(&self, item: IngestItem) -> Result<IngestOutcome, MemoryError> {- let namespace = item.namespace.clone().unwrap_or_else(|| "-".to_string());- self.policy.admit_write(- Capability::Ingest,- "ingest.ingest_document",- &namespace,- true,- )?;- let item = self.admit(item);- trace_allowed(- &self.policy,- "ingest.ingest_document",- &namespace,- item.content.chars().count(),- );- self.family()?.ingest_document(item).await- }-- async fn ingest_chat(&self, messages: Vec<IngestItem>) -> Result<IngestOutcome, MemoryError> {- self.policy- .admit_write(Capability::Ingest, "ingest.ingest_chat", NO_NAMESPACE, true)?;- let messages: Vec<IngestItem> = messages.into_iter().map(|m| self.admit(m)).collect();- trace_allowed(- &self.policy,- "ingest.ingest_chat",- NO_NAMESPACE,- messages.iter().map(|m| m.content.chars().count()).sum(),- );- self.family()?.ingest_chat(messages).await- }-- async fn ingest_email(&self, messages: Vec<IngestItem>) -> Result<IngestOutcome, MemoryError> {- // Admitted exactly like chat: a thread is one conversation with no- // namespace of its own, and every message is taint-stamped and- // redacted before it reaches the driver.- self.policy.admit_write(- Capability::Ingest,- "ingest.ingest_email",- NO_NAMESPACE,- true,- )?;- let messages: Vec<IngestItem> = messages.into_iter().map(|m| self.admit(m)).collect();- trace_allowed(- &self.policy,- "ingest.ingest_email",- NO_NAMESPACE,- messages.iter().map(|m| m.content.chars().count()).sum(),- );- self.family()?.ingest_email(messages).await- }-}--// ── Documents ────────────────────────────────────────────────────────────────--#[async_trait]-impl MemoryDocuments for GuardedDocuments {- async fn put_document(&self, mut input: NamespaceDocumentInput) -> Result<String, MemoryError> {- self.policy.admit_write(- Capability::Documents,- "documents.put_document",- &input.namespace,- true,- )?;- input.taint = self.policy.stamp_taint(input.taint);- input.title = self.policy.redact_outbound(&input.title).into_owned();- input.content = self.policy.redact_outbound(&input.content).into_owned();- input.metadata = self.policy.redact_outbound_json(input.metadata);- trace_allowed(- &self.policy,- "documents.put_document",- &input.namespace,- input.content.chars().count(),- );- self.family()?.put_document(input).await- }-- async fn get_document(- &self,- namespace: &str,- key: &str,- ) -> Result<Option<StoredMemoryDocument>, MemoryError> {- self.policy.admit_read(- Capability::Documents,- "documents.get_document",- namespace,- false,- )?;- self.family()?.get_document(namespace, key).await- }-- async fn list_documents(- &self,- namespace: Option<&str>,- ) -> Result<serde_json::Value, MemoryError> {- self.policy.admit_read(- Capability::Documents,- "documents.list_documents",- namespace.unwrap_or(NO_NAMESPACE),- false,- )?;- self.family()?.list_documents(namespace).await- }-- async fn list_namespaces(&self) -> Result<Vec<String>, MemoryError> {- self.policy.admit_read(- Capability::Documents,- "documents.list_namespaces",- NO_NAMESPACE,- false,- )?;- self.family()?.list_namespaces().await- }-- async fn delete_document(- &self,- namespace: &str,- document_id: &str,- ) -> Result<serde_json::Value, MemoryError> {- self.policy.admit_write(- Capability::Documents,- "documents.delete_document",- namespace,- false,- )?;- self.family()?.delete_document(namespace, document_id).await- }-- async fn clear_namespace(&self, namespace: &str) -> Result<(), MemoryError> {- self.policy.admit_write(- Capability::Documents,- "documents.clear_namespace",- namespace,- false,- )?;- self.family()?.clear_namespace(namespace).await- }-- async fn query_documents(- &self,- namespace: &str,- query: &str,- limit: usize,- ) -> Result<NamespaceRetrievalContext, MemoryError> {- // The query text itself crosses the boundary on an external driver.- self.policy.admit_read(- Capability::Documents,- "documents.query_documents",- namespace,- true,- )?;- let query = self.policy.redact_outbound(query).into_owned();- self.family()?- .query_documents(namespace, &query, limit)- .await- }-- async fn recall_documents(- &self,- namespace: &str,- limit: usize,- ) -> Result<NamespaceRetrievalContext, MemoryError> {- self.policy.admit_read(- Capability::Documents,- "documents.recall_documents",- namespace,- false,- )?;- self.family()?.recall_documents(namespace, limit).await- }-}--// ── Tree ─────────────────────────────────────────────────────────────────────--#[async_trait]-impl MemoryTree for GuardedTree {- async fn append(&self, mut request: IngestRequest) -> Result<(), MemoryError> {- self.policy- .admit_write(Capability::Tree, "tree.append", &request.namespace, true)?;- request.content = self.policy.redact_outbound(&request.content).into_owned();- trace_allowed(- &self.policy,- "tree.append",- &request.namespace,- request.content.chars().count(),- );- self.family()?.append(request).await- }-- /// **Step 2 lives here.** This is the only contract method in the tree- /// today that both takes a [`SourceScope`] and applies it as a real query- /// predicate: the embedded driver pushes `scope.allow` into- /// `ListChunksQuery.source_scope`, which reaches SQL *before* `LIMIT`.- ///- /// The ambient allowlist- /// ([`source_scope::current_source_scope`](crate::memory::source_scope::current_source_scope))- /// is therefore read at this boundary and passed down, rather than being- /// applied to the returned rows. An explicit `scope` argument may only- /// *narrow* it: the two are intersected by- /// [`GuardPolicy::narrow_scope`](crate::memory::guard::GuardPolicy::narrow_scope),- /// so a caller that computed a tighter scope than the task-local still wins,- /// while one that names a collection outside the ambient allowlist cannot- /// widen the turn back out.- ///- /// There is **no double application**: the embedded `query_source` does not- /// itself read the task-local (only the deeper `tree::retrieval` and- /// `list_chunks` paths do, and the guard does not sit in front of those),- /// so this fills a predicate that would otherwise be `None`.- async fn query_source(- &self,- namespace: &str,- source_id: &str,- limit: usize,- scope: Option<&SourceScope>,- ) -> Result<Vec<crate::memory::api::chunks::Chunk>, MemoryError> {- self.policy- .admit_read(Capability::Tree, "tree.query_source", namespace, false)?;- let ambient = self.policy.ambient_scope();- let effective = self.policy.narrow_scope(scope);- log::debug!(- "[memory:guard] tree.query_source namespace={namespace} limit={limit} \- scoped={} scope_from={}",- effective.is_some(),- match (scope.is_some(), ambient.is_some()) {- (true, true) => "argument∩ambient",- (true, false) => "argument",- (false, true) => "ambient",- (false, false) => "none",- }- );- self.family()?- .query_source(namespace, source_id, limit, effective.as_ref())- .await- }-- async fn drill_down(&self, namespace: &str, node_id: &str) -> Result<QueryResult, MemoryError> {- self.policy- .admit_read(Capability::Tree, "tree.drill_down", namespace, false)?;- self.family()?.drill_down(namespace, node_id).await- }-- async fn seal(&self, namespace: &str) -> Result<TreeStatus, MemoryError> {- self.policy- .admit_write(Capability::Tree, "tree.seal", namespace, false)?;- self.family()?.seal(namespace).await- }-- async fn cascade(&self, namespace: &str) -> Result<TreeStatus, MemoryError> {- self.policy- .admit_write(Capability::Tree, "tree.cascade", namespace, false)?;- self.family()?.cascade(namespace).await- }-- /// Enumerates the sealed forest, so it narrows by the ambient scope for the- /// same reason [`Self::query_source`] does: a summary is derived from the- /// chunks beneath it, and handing back a node built from sources the caller- /// may not read discloses their contents in condensed form.- async fn summary_forest(- &self,- limit: usize,- scope: Option<&SourceScope>,- ) -> Result<SummaryForest, MemoryError> {- self.policy- .admit_read(Capability::Tree, "tree.summary_forest", NO_NAMESPACE, false)?;- let effective = self.policy.narrow_scope(scope);- self.family()?- .summary_forest(limit, effective.as_ref())- .await- }-- /// Sealing one source's tree is a write, and it names the scope it acts on- /// — so unlike the reads above it is admitted against that scope rather- /// than `NO_NAMESPACE`. `carries_content: false`: the caller supplies a- /// scope label, never prose, and the seals it fires write content the- /// driver already holds.- async fn flush_source_tree(&self, source_scope: &str) -> Result<u64, MemoryError> {- self.policy.admit_write(- Capability::Tree,- "tree.flush_source_tree",- source_scope,- false,- )?;- self.family()?.flush_source_tree(source_scope).await- }-- /// Leaves are chunks, so this is the same disclosure as- /// [`Self::query_source`] with a different ordering, and takes the same- /// intersection.- async fn recent_leaves(- &self,- limit: usize,- scope: Option<&SourceScope>,- ) -> Result<Vec<TreeLeaf>, MemoryError> {- self.policy- .admit_read(Capability::Tree, "tree.recent_leaves", NO_NAMESPACE, false)?;- let effective = self.policy.narrow_scope(scope);- self.family()?- .recent_leaves(limit, effective.as_ref())- .await- }-- /// A **read** tier check even though the fold costs a provider call: it- /// writes nothing. `seal` and `cascade` take the write tier because they- /// persist the nodes they produce; this hands the summary back and leaves- /// the tree exactly as it found it, so refusing it under `readonly` would- /// stop a recap that stores nothing.- ///- /// It is nevertheless the only member of this family besides- /// [`Self::append`] that carries prose *outbound* — every input's body- /// crosses to the driver's own chat provider — so it declares- /// `carries_content: true` and applies `append`'s scrub to each of them.- /// Admitted against [`SummaryContext::tree_id`] rather than- /// `NO_NAMESPACE` for the reason [`Self::flush_source_tree`] gives: it- /// names the tree it acts on.- async fn summarise(- &self,- inputs: &[SummaryInput],- context: &SummaryContext,- ) -> Result<SummaryOutput, MemoryError> {- self.policy- .admit_read(Capability::Tree, "tree.summarise", &context.tree_id, true)?;- // `redact_outbound` borrows for every driver class but `External`, so- // the re-owned slice is built only when the scrubber actually rewrote- // something — a recap folds every turn of a segment, and cloning them- // to hand back the same bytes is the one cost this can avoid.- let mut scrubbed: Option<Vec<SummaryInput>> = None;- for (index, input) in inputs.iter().enumerate() {- if let Cow::Owned(content) = self.policy.redact_outbound(&input.content) {- scrubbed.get_or_insert_with(|| inputs.to_vec())[index].content = content;- }- }- let effective = scrubbed.as_deref().unwrap_or(inputs);- trace_allowed(- &self.policy,- "tree.summarise",- &context.tree_id,- effective- .iter()- .map(|input| input.content.chars().count())- .sum(),- );- self.family()?.summarise(effective, context).await- }-- /// The markdown time tree's roots, one body per namespace.- ///- /// Takes no [`SourceScope`], so unlike [`Self::summary_forest`] there is- /// nothing here to intersect with the ambient allowlist — the contract- /// member has no scope parameter and the guard does not invent one. Both- /// caps are the caller's and cross unchanged: they bound the *response*,- /// and clipping them here would produce a body the driver did not choose- /// the truncation point of.- async fn root_summaries_with_caps(- &self,- per_namespace_cap: usize,- total_cap: usize,- ) -> Result<Vec<RootSummary>, MemoryError> {- self.policy.admit_read(- Capability::Tree,- "tree.root_summaries_with_caps",- NO_NAMESPACE,- false,- )?;- self.family()?- .root_summaries_with_caps(per_namespace_cap, total_cap)- .await- }-- // ── The runtime-tree and flavour doors ──────────────────────────────────- //- // **Forwarding these is not optional.** All seven are defaulted on- // [`MemoryTree`], so a decorator that omits one still compiles — and then- // answers `Err(Unsupported)` for a driver that serves the member perfectly- // well, because the guard *is* the handle every product caller holds and- // its own default is what runs. That exact bug shipped once, on- // `MemoryMaintenance::diagnose`. The rule this family follows: a new- // defaulted member on a wrapped trait is a new override here, in the same- // change.- //- // None of them takes a [`SourceScope`], so step 2 does not apply — the- // contract members carry no scope parameter and the guard does not invent- // one; see [`Self::root_summaries_with_caps`] for the same reasoning.-- /// Buffering raw content is [`Self::append`]'s write at a finer grain, so- /// it takes `append`'s admission exactly: the write tier, against the- /// namespace it names, `carries_content: true`, and the same outbound- /// scrub applied to the body before it crosses.- async fn runtime_buffer_write(- &self,- namespace: &str,- content: &str,- timestamp: chrono::DateTime<chrono::Utc>,- metadata: Option<serde_json::Value>,- ) -> Result<String, MemoryError> {- self.policy.admit_write(- Capability::Tree,- "tree.runtime_buffer_write",- namespace,- true,- )?;- let content = self.policy.redact_outbound(content);- trace_allowed(- &self.policy,- "tree.runtime_buffer_write",- namespace,- content.chars().count(),- );- self.family()?- .runtime_buffer_write(namespace, &content, timestamp, metadata)- .await- }-- /// A single node read, admitted like [`Self::drill_down`] — the same tree- /// at the same grain, minus the child list.- async fn runtime_read_node(- &self,- namespace: &str,- node_id: &str,- ) -> Result<Option<TreeNode>, MemoryError> {- self.policy- .admit_read(Capability::Tree, "tree.runtime_read_node", namespace, false)?;- self.family()?.runtime_read_node(namespace, node_id).await- }-- /// The other half of [`Self::drill_down`], admitted identically.- async fn runtime_read_children(- &self,- namespace: &str,- parent_id: &str,- ) -> Result<Vec<TreeNode>, MemoryError> {- self.policy.admit_read(- Capability::Tree,- "tree.runtime_read_children",- namespace,- false,- )?;- self.family()?- .runtime_read_children(namespace, parent_id)- .await- }-- /// Counts and timestamps for one namespace: a read, and one that carries- /// no prose either way.- async fn runtime_tree_status(&self, namespace: &str) -> Result<TreeStatus, MemoryError> {- self.policy.admit_read(- Capability::Tree,- "tree.runtime_tree_status",- namespace,- false,- )?;- self.family()?.runtime_tree_status(namespace).await- }-- /// The **write** tier, unlike [`Self::summarise`]: this drains the buffer- /// into hour leaves and persists them, which is what [`Self::seal`] does- /// and why `seal` takes the write tier too. `summarise` hands a fold back- /// and leaves the tree as it found it; this one does not.- ///- /// `carries_content: false`: the caller supplies a namespace and an- /// instant, never prose. The content the pass folds is already in the- /// driver's own buffer, put there by [`Self::runtime_buffer_write`], which- /// scrubbed it on the way in.- async fn runtime_summarize(- &self,- namespace: &str,- timestamp: chrono::DateTime<chrono::Utc>,- ) -> Result<Option<TreeNode>, MemoryError> {- self.policy- .admit_write(Capability::Tree, "tree.runtime_summarize", namespace, false)?;- self.family()?.runtime_summarize(namespace, timestamp).await- }-- /// As [`Self::runtime_summarize`], on [`Self::cascade`]'s terms.- async fn runtime_rebuild(&self, namespace: &str) -> Result<TreeStatus, MemoryError> {- self.policy- .admit_write(Capability::Tree, "tree.runtime_rebuild", namespace, false)?;- self.family()?.runtime_rebuild(namespace).await- }-- /// A compiled profile read. The scope is the caller's naming scheme rather- /// than a namespace, and it is what this call acts on, so it is what the- /// admission names — the reasoning [`Self::flush_source_tree`] gives for- /// admitting against its own label instead of `NO_NAMESPACE`.- async fn flavour_profile(&self, scope: &str) -> Result<Option<String>, MemoryError> {- self.policy- .admit_read(Capability::Tree, "tree.flavour_profile", scope, false)?;- self.family()?.flavour_profile(scope).await- }-}diff --git a/crates/openhuman-core/src/memory/guard/families/retrieval_and_profile.rs b/crates/openhuman-core/src/memory/guard/families/retrieval_and_profile.rsdeleted file mode 100644index 8609eaeb52..0000000000--- a/crates/openhuman-core/src/memory/guard/families/retrieval_and_profile.rs+++ /dev/null@@ -1,703 +0,0 @@-//! Guarded `Retrieval`, `Episodic`, `Profile`, `SourceSync`, `Scoring`, and-//! `CodingSessions` — the read/query families.-//!-//! Split out of `families.rs`; see [`super::types`] for the shared decorator-//! scaffolding these `impl` blocks build on.--use crate::memory::api::capabilities::Capability;-use crate::memory::api::error::MemoryError;-use crate::memory::api::provider::episodic::{ConversationSegment, EpisodicTurn};-use crate::memory::api::provider::profile::{FacetType, ProfileFacet, UserState};-use crate::memory::api::provider::retrieval::{- CoverWindowQuery, EntityMatch, FastRetrieveQuery, RetrievalHit, RetrievalResponse,- SourceRetrievalQuery,-};-use crate::memory::api::provider::sessions::{- CodingSessionIngestReport, CodingSessionIngestRequest, CodingSessionSource,-};-use crate::memory::api::provider::sync::{- RawArchiveCoverage, RawRebuildOutcome, SourceSyncState, SourceSyncStatus, SyncAuditEntry,- SyncRunOutcome,-};-use crate::memory::api::provider::types::SourceScope;-use crate::memory::api::provider::{- EpisodicEvent, MemoryCodingSessions, MemoryEpisodic, MemoryProfile, MemoryRetrieval,- MemoryScoring, MemorySourceSync,-};-use crate::memory::api::types::NamespaceMemoryHit;-use async_trait::async_trait;--use super::super::audit::NO_NAMESPACE;-use super::types::{- GuardedCodingSessions, GuardedEpisodic, GuardedProfile, GuardedRetrieval, GuardedScoring,- GuardedSourceSync,-};--// ── Chunks ───────────────────────────────────────────────────────────────────--// ── Retrieval ────────────────────────────────────────────────────────────────--#[async_trait]-impl MemoryRetrieval for GuardedRetrieval {- async fn fast_retrieve(- &self,- query: &str,- options: FastRetrieveQuery,- scope: Option<&SourceScope>,- ) -> Result<RetrievalResponse, MemoryError> {- self.policy.admit_read(- Capability::Retrieval,- "retrieval.fast_retrieve",- NO_NAMESPACE,- false,- )?;- let effective = self.policy.narrow_scope(scope);- self.family()?- .fast_retrieve(query, options, effective.as_ref())- .await- }-- async fn cover_window(- &self,- window: &CoverWindowQuery,- scope: Option<&SourceScope>,- ) -> Result<RetrievalResponse, MemoryError> {- self.policy.admit_read(- Capability::Retrieval,- "retrieval.cover_window",- NO_NAMESPACE,- false,- )?;- let effective = self.policy.narrow_scope(scope);- self.family()?- .cover_window(window, effective.as_ref())- .await- }-- async fn retrieve_source(- &self,- query: &SourceRetrievalQuery,- scope: Option<&SourceScope>,- ) -> Result<RetrievalResponse, MemoryError> {- self.policy.admit_read(- Capability::Retrieval,- "retrieval.retrieve_source",- NO_NAMESPACE,- false,- )?;- let effective = self.policy.narrow_scope(scope);- self.family()?- .retrieve_source(query, effective.as_ref())- .await- }-- async fn retrieve_children(- &self,- node_id: &str,- max_depth: u32,- query: Option<&str>,- limit: Option<usize>,- scope: Option<&SourceScope>,- ) -> Result<Vec<RetrievalHit>, MemoryError> {- self.policy.admit_read(- Capability::Retrieval,- "retrieval.retrieve_children",- NO_NAMESPACE,- false,- )?;- // Intersected with the ambient allowlist, never passed through — same- // rule as `list_chunks`. See `GuardPolicy::narrow_scope`.- let effective = self.policy.narrow_scope(scope);- self.family()?- .retrieve_children(node_id, max_depth, query, limit, effective.as_ref())- .await- }-- async fn retrieve_leaves(- &self,- chunk_ids: &[String],- scope: Option<&SourceScope>,- ) -> Result<Vec<RetrievalHit>, MemoryError> {- self.policy.admit_read(- Capability::Retrieval,- "retrieval.retrieve_leaves",- NO_NAMESPACE,- false,- )?;- let effective = self.policy.narrow_scope(scope);- self.family()?- .retrieve_leaves(chunk_ids, effective.as_ref())- .await- }-- /// Namespace-scoped, so the namespace reaches the tier check — unlike the- /// other retrieval primitives, which span the store.- async fn recall_namespace_scored(- &self,- namespace: &str,- query: &str,- limit: usize,- exclude_session_id: Option<&str>,- ) -> Result<Vec<NamespaceMemoryHit>, MemoryError> {- self.policy.admit_read(- Capability::Retrieval,- "retrieval.recall_namespace_scored",- namespace,- false,- )?;- self.family()?- .recall_namespace_scored(namespace, query, limit, exclude_session_id)- .await- }-- /// Namespace-scoped like its scored sibling, and admitted under the same- /// capability: recency versus ranking is a retrieval mode, not a policy- /// boundary.- async fn recall_namespace_recent(- &self,- namespace: &str,- limit: usize,- ) -> Result<Vec<NamespaceMemoryHit>, MemoryError> {- self.policy.admit_read(- Capability::Retrieval,- "retrieval.recall_namespace_recent",- namespace,- false,- )?;- self.family()?- .recall_namespace_recent(namespace, limit)- .await- }-- async fn search_entities(- &self,- query: &str,- kinds: Option<&[String]>,- limit: usize,- ) -> Result<Vec<EntityMatch>, MemoryError> {- self.policy.admit_read(- Capability::Retrieval,- "retrieval.search_entities",- NO_NAMESPACE,- false,- )?;- self.family()?.search_entities(query, kinds, limit).await- }-}--// ── Profile ──────────────────────────────────────────────────────────────────--#[async_trait]-impl MemoryEpisodic for GuardedEpisodic {- async fn insert_turn(&self, turn: &EpisodicTurn) -> Result<i64, MemoryError> {- // A recorded turn is user-authored conversation content, so this is a- // write and is admitted as one — the read/write split here is about- // what the tier permits, not about how much data moves.- // `carries_content: true`, unlike the tier note above, which is about- // what the tier permits rather than how much data moves. This flag is a- // different question: it decides whether the egress record classifies- // the transfer as `FileContent` or `Metadata`. A turn IS the user's- // prose, and an audit trail that calls a transcript "metadata"- // understates what left the process — the one thing that record exists- // to get right. `tree.append` has always passed `true` for this shape.- self.policy.admit_write(- Capability::Episodic,- "episodic.insert_turn",- NO_NAMESPACE,- true,- )?;- let mut turn = turn.clone();- turn.content = self.policy.redact_outbound(&turn.content).into_owned();- self.family()?.insert_turn(&turn).await- }-- async fn session_turns(&self, session_id: &str) -> Result<Vec<EpisodicTurn>, MemoryError> {- self.policy.admit_read(- Capability::Episodic,- "episodic.session_turns",- NO_NAMESPACE,- false,- )?;- self.family()?.session_turns(session_id).await- }-- async fn open_segment(- &self,- session_id: &str,- ) -> Result<Option<ConversationSegment>, MemoryError> {- self.policy.admit_read(- Capability::Episodic,- "episodic.open_segment",- NO_NAMESPACE,- false,- )?;- self.family()?.open_segment(session_id).await- }-- #[allow(- clippy::too_many_arguments,- reason = "trait signature; see the contract's rationale"- )]- async fn create_segment(- &self,- segment_id: &str,- session_id: &str,- namespace: &str,- start_episodic_id: i64,- start_seq: Option<u32>,- start_timestamp: f64,- now: f64,- ) -> Result<(), MemoryError> {- // One of the two episodic calls that names a namespace — `insert_event`- // is the other — so it is admitted against that namespace rather than- // `NO_NAMESPACE`. The rest of this family addresses a segment by id and- // has no namespace to check.- self.policy.admit_write(- Capability::Episodic,- "episodic.create_segment",- namespace,- false,- )?;- self.family()?- .create_segment(- segment_id,- session_id,- namespace,- start_episodic_id,- start_seq,- start_timestamp,- now,- )- .await- }-- async fn append_turn(- &self,- segment_id: &str,- episodic_id: i64,- seq: Option<u32>,- timestamp: f64,- now: f64,- ) -> Result<(), MemoryError> {- self.policy.admit_write(- Capability::Episodic,- "episodic.append_turn",- NO_NAMESPACE,- false,- )?;- self.family()?- .append_turn(segment_id, episodic_id, seq, timestamp, now)- .await- }-- /// Admitted like its sibling writes; the event's namespace is the- /// admission subject, since it is the one the record is scoped to.- async fn insert_event(&self, event: &EpisodicEvent) -> Result<(), MemoryError> {- // `carries_content: true` for the same reason as `insert_turn`: an- // extracted event is the user's prose, not a descriptor of it.- self.policy.admit_write(- Capability::Episodic,- "episodic.insert_event",- &event.namespace,- true,- )?;- let mut event = event.clone();- event.content = self.policy.redact_outbound(&event.content).into_owned();- self.family()?.insert_event(&event).await- }-- async fn close_segment(&self, segment_id: &str, now: f64) -> Result<(), MemoryError> {- self.policy.admit_write(- Capability::Episodic,- "episodic.close_segment",- NO_NAMESPACE,- false,- )?;- self.family()?.close_segment(segment_id, now).await- }-- async fn set_segment_summary(- &self,- segment_id: &str,- summary: &str,- now: f64,- ) -> Result<(), MemoryError> {- self.policy.admit_write(- Capability::Episodic,- "episodic.set_segment_summary",- NO_NAMESPACE,- false,- )?;- self.family()?- .set_segment_summary(segment_id, summary, now)- .await- }-- /// A read: it selects rows, it changes none. Admitted as one so a- /// read-only policy can still drive the re-summarisation pass (#6186) —- /// the write it leads to is `set_segment_summary`, which is admitted- /// separately on its own terms.- async fn segments_pending_summary(- &self,- limit: u32,- ) -> Result<Vec<ConversationSegment>, MemoryError> {- self.policy.admit_read(- Capability::Episodic,- "episodic.segments_pending_summary",- NO_NAMESPACE,- false,- )?;- self.family()?.segments_pending_summary(limit).await- }-- async fn upsert_segment_embedding(- &self,- segment_id: &str,- model_signature: &str,- embedding: &[f32],- created_at: f64,- ) -> Result<(), MemoryError> {- self.policy.admit_write(- Capability::Episodic,- "episodic.upsert_segment_embedding",- NO_NAMESPACE,- false,- )?;- self.family()?- .upsert_segment_embedding(segment_id, model_signature, embedding, created_at)- .await- }-}--#[async_trait]-impl MemoryProfile for GuardedProfile {- async fn list_active_facets(&self) -> Result<Vec<ProfileFacet>, MemoryError> {- self.policy.admit_read(- Capability::Profile,- "profile.list_active_facets",- NO_NAMESPACE,- false,- )?;- self.family()?.list_active_facets().await- }-- async fn list_all_facets(&self) -> Result<Vec<ProfileFacet>, MemoryError> {- self.policy.admit_read(- Capability::Profile,- "profile.list_all_facets",- NO_NAMESPACE,- false,- )?;- self.family()?.list_all_facets().await- }-- async fn get_facet(&self, key: &str) -> Result<Option<ProfileFacet>, MemoryError> {- self.policy.admit_read(- Capability::Profile,- "profile.get_facet",- NO_NAMESPACE,- false,- )?;- self.family()?.get_facet(key).await- }-- async fn facets_by_type(- &self,- facet_type: FacetType,- ) -> Result<Vec<ProfileFacet>, MemoryError> {- self.policy.admit_read(- Capability::Profile,- "profile.facets_by_type",- NO_NAMESPACE,- false,- )?;- self.family()?.facets_by_type(facet_type).await- }-- async fn upsert_facet(&self, facet: &ProfileFacet) -> Result<(), MemoryError> {- self.policy.admit_write(- Capability::Profile,- "profile.upsert_facet",- NO_NAMESPACE,- true,- )?;- self.family()?.upsert_facet(facet).await- }-- async fn upsert_provider_facet(- &self,- facet_id: &str,- facet_type: FacetType,- key: &str,- value: &str,- confidence: f64,- segment_id: Option<&str>,- observed_at: f64,- ) -> Result<(), MemoryError> {- self.policy.admit_write(- Capability::Profile,- "profile.upsert_provider_facet",- NO_NAMESPACE,- true,- )?;- self.family()?- .upsert_provider_facet(- facet_id,- facet_type,- key,- value,- confidence,- segment_id,- observed_at,- )- .await- }-- async fn set_facet_user_state(- &self,- key: &str,- user_state: UserState,- ) -> Result<bool, MemoryError> {- self.policy.admit_write(- Capability::Profile,- "profile.set_facet_user_state",- NO_NAMESPACE,- true,- )?;- self.family()?.set_facet_user_state(key, user_state).await- }-- async fn delete_facet(&self, key: &str) -> Result<bool, MemoryError> {- self.policy.admit_write(- Capability::Profile,- "profile.delete_facet",- NO_NAMESPACE,- true,- )?;- self.family()?.delete_facet(key).await- }-- async fn delete_facet_by_id(&self, facet_id: &str) -> Result<bool, MemoryError> {- self.policy.admit_write(- Capability::Profile,- "profile.delete_facet_by_id",- NO_NAMESPACE,- true,- )?;- self.family()?.delete_facet_by_id(facet_id).await- }-- async fn drop_facets_below(&self, threshold: f64) -> Result<usize, MemoryError> {- self.policy.admit_write(- Capability::Profile,- "profile.drop_facets_below",- NO_NAMESPACE,- true,- )?;- self.family()?.drop_facets_below(threshold).await- }-- /// Refused reads answer `false`, matching the trait's "an error reads as- /// no". A tier refusal is not evidence that the row matches.- async fn workflow_identity_matches(&self, key_pattern: &str, canonical_value: &str) -> bool {- if self- .policy- .admit_read(- Capability::Profile,- "profile.workflow_identity_matches",- NO_NAMESPACE,- false,- )- .is_err()- {- return false;- }- match self.family() {- Ok(family) => {- family- .workflow_identity_matches(key_pattern, canonical_value)- .await- }- Err(_) => false,- }- }-}--// ── 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- }-}--// ── Scoring ──────────────────────────────────────────────────────────────────--#[async_trait]-impl MemoryScoring for GuardedScoring {- async fn extract_entities(&self, query: &str) -> Result<Vec<String>, MemoryError> {- self.policy.admit_read(- Capability::Scoring,- "scoring.extract_entities",- NO_NAMESPACE,- true,- )?;- self.family()?.extract_entities(query).await- }-- async fn embed_text(&self, text: &str) -> Result<Vec<f32>, MemoryError> {- self.policy.admit_read(- Capability::Scoring,- "scoring.embed_text",- NO_NAMESPACE,- true,- )?;- self.family()?.embed_text(text).await- }-- async fn embedder_slug(&self) -> Result<String, MemoryError> {- self.policy.admit_read(- Capability::Scoring,- "scoring.embedder_slug",- NO_NAMESPACE,- false,- )?;- self.family()?.embedder_slug().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/crates/openhuman-core/src/memory/guard/families/typed_ingest_and_answer.rs b/crates/openhuman-core/src/memory/guard/families/typed_ingest_and_answer.rsdeleted file mode 100644index f9d5d79f89..0000000000--- a/crates/openhuman-core/src/memory/guard/families/typed_ingest_and_answer.rs+++ /dev/null@@ -1,304 +0,0 @@-//! Guarded `DocumentIngest`, `ConversationIngest`, `LearningIngest`,-//! `EventIngest`, `Answer`, and `Chunks` — the typed-ingestion round the-//! v1.13.7 contract release added, plus the sibling `Chunks` family wired-//! alongside it.-//!-//! Split out of `families.rs`; see [`super::types`] for the shared decorator-//! scaffolding these `impl` blocks build on.--use crate::memory::api::capabilities::Capability;-use crate::memory::api::chunks::Chunk;-use crate::memory::api::error::MemoryError;-use crate::memory::api::provider::chunks::{- ChunkDetail, ChunkEmbedding, ChunkListRow, ChunkQuery, ChunkScore, SourceIngestQuery,- SourceIngestStatus, SourceTotal,-};-use crate::memory::api::provider::operations::{- AnswerRequest, AnswerResponse, MemoryAnswer, MemoryConversationIngest, MemoryDocumentIngest,- MemoryEventIngest, MemoryLearningIngest, RawMemoryEvent,-};-use crate::memory::api::provider::types::SourceScope;-use crate::memory::api::provider::types::{IngestItem, IngestOutcome};-use crate::memory::api::provider::MemoryChunks;-use async_trait::async_trait;-use tinymemory_api::learning::LearningCandidate;--use super::super::audit::{trace_allowed, NO_NAMESPACE};-use super::super::policy::GuardPolicy;-use super::types::{- GuardedAnswer, GuardedChunks, GuardedConversationIngest, GuardedDocumentIngest,- GuardedEventIngest, GuardedLearningIngest,-};--/// Steps 3 + 4 over one ingest item, shared by the typed-ingest decorators:-/// stamp provenance, redact on egress — the same admission-/// [`GuardedIngest::admit`] applies on the legacy family.-fn admit_typed_item(policy: &GuardPolicy, mut item: IngestItem) -> IngestItem {- item.taint = policy.stamp_taint(item.taint);- item.content = policy.redact_outbound(&item.content).into_owned();- item-}--#[async_trait]-impl MemoryDocumentIngest for GuardedDocumentIngest {- async fn ingest_document(&self, document: IngestItem) -> Result<IngestOutcome, MemoryError> {- let namespace = document- .namespace- .clone()- .unwrap_or_else(|| "-".to_string());- self.policy.admit_write(- Capability::DocumentIngest,- "document_ingest.ingest_document",- &namespace,- true,- )?;- let document = admit_typed_item(&self.policy, document);- trace_allowed(- &self.policy,- "document_ingest.ingest_document",- &namespace,- document.content.chars().count(),- );- self.family()?.ingest_document(document).await- }-}--#[async_trait]-impl MemoryConversationIngest for GuardedConversationIngest {- async fn ingest_conversation(- &self,- messages: Vec<IngestItem>,- ) -> Result<IngestOutcome, MemoryError> {- self.policy.admit_write(- Capability::ConversationIngest,- "conversation_ingest.ingest_conversation",- NO_NAMESPACE,- true,- )?;- let messages: Vec<IngestItem> = messages- .into_iter()- .map(|m| admit_typed_item(&self.policy, m))- .collect();- trace_allowed(- &self.policy,- "conversation_ingest.ingest_conversation",- NO_NAMESPACE,- messages.iter().map(|m| m.content.chars().count()).sum(),- );- self.family()?.ingest_conversation(messages).await- }-}--#[async_trait]-impl MemoryLearningIngest for GuardedLearningIngest {- async fn ingest_learning(- &self,- learning: LearningCandidate,- ) -> Result<IngestOutcome, MemoryError> {- // No content redaction: a learning candidate is already extracted- // structure, not raw user text — provenance is the driver's to stamp- // from the evidence pointer it carries.- self.policy.admit_write(- Capability::LearningIngest,- "learning_ingest.ingest_learning",- NO_NAMESPACE,- true,- )?;- trace_allowed(- &self.policy,- "learning_ingest.ingest_learning",- NO_NAMESPACE,- 0,- );- self.family()?.ingest_learning(learning).await- }-}--#[async_trait]-impl MemoryEventIngest for GuardedEventIngest {- async fn ingest_event(&self, event: RawMemoryEvent) -> Result<IngestOutcome, MemoryError> {- self.policy.admit_write(- Capability::EventIngest,- "event_ingest.ingest_event",- NO_NAMESPACE,- true,- )?;- trace_allowed(&self.policy, "event_ingest.ingest_event", NO_NAMESPACE, 0);- self.family()?.ingest_event(event).await- }-}--#[async_trait]-impl MemoryAnswer for GuardedAnswer {- async fn answer(&self, request: AnswerRequest) -> Result<AnswerResponse, MemoryError> {- // A read-shaped family: retrieval plus synthesis, no persistence.- self.policy- .admit_read(Capability::Answer, "answer.answer", NO_NAMESPACE, false)?;- trace_allowed(&self.policy, "answer.answer", NO_NAMESPACE, 0);- self.family()?.answer(request).await- }-}--#[async_trait]-impl MemoryChunks for GuardedChunks {- async fn list_chunks(- &self,- query: &ChunkQuery,- scope: Option<&SourceScope>,- ) -> Result<Vec<Chunk>, MemoryError> {- self.policy.admit_read(- Capability::Chunks,- "chunks.list_chunks",- NO_NAMESPACE,- false,- )?;- // Intersected with the ambient allowlist, never passed through. The- // ambient scope is an upper bound: forwarding the caller's scope- // unchanged would let a source-restricted turn widen itself back out by- // naming a collection the restriction excluded. See- // `GuardPolicy::narrow_scope`.- let effective = self.policy.narrow_scope(scope);- self.family()?.list_chunks(query, effective.as_ref()).await- }-- /// The count that labels a [`Self::list_chunks`] page, and it must be- /// narrowed by exactly the same rule. A total computed against a wider- /// scope than the page it labels leaks the existence of rows the caller may- /// not read — "showing 20 of 4000" tells a source-restricted turn how much- /// it is not being shown.- async fn count_chunks(- &self,- query: &ChunkQuery,- scope: Option<&SourceScope>,- ) -> Result<u64, MemoryError> {- self.policy.admit_read(- Capability::Chunks,- "chunks.count_chunks",- NO_NAMESPACE,- false,- )?;- let effective = self.policy.narrow_scope(scope);- self.family()?.count_chunks(query, effective.as_ref()).await- }-- /// Same rows as [`Self::list_chunks`] with the stored facts beside them, so- /// the same intersection applies for the same reason.- async fn list_chunk_details(- &self,- query: &ChunkQuery,- scope: Option<&SourceScope>,- ) -> Result<Vec<ChunkListRow>, MemoryError> {- self.policy.admit_read(- Capability::Chunks,- "chunks.list_chunk_details",- NO_NAMESPACE,- false,- )?;- let effective = self.policy.narrow_scope(scope);- self.family()?- .list_chunk_details(query, effective.as_ref())- .await- }-- /// Per-source totals are computed from the chunks the scope admits, not- /// filtered afterwards — so a restricted caller must not learn that a- /// forbidden source exists by seeing its row, nor see a permitted source- /// carrying a count that includes rows it cannot read.- async fn source_totals(- &self,- limit: usize,- scope: Option<&SourceScope>,- ) -> Result<Vec<SourceTotal>, MemoryError> {- self.policy.admit_read(- Capability::Chunks,- "chunks.source_totals",- NO_NAMESPACE,- false,- )?;- let effective = self.policy.narrow_scope(scope);- self.family()?- .source_totals(limit, effective.as_ref())- .await- }-- async fn get_chunk(&self, chunk_id: &str) -> Result<Option<Chunk>, MemoryError> {- self.policy- .admit_read(Capability::Chunks, "chunks.get_chunk", NO_NAMESPACE, false)?;- self.family()?.get_chunk(chunk_id).await- }-- async fn chunk_detail(&self, chunk_id: &str) -> Result<Option<ChunkDetail>, MemoryError> {- self.policy.admit_read(- Capability::Chunks,- "chunks.chunk_detail",- NO_NAMESPACE,- false,- )?;- self.family()?.chunk_detail(chunk_id).await- }-- /// The catalog is not user content, so it takes no namespace and the- /// lightest read check — refusing it under `readonly` would stop an- /// operator finding out what the store can even hold.- async fn storage_kinds(&self) -> Result<Vec<String>, MemoryError> {- self.policy.admit_read(- Capability::Chunks,- "chunks.storage_kinds",- NO_NAMESPACE,- false,- )?;- self.family()?.storage_kinds().await- }-- /// Vectors, not content — but still a read of stored material, so it takes- /// the same tier check rather than being waved through as metadata.- async fn chunk_embeddings(- &self,- chunk_ids: &[String],- model_signature: &str,- ) -> Result<Vec<ChunkEmbedding>, MemoryError> {- self.policy.admit_read(- Capability::Chunks,- "chunks.chunk_embeddings",- NO_NAMESPACE,- false,- )?;- self.family()?- .chunk_embeddings(chunk_ids, model_signature)- .await- }-- /// One chunk's admission verdict, read by chunk id exactly as- /// [`Self::chunk_detail`] is — so it takes that member's check, not- /// [`Self::list_chunks`]'s scope intersection. There is no scope to narrow:- /// the caller already holds the id.- async fn chunk_score(&self, chunk_id: &str) -> Result<Option<ChunkScore>, MemoryError> {- self.policy.admit_read(- Capability::Chunks,- "chunks.chunk_score",- NO_NAMESPACE,- false,- )?;- self.family()?.chunk_score(chunk_id).await- }-- /// Ingest progress for the sources the caller names, one row per query.- ///- /// Unlike [`Self::source_totals`], which enumerates the groups that exist- /// and therefore has to be narrowed to the ambient allowlist, this answers- /// only about prefixes the caller supplied — it discloses no source the- /// caller did not already name — and the contract member carries no- /// [`SourceScope`] for the guard to intersect anything into.- async fn source_ingest_status(- &self,- source_prefixes: &[SourceIngestQuery],- ) -> Result<Vec<SourceIngestStatus>, MemoryError> {- self.policy.admit_read(- Capability::Chunks,- "chunks.source_ingest_status",- NO_NAMESPACE,- false,- )?;- self.family()?.source_ingest_status(source_prefixes).await- }-}diff --git a/crates/openhuman-core/src/memory/guard/families/types.rs b/crates/openhuman-core/src/memory/guard/families/types.rsdeleted file mode 100644index 0e758afdcc..0000000000--- a/crates/openhuman-core/src/memory/guard/families/types.rs+++ /dev/null@@ -1,226 +0,0 @@-//! The shared decorator scaffolding for every guarded family: the-//! `decorator!` macro that declares one struct's two fields, constructor,-//! and `family()` re-derivation, plus every family's invocation of it.-//!-//! Split out of `families.rs` (see that module's doc comment for why each-//! family gets its own decorator rather than the guard forwarding a raw-//! borrow). The trait implementations that make each of these types actually-//! guard something live in the sibling `*_impls`-style files under-//! [`super`].--use std::sync::Arc;--use crate::memory::api::capabilities::Capability;-use crate::memory::api::error::MemoryError;-use crate::memory::api::provider::chunks::MemoryChunks;-use crate::memory::api::provider::episodic::MemoryEpisodic;-use crate::memory::api::provider::operations::{- MemoryAnswer, MemoryConversationIngest, MemoryDocumentIngest, MemoryEventIngest,- MemoryLearningIngest,-};-use crate::memory::api::provider::people::MemoryPeople;-use crate::memory::api::provider::profile::MemoryProfile;-use crate::memory::api::provider::retrieval::MemoryRetrieval;-use crate::memory::api::provider::scoring::MemoryScoring;-use crate::memory::api::provider::sessions::MemoryCodingSessions;-use crate::memory::api::provider::sync::MemorySourceSync;-use crate::memory::api::provider::{- MemoryDiff, MemoryDocuments, MemoryEntities, MemoryGoals, MemoryGraph, MemoryIngest,- MemoryMaintenance, MemoryProvider, MemorySourceSink, MemoryToolMemory, MemoryTree,-};--use super::super::policy::GuardPolicy;--macro_rules! decorator {- ($(#[$meta:meta])* $name:ident, $fam:ty, $accessor:ident, $cap:ident) => {- $(#[$meta])*- pub struct $name {- inner: Arc<dyn MemoryProvider>,- pub(super) policy: Arc<GuardPolicy>,- }-- impl $name {- pub(crate) fn new(inner: Arc<dyn MemoryProvider>, policy: Arc<GuardPolicy>) -> Self {- Self { inner, policy }- }-- /// The underlying family handle.- ///- /// The `Err` arm is **structurally unreachable**: `MemoryGuard::new`- /// only builds this decorator when the inner provider answered- /// `provides(Capability::$cap)`, and the contract documents the- /// capability set as fixed at bind time. It is written as a real- /// error rather than `.expect(...)` because a panic inside a memory- /// call is a strictly worse failure than an `Unsupported` a caller- /// can already handle.- pub(super) fn family(&self) -> Result<&$fam, MemoryError> {- self.inner- .$accessor()- .ok_or_else(|| MemoryError::unsupported(Capability::$cap))- }- }- };-}--decorator!(- /// Guarded [`MemoryIngest`].- GuardedIngest,- dyn MemoryIngest,- as_ingest,- Ingest-);-decorator!(- /// Guarded [`MemoryDocuments`].- GuardedDocuments,- dyn MemoryDocuments,- as_documents,- Documents-);-decorator!(- /// Guarded [`MemoryTree`] — the one family that carries step 2.- GuardedTree,- dyn MemoryTree,- as_tree,- Tree-);-decorator!(- /// Guarded [`MemoryEntities`].- GuardedEntities,- dyn MemoryEntities,- as_entities,- Entities-);-decorator!(- /// Guarded [`MemoryGraph`].- GuardedGraph,- dyn MemoryGraph,- as_graph,- Graph-);-decorator!(- /// Guarded [`MemoryDiff`].- GuardedDiff,- dyn MemoryDiff,- as_diff,- Diff-);-decorator!(- /// Guarded [`MemoryGoals`].- GuardedGoals,- dyn MemoryGoals,- as_goals,- Goals-);-decorator!(- /// Guarded [`MemoryToolMemory`].- GuardedToolMemory,- dyn MemoryToolMemory,- as_tool_memory,- ToolMemory-);-decorator!(- /// Guarded [`MemorySourceSink`].- GuardedSources,- dyn MemorySourceSink,- as_sources,- Sources-);-decorator!(- /// Guarded [`MemoryMaintenance`].- GuardedMaintenance,- dyn MemoryMaintenance,- as_maintenance,- Maintenance-);-decorator!(- /// Guarded [`MemoryPeople`].- GuardedPeople,- dyn MemoryPeople,- as_people,- People-);-decorator!(- /// Guarded [`MemoryChunks`].- GuardedChunks,- dyn MemoryChunks,- as_chunks,- Chunks-);-decorator!(- /// Guarded [`MemoryRetrieval`].- GuardedRetrieval,- dyn MemoryRetrieval,- as_retrieval,- Retrieval-);-decorator!(- /// Guarded [`MemoryEpisodic`].- GuardedEpisodic,- dyn MemoryEpisodic,- 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,- dyn MemoryProfile,- as_profile,- Profile-);-decorator!(- /// Guarded [`MemoryScoring`].- GuardedScoring,- dyn MemoryScoring,- as_scoring,- Scoring-);--decorator!(- /// Guarded [`MemoryDocumentIngest`].- GuardedDocumentIngest,- dyn MemoryDocumentIngest,- as_document_ingest,- DocumentIngest-);-decorator!(- /// Guarded [`MemoryConversationIngest`].- GuardedConversationIngest,- dyn MemoryConversationIngest,- as_conversation_ingest,- ConversationIngest-);-decorator!(- /// Guarded [`MemoryLearningIngest`].- GuardedLearningIngest,- dyn MemoryLearningIngest,- as_learning_ingest,- LearningIngest-);-decorator!(- /// Guarded [`MemoryEventIngest`].- GuardedEventIngest,- dyn MemoryEventIngest,- as_event_ingest,- EventIngest-);-decorator!(- /// Guarded [`MemoryAnswer`].- GuardedAnswer,- dyn MemoryAnswer,- as_answer,- Answer-);diff --git a/crates/openhuman-core/src/memory/guard/mandatory.rs b/crates/openhuman-core/src/memory/guard/mandatory.rsdeleted file mode 100644index bab08195b3..0000000000--- a/crates/openhuman-core/src/memory/guard/mandatory.rs+++ /dev/null@@ -1,188 +0,0 @@-//! The three mandatory families on [`MemoryGuard`] — where steps 3, 4 and 6-//! land for the always-present surface.--use crate::memory::api::capabilities::Capability;-use crate::memory::api::error::MemoryError;-use crate::memory::api::provider::types::{ExportPage, ExportRecord, ImportOutcome, SourceScope};-use crate::memory::api::provider::{MemoryCore, MemoryPortability, MemoryRecall};-use crate::memory::api::recall::OwnedRecallOpts;-use crate::memory::api::types::{MemoryCategory, MemoryEntry, MemoryTaint, NamespaceSummary};-use async_trait::async_trait;--use super::audit::{trace_allowed, trace_budget, NO_NAMESPACE};-use super::budget::{truncate_content, truncate_entries};-use super::provider::MemoryGuard;--#[async_trait]-impl MemoryCore for MemoryGuard {- /// Store, with steps 1, 3, 4, 5 and the capture half of 6 applied in that- /// order: refuse first, then stamp provenance, then redact, then trim.- ///- /// Trimming last is deliberate — redaction can lengthen content (a matched- /// secret becomes `[REDACTED_SECRET]`), so a budget applied before it could- /// be exceeded by the time the write leaves.- async fn store(- &self,- namespace: &str,- key: &str,- content: &str,- category: MemoryCategory,- session_id: Option<&str>,- taint: MemoryTaint,- ) -> Result<(), MemoryError> {- let policy = self.policy();- policy.admit_write(Capability::Core, "core.store", namespace, true)?;-- let taint = policy.stamp_taint(taint);- let content = policy.redact_outbound(content);- let content = match policy.capture_budget() {- Some(max) => truncate_content(&content, max).into_owned(),- None => content.into_owned(),- };- trace_allowed(policy, "core.store", namespace, content.chars().count());-- self.inner()- .store(namespace, key, &content, category, session_id, taint)- .await- }-- async fn get(&self, namespace: &str, key: &str) -> Result<Option<MemoryEntry>, MemoryError> {- let policy = self.policy();- policy.admit_read(Capability::Core, "core.get", namespace, false)?;- self.inner().get(namespace, key).await- }-- async fn forget(&self, namespace: &str, key: &str) -> Result<bool, MemoryError> {- let policy = self.policy();- policy.admit_write(Capability::Core, "core.forget", namespace, false)?;- self.inner().forget(namespace, key).await- }-- async fn list(- &self,- namespace: Option<&str>,- category: Option<&MemoryCategory>,- session_id: Option<&str>,- ) -> Result<Vec<MemoryEntry>, MemoryError> {- let policy = self.policy();- policy.admit_read(- Capability::Core,- "core.list",- namespace.unwrap_or(NO_NAMESPACE),- false,- )?;- // No recall budget here on purpose: `list` is an enumeration surface- // (the UI's memory browser, export tooling) rather than the context- // block a turn injects, and silently truncating it would make the- // browser disagree with the store. `recall_max_chars` is a *recall*- // budget and is applied where recall happens.- self.inner().list(namespace, category, session_id).await- }-- async fn namespaces(&self) -> Result<Vec<NamespaceSummary>, MemoryError> {- let policy = self.policy();- policy.admit_read(Capability::Core, "core.namespaces", NO_NAMESPACE, false)?;- self.inner().namespaces().await- }-}--#[async_trait]-impl MemoryRecall for MemoryGuard {- /// Recall, with the recall char budget (step 6) applied to the driver's- /// result.- ///- /// ## `scope` is forwarded, never filled from the task-local- ///- /// This is the one place the "read the ambient scope at the guard boundary"- /// rule does **not** apply, and it is deliberate. The embedded driver- /// *refuses* a `Some(scope)` on recall — see `SCOPE_UNAPPLIED` in- /// `memory/driver/embedded/recall.rs`, which argues at length that- /// ignoring the scope is a silent leak and post-filtering is the named- /// anti-pattern, so refusing is the only honest answer until the recall- /// predicate exists. Filling `scope` here from- /// `current_source_scope()` would therefore turn **every** recall issued- /// inside a `with_source_scope` into a hard error against the only real- /// driver.- ///- /// So the guard passes the caller's `scope` through untouched. The ambient- /// allowlist is applied where a driver actually implements it as a query- /// predicate — `MemoryTree::query_source` — and recall joins that list when- /// the embedded recall path grows the predicate.- async fn recall(- &self,- query: &str,- limit: usize,- opts: &OwnedRecallOpts,- scope: Option<&SourceScope>,- ) -> Result<Vec<MemoryEntry>, MemoryError> {- let policy = self.policy();- // The query text itself crosses the boundary on an external driver.- policy.admit_read(- Capability::Recall,- "recall.recall",- opts.namespace.as_deref().unwrap_or(NO_NAMESPACE),- true,- )?;- let query = policy.redact_outbound(query);-- let hits = self.inner().recall(&query, limit, opts, scope).await?;-- match policy.recall_budget() {- None => Ok(hits),- Some(max) => {- let outcome = truncate_entries(hits, max);- trace_budget(- policy,- "recall.recall",- outcome.dropped,- outcome.trimmed_chars,- );- Ok(outcome.entries)- }- }- }-}--#[async_trait]-impl MemoryPortability for MemoryGuard {- /// Export is **not** budget-trimmed. A truncated export is a corrupt- /// backup, and portability exists so a binding is reversible — trimming it- /// would silently make it a one-way door, which is the exact failure the- /// contract made this family mandatory to avoid.- async fn export_page(- &self,- cursor: Option<&str>,- limit: usize,- ) -> Result<ExportPage, MemoryError> {- let policy = self.policy();- policy.admit_read(- Capability::Portability,- "portability.export_page",- NO_NAMESPACE,- false,- )?;- self.inner().export_page(cursor, limit).await- }-- /// Import **preserves** each record's taint rather than re-stamping it.- ///- /// The contract is explicit: "records carry their own taint; an importing- /// driver must persist what it is given and must not re-stamp provenance."- /// The guard holds to the same rule. Re-stamping here would rewrite an- /// entire restored store's provenance to whatever the ambient scope of the- /// restoring turn happened to be — laundering a million records in one- /// call, which is the opposite of what step 3 is for.- async fn import_records(- &self,- records: Vec<ExportRecord>,- ) -> Result<ImportOutcome, MemoryError> {- let policy = self.policy();- policy.admit_write(- Capability::Portability,- "portability.import_records",- NO_NAMESPACE,- true,- )?;- self.inner().import_records(records).await- }-}diff --git a/crates/openhuman-core/src/memory/guard/mod.rs b/crates/openhuman-core/src/memory/guard/mod.rsindex a85654076a..13a6fbed89 100644--- a/crates/openhuman-core/src/memory/guard/mod.rs+++ b/crates/openhuman-core/src/memory/guard/mod.rs@@ -1,6 +1,17 @@//! [`MemoryGuard`] — the kernel-owned policy decorator over the bound memory//! driver (`docs/specs/plan-memory.md` §3.4, `docs/specs/kernel.md` §3.4).//!+//! ## Where the code lives+//!+//! The decorator is generic and lives in the `tinymemory-guard` crate+//! (`vendor/tinymemory/crates/tinymemory-guard`): `GuardedProvider<P: GuardPolicy>`,+//! the per-family decorators, the char-budget arithmetic and the span. This+//! module is the host half: [`HostGuardPolicy`] implements+//! `tinymemory_guard::GuardPolicy` with the live `SecurityPolicy` tier, the+//! task-local source scope, the sanitizer, egress disclosure and the+//! `MemoryGuardDenied` bus event, and [`MemoryGuard`] is that decorator+//! instantiated with it.+//!//! ## The shape, and why it is this shape//!//! The guard implements [`MemoryProvider`](crate::memory::api::provider::MemoryProvider)@@ -12,25 +23,25 @@//! The load-bearing detail is the `as_*` accessors. Every optional capability//! family (23 of the contract's 26; only `MemoryCore`, `MemoryRecall` and//! `MemoryPortability` are mandatory and implemented on the guard directly in-//! `mandatory.rs`) is reachable **only** through them, so an override that+//! `tinymemory_guard`'s `mandatory.rs`) is reachable **only** through them, so an override that//! forwarded `self.inner.as_tree()` would hand out a raw driver handle and//! defeat the entire design with one method call. Each family therefore gets//! its own decorator, owned as a field on the guard (an accessor returns a//! borrow, so it cannot build one on demand) and present exactly when the inner-//! driver provides that family. See [`families`].+//! driver provides that family. See `tinymemory_guard::families`.//!//! ## The seven enforcement steps//!//! | # | Step | Where |//! | - | ---- | ----- |-//! | 1 | `SecurityPolicy` tier | [`GuardPolicy::enforce_read`] / [`GuardPolicy::enforce_write`] |+//! | 1 | `SecurityPolicy` tier | `GuardPolicy::enforce_read` / `GuardPolicy::enforce_write` |//! | 1b | path rules | **no-op** — no contract method carries a path; see [`policy`] |-//! | 2 | source scope as a query predicate | [`GuardPolicy::ambient_scope`], applied in `GuardedTree::query_source` |-//! | 3 | taint stamping | [`GuardPolicy::stamp_taint`] |-//! | 4 | redaction | [`GuardPolicy::redact_outbound`] — a no-op for embedded drivers |-//! | 5 | egress + trust | [`GuardPolicy::check_egress`] |-//! | 6 | char budgets | [`budget`], driven by `MemoryHooksConfig` |-//! | 7 | audit + tracing | [`audit`] |+//! | 2 | source scope as a query predicate | `GuardPolicy::ambient_scope`, applied in `GuardedTree::query_source` |+//! | 3 | taint stamping | `GuardPolicy::stamp_taint` |+//! | 4 | redaction | `GuardPolicy::redact_outbound` — a no-op for embedded drivers |+//! | 5 | egress + trust | `GuardPolicy::check_egress` |+//! | 6 | char budgets | `tinymemory_guard::budget`, driven by `MemoryHooksConfig` |+//! | 7 | audit + tracing | [`audit`], `tinymemory_guard::audit` |//!//! Three of those departed from the milestone brief because the brief's version//! would have been wrong against this tree; each departure is argued at its own@@ -84,7 +95,7 @@//! shipped in no released artifact until v1.2.0, so a caller moved onto it//! before the registry re-pin would get a runtime `Unsupported`. The host-side//! half-measure the note floated (having `ProfileStore` consult-//! [`policy::GuardPolicy`] directly) is no longer the only option and should not+//! [`policy::HostGuardPolicy`] directly) is no longer the only option and should not//! be taken: it would make a `readonly` tier start rejecting learning-cache//! rebuilds, which is a behaviour change rather than a refactor.//!@@ -96,19 +107,18 @@//! the same grep before relying on this being still true; the allowlist test//! is the actual enforcement, this paragraph is not.-pub mod audit;-pub mod budget;-pub mod families;-/// In-memory provider fake for tests. Not `#[cfg(test)]` — integration tests-/// link the lib without it.-#[doc(hidden)]-pub mod in_memory;-mod mandatory;+mod audit;+/// In-memory provider fakes and guard-wrapping helpers for tests. The drivers+/// are `tinymemory-conformance`'s; only the host-policy wrapping lives here.+#[cfg(test)]+pub(crate) mod in_memory;pub mod policy;-pub mod provider;#[cfg(test)]pub(crate) mod test_support;-pub use policy::GuardPolicy;-pub use provider::MemoryGuard;+pub use policy::HostGuardPolicy;++/// The policy decorator every product caller receives instead of the raw driver:+/// `tinymemory_guard::GuardedProvider` over the host's policy.+pub type MemoryGuard = tinymemory_guard::GuardedProvider<HostGuardPolicy>;diff --git a/crates/openhuman-core/src/memory/guard/provider.rs b/crates/openhuman-core/src/memory/guard/provider.rsdeleted file mode 100644index 4451919faf..0000000000--- a/crates/openhuman-core/src/memory/guard/provider.rs+++ /dev/null@@ -1,266 +0,0 @@-//! [`MemoryGuard`] — the kernel-owned policy decorator over a bound driver.--use std::sync::Arc;--use crate::memory::api::capabilities::{Capabilities, Capability};-use crate::memory::api::error::MemoryError;-use crate::memory::api::health::MemoryHealth;-use crate::memory::api::provider::operations::{- MemoryAnswer, MemoryConversationIngest, MemoryDocumentIngest, MemoryEventIngest,- MemoryLearningIngest,-};-use crate::memory::api::provider::scoring::MemoryScoring;-use crate::memory::api::provider::{- 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::{- GuardedAnswer, GuardedChunks, GuardedCodingSessions, GuardedConversationIngest, GuardedDiff,- GuardedDocumentIngest, GuardedDocuments, GuardedEntities, GuardedEpisodic, GuardedEventIngest,- GuardedGoals, GuardedGraph, GuardedIngest, GuardedLearningIngest, GuardedMaintenance,- GuardedPeople, GuardedProfile, GuardedRetrieval, GuardedScoring, GuardedSourceSync,- GuardedSources, GuardedToolMemory, GuardedTree,-};-use super::policy::GuardPolicy;--/// The policy decorator every product caller receives instead of the raw-/// driver (`docs/specs/plan-memory.md` §3.4, `docs/specs/kernel.md` §3.4).-///-/// It implements [`MemoryProvider`], so it is transparent to callers and cannot-/// be "skipped" by a caller that simply keeps using the contract — there is no-/// second, unguarded shape to hold. Its fourteen `as_*` overrides hand back-/// **guarded** family handles rather than the inner driver's, which is what-/// closes the accessor bypass; see [`super::families`] for why that forces the-/// decorators to be owned fields.-pub struct MemoryGuard {- inner: Arc<dyn MemoryProvider>,- policy: Arc<GuardPolicy>,-- // The fourteen optional families. Each is `Some` **iff** the inner driver- // provides it, so `provides()` — which the contract's `audit_provider`- // compares against `capabilities()` — answers identically for the guard and- // for the driver underneath it.- ingest: Option<GuardedIngest>,- documents: Option<GuardedDocuments>,- tree: Option<GuardedTree>,- entities: Option<GuardedEntities>,- graph: Option<GuardedGraph>,- diff: Option<GuardedDiff>,- goals: Option<GuardedGoals>,- tool_memory: Option<GuardedToolMemory>,- sources: Option<GuardedSources>,- maintenance: Option<GuardedMaintenance>,- people: Option<GuardedPeople>,- chunks: Option<GuardedChunks>,- retrieval: Option<GuardedRetrieval>,- profile: Option<GuardedProfile>,- episodic: Option<GuardedEpisodic>,- source_sync: Option<GuardedSourceSync>,- coding_sessions: Option<GuardedCodingSessions>,- scoring: Option<GuardedScoring>,- document_ingest: Option<GuardedDocumentIngest>,- conversation_ingest: Option<GuardedConversationIngest>,- learning_ingest: Option<GuardedLearningIngest>,- event_ingest: Option<GuardedEventIngest>,- answer: Option<GuardedAnswer>,-}--impl MemoryGuard {- /// How the guarded driver was bound (a host fact, from the policy).- pub(crate) fn class(&self) -> crate::core::subsystem::DriverClass {- self.policy.class()- }-- /// Wrap `inner` in `policy`.- ///- /// Builds all fourteen decorators up front. That is not an optimisation: the- /// `as_*` accessors return borrows, so a decorator constructed inside an- /// accessor could not outlive the call.- pub fn new(inner: Arc<dyn MemoryProvider>, policy: Arc<GuardPolicy>) -> Self {- macro_rules! family {- ($cap:ident, $ty:ident) => {- inner- .provides(Capability::$cap)- .then(|| $ty::new(Arc::clone(&inner), Arc::clone(&policy)))- };- }- Self {- ingest: family!(Ingest, GuardedIngest),- documents: family!(Documents, GuardedDocuments),- tree: family!(Tree, GuardedTree),- entities: family!(Entities, GuardedEntities),- graph: family!(Graph, GuardedGraph),- diff: family!(Diff, GuardedDiff),- goals: family!(Goals, GuardedGoals),- tool_memory: family!(ToolMemory, GuardedToolMemory),- sources: family!(Sources, GuardedSources),- maintenance: family!(Maintenance, GuardedMaintenance),- people: family!(People, GuardedPeople),- chunks: family!(Chunks, GuardedChunks),- retrieval: family!(Retrieval, GuardedRetrieval),- profile: family!(Profile, GuardedProfile),- episodic: family!(Episodic, GuardedEpisodic),- source_sync: family!(SourceSync, GuardedSourceSync),- coding_sessions: family!(CodingSessions, GuardedCodingSessions),- scoring: family!(Scoring, GuardedScoring),- document_ingest: family!(DocumentIngest, GuardedDocumentIngest),- conversation_ingest: family!(ConversationIngest, GuardedConversationIngest),- learning_ingest: family!(LearningIngest, GuardedLearningIngest),- event_ingest: family!(EventIngest, GuardedEventIngest),- answer: family!(Answer, GuardedAnswer),- inner,- policy,- }- }-- /// The policy this guard enforces.- pub fn policy(&self) -> &Arc<GuardPolicy> {- &self.policy- }-- /// The wrapped driver.- ///- /// `pub(crate)` on purpose: handing this out is exactly the bypass the- /// guard exists to prevent, and the only legitimate use is inside the- /// memory subsystem itself (identity, health, tests). Do not widen it.- pub(crate) fn inner(&self) -> &Arc<dyn MemoryProvider> {- &self.inner- }-}--#[async_trait]-impl MemoryProvider for MemoryGuard {- /// The **wrapped driver's** id, not a synthetic `"guard"`. The guard is a- /// policy layer, not a driver: status output, spans, and audit events all- /// name the thing that actually stores the bytes.- fn driver_id(&self) -> &str {- self.inner.driver_id()- }-- fn capabilities(&self) -> Capabilities {- self.inner.capabilities()- }-- async fn health(&self) -> MemoryHealth {- self.inner.health().await- }-- async fn shutdown(&self) -> Result<(), MemoryError> {- self.inner.shutdown().await- }-- fn as_document_ingest(&self) -> Option<&dyn MemoryDocumentIngest> {- self.document_ingest- .as_ref()- .map(|g| g as &dyn MemoryDocumentIngest)- }-- fn as_conversation_ingest(&self) -> Option<&dyn MemoryConversationIngest> {- self.conversation_ingest- .as_ref()- .map(|g| g as &dyn MemoryConversationIngest)- }-- fn as_learning_ingest(&self) -> Option<&dyn MemoryLearningIngest> {- self.learning_ingest- .as_ref()- .map(|g| g as &dyn MemoryLearningIngest)- }-- fn as_event_ingest(&self) -> Option<&dyn MemoryEventIngest> {- self.event_ingest- .as_ref()- .map(|g| g as &dyn MemoryEventIngest)- }-- fn as_answer(&self) -> Option<&dyn MemoryAnswer> {- self.answer.as_ref().map(|g| g as &dyn MemoryAnswer)- }-- fn as_ingest(&self) -> Option<&dyn MemoryIngest> {- self.ingest.as_ref().map(|g| g as &dyn MemoryIngest)- }-- fn as_documents(&self) -> Option<&dyn MemoryDocuments> {- self.documents.as_ref().map(|g| g as &dyn MemoryDocuments)- }-- fn as_tree(&self) -> Option<&dyn MemoryTree> {- self.tree.as_ref().map(|g| g as &dyn MemoryTree)- }-- fn as_entities(&self) -> Option<&dyn MemoryEntities> {- self.entities.as_ref().map(|g| g as &dyn MemoryEntities)- }-- fn as_graph(&self) -> Option<&dyn MemoryGraph> {- self.graph.as_ref().map(|g| g as &dyn MemoryGraph)- }-- fn as_diff(&self) -> Option<&dyn MemoryDiff> {- self.diff.as_ref().map(|g| g as &dyn MemoryDiff)- }-- fn as_goals(&self) -> Option<&dyn MemoryGoals> {- self.goals.as_ref().map(|g| g as &dyn MemoryGoals)- }-- fn as_tool_memory(&self) -> Option<&dyn MemoryToolMemory> {- self.tool_memory- .as_ref()- .map(|g| g as &dyn MemoryToolMemory)- }-- fn as_sources(&self) -> Option<&dyn MemorySourceSink> {- self.sources.as_ref().map(|g| g as &dyn MemorySourceSink)- }-- fn as_maintenance(&self) -> Option<&dyn MemoryMaintenance> {- self.maintenance- .as_ref()- .map(|g| g as &dyn MemoryMaintenance)- }-- fn as_people(&self) -> Option<&dyn MemoryPeople> {- self.people.as_ref().map(|g| g as &dyn MemoryPeople)- }-- fn as_chunks(&self) -> Option<&dyn MemoryChunks> {- self.chunks.as_ref().map(|g| g as &dyn MemoryChunks)- }-- fn as_retrieval(&self) -> Option<&dyn MemoryRetrieval> {- self.retrieval.as_ref().map(|g| g as &dyn MemoryRetrieval)- }-- fn as_profile(&self) -> Option<&dyn MemoryProfile> {- self.profile.as_ref().map(|g| g as &dyn MemoryProfile)- }-- 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)- }- fn as_scoring(&self) -> Option<&dyn MemoryScoring> {- self.scoring.as_ref().map(|g| g as &dyn MemoryScoring)- }-}--#[cfg(test)]-#[path = "provider_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/memory/guard/test_support/core_and_docs_impls.rs b/crates/openhuman-core/src/memory/guard/test_support/core_and_docs_impls.rsdeleted file mode 100644index 685432680a..0000000000--- a/crates/openhuman-core/src/memory/guard/test_support/core_and_docs_impls.rs+++ /dev/null@@ -1,541 +0,0 @@-//! `RecordingProvider`'s `Core`, `Recall`, `Portability`, `Ingest`,-//! `Documents`, `Tree`, `Entities`, `Graph`, `Diff`, `Goals`, and-//! `ToolMemory` family implementations — the write/tree/graph half.-//!-//! Split out of the original `test_support.rs`; see [`super::fixtures`] for-//! `RecordingProvider`'s type and constructors.--use crate::memory::api::chunks::Chunk;-use crate::memory::api::error::MemoryError;-use crate::memory::api::goals::GoalsDoc;-use crate::memory::api::provider::types::{- DiffReport, EntityHit, ExportPage, ExportRecord, ImportOutcome, IngestItem, IngestOutcome,- SnapshotRef, SourceScope,-};-use crate::memory::api::provider::{- MemoryCore, MemoryDiff, MemoryDocuments, MemoryEntities, MemoryGoals, MemoryGraph,- MemoryIngest, MemoryPortability, MemoryRecall, MemoryToolMemory, MemoryTree,-};-use crate::memory::api::recall::OwnedRecallOpts;-use crate::memory::api::tool_memory::ToolMemoryRule;-use crate::memory::api::tree::{IngestRequest, QueryResult, TreeStatus};-use crate::memory::api::types::{- GraphRelationRecord, MemoryCategory, MemoryEntry, MemoryKvRecord, MemoryTaint,- NamespaceDocumentInput, NamespaceRetrievalContext, NamespaceSummary, StoredMemoryDocument,-};-use async_trait::async_trait;--use super::fixtures::{Call, RecordingProvider};--/// A [`TreeStatus`] fixture.-fn tree_status(namespace: &str) -> TreeStatus {- TreeStatus {- namespace: namespace.to_string(),- total_nodes: 0,- depth: 0,- oldest_entry: None,- newest_entry: None,- last_run_at: None,- }-}--#[async_trait]-impl MemoryCore for RecordingProvider {- async fn store(- &self,- _namespace: &str,- _key: &str,- content: &str,- _category: MemoryCategory,- _session_id: Option<&str>,- taint: MemoryTaint,- ) -> Result<(), MemoryError> {- self.record(Call {- method: "core.store".into(),- content: Some(content.to_string()),- taint: Some(taint),- scoped: None,- });- Ok(())- }-- async fn get(&self, _namespace: &str, _key: &str) -> Result<Option<MemoryEntry>, MemoryError> {- self.record(Call::plain("core.get"));- Ok(None)- }-- async fn forget(&self, _namespace: &str, _key: &str) -> Result<bool, MemoryError> {- self.record(Call::plain("core.forget"));- Ok(false)- }-- async fn list(- &self,- _namespace: Option<&str>,- _category: Option<&MemoryCategory>,- _session_id: Option<&str>,- ) -> Result<Vec<MemoryEntry>, MemoryError> {- self.record(Call::plain("core.list"));- Ok(vec![])- }-- async fn namespaces(&self) -> Result<Vec<NamespaceSummary>, MemoryError> {- self.record(Call::plain("core.namespaces"));- Ok(self.namespace_summaries.lock().unwrap().clone())- }-}--#[async_trait]-impl MemoryRecall for RecordingProvider {- async fn recall(- &self,- query: &str,- _limit: usize,- _opts: &OwnedRecallOpts,- scope: Option<&SourceScope>,- ) -> Result<Vec<MemoryEntry>, MemoryError> {- self.record(Call {- method: "recall.recall".into(),- content: Some(query.to_string()),- taint: None,- scoped: Some(scope.is_some()),- });- Ok(self.recall_result.lock().unwrap().clone())- }-}--#[async_trait]-impl MemoryPortability for RecordingProvider {- async fn export_page(- &self,- _cursor: Option<&str>,- _limit: usize,- ) -> Result<ExportPage, MemoryError> {- self.record(Call::plain("portability.export_page"));- Ok(ExportPage::default())- }-- async fn import_records(- &self,- records: Vec<ExportRecord>,- ) -> Result<ImportOutcome, MemoryError> {- self.record(Call {- method: "portability.import_records".into(),- content: None,- taint: records.first().map(|r| r.taint),- scoped: None,- });- Ok(ImportOutcome::default())- }-}--#[async_trait]-impl MemoryIngest for RecordingProvider {- async fn ingest_document(&self, item: IngestItem) -> Result<IngestOutcome, MemoryError> {- self.record(Call {- method: "ingest.ingest_document".into(),- content: Some(item.content),- taint: Some(item.taint),- scoped: None,- });- Ok(IngestOutcome::default())- }-- async fn ingest_chat(&self, messages: Vec<IngestItem>) -> Result<IngestOutcome, MemoryError> {- self.record(Call {- method: "ingest.ingest_chat".into(),- content: messages.first().map(|m| m.content.clone()),- taint: messages.first().map(|m| m.taint),- scoped: None,- });- Ok(IngestOutcome::default())- }-}--#[async_trait]-impl MemoryDocuments for RecordingProvider {- async fn put_document(&self, input: NamespaceDocumentInput) -> Result<String, MemoryError> {- self.record(Call {- method: "documents.put_document".into(),- content: Some(input.content),- taint: Some(input.taint),- scoped: None,- });- Ok("doc".into())- }-- async fn get_document(- &self,- _namespace: &str,- _key: &str,- ) -> Result<Option<StoredMemoryDocument>, MemoryError> {- self.record(Call::plain("documents.get_document"));- Ok(None)- }-- async fn list_documents(- &self,- _namespace: Option<&str>,- ) -> Result<serde_json::Value, MemoryError> {- self.record(Call::plain("documents.list_documents"));- Ok(serde_json::json!({"documents": []}))- }-- async fn list_namespaces(&self) -> Result<Vec<String>, MemoryError> {- self.record(Call::plain("documents.list_namespaces"));- Ok(vec![])- }-- async fn delete_document(- &self,- _namespace: &str,- _document_id: &str,- ) -> Result<serde_json::Value, MemoryError> {- self.record(Call::plain("documents.delete_document"));- Ok(serde_json::json!({"deleted": false}))- }-- async fn clear_namespace(&self, _namespace: &str) -> Result<(), MemoryError> {- self.record(Call::plain("documents.clear_namespace"));- Ok(())- }-- async fn query_documents(- &self,- namespace: &str,- query: &str,- _limit: usize,- ) -> Result<NamespaceRetrievalContext, MemoryError> {- self.record(Call {- method: "documents.query_documents".into(),- content: Some(query.to_string()),- taint: None,- scoped: None,- });- Ok(NamespaceRetrievalContext {- namespace: namespace.to_string(),- query: Some(query.to_string()),- context_text: String::new(),- hits: vec![],- })- }-- async fn recall_documents(- &self,- namespace: &str,- _limit: usize,- ) -> Result<NamespaceRetrievalContext, MemoryError> {- self.record(Call::plain("documents.recall_documents"));- Ok(NamespaceRetrievalContext {- namespace: namespace.to_string(),- query: None,- context_text: String::new(),- hits: vec![],- })- }-}--#[async_trait]-impl MemoryTree for RecordingProvider {- async fn append(&self, request: IngestRequest) -> Result<(), MemoryError> {- self.record(Call {- method: "tree.append".into(),- content: Some(request.content),- taint: None,- scoped: None,- });- Ok(())- }-- async fn query_source(- &self,- _namespace: &str,- _source_id: &str,- _limit: usize,- scope: Option<&SourceScope>,- ) -> Result<Vec<Chunk>, MemoryError> {- self.record(Call {- method: "tree.query_source".into(),- // The scope's allow list, rendered so a test can assert which one- // arrived. Sorted because it comes from a `HashSet`.- content: scope.map(|s| {- let mut allow = s.allow.clone();- allow.sort();- allow.join(",")- }),- taint: None,- scoped: Some(scope.is_some()),- });- Ok(vec![])- }-- async fn drill_down(- &self,- _namespace: &str,- _node_id: &str,- ) -> Result<QueryResult, MemoryError> {- self.record(Call::plain("tree.drill_down"));- Err(MemoryError::NotFound("node".into()))- }-- async fn seal(&self, namespace: &str) -> Result<TreeStatus, MemoryError> {- self.record(Call::plain("tree.seal"));- Ok(tree_status(namespace))- }-- async fn cascade(&self, namespace: &str) -> Result<TreeStatus, MemoryError> {- self.record(Call::plain("tree.cascade"));- Ok(tree_status(namespace))- }-- /// Records the folded bodies as one blob, so a redaction test can assert on- /// what the driver's summariser would have been handed.- async fn summarise(- &self,- inputs: &[crate::memory::api::provider::content::SummaryInput],- _context: &crate::memory::api::provider::content::SummaryContext,- ) -> Result<crate::memory::api::provider::content::SummaryOutput, MemoryError> {- self.record(Call {- method: "tree.summarise".into(),- content: Some(- inputs- .iter()- .map(|input| input.content.clone())- .collect::<Vec<_>>()- .join("|"),- ),- taint: None,- scoped: None,- });- Ok(Default::default())- }-- async fn root_summaries_with_caps(- &self,- _per_namespace_cap: usize,- _total_cap: usize,- ) -> Result<Vec<crate::memory::api::provider::content::RootSummary>, MemoryError> {- self.record(Call::plain("tree.root_summaries_with_caps"));- Ok(Vec::new())- }-- // ── The runtime-tree and flavour doors ──────────────────────────────────- //- // Overridden for the same reason `summarise` and `root_summaries_with_caps`- // are: each is defaulted on the trait, so a `GuardedTree` that forgot to- // forward one still compiles and answers `Unsupported`. A driver that- // *succeeds* here is what makes `the_defaulted_doors_are_forwarded_rather_than_refused`- // able to tell the two apart.-- /// Records the buffered body, so a redaction test can assert what the- /// driver's buffer would have been handed — [`Self::append`]'s twin.- async fn runtime_buffer_write(- &self,- _namespace: &str,- content: &str,- _timestamp: chrono::DateTime<chrono::Utc>,- _metadata: Option<serde_json::Value>,- ) -> Result<String, MemoryError> {- self.record(Call {- method: "tree.runtime_buffer_write".into(),- content: Some(content.to_string()),- taint: None,- scoped: None,- });- Ok("/buffer/2026/01/01/00.md".to_string())- }-- async fn runtime_read_node(- &self,- _namespace: &str,- _node_id: &str,- ) -> Result<Option<crate::memory::api::tree::TreeNode>, MemoryError> {- self.record(Call::plain("tree.runtime_read_node"));- Ok(None)- }-- async fn runtime_read_children(- &self,- _namespace: &str,- _parent_id: &str,- ) -> Result<Vec<crate::memory::api::tree::TreeNode>, MemoryError> {- self.record(Call::plain("tree.runtime_read_children"));- Ok(Vec::new())- }-- async fn runtime_tree_status(&self, namespace: &str) -> Result<TreeStatus, MemoryError> {- self.record(Call::plain("tree.runtime_tree_status"));- Ok(tree_status(namespace))- }-- async fn runtime_summarize(- &self,- _namespace: &str,- _timestamp: chrono::DateTime<chrono::Utc>,- ) -> Result<Option<crate::memory::api::tree::TreeNode>, MemoryError> {- self.record(Call::plain("tree.runtime_summarize"));- Ok(None)- }-- async fn runtime_rebuild(&self, namespace: &str) -> Result<TreeStatus, MemoryError> {- self.record(Call::plain("tree.runtime_rebuild"));- Ok(tree_status(namespace))- }-- async fn flavour_profile(&self, _scope: &str) -> Result<Option<String>, MemoryError> {- self.record(Call::plain("tree.flavour_profile"));- Ok(None)- }-}--#[async_trait]-impl MemoryEntities for RecordingProvider {- async fn entities(- &self,- _namespace: &str,- _query: Option<&str>,- _limit: usize,- ) -> Result<Vec<EntityHit>, MemoryError> {- self.record(Call::plain("entities.entities"));- Ok(vec![])- }-- async fn entity_edges(- &self,- _namespace: &str,- _entity_id: &str,- _limit: usize,- ) -> Result<Vec<GraphRelationRecord>, MemoryError> {- self.record(Call::plain("entities.entity_edges"));- Ok(vec![])- }-- async fn touch_entities(- &self,- _namespace: &str,- _entity_ids: &[String],- ) -> Result<(), MemoryError> {- self.record(Call::plain("entities.touch_entities"));- Ok(())- }-}--#[async_trait]-impl MemoryGraph for RecordingProvider {- async fn kv_get(- &self,- _namespace: Option<&str>,- _key: &str,- ) -> Result<Option<MemoryKvRecord>, MemoryError> {- self.record(Call::plain("graph.kv_get"));- Ok(None)- }-- async fn kv_put(- &self,- _namespace: Option<&str>,- _key: &str,- value: serde_json::Value,- ) -> Result<(), MemoryError> {- self.record(Call {- method: "graph.kv_put".into(),- content: Some(value.to_string()),- taint: None,- scoped: None,- });- Ok(())- }-- async fn kv_delete(&self, _namespace: Option<&str>, _key: &str) -> Result<bool, MemoryError> {- self.record(Call::plain("graph.kv_delete"));- Ok(false)- }-- async fn kv_list(- &self,- _namespace: Option<&str>,- _prefix: Option<&str>,- _limit: usize,- ) -> Result<Vec<MemoryKvRecord>, MemoryError> {- self.record(Call::plain("graph.kv_list"));- Ok(vec![])- }-- async fn relations(- &self,- _namespace: Option<&str>,- _subject: Option<&str>,- _predicate: Option<&str>,- _limit: usize,- ) -> Result<Vec<GraphRelationRecord>, MemoryError> {- self.record(Call::plain("graph.relations"));- Ok(vec![])- }-- async fn put_relation(&self, _relation: GraphRelationRecord) -> Result<(), MemoryError> {- self.record(Call::plain("graph.put_relation"));- Ok(())- }-}--#[async_trait]-impl MemoryDiff for RecordingProvider {- async fn capture_snapshot(&self, _source_id: &str) -> Result<SnapshotRef, MemoryError> {- self.record(Call::plain("diff.capture_snapshot"));- Err(MemoryError::NotFound("source".into()))- }-- async fn snapshots(- &self,- _source_id: &str,- _limit: usize,- ) -> Result<Vec<SnapshotRef>, MemoryError> {- self.record(Call::plain("diff.snapshots"));- Ok(vec![])- }-- async fn diff(- &self,- _source_id: &str,- _from: Option<&str>,- _to: &str,- ) -> Result<DiffReport, MemoryError> {- self.record(Call::plain("diff.diff"));- Err(MemoryError::NotFound("snapshot".into()))- }-}--#[async_trait]-impl MemoryGoals for RecordingProvider {- async fn goals(&self) -> Result<GoalsDoc, MemoryError> {- self.record(Call::plain("goals.goals"));- Ok(GoalsDoc::default())- }-- async fn set_goals(&self, _goals: GoalsDoc) -> Result<(), MemoryError> {- self.record(Call::plain("goals.set_goals"));- Ok(())- }-}--#[async_trait]-impl MemoryToolMemory for RecordingProvider {- async fn tool_rules(&self, _tool_name: &str) -> Result<Vec<ToolMemoryRule>, MemoryError> {- self.record(Call::plain("tool_memory.tool_rules"));- Ok(vec![])- }-- async fn put_tool_rule(&self, _rule: ToolMemoryRule) -> Result<(), MemoryError> {- self.record(Call::plain("tool_memory.put_tool_rule"));- Ok(())- }-- async fn delete_tool_rule(- &self,- _tool_name: &str,- _rule_id: &str,- ) -> Result<bool, MemoryError> {- self.record(Call::plain("tool_memory.delete_tool_rule"));- Ok(false)- }-}diff --git a/crates/openhuman-core/src/memory/guard/test_support/fixtures.rs b/crates/openhuman-core/src/memory/guard/test_support/fixtures.rsdeleted file mode 100644index 10a3ef3a03..0000000000--- a/crates/openhuman-core/src/memory/guard/test_support/fixtures.rs+++ /dev/null@@ -1,290 +0,0 @@-//! `RecordingProvider`'s type, constructor, call log, and the guard/entity-//! fixtures the family tests build from.-//!-//! Split out of the original `test_support.rs` (see that module's doc-//! comment for why `RecordingProvider` implements every family rather than-//! relying on the null driver). The family trait implementations that answer-//! each call recorded here live in the sibling `*_impls` files under-//! [`super`].--use std::sync::{Arc, Mutex};--use crate::memory::api::provider::episodic::ConversationSegment;-use crate::memory::api::provider::episodic::EpisodicTurn;-use crate::memory::api::provider::retrieval::RetrievalResponse;-use crate::memory::api::provider::types::{ExportRecord, SourceScope};-use crate::memory::api::provider::MemoryProvider;-use crate::memory::api::types::{- MemoryCategory, MemoryEntry, MemoryTaint, NamespaceDocumentInput, NamespaceMemoryHit,- NamespaceSummary,-};--/// One call that reached the driver.-#[derive(Debug, Clone, PartialEq)]-pub struct Call {- pub method: String,- /// Content the driver was handed, when the method carries any.- pub content: Option<String>,- /// Provenance the driver was handed, when the method carries any.- pub taint: Option<MemoryTaint>,- /// Whether the method received a `Some(scope)`.- pub scoped: Option<bool>,-}--/// The scope's allow list rendered for assertions, sorted for determinism.-pub(super) fn rendered_scope(scope: Option<&SourceScope>) -> Option<String> {- scope.map(|s| {- let mut allow = s.allow.clone();- allow.sort();- allow.join(",")- })-}--impl Call {- pub(crate) fn plain(method: &str) -> Self {- Self {- method: method.into(),- content: None,- taint: None,- scoped: None,- }- }-}--/// A provider that records and answers with empties.-pub struct RecordingProvider {- pub(super) calls: Mutex<Vec<Call>>,- /// What `recall` returns, so budget tests can drive a known result set.- pub(super) recall_result: Mutex<Vec<MemoryEntry>>,- /// What `fast_retrieve` returns, so the auto-recall lane can be driven- /// through a real guard with known hits.- pub(super) fast_retrieve_result: Mutex<RetrievalResponse>,- /// What `recall_namespace_scored` returns, so the vector-floored recall- /// paths (Lane B, the contradiction check) can be driven with known scores.- pub(super) namespace_hits: Mutex<Vec<NamespaceMemoryHit>>,- /// What `namespaces` returns, so a namespace can look populated (Lane B- /// asks for the count before it pays for an embed) without a real store.- pub(super) namespace_summaries: Mutex<Vec<NamespaceSummary>>,- /// What `session_turns` returns, so the archivist's finalize path can be- /// driven past its empty-entries early return without an engine behind it.- pub(super) session_turns: Mutex<Vec<EpisodicTurn>>,- /// What `segments_pending_summary` returns, so the re-summarisation pass- /// (#6186) can be driven over a known queue.- pub(super) pending_segments: Mutex<Vec<ConversationSegment>>,-}--impl Default for RecordingProvider {- fn default() -> Self {- Self::new()- }-}--/// A [`GuardPolicy`](super::super::GuardPolicy) over an embedded driver with default-/// budgets — the shipped configuration.-pub fn embedded_policy() -> super::super::GuardPolicy {- super::super::GuardPolicy::new(- "recording",- crate::core::subsystem::DriverClass::Embedded,- crate::config::schema::MemoryHooksConfig::default(),- super::super::policy::TRUSTED,- )-}--/// A policy over an *external* driver. No such driver can bind today-/// (`binding::admit` refuses them), so this is the only way to reach the class-/// branches that land for real in M6.-pub fn external_policy(trust_state: &str) -> super::super::GuardPolicy {- super::super::GuardPolicy::new(- "supermemory",- crate::core::subsystem::DriverClass::External,- crate::config::schema::MemoryHooksConfig::default(),- trust_state,- )-}--/// An [`ExportRecord`] fixture.-pub fn export_record(taint: MemoryTaint) -> ExportRecord {- ExportRecord {- kind: "entry".into(),- id: "r1".into(),- namespace: Some("ns".into()),- taint,- payload: serde_json::Value::Null,- }-}--/// A guard over a fresh recording provider, plus a handle on that provider.-pub fn guarded(- policy: super::super::GuardPolicy,-) -> (Arc<RecordingProvider>, super::super::MemoryGuard) {- guarded_with(RecordingProvider::new(), policy)-}--/// As [`guarded`], over a caller-configured provider.-pub fn guarded_with(- provider: RecordingProvider,- policy: super::super::GuardPolicy,-) -> (Arc<RecordingProvider>, super::super::MemoryGuard) {- let provider = Arc::new(provider);- let guard = super::super::MemoryGuard::new(- Arc::clone(&provider) as Arc<dyn MemoryProvider>,- Arc::new(policy),- );- (provider, guard)-}--/// A [`MemoryEntry`] fixture.-pub fn entry(content: &str) -> MemoryEntry {- MemoryEntry {- id: "id".into(),- key: "key".into(),- content: content.into(),- namespace: Some("ns".into()),- category: MemoryCategory::Core,- timestamp: "2026-01-01T00:00:00Z".into(),- session_id: None,- score: None,- taint: MemoryTaint::Internal,- }-}--pub fn document(content: &str, taint: MemoryTaint) -> NamespaceDocumentInput {- NamespaceDocumentInput {- namespace: "ns".into(),- key: "k".into(),- title: "t".into(),- content: content.into(),- source_type: "chat".into(),- priority: "normal".into(),- tags: vec![],- metadata: serde_json::Value::Null,- category: "core".into(),- session_id: None,- document_id: None,- taint,- }-}--impl RecordingProvider {- /// A provider with an empty call log and every seeded answer at its- /// default — the shape most tests want before layering a `with_*` on top.- pub fn new() -> Self {- Self {- calls: Mutex::new(Vec::new()),- recall_result: Mutex::new(Vec::new()),- fast_retrieve_result: Mutex::new(RetrievalResponse::default()),- namespace_hits: Mutex::new(Vec::new()),- namespace_summaries: Mutex::new(Vec::new()),- session_turns: Mutex::new(Vec::new()),- pending_segments: Mutex::new(Vec::new()),- }- }-- /// Seed what `recall` answers, so a budget test can drive a known set.- pub fn with_recall_result(self, entries: Vec<MemoryEntry>) -> Self {- *self.recall_result.lock().unwrap() = entries;- self- }-- /// Seed what `fast_retrieve` answers, so the auto-recall lane can run- /// through a real guard with known hits.- pub fn with_fast_retrieve_result(self, response: RetrievalResponse) -> Self {- *self.fast_retrieve_result.lock().unwrap() = response;- self- }-- /// Seed what `recall_namespace_scored` answers, so the vector-floored- /// paths can be driven with known scores.- pub fn with_namespace_hits(self, hits: Vec<NamespaceMemoryHit>) -> Self {- *self.namespace_hits.lock().unwrap() = hits;- self- }-- /// Seed what `namespaces` answers, so a namespace can look populated- /// without a real store behind it.- pub fn with_namespace_summaries(self, summaries: Vec<NamespaceSummary>) -> Self {- *self.namespace_summaries.lock().unwrap() = summaries;- self- }-- /// Seed what `session_turns` answers. Without this the archivist's- /// finalize path stops at its empty-entries early return and never- /// reaches the recap it is being tested for.- pub fn with_session_turns(self, turns: Vec<EpisodicTurn>) -> Self {- *self.session_turns.lock().unwrap() = turns;- self- }-- /// Seed the re-summarisation queue (#6186). The default is empty, so a- /// test that does not set this drives the pass over nothing — which is- /// the state a healthy store is in.- pub fn with_pending_segments(self, segments: Vec<ConversationSegment>) -> Self {- *self.pending_segments.lock().unwrap() = segments;- self- }-- /// Append one call to the log. Every family impl funnels through this.- pub(super) fn record(&self, call: Call) {- self.calls.lock().unwrap().push(call);- }-- /// Every call the driver saw, in order.- pub fn calls(&self) -> Vec<Call> {- self.calls.lock().unwrap().clone()- }-- /// How many calls reached the driver — for tests that only care that a- /// path was or was not taken.- pub fn call_count(&self) -> usize {- self.calls.lock().unwrap().len()- }-- /// The single recorded call, panicking when there is not exactly one.- pub fn only_call(&self) -> Call {- let calls = self.calls();- assert_eq!(- calls.len(),- 1,- "expected exactly one driver call: {calls:?}"- );- calls.into_iter().next().unwrap()- }-}--pub fn namespace_summary(namespace: &str, count: usize) -> NamespaceSummary {- NamespaceSummary {- namespace: namespace.into(),- count,- last_updated: None,- }-}--/// A [`NamespaceMemoryHit`] with only the vector component set — the signal the-/// vector-floored recall paths (Lane B, the contradiction check) filter on.-pub fn namespace_hit(- namespace: &str,- key: &str,- content: &str,- vector_similarity: f64,-) -> NamespaceMemoryHit {- NamespaceMemoryHit {- id: format!("{namespace}/{key}"),- kind: crate::memory::api::types::MemoryItemKind::Kv,- namespace: namespace.into(),- key: key.into(),- title: None,- content: content.into(),- category: "core".into(),- source_type: None,- updated_at: 0.0,- score: vector_similarity,- score_breakdown: crate::memory::api::types::RetrievalScoreBreakdown {- vector_similarity,- ..Default::default()- },- document_id: None,- chunk_id: None,- supporting_relations: Vec::new(),- taint: MemoryTaint::default(),- }-}diff --git a/crates/openhuman-core/src/memory/guard/test_support/provider_and_sync_impls.rs b/crates/openhuman-core/src/memory/guard/test_support/provider_and_sync_impls.rsdeleted file mode 100644index a56d054688..0000000000--- a/crates/openhuman-core/src/memory/guard/test_support/provider_and_sync_impls.rs+++ /dev/null@@ -1,260 +0,0 @@-//! `RecordingProvider`'s `SourceSink`, `Maintenance`, `SourceSync`, and-//! `CodingSessions` family implementations, plus the top-level-//! `MemoryProvider` impl that advertises every family through its `as_*`-//! accessors.-//!-//! Split out of the original `test_support.rs`; see [`super::fixtures`] for-//! `RecordingProvider`'s type and constructors. The read-heavy families-//! (`Retrieval`, `Episodic`, `Profile`, ...) and the typed-ingestion round-//! live in [`super::retrieval_and_ingest_impls`].--use crate::memory::api::capabilities::Capabilities;-use crate::memory::api::error::MemoryError;-use crate::memory::api::health::MemoryHealth;-use crate::memory::api::provider::operations::{- MemoryAnswer, MemoryConversationIngest, MemoryDocumentIngest, MemoryEventIngest,- MemoryLearningIngest,-};-use crate::memory::api::provider::sessions::{- CodingSessionIngestReport, CodingSessionIngestRequest, CodingSessionSource,-};-use crate::memory::api::provider::sync::{- RawArchiveCoverage, RawRebuildOutcome, SourceSyncState, SourceSyncStatus, SyncAuditEntry,- SyncRunOutcome,-};-use crate::memory::api::provider::types::{IngestOutcome, MaintenanceReport, SourceItem};-use crate::memory::api::provider::{- MemoryChunks, MemoryCodingSessions, MemoryDiff, MemoryDocuments, MemoryEntities,- MemoryEpisodic, MemoryGoals, MemoryGraph, MemoryIngest, MemoryMaintenance, MemoryPeople,- MemoryProfile, MemoryProvider, MemoryRetrieval, MemoryScoring, MemorySourceSink,- MemorySourceSync, MemoryToolMemory, MemoryTree,-};-use crate::memory::api::types::MemoryTaint;-use async_trait::async_trait;--use super::fixtures::{Call, RecordingProvider};--#[async_trait]-impl MemorySourceSink for RecordingProvider {- async fn accept_source_items(- &self,- _source_id: &str,- _source_kind: &str,- items: Vec<SourceItem>,- taint: MemoryTaint,- ) -> Result<IngestOutcome, MemoryError> {- self.record(Call {- method: "sources.accept_source_items".into(),- content: items.first().map(|i| i.content.clone()),- taint: Some(taint),- scoped: None,- });- Ok(IngestOutcome::default())- }-- async fn forget_source(&self, _source_id: &str) -> Result<u64, MemoryError> {- self.record(Call::plain("sources.forget_source"));- Ok(0)- }-}--#[async_trait]-impl MemoryMaintenance for RecordingProvider {- async fn reembed(&self) -> Result<MaintenanceReport, MemoryError> {- self.record(Call::plain("maintenance.reembed"));- Ok(MaintenanceReport::default())- }-- async fn compact(&self) -> Result<MaintenanceReport, MemoryError> {- self.record(Call::plain("maintenance.compact"));- Ok(MaintenanceReport::default())- }-- async fn consolidate(&self) -> Result<MaintenanceReport, MemoryError> {- self.record(Call::plain("maintenance.consolidate"));- Ok(MaintenanceReport::default())- }-- async fn doctor(&self) -> Result<MaintenanceReport, MemoryError> {- self.record(Call::plain("maintenance.doctor"));- Ok(MaintenanceReport::default())- }-- async fn diagnose(- &self,- ) -> Result<crate::memory::api::provider::diagnosis::Diagnosis, MemoryError> {- self.record(Call::plain("maintenance.diagnose"));- Ok(Default::default())- }-- async fn degraded_state(- &self,- ) -> Result<crate::memory::api::provider::diagnosis::DegradedCapabilities, MemoryError> {- self.record(Call::plain("maintenance.degraded_state"));- Ok(Default::default())- }-}--#[async_trait]-impl MemoryProvider for RecordingProvider {- fn driver_id(&self) -> &str {- "recording"- }-- fn capabilities(&self) -> Capabilities {- Capabilities::all()- }-- async fn health(&self) -> MemoryHealth {- MemoryHealth::Ready- }-- fn as_ingest(&self) -> Option<&dyn MemoryIngest> {- Some(self)- }- fn as_documents(&self) -> Option<&dyn MemoryDocuments> {- Some(self)- }- fn as_tree(&self) -> Option<&dyn MemoryTree> {- Some(self)- }- fn as_entities(&self) -> Option<&dyn MemoryEntities> {- Some(self)- }- fn as_graph(&self) -> Option<&dyn MemoryGraph> {- Some(self)- }- fn as_diff(&self) -> Option<&dyn MemoryDiff> {- Some(self)- }- fn as_goals(&self) -> Option<&dyn MemoryGoals> {- Some(self)- }- fn as_tool_memory(&self) -> Option<&dyn MemoryToolMemory> {- Some(self)- }- fn as_sources(&self) -> Option<&dyn MemorySourceSink> {- Some(self)- }- fn as_maintenance(&self) -> Option<&dyn MemoryMaintenance> {- Some(self)- }- fn as_people(&self) -> Option<&dyn MemoryPeople> {- Some(self)- }- fn as_chunks(&self) -> Option<&dyn MemoryChunks> {- Some(self)- }- fn as_retrieval(&self) -> Option<&dyn MemoryRetrieval> {- Some(self)- }- fn as_profile(&self) -> Option<&dyn MemoryProfile> {- Some(self)- }- 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)- }- fn as_scoring(&self) -> Option<&dyn MemoryScoring> {- Some(self)- }- fn as_document_ingest(&self) -> Option<&dyn MemoryDocumentIngest> {- Some(self)- }- fn as_conversation_ingest(&self) -> Option<&dyn MemoryConversationIngest> {- Some(self)- }- fn as_learning_ingest(&self) -> Option<&dyn MemoryLearningIngest> {- Some(self)- }- fn as_event_ingest(&self) -> Option<&dyn MemoryEventIngest> {- Some(self)- }- fn as_answer(&self) -> Option<&dyn MemoryAnswer> {- 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())- }-}diff --git a/crates/openhuman-core/src/memory/guard/test_support/retrieval_and_ingest_impls.rs b/crates/openhuman-core/src/memory/guard/test_support/retrieval_and_ingest_impls.rsdeleted file mode 100644index 15f77c0b0b..0000000000--- a/crates/openhuman-core/src/memory/guard/test_support/retrieval_and_ingest_impls.rs+++ /dev/null@@ -1,566 +0,0 @@-//! `RecordingProvider`'s `Episodic`, `Profile`, `Chunks`, `Retrieval`,-//! `People`, `Scoring`, `Answer`, and typed-ingestion (`DocumentIngest`,-//! `ConversationIngest`, `LearningIngest`, `EventIngest`) family-//! implementations — the read/query half plus the v1.13.7 ingestion round.-//!-//! Split out of the original `test_support.rs`; see [`super::fixtures`] for-//! `RecordingProvider`'s type and constructors. The write/tree/graph-//! families live in [`super::provider_and_sync_impls`] and-//! [`super::core_and_docs_impls`].--use crate::memory::api::chunks::Chunk;-use crate::memory::api::error::MemoryError;-use crate::memory::api::provider::chunks::{ChunkDetail, ChunkEmbedding, ChunkQuery};-use crate::memory::api::provider::operations::{- MemoryAnswer, MemoryConversationIngest, MemoryDocumentIngest, MemoryEventIngest,- MemoryLearningIngest,-};-use crate::memory::api::provider::people::{- AddressBookSeedOutcome, PersonHandle, PersonInteraction, PersonRecord, PersonScore,- RankedPerson, ResolvedPerson,-};-use crate::memory::api::provider::profile::{FacetType, ProfileFacet, UserState};-use crate::memory::api::provider::retrieval::{- CoverWindowQuery, EntityMatch, FastRetrieveQuery, RetrievalHit, RetrievalResponse,- SourceRetrievalQuery,-};-use crate::memory::api::provider::types::SourceScope;-use crate::memory::api::provider::types::{IngestItem, IngestOutcome};-use crate::memory::api::provider::{- EpisodicEvent, MemoryChunks, MemoryEpisodic, MemoryPeople, MemoryProfile, MemoryRetrieval,- MemoryScoring,-};-use crate::memory::api::types::NamespaceMemoryHit;-use async_trait::async_trait;--use super::fixtures::{rendered_scope, Call, RecordingProvider};--#[async_trait]-impl MemoryEpisodic for RecordingProvider {- async fn insert_turn(- &self,- turn: &crate::memory::api::provider::episodic::EpisodicTurn,- ) -> Result<i64, MemoryError> {- // Records the turn text, so a guard that failed to redact one would be- // visible here rather than only in a live store.- self.record(Call {- method: "episodic.insert_turn".into(),- content: Some(turn.content.clone()),- taint: None,- scoped: None,- });- Ok(1)- }-- async fn session_turns(- &self,- _session_id: &str,- ) -> Result<Vec<crate::memory::api::provider::episodic::EpisodicTurn>, MemoryError> {- self.record(Call::plain("episodic.session_turns"));- Ok(self.session_turns.lock().unwrap().clone())- }-- async fn open_segment(- &self,- _session_id: &str,- ) -> Result<Option<crate::memory::api::provider::episodic::ConversationSegment>, MemoryError>- {- self.record(Call::plain("episodic.open_segment"));- Ok(None)- }-- async fn segments_pending_summary(- &self,- limit: u32,- ) -> Result<Vec<crate::memory::api::provider::episodic::ConversationSegment>, MemoryError> {- self.record(Call::plain("episodic.segments_pending_summary"));- // Honour `limit` — a fake that ignored it would let a test drive more- // segments than the caller asked for and hide a bounded-recovery bug.- Ok(self- .pending_segments- .lock()- .unwrap()- .iter()- .take(limit as usize)- .cloned()- .collect())- }-- async fn create_segment(- &self,- _segment_id: &str,- _session_id: &str,- _namespace: &str,- _start_episodic_id: i64,- _start_seq: Option<u32>,- _start_timestamp: f64,- _now: f64,- ) -> Result<(), MemoryError> {- self.record(Call::plain("episodic.create_segment"));- Ok(())- }-- async fn append_turn(- &self,- _segment_id: &str,- _episodic_id: i64,- _seq: Option<u32>,- _timestamp: f64,- _now: f64,- ) -> Result<(), MemoryError> {- self.record(Call::plain("episodic.append_turn"));- Ok(())- }-- async fn close_segment(&self, _segment_id: &str, _now: f64) -> Result<(), MemoryError> {- self.record(Call::plain("episodic.close_segment"));- Ok(())- }-- async fn insert_event(&self, event: &EpisodicEvent) -> Result<(), MemoryError> {- // Records the event text for the same reason `insert_turn` does: a guard- // that stopped redacting one would otherwise be invisible to every test,- // and the redaction on this path has already been missing once.- self.record(Call {- method: "episodic.insert_event".into(),- content: Some(event.content.clone()),- taint: None,- scoped: None,- });- Ok(())- }-- async fn set_segment_summary(- &self,- _segment_id: &str,- summary: &str,- _now: f64,- ) -> Result<(), MemoryError> {- self.record(Call {- method: "episodic.set_segment_summary".into(),- content: Some(summary.to_string()),- taint: None,- scoped: None,- });- Ok(())- }-- async fn upsert_segment_embedding(- &self,- _segment_id: &str,- _model_signature: &str,- _embedding: &[f32],- _created_at: f64,- ) -> Result<(), MemoryError> {- self.record(Call::plain("episodic.upsert_segment_embedding"));- Ok(())- }-}-#[async_trait]-impl MemoryProfile for RecordingProvider {- async fn list_active_facets(&self) -> Result<Vec<ProfileFacet>, MemoryError> {- self.record(Call::plain("profile.list_active_facets"));- Ok(vec![])- }- async fn list_all_facets(&self) -> Result<Vec<ProfileFacet>, MemoryError> {- self.record(Call::plain("profile.list_all_facets"));- Ok(vec![])- }- async fn get_facet(&self, _key: &str) -> Result<Option<ProfileFacet>, MemoryError> {- self.record(Call::plain("profile.get_facet"));- Ok(None)- }- async fn facets_by_type(- &self,- _facet_type: FacetType,- ) -> Result<Vec<ProfileFacet>, MemoryError> {- self.record(Call::plain("profile.facets_by_type"));- Ok(vec![])- }- async fn upsert_facet(&self, _facet: &ProfileFacet) -> Result<(), MemoryError> {- self.record(Call::plain("profile.upsert_facet"));- Ok(())- }- async fn upsert_provider_facet(- &self,- _facet_id: &str,- _facet_type: FacetType,- _key: &str,- _value: &str,- _confidence: f64,- _segment_id: Option<&str>,- _observed_at: f64,- ) -> Result<(), MemoryError> {- self.record(Call::plain("profile.upsert_provider_facet"));- Ok(())- }- async fn set_facet_user_state(- &self,- _key: &str,- _user_state: UserState,- ) -> Result<bool, MemoryError> {- self.record(Call::plain("profile.set_facet_user_state"));- Ok(false)- }- async fn delete_facet(&self, _key: &str) -> Result<bool, MemoryError> {- self.record(Call::plain("profile.delete_facet"));- Ok(false)- }- async fn delete_facet_by_id(&self, _facet_id: &str) -> Result<bool, MemoryError> {- self.record(Call::plain("profile.delete_facet_by_id"));- Ok(false)- }- async fn drop_facets_below(&self, _threshold: f64) -> Result<usize, MemoryError> {- self.record(Call::plain("profile.drop_facets_below"));- Ok(0)- }- async fn workflow_identity_matches(&self, _pattern: &str, _value: &str) -> bool {- self.record(Call::plain("profile.workflow_identity_matches"));- false- }-}--#[async_trait]-impl MemoryChunks for RecordingProvider {- async fn list_chunks(- &self,- _query: &ChunkQuery,- scope: Option<&SourceScope>,- ) -> Result<Vec<Chunk>, MemoryError> {- self.record(Call {- method: "chunks.list_chunks".into(),- content: rendered_scope(scope),- taint: None,- scoped: Some(scope.is_some()),- });- Ok(vec![])- }-- async fn get_chunk(&self, _chunk_id: &str) -> Result<Option<Chunk>, MemoryError> {- self.record(Call::plain("chunks.get_chunk"));- Ok(None)- }-- async fn chunk_detail(&self, _chunk_id: &str) -> Result<Option<ChunkDetail>, MemoryError> {- self.record(Call::plain("chunks.chunk_detail"));- Ok(None)- }-- async fn storage_kinds(&self) -> Result<Vec<String>, MemoryError> {- self.record(Call::plain("chunks.storage_kinds"));- Ok(vec![])- }-- async fn chunk_embeddings(- &self,- _chunk_ids: &[String],- _model_signature: &str,- ) -> Result<Vec<ChunkEmbedding>, MemoryError> {- self.record(Call::plain("chunks.chunk_embeddings"));- Ok(vec![])- }-- async fn chunk_score(- &self,- _chunk_id: &str,- ) -> Result<Option<crate::memory::api::provider::chunks::ChunkScore>, MemoryError> {- self.record(Call::plain("chunks.chunk_score"));- Ok(None)- }-- async fn source_ingest_status(- &self,- _source_prefixes: &[crate::memory::api::provider::chunks::SourceIngestQuery],- ) -> Result<Vec<crate::memory::api::provider::chunks::SourceIngestStatus>, MemoryError> {- self.record(Call::plain("chunks.source_ingest_status"));- Ok(vec![])- }-}--#[async_trait]-impl MemoryRetrieval for RecordingProvider {- async fn fast_retrieve(- &self,- _query: &str,- _options: FastRetrieveQuery,- scope: Option<&SourceScope>,- ) -> Result<RetrievalResponse, MemoryError> {- self.record(Call {- method: "retrieval.fast_retrieve".into(),- content: rendered_scope(scope),- taint: None,- scoped: Some(scope.is_some()),- });- Ok(self.fast_retrieve_result.lock().unwrap().clone())- }-- async fn cover_window(- &self,- _window: &CoverWindowQuery,- scope: Option<&SourceScope>,- ) -> Result<RetrievalResponse, MemoryError> {- self.record(Call {- method: "retrieval.cover_window".into(),- content: rendered_scope(scope),- taint: None,- scoped: Some(scope.is_some()),- });- Ok(RetrievalResponse::default())- }-- async fn retrieve_source(- &self,- _query: &SourceRetrievalQuery,- scope: Option<&SourceScope>,- ) -> Result<RetrievalResponse, MemoryError> {- self.record(Call {- method: "retrieval.retrieve_source".into(),- content: rendered_scope(scope),- taint: None,- scoped: Some(scope.is_some()),- });- Ok(RetrievalResponse::default())- }-- async fn retrieve_children(- &self,- _node_id: &str,- _max_depth: u32,- _query: Option<&str>,- _limit: Option<usize>,- scope: Option<&SourceScope>,- ) -> Result<Vec<RetrievalHit>, MemoryError> {- self.record(Call {- method: "retrieval.retrieve_children".into(),- content: rendered_scope(scope),- taint: None,- scoped: Some(scope.is_some()),- });- Ok(vec![])- }-- async fn retrieve_leaves(- &self,- _chunk_ids: &[String],- scope: Option<&SourceScope>,- ) -> Result<Vec<RetrievalHit>, MemoryError> {- self.record(Call {- method: "retrieval.retrieve_leaves".into(),- content: rendered_scope(scope),- taint: None,- scoped: Some(scope.is_some()),- });- Ok(vec![])- }-- async fn recall_namespace_scored(- &self,- namespace: &str,- _query: &str,- limit: usize,- _exclude_session_id: Option<&str>,- ) -> Result<Vec<NamespaceMemoryHit>, MemoryError> {- // Honours the two request parameters a caller can get wrong — the- // namespace it asks for and the page it accepts — and records them,- // so a test can assert both rather than only the content it got.- self.record(Call {- method: "retrieval.recall_namespace_scored".into(),- content: Some(format!("namespace={namespace} limit={limit}")),- taint: None,- scoped: None,- });- Ok(self- .namespace_hits- .lock()- .unwrap()- .iter()- .filter(|hit| hit.namespace == namespace)- .take(limit)- .cloned()- .collect())- }-- async fn recall_namespace_recent(- &self,- _namespace: &str,- _limit: usize,- ) -> Result<Vec<NamespaceMemoryHit>, MemoryError> {- self.record(Call::plain("retrieval.recall_namespace_recent"));- Ok(vec![])- }-- async fn search_entities(- &self,- _query: &str,- _kinds: Option<&[String]>,- _limit: usize,- ) -> Result<Vec<EntityMatch>, MemoryError> {- self.record(Call::plain("retrieval.search_entities"));- Ok(vec![])- }-}--#[async_trait]-impl MemoryPeople for RecordingProvider {- async fn list_people(&self, _limit: Option<usize>) -> Result<Vec<RankedPerson>, MemoryError> {- self.record(Call::plain("people.list_people"));- Ok(vec![])- }-- async fn get_person(&self, _person_id: &str) -> Result<Option<PersonRecord>, MemoryError> {- self.record(Call::plain("people.get_person"));- Ok(None)- }-- async fn resolve_handle(- &self,- _handle: &PersonHandle,- _create_if_missing: bool,- ) -> Result<Option<ResolvedPerson>, MemoryError> {- self.record(Call::plain("people.resolve_handle"));- Ok(None)- }-- async fn add_handle_alias(- &self,- _person_id: &str,- _handle: &PersonHandle,- ) -> Result<(), MemoryError> {- self.record(Call::plain("people.add_handle_alias"));- Ok(())- }-- async fn score_person(&self, _person_id: &str) -> Result<Option<PersonScore>, MemoryError> {- self.record(Call::plain("people.score_person"));- Ok(None)- }-- async fn record_interaction(- &self,- _interaction: &PersonInteraction,- ) -> Result<(), MemoryError> {- self.record(Call::plain("people.record_interaction"));- Ok(())- }-- async fn seed_from_address_book(&self) -> Result<AddressBookSeedOutcome, MemoryError> {- self.record(Call::plain("people.seed_from_address_book"));- Ok(AddressBookSeedOutcome::default())- }-}--#[async_trait]-impl MemoryScoring for RecordingProvider {- async fn extract_entities(&self, query: &str) -> Result<Vec<String>, MemoryError> {- self.record(Call {- method: "scoring.extract_entities".into(),- content: Some(query.to_string()),- taint: None,- scoped: None,- });- Ok(Vec::new())- }-- async fn embed_text(&self, text: &str) -> Result<Vec<f32>, MemoryError> {- self.record(Call {- method: "scoring.embed_text".into(),- content: Some(text.to_string()),- taint: None,- scoped: None,- });- Ok(Vec::new())- }-- async fn embedder_slug(&self) -> Result<String, MemoryError> {- self.record(Call::plain("scoring.embedder_slug"));- Ok(String::new())- }-}--// ── The v1.13.7 typed-ingestion round + Answer ──────────────────────────────-// Same contract as every family above: `capabilities()` answers all(), so the-// audit demands a live accessor and a recording impl for each.--#[async_trait]-impl MemoryDocumentIngest for RecordingProvider {- async fn ingest_document(&self, document: IngestItem) -> Result<IngestOutcome, MemoryError> {- self.record(Call {- method: "document_ingest.ingest_document".into(),- content: Some(document.content),- taint: Some(document.taint),- scoped: None,- });- Ok(IngestOutcome::default())- }-}--#[async_trait]-impl MemoryConversationIngest for RecordingProvider {- async fn ingest_conversation(- &self,- messages: Vec<IngestItem>,- ) -> Result<IngestOutcome, MemoryError> {- for message in messages {- self.record(Call {- method: "conversation_ingest.ingest_conversation".into(),- content: Some(message.content),- taint: Some(message.taint),- scoped: None,- });- }- Ok(IngestOutcome::default())- }-}--#[async_trait]-impl MemoryLearningIngest for RecordingProvider {- async fn ingest_learning(- &self,- _learning: tinymemory_api::learning::LearningCandidate,- ) -> Result<IngestOutcome, MemoryError> {- self.record(Call {- method: "learning_ingest.ingest_learning".into(),- content: None,- taint: None,- scoped: None,- });- Ok(IngestOutcome::default())- }-}--#[async_trait]-impl MemoryEventIngest for RecordingProvider {- async fn ingest_event(- &self,- _event: crate::memory::api::provider::operations::RawMemoryEvent,- ) -> Result<IngestOutcome, MemoryError> {- self.record(Call {- method: "event_ingest.ingest_event".into(),- content: None,- taint: None,- scoped: None,- });- Ok(IngestOutcome::default())- }-}--#[async_trait]-impl MemoryAnswer for RecordingProvider {- async fn answer(- &self,- _request: crate::memory::api::provider::operations::AnswerRequest,- ) -> Result<crate::memory::api::provider::operations::AnswerResponse, MemoryError> {- self.record(Call {- method: "answer.answer".into(),- content: None,- taint: None,- scoped: None,- });- Ok(crate::memory::api::provider::operations::AnswerResponse {- answer: String::new(),- model: None,- citations: Vec::new(),- steps: Vec::new(),- })- }-}