Skip to main content

trusty_code/workstreams/
store.rs

1//! On-disk JSON persistence + boot reconciliation for workstream records
2//! (DOC-48 §3).
3//!
4//! Why: the daemon must survive restarts without losing track of which
5//! workstreams it owns, or silently changing which one is active
6//! (§3.2: "A daemon restart never silently changes which workstream is
7//! active"). A single flat JSON file with an atomic temp+rename write gives
8//! crash-safe persistence without a database dependency — mirroring
9//! `trusty_mpm::session_manager::store::SessionStore`'s proven pattern
10//! (fingerprint-gated reload, atomic write, structured errors), adapted to
11//! this spec's flat-array-plus-pointer shape (§3.1) instead of a keyed map.
12//! What: [`StoreError`] (structured failure surface), [`ReconcileOutcome`]
13//! (what boot reconciliation did), and [`WorkstreamStore`] — load/save,
14//! create/get/list, the low-level `set_active` persistence primitive (NOT
15//! the future `workstream.activate` RPC verb — see its docs), and
16//! [`WorkstreamStore::reconcile_on_boot`] (§3.3: non-destructive, restores
17//! the active pointer or clears it if the target vanished).
18//! Test: `store_tests`.
19
20use std::collections::HashSet;
21use std::path::{Path, PathBuf};
22use std::time::SystemTime;
23
24use serde::{Deserialize, Serialize};
25use thiserror::Error;
26use tokio::fs;
27use tracing::debug;
28
29use super::model::{Workstream, WorkstreamId};
30use super::path::store_path;
31use crate::binding::ProjectBinding;
32
33/// The `version` field stamped into every store file (§3.1).
34pub const STORE_VERSION: &str = "1.0";
35
36/// Errors that can arise from store I/O or serialization.
37///
38/// Why: callers (the daemon boot path, future RPC handlers) need structured
39/// errors they can pattern-match rather than opaque strings.
40/// What: one variant per failure mode.
41/// Test: `store_tests::load_returns_error_on_corrupt_file`,
42/// `store_tests::get_missing_id_returns_not_found`.
43#[derive(Debug, Error)]
44pub enum StoreError {
45    /// An I/O operation on the backing file failed.
46    #[error("workstream store I/O error: {0}")]
47    Io(#[from] std::io::Error),
48    /// JSON serialization or deserialization failed.
49    #[error("workstream store serialization error: {0}")]
50    Serialize(String),
51    /// The requested workstream id was not found in the store.
52    #[error("workstream not found: {0}")]
53    NotFound(String),
54}
55
56/// Typed failure surface for [`WorkstreamStore::bind_session`] (issue
57/// #3298).
58///
59/// Why: a SEPARATE enum from [`StoreError`] rather than two new variants on
60/// it — `StoreError` already has non-exhaustive `match`es at existing call
61/// sites outside this ticket's file ownership (`workstreams::sse`'s own
62/// `map_store_err`, owned by the concurrent sibling ticket #3299), which
63/// widening `StoreError` would silently break. `BindError::Store` wraps
64/// every other [`StoreError`] variant unchanged.
65/// What: [`Self::NotFound`] — the target workstream does not exist.
66/// [`Self::Closed`] — DOC-48 §4.1/§4.4: "If a workstream is closed, new
67/// sessions may not bind to it". [`Self::AlreadyBound`] — DOC-48 §2: a
68/// session appears in at most one workstream's `session_ids`; this session
69/// id is already bound to a DIFFERENT workstream.
70/// Test: `store_tests::bind_session_rejects_unknown_workstream`,
71/// `store_tests::bind_session_rejects_closed_workstream`,
72/// `store_tests::bind_session_rejects_double_binding_to_different_workstream`.
73#[derive(Debug, Error)]
74pub enum BindError {
75    #[error("workstream not found: {0}")]
76    NotFound(String),
77    #[error("workstream is closed: {0}")]
78    Closed(String),
79    #[error("session already bound to another workstream: {0}")]
80    AlreadyBound(String),
81    #[error(transparent)]
82    Store(#[from] StoreError),
83}
84
85/// The versioned, on-disk JSON shape (§3.1): `version`, `active_workstream_id`,
86/// and a flat `workstreams` array — NOT a file-per-record or a keyed map.
87#[derive(Debug, Serialize, Deserialize)]
88struct StoredData {
89    version: String,
90    #[serde(default)]
91    active_workstream_id: Option<WorkstreamId>,
92    #[serde(default)]
93    workstreams: Vec<Workstream>,
94}
95
96impl Default for StoredData {
97    fn default() -> Self {
98        Self {
99            version: STORE_VERSION.to_string(),
100            active_workstream_id: None,
101            workstreams: Vec::new(),
102        }
103    }
104}
105
106/// A cheap freshness fingerprint for the backing file (mirrors
107/// `SessionStore`'s `FileSig`: mtime alone is insufficient on filesystems
108/// with coarse mtime resolution, so pairing it with byte length catches a
109/// same-second write that changed the file size).
110#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
111struct FileSig {
112    mtime: Option<SystemTime>,
113    len: u64,
114}
115
116/// What a boot-time reconciliation pass (§3.3) observed and did.
117///
118/// Why: the daemon boot path needs to log/report what reconciliation found
119/// without re-deriving it from before/after store snapshots.
120/// What: how many workstream records were loaded, the active id restored (if
121/// any), whether a stale pointer (referencing a now-nonexistent workstream)
122/// was cleared, and how many dangling `session_ids` were pruned across all
123/// records (#4579).
124/// Test: `store_tests::reconcile_restores_active_pointer`,
125/// `store_tests::reconcile_clears_active_when_target_missing`,
126/// `store_tests::reconcile_prunes_dangling_session_ids`.
127#[derive(Debug, Clone, Default, PartialEq, Eq)]
128pub struct ReconcileOutcome {
129    pub workstream_count: usize,
130    pub active_restored: Option<WorkstreamId>,
131    pub active_cleared: bool,
132    /// #4579: total count of `session_ids` entries dropped on boot because no
133    /// matching session is present in the (in-memory) `SessionRegistry`.
134    pub sessions_pruned: usize,
135}
136
137/// Async, file-backed store for [`Workstream`] records (DOC-48 §3).
138///
139/// Why: gives the daemon crash-safe persistence with restart-time
140/// reconciliation, matching the exact atomic-write + fingerprint-reload
141/// contract `SessionStore` already proved out for a sibling harness.
142/// What: holds the in-memory [`StoredData`], the backing file path, and the
143/// last-observed [`FileSig`] so a read can detect an external write (e.g. a
144/// second daemon process, or a test writing the file directly) and reload
145/// before answering.
146///
147/// **Concurrency model:** `create`/`set_active`/`reconcile_on_boot` are
148/// read-modify-write cycles (reload → mutate `self.data` → `save`) with NO
149/// cross-process lock — unlike
150/// [`trusty_agents_common::workstreams::WorkstreamLedger`], which at least
151/// serializes concurrent *threads within one process* behind an in-process
152/// `Mutex`, this store doesn't even do that; `&mut self` on every mutating
153/// method is the only serialization, so it is safe only for a single
154/// `WorkstreamStore` handle used from one task at a time. Two *processes*
155/// racing a read-modify-write on the same file can still lose an update: the
156/// last writer's atomic `rename` always leaves a whole, parseable file
157/// (never a torn one), but an interleaved writer can silently overwrite the
158/// other's change with a stale in-memory copy. This is inert today because
159/// DOC-48's architecture binds exactly one daemon process to one
160/// `ProjectBinding` (§2.3), and that daemon is the store's only writer; it
161/// becomes a real constraint only if a future caller opens a second
162/// `WorkstreamStore` over the same file from another process — such a
163/// caller must route writes through the owning daemon instead of writing
164/// directly, mirroring `WorkstreamLedger`'s documented callers-must-route-
165/// through-one-process caveat.
166/// Test: `store_tests::store_load_save_round_trip`,
167/// `store_tests::store_reload_picks_up_external_write`.
168#[derive(Debug)]
169pub struct WorkstreamStore {
170    data: StoredData,
171    path: PathBuf,
172    last_sig: Option<FileSig>,
173}
174
175impl WorkstreamStore {
176    /// Load (or create) the store at an explicit file path.
177    ///
178    /// Why: the filename is derived from the daemon's `ProjectBinding`
179    /// (§3.1), not a fixed name under a directory — so this takes the full
180    /// resolved path rather than a directory, unlike `SessionStore::load`.
181    /// What: reads `path` if it exists; returns a fresh default store
182    /// (`version` stamped, empty `workstreams`, no active pointer) if the
183    /// file is absent. Propagates I/O and JSON errors — a CORRUPT file is
184    /// never silently treated as empty (see [`Self::read_file`]).
185    /// Test: `store_tests::store_load_save_round_trip`,
186    /// `store_tests::load_returns_error_on_corrupt_file`.
187    pub async fn load(path: impl Into<PathBuf>) -> Result<Self, StoreError> {
188        let path = path.into();
189        let (data, last_sig) = Self::read_file(&path).await?;
190        Ok(Self {
191            data,
192            path,
193            last_sig,
194        })
195    }
196
197    /// Load the store for a daemon's project binding, deriving the filename
198    /// per §3.1.
199    ///
200    /// Why: the entry point a daemon boot path (or a test standing in for
201    /// one) calls — it never assembles the filename itself.
202    /// What: `Self::load(store_path(data_dir, binding))`.
203    /// Test: `store_tests::store_load_for_binding_derives_filename`.
204    pub async fn load_for_binding(
205        data_dir: &Path,
206        binding: &ProjectBinding,
207    ) -> Result<Self, StoreError> {
208        Self::load(store_path(data_dir, binding)).await
209    }
210
211    async fn sig_of(path: &Path) -> Option<FileSig> {
212        let meta = fs::metadata(path).await.ok()?;
213        Some(FileSig {
214            mtime: meta.modified().ok(),
215            len: meta.len(),
216        })
217    }
218
219    /// Read and parse the backing file, returning the data and its signature.
220    ///
221    /// Why: a corrupt (malformed/truncated) file must surface as a loud
222    /// error, not silently reset to an empty store — that would look like
223    /// every workstream the user had was deleted (violates AC-6.1's
224    /// non-destructive spirit at the read layer too).
225    /// What: file absent -> `(default, None)`; file present and parseable ->
226    /// `(data, Some(sig))`; file present and unparseable -> propagates
227    /// `StoreError::Serialize`. The signature is captured AFTER the read
228    /// (closes the same TOCTOU window `SessionStore` documents).
229    /// Test: `store_tests::load_returns_error_on_corrupt_file`.
230    async fn read_file(path: &Path) -> Result<(StoredData, Option<FileSig>), StoreError> {
231        match fs::read_to_string(path).await {
232            Ok(raw) => {
233                let data = serde_json::from_str::<StoredData>(&raw)
234                    .map_err(|e| StoreError::Serialize(e.to_string()))?;
235                let sig = Self::sig_of(path).await.unwrap_or_default();
236                Ok((data, Some(sig)))
237            }
238            Err(_) => {
239                debug!(path = %path.display(), "no workstream store file found; starting fresh");
240                Ok((StoredData::default(), None))
241            }
242        }
243    }
244
245    /// Reload the in-memory state from disk if the backing file changed.
246    ///
247    /// Why: mirrors `SessionStore::reload_if_changed` — another process (or,
248    /// in tests, a second store handle) may have written the shared file
249    /// since this handle last touched it.
250    /// What: cheap no-op when the (mtime, len) fingerprint is unchanged;
251    /// otherwise re-reads and replaces the in-memory data + signature.
252    /// Test: `store_tests::store_reload_picks_up_external_write`,
253    /// `store_tests::store_reload_noop_when_unchanged`.
254    pub async fn reload_if_changed(&mut self) -> Result<(), StoreError> {
255        let current = Self::sig_of(&self.path).await;
256        let unchanged = matches!((current, self.last_sig), (Some(a), Some(b)) if a == b);
257        if unchanged {
258            return Ok(());
259        }
260        let (data, sig) = Self::read_file(&self.path).await?;
261        self.data = data;
262        self.last_sig = sig;
263        debug!(path = %self.path.display(), "workstream store reloaded after external change");
264        Ok(())
265    }
266
267    /// Persist the current in-memory state to disk atomically.
268    ///
269    /// Why: §3.1 requires "no partial writes even if the daemon crashes
270    /// mid-write" — a plain `fs::write` truncates then rewrites, exposing a
271    /// half-written file to a concurrent reader.
272    /// What: serializes to pretty JSON, writes a sibling `.json.tmp`, then
273    /// renames it over the real path (atomic swap on POSIX); records the
274    /// resulting fingerprint so a subsequent `reload_if_changed` treats this
275    /// write as "unchanged".
276    /// Test: exercised by every mutating test; `store_tests::store_load_save_round_trip`
277    /// verifies the round-trip.
278    pub async fn save(&mut self) -> Result<(), StoreError> {
279        if let Some(parent) = self.path.parent() {
280            fs::create_dir_all(parent).await?;
281        }
282        let json = serde_json::to_string_pretty(&self.data)
283            .map_err(|e| StoreError::Serialize(e.to_string()))?;
284        let tmp = self.path.with_extension("json.tmp");
285        fs::write(&tmp, json).await?;
286        fs::rename(&tmp, &self.path).await?;
287        self.last_sig = Self::sig_of(&self.path).await;
288        debug!(path = %self.path.display(), "workstream store saved");
289        Ok(())
290    }
291
292    /// Create a new workstream and persist it.
293    ///
294    /// Why: the one creation path this ticket owns (the `workstream.create`
295    /// RPC verb itself is #3295 scope; this is the persistence primitive it
296    /// will call).
297    /// What: reloads first (so a concurrent write is not clobbered),
298    /// appends a fresh [`Workstream::new`], saves, and returns its id.
299    /// Test: `store_tests::create_persists_and_is_gettable`.
300    pub async fn create(&mut self, name: impl Into<String>) -> Result<WorkstreamId, StoreError> {
301        self.reload_if_changed().await?;
302        let ws = Workstream::new(name);
303        let id = ws.id;
304        self.data.workstreams.push(ws);
305        self.save().await?;
306        Ok(id)
307    }
308
309    /// Look up a workstream by id, reloading first.
310    ///
311    /// Test: `store_tests::create_persists_and_is_gettable`,
312    /// `store_tests::get_missing_id_returns_not_found`.
313    pub async fn get(&mut self, id: WorkstreamId) -> Result<Workstream, StoreError> {
314        self.reload_if_changed().await?;
315        self.data
316            .workstreams
317            .iter()
318            .find(|w| w.id == id)
319            .cloned()
320            .ok_or_else(|| StoreError::NotFound(id.to_string()))
321    }
322
323    /// Return every stored workstream record, reloading first.
324    ///
325    /// Why: state is computed, not stored — callers pair each record with
326    /// [`Workstream::state`] and [`Self::active_workstream_id`] themselves.
327    /// Test: `store_tests::list_returns_all_records`.
328    pub async fn list(&mut self) -> Result<Vec<Workstream>, StoreError> {
329        self.reload_if_changed().await?;
330        Ok(self.data.workstreams.clone())
331    }
332
333    /// Return the persisted active-workstream pointer, reloading first.
334    ///
335    /// Test: `store_tests::set_active_persists_pointer`.
336    pub async fn active_workstream_id(&mut self) -> Result<Option<WorkstreamId>, StoreError> {
337        self.reload_if_changed().await?;
338        Ok(self.data.active_workstream_id)
339    }
340
341    /// Low-level persistence primitive: set (or clear) the active-workstream
342    /// pointer and persist.
343    ///
344    /// Why: this is NOT the future `workstream.activate{id, force}` RPC verb
345    /// (#3294) — that verb layers conflict detection (`ActiveConflict` when
346    /// another workstream is already active) and the prior-workstream
347    /// deactivation side effect on top. This method is the mechanical
348    /// "write the pointer" primitive that verb — and this ticket's own boot
349    /// reconciliation — build on.
350    /// What: validates that `Some(id)` refers to an existing record (a
351    /// dangling pointer must never be written deliberately — only
352    /// reconciliation clears an already-dangling one), then persists.
353    /// Test: `store_tests::set_active_persists_pointer`,
354    /// `store_tests::set_active_rejects_unknown_id`.
355    pub async fn set_active(&mut self, id: Option<WorkstreamId>) -> Result<(), StoreError> {
356        self.reload_if_changed().await?;
357        if let Some(id) = id
358            && !self.data.workstreams.iter().any(|w| w.id == id)
359        {
360            return Err(StoreError::NotFound(id.to_string()));
361        }
362        self.data.active_workstream_id = id;
363        self.save().await
364    }
365
366    /// Irreversibly close a workstream, auto-deactivating it if it is the
367    /// active one (DOC-48 §4.4, [`SPEC-WS-04~draft`](docs/specs/DOC-48-tcode-workstreams.md#SPEC-WS-04~draft)).
368    ///
369    /// Why: the persistence primitive `workstream.close` (#3295) calls. §4.4
370    /// is explicit that "if the closed workstream is the active one, it is
371    /// automatically deactivated (sets `active_workstream_id` to `null`)" —
372    /// closing must never leave a dangling active pointer referencing a
373    /// closed workstream, which would otherwise let a closed workstream keep
374    /// reporting `Active` state forever (model precedence: the pointer beats
375    /// the closed flag, see [`Workstream::state`]'s docs).
376    /// What: reloads first, marks the record closed via
377    /// [`Workstream::mark_closed`] (idempotent — closing twice is not an
378    /// error), clears `active_workstream_id` if it pointed at `id`, persists,
379    /// and returns the updated record. `NotFound` if `id` does not exist.
380    /// Test: `store_tests::close_marks_closed_and_persists`,
381    /// `store_tests::close_active_workstream_clears_active_pointer`,
382    /// `store_tests::close_missing_id_returns_not_found`,
383    /// `store_tests::close_is_idempotent`.
384    pub async fn close(&mut self, id: WorkstreamId) -> Result<Workstream, StoreError> {
385        self.reload_if_changed().await?;
386        {
387            let ws = self
388                .data
389                .workstreams
390                .iter_mut()
391                .find(|w| w.id == id)
392                .ok_or_else(|| StoreError::NotFound(id.to_string()))?;
393            ws.mark_closed();
394        }
395        if self.data.active_workstream_id == Some(id) {
396            self.data.active_workstream_id = None;
397        }
398        self.save().await?;
399        self.data
400            .workstreams
401            .iter()
402            .find(|w| w.id == id)
403            .cloned()
404            .ok_or_else(|| StoreError::NotFound(id.to_string()))
405    }
406
407    /// Rename a workstream (DOC-48 §5.1 `workstream.rename`, Phase C —
408    /// issue #3300).
409    ///
410    /// Why: the persistence primitive `workstream.rename` calls. The domain
411    /// model has always documented `name` as mutable ("future rename
412    /// support, Phase C" — [`Workstream`]'s own doc comment); this is that
413    /// support landing. Renaming a closed workstream is allowed — closure
414    /// only rejects new session bindings (§4.4), it says nothing about the
415    /// label, and forbidding it would leave a typo permanently unfixable.
416    /// What: reloads first, overwrites `name` and calls
417    /// [`Workstream::touch`] to refresh `updated_at`, persists, and returns
418    /// the updated record. `NotFound` if `id` does not exist.
419    /// Test: `store_tests::rename_updates_name_and_persists`,
420    /// `store_tests::rename_missing_id_returns_not_found`,
421    /// `store_tests::rename_closed_workstream_succeeds`.
422    pub async fn rename(
423        &mut self,
424        id: WorkstreamId,
425        name: impl Into<String>,
426    ) -> Result<Workstream, StoreError> {
427        self.reload_if_changed().await?;
428        {
429            let ws = self
430                .data
431                .workstreams
432                .iter_mut()
433                .find(|w| w.id == id)
434                .ok_or_else(|| StoreError::NotFound(id.to_string()))?;
435            ws.name = name.into();
436            ws.touch();
437        }
438        self.save().await?;
439        self.data
440            .workstreams
441            .iter()
442            .find(|w| w.id == id)
443            .cloned()
444            .ok_or_else(|| StoreError::NotFound(id.to_string()))
445    }
446
447    /// Bind `session_id` to `workstream_id`, persisting the append (DOC-48
448    /// §4.1, issue #3298).
449    ///
450    /// Why: the persistence primitive `session::protocol::create` and
451    /// `task::protocol::task_run` call once they have resolved the EFFECTIVE
452    /// target workstream (either the caller's explicit `workstream_id` or
453    /// §4.2's ambient active-workstream default) for a freshly minted
454    /// session — mirrors [`Self::set_active`]'s role as the low-level
455    /// "write it and persist" primitive beneath the higher-level resolution
456    /// logic those call sites own.
457    /// What: reloads first. Idempotent no-op success if `session_id` is
458    /// already bound to `workstream_id` itself (a caller resolving the SAME
459    /// binding twice — e.g. a retried request — must not error). Otherwise:
460    /// `AlreadyBound` if `session_id` is bound to a DIFFERENT workstream
461    /// (§2's at-most-one-workstream invariant); `NotFound` if `workstream_id`
462    /// names no record; `Closed` if the target workstream is closed (§4.1/
463    /// §4.4). On success, appends `session_id` to the target's `session_ids`
464    /// (append-only, §2.1), touches it, and persists.
465    /// Test: `store_tests::bind_session_appends_and_persists`,
466    /// `store_tests::bind_session_is_idempotent_for_same_workstream`,
467    /// `store_tests::bind_session_rejects_double_binding_to_different_workstream`,
468    /// `store_tests::bind_session_rejects_unknown_workstream`,
469    /// `store_tests::bind_session_rejects_closed_workstream`.
470    pub async fn bind_session(
471        &mut self,
472        workstream_id: WorkstreamId,
473        session_id: &str,
474    ) -> Result<(), BindError> {
475        self.reload_if_changed().await?;
476        if let Some(existing) = self
477            .data
478            .workstreams
479            .iter()
480            .find(|w| w.session_ids.iter().any(|s| s == session_id))
481        {
482            return if existing.id == workstream_id {
483                Ok(())
484            } else {
485                Err(BindError::AlreadyBound(session_id.to_string()))
486            };
487        }
488        let ws = self
489            .data
490            .workstreams
491            .iter_mut()
492            .find(|w| w.id == workstream_id)
493            .ok_or_else(|| BindError::NotFound(workstream_id.to_string()))?;
494        if ws.is_closed() {
495            return Err(BindError::Closed(workstream_id.to_string()));
496        }
497        ws.session_ids.push(session_id.to_string());
498        ws.touch();
499        self.save().await?;
500        Ok(())
501    }
502
503    /// Boot-time reconciliation (DOC-48 §3.3, AC-1.4, AC-6.1, AC-6.2; #4579).
504    ///
505    /// Why: a daemon restart must never silently change which workstream is
506    /// active (§3.2), and must never delete a workstream record (§3.3,
507    /// AC-6.1) — session liveness plays NO part in the active/idle STATE a
508    /// record reports (§3.3: "does NOT determine active/idle state"). #4579:
509    /// but the `SessionRegistry` is in-memory only, so after a restart every
510    /// persisted `session_id` names a session that no longer exists. Left in
511    /// place those references dangle forever — the workstream event
512    /// aggregation layer (§3, "fan-outs over the workstream's bound
513    /// `session_ids`") would keep resolving them against an empty registry.
514    /// Per owner ruling (2026-08-31, PRUNE ON BOOT), reconciliation drops each
515    /// `session_id` absent from the live registry. This prunes stale entries
516    /// from a record's list; it never removes a record, and never changes the
517    /// active/idle state a record reports — so it is still non-destructive in
518    /// the sense §3.3/AC-6.1 require. It is the one exception to §2.1's
519    /// append-only `session_ids`, scoped to boot only.
520    /// What: reloads from disk, then (1) if the persisted active pointer still
521    /// references an existing workstream, leaves it untouched (restored); if
522    /// it references a workstream that no longer exists, clears it to `None`;
523    /// if there was no pointer, does nothing. (2) Retains, in every record's
524    /// `session_ids`, only ids present in `live_session_ids`; a live id is
525    /// always kept. Persists once iff anything changed. Every workstream
526    /// record is preserved either way — this method never removes an entry
527    /// from `workstreams`. `updated_at` is deliberately NOT touched by a
528    /// prune, so a restart does not silently reorder records by recency.
529    /// Test: `store_tests::reconcile_restores_active_pointer`,
530    /// `store_tests::reconcile_clears_active_when_target_missing`,
531    /// `store_tests::reconcile_is_noop_with_no_active_pointer`,
532    /// `store_tests::reconcile_prunes_dangling_session_ids`,
533    /// `store_tests::reconcile_keeps_live_session_ids`.
534    pub async fn reconcile_on_boot(
535        &mut self,
536        live_session_ids: &HashSet<String>,
537    ) -> Result<ReconcileOutcome, StoreError> {
538        self.reload_if_changed().await?;
539        let mut outcome = ReconcileOutcome {
540            workstream_count: self.data.workstreams.len(),
541            ..Default::default()
542        };
543        let mut changed = false;
544        match self.data.active_workstream_id {
545            Some(id) if self.data.workstreams.iter().any(|w| w.id == id) => {
546                outcome.active_restored = Some(id);
547            }
548            Some(_) => {
549                self.data.active_workstream_id = None;
550                outcome.active_cleared = true;
551                changed = true;
552            }
553            None => {}
554        }
555        // #4579: prune session_ids whose session is gone from the in-memory
556        // registry, keeping every live one.
557        for ws in &mut self.data.workstreams {
558            let before = ws.session_ids.len();
559            ws.session_ids.retain(|sid| live_session_ids.contains(sid));
560            outcome.sessions_pruned += before - ws.session_ids.len();
561        }
562        if outcome.sessions_pruned > 0 {
563            changed = true;
564        }
565        if changed {
566            self.save().await?;
567        }
568        Ok(outcome)
569    }
570}
571
572#[cfg(test)]
573#[path = "store_tests.rs"]
574mod store_tests;