dirge-agent 0.12.5

Minimalistic coding agent written in Rust, optimized for memory footprint and performance
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
//! Apply plugin-issued [`TreeOp`]s to a live [`Session`] (P4d).
//!
//! The plugin worker queues ops on `harness-tree-ops`; the UI loop
//! drains them between events via `PluginManager::drain_tree_ops` and
//! hands the result to [`apply_tree_op`] here.
//!
//! Mirrors pi's `ctx.setLabel` / `ctx.fork` / `ctx.navigateTree` /
//! `ctx.newSession` / `ctx.switchSession` semantics. See `P4d` notes in
//! the README for the user-facing surface.

use compact_str::CompactString;

use crate::plugin::TreeOp;
use crate::session::{MessageRole, Session};
use crate::ui::input::InputEditor;

/// Outcome surfaced to the UI so it can render a status line, redraw
/// the chat, etc. Plain enum (no Display impl — callers format).
#[derive(Debug, PartialEq, Eq)]
pub enum TreeOpEffect {
    /// State change happened; UI should re-render the session and
    /// show the optional confirmation message.
    Applied(String),
    /// Op failed — message describes why. Surface as an error line.
    Failed(String),
    /// Session itself was replaced (new-session / switch-session).
    /// Caller must rebuild the agent + repaint completely.
    SessionReplaced(String),
}

