rho-coding-agent 1.19.2

A lightweight agent harness inspired by Pi
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
use std::sync::Arc;

use super::*;
use crate::app::subagent_host_input::SubagentHostInputBridge;

#[test]
fn provider_selection_updates_are_shared_with_executor_clones() {
    let executor = AgentExecutor::new(
        Config::default(),
        PathBuf::new(),
        PathBuf::new(),
        SubagentHostInputBridge::new(),
    );
    let cloned = executor.clone();

    executor.update_selection(
        "openai-codex",
        "gpt-5.6-luna",
        rho_sdk::ReasoningLevel::Low,
        "codex",
    );

    let config = cloned.config.read().expect("delegated config lock");
    assert_eq!(config.provider, "openai-codex");
    assert_eq!(config.model, "gpt-5.6-luna");
    assert_eq!(config.auth, "codex");
    assert_eq!(config.reasoning, rho_sdk::ReasoningLevel::Low);
}

#[test]
fn permission_mode_updates_are_shared_with_executor_clones() {
    let executor = AgentExecutor::new(
        Config::default(),
        PathBuf::new(),
        PathBuf::new(),
        SubagentHostInputBridge::new(),
    );
    let cloned = executor.clone();

    executor.update_permission_mode(crate::permission::PermissionMode::Plan);
    assert_eq!(
        cloned.launch_permission_mode(),
        crate::permission::PermissionMode::Plan
    );

    cloned.update_permission_mode(crate::permission::PermissionMode::Supervised);
    assert_eq!(
        executor.launch_permission_mode(),
        crate::permission::PermissionMode::Supervised
    );
}

#[test]
fn default_concurrency_is_global_four_with_nested_claude_two() {
    let limits = concurrency_limits_from_env(None, None);
    assert_eq!(
        limits,
        ConcurrencyLimits {
            total: 4,
            claude: 2
        }
    );
}

#[test]
fn total_env_override_keeps_default_claude_cap_and_clamps() {
    let limits = concurrency_limits_from_env(Some("6"), None);
    assert_eq!(
        limits,
        ConcurrencyLimits {
            total: 6,
            claude: 2
        }
    );

    let tight = concurrency_limits_from_env(Some("1"), None);
    assert_eq!(
        tight,
        ConcurrencyLimits {
            total: 1,
            claude: 1
        }
    );
}

#[test]
fn claude_env_override_raises_nested_cap_within_total() {
    let limits = concurrency_limits_from_env(Some("6"), Some("4"));
    assert_eq!(
        limits,
        ConcurrencyLimits {
            total: 6,
            claude: 4
        }
    );
}

#[test]
fn claude_env_override_clamps_to_total() {
    let limits = concurrency_limits_from_env(Some("3"), Some("10"));
    assert_eq!(
        limits,
        ConcurrencyLimits {
            total: 3,
            claude: 3
        }
    );
}

#[test]
fn zero_invalid_and_huge_concurrency_values_fall_back() {
    assert_eq!(
        concurrency_limits_from_env(Some("0"), Some("0")),
        ConcurrencyLimits {
            total: 4,
            claude: 2
        }
    );
    assert_eq!(
        concurrency_limits_from_env(Some("-1"), Some("nope")),
        ConcurrencyLimits {
            total: 4,
            claude: 2
        }
    );
    assert_eq!(
        concurrency_limits_from_env(Some(""), Some(" ")),
        ConcurrencyLimits {
            total: 4,
            claude: 2
        }
    );
    // Larger than usize::MAX decimal representation is rejected by parse.
    let huge = format!("{}0", usize::MAX);
    assert_eq!(
        concurrency_limits_from_env(Some(huge.as_str()), Some(huge.as_str())),
        ConcurrencyLimits {
            total: 4,
            claude: 2
        }
    );
}

#[test]
fn total_and_claude_env_values_interact() {
    // Valid Claude override with invalid total keeps default total and clamps.
    assert_eq!(
        concurrency_limits_from_env(Some("bad"), Some("3")),
        ConcurrencyLimits {
            total: 4,
            claude: 3
        }
    );
    // Valid total with invalid Claude keeps default Claude, clamped to total.
    assert_eq!(
        concurrency_limits_from_env(Some("1"), Some("bad")),
        ConcurrencyLimits {
            total: 1,
            claude: 1
        }
    );
    // Both valid: Claude is min(requested, total).
    assert_eq!(
        concurrency_limits_from_env(Some("8"), Some("5")),
        ConcurrencyLimits {
            total: 8,
            claude: 5
        }
    );
}

const CLOSED_MSG: &str = "test concurrency pool closed";

