trusty_code/workstreams/protocol.rs
1//! `workstream.*` JSON-RPC method handlers (issues #3294, #3295, epic #3292).
2//!
3//! # Spec References
4//!
5//! - [`SPEC-WS-05~draft`](docs/specs/DOC-48-tcode-workstreams.md#SPEC-WS-05~draft)
6//! - [`SPEC-WS-06~draft`](docs/specs/DOC-48-tcode-workstreams.md#SPEC-WS-06~draft)
7//! - [`SPEC-WS-07~draft`](docs/specs/DOC-48-tcode-workstreams.md#SPEC-WS-07~draft)
8//!
9//! Why: mirrors `crate::session::protocol`'s role for `session.*` — the RPC
10//! surface the daemon exposes over `POST /rpc` (and, via
11//! `crate::serve::rest::workstreams`, the REST twin). #3293 (merged) built
12//! the domain model and the flat-JSON [`super::store::WorkstreamStore`], but
13//! left it unreachable from any transport. This file is where BOTH
14//! concurrent follow-up tickets against that foundation land: #3294's
15//! activation-lock exclusivity model (`activate`/`deactivate`, built on
16//! [`super::activation`]) and #3295's CRUD/inspection surface
17//! (`create`/`get`/`list`/`close`, built directly on the store) — six thin
18//! handlers, one shared [`SharedWorkstreamStore`], one `register` call.
19//!
20//! **Scope note:** `activate`/`deactivate`'s business logic (conflict
21//! detection, force-switch) lives entirely in [`super::activation`] — this
22//! file only parses `params` and maps [`ActivationError`] onto the JSON-RPC
23//! taxonomy. `create`/`get`/`list`/`close` have no activation-lock rules to
24//! apply, so they call [`super::store::WorkstreamStore`] directly. The CLI
25//! (#3296) and the SSE aggregation route (#3297) remain out of scope.
26//!
27//! What: [`register`] wires `workstream.create`, `workstream.get`,
28//! `workstream.list`, `workstream.close`, `workstream.activate`,
29//! `workstream.deactivate`, `workstream.rename` (Phase C, issue #3300) onto
30//! a [`crate::jsonrpc::Router`], all sharing one [`SharedWorkstreamStore`].
31//! Every verb that takes a wire `id` parses it via
32//! [`parse_id`] (a manual `Uuid::parse_str` + `-32602 Invalid params` on
33//! failure) rather than deserializing straight into a [`WorkstreamId`] —
34//! chosen as the ONE id-parsing style for this file since #3294 landed it
35//! first. [`WorkstreamView`] is the wire-shape adapter `get`/`list` share:
36//! the domain [`Workstream`] has no `state` FIELD (§2.2 — it is computed,
37//! never stored), so every read path builds this view by pairing a record
38//! with the store's current `active_workstream_id` pointer via
39//! [`Workstream::state`], exactly once, right before serializing.
40//! Test: `protocol_tests`.
41
42use serde::Deserialize;
43use serde::de::DeserializeOwned;
44use serde_json::{Value, json};
45use uuid::Uuid;
46
47use crate::jsonrpc::{ConnectionContext, Router, RpcError};
48
49use super::activation::{self, ActivationError, SharedWorkstreamStore, publish_state_inferred};
50use super::model::{Workstream, WorkstreamId, WorkstreamState};
51use super::store::StoreError;
52
53/// Register every `workstream.*` method onto `router`, all sharing `store`.
54///
55/// Why: the one place that lists the full `workstream.*` surface — mirrors
56/// `crate::session::protocol::register`'s role for `session.*`.
57/// What: clones `store` once per method (cheap — `Arc`) into a small adapter
58/// closure that forwards to the corresponding free function below.
59/// Test: `protocol_tests::register_wires_activate_and_deactivate`,
60/// `protocol_tests::register_wires_create_get_list_close`.
61pub fn register(router: &mut Router, store: SharedWorkstreamStore) {
62 let s = store.clone();
63 router.register(
64 "workstream.create",
65 move |params: Value, ctx: ConnectionContext| {
66 let s = s.clone();
67 async move { create(&s, params, ctx).await }
68 },
69 );
70
71 let s = store.clone();
72 router.register(
73 "workstream.get",
74 move |params: Value, ctx: ConnectionContext| {
75 let s = s.clone();
76 async move { get(&s, params, ctx).await }
77 },
78 );
79
80 let s = store.clone();
81 router.register(
82 "workstream.list",
83 move |params: Value, ctx: ConnectionContext| {
84 let s = s.clone();
85 async move { list(&s, params, ctx).await }
86 },
87 );
88
89 let s = store.clone();
90 router.register(
91 "workstream.close",
92 move |params: Value, ctx: ConnectionContext| {
93 let s = s.clone();
94 async move { close(&s, params, ctx).await }
95 },
96 );
97
98 let s = store.clone();
99 router.register(
100 "workstream.activate",
101 move |params: Value, ctx: ConnectionContext| {
102 let s = s.clone();
103 async move { activate(&s, params, ctx).await }
104 },
105 );
106
107 let s = store.clone();
108 router.register(
109 "workstream.deactivate",
110 move |params: Value, ctx: ConnectionContext| {
111 let s = s.clone();
112 async move { deactivate(&s, params, ctx).await }
113 },
114 );
115
116 let s = store;
117 router.register(
118 "workstream.rename",
119 move |params: Value, ctx: ConnectionContext| {
120 let s = s.clone();
121 async move { rename(&s, params, ctx).await }
122 },
123 );
124}
125
126/// The wire shape for a workstream record — the domain [`Workstream`] plus
127/// its computed [`WorkstreamState`] (§2.2: never a stored field), assembled
128/// fresh for every response.
129#[derive(Debug, serde::Serialize)]
130struct WorkstreamView {
131 id: WorkstreamId,
132 name: String,
133 state: WorkstreamState,
134 session_ids: Vec<String>,
135 created_at: chrono::DateTime<chrono::Utc>,
136 updated_at: chrono::DateTime<chrono::Utc>,
137 metadata: serde_json::Map<String, Value>,
138}
139
140impl WorkstreamView {
141 /// Pair a stored record with the pointer that governs its state.
142 fn new(ws: Workstream, active_workstream_id: Option<WorkstreamId>) -> Self {
143 let state = ws.state(active_workstream_id);
144 Self {
145 id: ws.id,
146 name: ws.name,
147 state,
148 session_ids: ws.session_ids,
149 created_at: ws.created_at,
150 updated_at: ws.updated_at,
151 metadata: ws.metadata,
152 }
153 }
154}
155
156/// Resolve + VALIDATE the EFFECTIVE workstream target, then mint a session
157/// and persist its binding — all under one store lock (DOC-48 §4.1/§4.2,
158/// issue #3298; validate-before-mint ordering per PR #3354 code-critic
159/// HIGH findings 1 & 2).
160///
161/// Why: `session::protocol::create` and `task::protocol::task_run` (minting
162/// a NEW session) both need this exact resolution — an explicit
163/// `workstream_id` param (§4.1) takes precedence; otherwise the daemon's
164/// currently active workstream is the ambient default target (§4.2); if
165/// neither applies, the session stays projectless (valid, never an error).
166/// Centralising it here (rather than duplicating in both `protocol` modules)
167/// is the same "one place, both callers" precedent
168/// `crate::binding::ProjectBinding::resolve` already set for project
169/// binding.
170///
171/// **Why the `mint` closure (atomicity):** `SessionRegistry` has no
172/// delete/rollback — a session, once minted, exists for the daemon
173/// lifetime. The first cut of this function took an ALREADY-minted
174/// `session_id` and could then fail (closed/unknown/malformed target),
175/// leaving an orphaned, caller-invisible session in the registry on every
176/// rejected bind — a retry-amplified memory-growth vector (code-critic
177/// HIGH, PR #3354). Now every caller-triggerable failure mode (malformed
178/// id, unknown id, closed workstream) is validated BEFORE `mint()` runs, so
179/// a rejected bind mints nothing. Holding the ONE store lock across
180/// resolve -> validate -> mint -> bind keeps the sequence TOCTOU-free: no
181/// concurrent `workstream.close`/`deactivate` can invalidate the target
182/// between its validation and the bind.
183/// What: `explicit` is the caller's raw wire `workstream_id` string, if
184/// any; `mint` mints the session (infallible — `SessionRegistry::create`
185/// never fails) and returns its id, called EXACTLY ONCE, and only after
186/// validation passes. Returns `(session_id, bound_workstream)` —
187/// `(id, None)` when no explicit param was given and no workstream is
188/// active (projectless mint); `(id, Some(ws))` after
189/// `WorkstreamStore::bind_session` persisted the append.
190/// `Err(-32602 invalid_params)` — `explicit` is not a valid UUID.
191/// `Err(-32002 not_found)` — `explicit` names no workstream.
192/// `Err(-32003 invalid_argument)` — the target (explicit OR ambient) is
193/// closed (§4.1: "new sessions may not bind to it"). All three fire before
194/// `mint`. The residual post-mint failure surface is `bind_session`'s
195/// save-to-disk I/O error (`-32603 internal`) — a daemon-side storage
196/// fault, not caller-triggerable; `BindError::NotFound`/`Closed`/
197/// `AlreadyBound` are unreachable post-validation under the held lock and
198/// map to `-32603 internal` defensively.
199/// Test: `protocol_tests::resolve_validate_bind_explicit_wins_over_active`,
200/// `protocol_tests::resolve_validate_bind_falls_back_to_active`,
201/// `protocol_tests::resolve_validate_bind_none_when_nothing_active`,
202/// `protocol_tests::resolve_validate_bind_rejects_closed_target_without_minting`,
203/// `protocol_tests::resolve_validate_bind_rejects_unknown_id_without_minting`,
204/// `protocol_tests::resolve_validate_bind_rejects_malformed_id_without_minting`;
205/// the end-to-end no-phantom-session regression at both RPC surfaces in
206/// `session::protocol::workstream_binding_tests::create_rejected_bind_leaves_no_phantom_session`
207/// and `task::protocol::tests::task_run_rejected_bind_leaves_no_phantom_session`.
208pub async fn resolve_validate_bind<F>(
209 store: &SharedWorkstreamStore,
210 explicit: Option<&str>,
211 method: &str,
212 mint: F,
213) -> Result<(String, Option<WorkstreamId>), RpcError>
214where
215 F: FnOnce() -> String,
216{
217 let mut store = store.lock().await;
218 let target = match explicit {
219 Some(raw) => Some(parse_id(raw, method)?),
220 None => store.active_workstream_id().await.map_err(map_store_err)?,
221 };
222 // Validate the target BEFORE minting — every caller-triggerable
223 // rejection must happen while nothing has been created yet.
224 if let Some(id) = target {
225 let ws = store.get(id).await.map_err(map_store_err)?;
226 if ws.is_closed() {
227 return Err(RpcError::invalid_argument(format!(
228 "workstream {id} is closed; new sessions may not bind to it"
229 )));
230 }
231 }
232 let session_id = mint();
233 if let Some(id) = target {
234 store
235 .bind_session(id, &session_id)
236 .await
237 .map_err(|e| match e {
238 // Post-validation, under the same lock, only a storage I/O
239 // fault can land here; the caller-shaped variants are
240 // defensively mapped to internal rather than silently
241 // reusing their pre-mint codes (which would misreport an
242 // impossible state as a caller error).
243 super::store::BindError::Store(e) => map_store_err(e),
244 other => RpcError::internal(format!(
245 "unexpected post-validation bind failure for session `{session_id}`: {other}"
246 )),
247 })?;
248 }
249 Ok((session_id, target))
250}
251
252/// Enforce DOC-48 §4.1's binding immutability on a REUSED session (AC-1.3,
253/// issue #3298): "if a session with an existing workstream binding receives
254/// a task with a different workstream, the task is rejected."
255///
256/// Why: `task::protocol::task_run`'s `session_id` ("sessionful") path is the
257/// one call site that can present a session already carrying a persisted
258/// `workstream_id` alongside a fresh, possibly-conflicting `workstream_id`
259/// param — mirrors the existing `project` mismatch guard right next to it
260/// (`task::protocol::task_run`'s own docs) at the exact same layer.
261/// What: `explicit: None` never rejects — ambient default-targeting (§4.2)
262/// applies only to a session's FIRST binding at creation, never re-applied
263/// on reuse. `explicit: Some(raw)` — parses `raw`; `Ok(())` if it restates
264/// `existing` exactly (including `existing: None` restated by... it cannot
265/// restate `None`, so any `Some` explicit id against an unbound session is
266/// ALSO a mismatch, per the same authoritative-binding rule
267/// `task::protocol::task_run`'s `project` check already applies); otherwise
268/// `Err(-32003 invalid_argument)` naming both ids.
269/// Test: `protocol_tests::check_workstream_immutable_allows_none`,
270/// `protocol_tests::check_workstream_immutable_allows_restating_same_id`,
271/// `protocol_tests::check_workstream_immutable_rejects_mismatch`,
272/// `protocol_tests::check_workstream_immutable_rejects_binding_an_unbound_session`.
273pub fn check_workstream_immutable(
274 existing: Option<WorkstreamId>,
275 explicit: Option<&str>,
276 method: &str,
277) -> Result<(), RpcError> {
278 let Some(raw) = explicit else {
279 return Ok(());
280 };
281 let requested = parse_id(raw, method)?;
282 if existing == Some(requested) {
283 return Ok(());
284 }
285 Err(RpcError::invalid_argument(format!(
286 "{method}: workstream `{requested}` does not match this session's existing binding \
287 `{}` — a session's workstream binding is immutable once set (DOC-48 §4.1)",
288 existing
289 .map(|id| id.to_string())
290 .unwrap_or_else(|| "<unbound>".to_string()),
291 )))
292}
293
294/// Deserialise `params` into `T`, mapping a failure onto `-32602 Invalid
295/// params` with the method name for context (mirrors
296/// `crate::session::protocol::parse`).
297fn parse<T: DeserializeOwned>(params: Value, method: &str) -> Result<T, RpcError> {
298 serde_json::from_value(params).map_err(|e| RpcError::invalid_params(format!("{method}: {e}")))
299}
300
301/// Parse a wire `id` string into a [`WorkstreamId`], mapping a malformed
302/// UUID onto `-32602 Invalid params` rather than a panic (issue #3294's
303/// id-parsing style, applied uniformly to every verb in this file — see
304/// module docs).
305fn parse_id(raw: &str, method: &str) -> Result<WorkstreamId, RpcError> {
306 Uuid::parse_str(raw)
307 .map(WorkstreamId::from)
308 .map_err(|e| RpcError::invalid_params(format!("{method}: invalid workstream id: {e}")))
309}
310
311/// Map a [`StoreError`] onto the JSON-RPC error taxonomy (vision spec §13.2)
312/// for the `create`/`get`/`list`/`close` verbs (the `activate`/`deactivate`
313/// verbs instead map [`ActivationError`], which wraps `StoreError` alongside
314/// its own `NotFound`/`ActiveConflict` variants).
315///
316/// Why: the one place `NotFound` becomes the spec's general `-32002
317/// not_found` (workstreams have no session-specific error code) and every
318/// other variant (I/O, serialization) becomes `-32603 internal` — a
319/// caller-triggerable "id doesn't exist" must never be indistinguishable
320/// from a daemon-side storage fault.
321/// Test: `protocol_tests::get_unknown_id_maps_to_not_found`.
322fn map_store_err(err: StoreError) -> RpcError {
323 match err {
324 StoreError::NotFound(id) => RpcError::not_found(format!("workstream not found: {id}")),
325 StoreError::Io(_) | StoreError::Serialize(_) => RpcError::internal(err.to_string()),
326 }
327}
328
329/// `params` shape for `workstream.create`.
330#[derive(Deserialize)]
331struct CreateParams {
332 #[serde(default)]
333 name: Option<String>,
334}
335
336/// `params` shape shared by every verb that only needs a workstream id
337/// (`get`, `close`, `deactivate`).
338#[derive(Deserialize)]
339struct WorkstreamIdParams {
340 id: String,
341}
342
343/// `params` shape for `workstream.list`.
344#[derive(Deserialize, Default)]
345struct ListParams {
346 #[serde(default)]
347 include_closed: bool,
348}
349
350/// `params` shape for `workstream.activate` (DOC-48 §5.1).
351#[derive(Deserialize)]
352struct ActivateParams {
353 id: String,
354 #[serde(default)]
355 force: bool,
356}
357
358/// `params` shape for `workstream.rename` (DOC-48 §5.1, Phase C).
359#[derive(Deserialize)]
360struct RenameParams {
361 id: String,
362 name: String,
363}
364
365/// `workstream.create{name?} -> {id: UUID}` (DOC-48 §5.1, AC-2.1).
366///
367/// Why: mints a brand-new daemon-owned workstream. No `project_id`
368/// parameter — the daemon's own `ProjectBinding` is implicit (§2.3): the
369/// store this handler shares is already scoped to it via the file the daemon
370/// booted with.
371/// What: `name` defaults to an empty string when omitted (§5.1: "Name is
372/// initially empty"). Returns `{"id": <new id>}`.
373/// Test: `protocol_tests::create_returns_new_id`,
374/// `protocol_tests::create_without_name_defaults_to_empty`.
375async fn create(
376 store: &SharedWorkstreamStore,
377 params: Value,
378 _ctx: ConnectionContext,
379) -> Result<Value, RpcError> {
380 let p: CreateParams = parse(params, "workstream.create")?;
381 let mut store = store.lock().await;
382 let id = store
383 .create(p.name.unwrap_or_default())
384 .await
385 .map_err(map_store_err)?;
386 Ok(json!({ "id": id }))
387}
388
389/// `workstream.get{id} -> Workstream` (DOC-48 §5.1, AC-2.1).
390///
391/// Why: point lookup for one workstream's current (inferred) state.
392/// What: `-32002 not_found` if `id` is unknown; otherwise the full
393/// [`WorkstreamView`] — id, name, computed `state`, `session_ids`,
394/// timestamps, `metadata`.
395/// Test: `protocol_tests::get_returns_workstream_with_state`,
396/// `protocol_tests::get_unknown_id_maps_to_not_found`.
397async fn get(
398 store: &SharedWorkstreamStore,
399 params: Value,
400 _ctx: ConnectionContext,
401) -> Result<Value, RpcError> {
402 let p: WorkstreamIdParams = parse(params, "workstream.get")?;
403 let id = parse_id(&p.id, "workstream.get")?;
404 let mut store = store.lock().await;
405 let ws = store.get(id).await.map_err(map_store_err)?;
406 let active_id = store.active_workstream_id().await.map_err(map_store_err)?;
407 Ok(json!(WorkstreamView::new(ws, active_id)))
408}
409
410/// `workstream.list{include_closed?} -> {active_workstream_id, workstreams: [Workstream]}`
411/// (DOC-48 §5.1, AC-2.1, AC-2.3).
412///
413/// Why: enumerates every workstream in the daemon's project, so a client can
414/// build a switcher without a `get` per id.
415/// What: default `include_closed = false` filters out records whose
416/// [`Workstream::is_closed`] flag is set (§4.4: "optionally listable ...
417/// for audit/historical query"); `true` includes them. Every returned record
418/// is paired with the SAME `active_workstream_id` snapshot (read once, not
419/// per record) so the response is internally consistent even if a concurrent
420/// writer changes the pointer mid-list. `active_workstream_id` is always
421/// present at the top level (`null` if none active, AC-2.3).
422/// Test: `protocol_tests::list_returns_active_workstream_id_and_records`,
423/// `protocol_tests::list_default_excludes_closed`,
424/// `protocol_tests::list_include_closed_true_includes_closed`.
425async fn list(
426 store: &SharedWorkstreamStore,
427 params: Value,
428 _ctx: ConnectionContext,
429) -> Result<Value, RpcError> {
430 let p: ListParams = if params.is_null() {
431 ListParams::default()
432 } else {
433 parse(params, "workstream.list")?
434 };
435 let mut store = store.lock().await;
436 let all = store.list().await.map_err(map_store_err)?;
437 let active_id = store.active_workstream_id().await.map_err(map_store_err)?;
438 let views: Vec<WorkstreamView> = all
439 .into_iter()
440 .filter(|ws| p.include_closed || !ws.is_closed())
441 .map(|ws| WorkstreamView::new(ws, active_id))
442 .collect();
443 Ok(json!({
444 "active_workstream_id": active_id,
445 "workstreams": views,
446 }))
447}
448
449/// `workstream.close{id} -> {}` (DOC-48 §4.4/§5.1, AC-2.1).
450///
451/// Why: irreversibly closes a workstream — rejects future session bindings
452/// (enforced at the session-binding call site, #3298 scope, not here) and,
453/// per §4.4, auto-deactivates it if it is currently the active one.
454/// What: `-32002 not_found` if `id` is unknown; otherwise `{}` (matching the
455/// spec's §5.1 signature exactly — not the updated record, since a client
456/// that needs the post-close view already has `workstream.get`). Idempotent:
457/// closing an already-closed workstream succeeds again (see
458/// [`super::model::Workstream::mark_closed`]'s docs). (Issue #3297)
459/// Unconditionally publishes `Event::WorkstreamStateInferred{state: "closed"}`
460/// via [`publish_state_inferred`] — even a repeat close re-asserts the same
461/// state to any freshly-subscribed `GET /workstreams/{id}/events` observer,
462/// and re-publishing an unchanged state is harmless.
463/// Test: `protocol_tests::close_succeeds_and_clears_active_pointer`,
464/// `protocol_tests::close_unknown_id_maps_to_not_found`,
465/// `protocol_tests::close_publishes_state_inferred`.
466async fn close(
467 store: &SharedWorkstreamStore,
468 params: Value,
469 _ctx: ConnectionContext,
470) -> Result<Value, RpcError> {
471 let p: WorkstreamIdParams = parse(params, "workstream.close")?;
472 let id = parse_id(&p.id, "workstream.close")?;
473 let mut store = store.lock().await;
474 store.close(id).await.map_err(map_store_err)?;
475 publish_state_inferred(id, "closed", "closed");
476 Ok(json!({}))
477}
478
479/// `workstream.activate(id, force?) -> {active_id, prior_id?}` (DOC-48
480/// §5.1/§6.1).
481///
482/// Why: the RPC entry point for the activation-lock exclusivity model.
483/// What: parses `params`, delegates to [`activation::activate`], and maps
484/// its typed error onto the JSON-RPC error taxonomy — [`ActivationError::NotFound`]
485/// to `-32002 not_found`, [`ActivationError::ActiveConflict`] to `-32008
486/// active_conflict` (`RpcError::active_conflict`, carrying `active_id`), and
487/// [`ActivationError::Store`] to `-32603 internal_error`.
488/// Test: `protocol_tests::activate_succeeds_with_no_prior_active`,
489/// `protocol_tests::activate_without_force_maps_to_active_conflict`,
490/// `protocol_tests::activate_with_force_switches`,
491/// `protocol_tests::activate_unknown_id_maps_to_not_found`,
492/// `protocol_tests::activate_malformed_id_maps_to_invalid_params`.
493async fn activate(
494 store: &SharedWorkstreamStore,
495 params: Value,
496 _ctx: ConnectionContext,
497) -> Result<Value, RpcError> {
498 let p: ActivateParams = parse(params, "workstream.activate")?;
499 let id = parse_id(&p.id, "workstream.activate")?;
500
501 match activation::activate(store, id, p.force).await {
502 Ok(outcome) => Ok(json!({
503 "active_id": outcome.active_id,
504 "prior_id": outcome.prior_id,
505 })),
506 Err(ActivationError::NotFound(id)) => {
507 Err(RpcError::not_found(format!("workstream not found: {id}")))
508 }
509 Err(ActivationError::ActiveConflict(active_id)) => {
510 Err(RpcError::active_conflict(active_id))
511 }
512 Err(ActivationError::Store(e)) => Err(RpcError::internal(e.to_string())),
513 }
514}
515
516/// `workstream.deactivate(id) -> {}` (DOC-48 §5.1/§4.3).
517///
518/// Why: the RPC entry point for clearing the active pointer.
519/// What: idempotent — see [`activation::deactivate`]'s docs; the only
520/// failure mode is a lower-level store error, mapped to `-32603
521/// internal_error`.
522/// Test: `protocol_tests::deactivate_active_clears_pointer`,
523/// `protocol_tests::deactivate_idle_is_idempotent_noop`.
524async fn deactivate(
525 store: &SharedWorkstreamStore,
526 params: Value,
527 _ctx: ConnectionContext,
528) -> Result<Value, RpcError> {
529 let p: WorkstreamIdParams = parse(params, "workstream.deactivate")?;
530 let id = parse_id(&p.id, "workstream.deactivate")?;
531
532 activation::deactivate(store, id)
533 .await
534 .map_err(|e| match e {
535 ActivationError::Store(e) => RpcError::internal(e.to_string()),
536 // `deactivate` never constructs `NotFound`/`ActiveConflict` itself
537 // (see its docs) — reachable only if a future change to
538 // `activation::deactivate` starts returning them without updating
539 // this mapping, so fail loudly rather than mis-mapping silently.
540 other => RpcError::internal(format!("unexpected activation error: {other}")),
541 })?;
542 Ok(json!({}))
543}
544
545/// `workstream.rename{id, name} -> Workstream` (DOC-48 §5.1, Phase C, issue
546/// #3300).
547///
548/// Why: the RPC entry point for the GUI switcher's rename action — the one
549/// verb DOC-48 §5.1 marked "future, Phase C" when Phase 1A shipped; this
550/// issue is that phase.
551/// What: `-32002 not_found` if `id` is unknown; otherwise the updated
552/// [`WorkstreamView`] (matching `get`'s response shape, since a client that
553/// just renamed a record typically wants the fresh view without a second
554/// round-trip). An empty `name` is accepted — matching `workstream.create`'s
555/// own "name defaults to empty" tolerance rather than inventing a new
556/// validation rule this spec never states.
557/// Test: `protocol_tests::rename_succeeds_and_returns_updated_view`,
558/// `protocol_tests::rename_unknown_id_maps_to_not_found`.
559async fn rename(
560 store: &SharedWorkstreamStore,
561 params: Value,
562 _ctx: ConnectionContext,
563) -> Result<Value, RpcError> {
564 let p: RenameParams = parse(params, "workstream.rename")?;
565 let id = parse_id(&p.id, "workstream.rename")?;
566 let mut store = store.lock().await;
567 let ws = store.rename(id, p.name).await.map_err(map_store_err)?;
568 let active_id = store.active_workstream_id().await.map_err(map_store_err)?;
569 Ok(json!(WorkstreamView::new(ws, active_id)))
570}
571
572#[cfg(test)]
573#[path = "protocol_tests.rs"]
574mod protocol_tests;