trusty-code 0.8.0

Per-project Claude-Code-compatible MPM orchestration harness (bin: tcode) — an original coding harness, tracked under epic #2052.
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
//! Tests for `task.run` (#2056, #3178's per-call project convergence). Split
//! out of `protocol.rs` per the crate's `_tests.rs` sibling-file convention
//! (see `executor_tests.rs` for precedent) to keep the production file under
//! the 500-SLOC cap.

use super::*;
use crate::jsonrpc::Request;
use tokio::sync::mpsc;

fn test_ctx() -> ConnectionContext {
    let (tx, _rx) = mpsc::unbounded_channel();
    ConnectionContext::new(tx)
}

fn agents_dir() -> tempfile::TempDir {
    let tmp = tempfile::tempdir().expect("agents tempdir");
    std::fs::write(
        tmp.path().join("pm.md"),
        "---\nname: pm\nmodel: openai/gpt-4o-mini\n---\n\nYou are the PM.\n",
    )
    .expect("write pm.md");
    std::fs::write(
        tmp.path().join("python-engineer.md"),
        "---\nname: python-engineer\nmodel: deepseek/deepseek-chat\n---\n\nengineer\n",
    )
    .expect("write python-engineer.md");
    tmp
}

/// `register` must wire `task.run` so the router recognises it.
#[tokio::test]
async fn register_wires_task_run() {
    let _guard = super::super::mock_llm::MOCK_LLM_ENV_LOCK.lock().await;
    // SAFETY: test-only env mutation; serialized by `ENV_LOCK` above.
    unsafe {
        std::env::set_var(
            super::super::mock_llm::MOCK_LLM_ENV,
            super::super::mock_llm::MOCK_LLM_ECHO,
        );
    }
    let registry = Arc::new(SessionRegistry::new());
    let agents = agents_dir();
    let project = tempfile::tempdir().expect("project tempdir");
    let mut router = Router::new();
    register(
        &mut router,
        registry,
        ProjectBinding::resolve(Some(project.path().to_path_buf())).expect("tempdir must bind"),
        agents.path().to_path_buf(),
        crate::workstreams::test_shared_store().await,
    );

    let req = Request {
        jsonrpc: Some("2.0".to_string()),
        id: Some(json!(1)),
        method: "task.run".to_string(),
        params: Some(json!({"task_description": "say hi"})),
    };
    let resp = router.dispatch(req, &test_ctx()).await;
    unsafe {
        std::env::remove_var(super::super::mock_llm::MOCK_LLM_ENV);
    }
    assert!(
        resp.error.is_none(),
        "task.run should succeed, got {:?}",
        resp.error
    );
    assert_eq!(resp.result.unwrap()["status"], "running");
}

/// `task.run` must be callable with NO project bound at all (AC-16.1) —
/// the change that makes the shell's entry screen (7a) implementable. This
/// call was impossible before: `register` took a required `PathBuf`.
#[tokio::test]
async fn register_wires_task_run_projectless() {
    let _guard = super::super::mock_llm::MOCK_LLM_ENV_LOCK.lock().await;
    // SAFETY: test-only env mutation; serialized by the lock above.
    unsafe {
        std::env::set_var(
            super::super::mock_llm::MOCK_LLM_ENV,
            super::super::mock_llm::MOCK_LLM_ECHO,
        );
    }
    let registry = Arc::new(SessionRegistry::new());
    let agents = agents_dir();
    let mut router = Router::new();
    register(
        &mut router,
        registry,
        ProjectBinding::None,
        agents.path().to_path_buf(),
        crate::workstreams::test_shared_store().await,
    );

    let req = Request {
        jsonrpc: Some("2.0".to_string()),
        id: Some(json!(1)),
        method: "task.run".to_string(),
        params: Some(json!({"task_description": "just chat"})),
    };
    let resp = router.dispatch(req, &test_ctx()).await;
    unsafe {
        std::env::remove_var(super::super::mock_llm::MOCK_LLM_ENV);
    }
    assert!(
        resp.error.is_none(),
        "projectless task.run must succeed, got {:?}",
        resp.error
    );
    let result = resp.result.expect("a result");
    assert_eq!(result["status"], "running");
    assert_eq!(
        result["binding"]["state"], "projectless",
        "task.run must report the projectless binding back to the caller: {result}"
    );
}

/// An empty `task_description` must map to `-32003 invalid_argument`.
#[tokio::test]
async fn task_run_rejects_empty_task_description() {
    let registry = Arc::new(SessionRegistry::new());
    let agents = agents_dir();
    let project = tempfile::tempdir().expect("project tempdir");
    let err = task_run(
        registry,
        json!({"task_description": "   "}),
        ProjectBinding::resolve(Some(project.path().to_path_buf())).expect("tempdir must bind"),
        agents.path().to_path_buf(),
        crate::workstreams::test_shared_store().await,
    )
    .await
    .unwrap_err();
    assert_eq!(err.code, -32003);
}

/// Omitting `session_id` must mint a fresh session.
#[tokio::test]
async fn task_run_creates_session_when_none_given() {
    let _guard = super::super::mock_llm::MOCK_LLM_ENV_LOCK.lock().await;
    unsafe {
        std::env::set_var(
            super::super::mock_llm::MOCK_LLM_ENV,
            super::super::mock_llm::MOCK_LLM_ECHO,
        );
    }
    let registry = Arc::new(SessionRegistry::new());
    let agents = agents_dir();
    let project = tempfile::tempdir().expect("project tempdir");

    let result = task_run(
        Arc::clone(&registry),
        json!({"task_description": "say hi"}),
        ProjectBinding::resolve(Some(project.path().to_path_buf())).expect("tempdir must bind"),
        agents.path().to_path_buf(),
        crate::workstreams::test_shared_store().await,
    )
    .await;
    unsafe {
        std::env::remove_var(super::super::mock_llm::MOCK_LLM_ENV);
    }
    let value = result.expect("task.run should succeed");
    let session_id = value["session_id"].as_str().expect("session_id string");
    assert!(
        registry.status(session_id).is_ok(),
        "a new session must have been created"
    );
}

