agent-doc-fs 0.34.69

Filesystem helpers for agent-doc
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
use anyhow::{Context, Result};
use std::path::{Component, Path, PathBuf};

pub mod install_freshness;

const SNAPSHOT_DIR: &str = ".agent-doc/snapshots";
const BASELINE_DIR: &str = ".agent-doc/baselines";
const LOCK_DIR: &str = ".agent-doc/locks";
const PENDING_DIR: &str = ".agent-doc/pending";
const TURN_SCOPE_DIR: &str = ".agent-doc/turn-scope";
const CRDT_DIR: &str = ".agent-doc/crdt";
const CRDT_REPLICA_EVENT_DIR: &str = ".agent-doc/crdt-replica-events";
const PRE_RESPONSE_DIR: &str = ".agent-doc/pre-response";
const CYCLE_STATE_DIR: &str = ".agent-doc/state/cycles";
const DISK_CHANGE_REQUEST_DIR: &str = ".agent-doc/disk-change-requests";
const RECOVERY_DIR: &str = ".agent-doc/recovery";
const STARTING_DIR: &str = ".agent-doc/starting";
const BASELINE_OVERLAY_EXT: &str = "overlay.yrs";

/// Walk up the directory tree from `path` to find the directory containing
/// `.agent-doc` (the project root). Returns `None` if no such ancestor exists.
pub fn find_project_root(path: &Path) -> Option<PathBuf> {
    let mut current = if path.is_file() { path.parent()? } else { path };
    loop {
        if current.join(".agent-doc").is_dir() {
            return Some(current.to_path_buf());
        }
        current = current.parent()?;
    }
}

/// Canonicalize `path` first, then delegate to [`find_project_root`].
/// Returns `None` if canonicalization fails or no `.agent-doc` ancestor exists.
pub fn find_project_root_canonical(path: &Path) -> Option<PathBuf> {
    let canonical = path.canonicalize().ok()?;
    find_project_root(&canonical)
}

/// Compute the SHA-256 hex hash used to key per-document state sidecars.
pub fn document_state_hash(doc: &Path) -> Result<String> {
    let canonical = canonical_document_path(doc)?;
    Ok(agent_doc_hash::path_string_hash(
        &canonical.to_string_lossy(),
    ))
}

/// Compute the per-document state hash from an already-resolved path string.
///
/// This avoids filesystem access for paths that no longer exist, such as the
/// old document path during rename recovery.
pub fn document_state_hash_from_str(absolute_path: &str) -> String {
    agent_doc_hash::path_string_hash(absolute_path)
}

/// Compute `<project_root>/.agent-doc/snapshots/<hash>.md` for a document.
///
/// If no `.agent-doc` project root exists, this preserves the historical
/// relative fallback `.agent-doc/snapshots/<hash>.md`.
pub fn snapshot_path_for(doc: &Path) -> Result<PathBuf> {
    let canonical = canonical_document_path(doc)?;
    let filename = format!(
        "{}.md",
        agent_doc_hash::path_string_hash(&canonical.to_string_lossy())
    );
    if let Some(root) = find_project_root(&canonical) {
        return Ok(root.join(SNAPSHOT_DIR).join(filename));
    }
    Ok(PathBuf::from(SNAPSHOT_DIR).join(filename))
}

/// Compute `<project_root>/.agent-doc/locks/<hash>.lock` for a document.
pub fn state_lock_path_for(doc: &Path) -> Result<PathBuf> {
    hashed_state_path(doc, LOCK_DIR, "lock")
}

/// Compute `<project_root>/.agent-doc/pending/<hash>.md` for a document.
pub fn pending_response_path_for(doc: &Path) -> Result<PathBuf> {
    hashed_state_path(doc, PENDING_DIR, "md")
}

/// Compute `<project_root>/.agent-doc/turn-scope/<hash>.json` for a document.
pub fn turn_scope_path_for(doc: &Path) -> Result<PathBuf> {
    hashed_state_path(doc, TURN_SCOPE_DIR, "json")
}

/// Compute `<project_root>/.agent-doc/disk-change-requests/<hash>.json` for a
/// document. The controller watch daemon drops this marker when the file changed
/// on disk out of band; the CPC/controller consumer reads it, reconciles the
/// change into the canonical replica, and clears it (the marker + idle-poll
/// cross-process signal, mirroring recycle-request).
pub fn disk_change_request_path_for(doc: &Path) -> Result<PathBuf> {
    hashed_state_path(doc, DISK_CHANGE_REQUEST_DIR, "json")
}

/// Compute `<project_root>/.agent-doc/crdt-replica-events/<hash>.json` for a
/// document. The controller writes this as an editor-facing event signal after
/// CRDT fan-out or replace rebootstrap work is queued, and editor plugins watch
/// the directory to drain pending replica deliveries without polling.
pub fn crdt_replica_event_path_for(doc: &Path) -> Result<PathBuf> {
    hashed_state_path(doc, CRDT_REPLICA_EVENT_DIR, "json")
}

/// Compute `<project_root>/.agent-doc/state/cycles/<hash>.json` for a document.
///
/// Returns `Ok(None)` when `doc` cannot be canonicalized or no `.agent-doc`
/// project root exists.
pub fn cycle_state_path_for(doc: &Path) -> Result<Option<PathBuf>> {
    let canonical = match doc.canonicalize() {
        Ok(path) => path,
        Err(_) => return Ok(None),
    };
    let Some(root) = find_project_root(&canonical) else {
        return Ok(None);
    };
    let hash = document_state_hash(&canonical)?;
    Ok(Some(
        root.join(CYCLE_STATE_DIR).join(format!("{hash}.json")),
    ))
}

