trusty-code 0.2.0

Per-project Claude-Code-compatible MPM orchestration harness (bin: tcode) — an original coding harness, tracked under epic #2052.
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
//! Unit tests for `SessionRegistry` (#2054, #2055). Split out of
//! `registry.rs` per the crate's `_tests.rs` sibling-file convention (see
//! `intent::classifier_tests` for precedent) to keep the production file
//! under the 500-SLOC cap.

use super::*;
use tokio::sync::broadcast;
use tokio::sync::mpsc;
use tokio::time::{Duration, timeout};

/// Build a throwaway `(NotifySender, receiver)` pair for attach tests.
fn notify_channel() -> (NotifySender, mpsc::UnboundedReceiver<serde_json::Value>) {
    mpsc::unbounded_channel()
}

/// Read from the process-global event bus until an envelope matching
/// `session_id` arrives, ignoring anything else.
///
/// Why: `crate::events::bus()` is a single process-wide singleton shared by
/// every test in this binary; cargo runs tests concurrently, so a raw
/// `events.recv().await` can observe another test's unrelated envelope
/// interleaved on the same subscription. Filtering by `session_id` (unique
/// per test via a fresh UUID) makes these tests robust to that interleaving
/// instead of assuming "the very next envelope is mine". Bounded by a 2s
/// timeout so a genuine bug (event never published) still fails fast
/// instead of hanging.
async fn next_event_for(
    rx: &mut broadcast::Receiver<SessionEventEnvelope>,
    session_id: &str,
) -> SessionEventEnvelope {
    timeout(Duration::from_secs(2), async {
        loop {
            let envelope = rx.recv().await.expect("event bus closed unexpectedly");
            if envelope.session_id == session_id {
                return envelope;
            }
        }
    })
    .await
    .expect("timed out waiting for an event on this session")
}

/// `create` must publish `SessionStarted` (seq 1) then `SessionStatusChanged`
/// (seq 2, `status: "running"`), and the returned snapshot must already be
/// `Running`.
#[tokio::test]
async fn create_publishes_started_and_status_events() {
    let registry = SessionRegistry::new();
    let mut events = crate::events::subscribe();

    let session = registry.create("do the thing".to_string(), None, Some("proj".to_string()));
    assert_eq!(session.status, SessionStatus::Running);

    let first = next_event_for(&mut events, &session.id).await;
    assert_eq!(first.seq, 1);
    assert_eq!(first.kind, "session_started");
    assert!(matches!(first.event, Event::SessionStarted { project, .. } if project == "proj"));

    let second = next_event_for(&mut events, &session.id).await;
    assert_eq!(second.seq, 2);
    assert!(
        matches!(second.event, Event::SessionStatusChanged { status, .. } if status == "running")
    );
}

/// `list` must return every created session.
#[tokio::test]
async fn list_returns_every_created_session() {
    let registry = SessionRegistry::new();
    registry.create("a".to_string(), None, None);
    registry.create("b".to_string(), None, None);
    assert_eq!(registry.list().len(), 2);
}

/// `status` on an unknown id must return `session_not_found`.
#[tokio::test]
async fn status_returns_not_found_for_unknown_id() {
    let registry = SessionRegistry::new();
    let err = registry.status("does-not-exist").unwrap_err();
    assert_eq!(err.code, -32007);
}

/// `send` must publish `SessionInput` carrying the given text.
#[tokio::test]
async fn send_publishes_input_event() {
    let registry = SessionRegistry::new();
    let session = registry.create("t".to_string(), None, None);
    let mut events = crate::events::subscribe();

    registry.send(&session.id, "hello").unwrap();

    let envelope = next_event_for(&mut events, &session.id).await;
    assert_eq!(envelope.seq, 3); // after SessionStarted(1), StatusChanged(2)
    assert!(matches!(envelope.event, Event::SessionInput { input, .. } if input == "hello"));
}

/// `send` on an unknown session must error, not panic.
#[tokio::test]
async fn send_unknown_session_errors() {
    let registry = SessionRegistry::new();
    let err = registry.send("nope", "hi").unwrap_err();
    assert_eq!(err.code, -32007);
}

/// `cancel` must transition to `Cancelled` and publish the terminal events
/// (`status_changed` -> `session_cancelled` -> `session_done`), each with a
/// strictly increasing `seq`.
#[tokio::test]
async fn cancel_transitions_to_cancelled_and_publishes() {
    let registry = SessionRegistry::new();
    let session = registry.create("t".to_string(), None, None);
    let mut events = crate::events::subscribe();

    let cancelled = registry.cancel(&session.id).unwrap();
    assert_eq!(cancelled.status, SessionStatus::Cancelled);

    let status_changed = next_event_for(&mut events, &session.id).await;
    assert!(
        matches!(status_changed.event, Event::SessionStatusChanged { status, .. } if status == "cancelled")
    );

    let cancelled_event = next_event_for(&mut events, &session.id).await;
    assert!(matches!(
        cancelled_event.event,
        Event::SessionCancelled { .. }
    ));
    assert!(cancelled_event.seq > status_changed.seq);

    let done = next_event_for(&mut events, &session.id).await;
    assert!(matches!(done.event, Event::SessionDone { status, .. } if status == "cancelled"));
    assert!(done.seq > cancelled_event.seq);

    // Idempotent: cancelling again returns the same terminal snapshot,
    // no error, no further events required.
    let again = registry.cancel(&session.id).unwrap();
    assert_eq!(again.status, SessionStatus::Cancelled);
}

