lean-ctx-cloud 3.12.10

The LeanCTX connector: enrollment, bus, knowledge sync, tasks and policy on top of LeanCTX | OSS.
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
// SPDX-License-Identifier: Apache-2.0
//! Worker identity against C0 2.0 `vectors/worker_id.vectors.json` and
//! `vectors/signing.vectors.json` (test-only keys).

use super::attach::{WORKER_CAP, attach_in, detect_host_app, host_display};

/// Task #21: a role is made per app session, stays a valid normalised role
/// (so Cloud recomputes the same `wkr_` id from it) and is stable.
#[test]
fn a_session_role_is_per_session_stable_and_a_valid_role() {
    use super::{normalize_role, session_role};
    assert_eq!(session_role("Coder", None), "coder");
    assert_eq!(
        session_role("coder", Some("  ")),
        "coder",
        "blank: no session"
    );
    let a = session_role("coder", Some("sess-a"));
    assert_eq!(a, session_role("coder", Some("sess-a")), "stable");
    assert_ne!(a, session_role("coder", Some("sess-b")), "per session");
    assert_ne!(a, session_role("reviewer", Some("sess-a")), "per role");
    assert!(
        a.starts_with("coder-s") && a.len() == "coder-s".len() + 8,
        "{a}"
    );
    let long = session_role("a-very-long-role-name-that-goes-past-32", Some("sess-a"));
    assert!(long.len() <= 32, "{long}");
    let cut_on_dash = session_role("abcdefghijklmnopqrstu-wxyz", Some("sess-a"));
    assert!(!cut_on_dash.contains("--"), "{cut_on_dash}");
    for role in [a, long, cut_on_dash, session_role("", Some("x"))] {
        assert_eq!(normalize_role(&role), role, "already normalised");
    }
    let instance = "0a80ace1-52f1-49c2-85f7-6991bada0099";
    assert_ne!(
        workspace_worker_id(instance, "claude-code", &session_role("coder", Some("w"))),
        workspace_worker_id(instance, "claude-code", &session_role("coder", Some("r"))),
    );
}

/// Dogfood finding 25.10.: a 1.x enrolment stores `inst_<32 hex>`, the
/// server hashes the dashed UUID; both spellings give the server's id.
#[test]
fn the_worker_id_hashes_the_canonical_instance_id() {
    let uuid = "0a80ace1-52f1-49c2-85f7-6991bada0099";
    for spelling in [
        "inst_0a80ace152f149c285f76991bada0099",
        "0A80ACE1-52F1-49C2-85F7-6991BADA0099",
        "0a80ace152f149c285f76991bada0099",
        uuid,
    ] {
        assert_eq!(canonical_instance_id(spelling), uuid, "{spelling}");
        assert_eq!(
            workspace_worker_id(spelling, "codex", "backend"),
            workspace_worker_id(uuid, "codex", "backend")
        );
    }
    let expected = {
        let digest = blake3::hash(format!("{uuid}|codex|backend").as_bytes());
        format!("wkr_{}", &base32_lower(digest.as_bytes())[..20])
    };
    assert_eq!(
        workspace_worker_id("inst_0a80ace152f149c285f76991bada0099", "codex", "backend"),
        expected
    );
    // Anything that is not a UUID in some spelling stays as it is.
    assert_eq!(canonical_instance_id("inst_short"), "inst_short");
}

#[test]
fn a_book_from_the_inst_spelling_is_replaced() {
    let dir = tempfile::tempdir().unwrap();
    let store = CloudStore::at(dir.path().join("c"), dir.path().join("d"));
    let legacy = "inst_0a80ace152f149c285f76991bada0099";
    std::fs::create_dir_all(store.data_dir()).unwrap();
    let old_id = {
        let digest = blake3::hash(format!("{legacy}|codex|backend").as_bytes());
        format!("wkr_{}", &base32_lower(digest.as_bytes())[..20])
    };
    std::fs::write(
        store.data_dir().join("workers.json"),
        serde_json::to_vec(&serde_json::json!({
            "schema": 1,
            "instance_id": legacy,
            "workers": [{"worker_id": old_id, "host_app": "codex", "role": "backend"}],
        }))
        .unwrap(),
    )
    .unwrap();
    let attached = super::attach::attach(&store, legacy, "codex", "backend").unwrap();
    assert_eq!(
        attached.worker.worker_id,
        workspace_worker_id(legacy, "codex", "backend")
    );
    assert_ne!(attached.worker.worker_id, old_id);
}
use super::card::{Availability, Budget, ModelSource, WorkerCard, self_reported_model};
use super::*;
use crate::CloudStore;

const SEED_A: [u8; 32] = [0x49; 32];
const SEED_B: [u8; 32] = [0x4a; 32];
const INSTANCE_A: &str = "6f2b9c4e-1a3d-4e5f-8a7b-0c1d2e3f4a5b";
const INSTANCE_B: &str = "8e3c0d5f-2b4e-4f60-9b8c-1d2e3f4a5b6c";
const OTHER_VAULT: &str = "vault:c5e8a1f3-2d7b-4e96-a4c0-7b1d9e3f6a03";
const VAULT: &str = "vault:3f1c2b6a-8d4e-4a7b-9c10-5e2f6a7b8c01";

fn keys(seed: [u8; 32]) -> InstanceKeys {
    InstanceKeys::from_seeds(seed, [0x01; 32])
}