/// Compute `<project_root>/.agent-doc/starting` for a document.
///
/// Returns `None` when `doc` cannot be canonicalized or a root/fallback parent
/// cannot be resolved.
pub fn startup_starting_dir_for(doc: &Path) -> Option<PathBuf> {
    let canonical = doc.canonicalize().ok()?;
    let base =
        find_project_root(&canonical).or_else(|| canonical.parent().map(Path::to_path_buf))?;
    Some(base.join(STARTING_DIR))
}

/// Compute the startup lock filename for a tmux session.
pub fn startup_session_lock_name(session_name: &str) -> String {
    let hash = document_state_hash_from_str(&format!("session:{session_name}"));
    format!("session-{hash}.lock")
}

/// Compute `<project_root>/.agent-doc/starting/<hash>.lock` for a document.
///
/// Returns `None` when the startup directory cannot be resolved. Falls back to
/// hashing the input path text when the document hash cannot be derived from the
/// filesystem.
pub fn startup_document_lock_path_for(doc: &Path) -> Option<PathBuf> {
    let starting_dir = startup_starting_dir_for(doc)?;
    let hash = document_state_hash(doc)
        .unwrap_or_else(|_| document_state_hash_from_str(&doc.to_string_lossy()));
    Some(starting_dir.join(format!("{hash}.lock")))
}

/// Compute `<project_root>/.agent-doc/starting/session-<hash>.lock`.
pub fn startup_session_lock_path_for(doc: &Path, session_name: &str) -> Option<PathBuf> {
    Some(startup_starting_dir_for(doc)?.join(startup_session_lock_name(session_name)))
}

/// Compute `<project_root>/.agent-doc/baselines/<hash>.md` for a document.
pub fn baseline_path_for(doc: &Path) -> Result<PathBuf> {
    hashed_state_path(doc, BASELINE_DIR, "md")
}

/// Compute `<project_root>/.agent-doc/baselines/<hash>.overlay.yrs`.
pub fn baseline_overlay_path_for(doc: &Path) -> Result<PathBuf> {
    let (root, hash) = state_root_and_hash(doc)?;
    Ok(root
        .join(BASELINE_DIR)
        .join(format!("{}.{}", hash, BASELINE_OVERLAY_EXT)))
}

/// Compute `<project_root>/.agent-doc/pre-response/<hash>.md`.
pub fn pre_response_path_for(doc: &Path) -> Result<PathBuf> {
    hashed_state_path(doc, PRE_RESPONSE_DIR, "md")
}

/// Compute `<project_root>/.agent-doc/crdt/<hash>.yrs`.
pub fn crdt_path_for(doc: &Path) -> Result<PathBuf> {
    hashed_state_path(doc, CRDT_DIR, "yrs")
}

/// Compute `<project_root>/.agent-doc/crdt/<hash>.overlay.yrs`.
pub fn overlay_crdt_path_for(doc: &Path) -> Result<PathBuf> {
    hashed_state_path_with_suffix(doc, CRDT_DIR, "overlay.yrs")
}

/// Compute `<project_root>/.agent-doc/crdt/<hash>.nodes.yrs`.
pub fn multinode_crdt_path_for(doc: &Path) -> Result<PathBuf> {
    hashed_state_path_with_suffix(doc, CRDT_DIR, "nodes.yrs")
}

/// Compute the snapshot flock path adjacent to the snapshot sidecar.
pub fn snapshot_flock_path_for(doc: &Path) -> Result<PathBuf> {
    Ok(snapshot_path_for(doc)?.with_extension("md.lock"))
}

/// Compute the CRDT flock path adjacent to the legacy CRDT sidecar.
pub fn crdt_flock_path_for(doc: &Path) -> Result<PathBuf> {
    Ok(crdt_path_for(doc)?.with_extension("yrs.lock"))
}

/// Rewrite `file_path` to be relative to `cwd` so a spawned command resolves
/// correctly when its working directory is narrowed to a submodule root.
///
/// When pane cwd resolution narrows to a submodule, a caller's super-root
/// relative path does not resolve inside that cwd. On any filesystem miss or
/// non-descendant path, the original string is returned unchanged.
pub fn rewrite_start_path(file: &Path, cwd: &Path, original: &str) -> String {
    let Ok(abs_file) = std::fs::canonicalize(file) else {
        return original.to_string();
    };
    let Ok(abs_cwd) = std::fs::canonicalize(cwd) else {
        return original.to_string();
    };
    match abs_file.strip_prefix(&abs_cwd) {
        Ok(rel) => rel.to_string_lossy().into_owned(),
        Err(_) => original.to_string(),
    }
}

/// The inode a process currently maps via `/proc/<pid>/exe`.
///
/// On Linux this magic symlink resolves to the real on-disk inode of the running
/// executable even after the install path has been replaced. Returns `None`
/// when `/proc` is unavailable, the process is gone, or the stat fails.
pub fn running_exe_inode_for_pid(pid: u32) -> Option<u64> {
    #[cfg(target_os = "linux")]
    {
        use std::os::unix::fs::MetadataExt;

        std::fs::metadata(format!("/proc/{pid}/exe"))
            .ok()
            .map(|meta| meta.ino())
    }
    #[cfg(not(target_os = "linux"))]
    {
        let _ = pid;
        None
    }
}

/// Inode of the on-disk file at `path`. Returns `None` on non-Unix platforms or
/// any stat error.
pub fn inode_of_path(path: &Path) -> Option<u64> {
    #[cfg(unix)]
    {
        use std::os::unix::fs::MetadataExt;

        std::fs::metadata(path).ok().map(|meta| meta.ino())
    }
    #[cfg(not(unix))]
    {
        let _ = path;
        None
    }
}

