rho-coding-agent 3.10.0

A fast Rust agent harness with a small footprint and opinionated defaults
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
use std::fs::OpenOptions;
use std::io::Write;

use pretty_assertions::assert_eq;
use rho_providers::model::{Message, ModelIdentity};
use rho_sdk::{CompactionState, Revision, SessionId, SessionSnapshot};

use super::super::persistence::active_display_from_tree;
use super::super::tree::{
    DisplayKeys, DisplayMarks, DisplayRowOrigin, MessageKey, NodeId, RowPrompt, SessionNodeKind,
    SessionTree, SessionTreeItemContent, StoredStateTransition, TurnEnd,
};
use super::super::Session;

fn snapshot(session: &Session, revision: u64, history: Vec<Message>) -> SessionSnapshot {
    compacted_snapshot(session, revision, history, CompactionState::default())
}

fn compacted_snapshot(
    session: &Session,
    revision: u64,
    history: Vec<Message>,
    compaction: CompactionState,
) -> SessionSnapshot {
    SessionSnapshot::new(
        SessionId::from_string(session.id().to_owned()).unwrap(),
        Revision::from_u64(revision),
        history,
        ModelIdentity::new("provider", "api", "model"),
        compaction,
    )
    .with_prompt_cache_key(format!("rho:{}", session.id()))
}

fn create_session() -> (tempfile::TempDir, tempfile::TempDir, Session) {
    let root = tempfile::tempdir().unwrap();
    let cwd = tempfile::tempdir().unwrap();
    let session = Session::create_in_root(root.path(), cwd.path()).unwrap();
    (root, cwd, session)
}

// Covers: the durable pre-turn baseline is a session start, not a phantom turn.
// Owner: session tree projection; assert classification, not picker label copy.
#[test]
fn empty_root_is_session_start_and_remains_restorable() -> anyhow::Result<()> {
    let (_root, _cwd, session) = create_session();
    let baseline = snapshot(&session, 1, Vec::new());
    session.save_snapshot(&baseline, &[])?;
    let baseline_id = session.active_checkpoint_target()?.unwrap().0;
    let first_turn = snapshot(&session, 2, vec![Message::user_text("first prompt")]);
    session.save_snapshot(&first_turn, first_turn.history())?;
    // Missing user text alone must not classify a later commit as a session
    // start: it carries the turn before it on.
    let assistant_turn = snapshot(
        &session,
        3,
        vec![
            Message::user_text("first prompt"),
            Message::assistant_text("reply"),
        ],
    );
    session.save_snapshot(&assistant_turn, &assistant_turn.history()[1..])?;

    let tree = SessionTree::load(session.path())?;
    let items = tree.turn_items()?;
    assert!(
        matches!(
            items
                .iter()
                .map(|item| &item.content)
                .collect::<Vec<_>>()
                .as_slice(),
            [
                SessionTreeItemContent::SessionStart,
                SessionTreeItemContent::Turn { .. }
            ]
        ),
        "{items:?}"
    );
    assert_eq!(items[0].id, baseline_id);
    session.set_leaf(&baseline_id)?;
    assert_eq!(
        session.snapshot_for_resume(baseline.provider().clone(), "unused".into())?,
        baseline
    );
    assert!(session.active_display_history()?.is_empty());
    Ok(())
}