/// Apply one op. Returns the UI-visible effect. Restored editor text
/// (for fork :before / navigate-tree on user messages) is pushed
/// straight into `input`.
/// dirge-dp24: optional `agent` parameter wired so plugin-driven
/// session resets (`TreeOp::NewSession`) and switches
/// (`TreeOp::SwitchSession`) fire the same lifecycle hooks the
/// `/clear` / `/session` slash commands do. Tests pass `None` to
/// skip the hook fires (they're testing the tree-op semantics, not
/// the lifecycle wiring). Production call site at
/// `ui/mod.rs::run_interactive` passes `Some(&agent)`.
pub fn apply_tree_op(
    op: TreeOp,
    session: &mut Session,
    input: &mut InputEditor,
    agent: Option<&crate::provider::AnyAgent>,
) -> TreeOpEffect {
    match op {
        TreeOp::SetLabel { id, label } => {
            let cid = CompactString::new(id.clone());
            match session.set_label(&cid, label.clone()) {
                Ok(()) => TreeOpEffect::Applied(match label {
                    Some(l) => format!("[plugin] labeled {} as \"{}\"", short(&id), l),
                    None => format!("[plugin] cleared label on {}", short(&id)),
                }),
                Err(e) => TreeOpEffect::Failed(format!("[plugin] set-label: {}", e)),
            }
        }
        TreeOp::Fork { id, restore_text } => {
            let cid = CompactString::new(id.clone());
            match session.fork_at(&cid) {
                Ok(original) => {
                    if restore_text {
                        input.set_text(&original.content);
                    }
                    TreeOpEffect::Applied(format!("[plugin] forked at {}", short(&id)))
                }
                Err(e) => TreeOpEffect::Failed(format!("[plugin] fork: {}", e)),
            }
        }
        TreeOp::NavigateTree { id } => {
            let cid = CompactString::new(id.clone());
            // Pi's semantics: if the target is a user message, move
            // the leaf to its parent and restore the prompt; for any
            // other role, the target itself becomes the new leaf.
            let role = session.message_store.get(&cid).map(|m| m.role);
            match role {
                None => TreeOpEffect::Failed(format!(
                    "[plugin] navigate-tree: unknown entry {}",
                    short(&id)
                )),
                Some(MessageRole::User) => match session.fork_at(&cid) {
                    Ok(original) => {
                        input.set_text(&original.content);
                        TreeOpEffect::Applied(format!(
                            "[plugin] navigated to user message {} (prompt restored)",
                            short(&id),
                        ))
                    }
                    Err(e) => TreeOpEffect::Failed(format!("[plugin] navigate-tree: {}", e)),
                },
                Some(_) => match session.switch_to_leaf(&cid) {
                    Ok(()) => {
                        TreeOpEffect::Applied(format!("[plugin] navigated to {}", short(&id)))
                    }
                    Err(e) => TreeOpEffect::Failed(format!("[plugin] navigate-tree: {}", e)),
                },
            }
        }
        TreeOp::NewSession { parent } => {
            // Persist the current session before resetting so the user
            // can still recover it via `/sessions`. Failures here are
            // logged but don't block the reset — getting wedged on disk
            // I/O would be worse than losing a session.
            //
            // Audit L15: previously a `let _ =` swallowed save errors
            // silently. On disk-full / permission errors the user lost
            // the previous session with no warning. Now we include
            // the save failure in the effect message so the user sees
            // it before the destructive reset takes effect.
            let prev_id = session.id.to_string();
            let parent_id = parent.as_deref().unwrap_or(&prev_id);
            // dirge-dp24: fire on_session_end BEFORE save (the
            // hook receives a transcript built from the still-live
            // session) and on_session_switch AFTER reset_to_new
            // gives us the new id. reset=true because this is a
            // genuinely fresh conversation from the provider's POV.
            if let Some(a) = agent {
                crate::agent::review::maybe_fire_session_end(a, session);
            }
            let save_err = crate::session::storage::save_session(session).err();
            session.reset_to_new(Some(parent_id));
            if let Some(a) = agent {
                crate::agent::review::maybe_fire_session_switch(
                    a,
                    &session.id,
                    &prev_id,
                    /* reset = */ true,
                );
            }
            input.set_text("");
            let mut msg = format!(
                "[plugin] new session started (parent: {})",
                short(parent_id),
            );
            if let Some(e) = save_err {
                msg.push_str(&format!(
                    "\n  warning: previous session save failed ({}); previous state may not be recoverable",
                    e,
                ));
            }
            TreeOpEffect::SessionReplaced(msg)
        }
        TreeOp::SwitchSession { id_prefix } => {
            match crate::session::storage::find_sessions_by_prefix(&id_prefix) {
                Ok(matches) => match matches.len() {
                    0 => TreeOpEffect::Failed(format!(
                        "[plugin] switch-session: no session matching '{}'",
                        id_prefix
                    )),
                    1 => {
                        // dirge-dp24: fire on_session_end on the
                        // outgoing session BEFORE we overwrite it,
                        // then on_session_switch with the loaded id.
                        // reset=false because switch-session restores
                        // an existing logical conversation rather
                        // than starting fresh.
                        if let Some(a) = agent {
                            crate::agent::review::maybe_fire_session_end(a, session);
                        }
                        let prev_id = session.id.to_string();
                        let save_err = crate::session::storage::save_session(session).err();
                        let loaded = matches.into_iter().next().expect("len == 1");
                        let new_id = loaded.id.clone();
                        *session = loaded;
                        if let Some(a) = agent {
                            crate::agent::review::maybe_fire_session_switch(
                                a,
                                &session.id,
                                &prev_id,
                                /* reset = */ false,
                            );
                        }
                        input.set_text("");
                        let mut msg =
                            format!("[plugin] switched to session {}", short(new_id.as_str()),);
                        if let Some(e) = save_err {
                            msg.push_str(&format!(
                                "\n  warning: previous session save failed ({}); previous state may not be recoverable",
                                e,
                            ));
                        }
                        TreeOpEffect::SessionReplaced(msg)
                    }
                    n => {
                        // Surface the first few matches so the plugin
                        // author / user can pick a longer prefix.
                        let ids: Vec<String> = matches
                            .iter()
                            .take(3)
                            .map(|s| short(s.id.as_str()))
                            .collect();
                        let suffix = if n > 3 {
                            format!(" (and {} more)", n - 3)
                        } else {
                            String::new()
                        };
                        TreeOpEffect::Failed(format!(
                            "[plugin] switch-session: prefix '{}' matches {} sessions ({}){}",
                            id_prefix,
                            n,
                            ids.join(", "),
                            suffix,
                        ))
                    }
                },
                Err(e) => TreeOpEffect::Failed(format!("[plugin] switch-session: {}", e)),
            }
        }
    }
}