pub fn referenced_markdown_path(current_file: &Path, text: &str) -> Option<PathBuf> {
    referenced_markdown_path_checked(current_file, text)
        .ok()
        .flatten()
}

pub fn referenced_markdown_path_checked(
    current_file: &Path,
    text: &str,
) -> Result<Option<PathBuf>> {
    let current = normalize_path(current_file);
    let project_roots = project_roots_for(current_file);
    for raw in text.split_whitespace() {
        let candidate = raw.trim_matches(|c: char| {
            matches!(
                c,
                '`' | '"' | '\'' | '(' | ')' | '[' | ']' | '{' | '}' | '<' | '>' | ',' | ';' | ':'
            )
        });
        if !candidate.ends_with(".md") {
            continue;
        }

        let path = Path::new(candidate);
        let mut possibilities = Vec::<PathBuf>::new();
        let has_project_prefix = first_component(path).is_some_and(|first| {
            project_roots.iter().any(|root| {
                root.file_name()
                    .is_some_and(|name| Component::Normal(name) == first)
            })
        });
        if path.is_absolute() {
            possibilities.push(path.to_path_buf());
        } else {
            for root in &project_roots {
                if let Some(stripped) = strip_redundant_project_prefix(root, path) {
                    possibilities.push(root.join(stripped));
                }
            }
            for root in &project_roots {
                possibilities.push(root.join(path));
                if let Some(stripped) = strip_redundant_project_prefix(root, path) {
                    possibilities.push(root.join(stripped));
                }
            }
            possibilities.push(
                current_file
                    .parent()
                    .unwrap_or_else(|| Path::new("."))
                    .join(path),
            );
        }

        let mut fallback = None;
        let mut matched_current = false;
        let mut existing = Vec::new();
        for resolved in possibilities {
            let resolved = normalize_path(&resolved);
            if resolved == current {
                matched_current = true;
                continue;
            }
            if resolved.exists() {
                if !existing.iter().any(|seen| seen == &resolved) {
                    existing.push(resolved);
                }
                continue;
            }
            fallback.get_or_insert(resolved);
        }
        if existing.len() > 1 {
            anyhow::bail!(
                "ambiguous markdown reference `{}` from {} matched multiple project roots: {}",
                candidate,
                current_file.display(),
                existing
                    .iter()
                    .map(|path| path.display().to_string())
                    .collect::<Vec<_>>()
                    .join(", ")
            );
        }
        if let Some(resolved) = existing.into_iter().next() {
            return Ok(Some(resolved));
        }
        if has_project_prefix {
            let attempted = fallback
                .as_ref()
                .map(|path| path.display().to_string())
                .unwrap_or_else(|| candidate.to_string());
            anyhow::bail!(
                "project-prefixed markdown reference `{}` from {} did not resolve to an existing file (first candidate: {})",
                candidate,
                current_file.display(),
                attempted
            );
        }
        if matched_current {
            continue;
        }
        if let Some(resolved) = fallback {
            return Ok(Some(resolved));
        }
    }
    Ok(None)
}

/// Process-local sequence so concurrent [`write_atomic`] calls never collide on
/// the same sibling temp-file name.
static ATOMIC_WRITE_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);

/// Atomically write `contents` to `path` by writing a sibling temp file and
/// renaming it into place. `rename(2)` on the same filesystem is atomic, so a
/// crash or `execve` mid-write leaves either the previous file or the
/// fully-written new one — never a truncated/0-byte file. Creates the parent
/// directory if missing.
///
/// This is the write counterpart to [`read_optional_text`] and the fix for an
/// interrupted write (e.g. an `auto_install_reexec` recycle killed mid-write)
/// leaving a 0-byte controller-state file that then wedges every future read.
pub fn write_atomic(path: &Path, contents: &[u8]) -> Result<()> {
    let parent = path.parent().filter(|p| !p.as_os_str().is_empty());
    if let Some(parent) = parent {
        std::fs::create_dir_all(parent)
            .with_context(|| format!("failed to create parent dir for {}", path.display()))?;
    }
    let dir = parent.unwrap_or_else(|| Path::new("."));
    let stem = path
        .file_name()
        .and_then(|n| n.to_str())
        .unwrap_or("agent-doc-state");
    let seq = ATOMIC_WRITE_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    let tmp = dir.join(format!(".{stem}.tmp-{}-{seq}", std::process::id()));
    std::fs::write(&tmp, contents)
        .with_context(|| format!("failed to write temp file {}", tmp.display()))?;
    if let Err(err) = std::fs::rename(&tmp, path) {
        // Best-effort cleanup so a failed rename does not litter temp files;
        // surface (never swallow) the original rename error.
        if let Err(cleanup) = std::fs::remove_file(&tmp) {
            eprintln!(
                "[agent-doc] warning: failed to clean up temp file {} after rename error: {cleanup}",
                tmp.display()
            );
        }
        return Err(err)
            .with_context(|| format!("failed to rename {} -> {}", tmp.display(), path.display()));
    }
    Ok(())
}

pub fn read_optional_text(path: &Path) -> Result<Option<String>> {
    read_optional(path, |path| std::fs::read_to_string(path))
}

pub fn read_optional_bytes(path: &Path) -> Result<Option<Vec<u8>>> {
    read_optional(path, |path| std::fs::read(path))
}

fn read_optional<T, F>(path: &Path, read: F) -> Result<Option<T>>
where
    F: FnOnce(&Path) -> std::io::Result<T>,
{
    match read(path) {
        Ok(value) => Ok(Some(value)),
        Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(None),
        Err(err) => Err(err.into()),
    }
}

