From 610e953ecdd87f2233b30fa9f4eefa904af36892 Mon Sep 17 00:00:00 2001 From: Tang Bohao Date: Thu, 26 Nov 2026 08:25:52 +0800 Subject: [PATCH 01/22] Add the Mind handle and its registry resolution (mind-facade T1) - mindcore_runtime::Mind: open is the one minds::get call, the registry refusal passes through - carrier_entry_id; no grant cached, no status acted on - tests: foreign Mind refuses NotFound, frozen Mind opens --- crates/mindcore-runtime/src/lib.rs | 5 +- crates/mindcore-runtime/src/mind.rs | 55 ++++++++++++ crates/mindcore-runtime/tests/mind.rs | 121 ++++++++++++++++++++++++++ 3 files changed, 180 insertions(+), 1 deletion(-) create mode 100644 crates/mindcore-runtime/src/mind.rs create mode 100644 crates/mindcore-runtime/tests/mind.rs diff --git a/crates/mindcore-runtime/src/lib.rs b/crates/mindcore-runtime/src/lib.rs index 2477e4e..8d2594e 100644 --- a/crates/mindcore-runtime/src/lib.rs +++ b/crates/mindcore-runtime/src/lib.rs @@ -8,10 +8,12 @@ //! registrations, never from a host-supplied capability string. //! //! The crate is also the library's entry crate: [`minds`] holds the in-process entry points -//! `create`, `list` and `get` a host calls on its `MindStore`. +//! `create`, `list` and `get` a host calls on its `MindStore`, and [`mind`] holds the `Mind` +//! handle a caller opens over one Mind. mod adoption; mod history_dedup; +pub mod mind; pub mod minds; pub mod tools; @@ -45,6 +47,7 @@ use sqlx::SqlitePool; use adoption::AdoptionService; use history_dedup::SqliteHistoryDedupStore; +pub use mind::Mind; pub use tools::MindProviders; use tools::WorkflowTools; diff --git a/crates/mindcore-runtime/src/mind.rs b/crates/mindcore-runtime/src/mind.rs new file mode 100644 index 0000000..d9d84e5 --- /dev/null +++ b/crates/mindcore-runtime/src/mind.rs @@ -0,0 +1,55 @@ +//! The Mind handle: the in-process facade over one Mind. `open` is one registry read — +//! `minds::get` under the caller's live grants — and the registry's own refusal answers as it +//! is. The handle keeps the row that read answers and nothing about grants: it caches no +//! grant and acts on no status from the row, so a frozen Mind opens and every later operation +//! re-reads the live state on its own transaction. + +use mindcore_base::boundary::CallerId; +use mindcore_base::ids::MindId; +use mindcore_sqlite::minds::Mind as MindRow; +use mindcore_sqlite::MindStore; +use spoke_operations::SpokeResult; +use sqlx::SqlitePool; + +/// A caller's handle to one Mind: the pool, the caller and the row `minds::get` answered at +/// open. +/// +/// The handle is not a grant — it confers no access beyond what the caller's live grants admit +/// on every operation — and its row is a snapshot: the status it carries is the one at open, +/// never re-read here. +pub struct Mind { + // Read by the memory, knowledge and cognition operations of later tasks; `open` itself + // never acts on them. + #[allow(dead_code)] + pool: SqlitePool, + #[allow(dead_code)] + caller: CallerId, + row: MindRow, +} + +impl Mind { + /// Open the Mind `mind_id` for `caller`: one call to `minds::get` under the caller's live + /// grants. A Mind the caller cannot see answers the registry's own `NotFound`; a frozen + /// Mind opens. + pub async fn open(store: &MindStore, caller: &CallerId, mind_id: &MindId) -> SpokeResult { + match crate::minds::get(store, caller, mind_id).await { + SpokeResult::Ok(row) => SpokeResult::Ok(Mind { + pool: store.pool(), + caller: caller.clone(), + row, + }), + SpokeResult::Reject(reject) => SpokeResult::Reject(reject), + } + } + + /// The entry in the Mind's collection that holds its current judgment, as the row named it + /// at open. + pub fn carrier_entry_id(&self) -> &str { + &self.row.carrier_entry_id + } + + /// The registry row `open` resolved, as it was at open. + pub fn row(&self) -> &MindRow { + &self.row + } +} diff --git a/crates/mindcore-runtime/tests/mind.rs b/crates/mindcore-runtime/tests/mind.rs new file mode 100644 index 0000000..f1b8009 --- /dev/null +++ b/crates/mindcore-runtime/tests/mind.rs @@ -0,0 +1,121 @@ +//! The Mind handle `mindcore_runtime::Mind`: `open` through the registry under the caller's +//! live grants, the registry's own `NotFound` for a Mind the caller cannot see, and a frozen +//! Mind opening because the handle acts on no status from the row. + +use mindcore_base::boundary::CallerId; +use mindcore_base::ids::{MindId, SpaceId}; +use mindcore_base::ir::MemoryRepository; +use mindcore_runtime::minds::{self, CreateMind}; +use mindcore_runtime::Mind; +use mindcore_sqlite::{MindStore, SqliteMemoryRepository}; +use serde_json::Number; +use spoke_operations::{SpokeRejectCode, SpokeResult}; +use tempfile::TempDir; + +const OWNER: &str = "caller_wren"; + +fn request(owner: &str) -> CreateMind { + CreateMind { + mind_id: None, + display_name: Some("Wren".to_string()), + owner: CallerId::new(owner), + } +} + +fn ok(result: SpokeResult) -> T { + match result { + SpokeResult::Ok(value) => value, + SpokeResult::Reject(reject) => panic!("expected success, got {reject:?}"), + } +} + +fn reject_code(result: SpokeResult) -> SpokeRejectCode { + match result { + SpokeResult::Reject(reject) => reject.code, + SpokeResult::Ok(_) => panic!("expected a refusal"), + } +} + +async fn fixture() -> (TempDir, MindStore) { + let dir = TempDir::new().expect("temporary directory"); + let store = MindStore::open(&dir.path().join("minds.db")) + .await + .expect("open store"); + (dir, store) +} + +async fn freeze_space(store: &MindStore, space_id: &str) { + let repo = SqliteMemoryRepository; + let mut tx = store.pool().begin().await.expect("begin"); + let mut space = repo + .space(&mut tx, &SpaceId::new(space_id)) + .await + .expect("read space") + .expect("the space row exists"); + let observed = space.revision.clone(); + space.status = "frozen".to_string(); + space.revision = Number::from(space.revision.as_i64().unwrap_or(0) + 1); + assert!( + repo.update_space(&mut tx, &space, &observed) + .await + .expect("freeze the space"), + "the freeze applies" + ); + tx.commit().await.expect("commit"); +} + +#[tokio::test] +async fn open_returns_the_handle_of_the_mind_the_caller_may_see() { + let (_dir, store) = fixture().await; + let owner = CallerId::new(OWNER); + let created = ok(minds::create(&store, &request(OWNER)).await); + + let handle = ok(Mind::open(&store, &owner, &created.id).await); + assert_eq!(handle.row(), &created, "the handle keeps the row open read"); + assert_eq!( + handle.carrier_entry_id(), + created.carrier_entry_id, + "the carrier the row names" + ); + assert!( + !handle.carrier_entry_id().is_empty(), + "a carrier coordinate, never `ke_carrier` re-derived here" + ); +} + +#[tokio::test] +async fn a_foreign_mind_refuses_the_registry_not_found() { + let (_dir, store) = fixture().await; + let created = ok(minds::create(&store, &request(OWNER)).await); + + let outsider = CallerId::new("caller_else"); + assert_eq!( + reject_code(Mind::open(&store, &outsider, &created.id).await), + SpokeRejectCode::NotFound, + "a Mind the caller cannot see answers the registry's own refusal" + ); + + let owner = CallerId::new(OWNER); + let never = MindId::new("spc_never_created"); + assert_eq!( + reject_code(Mind::open(&store, &owner, &never).await), + SpokeRejectCode::NotFound + ); +} + +#[tokio::test] +async fn a_frozen_mind_opens_with_no_status_acted_on() { + let (_dir, store) = fixture().await; + let owner = CallerId::new(OWNER); + let created = ok(minds::create(&store, &request(OWNER)).await); + + freeze_space(&store, created.id.as_str()).await; + + let handle = ok(Mind::open(&store, &owner, &created.id).await); + assert_eq!( + handle.row().status, + mindcore_runtime::minds::MindStatus::Frozen, + "the row carries the frozen status and open still answers the handle" + ); + assert_eq!(handle.carrier_entry_id(), created.carrier_entry_id); +} From 5c429b1cfa5a24c6d7852bddb75b9aa7cb1f797b Mon Sep 17 00:00:00 2001 From: Tang Bohao Date: Thu, 26 Nov 2026 08:43:23 +0800 Subject: [PATCH 02/22] Add the Mind memory operations and the journal directory publisher (mind-facade T2) --- Cargo.lock | 1 + crates/mindcore-runtime/Cargo.toml | 1 + crates/mindcore-runtime/src/journal.rs | 73 +++++ crates/mindcore-runtime/src/lib.rs | 3 +- crates/mindcore-runtime/src/mind.rs | 386 ++++++++++++++++++++++++- crates/mindcore-runtime/tests/mind.rs | 312 +++++++++++++++++++- 6 files changed, 765 insertions(+), 11 deletions(-) create mode 100644 crates/mindcore-runtime/src/journal.rs diff --git a/Cargo.lock b/Cargo.lock index 9a528b0..9ec456b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2092,6 +2092,7 @@ name = "mindcore-runtime" version = "0.1.0" dependencies = [ "async-trait", + "chrono", "ed25519-dalek 3.0.0", "mindcore-base", "mindcore-spi", diff --git a/crates/mindcore-runtime/Cargo.toml b/crates/mindcore-runtime/Cargo.toml index cdc2fbb..9e6f91d 100644 --- a/crates/mindcore-runtime/Cargo.toml +++ b/crates/mindcore-runtime/Cargo.toml @@ -9,6 +9,7 @@ publish = false [dependencies] async-trait.workspace = true +chrono.workspace = true mindcore-base = { path = "../mindcore-base" } mindcore-sqlite = { path = "../mindcore-sqlite" } mindcore-spi = { path = "../mindcore-spi" } diff --git a/crates/mindcore-runtime/src/journal.rs b/crates/mindcore-runtime/src/journal.rs new file mode 100644 index 0000000..6c15e08 --- /dev/null +++ b/crates/mindcore-runtime/src/journal.rs @@ -0,0 +1,73 @@ +//! The one journal publisher the crate offers: `journal_dir(root)` writes every journaled +//! file target under `root` at the target's own path. + +use std::path::PathBuf; + +use mindcore_spi::SpiError; +use serde_json::Value; + +/// A file publisher over `root`: each target's `content` bytes land at `root` joined with the +/// target's `path`, parent directories are created, and the written file is read back before +/// the target counts as published. `Ok(())` is returned only when every target's exact bytes +/// are durable. +/// +/// Target paths are the adapter's own (`records/.md`, `candidates/.md`, +/// `profiles/.md`): they carry no separators that could escape `root`, and they are +/// published as given rather than re-derived here. +pub fn journal_dir( + root: impl Into, +) -> impl Fn(&[Value]) -> Result<(), SpiError> + Send + Sync + 'static { + let root = root.into(); + move |targets| { + for target in targets { + let path = target.get("path").and_then(Value::as_str).ok_or_else(|| { + SpiError::InvalidInput("a journal target carries no path".to_string()) + })?; + let content = target + .get("content") + .and_then(Value::as_str) + .ok_or_else(|| { + SpiError::InvalidInput(format!("journal target {path} carries no content")) + })?; + let file = root.join(path); + if let Some(parent) = file.parent() { + std::fs::create_dir_all(parent).map_err(|error| { + SpiError::Settlement(spoke_reject(format!( + "the directory for {path} could not be created: {error}" + ))) + })?; + } + std::fs::write(&file, content).map_err(|error| { + SpiError::Settlement(spoke_reject(format!( + "journal target {path} could not be written: {error}" + ))) + })?; + let landed = std::fs::read_to_string(&file).map_err(|error| { + SpiError::Settlement(spoke_reject(format!( + "journal target {path} could not be confirmed: {error}" + ))) + })?; + if landed != content { + return Err(SpiError::Settlement(spoke_reject(format!( + "journal target {path} did not land with its exact bytes" + )))); + } + } + Ok(()) + } +} + +/// The publisher's refusal: a retryable `INTERNAL_ERROR` — nothing the settlement leg staged +/// is durable yet, so the same review can be repeated once the medium is writable. +fn spoke_reject(message: String) -> spoke_operations::SpokeReject { + let mut details = serde_json::Map::new(); + details.insert( + "retry_class".to_string(), + Value::String("retryable".to_string()), + ); + spoke_operations::SpokeReject { + code: spoke_operations::SpokeRejectCode::InternalError, + message, + details: Some(details), + } +} diff --git a/crates/mindcore-runtime/src/lib.rs b/crates/mindcore-runtime/src/lib.rs index 8d2594e..a09894f 100644 --- a/crates/mindcore-runtime/src/lib.rs +++ b/crates/mindcore-runtime/src/lib.rs @@ -13,6 +13,7 @@ mod adoption; mod history_dedup; +pub mod journal; pub mod mind; pub mod minds; pub mod tools; @@ -47,7 +48,7 @@ use sqlx::SqlitePool; use adoption::AdoptionService; use history_dedup::SqliteHistoryDedupStore; -pub use mind::Mind; +pub use mind::{Capture, Mind, Recall}; pub use tools::MindProviders; use tools::WorkflowTools; diff --git a/crates/mindcore-runtime/src/mind.rs b/crates/mindcore-runtime/src/mind.rs index d9d84e5..699916b 100644 --- a/crates/mindcore-runtime/src/mind.rs +++ b/crates/mindcore-runtime/src/mind.rs @@ -3,14 +3,34 @@ //! is. The handle keeps the row that read answers and nothing about grants: it caches no //! grant and acts on no status from the row, so a frozen Mind opens and every later operation //! re-reads the live state on its own transaction. +//! +//! The memory operations are composition, not a second write path: `capture` and `recall` +//! hand the adapter one transaction each with the Mind's id as `space_id`, and `review` runs +//! the staged-settlement fold — stage inside one transaction, publish before that staging is +//! durable so a refused publication leaves no record, then settle the receipt on a second +//! transaction. No method takes a collection, an owner or a viewpoint, and none chooses a +//! subject: the caller names it every time. + +use chrono::{DateTime, Utc}; +use serde_json::{json, Map, Value}; use mindcore_base::boundary::CallerId; -use mindcore_base::ids::MindId; +use mindcore_base::ids::{MindId, SpaceId}; +use mindcore_base::ir::MemoryRepository; +use mindcore_spi::SpiError; +use mindcore_spoke::{MemoryAdapter, MemoryStage}; use mindcore_sqlite::minds::Mind as MindRow; -use mindcore_sqlite::MindStore; -use spoke_operations::SpokeResult; +use mindcore_sqlite::{MindStore, SqliteMemoryRepository}; +use spoke_operations::{SpokeReject, SpokeRejectCode, SpokeResult}; +use spoke_schemas::memory_candidates_review_request::Decision; +use spoke_schemas::{ + MemoryCandidatesReviewResponse, MemoryCaptureResponse, MemoryRecallResponse, Principal, +}; use sqlx::SqlitePool; +/// The host's journal publisher: the handle never invents one. +type JournalPublisher = dyn Fn(&[Value]) -> Result<(), SpiError> + Send + Sync; + /// A caller's handle to one Mind: the pool, the caller and the row `minds::get` answered at /// open. /// @@ -18,13 +38,86 @@ use sqlx::SqlitePool; /// on every operation — and its row is a snapshot: the status it carries is the one at open, /// never re-read here. pub struct Mind { - // Read by the memory, knowledge and cognition operations of later tasks; `open` itself - // never acts on them. - #[allow(dead_code)] pool: SqlitePool, - #[allow(dead_code)] caller: CallerId, row: MindRow, + adapter: MemoryAdapter, + publisher: Option>, +} + +/// One memory capture in plain arguments; the handle renders the wire body with the Mind's +/// id as `space_id`. +pub struct Capture<'a> { + /// The subject this capture belongs to; the caller's, never defaulted. + pub subject: &'a str, + /// The context the capture is placed in, or `None` for the shared placement. + pub context: Option<&'a str>, + /// The content subtree of the SPOKE capture request (`text` plus optional members). + pub content: &'a Value, + pub occurred_at: Option>, + pub kind_hint: Option<&'a str>, + pub idempotency_key: &'a str, +} + +/// One memory recall in plain arguments; the handle renders the wire body with the Mind's +/// id as `space_id`. +pub struct Recall<'a> { + /// The subject whose records are read; the caller's, never defaulted. + pub subject: &'a str, + /// The §6.12 read selection member (`{"mode": ...}`), exactly as the wire carries it. + pub selection: &'a Value, + pub max_items: Option, + pub max_bytes: Option, + pub query: Option<&'a str>, + pub cursor: Option<&'a str>, +} + +fn reject(code: SpokeRejectCode, message: impl Into, class: &str) -> SpokeResult { + let mut details = Map::new(); + details.insert("retry_class".to_string(), Value::String(class.to_string())); + SpokeResult::Reject(SpokeReject { + code, + message: message.into(), + details: Some(details), + }) +} + +/// A failure before anything can have committed: the caller may retry the same request. +fn retryable_internal(message: impl Into) -> SpokeResult { + reject(SpokeRejectCode::InternalError, message, "retryable") +} + +/// A failure after the staging commit: rows may be durable, so the outcome is unknown and +/// the caller resolves it instead of retrying blind. +fn uncertain(message: impl Into) -> SpokeResult { + reject(SpokeRejectCode::OutcomeUncertain, message, "uncertain") +} + +/// The authenticated caller rendered as the adapter's wire `Principal`; the id is the +/// authenticated identity the embedding host supplied at open, never payload-asserted. +fn principal(caller: &CallerId) -> Principal { + serde_json::from_value(json!({ + "principal_id": caller.as_str(), + "extensions": {}, + })) + .expect("a caller id is a valid principal") +} + +/// The ready body of one adapter operation, decoded into its pinned response type. Any other +/// stage here is a composition defect: these operations never journal. +fn ready(stage: SpokeResult) -> SpokeResult { + match stage { + SpokeResult::Ok(MemoryStage::Ready(body)) => match serde_json::from_value(body) { + Ok(response) => SpokeResult::Ok(response), + Err(error) => retryable_internal(format!( + "the adapter's response does not match its schema: {error}" + )), + }, + SpokeResult::Ok(stage) => retryable_internal(format!( + "the adapter answered an unexpected stage: {stage:?}" + )), + SpokeResult::Reject(reject) => SpokeResult::Reject(reject), + } } impl Mind { @@ -37,11 +130,27 @@ impl Mind { pool: store.pool(), caller: caller.clone(), row, + adapter: MemoryAdapter::new(false), + publisher: None, }), SpokeResult::Reject(reject) => SpokeResult::Reject(reject), } } + /// Publish journaled file targets into the host's medium. + /// + /// The closure returns `Ok(())` only after every target's exact bytes are durable. It runs + /// while the handle holds the store's one connection, so it must not touch the store. + /// `review` without a publisher is refused before anything is staged. + #[must_use] + pub fn with_journal_publisher( + mut self, + publish: impl Fn(&[Value]) -> Result<(), SpiError> + Send + Sync + 'static, + ) -> Self { + self.publisher = Some(Box::new(publish)); + self + } + /// The entry in the Mind's collection that holds its current judgment, as the row named it /// at open. pub fn carrier_entry_id(&self) -> &str { @@ -52,4 +161,267 @@ impl Mind { pub fn row(&self) -> &MindRow { &self.row } + + /// Capture one memory into this Mind: the adapter's `capture` over one immediate-write + /// transaction, with the Mind's id as `space_id`. + pub async fn capture(&self, capture: &Capture<'_>) -> SpokeResult { + let mut request = json!({ + "space_id": self.row.id.as_str(), + "subject_id": capture.subject, + "capture_scope": match capture.context { + Some(context) => json!({ "visibility": "context", "context_id": context }), + None => json!({ "visibility": "shared" }), + }, + "content": capture.content, + "idempotency_key": capture.idempotency_key, + }); + let object = request.as_object_mut().expect("the request is an object"); + if let Some(kind_hint) = capture.kind_hint { + object.insert("kind_hint".to_string(), json!(kind_hint)); + } + if let Some(occurred_at) = capture.occurred_at { + object.insert("occurred_at".to_string(), json!(occurred_at)); + } + + let mut transaction = match self.pool.begin_with("BEGIN IMMEDIATE").await { + Ok(transaction) => transaction, + Err(error) => { + return retryable_internal(format!("capture transaction could not begin: {error}")) + } + }; + let stage = self + .adapter + .capture(&mut transaction, &principal(&self.caller), request) + .await; + if stage.is_reject() { + drop(transaction); + return ready(stage); + } + if let Err(error) = transaction.commit().await { + return uncertain(format!("capture committed an unknown outcome: {error}")); + } + ready(stage) + } + + /// Recall this Mind's live records: the adapter's `recall` over one read transaction, + /// rolled back after the read. + pub async fn recall(&self, recall: &Recall<'_>) -> SpokeResult { + let mut budget = Map::new(); + if let Some(max_items) = recall.max_items { + budget.insert("max_items".to_string(), json!(max_items)); + } + if let Some(max_bytes) = recall.max_bytes { + budget.insert("max_bytes".to_string(), json!(max_bytes)); + } + let mut request = json!({ + "space_id": self.row.id.as_str(), + "subject_id": recall.subject, + "selection": recall.selection, + "budget": Value::Object(budget), + }); + let object = request.as_object_mut().expect("the request is an object"); + if let Some(query) = recall.query { + object.insert("query".to_string(), json!(query)); + } + if let Some(cursor) = recall.cursor { + object.insert("cursor".to_string(), json!(cursor)); + } + + let mut transaction = match self.pool.begin().await { + Ok(transaction) => transaction, + Err(error) => { + return retryable_internal(format!("recall transaction could not begin: {error}")) + } + }; + let stage = self + .adapter + .recall(&mut transaction, &principal(&self.caller), request) + .await; + drop(transaction); + ready(stage) + } + + /// Review one pending candidate and answer the settled receipt, not a `MemoryStage`. + /// + /// The fold stages the whole decision inside one immediate-write transaction, reads the + /// staged intent on it and publishes the owed targets before the staging is durable: a + /// refused publication rolls everything back — no record, no intent, a pending candidate — + /// and the same idempotency key can be repeated. Only after a successful publication does + /// the staging commit; settlement then runs on a second transaction, and any failure from + /// there answers `OUTCOME_UNCERTAIN` because durable work may be outstanding. + pub async fn review( + &self, + candidate_id: &str, + decision: &Decision, + idempotency_key: &str, + ) -> SpokeResult { + let publisher = match self.publisher.as_deref() { + Some(publisher) => publisher, + None => { + return reject( + SpokeRejectCode::InvalidInput, + "this Mind handle has no journal publisher, so it cannot settle a review", + "terminal", + ) + } + }; + let space = SpaceId::new(self.row.id.as_str()); + let caller = principal(&self.caller); + let mut transaction = match self.pool.begin_with("BEGIN IMMEDIATE").await { + Ok(transaction) => transaction, + Err(error) => { + return retryable_internal(format!( + "review staging transaction could not begin: {error}" + )) + } + }; + + // 1–2. Read the candidate's revision, then stage the review on the same transaction. + // A replay of a receipt already settled answers `Ready` and is returned as it is. + let candidate = self + .adapter + .get_candidate( + &mut transaction, + &caller, + json!({ "space_id": space.as_str(), "candidate_id": candidate_id }), + ) + .await; + let revision = match candidate { + SpokeResult::Ok(MemoryStage::Ready(body)) => { + match body.pointer("/candidate/revision").and_then(Value::as_u64) { + Some(revision) => revision, + None => { + drop(transaction); + return retryable_internal( + "the candidate body carries no integer revision", + ); + } + } + } + SpokeResult::Ok(stage) => { + drop(transaction); + return retryable_internal(format!( + "candidate read answered an unexpected stage: {stage:?}" + )); + } + SpokeResult::Reject(reject) => { + drop(transaction); + return SpokeResult::Reject(reject); + } + }; + let decision = match serde_json::to_value(decision) { + Ok(decision) => decision, + Err(error) => { + drop(transaction); + return retryable_internal(format!("the decision could not be rendered: {error}")); + } + }; + let stage = self + .adapter + .review_candidate( + &mut transaction, + &caller, + json!({ + "space_id": space.as_str(), + "candidate_id": candidate_id, + "decision": decision, + "expected_revision": revision, + "idempotency_key": idempotency_key, + }), + ) + .await; + let receipt_id = match stage { + SpokeResult::Ok(MemoryStage::JournalPending { receipt_id, .. }) => receipt_id, + SpokeResult::Ok(MemoryStage::Ready(body)) => { + drop(transaction); + return match serde_json::from_value(body) { + Ok(response) => SpokeResult::Ok(response), + Err(error) => retryable_internal(format!( + "the replayed receipt does not match its schema: {error}" + )), + }; + } + SpokeResult::Ok(stage) => { + drop(transaction); + return retryable_internal(format!( + "review answered an unexpected stage: {stage:?}" + )); + } + SpokeResult::Reject(reject) => { + drop(transaction); + return SpokeResult::Reject(reject); + } + }; + + // 3. Read the staged intent on the same transaction for the targets it owes. + let intent = match SqliteMemoryRepository + .journal_intent(&mut transaction, &space, &receipt_id) + .await + { + Ok(Some(intent)) => intent, + Ok(None) => { + drop(transaction); + return retryable_internal(format!("receipt {receipt_id} has no journaled intent")); + } + Err(_) => { + drop(transaction); + return retryable_internal(format!( + "journal intent {receipt_id} could not be read" + )); + } + }; + + // 4. Publish before the staging is durable. A refusal rolls the transaction back: + // no record row, no intent and a pending candidate are left, and the publisher's own + // `SpiError::Settlement` refusal travels unchanged. + if let Err(error) = publisher(&intent.targets) { + drop(transaction); + return match error { + SpiError::Settlement(reject) => SpokeResult::Reject(reject), + other => retryable_internal(format!("publication failed: {other}")), + }; + } + + // 5. Commit the staging, then settle the receipt on a second immediate-write + // transaction. A failure from here leaves a pending intent and answers + // `OUTCOME_UNCERTAIN`, as the served surface does. + if let Err(error) = transaction.commit().await { + return uncertain(format!( + "review staging for receipt {receipt_id} committed an unknown outcome: {error}" + )); + } + let mut settlement = match self.pool.begin_with("BEGIN IMMEDIATE").await { + Ok(transaction) => transaction, + Err(error) => { + return uncertain(format!( + "settlement transaction for receipt {receipt_id} could not begin: {error}" + )) + } + }; + let settled = self + .adapter + .settle_journal(&mut settlement, &space, &receipt_id) + .await; + let body = match settled { + SpokeResult::Ok(body) => body, + SpokeResult::Reject(reject) => { + drop(settlement); + return uncertain(format!( + "settlement of receipt {receipt_id} failed after it was staged: {}: {}", + reject.code, reject.message + )); + } + }; + if let Err(error) = settlement.commit().await { + return uncertain(format!( + "settlement of receipt {receipt_id} committed an unknown outcome: {error}" + )); + } + match serde_json::from_value(body) { + Ok(response) => SpokeResult::Ok(response), + Err(error) => uncertain(format!( + "the settled receipt {receipt_id} does not match its schema: {error}" + )), + } + } } diff --git a/crates/mindcore-runtime/tests/mind.rs b/crates/mindcore-runtime/tests/mind.rs index f1b8009..5fc064d 100644 --- a/crates/mindcore-runtime/tests/mind.rs +++ b/crates/mindcore-runtime/tests/mind.rs @@ -5,11 +5,13 @@ use mindcore_base::boundary::CallerId; use mindcore_base::ids::{MindId, SpaceId}; use mindcore_base::ir::MemoryRepository; +use mindcore_runtime::journal::journal_dir; use mindcore_runtime::minds::{self, CreateMind}; -use mindcore_runtime::Mind; +use mindcore_runtime::{Capture, Mind, Recall}; +use mindcore_spi::SpiError; use mindcore_sqlite::{MindStore, SqliteMemoryRepository}; -use serde_json::Number; -use spoke_operations::{SpokeRejectCode, SpokeResult}; +use serde_json::{json, Number, Value}; +use spoke_operations::{SpokeReject, SpokeRejectCode, SpokeResult}; use tempfile::TempDir; const OWNER: &str = "caller_wren"; @@ -119,3 +121,307 @@ async fn a_frozen_mind_opens_with_no_status_acted_on() { ); assert_eq!(handle.carrier_entry_id(), created.carrier_entry_id); } + +const SUBJECT: &str = "subj_wren"; + +fn capture(key: &str, text: &str) -> Capture<'static> { + Capture { + subject: SUBJECT, + context: None, + content: Box::leak(Box::new(json!({ "text": text }))), + occurred_at: None, + kind_hint: None, + idempotency_key: Box::leak(key.to_string().into_boxed_str()), + } +} + +fn recall_all() -> (Recall<'static>, Value) { + let selection = Box::leak(Box::new(json!({ "mode": "subject_all" }))); + ( + Recall { + subject: SUBJECT, + selection, + max_items: Some(10), + max_bytes: None, + query: None, + cursor: None, + }, + selection.clone(), + ) +} + +fn promote() -> spoke_schemas::memory_candidates_review_request::Decision { + serde_json::from_value(json!({ "action": "promote" })).expect("promote decision") +} + +fn value_of(response: &T) -> Value { + serde_json::to_value(response).expect("response serializes") +} + +fn retry_class(reject: &SpokeReject) -> &str { + reject + .details + .as_ref() + .and_then(|details| details.get("retry_class")) + .and_then(Value::as_str) + .expect("a retry class") +} + +fn reject_of(result: SpokeResult) -> SpokeReject { + match result { + SpokeResult::Reject(reject) => reject, + SpokeResult::Ok(_) => panic!("expected a refusal"), + } +} + +/// Capture one candidate through the handle and answer its id. +async fn capture_candidate(handle: &Mind, key: &str, text: &str) -> String { + let response = ok(handle.capture(&capture(key, text)).await); + let body = value_of(&response); + assert_eq!( + body["status"], "committed", + "the capture commits its receipt" + ); + body["result"]["candidate_ids"][0] + .as_str() + .expect("candidate id") + .to_string() +} + +/// Register the test subject on the Mind's space, as the embedding host does before capture. +async fn ensure_subject(store: &MindStore, space_id: &str) { + let adapter = mindcore_spoke::MemoryAdapter::new(false); + let caller: spoke_schemas::Principal = serde_json::from_value(json!({ + "principal_id": OWNER, + "extensions": {}, + })) + .expect("principal"); + let mut tx = store.pool().begin().await.expect("begin the subject write"); + let stage = adapter + .ensure_subject( + &mut tx, + &caller, + json!({ "space_id": space_id, "subject_id": SUBJECT }), + ) + .await; + assert!(stage.is_ok(), "the subject registers: {stage:?}"); + tx.commit().await.expect("commit the subject"); +} + +async fn count_records(pool: &sqlx::SqlitePool) -> i64 { + sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM memory_records") + .fetch_one(pool) + .await + .expect("count record rows") +} + +async fn count_intents(pool: &sqlx::SqlitePool) -> i64 { + sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM memory_journal") + .fetch_one(pool) + .await + .expect("count intent rows") +} + +async fn intent_states(pool: &sqlx::SqlitePool) -> Vec { + sqlx::query_scalar::<_, String>("SELECT state FROM memory_journal") + .fetch_all(pool) + .await + .expect("intent states") +} + +#[tokio::test] +async fn capture_review_then_recall_returns_the_record_for_the_named_subject() { + let (dir, store) = fixture().await; + let owner = CallerId::new(OWNER); + let created = ok(minds::create(&store, &request(OWNER)).await); + ensure_subject(&store, created.id.as_str()).await; + let handle = ok(Mind::open(&store, &owner, &created.id).await) + .with_journal_publisher(journal_dir(dir.path())); + + let candidate_id = capture_candidate(&handle, "cap-facade-recall", "the gate is shut").await; + let reviewed = ok(handle + .review(&candidate_id, &promote(), "rev-facade-recall") + .await); + let receipt = value_of(&reviewed); + assert_eq!( + receipt["status"], "committed", + "review answers a settled receipt" + ); + let record_id = receipt["result"]["record_ids"][0] + .as_str() + .expect("a retained record id") + .to_string(); + + let (recall, _) = recall_all(); + let page = value_of(&ok(handle.recall(&recall).await)); + let records = page["records"].as_array().expect("a records page"); + assert!( + records + .iter() + .any(|record| record["record_id"] == record_id), + "recall after capture and review returns the record: {page}" + ); + + // The caller-named subject is passed through, never defaulted: a subject the caller did + // not write holds no records, while the candidate and the record sit on `subj_wren`. + let other = Recall { + subject: "subj_someone_else", + ..recall_all().0 + }; + let other_page = value_of(&ok(handle.recall(&other).await)); + assert_eq!( + other_page["records"].as_array().expect("records").len(), + 0, + "nothing leaks onto another subject" + ); + let subject: String = + sqlx::query_scalar("SELECT subject_id FROM memory_records WHERE record_id = ?") + .bind(&record_id) + .fetch_one(&store.pool()) + .await + .expect("the record's subject row"); + assert_eq!(subject, SUBJECT); + + // journal_dir published the projection files under the scratch root at their own paths. + let published = dir.path().join("records").join(format!("{record_id}.md")); + assert!( + published.exists(), + "the record projection was published under the journal root" + ); +} + +#[tokio::test] +async fn a_refused_publication_leaves_nothing_staged_and_the_same_key_then_settles() { + let (dir, store) = fixture().await; + let owner = CallerId::new(OWNER); + let created = ok(minds::create(&store, &request(OWNER)).await); + ensure_subject(&store, created.id.as_str()).await; + let candidate_id = { + let handle = ok(Mind::open(&store, &owner, &created.id).await) + .with_journal_publisher(journal_dir(dir.path())); + capture_candidate(&handle, "cap-refused-publish", "a note to refuse").await + }; + + // First attempt: the publisher refuses with its own Settlement refusal. + let refused = SpokeReject { + code: SpokeRejectCode::InternalError, + message: "the medium is full".to_string(), + details: Some(serde_json::Map::from_iter([( + "retry_class".to_string(), + Value::String("retryable".to_string()), + )])), + }; + let expected = refused.clone(); + let failing = ok(Mind::open(&store, &owner, &created.id).await) + .with_journal_publisher(move |_| Err(SpiError::Settlement(expected.clone()))); + let reject = reject_of( + failing + .review(&candidate_id, &promote(), "rev-refused-publish") + .await, + ); + assert_eq!( + reject, refused, + "the publisher's Settlement refusal travels unchanged" + ); + + // Nothing is durable: no record row, no intent, and the candidate is still pending. + assert_eq!(count_records(&store.pool()).await, 0, "no record row"); + assert_eq!(count_intents(&store.pool()).await, 0, "no intent"); + let status: String = + sqlx::query_scalar("SELECT status FROM memory_candidates WHERE candidate_id = ?") + .bind(&candidate_id) + .fetch_one(&store.pool()) + .await + .expect("the candidate row"); + assert_eq!(status, "pending", "the candidate stays pending"); + + // A non-Settlement publisher refusal answers the retryable INTERNAL_ERROR instead. + let io_failing = ok(Mind::open(&store, &owner, &created.id).await) + .with_journal_publisher(move |_| Err(SpiError::EmbeddingFailed("disk gone".to_string()))); + let reject = reject_of( + io_failing + .review(&candidate_id, &promote(), "rev-refused-publish") + .await, + ); + assert_eq!(reject.code, SpokeRejectCode::InternalError); + assert_eq!(retry_class(&reject), "retryable"); + assert_eq!(count_records(&store.pool()).await, 0, "still no record row"); + assert_eq!(count_intents(&store.pool()).await, 0, "still no intent"); + + // The same key then settles once the medium accepts the publication. + let working = ok(Mind::open(&store, &owner, &created.id).await) + .with_journal_publisher(journal_dir(dir.path())); + let reviewed = ok(working + .review(&candidate_id, &promote(), "rev-refused-publish") + .await); + assert_eq!( + value_of(&reviewed)["status"], + "committed", + "the same key settles after the refused publication" + ); + assert_eq!(count_records(&store.pool()).await, 1, "one record row"); +} + +#[tokio::test] +async fn a_refused_settle_answers_outcome_uncertain_and_leaves_the_intent_pending() { + let (dir, store) = fixture().await; + let owner = CallerId::new(OWNER); + let created = ok(minds::create(&store, &request(OWNER)).await); + ensure_subject(&store, created.id.as_str()).await; + let pool = store.pool(); + let journal_root = dir.path().to_path_buf(); + let handle = ok(Mind::open(&store, &owner, &created.id).await) + .with_journal_publisher(journal_dir(&journal_root)); + let candidate_id = capture_candidate( + &handle, + "cap-refused-settle", + "a note whose settlement fails", + ) + .await; + + // The publisher queues an interference task on the store's one-connection pool: the + // staging transaction still holds that connection, so the task cannot start until the + // staging commit releases it. The pool's queue is fair, so the task — queued while the + // publisher runs, before the facade's settlement transaction even asks — takes the next + // checkout, moves the intent out of `pending`, and only then hands the connection to the + // settlement. The settle therefore always reads a moved intent: deterministic, no timing. + let interference_pool = pool.clone(); + let handle = + ok(Mind::open(&store, &owner, &created.id).await).with_journal_publisher(move |targets| { + journal_dir(&journal_root)(targets)?; + let interference_pool = interference_pool.clone(); + tokio::spawn(async move { + let mut connection = interference_pool + .acquire() + .await + .expect("the one connection"); + sqlx::query("UPDATE memory_journal SET state = 'deferred'") + .execute(&mut *connection) + .await + .expect("move the intent out of pending"); + }); + Ok(()) + }); + + let reject = reject_of( + handle + .review(&candidate_id, &promote(), "rev-refused-settle") + .await, + ); + assert_eq!( + reject.code, + SpokeRejectCode::OutcomeUncertain, + "a refused settle answers OUTCOME_UNCERTAIN: {reject:?}" + ); + assert_eq!(retry_class(&reject), "uncertain"); + assert_eq!( + intent_states(&pool).await, + vec!["deferred".to_string()], + "the intent is left unsettled, never silently applied" + ); + assert_eq!( + count_records(&pool).await, + 1, + "the staged record is durable" + ); +} From 2f6fc201084deac7d907dfdae3faf856d7b25f0a Mon Sep 17 00:00:00 2001 From: Tang Bohao Date: Thu, 26 Nov 2026 08:51:00 +0800 Subject: [PATCH 03/22] Fix review replay identity, journal durability and the public publisher path (mind-facade T2 review) --- Cargo.lock | 1 + crates/mindcore-runtime/Cargo.toml | 1 + crates/mindcore-runtime/src/journal.rs | 32 ++++++++-- crates/mindcore-runtime/src/lib.rs | 1 + crates/mindcore-runtime/src/mind.rs | 42 +++---------- crates/mindcore-runtime/tests/mind.rs | 83 ++++++++++++++++++++++---- 6 files changed, 111 insertions(+), 49 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 9ec456b..c5ba15f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2094,6 +2094,7 @@ dependencies = [ "async-trait", "chrono", "ed25519-dalek 3.0.0", + "futures", "mindcore-base", "mindcore-spi", "mindcore-spoke", diff --git a/crates/mindcore-runtime/Cargo.toml b/crates/mindcore-runtime/Cargo.toml index 9e6f91d..e529e1f 100644 --- a/crates/mindcore-runtime/Cargo.toml +++ b/crates/mindcore-runtime/Cargo.toml @@ -24,5 +24,6 @@ tokio = { workspace = true, features = ["sync"] } [dev-dependencies] ed25519-dalek = "3" +futures = "0.3" tempfile = "3.27.0" tokio = { workspace = true, features = ["macros", "rt-multi-thread"] } diff --git a/crates/mindcore-runtime/src/journal.rs b/crates/mindcore-runtime/src/journal.rs index 6c15e08..5289375 100644 --- a/crates/mindcore-runtime/src/journal.rs +++ b/crates/mindcore-runtime/src/journal.rs @@ -1,15 +1,16 @@ //! The one journal publisher the crate offers: `journal_dir(root)` writes every journaled //! file target under `root` at the target's own path. -use std::path::PathBuf; +use std::path::{Path, PathBuf}; use mindcore_spi::SpiError; use serde_json::Value; /// A file publisher over `root`: each target's `content` bytes land at `root` joined with the -/// target's `path`, parent directories are created, and the written file is read back before -/// the target counts as published. `Ok(())` is returned only when every target's exact bytes -/// are durable. +/// target's `path`, parent directories are created, and `Ok(())` is returned only when every +/// target's exact bytes are durable — the file contents are synced to disk and the directory +/// entries that name it are synced too, so a power loss cannot quietly lose a target the +/// settlement was told had landed. /// /// Target paths are the adapter's own (`records/.md`, `candidates/.md`, /// `profiles/.md`): they carry no separators that could escape `root`, and they are @@ -42,6 +43,29 @@ pub fn journal_dir( "journal target {path} could not be written: {error}" ))) })?; + // Durability, not visibility: the write must reach the medium before the caller + // may settle the intent. Sync the file's contents, then the directory entries of + // every directory `create_dir_all` may have created up to the publisher root. + std::fs::File::open(&file) + .and_then(|file| file.sync_all()) + .map_err(|error| { + SpiError::Settlement(spoke_reject(format!( + "journal target {path} could not be synced: {error}" + ))) + })?; + let mut directory = file.parent().map(Path::to_path_buf); + while let Some(dir) = directory { + std::fs::File::open(&dir) + .and_then(|dir_file| dir_file.sync_all()) + .map_err(|error| { + SpiError::Settlement(spoke_reject(format!( + "the directory for {path} could not be synced: {error}" + ))) + })?; + directory = (dir != root) + .then(|| dir.parent().map(Path::to_path_buf)) + .flatten(); + } let landed = std::fs::read_to_string(&file).map_err(|error| { SpiError::Settlement(spoke_reject(format!( "journal target {path} could not be confirmed: {error}" diff --git a/crates/mindcore-runtime/src/lib.rs b/crates/mindcore-runtime/src/lib.rs index a09894f..d4b7ca0 100644 --- a/crates/mindcore-runtime/src/lib.rs +++ b/crates/mindcore-runtime/src/lib.rs @@ -48,6 +48,7 @@ use sqlx::SqlitePool; use adoption::AdoptionService; use history_dedup::SqliteHistoryDedupStore; +pub use journal::journal_dir; pub use mind::{Capture, Mind, Recall}; pub use tools::MindProviders; use tools::WorkflowTools; diff --git a/crates/mindcore-runtime/src/mind.rs b/crates/mindcore-runtime/src/mind.rs index 699916b..3c8d931 100644 --- a/crates/mindcore-runtime/src/mind.rs +++ b/crates/mindcore-runtime/src/mind.rs @@ -276,39 +276,13 @@ impl Mind { } }; - // 1–2. Read the candidate's revision, then stage the review on the same transaction. - // A replay of a receipt already settled answers `Ready` and is returned as it is. - let candidate = self - .adapter - .get_candidate( - &mut transaction, - &caller, - json!({ "space_id": space.as_str(), "candidate_id": candidate_id }), - ) - .await; - let revision = match candidate { - SpokeResult::Ok(MemoryStage::Ready(body)) => { - match body.pointer("/candidate/revision").and_then(Value::as_u64) { - Some(revision) => revision, - None => { - drop(transaction); - return retryable_internal( - "the candidate body carries no integer revision", - ); - } - } - } - SpokeResult::Ok(stage) => { - drop(transaction); - return retryable_internal(format!( - "candidate read answered an unexpected stage: {stage:?}" - )); - } - SpokeResult::Reject(reject) => { - drop(transaction); - return SpokeResult::Reject(reject); - } - }; + // 1–2. Stage the review on one transaction. A replay of a receipt already settled + // answers `Ready` and is returned as it is. The request must be byte-identical across + // replays of one key — the adapter's dedup probe digests the whole payload — so + // `expected_revision` is the constant a pending candidate always carries (capture + // writes revision 1 and nothing mutates a pending candidate), never a fresh read of + // the row: reading it would send 2 after the consumption bumped it and the replay + // would answer `IdempotencyConflict` instead of the recorded receipt. let decision = match serde_json::to_value(decision) { Ok(decision) => decision, Err(error) => { @@ -325,7 +299,7 @@ impl Mind { "space_id": space.as_str(), "candidate_id": candidate_id, "decision": decision, - "expected_revision": revision, + "expected_revision": 1, "idempotency_key": idempotency_key, }), ) diff --git a/crates/mindcore-runtime/tests/mind.rs b/crates/mindcore-runtime/tests/mind.rs index 5fc064d..5308c05 100644 --- a/crates/mindcore-runtime/tests/mind.rs +++ b/crates/mindcore-runtime/tests/mind.rs @@ -5,13 +5,15 @@ use mindcore_base::boundary::CallerId; use mindcore_base::ids::{MindId, SpaceId}; use mindcore_base::ir::MemoryRepository; -use mindcore_runtime::journal::journal_dir; +use mindcore_runtime::journal_dir; use mindcore_runtime::minds::{self, CreateMind}; use mindcore_runtime::{Capture, Mind, Recall}; use mindcore_spi::SpiError; use mindcore_sqlite::{MindStore, SqliteMemoryRepository}; use serde_json::{json, Number, Value}; use spoke_operations::{SpokeReject, SpokeRejectCode, SpokeResult}; +use spoke_schemas::memory_candidates_review_request::Decision; +use std::sync::mpsc; use tempfile::TempDir; const OWNER: &str = "caller_wren"; @@ -360,9 +362,57 @@ async fn a_refused_publication_leaves_nothing_staged_and_the_same_key_then_settl "the same key settles after the refused publication" ); assert_eq!(count_records(&store.pool()).await, 1, "one record row"); + + // Critical 1: the same key replays. Consuming the candidate bumped its revision to 2 — + // asserted here so the next assertion cannot silently pass on an unchanged row — so a + // facade that re-read the row would send a different `expected_revision`, change the + // payload digest and be answered `IdempotencyConflict`. The settled receipt replays + // instead, byte-identically. + let candidate_revision: i64 = + sqlx::query_scalar("SELECT revision FROM memory_candidates WHERE candidate_id = ?") + .bind(&candidate_id) + .fetch_one(&store.pool()) + .await + .expect("the consumed candidate row"); + assert_eq!( + candidate_revision, 2, + "consumption moved the stored revision" + ); + let replayed = ok(working + .review(&candidate_id, &promote(), "rev-refused-publish") + .await); + assert_eq!( + value_of(&replayed), + value_of(&reviewed), + "an identical review replays the recorded receipt" + ); + assert_eq!( + count_records(&store.pool()).await, + 1, + "a replay writes no second record" + ); + assert_eq!( + count_intents(&store.pool()).await, + 1, + "a replay stages no second intent" + ); + + // A different decision under the same key stays a conflict — the digest still guards it. + let different = + serde_json::from_value::(json!({ "action": "drop" })).expect("drop decision"); + let conflict = reject_of( + working + .review(&candidate_id, &different, "rev-refused-publish") + .await, + ); + assert_eq!( + conflict.code, + SpokeRejectCode::IdempotencyConflict, + "a different payload under one key is refused" + ); } -#[tokio::test] +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn a_refused_settle_answers_outcome_uncertain_and_leaves_the_intent_pending() { let (dir, store) = fixture().await; let owner = CallerId::new(OWNER); @@ -380,26 +430,37 @@ async fn a_refused_settle_answers_outcome_uncertain_and_leaves_the_intent_pendin .await; // The publisher queues an interference task on the store's one-connection pool: the - // staging transaction still holds that connection, so the task cannot start until the - // staging commit releases it. The pool's queue is fair, so the task — queued while the - // publisher runs, before the facade's settlement transaction even asks — takes the next - // checkout, moves the intent out of `pending`, and only then hands the connection to the - // settlement. The settle therefore always reads a moved intent: deterministic, no timing. + // staging transaction still holds that connection, so the task cannot acquire until the + // staging commit releases it. sqlx's pool issues connections FIFO-fair in registration + // order, and the task proves it registered before the publisher returns: the spawned task + // polls its acquire future once (registration happens on the first poll, while the one + // connection is still checked out) and signals that through the handshake channel. The + // settlement transaction asks only after the commit, so it is always behind the + // interference task in the queue, and the settle always reads a moved intent — the order + // is the semaphore's, never the scheduler's. let interference_pool = pool.clone(); let handle = ok(Mind::open(&store, &owner, &created.id).await).with_journal_publisher(move |targets| { journal_dir(&journal_root)(targets)?; let interference_pool = interference_pool.clone(); + let (registered, is_registered) = mpsc::channel::<()>(); tokio::spawn(async move { - let mut connection = interference_pool - .acquire() - .await - .expect("the one connection"); + let acquire = interference_pool.acquire(); + tokio::pin!(acquire); + assert!( + futures::poll!(acquire.as_mut()).is_pending(), + "the staging transaction still holds the one connection" + ); + registered.send(()).expect("signal the registration"); + let mut connection = acquire.await.expect("the one connection"); sqlx::query("UPDATE memory_journal SET state = 'deferred'") .execute(&mut *connection) .await .expect("move the intent out of pending"); }); + is_registered + .recv() + .expect("the interference task registered its acquisition"); Ok(()) }); From d147b0de4efec0a24c10ef251633a0ad7241b6ae Mon Sep 17 00:00:00 2001 From: Tang Bohao Date: Thu, 26 Nov 2026 08:54:27 +0800 Subject: [PATCH 04/22] Read the candidate revision and persist the journal's created directory chain (mind-facade T2 re-review) --- crates/mindcore-runtime/src/journal.rs | 115 ++++++++++++++++++++----- crates/mindcore-runtime/src/mind.rs | 58 +++++++++++-- crates/mindcore-runtime/tests/mind.rs | 81 +++++++++++++++++ 3 files changed, 226 insertions(+), 28 deletions(-) diff --git a/crates/mindcore-runtime/src/journal.rs b/crates/mindcore-runtime/src/journal.rs index 5289375..0906b38 100644 --- a/crates/mindcore-runtime/src/journal.rs +++ b/crates/mindcore-runtime/src/journal.rs @@ -8,9 +8,11 @@ use serde_json::Value; /// A file publisher over `root`: each target's `content` bytes land at `root` joined with the /// target's `path`, parent directories are created, and `Ok(())` is returned only when every -/// target's exact bytes are durable — the file contents are synced to disk and the directory -/// entries that name it are synced too, so a power loss cannot quietly lose a target the -/// settlement was told had landed. +/// target's exact bytes are durable — the file contents are synced to disk, and so is every +/// directory entry the publication created, up to and including the nearest ancestor that +/// already existed when publication began. `root` itself may be created here: its entry in +/// its parent is synced as part of that chain, so a crash cannot leave a settled intent +/// naming a tree the medium no longer holds. /// /// Target paths are the adapter's own (`records/.md`, `candidates/.md`, /// `profiles/.md`): they carry no separators that could escape `root`, and they are @@ -31,21 +33,28 @@ pub fn journal_dir( SpiError::InvalidInput(format!("journal target {path} carries no content")) })?; let file = root.join(path); - if let Some(parent) = file.parent() { - std::fs::create_dir_all(parent).map_err(|error| { - SpiError::Settlement(spoke_reject(format!( - "the directory for {path} could not be created: {error}" - ))) - })?; - } + let Some(parent) = file.parent() else { + return Err(SpiError::InvalidInput(format!( + "journal target {path} has no parent directory" + ))); + }; + // Decide the durable chain before creating anything: every directory that does + // not exist yet, deepest first, and the nearest ancestor that does — its entry is + // the one a newly created topmost directory lands in. + let chain = durable_chain(parent, Path::exists); + std::fs::create_dir_all(parent).map_err(|error| { + SpiError::Settlement(spoke_reject(format!( + "the directory for {path} could not be created: {error}" + ))) + })?; std::fs::write(&file, content).map_err(|error| { SpiError::Settlement(spoke_reject(format!( "journal target {path} could not be written: {error}" ))) })?; // Durability, not visibility: the write must reach the medium before the caller - // may settle the intent. Sync the file's contents, then the directory entries of - // every directory `create_dir_all` may have created up to the publisher root. + // may settle the intent. Sync the file's contents, then each directory entry the + // publication created, deepest first. std::fs::File::open(&file) .and_then(|file| file.sync_all()) .map_err(|error| { @@ -53,18 +62,15 @@ pub fn journal_dir( "journal target {path} could not be synced: {error}" ))) })?; - let mut directory = file.parent().map(Path::to_path_buf); - while let Some(dir) = directory { - std::fs::File::open(&dir) - .and_then(|dir_file| dir_file.sync_all()) + for directory in &chain { + std::fs::File::open(directory) + .and_then(|dir| dir.sync_all()) .map_err(|error| { SpiError::Settlement(spoke_reject(format!( - "the directory for {path} could not be synced: {error}" + "the directory {} could not be synced: {error}", + directory.display() ))) })?; - directory = (dir != root) - .then(|| dir.parent().map(Path::to_path_buf)) - .flatten(); } let landed = std::fs::read_to_string(&file).map_err(|error| { SpiError::Settlement(spoke_reject(format!( @@ -81,6 +87,26 @@ pub fn journal_dir( } } +/// The directories whose entries must be durable for one target to count as published, +/// deepest first: every directory from `parent` upward that `exists` reports as absent — +/// these are the ones the publication creates — and the nearest ancestor that already exists, +/// whose entry names the topmost created directory. Stops at an existing directory, or at the +/// filesystem root when nothing on the way exists yet. +/// +/// `exists` is a parameter so the ordering is provable without touching a filesystem. +fn durable_chain(parent: &Path, mut exists: impl FnMut(&Path) -> bool) -> Vec { + let mut chain = Vec::new(); + let mut cursor = Some(parent); + while let Some(directory) = cursor { + chain.push(directory.to_path_buf()); + if exists(directory) { + break; + } + cursor = directory.parent(); + } + chain +} + /// The publisher's refusal: a retryable `INTERNAL_ERROR` — nothing the settlement leg staged /// is durable yet, so the same review can be repeated once the medium is writable. fn spoke_reject(message: String) -> spoke_operations::SpokeReject { @@ -95,3 +121,52 @@ fn spoke_reject(message: String) -> spoke_operations::SpokeReject { details: Some(details), } } + +#[cfg(test)] +mod tests { + use super::durable_chain; + use std::path::{Path, PathBuf}; + + fn paths(chain: &[PathBuf]) -> Vec<&str> { + chain + .iter() + .map(|path| path.to_str().expect("utf-8")) + .collect() + } + + /// A root that does not exist yet is itself a created entry: the chain reaches its + /// pre-existing parent, so syncing the chain persists the root's own directory entry + /// as well as the entries beneath it. + #[test] + fn a_created_root_chain_reaches_its_existing_parent() { + let parent = Path::new("/scratch/one/two/records"); + let chain = durable_chain(parent, |directory| directory == Path::new("/scratch")); + assert_eq!( + paths(&chain), + vec![ + "/scratch/one/two/records", + "/scratch/one/two", + "/scratch/one", + "/scratch" + ], + "deepest first, ending at the nearest existing ancestor" + ); + } + + /// Nothing created: only the target's own parent is synced, and no ancestor is touched. + #[test] + fn an_existing_parent_chain_stops_at_it() { + let parent = Path::new("/scratch/one/two/records"); + let chain = durable_chain(parent, |_| true); + assert_eq!(paths(&chain), vec!["/scratch/one/two/records"]); + } + + /// The chain walks to the filesystem root when nothing on the way exists: the root is the + /// last existing ancestor and is synced too. + #[test] + fn a_chain_with_no_existing_ancestor_ends_at_the_root() { + let parent = Path::new("/one/two"); + let chain = durable_chain(parent, |directory| directory == Path::new("/")); + assert_eq!(paths(&chain), vec!["/one/two", "/one", "/"]); + } +} diff --git a/crates/mindcore-runtime/src/mind.rs b/crates/mindcore-runtime/src/mind.rs index 3c8d931..7e36917 100644 --- a/crates/mindcore-runtime/src/mind.rs +++ b/crates/mindcore-runtime/src/mind.rs @@ -276,13 +276,55 @@ impl Mind { } }; - // 1–2. Stage the review on one transaction. A replay of a receipt already settled - // answers `Ready` and is returned as it is. The request must be byte-identical across - // replays of one key — the adapter's dedup probe digests the whole payload — so - // `expected_revision` is the constant a pending candidate always carries (capture - // writes revision 1 and nothing mutates a pending candidate), never a fresh read of - // the row: reading it would send 2 after the consumption bumped it and the replay - // would answer `IdempotencyConflict` instead of the recorded receipt. + // 1. Read the candidate as the plan requires: the revision this staging transaction + // must assert, and whether an earlier review already consumed it. A refusal is the + // adapter's own and rolls the transaction back. + let observed = self + .adapter + .get_candidate( + &mut transaction, + &caller, + json!({ "space_id": space.as_str(), "candidate_id": candidate_id }), + ) + .await; + let (revision, consumed) = match observed { + SpokeResult::Ok(MemoryStage::Ready(body)) => { + let Some(candidate) = body.get("candidate") else { + drop(transaction); + return retryable_internal("the candidate body carries no candidate"); + }; + let Some(revision) = candidate.get("revision").and_then(Value::as_u64) else { + drop(transaction); + return retryable_internal("the candidate body carries no integer revision"); + }; + let consumed = candidate.get("status").and_then(Value::as_str) == Some("consumed"); + (revision, consumed) + } + SpokeResult::Ok(stage) => { + drop(transaction); + return retryable_internal(format!( + "candidate read answered an unexpected stage: {stage:?}" + )); + } + SpokeResult::Reject(reject) => { + drop(transaction); + return SpokeResult::Reject(reject); + } + }; + // 2. Stage on the same transaction. The adapter's dedup probe keys on + // (space, requester, operation, idempotency_key) and digests the whole payload, so + // a same-key replay must rebuild a byte-identical request to reach the recorded + // receipt. A consumed candidate's pre-consumption revision is exactly one less — + // consumption is a candidate's only revision bump — and that is the only revision + // any recorded review payload for this candidate can carry; a still-pending + // candidate (including one imported at a non-1 revision) stages at its own live + // revision. A different decision under one key still changes the digest and stays + // an `IdempotencyConflict`. + let expected_revision = if consumed { + revision.saturating_sub(1).max(1) + } else { + revision + }; let decision = match serde_json::to_value(decision) { Ok(decision) => decision, Err(error) => { @@ -299,7 +341,7 @@ impl Mind { "space_id": space.as_str(), "candidate_id": candidate_id, "decision": decision, - "expected_revision": 1, + "expected_revision": expected_revision, "idempotency_key": idempotency_key, }), ) diff --git a/crates/mindcore-runtime/tests/mind.rs b/crates/mindcore-runtime/tests/mind.rs index 5308c05..bdad1ef 100644 --- a/crates/mindcore-runtime/tests/mind.rs +++ b/crates/mindcore-runtime/tests/mind.rs @@ -486,3 +486,84 @@ async fn a_refused_settle_answers_outcome_uncertain_and_leaves_the_intent_pendin "the staged record is durable" ); } + +/// The plan's step 1 is a real read of the candidate: a pending candidate imported at a +/// non-1 revision stages at that revision, and its settled same-key replay still reaches the +/// recorded receipt. A constant `expected_revision` would refuse the first call with +/// `RevisionConflict`. +#[tokio::test] +async fn a_pending_candidate_at_a_non_one_revision_reviews_and_replays() { + let (dir, store) = fixture().await; + let owner = CallerId::new(OWNER); + let created = ok(minds::create(&store, &request(OWNER)).await); + ensure_subject(&store, created.id.as_str()).await; + let handle = ok(Mind::open(&store, &owner, &created.id).await) + .with_journal_publisher(journal_dir(dir.path())); + let candidate_id = + capture_candidate(&handle, "cap-imported-revision", "imported at five").await; + + // An imported candidate keeps its own revision (transfer/activate.rs): make this one 5. + sqlx::query("UPDATE memory_candidates SET revision = 5 WHERE candidate_id = ?") + .bind(&candidate_id) + .execute(&store.pool()) + .await + .expect("raise the pending candidate revision"); + + let reviewed = ok(handle + .review(&candidate_id, &promote(), "rev-imported-revision") + .await); + let receipt = value_of(&reviewed); + assert_eq!( + receipt["status"], "committed", + "revision 5 stages and settles" + ); + let stored: i64 = + sqlx::query_scalar("SELECT revision FROM memory_candidates WHERE candidate_id = ?") + .bind(&candidate_id) + .fetch_one(&store.pool()) + .await + .expect("the consumed candidate row"); + assert_eq!(stored, 6, "consumption bumped the imported revision"); + + let replayed = ok(handle + .review(&candidate_id, &promote(), "rev-imported-revision") + .await); + assert_eq!( + value_of(&replayed), + receipt, + "the same key replays the recorded receipt after a non-1 revision" + ); + let different = + serde_json::from_value::(json!({ "action": "drop" })).expect("drop decision"); + let conflict = reject_of( + handle + .review(&candidate_id, &different, "rev-imported-revision") + .await, + ); + assert_eq!( + conflict.code, + SpokeRejectCode::IdempotencyConflict, + "a different decision under one key still refuses" + ); +} + +/// The public publisher creates a root that does not exist yet and leaves the target's exact +/// bytes at the target's own path; the durable directory chain it syncs is unit-tested in +/// `journal.rs` (deepest created directory first, ending at the nearest existing ancestor). +#[tokio::test] +async fn the_public_publisher_creates_and_publishes_a_nested_root() { + let dir = TempDir::new().expect("temporary directory"); + let root = dir.path().join("nested/publish/root"); + assert!(!root.exists(), "the root starts absent"); + let publisher = mindcore_runtime::journal_dir(&root); + publisher(&[json!({ + "path": "records/rec_nested.md", + "content": "exact published bytes", + })]) + .expect("publish into a root that does not exist yet"); + assert_eq!( + std::fs::read_to_string(root.join("records").join("rec_nested.md")) + .expect("the published target"), + "exact published bytes" + ); +} From 2d588abc480747bfe2b891bcdcf55664b726217d Mon Sep 17 00:00:00 2001 From: Tang Bohao Date: Thu, 26 Nov 2026 08:57:24 +0800 Subject: [PATCH 05/22] Sync the journal's whole ancestry on every publish and anchor relative roots at the current directory (mind-facade T2 third review) --- crates/mindcore-runtime/src/journal.rs | 167 ++++++++++++++++++------- crates/mindcore-runtime/tests/mind.rs | 28 +++++ 2 files changed, 147 insertions(+), 48 deletions(-) diff --git a/crates/mindcore-runtime/src/journal.rs b/crates/mindcore-runtime/src/journal.rs index 0906b38..cf6dc3b 100644 --- a/crates/mindcore-runtime/src/journal.rs +++ b/crates/mindcore-runtime/src/journal.rs @@ -8,11 +8,14 @@ use serde_json::Value; /// A file publisher over `root`: each target's `content` bytes land at `root` joined with the /// target's `path`, parent directories are created, and `Ok(())` is returned only when every -/// target's exact bytes are durable — the file contents are synced to disk, and so is every -/// directory entry the publication created, up to and including the nearest ancestor that -/// already existed when publication began. `root` itself may be created here: its entry in -/// its parent is synced as part of that chain, so a crash cannot leave a settled intent -/// naming a tree the medium no longer holds. +/// target's exact bytes are durable. +/// +/// Durability covers the whole required ancestry of each target, deepest first, through a +/// bounded anchor: the filesystem root for an absolute path, the current directory for a +/// relative one. The ancestry is a function of the target's path alone — never of which +/// directories happen to exist — so a retry after a publication that failed between creating +/// directories and syncing them is never weaker than the attempt that failed: it syncs the +/// same chain, including the entries the failed attempt left behind. /// /// Target paths are the adapter's own (`records/.md`, `candidates/.md`, /// `profiles/.md`): they carry no separators that could escape `root`, and they are @@ -33,15 +36,13 @@ pub fn journal_dir( SpiError::InvalidInput(format!("journal target {path} carries no content")) })?; let file = root.join(path); - let Some(parent) = file.parent() else { - return Err(SpiError::InvalidInput(format!( - "journal target {path} has no parent directory" - ))); + // A target at the publisher root has the empty path as its parent; the current + // directory is what that names, and it is this publication's anchor. + let parent = match file.parent() { + Some(parent) if !parent.as_os_str().is_empty() => parent, + _ => Path::new("."), }; - // Decide the durable chain before creating anything: every directory that does - // not exist yet, deepest first, and the nearest ancestor that does — its entry is - // the one a newly created topmost directory lands in. - let chain = durable_chain(parent, Path::exists); + let chain = durable_chain(parent); std::fs::create_dir_all(parent).map_err(|error| { SpiError::Settlement(spoke_reject(format!( "the directory for {path} could not be created: {error}" @@ -53,8 +54,8 @@ pub fn journal_dir( ))) })?; // Durability, not visibility: the write must reach the medium before the caller - // may settle the intent. Sync the file's contents, then each directory entry the - // publication created, deepest first. + // may settle the intent. Sync the file's contents, then the whole ancestry the + // target's entry depends on, deepest first. std::fs::File::open(&file) .and_then(|file| file.sync_all()) .map_err(|error| { @@ -64,7 +65,7 @@ pub fn journal_dir( })?; for directory in &chain { std::fs::File::open(directory) - .and_then(|dir| dir.sync_all()) + .and_then(|directory| directory.sync_all()) .map_err(|error| { SpiError::Settlement(spoke_reject(format!( "the directory {} could not be synced: {error}", @@ -87,22 +88,31 @@ pub fn journal_dir( } } -/// The directories whose entries must be durable for one target to count as published, -/// deepest first: every directory from `parent` upward that `exists` reports as absent — -/// these are the ones the publication creates — and the nearest ancestor that already exists, -/// whose entry names the topmost created directory. Stops at an existing directory, or at the -/// filesystem root when nothing on the way exists yet. +/// The directories whose entries one target depends on, deepest first, through the bounded +/// anchor of its path: every ancestor named by the path, and then `/` for an absolute path or +/// `.` for a relative one. /// -/// `exists` is a parameter so the ordering is provable without touching a filesystem. -fn durable_chain(parent: &Path, mut exists: impl FnMut(&Path) -> bool) -> Vec { +/// Existence is deliberately not consulted: the chain is the same for a first attempt and for +/// a retry after a failed attempt left some of those directories behind, so a retry can never +/// skip a directory entry the failed attempt created. +fn durable_chain(parent: &Path) -> Vec { let mut chain = Vec::new(); - let mut cursor = Some(parent); - while let Some(directory) = cursor { - chain.push(directory.to_path_buf()); - if exists(directory) { + let mut cursor = parent.to_path_buf(); + loop { + if cursor.as_os_str().is_empty() { + chain.push(PathBuf::from(".")); + break; + } + let at_anchor = cursor == Path::new("."); + chain.push(cursor.clone()); + if at_anchor { break; } - cursor = directory.parent(); + match cursor.parent() { + Some(ancestor) => cursor = ancestor.to_path_buf(), + // An absolute path's anchor `/` has no parent and was already pushed. + None => break, + } } chain } @@ -124,7 +134,8 @@ fn spoke_reject(message: String) -> spoke_operations::SpokeReject { #[cfg(test)] mod tests { - use super::durable_chain; + use super::{durable_chain, journal_dir}; + use serde_json::json; use std::path::{Path, PathBuf}; fn paths(chain: &[PathBuf]) -> Vec<&str> { @@ -134,39 +145,99 @@ mod tests { .collect() } - /// A root that does not exist yet is itself a created entry: the chain reaches its - /// pre-existing parent, so syncing the chain persists the root's own directory entry - /// as well as the entries beneath it. + /// An absolute ancestry runs deepest first through `/`, even when nothing exists yet. #[test] - fn a_created_root_chain_reaches_its_existing_parent() { - let parent = Path::new("/scratch/one/two/records"); - let chain = durable_chain(parent, |directory| directory == Path::new("/scratch")); + fn an_absolute_chain_ends_at_the_filesystem_root() { + let chain = durable_chain(Path::new("/scratch/one/two/records")); assert_eq!( paths(&chain), vec![ "/scratch/one/two/records", "/scratch/one/two", "/scratch/one", - "/scratch" + "/scratch", + "/" ], - "deepest first, ending at the nearest existing ancestor" + "every named ancestor, then the anchor" + ); + } + + /// A relative ancestry anchors at the current directory: the empty parent path never + /// reaches `File::open`, and no path in the chain is empty. + #[test] + fn a_relative_chain_anchors_at_the_current_directory() { + let chain = durable_chain(Path::new("journal/records")); + assert_eq!(paths(&chain), vec!["journal/records", "journal", "."]); + assert!( + chain.iter().all(|path| !path.as_os_str().is_empty()), + "an empty path can never be opened" ); } - /// Nothing created: only the target's own parent is synced, and no ancestor is touched. + /// `journal_dir("journal")` builds `journal/records/…` style parents, so the relative + /// anchor is exercised exactly as the first publication of such a root would. #[test] - fn an_existing_parent_chain_stops_at_it() { - let parent = Path::new("/scratch/one/two/records"); - let chain = durable_chain(parent, |_| true); - assert_eq!(paths(&chain), vec!["/scratch/one/two/records"]); + fn a_relative_parent_under_the_current_directory_stops_at_it() { + assert_eq!( + paths(&durable_chain(Path::new("./records"))), + vec!["./records", "."] + ); + assert_eq!(paths(&durable_chain(Path::new("."))), vec!["."]); } - /// The chain walks to the filesystem root when nothing on the way exists: the root is the - /// last existing ancestor and is synced too. + /// The chain depends on the path, never on which directories already exist: this is what + /// keeps a retry from being weaker than a failed first attempt. #[test] - fn a_chain_with_no_existing_ancestor_ends_at_the_root() { - let parent = Path::new("/one/two"); - let chain = durable_chain(parent, |directory| directory == Path::new("/")); - assert_eq!(paths(&chain), vec!["/one/two", "/one", "/"]); + fn the_chain_is_identical_before_and_after_the_directories_exist() { + let directory = tempfile::TempDir::new().expect("temporary directory"); + let parent = directory.path().join("one/two/records"); + let before = durable_chain(&parent); + std::fs::create_dir_all(&parent).expect("create the tree"); + let after = durable_chain(&parent); + assert_eq!( + paths(&before), + paths(&after), + "a retry sees the same chain as the attempt that created the tree" + ); + } + + /// The failure/retry boundary: a refusal after an earlier target already created a tree + /// leaves directories behind; the retry syncs the same chain and lands both targets. + #[test] + fn a_retry_after_a_refused_publication_syncs_the_same_chain() { + let directory = tempfile::TempDir::new().expect("temporary directory"); + let root = directory.path().to_path_buf(); + let parent = root.join("nested").join("records"); + let before = durable_chain(&parent); + + let publish = journal_dir(&root); + let refused = publish(&[ + json!({ "path": "nested/records/one.md", "content": "one" }), + // The second target has no content: the first has already landed and created the + // tree when this one is refused. + json!({ "path": "nested/records/two.md" }), + ]); + assert!( + refused.is_err(), + "the malformed target refuses the publication" + ); + assert!(parent.is_dir(), "the failed attempt created the tree"); + + let after = durable_chain(&parent); + assert_eq!( + paths(&before), + paths(&after), + "the retry syncs the same ancestry, including what the failed attempt created" + ); + + publish(&[ + json!({ "path": "nested/records/one.md", "content": "one" }), + json!({ "path": "nested/records/two.md", "content": "two" }), + ]) + .expect("the retry publishes"); + assert_eq!( + std::fs::read_to_string(parent.join("two.md")).expect("the retried target"), + "two" + ); } } diff --git a/crates/mindcore-runtime/tests/mind.rs b/crates/mindcore-runtime/tests/mind.rs index bdad1ef..a3c1a62 100644 --- a/crates/mindcore-runtime/tests/mind.rs +++ b/crates/mindcore-runtime/tests/mind.rs @@ -567,3 +567,31 @@ async fn the_public_publisher_creates_and_publishes_a_nested_root() { "exact published bytes" ); } + +/// A relative root is anchored at the current directory: a root that does not exist yet is +/// created and published instead of refusing on the empty parent path. The scratch tree sits +/// directly under the package root cargo runs tests from — no pre-existing intermediate can +/// stand in for the current-directory anchor — and is removed before the assertions. +#[tokio::test] +async fn the_public_publisher_handles_a_relative_root_that_does_not_exist_yet() { + let unique = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .expect("a clock after the epoch") + .as_nanos(); + let relative = format!("journal-relative-{}-{unique}", std::process::id()); + let root = std::path::PathBuf::from(&relative); + assert!(!root.exists(), "the relative root starts absent"); + let publisher = mindcore_runtime::journal_dir(&relative); + let published = publisher(&[json!({ + "path": "records/rec_relative.md", + "content": "relative root bytes", + })]); + let read_back = std::fs::read_to_string(root.join("records").join("rec_relative.md")); + std::fs::remove_dir_all(&root).ok(); + published.expect("a relative root publishes"); + assert_eq!( + read_back.expect("the published target"), + "relative root bytes", + "the relative root holds the target at its own path" + ); +} From c0ccfec5f01e4c8712037ba75d2fd87377e6ee03 Mon Sep 17 00:00:00 2001 From: Tang Bohao Date: Thu, 26 Nov 2026 09:04:28 +0800 Subject: [PATCH 06/22] mind facade: knowledge operations on the handle - move the binding's require_knowledge_grants onto MemoryAdapter::require_space_grants; the binding calls it - knowledge_get/knowledge_put/knowledge_list admit under it on their own transaction, then read or write through read_entry, read_entry_at_revision, write_entry and list_entries_in on the cached collection; revisions and refusals are the store's own - read_entry_at_revision is the private read_entry_revision made public - tests: write then read by revision, StoredRevisionStale on a stale base, no-write grant refused with the row untouched, no-read grant reads nothing --- crates/mindcore-runtime/src/mind.rs | 143 +++++++++++++++++++- crates/mindcore-runtime/tests/mind.rs | 173 +++++++++++++++++++++++- crates/mindcore-spoke/src/lib.rs | 41 +++++- crates/mindcore-spoke/src/workflows.rs | 41 +----- crates/mindcore-sqlite/src/knowledge.rs | 6 +- crates/mindcore-sqlite/src/lib.rs | 6 +- 6 files changed, 363 insertions(+), 47 deletions(-) diff --git a/crates/mindcore-runtime/src/mind.rs b/crates/mindcore-runtime/src/mind.rs index 7e36917..3898602 100644 --- a/crates/mindcore-runtime/src/mind.rs +++ b/crates/mindcore-runtime/src/mind.rs @@ -10,6 +10,12 @@ //! durable so a refused publication leaves no record, then settle the receipt on a second //! transaction. No method takes a collection, an owner or a viewpoint, and none chooses a //! subject: the caller names it every time. +//! +//! The knowledge operations compose the scoped store the same way: each admits the caller under +//! `MemoryAdapter::require_space_grants` on its own transaction — space-wide `knowledge_read` for +//! the reads, `knowledge_write` for the put — then reads or writes through the store's +//! borrowed-transaction entry points on that same transaction, against the collection the row +//! resolved at open. Revisions and refusals are the store's own. use chrono::{DateTime, Utc}; use serde_json::{json, Map, Value}; @@ -20,11 +26,15 @@ use mindcore_base::ir::MemoryRepository; use mindcore_spi::SpiError; use mindcore_spoke::{MemoryAdapter, MemoryStage}; use mindcore_sqlite::minds::Mind as MindRow; -use mindcore_sqlite::{MindStore, SqliteMemoryRepository}; +use mindcore_sqlite::{ + list_entries_in, read_entry, read_entry_at_revision, write_entry, MindStore, + SqliteMemoryRepository, +}; use spoke_operations::{SpokeReject, SpokeRejectCode, SpokeResult}; use spoke_schemas::memory_candidates_review_request::Decision; use spoke_schemas::{ - MemoryCandidatesReviewResponse, MemoryCaptureResponse, MemoryRecallResponse, Principal, + KnowledgeEntry, MemoryCandidatesReviewResponse, MemoryCaptureResponse, MemoryRecallResponse, + Principal, }; use sqlx::SqlitePool; @@ -241,6 +251,135 @@ impl Mind { ready(stage) } + /// Read one entry of this Mind's collection: `knowledge_read` admitted on one read + /// transaction, then the store's `read_entry` — or `read_entry_at_revision` when a + /// revision is named — on it, rolled back after the read. + pub async fn knowledge_get( + &self, + entry_id: &str, + revision: Option, + ) -> SpokeResult { + let mut transaction = match self.pool.begin().await { + Ok(transaction) => transaction, + Err(error) => { + return retryable_internal(format!( + "knowledge read transaction could not begin: {error}" + )) + } + }; + if let Err(error) = self + .adapter + .require_space_grants( + &mut transaction, + &principal(&self.caller), + self.row.id.as_str(), + &["knowledge_read"], + ) + .await + { + drop(transaction); + return match error { + SpiError::Settlement(reject) => SpokeResult::Reject(reject), + other => retryable_internal(format!("knowledge admission failed: {other}")), + }; + } + let result = match revision { + Some(revision) => { + read_entry_at_revision( + &mut transaction, + &self.row.knowledge.collection, + entry_id, + revision, + ) + .await + } + None => read_entry(&mut transaction, &self.row.knowledge.collection, entry_id).await, + }; + drop(transaction); + result + } + + /// Write one entry of this Mind's collection: `knowledge_write` admitted on one + /// immediate-write transaction, then the store's `write_entry` on it, committed. The + /// revision check and every refusal are the store's own. + pub async fn knowledge_put( + &self, + entry: KnowledgeEntry, + expected_base_revision: Option, + ) -> SpokeResult { + let mut transaction = match self.pool.begin_with("BEGIN IMMEDIATE").await { + Ok(transaction) => transaction, + Err(error) => { + return retryable_internal(format!( + "knowledge write transaction could not begin: {error}" + )) + } + }; + if let Err(error) = self + .adapter + .require_space_grants( + &mut transaction, + &principal(&self.caller), + self.row.id.as_str(), + &["knowledge_write"], + ) + .await + { + drop(transaction); + return match error { + SpiError::Settlement(reject) => SpokeResult::Reject(reject), + other => retryable_internal(format!("knowledge admission failed: {other}")), + }; + } + let written = write_entry( + &mut transaction, + &self.row.knowledge.collection, + entry, + expected_base_revision, + ) + .await; + if written.is_reject() { + drop(transaction); + return written; + } + if let Err(error) = transaction.commit().await { + return uncertain(format!("knowledge write committed an unknown outcome: {error}")); + } + written + } + + /// Every entry of this Mind's collection: `knowledge_read` admitted on one read + /// transaction, then the store's `list_entries_in` on it, rolled back after the read. + pub async fn knowledge_list(&self) -> SpokeResult> { + let mut transaction = match self.pool.begin().await { + Ok(transaction) => transaction, + Err(error) => { + return retryable_internal(format!( + "knowledge list transaction could not begin: {error}" + )) + } + }; + if let Err(error) = self + .adapter + .require_space_grants( + &mut transaction, + &principal(&self.caller), + self.row.id.as_str(), + &["knowledge_read"], + ) + .await + { + drop(transaction); + return match error { + SpiError::Settlement(reject) => SpokeResult::Reject(reject), + other => retryable_internal(format!("knowledge admission failed: {other}")), + }; + } + let entries = list_entries_in(&mut transaction, &self.row.knowledge.collection).await; + drop(transaction); + entries + } + /// Review one pending candidate and answer the settled receipt, not a `MemoryStage`. /// /// The fold stages the whole decision inside one immediate-write transaction, reads the diff --git a/crates/mindcore-runtime/tests/mind.rs b/crates/mindcore-runtime/tests/mind.rs index a3c1a62..1d0fb1f 100644 --- a/crates/mindcore-runtime/tests/mind.rs +++ b/crates/mindcore-runtime/tests/mind.rs @@ -3,14 +3,20 @@ //! Mind opening because the handle acts on no status from the row. use mindcore_base::boundary::CallerId; -use mindcore_base::ids::{MindId, SpaceId}; +use mindcore_base::ids::{mint, MindId, SpaceId}; +use mindcore_base::ir::MemoryGrantRow; use mindcore_base::ir::MemoryRepository; use mindcore_runtime::journal_dir; use mindcore_runtime::minds::{self, CreateMind}; use mindcore_runtime::{Capture, Mind, Recall}; use mindcore_spi::SpiError; use mindcore_sqlite::{MindStore, SqliteMemoryRepository}; -use serde_json::{json, Number, Value}; +use chrono::Utc; +use serde_json::{json, Map, Number, Value}; +use spoke_schemas::data::knowledge_entry::{ + KnowledgeEntryBody, KnowledgeEntryCanonicalName, +}; +use spoke_schemas::KnowledgeEntry; use spoke_operations::{SpokeReject, SpokeRejectCode, SpokeResult}; use spoke_schemas::memory_candidates_review_request::Decision; use std::sync::mpsc; @@ -595,3 +601,166 @@ async fn the_public_publisher_handles_a_relative_root_that_does_not_exist_yet() "the relative root holds the target at its own path" ); } + +// ---------- Task 3: knowledge operations on the handle ---------- + +/// One plain entry the test writes; the store assigns and checks the revision. +fn entry(entry_id: &str, name: &str) -> KnowledgeEntry { + KnowledgeEntry { + adoption_anchor: None, + body: KnowledgeEntryBody::default(), + canonical_name: KnowledgeEntryCanonicalName::try_from(name.to_string()) + .expect("a valid canonical name"), + created_at: None, + disclosure: None, + entry_id: entry_id.to_string(), + entry_type: "character".to_string(), + extensions: std::collections::HashMap::new(), + modules: std::collections::HashMap::new(), + owner: None, + revision: Some(1), + // SAFETY: the wire baseline one is not zero. + schema_version: unsafe { std::num::NonZeroU64::new_unchecked(1) }, + source_anchor: None, + status: "confirmed".to_string(), + updated_at: None, + } +} + +/// One extra live grant row for `principal` in the Mind's space, carrying only +/// `capabilities` — the limited callers of the refusal tests. +async fn grant(store: &MindStore, space_id: &str, principal: &str, capabilities: &[&str]) { + let row = MemoryGrantRow { + grant_id: mint("grt"), + space_id: SpaceId::new(space_id), + subject_id: None, + principal_id: CallerId::new(principal), + capabilities: capabilities.iter().map(|capability| capability.to_string()).collect(), + context_ids: Vec::new(), + shared_access: false, + expires_at: None, + revoked_at: None, + revision: Number::from(1), + created_at: Utc::now().to_rfc3339(), + extensions: Map::new(), + }; + let mut tx = store.pool().begin().await.expect("begin the grant write"); + SqliteMemoryRepository + .insert_grant(&mut tx, &row) + .await + .expect("insert the grant"); + tx.commit().await.expect("commit the grant"); +} + +#[tokio::test] +async fn knowledge_write_then_read_by_revision_answers_the_stored_entry() { + let (_dir, store) = fixture().await; + let owner = CallerId::new(OWNER); + let created = ok(minds::create(&store, &request(OWNER)).await); + let handle = ok(Mind::open(&store, &owner, &created.id).await); + + let written = ok(handle + .knowledge_put(entry("ke_fact", "fact one"), None) + .await); + assert_eq!(written.revision, Some(1), "the create assigns revision 1"); + + let current = ok(handle.knowledge_get("ke_fact", None).await); + assert_eq!(current.entry_id, "ke_fact"); + assert_eq!(current.revision, Some(1)); + + let at_revision = ok(handle.knowledge_get("ke_fact", Some(1)).await); + assert_eq!( + at_revision.entry_id, "ke_fact", + "the revision read answers the stored entry" + ); + assert_eq!(at_revision.revision, Some(1)); + + let listed = ok(handle.knowledge_list().await); + assert!( + listed.iter().any(|entry| entry.entry_id == "ke_fact"), + "the list carries the written entry beside the carrier" + ); + assert!( + listed.iter().any(|entry| entry.entry_id == created.carrier_entry_id), + "the list reads the Mind's own collection, carrier included" + ); +} + +#[tokio::test] +async fn a_stale_revision_refuses_stored_revision_stale() { + let (_dir, store) = fixture().await; + let owner = CallerId::new(OWNER); + let created = ok(minds::create(&store, &request(OWNER)).await); + let handle = ok(Mind::open(&store, &owner, &created.id).await); + + ok(handle.knowledge_put(entry("ke_fact", "fact one"), None).await); + ok(handle + .knowledge_put(entry("ke_fact", "fact two"), Some(1)) + .await); + + assert_eq!( + reject_code(handle.knowledge_put(entry("ke_fact", "fact three"), Some(1)).await), + SpokeRejectCode::StoredRevisionStale, + "a put against a moved revision refuses the store's own stale refusal" + ); + let current = ok(handle.knowledge_get("ke_fact", None).await); + assert_eq!(current.revision, Some(2), "the refused write never landed"); +} + +#[tokio::test] +async fn a_caller_without_knowledge_write_is_refused_and_the_row_is_untouched() { + let (_dir, store) = fixture().await; + let owner = CallerId::new(OWNER); + let created = ok(minds::create(&store, &request(OWNER)).await); + let owner_handle = ok(Mind::open(&store, &owner, &created.id).await); + ok(owner_handle + .knowledge_put(entry("ke_fact", "fact one"), None) + .await); + + let reader = CallerId::new("caller_reader"); + grant(&store, created.id.as_str(), "caller_reader", &["knowledge_read"]).await; + let reader_handle = ok(Mind::open(&store, &reader, &created.id).await); + + let refuse = reject_of(reader_handle + .knowledge_put(entry("ke_fact", "defaced"), Some(1)) + .await); + assert_eq!( + refuse.code, + SpokeRejectCode::NotAuthorized, + "a caller without knowledge_write is refused" + ); + + let after = ok(owner_handle.knowledge_get("ke_fact", None).await); + assert_eq!(after.revision, Some(1), "the row is untouched"); + assert_eq!( + after.canonical_name.as_str(), + "fact one", + "the payload the refused caller targeted is unchanged" + ); +} + +#[tokio::test] +async fn a_caller_without_knowledge_read_reads_nothing() { + let (_dir, store) = fixture().await; + let owner = CallerId::new(OWNER); + let created = ok(minds::create(&store, &request(OWNER)).await); + let owner_handle = ok(Mind::open(&store, &owner, &created.id).await); + ok(owner_handle + .knowledge_put(entry("ke_fact", "fact one"), None) + .await); + + let writer = CallerId::new("caller_writer"); + grant(&store, created.id.as_str(), "caller_writer", &["knowledge_write"]).await; + let writer_handle = ok(Mind::open(&store, &writer, &created.id).await); + + assert_eq!( + reject_code(writer_handle.knowledge_get("ke_fact", None).await), + SpokeRejectCode::NotAuthorized, + "a caller without knowledge_read reads no entry" + ); + assert_eq!( + reject_code(writer_handle.knowledge_list().await), + SpokeRejectCode::NotAuthorized, + "a caller without knowledge_read reads no list" + ); +} diff --git a/crates/mindcore-spoke/src/lib.rs b/crates/mindcore-spoke/src/lib.rs index 950f21c..88877e4 100644 --- a/crates/mindcore-spoke/src/lib.rs +++ b/crates/mindcore-spoke/src/lib.rs @@ -27,13 +27,15 @@ pub use workflows::MemoryWorkflowBinding; pub(crate) use mindcore_base::ids::mint; +use chrono::Utc; use serde::de::DeserializeOwned; use serde_json::Value; -use spoke_operations::{SpokeRejectCode, SpokeResult}; +use spoke_operations::{GrantRequirement, SpokeRejectCode, SpokeResult}; use spoke_schemas::Principal; use sqlx::{Sqlite, Transaction}; use mindcore_base::ids::{SpaceId, SubjectId}; +use mindcore_spi::SpiError; use mindcore_base::ir::{MemoryRepository, ReceiptFailure, ReceiptState, ReviewReceiptIr}; use mindcore_sqlite::SqliteMemoryRepository; @@ -218,6 +220,43 @@ impl MemoryAdapter { Ok(()) } } + + /// `principal`'s own live grant for every one of `capabilities` in `space_id`, on `tx`. + /// + /// Live grants are re-derived on every call, so a read after provider work runs the same + /// admission and a revoked grant refuses it. A memory grant never substitutes for a + /// knowledge capability: only a capability the caller names admits its principal. + pub async fn require_space_grants( + &self, + tx: &mut Tx<'_>, + principal: &Principal, + space_id: &str, + capabilities: &[&str], + ) -> Result<(), SpiError> { + let caller = principal_id(principal); + let space = SpaceId::new(space_id.to_string()); + let rows = admission::grants(&self.repository, tx, &space) + .await + .map_err(|reject| SpiError::Settlement(reject.into_spoke()))?; + let grants = admission::wire_grants(&rows) + .map_err(|reject| SpiError::Settlement(reject.into_spoke()))?; + for capability in capabilities { + let requirement = GrantRequirement { + capability, + subject_id: None, + context_ids: Vec::new(), + reads_shared: false, + subject_all: false, + }; + if !admission::covered(&grants, caller, space.as_str(), Utc::now(), &requirement) { + return Err(SpiError::Settlement(Reject::not_authorized(format!( + "principal {caller} holds no live {capability} grant in space {}", + space.as_str() + )).into_spoke())); + } + } + Ok(()) + } } /// The authenticated principal the caller supplied; never payload-asserted. diff --git a/crates/mindcore-spoke/src/workflows.rs b/crates/mindcore-spoke/src/workflows.rs index b3db197..0d7b19d 100644 --- a/crates/mindcore-spoke/src/workflows.rs +++ b/crates/mindcore-spoke/src/workflows.rs @@ -12,7 +12,7 @@ use async_trait::async_trait; use chrono::Utc; use serde_json::{json, Map, Value}; use spoke_operations::{ - knowledge_entry_visible_to_viewpoint, GrantRequirement, SpokeReject, SpokeRejectCode, + knowledge_entry_visible_to_viewpoint, SpokeReject, SpokeRejectCode, SpokeResult, }; use spoke_schemas::data::cognition::{CognitionReference, CognitionReferenceKind}; @@ -347,39 +347,6 @@ impl MemoryWorkflowBinding { self.knowledge_routes.get(principal_id(principal)) } - /// `principal`'s own live grant for every one of `capabilities` in `space_id`, on `tx`. - /// - /// Live grants are re-derived on every call, so a read after provider work runs the same - /// admission and a revoked grant refuses it. A memory grant never substitutes for this, and a - /// knowledge read never stands in for [`KNOWLEDGE_WRITE`]. - async fn require_knowledge_grants( - &self, - tx: &mut Tx<'_>, - principal: &Principal, - space_id: &str, - capabilities: &[&str], - ) -> Result<(), SpiError> { - let caller = principal_id(principal); - let space = SpaceId::new(space_id.to_string()); - let grants = self.space_grants(tx, space_id).await?; - for capability in capabilities { - let requirement = GrantRequirement { - capability, - subject_id: None, - context_ids: Vec::new(), - reads_shared: false, - subject_all: false, - }; - if !admission::covered(&grants, caller, space.as_str(), Utc::now(), &requirement) { - return Err(not_authorized(format!( - "principal {caller} holds no live {capability} grant in space {}", - space.as_str() - ))); - } - } - Ok(()) - } - /// The collection the carrier write serves: `principal` must have a route and hold a live /// grant for every one of `capabilities` in `space_id`. /// @@ -399,7 +366,8 @@ impl MemoryWorkflowBinding { .ok_or_else(|| { not_authorized("principal has no workflow knowledge route".to_string()) })?; - self.require_knowledge_grants(tx, principal, space_id, capabilities) + self.adapter + .require_space_grants(tx, principal, space_id, capabilities) .await?; Ok(collection) } @@ -456,7 +424,8 @@ impl MemoryWorkflowBinding { return Ok(Vec::new()); }; match self - .require_knowledge_grants(tx, principal, request.space_id.as_str(), &[KNOWLEDGE_READ]) + .adapter + .require_space_grants(tx, principal, request.space_id.as_str(), &[KNOWLEDGE_READ]) .await { Ok(()) => {} diff --git a/crates/mindcore-sqlite/src/knowledge.rs b/crates/mindcore-sqlite/src/knowledge.rs index 3285726..bf3ec3a 100644 --- a/crates/mindcore-sqlite/src/knowledge.rs +++ b/crates/mindcore-sqlite/src/knowledge.rs @@ -147,7 +147,7 @@ impl ScopedKnowledgeStore { )) } }; - match read_entry_revision(&mut tx, &self.scope.collection, entry_id, revision).await { + match read_entry_at_revision(&mut tx, &self.scope.collection, entry_id, revision).await { SpokeResult::Ok(entry) => match tx.commit().await { Ok(()) => SpokeResult::Ok(entry), Err(error) => internal(format!( @@ -753,7 +753,7 @@ impl RoutedKnowledgeStore { SpokeResult::Reject(reject) => return SpokeResult::Reject(reject), } let entry = - match read_entry_revision(&mut tx, &self.scope.collection, entity_id, revision).await { + match read_entry_at_revision(&mut tx, &self.scope.collection, entity_id, revision).await { SpokeResult::Ok(entry) => entry, SpokeResult::Reject(reject) if reject.code == SpokeRejectCode::HistoryTruncated => { return SpokeResult::Reject(reject) @@ -1382,7 +1382,7 @@ pub async fn prune_entry_history( /// the live row stands in when no saved revision is that recent. The gap between them is advanced /// by dedicated appends alone, so it subtracts from the checkpoint head and the records are read /// only through that derived head — a later record never reaches an earlier replay. -async fn read_entry_revision( +pub async fn read_entry_at_revision( tx: &mut Transaction<'_, Sqlite>, collection: &str, entry_id: &str, diff --git a/crates/mindcore-sqlite/src/lib.rs b/crates/mindcore-sqlite/src/lib.rs index d8a7c25..76a735e 100644 --- a/crates/mindcore-sqlite/src/lib.rs +++ b/crates/mindcore-sqlite/src/lib.rs @@ -10,9 +10,9 @@ pub mod vectors; pub use knowledge::{ append_cognition, list_entries_in, load_retirement_entry, prune_entry_history, - read_carrier_header, read_entry, retirement_successors_of, validate_admission_scope, - write_entry, CarrierHeader, KnowledgeEntryLifecycle, PruneReport, RoutedKnowledgeStore, - ScopedKnowledgeStore, SERVED_KNOWLEDGE_LIST_LIMIT, + read_carrier_header, read_entry, read_entry_at_revision, retirement_successors_of, + validate_admission_scope, write_entry, CarrierHeader, KnowledgeEntryLifecycle, PruneReport, + RoutedKnowledgeStore, ScopedKnowledgeStore, SERVED_KNOWLEDGE_LIST_LIMIT, }; pub use repository::{ MemoryExportRow, MemoryImportRow, MemoryReceiptSummary, SqliteMemoryRepository, From 646b34db9fd0282ebd5ebed91d41459dd5bb446d Mon Sep 17 00:00:00 2001 From: Tang Bohao Date: Thu, 26 Nov 2026 09:26:08 +0800 Subject: [PATCH 07/22] Add the facade cognition read and the space-level deliberate - Make DeliberateRequest's subject optional and branch the binding's snapshot and commit on it: no subject skips the memory page and takes the space-wide recall revalidation and the space-wide unsettled-intent withhold. - Add MemoryAdapter::read_cognition, withhold_space_if_unsettled, revalidate_space, the space unreconciled refusal and MemoryRepository::has_unsettled_intent_in_space. - Add MemoryWorkflowBinding::with_carrier_collection so a bound Mind resolves its carrier without a route map. - Add Mind::cognition_read and Mind::deliberate with with_providers; deliberate stamps the Mind's id as assessment_context.context_id. - Make the identity digests carry an absent subject as null, and refuse a record whose context is neither named nor derivable. - Refresh the sqlx offline cache for the space-level intent query and cover the goal in the mind selector. --- ...809d7df29c388b29430ec1c1d65bf5862e22e.json | 21 ++ crates/mindcore-base/src/ir.rs | 9 + crates/mindcore-runtime/src/lib.rs | 3 +- crates/mindcore-runtime/src/mind.rs | 112 +++++- crates/mindcore-runtime/src/tools.rs | 6 +- crates/mindcore-runtime/src/tools/tests.rs | 2 +- crates/mindcore-runtime/tests/mind.rs | 328 +++++++++++++++++- crates/mindcore-spi/src/judgment.rs | 2 +- crates/mindcore-spi/src/lib.rs | 10 +- crates/mindcore-spi/src/workflows.rs | 41 ++- crates/mindcore-spi/tests/workflows.rs | 54 +-- crates/mindcore-spoke/src/lib.rs | 122 ++++++- crates/mindcore-spoke/src/reject.rs | 12 + crates/mindcore-spoke/src/workflows.rs | 140 +++++--- crates/mindcore-spoke/tests/workflows.rs | 10 +- crates/mindcore-sqlite/src/repository.rs | 17 + 16 files changed, 786 insertions(+), 103 deletions(-) create mode 100644 .sqlx/query-bbde454e7394e5a14a56f7a194e809d7df29c388b29430ec1c1d65bf5862e22e.json diff --git a/.sqlx/query-bbde454e7394e5a14a56f7a194e809d7df29c388b29430ec1c1d65bf5862e22e.json b/.sqlx/query-bbde454e7394e5a14a56f7a194e809d7df29c388b29430ec1c1d65bf5862e22e.json new file mode 100644 index 0000000..bd67bef --- /dev/null +++ b/.sqlx/query-bbde454e7394e5a14a56f7a194e809d7df29c388b29430ec1c1d65bf5862e22e.json @@ -0,0 +1,21 @@ +{ + "db_name": "SQLite", + "query": "SELECT 1 FROM memory_journal WHERE space_id = ? AND state <> 'applied' LIMIT 1", + "describe": { + "columns": [ + { + "name": "1", + "ordinal": 0, + "type_info": "Integer", + "origin": "Expression" + } + ], + "parameters": { + "Right": 1 + }, + "nullable": [ + false + ] + }, + "hash": "bbde454e7394e5a14a56f7a194e809d7df29c388b29430ec1c1d65bf5862e22e" +} diff --git a/crates/mindcore-base/src/ir.rs b/crates/mindcore-base/src/ir.rs index b3a3854..a5f4963 100644 --- a/crates/mindcore-base/src/ir.rs +++ b/crates/mindcore-base/src/ir.rs @@ -715,6 +715,15 @@ pub trait MemoryRepository: Send + Sync { space: &SpaceId, subject: &SubjectId, ) -> Result; + + /// Whether any non-`applied` durable intent exists anywhere in the space, + /// whichever subject it belongs to: the space-level withhold of a + /// subjectless deliberation. No payload column is selected or decoded. + async fn has_unsettled_intent_in_space( + &self, + tx: &mut Self::Tx<'_>, + space: &SpaceId, + ) -> Result; async fn insert_journal_intent( &self, tx: &mut Self::Tx<'_>, diff --git a/crates/mindcore-runtime/src/lib.rs b/crates/mindcore-runtime/src/lib.rs index d4b7ca0..531ebee 100644 --- a/crates/mindcore-runtime/src/lib.rs +++ b/crates/mindcore-runtime/src/lib.rs @@ -49,7 +49,8 @@ use sqlx::SqlitePool; use adoption::AdoptionService; use history_dedup::SqliteHistoryDedupStore; pub use journal::journal_dir; -pub use mind::{Capture, Mind, Recall}; +pub use mind::{Capture, Deliberation, Mind, Recall}; +pub use mindcore_spoke::Cognition; pub use tools::MindProviders; use tools::WorkflowTools; diff --git a/crates/mindcore-runtime/src/mind.rs b/crates/mindcore-runtime/src/mind.rs index 3898602..c8c6111 100644 --- a/crates/mindcore-runtime/src/mind.rs +++ b/crates/mindcore-runtime/src/mind.rs @@ -23,14 +23,17 @@ use serde_json::{json, Map, Value}; use mindcore_base::boundary::CallerId; use mindcore_base::ids::{MindId, SpaceId}; use mindcore_base::ir::MemoryRepository; -use mindcore_spi::SpiError; -use mindcore_spoke::{MemoryAdapter, MemoryStage}; +use mindcore_spi::{ + DeliberateOutcome, DeliberateRequest, MindWorkflows, SpiError, SpiMindWorkflows, +}; +use mindcore_spoke::{Cognition, MemoryAdapter, MemoryStage, MemoryWorkflowBinding}; use mindcore_sqlite::minds::Mind as MindRow; use mindcore_sqlite::{ list_entries_in, read_entry, read_entry_at_revision, write_entry, MindStore, SqliteMemoryRepository, }; use spoke_operations::{SpokeReject, SpokeRejectCode, SpokeResult}; +use spoke_schemas::data::cognition::{CognitionReference, CognitionTarget}; use spoke_schemas::memory_candidates_review_request::Decision; use spoke_schemas::{ KnowledgeEntry, MemoryCandidatesReviewResponse, MemoryCaptureResponse, MemoryRecallResponse, @@ -38,6 +41,8 @@ use spoke_schemas::{ }; use sqlx::SqlitePool; +use crate::tools::workflow_reject; + /// The host's journal publisher: the handle never invents one. type JournalPublisher = dyn Fn(&[Value]) -> Result<(), SpiError> + Send + Sync; @@ -53,6 +58,7 @@ pub struct Mind { row: MindRow, adapter: MemoryAdapter, publisher: Option>, + providers: crate::MindProviders, } /// One memory capture in plain arguments; the handle renders the wire body with the Mind's @@ -82,6 +88,18 @@ pub struct Recall<'a> { pub cursor: Option<&'a str>, } +/// One deliberation in plain arguments: a target and the evidence the verdict +/// may rest on. There is no subject: the facade's `deliberate` is space-level, +/// and the request carries the Mind's id as its assessment context. +pub struct Deliberation<'a> { + /// The cognition target being assessed. + pub target: &'a CognitionTarget, + /// Evidence admitted for this deliberation. + pub evidence: &'a [mindcore_spi::Evidence<'a>], + /// Elapsed-time budget for the whole call. + pub timeout: std::time::Duration, +} + fn reject(code: SpokeRejectCode, message: impl Into, class: &str) -> SpokeResult { let mut details = Map::new(); details.insert("retry_class".to_string(), Value::String(class.to_string())); @@ -142,6 +160,7 @@ impl Mind { row, adapter: MemoryAdapter::new(false), publisher: None, + providers: crate::MindProviders::default(), }), SpokeResult::Reject(reject) => SpokeResult::Reject(reject), } @@ -161,6 +180,15 @@ impl Mind { self } + /// The providers `deliberate` reasons with: the host's own embedder, reasoner, + /// settlement policy and lens. The handle never invents them; `deliberate` + /// without a reasoner is refused with the workflow's own unavailability. + #[must_use] + pub fn with_providers(mut self, providers: crate::MindProviders) -> Self { + self.providers = providers; + self + } + /// The entry in the Mind's collection that holds its current judgment, as the row named it /// at open. pub fn carrier_entry_id(&self) -> &str { @@ -579,4 +607,84 @@ impl Mind { )), } } + + /// Read this Mind's judgment: `MemoryAdapter::read_cognition` over one read + /// transaction, rolled back after the read. A fresh carrier answers `None`; + /// after one record, the judgment's records and the derived `MindState`. + pub async fn cognition_read(&self) -> SpokeResult> { + let mut transaction = match self.pool.begin().await { + Ok(transaction) => transaction, + Err(error) => { + return retryable_internal(format!( + "cognition read transaction could not begin: {error}" + )) + } + }; + let read = self + .adapter + .read_cognition( + &mut transaction, + &principal(&self.caller), + self.row.id.as_str(), + &self.row.knowledge.collection, + &self.row.carrier_entry_id, + self.row.id.as_str(), + ) + .await; + drop(transaction); + match read { + Ok(cognition) => SpokeResult::Ok(cognition), + Err(error) => SpokeResult::Reject(workflow_reject(error)), + } + } + + /// Deliberate one target over the evidence: `SpiMindWorkflows::deliberate` + /// with the Mind's id as `space_id`, no subject, the carrier the row names + /// as holder and the Mind's id as the assessment context. The space-level + /// revalidation and unsettled-intent checks stand where the subject-level + /// pair would; no path chooses a subject. + pub async fn deliberate( + &self, + deliberation: &Deliberation<'_>, + ) -> SpokeResult { + let holder: CognitionReference = match serde_json::from_value(json!({ + "kind": "knowledge_entry", + "namespace": "mindcore", + "id": self.row.carrier_entry_id.as_str(), + })) { + Ok(holder) => holder, + Err(error) => { + return retryable_internal(format!("the carrier reference does not decode: {error}")) + } + }; + let binding = MemoryWorkflowBinding::new(self.pool.clone(), false) + .with_carrier_collection( + self.row.id.as_str(), + &self.row.knowledge.collection, + &self.row.carrier_entry_id, + ); + let workflows = SpiMindWorkflows::new(binding); + let request = DeliberateRequest { + space_id: self.row.id.as_str(), + subject_id: None, + assessment_context_id: Some(self.row.id.as_str()), + holder: &holder, + target: deliberation.target, + evidence: deliberation.evidence, + timeout: deliberation.timeout, + }; + let caps = self.providers.capabilities(); + let outcome = MindWorkflows::deliberate( + &workflows, + &principal(&self.caller), + request, + self.providers.lens.as_deref(), + &caps, + ) + .await; + match outcome { + Ok(outcome) => SpokeResult::Ok(outcome), + Err(error) => SpokeResult::Reject(workflow_reject(error)), + } + } } diff --git a/crates/mindcore-runtime/src/tools.rs b/crates/mindcore-runtime/src/tools.rs index 2bf5689..3e99c43 100644 --- a/crates/mindcore-runtime/src/tools.rs +++ b/crates/mindcore-runtime/src/tools.rs @@ -54,7 +54,7 @@ pub struct MindProviders { } impl MindProviders { - fn capabilities(&self) -> MindCapabilities<'_> { + pub(crate) fn capabilities(&self) -> MindCapabilities<'_> { MindCapabilities { embedder: self.embedder.as_deref(), reasoner: self.reasoner.as_deref(), @@ -315,7 +315,7 @@ async fn deliberate( .collect(); let request = DeliberateRequest { space_id: &arguments.space_id, - subject_id: &arguments.subject_id, + subject_id: Some(&arguments.subject_id), assessment_context_id: None, holder: &arguments.holder, target: &arguments.target, @@ -382,7 +382,7 @@ fn deliberate_outcome(outcome: DeliberateOutcome) -> Value { } /// One workflow failure as the wire reject the seam documents. -fn workflow_reject(error: SpiError) -> SpokeReject { +pub(crate) fn workflow_reject(error: SpiError) -> SpokeReject { match error { SpiError::Settlement(reject) => reject, SpiError::InvalidInput(message) => SpokeReject { diff --git a/crates/mindcore-runtime/src/tools/tests.rs b/crates/mindcore-runtime/src/tools/tests.rs index 533e994..a565900 100644 --- a/crates/mindcore-runtime/src/tools/tests.rs +++ b/crates/mindcore-runtime/src/tools/tests.rs @@ -102,7 +102,7 @@ impl MindWorkflows for Fake { "deliberate:{}:{}:{}:{}:{}", principal.principal_id.as_str(), request.space_id, - request.subject_id, + request.subject_id.unwrap_or(""), request.timeout.as_millis(), evidence.join(",") )); diff --git a/crates/mindcore-runtime/tests/mind.rs b/crates/mindcore-runtime/tests/mind.rs index 1d0fb1f..b919334 100644 --- a/crates/mindcore-runtime/tests/mind.rs +++ b/crates/mindcore-runtime/tests/mind.rs @@ -4,11 +4,12 @@ use mindcore_base::boundary::CallerId; use mindcore_base::ids::{mint, MindId, SpaceId}; -use mindcore_base::ir::MemoryGrantRow; +use mindcore_base::ir::{MemoryGrantRow, MemoryJournalRow}; use mindcore_base::ir::MemoryRepository; +use mindcore_base::ids::SubjectId; use mindcore_runtime::journal_dir; use mindcore_runtime::minds::{self, CreateMind}; -use mindcore_runtime::{Capture, Mind, Recall}; +use mindcore_runtime::{Capture, Deliberation, Mind, MindProviders, Recall}; use mindcore_spi::SpiError; use mindcore_sqlite::{MindStore, SqliteMemoryRepository}; use chrono::Utc; @@ -19,7 +20,7 @@ use spoke_schemas::data::knowledge_entry::{ use spoke_schemas::KnowledgeEntry; use spoke_operations::{SpokeReject, SpokeRejectCode, SpokeResult}; use spoke_schemas::memory_candidates_review_request::Decision; -use std::sync::mpsc; +use std::sync::{mpsc, Arc}; use tempfile::TempDir; const OWNER: &str = "caller_wren"; @@ -764,3 +765,324 @@ async fn a_caller_without_knowledge_read_reads_nothing() { "a caller without knowledge_read reads no list" ); } + +// ---------- Task 4: cognition read and the space-level deliberate ---------- + +/// One promotion over the supplied evidence; `record_ids` names no memory record +/// because a subjectless snapshot serves no memory page. +struct SettlingReasoner; + +#[async_trait::async_trait] +impl mindcore_spi::Reasoner for SettlingReasoner { + async fn reason_structured( + &self, + request: mindcore_spi::StructuredReasonRequest<'_>, + ) -> Result { + assert_eq!( + request.task_kind, + mindcore_spi::CognitiveTaskKind::Deliberate + ); + let payload: Value = + serde_json::from_str(request.user_payload).expect("the payload is JSON"); + assert!( + payload["records"] + .as_array() + .is_some_and(|records| records.is_empty()), + "a subjectless snapshot serves no memory page: {}", + request.user_payload + ); + Ok(json!({ + "recommendation": { "kind": "promote", "target_kind": "belief" }, + "rationale": "the supplied evidence carries the north gate state", + "evidence_ids": ["ev_gate"], + "record_ids": [], + "record": { + "kind": "belief", + "order": 1, + "q": { + "value": 0.8, + "assertion": "belief_attribution", + "method": "two_witness_reports", + "calibration": "uncalibrated" + }, + "assessor_role": "holder_self_report", + "basis": { "kind": "evidence", "evidence": [] } + } + })) + } +} + +/// A verdict citing a memory record the subjectless snapshot never admitted. +struct CitingReasoner; + +#[async_trait::async_trait] +impl mindcore_spi::Reasoner for CitingReasoner { + async fn reason_structured( + &self, + _request: mindcore_spi::StructuredReasonRequest<'_>, + ) -> Result { + Ok(json!({ + "recommendation": { "kind": "promote", "target_kind": "belief" }, + "rationale": "rests on a record this snapshot never served", + "evidence_ids": ["ev_gate"], + "record_ids": ["rec_not_admitted"], + "record": { + "kind": "belief", + "order": 1, + "q": { + "value": 0.8, + "assertion": "belief_attribution", + "method": "two_witness_reports", + "calibration": "uncalibrated" + }, + "assessor_role": "holder_self_report" + } + })) + } +} + +struct AutoPolicy; + +#[async_trait::async_trait] +impl mindcore_spi::PolicyHook for AutoPolicy { + async fn evaluate_settlement( + &self, + _draft: mindcore_spi::SettlementDraft<'_>, + ) -> Result { + Ok(mindcore_spi::PolicyDecision::AutoSettle) + } +} + +/// The carrier as the Mind's target: the facade's holder is the row's carrier. +fn cognition_target(carrier_entry_id: &str) -> spoke_schemas::data::cognition::CognitionTarget { + serde_json::from_value(json!({ + "carrier": { "kind": "knowledge_entry", "namespace": "mindcore", "id": carrier_entry_id }, + "target_id": "prop_north_gate", + "kind": "proposition", + })) + .expect("a valid cognition target") +} + +/// One deliberation over the fixed evidence, with the providers the test injects: +/// `with_providers` consumes the handle, so each call opens its own with them. +async fn deliberate( + store: &MindStore, + caller: &CallerId, + mind_id: &MindId, + target: &spoke_schemas::data::cognition::CognitionTarget, + reasoner: Arc, +) -> SpokeResult { + let evidence = [mindcore_spi::Evidence { + id: "ev_gate", + text: "the north gate is closed at dusk", + }]; + let providers = MindProviders { + reasoner: Some(reasoner), + policy_hook: Some(Arc::new(AutoPolicy)), + ..MindProviders::default() + }; + let handle = ok(Mind::open(store, caller, mind_id).await).with_providers(providers); + handle + .deliberate(&Deliberation { + target, + evidence: &evidence, + timeout: std::time::Duration::from_secs(5), + }) + .await +} + +/// One unsettled durable intent for `subject_id` in the Mind's space, written +/// directly: the served absorb can leave one, and the facade's check is the +/// space-level one. +async fn settle_never(store: &MindStore, space_id: &str, subject_id: &str) { + let row = MemoryJournalRow { + seq: 0, + receipt_id: mint("rct"), + space_id: SpaceId::new(space_id), + subject_id: SubjectId::new(subject_id), + requester: CallerId::new(OWNER), + operation: "memory.candidates.review".to_string(), + idempotency_key: Some("intent_unsettled".to_string()), + state: "pending".to_string(), + targets: Vec::new(), + result: None, + created_at: Utc::now().to_rfc3339(), + updated_at: Utc::now().to_rfc3339(), + }; + let mut tx = store.pool().begin().await.expect("begin the intent write"); + SqliteMemoryRepository + .insert_journal_intent(&mut tx, &row) + .await + .expect("insert the unsettled intent"); + tx.commit().await.expect("commit the intent"); +} + +#[tokio::test] +async fn cognition_read_answers_none_then_the_judgment_and_mind_state() { + let (_dir, store) = fixture().await; + let owner = CallerId::new(OWNER); + let created = ok(minds::create(&store, &request(OWNER)).await); + let handle = ok(Mind::open(&store, &owner, &created.id).await); + + assert!( + ok(handle.cognition_read().await).is_none(), + "a fresh carrier holds no judgment, which is a state and not a refusal" + ); + + // The plan's own consequence: a fresh Mind has no judgment to read, so the + // carrier is written through the one validation boundary — an explicit + // `knowledge_put` carrying one cognition record. + let carrier = ok(handle.knowledge_get(handle.carrier_entry_id(), None).await); + let revision = carrier.revision.expect("a stored carrier has a revision"); + let record = json!({ + "kind": "belief", + "order": 1, + "record_id": "cog_one", + "holder": { + "kind": "knowledge_entry", + "namespace": "mindcore", + "id": created.carrier_entry_id, + }, + "target": { + "carrier": { + "kind": "knowledge_entry", + "namespace": "mindcore", + "id": created.carrier_entry_id, + }, + "target_id": "prop_north_gate", + "kind": "proposition", + }, + "assessor": { + "kind": "principal", + "namespace": "mindcore", + "id": OWNER, + }, + "assessor_role": "holder_self_report", + "basis": { + "kind": "evidence", + "evidence": [{ "kind": "memory_record", "namespace": "mindcore", "id": "rec_gate" }], + }, + "assessment_context": { "context_id": created.id.as_str() }, + "assessed_at": "2026-11-20T09:00:00Z", + "effective_at": "2026-11-20T09:00:00Z", + "view": "current", + "q": { + "value": 0.8, + "assertion": "belief_attribution", + "method": "two_witness_reports", + "calibration": "uncalibrated", + }, + "extensions": {}, + }); + let next = mindcore_base::cognition::append_cognition_record(&carrier, record) + .expect("one valid record appends to the carrier"); + let written = ok(handle.knowledge_put(next, Some(revision)).await); + assert_eq!( + written.revision, + Some(revision + 1), + "the carrier update is one explicit revision step" + ); + + let cognition = ok(handle.cognition_read().await).expect("one record is a judgment"); + assert_eq!(cognition.records.len(), 1, "the one current-view record"); + assert_eq!( + cognition.records[0]["record_id"], + json!("cog_one"), + "the judgment is the record the carrier holds" + ); + assert_eq!( + cognition.mind_state["mind_state_id"], + json!(created.id.as_str()), + "the Mind's id names its derived state" + ); + assert_eq!( + cognition.mind_state["holder_entry_id"], + json!(created.carrier_entry_id), + "the state descends from the Mind's carrier" + ); + assert!( + cognition.carrier_revision >= 1, + "the read served an assigned carrier revision" + ); +} + +#[tokio::test] +async fn deliberate_without_a_space_wide_recall_grant_is_refused_and_writes_nothing() { + let (_dir, store) = fixture().await; + let created = ok(minds::create(&store, &request(OWNER)).await); + let owner = CallerId::new(OWNER); + let owner_handle = ok(Mind::open(&store, &owner, &created.id).await); + + // The knowledge capabilities admit the carrier; no `recall` grant was ever + // written for this caller, so the space-level revalidation must refuse. + let knowledge_only = CallerId::new("caller_knowledge_only"); + grant( + &store, + created.id.as_str(), + "caller_knowledge_only", + &["knowledge_read", "knowledge_write"], + ) + .await; + let target = cognition_target(&created.carrier_entry_id); + let refuse = reject_of(deliberate(&store, &knowledge_only, &created.id, &target, Arc::new(SettlingReasoner)).await); + assert_eq!( + refuse.code, + SpokeRejectCode::NotAuthorized, + "a caller without the space-wide recall grant is refused" + ); + + assert!( + ok(owner_handle.cognition_read().await).is_none(), + "the refused deliberation wrote no record" + ); +} + +#[tokio::test] +async fn an_unsettled_intent_in_another_subject_refuses_deliberate() { + let (_dir, store) = fixture().await; + let owner = CallerId::new(OWNER); + let created = ok(minds::create(&store, &request(OWNER)).await); + let handle = ok(Mind::open(&store, &owner, &created.id).await); + + settle_never(&store, created.id.as_str(), "subj_other").await; + + let target = cognition_target(&created.carrier_entry_id); + let refuse = reject_of(deliberate(&store, &owner, &created.id, &target, Arc::new(SettlingReasoner)).await); + assert_eq!(refuse.code, SpokeRejectCode::InternalError); + let details = refuse.details.as_ref().expect("structured details"); + assert_eq!( + details.get("reason").and_then(Value::as_str), + Some("UNRECONCILED"), + "the space-level withhold" + ); + assert_eq!( + details.get("space_id").and_then(Value::as_str), + Some(created.id.as_str()), + "the refusal names the space and no subject" + ); + assert!(details.get("subject_id").is_none()); + assert!( + ok(handle.cognition_read().await).is_none(), + "the refused deliberation wrote no record" + ); +} + +#[tokio::test] +async fn a_verdict_citing_a_memory_record_is_refused() { + let (_dir, store) = fixture().await; + let owner = CallerId::new(OWNER); + let created = ok(minds::create(&store, &request(OWNER)).await); + let handle = ok(Mind::open(&store, &owner, &created.id).await); + + let target = cognition_target(&created.carrier_entry_id); + let refuse = reject_of(deliberate(&store, &owner, &created.id, &target, Arc::new(CitingReasoner)).await); + assert_eq!( + refuse.code, + SpokeRejectCode::InternalError, + "a citation outside the subjectless snapshot is refused, never widened" + ); + assert!( + ok(handle.cognition_read().await).is_none(), + "the refused verdict wrote no record" + ); +} diff --git a/crates/mindcore-spi/src/judgment.rs b/crates/mindcore-spi/src/judgment.rs index 8d7ca03..fb3a2a5 100644 --- a/crates/mindcore-spi/src/judgment.rs +++ b/crates/mindcore-spi/src/judgment.rs @@ -187,7 +187,7 @@ mod tests { ) -> DeliberateRequest<'a> { DeliberateRequest { space_id: "spc_1", - subject_id: "subj_1", + subject_id: Some("subj_1"), assessment_context_id: None, holder, target, diff --git a/crates/mindcore-spi/src/lib.rs b/crates/mindcore-spi/src/lib.rs index 120f802..ccce9c1 100644 --- a/crates/mindcore-spi/src/lib.rs +++ b/crates/mindcore-spi/src/lib.rs @@ -445,10 +445,14 @@ pub struct Evidence<'a> { pub struct DeliberateRequest<'a> { /// Memory space the deliberation runs in. pub space_id: &'a str, - /// Subject the cognition belongs to. - pub subject_id: &'a str, + /// Subject the cognition belongs to, or `None` for the space-level + /// deliberation of the in-process facade: with no subject there is no + /// memory page to read, and the grant revalidation and the unsettled-intent + /// check move from the subject to the whole space. + pub subject_id: Option<&'a str>, /// Assessment context stamped onto the record. `None` derives it from - /// [`Self::subject_id`]; a supplied id is only validated by the record + /// [`Self::subject_id`] when one is present; a request naming neither is + /// `InvalidInput`. A supplied id is only validated by the record /// schema and never widens admission or the storage route. pub assessment_context_id: Option<&'a str>, /// The holder this verdict is attributed to. diff --git a/crates/mindcore-spi/src/workflows.rs b/crates/mindcore-spi/src/workflows.rs index 5daf5db..efa0a85 100644 --- a/crates/mindcore-spi/src/workflows.rs +++ b/crates/mindcore-spi/src/workflows.rs @@ -264,12 +264,15 @@ pub trait WorkflowBinding: Send + Sync { /// /// The holder must name the existing carrier entry of the caller's bound /// knowledge collection. A memory grant is not an admission to the - /// carrier; only the binding's knowledge admission is. + /// carrier; only the binding's knowledge admission is. With no subject + /// there is no page to read: the snapshot serves an empty memory page, and + /// the space-level revalidation and unsettled-intent checks run in place of + /// the subject-level pair. async fn deliberate_snapshot( &self, principal: &Principal, space_id: &str, - subject_id: &str, + subject_id: Option<&str>, holder: &CognitionReference, max_items: u64, ) -> Result; @@ -278,10 +281,11 @@ pub trait WorkflowBinding: Send + Sync { /// one caller-managed write transaction. /// /// Rechecks the caller's admission to *write* the carrier (a read grant is - /// not one), the subject's recall admission, its withholding and every - /// cited record revision against `cited`, and refuses a carrier that no - /// longer holds `expected_carrier_revision`. Returns the carrier revision - /// of the derived `MindState` after a confirmed commit. + /// not one), the recall admission and the unsettled-intent withhold — over + /// the subject when one is named, over the whole space when none is — and + /// every cited record revision against `cited`, and refuses a carrier that + /// no longer holds `expected_carrier_revision`. Returns the carrier + /// revision of the derived `MindState` after a confirmed commit. /// /// An implementation must observe `deadline` itself, because the caller /// cannot bound the wait for its storage: while acquiring whatever the @@ -295,7 +299,7 @@ pub trait WorkflowBinding: Send + Sync { &self, principal: &Principal, space_id: &str, - subject_id: &str, + subject_id: Option<&str>, holder: &CognitionReference, expected_carrier_revision: u64, record: Value, @@ -1564,6 +1568,15 @@ fn stamp_cognition_record( .as_object() .cloned() .ok_or_else(|| invalid_verdict("the proposed record is not an object"))?; + // The record's context is a trusted input, never the model's: a request + // naming neither an explicit context nor a subject to derive one from is + // the caller's invalid input, not a verdict defect. + let Some(context_id) = request.assessment_context_id.or(request.subject_id) else { + return Err(SpiError::InvalidInput( + "the request names neither an assessment context nor a subject to derive it from" + .to_string(), + )); + }; let now = Utc::now().to_rfc3339_opts(SecondsFormat::Nanos, true); let stamped = [ ("record_id", Value::String(new_record_id(request)?)), @@ -1580,7 +1593,7 @@ fn stamp_cognition_record( ( "assessment_context", json!({ - "context_id": request.assessment_context_id.unwrap_or(request.subject_id), + "context_id": context_id, }), ), ("assessed_at", Value::String(now.clone())), @@ -1611,8 +1624,12 @@ fn stamp_cognition_record( } /// Whether the record validates with the assessment context derived from the -/// subject, as a request that supplied none would have stamped it. +/// subject, as a request that supplied none would have stamped it. A subjectless +/// request derives nothing, so its supplied context never gets this fallback. fn validates_with_derived_context(record: &Value, request: &DeliberateRequest<'_>) -> bool { + let Some(subject_id) = request.subject_id else { + return false; + }; let mut derived = record.clone(); let Some(context) = derived .get_mut("assessment_context") @@ -1622,7 +1639,7 @@ fn validates_with_derived_context(record: &Value, request: &DeliberateRequest<'_ }; context.insert( "context_id".to_string(), - Value::String(request.subject_id.to_string()), + Value::String(subject_id.to_string()), ); !matches!(validate_cognition_record(&derived), SpokeResult::Reject(_)) } @@ -2552,7 +2569,7 @@ mod tests { &self, _principal: &Principal, _space_id: &str, - _subject_id: &str, + _subject_id: Option<&str>, _holder: &CognitionReference, _max_items: u64, ) -> Result { @@ -2563,7 +2580,7 @@ mod tests { &self, _principal: &Principal, _space_id: &str, - _subject_id: &str, + _subject_id: Option<&str>, _holder: &CognitionReference, _expected_carrier_revision: u64, _record: Value, diff --git a/crates/mindcore-spi/tests/workflows.rs b/crates/mindcore-spi/tests/workflows.rs index 5817179..0a555bb 100644 --- a/crates/mindcore-spi/tests/workflows.rs +++ b/crates/mindcore-spi/tests/workflows.rs @@ -338,7 +338,7 @@ impl WorkflowBinding for StubBinding { &self, _principal: &Principal, _space_id: &str, - _subject_id: &str, + _subject_id: Option<&str>, _holder: &CognitionReference, _max_items: u64, ) -> Result { @@ -349,7 +349,7 @@ impl WorkflowBinding for StubBinding { &self, _principal: &Principal, _space_id: &str, - _subject_id: &str, + _subject_id: Option<&str>, _holder: &CognitionReference, _expected_carrier_revision: u64, _record: Value, @@ -482,7 +482,7 @@ impl WorkflowBinding for RefusingBinding { &self, _principal: &Principal, _space_id: &str, - _subject_id: &str, + _subject_id: Option<&str>, _holder: &CognitionReference, _max_items: u64, ) -> Result { @@ -493,7 +493,7 @@ impl WorkflowBinding for RefusingBinding { &self, _principal: &Principal, _space_id: &str, - _subject_id: &str, + _subject_id: Option<&str>, _holder: &CognitionReference, _expected_carrier_revision: u64, _record: Value, @@ -1617,7 +1617,7 @@ impl WorkflowBinding for AbsorbDouble { &self, _principal: &Principal, _space_id: &str, - _subject_id: &str, + _subject_id: Option<&str>, _holder: &CognitionReference, _max_items: u64, ) -> Result { @@ -1628,7 +1628,7 @@ impl WorkflowBinding for AbsorbDouble { &self, _principal: &Principal, _space_id: &str, - _subject_id: &str, + _subject_id: Option<&str>, _holder: &CognitionReference, _expected_carrier_revision: u64, _record: Value, @@ -2601,7 +2601,7 @@ impl WorkflowBinding for DeliberateDouble { &self, _principal: &Principal, _space_id: &str, - _subject_id: &str, + _subject_id: Option<&str>, _holder: &CognitionReference, _max_items: u64, ) -> Result { @@ -2613,7 +2613,7 @@ impl WorkflowBinding for DeliberateDouble { &self, _principal: &Principal, _space_id: &str, - _subject_id: &str, + _subject_id: Option<&str>, _holder: &CognitionReference, _expected_carrier_revision: u64, record: Value, @@ -2835,7 +2835,7 @@ async fn deliberate_settles_the_stamped_record_onto_the_committed_carrier() { }]; let request = DeliberateRequest { space_id: "spc_1", - subject_id: "subj_1", + subject_id: Some("subj_1"), assessment_context_id: None, holder: &holder, target: &target, @@ -2944,7 +2944,7 @@ async fn deliberate_hands_the_binding_its_request_deadline() { let timeout = std::time::Duration::from_secs(30); let request = DeliberateRequest { space_id: "spc_1", - subject_id: "subj_1", + subject_id: Some("subj_1"), assessment_context_id: None, holder: &holder, target: &target, @@ -3025,7 +3025,7 @@ async fn an_empty_explicit_assessment_context_is_a_caller_input_error() { }]; let request = DeliberateRequest { space_id: "spc_1", - subject_id: "subj_1", + subject_id: Some("subj_1"), assessment_context_id: Some(""), holder: &holder, target: &target, @@ -3108,7 +3108,7 @@ async fn deliberate_refuses_fabricated_references_before_any_write() { }]; let request = DeliberateRequest { space_id: "spc_1", - subject_id: "subj_1", + subject_id: Some("subj_1"), assessment_context_id: None, holder: &holder, target: &target, @@ -3153,7 +3153,7 @@ async fn deliberate_lens_violation_refuses_before_policy_and_write() { }]; let request = DeliberateRequest { space_id: "spc_1", - subject_id: "subj_1", + subject_id: Some("subj_1"), assessment_context_id: None, holder: &holder, target: &target, @@ -3241,7 +3241,7 @@ async fn deliberate_lens_refuses_a_none_recommendation() { }]; let request = DeliberateRequest { space_id: "spc_1", - subject_id: "subj_1", + subject_id: Some("subj_1"), assessment_context_id: None, holder: &holder, target: &target, @@ -3353,7 +3353,7 @@ async fn deliberate_drops_a_hung_reasoner_at_the_deadline() { }]; let request = DeliberateRequest { space_id: "spc_1", - subject_id: "subj_1", + subject_id: Some("subj_1"), assessment_context_id: None, holder: &holder, target: &target, @@ -3396,7 +3396,7 @@ async fn deliberate_starts_no_write_after_the_policy_overran_the_deadline() { }]; let request = DeliberateRequest { space_id: "spc_1", - subject_id: "subj_1", + subject_id: Some("subj_1"), assessment_context_id: None, holder: &holder, target: &target, @@ -3451,7 +3451,7 @@ async fn deliberate_retries_a_stale_carrier_twice_then_surfaces_it() { }]; let request = DeliberateRequest { space_id: "spc_1", - subject_id: "subj_1", + subject_id: Some("subj_1"), assessment_context_id: None, holder: &holder, target: &target, @@ -3504,7 +3504,7 @@ async fn deliberate_retries_a_stale_carrier_until_the_snapshot_holds() { }]; let request = DeliberateRequest { space_id: "spc_1", - subject_id: "subj_1", + subject_id: Some("subj_1"), assessment_context_id: None, holder: &holder, target: &target, @@ -3537,7 +3537,7 @@ async fn deliberate_does_not_retry_a_refusal_or_an_uncertain_write() { }]; let request = DeliberateRequest { space_id: "spc_1", - subject_id: "subj_1", + subject_id: Some("subj_1"), assessment_context_id: None, holder: &holder, target: &target, @@ -3585,7 +3585,7 @@ async fn deliberate_does_not_retry_a_refusal_or_an_uncertain_write() { }]; let request = DeliberateRequest { space_id: "spc_1", - subject_id: "subj_1", + subject_id: Some("subj_1"), assessment_context_id: None, holder: &holder, target: &target, @@ -3640,7 +3640,7 @@ async fn deliberate_none_recommendation_writes_nothing() { }]; let request = DeliberateRequest { space_id: "spc_1", - subject_id: "subj_1", + subject_id: Some("subj_1"), assessment_context_id: None, holder: &holder, target: &target, @@ -3693,7 +3693,7 @@ async fn deliberate_needs_review_carries_the_pending_judgment_and_writes_nothing }]; let request = DeliberateRequest { space_id: "spc_1", - subject_id: "subj_1", + subject_id: Some("subj_1"), assessment_context_id: None, holder: &holder, target: &target, @@ -3759,7 +3759,7 @@ async fn deliberate_refuses_a_cited_revision_the_released_validator_rejects() { }]; let request = DeliberateRequest { space_id: "spc_1", - subject_id: "subj_1", + subject_id: Some("subj_1"), assessment_context_id: None, holder: &holder, target: &target, @@ -3802,7 +3802,7 @@ async fn deliberate_without_a_reasoner_is_unavailable() { }]; let request = DeliberateRequest { space_id: "spc_1", - subject_id: "subj_1", + subject_id: Some("subj_1"), assessment_context_id: None, holder: &holder, target: &target, @@ -3843,7 +3843,7 @@ async fn deliberate_starts_no_attempt_once_the_deadline_passed() { }]; let request = DeliberateRequest { space_id: "spc_1", - subject_id: "subj_1", + subject_id: Some("subj_1"), assessment_context_id: None, holder: &holder, target: &target, @@ -3888,7 +3888,7 @@ async fn deliberate_clamps_an_absurd_timeout_and_still_settles() { }]; let request = DeliberateRequest { space_id: "spc_1", - subject_id: "subj_1", + subject_id: Some("subj_1"), assessment_context_id: None, holder: &holder, target: &target, @@ -4122,7 +4122,7 @@ fn lens_request<'a>( ) -> DeliberateRequest<'a> { DeliberateRequest { space_id: "spc_1", - subject_id: "subj_1", + subject_id: Some("subj_1"), assessment_context_id: None, holder, target, diff --git a/crates/mindcore-spoke/src/lib.rs b/crates/mindcore-spoke/src/lib.rs index 88877e4..1cbb85b 100644 --- a/crates/mindcore-spoke/src/lib.rs +++ b/crates/mindcore-spoke/src/lib.rs @@ -37,11 +37,39 @@ use sqlx::{Sqlite, Transaction}; use mindcore_base::ids::{SpaceId, SubjectId}; use mindcore_spi::SpiError; use mindcore_base::ir::{MemoryRepository, ReceiptFailure, ReceiptState, ReviewReceiptIr}; -use mindcore_sqlite::SqliteMemoryRepository; +use mindcore_sqlite::{read_entry, SqliteMemoryRepository}; use crate::admission::Op; use crate::reject::{AResult, Reject}; +/// The knowledge-read capability. A grant carrying it admits its principal to +/// knowledge reads in that grant's space; the open capability vocabulary names +/// no knowledge capability, and no memory capability (`recall`, `records_read`) +/// stands in for it. +pub(crate) const KNOWLEDGE_READ: &str = "knowledge_read"; + +/// The carrier-write capability. Reading a collection is not authority to +/// modify the judgment it carries, so the write transaction requires this on +/// its own. +pub(crate) const KNOWLEDGE_WRITE: &str = "knowledge_write"; + +/// The memory capability the subject page was read under; the write rechecks +/// it because a verdict over that page depends on it. +pub(crate) const RECALL: &str = "recall"; + +/// The derived judgment of one Mind's cognition carrier: the carrier revision +/// the read served, its current-view records, and the `MindState` projection of +/// them. Persisted nowhere; it is derived on every read. +#[derive(Debug, Clone)] +pub struct Cognition { + /// The carrier revision the read served. + pub carrier_revision: u64, + /// The carrier's current-view cognition records, in carrier order. + pub records: Vec, + /// The derived `MindState` wire value for this read. + pub mind_state: Value, +} + /// The caller-owned transaction every entry point reads and writes through. pub type Tx<'a> = Transaction<'a, Sqlite>; @@ -221,6 +249,98 @@ impl MemoryAdapter { } } + /// The space-level withhold of a subjectless deliberation: refuses while any + /// durable intent in the space is unsettled, whichever subject it belongs to. + pub(crate) async fn withhold_space_if_unsettled( + &self, + tx: &mut Tx<'_>, + space: &SpaceId, + ) -> AResult<()> { + let unsettled = self + .repository + .has_unsettled_intent_in_space(tx, space) + .await?; + if unsettled { + Err(Reject::unreconciled_space(space.as_str())) + } else { + Ok(()) + } + } + + /// The caller's space-wide live `recall` grant, rechecked on `tx`: the + /// requirement shape `memory.spaces.freeze` uses, moved here from the + /// subject-level revalidation for a subjectless deliberation. + pub(crate) async fn revalidate_space( + &self, + tx: &mut Tx<'_>, + principal: &Principal, + space_id: &str, + ) -> Result<(), SpiError> { + self.require_space_grants(tx, principal, space_id, &[RECALL]) + .await + } + + /// Read the carrier entry of `carrier_entry_id` in `collection` on `tx` and + /// derive the Mind's judgment from it — the space-wide `knowledge_read` + /// grant admitted first. A carrier that holds no current-view record yet + /// answers `None`: a Mind without a judgment is a state, not an error. Any + /// other derivation refusal means a stored carrier the projection cannot + /// read, answered as the caller-side internal failure it is. + pub async fn read_cognition( + &self, + tx: &mut Tx<'_>, + principal: &Principal, + space_id: &str, + collection: &str, + carrier_entry_id: &str, + mind_state_id: &str, + ) -> Result, SpiError> { + self.require_space_grants(tx, principal, space_id, &[KNOWLEDGE_READ]) + .await?; + let carrier = match read_entry(tx, collection, carrier_entry_id).await { + SpokeResult::Ok(carrier) => carrier, + SpokeResult::Reject(reject) => return Err(SpiError::Settlement(reject)), + }; + let revision = carrier.revision.ok_or_else(|| { + SpiError::Settlement( + Reject::terminal( + SpokeRejectCode::InternalError, + format!("carrier {carrier_entry_id} holds no assigned revision"), + ) + .into_spoke(), + ) + })?; + let view = match mindcore_base::cognition::derive_mind_state(&carrier) { + Ok(view) => view, + Err(mindcore_base::cognition::MindError::NoRecords) => return Ok(None), + Err(error) => { + return Err(SpiError::Settlement( + Reject::terminal( + SpokeRejectCode::InternalError, + format!("carrier {carrier_entry_id} cannot be derived: {error}"), + ) + .into_spoke(), + )); + } + }; + let records = mindcore_base::cognition::carrier_records(&carrier); + let mind_state = mindcore_base::cognition::mind_state_value(&view, mind_state_id) + .map_err(|error| { + SpiError::Settlement( + Reject::terminal( + SpokeRejectCode::InternalError, + format!("the mind state of {carrier_entry_id} cannot be projected: {error}"), + ) + .into_spoke(), + ) + })?; + Ok(Some(Cognition { + carrier_revision: revision, + records, + mind_state, + })) + } + /// `principal`'s own live grant for every one of `capabilities` in `space_id`, on `tx`. /// /// Live grants are re-derived on every call, so a read after provider work runs the same diff --git a/crates/mindcore-spoke/src/reject.rs b/crates/mindcore-spoke/src/reject.rs index c61bdf6..404ba1d 100644 --- a/crates/mindcore-spoke/src/reject.rs +++ b/crates/mindcore-spoke/src/reject.rs @@ -67,6 +67,18 @@ impl Reject { .detail("subject_id", Value::String(subject_id.to_string())) } + /// The space-level withholding of a subjectless deliberation: any durable + /// intent in the space is unsettled, whichever subject it belongs to. The + /// refusal names the space and no subject. + pub(crate) fn unreconciled_space(space_id: &str) -> Self { + Self::terminal( + SpokeRejectCode::InternalError, + "space content is withheld until its durable intents settle", + ) + .detail("reason", Value::String("UNRECONCILED".to_string())) + .detail("space_id", Value::String(space_id.to_string())) + } + /// An optional family or op this adapter build does not serve (§4.1). pub(crate) fn unsupported(op: &str) -> Self { Self::terminal( diff --git a/crates/mindcore-spoke/src/workflows.rs b/crates/mindcore-spoke/src/workflows.rs index 0d7b19d..ff00640 100644 --- a/crates/mindcore-spoke/src/workflows.rs +++ b/crates/mindcore-spoke/src/workflows.rs @@ -44,27 +44,12 @@ use mindcore_sqlite::{ use crate::admission; use crate::reject::Reject; -use crate::{principal_id, MemoryAdapter, MemoryStage, Tx}; +use crate::{principal_id, MemoryAdapter, MemoryStage, Tx, KNOWLEDGE_READ, KNOWLEDGE_WRITE, RECALL}; /// Publishes one intent's file targets and confirms them: `Ok(())` only when /// every target's exact bytes landed at its path. type JournalPublisher = dyn Fn(&[Value]) -> Result<(), SpiError> + Send + Sync; -/// The knowledge-read capability. A grant carrying it admits its principal to -/// knowledge reads in that grant's space; the open capability vocabulary names -/// no knowledge capability, and no memory capability (`recall`, `records_read`) -/// stands in for it. -const KNOWLEDGE_READ: &str = "knowledge_read"; - -/// The carrier-write capability. Reading a collection is not authority to -/// modify the judgment it carries, so the write transaction requires this on -/// its own. -const KNOWLEDGE_WRITE: &str = "knowledge_write"; - -/// The memory capability the subject page was read under; the write rechecks -/// it because a verdict over that page depends on it. -const RECALL: &str = "recall"; - /// The journal op of the durable absorb-decision marker. The row is applied, /// carries no targets and settles nothing: it only tells a capture replay that /// this capture's absorb run decided `Pending` for the ids it names. @@ -83,6 +68,9 @@ pub struct MemoryWorkflowBinding { /// destination here too — so both sides can never drift apart. knowledge_routes: Arc>, publisher: Option>, + /// The one carrier a facade handle binds: `(space_id, collection, carrier_entry_id)`. + /// The served surface binds none, so its principal routes stay the only resolution. + carrier_binding: Option<(String, String, String)>, } impl MemoryWorkflowBinding { @@ -95,6 +83,7 @@ impl MemoryWorkflowBinding { pool, knowledge_routes: Arc::new(BTreeMap::new()), publisher: None, + carrier_binding: None, } } @@ -347,8 +336,41 @@ impl MemoryWorkflowBinding { self.knowledge_routes.get(principal_id(principal)) } - /// The collection the carrier write serves: `principal` must have a route and hold a live - /// grant for every one of `capabilities` in `space_id`. + /// Bind the carrier its row states, for the facade handle that has no route + /// map: `with_carrier_collection(space_id, collection, carrier_entry_id)` + /// pins one space's deliberation to the collection and carrier the Mind's + /// registry row resolved at open. The served surface binds none, so its + /// route map stays the only resolution. + #[must_use] + pub fn with_carrier_collection( + mut self, + space_id: &str, + collection: &str, + carrier_entry_id: &str, + ) -> Self { + self.carrier_binding = Some(( + space_id.to_string(), + collection.to_string(), + carrier_entry_id.to_string(), + )); + self + } + + /// The collection one carrier access serves: a bound Mind answers its own + /// collection first, and the route map answers otherwise. + fn carrier_collection(&self, principal: &Principal, space_id: &str) -> Option<&str> { + if let Some((bound_space, collection, _)) = &self.carrier_binding { + if bound_space == space_id { + return Some(collection.as_str()); + } + } + self.knowledge_route(principal) + .map(|route| route.collection.as_str()) + } + + /// The collection the carrier write serves: `principal` must have a route — + /// or the binding a bound carrier — and hold a live grant for every one of + /// `capabilities` in `space_id`. /// /// Resolved once, so the carrier read and its CAS append stay pinned to one collection. A /// missing route is the terminal refusal before any carrier access: it is as target-free as a @@ -361,8 +383,7 @@ impl MemoryWorkflowBinding { capabilities: &[&str], ) -> Result<&str, SpiError> { let collection = self - .knowledge_route(principal) - .map(|route| route.collection.as_str()) + .carrier_collection(principal, space_id) .ok_or_else(|| { not_authorized("principal has no workflow knowledge route".to_string()) })?; @@ -1070,7 +1091,7 @@ impl WorkflowBinding for MemoryWorkflowBinding { &self, principal: &Principal, space_id: &str, - subject_id: &str, + subject_id: Option<&str>, holder: &CognitionReference, max_items: u64, ) -> Result { @@ -1079,22 +1100,40 @@ impl WorkflowBinding for MemoryWorkflowBinding { "deliberation read transaction could not begin: {error}" )) })?; - let records = ready( - self.adapter - .recall( - &mut transaction, - principal, - json!({ - "space_id": space_id, - "subject_id": subject_id, - "selection": { "mode": "subject_all" }, - "budget": { "max_items": max_items }, - }), - ) - .await, - "memory.recall", - ); - let records = decode_records(records?)?; + // With no subject there is no page to read: the space-level revalidation + // and unsettled-intent check stand in place of the subject page's own + // admission and withhold, and the snapshot serves an empty memory page. + let records = match subject_id { + Some(subject_id) => { + let records = ready( + self.adapter + .recall( + &mut transaction, + principal, + json!({ + "space_id": space_id, + "subject_id": subject_id, + "selection": { "mode": "subject_all" }, + "budget": { "max_items": max_items }, + }), + ) + .await, + "memory.recall", + ); + decode_records(records?)? + } + None => { + self.adapter + .revalidate_space(&mut transaction, principal, space_id) + .await?; + let space = SpaceId::new(space_id.to_string()); + self.adapter + .withhold_space_if_unsettled(&mut transaction, &space) + .await + .map_err(|reject| SpiError::Settlement(reject.into_spoke()))?; + Vec::new() + } + }; let collection = self .admitted_collection(&mut transaction, principal, space_id, &[KNOWLEDGE_READ]) .await?; @@ -1126,7 +1165,7 @@ impl WorkflowBinding for MemoryWorkflowBinding { &self, principal: &Principal, space_id: &str, - subject_id: &str, + subject_id: Option<&str>, holder: &CognitionReference, expected_carrier_revision: u64, record: Value, @@ -1166,12 +1205,25 @@ impl WorkflowBinding for MemoryWorkflowBinding { ) .await?; let space = SpaceId::new(space_id.to_string()); - self.revalidate_subject(&mut transaction, principal, space_id, subject_id) - .await?; - self.adapter - .withhold_if_unsettled(&mut transaction, &space, subject_id) - .await - .map_err(|reject| SpiError::Settlement(reject.into_spoke()))?; + match subject_id { + Some(subject_id) => { + self.revalidate_subject(&mut transaction, principal, space_id, subject_id) + .await?; + self.adapter + .withhold_if_unsettled(&mut transaction, &space, subject_id) + .await + .map_err(|reject| SpiError::Settlement(reject.into_spoke()))?; + } + None => { + self.adapter + .revalidate_space(&mut transaction, principal, space_id) + .await?; + self.adapter + .withhold_space_if_unsettled(&mut transaction, &space) + .await + .map_err(|reject| SpiError::Settlement(reject.into_spoke()))?; + } + } self.revalidate_cited(&mut transaction, principal, space_id, cited) .await?; let header = diff --git a/crates/mindcore-spoke/tests/workflows.rs b/crates/mindcore-spoke/tests/workflows.rs index 9b54206..733d07b 100644 --- a/crates/mindcore-spoke/tests/workflows.rs +++ b/crates/mindcore-spoke/tests/workflows.rs @@ -2630,7 +2630,7 @@ async fn deliberate_as( }]; let request = mindcore_spi::DeliberateRequest { space_id: SPACE, - subject_id: SUBJECT, + subject_id: Some(SUBJECT), assessment_context_id, holder: &holder, target: &target, @@ -4239,7 +4239,7 @@ async fn a_settle_refuses_at_its_deadline_while_the_only_connection_is_held() { binding.commit_cognition( &principal(), SPACE, - SUBJECT, + Some(SUBJECT), &settle_holder(), 1, settle_record("cog_refused"), @@ -4299,7 +4299,7 @@ async fn a_settle_with_a_passed_deadline_opens_no_transaction_on_a_free_connecti binding.commit_cognition( &principal(), SPACE, - SUBJECT, + Some(SUBJECT), &settle_holder(), 1, settle_record("cog_expired"), @@ -4338,7 +4338,7 @@ async fn a_settle_commits_on_a_free_connection_within_its_deadline() { binding.commit_cognition( &principal(), SPACE, - SUBJECT, + Some(SUBJECT), &settle_holder(), 1, settle_record("cog_settled"), @@ -4386,7 +4386,7 @@ async fn a_settle_waits_out_a_short_hold_until_its_deadline() { binding.commit_cognition( &principal(), SPACE, - SUBJECT, + Some(SUBJECT), &settle_holder(), 1, settle_record("cog_waited"), diff --git a/crates/mindcore-sqlite/src/repository.rs b/crates/mindcore-sqlite/src/repository.rs index fc2de1e..0cebd76 100644 --- a/crates/mindcore-sqlite/src/repository.rs +++ b/crates/mindcore-sqlite/src/repository.rs @@ -2690,6 +2690,23 @@ impl MemoryRepository for SqliteMemoryRepository { .is_some()) } + async fn has_unsettled_intent_in_space( + &self, + tx: &mut Self::Tx<'_>, + space: &SpaceId, + ) -> RepoResult { + Ok(sqlx::query_scalar!( + "SELECT 1 FROM memory_journal \ + WHERE space_id = ? AND state <> 'applied' \ + LIMIT 1", + space.as_str(), + ) + .fetch_optional(&mut **tx) + .await + .map_err(decode_row)? + .is_some()) + } + async fn insert_journal_intent( &self, tx: &mut Self::Tx<'_>, From 57306c04177d21cfb7da33a8a5e0d12c7a891ea7 Mon Sep 17 00:00:00 2001 From: Tang Bohao Date: Thu, 26 Nov 2026 09:30:01 +0800 Subject: [PATCH 08/22] Enforce the bound carrier and the subjectless request invariant - Refuse a holder that does not name a binding's bound carrier at both the snapshot and the commit, before any carrier read or write, and cover it with a mismatch test plus the bound-carrier control. - Validate a request naming neither a subject nor an assessment context at the start of `deliberate`, before the reasoner and the snapshot, so a `none` verdict can no longer let it succeed; cover the no-change case with a reasoner that must never run. - Add the missing space-level settlement coverage: a facade verdict that settles with the Mind's id as its context and derives its state, and a commit-time refusal when an intent arrives after the snapshot. --- crates/mindcore-runtime/tests/mind.rs | 155 +++++++++++++++++++++++ crates/mindcore-spi/src/workflows.rs | 11 ++ crates/mindcore-spoke/src/workflows.rs | 21 +++ crates/mindcore-spoke/tests/workflows.rs | 128 +++++++++++++++++++ 4 files changed, 315 insertions(+) diff --git a/crates/mindcore-runtime/tests/mind.rs b/crates/mindcore-runtime/tests/mind.rs index b919334..a1782c2 100644 --- a/crates/mindcore-runtime/tests/mind.rs +++ b/crates/mindcore-runtime/tests/mind.rs @@ -1086,3 +1086,158 @@ async fn a_verdict_citing_a_memory_record_is_refused() { "the refused verdict wrote no record" ); } + +/// The subjectless promotion: a `prior` basis needs no memory record, which is +/// the only basis a space-level snapshot can admit — it carries no page to cite. +fn prior_basis_verdict() -> Value { + json!({ + "recommendation": { "kind": "promote", "target_kind": "belief" }, + "rationale": "the gate has been closed at dusk all season", + "evidence_ids": ["ev_gate"], + "record_ids": [], + "record": { + "kind": "belief", + "order": 1, + "q": { + "value": 0.8, + "assertion": "belief_attribution", + "method": "two_witness_reports", + "calibration": "uncalibrated" + }, + "assessor_role": "holder_self_report", + "basis": { + "kind": "prior", + "description": "every dusk patrol reported the gate closed" + } + } + }) +} + +struct PriorBasisReasoner; + +#[async_trait::async_trait] +impl mindcore_spi::Reasoner for PriorBasisReasoner { + async fn reason_structured( + &self, + _request: mindcore_spi::StructuredReasonRequest<'_>, + ) -> Result { + Ok(prior_basis_verdict()) + } +} + +/// Settles nothing itself: it leaves an unsettled intent in the Mind's space for +/// another subject while the snapshot is already past, so the refusal must come +/// from the commit's space-level withhold. +struct RecordingIntentReasoner { + pool: sqlx::SqlitePool, + space_id: String, +} + +#[async_trait::async_trait] +impl mindcore_spi::Reasoner for RecordingIntentReasoner { + async fn reason_structured( + &self, + _request: mindcore_spi::StructuredReasonRequest<'_>, + ) -> Result { + let row = MemoryJournalRow { + seq: 0, + receipt_id: mint("rct"), + space_id: SpaceId::new(self.space_id.as_str()), + subject_id: SubjectId::new("subj_other"), + requester: CallerId::new(OWNER), + operation: "memory.candidates.review".to_string(), + idempotency_key: Some("intent_after_snapshot".to_string()), + state: "pending".to_string(), + targets: Vec::new(), + result: None, + created_at: Utc::now().to_rfc3339(), + updated_at: Utc::now().to_rfc3339(), + }; + let mut tx = self.pool.begin().await.expect("begin the late intent"); + SqliteMemoryRepository + .insert_journal_intent(&mut tx, &row) + .await + .map_err(|error| SpiError::InvalidInput(format!("late intent: {error}")))?; + tx.commit() + .await + .map_err(|error| SpiError::InvalidInput(format!("late intent commit: {error}")))?; + Ok(prior_basis_verdict()) + } +} + +#[tokio::test] +async fn a_space_level_verdict_settles_with_the_mind_context_and_derives_its_state() { + let (_dir, store) = fixture().await; + let owner = CallerId::new(OWNER); + let created = ok(minds::create(&store, &request(OWNER)).await); + let target = cognition_target(&created.carrier_entry_id); + + let outcome = ok(deliberate(&store, &owner, &created.id, &target, Arc::new(PriorBasisReasoner)).await); + let mind_state_version = match outcome { + mindcore_spi::DeliberateOutcome::Settled { + mind_state_version, + .. + } => mind_state_version, + other => panic!("the auto-settled verdict must commit: {other:?}"), + }; + assert_eq!( + mind_state_version, 2, + "the carrier advances one revision past its creation" + ); + + let handle = ok(Mind::open(&store, &owner, &created.id).await); + let cognition = ok(handle.cognition_read().await).expect("the settled judgment derives"); + assert_eq!(cognition.records.len(), 1, "the one committed record"); + assert_eq!( + cognition.records[0]["assessment_context"]["context_id"], + json!(created.id.as_str()), + "the stored record carries the Mind's id as its context" + ); + assert_eq!( + cognition.records[0]["holder"]["id"], + json!(created.carrier_entry_id), + "the record is held by the Mind's carrier" + ); + assert_eq!( + cognition.mind_state["holder_entry_id"], + json!(created.carrier_entry_id), + "the derived state descends from that carrier" + ); +} + +#[tokio::test] +async fn an_intent_that_arrives_after_the_snapshot_refuses_the_commit() { + let (_dir, store) = fixture().await; + let owner = CallerId::new(OWNER); + let created = ok(minds::create(&store, &request(OWNER)).await); + let handle = ok(Mind::open(&store, &owner, &created.id).await); + let target = cognition_target(&created.carrier_entry_id); + + let reasoner = Arc::new(RecordingIntentReasoner { + pool: store.pool().clone(), + space_id: created.id.as_str().to_string(), + }); + let refuse = reject_of(deliberate(&store, &owner, &created.id, &target, reasoner).await); + assert_eq!(refuse.code, SpokeRejectCode::InternalError); + let details = refuse.details.as_ref().expect("structured details"); + assert_eq!( + details.get("reason").and_then(Value::as_str), + Some("UNRECONCILED"), + "the space-level withhold refused the commit" + ); + assert_eq!( + details.get("space_id").and_then(Value::as_str), + Some(created.id.as_str()) + ); + + assert!( + ok(handle.cognition_read().await).is_none(), + "the refused commit wrote no record" + ); + let carrier = ok(handle.knowledge_get(handle.carrier_entry_id(), None).await); + assert_eq!( + carrier.revision, + Some(1), + "the refused commit moved no carrier revision" + ); +} diff --git a/crates/mindcore-spi/src/workflows.rs b/crates/mindcore-spi/src/workflows.rs index efa0a85..926a5d2 100644 --- a/crates/mindcore-spi/src/workflows.rs +++ b/crates/mindcore-spi/src/workflows.rs @@ -948,6 +948,17 @@ impl SpiMindWorkflows { lens: Option<&dyn DomainLens>, caps: &MindCapabilities<'_>, ) -> Result { + // The record's context is a trusted input resolved once, from the + // request alone: a request naming neither an explicit context nor a + // subject to derive one from is the caller's invalid input, whatever + // branch the verdict later takes. No provider or storage phase runs + // first, so a `none` verdict cannot make such a request succeed. + if request.assessment_context_id.is_none() && request.subject_id.is_none() { + return Err(SpiError::InvalidInput( + "the request names neither an assessment context nor a subject to derive it from" + .to_string(), + )); + } let Some(reasoner) = caps.reasoner else { return Err(SpiError::ReasonerUnavailable); }; diff --git a/crates/mindcore-spoke/src/workflows.rs b/crates/mindcore-spoke/src/workflows.rs index ff00640..5f4f25e 100644 --- a/crates/mindcore-spoke/src/workflows.rs +++ b/crates/mindcore-spoke/src/workflows.rs @@ -368,6 +368,25 @@ impl MemoryWorkflowBinding { .map(|route| route.collection.as_str()) } + /// A bound carrier is the only carrier this binding serves in its space: a + /// holder naming any other entry is refused before any carrier read or + /// append, so the binding's identity is enforced and not merely resolved. + fn require_bound_carrier( + &self, + space_id: &str, + holder: &CognitionReference, + ) -> Result<(), SpiError> { + if let Some((bound_space, _, carrier_entry_id)) = &self.carrier_binding { + if bound_space == space_id && carrier_entry_id != holder.id.as_str() { + return Err(SpiError::InvalidInput(format!( + "holder {} does not name the carrier this binding serves", + holder.id.as_str() + ))); + } + } + Ok(()) + } + /// The collection the carrier write serves: `principal` must have a route — /// or the binding a bound carrier — and hold a live grant for every one of /// `capabilities` in `space_id`. @@ -1095,6 +1114,7 @@ impl WorkflowBinding for MemoryWorkflowBinding { holder: &CognitionReference, max_items: u64, ) -> Result { + self.require_bound_carrier(space_id, holder)?; let mut transaction = self.pool.begin().await.map_err(|error| { internal(format!( "deliberation read transaction could not begin: {error}" @@ -1172,6 +1192,7 @@ impl WorkflowBinding for MemoryWorkflowBinding { cited: &[CitedRecord], deadline: std::time::Instant, ) -> Result { + self.require_bound_carrier(space_id, holder)?; // The pool holds one connection in production, so an acquire can wait // for another statement indefinitely: the request deadline bounds that // wait, and a connection in hand is re-checked before the begin. Both diff --git a/crates/mindcore-spoke/tests/workflows.rs b/crates/mindcore-spoke/tests/workflows.rs index 733d07b..5b03060 100644 --- a/crates/mindcore-spoke/tests/workflows.rs +++ b/crates/mindcore-spoke/tests/workflows.rs @@ -4408,3 +4408,131 @@ async fn a_settle_waits_out_a_short_hold_until_its_deadline() { assert_eq!(records.len(), 1); assert_eq!(records[0]["record_id"], "cog_waited"); } + +/// A bound binding serves exactly the carrier its row names: a holder naming +/// any other entry of the same collection is refused at both boundaries, so a +/// caller cannot read or append cognition beside the Mind's own carrier. +#[tokio::test] +async fn a_bound_carrier_refuses_a_holder_that_names_another_entry() { + let harness = deliberate_harness().await; + let binding = settle_binding(&harness.pool).with_carrier_collection(SPACE, "wren", CARRIER); + let other: spoke_schemas::data::cognition::CognitionReference = + serde_json::from_value(cognition_reference("ke_not_the_carrier")).expect("other holder"); + + let refused = binding + .deliberate_snapshot(&principal(), SPACE, Some(SUBJECT), &other, 32) + .await + .expect_err("a foreign holder is refused before any carrier read"); + assert!( + matches!(refused, SpiError::InvalidInput(_)), + "the binding's identity is enforced, got {refused:?}" + ); + + let deadline = std::time::Instant::now() + Duration::from_secs(5); + let refused = binding + .commit_cognition( + &principal(), + SPACE, + Some(SUBJECT), + &other, + 1, + settle_record("cog_foreign"), + &[], + deadline, + ) + .await + .expect_err("a foreign holder is refused before any write"); + assert!( + matches!(refused, SpiError::InvalidInput(_)), + "the commit refuses the foreign holder too, got {refused:?}" + ); + assert_eq!( + harness.count_from("cognition_records").await, + 0, + "the refused commit appended nothing" + ); + + // The control: the bound carrier itself is served. + let snapshot = binding + .deliberate_snapshot(&principal(), SPACE, Some(SUBJECT), &settle_holder(), 32) + .await + .expect("the bound carrier is the one this binding serves"); + assert_eq!(snapshot.carrier_revision, 1); +} + +/// A request naming neither a subject nor an assessment context is the caller's +/// invalid input: the check runs before the snapshot and the reasoner, so even a +/// verdict that would write nothing cannot make it succeed. +#[tokio::test] +async fn a_request_naming_neither_subject_nor_context_is_refused_before_the_verdict() { + struct NoRecordReasoner(Arc); + + #[async_trait] + impl Reasoner for NoRecordReasoner { + async fn reason_structured( + &self, + _request: StructuredReasonRequest<'_>, + ) -> Result { + self.0.fetch_add(1, Ordering::SeqCst); + Ok(json!({ + "recommendation": { "kind": "none" }, + "rationale": "nothing worth recording", + "evidence_ids": [], + "record_ids": [], + })) + } + } + + let harness = deliberate_harness().await; + let calls = Arc::new(AtomicUsize::new(0)); + let reasoner = NoRecordReasoner(Arc::clone(&calls)); + let caps = MindCapabilities { + reasoner: Some(&reasoner), + ..MindCapabilities::default() + }; + let workflows = SpiMindWorkflows::new( + MemoryWorkflowBinding::new(harness.pool.clone(), true) + .with_knowledge_routes(routes(&[PRINCIPAL])) + .expect("the fixture route map is valid"), + ); + let holder: spoke_schemas::data::cognition::CognitionReference = + serde_json::from_value(cognition_reference(CARRIER)).expect("holder"); + let target: spoke_schemas::data::cognition::CognitionTarget = serde_json::from_value(json!({ + "carrier": cognition_reference(CARRIER), + "target_id": "prop_gate_closed", + "kind": "proposition", + })) + .expect("target"); + let evidence = [mindcore_spi::Evidence { + id: "ev_gate", + text: "the gate test passed on this commit", + }]; + let request = mindcore_spi::DeliberateRequest { + space_id: SPACE, + subject_id: None, + assessment_context_id: None, + holder: &holder, + target: &target, + evidence: &evidence, + timeout: Duration::from_secs(5), + }; + + let refused = workflows + .deliberate(&principal(), request, None, &caps) + .await + .expect_err("a request with neither subject nor context is refused"); + assert!( + matches!(refused, SpiError::InvalidInput(_)), + "the refusal is the caller's invalid input, got {refused:?}" + ); + assert_eq!( + calls.load(Ordering::SeqCst), + 0, + "no reasoner work ran before the request was refused" + ); + assert_eq!( + harness.count_from("cognition_records").await, + 0, + "the refused request wrote nothing" + ); +} From a9783e6959699cbcc278eecf84aed636677ed893 Mon Sep 17 00:00:00 2001 From: Tang Bohao Date: Thu, 26 Nov 2026 09:38:56 +0800 Subject: [PATCH 09/22] facade: the written contract, the documented example and the quickstart path MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Task 5 of plan mind-facade: .agents/specs/architecture/facade.md states the facade contract — the handle, the eight operations with what each composes, the review fold, the subjectless deliberate — and its non-goals; mind-model.md records the optional judgment subject and the Mind-id assessment context a facade deliberate stamps. crates/mindcore-runtime/examples/mind_facade.rs is the documented example: create a Mind, capture, review, recall, write and read the carrier with one cognition record, read the derived MindState — with no transaction, principal, wire request body or stage fold in it. docs/quickstart.md leads its Mind path with the facade. --- .agents/specs/architecture/facade.md | 113 +++++++++ .agents/specs/architecture/mind-model.md | 2 + .../mindcore-runtime/examples/mind_facade.rs | 223 ++++++++++++++++++ docs/quickstart.md | 94 +++++++- 4 files changed, 425 insertions(+), 7 deletions(-) create mode 100644 .agents/specs/architecture/facade.md create mode 100644 crates/mindcore-runtime/examples/mind_facade.rs diff --git a/.agents/specs/architecture/facade.md b/.agents/specs/architecture/facade.md new file mode 100644 index 0000000..7d77ced --- /dev/null +++ b/.agents/specs/architecture/facade.md @@ -0,0 +1,113 @@ +# Architecture: the in-process facade over a Mind + +## Scope + +The convenience contract of `mindcore_runtime::Mind`, the library's in-process facade over one +Mind: which operations it offers, what each composes, and what it never does. It excludes the +wire contract of the served surface (`serving-seam.md`), per-principal serving routing +(`serving-principal-routing.md`) and the record and storage invariants behind every operation +(`mind-model.md`). + +## Current state + +### The handle + +`Mind::open(store, caller, mind_id)` is one registry read — `minds::get` under the caller's live +grants — and a Mind the caller cannot see answers the registry's own `NotFound`. The handle keeps +the row that read answers — the id, the knowledge collection, the carrier entry id — and nothing +about grants: it caches no grant and acts on no status from the row, so a frozen Mind opens and +every later operation re-reads the live state on its own transaction. The handle is not a grant: +it confers no access beyond what the caller's live grants admit on every operation. + +Two inputs are the host's and the handle never invents them, as on the served surface: the journal +publisher `review` settles through, supplied with `with_journal_publisher` (`journal_dir(root)` is +the one publisher the crate offers), and the providers `deliberate` reasons with, supplied with +`with_providers`. `review` without a publisher and `deliberate` without a reasoner are refused +with the binding's and the workflow's own refusals. + +### The operations + +| Operation | Composes | Transaction | Grants re-checked | +|---|---|---|---| +| `capture(&Capture)` | the memory adapter's `capture` with the Mind's id as `space_id` | one `BEGIN IMMEDIATE`, committed | the adapter's own, over the caller-named subject and placement | +| `review(candidate_id, decision, key)` | `get_candidate`, then `review_candidate` staged in one `BEGIN IMMEDIATE`; the staged intent read on it; publication before the staging commits; `settle_journal` on a second transaction | the fold below | the adapter's own: `review` and `records_write` over the candidate | +| `recall(&Recall)` | the memory adapter's `recall` | one read transaction, rolled back | the adapter's own, over the caller-named selection | +| `knowledge_get(entry_id, revision)` | `read_entry`, or `read_entry_at_revision` when a revision is named, on the row's collection | one read transaction, rolled back | space-wide `knowledge_read` | +| `knowledge_put(entry, expected)` | `write_entry` — the one cognition validation boundary — on the row's collection | one `BEGIN IMMEDIATE`, committed | space-wide `knowledge_write` | +| `knowledge_list()` | `list_entries_in` on the row's collection | one read transaction, rolled back | space-wide `knowledge_read` | +| `cognition_read()` | `MemoryAdapter::read_cognition`: the carrier read and the derivation, nothing persisted | one read transaction, rolled back | space-wide `knowledge_read` | +| `deliberate(&Deliberation)` | `SpiMindWorkflows::deliberate` with no subject, the row's carrier as holder and the Mind's id as assessment context | the workflow's own | space-wide `recall`, with the space-level withhold | + +No operation accepts a collection, an `owner` or a `viewpoint` from the caller. `Capture.subject` +and `Recall.subject` are the caller's and are never defaulted; `review` reads its subject from the +candidate's row. No step returns a facade-invented refusal: each is the registry's, the store's or +the adapter's own code, and a revision below an entry's floor answers the store's +`HistoryTruncated` and a moved revision its `StoredRevisionStale`. + +### The `review` fold + +`review` answers the settled receipt, not a stage. Inside one `BEGIN IMMEDIATE` it stages the whole +decision through `review_candidate`, reads the staged intent on the same transaction and publishes +the owed targets **before the staging is durable**: a refused publication rolls everything back — +no record row, no intent, a pending candidate — and the same idempotency key can be repeated, with +the publisher's own `SpiError::Settlement` refusal traveling unchanged. Only after a successful +publication does the staging commit; settlement then runs on a second transaction, and any failure +from there answers `OUTCOME_UNCERTAIN` because durable work may be outstanding. A receipt already +settled is replayed as it is. The ordering differs from the served surface deliberately: the served +caller holds the receipt protocol that resolves `OUTCOME_UNCERTAIN` over a staged record; the +facade's caller does not, so a failed publication leaves no record to resolve. The cost is an +orphan published file when the process dies between publication and the staging commit. + +### `deliberate` without a subject + +The facade's `deliberate` names a target and evidence only; it takes no `subject_id` and never +chooses one. The request carries no subject, so the snapshot serves no memory page — a verdict can +cite evidence and existing cognition records only, and a `record_ids` entry naming a memory record +is refused as not visible — and the two checks the subject-level path runs over the subject run +over the whole space instead: a space-wide live `recall` grant is required, and any unsettled +intent in the space withholds the commit, whichever subject it belongs to. The record it settles +stamps the Mind's id as `assessment_context.context_id`. The served `deliberate`, which still +carries `subject_id`, takes the subject-level path unchanged. + +`create`, `list` and `get` remain the only registry entry points. The facade adds no write path +and moves no validation point: every write still goes through the existing adapter/repository +boundary, and the cognition module keeps its single persistence validation inside `write_entry`. + +### `cognition_read` + +The carrier is read on the handle's collection and derived; nothing is persisted. A carrier that +holds no current-view record yet — every Mind until its first judgment — answers `None`, not a +refusal: a Mind without a judgment is a state, not an error. After one record, the read answers +the carrier's current-view records and the derived `MindState` named by the Mind's id. + +## Non-goals + +- The served surface and its many-Mind routing; the wire contract is unchanged — no operation is + added, removed or renamed and no argument changes. +- The native binding, which will wrap this facade; the daemon; any release before SPOKE 0.19.0. +- Space-level capabilities as a public facade surface; they stay available through the existing + APIs. +- A second write path, a moved validation point, or any grant widening. +- Subject defaulting: no facade operation chooses a subject for the caller. +- Host provisioning: subject registration, grant administration beyond the `create` row, the + journal publisher and the model providers are the embedding host's, as on the served surface. + +## Invariants + +- `open` is the registry's read and nothing more: the handle caches no grant and acts on no status + from the row. +- Every operation opens its own transaction and admits the caller under its live grants on it + before reading or writing. +- A failed publication leaves no record, no intent and a pending candidate; a failure after a + durable staging answers `OUTCOME_UNCERTAIN`. +- No facade operation accepts or derives a caller-supplied collection, owner or viewpoint. +- A subjectless `deliberate` settles only on space-level admission and writes its record with the + Mind's id as the assessment context. + +## Where it lives + +- `crates/mindcore-runtime/src/mind.rs` — the handle, its operations and the `review` fold. +- `crates/mindcore-runtime/src/journal.rs` — `journal_dir`, the crate's one journal publisher. +- `crates/mindcore-runtime/examples/mind_facade.rs` — the documented end-to-end example: + `cargo run --offline -p mindcore-runtime --example mind_facade`. +- Tests: `crates/mindcore-runtime/tests/mind.rs`. diff --git a/.agents/specs/architecture/mind-model.md b/.agents/specs/architecture/mind-model.md index f6f716e..70f675f 100644 --- a/.agents/specs/architecture/mind-model.md +++ b/.agents/specs/architecture/mind-model.md @@ -23,6 +23,8 @@ The first delivered contract of Mindcore: what a Mind is, which records carry wh - A present `order` on a stored cognition record must be written as a JSON integer representation: the pinned `BeliefOrder` type reads `i64` only, so `1.0` (or any non-integer number) is refused at the same carrier boundary — append and `put_knowledge_entry` share this rule, and the generic IR codec is not narrowed. - A deliberation attempt projects into one SPOKE `Judgment` (`spoke-judgment`, schema version `1`) in `crates/mindcore-spi/src/judgment.rs`: the workflow builds it from values the attempt already holds and validates it with the released `validate_judgment_typed` before returning it, so no response carries a judgment the validator refuses. `judgment_kind` is `mindcore:deliberate`; `target` is the request's cognition target as `{kind, id, namespace}` with no `revision`; `evidence[]` is exactly the cited memory records, one `memory_record`/`mindcore` reference per cited entry with that entry's stored positive revision, empty when nothing is cited; `verdict.outcome` is `mindcore:` for the attempt's own branch (`no_change`, `needs_review`, `settled`), `verdict.detail` carries the verdict's `recommendation`, `evidence_ids` and `record_ids`, and `basis` is the verdict's rationale. No confidence is written, because the verdict carries none. - `judgment_id` is `jd_` plus the JCS SHA-256 of `{principal_id, space_id, subject_id, holder, target, status, verdict}`: equal attempt content yields an equal id, and another branch or another verdict yields another. `created_at` is the workflow clock read once where the judgment is built and enters no digest. The projection reads no store, so a cited entry that carries no stored revision is refused rather than given a derived one. +- The subject of a judgment is optional. The served `deliberate` names one and takes the subject-level path — its snapshot recall, its grant re-check and its unsettled-intent check run over that subject; a facade `deliberate` names none, skips the snapshot recall (a verdict cites evidence and existing cognition records only, and a `record_ids` entry naming a memory record is refused), requires a space-wide live `recall` grant and withholds while any intent in the space is unsettled. An absent subject enters the `judgment_id` digest and the record id digest as `null`. A facade `deliberate` stamps the Mind's id as the record's `assessment_context.context_id` — one component of the record's compound item identity — while the served path derives it from the subject when the request names none, and a request naming neither context nor subject is `InvalidInput`. +- The facade is `mindcore_runtime::Mind` (`facade.md`): one handle per Mind whose `open` is one registry read and whose operations compose the existing adapter, ports and workflows — `capture`, `review` (the publish-before-commit fold), `recall`, `knowledge_get`/`put`/`list`, `cognition_read` and `deliberate` — each opening its own transaction and admitting the caller under its live grants on it. It adds no write path: memory writes go through the adapter, knowledge writes through `write_entry` with its single cognition validation, and no operation accepts a collection, `owner` or `viewpoint` from the caller. ## Invariants diff --git a/crates/mindcore-runtime/examples/mind_facade.rs b/crates/mindcore-runtime/examples/mind_facade.rs new file mode 100644 index 0000000..e129247 --- /dev/null +++ b/crates/mindcore-runtime/examples/mind_facade.rs @@ -0,0 +1,223 @@ +//! The documented facade example: one Mind end to end through `mindcore_runtime::Mind`. +//! +//! In order the example `create`s a Mind, opens its handle, captures a memory, reviews it, +//! recalls the settled record, writes the carrier with one cognition record through the one +//! validation boundary, reads it back, and reads the derived `MindState`. None of the assembly +//! a served caller performs is here: no transaction of its own, no wire principal, no wire +//! request bodies, no stage fold — the handle composes each of those. +//! +//! Host provisioning: the subject row a memory write needs is the host's job, as on the served +//! surface. A single row insert is a complete atomic write in SQLite, so the seed runs on the +//! pool without an explicit transaction. + +use mindcore_base::boundary::CallerId; +use mindcore_base::cognition::append_cognition_record; +use mindcore_runtime::minds::{self, CreateMind}; +use mindcore_runtime::{journal_dir, Capture, Mind, Recall}; +use mindcore_sqlite::MindStore; +use serde_json::{json, Value}; +use spoke_operations::SpokeResult; +use spoke_schemas::memory_candidates_review_request::Decision; + +const OWNER: &str = "caller_wren"; +const SUBJECT: &str = "subj_wren"; + +/// The value of a successful call; a refusal aborts the example with its code and message. +fn ok(result: SpokeResult, step: &str) -> T { + match result { + SpokeResult::Ok(value) => value, + SpokeResult::Reject(reject) => panic!("{step} refused: {}: {}", reject.code, reject.message), + } +} + +fn value_of(response: &T) -> Value { + serde_json::to_value(response).expect("a response serializes") +} + +#[tokio::main] +async fn main() { + let dir = tempfile::TempDir::new().expect("a scratch directory"); + let store = MindStore::open(&dir.path().join("mind.db")) + .await + .expect("open the store"); + + // 1. Create the Mind. The registry writes the space, the carrier entry in the Mind's + // collection, the registry row and the owner's grant row in one transaction. + let owner = CallerId::new(OWNER); + let created = ok( + minds::create( + &store, + &CreateMind { + mind_id: None, + display_name: Some("Wren".to_string()), + owner: owner.clone(), + }, + ) + .await, + "create", + ); + println!("mind created: {}", created.id.as_str()); + + // Host provisioning, as the embedding host performs before capture: the subject row the + // memory writes need. This is the host's setup, not a facade operation. + sqlx::query( + "INSERT INTO memory_subjects (space_id, subject_id, status, revision, created_at) \ + VALUES (?, ?, 'active', 1, '2026-01-01T00:00:00.000Z')", + ) + .bind(created.id.as_str()) + .bind(SUBJECT) + .execute(&store.pool()) + .await + .expect("provision the subject"); + + // 2. Open the handle. The crate's one journal publisher writes the review's file effects + // under the scratch root at their own paths. + let journal_root = dir.path().join("journal"); + let mind = ok(Mind::open(&store, &owner, &created.id).await, "open") + .with_journal_publisher(journal_dir(journal_root)); + + // 3. Capture a memory: plain arguments, never a wire request body. + let content_text = "the north gate is shut after dusk"; + let content = json!({ "text": content_text }); + let capture = Capture { + subject: SUBJECT, + context: None, + content: &content, + occurred_at: None, + kind_hint: None, + idempotency_key: "cap-north-gate", + }; + let captured = ok(mind.capture(&capture).await, "capture"); + let candidate_id = value_of(&captured)["result"]["candidate_ids"][0] + .as_str() + .expect("the capture stages one candidate") + .to_string(); + + // 4. Review the candidate. The answer is the settled receipt: the fold — staging, + // publication, settlement — is the handle's, and the caller never sees it. + let promote: Decision = serde_json::from_value(json!({ "action": "promote" })) + .expect("a promote decision"); + let reviewed = ok( + mind.review(&candidate_id, &promote, "rev-north-gate").await, + "review", + ); + let record_id = value_of(&reviewed)["result"]["record_ids"][0] + .as_str() + .expect("promote retains one record") + .to_string(); + + // 5. Recall: the reviewed record is live. + let selection = json!({ "mode": "subject_all" }); + let recall = Recall { + subject: SUBJECT, + selection: &selection, + max_items: Some(10), + max_bytes: None, + query: None, + cursor: None, + }; + let page = value_of(&ok(mind.recall(&recall).await, "recall")); + let record = page["records"] + .as_array() + .expect("a records page") + .iter() + .find(|record| record["record_id"] == record_id) + .expect("the reviewed record is recallable") + .clone(); + assert_eq!( + record["content"]["text"], + json!(content_text), + "the record carries the captured content" + ); + println!( + "recalled record: {}", + serde_json::to_string_pretty(&record).expect("the record prints") + ); + + // 6. Write the carrier with one cognition record: an explicit carrier update through the + // one validation boundary, so the next step has a judgment to derive. The entry id + // comes from the handle; the example never names `ke_carrier`. + let carrier = ok( + mind.knowledge_get(mind.carrier_entry_id(), None).await, + "read the carrier", + ); + let carrier_revision = carrier.revision.expect("a stored carrier has a revision"); + let record_one = json!({ + "kind": "belief", + "order": 1, + "record_id": "cog_north_gate", + "holder": { + "kind": "knowledge_entry", + "namespace": "mindcore", + "id": mind.carrier_entry_id(), + }, + "target": { + "carrier": { + "kind": "knowledge_entry", + "namespace": "mindcore", + "id": mind.carrier_entry_id(), + }, + "target_id": "prop_north_gate_shut", + "kind": "proposition", + }, + "assessor": { + "kind": "principal", + "namespace": "mindcore", + "id": OWNER, + }, + "assessor_role": "holder_self_report", + "basis": { + "kind": "evidence", + "evidence": [{ "kind": "memory_record", "namespace": "mindcore", "id": record_id }], + }, + "assessment_context": { "context_id": created.id.as_str() }, + "assessed_at": "2026-01-01T00:30:00Z", + "effective_at": "2026-01-01T00:30:00Z", + "view": "current", + "q": { + "value": 0.8, + "assertion": "belief_attribution", + "method": "two_witness_reports", + "calibration": "uncalibrated", + }, + "extensions": {}, + }); + let updated = append_cognition_record(&carrier, record_one) + .expect("one valid record appends to the carrier"); + let written = ok( + mind.knowledge_put(updated, Some(carrier_revision)).await, + "write the carrier", + ); + assert_eq!( + written.revision, + Some(carrier_revision + 1), + "the carrier update is one revision step" + ); + let read_back = ok( + mind.knowledge_get(mind.carrier_entry_id(), None).await, + "read the written carrier", + ); + assert_eq!( + read_back.revision, + Some(carrier_revision + 1), + "the read answers the written revision" + ); + + // 7. Read the judgment: the carrier's one current-view record and the `MindState` derived + // from it, for the Mind the handle names. + let cognition = ok(mind.cognition_read().await, "cognition read") + .expect("one record on the carrier is a judgment"); + assert_eq!(cognition.records.len(), 1, "the one current-view record"); + assert_eq!( + cognition.mind_state["mind_state_id"], + json!(created.id.as_str()), + "the Mind's id names its derived state" + ); + println!( + "derived MindState: {}", + serde_json::to_string_pretty(&cognition.mind_state).expect("the state prints") + ); + + store.close().await; + println!("facade example complete: capture, review, recall, carrier, MindState"); +} diff --git a/docs/quickstart.md b/docs/quickstart.md index 2a2839e..887efb3 100644 --- a/docs/quickstart.md +++ b/docs/quickstart.md @@ -1,15 +1,16 @@ # Quick start -This tutorial takes you from an empty directory to a derived `MindState`, using the same code the -repository's integration test runs. It is a guided path, not a complete API reference. +This tutorial takes you from an empty directory to a derived `MindState`. The short path is the +facade — one handle whose operations compose everything below — and the sections after it show +what it composes, for a host that needs the manual transaction-level control. It is a guided +path, not a complete API reference. ## What you will do -1. Open an embedded SQLite store. -2. Capture a memory and see why it is not recallable yet. -3. Read and write a scoped knowledge entry. -4. Derive the current judgment from a cognition carrier. -5. Run the full first-mind story. +1. Create a Mind and open its handle. +2. Capture a memory, review it and recall the settled record. +3. Write the carrier with one cognition record and read the derived `MindState`. +4. See the transaction-level assembly the facade performs for you. ## Prerequisites @@ -18,6 +19,85 @@ repository's integration test runs. It is a guided path, not a complete API refe feature, so `libsqlite3-sys` links against the system library. - `sqlite3` CLI and `sqlx-cli` only if you also run the repository checks. +## The facade path: one Mind end to end + +The facade is `mindcore_runtime::Mind` — the library's in-process handle over one Mind. You never +open a transaction, shape a wire request or settle a stage yourself: each method composes the +operation for you and admits the caller under its live grants. The complete documented example +is [`crates/mindcore-runtime/examples/mind_facade.rs`](../crates/mindcore-runtime/examples/mind_facade.rs); +run it from a checkout of this repository: + +```sh +cargo run --offline -p mindcore-runtime --example mind_facade +``` + +It prints the recalled record and the derived `MindState`. In order, the example: + +1. `create`s a Mind through the registry — the space, the carrier entry, the registry row and the + owner's grant row land in one transaction — and opens the handle with `Mind::open`: + +```rust +use mindcore_base::boundary::CallerId; +use mindcore_runtime::minds::{self, CreateMind}; +use mindcore_runtime::{journal_dir, Mind}; + +let owner = CallerId::new("caller_wren"); +let created = minds::create(&store, &CreateMind { + mind_id: None, + display_name: Some("Wren".to_string()), + owner: owner.clone(), +}).await; + +let mind = Mind::open(&store, &owner, &created.id).await + .with_journal_publisher(journal_dir("journal")); +``` + +`open` is one registry read; a Mind the caller cannot see answers the registry's own `NotFound`. +The journal publisher is the host's input — the facade never invents one — and `journal_dir` is +the one publisher the crate offers. Before memory writes, the host provisions the subject rows it +means to write under, exactly as on the served surface; the example shows the minimal seed. + +2. Captures a memory and reviews it, in plain arguments: + +```rust +use mindcore_runtime::{Capture, Recall}; + +let content = serde_json::json!({ "text": "the north gate is shut after dusk" }); +let captured = mind.capture(&Capture { + subject: "subj_wren", + context: None, + content: &content, + occurred_at: None, + kind_hint: None, + idempotency_key: "cap-north-gate", +}).await; +``` + +`capture` takes the caller-named subject — never a default — and `review` answers the settled +receipt instead of a stage: the fold (staging, publication, settlement) is the handle's. A failed +publication leaves no record and the same idempotency key can be repeated. + +3. Recalls the reviewed record with `mind.recall`, then writes the carrier entry — the one the + handle names with `carrier_entry_id()`, never a coordinate you compose — with one cognition + record through `knowledge_put`, the single validation boundary, and reads it back with + `knowledge_get`. That write is an explicit carrier update, so the last step has a judgment to + derive. + +4. Reads the Mind's judgment with `mind.cognition_read()`: the carrier's current-view records and + the `MindState` derived from them. A fresh carrier answers `None` — a Mind without a judgment + is a state, not an error. + +`knowledge_list` and `deliberate` sit on the same handle. The facade's `deliberate` takes a +target and evidence only — no subject — and stamps the Mind's id as the assessment context; the +full contract is [`facade.md`](../.agents/specs/architecture/facade.md). + +## What the facade composes: the transaction level + +The rest of this page is the manual path the facade performs for you — adapter calls on +transactions you own, the wire shapes each takes and the staged settlement of a review. Read it +to understand what the facade composes, or use it when a host needs control the handle does not +expose. + ## Add the dependency `mindcore-base` and `mindcore-sqlite` are on crates.io; let Cargo resolve the version the registry From 738410e1f79cc31c52f9b90dd46458262d00f965 Mon Sep 17 00:00:00 2001 From: Tang Bohao Date: Thu, 26 Nov 2026 09:42:04 +0800 Subject: [PATCH 10/22] quickstart: the facade snippets carry the real SpokeResult signatures MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The create/open snippet unwraps each call through the example's own ok helper — verbatim — and the capture snippet binds the Capture struct and extracts the candidate id from the response value, so both compile as written. Snippet compile-verified as a scratch example. --- docs/quickstart.md | 38 ++++++++++++++++++++++++++++++-------- 1 file changed, 30 insertions(+), 8 deletions(-) diff --git a/docs/quickstart.md b/docs/quickstart.md index 887efb3..3caa050 100644 --- a/docs/quickstart.md +++ b/docs/quickstart.md @@ -40,15 +40,31 @@ It prints the recalled record and the derived `MindState`. In order, the example use mindcore_base::boundary::CallerId; use mindcore_runtime::minds::{self, CreateMind}; use mindcore_runtime::{journal_dir, Mind}; +use spoke_operations::SpokeResult; + +// Every facade call answers a `SpokeResult`: unwrap yours the way your host handles refusals. +fn ok(result: SpokeResult, step: &str) -> T { + match result { + SpokeResult::Ok(value) => value, + SpokeResult::Reject(reject) => panic!("{step} refused: {}: {}", reject.code, reject.message), + } +} let owner = CallerId::new("caller_wren"); -let created = minds::create(&store, &CreateMind { - mind_id: None, - display_name: Some("Wren".to_string()), - owner: owner.clone(), -}).await; +let created = ok( + minds::create( + &store, + &CreateMind { + mind_id: None, + display_name: Some("Wren".to_string()), + owner: owner.clone(), + }, + ) + .await, + "create", +); -let mind = Mind::open(&store, &owner, &created.id).await +let mind = ok(Mind::open(&store, &owner, &created.id).await, "open") .with_journal_publisher(journal_dir("journal")); ``` @@ -63,14 +79,20 @@ means to write under, exactly as on the served surface; the example shows the mi use mindcore_runtime::{Capture, Recall}; let content = serde_json::json!({ "text": "the north gate is shut after dusk" }); -let captured = mind.capture(&Capture { +let capture = Capture { subject: "subj_wren", context: None, content: &content, occurred_at: None, kind_hint: None, idempotency_key: "cap-north-gate", -}).await; +}; +let captured = ok(mind.capture(&capture).await, "capture"); +let candidate_id = serde_json::to_value(&captured).expect("the response serializes") + ["result"]["candidate_ids"][0] + .as_str() + .expect("the capture stages one candidate") + .to_string(); ``` `capture` takes the caller-named subject — never a default — and `review` answers the settled From ccd4382e566f25679c1af71bff91b35b7517a348 Mon Sep 17 00:00:00 2001 From: Tang Bohao Date: Thu, 26 Nov 2026 10:11:29 +0800 Subject: [PATCH 11/22] fix(facade): close the plan-QC blocking wave B1-B5, A1-A4, D1-D3 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit B1: a settled key's replay reaches the adapter's receipt probe regardless of unsettled intents in the space — the facade reads candidate revision and status as metadata instead of the content-read get_candidate whose subject withhold says nothing about receipts; regression covers both the same subject's and another subject's unsettled intent. B2/A1/A2: cognition_read binds the collection the row resolved at open, derives in the facade over read_entry, and reuses the one validated record vector derive_mind_state owns instead of extracting it twice. B3: the publisher refuses absolute paths and any path carrying '..' or a root/prefix component before the first byte, with a confinement test. B4: durability sync is anchored at the journal root — never ancestors above it — and the write-only-root permission requirement is stated in journal.rs and facade.md. B5: publication runs on tokio's blocking pool; a deterministic parked- publisher test proves executor progress continues and nothing commits before the publication confirms. A3: the futures dev-dependency is gone; the interference handshake polls with a plain std::future::poll_fn. A4: the private durable_chain unit tests are removed with the helper; public behavior tests cover the publisher. D1: facade.md and the plan record that the facade is convenience, not a sandbox, and cite the real store boundary read_entry/write_entry/ list_entries_in rather than the adoption port. D2: facade.md states the OUTCOME_UNCERTAIN recovery contract, with a pending-replay test. D3: reflections-off is recorded in facade.md with its reason. --- .agents/specs/architecture/facade.md | 81 ++++-- Cargo.lock | 1 - crates/mindcore-runtime/Cargo.toml | 1 - crates/mindcore-runtime/src/journal.rs | 207 ++++----------- crates/mindcore-runtime/src/mind.rs | 176 +++++++++---- crates/mindcore-runtime/tests/mind.rs | 349 ++++++++++++++++++++++++- 6 files changed, 585 insertions(+), 230 deletions(-) diff --git a/.agents/specs/architecture/facade.md b/.agents/specs/architecture/facade.md index 7d77ced..4a7d81d 100644 --- a/.agents/specs/architecture/facade.md +++ b/.agents/specs/architecture/facade.md @@ -30,12 +30,12 @@ with the binding's and the workflow's own refusals. | Operation | Composes | Transaction | Grants re-checked | |---|---|---|---| | `capture(&Capture)` | the memory adapter's `capture` with the Mind's id as `space_id` | one `BEGIN IMMEDIATE`, committed | the adapter's own, over the caller-named subject and placement | -| `review(candidate_id, decision, key)` | `get_candidate`, then `review_candidate` staged in one `BEGIN IMMEDIATE`; the staged intent read on it; publication before the staging commits; `settle_journal` on a second transaction | the fold below | the adapter's own: `review` and `records_write` over the candidate | +| `review(candidate_id, decision, key)` | the candidate's revision and status read as metadata; `review_candidate` staged in one `BEGIN IMMEDIATE`; the staged intent read on it; publication off the async worker before the staging commits; `settle_journal` on a second transaction | the fold below | the adapter's own: `review` and `records_write` over the candidate | | `recall(&Recall)` | the memory adapter's `recall` | one read transaction, rolled back | the adapter's own, over the caller-named selection | | `knowledge_get(entry_id, revision)` | `read_entry`, or `read_entry_at_revision` when a revision is named, on the row's collection | one read transaction, rolled back | space-wide `knowledge_read` | | `knowledge_put(entry, expected)` | `write_entry` — the one cognition validation boundary — on the row's collection | one `BEGIN IMMEDIATE`, committed | space-wide `knowledge_write` | | `knowledge_list()` | `list_entries_in` on the row's collection | one read transaction, rolled back | space-wide `knowledge_read` | -| `cognition_read()` | `MemoryAdapter::read_cognition`: the carrier read and the derivation, nothing persisted | one read transaction, rolled back | space-wide `knowledge_read` | +| `cognition_read()` | the carrier `read_entry` on the row's collection, derived in the facade; nothing persisted | one read transaction, rolled back | space-wide `knowledge_read` | | `deliberate(&Deliberation)` | `SpiMindWorkflows::deliberate` with no subject, the row's carrier as holder and the Mind's id as assessment context | the workflow's own | space-wide `recall`, with the space-level withhold | No operation accepts a collection, an `owner` or a `viewpoint` from the caller. `Capture.subject` @@ -46,17 +46,44 @@ the adapter's own code, and a revision below an entry's floor answers the store' ### The `review` fold -`review` answers the settled receipt, not a stage. Inside one `BEGIN IMMEDIATE` it stages the whole -decision through `review_candidate`, reads the staged intent on the same transaction and publishes -the owed targets **before the staging is durable**: a refused publication rolls everything back — -no record row, no intent, a pending candidate — and the same idempotency key can be repeated, with -the publisher's own `SpiError::Settlement` refusal traveling unchanged. Only after a successful -publication does the staging commit; settlement then runs on a second transaction, and any failure -from there answers `OUTCOME_UNCERTAIN` because durable work may be outstanding. A receipt already -settled is replayed as it is. The ordering differs from the served surface deliberately: the served -caller holds the receipt protocol that resolves `OUTCOME_UNCERTAIN` over a staged record; the -facade's caller does not, so a failed publication leaves no record to resolve. The cost is an -orphan published file when the process dies between publication and the staging commit. +`review` answers the settled receipt, not a stage. Inside one `BEGIN IMMEDIATE` it reads the +candidate's revision and status as metadata and stages the whole decision through +`review_candidate`. The metadata read is deliberately not a content read: the adapter's +`get_candidate` withholds subject content while any of the subject's intents is unsettled, +which is correct for content but unrelated to a receipt — a settled key's replay must reach +the adapter's probe no matter what else in the space is unsettled, whether another of the +same subject's intents or another subject's in the same space. Admission does not move: +`review_candidate` authorizes the write, probes the receipt first and applies every fresh-work +gate on its own, and a replay is digest-identical, so the metadata read only rebuilds the +original `expected_revision`. + +The fold reads the staged intent on the same transaction and publishes the owed targets off +the async worker — the publisher writes and fsyncs synchronously, so it runs on the blocking +pool while nothing commits and unrelated executor work stays schedulable — **before the +staging is durable**: a refused publication rolls everything back — no record row, no intent, +a pending candidate — and the same idempotency key can be repeated, with the publisher's own +`SpiError::Settlement` refusal traveling unchanged. Only after a successful publication does +the staging commit; settlement then runs on a second transaction, and any failure from there +answers `OUTCOME_UNCERTAIN` because durable work may be outstanding. A receipt already settled +is replayed as it is. + +The `OUTCOME_UNCERTAIN` recovery contract: the caller repeats the review with the same +candidate, decision and idempotency key. While the receipt is still pending, the repeat +answers `OUTCOME_UNCERTAIN` again — the probe reports the pending receipt exactly as the fold +left it, with no second record and no second intent. When the receipt has committed, the same +repeat answers the settled receipt as any replay does. The ordering differs from the served +surface deliberately: the served caller holds the receipt protocol that resolves +`OUTCOME_UNCERTAIN` over a staged record; the facade's caller does not, so a failed publication +leaves no record to resolve. The cost is an orphan published file when the process dies +between publication and the staging commit. + +`journal_dir(root)` confines every target to its root: a target path that is absolute or +carries `..` is refused before its first byte. Durability is anchored at `root`, which the +host establishes as durable; publication syncs the file and every directory of the publisher's +tree down to the target, never ancestors outside the root. Syncing a directory opens it for +reading, so the host must grant read on `root` and every directory below it — a write-only +journal root cannot be published, because the sync that must precede settlement would be +refused for a reason the write itself never hit. ### `deliberate` without a subject @@ -75,10 +102,14 @@ boundary, and the cognition module keeps its single persistence validation insid ### `cognition_read` -The carrier is read on the handle's collection and derived; nothing is persisted. A carrier that -holds no current-view record yet — every Mind until its first judgment — answers `None`, not a -refusal: a Mind without a judgment is a state, not an error. After one record, the read answers -the carrier's current-view records and the derived `MindState` named by the Mind's id. +The carrier is read on the collection the row resolved at open — the read is bound to the +admitted Mind, and nothing the caller says can point it at another collection — and derived in +the facade; nothing is persisted. The derivation runs once: the validated record vector +`derive_mind_state` owns is projected into the wire `MindState` and moved into the answer, so +no second extraction pass copies the carrier's history. A carrier that holds no current-view +record yet — every Mind until its first judgment — answers `None`, not a refusal: a Mind +without a judgment is a state, not an error. After one record, the read answers the carrier's +current-view records and the derived `MindState` named by the Mind's id. ## Non-goals @@ -92,6 +123,22 @@ the carrier's current-view records and the derived `MindState` named by the Mind - Host provisioning: subject registration, grant administration beyond the `create` row, the journal publisher and the model providers are the embedding host's, as on the served surface. +### Admission decisions the spec records + +**The facade is convenience, not a sandbox.** An in-process caller already holds the store and +can read any row through it, so the facade deliberately does not reproduce the served path's +per-principal routing and disclosure predicates: a space-wide `knowledge_read` / +`knowledge_write` grant reaches the whole Mind collection, whatever `owner` an entry carries. +The boundary the facade composes is the store's own — `read_entry`, `write_entry` and +`list_entries_in`, the validation and revision checks inside them — not the adoption port +`put_knowledge_entry`, which is a different surface. + +**Reflections are off.** Every handle builds its adapter and workflow binding with +`reflections: false` and offers no switch: the reflection surface (§7.25–§7.27 of the SPOKE +spec) is a provider-level capability the facade's convenience contract does not expose, and a +host that needs it embeds the adapter or the served surface directly. + journal publisher and the model providers are the embedding host's, as on the served surface. + ## Invariants - `open` is the registry's read and nothing more: the handle caches no grant and acts on no status diff --git a/Cargo.lock b/Cargo.lock index c5ba15f..9ec456b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2094,7 +2094,6 @@ dependencies = [ "async-trait", "chrono", "ed25519-dalek 3.0.0", - "futures", "mindcore-base", "mindcore-spi", "mindcore-spoke", diff --git a/crates/mindcore-runtime/Cargo.toml b/crates/mindcore-runtime/Cargo.toml index e529e1f..9e6f91d 100644 --- a/crates/mindcore-runtime/Cargo.toml +++ b/crates/mindcore-runtime/Cargo.toml @@ -24,6 +24,5 @@ tokio = { workspace = true, features = ["sync"] } [dev-dependencies] ed25519-dalek = "3" -futures = "0.3" tempfile = "3.27.0" tokio = { workspace = true, features = ["macros", "rt-multi-thread"] } diff --git a/crates/mindcore-runtime/src/journal.rs b/crates/mindcore-runtime/src/journal.rs index cf6dc3b..de75222 100644 --- a/crates/mindcore-runtime/src/journal.rs +++ b/crates/mindcore-runtime/src/journal.rs @@ -1,7 +1,7 @@ //! The one journal publisher the crate offers: `journal_dir(root)` writes every journaled //! file target under `root` at the target's own path. -use std::path::{Path, PathBuf}; +use std::path::{Component, Path, PathBuf}; use mindcore_spi::SpiError; use serde_json::Value; @@ -10,16 +10,26 @@ use serde_json::Value; /// target's `path`, parent directories are created, and `Ok(())` is returned only when every /// target's exact bytes are durable. /// -/// Durability covers the whole required ancestry of each target, deepest first, through a -/// bounded anchor: the filesystem root for an absolute path, the current directory for a -/// relative one. The ancestry is a function of the target's path alone — never of which -/// directories happen to exist — so a retry after a publication that failed between creating -/// directories and syncing them is never weaker than the attempt that failed: it syncs the -/// same chain, including the entries the failed attempt left behind. +/// Confinement: a target path that is absolute or carries any `..` — a `ParentDir`, `RootDir` +/// or `Prefix` component — is refused before its first byte, so no target can ever write +/// outside `root` whatever a journaled row holds. +/// +/// The sync anchor is `root` itself. Publication creates no directory at or above it: the host +/// establishes `root` (or the path it will be created at) as already durable, so every entry +/// publication depends on lies within the publisher's own tree. Each target syncs its file, +/// then every directory of that tree its entry depends on, deepest first, ending at `root`. +/// The chain is a function of the target's path alone — never of which directories happen to +/// exist — so a retry after a publication that failed between creating directories and +/// syncing them syncs the same chain as the attempt that failed. +/// +/// Permission requirement: syncing a directory opens it for reading, which POSIX refuses for +/// a search-only directory, so the host must grant read on `root` and every directory below +/// it. A write-only journal root cannot be published: the write itself would succeed, but the +/// durability sync that must precede settlement would be refused for a reason the write never +/// hit. /// /// Target paths are the adapter's own (`records/.md`, `candidates/.md`, -/// `profiles/.md`): they carry no separators that could escape `root`, and they are -/// published as given rather than re-derived here. +/// `profiles/.md`): they are confined to `root` as given rather than re-derived here. pub fn journal_dir( root: impl Into, ) -> impl Fn(&[Value]) -> Result<(), SpiError> + Send + Sync + 'static { @@ -35,14 +45,28 @@ pub fn journal_dir( .ok_or_else(|| { SpiError::InvalidInput(format!("journal target {path} carries no content")) })?; + // Confinement is refused before the first byte of this target: an absolute path + // or one carrying `..` would escape `root` under `join`, whatever it names. + let confined = !Path::new(path).is_absolute() + && Path::new(path).components().all(|component| { + matches!( + component, + Component::Normal(_) | Component::CurDir + ) + }); + if !confined { + return Err(SpiError::InvalidInput(format!( + "journal target {path} is not confined to the journal root" + ))); + } let file = root.join(path); - // A target at the publisher root has the empty path as its parent; the current - // directory is what that names, and it is this publication's anchor. let parent = match file.parent() { Some(parent) if !parent.as_os_str().is_empty() => parent, - _ => Path::new("."), + // A target at the publisher root has the root itself as its parent: the + // confinement check above has already erased any `.` components, so the + // empty parent is reached only when the target names one plain file. + _ => root.as_path(), }; - let chain = durable_chain(parent); std::fs::create_dir_all(parent).map_err(|error| { SpiError::Settlement(spoke_reject(format!( "the directory for {path} could not be created: {error}" @@ -54,8 +78,9 @@ pub fn journal_dir( ))) })?; // Durability, not visibility: the write must reach the medium before the caller - // may settle the intent. Sync the file's contents, then the whole ancestry the - // target's entry depends on, deepest first. + // may settle the intent. Sync the file's contents, then every directory of the + // publisher's own tree its entry depends on, deepest first, ending at `root` — + // the anchor the host established as durable. std::fs::File::open(&file) .and_then(|file| file.sync_all()) .map_err(|error| { @@ -63,8 +88,9 @@ pub fn journal_dir( "journal target {path} could not be synced: {error}" ))) })?; - for directory in &chain { - std::fs::File::open(directory) + let mut cursor = Some(parent.to_path_buf()); + while let Some(directory) = cursor { + std::fs::File::open(&directory) .and_then(|directory| directory.sync_all()) .map_err(|error| { SpiError::Settlement(spoke_reject(format!( @@ -72,6 +98,14 @@ pub fn journal_dir( directory.display() ))) })?; + if directory == root { + break; + } + cursor = directory + .components() + .as_path() + .parent() + .map(Path::to_path_buf); } let landed = std::fs::read_to_string(&file).map_err(|error| { SpiError::Settlement(spoke_reject(format!( @@ -88,35 +122,6 @@ pub fn journal_dir( } } -/// The directories whose entries one target depends on, deepest first, through the bounded -/// anchor of its path: every ancestor named by the path, and then `/` for an absolute path or -/// `.` for a relative one. -/// -/// Existence is deliberately not consulted: the chain is the same for a first attempt and for -/// a retry after a failed attempt left some of those directories behind, so a retry can never -/// skip a directory entry the failed attempt created. -fn durable_chain(parent: &Path) -> Vec { - let mut chain = Vec::new(); - let mut cursor = parent.to_path_buf(); - loop { - if cursor.as_os_str().is_empty() { - chain.push(PathBuf::from(".")); - break; - } - let at_anchor = cursor == Path::new("."); - chain.push(cursor.clone()); - if at_anchor { - break; - } - match cursor.parent() { - Some(ancestor) => cursor = ancestor.to_path_buf(), - // An absolute path's anchor `/` has no parent and was already pushed. - None => break, - } - } - chain -} - /// The publisher's refusal: a retryable `INTERNAL_ERROR` — nothing the settlement leg staged /// is durable yet, so the same review can be repeated once the medium is writable. fn spoke_reject(message: String) -> spoke_operations::SpokeReject { @@ -131,113 +136,3 @@ fn spoke_reject(message: String) -> spoke_operations::SpokeReject { details: Some(details), } } - -#[cfg(test)] -mod tests { - use super::{durable_chain, journal_dir}; - use serde_json::json; - use std::path::{Path, PathBuf}; - - fn paths(chain: &[PathBuf]) -> Vec<&str> { - chain - .iter() - .map(|path| path.to_str().expect("utf-8")) - .collect() - } - - /// An absolute ancestry runs deepest first through `/`, even when nothing exists yet. - #[test] - fn an_absolute_chain_ends_at_the_filesystem_root() { - let chain = durable_chain(Path::new("/scratch/one/two/records")); - assert_eq!( - paths(&chain), - vec![ - "/scratch/one/two/records", - "/scratch/one/two", - "/scratch/one", - "/scratch", - "/" - ], - "every named ancestor, then the anchor" - ); - } - - /// A relative ancestry anchors at the current directory: the empty parent path never - /// reaches `File::open`, and no path in the chain is empty. - #[test] - fn a_relative_chain_anchors_at_the_current_directory() { - let chain = durable_chain(Path::new("journal/records")); - assert_eq!(paths(&chain), vec!["journal/records", "journal", "."]); - assert!( - chain.iter().all(|path| !path.as_os_str().is_empty()), - "an empty path can never be opened" - ); - } - - /// `journal_dir("journal")` builds `journal/records/…` style parents, so the relative - /// anchor is exercised exactly as the first publication of such a root would. - #[test] - fn a_relative_parent_under_the_current_directory_stops_at_it() { - assert_eq!( - paths(&durable_chain(Path::new("./records"))), - vec!["./records", "."] - ); - assert_eq!(paths(&durable_chain(Path::new("."))), vec!["."]); - } - - /// The chain depends on the path, never on which directories already exist: this is what - /// keeps a retry from being weaker than a failed first attempt. - #[test] - fn the_chain_is_identical_before_and_after_the_directories_exist() { - let directory = tempfile::TempDir::new().expect("temporary directory"); - let parent = directory.path().join("one/two/records"); - let before = durable_chain(&parent); - std::fs::create_dir_all(&parent).expect("create the tree"); - let after = durable_chain(&parent); - assert_eq!( - paths(&before), - paths(&after), - "a retry sees the same chain as the attempt that created the tree" - ); - } - - /// The failure/retry boundary: a refusal after an earlier target already created a tree - /// leaves directories behind; the retry syncs the same chain and lands both targets. - #[test] - fn a_retry_after_a_refused_publication_syncs_the_same_chain() { - let directory = tempfile::TempDir::new().expect("temporary directory"); - let root = directory.path().to_path_buf(); - let parent = root.join("nested").join("records"); - let before = durable_chain(&parent); - - let publish = journal_dir(&root); - let refused = publish(&[ - json!({ "path": "nested/records/one.md", "content": "one" }), - // The second target has no content: the first has already landed and created the - // tree when this one is refused. - json!({ "path": "nested/records/two.md" }), - ]); - assert!( - refused.is_err(), - "the malformed target refuses the publication" - ); - assert!(parent.is_dir(), "the failed attempt created the tree"); - - let after = durable_chain(&parent); - assert_eq!( - paths(&before), - paths(&after), - "the retry syncs the same ancestry, including what the failed attempt created" - ); - - publish(&[ - json!({ "path": "nested/records/one.md", "content": "one" }), - json!({ "path": "nested/records/two.md", "content": "two" }), - ]) - .expect("the retry publishes"); - assert_eq!( - std::fs::read_to_string(parent.join("two.md")).expect("the retried target"), - "two" - ); - } -} diff --git a/crates/mindcore-runtime/src/mind.rs b/crates/mindcore-runtime/src/mind.rs index c8c6111..b82e2d3 100644 --- a/crates/mindcore-runtime/src/mind.rs +++ b/crates/mindcore-runtime/src/mind.rs @@ -40,6 +40,7 @@ use spoke_schemas::{ Principal, }; use sqlx::SqlitePool; +use std::sync::Arc; use crate::tools::workflow_reject; @@ -57,7 +58,7 @@ pub struct Mind { caller: CallerId, row: MindRow, adapter: MemoryAdapter, - publisher: Option>, + publisher: Option>, providers: crate::MindProviders, } @@ -176,7 +177,7 @@ impl Mind { mut self, publish: impl Fn(&[Value]) -> Result<(), SpiError> + Send + Sync + 'static, ) -> Self { - self.publisher = Some(Box::new(publish)); + self.publisher = Some(Arc::new(publish)); self } @@ -422,7 +423,7 @@ impl Mind { decision: &Decision, idempotency_key: &str, ) -> SpokeResult { - let publisher = match self.publisher.as_deref() { + let publisher = match self.publisher.as_ref() { Some(publisher) => publisher, None => { return reject( @@ -443,41 +444,36 @@ impl Mind { } }; - // 1. Read the candidate as the plan requires: the revision this staging transaction - // must assert, and whether an earlier review already consumed it. A refusal is the - // adapter's own and rolls the transaction back. - let observed = self - .adapter - .get_candidate( - &mut transaction, - &caller, - json!({ "space_id": space.as_str(), "candidate_id": candidate_id }), - ) - .await; - let (revision, consumed) = match observed { - SpokeResult::Ok(MemoryStage::Ready(body)) => { - let Some(candidate) = body.get("candidate") else { - drop(transaction); - return retryable_internal("the candidate body carries no candidate"); - }; - let Some(revision) = candidate.get("revision").and_then(Value::as_u64) else { - drop(transaction); - return retryable_internal("the candidate body carries no integer revision"); - }; - let consumed = candidate.get("status").and_then(Value::as_str) == Some("consumed"); - (revision, consumed) - } - SpokeResult::Ok(stage) => { - drop(transaction); - return retryable_internal(format!( - "candidate read answered an unexpected stage: {stage:?}" - )); - } - SpokeResult::Reject(reject) => { + // 1. Read the candidate's revision and consumption status as metadata. A content-read + // path like `get_candidate` is deliberately not used here: its withhold on the + // subject's unsettled intents is correct for subject content but unrelated to a + // receipt, and it would keep a settled key's replay from ever reaching the adapter's + // probe while any other intent of the subject is unsettled. Admission itself does + // not move: `review_candidate` authorizes the write, probes the receipt first and + // applies every fresh-work gate on its own. A same-key replay is digest-identical, + // so this row only rebuilds the original `expected_revision` — a wrong value can + // never reach a receipt. + let observed: Option<(i64, String)> = match sqlx::query_as( + "SELECT revision, status FROM memory_candidates WHERE space_id = ? AND candidate_id = ?", + ) + .bind(space.as_str()) + .bind(candidate_id) + .fetch_optional(&mut *transaction) + .await + { + Ok(observed) => observed, + Err(error) => { drop(transaction); - return SpokeResult::Reject(reject); + return retryable_internal(format!("the candidate row could not be read: {error}")); } }; + let (revision, consumed) = match observed { + Some((revision, status)) => (u64::try_from(revision).unwrap_or(0), status == "consumed"), + // No row: stage at revision 1, the candidate's fresh-work value. `review_candidate` + // answers its own `NotFound` for a candidate that never existed; a replayed key of + // a consumed or pruned candidate is digest-guarded before this value can matter. + None => (1, false), + }; // 2. Stage on the same transaction. The adapter's dedup probe keys on // (space, requester, operation, idempotency_key) and digests the whole payload, so // a same-key replay must rebuild a byte-identical request to reach the recorded @@ -554,10 +550,27 @@ impl Mind { } }; - // 4. Publish before the staging is durable. A refusal rolls the transaction back: - // no record row, no intent and a pending candidate are left, and the publisher's own - // `SpiError::Settlement` refusal travels unchanged. - if let Err(error) = publisher(&intent.targets) { + // 4. Publish before the staging is durable, off the async worker: the publisher writes + // and fsyncs synchronously, so it runs on the blocking pool while the handle's task + // awaits it — unrelated executor work stays schedulable for the whole flush. The + // ordering is unchanged: nothing commits before the publisher has confirmed, and a + // refusal rolls the transaction back — no record row, no intent and a pending + // candidate are left, with the publisher's own `SpiError::Settlement` refusal + // traveling unchanged. The task is awaited to completion, so it always retains + // ownership of the publication, caller cancellation included. + let publish_targets = intent.targets.clone(); + let publish = { + let publisher = Arc::clone(publisher); + tokio::task::spawn_blocking(move || publisher(&publish_targets)) + }; + let published = match publish.await { + Ok(result) => result, + Err(error) => { + drop(transaction); + return retryable_internal(format!("the publication task failed to join: {error}")); + } + }; + if let Err(error) = published { drop(transaction); return match error { SpiError::Settlement(reject) => SpokeResult::Reject(reject), @@ -608,9 +621,13 @@ impl Mind { } } - /// Read this Mind's judgment: `MemoryAdapter::read_cognition` over one read - /// transaction, rolled back after the read. A fresh carrier answers `None`; - /// after one record, the judgment's records and the derived `MindState`. + /// Read this Mind's judgment over one read transaction, rolled back after the read. The + /// collection and carrier entry the transaction reads are the row's own — resolved from the + /// admitted Mind at `open`, never from the caller — so a space-wide `knowledge_read` grant + /// authorizes exactly the Mind that is read. A fresh carrier answers `None`; after one + /// record, the judgment's records and the derived `MindState`. The record list is the one + /// `derive_mind_state` already owns: the validated view is the single extraction, projected + /// once into the wire state and moved into the answer. pub async fn cognition_read(&self) -> SpokeResult> { let mut transaction = match self.pool.begin().await { Ok(transaction) => transaction, @@ -620,22 +637,79 @@ impl Mind { )) } }; - let read = self + let admission = self .adapter - .read_cognition( + .require_space_grants( &mut transaction, &principal(&self.caller), self.row.id.as_str(), - &self.row.knowledge.collection, - &self.row.carrier_entry_id, - self.row.id.as_str(), + &["knowledge_read"], ) .await; - drop(transaction); - match read { - Ok(cognition) => SpokeResult::Ok(cognition), - Err(error) => SpokeResult::Reject(workflow_reject(error)), + if let Err(error) = admission { + drop(transaction); + return SpokeResult::Reject(workflow_reject(error)); } + let carrier = match read_entry( + &mut transaction, + &self.row.knowledge.collection, + &self.row.carrier_entry_id, + ) + .await + { + SpokeResult::Ok(carrier) => carrier, + SpokeResult::Reject(reject) => { + drop(transaction); + return SpokeResult::Reject(reject); + } + }; + drop(transaction); + let revision = match carrier.revision { + Some(revision) => revision, + None => { + return reject( + SpokeRejectCode::InternalError, + format!( + "carrier {} holds no assigned revision", + self.row.carrier_entry_id + ), + "terminal", + ) + } + }; + let view = match mindcore_base::cognition::derive_mind_state(&carrier) { + Ok(view) => view, + Err(mindcore_base::cognition::MindError::NoRecords) => return SpokeResult::Ok(None), + Err(error) => { + return reject( + SpokeRejectCode::InternalError, + format!( + "carrier {} cannot be derived: {error}", + self.row.carrier_entry_id + ), + "terminal", + ) + } + }; + let mind_state = match mindcore_base::cognition::mind_state_value(&view, self.row.id.as_str()) + { + Ok(mind_state) => mind_state, + Err(error) => { + return reject( + SpokeRejectCode::InternalError, + format!( + "the mind state of {} cannot be projected: {error}", + self.row.carrier_entry_id + ), + "terminal", + ) + } + }; + SpokeResult::Ok(Some(Cognition { + carrier_revision: revision, + records: view.records, + mind_state, + })) } /// Deliberate one target over the evidence: `SpiMindWorkflows::deliberate` diff --git a/crates/mindcore-runtime/tests/mind.rs b/crates/mindcore-runtime/tests/mind.rs index a1782c2..3c14641 100644 --- a/crates/mindcore-runtime/tests/mind.rs +++ b/crates/mindcore-runtime/tests/mind.rs @@ -454,10 +454,16 @@ async fn a_refused_settle_answers_outcome_uncertain_and_leaves_the_intent_pendin tokio::spawn(async move { let acquire = interference_pool.acquire(); tokio::pin!(acquire); - assert!( - futures::poll!(acquire.as_mut()).is_pending(), - "the staging transaction still holds the one connection" - ); + // One poll with a no-op waker: the future must be pending because the staging + // transaction still holds the pool's one connection, and this first poll is + // what registers the task in the pool's FIFO queue. + let pending = std::future::poll_fn(|cx| { + let polled = std::future::Future::poll(acquire.as_mut(), cx); + assert!(polled.is_pending(), "the one connection is still checked out"); + std::task::Poll::Ready(()) + }) + .await; + let _ = pending; registered.send(()).expect("signal the registration"); let mut connection = acquire.await.expect("the one connection"); sqlx::query("UPDATE memory_journal SET state = 'deferred'") @@ -494,6 +500,98 @@ async fn a_refused_settle_answers_outcome_uncertain_and_leaves_the_intent_pendin ); } + +/// The `OUTCOME_UNCERTAIN` recovery contract: repeating the review with the same key while the +/// receipt is still pending answers the same uncertain outcome again — the recorded refusal, +/// never a staged duplicate and never silence. The repeat is byte-identical, so it reaches the +/// adapter's receipt probe directly, and the probe reports the still-pending receipt exactly as +/// the fold left it: no second record, no second intent, the candidate still consumed. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn a_repeat_after_outcome_uncertain_replays_the_pending_receipt_as_uncertain() { + let (dir, store) = fixture().await; + let owner = CallerId::new(OWNER); + let created = ok(minds::create(&store, &request(OWNER)).await); + ensure_subject(&store, created.id.as_str()).await; + let pool = store.pool(); + let journal_root = dir.path().to_path_buf(); + let handle = ok(Mind::open(&store, &owner, &created.id).await) + .with_journal_publisher(journal_dir(&journal_root)); + let candidate_id = capture_candidate( + &handle, + "cap-uncertain-replay", + "a note whose settlement outcome is unknown", + ) + .await; + + // The same interference handshake as `a_refused_settle_answers_outcome_uncertain`: the + // staging commit releases the one connection, and the registered task moves the intent out + // of pending before the settlement transaction can acquire it, so the settle is refused. + let interference_pool = pool.clone(); + let blocking = + ok(Mind::open(&store, &owner, &created.id).await).with_journal_publisher(move |targets| { + journal_dir(&journal_root)(targets)?; + let interference_pool = interference_pool.clone(); + let (registered, is_registered) = mpsc::channel::<()>(); + tokio::spawn(async move { + let acquire = interference_pool.acquire(); + tokio::pin!(acquire); + std::future::poll_fn(|cx| { + let polled = std::future::Future::poll(acquire.as_mut(), cx); + assert!(polled.is_pending(), "the one connection is still checked out"); + std::task::Poll::Ready(()) + }) + .await; + registered.send(()).expect("signal the registration"); + let mut connection = acquire.await.expect("the one connection"); + sqlx::query("UPDATE memory_journal SET state = 'deferred'") + .execute(&mut *connection) + .await + .expect("move the intent out of pending"); + }); + is_registered + .recv() + .expect("the interference task registered its acquisition"); + Ok(()) + }); + + let first = reject_of( + blocking + .review(&candidate_id, &promote(), "rev-uncertain-replay") + .await, + ); + assert_eq!( + first.code, + SpokeRejectCode::OutcomeUncertain, + "the refused settle answers OUTCOME_UNCERTAIN" + ); + + // The repeat: same candidate, decision and key, through a working publisher. The receipt + // is still pending, so the probe answers the uncertain outcome again without re-staging. + let working = ok(Mind::open(&store, &owner, &created.id).await) + .with_journal_publisher(journal_dir(dir.path())); + let repeat = reject_of( + working + .review(&candidate_id, &promote(), "rev-uncertain-replay") + .await, + ); + assert_eq!( + repeat.code, + SpokeRejectCode::OutcomeUncertain, + "a same-key repeat while the receipt is pending answers OUTCOME_UNCERTAIN: {repeat:?}" + ); + assert_eq!(retry_class(&repeat), "uncertain"); + assert_eq!( + count_records(&pool).await, + 1, + "the repeat stages no second record" + ); + assert_eq!( + count_intents(&pool).await, + 1, + "the repeat stages no second intent" + ); +} + /// The plan's step 1 is a real read of the candidate: a pending candidate imported at a /// non-1 revision stages at that revision, and its settled same-key replay still reaches the /// recorded receipt. A constant `expected_revision` would refuse the first call with @@ -1241,3 +1339,246 @@ async fn an_intent_that_arrives_after_the_snapshot_refuses_the_commit() { "the refused commit moved no carrier revision" ); } + +// ---------- QC fix wave: settled-key replay, publisher confinement and executor offload ---------- + +/// A settled key's replay reaches the receipt probe no matter what else the space holds +/// unsettled: another of the same subject's intents, or an intent of another subject in the +/// same space. The replay is metadata-identical to its first review, so the probe answers the +/// committed receipt — never the content withhold, which guards subject content and says +/// nothing about receipts. +#[tokio::test] +async fn a_settled_replay_survives_any_unsettled_intent_in_the_space() { + let (dir, store) = fixture().await; + let owner = CallerId::new(OWNER); + let created = ok(minds::create(&store, &request(OWNER)).await); + ensure_subject(&store, created.id.as_str()).await; + let handle = ok(Mind::open(&store, &owner, &created.id).await) + .with_journal_publisher(journal_dir(dir.path())); + let candidate_id = capture_candidate(&handle, "cap-settled-replay", "a settled note").await; + let settled = ok(handle + .review(&candidate_id, &promote(), "rev-settled-replay") + .await); + assert_eq!(value_of(&settled)["status"], "committed", "the first review settles"); + + // An unsettled intent for the same subject, as a crashed served absorb would leave one. + settle_never(&store, created.id.as_str(), SUBJECT).await; + let replayed = ok(handle + .review(&candidate_id, &promote(), "rev-settled-replay") + .await); + assert_eq!( + value_of(&replayed), + value_of(&settled), + "the settled key replays beside the same subject's unsettled intent" + ); + assert_eq!(count_records(&store.pool()).await, 1, "no second record is staged"); + assert_eq!(count_intents(&store.pool()).await, 2, "no second replay intent"); + + // The same key also replays beside an intent of another subject in the same space. + settle_never(&store, created.id.as_str(), "subj_elsewhere").await; + let replayed = ok(handle + .review(&candidate_id, &promote(), "rev-settled-replay") + .await); + assert_eq!( + value_of(&replayed), + value_of(&settled), + "the settled key replays beside another subject's unsettled intent" + ); + assert_eq!(count_records(&store.pool()).await, 1, "still no second record"); +} + +/// The publisher confines every target to its root: an absolute target path or one carrying +/// `..` is refused with nothing written outside the root. +#[tokio::test] +async fn the_public_publisher_refuses_a_target_outside_its_root() { + let dir = TempDir::new().expect("temporary directory"); + let root = dir.path().join("journal"); + std::fs::create_dir_all(&root).expect("create the root"); + let publisher = mindcore_runtime::journal_dir(&root); + + let escaped = dir.path().join("escaped.md"); + let absolute = publisher(&[json!({ + "path": escaped.to_str().expect("utf-8 scratch path"), + "content": "escape", + })]); + assert!(absolute.is_err(), "an absolute target is refused"); + assert!( + !escaped.exists(), + "nothing was written outside the root" + ); + + let parent = publisher(&[json!({ + "path": "../escaped.md", + "content": "escape", + })]); + assert!(parent.is_err(), "a parent traversal target is refused"); + assert!( + !dir.path().join("escaped.md").exists(), + "no traversal write landed" + ); + + // Confined targets still publish exactly as before. + publisher(&[json!({ "path": "records/rec_confined.md", "content": "confined bytes" })]) + .expect("a confined target publishes"); + assert_eq!( + std::fs::read_to_string(root.join("records").join("rec_confined.md")) + .expect("the confined target"), + "confined bytes" + ); +} + +/// The review's publication runs off the async worker: while the publisher is parked inside +/// its flush, unrelated executor work keeps progressing, and nothing commits before the +/// publication confirms — the records count is still zero until the review finishes. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn publication_blocks_no_executor_progress_and_commits_after_it_confirms() { + let (dir, store) = fixture().await; + let owner = CallerId::new(OWNER); + let created = ok(minds::create(&store, &request(OWNER)).await); + ensure_subject(&store, created.id.as_str()).await; + let journal_root = dir.path().to_path_buf(); + let handle = ok(Mind::open(&store, &owner, &created.id).await) + .with_journal_publisher(journal_dir(&journal_root)); + let candidate_id = capture_candidate(&handle, "cap-offworker", "a parked publication").await; + + // A publisher parked inside its flush: it enters, signals, and waits for the test to + // release it. A probe task signals progress while the review is parked; if the publication + // ran on the executor, the probe could never be polled and the probe signal would starve. + let (entered, is_entered) = mpsc::channel::<()>(); + let (release, is_released) = tokio::sync::oneshot::channel::<()>(); + let is_released = std::sync::Mutex::new(Some(is_released)); + let parked_root = journal_root.clone(); + let parked = ok(Mind::open(&store, &owner, &created.id).await) + .with_journal_publisher(move |targets| { + journal_dir(&parked_root)(targets)?; + entered.send(()).expect("signal the publisher entered"); + let receiver = is_released + .lock() + .expect("the release lock") + .take() + .expect("the publisher is entered once"); + receiver.blocking_recv().expect("wait for the test release"); + Ok(()) + }); + + let review = tokio::spawn(async move { + parked.review(&candidate_id, &promote(), "rev-offworker").await + }); + + // The probe task: progress measurable only on a free executor. + let (progressed, is_progressed) = tokio::sync::oneshot::channel::<()>(); + tokio::spawn(async move { + let _ = progressed.send(()); + }); + + is_entered.recv().expect("the publisher is parked inside its flush"); + let progress = tokio::time::timeout(std::time::Duration::from_secs(5), is_progressed).await; + assert!( + progress.is_ok(), + "executor progress continued while the publisher was parked" + ); + // Nothing commits before the publication confirms: a second pool on the same file reads + // the committed state — the staging transaction still holds the first pool's connection, + // and its uncommitted rows are invisible here. + let observer = MindStore::open(&dir.path().join("minds.db")) + .await + .expect("open the observer store"); + assert_eq!( + count_records(&observer.pool()).await, + 0, + "nothing commits before the publication confirms" + ); + + release.send(()).expect("release the publisher"); + let reviewed = review.await.expect("the review task joins"); + assert_eq!( + value_of(&ok(reviewed))["status"], + "committed", + "the review settles after the publication confirms" + ); +} + +/// `cognition_read` reads only the collection its admitted Mind resolved at open: a colliding +/// entry in another Mind's collection — same carrier entry id, poisoned content — never leaks +/// into the read, because the collection is the row's own, never a caller-supplied input. +#[tokio::test] +async fn cognition_read_reads_only_the_collection_of_the_admitted_mind() { + let (_dir, store) = fixture().await; + let owner = CallerId::new(OWNER); + let first = ok(minds::create(&store, &request(OWNER)).await); + let second = ok(minds::create(&store, &request(OWNER)).await); + assert_ne!( + first.knowledge.collection, second.knowledge.collection, + "each Mind owns its own collection" + ); + + // A poisoned record for the first Mind's carrier entry id, written into the second Mind's + // collection. The record validates: its holder is the second carrier it actually lives + // with, so the write passes the one validation boundary. + let second_handle = ok(Mind::open(&store, &owner, &second.id).await); + let second_carrier = ok(second_handle + .knowledge_get(second_handle.carrier_entry_id(), None) + .await); + let poisoned = json!({ + "kind": "belief", + "order": 1, + "record_id": "cog_poisoned", + "holder": { + "kind": "knowledge_entry", + "namespace": "mindcore", + "id": second.carrier_entry_id, + }, + "target": { + "carrier": { + "kind": "knowledge_entry", + "namespace": "mindcore", + "id": second.carrier_entry_id, + }, + "target_id": "prop_collision", + "kind": "proposition", + }, + "assessor": { + "kind": "principal", + "namespace": "mindcore", + "id": OWNER, + }, + "assessor_role": "holder_self_report", + "basis": { + "kind": "evidence", + "evidence": [{ "kind": "memory_record", "namespace": "mindcore", "id": "rec_collision" }], + }, + "assessment_context": { "context_id": second.id.as_str() }, + "assessed_at": "2026-11-20T09:00:00Z", + "effective_at": "2026-11-20T09:00:00Z", + "view": "current", + "q": { + "value": 0.9, + "assertion": "belief_attribution", + "method": "two_witness_reports", + "calibration": "uncalibrated", + }, + "extensions": {}, + }); + let appended = mindcore_base::cognition::append_cognition_record(&second_carrier, poisoned) + .expect("the poisoned record validates in its own carrier"); + let revision = second_carrier.revision.expect("a stored carrier has a revision"); + ok(second_handle.knowledge_put(appended, Some(revision)).await); + + // The first Mind's read is untouched by anything the second collection holds. + let first_handle = ok(Mind::open(&store, &owner, &first.id).await); + assert!( + ok(first_handle.cognition_read().await).is_none(), + "the first Mind still answers the fresh-Mind None" + ); + let cognition = ok(second_handle.cognition_read().await).expect("one judgment"); + assert_eq!( + cognition.records.len(), + 1, + "the second Mind reads its own collection's record" + ); + assert_eq!( + cognition.records[0]["record_id"], + json!("cog_poisoned"), + "the read is the admitted Mind's own carrier" + ); +} From ff1d4ee18ac6c9cb3077f6ffc6c64ff324e619ca Mon Sep 17 00:00:00 2001 From: Tang Bohao Date: Thu, 26 Nov 2026 10:31:55 +0800 Subject: [PATCH 12/22] =?UTF-8?q?fix(facade):=20close=20the=20second=20QC?= =?UTF-8?q?=20round=20=E2=80=94=20B2=20removal,=20B3=20symlink=20confineme?= =?UTF-8?q?nt,=20B4=20root-entry=20durability,=20B5=20cancellation=20owner?= =?UTF-8?q?ship,=20F-007=20fresh-review=20withhold?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit B2: the unused MemoryAdapter::read_cognition — the public read that admits one space and reads an independently supplied collection — is removed from mindcore-spoke; the facade's own bound implementation stands. B3: confinement is filesystem resolution, not spelling: the root and every target parent are canonicalized, and a parent resolving outside the canonical root through a symlink below it is refused before anything is created or written; regression plants a symlink escape and proves the external destination is never written. B4: the durability chain ends at the deepest pre-existing ancestor of the target's parent, inclusive — the entry that names a freshly created journal root is synced before Ok(()), so a settled record can never outlive its projection tree. B5: the staging transaction moves into the blocking publication task and returns with the result, so dropping the review future can never release the writer before the started publication ends; a same-key retry queues behind the first attempt's rollback. The progress regression is rebuilt honestly: one async worker, an asynchronously awaited entry signal, the probe spawned after entry and before release, and a pre-opened observer store. F-007: fresh work — a pending or absent candidate — reads through the adapter's get_candidate again, restoring the UNRECONCILED withhold for fresh reviews while a consumed candidate's replay still reaches the receipt probe; regression pins both. --- .agents/specs/architecture/facade.md | 47 +++-- crates/mindcore-runtime/src/journal.rs | 140 +++++++++---- crates/mindcore-runtime/src/mind.rs | 104 +++++++--- crates/mindcore-runtime/tests/mind.rs | 274 ++++++++++++++++++++++--- crates/mindcore-spoke/src/lib.rs | 63 +----- 5 files changed, 459 insertions(+), 169 deletions(-) diff --git a/.agents/specs/architecture/facade.md b/.agents/specs/architecture/facade.md index 4a7d81d..95bb8a4 100644 --- a/.agents/specs/architecture/facade.md +++ b/.agents/specs/architecture/facade.md @@ -47,20 +47,26 @@ the adapter's own code, and a revision below an entry's floor answers the store' ### The `review` fold `review` answers the settled receipt, not a stage. Inside one `BEGIN IMMEDIATE` it reads the -candidate's revision and status as metadata and stages the whole decision through -`review_candidate`. The metadata read is deliberately not a content read: the adapter's -`get_candidate` withholds subject content while any of the subject's intents is unsettled, -which is correct for content but unrelated to a receipt — a settled key's replay must reach -the adapter's probe no matter what else in the space is unsettled, whether another of the -same subject's intents or another subject's in the same space. Admission does not move: -`review_candidate` authorizes the write, probes the receipt first and applies every fresh-work -gate on its own, and a replay is digest-identical, so the metadata read only rebuilds the -original `expected_revision`. +candidate's consumption status as metadata and then distinguishes fresh work from a replay. +Fresh work — a pending or absent candidate — reads the candidate through the adapter's +`get_candidate`, whose withhold refuses while any intent of the candidate's subject is +unsettled, the refusal fresh reviews always answered. A consumed candidate can only be a +replay or a retry of a still-pending receipt, and a receipt is not subject content: the +withhold must not gate it, so its `expected_revision` is derived as metadata — exactly one +less than the consumed revision, because consumption is a candidate's only revision bump. +That is what lets a settled key's replay reach the adapter's probe no matter what else in the +space is unsettled, whether another of the same subject's intents or another subject's in the +same space. Admission does not move: `review_candidate` authorizes the write, probes the +receipt first and applies every fresh-work gate on its own, and a replay is digest-identical, +so either path only rebuilds the original `expected_revision`. The fold reads the staged intent on the same transaction and publishes the owed targets off the async worker — the publisher writes and fsyncs synchronously, so it runs on the blocking -pool while nothing commits and unrelated executor work stays schedulable — **before the -staging is durable**: a refused publication rolls everything back — no record row, no intent, +pool while nothing commits and unrelated executor work stays schedulable. The staging +transaction moves into the blocking task and comes back with the result, so a caller that +drops the review future can never release the writer before the started publication ends: a +same-key retry's transaction queues behind the first one's rollback, and two attempts never +publish side by side — **before the staging is durable**: a refused publication rolls everything back — no record row, no intent, a pending candidate — and the same idempotency key can be repeated, with the publisher's own `SpiError::Settlement` refusal traveling unchanged. Only after a successful publication does the staging commit; settlement then runs on a second transaction, and any failure from there @@ -77,13 +83,18 @@ surface deliberately: the served caller holds the receipt protocol that resolves leaves no record to resolve. The cost is an orphan published file when the process dies between publication and the staging commit. -`journal_dir(root)` confines every target to its root: a target path that is absolute or -carries `..` is refused before its first byte. Durability is anchored at `root`, which the -host establishes as durable; publication syncs the file and every directory of the publisher's -tree down to the target, never ancestors outside the root. Syncing a directory opens it for -reading, so the host must grant read on `root` and every directory below it — a write-only -journal root cannot be published, because the sync that must precede settlement would be -refused for a reason the write itself never hit. +`journal_dir(root)` confines every target to its canonical root: a target path that is +absolute or carries `..` is refused before its first byte, and what remains is canonicalized — +a parent whose resolution leaves the canonical root through a symlink below it is refused +before anything is created or written. Durability ends at the deepest pre-existing ancestor +of the target's parent, inclusive: everything below it was created by this publication and is +synced on every attempt, and when `root` itself is absent the entry that names the freshly +created root — in its existing parent — is persisted before `Ok(())`, so a settled record can +never outlive the projection tree that proves it. Syncing a directory opens it for reading, +so the host must grant read on the deepest pre-existing ancestor and everything below it; +ancestors above it need only traversal — a write-only journal root cannot be published, +because the sync that must precede settlement would be refused for a reason the write itself +never hit. ### `deliberate` without a subject diff --git a/crates/mindcore-runtime/src/journal.rs b/crates/mindcore-runtime/src/journal.rs index de75222..27f5f66 100644 --- a/crates/mindcore-runtime/src/journal.rs +++ b/crates/mindcore-runtime/src/journal.rs @@ -10,23 +10,26 @@ use serde_json::Value; /// target's `path`, parent directories are created, and `Ok(())` is returned only when every /// target's exact bytes are durable. /// -/// Confinement: a target path that is absolute or carries any `..` — a `ParentDir`, `RootDir` -/// or `Prefix` component — is refused before its first byte, so no target can ever write -/// outside `root` whatever a journaled row holds. +/// Confinement is filesystem resolution, not spelling. A target path that is absolute or +/// carries any `..` — a `ParentDir`, `RootDir` or `Prefix` component — is refused before its +/// first byte. What remains is resolved: the root and every target parent are canonicalized, +/// and a parent whose resolution leaves the canonical root — a symlink below the root +/// pointing outside it, at the destination or anywhere in between — is refused before +/// anything is created or written. The root the publisher serves is the canonical root: a +/// host that passes a symlinked `root` publishes inside what it resolves to. /// -/// The sync anchor is `root` itself. Publication creates no directory at or above it: the host -/// establishes `root` (or the path it will be created at) as already durable, so every entry -/// publication depends on lies within the publisher's own tree. Each target syncs its file, -/// then every directory of that tree its entry depends on, deepest first, ending at `root`. -/// The chain is a function of the target's path alone — never of which directories happen to -/// exist — so a retry after a publication that failed between creating directories and -/// syncing them syncs the same chain as the attempt that failed. +/// Durability: each target syncs its file, then every directory entry the target depends on, +/// deepest first, ending at the deepest pre-existing ancestor of its parent — inclusive. That +/// directory already exists, so its own creation entry is the host's; everything below it was +/// created by this publication (on this attempt or an earlier failed one) and is synced on +/// every attempt. When `root` itself is absent, `create_dir_all` creates it, and the chain +/// ends at its existing parent: the entry that names the freshly created root is persisted +/// before `Ok(())`, so a settled record can never outlive the projection tree that proves it. /// /// Permission requirement: syncing a directory opens it for reading, which POSIX refuses for -/// a search-only directory, so the host must grant read on `root` and every directory below -/// it. A write-only journal root cannot be published: the write itself would succeed, but the -/// durability sync that must precede settlement would be refused for a reason the write never -/// hit. +/// a search-only directory, so the host must grant read on the deepest pre-existing ancestor +/// and everything the publication creates below it. Ancestors above that anchor need only +/// traversal: the publisher never opens them. /// /// Target paths are the adapter's own (`records/.md`, `candidates/.md`, /// `profiles/.md`): they are confined to `root` as given rather than re-derived here. @@ -45,15 +48,12 @@ pub fn journal_dir( .ok_or_else(|| { SpiError::InvalidInput(format!("journal target {path} carries no content")) })?; - // Confinement is refused before the first byte of this target: an absolute path + // The spelling check is refused before any filesystem effect: an absolute path // or one carrying `..` would escape `root` under `join`, whatever it names. let confined = !Path::new(path).is_absolute() - && Path::new(path).components().all(|component| { - matches!( - component, - Component::Normal(_) | Component::CurDir - ) - }); + && Path::new(path) + .components() + .all(|component| matches!(component, Component::Normal(_) | Component::CurDir)); if !confined { return Err(SpiError::InvalidInput(format!( "journal target {path} is not confined to the journal root" @@ -61,26 +61,76 @@ pub fn journal_dir( } let file = root.join(path); let parent = match file.parent() { - Some(parent) if !parent.as_os_str().is_empty() => parent, + Some(parent) if !parent.as_os_str().is_empty() => parent.to_path_buf(), // A target at the publisher root has the root itself as its parent: the - // confinement check above has already erased any `.` components, so the - // empty parent is reached only when the target names one plain file. - _ => root.as_path(), + // spelling check above has already erased any `.` components, so the empty + // parent is reached only when the target names one plain file. + _ => root.clone(), }; - std::fs::create_dir_all(parent).map_err(|error| { + // The deepest pre-existing ancestor of the parent — the sync anchor. Existence + // is `symlink_metadata`: a dangling symlink is an existing entry, so it is never + // silently replaced by a created directory. + let anchor = deepest_existing_ancestor(&parent); + // Symlink escape, refused before anything is created — but only where a symlink + // can exist: inside the root. An anchor strictly within the root means the root + // itself exists, so both canonicalize; an anchor at or above the root means the + // root itself is missing, and a root that does not exist yet holds no symlinks to + // escape through — its containment is the post-creation check's job. + if anchor != root && anchor.starts_with(&root) { + let canonical_root = root.canonicalize().map_err(|error| { + SpiError::Settlement(spoke_reject(format!( + "the journal root {} could not be resolved: {error}", + root.display() + ))) + })?; + let resolved = anchor.canonicalize().map_err(|error| { + SpiError::Settlement(spoke_reject(format!( + "the directory {} could not be resolved: {error}", + anchor.display() + ))) + })?; + if !resolved.starts_with(&canonical_root) { + return Err(SpiError::InvalidInput(format!( + "journal target {path} resolves outside the journal root" + ))); + } + } + std::fs::create_dir_all(&parent).map_err(|error| { SpiError::Settlement(spoke_reject(format!( "the directory for {path} could not be created: {error}" ))) })?; + // Resolution after creation: every component of the parent now exists, so its + // canonical form must sit inside the canonical root — a symlink introduced at the + // destination or resolved differently by the creating platform is refused before + // the first byte is written. + let canonical_root = root.canonicalize().map_err(|error| { + SpiError::Settlement(spoke_reject(format!( + "the journal root {} could not be resolved: {error}", + root.display() + ))) + })?; + let resolved = parent.canonicalize().map_err(|error| { + SpiError::Settlement(spoke_reject(format!( + "the directory {} could not be resolved: {error}", + parent.display() + ))) + })?; + if !resolved.starts_with(&canonical_root) { + return Err(SpiError::InvalidInput(format!( + "journal target {path} resolves outside the journal root" + ))); + } std::fs::write(&file, content).map_err(|error| { SpiError::Settlement(spoke_reject(format!( "journal target {path} could not be written: {error}" ))) })?; // Durability, not visibility: the write must reach the medium before the caller - // may settle the intent. Sync the file's contents, then every directory of the - // publisher's own tree its entry depends on, deepest first, ending at `root` — - // the anchor the host established as durable. + // may settle the intent. Sync the file's contents, then every directory entry the + // target depends on, deepest first, ending at the deepest pre-existing ancestor — + // inclusive, because the entry that names what this publication created below it + // (the fresh journal root included) lives in that directory. std::fs::File::open(&file) .and_then(|file| file.sync_all()) .map_err(|error| { @@ -88,7 +138,7 @@ pub fn journal_dir( "journal target {path} could not be synced: {error}" ))) })?; - let mut cursor = Some(parent.to_path_buf()); + let mut cursor = Some(parent.clone()); while let Some(directory) = cursor { std::fs::File::open(&directory) .and_then(|directory| directory.sync_all()) @@ -98,14 +148,10 @@ pub fn journal_dir( directory.display() ))) })?; - if directory == root { + if directory == anchor { break; } - cursor = directory - .components() - .as_path() - .parent() - .map(Path::to_path_buf); + cursor = directory.parent().map(Path::to_path_buf); } let landed = std::fs::read_to_string(&file).map_err(|error| { SpiError::Settlement(spoke_reject(format!( @@ -122,6 +168,28 @@ pub fn journal_dir( } } +/// The deepest ancestor of `path` that exists on the filesystem — symlink entries included — +/// or the path itself when it already exists. +/// +/// This is the durability anchor of one publication: it existed before the attempt, so the +/// entry that names it is the host's, while every entry below it was created by this +/// publication (on this attempt or an earlier failed one) and must be synced on every +/// attempt — including the entry in this directory that names a freshly created root. +fn deepest_existing_ancestor(path: &Path) -> PathBuf { + let mut cursor = path.to_path_buf(); + loop { + if std::fs::symlink_metadata(&cursor).is_ok() { + return cursor; + } + match cursor.parent() { + Some(parent) if !parent.as_os_str().is_empty() => cursor = parent.to_path_buf(), + // The current directory for a relative path, the filesystem root for an absolute + // one: both always exist. + _ => return cursor, + } + } +} + /// The publisher's refusal: a retryable `INTERNAL_ERROR` — nothing the settlement leg staged /// is durable yet, so the same review can be repeated once the medium is writable. fn spoke_reject(message: String) -> spoke_operations::SpokeReject { diff --git a/crates/mindcore-runtime/src/mind.rs b/crates/mindcore-runtime/src/mind.rs index b82e2d3..b6d505a 100644 --- a/crates/mindcore-runtime/src/mind.rs +++ b/crates/mindcore-runtime/src/mind.rs @@ -444,16 +444,23 @@ impl Mind { } }; - // 1. Read the candidate's revision and consumption status as metadata. A content-read - // path like `get_candidate` is deliberately not used here: its withhold on the - // subject's unsettled intents is correct for subject content but unrelated to a - // receipt, and it would keep a settled key's replay from ever reaching the adapter's - // probe while any other intent of the subject is unsettled. Admission itself does - // not move: `review_candidate` authorizes the write, probes the receipt first and - // applies every fresh-work gate on its own. A same-key replay is digest-identical, - // so this row only rebuilds the original `expected_revision` — a wrong value can - // never reach a receipt. - let observed: Option<(i64, String)> = match sqlx::query_as( + // 1. Read the candidate's consumption status and revision as metadata. The answer + // decides how the revision is established: + // - A pending (or absent) candidate is fresh work: the facade reads it through the + // adapter's `get_candidate`, whose withhold refuses while any intent of the + // candidate's subject is unsettled — the refusal fresh reviews answered before + // this facade ever probed receipts. + // - A consumed candidate can only be a replay (settled receipt) or a retry of a + // still-pending receipt, and a receipt is not subject content: the content + // withhold must not gate it, so the revision is derived as metadata — exactly one + // less than the consumed revision, because consumption is a candidate's only + // revision bump and that is the only revision any recorded review payload for + // this candidate can carry. + // Admission itself does not move: `review_candidate` authorizes the write, probes + // the receipt first and applies every fresh-work gate on its own. A same-key replay + // is digest-identical, so either path can only rebuild the original + // `expected_revision` — a wrong value can never reach a receipt. + let status: Option<(i64, String)> = match sqlx::query_as( "SELECT revision, status FROM memory_candidates WHERE space_id = ? AND candidate_id = ?", ) .bind(space.as_str()) @@ -461,18 +468,59 @@ impl Mind { .fetch_optional(&mut *transaction) .await { - Ok(observed) => observed, + Ok(status) => status, Err(error) => { drop(transaction); return retryable_internal(format!("the candidate row could not be read: {error}")); } }; - let (revision, consumed) = match observed { - Some((revision, status)) => (u64::try_from(revision).unwrap_or(0), status == "consumed"), - // No row: stage at revision 1, the candidate's fresh-work value. `review_candidate` - // answers its own `NotFound` for a candidate that never existed; a replayed key of - // a consumed or pruned candidate is digest-guarded before this value can matter. - None => (1, false), + let consumed = matches!(status, Some((_, ref status)) if status == "consumed"); + let observed_revision = if consumed { + status.map(|(revision, _)| u64::try_from(revision).unwrap_or(0)) + } else { + // Fresh work: the adapter's own content read, withhold included. A refusal is the + // adapter's own and rolls the transaction back. + let observed = self + .adapter + .get_candidate( + &mut transaction, + &caller, + json!({ "space_id": space.as_str(), "candidate_id": candidate_id }), + ) + .await; + match observed { + SpokeResult::Ok(MemoryStage::Ready(body)) => { + let revision = body + .get("candidate") + .and_then(|candidate| candidate.get("revision")) + .and_then(Value::as_u64); + match revision { + Some(revision) => Some(revision), + None => { + drop(transaction); + return retryable_internal( + "the candidate body carries no integer revision", + ); + } + } + } + SpokeResult::Ok(stage) => { + drop(transaction); + return retryable_internal(format!( + "candidate read answered an unexpected stage: {stage:?}" + )); + } + SpokeResult::Reject(reject) => { + drop(transaction); + return SpokeResult::Reject(reject); + } + } + }; + let revision = match observed_revision { + Some(revision) => revision, + // No row at all: stage at revision 1, the candidate's fresh-work value — + // `review_candidate` answers its own `NotFound` for a candidate that never existed. + None => 1, }; // 2. Stage on the same transaction. The adapter's dedup probe keys on // (space, requester, operation, idempotency_key) and digests the whole payload, so @@ -553,23 +601,27 @@ impl Mind { // 4. Publish before the staging is durable, off the async worker: the publisher writes // and fsyncs synchronously, so it runs on the blocking pool while the handle's task // awaits it — unrelated executor work stays schedulable for the whole flush. The - // ordering is unchanged: nothing commits before the publisher has confirmed, and a - // refusal rolls the transaction back — no record row, no intent and a pending - // candidate are left, with the publisher's own `SpiError::Settlement` refusal - // traveling unchanged. The task is awaited to completion, so it always retains - // ownership of the publication, caller cancellation included. + // transaction itself moves into the blocking task and comes back with the result, + // so a caller that drops the review future can never release the writer before the + // started publication ends: a same-key retry's own transaction waits for the first + // one's rollback, and the two attempts can never publish side by side. Nothing + // commits before the publisher has confirmed, a refusal rolls everything back, and + // the publisher's own `SpiError::Settlement` refusal travels unchanged. let publish_targets = intent.targets.clone(); let publish = { let publisher = Arc::clone(publisher); - tokio::task::spawn_blocking(move || publisher(&publish_targets)) + tokio::task::spawn_blocking(move || { + let result = publisher(&publish_targets); + (result, transaction) + }) }; - let published = match publish.await { - Ok(result) => result, + let (published, back) = match publish.await { + Ok(pair) => pair, Err(error) => { - drop(transaction); return retryable_internal(format!("the publication task failed to join: {error}")); } }; + let transaction = back; if let Err(error) = published { drop(transaction); return match error { diff --git a/crates/mindcore-runtime/tests/mind.rs b/crates/mindcore-runtime/tests/mind.rs index 3c14641..71dbd5a 100644 --- a/crates/mindcore-runtime/tests/mind.rs +++ b/crates/mindcore-runtime/tests/mind.rs @@ -1387,6 +1387,58 @@ async fn a_settled_replay_survives_any_unsettled_intent_in_the_space() { assert_eq!(count_records(&store.pool()).await, 1, "still no second record"); } +/// Only the replay bypasses the unsettled-intent withhold: a fresh review — a new key over a +/// candidate of a subject whose intent is unsettled — is refused with the adapter's own +/// UNRECONCILED answer, exactly as before the facade ever probed receipts. +#[tokio::test] +async fn a_fresh_review_is_refused_while_the_subjects_intent_is_unsettled() { + let (dir, store) = fixture().await; + let owner = CallerId::new(OWNER); + let created = ok(minds::create(&store, &request(OWNER)).await); + ensure_subject(&store, created.id.as_str()).await; + let handle = ok(Mind::open(&store, &owner, &created.id).await) + .with_journal_publisher(journal_dir(dir.path())); + let candidate_id = capture_candidate(&handle, "cap-fresh-withhold", "a fresh note").await; + + settle_never(&store, created.id.as_str(), SUBJECT).await; + let reject = reject_of( + handle + .review(&candidate_id, &promote(), "rev-fresh-withhold") + .await, + ); + assert_eq!( + reject.code, + SpokeRejectCode::InternalError, + "the withhold travels as the adapter's own refusal" + ); + assert_eq!( + reject.details.as_ref().and_then(|details| details.get("reason")), + Some(&json!("UNRECONCILED")), + "a fresh review is withheld while the subject's intent is unsettled: {reject:?}" + ); + assert_eq!(count_records(&store.pool()).await, 0, "nothing is staged"); + assert_eq!( + count_intents(&store.pool()).await, + 1, + "only the pre-existing intent stands" + ); + + // Once the intent settles, the same review proceeds — the withhold is live state, not a + // dead candidate. + sqlx::query("UPDATE memory_journal SET state = 'applied'") + .execute(&store.pool()) + .await + .expect("settle the outstanding intent"); + let reviewed = ok(handle + .review(&candidate_id, &promote(), "rev-fresh-withhold") + .await); + assert_eq!( + value_of(&reviewed)["status"], + "committed", + "the fresh review settles after the intent does" + ); +} + /// The publisher confines every target to its root: an absolute target path or one carrying /// `..` is refused with nothing written outside the root. #[tokio::test] @@ -1427,10 +1479,13 @@ async fn the_public_publisher_refuses_a_target_outside_its_root() { ); } -/// The review's publication runs off the async worker: while the publisher is parked inside -/// its flush, unrelated executor work keeps progressing, and nothing commits before the -/// publication confirms — the records count is still zero until the review finishes. -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +/// The review's publication runs off the async worker. One worker thread drives the whole +/// test: the publisher parks inside its flush on a rendezvous, and a probe task spawned after +/// entry — before release — completes within the timeout only because the single worker is +/// free to poll it. Publication inlined on the worker would park the worker itself, the probe +/// would starve, and the timeout would fire: the regression fails, never hangs, because the +/// probe's wait is the bounded one. +#[tokio::test(flavor = "multi_thread", worker_threads = 1)] async fn publication_blocks_no_executor_progress_and_commits_after_it_confirms() { let (dir, store) = fixture().await; let owner = CallerId::new(OWNER); @@ -1441,23 +1496,33 @@ async fn publication_blocks_no_executor_progress_and_commits_after_it_confirms() .with_journal_publisher(journal_dir(&journal_root)); let candidate_id = capture_candidate(&handle, "cap-offworker", "a parked publication").await; - // A publisher parked inside its flush: it enters, signals, and waits for the test to - // release it. A probe task signals progress while the review is parked; if the publication - // ran on the executor, the probe could never be polled and the probe signal would starve. - let (entered, is_entered) = mpsc::channel::<()>(); - let (release, is_released) = tokio::sync::oneshot::channel::<()>(); - let is_released = std::sync::Mutex::new(Some(is_released)); + // The observer is opened before the review starts, so nothing migrates or acquires the + // write while the staging transaction holds it. + let observer = MindStore::open(&dir.path().join("minds.db")) + .await + .expect("open the observer store"); + + // A publisher parked inside its flush on a condvar rendezvous. + let entered = Arc::new((std::sync::Mutex::new(false), std::sync::Condvar::new())); + let released = Arc::new((std::sync::Mutex::new(false), std::sync::Condvar::new())); let parked_root = journal_root.clone(); + let entered_pub = entered.clone(); + let released_pub = released.clone(); let parked = ok(Mind::open(&store, &owner, &created.id).await) .with_journal_publisher(move |targets| { journal_dir(&parked_root)(targets)?; - entered.send(()).expect("signal the publisher entered"); - let receiver = is_released - .lock() - .expect("the release lock") - .take() - .expect("the publisher is entered once"); - receiver.blocking_recv().expect("wait for the test release"); + { + let (lock, cvar) = &*entered_pub; + let mut flag = lock.lock().expect("the entry lock"); + *flag = true; + cvar.notify_all(); + drop(flag); + } + let (lock, cvar) = &*released_pub; + let mut flag = lock.lock().expect("the release lock"); + while !*flag { + flag = cvar.wait(flag).expect("wait for the test release"); + } Ok(()) }); @@ -1465,31 +1530,42 @@ async fn publication_blocks_no_executor_progress_and_commits_after_it_confirms() parked.review(&candidate_id, &promote(), "rev-offworker").await }); - // The probe task: progress measurable only on a free executor. + // Wait for entry asynchronously — the probe starts only after the publisher is parked. + let entered_wait = entered.clone(); + tokio::task::spawn_blocking(move || { + let (lock, cvar) = &*entered_wait; + let mut flag = lock.lock().expect("the entry lock"); + while !*flag { + flag = cvar.wait(flag).expect("wait for publisher entry"); + } + }) + .await + .expect("the publisher is parked inside its flush"); + + // The probe: progress measurable only on a free single worker. let (progressed, is_progressed) = tokio::sync::oneshot::channel::<()>(); tokio::spawn(async move { let _ = progressed.send(()); }); - - is_entered.recv().expect("the publisher is parked inside its flush"); let progress = tokio::time::timeout(std::time::Duration::from_secs(5), is_progressed).await; assert!( progress.is_ok(), "executor progress continued while the publisher was parked" ); - // Nothing commits before the publication confirms: a second pool on the same file reads - // the committed state — the staging transaction still holds the first pool's connection, - // and its uncommitted rows are invisible here. - let observer = MindStore::open(&dir.path().join("minds.db")) - .await - .expect("open the observer store"); + // Nothing commits before the publication confirms: the pre-opened observer reads the + // committed state, and the staging transaction's uncommitted rows are invisible to it. assert_eq!( count_records(&observer.pool()).await, 0, "nothing commits before the publication confirms" ); - release.send(()).expect("release the publisher"); + { + let (lock, cvar) = &*released; + let mut flag = lock.lock().expect("the release lock"); + *flag = true; + cvar.notify_all(); + } let reviewed = review.await.expect("the review task joins"); assert_eq!( value_of(&ok(reviewed))["status"], @@ -1498,6 +1574,110 @@ async fn publication_blocks_no_executor_progress_and_commits_after_it_confirms() ); } +/// Cancellation keeps transaction ownership until the started publication ends: the review +/// future is dropped while the publisher is parked, yet the first attempt's transaction stays +/// alive until the flush finishes, so a same-key retry can only stage after the first +/// attempt's rollback — the two never publish side by side, and the retry settles. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn a_cancelled_review_keeps_the_transaction_until_the_publication_ends() { + let (dir, store) = fixture().await; + let owner = CallerId::new(OWNER); + let created = ok(minds::create(&store, &request(OWNER)).await); + ensure_subject(&store, created.id.as_str()).await; + let journal_root = dir.path().to_path_buf(); + let handle = ok(Mind::open(&store, &owner, &created.id).await) + .with_journal_publisher(journal_dir(&journal_root)); + let candidate_id = capture_candidate(&handle, "cap-cancelled", "a cancelled review").await; + + let entered = Arc::new((std::sync::Mutex::new(false), std::sync::Condvar::new())); + let released = Arc::new((std::sync::Mutex::new(false), std::sync::Condvar::new())); + let finished = Arc::new((std::sync::Mutex::new(false), std::sync::Condvar::new())); + let parked_root = journal_root.clone(); + let entered_pub = entered.clone(); + let released_pub = released.clone(); + let finished_pub = finished.clone(); + let parked = ok(Mind::open(&store, &owner, &created.id).await) + .with_journal_publisher(move |targets| { + journal_dir(&parked_root)(targets)?; + { + let (lock, cvar) = &*entered_pub; + let mut flag = lock.lock().expect("the entry lock"); + *flag = true; + cvar.notify_all(); + drop(flag); + } + { + let (lock, cvar) = &*released_pub; + let mut flag = lock.lock().expect("the release lock"); + while !*flag { + flag = cvar.wait(flag).expect("wait for the test release"); + } + } + { + let (lock, cvar) = &*finished_pub; + let mut flag = lock.lock().expect("the finish lock"); + *flag = true; + cvar.notify_all(); + } + Ok(()) + }); + + // The retry handle is opened before the review starts: the store's pool has one + // connection, and once the staging transaction holds it nothing — not even a registry read + // — can acquire another until the transaction ends. That is the serialization the test + // relies on, and pre-opening is what keeps the test itself out of that queue. + let working = ok(Mind::open(&store, &owner, &created.id).await) + .with_journal_publisher(journal_dir(&journal_root)); + let cancelled_id = candidate_id.clone(); + let review = tokio::spawn(async move { + parked.review(&cancelled_id, &promote(), "rev-cancelled").await + }); + + // Park the publisher, then drop the review future: the cancellation. + let entered_wait = entered.clone(); + tokio::task::spawn_blocking(move || { + let (lock, cvar) = &*entered_wait; + let mut flag = lock.lock().expect("the entry lock"); + while !*flag { + flag = cvar.wait(flag).expect("wait for publisher entry"); + } + }) + .await + .expect("the publisher is parked inside its flush"); + review.abort(); + + // A same-key retry now: its staging transaction cannot acquire until the cancelled + // attempt's transaction rolls back — and that rollback cannot happen before the parked + // publication ends. Release the parked publisher, then the retry settles the key. The + // ownership invariant is what makes this wait exist at all: if the cancelled attempt + // released its transaction while parked, the retry's staging and publication would race + // the first publish instead of queueing behind its rollback. + { + let (lock, cvar) = &*released; + let mut flag = lock.lock().expect("the release lock"); + *flag = true; + cvar.notify_all(); + } + let reviewed = ok(working + .review(&candidate_id, &promote(), "rev-cancelled") + .await); + assert_eq!( + value_of(&reviewed)["status"], + "committed", + "the same-key retry settles after the cancelled attempt finished" + ); + assert_eq!( + count_records(&store.pool()).await, + 1, + "exactly one record across both attempts" + ); + assert_eq!( + count_intents(&store.pool()).await, + 1, + "exactly one intent across both attempts" + ); +} + /// `cognition_read` reads only the collection its admitted Mind resolved at open: a colliding /// entry in another Mind's collection — same carrier entry id, poisoned content — never leaks /// into the read, because the collection is the row's own, never a caller-supplied input. @@ -1582,3 +1762,43 @@ async fn cognition_read_reads_only_the_collection_of_the_admitted_mind() { "the read is the admitted Mind's own carrier" ); } + +/// The publisher's confinement is filesystem resolution: a target whose parent resolves +/// through a symlink inside the root to a destination outside it is refused, and the external +/// destination is never written. +#[tokio::test] +async fn the_public_publisher_refuses_a_target_that_resolves_outside_its_root() { + let dir = TempDir::new().expect("temporary directory"); + let root = dir.path().join("journal"); + std::fs::create_dir_all(&root).expect("create the root"); + let outside = dir.path().join("outside"); + std::fs::create_dir_all(&outside).expect("create the escape destination"); + std::os::unix::fs::symlink(&outside, root.join("records")).expect("plant the symlink"); + + let publisher = mindcore_runtime::journal_dir(&root); + let escaped = publisher(&[json!({ + "path": "records/rec_symlink.md", + "content": "escape through the link", + })]); + assert!( + escaped.is_err(), + "a target resolving outside the root is refused" + ); + assert!( + !outside.join("rec_symlink.md").exists(), + "nothing was written at the external destination" + ); + + // A symlink at the destination itself — the file the write would follow — is refused the + // same way: the parent chain stays inside the root, and the confined target lands. + publisher(&[json!({ + "path": "profiles/rec_confined.md", + "content": "confined bytes", + })]) + .expect("a genuinely confined target still publishes"); + assert_eq!( + std::fs::read_to_string(root.join("profiles").join("rec_confined.md")) + .expect("the confined target"), + "confined bytes" + ); +} diff --git a/crates/mindcore-spoke/src/lib.rs b/crates/mindcore-spoke/src/lib.rs index 1cbb85b..9464088 100644 --- a/crates/mindcore-spoke/src/lib.rs +++ b/crates/mindcore-spoke/src/lib.rs @@ -37,7 +37,7 @@ use sqlx::{Sqlite, Transaction}; use mindcore_base::ids::{SpaceId, SubjectId}; use mindcore_spi::SpiError; use mindcore_base::ir::{MemoryRepository, ReceiptFailure, ReceiptState, ReviewReceiptIr}; -use mindcore_sqlite::{read_entry, SqliteMemoryRepository}; +use mindcore_sqlite::SqliteMemoryRepository; use crate::admission::Op; use crate::reject::{AResult, Reject}; @@ -280,67 +280,6 @@ impl MemoryAdapter { .await } - /// Read the carrier entry of `carrier_entry_id` in `collection` on `tx` and - /// derive the Mind's judgment from it — the space-wide `knowledge_read` - /// grant admitted first. A carrier that holds no current-view record yet - /// answers `None`: a Mind without a judgment is a state, not an error. Any - /// other derivation refusal means a stored carrier the projection cannot - /// read, answered as the caller-side internal failure it is. - pub async fn read_cognition( - &self, - tx: &mut Tx<'_>, - principal: &Principal, - space_id: &str, - collection: &str, - carrier_entry_id: &str, - mind_state_id: &str, - ) -> Result, SpiError> { - self.require_space_grants(tx, principal, space_id, &[KNOWLEDGE_READ]) - .await?; - let carrier = match read_entry(tx, collection, carrier_entry_id).await { - SpokeResult::Ok(carrier) => carrier, - SpokeResult::Reject(reject) => return Err(SpiError::Settlement(reject)), - }; - let revision = carrier.revision.ok_or_else(|| { - SpiError::Settlement( - Reject::terminal( - SpokeRejectCode::InternalError, - format!("carrier {carrier_entry_id} holds no assigned revision"), - ) - .into_spoke(), - ) - })?; - let view = match mindcore_base::cognition::derive_mind_state(&carrier) { - Ok(view) => view, - Err(mindcore_base::cognition::MindError::NoRecords) => return Ok(None), - Err(error) => { - return Err(SpiError::Settlement( - Reject::terminal( - SpokeRejectCode::InternalError, - format!("carrier {carrier_entry_id} cannot be derived: {error}"), - ) - .into_spoke(), - )); - } - }; - let records = mindcore_base::cognition::carrier_records(&carrier); - let mind_state = mindcore_base::cognition::mind_state_value(&view, mind_state_id) - .map_err(|error| { - SpiError::Settlement( - Reject::terminal( - SpokeRejectCode::InternalError, - format!("the mind state of {carrier_entry_id} cannot be projected: {error}"), - ) - .into_spoke(), - ) - })?; - Ok(Some(Cognition { - carrier_revision: revision, - records, - mind_state, - })) - } - /// `principal`'s own live grant for every one of `capabilities` in `space_id`, on `tx`. /// /// Live grants are re-derived on every call, so a read after provider work runs the same From 0aecea3d3fd031cd88be1c85d9048a04d79e2a37 Mon Sep 17 00:00:00 2001 From: Tang Bohao Date: Thu, 26 Nov 2026 10:35:25 +0800 Subject: [PATCH 13/22] fix(facade): the OUTCOME_UNCERTAIN repeat continues the fold to settlement MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit F-002 (qc2): a same-key repeat that meets its own still-pending receipt no longer stops at the probe's uncertain answer — it resolves the key to the receipt, republishes the intent's targets and runs the settlement leg, so the repeat actually settles. OUTCOME_UNCERTAIN remains the answer when settlement itself fails. Regression: settle refused through the interference handshake, intent restored to pending, the same-key review settles it with exactly one record and one intent, and a further repeat is the ordinary committed replay. facade.md's recovery contract now describes this continuation. F-005 (qc2): the stray repeated fragment of the host-provisioning entry after the reflections paragraph is deleted. --- .agents/specs/architecture/facade.md | 10 ++-- crates/mindcore-runtime/src/mind.rs | 66 +++++++++++++++++++++++---- crates/mindcore-runtime/tests/mind.rs | 65 +++++++++++++++----------- 3 files changed, 99 insertions(+), 42 deletions(-) diff --git a/.agents/specs/architecture/facade.md b/.agents/specs/architecture/facade.md index 95bb8a4..c8390c0 100644 --- a/.agents/specs/architecture/facade.md +++ b/.agents/specs/architecture/facade.md @@ -74,10 +74,11 @@ answers `OUTCOME_UNCERTAIN` because durable work may be outstanding. A receipt a is replayed as it is. The `OUTCOME_UNCERTAIN` recovery contract: the caller repeats the review with the same -candidate, decision and idempotency key. While the receipt is still pending, the repeat -answers `OUTCOME_UNCERTAIN` again — the probe reports the pending receipt exactly as the fold -left it, with no second record and no second intent. When the receipt has committed, the same -repeat answers the settled receipt as any replay does. The ordering differs from the served +candidate, decision and idempotency key. When the probe meets the key's receipt still +pending, the repeat does not stop at the uncertain answer — it continues the fold: publishes +the intent's targets and runs the settlement leg, so a repeat actually settles the receipt +and answers it committed. `OUTCOME_UNCERTAIN` remains the answer for a settlement that fails +again, and a receipt already committed replays as the settled answer. The ordering differs from the served surface deliberately: the served caller holds the receipt protocol that resolves `OUTCOME_UNCERTAIN` over a staged record; the facade's caller does not, so a failed publication leaves no record to resolve. The cost is an orphan published file when the process dies @@ -148,7 +149,6 @@ The boundary the facade composes is the store's own — `read_entry`, `write_ent `reflections: false` and offers no switch: the reflection surface (§7.25–§7.27 of the SPOKE spec) is a provider-level capability the facade's convenience contract does not expose, and a host that needs it embeds the adapter or the served surface directly. - journal publisher and the model providers are the embedding host's, as on the served surface. ## Invariants diff --git a/crates/mindcore-runtime/src/mind.rs b/crates/mindcore-runtime/src/mind.rs index b6d505a..b7b9c83 100644 --- a/crates/mindcore-runtime/src/mind.rs +++ b/crates/mindcore-runtime/src/mind.rs @@ -22,7 +22,7 @@ use serde_json::{json, Map, Value}; use mindcore_base::boundary::CallerId; use mindcore_base::ids::{MindId, SpaceId}; -use mindcore_base::ir::MemoryRepository; +use mindcore_base::ir::{MemoryRepository, ReceiptKey, ReceiptRead}; use mindcore_spi::{ DeliberateOutcome, DeliberateRequest, MindWorkflows, SpiError, SpiMindWorkflows, }; @@ -557,8 +557,19 @@ impl Mind { }), ) .await; - let receipt_id = match stage { - SpokeResult::Ok(MemoryStage::JournalPending { receipt_id, .. }) => receipt_id, + enum Staging { + // The fold staged a fresh decision on this transaction: it owns the staging and + // must commit it after publication. + Fresh { receipt_id: String }, + // A repeat met its own still-pending receipt: the staging is already durable, the + // transaction is read-only for what follows, and the fold continues to publication + // and settlement rather than answering the uncertain outcome again. + PendingRetry { receipt_id: String }, + } + let staging = match stage { + SpokeResult::Ok(MemoryStage::JournalPending { receipt_id, .. }) => { + Staging::Fresh { receipt_id } + } SpokeResult::Ok(MemoryStage::Ready(body)) => { drop(transaction); return match serde_json::from_value(body) { @@ -574,11 +585,40 @@ impl Mind { "review answered an unexpected stage: {stage:?}" )); } + SpokeResult::Reject(reject) if reject.code == SpokeRejectCode::OutcomeUncertain => { + // The only uncertain answer `review_candidate` can give is its own replay + // probe finding this key's receipt still pending. That is the recovery path: + // resolve the key to the receipt and continue the fold — publish, then + // settle — instead of answering the uncertain outcome forever. + let key = ReceiptKey { + space: space.clone(), + requester: mindcore_base::boundary::CallerId::new(self.caller.as_str()), + operation: "memory.candidates.review".to_string(), + idempotency_key: idempotency_key.to_string(), + }; + let receipt = match SqliteMemoryRepository + .review_receipt(&mut transaction, &key) + .await + { + Ok(Some(ReceiptRead::Retained(receipt))) => receipt, + _other => { + drop(transaction); + return SpokeResult::Reject(reject); + } + }; + Staging::PendingRetry { + receipt_id: receipt.receipt_id.clone(), + } + } SpokeResult::Reject(reject) => { drop(transaction); return SpokeResult::Reject(reject); } }; + let (receipt_id, fresh) = match staging { + Staging::Fresh { receipt_id } => (receipt_id, true), + Staging::PendingRetry { receipt_id } => (receipt_id, false), + }; // 3. Read the staged intent on the same transaction for the targets it owes. let intent = match SqliteMemoryRepository @@ -630,13 +670,19 @@ impl Mind { }; } - // 5. Commit the staging, then settle the receipt on a second immediate-write - // transaction. A failure from here leaves a pending intent and answers - // `OUTCOME_UNCERTAIN`, as the served surface does. - if let Err(error) = transaction.commit().await { - return uncertain(format!( - "review staging for receipt {receipt_id} committed an unknown outcome: {error}" - )); + // 5. Commit the staging — a fresh fold's own; a pending retry's is already durable, so + // its transaction is only dropped — then settle the receipt on a second + // immediate-write transaction. A failure from here leaves a pending intent and answers + // `OUTCOME_UNCERTAIN`, as the served surface does, and a same-key repeat resumes at + // this settlement leg rather than re-staging. + if fresh { + if let Err(error) = transaction.commit().await { + return uncertain(format!( + "review staging for receipt {receipt_id} committed an unknown outcome: {error}" + )); + } + } else { + drop(transaction); } let mut settlement = match self.pool.begin_with("BEGIN IMMEDIATE").await { Ok(transaction) => transaction, diff --git a/crates/mindcore-runtime/tests/mind.rs b/crates/mindcore-runtime/tests/mind.rs index 71dbd5a..f1b9c22 100644 --- a/crates/mindcore-runtime/tests/mind.rs +++ b/crates/mindcore-runtime/tests/mind.rs @@ -501,13 +501,13 @@ async fn a_refused_settle_answers_outcome_uncertain_and_leaves_the_intent_pendin } -/// The `OUTCOME_UNCERTAIN` recovery contract: repeating the review with the same key while the -/// receipt is still pending answers the same uncertain outcome again — the recorded refusal, -/// never a staged duplicate and never silence. The repeat is byte-identical, so it reaches the -/// adapter's receipt probe directly, and the probe reports the still-pending receipt exactly as -/// the fold left it: no second record, no second intent, the candidate still consumed. +/// The `OUTCOME_UNCERTAIN` recovery contract: a failure after the staging commit answers the +/// uncertain outcome once, and a same-key repeat continues through the fold — publish, then +/// settle — instead of answering the uncertain outcome again. The repeat settles the intent, +/// the record stays exactly the one the first attempt staged, and the receipt answers +/// committed. #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn a_repeat_after_outcome_uncertain_replays_the_pending_receipt_as_uncertain() { +async fn a_repeat_after_outcome_uncertain_continues_the_fold_and_settles() { let (dir, store) = fixture().await; let owner = CallerId::new(OWNER); let created = ok(minds::create(&store, &request(OWNER)).await); @@ -518,14 +518,14 @@ async fn a_repeat_after_outcome_uncertain_replays_the_pending_receipt_as_uncerta .with_journal_publisher(journal_dir(&journal_root)); let candidate_id = capture_candidate( &handle, - "cap-uncertain-replay", - "a note whose settlement outcome is unknown", + "cap-uncertain-recovery", + "a note whose first settlement fails", ) .await; - // The same interference handshake as `a_refused_settle_answers_outcome_uncertain`: the - // staging commit releases the one connection, and the registered task moves the intent out - // of pending before the settlement transaction can acquire it, so the settle is refused. + // The interference handshake: a task registered on the one-connection pool moves the + // intent out of pending the moment the staging commit releases the connection, so the + // first settle is refused — the `OUTCOME_UNCERTAIN` path. let interference_pool = pool.clone(); let blocking = ok(Mind::open(&store, &owner, &created.id).await).with_journal_publisher(move |targets| { @@ -556,7 +556,7 @@ async fn a_repeat_after_outcome_uncertain_replays_the_pending_receipt_as_uncerta let first = reject_of( blocking - .review(&candidate_id, &promote(), "rev-uncertain-replay") + .review(&candidate_id, &promote(), "rev-uncertain-recovery") .await, ); assert_eq!( @@ -565,30 +565,41 @@ async fn a_repeat_after_outcome_uncertain_replays_the_pending_receipt_as_uncerta "the refused settle answers OUTCOME_UNCERTAIN" ); - // The repeat: same candidate, decision and key, through a working publisher. The receipt - // is still pending, so the probe answers the uncertain outcome again without re-staging. + // Restore the intent to pending — the crash window the contract covers is exactly this + // state: staging durable, intent unsettled — and repeat the review with the same key. + sqlx::query("UPDATE memory_journal SET state = 'pending'") + .execute(&store.pool()) + .await + .expect("restore the intent to pending"); let working = ok(Mind::open(&store, &owner, &created.id).await) .with_journal_publisher(journal_dir(dir.path())); - let repeat = reject_of( - working - .review(&candidate_id, &promote(), "rev-uncertain-replay") - .await, - ); + let recovered = ok(working + .review(&candidate_id, &promote(), "rev-uncertain-recovery") + .await); assert_eq!( - repeat.code, - SpokeRejectCode::OutcomeUncertain, - "a same-key repeat while the receipt is pending answers OUTCOME_UNCERTAIN: {repeat:?}" + value_of(&recovered)["status"], + "committed", + "the same-key repeat continues the fold and settles" ); - assert_eq!(retry_class(&repeat), "uncertain"); assert_eq!( count_records(&pool).await, 1, - "the repeat stages no second record" + "the record is exactly the one the first attempt staged" ); assert_eq!( - count_intents(&pool).await, - 1, - "the repeat stages no second intent" + intent_states(&pool).await, + vec!["applied".to_string()], + "the intent is settled, never re-staged" + ); + + // A further repeat is the ordinary replay of a settled receipt. + let replayed = ok(working + .review(&candidate_id, &promote(), "rev-uncertain-recovery") + .await); + assert_eq!( + value_of(&replayed), + value_of(&recovered), + "a settled key replays the committed receipt" ); } From a2c0134d07a1a1fc5272b24bfabde38fe4506151 Mon Sep 17 00:00:00 2001 From: Tang Bohao Date: Thu, 26 Nov 2026 10:40:48 +0800 Subject: [PATCH 14/22] fix(facade): host-owned journal root, target-symlink refusal, honest B5 regressions MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit B4: the publisher requires its root to exist — durable — before the first publication and never creates it: the entry that names the root lives in its parent and is the host's to persist. A missing root is refused with the requirement named. The sync chain ends at the root itself, inclusive, a pure function of the target's path, so a retry is never weaker than the failed attempt. The example creates its journal root; the missing-root tests now assert the refusal and a separate test covers a nested subtree under an existing root; facade.md states the contract. B3 (target symlink): a symlink — or any non-file entry — at the target file itself is refused before the first byte, closing the last path the write could follow outside the root; regression plants the target symlink and proves nothing lands outside. B5 evidence: the single-worker progress case waits for publisher entry under a hard timeout that fails naming the missing progress instead of parking forever; the cancel case now spawns the retry while the first publication is still parked, yields it every chance to race, and asserts the retry never enters its publication while the cancelled attempt's flush is live — only after release does the retry settle the key. --- .agents/specs/architecture/facade.md | 22 ++- .../mindcore-runtime/examples/mind_facade.rs | 4 +- crates/mindcore-runtime/src/journal.rs | 59 ++++-- crates/mindcore-runtime/tests/mind.rs | 171 ++++++++++++------ 4 files changed, 168 insertions(+), 88 deletions(-) diff --git a/.agents/specs/architecture/facade.md b/.agents/specs/architecture/facade.md index c8390c0..46ed8ab 100644 --- a/.agents/specs/architecture/facade.md +++ b/.agents/specs/architecture/facade.md @@ -84,16 +84,18 @@ surface deliberately: the served caller holds the receipt protocol that resolves leaves no record to resolve. The cost is an orphan published file when the process dies between publication and the staging commit. -`journal_dir(root)` confines every target to its canonical root: a target path that is -absolute or carries `..` is refused before its first byte, and what remains is canonicalized — -a parent whose resolution leaves the canonical root through a symlink below it is refused -before anything is created or written. Durability ends at the deepest pre-existing ancestor -of the target's parent, inclusive: everything below it was created by this publication and is -synced on every attempt, and when `root` itself is absent the entry that names the freshly -created root — in its existing parent — is persisted before `Ok(())`, so a settled record can -never outlive the projection tree that proves it. Syncing a directory opens it for reading, -so the host must grant read on the deepest pre-existing ancestor and everything below it; -ancestors above it need only traversal — a write-only journal root cannot be published, +`journal_dir(root)` confines every target to its canonical root, and the root is the host's: +it must exist — durable — before the first publication, because the entry that names it lives +in its parent and only the host can establish that durability. A missing root is refused with +the requirement named, and the publisher never creates it. Everything the publisher creates +is beneath the root. A target path that is absolute or carries `..` is refused before its +first byte; what remains is canonicalized — a parent resolving outside the canonical root +through a symlink below it, or a symlink at the target file itself, is refused before anything +is written. Durability syncs the target's file, then every directory beneath the root the +publication created or wrote into, deepest first, ending at the root itself — a pure function +of the target's path, so a retry can never be weaker than the attempt that failed. Syncing a +directory opens it for reading, so the host must grant read on the root and everything beneath +it; ancestors above it need only traversal — a write-only journal root cannot be published, because the sync that must precede settlement would be refused for a reason the write itself never hit. diff --git a/crates/mindcore-runtime/examples/mind_facade.rs b/crates/mindcore-runtime/examples/mind_facade.rs index e129247..2a59ab4 100644 --- a/crates/mindcore-runtime/examples/mind_facade.rs +++ b/crates/mindcore-runtime/examples/mind_facade.rs @@ -71,8 +71,10 @@ async fn main() { .expect("provision the subject"); // 2. Open the handle. The crate's one journal publisher writes the review's file effects - // under the scratch root at their own paths. + // under the scratch root at their own paths — the host creates the root first, because + // the publisher never does: the entry that names it is the host's to make durable. let journal_root = dir.path().join("journal"); + std::fs::create_dir_all(&journal_root).expect("the host creates the journal root"); let mind = ok(Mind::open(&store, &owner, &created.id).await, "open") .with_journal_publisher(journal_dir(journal_root)); diff --git a/crates/mindcore-runtime/src/journal.rs b/crates/mindcore-runtime/src/journal.rs index 27f5f66..36e0c4a 100644 --- a/crates/mindcore-runtime/src/journal.rs +++ b/crates/mindcore-runtime/src/journal.rs @@ -10,6 +10,11 @@ use serde_json::Value; /// target's `path`, parent directories are created, and `Ok(())` is returned only when every /// target's exact bytes are durable. /// +/// The root is the host's, not the publisher's: it must exist — durable — before the first +/// publication, because the entry that names it lives in its parent and only the host can +/// establish that durability. A missing root is refused with the requirement named, and the +/// publisher never creates it. Everything the publisher creates is beneath the root. +/// /// Confinement is filesystem resolution, not spelling. A target path that is absolute or /// carries any `..` — a `ParentDir`, `RootDir` or `Prefix` component — is refused before its /// first byte. What remains is resolved: the root and every target parent are canonicalized, @@ -18,18 +23,17 @@ use serde_json::Value; /// anything is created or written. The root the publisher serves is the canonical root: a /// host that passes a symlinked `root` publishes inside what it resolves to. /// -/// Durability: each target syncs its file, then every directory entry the target depends on, -/// deepest first, ending at the deepest pre-existing ancestor of its parent — inclusive. That -/// directory already exists, so its own creation entry is the host's; everything below it was -/// created by this publication (on this attempt or an earlier failed one) and is synced on -/// every attempt. When `root` itself is absent, `create_dir_all` creates it, and the chain -/// ends at its existing parent: the entry that names the freshly created root is persisted -/// before `Ok(())`, so a settled record can never outlive the projection tree that proves it. +/// Durability: each target syncs its file, then every directory the publication created or +/// wrote into beneath the root, deepest first, ending at the root itself — inclusive. The +/// chain is a pure function of the target's path, never of which directories happen to exist, +/// so a retry after a publication that failed between creating directories and syncing them +/// syncs the same chain as the attempt that failed. The root's own creation entry is the +/// host's and never the publisher's to sync: the host established it durable before the first +/// publication, which is exactly why the publisher requires the root to exist. /// /// Permission requirement: syncing a directory opens it for reading, which POSIX refuses for -/// a search-only directory, so the host must grant read on the deepest pre-existing ancestor -/// and everything the publication creates below it. Ancestors above that anchor need only -/// traversal: the publisher never opens them. +/// a search-only directory, so the host must grant read on `root` and everything beneath it. +/// Ancestors above the root need only traversal: the publisher never opens them. /// /// Target paths are the adapter's own (`records/.md`, `candidates/.md`, /// `profiles/.md`): they are confined to `root` as given rather than re-derived here. @@ -67,15 +71,21 @@ pub fn journal_dir( // parent is reached only when the target names one plain file. _ => root.clone(), }; - // The deepest pre-existing ancestor of the parent — the sync anchor. Existence - // is `symlink_metadata`: a dangling symlink is an existing entry, so it is never - // silently replaced by a created directory. - let anchor = deepest_existing_ancestor(&parent); + // The root is the host's: it must already exist — durable — before the first + // publication. The publisher never creates it, because the entry that names it + // lives in its parent and only the host can establish that durability. + if std::fs::symlink_metadata(&root).is_err() { + return Err(SpiError::InvalidInput(format!( + "journal root {} does not exist: the host must create it — durable — before publication", + root.display() + ))); + } // Symlink escape, refused before anything is created — but only where a symlink - // can exist: inside the root. An anchor strictly within the root means the root - // itself exists, so both canonicalize; an anchor at or above the root means the - // root itself is missing, and a root that does not exist yet holds no symlinks to - // escape through — its containment is the post-creation check's job. + // can exist: inside the root. The deepest pre-existing component strictly within + // the root is canonicalized and must resolve inside the canonical root; a target + // whose parent sits in a freshly creatable subtree has no symlink to escape + // through yet, and its containment is the post-creation check's job. + let anchor = deepest_existing_ancestor(&parent); if anchor != root && anchor.starts_with(&root) { let canonical_root = root.canonicalize().map_err(|error| { SpiError::Settlement(spoke_reject(format!( @@ -121,6 +131,17 @@ pub fn journal_dir( "journal target {path} resolves outside the journal root" ))); } + // The target file itself must not redirect the write: a symlink — or any other + // pre-existing entry that is not a regular file — at the target name is refused + // before the first byte. A regular file is the retry of this same target's own + // earlier write and is replaced with the identical bytes. + if let Ok(metadata) = std::fs::symlink_metadata(&file) { + if !metadata.file_type().is_file() { + return Err(SpiError::InvalidInput(format!( + "journal target {path} already exists as a non-file entry" + ))); + } + } std::fs::write(&file, content).map_err(|error| { SpiError::Settlement(spoke_reject(format!( "journal target {path} could not be written: {error}" @@ -148,7 +169,7 @@ pub fn journal_dir( directory.display() ))) })?; - if directory == anchor { + if directory == root { break; } cursor = directory.parent().map(Path::to_path_buf); diff --git a/crates/mindcore-runtime/tests/mind.rs b/crates/mindcore-runtime/tests/mind.rs index f1b9c22..278f86d 100644 --- a/crates/mindcore-runtime/tests/mind.rs +++ b/crates/mindcore-runtime/tests/mind.rs @@ -663,52 +663,50 @@ async fn a_pending_candidate_at_a_non_one_revision_reviews_and_replays() { ); } -/// The public publisher creates a root that does not exist yet and leaves the target's exact -/// bytes at the target's own path; the durable directory chain it syncs is unit-tested in -/// `journal.rs` (deepest created directory first, ending at the nearest existing ancestor). +/// The root is the host's: the publisher never creates it. A missing root is refused with the +/// requirement named, and nothing is created anywhere. #[tokio::test] -async fn the_public_publisher_creates_and_publishes_a_nested_root() { +async fn the_public_publisher_refuses_a_root_that_does_not_exist() { let dir = TempDir::new().expect("temporary directory"); let root = dir.path().join("nested/publish/root"); assert!(!root.exists(), "the root starts absent"); let publisher = mindcore_runtime::journal_dir(&root); - publisher(&[json!({ + let published = publisher(&[json!({ "path": "records/rec_nested.md", "content": "exact published bytes", - })]) - .expect("publish into a root that does not exist yet"); - assert_eq!( - std::fs::read_to_string(root.join("records").join("rec_nested.md")) - .expect("the published target"), - "exact published bytes" + })]); + let error = published.expect_err("a missing root is refused"); + let message = format!("{error:?}"); + assert!( + message.contains("does not exist"), + "the refusal names the missing root requirement: {message}" + ); + assert!( + !dir.path().join("nested").exists(), + "the publisher created nothing" ); } -/// A relative root is anchored at the current directory: a root that does not exist yet is -/// created and published instead of refusing on the empty parent path. The scratch tree sits -/// directly under the package root cargo runs tests from — no pre-existing intermediate can -/// stand in for the current-directory anchor — and is removed before the assertions. +/// A root the host created receives a nested subtree beneath it: the publisher creates the +/// directories between the root and the target and lands the exact bytes at the target's own +/// path. #[tokio::test] -async fn the_public_publisher_handles_a_relative_root_that_does_not_exist_yet() { - let unique = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .expect("a clock after the epoch") - .as_nanos(); - let relative = format!("journal-relative-{}-{unique}", std::process::id()); - let root = std::path::PathBuf::from(&relative); - assert!(!root.exists(), "the relative root starts absent"); - let publisher = mindcore_runtime::journal_dir(&relative); - let published = publisher(&[json!({ - "path": "records/rec_relative.md", - "content": "relative root bytes", - })]); - let read_back = std::fs::read_to_string(root.join("records").join("rec_relative.md")); - std::fs::remove_dir_all(&root).ok(); - published.expect("a relative root publishes"); +async fn the_public_publisher_publishes_a_nested_subtree_under_an_existing_root() { + let dir = TempDir::new().expect("temporary directory"); + let root = dir.path().join("journal"); + std::fs::create_dir_all(&root).expect("the host creates the root"); + let publisher = mindcore_runtime::journal_dir(&root); + publisher(&[json!({ + "path": "deeply/nested/records/rec_nested.md", + "content": "exact published bytes", + })]) + .expect("publish beneath an existing root"); assert_eq!( - read_back.expect("the published target"), - "relative root bytes", - "the relative root holds the target at its own path" + std::fs::read_to_string( + root.join("deeply").join("nested").join("records").join("rec_nested.md") + ) + .expect("the published target"), + "exact published bytes" ); } @@ -1541,17 +1539,25 @@ async fn publication_blocks_no_executor_progress_and_commits_after_it_confirms() parked.review(&candidate_id, &promote(), "rev-offworker").await }); - // Wait for entry asynchronously — the probe starts only after the publisher is parked. + // Wait for entry asynchronously, with a hard bound: if the publisher never enters — the + // regression this test guards — the timeout fails the test instead of parking it forever. let entered_wait = entered.clone(); - tokio::task::spawn_blocking(move || { - let (lock, cvar) = &*entered_wait; - let mut flag = lock.lock().expect("the entry lock"); - while !*flag { - flag = cvar.wait(flag).expect("wait for publisher entry"); - } - }) - .await - .expect("the publisher is parked inside its flush"); + let entry = tokio::time::timeout( + std::time::Duration::from_secs(5), + tokio::task::spawn_blocking(move || { + let (lock, cvar) = &*entered_wait; + let mut flag = lock.lock().expect("the entry lock"); + while !*flag { + flag = cvar.wait(flag).expect("wait for publisher entry"); + } + }), + ) + .await; + assert!( + entry.is_ok(), + "the publisher never entered its flush — the publication never started" + ); + entry.expect("the entry wait did not panic").expect("the entry task joins"); // The probe: progress measurable only on a free single worker. let (progressed, is_progressed) = tokio::sync::oneshot::channel::<()>(); @@ -1636,9 +1642,20 @@ async fn a_cancelled_review_keeps_the_transaction_until_the_publication_ends() { // The retry handle is opened before the review starts: the store's pool has one // connection, and once the staging transaction holds it nothing — not even a registry read // — can acquire another until the transaction ends. That is the serialization the test - // relies on, and pre-opening is what keeps the test itself out of that queue. - let working = ok(Mind::open(&store, &owner, &created.id).await) - .with_journal_publisher(journal_dir(&journal_root)); + // relies on, and pre-opening is what keeps the test itself out of that queue. The retry's + // publisher signals when it is entered, which can only happen after the retry's own + // staging transaction acquired the pool. + let retry_entered = Arc::new(std::sync::Mutex::new(false)); + let retry_flag = retry_entered.clone(); + let retry_root_handle = journal_root.clone(); + let working = { + let retry_entered = retry_entered.clone(); + ok(Mind::open(&store, &owner, &created.id).await).with_journal_publisher(move |targets| { + journal_dir(&retry_root_handle)(targets)?; + *retry_entered.lock().expect("the retry entry lock") = true; + Ok(()) + }) + }; let cancelled_id = candidate_id.clone(); let review = tokio::spawn(async move { parked.review(&cancelled_id, &promote(), "rev-cancelled").await @@ -1657,21 +1674,39 @@ async fn a_cancelled_review_keeps_the_transaction_until_the_publication_ends() { .expect("the publisher is parked inside its flush"); review.abort(); - // A same-key retry now: its staging transaction cannot acquire until the cancelled - // attempt's transaction rolls back — and that rollback cannot happen before the parked - // publication ends. Release the parked publisher, then the retry settles the key. The - // ownership invariant is what makes this wait exist at all: if the cancelled attempt - // released its transaction while parked, the retry's staging and publication would race - // the first publish instead of queueing behind its rollback. + // A same-key retry while the first publication is still parked. The retry instrumented + // here proves the ordering directly: its own publisher signals when it is entered, and + // that entry can only happen after the retry's staging transaction acquired the pool — + // which the cancelled attempt's rollback gates. If the cancelled attempt released its + // transaction while its publication was still parked, the retry would publish before the + // first attempt's flush ended, and the final assertions would catch the race. + let retrying = working; + let retry = tokio::spawn({ + let candidate_id = candidate_id.clone(); + async move { + retrying.review(&candidate_id, &promote(), "rev-cancelled").await + } + }); + + // Give the retry a real chance to race: yield until it has had every opportunity to enter + // its publication while the first one is still parked. + for _ in 0..16 { + tokio::task::yield_now().await; + } + assert!( + !*retry_flag.lock().expect("the retry entry lock"), + "the retry must not publish while the cancelled attempt's publication is still live" + ); + + // Release the parked publisher: the cancelled attempt's publication ends, its transaction + // rolls back, and only then can the retry's staging acquire. { let (lock, cvar) = &*released; let mut flag = lock.lock().expect("the release lock"); *flag = true; cvar.notify_all(); } - let reviewed = ok(working - .review(&candidate_id, &promote(), "rev-cancelled") - .await); + let reviewed = ok(retry.await.expect("the retry task joins")); assert_eq!( value_of(&reviewed)["status"], "committed", @@ -1800,8 +1835,28 @@ async fn the_public_publisher_refuses_a_target_that_resolves_outside_its_root() "nothing was written at the external destination" ); - // A symlink at the destination itself — the file the write would follow — is refused the - // same way: the parent chain stays inside the root, and the confined target lands. + // A symlink at the target file itself is refused too: bytes must never follow it outside + // the root. + std::fs::create_dir_all(root.join("candidates")).expect("create the target parent"); + std::os::unix::fs::symlink( + outside.join("planted.md"), + root.join("candidates").join("rec_target.md"), + ) + .expect("plant the target symlink"); + let at_target = publisher(&[json!({ + "path": "candidates/rec_target.md", + "content": "escape through the target file", + })]); + assert!( + at_target.is_err(), + "a symlink at the target file is refused" + ); + assert!( + !outside.join("planted.md").exists(), + "nothing was written through the target symlink" + ); + + // The parent chain stays inside the root, and the confined target lands. publisher(&[json!({ "path": "profiles/rec_confined.md", "content": "confined bytes", From a6bca500697fa616139b641b31530cefba793463 Mon Sep 17 00:00:00 2001 From: Tang Bohao Date: Thu, 26 Nov 2026 10:48:06 +0800 Subject: [PATCH 15/22] fix(facade): atomic write-rename against symlink swap, host-root docs, handshake B5 evidence MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit F-003: the write itself can no longer follow a symlink at the target — bytes land in a temp file in the target directory, are synced there, and rename replaces the target entry atomically instead of writing through whatever the entry points to. A symlink at the target is no longer refused but replaced; regression publishes once, swaps the target for a symlink to an outside victim, publishes again, and proves the outside destination is never written while the target lands as a regular file. The residual window — a hostile writer replacing a directory in the parent chain during one publication — is documented in facade.md as a trust-the-host-tree limit, because resolution-before-write is not a filesystem lock. F-008: the example syncs the journal root's parent after creating it, the quickstart carries one sentence on the host's duty to create and make durable the root before the first publish, and facade.md states the parent-sync explicitly. B5 evidence: both proofs are rebuilt on handshakes on the single-threaded runtime, where one yield runs every ready task exactly once — scheduling is control, not timing. The publisher signals entry and parks on a blocking-channel rendezvous; the probe is spawned after the entry signal and its completion is observed after one deterministic yield; the retry is provably parked at its pool acquisition when the negative assertion is read, and its instrumented publisher records whether the cancelled attempt's flush had finished when the retry entered its own. Hard watchdog threads are the only hang guard, each naming the signal that never arrived. No sleeps, no yield counts, no async timeouts. --- .agents/specs/architecture/facade.md | 11 +- .../mindcore-runtime/examples/mind_facade.rs | 5 + crates/mindcore-runtime/src/journal.rs | 48 ++- crates/mindcore-runtime/tests/mind.rs | 306 ++++++++++-------- docs/quickstart.md | 3 +- 5 files changed, 221 insertions(+), 152 deletions(-) diff --git a/.agents/specs/architecture/facade.md b/.agents/specs/architecture/facade.md index 46ed8ab..2a2736c 100644 --- a/.agents/specs/architecture/facade.md +++ b/.agents/specs/architecture/facade.md @@ -86,7 +86,9 @@ between publication and the staging commit. `journal_dir(root)` confines every target to its canonical root, and the root is the host's: it must exist — durable — before the first publication, because the entry that names it lives -in its parent and only the host can establish that durability. A missing root is refused with +in its parent and only the host can establish that durability. Creating the root writes an +entry in its parent, so the host makes it durable by syncing the parent, exactly as the +example does. A missing root is refused with the requirement named, and the publisher never creates it. Everything the publisher creates is beneath the root. A target path that is absolute or carries `..` is refused before its first byte; what remains is canonicalized — a parent resolving outside the canonical root @@ -97,7 +99,12 @@ of the target's path, so a retry can never be weaker than the attempt that faile directory opens it for reading, so the host must grant read on the root and everything beneath it; ancestors above it need only traversal — a write-only journal root cannot be published, because the sync that must precede settlement would be refused for a reason the write itself -never hit. +never hit. A residual +window is documented rather than hidden: a hostile writer that replaces a directory beneath +the root with a symlink *after* the canonicalization check but during the write can redirect +that write, because canonicalization is resolution-before-write, not a filesystem lock. The +publisher trusts the host's tree for the duration of one publication; a host that cannot trust +its own journal tree has no filesystem-level defense the publisher could add. ### `deliberate` without a subject diff --git a/crates/mindcore-runtime/examples/mind_facade.rs b/crates/mindcore-runtime/examples/mind_facade.rs index 2a59ab4..eacdcd7 100644 --- a/crates/mindcore-runtime/examples/mind_facade.rs +++ b/crates/mindcore-runtime/examples/mind_facade.rs @@ -75,6 +75,11 @@ async fn main() { // the publisher never does: the entry that names it is the host's to make durable. let journal_root = dir.path().join("journal"); std::fs::create_dir_all(&journal_root).expect("the host creates the journal root"); + // The host, not the publisher, owns the root's creation entry: creating the root writes an + // entry in its parent, and that entry is durable only once the parent is synced. + std::fs::File::open(journal_root.parent().expect("the journal root has a parent")) + .and_then(|parent| parent.sync_all()) + .expect("sync the journal root's creation entry"); let mind = ok(Mind::open(&store, &owner, &created.id).await, "open") .with_journal_publisher(journal_dir(journal_root)); diff --git a/crates/mindcore-runtime/src/journal.rs b/crates/mindcore-runtime/src/journal.rs index 36e0c4a..08bd6f3 100644 --- a/crates/mindcore-runtime/src/journal.rs +++ b/crates/mindcore-runtime/src/journal.rs @@ -131,34 +131,56 @@ pub fn journal_dir( "journal target {path} resolves outside the journal root" ))); } - // The target file itself must not redirect the write: a symlink — or any other - // pre-existing entry that is not a regular file — at the target name is refused - // before the first byte. A regular file is the retry of this same target's own - // earlier write and is replaced with the identical bytes. + // The write itself can never follow a symlink at the target: the bytes land in a + // temporary file inside the target's own directory, are synced there, and the + // `rename` then replaces the target entry atomically — rename swaps the directory + // entry, it never follows what the entry points to, so a symlink swapped in at any + // moment before it is replaced itself rather than written through. An existing + // regular file is the retry of this target's earlier write and is replaced with + // the identical bytes; any other pre-existing non-file entry is refused first, so + // a directory or device node can never be clobbered by the rename. if let Ok(metadata) = std::fs::symlink_metadata(&file) { - if !metadata.file_type().is_file() { + if !metadata.file_type().is_file() && !metadata.file_type().is_symlink() { return Err(SpiError::InvalidInput(format!( "journal target {path} already exists as a non-file entry" ))); } } - std::fs::write(&file, content).map_err(|error| { + let temporary = parent.join(format!( + ".journal-{}-{pathhash:016x}.tmp", + std::process::id(), + pathhash = { + // A stable hash of the target path: retries of the same target reuse one + // temporary name, so a crashed earlier attempt's leftover is overwritten + // rather than accumulated. + use std::hash::{Hash, Hasher}; + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + file.hash(&mut hasher); + hasher.finish() + } + )); + std::fs::write(&temporary, content).map_err(|error| { SpiError::Settlement(spoke_reject(format!( "journal target {path} could not be written: {error}" ))) })?; - // Durability, not visibility: the write must reach the medium before the caller - // may settle the intent. Sync the file's contents, then every directory entry the - // target depends on, deepest first, ending at the deepest pre-existing ancestor — - // inclusive, because the entry that names what this publication created below it - // (the fresh journal root included) lives in that directory. - std::fs::File::open(&file) - .and_then(|file| file.sync_all()) + std::fs::File::open(&temporary) + .and_then(|temporary| temporary.sync_all()) .map_err(|error| { SpiError::Settlement(spoke_reject(format!( "journal target {path} could not be synced: {error}" ))) })?; + std::fs::rename(&temporary, &file).map_err(|error| { + SpiError::Settlement(spoke_reject(format!( + "journal target {path} could not be renamed into place: {error}" + ))) + })?; + // Durability, not visibility: the write must reach the medium before the caller + // may settle the intent. The temporary's contents were synced before the rename; + // what remains is the directory entries: the rename itself, and every directory the + // publication created or wrote into beneath the root, deepest first, ending at the + // root. let mut cursor = Some(parent.clone()); while let Some(directory) = cursor { std::fs::File::open(&directory) diff --git a/crates/mindcore-runtime/tests/mind.rs b/crates/mindcore-runtime/tests/mind.rs index 278f86d..a7b28f7 100644 --- a/crates/mindcore-runtime/tests/mind.rs +++ b/crates/mindcore-runtime/tests/mind.rs @@ -1488,14 +1488,61 @@ async fn the_public_publisher_refuses_a_target_outside_its_root() { ); } -/// The review's publication runs off the async worker. One worker thread drives the whole -/// test: the publisher parks inside its flush on a rendezvous, and a probe task spawned after -/// entry — before release — completes within the timeout only because the single worker is -/// free to poll it. Publication inlined on the worker would park the worker itself, the probe -/// would starve, and the timeout would fire: the regression fails, never hangs, because the -/// probe's wait is the bounded one. -#[tokio::test(flavor = "multi_thread", worker_threads = 1)] +/// The write cannot follow a symlink even when the swap happens between attempts: publish +/// once, replace the landed target with a symlink to an outside file, publish again — the +/// outside destination is untouched, and the target is the regular file the rename left. +#[tokio::test] +async fn the_public_publisher_never_writes_through_a_swapped_in_target_symlink() { + let dir = TempDir::new().expect("temporary directory"); + let root = dir.path().join("journal"); + std::fs::create_dir_all(&root).expect("the host creates the root"); + let outside = dir.path().join("outside"); + std::fs::create_dir_all(&outside).expect("create the escape destination"); + let publisher = mindcore_runtime::journal_dir(&root); + + publisher(&[json!({ + "path": "records/rec_swap.md", + "content": "first attempt", + })]) + .expect("the first publication lands"); + // The swap: the landed regular file is replaced by a symlink to the outside destination. + std::fs::remove_file(root.join("records").join("rec_swap.md")).expect("remove the first write"); + std::os::unix::fs::symlink( + outside.join("victim.md"), + root.join("records").join("rec_swap.md"), + ) + .expect("swap in the target symlink"); + + publisher(&[json!({ + "path": "records/rec_swap.md", + "content": "second attempt", + })]) + .expect("the rename replaces the swapped symlink instead of writing through it"); + assert!( + !outside.join("victim.md").exists(), + "the outside destination was never written" + ); + assert_eq!( + std::fs::read_to_string(root.join("records").join("rec_swap.md")) + .expect("the target content"), + "second attempt", + "the target holds the retry's bytes as a regular file" + ); +} + +/// The review's publication runs off the async worker. The runtime is single-threaded, which +/// makes scheduling fully controllable: spawned tasks run only when the test yields or awaits, +/// so every assertion below is ordering, never timing. A watchdog thread with a hard deadline +/// is the only guard against a hang, and it names exactly what never arrived. +#[tokio::test] async fn publication_blocks_no_executor_progress_and_commits_after_it_confirms() { + let watchdog = std::thread::spawn(|| { + std::thread::sleep(std::time::Duration::from_secs(30)); + eprintln!("TIMEOUT: the publisher's entry signal never arrived — the publication never started"); + std::process::exit(2); + }); + let _ = &watchdog; + let (dir, store) = fixture().await; let owner = CallerId::new(OWNER); let created = ok(minds::create(&store, &request(OWNER)).await); @@ -1511,27 +1558,23 @@ async fn publication_blocks_no_executor_progress_and_commits_after_it_confirms() .await .expect("open the observer store"); - // A publisher parked inside its flush on a condvar rendezvous. - let entered = Arc::new((std::sync::Mutex::new(false), std::sync::Condvar::new())); - let released = Arc::new((std::sync::Mutex::new(false), std::sync::Condvar::new())); + // The publication handshake: the publisher signals `entered` the moment it is inside its + // flush, then parks on a condvar until the test signals `released`. Both signals are + // blocking-channel rendezvous — no sleeps, no yields, no async timeouts. + let (entered, is_entered) = mpsc::channel::<()>(); + let (release, is_released) = tokio::sync::oneshot::channel::<()>(); + let is_released = std::sync::Mutex::new(Some(is_released)); let parked_root = journal_root.clone(); - let entered_pub = entered.clone(); - let released_pub = released.clone(); let parked = ok(Mind::open(&store, &owner, &created.id).await) .with_journal_publisher(move |targets| { journal_dir(&parked_root)(targets)?; - { - let (lock, cvar) = &*entered_pub; - let mut flag = lock.lock().expect("the entry lock"); - *flag = true; - cvar.notify_all(); - drop(flag); - } - let (lock, cvar) = &*released_pub; - let mut flag = lock.lock().expect("the release lock"); - while !*flag { - flag = cvar.wait(flag).expect("wait for the test release"); - } + entered.send(()).expect("signal the publisher entered"); + let receiver = is_released + .lock() + .expect("the release lock") + .take() + .expect("the publisher is entered once"); + receiver.blocking_recv().expect("wait for the test release"); Ok(()) }); @@ -1539,36 +1582,30 @@ async fn publication_blocks_no_executor_progress_and_commits_after_it_confirms() parked.review(&candidate_id, &promote(), "rev-offworker").await }); - // Wait for entry asynchronously, with a hard bound: if the publisher never enters — the - // regression this test guards — the timeout fails the test instead of parking it forever. - let entered_wait = entered.clone(); - let entry = tokio::time::timeout( - std::time::Duration::from_secs(5), - tokio::task::spawn_blocking(move || { - let (lock, cvar) = &*entered_wait; - let mut flag = lock.lock().expect("the entry lock"); - while !*flag { - flag = cvar.wait(flag).expect("wait for publisher entry"); - } - }), - ) - .await; - assert!( - entry.is_ok(), - "the publisher never entered its flush — the publication never started" - ); - entry.expect("the entry wait did not panic").expect("the entry task joins"); + // Handshake step one: wait for the publisher's entry signal. On the single-threaded + // runtime, awaiting the receive runs the review task — so the task is polled, the + // blocking publication starts, and its signal arrives — or nothing ever runs, which is + // what the watchdog reports. + tokio::task::yield_now().await; + let entered_blocking = tokio::task::spawn_blocking(move || { + is_entered.recv().expect("the publisher entry signal") + }); + entered_blocking.await.expect("the entry signal arrived"); - // The probe: progress measurable only on a free single worker. + // Handshake step two: spawn the probe after the entry signal, yield once — on the + // single-threaded runtime that runs every ready task exactly once — and the probe's send + // must have completed. Publication inlined on the executor would block the runtime thread + // inside the publisher's condvar wait, the probe could never be polled, and its send would + // still be pending here: the test fails on a concrete state, never a timeout. let (progressed, is_progressed) = tokio::sync::oneshot::channel::<()>(); tokio::spawn(async move { let _ = progressed.send(()); }); - let progress = tokio::time::timeout(std::time::Duration::from_secs(5), is_progressed).await; - assert!( - progress.is_ok(), - "executor progress continued while the publisher was parked" - ); + tokio::task::yield_now().await; + match is_progressed.await { + Ok(()) => {} + Err(_) => panic!("executor progress stopped while the publisher was parked"), + } // Nothing commits before the publication confirms: the pre-opened observer reads the // committed state, and the staging transaction's uncommitted rows are invisible to it. assert_eq!( @@ -1577,12 +1614,7 @@ async fn publication_blocks_no_executor_progress_and_commits_after_it_confirms() "nothing commits before the publication confirms" ); - { - let (lock, cvar) = &*released; - let mut flag = lock.lock().expect("the release lock"); - *flag = true; - cvar.notify_all(); - } + release.send(()).expect("release the publisher"); let reviewed = review.await.expect("the review task joins"); assert_eq!( value_of(&ok(reviewed))["status"], @@ -1591,12 +1623,21 @@ async fn publication_blocks_no_executor_progress_and_commits_after_it_confirms() ); } -/// Cancellation keeps transaction ownership until the started publication ends: the review -/// future is dropped while the publisher is parked, yet the first attempt's transaction stays -/// alive until the flush finishes, so a same-key retry can only stage after the first -/// attempt's rollback — the two never publish side by side, and the retry settles. -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +/// Cancellation keeps transaction ownership until the started publication ends. The runtime +/// is single-threaded: one `yield_now` after spawning the retry runs every ready task exactly +/// once, so the retry task is provably parked at its pool acquisition — the first await inside +/// the fold — before the negative assertion is read. The first publication signals `entered` +/// and then parks on a condvar; the retry's instrumented publisher records whether the first +/// publication had finished when the retry entered its own. Ordering is evidence, never +/// timing; the watchdog thread is the only guard against a hang. +#[tokio::test] async fn a_cancelled_review_keeps_the_transaction_until_the_publication_ends() { + std::thread::spawn(|| { + std::thread::sleep(std::time::Duration::from_secs(30)); + eprintln!("TIMEOUT: the publication handshake never completed — a signal never arrived"); + std::process::exit(2); + }); + let (dir, store) = fixture().await; let owner = CallerId::new(OWNER); let created = ok(minds::create(&store, &request(OWNER)).await); @@ -1606,53 +1647,40 @@ async fn a_cancelled_review_keeps_the_transaction_until_the_publication_ends() { .with_journal_publisher(journal_dir(&journal_root)); let candidate_id = capture_candidate(&handle, "cap-cancelled", "a cancelled review").await; - let entered = Arc::new((std::sync::Mutex::new(false), std::sync::Condvar::new())); - let released = Arc::new((std::sync::Mutex::new(false), std::sync::Condvar::new())); - let finished = Arc::new((std::sync::Mutex::new(false), std::sync::Condvar::new())); + let (entered, is_entered) = mpsc::channel::<()>(); + let (release, is_released) = tokio::sync::oneshot::channel::<()>(); + let is_released = std::sync::Mutex::new(Some(is_released)); + let first_finished = Arc::new(std::sync::Mutex::new(false)); + let finished_pub = first_finished.clone(); let parked_root = journal_root.clone(); - let entered_pub = entered.clone(); - let released_pub = released.clone(); - let finished_pub = finished.clone(); let parked = ok(Mind::open(&store, &owner, &created.id).await) .with_journal_publisher(move |targets| { journal_dir(&parked_root)(targets)?; - { - let (lock, cvar) = &*entered_pub; - let mut flag = lock.lock().expect("the entry lock"); - *flag = true; - cvar.notify_all(); - drop(flag); - } - { - let (lock, cvar) = &*released_pub; - let mut flag = lock.lock().expect("the release lock"); - while !*flag { - flag = cvar.wait(flag).expect("wait for the test release"); - } - } - { - let (lock, cvar) = &*finished_pub; - let mut flag = lock.lock().expect("the finish lock"); - *flag = true; - cvar.notify_all(); - } + entered.send(()).expect("signal the publisher entered"); + let receiver = is_released + .lock() + .expect("the release lock") + .take() + .expect("the publisher is entered once"); + receiver.blocking_recv().expect("wait for the test release"); + *finished_pub.lock().expect("the finish lock") = true; Ok(()) }); // The retry handle is opened before the review starts: the store's pool has one // connection, and once the staging transaction holds it nothing — not even a registry read - // — can acquire another until the transaction ends. That is the serialization the test - // relies on, and pre-opening is what keeps the test itself out of that queue. The retry's - // publisher signals when it is entered, which can only happen after the retry's own - // staging transaction acquired the pool. - let retry_entered = Arc::new(std::sync::Mutex::new(false)); - let retry_flag = retry_entered.clone(); + // — can acquire another until the transaction ends. The retry's instrumented publisher + // records what the first publication's finish flag read at the moment the retry entered + // its own flush — the ordering evidence. + let retry_saw_first_finished = Arc::new(std::sync::Mutex::new(None::)); + let retry_flag = retry_saw_first_finished.clone(); let retry_root_handle = journal_root.clone(); + let finished_probe = first_finished.clone(); let working = { - let retry_entered = retry_entered.clone(); ok(Mind::open(&store, &owner, &created.id).await).with_journal_publisher(move |targets| { journal_dir(&retry_root_handle)(targets)?; - *retry_entered.lock().expect("the retry entry lock") = true; + *retry_flag.lock().expect("the retry entry lock") = + Some(*finished_probe.lock().expect("the finish lock")); Ok(()) }) }; @@ -1661,25 +1689,20 @@ async fn a_cancelled_review_keeps_the_transaction_until_the_publication_ends() { parked.review(&cancelled_id, &promote(), "rev-cancelled").await }); - // Park the publisher, then drop the review future: the cancellation. - let entered_wait = entered.clone(); - tokio::task::spawn_blocking(move || { - let (lock, cvar) = &*entered_wait; - let mut flag = lock.lock().expect("the entry lock"); - while !*flag { - flag = cvar.wait(flag).expect("wait for publisher entry"); - } - }) - .await - .expect("the publisher is parked inside its flush"); + // Handshake: yield once so the review task starts, then receive the publisher's entry + // signal on a blocking thread, then cancel. + tokio::task::yield_now().await; + let entry = tokio::task::spawn_blocking(move || { + is_entered.recv().expect("the publisher entry signal") + }); + entry.await.expect("the entry signal arrived"); review.abort(); - // A same-key retry while the first publication is still parked. The retry instrumented - // here proves the ordering directly: its own publisher signals when it is entered, and - // that entry can only happen after the retry's staging transaction acquired the pool — - // which the cancelled attempt's rollback gates. If the cancelled attempt released its - // transaction while its publication was still parked, the retry would publish before the - // first attempt's flush ended, and the final assertions would catch the race. + // The retry, while the first publication is still parked. One yield on the single-threaded + // runtime polls the retry task exactly once: it runs into the fold and parks at the pool + // acquisition — the pool's one connection is held by the cancelled attempt's transaction — + // so the negative assertion below is read with the retry provably contending, never merely + // unscheduled. let retrying = working; let retry = tokio::spawn({ let candidate_id = candidate_id.clone(); @@ -1687,26 +1710,28 @@ async fn a_cancelled_review_keeps_the_transaction_until_the_publication_ends() { retrying.review(&candidate_id, &promote(), "rev-cancelled").await } }); - - // Give the retry a real chance to race: yield until it has had every opportunity to enter - // its publication while the first one is still parked. - for _ in 0..16 { - tokio::task::yield_now().await; - } + tokio::task::yield_now().await; assert!( - !*retry_flag.lock().expect("the retry entry lock"), - "the retry must not publish while the cancelled attempt's publication is still live" + retry_saw_first_finished + .lock() + .expect("the retry entry lock") + .is_none(), + "the retry must not enter its publication while the cancelled attempt's flush is live" ); - // Release the parked publisher: the cancelled attempt's publication ends, its transaction - // rolls back, and only then can the retry's staging acquire. - { - let (lock, cvar) = &*released; - let mut flag = lock.lock().expect("the release lock"); - *flag = true; - cvar.notify_all(); - } + // Release: the first publication ends, the cancelled attempt's transaction rolls back, and + // only then can the retry's staging acquire. Awaiting the retry runs it to completion on + // this runtime. + release.send(()).expect("release the publisher"); let reviewed = ok(retry.await.expect("the retry task joins")); + + // The ordering evidence: when the retry entered its publication, the first publication + // had finished — the cancelled attempt's flush ended before any retry publish began. + assert_eq!( + *retry_saw_first_finished.lock().expect("the retry entry lock"), + Some(true), + "the retry's publication began only after the cancelled attempt's flush ended" + ); assert_eq!( value_of(&reviewed)["status"], "committed", @@ -1835,26 +1860,35 @@ async fn the_public_publisher_refuses_a_target_that_resolves_outside_its_root() "nothing was written at the external destination" ); - // A symlink at the target file itself is refused too: bytes must never follow it outside - // the root. + // A symlink at the target file itself cannot redirect the write either: the bytes are + // written to a temporary file in the same directory and renamed over the target — rename + // replaces the directory entry, it never follows what the entry points to. std::fs::create_dir_all(root.join("candidates")).expect("create the target parent"); std::os::unix::fs::symlink( outside.join("planted.md"), root.join("candidates").join("rec_target.md"), ) .expect("plant the target symlink"); - let at_target = publisher(&[json!({ + publisher(&[json!({ "path": "candidates/rec_target.md", - "content": "escape through the target file", - })]); - assert!( - at_target.is_err(), - "a symlink at the target file is refused" - ); + "content": "confined despite the target symlink", + })]) + .expect("the rename replaces the symlink instead of following it"); assert!( !outside.join("planted.md").exists(), "nothing was written through the target symlink" ); + let landed = std::fs::symlink_metadata(root.join("candidates").join("rec_target.md")) + .expect("the target entry"); + assert!( + landed.file_type().is_file(), + "the target is a regular file after the rename, not the planted symlink" + ); + assert_eq!( + std::fs::read_to_string(root.join("candidates").join("rec_target.md")) + .expect("the target content"), + "confined despite the target symlink" + ); // The parent chain stays inside the root, and the confined target lands. publisher(&[json!({ diff --git a/docs/quickstart.md b/docs/quickstart.md index 3caa050..75e3436 100644 --- a/docs/quickstart.md +++ b/docs/quickstart.md @@ -70,7 +70,8 @@ let mind = ok(Mind::open(&store, &owner, &created.id).await, "open") `open` is one registry read; a Mind the caller cannot see answers the registry's own `NotFound`. The journal publisher is the host's input — the facade never invents one — and `journal_dir` is -the one publisher the crate offers. Before memory writes, the host provisions the subject rows it +the one publisher the crate offers. The journal root is the host's to create and make durable +before the first publish: create it, then sync its parent, exactly as the example does. Before memory writes, the host provisions the subject rows it means to write under, exactly as on the served surface; the example shows the minimal seed. 2. Captures a memory and reviews it, in plain arguments: From 9cf9cb4962a4dc77fa118c348666bb91f45e5cf1 Mon Sep 17 00:00:00 2001 From: Tang Bohao Date: Thu, 26 Nov 2026 10:52:09 +0800 Subject: [PATCH 16/22] test(facade): observed-state B5 evidence, exclusive temp creation, complete host durability MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Watchdogs are disarmed on success: an atomic flag the watchdog thread checks before firing, so a passing test leaves nothing armed. The retry's instrumented publisher samples the first publication's finish flag before writing anything — the ordering evidence reads the world as it was before the retry's own bytes existed. The single-yield scheduling assumption is gone: loops advance only on observed state — JoinHandle::is_finished on the probe and on a sentinel task spawned behind the retry — with yield_now as a politeness hint inside the loop, never the ordering proof. A tick bound fails the test naming what never happened if the runtime never polls the tasks. F-003: the temporary file is created exclusively with create_new, which fails on any existing entry, so a symlink pre-placed at the temporary name is refused rather than followed; a leftover regular file — this target's own crashed attempt — is removed and retried, anything else is refused. Regression pre-places a symlink at the temp name and proves the outside victim is never written. F-008: the example now syncs the TempDir's own parent entry as well, the same way it syncs the journal root's parent. --- .../mindcore-runtime/examples/mind_facade.rs | 5 + crates/mindcore-runtime/src/journal.rs | 60 +++++- crates/mindcore-runtime/tests/mind.rs | 202 ++++++++++++------ 3 files changed, 194 insertions(+), 73 deletions(-) diff --git a/crates/mindcore-runtime/examples/mind_facade.rs b/crates/mindcore-runtime/examples/mind_facade.rs index eacdcd7..b661bb3 100644 --- a/crates/mindcore-runtime/examples/mind_facade.rs +++ b/crates/mindcore-runtime/examples/mind_facade.rs @@ -37,6 +37,11 @@ fn value_of(response: &T) -> Value { #[tokio::main] async fn main() { let dir = tempfile::TempDir::new().expect("a scratch directory"); + // Creating the scratch directory wrote an entry in its parent; the host makes that entry + // durable before anything depends on it, exactly as it will for the journal root below. + std::fs::File::open(dir.path().parent().expect("the scratch directory has a parent")) + .and_then(|parent| parent.sync_all()) + .expect("sync the scratch directory's creation entry"); let store = MindStore::open(&dir.path().join("mind.db")) .await .expect("open the store"); diff --git a/crates/mindcore-runtime/src/journal.rs b/crates/mindcore-runtime/src/journal.rs index 08bd6f3..f59657e 100644 --- a/crates/mindcore-runtime/src/journal.rs +++ b/crates/mindcore-runtime/src/journal.rs @@ -159,18 +159,62 @@ pub fn journal_dir( hasher.finish() } )); - std::fs::write(&temporary, content).map_err(|error| { - SpiError::Settlement(spoke_reject(format!( - "journal target {path} could not be written: {error}" - ))) - })?; - std::fs::File::open(&temporary) - .and_then(|temporary| temporary.sync_all()) + // The temporary itself is created exclusively: `create_new` fails on any existing + // entry — a pre-planted symlink included — and otherwise creates a fresh regular + // file, so the write can never follow a symlink at the temporary name either. A + // leftover regular file is this target's own crashed attempt and is removed before + // the retry; a symlink or any other entry is refused. + let mut attempts = 0u32; + let mut temporary_file = loop { + match std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(&temporary) + { + Ok(temporary_file) => break temporary_file, + Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => { + match std::fs::symlink_metadata(&temporary) { + Ok(metadata) if metadata.file_type().is_file() => { + std::fs::remove_file(&temporary).map_err(|error| { + SpiError::Settlement(spoke_reject(format!( + "the leftover temporary for {path} could not be removed: {error}" + ))) + })?; + } + _ => { + return Err(SpiError::InvalidInput(format!( + "the temporary file for journal target {path} already exists as a non-file entry" + ))); + } + } + attempts += 1; + if attempts >= 8 { + return Err(SpiError::Settlement(spoke_reject(format!( + "the temporary file for journal target {path} could not be created exclusively" + )))); + } + } + Err(error) => { + return Err(SpiError::Settlement(spoke_reject(format!( + "journal target {path} could not be written: {error}" + )))); + } + } + }; + use std::io::Write as _; + temporary_file + .write_all(content.as_bytes()) .map_err(|error| { SpiError::Settlement(spoke_reject(format!( - "journal target {path} could not be synced: {error}" + "journal target {path} could not be written: {error}" ))) })?; + temporary_file.sync_all().map_err(|error| { + SpiError::Settlement(spoke_reject(format!( + "journal target {path} could not be synced: {error}" + ))) + })?; + drop(temporary_file); std::fs::rename(&temporary, &file).map_err(|error| { SpiError::Settlement(spoke_reject(format!( "journal target {path} could not be renamed into place: {error}" diff --git a/crates/mindcore-runtime/tests/mind.rs b/crates/mindcore-runtime/tests/mind.rs index a7b28f7..4d26771 100644 --- a/crates/mindcore-runtime/tests/mind.rs +++ b/crates/mindcore-runtime/tests/mind.rs @@ -1530,18 +1530,69 @@ async fn the_public_publisher_never_writes_through_a_swapped_in_target_symlink() ); } -/// The review's publication runs off the async worker. The runtime is single-threaded, which -/// makes scheduling fully controllable: spawned tasks run only when the test yields or awaits, -/// so every assertion below is ordering, never timing. A watchdog thread with a hard deadline -/// is the only guard against a hang, and it names exactly what never arrived. +/// The temporary file itself is created exclusively: a symlink pre-placed at the temporary +/// name is refused rather than followed, and the victim outside the root is never written. +#[tokio::test] +async fn the_public_publisher_never_writes_through_a_preplaced_temporary_symlink() { + let dir = TempDir::new().expect("temporary directory"); + let root = dir.path().join("journal"); + std::fs::create_dir_all(&root).expect("the host creates the root"); + let outside = dir.path().join("outside"); + std::fs::create_dir_all(&outside).expect("create the escape destination"); + let publisher = mindcore_runtime::journal_dir(&root); + + // Compute the temporary name exactly as the publisher does and pre-place a symlink there. + let target_path = "records/rec_preplaced.md"; + let file = root.join(target_path); + let parent = file.parent().expect("the target parent").to_path_buf(); + std::fs::create_dir_all(&parent).expect("create the target parent"); + let temporary = parent.join(format!( + ".journal-{}-{:016x}.tmp", + std::process::id(), + { + use std::hash::{Hash, Hasher}; + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + file.hash(&mut hasher); + hasher.finish() + } + )); + std::os::unix::fs::symlink(outside.join("victim.md"), &temporary) + .expect("pre-place the temporary symlink"); + + let published = publisher(&[json!({ + "path": target_path, + "content": "must never land outside", + })]); + assert!( + published.is_err(), + "a pre-placed symlink at the temporary name is refused" + ); + assert!( + !outside.join("victim.md").exists(), + "the victim outside the root was never written" + ); +} + +/// The review's publication runs off the async worker. The proof is the probe's own lifecycle: +/// the probe task is spawned while the publisher is parked inside its flush, and its join +/// handle is observed finished — an observed state, never a scheduling assumption — before the +/// publisher is released. Publication inlined on the executor would park the runtime thread in +/// the publisher's blocking wait, the probe could never be polled, the handle would never +/// finish, and the watchdog would name that exact missing signal. The watchdog is disarmed on +/// success. #[tokio::test] async fn publication_blocks_no_executor_progress_and_commits_after_it_confirms() { - let watchdog = std::thread::spawn(|| { - std::thread::sleep(std::time::Duration::from_secs(30)); - eprintln!("TIMEOUT: the publisher's entry signal never arrived — the publication never started"); - std::process::exit(2); - }); - let _ = &watchdog; + let disarm = Arc::new(std::sync::atomic::AtomicBool::new(false)); + { + let disarm = disarm.clone(); + std::thread::spawn(move || { + std::thread::sleep(std::time::Duration::from_secs(30)); + if !disarm.load(std::sync::atomic::Ordering::SeqCst) { + eprintln!("TIMEOUT: the probe never completed — executor progress stopped while the publisher was parked"); + std::process::exit(2); + } + }); + } let (dir, store) = fixture().await; let owner = CallerId::new(OWNER); @@ -1559,8 +1610,7 @@ async fn publication_blocks_no_executor_progress_and_commits_after_it_confirms() .expect("open the observer store"); // The publication handshake: the publisher signals `entered` the moment it is inside its - // flush, then parks on a condvar until the test signals `released`. Both signals are - // blocking-channel rendezvous — no sleeps, no yields, no async timeouts. + // flush, then parks on a blocking channel until the test releases it. let (entered, is_entered) = mpsc::channel::<()>(); let (release, is_released) = tokio::sync::oneshot::channel::<()>(); let is_released = std::sync::Mutex::new(Some(is_released)); @@ -1582,30 +1632,30 @@ async fn publication_blocks_no_executor_progress_and_commits_after_it_confirms() parked.review(&candidate_id, &promote(), "rev-offworker").await }); - // Handshake step one: wait for the publisher's entry signal. On the single-threaded - // runtime, awaiting the receive runs the review task — so the task is polled, the - // blocking publication starts, and its signal arrives — or nothing ever runs, which is - // what the watchdog reports. - tokio::task::yield_now().await; - let entered_blocking = tokio::task::spawn_blocking(move || { + // Wait for the publisher's entry signal on a blocking thread — the receive itself is the + // observed state: it completes exactly when the publisher is inside its flush, however the + // scheduler gets there. + let entry = tokio::task::spawn_blocking(move || { is_entered.recv().expect("the publisher entry signal") }); - entered_blocking.await.expect("the entry signal arrived"); - - // Handshake step two: spawn the probe after the entry signal, yield once — on the - // single-threaded runtime that runs every ready task exactly once — and the probe's send - // must have completed. Publication inlined on the executor would block the runtime thread - // inside the publisher's condvar wait, the probe could never be polled, and its send would - // still be pending here: the test fails on a concrete state, never a timeout. - let (progressed, is_progressed) = tokio::sync::oneshot::channel::<()>(); - tokio::spawn(async move { - let _ = progressed.send(()); - }); - tokio::task::yield_now().await; - match is_progressed.await { - Ok(()) => {} - Err(_) => panic!("executor progress stopped while the publisher was parked"), + entry.await.expect("the entry signal arrived"); + + // The probe: spawned after the entry signal, a bare unit of executor work. Its completion + // is proof of executor progress — the publisher is parked, so the probe completing means + // something other than the blocked publication polled it. The observation loop advances + // only on the handle's own observed state, with `yield_now` as a politeness hint to the + // scheduler, never as the ordering proof: the handle either finishes or it does not. + let probe = tokio::spawn(async {}); + let mut ticks = 0u32; + while !probe.is_finished() { + tokio::task::yield_now().await; + ticks += 1; + assert!( + ticks < 1_000_000, + "the probe never completed — executor progress stopped while the publisher was parked" + ); } + probe.await.expect("the probe joins"); // Nothing commits before the publication confirms: the pre-opened observer reads the // committed state, and the staging transaction's uncommitted rows are invisible to it. assert_eq!( @@ -1621,22 +1671,28 @@ async fn publication_blocks_no_executor_progress_and_commits_after_it_confirms() "committed", "the review settles after the publication confirms" ); + disarm.store(true, std::sync::atomic::Ordering::SeqCst); } -/// Cancellation keeps transaction ownership until the started publication ends. The runtime -/// is single-threaded: one `yield_now` after spawning the retry runs every ready task exactly -/// once, so the retry task is provably parked at its pool acquisition — the first await inside -/// the fold — before the negative assertion is read. The first publication signals `entered` -/// and then parks on a condvar; the retry's instrumented publisher records whether the first -/// publication had finished when the retry entered its own. Ordering is evidence, never -/// timing; the watchdog thread is the only guard against a hang. +/// Cancellation keeps transaction ownership until the started publication ends. The evidence +/// is a chain of observed states, never a scheduling assumption: the probe of the retry's +/// contention is the retry's own publisher-entry flag read after the retry has been given its +/// turn, and the turn is the observer pattern of `JoinHandle::is_finished` on a sentinel task +/// spawned with it — a task that finishes only after the runtime has polled every task that +/// was ready before it. The watchdog is disarmed on success. #[tokio::test] async fn a_cancelled_review_keeps_the_transaction_until_the_publication_ends() { - std::thread::spawn(|| { - std::thread::sleep(std::time::Duration::from_secs(30)); - eprintln!("TIMEOUT: the publication handshake never completed — a signal never arrived"); - std::process::exit(2); - }); + let disarm = Arc::new(std::sync::atomic::AtomicBool::new(false)); + { + let disarm = disarm.clone(); + std::thread::spawn(move || { + std::thread::sleep(std::time::Duration::from_secs(30)); + if !disarm.load(std::sync::atomic::Ordering::SeqCst) { + eprintln!("TIMEOUT: the publication handshake never completed — a signal never arrived"); + std::process::exit(2); + } + }); + } let (dir, store) = fixture().await; let owner = CallerId::new(OWNER); @@ -1670,17 +1726,20 @@ async fn a_cancelled_review_keeps_the_transaction_until_the_publication_ends() { // The retry handle is opened before the review starts: the store's pool has one // connection, and once the staging transaction holds it nothing — not even a registry read // — can acquire another until the transaction ends. The retry's instrumented publisher - // records what the first publication's finish flag read at the moment the retry entered - // its own flush — the ordering evidence. - let retry_saw_first_finished = Arc::new(std::sync::Mutex::new(None::)); - let retry_flag = retry_saw_first_finished.clone(); + // samples the first publication's finish flag *before writing anything*: the sample is + // taken the moment the retry enters its flush, so it reads the world as it was before the + // retry's own bytes existed. + let retry_sample = Arc::new(std::sync::Mutex::new(None::)); + let retry_flag = retry_sample.clone(); let retry_root_handle = journal_root.clone(); let finished_probe = first_finished.clone(); let working = { ok(Mind::open(&store, &owner, &created.id).await).with_journal_publisher(move |targets| { - journal_dir(&retry_root_handle)(targets)?; + // Sample before any write of this flush: the ordering evidence is the state of the + // first publication at the moment the retry's publication begins, not after it. *retry_flag.lock().expect("the retry entry lock") = Some(*finished_probe.lock().expect("the finish lock")); + journal_dir(&retry_root_handle)(targets)?; Ok(()) }) }; @@ -1689,20 +1748,20 @@ async fn a_cancelled_review_keeps_the_transaction_until_the_publication_ends() { parked.review(&cancelled_id, &promote(), "rev-cancelled").await }); - // Handshake: yield once so the review task starts, then receive the publisher's entry - // signal on a blocking thread, then cancel. - tokio::task::yield_now().await; + // Wait for the publisher's entry signal, then cancel. The receive itself is the observed + // state: it completes exactly when the publisher is inside its flush. let entry = tokio::task::spawn_blocking(move || { is_entered.recv().expect("the publisher entry signal") }); entry.await.expect("the entry signal arrived"); review.abort(); - // The retry, while the first publication is still parked. One yield on the single-threaded - // runtime polls the retry task exactly once: it runs into the fold and parks at the pool - // acquisition — the pool's one connection is held by the cancelled attempt's transaction — - // so the negative assertion below is read with the retry provably contending, never merely - // unscheduled. + // The retry, spawned with a sentinel task behind it. The sentinel finishes only after the + // runtime has polled every task that was ready before it — the retry included — so the + // sentinel's finished handle is the observed state that the retry was polled to its first + // suspension point: the pool acquisition, because the pool's one connection is held by the + // cancelled attempt's transaction. `yield_now` inside the loop is a politeness hint to the + // scheduler; the loop advances only on the observed state. let retrying = working; let retry = tokio::spawn({ let candidate_id = candidate_id.clone(); @@ -1710,9 +1769,21 @@ async fn a_cancelled_review_keeps_the_transaction_until_the_publication_ends() { retrying.review(&candidate_id, &promote(), "rev-cancelled").await } }); - tokio::task::yield_now().await; + let sentinel = tokio::spawn(async {}); + let mut ticks = 0u32; + while !sentinel.is_finished() { + tokio::task::yield_now().await; + ticks += 1; + assert!( + ticks < 1_000_000, + "the sentinel never finished — the runtime never polled the spawned tasks" + ); + } + // The retry has now been polled to its pool acquisition — it is contending — and it must + // not have entered its publication: the first publication is still parked, and the + // cancelled attempt's transaction is still the pool's tenant. assert!( - retry_saw_first_finished + retry_sample .lock() .expect("the retry entry lock") .is_none(), @@ -1720,15 +1791,15 @@ async fn a_cancelled_review_keeps_the_transaction_until_the_publication_ends() { ); // Release: the first publication ends, the cancelled attempt's transaction rolls back, and - // only then can the retry's staging acquire. Awaiting the retry runs it to completion on - // this runtime. + // only then can the retry's staging acquire. release.send(()).expect("release the publisher"); let reviewed = ok(retry.await.expect("the retry task joins")); - // The ordering evidence: when the retry entered its publication, the first publication - // had finished — the cancelled attempt's flush ended before any retry publish began. + // The ordering evidence: sampled before the retry wrote anything, the first publication's + // finish flag was already set — the cancelled attempt's flush ended before the retry's + // publication began. assert_eq!( - *retry_saw_first_finished.lock().expect("the retry entry lock"), + *retry_sample.lock().expect("the retry entry lock"), Some(true), "the retry's publication began only after the cancelled attempt's flush ended" ); @@ -1747,6 +1818,7 @@ async fn a_cancelled_review_keeps_the_transaction_until_the_publication_ends() { 1, "exactly one intent across both attempts" ); + disarm.store(true, std::sync::atomic::Ordering::SeqCst); } /// `cognition_read` reads only the collection its admitted Mind resolved at open: a colliding From 553384ea83d84bb5b5898fbcc6df7d02127deafe Mon Sep 17 00:00:00 2001 From: Tang Bohao Date: Thu, 26 Nov 2026 10:57:46 +0800 Subject: [PATCH 17/22] test(facade): the cancel regression proves the invariant directly and has teeth MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The witness replaces the retry as evidence: the pool has exactly one connection, so a bare acquisition observes the invariant itself — the connection is free while the first publication is parked only if the cancelled attempt released its transaction early. The witness is provably at its acquisition when the negative assertion reads it (the sentinel behind it finishing is the observed state of its first poll), the negative assertion is read while the first publication is still parked with nothing between the read and the release, and the positive side is asserted too: the witness must acquire after the publication ends, which is when the correct implementation's rollback releases the connection. Teeth proven: with the transaction moved back out of the blocking task (the pre-fix shape), the test fails in 0.07s with 'the witness acquired the connection while the cancelled attempt's publication was still parked: the transaction was released before the publication ended'; the implementation file was then restored byte for byte (cmp-verified) and the suite re-run green. --- crates/mindcore-runtime/tests/mind.rs | 128 ++++++++++++++------------ 1 file changed, 70 insertions(+), 58 deletions(-) diff --git a/crates/mindcore-runtime/tests/mind.rs b/crates/mindcore-runtime/tests/mind.rs index 4d26771..9ad4222 100644 --- a/crates/mindcore-runtime/tests/mind.rs +++ b/crates/mindcore-runtime/tests/mind.rs @@ -1674,12 +1674,18 @@ async fn publication_blocks_no_executor_progress_and_commits_after_it_confirms() disarm.store(true, std::sync::atomic::Ordering::SeqCst); } -/// Cancellation keeps transaction ownership until the started publication ends. The evidence -/// is a chain of observed states, never a scheduling assumption: the probe of the retry's -/// contention is the retry's own publisher-entry flag read after the retry has been given its -/// turn, and the turn is the observer pattern of `JoinHandle::is_finished` on a sentinel task -/// spawned with it — a task that finishes only after the runtime has polled every task that -/// was ready before it. The watchdog is disarmed on success. +/// Cancellation keeps transaction ownership until the started publication ends. The invariant +/// is tested directly, not through the retry: the pool has exactly one connection, so while +/// the first publication is parked the connection is free only if the cancelled attempt +/// released its transaction early — and a witness acquisition observes that directly. The +/// witness is spawned with a sentinel behind it: the sentinel finishes only after the runtime +/// has polled every task that was ready before it, so its finished handle is the observed +/// state that the witness was polled to its acquisition. What the witness then does is the +/// evidence, observed rather than assumed: it must NOT acquire while the first publication is +/// parked — a parked flush with a released transaction would hand the witness the connection +/// and the test would fail naming the premature acquisition — and it MUST acquire once the +/// first publication has ended, which is when the correct implementation's rollback releases +/// the connection. The watchdog is disarmed on success. #[tokio::test] async fn a_cancelled_review_keeps_the_transaction_until_the_publication_ends() { let disarm = Arc::new(std::sync::atomic::AtomicBool::new(false)); @@ -1723,26 +1729,6 @@ async fn a_cancelled_review_keeps_the_transaction_until_the_publication_ends() { Ok(()) }); - // The retry handle is opened before the review starts: the store's pool has one - // connection, and once the staging transaction holds it nothing — not even a registry read - // — can acquire another until the transaction ends. The retry's instrumented publisher - // samples the first publication's finish flag *before writing anything*: the sample is - // taken the moment the retry enters its flush, so it reads the world as it was before the - // retry's own bytes existed. - let retry_sample = Arc::new(std::sync::Mutex::new(None::)); - let retry_flag = retry_sample.clone(); - let retry_root_handle = journal_root.clone(); - let finished_probe = first_finished.clone(); - let working = { - ok(Mind::open(&store, &owner, &created.id).await).with_journal_publisher(move |targets| { - // Sample before any write of this flush: the ordering evidence is the state of the - // first publication at the moment the retry's publication begins, not after it. - *retry_flag.lock().expect("the retry entry lock") = - Some(*finished_probe.lock().expect("the finish lock")); - journal_dir(&retry_root_handle)(targets)?; - Ok(()) - }) - }; let cancelled_id = candidate_id.clone(); let review = tokio::spawn(async move { parked.review(&cancelled_id, &promote(), "rev-cancelled").await @@ -1756,18 +1742,16 @@ async fn a_cancelled_review_keeps_the_transaction_until_the_publication_ends() { entry.await.expect("the entry signal arrived"); review.abort(); - // The retry, spawned with a sentinel task behind it. The sentinel finishes only after the - // runtime has polled every task that was ready before it — the retry included — so the - // sentinel's finished handle is the observed state that the retry was polled to its first - // suspension point: the pool acquisition, because the pool's one connection is held by the - // cancelled attempt's transaction. `yield_now` inside the loop is a politeness hint to the - // scheduler; the loop advances only on the observed state. - let retrying = working; - let retry = tokio::spawn({ - let candidate_id = candidate_id.clone(); - async move { - retrying.review(&candidate_id, &promote(), "rev-cancelled").await - } + // The witness: a bare pool acquisition. The pool has one connection, so it completes + // exactly when the connection is free — and the connection is free while the publication + // is parked only if the cancelled attempt released its transaction early. The sentinel is + // spawned behind it: its finished handle is the observed state that the witness was + // polled to its acquisition — the witness can only be waiting on the connection or already + // holding it, never merely unscheduled. + let witness_pool = store.pool(); + let witness = tokio::spawn(async move { + let connection = witness_pool.acquire().await.expect("the witness acquisition"); + drop(connection); }); let sentinel = tokio::spawn(async {}); let mut ticks = 0u32; @@ -1779,34 +1763,62 @@ async fn a_cancelled_review_keeps_the_transaction_until_the_publication_ends() { "the sentinel never finished — the runtime never polled the spawned tasks" ); } - // The retry has now been polled to its pool acquisition — it is contending — and it must - // not have entered its publication: the first publication is still parked, and the - // cancelled attempt's transaction is still the pool's tenant. - assert!( - retry_sample - .lock() - .expect("the retry entry lock") - .is_none(), - "the retry must not enter its publication while the cancelled attempt's flush is live" - ); + // The witness is provably at its acquisition. Give an early release every chance to hand + // it the connection: the rollback after a cancelled attempt runs on sqlx's connection + // worker thread, so the observation window spans real thread scheduling — this is the + // detection window for a regression, not an ordering proof for the correct behavior, and + // its length bounds nothing the fixed implementation depends on. + let window = std::time::Instant::now(); + while window.elapsed() < std::time::Duration::from_millis(500) { + assert!( + !witness.is_finished(), + "the witness acquired the connection while the cancelled attempt's publication was still parked: the transaction was released before the publication ended" + ); + tokio::task::yield_now().await; + } - // Release: the first publication ends, the cancelled attempt's transaction rolls back, and - // only then can the retry's staging acquire. + // Release the first publication: its flush ends, the finish flag is set, and only then + // may the connection become free — the correct implementation's rollback runs after the + // blocking task returns the transaction. release.send(()).expect("release the publisher"); - let reviewed = ok(retry.await.expect("the retry task joins")); + let mut ticks = 0u32; + while !witness.is_finished() { + tokio::task::yield_now().await; + ticks += 1; + assert!( + ticks < 1_000_000, + "the witness never acquired after the publication ended — the connection was never released" + ); + } + witness.await.expect("the witness joins"); + assert!( + *first_finished.lock().expect("the finish lock"), + "the first publication finished before the connection became free" + ); - // The ordering evidence: sampled before the retry wrote anything, the first publication's - // finish flag was already set — the cancelled attempt's flush ended before the retry's - // publication began. + // The end state is clean: the cancelled attempt left nothing behind. assert_eq!( - *retry_sample.lock().expect("the retry entry lock"), - Some(true), - "the retry's publication began only after the cancelled attempt's flush ended" + count_records(&store.pool()).await, + 0, + "the cancelled attempt rolled everything back" ); + assert_eq!( + count_intents(&store.pool()).await, + 0, + "no intent survives the cancellation" + ); + + // And the same key still settles through a fresh attempt — the rollback is complete, not + // merely invisible. + let working = ok(Mind::open(&store, &owner, &created.id).await) + .with_journal_publisher(journal_dir(&journal_root)); + let reviewed = ok(working + .review(&candidate_id, &promote(), "rev-cancelled") + .await); assert_eq!( value_of(&reviewed)["status"], "committed", - "the same-key retry settles after the cancelled attempt finished" + "the same key settles after the cancelled attempt rolled back" ); assert_eq!( count_records(&store.pool()).await, From d20943e1c2ba42b7cc6952db46bd5af86a69aaaa Mon Sep 17 00:00:00 2001 From: Tang Bohao Date: Thu, 26 Nov 2026 11:00:36 +0800 Subject: [PATCH 18/22] docs(facade): symlink semantics are replacement, and the quickstart snippet runs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit F-011: facade.md and journal.rs's module doc no longer say a symlink at the target file is refused — since the write-temp-sync-rename change the target entry is replaced atomically and the publish succeeds; refusal applies to a symlink at the temporary name and to an escaping parent chain, and both documents now say exactly that. F-012: the quickstart snippet prepares the journal root the way the publisher requires — create_dir_all plus a sync of its parent — so the printed example runs against the host-owned-root contract. --- .agents/specs/architecture/facade.md | 7 +++++-- crates/mindcore-runtime/src/journal.rs | 7 ++++++- docs/quickstart.md | 7 +++++++ 3 files changed, 18 insertions(+), 3 deletions(-) diff --git a/.agents/specs/architecture/facade.md b/.agents/specs/architecture/facade.md index 2a2736c..bbef2cf 100644 --- a/.agents/specs/architecture/facade.md +++ b/.agents/specs/architecture/facade.md @@ -92,8 +92,11 @@ example does. A missing root is refused with the requirement named, and the publisher never creates it. Everything the publisher creates is beneath the root. A target path that is absolute or carries `..` is refused before its first byte; what remains is canonicalized — a parent resolving outside the canonical root -through a symlink below it, or a symlink at the target file itself, is refused before anything -is written. Durability syncs the target's file, then every directory beneath the root the +through a symlink below it is refused before anything is created or written. At the target +file itself no symlink can redirect the write: the bytes are written to a temporary file +created exclusively in the same directory and renamed over the target atomically, so a symlink +at the target is replaced rather than followed — refusal applies instead to a symlink at the +temporary name. Durability syncs the target's file, then every directory beneath the root the publication created or wrote into, deepest first, ending at the root itself — a pure function of the target's path, so a retry can never be weaker than the attempt that failed. Syncing a directory opens it for reading, so the host must grant read on the root and everything beneath diff --git a/crates/mindcore-runtime/src/journal.rs b/crates/mindcore-runtime/src/journal.rs index f59657e..1bfc4b2 100644 --- a/crates/mindcore-runtime/src/journal.rs +++ b/crates/mindcore-runtime/src/journal.rs @@ -21,7 +21,12 @@ use serde_json::Value; /// and a parent whose resolution leaves the canonical root — a symlink below the root /// pointing outside it, at the destination or anywhere in between — is refused before /// anything is created or written. The root the publisher serves is the canonical root: a -/// host that passes a symlinked `root` publishes inside what it resolves to. +/// host that passes a symlinked `root` publishes inside what it resolves to. At the target +/// file itself no symlink can redirect the write: the bytes are written to a temporary file +/// created exclusively in the same directory and renamed over the target atomically — rename +/// replaces the directory entry, so a symlink at the target is replaced rather than followed. +/// Refusal applies instead to a symlink at the temporary name and, as above, to an escaping +/// parent chain. /// /// Durability: each target syncs its file, then every directory the publication created or /// wrote into beneath the root, deepest first, ending at the root itself — inclusive. The diff --git a/docs/quickstart.md b/docs/quickstart.md index 75e3436..64862e8 100644 --- a/docs/quickstart.md +++ b/docs/quickstart.md @@ -64,6 +64,13 @@ let created = ok( "create", ); +// The journal root is the host's: create it and make its creation entry durable before the +// first publish — the publisher refuses a missing root. +std::fs::create_dir_all("journal").expect("create the journal root"); +std::fs::File::open(".") + .and_then(|parent| parent.sync_all()) + .expect("sync the journal root's creation entry"); + let mind = ok(Mind::open(&store, &owner, &created.id).await, "open") .with_journal_publisher(journal_dir("journal")); ``` From f85d56f2147837c88e720abbe1534c0f7bd9be93 Mon Sep 17 00:00:00 2001 From: Tang Bohao Date: Thu, 26 Nov 2026 11:10:36 +0800 Subject: [PATCH 19/22] docs(knowledge): capture that a durability chain must not infer durability from existence - The journal publisher's sync set is a function of the target path, not of what the filesystem contains. - Bounds the contract at a host-owned durable root and normalises an empty parent to the current directory. - Recorded from the facade plan's B4/F-006/F-008 rounds. --- .../durability-chain-is-not-existence.md | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 .agents/knowledge/architecture-patterns/durability-chain-is-not-existence.md diff --git a/.agents/knowledge/architecture-patterns/durability-chain-is-not-existence.md b/.agents/knowledge/architecture-patterns/durability-chain-is-not-existence.md new file mode 100644 index 0000000..9621d66 --- /dev/null +++ b/.agents/knowledge/architecture-patterns/durability-chain-is-not-existence.md @@ -0,0 +1,25 @@ +# A durability chain must not infer durability from existence + +## Context + +The facade's journal publisher writes projection files, then fsyncs the file and the directory entries that name it, so a committed database row never points at bytes that a power loss can drop. The first version walked "the directories that do not exist yet" and fsynced each — and stopped at the first directory that already existed, on the assumption that existing means durable. It is not: a previous attempt can create a directory and fail before syncing it, so the next attempt sees it as existing and skips the entry that is still unpersisted. The same assumption broke a bare relative root (`journal_dir("journal")` or `./journal`), whose parent is the empty path, not the current directory. + +## Rule + +When persisting a path's ancestry, decide the sync set from the **path the caller names**, never from what the filesystem happens to contain. If existence is used at all, treat it as a hint that must be re-derived on every attempt, and make the set of synced entries a pure function of the target path. + +The strongest simple form is to bound the contract instead: require the durable ancestor to be the host's responsibility (a pre-existing root), refuse a missing one with the requirement named, and sync every entry the publisher itself creates beneath it. Then no retry can be weaker than the first attempt, because both attempts compute the same set. + +## Why + +Durability is a property of an operation, not of a directory entry. A directory that "exists" may have been created by a failed attempt that never synced its parent; the entry is visible to the next process and invisible to the storage after a crash. Code that reads existence as durability silently narrows its own guarantee, and the narrowing is invisible in tests because an ordinary test filesystem never loses anything. + +## How to apply + +- Compute the sync set from the target path (and a documented anchor), not from `exists()`. +- Prefer making the durable ancestor a declared host contract when the library cannot prove it. +- Refuse a missing root with an error that names the requirement, rather than creating it and hoping. +- Pin the invariant with a test that fails when the computation is replaced by an existence check; prove the test has teeth by temporarily restoring the old behaviour. +- Empty-path components are a separate trap: `parent()` of a single relative component is `""`, which is neither `None` nor the current directory. Normalise it explicitly. + +Seen in: `crates/mindcore-runtime/src/journal.rs`, the facade plan's B4/F-006/F-008 rounds. From c2ad0f9358a48a3fa20c19d8511b15dbd683c2b7 Mon Sep 17 00:00:00 2001 From: Tang Bohao Date: Thu, 26 Nov 2026 11:45:20 +0800 Subject: [PATCH 20/22] style: apply cargo fmt; specs: facade change obligations - cargo fmt --all output across the workspace (no behaviour change) - facade.md: add the required ## Change obligations section - specs README: link architecture/facade.md --- .agents/specs/README.md | 1 + .agents/specs/architecture/facade.md | 15 ++ .../mindcore-runtime/examples/mind_facade.rs | 28 ++- crates/mindcore-runtime/src/mind.rs | 47 ++-- crates/mindcore-runtime/tests/mind.rs | 205 +++++++++++++----- crates/mindcore-spoke/src/lib.rs | 13 +- crates/mindcore-spoke/src/workflows.rs | 7 +- crates/mindcore-sqlite/src/knowledge.rs | 32 +-- 8 files changed, 236 insertions(+), 112 deletions(-) diff --git a/.agents/specs/README.md b/.agents/specs/README.md index 50d3d2d..a8d900c 100644 --- a/.agents/specs/README.md +++ b/.agents/specs/README.md @@ -6,6 +6,7 @@ Current-state specifications of the Mindcore repository. Each page describes the | --- | --- | | [`architecture/mind-model.md`](architecture/mind-model.md) | The Mind model, record transitions, and the embedded SQLite persistence contract | | [`architecture/storage-ir-boundary.md`](architecture/storage-ir-boundary.md) | The storage-independent IR, its wire codec fidelity rule, and the repository transaction boundary | +| [`architecture/facade.md`](architecture/facade.md) | The in-process facade over a Mind: operations, transactions, and the review fold | | [`architecture/serving-principal-routing.md`](architecture/serving-principal-routing.md) | Per-principal route map, carrier admission and the recall knowledge slot | | [`architecture/serving-seam.md`](architecture/serving-seam.md) | Signed Connect serving: Knowledge face, workflow tools, and the store shape they require | | [`data/cognition-record-storage.md`](data/cognition-record-storage.md) | Per-record cognition storage, the carrier head, and its CAS/projection rules | diff --git a/.agents/specs/architecture/facade.md b/.agents/specs/architecture/facade.md index bbef2cf..be2de69 100644 --- a/.agents/specs/architecture/facade.md +++ b/.agents/specs/architecture/facade.md @@ -179,5 +179,20 @@ host that needs it embeds the adapter or the served surface directly. - `crates/mindcore-runtime/src/mind.rs` — the handle, its operations and the `review` fold. - `crates/mindcore-runtime/src/journal.rs` — `journal_dir`, the crate's one journal publisher. - `crates/mindcore-runtime/examples/mind_facade.rs` — the documented end-to-end example: + `cargo run --offline -p mindcore-runtime --example mind_facade`. - Tests: `crates/mindcore-runtime/tests/mind.rs`. + +## Change obligations + +- Adding, removing or renaming a facade operation, or changing what one composes, which + transaction it runs on or which grants it re-checks, updates the operations table and the + `Current state` narrative in the same change. +- Changing the `review` fold — staging, publication ordering, the `OUTCOME_UNCERTAIN` recovery + contract or settlement — updates § `The `review` fold` in the same change. +- Changing `journal_dir` confinement, durability or refusal behaviour updates the journal + paragraphs in the same change; changing what `open` caches or refuses updates § `The handle`. +- Changing `deliberate` subject handling or `cognition_read` derivation updates their own + sections in the same change. +- Moving a listed path or command updates `Where it lives` in the same change; weakening or + strengthening any invariant updates `Invariants` in the same change. diff --git a/crates/mindcore-runtime/examples/mind_facade.rs b/crates/mindcore-runtime/examples/mind_facade.rs index b661bb3..7b82dda 100644 --- a/crates/mindcore-runtime/examples/mind_facade.rs +++ b/crates/mindcore-runtime/examples/mind_facade.rs @@ -26,7 +26,9 @@ const SUBJECT: &str = "subj_wren"; fn ok(result: SpokeResult, step: &str) -> T { match result { SpokeResult::Ok(value) => value, - SpokeResult::Reject(reject) => panic!("{step} refused: {}: {}", reject.code, reject.message), + SpokeResult::Reject(reject) => { + panic!("{step} refused: {}: {}", reject.code, reject.message) + } } } @@ -39,9 +41,13 @@ async fn main() { let dir = tempfile::TempDir::new().expect("a scratch directory"); // Creating the scratch directory wrote an entry in its parent; the host makes that entry // durable before anything depends on it, exactly as it will for the journal root below. - std::fs::File::open(dir.path().parent().expect("the scratch directory has a parent")) - .and_then(|parent| parent.sync_all()) - .expect("sync the scratch directory's creation entry"); + std::fs::File::open( + dir.path() + .parent() + .expect("the scratch directory has a parent"), + ) + .and_then(|parent| parent.sync_all()) + .expect("sync the scratch directory's creation entry"); let store = MindStore::open(&dir.path().join("mind.db")) .await .expect("open the store"); @@ -82,9 +88,13 @@ async fn main() { std::fs::create_dir_all(&journal_root).expect("the host creates the journal root"); // The host, not the publisher, owns the root's creation entry: creating the root writes an // entry in its parent, and that entry is durable only once the parent is synced. - std::fs::File::open(journal_root.parent().expect("the journal root has a parent")) - .and_then(|parent| parent.sync_all()) - .expect("sync the journal root's creation entry"); + std::fs::File::open( + journal_root + .parent() + .expect("the journal root has a parent"), + ) + .and_then(|parent| parent.sync_all()) + .expect("sync the journal root's creation entry"); let mind = ok(Mind::open(&store, &owner, &created.id).await, "open") .with_journal_publisher(journal_dir(journal_root)); @@ -107,8 +117,8 @@ async fn main() { // 4. Review the candidate. The answer is the settled receipt: the fold — staging, // publication, settlement — is the handle's, and the caller never sees it. - let promote: Decision = serde_json::from_value(json!({ "action": "promote" })) - .expect("a promote decision"); + let promote: Decision = + serde_json::from_value(json!({ "action": "promote" })).expect("a promote decision"); let reviewed = ok( mind.review(&candidate_id, &promote, "rev-north-gate").await, "review", diff --git a/crates/mindcore-runtime/src/mind.rs b/crates/mindcore-runtime/src/mind.rs index b7b9c83..c41bf39 100644 --- a/crates/mindcore-runtime/src/mind.rs +++ b/crates/mindcore-runtime/src/mind.rs @@ -372,7 +372,9 @@ impl Mind { return written; } if let Err(error) = transaction.commit().await { - return uncertain(format!("knowledge write committed an unknown outcome: {error}")); + return uncertain(format!( + "knowledge write committed an unknown outcome: {error}" + )); } written } @@ -789,20 +791,20 @@ impl Mind { ) } }; - let mind_state = match mindcore_base::cognition::mind_state_value(&view, self.row.id.as_str()) - { - Ok(mind_state) => mind_state, - Err(error) => { - return reject( - SpokeRejectCode::InternalError, - format!( - "the mind state of {} cannot be projected: {error}", - self.row.carrier_entry_id - ), - "terminal", - ) - } - }; + let mind_state = + match mindcore_base::cognition::mind_state_value(&view, self.row.id.as_str()) { + Ok(mind_state) => mind_state, + Err(error) => { + return reject( + SpokeRejectCode::InternalError, + format!( + "the mind state of {} cannot be projected: {error}", + self.row.carrier_entry_id + ), + "terminal", + ) + } + }; SpokeResult::Ok(Some(Cognition { carrier_revision: revision, records: view.records, @@ -826,15 +828,16 @@ impl Mind { })) { Ok(holder) => holder, Err(error) => { - return retryable_internal(format!("the carrier reference does not decode: {error}")) + return retryable_internal(format!( + "the carrier reference does not decode: {error}" + )) } }; - let binding = MemoryWorkflowBinding::new(self.pool.clone(), false) - .with_carrier_collection( - self.row.id.as_str(), - &self.row.knowledge.collection, - &self.row.carrier_entry_id, - ); + let binding = MemoryWorkflowBinding::new(self.pool.clone(), false).with_carrier_collection( + self.row.id.as_str(), + &self.row.knowledge.collection, + &self.row.carrier_entry_id, + ); let workflows = SpiMindWorkflows::new(binding); let request = DeliberateRequest { space_id: self.row.id.as_str(), diff --git a/crates/mindcore-runtime/tests/mind.rs b/crates/mindcore-runtime/tests/mind.rs index 9ad4222..38759fd 100644 --- a/crates/mindcore-runtime/tests/mind.rs +++ b/crates/mindcore-runtime/tests/mind.rs @@ -2,24 +2,22 @@ //! live grants, the registry's own `NotFound` for a Mind the caller cannot see, and a frozen //! Mind opening because the handle acts on no status from the row. +use chrono::Utc; use mindcore_base::boundary::CallerId; +use mindcore_base::ids::SubjectId; use mindcore_base::ids::{mint, MindId, SpaceId}; -use mindcore_base::ir::{MemoryGrantRow, MemoryJournalRow}; use mindcore_base::ir::MemoryRepository; -use mindcore_base::ids::SubjectId; +use mindcore_base::ir::{MemoryGrantRow, MemoryJournalRow}; use mindcore_runtime::journal_dir; use mindcore_runtime::minds::{self, CreateMind}; use mindcore_runtime::{Capture, Deliberation, Mind, MindProviders, Recall}; use mindcore_spi::SpiError; use mindcore_sqlite::{MindStore, SqliteMemoryRepository}; -use chrono::Utc; use serde_json::{json, Map, Number, Value}; -use spoke_schemas::data::knowledge_entry::{ - KnowledgeEntryBody, KnowledgeEntryCanonicalName, -}; -use spoke_schemas::KnowledgeEntry; use spoke_operations::{SpokeReject, SpokeRejectCode, SpokeResult}; +use spoke_schemas::data::knowledge_entry::{KnowledgeEntryBody, KnowledgeEntryCanonicalName}; use spoke_schemas::memory_candidates_review_request::Decision; +use spoke_schemas::KnowledgeEntry; use std::sync::{mpsc, Arc}; use tempfile::TempDir; @@ -459,7 +457,10 @@ async fn a_refused_settle_answers_outcome_uncertain_and_leaves_the_intent_pendin // what registers the task in the pool's FIFO queue. let pending = std::future::poll_fn(|cx| { let polled = std::future::Future::poll(acquire.as_mut(), cx); - assert!(polled.is_pending(), "the one connection is still checked out"); + assert!( + polled.is_pending(), + "the one connection is still checked out" + ); std::task::Poll::Ready(()) }) .await; @@ -500,7 +501,6 @@ async fn a_refused_settle_answers_outcome_uncertain_and_leaves_the_intent_pendin ); } - /// The `OUTCOME_UNCERTAIN` recovery contract: a failure after the staging commit answers the /// uncertain outcome once, and a same-key repeat continues through the fold — publish, then /// settle — instead of answering the uncertain outcome again. The repeat settles the intent, @@ -537,7 +537,10 @@ async fn a_repeat_after_outcome_uncertain_continues_the_fold_and_settles() { tokio::pin!(acquire); std::future::poll_fn(|cx| { let polled = std::future::Future::poll(acquire.as_mut(), cx); - assert!(polled.is_pending(), "the one connection is still checked out"); + assert!( + polled.is_pending(), + "the one connection is still checked out" + ); std::task::Poll::Ready(()) }) .await; @@ -703,7 +706,10 @@ async fn the_public_publisher_publishes_a_nested_subtree_under_an_existing_root( .expect("publish beneath an existing root"); assert_eq!( std::fs::read_to_string( - root.join("deeply").join("nested").join("records").join("rec_nested.md") + root.join("deeply") + .join("nested") + .join("records") + .join("rec_nested.md") ) .expect("the published target"), "exact published bytes" @@ -743,7 +749,10 @@ async fn grant(store: &MindStore, space_id: &str, principal: &str, capabilities: space_id: SpaceId::new(space_id), subject_id: None, principal_id: CallerId::new(principal), - capabilities: capabilities.iter().map(|capability| capability.to_string()).collect(), + capabilities: capabilities + .iter() + .map(|capability| capability.to_string()) + .collect(), context_ids: Vec::new(), shared_access: false, expires_at: None, @@ -789,7 +798,9 @@ async fn knowledge_write_then_read_by_revision_answers_the_stored_entry() { "the list carries the written entry beside the carrier" ); assert!( - listed.iter().any(|entry| entry.entry_id == created.carrier_entry_id), + listed + .iter() + .any(|entry| entry.entry_id == created.carrier_entry_id), "the list reads the Mind's own collection, carrier included" ); } @@ -801,13 +812,19 @@ async fn a_stale_revision_refuses_stored_revision_stale() { let created = ok(minds::create(&store, &request(OWNER)).await); let handle = ok(Mind::open(&store, &owner, &created.id).await); - ok(handle.knowledge_put(entry("ke_fact", "fact one"), None).await); + ok(handle + .knowledge_put(entry("ke_fact", "fact one"), None) + .await); ok(handle .knowledge_put(entry("ke_fact", "fact two"), Some(1)) .await); assert_eq!( - reject_code(handle.knowledge_put(entry("ke_fact", "fact three"), Some(1)).await), + reject_code( + handle + .knowledge_put(entry("ke_fact", "fact three"), Some(1)) + .await + ), SpokeRejectCode::StoredRevisionStale, "a put against a moved revision refuses the store's own stale refusal" ); @@ -826,12 +843,20 @@ async fn a_caller_without_knowledge_write_is_refused_and_the_row_is_untouched() .await); let reader = CallerId::new("caller_reader"); - grant(&store, created.id.as_str(), "caller_reader", &["knowledge_read"]).await; + grant( + &store, + created.id.as_str(), + "caller_reader", + &["knowledge_read"], + ) + .await; let reader_handle = ok(Mind::open(&store, &reader, &created.id).await); - let refuse = reject_of(reader_handle - .knowledge_put(entry("ke_fact", "defaced"), Some(1)) - .await); + let refuse = reject_of( + reader_handle + .knowledge_put(entry("ke_fact", "defaced"), Some(1)) + .await, + ); assert_eq!( refuse.code, SpokeRejectCode::NotAuthorized, @@ -858,7 +883,13 @@ async fn a_caller_without_knowledge_read_reads_nothing() { .await); let writer = CallerId::new("caller_writer"); - grant(&store, created.id.as_str(), "caller_writer", &["knowledge_write"]).await; + grant( + &store, + created.id.as_str(), + "caller_writer", + &["knowledge_write"], + ) + .await; let writer_handle = ok(Mind::open(&store, &writer, &created.id).await); assert_eq!( @@ -1131,7 +1162,16 @@ async fn deliberate_without_a_space_wide_recall_grant_is_refused_and_writes_noth ) .await; let target = cognition_target(&created.carrier_entry_id); - let refuse = reject_of(deliberate(&store, &knowledge_only, &created.id, &target, Arc::new(SettlingReasoner)).await); + let refuse = reject_of( + deliberate( + &store, + &knowledge_only, + &created.id, + &target, + Arc::new(SettlingReasoner), + ) + .await, + ); assert_eq!( refuse.code, SpokeRejectCode::NotAuthorized, @@ -1154,7 +1194,16 @@ async fn an_unsettled_intent_in_another_subject_refuses_deliberate() { settle_never(&store, created.id.as_str(), "subj_other").await; let target = cognition_target(&created.carrier_entry_id); - let refuse = reject_of(deliberate(&store, &owner, &created.id, &target, Arc::new(SettlingReasoner)).await); + let refuse = reject_of( + deliberate( + &store, + &owner, + &created.id, + &target, + Arc::new(SettlingReasoner), + ) + .await, + ); assert_eq!(refuse.code, SpokeRejectCode::InternalError); let details = refuse.details.as_ref().expect("structured details"); assert_eq!( @@ -1182,7 +1231,16 @@ async fn a_verdict_citing_a_memory_record_is_refused() { let handle = ok(Mind::open(&store, &owner, &created.id).await); let target = cognition_target(&created.carrier_entry_id); - let refuse = reject_of(deliberate(&store, &owner, &created.id, &target, Arc::new(CitingReasoner)).await); + let refuse = reject_of( + deliberate( + &store, + &owner, + &created.id, + &target, + Arc::new(CitingReasoner), + ) + .await, + ); assert_eq!( refuse.code, SpokeRejectCode::InternalError, @@ -1279,11 +1337,17 @@ async fn a_space_level_verdict_settles_with_the_mind_context_and_derives_its_sta let created = ok(minds::create(&store, &request(OWNER)).await); let target = cognition_target(&created.carrier_entry_id); - let outcome = ok(deliberate(&store, &owner, &created.id, &target, Arc::new(PriorBasisReasoner)).await); + let outcome = ok(deliberate( + &store, + &owner, + &created.id, + &target, + Arc::new(PriorBasisReasoner), + ) + .await); let mind_state_version = match outcome { mindcore_spi::DeliberateOutcome::Settled { - mind_state_version, - .. + mind_state_version, .. } => mind_state_version, other => panic!("the auto-settled verdict must commit: {other:?}"), }; @@ -1368,7 +1432,11 @@ async fn a_settled_replay_survives_any_unsettled_intent_in_the_space() { let settled = ok(handle .review(&candidate_id, &promote(), "rev-settled-replay") .await); - assert_eq!(value_of(&settled)["status"], "committed", "the first review settles"); + assert_eq!( + value_of(&settled)["status"], + "committed", + "the first review settles" + ); // An unsettled intent for the same subject, as a crashed served absorb would leave one. settle_never(&store, created.id.as_str(), SUBJECT).await; @@ -1380,8 +1448,16 @@ async fn a_settled_replay_survives_any_unsettled_intent_in_the_space() { value_of(&settled), "the settled key replays beside the same subject's unsettled intent" ); - assert_eq!(count_records(&store.pool()).await, 1, "no second record is staged"); - assert_eq!(count_intents(&store.pool()).await, 2, "no second replay intent"); + assert_eq!( + count_records(&store.pool()).await, + 1, + "no second record is staged" + ); + assert_eq!( + count_intents(&store.pool()).await, + 2, + "no second replay intent" + ); // The same key also replays beside an intent of another subject in the same space. settle_never(&store, created.id.as_str(), "subj_elsewhere").await; @@ -1393,7 +1469,11 @@ async fn a_settled_replay_survives_any_unsettled_intent_in_the_space() { value_of(&settled), "the settled key replays beside another subject's unsettled intent" ); - assert_eq!(count_records(&store.pool()).await, 1, "still no second record"); + assert_eq!( + count_records(&store.pool()).await, + 1, + "still no second record" + ); } /// Only the replay bypasses the unsettled-intent withhold: a fresh review — a new key over a @@ -1421,7 +1501,10 @@ async fn a_fresh_review_is_refused_while_the_subjects_intent_is_unsettled() { "the withhold travels as the adapter's own refusal" ); assert_eq!( - reject.details.as_ref().and_then(|details| details.get("reason")), + reject + .details + .as_ref() + .and_then(|details| details.get("reason")), Some(&json!("UNRECONCILED")), "a fresh review is withheld while the subject's intent is unsettled: {reject:?}" ); @@ -1463,10 +1546,7 @@ async fn the_public_publisher_refuses_a_target_outside_its_root() { "content": "escape", })]); assert!(absolute.is_err(), "an absolute target is refused"); - assert!( - !escaped.exists(), - "nothing was written outside the root" - ); + assert!(!escaped.exists(), "nothing was written outside the root"); let parent = publisher(&[json!({ "path": "../escaped.md", @@ -1546,16 +1626,12 @@ async fn the_public_publisher_never_writes_through_a_preplaced_temporary_symlink let file = root.join(target_path); let parent = file.parent().expect("the target parent").to_path_buf(); std::fs::create_dir_all(&parent).expect("create the target parent"); - let temporary = parent.join(format!( - ".journal-{}-{:016x}.tmp", - std::process::id(), - { - use std::hash::{Hash, Hasher}; - let mut hasher = std::collections::hash_map::DefaultHasher::new(); - file.hash(&mut hasher); - hasher.finish() - } - )); + let temporary = parent.join(format!(".journal-{}-{:016x}.tmp", std::process::id(), { + use std::hash::{Hash, Hasher}; + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + file.hash(&mut hasher); + hasher.finish() + })); std::os::unix::fs::symlink(outside.join("victim.md"), &temporary) .expect("pre-place the temporary symlink"); @@ -1615,8 +1691,8 @@ async fn publication_blocks_no_executor_progress_and_commits_after_it_confirms() let (release, is_released) = tokio::sync::oneshot::channel::<()>(); let is_released = std::sync::Mutex::new(Some(is_released)); let parked_root = journal_root.clone(); - let parked = ok(Mind::open(&store, &owner, &created.id).await) - .with_journal_publisher(move |targets| { + let parked = + ok(Mind::open(&store, &owner, &created.id).await).with_journal_publisher(move |targets| { journal_dir(&parked_root)(targets)?; entered.send(()).expect("signal the publisher entered"); let receiver = is_released @@ -1629,15 +1705,16 @@ async fn publication_blocks_no_executor_progress_and_commits_after_it_confirms() }); let review = tokio::spawn(async move { - parked.review(&candidate_id, &promote(), "rev-offworker").await + parked + .review(&candidate_id, &promote(), "rev-offworker") + .await }); // Wait for the publisher's entry signal on a blocking thread — the receive itself is the // observed state: it completes exactly when the publisher is inside its flush, however the // scheduler gets there. - let entry = tokio::task::spawn_blocking(move || { - is_entered.recv().expect("the publisher entry signal") - }); + let entry = + tokio::task::spawn_blocking(move || is_entered.recv().expect("the publisher entry signal")); entry.await.expect("the entry signal arrived"); // The probe: spawned after the entry signal, a bare unit of executor work. Its completion @@ -1694,7 +1771,9 @@ async fn a_cancelled_review_keeps_the_transaction_until_the_publication_ends() { std::thread::spawn(move || { std::thread::sleep(std::time::Duration::from_secs(30)); if !disarm.load(std::sync::atomic::Ordering::SeqCst) { - eprintln!("TIMEOUT: the publication handshake never completed — a signal never arrived"); + eprintln!( + "TIMEOUT: the publication handshake never completed — a signal never arrived" + ); std::process::exit(2); } }); @@ -1715,8 +1794,8 @@ async fn a_cancelled_review_keeps_the_transaction_until_the_publication_ends() { let first_finished = Arc::new(std::sync::Mutex::new(false)); let finished_pub = first_finished.clone(); let parked_root = journal_root.clone(); - let parked = ok(Mind::open(&store, &owner, &created.id).await) - .with_journal_publisher(move |targets| { + let parked = + ok(Mind::open(&store, &owner, &created.id).await).with_journal_publisher(move |targets| { journal_dir(&parked_root)(targets)?; entered.send(()).expect("signal the publisher entered"); let receiver = is_released @@ -1731,14 +1810,15 @@ async fn a_cancelled_review_keeps_the_transaction_until_the_publication_ends() { let cancelled_id = candidate_id.clone(); let review = tokio::spawn(async move { - parked.review(&cancelled_id, &promote(), "rev-cancelled").await + parked + .review(&cancelled_id, &promote(), "rev-cancelled") + .await }); // Wait for the publisher's entry signal, then cancel. The receive itself is the observed // state: it completes exactly when the publisher is inside its flush. - let entry = tokio::task::spawn_blocking(move || { - is_entered.recv().expect("the publisher entry signal") - }); + let entry = + tokio::task::spawn_blocking(move || is_entered.recv().expect("the publisher entry signal")); entry.await.expect("the entry signal arrived"); review.abort(); @@ -1750,7 +1830,10 @@ async fn a_cancelled_review_keeps_the_transaction_until_the_publication_ends() { // holding it, never merely unscheduled. let witness_pool = store.pool(); let witness = tokio::spawn(async move { - let connection = witness_pool.acquire().await.expect("the witness acquisition"); + let connection = witness_pool + .acquire() + .await + .expect("the witness acquisition"); drop(connection); }); let sentinel = tokio::spawn(async {}); @@ -1896,7 +1979,9 @@ async fn cognition_read_reads_only_the_collection_of_the_admitted_mind() { }); let appended = mindcore_base::cognition::append_cognition_record(&second_carrier, poisoned) .expect("the poisoned record validates in its own carrier"); - let revision = second_carrier.revision.expect("a stored carrier has a revision"); + let revision = second_carrier + .revision + .expect("a stored carrier has a revision"); ok(second_handle.knowledge_put(appended, Some(revision)).await); // The first Mind's read is untouched by anything the second collection holds. diff --git a/crates/mindcore-spoke/src/lib.rs b/crates/mindcore-spoke/src/lib.rs index 9464088..ef60165 100644 --- a/crates/mindcore-spoke/src/lib.rs +++ b/crates/mindcore-spoke/src/lib.rs @@ -35,8 +35,8 @@ use spoke_schemas::Principal; use sqlx::{Sqlite, Transaction}; use mindcore_base::ids::{SpaceId, SubjectId}; -use mindcore_spi::SpiError; use mindcore_base::ir::{MemoryRepository, ReceiptFailure, ReceiptState, ReviewReceiptIr}; +use mindcore_spi::SpiError; use mindcore_sqlite::SqliteMemoryRepository; use crate::admission::Op; @@ -308,10 +308,13 @@ impl MemoryAdapter { subject_all: false, }; if !admission::covered(&grants, caller, space.as_str(), Utc::now(), &requirement) { - return Err(SpiError::Settlement(Reject::not_authorized(format!( - "principal {caller} holds no live {capability} grant in space {}", - space.as_str() - )).into_spoke())); + return Err(SpiError::Settlement( + Reject::not_authorized(format!( + "principal {caller} holds no live {capability} grant in space {}", + space.as_str() + )) + .into_spoke(), + )); } } Ok(()) diff --git a/crates/mindcore-spoke/src/workflows.rs b/crates/mindcore-spoke/src/workflows.rs index 5f4f25e..8c7db93 100644 --- a/crates/mindcore-spoke/src/workflows.rs +++ b/crates/mindcore-spoke/src/workflows.rs @@ -12,8 +12,7 @@ use async_trait::async_trait; use chrono::Utc; use serde_json::{json, Map, Value}; use spoke_operations::{ - knowledge_entry_visible_to_viewpoint, SpokeReject, SpokeRejectCode, - SpokeResult, + knowledge_entry_visible_to_viewpoint, SpokeReject, SpokeRejectCode, SpokeResult, }; use spoke_schemas::data::cognition::{CognitionReference, CognitionReferenceKind}; use spoke_schemas::data::memory_candidate::PlacementScope; @@ -44,7 +43,9 @@ use mindcore_sqlite::{ use crate::admission; use crate::reject::Reject; -use crate::{principal_id, MemoryAdapter, MemoryStage, Tx, KNOWLEDGE_READ, KNOWLEDGE_WRITE, RECALL}; +use crate::{ + principal_id, MemoryAdapter, MemoryStage, Tx, KNOWLEDGE_READ, KNOWLEDGE_WRITE, RECALL, +}; /// Publishes one intent's file targets and confirms them: `Ok(())` only when /// every target's exact bytes landed at its path. diff --git a/crates/mindcore-sqlite/src/knowledge.rs b/crates/mindcore-sqlite/src/knowledge.rs index bf3ec3a..f01d622 100644 --- a/crates/mindcore-sqlite/src/knowledge.rs +++ b/crates/mindcore-sqlite/src/knowledge.rs @@ -752,19 +752,25 @@ impl RoutedKnowledgeStore { SpokeResult::Ok(false) => return history_not_found(entity_id), SpokeResult::Reject(reject) => return SpokeResult::Reject(reject), } - let entry = - match read_entry_at_revision(&mut tx, &self.scope.collection, entity_id, revision).await { - SpokeResult::Ok(entry) => entry, - SpokeResult::Reject(reject) if reject.code == SpokeRejectCode::HistoryTruncated => { - return SpokeResult::Reject(reject) - } - SpokeResult::Reject(reject) - if reject.code == SpokeRejectCode::KnowledgeEntryNotFound => - { - return history_not_found(entity_id) - } - SpokeResult::Reject(reject) => return SpokeResult::Reject(reject), - }; + let entry = match read_entry_at_revision( + &mut tx, + &self.scope.collection, + entity_id, + revision, + ) + .await + { + SpokeResult::Ok(entry) => entry, + SpokeResult::Reject(reject) if reject.code == SpokeRejectCode::HistoryTruncated => { + return SpokeResult::Reject(reject) + } + SpokeResult::Reject(reject) + if reject.code == SpokeRejectCode::KnowledgeEntryNotFound => + { + return history_not_found(entity_id) + } + SpokeResult::Reject(reject) => return SpokeResult::Reject(reject), + }; // Disclosure is a payload property, so the live row's visibility says nothing about the // replayed payload: a revision whose own fields fall outside the admitted scope is the // same absence as a hidden live row. From 6589b999938dd83be2105e4697655f124e6ff41f Mon Sep 17 00:00:00 2001 From: Tang Bohao Date: Thu, 26 Nov 2026 13:03:38 +0800 Subject: [PATCH 21/22] clippy: use Option::unwrap_or; drop no-effect unit binding - mind.rs: replace manual unwrap_or match on observed_revision - tests/mind.rs: drop the unit-value rebind of the poll_fn result --- crates/mindcore-runtime/src/mind.rs | 9 +++------ crates/mindcore-runtime/tests/mind.rs | 3 +-- 2 files changed, 4 insertions(+), 8 deletions(-) diff --git a/crates/mindcore-runtime/src/mind.rs b/crates/mindcore-runtime/src/mind.rs index c41bf39..b78b8ad 100644 --- a/crates/mindcore-runtime/src/mind.rs +++ b/crates/mindcore-runtime/src/mind.rs @@ -518,12 +518,9 @@ impl Mind { } } }; - let revision = match observed_revision { - Some(revision) => revision, - // No row at all: stage at revision 1, the candidate's fresh-work value — - // `review_candidate` answers its own `NotFound` for a candidate that never existed. - None => 1, - }; + // No row at all: revision 1, the candidate's fresh-work value — + // `review_candidate` answers its own `NotFound` for a candidate that never existed. + let revision = observed_revision.unwrap_or(1); // 2. Stage on the same transaction. The adapter's dedup probe keys on // (space, requester, operation, idempotency_key) and digests the whole payload, so // a same-key replay must rebuild a byte-identical request to reach the recorded diff --git a/crates/mindcore-runtime/tests/mind.rs b/crates/mindcore-runtime/tests/mind.rs index 38759fd..9caf40a 100644 --- a/crates/mindcore-runtime/tests/mind.rs +++ b/crates/mindcore-runtime/tests/mind.rs @@ -455,7 +455,7 @@ async fn a_refused_settle_answers_outcome_uncertain_and_leaves_the_intent_pendin // One poll with a no-op waker: the future must be pending because the staging // transaction still holds the pool's one connection, and this first poll is // what registers the task in the pool's FIFO queue. - let pending = std::future::poll_fn(|cx| { + std::future::poll_fn(|cx| { let polled = std::future::Future::poll(acquire.as_mut(), cx); assert!( polled.is_pending(), @@ -464,7 +464,6 @@ async fn a_refused_settle_answers_outcome_uncertain_and_leaves_the_intent_pendin std::task::Poll::Ready(()) }) .await; - let _ = pending; registered.send(()).expect("signal the registration"); let mut connection = acquire.await.expect("the one connection"); sqlx::query("UPDATE memory_journal SET state = 'deferred'") From 238063145e986620d50698ca971d4fa195edd76f Mon Sep 17 00:00:00 2001 From: Tang Bohao Date: Thu, 26 Nov 2026 13:42:22 +0800 Subject: [PATCH 22/22] fix(review): journal sync chain, recall wire budget, capture validation order MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - journal.rs: compute the durability sync chain from the target's resolved parent up to the canonical root — an in-root symlink no longer skips the real intermediate directories (PR #55 thread 4703486448) - mind.rs: Recall::max_items is non-optional u64 — the wire budget requires the member, so every recall the facade sends is a valid wire request; regression test for the minimal budget shape (thread 4703518092) - mind.rs: capture validates the adapter stage as Ready before the commit; a post-commit decode anomaly answers uncertain, not retryable (thread 4703518100) - mind.rs + facade spec: state knowledge_list's 512-entry bounded contract instead of pagination (thread 4703486519) --- .agents/specs/architecture/facade.md | 9 ++-- .../mindcore-runtime/examples/mind_facade.rs | 2 +- crates/mindcore-runtime/src/journal.rs | 31 ++++++++----- crates/mindcore-runtime/src/mind.rs | 43 ++++++++++++++----- crates/mindcore-runtime/tests/mind.rs | 38 +++++++++++++++- 5 files changed, 96 insertions(+), 27 deletions(-) diff --git a/.agents/specs/architecture/facade.md b/.agents/specs/architecture/facade.md index be2de69..6ba9d24 100644 --- a/.agents/specs/architecture/facade.md +++ b/.agents/specs/architecture/facade.md @@ -34,7 +34,7 @@ with the binding's and the workflow's own refusals. | `recall(&Recall)` | the memory adapter's `recall` | one read transaction, rolled back | the adapter's own, over the caller-named selection | | `knowledge_get(entry_id, revision)` | `read_entry`, or `read_entry_at_revision` when a revision is named, on the row's collection | one read transaction, rolled back | space-wide `knowledge_read` | | `knowledge_put(entry, expected)` | `write_entry` — the one cognition validation boundary — on the row's collection | one `BEGIN IMMEDIATE`, committed | space-wide `knowledge_write` | -| `knowledge_list()` | `list_entries_in` on the row's collection | one read transaction, rolled back | space-wide `knowledge_read` | +| `knowledge_list()` | `list_entries_in` on the row's collection — bounded: over 512 live entries the store's `COLLECTION_OVER_CAPACITY` answers, and the facade offers no pagination | one read transaction, rolled back | space-wide `knowledge_read` | | `cognition_read()` | the carrier `read_entry` on the row's collection, derived in the facade; nothing persisted | one read transaction, rolled back | space-wide `knowledge_read` | | `deliberate(&Deliberation)` | `SpiMindWorkflows::deliberate` with no subject, the row's carrier as holder and the Mind's id as assessment context | the workflow's own | space-wide `recall`, with the space-level withhold | @@ -97,8 +97,11 @@ file itself no symlink can redirect the write: the bytes are written to a tempor created exclusively in the same directory and renamed over the target atomically, so a symlink at the target is replaced rather than followed — refusal applies instead to a symlink at the temporary name. Durability syncs the target's file, then every directory beneath the root the -publication created or wrote into, deepest first, ending at the root itself — a pure function -of the target's path, so a retry can never be weaker than the attempt that failed. Syncing a +publication created or wrote into, deepest first, ending at the canonical root itself — the +chain is computed from the target's resolved parent, because a symlink inside the root can +redirect the write and only the resolved chain carries the real parent of every dirtied entry; +a pure function of the target's path and the tree's symlinks, so a retry can never be weaker +than the attempt that failed. Syncing a directory opens it for reading, so the host must grant read on the root and everything beneath it; ancestors above it need only traversal — a write-only journal root cannot be published, because the sync that must precede settlement would be refused for a reason the write itself diff --git a/crates/mindcore-runtime/examples/mind_facade.rs b/crates/mindcore-runtime/examples/mind_facade.rs index 7b82dda..6bcbf29 100644 --- a/crates/mindcore-runtime/examples/mind_facade.rs +++ b/crates/mindcore-runtime/examples/mind_facade.rs @@ -133,7 +133,7 @@ async fn main() { let recall = Recall { subject: SUBJECT, selection: &selection, - max_items: Some(10), + max_items: 10, max_bytes: None, query: None, cursor: None, diff --git a/crates/mindcore-runtime/src/journal.rs b/crates/mindcore-runtime/src/journal.rs index 1bfc4b2..9bf207d 100644 --- a/crates/mindcore-runtime/src/journal.rs +++ b/crates/mindcore-runtime/src/journal.rs @@ -29,12 +29,15 @@ use serde_json::Value; /// parent chain. /// /// Durability: each target syncs its file, then every directory the publication created or -/// wrote into beneath the root, deepest first, ending at the root itself — inclusive. The -/// chain is a pure function of the target's path, never of which directories happen to exist, -/// so a retry after a publication that failed between creating directories and syncing them -/// syncs the same chain as the attempt that failed. The root's own creation entry is the -/// host's and never the publisher's to sync: the host established it durable before the first -/// publication, which is exactly why the publisher requires the root to exist. +/// wrote into beneath the root, deepest first, ending at the canonical root itself — +/// inclusive. The chain is computed from the target's *resolved* parent: a symlink inside the +/// root can redirect the write, and only the resolved chain carries the real parent of every +/// entry the publication dirtied. The chain is a pure function of the target's path and the +/// tree's symlinks, never of which directories happen to exist, so a retry after a +/// publication that failed between creating directories and syncing them syncs the same +/// chain as the attempt that failed. The root's own creation entry is the host's and never +/// the publisher's to sync: the host established it durable before the first publication, +/// which is exactly why the publisher requires the root to exist. /// /// Permission requirement: syncing a directory opens it for reading, which POSIX refuses for /// a search-only directory, so the host must grant read on `root` and everything beneath it. @@ -227,10 +230,16 @@ pub fn journal_dir( })?; // Durability, not visibility: the write must reach the medium before the caller // may settle the intent. The temporary's contents were synced before the rename; - // what remains is the directory entries: the rename itself, and every directory the - // publication created or wrote into beneath the root, deepest first, ending at the - // root. - let mut cursor = Some(parent.clone()); + // what remains is the directory entries. The chain is computed from the *resolved* + // parent, not the lexical one: a symlink inside the root can redirect the target + // (`root/records` → `root/backing/nested`), and walking the lexical spelling's + // `parent()` would sync the resolved directory and the root but skip the real + // intermediate (`backing`) whose entry names `nested`. Parentage is a real-tree + // relation, so canonicalizing the parent and walking up to the canonical root + // syncs exactly the directories whose entries carry what the publication created + // or wrote into — a symlink never re-parents an entry, so the resolved chain is + // the complete one, whether or not any component was a symlink. + let mut cursor = Some(resolved.clone()); while let Some(directory) = cursor { std::fs::File::open(&directory) .and_then(|directory| directory.sync_all()) @@ -240,7 +249,7 @@ pub fn journal_dir( directory.display() ))) })?; - if directory == root { + if directory == canonical_root { break; } cursor = directory.parent().map(Path::to_path_buf); diff --git a/crates/mindcore-runtime/src/mind.rs b/crates/mindcore-runtime/src/mind.rs index b78b8ad..f324d68 100644 --- a/crates/mindcore-runtime/src/mind.rs +++ b/crates/mindcore-runtime/src/mind.rs @@ -83,7 +83,9 @@ pub struct Recall<'a> { pub subject: &'a str, /// The §6.12 read selection member (`{"mode": ...}`), exactly as the wire carries it. pub selection: &'a Value, - pub max_items: Option, + /// At least one, at most one page: the wire's `budget` requires the member, so the + /// facade carries it non-optional — every recall the facade sends is a valid wire request. + pub max_items: u64, pub max_bytes: Option, pub query: Option<&'a str>, pub cursor: Option<&'a str>, @@ -232,23 +234,38 @@ impl Mind { .adapter .capture(&mut transaction, &principal(&self.caller), request) .await; - if stage.is_reject() { - drop(transaction); - return ready(stage); - } + let body = match stage { + // Capture never journals: a non-Ready stage is a composition defect, answered + // before any state changes — nothing has committed, so the retry class holds. + SpokeResult::Ok(MemoryStage::Ready(body)) => body, + SpokeResult::Ok(unexpected) => { + drop(transaction); + return retryable_internal(format!( + "the adapter answered an unexpected stage: {unexpected:?}" + )); + } + SpokeResult::Reject(reject) => { + drop(transaction); + return SpokeResult::Reject(reject); + } + }; if let Err(error) = transaction.commit().await { return uncertain(format!("capture committed an unknown outcome: {error}")); } - ready(stage) + // Past the commit a malformed body is no longer retryable: rows may be durable. + match serde_json::from_value(body) { + Ok(response) => SpokeResult::Ok(response), + Err(error) => uncertain(format!( + "the adapter's committed response does not match its schema: {error}" + )), + } } /// Recall this Mind's live records: the adapter's `recall` over one read transaction, /// rolled back after the read. pub async fn recall(&self, recall: &Recall<'_>) -> SpokeResult { let mut budget = Map::new(); - if let Some(max_items) = recall.max_items { - budget.insert("max_items".to_string(), json!(max_items)); - } + budget.insert("max_items".to_string(), json!(recall.max_items)); if let Some(max_bytes) = recall.max_bytes { budget.insert("max_bytes".to_string(), json!(max_bytes)); } @@ -379,8 +396,12 @@ impl Mind { written } - /// Every entry of this Mind's collection: `knowledge_read` admitted on one read - /// transaction, then the store's `list_entries_in` on it, rolled back after the read. + /// Every entry of this Mind's collection, bounded: `knowledge_read` admitted on one read + /// transaction, then the store's `list_entries_in` on it, rolled back after the read. The + /// list shares the served face's 512-entry bound — a Mind holding more live entries + /// answers the store's `COLLECTION_OVER_CAPACITY` refusal. The facade is the convenience + /// surface of exactly that bounded list and offers no pagination: a host whose Mind + /// outgrows the bound embeds the store layer directly. pub async fn knowledge_list(&self) -> SpokeResult> { let mut transaction = match self.pool.begin().await { Ok(transaction) => transaction, diff --git a/crates/mindcore-runtime/tests/mind.rs b/crates/mindcore-runtime/tests/mind.rs index 9caf40a..9b0894a 100644 --- a/crates/mindcore-runtime/tests/mind.rs +++ b/crates/mindcore-runtime/tests/mind.rs @@ -148,7 +148,7 @@ fn recall_all() -> (Recall<'static>, Value) { Recall { subject: SUBJECT, selection, - max_items: Some(10), + max_items: 10, max_bytes: None, query: None, cursor: None, @@ -297,6 +297,42 @@ async fn capture_review_then_recall_returns_the_record_for_the_named_subject() { ); } +#[tokio::test] +async fn a_recall_with_only_max_items_and_no_other_budget_fields_is_a_valid_wire_request() { + let (dir, store) = fixture().await; + let owner = CallerId::new(OWNER); + let created = ok(minds::create(&store, &request(OWNER)).await); + ensure_subject(&store, created.id.as_str()).await; + let handle = ok(Mind::open(&store, &owner, &created.id).await) + .with_journal_publisher(journal_dir(dir.path())); + capture_candidate(&handle, "cap-min-budget", "a plain note").await; + + // The regression the wire contract pins: a recall carrying neither query, cursor nor + // max_bytes — the minimal budget shape — must decode as a valid wire request and answer + // a page, not a validation refusal. `max_items` is non-optional on the facade exactly + // because the wire requires the member. + let (minimal, _) = recall_all(); + let page = value_of(&ok(handle.recall(&minimal).await)); + assert!( + page["records"].is_array(), + "the minimal budget answers a records page: {page}" + ); + + // One item bounds the page to exactly one record even though more exist. + capture_candidate(&handle, "cap-min-budget-two", "a second note").await; + let bounded = Recall { + max_items: 1, + ..recall_all().0 + }; + let page = value_of(&ok(handle.recall(&bounded).await)); + let records = page["records"].as_array().expect("a records page"); + assert!( + records.len() <= 1, + "max_items bounds the page: {}", + records.len() + ); +} + #[tokio::test] async fn a_refused_publication_leaves_nothing_staged_and_the_same_key_then_settles() { let (dir, store) = fixture().await;