/// (#4351) `task.run`'s response carries a `result` object, and every key it
/// carried before #4351 is still there and unchanged.
///
/// Why: the whole point of the change is that a caller gets something
/// actionable back — and that adding it broke nothing. `task.run` is
/// asynchronous, so the only truthful status at return time is `pending` with
/// no refs; a `success` here would be a lie about a run that has not happened.
/// Test: this test.
#[tokio::test]
async fn task_run_response_carries_a_pending_result() {
    let _guard = super::super::mock_llm::MOCK_LLM_ENV_LOCK.lock().await;
    unsafe {
        std::env::set_var(
            super::super::mock_llm::MOCK_LLM_ENV,
            super::super::mock_llm::MOCK_LLM_ECHO,
        );
    }
    let registry = Arc::new(SessionRegistry::new());
    let agents = agents_dir();
    let project = tempfile::tempdir().expect("project tempdir");

    let result = task_run(
        Arc::clone(&registry),
        json!({"task_description": "say hi"}),
        ProjectBinding::resolve(Some(project.path().to_path_buf())).expect("tempdir must bind"),
        agents.path().to_path_buf(),
        crate::workstreams::test_shared_store().await,
    )
    .await;
    unsafe {
        std::env::remove_var(super::super::mock_llm::MOCK_LLM_ENV);
    }
    let value = result.expect("task.run should succeed");

    // Backward compatibility: the pre-#4351 keys are untouched.
    assert!(value["session_id"].is_string());
    assert_eq!(value["status"], "running");
    assert!(value["mode"].is_string());
    assert!(value["binding"].is_object());

    assert_eq!(value["result"]["status"], "pending");
    assert!(value["result"]["diff_ref"].is_null());
    assert!(value["result"]["branch"].is_null());
    assert!(value["result"]["pr_ref"].is_null());
    assert!(value["result"]["summary"].is_null());
}

/// `task.run` must resolve `HarnessMode` per §5.9's three-tier
/// precedence and report it BOTH in its own immediate response AND on
/// the session (queryable via `session.status`/`get_transcript`
/// afterward) — #2059.
///
/// Why: this is the integration point proving the wiring
/// `crate::mode::resolve_mode`'s own unit tests cannot: that
/// `task::protocol::task_run` actually reads the `mode` request param,
/// the project's `.claude/settings.json`, and `TRUSTY_CODE_MODE`, in
/// that precedence, and persists the result via
/// `SessionRegistry::set_mode` before spawning the run.
/// What: covers default (nothing set), settings.json alone,
/// task-param-over-settings.json, and env-var-over-everything.
/// Test: this test.
#[tokio::test]
async fn task_run_resolves_and_reports_mode() {
    let _mock_guard = super::super::mock_llm::MOCK_LLM_ENV_LOCK.lock().await;
    let _mode_guard = crate::mode::MODE_ENV_LOCK.lock().await;
    // SAFETY: test-only env mutation; serialized by both locks above.
    unsafe {
        std::env::set_var(
            super::super::mock_llm::MOCK_LLM_ENV,
            super::super::mock_llm::MOCK_LLM_ECHO,
        );
        std::env::remove_var(crate::mode::MODE_ENV_VAR);
    }
    let agents = agents_dir();

    // 1. Nothing set anywhere -> default (daily-driver).
    let project = tempfile::tempdir().expect("project tempdir");
    let registry = Arc::new(SessionRegistry::new());
    let value = task_run(
        Arc::clone(&registry),
        json!({"task_description": "say hi"}),
        ProjectBinding::resolve(Some(project.path().to_path_buf())).expect("tempdir must bind"),
        agents.path().to_path_buf(),
        crate::workstreams::test_shared_store().await,
    )
    .await
    .expect("task.run should succeed");
    assert_eq!(value["mode"], "daily-driver");
    let session_id = value["session_id"].as_str().unwrap().to_string();
    assert_eq!(
        registry.status(&session_id).unwrap().mode,
        Some(crate::mode::HarnessMode::DailyDriver)
    );

    // 2. `.claude/settings.json` alone sets parity.
    let project2 = tempfile::tempdir().expect("project tempdir");
    std::fs::create_dir_all(project2.path().join(".claude")).expect("mkdir");
    std::fs::write(
        project2.path().join(".claude").join("settings.json"),
        r#"{"code_harness": {"mode": "parity"}}"#,
    )
    .expect("write settings.json");
    let registry2 = Arc::new(SessionRegistry::new());
    let value2 = task_run(
        Arc::clone(&registry2),
        json!({"task_description": "say hi"}),
        ProjectBinding::resolve(Some(project2.path().to_path_buf())).expect("tempdir must bind"),
        agents.path().to_path_buf(),
        crate::workstreams::test_shared_store().await,
    )
    .await
    .expect("task.run should succeed");
    assert_eq!(value2["mode"], "parity");

    // 3. A `mode` request param overrides settings.json (still parity
    //    from settings.json here, but requesting daily-driver must win).
    let registry3 = Arc::new(SessionRegistry::new());
    let value3 = task_run(
        Arc::clone(&registry3),
        json!({"task_description": "say hi", "mode": "daily-driver"}),
        ProjectBinding::resolve(Some(project2.path().to_path_buf())).expect("tempdir must bind"),
        agents.path().to_path_buf(),
        crate::workstreams::test_shared_store().await,
    )
    .await
    .expect("task.run should succeed");
    assert_eq!(
        value3["mode"], "daily-driver",
        "task.run's mode param must override settings.json"
    );

    // 4. TRUSTY_CODE_MODE overrides EVERYTHING, including a task param.
    unsafe {
        std::env::set_var(crate::mode::MODE_ENV_VAR, "parity");
    }
    let registry4 = Arc::new(SessionRegistry::new());
    let value4 = task_run(
        Arc::clone(&registry4),
        json!({"task_description": "say hi", "mode": "daily-driver"}),
        ProjectBinding::resolve(Some(project2.path().to_path_buf())).expect("tempdir must bind"),
        agents.path().to_path_buf(),
        crate::workstreams::test_shared_store().await,
    )
    .await
    .expect("task.run should succeed");
    assert_eq!(
        value4["mode"], "parity",
        "TRUSTY_CODE_MODE must win over a task.run mode param"
    );

    unsafe {
        std::env::remove_var(super::super::mock_llm::MOCK_LLM_ENV);
        std::env::remove_var(crate::mode::MODE_ENV_VAR);
    }
}