#[test]
fn roles_normalise_like_the_contract() {
    for (input, output) in [
        ("backend", "backend"),
        ("Backend Dev", "backend-dev"),
        ("  QA / Review!!  ", "qa-review"),
        ("", "general"),
        ("---", "general"),
        ("Ünïcode Rôle", "n-code-r-le"),
        (
            "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
            "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
        ),
        (
            "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx-yz",
            "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
        ),
    ] {
        assert_eq!(normalize_role(input), output, "{input:?}");
    }
}

#[test]
fn workspace_ids_match_the_vectors() {
    for (instance, host, role, id) in [
        (
            INSTANCE_A,
            "claude-code",
            "backend",
            "wkr_vk4oelpv5lzjmev44hun",
        ),
        (INSTANCE_A, "codex", "backend", "wkr_kevgmpb7tmes3ii4aly6"),
        (
            INSTANCE_B,
            "claude-code",
            "backend",
            "wkr_jnt2cjplb6j4ugrq4pxw",
        ),
        (INSTANCE_B, "codex", "reviewer", "wkr_gawyravj36igdp3irdfo"),
    ] {
        assert_eq!(workspace_worker_id(instance, host, role), id);
    }
}

#[test]
fn alias_key_ids_and_hlc_nodes_match_the_vectors() {
    let vectors = signing_vectors();
    for (seed, name) in [(SEED_A, "instance_a"), (SEED_B, "instance_b")] {
        assert_eq!(
            hex::encode(WorkerAliasKey::from_seed(&seed).0.as_ref()),
            vectors["keys"][name]["worker_alias_key_hex"]
                .as_str()
                .unwrap(),
            "{name}"
        );
    }
    let seed_of = |instance: &str| {
        if instance == "instance_a" {
            SEED_A
        } else {
            SEED_B
        }
    };
    for worker in vectors["workers"].as_array().unwrap() {
        let Some(place) = worker["place"].as_str() else {
            continue;
        };
        let seed = seed_of(worker["instance"].as_str().unwrap());
        assert_eq!(
            WorkerAliasKey::from_seed(&seed).worker_id(
                worker["host_app"].as_str().unwrap(),
                worker["role"].as_str().unwrap(),
                place
            ),
            worker["worker_id"].as_str().unwrap()
        );
    }
    for alias in vectors["aliases"].as_array().unwrap() {
        let seed = seed_of(alias["instance"].as_str().unwrap());
        let place = alias["place"].as_str().unwrap();
        assert_eq!(
            alias_hlc_node(&keys(seed), place),
            alias["hlc_node"].as_str().unwrap()
        );
    }
}

#[test]
fn alias_signing_keys_match_the_vectors() {
    let vectors = signing_vectors();
    for alias in vectors["aliases"].as_array().unwrap() {
        let seed = if alias["instance"] == "instance_a" {
            SEED_A
        } else {
            SEED_B
        };
        let key = alias_signing_key(&keys(seed), alias["place"].as_str().unwrap());
        assert_eq!(
            hex::encode(key.to_bytes()),
            alias["seed_hex"].as_str().unwrap()
        );
        assert_eq!(key_id(&key), alias["key_id"].as_str().unwrap());
    }
    assert_eq!(
        key_id(keys(SEED_A).signing_key()),
        vectors["keys"]["instance_a"]["key_id"].as_str().unwrap()
    );
}

/// The contract's signing vectors (byte-identical mirror of the Cloud repo).
fn signing_vectors() -> serde_json::Value {
    let path = format!(
        "{}/crates/lean-ctx-protocol/tests/fixtures/cloud-v2/vectors/signing.vectors.json",
        concat!(env!("CARGO_MANIFEST_DIR"), "/../..")
    );
    serde_json::from_slice(&std::fs::read(&path).expect(&path)).expect(&path)
}

#[test]
fn one_engine_is_unlinkable_across_places_and_to_its_instance_id() {
    let a = WorkerAliasKey::from_seed(&SEED_A);
    let (in_other, in_vault) = (
        a.worker_id("codex", "general", OTHER_VAULT),
        a.worker_id("codex", "general", VAULT),
    );
    assert_ne!(in_other, in_vault);
    assert_ne!(a.hlc_node(OTHER_VAULT), a.hlc_node(VAULT));
    // A co-member knows the instance UUID, not the seed: nothing derived
    // from the UUID reproduces the alias or the node.
    let guess = workspace_worker_id(INSTANCE_A, "codex", "general");
    assert_ne!(guess, in_other);
    let unkeyed = blake3::hash(format!("codex|general|{OTHER_VAULT}").as_bytes());
    assert_ne!(worker_id_of(unkeyed.as_bytes()), in_other);
    assert_ne!(
        &blake3::hash(OTHER_VAULT.as_bytes()).to_hex()[..16],
        a.hlc_node(OTHER_VAULT)
    );
    let keyed_by_uuid = blake3::keyed_hash(
        blake3::hash(INSTANCE_A.as_bytes()).as_bytes(),
        OTHER_VAULT.as_bytes(),
    );
    assert_ne!(&keyed_by_uuid.to_hex()[..16], a.hlc_node(OTHER_VAULT));
}

