capsule-runtime 0.9.0

The runtime that executes Murmur capsules. Runs packaged AI agents in isolation, enforcing WASI capability grants on a Wasmtime component sandbox.
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
//! Host implementation of `murmur:conversation/read@0.2.0`.
//!
//! A hook component that imports this interface reads the capsule's durable conversation record —
//! every message the runtime put in front of the model, newest first, paged — holding no
//! `filesystem` grant and with no other artifact involved. Nothing is preopened under
//! `conversations/`, so this is the only way in.
//!
//! See `wit/hook/deps/murmur-conversation/read.wit` for the contract and
//! [`crate::conversation`] for the record itself.

use std::path::PathBuf;
use std::sync::{Arc, Mutex, PoisonError};

use wasmtime::component::Linker;

use crate::bindings::hook::murmur::conversation::read::MessagePage;
use crate::workdir_fs::WorkdirRoot;

/// The versioned instance name the host provides `read-messages` under. Hook components that do
/// not import it ignore the registration.
pub(crate) const CONVERSATION_IFACE_VERSIONED: &str = "murmur:conversation/read@0.2.0";

/// The runtime's view of which record is in scope.
///
/// Owned by `HookRuntime` for the whole launch and shared with each granted hook's linker through
/// an `Arc`. `root` is fixed for the launch; the context id moves with the task loop, so a hook
/// dispatched during task N reads task N's conversation.
pub(crate) struct ConversationState {
    /// `<home>/.murmur/conversations/<record>`, or `None` when this session writes no record —
    /// `context.record: off`, a `process`-transport capsule, or a host whose home could not be
    /// resolved. A read then returns an empty page, never an error.
    root: Option<PathBuf>,
    /// Session directory a malformed record line is reported into, beside stderr.
    workdir: WorkdirRoot,
    /// Context id of the task in scope. `None` before the first task of a launch.
    context_id: Mutex<Option<String>>,
    /// The record parsed for the last read, held so a hook paging one record reads and parses it
    /// once rather than once per page. Keyed on the record path as well as its length, because
    /// [`Self::set_context`] moves this one state between the records of a launch.
    cache: Mutex<crate::conversation::RecordCache>,
}

impl ConversationState {
    pub(crate) fn new(root: Option<PathBuf>, workdir: &WorkdirRoot) -> Self {
        Self {
            root,
            workdir: workdir.clone(),
            context_id: Mutex::new(None),
            cache: Mutex::new(crate::conversation::RecordCache::default()),
        }
    }

    /// Put one task's conversation in scope. Called for every task the runtime starts, from the
    /// same dispatch that tells hooks the task's `context-id`.
    pub(crate) fn set_context(&self, context_id: Option<String>) {
        *self.lock() = context_id;
    }

    /// One page of the record in scope, newest first.
    ///
    /// A context id that is not a usable path segment reads as no record rather than as an error:
    /// the id came from an A2A client, and a conversation the runtime declined to record has
    /// nothing to report but its emptiness.
    pub(crate) fn read_messages(
        &self,
        cursor: Option<String>,
        limit: u32,
    ) -> Result<MessagePage, String> {
        // Cloned out from under the context lock before the cache lock is taken: the two are
        // never held at once, so a reading hook cannot stand between a task and `set_context`.
        let context_id = self.lock().clone();
        let path = match (self.root.as_deref(), context_id.as_deref()) {
            (Some(root), Some(context_id))
                if crate::state_store::validate_store_name(context_id).is_ok() =>
            {
                Some(root.join(context_id).join("conversation.jsonl"))
            }
            _ => None,
        };
        crate::conversation::page(
            &mut self.cache(),
            path.as_deref(),
            &self.workdir,
            cursor.as_deref(),
            limit,
        )
    }

    /// Reads of the record file this state has made, for the tests that pin a paging loop's cost.
    #[cfg(test)]
    pub(crate) fn record_reads(&self) -> u32 {
        self.cache().reads()
    }

