Skip to content
40 changes: 38 additions & 2 deletions desktop/src-tauri/src/commands/teams.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@ use uuid::Uuid;
use crate::{
app_state::AppState,
managed_agents::{
delete_team_with_cascade, ensure_persona_ids_are_active, load_personas, load_teams,
save_teams, try_regenerate_nest, CreateTeamRequest, TeamRecord, UpdateTeamRequest,
delete_team_with_cascade, ensure_persona_ids_are_active, load_managed_agents,
load_personas, load_teams, save_managed_agents, save_teams, try_regenerate_nest,
CreateTeamRequest, TeamRecord, UpdateTeamRequest,
},
util::now_iso,
};
Expand All @@ -25,6 +26,39 @@ fn trim_optional(value: Option<String>) -> Option<String> {
})
}

/// Backfill `team_id` on already-running instances of a team's members whose own
/// `team_id` is unset. Adding a persona to a team records it on the team but does
/// not touch the persona's live instances; without this, an added persona spawns
/// without team instructions (`spawn_snapshot::effective_team_instructions` keys
/// on `record.team_id`). Runs inside the caller's held `managed_agents_store_lock`
/// after `save_teams`. Conservative — sets only an unset field, so a persona
/// shared across teams keeps its existing binding.
fn backfill_member_instance_team_ids(
app: &AppHandle,
team_id: &str,
persona_ids: &[String],
) -> Result<(), String> {
let mut records = load_managed_agents(app)?;
let mut changed = false;
for record in records.iter_mut() {
if record.pubkey.is_empty() || record.team_id.is_some() {
continue;
}
if record
.persona_id
.as_deref()
.is_some_and(|id| persona_ids.iter().any(|p| p == id))
{
record.team_id = Some(team_id.to_string());
changed = true;
}
}
if changed {
save_managed_agents(app, &records)?;
}
Ok(())
}

/// Retain a freshly authored team event in the local store, flagged for relay
/// sync. Called inside a command's `managed_agents_store_lock`-held body after
/// `save_teams`; the background flush loop publishes it out-of-band.
Expand Down Expand Up @@ -173,6 +207,7 @@ pub async fn create_team(input: CreateTeamRequest, app: AppHandle) -> Result<Tea
};
teams.push(team.clone());
save_teams(&app, &teams)?;
backfill_member_instance_team_ids(&app, &team.id, &team.persona_ids)?;
// Created teams are always non-builtin; publish to the relay.
retain_team_pending(&app, &state, &team);
Ok(team)
Expand Down Expand Up @@ -210,6 +245,7 @@ pub async fn update_team(input: UpdateTeamRequest, app: AppHandle) -> Result<Tea

