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
use super::*;
use crate::domain::{KnowledgeMapChange, KnowledgeMapSourceKind};

#[tokio::test]
async fn writes_and_reads_yaml_contract() {
    let root = std::env::temp_dir().join(format!(
        "relay-knowledge-map-{}",
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("time should work")
            .as_nanos()
    ));
    fs::create_dir_all(&root).await.expect("root should create");
    fs::write(
        root.join("AGENTS.md"),
        format!("Knowledge map: {KNOWLEDGE_MAP_RELATIVE_PATH}"),
    )
    .await
    .expect("agents should write");
    let service = KnowledgeMapService::new(root.clone());
    let context = RequestContext::for_interface(crate::api::InterfaceKind::Cli);

    service.init(&context).await.expect("init should work");
    service
        .add_source(
            &context,
            KnowledgeMapSourceAddRequest {
                id: "build-cargo".to_owned(),
                topic: "build".to_owned(),
                kind: KnowledgeMapSourceKind::Config,
                uri: "Cargo.toml".to_owned(),
                source_scope: Some("repo".to_owned()),
                description: None,
            },
        )
        .await
        .expect("source should add");
    service
        .update_source(
            &context,
            crate::domain::KnowledgeMapChange {
                id: "build-cargo".to_owned(),
                topic: None,
                kind: None,
                uri: None,
                source_scope: None,
                description: Some("Cargo package manifest".to_owned()),
            },
        )
        .await
        .expect("existing map should be replaceable");
    let route = service
        .route(&context, "build".to_owned())
        .await
        .expect("route should load");
    let validation = service
        .validate(&context)
        .await
        .expect("validate should run");

    assert_eq!(route.sources[0].id, "build-cargo");
    assert!(validation.valid);
    let shown = service
        .show(&context, None)
        .await
        .expect("assembled map should load");
    assert_eq!(shown.map.artifact_schema_version, ARTIFACT_SCHEMA_VERSION);
    assert!(shown.map.history.complete);
    assert_eq!(
        service
            .show(&context, None)
            .await
            .expect("public view must remain readable")
            .map,
        shown.map
    );
    let _ = fs::remove_dir_all(root).await;
}

#[tokio::test]
async fn concurrent_source_adds_preserve_both_changes() {
    let root = std::env::temp_dir().join(format!(
        "relay-knowledge-map-concurrent-{}",
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("time should work")
            .as_nanos()
    ));
    fs::create_dir_all(&root).await.expect("root should create");
    let service = KnowledgeMapService::new(root.clone());
    let context = RequestContext::for_interface(crate::api::InterfaceKind::Cli);
    service.init(&context).await.expect("init should work");

    let first = service.add_source(
        &context,
        KnowledgeMapSourceAddRequest {
            id: "build-cargo".to_owned(),
            topic: "build".to_owned(),
            kind: KnowledgeMapSourceKind::Config,
            uri: "Cargo.toml".to_owned(),
            source_scope: Some("repo".to_owned()),
            description: None,
        },
    );
    let second = service.add_source(
        &context,
        KnowledgeMapSourceAddRequest {
            id: "build-readme".to_owned(),
            topic: "build".to_owned(),
            kind: KnowledgeMapSourceKind::Doc,
            uri: "README.md".to_owned(),
            source_scope: Some("repo".to_owned()),
            description: None,
        },
    );

    let (first, second) = tokio::join!(first, second);
    first.expect("first add should succeed");
    second.expect("second add should succeed");
    let route = service
        .route(&context, "build".to_owned())
        .await
        .expect("route should load");

    assert_eq!(route.sources.len(), 2);
    let _ = fs::remove_dir_all(root).await;
}