/// `cancel` on an unknown session must error.
#[tokio::test]
async fn cancel_unknown_session_errors() {
    let registry = SessionRegistry::new();
    let err = registry.cancel("nope").unwrap_err();
    assert_eq!(err.code, -32007);
}

/// `attach` must replay the ring buffer accumulated so far, in order, with
/// `seq` starting at 1 and increasing by 1 per entry.
#[tokio::test]
async fn attach_returns_ring_buffer_replay() {
    let registry = SessionRegistry::new();
    let session = registry.create("t".to_string(), None, None);
    registry.send(&session.id, "one").unwrap();

    let (tx, _rx) = notify_channel();
    let replay = registry.attach(&session.id, Uuid::new_v4(), tx).unwrap();

    // SessionStarted(1), SessionStatusChanged(2, running), SessionInput(3).
    assert_eq!(replay.len(), 3);
    let seqs: Vec<u64> = replay.iter().map(|e| e.seq).collect();
    assert_eq!(seqs, vec![1, 2, 3]);
    assert!(
        matches!(&replay.last().unwrap().event, Event::SessionInput { input, .. } if input == "one")
    );
}

/// After `attach`, a live event published on the session must be forwarded
/// to the connection's notify channel as a JSON-RPC notification whose
/// `params` is the full envelope.
#[tokio::test]
async fn attach_forwards_live_events_until_detach() {
    let registry = SessionRegistry::new();
    let session = registry.create("t".to_string(), None, None);
    let connection_id = Uuid::new_v4();
    let (tx, mut rx) = notify_channel();

    registry.attach(&session.id, connection_id, tx).unwrap();

    registry.send(&session.id, "live").unwrap();

    let notification = timeout(Duration::from_secs(2), rx.recv())
        .await
        .expect("forwarder must deliver the live event")
        .expect("channel must still be open");
    assert_eq!(notification["method"], "session.event");
    assert_eq!(notification["params"]["session_id"], session.id);
    assert_eq!(notification["params"]["seq"], 3);
    assert_eq!(notification["params"]["kind"], "session_input");
    assert_eq!(notification["params"]["event"]["type"], "session_input");
    assert_eq!(notification["params"]["event"]["input"], "live");
    assert!(notification["params"]["at"].is_string());

    registry.detach(&session.id, connection_id).unwrap();
    // The forwarder task is cancelled by waking its `select!` on a
    // separate spawned task; give the scheduler a beat to actually run it
    // before publishing the next event, so this assertion isn't racing the
    // cancellation.
    tokio::time::sleep(Duration::from_millis(50)).await;
    registry.send(&session.id, "after-detach").unwrap();

    // Two outcomes both mean "no event arrived": the read times out (the
    // channel is still open but empty), or `recv` resolves to `None`
    // because the cancelled forwarder already dropped its `NotifySender`
    // (this is what actually happens here — the forwarder holds the only
    // sender, so cancelling it closes the channel almost immediately,
    // resolving `recv()` quickly rather than timing out). Only `Some(_)`
    // — an actual forwarded event — is a failure.
    match timeout(Duration::from_millis(300), rx.recv()).await {
        Err(_) => {}   // timed out waiting: nothing arrived, good.
        Ok(None) => {} // channel closed: nothing arrived, good.
        Ok(Some(v)) => panic!("no event should arrive after detach, got {v:?}"),
    }
}

/// Replay and live events must share ONE gap-free, strictly increasing
/// `seq` — the correctness property the whole envelope design exists for.
#[tokio::test]
async fn attach_replay_then_live_seq_is_contiguous() {
    let registry = SessionRegistry::new();
    let session = registry.create("t".to_string(), None, None);
    registry.send(&session.id, "before-attach").unwrap();

    let (tx, mut rx) = notify_channel();
    let replay = registry.attach(&session.id, Uuid::new_v4(), tx).unwrap();
    let last_replay_seq = replay.last().unwrap().seq;

    registry.send(&session.id, "after-attach").unwrap();
    let notification = timeout(Duration::from_secs(2), rx.recv())
        .await
        .expect("forwarder must deliver the live event")
        .expect("channel must still be open");
    let live_seq = notification["params"]["seq"].as_u64().unwrap();

    assert_eq!(
        live_seq,
        last_replay_seq + 1,
        "no gap and no duplicate between replay and live"
    );

    // The whole replay sequence itself must be gap-free from 1.
    for (i, envelope) in replay.iter().enumerate() {
        assert_eq!(envelope.seq, (i as u64) + 1);
    }
}

/// `attach` on an unknown session must error.
#[tokio::test]
async fn attach_unknown_session_errors() {
    let registry = SessionRegistry::new();
    let (tx, _rx) = notify_channel();
    let err = registry.attach("nope", Uuid::new_v4(), tx).unwrap_err();
    assert_eq!(err.code, -32007);
}

/// `detach` without a prior `attach` for that connection must be a no-op
/// success, not an error.
#[tokio::test]
async fn detach_without_prior_attach_is_a_noop() {
    let registry = SessionRegistry::new();
    let session = registry.create("t".to_string(), None, None);
    registry.detach(&session.id, Uuid::new_v4()).unwrap();
}

/// `detach` on an unknown session must error.
#[tokio::test]
async fn detach_unknown_session_errors() {
    let registry = SessionRegistry::new();
    let err = registry.detach("nope", Uuid::new_v4()).unwrap_err();
    assert_eq!(err.code, -32007);
}

