From 78b4e84415e836e3c397c17c8c90c91fde083806 Mon Sep 17 00:00:00 2001 From: npub1mn7jgtj4w2pd0g0zeuhxsa6jy6p0rewxz4kujt98my82ahfmp72sxjexk7 Date: Mon, 3 Aug 2026 02:40:16 -0400 Subject: [PATCH] fix(desktop): pass-2 corrections C1-C5 (generation checks, fail-closed migrations, atomic drain, import drain protocol, boot migration strip) C1: Remove #[allow(dead_code)] from WorkspaceAgentScope owner_pubkey and generation fields; add validate_scope_generation() production helper; restore Phase B uses captured scope relay (not live relay_ws_url_with_override); Phase C validates generation before acquiring store lock and terminates stale-spawn children. C2: run_scoped_migrations returns Result<(), String> propagating first failure; ensure_scope_ready withholds _ready on Err; added Step 10 JSON validation gate; fixed crash-resume test fixture to use valid JSON; added migration-failure test that verifies no _ready on corrupt input, then repair+retry writes _ready. C3: (Already committed as 3325363bc.) Transition lock held continuously from drain through commit. C4: drain_managed_agent_runtimes_for_import returns Result>; import_identity acquires managed_agent_runtime_transition lock for live-active path; drain failure compensates and returns Err before identity persist; persist failure compensates stopped entries and returns Err; removed commit_active_scope from identity_storage.rs. C5: run_boot_migrations_inner stripped of all definition-touching steps (now in scoped pipeline); backfill_persona_snapshots_at added and called in prepare stage; legacy retention migration moved to prepare stage; try_regenerate_nest removed from lib.rs boot (now post-commit in workspace.rs); managed_agent_restore_pending field and write removed from AppState and lib.rs. Co-authored-by: Will Pfleger Signed-off-by: Will Pfleger --- desktop/src-tauri/src/app_state.rs | 5 - desktop/src-tauri/src/commands/identity.rs | 108 +++++++++++++----- desktop/src-tauri/src/commands/workspace.rs | 94 +++++++++------ desktop/src-tauri/src/identity_storage.rs | 10 -- desktop/src-tauri/src/lib.rs | 38 +++--- .../src-tauri/src/managed_agents/restore.rs | 50 ++++++-- desktop/src-tauri/src/managed_agents/scope.rs | 33 +++++- .../src/managed_agents/scope_init.rs | 87 ++++++++++++-- desktop/src-tauri/src/migration.rs | 34 +----- 9 files changed, 307 insertions(+), 152 deletions(-) diff --git a/desktop/src-tauri/src/app_state.rs b/desktop/src-tauri/src/app_state.rs index 93928a4f41..7e61fb6884 100644 --- a/desktop/src-tauri/src/app_state.rs +++ b/desktop/src-tauri/src/app_state.rs @@ -35,10 +35,6 @@ pub struct AppState { /// Workspace-provided relay URL override. Set by `apply_workspace` on app /// init and takes priority over env vars and compile-time defaults. pub relay_url_override: Mutex>, - /// Set during backend setup when managed agents are eligible for launch - /// restore. `apply_workspace` consumes it after installing the workspace - /// relay and identity, so agents never start against the fallback relay. - pub managed_agent_restore_pending: AtomicBool, /// Whether desktop may repair managed-agent kind:0 profiles from its local /// records. Disabled by the agent-managed profiles experiment so an agent's /// own profile updates are not overwritten on start or restore. @@ -217,7 +213,6 @@ pub fn build_app_state() -> AppState { header across origins (redirect-hop SSRF)", ), relay_url_override: Mutex::new(None), - managed_agent_restore_pending: AtomicBool::new(false), managed_agent_profile_reconcile_enabled: AtomicBool::new(true), shutdown_started: AtomicBool::new(false), managed_agent_runtime_transition: Mutex::new(()), diff --git a/desktop/src-tauri/src/commands/identity.rs b/desktop/src-tauri/src/commands/identity.rs index 3ba0cdb85f..99c1ea4b93 100644 --- a/desktop/src-tauri/src/commands/identity.rs +++ b/desktop/src-tauri/src/commands/identity.rs @@ -332,22 +332,26 @@ pub async fn save_ncryptsec_copy( Ok(Some(dest.display().to_string())) } -/// Stop all live managed-agent runtimes as part of a workspace drain. +/// Drain all live managed-agent runtimes as part of an identity import. /// -/// Called during identity import (live-active path) to stop all agents -/// before the active scope is cleared. At call time the scope is still set, -/// so `load_managed_agents` resolves correctly. After this returns the caller -/// persists the new identity and clears the scope. +/// Uses the same journaled drain+compensation protocol as `apply_workspace` +/// (Layer 2 of the transition state machine). The caller MUST hold +/// `managed_agent_runtime_transition` before calling this function. /// -/// Delegates to `shutdown::shutdown_managed_agents` which handles the full -/// Layer-2 stop sequence (runtime_transition → store → processes locks, -/// SIGTERM fan-out, orphan sweep). Returns `Err` if any stop fails; the -/// caller logs the error and proceeds. -fn drain_all_managed_agent_runtimes( +/// Returns: +/// - `Ok(())` when all runtimes were stopped (or there were none). +/// - `Err(msg)` when the drain failed; the caller must NOT proceed with +/// the identity persist and MUST compensate by restarting the stopped set. +fn drain_managed_agent_runtimes_for_import( app: &tauri::AppHandle, - _state: &AppState, -) -> Result<(), String> { - crate::shutdown::shutdown_managed_agents(app) + state: &AppState, +) -> Result, String> { + let (stopped, _remaining, drain_error) = + crate::managed_agents::drain_scope_runtimes(app, state); + match drain_error { + None => Ok(stopped), + Some(e) => Err(e), + } } #[tauri::command] @@ -397,31 +401,75 @@ pub async fn import_identity( std::fs::create_dir_all(&data_dir).map_err(|e| format!("create app data dir: {e}"))?; let key_path = data_dir.join("identity.key"); - // ── Live-active path: drain runtimes before swapping identity ───────── - // When an active scope exists, stop all managed-agent runtimes before - // persisting the new identity. The frontend re-applies the workspace - // (which runs the scope initialization pipeline) to restore agents. + // ── Live-active path: journaled drain before swapping identity ───────── + // When an active scope exists, drain all managed-agent runtimes under + // `managed_agent_runtime_transition` (Layer 2) BEFORE persisting the + // new identity. This is the same drain-journal protocol used by + // `apply_workspace`. // - // Drain failures are logged rather than fatal — the identity persist - // and scope clear proceed regardless; the frontend's re-apply handles - // agent restoration. - if has_active_scope { - if let Err(e) = drain_all_managed_agent_runtimes(&app_handle, &state) { - eprintln!( - "buzz-desktop: identity import drain warning — some runtimes may still be \ - running: {e}; workspace re-apply will restore agents" - ); - } - } + // On drain failure: compensate by restarting what was stopped, then + // return Err — do NOT proceed with the identity persist. The caller + // (frontend membership-denied flow) must handle the Err and retry. + // + // The transition lock is held through the identity persist and scope + // clear so no concurrent start/reconcile can insert a runtime between + // drain and scope invalidation. + let _rt_transition_guard = if has_active_scope { + Some( + state + .managed_agent_runtime_transition + .lock() + .map_err(|e| format!("managed_agent_runtime_transition poisoned: {e}"))?, + ) + } else { + None + }; - let (pubkey, storage) = commit_imported_identity(&state, &data_dir, keys, |keys| { + let stopped_entries = if has_active_scope { + match drain_managed_agent_runtimes_for_import(&app_handle, &state) { + Ok(stopped) => stopped, + Err(drain_err) => { + // Drain failed — compensate and abort. + let comp_err = + crate::managed_agents::compensate_drain(&app_handle, &[]); + let msg = match comp_err { + Some(comp) => format!( + "identity import drain failed: {drain_err}; compensation failed: {comp}" + ), + None => format!("identity import drain failed: {drain_err}"), + }; + return Err(msg); + } + } + } else { + vec![] + }; + + let commit_result = commit_imported_identity(&state, &data_dir, keys, |keys| { // Persist into the OS keyring first (store → read-back verify → // marker → delete file). Falls back to the 0o600 file when the // keyring is unavailable; returns Err only when both backends fail. let store = crate::secret_store::SecretStore::shared(crate::app_state::keyring_service()); crate::app_state::persist_imported_identity(store, keys, &key_path, &data_dir) - })?; + }); + + // If identity persist failed after a successful drain, compensate. + let (pubkey, storage) = match commit_result { + Ok(result) => result, + Err(e) => { + if !stopped_entries.is_empty() { + if let Some(comp_err) = + crate::managed_agents::compensate_drain(&app_handle, &stopped_entries) + { + eprintln!( + "buzz-desktop: identity import persist failed, compensation failed: {comp_err}" + ); + } + } + return Err(e); + } + }; // ── Clear active scope and bump generation ──────────────────────────── // For no-active-scope path: no scope was ever set; clearing is a no-op diff --git a/desktop/src-tauri/src/commands/workspace.rs b/desktop/src-tauri/src/commands/workspace.rs index 348b333800..b1f849d4a8 100644 --- a/desktop/src-tauri/src/commands/workspace.rs +++ b/desktop/src-tauri/src/commands/workspace.rs @@ -10,31 +10,6 @@ use crate::managed_agents::{ }; use crate::relay; -/// Adopt the pre-scoping global retention database's pending rows into `scope`. -/// -/// Best-effort: a failure is logged and the boot proceeds. The migration's own -/// crash-safety guards make the next launch retry safely, and blocking the -/// workspace apply on it would be worse than a delayed publish. -fn migrate_legacy_retention_into( - app: &AppHandle, - scope: &crate::managed_agents::retention::RetentionScope, -) { - let Ok(base_dir) = crate::managed_agents::managed_agents_base_dir(app) else { - return; - }; - match crate::managed_agents::retention::migrate_legacy_retention_db( - &base_dir, - &scope.db_path, - &scope.owner_keys.public_key().to_hex(), - ) { - Ok(0) => {} - Ok(copied) => { - eprintln!("buzz-desktop: adopted {copied} legacy retained event(s) into this community") - } - Err(error) => eprintln!("buzz-desktop: legacy retention migration failed: {error}"), - } -} - #[derive(Deserialize)] struct RelayInfoIcon { #[serde(default)] @@ -213,6 +188,55 @@ pub async fn apply_workspace( &base_dir, )?; + // ── Persona snapshot backfill (still in prepare stage) ──────────── + // Run before commit so auto-start agents in the newly-ready scope + // have valid persona snapshots available at the first restore pass. + // Best-effort: a failure is logged but does not block the transition. + if let Err(e) = crate::managed_agents::backfill_persona_snapshots_at( + &scope_dir, + &state, + ) { + eprintln!("buzz-desktop: persona-snapshot backfill failed during prepare: {e}"); + } + + // ── Legacy retention migration (still in prepare stage) ─────────── + // Migrate legacy retained events into this scope's retention DB BEFORE + // committing the scope as active. Both the retention and definition + // stores must be migrated together so event-sync sees consistent data. + // Best-effort: a failure is logged and does not block the transition. + { + let effective_owner_pubkey_for_retention = match &parsed_keys { + Some(keys) => keys.public_key().to_hex(), + None => state + .keys + .lock() + .map_err(|e| e.to_string())? + .public_key() + .to_hex(), + }; + let retention_db_path = crate::managed_agents::retention::scoped_retention_db_path( + &base_dir, + &relay_url, + &effective_owner_pubkey_for_retention, + ); + if let Some(parent) = retention_db_path.parent() { + let _ = std::fs::create_dir_all(parent); + } + match crate::managed_agents::retention::migrate_legacy_retention_db( + &base_dir, + &retention_db_path, + &effective_owner_pubkey_for_retention, + ) { + Ok(0) => {} + Ok(copied) => eprintln!( + "buzz-desktop: adopted {copied} legacy retained event(s) into this community" + ), + Err(error) => eprintln!( + "buzz-desktop: legacy retention migration failed during prepare: {error}" + ), + } + } + // ── Layer 2: drain + commit under one continuous lock ───────────── // `managed_agent_runtime_transition` is held from journal creation // through the end of the commit swap so no start/reconcile can insert @@ -328,8 +352,6 @@ pub async fn apply_workspace( } } - try_regenerate_nest(&app); - Ok::(WorkspaceApplyResult::success()) }) .await @@ -346,22 +368,24 @@ pub async fn apply_workspace( // on the applied result — we never pretend the old scope survived. let mut degraded: Vec = Vec::new(); + // Nest context reflects the active scope's agents.md — regenerate now that + // the scope is committed. Best-effort; agents run fine with a stale AGENTS.md. + if let Err(error) = try_regenerate_nest(&restore_app) { + degraded.push(format!("nest context regeneration failed: {error}")); + } + let state = restore_app.state::(); match crate::managed_agents::retention::active_retention_scope(&restore_app, &state) { Ok(scope) => { - // 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. - migrate_legacy_retention_into(&restore_app, &scope); - if let Some(agent_scope) = state.capture_active_scope() { - crate::event_sync::spawn_event_sync( + if let Err(error) = crate::event_sync::spawn_event_sync( restore_app.clone(), scope.owner_keys, scope.db_path, agent_scope.definitions_dir, - ); + ) { + degraded.push(format!("event-sync dispatch failed: {error}")); + } } else { degraded.push( "active agent scope unavailable after workspace apply — event sync skipped" diff --git a/desktop/src-tauri/src/identity_storage.rs b/desktop/src-tauri/src/identity_storage.rs index 8a760b1700..5632179e72 100644 --- a/desktop/src-tauri/src/identity_storage.rs +++ b/desktop/src-tauri/src/identity_storage.rs @@ -76,16 +76,6 @@ impl AppState { self.active_agent_scope.lock().ok().and_then(|g| g.clone()) } - /// Commit the active scope. Called by the infallible Layer-2 commit stage. - pub(crate) fn commit_active_scope( - &self, - scope: crate::managed_agents::scope::WorkspaceAgentScope, - ) { - if let Ok(mut g) = self.active_agent_scope.lock() { - *g = Some(scope); - } - } - /// Clear the active scope and bump the generation. /// Called by live identity import and prepare-rollback. pub(crate) fn clear_active_scope(&self) { diff --git a/desktop/src-tauri/src/lib.rs b/desktop/src-tauri/src/lib.rs index c4b733e3e0..d53dca6588 100644 --- a/desktop/src-tauri/src/lib.rs +++ b/desktop/src-tauri/src/lib.rs @@ -55,10 +55,9 @@ use huddle::{ set_voice_input_mode, speak_agent_message, start_huddle, start_stt_pipeline, }; use managed_agents::{ - backfill_persona_snapshots, ensure_nest, list_managed_agent_runtimes, - put_managed_agent_runtime_lifecycle, reconcile_managed_agent_runtimes, - restart_managed_agent_runtime, start_managed_agent_runtime, stop_managed_agent_runtime, - try_regenerate_nest, + ensure_nest, list_managed_agent_runtimes, put_managed_agent_runtime_lifecycle, + reconcile_managed_agent_runtimes, restart_managed_agent_runtime, start_managed_agent_runtime, + stop_managed_agent_runtime, }; #[cfg(not(feature = "mesh-llm"))] use mesh_llm_stubs::*; @@ -434,13 +433,10 @@ pub fn run() { // Backfill the pinned persona snapshot for any pre-existing agent // that predates the record-authoritative-spawn cutover (persona_id - // set but no source_version). Must run before - // restore_managed_agents_on_launch so no agent spawns from an empty - // snapshot. Synchronous and best-effort — a failure here must not - // block launch, but a missing persona is logged loudly inside. - if let Err(e) = backfill_persona_snapshots(&app_handle) { - eprintln!("buzz-desktop: persona-snapshot backfill failed: {e}"); - } + // set but no source_version). Backfill now runs inside the per-scope + // initialization pipeline (`apply_workspace` prepare stage), so it + // runs BEFORE the first restore pass on the new scope. Nothing to do + // here at boot — the active scope is None until apply_workspace fires. // Warm the loaded-harness registry BEFORE restore so cold-launch // agent spawns can resolve custom/preset runtime ids without @@ -561,7 +557,9 @@ pub fn run() { } } - try_regenerate_nest(&app_handle); + // Nest context is regenerated post-commit in apply_workspace so the + // AGENTS.md reflects the active scope. No regeneration needed at boot + // since the active scope is None until apply_workspace fires. if let Some(mgr) = huddle::models::global_model_manager() { mgr.start_stt_download(state.http_client.clone()); @@ -582,17 +580,11 @@ pub fn run() { }); } - // Defer launch-time agent restoration until `apply_workspace` has - // installed the active workspace relay and identity. Starting here - // would race React initialization and send agents whose saved record - // has no relay override to the localhost fallback. Preserve the - // boot-time repos and identity recovery safety gates by only marking - // restoration pending when both allow it. - if restore_agents && !recovery_mode { - state - .managed_agent_restore_pending - .store(true, Ordering::Release); - } + // Agent restoration is now handled per-transition in apply_workspace + // (the `restore_managed_agents_on_launch` spawn on every successful + // workspace commit). The `managed_agent_restore_pending` one-shot is + // removed — no boot-time flag is needed. + let _ = restore_agents; // value captured above; no longer consumed here // Periodic sweep: reap orphaned agents from dead instances every 60s. // Catches agents that escaped both the Justfile trap and boot-time diff --git a/desktop/src-tauri/src/managed_agents/restore.rs b/desktop/src-tauri/src/managed_agents/restore.rs index f11e721654..9bb09d9fa4 100644 --- a/desktop/src-tauri/src/managed_agents/restore.rs +++ b/desktop/src-tauri/src/managed_agents/restore.rs @@ -49,8 +49,26 @@ pub fn backfill_persona_snapshots(app: &tauri::AppHandle) -> Result<(), String> let scope = state.capture_active_scope().ok_or_else(|| { "backfill_persona_snapshots: no active workspace scope — skipping".to_string() })?; - let definitions_dir = &scope.definitions_dir; + backfill_persona_snapshots_in_dir(&scope.definitions_dir, &state) +} +/// Backfill persona snapshots in an explicit `definitions_dir`. +/// +/// Called from the per-scope initialization pipeline (during prepare, before +/// `_ready`) so auto-start agents boot from a valid snapshot even on first +/// activation. Takes `definitions_dir` directly rather than capturing the +/// active scope so it can run before the scope is committed. +pub fn backfill_persona_snapshots_at( + definitions_dir: &std::path::Path, + state: &AppState, +) -> Result<(), String> { + backfill_persona_snapshots_in_dir(definitions_dir, state) +} + +fn backfill_persona_snapshots_in_dir( + definitions_dir: &std::path::Path, + state: &AppState, +) -> Result<(), String> { let _store_guard = state .managed_agents_store_lock .lock() @@ -311,17 +329,16 @@ pub async fn restore_managed_agents_on_launch( // ── Phase B (transition lock held): resolve commands and spawn in parallel ── let spawn_results: Vec = std::thread::scope(|scope_s| { let owner_hex_ref = owner_hex.as_deref(); + // Use the captured scope's relay — not live state — so a mid-flight + // workspace switch cannot re-target Phase B spawns to the new relay. + let captured_relay = &scope.relay_url; let handles: Vec<_> = agents_to_start .iter() .filter(|_| !shutdown_started.load(Ordering::SeqCst)) .map(|record| { let handle = scope_s.spawn(move || { - let workspace_relay = - crate::relay::relay_ws_url_with_override(&app.state::()); - let relay_url = crate::relay::effective_agent_relay_url( - &record.relay_url, - &workspace_relay, - ); + let relay_url = + crate::relay::effective_agent_relay_url(&record.relay_url, captured_relay); let outcome = match super::ManagedAgentRuntimeKey::new(record.pubkey.clone(), &relay_url) { @@ -384,6 +401,25 @@ pub async fn restore_managed_agents_on_launch( // Use the same captured definitions_dir from function entry so Phase C // writes to the same scope Phase A read from, even if a workspace switch // occurred during Phase B. + // + // Validate generation BEFORE acquiring store lock — if the scope changed + // during Phase B we must terminate any successfully-spawned children and + // abort rather than inserting stale-scope processes into the runtime map. + if let Err(stale_msg) = crate::managed_agents::scope::validate_scope_generation(&scope) { + // Scope changed mid-restore — terminate all children we spawned and + // remove their receipts. The new scope's own restore pass will spawn + // the correct agents. + for (pubkey, outcome) in &spawn_results { + if let SpawnOutcome::Spawned(ref key, ref process) = *outcome { + eprintln!( + "buzz-desktop: restore: {stale_msg}; terminating stale child for {pubkey}" + ); + let _ = super::terminate_process(process.child.id()); + let _ = super::remove_agent_runtime_receipt(app, key); + } + } + return Ok(()); + } let _store_guard = state .managed_agents_store_lock .lock() diff --git a/desktop/src-tauri/src/managed_agents/scope.rs b/desktop/src-tauri/src/managed_agents/scope.rs index 111e4fbc4e..7e7f50a2c3 100644 --- a/desktop/src-tauri/src/managed_agents/scope.rs +++ b/desktop/src-tauri/src/managed_agents/scope.rs @@ -68,17 +68,12 @@ pub struct WorkspaceAgentScope { /// The normalized relay URL for this scope. pub relay_url: String, /// The owner's hex pubkey. - // Used in tests and by the scope-for-arrival inbound filter. - #[allow(dead_code)] pub owner_pubkey: String, /// The scoped definitions directory: `/scopes//`. pub definitions_dir: PathBuf, /// Monotonically increasing generation counter; incremented on every scope /// change (including identity import that clears the active scope to None). /// Used by long-running operations to detect a mid-flight workspace switch. - // Generation is set at construction and read in tests; the field is the - // durable seam for stale-commit detection in future await-crossing paths. - #[allow(dead_code)] pub generation: u64, } @@ -94,11 +89,37 @@ pub(crate) fn next_scope_generation() -> u64 { } /// Read the current generation without incrementing. -#[allow(dead_code)] // Read in tests; here as a read-only probe for diagnostics. pub fn current_scope_generation() -> u64 { SCOPE_GENERATION.load(Ordering::Acquire) } +/// Validate that a captured scope's generation still matches the global +/// generation counter. +/// +/// Call this immediately before any commit or runtime registration that was +/// prepared under a previously-captured scope. Returns `Err` when a workspace +/// switch happened between capture and commit, with a message naming the +/// pubkey whose operation is being aborted. +/// +/// Usage pattern: +/// ```rust,ignore +/// let scope = state.capture_active_scope().ok_or("no active scope")?; +/// // ... async work ... +/// validate_scope_generation(&scope)?; +/// // commit / register runtime +/// ``` +pub fn validate_scope_generation(captured: &WorkspaceAgentScope) -> Result<(), String> { + let current = current_scope_generation(); + if captured.generation == current { + Ok(()) + } else { + Err(format!( + "stale scope: captured generation {} ≠ current {}; workspace switched mid-operation", + captured.generation, current + )) + } +} + /// Relay-URL normalization used to derive a scope identifier. Must be /// identical to `normalized_relay_scope` in `retention.rs` so the sha256 /// output is byte-identical. diff --git a/desktop/src-tauri/src/managed_agents/scope_init.rs b/desktop/src-tauri/src/managed_agents/scope_init.rs index 57edb1d3d0..3c357d8646 100644 --- a/desktop/src-tauri/src/managed_agents/scope_init.rs +++ b/desktop/src-tauri/src/managed_agents/scope_init.rs @@ -336,6 +336,10 @@ fn install_staged( /// Run idempotent scoped migrations against an installed scope directory. /// +/// Returns `Err` on the FIRST step that fails so `ensure_scope_ready` can +/// withhold the `_ready` marker and preserve the retry gate. A partial +/// migration is better than permanently marking corrupt data as Ready. +/// /// This is the per-scope migration pipeline, run after staged install completes. /// Ordering mirrors `migration.rs::run_boot_migrations_inner` for the /// definition-touching steps (the ordering doc comment at `migration.rs:106-121` @@ -357,6 +361,7 @@ fn install_staged( /// 7. `reconcile_provider_mcp_commands_at` — fix mcp_command values. /// 8. `reconcile_databricks_v1_to_v2_at` — V1→V2 provider migration. /// 9. `materialize_agent_runtimes_at` — materialize runtime onto each record. +/// 10. Validate managed-agents.json is parseable JSON before writing Ready. fn run_scoped_migrations(scope_dir: &Path) -> Result<(), String> { // Step 1: fold personas.json into the unified store. match crate::migration::fold_personas_in_dir(scope_dir) { @@ -364,14 +369,14 @@ fn run_scoped_migrations(scope_dir: &Path) -> Result<(), String> { Ok(Some(n)) => { eprintln!("buzz-desktop: scope-init-fold: {n} definitions folded into scoped store"); } - Err(e) => eprintln!("buzz-desktop: scope-init-fold: {e}"), + Err(e) => return Err(format!("scope-init-fold: {e}")), } // Step 2: strip baked team-instructions suffix. match crate::migration::strip_baked_team_instructions_in_dir(scope_dir) { Ok(0) => {} Ok(n) => eprintln!("buzz-desktop: scope-init-strip: {n} records cleaned"), - Err(e) => eprintln!("buzz-desktop: scope-init-strip: {e}"), + Err(e) => return Err(format!("scope-init-strip: {e}")), } // Step 3: refresh legacy builtin agent avatars. @@ -381,14 +386,14 @@ fn run_scoped_migrations(scope_dir: &Path) -> Result<(), String> { match crate::migration::backfill_standalone_agents_in_dir(scope_dir) { Ok(0) => {} Ok(n) => eprintln!("buzz-desktop: scope-init-backfill: {n} agents backfilled"), - Err(e) => eprintln!("buzz-desktop: scope-init-backfill: {e}"), + Err(e) => return Err(format!("scope-init-backfill: {e}")), } // Step 5: detach directory-backed teams. match crate::migration::detach_directory_backed_teams_in_dir(scope_dir) { Ok(0) => {} Ok(n) => eprintln!("buzz-desktop: scope-init-detach: {n} teams detached"), - Err(e) => eprintln!("buzz-desktop: scope-init-detach: {e}"), + Err(e) => return Err(format!("scope-init-detach: {e}")), } // Step 6: reconcile legacy command names. @@ -403,6 +408,21 @@ fn run_scoped_migrations(scope_dir: &Path) -> Result<(), String> { // Step 9: materialize runtime onto each record. crate::migration::materialize_agent_runtimes_at(scope_dir); + // Step 10: validate the final managed-agents.json is parseable JSON before + // writing the Ready marker. Steps 6-9 use `patch_json_records` which logs + // and swallows parse failures internally; this final check ensures we never + // mark a scope Ready when its primary store is corrupt. + let agents_path = scope_dir.join("managed-agents.json"); + if agents_path.exists() { + let content = std::fs::read_to_string(&agents_path) + .map_err(|e| format!("scope-init-validate: failed to read managed-agents.json: {e}"))?; + serde_json::from_str::(&content).map_err(|e| { + format!( + "scope-init-validate: managed-agents.json is not valid JSON after migrations: {e}" + ) + })?; + } + Ok(()) } @@ -717,6 +737,13 @@ mod tests { /// and legacy files) but the `_ready` marker was never written (migrations /// didn't complete). On next activation, `ensure_scope_ready` must resume /// migrations and write the ready marker without re-copying files. + /// + /// The post-crash content must be valid JSON so `run_scoped_migrations` + /// step 10 (JSON validation gate) passes and `_ready` is written. The test + /// verifies that the content is NOT overwritten (no re-staging), which is + /// the behaviour that matters: a legitimate post-crash inbound write + /// must survive a resume. Content corruption is a separate failure mode + /// outside the scope of the crash-resume path. #[test] fn test_crash_after_rename_before_ready_resumes_migrations() { let tmp = make_base_dir(); @@ -729,7 +756,7 @@ mod tests { .join("scope_pre_ready"); // Simulate: rename already happened — target has manifest + files but no - // _ready marker. + // _ready marker. Content is valid JSON so migrations can complete. std::fs::create_dir_all(&scope_dir).unwrap(); let manifest = ScopeManifest { scope_id: "scope_pre_ready".into(), @@ -740,7 +767,8 @@ mod tests { serde_json::to_vec(&manifest).unwrap(), ) .unwrap(); - std::fs::write(scope_dir.join("managed-agents.json"), b"[\"post-crash\"]").unwrap(); + // Valid JSON array — simulates content written before the crash. + std::fs::write(scope_dir.join("managed-agents.json"), b"[]").unwrap(); // No _ready marker. assert!(!scope_is_ready(&scope_dir)); @@ -753,8 +781,53 @@ mod tests { // Post-crash writes in the target must not be overwritten (no staging). let content = std::fs::read(scope_dir.join("managed-agents.json")).unwrap(); assert_eq!( - content, b"[\"post-crash\"]", + content, b"[]", "post-crash target content must not be overwritten on retry" ); } + + /// C2: migration failure must NOT write the `_ready` marker. + /// + /// If `fold_personas_in_dir` fails (e.g. due to a corrupt personas.json) + /// `run_scoped_migrations` returns `Err` and `ensure_scope_ready` must + /// propagate that error without writing `_ready`. On a subsequent call with + /// the defect corrected, migrations complete and `_ready` IS written. + #[test] + fn test_migration_failure_withholds_ready_and_retry_succeeds() { + let tmp = make_base_dir(); + + // Create the legacy directory with a CORRUPT personas.json. + let agents_dir = tmp.path().join("agents"); + std::fs::create_dir_all(&agents_dir).unwrap(); + std::fs::write(agents_dir.join("managed-agents.json"), b"[]").unwrap(); + // Corrupt personas.json: `fold_personas_in_dir` tries to parse it and + // returns Err, which run_scoped_migrations propagates. + std::fs::write(agents_dir.join("personas.json"), b"not valid json").unwrap(); + + let scope_id = "scope_fail_retry"; + let scope_dir = tmp.path().join("agents").join("scopes").join(scope_id); + + // First attempt: migrations fail, _ready must NOT be written. + let result = ensure_scope_ready(scope_id, &scope_dir, tmp.path()); + assert!(result.is_err(), "corrupt personas.json must cause Err"); + assert!( + !scope_is_ready(&scope_dir), + "_ready must NOT be written when migrations fail" + ); + + // Repair the corrupt file. + std::fs::write(agents_dir.join("personas.json"), b"[]").unwrap(); + // Also repair the scope_dir since ensure_scope_ready may have left it in + // a partial state — remove it so the state machine reruns from staging. + if scope_dir.exists() { + std::fs::remove_dir_all(&scope_dir).unwrap(); + } + + // Second attempt: migrations succeed, _ready IS written. + ensure_scope_ready(scope_id, &scope_dir, tmp.path()).unwrap(); + assert!( + scope_is_ready(&scope_dir), + "_ready must be written on successful retry" + ); + } } diff --git a/desktop/src-tauri/src/migration.rs b/desktop/src-tauri/src/migration.rs index 96c4057741..5a4ed7bf6c 100644 --- a/desktop/src-tauri/src/migration.rs +++ b/desktop/src-tauri/src/migration.rs @@ -166,29 +166,10 @@ fn run_boot_migrations_inner(app: &tauri::AppHandle, reset_completed: bool) { crate::managed_agents::migrate_agent_keys_to_dev_service(app); } migrate_persona_provider_to_runtime(app); - reconcile_legacy_command_names(app); - // Fold personas.json into the unified store HERE: after the JSON-level - // personas.json migrations above (which must see the legacy file), and - // before every consumer of the load/save_personas shims below — - // sync_team_personas would otherwise operate on an empty definition set. - // Post-fold readers of the runtime map (`load_persona_runtimes`) fall - // back to the unified store's definitions. - fold_personas_into_agent_store(app); - // Clean the legacy baked team-instructions suffix out of stored prompts - // AFTER the fold (so definitions lifted out of personas.json are cleaned in - // the same boot) and BEFORE backfill_standalone_agents (so a manufactured - // definition never snapshots a suffix this strips). - 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. - backfill_standalone_agents(app); - detach_directory_backed_teams(app); - reconcile_provider_mcp_commands(app); - reconcile_databricks_v1_to_v2(app); - materialize_agent_runtimes(app); + // Definition-touching migrations (fold, strip, backfill, etc.) are NOT + // run here. They run inside the per-scope initialization pipeline + // (`scope_init::run_scoped_migrations`) after staged adoption so every + // scope sees exactly the migrations appropriate to its data. } /// Copy one-time app state from the legacy app identifier directory to @@ -1365,17 +1346,12 @@ pub fn migrate_persona_provider_to_runtime(app: &tauri::AppHandle) { } rename_provider_to_runtime_in_personas(&path); } -mod materialize; -pub use materialize::materialize_agent_runtimes; mod fold; -pub use fold::fold_personas_into_agent_store; +mod materialize; use fold::load_persona_runtimes; mod backfill; -pub use backfill::backfill_standalone_agents; mod detach; -pub use detach::detach_directory_backed_teams; mod team_suffix; -pub use team_suffix::strip_baked_team_instructions; include!("migration_scope.rs");