roba 0.7.1

A sharp, focused sugaring of claude -p -- pipeable, composable, safe-by-default, session-re-enterable.
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
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
//! Live integration tests -- these actually invoke the real `claude`
//! binary and cost money. Marked `#[ignore]` so they only run when
//! you opt in:
//!
//!   cargo test --test live -- --ignored --nocapture
//!   just live                  # equivalent (full suite)
//!   just live-smoke            # the cheap subset, a few tests
//!   just live-category perms   # one category by prefix
//!
//! Each test runs in a fresh tempdir via `-C PATH` so sessions don't
//! bleed between tests (claude scopes sessions by cwd / project, and
//! each tempdir is its own project from claude's POV).
//!
//! All tests default to `--model haiku` for cost. A test that cares
//! about a specific model can append `--model <id>` -- clap's
//! last-wins semantics applies.
//!
//! Budget: at haiku rates the full suite is well under $1.
//! Keep prompts short and answers terse to minimize spend.
//!
//! Naming convention: every test is named `live_<category>_<descriptor>`
//! so `cargo test ... live_<category>_` filters a single category and
//! the `just live-category <cat>` target works. Current categories:
//! `smoke`, `output`, `session`, `stream`, `trace`, `perms`, `compose`,
//! `profile`, `env`. New categories from #22 (e.g. `cost`, `subcmd`)
//! follow the same shape. When adding a test, pick the category prefix
//! first; co-locate the helpers (`roba_in`, `fresh_dir`,
//! `fixture_with_config`, `empty_user_home`) at the top of this file.

use assert_cmd::Command;
use predicates::prelude::*;
use std::path::Path;

/// Run `roba` against `dir` via `-C`, defaulting to the haiku model.
/// Tests that need a specific model can append `--model <id>` later;
/// clap's last-occurrence-wins semantics applies.
fn roba_in(dir: &Path) -> Command {
    let mut cmd = Command::cargo_bin("roba").expect("cargo-built roba binary");
    cmd.args([
        "-C",
        dir.to_str().expect("utf-8 tempdir path"),
        "--model",
        "haiku",
    ]);
    cmd
}

fn fresh_dir() -> tempfile::TempDir {
    tempfile::tempdir().expect("create test tempdir")
}

/// Make a tempdir pre-seeded with a `roba.toml`. Adds a `.git`
/// marker so the config walk-up stops at the tempdir boundary
/// (otherwise it could leak the developer's own `roba.toml` higher
/// up the tree). Returns the TempDir so the caller can keep it
/// alive for the duration of the test.
fn fixture_with_config(content: &str) -> tempfile::TempDir {
    let tmp = fresh_dir();
    std::fs::create_dir_all(tmp.path().join(".git")).expect(".git marker");
    std::fs::write(tmp.path().join("roba.toml"), content).expect("write roba.toml");
    tmp
}

/// An empty tempdir to set `XDG_CONFIG_HOME` to. Each test that wants
/// to be sure it doesn't pick up the developer's own
/// `~/.config/roba.toml` should hold this for the duration of the
/// `roba` call.
fn empty_user_home() -> tempfile::TempDir {
    fresh_dir()
}

// ---------------------------------------------------------------------------
// smoke: basic round-trip
// ---------------------------------------------------------------------------

#[test]
#[ignore]
fn live_smoke_prompt() {
    let dir = fresh_dir();
    roba_in(dir.path())
        .arg("respond with the single word: pong")
        .assert()
        .success()
        .stdout(predicate::str::contains("pong"));
}

#[test]
#[ignore]
fn live_smoke_cwd_scopes_session_to_path() {
    // Verify -C scopes claude's session to the given path: a seeded
    // session in dir A is reachable from -c when we point -C at A again,
    // even though the test process's cwd never changed.
    let dir = fresh_dir();
    roba_in(dir.path())
        .arg("remember the word: aurora")
        .assert()
        .success();

    let out = roba_in(dir.path())
        .args(["-c", "-p", "what word did I ask you to remember"])
        .output()
        .expect("run roba -c");
    assert!(out.status.success());
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(
        stdout.to_lowercase().contains("aurora"),
        "expected -C to scope sessions to the tmp dir, got: {stdout}"
    );
}

// ---------------------------------------------------------------------------
// output shaping
// ---------------------------------------------------------------------------

#[test]
#[ignore]
fn live_output_quiet_no_metadata() {
    let dir = fresh_dir();
    let out = roba_in(dir.path())
        .args(["-q", "respond with the single word: hush"])
        .output()
        .expect("run roba");
    assert!(out.status.success(), "roba failed: {out:?}");
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        !stderr.contains("cost"),
        "expected no cost footer with -q, got stderr: {stderr}"
    );
}

#[test]
#[ignore]
fn live_output_json_valid() {
    let dir = fresh_dir();
    let out = roba_in(dir.path())
        .args(["--json", "respond with the single word: jay"])
        .output()
        .expect("run roba");
    assert!(out.status.success());
    let stdout = String::from_utf8_lossy(&out.stdout);
    let parsed: serde_json::Value =
        serde_json::from_str(&stdout).expect("--json produced non-JSON stdout");
    // v1 envelope from #33: { version: 1, result: { ... }, refusal: bool }
    assert_eq!(parsed["version"].as_u64(), Some(1));
    assert!(parsed.get("result").is_some());
    assert!(parsed["result"].get("session_id").is_some());
    assert!(parsed["result"].get("duration_ms").is_some());
    assert!(parsed.get("refusal").is_some());
}

