rho-coding-agent 3.0.0

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

use pretty_assertions::assert_eq;
use tempfile::TempDir;

use super::{JobRegistry, RegisterError, SessionJob, StartTurnError};
use crate::app::daemon_host::jobs::{
    Admission, JobEvent, JobId, JobRecord, JobState, JobStore, TurnEnd, TurnRecord,
};

fn states(records: Vec<JobRecord>) -> Vec<(JobId, JobState)> {
    let mut states: Vec<_> = records
        .into_iter()
        .map(|record| (record.id, record.state))
        .collect();
    states.sort_by(|a, b| a.0.cmp(&b.0));
    states
}

// Covers: a daemon that starts over its predecessor's records lists every
// one, records each job that was queued, running, or waiting for input as
// interrupted, on disk as well as in memory, and leaves every other state
// as it was.
// Owner: daemon job registry startup.
#[test]
fn startup_interrupts_the_turns_a_dead_daemon_left_open() {
    use JobState::{Ended, Idle, Queued, Running, WaitingForInput};
    let home = TempDir::new().unwrap();
    let store = JobStore::open(home.path()).unwrap();
    let failed = Ended(TurnEnd::Failed("provider refused the request".into()));
    let cases = [
        (Idle, Idle),
        (Queued, Ended(TurnEnd::Interrupted)),
        (Running, Ended(TurnEnd::Interrupted)),
        (WaitingForInput, Ended(TurnEnd::Interrupted)),
        (Ended(TurnEnd::Completed), Ended(TurnEnd::Completed)),
        (failed.clone(), failed),
        (Ended(TurnEnd::Cancelled), Ended(TurnEnd::Cancelled)),
        (Ended(TurnEnd::Interrupted), Ended(TurnEnd::Interrupted)),
    ];
    let mut expected = Vec::new();
    for (saved, after) in cases {
        let record = JobRecord {
            state: saved,
            ..JobRecord::new_session(
                JobId::generate(),
                PathBuf::from("/work"),
                rho_sdk::SessionId::new(),
            )
        };
        expected.push((record.id.clone(), after));
        store.write(&record).unwrap();
    }
    expected.sort_by(|a, b| a.0.cmp(&b.0));

    let registry = JobRegistry::open(store.clone());

    assert_eq!(states(registry.list()), expected);
    assert_eq!(states(store.load().unwrap()), expected);
    assert_eq!(registry.in_progress(), 0);
}

// Covers: a turn starts only on a job with none under way, so a second
// prompt to a running, waiting, or queued session is refused as busy and
// leaves it as it was, and an unknown job is reported as unknown; the turn of
// a session admitted through the shared budget queues for capacity first
// (#1714).
// Owner: daemon job registry.
#[test]
fn a_turn_starts_only_when_none_is_in_progress() {
    let home = TempDir::new().unwrap();
    let registry = JobRegistry::open(JobStore::open(home.path()).unwrap());
    let job = JobRecord::new_session(
        JobId::generate(),
        PathBuf::from("/work"),
        rho_sdk::SessionId::new(),
    );
    let id = job.id.clone();
    let started_by = JobRecord {
        admission: Admission::SharedBudget,
        ..JobRecord::new_session(
            JobId::generate(),
            PathBuf::from("/work"),
            rho_sdk::SessionId::new(),
        )
    };
    let child = started_by.id.clone();
    registry.register(job).unwrap();
    registry.register(started_by).unwrap();

    let start = |job: &JobId| {
        registry
            .start_turn(
                job,
                TurnRecord::starting(/*key*/ None),
                crate::caller_context::CallerContext::ROOT,
            )
            .map(|(moved, _)| moved.state)
    };
    let started = start(&id);
    let while_running = start(&id);
    registry.record(&id, JobEvent::InputOpened).unwrap();
    let while_waiting = start(&id);
    let unknown = start(&JobId::generate());
    let queued = start(&child);
    let while_queued = start(&child);

    assert_eq!(
        [
            started,
            while_running,
            while_waiting,
            unknown,
            queued,
            while_queued
        ],
        [
            Ok(JobState::Running),
            Err(StartTurnError::Busy),
            Err(StartTurnError::Busy),
            Err(StartTurnError::Unknown(super::UnknownJob)),
            Ok(JobState::Queued),
            Err(StartTurnError::Busy),
        ]
    );
    assert_eq!(
        registry.get(&id).map(|record| record.state),
        Some(JobState::WaitingForInput)
    );
}

// Covers: the daemon's stop records a running job as interrupted, on disk
// too, and refuses every job registered after it, so a run started during
// the stop is never left listed as running.
// Owner: daemon job registry stop.
#[test]
fn a_closed_registry_interrupts_its_turns_and_takes_no_new_jobs() {
    let home = TempDir::new().unwrap();
    let store = JobStore::open(home.path()).unwrap();
    let registry = JobRegistry::open(store.clone());
    let job = |state| JobRecord {
        state,
        ..JobRecord::new_session(
            JobId::generate(),
            PathBuf::from("/work"),
            rho_sdk::SessionId::new(),
        )
    };
    let running = job(JobState::Running);
    let expected = vec![(running.id.clone(), JobState::Ended(TurnEnd::Interrupted))];
    registry.register(running).unwrap();

    registry.close();

    assert!(matches!(
        registry.register(job(JobState::Queued)),
        Err(RegisterError::Closed)
    ));
    assert_eq!(states(registry.list()), expected);
    assert_eq!(states(store.load().unwrap()), expected);
}

