meerkat-mobkit 0.8.19

Companion orchestration platform for the Meerkat multi-agent runtime
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
#![allow(
    clippy::expect_used,
    clippy::unwrap_used,
    clippy::panic,
    clippy::uninlined_format_args,
    clippy::redundant_clone,
    clippy::needless_raw_string_hashes,
    clippy::ignored_unit_patterns,
    clippy::useless_vec
)]
//! TDD tests for the new UnifiedRuntimeBuilder convenience API.
//!
//! Each test is written before the corresponding implementation code exists.
//! They cover: definition loading, persistent/ephemeral paths, session hooks,
//! capability flags, defaults, and backward-compat escape hatch.

use std::sync::Arc;

use async_trait::async_trait;
use base64::Engine as _;
use meerkat_client::TestClient;
use meerkat_core::service::{CreateSessionRequest, SessionError};
use meerkat_mob::{
    MobDefinition,
    MobState,
    MobStorage,
    ProfileName,
    SpawnMemberSpec,
    // meerkat 0.7: the MeerkatId alias was deleted; member ids are AgentIdentity.
    ids::AgentIdentity as MeerkatId,
};
use meerkat_mobkit::{
    DiscoverySpec, MobBootstrapOptions, MobBootstrapSpec, MobKitConfig, SessionHook, UnifiedRuntime,
};

/// Per-test mob id counter: 0.8.23's fail-closed in-proc registration
/// means concurrently running tests must not share a supervisor route.
static NEXT_TEST_MOB_ID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);

/// Per-call mob id: 0.8.23's fail-closed in-proc registration means
/// concurrently running tests must not share a supervisor route.
fn minimal_mob_toml() -> String {
    format!(
        r#"
[mob]
id = "builder-test-mob-{}"

[profiles.worker]
model = "gpt-5.5"
"#,
        NEXT_TEST_MOB_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
    )
}

// ---------------------------------------------------------------------------
// Helper: build a definition from the inline TOML
// ---------------------------------------------------------------------------
fn test_definition() -> MobDefinition {
    MobDefinition::from_toml(&minimal_mob_toml()).expect("parse test mob definition")
}

// ---------------------------------------------------------------------------
// 1. Builder ephemeral (no persistent_state → auto temp dir)
// ---------------------------------------------------------------------------
#[tokio::test]
#[ignore]
async fn test_builder_ephemeral() {
    let runtime = Box::pin(
        UnifiedRuntime::builder()
            .definition(test_definition())
            .default_llm_client(Arc::new(TestClient::default()))
            .build(),
    )
    .await
    .expect("ephemeral build");

    assert_eq!(
        runtime.mob_handle().status().await.unwrap(),
        MobState::Running
    );
    runtime.mob_handle().stop().await.expect("stop");
}

// ---------------------------------------------------------------------------
// 2. Builder persistent (SQLite session/runtime state + in-memory mob storage)
// ---------------------------------------------------------------------------
#[tokio::test]
#[ignore]
async fn test_builder_persistent_default() {
    let tmp = tempfile::tempdir().expect("temp dir");
    let state_path = tmp.path().join("state");

    let runtime = Box::pin(
        UnifiedRuntime::builder()
            .definition(test_definition())
            .persistent_state(&state_path)
            .default_llm_client(Arc::new(TestClient::default()))
            .build(),
    )
    .await
    .expect("persistent build");

    assert_eq!(
        runtime.mob_handle().status().await.unwrap(),
        MobState::Running
    );

    // Verify persistent artifacts were created (M2 canonical spellings on a
    // fresh state dir).
    assert!(
        state_path.join("sessions.sqlite3").exists(),
        "SQLite session store must be created"
    );
    assert!(
        state_path.join("mobkit_console.sqlite3").exists(),
        "durable MobKit console log must be created"
    );

    runtime.mob_handle().stop().await.expect("stop");
}

// ---------------------------------------------------------------------------
// 3. Builder TOML definition from path
// ---------------------------------------------------------------------------
#[tokio::test]
#[ignore]
async fn test_builder_toml_definition() {
    let tmp = tempfile::tempdir().expect("temp dir");
    let toml_path = tmp.path().join("mob.toml");
    std::fs::write(&toml_path, minimal_mob_toml()).expect("write toml");

    let runtime = Box::pin(
        UnifiedRuntime::builder()
            .definition_path(&toml_path)
            .default_llm_client(Arc::new(TestClient::default()))
            .build(),
    )
    .await
    .expect("toml definition build");

    assert_eq!(
        runtime.mob_handle().status().await.unwrap(),
        MobState::Running
    );
    runtime.mob_handle().stop().await.expect("stop");
}

// ---------------------------------------------------------------------------
// 4. Capability flags — shell(false) propagates
// ---------------------------------------------------------------------------
#[tokio::test]
#[ignore]
async fn test_builder_capability_flags() {
    // This test verifies that the builder accepts capability flag methods
    // and that the runtime bootstraps successfully with modified flags.
    let runtime = Box::pin(
        UnifiedRuntime::builder()
            .definition(test_definition())
            .default_llm_client(Arc::new(TestClient::default()))
            .shell(false)
            .build(),
    )
    .await
    .expect("build with shell disabled");

    assert_eq!(
        runtime.mob_handle().status().await.unwrap(),
        MobState::Running
    );
    runtime.mob_handle().stop().await.expect("stop");
}