/// Read `path` and parse it with `parse`. Missing → `Ok(None)`. If the file
/// exists but is empty / whitespace-only / fails to parse (a *corrupt* state
/// file — e.g. a 0-byte `controller-state.json` left by a pre-[`write_atomic`]
/// interrupted write or an external truncation), quarantine the bad file by
/// renaming it aside and return `Ok(None)` so the caller reboots from a clean
/// slate instead of wedging on every future read.
///
/// This is the read counterpart to [`write_atomic`] (`#corrupt-state-quarantine`):
/// `write_atomic` stops *new* 0-byte files; this recovers automatically from an
/// *already-corrupt* one, so a partial write no longer manifests as the manual
/// `start "timed out waiting for project controller"` move-aside dance.
pub fn read_valid_or_quarantine<T, F>(path: &Path, parse: F) -> Result<Option<T>>
where
    F: FnOnce(&str) -> Option<T>,
{
    let Some(text) = read_optional_text(path)? else {
        return Ok(None);
    };
    if !text.trim().is_empty()
        && let Some(parsed) = parse(&text)
    {
        return Ok(Some(parsed));
    }
    quarantine_corrupt_file(path)?;
    Ok(None)
}

/// Rename a corrupt state file aside to a sibling `<name>.corrupt-<pid>-<seq>`
/// so it stops wedging reads while remaining available for forensics. A file
/// that raced away (already removed) is treated as success.
pub fn quarantine_corrupt_file(path: &Path) -> Result<()> {
    let file_name = path
        .file_name()
        .and_then(|n| n.to_str())
        .unwrap_or("agent-doc-state");
    let seq = ATOMIC_WRITE_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    let quarantine =
        path.with_file_name(format!("{file_name}.corrupt-{}-{seq}", std::process::id()));
    match std::fs::rename(path, &quarantine) {
        Ok(()) => {
            eprintln!(
                "[agent-doc] quarantined corrupt state file {} -> {}",
                path.display(),
                quarantine.display()
            );
            Ok(())
        }
        Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(()),
        Err(err) => Err(err).with_context(|| {
            format!(
                "failed to quarantine corrupt state file {} -> {}",
                path.display(),
                quarantine.display()
            )
        }),
    }
}

/// Preserve a buffer the merge is about to drop to a durable recovery sidecar at
/// `<project_root>/.agent-doc/recovery/<hash>.<pid>-<seq>.md`, so concurrent
/// operator text is recoverable instead of silently lost (`#qftlossdelta`).
/// Written atomically; returns the sidecar path. Best-effort by the caller —
/// this is a safety net alongside, not a replacement for, the merge decision.
pub fn preserve_dropped_operator_buffer(doc: &Path, content: &str) -> Result<PathBuf> {
    let (root, hash) = state_root_and_hash(doc)?;
    let seq = ATOMIC_WRITE_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    let path = root
        .join(RECOVERY_DIR)
        .join(format!("{hash}.{}-{seq}.md", std::process::id()));
    write_atomic(&path, content.as_bytes())?;
    Ok(path)
}

fn first_component(path: &Path) -> Option<Component<'_>> {
    path.components().next()
}

fn strip_redundant_project_prefix(root: &Path, path: &Path) -> Option<PathBuf> {
    let root_name = root.file_name()?;
    let mut components = path.components();
    let Component::Normal(first) = components.next()? else {
        return None;
    };
    if first != root_name {
        return None;
    }
    let stripped = components.as_path();
    (!stripped.as_os_str().is_empty()).then(|| stripped.to_path_buf())
}

fn normalize_path(path: &Path) -> PathBuf {
    std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
}

pub fn same_document_path(left: &Path, right: &Path) -> bool {
    normalize_path(left) == normalize_path(right)
}

fn canonical_document_path(doc: &Path) -> Result<PathBuf> {
    doc.canonicalize()
        .with_context(|| format!("canonicalize document path for hash: {}", doc.display()))
}

fn state_root_and_hash(doc: &Path) -> Result<(PathBuf, String)> {
    let canonical = canonical_document_path(doc)?;
    let hash = agent_doc_hash::path_string_hash(&canonical.to_string_lossy());
    let root = find_project_root(&canonical)
        .unwrap_or_else(|| canonical.parent().unwrap_or(Path::new(".")).to_path_buf());
    Ok((root, hash))
}

fn hashed_state_path(doc: &Path, dir: &str, extension: &str) -> Result<PathBuf> {
    hashed_state_path_with_suffix(doc, dir, extension)
}

fn hashed_state_path_with_suffix(doc: &Path, dir: &str, suffix: &str) -> Result<PathBuf> {
    let (root, hash) = state_root_and_hash(doc)?;
    Ok(root.join(dir).join(format!("{}.{}", hash, suffix)))
}