#[test]
fn names_follow_the_contract_rule_in_its_order() {
    use NameRefusal::*;
    for (input, result) in [
        ("yves-mac · Claude Code · backend", None),
        ("Codex · general", None),
        ("Пётр · reviewer", Some(Confusable)),
        ("Pаypal bot", Some(Confusable)),
        ("аdmin", Some(Confusable)),
        ("my cloud helper", Some(Reserved)),
        ("LeanCTX bot", Some(Reserved)),
        ("", Some(Length)),
        (
            "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
            Some(Length),
        ),
        ("emoji 😀 bot", Some(Charset)),
        ("fullwidth ok", None),
        ("日本 bot", Some(Confusable)),
    ] {
        assert_eq!(check_name(input).err(), result, "{input:?}");
    }
    assert_eq!(check_name("fullwidth ok").unwrap(), "fullwidth ok");
}

#[test]
fn default_names_pass_the_rule() {
    assert_eq!(
        default_name("yves-mac", Some("Claude Code"), "backend"),
        "yves-mac · Claude Code · backend"
    );
    assert_eq!(
        default_name("", Some("Codex"), "general"),
        "Codex · general"
    );
    // A label that cannot pass (mixed alphabets, reserved word) is left out.
    assert_eq!(
        default_name("Пётр-mac", Some("Codex"), "general"),
        "Codex · general"
    );
    assert_eq!(
        default_name("cloud-box", Some("Codex"), "general"),
        "Codex · general"
    );
    assert_eq!(
        default_name("my 😀 mac", Some("Codex"), "general"),
        "my mac · Codex · general"
    );
}

/// rc4-39: Cloud showed "unknown on MacBook Airles a". A character outside
/// the name rule glued two words together, and an app the engine could not
/// tell was named "unknown".
#[test]
fn default_names_keep_the_computer_readable_and_never_say_unknown() {
    // Dropped characters separate words instead of gluing them.
    assert_eq!(
        default_name("MacBook Air\u{2014}les a", Some("Codex"), "general"),
        "MacBook Air les a · Codex · general"
    );
    assert_eq!(
        default_name("MacBook Air\nles a", Some("Codex"), "general"),
        "MacBook Air les a · Codex · general"
    );
    assert_eq!(
        default_name("MacBook Air (Studio)", Some("Codex"), "general"),
        "MacBook Air Studio · Codex · general"
    );
    // An apostrophe goes, as in the host name macOS derives itself.
    assert_eq!(
        default_name("Ada\u{2019}s MacBook Air", Some("Claude Code"), "backend"),
        "Adas MacBook Air · Claude Code · backend"
    );
    // A network host name loses its domain; a name someone chose stays whole.
    assert_eq!(
        default_name("Adas-MacBook-Air.local", Some("Cursor"), "review"),
        "Adas-MacBook-Air · Cursor · review"
    );
    assert_eq!(
        default_name("Studio Mac 2", Some("Cursor"), "review"),
        "Studio Mac 2 · Cursor · review"
    );
    // No app known: the name leaves it out rather than say "unknown".
    assert_eq!(
        default_name("MacBook Air", None, "backend"),
        "MacBook Air · backend"
    );
    assert_eq!(default_name("", None, "backend"), "backend");
    assert_eq!(
        default_name("MacBook Air", Some("  "), "backend"),
        "MacBook Air · backend"
    );
}

#[test]
fn unknown_host_apps_have_no_display_name() {
    use super::attach::named_host_display;
    assert_eq!(named_host_display("mcp-client:unknown"), None);
    assert_eq!(named_host_display("unknown"), None);
    assert_eq!(named_host_display(""), None);
    assert_eq!(named_host_display("mcp-client:"), None);
    assert_eq!(
        named_host_display("claude-code").as_deref(),
        Some("Claude Code")
    );
    assert_eq!(named_host_display("mcp-client:Zed").as_deref(), Some("Zed"));
}

#[test]
fn a_per_session_role_is_named_without_its_session_tag() {
    use super::{display_role, session_role, worker_default_name};
    let role = session_role("backend", Some("app-session-1"));
    assert_ne!(role, "backend");
    assert_eq!(display_role(&role, true), "backend");
    // Only a worker marked per session loses a tag-like tail.
    assert_eq!(display_role("dev-storybook", false), "dev-storybook");
    assert_eq!(display_role(&role, false), role);
    // Not a tag: wrong length or outside base32.
    assert_eq!(display_role("dev-sbook", true), "dev-sbook");
    assert_eq!(display_role("dev-s01234567", true), "dev-s01234567");

    let mut worker = attach_in(&mut Vec::new(), "inst", "mcp-client:unknown", &role).worker;
    worker.per_session = true;
    assert_eq!(
        worker_default_name("MacBook Air", &worker, &[], &Default::default()),
        "MacBook Air · backend"
    );
    worker.host_app = "claude-code".into();
    assert_eq!(
        worker_default_name(
            "Ada\u{2019}s MacBook Air",
            &worker,
            &[],
            &Default::default()
        ),
        "Adas MacBook Air · Claude Code · backend"
    );
}