// ---------------------------------------------------------------------------
// 5. Session hook — before_create mutates request
// ---------------------------------------------------------------------------
#[tokio::test]
#[ignore]
async fn test_builder_session_hook_before_create() {
    struct LabelInjector;
    #[async_trait]
    impl SessionHook for LabelInjector {
        async fn before_create(&self, req: &mut CreateSessionRequest) -> Result<(), SessionError> {
            let labels = req.labels.get_or_insert_with(Default::default);
            labels.insert("injected".to_string(), "true".to_string());
            Ok(())
        }
    }

    let runtime = Box::pin(
        UnifiedRuntime::builder()
            .definition(test_definition())
            .default_llm_client(Arc::new(TestClient::default()))
            .session_hook(Arc::new(LabelInjector))
            .build(),
    )
    .await
    .expect("build with session hook");

    assert_eq!(
        runtime.mob_handle().status().await.unwrap(),
        MobState::Running
    );
    runtime.mob_handle().stop().await.expect("stop");
}

// ---------------------------------------------------------------------------
// 6. Backward-compat — .mob_spec() escape hatch still works
// ---------------------------------------------------------------------------
#[tokio::test]
#[ignore]
async fn test_builder_mob_spec_escape_hatch() {
    let tmp = tempfile::tempdir().expect("temp dir");
    let session_path = tmp.path().join("sessions");
    std::fs::create_dir_all(&session_path).expect("session path");

    let factory = meerkat::AgentFactory::new(&session_path).comms(true);
    let session_service = Arc::new(meerkat::build_ephemeral_service(
        factory,
        meerkat::Config::default(),
        16,
    ));

    let spec = MobBootstrapSpec::new(test_definition(), MobStorage::in_memory(), session_service)
        .with_options(MobBootstrapOptions {
            allow_ephemeral_sessions: true,
            notify_orchestrator_on_resume: true,
            default_llm_client: Some(Arc::new(TestClient::default())),
        });

    let runtime = Box::pin(
        UnifiedRuntime::builder()
            .mob_spec(spec)
            .module_config(MobKitConfig {
                modules: Vec::new(),
                discovery: DiscoverySpec {
                    namespace: String::new(),
                    modules: Vec::new(),
                },
                pre_spawn: Vec::new(),
            })
            .timeout(std::time::Duration::from_secs(30))
            .build(),
    )
    .await
    .expect("escape hatch build");

    assert_eq!(
        runtime.mob_handle().status().await.unwrap(),
        MobState::Running
    );
    runtime.mob_handle().stop().await.expect("stop");
}

// ---------------------------------------------------------------------------
// 7. Builder defaults — module_config and timeout are defaulted
// ---------------------------------------------------------------------------
#[tokio::test]
#[ignore]
async fn test_builder_defaults() {
    // When using the new .definition() path, module_config and timeout
    // must be defaulted (no longer required fields).
    let runtime = Box::pin(
        UnifiedRuntime::builder()
            .definition(test_definition())
            .default_llm_client(Arc::new(TestClient::default()))
            .build(),
    )
    .await
    .expect("build with defaults");

    assert_eq!(
        runtime.mob_handle().status().await.unwrap(),
        MobState::Running
    );
    runtime.mob_handle().stop().await.expect("stop");
}

// ---------------------------------------------------------------------------
// 8. Builder persistent with custom session store
// ---------------------------------------------------------------------------
#[tokio::test]
#[ignore]
async fn test_builder_persistent_custom_store() {
    let tmp = tempfile::tempdir().expect("temp dir");
    let state_path = tmp.path().join("state");
    std::fs::create_dir_all(&state_path).expect("create state dir");

    // Open a custom SQLite store at a non-default path to prove the builder
    // uses it instead of creating its own.
    let custom_db_path = state_path.join("custom_sessions.db");
    let custom_store: std::sync::Arc<dyn meerkat::SessionStore> = std::sync::Arc::new(
        meerkat_store::SqliteSessionStore::open(&custom_db_path).expect("open custom store"),
    );

    let runtime = Box::pin(
        UnifiedRuntime::builder()
            .definition(test_definition())
            .persistent_state(&state_path)
            .session_store(custom_store)
            .default_llm_client(Arc::new(TestClient::default()))
            .build(),
    )
    .await
    .expect("persistent build with custom store");

    assert_eq!(
        runtime.mob_handle().status().await.unwrap(),
        MobState::Running
    );

    // The custom store path should exist (we created it).
    assert!(
        custom_db_path.exists(),
        "custom session store db must exist"
    );
    // The default sessions.db should NOT have been created by the builder.
    assert!(
        !state_path.join("sessions.db").exists(),
        "builder must use custom store, not create default SQLite"
    );

    runtime.mob_handle().stop().await.expect("stop");
}