/// A `session_id` that does not exist must propagate `session_not_found`.
#[tokio::test]
async fn task_run_unknown_session_id_errors() {
    let registry = Arc::new(SessionRegistry::new());
    let agents = agents_dir();
    let project = tempfile::tempdir().expect("project tempdir");

    let err = task_run(
        registry,
        json!({"task_description": "say hi", "session_id": "does-not-exist"}),
        ProjectBinding::resolve(Some(project.path().to_path_buf())).expect("tempdir must bind"),
        agents.path().to_path_buf(),
        crate::workstreams::test_shared_store().await,
    )
    .await
    .unwrap_err();
    assert_eq!(err.code, -32007);
}

/// Omitting `project` must keep today's process-boot-time binding
/// unchanged (#3178 back-compat) — the daemon's `binding` param, not
/// `ProjectBinding::None`.
#[tokio::test]
async fn task_run_without_project_keeps_boot_binding() {
    let _guard = super::super::mock_llm::MOCK_LLM_ENV_LOCK.lock().await;
    unsafe {
        std::env::set_var(
            super::super::mock_llm::MOCK_LLM_ENV,
            super::super::mock_llm::MOCK_LLM_ECHO,
        );
    }
    let registry = Arc::new(SessionRegistry::new());
    let agents = agents_dir();
    let boot_project = tempfile::tempdir().expect("project tempdir");
    let boot_binding = ProjectBinding::resolve(Some(boot_project.path().to_path_buf()))
        .expect("tempdir must bind");

    let value = task_run(
        registry,
        json!({"task_description": "say hi"}),
        boot_binding.clone(),
        agents.path().to_path_buf(),
        crate::workstreams::test_shared_store().await,
    )
    .await
    .expect("task.run should succeed");
    unsafe {
        std::env::remove_var(super::super::mock_llm::MOCK_LLM_ENV);
    }
    assert_eq!(value["binding"], boot_binding.to_json());
}

/// A per-call `project` must override the boot-time binding for this
/// call, resolved through the same `ProjectBinding::resolve` helper
/// `session.create` uses (#3178, DOC-39 §5.5/AC-16.2).
#[tokio::test]
async fn task_run_with_project_overrides_boot_binding() {
    let _guard = super::super::mock_llm::MOCK_LLM_ENV_LOCK.lock().await;
    unsafe {
        std::env::set_var(
            super::super::mock_llm::MOCK_LLM_ENV,
            super::super::mock_llm::MOCK_LLM_ECHO,
        );
    }
    let registry = Arc::new(SessionRegistry::new());
    let agents = agents_dir();
    let call_project = tempfile::tempdir().expect("project tempdir");

    let value = task_run(
        registry,
        json!({
            "task_description": "say hi",
            "project": call_project.path().to_string_lossy(),
        }),
        ProjectBinding::None,
        agents.path().to_path_buf(),
        crate::workstreams::test_shared_store().await,
    )
    .await
    .expect("task.run should succeed");
    unsafe {
        std::env::remove_var(super::super::mock_llm::MOCK_LLM_ENV);
    }
    assert_eq!(
        value["binding"]["state"], "directory",
        "the per-call project must bind, not stay projectless: {value}"
    );
}

/// A `project` naming a nonexistent path must map to `-32003
/// invalid_argument`, matching `session.create`'s error mapping for the
/// same failure mode.
#[tokio::test]
async fn task_run_rejects_invalid_project() {
    let registry = Arc::new(SessionRegistry::new());
    let agents = agents_dir();

    let err = task_run(
        registry,
        json!({"task_description": "say hi", "project": "/no/such/path/anywhere"}),
        ProjectBinding::None,
        agents.path().to_path_buf(),
        crate::workstreams::test_shared_store().await,
    )
    .await
    .unwrap_err();
    assert_eq!(err.code, -32003);
}

/// A `session_id` for an existing session must reuse it, not mint a new
/// one.
#[tokio::test]
async fn task_run_sessionful_reuses_existing_session() {
    let _guard = super::super::mock_llm::MOCK_LLM_ENV_LOCK.lock().await;
    unsafe {
        std::env::set_var(
            super::super::mock_llm::MOCK_LLM_ENV,
            super::super::mock_llm::MOCK_LLM_ECHO,
        );
    }
    let registry = Arc::new(SessionRegistry::new());
    let existing = registry.create(
        "say hi".to_string(),
        None,
        crate::binding::ProjectBinding::None,
    );
    let agents = agents_dir();
    let project = tempfile::tempdir().expect("project tempdir");

    let result = task_run(
        Arc::clone(&registry),
        json!({"task_description": "say hi", "session_id": existing.id}),
        ProjectBinding::resolve(Some(project.path().to_path_buf())).expect("tempdir must bind"),
        agents.path().to_path_buf(),
        crate::workstreams::test_shared_store().await,
    )
    .await;
    unsafe {
        std::env::remove_var(super::super::mock_llm::MOCK_LLM_ENV);
    }
    let value = result.expect("task.run should succeed");
    assert_eq!(value["session_id"], existing.id);
}