#[tokio::test]
async fn cancellation_interrupts_concurrency_queue() {
    let permits = Arc::new(tokio::sync::Semaphore::new(0));
    let cancellation = RunCancellation::new();
    let queued = tokio::spawn({
        let permits = Arc::clone(&permits);
        let cancellation = cancellation.clone();
        async move { acquire_permit_or_cancel(permits, &cancellation, CLOSED_MSG).await }
    });

    cancellation.cancel();

    let permit = tokio::time::timeout(std::time::Duration::from_secs(1), queued)
        .await
        .expect("queued acquisition should observe cancellation")
        .unwrap()
        .unwrap();
    assert!(permit.is_none());
}

#[tokio::test]
async fn cancellation_wins_when_a_permit_is_already_available() {
    let permits = Arc::new(tokio::sync::Semaphore::new(1));
    let cancellation = RunCancellation::new();
    cancellation.cancel();

    let permit = acquire_permit_or_cancel(permits, &cancellation, CLOSED_MSG)
        .await
        .unwrap();

    assert!(permit.is_none());
}

#[tokio::test]
async fn closed_semaphore_returns_clear_error() {
    let permits = Arc::new(tokio::sync::Semaphore::new(1));
    permits.close();

    let error = acquire_permit_or_cancel(permits, &RunCancellation::new(), CLOSED_MSG)
        .await
        .expect_err("closed pool should error");
    assert!(
        error.to_string().contains(CLOSED_MSG),
        "unexpected error: {error:#}"
    );
}

/// Deterministic scheduling probe: wait until `ready` is true, yielding so the
/// runtime can progress other tasks without wall-clock sleeps.
async fn wait_until(mut ready: impl FnMut() -> bool) {
    for _ in 0..10_000 {
        if ready() {
            return;
        }
        tokio::task::yield_now().await;
    }
    panic!("condition not met after cooperative yields");
}

#[tokio::test(flavor = "current_thread")]
async fn claude_queue_does_not_starve_rho_and_progresses_after_release() {
    // total=2, claude=1: one active Claude holds both pools; a second Claude
    // waits on Claude capacity without taking the spare global slot, so Rho
    // can still start. After active Claude and Rho release, queued Claude
    // progresses.
    let total = Arc::new(tokio::sync::Semaphore::new(2));
    let claude = Arc::new(tokio::sync::Semaphore::new(1));

    let active_claude = acquire_runtime_permits(
        Arc::clone(&total),
        Arc::clone(&claude),
        CapacityClass::Claude,
        &RunCancellation::new(),
    )
    .await
    .unwrap()
    .expect("active Claude should acquire");
    assert_eq!(total.available_permits(), 1);
    assert_eq!(claude.available_permits(), 0);

    let queued_started = Arc::new(std::sync::atomic::AtomicBool::new(false));
    let queued_claude = tokio::spawn({
        let total = Arc::clone(&total);
        let claude = Arc::clone(&claude);
        let queued_started = Arc::clone(&queued_started);
        async move {
            queued_started.store(true, std::sync::atomic::Ordering::SeqCst);
            acquire_runtime_permits(
                total,
                claude,
                CapacityClass::Claude,
                &RunCancellation::new(),
            )
            .await
        }
    });

    wait_until(|| queued_started.load(std::sync::atomic::Ordering::SeqCst)).await;
    // Yield so the queued Claude task reaches its Claude-pool wait.
    for _ in 0..32 {
        tokio::task::yield_now().await;
    }
    assert!(
        !queued_claude.is_finished(),
        "queued Claude must still wait on Claude capacity"
    );
    // Spare global capacity must remain free while Claude is nested-waiting.
    assert_eq!(total.available_permits(), 1);
    assert_eq!(claude.available_permits(), 0);

    let rho = acquire_runtime_permits(
        Arc::clone(&total),
        Arc::clone(&claude),
        CapacityClass::Rho,
        &RunCancellation::new(),
    )
    .await
    .unwrap()
    .expect("Rho should take the spare global permit");
    assert_eq!(total.available_permits(), 0);
    assert_eq!(claude.available_permits(), 0);
    assert!(
        !queued_claude.is_finished(),
        "queued Claude must not finish while Claude capacity is held"
    );

    // Releasing the active Claude frees nested Claude capacity and one global
    // slot. Queued Claude can finish even while Rho still holds its spare
    // global permit - that is the non-starvation property.
    drop(active_claude);
    let queued = tokio::time::timeout(std::time::Duration::from_secs(1), queued_claude)
        .await
        .expect("queued Claude should acquire after active Claude releases")
        .unwrap()
        .unwrap()
        .expect("queued Claude should not cancel");
    // Rho still holds one global permit; queued Claude took the freed pair.
    assert_eq!(total.available_permits(), 0);
    assert_eq!(claude.available_permits(), 0);

    drop(rho);
    drop(queued);
    assert_eq!(total.available_permits(), 2);
    assert_eq!(claude.available_permits(), 1);
}