#[tokio::test]
async fn readers_retry_across_concurrent_manifest_publications() {
    let root = temp_root("concurrent-readers");
    fs::create_dir_all(&root).await.expect("root should create");
    let service = KnowledgeMapService::new(root.clone());
    let context = RequestContext::for_interface(crate::api::InterfaceKind::Cli);
    service.init(&context).await.expect("init should work");
    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: None,
            },
        )
        .await
        .expect("source should add");
    let writer = async {
        for index in 0..20 {
            service
                .update_source(
                    &context,
                    KnowledgeMapChange {
                        id: "build".to_owned(),
                        topic: None,
                        kind: None,
                        uri: None,
                        source_scope: None,
                        description: Some(format!("revision {index}")),
                    },
                )
                .await
                .expect("publication should succeed");
        }
    };
    let reader = async {
        for _ in 0..100 {
            let route = service
                .route(&context, "build".to_owned())
                .await
                .expect("reader should survive the rename window");
            assert_eq!(route.sources.len(), 1);
            tokio::task::yield_now().await;
        }
    };
    tokio::join!(writer, reader);
    let _ = fs::remove_dir_all(root).await;
}

#[tokio::test]
async fn init_upgrades_legacy_map_once() {
    let root = std::env::temp_dir().join(format!(
        "relay-knowledge-map-upgrade-{}",
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("time should work")
            .as_nanos()
    ));
    fs::create_dir_all(root.join(AGENT_CONTRACT_DIR_NAME))
        .await
        .expect("knowledge directory should create");
    let mut legacy = KnowledgeMap::initial("legacy".to_owned());
    legacy
        .remove_source("repository-software-model")
        .expect("legacy fixture should omit the new default route");
    legacy.schema_version = 1;
    let legacy_yaml = serde_norway::to_string(&legacy).expect("legacy map should serialize");
    fs::write(root.join(KNOWLEDGE_MAP_RELATIVE_PATH), legacy_yaml)
        .await
        .expect("legacy map should write");
    let service = KnowledgeMapService::new(root.clone());
    let context = RequestContext::for_interface(crate::api::InterfaceKind::Cli);

    let upgraded = service.init(&context).await.expect("upgrade should work");
    let repeated = service
        .init(&context)
        .await
        .expect("repeat init should be idempotent");
    let shown = service
        .show(&context, Some("software-model".to_owned()))
        .await
        .expect("upgraded map should load");

    assert_eq!(upgraded.map_version, 2);
    assert_eq!(repeated.map_version, upgraded.map_version);
    assert_eq!(shown.map.sources.len(), 1);
    assert_eq!(shown.map.sources[0].id, "repository-software-model");
    assert_eq!(shown.map.history.recent.last().expect("history").version, 2);
    let _ = fs::remove_dir_all(root).await;
}

#[tokio::test]
async fn init_creates_and_then_preserves_business_glossary_without_version_churn() {
    let root = temp_root("business-glossary-init");
    fs::create_dir_all(&root).await.expect("root should create");
    fs::write(
        root.join("AGENTS.md"),
        format!("Knowledge map: {KNOWLEDGE_MAP_RELATIVE_PATH}\n"),
    )
    .await
    .expect("agent contract should write");
    let service = KnowledgeMapService::new(root.clone());
    let context = RequestContext::for_interface(crate::api::InterfaceKind::Cli);

    let initialized = service.init(&context).await.expect("init should work");
    let glossary_path = root.join(crate::project::BUSINESS_GLOSSARY_RELATIVE_PATH);
    let empty = fs::read(&glossary_path)
        .await
        .expect("glossary should exist");
    crate::domain::BusinessGlossary::parse(&empty).expect("empty glossary should validate");
    let authored = "schema_version: 1\ndomains:\n  - id: sales\n    name: Sales\nterms: []\n";
    fs::write(&glossary_path, authored)
        .await
        .expect("authored glossary should write");

    let repeated = service
        .init(&context)
        .await
        .expect("repeat init should work");
    let validation = service
        .validate(&context)
        .await
        .expect("validate should run");

    assert_eq!(repeated.map_version, initialized.map_version);
    assert_eq!(fs::read_to_string(&glossary_path).await.unwrap(), authored);
    assert!(validation.valid);
    let _ = fs::remove_dir_all(root).await;
}