/// `session_id` + a `project` that RESTATES the reused session's own
/// binding root must succeed (#3178, code-critic PR #3189 fix) — the
/// invariant only forbids a DIFFERENT root, never the same one.
#[tokio::test]
async fn task_run_session_id_with_matching_project_succeeds() {
    let _guard = super::super::mock_llm::MOCK_LLM_ENV_LOCK.lock().await;
    unsafe {
        std::env::set_var(
            super::super::mock_llm::MOCK_LLM_ENV,
            super::super::mock_llm::MOCK_LLM_ECHO,
        );
    }
    let registry = Arc::new(SessionRegistry::new());
    let agents = agents_dir();
    let project = tempfile::tempdir().expect("project tempdir");
    let session_binding =
        ProjectBinding::resolve(Some(project.path().to_path_buf())).expect("tempdir must bind");
    let existing = registry.create("say hi".to_string(), None, session_binding);

    let result = task_run(
        Arc::clone(&registry),
        json!({
            "task_description": "say hi",
            "session_id": existing.id,
            "project": project.path().to_string_lossy(),
        }),
        ProjectBinding::None,
        agents.path().to_path_buf(),
        crate::workstreams::test_shared_store().await,
    )
    .await;
    unsafe {
        std::env::remove_var(super::super::mock_llm::MOCK_LLM_ENV);
    }
    let value = result.expect("a project restating the session's own binding must succeed");
    assert_eq!(value["session_id"], existing.id);
    assert_eq!(value["binding"]["state"], "directory");
}

/// `session_id` + a `project` naming a DIFFERENT root than the reused
/// session's own persisted binding must be rejected with `-32003
/// invalid_argument` (#3178, code-critic HIGH finding, PR #3189) — never
/// silently executed against a project `session.status`/`session.list`
/// would never agree the session is bound to.
#[tokio::test]
async fn task_run_session_id_with_mismatched_project_is_rejected() {
    let registry = Arc::new(SessionRegistry::new());
    let agents = agents_dir();
    let session_project = tempfile::tempdir().expect("session project tempdir");
    let other_project = tempfile::tempdir().expect("other project tempdir");
    let session_binding = ProjectBinding::resolve(Some(session_project.path().to_path_buf()))
        .expect("tempdir must bind");
    let existing = registry.create("say hi".to_string(), None, session_binding);

    let err = task_run(
        registry,
        json!({
            "task_description": "say hi",
            "session_id": existing.id,
            "project": other_project.path().to_string_lossy(),
        }),
        ProjectBinding::None,
        agents.path().to_path_buf(),
        crate::workstreams::test_shared_store().await,
    )
    .await
    .unwrap_err();
    assert_eq!(err.code, -32003);
    assert!(
        err.message.contains("does not match session"),
        "error message must name the mismatch: {}",
        err.message
    );
}

/// A second `task.run` at the JSON-RPC entry point, issued AFTER the
/// first run against the same `session_id` has fully `Finished`, must be
/// ACCEPTED (#2344 resumption) rather than erroring — the acceptance
/// criterion "two sequential task.run calls on one session" exercised at
/// the actual RPC surface, not just `spawn_task_run` directly
/// (`task::executor::tests::spawn_task_run_second_call_after_finish_appends_to_cumulative_transcript`
/// covers the transcript-accumulation half; this test covers that
/// `task_run` itself — including its `registry.status(id)` existing-
/// session lookup — does not reject the resumed call).
#[tokio::test]
async fn task_run_second_call_after_finish_continues_the_session() {
    let _guard = super::super::mock_llm::MOCK_LLM_ENV_LOCK.lock().await;
    unsafe {
        std::env::set_var(
            super::super::mock_llm::MOCK_LLM_ENV,
            super::super::mock_llm::MOCK_LLM_ECHO,
        );
    }
    let registry = Arc::new(SessionRegistry::new());
    let agents = agents_dir();
    let project = tempfile::tempdir().expect("project tempdir");

    let first = task_run(
        Arc::clone(&registry),
        json!({"task_description": "say hi"}),
        ProjectBinding::resolve(Some(project.path().to_path_buf())).expect("tempdir must bind"),
        agents.path().to_path_buf(),
        crate::workstreams::test_shared_store().await,
    )
    .await
    .expect("first task.run should succeed");
    let session_id = first["session_id"].as_str().unwrap().to_string();

    let deadline = tokio::time::Instant::now() + tokio::time::Duration::from_secs(5);
    loop {
        let status = registry.status(&session_id).expect("session must exist");
        if status.status.is_terminal() {
            break;
        }
        assert!(
            tokio::time::Instant::now() < deadline,
            "first run did not reach a terminal state within 5s"
        );
        tokio::time::sleep(tokio::time::Duration::from_millis(20)).await;
    }

    let second = task_run(
        Arc::clone(&registry),
        json!({"task_description": "say hi again", "session_id": session_id}),
        ProjectBinding::resolve(Some(project.path().to_path_buf())).expect("tempdir must bind"),
        agents.path().to_path_buf(),
        crate::workstreams::test_shared_store().await,
    )
    .await;
    unsafe {
        std::env::remove_var(super::super::mock_llm::MOCK_LLM_ENV);
    }
    let value = second.expect("a second task.run on a Finished session must be accepted");
    assert_eq!(value["session_id"], session_id);
    assert_eq!(value["status"], "running");
}

// -- Workstream binding (DOC-48 §4.1/§4.2, issue #3298) --