#[test]
#[ignore]
fn live_output_refusal_in_json_envelope() {
    // The v1 envelope's top-level `refusal` flag surfaces
    // `output::looks_like_refusal` to non-TTY consumers. We assert the wiring
    // on the RELIABLE side: a normal answer carries `refusal: false`.
    //
    // The `refusal: true` path is deliberately NOT live-tested. claude refuses
    // to roleplay a refusal -- asked to echo "I can't help with that" it
    // answers "I should respond authentically..." instead -- and engineering a
    // genuine policy refusal is both unreliable and generates harmful content.
    // The true-case detection (a refusal-marker prefix flips the flag) is
    // covered deterministically by the `looks_like_refusal` unit tests in
    // `src/output.rs` (refusal_detects_common_phrases, _is_case_insensitive,
    // _tolerates_leading_whitespace, _does_not_match_normal_answers).
    let dir = fresh_dir();
    let out = roba_in(dir.path())
        .args([
            "--json",
            "--quiet",
            "what is 2+2? answer with just the number.",
        ])
        .output()
        .expect("run roba --json");
    assert!(out.status.success(), "roba failed: {out:?}");
    let stdout = String::from_utf8_lossy(&out.stdout);
    let parsed: serde_json::Value =
        serde_json::from_str(&stdout).expect("--json produced non-JSON stdout");
    assert_eq!(parsed["version"].as_u64(), Some(1));
    assert_eq!(
        parsed["refusal"].as_bool(),
        Some(false),
        "a normal answer must not be flagged as a refusal, got: {stdout}"
    );
}

#[test]
#[ignore]
fn live_output_code_strips_fences() {
    let dir = fresh_dir();
    let out = roba_in(dir.path())
        .args([
            "write exactly one rust function called id that takes i32 and returns it. fenced code block, no other prose.",
            "--code",
        ])
        .output()
        .expect("run roba");
    assert!(out.status.success());
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(
        !stdout.contains("```"),
        "--code did not strip fences: {stdout}"
    );
    assert!(
        stdout.contains("fn id"),
        "expected fn id in output, got: {stdout}"
    );
}

#[test]
#[ignore]
fn live_output_out_writes_file_and_stdout() {
    let dir = fresh_dir();
    let target = dir.path().join("out.md");

    let out = roba_in(dir.path())
        .args([
            "respond with the single word: saved",
            "--out",
            target.to_str().unwrap(),
        ])
        .output()
        .expect("run roba --out");
    assert!(out.status.success());
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(
        stdout.to_lowercase().contains("saved"),
        "expected 'saved' in stdout with --out, got: {stdout}"
    );
    let file_contents = std::fs::read_to_string(&target).expect("read saved file");
    assert!(
        file_contents.to_lowercase().contains("saved"),
        "expected 'saved' in saved file, got: {file_contents}"
    );
}

#[test]
#[ignore]
fn live_output_out_json_extension() {
    let dir = fresh_dir();
    let target = dir.path().join("out.json");

    roba_in(dir.path())
        .args([
            "respond with the single word: jp",
            "--out",
            target.to_str().unwrap(),
        ])
        .assert()
        .success();

    let file_contents = std::fs::read_to_string(&target).expect("read saved file");
    let parsed: serde_json::Value =
        serde_json::from_str(&file_contents).expect("saved file should be JSON");
    // v1 envelope from #33: session_id is nested under result
    assert_eq!(parsed["version"].as_u64(), Some(1));
    assert!(parsed["result"].get("session_id").is_some());
}

// ---------------------------------------------------------------------------
// session continuation + fork
// ---------------------------------------------------------------------------

#[test]
#[ignore]
fn live_session_continue_carries_context() {
    let dir = fresh_dir();
    roba_in(dir.path())
        .arg("remember the word: zenith")
        .assert()
        .success();

    let out = roba_in(dir.path())
        .args(["-c", "-p", "what word did I ask you to remember"])
        .output()
        .expect("run roba -c");
    assert!(out.status.success());
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(
        stdout.to_lowercase().contains("zenith"),
        "expected 'zenith' from continued session, got: {stdout}"
    );
}

#[test]
#[ignore]
fn live_session_resume_fork_new_id() {
    let dir = fresh_dir();

    // 1. seed a session and grab its id from --json (v1 envelope: nested under result)
    let seed = roba_in(dir.path())
        .args(["--json", "respond with the single word: seed"])
        .output()
        .expect("seed run");
    let seed_json: serde_json::Value = serde_json::from_slice(&seed.stdout).expect("json");
    let seed_id = seed_json["result"]["session_id"]
        .as_str()
        .expect("session_id")
        .to_string();

    // 2. resume + fork -- expect a NEW session id in the result
    // -c=ID is the unified continue/resume flag from #20
    let resume_arg = format!("-c={seed_id}");
    let fork = roba_in(dir.path())
        .args([
            "--json",
            &resume_arg,
            "--fork",
            "respond with the single word: forked",
        ])
        .output()
        .expect("fork run");
    let fork_json: serde_json::Value = serde_json::from_slice(&fork.stdout).expect("json");
    let fork_id = fork_json["result"]["session_id"]
        .as_str()
        .expect("session_id");

    assert_ne!(
        seed_id, fork_id,
        "expected fork to produce a new session id"
    );
}

#[test]
#[ignore]
fn live_session_id_assigns() {
    // --session-id assigns a caller-chosen UUID to the new session.
    // Assert the mechanics (the flag plumbs through and the returned
    // session id EQUALS what we supplied), not model behavior. A fixed
    // valid UUID keeps the run deterministic.
    let dir = fresh_dir();
    let chosen = "5f3c1a2b-4d6e-4f80-9a1b-2c3d4e5f6071";

    let out = roba_in(dir.path())
        .args([
            "--json",
            "--session-id",
            chosen,
            "respond with the single word: assigned",
        ])
        .output()
        .expect("session-id run");
    let parsed: serde_json::Value = serde_json::from_slice(&out.stdout).expect("json");
    let returned = parsed["result"]["session_id"].as_str().expect("session_id");

    assert_eq!(
        returned, chosen,
        "expected the returned session id to equal the supplied --session-id"
    );
}

#[test]
#[ignore]
fn live_show_roundtrips() {
    // Create a session, capture its id, then `roba show` it back and
    // assert the reconstructed envelope roundtrips: same session id, a
    // non-empty result. Mechanics, not model compliance.
    let dir = fresh_dir();
    let seed = roba_in(dir.path())
        .args(["--json", "respond with the single word: echo"])
        .output()
        .expect("run roba --json");
    assert!(seed.status.success(), "seed failed: {seed:?}");
    let seed_json: serde_json::Value =
        serde_json::from_slice(&seed.stdout).expect("seed stdout is JSON");
    let id = seed_json["result"]["session_id"]
        .as_str()
        .expect("session_id");

    // `show` finds the session by id across all projects, so it does not
    // need `-C`; use a plain binary invocation against the real $HOME.
    let out = Command::cargo_bin("roba")
        .expect("cargo-built roba binary")
        .args(["show", id, "--json"])
        .output()
        .expect("run roba show");
    assert!(out.status.success(), "show failed: {out:?}");
    let shown: serde_json::Value =
        serde_json::from_slice(&out.stdout).expect("show stdout is JSON");
    assert_eq!(
        shown["result"]["session_id"].as_str(),
        Some(id),
        "session id must roundtrip"
    );
    assert!(
        !shown["result"]["result"]
            .as_str()
            .unwrap_or_default()
            .is_empty(),
        "reconstructed result must be non-empty"
    );
}