#[tokio::test]
async fn route_loads_only_the_requested_topic_shard() {
    let root = temp_root("progressive");
    fs::create_dir_all(&root).await.expect("root should create");
    let service = KnowledgeMapService::new(root.clone());
    let context = RequestContext::for_interface(crate::api::InterfaceKind::Cli);
    service.init(&context).await.expect("init should work");
    for (id, topic) in [("cargo", "build"), ("adr", "architecture")] {
        service
            .add_source(
                &context,
                KnowledgeMapSourceAddRequest {
                    id: id.to_owned(),
                    topic: topic.to_owned(),
                    kind: KnowledgeMapSourceKind::Doc,
                    uri: format!("docs/{id}.md"),
                    source_scope: Some("repo".to_owned()),
                    description: None,
                },
            )
            .await
            .expect("source should add");
    }
    let manifest_text = fs::read_to_string(root.join(KNOWLEDGE_MAP_RELATIVE_PATH))
        .await
        .expect("manifest should read");
    let manifest = parse_manifest(&manifest_text).expect("manifest should parse");
    let unrelated = manifest
        .topics
        .iter()
        .find(|topic| topic.id == "architecture")
        .expect("architecture topic");
    fs::write(
        root.join(AGENT_CONTRACT_DIR_NAME).join(&unrelated.r#ref),
        "corrupted",
    )
    .await
    .expect("unrelated shard should corrupt");

    let route = service
        .route(&context, "build".to_owned())
        .await
        .expect("build route should not load architecture");
    assert_eq!(route.sources[0].id, "cargo");
    assert!(!service.validate(&context).await.expect("validate").valid);
    let _ = fs::remove_dir_all(root).await;
}

#[tokio::test]
async fn route_rejects_a_digest_consistent_but_semantically_invalid_shard() {
    let root = temp_root("invalid-shard");
    fs::create_dir_all(&root).await.expect("root should create");
    let service = KnowledgeMapService::new(root.clone());
    let context = RequestContext::for_interface(crate::api::InterfaceKind::Cli);
    service.init(&context).await.expect("init should work");
    let mut manifest = parse_manifest(
        &fs::read_to_string(root.join(KNOWLEDGE_MAP_RELATIVE_PATH))
            .await
            .expect("manifest should read"),
    )
    .expect("manifest should parse");
    let topic_ref = manifest
        .topics
        .iter_mut()
        .find(|topic| topic.id == "software-model")
        .expect("software topic should exist");
    let mut shard: KnowledgeMapTopicShard = serde_norway::from_str(
        &fs::read_to_string(root.join(AGENT_CONTRACT_DIR_NAME).join(&topic_ref.r#ref))
            .await
            .expect("shard should read"),
    )
    .expect("shard should parse");
    shard.sources[0].version = 0;
    let yaml = serialize_yaml(&shard).expect("invalid shard should serialize");
    topic_ref.digest = content_digest(yaml.as_bytes());
    topic_ref.r#ref = format!(
        "{KNOWLEDGE_MAP_TOPICS_DIR_NAME}/topic-{}-{}.yaml",
        stable_id(&topic_ref.id),
        topic_ref.digest
    );
    fs::write(
        root.join(AGENT_CONTRACT_DIR_NAME).join(&topic_ref.r#ref),
        yaml,
    )
    .await
    .expect("invalid shard should write");
    fs::write(
        root.join(KNOWLEDGE_MAP_RELATIVE_PATH),
        serialize_yaml(&manifest).expect("manifest should serialize"),
    )
    .await
    .expect("manifest should write");

    let error = service
        .route(&context, "software-model".to_owned())
        .await
        .expect_err("route must apply domain source validation");
    assert!(matches!(error, KnowledgeMapServiceError::Domain(_)));
    let _ = fs::remove_dir_all(root).await;
}

#[tokio::test]
async fn route_rejects_source_ids_duplicated_across_topic_shards() {
    let root = temp_root("duplicate-cross-shard-source");
    fs::create_dir_all(&root).await.expect("root should create");
    let service = KnowledgeMapService::new(root.clone());
    let context = RequestContext::for_interface(crate::api::InterfaceKind::Cli);
    service.init(&context).await.expect("init should work");
    for (id, topic) in [("cargo", "build"), ("adr", "architecture")] {
        service
            .add_source(
                &context,
                KnowledgeMapSourceAddRequest {
                    id: id.to_owned(),
                    topic: topic.to_owned(),
                    kind: KnowledgeMapSourceKind::Doc,
                    uri: format!("docs/{id}.md"),
                    source_scope: Some("repo".to_owned()),
                    description: None,
                },
            )
            .await
            .expect("source should add");
    }
    let mut manifest = parse_manifest(
        &fs::read_to_string(root.join(KNOWLEDGE_MAP_RELATIVE_PATH))
            .await
            .expect("manifest should read"),
    )
    .expect("manifest should parse");
    let topic_ref = manifest
        .topics
        .iter_mut()
        .find(|topic| topic.id == "architecture")
        .expect("architecture topic should exist");
    let mut shard: KnowledgeMapTopicShard = serde_norway::from_str(
        &fs::read_to_string(root.join(AGENT_CONTRACT_DIR_NAME).join(&topic_ref.r#ref))
            .await
            .expect("architecture shard should read"),
    )
    .expect("architecture shard should parse");
    shard.sources[0].id = "cargo".to_owned();
    shard
        .route
        .as_mut()
        .expect("architecture route should exist")
        .source_order[0] = "cargo".to_owned();
    let yaml = serialize_yaml(&shard).expect("duplicate shard should serialize");
    topic_ref.source_ids = vec!["cargo".to_owned()];
    topic_ref.digest = content_digest(yaml.as_bytes());
    topic_ref.r#ref = format!(
        "{KNOWLEDGE_MAP_TOPICS_DIR_NAME}/topic-{}-{}.yaml",
        stable_id(&topic_ref.id),
        topic_ref.digest
    );
    fs::write(
        root.join(AGENT_CONTRACT_DIR_NAME).join(&topic_ref.r#ref),
        yaml,
    )
    .await
    .expect("duplicate shard should write");
    fs::write(
        root.join(KNOWLEDGE_MAP_RELATIVE_PATH),
        serialize_yaml(&manifest).expect("manifest should serialize"),
    )
    .await
    .expect("manifest should write");

    let error = service
        .route(&context, "build".to_owned())
        .await
        .expect_err("root summary must reject cross-shard duplicate ids");
    assert!(matches!(error, KnowledgeMapServiceError::Integrity(_)));
    let _ = fs::remove_dir_all(root).await;
}

#[tokio::test]
async fn route_rejects_blank_recent_history_fields() {
    let root = temp_root("blank-recent-history");
    fs::create_dir_all(&root).await.expect("root should create");
    let service = KnowledgeMapService::new(root.clone());
    let context = RequestContext::for_interface(crate::api::InterfaceKind::Cli);
    service.init(&context).await.expect("init should work");
    let mut manifest = parse_manifest(
        &fs::read_to_string(service.map_path())
            .await
            .expect("manifest should read"),
    )
    .expect("manifest should parse");
    manifest.history.recent[0].action.clear();
    fs::write(
        service.map_path(),
        serialize_yaml(&manifest).expect("manifest should serialize"),
    )
    .await
    .expect("manifest should write");

    let error = service
        .route(&context, "software-model".to_owned())
        .await
        .expect_err("progressive route must validate recent entry contents");
    assert!(matches!(error, KnowledgeMapServiceError::Integrity(_)));
    let _ = fs::remove_dir_all(root).await;
}

#[tokio::test]
async fn route_rejects_overflow_and_unsafe_archive_metadata() {
    let root = temp_root("invalid-archive-metadata");
    fs::create_dir_all(&root).await.expect("root should create");
    let service = KnowledgeMapService::new(root.clone());
    let context = RequestContext::for_interface(crate::api::InterfaceKind::Cli);
    service.init(&context).await.expect("init should work");
    let baseline = parse_manifest(
        &fs::read_to_string(service.map_path())
            .await
            .expect("manifest should read"),
    )
    .expect("manifest should parse");

    let mut overflow = baseline.clone();
    overflow.map_version = u64::MAX;
    overflow.history.archived_through = u64::MAX;
    overflow.history.archive = Some(KnowledgeMapArchiveRef {
        r#ref: "history/archive.yaml".to_owned(),
        digest: "0".repeat(64),
    });
    overflow.history.recent[0].version = u64::MAX;
    fs::write(
        service.map_path(),
        serialize_yaml(&overflow).expect("overflow manifest should serialize"),
    )
    .await
    .expect("overflow manifest should write");
    assert!(matches!(
        service.route(&context, "software-model".to_owned()).await,
        Err(KnowledgeMapServiceError::Integrity(_))
    ));

    let mut unsafe_archive = baseline;
    unsafe_archive.map_version = 2;
    unsafe_archive.history.archived_through = 1;
    unsafe_archive.history.archive = Some(KnowledgeMapArchiveRef {
        r#ref: "../archive.yaml".to_owned(),
        digest: "0".repeat(64),
    });
    unsafe_archive.history.recent[0].version = 2;
    fs::write(
        service.map_path(),
        serialize_yaml(&unsafe_archive).expect("unsafe manifest should serialize"),
    )
    .await
    .expect("unsafe manifest should write");
    assert!(matches!(
        service.route(&context, "software-model".to_owned()).await,
        Err(KnowledgeMapServiceError::Integrity(_))
    ));
    let _ = fs::remove_dir_all(root).await;
}

#[tokio::test]
async fn show_rejects_archive_fields_in_a_recent_only_manifest() {
    let root = temp_root("invalid-show-archive-ref");
    fs::create_dir_all(&root).await.expect("root should create");
    let service = KnowledgeMapService::new(root.clone());
    let context = RequestContext::for_interface(crate::api::InterfaceKind::Cli);
    service.init(&context).await.expect("init should work");
    let content = fs::read_to_string(service.map_path())
        .await
        .expect("manifest should read");
    let mut manifest = parse_manifest(&content).expect("manifest should parse");
    manifest.map_version = 2;
    manifest.history.omitted_through = 1;
    manifest.history.archived_through = 1;
    manifest.history.archive = Some(KnowledgeMapArchiveRef {
        r#ref: "history/archive.yaml".to_owned(),
        digest: "a".repeat(64),
    });
    manifest.history.recent[0].version = 2;
    fs::write(
        service.map_path(),
        serialize_yaml(&manifest).expect("manifest should serialize"),
    )
    .await
    .expect("manifest should write");

    let error = service
        .show(&context, None)
        .await
        .expect_err("show must reject archive fields in schema v4");
    let message = error.to_string();
    assert!(
        message.contains("must not reference archive artifacts"),
        "unexpected validation error: {message}"
    );
    let _ = fs::remove_dir_all(root).await;
}

#[tokio::test]
async fn mutations_reject_case_colliding_topics_before_publication() {
    let root = temp_root("case-collision");
    fs::create_dir_all(&root).await.expect("root should create");
    let service = KnowledgeMapService::new(root.clone());
    let context = RequestContext::for_interface(crate::api::InterfaceKind::Cli);
    service.init(&context).await.expect("init should work");
    for (id, topic) in [("lower", "build"), ("upper", "Build")] {
        let result = service
            .add_source(
                &context,
                KnowledgeMapSourceAddRequest {
                    id: id.to_owned(),
                    topic: topic.to_owned(),
                    kind: KnowledgeMapSourceKind::Doc,
                    uri: format!("docs/{id}.md"),
                    source_scope: Some("repo".to_owned()),
                    description: None,
                },
            )
            .await;
        if id == "lower" {
            result.expect("first spelling should publish");
        } else {
            assert!(matches!(result, Err(KnowledgeMapServiceError::Domain(_))));
        }
    }
    let shown = service
        .show(&context, None)
        .await
        .expect("published map should remain readable");
    assert!(!shown.map.topics.iter().any(|topic| topic.id == "Build"));
    let _ = fs::remove_dir_all(root).await;
}

#[tokio::test]
async fn successful_publication_cleans_superseded_topic_shards() {
    let root = temp_root("shard-cleanup");
    fs::create_dir_all(&root).await.expect("root should create");
    let service = KnowledgeMapService::new(root.clone());
    let context = RequestContext::for_interface(crate::api::InterfaceKind::Cli);
    service.init(&context).await.expect("init should work");
    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: None,
            },
        )
        .await
        .expect("source should add");
    for index in 0..4 {
        service
            .update_source(
                &context,
                KnowledgeMapChange {
                    id: "build".to_owned(),
                    topic: None,
                    kind: None,
                    uri: None,
                    source_scope: None,
                    description: Some(format!("revision {index}")),
                },
            )
            .await
            .expect("source should update");
    }
    let manifest = parse_manifest(
        &fs::read_to_string(root.join(KNOWLEDGE_MAP_RELATIVE_PATH))
            .await
            .expect("manifest should read"),
    )
    .expect("manifest should parse");
    let topics = root
        .join(AGENT_CONTRACT_DIR_NAME)
        .join(KNOWLEDGE_MAP_TOPICS_DIR_NAME);
    for name in ["README.md", ".gitkeep", "manual.yaml"] {
        fs::write(topics.join(name), "user-managed")
            .await
            .expect("user-managed file should write");
    }
    fs::remove_file(service.backup_path())
        .await
        .expect("expired recovery manifest should remove");
    cleanup_superseded_topic_shards(&root, &service.backup_path(), &manifest, Duration::ZERO).await;
    let mut entries = fs::read_dir(
        root.join(AGENT_CONTRACT_DIR_NAME)
            .join(KNOWLEDGE_MAP_TOPICS_DIR_NAME),
    )
    .await
    .expect("topic directory should read");
    let mut shard_count = 0;
    while entries
        .next_entry()
        .await
        .expect("topic entry should read")
        .is_some()
    {
        shard_count += 1;
    }
    assert_eq!(shard_count, manifest.topics.len() + 3);
    for name in ["README.md", ".gitkeep", "manual.yaml"] {
        assert!(
            fs::try_exists(topics.join(name))
                .await
                .expect("user-managed file check should work"),
            "cleanup must preserve {name}"
        );
    }
    let _ = fs::remove_dir_all(root).await;
}

#[tokio::test]
async fn shard_grace_starts_when_the_shard_becomes_unreferenced() {
    let root = temp_root("shard-retirement-time");
    fs::create_dir_all(&root).await.expect("root should create");
    let service = KnowledgeMapService::new(root.clone());
    let context = RequestContext::for_interface(crate::api::InterfaceKind::Cli);
    service.init(&context).await.expect("init should work");
    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: None,
            },
        )
        .await
        .expect("source should add");
    let original = parse_manifest(
        &fs::read_to_string(service.map_path())
            .await
            .expect("manifest should read"),
    )
    .expect("manifest should parse")
    .topics
    .into_iter()
    .find(|topic| topic.id == "build")
    .expect("build topic should exist");
    let shard = root.join(AGENT_CONTRACT_DIR_NAME).join(original.r#ref);
    sleep(Duration::from_millis(20)).await;
    for description in ["revision one", "revision two"] {
        service
            .update_source(
                &context,
                KnowledgeMapChange {
                    id: "build".to_owned(),
                    topic: None,
                    kind: None,
                    uri: None,
                    source_scope: None,
                    description: Some(description.to_owned()),
                },
            )
            .await
            .expect("source should update");
    }
    let mut marker_name = shard.file_name().expect("shard name").to_os_string();
    marker_name.push(".retired");
    let marker = shard.with_file_name(marker_name);
    let shard_age = fs::metadata(&shard)
        .await
        .expect("shard metadata")
        .modified()
        .expect("shard modified time")
        .elapsed()
        .expect("shard age");
    let marker_age = fs::metadata(&marker)
        .await
        .expect("retirement marker metadata")
        .modified()
        .expect("marker modified time")
        .elapsed()
        .expect("marker age");
    assert!(shard_age > marker_age);
    let grace = marker_age + (shard_age - marker_age) / 2;
    let manifest = parse_manifest(
        &fs::read_to_string(service.map_path())
            .await
            .expect("current manifest should read"),
    )
    .expect("current manifest should parse");
    cleanup_superseded_topic_shards(&root, &service.backup_path(), &manifest, grace).await;
    assert!(
        fs::try_exists(&shard).await.expect("shard check"),
        "old artifact age must not bypass its fresh retirement marker"
    );
    cleanup_superseded_topic_shards(&root, &service.backup_path(), &manifest, Duration::ZERO).await;
    assert!(!fs::try_exists(&shard).await.expect("shard check"));
    let _ = fs::remove_dir_all(root).await;
}

#[tokio::test]
async fn rejects_topic_refs_that_escape_the_contract_directory() {
    let root = temp_root("unsafe-ref");
    fs::create_dir_all(&root).await.expect("root should create");
    let service = KnowledgeMapService::new(root.clone());
    let context = RequestContext::for_interface(crate::api::InterfaceKind::Cli);
    service.init(&context).await.expect("init should work");
    let manifest_text = fs::read_to_string(root.join(KNOWLEDGE_MAP_RELATIVE_PATH))
        .await
        .expect("manifest should read");
    let mut manifest = parse_manifest(&manifest_text).expect("manifest should parse");
    manifest.topics[0].r#ref = "topics/../outside.yaml".to_owned();
    fs::write(
        root.join(KNOWLEDGE_MAP_RELATIVE_PATH),
        serialize_yaml(&manifest).expect("manifest should serialize"),
    )
    .await
    .expect("manifest should write");

    let error = service
        .route(&context, "software-model".to_owned())
        .await
        .expect_err("unsafe ref must fail");
    assert!(matches!(error, KnowledgeMapServiceError::Integrity(_)));
    let _ = fs::remove_dir_all(root).await;
}

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

    let root = temp_root("unsafe-write-symlink");
    let outside = temp_root("unsafe-write-target");
    fs::create_dir_all(root.join(AGENT_CONTRACT_DIR_NAME))
        .await
        .expect("contract directory should create");
    fs::create_dir_all(&outside)
        .await
        .expect("outside directory should create");
    symlink(
        &outside,
        root.join(AGENT_CONTRACT_DIR_NAME)
            .join(KNOWLEDGE_MAP_TOPICS_DIR_NAME),
    )
    .expect("topic directory symlink should create");
    let service = KnowledgeMapService::new(root.clone());
    let context = RequestContext::for_interface(crate::api::InterfaceKind::Cli);

    let error = service
        .init(&context)
        .await
        .expect_err("artifact publication must reject a symlink escape");
    assert!(matches!(error, KnowledgeMapServiceError::UnsafePath(_)));
    assert!(
        fs::read_dir(&outside)
            .await
            .expect("outside directory should remain readable")
            .next_entry()
            .await
            .expect("outside directory listing should work")
            .is_none()
    );
    let _ = fs::remove_dir_all(root).await;
    let _ = fs::remove_dir_all(outside).await;
}

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

    let root = temp_root("unsafe-internal-topic-symlink");
    let contract = root.join(AGENT_CONTRACT_DIR_NAME);
    fs::create_dir_all(&contract)
        .await
        .expect("contract directory should create");
    symlink(&contract, contract.join(KNOWLEDGE_MAP_TOPICS_DIR_NAME))
        .expect("topic directory symlink should create");
    let service = KnowledgeMapService::new(root.clone());
    let context = RequestContext::for_interface(crate::api::InterfaceKind::Cli);

    let error = service
        .init(&context)
        .await
        .expect_err("owned topic directory must not be a symlink");
    assert!(matches!(error, KnowledgeMapServiceError::UnsafePath(_)));
    assert!(
        !fs::try_exists(service.map_path())
            .await
            .expect("root check should work")
    );
    let _ = fs::remove_dir_all(root).await;
}

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

    let root = temp_root("unsafe-topic-read-symlink");
    fs::create_dir_all(&root).await.expect("root should create");
    let service = KnowledgeMapService::new(root.clone());
    let context = RequestContext::for_interface(crate::api::InterfaceKind::Cli);
    service.init(&context).await.expect("init should work");
    let contract = root.join(AGENT_CONTRACT_DIR_NAME);
    let topics = contract.join(KNOWLEDGE_MAP_TOPICS_DIR_NAME);
    let relocated = contract.join("relocated-topics");
    fs::rename(&topics, &relocated)
        .await
        .expect("topics should relocate");
    symlink(&relocated, &topics).expect("topics symlink should create");

    let error = service
        .route(&context, "software-model".to_owned())
        .await
        .expect_err("read must reject a symlinked artifact directory");
    assert!(matches!(error, KnowledgeMapServiceError::UnsafePath(_)));
    let _ = fs::remove_dir_all(root).await;
}

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

    let root = temp_root("unsafe-leaf-symlink");
    let outside = temp_root("unsafe-leaf-target");
    let map = KnowledgeMap::initial("fixture".to_owned());
    let topic = map.topics[0].clone();
    let shard = KnowledgeMapTopicShard {
        schema_version: ARTIFACT_SCHEMA_VERSION,
        sources: map
            .sources
            .iter()
            .filter(|source| source.topic == topic.id)
            .cloned()
            .collect(),
        route: map.routes.first().cloned(),
        topic: topic.clone(),
    };
    let yaml = serialize_yaml(&shard).expect("shard should serialize");
    let digest = content_digest(yaml.as_bytes());
    let relative = format!(
        "{KNOWLEDGE_MAP_TOPICS_DIR_NAME}/topic-{}-{digest}.yaml",
        stable_id(&topic.id)
    );
    fs::create_dir_all(
        root.join(AGENT_CONTRACT_DIR_NAME)
            .join(KNOWLEDGE_MAP_TOPICS_DIR_NAME),
    )
    .await
    .expect("topic directory should create");
    fs::create_dir_all(&outside)
        .await
        .expect("outside directory should create");
    let outside_file = outside.join("shard.yaml");
    fs::write(&outside_file, yaml)
        .await
        .expect("outside artifact should write");
    symlink(
        outside_file,
        root.join(AGENT_CONTRACT_DIR_NAME).join(relative),
    )
    .expect("artifact symlink should create");
    let service = KnowledgeMapService::new(root.clone());
    let context = RequestContext::for_interface(crate::api::InterfaceKind::Cli);

    let error = service
        .init(&context)
        .await
        .expect_err("existing artifact symlink must be rejected");
    assert!(matches!(error, KnowledgeMapServiceError::UnsafePath(_)));
    let _ = fs::remove_dir_all(root).await;
    let _ = fs::remove_dir_all(outside).await;
}