/// Seed a workstream and activate it on `workstreams`, returning its id.
async fn seed_active_workstream(
    workstreams: &crate::workstreams::SharedWorkstreamStore,
) -> crate::workstreams::WorkstreamId {
    let id = workstreams
        .lock()
        .await
        .create("active")
        .await
        .expect("create");
    crate::workstreams::activation::activate(workstreams, id, false)
        .await
        .expect("activate");
    id
}

/// `task.run` minting a NEW session with no explicit `workstream_id`, while
/// a workstream is active, must bind to the ACTIVE workstream (§4.2) and
/// publish `Event::SessionAdded`.
#[tokio::test]
async fn task_run_binds_ambient_active_workstream_and_publishes_session_added() {
    let _guard = super::super::mock_llm::MOCK_LLM_ENV_LOCK.lock().await;
    unsafe {
        std::env::set_var(
            super::super::mock_llm::MOCK_LLM_ENV,
            super::super::mock_llm::MOCK_LLM_ECHO,
        );
    }
    let registry = Arc::new(SessionRegistry::new());
    let agents = agents_dir();
    let project = tempfile::tempdir().expect("project tempdir");
    let workstreams = crate::workstreams::test_shared_store().await;
    let active_id = seed_active_workstream(&workstreams).await;

    let mut rx = crate::events::subscribe();
    let value = task_run(
        Arc::clone(&registry),
        json!({"task_description": "say hi"}),
        ProjectBinding::resolve(Some(project.path().to_path_buf())).expect("tempdir must bind"),
        agents.path().to_path_buf(),
        workstreams.clone(),
    )
    .await;
    unsafe {
        std::env::remove_var(super::super::mock_llm::MOCK_LLM_ENV);
    }
    let value = value.expect("task.run should succeed");
    let session_id = value["session_id"].as_str().unwrap().to_string();

    let status = registry.status(&session_id).expect("status");
    assert_eq!(status.workstream_id, Some(active_id));

    let found = tokio::time::timeout(std::time::Duration::from_secs(2), async {
        loop {
            let envelope = rx.recv().await.expect("event bus channel closed");
            if let crate::events::Event::SessionAdded {
                session_id: sid,
                workstream_id,
                ..
            } = envelope.event
                && sid == session_id
            {
                return workstream_id;
            }
        }
    })
    .await
    .expect("timed out waiting for SessionAdded");
    assert_eq!(found, active_id.to_string());
}

/// `task.run` reusing an EXISTING session that is already bound to a
/// workstream, with a `workstream_id` param naming a DIFFERENT workstream,
/// must be rejected (§4.1 AC-1.3 immutability) — mirroring the sibling
/// `project` mismatch guard.
#[tokio::test]
async fn task_run_mismatched_workstream_on_reuse_is_rejected() {
    let _guard = super::super::mock_llm::MOCK_LLM_ENV_LOCK.lock().await;
    unsafe {
        std::env::set_var(
            super::super::mock_llm::MOCK_LLM_ENV,
            super::super::mock_llm::MOCK_LLM_ECHO,
        );
    }
    let registry = Arc::new(SessionRegistry::new());
    let agents = agents_dir();
    let project = tempfile::tempdir().expect("project tempdir");
    let workstreams = crate::workstreams::test_shared_store().await;
    let bound_id = seed_active_workstream(&workstreams).await;

    let first = task_run(
        Arc::clone(&registry),
        json!({"task_description": "say hi"}),
        ProjectBinding::resolve(Some(project.path().to_path_buf())).expect("tempdir must bind"),
        agents.path().to_path_buf(),
        workstreams.clone(),
    )
    .await
    .expect("first task.run should succeed");
    let session_id = first["session_id"].as_str().unwrap().to_string();

    let other_id = workstreams
        .lock()
        .await
        .create("other")
        .await
        .expect("create");
    let err = task_run(
        Arc::clone(&registry),
        json!({
            "task_description": "say hi again",
            "session_id": session_id,
            "workstream_id": other_id.to_string(),
        }),
        ProjectBinding::resolve(Some(project.path().to_path_buf())).expect("tempdir must bind"),
        agents.path().to_path_buf(),
        workstreams.clone(),
    )
    .await;
    unsafe {
        std::env::remove_var(super::super::mock_llm::MOCK_LLM_ENV);
    }
    let err = err.expect_err("a mismatched workstream_id on reuse must be rejected");
    assert_eq!(err.code, -32003);
    assert_ne!(bound_id, other_id);
}

/// (PR #3354 code-critic HIGH 2 regression) A rejected bind on `task.run`'s
/// mint path must leave the `SessionRegistry` UNCHANGED — no phantom,
/// caller-invisible session may survive the error — for ALL THREE
/// caller-triggerable failure modes: closed workstream, unknown workstream,
/// malformed id. No mock-LLM env is needed: the rejection fires before
/// `build_llm_client` is ever reached.
#[tokio::test]
async fn task_run_rejected_bind_leaves_no_phantom_session() {
    let registry = Arc::new(SessionRegistry::new());
    let agents = agents_dir();
    let project = tempfile::tempdir().expect("project tempdir");
    let workstreams = crate::workstreams::test_shared_store().await;
    let closed = workstreams
        .lock()
        .await
        .create("closed")
        .await
        .expect("create");
    workstreams.lock().await.close(closed).await.expect("close");

    let cases: &[(&str, String, i32)] = &[
        ("closed workstream", closed.to_string(), -32003),
        (
            "unknown workstream",
            crate::workstreams::WorkstreamId::new().to_string(),
            -32002,
        ),
        ("malformed id", "not-a-uuid".to_string(), -32602),
    ];
    for (label, ws_id, expected_code) in cases {
        let before = registry.list().len();
        let err = task_run(
            Arc::clone(&registry),
            json!({"task_description": "say hi", "workstream_id": ws_id}),
            ProjectBinding::resolve(Some(project.path().to_path_buf())).expect("tempdir must bind"),
            agents.path().to_path_buf(),
            workstreams.clone(),
        )
        .await
        .expect_err("bind must be rejected");
        assert_eq!(err.code, *expected_code, "{label}: wrong error code");
        assert_eq!(
            registry.list().len(),
            before,
            "{label}: a rejected bind must not leave a phantom session"
        );
    }
    assert_eq!(
        registry.list().len(),
        0,
        "no session may exist after three rejected task.run calls"
    );
}