/// rc4-39 review: two sessions of one role on one instance read apart by
/// an ordinal; a role on its own never gets one.
#[test]
fn sibling_sessions_of_one_role_get_distinct_names() {
    use super::{session_role, worker_default_name};
    let mut book = Vec::new();
    for session in ["app-session-1", "app-session-2", "app-session-3"] {
        let role = session_role("backend", Some(session));
        attach_in(&mut book, "inst", "claude-code", &role);
    }
    attach_in(&mut book, "inst", "claude-code", "review");
    attach_in(&mut book, "inst", "codex", "backend");
    for w in &mut book {
        w.per_session = w.role.starts_with("backend-s");
    }
    let names: Vec<String> = book
        .iter()
        .map(|w| worker_default_name("Studio", w, &book, &live_keys(&book)))
        .collect();
    assert_eq!(
        names,
        [
            "Studio · Claude Code · backend",
            "Studio · Claude Code · backend 2",
            "Studio · Claude Code · backend 3",
            "Studio · Claude Code · review",
            "Studio · Codex · backend",
        ]
    );

    // A name Cloud already accepted is taken: the first unnamed sibling
    // steps around it, and names never repeat.
    book[1].name = Some("Studio · Claude Code · backend".into());
    assert_eq!(
        worker_default_name("Studio", &book[0], &book, &live_keys(&book)),
        "Studio · Claude Code · backend 2"
    );
    assert_eq!(
        worker_default_name("Studio", &book[2], &book, &live_keys(&book)),
        "Studio · Claude Code · backend 3"
    );
    // A worker not (yet) in the book is named after every one there.
    let mut fresh = attach_in(
        &mut Vec::new(),
        "inst",
        "claude-code",
        &session_role("backend", Some("app-session-4")),
    )
    .worker;
    fresh.per_session = true;
    assert_eq!(
        worker_default_name("Studio", &fresh, &book, &live_keys(&book)),
        "Studio · Claude Code · backend 4"
    );
}

/// Every worker in `book` held by an active session.
fn live_keys(book: &[super::attach::LocalWorker]) -> std::collections::BTreeSet<(String, String)> {
    book.iter()
        .map(|w| (w.host_app.clone(), w.role.clone()))
        .collect()
}

/// bd 5!678: an ended or crashed sibling holds no ordinal, so the only
/// live session of a role is plain `backend`, and live ones still count.
#[test]
fn a_dead_sibling_gives_no_suffix() {
    use super::{session_role, worker_default_name};
    let mut book = Vec::new();
    for session in ["app-session-1", "app-session-2", "app-session-3"] {
        let role = session_role("backend", Some(session));
        attach_in(&mut book, "inst", "claude-code", &role);
    }
    for w in &mut book {
        w.per_session = true;
    }
    // Sessions 1 and 2 ended; session 3 is the only live one.
    let only = live_keys(&book[2..]);
    assert_eq!(
        worker_default_name("Studio", &book[2], &book, &only),
        "Studio · Claude Code · backend"
    );
    // A dead sibling's stored name is free again.
    book[0].name = Some("Studio · Claude Code · backend".into());
    assert_eq!(
        worker_default_name("Studio", &book[2], &book, &only),
        "Studio · Claude Code · backend"
    );
    // Session 1 and 3 live: 3 comes second.
    book[0].name = None;
    let two = live_keys(&[book[0].clone(), book[2].clone()]);
    assert_eq!(
        worker_default_name("Studio", &book[2], &book, &two),
        "Studio · Claude Code · backend 2"
    );
}

/// rc4-39 review: a worker from before the readable label, re-attached by
/// a new session, keeps its id and is named by the new rule.
#[test]
fn a_reattached_worker_keeps_its_id_and_gets_the_new_label() {
    use super::worker_default_name;
    let mut book = vec![attach_in(&mut Vec::new(), "inst", "mcp-client:unknown", "backend").worker];
    let before = book[0].worker_id.clone();
    let again = attach_in(&mut book, "inst", "mcp-client:unknown", "backend");
    assert!(!again.cap_reached);
    assert_eq!(again.worker.worker_id, before);
    assert_eq!(book.len(), 1);
    assert_eq!(
        worker_default_name(
            "MacBook Air\u{2014}les a",
            &again.worker,
            &book,
            &live_keys(&book)
        ),
        "MacBook Air les a · backend"
    );
}

/// rc4-39 review: a subagent of an app outside the host table (Zed)
/// attaches under its parent's app, not `mcp-client:unknown`.
#[test]
fn a_subagent_runs_under_its_parents_app() {
    let zed = lean_ctx::core::agents::TransportClient {
        host: "unknown".into(),
        name: Some("Zed".into()),
        version: None,
    };
    let mut parent = session("mcp-4201-p", "mcp", Some("lead"), 4201);
    parent.transport = Some(zed.clone());
    let mut child = session("subagent-4201-c", "subagent", Some("lead"), 4201);
    child.parent = Some(parent.agent_id.clone());
    child.parent_client = Some(zed);
    let (parent_host, _) = attach::agent_worker_key(&parent);
    assert_eq!(parent_host, "mcp-client:Zed");
    assert_eq!(
        attach::agent_worker_key(&child),
        attach::agent_worker_key(&parent)
    );

    // A known app the parent's handshake named carries over the same way.
    let claude = lean_ctx::core::agents::TransportClient {
        host: "claude-code".into(),
        name: Some("claude-ai".into()),
        version: None,
    };
    parent.transport = Some(claude.clone());
    child.parent_client = Some(claude);
    assert_eq!(attach::agent_worker_key(&child).0, "claude-code");
    // Without the parent's client the subagent cannot be told.
    child.parent_client = None;
    assert_eq!(attach::agent_worker_key(&child).0, "mcp-client:unknown");
}

