Skip to main content

trusty_code/workstreams/
model.rs

1//! Workstream domain types (DOC-48 §2).
2//!
3//! Why: a workstream needs a canonical, serializable shape so it can survive
4//! daemon restarts (persisted to the flat JSON store, §3) and be returned
5//! over the future RPC/REST surface (#3295) without ambiguity. State is
6//! deliberately NOT a stored field — §2.2/§3.2 require it to be *computed*
7//! from the store's `active_workstream_id` pointer on every read, so an
8//! operator can never desync the persisted state from the pointer that
9//! actually governs it.
10//! What: [`WorkstreamId`] (a UUID newtype, mirrors
11//! `trusty_mpm::session_manager::ManagedSessionId`'s pattern), [`WorkstreamState`]
12//! (the computed `active | idle | closed` enum), and [`Workstream`] (the
13//! persisted record: id, name, session_ids, timestamps, metadata — §2.1).
14//! Test: `model_tests`.
15
16use std::fmt;
17
18use chrono::{DateTime, Utc};
19use serde::{Deserialize, Serialize};
20use serde_json::{Map, Value};
21use uuid::Uuid;
22
23/// Opaque identifier for a workstream.
24///
25/// Why: a newtype over [`Uuid`] prevents accidental confusion with other
26/// UUID-typed identifiers (e.g. a session id) at the type level.
27/// What: wraps `uuid::Uuid`; implements `Display` and serde derive for
28/// transparent JSON serialization as a plain UUID string.
29/// Test: `model_tests::workstream_id_round_trip`.
30#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
31pub struct WorkstreamId(pub Uuid);
32
33impl WorkstreamId {
34    /// Generate a new random workstream id.
35    ///
36    /// Why: every new workstream needs a stable, globally unique identifier
37    /// assigned at creation time (§2.1: "Generated on creation").
38    /// What: wraps `Uuid::new_v4()`.
39    /// Test: used throughout `store_tests`.
40    pub fn new() -> Self {
41        Self(Uuid::new_v4())
42    }
43
44    /// Return the inner UUID value.
45    pub fn as_uuid(&self) -> &Uuid {
46        &self.0
47    }
48}
49
50impl Default for WorkstreamId {
51    fn default() -> Self {
52        Self::new()
53    }
54}
55
56impl fmt::Display for WorkstreamId {
57    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
58        self.0.fmt(f)
59    }
60}
61
62impl From<Uuid> for WorkstreamId {
63    fn from(uuid: Uuid) -> Self {
64        Self(uuid)
65    }
66}
67
68/// Computed lifecycle state of a [`Workstream`] (DOC-48 §2.2).
69///
70/// Why: the operator never sets this directly — it is inferred fresh on
71/// every `get`/`list` from the store's `active_workstream_id` pointer
72/// (§3.2), so state can never drift out of sync with the pointer that
73/// actually governs which workstream is active.
74/// What: `Active` (its id equals the persisted active pointer, regardless of
75/// session liveness), `Idle` (default, not active, not closed), `Closed`
76/// (marked closed via the reserved `metadata["closed"]` flag — see
77/// [`Workstream::is_closed`]; the `workstream.close` RPC verb that sets this
78/// flag is #3294/#3295 scope, not this ticket's).
79/// Test: `model_tests::state_is_active_iff_pointer_matches`,
80/// `model_tests::state_is_closed_when_metadata_flag_set`.
81#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
82#[serde(rename_all = "snake_case")]
83pub enum WorkstreamState {
84    Active,
85    Idle,
86    Closed,
87}
88
89impl fmt::Display for WorkstreamState {
90    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
91        let s = match self {
92            Self::Active => "active",
93            Self::Idle => "idle",
94            Self::Closed => "closed",
95        };
96        write!(f, "{s}")
97    }
98}
99
100/// The reserved `metadata` key marking a workstream as closed (§3.2: "a
101/// metadata flag; see future Phase C"). Reserved here so the eventual
102/// `workstream.close` verb (#3294/#3295) and this state-inference logic
103/// agree on the wire shape without either side inventing its own key.
104const CLOSED_METADATA_KEY: &str = "closed";
105
106/// A durable named grouping of sessions, scoped to a single daemon instance
107/// (DOC-48 §2.1).
108///
109/// Why: the domain object that finally gives a workstream daemon-owned
110/// identity (DOC-48 §1.1) — previously the in-memory `SessionRegistry` was
111/// the sole record and a restart discarded it.
112/// What: `id` is immutable; `name` and `metadata` are mutable; `session_ids`
113/// is append-only (never removed, per §2.1); `created_at` is immutable,
114/// `updated_at` reflects last activity. `state` is deliberately NOT a field —
115/// call [`Self::state`] with the store's active pointer to compute it.
116/// Test: `model_tests::workstream_serde_round_trip`,
117/// `model_tests::new_workstream_starts_idle_with_no_sessions`.
118#[derive(Debug, Clone, Serialize, Deserialize)]
119pub struct Workstream {
120    /// Unique, immutable identifier assigned at creation.
121    pub id: WorkstreamId,
122    /// Human-readable name; mutable (future rename support, Phase C).
123    pub name: String,
124    /// Sessions bound to this workstream. Append-only — never remove an
125    /// entry (§2.1).
126    #[serde(default)]
127    pub session_ids: Vec<String>,
128    /// When the workstream was created (first `workstream.create` call).
129    pub created_at: DateTime<Utc>,
130    /// Last activity: state inferred, name changed, session attached,
131    /// activated/deactivated, or closed.
132    pub updated_at: DateTime<Utc>,
133    /// Reserved for future use (tags, description, the `closed` flag). Empty
134    /// by default; `#[serde(default)]` keeps pre-existing records without
135    /// this key deserializable.
136    #[serde(default)]
137    pub metadata: Map<String, Value>,
138}
139
140impl Workstream {
141    /// Create a new workstream with the given name, no bound sessions, and
142    /// empty metadata.
143    ///
144    /// Why: the one constructor every creation path (the future
145    /// `workstream.create` RPC, and this ticket's store/tests) funnels
146    /// through, so `id`/`created_at`/`updated_at` are never hand-assembled
147    /// inconsistently.
148    /// What: assigns a fresh [`WorkstreamId`], stamps `created_at` ==
149    /// `updated_at` == now, and starts with empty `session_ids`/`metadata`.
150    /// Test: `model_tests::new_workstream_starts_idle_with_no_sessions`.
151    pub fn new(name: impl Into<String>) -> Self {
152        let now = Utc::now();
153        Self {
154            id: WorkstreamId::new(),
155            name: name.into(),
156            session_ids: Vec::new(),
157            created_at: now,
158            updated_at: now,
159            metadata: Map::new(),
160        }
161    }
162
163    /// Whether this workstream is marked closed via the reserved metadata
164    /// flag (§3.2).
165    ///
166    /// Why: closure itself (`workstream.close`, #3294/#3295) is out of this
167    /// ticket's scope, but the domain model must already agree on where that
168    /// future verb will record its effect, so state inference is correct
169    /// from day one rather than needing a schema migration later.
170    /// What: `true` iff `metadata["closed"]` is present and `== true`.
171    /// Test: `model_tests::state_is_closed_when_metadata_flag_set`.
172    pub fn is_closed(&self) -> bool {
173        self.metadata
174            .get(CLOSED_METADATA_KEY)
175            .and_then(Value::as_bool)
176            .unwrap_or(false)
177    }
178
179    /// Compute this workstream's state given the store's persisted active
180    /// pointer (DOC-48 §2.2/§3.2).
181    ///
182    /// Why: state must never be read from a stored field — the pointer is
183    /// the single source of truth for which workstream is active, and
184    /// session liveness never gates this (§3.3: "it does NOT determine
185    /// active/idle state").
186    /// What: `Active` iff `active_workstream_id == Some(self.id)` (checked
187    /// FIRST, matching §3.2's literal ordering); otherwise `Closed` if
188    /// [`Self::is_closed`], else `Idle`.
189    /// Test: `model_tests::state_is_active_iff_pointer_matches`,
190    /// `model_tests::state_is_closed_when_metadata_flag_set`,
191    /// `model_tests::state_defaults_to_idle`.
192    pub fn state(&self, active_workstream_id: Option<WorkstreamId>) -> WorkstreamState {
193        if active_workstream_id == Some(self.id) {
194            WorkstreamState::Active
195        } else if self.is_closed() {
196            WorkstreamState::Closed
197        } else {
198            WorkstreamState::Idle
199        }
200    }
201
202    /// Stamp `updated_at` to now.
203    ///
204    /// Why: every mutation the store performs on a record (rename, session
205    /// bind, activation change, close) must refresh liveness per §2.1's
206    /// `updated_at` semantics; centralising it here keeps every call site in
207    /// lock-step.
208    /// What: sets `updated_at = Utc::now()`.
209    /// Test: `model_tests::touch_updates_timestamp`.
210    pub fn touch(&mut self) {
211        self.updated_at = Utc::now();
212    }
213
214    /// Mark this workstream closed via the reserved metadata flag (DOC-48
215    /// §4.4, [`SPEC-WS-04~draft`](docs/specs/DOC-48-tcode-workstreams.md#SPEC-WS-04~draft)).
216    ///
217    /// Why: `workstream.close` (#3295) is the sole call site that flips a
218    /// workstream irreversible-closed; centralising the mutation here keeps
219    /// the reserved `metadata["closed"]` key private to this module rather
220    /// than leaking its literal string to the store/RPC layers. Idempotent —
221    /// closing an already-closed workstream re-sets the same flag and simply
222    /// refreshes `updated_at`, since the spec never requires re-close to
223    /// error.
224    /// What: sets `metadata["closed"] = true`, then calls [`Self::touch`].
225    /// Test: `model_tests::mark_closed_sets_flag_and_touches`.
226    pub fn mark_closed(&mut self) {
227        self.metadata
228            .insert(CLOSED_METADATA_KEY.to_string(), Value::Bool(true));
229        self.touch();
230    }
231}
232
233#[cfg(test)]
234#[path = "model_tests.rs"]
235mod model_tests;