#[tokio::test(flavor = "current_thread")]
async fn claude_waits_on_global_after_taking_claude_capacity() {
    // Global full (two Rho runs), Claude free: Claude takes nested capacity
    // first, waits on global, then finishes when a Rho slot frees.
    let total = Arc::new(tokio::sync::Semaphore::new(2));
    let claude = Arc::new(tokio::sync::Semaphore::new(1));

    let rho_a = acquire_runtime_permits(
        Arc::clone(&total),
        Arc::clone(&claude),
        CapacityClass::Rho,
        &RunCancellation::new(),
    )
    .await
    .unwrap()
    .expect("rho a");
    let rho_b = acquire_runtime_permits(
        Arc::clone(&total),
        Arc::clone(&claude),
        CapacityClass::Rho,
        &RunCancellation::new(),
    )
    .await
    .unwrap()
    .expect("rho b");
    assert_eq!(total.available_permits(), 0);
    assert_eq!(claude.available_permits(), 1);

    let queued = tokio::spawn({
        let total = Arc::clone(&total);
        let claude = Arc::clone(&claude);
        async move {
            acquire_runtime_permits(
                total,
                claude,
                CapacityClass::Claude,
                &RunCancellation::new(),
            )
            .await
        }
    });

    wait_until(|| claude.available_permits() == 0).await;
    for _ in 0..16 {
        tokio::task::yield_now().await;
    }
    assert!(!queued.is_finished());
    assert_eq!(total.available_permits(), 0);
    assert_eq!(claude.available_permits(), 0);

    drop(rho_a);
    let permits = tokio::time::timeout(std::time::Duration::from_secs(1), queued)
        .await
        .expect("Claude should finish once a global slot frees")
        .unwrap()
        .unwrap()
        .expect("Claude acquired");
    assert_eq!(total.available_permits(), 0);
    assert_eq!(claude.available_permits(), 0);
    drop(rho_b);
    drop(permits);
    assert_eq!(total.available_permits(), 2);
    assert_eq!(claude.available_permits(), 1);
}

#[tokio::test(flavor = "current_thread")]
async fn cancellation_during_claude_wait_releases_nothing() {
    let total = Arc::new(tokio::sync::Semaphore::new(2));
    let claude = Arc::new(tokio::sync::Semaphore::new(0));
    let cancellation = RunCancellation::new();

    let queued = tokio::spawn({
        let total = Arc::clone(&total);
        let claude = Arc::clone(&claude);
        let cancellation = cancellation.clone();
        async move { acquire_runtime_permits(total, claude, CapacityClass::Claude, &cancellation).await }
    });

    for _ in 0..32 {
        tokio::task::yield_now().await;
    }
    cancellation.cancel();

    let result = tokio::time::timeout(std::time::Duration::from_secs(1), queued)
        .await
        .expect("cancel during Claude wait")
        .unwrap()
        .unwrap();
    assert!(result.is_none());
    assert_eq!(total.available_permits(), 2);
    assert_eq!(claude.available_permits(), 0);
}

#[tokio::test(flavor = "current_thread")]
async fn cancellation_during_global_wait_releases_claude_permit() {
    let total = Arc::new(tokio::sync::Semaphore::new(0));
    let claude = Arc::new(tokio::sync::Semaphore::new(1));
    let cancellation = RunCancellation::new();

    let queued = tokio::spawn({
        let total = Arc::clone(&total);
        let claude = Arc::clone(&claude);
        let cancellation = cancellation.clone();
        async move { acquire_runtime_permits(total, claude, CapacityClass::Claude, &cancellation).await }
    });

    // Let the task take the Claude permit and block on global.
    wait_until(|| claude.available_permits() == 0).await;
    for _ in 0..16 {
        tokio::task::yield_now().await;
    }
    assert_eq!(total.available_permits(), 0);
    assert_eq!(claude.available_permits(), 0);

    cancellation.cancel();

    let result = tokio::time::timeout(std::time::Duration::from_secs(1), queued)
        .await
        .expect("cancel during global wait")
        .unwrap()
        .unwrap();
    assert!(result.is_none());
    // Claude permit acquired before the global wait must be returned.
    assert_eq!(total.available_permits(), 0);
    assert_eq!(claude.available_permits(), 1);
}

