relay-knowledge 1.1.17

Graph-database-based knowledge graph project.
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
use std::time::{SystemTime, UNIX_EPOCH};

use super::*;
use crate::{
    api::{InterfaceKind, RequestContext},
    domain::{KnowledgeMap, KnowledgeMapChange, KnowledgeMapSourceKind},
};
use tokio::time::Duration;

use super::super::{
    KnowledgeMapSourceAddRequest, cleanup_superseded_topic_shards,
    cleanup_superseded_topic_shards_in, parse_manifest,
};

#[tokio::test]
async fn legacy_map_migrates_to_visible_v4_and_legacy_recovery_stays_readable() {
    let root = temp_root("map-v3-migration");
    fs::create_dir_all(root.join(LEGACY_AGENT_CONTRACT_DIR_NAME))
        .await
        .expect("legacy directory should create");
    fs::write(
        root.join("AGENTS.md"),
        "CodeSpec map: codespec/codespec-map.yaml\nKnowledge map: knowledge/knowledge-map.yaml\n",
    )
    .await
    .expect("agents should write");
    let legacy = KnowledgeMap::initial("unix:1".to_owned());
    let legacy_yaml = serde_norway::to_string(&legacy).expect("legacy map should serialize");
    fs::write(root.join(LEGACY_KNOWLEDGE_MAP_RELATIVE_PATH), &legacy_yaml)
        .await
        .expect("legacy map should write");
    let service = KnowledgeMapService::new(root.clone());
    let context = RequestContext::for_interface(InterfaceKind::Cli);

    service
        .migrate_to_v4(&context)
        .await
        .expect("migration should work");
    let visible = fs::read_to_string(root.join(KNOWLEDGE_MAP_RELATIVE_PATH))
        .await
        .expect("visible root should exist");
    assert!(visible.contains("schema_version: 4"));
    assert!(
        fs::try_exists(service.backup_path()).await.unwrap(),
        "v3 publication should leave the ordinary reader fallback used by this regression"
    );
    let redirect = fs::read_to_string(root.join(LEGACY_KNOWLEDGE_MAP_RELATIVE_PATH))
        .await
        .expect("legacy redirect should exist");
    assert!(redirect.contains("artifact_kind: redirect"));

    service
        .rollback_v3(&context)
        .await
        .expect("rollback should work");
    assert!(
        !fs::try_exists(root.join(KNOWLEDGE_MAP_RELATIVE_PATH))
            .await
            .expect("visible root should be probed")
    );
    let restored = fs::read_to_string(root.join(LEGACY_KNOWLEDGE_MAP_RELATIVE_PATH))
        .await
        .expect("legacy root should restore");
    assert!(restored.contains("schema_version: 1"));
    assert_eq!(restored, legacy_yaml, "rollback must restore exact bytes");
    assert!(
        !fs::try_exists(service.backup_path()).await.unwrap(),
        "the ordinary visible backup must not shadow the restored legacy root"
    );
    assert!(
        fs::try_exists(service.retained_v3_backup_path())
            .await
            .unwrap(),
        "the ordinary backup should remain available outside the reader fallback"
    );
    assert_eq!(
        service
            .read_contract_dir_name()
            .await
            .expect("contract directory should resolve"),
        LEGACY_AGENT_CONTRACT_DIR_NAME
    );
    assert_eq!(
        service
            .read_root_content()
            .await
            .expect("active root should read"),
        legacy_yaml
    );

    let shown = service
        .show(&context, None)
        .await
        .expect("show should read the restored legacy root");
    assert_eq!(
        shown.map.artifact_schema_version,
        KnowledgeMap::SCHEMA_VERSION
    );
    assert_eq!(shown.map.updated_at, "unix:1");
    let routed = service
        .route(&context, "software-model".to_owned())
        .await
        .expect("route should read the restored legacy root");
    assert_eq!(
        routed
            .route
            .expect("legacy software route should resolve")
            .source_order,
        ["repository-software-model"]
    );
    assert_eq!(routed.sources.len(), 1);
    assert_eq!(routed.sources[0].id, "repository-software-model");

    let _ = fs::remove_dir_all(root).await;
}