fn project_roots_for(path: &Path) -> Vec<PathBuf> {
    let mut current = if path.is_dir() {
        path.to_path_buf()
    } else {
        match path.parent() {
            Some(parent) => parent.to_path_buf(),
            None => return Vec::new(),
        }
    };
    let mut roots = Vec::new();
    loop {
        if current.join(".agent-doc").is_dir() {
            roots.push(normalize_path(&current));
        }
        if !current.pop() {
            return roots;
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{
        baseline_overlay_path_for, baseline_path_for, crdt_flock_path_for, crdt_path_for,
        cycle_state_path_for, document_state_hash, document_state_hash_from_str, inode_of_path,
        multinode_crdt_path_for, overlay_crdt_path_for, pending_response_path_for,
        pre_response_path_for, preserve_dropped_operator_buffer, quarantine_corrupt_file,
        read_optional, read_valid_or_quarantine, referenced_markdown_path,
        referenced_markdown_path_checked, rewrite_start_path, running_exe_inode_for_pid,
        same_document_path, snapshot_flock_path_for, snapshot_path_for,
        startup_document_lock_path_for, startup_session_lock_name, startup_session_lock_path_for,
        startup_starting_dir_for, state_lock_path_for, turn_scope_path_for, write_atomic,
    };
    use std::path::Path;

    #[test]
    fn write_atomic_creates_parent_and_writes_contents() {
        let tmp = tempfile::TempDir::new().unwrap();
        let path = tmp.path().join("nested/dir/state.json");
        write_atomic(&path, b"{\"k\":1}").unwrap();
        assert_eq!(std::fs::read_to_string(&path).unwrap(), "{\"k\":1}");
    }

    // #corrupt-state-quarantine

    #[test]
    fn read_valid_or_quarantine_missing_is_none_no_side_effect() {
        let tmp = tempfile::TempDir::new().unwrap();
        let path = tmp.path().join("controller-state.json");
        let got: Option<String> = read_valid_or_quarantine(&path, |s| Some(s.to_string())).unwrap();
        assert!(got.is_none());
        assert!(std::fs::read_dir(tmp.path()).unwrap().next().is_none());
    }

    #[test]
    fn read_valid_or_quarantine_valid_returns_parsed_and_keeps_file() {
        let tmp = tempfile::TempDir::new().unwrap();
        let path = tmp.path().join("controller-state.json");
        std::fs::write(&path, "42").unwrap();
        let got: Option<u32> = read_valid_or_quarantine(&path, |s| s.trim().parse().ok()).unwrap();
        assert_eq!(got, Some(42));
        assert!(path.exists(), "valid file must be left intact");
    }

    #[test]
    fn read_valid_or_quarantine_zero_byte_quarantines_and_returns_none() {
        let tmp = tempfile::TempDir::new().unwrap();
        let path = tmp.path().join("controller-state.json");
        std::fs::write(&path, "").unwrap(); // 0-byte, the classic wedge
        let got: Option<u32> = read_valid_or_quarantine(&path, |s| s.trim().parse().ok()).unwrap();
        assert!(got.is_none(), "empty state must not parse");
        assert!(!path.exists(), "0-byte file must be moved aside");
        let quarantined: Vec<_> = std::fs::read_dir(tmp.path())
            .unwrap()
            .filter_map(|e| e.ok())
            .filter(|e| e.file_name().to_string_lossy().contains(".corrupt-"))
            .collect();
        assert_eq!(quarantined.len(), 1, "exactly one quarantine sibling");
    }

    #[test]
    fn read_valid_or_quarantine_unparseable_quarantines() {
        let tmp = tempfile::TempDir::new().unwrap();
        let path = tmp.path().join("controller-state.json");
        std::fs::write(&path, "{not json").unwrap();
        let got: Option<u32> = read_valid_or_quarantine(&path, |s| s.trim().parse().ok()).unwrap();
        assert!(got.is_none());
        assert!(!path.exists(), "corrupt file must be moved aside");
    }

    #[test]
    fn quarantine_corrupt_file_missing_is_ok() {
        let tmp = tempfile::TempDir::new().unwrap();
        // A file that raced away is treated as success (idempotent recovery).
        quarantine_corrupt_file(&tmp.path().join("gone.json")).unwrap();
    }

    #[test]
    fn preserve_dropped_operator_buffer_writes_recovery_sidecar() {
        let tmp = tempfile::TempDir::new().unwrap();
        std::fs::create_dir_all(tmp.path().join(".agent-doc")).unwrap();
        let doc = tmp.path().join("plan.md");
        std::fs::write(&doc, "# plan\n").unwrap();
        let path =
            preserve_dropped_operator_buffer(&doc, "operator text that would be lost").unwrap();
        assert!(path.exists(), "recovery sidecar must be written");
        assert!(
            path.to_string_lossy().contains("/.agent-doc/recovery/"),
            "sidecar under .agent-doc/recovery: {}",
            path.display()
        );
        assert_eq!(
            std::fs::read_to_string(&path).unwrap(),
            "operator text that would be lost"
        );
    }

    #[test]
    fn write_atomic_overwrites_existing_and_leaves_no_temp_files() {
        let tmp = tempfile::TempDir::new().unwrap();
        let path = tmp.path().join("state.json");
        write_atomic(&path, b"old").unwrap();
        write_atomic(&path, b"new-longer-content").unwrap();
        assert_eq!(
            std::fs::read_to_string(&path).unwrap(),
            "new-longer-content"
        );
        // No sibling ".state.json.tmp-*" temp files should survive a successful write.
        let leftover = std::fs::read_dir(tmp.path())
            .unwrap()
            .filter_map(|e| e.ok())
            .any(|e| e.file_name().to_string_lossy().contains(".tmp-"));
        assert!(!leftover, "temp file leaked after atomic write");
    }

    #[cfg(unix)]
    #[test]
    fn inode_of_path_reads_existing_file_inode() {
        use std::os::unix::fs::MetadataExt;

        let tmp = tempfile::TempDir::new().unwrap();
        let path = tmp.path().join("binary");
        std::fs::write(&path, b"agent-doc").unwrap();

        assert_eq!(
            inode_of_path(&path),
            Some(std::fs::metadata(&path).unwrap().ino())
        );
        assert_eq!(inode_of_path(&tmp.path().join("missing")), None);
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn running_exe_inode_for_pid_reads_current_process_inode() {
        use std::os::unix::fs::MetadataExt;

        let expected = std::fs::metadata(format!("/proc/{}/exe", std::process::id()))
            .unwrap()
            .ino();

        assert_eq!(
            running_exe_inode_for_pid(std::process::id()),
            Some(expected)
        );
    }

    #[test]
    fn read_optional_returns_none_on_not_found() {
        let value: Option<String> = read_optional(Path::new("missing"), |_| {
            Err(std::io::Error::from(std::io::ErrorKind::NotFound))
        })
        .unwrap();
        assert!(value.is_none());
    }

    #[test]
    fn read_optional_preserves_other_errors() {
        let err = read_optional::<String, _>(Path::new("denied"), |_| {
            Err(std::io::Error::from(std::io::ErrorKind::PermissionDenied))
        })
        .unwrap_err();
        let message = err.to_string().to_ascii_lowercase();
        assert!(
            message.contains("permission denied"),
            "unexpected error: {err}"
        );
    }

    #[test]
    fn document_state_hash_uses_canonical_path_string() {
        let tmp = tempfile::TempDir::new().unwrap();
        let doc = tmp.path().join("doc.md");
        std::fs::write(&doc, "# doc\n").unwrap();
        let canonical = doc.canonicalize().unwrap();

        assert_eq!(
            document_state_hash(&doc).unwrap(),
            document_state_hash_from_str(&canonical.to_string_lossy())
        );
    }

    #[test]
    fn same_document_path_matches_equal_unresolved_paths() {
        assert!(same_document_path(
            Path::new("/tmp/agent-doc-same.md"),
            Path::new("/tmp/agent-doc-same.md")
        ));
        assert!(!same_document_path(
            Path::new("/tmp/agent-doc-left.md"),
            Path::new("/tmp/agent-doc-right.md")
        ));
    }

    #[test]
    fn snapshot_path_uses_project_root_when_available() {
        let tmp = tempfile::TempDir::new().unwrap();
        std::fs::create_dir_all(tmp.path().join(".agent-doc")).unwrap();
        let doc = tmp.path().join("nested").join("doc.md");
        std::fs::create_dir_all(doc.parent().unwrap()).unwrap();
        std::fs::write(&doc, "# doc\n").unwrap();
        let hash = document_state_hash(&doc).unwrap();

        assert_eq!(
            snapshot_path_for(&doc).unwrap(),
            tmp.path()
                .join(".agent-doc")
                .join("snapshots")
                .join(format!("{hash}.md"))
        );
    }

    #[test]
    fn snapshot_path_preserves_relative_fallback_without_project_root() {
        let Some(tmp) = temp_dir_without_agent_doc_ancestor() else {
            return;
        };
        let doc = tmp.path().join("doc.md");
        std::fs::write(&doc, "# doc\n").unwrap();
        let hash = document_state_hash(&doc).unwrap();

        assert_eq!(
            snapshot_path_for(&doc).unwrap(),
            Path::new(".agent-doc")
                .join("snapshots")
                .join(format!("{hash}.md"))
        );
    }

    fn temp_dir_without_agent_doc_ancestor() -> Option<tempfile::TempDir> {
        for base in [
            std::path::PathBuf::from("/var/tmp"),
            std::path::PathBuf::from("/dev/shm"),
            std::env::temp_dir(),
        ] {
            if !base.is_dir() || has_agent_doc_ancestor(&base) {
                continue;
            }
            if let Ok(dir) = tempfile::Builder::new()
                .prefix("agent-doc-fs-no-root")
                .tempdir_in(base)
            {
                return Some(dir);
            }
        }
        None
    }

    fn has_agent_doc_ancestor(path: &Path) -> bool {
        let Ok(mut current) = path.canonicalize() else {
            return false;
        };
        loop {
            if current.join(".agent-doc").is_dir() {
                return true;
            }
            if !current.pop() {
                return false;
            }
        }
    }

    #[test]
    fn document_state_sidecar_paths_share_hash_and_project_root() {
        let tmp = tempfile::TempDir::new().unwrap();
        std::fs::create_dir_all(tmp.path().join(".agent-doc")).unwrap();
        let doc = tmp.path().join("doc.md");
        std::fs::write(&doc, "# doc\n").unwrap();
        let hash = document_state_hash(&doc).unwrap();
        let agent_doc = tmp.path().join(".agent-doc");

        assert_eq!(
            state_lock_path_for(&doc).unwrap(),
            agent_doc.join("locks").join(format!("{hash}.lock"))
        );
        assert_eq!(
            pending_response_path_for(&doc).unwrap(),
            agent_doc.join("pending").join(format!("{hash}.md"))
        );
        assert_eq!(
            turn_scope_path_for(&doc).unwrap(),
            agent_doc.join("turn-scope").join(format!("{hash}.json"))
        );
        assert_eq!(
            baseline_path_for(&doc).unwrap(),
            agent_doc.join("baselines").join(format!("{hash}.md"))
        );
        assert_eq!(
            baseline_overlay_path_for(&doc).unwrap(),
            agent_doc
                .join("baselines")
                .join(format!("{hash}.overlay.yrs"))
        );
        assert_eq!(
            pre_response_path_for(&doc).unwrap(),
            agent_doc.join("pre-response").join(format!("{hash}.md"))
        );
        assert_eq!(
            crdt_path_for(&doc).unwrap(),
            agent_doc.join("crdt").join(format!("{hash}.yrs"))
        );
        assert_eq!(
            overlay_crdt_path_for(&doc).unwrap(),
            agent_doc.join("crdt").join(format!("{hash}.overlay.yrs"))
        );
        assert_eq!(
            multinode_crdt_path_for(&doc).unwrap(),
            agent_doc.join("crdt").join(format!("{hash}.nodes.yrs"))
        );
    }

    #[test]
    fn turn_scope_path_uses_project_root_and_document_hash() {
        let tmp = tempfile::TempDir::new().unwrap();
        std::fs::create_dir_all(tmp.path().join(".agent-doc")).unwrap();
        let doc = tmp.path().join("nested").join("doc.md");
        std::fs::create_dir_all(doc.parent().unwrap()).unwrap();
        std::fs::write(&doc, "# doc\n").unwrap();
        let hash = document_state_hash(&doc).unwrap();

        assert_eq!(
            turn_scope_path_for(&doc).unwrap(),
            tmp.path()
                .join(".agent-doc")
                .join("turn-scope")
                .join(format!("{hash}.json"))
        );
    }

    #[test]
    fn cycle_state_path_uses_project_root_and_document_hash() {
        let tmp = tempfile::TempDir::new().unwrap();
        std::fs::create_dir_all(tmp.path().join(".agent-doc")).unwrap();
        let doc = tmp.path().join("nested").join("doc.md");
        std::fs::create_dir_all(doc.parent().unwrap()).unwrap();
        std::fs::write(&doc, "# doc\n").unwrap();
        let hash = document_state_hash(&doc).unwrap();

        assert_eq!(
            cycle_state_path_for(&doc).unwrap(),
            Some(
                tmp.path()
                    .join(".agent-doc")
                    .join("state")
                    .join("cycles")
                    .join(format!("{hash}.json"))
            )
        );
    }

    #[test]
    fn cycle_state_path_returns_none_without_project_root() {
        let Some(tmp) = temp_dir_without_agent_doc_ancestor() else {
            return;
        };
        let doc = tmp.path().join("doc.md");
        std::fs::write(&doc, "# doc\n").unwrap();

        assert_eq!(cycle_state_path_for(&doc).unwrap(), None);
    }

    #[test]
    fn startup_lock_paths_use_project_starting_dir() {
        let tmp = tempfile::TempDir::new().unwrap();
        std::fs::create_dir_all(tmp.path().join(".agent-doc")).unwrap();
        let doc = tmp.path().join("session.md");
        std::fs::write(&doc, "content").unwrap();

        let starting_dir = startup_starting_dir_for(&doc).unwrap();
        assert_eq!(starting_dir, tmp.path().join(".agent-doc/starting"));

        let doc_hash = document_state_hash(&doc).unwrap();
        assert_eq!(
            startup_document_lock_path_for(&doc).unwrap(),
            starting_dir.join(format!("{doc_hash}.lock"))
        );
        assert_eq!(
            startup_session_lock_path_for(&doc, "session-a").unwrap(),
            starting_dir.join(startup_session_lock_name("session-a"))
        );
    }

    #[test]
    fn cycle_state_path_returns_none_when_canonicalize_fails() {
        let tmp = tempfile::TempDir::new().unwrap();
        std::fs::create_dir_all(tmp.path().join(".agent-doc")).unwrap();
        let missing = tmp.path().join("missing.md");

        assert_eq!(cycle_state_path_for(&missing).unwrap(), None);
    }

    #[test]
    fn turn_scope_path_falls_back_to_document_parent_without_project_root() {
        let Some(tmp) = temp_dir_without_agent_doc_ancestor() else {
            return;
        };
        let doc = tmp.path().join("doc.md");
        std::fs::write(&doc, "# doc\n").unwrap();
        let hash = document_state_hash(&doc).unwrap();

        assert_eq!(
            turn_scope_path_for(&doc).unwrap(),
            tmp.path()
                .join(".agent-doc")
                .join("turn-scope")
                .join(format!("{hash}.json"))
        );
    }

    #[test]
    fn flock_paths_are_adjacent_to_snapshot_and_crdt_sidecars() {
        let tmp = tempfile::TempDir::new().unwrap();
        std::fs::create_dir_all(tmp.path().join(".agent-doc")).unwrap();
        let doc = tmp.path().join("doc.md");
        std::fs::write(&doc, "# doc\n").unwrap();

        assert_eq!(
            snapshot_flock_path_for(&doc).unwrap(),
            snapshot_path_for(&doc).unwrap().with_extension("md.lock")
        );
        assert_eq!(
            crdt_flock_path_for(&doc).unwrap(),
            crdt_path_for(&doc).unwrap().with_extension("yrs.lock")
        );
    }

    #[test]
    fn rewrite_start_path_narrows_to_submodule_relative() {
        let tmp = tempfile::TempDir::new().unwrap();
        let super_root = tmp.path();
        let sub_root = super_root.join("src").join("sub");
        let tasks_dir = sub_root.join("tasks");
        std::fs::create_dir_all(&tasks_dir).unwrap();
        let doc = tasks_dir.join("foo.md");
        std::fs::write(&doc, "# foo\n").unwrap();

        let rewritten = rewrite_start_path(&doc, &sub_root, "src/sub/tasks/foo.md");

        assert_eq!(
            rewritten,
            format!("tasks{}foo.md", std::path::MAIN_SEPARATOR)
        );
    }

    #[test]
    fn rewrite_start_path_noops_when_file_path_is_already_cwd_relative() {
        let tmp = tempfile::TempDir::new().unwrap();
        let root = tmp.path();
        let doc = root.join("plan.md");
        std::fs::write(&doc, "# plan\n").unwrap();

        assert_eq!(rewrite_start_path(&doc, root, "plan.md"), "plan.md");
    }

    #[test]
    fn rewrite_start_path_falls_back_when_canonicalize_fails() {
        let tmp = tempfile::TempDir::new().unwrap();
        let ghost = tmp.path().join("does-not-exist.md");

        assert_eq!(
            rewrite_start_path(&ghost, tmp.path(), "does-not-exist.md"),
            "does-not-exist.md"
        );
    }

    #[test]
    fn rewrite_start_path_falls_back_when_file_not_under_cwd() {
        let tmp = tempfile::TempDir::new().unwrap();
        let outside = tmp.path().join("outside.md");
        std::fs::write(&outside, "# outside\n").unwrap();
        let unrelated_cwd = tempfile::TempDir::new().unwrap();

        assert_eq!(
            rewrite_start_path(&outside, unrelated_cwd.path(), "outside.md"),
            "outside.md"
        );
    }

    #[test]
    fn referenced_markdown_path_ignores_self_reference() {
        let dir = tempfile::TempDir::new().unwrap();
        std::fs::create_dir_all(dir.path().join(".agent-doc")).unwrap();
        std::fs::create_dir_all(dir.path().join("tasks")).unwrap();
        let file = dir.path().join("tasks/plan.md");
        std::fs::write(&file, "# plan\n").unwrap();
        assert_eq!(
            referenced_markdown_path(&file, "Update tasks/plan.md before closing"),
            None
        );
    }

    #[test]
    fn referenced_markdown_path_finds_other_doc_reference() {
        let file = Path::new("/tmp/tasks/plan.md");
        let path = referenced_markdown_path(file, "Follow tasks/other-plan.md next").unwrap();
        assert!(path.ends_with("tasks/other-plan.md"));
    }

    #[test]
    fn referenced_markdown_path_strips_redundant_project_prefix() {
        let dir = tempfile::TempDir::new().unwrap();
        let root = dir.path().join("agent-loop");
        std::fs::create_dir_all(root.join(".agent-doc")).unwrap();
        std::fs::create_dir_all(root.join("tasks/agent-doc")).unwrap();
        let current = root.join("tasks/software/tmux-router.md");
        let target = root.join("tasks/agent-doc/agent-doc-bugs2.md");
        std::fs::create_dir_all(current.parent().unwrap()).unwrap();
        std::fs::write(&current, "# source\n").unwrap();
        std::fs::write(&target, "# bugs\n").unwrap();

        let resolved = referenced_markdown_path(
            &current,
            "Add to the backlog of agent-loop/tasks/agent-doc/agent-doc-bugs2.md",
        )
        .unwrap();

        assert_eq!(resolved, target.canonicalize().unwrap());
    }

    #[test]
    fn referenced_markdown_path_resolves_parent_project_prefix_from_nested_root() {
        let dir = tempfile::TempDir::new().unwrap();
        let root = dir.path().join("agent-loop");
        let nested = root.join("src/session-share");
        std::fs::create_dir_all(root.join(".agent-doc")).unwrap();
        std::fs::create_dir_all(nested.join(".agent-doc")).unwrap();
        std::fs::create_dir_all(root.join("tasks/agent-doc")).unwrap();
        std::fs::create_dir_all(nested.join("tasks/agent-doc")).unwrap();
        std::fs::create_dir_all(nested.join("tasks")).unwrap();
        let current = nested.join("tasks/root.md");
        let parent_target = root.join("tasks/agent-doc/agent-doc-bugs2.md");
        let nested_target = nested.join("tasks/agent-doc/agent-doc-bugs2.md");
        std::fs::write(&current, "# root\n").unwrap();
        std::fs::write(&parent_target, "# parent bugs\n").unwrap();
        std::fs::write(&nested_target, "# nested bugs\n").unwrap();

        let resolved = referenced_markdown_path_checked(
            &current,
            "Add to the backlog of agent-loop/tasks/agent-doc/agent-doc-bugs2.md",
        )
        .unwrap()
        .unwrap();

        assert_eq!(resolved, parent_target.canonicalize().unwrap());
    }

    #[test]
    fn referenced_markdown_path_fails_on_ambiguous_nested_task_tree() {
        let dir = tempfile::TempDir::new().unwrap();
        let root = dir.path().join("agent-loop");
        let nested = root.join("src/session-share");
        std::fs::create_dir_all(root.join(".agent-doc")).unwrap();
        std::fs::create_dir_all(nested.join(".agent-doc")).unwrap();
        std::fs::create_dir_all(root.join("tasks/agent-doc")).unwrap();
        std::fs::create_dir_all(nested.join("tasks/agent-doc")).unwrap();
        std::fs::create_dir_all(nested.join("tasks")).unwrap();
        let current = nested.join("tasks/root.md");
        std::fs::write(&current, "# root\n").unwrap();
        std::fs::write(
            root.join("tasks/agent-doc/agent-doc-bugs2.md"),
            "# parent bugs\n",
        )
        .unwrap();
        std::fs::write(
            nested.join("tasks/agent-doc/agent-doc-bugs2.md"),
            "# nested bugs\n",
        )
        .unwrap();

        let err = referenced_markdown_path_checked(
            &current,
            "Add to the backlog of tasks/agent-doc/agent-doc-bugs2.md",
        )
        .unwrap_err();

        assert!(
            err.to_string().contains("ambiguous markdown reference"),
            "{err:#}"
        );
    }

    #[test]
    fn referenced_markdown_path_fails_missing_project_prefixed_target() {
        let dir = tempfile::TempDir::new().unwrap();
        let root = dir.path().join("agent-loop");
        let nested = root.join("src/session-share");
        std::fs::create_dir_all(root.join(".agent-doc")).unwrap();
        std::fs::create_dir_all(nested.join(".agent-doc")).unwrap();
        std::fs::create_dir_all(nested.join("tasks")).unwrap();
        let current = nested.join("tasks/root.md");
        std::fs::write(&current, "# root\n").unwrap();

        let err = referenced_markdown_path_checked(
            &current,
            "Add to the backlog of agent-loop/tasks/agent-doc/missing.md",
        )
        .unwrap_err();

        assert!(
            err.to_string()
                .contains("project-prefixed markdown reference"),
            "{err:#}"
        );
    }
}