// Covers: `/tree` lists one row for each prompt however many nodes its turn
// saved: the row names the turn's last node, so restoring it gives the
// conversation once the turn ended, follows the row its first node follows,
// and keeps where its prompt was saved, which names the message a replay
// shows; a branch from that node starts a row of its own, and the row
// holding the active leaf is the active one; a node names the prompt of the
// turn that saved it.
// Owner: session tree projection.
#[test]
fn turn_rows_join_the_nodes_that_carry_a_prompt_on() -> anyhow::Result<()> {
    let (_root, _cwd, session) = create_session();
    let system = || Message::System("prompt".into());
    let saved = |revision: u64, history: Vec<Message>, shown: usize| {
        let snapshot = snapshot(&session, revision, history);
        let rows = &snapshot.history()[snapshot.history().len() - shown..];
        session.save_snapshot_node(&snapshot, rows, /*keys*/ &[])
    };
    let user = Message::user_text;
    let reply = Message::assistant_text;
    // A host that saves before the first prompt, then at each step.
    let start = saved(1, vec![system()], 0)?;
    let first = saved(2, vec![system(), user("first")], 1)?;
    let first_end = saved(3, vec![system(), user("first"), reply("one")], 1)?;
    let second_start = saved(
        4,
        vec![system(), user("first"), reply("one"), user("second")],
        1,
    )?;
    let second = [system(), user("first"), reply("one"), user("second")];
    let second_end = saved(5, [&second[..], &[reply("two")]].concat(), 1)?;
    // Back to the first turn's end, then a prompt that is still running.
    session.set_leaf(&first_end)?;
    let branch = saved(
        6,
        vec![system(), user("first"), reply("one"), user("other")],
        1,
    )?;

    let tree = SessionTree::load(session.path())?;
    let rows = tree
        .turn_items()?
        .into_iter()
        .map(|item| {
            (
                item.content,
                (item.id, item.parent, item.run),
                (item.depth, item.active),
            )
        })
        .collect::<Vec<_>>();
    // A node a turn saved after its prompt still names that prompt.
    assert_eq!(
        [&first_end, &second_end, &branch].map(|node| tree.turn_prompt(node)),
        ["first", "second", "other"].map(|prompt| Some(prompt.to_owned()))
    );
    let row = |text: &str, run: &[&NodeId], parent: &NodeId, depth, active| {
        let run = run.iter().map(|&node| node.clone()).collect::<Vec<_>>();
        let id = run.last().unwrap().clone();
        let prompt = RowPrompt {
            origin: DisplayRowOrigin {
                node: run[0].clone(),
                row: 0,
            },
            key: None,
            text: Some(text.to_owned()),
        };
        (
            SessionTreeItemContent::Turn {
                prompt: Some(prompt),
                end: None,
            },
            (id, Some(parent.clone()), run),
            (depth, active),
        )
    };
    assert_eq!(
        rows,
        [
            (
                SessionTreeItemContent::SessionStart,
                (start.clone(), None, vec![start.clone()]),
                (0, false)
            ),
            row("first", &[&first, &first_end], &start, 1, false),
            row(
                "second",
                &[&second_start, &second_end],
                &first_end,
                2,
                false
            ),
            row("other", &[&branch], &first_end, 2, true),
        ]
    );
    Ok(())
}

// Covers: a turn that compacts part way saves its later steps on the
// compaction's row, yet its prompt's row says how the turn ended, also once
// a prompt branches from that row's node, which ends on a row of its own;
// the turn's first node is found from the node it began at, past the
// compaction.
// Owner: session tree projection.
#[test]
fn a_turn_that_compacts_part_way_ends_on_its_prompts_row() -> anyhow::Result<()> {
    let (_root, _cwd, session) = create_session();
    let leaf = || {
        session
            .active_checkpoint_target()
            .map(|target| target.unwrap().0)
    };
    let (user, reply) = (Message::user_text, Message::assistant_text);
    session.save_snapshot(&snapshot(&session, 1, Vec::new()), &[])?;
    let start = leaf()?;
    session.save_snapshot(
        &snapshot(&session, 2, vec![user("prompt")]),
        &[user("prompt")],
    )?;
    let prompt = leaf()?;
    let compacted = CompactionState::from_parts(1, 1, Some(Revision::from_u64(3)));
    let summary = vec![user("summary")];
    session.save_snapshot(
        &compacted_snapshot(&session, 3, summary.clone(), compacted.clone()),
        &[],
    )?;
    let compaction = leaf()?;
    let settled = [summary, vec![reply("done")]].concat();
    session.save_settled_turn(
        &compacted_snapshot(&session, 4, settled, compacted),
        &[reply("done")],
        DisplayMarks::default(),
        TurnEnd::Completed,
    )?;
    let last = leaf()?;
    session.set_leaf(&prompt)?;
    let branched = [user("prompt"), user("branch"), reply("stopped")];
    session.save_settled_turn(
        &snapshot(&session, 5, branched.to_vec()),
        &branched[1..],
        DisplayMarks::default(),
        TurnEnd::Cancelled,
    )?;
    let branch = leaf()?;

    let tree = SessionTree::load(session.path())?;
    let rows = tree
        .turn_items()?
        .into_iter()
        .map(|item| match item.content {
            SessionTreeItemContent::Compaction(_) => (None, item.run),
            content => (Some(content), item.run),
        })
        .collect::<Vec<_>>();
    let turn = SessionTreeItemContent::Turn {
        prompt: Some(RowPrompt {
            origin: DisplayRowOrigin {
                node: prompt.clone(),
                row: 0,
            },
            key: None,
            text: Some("prompt".into()),
        }),
        end: Some(TurnEnd::Completed),
    };
    assert_eq!(
        (rows, tree.turn_start(&start, &last)),
        (
            vec![
                (
                    Some(SessionTreeItemContent::SessionStart),
                    vec![start.clone()]
                ),
                (Some(turn), vec![prompt.clone()]),
                (None, vec![compaction, last.clone()]),
                (
                    Some(SessionTreeItemContent::Turn {
                        prompt: Some(RowPrompt {
                            origin: DisplayRowOrigin {
                                node: branch.clone(),
                                row: 0,
                            },
                            key: None,
                            text: Some("branch".into()),
                        }),
                        end: Some(TurnEnd::Cancelled),
                    }),
                    vec![branch.clone()]
                ),
            ],
            Some(&prompt)
        )
    );
    Ok(())
}

