mobius 0.10.0

A small, modular Rust framework for building coding agents
Documentation
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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
//! Durable session, Swarm, and global notes for agent self-improvement.

use std::borrow::Cow;
use std::collections::BTreeSet;
use std::sync::Arc;
use std::time::{SystemTime, UNIX_EPOCH};

use serde::{Deserialize, Serialize};
use tokio::sync::Mutex;
use uuid::Uuid;

use super::bots::BotsBackend;
use super::manifest::MiddlewareManifest;
use super::tools::{Catalog, labeled_tool_heading, render_tool_event};
use super::{
    ActiveCommandContext, Middleware, MiddlewareCommandContext, MiddlewareCommandOutput,
    ModelContext, PromptSection, RuntimeContext, SessionStartContext, SessionStartSource,
    SubmissionResult,
};
use crate::backend::checkpoint::{CheckpointStore, ContextRewriteReason};
use crate::protocol::{
    EventMsg, FrontendBlock, FrontendCommand, FrontendContribution, FrontendTone,
};
use crate::{BoxFuture, Error, Result};

mod text {
    include!(concat!(
        env!("OUT_DIR"),
        "/src_middleware_scratchpad_text.rs"
    ));
}

mod presentation;
mod projection;
mod tools;

#[cfg(test)]
use presentation::action_list_item;
use presentation::{
    command_confirmation, format_snapshot, global_widget, parse_scope, publish_widgets,
    surface_widgets, swarm_widget, usage, widget_events,
};
pub(crate) use projection::is_projection_item;
use projection::{next_projection, scratchpad_message, without_projection_items};
use tools::{PromoteScratchpad, WriteScratchpad};

const SESSION_STATE_KEY: &str = "scratchpad.v1";
const GLOBAL_SCOPE: &str = "scratchpad.global";
const GLOBAL_STATE_KEY: &str = "entries.v1";
const SWARM_SCOPE_PREFIX: &str = "scratchpad.swarm:";
const SWARM_STATE_KEY: &str = "entries.v1";
const MAX_NOTES: usize = 20;
const MAX_NOTE_BYTES: usize = 500;
const MAX_INJECTION_BYTES: usize = 4 * 1024;
const PROJECTION_FIELD: &str = "_mobius_scratchpad_projection";
const BASELINE_KIND: &str = "scratchpad_baseline";
const DELTA_KIND: &str = "scratchpad_delta";

/// Configuration and presentation metadata for durable agent notes.
pub const MANIFEST: MiddlewareManifest = MiddlewareManifest {
    id: "scratchpad",
    label: text::MANIFEST_LABEL,
    description: text::MANIFEST_DESCRIPTION,
    required: false,
    default_enabled: true,
    settings: &[],
};

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct Entry {
    id: String,
    note: String,
    basis: Basis,
    created_at: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
enum Basis {
    AgentObservation,
    UserConfirmed,
}

impl Basis {
    const fn strength(&self) -> u8 {
        match self {
            Self::AgentObservation => 0,
            Self::UserConfirmed => 1,
        }
    }
}

#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct Snapshot {
    session: Vec<Entry>,
    #[serde(deserialize_with = "deserialize_required_option")]
    swarm: Option<Vec<Entry>>,
    global: Vec<Entry>,
}

fn deserialize_required_option<'de, D>(
    deserializer: D,
) -> std::result::Result<Option<Vec<Entry>>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    Option::deserialize(deserializer)
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Scope {
    Session,
    Swarm,
    Global,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "snake_case")]
enum PromotionTarget {
    Global,
    Swarm,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum WriteOutcome {
    Added,
    Updated,
    Existing,
}

#[derive(Clone)]
struct SwarmScope {
    backend: Arc<dyn BotsBackend>,
    bot_id: String,
}

impl SwarmScope {
    async fn resolve(&self) -> Result<Option<String>> {
        self.backend.scratchpad_scope(&self.bot_id).await
    }
}

/// Cloneable scratchpad persistence shared by agent runtimes and management commands.
#[derive(Clone)]
pub struct ScratchpadStore {
    checkpoints: Arc<dyn CheckpointStore>,
    // ponytail: one process-wide lock keeps whole-value writes correct; split by scope only if
    // measured contention justifies the extra lock registry.
    access: Arc<Mutex<()>>,
}

impl ScratchpadStore {
    /// Wraps one tenant-scoped checkpoint store with serialized note mutations.
    #[must_use]
    pub fn new(checkpoints: Arc<dyn CheckpointStore>) -> Self {
        Self {
            checkpoints,
            access: Arc::new(Mutex::new(())),
        }
    }