#[tokio::test]
async fn legacy_map_without_current_reserved_routes_migrates_and_remains_rollbackable() {
    let root = temp_root("map-v3-legacy-without-builtins");
    fs::create_dir_all(root.join(LEGACY_AGENT_CONTRACT_DIR_NAME))
        .await
        .expect("legacy directory should create");
    let mut legacy = KnowledgeMap::initial("unix:1".to_owned());
    legacy.topics.clear();
    legacy.sources.clear();
    legacy.routes.clear();
    legacy
        .validate()
        .expect("legacy map without current reserved routes remains structurally valid");
    let legacy_yaml = serde_norway::to_string(&legacy).expect("legacy map should serialize");
    fs::write(root.join(LEGACY_KNOWLEDGE_MAP_RELATIVE_PATH), &legacy_yaml)
        .await
        .expect("legacy map should write");
    let service = KnowledgeMapService::new(root.clone());
    let context = RequestContext::for_interface(InterfaceKind::Cli);

    service
        .migrate_to_v4(&context)
        .await
        .expect("current migration should add reserved routes to the visible contract");
    service
        .validate_map_contract()
        .await
        .expect("visible contract should satisfy current reserved-route rules");
    assert_eq!(
        fs::read_to_string(service.legacy_backup_path())
            .await
            .expect("legacy backup should read"),
        legacy_yaml,
        "migration must retain the exact old recovery boundary"
    );

    service
        .rollback_v3(&context)
        .await
        .expect("legacy structural validation should permit rollback");
    assert_eq!(
        fs::read_to_string(service.legacy_map_path())
            .await
            .expect("rolled-back legacy root should read"),
        legacy_yaml
    );
    let _ = fs::remove_dir_all(root).await;
}

#[tokio::test]
async fn migration_repairs_legacy_reserved_sources_without_route_membership() {
    let root = temp_root("map-v3-legacy-repairs-reserved-routes");
    fs::create_dir_all(root.join(LEGACY_AGENT_CONTRACT_DIR_NAME))
        .await
        .expect("legacy directory should create");
    let mut legacy = KnowledgeMap::initial("unix:1".to_owned());
    for topic in ["software-model", "business-knowledge"] {
        legacy
            .routes
            .iter_mut()
            .find(|route| route.topic == topic)
            .expect("reserved route should exist")
            .source_order
            .clear();
    }
    let legacy_yaml =
        serde_norway::to_string(&legacy).expect("repairable legacy map should serialize");
    fs::write(root.join(LEGACY_KNOWLEDGE_MAP_RELATIVE_PATH), &legacy_yaml)
        .await
        .expect("repairable legacy map should write");
    let service = KnowledgeMapService::new(root.clone());
    let context = RequestContext::for_interface(InterfaceKind::Cli);

    service
        .migrate_to_v4(&context)
        .await
        .expect("migration should repair reserved route membership");
    service
        .validate_map_contract()
        .await
        .expect("published v3 map should satisfy reserved route validation");
    for (topic, source) in [
        ("software-model", "repository-software-model"),
        ("business-knowledge", "repository-business-glossary"),
    ] {
        let route = service
            .route(&context, topic.to_owned())
            .await
            .expect("migrated route should load")
            .route
            .expect("reserved route should remain visible");
        assert!(route.source_order.iter().any(|entry| entry == source));
    }
    service
        .rollback_v3(&context)
        .await
        .expect("repairable legacy sources should remain rollbackable");
    assert_eq!(
        fs::read_to_string(service.legacy_map_path())
            .await
            .expect("rolled-back legacy root should read"),
        legacy_yaml
    );
    let _ = fs::remove_dir_all(root).await;
}