    /// A hook that panicked mid-call must not turn every later read into a different error than
    /// the contract names, so a poisoned lock is recovered rather than propagated — the state
    /// behind it is one owned string with no invariant a panic could have broken.
    fn lock(&self) -> std::sync::MutexGuard<'_, Option<String>> {
        self.context_id
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
    }

    /// Recovered on poison for the reason [`Self::lock`] is: a cache holds a parse of a file that
    /// is still on disk, so the worst a panic mid-update leaves behind is a re-read.
    fn cache(&self) -> std::sync::MutexGuard<'_, crate::conversation::RecordCache> {
        self.cache.lock().unwrap_or_else(PoisonError::into_inner)
    }
}

/// Register `murmur:conversation/read@0.2.0` on a hook linker.
///
/// `state` is `None` for a hook whose manifest entry does not declare
/// `capabilities.conversation.read: true`: the function is still *defined* (so an importing hook
/// links and runs), it just returns `not-granted`. A denied read is a value the hook branches on,
/// never a trap, and it is distinguishable from the `Ok` empty page a session with no record
/// returns.
pub(crate) fn add_conversation_to_linker<T: 'static>(
    linker: &mut Linker<T>,
    state: Option<Arc<ConversationState>>,
) -> Result<(), String> {
    let mut instance = linker
        .instance(CONVERSATION_IFACE_VERSIONED)
        .map_err(|e| format!("failed to define {CONVERSATION_IFACE_VERSIONED}: {e}"))?;

    instance
        .func_wrap(
            "read-messages",
            move |_store: wasmtime::StoreContextMut<'_, T>,
                  (cursor, limit): (Option<String>, u32)| {
                Ok((state.as_ref().map_or_else(
                    || Err("not-granted".to_string()),
                    |state| state.read_messages(cursor, limit),
                ),))
            },
        )
        .map_err(|e| {
            format!("failed to register {CONVERSATION_IFACE_VERSIONED}#read-messages: {e}")
        })?;

    Ok(())
}

#[cfg(test)]
pub(crate) mod test_support {
    use super::CONVERSATION_IFACE_VERSIONED;
    use wasmtime::component::Component;

    /// The import declaration for `murmur:conversation/read@0.2.0`, plus the memory and `realloc`
    /// the lowered import needs.
    ///
    /// Two things about the shape, both of which a `wit-bindgen` guest produces as well:
    ///
    /// * `read`'s `message` is `use`d from `murmur:hook/lifecycle`, so a component importing it
    ///   also imports that interface for the type alone. The host defines no such instance and
    ///   does not have to: a types-only import carries no runtime value to link against.
    /// * An import instance must *export* every named type it uses, and everything referencing
    ///   one has to name the exported alias rather than the definition behind it — hence the
    ///   numeric type indices below, which are the exports at 2 (`context-insertion`), 5
    ///   (`message`) and 8 (`message-page`).
    fn preamble() -> String {
        format!(
            r#"  (import "murmur:hook/lifecycle@0.9.0" (instance $lct
    (type $o (option string))
    (type $ci (enum "replace-context" "seed-context"))
    (export "context-insertion" (type (eq $ci)))
    (type $oci (option 2))
    (type $m (record
      (field "role" string)
      (field "content" string)
      (field "id" $o)
      (field "source-id" $o)
      (field "inserted-by" $oci)))
    (export "message" (type (eq $m)))
  ))
  (import "{CONVERSATION_IFACE_VERSIONED}" (instance $conv
    (type $optstr (option string))
    (type $ci (enum "replace-context" "seed-context"))
    (export "context-insertion" (type (eq $ci)))
    (type $optci (option 2))
    (type $message (record
      (field "role" string)
      (field "content" string)
      (field "id" $optstr)
      (field "source-id" $optstr)
      (field "inserted-by" $optci)))
    (export "message" (type (eq $message)))
    (type $msglist (list 5))
    (type $page (record
      (field "messages" $msglist)
      (field "next-cursor" $optstr)
      (field "total" u32)))
    (export "message-page" (type (eq $page)))
    (type $ret (result 8 (error string)))
    (export "read-messages"
      (func (param "cursor" $optstr) (param "limit" u32) (result $ret)))
  ))
  (alias export $conv "read-messages" (func $read))