/// `replay` must return the ring buffer without registering an attachment
/// (no forwarder side effect).
#[tokio::test]
async fn replay_returns_ring_buffer_without_attaching() {
    let registry = SessionRegistry::new();
    let session = registry.create("t".to_string(), None, None);
    let replay = registry.replay(&session.id).unwrap();
    assert_eq!(replay.len(), 2); // SessionStarted + SessionStatusChanged(running)
}

/// The ring buffer must drop the oldest event once it reaches capacity.
#[tokio::test]
async fn ring_buffer_drops_oldest_when_full() {
    let registry = SessionRegistry::with_capacity(2);
    let session = registry.create("t".to_string(), None, None);
    // Ring already has 2 entries (SessionStarted, StatusChanged running) at
    // capacity 2; one more push must evict the oldest (SessionStarted).
    registry.send(&session.id, "evicts-started").unwrap();

    let replay = registry.replay(&session.id).unwrap();
    assert_eq!(replay.len(), 2);
    assert!(matches!(
        replay.first().unwrap().event,
        Event::SessionStatusChanged { .. }
    ));
    assert!(
        matches!(&replay.last().unwrap().event, Event::SessionInput { input, .. } if input == "evicts-started")
    );
    // Eviction must not reset the seq counter — the surviving entries keep
    // their original sequence numbers (2, 3), not renumbered to (1, 2).
    let seqs: Vec<u64> = replay.iter().map(|e| e.seq).collect();
    assert_eq!(seqs, vec![2, 3]);
}

/// `record_tool_started` must publish a `ToolStarted` event with a
/// truncated `args_preview`.
#[tokio::test]
async fn record_tool_started_publishes_event() {
    let registry = SessionRegistry::new();
    let session = registry.create("t".to_string(), None, None);
    let mut events = crate::events::subscribe();

    registry
        .record_tool_started(&session.id, "bash", "call-1", "ls -la")
        .unwrap();

    let envelope = next_event_for(&mut events, &session.id).await;
    assert_eq!(envelope.kind, "tool_started");
    assert!(matches!(
        envelope.event,
        Event::ToolStarted { tool, call_id, args_preview, .. }
            if tool == "bash" && call_id == "call-1" && args_preview == "ls -la"
    ));
}

/// `record_tool_finished` must publish a `ToolFinished` event carrying
/// `success` and a truncated `result_preview`.
#[tokio::test]
async fn record_tool_finished_publishes_event() {
    let registry = SessionRegistry::new();
    let session = registry.create("t".to_string(), None, None);
    let mut events = crate::events::subscribe();

    registry
        .record_tool_finished(&session.id, "bash", "call-1", true, "done")
        .unwrap();

    let envelope = next_event_for(&mut events, &session.id).await;
    assert_eq!(envelope.kind, "tool_finished");
    assert!(matches!(
        envelope.event,
        Event::ToolFinished { success, result_preview, .. } if success && result_preview == "done"
    ));
}

/// `record_tool_error` must publish a `ToolError` event.
#[tokio::test]
async fn record_tool_error_publishes_event() {
    let registry = SessionRegistry::new();
    let session = registry.create("t".to_string(), None, None);
    let mut events = crate::events::subscribe();

    registry
        .record_tool_error(&session.id, "bash", "call-1", "timed out")
        .unwrap();

    let envelope = next_event_for(&mut events, &session.id).await;
    assert_eq!(envelope.kind, "tool_error");
    assert!(matches!(envelope.event, Event::ToolError { error, .. } if error == "timed out"));
}

/// `record_log` must publish a `Log` event.
#[tokio::test]
async fn record_log_publishes_event() {
    let registry = SessionRegistry::new();
    let session = registry.create("t".to_string(), None, None);
    let mut events = crate::events::subscribe();

    registry
        .record_log(&session.id, "warn", "disk almost full")
        .unwrap();

    let envelope = next_event_for(&mut events, &session.id).await;
    assert_eq!(envelope.kind, "log");
    assert!(
        matches!(envelope.event, Event::Log { level, message, .. } if level == "warn" && message == "disk almost full")
    );
}

/// `record_progress` must publish a `Progress` event.
#[tokio::test]
async fn record_progress_publishes_event() {
    let registry = SessionRegistry::new();
    let session = registry.create("t".to_string(), None, None);
    let mut events = crate::events::subscribe();

    registry
        .record_progress(&session.id, "indexing", Some(0.5))
        .unwrap();

    let envelope = next_event_for(&mut events, &session.id).await;
    assert_eq!(envelope.kind, "progress");
    assert!(matches!(envelope.event, Event::Progress { percent: Some(p), .. } if p == 0.5));
}

/// `record_message` must publish a `Message` event.
#[tokio::test]
async fn record_message_publishes_event() {
    let registry = SessionRegistry::new();
    let session = registry.create("t".to_string(), None, None);
    let mut events = crate::events::subscribe();

    registry.record_message(&session.id, "hello world").unwrap();

    let envelope = next_event_for(&mut events, &session.id).await;
    assert_eq!(envelope.kind, "message");
    assert!(matches!(envelope.event, Event::Message { text, .. } if text == "hello world"));
}

/// Every `record_*` emission-plumbing method must reject an unknown
/// session id with `session_not_found` rather than panicking.
#[tokio::test]
async fn record_plumbing_methods_reject_unknown_session() {
    let registry = SessionRegistry::new();
    assert_eq!(
        registry
            .record_tool_started("nope", "t", "c", "a")
            .unwrap_err()
            .code,
        -32007
    );
    assert_eq!(
        registry
            .record_tool_finished("nope", "t", "c", true, "r")
            .unwrap_err()
            .code,
        -32007
    );
    assert_eq!(
        registry
            .record_tool_error("nope", "t", "c", "e")
            .unwrap_err()
            .code,
        -32007
    );
    assert_eq!(
        registry.record_log("nope", "info", "m").unwrap_err().code,
        -32007
    );
    assert_eq!(
        registry
            .record_progress("nope", "m", None)
            .unwrap_err()
            .code,
        -32007
    );
    assert_eq!(
        registry.record_message("nope", "m").unwrap_err().code,
        -32007
    );
}