/// #8031: `task.run`'s `no_delegate` field defaults to `false` when omitted.
///
/// Why: the field is the API-side half of the `--no-delegate` flag. Without
/// `#[serde(default)]` every existing caller's body would fail to parse, and a
/// wrong default would silently disable delegation for every run.
/// What: deserialises a minimal request body through the real
/// `TaskRunRequestParams` and asserts the parsed field.
/// Test: this test.
#[test]
fn task_run_params_default_no_delegate_to_false() {
    let p: TaskRunRequestParams =
        serde_json::from_value(json!({"task_description": "say hi"})).expect("minimal body parses");
    assert!(!p.no_delegate, "an omitted no_delegate must parse as false");
}

/// #8031: `no_delegate: true` round-trips through `task.run`'s serde.
///
/// Why/What: pins the wire spelling the CLI's thin-client path sends
/// (`cli::run_task::build_run_params`) against the field that parses it.
/// Test: this test.
#[test]
fn task_run_params_parse_no_delegate_true() {
    let p: TaskRunRequestParams =
        serde_json::from_value(json!({"task_description": "say hi", "no_delegate": true}))
            .expect("body with no_delegate parses");
    assert!(p.no_delegate, "no_delegate: true must parse as true");
}

// ── #8030 / #8128: `task.run`'s pm_model / max_turns fields ────────────────

/// #8030: `pm_model` round-trips through `task.run`'s serde.
///
/// Why/What: pins the wire spelling the CLI's thin-client path sends
/// (`cli::run_task::build_run_params`) against the field that parses it — the
/// exact seam a rename would silently break, since no compiler check spans it.
/// Test: this test.
#[test]
fn task_run_params_parse_pm_model() {
    let p: TaskRunRequestParams = serde_json::from_value(
        json!({"task_description": "say hi", "pm_model": "anthropic/claude-opus-5"}),
    )
    .expect("body with pm_model parses");
    assert_eq!(p.pm_model.as_deref(), Some("anthropic/claude-opus-5"));
}

/// #8030: an omitted `pm_model` parses as `None`.
///
/// Why: every pre-#8030 caller sends a body without the field; a missing
/// `#[serde(default)]` would turn all of them into parse errors.
/// What: deserialises a minimal body and asserts `None`.
/// Test: this test.
#[test]
fn task_run_params_default_pm_model_to_none() {
    let p: TaskRunRequestParams =
        serde_json::from_value(json!({"task_description": "say hi"})).expect("minimal body parses");
    assert!(
        p.pm_model.is_none(),
        "an omitted pm_model must parse as None"
    );
}

/// #8128: `max_turns` round-trips through `task.run`'s serde, and an omitted
/// field parses as `None`.
///
/// Why/What: same wire-spelling seam as `pm_model` above, plus the
/// absent-means-unchanged guarantee the turn-cap override rests on.
/// Test: this test.
#[test]
fn task_run_params_parse_max_turns() {
    let set: TaskRunRequestParams =
        serde_json::from_value(json!({"task_description": "say hi", "max_turns": 24}))
            .expect("body with max_turns parses");
    assert_eq!(set.max_turns, Some(24));

    let unset: TaskRunRequestParams =
        serde_json::from_value(json!({"task_description": "say hi"})).expect("minimal body parses");
    assert!(unset.max_turns.is_none());
}

// ── #8184: a `session.create`d session's agent shape drives its turns ────────

/// Mint a session through the REAL `session.create` handler and return its id.
///
/// Why (#8184): the tests below have to observe what a session minted the way
/// `tcode tui` mints one actually runs, so they must go through
/// `session::protocol`'s own handler rather than `SessionRegistry::create` —
/// the default they are asserting lives in that handler.
/// What: registers `session.*` on a throwaway `Router` and dispatches
/// `session.create` with `extra` merged into the params.
/// Test: `task_run_on_a_default_session_never_delegates`,
/// `task_run_on_a_delegating_session_still_delegates`.
async fn create_session(
    registry: Arc<SessionRegistry>,
    workstreams: crate::workstreams::SharedWorkstreamStore,
    project: &std::path::Path,
    extra: Value,
) -> String {
    let mut router = Router::new();
    crate::session::protocol::register(&mut router, registry, workstreams);
    let mut params = json!({"task": "tcode tui session", "project": project});
    for (k, v) in extra.as_object().expect("extra must be an object") {
        params[k] = v.clone();
    }
    let resp = router
        .dispatch(
            Request {
                jsonrpc: Some("2.0".to_string()),
                id: Some(json!(1)),
                method: "session.create".to_string(),
                params: Some(params),
            },
            &test_ctx(),
        )
        .await;
    assert!(resp.error.is_none(), "session.create: {:?}", resp.error);
    resp.result.expect("result")["id"]
        .as_str()
        .expect("id")
        .to_string()
}

/// Block until `id`'s run reaches a terminal state.
async fn await_terminal(registry: &SessionRegistry, id: &str) {
    let deadline = tokio::time::Instant::now() + tokio::time::Duration::from_secs(20);
    loop {
        if registry
            .status(id)
            .expect("session must exist")
            .status
            .is_terminal()
        {
            return;
        }
        assert!(
            tokio::time::Instant::now() < deadline,
            "run did not reach a terminal state within 20s"
        );
        tokio::time::sleep(tokio::time::Duration::from_millis(20)).await;
    }
}