    async fn lock_access(&self) -> tokio::sync::MutexGuard<'_, ()> {
        self.access.lock().await
    }

    fn try_lock_access(&self) -> Option<tokio::sync::MutexGuard<'_, ()>> {
        self.access.try_lock().ok()
    }

    async fn snapshot(&self, session_id: &str, swarm_id: Option<&str>) -> Result<Snapshot> {
        let access = self.lock_access().await;
        self.snapshot_locked(session_id, swarm_id, &access).await
    }

    async fn snapshot_locked(
        &self,
        session_id: &str,
        swarm_id: Option<&str>,
        _access: &tokio::sync::MutexGuard<'_, ()>,
    ) -> Result<Snapshot> {
        Ok(Snapshot {
            session: self.load(Scope::Session, session_id).await?,
            swarm: match swarm_id {
                Some(swarm_id) => Some(self.load(Scope::Swarm, swarm_id).await?),
                None => None,
            },
            global: self.load(Scope::Global, GLOBAL_SCOPE).await?,
        })
    }

    /// Returns the persisted gateway-wide scratchpad management surface.
    pub async fn global_contribution(&self) -> Result<FrontendContribution> {
        let access = self.lock_access().await;
        self.global_contribution_locked(&access).await
    }

    /// Adds one user-confirmed gateway-wide note and returns its refreshed surface.
    pub async fn add_global(&self, note: &str) -> Result<FrontendContribution> {
        let note = canonical_note(note).map_err(Error::Tool)?;
        let access = self.lock_access().await;
        let mut entries = self.load(Scope::Global, GLOBAL_SCOPE).await?;
        let outcome = insert(&mut entries, note, Basis::UserConfirmed)?;
        if outcome != WriteOutcome::Existing {
            self.save(Scope::Global, GLOBAL_SCOPE, &entries).await?;
        }
        self.global_contribution_locked(&access).await
    }

    /// Edits one gateway-wide note and returns the refreshed management surface.
    pub async fn edit_global(&self, id: &str, note: &str) -> Result<FrontendContribution> {
        validate_id(id).map_err(Error::Tool)?;
        let access = self.lock_access().await;
        self.edit_locked(GLOBAL_SCOPE, None, Scope::Global, id, note, &access)
            .await?;
        self.global_contribution_locked(&access).await
    }

    /// Forgets one gateway-wide note and returns the refreshed management surface.
    pub async fn forget_global(&self, id: &str) -> Result<FrontendContribution> {
        validate_id(id).map_err(Error::Tool)?;
        let access = self.lock_access().await;
        self.forget_locked(GLOBAL_SCOPE, None, Scope::Global, id, &access)
            .await?;
        self.global_contribution_locked(&access).await
    }

    /// Returns the persisted management surface for one stable Swarm.
    pub async fn swarm_contribution(&self, swarm_id: &str) -> Result<FrontendContribution> {
        validate_swarm_id(swarm_id).map_err(Error::Tool)?;
        let access = self.lock_access().await;
        self.swarm_contribution_locked(swarm_id, &access).await
    }

    /// Adds one user-confirmed Swarm note and returns its refreshed surface.
    pub async fn add_swarm(&self, swarm_id: &str, note: &str) -> Result<FrontendContribution> {
        validate_swarm_id(swarm_id).map_err(Error::Tool)?;
        let note = canonical_note(note).map_err(Error::Tool)?;
        let access = self.lock_access().await;
        let mut entries = self.load(Scope::Swarm, swarm_id).await?;
        let outcome = insert(&mut entries, note, Basis::UserConfirmed)?;
        if outcome != WriteOutcome::Existing {
            self.save(Scope::Swarm, swarm_id, &entries).await?;
        }
        self.swarm_contribution_locked(swarm_id, &access).await
    }

    /// Edits one user-confirmed Swarm note and returns its refreshed surface.
    pub async fn edit_swarm(
        &self,
        swarm_id: &str,
        id: &str,
        note: &str,
    ) -> Result<FrontendContribution> {
        validate_swarm_id(swarm_id).map_err(Error::Tool)?;
        validate_id(id).map_err(Error::Tool)?;
        let access = self.lock_access().await;
        self.edit_locked(swarm_id, Some(swarm_id), Scope::Swarm, id, note, &access)
            .await?;
        self.swarm_contribution_locked(swarm_id, &access).await
    }

    /// Forgets one Swarm note and returns its refreshed management surface.
    pub async fn forget_swarm(&self, swarm_id: &str, id: &str) -> Result<FrontendContribution> {
        validate_swarm_id(swarm_id).map_err(Error::Tool)?;
        validate_id(id).map_err(Error::Tool)?;
        let access = self.lock_access().await;
        self.forget_locked(swarm_id, Some(swarm_id), Scope::Swarm, id, &access)
            .await?;
        self.swarm_contribution_locked(swarm_id, &access).await
    }

    /// Clears notes owned by a permanently disbanded Swarm.
    pub async fn clear_swarm(&self, swarm_id: &str) -> Result<()> {
        validate_swarm_id(swarm_id).map_err(Error::Tool)?;
        let _access = self.lock_access().await;
        self.save(Scope::Swarm, swarm_id, &[]).await
    }

    async fn global_contribution_locked(
        &self,
        _access: &tokio::sync::MutexGuard<'_, ()>,
    ) -> Result<FrontendContribution> {
        let entries = self.load(Scope::Global, GLOBAL_SCOPE).await?;
        Ok(FrontendContribution {
            capability: MANIFEST.id.into(),
            widgets: vec![global_widget(&entries)],
            ..FrontendContribution::default()
        })
    }

    async fn swarm_contribution_locked(
        &self,
        swarm_id: &str,
        _access: &tokio::sync::MutexGuard<'_, ()>,
    ) -> Result<FrontendContribution> {
        let entries = self.load(Scope::Swarm, swarm_id).await?;
        Ok(FrontendContribution {
            capability: MANIFEST.id.into(),
            widgets: vec![swarm_widget(&entries)],
            ..FrontendContribution::default()
        })
    }

    async fn write_session(&self, session_id: &str, note: &str) -> Result<WriteOutcome> {
        let note = canonical_note(note).map_err(Error::Tool)?;
        let _guard = self.access.lock().await;
        let mut entries = self.load(Scope::Session, session_id).await?;
        let outcome = insert(&mut entries, note, Basis::AgentObservation)?;
        if outcome != WriteOutcome::Existing {
            self.save(Scope::Session, session_id, &entries).await?;
        }
        Ok(outcome)
    }

    async fn promote_note(
        &self,
        session_id: &str,
        swarm_id: Option<&str>,
        note: &str,
        target: PromotionTarget,
    ) -> Result<WriteOutcome> {
        let note = canonical_note(note).map_err(Error::Tool)?;
        let _guard = self.access.lock().await;
        let session = self.load(Scope::Session, session_id).await?;
        let entry = session
            .into_iter()
            .find(|entry| entry.note == note)
            .ok_or_else(|| {
                Error::Tool("the exact note no longer exists in this session scratchpad".into())
            })?;
        self.promote_locked(swarm_id, entry, false, target).await
    }

    #[cfg(test)]
    async fn promote_id(
        &self,
        session_id: &str,
        swarm_id: Option<&str>,
        id: &str,
        target: PromotionTarget,
    ) -> Result<WriteOutcome> {
        validate_id(id).map_err(Error::Tool)?;
        let access = self.lock_access().await;
        self.promote_id_locked(session_id, swarm_id, id, target, &access)
            .await
    }

    async fn promote_id_locked(
        &self,
        session_id: &str,
        swarm_id: Option<&str>,
        id: &str,
        target: PromotionTarget,
        _access: &tokio::sync::MutexGuard<'_, ()>,
    ) -> Result<WriteOutcome> {
        let session = self.load(Scope::Session, session_id).await?;
        let entry = session
            .iter()
            .find(|entry| entry.id == id)
            .cloned()
            .ok_or_else(|| Error::Tool("the session scratchpad note no longer exists".into()))?;
        self.promote_locked(swarm_id, entry, true, target).await
    }

    async fn promote_locked(
        &self,
        swarm_id: Option<&str>,
        entry: Entry,
        user_confirmed: bool,
        target: PromotionTarget,
    ) -> Result<WriteOutcome> {
        let (scope, owner_id) = promotion_location(target, swarm_id)?;
        let mut entries = self.load(scope, owner_id).await?;
        let basis = match entry.basis {
            Basis::AgentObservation if user_confirmed => Basis::UserConfirmed,
            basis => basis,
        };
        let outcome = insert(&mut entries, entry.note, basis)?;
        if outcome != WriteOutcome::Existing {
            self.save(scope, owner_id, &entries).await?;
        }
        Ok(outcome)
    }

    async fn forget_locked(
        &self,
        session_id: &str,
        swarm_id: Option<&str>,
        scope: Scope,
        id: &str,
        _access: &tokio::sync::MutexGuard<'_, ()>,
    ) -> Result<()> {
        let owner_id = scope_owner(scope, session_id, swarm_id)?;
        let mut entries = self.load(scope, owner_id).await?;
        let previous_len = entries.len();
        entries.retain(|entry| entry.id != id);
        if entries.len() == previous_len {
            return Err(Error::Tool("the scratchpad note no longer exists".into()));
        }
        self.save(scope, owner_id, &entries).await
    }

    #[cfg(test)]
    async fn edit(
        &self,
        session_id: &str,
        swarm_id: Option<&str>,
        scope: Scope,
        id: &str,
        note: &str,
    ) -> Result<()> {
        validate_id(id).map_err(Error::Tool)?;
        let access = self.lock_access().await;
        self.edit_locked(session_id, swarm_id, scope, id, note, &access)
            .await
    }

    async fn edit_locked(
        &self,
        session_id: &str,
        swarm_id: Option<&str>,
        scope: Scope,
        id: &str,
        note: &str,
        _access: &tokio::sync::MutexGuard<'_, ()>,
    ) -> Result<()> {
        let note = canonical_note(note).map_err(Error::Tool)?;
        let owner_id = scope_owner(scope, session_id, swarm_id)?;
        let mut entries = self.load(scope, owner_id).await?;
        if entries
            .iter()
            .any(|entry| entry.id != id && entry.note == note)
        {
            return Err(Error::Tool(
                "the scratchpad already contains that note".into(),
            ));
        }
        let entry = entries
            .iter_mut()
            .find(|entry| entry.id == id)
            .ok_or_else(|| Error::Tool("the scratchpad note no longer exists".into()))?;
        entry.note = note;
        entry.basis = Basis::UserConfirmed;
        self.save(scope, owner_id, &entries).await
    }

    async fn load(&self, scope: Scope, session_id: &str) -> Result<Vec<Entry>> {
        let (scope, key) = storage_location(scope, session_id);
        let mut entries: Vec<Entry> = self
            .checkpoints
            .load_state(scope.as_ref(), key)
            .await?
            .map(serde_json::from_value)
            .transpose()
            .map_err(|error| Error::Checkpoint(format!("invalid scratchpad state: {error}")))?
            .unwrap_or_default();
        validate_entries(&mut entries)
            .map_err(|error| Error::Checkpoint(format!("invalid scratchpad state: {error}")))?;
        Ok(entries)
    }

    async fn save(&self, scope: Scope, session_id: &str, entries: &[Entry]) -> Result<()> {
        let (scope, key) = storage_location(scope, session_id);
        self.checkpoints
            .save_state(scope.as_ref(), key, &serde_json::to_value(entries)?)
            .await
    }
}