// Covers: an upgrade closes the registry only while no job is in progress,
// and not after a turn that ran since it found the daemon idle, which may
// have left work its other checks missed; once closed, no turn starts, so a
// prompt that races the upgrade is refused rather than interrupted (#1713).
// Owner: daemon job registry upgrade.
#[test]
fn an_upgrade_closes_the_registry_only_while_idle() {
    let home = TempDir::new().unwrap();
    let registry = JobRegistry::open(JobStore::open(home.path()).unwrap());
    let job = JobRecord::new_session(
        JobId::generate(),
        PathBuf::from("/work"),
        rho_sdk::SessionId::new(),
    );
    let id = job.id.clone();
    registry.register(job).unwrap();

    let before = registry.idle().unwrap();
    registry
        .start_turn(
            &id,
            TurnRecord::starting(/*key*/ None),
            crate::caller_context::CallerContext::ROOT,
        )
        .unwrap();
    let while_running = registry.idle();
    registry
        .record(&id, JobEvent::TurnEnded(TurnEnd::Completed))
        .unwrap();
    // A turn that ran since the daemon was found idle may have left work.
    let after_a_turn = registry.close_if_still(before);
    let idle = registry.idle().unwrap();
    let still_idle = registry.close_if_still(idle);
    let next_turn = registry
        .start_turn(
            &id,
            TurnRecord::starting(/*key*/ None),
            crate::caller_context::CallerContext::ROOT,
        )
        .map(|(moved, _)| moved.state);

    assert_eq!(
        (while_running, after_a_turn, still_idle, next_turn),
        (None, false, true, Err(StartTurnError::Closed))
    );
}

// Covers: what a reopen finds for a session (#1661): nothing when no job ran
// its turns (another session's, or a finished subagent run that wrote it,
// does not count); the latest of its session jobs otherwise; and the job
// that writes it while one has a turn under way, a subagent run's included,
// so the session is not opened twice.
// Owner: daemon job registry session lookup.
#[test]
fn a_session_reopens_on_its_latest_job_unless_one_writes_it() {
    let session = rho_sdk::SessionId::new();
    let turns = |created_at, state| JobRecord {
        state,
        created_at,
        ..JobRecord::new_session(JobId::generate(), PathBuf::from("/work"), session.clone())
    };
    let subagent = |state| JobRecord {
        state,
        ..JobRecord::new_subagent(
            JobId::generate(),
            PathBuf::from("/work"),
            Some(session.clone()),
            "run".into(),
        )
    };
    let other = JobRecord::new_session(
        JobId::generate(),
        PathBuf::from("/work"),
        rho_sdk::SessionId::new(),
    );
    let older = turns(1, JobState::Ended(TurnEnd::Completed));
    let newer = turns(2, JobState::Ended(TurnEnd::Interrupted));
    let running = turns(3, JobState::Running);
    let writing = subagent(JobState::Running);
    let wrote = subagent(JobState::Ended(TurnEnd::Completed));
    let cases = [
        ("nothing", vec![], SessionJob::New),
        ("another session", vec![other.clone()], SessionJob::New),
        ("a finished subagent", vec![wrote.clone()], SessionJob::New),
        (
            "two session jobs",
            vec![newer.clone(), older.clone(), wrote],
            SessionJob::Last(Box::new(newer.clone())),
        ),
        (
            "a running turn",
            vec![older.clone(), running.clone()],
            SessionJob::Busy(running.id.clone()),
        ),
        (
            "a running subagent",
            vec![newer, other, writing.clone()],
            SessionJob::Busy(writing.id.clone()),
        ),
    ];
    for (name, records, expected) in cases {
        let home = TempDir::new().unwrap();
        let registry = JobRegistry::open(JobStore::open(home.path()).unwrap());
        for record in records {
            registry.register(record).unwrap();
        }
        assert_eq!(registry.session_job(&session), expected, "{name}");
    }
}

// Covers: a session job's record holds the grant of its turn under way, each
// turn's replacing the last one's, and a daemon that starts over the records
// still finds it (#1780).
// Owner: daemon job registry, session grants.
#[test]
fn a_turns_grant_is_kept_on_its_jobs_record_across_daemons() {
    use crate::caller_context::{Access, CallerContext, Scope, Workspaces};
    let home = TempDir::new().unwrap();
    let registry = JobRegistry::open(JobStore::open(home.path()).unwrap());
    let job = JobRecord::new_session(
        JobId::generate(),
        PathBuf::from("/work"),
        rho_sdk::SessionId::new(),
    );
    let id = job.id.clone();
    registry.register(job).unwrap();
    let limited = CallerContext {
        depth: 2,
        scope: Scope {
            access: Access::Read,
            workspaces: Workspaces::Only(vec![PathBuf::from("/work")]),
        },
    };

    let opened = registry.grant_of(&id);
    registry
        .start_turn(&id, TurnRecord::starting(/*key*/ None), limited.clone())
        .unwrap();
    let under_way = registry.grant_of(&id);
    drop(registry);
    let restarted = JobRegistry::open(JobStore::open(home.path()).unwrap());

    assert_eq!(
        (opened, under_way, restarted.grant_of(&id)),
        (
            Some(CallerContext::ROOT),
            Some(limited.clone()),
            Some(limited)
        )
    );
}