#[tokio::test]
async fn migration_rejects_a_legacy_redirect_instead_of_copying_it_as_a_visible_root() {
    let root = temp_root("legacy-redirect-is-not-a-map");
    fs::create_dir_all(root.join(LEGACY_AGENT_CONTRACT_DIR_NAME))
        .await
        .expect("legacy directory should create");
    fs::write(
        root.join(LEGACY_KNOWLEDGE_MAP_RELATIVE_PATH),
        "schema_version: 4\nartifact_kind: redirect\nmap_type: knowledge\ntarget: knowledge/knowledge-map.yaml\n",
    )
    .await
    .expect("orphan redirect should seed");
    let service = KnowledgeMapService::new(root.clone());
    let context = RequestContext::for_interface(InterfaceKind::Cli);

    service
        .init(&context)
        .await
        .expect_err("an orphan redirect must not be copied as a visible map");

    assert!(!fs::try_exists(service.map_path()).await.unwrap());
    assert!(!fs::try_exists(service.legacy_backup_path()).await.unwrap());
    let _ = fs::remove_dir_all(root).await;
}

#[cfg(unix)]
#[tokio::test]
async fn migration_rejects_legacy_tree_directory_and_entry_symlinks() {
    use std::os::unix::fs::symlink;

    for symlink_directory in [true, false] {
        let label = if symlink_directory {
            "legacy-tree-directory-symlink"
        } else {
            "legacy-tree-entry-symlink"
        };
        let root = temp_root(label);
        let outside = temp_root(&format!("{label}-outside"));
        let legacy_dir = root.join(LEGACY_AGENT_CONTRACT_DIR_NAME);
        let legacy_topics = legacy_dir.join(KNOWLEDGE_MAP_TOPICS_DIR_NAME);
        fs::create_dir_all(&legacy_dir)
            .await
            .expect("legacy directory should create");
        fs::create_dir_all(&outside)
            .await
            .expect("outside directory should create");
        let outside_file = outside.join("outside.yaml");
        let outside_before = b"outside must not be copied through a symlink";
        fs::write(&outside_file, outside_before)
            .await
            .expect("outside file should write");
        if symlink_directory {
            symlink(&outside, &legacy_topics).expect("topic directory symlink should create");
        } else {
            fs::create_dir_all(&legacy_topics)
                .await
                .expect("legacy topics directory should create");
            symlink(&outside_file, legacy_topics.join("unreferenced.yaml"))
                .expect("topic entry symlink should create");
        }
        let legacy = KnowledgeMap::initial("unix:1".to_owned());
        fs::write(
            root.join(LEGACY_KNOWLEDGE_MAP_RELATIVE_PATH),
            serde_norway::to_string(&legacy).expect("legacy map should serialize"),
        )
        .await
        .expect("legacy root should write");
        let service = KnowledgeMapService::new(root.clone());
        let context = RequestContext::for_interface(InterfaceKind::Cli);

        let error = service
            .migrate_to_v4(&context)
            .await
            .expect_err("legacy tree symlinks must fail closed");

        assert!(matches!(error, KnowledgeMapServiceError::UnsafePath(_)));
        assert!(!fs::try_exists(service.map_path()).await.unwrap());
        assert_eq!(
            fs::read(&outside_file)
                .await
                .expect("outside file should remain readable"),
            outside_before
        );
        let _ = fs::remove_dir_all(root).await;
        let _ = fs::remove_dir_all(outside).await;
    }
}

#[cfg(unix)]
#[tokio::test]
async fn rollback_rejects_a_symlink_destination_before_moving_the_visible_root() {
    use std::os::unix::fs::symlink;

    let (root, service, context) = migrated_v2_fixture("rollback-symlink-destination").await;
    let outside = temp_root("rollback-symlink-outside");
    fs::create_dir_all(&outside)
        .await
        .expect("outside directory should create");
    let outside_file = outside.join("outside.yaml");
    let outside_before = b"outside must remain unchanged";
    fs::write(&outside_file, outside_before)
        .await
        .expect("outside file should write");
    fs::remove_file(service.legacy_map_path())
        .await
        .expect("legacy redirect should remove");
    symlink(&outside_file, service.legacy_map_path())
        .expect("legacy destination symlink should create");
    let visible_before = fs::read(service.map_path())
        .await
        .expect("visible root should read");

    let error = service
        .rollback_v3(&context)
        .await
        .expect_err("rollback destination symlink must fail closed");

    assert!(matches!(error, KnowledgeMapServiceError::UnsafePath(_)));
    assert_eq!(
        fs::read(service.map_path())
            .await
            .expect("visible root should remain"),
        visible_before
    );
    assert_eq!(
        fs::read(&outside_file)
            .await
            .expect("outside file should remain readable"),
        outside_before
    );
    assert!(!fs::try_exists(service.retained_v3_path()).await.unwrap());
    assert!(
        !fs::try_exists(service.legacy_rollback_prepared_path())
            .await
            .unwrap()
    );
    let _ = fs::remove_dir_all(root).await;
    let _ = fs::remove_dir_all(outside).await;
}