/// Adds bounded durable notes without exposing persistence details to the agent loop.
#[derive(Clone)]
pub struct Scratchpad {
    store: ScratchpadStore,
    swarm: SwarmScope,
    agent_enabled: bool,
}

impl Scratchpad {
    /// Creates scratchpad middleware for one Bot backed by shared durable stores.
    #[must_use]
    pub fn new(
        store: ScratchpadStore,
        swarm: Arc<dyn BotsBackend>,
        bot_id: impl Into<String>,
    ) -> Self {
        Self {
            store,
            swarm: SwarmScope {
                backend: swarm,
                bot_id: bot_id.into(),
            },
            agent_enabled: true,
        }
    }

    /// Controls agent access while retaining the read-only management surface.
    #[must_use]
    pub fn agent_enabled(mut self, enabled: bool) -> Self {
        self.agent_enabled = enabled;
        self
    }

    async fn snapshot(&self, session_id: &str) -> Result<Snapshot> {
        let swarm_id = self.swarm.resolve().await?;
        self.store.snapshot(session_id, swarm_id.as_deref()).await
    }
}

impl Scratchpad {
    async fn execute_command_locked(
        &self,
        session_id: &str,
        command: &str,
        arguments: &str,
        input: Option<&str>,
        swarm_id: Option<&str>,
        access: tokio::sync::MutexGuard<'_, ()>,
    ) -> Result<MiddlewareCommandOutput> {
        let _access = access;
        if command != "scratchpad" {
            return Err(Error::Unknown(format!("scratchpad command `{command}`")));
        }
        let mut arguments = arguments.split_whitespace();
        let operation = arguments.next().unwrap_or("read");
        if !self.agent_enabled && !matches!(operation, "read" | "refresh") {
            return Err(Error::Tool("scratchpad is disabled for this chat".into()));
        }
        match operation {
            "read" if arguments.next().is_none() && input.is_none() => {
                let snapshot = self
                    .store
                    .snapshot_locked(session_id, swarm_id, &_access)
                    .await?;
                Ok(MiddlewareCommandOutput::render(
                    self.name(),
                    format_snapshot(&snapshot),
                    FrontendTone::Neutral,
                ))
            }
            "refresh" if arguments.next().is_none() && input.is_none() => {
                let snapshot = self
                    .store
                    .snapshot_locked(session_id, swarm_id, &_access)
                    .await?;
                Ok(MiddlewareCommandOutput::events(widget_events(&snapshot)))
            }
            "promote" if input.is_none() => {
                match (arguments.next(), arguments.next(), arguments.next()) {
                    (Some(target), Some(id), None) => {
                        let Some(target) = parse_promotion_target(target) else {
                            return Ok(usage());
                        };
                        let outcome = self
                            .store
                            .promote_id_locked(session_id, swarm_id, id, target, &_access)
                            .await?;
                        let snapshot = self
                            .store
                            .snapshot_locked(session_id, swarm_id, &_access)
                            .await?;
                        Ok(command_confirmation(target, outcome, &snapshot))
                    }
                    _ => Ok(usage()),
                }
            }
            "edit" => match (arguments.next(), arguments.next(), arguments.next(), input) {
                (Some(scope), Some(id), None, Some(note)) => {
                    let Some(scope) = parse_scope(scope) else {
                        return Ok(usage());
                    };
                    self.store
                        .edit_locked(session_id, swarm_id, scope, id, note, &_access)
                        .await?;
                    let snapshot = self
                        .store
                        .snapshot_locked(session_id, swarm_id, &_access)
                        .await?;
                    let mut events = widget_events(&snapshot);
                    events.extend(
                        MiddlewareCommandOutput::render(
                            self.name(),
                            text::MESSAGE_UPDATED,
                            FrontendTone::Success,
                        )
                        .events,
                    );
                    Ok(MiddlewareCommandOutput::events(events))
                }
                _ => Ok(usage()),
            },
            "forget" if input.is_none() => {
                match (arguments.next(), arguments.next(), arguments.next()) {
                    (Some(scope), Some(id), None) => {
                        let Some(scope) = parse_scope(scope) else {
                            return Ok(usage());
                        };
                        self.store
                            .forget_locked(session_id, swarm_id, scope, id, &_access)
                            .await?;
                        let snapshot = self
                            .store
                            .snapshot_locked(session_id, swarm_id, &_access)
                            .await?;
                        let mut events = widget_events(&snapshot);
                        events.extend(
                            MiddlewareCommandOutput::render(
                                self.name(),
                                text::MESSAGE_FORGOT,
                                FrontendTone::Success,
                            )
                            .events,
                        );
                        Ok(MiddlewareCommandOutput::events(events))
                    }
                    _ => Ok(usage()),
                }
            }
            _ => Ok(usage()),
        }
    }
}

