meerkat-mob 0.7.29

Multi-agent orchestration runtime for Meerkat
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
//! MobStorage bundle.
//!
//! Groups the event store with a session store for a mob's isolated storage.

#[cfg(not(target_arch = "wasm32"))]
use crate::store::SqliteMobStores;
use crate::store::{
    InMemoryMobEventStore, InMemoryMobRunStore, InMemoryMobRuntimeMetadataStore,
    InMemoryMobSpecStore, InMemoryRealmProfileStore, MobEventStore, MobRunStore,
    MobRuntimeMetadataStore, MobSpecStore, RealmProfileStore, authority_validating_mob_run_store,
};
#[cfg(not(target_arch = "wasm32"))]
use std::path::Path;
use std::sync::Arc;

/// Storage bundle for a mob.
///
/// Contains both the mob event store (structural state) and session
/// store (for meerkat sessions). Each mob has its own isolated storage.
pub struct MobStorage {
    /// Event store for mob structural events.
    pub(crate) events: Arc<dyn MobEventStore>,
    /// Flow run persistence store.
    pub(crate) runs: Arc<dyn MobRunStore>,
    /// Flow spec persistence store.
    pub(crate) specs: Arc<dyn MobSpecStore>,
    /// Runtime metadata store for supervisor authority and compatibility projections.
    pub(crate) runtime_metadata: Arc<dyn MobRuntimeMetadataStore>,
    /// Realm-scoped reusable profile store.
    pub(crate) realm_profiles: Option<Arc<dyn RealmProfileStore>>,
}

impl MobStorage {
    /// Create a storage bundle with in-memory stores (for tests and ephemeral mobs).
    pub fn in_memory() -> Self {
        let (runs, specs) = Self::in_memory_flow_stores();
        Self {
            events: Arc::new(InMemoryMobEventStore::new()),
            runs,
            specs,
            runtime_metadata: Arc::new(InMemoryMobRuntimeMetadataStore::new()),
            realm_profiles: Some(Arc::new(InMemoryRealmProfileStore::new())),
        }
    }

    /// Create in-memory run/spec stores for flow persistence.
    pub fn in_memory_flow_stores() -> (Arc<dyn MobRunStore>, Arc<dyn MobSpecStore>) {
        (
            authority_validating_mob_run_store(Arc::new(InMemoryMobRunStore::new())),
            Arc::new(InMemoryMobSpecStore::new()),
        )
    }

    /// Build a full storage bundle from a custom event store and in-memory flow stores.
    pub fn with_events(events: Arc<dyn MobEventStore>) -> Self {
        let (runs, specs) = Self::in_memory_flow_stores();
        Self {
            events,
            runs,
            specs,
            runtime_metadata: Arc::new(InMemoryMobRuntimeMetadataStore::new()),
            realm_profiles: Some(Arc::new(InMemoryRealmProfileStore::new())),
        }
    }

    /// Build a storage bundle from an event store plus an existing runtime metadata store.
    pub fn with_events_and_runtime_metadata(
        events: Arc<dyn MobEventStore>,
        runtime_metadata: Arc<dyn MobRuntimeMetadataStore>,
    ) -> Self {
        let (runs, specs) = Self::in_memory_flow_stores();
        Self {
            events,
            runs,
            specs,
            runtime_metadata,
            realm_profiles: Some(Arc::new(InMemoryRealmProfileStore::new())),
        }
    }

    /// Build a storage bundle from custom store implementations.
    pub fn custom(
        events: Arc<dyn MobEventStore>,
        runs: Arc<dyn MobRunStore>,
        specs: Arc<dyn MobSpecStore>,
    ) -> Self {
        Self::custom_with_runtime_metadata(
            events,
            runs,
            specs,
            Arc::new(InMemoryMobRuntimeMetadataStore::new()),
        )
    }