#[test]
#[ignore]
fn live_show_wait_returns_completed_result() {
    // A completed session is already terminal on disk by the time the
    // seed call returns, so `show --wait` short-circuits its poll loop
    // and renders immediately. Mechanics, not model compliance: assert
    // the id roundtrips and the result is non-empty within the timeout.
    let dir = fresh_dir();
    let seed = roba_in(dir.path())
        .args(["--json", "respond with the single word: waited"])
        .output()
        .expect("run roba --json");
    assert!(seed.status.success(), "seed failed: {seed:?}");
    let seed_json: serde_json::Value =
        serde_json::from_slice(&seed.stdout).expect("seed stdout is JSON");
    let id = seed_json["result"]["session_id"]
        .as_str()
        .expect("session_id");

    let out = Command::cargo_bin("roba")
        .expect("cargo-built roba binary")
        .args(["show", id, "--wait", "--timeout", "60", "--json"])
        .output()
        .expect("run roba show --wait");
    assert!(out.status.success(), "show --wait failed: {out:?}");
    let shown: serde_json::Value =
        serde_json::from_slice(&out.stdout).expect("show stdout is JSON");
    assert_eq!(shown["result"]["session_id"].as_str(), Some(id));
    assert!(
        !shown["result"]["result"]
            .as_str()
            .unwrap_or_default()
            .is_empty(),
        "waited reconstructed result must be non-empty"
    );
}

#[test]
#[ignore]
fn live_json_schema_accepted() {
    // --json-schema constrains structured output. Assert MECHANICS only:
    // the flag is accepted, the run completes, and the --json envelope
    // parses. We do NOT assert the model's output is schema-valid -- that
    // is model compliance and flaky. roba reads the schema from a file
    // and inlines it; a tiny valid JSON Schema keeps the run cheap.
    let dir = fresh_dir();
    let schema_path = dir.path().join("schema.json");
    std::fs::write(
        &schema_path,
        r#"{"type":"object","properties":{"answer":{"type":"string"}},"required":["answer"]}"#,
    )
    .expect("write schema");

    let out = roba_in(dir.path())
        .args(["--json", "--json-schema"])
        .arg(&schema_path)
        .arg("respond with the single word: schema")
        .output()
        .expect("json-schema run");

    assert!(out.status.success(), "roba failed: {out:?}");
    let parsed: serde_json::Value =
        serde_json::from_slice(&out.stdout).expect("--json produced non-JSON stdout");
    assert_eq!(parsed["version"].as_u64(), Some(1));
    assert!(parsed.get("result").is_some());
}

#[test]
#[ignore]
fn live_json_schema_default_render() {
    // --json-schema with NO --json: the validated answer lands in
    // structured_output (the textual result is empty), and roba's default
    // path renders it as pretty JSON on stdout instead of a blank line.
    // Assert MECHANICS: stdout is non-empty and parses as a JSON object.
    let dir = fresh_dir();
    let schema_path = dir.path().join("schema.json");
    std::fs::write(
        &schema_path,
        r#"{"type":"object","properties":{"answer":{"type":"string"}},"required":["answer"]}"#,
    )
    .expect("write schema");

    let out = roba_in(dir.path())
        .arg("--json-schema")
        .arg(&schema_path)
        .arg("capital of France?")
        .output()
        .expect("json-schema default run");

    assert!(out.status.success(), "roba failed: {out:?}");
    assert!(
        !out.stdout.is_empty(),
        "default path printed nothing; structured_output was dropped"
    );
    let parsed: serde_json::Value =
        serde_json::from_slice(&out.stdout).expect("default path produced non-JSON stdout");
    assert!(
        parsed.get("answer").is_some(),
        "structured output missing `answer` key: {parsed}"
    );
}

// ---------------------------------------------------------------------------
// streaming + tool use
// ---------------------------------------------------------------------------

#[test]
#[ignore]
fn live_stream_emits_to_stdout() {
    let dir = fresh_dir();
    let out = roba_in(dir.path())
        .args(["respond with the single word: streamed", "--stream"])
        .output()
        .expect("run roba --stream");
    assert!(out.status.success());
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(
        stdout.to_lowercase().contains("streamed"),
        "expected 'streamed' on stdout, got: {stdout}"
    );
}

#[test]
#[ignore]
fn live_stream_session_id_on_stderr() {
    // When --stream is active the spawned session id is printed to stderr
    // as `[roba] session: <id>` on the first event that carries it.
    // --quiet suppresses the line (it is metadata).
    let dir = fresh_dir();

    // With --stream the line must appear on stderr.
    let out = roba_in(dir.path())
        .args(["--stream", "respond with the single word: ping"])
        .output()
        .expect("run roba --stream");
    assert!(out.status.success(), "roba --stream failed: {out:?}");
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("[roba] session:"),
        "expected [roba] session: on stderr with --stream, got stderr: {stderr}"
    );

    // With --quiet the line must be suppressed.
    let quiet_out = roba_in(dir.path())
        .args(["--stream", "--quiet", "respond with the single word: ping"])
        .output()
        .expect("run roba --stream --quiet");
    assert!(
        quiet_out.status.success(),
        "roba --stream --quiet failed: {quiet_out:?}"
    );
    let quiet_stderr = String::from_utf8_lossy(&quiet_out.stderr);
    assert!(
        !quiet_stderr.contains("[roba] session:"),
        "expected no [roba] session: on stderr with --quiet, got stderr: {quiet_stderr}"
    );
}