// ── #2056: execution-lifecycle tracking ─────────────────────────────────────────

/// `begin_execution` on an unknown session must error.
#[tokio::test]
async fn begin_execution_unknown_session_errors() {
    let registry = SessionRegistry::new();
    let err = registry.begin_execution("nope").unwrap_err();
    assert_eq!(err.code, -32007);
}

/// `begin_execution` on an already-terminal session must be rejected.
#[tokio::test]
async fn begin_execution_rejects_terminal_session() {
    let registry = SessionRegistry::new();
    let session = registry.create("t".to_string(), None, None);
    registry.cancel(&session.id).unwrap();

    let err = registry.begin_execution(&session.id).unwrap_err();
    assert_eq!(
        err.code, -32003,
        "must be invalid_argument, not session_not_found"
    );
}

/// A second `begin_execution` while one is already in flight must be
/// rejected; after `finish_execution`, a new one must succeed.
#[tokio::test]
async fn begin_execution_rejects_second_overlapping_run() {
    let registry = SessionRegistry::new();
    let session = registry.create("t".to_string(), None, None);

    let _first = registry.begin_execution(&session.id).unwrap();
    let err = registry.begin_execution(&session.id).unwrap_err();
    assert_eq!(err.code, -32003);

    registry.finish_execution(&session.id);
    assert!(
        registry.begin_execution(&session.id).is_ok(),
        "a new execution must be startable once the prior one finished"
    );
}

/// `request_cancel` on a session with no in-flight execution must return
/// `Ok(false)` (the caller falls back to the immediate-transition `cancel`).
#[tokio::test]
async fn request_cancel_returns_false_when_idle() {
    let registry = SessionRegistry::new();
    let session = registry.create("t".to_string(), None, None);
    assert!(!registry.request_cancel(&session.id).unwrap());
}

/// `request_cancel` on an executing session must set the flag and return
/// `Ok(true)`; `is_executing` must reflect the in-flight state throughout.
#[tokio::test]
async fn request_cancel_sets_flag_when_executing() {
    let registry = SessionRegistry::new();
    let session = registry.create("t".to_string(), None, None);
    assert!(!registry.is_executing(&session.id));

    let cancel = registry.begin_execution(&session.id).unwrap();
    assert!(registry.is_executing(&session.id));
    assert!(!cancel.load(std::sync::atomic::Ordering::Relaxed));

    assert!(registry.request_cancel(&session.id).unwrap());
    assert!(
        cancel.load(std::sync::atomic::Ordering::Relaxed),
        "the SAME flag must observe the request"
    );
}

/// `request_cancel` on an unknown session must error.
#[tokio::test]
async fn request_cancel_unknown_session_errors() {
    let registry = SessionRegistry::new();
    assert_eq!(registry.request_cancel("nope").unwrap_err().code, -32007);
}

/// (#2344) A `Finished` session is resumable: `begin_execution` must
/// succeed on it (rather than treating `Finished` as a dead end like
/// `Cancelled`/`Failed`/`DeadlineExceeded`), transitioning the session back
/// to `Running` and publishing the same `SessionStatusChanged` event every
/// other transition in this module publishes.
///
/// Why: this is the change that makes "two sequential `task.run` calls on
/// one session" (#2344's acceptance criterion) possible at all — without it,
/// the second call would be rejected here before ever reaching
/// `begin_pm_transcript`.
#[tokio::test]
async fn begin_execution_resumes_a_finished_session() {
    let registry = SessionRegistry::new();
    let session = registry.create("t".to_string(), None, None);

    let _first = registry.begin_execution(&session.id).unwrap();
    registry.finish_execution(&session.id);
    registry
        .finish(&session.id, SessionStatus::Finished)
        .unwrap();
    assert_eq!(
        registry.status(&session.id).unwrap().status,
        SessionStatus::Finished
    );

    let mut events = crate::events::subscribe();
    assert!(
        registry.begin_execution(&session.id).is_ok(),
        "a Finished session must be resumable for its next task.run"
    );
    assert_eq!(
        registry.status(&session.id).unwrap().status,
        SessionStatus::Running,
        "resuming must transition the session back to Running"
    );

    let envelope = next_event_for(&mut events, &session.id).await;
    assert!(
        matches!(envelope.event, Event::SessionStatusChanged { status, .. } if status == "running"),
        "resuming must publish the SAME SessionStatusChanged event other transitions do"
    );
}

/// `begin_execution` must still reject `Cancelled`/`Failed`/
/// `DeadlineExceeded` sessions even after the #2344 `Finished`-resumption
/// change — only a successful finish is resumable.
#[tokio::test]
async fn begin_execution_still_rejects_cancelled_failed_and_deadline_exceeded() {
    let registry = SessionRegistry::new();

    let cancelled = registry.create("t".to_string(), None, None);
    registry.cancel(&cancelled.id).unwrap();
    assert_eq!(
        registry.begin_execution(&cancelled.id).unwrap_err().code,
        -32003
    );

    let failed = registry.create("t".to_string(), None, None);
    registry.finish(&failed.id, SessionStatus::Failed).unwrap();
    assert_eq!(
        registry.begin_execution(&failed.id).unwrap_err().code,
        -32003
    );

    let deadline = registry.create("t".to_string(), None, None);
    registry
        .finish(&deadline.id, SessionStatus::DeadlineExceeded)
        .unwrap();
    assert_eq!(
        registry.begin_execution(&deadline.id).unwrap_err().code,
        -32003
    );
}