fn short(s: &str) -> String {
    crate::text::short_id(s)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::session::Session;

    fn fresh_input() -> InputEditor {
        InputEditor::new()
    }

    #[test]
    fn set_label_applies_to_existing_node() {
        let mut s = Session::new("p", "m", 0);
        s.add_message(MessageRole::User, "hello");
        let id = s.messages[0].id.to_string();
        let mut input = fresh_input();
        let effect = apply_tree_op(
            TreeOp::SetLabel {
                id: id.clone(),
                label: Some("milestone".to_string()),
            },
            &mut s,
            &mut input,
            None,
        );
        assert!(matches!(effect, TreeOpEffect::Applied(_)));
        let node_label = s
            .tree
            .entries
            .get(&CompactString::new(&id))
            .and_then(|n| n.label.as_deref());
        assert_eq!(node_label, Some("milestone"));
    }

    /// SetLabel with None clears any existing label on the node.
    #[test]
    fn set_label_with_none_clears() {
        let mut s = Session::new("p", "m", 0);
        s.add_message(MessageRole::User, "hi");
        let id = s.messages[0].id.clone();
        s.set_label(&id, Some("old".to_string())).unwrap();
        let mut input = fresh_input();
        apply_tree_op(
            TreeOp::SetLabel {
                id: id.to_string(),
                label: None,
            },
            &mut s,
            &mut input,
            None,
        );
        assert_eq!(s.tree.entries[&id].label, None);
    }

    /// Fork with `restore_text=true` pushes the original prompt back
    /// into the editor so the user can re-edit.
    #[test]
    fn fork_with_restore_text_pushes_to_input() {
        let mut s = Session::new("p", "m", 0);
        s.add_message(MessageRole::User, "what's 2+2?");
        s.add_message(MessageRole::Assistant, "4");
        // Fork at the user message — its content should land back in
        // the editor and the assistant reply should be gone from the
        // current branch.
        let user_id = s.messages[0].id.to_string();
        let mut input = fresh_input();
        let effect = apply_tree_op(
            TreeOp::Fork {
                id: user_id,
                restore_text: true,
            },
            &mut s,
            &mut input,
            None,
        );
        assert!(matches!(effect, TreeOpEffect::Applied(_)));
        assert_eq!(input.buffer.as_str(), "what's 2+2?");
        assert!(s.messages.is_empty(), "leaf moved before user msg");
    }

    /// Fork with `restore_text=false` (the :at position) shifts the
    /// leaf but leaves the editor alone.
    #[test]
    fn fork_at_position_does_not_touch_input() {
        let mut s = Session::new("p", "m", 0);
        s.add_message(MessageRole::User, "q1");
        s.add_message(MessageRole::Assistant, "a1");
        let user_id = s.messages[0].id.to_string();
        let mut input = fresh_input();
        input.set_text("user-was-typing");
        apply_tree_op(
            TreeOp::Fork {
                id: user_id,
                restore_text: false,
            },
            &mut s,
            &mut input,
            None,
        );
        // Editor untouched.
        assert_eq!(input.buffer.as_str(), "user-was-typing");
    }

    /// Fork with unknown id surfaces a Failed effect, not a panic.
    #[test]
    fn fork_with_unknown_id_returns_failed() {
        let mut s = Session::new("p", "m", 0);
        let mut input = fresh_input();
        let effect = apply_tree_op(
            TreeOp::Fork {
                id: "ghost".to_string(),
                restore_text: true,
            },
            &mut s,
            &mut input,
            None,
        );
        assert!(matches!(effect, TreeOpEffect::Failed(_)));
    }

    /// NavigateTree to a user message restores text + moves to parent
    /// (pi parity).
    #[test]
    fn navigate_tree_user_message_restores_text() {
        let mut s = Session::new("p", "m", 0);
        s.add_message(MessageRole::User, "redo me");
        s.add_message(MessageRole::Assistant, "won't survive");
        let user_id = s.messages[0].id.to_string();
        let mut input = fresh_input();
        apply_tree_op(
            TreeOp::NavigateTree { id: user_id },
            &mut s,
            &mut input,
            None,
        );
        assert_eq!(input.buffer.as_str(), "redo me");
        assert!(s.messages.is_empty());
    }

    /// NavigateTree to a non-user (assistant) message sets that node
    /// as the leaf — no editor restore.
    #[test]
    fn navigate_tree_assistant_message_switches_leaf() {
        let mut s = Session::new("p", "m", 0);
        s.add_message(MessageRole::User, "q");
        s.add_message(MessageRole::Assistant, "a");
        s.add_message(MessageRole::User, "q2");
        let asst_id = s.messages[1].id.clone();
        let mut input = fresh_input();
        input.set_text("hands-off");
        apply_tree_op(
            TreeOp::NavigateTree {
                id: asst_id.to_string(),
            },
            &mut s,
            &mut input,
            None,
        );
        assert_eq!(input.buffer.as_str(), "hands-off");
        assert_eq!(s.tree.leaf_id.as_deref(), Some(asst_id.as_str()));
        // messages was rebuilt to the path-from-leaf for the new leaf.
        assert_eq!(s.messages.last().map(|m| m.content.as_str()), Some("a"));
    }

    /// NavigateTree with unknown id surfaces a Failed effect (we look
    /// up the role in message_store first to decide branch vs. switch).
    #[test]
    fn navigate_tree_unknown_id_returns_failed() {
        let mut s = Session::new("p", "m", 0);
        let mut input = fresh_input();
        let effect = apply_tree_op(
            TreeOp::NavigateTree {
                id: "missing".to_string(),
            },
            &mut s,
            &mut input,
            None,
        );
        assert!(matches!(effect, TreeOpEffect::Failed(_)));
    }

    /// NewSession wipes session state and assigns a fresh id; the
    /// effect must be SessionReplaced so the host rebuilds the agent.
    #[test]
    fn new_session_returns_session_replaced() {
        let mut s = Session::new("p", "m", 0);
        s.add_message(MessageRole::User, "stale");
        let old_id = s.id.clone();
        let mut input = fresh_input();
        let effect = apply_tree_op(
            TreeOp::NewSession { parent: None },
            &mut s,
            &mut input,
            None,
        );
        assert!(matches!(effect, TreeOpEffect::SessionReplaced(_)));
        assert!(s.messages.is_empty());
        assert_ne!(s.id, old_id);
    }

    /// SwitchSession with a non-matching prefix returns Failed without
    /// touching the session.
    #[test]
    fn switch_session_unknown_prefix_returns_failed() {
        let mut s = Session::new("p", "m", 0);
        s.add_message(MessageRole::User, "keep me");
        let id_before = s.id.clone();
        let msg_count_before = s.messages.len();
        let mut input = fresh_input();
        let effect = apply_tree_op(
            TreeOp::SwitchSession {
                id_prefix: "zzzzzzzz-nope".to_string(),
            },
            &mut s,
            &mut input,
            None,
        );
        // No matching session on disk -> Failed.
        assert!(matches!(effect, TreeOpEffect::Failed(_)));
        // Session untouched.
        assert_eq!(s.id, id_before);
        assert_eq!(s.messages.len(), msg_count_before);
    }

    // ── dirge-dp24: plugin-driven session boundaries fire hooks ──

    use crate::agent::tools::ToolCache;
    use crate::extras::memory_provider::MemoryProvider;
    use crate::provider::{AnyAgent, AnyAgentInner};
    use std::sync::{Arc, Mutex};

    #[derive(Default)]
    struct RecordingProvider {
        ends: Mutex<Vec<String>>,
        switches: Mutex<Vec<(String, String, bool)>>,
    }
    impl MemoryProvider for RecordingProvider {
        fn name(&self) -> &str {
            "recording"
        }
        fn view(&self, _: &str) -> serde_json::Value {
            serde_json::Value::Null
        }
        fn add(&self, _: &str, _: &str, _kind: Option<&str>) -> Result<serde_json::Value, String> {
            Ok(serde_json::Value::Null)
        }
        fn replace(
            &self,
            _: &str,
            _: &str,
            _: &str,
            _kind: Option<&str>,
        ) -> Result<serde_json::Value, String> {
            Ok(serde_json::Value::Null)
        }
        fn remove(&self, _: &str, _: &str) -> Result<serde_json::Value, String> {
            Ok(serde_json::Value::Null)
        }
        fn on_session_end(&self, t: &str) {
            self.ends.lock().unwrap().push(t.to_string());
        }
        fn on_session_switch(&self, new_id: &str, parent_id: &str, reset: bool) {
            self.switches
                .lock()
                .unwrap()
                .push((new_id.into(), parent_id.into(), reset));
        }
    }

    fn agent_with_provider() -> (AnyAgent, Arc<RecordingProvider>) {
        use rig::client::CompletionClient;
        use rig::providers::openai;
        let client = openai::CompletionsClient::builder()
            .api_key("test-key")
            .build()
            .expect("openai client");
        let model = client.completion_model("gpt-4o");
        let inner = rig::agent::AgentBuilder::new(model).build();
        let provider = Arc::new(RecordingProvider::default());
        let provider_dyn: Arc<dyn MemoryProvider> = provider.clone();
        let agent = AnyAgent::new(
            AnyAgentInner::OpenAI(inner),
            ToolCache::new(),
            std::time::Duration::from_secs(300),
            Vec::new(),
            String::new(),
            "gpt-4o".to_string(),
        )
        .with_memory_provider(provider_dyn);
        (agent, provider)
    }

    /// dirge-dp24 — `TreeOp::NewSession` fires on_session_end on the
    /// outgoing session AND on_session_switch on the rotated id.
    /// `reset=true` because new-session is a fresh chat.
    #[test]
    fn new_session_fires_end_and_switch_with_reset_true() {
        let (agent, provider) = agent_with_provider();
        let mut s = Session::new("p", "m", 0);
        s.add_message(MessageRole::User, "outgoing");
        let old_id = s.id.to_string();
        let mut input = fresh_input();

        let effect = apply_tree_op(
            TreeOp::NewSession { parent: None },
            &mut s,
            &mut input,
            Some(&agent),
        );
        assert!(matches!(effect, TreeOpEffect::SessionReplaced(_)));

        let ends = provider.ends.lock().unwrap();
        assert_eq!(ends.len(), 1, "exactly one on_session_end fire");
        assert!(ends[0].contains("User: outgoing"));

        let switches = provider.switches.lock().unwrap();
        assert_eq!(switches.len(), 1, "exactly one on_session_switch fire");
        let (new_id, parent_id, reset) = &switches[0];
        assert_ne!(new_id, &old_id, "switch must report the new id");
        assert_eq!(parent_id, &old_id, "switch must carry the old id as parent");
        assert!(*reset, "new-session implies reset=true");
    }

    /// dirge-dp24 — `TreeOp::SwitchSession` against a non-matching
    /// prefix returns Failed and fires NO hooks.
    #[test]
    fn switch_session_no_match_fires_no_hooks() {
        let (agent, provider) = agent_with_provider();
        let mut s = Session::new("p", "m", 0);
        s.add_message(MessageRole::User, "stays");
        let mut input = fresh_input();

        let effect = apply_tree_op(
            TreeOp::SwitchSession {
                id_prefix: "zzzz-no-match".into(),
            },
            &mut s,
            &mut input,
            Some(&agent),
        );
        assert!(matches!(effect, TreeOpEffect::Failed(_)));

        assert!(
            provider.ends.lock().unwrap().is_empty(),
            "failed switch must NOT fire on_session_end"
        );
        assert!(
            provider.switches.lock().unwrap().is_empty(),
            "failed switch must NOT fire on_session_switch"
        );
    }
}