#[test]
fn six_host_apps_are_detected() {
    let none: [(&str, &str); 0] = [];
    let env = |pairs: &[(&'static str, &'static str)]| pairs.to_vec();
    assert_eq!(
        detect_host_app(None, None, env(&[("CLAUDECODE", "1")]), None),
        "claude-code"
    );
    assert_eq!(
        detect_host_app(None, None, env(&[("CODEX_THREAD_ID", "t")]), None),
        "codex"
    );
    assert_eq!(
        detect_host_app(None, None, env(&[("CURSOR_TRACE_ID", "x")]), None),
        "cursor"
    );
    assert_eq!(
        detect_host_app(None, None, env(&[("GEMINI_CLI", "1")]), None),
        "gemini-cli"
    );
    assert_eq!(
        detect_host_app(None, None, env(&[("COPILOT_AGENT", "1")]), None),
        "copilot"
    );
    assert_eq!(
        detect_host_app(None, None, env(&[("OPENCODE", "1")]), None),
        "opencode"
    );
    assert_eq!(
        detect_host_app(None, None, none, Some("cursor-agent")),
        "cursor"
    );
    // The handshake and the agent type outrank the environment.
    assert_eq!(
        detect_host_app(Some("codex"), None, env(&[("CLAUDECODE", "1")]), None),
        "codex"
    );
    assert_eq!(
        detect_host_app(Some("unknown"), Some("claude"), none, None),
        "claude-code"
    );
    assert_eq!(
        detect_host_app(None, None, none, Some("Zed Editor/1.0 ✓")),
        "mcp-client:Zed Editor1.0"
    );
    assert_eq!(
        detect_host_app(None, None, none, None),
        "mcp-client:unknown"
    );
    assert_eq!(host_display("claude-code"), "Claude Code");
    assert_eq!(host_display("mcp-client:Zed"), "Zed");
}

#[test]
fn the_thirty_third_role_maps_to_general() {
    let mut workers = Vec::new();
    let first = attach_in(&mut workers, INSTANCE_A, "codex", "General");
    assert_eq!(first.worker.role, "general");
    for n in 1..WORKER_CAP {
        let a = attach_in(&mut workers, INSTANCE_A, "codex", &format!("role-{n}"));
        assert!(!a.cap_reached);
    }
    assert_eq!(workers.len(), WORKER_CAP);
    let again = attach_in(&mut workers, INSTANCE_A, "codex", "role-7");
    assert_eq!(again.worker.role, "role-7");
    assert!(!again.cap_reached);
    let over = attach_in(&mut workers, INSTANCE_A, "codex", "one-too-many");
    assert!(over.cap_reached);
    assert_eq!(over.worker, first.worker);
    assert_eq!(workers.len(), WORKER_CAP);
}

/// Dogfood 03.11.: the owner's machine had 32 workers from roles of every
/// project, so a new `ops` session shared the `capture` worker and Cloud
/// refused its claim (presence with another role). A full book now gives
/// up the longest-unused worker without a session; a registered one is
/// queued for retirement on Cloud, and coming back un-queues it.
#[test]
fn a_full_book_gives_the_longest_unused_slot_to_a_new_role() {
    let _data = lean_ctx::core::data_dir::isolated_data_dir();
    let dir = tempfile::tempdir().unwrap();
    let store = CloudStore::at(dir.path().join("c"), dir.path().join("d"));
    for n in 0..WORKER_CAP {
        attach::attach(&store, INSTANCE_A, "claude-code", &format!("role-{n}")).unwrap();
    }
    // Registered, in order: role-0 is the oldest.
    attach::update_book(&store, INSTANCE_A, |workers| {
        for (n, w) in workers.iter_mut().enumerate() {
            w.registered_at = Some(1_000 + n as u64);
            w.last_attached = Some(1_000 + n as u64);
        }
    })
    .unwrap();
    let gone = workspace_worker_id(INSTANCE_A, "claude-code", "role-0");

    let ops = attach::attach(&store, INSTANCE_A, "claude-code", "ops").unwrap();
    assert_eq!(ops.worker.role, "ops");
    assert!(!ops.cap_reached, "the new role has its own worker");
    let book = attach::list(&store, INSTANCE_A).unwrap();
    assert_eq!(book.len(), WORKER_CAP);
    assert!(book.iter().all(|w| w.worker_id != gone), "role-0 gave way");
    assert_eq!(
        attach::retired(&store, INSTANCE_A).unwrap(),
        vec![gone.clone()]
    );

    // role-0 returns before Cloud retired it: it is no longer to be retired.
    let back = attach::attach(&store, INSTANCE_A, "claude-code", "role-0").unwrap();
    assert_eq!(back.worker.worker_id, gone, "the same deterministic id");
    let retired = attach::retired(&store, INSTANCE_A).unwrap();
    assert!(!retired.contains(&gone), "{retired:?}");
    assert_eq!(retired.len(), 1, "role-1 gave way for it");

    attach::retirement_done(&store, INSTANCE_A, &retired[0]).unwrap();
    assert!(attach::retired(&store, INSTANCE_A).unwrap().is_empty());
}