// ── #2344: persistent PM transcript ─────────────────────────────────────────────

/// `begin_pm_transcript` seeds a fresh system+user pair on a session's FIRST
/// call.
#[tokio::test]
async fn begin_pm_transcript_seeds_on_first_call() {
    let registry = SessionRegistry::new();
    let session = registry.create("t".to_string(), None, None);

    let transcript = registry
        .begin_pm_transcript(&session.id, "you are the pm", "first task")
        .unwrap();
    let messages = transcript.messages();
    assert_eq!(messages.len(), 2);
    assert_eq!(messages[0].role, "system");
    assert_eq!(messages[0].content.as_deref(), Some("you are the pm"));
    assert_eq!(messages[1].role, "user");
    assert_eq!(messages[1].content.as_deref(), Some("first task"));
}

/// `begin_pm_transcript`'s second call appends the new task as a user turn
/// onto the EXISTING history stored by `store_pm_transcript`, without
/// re-adding a system message — the core "two sequential task.run calls
/// share one growing Transcript" acceptance criterion.
#[tokio::test]
async fn begin_pm_transcript_appends_on_second_call() {
    let registry = SessionRegistry::new();
    let session = registry.create("t".to_string(), None, None);

    let mut transcript = registry
        .begin_pm_transcript(&session.id, "you are the pm", "first task")
        .unwrap();
    transcript.push_assistant(Some("first answer".into()), &[]);
    registry.store_pm_transcript(&session.id, transcript);

    let continued = registry
        .begin_pm_transcript(&session.id, "a DIFFERENT system prompt", "second task")
        .unwrap();
    let messages = continued.messages();
    assert_eq!(messages.len(), 4, "system, user, assistant, new user");
    assert_eq!(messages[0].role, "system");
    assert_eq!(
        messages[0].content.as_deref(),
        Some("you are the pm"),
        "the ORIGINAL seed's system message must stay authoritative, not the second call's"
    );
    assert_eq!(messages[1].content.as_deref(), Some("first task"));
    assert_eq!(messages[2].role, "assistant");
    assert_eq!(messages[2].content.as_deref(), Some("first answer"));
    assert_eq!(messages[3].role, "user");
    assert_eq!(messages[3].content.as_deref(), Some("second task"));
    assert_eq!(
        messages.iter().filter(|m| m.role == "system").count(),
        1,
        "must never end up with two system messages across runs"
    );
}

/// `begin_pm_transcript` on an unknown session must error.
#[tokio::test]
async fn begin_pm_transcript_unknown_session_errors() {
    let registry = SessionRegistry::new();
    let err = registry
        .begin_pm_transcript("nope", "sys", "task")
        .unwrap_err();
    assert_eq!(err.code, -32007);
}

/// `memory_sink_for` (#2345) must construct exactly ONE sink for a session
/// and return the SAME `Arc` on every subsequent call — proving the sink (and
/// therefore its background drain task) survives across repeated
/// `task.run`s on one session rather than being rebuilt per run.
#[tokio::test]
async fn memory_sink_for_reuses_the_same_sink_across_calls() {
    let registry = SessionRegistry::new();
    let session = registry.create("t".to_string(), None, None);
    let project_dir = tempfile::TempDir::new().unwrap();

    let first = registry
        .memory_sink_for(&session.id, project_dir.path())
        .expect("first call constructs a sink");
    let second = registry
        .memory_sink_for(&session.id, project_dir.path())
        .expect("second call reuses the sink");

    assert!(
        Arc::ptr_eq(&first, &second),
        "memory_sink_for must return the SAME Arc across calls on one session"
    );
}

/// `memory_sink_for` on an unknown session must return `None`, not panic
/// (best-effort, mirrors `set_run_outcome`'s framing).
#[tokio::test]
async fn memory_sink_for_unknown_session_returns_none() {
    let registry = SessionRegistry::new();
    let project_dir = tempfile::TempDir::new().unwrap();
    assert!(
        registry
            .memory_sink_for("nope", project_dir.path())
            .is_none()
    );
}

/// `set_run_outcome` must store the transcript/usage/cost verbatim, and must
/// not panic when the session no longer exists.
#[tokio::test]
async fn set_run_outcome_stores_transcript_and_usage() {
    let registry = SessionRegistry::new();
    let session = registry.create("t".to_string(), None, None);

    let turns = vec![crate::run_task::TurnRecord {
        role: "pm".to_string(),
        model: "openai/gpt-4o-mini".to_string(),
        text: "done".to_string(),
        tool_calls: vec![],
        ran_test_command: false,
        usage: crate::perf::TokenUsage::new(10, 5, 0, 0),
    }];
    registry.set_run_outcome(
        &session.id,
        turns.clone(),
        crate::perf::TokenUsage::new(10, 5, 0, 0),
        Some(0.01),
    );

    let stored = registry.get_transcript(&session.id).unwrap();
    assert_eq!(stored.turns, turns);
    assert_eq!(stored.usage, crate::perf::TokenUsage::new(10, 5, 0, 0));
    assert_eq!(stored.cost_usd, Some(0.01));

    // A no-op on a missing session, not a panic.
    registry.set_run_outcome("nope", turns, crate::perf::TokenUsage::default(), None);
}