#[test]
#[ignore]
fn live_trace_writes_jsonl() {
    // --trace PATH forces the streaming pipeline internally (no
    // --stream needed) and writes every spawned-session event to PATH
    // as one JSON line, in arrival order. The final answer still
    // renders to stdout the way the non-streaming path would.
    let dir = fresh_dir();
    let trace = dir.path().join("run.jsonl");

    let out = roba_in(dir.path())
        .args([
            "respond with the single word: traced",
            "--trace",
            trace.to_str().unwrap(),
        ])
        .output()
        .expect("run roba --trace");
    assert!(out.status.success(), "roba --trace failed: {out:?}");

    // The answer still reaches stdout (non-stream render).
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(
        stdout.to_lowercase().contains("traced"),
        "expected 'traced' on stdout with --trace, got: {stdout}"
    );

    // The trace file exists and every line parses as JSON.
    let body = std::fs::read_to_string(&trace).expect("read trace file");
    let mut lines = 0usize;
    let mut saw_assistant = false;
    let mut saw_result = false;
    for line in body.lines().filter(|l| !l.trim().is_empty()) {
        lines += 1;
        let ev: serde_json::Value = serde_json::from_str(line)
            .unwrap_or_else(|e| panic!("non-JSON trace line {line:?}: {e}"));
        match ev["type"].as_str() {
            Some("assistant") => saw_assistant = true,
            Some("result") => saw_result = true,
            _ => {}
        }
    }
    assert!(lines >= 1, "expected at least one trace line, got none");
    assert!(saw_assistant, "expected an assistant event in the trace");
    assert!(saw_result, "expected a result event in the trace");
}

// ---------------------------------------------------------------------------
// permissions
// ---------------------------------------------------------------------------

#[test]
#[ignore]
fn live_perms_readonly_blocks_edit() {
    let dir = fresh_dir();
    let target = dir.path().join("subject.txt");
    std::fs::write(&target, "original").expect("seed file");

    // Default: Edit isn't in the allow list. Claude should respond
    // (perhaps explaining it can't), but the file should be unchanged.
    roba_in(dir.path())
        .arg(format!(
            "edit the file at {} to replace its contents with the single word: changed. \
             if you cannot, briefly say so.",
            target.display()
        ))
        .assert()
        .success();

    let contents = std::fs::read_to_string(&target).expect("read target");
    assert_eq!(
        contents.trim(),
        "original",
        "readonly default should keep the file unchanged, got: {contents}"
    );
}

#[test]
#[ignore]
fn live_perms_writable_enables_edit() {
    let dir = fresh_dir();
    let target = dir.path().join("subject.txt");
    std::fs::write(&target, "original").expect("seed file");

    roba_in(dir.path())
        .args([
            "--writable",
            &format!(
                "edit the file at {} so its contents are exactly the single word: changed",
                target.display()
            ),
        ])
        .assert()
        .success();

    let contents = std::fs::read_to_string(&target).expect("read target");
    assert!(
        contents.contains("changed"),
        "--writable should allow edits, got: {contents}"
    );
}

#[test]
#[ignore]
fn live_perms_deny_tools_blocks_modification() {
    let dir = fresh_dir();
    let target = dir.path().join("subject.txt");
    std::fs::write(&target, "original").expect("seed file");

    // --writable opens Edit + Write. Denying only Edit isn't enough --
    // claude would fall back to Write to satisfy the request, which is
    // correct semantically (deny-tool only blocks the named tool, not
    // its alternatives). To actually prevent file modification with
    // --writable on, both writing tools must be denied.
    roba_in(dir.path())
        .args([
            "--writable",
            "--deny-tool",
            "Edit",
            "--deny-tool",
            "Write",
            &format!(
                "edit the file at {} to replace its contents with the single word: changed. \
                 if you cannot, briefly say so.",
                target.display()
            ),
        ])
        .assert()
        .success();

    let contents = std::fs::read_to_string(&target).expect("read target");
    assert_eq!(
        contents.trim(),
        "original",
        "denying Edit + Write should block all file modifications, got: {contents}"
    );
}

#[test]
#[ignore]
fn live_perms_full_auto_enables_bash() {
    let dir = fresh_dir();
    let target = dir.path().join("flag.txt");

    // --full-auto bypasses everything; Bash should work even though
    // it isn't in the default allow list.
    roba_in(dir.path())
        .args([
            "--full-auto",
            &format!(
                "use the Bash tool to write the literal string `bypassed` into the file at {}. \
                 just run the shell command; no other prose.",
                target.display()
            ),
        ])
        .assert()
        .success();

    let contents = std::fs::read_to_string(&target).expect("read target");
    assert!(
        contents.contains("bypassed"),
        "--full-auto should allow Bash to write the file, got: {contents}"
    );
}

// ---------------------------------------------------------------------------
// composition: attach / var
// ---------------------------------------------------------------------------

#[test]
#[ignore]
fn live_compose_attach_files_visible() {
    let dir = fresh_dir();
    let attach_path = dir.path().join("greeting.txt");
    std::fs::write(&attach_path, "secret word: kazoo").expect("write attach file");

    let out = roba_in(dir.path())
        .args([
            "--attach",
            attach_path.to_str().unwrap(),
            "what is the secret word in the attached file? answer with just the word.",
        ])
        .output()
        .expect("run roba --attach");
    assert!(out.status.success());
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(
        stdout.to_lowercase().contains("kazoo"),
        "expected 'kazoo' to be referenced from attached file, got: {stdout}"
    );
}

#[test]
#[ignore]
fn live_compose_var_substitution() {
    let dir = fresh_dir();
    let tpl = dir.path().join("tpl.md");
    std::fs::write(&tpl, "Respond with exactly: {{TARGET}}").expect("write tpl");

    let out = roba_in(dir.path())
        .args(["-f", tpl.to_str().unwrap(), "--var", "TARGET=lighthouse"])
        .output()
        .expect("run roba -f --var");
    assert!(out.status.success());
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(
        stdout.to_lowercase().contains("lighthouse"),
        "expected substituted value to reach the model, got: {stdout}"
    );
}