  (core module $libc
    (memory (export "memory") 4)
    (global $bump (mut i32) (i32.const 32768))
    (func (export "realloc") (param i32 i32 i32 i32) (result i32)
      (local $p i32)
      (local.set $p (i32.and (i32.add (global.get $bump) (i32.const 7)) (i32.const -8)))
      (global.set $bump (i32.add (local.get $p) (i32.add (local.get 3) (i32.const 8))))
      (local.get $p))
  )
  (core instance $li (instantiate $libc))
  (alias core export $li "memory" (core memory $mem))
  (alias core export $li "realloc" (core func $realloc))
  (core func $read_l
    (canon lower (func $read) (memory $mem) (realloc $realloc) string-encoding=utf8))"#
        )
    }

    /// The field separator in [`reader_double`]'s report — ASCII unit separator, for the reason
    /// `task_io_import::test_support::REPORT_SEP` is one: message content is arbitrary text.
    pub(crate) const REPORT_SEP: char = '\u{1f}';

    /// Core-module boilerplate: the lowered import, a bump cursor over the report buffer, and the
    /// decoder that renders one `result<message-page, string>`.
    ///
    /// The report is `T=<total>` then, per message, `<id>=<role>=<mark>`, joined by
    /// [`REPORT_SEP`], and ends with `N=<next-cursor>` (`N=-` for `none`). `<mark>` is the
    /// message's `inserted-by`: `r` for `replace-context`, `s` for `seed-context`, `-` for
    /// `none`. An `err` renders as `!<error string>`, so a test asserts which error the host
    /// chose.
    ///
    /// `result<message-page, string>` has align 4: the discriminant is at byte 0, the page's
    /// three fields at 4/8 (messages ptr/len), 12/16/20 (`next-cursor` option), and 24 (`total`);
    /// an `err`'s string sits at 4/8. One `message` record is 44 bytes: `role` and `content`
    /// ptr/len at 0/4 and 8/12, `id` and `source-id` discriminant/ptr/len at 16/20/24 and
    /// 28/32/36, and `inserted-by` as a one-byte discriminant at 40 and a one-byte enum case at
    /// 41, padded to the record's 4-byte alignment.
    const CORE_HELPERS: &str = r#"
    (import "libc" "memory" (memory 4))
    (import "conv" "read" (func $read (param i32 i32 i32 i32 i32)))
    (global $cur (mut i32) (i32.const 0))
    (func $put (param $b i32)
      (i32.store8 (global.get $cur) (local.get $b))
      (global.set $cur (i32.add (global.get $cur) (i32.const 1))))
    (func $append (param $src i32) (param $n i32)
      (memory.copy (global.get $cur) (local.get $src) (local.get $n))
      (global.set $cur (i32.add (global.get $cur) (local.get $n))))
    (func $dec (param $v i32)
      (if (i32.ge_u (local.get $v) (i32.const 10))
        (then (call $dec (i32.div_u (local.get $v) (i32.const 10)))))
      (call $put (i32.add (i32.const 48) (i32.rem_u (local.get $v) (i32.const 10)))))
    (func $emit_page (param $rp i32) (local $i i32) (local $rec i32) (local $n i32)
      (if (i32.eqz (i32.load8_u (local.get $rp)))
        (then
          (call $put (i32.const 84)) (call $put (i32.const 61))
          (call $dec (i32.load (i32.add (local.get $rp) (i32.const 24))))
          (local.set $n (i32.load (i32.add (local.get $rp) (i32.const 8))))
          (local.set $i (i32.const 0))
          (block $done
            (loop $next
              (br_if $done (i32.ge_u (local.get $i) (local.get $n)))
              (local.set $rec (i32.add (i32.load (i32.add (local.get $rp) (i32.const 4)))
                                       (i32.mul (local.get $i) (i32.const 44))))
              (call $put (i32.const 31))
              ;; id, when the option carries one
              (if (i32.load8_u (i32.add (local.get $rec) (i32.const 16)))
                (then (call $append (i32.load (i32.add (local.get $rec) (i32.const 20)))
                                    (i32.load (i32.add (local.get $rec) (i32.const 24))))))
              (call $put (i32.const 61))
              (call $append (i32.load (local.get $rec)) (i32.load (i32.add (local.get $rec) (i32.const 4))))
              (call $put (i32.const 61))
              ;; inserted-by: `r` for replace-context, `s` for seed-context, `-` for none
              (if (i32.load8_u (i32.add (local.get $rec) (i32.const 40)))
                (then (if (i32.load8_u (i32.add (local.get $rec) (i32.const 41)))
                        (then (call $put (i32.const 115)))
                        (else (call $put (i32.const 114)))))
                (else (call $put (i32.const 45))))
              (local.set $i (i32.add (local.get $i) (i32.const 1)))
              (br $next)))
          (call $put (i32.const 31))
          (call $put (i32.const 78)) (call $put (i32.const 61))
          (if (i32.load8_u (i32.add (local.get $rp) (i32.const 12)))
            (then (call $append (i32.load (i32.add (local.get $rp) (i32.const 16)))
                                (i32.load (i32.add (local.get $rp) (i32.const 20)))))
            (else (call $put (i32.const 45)))))
        (else
          (call $put (i32.const 33))
          (call $append (i32.load (i32.add (local.get $rp) (i32.const 4)))
                        (i32.load (i32.add (local.get $rp) (i32.const 8)))))))