impl Middleware for Scratchpad {
    fn name(&self) -> &'static str {
        MANIFEST.id
    }

    fn register(&self, catalog: &mut Catalog, runtime: &RuntimeContext) -> Result<()> {
        if !self.agent_enabled {
            return Ok(());
        }
        catalog.register(Arc::new(WriteScratchpad {
            store: self.store.clone(),
            swarm: self.swarm.clone(),
            session_id: runtime.session_id.clone(),
            frontend: Arc::clone(&runtime.frontend),
        }))?;
        catalog.register(Arc::new(PromoteScratchpad {
            store: self.store.clone(),
            swarm: self.swarm.clone(),
            session_id: runtime.session_id.clone(),
            frontend: Arc::clone(&runtime.frontend),
        }))
    }

    fn prompt_section(&self, _runtime: &RuntimeContext) -> Result<Option<PromptSection>> {
        Ok(self
            .agent_enabled
            .then(|| PromptSection::new(text::PROMPT_MAIN)))
    }

    fn frontend(&self) -> FrontendContribution {
        FrontendContribution {
            capability: self.name().into(),
            accepts_file_attachments: false,
            count: None,
            commands: vec![FrontendCommand {
                name: "scratchpad".into(),
                arguments: text::COMMAND_ARGUMENTS.into(),
                description: text::COMMAND_DESCRIPTION.into(),
                requires_idle: false,
            }],
            widgets: surface_widgets(&Snapshot::default()),
            references: Vec::new(),
        }
    }

    fn render(&self, event: &EventMsg, _session_id: &str) -> Option<FrontendBlock> {
        render_tool_event(
            event,
            |name| matches!(name, "write_scratchpad" | "promote_scratchpad"),
            |name, arguments| match name {
                "write_scratchpad" => {
                    labeled_tool_heading(text::RENDER_REMEMBER, "note", arguments)
                }
                "promote_scratchpad" => {
                    labeled_tool_heading(text::RENDER_PROMOTE, "note", arguments)
                }
                _ => unreachable!("renderer is guarded by the owned tool names"),
            },
        )
    }

    fn session_start<'a>(
        &'a self,
        context: &'a mut SessionStartContext<'_>,
    ) -> BoxFuture<'a, Result<()>> {
        Box::pin(async move {
            let snapshot = self.snapshot(&context.runtime.session_id).await?;
            if self.agent_enabled
                && matches!(
                    context.source(),
                    SessionStartSource::Startup | SessionStartSource::Compact
                )
                && !context.input.iter().any(is_projection_item)
                && let Some(item) = scratchpad_message(&snapshot)
            {
                context.push_input(item);
            }
            if context.source() != SessionStartSource::Compact {
                publish_widgets(&context.runtime.frontend, &snapshot)?;
            }
            Ok(())
        })
    }

    fn command<'a>(
        &'a self,
        context: MiddlewareCommandContext<'a>,
    ) -> BoxFuture<'a, Result<MiddlewareCommandOutput>> {
        Box::pin(async move {
            let swarm_id = self.swarm.resolve().await?;
            let access = self.store.lock_access().await;
            self.execute_command_locked(
                context.session_id,
                context.command,
                context.arguments,
                context.input,
                swarm_id.as_deref(),
                access,
            )
            .await
        })
    }

    fn active_command<'a>(
        &'a self,
        context: &'a mut ActiveCommandContext<'_>,
    ) -> BoxFuture<'a, Result<Option<SubmissionResult>>> {
        Box::pin(async move {
            let swarm_id = self.swarm.resolve().await?;
            let Some(access) = self.store.try_lock_access() else {
                return Ok(None);
            };
            let output = self
                .execute_command_locked(
                    context.session_id,
                    context.command,
                    context.arguments,
                    context.input,
                    swarm_id.as_deref(),
                    access,
                )
                .await?;
            context
                .events
                .extend(output.events.into_iter().map(EventMsg::Frontend));
            Ok(Some(SubmissionResult::Handled))
        })
    }

    fn pre_model<'a>(&'a self, context: &'a mut ModelContext<'_>) -> BoxFuture<'a, Result<()>> {
        Box::pin(async move {
            if !self.agent_enabled {
                if let Some(input) = without_projection_items(context.input()) {
                    context.rewrite_input(ContextRewriteReason::Scratchpad, input)?;
                }
                return Ok(());
            }
            let snapshot = self.snapshot(context.session_id).await?;
            if let Some(item) = next_projection(context.input(), &snapshot)? {
                context.append_model_input(item);
            }
            Ok(())
        })
    }
}