#[test]
#[ignore]
fn live_compose_stdin_with_prompt() {
    // Piped stdin + a positional prompt: the stdin merges in as a context
    // block instead of being dropped. Assert on roba's OWN echoed
    // resolved prompt (stderr, printed before the model call) -- this is
    // deterministic, not model compliance.
    //
    // Note: `--echo` is gated on `!quiet`, so `-q` would suppress it;
    // `--echo --plain` is the right combo for observing the resolved
    // prompt.
    let dir = fresh_dir();
    let out = roba_in(dir.path())
        .args(["--echo", "--plain", "what is the marker?"])
        .write_stdin("MARKER LINE 42")
        .output()
        .expect("run roba --echo with piped stdin");
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("MARKER LINE 42"),
        "echoed prompt should contain the piped marker, got stderr: {stderr}"
    );
    assert!(
        stderr.contains("what is the marker?"),
        "echoed prompt should contain the positional question, got stderr: {stderr}"
    );
}

// ---------------------------------------------------------------------------
// profiles + env-var layer
// ---------------------------------------------------------------------------

#[test]
#[ignore]
fn live_profile_writable_via_top_level() {
    // Top-level `writable = true` in roba.toml should let claude
    // edit a file, with no --profile flag and no env var.
    let dir = fixture_with_config("writable = true\n");
    let user = empty_user_home();
    let target = dir.path().join("t.txt");
    std::fs::write(&target, "original").expect("seed");

    roba_in(dir.path())
        .env("XDG_CONFIG_HOME", user.path())
        .arg(format!(
            "edit the file at {} so its contents are exactly the single word: changed",
            target.display()
        ))
        .assert()
        .success();

    let contents = std::fs::read_to_string(&target).expect("read");
    assert!(
        contents.contains("changed"),
        "top-level writable should apply, got: {contents}"
    );
}

#[test]
#[ignore]
fn live_profile_named_overlay_via_flag() {
    // [profile.edit].writable = true activated via --profile edit.
    let dir = fixture_with_config("[profile.edit]\nwritable = true\n");
    let user = empty_user_home();
    let target = dir.path().join("t.txt");
    std::fs::write(&target, "original").expect("seed");

    roba_in(dir.path())
        .env("XDG_CONFIG_HOME", user.path())
        .args([
            "--profile",
            "edit",
            &format!(
                "edit the file at {} so its contents are exactly the single word: changed",
                target.display()
            ),
        ])
        .assert()
        .success();

    let contents = std::fs::read_to_string(&target).expect("read");
    assert!(
        contents.contains("changed"),
        "--profile edit overlay should apply writable, got: {contents}"
    );
}

#[test]
#[ignore]
fn live_profile_default_auto_applies() {
    // [profile.default].writable = true should apply with no flag.
    let dir = fixture_with_config("[profile.default]\nwritable = true\n");
    let user = empty_user_home();
    let target = dir.path().join("t.txt");
    std::fs::write(&target, "original").expect("seed");

    roba_in(dir.path())
        .env("XDG_CONFIG_HOME", user.path())
        .env_remove("ROBA_PROFILE")
        .arg(format!(
            "edit the file at {} so its contents are exactly the single word: changed",
            target.display()
        ))
        .assert()
        .success();

    let contents = std::fs::read_to_string(&target).expect("read");
    assert!(
        contents.contains("changed"),
        "[profile.default] should auto-apply, got: {contents}"
    );
}

#[test]
#[ignore]
fn live_profile_no_default_skips_auto() {
    // Same [profile.default] config but --no-default-profile bypasses
    // it, so writable stays off and the file is unchanged.
    let dir = fixture_with_config("[profile.default]\nwritable = true\n");
    let user = empty_user_home();
    let target = dir.path().join("t.txt");
    std::fs::write(&target, "original").expect("seed");

    roba_in(dir.path())
        .env("XDG_CONFIG_HOME", user.path())
        .env_remove("ROBA_PROFILE")
        .args([
            "--no-default-profile",
            &format!(
                "edit the file at {} to replace its contents with the single word: changed. \
                 if you cannot, briefly say so.",
                target.display()
            ),
        ])
        .assert()
        .success();

    let contents = std::fs::read_to_string(&target).expect("read");
    assert_eq!(
        contents.trim(),
        "original",
        "--no-default-profile should skip auto-apply, got: {contents}"
    );
}

#[test]
#[ignore]
fn live_env_writable_enables_edit() {
    // ROBA_WRITABLE=1 should add Edit/Write to the allow list even
    // when no CLI flag and no profile sets it.
    let dir = fresh_dir();
    let user = empty_user_home();
    let target = dir.path().join("t.txt");
    std::fs::write(&target, "original").expect("seed");

    roba_in(dir.path())
        .env("XDG_CONFIG_HOME", user.path())
        .env("ROBA_WRITABLE", "1")
        .arg(format!(
            "edit the file at {} so its contents are exactly the single word: changed",
            target.display()
        ))
        .assert()
        .success();

    let contents = std::fs::read_to_string(&target).expect("read");
    assert!(
        contents.contains("changed"),
        "ROBA_WRITABLE=1 should enable Edit, got: {contents}"
    );
}

#[test]
#[ignore]
fn live_env_var_per_key_substitution() {
    // ROBA_VAR_TARGET=spruce substitutes {{TARGET}} in the prompt
    // template loaded via -f, no --var CLI flag needed.
    let dir = fresh_dir();
    let user = empty_user_home();
    let tpl = dir.path().join("tpl.md");
    std::fs::write(&tpl, "Respond with exactly: {{TARGET}}").expect("seed tpl");

    let out = roba_in(dir.path())
        .env("XDG_CONFIG_HOME", user.path())
        .env("ROBA_VAR_TARGET", "spruce")
        .args(["-f", tpl.to_str().unwrap()])
        .output()
        .expect("run");
    assert!(out.status.success());
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(
        stdout.to_lowercase().contains("spruce"),
        "ROBA_VAR_TARGET=spruce should reach the model, got: {stdout}"
    );
}

