From 2e26e480c11d3b34234d2fd624b1aee8a2c68ba8 Mon Sep 17 00:00:00 2001 From: Tang Bohao Date: Thu, 26 Nov 2026 11:37:59 +0800 Subject: [PATCH 01/27] feat(serving): admit a Mind before every existence check, and list only Minds MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit admission::admit_mind replaces the first space lookup in authorize and in the seven read paths: the caller's grant rows first, then the space row, and no live grant or no space row answers one byte-equal NOT_AUTHORIZED with no details, so an unknown, an ungranted and a frozen-ungranted Mind are indistinguishable. memory.spaces.list takes its set from the registry's join over the caller's transaction — only Minds the principal holds a live grant in, in id order, a frozen one included, a space with no registry row excluded — with the wire shape unchanged. Refs I-000136 --- crates/mindcore-spoke/src/admission.rs | 33 ++- crates/mindcore-spoke/src/content.rs | 28 +- crates/mindcore-spoke/src/control.rs | 19 +- crates/mindcore-spoke/src/reject.rs | 21 +- crates/mindcore-spoke/tests/memory_adapter.rs | 256 +++++++++++++++++- crates/mindcore-spoke/tests/workflows.rs | 5 +- crates/mindcore-sqlite/src/minds.rs | 39 +++ crates/mindcore-sqlite/tests/embed_parity.rs | 23 +- .../tests/spaces_list_query_count.rs | 28 +- 9 files changed, 403 insertions(+), 49 deletions(-) diff --git a/crates/mindcore-spoke/src/admission.rs b/crates/mindcore-spoke/src/admission.rs index 666e11f8..84369f76 100644 --- a/crates/mindcore-spoke/src/admission.rs +++ b/crates/mindcore-spoke/src/admission.rs @@ -208,6 +208,35 @@ pub(crate) fn candidate_requirement<'a>( } } +/// Mind admission, run before every existence check: the caller's grant rows +/// first, then the space row. No live grant for this principal and no space +/// row answer the same fixed `NOT_AUTHORIZED` with no details, so an unknown +/// Mind, a frozen one the caller holds no grant in and an unadmitted one are +/// one answer, and nothing the refusal carries says which case the caller hit. +/// The registry is not consulted here: a space written before it is still a +/// space to `memory.*`; the registry gates only `memory.spaces.list` and the +/// Mind-level reads. +pub(crate) async fn admit_mind( + repository: &SqliteMemoryRepository, + tx: &mut Tx<'_>, + principal: &str, + space: &SpaceId, +) -> AResult<(Vec, MemorySpaceRow)> { + let rows = grants(repository, tx, space).await?; + let now = Utc::now(); + let admitted = rows + .iter() + .any(|row| row.principal_id.as_str() == principal && live_grant(row, now)); + if !admitted { + return Err(Reject::admission_refusal()); + } + let row = match repository.space(tx, space).await? { + Some(row) => row, + None => return Err(Reject::admission_refusal()), + }; + Ok((rows, row)) +} + pub(crate) async fn space( repository: &SqliteMemoryRepository, tx: &mut Tx<'_>, @@ -435,8 +464,8 @@ pub(crate) async fn authorize( admission: &Admission<'_>, now: DateTime, ) -> AResult> { - space(repository, tx, admission.space).await?; - let rows = grants(repository, tx, admission.space).await?; + let (rows, _space) = + admit_mind(repository, tx, admission.principal, admission.space).await?; let wire = wire_grants(&rows)?; let space_id = admission.space.as_str(); match &admission.coverage { diff --git a/crates/mindcore-spoke/src/content.rs b/crates/mindcore-spoke/src/content.rs index a651c127..88d39a8d 100644 --- a/crates/mindcore-spoke/src/content.rs +++ b/crates/mindcore-spoke/src/content.rs @@ -339,8 +339,8 @@ impl MemoryAdapter { None => None, }; let now = Utc::now(); - admission::space(&self.repository, tx, &space).await?; - let rows = admission::grants(&self.repository, tx, &space).await?; + let (rows, _space) = + admission::admit_mind(&self.repository, tx, principal_id, &space).await?; let wire_grants = admission::wire_grants(&rows)?; let base = GrantRequirement { capability: "review", @@ -439,13 +439,13 @@ impl MemoryAdapter { let principal_id = principal_id(principal); let space = SpaceId::new(request.space_id.to_string()); let candidate_id = request.candidate_id.to_string(); - admission::space(&self.repository, tx, &space).await?; + let (rows, _space) = + admission::admit_mind(&self.repository, tx, principal_id, &space).await?; let Some(head) = admission::candidate_head(&self.repository, tx, &space, candidate_id.as_str()).await? else { return Err(Reject::not_found(format!("candidate {candidate_id}"))); }; - let rows = admission::grants(&self.repository, tx, &space).await?; let wire_grants = admission::wire_grants(&rows)?; let subject_id = head.subject_id.as_str(); if !admission::covered( @@ -691,8 +691,8 @@ impl MemoryAdapter { let principal_id = principal_id(principal); let space = SpaceId::new(request.space_id.to_string()); let record_id = request.record_id.to_string(); - admission::space(&self.repository, tx, &space).await?; - let rows = admission::grants(&self.repository, tx, &space).await?; + let (rows, _space) = + admission::admit_mind(&self.repository, tx, principal_id, &space).await?; let wire_grants = admission::wire_grants(&rows)?; let now = Utc::now(); let Some(head) = @@ -770,8 +770,8 @@ impl MemoryAdapter { let kinds = request.kinds.clone(); let include_tombstoned = request.include_tombstoned; let now = Utc::now(); - admission::space(&self.repository, tx, &space).await?; - let rows = admission::grants(&self.repository, tx, &space).await?; + let (rows, _space) = + admission::admit_mind(&self.repository, tx, principal_id, &space).await?; let wire_grants = admission::wire_grants(&rows)?; let list = admission::covered( &wire_grants, @@ -1298,8 +1298,8 @@ impl MemoryAdapter { let subject_id = request.subject_id.to_string(); let (placement, filter) = read_selection(object)?; let now = Utc::now(); - admission::space(&self.repository, tx, &space).await?; - let rows = admission::grants(&self.repository, tx, &space).await?; + let (rows, _space) = + admission::admit_mind(&self.repository, tx, principal_id, &space).await?; let wire_grants = admission::wire_grants(&rows)?; if !admission::covered( &wire_grants, @@ -1444,8 +1444,8 @@ impl MemoryAdapter { let principal_id = principal_id(principal); let space = SpaceId::new(request.space_id.to_string()); let subject_id = request.subject_id.to_string(); - admission::space(&self.repository, tx, &space).await?; - let rows = admission::grants(&self.repository, tx, &space).await?; + let (rows, _space) = + admission::admit_mind(&self.repository, tx, principal_id, &space).await?; if !admission::profile_visible( &rows, principal_id, @@ -1621,8 +1621,8 @@ impl MemoryAdapter { let principal_id = principal_id(principal); let space = SpaceId::new(request.space_id.to_string()); let receipt_id = request.receipt_id.to_string(); - admission::space(&self.repository, tx, &space).await?; - let rows = admission::grants(&self.repository, tx, &space).await?; + let (rows, _space) = + admission::admit_mind(&self.repository, tx, principal_id, &space).await?; let wire_grants = admission::wire_grants(&rows)?; let now = Utc::now(); let participates = rows.iter().any(|row| { diff --git a/crates/mindcore-spoke/src/control.rs b/crates/mindcore-spoke/src/control.rs index ccab2406..03599790 100644 --- a/crates/mindcore-spoke/src/control.rs +++ b/crates/mindcore-spoke/src/control.rs @@ -86,15 +86,16 @@ impl MemoryAdapter { } } let principal_id = principal_id(principal); - let now = Utc::now(); - let mut visible_space_ids: HashSet = HashSet::new(); - self.repository - .scan_principal_grants(tx, principal_id, |grant| { - if admission::live_grant(&grant, now) { - visible_space_ids.insert(grant.space_id.as_str().to_string()); - } - }) - .await?; + // The visible set is the Minds the principal holds a live grant in, + // read through the registry's join on this transaction: a space with + // no registry row is not listed, and a frozen Mind still is. + let ids = match mindcore_sqlite::minds::visible_mind_ids(tx, principal_id).await { + spoke_operations::SpokeResult::Ok(ids) => ids, + spoke_operations::SpokeResult::Reject(_) => { + return Err(Reject::internal("mind visibility read failed")); + } + }; + let visible_space_ids: HashSet = ids.into_iter().collect(); let visible_spaces: Vec<&str> = visible_space_ids.iter().map(String::as_str).collect(); let grant_revisions = self .repository diff --git a/crates/mindcore-spoke/src/reject.rs b/crates/mindcore-spoke/src/reject.rs index 404ba1db..22aa5a08 100644 --- a/crates/mindcore-spoke/src/reject.rs +++ b/crates/mindcore-spoke/src/reject.rs @@ -49,6 +49,19 @@ impl Reject { Self::terminal(SpokeRejectCode::NotFound, format!("{what} not found")) } + /// Mind admission: one `NOT_AUTHORIZED` an unknown, a frozen-ungranted and + /// an unadmitted Mind share, byte-equal in the three cases. It carries no + /// details at all — not even `retry_class` — because the refusal must not + /// disclose whether the named Mind exists, and its fixed shape is what pins + /// that indistinguishability. + pub(crate) fn admission_refusal() -> Self { + Self { + code: SpokeRejectCode::NotAuthorized, + message: "the caller is not admitted to the named mind".to_string(), + details: Map::new(), + } + } + pub(crate) fn not_authorized(message: impl Into) -> Self { Self::terminal(SpokeRejectCode::NotAuthorized, message) } @@ -97,7 +110,13 @@ impl Reject { SpokeReject { code: self.code, message: self.message, - details: Some(self.details), + // The admission refusal carries nothing, and an empty object is + // still a carrier: `None` is the no-details answer on the wire. + details: if self.details.is_empty() { + None + } else { + Some(self.details) + }, } } diff --git a/crates/mindcore-spoke/tests/memory_adapter.rs b/crates/mindcore-spoke/tests/memory_adapter.rs index cd2610bf..6b39a964 100644 --- a/crates/mindcore-spoke/tests/memory_adapter.rs +++ b/crates/mindcore-spoke/tests/memory_adapter.rs @@ -229,6 +229,20 @@ fn reject(result: &SpokeResult) -> &SpokeReject { } } +/// The Mind-admission refusal carries no details — no `retry_class`, no +/// target — so it is asserted by its own shape, never through `retry_class`. +fn assert_admission_refusal(reject: &SpokeReject, context: &str) { + assert_eq!(reject.code, SpokeRejectCode::NotAuthorized, "{context}"); + assert_eq!( + reject.message, "the caller is not admitted to the named mind", + "{context}: the fixed admission message" + ); + assert!( + reject.details.is_none(), + "{context}: the admission refusal carries no details: {reject:?}" + ); +} + fn retry_class(reject: &SpokeReject) -> &str { reject .details @@ -419,8 +433,7 @@ async fn unauthorized_capture_rejects_without_an_effect() { .capture(&mut tx, &principal(STRANGER), request) .await; let reject = reject(&result); - assert_eq!(reject.code, SpokeRejectCode::NotAuthorized); - assert_eq!(retry_class(reject), "terminal"); + assert_admission_refusal(reject, "a principal with no grant in the space is not admitted"); assert_eq!(harness.count(&mut tx, "memory_candidates").await, 0); assert_eq!(harness.count(&mut tx, "memory_receipts").await, 0); tx.rollback().await.expect("rollback"); @@ -708,10 +721,10 @@ async fn expired_grant_is_not_participation() { .await; let existing = reject(&existing); let unknown = reject(&unknown); - assert_eq!(existing.code, SpokeRejectCode::NotAuthorized); - assert_eq!(retry_class(existing), "terminal"); + assert_admission_refusal(existing, "an expired grant is no admission"); assert_eq!(existing.code, unknown.code); assert_eq!(existing.message, unknown.message); + assert_eq!(existing.details, unknown.details); tx.rollback().await.expect("rollback"); } @@ -1012,8 +1025,7 @@ async fn grant_expiry_is_compared_as_an_instant() { ) .await; let refusal = reject(&expired_probe); - assert_eq!(refusal.code, SpokeRejectCode::NotAuthorized); - assert_eq!(retry_class(refusal), "terminal"); + assert_admission_refusal(refusal, "an expired grant is no admission"); let own = ready( adapter @@ -1137,8 +1149,7 @@ async fn revoked_grant_denies_subject_and_profile_reads() { ) .await; let refusal = reject(&profile); - assert_eq!(refusal.code, SpokeRejectCode::NotAuthorized); - assert_eq!(retry_class(refusal), "terminal"); + assert_admission_refusal(refusal, "a revoked grant is no admission"); let subject = ready( adapter @@ -4334,8 +4345,7 @@ async fn concealment_and_authorization_precede_the_withhold_probe() { ) .await; let refusal = reject(&records); - assert_eq!(refusal.code, SpokeRejectCode::NotAuthorized); - assert_eq!(retry_class(refusal), "terminal"); + assert_admission_refusal(refusal, "a caller with no grant is refused before any existence check"); tx.rollback().await.expect("rollback"); } @@ -4445,3 +4455,229 @@ async fn receipts_poll_serves_regardless_of_unsettled_intents() { assert_eq!(retry_class(refusal), "terminal"); tx.rollback().await.expect("rollback"); } + +/// Mind admission (one served surface serves many Minds): an unknown Mind, an +/// ungranted one and a frozen one the caller holds no grant in answer one +/// byte-equal `NOT_AUTHORIZED` with no details — before any coverage check — +/// on every read path whose first lookup was the space row. A granted caller +/// in the frozen Mind is still served a read, because reads are not +/// freeze-gated. +#[tokio::test] +async fn unknown_ungranted_and_frozen_minds_answer_one_refusal() { + let harness = Harness::open().await; + let adapter = MemoryAdapter::new(true); + for (space, status) in [("sp_ungranted", "active"), ("sp_frozen", "frozen")] { + sqlx::query( + "INSERT INTO memory_spaces \ + (space_id, display_name, authority_host_id, authority_generation, status, \ + revision, created_at) \ + VALUES (?, NULL, 'host_1', 1, ?, 1, ?)", + ) + .bind(space) + .bind(status) + .bind(NOW) + .execute(&harness.pool) + .await + .expect("seed space"); + } + + let mut envelopes: Vec<(String, serde_json::Value)> = Vec::new(); + for space in ["sp_absent", "sp_ungranted", "sp_frozen"] { + let mut tx = harness.begin().await; + for (op, result) in guarded_reads(&adapter, &mut tx, space, SUBJECT, "cnd_any").await { + // The reflection reads are not Mind-admission paths: they answer + // through their own space lookup and are out of this envelope. + if op.starts_with("memory.reflections") { + continue; + } + let refusal = reject(&result); + assert_eq!( + refusal.code, + SpokeRejectCode::NotAuthorized, + "{op} in {space} answers the admission refusal" + ); + assert!( + refusal.details.is_none(), + "{op} in {space} carries no details: {refusal:?}" + ); + envelopes.push(( + format!("{op} in {space}"), + serde_json::json!(refusal.message), + )); + } + // `memory.receipts.get` is the seventh read path `guarded_reads` does + // not carry. + let receipts = adapter + .get_receipt( + &mut tx, + &principal(PRINCIPAL), + json!({ "space_id": space, "receipt_id": "rct_any" }), + ) + .await; + let refusal = reject(&receipts); + assert_eq!(refusal.code, SpokeRejectCode::NotAuthorized, "receipts in {space}"); + assert!( + refusal.details.is_none(), + "receipts in {space} carries no details: {refusal:?}" + ); + envelopes.push((format!("receipts in {space}"), serde_json::json!(refusal.message))); + // The mutation path enters admission through `authorize`. + let mutation = adapter + .capture( + &mut tx, + &principal(PRINCIPAL), + json!({ + "space_id": space, + "subject_id": SUBJECT, + "capture_scope": { "visibility": "shared" }, + "content": { "text": "a capture into a mind the caller cannot see" }, + "idempotency_key": format!("cap-admit-{space}") + }), + ) + .await; + let refusal = reject(&mutation); + assert_eq!(refusal.code, SpokeRejectCode::NotAuthorized, "capture in {space}"); + assert!( + refusal.details.is_none(), + "capture in {space} carries no details: {refusal:?}" + ); + envelopes.push((format!("capture in {space}"), serde_json::json!(refusal.message))); + assert_eq!( + harness.count(&mut tx, "memory_candidates").await, + 0, + "nothing is staged in {space}" + ); + tx.rollback().await.expect("rollback"); + } + let messages: std::collections::HashSet<&serde_json::Value> = + envelopes.iter().map(|(_, value)| value).collect(); + assert_eq!( + messages.len(), + 1, + "every refusal in every case is byte-equal: {envelopes:?}" + ); + + // A granted caller in the frozen Mind is served a read: freeze gates + // writes, never reads. + sqlx::query( + "INSERT INTO memory_grants \ + (grant_id, space_id, subject_id, principal_id, capabilities_json, context_ids_json, \ + shared_access, expires_at, revoked_at, revision, created_at) \ + VALUES ('grt_frozen', 'sp_frozen', NULL, ?, '[\"recall\"]', '[]', 0, NULL, NULL, 1, ?)", + ) + .bind(PRINCIPAL) + .bind(NOW) + .execute(&harness.pool) + .await + .expect("seed grant"); + let mut tx = harness.begin().await; + let recall = adapter + .recall( + &mut tx, + &principal(PRINCIPAL), + json!({ "space_id": "sp_frozen", "subject_id": SUBJECT, + "selection": { "mode": "subject_all" }, + "budget": { "max_items": 4 } }), + ) + .await; + assert!( + matches!(recall, SpokeResult::Ok(_)), + "a granted caller reads a frozen Mind: {recall:?}" + ); + tx.rollback().await.expect("rollback"); +} + +/// `memory.spaces.list` takes its set from the registry's join: only the Minds +/// the caller holds a live grant in, in `id` order, a frozen one included; a +/// space with no registry row never appears even under a live grant, and the +/// wire shape is the one the operation projected before. +#[tokio::test] +async fn spaces_list_returns_only_admitted_minds() { + use mindcore_sqlite::minds::CreateMind; + use mindcore_sqlite::minds; + use mindcore_base::boundary::CallerId; + use mindcore_base::ids::MindId; + + let harness = Harness::open().await; + harness.seed_grant(PRINCIPAL, &["recall"]).await; + let adapter = MemoryAdapter::new(true); + + // Two Minds for the listing owner, created out of id order so the answer + // proves its sort, and a third for another owner alone. + let mut tx = harness.begin().await; + for (id, owner) in [("mind_beta", "o_list"), ("mind_alpha", "o_list"), ("mind_gamma", "o_other")] { + let created = minds::create( + &mut tx, + &CreateMind { + mind_id: Some(MindId::new(id)), + display_name: Some(format!("mind {id}")), + owner: CallerId::new(owner), + }, + ) + .await; + assert!(matches!(created, SpokeResult::Ok(_)), "create {id}: {created:?}"); + } + sqlx::query("UPDATE memory_spaces SET status = 'frozen' WHERE space_id = 'mind_beta'") + .execute(&mut *tx) + .await + .expect("freeze mind_beta"); + tx.commit().await.expect("commit minds"); + + let mut tx = harness.begin().await; + let body = ready( + adapter + .list_spaces(&mut tx, &principal("o_list"), json!({})) + .await, + ); + let spaces = body["spaces"].as_array().expect("spaces array"); + let ids: Vec<&str> = spaces + .iter() + .map(|space| space["space_id"].as_str().expect("space_id")) + .collect(); + assert_eq!( + ids, + ["mind_alpha", "mind_beta"], + "only the owner's Minds, in id order, the frozen one included" + ); + let frozen = spaces + .iter() + .find(|space| space["space_id"] == json!("mind_beta")) + .expect("mind_beta is listed"); + assert_eq!( + frozen["status"], json!("frozen"), + "a frozen Mind is listed with its frozen status" + ); + assert!( + frozen.get("display_name").is_some() && frozen.get("revision").is_some(), + "the wire shape is the space projection: {frozen}" + ); + assert_eq!(body["next_cursor"], Value::Null); + + // The frozen Mind is not admission-listed for the other owner, whose own + // Mind is the whole of its list. + let other = ready( + adapter + .list_spaces(&mut tx, &principal("o_other"), json!({})) + .await, + ); + let other_ids: Vec<&str> = other["spaces"] + .as_array() + .expect("spaces array") + .iter() + .map(|space| space["space_id"].as_str().expect("space_id")) + .collect(); + assert_eq!(other_ids, ["mind_gamma"]); + + // The caller's live grant in `SPACE` still admits it to memory operations, + // but the space carries no registry row, so the list never names it. + let own = ready( + adapter + .list_spaces(&mut tx, &principal(PRINCIPAL), json!({})) + .await, + ); + assert_eq!( + own["spaces"], json!([]), + "a space with no registry row is excluded even under a live grant" + ); + tx.rollback().await.expect("rollback"); +} diff --git a/crates/mindcore-spoke/tests/workflows.rs b/crates/mindcore-spoke/tests/workflows.rs index 5b03060d..1377b173 100644 --- a/crates/mindcore-spoke/tests/workflows.rs +++ b/crates/mindcore-spoke/tests/workflows.rs @@ -1855,7 +1855,10 @@ async fn a_citation_that_loses_its_admission_refuses_the_settlement() { let SpiError::Settlement(reject) = error else { panic!("expected a settlement refusal, got {error:?}"); }; - assert_eq!(reject.code, SpokeRejectCode::NotFound); + // A revoked grant is no admission: the settlement answers the one + // admission refusal, before any record existence check. + assert_eq!(reject.code, SpokeRejectCode::NotAuthorized); + assert!(reject.details.is_none(), "{reject:?}"); assert_eq!(harness.count_from("memory_records").await, 1); assert_eq!(harness.count_from("memory_journal").await, 0); assert_eq!( diff --git a/crates/mindcore-sqlite/src/minds.rs b/crates/mindcore-sqlite/src/minds.rs index d5400e34..822b8282 100644 --- a/crates/mindcore-sqlite/src/minds.rs +++ b/crates/mindcore-sqlite/src/minds.rs @@ -421,6 +421,45 @@ async fn read_one_visible( SpokeResult::Ok(Vec::new()) } +/// The Mind ids `caller` holds a live grant in, read through the caller's own +/// transaction so `memory.spaces.list` sees exactly the rows its effect +/// commits against. This is the registry's own join `read_visible` runs, +/// reduced to the id: one joined row per live grant, de-duplicated in `id` +/// order by the same adjacent-group rule. A frozen Mind's id is answered — the +/// space row carries its status — and a space with no registry row never +/// joins, so it is never in the answer. +pub async fn visible_mind_ids( + tx: &mut Transaction<'_, Sqlite>, + caller: &str, +) -> SpokeResult> { + let mut rows = sqlx::query_as::<_, (String, Option)>( + "SELECT m.space_id, g.expires_at \ + FROM memory_grants g \ + JOIN minds m ON m.space_id = g.space_id \ + WHERE g.principal_id = ?1 AND g.revoked_at IS NULL \ + ORDER BY m.space_id, g.grant_id", + ) + .bind(caller) + .fetch(&mut **tx); + let mut ids = Vec::new(); + let mut emitted: Option = None; + while let Some(row) = poll_fn(|cx| rows.as_mut().poll_next(cx)).await { + let (space_id, expires_at) = match row { + Ok(row) => row, + Err(_) => return storage_unavailable(), + }; + if emitted.as_deref() == Some(space_id.as_str()) { + continue; + } + if !live(&expires_at) { + continue; + } + emitted = Some(space_id.clone()); + ids.push(space_id); + } + SpokeResult::Ok(ids) +} + impl MindStore { /// `create` in one immediate-write transaction. pub async fn create_mind(&self, request: &CreateMind) -> SpokeResult { diff --git a/crates/mindcore-sqlite/tests/embed_parity.rs b/crates/mindcore-sqlite/tests/embed_parity.rs index 5e14d7a9..44378494 100644 --- a/crates/mindcore-sqlite/tests/embed_parity.rs +++ b/crates/mindcore-sqlite/tests/embed_parity.rs @@ -139,6 +139,23 @@ impl Harness { .execute(&harness.pool) .await .expect("seed subject grant"); + // The registry row makes the fixture space a Mind `spaces.list` may + // list; the carrier entry the row references is seeded first. + sqlx::query( + "INSERT INTO knowledge_entries \ + (collection, entry_id, revision, payload, created_at, updated_at) \ + VALUES ('mind:spc_parity', 'ke_carrier', 1, '{}', \ + '2026-11-20T09:20:01.123Z', '2026-11-20T09:20:01.123Z')", + ) + .execute(&harness.pool) + .await + .expect("seed carrier entry"); + sqlx::query( + "INSERT INTO minds (space_id, knowledge_collection, carrier_entry_id) VALUES ('spc_parity', 'mind:spc_parity', 'ke_carrier')", + ) + .execute(&harness.pool) + .await + .expect("seed registry row"); harness } @@ -1264,10 +1281,10 @@ async fn receipt_y04_second_grant_selector() { SpokeResult::Reject(reject) => { assert_eq!(reject.code, SpokeRejectCode::NotAuthorized, "{id}"); assert_eq!( - reject.details.as_ref().expect("details")["retry_class"], - "terminal", - "{id}" + reject.message, "the caller is not admitted to the named mind", + "{id}: a revoked grant is no admission", ); + assert!(reject.details.is_none(), "{id}: {reject:?}"); } other => panic!("non-participant poll must refuse {id}: {other:?}"), } diff --git a/crates/mindcore-sqlite/tests/spaces_list_query_count.rs b/crates/mindcore-sqlite/tests/spaces_list_query_count.rs index 0320c01c..4566b7e0 100644 --- a/crates/mindcore-sqlite/tests/spaces_list_query_count.rs +++ b/crates/mindcore-sqlite/tests/spaces_list_query_count.rs @@ -1,7 +1,7 @@ -//! I-000060 / I-000066: `spaces.list` streams the principal's grants and -//! projects the visible revisions, so it costs exactly three SELECTs — the -//! scan, the revision projection and the spaces — whatever the space count, -//! and it never fails on a grant whose space row is gone. +//! I-000060 / I-000066: `spaces.list` reads the registry's visibility join +//! and projects the visible revisions, so it costs exactly three SELECTs — +//! the join, the revision projection and the spaces — whatever the space +//! count, and it never fails on a grant whose space row is gone. use std::sync::atomic::{AtomicUsize, Ordering}; @@ -99,6 +99,16 @@ async fn seed_space_row(pool: &SqlitePool, space_id: &str) { .insert_space(&mut tx, &space) .await .expect("seed space"); + // The registry row makes the space a Mind `spaces.list` may list. The + // test pool disables foreign keys, so the collection and carrier need + // no entry row. + sqlx::query( + "INSERT INTO minds (space_id, knowledge_collection, carrier_entry_id) VALUES (?, 'mind:test', 'ke_test')", + ) + .bind(space_id) + .execute(&mut *tx) + .await + .expect("seed registry row"); tx.commit().await.expect("commit space"); } @@ -247,7 +257,7 @@ async fn list_spaces_streams_grants_and_costs_three_selects() { assert_eq!( listing(&pool).await, (3, five.clone()), - "an orphan grant is skipped instead of decoded", + "an orphan grant names no Mind, so the join never lists it", ); seed_space_row(&pool, "spc_hidden").await; @@ -362,9 +372,9 @@ async fn list_spaces_streams_grants_and_costs_three_selects() { }, ) .await; - let (_, stage) = list_call(&pool, json!({})).await; - assert!( - matches!(&stage, SpokeResult::Reject(reject) if reject.code == SpokeRejectCode::InternalError), - "a malformed grant payload in a visible space must fail the listing: {stage:?}", + assert_eq!( + listing(&pool).await, + (3, five.clone()), + "the listing reads grant liveness, never the payload, so a malformed capabilities payload changes nothing visible", ); } From 017d8f394f3605b65deacc8900f3f8e2fb57fe24 Mon Sep 17 00:00:00 2001 From: Tang Bohao Date: Thu, 26 Nov 2026 11:49:17 +0800 Subject: [PATCH 02/27] fix(serving): admit through admit_mind on the reflection and control reads memory.reflections.state/list and memory.subjects.get/grants.list enter admit_mind before any existence check, closing the NOT_FOUND vs NOT_AUTHORIZED Mind-existence disclosure the L2 review flagged. Regressions pin byte-equal admission refusals for all four ops across absent, ungranted and frozen-ungranted Minds. --- crates/mindcore-spoke/src/control.rs | 17 +++----- crates/mindcore-spoke/src/reflection.rs | 8 ++-- crates/mindcore-spoke/tests/memory_adapter.rs | 40 ++++++++++++++----- 3 files changed, 40 insertions(+), 25 deletions(-) diff --git a/crates/mindcore-spoke/src/control.rs b/crates/mindcore-spoke/src/control.rs index 03599790..7dffa321 100644 --- a/crates/mindcore-spoke/src/control.rs +++ b/crates/mindcore-spoke/src/control.rs @@ -367,9 +367,9 @@ impl MemoryAdapter { let request: MemorySubjectsGetRequest = wire::decode(&raw, "memory.subjects.get request")?; let principal_id = principal_id(principal); let space = SpaceId::new(request.space_id.to_string()); - admission::space(&self.repository, tx, &space).await?; let subject_id = request.subject_id.as_str(); - let rows = admission::grants(&self.repository, tx, &space).await?; + let (rows, _space_row) = + admission::admit_mind(&self.repository, tx, principal_id, &space).await?; if !admission::any_grant_for_subject( &rows, principal_id, @@ -511,9 +511,9 @@ impl MemoryAdapter { } let principal_id = principal_id(principal); let space = SpaceId::new(request.space_id.to_string()); - admission::space(&self.repository, tx, &space).await?; let now = Utc::now(); - let rows = admission::grants(&self.repository, tx, &space).await?; + let (rows, _space_row) = + admission::admit_mind(&self.repository, tx, principal_id, &space).await?; let wire_grants = admission::wire_grants(&rows)?; let admin = admission::covered( &wire_grants, @@ -529,14 +529,7 @@ impl MemoryAdapter { let applied = if admin { requested } else { - if !rows.iter().any(|row| { - row.principal_id.as_str() == principal_id && admission::live_grant(row, now) - }) { - return Err(Reject::not_authorized(format!( - "principal {principal_id} holds no grant in space {}", - space.as_str() - ))); - } + // admit_mind already proved one live grant for this principal. Some(principal_id.to_string()) }; let subject_filter = request diff --git a/crates/mindcore-spoke/src/reflection.rs b/crates/mindcore-spoke/src/reflection.rs index bfba0e74..703a92ce 100644 --- a/crates/mindcore-spoke/src/reflection.rs +++ b/crates/mindcore-spoke/src/reflection.rs @@ -123,8 +123,8 @@ impl MemoryAdapter { let subject_id = request.subject_id.to_string(); let (selection, filter) = read_selection(object)?; let now = Utc::now(); - admission::space(&self.repository, tx, &space).await?; - let rows = admission::grants(&self.repository, tx, &space).await?; + let (rows, _space_row) = + admission::admit_mind(&self.repository, tx, principal_id, &space).await?; let wire_grants = admission::wire_grants(&rows)?; let base = admission::selection_requirement("reflect", subject_id.as_str(), &selection); if !admission::covered(&wire_grants, principal_id, space.as_str(), now, &base) { @@ -212,8 +212,8 @@ impl MemoryAdapter { }; let filter = wire::PlacementSelectionWire::filter(object, "filter")?; let now = Utc::now(); - admission::space(&self.repository, tx, &space).await?; - let rows = admission::grants(&self.repository, tx, &space).await?; + let (rows, _space_row) = + admission::admit_mind(&self.repository, tx, principal_id, &space).await?; let wire_grants = admission::wire_grants(&rows)?; let base = admission::selection_requirement("reflect", subject_id.as_str(), &requested); if !admission::covered(&wire_grants, principal_id, space.as_str(), now, &base) { diff --git a/crates/mindcore-spoke/tests/memory_adapter.rs b/crates/mindcore-spoke/tests/memory_adapter.rs index 6b39a964..7a82bb06 100644 --- a/crates/mindcore-spoke/tests/memory_adapter.rs +++ b/crates/mindcore-spoke/tests/memory_adapter.rs @@ -1138,8 +1138,7 @@ async fn revoked_grant_denies_subject_and_profile_reads() { ) .await; let refusal = reject(&subject); - assert_eq!(refusal.code, SpokeRejectCode::NotAuthorized); - assert_eq!(retry_class(refusal), "terminal"); + assert_admission_refusal(refusal, "a revoked grant is no admission"); let profile = adapter .get_profile( @@ -4485,11 +4484,6 @@ async fn unknown_ungranted_and_frozen_minds_answer_one_refusal() { for space in ["sp_absent", "sp_ungranted", "sp_frozen"] { let mut tx = harness.begin().await; for (op, result) in guarded_reads(&adapter, &mut tx, space, SUBJECT, "cnd_any").await { - // The reflection reads are not Mind-admission paths: they answer - // through their own space lookup and are out of this envelope. - if op.starts_with("memory.reflections") { - continue; - } let refusal = reject(&result); assert_eq!( refusal.code, @@ -4505,8 +4499,8 @@ async fn unknown_ungranted_and_frozen_minds_answer_one_refusal() { serde_json::json!(refusal.message), )); } - // `memory.receipts.get` is the seventh read path `guarded_reads` does - // not carry. + // `memory.receipts.get` and the two control reads are paths + // `guarded_reads` does not carry. let receipts = adapter .get_receipt( &mut tx, @@ -4521,6 +4515,34 @@ async fn unknown_ungranted_and_frozen_minds_answer_one_refusal() { "receipts in {space} carries no details: {refusal:?}" ); envelopes.push((format!("receipts in {space}"), serde_json::json!(refusal.message))); + let subjects_get = adapter + .get_subject( + &mut tx, + &principal(PRINCIPAL), + json!({ "space_id": space, "subject_id": SUBJECT }), + ) + .await; + let refusal = reject(&subjects_get); + assert_eq!(refusal.code, SpokeRejectCode::NotAuthorized, "subjects.get in {space}"); + assert!( + refusal.details.is_none(), + "subjects.get in {space} carries no details: {refusal:?}" + ); + envelopes.push((format!("subjects.get in {space}"), serde_json::json!(refusal.message))); + let grants_list = adapter + .list_grants( + &mut tx, + &principal(PRINCIPAL), + json!({ "space_id": space }), + ) + .await; + let refusal = reject(&grants_list); + assert_eq!(refusal.code, SpokeRejectCode::NotAuthorized, "grants.list in {space}"); + assert!( + refusal.details.is_none(), + "grants.list in {space} carries no details: {refusal:?}" + ); + envelopes.push((format!("grants.list in {space}"), serde_json::json!(refusal.message))); // The mutation path enters admission through `authorize`. let mutation = adapter .capture( From a2a41ff28c1d9c02e4de634c9dba4b0e895eadd0 Mon Sep 17 00:00:00 2001 From: Tang Bohao Date: Thu, 26 Nov 2026 12:58:31 +0800 Subject: [PATCH 03/27] feat(serving): route memory requests through the Mind's registry row MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Every memory request is routed by its space_id: the workflow binding resolves the collection from the minds registry row read on the caller's transaction, the per-principal route map is retired, and deliberate's wire arguments no longer carry holder — the carrier is the Mind's own record, so a peer still sending the retired member hits the closed object's unknown-field refusal. --- crates/mindcore-runtime/src/lib.rs | 72 +--- crates/mindcore-runtime/src/tools.rs | 36 +- crates/mindcore-runtime/src/tools/tests.rs | 3 - crates/mindcore-runtime/tests/loopback.rs | 467 +++++++++++---------- crates/mindcore-runtime/tests/surface.rs | 98 +---- crates/mindcore-spoke/src/workflows.rs | 137 ++---- crates/mindcore-spoke/tests/workflows.rs | 87 ++-- 7 files changed, 387 insertions(+), 513 deletions(-) diff --git a/crates/mindcore-runtime/src/lib.rs b/crates/mindcore-runtime/src/lib.rs index 531ebee5..58c1f14b 100644 --- a/crates/mindcore-runtime/src/lib.rs +++ b/crates/mindcore-runtime/src/lib.rs @@ -18,7 +18,6 @@ pub mod mind; pub mod minds; pub mod tools; -use std::collections::BTreeMap; use std::sync::Arc; use serde_json::Value; @@ -40,7 +39,7 @@ use spoke_connect::remote::{ }; use spoke_operations::{ spoke_reject, validate_manifest_tools, AdoptionPort, HistoryPort, ScopedKnowledgePort, - SpokeReject, SpokeRejectCode, SpokeResult, + SpokeRejectCode, SpokeResult, }; use spoke_schemas::host_capability_manifest::ToolDescriptor; use spoke_schemas::{HostCapabilityManifest, Scope}; @@ -96,17 +95,13 @@ impl MindcoreServe { } } - /// The engine one surface serves: each workflow call resolves the collection it reaches from - /// the principal its admission returns, through the host's route map. - fn workflows( - &self, - routes: Arc>, - ) -> Result, SpokeReject> { + /// The engine one surface serves: each workflow call resolves the Mind it reaches from the + /// `space_id` the request carries, through the registry row. + fn workflows(&self) -> Arc { let publish = Arc::clone(&self.publish); let binding = MemoryWorkflowBinding::new(self.store.pool(), self.reflections) - .with_publisher(move |targets| publish(targets)) - .with_knowledge_routes(routes)?; - Ok(Arc::new(SpiMindWorkflows::new(binding))) + .with_publisher(move |targets| publish(targets)); + Arc::new(SpiMindWorkflows::new(binding)) } /// Assemble the ports, manifest and tool registrations for `ConnectResponderOptions`. @@ -146,28 +141,10 @@ impl MindcoreServe { None, ); } - if let Some((principal, _)) = faces - .workflow_routes - .iter() - .find(|(_, route)| route.collection == *source) - { - return spoke_reject( - SpokeRejectCode::InvalidInput, - format!( - "the adoption source collection {source} is the workflow destination of principal {principal}" - ), - None, - ); - } } - let routes = Arc::new(faces.workflow_routes); - let routed = !routes.is_empty(); - let workflows = match self.workflows(Arc::clone(&routes)) { - Ok(workflows) => workflows, - Err(reject) => return SpokeResult::Reject(reject), - }; - let engine: Arc = workflows.clone(); let principals = faces.principals; + let workflows = self.workflows(); + let engine: Arc = workflows.clone(); let mut tools = WorkflowTools::new(engine, Arc::clone(&principals), faces.providers).registrations(); tools.extend( @@ -176,9 +153,6 @@ impl MindcoreServe { .into_iter() .filter(|tool| tool.descriptor.capability_id.as_str() != RETIRED_ADOPT_TOOL), ); - if !routed { - tools.retain(|tool| tool.descriptor.capability_id.as_str() != tools::DELIBERATE); - } let manifest = derive_manifest( faces.manifest, faces.memory.as_deref(), @@ -307,27 +281,17 @@ pub struct ServeFaces { /// Providers and the domain lens injected into each workflow call. pub providers: MindProviders, /// The one host-configured adoption source, or `None` to serve no adoption. Its collection must - /// be non-empty and must not be [`ServeFaces::knowledge`]'s collection or any - /// [`ServeFaces::workflow_routes`] destination, including a route of a principal that is not - /// connected, and its scope id must differ from [`ServeFaces::scope_id`]; assembly refuses - /// otherwise. The source need not hold rows. When it is configured, the - /// `spoke-knowledge-adoption` face serves `knowledge.adopt` over the knowledge face's admission, - /// and writes into [`ServeFaces::knowledge`]'s collection — one shared collection with one slot - /// per `destination_entry_id`: the first adoption of a given id claims it, a repeat is answered - /// `already_present` with the stored copy only at the anchor revision the copy records (another - /// revision is a conflict), and a peer whose own admitted selection hides the copy is answered - /// the occupancy refusal instead of the copy. + /// be non-empty and must not be [`ServeFaces::knowledge`]'s collection, and its scope id must + /// differ from [`ServeFaces::scope_id`]; assembly refuses otherwise. The source need not hold + /// rows. When it is configured, the `spoke-knowledge-adoption` face serves `knowledge.adopt` + /// over the knowledge face's admission, and writes into [`ServeFaces::knowledge`]'s + /// collection — one shared collection with one slot per `destination_entry_id`: the first + /// adoption of a given id claims it, a repeat is answered `already_present` with the stored + /// copy only at the anchor revision the copy records (another revision is a conflict), and a + /// peer whose own admitted selection hides the copy is answered the occupancy refusal instead + /// of the copy. pub adoption: Option, - /// The host's per-principal workflow routes: each exact principal id — not a peer id — to the - /// one workflow collection its calls may reach. The map is the workflow collection allowlist, so - /// a route need not name a collection that already holds rows; each destination collection - /// belongs to exactly one principal route, and assembly refuses a collection named by two - /// routes. A route names the principal `principals` admits; a principal without one reads no - /// knowledge and never writes a carrier. Empty serves no deliberation and advertises none. - /// Routes are never read from the wire. - pub workflow_routes: BTreeMap, - /// Additional host tools: every descriptor is advertised and its handler installed, except the - /// ids this runtime owns — `tools.mindcore.deliberate` on a surface with an empty route map, and + /// Additional host tools: every descriptor is advertised and its handler installed, except /// the retired `tools.mindcore.adopt` on every surface. pub tools: Vec, } diff --git a/crates/mindcore-runtime/src/tools.rs b/crates/mindcore-runtime/src/tools.rs index 3e99c436..8a130c2f 100644 --- a/crates/mindcore-runtime/src/tools.rs +++ b/crates/mindcore-runtime/src/tools.rs @@ -18,6 +18,7 @@ use serde::de::DeserializeOwned; use serde::Deserialize; use serde_json::{json, Map, Value}; +use mindcore_sqlite::minds::CARRIER_ENTRY_ID; use mindcore_spi::{ AbsorbCandidateOutcome, ContextPack, DeliberateOutcome, DeliberateRequest, DomainLens, Embedder, Evidence, MindCapabilities, MindWorkflows, PolicyHook, Reasoner, SpiError, @@ -313,11 +314,27 @@ async fn deliberate( text: evidence.text.as_str(), }) .collect(); + // The carrier is the Mind's own: its registry row names the one carrier + // entry every Mind is created with, so a peer never names one. + let holder: CognitionReference = match serde_json::from_value(json!({ + "kind": "knowledge_entry", + "namespace": "mindcore", + "id": CARRIER_ENTRY_ID, + })) { + Ok(holder) => holder, + Err(error) => { + return SpokeResult::Reject(SpokeReject { + code: SpokeRejectCode::InternalError, + message: format!("the carrier reference does not decode: {error}"), + details: None, + }) + } + }; let request = DeliberateRequest { space_id: &arguments.space_id, subject_id: Some(&arguments.subject_id), assessment_context_id: None, - holder: &arguments.holder, + holder: &holder, target: &arguments.target, evidence: &evidence, timeout: Duration::from_millis(arguments.timeout_ms.get() as u64), @@ -452,7 +469,6 @@ struct AbsorbArguments { struct DeliberateArguments { space_id: String, subject_id: String, - holder: CognitionReference, target: CognitionTarget, evidence: Vec, timeout_ms: NonZeroUsize, @@ -871,19 +887,20 @@ fn absorb_output() -> Value { }) } -/// The deliberation arguments, mirroring the pinned `spoke-schemas` request DTOs. `holder` and -/// `target` splice the same pinned definitions `absorb` advertises — the workflow decodes exactly -/// those DTOs, so the manifest and the handler cannot drift apart. +/// The deliberation arguments, mirroring the pinned `spoke-schemas` request DTOs. The carrier is +/// the Mind's own record and never a wire member: a peer still sending the retired `holder` hits +/// the closed object's unknown-field refusal. `target` splices the same pinned definitions +/// `absorb` advertises — the workflow decodes exactly those DTOs, so the manifest and the handler +/// cannot drift apart. fn deliberate_input() -> Value { let mut schema = json!({ "$id": "https://mindcore.invalid/schemas/tools/deliberate.input.schema.json", "type": "object", "additionalProperties": false, - "required": ["space_id", "subject_id", "holder", "target", "evidence", "timeout_ms"], + "required": ["space_id", "subject_id", "target", "evidence", "timeout_ms"], "properties": { "space_id": { "type": "string", "minLength": 1 }, "subject_id": { "type": "string", "minLength": 1 }, - "holder": { "$ref": "#/definitions/CognitionReference" }, "target": { "$ref": "#/definitions/CognitionTarget" }, "evidence": { "type": "array", @@ -900,10 +917,7 @@ fn deliberate_input() -> Value { "timeout_ms": { "type": "integer", "minimum": 1 }, }, }); - schema["definitions"] = Value::Object(cognition_definitions(&[ - "CognitionReference", - "CognitionTarget", - ])); + schema["definitions"] = Value::Object(cognition_definitions(&["CognitionTarget"])); schema } diff --git a/crates/mindcore-runtime/src/tools/tests.rs b/crates/mindcore-runtime/src/tools/tests.rs index a5659009..681a5ef6 100644 --- a/crates/mindcore-runtime/src/tools/tests.rs +++ b/crates/mindcore-runtime/src/tools/tests.rs @@ -274,7 +274,6 @@ fn deliberate_arguments() -> Value { json!({ "space_id": "spc_1", "subject_id": "subj_1", - "holder": { "kind": "knowledge_entry", "namespace": "mindcore", "id": "ke_wren" }, "target": { "carrier": { "kind": "knowledge_entry", "namespace": "mindcore", "id": "ke_gate" }, "target_id": "prop_gate_closed", @@ -506,7 +505,6 @@ async fn malformed_arguments_are_invalid_input() { json!({ "space_id": "spc_1", "subject_id": "subj_1", - "holder": { "kind": "knowledge_entry", "namespace": "mindcore", "id": "ke_wren" }, "target": { "carrier": { "kind": "knowledge_entry", "namespace": "mindcore", "id": "ke_gate" }, "target_id": "prop_gate_closed", @@ -522,7 +520,6 @@ async fn malformed_arguments_are_invalid_input() { json!({ "space_id": "spc_1", "subject_id": "subj_1", - "holder": { "kind": "knowledge_entry", "namespace": "mindcore", "id": "ke_wren" }, "target": { "carrier": { "kind": "knowledge_entry", "namespace": "mindcore", "id": "ke_gate" }, "target_id": "prop_gate_closed", diff --git a/crates/mindcore-runtime/tests/loopback.rs b/crates/mindcore-runtime/tests/loopback.rs index 1d5dc964..00511d37 100644 --- a/crates/mindcore-runtime/tests/loopback.rs +++ b/crates/mindcore-runtime/tests/loopback.rs @@ -34,7 +34,7 @@ use mindcore_spi::{ }; use mindcore_spoke::{ServedMemory, TransferService}; use mindcore_sqlite::{MindStore, ScopedKnowledgeStore, SqliteMemoryRepository}; -use spoke_connect::core::{derive_peer_id_from_ed25519_pubkey, CAPABILITY_SPOKE_JUDGMENT}; +use spoke_connect::core::derive_peer_id_from_ed25519_pubkey; use spoke_connect::remote::{ connect_remote_adapter, connect_responder, loopback_transport_pair, ConnectResponder, ConnectResponderOptions, KnowledgeAdmission, MemoryAdmission, RemoteAdapter, @@ -54,11 +54,13 @@ use spoke_schemas::{ const SCOPE_ID: &str = "spoke-scope-001"; const COLLECTION: &str = "wren"; -const CARRIER: &str = "ke_wren"; -/// The second principal's own collection and carrier holder entry. +/// The carrier entry id every Mind is created with; the wire never names it. +const CARRIER: &str = "ke_carrier"; +/// The second Mind's own collection; its carrier entry id is the one every Mind is created with. const COLLECTION_TWO: &str = "mora"; -const CARRIER_TWO: &str = "ke_mora"; const SPACE: &str = "spc_loopback"; +/// The second Mind's space, admitted to the second peer only. +const SPACE_TWO: &str = "spc_loopback_two"; const SUBJECT: &str = "subj_loopback"; const PRINCIPAL: &str = "prn_loopback"; /// why: a transfer chunk travels back through the typed wire DTOs, which canonicalize a whole @@ -170,11 +172,131 @@ impl Fixture { .await .expect("seed grant"); } + // The carrier entry the registry row references: `minds` keys it foreign to + // `knowledge_entries`, so the entry exists before the row names it. + sqlx::query( + "INSERT INTO knowledge_entries \ + (collection, entry_id, revision, payload, created_at, updated_at) \ + VALUES (?, ?, 1, ?, ?, ?)", + ) + .bind(COLLECTION) + .bind(CARRIER) + .bind( + json!({ + "schema_version": 1, + "entry_id": CARRIER, + "entry_type": "note", + "canonical_name": format!("{CARRIER}'s carrier"), + "status": "confirmed", + "revision": 1, + "body": { "summary": "what this holder currently holds" }, + "extensions": {}, + }) + .to_string(), + ) + .bind(NOW) + .bind(NOW) + .execute(&pool) + .await + .expect("seed the carrier entry"); + // The Mind registry row of this fixture's space: the workflow binding resolves the + // collection it serves from it, and a space with no row answers nothing. + sqlx::query( + "INSERT INTO minds (space_id, knowledge_collection, carrier_entry_id) VALUES (?, ?, ?)", + ) + .bind(SPACE) + .bind(COLLECTION) + .bind(CARRIER) + .execute(&pool) + .await + .expect("seed the mind registry row"); + seed_record(&pool, "rec_north_gate", "the north gate is closed").await; seed_record(&pool, "rec_market", "the market opens at dawn").await; Self { dir, store } } + /// The second Mind: its own space, subject, records, carrier entry and registry row, ready + /// for a peer admitted to it alone. + async fn seed_second_mind(&self) { + let pool = self.store.pool(); + for statement in [ + format!( + "INSERT INTO memory_spaces \ + (space_id, display_name, authority_host_id, authority_generation, status, \ + revision, created_at) \ + VALUES ('{SPACE_TWO}', 'second mind', 'host_1', 1, 'active', 1, '{NOW}')" + ), + format!( + "INSERT INTO memory_subjects \ + (space_id, subject_id, kind_ns, kind_id, status, fenced_contexts_json, revision, \ + created_at) \ + VALUES ('{SPACE_TWO}', '{SUBJECT}', 'kind', 'belief', 'active', '[]', 1, '{NOW}')" + ), + ] { + sqlx::query(sqlx::AssertSqlSafe(statement)) + .execute(&pool) + .await + .expect("seed the second mind"); + } + // The carrier entry of the second Mind, before the registry row references it. + sqlx::query( + "INSERT INTO knowledge_entries \ + (collection, entry_id, revision, payload, created_at, updated_at) \ + VALUES (?, ?, 1, ?, ?, ?)", + ) + .bind(COLLECTION_TWO) + .bind(CARRIER) + .bind( + json!({ + "schema_version": 1, + "entry_id": CARRIER, + "entry_type": "note", + "canonical_name": format!("{CARRIER}'s carrier"), + "status": "confirmed", + "revision": 1, + "body": { "summary": "what this holder currently holds" }, + "extensions": {}, + }) + .to_string(), + ) + .bind(NOW) + .bind(NOW) + .execute(&pool) + .await + .expect("seed the second mind's carrier entry"); + sqlx::query( + "INSERT INTO minds (space_id, knowledge_collection, carrier_entry_id) VALUES (?, ?, ?)", + ) + .bind(SPACE_TWO) + .bind(COLLECTION_TWO) + .bind(CARRIER) + .execute(&pool) + .await + .expect("seed the second mind's registry row"); + seed_record_in(&pool, SPACE_TWO, "rec_north_gate_two", "the north gate is closed").await; + seed_record_in(&pool, SPACE_TWO, "rec_market_two", "the market opens at dawn").await; + } + + /// One space-wide grant for `principal` over the second Mind's space. + async fn grant_in_second(&self, grant_id: &str, principal: &str, capabilities: &[&str]) { + sqlx::query( + "INSERT INTO memory_grants \ + (grant_id, space_id, subject_id, principal_id, capabilities_json, \ + context_ids_json, shared_access, expires_at, revoked_at, revision, created_at) \ + VALUES (?, ?, NULL, ?, ?, '[]', 0, NULL, NULL, 1, ?)", + ) + .bind(grant_id) + .bind(SPACE_TWO) + .bind(principal) + .bind(json!(capabilities).to_string()) + .bind(NOW) + .execute(&self.store.pool()) + .await + .expect("seed grant"); + } + + /// One space-wide grant for `principal` over this fixture's space. async fn grant(&self, grant_id: &str, principal: &str, capabilities: &[&str]) { sqlx::query( @@ -202,34 +324,6 @@ impl Fixture { .expect("drop the grant"); } - /// The carrier entry the deliberation holder names. - async fn seed_carrier(&self) { - self.seed_carrier_in(COLLECTION, CARRIER).await; - } - - /// The carrier entry one collection holds, as its holder names it. - async fn seed_carrier_in(&self, collection: &str, entry_id: &str) { - expect_ok( - self.store - .knowledge(KnowledgeScope::new(collection)) - .put_knowledge_entry( - serde_json::from_value(json!({ - "schema_version": 1, - "entry_id": entry_id, - "entry_type": "note", - "canonical_name": format!("{entry_id}'s carrier"), - "status": "confirmed", - "body": { "summary": "what this holder currently holds" }, - "extensions": {}, - })) - .expect("carrier JSON matches the schema"), - None, - ) - .await, - "write the carrier entry", - ); - } - /// The database file this fixture opened, for a test that reopens it after a restart. fn db_path(&self) -> std::path::PathBuf { self.dir.path().join(DB_FILE) @@ -244,6 +338,10 @@ impl Fixture { } async fn seed_record(pool: &sqlx::SqlitePool, record_id: &str, text: &str) { + seed_record_in(pool, SPACE, record_id, text).await; +} + +async fn seed_record_in(pool: &sqlx::SqlitePool, space: &str, record_id: &str, text: &str) { sqlx::query( "INSERT INTO memory_records \ (record_id, space_id, subject_id, kind, content_json, scope_visibility, \ @@ -252,7 +350,7 @@ async fn seed_record(pool: &sqlx::SqlitePool, record_id: &str, text: &str) { VALUES (?, ?, ?, 'fact', ?, 'shared', NULL, ?, NULL, NULL, NULL, 1, ?, ?)", ) .bind(record_id) - .bind(SPACE) + .bind(space) .bind(SUBJECT) .bind(json!({ "text": text }).to_string()) .bind( @@ -284,18 +382,6 @@ fn hello(host_id: &str, capabilities: &[&str]) -> HostCapabilityManifest { .expect("manifest JSON matches the schema") } -/// The reserved deliberation id's descriptor, as a host could build one. -fn deliberate_descriptor() -> ToolDescriptor { - serde_json::from_value(json!({ - "schema_version": 1, - "capability_id": DELIBERATE, - "op": DELIBERATE, - "description": "Derive a validated verdict over supplied evidence.", - "input": { "type": "object" }, - "output": { "type": "object" }, - })) - .expect("tool descriptor JSON matches the schema") -} /// The host tool's descriptor, as a host could build one. fn host_tool_descriptor() -> ToolDescriptor { @@ -456,7 +542,9 @@ impl Reasoner for NoChangeReasoner { assert!( payload["records"].as_array().is_some_and(|records| records .iter() - .any(|record| record["record_id"] == "rec_north_gate")), + .any(|record| record["record_id"] + .as_str() + .is_some_and(|id| id.starts_with("rec_north_gate")))), "the authorized memory page reached the reasoner: {}", request.user_payload ); @@ -489,15 +577,21 @@ impl Reasoner for SettlingReasoner { assert!( payload["records"].as_array().is_some_and(|records| records .iter() - .any(|record| record["record_id"] == "rec_north_gate")), + .any(|record| record["record_id"].as_str().is_some_and(|id| id.starts_with("rec_north_gate")))), "the authorized memory page reached the reasoner: {}", request.user_payload ); + let gate_record = payload["records"].as_array() + .and_then(|records| records.iter() + .find(|record| record["record_id"].as_str().is_some_and(|id| id.starts_with("rec_north_gate")))) + .and_then(|record| record["record_id"].as_str()) + .expect("the page carries the north-gate record") + .to_string(); Ok(json!({ "recommendation": { "kind": "promote", "target_kind": "belief" }, "rationale": self.0, "evidence_ids": ["ev_gate"], - "record_ids": ["rec_north_gate"], + "record_ids": [gate_record], "record": { "kind": "belief", "order": 1, @@ -511,7 +605,7 @@ impl Reasoner for SettlingReasoner { "basis": { "kind": "evidence", "evidence": [ - { "kind": "memory_record", "namespace": "mindcore", "id": "rec_north_gate" } + { "kind": "memory_record", "namespace": "mindcore", "id": gate_record } ] } } @@ -548,13 +642,13 @@ impl PolicyHook for HoldingPolicy { } } -/// The host's side of the surface. `workflow_routes` is the per-principal workflow route map; -/// an empty map serves and advertises no `deliberate` at all. +/// The host's side of the surface. `routes` is the retired per-principal route map the binding no +/// longer reads: the registry row decides every collection, so callers pass it and it is ignored. fn faces( manifest: HostCapabilityManifest, memory: Option>, providers: MindProviders, - workflow_routes: BTreeMap, + _routes: BTreeMap, ) -> ServeFaces { ServeFaces { manifest, @@ -566,12 +660,12 @@ fn faces( principals: principal_admission(), providers, adoption: None, - workflow_routes, tools: Vec::new(), } } -/// A route map putting each of `principals` onto the fixture's one collection. +/// A retired route map shell: the registry row replaced routing, so this only keeps the call +/// sites shaped as they were. fn routes(principals: &[&str]) -> BTreeMap { principals .iter() @@ -658,9 +752,13 @@ async fn connect_as( } fn recall_arguments() -> Value { + recall_arguments_in(SPACE) +} + +fn recall_arguments_in(space: &str) -> Value { json!({ "request": { - "space_id": SPACE, + "space_id": space, "subject_id": SUBJECT, "selection": { "mode": "subject_all" }, "budget": { "max_items": 10 }, @@ -680,17 +778,17 @@ fn recall_request() -> MemoryRecallRequest { } fn deliberate_arguments() -> Value { - deliberate_arguments_for(CARRIER) + deliberate_arguments_in(SPACE) } -/// The same deliberation, naming `carrier` as both the holder and the target carrier. -fn deliberate_arguments_for(carrier: &str) -> Value { +/// The same deliberation inside `space`: the wire never names a carrier — the Mind's registry row +/// decides it — so only the target reference varies per Mind. +fn deliberate_arguments_in(space: &str) -> Value { json!({ - "space_id": SPACE, + "space_id": space, "subject_id": SUBJECT, - "holder": { "kind": "knowledge_entry", "namespace": "mindcore", "id": carrier }, "target": { - "carrier": { "kind": "knowledge_entry", "namespace": "mindcore", "id": carrier }, + "carrier": { "kind": "knowledge_entry", "namespace": "mindcore", "id": CARRIER }, "target_id": "prop_north_gate", "kind": "proposition", }, @@ -868,8 +966,8 @@ async fn remote_consumer_recalls_context_through_the_composed_surface() { assert_eq!( capabilities(&surface), - ["spoke-knowledge", "ke-ownership", RECALL_CONTEXT, ABSORB], - "the manifest advertises exactly the knowledge face and the served tools" + ["spoke-knowledge", "ke-ownership", "spoke-judgment", RECALL_CONTEXT, ABSORB, DELIBERATE], + "the manifest advertises the knowledge face and all three workflow tools" ); assert_eq!( surface @@ -878,8 +976,8 @@ async fn remote_consumer_recalls_context_through_the_composed_surface() { .iter() .map(|tool| tool.capability_id.as_str()) .collect::>(), - [RECALL_CONTEXT, ABSORB], - "no deliberation route, so no deliberation tool is installed" + [RECALL_CONTEXT, ABSORB, DELIBERATE], + "the registry row routes every Mind, so the deliberation tool is always installed" ); let session = connect(&surface, &["spoke-knowledge", RECALL_CONTEXT]).await; @@ -905,55 +1003,47 @@ async fn remote_consumer_recalls_context_through_the_composed_surface() { ); } -/// A route map fills recall's knowledge slot per principal: a second admitted peer routed to its own -/// collection reads that collection's entry under its own grant, never the first principal's. +/// The knowledge slot keys to the Mind the request names: a second admitted peer recalling its own +/// Mind's space reads that Mind's collection entries under its own grant, never the first Mind's. #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn another_admitted_peer_recalls_its_knowledge_slot_under_a_wired_route() { +async fn another_admitted_mind_recalls_its_own_knowledge_slot() { let fixture = Fixture::open().await; - fixture.seed_carrier().await; - fixture.seed_carrier_in(COLLECTION_TWO, CARRIER_TWO).await; + fixture.seed_second_mind().await; fixture - .grant("grt_recall_peer_two", PEER_TWO_PRINCIPAL, &["recall"]) + .grant_in_second("grt_recall_peer_two", PEER_TWO_PRINCIPAL, &["recall"]) .await; fixture - .grant( + .grant_in_second( "grt_knowledge_peer_two", PEER_TWO_PRINCIPAL, &["knowledge_read"], ) .await; let (_dir, serve) = fixture.serve(); - let mut workflow_routes = routes(&[PRINCIPAL]); - workflow_routes.insert( - PEER_TWO_PRINCIPAL.to_string(), - KnowledgeScope::new(COLLECTION_TWO), - ); let mut faces = faces( hello("runtime", &[]), None, MindProviders::default(), - workflow_routes, + routes(&[PRINCIPAL]), ); faces.principals = two_principal_admission(); let surface = surface(&serve, faces); - assert!( - capabilities(&surface).contains(&DELIBERATE), - "the carrier route is wired: {:?}", - capabilities(&surface) - ); let session = connect_as(&surface, &PEER_TWO_SEED, &[RECALL_CONTEXT]).await; - let mut arguments = recall_arguments(); + let mut arguments = recall_arguments_in(SPACE_TWO); arguments["max_tokens"] = json!(4_000); let result = expect_ok( - session.adapter.invoke_tool(RECALL_CONTEXT, arguments).await, - "recall by a peer that is not the route's caller", + session + .adapter + .invoke_tool(RECALL_CONTEXT, arguments) + .await, + "recall by a peer admitted to the second Mind", ); - assert_eq!(packed_record_ids(&result), ["rec_market", "rec_north_gate"]); + assert_eq!(packed_record_ids(&result), ["rec_market_two", "rec_north_gate_two"]); assert_eq!( packed_knowledge_ids(&result), - [CARRIER_TWO], + [CARRIER], "the peer's own knowledge_read grant fills the slot from its own route: {result}" ); } @@ -964,7 +1054,6 @@ async fn another_admitted_peer_recalls_its_knowledge_slot_under_a_wired_route() #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn the_route_caller_without_knowledge_read_recalls_with_an_empty_slot() { let fixture = Fixture::open().await; - fixture.seed_carrier().await; fixture.revoke("grt_knowledge").await; let (_dir, serve) = fixture.serve(); let surface = surface( @@ -1009,7 +1098,6 @@ async fn the_route_caller_without_knowledge_read_recalls_with_an_empty_slot() { #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn remote_consumer_deliberates_through_the_composed_surface() { let fixture = Fixture::open().await; - fixture.seed_carrier().await; let pool = fixture.store.pool(); let (_dir, serve) = fixture.serve(); let providers = MindProviders { @@ -1070,7 +1158,6 @@ async fn deliberation_session( policy: Arc, ) -> (TempDir, MindcoreServe, Session) { let fixture = Fixture::open().await; - fixture.seed_carrier().await; let (dir, serve) = fixture.serve(); let surface = surface( &serve, @@ -1173,7 +1260,6 @@ async fn a_deliberation_judgment_identity_follows_the_attempt_content() { #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn remote_consumer_holds_a_deliberation_with_a_valid_judgment() { let fixture = Fixture::open().await; - fixture.seed_carrier().await; let pool = fixture.store.pool(); let (_dir, serve) = fixture.serve(); let providers = MindProviders { @@ -1222,7 +1308,6 @@ async fn remote_consumer_holds_a_deliberation_with_a_valid_judgment() { #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn remote_consumer_settles_a_deliberation_with_a_valid_judgment() { let fixture = Fixture::open().await; - fixture.seed_carrier().await; let pool = fixture.store.pool(); let (_dir, serve) = fixture.serve(); let providers = MindProviders { @@ -1314,16 +1399,15 @@ fn assert_judgment(response: &Value, outcome: &str) { ); } -/// One surface, two principals: each authenticated peer routes to its own collection and settles -/// onto its own carrier entry, and neither call writes the other principal's carrier. A holder the -/// routed collection does not hold is refused and writes nothing anywhere. +/// One surface, two admitted Minds: each peer's call names its own space id and settles the +/// cognition onto its own carrier entry, and neither call writes the other Mind's carrier. The +/// `space_id` the request carries decides the collection, so the registry row is the only route. #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn two_routed_principals_settle_onto_their_own_carriers() { +async fn two_minds_settle_onto_their_own_carriers() { let fixture = Fixture::open().await; - fixture.seed_carrier().await; - fixture.seed_carrier_in(COLLECTION_TWO, CARRIER_TWO).await; + fixture.seed_second_mind().await; fixture - .grant( + .grant_in_second( "grt_settle_peer_two", PEER_TWO_PRINCIPAL, &["recall", "knowledge_read", "knowledge_write"], @@ -1331,11 +1415,7 @@ async fn two_routed_principals_settle_onto_their_own_carriers() { .await; let pool = fixture.store.pool(); let (_dir, serve) = fixture.serve(); - let mut workflow_routes = routes(&[PRINCIPAL]); - workflow_routes.insert( - PEER_TWO_PRINCIPAL.to_string(), - KnowledgeScope::new(COLLECTION_TWO), - ); + let workflow_routes = routes(&[PRINCIPAL]); let mut faces = faces( hello("runtime", &[]), None, @@ -1350,7 +1430,7 @@ async fn two_routed_principals_settle_onto_their_own_carriers() { let surface = surface(&serve, faces); let first = connect(&surface, &[DELIBERATE, RECALL_CONTEXT]).await; - let untouched = collection_state(&pool, COLLECTION_TWO, CARRIER_TWO).await; + let untouched = collection_state(&pool, COLLECTION_TWO, CARRIER).await; let settled = expect_ok( first .adapter @@ -1367,7 +1447,7 @@ async fn two_routed_principals_settle_onto_their_own_carriers() { ); assert_eq!(carrier_revision(&pool, COLLECTION, CARRIER).await, 2); assert_eq!( - carrier_revision(&pool, COLLECTION_TWO, CARRIER_TWO).await, + carrier_revision(&pool, COLLECTION_TWO, CARRIER).await, 1, "the second principal's carrier keeps its seeded revision" ); @@ -1376,13 +1456,13 @@ async fn two_routed_principals_settle_onto_their_own_carriers() { [PRINCIPAL] ); assert!( - carrier_assessors(&pool, COLLECTION_TWO, CARRIER_TWO) + carrier_assessors(&pool, COLLECTION_TWO, CARRIER) .await .is_empty(), "the second collection carries no assessment" ); assert_eq!( - collection_state(&pool, COLLECTION_TWO, CARRIER_TWO).await, + collection_state(&pool, COLLECTION_TWO, CARRIER).await, untouched, "the first call leaves the second collection's rows, carrier revision and update stamp unchanged" ); @@ -1392,19 +1472,19 @@ async fn two_routed_principals_settle_onto_their_own_carriers() { let settled = expect_ok( second .adapter - .invoke_tool(DELIBERATE, deliberate_arguments_for(CARRIER_TWO)) + .invoke_tool(DELIBERATE, deliberate_arguments_in(SPACE_TWO)) .await, "deliberate by the second principal", ); assert_eq!(settled["status"], "settled"); - assert_eq!(settled["record"]["holder"]["id"], CARRIER_TWO); + assert_eq!(settled["record"]["holder"]["id"], CARRIER); assert_eq!(settled["record"]["assessor"]["id"], PEER_TWO_PRINCIPAL); assert_eq!( settled["mind_state_version"], 2, "the second write descends from its own carrier, never the first's" ); assert_eq!( - carrier_revision(&pool, COLLECTION_TWO, CARRIER_TWO).await, + carrier_revision(&pool, COLLECTION_TWO, CARRIER).await, 2 ); assert_eq!( @@ -1413,7 +1493,7 @@ async fn two_routed_principals_settle_onto_their_own_carriers() { "the first principal's carrier keeps the revision its own call left" ); assert_eq!( - carrier_assessors(&pool, COLLECTION_TWO, CARRIER_TWO).await, + carrier_assessors(&pool, COLLECTION_TWO, CARRIER).await, [PEER_TWO_PRINCIPAL] ); assert_eq!( @@ -1446,64 +1526,73 @@ async fn two_routed_principals_settle_onto_their_own_carriers() { [CARRIER], "the first principal's slot lists only its own routed collection: {first_pack}" ); + let mut second_recall = recall_arguments_in(SPACE_TWO); + second_recall["max_tokens"] = json!(4_000); let second_pack = expect_ok( - second.adapter.invoke_tool(RECALL_CONTEXT, recall).await, + second + .adapter + .invoke_tool(RECALL_CONTEXT, second_recall) + .await, "recall by the second principal", ); assert_eq!( packed_record_ids(&second_pack), - ["rec_market", "rec_north_gate"], + ["rec_market_two", "rec_north_gate_two"], "the second principal's memory page is served: {second_pack}" ); assert_eq!( packed_knowledge_ids(&second_pack), - [CARRIER_TWO], - "the second principal's slot lists only its own routed collection: {second_pack}" + [CARRIER], + "the second principal's slot lists only its own Mind's collection: {second_pack}" ); assert_eq!( - second_pack["knowledge"][0]["canonical_name"], "ke_mora's carrier", - "the slot carries this collection's entry, not the other principal's copy: {second_pack}" + second_pack["knowledge"][0]["canonical_name"], "ke_carrier's carrier", + "the slot carries this collection's entry, not the other Mind's copy: {second_pack}" ); let first_before = collection_state(&pool, COLLECTION, CARRIER).await; - let second_before = collection_state(&pool, COLLECTION_TWO, CARRIER_TWO).await; + let second_before = collection_state(&pool, COLLECTION_TWO, CARRIER).await; + // The retired `holder` member: the closed argument object refuses it before any carrier access. + let mut with_holder = deliberate_arguments(); + with_holder["holder"] = json!({ "kind": "knowledge_entry", "namespace": "mindcore", "id": CARRIER }); let reject = expect_reject( first .adapter - .invoke_tool(DELIBERATE, deliberate_arguments_for(CARRIER_TWO)) + .invoke_tool(DELIBERATE, with_holder) .await, - "deliberate by the first principal naming the second principal's holder", + "deliberate still naming the retired holder member", ); assert_eq!( reject.code, - SpokeRejectCode::KnowledgeEntryNotFound, - "the routed collection holds no such holder: {reject:?}" - ); - assert!( - reject.message.contains(CARRIER_TWO), - "the refusal answers the holder the request named: {reject:?}" + SpokeRejectCode::InvalidInput, + "a retired holder member is the closed object's unknown-field refusal: {reject:?}" ); assert_eq!( collection_state(&pool, COLLECTION, CARRIER).await, first_before, - "a foreign holder settles nothing in the caller's own collection" + "a refused write settles nothing in either collection" ); assert_eq!( - collection_state(&pool, COLLECTION_TWO, CARRIER_TWO).await, + collection_state(&pool, COLLECTION_TWO, CARRIER).await, second_before, - "nor in the collection that holder lives in" ); } -/// A principal the host did not route reaches no carrier: a peer holding `recall` and both -/// knowledge grants in the space is still refused, target-free, and nothing is written; the same -/// peer still recalls its memory, with an empty knowledge slot. +/// A space that is no Mind — grants live, no registry row — reaches no carrier: a peer holding +/// `recall` and both knowledge grants in it is still refused, target-free, and nothing is written; +/// the same peer still recalls its memory there, with an empty knowledge slot. #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn a_peer_without_a_route_cannot_write_the_carrier() { +async fn a_space_with_no_registry_row_reaches_no_carrier() { let fixture = Fixture::open().await; - fixture.seed_carrier().await; + // The second space without its Mind: the space, subjects and grants live, but no registry row. + fixture.seed_second_mind().await; + sqlx::query("DELETE FROM minds WHERE space_id = ?") + .bind(SPACE_TWO) + .execute(&fixture.store.pool()) + .await + .expect("drop the registry row"); fixture - .grant( + .grant_in_second( "grt_route_peer_two", PEER_TWO_PRINCIPAL, &["recall", "knowledge_read", "knowledge_write"], @@ -1527,16 +1616,14 @@ async fn a_peer_without_a_route_cannot_write_the_carrier() { let reject = expect_reject( session .adapter - .invoke_tool(DELIBERATE, deliberate_arguments()) + .invoke_tool(DELIBERATE, deliberate_arguments_in(SPACE_TWO)) .await, - "deliberate by a peer without a knowledge route", + "deliberate by a peer in a space with no registry row", ); assert_eq!(reject.code, SpokeRejectCode::NotAuthorized); assert!( - reject - .message - .contains("principal has no workflow knowledge route"), - "the refusal is the missing-route rule: {reject:?}" + reject.message.contains("the caller is not admitted to the named mind"), + "the refusal is the admission rule: {reject:?}" ); let refusal = format!("{reject:?}"); assert!( @@ -1556,20 +1643,20 @@ async fn a_peer_without_a_route_cannot_write_the_carrier() { "a refused carrier write leaves the entry untouched" ); - let mut arguments = recall_arguments(); + let mut arguments = recall_arguments_in(SPACE_TWO); arguments["max_tokens"] = json!(4_000); let recalled = expect_ok( session.adapter.invoke_tool(RECALL_CONTEXT, arguments).await, - "recall by a peer without a knowledge route", + "recall by a peer in a space with no registry row", ); assert_eq!( packed_record_ids(&recalled), - ["rec_market", "rec_north_gate"] + ["rec_market_two", "rec_north_gate_two"] ); assert_eq!( recalled["knowledge"], json!([]), - "an unrouted peer reads its memory with an empty knowledge slot" + "a space with no registry row reads its memory with an empty knowledge slot" ); } @@ -1883,92 +1970,8 @@ async fn an_unserved_tool_answers_op_unsupported() { ); } -/// Advertisement honesty for the deliberation route: a surface assembled without a workflow caller -/// installs no `deliberate` handler, advertises none, and answers the invoke with -/// `op_unsupported` even when the dialer claims the id. -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn an_unwired_deliberation_route_is_neither_advertised_nor_served() { - let fixture = Fixture::open().await; - let (_dir, serve) = fixture.serve(); - let surface = surface( - &serve, - faces( - hello("runtime", &[]), - None, - MindProviders::default(), - routes(&[]), - ), - ); - assert!( - !capabilities(&surface).contains(&DELIBERATE), - "an unwired deliberation route is never advertised: {:?}", - capabilities(&surface) - ); - assert!( - !capabilities(&surface).contains(&CAPABILITY_SPOKE_JUDGMENT), - "no `deliberate` registration, so no judgment family is advertised: {:?}", - capabilities(&surface) - ); - - let session = connect(&surface, &[DELIBERATE]).await; - assert_wire_deny( - session - .adapter - .invoke_tool(DELIBERATE, deliberate_arguments()) - .await, - DELIBERATE, - "op_unsupported", - ); -} - -/// A host registration cannot restore the unwired route: the reserved id is dropped from the -/// final registration set, so it is neither advertised nor installed. -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn a_host_registration_cannot_restore_an_unwired_deliberation_route() { - let fixture = Fixture::open().await; - let (_dir, serve) = fixture.serve(); - let mut faces = faces( - hello("runtime", &[]), - None, - MindProviders::default(), - routes(&[]), - ); - faces.tools = vec![ToolRegistration::new( - deliberate_descriptor(), - |_responder| { - let handler: ToolHandler = - Arc::new(|arguments: Value| Box::pin(async move { spoke_ok(arguments) })); - handler - }, - )]; - let surface = surface(&serve, faces); - - assert!( - !capabilities(&surface).contains(&DELIBERATE), - "a host registration cannot re-advertise the unwired route: {:?}", - capabilities(&surface) - ); - assert!( - surface - .manifest - .tools - .iter() - .all(|tool| tool.capability_id.as_str() != DELIBERATE), - "the reserved descriptor is dropped from the manifest" - ); - - let session = connect(&surface, &[DELIBERATE]).await; - assert_wire_deny( - session - .adapter - .invoke_tool(DELIBERATE, deliberate_arguments()) - .await, - DELIBERATE, - "op_unsupported", - ); -} - /// One shared-source entry the adoption copies: a note whose summary names what the source holds. + fn shared_entry(entry_id: &str, summary: &str) -> KnowledgeEntry { serde_json::from_value(json!({ "schema_version": 1, diff --git a/crates/mindcore-runtime/tests/surface.rs b/crates/mindcore-runtime/tests/surface.rs index 2379b4ea..a28a6f39 100644 --- a/crates/mindcore-runtime/tests/surface.rs +++ b/crates/mindcore-runtime/tests/surface.rs @@ -2,7 +2,7 @@ //! registrations, the knowledge admission is validated where the face is assembled, and the ports //! compose no baseline provider. -use std::collections::{BTreeMap, HashMap}; +use std::collections::HashMap; use std::sync::{Arc, Mutex}; use async_trait::async_trait; @@ -167,11 +167,6 @@ fn adoption_source() -> AdoptionRoute { } } -/// The host's route map: its one admitted principal's workflow collection. -fn routes() -> BTreeMap { - BTreeMap::from([("prn_owner".to_string(), KnowledgeScope::new(COLLECTION))]) -} - fn faces(manifest: HostCapabilityManifest) -> ServeFaces { ServeFaces { manifest, @@ -183,7 +178,6 @@ fn faces(manifest: HostCapabilityManifest) -> ServeFaces { principals: principals(), providers: MindProviders::default(), adoption: None, - workflow_routes: routes(), tools: Vec::new(), } } @@ -348,54 +342,9 @@ async fn manifest_follows_the_composed_faces() { ); } -/// The host's route map is validated once, where the surface is assembled: an empty principal key, -/// an empty destination collection, or one destination collection claimed by two routes is the -/// host's input error, refused before any port or registration exists. +/// The adoption source is one collection for the whole surface; the source need not hold any row. #[tokio::test] -async fn an_unroutable_destination_is_refused_at_assembly() { - let serve = Fixture::open().await.serve(); - for (routes, message) in [ - ( - BTreeMap::from([(String::new(), KnowledgeScope::new(COLLECTION))]), - "a knowledge route needs a non-empty principal id", - ), - ( - BTreeMap::from([("prn_owner".to_string(), KnowledgeScope::new(""))]), - "the knowledge route for principal prn_owner names an empty collection", - ), - ( - BTreeMap::from([ - ("prn_owner".to_string(), KnowledgeScope::new(COLLECTION)), - ("prn_other".to_string(), KnowledgeScope::new(COLLECTION)), - ]), - "a destination collection is routed to more than one principal", - ), - ] { - let reject = match serve.surface(ServeFaces { - workflow_routes: routes, - ..faces(metadata("runtime")) - }) { - SpokeResult::Reject(reject) => reject, - SpokeResult::Ok(surface) => { - panic!( - "an unroutable destination assembled {:?}", - capabilities(&surface) - ) - } - }; - assert_eq!(reject.code, SpokeRejectCode::InvalidInput); - assert_eq!(reject.message, message); - assert!( - reject.details.is_none(), - "the assembly refusal carries no route details: {reject:?}" - ); - } -} - -/// The adoption source is one collection for the whole surface. Beside the per-principal routes it -/// assembles, and the source need not hold any row. -#[tokio::test] -async fn an_adoption_source_beside_the_routes_assembles() { +async fn an_adoption_source_assembles() { let serve = Fixture::open().await.serve(); let surface = expect_ok( serve.surface(ServeFaces { @@ -411,44 +360,12 @@ async fn an_adoption_source_beside_the_routes_assembles() { assert!(surface.ports.as_knowledge().is_some()); } -/// The adoption source must differ from every route destination, connected or not: a source that -/// is also a principal's destination would let one principal's write become another's source. -#[tokio::test] -async fn an_adoption_source_matching_a_route_destination_is_refused_at_assembly() { - let serve = Fixture::open().await.serve(); - // An unconnected principal's route is a refusal too: the copy it would write is one no - // knowledge-face read of the sharing principal reaches. - let reject = match serve.surface(ServeFaces { - workflow_routes: BTreeMap::from([ - ("prn_owner".to_string(), KnowledgeScope::new(COLLECTION)), - ("prn_unconnected".to_string(), KnowledgeScope::new("shared")), - ]), - adoption: Some(AdoptionRoute { - scope_id: "spc_shared".to_string(), - source: KnowledgeScope::new("shared"), - }), - ..faces(metadata("runtime")) - }) { - SpokeResult::Reject(reject) => reject, - SpokeResult::Ok(surface) => panic!( - "a route destination became the adoption source {:?}", - capabilities(&surface) - ), - }; - assert_eq!(reject.code, SpokeRejectCode::InvalidInput); - assert!( - reject.details.is_none(), - "the assembly refusal carries no route details: {reject:?}" - ); -} - /// A source naming the collection the knowledge face serves would copy the destination into -/// itself, so assembly refuses it even with no route map at all. +/// itself, so assembly refuses it. #[tokio::test] async fn an_adoption_source_in_the_knowledge_faces_collection_is_refused() { let serve = Fixture::open().await.serve(); let reject = match serve.surface(ServeFaces { - workflow_routes: BTreeMap::new(), adoption: Some(AdoptionRoute { scope_id: "spc_shared".to_string(), source: KnowledgeScope::new(COLLECTION), @@ -863,13 +780,6 @@ fn two_principal_faces(manifest: HostCapabilityManifest) -> ServeFaces { None, ), }), - // One routed principal whose workflow collection is deliberately *not* the one the - // knowledge face serves, and one admitted principal with no workflow route at all: under a - // route-derived destination both copies would land where `knowledge.get` never reads. - workflow_routes: BTreeMap::from([( - "peer-owner".to_string(), - KnowledgeScope::new("workflow-only"), - )]), ..faces(manifest) } } diff --git a/crates/mindcore-spoke/src/workflows.rs b/crates/mindcore-spoke/src/workflows.rs index 5f4f25eb..b6f64e54 100644 --- a/crates/mindcore-spoke/src/workflows.rs +++ b/crates/mindcore-spoke/src/workflows.rs @@ -5,9 +5,6 @@ //! call reads and returns, so an embedder, reasoner or policy hook runs with no //! transaction open and the workflow can revalidate afterwards. -use std::collections::{BTreeMap, BTreeSet}; -use std::sync::Arc; - use async_trait::async_trait; use chrono::Utc; use serde_json::{json, Map, Value}; @@ -30,7 +27,6 @@ use mindcore_base::ids::{SpaceId, SubjectId}; use mindcore_base::ir::{ CandidateState, MemoryJournalRow, MemoryRepository, ReceiptKey, ReceiptRead, ReceiptState, }; -use mindcore_base::knowledge::KnowledgeScope; use mindcore_spi::{ page_fact, snapshot_fact, AbsorbSnapshot, CandidateLifecycle, CaptureOutcome, CapturedCandidate, CitedRecord, DeliberateSnapshot, EmbeddingIdentity, PageFact, PageVector, @@ -57,19 +53,18 @@ const ABSORB_DECISION_OP: &str = "mindcore.absorb.decision"; /// The in-process workflow binding over one SQLite pool. /// -/// `knowledge_routes` maps each admitted principal id to the one collection its workflow calls -/// reach: a principal with no route reads no knowledge and never writes a carrier. `publisher` is +/// Every carrier access resolves through the Mind the request names: a facade +/// handle's bound carrier, or the registry row of the request's `space_id` read +/// on the caller's transaction. `publisher` is /// the host's file medium; the settlement legs require it before they stage anything, and a /// binding without one refuses them with no write at all. pub struct MemoryWorkflowBinding { adapter: MemoryAdapter, pool: SqlitePool, - /// Shared with every other reader of the same validated map — the adoption tool resolves its - /// 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. + /// The served surface binds none; its carrier access resolves the registry + /// row of the request's `space_id` instead. carrier_binding: Option<(String, String, String)>, } @@ -81,7 +76,6 @@ impl MemoryWorkflowBinding { Self { adapter: MemoryAdapter::new(reflections), pool, - knowledge_routes: Arc::new(BTreeMap::new()), publisher: None, carrier_binding: None, } @@ -268,52 +262,6 @@ impl MemoryWorkflowBinding { Ok(settled) } - /// Bind the host's route map: each exact principal id to the collection its workflow calls - /// reach. - /// - /// The map is the workflow collection allowlist, so a route need not name a collection that - /// already holds rows. An empty key, an empty destination collection, or one collection named by - /// two routes is refused with `InvalidInput`, so surface assembly fails instead of serving a - /// binding whose map must still be completed. A destination collection is one principal's - /// carrier collection, so a repeat would let one routed principal reach another's carriers. A - /// map cannot repeat a key, and `KnowledgeScope` is not a wire `Scope`, so no admission call - /// applies. - /// - /// The map is shared, not copied: the caller holds the same `Arc` and reads it for anything else - /// that must resolve a destination (the adoption tool), so one validated map has one content. - pub fn with_knowledge_routes( - mut self, - routes: Arc>, - ) -> Result { - let invalid = |message: String| SpokeReject { - code: SpokeRejectCode::InvalidInput, - message, - details: None, - }; - for (principal, scope) in routes.iter() { - if principal.is_empty() { - return Err(invalid( - "a knowledge route needs a non-empty principal id".to_string(), - )); - } - if scope.collection.is_empty() { - return Err(invalid(format!( - "the knowledge route for principal {principal} names an empty collection" - ))); - } - } - let mut destinations = BTreeSet::new(); - for scope in routes.values() { - if !destinations.insert(scope.collection.as_str()) { - return Err(invalid( - "a destination collection is routed to more than one principal".to_string(), - )); - } - } - self.knowledge_routes = routes; - Ok(self) - } - /// Every live-admission candidate of `space_id`, read on `tx`. async fn space_grants( &self, @@ -327,20 +275,11 @@ impl MemoryWorkflowBinding { admission::wire_grants(&rows).map_err(|reject| SpiError::Settlement(reject.into_spoke())) } - /// The collection route the host configured for `principal`, by its exact id. - /// - /// The one lookup both the carrier write and the recall slot use, so two calls for the same - /// admitted principal can never reach different collections. Borrowed, never cloned: the - /// route map is immutable for the binding's lifetime. - fn knowledge_route(&self, principal: &Principal) -> Option<&KnowledgeScope> { - self.knowledge_routes.get(principal_id(principal)) - } - - /// 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. + /// Bind the carrier its row states, for the facade handle that resolved the + /// Mind's registry row at open: `with_carrier_collection(space_id, + /// collection, carrier_entry_id)` pins one space's deliberation to it. The + /// served surface binds none; its carrier access reads the registry row on + /// the caller's transaction. #[must_use] pub fn with_carrier_collection( mut self, @@ -357,15 +296,27 @@ impl MemoryWorkflowBinding { } /// 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> { + /// collection first, and otherwise the registry row of `space_id`, read on + /// the caller's transaction. A `space_id` with no row answers `None`, so a + /// carrier write refuses before any entry is read, exactly as an + /// unadmitted Mind answers `memory.spaces.list` nothing. + async fn carrier_collection( + &self, + tx: &mut Tx<'_>, + space_id: &str, + ) -> Result, SpiError> { if let Some((bound_space, collection, _)) = &self.carrier_binding { if bound_space == space_id { - return Some(collection.as_str()); + return Ok(Some(collection.clone())); } } - self.knowledge_route(principal) - .map(|route| route.collection.as_str()) + sqlx::query_scalar::<_, String>( + "SELECT knowledge_collection FROM minds WHERE space_id = ?", + ) + .bind(space_id) + .fetch_optional(&mut **tx) + .await + .map_err(|error| internal(format!("the mind registry could not be read: {error}"))) } /// A bound carrier is the only carrier this binding serves in its space: a @@ -392,19 +343,20 @@ impl MemoryWorkflowBinding { /// `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 - /// missing grant, so a peer never learns whether another principal has a route. + /// space with no registry row is the admission refusal before any carrier access: it is as + /// target-free as a missing grant, so a peer never learns whether the named Mind exists. async fn admitted_collection( &self, tx: &mut Tx<'_>, principal: &Principal, space_id: &str, capabilities: &[&str], - ) -> Result<&str, SpiError> { + ) -> Result { let collection = self - .carrier_collection(principal, space_id) + .carrier_collection(tx, space_id) + .await? .ok_or_else(|| { - not_authorized("principal has no workflow knowledge route".to_string()) + SpiError::Settlement(Reject::admission_refusal().into_spoke()) })?; self.adapter .require_space_grants(tx, principal, space_id, capabilities) @@ -437,13 +389,12 @@ impl MemoryWorkflowBinding { } Ok(()) } - - /// Fill the pack's knowledge slot from `principal`'s own routed collection. + /// Fill the pack's knowledge slot from the collection the request's `space_id` names. /// - /// The slot is independent of the memory page: a principal with no route, or without a live - /// [`KNOWLEDGE_READ`] grant in the request's space, reads its records with an empty slot - /// exactly as it would with no route map. A missing route never reveals whether another - /// principal has one. + /// The slot is independent of the memory page: a space with no registry row — a Mind the + /// caller never listed, or none at all — or a caller without a live [`KNOWLEDGE_READ`] grant + /// in the request's space reads its records with an empty slot. A missing row never reveals + /// whether the named Mind exists. /// /// The slot applies the same disclosure predicate as the served knowledge list. This binding /// carries no admitted viewpoint, so an entry a viewpoint-free read hides — an `owner`-private @@ -458,8 +409,8 @@ impl MemoryWorkflowBinding { request: &MemoryRecallRequest, ) -> Result, SpiError> { let Some(collection) = self - .knowledge_route(principal) - .map(|route| route.collection.as_str()) + .carrier_collection(tx, request.space_id.as_str()) + .await? else { return Ok(Vec::new()); }; @@ -474,7 +425,7 @@ impl MemoryWorkflowBinding { } Err(error) => return Err(error), } - match list_entries_in(tx, collection).await { + match list_entries_in(tx, &collection).await { SpokeResult::Ok(entries) => Ok(entries .into_iter() .filter(|entry| knowledge_entry_visible_to_viewpoint(entry, None)) @@ -1157,7 +1108,7 @@ impl WorkflowBinding for MemoryWorkflowBinding { let collection = self .admitted_collection(&mut transaction, principal, space_id, &[KNOWLEDGE_READ]) .await?; - let carrier = match read_entry(&mut transaction, collection, holder.id.as_str()).await { + let carrier = match read_entry(&mut transaction, &collection, holder.id.as_str()).await { SpokeResult::Ok(carrier) => carrier, SpokeResult::Reject(reject) => return Err(SpiError::Settlement(reject)), }; @@ -1248,7 +1199,7 @@ impl WorkflowBinding for MemoryWorkflowBinding { self.revalidate_cited(&mut transaction, principal, space_id, cited) .await?; let header = - match read_carrier_header(&mut *transaction, collection, holder.id.as_str()).await { + match read_carrier_header(&mut *transaction, &collection, holder.id.as_str()).await { SpokeResult::Ok(header) => header, SpokeResult::Reject(reject) => return Err(SpiError::Settlement(reject)), }; @@ -1269,7 +1220,7 @@ impl WorkflowBinding for MemoryWorkflowBinding { } let assigned = match append_cognition( &mut transaction, - collection, + &collection, holder.id.as_str(), current, &record, diff --git a/crates/mindcore-spoke/tests/workflows.rs b/crates/mindcore-spoke/tests/workflows.rs index 1377b173..e7430aed 100644 --- a/crates/mindcore-spoke/tests/workflows.rs +++ b/crates/mindcore-spoke/tests/workflows.rs @@ -203,6 +203,40 @@ impl Harness { .execute(&pool) .await .expect("seed subject"); + // The carrier entry, then the Mind registry row naming it: `minds` keys the pair foreign + // to `knowledge_entries`, so the entry exists before the row references it. The binding + // resolves every carrier access through the row now that the per-principal route map is + // retired. + sqlx::query( + "INSERT INTO knowledge_entries \ + (collection, entry_id, revision, payload, created_at, updated_at) \ + VALUES ('wren', 'ke_wren', 1, ?, ?, ?)", + ) + .bind( + serde_json::json!({ + "schema_version": 1, + "entry_id": "ke_wren", + "entry_type": "character", + "canonical_name": "ke_wren carrier", + "status": "confirmed", + "revision": 1, + "body": {}, + "extensions": {} + }) + .to_string(), + ) + .bind(NOW) + .bind(NOW) + .execute(&pool) + .await + .expect("seed the carrier entry"); + sqlx::query("INSERT INTO minds (space_id, knowledge_collection, carrier_entry_id) VALUES (?, ?, ?)") + .bind(SPACE) + .bind("wren") + .bind("ke_wren") + .execute(&pool) + .await + .expect("seed the mind registry row"); Self { _dir: dir, root, @@ -354,9 +388,7 @@ impl Harness { caller: &str, side_effect: SideEffect, ) -> (SpiMindWorkflows, BoundaryEmbedder) { - let binding = MemoryWorkflowBinding::new(self.pool.clone(), true) - .with_knowledge_routes(routes(&[caller])) - .expect("the fixture route map is valid"); + let binding = MemoryWorkflowBinding::new(self.pool.clone(), true); (SpiMindWorkflows::new(binding), self.embedder(side_effect)) } @@ -751,7 +783,7 @@ async fn knowledge_slot_reads_only_the_bound_collection() { .iter() .map(|entry| entry.entry_id.as_str()) .collect(); - assert_eq!(entries, ["ke_gate", "ke_market"]); + assert_eq!(entries, ["ke_gate", "ke_market", "ke_wren"]); assert_eq!(pack.knowledge[0].revision, Some(1)); assert_eq!( pack.knowledge[0].body.summary.as_deref(), @@ -766,7 +798,9 @@ async fn knowledge_slot_refuses_a_collection_over_the_served_bound() { let harness = Harness::open().await; harness.grant(&["recall"]).await; harness.knowledge_grant(PRINCIPAL).await; - for index in 0..SERVED_KNOWLEDGE_LIST_LIMIT { + // The carrier entry is the collection's first live row, so exactly-at-the-bound means + // SERVED_KNOWLEDGE_LIST_LIMIT - 1 seeded rows beside it. + for index in 0..(SERVED_KNOWLEDGE_LIST_LIMIT - 1) { harness .entry("wren", &format!("ke_{index:04}"), "bounded entry") .await; @@ -848,7 +882,7 @@ async fn knowledge_slot_hides_owner_private_entries() { .collect(); assert_eq!( entries, - ["ke_gate"], + ["ke_gate", "ke_wren"], "an owner-private entry must not reach a pack with no admitted viewpoint" ); } @@ -899,7 +933,7 @@ async fn knowledge_slot_omits_a_superseded_entry() { .collect(); assert_eq!( entries, - ["ke_gate"], + ["ke_gate", "ke_wren"], "a superseded entry never reaches the pack, and the private one stays withheld" ); } @@ -1110,10 +1144,13 @@ async fn memory_grant_alone_leaves_the_knowledge_slot_empty() { /// grant but no route of its own reads its records with an empty slot, and the recall is never /// refused for it. #[tokio::test] -async fn an_unrouted_principal_recalls_with_an_empty_slot() { +async fn a_caller_without_knowledge_read_recalls_with_an_empty_slot() { + // Under per-Mind routing there is no per-principal route map: the registry row answers every + // reader of this Mind's space. What still empties the slot is the knowledge grant itself — + // a caller without `knowledge_read` in the space reads its memory page with an empty slot, + // which is exactly the enforcement this test must now pin. let harness = Harness::open().await; harness.grant(&["recall"]).await; - harness.knowledge_grant(PRINCIPAL).await; harness .record( "rec_a", @@ -1122,7 +1159,7 @@ async fn an_unrouted_principal_recalls_with_an_empty_slot() { ) .await; harness.entry("wren", "ke_gate", "closed after dusk").await; - let (workflows, embedder) = harness.binding("prn_2", SideEffect::None); + let (workflows, embedder) = harness.binding(PRINCIPAL, SideEffect::None); let pack = workflows .recall_context( @@ -1135,12 +1172,12 @@ async fn an_unrouted_principal_recalls_with_an_empty_slot() { }, ) .await - .expect("a reader with no route still reads its memory page"); + .expect("a reader without a knowledge grant still reads its memory page"); assert_eq!(record_ids(&pack), ["rec_a"]); assert!( pack.knowledge.is_empty(), - "the routed collection is not this reader's: {:?}", + "no knowledge grant means an empty slot: {:?}", pack.knowledge ); } @@ -2614,9 +2651,7 @@ async fn deliberate_as( assessment_context_id: Option<&str>, ) -> Result { let workflows = SpiMindWorkflows::new( - MemoryWorkflowBinding::new(harness.pool.clone(), true) - .with_knowledge_routes(routes(&[caller])) - .expect("the fixture route map is valid"), + MemoryWorkflowBinding::new(harness.pool.clone(), true), ); let holder_value = cognition_reference(CARRIER); let holder: spoke_schemas::data::cognition::CognitionReference = @@ -2640,8 +2675,12 @@ async fn deliberate_as( evidence: &evidence, timeout, }; + let caller_principal: Principal = serde_json::from_value( + json!({ "principal_id": caller, "extensions": {} }), + ) + .expect("caller principal"); workflows - .deliberate(&principal(), request, None, caps) + .deliberate(&caller_principal, request, None, caps) .await } @@ -2691,17 +2730,17 @@ async fn deliberate_harness() -> Harness { ) .await; harness - .entry("wren", CARRIER, "the warden's north gate") - .await; - harness } fn long_timeout() -> std::time::Duration { std::time::Duration::from_secs(30) } +/// A principal holding no grants in the Mind's space cannot write its carrier: routing keys to +/// the space id, so admission inside the space is the whole boundary and a stranger never reads +/// the snapshot before the refusal. #[tokio::test] -async fn another_principal_cannot_write_the_bound_carrier() { +async fn a_principal_without_grants_cannot_write_the_carrier() { let harness = deliberate_harness().await; let reasoner = DeliberateReasoner::new(promote_verdict(), DeliberateEffect::None, &harness.pool); @@ -2715,7 +2754,7 @@ async fn another_principal_cannot_write_the_bound_carrier() { let error = deliberate_as(&harness, "prn_2", &caps, long_timeout(), None) .await - .expect_err("only the route's caller may write its carrier"); + .expect_err("a stranger in the space may not write its carrier"); let SpiError::Settlement(reject) = error else { panic!("expected a settlement refusal, got {error:?}"); @@ -4178,8 +4217,6 @@ const CANCELLATION_GUARD: Duration = Duration::from_secs(5); /// A binding over `pool` routed like `deliberate_as` routes it. fn settle_binding(pool: &SqlitePool) -> MemoryWorkflowBinding { MemoryWorkflowBinding::new(pool.clone(), true) - .with_knowledge_routes(routes(&[PRINCIPAL])) - .expect("the fixture route map is valid") } fn settle_holder() -> spoke_schemas::data::cognition::CognitionReference { @@ -4494,9 +4531,7 @@ async fn a_request_naming_neither_subject_nor_context_is_refused_before_the_verd ..MindCapabilities::default() }; let workflows = SpiMindWorkflows::new( - MemoryWorkflowBinding::new(harness.pool.clone(), true) - .with_knowledge_routes(routes(&[PRINCIPAL])) - .expect("the fixture route map is valid"), + MemoryWorkflowBinding::new(harness.pool.clone(), true), ); let holder: spoke_schemas::data::cognition::CognitionReference = serde_json::from_value(cognition_reference(CARRIER)).expect("holder"); From 8df0ec8818467e2f65cdfcfee3ca4e24ff9e4f6b Mon Sep 17 00:00:00 2001 From: Tang Bohao Date: Thu, 26 Nov 2026 13:11:15 +0800 Subject: [PATCH 04/27] fix(serving): resolve the deliberate carrier from the Mind registry row MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The served deliberate handler looked the constant carrier id up instead of reading what the Mind's registry row names: it now reads carrier_entry_id from the row of the request's space_id — the same lookup the routing performs — and a space with no row gets the admission refusal. The two-Mind loopback fixture names a deliberately non-canonical carrier id for the second Mind, so settling onto it is the regression, and the two Minds' knowledge slots carry distinguishable content that each recall asserts against, including non-contamination. --- crates/mindcore-runtime/src/lib.rs | 9 ++- crates/mindcore-runtime/src/tools.rs | 62 ++++++++++++++----- crates/mindcore-runtime/src/tools/tests.rs | 58 ++++++++++++++---- crates/mindcore-runtime/tests/loopback.rs | 71 +++++++++++++++------- 4 files changed, 151 insertions(+), 49 deletions(-) diff --git a/crates/mindcore-runtime/src/lib.rs b/crates/mindcore-runtime/src/lib.rs index 58c1f14b..493bf857 100644 --- a/crates/mindcore-runtime/src/lib.rs +++ b/crates/mindcore-runtime/src/lib.rs @@ -145,8 +145,13 @@ impl MindcoreServe { let principals = faces.principals; let workflows = self.workflows(); let engine: Arc = workflows.clone(); - let mut tools = - WorkflowTools::new(engine, Arc::clone(&principals), faces.providers).registrations(); + let mut tools = WorkflowTools::new( + engine, + Arc::clone(&principals), + faces.providers, + self.store.pool(), + ) + .registrations(); tools.extend( faces .tools diff --git a/crates/mindcore-runtime/src/tools.rs b/crates/mindcore-runtime/src/tools.rs index 8a130c2f..c9513035 100644 --- a/crates/mindcore-runtime/src/tools.rs +++ b/crates/mindcore-runtime/src/tools.rs @@ -18,7 +18,6 @@ use serde::de::DeserializeOwned; use serde::Deserialize; use serde_json::{json, Map, Value}; -use mindcore_sqlite::minds::CARRIER_ENTRY_ID; use mindcore_spi::{ AbsorbCandidateOutcome, ContextPack, DeliberateOutcome, DeliberateRequest, DomainLens, Embedder, Evidence, MindCapabilities, MindWorkflows, PolicyHook, Reasoner, SpiError, @@ -26,6 +25,7 @@ use mindcore_spi::{ use spoke_connect::remote::{ConnectResponder, MemoryAdmission, ToolHandler}; use spoke_operations::{SpokeReject, SpokeRejectCode, SpokeResult}; use spoke_schemas::data::cognition::{CognitionReference, CognitionTarget}; +use sqlx::SqlitePool; use spoke_schemas::host_capability_manifest::ToolDescriptor; use spoke_schemas::{MemoryCaptureRequest, MemoryRecallRequest, Principal}; @@ -73,20 +73,23 @@ pub(crate) struct WorkflowTools { workflows: Arc, principals: MemoryAdmission, providers: MindProviders, + pool: SqlitePool, } impl WorkflowTools { /// Bind the tools to one workflow engine, the host's peer-to-principal admission and its - /// providers. + /// providers. `pool` serves the Mind registry reads a carrier resolution needs. pub fn new( workflows: Arc, principals: MemoryAdmission, providers: MindProviders, + pool: SqlitePool, ) -> Self { Self { workflows, principals, providers, + pool, } } @@ -156,6 +159,7 @@ impl WorkflowTools { Arc::clone(&self.workflows), Arc::clone(&self.principals), self.providers.clone(), + self.pool.clone(), capability_id, peer_id, arguments, @@ -167,16 +171,19 @@ impl WorkflowTools { let workflows = Arc::clone(&self.workflows); let principals = Arc::clone(&self.principals); let providers = self.providers.clone(); + let pool = self.pool.clone(); ToolRegistration::new(descriptor, move |responder| { let session: Weak = Arc::downgrade(responder); let workflows = Arc::clone(&workflows); let principals = Arc::clone(&principals); let providers = providers.clone(); + let pool = pool.clone(); let handler: ToolHandler = Arc::new(move |arguments: Value| { let session = session.clone(); let workflows = Arc::clone(&workflows); let principals = Arc::clone(&principals); let providers = providers.clone(); + let pool = pool.clone(); Box::pin(async move { let peer_id = match authenticated_peer(&session) { Ok(peer_id) => peer_id, @@ -186,6 +193,7 @@ impl WorkflowTools { workflows, principals, providers, + pool, capability_id, &peer_id, arguments, @@ -221,6 +229,7 @@ async fn serve( workflows: Arc, principals: MemoryAdmission, providers: MindProviders, + pool: SqlitePool, capability_id: &str, peer_id: &str, arguments: Value, @@ -232,7 +241,7 @@ async fn serve( match capability_id { RECALL_CONTEXT => recall_context(&*workflows, &principal, arguments, &providers).await, ABSORB => absorb(&*workflows, &principal, arguments, &providers).await, - DELIBERATE => deliberate(&*workflows, &principal, arguments, &providers).await, + DELIBERATE => deliberate(&*workflows, &principal, arguments, &providers, &pool).await, other => SpokeResult::Reject(SpokeReject { code: SpokeRejectCode::InvalidInput, message: format!("unknown mindcore tool {other}"), @@ -301,25 +310,42 @@ async fn deliberate( principal: &Principal, arguments: Value, providers: &MindProviders, + pool: &SqlitePool, ) -> SpokeResult { let arguments: DeliberateArguments = match decode(arguments) { Ok(arguments) => arguments, Err(reject) => return SpokeResult::Reject(reject), }; - let evidence: Vec> = arguments - .evidence - .iter() - .map(|evidence| Evidence { - id: evidence.id.as_str(), - text: evidence.text.as_str(), - }) - .collect(); - // The carrier is the Mind's own: its registry row names the one carrier - // entry every Mind is created with, so a peer never names one. + // The carrier is the Mind's own record: the registry row of the request's `space_id` names + // it, the same lookup the routing performs, so a peer never names one. A space with no row + // is the admission refusal — target-free, exactly as the binding answers it. + let carrier_entry_id: Option = match sqlx::query_scalar( + "SELECT carrier_entry_id FROM minds WHERE space_id = ?", + ) + .bind(&arguments.space_id) + .fetch_optional(pool) + .await + { + Ok(carrier_entry_id) => carrier_entry_id, + Err(error) => { + return SpokeResult::Reject(SpokeReject { + code: SpokeRejectCode::InternalError, + message: format!("the mind registry could not be read: {error}"), + details: None, + }) + } + }; + let Some(carrier_entry_id) = carrier_entry_id else { + return SpokeResult::Reject(SpokeReject { + code: SpokeRejectCode::NotAuthorized, + message: "the caller is not admitted to the named mind".into(), + details: None, + }); + }; let holder: CognitionReference = match serde_json::from_value(json!({ "kind": "knowledge_entry", "namespace": "mindcore", - "id": CARRIER_ENTRY_ID, + "id": carrier_entry_id, })) { Ok(holder) => holder, Err(error) => { @@ -330,6 +356,14 @@ async fn deliberate( }) } }; + let evidence: Vec> = arguments + .evidence + .iter() + .map(|evidence| Evidence { + id: evidence.id.as_str(), + text: evidence.text.as_str(), + }) + .collect(); let request = DeliberateRequest { space_id: &arguments.space_id, subject_id: Some(&arguments.subject_id), diff --git a/crates/mindcore-runtime/src/tools/tests.rs b/crates/mindcore-runtime/src/tools/tests.rs index 681a5ef6..16a3f413 100644 --- a/crates/mindcore-runtime/src/tools/tests.rs +++ b/crates/mindcore-runtime/src/tools/tests.rs @@ -130,8 +130,34 @@ fn admission() -> MemoryAdmission { }) } -fn tools(fake: Arc) -> WorkflowTools { - WorkflowTools::new(fake, admission(), MindProviders::default()) +/// A store pool with the `minds` table the carrier resolution reads: the handler looks the +/// carrier entry id up in the registry row of the request's space, so the probe seeds the one +/// row the tests name. +async fn registry_pool() -> SqlitePool { + // One connection only: every pooled connection opens its own in-memory database, so the + // registry row must live on the single connection the probe serves. + let pool = sqlx::sqlite::SqlitePoolOptions::new() + .max_connections(1) + .connect("sqlite::memory:") + .await + .expect("in-memory sqlite"); + sqlx::query( + "CREATE TABLE minds (space_id TEXT PRIMARY KEY, knowledge_collection TEXT NOT NULL, carrier_entry_id TEXT NOT NULL)", + ) + .execute(&pool) + .await + .expect("create minds"); + sqlx::query( + "INSERT INTO minds (space_id, knowledge_collection, carrier_entry_id) VALUES ('spc_1', 'wren', 'ke_wren')", + ) + .execute(&pool) + .await + .expect("seed mind row"); + pool +} + +async fn tools(fake: Arc) -> WorkflowTools { + WorkflowTools::new(fake, admission(), MindProviders::default(), registry_pool().await) } fn expect_ok(result: SpokeResult, context: &str) -> T { @@ -295,6 +321,7 @@ async fn recall_context_round_trips_the_pack() { let value = expect_ok( tools(Arc::clone(&fake)) + .await .call(RECALL_CONTEXT, "peer-driver", recall_arguments()) .await, "recall context", @@ -326,7 +353,7 @@ async fn absorb_round_trips_every_candidate_status() { }, ])); - let tool = tools(Arc::clone(&fake)); + let tool = tools(Arc::clone(&fake)).await; let value = expect_ok( tool.call(ABSORB, "peer-driver", absorb_arguments()).await, "absorb", @@ -373,7 +400,7 @@ async fn absorb_round_trips_every_candidate_status() { #[tokio::test] async fn deliberate_round_trips_every_outcome_branch() { let fake = Arc::new(Fake::default()); - let tool = tools(Arc::clone(&fake)); + let tool = tools(Arc::clone(&fake)).await; fake.reply_deliberate(Ok(DeliberateOutcome::NoChange { verdict: json!({ "recommendation": { "kind": "none" } }), @@ -534,7 +561,7 @@ async fn malformed_arguments_are_invalid_input() { for (case, capability_id, arguments) in cases { let fake = Arc::new(Fake::default()); let reject = expect_reject( - tools(fake) + tools(fake).await .call(capability_id, "peer-driver", arguments) .await, case, @@ -548,6 +575,7 @@ async fn unadmitted_peers_are_not_authorized() { let fake = Arc::new(Fake::default()); let reject = expect_reject( tools(Arc::clone(&fake)) + .await .call(RECALL_CONTEXT, "peer-stranger", recall_arguments()) .await, "stranger", @@ -571,7 +599,7 @@ async fn settlement_refusals_keep_their_code_and_details() { fake.reply_absorb(Err(SpiError::Settlement(refusal.clone()))); let reject = expect_reject( - tools(fake) + tools(fake).await .call(ABSORB, "peer-driver", absorb_arguments()) .await, "settlement refusal", @@ -585,7 +613,7 @@ async fn workflow_failures_map_to_stable_reject_kinds() { let fake = Arc::new(Fake::default()); fake.reply_recall(Err(SpiError::DeadlineExceeded)); let reject = expect_reject( - tools(fake) + tools(fake).await .call(RECALL_CONTEXT, "peer-driver", recall_arguments()) .await, "deadline", @@ -630,7 +658,7 @@ async fn workflow_failures_map_to_stable_reject_kinds() { let fake = Arc::new(Fake::default()); fake.reply_recall(Err(error)); let reject = expect_reject( - tools(fake) + tools(fake).await .call(RECALL_CONTEXT, "peer-driver", recall_arguments()) .await, kind, @@ -655,7 +683,7 @@ async fn workflow_failures_map_to_stable_reject_kinds() { "domain redline on the north gate".into(), ))); let reject = expect_reject( - tools(fake) + tools(fake).await .call(RECALL_CONTEXT, "peer-driver", recall_arguments()) .await, "policy", @@ -683,7 +711,7 @@ async fn workflow_failures_map_to_stable_reject_kinds() { "max_tokens is unsupported".into(), ))); let reject = expect_reject( - tools(fake) + tools(fake).await .call(RECALL_CONTEXT, "peer-driver", recall_arguments()) .await, "invalid input", @@ -697,7 +725,7 @@ async fn workflow_failures_map_to_stable_reject_kinds() { #[tokio::test] async fn advertised_input_schemas_match_the_decoded_arguments() { let fake = Arc::new(Fake::default()); - let tool = tools(Arc::clone(&fake)); + let tool = tools(Arc::clone(&fake)).await; for descriptor in tool.descriptors() { let capability_id = descriptor.capability_id.as_str(); @@ -718,7 +746,13 @@ async fn advertised_input_schemas_match_the_decoded_arguments() { other => panic!("unadvertised tool {other}"), } - let arguments = minimal(&input, &input); + let mut arguments = minimal(&input, &input); + // `deliberate` resolves the carrier from the registry row of the request's space, so the + // manifest-shaped probe names the one Mind this harness seeds. `spc_1` satisfies the + // schema's `minLength` either way, so the shape check is unchanged. + if capability_id == DELIBERATE { + arguments["space_id"] = json!("spc_1"); + } expect_ok( tool.call(capability_id, "peer-driver", arguments.clone()) .await, diff --git a/crates/mindcore-runtime/tests/loopback.rs b/crates/mindcore-runtime/tests/loopback.rs index 00511d37..5990f910 100644 --- a/crates/mindcore-runtime/tests/loopback.rs +++ b/crates/mindcore-runtime/tests/loopback.rs @@ -56,8 +56,12 @@ const SCOPE_ID: &str = "spoke-scope-001"; const COLLECTION: &str = "wren"; /// The carrier entry id every Mind is created with; the wire never names it. const CARRIER: &str = "ke_carrier"; -/// The second Mind's own collection; its carrier entry id is the one every Mind is created with. +/// The second Mind's own collection. const COLLECTION_TWO: &str = "mora"; +/// The second Mind's carrier entry id: deliberately not the production constant, so this fixture +/// is also the regression that a Mind whose row names a different carrier id settles onto that +/// id — and so the two Minds' knowledge content can never be interchangeable. +const CARRIER_TWO: &str = "ke_carrier_mora"; const SPACE: &str = "spc_loopback"; /// The second Mind's space, admitted to the second peer only. const SPACE_TWO: &str = "spc_loopback_two"; @@ -246,16 +250,16 @@ impl Fixture { VALUES (?, ?, 1, ?, ?, ?)", ) .bind(COLLECTION_TWO) - .bind(CARRIER) + .bind(CARRIER_TWO) .bind( json!({ "schema_version": 1, - "entry_id": CARRIER, + "entry_id": CARRIER_TWO, "entry_type": "note", - "canonical_name": format!("{CARRIER}'s carrier"), + "canonical_name": "the second mind's carrier", "status": "confirmed", "revision": 1, - "body": { "summary": "what this holder currently holds" }, + "body": { "summary": "the knowledge of the second mind, not the first" }, "extensions": {}, }) .to_string(), @@ -270,7 +274,7 @@ impl Fixture { ) .bind(SPACE_TWO) .bind(COLLECTION_TWO) - .bind(CARRIER) + .bind(CARRIER_TWO) .execute(&pool) .await .expect("seed the second mind's registry row"); @@ -1043,8 +1047,12 @@ async fn another_admitted_mind_recalls_its_own_knowledge_slot() { assert_eq!(packed_record_ids(&result), ["rec_market_two", "rec_north_gate_two"]); assert_eq!( packed_knowledge_ids(&result), - [CARRIER], - "the peer's own knowledge_read grant fills the slot from its own route: {result}" + [CARRIER_TWO], + "the peer's own knowledge_read grant fills the slot from its own Mind: {result}" + ); + assert_eq!( + result["knowledge"][0]["canonical_name"], "the second mind's carrier", + "the slot carries the second Mind's own content: {result}" ); } @@ -1402,6 +1410,8 @@ fn assert_judgment(response: &Value, outcome: &str) { /// One surface, two admitted Minds: each peer's call names its own space id and settles the /// cognition onto its own carrier entry, and neither call writes the other Mind's carrier. The /// `space_id` the request carries decides the collection, so the registry row is the only route. +/// The second Mind's row names `ke_carrier_mora` — deliberately not the production constant — so +/// settling onto it is also the regression that the carrier id comes from the registry row. #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn two_minds_settle_onto_their_own_carriers() { let fixture = Fixture::open().await; @@ -1430,7 +1440,7 @@ async fn two_minds_settle_onto_their_own_carriers() { let surface = surface(&serve, faces); let first = connect(&surface, &[DELIBERATE, RECALL_CONTEXT]).await; - let untouched = collection_state(&pool, COLLECTION_TWO, CARRIER).await; + let untouched = collection_state(&pool, COLLECTION_TWO, CARRIER_TWO).await; let settled = expect_ok( first .adapter @@ -1447,7 +1457,7 @@ async fn two_minds_settle_onto_their_own_carriers() { ); assert_eq!(carrier_revision(&pool, COLLECTION, CARRIER).await, 2); assert_eq!( - carrier_revision(&pool, COLLECTION_TWO, CARRIER).await, + carrier_revision(&pool, COLLECTION_TWO, CARRIER_TWO).await, 1, "the second principal's carrier keeps its seeded revision" ); @@ -1456,13 +1466,13 @@ async fn two_minds_settle_onto_their_own_carriers() { [PRINCIPAL] ); assert!( - carrier_assessors(&pool, COLLECTION_TWO, CARRIER) + carrier_assessors(&pool, COLLECTION_TWO, CARRIER_TWO) .await .is_empty(), "the second collection carries no assessment" ); assert_eq!( - collection_state(&pool, COLLECTION_TWO, CARRIER).await, + collection_state(&pool, COLLECTION_TWO, CARRIER_TWO).await, untouched, "the first call leaves the second collection's rows, carrier revision and update stamp unchanged" ); @@ -1477,14 +1487,14 @@ async fn two_minds_settle_onto_their_own_carriers() { "deliberate by the second principal", ); assert_eq!(settled["status"], "settled"); - assert_eq!(settled["record"]["holder"]["id"], CARRIER); + assert_eq!(settled["record"]["holder"]["id"], CARRIER_TWO); assert_eq!(settled["record"]["assessor"]["id"], PEER_TWO_PRINCIPAL); assert_eq!( settled["mind_state_version"], 2, "the second write descends from its own carrier, never the first's" ); assert_eq!( - carrier_revision(&pool, COLLECTION_TWO, CARRIER).await, + carrier_revision(&pool, COLLECTION_TWO, CARRIER_TWO).await, 2 ); assert_eq!( @@ -1493,7 +1503,7 @@ async fn two_minds_settle_onto_their_own_carriers() { "the first principal's carrier keeps the revision its own call left" ); assert_eq!( - carrier_assessors(&pool, COLLECTION_TWO, CARRIER).await, + carrier_assessors(&pool, COLLECTION_TWO, CARRIER_TWO).await, [PEER_TWO_PRINCIPAL] ); assert_eq!( @@ -1526,6 +1536,10 @@ async fn two_minds_settle_onto_their_own_carriers() { [CARRIER], "the first principal's slot lists only its own routed collection: {first_pack}" ); + assert_eq!( + first_pack["knowledge"][0]["canonical_name"], "ke_carrier's carrier", + "the first slot is the first Mind's entry: {first_pack}" + ); let mut second_recall = recall_arguments_in(SPACE_TWO); second_recall["max_tokens"] = json!(4_000); let second_pack = expect_ok( @@ -1542,16 +1556,31 @@ async fn two_minds_settle_onto_their_own_carriers() { ); assert_eq!( packed_knowledge_ids(&second_pack), - [CARRIER], - "the second principal's slot lists only its own Mind's collection: {second_pack}" + [CARRIER_TWO], + "the second Mind's slot names its own carrier entry — the regression that the carrier id comes from the registry row, not the production constant: {second_pack}" ); assert_eq!( - second_pack["knowledge"][0]["canonical_name"], "ke_carrier's carrier", - "the slot carries this collection's entry, not the other Mind's copy: {second_pack}" + second_pack["knowledge"][0]["canonical_name"], "the second mind's carrier", + "the second slot carries the second Mind's entry, never the first's: {second_pack}" + ); + assert_eq!( + second_pack["knowledge"][0]["body"]["summary"], "the knowledge of the second mind, not the first", + "the content distinguishes the two Minds: {second_pack}" + ); + let contamination: Vec<&str> = first_pack["knowledge"] + .as_array() + .expect("first knowledge") + .iter() + .filter_map(|entry| entry["entry_id"].as_str()) + .filter(|id| *id == CARRIER_TWO) + .collect(); + assert!( + contamination.is_empty(), + "the first Mind's recall never carries the second Mind's entry: {first_pack}" ); let first_before = collection_state(&pool, COLLECTION, CARRIER).await; - let second_before = collection_state(&pool, COLLECTION_TWO, CARRIER).await; + let second_before = collection_state(&pool, COLLECTION_TWO, CARRIER_TWO).await; // The retired `holder` member: the closed argument object refuses it before any carrier access. let mut with_holder = deliberate_arguments(); with_holder["holder"] = json!({ "kind": "knowledge_entry", "namespace": "mindcore", "id": CARRIER }); @@ -1573,7 +1602,7 @@ async fn two_minds_settle_onto_their_own_carriers() { "a refused write settles nothing in either collection" ); assert_eq!( - collection_state(&pool, COLLECTION_TWO, CARRIER).await, + collection_state(&pool, COLLECTION_TWO, CARRIER_TWO).await, second_before, ); } From 2519e12d6deff3fae33422963fbbfe2c8d9d9669 Mon Sep 17 00:00:00 2001 From: Tang Bohao Date: Thu, 26 Nov 2026 13:19:08 +0800 Subject: [PATCH 05/27] fix(serving): gate deliberate admission before any existence read MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit An admitted peer holding no grants could vary space_id and tell an existing Mind from an absent one: the registry lookup ran before any grant check, so an existing row reached the engine (ReasonerUnavailable) while a missing row answered NotAuthorized. The handler now checks the space-wide knowledge_read grant first, and an ungranted Mind and an absent one are the byte-same NotAuthorized refusal with no details — probed by a test on a reasoner-less host where any leaked path would answer differently. One principal admitted to both Minds now recalls each by its own space_id with the full content triple pinned per Mind, and the unused route-map fixture is gone. --- crates/mindcore-runtime/src/tools.rs | 67 +++++++- crates/mindcore-runtime/src/tools/tests.rs | 21 +++ crates/mindcore-runtime/tests/loopback.rs | 178 +++++++++++++++------ 3 files changed, 213 insertions(+), 53 deletions(-) diff --git a/crates/mindcore-runtime/src/tools.rs b/crates/mindcore-runtime/src/tools.rs index c9513035..d40839a7 100644 --- a/crates/mindcore-runtime/src/tools.rs +++ b/crates/mindcore-runtime/src/tools.rs @@ -316,9 +316,24 @@ async fn deliberate( Ok(arguments) => arguments, Err(reject) => return SpokeResult::Reject(reject), }; + // Admission before existence: a caller without a live `knowledge_read` grant in the request's + // space is refused before any registry row is read, and a space with no row is the same + // refusal — same code, same message, no details — so a caller can never tell an existing + // Mind from an absent one by varying `space_id`. + match admitted_to_mind_space(pool, &arguments.space_id, &principal.principal_id).await { + Ok(true) => {} + Ok(false) => return SpokeResult::Reject(not_admitted_to_mind()), + Err(error) => { + return SpokeResult::Reject(SpokeReject { + code: SpokeRejectCode::InternalError, + message: format!("the mind admission could not be read: {error}"), + details: None, + }) + } + } // The carrier is the Mind's own record: the registry row of the request's `space_id` names // it, the same lookup the routing performs, so a peer never names one. A space with no row - // is the admission refusal — target-free, exactly as the binding answers it. + // is the same admission refusal as a missing grant. let carrier_entry_id: Option = match sqlx::query_scalar( "SELECT carrier_entry_id FROM minds WHERE space_id = ?", ) @@ -336,11 +351,7 @@ async fn deliberate( } }; let Some(carrier_entry_id) = carrier_entry_id else { - return SpokeResult::Reject(SpokeReject { - code: SpokeRejectCode::NotAuthorized, - message: "the caller is not admitted to the named mind".into(), - details: None, - }); + return SpokeResult::Reject(not_admitted_to_mind()); }; let holder: CognitionReference = match serde_json::from_value(json!({ "kind": "knowledge_entry", @@ -383,6 +394,50 @@ async fn deliberate( } } +/// The one refusal a caller without admission and a caller probing an absent Mind share: +/// `NotAuthorized` with the admission message and no details, byte-equal either way. +fn not_admitted_to_mind() -> SpokeReject { + SpokeReject { + code: SpokeRejectCode::NotAuthorized, + message: "the caller is not admitted to the named mind".into(), + details: None, + } +} + +/// One space-wide live grant of `knowledge_read` for `principal_id` in `space_id`: unexpired, +/// unrevoked, subject-wide. A caller holding nothing here is not admitted to the space's Mind +/// at all, so the refusal must come before any read that could reveal whether the Mind exists. +async fn admitted_to_mind_space( + pool: &SqlitePool, + space_id: &str, + principal_id: &str, +) -> Result { + let rows: Vec<(String, Option, Option)> = sqlx::query_as( + "SELECT capabilities_json, expires_at, revoked_at FROM memory_grants \ + WHERE space_id = ? AND principal_id = ? AND subject_id IS NULL", + ) + .bind(space_id) + .bind(principal_id) + .fetch_all(pool) + .await?; + let now = chrono::Utc::now(); + Ok(rows.iter().any(|(capabilities_json, expires_at, revoked_at)| { + if revoked_at.is_some() { + return false; + } + let expired = expires_at + .as_deref() + .and_then(|expiry| chrono::DateTime::parse_from_rfc3339(expiry).ok()) + .is_some_and(|expiry| expiry <= now); + if expired { + return false; + } + serde_json::from_str::>(capabilities_json) + .map(|capabilities| capabilities.iter().any(|cap| cap == "knowledge_read")) + .unwrap_or(false) + })) +} + fn absorb_outcome(outcome: AbsorbCandidateOutcome) -> Value { match outcome { AbsorbCandidateOutcome::Pending { candidate_id } => { diff --git a/crates/mindcore-runtime/src/tools/tests.rs b/crates/mindcore-runtime/src/tools/tests.rs index 16a3f413..ab7c0e83 100644 --- a/crates/mindcore-runtime/src/tools/tests.rs +++ b/crates/mindcore-runtime/src/tools/tests.rs @@ -153,6 +153,27 @@ async fn registry_pool() -> SqlitePool { .execute(&pool) .await .expect("seed mind row"); + // The admission probe reads live grants in the request's space; the probe principal holds a + // space-wide `knowledge_read` grant here. + sqlx::query( + "CREATE TABLE memory_grants (\ + grant_id TEXT PRIMARY KEY, space_id TEXT NOT NULL, subject_id TEXT, \ + principal_id TEXT NOT NULL, capabilities_json TEXT NOT NULL, \ + context_ids_json TEXT NOT NULL, shared_access INTEGER NOT NULL, \ + expires_at TEXT, revoked_at TEXT, revision INTEGER NOT NULL, created_at TEXT NOT NULL)", + ) + .execute(&pool) + .await + .expect("create memory_grants"); + sqlx::query( + "INSERT INTO memory_grants \ + (grant_id, space_id, subject_id, principal_id, capabilities_json, \ + context_ids_json, shared_access, expires_at, revoked_at, revision, created_at) \ + VALUES ('grt_probe', 'spc_1', NULL, 'prn_driver', '[\"knowledge_read\"]', '[]', 0, NULL, NULL, 1, '2026-11-21T00:00:00Z')", + ) + .execute(&pool) + .await + .expect("seed probe grant"); pool } diff --git a/crates/mindcore-runtime/tests/loopback.rs b/crates/mindcore-runtime/tests/loopback.rs index 5990f910..eeade6a8 100644 --- a/crates/mindcore-runtime/tests/loopback.rs +++ b/crates/mindcore-runtime/tests/loopback.rs @@ -646,13 +646,11 @@ impl PolicyHook for HoldingPolicy { } } -/// The host's side of the surface. `routes` is the retired per-principal route map the binding no -/// longer reads: the registry row decides every collection, so callers pass it and it is ignored. +/// The host's side of the surface. fn faces( manifest: HostCapabilityManifest, memory: Option>, providers: MindProviders, - _routes: BTreeMap, ) -> ServeFaces { ServeFaces { manifest, @@ -668,14 +666,6 @@ fn faces( } } -/// A retired route map shell: the registry row replaced routing, so this only keeps the call -/// sites shaped as they were. -fn routes(principals: &[&str]) -> BTreeMap { - principals - .iter() - .map(|principal| ((*principal).to_string(), KnowledgeScope::new(COLLECTION))) - .collect() -} fn surface(serve: &MindcoreServe, faces: ServeFaces) -> MindcoreSurface { expect_ok(serve.surface(faces), "assemble the served surface") @@ -964,7 +954,6 @@ async fn remote_consumer_recalls_context_through_the_composed_surface() { hello("runtime", &["spoke-baseline"]), None, MindProviders::default(), - routes(&[]), ), ); @@ -1028,7 +1017,6 @@ async fn another_admitted_mind_recalls_its_own_knowledge_slot() { hello("runtime", &[]), None, MindProviders::default(), - routes(&[PRINCIPAL]), ); faces.principals = two_principal_admission(); let surface = surface(&serve, faces); @@ -1054,6 +1042,11 @@ async fn another_admitted_mind_recalls_its_own_knowledge_slot() { result["knowledge"][0]["canonical_name"], "the second mind's carrier", "the slot carries the second Mind's own content: {result}" ); + assert_eq!( + result["knowledge"][0]["body"]["summary"], + "the knowledge of the second mind, not the first", + "the slot carries the second Mind's own summary: {result}" + ); } /// A configured route never narrows recall's authorization: the route's caller keeps the memory @@ -1070,7 +1063,6 @@ async fn the_route_caller_without_knowledge_read_recalls_with_an_empty_slot() { hello("runtime", &[]), None, MindProviders::default(), - routes(&[PRINCIPAL]), ), ); assert!( @@ -1114,7 +1106,7 @@ async fn remote_consumer_deliberates_through_the_composed_surface() { }; let surface = surface( &serve, - faces(hello("runtime", &[]), None, providers, routes(&[PRINCIPAL])), + faces(hello("runtime", &[]), None, providers), ); assert!( capabilities(&surface).contains(&DELIBERATE), @@ -1177,7 +1169,6 @@ async fn deliberation_session( policy_hook: Some(policy), ..MindProviders::default() }, - routes(&[PRINCIPAL]), ), ); let session = connect(&surface, &[DELIBERATE]).await; @@ -1277,7 +1268,7 @@ async fn remote_consumer_holds_a_deliberation_with_a_valid_judgment() { }; let surface = surface( &serve, - faces(hello("runtime", &[]), None, providers, routes(&[PRINCIPAL])), + faces(hello("runtime", &[]), None, providers), ); let session = connect(&surface, &[DELIBERATE]).await; @@ -1325,7 +1316,7 @@ async fn remote_consumer_settles_a_deliberation_with_a_valid_judgment() { }; let surface = surface( &serve, - faces(hello("runtime", &[]), None, providers, routes(&[PRINCIPAL])), + faces(hello("runtime", &[]), None, providers), ); let session = connect(&surface, &[DELIBERATE]).await; @@ -1425,7 +1416,6 @@ async fn two_minds_settle_onto_their_own_carriers() { .await; let pool = fixture.store.pool(); let (_dir, serve) = fixture.serve(); - let workflow_routes = routes(&[PRINCIPAL]); let mut faces = faces( hello("runtime", &[]), None, @@ -1434,7 +1424,6 @@ async fn two_minds_settle_onto_their_own_carriers() { policy_hook: Some(Arc::new(AutoPolicy)), ..MindProviders::default() }, - workflow_routes, ); faces.principals = two_principal_admission(); let surface = surface(&serve, faces); @@ -1636,7 +1625,6 @@ async fn a_space_with_no_registry_row_reaches_no_carrier() { reasoner: Some(Arc::new(NoChangeReasoner)), ..MindProviders::default() }, - routes(&[PRINCIPAL]), ); faces.principals = two_principal_admission(); let surface = surface(&serve, faces); @@ -1689,6 +1677,121 @@ async fn a_space_with_no_registry_row_reaches_no_carrier() { ); } +/// Existence privacy: a peer admitted to nothing — no grant in either space — cannot tell an +/// existing Mind from an absent one. Both `space_id` variations are answered with the same +/// refusal, byte-equal, and neither call reaches the reasoner: the reasoner is absent entirely +/// here, so a call that escaped the admission gate would surface `ReasonerUnavailable` instead. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn deliberate_cannot_distinguish_an_absent_mind_from_an_ungranted_one() { + let fixture = Fixture::open().await; + fixture.seed_second_mind().await; + let (_dir, serve) = fixture.serve(); + // No reasoner: any path that reaches the engine before admission is a different answer. + let mut faces = faces( + hello("runtime", &[]), + None, + MindProviders::default(), + ); + faces.principals = two_principal_admission(); + let surface = surface(&serve, faces); + + let session = connect_as(&surface, &PEER_TWO_SEED, &[DELIBERATE]).await; + let existing = expect_reject( + session + .adapter + .invoke_tool(DELIBERATE, deliberate_arguments_in(SPACE_TWO)) + .await, + "deliberate into an existing Mind the peer holds no grant in", + ); + let absent = expect_reject( + session + .adapter + .invoke_tool(DELIBERATE, deliberate_arguments_in("spc_no_such_mind")) + .await, + "deliberate into a space that is no Mind at all", + ); + assert_eq!(existing.code, SpokeRejectCode::NotAuthorized); + assert_eq!( + existing, absent, + "an ungranted Mind and an absent Mind must be the byte-same refusal" + ); + assert!( + existing.details.is_none(), + "the refusal carries no details either way: {existing:?}" + ); +} + +/// One principal admitted to both Minds: each recall names its own `space_id` and answers that +/// Mind's content — entry id, canonical name and body summary — never the other's. Two different +/// principals would not pin this: a route keyed to the principal would pass either way. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn one_principal_recalls_each_mind_by_its_own_space_id() { + let fixture = Fixture::open().await; + fixture.seed_second_mind().await; + fixture + .grant_in_second( + "grt_shared_peer", + PRINCIPAL, + &["recall", "knowledge_read"], + ) + .await; + let (_dir, serve) = fixture.serve(); + let mut faces = faces( + hello("runtime", &[]), + None, + MindProviders::default(), + ); + faces.principals = principal_admission(); + let surface = surface(&serve, faces); + + let session = connect(&surface, &[RECALL_CONTEXT]).await; + for (space, carrier, name, summary) in [ + (SPACE, CARRIER, "ke_carrier's carrier", "what this holder currently holds"), + ( + SPACE_TWO, + CARRIER_TWO, + "the second mind's carrier", + "the knowledge of the second mind, not the first", + ), + ] { + let mut arguments = recall_arguments_in(space); + arguments["max_tokens"] = json!(4_000); + let pack = expect_ok( + session.adapter.invoke_tool(RECALL_CONTEXT, arguments).await, + &format!("recall {space} by the shared principal"), + ); + assert_eq!( + packed_knowledge_ids(&pack), + [carrier], + "{space}: the slot names this Mind's carrier" + ); + assert_eq!( + pack["knowledge"][0]["canonical_name"], name, + "{space}: the slot is this Mind's canonical name" + ); + assert_eq!( + pack["knowledge"][0]["body"]["summary"], summary, + "{space}: the slot is this Mind's content" + ); + } + let first_pack = { + let mut arguments = recall_arguments_in(SPACE); + arguments["max_tokens"] = json!(4_000); + expect_ok( + session.adapter.invoke_tool(RECALL_CONTEXT, arguments).await, + "recall the first Mind", + ) + }; + assert!( + !first_pack["knowledge"] + .as_array() + .expect("first knowledge") + .iter() + .any(|entry| entry["entry_id"] == CARRIER_TWO), + "the first Mind's recall never carries the second Mind's entry: {first_pack}" + ); +} + /// Advertisement honesty for the optional face: the dialer claims `spoke-memory` in both /// sessions, yet the op is denied while the host attaches no memory service and served verbatim /// once it does. @@ -1702,7 +1805,6 @@ async fn memory_ops_are_served_only_when_the_host_attaches_the_face() { hello("runtime", &["spoke-memory"]), None, MindProviders::default(), - routes(&[]), ), ); assert!( @@ -1725,7 +1827,6 @@ async fn memory_ops_are_served_only_when_the_host_attaches_the_face() { hello("runtime", &["spoke-memory"]), Some(Arc::new(MemoryFace)), MindProviders::default(), - routes(&[]), ), ); assert!( @@ -1772,7 +1873,6 @@ async fn transfer_is_advertised_and_served_when_the_service_reports_all_five() { hello("runtime", &["spoke-memory", "spoke-memory-transfer"]), Some(service), MindProviders::default(), - routes(&[]), ), ); assert!( @@ -1904,7 +2004,6 @@ async fn a_transfer_receipt_is_polled_on_the_same_signed_session() { hello("runtime", &["spoke-memory", "spoke-memory-transfer"]), Some(service), MindProviders::default(), - routes(&[]), ), ); let session = connect(&surface, &["spoke-memory", "spoke-memory-transfer"]).await; @@ -1957,7 +2056,6 @@ async fn the_baseline_face_is_never_composed_or_advertised() { hello("runtime", &["spoke-baseline"]), None, MindProviders::default(), - routes(&[]), ), ); assert!( @@ -1986,7 +2084,6 @@ async fn an_unserved_tool_answers_op_unsupported() { hello("runtime", &[]), None, MindProviders::default(), - routes(&[]), ), ); assert!(!capabilities(&surface).contains(&UNSERVED_TOOL)); @@ -2027,7 +2124,7 @@ fn adopt_request(source_entry_id: &str, source_revision: u64, key: &str) -> Know } /// The fixture's faces with the one shared adoption source attached. -fn adopting_faces(workflow_routes: BTreeMap) -> ServeFaces { +fn adopting_faces() -> ServeFaces { ServeFaces { adoption: Some(AdoptionRoute { scope_id: SHARED_SCOPE.to_string(), @@ -2037,7 +2134,6 @@ fn adopting_faces(workflow_routes: BTreeMap) -> ServeFac hello("runtime", &[]), None, MindProviders::default(), - workflow_routes, ) } } @@ -2197,7 +2293,6 @@ async fn adoption_is_advertised_and_served_only_with_the_face() { hello("runtime", &[]), None, MindProviders::default(), - routes(&[PRINCIPAL]), ), ); assert!( @@ -2228,7 +2323,7 @@ async fn adoption_is_advertised_and_served_only_with_the_face() { ); drop(session); - let attached = surface(&serve, adopting_faces(routes(&[PRINCIPAL]))); + let attached = surface(&serve, adopting_faces()); assert!( capabilities(&attached).contains(&ADOPTION), "a composed adoption face is advertised: {:?}", @@ -2262,7 +2357,7 @@ async fn knowledge_adopt_anchors_the_terminal_and_repeats_idempotently() { let pool = fixture.store.pool(); seed_shared_source(&pool).await; let (_dir, serve) = fixture.serve(); - let surface = surface(&serve, adopting_faces(routes(&[PRINCIPAL]))); + let surface = surface(&serve, adopting_faces()); let session = connect(&surface, &[ADOPTION, "spoke-knowledge"]).await; let dialer = &*session.adapter; let destination = scope_of(SCOPE_ID); @@ -2440,7 +2535,7 @@ async fn knowledge_adopt_refuses_with_the_contract_codes() { seed_shared_source(&pool).await; seed_cycle(&pool).await; let (_dir, serve) = fixture.serve(); - let surface = surface(&serve, adopting_faces(routes(&[PRINCIPAL]))); + let surface = surface(&serve, adopting_faces()); let session = connect(&surface, &[ADOPTION, "spoke-knowledge"]).await; let dialer = &*session.adapter; let destination = scope_of(SCOPE_ID); @@ -2583,7 +2678,7 @@ async fn an_occupied_destination_answers_occupancy_whatever_the_selection_shows( ); let (_dir, serve) = fixture.serve(); let surface_of = |admission: KnowledgeAdmission| { - let mut admitted = adopting_faces(routes(&[PRINCIPAL])); + let mut admitted = adopting_faces(); admitted.admission = admission; surface(&serve, admitted) }; @@ -2746,7 +2841,7 @@ async fn a_retired_destination_occupant_answers_occupancy_over_the_signed_sessio seed_retired_destination(&pool).await; let before = destination_slot(&pool, RETIRED_SLOT).await; let (_dir, serve) = fixture.serve(); - let surface = surface(&serve, adopting_faces(routes(&[PRINCIPAL]))); + let surface = surface(&serve, adopting_faces()); let session = connect(&surface, &[ADOPTION, "spoke-knowledge"]).await; let mut claim = adopt_request(SHARED_ENTRY, 1, "retired-destination"); @@ -2793,7 +2888,7 @@ async fn adoption_refuses_a_terminal_revision_outside_the_served_range() { let pool = fixture.store.pool(); seed_shared_source(&pool).await; let (_dir, serve) = fixture.serve(); - let surface = surface(&serve, adopting_faces(routes(&[PRINCIPAL]))); + let surface = surface(&serve, adopting_faces()); let session = connect(&surface, &[ADOPTION, "spoke-knowledge"]).await; let dialer = &*session.adapter; @@ -2843,7 +2938,6 @@ async fn a_host_registration_reaches_its_handler_over_the_signed_session() { hello("runtime", &[]), None, MindProviders::default(), - routes(&[]), ); faces.tools = vec![ToolRegistration::new( host_tool_descriptor(), @@ -2983,7 +3077,6 @@ async fn retiring_an_identity_clears_its_slot_and_partition() { embedder: Some(embedder.clone()), ..MindProviders::default() }, - routes(&[]), ), ); let session = connect(&surface, &[RECALL_CONTEXT]).await; @@ -3089,7 +3182,6 @@ async fn retiring_a_warm_identity_forces_its_next_query_embed() { embedder: Some(embedder.clone()), ..MindProviders::default() }, - routes(&[]), ), ); let session = connect(&surface, &[RECALL_CONTEXT]).await; @@ -3218,7 +3310,6 @@ async fn history_is_advertised_and_served_only_with_the_face() { hello("runtime", &["spoke-history"]), None, MindProviders::default(), - routes(&[]), ), ); assert!( @@ -3260,7 +3351,6 @@ async fn history_is_advertised_and_served_only_with_the_face() { hello("runtime", &["spoke-history"]), None, MindProviders::default(), - routes(&[]), ); attached.history = true; let attached = surface(&serve, attached); @@ -3311,7 +3401,6 @@ async fn history_replays_prunes_and_refuses_over_a_signed_session() { hello("runtime", &["spoke-history", "spoke-knowledge"]), None, MindProviders::default(), - routes(&[]), ); attached.history = true; let surface = surface(&serve, attached); @@ -3514,7 +3603,6 @@ async fn a_prune_does_not_replay_across_collections_on_one_database() { hello("runtime", &["spoke-history"]), None, MindProviders::default(), - routes(&[]), ); first.history = true; let first_surface = surface(&serve, first); @@ -3534,7 +3622,6 @@ async fn a_prune_does_not_replay_across_collections_on_one_database() { hello("runtime", &["spoke-history"]), None, MindProviders::default(), - routes(&[]), ); second.history = true; second.knowledge = KnowledgeScope::new(COLLECTION_TWO); @@ -3607,7 +3694,6 @@ async fn a_prune_replays_its_recorded_outcome_for_the_same_key() { hello("runtime", &["spoke-history"]), None, MindProviders::default(), - routes(&[]), ); attached.history = true; let surface = surface(&serve, attached); @@ -3745,7 +3831,6 @@ async fn a_prune_replays_its_recorded_outcome_after_the_store_is_reopened() { hello("runtime", &["spoke-history"]), None, MindProviders::default(), - routes(&[]), ); attached.history = true; let surface = surface(&serve, attached); @@ -3786,7 +3871,6 @@ async fn a_prune_replays_its_recorded_outcome_after_the_store_is_reopened() { hello("runtime", &["spoke-history"]), None, MindProviders::default(), - routes(&[]), ); attached.history = true; let surface = surface(&serve, attached); From 7356f534fe7c8c190868c478ef04241a742a6bf0 Mon Sep 17 00:00:00 2001 From: Tang Bohao Date: Thu, 26 Nov 2026 13:27:26 +0800 Subject: [PATCH 06/27] fix(serving): one transaction for mind admission, one liveness rule MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The deliberate handler's own gate re-derived grant liveness and inverted the expiry rule — an unparseable expiry read as live — and read the grants and the registry row in two operations a revocation could slip between. Admission is now admitted_carrier_entry in mindcore-spoke: the grant rows and the registry row are read in one transaction, liveness runs the adapter's own live_grant (unrevoked, unexpired, an expiry that does not parse fails closed), and a missing, revoked, expired or unparseable grant and an absent Mind are all the byte-same refusal. Regressions: a garbled expiry refuses, a grant revoked after the session is established refuses the invoke that follows it. --- crates/mindcore-runtime/src/tools.rs | 83 +++-------------------- crates/mindcore-runtime/tests/loopback.rs | 71 +++++++++++++++++++ crates/mindcore-spoke/src/lib.rs | 2 +- crates/mindcore-spoke/src/workflows.rs | 49 +++++++++++++ 4 files changed, 130 insertions(+), 75 deletions(-) diff --git a/crates/mindcore-runtime/src/tools.rs b/crates/mindcore-runtime/src/tools.rs index d40839a7..b7272d3b 100644 --- a/crates/mindcore-runtime/src/tools.rs +++ b/crates/mindcore-runtime/src/tools.rs @@ -316,42 +316,21 @@ async fn deliberate( Ok(arguments) => arguments, Err(reject) => return SpokeResult::Reject(reject), }; - // Admission before existence: a caller without a live `knowledge_read` grant in the request's - // space is refused before any registry row is read, and a space with no row is the same + // Admission before existence, in one transaction: the grant rows and the registry row are + // read together, so a revocation cannot land between them, and the liveness rule is the + // adapter's own (`live_grant` — unrevoked, unexpired, an unparseable expiry fails closed). + // A missing grant, a revoked or expired one and a space with no registry row are the same // refusal — same code, same message, no details — so a caller can never tell an existing // Mind from an absent one by varying `space_id`. - match admitted_to_mind_space(pool, &arguments.space_id, &principal.principal_id).await { - Ok(true) => {} - Ok(false) => return SpokeResult::Reject(not_admitted_to_mind()), - Err(error) => { - return SpokeResult::Reject(SpokeReject { - code: SpokeRejectCode::InternalError, - message: format!("the mind admission could not be read: {error}"), - details: None, - }) - } - } - // The carrier is the Mind's own record: the registry row of the request's `space_id` names - // it, the same lookup the routing performs, so a peer never names one. A space with no row - // is the same admission refusal as a missing grant. - let carrier_entry_id: Option = match sqlx::query_scalar( - "SELECT carrier_entry_id FROM minds WHERE space_id = ?", + let carrier_entry_id = match mindcore_spoke::admitted_carrier_entry( + pool, + &principal.principal_id, + &arguments.space_id, ) - .bind(&arguments.space_id) - .fetch_optional(pool) .await { Ok(carrier_entry_id) => carrier_entry_id, - Err(error) => { - return SpokeResult::Reject(SpokeReject { - code: SpokeRejectCode::InternalError, - message: format!("the mind registry could not be read: {error}"), - details: None, - }) - } - }; - let Some(carrier_entry_id) = carrier_entry_id else { - return SpokeResult::Reject(not_admitted_to_mind()); + Err(reject) => return SpokeResult::Reject(reject), }; let holder: CognitionReference = match serde_json::from_value(json!({ "kind": "knowledge_entry", @@ -394,50 +373,6 @@ async fn deliberate( } } -/// The one refusal a caller without admission and a caller probing an absent Mind share: -/// `NotAuthorized` with the admission message and no details, byte-equal either way. -fn not_admitted_to_mind() -> SpokeReject { - SpokeReject { - code: SpokeRejectCode::NotAuthorized, - message: "the caller is not admitted to the named mind".into(), - details: None, - } -} - -/// One space-wide live grant of `knowledge_read` for `principal_id` in `space_id`: unexpired, -/// unrevoked, subject-wide. A caller holding nothing here is not admitted to the space's Mind -/// at all, so the refusal must come before any read that could reveal whether the Mind exists. -async fn admitted_to_mind_space( - pool: &SqlitePool, - space_id: &str, - principal_id: &str, -) -> Result { - let rows: Vec<(String, Option, Option)> = sqlx::query_as( - "SELECT capabilities_json, expires_at, revoked_at FROM memory_grants \ - WHERE space_id = ? AND principal_id = ? AND subject_id IS NULL", - ) - .bind(space_id) - .bind(principal_id) - .fetch_all(pool) - .await?; - let now = chrono::Utc::now(); - Ok(rows.iter().any(|(capabilities_json, expires_at, revoked_at)| { - if revoked_at.is_some() { - return false; - } - let expired = expires_at - .as_deref() - .and_then(|expiry| chrono::DateTime::parse_from_rfc3339(expiry).ok()) - .is_some_and(|expiry| expiry <= now); - if expired { - return false; - } - serde_json::from_str::>(capabilities_json) - .map(|capabilities| capabilities.iter().any(|cap| cap == "knowledge_read")) - .unwrap_or(false) - })) -} - fn absorb_outcome(outcome: AbsorbCandidateOutcome) -> Value { match outcome { AbsorbCandidateOutcome::Pending { candidate_id } => { diff --git a/crates/mindcore-runtime/tests/loopback.rs b/crates/mindcore-runtime/tests/loopback.rs index eeade6a8..919a7445 100644 --- a/crates/mindcore-runtime/tests/loopback.rs +++ b/crates/mindcore-runtime/tests/loopback.rs @@ -1721,6 +1721,77 @@ async fn deliberate_cannot_distinguish_an_absent_mind_from_an_ungranted_one() { ); } +/// Liveness is the adapter's one grant rule: an expiry that does not parse fails closed, so the +/// grant is dead and `deliberate` is the admission refusal, not a read of the carrier. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn a_grant_with_an_unparseable_expiry_is_dead_to_deliberate() { + let fixture = Fixture::open().await; + // Corrupt the seeded knowledge grant's expiry in place: it can no longer be read as a time. + sqlx::query("UPDATE memory_grants SET expires_at = 'not-a-time' WHERE grant_id = 'grt_knowledge'") + .execute(&fixture.store.pool()) + .await + .expect("corrupt the expiry"); + let (_dir, serve) = fixture.serve(); + let mut faces = faces( + hello("runtime", &[]), + None, + MindProviders::default(), + ); + faces.principals = principal_admission(); + let surface = surface(&serve, faces); + + let session = connect(&surface, &[DELIBERATE]).await; + let reject = expect_reject( + session + .adapter + .invoke_tool(DELIBERATE, deliberate_arguments()) + .await, + "deliberate with a garbled expiry", + ); + assert_eq!(reject.code, SpokeRejectCode::NotAuthorized); + assert!( + reject.details.is_none(), + "an unparseable expiry fails closed as the plain admission refusal: {reject:?}" + ); +} + +/// Revocation is final at call time: the grant is live when the session is established, revoked +/// before the invoke, and the call answers the admission refusal — the admission reads its +/// state once, on its own transaction, and never a cached yes. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn a_grant_revoked_before_the_call_refuses_deliberate() { + let fixture = Fixture::open().await; + let pool = fixture.store.pool(); + let (_dir, serve) = fixture.serve(); + let mut faces = faces( + hello("runtime", &[]), + None, + MindProviders::default(), + ); + faces.principals = principal_admission(); + let surface = surface(&serve, faces); + + let session = connect(&surface, &[DELIBERATE]).await; + sqlx::query( + "UPDATE memory_grants SET revoked_at = '2026-11-21T01:00:00Z' WHERE grant_id = 'grt_knowledge'", + ) + .execute(&pool) + .await + .expect("revoke the grant"); + let reject = expect_reject( + session + .adapter + .invoke_tool(DELIBERATE, deliberate_arguments()) + .await, + "deliberate after revocation", + ); + assert_eq!(reject.code, SpokeRejectCode::NotAuthorized); + assert!( + reject.details.is_none(), + "a revoked grant is the plain admission refusal: {reject:?}" + ); +} + /// One principal admitted to both Minds: each recall names its own `space_id` and answers that /// Mind's content — entry id, canonical name and body summary — never the other's. Two different /// principals would not pin this: a route keyed to the principal would pass either way. diff --git a/crates/mindcore-spoke/src/lib.rs b/crates/mindcore-spoke/src/lib.rs index 9464088d..31b134cd 100644 --- a/crates/mindcore-spoke/src/lib.rs +++ b/crates/mindcore-spoke/src/lib.rs @@ -23,7 +23,7 @@ mod workflows; pub use serve::{ServedMemory, TransferService}; pub use transfer::OPERATIONS as TRANSFER_OPERATIONS; -pub use workflows::MemoryWorkflowBinding; +pub use workflows::{admitted_carrier_entry, MemoryWorkflowBinding}; pub(crate) use mindcore_base::ids::mint; diff --git a/crates/mindcore-spoke/src/workflows.rs b/crates/mindcore-spoke/src/workflows.rs index b6f64e54..7756d315 100644 --- a/crates/mindcore-spoke/src/workflows.rs +++ b/crates/mindcore-spoke/src/workflows.rs @@ -51,6 +51,55 @@ type JournalPublisher = dyn Fn(&[Value]) -> Result<(), SpiError> + Send + Sync; /// this capture's absorb run decided `Pending` for the ids it names. const ABSORB_DECISION_OP: &str = "mindcore.absorb.decision"; +/// Mind admission for the host-side `deliberate` handler: the caller's grant rows and the +/// registry row read in one transaction, so a revocation cannot land between them, and every +/// liveness decision runs the one grant rule (`live_grant`: unrevoked, unexpired, an +/// unparseable expiry fails closed). Returns the row-named carrier entry id, or the fixed +/// admission refusal — byte-equal whether the Mind exists, the grant is missing, revoked or +/// expired — so an unadmitted caller cannot tell the cases apart. +pub async fn admitted_carrier_entry( + pool: &SqlitePool, + principal_id: &str, + space_id: &str, +) -> Result { + let repository = SqliteMemoryRepository; + let mut conn = pool + .acquire() + .await + .map_err(|e| Reject::internal(format!("the mind admission could not open: {e}")).into_spoke())?; + let mut tx = conn + .begin() + .await + .map_err(|e| Reject::internal(format!("the mind admission could not begin: {e}")).into_spoke())?; + let space = SpaceId::new(space_id.to_string()); + let rows = admission::grants(&repository, &mut tx, &space) + .await + .map_err(Reject::into_spoke)?; + let now = Utc::now(); + let admitted = rows.iter().any(|row| { + row.principal_id.as_str() == principal_id + && row.subject_id.is_none() + && row.capabilities.iter().any(|cap| cap == KNOWLEDGE_READ) + && admission::live_grant(row, now) + }); + if !admitted { + return Err(Reject::admission_refusal().into_spoke()); + } + // `live_grant` is the crate's one grant rule, but it is admission-internal. + // The row read follows in the same transaction: a revocation that commits + // before this statement is already covered by the grant check re-reading on + // its own transaction; one either sees both sides of it or neither. + let row: Option = sqlx::query_scalar( + "SELECT carrier_entry_id FROM minds WHERE space_id = ?", + ) + .bind(space_id) + .fetch_optional(&mut *tx) + .await + .map_err(|e| Reject::internal(format!("the mind admission could not be read: {e}")).into_spoke())?; + let _ = tx.rollback().await; + row.ok_or_else(|| Reject::admission_refusal().into_spoke()) +} + /// The in-process workflow binding over one SQLite pool. /// /// Every carrier access resolves through the Mind the request names: a facade From 548e67b623196bda9e21ec675d6f87014f838c18 Mon Sep 17 00:00:00 2001 From: Tang Bohao Date: Thu, 26 Nov 2026 13:32:34 +0800 Subject: [PATCH 07/27] fix(serving): pre-authorization reads only the caller's own grant rows admitted_carrier_entry no longer loads every principal's rows for the space: the read filters by principal at the query, so a stranger's malformed capabilities_json never reaches the decode, and a decode failure on the caller's own row (InvalidRow) answers the same target-free admission refusal as an absent Mind instead of propagating a storage error. Genuine driver failures stay internal errors. Regression: a malformed grant row on another principal in an existing Mind answers a no-grant caller byte-equal to a nonexistent space. --- crates/mindcore-runtime/tests/loopback.rs | 54 +++++++++++++++++++++++ crates/mindcore-spoke/src/workflows.rs | 15 +++++-- 2 files changed, 66 insertions(+), 3 deletions(-) diff --git a/crates/mindcore-runtime/tests/loopback.rs b/crates/mindcore-runtime/tests/loopback.rs index 919a7445..e4ea8c88 100644 --- a/crates/mindcore-runtime/tests/loopback.rs +++ b/crates/mindcore-runtime/tests/loopback.rs @@ -1721,6 +1721,60 @@ async fn deliberate_cannot_distinguish_an_absent_mind_from_an_ungranted_one() { ); } +/// Pre-authorization reads only the caller's own rows: another principal's malformed grant row +/// in an existing Mind must not leak the space's existence through a storage error. The peer +/// holds no grants anywhere; the malformed row belongs to a stranger in `SPACE_TWO`, and the +/// answer for that space and for a space that is no Mind at all are byte-equal. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn a_strangers_malformed_grant_row_cannot_leak_the_minds_existence() { + let fixture = Fixture::open().await; + fixture.seed_second_mind().await; + sqlx::query( + "INSERT INTO memory_grants \ + (grant_id, space_id, subject_id, principal_id, capabilities_json, \ + context_ids_json, shared_access, expires_at, revoked_at, revision, created_at) \ + VALUES ('grt_malformed_stranger', ?, NULL, 'prn_stranger', 'not-json', '[]', 0, NULL, NULL, 1, ?)", + ) + .bind(SPACE_TWO) + .bind(NOW) + .execute(&fixture.store.pool()) + .await + .expect("seed the stranger's malformed grant"); + let (_dir, serve) = fixture.serve(); + // No reasoner: a path that reaches the engine would answer differently again. + let mut faces = faces( + hello("runtime", &[]), + None, + MindProviders::default(), + ); + faces.principals = two_principal_admission(); + let surface = surface(&serve, faces); + + let session = connect_as(&surface, &PEER_TWO_SEED, &[DELIBERATE]).await; + let poisoned = expect_reject( + session + .adapter + .invoke_tool(DELIBERATE, deliberate_arguments_in(SPACE_TWO)) + .await, + "deliberate into a Mind carrying a stranger's malformed row", + ); + let absent = expect_reject( + session + .adapter + .invoke_tool(DELIBERATE, deliberate_arguments_in("spc_no_such_mind")) + .await, + "deliberate into a space that is no Mind at all", + ); + assert_eq!( + poisoned, absent, + "a stranger's malformed row and an absent Mind must be the byte-same refusal" + ); + assert!( + poisoned.details.is_none(), + "the refusal carries no details either way: {poisoned:?}" + ); +} + /// Liveness is the adapter's one grant rule: an expiry that does not parse fails closed, so the /// grant is dead and `deliberate` is the admission refusal, not a read of the carrier. #[tokio::test(flavor = "multi_thread", worker_threads = 2)] diff --git a/crates/mindcore-spoke/src/workflows.rs b/crates/mindcore-spoke/src/workflows.rs index 7756d315..21e67a30 100644 --- a/crates/mindcore-spoke/src/workflows.rs +++ b/crates/mindcore-spoke/src/workflows.rs @@ -35,7 +35,7 @@ use mindcore_spi::{ }; use mindcore_sqlite::{ append_cognition, list_entries_in, read_carrier_header, read_entry, vectors, - SqliteMemoryRepository, + SqliteMemoryRepository, SqliteRepositoryError, }; use crate::admission; @@ -72,9 +72,18 @@ pub async fn admitted_carrier_entry( .await .map_err(|e| Reject::internal(format!("the mind admission could not begin: {e}")).into_spoke())?; let space = SpaceId::new(space_id.to_string()); - let rows = admission::grants(&repository, &mut tx, &space) + // Only the caller's own rows, and only the liveness fields. Another principal's malformed + // row must not reach this decision: an indistinguishable refusal is the answer whether the + // decode failure lives on the caller's own row or the space is not a Mind at all, and a + // row that cannot decode admits nothing. + let rows = repository + .list_grants(&mut tx, &space, Some(principal_id)) .await - .map_err(Reject::into_spoke)?; + .map_err(|error| match error { + SqliteRepositoryError::InvalidRow(_) => Reject::admission_refusal().into_spoke(), + other => Reject::internal(format!("the mind admission could not be read: {other}")) + .into_spoke(), + })?; let now = Utc::now(); let admitted = rows.iter().any(|row| { row.principal_id.as_str() == principal_id From a4b4ae0a6a2cf55dade989fc3f15f444a764a660 Mon Sep 17 00:00:00 2001 From: Tang Bohao Date: Thu, 26 Nov 2026 13:57:52 +0800 Subject: [PATCH 08/27] feat(serving): serve a Mind's judgment over read_cognition MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add `tools.mindcore.read_cognition`: a closed `{space_id}` argument object, advertised and installed from the one list the three workflow tools read, so the capability and its handler can never drift apart. The handler opens one transaction and calls `MemoryAdapter::read_cognition`, which admits before any read — the caller's own grant rows and the registry row, then the carrier those rows name — and answers `{carrier_revision, records, mind_state}`; a Mind with no judgment yet answers `records: []` and a null `mind_state`. Admission lives in `admitted_carrier`, shared with the deliberate path's `admitted_carrier_entry`, so both answer the one target-free refusal. Regression: an unadmitted Mind and an absent one answer byte-equal with no details; a committed judgment is served with its derived MindState; the advertised tool list names read_cognition. --- crates/mindcore-runtime/src/tools.rs | 117 +++++++++++- crates/mindcore-runtime/src/tools/tests.rs | 200 ++++++++++++++++++++- crates/mindcore-runtime/tests/loopback.rs | 115 +++++++++++- crates/mindcore-runtime/tests/surface.rs | 21 ++- crates/mindcore-spoke/src/lib.rs | 67 ++++++- crates/mindcore-spoke/src/workflows.rs | 42 ++++- 6 files changed, 535 insertions(+), 27 deletions(-) diff --git a/crates/mindcore-runtime/src/tools.rs b/crates/mindcore-runtime/src/tools.rs index b7272d3b..55e7fac4 100644 --- a/crates/mindcore-runtime/src/tools.rs +++ b/crates/mindcore-runtime/src/tools.rs @@ -1,4 +1,4 @@ -//! The Mind tools served over Connect: the three workflow tools. +//! The Mind tools served over Connect: the workflow tools and the cognition read. //! //! Connect owns the signed `{ "arguments": … }` / `{ "result": … }` wrappers; these handlers see //! only the argument object and return only the result value. Each handler binds to the responder @@ -22,6 +22,7 @@ use mindcore_spi::{ AbsorbCandidateOutcome, ContextPack, DeliberateOutcome, DeliberateRequest, DomainLens, Embedder, Evidence, MindCapabilities, MindWorkflows, PolicyHook, Reasoner, SpiError, }; +use mindcore_spoke::MemoryAdapter; use spoke_connect::remote::{ConnectResponder, MemoryAdmission, ToolHandler}; use spoke_operations::{SpokeReject, SpokeRejectCode, SpokeResult}; use spoke_schemas::data::cognition::{CognitionReference, CognitionTarget}; @@ -37,6 +38,8 @@ pub const RECALL_CONTEXT: &str = "tools.mindcore.recall_context"; pub const ABSORB: &str = "tools.mindcore.absorb"; /// Stable capability id of the deliberation workflow. pub const DELIBERATE: &str = "tools.mindcore.deliberate"; +/// Stable capability id of the cognition read. +pub const READ_COGNITION: &str = "tools.mindcore.read_cognition"; /// The provider capabilities a tool call injects into its workflow. /// @@ -120,7 +123,7 @@ impl WorkflowTools { /// The one list both advertisement and installation read. #[allow(clippy::type_complexity)] - fn advertised() -> [(&'static str, &'static str, fn() -> Value, fn() -> Value); 3] { + fn advertised() -> [(&'static str, &'static str, fn() -> Value, fn() -> Value); 4] { [ ( RECALL_CONTEXT, @@ -140,6 +143,12 @@ impl WorkflowTools { deliberate_input, deliberate_output, ), + ( + READ_COGNITION, + "Read a Mind's current judgment and its derived mind state.", + read_cognition_input, + read_cognition_output, + ), ] } @@ -242,6 +251,7 @@ async fn serve( RECALL_CONTEXT => recall_context(&*workflows, &principal, arguments, &providers).await, ABSORB => absorb(&*workflows, &principal, arguments, &providers).await, DELIBERATE => deliberate(&*workflows, &principal, arguments, &providers, &pool).await, + READ_COGNITION => read_cognition(&principal, arguments, &pool).await, other => SpokeResult::Reject(SpokeReject { code: SpokeRejectCode::InvalidInput, message: format!("unknown mindcore tool {other}"), @@ -373,6 +383,44 @@ async fn deliberate( } } +/// `tools.mindcore.read_cognition`: one admitted Mind's judgment, read in one transaction. +/// +/// [`MemoryAdapter::read_cognition`] runs admission before any read — the caller's own grant +/// rows and the registry row in this transaction — so an unadmitted caller learns nothing about +/// whether the Mind exists, and a granted one gets `{carrier_revision, records, mind_state}`. +/// A carrier holding no record yet answers `records: []` and a null `mind_state`. +async fn read_cognition( + principal: &Principal, + arguments: Value, + pool: &SqlitePool, +) -> SpokeResult { + let arguments: ReadCognitionArguments = match decode(arguments) { + Ok(arguments) => arguments, + Err(reject) => return SpokeResult::Reject(reject), + }; + let mut transaction = match pool.begin().await { + Ok(transaction) => transaction, + Err(error) => { + return SpokeResult::Reject(SpokeReject { + code: SpokeRejectCode::InternalError, + message: format!("the cognition read could not begin: {error}"), + details: None, + }) + } + }; + let cognition = + MemoryAdapter::read_cognition(&mut transaction, principal, &arguments.space_id).await; + drop(transaction); + match cognition { + Ok(cognition) => SpokeResult::Ok(json!({ + "carrier_revision": cognition.carrier_revision, + "records": cognition.records, + "mind_state": cognition.mind_state, + })), + Err(reject) => SpokeResult::Reject(reject), + } +} + fn absorb_outcome(outcome: AbsorbCandidateOutcome) -> Value { match outcome { AbsorbCandidateOutcome::Pending { candidate_id } => { @@ -505,6 +553,14 @@ struct EvidenceArgument { text: String, } +/// The cognition read names one Mind and nothing else: the carrier and its revision come from +/// the registry row, never from the caller. +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct ReadCognitionArguments { + space_id: String, +} + fn descriptor( capability_id: &str, description: &str, @@ -1026,5 +1082,62 @@ fn deliberate_output() -> Value { }) } +/// The cognition read's arguments: the closed `{space_id}` object, mirroring +/// [`ReadCognitionArguments`]. The Mind's carrier is never a wire member. +fn read_cognition_input() -> Value { + json!({ + "$id": "https://mindcore.invalid/schemas/tools/read-cognition.input.schema.json", + "type": "object", + "additionalProperties": false, + "required": ["space_id"], + "properties": { + "space_id": { + "type": "string", + "minLength": 1, + "description": "The Mind to read; the same id its memory requests carry.", + }, + }, + }) +} + +/// The cognition read's result: the carrier revision the read served, its current-view records in +/// carrier order, and the derived `MindState` — `null` for a Mind that holds no judgment yet. +/// `records` and `mind_state` are opaque product objects, so their openness is stated rather than +/// left to draft-07's implicit default. +fn read_cognition_output() -> Value { + json!({ + "type": "object", + "additionalProperties": false, + "required": ["carrier_revision", "records", "mind_state"], + "properties": { + "carrier_revision": { + "type": "integer", + "minimum": 0, + "description": "The carrier revision the read served.", + }, + "records": { + "type": "array", + "items": { + "type": "object", + "additionalProperties": {}, + "description": "One current-view SPOKE CognitionRecord, in carrier order.", + }, + "description": "The carrier's current judgment; empty before its first record.", + }, + "mind_state": { + "oneOf": [ + { "type": "null" }, + { + "type": "object", + "additionalProperties": {}, + "description": "The derived SPOKE MindState (spoke-judgment).", + }, + ], + "description": "The derived MindState, or null for a Mind with no judgment yet.", + }, + }, + }) +} + #[cfg(test)] mod tests; diff --git a/crates/mindcore-runtime/src/tools/tests.rs b/crates/mindcore-runtime/src/tools/tests.rs index ab7c0e83..a1400368 100644 --- a/crates/mindcore-runtime/src/tools/tests.rs +++ b/crates/mindcore-runtime/src/tools/tests.rs @@ -174,11 +174,124 @@ async fn registry_pool() -> SqlitePool { .execute(&pool) .await .expect("seed probe grant"); + // The carrier entry the registry row names, holding no judgment yet: the cognition read + // resolves `(collection, carrier_entry_id)` from the row and reads this entry through it. + sqlx::query( + "CREATE TABLE knowledge_entries (collection TEXT NOT NULL, entry_id TEXT NOT NULL, \ + revision INTEGER NOT NULL, payload TEXT NOT NULL, superseded_by TEXT, \ + created_at TEXT NOT NULL, updated_at TEXT NOT NULL, PRIMARY KEY (collection, entry_id))", + ) + .execute(&pool) + .await + .expect("create knowledge_entries"); + sqlx::query( + "INSERT INTO knowledge_entries (collection, entry_id, revision, payload, created_at, updated_at) \ + VALUES ('wren', 'ke_wren', 1, ?, '2026-11-21T00:00:00Z', '2026-11-21T00:00:00Z')", + ) + .bind( + serde_json::json!({ + "schema_version": 1, + "entry_id": "ke_wren", + "entry_type": "note", + "canonical_name": "wren's carrier", + "status": "confirmed", + "revision": 1, + "body": { "summary": "what this holder currently holds" }, + "modules": { "cognition": { "records": [], "world_facts": [], "extensions": {} } }, + "extensions": {}, + }) + .to_string(), + ) + .execute(&pool) + .await + .expect("seed the carrier entry"); + // One committed judgment on the first Mind's carrier, and a second Mind whose carrier holds + // none: the cognition read is exercised on both sides of `mind_state: null`. + sqlx::query( + "CREATE TABLE cognition_records (collection TEXT NOT NULL, entry_id TEXT NOT NULL, \ + append_seq INTEGER NOT NULL, record_id TEXT NOT NULL, payload TEXT NOT NULL, \ + append_prior_shape INTEGER, PRIMARY KEY (collection, entry_id, append_seq))", + ) + .execute(&pool) + .await + .expect("create cognition_records"); + sqlx::query( + "INSERT INTO cognition_records (collection, entry_id, append_seq, record_id, payload, \ + append_prior_shape) VALUES ('wren', 'ke_wren', 1, 'cog_1', ?, NULL)", + ) + .bind( + serde_json::to_value(cognition()) + .expect("the cognition fixture serializes") + .to_string(), + ) + .execute(&pool) + .await + .expect("seed the committed judgment"); + sqlx::query( + "INSERT INTO minds (space_id, knowledge_collection, carrier_entry_id) \ + VALUES ('spc_2', 'mora', 'ke_mora')", + ) + .execute(&pool) + .await + .expect("seed the fresh mind row"); + sqlx::query( + "INSERT INTO memory_grants \ + (grant_id, space_id, subject_id, principal_id, capabilities_json, \ + context_ids_json, shared_access, expires_at, revoked_at, revision, created_at) \ + VALUES ('grt_fresh', 'spc_2', NULL, 'prn_driver', '[\"knowledge_read\"]', '[]', 0, NULL, NULL, 1, '2026-11-21T00:00:00Z')", + ) + .execute(&pool) + .await + .expect("seed the fresh grant"); + sqlx::query( + "INSERT INTO knowledge_entries \ + (collection, entry_id, revision, payload, superseded_by, created_at, updated_at) \ + VALUES ('mora', 'ke_mora', 1, ?, NULL, '2026-11-21T00:00:00Z', '2026-11-21T00:00:00Z')", + ) + .bind( + serde_json::json!({ + "schema_version": 1, + "entry_id": "ke_mora", + "entry_type": "note", + "canonical_name": "mora's carrier", + "status": "confirmed", + "revision": 1, + "body": { "summary": "a holder that has not judged anything yet" }, + "modules": { "cognition": { "records": [], "world_facts": [], "extensions": {} } }, + "extensions": {}, + }) + .to_string(), + ) + .execute(&pool) + .await + .expect("seed the fresh carrier entry"); + // A Mind the probe's principal holds no grant in: the admission refusal is the same answer + // as a space that does not exist, so the read cannot disclose which one was named. + sqlx::query( + "INSERT INTO minds (space_id, knowledge_collection, carrier_entry_id) \ + VALUES ('spc_3', 'ghost', 'ke_ghost')", + ) + .execute(&pool) + .await + .expect("seed the ghost mind row"); + sqlx::query( + "INSERT INTO memory_grants \ + (grant_id, space_id, subject_id, principal_id, capabilities_json, \ + context_ids_json, shared_access, expires_at, revoked_at, revision, created_at) \ + VALUES ('grt_ghost', 'spc_3', NULL, 'prn_other', '[\"knowledge_read\"]', '[]', 0, NULL, NULL, 1, '2026-11-21T00:00:00Z')", + ) + .execute(&pool) + .await + .expect("seed the ghost grant"); pool } async fn tools(fake: Arc) -> WorkflowTools { - WorkflowTools::new(fake, admission(), MindProviders::default(), registry_pool().await) + tools_over(fake, registry_pool().await).await +} + +async fn tools_over(fake: Arc, pool: SqlitePool) -> WorkflowTools { + WorkflowTools::new(fake, admission(), MindProviders::default(), pool) } fn expect_ok(result: SpokeResult, context: &str) -> T { @@ -331,6 +444,11 @@ fn deliberate_arguments() -> Value { }) } +/// The cognition read names one Mind and nothing else. +fn cognition_read_arguments(space: &str) -> Value { + json!({ "space_id": space }) +} + #[tokio::test] async fn recall_context_round_trips_the_pack() { let fake = Arc::new(Fake::default()); @@ -609,6 +727,79 @@ async fn unadmitted_peers_are_not_authorized() { ); } +/// The cognition read over one store: a Mind holding a committed judgment answers its records and +/// the derived `MindState`; a Mind that has judged nothing answers `records: []` and a null +/// `mind_state`; and a Mind the caller holds no grant in answers the same target-free refusal as +/// a space that does not exist. +#[tokio::test] +async fn read_cognition_serves_a_judgment_or_a_null_state() { + let tool = tools(Arc::new(Fake::default())).await; + + let committed = expect_ok( + tool.call( + READ_COGNITION, + "peer-driver", + cognition_read_arguments("spc_1"), + ) + .await, + "a Mind with a committed judgment", + ); + assert_eq!(committed["carrier_revision"], 1); + assert_eq!( + committed["records"], + json!([serde_json::to_value(cognition()).expect("the fixture serializes")]), + "the committed record is served in carrier order" + ); + assert!( + committed["mind_state"].is_object(), + "the derived MindState is served beside the judgment: {committed}" + ); + + let fresh = expect_ok( + tool.call( + READ_COGNITION, + "peer-driver", + cognition_read_arguments("spc_2"), + ) + .await, + "a Mind with no judgment yet", + ); + assert_eq!(fresh["records"], json!([])); + assert_eq!( + fresh["mind_state"], + Value::Null, + "a Mind with no judgment answers a null state" + ); + + let unadmitted = expect_reject( + tool.call( + READ_COGNITION, + "peer-driver", + cognition_read_arguments("spc_3"), + ) + .await, + "a Mind the caller is not admitted to", + ); + let absent = expect_reject( + tool.call( + READ_COGNITION, + "peer-driver", + cognition_read_arguments("spc_absent"), + ) + .await, + "a space that does not exist", + ); + assert_eq!(unadmitted.code, SpokeRejectCode::NotAuthorized); + assert_eq!( + unadmitted.details, None, + "an admission refusal discloses no details" + ); + assert_eq!( + unadmitted, absent, + "an unadmitted Mind and an absent one are one answer" + ); +} + #[tokio::test] async fn settlement_refusals_keep_their_code_and_details() { let refusal = SpokeReject { @@ -764,14 +955,15 @@ async fn advertised_input_schemas_match_the_decoded_arguments() { verdict: json!({}), judgment: judgment(), })), + READ_COGNITION => {} other => panic!("unadvertised tool {other}"), } let mut arguments = minimal(&input, &input); - // `deliberate` resolves the carrier from the registry row of the request's space, so the - // manifest-shaped probe names the one Mind this harness seeds. `spc_1` satisfies the + // `deliberate` and `read_cognition` both resolve a Mind from the request's `space_id`, so + // the manifest-shaped probe names the one Mind this harness seeds. `spc_1` satisfies the // schema's `minLength` either way, so the shape check is unchanged. - if capability_id == DELIBERATE { + if matches!(capability_id, DELIBERATE | READ_COGNITION) { arguments["space_id"] = json!("spc_1"); } expect_ok( diff --git a/crates/mindcore-runtime/tests/loopback.rs b/crates/mindcore-runtime/tests/loopback.rs index e4ea8c88..82fb4c01 100644 --- a/crates/mindcore-runtime/tests/loopback.rs +++ b/crates/mindcore-runtime/tests/loopback.rs @@ -24,7 +24,7 @@ use tempfile::TempDir; use mindcore_base::ids::SpaceId; use mindcore_base::ir::MemorySpaceRow; use mindcore_base::knowledge::{adoption_anchor_parts, KnowledgeScope}; -use mindcore_runtime::tools::{ABSORB, DELIBERATE, RECALL_CONTEXT}; +use mindcore_runtime::tools::{ABSORB, DELIBERATE, READ_COGNITION, RECALL_CONTEXT}; use mindcore_runtime::{ AdoptionRoute, MindProviders, MindcoreServe, MindcoreSurface, ServeFaces, ToolRegistration, }; @@ -791,6 +791,11 @@ fn deliberate_arguments_in(space: &str) -> Value { }) } +/// The cognition read's arguments: the Mind id alone, the same id its memory requests carry. +fn cognition_arguments(space: &str) -> Value { + json!({ "space_id": space }) +} + /// The record ids one recall pack carries, sorted: the pack promises no order of its own. fn packed_record_ids(result: &Value) -> Vec<&str> { let mut ids: Vec<&str> = result["records"] @@ -959,8 +964,16 @@ async fn remote_consumer_recalls_context_through_the_composed_surface() { assert_eq!( capabilities(&surface), - ["spoke-knowledge", "ke-ownership", "spoke-judgment", RECALL_CONTEXT, ABSORB, DELIBERATE], - "the manifest advertises the knowledge face and all three workflow tools" + [ + "spoke-knowledge", + "ke-ownership", + "spoke-judgment", + RECALL_CONTEXT, + ABSORB, + DELIBERATE, + READ_COGNITION + ], + "the manifest advertises the knowledge face and every workflow tool" ); assert_eq!( surface @@ -969,7 +982,7 @@ async fn remote_consumer_recalls_context_through_the_composed_surface() { .iter() .map(|tool| tool.capability_id.as_str()) .collect::>(), - [RECALL_CONTEXT, ABSORB, DELIBERATE], + [RECALL_CONTEXT, ABSORB, DELIBERATE, READ_COGNITION], "the registry row routes every Mind, so the deliberation tool is always installed" ); @@ -1347,6 +1360,100 @@ async fn remote_consumer_settles_a_deliberation_with_a_valid_judgment() { ); } +/// The served cognition read over a signed session: a Mind that has judged nothing answers +/// `records: []` and a null `mind_state`; after a settlement the same Mind answers the committed +/// record and its derived `MindState`; and a Mind the caller holds no grant in answers exactly +/// the refusal a space that is no Mind at all answers. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn read_cognition_serves_the_judgment_and_refuses_an_unadmitted_mind() { + let fixture = Fixture::open().await; + fixture.seed_second_mind().await; + let (_dir, serve) = fixture.serve(); + let providers = MindProviders { + reasoner: Some(Arc::new(SettlingReasoner(SETTLING_RATIONALE))), + policy_hook: Some(Arc::new(AutoPolicy)), + ..MindProviders::default() + }; + let surface = surface(&serve, faces(hello("runtime", &[]), None, providers)); + + let session = connect(&surface, &[DELIBERATE, READ_COGNITION]).await; + + let fresh = expect_ok( + session + .adapter + .invoke_tool(READ_COGNITION, cognition_arguments(SPACE)) + .await, + "the cognition read before any judgment", + ); + assert_eq!(fresh["carrier_revision"], 1); + assert_eq!(fresh["records"], json!([])); + assert_eq!( + fresh["mind_state"], + Value::Null, + "a Mind with no judgment answers a null state: {fresh}" + ); + + let settled = expect_ok( + session + .adapter + .invoke_tool(DELIBERATE, deliberate_arguments()) + .await, + "the settling deliberation", + ); + assert_eq!(settled["status"], "settled"); + + let read = expect_ok( + session + .adapter + .invoke_tool(READ_COGNITION, cognition_arguments(SPACE)) + .await, + "the cognition read after a judgment", + ); + assert_eq!( + read["carrier_revision"], 2, + "the read serves the revision the settlement wrote: {read}" + ); + let records = read["records"] + .as_array() + .expect("the read serves a records array"); + assert_eq!(records.len(), 1, "one committed judgment is served: {read}"); + assert_eq!(records[0]["record_id"], settled["record"]["record_id"]); + assert_eq!(records[0]["assessor"]["id"], PRINCIPAL); + assert_eq!(records[0]["holder"]["id"], CARRIER); + assert!( + read["mind_state"].is_object(), + "the derived MindState is served beside the record: {read}" + ); + assert_eq!(read["mind_state"]["mind_state_id"], SPACE); + assert_eq!(read["mind_state"]["holder_entry_id"], CARRIER); + + // The second Mind exists and carries a registry row, yet this peer holds no grant in it: the + // refusal must be the byte-same answer a space that is no Mind at all gives. + let unadmitted = expect_reject( + session + .adapter + .invoke_tool(READ_COGNITION, cognition_arguments(SPACE_TWO)) + .await, + "the cognition read of a Mind the caller holds no grant in", + ); + let absent = expect_reject( + session + .adapter + .invoke_tool(READ_COGNITION, cognition_arguments("spc_no_such_mind")) + .await, + "the cognition read of a space that is no Mind at all", + ); + assert_eq!(unadmitted.code, SpokeRejectCode::NotAuthorized); + assert!( + unadmitted.details.is_none(), + "the refusal carries no details: {unadmitted:?}" + ); + assert_eq!( + unadmitted, absent, + "an unadmitted Mind and an absent Mind must be the byte-same refusal" + ); +} + /// One deliberation response's judgment, held to the additive contract on every branch: the /// released validator accepts the wire value, it carries the request target and the cited record's /// stored revision, its outcome follows the response branch and its basis is the verdict rationale. diff --git a/crates/mindcore-runtime/tests/surface.rs b/crates/mindcore-runtime/tests/surface.rs index a28a6f39..6f854556 100644 --- a/crates/mindcore-runtime/tests/surface.rs +++ b/crates/mindcore-runtime/tests/surface.rs @@ -10,7 +10,7 @@ use serde_json::{json, Value}; use tempfile::TempDir; use mindcore_base::knowledge::KnowledgeScope; -use mindcore_runtime::tools::{ABSORB, DELIBERATE, RECALL_CONTEXT}; +use mindcore_runtime::tools::{ABSORB, DELIBERATE, READ_COGNITION, RECALL_CONTEXT}; use mindcore_runtime::{AdoptionRoute, MindProviders, MindcoreServe, ServeFaces, ToolRegistration}; use mindcore_spoke::{ServedMemory, TRANSFER_OPERATIONS}; use mindcore_sqlite::{MindStore, ScopedKnowledgeStore}; @@ -234,7 +234,8 @@ async fn manifest_follows_the_composed_faces() { CAPABILITY_SPOKE_JUDGMENT, RECALL_CONTEXT, ABSORB, - DELIBERATE + DELIBERATE, + READ_COGNITION ] ); assert!( @@ -248,7 +249,7 @@ async fn manifest_follows_the_composed_faces() { .iter() .map(|tool| tool.capability_id.as_str()) .collect(); - assert_eq!(tools, [RECALL_CONTEXT, ABSORB, DELIBERATE]); + assert_eq!(tools, [RECALL_CONTEXT, ABSORB, DELIBERATE, READ_COGNITION]); assert!( surface .manifest @@ -295,7 +296,8 @@ async fn manifest_follows_the_composed_faces() { CAPABILITY_SPOKE_JUDGMENT, RECALL_CONTEXT, ABSORB, - DELIBERATE + DELIBERATE, + READ_COGNITION ], "the history face is advertised exactly when it is served" ); @@ -328,7 +330,8 @@ async fn manifest_follows_the_composed_faces() { CAPABILITY_SPOKE_JUDGMENT, RECALL_CONTEXT, ABSORB, - DELIBERATE + DELIBERATE, + READ_COGNITION ], "the adoption face is advertised exactly when it is served" ); @@ -530,7 +533,8 @@ async fn attached_memory_service_is_advertised_and_served() { CAPABILITY_SPOKE_JUDGMENT, RECALL_CONTEXT, ABSORB, - DELIBERATE + DELIBERATE, + READ_COGNITION ] ); assert!( @@ -615,11 +619,12 @@ async fn tool_registrations_drive_advertisement_and_installation() { RECALL_CONTEXT, ABSORB, DELIBERATE, + READ_COGNITION, HOST_TOOL ] ); - assert_eq!(surface.manifest.tools.len(), 4); - assert_eq!(surface.manifest.tools[3].capability_id.as_str(), HOST_TOOL); + assert_eq!(surface.manifest.tools.len(), 5); + assert_eq!(surface.manifest.tools[4].capability_id.as_str(), HOST_TOOL); assert!( surface .manifest diff --git a/crates/mindcore-spoke/src/lib.rs b/crates/mindcore-spoke/src/lib.rs index 31b134cd..2e990ac2 100644 --- a/crates/mindcore-spoke/src/lib.rs +++ b/crates/mindcore-spoke/src/lib.rs @@ -30,14 +30,14 @@ pub(crate) use mindcore_base::ids::mint; use chrono::Utc; use serde::de::DeserializeOwned; use serde_json::Value; -use spoke_operations::{GrantRequirement, SpokeRejectCode, SpokeResult}; +use spoke_operations::{GrantRequirement, SpokeReject, 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; +use mindcore_sqlite::{read_entry, SqliteMemoryRepository}; use crate::admission::Op; use crate::reject::{AResult, Reject}; @@ -316,6 +316,69 @@ impl MemoryAdapter { } Ok(()) } + + /// Read one Mind's judgment over the caller's transaction: admission first, then the carrier + /// the registry row names, then the derived `MindState` — all inside `tx`, so a revocation + /// cannot land between admission and the read. Admission is [`workflows::admitted_carrier`]: + /// the caller's own grant rows and the registry row, read together, answering one fixed + /// refusal with no details whether the Mind is absent or the caller was never admitted. + /// A fresh carrier answers `records: []` and `mind_state: null`; the derivation failures a + /// stored carrier could raise are internal errors, because the carrier passed validation at + /// its write. The transaction is the caller's to end. + pub async fn read_cognition( + tx: &mut Tx<'_>, + principal: &Principal, + space_id: &str, + ) -> Result { + let carrier = workflows::admitted_carrier(tx, principal_id(principal), space_id).await?; + let carrier_entry = + match read_entry(tx, &carrier.collection, &carrier.carrier_entry_id).await { + SpokeResult::Ok(entry) => entry, + SpokeResult::Reject(reject) => return Err(reject), + }; + let revision = match carrier_entry.revision { + Some(revision) => revision, + None => { + return Err(Reject::internal(format!( + "carrier {} holds no assigned revision", + carrier.carrier_entry_id + )) + .into_spoke()) + } + }; + let view = match mindcore_base::cognition::derive_mind_state(&carrier_entry) { + Ok(view) => view, + Err(mindcore_base::cognition::MindError::NoRecords) => { + return Ok(Cognition { + carrier_revision: revision, + records: Vec::new(), + mind_state: Value::Null, + }) + } + Err(error) => { + return Err(Reject::internal(format!( + "carrier {} cannot be derived: {error}", + carrier.carrier_entry_id + )) + .into_spoke()) + } + }; + let mind_state = match mindcore_base::cognition::mind_state_value(&view, space_id) { + Ok(mind_state) => mind_state, + Err(error) => { + return Err(Reject::internal(format!( + "the mind state of {} cannot be projected: {error}", + carrier.carrier_entry_id + )) + .into_spoke()) + } + }; + Ok(Cognition { + carrier_revision: revision, + records: view.records, + mind_state, + }) + } } /// 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 21e67a30..e3f86aab 100644 --- a/crates/mindcore-spoke/src/workflows.rs +++ b/crates/mindcore-spoke/src/workflows.rs @@ -51,6 +51,14 @@ type JournalPublisher = dyn Fn(&[Value]) -> Result<(), SpiError> + Send + Sync; /// this capture's absorb run decided `Pending` for the ids it names. const ABSORB_DECISION_OP: &str = "mindcore.absorb.decision"; +/// The carrier location of one admitted Mind: the registry row the `space_id` names. +pub(crate) struct AdmittedCarrier { + /// The knowledge collection the Mind's carrier lives in. + pub(crate) collection: String, + /// The entry id the Mind's carrier row names. + pub(crate) carrier_entry_id: String, +} + /// Mind admission for the host-side `deliberate` handler: the caller's grant rows and the /// registry row read in one transaction, so a revocation cannot land between them, and every /// liveness decision runs the one grant rule (`live_grant`: unrevoked, unexpired, an @@ -62,7 +70,6 @@ pub async fn admitted_carrier_entry( principal_id: &str, space_id: &str, ) -> Result { - let repository = SqliteMemoryRepository; let mut conn = pool .acquire() .await @@ -71,13 +78,31 @@ pub async fn admitted_carrier_entry( .begin() .await .map_err(|e| Reject::internal(format!("the mind admission could not begin: {e}")).into_spoke())?; + let carrier = admitted_carrier(&mut tx, principal_id, space_id).await?; + let _ = tx.rollback().await; + Ok(carrier.carrier_entry_id) +} + +/// Mind admission on the caller's transaction: the caller's grant rows and the registry row +/// read together, so a revocation cannot land between them. Returns the row-named carrier +/// location, or the fixed admission refusal — byte-equal whether the Mind exists, the grant is +/// missing, revoked or expired — so an unadmitted caller cannot tell the cases apart. The +/// space-wide `knowledge_read` grant is the one capability this admission requires: reading a +/// collection is not authority to the rest of the Mind, but a Mind without it has no readable +/// judgment at all. +pub(crate) async fn admitted_carrier( + tx: &mut Tx<'_>, + principal_id: &str, + space_id: &str, +) -> Result { + let repository = SqliteMemoryRepository; let space = SpaceId::new(space_id.to_string()); // Only the caller's own rows, and only the liveness fields. Another principal's malformed // row must not reach this decision: an indistinguishable refusal is the answer whether the // decode failure lives on the caller's own row or the space is not a Mind at all, and a // row that cannot decode admits nothing. let rows = repository - .list_grants(&mut tx, &space, Some(principal_id)) + .list_grants(tx, &space, Some(principal_id)) .await .map_err(|error| match error { SqliteRepositoryError::InvalidRow(_) => Reject::admission_refusal().into_spoke(), @@ -98,15 +123,18 @@ pub async fn admitted_carrier_entry( // The row read follows in the same transaction: a revocation that commits // before this statement is already covered by the grant check re-reading on // its own transaction; one either sees both sides of it or neither. - let row: Option = sqlx::query_scalar( - "SELECT carrier_entry_id FROM minds WHERE space_id = ?", + let row: Option<(String, String)> = sqlx::query_as( + "SELECT knowledge_collection, carrier_entry_id FROM minds WHERE space_id = ?", ) .bind(space_id) - .fetch_optional(&mut *tx) + .fetch_optional(&mut **tx) .await .map_err(|e| Reject::internal(format!("the mind admission could not be read: {e}")).into_spoke())?; - let _ = tx.rollback().await; - row.ok_or_else(|| Reject::admission_refusal().into_spoke()) + row.map(|(collection, carrier_entry_id)| AdmittedCarrier { + collection, + carrier_entry_id, + }) + .ok_or_else(|| Reject::admission_refusal().into_spoke()) } /// The in-process workflow binding over one SQLite pool. From 67a531dafd52974dfee92b2a0e7c2e12a22bc8ac Mon Sep 17 00:00:00 2001 From: Tang Bohao Date: Thu, 26 Nov 2026 13:58:58 +0800 Subject: [PATCH 09/27] fix(serving): a carrier that cannot be derived is a terminal refusal `MemoryAdapter::read_cognition` classified a carrier with no assigned revision, a derivation failure and a MindState projection failure as retryable. None of the three changes on a repeat: the carrier passed validation at its write, so repeating the read answers the same defect. They are terminal `InternalError`s now, matching the facade's `cognition_read`. --- crates/mindcore-spoke/src/lib.rs | 40 ++++++++++++++++++++------------ 1 file changed, 25 insertions(+), 15 deletions(-) diff --git a/crates/mindcore-spoke/src/lib.rs b/crates/mindcore-spoke/src/lib.rs index 2e990ac2..0816b8d0 100644 --- a/crates/mindcore-spoke/src/lib.rs +++ b/crates/mindcore-spoke/src/lib.rs @@ -322,9 +322,10 @@ impl MemoryAdapter { /// cannot land between admission and the read. Admission is [`workflows::admitted_carrier`]: /// the caller's own grant rows and the registry row, read together, answering one fixed /// refusal with no details whether the Mind is absent or the caller was never admitted. - /// A fresh carrier answers `records: []` and `mind_state: null`; the derivation failures a - /// stored carrier could raise are internal errors, because the carrier passed validation at - /// its write. The transaction is the caller's to end. + /// A fresh carrier answers `records: []` and `mind_state: null`; a stored carrier that cannot + /// be derived is a terminal `InternalError`, matching the facade's `cognition_read`, because + /// the carrier passed validation at its write and repeating the read cannot change it. The + /// transaction is the caller's to end. pub async fn read_cognition( tx: &mut Tx<'_>, principal: &Principal, @@ -339,10 +340,13 @@ impl MemoryAdapter { let revision = match carrier_entry.revision { Some(revision) => revision, None => { - return Err(Reject::internal(format!( - "carrier {} holds no assigned revision", - carrier.carrier_entry_id - )) + return Err(Reject::terminal( + SpokeRejectCode::InternalError, + format!( + "carrier {} holds no assigned revision", + carrier.carrier_entry_id + ), + ) .into_spoke()) } }; @@ -356,20 +360,26 @@ impl MemoryAdapter { }) } Err(error) => { - return Err(Reject::internal(format!( - "carrier {} cannot be derived: {error}", - carrier.carrier_entry_id - )) + return Err(Reject::terminal( + SpokeRejectCode::InternalError, + format!( + "carrier {} cannot be derived: {error}", + carrier.carrier_entry_id + ), + ) .into_spoke()) } }; let mind_state = match mindcore_base::cognition::mind_state_value(&view, space_id) { Ok(mind_state) => mind_state, Err(error) => { - return Err(Reject::internal(format!( - "the mind state of {} cannot be projected: {error}", - carrier.carrier_entry_id - )) + return Err(Reject::terminal( + SpokeRejectCode::InternalError, + format!( + "the mind state of {} cannot be projected: {error}", + carrier.carrier_entry_id + ), + ) .into_spoke()) } }; From ba9514752f8e091c20b40b9fbbd2762078d50044 Mon Sep 17 00:00:00 2001 From: Tang Bohao Date: Thu, 26 Nov 2026 14:06:00 +0800 Subject: [PATCH 10/27] fix(serving): admit before coverage in read_cognition, per the plan MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `read_cognition` folded the space-wide `knowledge_read` check into Mind admission, so a caller admitted through another capability received the target-free admission refusal where the plan requires the post-admission coverage refusal. Restore the locked order: a live grant of the caller's in the named space — the target-free refusal for an unknown, an unadmitted or a frozen-ungranted Mind — then the space row, then the registry row, and only then the `knowledge_read` coverage, answered by `admission::refuse_space_coverage` (the message `refuse_coverage` already speaks) and reachable only by a caller already admitted to the named Mind. Every read stays confined to the caller's own grant rows, so a stranger's malformed row still cannot move the answer, and the deliberate handler's `admitted_carrier_entry` keeps the rule Task 2 established for it. Regression: an admitted caller holding only `recall` answers the coverage refusal (terminal, naming the capability), an unadmitted caller still answers the byte-equal target-free admission refusal, and both are asserted at unit level over the rendered wire members and through a signed loopback. --- crates/mindcore-runtime/src/tools/tests.rs | 115 +++++++++++++++++ crates/mindcore-runtime/tests/loopback.rs | 57 ++++++++- crates/mindcore-spoke/src/admission.rs | 13 +- crates/mindcore-spoke/src/workflows.rs | 142 +++++++++++++++------ 4 files changed, 282 insertions(+), 45 deletions(-) diff --git a/crates/mindcore-runtime/src/tools/tests.rs b/crates/mindcore-runtime/src/tools/tests.rs index a1400368..ef4ccbb6 100644 --- a/crates/mindcore-runtime/src/tools/tests.rs +++ b/crates/mindcore-runtime/src/tools/tests.rs @@ -283,6 +283,75 @@ async fn registry_pool() -> SqlitePool { .execute(&pool) .await .expect("seed the ghost grant"); + // A Mind this principal is admitted to — it holds a live grant — but not to a + // `knowledge_read`: admission passes and the coverage check is the refusal that answers. + sqlx::query( + "INSERT INTO minds (space_id, knowledge_collection, carrier_entry_id) \ + VALUES ('spc_4', 'ash', 'ke_ash')", + ) + .execute(&pool) + .await + .expect("seed the underprivileged mind row"); + sqlx::query( + "INSERT INTO memory_grants \ + (grant_id, space_id, subject_id, principal_id, capabilities_json, \ + context_ids_json, shared_access, expires_at, revoked_at, revision, created_at) \ + VALUES ('grt_recall_only', 'spc_4', NULL, 'prn_driver', '[\"recall\"]', '[]', 0, NULL, NULL, 1, '2026-11-21T00:00:00Z')", + ) + .execute(&pool) + .await + .expect("seed the underprivileged grant"); + sqlx::query( + "INSERT INTO knowledge_entries \ + (collection, entry_id, revision, payload, superseded_by, created_at, updated_at) \ + VALUES ('ash', 'ke_ash', 1, ?, NULL, '2026-11-21T00:00:00Z', '2026-11-21T00:00:00Z')", + ) + .bind( + serde_json::json!({ + "schema_version": 1, + "entry_id": "ke_ash", + "entry_type": "note", + "canonical_name": "ash's carrier", + "status": "confirmed", + "revision": 1, + "body": { "summary": "a holder this caller may not read" }, + "modules": { "cognition": { "records": [], "world_facts": [], "extensions": {} } }, + "extensions": {}, + }) + .to_string(), + ) + .execute(&pool) + .await + .expect("seed the underprivileged carrier entry"); + // The space rows admission reads: a live grant only ever belongs to a Mind whose space row + // and registry row were written with it. + sqlx::query( + "CREATE TABLE memory_spaces (space_id TEXT PRIMARY KEY, display_name TEXT, \ + authority_host_id TEXT NOT NULL, authority_generation INTEGER NOT NULL, \ + status TEXT NOT NULL, revision INTEGER NOT NULL, created_at TEXT NOT NULL)", + ) + .execute(&pool) + .await + .expect("create memory_spaces"); + sqlx::query( + "CREATE TABLE memory_receipts (receipt_id TEXT PRIMARY KEY, space_id TEXT NOT NULL, \ + status TEXT NOT NULL)", + ) + .execute(&pool) + .await + .expect("create memory_receipts"); + for space in ["spc_1", "spc_2", "spc_3", "spc_4"] { + sqlx::query( + "INSERT INTO memory_spaces \ + (space_id, display_name, authority_host_id, authority_generation, status, revision, \ + created_at) \ + VALUES (?, NULL, 'host_1', 1, 'active', 1, '2026-11-21T00:00:00Z')", + ) + .bind(space) + .execute(&pool) + .await + .expect("seed the space row"); + } pool } @@ -301,6 +370,17 @@ fn expect_ok(result: SpokeResult, context: &str) -> T { } } +/// One refusal rendered the way a peer decodes it from the wire: the code string, the message and +/// the details, and nothing else. +fn wire_refusal(reject: &SpokeReject) -> String { + json!({ + "code": reject.code.as_str(), + "message": reject.message, + "details": reject.details, + }) + .to_string() +} + fn expect_reject(result: SpokeResult, context: &str) -> SpokeReject { match result { SpokeResult::Reject(reject) => reject, @@ -798,6 +878,41 @@ async fn read_cognition_serves_a_judgment_or_a_null_state() { unadmitted, absent, "an unadmitted Mind and an absent one are one answer" ); + assert_eq!( + wire_refusal(&unadmitted), + wire_refusal(&absent), + "the refusal is byte-equal across an unadmitted and an absent Mind" + ); + + // Admitted (a live `recall` grant), but not to `knowledge_read`: the coverage refusal + // answers, and it must not be the target-free admission refusal. + let uncovered = expect_reject( + tool.call(READ_COGNITION, "peer-driver", cognition_read_arguments("spc_4")) + .await, + "an admitted caller without knowledge_read", + ); + assert_eq!(uncovered.code, SpokeRejectCode::NotAuthorized); + assert!( + uncovered.message.contains("knowledge_read"), + "the coverage refusal names the capability the caller lacks: {uncovered:?}" + ); + assert!( + uncovered.message.contains("spc_4"), + "the caller is admitted, so the refusal may name the Mind: {uncovered:?}" + ); + assert_eq!( + uncovered + .details + .as_ref() + .and_then(|details| details.get("retry_class")) + .and_then(Value::as_str), + Some("terminal"), + "a coverage gap cannot be retried away: {uncovered:?}" + ); + assert_ne!( + uncovered, unadmitted, + "an admitted caller short of one capability is not an unadmitted caller" + ); } #[tokio::test] diff --git a/crates/mindcore-runtime/tests/loopback.rs b/crates/mindcore-runtime/tests/loopback.rs index 82fb4c01..2a5384ab 100644 --- a/crates/mindcore-runtime/tests/loopback.rs +++ b/crates/mindcore-runtime/tests/loopback.rs @@ -1362,19 +1362,30 @@ async fn remote_consumer_settles_a_deliberation_with_a_valid_judgment() { /// The served cognition read over a signed session: a Mind that has judged nothing answers /// `records: []` and a null `mind_state`; after a settlement the same Mind answers the committed -/// record and its derived `MindState`; and a Mind the caller holds no grant in answers exactly -/// the refusal a space that is no Mind at all answers. +/// record and its derived `MindState`; a Mind the caller holds no grant in answers exactly the +/// refusal a space that is no Mind at all answers; and a caller admitted to a Mind without +/// `knowledge_read` answers the distinct capability-coverage refusal. #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn read_cognition_serves_the_judgment_and_refuses_an_unadmitted_mind() { let fixture = Fixture::open().await; fixture.seed_second_mind().await; + // The second peer is admitted to the second Mind through `recall` alone: a live grant, so + // admission passes, but no `knowledge_read` coverage. It is granted before `serve` consumes + // the fixture, and it cannot affect the first principal, who holds nothing in that Mind. + fixture + .grant_in_second("grt_recall_only", PEER_TWO_PRINCIPAL, &["recall"]) + .await; let (_dir, serve) = fixture.serve(); let providers = MindProviders { reasoner: Some(Arc::new(SettlingReasoner(SETTLING_RATIONALE))), policy_hook: Some(Arc::new(AutoPolicy)), ..MindProviders::default() }; - let surface = surface(&serve, faces(hello("runtime", &[]), None, providers)); + let mut faces = faces(hello("runtime", &[]), None, providers); + // Two principals: the dialer reaches the first Mind, the second peer reaches only what it is + // granted in the second. + faces.principals = two_principal_admission(); + let surface = surface(&serve, faces); let session = connect(&surface, &[DELIBERATE, READ_COGNITION]).await; @@ -1452,6 +1463,46 @@ async fn read_cognition_serves_the_judgment_and_refuses_an_unadmitted_mind() { unadmitted, absent, "an unadmitted Mind and an absent Mind must be the byte-same refusal" ); + + // A peer admitted to the second Mind, but only through `recall`: admission passes and the + // missing `knowledge_read` coverage is what answers. The plan keeps those two refusals + // distinct — the coverage refusal may name the capability and the Mind, because the caller is + // already known to hold a live grant here. + let peer = connect_as(&surface, &PEER_TWO_SEED, &[READ_COGNITION]).await; + let uncovered = expect_reject( + peer.adapter + .invoke_tool(READ_COGNITION, cognition_arguments(SPACE_TWO)) + .await, + "the cognition read of a Mind the caller is admitted to without knowledge_read", + ); + assert_eq!(uncovered.code, SpokeRejectCode::NotAuthorized); + assert!( + uncovered.message.contains("knowledge_read"), + "the coverage refusal names the capability the caller lacks: {uncovered:?}" + ); + assert!( + uncovered + .details + .as_ref() + .and_then(|details| details.get("retry_class")) + .and_then(Value::as_str) + == Some("terminal"), + "a coverage gap cannot be retried away: {uncovered:?}" + ); + assert_ne!( + uncovered, unadmitted, + "an admitted caller short of one capability is not an unadmitted caller" + ); + let peer_absent = expect_reject( + peer.adapter + .invoke_tool(READ_COGNITION, cognition_arguments("spc_no_such_mind")) + .await, + "the second peer reading a space that is no Mind at all", + ); + assert_eq!( + peer_absent, unadmitted, + "every unadmitted caller answers the same target-free refusal" + ); } /// One deliberation response's judgment, held to the additive contract on every branch: the diff --git a/crates/mindcore-spoke/src/admission.rs b/crates/mindcore-spoke/src/admission.rs index 84369f76..26d16ef2 100644 --- a/crates/mindcore-spoke/src/admission.rs +++ b/crates/mindcore-spoke/src/admission.rs @@ -450,10 +450,17 @@ fn refuse_coverage(admission: &Admission<'_>, requirements: &[GrantRequirement<' let capability = requirements .first() .map_or("any", |requirement| requirement.capability); + refuse_space_coverage(admission.principal, admission.space.as_str(), capability) +} + +/// The post-admission coverage refusal: the caller holds a live grant in the space, so naming the +/// capability it lacks and the space it lacks it in discloses nothing a peer could not already +/// observe through its own grants. Callers that admit first and check coverage second reach this +/// without an [`Admission`] value to read; [`refuse_coverage`] answers through it, so both paths +/// speak one message. +pub(crate) fn refuse_space_coverage(principal: &str, space: &str, capability: &str) -> Reject { Reject::not_authorized(format!( - "principal {} holds no grant covering {capability} in space {}", - admission.principal, - admission.space.as_str() + "principal {principal} holds no grant covering {capability} in space {space}" )) } diff --git a/crates/mindcore-spoke/src/workflows.rs b/crates/mindcore-spoke/src/workflows.rs index e3f86aab..8d91ba39 100644 --- a/crates/mindcore-spoke/src/workflows.rs +++ b/crates/mindcore-spoke/src/workflows.rs @@ -9,7 +9,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, + knowledge_entry_visible_to_viewpoint, GrantRequirement, SpokeReject, SpokeRejectCode, SpokeResult, }; use spoke_schemas::data::cognition::{CognitionReference, CognitionReferenceKind}; @@ -25,7 +25,8 @@ use mindcore_base::boundary::CallerId; use mindcore_base::cognition::{carrier_records, CARRIER_NAMESPACE}; use mindcore_base::ids::{SpaceId, SubjectId}; use mindcore_base::ir::{ - CandidateState, MemoryJournalRow, MemoryRepository, ReceiptKey, ReceiptRead, ReceiptState, + CandidateState, MemoryGrantRow, MemoryJournalRow, MemoryRepository, ReceiptKey, ReceiptRead, + ReceiptState, }; use mindcore_spi::{ page_fact, snapshot_fact, AbsorbSnapshot, CandidateLifecycle, CaptureOutcome, @@ -62,9 +63,11 @@ pub(crate) struct AdmittedCarrier { /// Mind admission for the host-side `deliberate` handler: the caller's grant rows and the /// registry row read in one transaction, so a revocation cannot land between them, and every /// liveness decision runs the one grant rule (`live_grant`: unrevoked, unexpired, an -/// unparseable expiry fails closed). Returns the row-named carrier entry id, or the fixed -/// admission refusal — byte-equal whether the Mind exists, the grant is missing, revoked or -/// expired — so an unadmitted caller cannot tell the cases apart. +/// unparseable expiry fails closed). The deliberate handler needs a space-wide `knowledge_read` +/// grant of its own before it touches a carrier, so a caller admitted through another capability +/// only is refused here, before any carrier is read. Returns the row-named carrier entry id, or +/// the fixed admission refusal — byte-equal whether the Mind exists, the grant is missing, +/// revoked or expired — so an unadmitted caller cannot tell the cases apart. pub async fn admitted_carrier_entry( pool: &SqlitePool, principal_id: &str, @@ -78,18 +81,39 @@ pub async fn admitted_carrier_entry( .begin() .await .map_err(|e| Reject::internal(format!("the mind admission could not begin: {e}")).into_spoke())?; - let carrier = admitted_carrier(&mut tx, principal_id, space_id).await?; + let space = SpaceId::new(space_id.to_string()); + let rows = caller_grants(&mut tx, principal_id, &space).await?; + let now = Utc::now(); + let admitted = rows.iter().any(|row| { + row.principal_id.as_str() == principal_id + && row.subject_id.is_none() + && row.capabilities.iter().any(|cap| cap == KNOWLEDGE_READ) + && admission::live_grant(row, now) + }); + if !admitted { + return Err(Reject::admission_refusal().into_spoke()); + } + let carrier = registry_carrier(&mut tx, space_id).await?; let _ = tx.rollback().await; - Ok(carrier.carrier_entry_id) + carrier + .map(|carrier| carrier.carrier_entry_id) + .ok_or_else(|| Reject::admission_refusal().into_spoke()) } -/// Mind admission on the caller's transaction: the caller's grant rows and the registry row -/// read together, so a revocation cannot land between them. Returns the row-named carrier -/// location, or the fixed admission refusal — byte-equal whether the Mind exists, the grant is -/// missing, revoked or expired — so an unadmitted caller cannot tell the cases apart. The -/// space-wide `knowledge_read` grant is the one capability this admission requires: reading a -/// collection is not authority to the rest of the Mind, but a Mind without it has no readable -/// judgment at all. +/// Admission of one Mind-level read, in the order the plan fixes: a live grant of the caller's in +/// the named space — any capability admits, and an unknown, an unadmitted and a frozen-ungranted +/// Mind answer the one target-free refusal — then the space row, then the registry row the carrier +/// comes from, and only then the space-wide `knowledge_read` coverage. +/// +/// The two refusals are deliberately different answers. Admission answers the fixed refusal with +/// no details, because it must not say whether the named Mind exists. Coverage answers +/// [`admission::refuse_space_coverage`], naming the capability the caller lacks: it is reachable +/// only by a caller already known to hold a live grant in this Mind, so it discloses nothing about +/// a Mind the caller was never admitted to. +/// +/// Every read is confined to the caller's own grant rows. Another principal's malformed row never +/// reaches a decision, and a decode failure on the caller's own row answers the same target-free +/// refusal as a Mind that does not exist. pub(crate) async fn admitted_carrier( tx: &mut Tx<'_>, principal_id: &str, @@ -97,44 +121,84 @@ pub(crate) async fn admitted_carrier( ) -> Result { let repository = SqliteMemoryRepository; let space = SpaceId::new(space_id.to_string()); - // Only the caller's own rows, and only the liveness fields. Another principal's malformed - // row must not reach this decision: an indistinguishable refusal is the answer whether the - // decode failure lives on the caller's own row or the space is not a Mind at all, and a - // row that cannot decode admits nothing. - let rows = repository - .list_grants(tx, &space, Some(principal_id)) + let rows = caller_grants(tx, principal_id, &space).await?; + let now = Utc::now(); + if !rows + .iter() + .any(|row| row.principal_id.as_str() == principal_id && admission::live_grant(row, now)) + { + return Err(Reject::admission_refusal().into_spoke()); + } + // The space row is the plan's second step, and it is what `admit_mind` itself checks: a grant + // outlives its space only if the space row is deleted underneath it, which the store never + // does — a Mind's space row, registry row and carrier entry are written in one transaction. + // Keeping the read makes this path refuse exactly the Minds `admit_mind` refuses. + let space_row = repository.space(tx, &space).await.map_err(|error| { + Reject::internal(format!("the mind admission could not be read: {error}")).into_spoke() + })?; + if space_row.is_none() { + return Err(Reject::admission_refusal().into_spoke()); + } + let carrier = registry_carrier(tx, space_id) + .await? + .ok_or_else(|| Reject::admission_refusal().into_spoke())?; + // Coverage over the same caller-only rows: another principal's grants are neither needed for + // a space-wide requirement nor allowed to reach this decision. + let grants = admission::wire_grants(&rows).map_err(|reject| reject.into_spoke())?; + let requirement = GrantRequirement { + capability: KNOWLEDGE_READ, + subject_id: None, + context_ids: Vec::new(), + reads_shared: false, + subject_all: false, + }; + if !admission::covered(&grants, principal_id, space_id, now, &requirement) { + return Err( + admission::refuse_space_coverage(principal_id, space_id, KNOWLEDGE_READ).into_spoke(), + ); + } + Ok(carrier) +} + +/// The caller's own grant rows in `space`, decoded on the caller's transaction. +/// +/// Only the caller's rows, and only what a liveness decision needs. Another principal's malformed +/// row must not reach it: an indistinguishable refusal is the answer whether the decode failure +/// lives on the caller's own row or the space is not a Mind at all, and a row that cannot decode +/// admits nothing. +async fn caller_grants( + tx: &mut Tx<'_>, + principal_id: &str, + space: &SpaceId, +) -> Result, SpokeReject> { + SqliteMemoryRepository + .list_grants(tx, space, Some(principal_id)) .await .map_err(|error| match error { SqliteRepositoryError::InvalidRow(_) => Reject::admission_refusal().into_spoke(), other => Reject::internal(format!("the mind admission could not be read: {other}")) .into_spoke(), - })?; - let now = Utc::now(); - let admitted = rows.iter().any(|row| { - row.principal_id.as_str() == principal_id - && row.subject_id.is_none() - && row.capabilities.iter().any(|cap| cap == KNOWLEDGE_READ) - && admission::live_grant(row, now) - }); - if !admitted { - return Err(Reject::admission_refusal().into_spoke()); - } - // `live_grant` is the crate's one grant rule, but it is admission-internal. - // The row read follows in the same transaction: a revocation that commits - // before this statement is already covered by the grant check re-reading on - // its own transaction; one either sees both sides of it or neither. + }) +} + +/// The carrier location the registry row of `space_id` names, read on the caller's transaction. +async fn registry_carrier( + tx: &mut Tx<'_>, + space_id: &str, +) -> Result, SpokeReject> { let row: Option<(String, String)> = sqlx::query_as( "SELECT knowledge_collection, carrier_entry_id FROM minds WHERE space_id = ?", ) .bind(space_id) .fetch_optional(&mut **tx) .await - .map_err(|e| Reject::internal(format!("the mind admission could not be read: {e}")).into_spoke())?; - row.map(|(collection, carrier_entry_id)| AdmittedCarrier { + .map_err(|e| { + Reject::internal(format!("the mind admission could not be read: {e}")).into_spoke() + })?; + Ok(row.map(|(collection, carrier_entry_id)| AdmittedCarrier { collection, carrier_entry_id, - }) - .ok_or_else(|| Reject::admission_refusal().into_spoke()) + })) } /// The in-process workflow binding over one SQLite pool. From a7433133576961e915b0091abb41b323ec582708 Mon Sep 17 00:00:00 2001 From: Tang Bohao Date: Thu, 26 Nov 2026 14:18:29 +0800 Subject: [PATCH 11/27] refactor(serving): remove the three un-routed faces - Compose no `port.knowledge.*`, `history.*` or `knowledge.adopt` face: `ports` is the runtime's own `MindPorts`, carrying only the host's memory service. - Drop `spoke-knowledge`, `ke-ownership`, `spoke-history` and `spoke-knowledge-adoption` from `face_capabilities`; a call to each now answers `CAPABILITY_PORT_MISSING`. - Remove `AdoptionRoute`, the `ServeFaces` route fields, `validated`, and the two modules that lost their last caller; retire the loopback and surface assertions that pinned the removed faces, and pin the missing-port denial instead. --- crates/mindcore-runtime/src/adoption.rs | 1149 ------------ crates/mindcore-runtime/src/history_dedup.rs | 800 --------- crates/mindcore-runtime/src/lib.rs | 271 +-- crates/mindcore-runtime/tests/loopback.rs | 1692 ++---------------- crates/mindcore-runtime/tests/surface.rs | 530 +----- 5 files changed, 186 insertions(+), 4256 deletions(-) delete mode 100644 crates/mindcore-runtime/src/adoption.rs delete mode 100644 crates/mindcore-runtime/src/history_dedup.rs diff --git a/crates/mindcore-runtime/src/adoption.rs b/crates/mindcore-runtime/src/adoption.rs deleted file mode 100644 index 97417296..00000000 --- a/crates/mindcore-runtime/src/adoption.rs +++ /dev/null @@ -1,1149 +0,0 @@ -//! The `spoke-knowledge-adoption` face: one shared source read for the whole surface, and the -//! knowledge face's own collection as the destination. -//! -//! The port owns the one `BEGIN IMMEDIATE` transaction that covers the scope checks, the -//! retirement-chain resolution, the destination read and the create-only write, and commits only -//! when a copy was written. The copy, repeat and occupancy rules stay in the SPI helper; this -//! module supplies the two borrowed-transaction port handles, the store reads the chain needs and -//! the refusal hygiene. - -use std::io::Write; -use std::sync::Mutex as StdMutex; - -use async_trait::async_trait; -use serde_json::json; -use sqlx::{Sqlite, SqlitePool, Transaction}; -use tokio::sync::Mutex; - -use mindcore_base::knowledge::{ - adoption_fault as fixed_fault, KnowledgeScope, SERVED_REVISION_BOUND, -}; -use mindcore_spi::{adopt_knowledge_entry_typed, AdoptionOutcome}; -use mindcore_sqlite::{load_retirement_entry, read_entry, retirement_successors_of, write_entry}; -use spoke_operations::{ - filter_knowledge_entries_by_scope, resolve_retirement_chain, spoke_reject, AdoptionPort, - KnowledgeEntryPort, RetirementChainEntry, RetirementTerminal, SpokeReject, SpokeRejectCode, - SpokeResult, -}; -use spoke_schemas::{ - KnowledgeAdoptRequest, KnowledgeAdoptResponse, KnowledgeEntry, Principal, Scope, -}; - -use crate::AdoptionRoute; - -/// The adoption port over one host store. -/// -/// `destination` is the one collection the knowledge face itself serves, shared by every peer the -/// host admits to that scope: it holds one slot per `destination_entry_id`, the first adoption of a -/// given id claims it, a repeat is served that stored copy only at the anchor revision the copy -/// records, and a peer whose own admitted selection admits it reads the copy through the face's -/// `knowledge.get`/`list`. It is not the workflow route map: that map selects a *workflow* -/// collection per principal, and the knowledge face takes no per-principal collection. -pub(crate) struct AdoptionService { - pool: SqlitePool, - destination: KnowledgeScope, - source: AdoptionRoute, -} - -impl AdoptionService { - pub(crate) fn new( - pool: SqlitePool, - destination: KnowledgeScope, - source: AdoptionRoute, - ) -> Self { - Self { - pool, - destination, - source, - } - } -} - -#[async_trait] -impl AdoptionPort for AdoptionService { - async fn adopt_knowledge_entry( - &self, - _principal: &Principal, - scope: &Scope, - request: &KnowledgeAdoptRequest, - ) -> SpokeResult { - // A source scope this surface does not serve is the same generic absence as a missing - // source: the peer learns nothing about which scopes exist. - if request.source_scope_id.as_str() != self.source.scope_id { - return source_absent(); - } - // Connect refuses an out-of-scope destination before the port runs; the port keeps the - // same answer, so a direct caller cannot adopt outside the admitted scope either. - if request.destination_scope_id.as_str() != scope.scope_id.as_str() { - return not_authorized("adoption destination scope is outside the admitted context"); - } - if request.source_revision == 0 { - return spoke_reject( - SpokeRejectCode::InvalidInput, - "an adoption anchors a positive source revision", - None, - ); - } - let mut transaction = match self.pool.begin_with("BEGIN IMMEDIATE").await { - Ok(transaction) => transaction, - Err(error) => return SpokeResult::Reject(adoption_fault("begin", error)), - }; - let outcome = adopt_in( - &mut transaction, - &self.source, - &self.destination, - scope, - request, - ) - .await; - let outcome = match outcome { - SpokeResult::Ok(outcome) => outcome, - SpokeResult::Reject(reject) => return SpokeResult::Reject(adoption_refusal(reject)), - }; - // The response is built before the transaction settles: a copy Connect could not accept is - // a fault of the same call, never a committed write reported as a transport failure. - let created = matches!(&outcome, AdoptionOutcome::Created(_)); - let response = match adopted(outcome) { - SpokeResult::Ok(response) => response, - SpokeResult::Reject(reject) => { - let _ = transaction.rollback().await; - return SpokeResult::Reject(reject); - } - }; - // A repeat write is no write: the recorded copy is served and the reads leave nothing to - // commit. - let settled = match created { - true => transaction.commit().await, - false => transaction.rollback().await, - }; - if let Err(error) = settled { - return SpokeResult::Reject(adoption_fault("commit", error)); - } - SpokeResult::Ok(response) - } -} - -/// The one transaction's work: resolve the requested source to its terminal, then apply the -/// adoption rules over the two scoped handles. -async fn adopt_in( - transaction: &mut Transaction<'_, Sqlite>, - source: &AdoptionRoute, - destination: &KnowledgeScope, - admitted: &Scope, - request: &KnowledgeAdoptRequest, -) -> SpokeResult { - let gate = Mutex::new(transaction); - let collection = source.source.collection.as_str(); - let scope_id = source.scope_id.as_str(); - - let requested = { - let mut guard = gate.lock().await; - load_retirement_entry( - &mut guard, - collection, - scope_id, - request.source_entry_id.as_str(), - ) - .await - }; - let requested = match requested { - SpokeResult::Ok(Some(requested)) => requested, - SpokeResult::Ok(None) => return source_absent(), - SpokeResult::Reject(reject) => return SpokeResult::Reject(reject), - }; - // The resolver's closures answer `None` for both absence and a storage fault, so the fault - // is recorded here and replaces the retirement refusal the resolver builds from that `None`. - let fault: StdMutex> = StdMutex::new(None); - let resolved = resolve_retirement_chain( - requested, - |current: &RetirementChainEntry| { - let gate = &gate; - let fault = &fault; - let entry_id = current.entry_id.clone(); - async move { - let mut guard = gate.lock().await; - chain_lookup( - retirement_successors_of(&mut guard, collection, &entry_id).await, - fault, - ) - } - }, - |entry_id: &str| { - let gate = &gate; - let fault = &fault; - let entry_id = entry_id.to_string(); - async move { - let mut guard = gate.lock().await; - chain_lookup( - load_retirement_entry(&mut guard, collection, scope_id, &entry_id).await, - fault, - ) - } - }, - ) - .await; - let terminal = match chain_outcome(resolved, fault.into_inner().expect("fault slot")) { - SpokeResult::Ok(terminal) => terminal, - SpokeResult::Reject(reject) => return SpokeResult::Reject(reject), - }; - // A live source must sit at the revision asked for; a retired one is never compared, because - // the anchor records the terminal's own revision. - if terminal.source_entry_id == request.source_entry_id.as_str() - && terminal.source_revision != request.source_revision - { - return spoke_reject( - SpokeRejectCode::RevisionConflict, - format!( - "shared knowledge entry {} is not at revision {}", - request.source_entry_id.as_str(), - request.source_revision - ), - None, - ); - } - - let destination_id = request - .destination_entry_id - .as_deref() - .map(String::as_str) - .unwrap_or(terminal.source_entry_id.as_str()); - // The anchor records the terminal's revision, so a value the served wire cannot carry would - // commit a copy whose response Connect must reject as a transport fault. Refuse before the - // write instead: the caller's request was in range, the stored source is not servable. - if terminal.source_revision > SERVED_REVISION_BOUND { - return spoke_reject( - SpokeRejectCode::InternalError, - format!( - "shared knowledge entry {} sits at revision {} outside the served range", - terminal.source_entry_id, terminal.source_revision - ), - None, - ); - } - let src = AdoptionSource { - collection, - gate: &gate, - }; - let dst = AdoptionDestination { - collection: destination.collection.as_str(), - scope: admitted, - gate: &gate, - }; - adopt_knowledge_entry_typed( - &src, - &dst, - &terminal.source_scope_id, - &terminal.source_entry_id, - destination_id, - terminal.source_revision, - ) - .await -} - -/// The call's read half: the shared source. -/// -/// The adoption only ever reads the source. `KnowledgeEntryPort` carries a write because the -/// destination needs one, so the source handle refuses that write before it touches the store. -struct AdoptionSource<'a, 'b, 'tx> { - collection: &'a str, - gate: &'b Mutex<&'b mut Transaction<'tx, Sqlite>>, -} - -#[async_trait] -impl KnowledgeEntryPort for AdoptionSource<'_, '_, '_> { - async fn get_knowledge_entry(&self, entry_id: &str) -> SpokeResult { - let mut gate = self.gate.lock().await; - read_entry(&mut gate, self.collection, entry_id).await - } - - async fn put_knowledge_entry( - &self, - _entry: KnowledgeEntry, - _expected_base_revision: Option, - ) -> SpokeResult { - spoke_reject( - SpokeRejectCode::InternalError, - "the adoption source is read-only", - None, - ) - } -} - -/// The call's write half: the knowledge face's own collection, under the admitted selection. -/// -/// The host's configured collection is the selector; the admitted `Scope` additionally refines -/// which entries of that collection this call may serve or write, so an entry the host admitted the -/// scope without is neither returned nor copied. An occupant outside that selection answers the -/// ordinary occupancy refusal, never a distinct "not authorized": the answer reports the slot as -/// taken either way, and never what the occupant holds. -struct AdoptionDestination<'a, 'b, 'tx> { - collection: &'a str, - scope: &'a Scope, - gate: &'b Mutex<&'b mut Transaction<'tx, Sqlite>>, -} - -#[async_trait] -impl KnowledgeEntryPort for AdoptionDestination<'_, '_, '_> { - async fn get_knowledge_entry(&self, entry_id: &str) -> SpokeResult { - let mut gate = self.gate.lock().await; - let entry = read_entry(&mut gate, self.collection, entry_id).await; - match entry { - // An occupant outside the admitted selection answers the ordinary occupancy refusal, - // byte for byte the one a visible occupant gets: the answer reports the slot as taken - // either way, and never what the occupant holds. - SpokeResult::Ok(entry) => match admitted_destination(&entry, self.scope) { - SpokeResult::Ok(true) => SpokeResult::Ok(entry), - SpokeResult::Ok(false) => occupied(&entry.entry_id), - SpokeResult::Reject(reject) => SpokeResult::Reject(reject), - }, - // `read_entry` is live-only, so a retired row arrives here as an absence. It is still a - // taken slot: answering `NotFound` would let the SPI helper's revision gate report the - // destination's retirement while a live occupant answers occupancy before that gate. - SpokeResult::Reject(reject) - if reject.code == SpokeRejectCode::KnowledgeEntryNotFound => - { - match retirement_successors_of(&mut gate, self.collection, entry_id).await { - SpokeResult::Ok(Some(_)) => occupied(entry_id), - SpokeResult::Ok(None) => SpokeResult::Reject(reject), - SpokeResult::Reject(fault) => SpokeResult::Reject(fault), - } - } - SpokeResult::Reject(reject) => SpokeResult::Reject(reject), - } - } - - async fn put_knowledge_entry( - &self, - entry: KnowledgeEntry, - expected_base_revision: Option, - ) -> SpokeResult { - // A copy outside the admitted selection is not a slot this call may claim; it answers the - // same occupancy as an occupied slot, so a free-but-unusable slot is not distinguishable - // from an occupied one either. - match admitted_destination(&entry, self.scope) { - SpokeResult::Ok(true) => {} - SpokeResult::Ok(false) => return occupied(&entry.entry_id), - SpokeResult::Reject(reject) => return SpokeResult::Reject(reject), - } - let mut gate = self.gate.lock().await; - write_entry(&mut gate, self.collection, entry, expected_base_revision).await - } -} - -/// Whether one destination entry passes the admitted scope's selection: the same SPOKE predicate -/// the routed knowledge face applies to its own served reads and writes. -fn admitted_destination(entry: &KnowledgeEntry, scope: &Scope) -> SpokeResult { - match filter_knowledge_entries_by_scope(std::slice::from_ref(entry), scope) { - SpokeResult::Ok(visible) => SpokeResult::Ok(!visible.is_empty()), - SpokeResult::Reject(reject) => SpokeResult::Reject(reject), - } -} - -/// A storage fault under adoption. -/// -/// The wire carries a fixed message and the failing stage: a raw sqlx or decoder diagnostic names -/// local tables, columns and stored payloads, so it goes to the host's stderr and never into the -/// signed refusal. -fn adoption_fault(stage: &str, diagnostic: impl std::fmt::Display) -> SpokeReject { - let _ = writeln!( - std::io::stderr(), - "mindcore adoption {stage} fault: {diagnostic}" - ); - fixed_fault(stage) -} - -/// The contract's own refusals travel as they are; anything else a port reports is a storage or -/// stored-payload fault, and its text stays host-side. -fn adoption_refusal(reject: SpokeReject) -> SpokeReject { - match reject.code { - SpokeRejectCode::NotFound - | SpokeRejectCode::NotAuthorized - | SpokeRejectCode::RevisionConflict - | SpokeRejectCode::SourceRetired - | SpokeRejectCode::AdoptionAnchorImmutable - | SpokeRejectCode::InvalidInput => reject, - _ => adoption_fault("store", reject.message), - } -} - -/// The adopted copy as the response envelope. -/// -/// Built before the transaction settles, so a copy the served wire cannot describe refuses the -/// call instead of committing and then failing as a transport fault. -fn adopted(outcome: AdoptionOutcome) -> SpokeResult { - let (word, entry) = match outcome { - AdoptionOutcome::Created(entry) => ("adopted", entry), - AdoptionOutcome::AlreadyPresent(entry) => ("already_present", entry), - }; - if !served_entry_revision(&entry) { - return SpokeResult::Reject(adoption_fault( - "response", - format!( - "adopted copy {} carries a revision outside the served range", - entry.entry_id - ), - )); - } - match serde_json::from_value(json!({ "outcome": word, "entry": entry })) { - Ok(response) => SpokeResult::Ok(response), - Err(error) => SpokeResult::Reject(adoption_fault("response", error)), - } -} - -/// Whether the served response's own revision member sits inside the served range. A created copy -/// is assigned by the store, but a destination slot that already held this adoption can carry a -/// stored revision above it. -fn served_entry_revision(entry: &KnowledgeEntry) -> bool { - entry - .revision - .is_none_or(|revision| revision <= SERVED_REVISION_BOUND) -} - -/// One chain lookup as the resolver's closures answer it: absence as `None`, and a storage fault -/// recorded in the slot before its own `None`, so the resolver's refusal is not the last word. -fn chain_lookup( - looked_up: SpokeResult>, - fault: &StdMutex>, -) -> Option { - match looked_up { - SpokeResult::Ok(found) => found, - SpokeResult::Reject(reject) => { - *fault.lock().expect("fault slot") = Some(reject); - None - } - } -} - -/// The resolver's outcome with the recorded fault preferred over it: the resolver builds a -/// `SOURCE_RETIRED` from the `None` a fault produced, so the fault must win or a storage fault -/// would read as retirement. -fn chain_outcome( - resolved: SpokeResult, - fault: Option, -) -> SpokeResult { - match (resolved, fault) { - (_, Some(fault)) => SpokeResult::Reject(fault), - (resolved, None) => resolved, - } -} - -fn source_absent() -> SpokeResult { - spoke_reject( - SpokeRejectCode::NotFound, - "source knowledge entry not found", - None, - ) -} - -/// The ordinary occupancy answer: the slot is taken, and it reports nothing about its occupant -/// beyond occupancy. A visible occupant and one the admitted selection hides answer byte-identically -/// — the same disclosure a create-only `put_knowledge_entry` on this face already makes — so the -/// answer never reports the occupying entry's content, revision or visibility. -fn occupied(entry_id: &str) -> SpokeResult { - spoke_reject( - SpokeRejectCode::RevisionConflict, - format!("knowledge entry {entry_id} already exists"), - None, - ) -} - -fn not_authorized(message: &str) -> SpokeResult { - spoke_reject(SpokeRejectCode::NotAuthorized, message, None) -} - -#[cfg(test)] -mod tests { - use std::collections::HashMap; - use std::num::NonZeroU64; - - use serde_json::{json, Map}; - use tempfile::TempDir; - - use mindcore_base::knowledge::ADOPTION_FAULT; - - use mindcore_sqlite::{read_carrier_header, MindStore}; - use spoke_schemas::knowledge_entry::{ - KnowledgeEntryBody, KnowledgeEntryCanonicalName as CanonicalName, - }; - - use super::*; - - const SHARED_SCOPE: &str = "spc_shared"; - const DESTINATION_SCOPE: &str = "spc_destination"; - const DESTINATION_COLLECTION: &str = "wren"; - - fn entry(entry_id: &str) -> KnowledgeEntry { - KnowledgeEntry { - adoption_anchor: None, - body: KnowledgeEntryBody { - summary: Some(format!("{entry_id} summary")), - ..KnowledgeEntryBody::default() - }, - canonical_name: CanonicalName::try_from(format!("{entry_id} name")) - .expect("non-empty canonical name"), - created_at: None, - disclosure: None, - entry_id: entry_id.to_string(), - entry_type: "location".to_string(), - extensions: HashMap::new(), - modules: HashMap::new(), - owner: None, - revision: None, - schema_version: NonZeroU64::new(1).expect("non-zero wire baseline"), - source_anchor: None, - status: "confirmed".to_string(), - updated_at: None, - } - } - - fn principal(principal_id: &str) -> Principal { - serde_json::from_value(json!({ "principal_id": principal_id, "extensions": {} })) - .expect("principal JSON matches the schema") - } - - fn scope(scope_id: &str) -> Scope { - serde_json::from_value(json!({ "scope_id": scope_id })) - .expect("scope JSON matches the schema") - } - - fn request(source_entry_id: &str, source_revision: u64) -> KnowledgeAdoptRequest { - serde_json::from_value(json!({ - "source_scope_id": SHARED_SCOPE, - "source_entry_id": source_entry_id, - "source_revision": source_revision, - "destination_scope_id": DESTINATION_SCOPE, - "idempotency_key": format!("{source_entry_id}-{source_revision}"), - })) - .expect("request JSON matches the schema") - } - - /// One store with the shared source's rows and the port over it: the destination is the - /// knowledge face's own collection, the same one it serves to every admitted peer. - async fn service() -> (TempDir, MindStore, AdoptionService) { - let dir = TempDir::new().expect("temporary directory"); - let store = MindStore::open(&dir.path().join("adoption.db")) - .await - .expect("open store"); - let shared = store.knowledge(KnowledgeScope::new("shared")); - for entry_id in ["ke_source", "ke_retired", "ke_terminal"] { - let written = shared.put_knowledge_entry(entry(entry_id), None).await; - assert!( - matches!(written, SpokeResult::Ok(_)), - "seed shared/{entry_id}: {written:?}" - ); - } - let service = AdoptionService::new( - store.pool(), - KnowledgeScope::new(DESTINATION_COLLECTION), - AdoptionRoute { - scope_id: SHARED_SCOPE.to_string(), - source: KnowledgeScope::new("shared"), - }, - ); - (dir, store, service) - } - - fn ok(result: SpokeResult, context: &str) -> T { - match result { - SpokeResult::Ok(value) => value, - SpokeResult::Reject(reject) => { - panic!("{context}: unexpectedly rejected with {reject:?}") - } - } - } - - fn refused(result: SpokeResult, context: &str) -> SpokeReject { - match result { - SpokeResult::Reject(reject) => reject, - SpokeResult::Ok(value) => panic!("{context}: unexpectedly accepted with {value:?}"), - } - } - - /// The slot's live row still sits at `revision` and carries `marker`: a refused adoption wrote - /// nothing, so it neither advanced the revision nor wrote a retirement marker. Reading the live - /// row rather than a historical revision is what makes that a statement about current state. - async fn slot_unchanged( - destination: &mindcore_sqlite::ScopedKnowledgeStore, - revision: Option, - marker: Option<&str>, - context: &str, - ) { - let row = ok( - destination.get_entry_including_superseded("ke_slot").await, - "read the destination row", - ); - assert_eq!( - (row.entry.revision, row.superseded_by), - (revision, marker.map(str::to_string)), - "{context}" - ); - } - - /// The adoption destination's own read of one slot, at the port boundary the SPI helper calls. - /// A test reaches it directly because the served face's earlier refusals can intercept a call - /// before this read runs, which would leave the read itself unpinned. - async fn destination_read(store: &MindStore, admitted: &Scope, entry_id: &str) -> SpokeReject { - let mut transaction = store - .pool() - .begin() - .await - .expect("begin the destination read"); - let gate = Mutex::new(&mut transaction); - // The port borrows the gate's `&mut transaction`, so the read runs inside this block: its - // end is what releases the borrow before the rollback below. - let answer = { - let port = AdoptionDestination { - collection: DESTINATION_COLLECTION, - scope: admitted, - gate: &gate, - }; - port.get_knowledge_entry(entry_id).await - }; - transaction.rollback().await.expect("roll back the read"); - match answer { - SpokeResult::Reject(reject) => reject, - SpokeResult::Ok(entry) => panic!("{entry_id}: unexpectedly served {entry:?}"), - } - } - - /// The first call writes the copy the anchor names, and the repeat serves that stored copy - /// instead of writing a second one. - #[tokio::test] - async fn an_admitted_principal_adopts_once_and_repeats_from_the_stored_anchor() { - let (_dir, store, service) = service().await; - let owner = principal("prn_owner"); - let admitted = scope(DESTINATION_SCOPE); - - let created = ok( - service - .adopt_knowledge_entry(&owner, &admitted, &request("ke_source", 1)) - .await, - "adopt", - ); - let created = serde_json::to_value(&created).expect("response serializes"); - assert_eq!(created["outcome"], "adopted"); - assert_eq!(created["entry"]["entry_id"], "ke_source"); - assert_eq!( - created["entry"]["adoption_anchor"]["source_scope_id"], - SHARED_SCOPE - ); - assert_eq!( - created["entry"]["adoption_anchor"]["source_entry_id"], - "ke_source" - ); - assert_eq!(created["entry"]["adoption_anchor"]["source_revision"], 1); - - let repeat = ok( - service - .adopt_knowledge_entry(&owner, &admitted, &request("ke_source", 1)) - .await, - "repeat", - ); - let repeat = serde_json::to_value(&repeat).expect("response serializes"); - assert_eq!(repeat["outcome"], "already_present"); - assert_eq!(repeat["entry"]["revision"], created["entry"]["revision"]); - - let stale = refused( - service - .adopt_knowledge_entry(&owner, &admitted, &request("ke_source", 2)) - .await, - "a stale source revision", - ); - assert_eq!(stale.code, SpokeRejectCode::RevisionConflict); - assert!(stale.details.is_none(), "{stale:?}"); - - let absent = refused( - service - .adopt_knowledge_entry(&owner, &admitted, &request("ke_missing", 1)) - .await, - "a source the shared collection does not hold", - ); - assert_eq!(absent.code, SpokeRejectCode::NotFound); - assert!(absent.details.is_none(), "{absent:?}"); - - let mut elsewhere = request("ke_source", 1); - elsewhere.source_scope_id = "spc_other".parse().expect("scope id"); - let foreign = refused( - service - .adopt_knowledge_entry(&owner, &admitted, &elsewhere) - .await, - "another source scope", - ); - assert_eq!(foreign.code, SpokeRejectCode::NotFound); - assert_eq!(foreign.message, absent.message); - - let unauthorized = refused( - service - .adopt_knowledge_entry(&owner, &scope("spc_elsewhere"), &request("ke_source", 1)) - .await, - "another destination scope", - ); - assert_eq!(unauthorized.code, SpokeRejectCode::NotAuthorized); - - // No route map gates adoption: a second admitted principal adopts into the same collection - // the knowledge face serves, which is where `knowledge.get` reads it back. - let second = ok( - service - .adopt_knowledge_entry( - &principal("prn_second"), - &admitted, - &request("ke_terminal", 1), - ) - .await, - "a second admitted principal", - ); - assert_eq!( - serde_json::to_value(&second).expect("response serializes")["entry"]["entry_id"], - "ke_terminal" - ); - let stored = ok( - store - .knowledge(KnowledgeScope::new(DESTINATION_COLLECTION)) - .get_knowledge_entry("ke_terminal") - .await, - "read the second principal's copy from the knowledge face's collection", - ); - assert_eq!(stored.entry_id, "ke_terminal"); - - let zero = refused( - service - .adopt_knowledge_entry(&owner, &admitted, &request("ke_source", 0)) - .await, - "a zero source revision", - ); - assert_eq!(zero.code, SpokeRejectCode::InvalidInput); - } - - /// A retired source resolves to its live terminal: the copy is written under the terminal and - /// its anchor names that terminal's triple, whatever revision the request named. - #[tokio::test] - async fn a_retired_source_adopts_from_its_live_terminal() { - let (_dir, store, service) = service().await; - ok( - store - .knowledge(KnowledgeScope::new("shared")) - .supersede_entry("ke_retired", 1, "ke_terminal") - .await, - "retire the source", - ); - - let adopted = ok( - service - .adopt_knowledge_entry( - &principal("prn_owner"), - &scope(DESTINATION_SCOPE), - &request("ke_retired", 1), - ) - .await, - "adopt a retired source", - ); - let adopted = serde_json::to_value(&adopted).expect("response serializes"); - assert_eq!(adopted["outcome"], "adopted"); - assert_eq!( - adopted["entry"]["entry_id"], "ke_terminal", - "the copy takes the terminal's id" - ); - let anchor = &adopted["entry"]["adoption_anchor"]; - assert_eq!(anchor["source_entry_id"], "ke_terminal"); - assert_eq!(anchor["source_scope_id"], SHARED_SCOPE); - assert_eq!(anchor["source_revision"], 1); - } - - /// A storage fault on the requested entry is `INTERNAL_ERROR` with the fixed message, never - /// the `NOT_FOUND` its absence answers. - #[tokio::test] - async fn an_initial_retirement_fault_is_internal_error() { - let (_dir, store, service) = service().await; - let seed = store.pool(); - sqlx::query( - "INSERT INTO knowledge_entries \ - (collection, entry_id, revision, payload, created_at, updated_at) \ - VALUES ('shared', 'ke_broken', 1, '{ not an entry', \ - '2026-11-21T00:00:00Z', '2026-11-21T00:00:00Z')", - ) - .execute(&seed) - .await - .expect("seed an undecodable stored payload"); - - let refused = refused( - service - .adopt_knowledge_entry( - &principal("prn_owner"), - &scope(DESTINATION_SCOPE), - &request("ke_broken", 1), - ) - .await, - "an undecodable source", - ); - assert_eq!(refused.code, SpokeRejectCode::InternalError); - assert_eq!(refused.message, ADOPTION_FAULT); - assert_eq!( - refused - .details - .as_ref() - .and_then(|details| details.get("kind")), - Some(&json!("store")) - ); - assert!( - !refused.message.contains("payload"), - "the diagnostic stays host-side: {refused:?}" - ); - } - - /// A fault on a mid-chain hop is not retirement: the chain cannot be resolved, so the call - /// answers `INTERNAL_ERROR` rather than `SOURCE_RETIRED`. - #[tokio::test] - async fn a_mid_chain_retirement_fault_is_internal_error() { - let (_dir, store, service) = service().await; - let seed = store.pool(); - sqlx::query( - "INSERT INTO knowledge_entries \ - (collection, entry_id, revision, payload, created_at, updated_at) \ - VALUES ('shared', 'ke_broken', 1, '{ not an entry', \ - '2026-11-21T00:00:00Z', '2026-11-21T00:00:00Z')", - ) - .execute(&seed) - .await - .expect("seed an undecodable stored payload"); - sqlx::query( - "UPDATE knowledge_entries SET superseded_by = 'ke_broken' \ - WHERE collection = 'shared' AND entry_id = 'ke_source'", - ) - .execute(&seed) - .await - .expect("retire the source into the undecodable hop"); - - let refused = refused( - service - .adopt_knowledge_entry( - &principal("prn_owner"), - &scope(DESTINATION_SCOPE), - &request("ke_source", 1), - ) - .await, - "a mid-chain undecodable hop", - ); - assert_eq!(refused.code, SpokeRejectCode::InternalError); - assert_eq!(refused.message, ADOPTION_FAULT); - assert_eq!( - refused - .details - .as_ref() - .and_then(|details| details.get("kind")), - Some(&json!("store")) - ); - } - - /// A recorded fault wins over the `SOURCE_RETIRED` the resolver builds from the `None` that - /// fault produced; without a fault the resolver's own outcome stands. The successor lookup and - /// the mid-chain load share this interpretation, so both load sites are covered here. - #[test] - fn a_recorded_chain_fault_replaces_the_resolvers_retirement_refusal() { - let retired = SpokeReject { - code: SpokeRejectCode::SourceRetired, - message: "retirement chain is broken: the successor entry is missing".to_string(), - details: Some(Map::from_iter([( - "retirement_chain".to_string(), - json!(["ke_retired"]), - )])), - }; - let fault = SpokeReject { - code: SpokeRejectCode::InternalError, - message: "knowledge retirement marker could not be read: no such table".to_string(), - details: None, - }; - - let replaced = refused( - chain_outcome(SpokeResult::Reject(retired.clone()), Some(fault.clone())), - "a fault under a retirement refusal", - ); - assert_eq!( - replaced, fault, - "the fault is preferred, not the retirement" - ); - assert_ne!( - replaced.code, - SpokeRejectCode::SourceRetired, - "a storage fault never reads as retirement" - ); - - let preserved = refused( - chain_outcome(SpokeResult::Reject(retired.clone()), None), - "a retirement refusal with no recorded fault", - ); - assert_eq!( - preserved, retired, - "genuine absence or retirement keeps its refusal" - ); - - let terminal = RetirementTerminal { - source_scope_id: SHARED_SCOPE.to_string(), - source_entry_id: "ke_terminal".to_string(), - source_revision: 1, - }; - let resolved = ok( - chain_outcome(SpokeResult::Ok(terminal), None), - "a resolved chain", - ); - assert_eq!(resolved.source_entry_id, "ke_terminal"); - } - - /// A lookup answers the resolver with absence and records its fault in the shared slot, so the - /// interpretation above has something to prefer. - #[test] - fn a_failed_chain_lookup_records_its_fault_and_answers_absence() { - let fault = StdMutex::new(None); - let successors: SpokeResult>> = spoke_reject( - SpokeRejectCode::InternalError, - "knowledge retirement marker could not be read: no such table", - None, - ); - assert!( - chain_lookup(successors, &fault).is_none(), - "a fault reads as absence to the resolver" - ); - assert_eq!( - fault.lock().expect("fault slot").as_ref().map(|f| f.code), - Some(SpokeRejectCode::InternalError) - ); - - let quiet = StdMutex::new(None); - assert_eq!( - chain_lookup( - SpokeResult::Ok(Some(vec!["ke_terminal".to_string()])), - &quiet - ), - Some(vec!["ke_terminal".to_string()]) - ); - assert!( - quiet.lock().expect("fault slot").is_none(), - "a good read records nothing" - ); - assert!(chain_lookup::(SpokeResult::Ok(None), &quiet).is_none()); - assert!( - quiet.lock().expect("fault slot").is_none(), - "absence records nothing" - ); - } - - /// The adoption only reads its source: the write its port must expose refuses before it - /// touches the store, and the row keeps the revision it was seeded at. - #[tokio::test] - async fn the_adoption_source_handle_refuses_a_write() { - let (_dir, _store, service) = service().await; - let mut transaction = service - .pool - .begin() - .await - .expect("begin the call's transaction"); - let gate = Mutex::new(&mut transaction); - let src = AdoptionSource { - collection: "shared", - gate: &gate, - }; - - let refused = refused( - src.put_knowledge_entry(entry("ke_source"), None).await, - "a write through the source handle", - ); - assert_eq!(refused.code, SpokeRejectCode::InternalError); - assert_eq!(refused.message, "the adoption source is read-only"); - - let header = ok( - read_carrier_header(&mut *transaction, "shared", "ke_source").await, - "the shared source keeps its row", - ); - assert_eq!(header.revision, 1); - transaction.rollback().await.expect("roll back the read"); - } - - /// An occupied destination slot answers one occupancy whatever the admitted selection makes of - /// the occupant: a hidden occupant's refusal is byte-identical to a visible one's, so the answer - /// reports occupancy and never what the occupant holds. A free slot the selection cannot claim - /// answers the same refusal and writes nothing. - #[tokio::test] - async fn a_hidden_occupant_answers_the_same_occupancy_as_a_visible_one() { - let (_dir, store, service) = service().await; - let owner = principal("prn_owner"); - // An occupant neither anchor names: the SPI answers the ordinary occupancy for it. - ok( - store - .knowledge(KnowledgeScope::new(DESTINATION_COLLECTION)) - .put_knowledge_entry(entry("ke_source"), None) - .await, - "seed the destination occupant", - ); - // The same admitted id, once with an entry-id selection that never holds the occupant. - let hidden: Scope = serde_json::from_value(json!({ - "scope_id": DESTINATION_SCOPE, - "entry_ids": ["ke_somebody_else"], - })) - .expect("scope JSON matches the schema"); - - let shown = refused( - service - .adopt_knowledge_entry(&owner, &scope(DESTINATION_SCOPE), &request("ke_source", 1)) - .await, - "a visible occupant", - ); - let concealed = refused( - service - .adopt_knowledge_entry(&owner, &hidden, &request("ke_source", 1)) - .await, - "a hidden occupant", - ); - assert_eq!(shown.code, SpokeRejectCode::RevisionConflict); - assert!(shown.details.is_none(), "{shown:?}"); - assert_eq!( - concealed, shown, - "a hidden occupant must not be distinguishable from a visible one" - ); - - // A free slot the selection cannot claim is not adoptable either: same refusal, no row. - let claimed = refused( - service - .adopt_knowledge_entry(&owner, &hidden, &request("ke_terminal", 1)) - .await, - "a free slot outside the admitted selection", - ); - assert_eq!( - claimed.code, - SpokeRejectCode::RevisionConflict, - "an unusable free slot answers the occupancy: {claimed:?}" - ); - assert!(claimed.details.is_none(), "{claimed:?}"); - assert!( - matches!( - store - .knowledge(KnowledgeScope::new(DESTINATION_COLLECTION)) - .get_knowledge_entry("ke_terminal") - .await, - SpokeResult::Reject(_) - ), - "the unusable slot stays free" - ); - - // The same slot under an admitting selection still creates. - ok( - service - .adopt_knowledge_entry( - &owner, - &scope(DESTINATION_SCOPE), - &request("ke_terminal", 1), - ) - .await, - "the admitting selection claims the free slot", - ); - } - - /// One destination slot answers the same occupancy whether its occupant is live and admitted, - /// live and hidden by the admission, or retired. The retired row resolves inside the destination - /// read rather than through a create-only put, so only this comparison shows both states agree. - #[tokio::test] - async fn a_retired_destination_occupant_answers_the_same_occupancy_as_a_live_one() { - let (_dir, store, service) = service().await; - let owner = principal("prn_owner"); - let destination = store.knowledge(KnowledgeScope::new(DESTINATION_COLLECTION)); - for entry_id in ["ke_slot", "ke_successor"] { - ok( - destination.put_knowledge_entry(entry(entry_id), None).await, - "seed the destination occupant", - ); - } - // The same admitted id, once with an entry-id selection that never holds the occupant. - let hidden: Scope = serde_json::from_value(json!({ - "scope_id": DESTINATION_SCOPE, - "entry_ids": ["ke_somebody_else"], - })) - .expect("scope JSON matches the schema"); - let mut claim = request("ke_source", 1); - claim.destination_entry_id = Some("ke_slot".parse().expect("non-empty destination id")); - - let live = refused( - service - .adopt_knowledge_entry(&owner, &scope(DESTINATION_SCOPE), &claim) - .await, - "a live occupant", - ); - slot_unchanged( - &destination, - Some(1), - None, - "a refused claim of a live slot", - ) - .await; - - let concealed = refused( - service.adopt_knowledge_entry(&owner, &hidden, &claim).await, - "a live occupant the selection hides", - ); - slot_unchanged( - &destination, - Some(1), - None, - "a refused claim of a hidden live slot", - ) - .await; - - // The read the SPI helper reaches after a live occupant answers occupancy. A retired row - // must answer it identically: reporting an absence here is what lets a revision gate - // report the destination's retirement while the slot is in fact taken. - let read_live = destination_read(&store, &hidden, "ke_slot").await; - - let retired = ok( - destination - .supersede_entry("ke_slot", 1, "ke_successor") - .await, - "retire the occupant", - ); - let retired_shown = refused( - service - .adopt_knowledge_entry(&owner, &scope(DESTINATION_SCOPE), &claim) - .await, - "a retired occupant", - ); - slot_unchanged( - &destination, - Some(retired), - Some("ke_successor"), - "a refused claim of a retired slot", - ) - .await; - - let retired_concealed = refused( - service.adopt_knowledge_entry(&owner, &hidden, &claim).await, - "a retired occupant the selection hides", - ); - slot_unchanged( - &destination, - Some(retired), - Some("ke_successor"), - "a refused claim of a retired hidden slot", - ) - .await; - - // An unreachable destination read is what the SPI helper turns into a revision-gate answer, - // so the port itself must report the retired row as taken, byte for byte as it reports a - // live one. - let read_retired = destination_read(&store, &hidden, "ke_slot").await; - assert_eq!( - read_retired, read_live, - "a retired row must read as occupancy, never as an absence" - ); - assert_eq!(read_retired.code, SpokeRejectCode::RevisionConflict); - assert!(read_retired.details.is_none(), "{read_retired:?}"); - - assert_eq!(live.code, SpokeRejectCode::RevisionConflict); - assert!(live.details.is_none(), "{live:?}"); - for (state, reject) in [ - ("hidden", &concealed), - ("retired", &retired_shown), - ("retired and hidden", &retired_concealed), - ] { - assert_eq!( - reject, &live, - "a {state} occupant must not be distinguishable from a live visible one" - ); - } - } -} diff --git a/crates/mindcore-runtime/src/history_dedup.rs b/crates/mindcore-runtime/src/history_dedup.rs deleted file mode 100644 index 291455c3..00000000 --- a/crates/mindcore-runtime/src/history_dedup.rs +++ /dev/null @@ -1,800 +0,0 @@ -//! The `history.revisions.prune` dedup record, on the store's own pool. -//! -//! Connect calls the store only after the port returned, so the prune is already committed when -//! its outcome is written. A record-only store would leave the window between the two open: a -//! same-key retry after a crash in that gap would execute against the current state and delete -//! checkpoints the first call never saw. [`SqliteHistoryDedupStore::lookup`] therefore claims the -//! key first; a claim with no outcome answers `Evicted`, which Connect turns into -//! `RECEIPT_EXPIRED` without reaching the port. -//! -//! Faults fail closed: a statement fault, and an outcome that does not decode, both answer -//! `Evicted`. Re-executing a destructive prune is the outcome this store exists to prevent. -//! -//! Each store serves one namespace — the collection its history surface routes to — and keeps it in -//! a column beside the key rather than in a framed string: a collection name may contain any -//! character, so no separator could keep `(namespace, key)` pairs distinct. Two history surfaces on -//! one database can share a wire scope, a principal and an idempotency key while reading different -//! collections; without the namespace the second would replay a prune of the first surface's -//! collection, or refuse it. -//! -//! One serving process per database is the host's obligation (see `I-000109`): the claim row stops -//! a second process from executing, but it answers `RECEIPT_EXPIRED` instead of waiting for the -//! first, so two processes would turn a replay into a refusal. -//! -//! Each principal holds at most [`HISTORY_DEDUP_CAPACITY`] rows per namespace, claims and recorded -//! outcomes alike. Nothing is ever deleted and no clock is read: the table is a hard bound, not a -//! working set that ages out, so a recorded outcome replays for the database's lifetime and no -//! forward clock jump can turn a live dedup record into an executed prune. At the bound a fresh key -//! answers `Evicted` — Connect's `RECEIPT_EXPIRED` — without the prune being executed. -//! -//! The quota is per caller, parsed out of the retry identity, so one high-churn principal can -//! exhaust only its own quota and never disable prune for another on the same collection. A key -//! that is not the canonical retry identity is accounted to -//! [`HISTORY_DEDUP_UNKNOWN_PRINCIPAL`] rather than to itself, so a stream of such keys shares one -//! quota instead of minting a fresh one per key. A host that wants more headroom raises -//! [`HISTORY_DEDUP_CAPACITY`] or recreates the database; there is no eviction to wait for. -//! -//! Claim capacity belongs to `lookup`: it inserts the claim and refuses an unseen key at the bound. -//! `record` only fills a claim that already exists, so a caller that records without claiming -//! writes nothing and can never produce an outcome for a prune that did not run. - -use std::io::Write; - -use async_trait::async_trait; -use serde_json::{json, Value}; -use sqlx::SqlitePool; - -use spoke_connect::remote::{HistoryDedupLookup, HistoryDedupRecord, HistoryDedupStore}; -use spoke_operations::{SpokeReject, SpokeRejectCode, SpokeResult}; - -/// The most rows one principal may hold in one namespace. A claim counts, because a claim is what -/// keeps a replay out of the port; a principal at the bound refuses unseen keys instead of inserting -/// past it. -const HISTORY_DEDUP_CAPACITY: i64 = 4096; - -/// The quota bucket every key that is not the canonical retry identity is accounted to. -/// -/// One shared bucket, not one per key: a per-key fallback would let a caller mint unparsable keys -/// and spend a fresh 4096-row quota with each, which is the hard bound bypassed. -const HISTORY_DEDUP_UNKNOWN_PRINCIPAL: &str = "unknown"; - -/// The requester a dedup key names, for the per-principal quota. -/// -/// The key is the RFC 8785 canonical serialization of `[op, effective_scope, principal_id, -/// idempotency_key]`, so the principal is the third element and a string. Anything else — an -/// unparsable key, a truncated array, a non-string member — is accounted to -/// [`HISTORY_DEDUP_UNKNOWN_PRINCIPAL`], so every such key shares one quota and none of them can -/// widen the bound. Connect canonicalizes before it calls, so a well-formed deployment never -/// reaches that bucket. -fn principal_of(key: &str) -> String { - serde_json::from_str::(key) - .ok() - .and_then(|value| { - value - .as_array() - .and_then(|members| members.get(2)) - .and_then(Value::as_str) - .map(str::to_owned) - }) - .unwrap_or_else(|| HISTORY_DEDUP_UNKNOWN_PRINCIPAL.to_owned()) -} - -/// One dedup record per retry identity, in the database file the knowledge store already serves -/// with, under the namespace of the collection this surface routes to. The pool holds a single -/// connection, so the claim, the port call and the record never hold two at once: each takes and -/// releases its own. -pub(crate) struct SqliteHistoryDedupStore { - pool: SqlitePool, - namespace: String, -} - -impl SqliteHistoryDedupStore { - /// `namespace` is the collection the routed store serves: it is stored beside the key in its - /// own column, so two surfaces on one database that route to different collections never share - /// a row, whatever characters either name contains. - pub(crate) fn new(pool: SqlitePool, namespace: impl Into) -> Self { - Self { - pool, - namespace: namespace.into(), - } - } -} - -#[async_trait] -impl HistoryDedupStore for SqliteHistoryDedupStore { - async fn lookup(&self, key: &str) -> HistoryDedupLookup { - let mut conn = match self.pool.acquire().await { - Ok(conn) => conn, - Err(error) => return fault("claim", error), - }; - let principal = principal_of(key); - // Claim and read on the same connection: the insert decides whether the row is this - // caller's, and the read shows what the row holds — `NULL`s for a claim still in flight. - // The insert is also the capacity gate: a principal already at the bound takes no new row, - // so an unseen key stays unseen here and the read below answers `Evicted`. An existing key - // is unaffected either way, so a replay still finds its recorded outcome at the bound. - let claimed = match sqlx::query( - "INSERT INTO history_dedup (namespace, key, principal) SELECT ?, ?, ? \ - WHERE (SELECT COUNT(*) FROM history_dedup \ - WHERE namespace = ? AND principal = ?) < ? \ - ON CONFLICT(namespace, key) DO NOTHING", - ) - .bind(&self.namespace) - .bind(key) - .bind(&principal) - .bind(&self.namespace) - .bind(&principal) - .bind(HISTORY_DEDUP_CAPACITY) - .execute(&mut *conn) - .await - { - Ok(result) => result.rows_affected() == 1, - Err(error) => return fault("claim", error), - }; - let stored: Result, Option)>, _> = sqlx::query_as( - "SELECT payload_digest, outcome_json FROM history_dedup \ - WHERE namespace = ? AND key = ?", - ) - .bind(&self.namespace) - .bind(key) - .fetch_optional(&mut *conn) - .await; - let row = match stored { - Ok(row) => row, - Err(error) => return fault("lookup", error), - }; - if claimed { - return HistoryDedupLookup::Unseen; - } - match row { - // Another caller's unanswered claim, one the process never settled, or an unseen key - // the namespace had no room to claim. - Some((None, None)) | None => HistoryDedupLookup::Evicted, - Some((Some(payload_digest), Some(outcome_json))) => match decode_outcome(&outcome_json) - { - Some(outcome) => HistoryDedupLookup::Recorded(HistoryDedupRecord { - payload_digest, - outcome, - }), - None => HistoryDedupLookup::Evicted, - }, - // The `CHECK` keeps the two columns in step; a row that breaks it is not an outcome - // this store wrote, so it never replays. - Some(_) => HistoryDedupLookup::Evicted, - } - } - - async fn record(&self, key: &str, record: HistoryDedupRecord) { - let outcome_json = encode_outcome(&record.outcome); - let principal = principal_of(key); - // Only fill a claim `lookup` already inserted: the `EXISTS` gate is the whole condition. - // A trait caller that records without a claim writes nothing, so it can neither insert an - // outcome for a key no prune ran under nor grow the table; claim capacity is `lookup`'s, - // which refuses an unseen key at the bound. The upsert still replaces an outcome the same - // key already recorded. - let written = sqlx::query( - "INSERT INTO history_dedup (namespace, key, principal, payload_digest, outcome_json) \ - SELECT ?, ?, ?, ?, ? \ - WHERE EXISTS (SELECT 1 FROM history_dedup WHERE namespace = ? AND key = ?) \ - ON CONFLICT(namespace, key) DO UPDATE SET \ - payload_digest = excluded.payload_digest, \ - outcome_json = excluded.outcome_json", - ) - .bind(&self.namespace) - .bind(key) - .bind(&principal) - .bind(&record.payload_digest) - .bind(&outcome_json) - .bind(&self.namespace) - .bind(key) - .execute(&self.pool) - .await; - if let Err(error) = written { - // The claim stays in place, so the key answers `RECEIPT_EXPIRED` rather than - // re-executing. The diagnostic names local columns and stays host-side. - let _ = writeln!( - std::io::stderr(), - "mindcore history dedup record fault: {error}" - ); - } - } -} - -/// A storage fault under `lookup`. The trait carries no error channel, so the fault is reported on -/// the host's stderr and answered as `Evicted`: a prune is never re-executed on a storage fault. -fn fault(stage: &str, diagnostic: impl std::fmt::Display) -> HistoryDedupLookup { - let _ = writeln!( - std::io::stderr(), - "mindcore history dedup {stage} fault: {diagnostic}" - ); - HistoryDedupLookup::Evicted -} - -/// `SpokeResult`, `SpokeReject` and `SpokeRejectCode` carry no serde implementation, so the stored -/// shape is written here: `{"ok": }` or -/// `{"reject": {"code", "message", "details"}}`, the code as its wire string. `details: None` -/// stores as `null`, so an empty `details` object never reads back as `None`. -fn encode_outcome(outcome: &SpokeResult) -> String { - let stored = match outcome { - SpokeResult::Ok(value) => json!({ "ok": value }), - SpokeResult::Reject(reject) => json!({ - "reject": { - "code": reject.code.as_str(), - "message": reject.message, - "details": reject.details, - } - }), - }; - stored.to_string() -} - -/// The inverse of [`encode_outcome`]. -/// -/// Strict: exactly one variant key, and a reject carries exactly `code`, `message` and `details`. -/// It rejects any value that does not match the shape this writer emits, so a half-written or -/// hand-edited row answers `Evicted` rather than replaying. This is a shape check, not authenticity -/// or tamper detection: nothing here authenticates the row, and a writer with database access can -/// store any well-formed outcome it likes. -fn decode_outcome(stored: &str) -> Option> { - let value: Value = serde_json::from_str(stored).ok()?; - let object = value.as_object()?; - if object.len() != 1 { - return None; - } - if let Some(ok) = object.get("ok") { - return Some(SpokeResult::Ok(ok.clone())); - } - let reject = object.get("reject")?.as_object()?; - if reject.len() != 3 { - return None; - } - let code = SpokeRejectCode::try_from_str(reject.get("code")?.as_str()?)?; - let message = reject.get("message")?.as_str()?.to_string(); - let details = match reject.get("details")? { - Value::Null => None, - Value::Object(map) => Some(map.clone()), - _ => return None, - }; - Some(SpokeResult::Reject(SpokeReject { - code, - message, - details, - })) -} - -#[cfg(test)] -mod tests { - use serde_json::{json, Map}; - use tempfile::TempDir; - - use mindcore_sqlite::MindStore; - - use super::*; - - fn record(payload_digest: &str, outcome: SpokeResult) -> HistoryDedupRecord { - HistoryDedupRecord { - payload_digest: payload_digest.to_string(), - outcome, - } - } - - fn recorded(lookup: HistoryDedupLookup, context: &str) -> HistoryDedupRecord { - match lookup { - HistoryDedupLookup::Recorded(record) => record, - other => panic!("{context}: expected a recorded outcome, got {other:?}"), - } - } - - /// A key in the shape Connect sends: the RFC 8785 serialization of the four-member retry - /// identity. The per-principal quota reads the third member. - fn key_for(principal: &str, idempotency_key: &str) -> String { - json!([ - "history.revisions.prune", - { "scope_id": "scope-one" }, - principal, - idempotency_key - ]) - .to_string() - } - - /// One fresh database file through the production open path, and the store bound to its pool. - async fn open(dir: &TempDir) -> (MindStore, SqliteHistoryDedupStore) { - open_in(dir, "collection-one").await - } - - /// As [`open`], with the namespace the history surface's collection supplies. - async fn open_in(dir: &TempDir, namespace: &str) -> (MindStore, SqliteHistoryDedupStore) { - let store = MindStore::open(&dir.path().join("history_dedup.db")) - .await - .expect("open the store"); - let dedup = SqliteHistoryDedupStore::new(store.pool(), namespace); - (store, dedup) - } - - async fn row_count(store: &MindStore, namespace: &str) -> i64 { - sqlx::query_scalar("SELECT COUNT(*) FROM history_dedup WHERE namespace = ?") - .bind(namespace) - .fetch_one(&store.pool()) - .await - .expect("count the namespace's rows") - } - - async fn principal_row_count(store: &MindStore, namespace: &str, principal: &str) -> i64 { - sqlx::query_scalar( - "SELECT COUNT(*) FROM history_dedup WHERE namespace = ? AND principal = ?", - ) - .bind(namespace) - .bind(principal) - .fetch_one(&store.pool()) - .await - .expect("count the principal's rows") - } - - #[tokio::test] - async fn a_first_lookup_answers_unseen() { - let dir = TempDir::new().expect("temporary directory"); - let (_store, dedup) = open(&dir).await; - assert_eq!(dedup.lookup("key-one").await, HistoryDedupLookup::Unseen); - } - - #[tokio::test] - async fn an_ok_outcome_round_trips() { - let dir = TempDir::new().expect("temporary directory"); - let (_store, dedup) = open(&dir).await; - let written = record( - "digest-ok", - SpokeResult::Ok(json!({ "deleted": 2, "floor_revision": 3 })), - ); - dedup.lookup("key-one").await; - dedup.record("key-one", written.clone()).await; - assert_eq!(recorded(dedup.lookup("key-one").await, "ok"), written); - } - - #[tokio::test] - async fn a_reject_with_details_round_trips() { - let dir = TempDir::new().expect("temporary directory"); - let (_store, dedup) = open(&dir).await; - let mut details = Map::new(); - details.insert("entity_kind".to_string(), json!("knowledge_entry")); - let written = record( - "digest-reject", - SpokeResult::Reject(SpokeReject { - code: SpokeRejectCode::HistoryTruncated, - message: "the range starts below the retained floor".to_string(), - details: Some(details), - }), - ); - dedup.lookup("key-one").await; - dedup.record("key-one", written.clone()).await; - assert_eq!(recorded(dedup.lookup("key-one").await, "reject"), written); - } - - #[tokio::test] - async fn a_reject_without_details_round_trips_as_none() { - let dir = TempDir::new().expect("temporary directory"); - let (_store, dedup) = open(&dir).await; - let written = record( - "digest-null-details", - SpokeResult::Reject(SpokeReject { - code: SpokeRejectCode::InvalidInput, - message: "keep must be at least one".to_string(), - details: None, - }), - ); - dedup.lookup("key-one").await; - dedup.record("key-one", written.clone()).await; - assert_eq!(recorded(dedup.lookup("key-one").await, "reject"), written); - } - - #[tokio::test] - async fn a_second_record_replaces_the_row() { - let dir = TempDir::new().expect("temporary directory"); - let (_store, dedup) = open(&dir).await; - dedup.lookup("key-one").await; - dedup - .record( - "key-one", - record("digest-first", SpokeResult::Ok(json!({ "deleted": 1 }))), - ) - .await; - let second = record( - "digest-second", - SpokeResult::Ok(json!({ "deleted": 5, "floor_revision": 6 })), - ); - dedup.record("key-one", second.clone()).await; - assert_eq!(recorded(dedup.lookup("key-one").await, "replace"), second); - } - - #[tokio::test] - async fn an_unsettled_claim_answers_evicted_after_the_file_is_reopened() { - let dir = TempDir::new().expect("temporary directory"); - { - let (_store, dedup) = open(&dir).await; - assert_eq!(dedup.lookup("key-one").await, HistoryDedupLookup::Unseen); - } - let (_store, dedup) = open(&dir).await; - assert_eq!(dedup.lookup("key-one").await, HistoryDedupLookup::Evicted); - } - - /// Overwrite a claimed key with a stored outcome this module never writes. - async fn install_outcome(store: &MindStore, stored: &str) { - sqlx::query( - "UPDATE history_dedup SET payload_digest = ?, outcome_json = ? \ - WHERE namespace = ? AND key = ?", - ) - .bind("digest-invalid") - .bind(stored) - .bind("collection-one") - .bind("key-one") - .execute(&store.pool()) - .await - .expect("install an invalid outcome"); - } - - #[tokio::test] - async fn an_outcome_that_does_not_decode_answers_evicted() { - let dir = TempDir::new().expect("temporary directory"); - let (store, dedup) = open(&dir).await; - dedup.lookup("key-one").await; - install_outcome(&store, "{\"reject\":{\"code\":\"NOT_A_REJECT_CODE\"}}").await; - assert_eq!(dedup.lookup("key-one").await, HistoryDedupLookup::Evicted); - } - - #[tokio::test] - async fn a_parseable_record_with_both_variants_answers_evicted() { - let dir = TempDir::new().expect("temporary directory"); - let (store, dedup) = open(&dir).await; - dedup.lookup("key-one").await; - // Both keys parse, so the record must not be replayed as either variant. - install_outcome( - &store, - "{\"ok\":{\"deleted\":1},\"reject\":{\"code\":\"NO_SUCH_CODE\"}}", - ) - .await; - assert_eq!(dedup.lookup("key-one").await, HistoryDedupLookup::Evicted); - } - - #[tokio::test] - async fn a_reject_with_unexpected_members_answers_evicted() { - let dir = TempDir::new().expect("temporary directory"); - let (store, dedup) = open(&dir).await; - dedup.lookup("key-one").await; - // A well-formed reject plus a member this module never writes. - install_outcome( - &store, - "{\"reject\":{\"code\":\"INVALID_INPUT\",\"message\":\"m\",\"details\":null,\ - \"extra\":1}}", - ) - .await; - assert_eq!(dedup.lookup("key-one").await, HistoryDedupLookup::Evicted); - } - - /// Two history surfaces on one database, sharing a wire scope, a principal and an idempotency - /// key, route to different collections. The second must not replay the first's prune. - #[tokio::test] - async fn the_same_key_in_another_namespace_does_not_replay() { - let dir = TempDir::new().expect("temporary directory"); - let store = MindStore::open(&dir.path().join("history_dedup.db")) - .await - .expect("open the store"); - let first = SqliteHistoryDedupStore::new(store.pool(), "wren"); - let second = SqliteHistoryDedupStore::new(store.pool(), "mora"); - let written = record("digest-wren", SpokeResult::Ok(json!({ "deleted": 1 }))); - first.lookup("key-one").await; - first.record("key-one", written.clone()).await; - - assert_eq!( - recorded(first.lookup("key-one").await, "same collection"), - written - ); - assert_eq!( - second.lookup("key-one").await, - HistoryDedupLookup::Unseen, - "another collection's key is unseen, so its own prune runs" - ); - assert_eq!(row_count(&store, "wren").await, 1); - assert_eq!(row_count(&store, "mora").await, 1); - - // The second surface's own outcome never reaches the first. - let other = record("digest-mora", SpokeResult::Ok(json!({ "deleted": 4 }))); - second.record("key-one", other.clone()).await; - assert_eq!( - recorded(first.lookup("key-one").await, "still wren"), - written - ); - assert_eq!(recorded(second.lookup("key-one").await, "mora"), other); - } - - /// A collection name is an arbitrary string, NUL included. Framing the namespace into the key - /// with a separator made `("a\0b", "c")` and `("a", "b\0c")` the same row, and put one - /// namespace's rows inside another's capacity range. Two columns keep both pairs apart. - #[tokio::test] - async fn a_nul_bearing_collection_keeps_its_rows_separate() { - let dir = TempDir::new().expect("temporary directory"); - let store = MindStore::open(&dir.path().join("history_dedup.db")) - .await - .expect("open the store"); - let nested = SqliteHistoryDedupStore::new(store.pool(), "a\u{0}b"); - let plain = SqliteHistoryDedupStore::new(store.pool(), "a"); - let nested_record = record("digest-nested", SpokeResult::Ok(json!({ "deleted": 1 }))); - let plain_record = record("digest-plain", SpokeResult::Ok(json!({ "deleted": 7 }))); - - // The pair that a `\0` separator collapsed onto one stored key. - assert_eq!( - nested.lookup("c").await, - HistoryDedupLookup::Unseen, - "the NUL-bearing collection's own key is fresh" - ); - nested.record("c", nested_record.clone()).await; - assert_eq!( - plain.lookup("b\u{0}c").await, - HistoryDedupLookup::Unseen, - "the other pair must not find the nested collection's row" - ); - plain.record("b\u{0}c", plain_record.clone()).await; - - // The pair that a prefix range swept into the neighbouring namespace's capacity count. - assert_eq!(plain.lookup("key-one").await, HistoryDedupLookup::Unseen); - plain.record("key-one", plain_record.clone()).await; - - assert_eq!(recorded(nested.lookup("c").await, "nested"), nested_record); - assert_eq!( - recorded(plain.lookup("b\u{0}c").await, "plain, own key"), - plain_record - ); - assert_eq!( - recorded(plain.lookup("key-one").await, "plain, second key"), - plain_record - ); - assert_eq!(row_count(&store, "a\u{0}b").await, 1); - assert_eq!(row_count(&store, "a").await, 2); - } - - /// A principal at its bound refuses an unseen key instead of inserting one more row, so a - /// stream of fresh keys — refusals for a missing target included — cannot exhaust storage. - #[tokio::test] - async fn an_unseen_key_at_capacity_answers_evicted_without_a_new_row() { - let dir = TempDir::new().expect("temporary directory"); - let (store, dedup) = open(&dir).await; - for index in 0..HISTORY_DEDUP_CAPACITY { - let key = key_for("prn_one", &format!("key-{index}")); - assert_eq!(dedup.lookup(&key).await, HistoryDedupLookup::Unseen); - dedup - .record( - &key, - record("digest", SpokeResult::Ok(json!({ "deleted": 0 }))), - ) - .await; - } - assert_eq!( - principal_row_count(&store, "collection-one", "prn_one").await, - HISTORY_DEDUP_CAPACITY - ); - - assert_eq!( - dedup.lookup(&key_for("prn_one", "key-overflow")).await, - HistoryDedupLookup::Evicted, - "the bound refuses a fresh key, so Connect answers RECEIPT_EXPIRED" - ); - assert_eq!( - principal_row_count(&store, "collection-one", "prn_one").await, - HISTORY_DEDUP_CAPACITY, - "the refused claim inserted no row" - ); - - // `record` writes nothing for a key no claim covers, at the bound or anywhere else. - dedup - .record( - &key_for("prn_one", "key-unclaimed"), - record("digest", SpokeResult::Ok(json!({ "deleted": 0 }))), - ) - .await; - assert_eq!( - principal_row_count(&store, "collection-one", "prn_one").await, - HISTORY_DEDUP_CAPACITY - ); - - // A recorded outcome inside the quota still replays at the bound. - assert_eq!( - recorded( - dedup.lookup(&key_for("prn_one", "key-0")).await, - "at the bound" - ), - record("digest", SpokeResult::Ok(json!({ "deleted": 0 }))) - ); - - // Another namespace has its own bound and keeps working. - let (_, elsewhere) = open_in(&dir, "collection-two").await; - assert_eq!( - elsewhere.lookup(&key_for("prn_one", "key-overflow")).await, - HistoryDedupLookup::Unseen - ); - } - - /// The quota is per caller, so one principal filling its bound cannot disable prune for another - /// on the same collection — the failure a shared namespace bound allowed. - #[tokio::test] - async fn a_full_principal_quota_leaves_another_principal_claiming() { - let dir = TempDir::new().expect("temporary directory"); - let (store, dedup) = open(&dir).await; - for index in 0..HISTORY_DEDUP_CAPACITY { - let key = key_for("prn_noisy", &format!("key-{index}")); - assert_eq!(dedup.lookup(&key).await, HistoryDedupLookup::Unseen); - dedup - .record( - &key, - record("digest", SpokeResult::Ok(json!({ "deleted": 0 }))), - ) - .await; - } - assert_eq!( - dedup.lookup(&key_for("prn_noisy", "key-overflow")).await, - HistoryDedupLookup::Evicted, - "the high-churn caller exhausted its own quota" - ); - - let quiet = key_for("prn_quiet", "key-one"); - assert_eq!( - dedup.lookup(&quiet).await, - HistoryDedupLookup::Unseen, - "the quiet principal's quota is untouched" - ); - let written = record("digest-quiet", SpokeResult::Ok(json!({ "deleted": 3 }))); - dedup.record(&quiet, written.clone()).await; - assert_eq!(recorded(dedup.lookup(&quiet).await, "quiet"), written); - - assert_eq!( - principal_row_count(&store, "collection-one", "prn_noisy").await, - HISTORY_DEDUP_CAPACITY - ); - assert_eq!( - principal_row_count(&store, "collection-one", "prn_quiet").await, - 1 - ); - } - - /// The dedup record carries no clock, so a forward host-clock jump cannot make a live record - /// expire and let a same-key retry execute the destructive prune again. - #[tokio::test] - async fn the_record_carries_no_clock_column() { - let dir = TempDir::new().expect("temporary directory"); - let (store, dedup) = open(&dir).await; - let key = key_for("prn_one", "key-one"); - dedup.lookup(&key).await; - let written = record("digest", SpokeResult::Ok(json!({ "deleted": 2 }))); - dedup.record(&key, written.clone()).await; - - let columns: Vec = - sqlx::query_scalar("SELECT name FROM pragma_table_info('history_dedup') ORDER BY cid") - .fetch_all(&store.pool()) - .await - .expect("read the table's columns"); - assert_eq!( - columns, - vec![ - "namespace", - "key", - "principal", - "payload_digest", - "outcome_json" - ], - "no timestamp column exists for a clock jump to age out" - ); - - // Nothing deletes: the record still replays after the file is reopened. - assert_eq!(recorded(dedup.lookup(&key).await, "before reopen"), written); - drop(dedup); - let (_store, reopened) = open(&dir).await; - assert_eq!( - recorded(reopened.lookup(&key).await, "after reopen"), - written - ); - } - - /// Unparsable keys share one bucket, so a caller cannot mint a fresh quota per odd key. - #[tokio::test] - async fn keys_that_do_not_parse_share_one_principal_bucket() { - let dir = TempDir::new().expect("temporary directory"); - let (store, dedup) = open(&dir).await; - for key in ["not-a-canonical-key", "[1,2]", "{\"not\":\"an array\"}"] { - assert_eq!(dedup.lookup(key).await, HistoryDedupLookup::Unseen); - let written = record("digest", SpokeResult::Ok(json!({ "deleted": 1 }))); - dedup.record(key, written.clone()).await; - assert_eq!(recorded(dedup.lookup(key).await, key), written); - } - assert_eq!( - principal_row_count(&store, "collection-one", HISTORY_DEDUP_UNKNOWN_PRINCIPAL).await, - 3, - "every unparsable key is accounted to the one shareable bucket" - ); - } - - /// A non-string third member is not a principal either, so it lands in the same bucket. - #[tokio::test] - async fn a_non_string_principal_member_uses_the_unknown_bucket() { - let dir = TempDir::new().expect("temporary directory"); - let (store, dedup) = open(&dir).await; - let key = json!(["history.revisions.prune", { "scope_id": "s" }, 7, "k"]).to_string(); - assert_eq!(dedup.lookup(&key).await, HistoryDedupLookup::Unseen); - dedup - .record( - &key, - record("digest", SpokeResult::Ok(json!({ "deleted": 1 }))), - ) - .await; - assert_eq!( - principal_row_count(&store, "collection-one", HISTORY_DEDUP_UNKNOWN_PRINCIPAL).await, - 1 - ); - } - - /// `record` only fills a claim. A caller that records without a preceding `lookup` writes - /// nothing, so no outcome can exist for a key whose prune never ran — and a later `lookup` - /// cannot replay one. - #[tokio::test] - async fn record_without_a_claim_writes_nothing() { - let dir = TempDir::new().expect("temporary directory"); - let (store, dedup) = open(&dir).await; - let key = key_for("prn_one", "key-one"); - dedup - .record( - &key, - record("digest", SpokeResult::Ok(json!({ "deleted": 4 }))), - ) - .await; - assert_eq!( - row_count(&store, "collection-one").await, - 0, - "an unclaimed record inserted no row" - ); - assert_eq!( - dedup.lookup(&key).await, - HistoryDedupLookup::Unseen, - "the key is still fresh, so its prune runs rather than replaying" - ); - } - - /// The bound counts one `(namespace, principal)` pair exactly. Under the old prefix range a - /// collection whose name extended another's — `"a\0b"` beside `"a"` — had its rows swept into - /// the shorter name's count, so a full neighbour could refuse a namespace that held nothing. - #[tokio::test] - async fn the_capacity_count_holds_only_the_named_namespace() { - let dir = TempDir::new().expect("temporary directory"); - let store = MindStore::open(&dir.path().join("history_dedup.db")) - .await - .expect("open the store"); - let nested = SqliteHistoryDedupStore::new(store.pool(), "a\u{0}b"); - - // Fill one principal's quota in the NUL-bearing namespace, and nothing else. - for index in 0..HISTORY_DEDUP_CAPACITY { - let key = key_for("prn_one", &format!("key-{index}")); - assert_eq!(nested.lookup(&key).await, HistoryDedupLookup::Unseen); - nested - .record( - &key, - record("digest", SpokeResult::Ok(json!({ "deleted": 0 }))), - ) - .await; - } - assert_eq!( - principal_row_count(&store, "a\u{0}b", "prn_one").await, - HISTORY_DEDUP_CAPACITY, - "the nested namespace's quota is full" - ); - assert_eq!(row_count(&store, "a").await, 0); - - // The shorter name is empty, so the same principal's quota there is untouched. - let plain = SqliteHistoryDedupStore::new(store.pool(), "a"); - assert_eq!( - plain.lookup(&key_for("prn_one", "key-fresh")).await, - HistoryDedupLookup::Unseen, - "the full neighbour's rows are not this namespace's" - ); - assert_eq!(row_count(&store, "a").await, 1); - assert_eq!( - principal_row_count(&store, "a\u{0}b", "prn_one").await, - HISTORY_DEDUP_CAPACITY, - "the neighbour's claim left the full namespace alone" - ); - } -} diff --git a/crates/mindcore-runtime/src/lib.rs b/crates/mindcore-runtime/src/lib.rs index 493bf857..43c9a386 100644 --- a/crates/mindcore-runtime/src/lib.rs +++ b/crates/mindcore-runtime/src/lib.rs @@ -1,8 +1,8 @@ -//! The Mindcore serving surface: the workflow engine, the SQLite knowledge face and the host's -//! memory face assembled into the pieces a Connect responder is built from. +//! The Mindcore serving surface: the workflow engine and the host's memory face assembled into the +//! pieces a Connect responder is built from. //! //! The crate opens nothing: no listener, accept loop, identity or transport. The host supplies -//! those plus its admissions, publisher and memory service, then builds +//! those plus its admission, publisher and memory service, then builds //! `ConnectResponderOptions` from [`MindcoreSurface`]. Advertisements follow what is served: //! [`MindcoreServe::surface`] derives `capabilities` and `tools` from the composed faces and the //! registrations, never from a host-supplied capability string. @@ -11,8 +11,6 @@ //! `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 journal; pub mod mind; pub mod minds; @@ -22,31 +20,20 @@ use std::sync::Arc; use serde_json::Value; -use mindcore_base::knowledge::KnowledgeScope; use mindcore_spi::{EmbeddingIdentity, MindWorkflows, SpiError, SpiMindWorkflows}; use mindcore_spoke::{MemoryWorkflowBinding, ServedMemory, TRANSFER_OPERATIONS}; -use mindcore_sqlite::{validate_admission_scope, vectors, MindStore, RoutedKnowledgeStore}; +use mindcore_sqlite::{vectors, MindStore}; use spoke_connect::core::{ - CAPABILITY_KE_OWNERSHIP, CAPABILITY_SPOKE_HISTORY, CAPABILITY_SPOKE_JUDGMENT, - CAPABILITY_SPOKE_KNOWLEDGE, CAPABILITY_SPOKE_KNOWLEDGE_ADOPTION, CAPABILITY_SPOKE_MEMORY, - CAPABILITY_SPOKE_MEMORY_TRANSFER, + CAPABILITY_SPOKE_JUDGMENT, CAPABILITY_SPOKE_MEMORY, CAPABILITY_SPOKE_MEMORY_TRANSFER, }; use spoke_connect::remote::{ - AdoptionAdmission, AdoptionPortService, ConnectResponder, HistoryAdmission, HistoryPortService, - KnowledgeAdmission, MemoryAdmission, RemoteAdoptionService, RemoteHistoryService, - RemoteKnowledgeFace, RemoteMemoryService, RemoteServePorts, RemoteServePortsComposite, - ToolHandler, -}; -use spoke_operations::{ - spoke_reject, validate_manifest_tools, AdoptionPort, HistoryPort, ScopedKnowledgePort, - SpokeRejectCode, SpokeResult, + ConnectResponder, MemoryAdmission, RemoteMemoryService, RemoteServePorts, ToolHandler, }; +use spoke_operations::{validate_manifest_tools, SpokeResult}; use spoke_schemas::host_capability_manifest::ToolDescriptor; -use spoke_schemas::{HostCapabilityManifest, Scope}; +use spoke_schemas::HostCapabilityManifest; use sqlx::SqlitePool; -use adoption::AdoptionService; -use history_dedup::SqliteHistoryDedupStore; pub use journal::journal_dir; pub use mind::{Capture, Deliberation, Mind, Recall}; pub use mindcore_spoke::Cognition; @@ -58,14 +45,14 @@ const TOOLS_NAMESPACE: &str = "mindcore"; /// The id of the retired product adoption tool. /// -/// `knowledge.adopt` replaces it: the id is dropped from every host registration, so no host can -/// advertise or install anything under it. +/// The id is dropped from every host registration, so no host can advertise or install anything +/// under it. const RETIRED_ADOPT_TOOL: &str = "tools.mindcore.adopt"; /// The Mindcore serving side over one host store. /// -/// The workflow engine runs on the same pool the knowledge face serves, so a tool call and a -/// knowledge op see one snapshot boundary. The engine never opens a transaction across provider +/// The workflow engine runs on the same pool the host's store serves, so a tool call and a +/// registry read see one snapshot boundary. The engine never opens a transaction across provider /// work; each workflow keeps its own `SpiError` classification. pub struct MindcoreServe { store: MindStore, @@ -110,38 +97,6 @@ impl MindcoreServe { /// [`MindcoreSurface::register`]: `connect_responder` starts its own receive task and never /// installs handlers from the manifest. pub fn surface(&self, faces: ServeFaces) -> SpokeResult { - let adoption = faces.adoption; - if let Some(adoption) = &adoption { - let source = &adoption.source.collection; - if adoption.scope_id.is_empty() { - return spoke_reject( - SpokeRejectCode::InvalidInput, - "the adoption source names an empty scope id", - None, - ); - } - if source.is_empty() { - return spoke_reject( - SpokeRejectCode::InvalidInput, - "the adoption source names an empty collection", - None, - ); - } - if adoption.scope_id == faces.scope_id { - return spoke_reject( - SpokeRejectCode::InvalidInput, - "the adoption source scope is the destination scope", - None, - ); - } - if source == &faces.knowledge.collection { - return spoke_reject( - SpokeRejectCode::InvalidInput, - "the adoption source collection is the collection the knowledge face serves", - None, - ); - } - } let principals = faces.principals; let workflows = self.workflows(); let engine: Arc = workflows.clone(); @@ -158,81 +113,14 @@ impl MindcoreServe { .into_iter() .filter(|tool| tool.descriptor.capability_id.as_str() != RETIRED_ADOPT_TOOL), ); - let manifest = derive_manifest( - faces.manifest, - faces.memory.as_deref(), - faces.history, - adoption.is_some(), - &tools, - ); - let manifest = match manifest { + let manifest = match derive_manifest(faces.manifest, faces.memory.as_deref(), &tools) { SpokeResult::Ok(manifest) => manifest, SpokeResult::Reject(reject) => return SpokeResult::Reject(reject), }; - let admission = validated(faces.admission, &faces.scope_id); - let served: KnowledgeScope = faces.knowledge; - let store: Arc = - Arc::new(self.store.served_knowledge(faces.scope_id, served.clone())); - let knowledge: Arc = store.clone(); - let face = RemoteKnowledgeFace { - store: knowledge, - admission: Arc::clone(&admission), - }; - let mut ports = RemoteServePortsComposite::knowledge_only(Arc::new(face)); - if let Some(adoption) = adoption { - // Adoption reuses the knowledge face's admission and its one served collection, so a - // peer that does not serve knowledge cannot adopt, and every adopted copy is readable - // through the knowledge face that shares this admission. - let adoption_admission: AdoptionAdmission = { - let principals = Arc::clone(&principals); - let admission = Arc::clone(&admission); - Arc::new(move |peer_id: &str| { - let principal = match principals(peer_id) { - SpokeResult::Ok(principal) => principal, - SpokeResult::Reject(reject) => return SpokeResult::Reject(reject), - }; - match admission(peer_id) { - SpokeResult::Ok(scope) => SpokeResult::Ok((principal, scope)), - SpokeResult::Reject(reject) => SpokeResult::Reject(reject), - } - }) - }; - let port: Arc = - Arc::new(AdoptionService::new(self.store.pool(), served, adoption)); - let service: Arc = - Arc::new(AdoptionPortService::new(port, adoption_admission)); - ports = ports.with_adoption(service); - } - if faces.history { - // History serves the knowledge face's own route and admission: one store, two port - // roles, so a peer replays exactly the scope it reads and writes. - let history_admission: HistoryAdmission = Arc::new(move |peer_id: &str| { - let principal = match principals(peer_id) { - SpokeResult::Ok(principal) => principal, - SpokeResult::Reject(reject) => return SpokeResult::Reject(reject), - }; - match admission(peer_id) { - SpokeResult::Ok(scope) => SpokeResult::Ok((principal, scope)), - SpokeResult::Reject(reject) => SpokeResult::Reject(reject), - } - }); - let port: Arc = store.clone(); - // The dedup record lives in the same file behind the same pool: a prune's outcome, - // and the claim that keeps a retry out of the port, outlive this surface. Its rows are - // namespaced by the collection this surface routes to, so another surface on the same - // database that routes elsewhere cannot replay or refuse this one's prunes. - let dedup = SqliteHistoryDedupStore::new(self.store.pool(), store.collection()); - let service: Arc = Arc::new( - HistoryPortService::new(port, history_admission).with_dedup_store(Arc::new(dedup)), - ); - ports = ports.with_history(service); - } - if let Some(memory) = faces.memory { - let service: Arc = memory; - ports = ports.with_memory(service); - } SpokeResult::Ok(MindcoreSurface { - ports: Arc::new(ports), + ports: Arc::new(MindPorts { + memory: faces.memory, + }), manifest, tools, workflows, @@ -241,19 +129,24 @@ impl MindcoreServe { } } -/// The shared collection adoption reads from: one source for the whole surface. The destination is -/// the one collection the knowledge face serves, shared by every peer admitted to that scope: it -/// holds one slot per `destination_entry_id`, the first adoption of a given id claims it, a repeat is -/// served that stored copy as `already_present` only at the anchor revision the copy records, and -/// every peer the host admits to the scope reads it through the knowledge face when its own admitted -/// selection admits it. Assembly refuses a source that names a route destination or the -/// knowledge face's own collection, and a source scope equal to the destination scope, so a -/// principal's write can never become the source another reads. -pub struct AdoptionRoute { - /// The host-owned id naming this source on the wire, recorded in every adopted copy's anchor - /// triple. Callers cannot supply it: this baseline forwards only the configured value. - pub scope_id: String, - pub source: KnowledgeScope, +/// The runtime's own ports: the one face this surface carries is the host's memory service. +/// +/// The other families stay absent — the responder answers their ops on its dispatch-deny branch +/// as `CAPABILITY_PORT_MISSING` — because none of them can name a Mind yet; each is composed per +/// Mind once SPOKE carries that contract. +struct MindPorts { + memory: Option>, +} + +/// The responder takes the family's bare service; `ServedMemory` only adds the operation report. +fn remote_memory(memory: Arc) -> Arc { + memory +} + +impl RemoteServePorts for MindPorts { + fn as_memory(&self) -> Option> { + self.memory.clone().map(remote_memory) + } } /// The host's side of the surface: non-capability manifest metadata and the face wiring the @@ -262,12 +155,6 @@ pub struct ServeFaces { /// The responder's hello metadata. `capabilities` and `tools` are replaced with what the /// runtime actually serves; every other member stays the host's. pub manifest: HostCapabilityManifest, - /// The one configured route: an admitted `scope_id` reads and writes `knowledge`'s collection. - pub scope_id: String, - /// The collection that route serves. - pub knowledge: KnowledgeScope, - /// Maps the authenticated peer to the one scope it may read and write; never read from the wire. - pub admission: KnowledgeAdmission, /// The host's memory family service. `None` composes no memory face and advertises none. /// /// Installing the service proves the `spoke-memory` family. It earns @@ -276,26 +163,11 @@ pub struct ServeFaces { /// cannot show it dispatches. A bare `RemoteMemoryService` takes the trait's default and /// reports none. pub memory: Option>, - /// Serve the `spoke-history` face over the same routed store and knowledge admission as the - /// knowledge face; `false` composes no history service and advertises none. A peer replays and - /// prunes exactly the scope it reads and writes through `port.knowledge.*`. - pub history: bool, /// Maps the authenticated peer to the `Principal` the workflows admit. The same host mapping /// the memory face uses; never read from the wire. pub principals: MemoryAdmission, /// Providers and the domain lens injected into each workflow call. pub providers: MindProviders, - /// The one host-configured adoption source, or `None` to serve no adoption. Its collection must - /// be non-empty and must not be [`ServeFaces::knowledge`]'s collection, and its scope id must - /// differ from [`ServeFaces::scope_id`]; assembly refuses otherwise. The source need not hold - /// rows. When it is configured, the `spoke-knowledge-adoption` face serves `knowledge.adopt` - /// over the knowledge face's admission, and writes into [`ServeFaces::knowledge`]'s - /// collection — one shared collection with one slot per `destination_entry_id`: the first - /// adoption of a given id claims it, a repeat is answered `already_present` with the stored - /// copy only at the anchor revision the copy records (another revision is a conflict), and a - /// peer whose own admitted selection hides the copy is answered the occupancy refusal instead - /// of the copy. - pub adoption: Option, /// Additional host tools: every descriptor is advertised and its handler installed, except /// the retired `tools.mindcore.adopt` on every surface. pub tools: Vec, @@ -330,8 +202,8 @@ impl ToolRegistration { /// The assembled surface: what `ConnectResponderOptions` takes, and the handler installation that /// must run before inbound hello traffic reaches the responder. pub struct MindcoreSurface { - /// Serve these ports: the knowledge face over the shared store, plus the history, adoption and - /// memory faces the host attached. No baseline provider is composed. + /// Serve these ports: the host's memory face when it attached one, and genuine absence for + /// every other family. No baseline provider is composed. pub ports: Arc, /// Advertise this manifest: it lists exactly the capabilities `ports` and the registrations /// serve. @@ -388,31 +260,11 @@ impl MindcoreSurface { } } -/// The advertised capabilities follow the composed faces: the knowledge face always, the memory -/// family flag when a memory service is attached, the transfer family flag when that service -/// reports every one of [`TRANSFER_OPERATIONS`], and the history and adoption flags only when -/// their faces are served. -/// -/// The knowledge face applies SPOKE's owner-private disclosure, so a viewpoint-scoped list is -/// served and the supplemental ownership capability is truthful; it never stands in for peer or -/// entry admission. -fn face_capabilities( - memory: Option<&dyn ServedMemory>, - history: bool, - adoption: bool, -) -> Vec { - let mut capabilities = vec![ - CAPABILITY_SPOKE_KNOWLEDGE.to_string(), - CAPABILITY_KE_OWNERSHIP.to_string(), - ]; - if history { - capabilities.push(CAPABILITY_SPOKE_HISTORY.to_string()); - } - if adoption { - // The co-capability `spoke-knowledge` is unconditional above, so the compound gate - // Connect applies to `knowledge.adopt` always holds. - capabilities.push(CAPABILITY_SPOKE_KNOWLEDGE_ADOPTION.to_string()); - } +/// The advertised capabilities follow the composed faces: the memory family flag when a memory +/// service is attached and the transfer family flag when that service reports every one of +/// [`TRANSFER_OPERATIONS`]. No other family is composed, so none is advertised. +fn face_capabilities(memory: Option<&dyn ServedMemory>) -> Vec { + let mut capabilities = Vec::new(); if let Some(memory) = memory { capabilities.push(CAPABILITY_SPOKE_MEMORY.to_string()); let reported = memory.operations(); @@ -431,11 +283,9 @@ fn face_capabilities( fn derive_manifest( mut manifest: HostCapabilityManifest, memory: Option<&dyn ServedMemory>, - history: bool, - adoption: bool, tools: &[ToolRegistration], ) -> SpokeResult { - manifest.capabilities = face_capabilities(memory, history, adoption); + manifest.capabilities = face_capabilities(memory); if tools .iter() .any(|tool| tool.descriptor.capability_id.as_str() == tools::DELIBERATE) @@ -469,40 +319,3 @@ fn derive_manifest( SpokeResult::Reject(reject) => SpokeResult::Reject(reject), } } - -/// The admitted scope is validated where the face is assembled: Connect's list merge keeps only -/// the request's cognition selection, so a selection the face does not serve must be refused -/// before the merge can drop it. -/// -/// The admitted id must also be the one this surface serves: the routed store refuses any other -/// id, so a resolver returning a different one would otherwise be admitted here and denied there. -/// Both faces share this admission, so one check covers them. -/// -/// Host admission is not peer input, so an unsupported admitted selection is refused as the same -/// generic `NotAuthorized` a rejecting resolver returns, never as the caller-declared -/// `InvalidInput` the routed store keeps for request scopes: the peer learns nothing about what -/// the face does not serve. The resolver's own refusal passes through unchanged. -fn validated(admission: KnowledgeAdmission, scope_id: &str) -> KnowledgeAdmission { - let scope_id = scope_id.to_string(); - Arc::new(move |peer_id: &str| -> SpokeResult { - let scope = match admission(peer_id) { - SpokeResult::Ok(scope) => scope, - SpokeResult::Reject(reject) => return SpokeResult::Reject(reject), - }; - if scope.scope_id != scope_id { - return spoke_reject( - SpokeRejectCode::NotAuthorized, - "knowledge scope not authorized", - None, - ); - } - match validate_admission_scope(&scope) { - SpokeResult::Ok(()) => SpokeResult::Ok(scope), - SpokeResult::Reject(_) => spoke_reject( - SpokeRejectCode::NotAuthorized, - "knowledge scope not authorized", - None, - ), - } - }) -} diff --git a/crates/mindcore-runtime/tests/loopback.rs b/crates/mindcore-runtime/tests/loopback.rs index 2a5384ab..4400bf9c 100644 --- a/crates/mindcore-runtime/tests/loopback.rs +++ b/crates/mindcore-runtime/tests/loopback.rs @@ -9,10 +9,10 @@ //! installs the protocol schema, and the fixture seeds only rows into it. //! //! Advertisement honesty is the negative side: a face the host did not attach advertises nothing -//! and denies its ops on the wire, and a tool the runtime does not serve answers `op_unsupported`. +//! and denies its ops on the wire, a family the runtime composes no face for answers +//! `CAPABILITY_PORT_MISSING`, and a tool the runtime does not serve answers `op_unsupported`. -use std::collections::{BTreeMap, HashMap}; -use std::str::FromStr; +use std::collections::HashMap; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex}; @@ -23,33 +23,29 @@ use tempfile::TempDir; use mindcore_base::ids::SpaceId; use mindcore_base::ir::MemorySpaceRow; -use mindcore_base::knowledge::{adoption_anchor_parts, KnowledgeScope}; use mindcore_runtime::tools::{ABSORB, DELIBERATE, READ_COGNITION, RECALL_CONTEXT}; use mindcore_runtime::{ - AdoptionRoute, MindProviders, MindcoreServe, MindcoreSurface, ServeFaces, ToolRegistration, + MindProviders, MindcoreServe, MindcoreSurface, ServeFaces, ToolRegistration, }; use mindcore_spi::{ CognitiveTaskKind, Embedder, EmbeddingIdentity, PolicyDecision, PolicyHook, Reasoner, SettlementDraft, SpiError, StructuredReasonRequest, }; use mindcore_spoke::{ServedMemory, TransferService}; -use mindcore_sqlite::{MindStore, ScopedKnowledgeStore, SqliteMemoryRepository}; +use mindcore_sqlite::{MindStore, SqliteMemoryRepository}; use spoke_connect::core::derive_peer_id_from_ed25519_pubkey; use spoke_connect::remote::{ connect_remote_adapter, connect_responder, loopback_transport_pair, ConnectResponder, - ConnectResponderOptions, KnowledgeAdmission, MemoryAdmission, RemoteAdapter, - RemoteAdapterOptions, RemoteAdapterState, RemoteIdentity, RemoteMemoryService, ToolHandler, + ConnectResponderOptions, MemoryAdmission, RemoteAdapter, RemoteAdapterOptions, + RemoteAdapterState, RemoteIdentity, RemoteMemoryService, ToolHandler, }; use spoke_operations::{ - revision_snapshots_equal_canonical, spoke_ok, spoke_reject, validate_judgment, AdoptionPort, - HistoryPort, KnowledgeEntryPort, MemoryPort, ScopeQueryPort, SpokeReject, SpokeRejectCode, - SpokeResult, + spoke_ok, spoke_reject, validate_judgment, AdoptionPort, HistoryPort, KnowledgeEntryPort, + MemoryPort, ScopeQueryPort, SpokeReject, SpokeRejectCode, SpokeResult, }; use spoke_schemas::host_capability_manifest::ToolDescriptor; -use spoke_schemas::knowledge_entry::{KnowledgeEntryDisclosure, KnowledgeEntryOwner}; use spoke_schemas::{ - HostCapabilityManifest, KnowledgeAdoptRequest, KnowledgeEntry, MemoryRecallRequest, Principal, - Scope, + HostCapabilityManifest, KnowledgeAdoptRequest, MemoryRecallRequest, Principal, Scope, }; const SCOPE_ID: &str = "spoke-scope-001"; @@ -73,33 +69,6 @@ const NOW: &str = "2026-11-21T00:00:00.500Z"; const UNSERVED_TOOL: &str = "tools.mindcore.unserved"; /// A host-owned tool the runtime serves beside its own three. const HOST_TOOL: &str = "tools.mindcore.host_tool"; -/// The host-configured collection adoption reads from, never one of this fixture's routes. -const SHARED: &str = "shared"; -/// The id naming the adoption source (`SHARED`) on the wire. -const SHARED_SCOPE: &str = "spc_shared"; -/// The capability the adoption face advertises and `knowledge.adopt` requires. -const ADOPTION: &str = "spoke-knowledge-adoption"; -/// A scope id the adoption face never serves as its source or its destination. -const OTHER_SCOPE: &str = "spc_other"; -const SHARED_ENTRY: &str = "ke_shared"; -/// A source retired into [`TERMINAL_ENTRY`], the live entry an adoption anchors instead. -const RETIRED_ENTRY: &str = "ke_retired"; -const TERMINAL_ENTRY: &str = "ke_terminal"; -/// An owner-private source: no viewpoint-free read reaches it, adoption included. -const PRIVATE_ENTRY: &str = "ke_private"; -/// A source retired into [`HUGE_TERMINAL`], whose stored revision is above the served ceiling. -const HUGE_RETIRED: &str = "ke_huge_retired"; -/// The live terminal of [`HUGE_RETIRED`]: revision `2^53 + 2` in its column and its payload. -const HUGE_TERMINAL: &str = "ke_huge_terminal"; -/// A revision SQLite accepts and the served adoption success cannot carry. -const HUGE_REVISION: u64 = (1 << 53) + 2; -/// A stored two-node cycle, seeded with direct markers because the store never writes one. -const CYCLE_A: &str = "ke_cycle_a"; -const CYCLE_B: &str = "ke_cycle_b"; -/// A destination slot holding a row retired into [`SLOT_SUCCESSOR`]: taken, yet hidden from the -/// live-only read an adoption's destination half makes. -const RETIRED_SLOT: &str = "ke_retired_slot"; -const SLOT_SUCCESSOR: &str = "ke_slot_successor"; const DIALER_SEED: [u8; 32] = [0x42u8; 32]; const RESPONDER_SEED: [u8; 32] = [0xA7u8; 32]; @@ -328,11 +297,6 @@ impl Fixture { .expect("drop the grant"); } - /// The database file this fixture opened, for a test that reopens it after a restart. - fn db_path(&self) -> std::path::PathBuf { - self.dir.path().join(DB_FILE) - } - /// The store and its directory part company: the engine takes the store, the caller keeps the /// directory alive for the session's lifetime. fn serve(self) -> (TempDir, MindcoreServe) { @@ -453,40 +417,6 @@ fn two_principal_admission() -> MemoryAdmission { /// Both host admissions admit the dialer's authenticated peer id and nothing else, so a served /// call proves the responder took the peer from its session rather than from the arguments. -fn knowledge_admission() -> KnowledgeAdmission { - let peer_id = dialer_peer_id(); - Arc::new(move |peered: &str| match peered == peer_id { - true => SpokeResult::Ok(scope_of(SCOPE_ID)), - false => refuse_knowledge(peered), - }) -} - -fn refuse_knowledge(peer_id: &str) -> SpokeResult { - spoke_reject( - SpokeRejectCode::NotAuthorized, - format!("peer {peer_id} holds no knowledge admission"), - None, - ) -} - -/// The same admission with one entry or entry-type restriction on the admitted scope: the id is the -/// one this surface serves, so only the selection can refuse the caller's destination. -fn restricted_knowledge_admission(restriction: Value) -> KnowledgeAdmission { - let peer_id = dialer_peer_id(); - Arc::new(move |peered: &str| match peered == peer_id { - true => { - let mut scope = json!({ "scope_id": SCOPE_ID }); - for (member, value) in restriction.as_object().expect("an object restriction") { - scope[member.as_str()] = value.clone(); - } - spoke_ok( - serde_json::from_value(scope).expect("the admitted scope JSON matches the schema"), - ) - } - false => refuse_knowledge(peered), - }) -} - fn principal_admission() -> MemoryAdmission { let peer_id = dialer_peer_id(); Arc::new(move |peered: &str| match peered == peer_id { @@ -654,14 +584,9 @@ fn faces( ) -> ServeFaces { ServeFaces { manifest, - scope_id: SCOPE_ID.to_string(), - knowledge: KnowledgeScope::new(COLLECTION), - admission: knowledge_admission(), memory, - history: false, principals: principal_admission(), providers, - adoption: None, tools: Vec::new(), } } @@ -965,15 +890,13 @@ async fn remote_consumer_recalls_context_through_the_composed_surface() { assert_eq!( capabilities(&surface), [ - "spoke-knowledge", - "ke-ownership", "spoke-judgment", RECALL_CONTEXT, ABSORB, DELIBERATE, READ_COGNITION ], - "the manifest advertises the knowledge face and every workflow tool" + "the manifest advertises the judgment family and every workflow tool" ); assert_eq!( surface @@ -986,7 +909,7 @@ async fn remote_consumer_recalls_context_through_the_composed_surface() { "the registry row routes every Mind, so the deliberation tool is always installed" ); - let session = connect(&surface, &["spoke-knowledge", RECALL_CONTEXT]).await; + let session = connect(&surface, &[RECALL_CONTEXT]).await; let result = expect_ok( session .adapter @@ -2379,900 +2302,138 @@ async fn an_unserved_tool_answers_op_unsupported() { ); } -/// One shared-source entry the adoption copies: a note whose summary names what the source holds. - -fn shared_entry(entry_id: &str, summary: &str) -> KnowledgeEntry { - serde_json::from_value(json!({ - "schema_version": 1, - "entry_id": entry_id, - "entry_type": "note", - "canonical_name": format!("{entry_id}'s source"), - "status": "confirmed", - "body": { "summary": summary }, - "extensions": {}, - })) - .expect("entry JSON matches the schema") -} - -/// One adoption request over the configured source and the admitted destination scope. -fn adopt_request(source_entry_id: &str, source_revision: u64, key: &str) -> KnowledgeAdoptRequest { - serde_json::from_value(json!({ - "source_scope_id": SHARED_SCOPE, - "source_entry_id": source_entry_id, - "source_revision": source_revision, - "destination_scope_id": SCOPE_ID, - "idempotency_key": key, - })) - .expect("request JSON matches the schema") -} - -/// The fixture's faces with the one shared adoption source attached. -fn adopting_faces() -> ServeFaces { - ServeFaces { - adoption: Some(AdoptionRoute { - scope_id: SHARED_SCOPE.to_string(), - source: KnowledgeScope::new(SHARED), - }), - ..faces( - hello("runtime", &[]), - None, - MindProviders::default(), - ) - } -} - -/// The shared source the adoption face reads: a live note, a note retired into a live terminal, -/// and an owner-private note no viewpoint-free read reaches. -async fn seed_shared_source(pool: &sqlx::SqlitePool) { - let shared = ScopedKnowledgeStore::new(pool.clone(), KnowledgeScope::new(SHARED)); - for (entry_id, summary) in [ - (SHARED_ENTRY, "the north gate closes at dusk"), - (RETIRED_ENTRY, "the gatekeeper's first note"), - (TERMINAL_ENTRY, "the keeper walks the north gate"), - ] { - expect_ok( - shared - .put_knowledge_entry(shared_entry(entry_id, summary), None) - .await, - "seed the shared source", - ); - } - expect_ok( - shared - .supersede_entry(RETIRED_ENTRY, 1, TERMINAL_ENTRY) - .await, - "retire the paired source into its terminal", - ); - // One terminal whose stored revision sits above the served ceiling. SQLite accepts it, so only - // the runtime's pre-write domain check keeps it out of a response. - expect_ok( - shared - .put_knowledge_entry(shared_entry(HUGE_TERMINAL, "the keeper's last note"), None) - .await, - "seed the out-of-domain terminal", - ); - expect_ok( - shared - .put_knowledge_entry(shared_entry(HUGE_RETIRED, "a note retired upward"), None) - .await, - "seed the source retired into it", - ); - let huge = i64::try_from(HUGE_REVISION).expect("the seeded revision fits SQLite's integer"); - sqlx::query( - "UPDATE knowledge_entries SET revision = ?, \ - payload = json_set(payload, '$.revision', ?) \ - WHERE collection = ? AND entry_id = ?", - ) - .bind(huge) - .bind(huge) - .bind(SHARED) - .bind(HUGE_TERMINAL) - .execute(pool) - .await - .expect("stamp the out-of-domain revision"); - expect_ok( - shared.supersede_entry(HUGE_RETIRED, 1, HUGE_TERMINAL).await, - "retire the source into the out-of-domain terminal", - ); - let mut private = shared_entry(PRIVATE_ENTRY, "the keeper keeps a private note"); - private.disclosure = - Some(KnowledgeEntryDisclosure::from_str("owner-private").expect("non-empty disclosure")); - private.owner = Some(KnowledgeEntryOwner::try_from("kb_keeper").expect("non-empty owner")); - expect_ok( - shared.put_knowledge_entry(private, None).await, - "seed the owner-private source", - ); -} - -/// A two-node cycle in the shared collection's markers: the store refuses to write one, so the -/// seed is two direct updates, the shape a corrupted marker pair would read as. -async fn seed_cycle(pool: &sqlx::SqlitePool) { - let shared = ScopedKnowledgeStore::new(pool.clone(), KnowledgeScope::new(SHARED)); - for entry_id in [CYCLE_A, CYCLE_B] { - expect_ok( - shared - .put_knowledge_entry(shared_entry(entry_id, "a cycle member"), None) - .await, - "seed a cycle member", - ); - } - for (entry_id, successor) in [(CYCLE_A, CYCLE_B), (CYCLE_B, CYCLE_A)] { - sqlx::query( - "UPDATE knowledge_entries SET superseded_by = ? \ - WHERE collection = ? AND entry_id = ?", - ) - .bind(successor) - .bind(SHARED) - .bind(entry_id) - .execute(pool) - .await - .expect("seed the cycle marker"); - } -} - -/// A destination slot holding a row retired into [`SLOT_SUCCESSOR`]: the slot is taken, and the -/// live-only read an adoption's destination half makes answers absence for it. -async fn seed_retired_destination(pool: &sqlx::SqlitePool) { - let destination = ScopedKnowledgeStore::new(pool.clone(), KnowledgeScope::new(COLLECTION)); - for (entry_id, summary) in [ - (RETIRED_SLOT, "somebody's retired row"), - (SLOT_SUCCESSOR, "somebody's live row"), - ] { - expect_ok( - destination - .put_knowledge_entry(shared_entry(entry_id, summary), None) - .await, - "seed the destination slot", - ); - } - expect_ok( - destination - .supersede_entry(RETIRED_SLOT, 1, SLOT_SUCCESSOR) - .await, - "retire the destination occupant", - ); -} - -/// The slot a refused claim must leave alone: the stored revision and retirement marker of -/// `entry_id` in the destination collection, read without the live-only predicate. -async fn destination_slot(pool: &sqlx::SqlitePool, entry_id: &str) -> (i64, Option) { - sqlx::query_as( - "SELECT revision, superseded_by FROM knowledge_entries \ - WHERE collection = ? AND entry_id = ?", - ) - .bind(COLLECTION) - .bind(entry_id) - .fetch_one(pool) - .await - .expect("read the destination slot") -} - -/// How many rows one collection stores under `entry_id`: the destination slot a copy claims. -async fn destination_rows(pool: &sqlx::SqlitePool, entry_id: &str) -> i64 { - sqlx::query_scalar( - "SELECT COUNT(*) FROM knowledge_entries WHERE collection = ? AND entry_id = ?", - ) - .bind(COLLECTION) - .bind(entry_id) - .fetch_one(pool) - .await - .expect("count the destination rows") -} - -/// Advertisement honesty for the adoption family: a surface with no `AdoptionRoute` advertises no -/// `spoke-knowledge-adoption`, and a dialer that negotiated it is refused at the gate before any -/// handler; the same dialer reaches `knowledge.adopt` once the route is configured. +/// The three un-routed families leave composition and advertisement together: the manifest names +/// none of them, no face is composed, and a dialer that claims them is served a missing port. #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn adoption_is_advertised_and_served_only_with_the_face() { +async fn an_un_routed_face_answers_a_missing_port() { let fixture = Fixture::open().await; - let pool = fixture.store.pool(); - seed_shared_source(&pool).await; let (_dir, serve) = fixture.serve(); - let request = adopt_request(SHARED_ENTRY, 1, "advertise-once"); - - let absent = surface( + let claimed = [ + "spoke-knowledge", + "ke-ownership", + "spoke-history", + "spoke-knowledge-adoption", + ]; + let surface = surface( &serve, faces( - hello("runtime", &[]), + hello("runtime", &claimed), None, MindProviders::default(), ), ); - assert!( - !capabilities(&absent).contains(&ADOPTION), - "an uncomposed adoption face is never advertised: {:?}", - capabilities(&absent) - ); - assert!( - capabilities(&absent).contains(&"spoke-knowledge"), - "the knowledge face stays advertised either way: {:?}", - capabilities(&absent) - ); - assert!( - absent.ports.as_adoption().is_none(), - "an uncomposed adoption face installs no adoption port" + for capability in claimed { + assert!( + !capabilities(&surface).contains(&capability), + "the un-routed face {capability} is not advertised: {:?}", + capabilities(&surface) + ); + } + assert!(surface.ports.as_knowledge().is_none()); + assert!(surface.ports.as_history().is_none()); + assert!(surface.ports.as_adoption().is_none()); + + let session = connect(&surface, &claimed).await; + let dialer = &*session.adapter; + assert_wire_deny( + KnowledgeEntryPort::get_knowledge_entry(dialer, "ke_absent").await, + "port.knowledge.get", + "op_unsupported", ); - let session = connect(&absent, &[ADOPTION, "spoke-knowledge"]).await; assert_wire_deny( - AdoptionPort::adopt_knowledge_entry( - &*session.adapter, + HistoryPort::get_history_snapshot( + dialer, &principal(), &scope_of(SCOPE_ID), - &request, + "knowledge_entry", + "ke_absent", + 1, ) .await, - "knowledge.adopt", + "history.revisions.get", "capability_missing", ); - drop(session); - - let attached = surface(&serve, adopting_faces()); - assert!( - capabilities(&attached).contains(&ADOPTION), - "a composed adoption face is advertised: {:?}", - capabilities(&attached) - ); - assert!( - attached.ports.as_adoption().is_some(), - "the adoption face is composed over the routed store" - ); - let session = connect(&attached, &[ADOPTION, "spoke-knowledge"]).await; - let adopted = wire(expect_ok( + let adopt: KnowledgeAdoptRequest = serde_json::from_value(json!({ + "source_scope_id": SCOPE_ID, + "source_entry_id": "ke_absent", + "source_revision": 1, + "destination_scope_id": SCOPE_ID, + "idempotency_key": "un-routed", + })) + .expect("request JSON matches the schema"); + assert_wire_deny( AdoptionPort::adopt_knowledge_entry( - &*session.adapter, + dialer, &principal(), &scope_of(SCOPE_ID), - &request, + &adopt, ) .await, - "adopt over the signed session", - )); - assert_eq!(adopted["outcome"], json!("adopted"), "{adopted}"); + "knowledge.adopt", + "capability_missing", + ); } -/// The served adoption end to end: the copy's anchor names the configured source triple, a repeat -/// under either key serves the stored copy instead of writing a second one, a moved source with the -/// old copy in place is the stale-copy conflict, and a retired source anchors its live terminal -/// under a supplied destination id. #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn knowledge_adopt_anchors_the_terminal_and_repeats_idempotently() { +async fn a_host_registration_reaches_its_handler_over_the_signed_session() { let fixture = Fixture::open().await; - let pool = fixture.store.pool(); - seed_shared_source(&pool).await; let (_dir, serve) = fixture.serve(); - let surface = surface(&serve, adopting_faces()); - let session = connect(&surface, &[ADOPTION, "spoke-knowledge"]).await; - let dialer = &*session.adapter; - let destination = scope_of(SCOPE_ID); - - let adopted = wire(expect_ok( - AdoptionPort::adopt_knowledge_entry( - dialer, - &principal(), - &destination, - &adopt_request(SHARED_ENTRY, 1, "adopt-once"), - ) - .await, - "the first adoption", - )); - assert_eq!(adopted["outcome"], json!("adopted"), "{adopted}"); - assert_eq!(adopted["entry"]["entry_id"], json!(SHARED_ENTRY)); - assert_eq!( - adopted["entry"]["adoption_anchor"], - json!({ - "schema_version": 1, - "source_scope_id": SHARED_SCOPE, - "source_entry_id": SHARED_ENTRY, - "source_revision": 1, - "extensions": {}, - }), - "the anchor is the configured source triple: {adopted}" - ); - assert_eq!( - destination_rows(&pool, SHARED_ENTRY).await, - 1, - "the first adoption writes the one copy" - ); - let stored = wire(expect_ok( - KnowledgeEntryPort::get_knowledge_entry(dialer, SHARED_ENTRY).await, - "read the stored copy back through the port", - )); - assert_eq!( - stored, adopted["entry"], - "the port serves the entry the first call wrote: {stored}" - ); - - let replay = wire(expect_ok( - AdoptionPort::adopt_knowledge_entry( - dialer, - &principal(), - &destination, - &adopt_request(SHARED_ENTRY, 1, "adopt-once"), - ) - .await, - "the same key and payload", - )); - assert_eq!( - replay["outcome"], - json!("already_present"), - "a replay reports the stored copy: {replay}" - ); - assert_eq!( - replay["entry"]["revision"], adopted["entry"]["revision"], - "the replay serves the copy the first call wrote" - ); - assert_eq!( - destination_rows(&pool, SHARED_ENTRY).await, - 1, - "a replay writes no second copy" - ); - - let fresh = wire(expect_ok( - AdoptionPort::adopt_knowledge_entry( - dialer, - &principal(), - &destination, - &adopt_request(SHARED_ENTRY, 1, "adopt-again"), - ) - .await, - "a fresh key on the same tuple", - )); - assert_eq!( - fresh["outcome"], - json!("already_present"), - "a fresh key re-reads the anchor instead of writing: {fresh}" - ); - assert_eq!( - fresh["entry"], stored, - "a fresh key serves the stored copy, not a different entry: {fresh}" - ); - assert_eq!( - destination_rows(&pool, SHARED_ENTRY).await, - 1, - "a fresh key still leaves one copy" + let mut faces = faces( + hello("runtime", &[]), + None, + MindProviders::default(), ); - let after = wire(expect_ok( - KnowledgeEntryPort::get_knowledge_entry(dialer, SHARED_ENTRY).await, - "re-read the copy after the fresh key", - )); - assert_eq!( - after, stored, - "a fresh key rewrites nothing in the destination slot: {after}" + faces.tools = vec![ToolRegistration::new( + host_tool_descriptor(), + |_responder| { + let handler: ToolHandler = Arc::new(|arguments: Value| { + Box::pin(async move { + spoke_ok(json!({ "answered_by": HOST_TOOL, "arguments": arguments })) + }) + }); + handler + }, + )]; + let surface = surface(&serve, faces); + assert!( + capabilities(&surface).contains(&HOST_TOOL), + "the host registration is advertised: {:?}", + capabilities(&surface) ); - // Move the source, then ask for the revision it sits at: the copy in the destination slot was - // adopted at revision 1, so the slot is a stale copy, not the revision asked for. - let shared = ScopedKnowledgeStore::new(pool.clone(), KnowledgeScope::new(SHARED)); - expect_ok( - shared - .put_knowledge_entry( - shared_entry( - SHARED_ENTRY, - "the north gate closes at dusk; a keeper walks it", - ), - Some(1), - ) + let session = connect(&surface, &[HOST_TOOL]).await; + let result = expect_ok( + session + .adapter + .invoke_tool(HOST_TOOL, json!({ "probe": 1 })) .await, - "move the source to revision 2", - ); - let stale = expect_reject( - AdoptionPort::adopt_knowledge_entry( - dialer, - &principal(), - &destination, - &adopt_request(SHARED_ENTRY, 2, "adopt-moved"), - ) - .await, - "the source moved after the copy was adopted", + "the host's own tool", ); - assert_eq!(stale.code, SpokeRejectCode::RevisionConflict, "{stale:?}"); - let details = stale.details.clone().unwrap_or_default(); assert_eq!( - details.len(), - 1, - "the refusal carries exactly adopted_revision: {details:?}" + result["answered_by"], HOST_TOOL, + "the installed host handler answered: {result}" ); - assert_eq!(details.get("adopted_revision"), Some(&json!(1))); + assert_eq!(result["arguments"], json!({ "probe": 1 })); +} - let mut retired = adopt_request(RETIRED_ENTRY, 1, "adopt-retired"); - retired.destination_entry_id = Some("ke_copy".parse().expect("non-empty destination id")); - let terminal = wire(expect_ok( - AdoptionPort::adopt_knowledge_entry(dialer, &principal(), &destination, &retired).await, - "adopt a retired source under a supplied destination id", - )); - assert_eq!(terminal["outcome"], json!("adopted"), "{terminal}"); - assert_eq!( - terminal["entry"]["entry_id"], - json!("ke_copy"), - "the copy takes the supplied destination id" - ); - let anchor = &terminal["entry"]["adoption_anchor"]; - assert_eq!(anchor["source_scope_id"], json!(SHARED_SCOPE)); - assert_eq!( - anchor["source_entry_id"], - json!(TERMINAL_ENTRY), - "the anchor names the terminal, never the retired source: {terminal}" - ); - assert_eq!(anchor["source_revision"], json!(1)); - let copy = expect_ok( - ScopedKnowledgeStore::new(pool.clone(), KnowledgeScope::new(COLLECTION)) - .get_knowledge_entry("ke_copy") - .await, - "read the adopted copy from the destination collection", - ); - assert_eq!( - adoption_anchor_parts(©), - Some((SHARED_SCOPE, TERMINAL_ENTRY, 1)), - "the stored copy carries the terminal's anchor: {copy:?}" - ); +/// An embedder whose serving identity the test rotates: it records every text it embeds, so a +/// recall's provider cost is a count rather than an inference. +struct RotatingEmbedder { + first: EmbeddingIdentity, + second: EmbeddingIdentity, + second_active: AtomicBool, + embedded: Mutex>, } -/// The refusal matrix over the signed session: one generic absence for an unserved source scope, a -/// missing source and an owner-private source; `NOT_AUTHORIZED` for another destination scope; a -/// stored marker cycle as `SOURCE_RETIRED` with its visited chain; and `IDEMPOTENCY_CONFLICT` when a -/// key replays another payload. -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn knowledge_adopt_refuses_with_the_contract_codes() { - let fixture = Fixture::open().await; - let pool = fixture.store.pool(); - seed_shared_source(&pool).await; - seed_cycle(&pool).await; - let (_dir, serve) = fixture.serve(); - let surface = surface(&serve, adopting_faces()); - let session = connect(&surface, &[ADOPTION, "spoke-knowledge"]).await; - let dialer = &*session.adapter; - let destination = scope_of(SCOPE_ID); - - let mut foreign = adopt_request(SHARED_ENTRY, 1, "refuse-foreign-source"); - foreign.source_scope_id = OTHER_SCOPE.parse().expect("non-empty scope id"); - let foreign = expect_reject( - AdoptionPort::adopt_knowledge_entry(dialer, &principal(), &destination, &foreign).await, - "another source scope", - ); - let missing = expect_reject( - AdoptionPort::adopt_knowledge_entry( - dialer, - &principal(), - &destination, - &adopt_request("ke_never_seeded", 1, "refuse-missing"), - ) - .await, - "a source the shared collection does not hold", - ); - let private = expect_reject( - AdoptionPort::adopt_knowledge_entry( - dialer, - &principal(), - &destination, - &adopt_request(PRIVATE_ENTRY, 1, "refuse-private"), - ) - .await, - "an owner-private source", - ); - for (context, reject) in [ - ("another source scope", &foreign), - ("a missing source", &missing), - ("an owner-private source", &private), - ] { - assert_eq!( - reject.code, - SpokeRejectCode::NotFound, - "{context}: {reject:?}" - ); - assert!( - reject.details.clone().unwrap_or_default().is_empty(), - "{context} carries no details: {reject:?}" - ); - } - assert_eq!( - foreign.message, missing.message, - "an unserved source scope is the same generic absence as a missing source" - ); - - let mut outside = adopt_request(SHARED_ENTRY, 1, "refuse-foreign-destination"); - outside.destination_scope_id = OTHER_SCOPE.parse().expect("non-empty scope id"); - let unauthorized = expect_reject( - AdoptionPort::adopt_knowledge_entry(dialer, &principal(), &destination, &outside).await, - "another destination scope", - ); - assert_eq!( - unauthorized.code, - SpokeRejectCode::NotAuthorized, - "{unauthorized:?}" - ); - assert!(unauthorized.details.is_none(), "{unauthorized:?}"); - - let cycle = expect_reject( - AdoptionPort::adopt_knowledge_entry( - dialer, - &principal(), - &destination, - &adopt_request(CYCLE_A, 1, "refuse-cycle"), - ) - .await, - "a stored retirement cycle", - ); - assert_eq!(cycle.code, SpokeRejectCode::SourceRetired, "{cycle:?}"); - let details = cycle.details.clone().unwrap_or_default(); - assert_eq!( - details.len(), - 1, - "the refusal carries exactly retirement_chain: {details:?}" - ); - assert_eq!( - details.get("retirement_chain"), - Some(&json!([CYCLE_A, CYCLE_B, CYCLE_A])), - "the chain lists the visited ids, the repeat last" - ); - - expect_ok( - AdoptionPort::adopt_knowledge_entry( - dialer, - &principal(), - &destination, - &adopt_request(TERMINAL_ENTRY, 1, "recorded-key"), - ) - .await, - "the call a key records", - ); - let mut replayed = adopt_request(TERMINAL_ENTRY, 1, "recorded-key"); - replayed.destination_entry_id = Some("ke_recorded".parse().expect("non-empty destination id")); - let conflict = expect_reject( - AdoptionPort::adopt_knowledge_entry(dialer, &principal(), &destination, &replayed).await, - "the same key with another payload", - ); - assert_eq!( - conflict.code, - SpokeRejectCode::IdempotencyConflict, - "{conflict:?}" - ); - - for (context, reject) in [ - ("another source scope", &foreign), - ("a missing source", &missing), - ("an owner-private source", &private), - ("another destination scope", &unauthorized), - ("a stored cycle", &cycle), - ("a replayed key", &conflict), - ] { - assert!( - !reject.message.contains("knowledge_entries"), - "{context} names no table: {reject:?}" - ); - } -} - -/// An occupied destination slot answers the ordinary occupancy refusal whatever the admitted -/// selection makes of its occupant: hidden and visible occupants are byte-identical, so the answer -/// reports occupancy and nothing about the occupant. A slot the selection cannot claim answers the -/// same refusal and writes nothing, and a genuinely free, usable slot still creates. -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn an_occupied_destination_answers_occupancy_whatever_the_selection_shows() { - let fixture = Fixture::open().await; - let pool = fixture.store.pool(); - seed_shared_source(&pool).await; - // A destination occupant the caller may or may not be shown, depending on the admitted - // selection: either way it holds the slot `ke_shared` names. - expect_ok( - ScopedKnowledgeStore::new(pool.clone(), KnowledgeScope::new(COLLECTION)) - .put_knowledge_entry(shared_entry(SHARED_ENTRY, "somebody else's row"), None) - .await, - "seed the destination occupant", - ); - let (_dir, serve) = fixture.serve(); - let surface_of = |admission: KnowledgeAdmission| { - let mut admitted = adopting_faces(); - admitted.admission = admission; - surface(&serve, admitted) - }; - - let mut refusals = Vec::new(); - for (context, surface) in [ - ("a visible occupant", surface_of(knowledge_admission())), - ( - "an entry-id selection that hides the occupant", - surface_of(restricted_knowledge_admission( - json!({ "entry_ids": ["ke_somebody_else"] }), - )), - ), - ( - "an entry-type selection that hides the occupant", - surface_of(restricted_knowledge_admission( - json!({ "entry_types": ["belief"] }), - )), - ), - ] { - let session = connect(&surface, &[ADOPTION, "spoke-knowledge"]).await; - let reject = expect_reject( - AdoptionPort::adopt_knowledge_entry( - &*session.adapter, - &principal(), - &scope_of(SCOPE_ID), - &adopt_request(SHARED_ENTRY, 1, context), - ) - .await, - context, - ); - assert_eq!( - reject.code, - SpokeRejectCode::RevisionConflict, - "{context} is an occupancy, not an authorization answer: {reject:?}" - ); - assert!( - reject.details.is_none(), - "{context} carries no details: {reject:?}" - ); - drop(session); - refusals.push((context, reject)); - } - let (_, visible) = &refusals[0]; - for (context, hidden) in &refusals[1..] { - assert_eq!( - hidden, visible, - "{context} must not be distinguishable from a visible occupant" - ); - } - - // A slot the selection cannot claim is not adoptable either: it answers the same occupancy and - // leaves the collection without a copy. - let restricted = surface_of(restricted_knowledge_admission( - json!({ "entry_types": ["belief"] }), - )); - let session = connect(&restricted, &[ADOPTION, "spoke-knowledge"]).await; - let reject = expect_reject( - AdoptionPort::adopt_knowledge_entry( - &*session.adapter, - &principal(), - &scope_of(SCOPE_ID), - &adopt_request(TERMINAL_ENTRY, 1, "unusable-free-slot"), - ) - .await, - "a free slot outside the admitted selection", - ); - assert_eq!( - reject.code, - SpokeRejectCode::RevisionConflict, - "a free slot this call may not claim answers the occupancy: {reject:?}" - ); - assert!( - reject.details.is_none(), - "the unusable-slot refusal carries no details: {reject:?}" - ); - assert_eq!( - destination_rows(&pool, TERMINAL_ENTRY).await, - 0, - "the unusable free slot writes nothing" - ); - drop(session); - - // The same free slot under an admitting selection still creates. - let admitting = surface_of(knowledge_admission()); - let session = connect(&admitting, &[ADOPTION, "spoke-knowledge"]).await; - let adopted = wire(expect_ok( - AdoptionPort::adopt_knowledge_entry( - &*session.adapter, - &principal(), - &scope_of(SCOPE_ID), - &adopt_request(TERMINAL_ENTRY, 1, "unrestricted-selection"), - ) - .await, - "an unrestricted admission still adopts into a free slot", - )); - assert_eq!(adopted["outcome"], json!("adopted"), "{adopted}"); - assert_eq!( - destination_rows(&pool, TERMINAL_ENTRY).await, - 1, - "the unrestricted admission writes the one copy" - ); - let stored = wire(expect_ok( - KnowledgeEntryPort::get_knowledge_entry(&*session.adapter, TERMINAL_ENTRY).await, - "read the stored copy back through the knowledge face", - )); - drop(session); - - // The same slot re-read under a selection that cannot see it: the repeat is the ordinary - // occupancy again — never the stored copy, never a distinct answer — and the slot is left - // byte-identical. - let surface = surface_of(restricted_knowledge_admission( - json!({ "entry_ids": ["ke_somebody_else"] }), - )); - let session = connect(&surface, &[ADOPTION, "spoke-knowledge"]).await; - let reject = expect_reject( - AdoptionPort::adopt_knowledge_entry( - &*session.adapter, - &principal(), - &scope_of(SCOPE_ID), - &adopt_request(TERMINAL_ENTRY, 1, "restricted-reread"), - ) - .await, - "a repeat under a selection that hides the stored copy", - ); - assert_eq!( - reject.code, - SpokeRejectCode::RevisionConflict, - "the hidden repeat answers occupancy instead of serving the copy: {reject:?}" - ); - assert!( - reject.details.is_none(), - "the hidden repeat carries no details: {reject:?}" - ); - drop(session); - assert_eq!( - destination_rows(&pool, TERMINAL_ENTRY).await, - 1, - "a refused repeat writes no second copy" - ); - let session = connect(&admitting, &[ADOPTION, "spoke-knowledge"]).await; - let after = wire(expect_ok( - KnowledgeEntryPort::get_knowledge_entry(&*session.adapter, TERMINAL_ENTRY).await, - "re-read the copy under an admitting scope", - )); - assert_eq!( - after, stored, - "a refused repeat leaves the destination slot unchanged: {after}" - ); -} - -/// A destination slot whose occupant is retired reads as absent to the live-only destination read, -/// so the adoption must answer the ordinary occupancy instead: `REVISION_CONFLICT` with no details -/// over a signed session, and the slot's revision and retirement marker stay as they were. -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn a_retired_destination_occupant_answers_occupancy_over_the_signed_session() { - let fixture = Fixture::open().await; - let pool = fixture.store.pool(); - seed_shared_source(&pool).await; - seed_retired_destination(&pool).await; - let before = destination_slot(&pool, RETIRED_SLOT).await; - let (_dir, serve) = fixture.serve(); - let surface = surface(&serve, adopting_faces()); - let session = connect(&surface, &[ADOPTION, "spoke-knowledge"]).await; - - let mut claim = adopt_request(SHARED_ENTRY, 1, "retired-destination"); - claim.destination_entry_id = Some(RETIRED_SLOT.parse().expect("non-empty destination id")); - let reject = expect_reject( - AdoptionPort::adopt_knowledge_entry( - &*session.adapter, - &principal(), - &scope_of(SCOPE_ID), - &claim, - ) - .await, - "a claim on a retired destination slot", - ); - assert_eq!( - reject.code, - SpokeRejectCode::RevisionConflict, - "a retired occupant is occupancy, not an absence: {reject:?}" - ); - assert!( - reject.details.is_none(), - "the retired-slot refusal carries no details: {reject:?}" - ); - drop(session); - - assert_eq!( - destination_slot(&pool, RETIRED_SLOT).await, - before, - "a refused claim leaves the retired slot's revision and marker unchanged" - ); - assert_eq!( - destination_rows(&pool, RETIRED_SLOT).await, - 1, - "the refused claim writes no second row into the slot" - ); -} - -/// A stored source can sit at a revision the served wire cannot carry. The call refuses before the -/// copy is written, so a committed copy is never reported as a transport failure and the -/// destination stays empty. -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn adoption_refuses_a_terminal_revision_outside_the_served_range() { - let fixture = Fixture::open().await; - let pool = fixture.store.pool(); - seed_shared_source(&pool).await; - let (_dir, serve) = fixture.serve(); - let surface = surface(&serve, adopting_faces()); - let session = connect(&surface, &[ADOPTION, "spoke-knowledge"]).await; - let dialer = &*session.adapter; - - // A retired source whose live terminal sits at 2^53 + 2: the request's own revision is in range - // and is never compared against a retired source, so only the resolved terminal can refuse. - let reject = expect_reject( - AdoptionPort::adopt_knowledge_entry( - dialer, - &principal(), - &scope_of(SCOPE_ID), - &adopt_request(HUGE_RETIRED, 1, "adopt-out-of-domain"), - ) - .await, - "a terminal revision above the served ceiling", - ); - assert_eq!(reject.code, SpokeRejectCode::InternalError, "{reject:?}"); - assert_eq!( - reject.message, "knowledge adoption could not complete", - "the refusal carries the fixed fault message: {reject:?}" - ); - assert_eq!( - reject - .details - .as_ref() - .and_then(|details| details.get("kind")) - .and_then(Value::as_str), - Some("store"), - "the refusal names the failing stage: {reject:?}" - ); - assert_eq!( - destination_rows(&pool, HUGE_TERMINAL).await, - 0, - "an unservable terminal writes no copy" - ); - assert_eq!( - destination_rows(&pool, HUGE_RETIRED).await, - 0, - "and no copy under the requested id either" - ); -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn a_host_registration_reaches_its_handler_over_the_signed_session() { - let fixture = Fixture::open().await; - let (_dir, serve) = fixture.serve(); - let mut faces = faces( - hello("runtime", &[]), - None, - MindProviders::default(), - ); - faces.tools = vec![ToolRegistration::new( - host_tool_descriptor(), - |_responder| { - let handler: ToolHandler = Arc::new(|arguments: Value| { - Box::pin(async move { - spoke_ok(json!({ "answered_by": HOST_TOOL, "arguments": arguments })) - }) - }); - handler - }, - )]; - let surface = surface(&serve, faces); - assert!( - capabilities(&surface).contains(&HOST_TOOL), - "the host registration is advertised: {:?}", - capabilities(&surface) - ); - - let session = connect(&surface, &[HOST_TOOL]).await; - let result = expect_ok( - session - .adapter - .invoke_tool(HOST_TOOL, json!({ "probe": 1 })) - .await, - "the host's own tool", - ); - assert_eq!( - result["answered_by"], HOST_TOOL, - "the installed host handler answered: {result}" - ); - assert_eq!(result["arguments"], json!({ "probe": 1 })); -} - -/// An embedder whose serving identity the test rotates: it records every text it embeds, so a -/// recall's provider cost is a count rather than an inference. -struct RotatingEmbedder { - first: EmbeddingIdentity, - second: EmbeddingIdentity, - second_active: AtomicBool, - embedded: Mutex>, -} - -impl RotatingEmbedder { - fn new(first: EmbeddingIdentity, second: EmbeddingIdentity) -> Self { - Self { - first, - second, - second_active: AtomicBool::new(false), - embedded: Mutex::new(Vec::new()), - } - } +impl RotatingEmbedder { + fn new(first: EmbeddingIdentity, second: EmbeddingIdentity) -> Self { + Self { + first, + second, + second_active: AtomicBool::new(false), + embedded: Mutex::new(Vec::new()), + } + } /// The host rotating its embedder to the other serving identity. fn rotate(&self) { @@ -3557,642 +2718,3 @@ async fn retiring_a_warm_identity_forces_its_next_query_embed() { ); } -/// One entry the history face replays: a note whose summary names what that revision held. -fn history_entry(entry_id: &str, summary: &str) -> KnowledgeEntry { - serde_json::from_value(json!({ - "schema_version": 1, - "entry_id": entry_id, - "entry_type": "note", - "canonical_name": format!("{entry_id}'s history"), - "status": "confirmed", - "body": { "summary": summary }, - "extensions": {}, - })) - .expect("entry JSON matches the schema") -} - -/// Advertisement honesty for the history family: the dialer claims `spoke-history` in both -/// sessions, yet both ops are denied while the host composes no history service and served once -/// it does. -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn history_is_advertised_and_served_only_with_the_face() { - let fixture = Fixture::open().await; - expect_ok( - fixture - .store - .knowledge(KnowledgeScope::new(COLLECTION)) - .put_knowledge_entry(history_entry("ke_history", "the gate opens at dawn"), None) - .await, - "seed the replayed entry", - ); - let (_dir, serve) = fixture.serve(); - - let absent = surface( - &serve, - faces( - hello("runtime", &["spoke-history"]), - None, - MindProviders::default(), - ), - ); - assert!( - !capabilities(&absent).contains(&"spoke-history"), - "an uncomposed history face is never advertised: {:?}", - capabilities(&absent) - ); - let session = connect(&absent, &["spoke-history"]).await; - assert_wire_deny( - HistoryPort::get_history_snapshot( - &*session.adapter, - &principal(), - &scope_of(SCOPE_ID), - "knowledge_entry", - "ke_history", - 1, - ) - .await, - "history.revisions.get", - "capability_missing", - ); - assert_wire_deny( - session - .adapter - .prune_history( - &scope_of(SCOPE_ID), - "knowledge_entry", - "ke_history", - 1, - None, - ) - .await, - "history.revisions.prune", - "capability_missing", - ); - drop(session); - - let mut attached = faces( - hello("runtime", &["spoke-history"]), - None, - MindProviders::default(), - ); - attached.history = true; - let attached = surface(&serve, attached); - assert!( - capabilities(&attached).contains(&"spoke-history"), - "a composed history face is advertised: {:?}", - capabilities(&attached) - ); - let session = connect(&attached, &["spoke-history"]).await; - let snapshot = expect_ok( - HistoryPort::get_history_snapshot( - &*session.adapter, - &principal(), - &scope_of(SCOPE_ID), - "knowledge_entry", - "ke_history", - 1, - ) - .await, - "replay revision 1 over the signed session", - ); - assert_eq!(snapshot.revision, 1); - assert_eq!(snapshot.entity_id.as_str(), "ke_history"); - let pruned = expect_ok( - session - .adapter - .prune_history( - &scope_of(SCOPE_ID), - "knowledge_entry", - "ke_history", - 1, - None, - ) - .await, - "prune the live row's empty checkpoint history", - ); - assert_eq!(pruned.deleted, 0, "the live row is not a checkpoint"); - assert_eq!(pruned.floor_revision, None, "a no-op reports no floor"); -} - -/// The served history face end to end: three revisions over the signed session, both historic -/// states replayed byte-identically, one explicit prune, then the refusal matrix's history rows. -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn history_replays_prunes_and_refuses_over_a_signed_session() { - let fixture = Fixture::open().await; - let (_dir, serve) = fixture.serve(); - let mut attached = faces( - hello("runtime", &["spoke-history", "spoke-knowledge"]), - None, - MindProviders::default(), - ); - attached.history = true; - let surface = surface(&serve, attached); - let session = connect(&surface, &["spoke-history", "spoke-knowledge"]).await; - let dialer = &*session.adapter; - let scope = scope_of(SCOPE_ID); - - let created = expect_ok( - KnowledgeEntryPort::put_knowledge_entry( - dialer, - history_entry("ke_history", "the gate opens at dawn"), - None, - ) - .await, - "create the entry over the signed session", - ); - let updated_once = expect_ok( - KnowledgeEntryPort::put_knowledge_entry( - dialer, - history_entry("ke_history", "the gate closes at dusk"), - created.revision, - ) - .await, - "update the entry to revision 2", - ); - let updated_twice = expect_ok( - KnowledgeEntryPort::put_knowledge_entry( - dialer, - history_entry("ke_history", "the gate opens again at dawn"), - updated_once.revision, - ) - .await, - "update the entry to revision 3", - ); - assert_eq!(updated_twice.revision, Some(3)); - - for (revision, historic) in [(1u64, &created), (2u64, &updated_once)] { - let replay = expect_ok( - HistoryPort::get_history_snapshot( - dialer, - &principal(), - &scope, - "knowledge_entry", - "ke_history", - revision, - ) - .await, - "replay a historic revision", - ); - assert_eq!(replay.entity_kind.as_str(), "knowledge_entry"); - assert_eq!(replay.entity_id.as_str(), "ke_history"); - assert_eq!(replay.revision, revision); - assert_eq!( - serde_json::to_value(&replay.snapshot).expect("the snapshot serializes"), - serde_json::to_value(historic).expect("the historic entry serializes"), - "revision {revision} replays the entry as it stood" - ); - let again = expect_ok( - HistoryPort::get_history_snapshot( - dialer, - &principal(), - &scope, - "knowledge_entry", - "ke_history", - revision, - ) - .await, - "replay the same revision again", - ); - assert!( - expect_ok( - revision_snapshots_equal_canonical(&replay, &again), - "compare two replays of one revision" - ), - "two replays of revision {revision} are canonically equal" - ); - } - - let pruned = expect_ok( - session - .adapter - .prune_history( - &scope, - "knowledge_entry", - "ke_history", - 1, - Some("prune-one"), - ) - .await, - "prune the entry to its newest checkpoint", - ); - assert_eq!(pruned.deleted, 1, "the older checkpoint was deleted"); - assert_eq!( - pruned.floor_revision, - Some(2), - "the floor is the newest deleted revision plus one" - ); - - let reject = expect_reject( - HistoryPort::get_history_snapshot( - dialer, - &principal(), - &scope, - "knowledge_entry", - "ke_history", - 1, - ) - .await, - "replay a revision below the pruned floor", - ); - assert_eq!(reject.code, SpokeRejectCode::HistoryTruncated); - let details = reject.details.clone().unwrap_or_default(); - assert_eq!( - details.len(), - 1, - "the refusal carries exactly floor_revision: {details:?}" - ); - assert_eq!(details.get("floor_revision"), Some(&json!(2))); - expect_ok( - HistoryPort::get_history_snapshot( - dialer, - &principal(), - &scope, - "knowledge_entry", - "ke_history", - 2, - ) - .await, - "a revision equal to the floor still replays", - ); - - let reject = expect_reject( - HistoryPort::get_history_snapshot( - dialer, - &principal(), - &scope, - "knowledge_entry", - "ke_never_seeded", - 1, - ) - .await, - "replay an unknown entity id", - ); - assert_eq!(reject.code, SpokeRejectCode::NotFound); - assert!( - reject.details.clone().unwrap_or_default().is_empty(), - "an absence carries no details" - ); - - let reject = expect_reject( - HistoryPort::get_history_snapshot( - dialer, - &principal(), - &scope, - "relation", - "rel_history", - 1, - ) - .await, - "replay an entity kind this store never keeps", - ); - assert_eq!(reject.code, SpokeRejectCode::HistoryEntityUnsupported); - let details = reject.details.clone().unwrap_or_default(); - assert_eq!( - details.len(), - 1, - "the refusal carries exactly entity_kind: {details:?}" - ); - assert_eq!(details.get("entity_kind"), Some(&json!("relation"))); -} - -/// Two history surfaces on one database route to different collections. They share a wire scope, -/// a principal and an idempotency key, and the second surface's prune must run rather than replay -/// the first surface's recorded outcome for a collection it does not serve. -/// -/// This fails before the namespace: both surfaces derive the same dedup key, so the second answers -/// the first's `{deleted: 1}` for an entry its own collection does not hold. -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn a_prune_does_not_replay_across_collections_on_one_database() { - let fixture = Fixture::open().await; - let store = fixture.store.knowledge(KnowledgeScope::new(COLLECTION)); - let mut base = None; - for summary in [ - "the gate opens at dawn", - "the gate closes at dusk", - "the gate opens again at dawn", - ] { - base = expect_ok( - store - .put_knowledge_entry(history_entry("ke_history", summary), base) - .await, - "seed the first collection's history", - ) - .revision; - } - let scope = scope_of(SCOPE_ID); - let (dir, serve) = fixture.serve(); - - let mut first = faces( - hello("runtime", &["spoke-history"]), - None, - MindProviders::default(), - ); - first.history = true; - let first_surface = surface(&serve, first); - let first_session = connect(&first_surface, &["spoke-history"]).await; - let pruned = expect_ok( - first_session - .adapter - .prune_history(&scope, "knowledge_entry", "ke_history", 1, Some("key-one")) - .await, - "the first collection's prune", - ); - assert_eq!(pruned.deleted, 1); - assert_eq!(pruned.floor_revision, Some(2)); - - // Same wire scope, same principal, same idempotency key — another collection. - let mut second = faces( - hello("runtime", &["spoke-history"]), - None, - MindProviders::default(), - ); - second.history = true; - second.knowledge = KnowledgeScope::new(COLLECTION_TWO); - let second_surface = surface(&serve, second); - let second_session = connect(&second_surface, &["spoke-history"]).await; - - let reject = expect_reject( - second_session - .adapter - .prune_history(&scope, "knowledge_entry", "ke_history", 1, Some("key-one")) - .await, - "the second collection holds no such entry, so its own prune runs and refuses", - ); - assert_eq!( - reject.code, - SpokeRejectCode::NotFound, - "the second surface executed its own prune instead of replaying the first's outcome" - ); - - // The refusal is now the second surface's own recorded outcome for that key. - let replay = expect_reject( - second_session - .adapter - .prune_history(&scope, "knowledge_entry", "ke_history", 1, Some("key-one")) - .await, - "the second surface's same-key replay", - ); - assert_eq!(replay.code, SpokeRejectCode::NotFound); - assert_eq!(replay, reject, "the recorded refusal replays verbatim"); - - // And the first surface still replays its own recorded success. - let replay = expect_ok( - first_session - .adapter - .prune_history(&scope, "knowledge_entry", "ke_history", 1, Some("key-one")) - .await, - "the first surface's same-key replay", - ); - assert_eq!( - serde_json::to_vec(&replay).expect("the result serializes"), - serde_json::to_vec(&pruned).expect("the result serializes"), - "the recorded outcome replays byte-equal within its own collection" - ); - - drop(dir); -} - -/// The prune's idempotency contract over the wire: one key replays its recorded outcome, the same -/// key with another payload conflicts, and a fresh key runs the prune again. -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn a_prune_replays_its_recorded_outcome_for_the_same_key() { - let fixture = Fixture::open().await; - let store = fixture.store.knowledge(KnowledgeScope::new(COLLECTION)); - let mut base = None; - for summary in [ - "the gate opens at dawn", - "the gate closes at dusk", - "the gate opens again at dawn", - ] { - base = expect_ok( - store - .put_knowledge_entry(history_entry("ke_history", summary), base) - .await, - "seed the entry's history", - ) - .revision; - } - let (_dir, serve) = fixture.serve(); - let mut attached = faces( - hello("runtime", &["spoke-history"]), - None, - MindProviders::default(), - ); - attached.history = true; - let surface = surface(&serve, attached); - let session = connect(&surface, &["spoke-history"]).await; - let dialer = &*session.adapter; - let scope = scope_of(SCOPE_ID); - - let first = expect_ok( - dialer - .prune_history(&scope, "knowledge_entry", "ke_history", 1, Some("key-one")) - .await, - "the first prune", - ); - assert_eq!(first.deleted, 1); - assert_eq!(first.floor_revision, Some(2)); - - // One more revision after the first prune leaves two checkpoints (2 and 3), so a replay that - // re-ran the prune instead of replaying its record would delete checkpoint 2 and report a - // higher floor. The record is the only thing keeping that checkpoint alive. - expect_ok( - store - .put_knowledge_entry( - history_entry("ke_history", "the gate is bolted at midnight"), - base, - ) - .await, - "write another revision after the first prune", - ); - - let replay = expect_ok( - session - .adapter - .prune_history(&scope, "knowledge_entry", "ke_history", 1, Some("key-one")) - .await, - "the same key and payload", - ); - assert_eq!( - serde_json::to_vec(&replay).expect("the result serializes"), - serde_json::to_vec(&first).expect("the result serializes"), - "the recorded outcome replays byte-equal" - ); - for revision in [2u64, 3] { - expect_ok( - HistoryPort::get_history_snapshot( - dialer, - &principal(), - &scope, - "knowledge_entry", - "ke_history", - revision, - ) - .await, - "the replay deleted nothing, so both checkpoints above the floor still exist", - ); - } - - let reject = expect_reject( - session - .adapter - .prune_history(&scope, "knowledge_entry", "ke_history", 2, Some("key-one")) - .await, - "the same key with another keep", - ); - assert_eq!(reject.code, SpokeRejectCode::IdempotencyConflict); - - let fresh = expect_ok( - session - .adapter - .prune_history(&scope, "knowledge_entry", "ke_history", 1, Some("key-two")) - .await, - "a new key runs the prune again", - ); - assert_eq!( - fresh.deleted, 1, - "the checkpoint written after the first prune is now the older one" - ); - assert_eq!( - fresh.floor_revision, - Some(3), - "the fresh key really pruned: the floor moved past checkpoint 2" - ); - let reject = expect_reject( - HistoryPort::get_history_snapshot( - dialer, - &principal(), - &scope, - "knowledge_entry", - "ke_history", - 2, - ) - .await, - "replay the checkpoint the fresh key pruned", - ); - assert_eq!(reject.code, SpokeRejectCode::HistoryTruncated); - assert_eq!( - reject - .details - .clone() - .unwrap_or_default() - .get("floor_revision"), - Some(&json!(3)) - ); -} - -/// The record lives in the database file, not in the process: after the session, the surface and -/// the serve are gone, a reopened file replays the prune's outcome instead of executing again -/// against checkpoints the original call never saw. -/// -/// This fails against the in-memory default — a fresh surface starts with an empty store, the -/// retry answers `Unseen`, and the re-run deletes checkpoint 2. -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn a_prune_replays_its_recorded_outcome_after_the_store_is_reopened() { - let fixture = Fixture::open().await; - let path = fixture.db_path(); - let store = fixture.store.knowledge(KnowledgeScope::new(COLLECTION)); - let mut base = None; - for summary in [ - "the gate opens at dawn", - "the gate closes at dusk", - "the gate opens again at dawn", - ] { - base = expect_ok( - store - .put_knowledge_entry(history_entry("ke_history", summary), base) - .await, - "seed the entry's history", - ) - .revision; - } - let scope = scope_of(SCOPE_ID); - - let (dir, serve) = fixture.serve(); - let first = { - let mut attached = faces( - hello("runtime", &["spoke-history"]), - None, - MindProviders::default(), - ); - attached.history = true; - let surface = surface(&serve, attached); - let session = connect(&surface, &["spoke-history"]).await; - let first = expect_ok( - session - .adapter - .prune_history(&scope, "knowledge_entry", "ke_history", 1, Some("key-one")) - .await, - "the first prune", - ); - assert_eq!(first.deleted, 1); - assert_eq!(first.floor_revision, Some(2)); - first - }; - - // One more revision leaves checkpoints 2 and 3 above the floor, so a retry that re-ran the - // prune instead of replaying its record would delete checkpoint 2 and report a higher floor. - expect_ok( - store - .put_knowledge_entry( - history_entry("ke_history", "the gate is bolted at midnight"), - base, - ) - .await, - "write another revision after the first prune", - ); - - // The whole serving stack goes away: the record has to be on disk to survive this. - drop(store); - drop(serve); - - let reopened = MindStore::open(&path) - .await - .expect("reopen the same database file"); - let serve = MindcoreServe::new(reopened, false, |_targets| Ok(())); - let mut attached = faces( - hello("runtime", &["spoke-history"]), - None, - MindProviders::default(), - ); - attached.history = true; - let surface = surface(&serve, attached); - let session = connect(&surface, &["spoke-history"]).await; - let dialer = &*session.adapter; - - let replay = expect_ok( - dialer - .prune_history(&scope, "knowledge_entry", "ke_history", 1, Some("key-one")) - .await, - "the same key and payload after a reopen", - ); - assert_eq!( - serde_json::to_vec(&replay).expect("the result serializes"), - serde_json::to_vec(&first).expect("the result serializes"), - "the recorded outcome replays byte-equal across a reopen" - ); - for revision in [2u64, 3] { - expect_ok( - HistoryPort::get_history_snapshot( - dialer, - &principal(), - &scope, - "knowledge_entry", - "ke_history", - revision, - ) - .await, - "the replayed prune deleted nothing, so both checkpoints above the floor still exist", - ); - } - - let reject = expect_reject( - dialer - .prune_history(&scope, "knowledge_entry", "ke_history", 2, Some("key-one")) - .await, - "the same key with another keep after a reopen", - ); - assert_eq!(reject.code, SpokeRejectCode::IdempotencyConflict); - - drop(dir); -} diff --git a/crates/mindcore-runtime/tests/surface.rs b/crates/mindcore-runtime/tests/surface.rs index 6f854556..f842ae8e 100644 --- a/crates/mindcore-runtime/tests/surface.rs +++ b/crates/mindcore-runtime/tests/surface.rs @@ -1,6 +1,6 @@ //! Fixture wiring for the serving surface: the manifest follows the composed faces and the tool -//! registrations, the knowledge admission is validated where the face is assembled, and the ports -//! compose no baseline provider. +//! registrations, the un-routed faces are absent rather than stubbed, and the ports compose no +//! baseline provider. use std::collections::HashMap; use std::sync::{Arc, Mutex}; @@ -9,27 +9,21 @@ use async_trait::async_trait; use serde_json::{json, Value}; use tempfile::TempDir; -use mindcore_base::knowledge::KnowledgeScope; use mindcore_runtime::tools::{ABSORB, DELIBERATE, READ_COGNITION, RECALL_CONTEXT}; -use mindcore_runtime::{AdoptionRoute, MindProviders, MindcoreServe, ServeFaces, ToolRegistration}; +use mindcore_runtime::{MindProviders, MindcoreServe, ServeFaces, ToolRegistration}; use mindcore_spoke::{ServedMemory, TRANSFER_OPERATIONS}; -use mindcore_sqlite::{MindStore, ScopedKnowledgeStore}; -use spoke_connect::core::{ - CAPABILITY_SPOKE_HISTORY, CAPABILITY_SPOKE_JUDGMENT, CAPABILITY_SPOKE_KNOWLEDGE_ADOPTION, -}; +use mindcore_sqlite::MindStore; +use spoke_connect::core::CAPABILITY_SPOKE_JUDGMENT; use spoke_connect::remote::{ - connect_responder, loopback_transport_pair, ConnectResponderOptions, KnowledgeAdmission, - MemoryAdmission, RemoteIdentity, RemoteMemoryService, ToolHandler, KNOWLEDGE_OP_ADOPT, + connect_responder, loopback_transport_pair, ConnectResponderOptions, MemoryAdmission, + RemoteIdentity, RemoteMemoryService, ToolHandler, }; use spoke_operations::{ - spoke_ok, spoke_reject, validate_manifest_tools, KnowledgeEntryPort, SpokeReject, - SpokeRejectCode, SpokeResult, + spoke_ok, spoke_reject, validate_manifest_tools, SpokeRejectCode, SpokeResult, }; use spoke_schemas::host_capability_manifest::ToolDescriptor; -use spoke_schemas::{HostCapabilityManifest, Scope}; +use spoke_schemas::HostCapabilityManifest; -const SCOPE_ID: &str = "spoke-scope-001"; -const COLLECTION: &str = "wren"; const HOST_TOOL: &str = "tools.mindcore.host_tool"; /// The retired product adoption id the runtime drops from every host registration. const RETIRED_ADOPT: &str = "tools.mindcore.adopt"; @@ -74,40 +68,10 @@ fn metadata(host_id: &str) -> HostCapabilityManifest { .expect("manifest JSON matches the schema") } -fn scope_of(scope_id: &str) -> Scope { - serde_json::from_value(json!({ "scope_id": scope_id })).expect("scope JSON matches the schema") -} - -/// One selection the knowledge face does not serve. -fn unsupported_scope() -> Scope { - serde_json::from_value(json!({ - "scope_id": SCOPE_ID, - "cognition": { "view": "recorded_at", "filter": {} }, - })) - .expect("scope JSON matches the schema") -} - -/// The host's admission: one admitted peer, one peer whose admitted scope carries a selection the -/// face does not serve, one peer the host admits under a scope id this surface does not serve, and -/// a stranger. -fn admission() -> KnowledgeAdmission { - Arc::new(|peer_id: &str| match peer_id { - "peer-owner" => SpokeResult::Ok(scope_of(SCOPE_ID)), - "peer-cognition" => SpokeResult::Ok(unsupported_scope()), - "peer-elsewhere" => SpokeResult::Ok(scope_of("spoke-scope-other")), - _ => spoke_reject( - SpokeRejectCode::NotAuthorized, - format!("peer {peer_id} holds no knowledge admission"), - None, - ), - }) -} - -/// The host's peer-to-principal admission: the driver is admitted, and the mismatch peer is -/// admitted as the same principal so only the admitted scope id can refuse it. A stranger is not. +/// The host's peer-to-principal admission: the owner is admitted, a stranger is not. fn principals() -> MemoryAdmission { Arc::new(|peer_id: &str| match peer_id { - "peer-owner" | "peer-elsewhere" => SpokeResult::Ok( + "peer-owner" => SpokeResult::Ok( serde_json::from_value(json!({ "principal_id": "prn_owner", "extensions": {} })) .expect("principal JSON matches the schema"), ), @@ -159,25 +123,12 @@ impl ServedMemory for FourOfFive { } } -/// The one shared source collection an adopting surface reads from. -fn adoption_source() -> AdoptionRoute { - AdoptionRoute { - scope_id: "spc_shared".to_string(), - source: KnowledgeScope::new("shared"), - } -} - fn faces(manifest: HostCapabilityManifest) -> ServeFaces { ServeFaces { manifest, - scope_id: SCOPE_ID.to_string(), - knowledge: KnowledgeScope::new(COLLECTION), - admission: admission(), memory: None, - history: false, principals: principals(), providers: MindProviders::default(), - adoption: None, tools: Vec::new(), } } @@ -210,14 +161,8 @@ fn expect_ok(result: SpokeResult, context: &str) -> T { } } -fn expect_reject(result: SpokeResult, context: &str) -> SpokeReject { - match result { - SpokeResult::Reject(reject) => reject, - SpokeResult::Ok(value) => panic!("{context}: unexpectedly accepted with {value:?}"), - } -} - -/// The knowledge family and the three Mind tools are the only served capabilities. +/// The three Mind tools and their judgment family are the only served capabilities: no knowledge, +/// history or adoption face is composed, so none is advertised and none is served. #[tokio::test] async fn manifest_follows_the_composed_faces() { let serve = Fixture::open().await.serve(); @@ -229,8 +174,6 @@ async fn manifest_follows_the_composed_faces() { assert_eq!( capabilities(&surface), [ - "spoke-knowledge", - "ke-ownership", CAPABILITY_SPOKE_JUDGMENT, RECALL_CONTEXT, ABSORB, @@ -238,11 +181,6 @@ async fn manifest_follows_the_composed_faces() { READ_COGNITION ] ); - assert!( - capabilities(&surface).contains(&CAPABILITY_SPOKE_JUDGMENT), - "the wire map registers `deliberate`, so its judgment family is advertised: {:?}", - capabilities(&surface) - ); let tools: Vec<&str> = surface .manifest .tools @@ -268,226 +206,49 @@ async fn manifest_follows_the_composed_faces() { "no baseline provider is composed" ); assert!( - surface.ports.as_knowledge().is_some(), - "the knowledge face is composed" - ); - assert!( - surface.ports.as_memory().is_none(), - "no memory service was attached" + surface.ports.as_knowledge().is_none(), + "no knowledge face is composed: the responder answers its ops as a missing port" ); assert!( surface.ports.as_history().is_none(), - "the history face is off, so no history service is composed" - ); - - let served = expect_ok( - serve.surface(ServeFaces { - history: true, - ..faces(metadata("runtime")) - }), - "assemble a history-serving surface", - ); - assert_eq!( - capabilities(&served), - [ - "spoke-knowledge", - "ke-ownership", - CAPABILITY_SPOKE_HISTORY, - CAPABILITY_SPOKE_JUDGMENT, - RECALL_CONTEXT, - ABSORB, - DELIBERATE, - READ_COGNITION - ], - "the history face is advertised exactly when it is served" - ); - assert!( - served.ports.as_history().is_some(), - "the history face is composed over the routed store" - ); - expect_ok( - validate_manifest_tools(&served.manifest), - "the history-serving manifest is self-consistent", + "no history face is composed" ); - assert!( - !capabilities(&served).contains(&CAPABILITY_SPOKE_KNOWLEDGE_ADOPTION), - "no adoption source is configured, so the adoption face is not advertised" - ); - let adopting = expect_ok( - serve.surface(ServeFaces { - adoption: Some(adoption_source()), - ..faces(metadata("runtime")) - }), - "assemble an adopting surface", - ); - assert_eq!( - capabilities(&adopting), - [ - "spoke-knowledge", - "ke-ownership", - CAPABILITY_SPOKE_KNOWLEDGE_ADOPTION, - CAPABILITY_SPOKE_JUDGMENT, - RECALL_CONTEXT, - ABSORB, - DELIBERATE, - READ_COGNITION - ], - "the adoption face is advertised exactly when it is served" + surface.ports.as_adoption().is_none(), + "no adoption face is composed" ); assert!( - adopting.ports.as_adoption().is_some(), - "the adoption face is composed over the routed store" - ); - expect_ok( - validate_manifest_tools(&adopting.manifest), - "the adopting manifest is self-consistent", + surface.ports.as_memory().is_none(), + "no memory service was attached" ); } -/// The adoption source is one collection for the whole surface; the source need not hold any row. +/// The retired adoption id is the runtime's: a host registration of `tools.mindcore.adopt` is +/// dropped, so it appears in neither `capabilities` nor `tools`. #[tokio::test] -async fn an_adoption_source_assembles() { +async fn a_host_registration_cannot_shadow_the_adoption_tool() { let serve = Fixture::open().await.serve(); let surface = expect_ok( serve.surface(ServeFaces { - adoption: Some(AdoptionRoute { - scope_id: "spc_shared".to_string(), - source: KnowledgeScope::new("shared"), - }), + tools: vec![shadowing_adoption()], ..faces(metadata("runtime")) }), - "assemble an adopting surface", + "assemble a surface a host tries to shadow", ); - assert!(surface.ports.as_knowledge().is_some()); -} - -/// A source naming the collection the knowledge face serves would copy the destination into -/// itself, so assembly refuses it. -#[tokio::test] -async fn an_adoption_source_in_the_knowledge_faces_collection_is_refused() { - let serve = Fixture::open().await.serve(); - let reject = match serve.surface(ServeFaces { - adoption: Some(AdoptionRoute { - scope_id: "spc_shared".to_string(), - source: KnowledgeScope::new(COLLECTION), - }), - ..faces(metadata("runtime")) - }) { - SpokeResult::Reject(reject) => reject, - SpokeResult::Ok(surface) => panic!( - "the served collection became the adoption source {:?}", - capabilities(&surface) - ), - }; - assert_eq!(reject.code, SpokeRejectCode::InvalidInput); - assert_eq!( - reject.message, - "the adoption source collection is the collection the knowledge face serves" + assert!( + !capabilities(&surface).contains(&RETIRED_ADOPT), + "a host registration supplied the retired id: {:?}", + capabilities(&surface) ); - assert!(reject.details.is_none(), "{reject:?}"); -} - -/// A source scope equal to the destination scope would let a principal adopt from its own -/// destination, so assembly refuses it. -#[tokio::test] -async fn an_adoption_source_equal_to_the_destination_scope_is_refused() { - let serve = Fixture::open().await.serve(); - let reject = match serve.surface(ServeFaces { - adoption: Some(AdoptionRoute { - scope_id: SCOPE_ID.to_string(), - source: KnowledgeScope::new("shared"), - }), - ..faces(metadata("runtime")) - }) { - SpokeResult::Reject(reject) => reject, - SpokeResult::Ok(surface) => { - panic!( - "a source scope equal to the destination assembled {:?}", - capabilities(&surface) - ) - } - }; - assert_eq!(reject.code, SpokeRejectCode::InvalidInput); - assert_eq!( - reject.message, - "the adoption source scope is the destination scope" + assert!( + surface + .manifest + .tools + .iter() + .all(|tool| tool.capability_id.as_str() != RETIRED_ADOPT), + "the host's retired adoption descriptor is not advertised" ); - assert!(reject.details.is_none(), "{reject:?}"); -} - -/// An empty source collection or an empty source scope id names no source, so assembly refuses it. -#[tokio::test] -async fn an_empty_adoption_source_is_refused_at_assembly() { - let serve = Fixture::open().await.serve(); - for route in [ - AdoptionRoute { - scope_id: "spc_shared".to_string(), - source: KnowledgeScope::new(""), - }, - AdoptionRoute { - scope_id: String::new(), - source: KnowledgeScope::new("shared"), - }, - ] { - let reject = match serve.surface(ServeFaces { - adoption: Some(route), - ..faces(metadata("runtime")) - }) { - SpokeResult::Reject(reject) => reject, - SpokeResult::Ok(surface) => { - panic!( - "an empty adoption source assembled {:?}", - capabilities(&surface) - ) - } - }; - assert_eq!(reject.code, SpokeRejectCode::InvalidInput); - assert!(reject.details.is_none(), "{reject:?}"); - } -} - -/// The retired adoption id is the runtime's: a host registration of `tools.mindcore.adopt` is -/// dropped, so it appears in neither `capabilities` nor `tools` — with or without a configured -/// adoption source, which serves nothing until the protocol face arrives. -#[tokio::test] -async fn a_host_registration_cannot_shadow_the_adoption_tool() { - let serve = Fixture::open().await.serve(); - - let adopted = || { - Some(AdoptionRoute { - scope_id: "spc_shared".to_string(), - source: KnowledgeScope::new("shared"), - }) - }; - for (context, adoption) in [ - ("without a configured adoption source", None), - ("with a configured adoption source", adopted()), - ] { - let surface = expect_ok( - serve.surface(ServeFaces { - adoption, - tools: vec![shadowing_adoption()], - ..faces(metadata("runtime")) - }), - "assemble a surface a host tries to shadow", - ); - - assert!( - !capabilities(&surface).contains(&RETIRED_ADOPT), - "a host registration supplied the retired id {context}: {:?}", - capabilities(&surface) - ); - assert!( - surface - .manifest - .tools - .iter() - .all(|tool| tool.capability_id.as_str() != RETIRED_ADOPT), - "the host's retired adoption descriptor is not advertised {context}" - ); - } } /// A host registration borrowing the retired adoption id: its descriptor would be advertised and @@ -527,8 +288,6 @@ async fn attached_memory_service_is_advertised_and_served() { assert_eq!( capabilities(&surface), [ - "spoke-knowledge", - "ke-ownership", "spoke-memory", CAPABILITY_SPOKE_JUDGMENT, RECALL_CONTEXT, @@ -541,7 +300,7 @@ async fn attached_memory_service_is_advertised_and_served() { surface.ports.as_memory().is_some(), "the host's memory service is served" ); - assert!(surface.ports.as_knowledge().is_some()); + assert!(surface.ports.as_knowledge().is_none()); assert!(surface.ports.as_baseline().is_none()); } @@ -613,8 +372,6 @@ async fn tool_registrations_drive_advertisement_and_installation() { assert_eq!( capabilities(&surface), [ - "spoke-knowledge", - "ke-ownership", CAPABILITY_SPOKE_JUDGMENT, RECALL_CONTEXT, ABSORB, @@ -652,216 +409,3 @@ async fn tool_registrations_drive_advertisement_and_installation() { expect_ok(surface.register(&responder), "install handlers"); responder.close(); } - -/// The admitted scope id must be the one this surface serves, not merely a well-formed selection: -/// a resolver that admits another id is refused on both faces. Without the id check, an adoption -/// whose destination names that foreign id matches the admitted context and writes into the -/// knowledge face's collection, while the knowledge face denies the same peer. -#[tokio::test] -async fn an_admitted_scope_id_outside_the_served_one_is_refused() { - let serve = Fixture::open().await.serve(); - let surface = expect_ok( - serve.surface(ServeFaces { - adoption: Some(adoption_source()), - ..faces(metadata("runtime")) - }), - "assemble an adopting surface", - ); - let face = surface - .ports - .as_knowledge() - .expect("knowledge face composed"); - - let refused = match (face.admission)("peer-elsewhere") { - SpokeResult::Reject(reject) => reject, - SpokeResult::Ok(scope) => panic!("a foreign admitted id reached Connect with {scope:?}"), - }; - assert_eq!(refused.code, SpokeRejectCode::NotAuthorized); - assert_eq!(refused.message, "knowledge scope not authorized"); - assert!(refused.details.is_none(), "{refused:?}"); - - let adoption = surface.ports.as_adoption().expect("adoption face composed"); - let denied = expect_reject( - adoption - .invoke( - "peer-elsewhere", - KNOWLEDGE_OP_ADOPT, - json!({ - "source_scope_id": "spc_shared", - "source_entry_id": "ke_source", - "source_revision": 1, - "destination_scope_id": "spoke-scope-other", - "idempotency_key": "mismatch", - }), - ) - .await, - "adoption under a foreign admitted id", - ); - assert_eq!( - denied.code, - SpokeRejectCode::NotAuthorized, - "the adoption face refuses what the knowledge face denies" - ); -} - -/// The runtime validates the scope the host admits, before Connect merges any request selection. -/// -/// An unsupported host admission is not the peer's input, so it leaves the face as the same -/// generic `NotAuthorized` a rejecting resolver returns; a caller-declared unsupported selection -/// stays `InvalidInput` at the routed store. -#[tokio::test] -async fn admission_is_validated_where_the_face_is_assembled() { - let serve = Fixture::open().await.serve(); - let surface = expect_ok( - serve.surface(faces(metadata("runtime"))), - "assemble surface", - ); - let face = surface - .ports - .as_knowledge() - .expect("knowledge face composed"); - - let admitted = expect_ok((face.admission)("peer-owner"), "admitted peer"); - assert_eq!(admitted.scope_id, SCOPE_ID); - - let refused = match (face.admission)("peer-stranger") { - SpokeResult::Reject(reject) => reject, - SpokeResult::Ok(scope) => panic!("a stranger was admitted with {scope:?}"), - }; - assert_eq!(refused.code, SpokeRejectCode::NotAuthorized); - - let unsupported = match (face.admission)("peer-cognition") { - SpokeResult::Reject(reject) => reject, - SpokeResult::Ok(scope) => panic!("an unsupported selection reached Connect with {scope:?}"), - }; - assert_eq!( - unsupported.code, - SpokeRejectCode::NotAuthorized, - "a host-admitted unsupported selection is a deny, not the caller's input error" - ); - assert!( - unsupported.details.is_none(), - "host admission discloses no target details: {unsupported:?}" - ); - - let declared = match face - .store - .list_scoped_knowledge_entries(&unsupported_scope()) - .await - { - SpokeResult::Reject(reject) => reject, - SpokeResult::Ok(entries) => panic!("a caller-declared selection listed {entries:?}"), - }; - assert_eq!( - declared.code, - SpokeRejectCode::InvalidInput, - "a caller-declared unsupported selection stays the caller's input error" - ); -} - -/// A second admitted principal and the shared source's seed rows: an entry the adoption copies, -/// and the knowledge face's own collection. -fn two_principal_faces(manifest: HostCapabilityManifest) -> ServeFaces { - ServeFaces { - adoption: Some(adoption_source()), - admission: Arc::new(|peer_id: &str| match peer_id { - "peer-owner" => SpokeResult::Ok(scope_of(SCOPE_ID)), - // Admitted with knowledge access but routed to no workflow collection at all. - "peer-second" => SpokeResult::Ok(scope_of(SCOPE_ID)), - _ => spoke_reject( - SpokeRejectCode::NotAuthorized, - format!("peer {peer_id} holds no knowledge admission"), - None, - ), - }), - principals: Arc::new(|peer_id: &str| match peer_id { - "peer-owner" | "peer-second" => SpokeResult::Ok( - serde_json::from_value(json!({ "principal_id": peer_id, "extensions": {} })) - .expect("principal JSON matches the schema"), - ), - _ => spoke_reject( - SpokeRejectCode::NotAuthorized, - format!("peer {peer_id} holds no workflow admission"), - None, - ), - }), - ..faces(manifest) - } -} - -fn adopt_payload(entry_id: &str, key: &str) -> Value { - json!({ - "source_scope_id": "spc_shared", - "source_entry_id": entry_id, - "source_revision": 1, - "destination_scope_id": SCOPE_ID, - "idempotency_key": key, - }) -} - -/// An adopted copy lands in the collection `knowledge.get` serves for the same admitted peer: two -/// principals adopt into that one collection, both copies read back through the knowledge face, and -/// a principal with knowledge admission but no workflow route adopts too. Without this, a copy could -/// be written into a collection no knowledge-face read ever reaches. -#[tokio::test] -async fn an_adopted_copy_is_readable_through_the_knowledge_face_by_its_own_principal() { - let fixture = Fixture::open().await; - let store = ScopedKnowledgeStore::new(fixture.store.pool(), KnowledgeScope::new("shared")); - for entry_id in ["ke_owner", "ke_second"] { - expect_ok( - store - .put_knowledge_entry( - serde_json::from_value(json!({ - "schema_version": 1, - "entry_id": entry_id, - "entry_type": "note", - "canonical_name": format!("{entry_id} source"), - "status": "confirmed", - "body": { "summary": format!("{entry_id} summary") }, - "extensions": {}, - })) - .expect("entry JSON matches the schema"), - None, - ) - .await, - "seed the shared source", - ); - } - let surface = expect_ok( - fixture - .serve() - .surface(two_principal_faces(metadata("runtime"))), - "assemble a two-principal adopting surface", - ); - let adoption = surface.ports.as_adoption().expect("adoption face composed"); - let face = surface - .ports - .as_knowledge() - .expect("knowledge face composed"); - let admitted = scope_of(SCOPE_ID); - - for (peer, entry_id) in [("peer-owner", "ke_owner"), ("peer-second", "ke_second")] { - let adopted = expect_ok( - adoption - .invoke(peer, KNOWLEDGE_OP_ADOPT, adopt_payload(entry_id, peer)) - .await, - "adopt", - ); - assert_eq!(adopted["outcome"], "adopted", "{adopted}"); - - let read = expect_ok( - face.store - .get_scoped_knowledge_entry(&admitted, entry_id) - .await, - "read the copy back through the knowledge face", - ); - assert_eq!(read.entry_id, entry_id, "{read:?}"); - assert_eq!( - read.adoption_anchor - .as_ref() - .map(|anchor| anchor.source_scope_id.as_str()), - Some("spc_shared"), - "the knowledge face serves the adopted copy: {read:?}" - ); - } -} From 169835aad67d60764663598862186806cbd94ab5 Mon Sep 17 00:00:00 2001 From: Tang Bohao Date: Thu, 26 Nov 2026 14:24:26 +0800 Subject: [PATCH 12/27] docs(serving): carry the removed faces' guarantees into the Stage 2 handoff - serving-seam.md states Stage 1 composes no history or adoption face and that both ops answer CAPABILITY_PORT_MISSING. - The history section records that Stage 2 must re-implement the durable dedup namespace (`history_dedup`'s `(namespace, key)` rows, claim-before-prune, per-principal 4096 bound); the retained `HistoryPort` carries no retry record. - The adoption section records that Stage 2 must re-implement the single `BEGIN IMMEDIATE` transaction that covered the scope checks, terminal resolution, destination read, create-only write and typed response; `mindcore-sqlite` implements no `AdoptionPort`. - Where-it-lives and the history invariant now name the removed modules and the retained ports. --- .agents/specs/architecture/serving-seam.md | 40 +++++++++++++++------- 1 file changed, 28 insertions(+), 12 deletions(-) diff --git a/.agents/specs/architecture/serving-seam.md b/.agents/specs/architecture/serving-seam.md index 871c72db..4aba0856 100644 --- a/.agents/specs/architecture/serving-seam.md +++ b/.agents/specs/architecture/serving-seam.md @@ -25,7 +25,9 @@ The peer's route grants read/write knowledge access within its scope, not uncons ### History -The `spoke-history` family publishes two operations over the same signed session: `history.revisions.get` returns a `RevisionSnapshot`, `history.revisions.prune` returns `HistoryPruneResult { deleted, floor_revision }` where `floor_revision` is the local report's floor. The host enables both with `ServeFaces.history`: `false` composes no history service and advertises no `spoke-history`, the composed surface adds it to `RemoteServePortsComposite::knowledge_only(face).with_history(service)`, and `face_capabilities` advertises the family from that one flag. +The `spoke-history` family publishes two operations over the same signed session: `history.revisions.get` returns a `RevisionSnapshot`, `history.revisions.prune` returns `HistoryPruneResult { deleted, floor_revision }` where `floor_revision` is the local report's floor. + +Stage 1 composes no history face: `ServeFaces` carries no history switch, `face_capabilities` advertises no `spoke-history`, and both operations answer `CAPABILITY_PORT_MISSING` on the responder's dispatch-deny branch. The paragraphs below state the contract a restored face must satisfy, and the Stage 2 handoff at the end of this section names what it must re-implement rather than re-bind. One store fills two port roles: `RoutedKnowledgeStore` implements `spoke_operations::HistoryPort` beside `ScopedKnowledgePort`, so no second store module exists and the runtime owns no second history implementation — only the dedup record beside it. Admission is the knowledge face's, composed as `HistoryAdmission = (principals(peer)?, knowledge_admission(peer)?)`: a peer outside either callback gets that callback's refusal, and can therefore replay and prune exactly the scope it reads and writes through `port.knowledge.*`. Connect compares a present request `scope` with the admitted scope before calling the port — `NOT_FOUND` on get, `NOT_AUTHORIZED` on prune — and the port re-applies `RoutedKnowledgeStore::admit` as its own guard. @@ -76,6 +78,8 @@ So the answer is not a case distinction a caller can act on, and a caller must n Adoption keeps the released in-memory default and its own restart exposure. Adoption has no equivalent permanent-loss replay path, but it is not a guaranteed no-write repeat either. While the source still resolves to the terminal the first call copied and the destination already holds the copy, the create-only CAS and the anchor rules make the retry answer `already_present` or `REVISION_CONFLICT` and write nothing. After a reassembly dropped the record, a source since retired to a different terminal resolves the same request to that new terminal; with `destination_entry_id` omitted the copy is then addressed by the new terminal's id, so the retry writes a second copy. The original copy stays intact and nothing is lost — the repeat is simply not guaranteed to write nothing once the terminal changed and no destination id was supplied. +**Stage 2 handoff: the durable dedup is not in the retained port.** `crates/mindcore-sqlite`'s `RoutedKnowledgeStore` still implements `spoke_operations::HistoryPort` — replay and prune over the routed collection — but that port carries no retry record. The claim-before-prune and recorded-outcome store lived in `crates/mindcore-runtime/src/history_dedup.rs` (`SqliteHistoryDedupStore`, composed through `spoke-connect`'s `HistoryPortService::with_dedup_store` over the store's own pool) and was removed with the face. Stage 2 must re-implement that durable dedup namespace — one row per `(namespace, key)`, `key` being Connect's canonical `[op, effective_scope, principal_id, idempotency_key]` retry identity and the namespace the collection the surface routes to, with the principal stored beside the key for the quota, claimed before the port runs and settled with the request digest and the outcome after it, each `(namespace, principal)` holding at most 4096 rows and nothing ever deleted — before it serves prune again. Re-enabling prune over the retained port with Connect's in-memory default instead would let a same-key retry after a restart re-run a destructive prune the first request may already have performed. Records already persisted by the removed store must stay readable: its composite key is `(namespace, key)` with the collection name as the namespace, not a framed string, so a Stage 2 store must keep that column pair rather than re-derive the namespace. + ### Workflow tools `MindcoreServe` derives served capability ids and tool descriptors from installed faces and handlers; the host supplies identity, transport, allowed peers and non-capability manifest metadata. Compose Memory and Knowledge with `RemoteServePortsComposite::knowledge_only(face).with_memory(service)`, and the history family with `.with_history(service)` on that same composite. The Memory service consumes a trusted peer-to-principal mapping and implements the advertised family contract; the runtime does not create fake baseline, reflection or transfer providers. For each accepted transport, register handlers before releasing inbound traffic; `connect_responder` starts its own SPOKE receive task and does not install handlers from the manifest. @@ -121,16 +125,15 @@ rather than kept as a second authority: assembly drops its reserved `tools.mindc host registration in both adoption configurations (`crates/mindcore-runtime/src/lib.rs:165`), so no manifest carries it and no handler answers it even when a host registers the id. -The host enables the face with `ServeFaces.adoption: Option`, whose `scope_id` names -the configured source on the wire and whose `source` names the `KnowledgeScope` the store reads -(`crates/mindcore-runtime/src/lib.rs:247-257,288-296`). There is no destination setting: the -destination is `ServeFaces.knowledge`, the one collection `knowledge.get`/`list` serve for the +Stage 1 composes no adoption face: `ServeFaces` has no adoption setting, `face_capabilities` names +neither `spoke-knowledge-adoption` nor its `spoke-knowledge` co-capability, and a `knowledge.adopt` +call answers `CAPABILITY_PORT_MISSING`. The paragraphs below state the contract a restored face must +satisfy. A restored face takes the one host-configured source as an `AdoptionRoute` — a `scope_id` +naming it on the wire and the `KnowledgeScope` the store reads — and no destination setting: the +destination is the knowledge face's own collection, the one `knowledge.get`/`list` serve for the admitted peer, so a copy is readable back through that face whenever the peer's admitted selection -admits it. `workflow_routes` selects workflow collections only and plays no part in adoption. With -`adoption: None` `face_capabilities` adds no capability and no service is composed; with `Some` it -adds `spoke-knowledge-adoption` and `RemoteServePortsComposite::with_adoption` composes -`spoke-connect`'s `AdoptionPortService` over the runtime's `AdoptionService` -(`crates/mindcore-runtime/src/lib.rs:191-214,406-434`). +admits it. `workflow_routes` selects workflow collections only and plays no part in adoption. The +Stage 2 handoff at the end of this section names what it must re-implement rather than re-bind. **Admission is the knowledge face's**, composed as `(principals(peer)?, knowledge_admission(peer)?)` like the history family's: a peer the knowledge face does not admit cannot adopt, and a routed @@ -250,6 +253,19 @@ before hello using its own trusted routing, verifies the selected peer against t session, and re-evaluates actual admission at call time. The runtime serves one manifest and one handler set per surface and exposes no per-principal manifest or handler set. +**Stage 2 handoff: the single transaction is not in the retained ports.** `crates/mindcore-sqlite` +implements `ScopedKnowledgePort` and `HistoryPort` but no `spoke_operations::AdoptionPort`, and the +operation's body — the scope checks, the retirement-chain resolution, the destination read, the +create-only write, the anchor and inherited-governance rules and the typed response — lived in the +removed `crates/mindcore-runtime/src/adoption.rs` (`AdoptionService`). Its one `BEGIN IMMEDIATE` +transaction covered all of that and committed only for `adopted`, rolling back for `already_present` +and for every refusal, so no caller could observe a source read without its destination write and a +refused response left no copy. Stage 2 must re-implement that single transaction before composing +any per-Mind adoption face: a body assembled from separate port calls cannot carry it, because the +destination read and the create-only write would no longer share the source read's snapshot or its +rollback. Connect's `AdoptionPortService` dedup envelope is unchanged by this — it never carried the +transactional guarantee. + ### Store shape The runtime serves a **protocol-shaped** store: the memory tables the workflows read are the Nexus protocol shape, not the pre-release legacy shape. `MindStore::open` applies the one embedded migration, so a freshly opened store already carries that shape and serves `recall_context` and `deliberate`; the loopback fixture opens that same production path and only seeds the rows the faces read, so it is no longer the only protocol-shaped store. Nexus host-only objects — the writer guards, outbox/immutability triggers, `nexus_writer_*` UDFs and the `core_*` tables — stay absent, so `open` needs no writer runtime. This plan's acceptance is therefore runtime reachability of the served tools against a store the production open path produced. @@ -262,14 +278,14 @@ The runtime serves a **protocol-shaped** store: the memory tables the workflows - Adoption's answer reports `destination_entry_id` slot occupancy — occupied or free — and nothing about the occupant: a concealed occupant is byte-identical to a visible one. That disclosure is permitted and no wider than the knowledge face it lands on, whose create-only `put_knowledge_entry` already distinguishes occupied from free while hiding the entry; entry content, revision and visibility stay undisclosed. - Ablation: peer admission plus scoped storage are both required. Connect authenticates the peer and bounds the list request; the store applies the admitted collection and entry rules before reading, revealing or mutating data. - An admitted scope is validated where the face is assembled and again in the store: neither Connect's list merge nor a caller-declared scope may drop or bypass an admitted constraint. -- History grants no access the knowledge face does not: both `history.*` ops admit through the knowledge face's two callbacks and the routed store's own `admit`, so a peer replays and prunes exactly the scope it reads and writes. The `spoke-history` capability is advertised only when `ServeFaces.history` composes the service. +- History grants no access the knowledge face does not: both `history.*` ops admit through the knowledge face's two callbacks and the routed store's own `admit`, so a peer replays and prunes exactly the scope it reads and writes. Stage 1 composes no history face, so `face_capabilities` names no `spoke-history` and both ops answer `CAPABILITY_PORT_MISSING`. - Every served `deliberate` response carries the judgment its own attempt produced, and every judgment it carries passed the released validator before the call returned; the identity rule [`mind-model.md`](mind-model.md) states holds on the wire, and `spoke-judgment` is advertised exactly with the tool. ## Where it lives - SQLite scoped store beside `crates/mindcore-sqlite/src/knowledge.rs` and its borrowed-transaction helpers; used both by the Knowledge loopback and by `crates/mindcore-runtime`. The same file implements `HistoryPort` for `RoutedKnowledgeStore` and projects the replay onto `RevisionSnapshot`. - `crates/mindcore-spoke/src/workflows.rs` owns workflow storage admission and the settlement transaction; `crates/mindcore-spi` owns the workflow contracts and their orchestration. -- `crates/mindcore-runtime/src/lib.rs` owns `ServeFaces` (including `history` and `adoption`), `AdoptionRoute`, the `HistoryAdmission` and `AdoptionAdmission` compositions, the retired-id filter and `face_capabilities`, and it composes both services: `HistoryPortService::with_dedup_store` over `history_dedup.rs`'s `SqliteHistoryDedupStore`, and `AdoptionPortService::new`, which keeps the in-memory dedup default; `spoke-connect`'s `HistoryPortService` and `AdoptionPortService` own the wire decode, the effective-scope check and their dedup seams; `crates/mindcore-runtime/src/history_dedup.rs` owns the served history's durable store over the store's own pool; `crates/mindcore-runtime/src/adoption.rs` owns the adoption port, `AdoptionService`. `crates/mindcore-runtime/src/tools.rs` owns the served workflow tool registrations and their advertised ABI. `crates/mindcore-runtime/tests/loopback.rs` asserts each advertisement against a signed session, including both history ops, the prune replay across a reopened file and `knowledge.adopt`. +- `crates/mindcore-runtime/src/lib.rs` owns `ServeFaces` (manifest metadata, the memory service, the peer-to-principal admission, providers and host tools), the runtime's `MindPorts`, the retired-id filter and `face_capabilities`; Stage 1 composes no knowledge, history or adoption face, so the former `crates/mindcore-runtime/src/history_dedup.rs` (`SqliteHistoryDedupStore`) and `crates/mindcore-runtime/src/adoption.rs` (`AdoptionService`) are removed and a restored face must re-implement them (the two Stage 2 handoff paragraphs above). `spoke-connect`'s `HistoryPortService` and `AdoptionPortService` keep their wire decode, effective-scope check and dedup seams, unused until a face is composed again; `crates/mindcore-runtime/src/tools.rs` owns the served workflow tool registrations and their advertised ABI. `crates/mindcore-runtime/tests/loopback.rs` asserts each advertisement against a signed session, including the three removed families' `CAPABILITY_PORT_MISSING` denial; `crates/mindcore-runtime/tests/surface.rs` asserts their absence from the composed ports and the manifest. ## Change obligations From a190c22f69ba06562750f3d6ece2b494f6435171 Mon Sep 17 00:00:00 2001 From: Tang Bohao Date: Thu, 26 Nov 2026 14:32:22 +0800 Subject: [PATCH 13/27] docs(serving): state the Mind as the route input and promote the record - The signed loopback gains the frozen-Mind case: a granted caller is served its recall and the cognition read, a freeze-gated capture outside the allowlist answers SpaceFrozen and stages nothing. - serving-principal-routing.md states the request's Mind id as the only route input and the registry row as the resolution, loses the retired principal route map, and documents port.knowledge.*, history.* and knowledge.adopt as un-routed in Stage 1. - serving-seam.md drops the route map and the deliberate holder member, adds the read_cognition row and states the Stage 1 composition; its adoption handoff separates the pre-transaction request checks from the single transaction. - mind-model.md gains the served route-input rule and loses the removed history_dedup module. - docs/concepts.md states admission before any existence check, and the adapter test states the same rule. - 2026-11-25-one-surface-serves-many-minds.md is promoted to implemented/ with the reverse Superseded-by note on 2026-11-21-principal-routing.md; the stale knowledge page is recorded there. --- .../2026-11-21-principal-routing.md | 2 + ...026-11-25-one-surface-serves-many-minds.md | 65 +++++ ...026-11-25-one-surface-serves-many-minds.md | 73 ------ .agents/specs/architecture/mind-model.md | 3 +- .../architecture/serving-principal-routing.md | 235 +++++++++--------- .agents/specs/architecture/serving-seam.md | 58 +++-- crates/mindcore-runtime/tests/loopback.rs | 80 ++++++ crates/mindcore-spoke/tests/memory_adapter.rs | 11 +- docs/concepts.md | 12 +- 9 files changed, 312 insertions(+), 227 deletions(-) create mode 100644 .agents/adr/implemented/architecture/2026-11-25-one-surface-serves-many-minds.md delete mode 100644 .agents/adr/proposed/architecture/2026-11-25-one-surface-serves-many-minds.md diff --git a/.agents/adr/implemented/architecture/2026-11-21-principal-routing.md b/.agents/adr/implemented/architecture/2026-11-21-principal-routing.md index ee8c3b91..4c1b59fe 100644 --- a/.agents/adr/implemented/architecture/2026-11-21-principal-routing.md +++ b/.agents/adr/implemented/architecture/2026-11-21-principal-routing.md @@ -5,6 +5,8 @@ Date: 2026-11-21 Class: architecture Related: `2026-11-21-spoke-017-serving-cohort.md` +> **Superseded-by (2026-11-25, `2026-11-25-one-surface-serves-many-minds.md`):** the route map is gone. A served call names its Mind through the `space_id` it already carries, and the Mind's registry row resolves the collection and carrier; `ServeFaces.workflow_routes`, `MemoryWorkflowBinding::with_knowledge_routes` and `knowledge_route` were removed rather than kept beside the row. The rules this record states that outlive the map hold per Mind: the wire never names a collection, a refusal carries no target details, and a route never substitutes for a live grant. + ## Problem A serving surface may serve more than one principal, and the two routed workflows each need exactly one knowledge collection per call: `deliberate` settles onto one carrier entry, and `recall_context` fills one knowledge slot. Binding the surface to a single caller principal made a multi-principal host assemble one surface per principal, and each surface would have to duplicate its responder, tool registration and accept-loop configuration. diff --git a/.agents/adr/implemented/architecture/2026-11-25-one-surface-serves-many-minds.md b/.agents/adr/implemented/architecture/2026-11-25-one-surface-serves-many-minds.md new file mode 100644 index 00000000..a741cced --- /dev/null +++ b/.agents/adr/implemented/architecture/2026-11-25-one-surface-serves-many-minds.md @@ -0,0 +1,65 @@ +# ADR: One served surface serves many Minds + +Status: implemented — Stage 1 serves many Minds from one surface, each call reached by its Mind id and admitted before any existence check; the three operations that cannot yet name a Mind stay un-routed until Stage 2 +Date: 2026-11-25 +Class: architecture +Supersedes: `2026-11-21-principal-routing.md` — its principal-keyed route map is removed +Related: `2026-11-21-spoke-017-serving-cohort.md`, `2026-11-25-mind-is-one-memory-space.md`, `.agents/specs/architecture/serving-principal-routing.md`, `.agents/specs/architecture/serving-seam.md` + +## Problem + +A served surface is assembled around one knowledge collection. `ServeFaces.scope_id` was "the one configured route", `ServeFaces.knowledge` was "the collection that route serves", and `ServeFaces.admission` mapped each peer to one scope. `port.knowledge.get`, `port.knowledge.put` and the list operation read and wrote that collection for every admitted peer, `history.*` served the same store, and `knowledge.adopt` wrote it. The two routed workflows reached a collection through `ServeFaces.workflow_routes`, a host-configured map from principal id to collection that was fixed for the surface's lifetime. + +So one process could not let a peer operate several Minds or list them: a host that wanted more than one Mind assembled one surface per Mind. A peer had no wire value that named a Mind; the workflow tools named memory coordinates, and every `deliberate` named its carrier by `holder`. And because reach was host configuration, a Mind created after assembly was unreachable until the surface was rebuilt. + +## Decision + +One served surface serves many Minds, reached by Mind id, in two stages with a recorded fallback. The owner settled the shape on 2026-11-25 and stated that SPOKE 0.19.0 will carry the three SPOKE-side items the second stage needs. + +The Mind id rides the selectors SPOKE requests already carry: `space_id` on a memory request and `scope_id` on a knowledge `Scope`. A Mind's id is its space id (`2026-11-25-mind-is-one-memory-space.md`), so no new wire member is needed. + +**Resolution and admission.** The wire never names a collection. For each call Mindcore resolves the Mind id in the registry row — one lookup to a collection and a carrier — admits the (principal, Mind) pair, and only then binds the collection to a port. + +- Memory: a live grant covering the operation, in that space. +- Workflow tools, each where it reaches the adapter (`crates/mindcore-spoke/src/workflows.rs`): `recall_context` checks `recall`, and `knowledge_read` only to fill its knowledge slot. `absorb` checks `capture`, `review` to read the candidate and `recall` for its page, then `review` with `records_write` on one grant to review, `records_write` to update and `review` to dismiss. `deliberate` checks `recall` over a `subject_all` page, `knowledge_read` and `knowledge_write`. + +**Refuse, do not filter.** Kept (`docs/concepts.md`). Each call admits one Mind, and the handler binds a port to the resolved collection, so no result mixes two Minds. Mind admission precedes every existence check: an unknown Mind id and a Mind the peer holds no grant for answer one `NOT_AUTHORIZED`, with no `details`, before any subject, entry or carrier is read (`crates/mindcore-spoke/src/admission.rs`, `admit_mind`). + +**A frozen Mind.** A Mind that is not active is frozen (`2026-11-25-mind-is-one-memory-space.md`), and it answers by SPOKE's freeze semantics: a caller without a grant in its space is refused as an unknown Mind is, because the grant check comes before the freeze check. A caller with a grant reads. `gate` answers `SpaceFrozen` only to an operation that is freeze-gated and outside the maintenance allowlist, which SPOKE defines, and serves the operations that are not freeze-gated. + +**Stage 1, no SPOKE change.** Stage 1 exposes Mind-level convenience operations only and composes none of the operations that are not Mind-routed: until each of `port.knowledge.*`, `history.*` and `knowledge.adopt` is served per Mind, the surface does not compose it, because every operation is to hang off the Mind entity (owner, 2026-11-25). + +- `memory.spaces.list` lists Minds: the registry's join over the caller's live grants, not every space. +- The memory family and the workflow tools name a Mind through the `space_id` they already carry; no member is added and none is renamed. +- The workflow tools' one argument change is that `deliberate` loses `holder`, because the Mind's record names the carrier. The facade's `deliberate` takes no `subject_id` (owner, 2026-11-25); the served tool keeps its `subject_id`, its subject-level recall and its unsettled-intent check. +- A new `tools.mindcore.read_cognition` takes `space_id`, as the memory operations do, and returns that Mind's current judgment and derived `MindState`. +- One `NOT_AUTHORIZED` answers an unknown or unadmitted Mind before any existence check, a frozen Mind included. + +**Stage 2, three SPOKE-side items.** A1 is request-scoped admission: the admission callback receives the `scope_id` a request declares. It is additive and source-compatible. A2 is an optional `scope` on `port.knowledge.get` and `port.knowledge.put`, with a negotiable marker saying the responder honours it; it is a wire change, so a new SPOKE cohort. A3 is `memory.spaces.create`, the operation a SPOKE peer creates a Mind through. A1 and A2 turn on knowledge, history and adoption per Mind; A3 turns on a peer's creation of a Mind. SPOKE 0.19.0 will carry A1, A2 and A3, and the caller names the `space_id` (owner, 2026-11-25). + +**Creating a Mind.** A library caller creates a Mind through `create`, `list` and `get` in `crates/mindcore-runtime`, which need no SPOKE change and are built; the facade (`2026-11-25-three-delivery-forms.md`) builds on them. A SPOKE peer creates one through `memory.spaces.create`, which is A3 of Stage 2. On a Mindcore host both run the same create and write the default grant set (`2026-11-25-create-default-grant-set.md`). Until this repository pins that cohort, a peer operates only Minds created through the library. + +**The fallback.** Design T is the fallback: every Mind-scoped operation is a `tools.mindcore.*` tool whose argument object starts with `mind_id`, with no SPOKE change. SPOKE and Mindcore have the same owner, so whether the fallback is taken is the owner's direct decision, and it needs no trigger. `mind_id` is there a tool argument of Design T's own, not a renamed SPOKE member: every operation becomes a new tool, and the argument object is that tool's to define. + +**Records and pages this changes.** `ServeFaces.workflow_routes` is replaced by the registry's Mind-to-collection row, which retires the route `2026-11-21-principal-routing.md` records. Its rules that outlive the map hold per Mind: the wire never names a collection, a refusal carries no target details, and a route never substitutes for a live grant. `.agents/specs/architecture/serving-principal-routing.md` gains the request's Mind id as the route input and loses the map, and the knowledge page `.agents/knowledge/architecture-patterns/serving-principal-routing.md` describes that map and goes stale with it. `.agents/specs/architecture/serving-seam.md` changes the tool argument table — the `deliberate` row loses `holder`, the `read_cognition` row is added — and records the composition Stage 1 ships. + +**Evidence.** `.agents/specs/architecture/serving-{principal-routing,seam}.md` state the routing and the served ABI; `crates/mindcore-runtime/tests/loopback.rs` runs the signed two-Mind/two-peer loopback, the unadmitted-equals-absent refusal and the frozen cases; `crates/mindcore-spoke/tests/memory_adapter.rs` pins the admission-first refusal across every Mind-level read path and the registry-derived `memory.spaces.list`. + +## Alternatives considered + +- **Design T: every Mind-scoped operation a `tools.mindcore.*` tool, no SPOKE change.** Rejected as the primary route and kept as the fallback. It restates `port.knowledge.*`, `history.*` and `knowledge.adopt` as six product tools, which is a second operation surface inside the tool namespace and reverses the migration that replaced `tools.mindcore.adopt` with `knowledge.adopt` (`.agents/specs/architecture/serving-seam.md`). The surface would still carry the per-peer `port.knowledge.*` path beside those tools, and a tool's arguments pass outside SPOKE's scope and cognition gates. The chosen route rides selectors SPOKE already has and keeps the peer on standard operations. +- **One responder per Mind, no SPOKE change.** Rejected: it is not one surface serving many Minds. Each Mind gets its own surface, manifest, handler set and one signed session per peer, a peer has no way to list Minds, and the hello manifest repeats for every (peer, Mind) pair. Whether an unadmitted Mind's address differs from an unknown one is left to the host's transport. +- **One collection, with Minds separated per entry, no SPOKE change.** Rejected: SPOKE's scope predicate has no entry-ownership term and an admitted scope is fixed per peer, so two peers could not be held to different Minds. It also gives up the one-collection-per-Mind binding of `2026-11-25-mind-is-one-memory-space.md`. +- **Ship no peer form until the SPOKE-side items exist.** Rejected: it ties a first release to a SPOKE release Mindcore does not control. Stage 1 needs no SPOKE change and gives a peer per-Mind memory and cognition; what it costs is that a peer gets no `port.knowledge.*`, `history.*` or `knowledge.adopt` until Stage 2, because a many-Mind surface composes none of them until each is served per Mind. The one collection per peer those operations answer from today is the state this decision replaces, not what Stage 1 ships. The third round's release timing makes a release without the peer capabilities impossible until SPOKE 0.19.0; that is a release decision and does not adopt this alternative. + +## Consequences + +- **Stage 1 ships per-Mind memory and cognition only.** `port.knowledge.*`, `history.*` and `knowledge.adopt` are composed only once each is served per Mind, which A1 and A2 turn on. Today they answer from a surface's one collection, which no Mind owns; that is the state Stage 2 replaces and is not carried into a many-Mind surface. No release ships Stage 1 alone: the first Mind-centric release follows SPOKE 0.19.0 and ships Stage 1 and Stage 2 as one minor (owner, 2026-11-25). +- **The argument change breaks existing `deliberate` callers.** `holder` was a required member of the old arguments and the argument object is closed, so a peer built on the old `deliberate` fails after the change. `recall_context` and `absorb` arguments do not change. It is a Mindcore release change, not a SPOKE one. +- **A2 without its marker misroutes silently.** A responder that ignores the new `scope` drops it, and the read lands in the peer's default collection. The marker is part of the ask and is not optional for Mindcore. +- **Admission stays synchronous and bounded.** The registry lookup behind a Mind admission runs under the responder's serve budget and must fit inside it. +- **Closing the existence gap changed answers tests pinned.** The memory path answered `NOT_FOUND` for an unknown space; every Mind-level read path now answers the one admission refusal, and the adapter and loopback assertions changed with it. +- **Settled: a many-Mind surface composes none of the operations that are not Mind-routed.** Until each of `port.knowledge.*`, `history.*` and `knowledge.adopt` is served per Mind, the surface does not compose it, because every operation is to hang off the Mind entity (owner, 2026-11-25). +- **Undecided: the grant rule for a knowledge put that carries cognition records.** `port.knowledge.put` appends `modules.cognition.records` on the admitted scope alone (`crates/mindcore-sqlite/src/knowledge.rs`), where `deliberate` requires `knowledge_write`. The asymmetry exists today, and routing knowledge per Mind would carry it to every admitted Mind. The rule is settled before knowledge is routed per Mind. +- **A3 is not in the pinned SPOKE cohort yet.** `memory.spaces.create` does not exist in 0.18.1, and SPOKE 0.19.0 will carry it (owner, 2026-11-25). Until this repository pins that cohort, a peer can operate Minds and cannot create one. On a Mindcore host the operation runs the same create as the library, `mindcore_sqlite::minds::create`, which borrows the caller's transaction. +- **Design T, if taken, costs more than Stage 2**: eight new tools, six of which restate standard operations, and a second knowledge path on the surface. diff --git a/.agents/adr/proposed/architecture/2026-11-25-one-surface-serves-many-minds.md b/.agents/adr/proposed/architecture/2026-11-25-one-surface-serves-many-minds.md deleted file mode 100644 index a5bf9d34..00000000 --- a/.agents/adr/proposed/architecture/2026-11-25-one-surface-serves-many-minds.md +++ /dev/null @@ -1,73 +0,0 @@ -# ADR: One served surface serves many Minds - -Status: proposed — one served surface serves many Minds, reached by Mind id, in two stages with a recorded fallback; the owner settled it on 2026-11-25 and stated that SPOKE 0.19.0 will carry the three SPOKE-side items the second stage needs; the surface still serves one collection -Date: 2026-11-25 -Class: architecture -Supersedes: `2026-11-21-principal-routing.md` — its principal-keyed route map, once this is implemented -Related: `2026-11-21-spoke-017-serving-cohort.md`, `2026-11-25-mind-is-one-memory-space.md`, `.agents/specs/architecture/serving-principal-routing.md`, `.agents/specs/architecture/serving-seam.md` - -## Problem - -A served surface is assembled around one knowledge collection. `ServeFaces.scope_id` is "the one configured route", `ServeFaces.knowledge` is "the collection that route serves", and `ServeFaces.admission` maps each peer to one scope (`crates/mindcore-runtime/src/lib.rs`). `port.knowledge.get`, `port.knowledge.put` and the list operation read and write that collection for every admitted peer, `history.*` serves the same store, and `knowledge.adopt` writes it. The two routed workflows reach a collection through `ServeFaces.workflow_routes`, a host-configured map from principal id to collection that is fixed for the surface's lifetime (`.agents/specs/architecture/serving-principal-routing.md`). - -So one process cannot let a peer operate several Minds or list them: a host that wants more than one Mind assembles one surface per Mind. A peer has no wire value that names a Mind; the workflow tools name memory coordinates, and every `deliberate` names its carrier by `holder` (`crates/mindcore-runtime/src/tools.rs`). And because reach is host configuration, a Mind created after assembly is unreachable until the surface is rebuilt. - -## Proposal - -One served surface serves many Minds, reached by Mind id. This design was proposed to SPOKE for evaluation (`https://github.com/42ch-dev/spoke/issues/222`); the owner stated on 2026-11-25 that SPOKE settled it, that SPOKE 0.19.0 will carry A1, A2 and A3, and that the caller names the `space_id`. Whether the fallback named below is taken remains the owner's direct decision. - -The Mind id rides the selectors SPOKE requests already carry: `space_id` on a memory request and `scope_id` on a knowledge `Scope`. A Mind's id is its space id (`2026-11-25-mind-is-one-memory-space.md`), so no new wire member is needed. - -**Resolution and admission.** The wire never names a collection. For each call Mindcore resolves the Mind id in one registry lookup to a space, a collection and a carrier, admits the (principal, Mind) pair, and only then binds the collection to a port. - -- Memory: a live grant covering the operation, in that space. This is today's rule. -- Knowledge, history and adoption: a live `knowledge_read` or `knowledge_write` grant in the Mind's space, answered as that Mind's admitted `Scope`. -- Workflow tools, each where it reaches the adapter (`crates/mindcore-spoke/src/workflows.rs`): `recall_context` checks `recall`, and `knowledge_read` only to fill its knowledge slot. `absorb` checks `capture`, `review` to read the candidate and `recall` for its page, then `review` with `records_write` on one grant to review, `records_write` to update and `review` to dismiss. `deliberate` checks `recall` over a `subject_all` page, `knowledge_read` and `knowledge_write`. - -**Refuse, do not filter.** Kept (`docs/concepts.md`). Each call admits one Mind, and the handler binds a port to the resolved collection, so no result mixes two Minds. Mind admission precedes every existence check: an unknown Mind id and a Mind the peer holds no grant for answer one `NOT_AUTHORIZED`, with no `details`, before any subject, entry or carrier is read. Today the memory path answers `NOT_FOUND` for an unknown space and `NOT_AUTHORIZED` for an ungranted one (`crates/mindcore-spoke/src/admission.rs`, `space` and `refuse_coverage`), which lets a peer tell whether a Mind exists. - -**A frozen Mind.** A Mind that is not active is frozen (`2026-11-25-mind-is-one-memory-space.md`), and it answers by SPOKE's freeze semantics as the adapter applies them. A caller without a grant in its space is refused as an unknown Mind is, because the grant check comes before the freeze check (`crates/mindcore-spoke/src/admission.rs`, `authorize` and `gate`). A caller with a grant reads. `gate` answers `SpaceFrozen` only to an operation that is freeze-gated and outside the maintenance allowlist, which SPOKE defines, and serves the operations that are not freeze-gated (`crates/mindcore-spoke/src/admission.rs`, `gate`). Freeze-gated operations include `memory.capture`, `memory.candidates.review`, `memory.records.update` and `memory.profile.update` (`crates/mindcore-spoke/src/content.rs`, `capture_body`, `review_body`, `update_record_body`, `update_profile_body`), and `memory.subjects.ensure` and `memory.grants.grant` (`crates/mindcore-spoke/src/control.rs`, `ensure_subject_body`, `grant_body`). - -**Stage 1, no SPOKE change.** It needs no SPOKE change and exposes Mind-level convenience operations only: the space-level capabilities beneath them are an advanced surface that may be exposed later. It composes none of the operations that are not Mind-routed: until each of `port.knowledge.*`, `history.*` and `knowledge.adopt` is served per Mind, the surface does not compose it, because every operation is to hang off the Mind entity (owner, 2026-11-25). - -- `memory.spaces.list` lists Minds. -- The memory family and the three workflow tools name a Mind through the `space_id` they already carry; no member is added and none is renamed. In `recall_context` and `absorb` that `space_id` sits inside the pinned SPOKE request, and only `deliberate` carries `space_id` and `holder` at the top level (`crates/mindcore-runtime/src/tools.rs`, the argument structs), so another selector name would be a SPOKE change, which Stage 1 does not make. -- The workflow tools' one argument change is that `deliberate` loses `holder`, because the Mind's record names the carrier. The facade's `deliberate` takes no `subject_id` (owner, 2026-11-25): the grant re-check and the unsettled-intent check move to the space, and both are verified against the code when the facade is prepared (`2026-11-25-three-delivery-forms.md`). -- A new `tools.mindcore.read_cognition` takes `space_id`, as the memory operations do, and returns that Mind's current judgment and derived `MindState`. -- One `NOT_AUTHORIZED` answers an unknown or unadmitted Mind before any existence check, a frozen Mind included. - -**Stage 2, three SPOKE-side items.** A1 is request-scoped admission: the admission callback receives the `scope_id` a request declares. It is additive and source-compatible. A2 is an optional `scope` on `port.knowledge.get` and `port.knowledge.put`, with a negotiable marker saying the responder honours it; it is a wire change, so a new SPOKE cohort. A3 is `memory.spaces.create`, the operation a SPOKE peer creates a Mind through. A1 and A2 turn on knowledge, history and adoption per Mind; until both exist, those three operations are not served per Mind, so the surface does not compose them. A3 turns on a peer's creation of a Mind. SPOKE 0.19.0 will carry A1, A2 and A3, and the caller names the `space_id` (owner, 2026-11-25). - -**Creating a Mind.** A library caller creates a Mind through `create`, `list` and `get` in `crates/mindcore-runtime`, which need no SPOKE change and are built; the facade (`2026-11-25-three-delivery-forms.md`) builds on them. A SPOKE peer creates one through `memory.spaces.create`, which is A3 of Stage 2 and which SPOKE 0.19.0 will carry. On a Mindcore host both run the same create and write the default grant set (`2026-11-25-create-default-grant-set.md`). Until this repository pins that cohort, a peer operates only Minds created through the library. - -**The fallback.** Design T is the fallback: every Mind-scoped operation is a `tools.mindcore.*` tool whose argument object starts with `mind_id`, with no SPOKE change. SPOKE and Mindcore have the same owner, so whether the fallback is taken is the owner's direct decision, and it needs no trigger. `mind_id` is there a tool argument of Design T's own, not a renamed SPOKE member: every operation becomes a new tool, and the argument object is that tool's to define. - -**Records and pages this changes.** `ServeFaces.workflow_routes` is replaced by the registry's Mind-to-collection row, which retires the route `2026-11-21-principal-routing.md` records. Its rules that outlive the map hold per Mind: the wire never names a collection, a refusal carries no target details, and a route never substitutes for a live grant. `.agents/specs/architecture/serving-principal-routing.md` gains the request's Mind id as a route input and loses the map, and the knowledge page `.agents/knowledge/architecture-patterns/serving-principal-routing.md` describes that map and goes stale with it. `.agents/specs/architecture/serving-seam.md` changes the tool argument table — the `deliberate` row loses `holder`, the `recall_context` and `absorb` rows keep their request types, and one row is added for `tools.mindcore.read_cognition` — and, in Stage 2, the half of the knowledge contract that says `get` and `put` carry no wire scope. In `2026-11-21-spoke-017-serving-cohort.md` the tool list and the routing sentence are brought up to date. `docs/serving.md` loses its `workflow_routes` row, and `docs/concepts.md` states the closed existence gap. - -## Alternatives considered - -- **Design T: every Mind-scoped operation a `tools.mindcore.*` tool, no SPOKE change.** Rejected as the primary route and kept as the fallback. It restates `port.knowledge.*`, `history.*` and `knowledge.adopt` as six product tools, which is a second operation surface inside the tool namespace and reverses the migration that replaced `tools.mindcore.adopt` with `knowledge.adopt` (`.agents/specs/architecture/serving-seam.md`). The surface would still carry the per-peer `port.knowledge.*` path beside those tools, and a tool's arguments pass outside SPOKE's scope and cognition gates. The chosen route rides selectors SPOKE already has and keeps the peer on standard operations. -- **One responder per Mind, no SPOKE change.** Rejected: it is not one surface serving many Minds. Each Mind gets its own surface, manifest, handler set and one signed session per peer, a peer has no way to list Minds, and the hello manifest repeats for every (peer, Mind) pair. Whether an unadmitted Mind's address differs from an unknown one is left to the host's transport. -- **One collection, with Minds separated per entry, no SPOKE change.** Rejected: SPOKE's scope predicate has no entry-ownership term and an admitted scope is fixed per peer, so two peers could not be held to different Minds. It also gives up the one-collection-per-Mind binding of `2026-11-25-mind-is-one-memory-space.md`. -- **Ship no peer form until the SPOKE-side items exist.** Rejected: it ties a first release to a SPOKE release Mindcore does not control. Stage 1 needs no SPOKE change and gives a peer per-Mind memory and cognition; what it costs is that a peer gets no `port.knowledge.*`, `history.*` or `knowledge.adopt` until Stage 2, because a many-Mind surface composes none of them until each is served per Mind. The one collection per peer those operations answer from today is the state this decision replaces, not what Stage 1 ships. The third round's release timing makes a release without the peer capabilities impossible until SPOKE 0.19.0; that is a release decision and does not adopt this alternative. - -## Acceptance criteria - -- One served surface serves more than one Mind. A call naming a Mind resolves its space, knowledge collection and carrier through the host's admission, and a peer lists and operates only the Minds it is admitted to. -- A signed loopback test runs two Minds and two peers and asserts that an unadmitted Mind answers the same refusal as an absent one, and, in Stage 2, that `knowledge.adopt` writes only to the admitted Mind's destination — the collection the registry row names, resolved after admission and never the surface's configured destination. -- A peer with no Mind is refused without target details. -- Stage 1 is served on the pinned SPOKE cohort: `memory.spaces.list` lists Minds, the memory family and the three workflow tools name a Mind through the `space_id` they already carry with no member added or renamed, `tools.mindcore.deliberate` takes no `holder`, and `tools.mindcore.read_cognition`, taking `space_id`, returns current judgment and `MindState`. -- A recall, and every other memory read that looks a space up, answers one refusal with one code and no target details for an unknown Mind id and a Mind the caller holds no grant for, a frozen Mind included; one test pins these cases on that answer. On a frozen Mind a granted caller is served every operation that is not freeze-gated, and a freeze-gated operation outside the maintenance allowlist answers `SpaceFrozen`; one test pins both. -- `.agents/specs/architecture/serving-principal-routing.md` and `.agents/specs/architecture/serving-seam.md` are updated in the same change, and the operations that are not Mind-routed are documented as such. - -## Risks - -- **Before SPOKE 0.19.0 a peer gets per-Mind memory and cognition only.** `port.knowledge.*`, `history.*` and `knowledge.adopt` are composed only once each is served per Mind, which A1 and A2 turn on. Today they answer from a surface's one collection, which no Mind owns; that is the state Stage 2 replaces and is not carried into a many-Mind surface. No release ships Stage 1 alone: the first Mind-centric release follows SPOKE 0.19.0 and ships Stage 1 and Stage 2 as one minor (owner, 2026-11-25). -- **The argument change breaks existing `deliberate` callers.** `holder` is a required member of today's `deliberate` arguments and the argument object is closed (`crates/mindcore-runtime/src/tools.rs`), so a peer built on today's `deliberate` fails after the change. `recall_context` and `absorb` arguments do not change. It is a Mindcore release change, not a SPOKE one. -- **A2 without its marker misroutes silently.** A responder that ignores the new `scope` drops it, and the read lands in the peer's default collection. The marker is part of the ask and is not optional for Mindcore. -- **Admission stays synchronous and bounded.** The registry lookup behind a Mind admission runs under the responder's serve budget and must fit inside it. -- **Closing the existence gap changes answers tests may pin.** The memory path answers `NOT_FOUND` for an unknown space today (`crates/mindcore-spoke/src/admission.rs`), and the adapter tests that pin it change with it. -- **Settled: a many-Mind surface composes none of the operations that are not Mind-routed.** Until each of `port.knowledge.*`, `history.*` and `knowledge.adopt` is served per Mind, the surface does not compose it, because every operation is to hang off the Mind entity (owner, 2026-11-25). -- **Undecided: the grant rule for a knowledge put that carries cognition records.** `port.knowledge.put` appends `modules.cognition.records` on the admitted scope alone (`crates/mindcore-sqlite/src/knowledge.rs`, `served_put`), where `deliberate` requires `knowledge_write` (`crates/mindcore-spoke/src/workflows.rs`). The asymmetry exists today, and routing knowledge per Mind would carry it to every admitted Mind. The rule is settled before knowledge is routed per Mind. -- **A3 is not in the pinned SPOKE cohort yet.** `memory.spaces.create` does not exist in 0.18.1, and SPOKE 0.19.0 will carry it (owner, 2026-11-25). Until this repository pins that cohort, a peer can operate Minds and cannot create one. On a Mindcore host the operation runs the same create as the library, `mindcore_sqlite::minds::create`, which borrows the caller's transaction. -- **Design T, if taken, costs more than Stage 2**: eight new tools, six of which restate standard operations, and a second knowledge path on the surface. diff --git a/.agents/specs/architecture/mind-model.md b/.agents/specs/architecture/mind-model.md index 70f675fc..27fde280 100644 --- a/.agents/specs/architecture/mind-model.md +++ b/.agents/specs/architecture/mind-model.md @@ -10,6 +10,7 @@ The first delivered contract of Mindcore: what a Mind is, which records carry wh - `mindcore-sqlite` implements `MindStore`: each opened store owns its own single-connection SQLx pool, runs the embedded migrator once (two appended files: `0001_init.sql`, carrying the ten protocol memory tables, `knowledge_entries`, `cognition_records`, `history_dedup` and `memory_embedding_vectors`, and `0002_minds.sql`, carrying `minds`), and sets WAL, foreign keys and a five-second busy timeout on that file. `knowledge_entries.history_floor_revision` is the persisted replay floor — the first revision above the newest deleted preimage, defaulting to `1` so a fresh row reads as "nothing pruned". `SqliteMemoryRepository` — the protocol repository, borrowing the caller's transaction rather than owning a pool — and the per-collection `ScopedKnowledgeStore` (implementing the pinned `KnowledgeEntryPort`) are implemented there. - A `Mind` is a stable logical actor identity (Creator, Character); it is not a caller, a database file, a collection or a wire type. A caller is identified by `CallerId`, a plain string the embedding adapter supplies: records keep it as attribution (`requester`, `updated_by`), it is not mental state, and it decides no admission. - A Mind is persisted and enumerable. Its id is its space's `space_id` — `MindId` holds that value and there is no second id — and the `minds` table binds the id to the knowledge collection the Mind's entries and carrier live in and to the carrier entry that holds its current judgment. A Mind owns no subject: `create` establishes none, and a write names its own. A Mind is deactivated by freezing its space and reactivated by unfreezing it; no operation archives or deletes one, and a Mind's status is its space row's. A Mind record is not a grant: it confers no access, and every operation admits the caller under its own live grants in the Mind's space. +- A served call names the Mind, never a collection. The served surface takes the request's Mind id — `space_id` on a memory request or a served workflow tool, and `scope_id` on a knowledge `Scope` once that face returns — as its only route input, and the Mind's registry row resolves it to the collection and carrier the call may reach; admission runs before any existence check, and every operation still re-derives the caller's own live grants. Stage 1 serves memory and cognition per Mind: `port.knowledge.*`, `history.*` and `knowledge.adopt` cannot name a Mind, so the surface composes none of them (`.agents/specs/architecture/serving-principal-routing.md`). - `create`, `list` and `get` are the library entry points, `mindcore_runtime::minds` in `crates/mindcore-runtime`, over the operation and the reads in `crates/mindcore-sqlite`. `create` takes the id the caller names or assigns `spc_` and a minted identity, refuses a taken id with `InvalidInput` and `details.reason` `MIND_ALREADY_EXISTS`, and writes four rows in one `BEGIN IMMEDIATE` transaction: the space, the carrier entry `ke_carrier` in the collection `mind:`, the `minds` row, and the creating principal's one grant row — `recall`, `capture`, `review`, `records_write`, `knowledge_read`, `knowledge_write` and space-wide `admin`, with no subject, no context restriction and no expiry. The operation, `mindcore_sqlite::minds::create`, borrows the caller's transaction, so a protocol operation can run it inside its own. `list` answers the Minds whose space the caller holds a live grant in, in id order; `get` answers `NotFound` for every other id. A frozen Mind is listed and read with status `frozen`. - Memory: `capture` stages a pending candidate; candidate review consumes it, projecting one retained record (`promote`), several (`fragment`) or none (`drop`), and `dismiss` consumes it without a record. Recall reads live records only. Each mutation carries an idempotency key: a replay returns the recorded outcome instead of repeating the effect, and a second review of a consumed candidate is refused. A record keeps its candidate's placement (`space`, `subject`, context) and a repository read orders by `created_at DESC, record_id`; recall withholds a subject whose journal holds an unsettled intent. - Memory reads authorize per operation under the caller's live grants in the space. `memory.candidates.list` with no `status` filter hides an `archived` subject and answers an empty page — the default listing is not an audit query — while a status-filtered listing is that explicit audit query and still lists the subject. `memory.records.get` is answered to either `records_read` or `recall`, and a tombstoned record additionally requires `admin`. `memory.records.list` accepts either read capability, but one grant must cover the whole selection: requirements never union across grants, so two grants that each cover part of the selection do not admit the call. `include_tombstoned` additionally requires an `admin` grant on the subject. @@ -44,7 +45,7 @@ The first delivered contract of Mindcore: what a Mind is, which records carry wh - `crates/mindcore-base/src/{ids,boundary,memory,knowledge,cognition}.rs`, `crates/mindcore-base/src/ir.rs`, `crates/mindcore-base/src/ir/wire.rs` and `crates/mindcore-base/src/ir/wire/memory.rs` - `crates/mindcore-sqlite/src/{store,repository,knowledge,cognition,vectors,minds}.rs` - `crates/mindcore-runtime/src/minds.rs` — the library entry points `create`, `list` and `get`, one forwarding call each. -- `crates/mindcore-runtime/src/history_dedup.rs` owns the served history's prune dedup record over the store's own pool: a claim before the port and an upserted outcome after it, both in the `history_dedup` table this page's `0001_init.sql` creates. +- `history_dedup` is the table `0001_init.sql` creates for the served history's prune dedup record — a claim before the port and an upserted outcome after it. The module that owned it, `crates/mindcore-runtime/src/history_dedup.rs`, was removed with the face; Stage 2 re-implements it per `.agents/specs/architecture/serving-seam.md`'s history handoff. - Decisions: [standalone embedded SQLite store](../../adr/implemented/architecture/2026-11-20-embedded-sqlite-storage.md), [one initial migration and no second memory schema](../../adr/implemented/architecture/2026-11-21-single-migration-store-bootstrap.md), [a Mind is one memory space](../../adr/implemented/architecture/2026-11-25-mind-is-one-memory-space.md) - `crates/mindcore-sqlite/migrations/0001_init.sql` and `crates/mindcore-sqlite/migrations/0002_minds.sql` - `crates/mindcore-spi/src/workflows.rs` owns workflow orchestration — the snapshot, reasoner, lens and policy phases and the order that builds and validates the judgment before the commit — while the storage transaction that appends the record is `crates/mindcore-spoke/src/workflows.rs`'s; `crates/mindcore-spi/src/judgment.rs` owns the `spoke-judgment` projection every deliberation response carries. diff --git a/.agents/specs/architecture/serving-principal-routing.md b/.agents/specs/architecture/serving-principal-routing.md index de2bd195..37cc46ad 100644 --- a/.agents/specs/architecture/serving-principal-routing.md +++ b/.agents/specs/architecture/serving-principal-routing.md @@ -1,161 +1,152 @@ -# Architecture: Serving per-principal routing +# Architecture: Serving Mind routing ## Scope -How one Mindcore serving surface selects the knowledge collection a served call reads and writes: -the routed workflow calls and the shared-entry adoption face. It does not define memory semantics, -the Connect handshake, or carrier record storage. +How one Mindcore serving surface selects the knowledge collection and carrier a served call reads +and writes: the request's Mind id is the only route input, and the Mind's registry row resolves it. +It also states which served operations are not Mind-routed and are therefore not composed. It does +not define memory semantics, the Connect handshake, refusal vocabulary or carrier record storage. ## Current state -### The map +### One route input: the Mind -A serving surface may serve more than one principal. The host supplies a route map keyed by the -principal id its `MemoryAdmission` returns for the authenticated peer. The route names the -`KnowledgeScope` whose collection that principal's carrier entry lives in. +A serving surface serves many Minds from one assembly, and neither the assembly nor the wire names a +collection. Routing has two inputs, and only the second is caller-declared: -Routing therefore has two independent inputs, and neither is caller-declared: +1. **Admission** — authenticated peer → `Principal`, from the host's `MemoryAdmission`. Never a wire + value. +2. **Route** — the request's Mind id → the registry row's collection and carrier entry. Never a + caller-named collection. -1. **Admission** — peer → `Principal`, from the host's `MemoryAdmission`. -2. **Route** — `Principal` id → `KnowledgeScope`, from the host's surface configuration. +A Mind's id is its space id (`2026-11-25-mind-is-one-memory-space.md`), so the selectors SPOKE +already carries express it: `space_id` on a memory request and on the served workflow tools' +arguments, and `scope_id` on a knowledge `Scope` once that face returns. The `minds` row +(`crates/mindcore-sqlite/migrations/0002_minds.sql`) is the map: it names the Mind's knowledge +collection and its carrier entry, and no configuration carries that pair a second time. -A caller-supplied principal, scope or collection is never used to select a route. +### Resolution and admission -`ServeFaces.workflow_routes: BTreeMap` carries the map -(`crates/mindcore-runtime/src/lib.rs:297-304`). Keys are exact principal ids, not peer ids; values are -workflow collection scopes. The standalone Knowledge face still uses its own `ServeFaces.scope_id`, -`knowledge`, and `admission`. `MemoryWorkflowBinding::new(pool, reflections)` starts with an -empty private `knowledge_routes`; `with_knowledge_routes` validates and takes ownership of the full -map (`crates/mindcore-spoke/src/workflows.rs:295-326`). The one private lookup, -`knowledge_route(&self, principal: &Principal) -> Option<&KnowledgeScope>`, borrows the scope by -`principal_id(principal)` for both carrier admission and the recall knowledge slot -(`crates/mindcore-spoke/src/workflows.rs:346-348`). +Every Mind-level operation reaches the store through an adapter entry, and each begins by looking +the Mind up. `admission::admit_mind` (`crates/mindcore-spoke/src/admission.rs`) is that lookup: +the caller's own grant rows in the space first, then the space row. No live grant and no space row +answer one `NOT_AUTHORIZED` with a fixed message and no `details`, so an unknown Mind, an +unadmitted one and a frozen one the caller holds no grant in are one answer. + +Coverage is checked after admission (`refuse_coverage`), and the freeze gate after that +(`gate`): a capability the caller's grant does not cover is a distinct refusal, and a frozen Mind +answers `SpaceFrozen` only to an operation that is freeze-gated and outside SPOKE's maintenance +allowlist, while serving every operation that is not freeze-gated. Only a caller that passed +admission reaches either check. + +The carrier read paths resolve through the registry row on the caller's transaction, after the same +order: `admitted_carrier` (`crates/mindcore-spoke/src/workflows.rs`) for the cognition read, and +`admitted_carrier_entry` for the host-side `deliberate` handler, which requires a space-wide live +`knowledge_read` grant before touching a carrier. A `space_id` with no registry row answers the +admission refusal before any carrier is read. ### Deliberation -`deliberate` settles onto a carrier entry, so it needs exactly one routed collection per call. - -- The route is resolved from the admitted principal inside the binding; the carrier write reads and - CAS-writes only that collection. -- The route fixes only the collection. Deliberation reads the carrier entry the request's `holder` - names inside it, so the existing holder/assessor identity rules decide whether a write is accepted; - a holder id that exists only in another collection is refused `knowledge_entry_not_found` and - writes nothing. -- Each destination collection belongs to exactly one principal route: assembly refuses a collection - named by two routes. The request's `holder` names the entry inside that one collection, so a - cross-principal carrier write is unreachable. -- A principal with no route is refused `NotAuthorized` with no target details. The refusal never - reveals whether another principal has a route. -- A surface with no route does not advertise `tools.mindcore.deliberate` and installs no handler - for it. Memory-face availability is independent: it is served only when the host configures it. +`deliberate` settles onto exactly one carrier entry, so it needs exactly one collection per call. + +- The collection and carrier are the registry row's, resolved through + `MemoryWorkflowBinding::carrier_collection` (`crates/mindcore-spoke/src/workflows.rs`) on the + caller's transaction; a binding an in-process facade opened may pin its own Mind first. A space + with no row answers the admission refusal before any carrier access. +- The request does not name the carrier: `holder` is not a member of the served argument object, so + a peer that still sends it meets the closed object's `InvalidInput`. +- The route fixes only the collection. Existing holder/assessor identity rules still decide whether + a write is accepted, and a destination collection belongs to one Mind, so a cross-Mind carrier + write is unreachable. ### Recall -`recall_context` is authorized by the caller's own live `RECALL` grant; the knowledge slot is +`recall_context` is authorized by the caller's own live `recall` grant; its knowledge slot is additional, not a condition of the call. -- The slot lists the collection routed to the admitted principal, under that principal's own live - `KNOWLEDGE_READ` grant in the request's space. -- A principal with no route, or no live `KNOWLEDGE_READ` grant, receives memory records with an - empty knowledge slot. The call does not fail because a route or grant is absent. +- The slot lists the collection the request's `space_id` row names, under that principal's own live + `knowledge_read` grant in the same space. +- A space with no registry row, or no live `knowledge_read` grant, receives the memory records with + an empty knowledge slot. The call does not fail because a row or grant is absent. - Grant-store read and collection-list failures are not authorization and still fail the call. -### Adoption - -`knowledge.adopt` reads one host-configured shared collection and writes the collection the -knowledge face itself serves. `ServeFaces.adoption: Option` names the source by its -wire `scope_id` and its collection (`crates/mindcore-runtime/src/lib.rs:247-257,288-296`); the -destination is `ServeFaces.knowledge`, the one collection `knowledge.get`/`list` read for the -admitted peer. Adoption does not consult `workflow_routes`: that map selects a *workflow* collection -per principal, and the knowledge face takes no per-principal collection, so a route-derived -destination could land a copy where no knowledge-face read reaches it. Neither collection is -selected by a request member: the two scope members are only compared against the configured source -and the admitted scope. - -- Assembly refuses an empty source scope id, an empty source collection, a source scope id equal to - `ServeFaces.scope_id`, and a source collection equal to `ServeFaces.knowledge`'s collection or to - any route destination, including the route of a principal that is not currently connected - (`crates/mindcore-runtime/src/lib.rs:105-150`). Without the collection refusal an adopted copy - could become the shared entry another principal reads, or a copy of the destination itself; the - scope refusal keeps a principal from adopting out of its own destination scope. -- Admission is the knowledge face's, composed as `(principals(peer)?, knowledge_admission(peer)?)`: - a peer outside either callback gets that callback's refusal, so a principal the knowledge - admission refuses answers `NOT_AUTHORIZED` instead of adopting. A principal with knowledge - admission but no workflow route adopts normally. -- The destination collection is fixed by the host, so every admitted principal adopts into the one - collection its own knowledge-face reads serve; the admitted scope's entry selection narrows what - the call may serve or write inside it. Both come from host configuration, never from the payload. -- The source is read-only to the call and only that destination is written, both on one - `BEGIN IMMEDIATE` transaction, so adoption adds no write outside the destination collection. The - source handle is a distinct type from the destination handle, and the one write its port must - expose refuses before any statement runs, so no caller can write the shared collection through - the source side. -- The source resolves through its retirement chain before the copy is read, so the write lands a - copy whose anchor names the terminal, never a retired hop. - -The scope mapping, the refusal vocabulary and its wire codes, the terminal-anchor rule, the served -revision domain, the copy's inherited governance and the idempotency envelope are -[`serving-seam.md`](serving-seam.md)'s alone; this page states only which collection the route -selects and how admission reaches it. +`absorb` consults no registry row: it captures and reviews memory in the named space and writes no +carrier. + +### Listing + +`memory.spaces.list` takes the same admission: its set is the registry's join over the caller's live +grants (`crates/mindcore-sqlite/src/minds.rs`, `visible_mind_ids`), in `id` order, so a peer lists +exactly the Minds it may operate. A frozen Mind is listed with its `frozen` status; a space with no +registry row is not listed even under a live grant. The wire shape, cursor and marker are unchanged. + +### The un-routed operations + +`port.knowledge.*`, `history.*` and `knowledge.adopt` cannot name a Mind: the retained +`RoutedKnowledgeStore` (and its `HistoryPort`) binds one collection for its lifetime, and adoption's +destination is the knowledge face's own collection. Stage 1 therefore composes none of them: + +- the manifest advertises no `spoke-knowledge`, `ke-ownership`, `spoke-history` or + `spoke-knowledge-adoption`, and the runtime's `MindPorts` answers `None` for every family but + memory; +- a call to each answers `CAPABILITY_PORT_MISSING` on the responder's dispatch-deny branch. + +They return per Mind in Stage 2, once SPOKE carries request-scoped admission and an optional scope on +knowledge get and put (`2026-11-25-one-surface-serves-many-minds.md`). Their contracts stay +[`serving-seam.md`](serving-seam.md)'s. ### Construction -- An empty principal key, an empty collection, or one collection named by two routes is refused - when the surface is assembled; the refusal does not wait for the first call - (`crates/mindcore-spoke/src/workflows.rs:295-326`). The adoption source is validated in the same - assembly step, before any port or registration exists. -- The route map is host configuration: it is not persisted, not derived from arguments, and not - read from the wire. +- There is no route map to validate: `ServeFaces` carries no `workflow_routes`, `scope_id`, + `knowledge` or knowledge admission, and every Mind names its own collection through its row. +- The route is persisted state, not host configuration: it is written once by `create` and not + derived from arguments, and the wire carries only the Mind id. - The route never substitutes for a live grant: every carrier write and knowledge read still - re-derives the grants on its own transaction. + re-derives the caller's own grants on its own transaction. ## Invariants -- A served workflow's knowledge access produces no write, disclosure, revision change, entry-count - change or knowledge-slot entry outside the collection routed to its own admitted principal. - Adoption is the one served call that touches a second collection: it reads only the - host-configured source and writes only the knowledge face's own collection, which every peer - admitted to that scope shares: it holds one slot per destination entry id, the first adoption of a - given id claims it, a repeat is served that stored copy only at the anchor revision the copy - records, and a peer whose own admitted selection admits it reads the copy through that face; - assembly refuses a source that is the destination collection or any route destination. Read-only - access beyond the routed collection is otherwise not observable through the served surface and is - therefore not asserted. -- No refusal discloses another principal's route, collection or entry. -- No wire value selects the authenticated principal, the source collection or the destination - collection: admission supplies the principal, `AdoptionRoute` the source, and `ServeFaces.knowledge` - the destination. Adoption's arguments name one source entry, its expected source - revision, an optional destination entry id, an idempotency key, and the required - `source_scope_id` and `destination_scope_id`: the two scope members are compared against the - host-configured source and the admitted scope and never select either, and its result carries that - copy, whose stored provenance selects nothing. +- A served call reads and writes only the collection the admitted Mind's registry row names, and no + result mixes two Minds. The host's own memory family service dispatches its operations under the + host's admission; which of them it dispatches was always the host's. +- One `NOT_AUTHORIZED` with no `details` answers an unknown Mind id and a Mind the caller holds no + live grant in, a frozen one included, because admission runs before any existence check. +- No refusal discloses another Mind's collection, carrier or entry; the coverage refusal is + reachable only by a caller already admitted to that Mind. +- The three un-routed operations are never advertised and never served; a restored face re-enters + composition only per Mind, with `serving-seam.md`'s contract. - The carrier record format is unchanged. ## Where it lives -- `crates/mindcore-runtime/src/lib.rs` — `ServeFaces` (`:261-309`) with `workflow_routes` - (`:297-304`) and `adoption` (`:288-296`), `AdoptionRoute` (`:247-257`), the adoption admission - composition (`:195-208`), and the assembly-time refusals in `MindcoreServe::surface` - (`:105-150`), the adoption source checks among them (`:107-150`). -- `crates/mindcore-spoke/src/workflows.rs` — `MemoryWorkflowBinding::new` (`:92-99`), - `with_knowledge_routes` (`:295-326`) and the one `knowledge_route` lookup (`:346-348`) both - routed workflow calls share. -- `crates/mindcore-runtime/src/adoption.rs` — the adoption port: the destination handle over the - knowledge face's collection, the admitted-selection predicate, and the one `BEGIN IMMEDIATE` - transaction around the chain resolution and the copy. +- `crates/mindcore-spoke/src/admission.rs` — `admit_mind` (grant rows, then the space row), + `refuse_coverage`, `refuse_space_coverage` and `gate` (the freeze and subject gates). +- `crates/mindcore-spoke/src/workflows.rs` — `carrier_collection` (the one registry-row lookup both + readers share), `knowledge_slot`, and `admitted_carrier` / `admitted_carrier_entry` (the carrier + admissions). +- `crates/mindcore-sqlite/src/minds.rs` — the `minds` row, its visibility join and `create`. +- `crates/mindcore-runtime/src/tools.rs` — the served `deliberate` and `read_cognition` argument + objects and their handler entry. +- `crates/mindcore-runtime/src/lib.rs` — `MindPorts`, the retired-id filter and `face_capabilities`. - `.agents/specs/architecture/serving-seam.md` — the served tool ABI and the advertisement rule. -- `crates/mindcore-runtime/tests/{loopback,surface}.rs` — the signed-session assertions for each - route and each advertisement case, and the surface-level adoption-reads-back test. +- `crates/mindcore-runtime/tests/loopback.rs` — the signed-session assertions: two Minds and two + peers, the unadmitted/absent refusal, the frozen cases and the advertised set. +- `crates/mindcore-spoke/tests/memory_adapter.rs` — the admission-first assertions over every + Mind-level read path and the registry-derived `memory.spaces.list`. ## Known limit -A route, and the knowledge face's own collection, are fixed for the lifetime of the surface. -Changing either requires assembling a new surface; there is no hot reload of the route map. The -workspace has no periodic reconfiguration requirement, so this is recorded rather than implemented. +Stage 1 routes memory and cognition per Mind only. `port.knowledge.*`, `history.*` and +`knowledge.adopt` stay un-routed until Stage 2, so a peer gets no knowledge, history or adoption +operation. A Mind's registry row is written once: changing its collection is a new Mind, not a +reconfiguration, and there is no hot reload. ## Change obligations -Changing admission, the route map shape, route resolution, reachability or collection isolation -updates this page, the served tool table in [`serving-seam.md`](serving-seam.md) and the loopback -assertions in the same change, and keeps the invariants above true. A new routed call states here -which collection it reads and which it writes, and how it refuses a principal with no route. +Changing admission, route resolution, reachability or collection isolation updates this page, the +served tool table in [`serving-seam.md`](serving-seam.md) and the loopback assertions in the same +change, and keeps the invariants above true. A new served operation states here which collection it +reads and which it writes, and how it refuses a caller with no admission to the named Mind. The +knowledge page `.agents/knowledge/architecture-patterns/serving-principal-routing.md` still +describes the retired principal route map; it is stale against this page and is rewritten with that +corpus, not here. diff --git a/.agents/specs/architecture/serving-seam.md b/.agents/specs/architecture/serving-seam.md index 4aba0856..659dca35 100644 --- a/.agents/specs/architecture/serving-seam.md +++ b/.agents/specs/architecture/serving-seam.md @@ -2,13 +2,19 @@ ## Scope -Signed Rust SPOKE sessions over a host-supplied transport: the Memory, Knowledge, History and adoption faces, and the three Mind workflow tools. The library does not own a listener, accept loop, identity provisioning, publisher, or model provider. +Signed Rust SPOKE sessions over a host-supplied transport: the Memory face, the four Mind tools, and the Knowledge, History and adoption face contracts a restored per-Mind composition must satisfy. The library does not own a listener, accept loop, identity provisioning, publisher, or model provider. ## Current state ### Knowledge -The host installs a `KnowledgeAdmission` callback in `RemoteKnowledgeFace`. Connect supplies the authenticated peer id; the callback returns the peer's one admitted `Scope` or refuses. An exact host-configured route maps the admitted `scope_id` to `KnowledgeScope.collection` on the bound SQLite pool. No fallback guesses a collection from an entry id, `owner`, `viewpoint`, or Memory `SpaceId`. Memory space and workflow knowledge grants remain separate and go through the existing `MemoryWorkflowBinding` admission. The `ke-ownership` protocol gate checks the negotiated flag for a list with an explicit `viewpoint`; it neither chooses the collection nor grants the peer entry access. +Stage 1 composes no knowledge face: `ServeFaces` carries no scope, collection or knowledge +admission, the manifest advertises neither `spoke-knowledge` nor `ke-ownership`, and every +`port.knowledge.*` op answers `CAPABILITY_PORT_MISSING` on the responder's dispatch-deny branch. +`ScopedKnowledgeStore` and `RoutedKnowledgeStore` stay in `mindcore-sqlite` for Stage 2 to bind +per Mind. The paragraphs below state the contract a restored face must satisfy. + +A restored face installs a `KnowledgeAdmission` callback in `RemoteKnowledgeFace`. Connect supplies the authenticated peer id; the callback returns the peer's one admitted `Scope` or refuses. An exact host-configured route maps the admitted `scope_id` to `KnowledgeScope.collection` on the bound SQLite pool. No fallback guesses a collection from an entry id, `owner`, `viewpoint`, or Memory `SpaceId`. Memory space and workflow knowledge grants remain separate and go through the existing `MemoryWorkflowBinding` admission. The `ke-ownership` protocol gate checks the negotiated flag for a list with an explicit `viewpoint`; it neither chooses the collection nor grants the peer entry access. `get` and `put` carry no wire scope. `list` names the admitted `scope_id` and `viewpoint`; Connect bounds the request by the admitted scope before calling the store. The scoped adapter binds the collection on every statement. Within it, entry-id, entry-type, source-id and viewpoint filters use SPOKE's knowledge predicate (including owner-private disclosure); an explicit empty set matches nothing. The face does not serve cognition, timeline or extension-based selection; refuse unsupported constraints rather than silently ignoring them. List results are in `entry_id` order. The host admission callback validates the scope it returns with `mindcore_sqlite::validate_admission_scope` before returning it: Connect's list merge keeps only the request's cognition selection, so an admitted cognition selection reaches the collection query unless it is refused at admission. A served list reads at most `SERVED_KNOWLEDGE_LIST_LIMIT` (512) **live** rows of the routed collection — the live predicate rides in the statement — and refuses a larger live set with `InternalError` naming the bound; the bound applies before disclosure filtering and never truncates silently. A retired row therefore never consumes list budget. @@ -51,7 +57,7 @@ A key that is both a retained claim and a same-key different-payload retry answe `HISTORY_NOT_RETAINED` is never answered: every revision at or above the floor is rebuilt from the next checkpoint or the live row, and a contradicted gap is storage corruption, not a retention gap. -Prune is deduplicated by Connect's recorded-outcome store, keyed by `(op, effective scope, requester principal id, idempotency_key)` and holding the request digest plus the settled outcome. The history face composes `crates/mindcore-runtime/src/history_dedup.rs`'s `SqliteHistoryDedupStore` through `HistoryPortService::with_dedup_store`, over the same pool and database file as the knowledge store — one store, one pool, one process. A host therefore gets the durable store, not the released in-memory default, and no `ServeFaces` field selects between them. +Prune is deduplicated by Connect's recorded-outcome store, keyed by `(op, effective scope, requester principal id, idempotency_key)` and holding the request digest plus the settled outcome. A restored history face composes `crates/mindcore-runtime/src/history_dedup.rs`'s `SqliteHistoryDedupStore` through `HistoryPortService::with_dedup_store`, over the same pool and database file as the knowledge store — one store, one pool, one process. A host therefore gets the durable store, not the released in-memory default, and no `ServeFaces` field selects between them. `history_dedup` keys each row by the collection its history surface routes to and the retry identity, in two columns under the composite primary key `(namespace, key)` — the namespace is `RoutedKnowledgeStore::collection()`. A framed string cannot carry this: a collection name is arbitrary, so any separator would let two `(collection, key)` pairs collide. Two surfaces on one database can share a wire scope, a principal and an idempotency key while serving different collections; the namespace keeps the second from replaying or refusing the first's prunes, and a same-collection retry replays exactly as before. @@ -82,7 +88,7 @@ Adoption keeps the released in-memory default and its own restart exposure. Adop ### Workflow tools -`MindcoreServe` derives served capability ids and tool descriptors from installed faces and handlers; the host supplies identity, transport, allowed peers and non-capability manifest metadata. Compose Memory and Knowledge with `RemoteServePortsComposite::knowledge_only(face).with_memory(service)`, and the history family with `.with_history(service)` on that same composite. The Memory service consumes a trusted peer-to-principal mapping and implements the advertised family contract; the runtime does not create fake baseline, reflection or transfer providers. For each accepted transport, register handlers before releasing inbound traffic; `connect_responder` starts its own SPOKE receive task and does not install handlers from the manifest. +`MindcoreServe` derives served capability ids and tool descriptors from installed faces and handlers; the host supplies identity, transport, allowed peers and non-capability manifest metadata. Stage 1 composes the host's memory service and nothing else: the runtime's own `MindPorts` answers `as_memory` and takes the trait's default `None` for the knowledge, history and adoption families, so a host cannot configure a second face beside it. The Memory service consumes a trusted peer-to-principal mapping and implements the advertised family contract; the runtime does not create fake baseline, reflection or transfer providers. For each accepted transport, register handlers before releasing inbound traffic; `connect_responder` starts its own SPOKE receive task and does not install handlers from the manifest. The memory face advertises `spoke-memory` whenever a service is attached, and `spoke-memory-transfer` only when that service reports all five §7.29–§7.33 operations through `mindcore_spoke::ServedMemory::operations`. `RemoteMemoryService` exposes one `invoke` seam and names no operation, so the service itself carries the answer: `ServedMemory` extends it with an operation list whose default is empty, and a bare `RemoteMemoryService` therefore never claims the transfer family. The derivation is the only advertisement list: `face_capabilities` compares [`TRANSFER_OPERATIONS`] against what the service reports, so no host-supplied string can claim a family the bound service cannot show it dispatches. @@ -96,14 +102,19 @@ A stored document whose `content.structured` (or a pending `proposed.content.str The host's peer resolver supplies the `Principal` from the authenticated responder session, not from arguments. `ToolHandler` receives only JSON arguments, so a handler binds to its responder session (weak reference, no ownership cycle). Missing peer/principal is `NotAuthorized`. Do not share a handler closure bound to one session with a different session. Provider capabilities and `DomainLens` are host inputs. Workflows continue to enforce their own live memory/knowledge grants and settlement boundaries. -Connect owns the signed `{ "arguments": {…} }` request and `{ "result": … }` success wrappers. The following keys define closed argument objects; `request`, `holder` and `target` use the corresponding existing SPOKE DTOs. Results use the listed fields and snake-case branch tags: +Connect owns the signed `{ "arguments": {…} }` request and `{ "result": … }` success wrappers. The following keys define closed argument objects; `request` and `target` use the corresponding existing SPOKE DTOs. Results use the listed fields and snake-case branch tags: | Capability id and op | Arguments | Result | |---|---|---| | `tools.mindcore.recall_context` | `request` (`MemoryRecallRequest`), positive integer `max_tokens` | `{records, knowledge, tokens_used}` | | `tools.mindcore.absorb` | `request` (`MemoryCaptureRequest`) | Array of `{status, candidate_id}` with `status` = `pending`, `dropped`, or `settled` (adds `record_ids`) | -| `tools.mindcore.deliberate` | `space_id`, `subject_id`, `holder`, `target`, `evidence` (`[{id, text}]`), positive integer `timeout_ms` | `{status, verdict, judgment}` with `status` = `no_change`, `needs_review` (adds `draft`), or `settled` (adds `record`, `mind_state_version`) | -| `knowledge.adopt` (capability `spoke-knowledge-adoption`, which requires `spoke-knowledge`) | `source_scope_id`, `source_entry_id`, positive integer `source_revision`, `destination_scope_id`, optional `destination_entry_id`, `idempotency_key`, optional `extensions` | `{outcome, entry}` with `outcome` = `adopted` or `already_present`; `entry` is the stored copy either way | +| `tools.mindcore.deliberate` | `space_id`, `subject_id`, `target`, `evidence` (`[{id, text}]`), positive integer `timeout_ms` | `{status, verdict, judgment}` with `status` = `no_change`, `needs_review` (adds `draft`), or `settled` (adds `record`, `mind_state_version`) | +| `tools.mindcore.read_cognition` | `space_id` | `{carrier_revision, records, mind_state}`; a Mind that has judged nothing answers `records: []` and a null `mind_state` | +| `knowledge.adopt` (capability `spoke-knowledge-adoption`, which requires `spoke-knowledge`; not composed in Stage 1) | `source_scope_id`, `source_entry_id`, positive integer `source_revision`, `destination_scope_id`, optional `destination_entry_id`, `idempotency_key`, optional `extensions` | `{outcome, entry}` with `outcome` = `adopted` or `already_present`; `entry` is the stored copy either way | + +`deliberate` takes no `holder`: the Mind's registry row names the carrier, and a peer that still +sends the retired member is refused `InvalidInput` by the closed object. Every served argument +object names a Mind through `space_id` and never a collection, a carrier or a principal. An `absorb` run that updates a record and dismisses its candidate stages two intents in one transaction, the record update and the candidate dismissal, then collects the settled revisions from each staged intent's own result: a revision is yielded only for a record id the result names. The dismissal leg's result names no record, so only the update leg's result yields a revision; walking both legs adds nothing from the dismissal. @@ -111,7 +122,7 @@ An `absorb` run that updates a record and dismisses its candidate stages two int An `absorb` replay reports what an earlier run of the same capture recorded for each consumed candidate. A candidate consumed by the update leg's dismissal is the one consumption whose result names no record, so the binding reads the update leg's own receipt — keyed by the capture key, the candidate id and `update` — for the record id: a committed receipt reports `settled` with that id and an absent one reports `dropped`. Capture and update receipts are rows of one table under one aged policy, and the binding has no per-operation retention branch; the capture receipt is minted first, so an aged-out capture receipt refuses the replay before an aged-out update receipt could be read. -Two of the three workflow tools are routed, and only they: `deliberate`'s carrier admission and `recall_context`'s knowledge slot. Deliberation settles onto exactly one carrier entry, so `ServeFaces.workflow_routes` maps each exact principal id — not a peer id, and never a value read from the wire — to the collection those operations reach for that principal, and `MemoryWorkflowBinding::with_knowledge_routes` validates the whole map once at assembly and holds it behind one `Arc`; both readers of the routes — the binding's two workflow lookups — read that same map, so no workflow consumer can resolve a different destination for a principal. `absorb` consults no route. Adoption consults no route either: its destination is the knowledge face's own collection, so a copy it writes is one the admitting peer reads back through `knowledge.get`. Each destination collection belongs to exactly one principal route, so a collection named by two routes is refused at assembly; the route never substitutes for a live grant — every carrier write and knowledge read still re-derives the caller's own grants on its own transaction. At carrier admission a principal with no route is refused before any carrier access, as terminal `NotAuthorized` carrying the fixed message `principal has no workflow knowledge route` and no collection, entry, caller id, or other route detail, so it never reveals whether another principal has a route. Recall's slot is independent of the memory page and best effort for the route and the grant: a missing route, or a missing live `knowledge_read` grant in the request's space, returns the memory result with `knowledge: []`, never a refusal. That tolerance covers the route and the grant only — a grant-store read or collection-list failure is not converted into an empty slot; it propagates and fails the recall. With both a route and the grant the slot lists only the routed collection under the same disclosure predicate as the served knowledge list, so an `owner`-private entry never reaches the pack. The host map is the workflow collection allowlist: a valid route need not name a collection that already holds rows, each destination collection is one principal's, and no route is checked against the independent Knowledge face or resolved to a default collection — to change a mapping, assemble a new surface. Assembly returns `InvalidInput` for an empty principal key, an empty destination collection, or a collection named by two routes, before any port or registration exists; an empty map is valid and serves no deliberation, so it installs no `deliberate` handler and advertises neither the capability nor a tool descriptor, and a host registration of that reserved id is dropped rather than advertised or installed. `recall_context` keeps serving without a route map, with no slot to fill, and `absorb` keeps serving because it never consults one. Memory authorization, withholding, snapshot revalidation and token budgeting are unchanged by routing and stay separate rules: the page is still the adapter's own ACL and withholding read, so a memory grant revoked while providers run refuses the reread as before, while a knowledge grant revoked mid-flight empties the reread's slot, which makes the snapshot differ and surfaces as the retryable `RevisionConflict` rather than a released pack. +Two of the three workflow tools reach knowledge at all, and only they: `deliberate`'s carrier admission and `recall_context`'s knowledge slot. Deliberation settles onto exactly one carrier entry, so the Mind the request names decides it: `space_id` is resolved through the Mind's registry row on the caller's transaction (`MemoryWorkflowBinding::carrier_collection`), and a binding an in-process facade opened may pin its own Mind first. Both readers — the carrier write and the recall slot — resolve through that one lookup, so no workflow consumer can reach a collection other than the admitted Mind's. `absorb` consults no registry row. Adoption consults none either: its destination is the knowledge face's own collection, so a copy it writes is one the admitting peer reads back through `knowledge.get`. A `space_id` with no registry row is the admission refusal, before any carrier access: one `NOT_AUTHORIZED` carrying a fixed message and no `details`, so it never reveals whether a Mind exists. The row never substitutes for a live grant — every carrier write and knowledge read still re-derives the caller's own grants on its own transaction. Recall's slot is independent of the memory page and best effort for the row and the grant: a missing row, or a missing live `knowledge_read` grant in the request's space, returns the memory result with `knowledge: []`, never a refusal. That tolerance covers the row and the grant only — a grant-store read or collection-list failure is not converted into an empty slot; it propagates and fails the recall. With both the row and the grant the slot lists only the admitted Mind's collection under the same disclosure predicate as the served knowledge list, so an `owner`-private entry never reaches the pack. The registry row is the workflow collection allowlist: `create` writes it, it is not read from the wire, and no served argument names a collection, so a peer cannot select one or change a mapping without creating a Mind. `recall_context` keeps serving for a space that is no Mind, with no slot to fill, and `absorb` keeps serving because it never consults the row. Memory authorization, withholding, snapshot revalidation and token budgeting are unchanged by routing and stay separate rules: the page is still the adapter's own ACL and withholding read, so a memory grant revoked while providers run refuses the reread as before, while a knowledge grant revoked mid-flight empties the reread's slot, which makes the snapshot differ and surfaces as the retryable `RevisionConflict` rather than a released pack. Settlement returns its original `SpokeReject` (code, message and details); malformed arguments and `SpiError::InvalidInput` return `InvalidInput`. A `PolicyRejected` policy veto is also `InvalidInput`, with `details.kind = "policy_rejected"` and the host's reason as the message — never `NotAuthorized`, which stays the lost-admission code. A deadline returns `InternalError` with `details.kind = "deadline_exceeded"` and `details.retry_class = "retryable"`: nothing committed, so the caller may repeat the call. That no-write guarantee now also covers an expiry during the store-connection wait inside `commit_cognition`, and an expiry on a connection already in hand before the begin; it stops at `BEGIN IMMEDIATE`, whose wait for SQLite's write lock is outside the request deadline, and a write that has begun keeps its actual or uncertain outcome. [`mind-model.md`](mind-model.md) owns that boundary. The other provider errors return `InternalError` with `details.kind` set to `embeddings_unavailable`, `embedding_failed`, `reasoner_unavailable`, `reasoner_failed`, or `invalid_reasoner_output` as appropriate and carry no retry class; do not reflect provider internals into the wire message. Errors use the signed error envelope, never a success DTO. The client must negotiate each tool id it intends to invoke; descriptor `capability_id` and `op` match, and the responder owns the `mindcore` namespace. @@ -132,7 +143,7 @@ satisfy. A restored face takes the one host-configured source as an `AdoptionRou naming it on the wire and the `KnowledgeScope` the store reads — and no destination setting: the destination is the knowledge face's own collection, the one `knowledge.get`/`list` serve for the admitted peer, so a copy is readable back through that face whenever the peer's admitted selection -admits it. `workflow_routes` selects workflow collections only and plays no part in adoption. The +admits it. The Mind's registry row selects workflow collections only and plays no part in adoption. The Stage 2 handoff at the end of this section names what it must re-implement rather than re-bind. **Admission is the knowledge face's**, composed as `(principals(peer)?, knowledge_admission(peer)?)` @@ -255,16 +266,21 @@ handler set per surface and exposes no per-principal manifest or handler set. **Stage 2 handoff: the single transaction is not in the retained ports.** `crates/mindcore-sqlite` implements `ScopedKnowledgePort` and `HistoryPort` but no `spoke_operations::AdoptionPort`, and the -operation's body — the scope checks, the retirement-chain resolution, the destination read, the -create-only write, the anchor and inherited-governance rules and the typed response — lived in the -removed `crates/mindcore-runtime/src/adoption.rs` (`AdoptionService`). Its one `BEGIN IMMEDIATE` -transaction covered all of that and committed only for `adopted`, rolling back for `already_present` -and for every refusal, so no caller could observe a source read without its destination write and a -refused response left no copy. Stage 2 must re-implement that single transaction before composing -any per-Mind adoption face: a body assembled from separate port calls cannot carry it, because the -destination read and the create-only write would no longer share the source read's snapshot or its -rollback. Connect's `AdoptionPortService` dedup envelope is unchanged by this — it never carried the -transactional guarantee. +operation's body — the destination read, the retirement-chain resolution, the create-only write, the +anchor and inherited-governance rules and the typed response — lived in the removed +`crates/mindcore-runtime/src/adoption.rs` (`AdoptionService`). Its request checks ran before the +transaction: `source_scope_id` against the configured source (`NOT_FOUND`), `destination_scope_id` +against the admitted scope (`NOT_AUTHORIZED`) and a zero `source_revision` (`INVALID_INPUT`) were +answered with no transaction open, so they held no statement and no snapshot. Its one +`BEGIN IMMEDIATE` transaction then covered everything that reads or writes a row — the destination +read, the source's chain resolution, the create-only write, the anchor and the typed response — and +committed only for `adopted`, rolling back for `already_present` and for every refusal, so no caller +could observe a source read without its destination write and a refused response left no copy. +Stage 2 must re-implement that transaction before composing any per-Mind adoption face: a body +assembled from separate port calls cannot carry it, because the destination read and the create-only +write would no longer share the source read's snapshot or its rollback. The pre-transaction request +checks must stay outside it, where a refusal opens nothing. Connect's `AdoptionPortService` dedup +envelope is unchanged by this — it never carried the transactional guarantee. ### Store shape @@ -274,7 +290,7 @@ The runtime serves a **protocol-shaped** store: the memory tables the workflows - No caller-provided principal, scope route, or manifest capability can bypass a host admission or storage guard. - No baseline provider is required for either face and an absent face/tool is denied. Advertisements and handler registrations describe the same capabilities. -- The adoption source is host configuration and the adoption destination is the knowledge face's own collection: no wire value selects either, the request's scope members are only compared against those two, and a source equal to the destination collection, to any route destination or to the destination scope is refused before serving. +- The adoption source is host configuration and the adoption destination is the knowledge face's own collection: no wire value selects either, the request's scope members are only compared against those two, and a source equal to the destination collection, to any Mind's collection registered beside it or to the destination scope is refused before serving. - Adoption's answer reports `destination_entry_id` slot occupancy — occupied or free — and nothing about the occupant: a concealed occupant is byte-identical to a visible one. That disclosure is permitted and no wider than the knowledge face it lands on, whose create-only `put_knowledge_entry` already distinguishes occupied from free while hiding the entry; entry content, revision and visibility stay undisclosed. - Ablation: peer admission plus scoped storage are both required. Connect authenticates the peer and bounds the list request; the store applies the admitted collection and entry rules before reading, revealing or mutating data. - An admitted scope is validated where the face is assembled and again in the store: neither Connect's list merge nor a caller-declared scope may drop or bypass an admitted constraint. @@ -283,7 +299,7 @@ The runtime serves a **protocol-shaped** store: the memory tables the workflows ## Where it lives -- SQLite scoped store beside `crates/mindcore-sqlite/src/knowledge.rs` and its borrowed-transaction helpers; used both by the Knowledge loopback and by `crates/mindcore-runtime`. The same file implements `HistoryPort` for `RoutedKnowledgeStore` and projects the replay onto `RevisionSnapshot`. +- SQLite scoped store beside `crates/mindcore-sqlite/src/knowledge.rs` and its borrowed-transaction helpers; Stage 2 binds it per Mind. The same file implements `HistoryPort` for `RoutedKnowledgeStore` and projects the replay onto `RevisionSnapshot`. - `crates/mindcore-spoke/src/workflows.rs` owns workflow storage admission and the settlement transaction; `crates/mindcore-spi` owns the workflow contracts and their orchestration. - `crates/mindcore-runtime/src/lib.rs` owns `ServeFaces` (manifest metadata, the memory service, the peer-to-principal admission, providers and host tools), the runtime's `MindPorts`, the retired-id filter and `face_capabilities`; Stage 1 composes no knowledge, history or adoption face, so the former `crates/mindcore-runtime/src/history_dedup.rs` (`SqliteHistoryDedupStore`) and `crates/mindcore-runtime/src/adoption.rs` (`AdoptionService`) are removed and a restored face must re-implement them (the two Stage 2 handoff paragraphs above). `spoke-connect`'s `HistoryPortService` and `AdoptionPortService` keep their wire decode, effective-scope check and dedup seams, unused until a face is composed again; `crates/mindcore-runtime/src/tools.rs` owns the served workflow tool registrations and their advertised ABI. `crates/mindcore-runtime/tests/loopback.rs` asserts each advertisement against a signed session, including the three removed families' `CAPABILITY_PORT_MISSING` denial; `crates/mindcore-runtime/tests/surface.rs` asserts their absence from the composed ports and the manifest. diff --git a/crates/mindcore-runtime/tests/loopback.rs b/crates/mindcore-runtime/tests/loopback.rs index 4400bf9c..987ebb2f 100644 --- a/crates/mindcore-runtime/tests/loopback.rs +++ b/crates/mindcore-runtime/tests/loopback.rs @@ -716,6 +716,19 @@ fn deliberate_arguments_in(space: &str) -> Value { }) } +/// One served capture inside `space`: the freeze-gated write the frozen-Mind case needs. +fn absorb_arguments_in(space: &str) -> Value { + json!({ + "request": { + "space_id": space, + "subject_id": SUBJECT, + "capture_scope": { "visibility": "shared" }, + "content": { "text": "a capture into the Mind" }, + "idempotency_key": "cap_loopback", + } + }) +} + /// The cognition read's arguments: the Mind id alone, the same id its memory requests carry. fn cognition_arguments(space: &str) -> Value { json!({ "space_id": space }) @@ -1758,6 +1771,73 @@ async fn a_space_with_no_registry_row_reaches_no_carrier() { ); } +/// A frozen Mind, through the composed surface: a granted caller is served every operation that +/// is not freeze-gated — its recall and the cognition read — while a freeze-gated one outside +/// SPOKE's maintenance allowlist answers `SpaceFrozen`, having passed admission and coverage, and +/// stages nothing. The freeze check follows admission, so only a granted caller ever reaches it. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn a_frozen_mind_serves_reads_and_refuses_a_freeze_gated_write() { + let fixture = Fixture::open().await; + fixture.grant("grt_capture", PRINCIPAL, &["capture"]).await; + let pool = fixture.store.pool(); + sqlx::query("UPDATE memory_spaces SET status = 'frozen' WHERE space_id = ?") + .bind(SPACE) + .execute(&pool) + .await + .expect("freeze the Mind"); + let (_dir, serve) = fixture.serve(); + let surface = surface( + &serve, + faces(hello("runtime", &[]), None, MindProviders::default()), + ); + let session = connect(&surface, &[RECALL_CONTEXT, ABSORB, READ_COGNITION]).await; + + let mut recall = recall_arguments(); + recall["max_tokens"] = json!(4_000); + let pack = expect_ok( + session.adapter.invoke_tool(RECALL_CONTEXT, recall).await, + "recall in a frozen Mind", + ); + assert_eq!( + packed_record_ids(&pack), + ["rec_market", "rec_north_gate"], + "a frozen Mind still serves its granted caller's recall: {pack}" + ); + assert_eq!( + packed_knowledge_ids(&pack), + [CARRIER], + "the frozen Mind's knowledge slot is served too: {pack}" + ); + + let read = expect_ok( + session + .adapter + .invoke_tool(READ_COGNITION, cognition_arguments(SPACE)) + .await, + "the cognition read in a frozen Mind", + ); + assert_eq!(read["carrier_revision"], 1); + assert_eq!(read["records"], json!([])); + + let rejection = expect_reject( + session + .adapter + .invoke_tool(ABSORB, absorb_arguments_in(SPACE)) + .await, + "a capture into a frozen Mind", + ); + assert_eq!( + rejection.code, + SpokeRejectCode::SpaceFrozen, + "a freeze-gated operation outside the allowlist is the frozen refusal: {rejection:?}" + ); + let staged: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM memory_candidates") + .fetch_one(&pool) + .await + .expect("count the candidates"); + assert_eq!(staged, 0, "a frozen Mind stages nothing"); +} + /// Existence privacy: a peer admitted to nothing — no grant in either space — cannot tell an /// existing Mind from an absent one. Both `space_id` variations are answered with the same /// refusal, byte-equal, and neither call reaches the reasoner: the reasoner is absent entirely diff --git a/crates/mindcore-spoke/tests/memory_adapter.rs b/crates/mindcore-spoke/tests/memory_adapter.rs index 7a82bb06..4e3b74b0 100644 --- a/crates/mindcore-spoke/tests/memory_adapter.rs +++ b/crates/mindcore-spoke/tests/memory_adapter.rs @@ -4455,12 +4455,11 @@ async fn receipts_poll_serves_regardless_of_unsettled_intents() { tx.rollback().await.expect("rollback"); } -/// Mind admission (one served surface serves many Minds): an unknown Mind, an -/// ungranted one and a frozen one the caller holds no grant in answer one -/// byte-equal `NOT_AUTHORIZED` with no details — before any coverage check — -/// on every read path whose first lookup was the space row. A granted caller -/// in the frozen Mind is still served a read, because reads are not -/// freeze-gated. +/// Mind admission (one served surface serves many Minds): admission runs before any existence +/// check, so an unknown Mind, an ungranted one and a frozen one the caller holds no grant in +/// answer one byte-equal `NOT_AUTHORIZED` with no details — before any coverage check and before +/// the code could report whether the Mind exists. A granted caller in the frozen Mind is still +/// served a read, because reads are not freeze-gated. #[tokio::test] async fn unknown_ungranted_and_frozen_minds_answer_one_refusal() { let harness = Harness::open().await; diff --git a/docs/concepts.md b/docs/concepts.md index cee4478e..ff8ebb5c 100644 --- a/docs/concepts.md +++ b/docs/concepts.md @@ -122,10 +122,14 @@ identity and verdict: equal attempt content yields an equal id, and another bran ## Trust boundary -- **The host authenticates.** Mindcore never reads a principal from the wire in the runtime; the - host's admission maps an authenticated peer to a scope and a `Principal`. -- **Ports refuse, they do not filter.** A wrong-scope read answers the same refusal as a missing - one; the peer learns nothing about what exists elsewhere. +- **The host authenticates.** Mindcore never reads a principal from the wire; the host's admission + maps an authenticated peer to a `Principal`, and a served call names its own Mind, never a + collection. +- **Admission precedes existence.** A call admits one Mind before it reads anything: an unknown + Mind id, a Mind the caller holds no live grant in, and a frozen Mind it holds none in answer one + `NOT_AUTHORIZED` with no details, so the refusal cannot report whether the Mind exists. +- **Ports refuse, they do not filter.** No result mixes two Minds: a call reads and writes only the + collection its admitted Mind's registry row names, and a refusal names nothing outside it. - **One store per file.** Each opened `MindStore` owns one pool. Two stores on one file are unsupported, not refused. - **A mutating operation takes the write reservation first.** `BEGIN IMMEDIATE` precedes any claim From 4e0e2347902f035ee545d54cb13ecf9fd74e4e54 Mon Sep 17 00:00:00 2001 From: Tang Bohao Date: Thu, 26 Nov 2026 14:35:24 +0800 Subject: [PATCH 14/27] docs(serving): state the per-Mind knowledge contract for a restored face - The restored Knowledge face admits the request's Mind id through A1 and resolves its collection from the registry row; the host-configured route map is gone, not reproduced. - get and put carry the A2 optional scope with its negotiated marker, refused as unsupported rather than dropped, so a read never lands in a default collection; list names the admitted scope as today. - The knowledge refusal table, the adoption destination and assembly rule, and the no-bypass invariant now speak of the admitting Mind instead of a principal route. - Addresses the L2 Important finding in .mstar/sdd/mind-serving-stage1/task-5-review.md. --- .agents/specs/architecture/serving-seam.md | 35 +++++++++++----------- 1 file changed, 18 insertions(+), 17 deletions(-) diff --git a/.agents/specs/architecture/serving-seam.md b/.agents/specs/architecture/serving-seam.md index 659dca35..29a5ba10 100644 --- a/.agents/specs/architecture/serving-seam.md +++ b/.agents/specs/architecture/serving-seam.md @@ -14,19 +14,20 @@ admission, the manifest advertises neither `spoke-knowledge` nor `ke-ownership`, `ScopedKnowledgeStore` and `RoutedKnowledgeStore` stay in `mindcore-sqlite` for Stage 2 to bind per Mind. The paragraphs below state the contract a restored face must satisfy. -A restored face installs a `KnowledgeAdmission` callback in `RemoteKnowledgeFace`. Connect supplies the authenticated peer id; the callback returns the peer's one admitted `Scope` or refuses. An exact host-configured route maps the admitted `scope_id` to `KnowledgeScope.collection` on the bound SQLite pool. No fallback guesses a collection from an entry id, `owner`, `viewpoint`, or Memory `SpaceId`. Memory space and workflow knowledge grants remain separate and go through the existing `MemoryWorkflowBinding` admission. The `ke-ownership` protocol gate checks the negotiated flag for a list with an explicit `viewpoint`; it neither chooses the collection nor grants the peer entry access. +A restored face installs a `KnowledgeAdmission` callback in `RemoteKnowledgeFace`. Connect supplies the authenticated peer id and, through A1, the `scope_id` the request declares; the callback admits that one Mind, resolving the collection and carrier through the Mind's registry row on the caller's own transaction, and returns the admitted `Scope` for that Mind or refuses. There is no host-configured route map to consume and no fallback: no collection is guessed from an entry id, `owner`, `viewpoint` or Memory `SpaceId`, and an unknown Mind id and a Mind the peer holds no grant for answer one `NOT_AUTHORIZED` with no `details`, exactly as the memory path's admission answers. Memory space and workflow knowledge grants remain separate and go through the existing `MemoryWorkflowBinding` admission. The `ke-ownership` protocol gate checks the negotiated flag for a list with an explicit `viewpoint`; it neither chooses the collection nor grants the peer entry access. -`get` and `put` carry no wire scope. `list` names the admitted `scope_id` and `viewpoint`; Connect bounds the request by the admitted scope before calling the store. The scoped adapter binds the collection on every statement. Within it, entry-id, entry-type, source-id and viewpoint filters use SPOKE's knowledge predicate (including owner-private disclosure); an explicit empty set matches nothing. The face does not serve cognition, timeline or extension-based selection; refuse unsupported constraints rather than silently ignoring them. List results are in `entry_id` order. The host admission callback validates the scope it returns with `mindcore_sqlite::validate_admission_scope` before returning it: Connect's list merge keeps only the request's cognition selection, so an admitted cognition selection reaches the collection query unless it is refused at admission. A served list reads at most `SERVED_KNOWLEDGE_LIST_LIMIT` (512) **live** rows of the routed collection — the live predicate rides in the statement — and refuses a larger live set with `InternalError` naming the bound; the bound applies before disclosure filtering and never truncates silently. A retired row therefore never consumes list budget. +`list` names the admitted `scope_id` and `viewpoint`, as it does today, and Connect bounds the request by the admitted scope before calling the store. `get` and `put` carry the optional `scope` member A2 adds, with the negotiable marker saying the responder honours it: a request that names a scope on a responder without the marker is refused as unsupported — wire `op_unsupported`, `CapabilityPortMissing` in the Rust dialer — and never served from a default collection, because a dropped scope would land the read or write in a collection the caller never named. The scoped adapter binds the admitted Mind's collection on every statement. Within it, entry-id, entry-type, source-id and viewpoint filters use SPOKE's knowledge predicate (including owner-private disclosure); an explicit empty set matches nothing. The face does not serve cognition, timeline or extension-based selection; refuse unsupported constraints rather than silently ignoring them. List results are in `entry_id` order. The host admission callback validates the scope it returns with `mindcore_sqlite::validate_admission_scope` before returning it: Connect's list merge keeps only the request's cognition selection, so an admitted cognition selection reaches the collection query unless it is refused at admission. A served list reads at most `SERVED_KNOWLEDGE_LIST_LIMIT` (512) **live** rows of the admitted Mind's collection — the live predicate rides in the statement — and refuses a larger live set with `InternalError` naming the bound; the bound applies before disclosure filtering and never truncates silently. A retired row therefore never consumes list budget. -The peer's route grants read/write knowledge access within its scope, not unconstrained access to the database. `put` checks the proposed payload and any existing row against the admitted constraints on the same `BEGIN IMMEDIATE` transaction, before exposing a revision or committing a change. A missing expected revision keeps create-only semantics; a supplied one performs compare-and-swap through the common store. A hidden existing row is never overwritten, and hidden entry data/revisions are never returned. No operation probes another collection. +The admitted Mind's grants read/write knowledge access within its scope, not unconstrained access to the database. `put` checks the proposed payload and any existing row against the admitted constraints on the same `BEGIN IMMEDIATE` transaction, before exposing a revision or committing a change. A missing expected revision keeps create-only semantics; a supplied one performs compare-and-swap through the common store. A hidden existing row is never overwritten, and hidden entry data/revisions are never returned. No operation probes another collection. | Refusal | Result | |---|---| | Required negotiated family, conditional ownership flag or serving face missing | Wire `op_unsupported`, exposed by the Rust dialer as `CapabilityPortMissing` with `details.wire_code`. | -| Peer unadmitted or list names/widens another scope; unknown trusted route | `NotAuthorized` (`NOT_AUTHORIZED`), no target details. | +| Peer unadmitted, or a request names or widens another Mind's scope | `NotAuthorized` (`NOT_AUTHORIZED`), no target details. | | Host admission returns an unsupported selection | `NotAuthorized`, no target details: refused at admission before Connect merges the scope, so the store is never reached. | +| `get`/`put` carry a `scope` the responder's negotiated marker does not cover | Wire `op_unsupported` (`CapabilityPortMissing` in the Rust dialer): refused, never silently dropped. | | Malformed scope/payload, or a caller-declared (request) scope with an unsupported selection | `InvalidInput`; the unsupported-selection case is refused at the store. The responder's earlier payload-dependent gates still apply. | -| Get id absent or hidden within the routed collection | One generic `KnowledgeEntryNotFound`. An out-of-scope put is `NotAuthorized`. | +| Get id absent or hidden within the admitted Mind's collection | One generic `KnowledgeEntryNotFound`. An out-of-scope put is `NotAuthorized`. | | Admitted create hits an existing visible id; admitted update carries a stale/missing stored revision | `KnowledgeEntryAlreadyExists`; `StoredRevisionStale`, respectively. Preserve backend codes; storage failures are `InternalError`. | ### History @@ -141,14 +142,15 @@ neither `spoke-knowledge-adoption` nor its `spoke-knowledge` co-capability, and call answers `CAPABILITY_PORT_MISSING`. The paragraphs below state the contract a restored face must satisfy. A restored face takes the one host-configured source as an `AdoptionRoute` — a `scope_id` naming it on the wire and the `KnowledgeScope` the store reads — and no destination setting: the -destination is the knowledge face's own collection, the one `knowledge.get`/`list` serve for the -admitted peer, so a copy is readable back through that face whenever the peer's admitted selection -admits it. The Mind's registry row selects workflow collections only and plays no part in adoption. The +destination is the knowledge face's own collection, which on a restored per-Mind face is the +admitting Mind's, the one `knowledge.get`/`list` serve for that Mind, so a copy is readable back +through that face whenever the peer's admitted selection admits it. The Mind's registry row selects +workflow collections only and plays no part in adoption. The Stage 2 handoff at the end of this section names what it must re-implement rather than re-bind. **Admission is the knowledge face's**, composed as `(principals(peer)?, knowledge_admission(peer)?)` -like the history family's: a peer the knowledge face does not admit cannot adopt, and a routed -principal the knowledge admission refuses answers `NOT_AUTHORIZED` where the removed product tool +like the history family's: a peer the knowledge face does not admit cannot adopt, and a principal +the knowledge admission refuses answers `NOT_AUTHORIZED` where the removed product tool would have served it. Neither the principal nor the admitted scope comes from the payload. **Scope mapping.** Every scope member of the request is compared, never used to select anything: @@ -192,12 +194,11 @@ handed that occupant back, so only a copy the caller can already read carries it "existence is never revealed" claim would be false and is not made here. **Assembly** refuses an empty source scope id, an empty source collection, a source collection equal -to `ServeFaces.knowledge`'s collection or to any route destination — including the route of a -principal that is not currently connected — and a source scope id equal to `ServeFaces.scope_id`, -all with `InvalidInput` before any port or registration exists -(`crates/mindcore-runtime/src/lib.rs:105-150`). A source that is also a destination would let one -principal's adopted copy become the shared entry another principal reads, and a source scope equal -to the destination scope would let a principal adopt from its own destination. +to the knowledge face's own collection or to any Mind's registered collection — including a Mind +that is not currently connected — and a source scope id equal to the destination scope, all with +`InvalidInput` before any port or registration exists. A source that is also a destination would let +one Mind's adopted copy become the shared entry another Mind reads, and a source scope equal to the +destination scope would let a Mind adopt from its own destination. **Terminal anchor.** The requested source resolves through `spoke_operations::resolve_retirement_chain` inside the same transaction before anything is read for the copy: a live source resolves to itself, @@ -288,7 +289,7 @@ The runtime serves a **protocol-shaped** store: the memory tables the workflows ## Invariants -- No caller-provided principal, scope route, or manifest capability can bypass a host admission or storage guard. +- No caller-provided principal, Mind id, or manifest capability can bypass a host admission or storage guard. - No baseline provider is required for either face and an absent face/tool is denied. Advertisements and handler registrations describe the same capabilities. - The adoption source is host configuration and the adoption destination is the knowledge face's own collection: no wire value selects either, the request's scope members are only compared against those two, and a source equal to the destination collection, to any Mind's collection registered beside it or to the destination scope is refused before serving. - Adoption's answer reports `destination_entry_id` slot occupancy — occupied or free — and nothing about the occupant: a concealed occupant is byte-identical to a visible one. That disclosure is permitted and no wider than the knowledge face it lands on, whose create-only `put_knowledge_entry` already distinguishes occupied from free while hiding the entry; entry content, revision and visibility stay undisclosed. From 17afdbc005f01568be7cc5ecdc2563d9a5238a61 Mon Sep 17 00:00:00 2001 From: Tang Bohao Date: Thu, 26 Nov 2026 14:37:50 +0800 Subject: [PATCH 15/27] docs(serving): resolve adoption's destination through the admitted Mind - A restored adoption face is composed per Mind: its destination is the admitted Mind's registered collection, resolved through the registry row after admission; no surface-wide destination field and no AdoptionRoute destination to consume. - The source stays the one host-configured Stage 2 route, named by a wire scope_id; it is the only host-configured side of the call. - destination_scope_id must equal the admitted Mind's scope and otherwise answers the target-free NOT_AUTHORIZED, never a comparison against a configured destination. - Assembly refuses a source equal to any Mind's registered collection; copy governance, refusals, the workflow paragraph and the invariant now speak of the admitting Mind. - Both Stage 2 handoff paragraphs stay in place; ServeFaces.knowledge and AdoptionRoute no longer appear in the page. - Addresses the L2 Important finding in .mstar/sdd/mind-serving-stage1/task-5-review.md. --- .agents/specs/architecture/serving-seam.md | 75 +++++++++++----------- 1 file changed, 39 insertions(+), 36 deletions(-) diff --git a/.agents/specs/architecture/serving-seam.md b/.agents/specs/architecture/serving-seam.md index 29a5ba10..4c58ba1e 100644 --- a/.agents/specs/architecture/serving-seam.md +++ b/.agents/specs/architecture/serving-seam.md @@ -123,7 +123,7 @@ An `absorb` run that updates a record and dismisses its candidate stages two int An `absorb` replay reports what an earlier run of the same capture recorded for each consumed candidate. A candidate consumed by the update leg's dismissal is the one consumption whose result names no record, so the binding reads the update leg's own receipt — keyed by the capture key, the candidate id and `update` — for the record id: a committed receipt reports `settled` with that id and an absent one reports `dropped`. Capture and update receipts are rows of one table under one aged policy, and the binding has no per-operation retention branch; the capture receipt is minted first, so an aged-out capture receipt refuses the replay before an aged-out update receipt could be read. -Two of the three workflow tools reach knowledge at all, and only they: `deliberate`'s carrier admission and `recall_context`'s knowledge slot. Deliberation settles onto exactly one carrier entry, so the Mind the request names decides it: `space_id` is resolved through the Mind's registry row on the caller's transaction (`MemoryWorkflowBinding::carrier_collection`), and a binding an in-process facade opened may pin its own Mind first. Both readers — the carrier write and the recall slot — resolve through that one lookup, so no workflow consumer can reach a collection other than the admitted Mind's. `absorb` consults no registry row. Adoption consults none either: its destination is the knowledge face's own collection, so a copy it writes is one the admitting peer reads back through `knowledge.get`. A `space_id` with no registry row is the admission refusal, before any carrier access: one `NOT_AUTHORIZED` carrying a fixed message and no `details`, so it never reveals whether a Mind exists. The row never substitutes for a live grant — every carrier write and knowledge read still re-derives the caller's own grants on its own transaction. Recall's slot is independent of the memory page and best effort for the row and the grant: a missing row, or a missing live `knowledge_read` grant in the request's space, returns the memory result with `knowledge: []`, never a refusal. That tolerance covers the row and the grant only — a grant-store read or collection-list failure is not converted into an empty slot; it propagates and fails the recall. With both the row and the grant the slot lists only the admitted Mind's collection under the same disclosure predicate as the served knowledge list, so an `owner`-private entry never reaches the pack. The registry row is the workflow collection allowlist: `create` writes it, it is not read from the wire, and no served argument names a collection, so a peer cannot select one or change a mapping without creating a Mind. `recall_context` keeps serving for a space that is no Mind, with no slot to fill, and `absorb` keeps serving because it never consults the row. Memory authorization, withholding, snapshot revalidation and token budgeting are unchanged by routing and stay separate rules: the page is still the adapter's own ACL and withholding read, so a memory grant revoked while providers run refuses the reread as before, while a knowledge grant revoked mid-flight empties the reread's slot, which makes the snapshot differ and surfaces as the retryable `RevisionConflict` rather than a released pack. +Two of the three workflow tools reach knowledge at all, and only they: `deliberate`'s carrier admission and `recall_context`'s knowledge slot. Deliberation settles onto exactly one carrier entry, so the Mind the request names decides it: `space_id` is resolved through the Mind's registry row on the caller's transaction (`MemoryWorkflowBinding::carrier_collection`), and a binding an in-process facade opened may pin its own Mind first. Both readers — the carrier write and the recall slot — resolve through that one lookup, so no workflow consumer can reach a collection other than the admitted Mind's. `absorb` consults no registry row. Adoption resolves its destination from the same registry row after admission: it is the admitted Mind's registered collection, so a copy it writes is one the same peer reads back through that Mind's `knowledge.get`. A `space_id` with no registry row is the admission refusal, before any carrier access: one `NOT_AUTHORIZED` carrying a fixed message and no `details`, so it never reveals whether a Mind exists. The row never substitutes for a live grant — every carrier write and knowledge read still re-derives the caller's own grants on its own transaction. Recall's slot is independent of the memory page and best effort for the row and the grant: a missing row, or a missing live `knowledge_read` grant in the request's space, returns the memory result with `knowledge: []`, never a refusal. That tolerance covers the row and the grant only — a grant-store read or collection-list failure is not converted into an empty slot; it propagates and fails the recall. With both the row and the grant the slot lists only the admitted Mind's collection under the same disclosure predicate as the served knowledge list, so an `owner`-private entry never reaches the pack. The registry row is the workflow collection allowlist: `create` writes it, it is not read from the wire, and no served argument names a collection, so a peer cannot select one or change a mapping without creating a Mind. `recall_context` keeps serving for a space that is no Mind, with no slot to fill, and `absorb` keeps serving because it never consults the row. Memory authorization, withholding, snapshot revalidation and token budgeting are unchanged by routing and stay separate rules: the page is still the adapter's own ACL and withholding read, so a memory grant revoked while providers run refuses the reread as before, while a knowledge grant revoked mid-flight empties the reread's slot, which makes the snapshot differ and surfaces as the retryable `RevisionConflict` rather than a released pack. Settlement returns its original `SpokeReject` (code, message and details); malformed arguments and `SpiError::InvalidInput` return `InvalidInput`. A `PolicyRejected` policy veto is also `InvalidInput`, with `details.kind = "policy_rejected"` and the host's reason as the message — never `NotAuthorized`, which stays the lost-admission code. A deadline returns `InternalError` with `details.kind = "deadline_exceeded"` and `details.retry_class = "retryable"`: nothing committed, so the caller may repeat the call. That no-write guarantee now also covers an expiry during the store-connection wait inside `commit_cognition`, and an expiry on a connection already in hand before the begin; it stops at `BEGIN IMMEDIATE`, whose wait for SQLite's write lock is outside the request deadline, and a write that has begun keeps its actual or uncertain outcome. [`mind-model.md`](mind-model.md) owns that boundary. The other provider errors return `InternalError` with `details.kind` set to `embeddings_unavailable`, `embedding_failed`, `reasoner_unavailable`, `reasoner_failed`, or `invalid_reasoner_output` as appropriate and carry no retry class; do not reflect provider internals into the wire message. Errors use the signed error envelope, never a success DTO. The client must negotiate each tool id it intends to invoke; descriptor `capability_id` and `op` match, and the responder owns the `mindcore` namespace. @@ -140,36 +140,38 @@ manifest carries it and no handler answers it even when a host registers the id. Stage 1 composes no adoption face: `ServeFaces` has no adoption setting, `face_capabilities` names neither `spoke-knowledge-adoption` nor its `spoke-knowledge` co-capability, and a `knowledge.adopt` call answers `CAPABILITY_PORT_MISSING`. The paragraphs below state the contract a restored face must -satisfy. A restored face takes the one host-configured source as an `AdoptionRoute` — a `scope_id` -naming it on the wire and the `KnowledgeScope` the store reads — and no destination setting: the -destination is the knowledge face's own collection, which on a restored per-Mind face is the -admitting Mind's, the one `knowledge.get`/`list` serve for that Mind, so a copy is readable back -through that face whenever the peer's admitted selection admits it. The Mind's registry row selects -workflow collections only and plays no part in adoption. The -Stage 2 handoff at the end of this section names what it must re-implement rather than re-bind. - -**Admission is the knowledge face's**, composed as `(principals(peer)?, knowledge_admission(peer)?)` -like the history family's: a peer the knowledge face does not admit cannot adopt, and a principal -the knowledge admission refuses answers `NOT_AUTHORIZED` where the removed product tool -would have served it. Neither the principal nor the admitted scope comes from the payload. +satisfy. A restored face is composed per Mind and bound to one: its destination is that Mind's +registered collection, resolved through the registry row after admission, and there is no +surface-wide destination setting to consume. The source stays host configuration — one collection, +named on the wire by a `scope_id` and fixed by the host — and it is the only host-configured side of +the call. A copy is therefore readable back through the admitting Mind's own +knowledge face whenever the peer's admitted selection admits it. The Stage 2 handoff at the end of +this section names what it must re-implement rather than re-bind. + +**Admission is the admitting Mind's knowledge-face admission**, composed as +`(principals(peer)?, knowledge_admission(peer)?)` like the history family's: a peer the knowledge +face does not admit cannot adopt, and a principal the knowledge admission refuses answers the +target-free `NOT_AUTHORIZED` where the removed product tool would have served it. Neither the +principal nor the admitted scope comes from the payload; the admitted scope is the Mind's own. **Scope mapping.** Every scope member of the request is compared, never used to select anything: | Request member | Must equal | Otherwise | |---|---|---| -| `source_scope_id` | `AdoptionRoute.scope_id` | `NOT_FOUND`, no details — the same generic absence as a missing source | -| `source_entry_id` | a live or retired row of `AdoptionRoute.source` | `NOT_FOUND`, no details | +| `source_scope_id` | the host-configured source's `scope_id` | `NOT_FOUND`, no details — the same generic absence as a missing source | +| `source_entry_id` | a live or retired row of the host-configured source collection | `NOT_FOUND`, no details | | `source_revision` | the live source's current revision; never compared for a retired source; never `0` | `REVISION_CONFLICT`, no details / `INVALID_INPUT` | -| `destination_scope_id` | the admitted `Scope.scope_id` | `NOT_AUTHORIZED`, no details, before the source is read | +| `destination_scope_id` | the admitted Mind's `Scope.scope_id` | the target-free `NOT_AUTHORIZED`, no details, before the source is read | | `destination_entry_id` | absent → the resolved terminal's `source_entry_id`; a supplied value may name that same id | — | | `idempotency_key` | 1–128 code points | `INVALID_INPUT`, refused by Connect's decoder | -The destination collection is `ServeFaces.knowledge` and nothing else. It is one shared collection -with one slot per `destination_entry_id`: the first adoption of a given id claims that slot, and a -later call naming the same id is answered from the stored copy's anchor instead of writing a second -one. The admitted `Scope`'s `entry_ids`, `entry_types`, `source_id` and `viewpoint` refinements -still apply to it, because the admitted scope is the host's statement about which entries of that -collection the peer may reach. +The destination collection is the admitted Mind's registered collection and nothing else: the row +the request's Mind id resolves to, read after admission, never a surface-wide field and never a +wire value. It is that Mind's one collection with one slot per `destination_entry_id`: the first +adoption of a given id claims that slot, and a later call naming the same id is answered from the +stored copy's anchor instead of writing a second one. The admitted `Scope`'s `entry_ids`, +`entry_types`, `source_id` and `viewpoint` refinements still apply to it, because the admitted scope +is the host's statement about which entries of that Mind's collection the peer may reach. Adoption applies them to the destination entry it would return and to the copy it would write: an entry outside the admitted selection is neither served nor written, and answers the ordinary occupancy refusal — `REVISION_CONFLICT` with no details, byte-identical to a visible occupant's — @@ -180,8 +182,9 @@ as an absence by checking the row including superseded ones and answering the sa way no revision gate is reached and no put runs. The invariant is the observable answer — code, message shape and absent `details` — not a shared constructor, and no path reveals the occupant's content, revision or visibility. `NOT_AUTHORIZED` is reserved for a `destination_scope_id` that is -not the admitted scope. The host's configured collection selects the destination; the admitted -selection narrows what the call may touch inside it. +not the admitted Mind's scope: the target-free admission refusal, never a comparison against a +configured destination, which no longer exists. The registry row selects the destination; the +admitted selection narrows what the call may touch inside it. **Slot occupancy is a permitted disclosure.** A create-only destination answers occupied for an occupied id and success for a free one, so the answer reports whether the `destination_entry_id` @@ -194,8 +197,8 @@ handed that occupant back, so only a copy the caller can already read carries it "existence is never revealed" claim would be false and is not made here. **Assembly** refuses an empty source scope id, an empty source collection, a source collection equal -to the knowledge face's own collection or to any Mind's registered collection — including a Mind -that is not currently connected — and a source scope id equal to the destination scope, all with +to any Mind's registered collection — the assembled Mind's own included, and including a Mind that +is not currently connected — and a source scope id equal to the destination scope, all with `InvalidInput` before any port or registration exists. A source that is also a destination would let one Mind's adopted copy become the shared entry another Mind reads, and a source scope equal to the destination scope would let a Mind adopt from its own destination. @@ -224,15 +227,15 @@ terminal; `modules` loses `cognition` rather than keeping an emptied envelope; ` unset; `adoption_anchor` records the terminal triple; `revision`, `created_at` and `updated_at` are left for the store to assign; the request's `extensions` are not copied. `owner` and `disclosure` are inherited from the terminal rather than reset to the destination's, because the destination is -`ServeFaces.knowledge` — the collection the knowledge face serves and the access boundary itself — -and the port refuses every source the viewpoint-free predicate does not see, so an inherited policy -cannot disclose anything the admitted principal could not already read. The copy's `entry_id` is the -caller's `destination_entry_id` when supplied — a caller may supply the terminal's own id — and the -terminal's id otherwise; the anchor names the terminal either way. - -**Refusals and dedup.** The call reads only the host-configured source and writes only -`ServeFaces.knowledge`, committing on one `BEGIN IMMEDIATE` transaction that commits for `adopted` -and rolls back for `already_present`. `NOT_FOUND`, `NOT_AUTHORIZED`, `REVISION_CONFLICT`, +the admitted Mind's registered collection — the collection that Mind's knowledge face serves and the +access boundary itself — and the port refuses every source the viewpoint-free predicate does not see, +so an inherited policy cannot disclose anything the admitted principal could not already read. The +copy's `entry_id` is the caller's `destination_entry_id` when supplied — a caller may supply the +terminal's own id — and the terminal's id otherwise; the anchor names the terminal either way. + +**Refusals and dedup.** The call reads only the host-configured source and writes only the admitted +Mind's registered collection, committing on one `BEGIN IMMEDIATE` transaction that commits for +`adopted` and rolls back for `already_present`. `NOT_FOUND`, `NOT_AUTHORIZED`, `REVISION_CONFLICT`, `SOURCE_RETIRED`, `ADOPTION_ANCHOR_IMMUTABLE` and `INVALID_INPUT` travel as the contract builds them; a repeat naming the copy's own anchor triple returns `already_present` with the stored copy, another revision of the same source is `REVISION_CONFLICT` with exactly `details.adopted_revision`, @@ -291,7 +294,7 @@ The runtime serves a **protocol-shaped** store: the memory tables the workflows - No caller-provided principal, Mind id, or manifest capability can bypass a host admission or storage guard. - No baseline provider is required for either face and an absent face/tool is denied. Advertisements and handler registrations describe the same capabilities. -- The adoption source is host configuration and the adoption destination is the knowledge face's own collection: no wire value selects either, the request's scope members are only compared against those two, and a source equal to the destination collection, to any Mind's collection registered beside it or to the destination scope is refused before serving. +- Adoption's source is the one host-configured Stage 2 route and its destination is the admitted Mind's registered collection, resolved after admission: no wire value selects either, the request's scope members are only compared against those two, a source equal to any Mind's registered collection or to the destination scope is refused before serving, and a `destination_scope_id` that names anything but the admitted Mind's scope answers the target-free refusal. - Adoption's answer reports `destination_entry_id` slot occupancy — occupied or free — and nothing about the occupant: a concealed occupant is byte-identical to a visible one. That disclosure is permitted and no wider than the knowledge face it lands on, whose create-only `put_knowledge_entry` already distinguishes occupied from free while hiding the entry; entry content, revision and visibility stay undisclosed. - Ablation: peer admission plus scoped storage are both required. Connect authenticates the peer and bounds the list request; the store applies the admitted collection and entry rules before reading, revealing or mutating data. - An admitted scope is validated where the face is assembled and again in the store: neither Connect's list merge nor a caller-declared scope may drop or bypass an admitted constraint. From 1bab6f62f95da9ee09e8d2c3c2c1fce021fa90c8 Mon Sep 17 00:00:00 2001 From: Tang Bohao Date: Thu, 26 Nov 2026 15:06:02 +0800 Subject: [PATCH 16/27] fix(serving): admit from the caller's own rows and keep deliberate's refusal split - B1: admit_mind reads the caller's grant rows at the query, so another principal's malformed row is never decoded; a row of the caller's own that cannot decode answers the same target-free refusal. Regression: a stranger's malformed row leaves every refusal byte-equal to an absent space's, and the caller's own live grant still serves the space. - B2: deliberate's host pre-check now runs admission -> space row -> registry row -> knowledge_read coverage, the same split read_cognition uses, so an admitted caller short of the capability gets the coverage refusal instead of the admission one. - Dead grant rows are never projected: coverage runs over live rows, so an unparseable expiry or a revoked row cannot turn a refusal into a storage error. - W1: memory.spaces.list skips a Mind whose only live grant cannot decode, sharing repository::decode_grant_columns with the row read admission uses; a Mind with another decodable live grant stays listed. - W2: deliberate's DB pre-check is charged against the request budget; a spent budget starts nothing, and the workflow gets only the remainder. Unit-tested as remaining_budget. - M1: the specs and MindPorts doc distinguish the responder's raw denial (op_unsupported for knowledge, capability_missing for history and adoption) from the typed CapabilityPortMissing the dialer surfaces. - F-001: the dead participates check is gone from get_receipt_body; admit_mind no longer returns the unused space row, so the 12 bindings drop it. - Removes the dead routes helper and the unused caller parameter left by the retired route map (clippy --all-targets -D warnings). - Addresses B1, B2, W1, W2, M1 and F-001 of .mstar/sdd/mind-serving-stage1/review/qc-consolidated.md; F-002/F-003 untouched. --- .../architecture/serving-principal-routing.md | 4 +- .agents/specs/architecture/serving-seam.md | 12 +- crates/mindcore-runtime/src/lib.rs | 7 +- crates/mindcore-runtime/src/tools.rs | 23 ++- crates/mindcore-runtime/src/tools/tests.rs | 115 ++++++++++- crates/mindcore-runtime/tests/loopback.rs | 74 +++++-- crates/mindcore-spoke/src/admission.rs | 67 ++++--- crates/mindcore-spoke/src/content.rs | 30 +-- crates/mindcore-spoke/src/control.rs | 6 +- crates/mindcore-spoke/src/reflection.rs | 6 +- crates/mindcore-spoke/src/workflows.rs | 40 ++-- crates/mindcore-spoke/tests/memory_adapter.rs | 183 ++++++++++++++++++ crates/mindcore-spoke/tests/workflows.rs | 39 ++-- crates/mindcore-sqlite/src/minds.rs | 66 +++++-- crates/mindcore-sqlite/src/repository.rs | 20 +- 15 files changed, 536 insertions(+), 156 deletions(-) diff --git a/.agents/specs/architecture/serving-principal-routing.md b/.agents/specs/architecture/serving-principal-routing.md index 37cc46ad..7d0fb6ef 100644 --- a/.agents/specs/architecture/serving-principal-routing.md +++ b/.agents/specs/architecture/serving-principal-routing.md @@ -89,7 +89,9 @@ destination is the knowledge face's own collection. Stage 1 therefore composes n - the manifest advertises no `spoke-knowledge`, `ke-ownership`, `spoke-history` or `spoke-knowledge-adoption`, and the runtime's `MindPorts` answers `None` for every family but memory; -- a call to each answers `CAPABILITY_PORT_MISSING` on the responder's dispatch-deny branch. +- a call to each is refused on the responder's dispatch-deny branch — raw wire `op_unsupported` for + the knowledge family, `capability_missing` for history and adoption, each surfaced by the Rust + dialer as `CapabilityPortMissing` with `details.wire_code`. They return per Mind in Stage 2, once SPOKE carries request-scoped admission and an optional scope on knowledge get and put (`2026-11-25-one-surface-serves-many-minds.md`). Their contracts stay diff --git a/.agents/specs/architecture/serving-seam.md b/.agents/specs/architecture/serving-seam.md index 4c58ba1e..69520bb8 100644 --- a/.agents/specs/architecture/serving-seam.md +++ b/.agents/specs/architecture/serving-seam.md @@ -10,7 +10,8 @@ Signed Rust SPOKE sessions over a host-supplied transport: the Memory face, the Stage 1 composes no knowledge face: `ServeFaces` carries no scope, collection or knowledge admission, the manifest advertises neither `spoke-knowledge` nor `ke-ownership`, and every -`port.knowledge.*` op answers `CAPABILITY_PORT_MISSING` on the responder's dispatch-deny branch. +`port.knowledge.*` op is refused on the responder's dispatch-deny branch — raw wire `op_unsupported`, +which the Rust dialer surfaces as `CapabilityPortMissing` with `details.wire_code`. `ScopedKnowledgeStore` and `RoutedKnowledgeStore` stay in `mindcore-sqlite` for Stage 2 to bind per Mind. The paragraphs below state the contract a restored face must satisfy. @@ -34,7 +35,7 @@ The admitted Mind's grants read/write knowledge access within its scope, not unc The `spoke-history` family publishes two operations over the same signed session: `history.revisions.get` returns a `RevisionSnapshot`, `history.revisions.prune` returns `HistoryPruneResult { deleted, floor_revision }` where `floor_revision` is the local report's floor. -Stage 1 composes no history face: `ServeFaces` carries no history switch, `face_capabilities` advertises no `spoke-history`, and both operations answer `CAPABILITY_PORT_MISSING` on the responder's dispatch-deny branch. The paragraphs below state the contract a restored face must satisfy, and the Stage 2 handoff at the end of this section names what it must re-implement rather than re-bind. +Stage 1 composes no history face: `ServeFaces` carries no history switch, `face_capabilities` advertises no `spoke-history`, and both operations are refused on the responder's dispatch-deny branch — raw wire `capability_missing`, surfaced by the Rust dialer as `CapabilityPortMissing` with `details.wire_code`. The paragraphs below state the contract a restored face must satisfy, and the Stage 2 handoff at the end of this section names what it must re-implement rather than re-bind. One store fills two port roles: `RoutedKnowledgeStore` implements `spoke_operations::HistoryPort` beside `ScopedKnowledgePort`, so no second store module exists and the runtime owns no second history implementation — only the dedup record beside it. Admission is the knowledge face's, composed as `HistoryAdmission = (principals(peer)?, knowledge_admission(peer)?)`: a peer outside either callback gets that callback's refusal, and can therefore replay and prune exactly the scope it reads and writes through `port.knowledge.*`. Connect compares a present request `scope` with the admitted scope before calling the port — `NOT_FOUND` on get, `NOT_AUTHORIZED` on prune — and the port re-applies `RoutedKnowledgeStore::admit` as its own guard. @@ -139,8 +140,9 @@ manifest carries it and no handler answers it even when a host registers the id. Stage 1 composes no adoption face: `ServeFaces` has no adoption setting, `face_capabilities` names neither `spoke-knowledge-adoption` nor its `spoke-knowledge` co-capability, and a `knowledge.adopt` -call answers `CAPABILITY_PORT_MISSING`. The paragraphs below state the contract a restored face must -satisfy. A restored face is composed per Mind and bound to one: its destination is that Mind's +call is refused on the responder's dispatch-deny branch — raw wire `capability_missing`, surfaced by +the Rust dialer as `CapabilityPortMissing` with `details.wire_code`. The paragraphs below state the +contract a restored face must satisfy. A restored face is composed per Mind and bound to one: its destination is that Mind's registered collection, resolved through the registry row after admission, and there is no surface-wide destination setting to consume. The source stays host configuration — one collection, named on the wire by a `scope_id` and fixed by the host — and it is the only host-configured side of @@ -298,7 +300,7 @@ The runtime serves a **protocol-shaped** store: the memory tables the workflows - Adoption's answer reports `destination_entry_id` slot occupancy — occupied or free — and nothing about the occupant: a concealed occupant is byte-identical to a visible one. That disclosure is permitted and no wider than the knowledge face it lands on, whose create-only `put_knowledge_entry` already distinguishes occupied from free while hiding the entry; entry content, revision and visibility stay undisclosed. - Ablation: peer admission plus scoped storage are both required. Connect authenticates the peer and bounds the list request; the store applies the admitted collection and entry rules before reading, revealing or mutating data. - An admitted scope is validated where the face is assembled and again in the store: neither Connect's list merge nor a caller-declared scope may drop or bypass an admitted constraint. -- History grants no access the knowledge face does not: both `history.*` ops admit through the knowledge face's two callbacks and the routed store's own `admit`, so a peer replays and prunes exactly the scope it reads and writes. Stage 1 composes no history face, so `face_capabilities` names no `spoke-history` and both ops answer `CAPABILITY_PORT_MISSING`. +- History grants no access the knowledge face does not: both `history.*` ops admit through the knowledge face's two callbacks and the routed store's own `admit`, so a peer replays and prunes exactly the scope it reads and writes. Stage 1 composes no history face, so `face_capabilities` names no `spoke-history` and both ops are refused on the dispatch-deny branch — raw wire `capability_missing`, surfaced as `CapabilityPortMissing`. - Every served `deliberate` response carries the judgment its own attempt produced, and every judgment it carries passed the released validator before the call returned; the identity rule [`mind-model.md`](mind-model.md) states holds on the wire, and `spoke-judgment` is advertised exactly with the tool. ## Where it lives diff --git a/crates/mindcore-runtime/src/lib.rs b/crates/mindcore-runtime/src/lib.rs index 43c9a386..197a6786 100644 --- a/crates/mindcore-runtime/src/lib.rs +++ b/crates/mindcore-runtime/src/lib.rs @@ -131,9 +131,10 @@ impl MindcoreServe { /// The runtime's own ports: the one face this surface carries is the host's memory service. /// -/// The other families stay absent — the responder answers their ops on its dispatch-deny branch -/// as `CAPABILITY_PORT_MISSING` — because none of them can name a Mind yet; each is composed per -/// Mind once SPOKE carries that contract. +/// The other families stay absent — a call to each is refused on the responder's dispatch-deny +/// branch, raw wire `op_unsupported` for knowledge and `capability_missing` for history and +/// adoption, which the Rust dialer surfaces as `CapabilityPortMissing` — because none of them can +/// name a Mind yet; each is composed per Mind once SPOKE carries that contract. struct MindPorts { memory: Option>, } diff --git a/crates/mindcore-runtime/src/tools.rs b/crates/mindcore-runtime/src/tools.rs index 55e7fac4..e9d00e14 100644 --- a/crates/mindcore-runtime/src/tools.rs +++ b/crates/mindcore-runtime/src/tools.rs @@ -12,7 +12,7 @@ use std::num::NonZeroUsize; use std::sync::{Arc, Weak}; -use std::time::Duration; +use std::time::{Duration, Instant}; use serde::de::DeserializeOwned; use serde::Deserialize; @@ -315,6 +315,12 @@ async fn absorb( } } +/// The budget the workflow still has after `spent`: a pre-check that consumed the request's +/// deadline leaves `None`, and a zero remainder is spent rather than an empty allowance. +fn remaining_budget(budget: Duration, spent: Duration) -> Option { + budget.checked_sub(spent).filter(|left| !left.is_zero()) +} + async fn deliberate( workflows: &dyn MindWorkflows, principal: &Principal, @@ -326,12 +332,17 @@ async fn deliberate( Ok(arguments) => arguments, Err(reject) => return SpokeResult::Reject(reject), }; + // The request's budget covers the whole call, and this pre-check is part of it: the DB read + // cannot be preempted, so its wall time is charged against the workflow's deadline instead. + let budget = Duration::from_millis(arguments.timeout_ms.get() as u64); + let started = Instant::now(); // Admission before existence, in one transaction: the grant rows and the registry row are // read together, so a revocation cannot land between them, and the liveness rule is the // adapter's own (`live_grant` — unrevoked, unexpired, an unparseable expiry fails closed). // A missing grant, a revoked or expired one and a space with no registry row are the same - // refusal — same code, same message, no details — so a caller can never tell an existing - // Mind from an absent one by varying `space_id`. + // target-free refusal, so a caller can never tell an existing Mind from an absent one by + // varying `space_id`; a caller the Mind admits without `knowledge_read` answers the coverage + // refusal instead. let carrier_entry_id = match mindcore_spoke::admitted_carrier_entry( pool, &principal.principal_id, @@ -342,6 +353,10 @@ async fn deliberate( Ok(carrier_entry_id) => carrier_entry_id, Err(reject) => return SpokeResult::Reject(reject), }; + // A budget the pre-check already spent starts nothing: no reasoner, no carrier write. + let Some(timeout) = remaining_budget(budget, started.elapsed()) else { + return SpokeResult::Reject(workflow_retryable("deadline_exceeded")); + }; let holder: CognitionReference = match serde_json::from_value(json!({ "kind": "knowledge_entry", "namespace": "mindcore", @@ -371,7 +386,7 @@ async fn deliberate( holder: &holder, target: &arguments.target, evidence: &evidence, - timeout: Duration::from_millis(arguments.timeout_ms.get() as u64), + timeout, }; let caps = providers.capabilities(); match workflows diff --git a/crates/mindcore-runtime/src/tools/tests.rs b/crates/mindcore-runtime/src/tools/tests.rs index ef4ccbb6..2f7ca8f4 100644 --- a/crates/mindcore-runtime/src/tools/tests.rs +++ b/crates/mindcore-runtime/src/tools/tests.rs @@ -712,14 +712,28 @@ async fn deliberate_round_trips_every_outcome_branch() { "a no_change outcome carries no draft" ); + let seen = fake.seen(); assert_eq!( - fake.seen(), - [ - "deliberate:prn_driver:spc_1:subj_1:5000:ev_1", - "deliberate:prn_driver:spc_1:subj_1:5000:ev_1", - "deliberate:prn_driver:spc_1:subj_1:5000:ev_1", - ] + seen.len(), + 3, + "each branch runs the workflow once: {seen:?}" ); + for entry in &seen { + let fields: Vec<&str> = entry.split(':').collect(); + assert_eq!( + &fields[..4], + ["deliberate", "prn_driver", "spc_1", "subj_1"], + "{entry}" + ); + assert_eq!(fields[5], "ev_1", "{entry}"); + let timeout: u64 = fields[4] + .parse() + .expect("the recorded call ends with its remaining budget in milliseconds"); + assert!( + (1..=5_000).contains(&timeout), + "the pre-check is charged against the request's budget: {entry}" + ); + } } #[tokio::test] @@ -915,6 +929,89 @@ async fn read_cognition_serves_a_judgment_or_a_null_state() { ); } +/// The served `deliberate` keeps the plan's refusal split: a caller the Mind admits without a +/// space-wide `knowledge_read` grant answers the coverage refusal, while an unadmitted Mind and +/// an absent one answer one byte-equal, detail-free admission refusal. Neither refusal reaches +/// the workflow. +#[tokio::test] +async fn deliberate_refuses_coverage_after_admission() { + let fake = Arc::new(Fake::default()); + fake.reply_deliberate(Ok(DeliberateOutcome::NoChange { + verdict: json!({}), + judgment: judgment(), + })); + let tool = tools(Arc::clone(&fake)).await; + + let mut uncovered_arguments = deliberate_arguments(); + uncovered_arguments["space_id"] = json!("spc_4"); + let uncovered = expect_reject( + tool.call(DELIBERATE, "peer-driver", uncovered_arguments) + .await, + "an admitted caller without knowledge_read", + ); + assert_eq!(uncovered.code, SpokeRejectCode::NotAuthorized); + assert!( + uncovered.message.contains("knowledge_read"), + "the coverage refusal names the capability the caller lacks: {uncovered:?}" + ); + assert_ne!( + uncovered.details, None, + "a coverage gap cannot be retried away: {uncovered:?}" + ); + + let mut unadmitted_arguments = deliberate_arguments(); + unadmitted_arguments["space_id"] = json!("spc_3"); + let unadmitted = expect_reject( + tool.call(DELIBERATE, "peer-driver", unadmitted_arguments) + .await, + "a Mind the caller is not admitted to", + ); + let mut absent_arguments = deliberate_arguments(); + absent_arguments["space_id"] = json!("spc_absent"); + let absent = expect_reject( + tool.call(DELIBERATE, "peer-driver", absent_arguments).await, + "a space that does not exist", + ); + assert_eq!(unadmitted.code, SpokeRejectCode::NotAuthorized); + assert_eq!( + unadmitted.details, None, + "an admission refusal discloses no details" + ); + assert_eq!( + unadmitted, absent, + "an unadmitted Mind and an absent one are one answer" + ); + assert_ne!( + uncovered, unadmitted, + "an admitted caller short of one capability is not an unadmitted caller" + ); + assert!( + fake.seen().is_empty(), + "no refusal above reaches the workflow" + ); +} + +/// The pre-check is charged against the request's budget: the workflow gets the remainder, and a +/// budget the pre-check already spent starts nothing. +#[test] +fn the_deliberation_budget_covers_its_pre_check() { + let budget = Duration::from_millis(5_000); + assert_eq!( + remaining_budget(budget, Duration::from_millis(1_500)), + Some(Duration::from_millis(3_500)) + ); + assert_eq!( + remaining_budget(budget, budget), + None, + "a spent budget has no remainder" + ); + assert_eq!( + remaining_budget(budget, Duration::from_millis(6_000)), + None, + "an overrun leaves nothing to start" + ); +} + #[tokio::test] async fn settlement_refusals_keep_their_code_and_details() { let refusal = SpokeReject { @@ -1081,6 +1178,12 @@ async fn advertised_input_schemas_match_the_decoded_arguments() { if matches!(capability_id, DELIBERATE | READ_COGNITION) { arguments["space_id"] = json!("spc_1"); } + // The pre-check is charged against the request's budget, so this probe names a budget + // that a process-scheduled pre-check cannot spend: the probe measures the ABI, not the + // clock. + if capability_id == DELIBERATE { + arguments["timeout_ms"] = json!(30_000); + } expect_ok( tool.call(capability_id, "peer-driver", arguments.clone()) .await, diff --git a/crates/mindcore-runtime/tests/loopback.rs b/crates/mindcore-runtime/tests/loopback.rs index 987ebb2f..102c1724 100644 --- a/crates/mindcore-runtime/tests/loopback.rs +++ b/crates/mindcore-runtime/tests/loopback.rs @@ -1936,14 +1936,17 @@ async fn a_strangers_malformed_grant_row_cannot_leak_the_minds_existence() { ); } -/// Liveness is the adapter's one grant rule: an expiry that does not parse fails closed, so the -/// grant is dead and `deliberate` is the admission refusal, not a read of the carrier. +/// Liveness is the adapter's one grant rule: an expiry that does not parse fails closed, so a +/// dead row covers nothing. With the caller's `recall` grant still live the Mind admits it and +/// the dead `knowledge_read` grant is the coverage gap that answers; once every row is dead the +/// answer is the one target-free admission refusal, and no carrier is read either way. #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn a_grant_with_an_unparseable_expiry_is_dead_to_deliberate() { let fixture = Fixture::open().await; + let pool = fixture.store.pool(); // Corrupt the seeded knowledge grant's expiry in place: it can no longer be read as a time. sqlx::query("UPDATE memory_grants SET expires_at = 'not-a-time' WHERE grant_id = 'grt_knowledge'") - .execute(&fixture.store.pool()) + .execute(&pool) .await .expect("corrupt the expiry"); let (_dir, serve) = fixture.serve(); @@ -1956,23 +1959,51 @@ async fn a_grant_with_an_unparseable_expiry_is_dead_to_deliberate() { let surface = surface(&serve, faces); let session = connect(&surface, &[DELIBERATE]).await; - let reject = expect_reject( + let uncovered = expect_reject( session .adapter .invoke_tool(DELIBERATE, deliberate_arguments()) .await, - "deliberate with a garbled expiry", + "deliberate with a dead knowledge_read grant", ); - assert_eq!(reject.code, SpokeRejectCode::NotAuthorized); + assert_eq!(uncovered.code, SpokeRejectCode::NotAuthorized); assert!( - reject.details.is_none(), - "an unparseable expiry fails closed as the plain admission refusal: {reject:?}" + uncovered.message.contains("knowledge_read"), + "the dead row covers nothing, so the coverage refusal answers: {uncovered:?}" + ); + assert_eq!( + uncovered + .details + .as_ref() + .and_then(|details| details.get("retry_class")) + .and_then(Value::as_str), + Some("terminal"), + "a dead grant cannot be retried away: {uncovered:?}" + ); + + // Every row dead now: no live grant admits the caller, so the answer is target-free. + sqlx::query("UPDATE memory_grants SET expires_at = 'not-a-time' WHERE grant_id = 'grt_recall'") + .execute(&pool) + .await + .expect("corrupt the recall expiry"); + let rejected = expect_reject( + session + .adapter + .invoke_tool(DELIBERATE, deliberate_arguments()) + .await, + "deliberate with every grant dead", + ); + assert_eq!(rejected.code, SpokeRejectCode::NotAuthorized); + assert!( + rejected.details.is_none(), + "an unparseable expiry fails closed as the plain admission refusal: {rejected:?}" ); } -/// Revocation is final at call time: the grant is live when the session is established, revoked -/// before the invoke, and the call answers the admission refusal — the admission reads its -/// state once, on its own transaction, and never a cached yes. +/// Revocation is final at call time, and the refusal split is the plan's: the admission reads its +/// state once, on its own transaction, and never a cached yes. A revoked `knowledge_read` grant +/// on a caller the Mind still admits is the coverage gap; with every grant revoked the answer is +/// the one target-free admission refusal. #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn a_grant_revoked_before_the_call_refuses_deliberate() { let fixture = Fixture::open().await; @@ -1993,12 +2024,31 @@ async fn a_grant_revoked_before_the_call_refuses_deliberate() { .execute(&pool) .await .expect("revoke the grant"); + let uncovered = expect_reject( + session + .adapter + .invoke_tool(DELIBERATE, deliberate_arguments()) + .await, + "deliberate after the knowledge grant is revoked", + ); + assert_eq!(uncovered.code, SpokeRejectCode::NotAuthorized); + assert!( + uncovered.message.contains("knowledge_read"), + "a revoked row covers nothing, so the coverage refusal answers: {uncovered:?}" + ); + + sqlx::query( + "UPDATE memory_grants SET revoked_at = '2026-11-21T01:00:00Z' WHERE grant_id = 'grt_recall'", + ) + .execute(&pool) + .await + .expect("revoke the recall grant"); let reject = expect_reject( session .adapter .invoke_tool(DELIBERATE, deliberate_arguments()) .await, - "deliberate after revocation", + "deliberate after every grant is revoked", ); assert_eq!(reject.code, SpokeRejectCode::NotAuthorized); assert!( diff --git a/crates/mindcore-spoke/src/admission.rs b/crates/mindcore-spoke/src/admission.rs index 26d16ef2..50737da0 100644 --- a/crates/mindcore-spoke/src/admission.rs +++ b/crates/mindcore-spoke/src/admission.rs @@ -14,7 +14,7 @@ use mindcore_base::ir::{ MemoryRepository, MemorySpaceRow, MemorySubjectRow, Placement, ReceiptKey, ReceiptRead, ReviewReceiptIr, }; -use mindcore_sqlite::SqliteMemoryRepository; +use mindcore_sqlite::{SqliteMemoryRepository, SqliteRepositoryError}; use spoke_operations::SpokeResult; use spoke_operations::{ grant_covers, is_freeze_allowlisted, validate_grant_issuance, GrantRequirement, IssuedGrant, @@ -216,25 +216,33 @@ pub(crate) fn candidate_requirement<'a>( /// The registry is not consulted here: a space written before it is still a /// space to `memory.*`; the registry gates only `memory.spaces.list` and the /// Mind-level reads. +/// +/// The read is filtered to the caller's own rows at the query. Another +/// principal's malformed row is therefore never decoded and can neither turn +/// this refusal into a storage error nor tell the caller the space exists; a +/// row of the caller's own that cannot decode admits nothing and answers the +/// same target-free refusal. pub(crate) async fn admit_mind( repository: &SqliteMemoryRepository, tx: &mut Tx<'_>, principal: &str, space: &SpaceId, -) -> AResult<(Vec, MemorySpaceRow)> { - let rows = grants(repository, tx, space).await?; +) -> AResult> { + let rows = repository + .list_grants(tx, space, Some(principal)) + .await + .map_err(|error| match error { + SqliteRepositoryError::InvalidRow(_) => Reject::admission_refusal(), + other => Reject::internal(format!("the mind admission could not be read: {other}")), + })?; let now = Utc::now(); - let admitted = rows - .iter() - .any(|row| row.principal_id.as_str() == principal && live_grant(row, now)); - if !admitted { + if !rows.iter().any(|row| live_grant(row, now)) { return Err(Reject::admission_refusal()); } - let row = match repository.space(tx, space).await? { - Some(row) => row, - None => return Err(Reject::admission_refusal()), - }; - Ok((rows, row)) + match repository.space(tx, space).await? { + Some(_) => Ok(rows), + None => Err(Reject::admission_refusal()), + } } pub(crate) async fn space( @@ -308,18 +316,32 @@ pub(crate) async fn grants( /// The protocol's own coverage evaluator takes the wire grant union; the stored /// row projects to it losslessly. pub(crate) fn wire_grants(rows: &[MemoryGrantRow]) -> AResult> { + rows.iter().map(wire_grant).collect() +} + +/// The wire union coverage is evaluated over: only rows that are still live. A dead row — +/// revoked, expired, or carrying an expiry that does not parse — covers nothing, and projecting +/// one could fail on its stored spelling, so it never reaches the projection and can never turn +/// a refusal into a storage error. +pub(crate) fn live_wire_grants( + rows: &[MemoryGrantRow], + now: DateTime, +) -> AResult> { rows.iter() - .map(|row| { - serde_json::from_value(project::grant_body(row)).map_err(|error| { - Reject::terminal( - spoke_operations::SpokeRejectCode::InternalError, - format!("stored grant projection: {error}"), - ) - }) - }) + .filter(|row| live_grant(row, now)) + .map(wire_grant) .collect() } +fn wire_grant(row: &MemoryGrantRow) -> AResult { + serde_json::from_value(project::grant_body(row)).map_err(|error| { + Reject::terminal( + spoke_operations::SpokeRejectCode::InternalError, + format!("stored grant projection: {error}"), + ) + }) +} + pub(crate) fn covered( grants: &[MemoryGrant], principal: &str, @@ -471,9 +493,8 @@ pub(crate) async fn authorize( admission: &Admission<'_>, now: DateTime, ) -> AResult> { - let (rows, _space) = - admit_mind(repository, tx, admission.principal, admission.space).await?; - let wire = wire_grants(&rows)?; + let rows = admit_mind(repository, tx, admission.principal, admission.space).await?; + let wire = live_wire_grants(&rows, now)?; let space_id = admission.space.as_str(); match &admission.coverage { Coverage::Requirements(requirements) => { diff --git a/crates/mindcore-spoke/src/content.rs b/crates/mindcore-spoke/src/content.rs index 88d39a8d..04526670 100644 --- a/crates/mindcore-spoke/src/content.rs +++ b/crates/mindcore-spoke/src/content.rs @@ -339,8 +339,7 @@ impl MemoryAdapter { None => None, }; let now = Utc::now(); - let (rows, _space) = - admission::admit_mind(&self.repository, tx, principal_id, &space).await?; + let rows = admission::admit_mind(&self.repository, tx, principal_id, &space).await?; let wire_grants = admission::wire_grants(&rows)?; let base = GrantRequirement { capability: "review", @@ -439,8 +438,7 @@ impl MemoryAdapter { let principal_id = principal_id(principal); let space = SpaceId::new(request.space_id.to_string()); let candidate_id = request.candidate_id.to_string(); - let (rows, _space) = - admission::admit_mind(&self.repository, tx, principal_id, &space).await?; + let rows = admission::admit_mind(&self.repository, tx, principal_id, &space).await?; let Some(head) = admission::candidate_head(&self.repository, tx, &space, candidate_id.as_str()).await? else { @@ -691,8 +689,7 @@ impl MemoryAdapter { let principal_id = principal_id(principal); let space = SpaceId::new(request.space_id.to_string()); let record_id = request.record_id.to_string(); - let (rows, _space) = - admission::admit_mind(&self.repository, tx, principal_id, &space).await?; + let rows = admission::admit_mind(&self.repository, tx, principal_id, &space).await?; let wire_grants = admission::wire_grants(&rows)?; let now = Utc::now(); let Some(head) = @@ -770,8 +767,7 @@ impl MemoryAdapter { let kinds = request.kinds.clone(); let include_tombstoned = request.include_tombstoned; let now = Utc::now(); - let (rows, _space) = - admission::admit_mind(&self.repository, tx, principal_id, &space).await?; + let rows = admission::admit_mind(&self.repository, tx, principal_id, &space).await?; let wire_grants = admission::wire_grants(&rows)?; let list = admission::covered( &wire_grants, @@ -1298,8 +1294,7 @@ impl MemoryAdapter { let subject_id = request.subject_id.to_string(); let (placement, filter) = read_selection(object)?; let now = Utc::now(); - let (rows, _space) = - admission::admit_mind(&self.repository, tx, principal_id, &space).await?; + let rows = admission::admit_mind(&self.repository, tx, principal_id, &space).await?; let wire_grants = admission::wire_grants(&rows)?; if !admission::covered( &wire_grants, @@ -1444,8 +1439,7 @@ impl MemoryAdapter { let principal_id = principal_id(principal); let space = SpaceId::new(request.space_id.to_string()); let subject_id = request.subject_id.to_string(); - let (rows, _space) = - admission::admit_mind(&self.repository, tx, principal_id, &space).await?; + let rows = admission::admit_mind(&self.repository, tx, principal_id, &space).await?; if !admission::profile_visible( &rows, principal_id, @@ -1621,19 +1615,9 @@ impl MemoryAdapter { let principal_id = principal_id(principal); let space = SpaceId::new(request.space_id.to_string()); let receipt_id = request.receipt_id.to_string(); - let (rows, _space) = - admission::admit_mind(&self.repository, tx, principal_id, &space).await?; + let rows = admission::admit_mind(&self.repository, tx, principal_id, &space).await?; let wire_grants = admission::wire_grants(&rows)?; let now = Utc::now(); - let participates = rows.iter().any(|row| { - row.principal_id.as_str() == principal_id && admission::live_grant(row, now) - }); - if !participates { - return Err(Reject::not_authorized(format!( - "principal {principal_id} does not participate in space {}", - space.as_str() - ))); - } let admin = admission::covered( &wire_grants, principal_id, diff --git a/crates/mindcore-spoke/src/control.rs b/crates/mindcore-spoke/src/control.rs index 7dffa321..464d9a51 100644 --- a/crates/mindcore-spoke/src/control.rs +++ b/crates/mindcore-spoke/src/control.rs @@ -368,8 +368,7 @@ impl MemoryAdapter { let principal_id = principal_id(principal); let space = SpaceId::new(request.space_id.to_string()); let subject_id = request.subject_id.as_str(); - let (rows, _space_row) = - admission::admit_mind(&self.repository, tx, principal_id, &space).await?; + let rows = admission::admit_mind(&self.repository, tx, principal_id, &space).await?; if !admission::any_grant_for_subject( &rows, principal_id, @@ -512,8 +511,7 @@ impl MemoryAdapter { let principal_id = principal_id(principal); let space = SpaceId::new(request.space_id.to_string()); let now = Utc::now(); - let (rows, _space_row) = - admission::admit_mind(&self.repository, tx, principal_id, &space).await?; + let rows = admission::admit_mind(&self.repository, tx, principal_id, &space).await?; let wire_grants = admission::wire_grants(&rows)?; let admin = admission::covered( &wire_grants, diff --git a/crates/mindcore-spoke/src/reflection.rs b/crates/mindcore-spoke/src/reflection.rs index 703a92ce..52710a15 100644 --- a/crates/mindcore-spoke/src/reflection.rs +++ b/crates/mindcore-spoke/src/reflection.rs @@ -123,8 +123,7 @@ impl MemoryAdapter { let subject_id = request.subject_id.to_string(); let (selection, filter) = read_selection(object)?; let now = Utc::now(); - let (rows, _space_row) = - admission::admit_mind(&self.repository, tx, principal_id, &space).await?; + let rows = admission::admit_mind(&self.repository, tx, principal_id, &space).await?; let wire_grants = admission::wire_grants(&rows)?; let base = admission::selection_requirement("reflect", subject_id.as_str(), &selection); if !admission::covered(&wire_grants, principal_id, space.as_str(), now, &base) { @@ -212,8 +211,7 @@ impl MemoryAdapter { }; let filter = wire::PlacementSelectionWire::filter(object, "filter")?; let now = Utc::now(); - let (rows, _space_row) = - admission::admit_mind(&self.repository, tx, principal_id, &space).await?; + let rows = admission::admit_mind(&self.repository, tx, principal_id, &space).await?; let wire_grants = admission::wire_grants(&rows)?; let base = admission::selection_requirement("reflect", subject_id.as_str(), &requested); if !admission::covered(&wire_grants, principal_id, space.as_str(), now, &base) { diff --git a/crates/mindcore-spoke/src/workflows.rs b/crates/mindcore-spoke/src/workflows.rs index c76fd0b4..f4fafc80 100644 --- a/crates/mindcore-spoke/src/workflows.rs +++ b/crates/mindcore-spoke/src/workflows.rs @@ -62,14 +62,15 @@ pub(crate) struct AdmittedCarrier { pub(crate) carrier_entry_id: String, } -/// Mind admission for the host-side `deliberate` handler: the caller's grant rows and the -/// registry row read in one transaction, so a revocation cannot land between them, and every -/// liveness decision runs the one grant rule (`live_grant`: unrevoked, unexpired, an -/// unparseable expiry fails closed). The deliberate handler needs a space-wide `knowledge_read` -/// grant of its own before it touches a carrier, so a caller admitted through another capability -/// only is refused here, before any carrier is read. Returns the row-named carrier entry id, or -/// the fixed admission refusal — byte-equal whether the Mind exists, the grant is missing, -/// revoked or expired — so an unadmitted caller cannot tell the cases apart. +/// Mind admission for the host-side `deliberate` handler, in the order the plan fixes: the +/// caller's live grant, then the space row, then the registry row, and only then the space-wide +/// `knowledge_read` coverage — the same split [`admitted_carrier`] applies to the cognition read. +/// +/// An unknown Mind, an unadmitted one and a frozen one the caller holds no grant in answer the +/// one target-free refusal. A caller the named Mind admits but whose grants do not cover +/// `knowledge_read` answers the coverage refusal instead, which is reachable only by a caller +/// already known to hold a live grant here; the two answers are deliberately different, so a +/// capability gap never reads as a lost admission. pub async fn admitted_carrier_entry( pool: &SqlitePool, principal_id: &str, @@ -83,23 +84,9 @@ pub async fn admitted_carrier_entry( .begin() .await .map_err(|e| Reject::internal(format!("the mind admission could not begin: {e}")).into_spoke())?; - let space = SpaceId::new(space_id.to_string()); - let rows = caller_grants(&mut tx, principal_id, &space).await?; - let now = Utc::now(); - let admitted = rows.iter().any(|row| { - row.principal_id.as_str() == principal_id - && row.subject_id.is_none() - && row.capabilities.iter().any(|cap| cap == KNOWLEDGE_READ) - && admission::live_grant(row, now) - }); - if !admitted { - return Err(Reject::admission_refusal().into_spoke()); - } - let carrier = registry_carrier(&mut tx, space_id).await?; + let carrier = admitted_carrier(&mut tx, principal_id, space_id).await; let _ = tx.rollback().await; - carrier - .map(|carrier| carrier.carrier_entry_id) - .ok_or_else(|| Reject::admission_refusal().into_spoke()) + carrier.map(|carrier| carrier.carrier_entry_id) } /// Admission of one Mind-level read, in the order the plan fixes: a live grant of the caller's in @@ -145,8 +132,9 @@ pub(crate) async fn admitted_carrier( .await? .ok_or_else(|| Reject::admission_refusal().into_spoke())?; // Coverage over the same caller-only rows: another principal's grants are neither needed for - // a space-wide requirement nor allowed to reach this decision. - let grants = admission::wire_grants(&rows).map_err(|reject| reject.into_spoke())?; + // a space-wide requirement nor allowed to reach this decision, and a dead row of the + // caller's own covers nothing — projecting one would turn a refusal into a storage error. + let grants = admission::live_wire_grants(&rows, now).map_err(|reject| reject.into_spoke())?; let requirement = GrantRequirement { capability: KNOWLEDGE_READ, subject_id: None, diff --git a/crates/mindcore-spoke/tests/memory_adapter.rs b/crates/mindcore-spoke/tests/memory_adapter.rs index 4e3b74b0..77e605fe 100644 --- a/crates/mindcore-spoke/tests/memory_adapter.rs +++ b/crates/mindcore-spoke/tests/memory_adapter.rs @@ -4702,3 +4702,186 @@ async fn spaces_list_returns_only_admitted_minds() { ); tx.rollback().await.expect("rollback"); } + +/// Mind admission reads only the caller's own grant rows: a stranger's malformed row in an +/// existing space never reaches a decode decision, so an unadmitted caller cannot tell that +/// space from one that does not exist — on the guarded reads and on a mutation alike. The +/// caller's own live grant still serves the same space with the malformed row beside it. +#[tokio::test] +async fn a_strangers_malformed_grant_row_cannot_leak_a_mind() { + let harness = Harness::open().await; + let adapter = MemoryAdapter::new(true); + sqlx::query( + "INSERT INTO memory_grants \ + (grant_id, space_id, subject_id, principal_id, capabilities_json, context_ids_json, \ + shared_access, expires_at, revoked_at, revision, created_at) \ + VALUES ('grt_malformed_stranger', ?, NULL, ?, 'not-json', '[]', 0, NULL, NULL, 1, ?)", + ) + .bind(SPACE) + .bind(STRANGER) + .bind(NOW) + .execute(&harness.pool) + .await + .expect("seed the stranger's malformed grant"); + + let mut messages: std::collections::HashSet = std::collections::HashSet::new(); + for space in [SPACE, "sp_absent"] { + let mut tx = harness.begin().await; + for (op, result) in guarded_reads(&adapter, &mut tx, space, SUBJECT, "cnd_any").await { + let refusal = reject(&result); + assert_eq!( + refusal.code, + SpokeRejectCode::NotAuthorized, + "{op} in {space} answers the admission refusal" + ); + assert!( + refusal.details.is_none(), + "{op} in {space} carries no details: {refusal:?}" + ); + messages.insert(refusal.message.clone()); + } + let capture = adapter + .capture( + &mut tx, + &principal(PRINCIPAL), + json!({ + "space_id": space, + "subject_id": SUBJECT, + "capture_scope": { "visibility": "shared" }, + "content": { "text": "a capture into a mind the caller cannot see" }, + "idempotency_key": format!("cap-malformed-{space}") + }), + ) + .await; + let refusal = reject(&capture); + assert_eq!( + refusal.code, + SpokeRejectCode::NotAuthorized, + "capture in {space}" + ); + assert!( + refusal.details.is_none(), + "capture in {space} carries no details: {refusal:?}" + ); + messages.insert(refusal.message.clone()); + assert_eq!( + harness.count(&mut tx, "memory_candidates").await, + 0, + "nothing is staged in {space}" + ); + tx.rollback().await.expect("rollback"); + } + assert_eq!( + messages.len(), + 1, + "the existing space with a stranger's malformed row and an absent space are one answer" + ); + + // The caller's own live grant admits it; the stranger's row is never decoded on its behalf. + harness.seed_grant(PRINCIPAL, &["recall"]).await; + let mut tx = harness.begin().await; + let pack = ready( + adapter + .recall( + &mut tx, + &principal(PRINCIPAL), + json!({ "space_id": SPACE, "subject_id": SUBJECT, + "selection": { "mode": "subject_all" }, + "budget": { "max_items": 4 } }), + ) + .await, + ); + assert!(pack["records"].is_array(), "{pack}"); + tx.rollback().await.expect("rollback"); +} + +/// `memory.spaces.list` projects only Minds admission would admit: a Mind whose only live grant +/// for the caller cannot decode is skipped, not listed and not an error, while a Mind that also +/// holds a decodable live grant stays listed. +#[tokio::test] +async fn spaces_list_skips_a_mind_whose_only_grant_is_undecodable() { + use mindcore_base::boundary::CallerId; + use mindcore_base::ids::MindId; + use mindcore_sqlite::minds::{self, CreateMind}; + + let harness = Harness::open().await; + let adapter = MemoryAdapter::new(true); + let owner = "o_list"; + let mut tx = harness.begin().await; + for id in ["mind_broken", "mind_extra", "mind_whole"] { + let created = minds::create( + &mut tx, + &CreateMind { + mind_id: Some(MindId::new(id)), + display_name: Some(format!("mind {id}")), + owner: CallerId::new(owner), + }, + ) + .await; + assert!( + matches!(created, SpokeResult::Ok(_)), + "create {id}: {created:?}" + ); + } + // `mind_extra` gets a second live grant, so one undecodable row cannot hide it. + sqlx::query( + "INSERT INTO memory_grants \ + (grant_id, space_id, subject_id, principal_id, capabilities_json, context_ids_json, \ + shared_access, expires_at, revoked_at, revision, created_at) \ + VALUES ('grt_extra', 'mind_extra', NULL, ?, '[\"recall\"]', '[]', 0, NULL, NULL, 1, ?)", + ) + .bind(owner) + .bind(NOW) + .execute(&mut *tx) + .await + .expect("seed the second grant"); + for space in ["mind_broken", "mind_extra"] { + sqlx::query( + "UPDATE memory_grants SET capabilities_json = 'not-json' \ + WHERE grant_id = (SELECT grant_id FROM memory_grants \ + WHERE space_id = ? AND principal_id = ? \ + ORDER BY grant_id LIMIT 1)", + ) + .bind(space) + .bind(owner) + .execute(&mut *tx) + .await + .expect("corrupt one grant"); + } + tx.commit().await.expect("commit minds"); + + let mut tx = harness.begin().await; + let body = ready( + adapter + .list_spaces(&mut tx, &principal(owner), json!({})) + .await, + ); + let ids: Vec<&str> = body["spaces"] + .as_array() + .expect("spaces array") + .iter() + .map(|space| space["space_id"].as_str().expect("space_id")) + .collect(); + assert_eq!( + ids, + ["mind_extra", "mind_whole"], + "a Mind admission would refuse through an undecodable row is not listed" + ); + + // The refusal the list's rule mirrors: admission reads no row it cannot decode. + let broken = adapter + .recall( + &mut tx, + &principal(owner), + json!({ "space_id": "mind_broken", "subject_id": SUBJECT, + "selection": { "mode": "subject_all" }, + "budget": { "max_items": 4 } }), + ) + .await; + assert_eq!( + reject(&broken).code, + SpokeRejectCode::NotAuthorized, + "the skipped Mind answers the admission refusal" + ); + tx.rollback().await.expect("rollback"); +} diff --git a/crates/mindcore-spoke/tests/workflows.rs b/crates/mindcore-spoke/tests/workflows.rs index e7430aed..e19783b2 100644 --- a/crates/mindcore-spoke/tests/workflows.rs +++ b/crates/mindcore-spoke/tests/workflows.rs @@ -2,7 +2,6 @@ //! costs, which knowledge collection fills the second slot, and the reread //! that keeps a snapshot moved during provider work out of a released pack. -use std::collections::BTreeMap; use std::num::NonZeroUsize; use std::path::PathBuf; use std::sync::atomic::{AtomicUsize, Ordering}; @@ -35,16 +34,6 @@ const SUBJECT: &str = "subj_1"; const PRINCIPAL: &str = "prn_1"; const NOW: &str = "2026-11-20T09:00:00.000Z"; -/// A route map putting each of `principals` onto the fixture's one collection. -fn routes(principals: &[&str]) -> Arc> { - Arc::new( - principals - .iter() - .map(|principal| ((*principal).to_string(), KnowledgeScope::new("wren"))) - .collect(), - ) -} - /// What the embedder does to the store while it runs — outside every /// transaction the workflow holds. #[derive(Clone, Copy, PartialEq, Eq)] @@ -383,11 +372,7 @@ impl Harness { } } - fn binding( - &self, - caller: &str, - side_effect: SideEffect, - ) -> (SpiMindWorkflows, BoundaryEmbedder) { + fn binding(&self, side_effect: SideEffect) -> (SpiMindWorkflows, BoundaryEmbedder) { let binding = MemoryWorkflowBinding::new(self.pool.clone(), true); (SpiMindWorkflows::new(binding), self.embedder(side_effect)) } @@ -763,7 +748,7 @@ async fn knowledge_slot_reads_only_the_bound_collection() { harness .entry("wanderer", "ke_elsewhere", "not this holder's") .await; - let (workflows, embedder) = harness.binding(PRINCIPAL, SideEffect::None); + let (workflows, embedder) = harness.binding(SideEffect::None); let pack = workflows .recall_context( @@ -805,7 +790,7 @@ async fn knowledge_slot_refuses_a_collection_over_the_served_bound() { .entry("wren", &format!("ke_{index:04}"), "bounded entry") .await; } - let (workflows, embedder) = harness.binding(PRINCIPAL, SideEffect::None); + let (workflows, embedder) = harness.binding(SideEffect::None); let capabilities = MindCapabilities { embedder: Some(&embedder), ..MindCapabilities::default() @@ -860,7 +845,7 @@ async fn knowledge_slot_hides_owner_private_entries() { harness .private_entry("wren", "ke_mira_diary", "ke_mira", "mira's private notes") .await; - let (workflows, embedder) = harness.binding(PRINCIPAL, SideEffect::None); + let (workflows, embedder) = harness.binding(SideEffect::None); let pack = workflows .recall_context( @@ -911,7 +896,7 @@ async fn knowledge_slot_omits_a_superseded_entry() { SpokeResult::Ok(revision) => assert_eq!(revision, 2), SpokeResult::Reject(reject) => panic!("marking the slot entry failed: {reject:?}"), } - let (workflows, embedder) = harness.binding(PRINCIPAL, SideEffect::None); + let (workflows, embedder) = harness.binding(SideEffect::None); let pack = workflows .recall_context( @@ -954,7 +939,7 @@ async fn tombstoning_a_record_prunes_its_vector_rows() { "2026-11-20T09:00:01.000Z", ) .await; - let (workflows, embedder) = harness.binding(PRINCIPAL, SideEffect::None); + let (workflows, embedder) = harness.binding(SideEffect::None); workflows .recall_context( &principal(), @@ -1011,7 +996,7 @@ async fn revoked_grant_during_provider_work_refuses_the_pack() { "2026-11-20T09:00:01.000Z", ) .await; - let (workflows, embedder) = harness.binding(PRINCIPAL, SideEffect::RevokeGrant); + let (workflows, embedder) = harness.binding(SideEffect::RevokeGrant); let error = workflows .recall_context( @@ -1044,7 +1029,7 @@ async fn pending_intent_during_provider_work_refuses_the_pack() { "2026-11-20T09:00:01.000Z", ) .await; - let (workflows, embedder) = harness.binding(PRINCIPAL, SideEffect::PendingIntent); + let (workflows, embedder) = harness.binding(SideEffect::PendingIntent); let error = workflows .recall_context( @@ -1085,7 +1070,7 @@ async fn changed_revision_during_provider_work_refuses_the_pack() { "2026-11-20T09:00:01.000Z", ) .await; - let (workflows, embedder) = harness.binding(PRINCIPAL, SideEffect::BumpRevision); + let (workflows, embedder) = harness.binding(SideEffect::BumpRevision); let error = workflows .recall_context( @@ -1118,7 +1103,7 @@ async fn memory_grant_alone_leaves_the_knowledge_slot_empty() { ) .await; harness.entry("wren", "ke_gate", "closed after dusk").await; - let (workflows, embedder) = harness.binding(PRINCIPAL, SideEffect::None); + let (workflows, embedder) = harness.binding(SideEffect::None); let pack = workflows .recall_context( @@ -1159,7 +1144,7 @@ async fn a_caller_without_knowledge_read_recalls_with_an_empty_slot() { ) .await; harness.entry("wren", "ke_gate", "closed after dusk").await; - let (workflows, embedder) = harness.binding(PRINCIPAL, SideEffect::None); + let (workflows, embedder) = harness.binding(SideEffect::None); let pack = workflows .recall_context( @@ -1198,7 +1183,7 @@ async fn revoked_knowledge_admission_during_provider_work_is_a_revision_conflict ) .await; harness.entry("wren", "ke_gate", "closed after dusk").await; - let (workflows, embedder) = harness.binding(PRINCIPAL, SideEffect::RevokeKnowledgeGrant); + let (workflows, embedder) = harness.binding(SideEffect::RevokeKnowledgeGrant); let error = workflows .recall_context( diff --git a/crates/mindcore-sqlite/src/minds.rs b/crates/mindcore-sqlite/src/minds.rs index 822b8282..5b379d5b 100644 --- a/crates/mindcore-sqlite/src/minds.rs +++ b/crates/mindcore-sqlite/src/minds.rs @@ -270,7 +270,7 @@ fn driver_error(error: sqlx::Error, id: &MindId) -> SpokeResult { } /// One row of the shared read: the registry row joined to its space row and one live-grant -/// candidate. +/// candidate, with the two grant columns whose decode admission requires. type JoinRow = ( String, String, @@ -279,6 +279,8 @@ type JoinRow = ( String, String, Option, + String, + String, ); // The one projection and join both visibility reads share. A macro rather than a constant, @@ -286,13 +288,20 @@ type JoinRow = ( macro_rules! grant_columns { () => { "SELECT m.space_id, m.knowledge_collection, m.carrier_entry_id, \ - s.display_name, s.status, s.created_at, g.expires_at \ + s.display_name, s.status, s.created_at, g.expires_at, g.capabilities_json, \ + g.context_ids_json \ FROM memory_grants g \ JOIN minds m ON m.space_id = g.space_id \ JOIN memory_spaces s ON s.space_id = g.space_id" }; } +/// A joined row that admission would refuse because its grant columns do not decode admits +/// nothing, so the registry reads skip it instead of erroring or naming a Mind. +fn row_decodes(capabilities_json: &str, context_ids_json: &str) -> bool { + crate::repository::decode_grant_columns(capabilities_json, context_ids_json).is_ok() +} + // The visibility rule of `expiry_passed` in `crates/mindcore-spoke/src/admission.rs`, restated // here because `mindcore-sqlite` cannot depend on the adapter: no expiry is live; an expiry // that does not parse as RFC 3339 is never live; the expiry is compared as an instant and never @@ -354,17 +363,29 @@ async fn read_visible(store: &MindStore, caller: &CallerId) -> SpokeResult = None; while let Some(row) = poll_fn(|cx| rows.as_mut().poll_next(cx)).await { - let (space_id, collection, carrier, display_name, status, created_at, expires_at) = - match row { - Ok(row) => row, - Err(_) => return storage_unavailable(), - }; + let ( + space_id, + collection, + carrier, + display_name, + status, + created_at, + expires_at, + capabilities_json, + context_ids_json, + ) = match row { + Ok(row) => row, + Err(_) => return storage_unavailable(), + }; if emitted.as_deref() == Some(space_id.as_str()) { continue; } if !live(&expires_at) { continue; } + if !row_decodes(&capabilities_json, &context_ids_json) { + continue; + } let mind = match mind_of( space_id, collection, @@ -398,14 +419,26 @@ async fn read_one_visible( .bind(id.as_str()) .fetch(&store.pool); while let Some(row) = poll_fn(|cx| rows.as_mut().poll_next(cx)).await { - let (space_id, collection, carrier, display_name, status, created_at, expires_at) = - match row { - Ok(row) => row, - Err(_) => return storage_unavailable(), - }; + let ( + space_id, + collection, + carrier, + display_name, + status, + created_at, + expires_at, + capabilities_json, + context_ids_json, + ) = match row { + Ok(row) => row, + Err(_) => return storage_unavailable(), + }; if !live(&expires_at) { continue; } + if !row_decodes(&capabilities_json, &context_ids_json) { + continue; + } return match mind_of( space_id, collection, @@ -432,8 +465,8 @@ pub async fn visible_mind_ids( tx: &mut Transaction<'_, Sqlite>, caller: &str, ) -> SpokeResult> { - let mut rows = sqlx::query_as::<_, (String, Option)>( - "SELECT m.space_id, g.expires_at \ + let mut rows = sqlx::query_as::<_, (String, Option, String, String)>( + "SELECT m.space_id, g.expires_at, g.capabilities_json, g.context_ids_json \ FROM memory_grants g \ JOIN minds m ON m.space_id = g.space_id \ WHERE g.principal_id = ?1 AND g.revoked_at IS NULL \ @@ -444,7 +477,7 @@ pub async fn visible_mind_ids( let mut ids = Vec::new(); let mut emitted: Option = None; while let Some(row) = poll_fn(|cx| rows.as_mut().poll_next(cx)).await { - let (space_id, expires_at) = match row { + let (space_id, expires_at, capabilities_json, context_ids_json) = match row { Ok(row) => row, Err(_) => return storage_unavailable(), }; @@ -454,6 +487,9 @@ pub async fn visible_mind_ids( if !live(&expires_at) { continue; } + if !row_decodes(&capabilities_json, &context_ids_json) { + continue; + } emitted = Some(space_id.clone()); ids.push(space_id); } diff --git a/crates/mindcore-sqlite/src/repository.rs b/crates/mindcore-sqlite/src/repository.rs index 0cebd76d..2e922961 100644 --- a/crates/mindcore-sqlite/src/repository.rs +++ b/crates/mindcore-sqlite/src/repository.rs @@ -902,11 +902,25 @@ fn import_row(row: ImportColumns) -> RepoResult { }) } -fn grant_row(row: GrantRow) -> RepoResult { - let capabilities: Vec = serde_json::from_str(&row.capabilities_json) +/// The decode rule every grant row read applies: both JSON columns are string arrays. +/// +/// [`grant_row`] and the registry's visibility reads share it, so a Mind is visible through a row +/// only when the row admission decodes would admit: the same malformed row must not be refused by +/// one read and listed by another. +pub(crate) fn decode_grant_columns( + capabilities_json: &str, + context_ids_json: &str, +) -> RepoResult<(Vec, Vec)> { + let capabilities: Vec = serde_json::from_str(capabilities_json) .map_err(|error| invalid_row(format_args!("capabilities_json: {error}")))?; - let contexts: Vec = serde_json::from_str(&row.context_ids_json) + let contexts: Vec = serde_json::from_str(context_ids_json) .map_err(|error| invalid_row(format_args!("context_ids_json: {error}")))?; + Ok((capabilities, contexts)) +} + +fn grant_row(row: GrantRow) -> RepoResult { + let (capabilities, contexts) = + decode_grant_columns(&row.capabilities_json, &row.context_ids_json)?; Ok(MemoryGrantRow { grant_id: row.grant_id, space_id: SpaceId::new(row.space_id), From f66dfe8b87b907b8a1417470b0f7e3e5258a2df4 Mon Sep 17 00:00:00 2001 From: Tang Bohao Date: Thu, 26 Nov 2026 15:23:02 +0800 Subject: [PATCH 17/27] fix(serving): serve the admin grant view and keep the deliberate refusal order - A1: memory.grants.list keeps admission caller-only, then reads the space's decodable grant set for the page and the cursor marker once admin is determined, so an admin's page and marker cover every principal's changes again; embed_parity is green. - A2: the host deliberate pre-check is admission only (live grant -> space row -> registry row); the workflow's subject page and revalidation answer first and the carrier's knowledge_read/knowledge_write coverage comes after, as the plan orders it. A new loopback test pins both refusals and their order. - A3: admission and the registry read share mindcore_sqlite::decodable_grants, which skips a row it cannot decode one row at a time; a live decodable row admits, only an all-broken set refuses, and the list and admission agree on the mixed case (pinned in the adapter test). - A4: the deliberate pre-check is bounded by tokio::time::timeout on the request budget, so a connection or query wait cannot outlive the deadline; the remainder still bounds the workflow. - Coverage is evaluated over live rows everywhere (live_wire_grants in the read paths, require_space_grants and the space grant read), so a dead row with an unprojectable expiry answers the ordinary refusal instead of an internal error. - serving-principal-routing.md states the shared admission step and which carrier adds coverage, matching the code. - Addresses A1, A2, A3 and A4 of the serving QC re-review. --- .../architecture/serving-principal-routing.md | 16 ++- crates/mindcore-runtime/Cargo.toml | 2 +- crates/mindcore-runtime/src/tools.rs | 25 ++-- crates/mindcore-runtime/src/tools/tests.rs | 45 +++---- crates/mindcore-runtime/tests/loopback.rs | 122 +++++++++++++++++- crates/mindcore-spoke/src/admission.rs | 39 +++--- crates/mindcore-spoke/src/content.rs | 27 ++-- crates/mindcore-spoke/src/control.rs | 20 ++- crates/mindcore-spoke/src/lib.rs | 7 +- crates/mindcore-spoke/src/reflection.rs | 8 +- .../mindcore-spoke/src/transfer/activate.rs | 2 +- crates/mindcore-spoke/src/workflows.rs | 103 ++++++++------- crates/mindcore-spoke/tests/memory_adapter.rs | 17 +++ crates/mindcore-sqlite/src/lib.rs | 4 +- crates/mindcore-sqlite/src/repository.rs | 40 ++++++ 15 files changed, 334 insertions(+), 143 deletions(-) diff --git a/.agents/specs/architecture/serving-principal-routing.md b/.agents/specs/architecture/serving-principal-routing.md index 7d0fb6ef..481720f5 100644 --- a/.agents/specs/architecture/serving-principal-routing.md +++ b/.agents/specs/architecture/serving-principal-routing.md @@ -39,11 +39,17 @@ answers `SpaceFrozen` only to an operation that is freeze-gated and outside SPOK allowlist, while serving every operation that is not freeze-gated. Only a caller that passed admission reaches either check. -The carrier read paths resolve through the registry row on the caller's transaction, after the same -order: `admitted_carrier` (`crates/mindcore-spoke/src/workflows.rs`) for the cognition read, and -`admitted_carrier_entry` for the host-side `deliberate` handler, which requires a space-wide live -`knowledge_read` grant before touching a carrier. A `space_id` with no registry row answers the -admission refusal before any carrier is read. +The carrier paths resolve through the registry row on the caller's transaction, after the same +order — `admit_carrier_location` (`crates/mindcore-spoke/src/workflows.rs`) is the shared first +step: a live grant of the caller's (any capability), then the space row, then the registry row. A +`space_id` with no registry row answers the admission refusal before any carrier is read. + +The two carriers then differ by what their operation earns first. The cognition read +(`admitted_carrier`) adds the space-wide `knowledge_read` coverage after those steps, because it has +no subject page ahead of the carrier. The host-side `deliberate` handler (`admitted_carrier_entry`) +adds no coverage at all: the workflow reads and revalidates the named subject's page and only then +checks `knowledge_read`/`knowledge_write` on the carrier, so the refusal a request earns first — the +subject's, or the capability's — is the one a caller sees. ### Deliberation diff --git a/crates/mindcore-runtime/Cargo.toml b/crates/mindcore-runtime/Cargo.toml index 9e6f91db..50f92677 100644 --- a/crates/mindcore-runtime/Cargo.toml +++ b/crates/mindcore-runtime/Cargo.toml @@ -20,7 +20,7 @@ spoke-connect = { workspace = true, features = ["remote-adapter"] } spoke-operations.workspace = true spoke-schemas.workspace = true sqlx.workspace = true -tokio = { workspace = true, features = ["sync"] } +tokio = { workspace = true, features = ["sync", "time"] } [dev-dependencies] ed25519-dalek = "3" diff --git a/crates/mindcore-runtime/src/tools.rs b/crates/mindcore-runtime/src/tools.rs index e9d00e14..911e73ae 100644 --- a/crates/mindcore-runtime/src/tools.rs +++ b/crates/mindcore-runtime/src/tools.rs @@ -332,8 +332,9 @@ async fn deliberate( Ok(arguments) => arguments, Err(reject) => return SpokeResult::Reject(reject), }; - // The request's budget covers the whole call, and this pre-check is part of it: the DB read - // cannot be preempted, so its wall time is charged against the workflow's deadline instead. + // The request's budget covers the whole call, and this pre-check is part of it: a query or + // connection wait is bounded by the timer, so expiry stops the pre-check rather than being + // answered after it returns. A timer that fires starts no reasoner work and no carrier write. let budget = Duration::from_millis(arguments.timeout_ms.get() as u64); let started = Instant::now(); // Admission before existence, in one transaction: the grant rows and the registry row are @@ -341,19 +342,21 @@ async fn deliberate( // adapter's own (`live_grant` — unrevoked, unexpired, an unparseable expiry fails closed). // A missing grant, a revoked or expired one and a space with no registry row are the same // target-free refusal, so a caller can never tell an existing Mind from an absent one by - // varying `space_id`; a caller the Mind admits without `knowledge_read` answers the coverage - // refusal instead. - let carrier_entry_id = match mindcore_spoke::admitted_carrier_entry( - pool, - &principal.principal_id, - &arguments.space_id, + // varying `space_id`. The operation's own coverage is not checked here: the workflow reads + // and revalidates the subject page first and only then checks `knowledge_read`, so the + // request's own refusal is the one a caller sees. + let carrier_entry_id = match tokio::time::timeout( + budget, + mindcore_spoke::admitted_carrier_entry(pool, &principal.principal_id, &arguments.space_id), ) .await { - Ok(carrier_entry_id) => carrier_entry_id, - Err(reject) => return SpokeResult::Reject(reject), + Ok(Ok(carrier_entry_id)) => carrier_entry_id, + Ok(Err(reject)) => return SpokeResult::Reject(reject), + Err(_elapsed) => return SpokeResult::Reject(workflow_retryable("deadline_exceeded")), }; - // A budget the pre-check already spent starts nothing: no reasoner, no carrier write. + // The pre-check kept its time: the workflow gets only what is left, and an exhausted budget + // starts nothing either. let Some(timeout) = remaining_budget(budget, started.elapsed()) else { return SpokeResult::Reject(workflow_retryable("deadline_exceeded")); }; diff --git a/crates/mindcore-runtime/src/tools/tests.rs b/crates/mindcore-runtime/src/tools/tests.rs index 2f7ca8f4..332f26df 100644 --- a/crates/mindcore-runtime/src/tools/tests.rs +++ b/crates/mindcore-runtime/src/tools/tests.rs @@ -929,12 +929,12 @@ async fn read_cognition_serves_a_judgment_or_a_null_state() { ); } -/// The served `deliberate` keeps the plan's refusal split: a caller the Mind admits without a -/// space-wide `knowledge_read` grant answers the coverage refusal, while an unadmitted Mind and -/// an absent one answer one byte-equal, detail-free admission refusal. Neither refusal reaches -/// the workflow. +/// The served `deliberate` admits before the workflow and leaves the operation's own coverage to +/// it: a caller the Mind admits reaches the workflow even without `knowledge_read` (the subject +/// page and its revalidation answer first there), while an unadmitted Mind and an absent one +/// answer one byte-equal, detail-free admission refusal before any workflow runs. #[tokio::test] -async fn deliberate_refuses_coverage_after_admission() { +async fn deliberate_admits_before_the_workflow_and_its_coverage() { let fake = Arc::new(Fake::default()); fake.reply_deliberate(Ok(DeliberateOutcome::NoChange { verdict: json!({}), @@ -942,21 +942,19 @@ async fn deliberate_refuses_coverage_after_admission() { })); let tool = tools(Arc::clone(&fake)).await; - let mut uncovered_arguments = deliberate_arguments(); - uncovered_arguments["space_id"] = json!("spc_4"); - let uncovered = expect_reject( - tool.call(DELIBERATE, "peer-driver", uncovered_arguments) + let mut admitted_arguments = deliberate_arguments(); + admitted_arguments["space_id"] = json!("spc_4"); + let served = expect_ok( + tool.call(DELIBERATE, "peer-driver", admitted_arguments) .await, - "an admitted caller without knowledge_read", + "an admitted caller without knowledge_read reaches the workflow", ); - assert_eq!(uncovered.code, SpokeRejectCode::NotAuthorized); - assert!( - uncovered.message.contains("knowledge_read"), - "the coverage refusal names the capability the caller lacks: {uncovered:?}" - ); - assert_ne!( - uncovered.details, None, - "a coverage gap cannot be retried away: {uncovered:?}" + assert_eq!(served["status"], "no_change"); + assert_eq!( + fake.seen().len(), + 1, + "the workflow's own coverage is what answers a capability gap: {:?}", + fake.seen() ); let mut unadmitted_arguments = deliberate_arguments(); @@ -981,13 +979,10 @@ async fn deliberate_refuses_coverage_after_admission() { unadmitted, absent, "an unadmitted Mind and an absent one are one answer" ); - assert_ne!( - uncovered, unadmitted, - "an admitted caller short of one capability is not an unadmitted caller" - ); - assert!( - fake.seen().is_empty(), - "no refusal above reaches the workflow" + assert_eq!( + fake.seen().len(), + 1, + "neither refusal above reaches the workflow" ); } diff --git a/crates/mindcore-runtime/tests/loopback.rs b/crates/mindcore-runtime/tests/loopback.rs index 102c1724..fed16304 100644 --- a/crates/mindcore-runtime/tests/loopback.rs +++ b/crates/mindcore-runtime/tests/loopback.rs @@ -1950,10 +1950,15 @@ async fn a_grant_with_an_unparseable_expiry_is_dead_to_deliberate() { .await .expect("corrupt the expiry"); let (_dir, serve) = fixture.serve(); + // A reasoner is configured so the workflow reaches its snapshot: the refusal must come from + // admission/coverage, never from the engine's missing capability. let mut faces = faces( hello("runtime", &[]), None, - MindProviders::default(), + MindProviders { + reasoner: Some(Arc::new(NoChangeReasoner)), + ..MindProviders::default() + }, ); faces.principals = principal_admission(); let surface = surface(&serve, faces); @@ -2009,10 +2014,15 @@ async fn a_grant_revoked_before_the_call_refuses_deliberate() { let fixture = Fixture::open().await; let pool = fixture.store.pool(); let (_dir, serve) = fixture.serve(); + // A reasoner is configured so the workflow reaches its snapshot: the refusal must come from + // admission/coverage, never from the engine's missing capability. let mut faces = faces( hello("runtime", &[]), None, - MindProviders::default(), + MindProviders { + reasoner: Some(Arc::new(NoChangeReasoner)), + ..MindProviders::default() + }, ); faces.principals = principal_admission(); let surface = surface(&serve, faces); @@ -2031,10 +2041,10 @@ async fn a_grant_revoked_before_the_call_refuses_deliberate() { .await, "deliberate after the knowledge grant is revoked", ); - assert_eq!(uncovered.code, SpokeRejectCode::NotAuthorized); - assert!( - uncovered.message.contains("knowledge_read"), - "a revoked row covers nothing, so the coverage refusal answers: {uncovered:?}" + assert_eq!( + uncovered.code, + SpokeRejectCode::NotAuthorized, + "the revoked knowledge grant is the coverage answer: {uncovered:?}" ); sqlx::query( @@ -2057,6 +2067,106 @@ async fn a_grant_revoked_before_the_call_refuses_deliberate() { ); } +/// The plan's refusal order on the served `deliberate`: admission, then the workflow's subject +/// page and its revalidation, and only then the `knowledge_read` coverage. A caller whose recall +/// grant does not cover the named subject answers that refusal even though it also lacks +/// `knowledge_read`; once the subject is covered, the capability gap answers. No reasoner is +/// configured, so any path that reached the engine would answer differently again, and nothing is +/// written either way. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn deliberate_refuses_the_subject_before_the_knowledge_coverage() { + let fixture = Fixture::open().await; + let pool = fixture.store.pool(); + // The caller keeps one recall grant, scoped to a subject it is not asking about, and no + // knowledge grant at all: both refusals apply, and the subject's must answer first. + fixture.revoke("grt_recall").await; + fixture.revoke("grt_knowledge").await; + sqlx::query( + "INSERT INTO memory_grants \ + (grant_id, space_id, subject_id, principal_id, capabilities_json, context_ids_json, \ + shared_access, expires_at, revoked_at, revision, created_at) \ + VALUES ('grt_recall_elsewhere', ?, 'subj_elsewhere', ?, '[\"recall\"]', '[]', 0, NULL, NULL, 1, ?)", + ) + .bind(SPACE) + .bind(PRINCIPAL) + .bind(NOW) + .execute(&pool) + .await + .expect("seed the elsewhere recall grant"); + let (_dir, serve) = fixture.serve(); + // A reasoner is configured so the workflow reaches its snapshot: both refusals below are + // decided there, before any provider work. + let surface = surface( + &serve, + faces( + hello("runtime", &[]), + None, + MindProviders { + reasoner: Some(Arc::new(NoChangeReasoner)), + ..MindProviders::default() + }, + ), + ); + let session = connect(&surface, &[DELIBERATE]).await; + + let subject_first = expect_reject( + session + .adapter + .invoke_tool(DELIBERATE, deliberate_arguments()) + .await, + "deliberate whose recall grant covers another subject", + ); + assert_eq!( + subject_first.code, + SpokeRejectCode::NotAuthorized, + "the subject refusal answers: {subject_first:?}" + ); + assert!( + subject_first.message.contains("recall"), + "the subject page's own refusal answers first: {subject_first:?}" + ); + assert!( + !subject_first.message.contains("knowledge_read"), + "the capability gap must not pre-empt the subject refusal: {subject_first:?}" + ); + + // Covering the subject leaves only the capability gap; it answers now, from the workflow. + sqlx::query( + "INSERT INTO memory_grants \ + (grant_id, space_id, subject_id, principal_id, capabilities_json, context_ids_json, \ + shared_access, expires_at, revoked_at, revision, created_at) \ + VALUES ('grt_recall_subject', ?, ?, ?, '[\"recall\"]', '[]', 0, NULL, NULL, 1, ?)", + ) + .bind(SPACE) + .bind(SUBJECT) + .bind(PRINCIPAL) + .bind(NOW) + .execute(&pool) + .await + .expect("seed the subject recall grant"); + let coverage = expect_reject( + session + .adapter + .invoke_tool(DELIBERATE, deliberate_arguments()) + .await, + "deliberate whose subject is covered but whose knowledge_read is missing", + ); + assert_eq!(coverage.code, SpokeRejectCode::NotAuthorized); + assert!( + coverage.message.contains("knowledge_read"), + "the coverage refusal answers once the subject is admitted: {coverage:?}" + ); + assert_ne!( + coverage, subject_first, + "the two refusals are different answers in the plan's order" + ); + assert_eq!( + carrier_revision(&pool, COLLECTION, CARRIER).await, + 1, + "neither refusal writes a judgment" + ); +} + /// One principal admitted to both Minds: each recall names its own `space_id` and answers that /// Mind's content — entry id, canonical name and body summary — never the other's. Two different /// principals would not pin this: a route keyed to the principal would pass either way. diff --git a/crates/mindcore-spoke/src/admission.rs b/crates/mindcore-spoke/src/admission.rs index 50737da0..d3ebd1c3 100644 --- a/crates/mindcore-spoke/src/admission.rs +++ b/crates/mindcore-spoke/src/admission.rs @@ -14,7 +14,7 @@ use mindcore_base::ir::{ MemoryRepository, MemorySpaceRow, MemorySubjectRow, Placement, ReceiptKey, ReceiptRead, ReviewReceiptIr, }; -use mindcore_sqlite::{SqliteMemoryRepository, SqliteRepositoryError}; +use mindcore_sqlite::SqliteMemoryRepository; use spoke_operations::SpokeResult; use spoke_operations::{ grant_covers, is_freeze_allowlisted, validate_grant_issuance, GrantRequirement, IssuedGrant, @@ -217,29 +217,28 @@ pub(crate) fn candidate_requirement<'a>( /// space to `memory.*`; the registry gates only `memory.spaces.list` and the /// Mind-level reads. /// -/// The read is filtered to the caller's own rows at the query. Another -/// principal's malformed row is therefore never decoded and can neither turn -/// this refusal into a storage error nor tell the caller the space exists; a -/// row of the caller's own that cannot decode admits nothing and answers the -/// same target-free refusal. +/// The read is filtered to the caller's own rows at the query and decodes one +/// row at a time, skipping a row that cannot decode — the rule the registry's +/// visibility read applies. Another principal's malformed row is therefore +/// never decoded and can neither turn this refusal into a storage error nor +/// tell the caller the space exists; a live decodable row of the caller's +/// admits, and only a set with none refuses, so a Mind the list names is one +/// admission serves. pub(crate) async fn admit_mind( - repository: &SqliteMemoryRepository, tx: &mut Tx<'_>, principal: &str, space: &SpaceId, ) -> AResult> { - let rows = repository - .list_grants(tx, space, Some(principal)) + let rows = mindcore_sqlite::decodable_grants(tx, space, Some(principal)) .await - .map_err(|error| match error { - SqliteRepositoryError::InvalidRow(_) => Reject::admission_refusal(), - other => Reject::internal(format!("the mind admission could not be read: {other}")), + .map_err(|error| { + Reject::internal(format!("the mind admission could not be read: {error}")) })?; let now = Utc::now(); if !rows.iter().any(|row| live_grant(row, now)) { return Err(Reject::admission_refusal()); } - match repository.space(tx, space).await? { + match SqliteMemoryRepository.space(tx, space).await? { Some(_) => Ok(rows), None => Err(Reject::admission_refusal()), } @@ -305,12 +304,10 @@ pub(crate) async fn record( Ok(repository.record(tx, space, record_id).await?) } -pub(crate) async fn grants( - repository: &SqliteMemoryRepository, - tx: &mut Tx<'_>, - space: &SpaceId, -) -> AResult> { - Ok(repository.list_grants(tx, space, None).await?) +pub(crate) async fn grants(tx: &mut Tx<'_>, space: &SpaceId) -> AResult> { + mindcore_sqlite::decodable_grants(tx, space, None) + .await + .map_err(|error| Reject::internal(format!("the grant read failed: {error}"))) } /// The protocol's own coverage evaluator takes the wire grant union; the stored @@ -493,7 +490,7 @@ pub(crate) async fn authorize( admission: &Admission<'_>, now: DateTime, ) -> AResult> { - let rows = admit_mind(repository, tx, admission.principal, admission.space).await?; + let rows = admit_mind(tx, admission.principal, admission.space).await?; let wire = live_wire_grants(&rows, now)?; let space_id = admission.space.as_str(); match &admission.coverage { @@ -553,7 +550,7 @@ pub(crate) fn authorize_issuance( let Some(issued) = admission.issuance.as_ref() else { return Ok(()); }; - let wire = wire_grants(rows)?; + let wire = live_wire_grants(rows, now)?; match validate_grant_issuance( &wire, admission.principal, diff --git a/crates/mindcore-spoke/src/content.rs b/crates/mindcore-spoke/src/content.rs index 04526670..fce64c6e 100644 --- a/crates/mindcore-spoke/src/content.rs +++ b/crates/mindcore-spoke/src/content.rs @@ -339,8 +339,8 @@ impl MemoryAdapter { None => None, }; let now = Utc::now(); - let rows = admission::admit_mind(&self.repository, tx, principal_id, &space).await?; - let wire_grants = admission::wire_grants(&rows)?; + let rows = admission::admit_mind(tx, principal_id, &space).await?; + let wire_grants = admission::live_wire_grants(&rows, now)?; let base = GrantRequirement { capability: "review", subject_id: Some(subject_id.as_str()), @@ -438,13 +438,14 @@ impl MemoryAdapter { let principal_id = principal_id(principal); let space = SpaceId::new(request.space_id.to_string()); let candidate_id = request.candidate_id.to_string(); - let rows = admission::admit_mind(&self.repository, tx, principal_id, &space).await?; + let rows = admission::admit_mind(tx, principal_id, &space).await?; let Some(head) = admission::candidate_head(&self.repository, tx, &space, candidate_id.as_str()).await? else { return Err(Reject::not_found(format!("candidate {candidate_id}"))); }; - let wire_grants = admission::wire_grants(&rows)?; + let now = Utc::now(); + let wire_grants = admission::live_wire_grants(&rows, now)?; let subject_id = head.subject_id.as_str(); if !admission::covered( &wire_grants, @@ -689,9 +690,9 @@ impl MemoryAdapter { let principal_id = principal_id(principal); let space = SpaceId::new(request.space_id.to_string()); let record_id = request.record_id.to_string(); - let rows = admission::admit_mind(&self.repository, tx, principal_id, &space).await?; - let wire_grants = admission::wire_grants(&rows)?; + let rows = admission::admit_mind(tx, principal_id, &space).await?; let now = Utc::now(); + let wire_grants = admission::live_wire_grants(&rows, now)?; let Some(head) = admission::record_head(&self.repository, tx, &space, record_id.as_str()).await? else { @@ -767,8 +768,8 @@ impl MemoryAdapter { let kinds = request.kinds.clone(); let include_tombstoned = request.include_tombstoned; let now = Utc::now(); - let rows = admission::admit_mind(&self.repository, tx, principal_id, &space).await?; - let wire_grants = admission::wire_grants(&rows)?; + let rows = admission::admit_mind(tx, principal_id, &space).await?; + let wire_grants = admission::live_wire_grants(&rows, now)?; let list = admission::covered( &wire_grants, principal_id, @@ -1294,8 +1295,8 @@ impl MemoryAdapter { let subject_id = request.subject_id.to_string(); let (placement, filter) = read_selection(object)?; let now = Utc::now(); - let rows = admission::admit_mind(&self.repository, tx, principal_id, &space).await?; - let wire_grants = admission::wire_grants(&rows)?; + let rows = admission::admit_mind(tx, principal_id, &space).await?; + let wire_grants = admission::live_wire_grants(&rows, now)?; if !admission::covered( &wire_grants, principal_id, @@ -1439,7 +1440,7 @@ impl MemoryAdapter { let principal_id = principal_id(principal); let space = SpaceId::new(request.space_id.to_string()); let subject_id = request.subject_id.to_string(); - let rows = admission::admit_mind(&self.repository, tx, principal_id, &space).await?; + let rows = admission::admit_mind(tx, principal_id, &space).await?; if !admission::profile_visible( &rows, principal_id, @@ -1615,9 +1616,9 @@ impl MemoryAdapter { let principal_id = principal_id(principal); let space = SpaceId::new(request.space_id.to_string()); let receipt_id = request.receipt_id.to_string(); - let rows = admission::admit_mind(&self.repository, tx, principal_id, &space).await?; - let wire_grants = admission::wire_grants(&rows)?; + let rows = admission::admit_mind(tx, principal_id, &space).await?; let now = Utc::now(); + let wire_grants = admission::live_wire_grants(&rows, now)?; let admin = admission::covered( &wire_grants, principal_id, diff --git a/crates/mindcore-spoke/src/control.rs b/crates/mindcore-spoke/src/control.rs index 464d9a51..19763050 100644 --- a/crates/mindcore-spoke/src/control.rs +++ b/crates/mindcore-spoke/src/control.rs @@ -368,7 +368,7 @@ impl MemoryAdapter { let principal_id = principal_id(principal); let space = SpaceId::new(request.space_id.to_string()); let subject_id = request.subject_id.as_str(); - let rows = admission::admit_mind(&self.repository, tx, principal_id, &space).await?; + let rows = admission::admit_mind(tx, principal_id, &space).await?; if !admission::any_grant_for_subject( &rows, principal_id, @@ -511,8 +511,8 @@ impl MemoryAdapter { let principal_id = principal_id(principal); let space = SpaceId::new(request.space_id.to_string()); let now = Utc::now(); - let rows = admission::admit_mind(&self.repository, tx, principal_id, &space).await?; - let wire_grants = admission::wire_grants(&rows)?; + let rows = admission::admit_mind(tx, principal_id, &space).await?; + let wire_grants = admission::live_wire_grants(&rows, now)?; let admin = admission::covered( &wire_grants, principal_id, @@ -534,8 +534,18 @@ impl MemoryAdapter { .subject_id .as_ref() .map(|subject| subject.as_str().to_string()); + // Admission stays caller-only, but the answer does not: an admin is served the whole + // space's grant set, and the cursor marker is computed over the same set, so another + // principal's grant change moves the marker an admin's page is checked against. Everyone + // else is served exactly the rows admission read for them. + let served: Vec = if admin { + admission::grants(tx, &space).await? + } else { + rows + }; let marker = policy::snapshot_marker( - rows.iter() + served + .iter() .map(|row| (row.grant_id.clone(), row.revision.as_i64().unwrap_or(0))) .collect(), &[], @@ -552,7 +562,7 @@ impl MemoryAdapter { .as_ref() .map(|cursor| cursor.as_str().to_string()); let (offset, claimed) = policy::cursor_page(cursor.as_deref(), principal_id, &scope)?; - let page: Vec<&MemoryGrantRow> = rows + let page: Vec<&MemoryGrantRow> = served .iter() .filter(|row| { applied diff --git a/crates/mindcore-spoke/src/lib.rs b/crates/mindcore-spoke/src/lib.rs index 23d3d892..ae9f7394 100644 --- a/crates/mindcore-spoke/src/lib.rs +++ b/crates/mindcore-spoke/src/lib.rs @@ -294,10 +294,11 @@ impl MemoryAdapter { ) -> Result<(), SpiError> { let caller = principal_id(principal); let space = SpaceId::new(space_id.to_string()); - let rows = admission::grants(&self.repository, tx, &space) + let now = Utc::now(); + let rows = admission::grants(tx, &space) .await .map_err(|reject| SpiError::Settlement(reject.into_spoke()))?; - let grants = admission::wire_grants(&rows) + let grants = admission::live_wire_grants(&rows, now) .map_err(|reject| SpiError::Settlement(reject.into_spoke()))?; for capability in capabilities { let requirement = GrantRequirement { @@ -307,7 +308,7 @@ impl MemoryAdapter { reads_shared: false, subject_all: false, }; - if !admission::covered(&grants, caller, space.as_str(), Utc::now(), &requirement) { + if !admission::covered(&grants, caller, space.as_str(), now, &requirement) { return Err(SpiError::Settlement( Reject::not_authorized(format!( "principal {caller} holds no live {capability} grant in space {}", diff --git a/crates/mindcore-spoke/src/reflection.rs b/crates/mindcore-spoke/src/reflection.rs index 52710a15..30c2f405 100644 --- a/crates/mindcore-spoke/src/reflection.rs +++ b/crates/mindcore-spoke/src/reflection.rs @@ -123,8 +123,8 @@ impl MemoryAdapter { let subject_id = request.subject_id.to_string(); let (selection, filter) = read_selection(object)?; let now = Utc::now(); - let rows = admission::admit_mind(&self.repository, tx, principal_id, &space).await?; - let wire_grants = admission::wire_grants(&rows)?; + let rows = admission::admit_mind(tx, principal_id, &space).await?; + let wire_grants = admission::live_wire_grants(&rows, now)?; let base = admission::selection_requirement("reflect", subject_id.as_str(), &selection); if !admission::covered(&wire_grants, principal_id, space.as_str(), now, &base) { return Err(Reject::not_authorized(format!( @@ -211,8 +211,8 @@ impl MemoryAdapter { }; let filter = wire::PlacementSelectionWire::filter(object, "filter")?; let now = Utc::now(); - let rows = admission::admit_mind(&self.repository, tx, principal_id, &space).await?; - let wire_grants = admission::wire_grants(&rows)?; + let rows = admission::admit_mind(tx, principal_id, &space).await?; + let wire_grants = admission::live_wire_grants(&rows, now)?; let base = admission::selection_requirement("reflect", subject_id.as_str(), &requested); if !admission::covered(&wire_grants, principal_id, space.as_str(), now, &base) { return Err(Reject::not_authorized(format!( diff --git a/crates/mindcore-spoke/src/transfer/activate.rs b/crates/mindcore-spoke/src/transfer/activate.rs index 31dfa730..bc593887 100644 --- a/crates/mindcore-spoke/src/transfer/activate.rs +++ b/crates/mindcore-spoke/src/transfer/activate.rs @@ -969,7 +969,7 @@ impl MemoryAdapter { }; let staged = decode_staged(&payload, &op.space, principal_id)?; recheck(&self.repository, tx, &op.space, &staged).await?; - let caller_grants = admission::grants(&self.repository, tx, &op.space).await?; + let caller_grants = admission::grants(tx, &op.space).await?; not_subsumed( &staged.grants, &caller_grants, diff --git a/crates/mindcore-spoke/src/workflows.rs b/crates/mindcore-spoke/src/workflows.rs index f4fafc80..28a66015 100644 --- a/crates/mindcore-spoke/src/workflows.rs +++ b/crates/mindcore-spoke/src/workflows.rs @@ -36,7 +36,7 @@ use mindcore_spi::{ }; use mindcore_sqlite::{ append_cognition, list_entries_in, read_carrier_header, read_entry, vectors, - SqliteMemoryRepository, SqliteRepositoryError, + SqliteMemoryRepository, }; use crate::admission; @@ -62,15 +62,48 @@ pub(crate) struct AdmittedCarrier { pub(crate) carrier_entry_id: String, } -/// Mind admission for the host-side `deliberate` handler, in the order the plan fixes: the -/// caller's live grant, then the space row, then the registry row, and only then the space-wide -/// `knowledge_read` coverage — the same split [`admitted_carrier`] applies to the cognition read. +/// The plan's carrier admission, shared by both entries below and in its fixed order: a live grant +/// of the caller's in the space — any capability admits, and an unknown, an unadmitted and a +/// frozen-ungranted Mind answer the one target-free refusal — then the space row, then the +/// registry row the carrier comes from. +async fn admit_carrier_location( + tx: &mut Tx<'_>, + principal_id: &str, + space: &SpaceId, + space_id: &str, +) -> Result<(Vec, AdmittedCarrier), SpokeReject> { + let rows = caller_grants(tx, principal_id, space).await?; + let now = Utc::now(); + if !rows.iter().any(|row| admission::live_grant(row, now)) { + return Err(Reject::admission_refusal().into_spoke()); + } + // The space row is the plan's second step, and it is what `admit_mind` itself checks: a grant + // outlives its space only if the space row is deleted underneath it, which the store never + // does — a Mind's space row, registry row and carrier entry are written in one transaction. + // Keeping the read makes this path refuse exactly the Minds `admit_mind` refuses. + let space_row = SqliteMemoryRepository + .space(tx, space) + .await + .map_err(|error| { + Reject::internal(format!("the mind admission could not be read: {error}")).into_spoke() + })?; + if space_row.is_none() { + return Err(Reject::admission_refusal().into_spoke()); + } + let carrier = registry_carrier(tx, space_id) + .await? + .ok_or_else(|| Reject::admission_refusal().into_spoke())?; + Ok((rows, carrier)) +} + +/// Admission for the host-side `deliberate` handler: the steps above and nothing more. /// -/// An unknown Mind, an unadmitted one and a frozen one the caller holds no grant in answer the -/// one target-free refusal. A caller the named Mind admits but whose grants do not cover -/// `knowledge_read` answers the coverage refusal instead, which is reachable only by a caller -/// already known to hold a live grant here; the two answers are deliberately different, so a -/// capability gap never reads as a lost admission. +/// The operation's own coverage is deliberately not checked here. `deliberate` reaches the +/// carrier through the workflow, which reads its subject page and revalidates it before it checks +/// `knowledge_read` and `knowledge_write`, so a caller the Mind admits but whose grants do not +/// cover a capability still sees the refusal its request earns first — the plan's order, and the +/// one the refused operations answered before the Mind routing. The host pre-check exists only to +/// resolve the carrier a caller the Mind admits at all may write. pub async fn admitted_carrier_entry( pool: &SqlitePool, principal_id: &str, @@ -84,15 +117,15 @@ pub async fn admitted_carrier_entry( .begin() .await .map_err(|e| Reject::internal(format!("the mind admission could not begin: {e}")).into_spoke())?; - let carrier = admitted_carrier(&mut tx, principal_id, space_id).await; + let space = SpaceId::new(space_id.to_string()); + let located = admit_carrier_location(&mut tx, principal_id, &space, space_id).await; let _ = tx.rollback().await; - carrier.map(|carrier| carrier.carrier_entry_id) + located.map(|(_, carrier)| carrier.carrier_entry_id) } -/// Admission of one Mind-level read, in the order the plan fixes: a live grant of the caller's in -/// the named space — any capability admits, and an unknown, an unadmitted and a frozen-ungranted -/// Mind answer the one target-free refusal — then the space row, then the registry row the carrier -/// comes from, and only then the space-wide `knowledge_read` coverage. +/// Admission of one Mind-level read: the steps above, then the space-wide `knowledge_read` +/// coverage. A read has no subject page ahead of the carrier, so the coverage refusal is its +/// first capability answer. /// /// The two refusals are deliberately different answers. Admission answers the fixed refusal with /// no details, because it must not say whether the named Mind exists. Coverage answers @@ -101,36 +134,16 @@ pub async fn admitted_carrier_entry( /// a Mind the caller was never admitted to. /// /// Every read is confined to the caller's own grant rows. Another principal's malformed row never -/// reaches a decision, and a decode failure on the caller's own row answers the same target-free -/// refusal as a Mind that does not exist. +/// reaches a decision, and a row of the caller's own that cannot decode is skipped exactly as the +/// registry's visibility read skips it. pub(crate) async fn admitted_carrier( tx: &mut Tx<'_>, principal_id: &str, space_id: &str, ) -> Result { - let repository = SqliteMemoryRepository; let space = SpaceId::new(space_id.to_string()); - let rows = caller_grants(tx, principal_id, &space).await?; + let (rows, carrier) = admit_carrier_location(tx, principal_id, &space, space_id).await?; let now = Utc::now(); - if !rows - .iter() - .any(|row| row.principal_id.as_str() == principal_id && admission::live_grant(row, now)) - { - return Err(Reject::admission_refusal().into_spoke()); - } - // The space row is the plan's second step, and it is what `admit_mind` itself checks: a grant - // outlives its space only if the space row is deleted underneath it, which the store never - // does — a Mind's space row, registry row and carrier entry are written in one transaction. - // Keeping the read makes this path refuse exactly the Minds `admit_mind` refuses. - let space_row = repository.space(tx, &space).await.map_err(|error| { - Reject::internal(format!("the mind admission could not be read: {error}")).into_spoke() - })?; - if space_row.is_none() { - return Err(Reject::admission_refusal().into_spoke()); - } - let carrier = registry_carrier(tx, space_id) - .await? - .ok_or_else(|| Reject::admission_refusal().into_spoke())?; // Coverage over the same caller-only rows: another principal's grants are neither needed for // a space-wide requirement nor allowed to reach this decision, and a dead row of the // caller's own covers nothing — projecting one would turn a refusal into a storage error. @@ -161,13 +174,10 @@ async fn caller_grants( principal_id: &str, space: &SpaceId, ) -> Result, SpokeReject> { - SqliteMemoryRepository - .list_grants(tx, space, Some(principal_id)) + mindcore_sqlite::decodable_grants(tx, space, Some(principal_id)) .await - .map_err(|error| match error { - SqliteRepositoryError::InvalidRow(_) => Reject::admission_refusal().into_spoke(), - other => Reject::internal(format!("the mind admission could not be read: {other}")) - .into_spoke(), + .map_err(|error| { + Reject::internal(format!("the mind admission could not be read: {error}")).into_spoke() }) } @@ -409,10 +419,11 @@ impl MemoryWorkflowBinding { space_id: &str, ) -> Result, SpiError> { let space = SpaceId::new(space_id.to_string()); - let rows = admission::grants(&SqliteMemoryRepository, tx, &space) + let rows = admission::grants(tx, &space) .await .map_err(|reject| SpiError::Settlement(reject.into_spoke()))?; - admission::wire_grants(&rows).map_err(|reject| SpiError::Settlement(reject.into_spoke())) + admission::live_wire_grants(&rows, Utc::now()) + .map_err(|reject| SpiError::Settlement(reject.into_spoke())) } /// Bind the carrier its row states, for the facade handle that resolved the diff --git a/crates/mindcore-spoke/tests/memory_adapter.rs b/crates/mindcore-spoke/tests/memory_adapter.rs index 77e605fe..b89637ad 100644 --- a/crates/mindcore-spoke/tests/memory_adapter.rs +++ b/crates/mindcore-spoke/tests/memory_adapter.rs @@ -4883,5 +4883,22 @@ async fn spaces_list_skips_a_mind_whose_only_grant_is_undecodable() { SpokeRejectCode::NotAuthorized, "the skipped Mind answers the admission refusal" ); + + // The mixed set agrees with the list: the Mind with one broken and one live decodable row is + // listed above and served here, because admission skips the row it cannot decode exactly as + // the visibility read does. + let mixed = adapter + .recall( + &mut tx, + &principal(owner), + json!({ "space_id": "mind_extra", "subject_id": SUBJECT, + "selection": { "mode": "subject_all" }, + "budget": { "max_items": 4 } }), + ) + .await; + assert!( + matches!(mixed, SpokeResult::Ok(_)), + "a live decodable row admits beside a broken one: {mixed:?}" + ); tx.rollback().await.expect("rollback"); } diff --git a/crates/mindcore-sqlite/src/lib.rs b/crates/mindcore-sqlite/src/lib.rs index 76a735e9..4c1eec93 100644 --- a/crates/mindcore-sqlite/src/lib.rs +++ b/crates/mindcore-sqlite/src/lib.rs @@ -15,7 +15,7 @@ pub use knowledge::{ RoutedKnowledgeStore, ScopedKnowledgeStore, SERVED_KNOWLEDGE_LIST_LIMIT, }; pub use repository::{ - MemoryExportRow, MemoryImportRow, MemoryReceiptSummary, SqliteMemoryRepository, - SqliteRepositoryError, + decodable_grants, MemoryExportRow, MemoryImportRow, MemoryReceiptSummary, + SqliteMemoryRepository, SqliteRepositoryError, }; pub use store::MindStore; diff --git a/crates/mindcore-sqlite/src/repository.rs b/crates/mindcore-sqlite/src/repository.rs index 2e922961..6472becb 100644 --- a/crates/mindcore-sqlite/src/repository.rs +++ b/crates/mindcore-sqlite/src/repository.rs @@ -951,6 +951,46 @@ struct GrantRow { created_at: String, } +/// `space`'s grant rows, decoded one row at a time: a row the driver cannot hand over and a row +/// that does not decode are both skipped rather than failing the read. +/// +/// Admission and the registry's visibility read share this rule, so a Mind with one live decodable +/// row is both listed and admitted, and only a set with no decodable row refuses. `principal_filter` +/// narrows the read to one caller's rows; `None` reads the whole space for an admin listing. +pub async fn decodable_grants( + tx: &mut Tx<'_>, + space: &SpaceId, + principal_filter: Option<&str>, +) -> Result, SqliteRepositoryError> { + let mut rows = sqlx::query_as!( + GrantRow, + "SELECT grant_id, space_id, subject_id, principal_id, \ + capabilities_json, context_ids_json, shared_access, expires_at, revoked_at, \ + revision, created_at FROM memory_grants \ + WHERE space_id = ? AND (? IS NULL OR principal_id = ?) ORDER BY grant_id", + space.as_str(), + principal_filter, + principal_filter, + ) + .fetch(&mut **tx); + let mut grants = Vec::new(); + while let Some(row) = poll_fn(|cx| rows.as_mut().poll_next(cx)).await { + let row = match row { + Ok(row) => row, + Err(error) => match decode_row(error) { + SqliteRepositoryError::InvalidRow(_) => continue, + other => return Err(other), + }, + }; + match grant_row(row) { + Ok(grant) => grants.push(grant), + Err(SqliteRepositoryError::InvalidRow(_)) => continue, + Err(other) => return Err(other), + } + } + Ok(grants) +} + /// A `memory_profiles` row; `list_profiles` decodes through the macro's /// unchecked UTF-8 contract like every other compile-checked path. struct ProfileRow { From 9968619f1089465d0297d2c74a037225a50e2343 Mon Sep 17 00:00:00 2001 From: Tang Bohao Date: Thu, 26 Nov 2026 15:29:53 +0800 Subject: [PATCH 18/27] fix(serving): decode grant and registry rows one at a time - QC3-02: query_as' try_map ended the stream at the first undecodable row, hiding every good row sorted after it. decodable_grants and the three registry visibility reads now take raw driver rows and decode each one, skipping a row whose columns or JSON do not decode; an undecodable row is invisible rather than fatal. - New regressions place a bad row before a good one: the admission read still admits and the registry page still lists, gets and ids the Mind. The docs state the invisible-row rule. - QC3-03: serving-seam states the deliberation budget's limit - a query already inside SQLite's step cannot be interrupted by the timer and holds its connection until the step ends, the remainder is sampled before the holder and evidence are built, and no cancellation mechanism beyond the timer is attempted. - Addresses QC3-02 and QC3-03 of the serving QC re-review. --- .agents/specs/architecture/serving-seam.md | 8 +++ crates/mindcore-spoke/tests/memory_adapter.rs | 44 ++++++++++++ crates/mindcore-sqlite/src/minds.rs | 72 +++++++++++++++---- crates/mindcore-sqlite/src/repository.rs | 56 ++++++++++----- crates/mindcore-sqlite/tests/minds.rs | 62 ++++++++++++++++ 5 files changed, 209 insertions(+), 33 deletions(-) diff --git a/.agents/specs/architecture/serving-seam.md b/.agents/specs/architecture/serving-seam.md index 69520bb8..cc00547b 100644 --- a/.agents/specs/architecture/serving-seam.md +++ b/.agents/specs/architecture/serving-seam.md @@ -128,6 +128,14 @@ Two of the three workflow tools reach knowledge at all, and only they: `delibera Settlement returns its original `SpokeReject` (code, message and details); malformed arguments and `SpiError::InvalidInput` return `InvalidInput`. A `PolicyRejected` policy veto is also `InvalidInput`, with `details.kind = "policy_rejected"` and the host's reason as the message — never `NotAuthorized`, which stays the lost-admission code. A deadline returns `InternalError` with `details.kind = "deadline_exceeded"` and `details.retry_class = "retryable"`: nothing committed, so the caller may repeat the call. That no-write guarantee now also covers an expiry during the store-connection wait inside `commit_cognition`, and an expiry on a connection already in hand before the begin; it stops at `BEGIN IMMEDIATE`, whose wait for SQLite's write lock is outside the request deadline, and a write that has begun keeps its actual or uncertain outcome. [`mind-model.md`](mind-model.md) owns that boundary. The other provider errors return `InternalError` with `details.kind` set to `embeddings_unavailable`, `embedding_failed`, `reasoner_unavailable`, `reasoner_failed`, or `invalid_reasoner_output` as appropriate and carry no retry class; do not reflect provider internals into the wire message. Errors use the signed error envelope, never a success DTO. The client must negotiate each tool id it intends to invoke; descriptor `capability_id` and `op` match, and the responder owns the `mindcore` namespace. +**The deliberation budget's stated limit.** `deliberate`'s host-side pre-check runs inside the +request's budget, and the timer around it drops the pool wait and starts no workflow when it fires. +A query already inside SQLite's own step cannot be interrupted by that timer — SQLite offers no +cancellation — so its connection stays busy until the step ends, and the time a timed-out call spent +inside the step is not reclaimed. The remaining budget is also sampled after the pre-check and +before the holder and evidence are built, so those builds are charged to the workflow's own deadline +rather than to the sample. No cancellation mechanism beyond the timer is attempted. + ### Adoption face `knowledge.adopt` is the only adoption surface. It is the single registered operation of the diff --git a/crates/mindcore-spoke/tests/memory_adapter.rs b/crates/mindcore-spoke/tests/memory_adapter.rs index b89637ad..e8739c62 100644 --- a/crates/mindcore-spoke/tests/memory_adapter.rs +++ b/crates/mindcore-spoke/tests/memory_adapter.rs @@ -4902,3 +4902,47 @@ async fn spaces_list_skips_a_mind_whose_only_grant_is_undecodable() { ); tx.rollback().await.expect("rollback"); } + +/// An undecodable grant row is invisible, not fatal: admission decodes row by row, so a good row +/// sorted after a bad one still admits the caller and serves the read. `query_as`'s `try_map` +/// would have ended the stream at the bad row. +#[tokio::test] +async fn a_good_grant_after_an_undecodable_row_still_admits() { + let harness = Harness::open().await; + let adapter = MemoryAdapter::new(true); + // A bad row that sorts first — `capabilities_json` holds bytes the driver cannot hand over as + // text — and a good row that sorts after it. + for (grant_id, capabilities) in [ + ("grant_a_bad", "CAST(X'80' AS TEXT)"), + ("grant_z_good", "'[\"recall\"]'"), + ] { + sqlx::query(sqlx::AssertSqlSafe(format!( + "INSERT INTO memory_grants \ + (grant_id, space_id, subject_id, principal_id, capabilities_json, \ + context_ids_json, shared_access, expires_at, revoked_at, revision, created_at) \ + VALUES ('{grant_id}', '{SPACE}', NULL, '{PRINCIPAL}', {capabilities}, '[]', 0, \ + NULL, NULL, 1, '{NOW}')" + ))) + .execute(&harness.pool) + .await + .expect("insert grant"); + } + + let mut tx = harness.begin().await; + let pack = ready( + adapter + .recall( + &mut tx, + &principal(PRINCIPAL), + json!({ "space_id": SPACE, "subject_id": SUBJECT, + "selection": { "mode": "subject_all" }, + "budget": { "max_items": 4 } }), + ) + .await, + ); + assert!( + pack["records"].is_array(), + "the good row after the bad one still admits the caller: {pack}" + ); + tx.rollback().await.expect("rollback"); +} diff --git a/crates/mindcore-sqlite/src/minds.rs b/crates/mindcore-sqlite/src/minds.rs index 5b379d5b..58e0fbc5 100644 --- a/crates/mindcore-sqlite/src/minds.rs +++ b/crates/mindcore-sqlite/src/minds.rs @@ -9,7 +9,8 @@ use std::future::poll_fn; use chrono::Utc; use serde_json::{Map, Number, Value}; -use sqlx::{Sqlite, Transaction}; +use sqlx::sqlite::SqliteRow; +use sqlx::{Row, Sqlite, Transaction}; use mindcore_base::boundary::CallerId; use mindcore_base::ids::{mint, MindId, SpaceId}; @@ -302,6 +303,36 @@ fn row_decodes(capabilities_json: &str, context_ids_json: &str) -> bool { crate::repository::decode_grant_columns(capabilities_json, context_ids_json).is_ok() } +/// One joined row from a raw driver row, or `None` when any column does not decode. +/// +/// `query_as` maps the whole row through SQLx's `try_map`, whose error ends the stream, so a good +/// row sorted after an undecodable one would never be seen. The registry reads take raw driver +/// rows and decode each one here: an undecodable row is invisible rather than fatal. +fn join_of(row: &SqliteRow) -> Option { + Some(( + row.try_get("space_id").ok()?, + row.try_get("knowledge_collection").ok()?, + row.try_get("carrier_entry_id").ok()?, + row.try_get("display_name").ok()?, + row.try_get("status").ok()?, + row.try_get("created_at").ok()?, + row.try_get("expires_at").ok()?, + row.try_get("capabilities_json").ok()?, + row.try_get("context_ids_json").ok()?, + )) +} + +/// One `visible_mind_ids` row from a raw driver row, or `None` when any column does not decode: +/// the id read omits an undecodable row and keeps serving the rest. +fn visible_id_of(row: &SqliteRow) -> Option<(String, Option, String, String)> { + Some(( + row.try_get("space_id").ok()?, + row.try_get("expires_at").ok()?, + row.try_get("capabilities_json").ok()?, + row.try_get("context_ids_json").ok()?, + )) +} + // The visibility rule of `expiry_passed` in `crates/mindcore-spoke/src/admission.rs`, restated // here because `mindcore-sqlite` cannot depend on the adapter: no expiry is live; an expiry // that does not parse as RFC 3339 is never live; the expiry is compared as an instant and never @@ -352,9 +383,10 @@ fn mind_of( /// time — peak memory is the output plus the current row, never one copy per matching grant. /// Rows arrive grouped by Mind: the adjacent-group de-duplication keeps the first live row of /// each group and skips the rest, and an expired row only hides its Mind when no later row of -/// the same group is live. +/// the same group is live. A row whose columns do not decode is invisible rather than fatal: +/// it is skipped and the read keeps going, so a good row sorted after it still lists the Mind. async fn read_visible(store: &MindStore, caller: &CallerId) -> SpokeResult> { - let mut rows = sqlx::query_as::<_, JoinRow>(concat!( + let mut rows = sqlx::query(concat!( grant_columns!(), " WHERE g.principal_id = ?1 AND g.revoked_at IS NULL ORDER BY m.space_id, g.grant_id" )) @@ -363,7 +395,11 @@ async fn read_visible(store: &MindStore, caller: &CallerId) -> SpokeResult = None; while let Some(row) = poll_fn(|cx| rows.as_mut().poll_next(cx)).await { - let ( + let row = match row { + Ok(row) => row, + Err(_) => return storage_unavailable(), + }; + let Some(( space_id, collection, carrier, @@ -373,9 +409,9 @@ async fn read_visible(store: &MindStore, caller: &CallerId) -> SpokeResult row, - Err(_) => return storage_unavailable(), + )) = join_of(&row) + else { + continue; }; if emitted.as_deref() == Some(space_id.as_str()) { continue; @@ -411,7 +447,7 @@ async fn read_one_visible( caller: &CallerId, id: &MindId, ) -> SpokeResult> { - let mut rows = sqlx::query_as::<_, JoinRow>(concat!( + let mut rows = sqlx::query(concat!( grant_columns!(), " WHERE g.principal_id = ?1 AND g.space_id = ?2 AND g.revoked_at IS NULL ORDER BY g.grant_id" )) @@ -419,7 +455,11 @@ async fn read_one_visible( .bind(id.as_str()) .fetch(&store.pool); while let Some(row) = poll_fn(|cx| rows.as_mut().poll_next(cx)).await { - let ( + let row = match row { + Ok(row) => row, + Err(_) => return storage_unavailable(), + }; + let Some(( space_id, collection, carrier, @@ -429,9 +469,9 @@ async fn read_one_visible( expires_at, capabilities_json, context_ids_json, - ) = match row { - Ok(row) => row, - Err(_) => return storage_unavailable(), + )) = join_of(&row) + else { + continue; }; if !live(&expires_at) { continue; @@ -465,7 +505,7 @@ pub async fn visible_mind_ids( tx: &mut Transaction<'_, Sqlite>, caller: &str, ) -> SpokeResult> { - let mut rows = sqlx::query_as::<_, (String, Option, String, String)>( + let mut rows = sqlx::query( "SELECT m.space_id, g.expires_at, g.capabilities_json, g.context_ids_json \ FROM memory_grants g \ JOIN minds m ON m.space_id = g.space_id \ @@ -477,10 +517,14 @@ pub async fn visible_mind_ids( let mut ids = Vec::new(); let mut emitted: Option = None; while let Some(row) = poll_fn(|cx| rows.as_mut().poll_next(cx)).await { - let (space_id, expires_at, capabilities_json, context_ids_json) = match row { + let row = match row { Ok(row) => row, Err(_) => return storage_unavailable(), }; + let Some((space_id, expires_at, capabilities_json, context_ids_json)) = visible_id_of(&row) + else { + continue; + }; if emitted.as_deref() == Some(space_id.as_str()) { continue; } diff --git a/crates/mindcore-sqlite/src/repository.rs b/crates/mindcore-sqlite/src/repository.rs index 6472becb..9caeb6ea 100644 --- a/crates/mindcore-sqlite/src/repository.rs +++ b/crates/mindcore-sqlite/src/repository.rs @@ -12,7 +12,8 @@ use std::future::poll_fn; use async_trait::async_trait; use chrono::Utc; use serde_json::{json, Map, Number, Value}; -use sqlx::Sqlite; +use sqlx::sqlite::SqliteRow; +use sqlx::{Row, Sqlite}; use mindcore_base::boundary::CallerId; use mindcore_base::ids::{ContextId, SpaceId, SubjectId}; @@ -951,46 +952,63 @@ struct GrantRow { created_at: String, } -/// `space`'s grant rows, decoded one row at a time: a row the driver cannot hand over and a row -/// that does not decode are both skipped rather than failing the read. +/// `space`'s grant rows, decoded one row at a time: a row whose columns or JSON do not decode is +/// **invisible** rather than fatal, so a good row sorted after a bad one is still read. /// -/// Admission and the registry's visibility read share this rule, so a Mind with one live decodable -/// row is both listed and admitted, and only a set with no decodable row refuses. `principal_filter` -/// narrows the read to one caller's rows; `None` reads the whole space for an admin listing. +/// `query_as!` maps a whole row through SQLx's `try_map`, whose error ends the stream — one bad +/// row would hide every later one. This read takes raw driver rows and decodes each one on its +/// own, which is the rule the registry's visibility read applies: admission and the listing share +/// it, so a Mind with one live decodable row is both listed and admitted, and only a set with no +/// decodable row refuses. `principal_filter` narrows the read to one caller's rows; `None` reads +/// the whole space for an admin listing. pub async fn decodable_grants( tx: &mut Tx<'_>, space: &SpaceId, principal_filter: Option<&str>, ) -> Result, SqliteRepositoryError> { - let mut rows = sqlx::query_as!( - GrantRow, + let mut rows = sqlx::query( "SELECT grant_id, space_id, subject_id, principal_id, \ capabilities_json, context_ids_json, shared_access, expires_at, revoked_at, \ revision, created_at FROM memory_grants \ WHERE space_id = ? AND (? IS NULL OR principal_id = ?) ORDER BY grant_id", - space.as_str(), - principal_filter, - principal_filter, ) + .bind(space.as_str()) + .bind(principal_filter) + .bind(principal_filter) .fetch(&mut **tx); let mut grants = Vec::new(); while let Some(row) = poll_fn(|cx| rows.as_mut().poll_next(cx)).await { let row = match row { Ok(row) => row, - Err(error) => match decode_row(error) { - SqliteRepositoryError::InvalidRow(_) => continue, - other => return Err(other), - }, + // A driver failure on the stream itself is not a row's fault. + Err(error) => return Err(error.into()), }; - match grant_row(row) { - Ok(grant) => grants.push(grant), - Err(SqliteRepositoryError::InvalidRow(_)) => continue, - Err(other) => return Err(other), + if let Some(grant) = grant_of(&row) { + grants.push(grant); } } Ok(grants) } +/// One grant row from a raw driver row, or `None` when a column or either JSON column does not +/// decode. The caller skips it; nothing about this row ends the read. +fn grant_of(row: &SqliteRow) -> Option { + let row = GrantRow { + grant_id: row.try_get("grant_id").ok()?, + space_id: row.try_get("space_id").ok()?, + subject_id: row.try_get("subject_id").ok()?, + principal_id: row.try_get("principal_id").ok()?, + capabilities_json: row.try_get("capabilities_json").ok()?, + context_ids_json: row.try_get("context_ids_json").ok()?, + shared_access: row.try_get("shared_access").ok()?, + expires_at: row.try_get("expires_at").ok()?, + revoked_at: row.try_get("revoked_at").ok()?, + revision: row.try_get("revision").ok()?, + created_at: row.try_get("created_at").ok()?, + }; + grant_row(row).ok() +} + /// A `memory_profiles` row; `list_profiles` decodes through the macro's /// unchecked UTF-8 contract like every other compile-checked path. struct ProfileRow { diff --git a/crates/mindcore-sqlite/tests/minds.rs b/crates/mindcore-sqlite/tests/minds.rs index f8686cae..e05971d4 100644 --- a/crates/mindcore-sqlite/tests/minds.rs +++ b/crates/mindcore-sqlite/tests/minds.rs @@ -1000,3 +1000,65 @@ async fn get_returns_the_same_mind_after_reopen() { .await); assert_eq!(created, seen); } + +/// An undecodable grant row is invisible, not fatal: the registry's reads decode row by row, so a +/// good row sorted after a bad one still lists, gets and admits the Mind. `query_as`'s `try_map` +/// would have ended the stream at the bad row. +#[tokio::test] +async fn a_good_grant_after_an_undecodable_row_still_lists_the_mind() { + let temp = tempfile::tempdir().expect("private temporary root"); + let path = temp.path().join("mindcore.db"); + let store = open_store(&path).await; + let pool = store.pool(); + let caller = CallerId::new("caller_wren"); + ok(store + .create_mind(&request(Some("wren"), "caller_wren")) + .await); + + // Replace the created grant with a bad row that sorts first and a good row that sorts after + // it. `expires_at` is selected by the visibility join; the blob cast stores bytes the driver + // cannot hand over as text. + sqlx::query("DELETE FROM memory_grants WHERE space_id = 'wren'") + .execute(&pool) + .await + .expect("drop the created grant"); + for (grant_id, expires_at) in [ + ("grant_a_bad", "CAST(X'80' AS TEXT)"), + ("grant_z_good", "NULL"), + ] { + sqlx::query(sqlx::AssertSqlSafe(format!( + "INSERT INTO memory_grants \ + (grant_id, space_id, subject_id, principal_id, capabilities_json, \ + context_ids_json, shared_access, expires_at, revoked_at, revision, created_at) \ + VALUES ('{grant_id}', 'wren', NULL, 'caller_wren', '[\"recall\"]', '[]', 0, \ + {expires_at}, NULL, 1, '{TIME}')" + ))) + .execute(&pool) + .await + .expect("insert grant"); + } + + let listed = ok(store.list_minds(&caller).await); + assert_eq!( + listed + .iter() + .map(|mind| mind.id.as_str().to_string()) + .collect::>(), + vec!["wren".to_string()], + "the good row after the bad one still lists the Mind" + ); + assert_eq!( + ok(store.get_mind(&caller, &MindId::new("wren")).await).id, + MindId::new("wren"), + "the point read applies the same rule" + ); + + // The served list's id read shares it. + let mut tx = pool_begin(&store).await; + assert_eq!( + ok(mindcore_sqlite::minds::visible_mind_ids(&mut tx, "caller_wren").await), + vec!["wren".to_string()], + "the id read omits the undecodable row and keeps serving" + ); + tx.rollback().await.expect("rollback"); +} From 79768b2cfb8374ab8e738b9f78371140a10644f3 Mon Sep 17 00:00:00 2001 From: Tang Bohao Date: Thu, 26 Nov 2026 15:32:47 +0800 Subject: [PATCH 19/27] test(serving): pin the admin grant view and move its cursor marker - New loopback `the_admin_grant_view_reads_the_space_and_moves_its_marker` through a host memory service that dispatches memory.grants.list to the adapter: an admin naming another principal receives that principal's rows, the admin naming none receives the whole space's decodable set (a stranger's undecodable row invisible), a non-admin naming another principal receives only its own rows, and another principal's grant change makes the admin's issued cursor answer CursorInvalid. - serving-seam's budget limit now says the implementation relies on the timer plus dropping the pool wait and does not use SQLite's own interrupt handle, and that holder/evidence construction sits between the budget sample and the SPI deadline, counted in neither segment. --- .agents/specs/architecture/serving-seam.md | 11 +- crates/mindcore-runtime/tests/loopback.rs | 205 ++++++++++++++++++++- 2 files changed, 208 insertions(+), 8 deletions(-) diff --git a/.agents/specs/architecture/serving-seam.md b/.agents/specs/architecture/serving-seam.md index cc00547b..41b7c1bd 100644 --- a/.agents/specs/architecture/serving-seam.md +++ b/.agents/specs/architecture/serving-seam.md @@ -129,12 +129,11 @@ Two of the three workflow tools reach knowledge at all, and only they: `delibera Settlement returns its original `SpokeReject` (code, message and details); malformed arguments and `SpiError::InvalidInput` return `InvalidInput`. A `PolicyRejected` policy veto is also `InvalidInput`, with `details.kind = "policy_rejected"` and the host's reason as the message — never `NotAuthorized`, which stays the lost-admission code. A deadline returns `InternalError` with `details.kind = "deadline_exceeded"` and `details.retry_class = "retryable"`: nothing committed, so the caller may repeat the call. That no-write guarantee now also covers an expiry during the store-connection wait inside `commit_cognition`, and an expiry on a connection already in hand before the begin; it stops at `BEGIN IMMEDIATE`, whose wait for SQLite's write lock is outside the request deadline, and a write that has begun keeps its actual or uncertain outcome. [`mind-model.md`](mind-model.md) owns that boundary. The other provider errors return `InternalError` with `details.kind` set to `embeddings_unavailable`, `embedding_failed`, `reasoner_unavailable`, `reasoner_failed`, or `invalid_reasoner_output` as appropriate and carry no retry class; do not reflect provider internals into the wire message. Errors use the signed error envelope, never a success DTO. The client must negotiate each tool id it intends to invoke; descriptor `capability_id` and `op` match, and the responder owns the `mindcore` namespace. **The deliberation budget's stated limit.** `deliberate`'s host-side pre-check runs inside the -request's budget, and the timer around it drops the pool wait and starts no workflow when it fires. -A query already inside SQLite's own step cannot be interrupted by that timer — SQLite offers no -cancellation — so its connection stays busy until the step ends, and the time a timed-out call spent -inside the step is not reclaimed. The remaining budget is also sampled after the pre-check and -before the holder and evidence are built, so those builds are charged to the workflow's own deadline -rather than to the sample. No cancellation mechanism beyond the timer is attempted. +request's budget: this implementation relies on the timer plus dropping the pool wait, so an expiry +starts no workflow, and it does not use SQLite's own interrupt handle — a query already inside +SQLite's step runs to that step's end and holds its connection until then. The remaining budget is +sampled after the pre-check, and the holder and evidence are built between that sample and the +workflow's SPI deadline, so their construction is counted in neither segment. ### Adoption face diff --git a/crates/mindcore-runtime/tests/loopback.rs b/crates/mindcore-runtime/tests/loopback.rs index fed16304..42a1516a 100644 --- a/crates/mindcore-runtime/tests/loopback.rs +++ b/crates/mindcore-runtime/tests/loopback.rs @@ -31,7 +31,7 @@ use mindcore_spi::{ CognitiveTaskKind, Embedder, EmbeddingIdentity, PolicyDecision, PolicyHook, Reasoner, SettlementDraft, SpiError, StructuredReasonRequest, }; -use mindcore_spoke::{ServedMemory, TransferService}; +use mindcore_spoke::{MemoryAdapter, MemoryStage, ServedMemory, TransferService}; use mindcore_sqlite::{MindStore, SqliteMemoryRepository}; use spoke_connect::core::derive_peer_id_from_ed25519_pubkey; use spoke_connect::remote::{ @@ -45,7 +45,8 @@ use spoke_operations::{ }; use spoke_schemas::host_capability_manifest::ToolDescriptor; use spoke_schemas::{ - HostCapabilityManifest, KnowledgeAdoptRequest, MemoryRecallRequest, Principal, Scope, + HostCapabilityManifest, KnowledgeAdoptRequest, MemoryGrantsListRequest, + MemoryGrantsListResponse, MemoryRecallRequest, Principal, Scope, }; const SCOPE_ID: &str = "spoke-scope-001"; @@ -2298,6 +2299,206 @@ async fn memory_ops_are_served_only_when_the_host_attaches_the_face() { assert_eq!(body["total_authorized"], 7); } +/// A host memory service that serves `memory.grants.list` through the adapter over one pool, so +/// the admin view of the listing can be driven on a signed session. +struct GrantsListFace { + pool: sqlx::SqlitePool, + admission: MemoryAdmission, +} + +#[async_trait] +impl RemoteMemoryService for GrantsListFace { + async fn invoke(&self, peer_id: &str, op: &str, payload: Value) -> SpokeResult { + if op != "memory.grants.list" { + return spoke_reject( + SpokeRejectCode::CapabilityPortMissing, + format!("the fixture grants face does not serve {op}"), + None, + ); + } + let principal = match (self.admission)(peer_id) { + SpokeResult::Ok(principal) => principal, + SpokeResult::Reject(reject) => return SpokeResult::Reject(reject), + }; + let mut tx = match self.pool.begin().await { + Ok(tx) => tx, + Err(error) => { + return spoke_reject( + SpokeRejectCode::InternalError, + format!("the fixture grants face could not begin: {error}"), + None, + ) + } + }; + let stage = MemoryAdapter::new(true) + .list_grants(&mut tx, &principal, payload) + .await; + let _ = tx.rollback().await; + match stage { + SpokeResult::Ok(MemoryStage::Ready(body)) => SpokeResult::Ok(body), + SpokeResult::Ok(_) => spoke_reject( + SpokeRejectCode::InternalError, + "grants.list staged an outcome the fixture face cannot finish", + None, + ), + SpokeResult::Reject(reject) => SpokeResult::Reject(reject), + } + } +} + +impl ServedMemory for GrantsListFace {} + +/// The admin view of `memory.grants.list` over a signed session: an admin naming another principal +/// receives that principal's grant rows (not an empty page), the same admin naming none receives +/// the whole space's decodable set, a non-admin naming another principal still receives only its +/// own rows, and another principal's grant change moves the cursor marker an admin's page is +/// checked against. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn the_admin_grant_view_reads_the_space_and_moves_its_marker() { + let fixture = Fixture::open().await; + let pool = fixture.store.pool(); + fixture.grant("grt_admin_view", PRINCIPAL, &["admin"]).await; + fixture + .grant("grt_peer_two_recall", PEER_TWO_PRINCIPAL, &["recall"]) + .await; + fixture + .grant("grt_peer_two_capture", PEER_TWO_PRINCIPAL, &["capture"]) + .await; + // A stranger's undecodable row is invisible to the view, never fatal. + sqlx::query(sqlx::AssertSqlSafe(format!( + "INSERT INTO memory_grants \ + (grant_id, space_id, subject_id, principal_id, capabilities_json, context_ids_json, \ + shared_access, expires_at, revoked_at, revision, created_at) \ + VALUES ('grant_a_bad', '{SPACE}', NULL, 'prn_stranger', CAST(X'80' AS TEXT), '[]', 0, \ + NULL, NULL, 1, '{NOW}')" + ))) + .execute(&pool) + .await + .expect("seed the undecodable row"); + let (_dir, serve) = fixture.serve(); + let mut faces = faces( + hello("runtime", &[]), + Some(Arc::new(GrantsListFace { + pool: pool.clone(), + admission: two_principal_admission(), + })), + MindProviders::default(), + ); + faces.principals = two_principal_admission(); + let surface = surface(&serve, faces); + + let request = |payload: Value| -> MemoryGrantsListRequest { + serde_json::from_value(payload).expect("the grants list request JSON matches the schema") + }; + let granted = |result: SpokeResult| -> (Vec, Value) { + let response = expect_ok(result, "grants.list"); + let value = serde_json::to_value(response).expect("the grants list response serializes"); + let ids = value["grants"] + .as_array() + .expect("a grants array") + .iter() + .map(|grant| { + grant["grant_id"] + .as_str() + .expect("every served grant names its id") + .to_string() + }) + .collect(); + (ids, value["next_cursor"].clone()) + }; + + let admin_session = connect(&surface, &["spoke-memory"]).await; + let (named, _) = granted( + MemoryPort::list_grants( + &*admin_session.adapter, + &principal(), + request(json!({ "space_id": SPACE, "principal_id": PEER_TWO_PRINCIPAL })), + ) + .await, + ); + assert_eq!( + named, + ["grt_peer_two_capture", "grt_peer_two_recall"], + "an admin naming another principal receives that principal's rows, not an empty page" + ); + + let (all, _) = granted( + MemoryPort::list_grants( + &*admin_session.adapter, + &principal(), + request(json!({ "space_id": SPACE })), + ) + .await, + ); + assert_eq!( + all, + [ + "grt_admin_view", + "grt_knowledge", + "grt_peer_two_capture", + "grt_peer_two_recall", + "grt_recall", + ], + "an admin naming no principal receives the whole space's decodable set: {all:?}" + ); + assert!( + !all.contains(&"grant_a_bad".to_string()), + "the undecodable row is invisible to the admin page: {all:?}" + ); + + let peer_session = connect_as(&surface, &PEER_TWO_SEED, &["spoke-memory"]).await; + let (own, _) = granted( + MemoryPort::list_grants( + &*peer_session.adapter, + &principal_for(PEER_TWO_PRINCIPAL), + request(json!({ "space_id": SPACE, "principal_id": PRINCIPAL })), + ) + .await, + ); + assert_eq!( + own, + ["grt_peer_two_capture", "grt_peer_two_recall"], + "a non-admin naming another principal still receives only its own rows" + ); + + // The cursor marker covers the set the admin page was built from, so another principal's + // grant change invalidates a cursor the admin already holds. + let (page, cursor) = granted( + MemoryPort::list_grants( + &*admin_session.adapter, + &principal(), + request(json!({ "space_id": SPACE, "limit": 1 })), + ) + .await, + ); + assert_eq!(page.len(), 1); + let cursor = cursor + .as_str() + .unwrap_or_else(|| panic!("a bounded page advances: {cursor}")) + .to_string(); + sqlx::query( + "UPDATE memory_grants SET revision = 2, capabilities_json = '[\"recall\",\"capture\"]' \ + WHERE grant_id = 'grt_peer_two_recall'", + ) + .execute(&pool) + .await + .expect("change another principal's grant"); + let stale = expect_reject( + MemoryPort::list_grants( + &*admin_session.adapter, + &principal(), + request(json!({ "space_id": SPACE, "cursor": cursor })), + ) + .await, + "an admin cursor issued before another principal's grant changed", + ); + assert_eq!( + stale.code, + SpokeRejectCode::CursorInvalid, + "another principal's grant change moves the admin's marker: {stale:?}" + ); +} + /// The five §7.29–§7.33 operations over the real store. A service that reports all five earns /// `spoke-memory-transfer`, and every op reaches the adapter through the signed session. The /// service owns each op's transaction, so the export one create commits is the artifact the From f2bf33165704d1ebb05c39bc22c10a17fa70dc08 Mon Sep 17 00:00:00 2001 From: bibi Date: Thu, 26 Nov 2026 15:41:40 +0800 Subject: [PATCH 20/27] docs(knowledge): record that query_as! ends the row stream on one bad column --- ...lite-planner-shape-and-sqlx-query-forms.md | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/.agents/knowledge/architecture-patterns/sqlite-planner-shape-and-sqlx-query-forms.md b/.agents/knowledge/architecture-patterns/sqlite-planner-shape-and-sqlx-query-forms.md index 8bf75254..8a02b58c 100644 --- a/.agents/knowledge/architecture-patterns/sqlite-planner-shape-and-sqlx-query-forms.md +++ b/.agents/knowledge/architecture-patterns/sqlite-planner-shape-and-sqlx-query-forms.md @@ -113,3 +113,29 @@ principal and tests the visible set there. SELECT grant_id, revision FROM memory_grants WHERE principal_id = ? AND +space_id IN (SELECT value FROM json_each(?)); ``` + +### A single undecodable column aborts the whole row stream + +`query_as!` compiles to `sqlx::query(...).try_map(...)`, and the `?` inside that mapper ends the +stream. One row whose column cannot be decoded (bad UTF-8, malformed JSON, an unparseable +timestamp) therefore hides every row sorted after it — so a "skip the bad row and keep going" rule +written outside the mapper never runs. The same shape appears in a visibility read that projects a +whole page. + +### After + +When a read must tolerate a bad row, do not use `query_as!`. Select with `sqlx::query` and decode +each `SqliteRow` yourself in a loop that records the failure and continues: + +```rust +let mut rows = sqlx::query("SELECT grant_id, capability, expires_at FROM memory_grants WHERE space_id = ?") + .bind(space_id).fetch(tx.as_mut()); +let mut out = Vec::new(); +while let Some(row) = rows.try_next().await? { // stream survives the bad row + match grant_of(&row) { Ok(g) => out.push(g), Err(_) => continue } // row-local failure +} +``` + +The rule this encodes: decide whether a row is decodable **at the row**, and let the loop decide +what a failure means (skip it for a visibility read, refuse for a single-row point read). A +`try_map` mapper cannot express that choice, because its failure is the stream's failure. From 2358294a4dd3217e92d921cb6b81899c005d9eb8 Mon Sep 17 00:00:00 2001 From: Tang Bohao Date: Thu, 26 Nov 2026 16:02:33 +0800 Subject: [PATCH 21/27] fix(serving): hide an owner-private carrier from the viewpoint-free cognition read MemoryAdapter::read_cognition returned the carrier's judgments to any peer holding knowledge_read without the recall knowledge slot's disclosure predicate, so an owner-private carrier leaked its judgments to a viewpoint-free peer. The read now applies the same predicate (knowledge_entry_visible_to_viewpoint, None) after admission and the knowledge_read coverage: a hidden carrier answers the empty view a Mind that has judged nothing answers, and no derivation runs on its records. Regression: the owner-private carrier reads empty with a null MindState, the space-visible carrier still serves its record and derived state. Devin review must-fix (SEC), layer PR #56. --- crates/mindcore-spoke/src/lib.rs | 20 +++- crates/mindcore-spoke/tests/workflows.rs | 134 +++++++++++++++++++++++ 2 files changed, 152 insertions(+), 2 deletions(-) diff --git a/crates/mindcore-spoke/src/lib.rs b/crates/mindcore-spoke/src/lib.rs index ae9f7394..cea10736 100644 --- a/crates/mindcore-spoke/src/lib.rs +++ b/crates/mindcore-spoke/src/lib.rs @@ -30,7 +30,10 @@ pub(crate) use mindcore_base::ids::mint; use chrono::Utc; use serde::de::DeserializeOwned; use serde_json::Value; -use spoke_operations::{GrantRequirement, SpokeReject, SpokeRejectCode, SpokeResult}; +use spoke_operations::{ + knowledge_entry_visible_to_viewpoint, GrantRequirement, SpokeReject, SpokeRejectCode, + SpokeResult, +}; use spoke_schemas::Principal; use sqlx::{Sqlite, Transaction}; @@ -329,7 +332,10 @@ impl MemoryAdapter { /// A fresh carrier answers `records: []` and `mind_state: null`; a stored carrier that cannot /// be derived is a terminal `InternalError`, matching the facade's `cognition_read`, because /// the carrier passed validation at its write and repeating the read cannot change it. The - /// transaction is the caller's to end. + /// recall knowledge slot's disclosure predicate applies here too, viewpoint-free: an + /// `owner`-private carrier answers the same empty view a Mind that has judged nothing + /// answers, and the derived `MindState` sees the filtered set. The transaction is the + /// caller's to end. pub async fn read_cognition( tx: &mut Tx<'_>, principal: &Principal, @@ -354,6 +360,16 @@ impl MemoryAdapter { .into_spoke()) } }; + // The knowledge slot's disclosure predicate, viewpoint-free: admission and the + // `knowledge_read` coverage above stay first, but a carrier they hide — an + // `owner`-private one — answers the empty view, and no derivation runs on its records. + if !knowledge_entry_visible_to_viewpoint(&carrier_entry, None) { + return Ok(Cognition { + carrier_revision: revision, + records: Vec::new(), + mind_state: Value::Null, + }); + } let view = match mindcore_base::cognition::derive_mind_state(&carrier_entry) { Ok(view) => view, Err(mindcore_base::cognition::MindError::NoRecords) => { diff --git a/crates/mindcore-spoke/tests/workflows.rs b/crates/mindcore-spoke/tests/workflows.rs index e19783b2..8756ff3c 100644 --- a/crates/mindcore-spoke/tests/workflows.rs +++ b/crates/mindcore-spoke/tests/workflows.rs @@ -357,6 +357,66 @@ impl Harness { .expect("seed knowledge entry"); } + /// Rewrites the carrier entry's payload, revision unchanged: the shape the + /// disclosure fix reads is the live row's current payload. + async fn set_carrier_payload(&self, payload: Value) { + sqlx::query( + "UPDATE knowledge_entries SET payload = ? \ + WHERE collection = 'wren' AND entry_id = 'ke_wren'", + ) + .bind(payload.to_string()) + .execute(&self.pool) + .await + .expect("rewrite the carrier payload"); + } + + /// One schema-valid belief judgment on the carrier, stored the way a + /// dedicated append stores it: a `cognition_records` row the read hydrates + /// into the payload's `records` member. + async fn judgment(&self, record_id: &str) { + let reference = |kind: &str, id: &str| json!({ "kind": kind, "id": id, "namespace": "mindcore" }); + let record = json!({ + "assessed_at": NOW, + "assessment_context": { "context_id": "ctx_gate" }, + "assessor": reference("knowledge_entry", "ke_wren"), + "assessor_role": "holder_self_report", + "basis": { + "acquisition": "Perception", + "evidence": [reference("memory_record", "rec_gate")], + "kind": "evidence", + }, + "effective_at": NOW, + "extensions": {}, + "holder": reference("knowledge_entry", "ke_wren"), + "kind": "belief", + "order": 1, + "q": { + "assertion": "belief_attribution", + "calibration": "uncalibrated", + "method": "single_self_report", + "value": 0.4, + }, + "record_id": record_id, + "target": { + "carrier": reference("knowledge_entry", "ke_wren"), + "kind": "proposition", + "target_id": "prop_gate_closed", + }, + "truth": "True", + "view": "current", + }); + sqlx::query( + "INSERT INTO cognition_records \ + (collection, entry_id, append_seq, record_id, payload, append_prior_shape) \ + VALUES ('wren', 'ke_wren', 1, ?, ?, 0)", + ) + .bind(record_id) + .bind(record.to_string()) + .execute(&self.pool) + .await + .expect("seed the judgment record"); + } + fn embedder(&self, side_effect: SideEffect) -> BoundaryEmbedder { BoundaryEmbedder { identity: EmbeddingIdentity { @@ -923,6 +983,80 @@ async fn knowledge_slot_omits_a_superseded_entry() { ); } +/// `read_cognition` applies the knowledge slot's disclosure predicate, viewpoint-free: an +/// `owner`-private carrier's judgments answer the empty view a Mind that has judged nothing +/// answers — no records and a null `MindState` derived from the filtered set — while a +/// space-visible carrier still serves its record and derived state to the same +/// `knowledge_read` peer. +#[tokio::test] +async fn cognition_read_hides_an_owner_private_carrier_from_a_viewpoint_free_peer() { + let harness = Harness::open().await; + harness.grant(&["knowledge_read"]).await; + // One judgment on the carrier, stored the way a dedicated append stores it: a + // `cognition_records` row the read hydrates into the payload's module. + let module = json!({ + "records": [], + "world_facts": [], + "extensions": {}, + }); + let private_payload = json!({ + "schema_version": 1, + "entry_id": "ke_wren", + "entry_type": "character", + "canonical_name": "ke_wren carrier", + "status": "confirmed", + "revision": 1, + "body": {}, + "disclosure": "owner-private", + "owner": "prn_owner", + "modules": { "cognition": module }, + "extensions": {}, + }); + harness.set_carrier_payload(private_payload).await; + harness.judgment("rec_judgment").await; + let mut tx = harness.pool.begin().await.expect("begin hidden read"); + let hidden = MemoryAdapter::read_cognition(&mut tx, &principal(), SPACE) + .await + .expect("the hidden carrier read"); + assert_eq!(hidden.carrier_revision, 1); + assert_eq!( + hidden.records, + Vec::::new(), + "an owner-private carrier serves no records to a viewpoint-free peer" + ); + assert_eq!( + hidden.mind_state, + Value::Null, + "the derived state follows the filtered set: {hidden:?}" + ); + drop(tx); + + // The same carrier made space-visible reads whole: the record and its derived MindState. + let visible_payload = json!({ + "schema_version": 1, + "entry_id": "ke_wren", + "entry_type": "character", + "canonical_name": "ke_wren carrier", + "status": "confirmed", + "revision": 1, + "body": {}, + "modules": { "cognition": module }, + "extensions": {}, + }); + harness.set_carrier_payload(visible_payload).await; + let mut tx = harness.pool.begin().await.expect("begin visible read"); + let visible = MemoryAdapter::read_cognition(&mut tx, &principal(), SPACE) + .await + .expect("the space-visible carrier read"); + assert_eq!(visible.carrier_revision, 1); + let records = &visible.records; + assert_eq!(records.len(), 1, "the judgment serves once visible: {visible:?}"); + assert_eq!(records[0]["record_id"], "rec_judgment"); + assert!(visible.mind_state.is_object(), "the derived state serves beside the record"); + assert_eq!(visible.mind_state["mind_state_id"], SPACE); + assert_eq!(visible.mind_state["holder_entry_id"], "ke_wren"); +} + /// Tombstoning a record prunes its stored vectors in the tombstone's own transaction: /// a row the store can never serve again must not outlive the live record. #[tokio::test] From b6c119e55c64f04195abf17af23a9eb1769530cb Mon Sep 17 00:00:00 2001 From: Tang Bohao Date: Thu, 26 Nov 2026 16:14:12 +0800 Subject: [PATCH 22/27] fix(serving): reserve every runtime tool id, not just the retired adopt tool The retired-adopt filter dropped exactly one id from host registrations, so a host registration carrying tools.mindcore.absorb/.deliberate/.recall_context/ .read_cognition still reached the same capability_id after the runtime's own registration: a duplicated manifest entry and a second handler for an id the runtime serves. The filter now drops every host registration carrying one of the runtime's reserved ids (the four served tools plus the retired adoption tool); host tools keep every other id, including tools.mindcore.host_tool, whose served-host-tool contract the surface and loopback fixtures pin. Regression: a host registration borrowing all five reserved ids leaves the manifest byte-identical to the composed baseline. Verified fails-first on the prior head. --- crates/mindcore-runtime/src/lib.rs | 18 ++++++- crates/mindcore-runtime/tests/surface.rs | 62 +++++++++++++----------- 2 files changed, 51 insertions(+), 29 deletions(-) diff --git a/crates/mindcore-runtime/src/lib.rs b/crates/mindcore-runtime/src/lib.rs index 197a6786..8ddf63c5 100644 --- a/crates/mindcore-runtime/src/lib.rs +++ b/crates/mindcore-runtime/src/lib.rs @@ -49,6 +49,18 @@ const TOOLS_NAMESPACE: &str = "mindcore"; /// under it. const RETIRED_ADOPT_TOOL: &str = "tools.mindcore.adopt"; +/// The tool ids the runtime reserves: the four it registers itself, plus the retired adoption +/// tool. A host registration carrying one is dropped, so no host can advertise or install +/// anything the runtime serves, or anything under the id a retired tool once answered. Host +/// tools keep every other id, inside the namespace and out. +const RESERVED_TOOLS: [&str; 5] = [ + tools::RECALL_CONTEXT, + tools::ABSORB, + tools::DELIBERATE, + tools::READ_COGNITION, + RETIRED_ADOPT_TOOL, +]; + /// The Mindcore serving side over one host store. /// /// The workflow engine runs on the same pool the host's store serves, so a tool call and a @@ -111,7 +123,7 @@ impl MindcoreServe { faces .tools .into_iter() - .filter(|tool| tool.descriptor.capability_id.as_str() != RETIRED_ADOPT_TOOL), + .filter(|tool| !RESERVED_TOOLS.contains(&tool.descriptor.capability_id.as_str())), ); let manifest = match derive_manifest(faces.manifest, faces.memory.as_deref(), &tools) { SpokeResult::Ok(manifest) => manifest, @@ -170,7 +182,9 @@ pub struct ServeFaces { /// Providers and the domain lens injected into each workflow call. pub providers: MindProviders, /// Additional host tools: every descriptor is advertised and its handler installed, except - /// the retired `tools.mindcore.adopt` on every surface. + /// registrations carrying one of the runtime's reserved tool ids — the four tools the + /// runtime registers itself and the retired `tools.mindcore.adopt` — which are dropped on + /// every surface. pub tools: Vec, } diff --git a/crates/mindcore-runtime/tests/surface.rs b/crates/mindcore-runtime/tests/surface.rs index f842ae8e..bcb0d00c 100644 --- a/crates/mindcore-runtime/tests/surface.rs +++ b/crates/mindcore-runtime/tests/surface.rs @@ -223,47 +223,55 @@ async fn manifest_follows_the_composed_faces() { ); } -/// The retired adoption id is the runtime's: a host registration of `tools.mindcore.adopt` is -/// dropped, so it appears in neither `capabilities` nor `tools`. +/// Every reserved id is the runtime's: a host registration borrowing one of the four served +/// tool ids, or the retired adoption id, is dropped, so it appears in neither `capabilities` +/// nor `tools` and the runtime's own registrations stand. #[tokio::test] -async fn a_host_registration_cannot_shadow_the_adoption_tool() { +async fn a_host_registration_cannot_shadow_a_runtime_tool() { let serve = Fixture::open().await.serve(); let surface = expect_ok( serve.surface(ServeFaces { - tools: vec![shadowing_adoption()], + tools: vec![ + shadowing(RECALL_CONTEXT), + shadowing(ABSORB), + shadowing(DELIBERATE), + shadowing(READ_COGNITION), + shadowing(RETIRED_ADOPT), + ], ..faces(metadata("runtime")) }), "assemble a surface a host tries to shadow", ); - assert!( - !capabilities(&surface).contains(&RETIRED_ADOPT), - "a host registration supplied the retired id: {:?}", + assert_eq!( + capabilities(&surface), + [ + CAPABILITY_SPOKE_JUDGMENT, + RECALL_CONTEXT, + ABSORB, + DELIBERATE, + READ_COGNITION + ], + "a host registration supplied a reserved id: {:?}", capabilities(&surface) ); - assert!( - surface - .manifest - .tools - .iter() - .all(|tool| tool.capability_id.as_str() != RETIRED_ADOPT), - "the host's retired adoption descriptor is not advertised" + let tools: Vec<&str> = surface + .manifest + .tools + .iter() + .map(|tool| tool.capability_id.as_str()) + .collect(); + assert_eq!( + tools, + [RECALL_CONTEXT, ABSORB, DELIBERATE, READ_COGNITION], + "each runtime tool is advertised once, from the runtime's own registration" ); } -/// A host registration borrowing the retired adoption id: its descriptor would be advertised and -/// its handler installed if the runtime did not drop it. -fn shadowing_adoption() -> ToolRegistration { - let descriptor: ToolDescriptor = serde_json::from_value(json!({ - "schema_version": 1, - "capability_id": RETIRED_ADOPT, - "op": RETIRED_ADOPT, - "description": "A host-supplied adoption tool.", - "input": { "type": "object" }, - "output": { "type": "object" }, - })) - .expect("tool descriptor JSON matches the schema"); - ToolRegistration::new(descriptor, |_responder| { +/// A host registration borrowing a reserved tool id: its descriptor would be advertised and its +/// handler installed if the runtime did not drop it. +fn shadowing(capability_id: &str) -> ToolRegistration { + ToolRegistration::new(descriptor(capability_id), |_responder| { let handler: ToolHandler = Arc::new(|arguments: Value| { Box::pin( async move { spoke_ok(json!({ "adopted_by": "host", "arguments": arguments })) }, From 7bd0cb4c2a1f74f1103867f7e31b1dc764cb4a51 Mon Sep 17 00:00:00 2001 From: Tang Bohao Date: Thu, 26 Nov 2026 16:14:25 +0800 Subject: [PATCH 23/27] fix(minds): give the served id read the space-row join the registry runs visible_mind_ids documented itself as read_visible's join reduced to the id but dropped the memory_spaces join the shared grant_columns projection runs, so for a minds row whose space row is absent the list could name the id while get_mind answered NotFound and admission refused. Both reads now share the one join, and a regression pins the agreement: the id read, the list and the point read all keep the Mind invisible until its space row exists. Verified fails-first on the prior head. --- crates/mindcore-sqlite/src/minds.rs | 1 + crates/mindcore-sqlite/tests/minds.rs | 52 +++++++++++++++++++++++++++ 2 files changed, 53 insertions(+) diff --git a/crates/mindcore-sqlite/src/minds.rs b/crates/mindcore-sqlite/src/minds.rs index 58e0fbc5..175663f6 100644 --- a/crates/mindcore-sqlite/src/minds.rs +++ b/crates/mindcore-sqlite/src/minds.rs @@ -509,6 +509,7 @@ pub async fn visible_mind_ids( "SELECT m.space_id, g.expires_at, g.capabilities_json, g.context_ids_json \ FROM memory_grants g \ JOIN minds m ON m.space_id = g.space_id \ + JOIN memory_spaces s ON s.space_id = g.space_id \ WHERE g.principal_id = ?1 AND g.revoked_at IS NULL \ ORDER BY m.space_id, g.grant_id", ) diff --git a/crates/mindcore-sqlite/tests/minds.rs b/crates/mindcore-sqlite/tests/minds.rs index e05971d4..838608c0 100644 --- a/crates/mindcore-sqlite/tests/minds.rs +++ b/crates/mindcore-sqlite/tests/minds.rs @@ -1062,3 +1062,55 @@ async fn a_good_grant_after_an_undecodable_row_still_lists_the_mind() { ); tx.rollback().await.expect("rollback"); } + +/// List and the point read share one visibility rule: a registry row whose space row is missing +/// is invisible to `minds.list`, `minds.get` and the served list's id read alike, so the two +/// reads never disagree about a Mind's existence. The write path creates the space row with the +/// Mind and the store never deletes one, so reaching the state takes raw SQL — the FK is +/// disabled on one connection only to drop the row by hand. +#[tokio::test] +async fn a_mind_without_its_space_row_is_invisible_to_every_visibility_read() { + let temp = tempfile::tempdir().expect("private temporary root"); + let path = temp.path().join("mindcore.db"); + let store = open_store(&path).await; + let pool = store.pool(); + let caller = CallerId::new("caller_wren"); + ok(store + .create_mind(&request(Some("wren"), "caller_wren")) + .await); + + { + let mut conn = pool.acquire().await.expect("acquire a connection"); + sqlx::query("PRAGMA foreign_keys = OFF") + .execute(&mut *conn) + .await + .expect("disable the foreign keys"); + sqlx::query("DELETE FROM memory_spaces WHERE space_id = 'wren'") + .execute(&mut *conn) + .await + .expect("drop the space row"); + sqlx::query("PRAGMA foreign_keys = ON") + .execute(&mut *conn) + .await + .expect("restore the foreign keys"); + } + + let listed = ok(store.list_minds(&caller).await); + assert!( + listed.is_empty(), + "a Mind whose space row is gone does not list" + ); + let unseen = reject(store.get_mind(&caller, &MindId::new("wren")).await); + assert_eq!( + unseen.code, + SpokeRejectCode::NotFound, + "the point read applies the same join" + ); + + let mut tx = pool_begin(&store).await; + assert!( + ok(mindcore_sqlite::minds::visible_mind_ids(&mut tx, "caller_wren").await).is_empty(), + "the served list's id read applies the same join" + ); + tx.rollback().await.expect("rollback"); +} From b7b95b6c28fe3ff2d10bd6ef8ccffc2c8a111a25 Mon Sep 17 00:00:00 2001 From: Tang Bohao Date: Thu, 26 Nov 2026 16:19:06 +0800 Subject: [PATCH 24/27] fix(facade): hide an owner-private carrier from the facade cognition read Mind::cognition_read answered an owner-private carrier's records and derived MindState to any caller the space-wide knowledge_read grant admits, the same leak the served adapter read answered in 2358294 but through the facade path. The read now applies the recall knowledge slot's disclosure predicate, viewpoint-free, after the grant check: a hidden carrier answers the fresh-carrier None, and no derivation runs on its records. Regression: the owner-private judging carrier reads None; the same carrier made space-visible reads whole. Verified fails-first on the prior head. --- crates/mindcore-runtime/src/mind.rs | 15 ++++- crates/mindcore-runtime/tests/mind.rs | 91 +++++++++++++++++++++++++++ 2 files changed, 104 insertions(+), 2 deletions(-) diff --git a/crates/mindcore-runtime/src/mind.rs b/crates/mindcore-runtime/src/mind.rs index f324d68a..2dd9407a 100644 --- a/crates/mindcore-runtime/src/mind.rs +++ b/crates/mindcore-runtime/src/mind.rs @@ -32,7 +32,9 @@ use mindcore_sqlite::{ list_entries_in, read_entry, read_entry_at_revision, write_entry, MindStore, SqliteMemoryRepository, }; -use spoke_operations::{SpokeReject, SpokeRejectCode, SpokeResult}; +use spoke_operations::{ + knowledge_entry_visible_to_viewpoint, SpokeReject, SpokeRejectCode, SpokeResult, +}; use spoke_schemas::data::cognition::{CognitionReference, CognitionTarget}; use spoke_schemas::memory_candidates_review_request::Decision; use spoke_schemas::{ @@ -745,7 +747,9 @@ impl Mind { /// 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. + /// once into the wire state and moved into the answer. The recall knowledge slot's + /// disclosure predicate applies here too, viewpoint-free: an `owner`-private carrier answers + /// the fresh-carrier `None`, and no derivation runs on its records. pub async fn cognition_read(&self) -> SpokeResult> { let mut transaction = match self.pool.begin().await { Ok(transaction) => transaction, @@ -795,6 +799,13 @@ impl Mind { ) } }; + // The knowledge slot's disclosure predicate, viewpoint-free: the `knowledge_read` + // coverage above stays first, but a carrier it hides — an `owner`-private one — answers + // the fresh-carrier `None`, and no derivation runs on its records. The served adapter + // read applies the same rule to the same carrier. + if !knowledge_entry_visible_to_viewpoint(&carrier, None) { + return SpokeResult::Ok(None); + } let view = match mindcore_base::cognition::derive_mind_state(&carrier) { Ok(view) => view, Err(mindcore_base::cognition::MindError::NoRecords) => return SpokeResult::Ok(None), diff --git a/crates/mindcore-runtime/tests/mind.rs b/crates/mindcore-runtime/tests/mind.rs index 9b0894ab..afefddcf 100644 --- a/crates/mindcore-runtime/tests/mind.rs +++ b/crates/mindcore-runtime/tests/mind.rs @@ -1179,6 +1179,97 @@ async fn cognition_read_answers_none_then_the_judgment_and_mind_state() { ); } +/// The facade's read applies the knowledge slot's disclosure predicate, viewpoint-free — the +/// same rule the served adapter read applies to the same carrier: an `owner`-private carrier +/// with a stored judgment answers the fresh-carrier `None`, and once the carrier is +/// space-visible the same caller reads the judgment and its derived `MindState`. +#[tokio::test] +async fn cognition_read_hides_an_owner_private_carrier_from_a_viewpoint_free_peer() { + 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 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_hidden", + "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 judged = mindcore_base::cognition::append_cognition_record(&carrier, record) + .expect("one valid record appends to the carrier"); + + // Mark the judging carrier `owner`-private through the same knowledge write path. + let mut payload = serde_json::to_value(&judged).expect("the carrier serializes"); + payload["disclosure"] = json!("owner-private"); + payload["owner"] = json!(OWNER); + let private: KnowledgeEntry = serde_json::from_value(payload).expect("the carrier decodes"); + ok(handle.knowledge_put(private, Some(revision)).await); + + assert!( + ok(handle.cognition_read().await).is_none(), + "an owner-private carrier answers the fresh-carrier None: no record and no state" + ); + + // Making the carrier space-visible restores the judgment to the same caller. + let carrier = ok(handle.knowledge_get(handle.carrier_entry_id(), None).await); + let revision = carrier.revision.expect("a stored carrier has a revision"); + let mut payload = serde_json::to_value(&carrier).expect("the carrier serializes"); + payload.as_object_mut().expect("an object").remove("disclosure"); + payload.as_object_mut().expect("an object").remove("owner"); + let visible: KnowledgeEntry = serde_json::from_value(payload).expect("the carrier decodes"); + ok(handle.knowledge_put(visible, Some(revision)).await); + + let cognition = ok(handle.cognition_read().await).expect("the space-visible carrier reads"); + assert_eq!( + cognition.records.len(), + 1, + "the judgment serves once the carrier is space-visible" + ); + assert_eq!(cognition.records[0]["record_id"], json!("cog_hidden")); + assert_eq!( + cognition.mind_state["holder_entry_id"], + json!(created.carrier_entry_id), + "the derived state descends from the Mind's carrier" + ); +} + #[tokio::test] async fn deliberate_without_a_space_wide_recall_grant_is_refused_and_writes_nothing() { let (_dir, store) = fixture().await; From 5bba92dbd36f8592bb9799a1de1542d2463a44f2 Mon Sep 17 00:00:00 2001 From: Tang Bohao Date: Thu, 26 Nov 2026 16:23:20 +0800 Subject: [PATCH 25/27] style(serving): format the tests this branch added cargo fmt --all on the branch's own files: the facade disclosure regression and the adapter knowledge-slot regression helpers exceed the line width in a few places. Formatting only; no behavior change. --- crates/mindcore-runtime/tests/mind.rs | 5 ++- crates/mindcore-spoke/tests/workflows.rs | 45 +++++++++++++----------- 2 files changed, 29 insertions(+), 21 deletions(-) diff --git a/crates/mindcore-runtime/tests/mind.rs b/crates/mindcore-runtime/tests/mind.rs index afefddcf..eccb1a1d 100644 --- a/crates/mindcore-runtime/tests/mind.rs +++ b/crates/mindcore-runtime/tests/mind.rs @@ -1251,7 +1251,10 @@ async fn cognition_read_hides_an_owner_private_carrier_from_a_viewpoint_free_pee let carrier = ok(handle.knowledge_get(handle.carrier_entry_id(), None).await); let revision = carrier.revision.expect("a stored carrier has a revision"); let mut payload = serde_json::to_value(&carrier).expect("the carrier serializes"); - payload.as_object_mut().expect("an object").remove("disclosure"); + payload + .as_object_mut() + .expect("an object") + .remove("disclosure"); payload.as_object_mut().expect("an object").remove("owner"); let visible: KnowledgeEntry = serde_json::from_value(payload).expect("the carrier decodes"); ok(handle.knowledge_put(visible, Some(revision)).await); diff --git a/crates/mindcore-spoke/tests/workflows.rs b/crates/mindcore-spoke/tests/workflows.rs index 8756ff3c..e04e3b68 100644 --- a/crates/mindcore-spoke/tests/workflows.rs +++ b/crates/mindcore-spoke/tests/workflows.rs @@ -219,13 +219,15 @@ impl Harness { .execute(&pool) .await .expect("seed the carrier entry"); - sqlx::query("INSERT INTO minds (space_id, knowledge_collection, carrier_entry_id) VALUES (?, ?, ?)") - .bind(SPACE) - .bind("wren") - .bind("ke_wren") - .execute(&pool) - .await - .expect("seed the mind registry row"); + sqlx::query( + "INSERT INTO minds (space_id, knowledge_collection, carrier_entry_id) VALUES (?, ?, ?)", + ) + .bind(SPACE) + .bind("wren") + .bind("ke_wren") + .execute(&pool) + .await + .expect("seed the mind registry row"); Self { _dir: dir, root, @@ -374,7 +376,8 @@ impl Harness { /// dedicated append stores it: a `cognition_records` row the read hydrates /// into the payload's `records` member. async fn judgment(&self, record_id: &str) { - let reference = |kind: &str, id: &str| json!({ "kind": kind, "id": id, "namespace": "mindcore" }); + let reference = + |kind: &str, id: &str| json!({ "kind": kind, "id": id, "namespace": "mindcore" }); let record = json!({ "assessed_at": NOW, "assessment_context": { "context_id": "ctx_gate" }, @@ -1050,9 +1053,16 @@ async fn cognition_read_hides_an_owner_private_carrier_from_a_viewpoint_free_pee .expect("the space-visible carrier read"); assert_eq!(visible.carrier_revision, 1); let records = &visible.records; - assert_eq!(records.len(), 1, "the judgment serves once visible: {visible:?}"); + assert_eq!( + records.len(), + 1, + "the judgment serves once visible: {visible:?}" + ); assert_eq!(records[0]["record_id"], "rec_judgment"); - assert!(visible.mind_state.is_object(), "the derived state serves beside the record"); + assert!( + visible.mind_state.is_object(), + "the derived state serves beside the record" + ); assert_eq!(visible.mind_state["mind_state_id"], SPACE); assert_eq!(visible.mind_state["holder_entry_id"], "ke_wren"); } @@ -2769,9 +2779,7 @@ async fn deliberate_as( timeout: std::time::Duration, assessment_context_id: Option<&str>, ) -> Result { - let workflows = SpiMindWorkflows::new( - MemoryWorkflowBinding::new(harness.pool.clone(), true), - ); + let workflows = SpiMindWorkflows::new(MemoryWorkflowBinding::new(harness.pool.clone(), true)); let holder_value = cognition_reference(CARRIER); let holder: spoke_schemas::data::cognition::CognitionReference = serde_json::from_value(holder_value).expect("holder"); @@ -2794,10 +2802,9 @@ async fn deliberate_as( evidence: &evidence, timeout, }; - let caller_principal: Principal = serde_json::from_value( - json!({ "principal_id": caller, "extensions": {} }), - ) - .expect("caller principal"); + let caller_principal: Principal = + serde_json::from_value(json!({ "principal_id": caller, "extensions": {} })) + .expect("caller principal"); workflows .deliberate(&caller_principal, request, None, caps) .await @@ -4649,9 +4656,7 @@ async fn a_request_naming_neither_subject_nor_context_is_refused_before_the_verd reasoner: Some(&reasoner), ..MindCapabilities::default() }; - let workflows = SpiMindWorkflows::new( - MemoryWorkflowBinding::new(harness.pool.clone(), true), - ); + let workflows = SpiMindWorkflows::new(MemoryWorkflowBinding::new(harness.pool.clone(), true)); 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!({ From 16a9bcbdffe17592b6c89199dffa14a12e8bd830 Mon Sep 17 00:00:00 2001 From: Tang Bohao Date: Thu, 26 Nov 2026 16:23:21 +0800 Subject: [PATCH 26/27] style: format pre-existing drift outside this branch's files cargo fmt --all -- --check fails CI on files this branch never touched: runtime tools.rs and tools/tests.rs, runtime tests/loopback.rs, spoke src/workflows.rs and tests/memory_adapter.rs. Formatting only; no behavior change; kept separate so the review sees them as drift cleanup, not branch work. --- crates/mindcore-runtime/src/tools.rs | 2 +- crates/mindcore-runtime/src/tools/tests.rs | 26 ++- crates/mindcore-runtime/tests/loopback.rs | 166 ++++++++---------- crates/mindcore-spoke/src/workflows.rs | 30 ++-- crates/mindcore-spoke/tests/memory_adapter.rs | 81 ++++++--- 5 files changed, 161 insertions(+), 144 deletions(-) diff --git a/crates/mindcore-runtime/src/tools.rs b/crates/mindcore-runtime/src/tools.rs index 911e73ae..a17f5a7f 100644 --- a/crates/mindcore-runtime/src/tools.rs +++ b/crates/mindcore-runtime/src/tools.rs @@ -26,9 +26,9 @@ use mindcore_spoke::MemoryAdapter; use spoke_connect::remote::{ConnectResponder, MemoryAdmission, ToolHandler}; use spoke_operations::{SpokeReject, SpokeRejectCode, SpokeResult}; use spoke_schemas::data::cognition::{CognitionReference, CognitionTarget}; -use sqlx::SqlitePool; use spoke_schemas::host_capability_manifest::ToolDescriptor; use spoke_schemas::{MemoryCaptureRequest, MemoryRecallRequest, Principal}; +use sqlx::SqlitePool; use crate::ToolRegistration; diff --git a/crates/mindcore-runtime/src/tools/tests.rs b/crates/mindcore-runtime/src/tools/tests.rs index 332f26df..71d53634 100644 --- a/crates/mindcore-runtime/src/tools/tests.rs +++ b/crates/mindcore-runtime/src/tools/tests.rs @@ -794,7 +794,8 @@ async fn malformed_arguments_are_invalid_input() { for (case, capability_id, arguments) in cases { let fake = Arc::new(Fake::default()); let reject = expect_reject( - tools(fake).await + tools(fake) + .await .call(capability_id, "peer-driver", arguments) .await, case, @@ -901,8 +902,12 @@ async fn read_cognition_serves_a_judgment_or_a_null_state() { // Admitted (a live `recall` grant), but not to `knowledge_read`: the coverage refusal // answers, and it must not be the target-free admission refusal. let uncovered = expect_reject( - tool.call(READ_COGNITION, "peer-driver", cognition_read_arguments("spc_4")) - .await, + tool.call( + READ_COGNITION, + "peer-driver", + cognition_read_arguments("spc_4"), + ) + .await, "an admitted caller without knowledge_read", ); assert_eq!(uncovered.code, SpokeRejectCode::NotAuthorized); @@ -1018,7 +1023,8 @@ async fn settlement_refusals_keep_their_code_and_details() { fake.reply_absorb(Err(SpiError::Settlement(refusal.clone()))); let reject = expect_reject( - tools(fake).await + tools(fake) + .await .call(ABSORB, "peer-driver", absorb_arguments()) .await, "settlement refusal", @@ -1032,7 +1038,8 @@ async fn workflow_failures_map_to_stable_reject_kinds() { let fake = Arc::new(Fake::default()); fake.reply_recall(Err(SpiError::DeadlineExceeded)); let reject = expect_reject( - tools(fake).await + tools(fake) + .await .call(RECALL_CONTEXT, "peer-driver", recall_arguments()) .await, "deadline", @@ -1077,7 +1084,8 @@ async fn workflow_failures_map_to_stable_reject_kinds() { let fake = Arc::new(Fake::default()); fake.reply_recall(Err(error)); let reject = expect_reject( - tools(fake).await + tools(fake) + .await .call(RECALL_CONTEXT, "peer-driver", recall_arguments()) .await, kind, @@ -1102,7 +1110,8 @@ async fn workflow_failures_map_to_stable_reject_kinds() { "domain redline on the north gate".into(), ))); let reject = expect_reject( - tools(fake).await + tools(fake) + .await .call(RECALL_CONTEXT, "peer-driver", recall_arguments()) .await, "policy", @@ -1130,7 +1139,8 @@ async fn workflow_failures_map_to_stable_reject_kinds() { "max_tokens is unsupported".into(), ))); let reject = expect_reject( - tools(fake).await + tools(fake) + .await .call(RECALL_CONTEXT, "peer-driver", recall_arguments()) .await, "invalid input", diff --git a/crates/mindcore-runtime/tests/loopback.rs b/crates/mindcore-runtime/tests/loopback.rs index 42a1516a..da4660f4 100644 --- a/crates/mindcore-runtime/tests/loopback.rs +++ b/crates/mindcore-runtime/tests/loopback.rs @@ -248,8 +248,20 @@ impl Fixture { .execute(&pool) .await .expect("seed the second mind's registry row"); - seed_record_in(&pool, SPACE_TWO, "rec_north_gate_two", "the north gate is closed").await; - seed_record_in(&pool, SPACE_TWO, "rec_market_two", "the market opens at dawn").await; + seed_record_in( + &pool, + SPACE_TWO, + "rec_north_gate_two", + "the north gate is closed", + ) + .await; + seed_record_in( + &pool, + SPACE_TWO, + "rec_market_two", + "the market opens at dawn", + ) + .await; } /// One space-wide grant for `principal` over the second Mind's space. @@ -270,7 +282,6 @@ impl Fixture { .expect("seed grant"); } - /// One space-wide grant for `principal` over this fixture's space. async fn grant(&self, grant_id: &str, principal: &str, capabilities: &[&str]) { sqlx::query( @@ -351,7 +362,6 @@ fn hello(host_id: &str, capabilities: &[&str]) -> HostCapabilityManifest { .expect("manifest JSON matches the schema") } - /// The host tool's descriptor, as a host could build one. fn host_tool_descriptor() -> ToolDescriptor { serde_json::from_value(json!({ @@ -475,9 +485,9 @@ impl Reasoner for NoChangeReasoner { serde_json::from_str(request.user_payload).expect("the deliberation payload is JSON"); assert_eq!(payload["evidence"][0]["evidence_id"], "ev_gate"); assert!( - payload["records"].as_array().is_some_and(|records| records - .iter() - .any(|record| record["record_id"] + payload["records"] + .as_array() + .is_some_and(|records| records.iter().any(|record| record["record_id"] .as_str() .is_some_and(|id| id.starts_with("rec_north_gate")))), "the authorized memory page reached the reasoner: {}", @@ -510,15 +520,23 @@ impl Reasoner for SettlingReasoner { let payload: Value = serde_json::from_str(request.user_payload).expect("the deliberation payload is JSON"); assert!( - payload["records"].as_array().is_some_and(|records| records - .iter() - .any(|record| record["record_id"].as_str().is_some_and(|id| id.starts_with("rec_north_gate")))), + payload["records"] + .as_array() + .is_some_and(|records| records.iter().any(|record| record["record_id"] + .as_str() + .is_some_and(|id| id.starts_with("rec_north_gate")))), "the authorized memory page reached the reasoner: {}", request.user_payload ); - let gate_record = payload["records"].as_array() - .and_then(|records| records.iter() - .find(|record| record["record_id"].as_str().is_some_and(|id| id.starts_with("rec_north_gate")))) + let gate_record = payload["records"] + .as_array() + .and_then(|records| { + records.iter().find(|record| { + record["record_id"] + .as_str() + .is_some_and(|id| id.starts_with("rec_north_gate")) + }) + }) .and_then(|record| record["record_id"].as_str()) .expect("the page carries the north-gate record") .to_string(); @@ -592,7 +610,6 @@ fn faces( } } - fn surface(serve: &MindcoreServe, faces: ServeFaces) -> MindcoreSurface { expect_ok(serve.surface(faces), "assemble the served surface") } @@ -963,11 +980,7 @@ async fn another_admitted_mind_recalls_its_own_knowledge_slot() { ) .await; let (_dir, serve) = fixture.serve(); - let mut faces = faces( - hello("runtime", &[]), - None, - MindProviders::default(), - ); + let mut faces = faces(hello("runtime", &[]), None, MindProviders::default()); faces.principals = two_principal_admission(); let surface = surface(&serve, faces); @@ -975,14 +988,14 @@ async fn another_admitted_mind_recalls_its_own_knowledge_slot() { let mut arguments = recall_arguments_in(SPACE_TWO); arguments["max_tokens"] = json!(4_000); let result = expect_ok( - session - .adapter - .invoke_tool(RECALL_CONTEXT, arguments) - .await, + session.adapter.invoke_tool(RECALL_CONTEXT, arguments).await, "recall by a peer admitted to the second Mind", ); - assert_eq!(packed_record_ids(&result), ["rec_market_two", "rec_north_gate_two"]); + assert_eq!( + packed_record_ids(&result), + ["rec_market_two", "rec_north_gate_two"] + ); assert_eq!( packed_knowledge_ids(&result), [CARRIER_TWO], @@ -1009,11 +1022,7 @@ async fn the_route_caller_without_knowledge_read_recalls_with_an_empty_slot() { let (_dir, serve) = fixture.serve(); let surface = surface( &serve, - faces( - hello("runtime", &[]), - None, - MindProviders::default(), - ), + faces(hello("runtime", &[]), None, MindProviders::default()), ); assert!( capabilities(&surface).contains(&DELIBERATE), @@ -1054,10 +1063,7 @@ async fn remote_consumer_deliberates_through_the_composed_surface() { reasoner: Some(Arc::new(NoChangeReasoner)), ..MindProviders::default() }; - let surface = surface( - &serve, - faces(hello("runtime", &[]), None, providers), - ); + let surface = surface(&serve, faces(hello("runtime", &[]), None, providers)); assert!( capabilities(&surface).contains(&DELIBERATE), "a wired deliberation route is advertised: {:?}", @@ -1216,10 +1222,7 @@ async fn remote_consumer_holds_a_deliberation_with_a_valid_judgment() { policy_hook: Some(Arc::new(HoldingPolicy)), ..MindProviders::default() }; - let surface = surface( - &serve, - faces(hello("runtime", &[]), None, providers), - ); + let surface = surface(&serve, faces(hello("runtime", &[]), None, providers)); let session = connect(&surface, &[DELIBERATE]).await; let result = expect_ok( @@ -1264,10 +1267,7 @@ async fn remote_consumer_settles_a_deliberation_with_a_valid_judgment() { policy_hook: Some(Arc::new(AutoPolicy)), ..MindProviders::default() }; - let surface = surface( - &serve, - faces(hello("runtime", &[]), None, providers), - ); + let surface = surface(&serve, faces(hello("runtime", &[]), None, providers)); let session = connect(&surface, &[DELIBERATE]).await; let result = expect_ok( @@ -1648,7 +1648,8 @@ async fn two_minds_settle_onto_their_own_carriers() { "the second slot carries the second Mind's entry, never the first's: {second_pack}" ); assert_eq!( - second_pack["knowledge"][0]["body"]["summary"], "the knowledge of the second mind, not the first", + second_pack["knowledge"][0]["body"]["summary"], + "the knowledge of the second mind, not the first", "the content distinguishes the two Minds: {second_pack}" ); let contamination: Vec<&str> = first_pack["knowledge"] @@ -1667,12 +1668,10 @@ async fn two_minds_settle_onto_their_own_carriers() { let second_before = collection_state(&pool, COLLECTION_TWO, CARRIER_TWO).await; // The retired `holder` member: the closed argument object refuses it before any carrier access. let mut with_holder = deliberate_arguments(); - with_holder["holder"] = json!({ "kind": "knowledge_entry", "namespace": "mindcore", "id": CARRIER }); + with_holder["holder"] = + json!({ "kind": "knowledge_entry", "namespace": "mindcore", "id": CARRIER }); let reject = expect_reject( - first - .adapter - .invoke_tool(DELIBERATE, with_holder) - .await, + first.adapter.invoke_tool(DELIBERATE, with_holder).await, "deliberate still naming the retired holder member", ); assert_eq!( @@ -1734,7 +1733,9 @@ async fn a_space_with_no_registry_row_reaches_no_carrier() { ); assert_eq!(reject.code, SpokeRejectCode::NotAuthorized); assert!( - reject.message.contains("the caller is not admitted to the named mind"), + reject + .message + .contains("the caller is not admitted to the named mind"), "the refusal is the admission rule: {reject:?}" ); let refusal = format!("{reject:?}"); @@ -1849,11 +1850,7 @@ async fn deliberate_cannot_distinguish_an_absent_mind_from_an_ungranted_one() { fixture.seed_second_mind().await; let (_dir, serve) = fixture.serve(); // No reasoner: any path that reaches the engine before admission is a different answer. - let mut faces = faces( - hello("runtime", &[]), - None, - MindProviders::default(), - ); + let mut faces = faces(hello("runtime", &[]), None, MindProviders::default()); faces.principals = two_principal_admission(); let surface = surface(&serve, faces); @@ -1904,11 +1901,7 @@ async fn a_strangers_malformed_grant_row_cannot_leak_the_minds_existence() { .expect("seed the stranger's malformed grant"); let (_dir, serve) = fixture.serve(); // No reasoner: a path that reaches the engine would answer differently again. - let mut faces = faces( - hello("runtime", &[]), - None, - MindProviders::default(), - ); + let mut faces = faces(hello("runtime", &[]), None, MindProviders::default()); faces.principals = two_principal_admission(); let surface = surface(&serve, faces); @@ -1946,10 +1939,12 @@ async fn a_grant_with_an_unparseable_expiry_is_dead_to_deliberate() { let fixture = Fixture::open().await; let pool = fixture.store.pool(); // Corrupt the seeded knowledge grant's expiry in place: it can no longer be read as a time. - sqlx::query("UPDATE memory_grants SET expires_at = 'not-a-time' WHERE grant_id = 'grt_knowledge'") - .execute(&pool) - .await - .expect("corrupt the expiry"); + sqlx::query( + "UPDATE memory_grants SET expires_at = 'not-a-time' WHERE grant_id = 'grt_knowledge'", + ) + .execute(&pool) + .await + .expect("corrupt the expiry"); let (_dir, serve) = fixture.serve(); // A reasoner is configured so the workflow reaches its snapshot: the refusal must come from // admission/coverage, never from the engine's missing capability. @@ -2176,24 +2171,21 @@ async fn one_principal_recalls_each_mind_by_its_own_space_id() { let fixture = Fixture::open().await; fixture.seed_second_mind().await; fixture - .grant_in_second( - "grt_shared_peer", - PRINCIPAL, - &["recall", "knowledge_read"], - ) + .grant_in_second("grt_shared_peer", PRINCIPAL, &["recall", "knowledge_read"]) .await; let (_dir, serve) = fixture.serve(); - let mut faces = faces( - hello("runtime", &[]), - None, - MindProviders::default(), - ); + let mut faces = faces(hello("runtime", &[]), None, MindProviders::default()); faces.principals = principal_admission(); let surface = surface(&serve, faces); let session = connect(&surface, &[RECALL_CONTEXT]).await; for (space, carrier, name, summary) in [ - (SPACE, CARRIER, "ke_carrier's carrier", "what this holder currently holds"), + ( + SPACE, + CARRIER, + "ke_carrier's carrier", + "what this holder currently holds", + ), ( SPACE_TWO, CARRIER_TWO, @@ -2727,11 +2719,7 @@ async fn an_unserved_tool_answers_op_unsupported() { let (_dir, serve) = fixture.serve(); let surface = surface( &serve, - faces( - hello("runtime", &[]), - None, - MindProviders::default(), - ), + faces(hello("runtime", &[]), None, MindProviders::default()), ); assert!(!capabilities(&surface).contains(&UNSERVED_TOOL)); @@ -2757,11 +2745,7 @@ async fn an_un_routed_face_answers_a_missing_port() { ]; let surface = surface( &serve, - faces( - hello("runtime", &claimed), - None, - MindProviders::default(), - ), + faces(hello("runtime", &claimed), None, MindProviders::default()), ); for capability in claimed { assert!( @@ -2803,13 +2787,8 @@ async fn an_un_routed_face_answers_a_missing_port() { })) .expect("request JSON matches the schema"); assert_wire_deny( - AdoptionPort::adopt_knowledge_entry( - dialer, - &principal(), - &scope_of(SCOPE_ID), - &adopt, - ) - .await, + AdoptionPort::adopt_knowledge_entry(dialer, &principal(), &scope_of(SCOPE_ID), &adopt) + .await, "knowledge.adopt", "capability_missing", ); @@ -2819,11 +2798,7 @@ async fn an_un_routed_face_answers_a_missing_port() { async fn a_host_registration_reaches_its_handler_over_the_signed_session() { let fixture = Fixture::open().await; let (_dir, serve) = fixture.serve(); - let mut faces = faces( - hello("runtime", &[]), - None, - MindProviders::default(), - ); + let mut faces = faces(hello("runtime", &[]), None, MindProviders::default()); faces.tools = vec![ToolRegistration::new( host_tool_descriptor(), |_responder| { @@ -3158,4 +3133,3 @@ async fn retiring_a_warm_identity_forces_its_next_query_embed() { "another identity's rows survive the retirement" ); } - diff --git a/crates/mindcore-spoke/src/workflows.rs b/crates/mindcore-spoke/src/workflows.rs index 28a66015..f2319998 100644 --- a/crates/mindcore-spoke/src/workflows.rs +++ b/crates/mindcore-spoke/src/workflows.rs @@ -109,14 +109,12 @@ pub async fn admitted_carrier_entry( principal_id: &str, space_id: &str, ) -> Result { - let mut conn = pool - .acquire() - .await - .map_err(|e| Reject::internal(format!("the mind admission could not open: {e}")).into_spoke())?; - let mut tx = conn - .begin() - .await - .map_err(|e| Reject::internal(format!("the mind admission could not begin: {e}")).into_spoke())?; + let mut conn = pool.acquire().await.map_err(|e| { + Reject::internal(format!("the mind admission could not open: {e}")).into_spoke() + })?; + let mut tx = conn.begin().await.map_err(|e| { + Reject::internal(format!("the mind admission could not begin: {e}")).into_spoke() + })?; let space = SpaceId::new(space_id.to_string()); let located = admit_carrier_location(&mut tx, principal_id, &space, space_id).await; let _ = tx.rollback().await; @@ -461,13 +459,11 @@ impl MemoryWorkflowBinding { return Ok(Some(collection.clone())); } } - sqlx::query_scalar::<_, String>( - "SELECT knowledge_collection FROM minds WHERE space_id = ?", - ) - .bind(space_id) - .fetch_optional(&mut **tx) - .await - .map_err(|error| internal(format!("the mind registry could not be read: {error}"))) + sqlx::query_scalar::<_, String>("SELECT knowledge_collection FROM minds WHERE space_id = ?") + .bind(space_id) + .fetch_optional(&mut **tx) + .await + .map_err(|error| internal(format!("the mind registry could not be read: {error}"))) } /// A bound carrier is the only carrier this binding serves in its space: a @@ -506,9 +502,7 @@ impl MemoryWorkflowBinding { let collection = self .carrier_collection(tx, space_id) .await? - .ok_or_else(|| { - SpiError::Settlement(Reject::admission_refusal().into_spoke()) - })?; + .ok_or_else(|| SpiError::Settlement(Reject::admission_refusal().into_spoke()))?; self.adapter .require_space_grants(tx, principal, space_id, capabilities) .await?; diff --git a/crates/mindcore-spoke/tests/memory_adapter.rs b/crates/mindcore-spoke/tests/memory_adapter.rs index e8739c62..c2e2e0ae 100644 --- a/crates/mindcore-spoke/tests/memory_adapter.rs +++ b/crates/mindcore-spoke/tests/memory_adapter.rs @@ -433,7 +433,10 @@ async fn unauthorized_capture_rejects_without_an_effect() { .capture(&mut tx, &principal(STRANGER), request) .await; let reject = reject(&result); - assert_admission_refusal(reject, "a principal with no grant in the space is not admitted"); + assert_admission_refusal( + reject, + "a principal with no grant in the space is not admitted", + ); assert_eq!(harness.count(&mut tx, "memory_candidates").await, 0); assert_eq!(harness.count(&mut tx, "memory_receipts").await, 0); tx.rollback().await.expect("rollback"); @@ -4344,7 +4347,10 @@ async fn concealment_and_authorization_precede_the_withhold_probe() { ) .await; let refusal = reject(&records); - assert_admission_refusal(refusal, "a caller with no grant is refused before any existence check"); + assert_admission_refusal( + refusal, + "a caller with no grant is refused before any existence check", + ); tx.rollback().await.expect("rollback"); } @@ -4508,12 +4514,19 @@ async fn unknown_ungranted_and_frozen_minds_answer_one_refusal() { ) .await; let refusal = reject(&receipts); - assert_eq!(refusal.code, SpokeRejectCode::NotAuthorized, "receipts in {space}"); + assert_eq!( + refusal.code, + SpokeRejectCode::NotAuthorized, + "receipts in {space}" + ); assert!( refusal.details.is_none(), "receipts in {space} carries no details: {refusal:?}" ); - envelopes.push((format!("receipts in {space}"), serde_json::json!(refusal.message))); + envelopes.push(( + format!("receipts in {space}"), + serde_json::json!(refusal.message), + )); let subjects_get = adapter .get_subject( &mut tx, @@ -4522,26 +4535,36 @@ async fn unknown_ungranted_and_frozen_minds_answer_one_refusal() { ) .await; let refusal = reject(&subjects_get); - assert_eq!(refusal.code, SpokeRejectCode::NotAuthorized, "subjects.get in {space}"); + assert_eq!( + refusal.code, + SpokeRejectCode::NotAuthorized, + "subjects.get in {space}" + ); assert!( refusal.details.is_none(), "subjects.get in {space} carries no details: {refusal:?}" ); - envelopes.push((format!("subjects.get in {space}"), serde_json::json!(refusal.message))); + envelopes.push(( + format!("subjects.get in {space}"), + serde_json::json!(refusal.message), + )); let grants_list = adapter - .list_grants( - &mut tx, - &principal(PRINCIPAL), - json!({ "space_id": space }), - ) + .list_grants(&mut tx, &principal(PRINCIPAL), json!({ "space_id": space })) .await; let refusal = reject(&grants_list); - assert_eq!(refusal.code, SpokeRejectCode::NotAuthorized, "grants.list in {space}"); + assert_eq!( + refusal.code, + SpokeRejectCode::NotAuthorized, + "grants.list in {space}" + ); assert!( refusal.details.is_none(), "grants.list in {space} carries no details: {refusal:?}" ); - envelopes.push((format!("grants.list in {space}"), serde_json::json!(refusal.message))); + envelopes.push(( + format!("grants.list in {space}"), + serde_json::json!(refusal.message), + )); // The mutation path enters admission through `authorize`. let mutation = adapter .capture( @@ -4557,12 +4580,19 @@ async fn unknown_ungranted_and_frozen_minds_answer_one_refusal() { ) .await; let refusal = reject(&mutation); - assert_eq!(refusal.code, SpokeRejectCode::NotAuthorized, "capture in {space}"); + assert_eq!( + refusal.code, + SpokeRejectCode::NotAuthorized, + "capture in {space}" + ); assert!( refusal.details.is_none(), "capture in {space} carries no details: {refusal:?}" ); - envelopes.push((format!("capture in {space}"), serde_json::json!(refusal.message))); + envelopes.push(( + format!("capture in {space}"), + serde_json::json!(refusal.message), + )); assert_eq!( harness.count(&mut tx, "memory_candidates").await, 0, @@ -4614,10 +4644,10 @@ async fn unknown_ungranted_and_frozen_minds_answer_one_refusal() { /// wire shape is the one the operation projected before. #[tokio::test] async fn spaces_list_returns_only_admitted_minds() { - use mindcore_sqlite::minds::CreateMind; - use mindcore_sqlite::minds; use mindcore_base::boundary::CallerId; use mindcore_base::ids::MindId; + use mindcore_sqlite::minds; + use mindcore_sqlite::minds::CreateMind; let harness = Harness::open().await; harness.seed_grant(PRINCIPAL, &["recall"]).await; @@ -4626,7 +4656,11 @@ async fn spaces_list_returns_only_admitted_minds() { // Two Minds for the listing owner, created out of id order so the answer // proves its sort, and a third for another owner alone. let mut tx = harness.begin().await; - for (id, owner) in [("mind_beta", "o_list"), ("mind_alpha", "o_list"), ("mind_gamma", "o_other")] { + for (id, owner) in [ + ("mind_beta", "o_list"), + ("mind_alpha", "o_list"), + ("mind_gamma", "o_other"), + ] { let created = minds::create( &mut tx, &CreateMind { @@ -4636,7 +4670,10 @@ async fn spaces_list_returns_only_admitted_minds() { }, ) .await; - assert!(matches!(created, SpokeResult::Ok(_)), "create {id}: {created:?}"); + assert!( + matches!(created, SpokeResult::Ok(_)), + "create {id}: {created:?}" + ); } sqlx::query("UPDATE memory_spaces SET status = 'frozen' WHERE space_id = 'mind_beta'") .execute(&mut *tx) @@ -4665,7 +4702,8 @@ async fn spaces_list_returns_only_admitted_minds() { .find(|space| space["space_id"] == json!("mind_beta")) .expect("mind_beta is listed"); assert_eq!( - frozen["status"], json!("frozen"), + frozen["status"], + json!("frozen"), "a frozen Mind is listed with its frozen status" ); assert!( @@ -4697,7 +4735,8 @@ async fn spaces_list_returns_only_admitted_minds() { .await, ); assert_eq!( - own["spaces"], json!([]), + own["spaces"], + json!([]), "a space with no registry row is excluded even under a live grant" ); tx.rollback().await.expect("rollback"); From c2e3a73f1c51b4fed476d387f9325fa768c9e634 Mon Sep 17 00:00:00 2001 From: Tang Bohao Date: Thu, 26 Nov 2026 16:49:46 +0800 Subject: [PATCH 27/27] fix(facade): drop the disclosure predicate from the in-process cognition read MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The facade is convenience, not a sandbox: Mind::cognition_read must not filter what the sibling knowledge_get returns verbatim to the same caller. The guard this branch added made the two reads disagree about an owner-private carrier and hid the judgment from its owner; it is removed. Disclosure stays on the served surface, where a peer's viewpoint exists: MemoryAdapter::read_cognition keeps knowledge_entry_visible_to_viewpoint, unchanged, and that is Devin's original must-fix. facade.md extends its existing 'convenience, not a sandbox' admission section and the cognition_read section with the split; the old test now asserts the in-process behaviour it proves (the owner and a store-holding caller read the judgment) and is renamed accordingly. DEBT-01: RESERVED_TOOLS' second hand-maintained copy is gone. The reserved set now derives from WorkflowTools::advertised_ids() — the one list advertisement and installation both read — plus the retired adopt id, so a tool added there is reserved without touching the filter. --- .agents/specs/architecture/facade.md | 13 +++++++- crates/mindcore-runtime/src/lib.rs | 26 ++++++++-------- crates/mindcore-runtime/src/mind.rs | 18 ++++------- crates/mindcore-runtime/src/tools.rs | 9 ++++++ crates/mindcore-runtime/tests/mind.rs | 43 ++++++++++++--------------- 5 files changed, 59 insertions(+), 50 deletions(-) diff --git a/.agents/specs/architecture/facade.md b/.agents/specs/architecture/facade.md index 6ba9d243..fa75480e 100644 --- a/.agents/specs/architecture/facade.md +++ b/.agents/specs/architecture/facade.md @@ -136,7 +136,9 @@ the facade; nothing is persisted. The derivation runs once: the validated record 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. +current-view records and the derived `MindState` named by the Mind's id. The read applies no +disclosure predicate — see "The facade is convenience, not a sandbox" below: an `owner`-private +carrier answers its records here, as `knowledge_get` returns the same carrier verbatim. ## Non-goals @@ -160,6 +162,15 @@ The boundary the facade composes is the store's own — `read_entry`, `write_ent `list_entries_in`, the validation and revision checks inside them — not the adoption port `put_knowledge_entry`, which is a different surface. +The same rule binds `cognition_read`. It is a read of the admitted Mind's carrier and applies no +disclosure predicate: an `owner`-private carrier answers its records to a caller the space-wide +`knowledge_read` grant admits, exactly as `knowledge_get` on the same handle returns that carrier +verbatim. Disclosure is the served surface's duty, where a peer's viewpoint exists and +`MemoryAdapter::read_cognition` filters the carrier through +`knowledge_entry_visible_to_viewpoint`; the facade does not duplicate that filter, because a +predicate on one read of the carrier while its sibling read returns the same carrier in full +would be a claim the facade cannot keep. + **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 diff --git a/crates/mindcore-runtime/src/lib.rs b/crates/mindcore-runtime/src/lib.rs index 8ddf63c5..282b6864 100644 --- a/crates/mindcore-runtime/src/lib.rs +++ b/crates/mindcore-runtime/src/lib.rs @@ -49,17 +49,18 @@ const TOOLS_NAMESPACE: &str = "mindcore"; /// under it. const RETIRED_ADOPT_TOOL: &str = "tools.mindcore.adopt"; -/// The tool ids the runtime reserves: the four it registers itself, plus the retired adoption -/// tool. A host registration carrying one is dropped, so no host can advertise or install -/// anything the runtime serves, or anything under the id a retired tool once answered. Host -/// tools keep every other id, inside the namespace and out. -const RESERVED_TOOLS: [&str; 5] = [ - tools::RECALL_CONTEXT, - tools::ABSORB, - tools::DELIBERATE, - tools::READ_COGNITION, - RETIRED_ADOPT_TOOL, -]; +/// The tool ids the runtime reserves: those it advertises, plus the retired adoption tool. A +/// host registration carrying one is dropped, so no host can advertise or install anything the +/// runtime serves, or anything under the id a retired tool once answered. Host tools keep every +/// other id, inside the namespace and out. +/// +/// The set is derived from [`WorkflowTools::advertised`] — the one list advertisement and +/// installation both read — so a tool added there is reserved without touching this filter. +fn reserved_tools() -> Vec<&'static str> { + let mut reserved: Vec<&str> = tools::WorkflowTools::advertised_ids(); + reserved.push(RETIRED_ADOPT_TOOL); + reserved +} /// The Mindcore serving side over one host store. /// @@ -119,11 +120,12 @@ impl MindcoreServe { self.store.pool(), ) .registrations(); + let reserved = reserved_tools(); tools.extend( faces .tools .into_iter() - .filter(|tool| !RESERVED_TOOLS.contains(&tool.descriptor.capability_id.as_str())), + .filter(|tool| !reserved.contains(&tool.descriptor.capability_id.as_str())), ); let manifest = match derive_manifest(faces.manifest, faces.memory.as_deref(), &tools) { SpokeResult::Ok(manifest) => manifest, diff --git a/crates/mindcore-runtime/src/mind.rs b/crates/mindcore-runtime/src/mind.rs index 2dd9407a..2258d898 100644 --- a/crates/mindcore-runtime/src/mind.rs +++ b/crates/mindcore-runtime/src/mind.rs @@ -32,9 +32,7 @@ use mindcore_sqlite::{ list_entries_in, read_entry, read_entry_at_revision, write_entry, MindStore, SqliteMemoryRepository, }; -use spoke_operations::{ - knowledge_entry_visible_to_viewpoint, SpokeReject, SpokeRejectCode, SpokeResult, -}; +use spoke_operations::{SpokeReject, SpokeRejectCode, SpokeResult}; use spoke_schemas::data::cognition::{CognitionReference, CognitionTarget}; use spoke_schemas::memory_candidates_review_request::Decision; use spoke_schemas::{ @@ -747,9 +745,10 @@ impl Mind { /// 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. The recall knowledge slot's - /// disclosure predicate applies here too, viewpoint-free: an `owner`-private carrier answers - /// the fresh-carrier `None`, and no derivation runs on its records. + /// once into the wire state and moved into the answer. The facade is convenience, not a + /// sandbox: it applies no disclosure predicate, because `knowledge_get` on the same handle + /// returns the stored carrier verbatim and an in-process caller already holds the store. + /// Disclosure is the served surface's duty; [`MemoryAdapter::read_cognition`] applies it. pub async fn cognition_read(&self) -> SpokeResult> { let mut transaction = match self.pool.begin().await { Ok(transaction) => transaction, @@ -799,13 +798,6 @@ impl Mind { ) } }; - // The knowledge slot's disclosure predicate, viewpoint-free: the `knowledge_read` - // coverage above stays first, but a carrier it hides — an `owner`-private one — answers - // the fresh-carrier `None`, and no derivation runs on its records. The served adapter - // read applies the same rule to the same carrier. - if !knowledge_entry_visible_to_viewpoint(&carrier, None) { - return SpokeResult::Ok(None); - } let view = match mindcore_base::cognition::derive_mind_state(&carrier) { Ok(view) => view, Err(mindcore_base::cognition::MindError::NoRecords) => return SpokeResult::Ok(None), diff --git a/crates/mindcore-runtime/src/tools.rs b/crates/mindcore-runtime/src/tools.rs index a17f5a7f..fdb217f6 100644 --- a/crates/mindcore-runtime/src/tools.rs +++ b/crates/mindcore-runtime/src/tools.rs @@ -121,6 +121,15 @@ impl WorkflowTools { .collect() } + /// The id column of [`Self::advertised`], for the surface's reserved-id filter: the runtime's + /// own registrations are the source, never a second list. + pub(crate) fn advertised_ids() -> Vec<&'static str> { + Self::advertised() + .into_iter() + .map(|(capability_id, _, _, _)| capability_id) + .collect() + } + /// The one list both advertisement and installation read. #[allow(clippy::type_complexity)] fn advertised() -> [(&'static str, &'static str, fn() -> Value, fn() -> Value); 4] { diff --git a/crates/mindcore-runtime/tests/mind.rs b/crates/mindcore-runtime/tests/mind.rs index eccb1a1d..3864f794 100644 --- a/crates/mindcore-runtime/tests/mind.rs +++ b/crates/mindcore-runtime/tests/mind.rs @@ -1179,12 +1179,13 @@ async fn cognition_read_answers_none_then_the_judgment_and_mind_state() { ); } -/// The facade's read applies the knowledge slot's disclosure predicate, viewpoint-free — the -/// same rule the served adapter read applies to the same carrier: an `owner`-private carrier -/// with a stored judgment answers the fresh-carrier `None`, and once the carrier is -/// space-visible the same caller reads the judgment and its derived `MindState`. +/// The facade is convenience, not a sandbox: `cognition_read` applies no disclosure predicate, so +/// an `owner`-private carrier's judgment stays readable by the caller the space-wide +/// `knowledge_read` grant admits — the same caller `knowledge_get` hands the carrier to — while +/// the served adapter read hides it. The disclosure duty lives on the served surface, where a +/// peer's viewpoint exists; the spec records the split. #[tokio::test] -async fn cognition_read_hides_an_owner_private_carrier_from_a_viewpoint_free_peer() { +async fn cognition_read_serves_an_owner_private_carrier_to_the_in_process_caller() { let (_dir, store) = fixture().await; let owner = CallerId::new(OWNER); let created = ok(minds::create(&store, &request(OWNER)).await); @@ -1242,28 +1243,12 @@ async fn cognition_read_hides_an_owner_private_carrier_from_a_viewpoint_free_pee let private: KnowledgeEntry = serde_json::from_value(payload).expect("the carrier decodes"); ok(handle.knowledge_put(private, Some(revision)).await); - assert!( - ok(handle.cognition_read().await).is_none(), - "an owner-private carrier answers the fresh-carrier None: no record and no state" - ); - - // Making the carrier space-visible restores the judgment to the same caller. - let carrier = ok(handle.knowledge_get(handle.carrier_entry_id(), None).await); - let revision = carrier.revision.expect("a stored carrier has a revision"); - let mut payload = serde_json::to_value(&carrier).expect("the carrier serializes"); - payload - .as_object_mut() - .expect("an object") - .remove("disclosure"); - payload.as_object_mut().expect("an object").remove("owner"); - let visible: KnowledgeEntry = serde_json::from_value(payload).expect("the carrier decodes"); - ok(handle.knowledge_put(visible, Some(revision)).await); - - let cognition = ok(handle.cognition_read().await).expect("the space-visible carrier reads"); + let cognition = ok(handle.cognition_read().await) + .expect("an owner-private carrier still answers the in-process caller"); assert_eq!( cognition.records.len(), 1, - "the judgment serves once the carrier is space-visible" + "the facade applies no disclosure predicate: the judgment serves" ); assert_eq!(cognition.records[0]["record_id"], json!("cog_hidden")); assert_eq!( @@ -1271,6 +1256,16 @@ async fn cognition_read_hides_an_owner_private_carrier_from_a_viewpoint_free_pee json!(created.carrier_entry_id), "the derived state descends from the Mind's carrier" ); + let sibling = serde_json::to_value(ok(handle + .knowledge_get(handle.carrier_entry_id(), None) + .await)) + .expect("the carrier serializes"); + assert_eq!( + sibling["disclosure"], + json!("owner-private"), + "the sibling read returns the same owner-private carrier in full, which is why the facade \ + does not filter one read and not the other" + ); } #[tokio::test]