diff --git a/desktop/src-tauri/src/commands/personas/inbound.rs b/desktop/src-tauri/src/commands/personas/inbound.rs index 3944af50e0..722bc44022 100644 --- a/desktop/src-tauri/src/commands/personas/inbound.rs +++ b/desktop/src-tauri/src/commands/personas/inbound.rs @@ -69,16 +69,8 @@ fn reconcile_inbound_persona_event_blocking( arrival_relay_url: String, app: AppHandle, ) -> Result { - use crate::managed_agents::{ - agent_events::managed_agent_content_from_event, - load_managed_agents, load_teams, - persona_events::persona_from_event, - retention::{open_retention_db, retain_inbound_event, InboundOutcome, RetainedEvent}, - save_managed_agents, save_teams, - team_events::team_content_from_event, - }; + use crate::managed_agents::persona_events::persona_from_event; use buzz_core_pkg::kind::{KIND_DELETION, KIND_MANAGED_AGENT, KIND_PERSONA, KIND_TEAM}; - use nostr::JsonUtil; let state = app.state::(); let event = parse_verified_inbound_event(&event_json)?; @@ -154,6 +146,37 @@ fn reconcile_inbound_persona_event_blocking( } } + apply_inbound_upsert_in_scope(&app, &scope, kind, d_tag, inbound_persona, &event) +} + +/// Retain an inbound upsert into `scope`'s store and apply it to disk — the +/// command core the blocking wrapper calls once it has resolved the arrival +/// retention scope and cleared the §2.7 preflight. +/// +/// Split out from [`reconcile_inbound_persona_event_blocking`] so a test can +/// drive the real retain → apply → §2.8 convergence sequence against a mock +/// app and a scope whose retention DB path it controls — crossing the exact +/// `?` on the corrective re-retain rather than exercising the helper in +/// isolation. Store I/O keys off the app's active scope; retention keys off +/// the passed `scope`, exactly as in production. +fn apply_inbound_upsert_in_scope( + app: &AppHandle, + scope: &crate::managed_agents::retention::RetentionScope, + kind: u32, + d_tag: String, + inbound_persona: Option, + event: &nostr::Event, +) -> Result { + use crate::managed_agents::{ + agent_events::managed_agent_content_from_event, + load_managed_agents, load_teams, + retention::{open_retention_db, retain_inbound_event, InboundOutcome, RetainedEvent}, + save_managed_agents, save_teams, + team_events::team_content_from_event, + }; + use buzz_core_pkg::kind::{KIND_MANAGED_AGENT, KIND_PERSONA, KIND_TEAM}; + use nostr::JsonUtil; + let conn = open_retention_db(&scope.db_path)?; let outcome = retain_inbound_event( &conn, @@ -174,31 +197,31 @@ fn reconcile_inbound_persona_event_blocking( let mut result = InboundReconcileOutcome::default(); match kind { KIND_PERSONA => { - let mut personas = load_personas(&app)?; + let mut personas = load_personas(app)?; // `inbound_persona` is `Some` for KIND_PERSONA (set above). apply_inbound_persona( &mut personas, inbound_persona.expect("persona parsed above"), ); - save_personas(&app, &personas)?; + save_personas(app, &personas)?; } KIND_TEAM => { - let mut teams = load_teams(&app)?; - apply_inbound_team(&mut teams, d_tag, team_content_from_event(&event)?); - save_teams(&app, &teams)?; + let mut teams = load_teams(app)?; + apply_inbound_team(&mut teams, d_tag, team_content_from_event(event)?); + save_teams(app, &teams)?; } KIND_MANAGED_AGENT => { - let mut agents = load_managed_agents(&app)?; + let mut agents = load_managed_agents(app)?; // §2.8 canonical linkage is resolved against the raw keyless // definition store (`library_ref` is not wire-carried). - let definitions = load_agent_definitions(&app)?; + let definitions = load_agent_definitions(app)?; let linkage = apply_inbound_managed_agent( &mut agents, &definitions, &d_tag, - managed_agent_content_from_event(&event)?, + managed_agent_content_from_event(event)?, ); - save_managed_agents(&app, &agents)?; + save_managed_agents(app, &agents)?; // §2.8 convergence: a frozen linkage means the retained head (the // inbound event, retained above) authored a library-owned or @@ -226,7 +249,7 @@ fn reconcile_inbound_persona_event_blocking( } _ => unreachable!("kind gated above"), } - try_regenerate_nest(&app).ok(); + try_regenerate_nest(app).ok(); // Signal the live UI to refetch agents data — inbound relay events otherwise // land on disk silently, leaving the Agents tab stale until restart. diff --git a/desktop/src-tauri/src/commands/personas/inbound/inbound_tests.rs b/desktop/src-tauri/src/commands/personas/inbound/inbound_tests.rs index cee2e52313..44bcb99dc2 100644 --- a/desktop/src-tauri/src/commands/personas/inbound/inbound_tests.rs +++ b/desktop/src-tauri/src/commands/personas/inbound/inbound_tests.rs @@ -915,3 +915,9 @@ fn inbound_gate_accepts_validly_signed_event() { let parsed = parse_verified_inbound_event(&event.as_json()).unwrap(); assert_eq!(parsed.pubkey, keys.public_key()); } + +// The command-seam integration fixture (P2-I1) lives in a sibling file to keep +// this module under the 1000-line file-size cap. Included here so it shares the +// fixtures above via `use super::*`. +#[path = "seam_tests.rs"] +mod seam_tests; diff --git a/desktop/src-tauri/src/commands/personas/inbound/seam_tests.rs b/desktop/src-tauri/src/commands/personas/inbound/seam_tests.rs new file mode 100644 index 0000000000..0dc24ce99c --- /dev/null +++ b/desktop/src-tauri/src/commands/personas/inbound/seam_tests.rs @@ -0,0 +1,228 @@ +//! P2-I1 command-seam integration fixture for the §2.8 frozen-linkage +//! convergence contract. +//! +//! Split from `inbound_tests.rs` to keep that file under the 1000-line ratchet; +//! included via `#[path = "seam_tests.rs"] mod seam_tests;`. `use super::*` +//! brings in the `inbound_tests.rs` fixtures (`local_agent`, `linked_agent`, +//! `definition`, `AGENT_PUBKEY`). +//! +//! Unlike the helper-level convergence tests, this fixture drives the real +//! command core [`apply_inbound_upsert_in_scope`] — crossing the exact `?` on +//! the corrective re-retain — against a mock Tauri app, an active workspace +//! scope, and a retention DB whose second (corrective) write is rejected by an +//! injected conditional trigger. It proves the sequence the helper tests +//! cannot: inbound retain succeeds → safe fields + frozen linkage persist to +//! disk → corrective retain fails → the command returns `Err`, never a +//! successful outcome. It then proves the durable retry: the real boot +//! reconcile, run against the state the failed command left behind, restores +//! the authoritative projection over the hostile head. +//! +//! If the `?` at the corrective call site (`inbound.rs`) were weakened to a +//! swallow (`let _ = converge_frozen_linkage(...)`, `.ok()`, or a bare +//! `eprintln!`), assertion (a) fails — the command would report success over a +//! retained non-authoritative head. +use super::*; + +use crate::app_state::AppState; +use crate::managed_agents::reconcile::reconcile_agents_to_events; +use crate::managed_agents::retention::{get_retained_event, open_retention_db, RetentionScope}; +use crate::managed_agents::scope::{current_scope_generation, WorkspaceAgentScope}; +use crate::managed_agents::storage::load_managed_agents_at; +use buzz_core_pkg::kind::KIND_MANAGED_AGENT; +use nostr::{EventBuilder, JsonUtil, Keys, Kind, Tag, Timestamp}; +use tauri::Manager; + +/// The projected definition the local instance links to, plus the linked +/// instance itself, written to a scope's `managed-agents.json` exactly as the +/// unified store persists them (key-less definitions first, keyed instances +/// after). The instance's `persona_id` resolves to the projected definition, +/// so the §2.8 resolver classifies its linkage library-owned. +fn seed_store(definitions_dir: &std::path::Path) { + std::fs::create_dir_all(definitions_dir).unwrap(); + let store = vec![definition("shared-def", true), linked_agent("shared-def")]; + let json = serde_json::to_vec_pretty(&store).unwrap(); + std::fs::write(definitions_dir.join("managed-agents.json"), json).unwrap(); +} + +/// A signed kind:30177 whose author is `owner_keys` (so it retains under the +/// owner's coordinate — the same coordinate the corrective re-retain and the +/// boot reconcile write, exactly as a device's own event reflected back off +/// the relay). Its `persona_id` re-points the library-owned linkage, which the +/// §2.8 rule freezes. Dated in the future so the retained head is +/// unambiguously newer, forcing the boot reconcile to bump past it. +fn hostile_repoint_event(owner_keys: &Keys, created_at: i64) -> nostr::Event { + let content = serde_json::json!({ + "name": "Hostile Rename", + "persona_id": "other-def", + "parallelism": 7, + "respond_to": "owner-only", + }) + .to_string(); + let event = EventBuilder::new(Kind::Custom(KIND_MANAGED_AGENT as u16), content) + .tags(vec![Tag::parse(["d", AGENT_PUBKEY]).unwrap()]) + .custom_created_at(Timestamp::from(created_at as u64)) + .sign_with_keys(owner_keys) + .unwrap(); + // Round-trip through JSON to mirror the wire path the command parses from. + nostr::Event::from_json(event.as_json()).unwrap() +} + +/// P2-I1: the real command core returns `Err` when the corrective re-retain +/// fails after the inbound head is retained, leaves the frozen linkage intact +/// on disk, keeps the hostile head retained, and the real boot reconcile then +/// converges the relay head back to the authoritative projection. +#[test] +fn frozen_linkage_corrective_failure_errs_and_boot_reconcile_converges() { + let tmp = tempfile::tempdir().unwrap(); + let definitions_dir = tmp.path().join("defs"); + let db_path = tmp.path().join("retention.db"); + + seed_store(&definitions_dir); + + let owner_keys = Keys::generate(); + let owner_hex = owner_keys.public_key().to_hex(); + + // Pre-create the retention DB and install the fault injection: a BEFORE + // INSERT/UPDATE trigger that ABORTs any write with `pending_sync = 1`. The + // inbound retain writes `pending_sync = 0` (permitted); the corrective + // re-retain writes `pending_sync = 1` into the SAME coordinate (an UPSERT + // that resolves to UPDATE — hence the UPDATE trigger), so it is rejected. + { + let conn = open_retention_db(&db_path).unwrap(); + conn.execute_batch( + "CREATE TRIGGER reject_corrective_insert + BEFORE INSERT ON persona_events + FOR EACH ROW WHEN NEW.pending_sync = 1 + BEGIN SELECT RAISE(ABORT, 'injected fault: corrective write rejected'); END; + CREATE TRIGGER reject_corrective_update + BEFORE UPDATE ON persona_events + FOR EACH ROW WHEN NEW.pending_sync = 1 + BEGIN SELECT RAISE(ABORT, 'injected fault: corrective write rejected'); END;", + ) + .unwrap(); + } + + // Mock Tauri app whose active scope points its definitions dir at the + // seeded store; the signing keys are the event's author. + let state = crate::app_state::build_app_state(); + *state.keys.lock().unwrap() = owner_keys.clone(); + let app = tauri::test::mock_builder() + .manage(state) + .build(tauri::test::mock_context(tauri::test::noop_assets())) + .expect("failed to build mock app for inbound seam test"); + app.state::() + .commit_active_scope(WorkspaceAgentScope { + scope_id: "seam-test-scope".to_string(), + relay_url: "wss://relay.local".to_string(), + owner_pubkey: owner_hex.clone(), + definitions_dir: definitions_dir.clone(), + generation: current_scope_generation(), + }); + let app_handle = app.handle().clone(); + + let scope = RetentionScope { + db_path: db_path.clone(), + relay_url: "wss://relay.local".to_string(), + owner_keys: owner_keys.clone(), + }; + + let hostile_created_at = (Timestamp::now().as_secs() as i64) + 3_600; + let event = hostile_repoint_event(&owner_keys, hostile_created_at); + + // Drive the REAL command core across the corrective `?` propagation site. + let result = super::super::apply_inbound_upsert_in_scope( + &app_handle, + &scope, + KIND_MANAGED_AGENT, + AGENT_PUBKEY.to_string(), + None, + &event, + ); + + // (a) The command MUST fail — never a successful typed outcome — while the + // non-authoritative head is retained. This is the assertion that fails if + // the corrective `?` is weakened to a swallow. + let err = result.expect_err("corrective retain failure must propagate as Err"); + assert!( + err.contains("convergence"), + "the error must be the frozen-linkage convergence failure: {err}" + ); + + // (b) Disk holds the safe-field update with the original projected linkage + // intact — the freeze applied `name` but refused the re-point. + let instances = load_managed_agents_at(&definitions_dir).unwrap(); + let instance = instances + .iter() + .find(|r| r.pubkey == AGENT_PUBKEY) + .expect("instance must remain on disk"); + assert_eq!( + instance.persona_id, + Some("shared-def".to_string()), + "the library-owned linkage must stay frozen on disk, not re-pointed" + ); + assert_eq!( + instance.name, "Hostile Rename", + "the safe per-instance field must have been applied and saved" + ); + + // (c) Retention still holds the hostile inbound head after the injected + // failure — the corrective row never landed. + { + let conn = open_retention_db(&db_path).unwrap(); + let head = get_retained_event(&conn, KIND_MANAGED_AGENT, &owner_hex, AGENT_PUBKEY) + .unwrap() + .expect("the inbound head must remain retained"); + assert!( + head.content.contains("other-def"), + "the retained head must still be the hostile re-point" + ); + assert!( + !head.pending_sync, + "the inbound head is retained pending_sync = 0" + ); + assert_eq!( + head.created_at, hostile_created_at, + "the retained head is the hostile inbound event" + ); + } + + // The injected transient failure clears (the DB is healthy at next boot); + // the RETAINED STATE — hostile head + authoritative on-disk record — is + // unchanged. Drop the triggers so the healthy boot reconcile can write. + { + let conn = open_retention_db(&db_path).unwrap(); + conn.execute_batch( + "DROP TRIGGER IF EXISTS reject_corrective_insert; + DROP TRIGGER IF EXISTS reject_corrective_update;", + ) + .unwrap(); + } + + // (d) The REAL boot reconcile, run against that same disk/DB state, re-diffs + // the authoritative on-disk record against the hostile head and replaces it + // with the authoritative projection at a greater created_at, queued for + // publish. This is the durable retry owner that makes the failure + // recoverable. + reconcile_agents_to_events(&definitions_dir, &owner_keys, &db_path); + + let conn = open_retention_db(&db_path).unwrap(); + let converged = get_retained_event(&conn, KIND_MANAGED_AGENT, &owner_hex, AGENT_PUBKEY) + .unwrap() + .expect("boot reconcile must retain the authoritative row"); + assert!( + converged.content.contains("shared-def"), + "boot reconcile must restore the authoritative library-owned linkage" + ); + assert!( + !converged.content.contains("other-def"), + "the hostile linkage must be superseded" + ); + assert!( + converged.pending_sync, + "the corrective row must queue for publish" + ); + assert!( + converged.created_at > hostile_created_at, + "created_at must bump past the hostile head so the relay accepts it" + ); +}