#[test]
#[ignore]
fn live_env_fresh_cancels_continue() {
    // With ROBA_CONTINUE=1 active, default would continue the last
    // session in this cwd. --fresh cancels it and starts a new one;
    // the resulting session id differs from the seeded one.
    let dir = fresh_dir();
    let user = empty_user_home();

    let seed = roba_in(dir.path())
        .env("XDG_CONFIG_HOME", user.path())
        .args(["--json", "respond with the single word: anchor"])
        .output()
        .expect("seed run");
    let seed_json: serde_json::Value = serde_json::from_slice(&seed.stdout).expect("seed json");
    // v1 envelope (#83): session_id is nested under `result`.
    let seed_id = seed_json["result"]["session_id"]
        .as_str()
        .expect("session_id")
        .to_string();

    let fresh = roba_in(dir.path())
        .env("XDG_CONFIG_HOME", user.path())
        .env("ROBA_CONTINUE", "1")
        .args(["--fresh", "--json", "respond with the single word: cedar"])
        .output()
        .expect("fresh run");
    let fresh_json: serde_json::Value = serde_json::from_slice(&fresh.stdout).expect("fresh json");
    let fresh_id = fresh_json["result"]["session_id"]
        .as_str()
        .expect("session_id");

    assert_ne!(
        seed_id, fresh_id,
        "--fresh should produce a new session id even with ROBA_CONTINUE=1"
    );
}

// ---------------------------------------------------------------------------
// effort: cost/quality tradeoff flag
// ---------------------------------------------------------------------------

#[test]
#[ignore]
fn live_effort_low_succeeds() {
    let dir = fresh_dir();
    roba_in(dir.path())
        .args(["--effort", "low", "respond with the single word: done"])
        .assert()
        .success()
        .stdout(predicate::str::contains("done"));
}

#[test]
#[ignore]
fn live_effort_max_succeeds() {
    let dir = fresh_dir();
    roba_in(dir.path())
        .args(["--effort", "max", "respond with the single word: done"])
        .assert()
        .success()
        .stdout(predicate::str::contains("done"));
}

// ---------------------------------------------------------------------------
// system_prompt: replace / append the default system prompt
// ---------------------------------------------------------------------------

#[test]
#[ignore]
fn live_system_prompt_succeeds() {
    let dir = fresh_dir();
    let user = empty_user_home();
    // SMOKE ONLY. We assert that a replacement `--system-prompt` reaches
    // claude and the call succeeds with non-empty output -- NOT that the
    // model obeys it. In `--print` mode haiku ignores a *replacement* system
    // prompt roughly half the time (it falls back to its default coding-agent
    // identity and just greets), so any marker-compliance assertion is ~50%
    // flaky regardless of wording. Earlier attempts to "fix" it by tweaking
    // the prompt only chased that coin-flip.
    //
    // The reliable end-to-end "system prompt influences output" signal is the
    // *additive* path, covered by `live_append_system_prompt_stacks` (haiku
    // reliably honors "always end with <token>"). Flag parsing is covered by
    // the mechanical tests in `tests/cli.rs`.
    roba_in(dir.path())
        .env("XDG_CONFIG_HOME", user.path())
        .args([
            "--system-prompt",
            "You are a helpful assistant.",
            "what is 1+1",
        ])
        .assert()
        .success()
        .stdout(predicate::str::is_empty().not());
}

#[test]
#[ignore]
fn live_append_system_prompt_stacks() {
    let dir = fresh_dir();
    roba_in(dir.path())
        .args([
            "--append-system-prompt",
            "Always end your response with the token: [APPENDED]",
            "what is 1+1",
        ])
        .assert()
        .success()
        .stdout(predicate::str::contains("[APPENDED]"));
}

// ---------------------------------------------------------------------------
// permission_mode: pass a specific mode to claude
// ---------------------------------------------------------------------------

#[test]
#[ignore]
fn live_perms_mode_dont_ask_succeeds() {
    let dir = fresh_dir();
    roba_in(dir.path())
        .args([
            "--writable",
            "--permission-mode",
            "dontAsk",
            "respond with the single word: ok",
        ])
        .assert()
        .success();
}

#[test]
#[ignore]
fn live_perms_mode_via_profile() {
    let dir =
        fixture_with_config("[profile.testmode]\npermission_mode = \"dontAsk\"\nwritable = true\n");
    let user = empty_user_home();
    roba_in(dir.path())
        .env("XDG_CONFIG_HOME", user.path())
        .args(["--profile", "testmode", "respond with: ok"])
        .assert()
        .success();
}

#[test]
#[ignore]
fn live_perms_mode_via_env() {
    let dir = fresh_dir();
    roba_in(dir.path())
        .env("ROBA_PERMISSION_MODE", "dontAsk")
        .args(["--writable", "respond with the single word: ok"])
        .assert()
        .success();
}

// ---------------------------------------------------------------------------
// bare: minimal-overhead mode
// ---------------------------------------------------------------------------

#[test]
#[ignore]
fn live_bare_succeeds() {
    // --bare skips keychain reads by design (see src/cli.rs: "Auth uses
    // ANTHROPIC_API_KEY only"). Under OAuth/keychain-only auth with no
    // ANTHROPIC_API_KEY in the environment, --bare cannot authenticate
    // ("Not logged in"), so the test can only run when an API key is
    // present. Skip cleanly otherwise rather than report a false failure.
    if std::env::var_os("ANTHROPIC_API_KEY").is_none() {
        eprintln!(
            "skipping live_bare_succeeds: --bare authenticates via ANTHROPIC_API_KEY only, \
             which is not set in this environment"
        );
        return;
    }
    let dir = fresh_dir();
    let user = empty_user_home();
    roba_in(dir.path())
        .env("XDG_CONFIG_HOME", user.path())
        .args(["--bare", "respond with the single word: bare"])
        .assert()
        .success()
        .stdout(predicate::str::contains("bare"));
}

// ---------------------------------------------------------------------------
// exit: typed exit codes for failure classes (claude-wrapper 0.11.1, #281)
// ---------------------------------------------------------------------------

#[test]
#[ignore]
fn live_exit_model_not_found_is_failure_not_auth() {
    // A bogus model 404s. claude-wrapper 0.11.1 (#633) no longer misclassifies
    // that as auth, so roba returns the generic failure code 1 -- NOT the
    // auth/usage code 2 (which an orchestrator reads as "halt the fleet").
    // Deterministic: an unknown model always 404s. Built without `roba_in`
    // because `--model` rejects multiple occurrences (its haiku default would
    // collide and produce a usage error, not the 404).
    let dir = fresh_dir();
    Command::cargo_bin("roba")
        .expect("cargo-built roba")
        .args([
            "-C",
            dir.path().to_str().expect("utf-8 path"),
            "--model",
            "totally-not-a-model-xyz",
            "hi",
        ])
        .assert()
        .code(1);
}

