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