Skip to main content

WorkstreamStore

Struct WorkstreamStore 

Source
pub struct WorkstreamStore { /* private fields */ }
Expand description

Async, file-backed store for Workstream records (DOC-48 §3).

Why: gives the daemon crash-safe persistence with restart-time reconciliation, matching the exact atomic-write + fingerprint-reload contract SessionStore already proved out for a sibling harness. What: holds the in-memory [StoredData], the backing file path, and the last-observed [FileSig] so a read can detect an external write (e.g. a second daemon process, or a test writing the file directly) and reload before answering.

Concurrency model: create/set_active/reconcile_on_boot are read-modify-write cycles (reload → mutate self.data → save) with NO cross-process lock — unlike trusty_agents_common::workstreams::WorkstreamLedger, which at least serializes concurrent threads within one process behind an in-process Mutex, this store doesn’t even do that; &mut self on every mutating method is the only serialization, so it is safe only for a single WorkstreamStore handle used from one task at a time. Two processes racing a read-modify-write on the same file can still lose an update: the last writer’s atomic rename always leaves a whole, parseable file (never a torn one), but an interleaved writer can silently overwrite the other’s change with a stale in-memory copy. This is inert today because DOC-48’s architecture binds exactly one daemon process to one ProjectBinding (§2.3), and that daemon is the store’s only writer; it becomes a real constraint only if a future caller opens a second WorkstreamStore over the same file from another process — such a caller must route writes through the owning daemon instead of writing directly, mirroring WorkstreamLedger’s documented callers-must-route- through-one-process caveat. Test: store_tests::store_load_save_round_trip, store_tests::store_reload_picks_up_external_write.

Implementations§

Source§

impl WorkstreamStore

Source

pub async fn load(path: impl Into<PathBuf>) -> Result<Self, StoreError>

Load (or create) the store at an explicit file path.

Why: the filename is derived from the daemon’s ProjectBinding (§3.1), not a fixed name under a directory — so this takes the full resolved path rather than a directory, unlike SessionStore::load. What: reads path if it exists; returns a fresh default store (version stamped, empty workstreams, no active pointer) if the file is absent. Propagates I/O and JSON errors — a CORRUPT file is never silently treated as empty (see Self::read_file). Test: store_tests::store_load_save_round_trip, store_tests::load_returns_error_on_corrupt_file.

Source

pub async fn load_for_binding( data_dir: &Path, binding: &ProjectBinding, ) -> Result<Self, StoreError>

Load the store for a daemon’s project binding, deriving the filename per §3.1.

Why: the entry point a daemon boot path (or a test standing in for one) calls — it never assembles the filename itself. What: Self::load(store_path(data_dir, binding)). Test: store_tests::store_load_for_binding_derives_filename.

Source

pub async fn reload_if_changed(&mut self) -> Result<(), StoreError>

Reload the in-memory state from disk if the backing file changed.

Why: mirrors SessionStore::reload_if_changed — another process (or, in tests, a second store handle) may have written the shared file since this handle last touched it. What: cheap no-op when the (mtime, len) fingerprint is unchanged; otherwise re-reads and replaces the in-memory data + signature. Test: store_tests::store_reload_picks_up_external_write, store_tests::store_reload_noop_when_unchanged.

Source

pub async fn save(&mut self) -> Result<(), StoreError>

Persist the current in-memory state to disk atomically.

Why: §3.1 requires “no partial writes even if the daemon crashes mid-write” — a plain fs::write truncates then rewrites, exposing a half-written file to a concurrent reader. What: serializes to pretty JSON, writes a sibling .json.tmp, then renames it over the real path (atomic swap on POSIX); records the resulting fingerprint so a subsequent reload_if_changed treats this write as “unchanged”. Test: exercised by every mutating test; store_tests::store_load_save_round_trip verifies the round-trip.

Source

pub async fn create( &mut self, name: impl Into<String>, ) -> Result<WorkstreamId, StoreError>

Create a new workstream and persist it.