/// Every sub-agent this session's run spawned, and every `(agent, tool)` pair
/// it started.
///
/// Why (#8184): "did this turn delegate" is answered by `AgentSpawned`, not by
/// `ToolStarted` — the loop emits a `ToolStarted` for a requested tool even
/// when the registry does not carry it, so a scripted `delegate_to_agent` call
/// against the solo registry still shows up as a started (and immediately
/// failed) call. A sub-agent is spawned only when the tool really ran, and the
/// tool attribution says who did the work.
/// Test: `task_run_on_a_default_session_never_delegates`,
/// `task_run_on_a_delegating_session_still_delegates`.
fn spawns_and_tool_calls(
    registry: &SessionRegistry,
    id: &str,
) -> (Vec<String>, Vec<(String, String)>) {
    let mut spawned = Vec::new();
    let mut calls = Vec::new();
    for e in registry.replay(id).expect("session must exist") {
        match &e.event {
            crate::events::Event::AgentSpawned { agent, .. } => spawned.push(agent.clone()),
            crate::events::Event::ToolStarted { agent, tool, .. } => {
                calls.push((agent.clone(), tool.clone()))
            }
            _ => {}
        }
    }
    (spawned, calls)
}

/// #8184 CLOSURE TEST: a turn on a DEFAULT `session.create`d session issues
/// ZERO `delegate_to_agent` calls.
///
/// Why: this is the issue's stated must-be-true, driven through the two real
/// handlers `tcode tui` drives — `session.create` (no `delegate` param, the
/// TUI's own call) then `task.run` (no `no_delegate` param, exactly what
/// `run_chat_turn` sends). A unit test on either handler alone would not show
/// that the session's shape survives the hop between them.
/// What: mints a default session, runs one turn under the `echo` mock whose
/// FIRST scripted response is a `delegate_to_agent` call, and asserts NO
/// sub-agent was spawned and that the run's own `bash` call was made by the
/// top-level agent itself. FAILS before #8184: the session was delegating, the
/// tool was registered, and `python-engineer` ran the turn.
/// Test: this test.
#[tokio::test]
async fn task_run_on_a_default_session_never_delegates() {
    let _guard = super::super::mock_llm::MOCK_LLM_ENV_LOCK.lock().await;
    // SAFETY: test-only env mutation; serialized by the lock above.
    unsafe {
        std::env::set_var(
            super::super::mock_llm::MOCK_LLM_ENV,
            super::super::mock_llm::MOCK_LLM_ECHO,
        );
    }
    let registry = Arc::new(SessionRegistry::new());
    let agents = agents_dir();
    let project = tempfile::tempdir().expect("project tempdir");
    let workstreams = crate::workstreams::test_shared_store().await;
    let session_id = create_session(
        Arc::clone(&registry),
        workstreams.clone(),
        project.path(),
        json!({}),
    )
    .await;

    let value = task_run(
        Arc::clone(&registry),
        json!({"task_description": "add a doc comment to fn X", "session_id": session_id}),
        ProjectBinding::resolve(Some(project.path().to_path_buf())).expect("tempdir must bind"),
        agents.path().to_path_buf(),
        workstreams,
    )
    .await
    .expect("task.run should succeed");
    assert_eq!(value["status"], "running");
    await_terminal(&registry, &session_id).await;
    unsafe {
        std::env::remove_var(super::super::mock_llm::MOCK_LLM_ENV);
    }

    let (spawned, calls) = spawns_and_tool_calls(&registry, &session_id);
    assert!(
        spawned.is_empty(),
        "a default TUI session must spawn no sub-agent; got {spawned:?}"
    );
    assert!(
        calls
            .iter()
            .any(|(agent, tool)| agent == "pm" && tool == "bash"),
        "the top-level agent must run the tool itself; got {calls:?}"
    );
}

/// #8184 companion: a session created with `delegate: true` still delegates.
///
/// Why: without this, `task_run_on_a_default_session_never_delegates` would
/// also pass if delegation had been removed outright — the default change
/// would be indistinguishable from losing the PM entirely.
/// What: the same flow with `delegate: true` on `session.create`, asserting the
/// scripted `delegate_to_agent` call really spawns `python-engineer`.
/// Test: this test.
#[tokio::test]
async fn task_run_on_a_delegating_session_still_delegates() {
    let _guard = super::super::mock_llm::MOCK_LLM_ENV_LOCK.lock().await;
    // SAFETY: test-only env mutation; serialized by the lock above.
    unsafe {
        std::env::set_var(
            super::super::mock_llm::MOCK_LLM_ENV,
            super::super::mock_llm::MOCK_LLM_ECHO,
        );
    }
    let registry = Arc::new(SessionRegistry::new());
    let agents = agents_dir();
    let project = tempfile::tempdir().expect("project tempdir");
    let workstreams = crate::workstreams::test_shared_store().await;
    let session_id = create_session(
        Arc::clone(&registry),
        workstreams.clone(),
        project.path(),
        json!({"delegate": true}),
    )
    .await;

    task_run(
        Arc::clone(&registry),
        json!({"task_description": "ship the feature", "session_id": session_id}),
        ProjectBinding::resolve(Some(project.path().to_path_buf())).expect("tempdir must bind"),
        agents.path().to_path_buf(),
        workstreams,
    )
    .await
    .expect("task.run should succeed");
    await_terminal(&registry, &session_id).await;
    unsafe {
        std::env::remove_var(super::super::mock_llm::MOCK_LLM_ENV);
    }

    let (spawned, calls) = spawns_and_tool_calls(&registry, &session_id);
    assert!(
        spawned.iter().any(|a| a == "python-engineer"),
        "delegate: true must keep the PM's delegation; spawned {spawned:?}, calls {calls:?}"
    );
}