/// `set_run_outcome` must ACCUMULATE across two calls (#2344): the second
/// run's turns are appended (not replacing the first run's), and usage/cost
/// are added onto the running total — `session.get_transcript` must reflect
/// the FULL cumulative history, not just the last run.
#[tokio::test]
async fn set_run_outcome_accumulates_across_two_calls() {
    let registry = SessionRegistry::new();
    let session = registry.create("t".to_string(), None, None);

    let run_one_turn = crate::run_task::TurnRecord {
        role: "pm".to_string(),
        model: "openai/gpt-4o-mini".to_string(),
        text: "run one".to_string(),
        tool_calls: vec![],
        ran_test_command: false,
        usage: crate::perf::TokenUsage::new(10, 5, 0, 0),
    };
    registry.set_run_outcome(
        &session.id,
        vec![run_one_turn.clone()],
        crate::perf::TokenUsage::new(10, 5, 0, 0),
        Some(0.01),
    );

    let run_two_turn = crate::run_task::TurnRecord {
        role: "pm".to_string(),
        model: "openai/gpt-4o-mini".to_string(),
        text: "run two".to_string(),
        tool_calls: vec![],
        ran_test_command: false,
        usage: crate::perf::TokenUsage::new(20, 8, 0, 0),
    };
    registry.set_run_outcome(
        &session.id,
        vec![run_two_turn.clone()],
        crate::perf::TokenUsage::new(20, 8, 0, 0),
        Some(0.02),
    );

    let stored = registry.get_transcript(&session.id).unwrap();
    assert_eq!(
        stored.turns,
        vec![run_one_turn, run_two_turn],
        "both runs' turns must be present, in order, not just the last run's"
    );
    assert_eq!(
        stored.usage,
        crate::perf::TokenUsage::new(30, 13, 0, 0),
        "usage must be the SUM of both runs, not the last run's alone"
    );
    assert_eq!(
        stored.cost_usd,
        Some(0.03),
        "cost must be the SUM of both runs' cost"
    );
}

/// `get_transcript` on a session that has never run a task must return an
/// empty, valid `TranscriptRecord` — not an error (#2058).
#[tokio::test]
async fn get_transcript_on_never_run_session_is_empty() {
    let registry = SessionRegistry::new();
    let session = registry.create("t".to_string(), None, None);

    let transcript = registry.get_transcript(&session.id).unwrap();
    assert_eq!(transcript.session_id, session.id);
    assert!(transcript.turns.is_empty());
    assert_eq!(transcript.usage, crate::perf::TokenUsage::default());
    assert_eq!(transcript.cost_usd, None);
    assert_eq!(transcript.mode, None);
}

/// `get_transcript` on an unknown session must error `session_not_found`
/// (#2058).
#[tokio::test]
async fn get_transcript_unknown_session_errors() {
    let registry = SessionRegistry::new();
    let err = registry.get_transcript("nope").unwrap_err();
    assert_eq!(err.code, -32007);
}

/// `get_transcript` surfaces `pm_transcript`'s own cumulative
/// `compaction_events` counter (#2349) — proving the one-line wiring in
/// `Self::get_transcript` actually reads the stored transcript rather than
/// always defaulting to `0`.
///
/// Why: `Transcript::record_threshold_compaction` is only ever called in
/// production from `agent_loop::AgentLoop::maybe_compact_transcript`
/// (exercised end-to-end by `agent_loop::tests::forced_degradation_*`); this
/// test isolates the SEPARATE registry-level contract — that whatever count
/// `pm_transcript` carries flows through `get_transcript` unchanged.
/// What: Seeds a `pm_transcript` via `begin_pm_transcript`, increments its
/// counter directly (the `pub(crate)` visibility this ticket adds exists
/// exactly for this), stores it back via `store_pm_transcript`, then asserts
/// `get_transcript(id).compaction_events` reflects it.
/// Test: this test.
#[tokio::test]
async fn get_transcript_reports_compaction_events() {
    let registry = SessionRegistry::new();
    let session = registry.create("t".to_string(), None, None);

    let mut transcript = registry
        .begin_pm_transcript(&session.id, "you are the pm", "first task")
        .unwrap();
    transcript.record_threshold_compaction();
    transcript.record_threshold_compaction();
    registry.store_pm_transcript(&session.id, transcript);

    let stored = registry.get_transcript(&session.id).unwrap();
    assert_eq!(stored.compaction_events, 2);
}

/// `set_mode` must store the mode on the session, queryable both via
/// `status`/`list` (`Session.mode`) and `get_transcript`
/// (`TranscriptRecord.mode`, the SAME field) (#2059).
#[tokio::test]
async fn set_mode_stores_on_session() {
    let registry = SessionRegistry::new();
    let session = registry.create("t".to_string(), None, None);
    assert_eq!(session.mode, None, "a fresh session has no mode yet");

    registry
        .set_mode(&session.id, crate::mode::HarnessMode::Parity)
        .unwrap();

    let status = registry.status(&session.id).unwrap();
    assert_eq!(status.mode, Some(crate::mode::HarnessMode::Parity));

    let transcript = registry.get_transcript(&session.id).unwrap();
    assert_eq!(transcript.mode, Some(crate::mode::HarnessMode::Parity));
}

/// `set_mode` on an unknown session must error `session_not_found` (#2059).
#[tokio::test]
async fn set_mode_unknown_session_errors() {
    let registry = SessionRegistry::new();
    let err = registry
        .set_mode("nope", crate::mode::HarnessMode::DailyDriver)
        .unwrap_err();
    assert_eq!(err.code, -32007);
}