    /// Build a storage bundle from custom store implementations, including runtime metadata.
    pub fn custom_with_runtime_metadata(
        events: Arc<dyn MobEventStore>,
        runs: Arc<dyn MobRunStore>,
        specs: Arc<dyn MobSpecStore>,
        runtime_metadata: Arc<dyn MobRuntimeMetadataStore>,
    ) -> Self {
        Self {
            events,
            runs: authority_validating_mob_run_store(runs),
            specs,
            runtime_metadata,
            realm_profiles: None,
        }
    }

    /// Attach the realm-scoped reusable profile store used by mob runtimes.
    pub fn with_realm_profile_store(
        mut self,
        realm_profiles: Option<Arc<dyn RealmProfileStore>>,
    ) -> Self {
        self.realm_profiles = realm_profiles;
        self
    }

    /// Return whether the structural event log is empty.
    pub async fn is_event_log_empty(&self) -> Result<bool, crate::store::MobStoreError> {
        Ok(self.events.latest_cursor().await? == 0)
    }

    /// Create a storage bundle backed by a single SQLite database file.
    ///
    /// Uses WAL mode — no exclusive file lock is held, so the same path
    /// can be reopened after drop within the same process.
    #[cfg(not(target_arch = "wasm32"))]
    pub fn persistent(path: impl AsRef<Path>) -> Result<Self, crate::MobError> {
        let stores = SqliteMobStores::open(path)?;
        Ok(Self {
            events: Arc::new(stores.event_store()),
            runs: authority_validating_mob_run_store(Arc::new(stores.run_store())),
            specs: Arc::new(stores.spec_store()),
            runtime_metadata: Arc::new(stores.runtime_metadata_store()),
            realm_profiles: Some(Arc::new(stores.realm_profile_store())),
        })
    }
}

impl std::fmt::Debug for MobStorage {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("MobStorage")
            .field("events", &"<dyn MobEventStore>")
            .field("runs", &"<dyn MobRunStore>")
            .field("specs", &"<dyn MobSpecStore>")
            .field("runtime_metadata", &"<dyn MobRuntimeMetadataStore>")
            .field(
                "realm_profiles",
                &self
                    .realm_profiles
                    .as_ref()
                    .map(|_| "<dyn RealmProfileStore>"),
            )
            .finish()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::event::{MobEventKind, NewMobEvent};
    use crate::ids::{FlowId, FrameId, LoopId, LoopInstanceId, MobId, RunId, StepId};
    use crate::run::{
        FailureLedgerEntry, FrameSnapshot, LoopIterationLedgerEntry, LoopSnapshot, MobRun,
        MobRunProvenanceAuthority, MobRunStatus, StepLedgerEntry,
    };
    use crate::store::MobStoreError;
    use std::sync::Mutex;

    struct ForgedRunStore {
        run: Mutex<Option<MobRun>>,
    }

    impl ForgedRunStore {
        fn new(run: Option<MobRun>) -> Self {
            Self {
                run: Mutex::new(run),
            }
        }
    }

    #[async_trait::async_trait]
    impl MobRunStore for ForgedRunStore {
        async fn create_run(&self, run: MobRun) -> Result<(), MobStoreError> {
            *self.run.lock().expect("forged run mutex") = Some(run);
            Ok(())
        }

        async fn get_run(&self, run_id: &RunId) -> Result<Option<MobRun>, MobStoreError> {
            Ok(self
                .run
                .lock()
                .expect("forged run mutex")
                .as_ref()
                .filter(|run| &run.run_id == run_id)
                .cloned())
        }

        async fn list_runs(
            &self,
            mob_id: &MobId,
            flow_id: Option<&FlowId>,
        ) -> Result<Vec<MobRun>, MobStoreError> {
            Ok(self
                .run
                .lock()
                .expect("forged run mutex")
                .as_ref()
                .filter(|run| &run.mob_id == mob_id)
                .filter(|run| flow_id.is_none_or(|flow_id| &run.flow_id == flow_id))
                .cloned()
                .into_iter()
                .collect())
        }