// Covers: saves leave the cached active state as a pending replay. Deltas,
// rewritten prefixes, and compactions built on it, and readers after it, must
// match a fresh reload, without depending on a stale disk parse.
// Owner: session persistence
#[test]
fn sequential_saves_match_fresh_reload() {
    let (_root, _cwd, session) = create_session();
    let compacted = CompactionState::from_parts(1, 3, Some(Revision::from_u64(6)))
        .with_removed_tokens(30)
        .with_last_compaction_tokens(40, 10);
    let at = |revision: u64, history: &[&str], compaction: &CompactionState| {
        let history = history.iter().copied().map(Message::user_text).collect();
        compacted_snapshot(&session, revision, history, compaction.clone())
    };
    let resume = || {
        session
            .snapshot_for_resume(
                ModelIdentity::new("unused", "unused", "unused"),
                "unused".into(),
            )
            .unwrap()
    };
    let none = CompactionState::default();
    let saves = [
        at(1, &["u1"], &none),
        at(2, &["u1", "a1"], &none),
        at(3, &["u1", "a1", "u2"], &none),
        at(4, &["u1", "a1", "u2", "a2"], &none),
        at(5, &["u1", "a1", "u2", "a2", "u3"], &none),
        at(6, &["summary"], &compacted),
        at(7, &["summary", "a3"], &compacted),
        at(8, &["edited", "a3", "u4"], &compacted),
    ];
    for (index, snapshot) in saves.iter().enumerate() {
        session.save_snapshot(snapshot, &[]).unwrap();
        // A mid-chain read must leave the pending replay intact.
        if index == 2 {
            assert_eq!(resume(), *snapshot);
        }
    }

    let cached = session.session_tree().unwrap();
    let reloaded = SessionTree::load(session.path()).unwrap();
    assert_eq!(cached.facts(), reloaded.facts());
    assert_eq!(
        cached.active_state().map(|state| state.model.clone()),
        reloaded.active_state().map(|state| state.model.clone())
    );
    assert_eq!(resume(), saves[saves.len() - 1]);
    let transitions: Vec<_> = reloaded
        .nodes_in_storage_order()
        .map(|node| {
            let stored = match node.transition() {
                StoredStateTransition::Snapshot { .. } => "snapshot",
                StoredStateTransition::SnapshotDelta { .. } => "delta",
            };
            let previous_messages = node.compaction_facts().map(|facts| facts.previous_messages);
            (node.kind(), stored, previous_messages)
        })
        .collect();
    assert_eq!(
        transitions,
        [
            (SessionNodeKind::Commit, "snapshot", None),
            (SessionNodeKind::Commit, "delta", None),
            (SessionNodeKind::Commit, "delta", None),
            (SessionNodeKind::Commit, "delta", None),
            (SessionNodeKind::Commit, "delta", None),
            (SessionNodeKind::Compaction, "snapshot", Some(5)),
            (SessionNodeKind::Commit, "delta", None),
            (SessionNodeKind::Commit, "snapshot", None),
        ]
    );
}

// Covers: the keys a save gives its display rows survive a fresh load of
// the transcript, on the rows they were given to, so a replay or the search
// index reading the file names a live turn's messages as it showed them.
// Owner: session persistence
#[test]
fn keyed_display_rows_load_with_their_keys() {
    let (_root, _cwd, session) = create_session();
    let rows = [
        Message::user_text("prompt"),
        Message::assistant_text("reply"),
    ];
    let marks = DisplayMarks {
        keys: DisplayKeys::from([(1, MessageKey::new("turn-1"))]),
        ..DisplayMarks::default()
    };
    session
        .save_snapshot_keyed(&snapshot(&session, 1, rows.to_vec()), &rows, marks)
        .unwrap();

    let loaded = active_display_from_tree(&SessionTree::load(session.path()).unwrap()).unwrap();
    assert_eq!(
        loaded.into_iter().map(|row| row.key).collect::<Vec<_>>(),
        vec![None, Some(MessageKey::new("turn-1"))]
    );
}