/// `shutdown_executions` must flip every tracked execution's cancel flag and
/// await its handle within the grace period.
#[tokio::test]
async fn shutdown_executions_awaits_cancelled_tasks() {
    let registry = SessionRegistry::new();
    let session = registry.create("t".to_string(), None, None);
    let cancel = registry.begin_execution(&session.id).unwrap();

    let done = Arc::new(std::sync::atomic::AtomicBool::new(false));
    let done_clone = done.clone();
    let handle = tokio::spawn(async move {
        // A well-behaved execution loop: poll the flag, exit promptly once set.
        while !cancel.load(std::sync::atomic::Ordering::Relaxed) {
            tokio::time::sleep(Duration::from_millis(5)).await;
        }
        done_clone.store(true, std::sync::atomic::Ordering::Relaxed);
    });
    registry.attach_execution_handle(&session.id, handle);

    registry.shutdown_executions(Duration::from_secs(2)).await;
    assert!(
        done.load(std::sync::atomic::Ordering::Relaxed),
        "the task must have observed cancellation and finished"
    );
}

/// `finish` must transition the session and publish `SessionDone` with the
/// given status.
#[tokio::test]
async fn finish_transitions_and_publishes_session_done() {
    let registry = SessionRegistry::new();
    let session = registry.create("t".to_string(), None, None);
    let mut events = crate::events::subscribe();

    let finished = registry
        .finish(&session.id, SessionStatus::Finished)
        .unwrap();
    assert_eq!(finished.status, SessionStatus::Finished);

    // `finish` publishes `SessionStatusChanged` (via `transition`) THEN
    // `SessionDone` — consume the former before asserting on the latter.
    let status_changed = next_event_for(&mut events, &session.id).await;
    assert!(
        matches!(status_changed.event, Event::SessionStatusChanged { status, .. } if status == "finished")
    );

    let done = next_event_for(&mut events, &session.id).await;
    assert!(matches!(done.event, Event::SessionDone { status, .. } if status == "finished"));
    assert!(done.seq > status_changed.seq);
}

/// `finish` on an already-terminal session must be a no-op, not a double
/// transition.
#[tokio::test]
async fn finish_is_idempotent_on_terminal_session() {
    let registry = SessionRegistry::new();
    let session = registry.create("t".to_string(), None, None);
    registry
        .finish(&session.id, SessionStatus::Finished)
        .unwrap();

    let again = registry.finish(&session.id, SessionStatus::Failed).unwrap();
    assert_eq!(
        again.status,
        SessionStatus::Finished,
        "must not overwrite an existing terminal status"
    );
}

/// `finish` on an unknown session must error.
#[tokio::test]
async fn finish_unknown_session_errors() {
    let registry = SessionRegistry::new();
    let err = registry
        .finish("nope", SessionStatus::Finished)
        .unwrap_err();
    assert_eq!(err.code, -32007);
}

// ── #2350: operator-facing goal slots ───────────────────────────────────────

/// Seed `id`'s `pm_transcript` the same way a real `task.run` would (via
/// `begin_pm_transcript` + `store_pm_transcript`), without needing a real
/// agent-loop execution — the shared setup every goal test in this section
/// needs to get past the "no transcript yet" guard.
fn seed_pm_transcript(registry: &SessionRegistry, id: &str) {
    let transcript = registry
        .begin_pm_transcript(id, "you are the pm", "first task")
        .unwrap();
    registry.store_pm_transcript(id, transcript);
}

/// `set_goal` on a session with a seeded transcript writes with
/// `GoalSource::Operator`, visible via both `get_goals` and
/// `get_transcript`.
#[tokio::test]
async fn set_goal_writes_operator_source() {
    let registry = SessionRegistry::new();
    let session = registry.create("t".to_string(), None, None);
    seed_pm_transcript(&registry, &session.id);

    registry.set_goal(&session.id, 2, "ship it").unwrap();

    let goals = registry.get_goals(&session.id).unwrap();
    assert_eq!(goals.len(), 1);
    assert_eq!(goals[0].slot, 2);
    assert_eq!(goals[0].text, "ship it");
    assert_eq!(goals[0].source, crate::agent_loop::GoalSource::Operator);
}

/// `set_goal` on a session that has never run a task (no `pm_transcript`
/// yet) must return the documented `invalid_argument` "no transcript yet"
/// error rather than panicking or silently no-op-ing.
#[tokio::test]
async fn set_goal_no_transcript_yet_errors() {
    let registry = SessionRegistry::new();
    let session = registry.create("t".to_string(), None, None);

    let err = registry.set_goal(&session.id, 1, "x").unwrap_err();
    assert_eq!(err.code, -32003);
    assert!(err.message.contains("no transcript yet"));
}

/// `set_goal` with slot `0` or past `GOAL_SLOT_COUNT` must map to a clean
/// `invalid_argument` error, not a panic.
#[tokio::test]
async fn set_goal_out_of_range_slot_errors() {
    let registry = SessionRegistry::new();
    let session = registry.create("t".to_string(), None, None);
    seed_pm_transcript(&registry, &session.id);

    assert_eq!(
        registry.set_goal(&session.id, 0, "x").unwrap_err().code,
        -32003
    );
    assert_eq!(
        registry.set_goal(&session.id, 6, "x").unwrap_err().code,
        -32003
    );
}

/// `set_goal` on an unknown session must map to `session_not_found`.
#[tokio::test]
async fn set_goal_unknown_session_errors() {
    let registry = SessionRegistry::new();
    assert_eq!(registry.set_goal("nope", 1, "x").unwrap_err().code, -32007);
}