        async fn cas_flow_state_with_authority(
            &self,
            _run_id: &RunId,
            _expected: &crate::run::flow_run::State,
            _next: &crate::run::flow_run::State,
            _authority_inputs: Vec<crate::machines::mob_machine::MobMachineInput>,
        ) -> Result<bool, MobStoreError> {
            Err(MobStoreError::Internal(
                "not implemented in forged store".into(),
            ))
        }

        async fn cas_run_snapshot_with_authority(
            &self,
            _run_id: &RunId,
            _expected_status: MobRunStatus,
            _expected_flow_state: &crate::run::flow_run::State,
            _next_status: MobRunStatus,
            _next_flow_state: &crate::run::flow_run::State,
            _authority_inputs: Vec<crate::machines::mob_machine::MobMachineInput>,
        ) -> Result<bool, MobStoreError> {
            Err(MobStoreError::Internal(
                "not implemented in forged store".into(),
            ))
        }

        async fn append_step_entry_with_authority(
            &self,
            _run_id: &RunId,
            _entry: StepLedgerEntry,
            _authority: MobRunProvenanceAuthority,
        ) -> Result<(), MobStoreError> {
            Err(MobStoreError::Internal(
                "not implemented in forged store".into(),
            ))
        }

        async fn append_step_entry_if_absent_with_authority(
            &self,
            _run_id: &RunId,
            _entry: StepLedgerEntry,
            _authority: MobRunProvenanceAuthority,
        ) -> Result<bool, MobStoreError> {
            Err(MobStoreError::Internal(
                "not implemented in forged store".into(),
            ))
        }

        async fn append_failure_entry_with_authority(
            &self,
            _run_id: &RunId,
            _entry: FailureLedgerEntry,
            _authority: MobRunProvenanceAuthority,
        ) -> Result<(), MobStoreError> {
            Err(MobStoreError::Internal(
                "not implemented in forged store".into(),
            ))
        }

        async fn cas_frame_state_with_authority(
            &self,
            _run_id: &RunId,
            _frame_id: &FrameId,
            _expected: Option<&FrameSnapshot>,
            _next: FrameSnapshot,
            _authority_inputs: Vec<crate::machines::mob_machine::MobMachineInput>,
        ) -> Result<bool, MobStoreError> {
            Err(MobStoreError::Internal(
                "not implemented in forged store".into(),
            ))
        }

        #[allow(clippy::too_many_arguments)]
        async fn cas_grant_node_slot_with_authority(
            &self,
            _run_id: &RunId,
            _expected_run_state: &crate::run::flow_run::State,
            _next_run_state: crate::run::flow_run::State,
            _frame_id: &FrameId,
            _expected_frame: &FrameSnapshot,
            _next_frame: FrameSnapshot,
            _authority_inputs: Vec<crate::machines::mob_machine::MobMachineInput>,
        ) -> Result<bool, MobStoreError> {
            Err(MobStoreError::Internal(
                "not implemented in forged store".into(),
            ))
        }

        #[allow(clippy::too_many_arguments)]
        async fn cas_complete_step_and_record_output_with_authority(
            &self,
            _run_id: &RunId,
            _frame_id: &FrameId,
            _expected_frame: &FrameSnapshot,
            _next_frame: FrameSnapshot,
            _step_output_key: String,
            _step_output: serde_json::Value,
            _loop_context: Option<(&LoopId, u64)>,
            _authority_inputs: Vec<crate::machines::mob_machine::MobMachineInput>,
        ) -> Result<bool, MobStoreError> {
            Err(MobStoreError::Internal(
                "not implemented in forged store".into(),
            ))
        }