/// Workers a live session holds, and the connector's own (capture,
/// friction, CLI), never give way; when nothing can, the session shares
/// as before and `cap_reached` says so.
#[test]
fn workers_in_use_and_the_connectors_own_stay() {
    let mut workers = Vec::new();
    attach_in(&mut workers, INSTANCE_A, "lean-ctx", "capture");
    for n in 1..WORKER_CAP {
        attach_in(&mut workers, INSTANCE_A, "codex", &format!("role-{n}"));
    }
    for (n, w) in workers.iter_mut().enumerate() {
        w.registered_at = Some(n as u64);
        w.last_attached = Some(n as u64);
    }
    let mut retired = Vec::new();
    let mut in_use: std::collections::BTreeSet<(String, String)> = (1..WORKER_CAP)
        .filter(|n| *n != 5)
        .map(|n| ("codex".to_string(), format!("role-{n}")))
        .collect();
    assert!(attach::evict_one(&mut workers, &mut retired, &in_use));
    assert_eq!(
        retired,
        vec![workspace_worker_id(INSTANCE_A, "codex", "role-5")],
        "the oldest worker is capture, but only role-5 is free"
    );
    in_use.insert(("codex".to_string(), "role-5".to_string()));
    let before = workers.len();
    assert!(!attach::evict_one(&mut workers, &mut retired, &in_use));
    assert_eq!(workers.len(), before, "nothing free: nothing leaves");
    assert!(workers.iter().any(|w| w.role == "capture"));
}

#[test]
fn the_book_persists_and_resets_for_another_instance() {
    let dir = tempfile::tempdir().unwrap();
    let store = CloudStore::at(dir.path().join("c"), dir.path().join("d"));
    let a = attach::attach(&store, INSTANCE_A, "claude-code", "backend").unwrap();
    assert_eq!(a.worker.worker_id, "wkr_vk4oelpv5lzjmev44hun");
    attach::attach(&store, INSTANCE_A, "claude-code", "Backend").unwrap();
    assert_eq!(attach::list(&store, INSTANCE_A).unwrap().len(), 1);
    assert!(attach::list(&store, INSTANCE_B).unwrap().is_empty());
}

/// A session as the registry keeps it (one per process; distinct pids).
fn session(
    agent_id: &str,
    agent_type: &str,
    role: Option<&str>,
    pid: u32,
) -> lean_ctx::core::agents::AgentEntry {
    let now = lean_ctx_time::UtcDateTime::now();
    lean_ctx::core::agents::AgentEntry {
        agent_id: agent_id.into(),
        agent_type: agent_type.into(),
        role: role.map(str::to_string),
        project_root: "/tmp/p".into(),
        started_at: now,
        last_active: now,
        pid,
        process_identity: None,
        durable_identity_id: None,
        status: lean_ctx::core::agents::AgentStatus::Active,
        status_message: None,
        agent_status_message: None,
        transport: None,
        role_source: None,
        parent: None,
        parent_client: None,
        app_session_id: None,
        display_name: None,
    }
}

/// V5.3: `ctx_agent list` shows workers; process ids are not agents.
#[test]
fn the_roster_lists_workers_not_processes() {
    let sessions = [
        session("mcp-4101-a", "claude", Some("Backend"), 4101),
        session("mcp-4102-b", "claude", Some("backend"), 4102),
        session("mcp-4103-c", "codex", None, 4103),
    ];
    let agents: Vec<&lean_ctx::core::agents::AgentEntry> = sessions.iter().collect();
    let now = lean_ctx_time::UtcDateTime::now();
    let enrolled = roster::render(&agents, Some((INSTANCE_A, &[])), now);
    let expected = format!(
        "Active workers (2):\n  wkr_vk4oelpv5lzjmev44hun Claude Code · backend state=active (2 sessions, last active 0m ago)\n      session mcp-4101-a status=active\n      session mcp-4102-b status=active\n  {} Codex · general state=active (1 session, last active 0m ago)\n      session mcp-4103-c status=active\n",
        workspace_worker_id(INSTANCE_A, "codex", "general"),
    );
    assert_eq!(enrolled, expected);
    assert!(!enrolled.contains("pid"));
    let local = roster::render(&agents, None, now);
    assert!(local.starts_with("Active workers (2):\n  (not on the Cloud) Claude Code · backend"));
}

#[test]
fn cards_stay_within_the_contract_bounds() {
    let card = WorkerCard::new(
        "claude-code",
        Some(" claude-opus-5-5 "),
        ["ctx_shell", "ctx_read", "ctx_read", ""].map(String::from),
        Budget {
            tasks_per_day: Some(500),
            usd_cents_per_day: Some(90_000),
        },
        Availability::Online,
    );
    assert_eq!(card.model, "claude-opus-5-5");
    assert_eq!(card.model_source, ModelSource::SelfReported);
    assert_eq!(card.tools, ["ctx_read", "ctx_shell"]);
    assert_eq!(card.budget.tasks_per_day, Some(200));
    assert_eq!(card.budget.usd_cents_per_day, Some(50_000));
    let bare = WorkerCard::new(
        "codex",
        None,
        Vec::new(),
        Budget::default(),
        Availability::Idle,
    );
    assert_eq!(
        serde_json::to_value(&bare).unwrap(),
        serde_json::json!({"host_app": "codex", "model": "unknown", "model_source": "unknown",
            "tools": [], "budget": {}, "availability": "idle"})
    );
    assert_eq!(
        self_reported_model([("CODEX_MODEL", "gpt"), ("ANTHROPIC_MODEL", "opus")]),
        Some("opus".to_string())
    );
}