"#;

    /// Every WIT type the lifecycle exports in this double name.
    const LIFECYCLE_TYPES: &str = r#"
  (type $context-insertion (enum "replace-context" "seed-context"))
  (type $message (record
    (field "role" string)
    (field "content" string)
    (field "id" (option string))
    (field "source-id" (option string))
    (field "inserted-by" (option $context-insertion))))
  (type $tool-manifest (record (field "binary-name" string) (field "content" string)))
  (type $hook-output (variant
    (case "none")
    (case "replace-context" (list $message))
    (case "write-manifests" (list $tool-manifest))
    (case "artifact" string)
    (case "reopen-task" string)
    (case "seed-context" (list $message))
    (case "deny" string)))
  (type $task-end-event (record
    (field "task-id" string)
    (field "exit-status" string)))
"#;

    /// A hook double that, on `on-task-end`, calls `read-messages` twice — a first page with the
    /// caller's `limit`, then the page its `next-cursor` names — and returns both reports as
    /// `reopen-task`, joined by `|`.
    ///
    /// Only `on-task-end` has a real body; the other required exports are bare stubs, exactly as
    /// the single-event doubles in `hooks.rs` are, so this double is only ever usefully
    /// dispatched for `on-task-end`.
    pub(crate) fn reader_double(engine: &wasmtime::Engine, limit: u32) -> Component {
        let core_body = format!(
            r#"
    (func (export "ontaskend") (param i32 i32 i32 i32) (result i32)
      (global.set $cur (i32.const 4096))
      (call $read (i32.const 0) (i32.const 0) (i32.const 0) (i32.const {limit}) (i32.const 1024))
      (call $emit_page (i32.const 1024))
      (call $put (i32.const 124))
      ;; The second call reuses the first page's `next-cursor`, when it had one.
      (if (i32.and (i32.eqz (i32.load8_u (i32.const 1024)))
                   (i32.load8_u (i32.const 1036)))
        (then (call $read (i32.const 1) (i32.load (i32.const 1040)) (i32.load (i32.const 1044))
                          (i32.const {limit}) (i32.const 2048)))
        (else (call $read (i32.const 0) (i32.const 0) (i32.const 0)
                          (i32.const {limit}) (i32.const 2048))))
      (call $emit_page (i32.const 2048))
      (i32.store (i32.const 128) (i32.const 0))
      (i32.store (i32.const 132) (i32.const 4))
      (i32.store (i32.const 136) (i32.const 4096))
      (i32.store (i32.const 140) (i32.sub (global.get $cur) (i32.const 4096)))
      (i32.const 128))
    (func (export "noop"))
"#
        );
        let wat = format!(
            "(component\n{preamble}\n\n  (core module $m{CORE_HELPERS}{core_body}  )\n  \
             (core instance $i (instantiate $m\n    (with \"libc\" (instance $li))\n    \
             (with \"conv\" (instance (export \"read\" (func $read_l))))))\n\
             {LIFECYCLE_TYPES}\n  \
             (type $ontaskend-ft (func (param \"event\" $task-end-event) \
             (result (result $hook-output (error string)))))\n  \
             (func $ontaskend (type $ontaskend-ft)\n    (canon lift (core func $i \"ontaskend\") \
             (memory $mem) (realloc $realloc) string-encoding=utf8))\n  \
             (func $noop (canon lift (core func $i \"noop\")))\n  \
             (instance $lc\n    (export \"context-insertion\" (type $context-insertion))\n    (export \"message\" (type $message))\n    \
             (export \"tool-manifest\" (type $tool-manifest))\n    \
             (export \"hook-output\" (type $hook-output))\n    \
             (export \"task-end-event\" (type $task-end-event))\n    \
             (export \"on-task-end\" (func $ontaskend))\n{stubs}  )\n  \
             (export \"murmur:hook/lifecycle@0.9.0\" (instance $lc))\n)",
            preamble = preamble(),
            stubs = [
                "on-session-start",
                "on-inference",
                "on-tool-call",
                "on-shell",
                "on-compaction",
                "on-session-end",
            ]
            .iter()
            .map(|name| format!("    (export \"{name}\" (func $noop))\n"))
            .collect::<String>(),
        );
        let bytes = wat::parse_str(&wat).expect("conversation double WAT parses");
        Component::new(engine, &bytes).expect("conversation double compiles")
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::path::Path;

    /// The hand-authored guest double is laid out against the canonical ABI, so its layout is
    /// only checked when Wasmtime validates it. Building it here fails loudly on a slip rather
    /// than inside whichever suite happens to use it.
    #[test]
    fn the_guest_double_compiles() {
        let mut config = wasmtime::Config::new();
        config.wasm_component_model(true);
        let engine = wasmtime::Engine::new(&config).expect("engine builds");
        test_support::reader_double(&engine, 2);
    }

    /// An importing component links whether or not it is granted: the import is defined either
    /// way, so an ungranted hook runs and gets `not-granted` from the call rather than failing to
    /// instantiate.
    #[test]
    fn an_importing_component_links_with_and_without_the_grant() {
        let mut config = wasmtime::Config::new();
        config.wasm_component_model(true);
        let engine = wasmtime::Engine::new(&config).expect("engine builds");
        let component = test_support::reader_double(&engine, 2);
        let workdir = tempfile::tempdir().unwrap();

        for state in [
            None,
            Some(Arc::new(ConversationState::new(
                None,
                &WorkdirRoot::open(workdir.path()).unwrap(),
            ))),
        ] {
            let mut linker: Linker<()> = Linker::new(&engine);
            add_conversation_to_linker(&mut linker, state).unwrap();
            let mut store = wasmtime::Store::new(&engine, ());
            linker
                .instantiate(&mut store, &component)
                .expect("the import is defined on every linker");
        }
    }

    /// A session with no record reads as an empty page, and so does one whose task never entered
    /// scope — never as an error, so a hook can tell "nothing recorded" from "not granted".
    #[test]
    fn no_record_and_no_context_both_read_as_an_empty_page() {
        let workdir = tempfile::tempdir().unwrap();
        let home = tempfile::tempdir().unwrap();

        let no_record = ConversationState::new(None, &WorkdirRoot::open(workdir.path()).unwrap());
        no_record.set_context(Some("ctx_1".to_string()));
        let no_context = ConversationState::new(
            Some(home.path().to_path_buf()),
            &WorkdirRoot::open(workdir.path()).unwrap(),
        );

        for state in [&no_record, &no_context] {
            let page = state.read_messages(None, 10).expect("an Ok empty page");
            assert!(page.messages.is_empty());
            assert_eq!(page.next_cursor, None);
            assert_eq!(page.total, 0);
        }
    }

    /// One state serves every task of a launch, so a read after `set_context` answers about the
    /// record that just came into scope and never about the one that left it.
    #[test]
    fn a_read_follows_the_context_the_state_was_moved_to() {
        use serde_json::json;

        let workdir = tempfile::tempdir().unwrap();
        let home = tempfile::tempdir().unwrap();
        let root = home.path().join("conversations/capsule");

        for (context_id, count) in [("ctx_a", 2), ("ctx_b", 3)] {
            let dir = root.join(context_id);
            std::fs::create_dir_all(&dir).unwrap();
            let raw: String = (0..count)
                .map(|n| {
                    format!(
                        "{}\n",
                        json!({"role": "user", "content": "m", "id": format!("{context_id}_{n}")})
                    )
                })
                .collect();
            std::fs::write(dir.join("conversation.jsonl"), raw).unwrap();
        }

        let state = ConversationState::new(Some(root), &WorkdirRoot::open(workdir.path()).unwrap());
        state.set_context(Some("ctx_a".to_string()));
        let first = state.read_messages(None, 10).unwrap();
        assert_eq!(first.total, 2);

        state.set_context(Some("ctx_b".to_string()));
        let second = state.read_messages(None, 10).unwrap();
        assert_eq!(second.total, 3);
        assert_eq!(
            second
                .messages
                .iter()
                .map(|m| m.id.clone().unwrap())
                .collect::<Vec<_>>(),
            vec!["ctx_b_2", "ctx_b_1", "ctx_b_0"],
        );
        assert_eq!(state.record_reads(), 2, "one read per record in scope");
    }

    /// A context id an A2A client could send is checked before it becomes a path: the read is
    /// empty rather than reaching outside the record root.
    #[test]
    fn a_context_id_that_escapes_reads_as_no_record() {
        let workdir = tempfile::tempdir().unwrap();
        let home = tempfile::tempdir().unwrap();
        let state = ConversationState::new(
            Some(home.path().join("conversations/c")),
            &WorkdirRoot::open(workdir.path()).unwrap(),
        );
        state.set_context(Some("../../escape".to_string()));

        assert_eq!(state.read_messages(None, 10).unwrap().total, 0);
    }

    /// Write `lines` as a record under `<root>/<context_id>/conversation.jsonl`.
    fn write_record_lines(root: &Path, context_id: &str, lines: &[serde_json::Value]) {
        let dir = root.join(context_id);
        std::fs::create_dir_all(&dir).unwrap();
        let raw: String = lines.iter().map(|line| format!("{line}\n")).collect();
        std::fs::write(dir.join("conversation.jsonl"), raw).unwrap();
    }

    /// A hook reading the record through the real import sees which message a hook output put
    /// there: the guest decodes `inserted-by` out of the lowered `message` itself, so the mark is
    /// checked at the byte offsets a compiled hook reads it from.
    #[test]
    fn a_reader_sees_which_messages_a_hook_inserted() {
        use serde_json::json;
        use wasmtime::component::Val;

        let workdir = tempfile::tempdir().unwrap();
        let home = tempfile::tempdir().unwrap();
        let root = home.path().join("conversations/capsule");
        write_record_lines(
            &root,
            "ctx_marks",
            &[
                json!({"role": "user", "content": "a person's turn", "id": "msg_person"}),
                json!({
                    "role": "user",
                    "content": "a summary",
                    "id": "msg_summary",
                    "inserted_by": "replace-context",
                }),
                json!({
                    "role": "user",
                    "content": "a seed",
                    "id": "msg_seed",
                    "inserted_by": "seed-context",
                }),
            ],
        );
        let state = Arc::new(ConversationState::new(
            Some(root),
            &WorkdirRoot::open(workdir.path()).unwrap(),
        ));
        state.set_context(Some("ctx_marks".to_string()));

        let mut config = wasmtime::Config::new();
        config.wasm_component_model(true);
        let engine = wasmtime::Engine::new(&config).expect("engine builds");
        let component = test_support::reader_double(&engine, 3);
        let mut linker: Linker<()> = Linker::new(&engine);
        add_conversation_to_linker(&mut linker, Some(state)).unwrap();
        let mut store = wasmtime::Store::new(&engine, ());
        let instance = linker.instantiate(&mut store, &component).unwrap();
        let lifecycle = instance
            .get_export_index(&mut store, None, "murmur:hook/lifecycle@0.9.0")
            .expect("the double exports the lifecycle");
        let on_task_end = instance
            .get_export_index(&mut store, Some(&lifecycle), "on-task-end")
            .and_then(|index| instance.get_func(&mut store, index))
            .expect("the double exports on-task-end");

        let mut results = [Val::Bool(false)];
        on_task_end
            .call(
                &mut store,
                &[Val::Record(vec![
                    ("task-id".to_string(), Val::String("tsk_1".to_string())),
                    ("exit-status".to_string(), Val::String("ok".to_string())),
                ])],
                &mut results,
            )
            .expect("the read succeeds");
        let Val::Result(Ok(Some(output))) = &results[0] else {
            panic!("the double returns ok(hook-output): {:?}", results[0]);
        };
        let Val::Variant(case, Some(reason)) = output.as_ref() else {
            panic!("the double returns reopen-task: {output:?}");
        };
        assert_eq!(case, "reopen-task");
        let Val::String(report) = reason.as_ref() else {
            panic!("reopen-task carries a string: {reason:?}");
        };
        let first_page = report.split('|').next().unwrap();

        assert_eq!(
            first_page,
            [
                "T=3",
                "msg_seed=user=s",
                "msg_summary=user=r",
                "msg_person=user=-",
                "N=-",
            ]
            .join(&test_support::REPORT_SEP.to_string()),
        );
    }

    /// A mark this runtime did not write reads as no mark. The line is still a message: it is
    /// served, counted in `total`, and reported nowhere.
    #[test]
    fn an_unrecognised_inserted_by_reads_as_none() {
        use serde_json::json;

        let workdir = tempfile::tempdir().unwrap();
        let home = tempfile::tempdir().unwrap();
        let root = home.path().join("conversations/capsule");
        write_record_lines(
            &root,
            "ctx_odd",
            &[
                json!({"role": "user", "content": "m", "id": "msg_absent"}),
                json!({"role": "user", "content": "m", "id": "msg_bogus", "inserted_by": "bogus"}),
                json!({"role": "user", "content": "m", "id": "msg_number", "inserted_by": 42}),
            ],
        );
        let state = ConversationState::new(Some(root), &WorkdirRoot::open(workdir.path()).unwrap());
        state.set_context(Some("ctx_odd".to_string()));

        let page = state.read_messages(None, 10).expect("the read succeeds");

        assert_eq!(page.total, 3);
        assert_eq!(
            page.messages
                .iter()
                .map(|m| (m.id.clone().unwrap(), m.inserted_by))
                .collect::<Vec<_>>(),
            vec![
                ("msg_number".to_string(), None),
                ("msg_bogus".to_string(), None),
                ("msg_absent".to_string(), None),
            ],
        );
        assert!(
            !workdir.path().join("logs/bootstrap.log").exists(),
            "an odd mark is not a defect worth reporting"
        );
    }
}