let updated = team.clone();
save_teams(&app, &teams)?;
backfill_member_instance_team_ids(&app, &updated.id, &updated.persona_ids)?;
// Built-in teams are not owner-authored — never publish them.
if !updated.is_builtin {
retain_team_pending(&app, &state, &updated);
Expand Down
29 changes: 26 additions & 3 deletions desktop/src-tauri/src/commands/workspace.rs
Original file line number Diff line number Diff line change
Expand Up @@ -222,16 +222,39 @@ pub async fn apply_workspace(
// Adopt whatever the pre-scoping release left queued in the global
// retention database BEFORE the scoped reconcile and flush run, so
// stranded tombstones and archive requests publish on this boot
// instead of being abandoned by the storage cutover.
// instead of being abandoned by the storage cutover. Best-effort:
// it is not a prerequisite for the superseding head — the team leg
// below builds the repaired roster's head fresh from disk with a
// monotonic `created_at` regardless of what the legacy copy left.
migrate_legacy_retention_into(&restore_app, &scope);
crate::event_sync::spawn_event_sync(
// Await the reconcile to completion — do NOT spawn it — and
// propagate its failure. The boot migration may have repaired team
// membership on disk; the frontend starts inbound history replay
// the moment `useCommunityInit` observes the applied workspace, and
// an old relay team head could otherwise win that race and overwrite
// the repaired `persona_ids`. The team leg is fatal (see
// `run_event_sync`): only its success durably retains the corrected
// head with a superseding `monotonic_created_at`, so
// `retain_inbound_event`'s equal/older guard rejects the stale head.
// On failure we return `Err` — the command reports failure,
// `useCommunityInit` never exposes the community, and inbound replay
// never starts against an un-superseded disk state.
crate::event_sync::run_event_sync_blocking(
restore_app.clone(),
scope.owner_keys,
scope.db_path,
)
.await?;
}
Err(error) => {
eprintln!("buzz-desktop: scoped event-sync unavailable after workspace apply: {error}");
// Scope resolution is a prerequisite for establishing the
// superseding head, so its failure is fatal for the same reason:
// without a scope we cannot retain the repaired roster ahead of an
// inbound replay. Fail the command rather than silently opening the
// inbound lane.
return Err(format!(
"scoped event-sync unavailable after workspace apply: {error}"
));
}
}

Expand Down
64 changes: 39 additions & 25 deletions desktop/src-tauri/src/event_sync.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,32 +13,44 @@ use std::path::Path;
/// `sync_team_personas` wrote in [`crate::migration::run_boot_migrations`]
/// (see its `# Ordering` guard). Event signing needs the resolved owner keys,
/// so this runs after identity resolution, not in the boot migrations.
pub fn run_event_sync(app: &tauri::AppHandle, owner_keys: &nostr::Keys, db_path: &Path) {
pub fn run_event_sync(
app: &tauri::AppHandle,
owner_keys: &nostr::Keys,
db_path: &Path,
) -> Result<(), String> {
// Persona and agent legs stay best-effort: they log and swallow, and their
// failure does not undo the boot team-membership repair. The team leg is
// fatal — it establishes the superseding local head (a monotonic
// `created_at`) that lets `retain_inbound_event`'s equal/older guard reject
// a stale relay roster. If it fails, the caller must not let the frontend
// expose the community and start inbound replay against an un-superseded
// disk state.
migrate_personas_to_events(app, owner_keys, db_path);
migrate_teams_to_events(app, owner_keys, db_path);
migrate_teams_to_events(app, owner_keys, db_path)?;
crate::managed_agents::reconcile::reconcile_agents_to_events(app, owner_keys, db_path);
Ok(())
}

/// Spawn the best-effort event reconcile off the synchronous Tauri setup path.
/// Run the scoped event reconcile to completion on the blocking pool.
///
/// Callers that must not let downstream work observe a not-yet-retained disk
/// state (e.g. `apply_workspace` before the frontend can start inbound history
/// replay) await this so the repaired local heads are durably retained — with a
/// superseding `monotonic_created_at` — before an old relay head can race in.
/// The owner keys are moved in so the task never touches the `AppState::keys`
/// mutex; the reconcile itself is synchronous JSON/SQLite/signing work, so it
/// runs on the blocking pool rather than an async worker.
///
/// The owner keys are cloned before spawning so the task never touches the
/// `AppState::keys` mutex. The reconcile itself is still synchronous JSON,
/// SQLite, and signing work, so it runs on the blocking pool rather than an
/// async worker.
pub fn spawn_event_sync(
/// Returns `Err` if the task fails to join or the fatal team leg errors, so the
/// caller can withhold community exposure until the superseding head is durable.
pub async fn run_event_sync_blocking(
app: tauri::AppHandle,
owner_keys: nostr::Keys,
db_path: std::path::PathBuf,
) {
tauri::async_runtime::spawn(async move {
if let Err(e) = tauri::async_runtime::spawn_blocking(move || {
run_event_sync(&app, &owner_keys, &db_path);
})
) -> Result<(), String> {
tauri::async_runtime::spawn_blocking(move || run_event_sync(&app, &owner_keys, &db_path))
.await
{
eprintln!("buzz-desktop: event-sync: spawn_blocking failed: {e}");
}
});
.map_err(|e| format!("event-sync: spawn_blocking failed: {e}"))?
}

/// Reconcile `personas.json` into the persona-event retention store.
Expand Down Expand Up @@ -219,21 +231,23 @@ fn migrate_personas_in_dir_at(
///
/// Must run after the persisted identity is resolved (it signs each event with
/// the owner's keys).
pub fn migrate_teams_to_events(app: &tauri::AppHandle, keys: &nostr::Keys, db_path: &Path) {
pub fn migrate_teams_to_events(
app: &tauri::AppHandle,
keys: &nostr::Keys,
db_path: &Path,
) -> Result<(), String> {
use crate::managed_agents::managed_agents_base_dir;

let Ok(base_dir) = managed_agents_base_dir(app) else {
return;
};
let base_dir = managed_agents_base_dir(app)
.map_err(|e| format!("team-event-migration: base dir unavailable: {e}"))?;

match migrate_teams_in_dir_at(&base_dir, keys, db_path) {
Ok(0) => {}
Ok(0) => Ok(()),
Ok(migrated) => {
eprintln!("buzz-desktop: team-event-migration: {migrated} teams migrated to retention");
Ok(())
}
Err(e) => {
eprintln!("buzz-desktop: team-event-migration: {e}");
}
Err(e) => Err(format!("team-event-migration: {e}")),
}
}

Expand Down
129 changes: 129 additions & 0 deletions desktop/src-tauri/src/event_sync_team_events_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -133,3 +133,132 @@ fn migrate_teams_no_file_is_noop() {
let keys = nostr::Keys::generate();
assert_eq!(migrate_teams_in_dir(base.path(), &keys).unwrap(), 0);
}

/// Error-contract for the fatal team leg. `run_event_sync` propagates a team
/// leg failure via `?`, and `apply_workspace` returns that `Err` so the
/// frontend never exposes the community against an un-superseded disk state.
/// This proves the leg genuinely surfaces failure (rather than logging and
/// swallowing) on an unreadable store — the precondition that made the
/// propagation load-bearing.
#[test]
fn migrate_teams_surfaces_error_on_unparseable_store() {
let base = tempfile::tempdir().unwrap();
std::fs::write(base.path().join("teams.json"), "{ not valid json").unwrap();
let keys = nostr::Keys::generate();
assert!(migrate_teams_in_dir(base.path(), &keys).is_err());
}

/// Build a signed inbound team head at an explicit `created_at`, mirroring a
/// relay replay of a stale, pre-namespacing roster.
fn stale_inbound_head(
keys: &nostr::Keys,
id: &str,
bare_persona_ids: &[&str],
created_at: i64,
) -> crate::managed_agents::retention::RetainedEvent {
use crate::managed_agents::{team_events::build_team_event, TeamRecord};
use buzz_core_pkg::kind::KIND_TEAM;
use nostr::JsonUtil;

let record = TeamRecord {
id: id.to_string(),
name: "Sietch Tabr".to_string(),
description: None,
instructions: None,
persona_ids: bare_persona_ids.iter().map(|s| s.to_string()).collect(),
is_builtin: false,
source_dir: None,
is_symlink: false,
symlink_target: None,
version: None,
created_at: "2025-01-01T00:00:00Z".to_string(),
updated_at: "2025-01-01T00:00:00Z".to_string(),
};
let event = build_team_event(&record)
.unwrap()
.custom_created_at(nostr::Timestamp::from(created_at as u64))
.sign_with_keys(keys)
.unwrap();
crate::managed_agents::retention::RetainedEvent {
kind: KIND_TEAM,
pubkey: keys.public_key().to_hex(),
d_tag: id.to_string(),
content: event.content.to_string(),
created_at: event.created_at.as_secs() as i64,
raw_event: event.as_json(),
pending_sync: false,
}
}

/// Finding-1 retention-precedence guarantee. This proves the *mechanic* the
/// awaited-reconcile ordering relies on — it does not itself exercise
/// `apply_workspace` (an `AppHandle`-level path). Given the boot reconcile has
/// retained the repaired namespaced roster with a monotonic `created_at`
/// (reconcile-first), a stale relay head replayed afterward is older, so
/// `retain_inbound_event` skips it and the repaired roster stays. The
/// inbound-first lane is the counterfactual the ordering closes: with no
/// repaired head retained yet, the very same stale head is applied and restores
/// bare membership. Retention order is the only difference between the lanes;
/// `apply_workspace` awaiting the reconcile (see `commands/workspace.rs`) is
/// what forces the reconcile-first order in production.
#[test]
fn reconcile_first_makes_stale_inbound_team_head_lose() {
use crate::managed_agents::retention::{
get_retained_event, open_retention_db, retain_inbound_event, InboundOutcome,
};
use buzz_core_pkg::kind::KIND_TEAM;

let keys = nostr::Keys::generate();
let pubkey = keys.public_key().to_hex();
let repaired = serde_json::json!([{
"id": "sietch-tabr",
"name": "Sietch Tabr",
"persona_ids": ["sietch-tabr:thufir", "sietch-tabr:paul", "sietch-tabr:duncan"],
"is_builtin": false,
"created_at": "2025-01-01T00:00:00Z",
"updated_at": "2025-01-01T00:00:00Z"
}]);
let bare = ["thufir", "paul", "duncan"];

// Reconcile-first lane (the fix): the awaited boot reconcile retains the
// repaired namespaced roster with a monotonic `created_at`; a stale relay
// head replayed afterward is older, so `retain_inbound_event` skips it and
// the retained roster stays repaired.
let ordered = tempfile::tempdir().unwrap();
let ordered_db = ordered.path().join("retention.db");
write_base_teams(ordered.path(), &repaired);
assert_eq!(
migrate_teams_in_dir_at(ordered.path(), &keys, &ordered_db).unwrap(),
1
);
let conn = open_retention_db(&ordered_db).unwrap();
let repaired_head = get_retained_event(&conn, KIND_TEAM, &pubkey, "sietch-tabr")
.unwrap()
.unwrap();
let stale = stale_inbound_head(&keys, "sietch-tabr", &bare, repaired_head.created_at - 1);
assert_eq!(
retain_inbound_event(&conn, &stale).unwrap(),
InboundOutcome::Skipped
);
let head = get_retained_event(&conn, KIND_TEAM, &pubkey, "sietch-tabr")
.unwrap()
.unwrap();
assert!(head.content.contains("sietch-tabr:thufir"));
assert!(!head.content.contains("\"thufir\""));

// Inbound-first lane (the race the fix closes): with no repaired head
// retained yet, the very same stale relay head is applied, restoring the
// bare pre-namespacing roster. Ordering is the only difference.
let raced = tempfile::tempdir().unwrap();
let raced_db = raced.path().join("retention.db");
let raced_conn = open_retention_db(&raced_db).unwrap();
let stale = stale_inbound_head(&keys, "sietch-tabr", &bare, repaired_head.created_at - 1);
assert_eq!(
retain_inbound_event(&raced_conn, &stale).unwrap(),
InboundOutcome::Applied
);
let head = get_retained_event(&raced_conn, KIND_TEAM, &pubkey, "sietch-tabr")
.unwrap()
.unwrap();
assert!(head.content.contains("\"thufir\""));
}
1 change: 1 addition & 0 deletions desktop/src-tauri/src/managed_agents/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ pub(crate) mod spawn_snapshot;
pub(crate) mod storage;
pub(crate) mod team_events;
mod team_repair;
pub(crate) use team_repair::team_persona_key;
mod teams;
mod types;

Expand Down
10 changes: 5 additions & 5 deletions desktop/src-tauri/src/migration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -149,8 +149,7 @@ fn run_boot_migrations_inner(app: &tauri::AppHandle, reset_completed: bool) {
// ensures the dev nest boots with the correct workspace on its first launch,
// matching what the prod nest had configured. Skip-if-dest-exists so it is
// idempotent and never clobbers a value the dev nest already set explicitly.
// Uses the composed helper so the gate + migration run through the same
// code path that the behavioral test exercises.
// Uses the composed helper so gate + migration share the tested code path.
if let (Some(home), Some(dev_nest)) = (dirs::home_dir(), crate::managed_agents::nest_dir()) {
maybe_migrate_dev_repos_dir(is_dev, reset_completed, &home, &dev_nest);
}
Expand Down Expand Up @@ -183,10 +182,10 @@ fn run_boot_migrations_inner(app: &tauri::AppHandle, reset_completed: bool) {
strip_baked_team_instructions(app);
refresh_builtin_agent_avatars(app);
// B5: manufacture definitions for standalone agents AFTER the fold (so
// pre-existing definition slugs are present for collision checks) and
// before event sync republishes — the backfilled link is what flips the
// 30177 projection to its slim shape.
// pre-existing definition slugs exist for collision checks) and before event
// sync republishes — the backfilled link flips the 30177 projection.
backfill_standalone_agents(app);
team_membership::repair_team_membership(app);
detach_directory_backed_teams(app);
reconcile_provider_mcp_commands(app);
reconcile_databricks_v1_to_v2(app);
Expand Down Expand Up @@ -1376,6 +1375,7 @@ mod backfill;
pub use backfill::backfill_standalone_agents;
mod detach;
pub use detach::detach_directory_backed_teams;
mod team_membership;
mod team_suffix;
pub use team_suffix::strip_baked_team_instructions;

Expand Down
Loading
Loading