#[tokio::test]
async fn v2_reader_resolves_shards_from_the_legacy_contract_root() {
    let root = temp_root("map-v2-reader-root");
    fs::create_dir_all(&root)
        .await
        .expect("repository root should create");
    let service = KnowledgeMapService::new(root.clone());
    let context = RequestContext::for_interface(InterfaceKind::Cli);
    service
        .init(&context)
        .await
        .expect("v3 map should initialize");
    fs::remove_dir_all(root.join(LEGACY_AGENT_CONTRACT_DIR_NAME))
        .await
        .expect("current writer lock directory should clear before seeding a v2 root");
    fs::rename(
        root.join(AGENT_CONTRACT_DIR_NAME),
        root.join(LEGACY_AGENT_CONTRACT_DIR_NAME),
    )
    .await
    .expect("contract should move to the legacy root");
    let legacy_root = root.join(LEGACY_KNOWLEDGE_MAP_RELATIVE_PATH);
    rewrite_contract_schema_for_test(
        &root,
        LEGACY_AGENT_CONTRACT_DIR_NAME,
        &legacy_root,
        LEGACY_ARTIFACT_SCHEMA_VERSION,
        None,
    )
    .await
    .expect("v2 root and shards should downgrade together");
    service
        .validate_map_contract()
        .await
        .expect("v2 refs should resolve beside the legacy root");
    let _ = fs::remove_dir_all(root).await;
}

#[tokio::test]
async fn rollback_rejects_a_missing_backup_without_moving_the_visible_root() {
    let (root, service, context) = migrated_v2_fixture("rollback-missing-backup").await;
    let visible_before = fs::read(service.map_path())
        .await
        .expect("visible v3 root should read");
    fs::remove_file(service.legacy_backup_path())
        .await
        .expect("rollback backup should remove");

    let error = service
        .rollback_v3(&context)
        .await
        .expect_err("missing rollback backup must fail");

    assert!(matches!(error, KnowledgeMapServiceError::InvalidRequest(_)));
    assert_eq!(
        fs::read(service.map_path())
            .await
            .expect("visible root should remain"),
        visible_before
    );
    assert!(!fs::try_exists(service.retained_v3_path()).await.unwrap());
    let _ = fs::remove_dir_all(root).await;
}