        #[allow(clippy::too_many_arguments)]
        async fn cas_start_loop_with_authority(
            &self,
            _run_id: &RunId,
            _loop_instance_id: &LoopInstanceId,
            _expected_run_state: &crate::run::flow_run::State,
            _next_run_state: crate::run::flow_run::State,
            _frame_id: &FrameId,
            _expected_frame: &FrameSnapshot,
            _next_frame: FrameSnapshot,
            _initial_loop: LoopSnapshot,
            _authority_inputs: Vec<crate::machines::mob_machine::MobMachineInput>,
        ) -> Result<bool, MobStoreError> {
            Err(MobStoreError::Internal(
                "not implemented in forged store".into(),
            ))
        }

        #[allow(clippy::too_many_arguments)]
        async fn cas_loop_request_body_frame_with_authority(
            &self,
            _run_id: &RunId,
            _loop_instance_id: &LoopInstanceId,
            _expected_loop: &LoopSnapshot,
            _next_loop: LoopSnapshot,
            _expected_run_state: &crate::run::flow_run::State,
            _next_run_state: crate::run::flow_run::State,
            _authority_inputs: Vec<crate::machines::mob_machine::MobMachineInput>,
        ) -> Result<bool, MobStoreError> {
            Err(MobStoreError::Internal(
                "not implemented in forged store".into(),
            ))
        }

        #[allow(clippy::too_many_arguments)]
        async fn cas_grant_body_frame_start_with_authority(
            &self,
            _run_id: &RunId,
            _loop_instance_id: &LoopInstanceId,
            _expected_loop: &LoopSnapshot,
            _next_loop: LoopSnapshot,
            _frame_id: &FrameId,
            _initial_frame: FrameSnapshot,
            _ledger_entry: LoopIterationLedgerEntry,
            _expected_run_state: &crate::run::flow_run::State,
            _next_run_state: crate::run::flow_run::State,
            _authority_inputs: Vec<crate::machines::mob_machine::MobMachineInput>,
        ) -> Result<bool, MobStoreError> {
            Err(MobStoreError::Internal(
                "not implemented in forged store".into(),
            ))
        }

        #[allow(clippy::too_many_arguments)]
        async fn cas_complete_body_frame_with_authority(
            &self,
            _run_id: &RunId,
            _loop_instance_id: &LoopInstanceId,
            _expected_loop: &LoopSnapshot,
            _next_loop: LoopSnapshot,
            _frame_id: &FrameId,
            _expected_frame: &FrameSnapshot,
            _next_frame: FrameSnapshot,
            _expected_run_state: &crate::run::flow_run::State,
            _next_run_state: crate::run::flow_run::State,
            _authority_inputs: Vec<crate::machines::mob_machine::MobMachineInput>,
        ) -> Result<bool, MobStoreError> {
            Err(MobStoreError::Internal(
                "not implemented in forged store".into(),
            ))
        }

        #[allow(clippy::too_many_arguments)]
        async fn cas_complete_loop_with_authority(
            &self,
            _run_id: &RunId,
            _loop_instance_id: &LoopInstanceId,
            _expected_loop: &LoopSnapshot,
            _next_loop: LoopSnapshot,
            _frame_id: &FrameId,
            _expected_frame: &FrameSnapshot,
            _next_frame: FrameSnapshot,
            _expected_run_state: &crate::run::flow_run::State,
            _next_run_state: crate::run::flow_run::State,
            _authority_inputs: Vec<crate::machines::mob_machine::MobMachineInput>,
        ) -> Result<bool, MobStoreError> {
            Err(MobStoreError::Internal(
                "not implemented in forged store".into(),
            ))
        }
    }

    fn forged_status_run() -> MobRun {
        let mut run = MobRun::authority_backed_for_steps(
            RunId::new(),
            MobId::from("mob"),
            crate::FlowId::from("flow"),
            [StepId::from("step-1")],
            MobRunStatus::Pending,
            serde_json::json!({}),
        )
        .expect("authority-backed run");
        run.status = MobRunStatus::Completed;
        run
    }

