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
use super::super::migration::rewrite_contract_schema_for_test as rewrite_schema;
use super::*;
use crate::application::knowledge::map::history::MISSING_HISTORY_INDEX_MESSAGE;

#[tokio::test]
async fn oldest_history_lookup_has_a_constant_read_bound_and_crosses_leaves() {
    let root = temp_root("bounded-history-index");
    fs::create_dir_all(
        root.join(AGENT_CONTRACT_DIR_NAME)
            .join(KNOWLEDGE_MAP_HISTORY_DIR_NAME),
    )
    .await
    .expect("history directory should create");
    let service = KnowledgeMapService::new(root.clone());
    let mut previous = None;
    let mut index = None;
    for version in 1..=70 {
        let archive = KnowledgeMapHistoryArchive {
            schema_version: DIRECTORY_ARTIFACT_SCHEMA_VERSION,
            from_version: version,
            through_version: version,
            previous: previous.clone(),
            entries: vec![crate::domain::KnowledgeMapHistoryEntry {
                version,
                action: "fixture".to_owned(),
                actor: "test".to_owned(),
                summary: format!("History entry {version}"),
            }],
        };
        let yaml = serialize_yaml(&archive).expect("archive should serialize");
        let digest = content_digest(yaml.as_bytes());
        let relative =
            format!("{KNOWLEDGE_MAP_HISTORY_DIR_NAME}/{version:020}-{version:020}-{digest}.yaml");
        publish_immutable(&root, &relative, yaml.as_bytes())
            .await
            .expect("archive should publish");
        let archive_ref = KnowledgeMapArchiveRef {
            r#ref: relative,
            digest,
        };
        index = Some(
            service
                .append_history_index(index, archive_ref.clone(), &archive)
                .await
                .expect("index append should work"),
        );
        previous = Some(archive_ref);
    }
    let index = index.expect("index should exist");
    assert_eq!(
        index.height, 1,
        "70 archives should require two index levels"
    );
    let manifest = KnowledgeMapManifest {
        schema_version: DIRECTORY_ARTIFACT_SCHEMA_VERSION,
        artifact_kind: Some("map".to_owned()),
        map_type: Some(crate::domain::RepositoryMapType::Knowledge),
        map_version: 71,
        updated_at: "fixture".to_owned(),
        directories: super::contracts::baseline_directories(
            crate::domain::RepositoryMapType::Knowledge,
        ),
        topics: Vec::new(),
        history: KnowledgeMapHistoryManifest {
            archived_through: 70,
            omitted_through: 0,
            archive: previous,
            index: Some(index.clone()),
            recent: vec![crate::domain::KnowledgeMapHistoryEntry {
                version: 71,
                action: "fixture".to_owned(),
                actor: "test".to_owned(),
                summary: "Recent entry".to_owned(),
            }],
        },
    };
    fs::write(
        service.map_path(),
        serialize_yaml(&manifest).expect("manifest should serialize"),
    )
    .await
    .expect("manifest should write");
    let (_, _, reads) = service
        .load_indexed_history_archive(&index, 1)
        .await
        .expect("oldest archive should load directly");
    assert!(reads <= history::MAX_HISTORY_LOOKUP_READS);
    assert_eq!(reads, usize::from(index.height) + 2);

    let page = service
        .history(
            &RequestContext::for_interface(crate::api::InterfaceKind::Cli),
            Some(32),
            3,
        )
        .await
        .expect("page should cross the balanced leaf boundary");
    assert_eq!(
        page.entries
            .iter()
            .map(|entry| entry.version)
            .collect::<Vec<_>>(),
        [32, 33, 34]
    );
    let _ = fs::remove_dir_all(root).await;
}