#[tokio::test]
async fn rollback_fully_validates_the_v2_backup_before_moving_the_visible_root() {
    let (root, service, context) = migrated_v2_fixture("rollback-corrupt-backup").await;
    let visible_before = fs::read(service.map_path())
        .await
        .expect("visible v3 root should read");
    let backup = parse_manifest(
        &fs::read_to_string(service.legacy_backup_path())
            .await
            .expect("v2 backup should read"),
    )
    .expect("v2 backup should parse");
    let shard = backup
        .topics
        .first()
        .expect("backup should reference a topic");
    fs::write(
        root.join(LEGACY_AGENT_CONTRACT_DIR_NAME).join(&shard.r#ref),
        "corrupt shard",
    )
    .await
    .expect("retained shard should corrupt");

    let error = service
        .rollback_v3(&context)
        .await
        .expect_err("corrupt retained graph must fail rollback preflight");

    assert!(matches!(error, KnowledgeMapServiceError::Integrity(_)));
    assert_eq!(
        fs::read(service.map_path())
            .await
            .expect("visible root should remain"),
        visible_before
    );
    assert!(!fs::try_exists(service.retained_v3_path()).await.unwrap());
    let _ = fs::remove_dir_all(root).await;
}

#[tokio::test]
async fn init_converges_each_legacy_redirect_crash_residue() {
    for residue in [
        RedirectResidue::PreparedAndPrevious,
        RedirectResidue::PreviousOnly,
        RedirectResidue::PreparedOnly,
    ] {
        let (root, service, context) = migrated_v2_fixture(residue.label()).await;
        let legacy = service.legacy_map_path();
        let prepared = service.legacy_redirect_prepared_path();
        let previous = service.legacy_redirect_previous_path();
        let backup = service.legacy_backup_path();
        let backup_before = fs::read(&backup).await.expect("v2 backup should read");
        let redirect = fs::read(&legacy).await.expect("redirect should read");

        match residue {
            RedirectResidue::PreparedAndPrevious => {
                fs::write(&prepared, &redirect)
                    .await
                    .expect("prepared redirect should seed");
                fs::copy(&backup, &previous)
                    .await
                    .expect("previous v2 root should seed");
                fs::remove_file(&legacy)
                    .await
                    .expect("live redirect should disappear");
            }
            RedirectResidue::PreviousOnly => {
                fs::copy(&backup, &previous)
                    .await
                    .expect("previous v2 root should seed");
                fs::remove_file(&legacy)
                    .await
                    .expect("live redirect should disappear");
            }
            RedirectResidue::PreparedOnly => {
                fs::copy(&backup, &legacy)
                    .await
                    .expect("live v2 root should seed");
                fs::write(&prepared, &redirect)
                    .await
                    .expect("prepared redirect should seed");
            }
        }

        service
            .init(&context)
            .await
            .expect("restart should converge the redirect publication");

        assert_eq!(
            fs::read(&legacy).await.expect("redirect should recover"),
            redirect
        );
        assert_eq!(
            fs::read(&backup).await.expect("v2 backup should remain"),
            backup_before
        );
        assert!(!fs::try_exists(prepared).await.unwrap());
        assert!(!fs::try_exists(previous).await.unwrap());
        let _ = fs::remove_dir_all(root).await;
    }
}

#[tokio::test]
async fn init_recovers_each_incomplete_rollback_transition_without_losing_either_root() {
    for residue in [
        RollbackResidue::CurrentRoot,
        RollbackResidue::BackupFallback,
        RollbackResidue::LegacyRedirect,
    ] {
        let (root, service, context) = migrated_v2_fixture(residue.label()).await;
        let current = service.map_path();
        let ordinary_backup = service.backup_path();
        let legacy = service.legacy_map_path();
        let legacy_backup = service.legacy_backup_path();
        let current_before = fs::read(&current).await.expect("v3 root should read");
        let ordinary_backup_before = fs::read(&ordinary_backup)
            .await
            .expect("ordinary backup should read");
        let redirect_before = fs::read(&legacy).await.expect("redirect should read");
        let legacy_backup_before = fs::read(&legacy_backup)
            .await
            .expect("legacy backup should read");
        fs::copy(&legacy_backup, service.legacy_rollback_prepared_path())
            .await
            .expect("rollback prepared root should seed");
        fs::rename(&current, service.retained_v3_path())
            .await
            .expect("current root should move");
        if residue.moves_ordinary_backup() {
            fs::rename(&ordinary_backup, service.retained_v3_backup_path())
                .await
                .expect("ordinary backup should move");
        }
        if residue.moves_legacy() {
            fs::rename(&legacy, service.legacy_rollback_previous_path())
                .await
                .expect("legacy redirect should move");
        }

        service
            .init(&context)
            .await
            .expect("restart should restore the pre-commit v3 state");

        assert_eq!(
            fs::read(&current).await.expect("v3 root should recover"),
            current_before
        );
        assert_eq!(
            fs::read(&ordinary_backup)
                .await
                .expect("ordinary backup should recover"),
            ordinary_backup_before
        );
        assert_eq!(
            fs::read(&legacy).await.expect("redirect should recover"),
            redirect_before
        );
        assert_eq!(
            fs::read(&legacy_backup)
                .await
                .expect("legacy backup should remain"),
            legacy_backup_before
        );
        assert!(!fs::try_exists(service.retained_v3_path()).await.unwrap());
        assert!(
            !fs::try_exists(service.retained_v3_backup_path())
                .await
                .unwrap()
        );
        assert!(
            !fs::try_exists(service.legacy_rollback_prepared_path())
                .await
                .unwrap()
        );
        assert!(
            !fs::try_exists(service.legacy_rollback_previous_path())
                .await
                .unwrap()
        );
        let _ = fs::remove_dir_all(root).await;
    }
}

#[tokio::test]
async fn committed_rollback_recovery_preserves_legacy_until_explicit_forward_init() {
    let (root, service, context) = migrated_v2_fixture("rollback-committed-before-cleanup").await;
    let current_before = fs::read(service.map_path())
        .await
        .expect("v3 root should read");
    let ordinary_backup_before = fs::read(service.backup_path())
        .await
        .expect("ordinary backup should read");
    let legacy_backup = fs::read(service.legacy_backup_path())
        .await
        .expect("legacy backup should read");
    let legacy_yaml =
        String::from_utf8(legacy_backup.clone()).expect("legacy backup should be UTF-8");
    let legacy_manifest = parse_manifest(&legacy_yaml).expect("legacy backup should parse");
    fs::copy(
        service.legacy_backup_path(),
        service.legacy_rollback_prepared_path(),
    )
    .await
    .expect("rollback prepared root should seed");
    fs::rename(service.map_path(), service.retained_v3_path())
        .await
        .expect("v3 root should retain");
    fs::rename(service.backup_path(), service.retained_v3_backup_path())
        .await
        .expect("ordinary backup should retain");
    fs::rename(
        service.legacy_map_path(),
        service.legacy_rollback_previous_path(),
    )
    .await
    .expect("legacy redirect should move");
    fs::rename(
        service.legacy_rollback_prepared_path(),
        service.legacy_map_path(),
    )
    .await
    .expect("legacy root publication is the rollback commit point");

    {
        let _legacy_lock = service
            .acquire_legacy_write_lock(WRITE_LOCK_TIMEOUT)
            .await
            .expect("legacy lock should acquire");
        let _current_lock = service
            .acquire_write_lock(WRITE_LOCK_TIMEOUT)
            .await
            .expect("current lock should acquire");
        assert!(
            service
                .recover_legacy_rollback_transition()
                .await
                .expect("restart recovery should finish the committed rollback")
        );
    }

    assert!(!fs::try_exists(service.map_path()).await.unwrap());
    assert!(!fs::try_exists(service.backup_path()).await.unwrap());
    assert_eq!(
        fs::read(service.retained_v3_path())
            .await
            .expect("retained v3 root should remain"),
        current_before
    );
    assert_eq!(
        fs::read(service.retained_v3_backup_path())
            .await
            .expect("retained ordinary backup should remain"),
        ordinary_backup_before
    );
    assert_eq!(
        fs::read(service.legacy_map_path())
            .await
            .expect("legacy root should remain active"),
        legacy_backup
    );
    assert!(
        !fs::try_exists(service.legacy_rollback_previous_path())
            .await
            .unwrap()
    );
    assert_eq!(
        service
            .read_contract_dir_name()
            .await
            .expect("legacy contract should resolve"),
        LEGACY_AGENT_CONTRACT_DIR_NAME
    );
    assert_eq!(
        service
            .read_root_content()
            .await
            .expect("active root should read"),
        legacy_yaml
    );
    let shown = service
        .show(&context, None)
        .await
        .expect("show should read the committed legacy root");
    assert_eq!(shown.map.updated_at, legacy_manifest.updated_at);
    let routed = service
        .route(&context, "software-model".to_owned())
        .await
        .expect("route should read the committed legacy root");
    assert_eq!(
        routed
            .route
            .expect("legacy route should resolve")
            .source_order,
        ["repository-software-model"]
    );

    service
        .init(&context)
        .await
        .expect("an explicit init should migrate forward after recovery");
    assert!(fs::try_exists(service.map_path()).await.unwrap());
    assert!(
        fs::read_to_string(service.legacy_map_path())
            .await
            .expect("legacy redirect should republish")
            .contains("artifact_kind: redirect")
    );
    assert_eq!(
        fs::read(service.retained_v3_path())
            .await
            .expect("retained v3 root should survive forward migration"),
        current_before
    );
    assert_eq!(
        fs::read(service.retained_v3_backup_path())
            .await
            .expect("retained backup should survive forward migration"),
        ordinary_backup_before
    );
    let _ = fs::remove_dir_all(root).await;
}

#[tokio::test]
async fn shard_cleanup_retains_refs_from_both_v3_rollback_roots() {
    let root = temp_root("rollback-shard-retention");
    fs::create_dir_all(&root)
        .await
        .expect("repository root should create");
    let service = KnowledgeMapService::new(root.clone());
    let context = RequestContext::for_interface(InterfaceKind::Cli);
    service.init(&context).await.expect("map should initialize");
    service
        .add_source(
            &context,
            KnowledgeMapSourceAddRequest {
                id: "build".to_owned(),
                topic: "build".to_owned(),
                kind: KnowledgeMapSourceKind::Config,
                uri: "Cargo.toml".to_owned(),
                source_scope: Some("repo".to_owned()),
                description: Some("initial build route".to_owned()),
            },
        )
        .await
        .expect("source should add");
    let retained_root = fs::read_to_string(service.map_path())
        .await
        .expect("retained root should read");
    let retained_manifest = parse_manifest(&retained_root).expect("retained root should parse");
    let retired_ref = retained_manifest
        .topics
        .iter()
        .find(|topic| topic.id == "build")
        .expect("build topic should exist")
        .r#ref
        .clone();
    let retired_shard = root.join(AGENT_CONTRACT_DIR_NAME).join(retired_ref);
    service
        .update_source(
            &context,
            KnowledgeMapChange {
                id: "build".to_owned(),
                topic: None,
                kind: None,
                uri: None,
                source_scope: None,
                description: Some("updated build route".to_owned()),
            },
        )
        .await
        .expect("source should update");
    fs::remove_file(service.backup_path())
        .await
        .expect("ordinary recovery root should remove");
    fs::write(service.retained_v3_path(), &retained_root)
        .await
        .expect("rollback root should seed");
    let current = parse_manifest(
        &fs::read_to_string(service.map_path())
            .await
            .expect("current root should read"),
    )
    .expect("current root should parse");

    cleanup_superseded_topic_shards(&root, &service.backup_path(), &current, Duration::ZERO).await;
    assert!(
        fs::try_exists(&retired_shard).await.unwrap(),
        "the rollback root must retain its unique shard"
    );

    fs::remove_file(service.retained_v3_path())
        .await
        .expect("rollback root should remove");
    fs::write(service.retained_v3_backup_path(), retained_root)
        .await
        .expect("rollback backup root should seed");
    cleanup_superseded_topic_shards(&root, &service.backup_path(), &current, Duration::ZERO).await;
    assert!(
        fs::try_exists(&retired_shard).await.unwrap(),
        "the rollback-retained ordinary backup must retain its unique shard"
    );

    fs::remove_file(service.retained_v3_backup_path())
        .await
        .expect("rollback backup root should remove");
    cleanup_superseded_topic_shards(&root, &service.backup_path(), &current, Duration::ZERO).await;
    assert!(!fs::try_exists(retired_shard).await.unwrap());
    let _ = fs::remove_dir_all(root).await;
}

#[tokio::test]
async fn legacy_namespace_cleanup_retains_refs_from_the_v2_recovery_manifest() {
    let (root, service, _context) = migrated_v2_fixture("legacy-recovery-shard-retention").await;
    let backup_path = service.legacy_backup_path();
    let backup = parse_manifest(
        &fs::read_to_string(&backup_path)
            .await
            .expect("legacy backup should read"),
    )
    .expect("legacy backup should parse");
    let unique_topic = backup
        .topics
        .first()
        .expect("legacy backup should reference a topic");
    let unique_shard = root
        .join(LEGACY_AGENT_CONTRACT_DIR_NAME)
        .join(&unique_topic.r#ref);
    let mut current = backup.clone();
    current.topics.remove(0);
    let absent_ordinary_backup = root
        .join(LEGACY_AGENT_CONTRACT_DIR_NAME)
        .join("absent.previous");

    cleanup_superseded_topic_shards_in(
        &root,
        LEGACY_AGENT_CONTRACT_DIR_NAME,
        &absent_ordinary_backup,
        &current,
        Duration::ZERO,
    )
    .await;
    assert!(
        fs::try_exists(&unique_shard).await.unwrap(),
        "the legacy v2 recovery manifest must retain its unique shard"
    );

    fs::remove_file(backup_path)
        .await
        .expect("legacy recovery manifest should remove");
    cleanup_superseded_topic_shards_in(
        &root,
        LEGACY_AGENT_CONTRACT_DIR_NAME,
        &absent_ordinary_backup,
        &current,
        Duration::ZERO,
    )
    .await;
    assert!(!fs::try_exists(unique_shard).await.unwrap());
    let _ = fs::remove_dir_all(root).await;
}

#[derive(Clone, Copy)]
enum RedirectResidue {
    PreparedAndPrevious,
    PreviousOnly,
    PreparedOnly,
}

#[derive(Clone, Copy)]
enum RollbackResidue {
    CurrentRoot,
    BackupFallback,
    LegacyRedirect,
}

impl RollbackResidue {
    fn label(self) -> &'static str {
        match self {
            Self::CurrentRoot => "rollback-current-moved",
            Self::BackupFallback => "rollback-ordinary-backup-moved",
            Self::LegacyRedirect => "rollback-legacy-moved",
        }
    }

    fn moves_ordinary_backup(self) -> bool {
        matches!(self, Self::BackupFallback | Self::LegacyRedirect)
    }

    fn moves_legacy(self) -> bool {
        matches!(self, Self::LegacyRedirect)
    }
}

impl RedirectResidue {
    fn label(self) -> &'static str {
        match self {
            Self::PreparedAndPrevious => "redirect-prepared-previous",
            Self::PreviousOnly => "redirect-previous-only",
            Self::PreparedOnly => "redirect-prepared-only",
        }
    }
}