#[test]
#[ignore]
fn live_exit_max_turns_returns_5() {
    // A task that needs >=2 sequential turns (read a file, THEN report it)
    // cannot finish in one turn, so --max-turns 1 trips the cap. claude-wrapper
    // 0.12.0 surfaces that as MaxTurnsExceeded (detected via the --json result
    // event), which roba maps to the recoverable exit code 5 -- distinct from a
    // generic failure so an orchestrator can finish the lifecycle. (#309)
    let dir = fresh_dir();
    std::fs::write(dir.path().join("marker.txt"), "sentinel-42").expect("seed marker");
    roba_in(dir.path())
        .args([
            "--json",
            "--max-turns",
            "1",
            "Read the file marker.txt and report its exact contents.",
        ])
        .assert()
        .code(5);
}

#[test]
#[ignore]
fn live_exit_bare_missing_key_is_auth() {
    // --bare authenticates via ANTHROPIC_API_KEY only. With the key removed,
    // claude-wrapper 0.11.1 (#633) surfaces the missing key as an auth failure,
    // so roba returns the auth/usage code 2 -- not the generic 1 it used to.
    let dir = fresh_dir();
    let user = empty_user_home();
    roba_in(dir.path())
        .env("XDG_CONFIG_HOME", user.path())
        .env_remove("ANTHROPIC_API_KEY")
        .args(["--bare", "hi"])
        .assert()
        .code(2);
}

// ---------------------------------------------------------------------------
// limits: unattended guardrails (--max-turns / --max-budget-usd)
// ---------------------------------------------------------------------------

#[test]
#[ignore]
fn live_limits_flags_accepted() {
    // Both guardrails plumb through and a normal short run completes.
    // We assert ONLY that the flags are accepted and the run succeeds --
    // not that a cap FIRES (turn-count / spend dependent = model-flaky).
    // The caps here (5 turns, $10) are generous enough that a trivial
    // one-shot answer never trips them.
    let dir = fresh_dir();
    roba_in(dir.path())
        .args([
            "--max-turns",
            "5",
            "--max-budget-usd",
            "10.0",
            "respond with the single word: bounded",
        ])
        .assert()
        .success()
        .stdout(predicate::str::contains("bounded"));
}

// ---------------------------------------------------------------------------
// mcp: per-run MCP server config pass-through (--mcp-config)
// ---------------------------------------------------------------------------