#[test]
fn balanced_prepend_shape_stays_logarithmic_past_two_full_levels() {
    #[derive(Clone)]
    enum Shape {
        Leaf(usize),
        Branch(Vec<Shape>),
    }
    fn prepend(node: &mut Shape) -> Option<Shape> {
        match node {
            Shape::Leaf(entries) => {
                *entries += 1;
                history::balanced_index_split(*entries).map(|split| {
                    let right = *entries - split;
                    *entries = split;
                    Shape::Leaf(right)
                })
            }
            Shape::Branch(children) => {
                if let Some(right) = prepend(&mut children[0]) {
                    children.insert(1, right);
                }
                history::balanced_index_split(children.len())
                    .map(|split| Shape::Branch(children.split_off(split)))
            }
        }
    }
    fn height(node: &Shape) -> u8 {
        match node {
            Shape::Leaf(_) => 0,
            Shape::Branch(children) => 1 + height(&children[0]),
        }
    }
    let mut root = Shape::Leaf(0);
    for _ in 0..=HISTORY_INDEX_FANOUT * HISTORY_INDEX_FANOUT {
        if let Some(right) = prepend(&mut root) {
            root = Shape::Branch(vec![root, right]);
        }
    }
    assert_eq!(height(&root), 2);
    assert!(usize::from(height(&root)) + 2 <= history::MAX_HISTORY_LOOKUP_READS);
}

