merry-runtime 0.1.3

Structured session, task ledger, context compaction, memory, permission, and tool runtime for Merry.
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
use merry_core::{
    InteractiveRunState, RuntimeEvent, SubagentActivityPhase, SubagentActivitySnapshot, SubagentId,
    SubagentTaskId,
};
use std::{collections::BTreeMap, sync::Arc};
use tokio::sync::watch;

const NON_TERMINAL_COALESCE_MS: u64 = 250;
const MAX_SUMMARY_BYTES: usize = 120;

/// Receiver for the latest sorted activity snapshot set.
pub type SubagentActivityReceiver = watch::Receiver<Vec<SubagentActivitySnapshot>>;

/// Runtime-owned latest-value activity projection for UI consumers.
#[derive(Clone)]
pub struct SubagentActivityHub {
    sender: watch::Sender<Vec<SubagentActivitySnapshot>>,
    state: Arc<std::sync::Mutex<ActivityHubState>>,
    publication_lock: Arc<std::sync::Mutex<()>>,
}

struct ActivityHubState {
    snapshots: BTreeMap<SubagentId, SubagentActivitySnapshot>,
    last_published_ms: BTreeMap<SubagentId, u64>,
    #[cfg(test)]
    published_phases: Vec<SubagentActivityPhase>,
}

impl SubagentActivityHub {
    /// Creates an empty latest-value activity hub.
    #[must_use]
    pub fn new() -> Self {
        let (sender, _receiver) = watch::channel(Vec::new());
        Self {
            sender,
            state: Arc::new(std::sync::Mutex::new(ActivityHubState {
                snapshots: BTreeMap::new(),
                last_published_ms: BTreeMap::new(),
                #[cfg(test)]
                published_phases: Vec::new(),
            })),
            publication_lock: Arc::new(std::sync::Mutex::new(())),
        }
    }

    /// Subscribes to the current and future latest snapshot sets.
    #[must_use]
    pub fn subscribe(&self) -> SubagentActivityReceiver {
        self.sender.subscribe()
    }

    pub(crate) fn publish(&self, snapshot: SubagentActivitySnapshot) {
        // Serialize the state snapshot and watch publication without holding the
        // state mutex across Tokio's internal watch write lock.
        let _publication_guard = self
            .publication_lock
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let is_terminal = is_terminal_phase(snapshot.phase);
        let subagent_id = snapshot.subagent_id.clone();
        let updated_at_ms = snapshot.updated_at_ms;
        let (values, should_publish) = {
            let mut state = self
                .state
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);

            if state
                .snapshots
                .get(&snapshot.subagent_id)
                .is_some_and(|previous| is_terminal_phase(previous.phase) && !is_terminal)
            {
                return;
            }

            let should_publish = is_terminal
                || state
                    .last_published_ms
                    .get(&subagent_id)
                    .is_none_or(|last_published_ms| {
                        updated_at_ms >= last_published_ms.saturating_add(NON_TERMINAL_COALESCE_MS)
                    });
            #[cfg(test)]
            state.published_phases.push(snapshot.phase);
            state.snapshots.insert(subagent_id.clone(), snapshot);
            if should_publish {
                state.last_published_ms.insert(subagent_id, updated_at_ms);
            }
            let values = state.snapshots.values().cloned().collect::<Vec<_>>();
            (values, should_publish)
        };

        let _ = self.sender.send_if_modified(|current| {
            *current = values;
            should_publish
        });
    }

    #[allow(dead_code)]
    pub(crate) fn current(&self) -> Vec<SubagentActivitySnapshot> {
        self.state
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .snapshots
            .values()
            .cloned()
            .collect()
    }

    #[cfg(test)]
    #[allow(dead_code)]
    pub(crate) fn published_phases(&self) -> Vec<SubagentActivityPhase> {
        self.state
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .published_phases
            .clone()
    }
}

impl Default for SubagentActivityHub {
    fn default() -> Self {
        Self::new()
    }
}