/// Review 5!246 #1: `cloud worker retire <wkr>` refuses a worker an active
/// session holds (Cloud would delete a worker that keeps posting), also when
/// the book does not have it; `--force` retires it anyway.
#[test]
fn retiring_a_worker_in_use_is_refused_unless_forced() {
    let _data = lean_ctx::core::data_dir::isolated_data_dir();
    let dir = tempfile::tempdir().unwrap();
    let store = CloudStore::at(dir.path().join("c"), dir.path().join("d"));
    let project = tempfile::tempdir().unwrap();
    let root = project.path().to_string_lossy().into_owned();
    let mut registry = lean_ctx::core::agents::AgentRegistry::new();
    let agent = registry
        .register("claude", Some("queen"), &root, None)
        .unwrap();
    registry.save().unwrap();
    let entry = registry
        .agents
        .iter()
        .find(|a| a.agent_id == agent)
        .unwrap();
    let (host, role) = attach::agent_worker_key(entry);
    let held = attach::attach(&store, INSTANCE_A, &host, &role)
        .unwrap()
        .worker;
    attach::update_book(&store, INSTANCE_A, |workers| {
        for w in workers.iter_mut() {
            w.registered_at = Some(1);
        }
    })
    .unwrap();
    let ids = vec![held.worker_id.clone()];

    let refused = attach::give_up(&store, INSTANCE_A, &ids, false).unwrap_err();
    assert!(refused.to_string().contains("in use"), "{refused}");
    assert_eq!(attach::list(&store, INSTANCE_A).unwrap().len(), 1);
    assert!(attach::retired(&store, INSTANCE_A).unwrap().is_empty());

    // Not in the book: the id is still the live session's worker.
    attach::update_book(&store, INSTANCE_A, Vec::clear).unwrap();
    assert!(attach::give_up(&store, INSTANCE_A, &ids, false).is_err());
    assert!(attach::retired(&store, INSTANCE_A).unwrap().is_empty());

    assert_eq!(
        attach::give_up(&store, INSTANCE_A, &ids, true).unwrap(),
        ids
    );
    assert_eq!(attach::retired(&store, INSTANCE_A).unwrap(), ids);
}

/// Review 5!246 #2: an agent registry that cannot be parsed is not "no
/// session": the idle sweeps and an explicit retirement give up nothing.
#[test]
fn sweeps_retire_nothing_when_the_agent_registry_is_unreadable() {
    let _data = lean_ctx::core::data_dir::isolated_data_dir();
    let dir = tempfile::tempdir().unwrap();
    let store = CloudStore::at(dir.path().join("c"), dir.path().join("d"));
    let id = attach::attach(&store, INSTANCE_A, "codex", "reviewer")
        .unwrap()
        .worker
        .worker_id;
    attach::update_book(&store, INSTANCE_A, |workers| {
        for w in workers.iter_mut() {
            w.registered_at = Some(1);
            w.last_attached = Some(1);
            w.per_session = true;
        }
    })
    .unwrap();
    let agents = lean_ctx::core::data_dir::lean_ctx_data_dir()
        .unwrap()
        .join("agents");
    std::fs::create_dir_all(&agents).unwrap();
    std::fs::write(agents.join("registry.json"), b"{ not json").unwrap();

    let idle = std::time::Duration::ZERO;
    assert!(attach::give_up_idle(&store, INSTANCE_A, idle, false).is_err());
    assert!(attach::give_up_idle(&store, INSTANCE_A, idle, true).is_err());
    assert!(attach::give_up(&store, INSTANCE_A, &[id], false).is_err());
    assert_eq!(attach::list(&store, INSTANCE_A).unwrap().len(), 1);
    assert!(attach::retired(&store, INSTANCE_A).unwrap().is_empty());
}

/// bd 5!678: a resumed session 1 whose stored `backend` was taken by
/// session 3 while it was gone yields and reads `backend 2`; session 3, the
/// later registration, keeps its name; a name the person chose stays.
#[test]
fn a_resumed_session_yields_a_name_a_live_sibling_took() {
    use super::{reattach_name, session_role};
    let mut book = Vec::new();
    for session in ["app-session-1", "app-session-3"] {
        let role = session_role("backend", Some(session));
        attach_in(&mut book, "inst", "claude-code", &role);
    }
    for w in &mut book {
        w.per_session = true;
        w.name = Some("Studio · Claude Code · backend".into());
    }
    book[0].registered_at = Some(1);
    book[1].registered_at = Some(2);
    let both = live_keys(&book);
    assert_eq!(
        reattach_name("Studio", &book[0], &book, &both).as_deref(),
        Some("Studio · Claude Code · backend 2")
    );
    assert_eq!(reattach_name("Studio", &book[1], &book, &both), None);
    // Session 3 ended: nothing to yield to.
    let only_one = live_keys(&book[..1]);
    assert_eq!(reattach_name("Studio", &book[0], &book, &only_one), None);
    // A name the person chose is never changed.
    book[0].name = Some("Ada's API".into());
    book[1].name = Some("Ada's API".into());
    assert_eq!(reattach_name("Studio", &book[0], &book, &both), None);
    // An unnamed worker gets its default over the live siblings.
    book[0].name = None;
    book[1].name = Some("Studio · Claude Code · backend".into());
    assert_eq!(
        reattach_name("Studio", &book[0], &book, &both).as_deref(),
        Some("Studio · Claude Code · backend 2")
    );
}

