Skip to main content

muse_code_sdk/
fold.rs

1//! Ephemeral fold. Params stay as JSON so newer open values survive verbatim.
2
3use std::collections::{HashMap, HashSet, hash_map::Entry};
4
5use serde_json::{Map, Value};
6
7use crate::msp::{Notification, ViewGapParams};
8
9mod approvals;
10mod items;
11mod types;
12
13pub use approvals::PendingApproval;
14pub use items::{ItemOutcome, Items};
15pub use types::{DeliveryGap, FoldOutcome, SessionState, Turn, TurnState};
16
17use approvals::Approvals;
18
19/// Request params keyed by id; each entry keeps the sequence at which it
20/// entered its set, so pending entries list in first-request order and resolved
21/// entries in first-resolution order, as the TS/Py folds do.
22#[derive(Debug, Default)]
23struct Requests {
24    observed: u64,
25    pending: HashMap<String, (u64, Value)>,
26    resolved: HashMap<String, (u64, Value)>,
27}
28
29impl Requests {
30    fn request(&mut self, id: &str, params: &Map<String, Value>) -> bool {
31        if self.resolved.contains_key(id) {
32            return false;
33        }
34        let params = Value::Object(params.clone());
35        match self.pending.entry(id.to_owned()) {
36            Entry::Occupied(mut slot) => slot.get_mut().1 = params,
37            Entry::Vacant(slot) => {
38                slot.insert((self.observed, params));
39                self.observed += 1;
40            }
41        }
42        true
43    }
44
45    fn resolve(&mut self, id: &str, params: &Map<String, Value>) -> bool {
46        self.pending.remove(id);
47        match self.resolved.entry(id.to_owned()) {
48            Entry::Vacant(slot) => {
49                slot.insert((self.observed, Value::Object(params.clone())));
50                self.observed += 1;
51                true
52            }
53            Entry::Occupied(_) => false,
54        }
55    }
56}
57
58fn params_of(entry: Option<&(u64, Value)>) -> Option<&Value> {
59    entry.map(|(_, params)| params)
60}
61
62fn in_observed_order(entries: &HashMap<String, (u64, Value)>) -> Vec<&Value> {
63    let mut ordered: Vec<_> = entries.values().collect();
64    ordered.sort_unstable_by_key(|(observed, _)| *observed);
65    ordered.into_iter().map(|(_, params)| params).collect()
66}
67
68/// A fold must be bound to one server session at construction.
69///
70/// ```compile_fail
71/// use muse_code_sdk::fold::SessionFold;
72///
73/// let unbound = SessionFold::default();
74/// ```
75#[derive(Debug)]
76pub struct SessionFold {
77    session_id: String,
78    items: Items,
79    state: SessionState,
80    turns: HashMap<String, Turn>,
81    // Turn ids in first-seen order; turns are never removed.
82    turn_order: Vec<String>,
83    active_turn: Option<String>,
84    approvals: Approvals,
85    user_inputs: Requests,
86    gap: Option<DeliveryGap>,
87    // In a standalone fold, every `next` a `view/gap` named while `gap` is
88    // pending, as the `Session` walk keeps its targets: a repeated one is a
89    // stale frame, not a new target.
90    gap_targets: HashSet<String>,
91    // Set by the owning `Session` once an event was lost; nothing folds after.
92    lost: bool,
93    // Set once its id was opened again on the same client; only question
94    // events fold after.
95    reopened: bool,
96}
97
98impl SessionFold {
99    /// An empty fold bound to `session_id`: events for any other session are
100    /// ignored.
101    pub fn new(session_id: impl Into<String>) -> Self {
102        Self {
103            session_id: session_id.into(),
104            items: Items::default(),
105            state: SessionState::default(),
106            turns: HashMap::new(),
107            turn_order: Vec::new(),
108            active_turn: None,
109            approvals: Approvals::default(),
110            user_inputs: Requests::default(),
111            gap: None,
112            gap_targets: HashSet::new(),
113            lost: false,
114            reopened: false,
115        }
116    }
117    /// The items the fold holds.
118    pub const fn items(&self) -> &Items {
119        &self.items
120    }
121    /// The latest params of each session-state notification the fold applied.
122    pub const fn session_state(&self) -> &SessionState {
123        &self.state
124    }
125    /// The turn whose `turn/started` the fold applied last, until that turn
126    /// completes, is retracted or is unqueued.
127    pub fn active_turn_id(&self) -> Option<&str> {
128        self.active_turn.as_deref()
129    }
130    /// The record of turn `id`, or `None` when no turn event the fold applied
131    /// named it.
132    pub fn turn(&self, id: &str) -> Option<&Turn> {
133        self.turns.get(id)
134    }
135    pub(crate) fn turn_ids(&self) -> &[String] {
136        &self.turn_order
137    }
138    /// The delivery gap the fold has pending, or `None`. A stopped fold keeps
139    /// its last gap, which nothing fills.
140    pub const fn pending_gap(&self) -> Option<&DeliveryGap> {
141        self.gap.as_ref()
142    }
143    /// False while a delivery gap is pending, and for good once the owning
144    /// `Session` lost an event or its session id was opened again on the
145    /// same client.
146    pub const fn is_current(&self) -> bool {
147        self.gap.is_none() && !self.is_stopped()
148    }
149    /// Clears the pending gap when `next` is its `next` cursor and returns
150    /// true; any other cursor leaves the gap in place and returns false.
151    pub fn gap_filled(&mut self, next: &str) -> bool {
152        if self.gap.as_ref().map(|gap| gap.next.as_str()) != Some(next) {
153            return false;
154        }
155        self.gap = None;
156        self.gap_targets.clear();
157        true
158    }
159
160    /// The latest params seen for a pending approval: its `approval/updated`
161    /// refresh if any, else its request. `pending_approvals` keeps both.
162    pub fn pending_approval(&self, id: &str) -> Option<&Value> {
163        self.approvals.latest(id)
164    }
165
166    /// The first `approval/resolved` params of approval `id`; a later
167    /// terminal never replaces it.
168    pub fn resolved_approval(&self, id: &str) -> Option<&Value> {
169        self.approvals.resolved(id)
170    }
171
172    /// Approvals awaiting a durable terminal, in the order they were first
173    /// requested, each with its latest request and latest update.
174    pub fn pending_approvals(&self) -> Vec<&PendingApproval> {
175        self.approvals.pending_in_order()
176    }
177
178    /// The first durable terminal per approval, in the order those first
179    /// terminals arrived.
180    pub fn resolved_approvals(&self) -> Vec<&Value> {
181        self.approvals.resolved_in_order()
182    }
183
184    /// The latest `userInput/requested` params of question `id` while it
185    /// awaits its first settlement.
186    pub fn pending_user_input(&self, id: &str) -> Option<&Value> {
187        params_of(self.user_inputs.pending.get(id))
188    }
189
190    /// The first `userInput/settled` params of question `id`; a later
191    /// settlement never replaces it.
192    pub fn settled_user_input(&self, id: &str) -> Option<&Value> {
193        params_of(self.user_inputs.resolved.get(id))
194    }
195
196    /// Questions awaiting a durable settlement, in the order they were first
197    /// requested.
198    pub fn pending_user_inputs(&self) -> Vec<&Value> {
199        in_observed_order(&self.user_inputs.pending)
200    }
201
202    /// The first durable settlement per question, in the order those first
203    /// settlements arrived.
204    pub fn settled_user_inputs(&self) -> Vec<&Value> {
205        in_observed_order(&self.user_inputs.resolved)
206    }
207
208    /// Folds one event and reports what it changed. Events for another
209    /// session and malformed params change nothing. After the owning
210    /// `Session` stops the fold it applies nothing, or only question events
211    /// after a re-open.
212    pub fn apply(&mut self, event: &Notification) -> FoldOutcome {
213        if self.lost {
214            return FoldOutcome::Ignored;
215        }
216        let method = event.method.as_str();
217        // Question events are safe to see twice, and a turn that asks one
218        // must stay answerable, so a re-opened fold still takes them.
219        if self.reopened && !matches!(method, "userInput/requested" | "userInput/settled") {
220            return FoldOutcome::Ignored;
221        }
222        let Some(params) = event.params.as_ref() else {
223            return FoldOutcome::Ignored;
224        };
225        if string(params, "sessionId") != Some(self.session_id.as_str()) {
226            return FoldOutcome::Ignored;
227        }
228        match method {
229            "item/started" | "item/updated" | "item/completed" => self.item(method, params),
230            "item/delta" => self.delta(params),
231            "turn/started" | "turn/completed" | "turn/retracted" | "turn/unqueued" => {
232                self.turn_event(method, params)
233            }
234            "approval/requested" => applied(
235                string(params, "approvalId").is_some_and(|id| self.approvals.request(id, params)),
236            ),
237            "approval/updated" => applied(
238                string(params, "approvalId").is_some_and(|id| self.approvals.update(id, params)),
239            ),
240            "approval/resolved" => {
241                string(params, "approvalId").map_or(FoldOutcome::Ignored, |id| {
242                    FoldOutcome::Resolution {
243                        first: self.approvals.resolve(id, params),
244                    }
245                })
246            }
247            "userInput/requested" => request(&mut self.user_inputs, params, "userInputId"),
248            "userInput/settled" => resolve(&mut self.user_inputs, params, "userInputId"),
249            "view/gap" => self.delivery_gap(params),
250            family if is_state_family(family) => {
251                self.state
252                    .0
253                    .insert(family.to_owned(), Value::Object(params.clone()));
254                FoldOutcome::Applied
255            }
256            _ => FoldOutcome::Ignored,
257        }
258    }
259
260    /// Seeds one raw resume-history item as of the resume cursor, keeping
261    /// members this SDK does not know; an `inProgress` item stays open to the
262    /// deltas that follow.
263    pub(crate) fn seed_history_item(&mut self, item: &Map<String, Value>) {
264        let method = if string(item, "status") == Some("inProgress") {
265            "item/updated"
266        } else {
267            "item/completed"
268        };
269        self.item(
270            method,
271            &Map::from_iter([("item".to_owned(), Value::Object(item.clone()))]),
272        );
273    }
274
275    /// Follows the owning session's gap fill: its pending hole is the one the
276    /// walk fills, so currency tracks the walk rather than this fold's own
277    /// `view/gap` coalescing. A stopped fold keeps its
278    /// last currency.
279    pub(crate) fn track_gap(&mut self, gap: Option<&ViewGapParams>) {
280        if self.is_stopped() {
281            return;
282        }
283        self.gap = gap.map(|gap| DeliveryGap {
284            after: gap.after.clone(),
285            next: gap.next.clone(),
286        });
287        // Only keeps the field consistent: a `Session`-owned fold never folds a
288        // `view/gap` itself, so nothing reads these targets.
289        self.gap_targets = gap.map(|gap| gap.next.clone()).into_iter().collect();
290    }
291
292    /// The owning session lost an event, or cannot prove it did not: stop
293    /// folding and stay not current, so the fold never passes for complete.
294    pub(crate) fn mark_lost(&mut self) {
295        self.lost = true;
296    }
297
298    /// The owning session's id was opened again on the same client, so an
299    /// event may reach it twice or reach another `Session` instead: stop
300    /// everything but question events and stay not current.
301    pub(crate) fn mark_reopened(&mut self) {
302        self.reopened = true;
303    }
304
305    pub(crate) const fn is_stopped(&self) -> bool {
306        self.lost || self.reopened
307    }
308
309    /// A pending hole that nothing can fill any more stops the fold.
310    pub(crate) fn stop_if_gap_pending(&mut self) {
311        if self.gap.is_some() {
312            self.lost = true;
313        }
314    }
315
316    fn turn_event(&mut self, method: &str, params: &Map<String, Value>) -> FoldOutcome {
317        let Some(id) = string(params, "turnId") else {
318            return FoldOutcome::Ignored;
319        };
320        let command_id = match method {
321            "turn/started" | "turn/retracted" | "turn/unqueued" => {
322                let Some(command_id) = string(params, "commandId") else {
323                    return FoldOutcome::Ignored;
324                };
325                Some(command_id)
326            }
327            _ => None,
328        };
329        let terminal = if method == "turn/completed" {
330            let Some(terminal) = string(params, "terminal") else {
331                return FoldOutcome::Ignored;
332            };
333            Some(terminal)
334        } else {
335            None
336        };
337        // A declined retract means the submission stood, so the
338        // fold keeps the turn's prior state, as the TypeScript and Python folds
339        // do: a running turn stays running and its `turn/completed` still
340        // settles it. On a turn it holds, the fold records the standing
341        // submission's command id. A declined retract carries no lifecycle
342        // fact, so for a turn the fold has not seen it adds no entry. Only an
343        // explicit "declined" counts; any other outcome reads as accepted.
344        if method == "turn/retracted" && string(params, "outcome") == Some("declined") {
345            let Some(turn) = self.turns.get_mut(id) else {
346                return FoldOutcome::Ignored;
347            };
348            turn.command_id = command_id.map(str::to_owned);
349            return FoldOutcome::Applied;
350        }
351        let turn = match self.turns.entry(id.to_owned()) {
352            Entry::Occupied(slot) => slot.into_mut(),
353            Entry::Vacant(slot) => {
354                self.turn_order.push(id.to_owned());
355                slot.insert(Turn {
356                    state: TurnState::Running,
357                    command_id: None,
358                    terminal: None,
359                    completion: None,
360                })
361            }
362        };
363        match method {
364            "turn/started" if turn.state == TurnState::Running => {
365                let Some(command_id) = command_id else {
366                    return FoldOutcome::Ignored;
367                };
368                turn.command_id = Some(command_id.to_owned());
369                self.active_turn = Some(id.to_owned());
370            }
371            "turn/completed"
372                if turn.terminal.is_none()
373                    && !matches!(turn.state, TurnState::Retracted | TurnState::Unqueued) =>
374            {
375                let Some(terminal) = terminal else {
376                    return FoldOutcome::Ignored;
377                };
378                turn.state = TurnState::Settled;
379                turn.terminal = Some(terminal.to_owned());
380                turn.completion = Some(Value::Object(params.clone()));
381                if self.active_turn.as_deref() == Some(id) {
382                    self.active_turn = None;
383                }
384            }
385            // As in the TypeScript and Python folds, an accepted retract or a
386            // reclaim applies from any state: on the wire, a turn that ran and
387            // was then retracted settles first and the accepted retract follows.
388            // Neither is a terminal, so a terminal the turn already carries stays
389            // as sent. A declined retract never reaches this arm (above).
390            "turn/retracted" | "turn/unqueued" => {
391                let Some(command_id) = command_id else {
392                    return FoldOutcome::Ignored;
393                };
394                turn.command_id = Some(command_id.to_owned());
395                turn.state = if method == "turn/retracted" {
396                    TurnState::Retracted
397                } else {
398                    TurnState::Unqueued
399                };
400                if self.active_turn.as_deref() == Some(id) {
401                    self.active_turn = None;
402                }
403            }
404            _ => return FoldOutcome::Ignored,
405        }
406        FoldOutcome::Applied
407    }
408
409    fn delivery_gap(&mut self, params: &Map<String, Value>) -> FoldOutcome {
410        let (Some(after), Some(next)) = (string(params, "after"), string(params, "next")) else {
411            return FoldOutcome::Ignored;
412        };
413        match self.gap.as_mut() {
414            None => {
415                self.gap = Some(DeliveryGap {
416                    after: after.to_owned(),
417                    next: next.to_owned(),
418                });
419                self.gap_targets = HashSet::from([next.to_owned()]);
420                FoldOutcome::Applied
421            }
422            // A later gap while one is pending keeps the first `after` and takes
423            // the newest `next`, contiguous or not, as the `Session` gap walk
424            // and the TypeScript fold do. Keeping only the first range would
425            // report current while the later hole's events never arrived. A
426            // `next` already named while this gap is pending is a stale frame
427            // and changes nothing, as in the walk.
428            Some(gap) if self.gap_targets.insert(next.to_owned()) => {
429                gap.next = next.to_owned();
430                FoldOutcome::Applied
431            }
432            Some(_) => FoldOutcome::Ignored,
433        }
434    }
435}
436fn request(store: &mut Requests, params: &Map<String, Value>, key: &str) -> FoldOutcome {
437    applied(string(params, key).is_some_and(|id| store.request(id, params)))
438}
439fn resolve(store: &mut Requests, params: &Map<String, Value>, key: &str) -> FoldOutcome {
440    string(params, key).map_or(FoldOutcome::Ignored, |id| FoldOutcome::Resolution {
441        first: store.resolve(id, params),
442    })
443}
444const fn applied(applied: bool) -> FoldOutcome {
445    if applied {
446        FoldOutcome::Applied
447    } else {
448        FoldOutcome::Ignored
449    }
450}
451fn string<'a>(params: &'a Map<String, Value>, key: &str) -> Option<&'a str> {
452    params.get(key).and_then(Value::as_str)
453}
454
455fn is_state_family(method: &str) -> bool {
456    matches!(
457        method,
458        "session/modelChanged"
459            | "session/reasoningEffortChanged"
460            | "session/goalChanged"
461            | "session/todoListChanged"
462            | "session/branchChanged"
463            | "session/tokenUsage"
464            | "session/contextUsage"
465            | "session/approvalModeChanged"
466            | "session/nameChanged"
467    )
468}
469
470#[cfg(test)]
471mod tests {
472    use serde_json::json;
473
474    use super::*;
475
476    fn event(method: &str, params: Value) -> Notification {
477        Notification {
478            jsonrpc: crate::msp::JsonRpcVersion::V2,
479            method: method.to_owned(),
480            params: params.as_object().cloned(),
481            emitted_at_ms: None,
482        }
483    }
484
485    /// A lost fold applies
486    /// nothing, question events included, even after a re-open, so a frame
487    /// that races past the router's failure check still cannot fold.
488    #[test]
489    fn a_lost_fold_applies_nothing_even_after_a_reopen() {
490        let question = |id: &str| {
491            event(
492                "userInput/requested",
493                json!({"sessionId": "session-1", "userInputId": id}),
494            )
495        };
496        let mut fold = SessionFold::new("session-1");
497        fold.mark_reopened();
498        assert_ne!(fold.apply(&question("input-before")), FoldOutcome::Ignored);
499        fold.mark_lost();
500        assert_eq!(fold.apply(&question("input-after")), FoldOutcome::Ignored);
501        assert_eq!(
502            fold.apply(&event(
503                "item/completed",
504                json!({"sessionId": "session-1", "item": {"itemId": "item-1", "revision": 1}})
505            )),
506            FoldOutcome::Ignored
507        );
508        assert_eq!(fold.pending_user_inputs().len(), 1);
509        assert!(fold.items().is_empty());
510    }
511
512    /// A re-opened fold keeps applying question
513    /// events only, so approvals stay stopped with items, turns and state: an
514    /// approval pending at the re-open neither updates nor resolves.
515    #[test]
516    fn a_reopened_fold_ignores_approval_events() {
517        let approval = |method: &str, id: &str| {
518            event(method, json!({"sessionId": "session-1", "approvalId": id}))
519        };
520        let mut fold = SessionFold::new("session-1");
521        assert_eq!(
522            fold.apply(&approval("approval/requested", "approval-held")),
523            FoldOutcome::Applied
524        );
525        fold.mark_reopened();
526        for method in [
527            "approval/requested",
528            "approval/updated",
529            "approval/resolved",
530        ] {
531            assert_eq!(
532                fold.apply(&approval(method, "approval-new")),
533                FoldOutcome::Ignored,
534                "{method} for a new approval"
535            );
536        }
537        assert_eq!(
538            fold.apply(&approval("approval/updated", "approval-held")),
539            FoldOutcome::Ignored
540        );
541        assert_eq!(
542            fold.apply(&approval("approval/resolved", "approval-held")),
543            FoldOutcome::Ignored
544        );
545        let pending = fold.pending_approvals();
546        assert_eq!(pending.len(), 1);
547        assert_eq!(pending[0].approval_id, "approval-held");
548        assert!(pending[0].latest_update.is_none());
549        assert!(fold.resolved_approvals().is_empty());
550    }
551}