    #[tokio::test]
    async fn test_in_memory_storage_creates_working_stores() {
        let storage = MobStorage::in_memory();

        // Event store works
        let event = NewMobEvent {
            mob_id: MobId::from("test"),
            timestamp: None,
            kind: MobEventKind::MobCompleted,
        };
        let stored = storage.events.append(event).await.unwrap();
        assert_eq!(stored.cursor, 1);

        let all = storage.events.replay_all().await.unwrap();
        assert_eq!(all.len(), 1);
    }

    #[tokio::test]
    async fn test_in_memory_flow_stores_create_working_run_and_spec_stores() {
        let (runs, specs) = MobStorage::in_memory_flow_stores();
        let run = MobRun::authority_backed_for_steps(
            RunId::new(),
            MobId::from("mob"),
            crate::FlowId::from("flow"),
            [StepId::from("step-1")],
            MobRunStatus::Pending,
            serde_json::json!({}),
        )
        .expect("authority-backed run");
        runs.create_run(run.clone()).await.unwrap();
        assert!(runs.get_run(&run.run_id).await.unwrap().is_some());

        let definition = crate::definition::MobDefinition::from_toml(
            r#"
[mob]
id = "mob"
[profiles.worker]
model = "test"
"#,
        )
        .unwrap();
        let revision = specs
            .put_spec(&MobId::from("mob"), &definition, None)
            .await
            .unwrap();
        assert_eq!(revision, 1);
    }

    #[tokio::test]
    async fn custom_run_store_rejects_forged_lifecycle_projection() {
        let forged = forged_status_run();
        let storage = MobStorage::custom(
            Arc::new(InMemoryMobEventStore::new()),
            Arc::new(ForgedRunStore::new(Some(forged.clone()))),
            Arc::new(InMemoryMobSpecStore::new()),
        );

        let read_error = storage
            .runs
            .get_run(&forged.run_id)
            .await
            .expect_err("custom store read must reject forged run projection");
        assert!(
            read_error
                .to_string()
                .contains("not authorized by MobMachine"),
            "unexpected custom read error: {read_error}"
        );

        let list_error = storage
            .runs
            .list_runs(&forged.mob_id, None)
            .await
            .expect_err("custom store list must reject forged run projection");
        assert!(
            list_error
                .to_string()
                .contains("not authorized by MobMachine"),
            "unexpected custom list error: {list_error}"
        );

        let write_error = storage
            .runs
            .create_run(forged)
            .await
            .expect_err("custom store create must reject forged run projection");
        assert!(
            write_error
                .to_string()
                .contains("not authorized by MobMachine"),
            "unexpected custom create error: {write_error}"
        );
    }

    #[tokio::test]
    async fn test_persistent_storage_uses_shared_database_for_all_stores() {
        let dir = tempfile::tempdir().unwrap();
        let db_path = dir.path().join("mob.db");
        let storage = MobStorage::persistent(&db_path).unwrap();

        let event = NewMobEvent {
            mob_id: MobId::from("mob"),
            timestamp: None,
            kind: MobEventKind::MobCompleted,
        };
        storage.events.append(event).await.unwrap();

        let run = MobRun::authority_backed_for_steps(
            RunId::new(),
            MobId::from("mob"),
            crate::FlowId::from("flow"),
            [StepId::from("step-1")],
            MobRunStatus::Pending,
            serde_json::json!({}),
        )
        .expect("authority-backed run");
        storage.runs.create_run(run.clone()).await.unwrap();
        assert!(storage.runs.get_run(&run.run_id).await.unwrap().is_some());

        let definition = crate::definition::MobDefinition::from_toml(
            r#"
[mob]
id = "mob"
[profiles.worker]
model = "test"
"#,
        )
        .unwrap();
        let revision = storage
            .specs
            .put_spec(&MobId::from("mob"), &definition, None)
            .await
            .unwrap();
        assert_eq!(revision, 1);
    }
}