Why: the one creation path this ticket owns (the workstream.create RPC verb itself is #3295 scope; this is the persistence primitive it will call). What: reloads first (so a concurrent write is not clobbered), appends a fresh Workstream::new, saves, and returns its id. Test: store_tests::create_persists_and_is_gettable.

Source

pub async fn get(&mut self, id: WorkstreamId) -> Result<Workstream, StoreError>

Look up a workstream by id, reloading first.

Test: store_tests::create_persists_and_is_gettable, store_tests::get_missing_id_returns_not_found.

Source

pub async fn list(&mut self) -> Result<Vec<Workstream>, StoreError>

Return every stored workstream record, reloading first.

Why: state is computed, not stored — callers pair each record with Workstream::state and Self::active_workstream_id themselves. Test: store_tests::list_returns_all_records.

Source

pub async fn active_workstream_id( &mut self, ) -> Result<Option<WorkstreamId>, StoreError>

Return the persisted active-workstream pointer, reloading first.

Test: store_tests::set_active_persists_pointer.

Source

pub async fn set_active( &mut self, id: Option<WorkstreamId>, ) -> Result<(), StoreError>

Low-level persistence primitive: set (or clear) the active-workstream pointer and persist.

Why: this is NOT the future workstream.activate{id, force} RPC verb (#3294) — that verb layers conflict detection (ActiveConflict when another workstream is already active) and the prior-workstream deactivation side effect on top. This method is the mechanical “write the pointer” primitive that verb — and this ticket’s own boot reconciliation — build on. What: validates that Some(id) refers to an existing record (a dangling pointer must never be written deliberately — only reconciliation clears an already-dangling one), then persists. Test: store_tests::set_active_persists_pointer, store_tests::set_active_rejects_unknown_id.

Source

pub async fn close( &mut self, id: WorkstreamId, ) -> Result<Workstream, StoreError>

Irreversibly close a workstream, auto-deactivating it if it is the active one (DOC-48 §4.4, SPEC-WS-04~draft).

Why: the persistence primitive workstream.close (#3295) calls. §4.4 is explicit that “if the closed workstream is the active one, it is automatically deactivated (sets active_workstream_id to null)” — closing must never leave a dangling active pointer referencing a closed workstream, which would otherwise let a closed workstream keep reporting Active state forever (model precedence: the pointer beats the closed flag, see Workstream::state’s docs). What: reloads first, marks the record closed via Workstream::mark_closed (idempotent — closing twice is not an error), clears active_workstream_id if it pointed at id, persists, and returns the updated record. NotFound if id does not exist. Test: store_tests::close_marks_closed_and_persists, store_tests::close_active_workstream_clears_active_pointer, store_tests::close_missing_id_returns_not_found, store_tests::close_is_idempotent.

Source

pub async fn rename( &mut self, id: WorkstreamId, name: impl Into<String>, ) -> Result<Workstream, StoreError>

Rename a workstream (DOC-48 §5.1 workstream.rename, Phase C — issue #3300).

Why: the persistence primitive workstream.rename calls. The domain model has always documented name as mutable (“future rename support, Phase C” — Workstream’s own doc comment); this is that support landing. Renaming a closed workstream is allowed — closure only rejects new session bindings (§4.4), it says nothing about the label, and forbidding it would leave a typo permanently unfixable. What: reloads first, overwrites name and calls Workstream::touch to refresh updated_at, persists, and returns the updated record. NotFound if id does not exist. Test: store_tests::rename_updates_name_and_persists, store_tests::rename_missing_id_returns_not_found, store_tests::rename_closed_workstream_succeeds.

Source

pub async fn bind_session( &mut self, workstream_id: WorkstreamId, session_id: &str, ) -> Result<(), BindError>

Bind session_id to workstream_id, persisting the append (DOC-48 §4.1, issue #3298).

Why: the persistence primitive session::protocol::create and task::protocol::task_run call once they have resolved the EFFECTIVE target workstream (either the caller’s explicit workstream_id or §4.2’s ambient active-workstream default) for a freshly minted session — mirrors Self::set_active’s role as the low-level “write it and persist” primitive beneath the higher-level resolution logic those call sites own. What: reloads first. Idempotent no-op success if session_id is already bound to workstream_id itself (a caller resolving the SAME binding twice — e.g. a retried request — must not error). Otherwise: AlreadyBound if session_id is bound to a DIFFERENT workstream (§2’s at-most-one-workstream invariant); NotFound if workstream_id names no record; Closed if the target workstream is closed (§4.1/ §4.4). On success, appends session_id to the target’s session_ids (append-only, §2.1), touches it, and persists. Test: store_tests::bind_session_appends_and_persists, store_tests::bind_session_is_idempotent_for_same_workstream, store_tests::bind_session_rejects_double_binding_to_different_workstream, store_tests::bind_session_rejects_unknown_workstream, store_tests::bind_session_rejects_closed_workstream.

Source

pub async fn reconcile_on_boot( &mut self, ) -> Result<ReconcileOutcome, StoreError>

Boot-time reconciliation (DOC-48 §3.3, AC-1.4, AC-6.1, AC-6.2).

Why: a daemon restart must never silently change which workstream is active (§3.2), and must never delete a workstream record (§3.3, AC-6.1) — session liveness plays NO part in this (§3.3: “does NOT determine active/idle state”). What: reloads from disk, then: if the persisted active pointer still references an existing workstream, leaves it untouched (restored); if it references a workstream that no longer exists, clears it to None and persists that single change; if there was no pointer, does nothing. Every workstream record is preserved either way — this method never removes an entry from workstreams. Test: store_tests::reconcile_restores_active_pointer, store_tests::reconcile_clears_active_when_target_missing, store_tests::reconcile_is_noop_with_no_active_pointer.

Trait Implementations§

Source§

impl Debug for WorkstreamStore

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<Unshared, Shared> IntoShared<Shared> for Unshared
where Shared: FromUnshared<Unshared>,

Source§

fn into_shared(self) -> Shared

Creates a shared type from an unshared type.
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more