async fn migrated_v2_fixture(label: &str) -> (PathBuf, KnowledgeMapService, RequestContext) {
    let root = temp_root(label);
    fs::create_dir_all(&root)
        .await
        .expect("repository root should create");
    let service = KnowledgeMapService::new(root.clone());
    let context = RequestContext::for_interface(InterfaceKind::Cli);
    service
        .init(&context)
        .await
        .expect("v3 fixture should create");
    fs::remove_dir_all(root.join(LEGACY_AGENT_CONTRACT_DIR_NAME))
        .await
        .expect("current writer lock directory should clear before seeding a v2 root");
    fs::rename(
        root.join(AGENT_CONTRACT_DIR_NAME),
        root.join(LEGACY_AGENT_CONTRACT_DIR_NAME),
    )
    .await
    .expect("fixture contract should move to the legacy root");
    let legacy = service.legacy_map_path();
    rewrite_contract_schema_for_test(
        &root,
        LEGACY_AGENT_CONTRACT_DIR_NAME,
        &legacy,
        LEGACY_ARTIFACT_SCHEMA_VERSION,
        None,
    )
    .await
    .expect("v2 fixture root and shards should downgrade together");
    service
        .migrate_to_v4(&context)
        .await
        .expect("v2 fixture should migrate");
    (root, service, context)
}
#[test]
fn rollback_response_version_reads_a_legacy_manifest_without_a_history_index() {
    let legacy_manifest = r#"
schema_version: 2
map_version: 7
updated_at: unix:7
topics: []
history:
  archived_through: 6
  archive:
    ref: history/00000000000000000001-00000000000000000006-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.yaml
    digest: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
  recent:
    - version: 7
      action: mutation
      actor: cli
      summary: retained legacy fixture
"#;

    assert_eq!(
        map_version_from_validated_legacy_content(legacy_manifest)
            .expect("a validated legacy root should expose its response version"),
        7
    );
}

fn temp_root(name: &str) -> PathBuf {
    let nonce = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .expect("clock should be valid")
        .as_nanos();
    std::env::temp_dir().join(format!("relay-knowledge-{name}-{nonce}"))
}