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