#[tokio::test(flavor = "current_thread")]
async fn cancellation_during_rho_global_wait_holds_nothing() {
    let total = Arc::new(tokio::sync::Semaphore::new(0));
    let claude = Arc::new(tokio::sync::Semaphore::new(1));
    let cancellation = RunCancellation::new();

    let queued = tokio::spawn({
        let total = Arc::clone(&total);
        let claude = Arc::clone(&claude);
        let cancellation = cancellation.clone();
        async move { acquire_runtime_permits(total, claude, CapacityClass::Rho, &cancellation).await }
    });

    for _ in 0..32 {
        tokio::task::yield_now().await;
    }
    cancellation.cancel();

    let result = tokio::time::timeout(std::time::Duration::from_secs(1), queued)
        .await
        .expect("cancel during Rho global wait")
        .unwrap()
        .unwrap();
    assert!(result.is_none());
    assert_eq!(total.available_permits(), 0);
    assert_eq!(claude.available_permits(), 1);
}

#[tokio::test(flavor = "current_thread")]
async fn rho_skips_claude_pool_entirely() {
    let total = Arc::new(tokio::sync::Semaphore::new(1));
    // Claude pool empty: Rho must still acquire.
    let claude = Arc::new(tokio::sync::Semaphore::new(0));

    let rho = acquire_runtime_permits(
        Arc::clone(&total),
        Arc::clone(&claude),
        CapacityClass::Rho,
        &RunCancellation::new(),
    )
    .await
    .unwrap()
    .expect("Rho ignores Claude pool");
    assert_eq!(total.available_permits(), 0);
    assert_eq!(claude.available_permits(), 0);
    drop(rho);
    assert_eq!(total.available_permits(), 1);
    assert_eq!(claude.available_permits(), 0);
}

#[test]
fn update_selection_does_not_alter_bound_claude_runtime() {
    use crate::agent::{AgentDefinition, AgentId, AgentRuntimeSpec, PromptPolicy};
    use crate::app::agent_binding::{AgentBinder, AgentInvocation, AgentRole, BoundRuntime};

    let executor = AgentExecutor::new(
        Config {
            provider: "openai-codex".into(),
            model: "gpt-parent-before".into(),
            permission_mode: crate::permission::PermissionMode::Plan,
            ..Config::default()
        },
        PathBuf::new(),
        PathBuf::new(),
        SubagentHostInputBridge::new(),
    );

    let definition = Arc::new(AgentDefinition {
        id: AgentId::new("claude-bound").unwrap(),
        description: "claude".into(),
        prompt: PromptPolicy::Replace("plan".into()),
        runtime: AgentRuntimeSpec::ClaudeCli(crate::agent::ClaudeAgentConfig {
            tools: crate::agent::ClaudeToolPolicy::Allow(vec!["Read".into()]),
            inherit_claude_config: false,
            model: Some("opus".into()),
            reasoning: None,
        }),
    });

    // Bind before the parent model changes.
    let host_before = executor
        .config
        .read()
        .expect("delegated config lock")
        .clone();
    let bound_before = AgentBinder::bind(
        Arc::clone(&definition),
        AgentInvocation {
            role: AgentRole::Delegated,
            available_tools: crate::agent::AgentCapabilities::default(),
        },
        &host_before,
    )
    .unwrap();

    executor.update_selection(
        "moonshot-kimi",
        "kimi-parent-after",
        rho_sdk::ReasoningLevel::High,
        "kimi-oauth",
    );

    let host_after = executor
        .config
        .read()
        .expect("delegated config lock")
        .clone();
    assert_eq!(host_after.provider, "moonshot-kimi");
    assert_eq!(host_after.model, "kimi-parent-after");

    // Already-bound Claude runtime keeps definition model/tools; parent snapshot
    // is irrelevant once BoundRuntime::ClaudeCli is produced.
    match bound_before.runtime() {
        BoundRuntime::ClaudeCli {
            model,
            tools,
            inherit_claude_config,
            permission_mode,
            ..
        } => {
            assert_eq!(model.as_deref(), Some("opus"));
            assert_eq!(tools.as_slice(), ["Read".to_string()].as_slice());
            assert!(!*inherit_claude_config);
            assert_eq!(*permission_mode, crate::permission::PermissionMode::Plan);
        }
        BoundRuntime::Rho { .. } => panic!("expected Claude bound runtime"),
    }
    assert!(bound_before.rho_config().is_none());

    // Re-bind after update_model: Claude model still comes from definition only.
    let bound_after = AgentBinder::bind(
        definition,
        AgentInvocation {
            role: AgentRole::Delegated,
            available_tools: crate::agent::AgentCapabilities::default(),
        },
        &host_after,
    )
    .unwrap();
    match bound_after.runtime() {
        BoundRuntime::ClaudeCli {
            model,
            permission_mode,
            ..
        } => {
            assert_eq!(model.as_deref(), Some("opus"));
            // Permission mode is the only host field Claude bind snapshots.
            assert_eq!(*permission_mode, crate::permission::PermissionMode::Plan);
        }
        BoundRuntime::Rho { .. } => panic!("expected Claude bound runtime"),
    }
    assert_ne!(host_after.model, "opus");
    assert_ne!(host_after.provider, "claude-code");
}