// Covers: a job with a grant limit, as a session an agent started has, never records more than the limit: a turn that asks for no limit, as
// a person's prompt does, gets the limit; one that asks for less gets less;
// a reopen is held the same; a daemon that starts over the records still
// holds it; and a job without a limit takes each grant as asked (#1796).
// Owner: daemon job registry, session grants.
#[test]
fn a_jobs_grant_never_exceeds_its_limit() {
    use crate::caller_context::{Access, CallerContext, Scope, Workspaces};
    let only = |root: &str| Workspaces::Only(vec![PathBuf::from(root)]);
    let limit = CallerContext {
        depth: 2,
        scope: Scope {
            access: Access::Write,
            workspaces: only("/work"),
        },
    };
    let narrower = CallerContext {
        depth: 3,
        scope: Scope {
            access: Access::Read,
            workspaces: only("/work/deep"),
        },
    };
    let home = TempDir::new().unwrap();
    let registry = JobRegistry::open(JobStore::open(home.path()).unwrap());
    let session = || {
        JobRecord::new_session(
            JobId::generate(),
            PathBuf::from("/work"),
            rho_sdk::SessionId::new(),
        )
    };
    let child = JobRecord {
        grant: limit.clone(),
        grant_limit: Some(limit.clone()),
        ..session()
    };
    let top_level = session();
    let (child, top_level) = {
        let ids = (child.id.clone(), top_level.id.clone());
        registry.register(child).unwrap();
        registry.register(top_level).unwrap();
        ids
    };
    let turn = |registry: &JobRegistry, job: &JobId, asked: &CallerContext| {
        let (_, granted) = registry
            .start_turn(job, TurnRecord::starting(/*key*/ None), asked.clone())
            .unwrap();
        registry
            .record(job, JobEvent::TurnEnded(TurnEnd::Completed))
            .unwrap();
        (granted, registry.grant_of(job).unwrap())
    };

    let by_a_person = turn(&registry, &child, &CallerContext::ROOT);
    let asking_less = turn(&registry, &child, &narrower);
    registry.set_grant(&child, CallerContext::ROOT);
    let reopened = registry.grant_of(&child).unwrap();
    let unlimited = turn(&registry, &top_level, &CallerContext::ROOT);
    drop(registry);
    let restarted = JobRegistry::open(JobStore::open(home.path()).unwrap());
    let after_a_restart = turn(&restarted, &child, &CallerContext::ROOT);

    assert_eq!(
        (
            by_a_person,
            asking_less,
            reopened,
            unlimited,
            after_a_restart
        ),
        (
            (limit.clone(), limit.clone()),
            (narrower.clone(), narrower),
            limit.clone(),
            (CallerContext::ROOT, CallerContext::ROOT),
            (limit.clone(), limit),
        )
    );
}

// Covers: the grant a session started from a subagent's or a workflow
// node's session is held under is that of the session whose turn runs
// them, not the unlimited one their own jobs keep (#1796).
// Owner: daemon job registry, session grants.
#[test]
fn a_run_a_session_started_is_under_that_sessions_grant() {
    use crate::caller_context::{Access, CallerContext, Scope, Workspaces};
    let home = TempDir::new().unwrap();
    let registry = JobRegistry::open(JobStore::open(home.path()).unwrap());
    let limited = CallerContext {
        depth: 1,
        scope: Scope {
            access: Access::Read,
            workspaces: Workspaces::Any,
        },
    };
    let session = JobRecord {
        grant: limited.clone(),
        ..JobRecord::new_session(
            JobId::generate(),
            PathBuf::from("/work"),
            rho_sdk::SessionId::new(),
        )
    };
    let workflow = JobRecord::new_workflow(
        session.id.clone(),
        PathBuf::from("/work"),
        crate::workflow::RunId::new(),
    );
    let subagent =
        |parent: JobId| JobRecord::new_subagent(parent, PathBuf::from("/work"), None, "run".into());
    let node = subagent(workflow.id.clone());
    let orphan = subagent(JobId::generate());
    let ids = [&session, &workflow, &node, &orphan].map(|record| record.id.clone());
    for record in [session, workflow, node, orphan] {
        registry.register(record).unwrap();
    }

    assert_eq!(
        ids.map(|id| registry.session_grant(&id)),
        [
            Some(limited.clone()),
            Some(limited.clone()),
            Some(limited),
            None
        ]
    );
}