fn storage_location(scope: Scope, owner_id: &str) -> (Cow<'_, str>, &'static str) {
    match scope {
        Scope::Session => (Cow::Borrowed(owner_id), SESSION_STATE_KEY),
        Scope::Swarm => (
            Cow::Owned(format!("{SWARM_SCOPE_PREFIX}{owner_id}")),
            SWARM_STATE_KEY,
        ),
        Scope::Global => (Cow::Borrowed(GLOBAL_SCOPE), GLOBAL_STATE_KEY),
    }
}

fn promotion_location(target: PromotionTarget, swarm_id: Option<&str>) -> Result<(Scope, &str)> {
    match target {
        PromotionTarget::Global => Ok((Scope::Global, GLOBAL_SCOPE)),
        PromotionTarget::Swarm => swarm_id
            .map(|swarm_id| (Scope::Swarm, swarm_id))
            .ok_or_else(|| Error::Tool("this Bot is not currently in a swarm".into())),
    }
}

fn scope_owner<'a>(
    scope: Scope,
    session_id: &'a str,
    swarm_id: Option<&'a str>,
) -> Result<&'a str> {
    match scope {
        Scope::Session => Ok(session_id),
        Scope::Swarm => {
            swarm_id.ok_or_else(|| Error::Tool("this Bot is not currently in a swarm".into()))
        }
        Scope::Global => Ok(GLOBAL_SCOPE),
    }
}