fn is_terminal_phase(phase: SubagentActivityPhase) -> bool {
    matches!(
        phase,
        SubagentActivityPhase::Completed
            | SubagentActivityPhase::Failed
            | SubagentActivityPhase::Blocked
            | SubagentActivityPhase::Cancelled
    )
}

#[derive(Debug, Clone)]
pub(crate) struct SubagentActivityReducer {
    subagent_id: SubagentId,
    task_id: SubagentTaskId,
    last_valid: Option<SubagentActivitySnapshot>,
}

impl SubagentActivityReducer {
    pub(crate) fn new(subagent_id: SubagentId, task_id: SubagentTaskId) -> Self {
        Self {
            subagent_id,
            task_id,
            last_valid: None,
        }
    }

    pub(crate) fn reduce(
        &mut self,
        event: &RuntimeEvent,
        updated_at_ms: u64,
    ) -> Option<SubagentActivitySnapshot> {
        match self.try_reduce(event, updated_at_ms) {
            Ok(Some(snapshot)) => {
                self.last_valid = Some(snapshot.clone());
                Some(snapshot)
            }
            Ok(None) => None,
            Err(error) => {
                tracing::warn!(
                    subagent_id = %self.subagent_id,
                    task_id = %self.task_id,
                    error,
                    "subagent activity event projection skipped"
                );
                None
            }
        }
    }

    pub(crate) fn starting(&mut self, updated_at_ms: u64) -> SubagentActivitySnapshot {
        let snapshot = self.snapshot(SubagentActivityPhase::Starting, "starting", updated_at_ms);
        self.last_valid = Some(snapshot.clone());
        snapshot
    }

    pub(crate) fn terminal(
        &mut self,
        phase: SubagentActivityPhase,
        summary: &str,
        updated_at_ms: u64,
    ) -> SubagentActivitySnapshot {
        let snapshot = self.snapshot(phase, summary, updated_at_ms);
        self.last_valid = Some(snapshot.clone());
        snapshot
    }

    #[cfg(test)]
    fn last_valid(&self) -> Option<&SubagentActivitySnapshot> {
        self.last_valid.as_ref()
    }

    fn try_reduce(
        &self,
        event: &RuntimeEvent,
        updated_at_ms: u64,
    ) -> Result<Option<SubagentActivitySnapshot>, &'static str> {
        let (phase, summary) = match event {
            RuntimeEvent::StepStarted { .. } => {
                (SubagentActivityPhase::Running, "working".to_owned())
            }
            RuntimeEvent::ToolCallStarted { call, .. } => {
                let tool_name = call.name().as_str();
                if tool_name.is_empty() {
                    return Err("tool call name was empty");
                }
                (SubagentActivityPhase::Running, format!("tool: {tool_name}"))
            }
            RuntimeEvent::PlanSaved { .. } => {
                (SubagentActivityPhase::Running, "plan saved".to_owned())
            }
            RuntimeEvent::InteractiveRunStateChanged { state } => match state {
                InteractiveRunState::WaitingForInput => (
                    SubagentActivityPhase::Waiting,
                    "waiting for input".to_owned(),
                ),
                InteractiveRunState::RunningModel | InteractiveRunState::RunningTool => {
                    (SubagentActivityPhase::Running, "working".to_owned())
                }
                InteractiveRunState::Interrupting | InteractiveRunState::Closed => return Ok(None),
            },
            _ => return Ok(None),
        };

        Ok(Some(self.snapshot(phase, &summary, updated_at_ms)))
    }

    fn snapshot(
        &self,
        phase: SubagentActivityPhase,
        summary: &str,
        updated_at_ms: u64,
    ) -> SubagentActivitySnapshot {
        SubagentActivitySnapshot {
            subagent_id: self.subagent_id.clone(),
            task_id: self.task_id.clone(),
            phase,
            summary: bounded_summary(summary),
            updated_at_ms,
        }
    }
}