// ---------------------------------------------------------------------------
// 8b. Per-slot WorkGraph store injection (0.8.16 item 5)
// ---------------------------------------------------------------------------
/// Item 5 is "a durable WorkGraph store injectable INDEPENDENTLY of continuity,
/// schedule, lease, console and blob". The seam
/// (`attach_workgraph_tools_with_store`) existed before this test and was
/// exercised directly by a unit test - but it was unreachable from
/// `UnifiedRuntimeBuilder`, so no caller could actually use it. A unit test
/// over the seam cannot fail on that; only a builder-level test can.
///
/// The assertion is deliberately NEGATIVE. "the field is populated" is a
/// measurement of the present, not a property of the mechanism: it stays true
/// if the value is later dropped on the floor. The absence of
/// `workgraph.sqlite3` is positive proof that the local-SQLite fallback did
/// NOT run, which is the thing injection has to accomplish.
#[tokio::test]
async fn builder_workgraph_store_injection_suppresses_the_local_sqlite_fallback() {
    let tmp = tempfile::tempdir().expect("temp dir");
    let state_path = tmp.path().join("state");
    std::fs::create_dir_all(&state_path).expect("create state dir");

    let injected: Arc<dyn meerkat::WorkGraphStore> = Arc::new(meerkat::MemoryWorkGraphStore::new());

    let runtime = Box::pin(
        UnifiedRuntime::builder()
            .definition(test_definition())
            .persistent_state(&state_path)
            .workgraph_store(Arc::clone(&injected))
            .default_llm_client(Arc::new(TestClient::default()))
            .build(),
    )
    .await
    .expect("persistent build with an injected workgraph store");

    // Positive control for the assertion below: the builder demonstrably ran
    // its persistent composition in this directory, so an absent
    // workgraph.sqlite3 means "suppressed", not "nothing happened here".
    assert!(
        state_path.join("runtime.sqlite").exists(),
        "persistent composition must have run in the state dir"
    );
    assert!(
        !state_path.join("workgraph.sqlite3").exists(),
        "an injected workgraph store must suppress the local SQLite fallback; \
         the file's presence means the injected store was dropped and \
         attach_workgraph_tools_reporting ran instead"
    );

    runtime.mob_handle().stop().await.expect("stop");
}

#[tokio::test]
async fn test_builder_ephemeral_custom_store_persists_sessions() {
    let custom_store: Arc<dyn meerkat::SessionStore> = Arc::new(meerkat::MemoryStore::new());
    let definition = MobDefinition::from_toml(&format!(
        r#"
[mob]
id = "builder-test-mob-{}"

[profiles.worker]
model = "gpt-5.5"

[profiles.worker.tools]
comms = true
"#,
        NEXT_TEST_MOB_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
    ))
    .expect("parse test mob definition");
    let runtime = Box::pin(
        UnifiedRuntime::builder()
            .definition(definition)
            .session_store(custom_store.clone())
            .default_llm_client(Arc::new(TestClient::default()))
            .build(),
    )
    .await
    .expect("ephemeral build with custom store");

    // meerkat 0.7: MemberCommsName is fail-closed; raw mob member ids must be
    // identifier-safe (no ":").
    let mid = MeerkatId::from("worker-one");
    Box::pin(runtime.mob_handle().spawn_spec(SpawnMemberSpec::new(
        ProfileName::from("worker"),
        mid.clone(),
    )))
    .await
    .expect("spawn worker");
    let session_id = runtime
        .mob_handle()
        .resolve_bridge_session_id(&mid)
        .await
        .expect("spawned worker has a bridge session id");

    assert!(
        custom_store
            .load(&session_id)
            .await
            .expect("custom store load")
            .is_some(),
        "ephemeral builder session_store() must wire the custom store into the real session service"
    );

    runtime.mob_handle().stop().await.expect("stop");
}

#[tokio::test]
async fn test_builder_custom_blob_store_serves_binary_blobs() {
    let blob_store: Arc<dyn meerkat_core::BlobStore> =
        Arc::new(meerkat_store::MemoryBlobStore::new());
    let runtime = Box::pin(
        UnifiedRuntime::builder()
            .definition(test_definition())
            .blob_store(blob_store.clone())
            .default_llm_client(Arc::new(TestClient::default()))
            .build(),
    )
    .await
    .expect("ephemeral build with custom blob store");

    let binary_store = runtime
        .binary_blob_store()
        .expect("builder-created runtime must expose binary blob serving store");
    let blob_ref = binary_store
        .put_bytes("image/png", bytes::Bytes::from_static(b"tiny-png"))
        .await
        .expect("binary put");
    let served = binary_store
        .get_bytes(&blob_ref.blob_id)
        .await
        .expect("binary get");
    assert_eq!(served.data.as_ref(), b"tiny-png");

    let stored = blob_store.get(&blob_ref.blob_id).await.expect("blob get");
    assert_eq!(stored.media_type, "image/png");
    assert_eq!(
        base64::engine::general_purpose::STANDARD
            .decode(stored.data.as_bytes())
            .expect("stored blob base64")
            .as_slice(),
        b"tiny-png"
    );

    runtime.mob_handle().stop().await.expect("stop");
}