/// #8184: `no_delegate: true` against a DELEGATING session is rejected, and
/// the session's reported shape is what the run would have used.
///
/// Why: the effective shape and the persisted one must never diverge —
/// `session.status`/`session.list` keep reporting the persisted value, so a
/// call that silently ran the other shape is the record-vs-run divergence the
/// sibling `project` guard exists to prevent (PR #3189). Rejecting is what
/// makes "a session's reported shape IS the shape it runs" true by
/// construction.
/// What: mints a delegating session through `session.create`, then asserts
/// (a) `task.run` with `no_delegate: true` is `-32003 invalid_argument`,
/// (b) the session still reports `no_delegate: false`, and (c) the same call
/// WITHOUT the param is accepted, so the guard rejects only the mismatch.
/// Test: this test.
#[tokio::test]
async fn task_run_no_delegate_against_a_delegating_session_is_rejected() {
    let _guard = super::super::mock_llm::MOCK_LLM_ENV_LOCK.lock().await;
    // SAFETY: test-only env mutation; serialized by the lock above.
    unsafe {
        std::env::set_var(
            super::super::mock_llm::MOCK_LLM_ENV,
            super::super::mock_llm::MOCK_LLM_ECHO,
        );
    }
    let registry = Arc::new(SessionRegistry::new());
    let agents = agents_dir();
    let project = tempfile::tempdir().expect("project tempdir");
    let workstreams = crate::workstreams::test_shared_store().await;
    let session_id = create_session(
        Arc::clone(&registry),
        workstreams.clone(),
        project.path(),
        json!({"delegate": true}),
    )
    .await;

    let err = task_run(
        Arc::clone(&registry),
        json!({
            "task_description": "say hi",
            "session_id": session_id,
            "no_delegate": true,
        }),
        ProjectBinding::resolve(Some(project.path().to_path_buf())).expect("tempdir must bind"),
        agents.path().to_path_buf(),
        workstreams.clone(),
    )
    .await
    .expect_err("a shape mismatch must be rejected");
    assert_eq!(err.code, -32003);

    let session = serde_json::to_value(registry.status(&session_id).expect("session must exist"))
        .expect("serialize");
    assert_eq!(
        session["no_delegate"],
        json!(false),
        "the rejected call must not have changed the reported shape: {session}"
    );

    // The guard rejects the MISMATCH, not the session.
    task_run(
        Arc::clone(&registry),
        json!({"task_description": "say hi", "session_id": session_id}),
        ProjectBinding::resolve(Some(project.path().to_path_buf())).expect("tempdir must bind"),
        agents.path().to_path_buf(),
        workstreams,
    )
    .await
    .expect("restating the session's own shape must be accepted");
    await_terminal(&registry, &session_id).await;
    unsafe {
        std::env::remove_var(super::super::mock_llm::MOCK_LLM_ENV);
    }
}

/// #8184: a `task.run` that mints its OWN session records that call's shape.
///
/// Why: the inheritance above only works if the mint path persists what it
/// was asked for — otherwise a `tcode run-task --no-delegate` session would
/// silently regain `delegate_to_agent` on its second turn.
/// What: `task.run` with `no_delegate: true` and no `session_id`, asserting
/// the minted session reports `no_delegate: true`. FAILS before #8184 — the
/// field did not exist, so the assertion reads `null`.
/// Test: this test.
#[tokio::test]
async fn task_run_minted_session_records_its_no_delegate() {
    let _guard = super::super::mock_llm::MOCK_LLM_ENV_LOCK.lock().await;
    // SAFETY: test-only env mutation; serialized by the lock above.
    unsafe {
        std::env::set_var(
            super::super::mock_llm::MOCK_LLM_ENV,
            super::super::mock_llm::MOCK_LLM_ECHO,
        );
    }
    let registry = Arc::new(SessionRegistry::new());
    let agents = agents_dir();
    let project = tempfile::tempdir().expect("project tempdir");
    let value = task_run(
        Arc::clone(&registry),
        json!({"task_description": "say hi", "no_delegate": true}),
        ProjectBinding::resolve(Some(project.path().to_path_buf())).expect("tempdir must bind"),
        agents.path().to_path_buf(),
        crate::workstreams::test_shared_store().await,
    )
    .await
    .expect("task.run should succeed");
    let session_id = value["session_id"]
        .as_str()
        .expect("session_id")
        .to_string();
    await_terminal(&registry, &session_id).await;
    unsafe {
        std::env::remove_var(super::super::mock_llm::MOCK_LLM_ENV);
    }

    let session = serde_json::to_value(registry.status(&session_id).expect("session must exist"))
        .expect("serialize");
    assert_eq!(
        session["no_delegate"],
        json!(true),
        "a --no-delegate run's session must remember it; got {session}"
    );
}

/// #8128: `max_turns: 0` is rejected with `-32003 invalid_argument` before a
/// session is minted.
///
/// Why: a zero-turn loop makes no LLM call at all and would report the empty
/// result as a normal run. Rejecting it in the handler — rather than letting
/// it through to `AgentLoopConfig` — is also what keeps a direct RPC caller
/// from bypassing the CLI flag's own `value_parser` range check.
/// What: drives the real `task_run` handler with a zero cap and asserts the
/// error code.
/// Test: this test.
#[tokio::test]
async fn task_run_rejects_zero_max_turns() {
    let registry = Arc::new(SessionRegistry::new());
    let agents = agents_dir();
    let project = tempfile::tempdir().expect("project tempdir");
    let err = task_run(
        registry,
        json!({"task_description": "say hi", "max_turns": 0}),
        ProjectBinding::resolve(Some(project.path().to_path_buf())).expect("tempdir must bind"),
        agents.path().to_path_buf(),
        crate::workstreams::test_shared_store().await,
    )
    .await
    .unwrap_err();
    assert_eq!(err.code, -32003);
}