/// `clear_goal` empties a previously-set slot.
#[tokio::test]
async fn clear_goal_clears_slot() {
    let registry = SessionRegistry::new();
    let session = registry.create("t".to_string(), None, None);
    seed_pm_transcript(&registry, &session.id);
    registry.set_goal(&session.id, 3, "temp").unwrap();

    registry.clear_goal(&session.id, 3).unwrap();

    assert!(registry.get_goals(&session.id).unwrap().is_empty());
}

/// `clear_goal` on a session with no transcript yet must error the same way
/// `set_goal` does.
#[tokio::test]
async fn clear_goal_no_transcript_yet_errors() {
    let registry = SessionRegistry::new();
    let session = registry.create("t".to_string(), None, None);

    let err = registry.clear_goal(&session.id, 1).unwrap_err();
    assert_eq!(err.code, -32003);
}

/// `clear_goal` with an out-of-range slot must map to a clean
/// `invalid_argument` error.
#[tokio::test]
async fn clear_goal_out_of_range_slot_errors() {
    let registry = SessionRegistry::new();
    let session = registry.create("t".to_string(), None, None);
    seed_pm_transcript(&registry, &session.id);

    assert_eq!(
        registry.clear_goal(&session.id, 0).unwrap_err().code,
        -32003
    );
}

/// `get_goals` reports BOTH an operator-written slot (via `set_goal`) and a
/// model-written slot (simulating what the `set_goal` tool writes directly
/// onto the same shared `GoalSlots` handle) — and that a later operator
/// write to the SAME slot the model wrote wins (last-write-wins).
#[tokio::test]
async fn get_goals_returns_operator_and_model_sources() {
    let registry = SessionRegistry::new();
    let session = registry.create("t".to_string(), None, None);
    seed_pm_transcript(&registry, &session.id);

    registry.set_goal(&session.id, 2, "operator goal").unwrap();

    // Simulate the model's own `set_goal` tool writing slot 1 directly onto
    // the same shared handle `tools::goals::SetGoalTool` would hold.
    {
        let sessions = registry.lock();
        let handle = sessions
            .get(&session.id)
            .unwrap()
            .pm_transcript
            .as_ref()
            .unwrap()
            .goals_handle();
        handle
            .lock()
            .unwrap()
            .set(1, "model goal", crate::agent_loop::GoalSource::Model)
            .unwrap();
    }

    let goals = registry.get_goals(&session.id).unwrap();
    assert_eq!(goals.len(), 2);
    let slot1 = goals.iter().find(|g| g.slot == 1).expect("slot 1 present");
    assert_eq!(slot1.source, crate::agent_loop::GoalSource::Model);
    let slot2 = goals.iter().find(|g| g.slot == 2).expect("slot 2 present");
    assert_eq!(slot2.source, crate::agent_loop::GoalSource::Operator);

    // Last-write-wins: an operator write to the model's slot replaces it.
    registry
        .set_goal(&session.id, 1, "operator overwrites model")
        .unwrap();
    let goals = registry.get_goals(&session.id).unwrap();
    let slot1 = goals.iter().find(|g| g.slot == 1).expect("slot 1 present");
    assert_eq!(slot1.text, "operator overwrites model");
    assert_eq!(slot1.source, crate::agent_loop::GoalSource::Operator);
}

/// `get_goals` on a session that has never run a task returns `[]`, not an
/// error — mirrors `get_transcript`'s never-run convention.
#[tokio::test]
async fn get_goals_on_never_run_session_is_empty() {
    let registry = SessionRegistry::new();
    let session = registry.create("t".to_string(), None, None);

    assert!(registry.get_goals(&session.id).unwrap().is_empty());
}

/// `get_goals` on an unknown session must map to `session_not_found`.
#[tokio::test]
async fn get_goals_unknown_session_errors() {
    let registry = SessionRegistry::new();
    assert_eq!(registry.get_goals("nope").unwrap_err().code, -32007);
}

/// `session.get_transcript` round-trips goal state (#2350 acceptance
/// criterion): a goal set via `set_goal` is visible on `TranscriptRecord.goals`
/// with the same slot/text/source it was written with.
#[tokio::test]
async fn get_transcript_round_trips_goal_state() {
    let registry = SessionRegistry::new();
    let session = registry.create("t".to_string(), None, None);
    seed_pm_transcript(&registry, &session.id);
    registry
        .set_goal(&session.id, 4, "finish the migration")
        .unwrap();

    let record = registry.get_transcript(&session.id).unwrap();
    assert_eq!(record.goals.len(), 1);
    assert_eq!(record.goals[0].slot, 4);
    assert_eq!(record.goals[0].text, "finish the migration");
    assert_eq!(
        record.goals[0].source,
        crate::agent_loop::GoalSource::Operator
    );

    // Round-trip through JSON, exactly as a real client would.
    let value = serde_json::to_value(&record).unwrap();
    let back: TranscriptRecord = serde_json::from_value(value).unwrap();
    assert_eq!(back.goals.len(), 1);
    assert_eq!(back.goals[0].text, "finish the migration");
}

/// `session.get_transcript` on a never-run session has an empty `goals`
/// array, matching the empty `turns`/`usage`/`cost_usd` convention.
#[tokio::test]
async fn get_transcript_goals_empty_on_never_run_session() {
    let registry = SessionRegistry::new();
    let session = registry.create("t".to_string(), None, None);

    let record = registry.get_transcript(&session.id).unwrap();
    assert!(record.goals.is_empty());
}