#[test]
#[ignore]
fn live_mcp_config_accepted() {
    // --mcp-config plumbs through and a normal short run completes. Assert
    // MECHANICS only: the flag is accepted, no server starts, the run
    // succeeds. We use a MINIMAL config with NO servers ({"mcpServers":{}})
    // so nothing real is launched -- asserting actual MCP tools would need a
    // live server and would be flaky. roba forwards the path; claude reads it.
    let dir = fresh_dir();
    let cfg_path = dir.path().join("mcp.json");
    std::fs::write(&cfg_path, r#"{"mcpServers":{}}"#).expect("write mcp config");

    roba_in(dir.path())
        .arg("--mcp-config")
        .arg(&cfg_path)
        .arg("respond with the single word: mcp")
        .assert()
        .success()
        .stdout(predicate::str::contains("mcp"));
}

// ---------------------------------------------------------------------------
// med-tier pass-throughs (--add-dir / --fallback-model / --no-session-persistence)
// ---------------------------------------------------------------------------

#[test]
#[ignore]
fn live_medtier_flags_accepted() {
    // The three med-tier pass-throughs plumb through and a normal short run
    // completes. Assert MECHANICS only: all three flags are accepted and the
    // run succeeds. We do NOT assert that the fallback actually fires (needs
    // an overloaded primary) or that no JSONL was written (environment- and
    // timing-dependent) -- those are claude's behaviors, not roba's plumbing.
    // --add-dir points at a real temp dir; --fallback-model reuses the haiku
    // id the helpers default to; --no-session-persistence is a bare flag.
    let dir = fresh_dir();
    let extra = fresh_dir();

    roba_in(dir.path())
        .arg("--add-dir")
        .arg(extra.path())
        .args([
            "--fallback-model",
            "haiku",
            "--no-session-persistence",
            "respond with the single word: medtier",
        ])
        .assert()
        .success()
        .stdout(predicate::str::contains("medtier"));
}

// ---------------------------------------------------------------------------
// alias draft (claude-assisted, parse-validated alias generation)
// ---------------------------------------------------------------------------

#[test]
#[ignore]
fn live_alias_draft() {
    // Assert MECHANICS: a draft exits 0 and its stdout parses through the
    // REAL `Alias` deserializer as exactly one `[alias.NAME]` block. We do
    // NOT assert anything about the generated NAME or wording -- that's
    // model behavior, not roba's plumbing. The draft call carries its own
    // `--model` (not roba_in's top-level one, which draft ignores).
    let dir = fresh_dir();
    let out = Command::cargo_bin("roba")
        .expect("cargo-built roba binary")
        .args([
            "-C",
            dir.path().to_str().expect("utf-8 tempdir path"),
            "alias",
            "draft",
            "a verb that asks for a one-line summary of a file given as the first argument",
            "--model",
            "claude-haiku-4-5",
        ])
        .output()
        .expect("run roba alias draft");
    assert!(
        out.status.success(),
        "draft should exit 0; stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let stdout = String::from_utf8_lossy(&out.stdout);

    #[derive(serde::Deserialize)]
    struct Wrapper {
        alias: std::collections::HashMap<String, roba::aliases::Alias>,
    }
    let parsed: Wrapper = toml::from_str(&stdout)
        .unwrap_or_else(|e| panic!("draft stdout did not parse as an alias: {e}\n{stdout}"));
    assert_eq!(
        parsed.alias.len(),
        1,
        "expected exactly one alias block on stdout, got:\n{stdout}"
    );
}

#[test]
#[ignore]
fn live_profile_draft() {
    // Profile twin of `live_alias_draft`. Assert MECHANICS: a draft exits 0
    // and its stdout parses through the REAL `Profile` deserializer
    // (`deny_unknown_fields`) as exactly one `[profile.NAME]` block. We do
    // NOT assert anything about the generated NAME or keys -- that's model
    // behavior, not roba's plumbing. The draft call carries its own
    // `--model` (not roba_in's top-level one, which draft ignores).
    let dir = fresh_dir();
    let out = Command::cargo_bin("roba")
        .expect("cargo-built roba binary")
        .args([
            "-C",
            dir.path().to_str().expect("utf-8 tempdir path"),
            "profile",
            "draft",
            "a cheap fast one-shot profile",
            "--model",
            "claude-haiku-4-5",
        ])
        .output()
        .expect("run roba profile draft");
    assert!(
        out.status.success(),
        "draft should exit 0; stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let stdout = String::from_utf8_lossy(&out.stdout);

    #[derive(serde::Deserialize)]
    struct Wrapper {
        profile: std::collections::HashMap<String, roba::profile::Profile>,
    }
    let parsed: Wrapper = toml::from_str(&stdout)
        .unwrap_or_else(|e| panic!("draft stdout did not parse as a profile: {e}\n{stdout}"));
    assert_eq!(
        parsed.profile.len(),
        1,
        "expected exactly one profile block on stdout, got:\n{stdout}"
    );
}

#[test]
#[ignore]
fn live_config_init() {
    // The per-project bootstrap. Assert MECHANICS: in a tiny fixture
    // project, `roba config init` exits 0 and its stdout parses through
    // the REAL per-file config deserializer (the exact path the pool
    // loader uses). We do NOT assert anything about which profiles/keys
    // were chosen -- that's model behavior, not roba's plumbing. The call
    // carries its own `--model` (config init ignores roba_in's top-level).
    let dir = fresh_dir();
    // A minimal but realistic project: a git marker so the config walk
    // stops here, a README, and a source file for the call to skim.
    std::fs::create_dir_all(dir.path().join(".git")).expect(".git marker");
    std::fs::write(
        dir.path().join("README.md"),
        "# widget\n\nA small Rust CLI for widgets.\n",
    )
    .expect("write README");
    std::fs::create_dir_all(dir.path().join("src")).expect("src dir");
    std::fs::write(
        dir.path().join("src/main.rs"),
        "fn main() { println!(\"widget\"); }\n",
    )
    .expect("write src");

    let out = Command::cargo_bin("roba")
        .expect("cargo-built roba binary")
        .args([
            "-C",
            dir.path().to_str().expect("utf-8 tempdir path"),
            "config",
            "init",
            "keep it minimal",
            "--model",
            "claude-haiku-4-5",
        ])
        .output()
        .expect("run roba config init");
    assert!(
        out.status.success(),
        "config init should exit 0; stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let stdout = String::from_utf8_lossy(&out.stdout);

    // Validate through the SAME deserializer the pool loader uses.
    roba::profile::pool::parse_config_str(&stdout).unwrap_or_else(|e| {
        panic!("config init stdout did not parse as a config: {e:#}\n{stdout}")
    });
}

// ---------------------------------------------------------------------------
// detach: fire-and-survive round-trip
// ---------------------------------------------------------------------------

#[test]
#[ignore]
fn live_detach_roundtrip() {
    // The #258 survivable-hand-off recipe, automated: `--detach` fires a
    // disowned run and prints the session handle; `show <id> --wait` then
    // re-attaches from a fresh process and renders the answer.
    //
    // `--detach` refuses a non-TTY stdin (piped input would be lost on the
    // detached child), and assert_cmd always pipes stdin -- so this test
    // drives the binary via std::process with stdin INHERITED. Run it from a
    // real terminal: `cargo test --test live -- --ignored live_detach_`.
    use std::process::{Command as StdCommand, Stdio};

    let dir = fresh_dir();
    let bin = assert_cmd::cargo::cargo_bin("roba");

    let out = StdCommand::new(&bin)
        .args([
            "-C",
            dir.path().to_str().expect("utf-8 tempdir path"),
            "--model",
            "haiku",
            "--detach",
            "respond with the single word: pong",
        ])
        .stdin(Stdio::inherit()) // a real TTY when run from a terminal
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .output()
        .expect("spawn roba --detach");

    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        out.status.success(),
        "--detach should exit 0 after spawning (stdin must be a TTY); stderr:\n{stderr}"
    );
    let handle = String::from_utf8_lossy(&out.stdout).trim().to_string();
    // Handle is the ONLY thing on stdout, and is a v4-UUID-shaped line.
    assert_eq!(handle.len(), 36, "handle should be a UUID, got: {handle:?}");
    assert_eq!(
        handle.matches('-').count(),
        4,
        "handle should be a UUID, got: {handle:?}"
    );

    // Re-attach from a fresh process and wait for the detached run to finish.
    let show = Command::cargo_bin("roba")
        .expect("cargo-built roba binary")
        .args(["show", &handle, "--wait", "--timeout", "90"])
        .assert()
        .success();
    let rendered = String::from_utf8_lossy(&show.get_output().stdout);
    assert!(
        !rendered.trim().is_empty(),
        "show --wait should render a non-empty result for the detached run"
    );
}

// ---------------------------------------------------------------------------
// INTENTIONALLY UNTESTED (high cost / low signal, or no fixture path yet)
// ---------------------------------------------------------------------------
//
// These recently-shipped surfaces have no live coverage on purpose.
// Documented here so the gap is visible rather than silently missing.
//
// - --no-retry transient-failure injection: provoking a transient
//   wrapper failure needs a network shim / fault injector we don't have.
//   Today the flag is forward-looking (roba builds Claude with no retry
//   policy, so it's already one-shot); the clap-level parse is covered
//   in src/cli.rs unit tests.
// - --agent NAME role verification: depends on a local subagent registry
//   (.claude/agents/<name>.md) in the run cwd. Without a staged fixture
//   the spawned claude's actual agent behavior isn't assertable; the flag
//   is a pass-through. Parse-level coverage lives in src/cli.rs.
// - --json error envelope on auth failure: would require breaking auth
//   for the duration of the test. Envelope shape is unit-tested in
//   src/error.rs.
// - --json error envelope on budget exceeded: would spend real budget to
//   trip the limit. Same unit coverage as above.
// - Deterministic, no-claude subcommands (skill/agent list|show|install,
//   --show-permissions): covered by the mechanical CLI tests in
//   tests/cli.rs (#90). Live tests here focus on claude-calling paths, so
//   these are deliberately not duplicated.