Skip to main content

trusty_code/workstreams/
activation.rs

1//! Activation-lock exclusivity layer over [`WorkstreamStore`] (DOC-48 §6,
2//! issue #3294).
3//!
4//! # Spec References
5//!
6//! - [`SPEC-WS-04~draft`](docs/specs/DOC-48-tcode-workstreams.md#SPEC-WS-04~draft) §4.3
7//! - [`SPEC-WS-06~draft`](docs/specs/DOC-48-tcode-workstreams.md#SPEC-WS-06~draft)
8//!
9//! Why: [`WorkstreamStore::set_active`] is a bare "write the pointer"
10//! primitive — issue #3293's foundation deliberately left conflict detection
11//! and force-switch semantics for this ticket to build (see that method's
12//! own docs). The daemon-enforced singleton invariant (AC-3.1) needs a layer
13//! ABOVE the store that decides `ActiveConflict` vs. idempotent re-activation
14//! vs. force-switch, and reports which workstream was previously active so
15//! RPC/REST callers (and #3297's SSE `WorkstreamActivationChanged` producer)
16//! can react to the change.
17//!
18//! What: [`SharedWorkstreamStore`] (the `Arc<Mutex<...>>` handle every RPC
19//! handler closure clones — mirrors `crate::session::SessionRegistry`'s
20//! `Arc`-shared-state convention, except `WorkstreamStore`'s mutating methods
21//! take `&mut self`, so a `tokio::sync::Mutex` wrapper is required; `tokio`'s
22//! (not `std`'s) because every store operation is `async` file I/O and must
23//! not block the executor while held), [`ActivationError`] (the typed
24//! failure surface), [`ActivateOutcome`] (new + prior ids), and the two free
25//! functions [`activate`]/[`deactivate`] that implement DOC-48 §6.1's exact
26//! rules:
27//!   - `activate{id, force: false}` when `id` is ALREADY the active
28//!     workstream: succeeds (idempotent — re-activating yourself is not a
29//!     "switch" at all; §6.1's `ActiveConflict` only fires when ANOTHER
30//!     workstream is active).
31//!   - `activate{id, force: false}` when a DIFFERENT workstream is active:
32//!     `ActivationError::ActiveConflict(active_id)`.
33//!   - `activate{id, force: true}`: deactivates whichever workstream was
34//!     active (if any) and activates `id`, reporting both ids.
35//!   - `deactivate{id}`: clears the pointer only if `id` IS the currently
36//!     active workstream; otherwise a no-op success (§4.3: "deactivating an
37//!     idle or closed workstream is a no-op (idempotent)" — this includes an
38//!     unknown or nonexistent id, since the caller cannot distinguish "idle"
39//!     from "never existed" without an extra lookup the spec does not ask
40//!     for).
41//!
42//! (issue #3297) [`activate`]/[`deactivate`] are also the sole publishers of
43//! [`crate::events::Event::WorkstreamActivationChanged`] (DOC-48 §5.3/§6.3,
44//! AC-3.3) — emitted exactly when the persisted active pointer actually
45//! changes (a fresh activation, a force-switch, or a real deactivation),
46//! never on the idempotent no-op branches. Centralising the emission here
47//! (rather than at each RPC/REST call site) means every current AND future
48//! caller of these two functions gets the notification for free — see
49//! [`crate::events::Event::WorkstreamActivationChanged`]'s own docs for why
50//! this reuses the existing global event bus instead of a second channel.
51//! They also publish [`crate::events::Event::WorkstreamStateInferred`] for
52//! every workstream whose computed state actually transitions alongside the
53//! pointer change (the newly-active workstream on every real activation, plus
54//! the prior one on a force-switch); `super::protocol::close` publishes the
55//! same event's `"closed"` state via [`publish_state_inferred`] (`pub(super)`
56//! for exactly that one cross-file call).
57//!
58//! Test: `activation_tests`.
59
60use std::sync::Arc;
61
62use chrono::Utc;
63use thiserror::Error;
64use tokio::sync::Mutex;
65
66use crate::events::{Event, SessionEventEnvelope};
67
68use super::model::WorkstreamId;
69use super::store::{StoreError, WorkstreamStore};
70
71/// Publish `Event::WorkstreamActivationChanged` on the global event bus.
72///
73/// Why: the one place [`activate`]/[`deactivate`] construct this event, so
74/// both always build the same envelope shape.
75/// What: `seq` is always `0` — this event is not part of any per-session
76/// ring buffer (there is no owning session to sequence it against), unlike
77/// every other envelope this daemon publishes. `session_id` is the empty
78/// string for the same reason (see the event's own docs).
79fn publish_activation_changed(new_active_id: Option<WorkstreamId>, prior_id: Option<WorkstreamId>) {
80    let event = Event::WorkstreamActivationChanged {
81        new_active_id: new_active_id.map(|id| id.to_string()),
82        prior_id: prior_id.map(|id| id.to_string()),
83    };
84    crate::events::publish(SessionEventEnvelope::new(
85        String::new(),
86        0,
87        Utc::now(),
88        event,
89    ));
90}
91
92/// Publish `Event::WorkstreamStateInferred` on the global event bus.
93///
94/// Why: shared by [`activate`]/[`deactivate`] (this file) and
95/// `super::protocol::close` (the one place outside this module that
96/// transitions a workstream's state) — see the module docs for why `close`
97/// reaches into this helper rather than duplicating the envelope shape.
98/// What: mirrors [`publish_activation_changed`]'s `seq`/`session_id`
99/// convention (both are meaningless for a daemon-scoped event).
100pub(super) fn publish_state_inferred(workstream_id: WorkstreamId, state: &str, reason: &str) {
101    let event = Event::WorkstreamStateInferred {
102        workstream_id: workstream_id.to_string(),
103        state: state.to_string(),
104        reason: reason.to_string(),
105    };
106    crate::events::publish(SessionEventEnvelope::new(
107        String::new(),
108        0,
109        Utc::now(),
110        event,
111    ));
112}
113
114/// Shared, lock-wrapped handle to a project's workstream store.
115///
116/// Why: `WorkstreamStore`'s mutating methods take `&mut self` (#3293's
117/// single-writer-per-process design — see its own docs), but the daemon's
118/// JSON-RPC handlers are `Fn(...) -> Future` closures cloned once per method
119/// registration (see `crate::session::protocol::register`'s
120/// `Arc<SessionRegistry>` pattern) — they need shared, interior-mutable
121/// ownership of the SAME store instance.
122/// What: `Arc<tokio::sync::Mutex<WorkstreamStore>>`. `tokio::sync::Mutex`
123/// (not `std::sync::Mutex`) because every store operation is `async` (file
124/// I/O) and the lock must be held across `.await` points.
125pub type SharedWorkstreamStore = Arc<Mutex<WorkstreamStore>>;
126
127/// Typed failure surface for [`activate`]/[`deactivate`].
128///
129/// Why: callers (the `workstream.activate`/`workstream.deactivate` RPC
130/// handlers, `crate::workstreams::protocol`) need to pattern-match the
131/// distinct failure modes onto their own JSON-RPC error codes rather than
132/// string-sniffing.
133/// What: [`Self::NotFound`] — the target `id` names no existing workstream
134/// (maps to `-32002 not_found`); [`Self::ActiveConflict`] — DOC-48 §6.1's
135/// exclusivity gate (maps to `-32008 active_conflict`, carrying the
136/// currently-active id); [`Self::Store`] — a lower-level I/O/serialization
137/// failure (maps to `-32603 internal_error`).
138/// Test: `activation_tests::activate_unknown_id_returns_not_found`,
139/// `activation_tests::activate_without_force_returns_active_conflict`.
140#[derive(Debug, Error)]
141pub enum ActivationError {
142    #[error("workstream not found: {0}")]
143    NotFound(WorkstreamId),
144    #[error("another workstream is active: {0}")]
145    ActiveConflict(WorkstreamId),
146    #[error(transparent)]
147    Store(#[from] StoreError),
148}
149
150/// The result of a successful [`activate`] call (DOC-48 §5.1's
151/// `{active_id, prior_id?}` response shape).
152///
153/// Why: the RPC/REST layers need both ids to report the switch (and #3297's
154/// `WorkstreamActivationChanged` event will need the same pair) — a bare
155/// `()` would lose the "what changed" information the spec's response shape
156/// requires.
157/// What: `active_id` is always `id` (the just-activated workstream);
158/// `prior_id` is `None` for a fresh activation or an idempotent
159/// re-activation of the already-active workstream, `Some(...)` only when a
160/// DIFFERENT workstream was actually deactivated (a force-switch).
161/// Test: `activation_tests::*`.
162#[derive(Debug, Clone, Copy, PartialEq, Eq)]
163pub struct ActivateOutcome {
164    pub active_id: WorkstreamId,
165    pub prior_id: Option<WorkstreamId>,
166}
167
168/// Activate `id` under DOC-48 §6.1's exclusivity rules.
169///
170/// Why: the single entry point for both `workstream.activate` (RPC) and its
171/// REST twin — see the module docs for the exact rule table.
172/// What: rejects an unknown `id` with [`ActivationError::NotFound`] BEFORE
173/// looking at the active pointer (activating a nonexistent workstream is
174/// never valid, force or not). Otherwise: no workstream active -> activate
175/// and persist, `prior_id: None`; `id` already active -> idempotent success,
176/// `prior_id: None` (no pointer write); a DIFFERENT workstream active and
177/// `force: false` -> `ActivationError::ActiveConflict`; a DIFFERENT
178/// workstream active and `force: true` -> persist the switch, `prior_id:
179/// Some(previous)`.
180/// Test: `activation_tests::activate_with_no_prior_active_succeeds`,
181/// `activation_tests::activate_already_active_is_idempotent`,
182/// `activation_tests::activate_without_force_returns_active_conflict`,
183/// `activation_tests::activate_with_force_switches_and_reports_prior`,
184/// `activation_tests::activate_unknown_id_returns_not_found`,
185/// `activation_tests::activate_with_no_prior_active_publishes_state_inferred`,
186/// `activation_tests::activate_with_force_publishes_state_inferred_for_both`.
187pub async fn activate(
188    store: &SharedWorkstreamStore,
189    id: WorkstreamId,
190    force: bool,
191) -> Result<ActivateOutcome, ActivationError> {
192    let mut store = store.lock().await;
193
194    store.get(id).await.map_err(|e| match e {
195        StoreError::NotFound(_) => ActivationError::NotFound(id),
196        other => ActivationError::Store(other),
197    })?;
198
199    match store.active_workstream_id().await? {
200        Some(active) if active == id => Ok(ActivateOutcome {
201            active_id: id,
202            prior_id: None,
203        }),
204        Some(active) if !force => Err(ActivationError::ActiveConflict(active)),
205        Some(active) => {
206            store.set_active(Some(id)).await?;
207            publish_activation_changed(Some(id), Some(active));
208            publish_state_inferred(id, "active", "activated (force-switch)");
209            publish_state_inferred(active, "idle", "deactivated (force-switch)");
210            Ok(ActivateOutcome {
211                active_id: id,
212                prior_id: Some(active),
213            })
214        }
215        None => {
216            store.set_active(Some(id)).await?;
217            publish_activation_changed(Some(id), None);
218            publish_state_inferred(id, "active", "activated");
219            Ok(ActivateOutcome {
220                active_id: id,
221                prior_id: None,
222            })
223        }
224    }
225}
226
227/// Deactivate `id` under DOC-48 §4.3's idempotent rule.
228///
229/// Why: the single entry point for both `workstream.deactivate` (RPC) and
230/// its REST twin.
231/// What: clears the pointer (persisting `None`) and returns `Some(id)` ONLY
232/// when `id` is the CURRENTLY active workstream; otherwise a no-op success
233/// returning `None` — deactivating an idle, closed, or even nonexistent id
234/// is idempotent by design (§4.3), so this never looks the id up in
235/// `workstreams[]` at all.
236/// Test: `activation_tests::deactivate_active_clears_pointer`,
237/// `activation_tests::deactivate_non_active_is_idempotent_noop`,
238/// `activation_tests::deactivate_active_publishes_state_inferred_idle`.
239pub async fn deactivate(
240    store: &SharedWorkstreamStore,
241    id: WorkstreamId,
242) -> Result<Option<WorkstreamId>, ActivationError> {
243    let mut store = store.lock().await;
244    if store.active_workstream_id().await? == Some(id) {
245        store.set_active(None).await?;
246        publish_activation_changed(None, Some(id));
247        publish_state_inferred(id, "idle", "deactivated");
248        Ok(Some(id))
249    } else {
250        Ok(None)
251    }
252}
253
254#[cfg(test)]
255#[path = "activation_tests.rs"]
256mod activation_tests;