/// Registers live agents with role `backend` for each app session in the
/// isolated agent registry; their `(host_app, role)` keys.
fn live_backend_sessions(sessions: &[&str]) -> Vec<(String, String)> {
    let project = tempfile::tempdir().unwrap();
    let root = project.path().to_string_lossy().into_owned();
    let mut registry = lean_ctx::core::agents::AgentRegistry::new();
    // One process registers once: each session is a copy of that entry
    // under its own id and app session id.
    let id = registry
        .register("claude", Some("backend"), &root, None)
        .unwrap();
    let base = registry
        .agents
        .iter()
        .find(|a| a.agent_id == id)
        .unwrap()
        .clone();
    registry.agents.clear();
    let mut keys = Vec::new();
    for (n, session) in sessions.iter().enumerate() {
        let mut entry = base.clone();
        entry.agent_id = format!("{id}-{n}");
        entry.app_session_id = Some((*session).to_string());
        keys.push(attach::agent_worker_key(&entry));
        registry.agents.push(entry);
    }
    registry.save().unwrap();
    let active = lean_ctx::core::agents::AgentRegistry::load_checked().unwrap();
    assert_eq!(active.list_active(None).len(), sessions.len(), "all live");
    keys
}

/// bd 5!678 wiring: `ensure_registered` names a worker from the live agent
/// registry (`register::name_to_register`), so an ended sibling holds no
/// ordinal and a resumed one yields to the live holder of its name.
#[test]
fn registration_names_count_the_live_agent_registry() {
    let _data = lean_ctx::core::data_dir::isolated_data_dir();
    let dir = tempfile::tempdir().unwrap();
    let store = CloudStore::at(dir.path().join("c"), dir.path().join("d"));
    let keys = live_backend_sessions(&["app-session-3"]);
    let (host, _) = keys[0].clone();
    let mut workers = Vec::new();
    for session in ["app-session-1", "app-session-3"] {
        let role = session_role("backend", Some(session));
        workers.push(
            attach::attach(&store, INSTANCE_A, &host, &role)
                .unwrap()
                .worker,
        );
    }
    assert_eq!(workers[1].role, keys[0].1, "same key as the live agent");
    // Session 1 ended: session 3 is plain `backend`.
    let name = super::register::name_to_register(&store, INSTANCE_A, "Studio", &workers[1])
        .expect("an unnamed worker gets a name");
    assert!(name.ends_with("· backend"), "{name}");
    attach::update_book(&store, INSTANCE_A, |book| {
        for w in book.iter_mut() {
            w.per_session = true;
        }
        book[0].name = Some(name.clone());
        book[0].registered_at = Some(1);
        book[1].name = Some(name.clone());
        book[1].registered_at = Some(2);
    })
    .unwrap();
    // Session 1 resumes: both live, session 1 yields.
    live_backend_sessions(&["app-session-1", "app-session-3"]);
    let book = attach::list(&store, INSTANCE_A).unwrap();
    assert_eq!(
        super::register::name_to_register(&store, INSTANCE_A, "Studio", &book[0]),
        Some(format!("{name} 2"))
    );
    assert_eq!(
        super::register::name_to_register(&store, INSTANCE_A, "Studio", &book[1]),
        None
    );
}

/// bd 5!678 wiring: `cloud worker list` names unnamed workers over the
/// live agent registry; with it unreadable, it still lists (logged).
#[test]
fn worker_list_names_count_the_live_agent_registry() {
    let _data = lean_ctx::core::data_dir::isolated_data_dir();
    let dir = tempfile::tempdir().unwrap();
    let store = CloudStore::at(dir.path().join("c"), dir.path().join("d"));
    let keys = live_backend_sessions(&["app-session-3"]);
    let (host, _) = keys[0].clone();
    for session in ["app-session-1", "app-session-2", "app-session-3"] {
        let role = session_role("backend", Some(session));
        attach::attach(&store, INSTANCE_A, &host, &role).unwrap();
    }
    attach::update_book(&store, INSTANCE_A, |book| {
        for w in book.iter_mut() {
            w.per_session = true;
        }
    })
    .unwrap();
    let book = attach::list(&store, INSTANCE_A).unwrap();
    let names = shown_names("Studio", &book);
    assert!(names[2].ends_with("· backend"), "{names:?}");
    // Sessions 1 and 3 live: 3 comes second.
    live_backend_sessions(&["app-session-1", "app-session-3"]);
    let names = shown_names("Studio", &book);
    assert!(names[0].ends_with("· backend"), "{names:?}");
    assert!(names[2].ends_with("· backend 2"), "{names:?}");
    // An unreadable registry names as if no sibling were live.
    let agents = lean_ctx::core::data_dir::lean_ctx_data_dir()
        .unwrap()
        .join("agents");
    std::fs::write(agents.join("registry.json"), b"{ not json").unwrap();
    assert!(live_keys_for_names().is_empty());
    let names = shown_names("Studio", &book);
    assert!(names.iter().all(|n| n.ends_with("· backend")), "{names:?}");
}