#[tokio::test]
async fn recovers_a_root_manifest_left_in_the_publish_backup() {
    let root = temp_root("publish-recovery");
    fs::create_dir_all(&root).await.expect("root should create");
    let service = KnowledgeMapService::new(root.clone());
    let context = RequestContext::for_interface(crate::api::InterfaceKind::Cli);
    service.init(&context).await.expect("init should work");
    fs::rename(service.map_path(), service.backup_path())
        .await
        .expect("interrupted publish should leave a backup");

    service
        .route(&context, "software-model".to_owned())
        .await
        .expect("read path should fall back to the previous root");
    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: None,
            },
        )
        .await
        .expect("writer should recover before mutation");
    assert!(
        fs::try_exists(service.map_path())
            .await
            .expect("root check")
    );
    assert!(
        fs::try_exists(service.backup_path())
            .await
            .expect("backup check"),
        "successful publication retains the recovered root for readers"
    );
    let _ = fs::remove_dir_all(root).await;
}

fn temp_root(label: &str) -> PathBuf {
    std::env::temp_dir().join(format!(
        "relay-knowledge-map-{label}-{}",
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("time should work")
            .as_nanos()
    ))
}

#[path = "history_cleanup_tests.rs"]
mod history_cleanup_tests;
#[path = "history_legacy_tests.rs"]
mod history_legacy_tests;
#[path = "history_tests.rs"]
mod history_tests;
#[path = "path_tests.rs"]
mod path_tests;
use std::time::{SystemTime, UNIX_EPOCH};