// Covers: a turn's final save records how the turn ended, and its rows load
// with it, while other saves' rows load with none. A node a later rho wrote,
// with an end or a field this one does not know, still loads, its end read
// as unknown, as rho before turn ends reads the field this one writes.
// Owner: session persistence
#[test]
fn a_turns_final_save_records_how_it_ended() {
    let (_root, _cwd, session) = create_session();
    let prompt = [Message::user_text("prompt")];
    let reply = [Message::assistant_text("reply")];
    let history = [prompt.clone(), reply.clone()].concat();
    session
        .save_snapshot(&snapshot(&session, 1, prompt.to_vec()), &prompt)
        .unwrap();
    session
        .save_settled_turn(
            &snapshot(&session, 2, history.clone()),
            &reply,
            DisplayMarks::default(),
            TurnEnd::Cancelled,
        )
        .unwrap();
    let ends = |session: &Session| {
        active_display_from_tree(&SessionTree::load(session.path()).unwrap())
            .unwrap()
            .into_iter()
            .map(|row| row.turn_end)
            .collect::<Vec<_>>()
    };
    assert_eq!(ends(&session), vec![None, Some(TurnEnd::Cancelled)]);

    let text = std::fs::read_to_string(session.path()).unwrap();
    let mut lines: Vec<serde_json::Value> = text
        .lines()
        .map(|line| serde_json::from_str(line).unwrap())
        .collect();
    let last = lines.last_mut().unwrap();
    last["turn_end"] = "abandoned".into();
    last["a_later_field"] = serde_json::json!({"kept": true});
    let rewritten: String = lines.iter().map(|line| format!("{line}\n")).collect();
    std::fs::write(session.path(), rewritten).unwrap();
    assert_eq!(ends(&session), vec![None, Some(TurnEnd::Unknown)]);
}

// Covers: the keys of the rows a session saved are read from every branch
// of its tree, so a prompt key still names a message on a branch the session
// moved away from.
// Owner: session persistence
#[test]
fn saved_message_keys_cover_every_branch() -> anyhow::Result<()> {
    let (_root, _cwd, session) = create_session();
    let system = || Message::System("prompt".into());
    let start = session.save_snapshot_node(&snapshot(&session, 1, vec![system()]), &[], &[])?;
    let keyed = |revision: u64, text: &str, key: &str| {
        let history = vec![system(), Message::user_text(text)];
        let snapshot = snapshot(&session, revision, history);
        let rows = &snapshot.history()[1..];
        session.save_snapshot_node(&snapshot, rows, &[(0, MessageKey::new(key))])
    };
    keyed(2, "first", "prompt-a")?;
    session.set_leaf(&start)?;
    keyed(3, "other", "prompt-b")?;

    assert_eq!(
        session.saved_message_keys()?,
        vec![MessageKey::new("prompt-a"), MessageKey::new("prompt-b")]
    );
    Ok(())
}

// Covers: an external append that grows the transcript must not be ignored by
// the cached tree on the next save.
// Owner: session persistence
#[test]
fn external_file_growth_is_visible_on_next_save() {
    let (_root, _cwd, session) = create_session();
    let first = snapshot(&session, 1, vec![Message::user_text("root")]);
    session.save_snapshot(&first, first.history()).unwrap();
    let root_id = session
        .session_tree()
        .unwrap()
        .active_leaf_id()
        .unwrap()
        .clone();

    let sibling = snapshot(
        &session,
        2,
        vec![Message::user_text("root"), Message::assistant_text("side")],
    );
    session
        .save_snapshot(
            &sibling,
            std::slice::from_ref(sibling.history().last().unwrap()),
        )
        .unwrap();
    session.set_leaf(&root_id).unwrap();

    OpenOptions::new()
        .append(true)
        .open(session.path())
        .unwrap()
        .write_all(
            b"{\"type\":\"set_leaf\",\"timestamp\":\"1\",\"target_id\":\"missing-external\"}\n",
        )
        .unwrap();

    let error = session
        .save_snapshot(
            &snapshot(
                &session,
                3,
                vec![Message::user_text("root"), Message::assistant_text("next")],
            ),
            &[Message::assistant_text("next")],
        )
        .unwrap_err();
    assert!(
        error.to_string().contains("missing"),
        "cached tree ignored external growth: {error:#}"
    );
}