#[tokio::test]
async fn map_validate_is_read_only_before_init_migrates_and_defers_legacy_history_cleanup() {
    let root = temp_root("legacy-v2-index-migration");
    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");
    for index in 0..RECENT_HISTORY_LIMIT {
        service
            .add_source(
                &context,
                KnowledgeMapSourceAddRequest {
                    id: format!("migration-source-{index}"),
                    topic: "migration".to_owned(),
                    kind: KnowledgeMapSourceKind::Config,
                    uri: format!("migration/{index}.toml"),
                    source_scope: Some("repo".to_owned()),
                    description: None,
                },
            )
            .await
            .expect("source should add");
    }
    let manifest = parse_manifest(
        &fs::read_to_string(service.map_path())
            .await
            .expect("manifest should read"),
    )
    .expect("manifest should parse");
    assert_eq!(manifest.history.omitted_through, 1);
    let archive = KnowledgeMapHistoryArchive {
        schema_version: DIRECTORY_ARTIFACT_SCHEMA_VERSION,
        from_version: 1,
        through_version: 1,
        previous: None,
        entries: vec![crate::domain::KnowledgeMapHistoryEntry {
            version: 1,
            action: "init".to_owned(),
            actor: "cli".to_owned(),
            summary: "Legacy history fixture".to_owned(),
        }],
    };
    let archive_yaml = serialize_yaml(&archive).expect("legacy archive should serialize");
    let archive_digest = content_digest(archive_yaml.as_bytes());
    let archive_ref = KnowledgeMapArchiveRef {
        r#ref: format!(
            "{KNOWLEDGE_MAP_HISTORY_DIR_NAME}/{:020}-{:020}-{archive_digest}.yaml",
            archive.from_version, archive.through_version
        ),
        digest: archive_digest,
    };
    let history_directory = root
        .join(AGENT_CONTRACT_DIR_NAME)
        .join(KNOWLEDGE_MAP_HISTORY_DIR_NAME);
    fs::create_dir_all(&history_directory)
        .await
        .expect("legacy history directory should create");
    fs::write(
        root.join(AGENT_CONTRACT_DIR_NAME).join(&archive_ref.r#ref),
        archive_yaml,
    )
    .await
    .expect("legacy archive should write");
    rewrite_schema(
        &root,
        AGENT_CONTRACT_DIR_NAME,
        &service.map_path(),
        DIRECTORY_ARTIFACT_SCHEMA_VERSION,
        Some(archive_ref.clone()),
    )
    .await
    .expect("legacy root and shards should downgrade together");
    let manifest = parse_manifest(
        &fs::read_to_string(service.map_path())
            .await
            .expect("legacy manifest should read"),
    )
    .expect("legacy manifest should parse");
    assert_eq!(manifest.history.archived_through, 1);
    assert_eq!(manifest.history.archive, Some(archive_ref.clone()));

    let mut history_files = fs::read_dir(&history_directory)
        .await
        .expect("history directory should read");
    while let Some(entry) = history_files
        .next_entry()
        .await
        .expect("history entry should read")
    {
        if entry.file_name().to_string_lossy().starts_with("index-") {
            fs::remove_file(entry.path())
                .await
                .expect("legacy fixture index should remove");
        }
    }
    let root_before_validation = fs::read(service.map_path())
        .await
        .expect("legacy v2 root should read");
    let history_before_validation =
        super::history_cleanup_tests::history_file_contents(&history_directory).await;

    let validation = service
        .validate(&context)
        .await
        .expect("read-only validation should return diagnostics");
    assert!(!validation.valid);
    assert!(
        validation
            .diagnostics
            .iter()
            .any(|diagnostic| diagnostic.contains(MISSING_HISTORY_INDEX_MESSAGE))
    );
    assert_eq!(
        fs::read(service.map_path())
            .await
            .expect("validated root should read"),
        root_before_validation,
        "map validate must not publish a migrated root"
    );
    assert_eq!(
        super::history_cleanup_tests::history_file_contents(&history_directory).await,
        history_before_validation,
        "map validate must not create or rewrite history artifacts"
    );

    let archive_path = root.join(AGENT_CONTRACT_DIR_NAME).join(&archive_ref.r#ref);
    let archive_content = fs::read(&archive_path)
        .await
        .expect("archive should read before corruption");
    fs::write(&archive_path, "corrupt archive").await.unwrap();
    let corrupted = service
        .validate(&context)
        .await
        .expect("validation should surface the blocking archive corruption");
    assert!(
        corrupted
            .diagnostics
            .iter()
            .any(|diagnostic| diagnostic.contains("digest mismatch")),
        "archive integrity must be checked before reporting a missing index"
    );
    assert!(
        !corrupted
            .diagnostics
            .iter()
            .any(|diagnostic| diagnostic.contains(MISSING_HISTORY_INDEX_MESSAGE))
    );
    let migration_error = service
        .init(&context)
        .await
        .expect_err("migration must fail before deleting a corrupt archive");
    assert!(migration_error.to_string().contains("digest mismatch"));
    assert_eq!(
        fs::read(service.map_path())
            .await
            .expect("legacy root should remain readable"),
        root_before_validation
    );
    assert!(fs::try_exists(&archive_path).await.unwrap());
    fs::write(&archive_path, archive_content)
        .await
        .expect("archive should restore");

    let error = service
        .history(&context, Some(1), 1)
        .await
        .expect_err("history must not fall back to a reverse-chain scan");
    assert!(error.to_string().contains("relay-knowledge map init"));
    let migration = service.init(&context).await.expect("migration should work");
    assert!(migration.summary.contains("schema v4 recent-only history"));
    let migrated = parse_manifest(
        &fs::read_to_string(service.map_path())
            .await
            .expect("migrated manifest should read"),
    )
    .expect("migrated manifest should parse");
    assert_eq!(migrated.schema_version, ARTIFACT_SCHEMA_VERSION);
    assert_eq!(migrated.history.omitted_through, 2);
    assert!(migrated.history.index.is_none());
    assert!(migrated.history.archive.is_none());
    let fallback = parse_manifest(
        &fs::read_to_string(service.backup_path())
            .await
            .expect("reader fallback should remain available"),
    )
    .expect("reader fallback should parse");
    assert_eq!(fallback.schema_version, ARTIFACT_SCHEMA_VERSION);
    assert!(fallback.history.archive.is_none());
    assert!(fs::try_exists(&history_directory).await.unwrap());
    assert_eq!(
        service
            .history(&context, None, 1)
            .await
            .expect("retained history should work")
            .entries[0]
            .version,
        3
    );
    assert!(service.history(&context, Some(1), 1).await.is_err());
    let _ = fs::remove_dir_all(root).await;
}

#[tokio::test]
async fn bounds_recent_history_without_creating_archive_artifacts() {
    let root = temp_root("history");
    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");
    for index in 0..RECENT_HISTORY_LIMIT * 2 + 2 {
        service
            .add_source(
                &context,
                KnowledgeMapSourceAddRequest {
                    id: format!("source-{index}"),
                    topic: "build".to_owned(),
                    kind: KnowledgeMapSourceKind::Config,
                    uri: format!("build/{index}.toml"),
                    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");
    assert_eq!(manifest.history.recent.len(), RECENT_HISTORY_LIMIT);
    assert_eq!(
        manifest.history.omitted_through,
        (RECENT_HISTORY_LIMIT + 3) as u64
    );
    assert_eq!(manifest.history.archived_through, 0);
    assert!(manifest.history.archive.is_none());
    assert!(manifest.history.index.is_none());
    assert!(
        !fs::try_exists(
            root.join(AGENT_CONTRACT_DIR_NAME)
                .join(KNOWLEDGE_MAP_HISTORY_DIR_NAME)
        )
        .await
        .expect("history path should be inspectable")
    );
    let retained = service
        .history(&context, None, RECENT_HISTORY_LIMIT)
        .await
        .expect("default history page should start at the retained boundary");
    assert_eq!(retained.entries.len(), RECENT_HISTORY_LIMIT);
    assert_eq!(retained.omitted_through, (RECENT_HISTORY_LIMIT + 3) as u64);
    assert_eq!(
        retained.earliest_available_version,
        retained.omitted_through + 1
    );
    let error = service
        .history(&context, Some(1), 1)
        .await
        .expect_err("omitted history must not be synthesized");
    assert!(error.to_string().contains("no longer retained"));
    assert!(
        service
            .history(&context, Some(1), MAX_HISTORY_PAGE_SIZE + 1)
            .await
            .is_err()
    );

    let shown = service
        .show(&context, None)
        .await
        .expect("default show should expose only retained history");
    assert!(!shown.map.history.complete);
    assert_eq!(
        shown.map.history.omitted_through,
        (RECENT_HISTORY_LIMIT + 3) as u64
    );
    service
        .route(&context, "build".to_owned())
        .await
        .expect("route should not depend on omitted history");
    let validation = service.validate(&context).await.expect("validate");
    assert!(validation.valid, "{:?}", validation.diagnostics);
    service
        .add_source(
            &context,
            KnowledgeMapSourceAddRequest {
                id: "after-compaction".to_owned(),
                topic: "build".to_owned(),
                kind: KnowledgeMapSourceKind::Doc,
                uri: "docs/history.md".to_owned(),
                source_scope: Some("repo".to_owned()),
                description: None,
            },
        )
        .await
        .expect("mutation should advance the bounded window");
    let _ = fs::remove_dir_all(root).await;
}

#[tokio::test]
async fn legacy_show_returns_only_the_recent_history_window() {
    let root = temp_root("legacy-bounded-show");
    fs::create_dir_all(root.join(AGENT_CONTRACT_DIR_NAME))
        .await
        .expect("contract directory should create");
    let mut map = KnowledgeMap::initial("initial".to_owned());
    for index in 0..RECENT_HISTORY_LIMIT + 4 {
        map.record_change(
            "fixture",
            format!("Legacy history {index}"),
            format!("time-{index}"),
        );
    }
    let service = KnowledgeMapService::new(root.clone());
    fs::write(
        service.map_path(),
        serialize_yaml(&map).expect("legacy map should serialize"),
    )
    .await
    .expect("legacy map should write");
    let context = RequestContext::for_interface(crate::api::InterfaceKind::Cli);

    let shown = service
        .show(&context, None)
        .await
        .expect("show should work");

    assert_eq!(shown.map.history.recent.len(), RECENT_HISTORY_LIMIT);
    assert_eq!(shown.map.history.omitted_through, 5);
    assert!(!shown.map.history.complete);
    let first_page = service
        .history(&context, Some(1), 3)
        .await
        .expect("legacy history should remain pageable");
    assert_eq!(
        first_page
            .entries
            .iter()
            .map(|entry| entry.version)
            .collect::<Vec<_>>(),
        [1, 2, 3]
    );
    let _ = fs::remove_dir_all(root).await;
}

#[tokio::test]
async fn an_unlocked_marked_lock_inode_does_not_block_a_writer() {
    let root = temp_root("stale-lock-inode");
    let contract = root.join(AGENT_CONTRACT_DIR_NAME);
    fs::create_dir_all(&contract)
        .await
        .expect("contract directory should create");
    let lock_path = contract.join(format!("{KNOWLEDGE_MAP_FILE_NAME}.lock"));
    fs::write(&lock_path, ADVISORY_LOCK_MARKER)
        .await
        .expect("persistent lock inode should seed");
    let service = KnowledgeMapService::new(root.clone());
    let context = RequestContext::for_interface(crate::api::InterfaceKind::Cli);

    service
        .init(&context)
        .await
        .expect("OS-released lock must be reusable after an owner exits");
    assert!(fs::try_exists(lock_path).await.expect("lock path check"));
    let _ = fs::remove_dir_all(root).await;
}

#[tokio::test]
async fn an_unmarked_legacy_lock_is_not_stolen_during_upgrade() {
    let root = temp_root("legacy-lock");
    let contract = root.join(AGENT_CONTRACT_DIR_NAME);
    fs::create_dir_all(&contract)
        .await
        .expect("contract directory should create");
    let lock_path = contract.join(format!("{KNOWLEDGE_MAP_FILE_NAME}.lock"));
    fs::write(&lock_path, b"")
        .await
        .expect("legacy lock should seed");
    let service = KnowledgeMapService::new(root.clone());

    let error = service
        .acquire_write_lock(Duration::from_millis(50))
        .await
        .expect_err("an old-version writer lock must not be stolen");

    assert!(matches!(error, KnowledgeMapServiceError::LockTimeout(_)));
    assert_eq!(
        fs::read(lock_path).await.expect("legacy lock should read"),
        b""
    );
    let _ = fs::remove_dir_all(root).await;
}

#[test]
fn a_restarted_process_cannot_collide_with_young_staging_names_from_the_same_pid() {
    let lock_path = PathBuf::from(".knowledge").join(format!("{KNOWLEDGE_MAP_FILE_NAME}.lock"));
    let process_id = 42;
    let previous_startup = "00112233445566778899aabbccddeeff";
    let restarted_startup = "ffeeddccbbaa99887766554433221100";
    let previous = (0..16)
        .map(|nonce| {
            transition_lock_prepared_path_with_identity(
                &lock_path,
                process_id,
                previous_startup,
                nonce,
            )
        })
        .collect::<std::collections::HashSet<_>>();

    for nonce in 0..16 {
        let restarted = transition_lock_prepared_path_with_identity(
            &lock_path,
            process_id,
            restarted_startup,
            nonce,
        );
        assert!(!previous.contains(&restarted));
    }
}

#[tokio::test]
async fn writer_lock_ignore_contract_is_target_local_preserved_and_idempotent() {
    let root = temp_root("target-lock-ignore-contract");
    let contract = root.join(AGENT_CONTRACT_DIR_NAME);
    fs::create_dir_all(&contract)
        .await
        .expect("contract directory should create");
    let ignore_path = contract.join(".gitignore");
    fs::write(&ignore_path, b"/user-owned-entry\n")
        .await
        .expect("existing ignore contract should seed");
    let first_service = KnowledgeMapService::new(root.clone());
    let second_service = KnowledgeMapService::new(root.clone());
    let first = async move {
        let lock = first_service
            .acquire_write_lock(Duration::from_millis(500))
            .await
            .expect("first writer should establish target ignore contract");
        drop(lock);
    };
    let second = async move {
        let lock = second_service
            .acquire_write_lock(Duration::from_millis(500))
            .await
            .expect("concurrent writer should reuse target ignore contract");
        drop(lock);
    };
    tokio::join!(first, second);

    let content = fs::read_to_string(ignore_path)
        .await
        .expect("target ignore contract should read");
    assert!(content.contains("/user-owned-entry\n"));
    assert_eq!(content.matches("/knowledge-map.yaml.lock\n").count(), 1);
    assert_eq!(
        content
            .matches("/knowledge-map.yaml.lock.prepared.*\n")
            .count(),
        1
    );
    assert_eq!(content.matches("/topics/*.retired\n").count(), 1);
    let _ = fs::remove_dir_all(root).await;
}

#[tokio::test]
async fn ignore_contract_failure_precedes_every_canonical_or_staging_lock_path() {
    let root = temp_root("lock-ignore-failure-boundary");
    let contract = root.join(AGENT_CONTRACT_DIR_NAME);
    fs::create_dir_all(contract.join(".gitignore"))
        .await
        .expect("invalid ignore directory should seed");
    let service = KnowledgeMapService::new(root.clone());

    service
        .acquire_write_lock(Duration::from_millis(50))
        .await
        .expect_err("invalid target ignore contract must stop lock publication");

    let lock_prefix = format!("{KNOWLEDGE_MAP_FILE_NAME}.lock");
    let mut entries = fs::read_dir(&contract)
        .await
        .expect("contract directory should read");
    while let Some(entry) = entries.next_entry().await.expect("entry should read") {
        assert!(
            !entry
                .file_name()
                .to_string_lossy()
                .starts_with(&lock_prefix),
            "ignore failure must not leave canonical or prepared lock paths"
        );
    }
    let _ = fs::remove_dir_all(root).await;
}

#[tokio::test]
async fn an_incomplete_staging_lock_does_not_block_atomic_publication() {
    let root = temp_root("incomplete-prepared-lock");
    let contract = root.join(AGENT_CONTRACT_DIR_NAME);
    fs::create_dir_all(&contract)
        .await
        .expect("contract directory should create");
    let lock_path = contract.join(format!("{KNOWLEDGE_MAP_FILE_NAME}.lock"));
    let prepared_path =
        transition_lock_prepared_path(&lock_path).expect("prepared lock path should generate");
    fs::write(&prepared_path, &ADVISORY_LOCK_MARKER[..7])
        .await
        .expect("interrupted prepared lock should seed");
    let service = KnowledgeMapService::new(root.clone());

    let owned = service
        .acquire_write_lock(Duration::from_millis(50))
        .await
        .expect("an abandoned staging inode must not block publication");
    drop(owned);

    assert_eq!(
        fs::read(&lock_path)
            .await
            .expect("published lock should read"),
        ADVISORY_LOCK_MARKER
    );
    let _ = fs::remove_dir_all(root).await;
}

#[tokio::test]
async fn an_active_unique_staging_lock_does_not_share_the_canonical_inode() {
    let root = temp_root("active-prepared-lock");
    let contract = root.join(AGENT_CONTRACT_DIR_NAME);
    fs::create_dir_all(&contract)
        .await
        .expect("contract directory should create");
    let lock_path = contract.join(format!("{KNOWLEDGE_MAP_FILE_NAME}.lock"));
    let prepared_path =
        transition_lock_prepared_path(&lock_path).expect("prepared lock path should generate");
    let prepared = std::fs::OpenOptions::new()
        .read(true)
        .write(true)
        .create_new(true)
        .open(&prepared_path)
        .expect("prepared lock should create");
    fs2::FileExt::try_lock_exclusive(&prepared).expect("initializer should own prepared lock");
    let service = KnowledgeMapService::new(root.clone());

    let owned = service
        .acquire_write_lock(Duration::from_millis(50))
        .await
        .expect("another unique staging inode should publish safely");
    drop(owned);

    assert_eq!(
        fs::read(&lock_path)
            .await
            .expect("published lock should read"),
        ADVISORY_LOCK_MARKER
    );
    drop(prepared);
    let _ = fs::remove_dir_all(root).await;
}

#[tokio::test]
async fn cleanup_preserves_an_old_staging_inode_while_its_initializer_is_active() {
    let root = temp_root("active-staging-cleanup");
    let contract = root.join(AGENT_CONTRACT_DIR_NAME);
    fs::create_dir_all(&contract)
        .await
        .expect("contract directory should create");
    let lock_path = contract.join(format!("{KNOWLEDGE_MAP_FILE_NAME}.lock"));
    let prepared_path =
        transition_lock_prepared_path(&lock_path).expect("prepared lock path should generate");
    let prepared = std::fs::OpenOptions::new()
        .read(true)
        .write(true)
        .create_new(true)
        .open(&prepared_path)
        .expect("prepared lock should create");
    fs2::FileExt::try_lock_exclusive(&prepared).expect("initializer should own prepared lock");

    cleanup_transition_locks(&lock_path, Duration::ZERO);

    assert!(
        fs::try_exists(&prepared_path)
            .await
            .expect("active staging path check")
    );
    // Match the production guard's explicit unlock: concurrently spawned children
    // can briefly inherit this descriptor and extend a drop-only lock lifetime.
    fs2::FileExt::unlock(&prepared).expect("initializer should release its staging lock");
    drop(prepared);
    cleanup_transition_locks(&lock_path, Duration::ZERO);
    assert!(
        !fs::try_exists(&prepared_path)
            .await
            .expect("retired staging path check")
    );
    let _ = fs::remove_dir_all(root).await;
}

#[tokio::test]
async fn cleanup_retires_a_legacy_pid_nonce_staging_name_after_upgrade() {
    let root = temp_root("legacy-staging-cleanup");
    let contract = root.join(AGENT_CONTRACT_DIR_NAME);
    fs::create_dir_all(&contract)
        .await
        .expect("contract directory should create");
    let lock_path = contract.join(format!("{KNOWLEDGE_MAP_FILE_NAME}.lock"));
    let legacy_path = contract.join(format!("{KNOWLEDGE_MAP_FILE_NAME}.lock.prepared.4242.0"));
    fs::write(&legacy_path, &ADVISORY_LOCK_MARKER[..7])
        .await
        .expect("legacy staging residue should seed");

    cleanup_transition_locks(&lock_path, Duration::ZERO);

    assert!(
        !fs::try_exists(&legacy_path)
            .await
            .expect("legacy staging path check")
    );
    let _ = fs::remove_dir_all(root).await;
}

#[tokio::test]
async fn a_hard_linked_staging_name_is_never_opened_or_overwritten() {
    let root = temp_root("hard-linked-prepared-lock");
    let contract = root.join(AGENT_CONTRACT_DIR_NAME);
    fs::create_dir_all(&contract)
        .await
        .expect("contract directory should create");
    let outside = root.join("outside-prepared-target");
    fs::write(&outside, b"outside")
        .await
        .expect("outside file should seed");
    let lock_path = contract.join(format!("{KNOWLEDGE_MAP_FILE_NAME}.lock"));
    let prepared_path =
        transition_lock_prepared_path(&lock_path).expect("prepared lock path should generate");
    fs::hard_link(&outside, &prepared_path)
        .await
        .expect("prepared hard link should create");
    let service = KnowledgeMapService::new(root.clone());

    let owned = service
        .acquire_write_lock(Duration::from_millis(50))
        .await
        .expect("an unrelated staging name must not block publication");

    drop(owned);
    assert_eq!(
        fs::read(outside).await.expect("outside file should read"),
        b"outside"
    );
    let _ = fs::remove_dir_all(root).await;
}

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

    let root = temp_root("writer-lock-symlink");
    let contract = root.join(AGENT_CONTRACT_DIR_NAME);
    fs::create_dir_all(&contract)
        .await
        .expect("contract directory should create");
    let outside = root.join("outside-lock-target");
    fs::write(&outside, ADVISORY_LOCK_MARKER)
        .await
        .expect("outside target should seed");
    let lock_path = contract.join(format!("{KNOWLEDGE_MAP_FILE_NAME}.lock"));
    symlink(&outside, &lock_path).expect("lock symlink should create");
    let service = KnowledgeMapService::new(root.clone());

    let error = service
        .acquire_write_lock(Duration::from_millis(50))
        .await
        .expect_err("writer lock symlink must not be followed");

    assert!(matches!(error, KnowledgeMapServiceError::Io(_)));
    assert_eq!(
        fs::read(&outside)
            .await
            .expect("outside target should read"),
        ADVISORY_LOCK_MARKER
    );
    assert!(
        fs::symlink_metadata(lock_path)
            .await
            .expect("lock symlink metadata should read")
            .file_type()
            .is_symlink()
    );
    let _ = fs::remove_dir_all(root).await;
}

#[cfg(windows)]
#[tokio::test]
async fn an_existing_writer_lock_reparse_point_is_rejected_without_following_it() {
    use std::os::windows::fs::symlink_file;

    let root = temp_root("writer-lock-reparse-point");
    let contract = root.join(AGENT_CONTRACT_DIR_NAME);
    fs::create_dir_all(&contract)
        .await
        .expect("contract directory should create");
    let outside = root.join("outside-lock-target");
    fs::write(&outside, ADVISORY_LOCK_MARKER)
        .await
        .expect("outside target should seed");
    let lock_path = contract.join(format!("{KNOWLEDGE_MAP_FILE_NAME}.lock"));
    if let Err(error) = symlink_file(&outside, &lock_path) {
        const ERROR_PRIVILEGE_NOT_HELD: i32 = 1314;
        if error.kind() == std::io::ErrorKind::PermissionDenied
            || error.raw_os_error() == Some(ERROR_PRIVILEGE_NOT_HELD)
        {
            let _ = fs::remove_dir_all(root).await;
            return;
        }
        panic!("lock reparse point should create: {error}");
    }
    let service = KnowledgeMapService::new(root.clone());

    let error = service
        .acquire_write_lock(Duration::from_millis(50))
        .await
        .expect_err("writer lock reparse point must not be followed");

    assert!(matches!(error, KnowledgeMapServiceError::Io(_)));
    assert_eq!(
        fs::read(&outside)
            .await
            .expect("outside target should read"),
        ADVISORY_LOCK_MARKER
    );
    assert!(
        fs::symlink_metadata(lock_path)
            .await
            .expect("lock reparse metadata should read")
            .file_type()
            .is_symlink()
    );
    let _ = fs::remove_dir_all(root).await;
}

#[tokio::test]
async fn an_active_writer_cannot_be_stolen_and_wait_is_bounded() {
    let root = temp_root("active-lock");
    fs::create_dir_all(&root).await.expect("root should create");
    let service = KnowledgeMapService::new(root.clone());
    let active = service
        .acquire_write_lock(Duration::from_millis(50))
        .await
        .expect("first writer should acquire ownership");

    let error = service
        .acquire_write_lock(Duration::from_millis(50))
        .await
        .expect_err("a live writer must retain ownership");
    assert!(matches!(error, KnowledgeMapServiceError::LockTimeout(_)));

    drop(active);
    service
        .acquire_write_lock(Duration::from_millis(50))
        .await
        .expect("released ownership should be immediately reusable");
    let _ = fs::remove_dir_all(root).await;
}