fn bounded_summary(summary: &str) -> String {
    let sanitized = summary
        .chars()
        .map(|character| {
            if character.is_control() {
                ' '
            } else {
                character
            }
        })
        .collect::<String>();
    let mut end = sanitized.len().min(MAX_SUMMARY_BYTES);
    while !sanitized.is_char_boundary(end) {
        end -= 1;
    }
    sanitized[..end].to_owned()
}

#[cfg(test)]
mod tests {
    use super::*;
    use merry_core::{
        PendingToolCall, RuntimeEventSource, ToolCallArguments, ToolCallId, ToolName,
    };
    use serde_json::Map;
    use std::sync::{Arc, Barrier};

    fn agent_id(value: &str) -> SubagentId {
        SubagentId::new(value).expect("valid subagent id")
    }

    fn task_id(value: &str) -> SubagentTaskId {
        SubagentTaskId::new(value).expect("valid task id")
    }

    fn source() -> RuntimeEventSource {
        RuntimeEventSource::new(
            merry_core::SessionId::new("child-session").expect("valid session id"),
            1,
        )
    }

    fn snapshot(
        id: &str,
        phase: SubagentActivityPhase,
        updated_at_ms: u64,
    ) -> SubagentActivitySnapshot {
        SubagentActivitySnapshot {
            subagent_id: agent_id(id),
            task_id: task_id("task-1"),
            phase,
            summary: "working".to_owned(),
            updated_at_ms,
        }
    }

    fn tool_call(name: &str) -> PendingToolCall {
        PendingToolCall::new(
            ToolCallId::new("call-1").expect("valid call id"),
            ToolName::new(name).expect("valid tool name"),
            ToolCallArguments::new(Map::new()),
        )
    }

    #[test]
    fn reducer_maps_structured_events_and_ignores_assistant_text() {
        let mut reducer = SubagentActivityReducer::new(agent_id("agent-1"), task_id("task-1"));

        let started = reducer
            .reduce(&RuntimeEvent::StepStarted { source: source() }, 10)
            .expect("step start projects activity");
        assert_eq!(started.phase, SubagentActivityPhase::Running);
        assert_eq!(started.summary, "working");

        let tool = reducer
            .reduce(
                &RuntimeEvent::ToolCallStarted {
                    call: tool_call("apply_patch"),
                    source: source(),
                },
                20,
            )
            .expect("tool start projects activity");
        assert_eq!(tool.phase, SubagentActivityPhase::Running);
        assert_eq!(tool.summary, "tool: apply_patch");
        assert_eq!(reducer.last_valid(), Some(&tool));

        assert!(
            reducer
                .reduce(
                    &RuntimeEvent::AssistantMessageDelta {
                        delta: "unstructured assistant prose".to_owned(),
                        source: source(),
                    },
                    30,
                )
                .is_none()
        );
        assert_eq!(reducer.last_valid(), Some(&tool));

        let plan_saved = reducer
            .reduce(
                &RuntimeEvent::PlanSaved {
                    plan: merry_core::PlanDocument {
                        summary: merry_core::PlanDocumentSummary {
                            id: merry_core::PlanId::new("plan-1").expect("valid plan id"),
                            title: "Refactor auth".to_owned(),
                            file_name: "001-refactor-auth.md".to_owned(),
                            status: merry_core::PlanDocumentStatus::Draft,
                            revision: 1,
                            created_at_ms: 10,
                            updated_at_ms: 35,
                        },
                        content: "# Refactor auth\n".to_owned(),
                    },
                    source: source(),
                },
                35,
            )
            .expect("plan save projects activity");
        assert_eq!(plan_saved.phase, SubagentActivityPhase::Running);
        assert_eq!(plan_saved.summary, "plan saved");

        let waiting = reducer
            .reduce(
                &RuntimeEvent::InteractiveRunStateChanged {
                    state: InteractiveRunState::WaitingForInput,
                },
                40,
            )
            .expect("waiting state projects activity");
        assert_eq!(waiting.phase, SubagentActivityPhase::Waiting);
    }

    #[test]
    fn summaries_sanitize_controls_and_cap_without_splitting_utf8() {
        let sanitized = bounded_summary("before\n\tafter");
        assert_eq!(sanitized, "before  after");

        let capped = bounded_summary(&"界".repeat(50));
        assert_eq!(capped.len(), 120);
        assert_eq!(capped.chars().count(), 40);
    }