fn parse_promotion_target(target: &str) -> Option<PromotionTarget> {
    match target {
        "global" => Some(PromotionTarget::Global),
        "swarm" => Some(PromotionTarget::Swarm),
        _ => None,
    }
}

fn insert(entries: &mut Vec<Entry>, note: String, basis: Basis) -> Result<WriteOutcome> {
    if let Some(entry) = entries.iter_mut().find(|entry| entry.note == note) {
        if basis.strength() > entry.basis.strength() {
            entry.basis = basis;
            return Ok(WriteOutcome::Updated);
        }
        return Ok(WriteOutcome::Existing);
    }
    if entries.len() >= MAX_NOTES {
        return Err(Error::Tool(format!(
            "scratchpad already contains the maximum {MAX_NOTES} notes"
        )));
    }
    entries.push(Entry {
        id: Uuid::new_v4().to_string(),
        note,
        basis,
        created_at: created_at()?,
    });
    Ok(WriteOutcome::Added)
}

fn validate_entries(entries: &mut [Entry]) -> std::result::Result<(), String> {
    if entries.len() > MAX_NOTES {
        return Err(format!("note count exceeds {MAX_NOTES}"));
    }
    let mut ids = BTreeSet::new();
    let mut notes = BTreeSet::new();
    for entry in entries {
        validate_id(&entry.id)?;
        let note = canonical_note(&entry.note)?;
        if note != entry.note {
            return Err("stored note is not canonical".into());
        }
        if !ids.insert(entry.id.as_str()) {
            return Err("duplicate note ID".into());
        }
        if !notes.insert(entry.note.as_str()) {
            return Err("duplicate note content".into());
        }
        let created_at = entry
            .created_at
            .parse::<u64>()
            .map_err(|_| "invalid scratchpad creation time")?;
        if created_at.to_string() != entry.created_at {
            return Err("scratchpad creation time is not canonical".into());
        }
    }
    Ok(())
}

fn created_at() -> Result<String> {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|duration| duration.as_secs().to_string())
        .map_err(|error| Error::Tool(format!("system clock is before the Unix epoch: {error}")))
}

fn validate_id(id: &str) -> std::result::Result<(), String> {
    Uuid::parse_str(id)
        .map(|_| ())
        .map_err(|_| "invalid scratchpad note ID".into())
}

fn validate_swarm_id(id: &str) -> std::result::Result<(), String> {
    Uuid::parse_str(id)
        .map(|_| ())
        .map_err(|_| "invalid Swarm ID".into())
}

fn canonical_note(note: &str) -> std::result::Result<String, String> {
    let note = note.replace("\r\n", "\n").replace('\r', "\n");
    let note = note.trim();
    if note.is_empty() || note.len() > MAX_NOTE_BYTES {
        return Err(format!(
            "scratchpad note must be 1–{MAX_NOTE_BYTES} UTF-8 bytes"
        ));
    }
    Ok(note.into())
}

#[cfg(test)]
mod tests;