    #[test]
    fn hub_publishes_sorted_latest_values_and_coalesces_nonterminal_updates() {
        let hub = SubagentActivityHub::new();
        let mut receiver = hub.subscribe();

        hub.publish(snapshot("agent-b", SubagentActivityPhase::Starting, 100));
        assert!(receiver.has_changed().expect("receiver remains open"));
        let _ = receiver.borrow_and_update();

        hub.publish(snapshot("agent-b", SubagentActivityPhase::Running, 200));
        assert!(!receiver.has_changed().expect("receiver remains open"));
        assert_eq!(receiver.borrow()[0].updated_at_ms, 200);

        hub.publish(snapshot("agent-a", SubagentActivityPhase::Starting, 350));
        assert!(receiver.has_changed().expect("receiver remains open"));
        let values = receiver.borrow_and_update().clone();
        assert_eq!(values[0].subagent_id, agent_id("agent-a"));
        assert_eq!(values[1].subagent_id, agent_id("agent-b"));
        assert_eq!(values[1].updated_at_ms, 200);

        hub.publish(snapshot("agent-b", SubagentActivityPhase::Completed, 201));
        assert!(
            receiver
                .has_changed()
                .expect("terminal update is immediate")
        );
        assert_eq!(hub.current()[1].phase, SubagentActivityPhase::Completed);
    }

    #[test]
    fn dropping_a_receiver_does_not_cancel_activity_production() {
        let hub = SubagentActivityHub::new();
        let receiver = hub.subscribe();
        drop(receiver);

        hub.publish(snapshot("agent-1", SubagentActivityPhase::Running, 1));
        assert_eq!(hub.current().len(), 1);
    }

    #[test]
    fn concurrent_publish_keeps_watch_value_equal_to_final_sorted_state() {
        let hub = Arc::new(SubagentActivityHub::new());
        let receiver = hub.subscribe();
        let barrier = Arc::new(Barrier::new(3));

        let first_hub = Arc::clone(&hub);
        let first_barrier = Arc::clone(&barrier);
        let first = std::thread::spawn(move || {
            first_barrier.wait();
            first_hub.publish(snapshot("agent-a", SubagentActivityPhase::Running, 1));
        });
        let second_hub = Arc::clone(&hub);
        let second_barrier = Arc::clone(&barrier);
        let second = std::thread::spawn(move || {
            second_barrier.wait();
            second_hub.publish(snapshot("agent-b", SubagentActivityPhase::Running, 1));
        });

        barrier.wait();
        first.join().expect("first publisher should finish");
        second.join().expect("second publisher should finish");

        let current = hub.current();
        assert_eq!(&*receiver.borrow(), &current);
        assert_eq!(
            current
                .iter()
                .map(|snapshot| snapshot.subagent_id.as_str())
                .collect::<Vec<_>>(),
            vec!["agent-a", "agent-b"]
        );
    }

    #[test]
    fn publish_tolerates_poisoned_state_and_closed_receiver() {
        let hub = SubagentActivityHub::new();
        let state = Arc::clone(&hub.state);
        let panic_result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            let _guard = state
                .lock()
                .expect("state lock should initially be healthy");
            panic!("poison activity state for the test");
        }));
        assert!(panic_result.is_err());

        let publication_lock = Arc::clone(&hub.publication_lock);
        let publication_panic = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            let _guard = publication_lock
                .lock()
                .expect("publication lock should initially be healthy");
            panic!("poison activity publication lock for the test");
        }));
        assert!(publication_panic.is_err());

        hub.publish(snapshot("agent-1", SubagentActivityPhase::Failed, 1));
        let receiver = hub.subscribe();
        drop(receiver);
        hub.publish(snapshot("agent-1", SubagentActivityPhase::Completed, 2));

        assert_eq!(hub.current()[0].phase, SubagentActivityPhase::Completed);
    }
}