Skip to main content

lean_ctx/core/knowledge/
anchors.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Code anchors of knowledge facts (Hive plan v3 J2; C0 1.9 section 3,
3//! `CodeAnchorV1`).
4//!
5//! An anchor ties a fact to the code it is about: a repo-relative `path`, an
6//! optional `symbol` defined in that file, and the `digest` of exactly those
7//! bytes when the fact was written. The engine resolves anchors against the
8//! checkout on disk, never against a cached index, so a stale graph cannot
9//! report an old body as current:
10//!
11//! - `current`: the symbol (or file) still digests to the anchored bytes;
12//! - `changed`: it is still there with other bytes;
13//! - `moved`: the same bytes now live under another path (found through the
14//!   project's code graph);
15//! - `missing`: neither the symbol nor its bytes are found.
16//!
17//! A fact with any anchor that is not `current` is *to verify*: it is still
18//! recalled, marked, never presented as current knowledge.
19//!
20//! Digest (normalisation fixed by the contract's `anchor_digest` vectors):
21//! the UTF-8 bytes of the definition node (tree-sitter node bytes, without
22//! the doc comments or attributes before it) or of the whole file, with a
23//! leading BOM dropped, `\r\n` and `\r` as `\n`, and trailing spaces and tabs
24//! of every line removed; `sha256:` + lowercase hex.
25//!
26//! Sealed-safe: anchors are part of the fact. A sealed repo's facts travel
27//! only inside the encrypted content, so their paths and symbol names do too;
28//! only the state (`to_verify`) is ever plain metadata.
29
30use std::path::{Component, Path};
31
32use unicode_normalization::UnicodeNormalization as _;
33
34/// The contract's anchor (C0 1.9 `CodeAnchorV1`). The engine's symbol names
35/// are `name`, or `name#n` for the n-th definition of that name in a file,
36/// and slug paths for Markdown sections ([`markdown_sections`]).
37pub use lean_ctx_protocol::hive::anchor::{CodeAnchorV1 as CodeAnchor, MAX_ANCHORS};
38
39const MAX_LANG_BYTES: usize = 32;
40/// Files above this size are not anchored (or resolved): `missing`.
41const MAX_FILE_BYTES: u64 = 4 * 1024 * 1024;
42
43/// Where an anchor stands in a checkout now.
44#[derive(Debug, Clone, PartialEq, Eq)]
45pub enum AnchorState {
46    Current,
47    Changed,
48    Moved { path: String },
49    Missing,
50}
51
52impl AnchorState {
53    /// The contract's reason for a fact to verify (`None` when current).
54    pub fn reason(&self) -> Option<&'static str> {
55        match self {
56            Self::Current => None,
57            Self::Changed => Some("anchor_changed"),
58            Self::Moved { .. } => Some("anchor_moved"),
59            Self::Missing => Some("anchor_missing"),
60        }
61    }
62}
63
64/// The contract's limits on a fact's anchors (`validate_anchors`: at most
65/// [`MAX_ANCHORS`], each valid, sorted by path and symbol with the whole-file
66/// anchor first, no repeats), plus the engine's own: every path in NFC.
67pub fn validate_all(anchors: &[CodeAnchor]) -> Result<(), String> {
68    lean_ctx_protocol::hive::anchor::validate_anchors(anchors).map_err(|e| e.to_string())?;
69    anchors
70        .iter()
71        .try_for_each(|anchor| check_path(&anchor.path))
72}
73
74/// Sort and de-duplicate anchors into their one encoding.
75pub fn canonical(mut anchors: Vec<CodeAnchor>) -> Vec<CodeAnchor> {
76    anchors.sort_by(|a, b| sort_key(a).cmp(&sort_key(b)));
77    anchors.dedup_by(|a, b| sort_key(a) == sort_key(b));
78    anchors
79}
80
81fn sort_key(anchor: &CodeAnchor) -> (&str, Option<&str>) {
82    (anchor.path.as_str(), anchor.symbol.as_deref())
83}
84
85#[cfg(test)]
86fn is_digest(value: &str) -> bool {
87    value.strip_prefix("sha256:").is_some_and(|hex| {
88        hex.len() == 64
89            && hex
90                .bytes()
91                .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
92    })
93}
94
95fn check_path(path: &str) -> Result<(), String> {
96    let malformed = || Err(format!("anchor path {path:?} is malformed"));
97    if path.is_empty()
98        || path.len() > lean_ctx_protocol::hive::anchor::MAX_ANCHOR_PATH_BYTES
99        || path.starts_with('/')
100        || path.starts_with("./")
101        || path.ends_with('/')
102        || path.contains('\\')
103        || path.contains('\0')
104        || path.nfc().collect::<String>() != path
105    {
106        return malformed();
107    }
108    if path
109        .split('/')
110        .any(|segment| segment.is_empty() || segment == "." || segment == "..")
111    {
112        return malformed();
113    }
114    Ok(())
115}
116
117/// A path as an anchor names it: relative to `root`, `/`-separated, NFC.
118/// `None` for a path outside `root` or with `..` components.
119pub fn anchor_path(root: &Path, path: &str) -> Option<String> {
120    let candidate = Path::new(path);
121    let relative = if candidate.is_absolute() {
122        candidate.strip_prefix(root).ok()?
123    } else {
124        candidate
125    };
126    let mut parts = Vec::new();
127    for component in relative.components() {
128        match component {
129            Component::Normal(part) => parts.push(part.to_str()?.nfc().collect::<String>()),
130            Component::CurDir => {}
131            _ => return None,
132        }
133    }
134    let joined = parts.join("/");
135    check_path(&joined).ok()?;
136    Some(joined)
137}
138
139/// `sha256:` + hex of the normalised bytes (C0 1.9 section 3: BOM dropped,
140/// CRLF/CR to LF, trailing spaces and tabs removed per line).
141pub use lean_ctx_protocol::hive::anchor::anchor_digest as digest;
142
143fn extension(path: &str) -> &str {
144    Path::new(path)
145        .extension()
146        .and_then(|e| e.to_str())
147        .unwrap_or("")
148}
149
150/// The file at the anchor path, read inside `root` only: no symlink may lead
151/// out of the checkout, and oversized or unreadable files are `None`.
152fn read_inside(root: &Path, path: &str) -> Option<Vec<u8>> {
153    check_path(path).ok()?;
154    let root = root.canonicalize().ok()?;
155    let full = root.join(path).canonicalize().ok()?;
156    if !full.starts_with(&root) {
157        return None;
158    }
159    let meta = std::fs::metadata(&full).ok()?;
160    if !meta.is_file() || meta.len() > MAX_FILE_BYTES {
161        return None;
162    }
163    std::fs::read(&full).ok()
164}
165
166/// The slug of a Markdown heading text: lowercase, letters and digits kept,
167/// runs of anything else as one `-`, none at the edges ("Release & Steps"
168/// → "release-steps"). Imported facts (K1) key sections by the same slugs.
169pub fn heading_slug(text: &str) -> String {
170    let mut slug = String::new();
171    for c in text.trim().chars().flat_map(char::to_lowercase) {
172        if c.is_alphanumeric() {
173            slug.push(c);
174        } else if !slug.is_empty() && !slug.ends_with('-') {
175            slug.push('-');
176        }
177    }
178    while slug.ends_with('-') {
179        slug.pop();
180    }
181    slug
182}
183
184/// The ATX sections of a Markdown file as (slug path, byte range): a
185/// section runs from its heading to the next heading of the same or a
186/// higher level (or the end). The path joins the slugs of its parent
187/// headings with `/` ("release/steps"); headings inside fenced code are not
188/// headings. Repeated paths get `#n` from the second on.
189pub fn markdown_sections(content: &str) -> Vec<(String, std::ops::Range<usize>)> {
190    let mut headings: Vec<(usize, usize, String)> = Vec::new(); // (level, start, slug)
191    let mut fence: Option<&str> = None;
192    let mut offset = 0;
193    for line in content.split_inclusive('\n') {
194        let start = offset;
195        offset += line.len();
196        let trimmed = line.trim_start();
197        if let Some(open) = fence {
198            if trimmed.starts_with(open) {
199                fence = None;
200            }
201            continue;
202        }
203        if trimmed.starts_with("```") || trimmed.starts_with("~~~") {
204            fence = Some(&trimmed[..3]);
205            continue;
206        }
207        if line.len() - trimmed.len() > 3 {
208            continue; // indented code
209        }
210        let level = trimmed.bytes().take_while(|b| *b == b'#').count();
211        let rest = &trimmed[level..];
212        if (1..=6).contains(&level) && (rest.starts_with(' ') || rest.trim().is_empty()) {
213            let text = rest.trim().trim_end_matches('#').trim();
214            headings.push((level, start, heading_slug(text)));
215        }
216    }
217    let mut sections = Vec::with_capacity(headings.len());
218    let mut stack: Vec<(usize, String)> = Vec::new();
219    let mut seen = std::collections::HashMap::<String, usize>::new();
220    for (i, (level, start, slug)) in headings.iter().enumerate() {
221        while stack.last().is_some_and(|(l, _)| l >= level) {
222            stack.pop();
223        }
224        stack.push((*level, slug.clone()));
225        let end = headings[i + 1..]
226            .iter()
227            .find(|(l, _, _)| l <= level)
228            .map_or(content.len(), |(_, s, _)| *s);
229        let path = stack
230            .iter()
231            .map(|(_, s)| s.as_str())
232            .filter(|s| !s.is_empty())
233            .collect::<Vec<_>>()
234            .join("/");
235        if path.is_empty() {
236            continue;
237        }
238        let n = seen.entry(path.clone()).or_insert(0);
239        *n += 1;
240        let symbol = if *n == 1 { path } else { format!("{path}#{n}") };
241        sections.push((symbol, *start..end));
242    }
243    sections
244}
245
246/// Each definition in `content` as (symbol, byte range): `name`, and
247/// `name#n` from the second definition of the same name on; Markdown files
248/// by their sections ([`markdown_sections`]).
249#[cfg(feature = "tree-sitter")]
250fn symbols(content: &str, ext: &str) -> Vec<(String, std::ops::Range<usize>)> {
251    if matches!(ext, "md" | "markdown" | "mdx") {
252        return markdown_sections(content);
253    }
254    let Some(spans) = crate::core::signatures_ts::extract_spans_ts(content, ext) else {
255        return Vec::new();
256    };
257    let mut seen = std::collections::HashMap::<String, usize>::new();
258    spans
259        .into_iter()
260        .map(|(sig, range)| {
261            let n = seen.entry(sig.name.clone()).or_insert(0);
262            *n += 1;
263            let symbol = if *n == 1 {
264                sig.name
265            } else {
266                format!("{}#{n}", sig.name)
267            };
268            (symbol, range)
269        })
270        .collect()
271}
272
273#[cfg(not(feature = "tree-sitter"))]
274fn symbols(content: &str, ext: &str) -> Vec<(String, std::ops::Range<usize>)> {
275    if matches!(ext, "md" | "markdown" | "mdx") {
276        return markdown_sections(content);
277    }
278    Vec::new()
279}
280
281/// The anchored bytes of `symbol` (or of the whole file) in `content`.
282pub(crate) fn anchored<'a>(
283    content: &'a [u8],
284    path: &str,
285    symbol: Option<&str>,
286) -> Option<&'a [u8]> {
287    let Some(symbol) = symbol else {
288        return Some(content);
289    };
290    let text = std::str::from_utf8(content).ok()?;
291    symbols(text, extension(path))
292        .into_iter()
293        .find(|(name, _)| name == symbol)
294        .map(|(_, range)| &content[range])
295}
296
297/// Anchor `path` (and `symbol` in it) as it is in `root` now.
298pub fn capture(root: &Path, path: &str, symbol: Option<&str>) -> Result<CodeAnchor, String> {
299    let path =
300        anchor_path(root, path).ok_or_else(|| format!("{path}: not a path inside the project"))?;
301    let content =
302        read_inside(root, &path).ok_or_else(|| format!("{path}: not readable in the project"))?;
303    let bytes = anchored(&content, &path, symbol)
304        .ok_or_else(|| format!("{path}: no definition named {}", symbol.unwrap_or_default()))?;
305    let ext = extension(&path);
306    let anchor = CodeAnchor {
307        path: path.clone(),
308        symbol: symbol.map(str::to_owned),
309        digest: digest(bytes),
310        lang: (!ext.is_empty() && ext.len() <= MAX_LANG_BYTES)
311            .then(|| ext.to_ascii_lowercase())
312            .filter(|l| {
313                l.bytes()
314                    .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_')
315            }),
316    };
317    validate_all(std::slice::from_ref(&anchor))?;
318    Ok(anchor)
319}
320
321/// Parse `path` or `path::symbol` as a writer names an anchor.
322pub fn parse_spec(spec: &str) -> (&str, Option<&str>) {
323    match spec.split_once("::") {
324        Some((path, symbol)) if !symbol.is_empty() => (path, Some(symbol)),
325        _ => (spec, None),
326    }
327}
328
329/// Where `anchor` stands in `root` now.
330pub fn resolve(root: &Path, anchor: &CodeAnchor) -> AnchorState {
331    if let Some(content) = read_inside(root, &anchor.path)
332        && let Some(bytes) = anchored(&content, &anchor.path, anchor.symbol.as_deref())
333    {
334        return if digest(bytes) == anchor.digest {
335            AnchorState::Current
336        } else {
337            AnchorState::Changed
338        };
339    }
340    match moved_to(root, anchor) {
341        Some(path) => AnchorState::Moved { path },
342        None => AnchorState::Missing,
343    }
344}
345
346/// Another file of the project that holds the anchored bytes: for a symbol,
347/// a definition of the same name in the code graph; for a whole file, none
348/// (a moved file without a symbol is `missing`).
349fn moved_to(root: &Path, anchor: &CodeAnchor) -> Option<String> {
350    let symbol = anchor.symbol.as_deref()?;
351    let name = symbol.split_once('#').map_or(symbol, |(name, _)| name);
352    let index = crate::core::graph_index::ProjectIndex::load(root.to_str()?)?;
353    let mut files: Vec<&str> = index
354        .symbols
355        .values()
356        .filter(|entry| entry.name == name && entry.file != anchor.path)
357        .map(|entry| entry.file.as_str())
358        .collect();
359    files.sort_unstable();
360    files.dedup();
361    files.into_iter().find_map(|file| {
362        let content = read_inside(root, file)?;
363        let text = std::str::from_utf8(&content).ok()?;
364        symbols(text, extension(file))
365            .into_iter()
366            .any(|(_, range)| digest(&content[range]) == anchor.digest)
367            .then(|| file.to_owned())
368    })
369}
370
371/// The reasons a fact with `anchors` is to verify in `root` (empty: current).
372/// Anchors resolved past this many in one pass are skipped (each costs a
373/// read and a parse).
374pub const MAX_RESOLVED_PER_PASS: usize = 20_000;
375
376/// Resolves anchors that may come from elsewhere (Hive facts other engines
377/// wrote) without turning the checkout into an oracle: only files the
378/// engine may read for knowledge (source admission), and in a git checkout
379/// only tracked ones, are ever read. Any other path is `Missing` without a
380/// read, whether it exists or not, so a crafted anchor on `.env` learns
381/// neither its content nor its existence. Reads are memoised for the pass;
382/// past [`MAX_RESOLVED_PER_PASS`] an anchor has no state (`None`).
383pub struct GuardedResolver<'a> {
384    root: &'a Path,
385    tracked: Option<std::collections::HashSet<String>>,
386    admitted: std::collections::HashMap<String, bool>,
387    memo: std::collections::HashMap<(String, Option<String>, String), AnchorState>,
388    resolved: usize,
389}
390
391impl<'a> GuardedResolver<'a> {
392    /// For a report that leaves the machine: tracked and admitted files.
393    pub fn for_report(root: &'a Path) -> Self {
394        Self {
395            root,
396            tracked: git_tracked(root),
397            admitted: std::collections::HashMap::new(),
398            memo: std::collections::HashMap::new(),
399            resolved: 0,
400        }
401    }
402
403    /// For what this engine shows its own agents: admitted files.
404    pub fn local(root: &'a Path) -> Self {
405        Self {
406            tracked: None,
407            ..Self::for_report(root)
408        }
409    }
410
411    /// Whether `path` may be read for an anchor at all.
412    pub fn may_read(&mut self, path: &str) -> bool {
413        if self
414            .tracked
415            .as_ref()
416            .is_some_and(|tracked| !tracked.contains(path))
417        {
418            return false;
419        }
420        let root = self.root;
421        *self.admitted.entry(path.to_owned()).or_insert_with(|| {
422            crate::core::archive::bindings::sources_at(
423                &root.to_string_lossy(),
424                &[path],
425                "ctx_knowledge",
426            )
427            .is_some()
428        })
429    }
430
431    /// Where `anchor` stands now; `None` only past the per-pass cap.
432    pub fn resolve(&mut self, anchor: &CodeAnchor) -> Option<AnchorState> {
433        if check_path(&anchor.path).is_err() || !self.may_read(&anchor.path) {
434            return Some(AnchorState::Missing);
435        }
436        let key = (
437            anchor.path.clone(),
438            anchor.symbol.clone(),
439            anchor.digest.clone(),
440        );
441        if let Some(state) = self.memo.get(&key) {
442            return Some(state.clone());
443        }
444        if self.resolved >= MAX_RESOLVED_PER_PASS {
445            return None;
446        }
447        self.resolved += 1;
448        let state = match resolve(self.root, anchor) {
449            // A move found through the index points at another file: that
450            // one must be readable too, or the move tells nothing.
451            AnchorState::Moved { path } if !self.may_read(&path) => AnchorState::Missing,
452            state => state,
453        };
454        self.memo.insert(key, state.clone());
455        Some(state)
456    }
457}
458
459/// The checkout's tracked files (`git ls-files`), or `None` outside git.
460fn git_tracked(root: &Path) -> Option<std::collections::HashSet<String>> {
461    let out = std::process::Command::new("git")
462        .arg("-C")
463        .arg(root)
464        .args(["ls-files", "-z"])
465        .output()
466        .ok()?;
467    if !out.status.success() {
468        return None;
469    }
470    Some(
471        out.stdout
472            .split(|b| *b == 0)
473            .filter(|p| !p.is_empty())
474            .filter_map(|p| std::str::from_utf8(p).ok().map(str::to_owned))
475            .collect(),
476    )
477}
478
479pub fn review(root: &Path, anchors: &[CodeAnchor]) -> Vec<(CodeAnchor, AnchorState)> {
480    anchors
481        .iter()
482        .map(|anchor| (anchor.clone(), resolve(root, anchor)))
483        .filter(|(_, state)| *state != AnchorState::Current)
484        .collect()
485}
486
487#[cfg(test)]
488mod tests {
489    use super::*;
490
491    fn project(files: &[(&str, &str)]) -> tempfile::TempDir {
492        let dir = tempfile::tempdir().unwrap();
493        for (path, content) in files {
494            let full = dir.path().join(path);
495            std::fs::create_dir_all(full.parent().unwrap()).unwrap();
496            std::fs::write(full, content).unwrap();
497        }
498        dir
499    }
500
501    #[test]
502    fn a_guarded_resolver_never_reads_an_unadmitted_or_untracked_file() {
503        let _iso = crate::core::data_dir::isolated_data_dir();
504        let dir = project(&[("src/a.md", "kept\n"), (".env", "API_KEY=abc\n")]);
505        let root = dir.path();
506        let git = |args: &[&str]| {
507            std::process::Command::new("git")
508                .arg("-C")
509                .arg(root)
510                .args(args)
511                .output()
512                .unwrap()
513        };
514        git(&["init", "-q"]);
515        git(&["add", "src/a.md"]);
516        let tracked = capture(root, "src/a.md", None).unwrap();
517        // An anchor someone else wrote, with the right digest of the secret.
518        let probe = CodeAnchor {
519            path: ".env".into(),
520            symbol: None,
521            digest: digest(b"API_KEY=abc\n"),
522            lang: None,
523        };
524        let wrong = CodeAnchor {
525            digest: digest(b"API_KEY=xyz\n"),
526            ..probe.clone()
527        };
528        let mut guard = GuardedResolver::for_report(root);
529        assert_eq!(guard.resolve(&tracked), Some(AnchorState::Current));
530        // Right or wrong guess, present or not: the same answer, no read.
531        assert_eq!(guard.resolve(&probe), Some(AnchorState::Missing));
532        assert_eq!(guard.resolve(&wrong), Some(AnchorState::Missing));
533        std::fs::remove_file(root.join(".env")).unwrap();
534        assert_eq!(guard.resolve(&probe), Some(AnchorState::Missing));
535        // A tracked file that changes is still seen.
536        std::fs::write(root.join("src/a.md"), "changed\n").unwrap();
537        let mut fresh = GuardedResolver::for_report(root);
538        assert_eq!(fresh.resolve(&tracked), Some(AnchorState::Changed));
539    }
540
541    #[test]
542    fn the_digest_normalises_bom_line_ends_and_trailing_blanks() {
543        assert_eq!(
544            digest(b"\xEF\xBB\xBFfn a() {}  \r\n}\t\r"),
545            digest(b"fn a() {}\n}\n")
546        );
547        assert_ne!(
548            digest(b"  fn a()"),
549            digest(b"fn a()"),
550            "leading blanks count"
551        );
552        assert!(is_digest(&digest(b"")));
553    }
554
555    #[test]
556    fn whole_file_anchors_follow_the_bytes() {
557        let dir = project(&[("src/notes.md", "retry three times\n")]);
558        let anchor = capture(dir.path(), "src/notes.md", None).unwrap();
559        assert_eq!(anchor.path, "src/notes.md");
560        assert_eq!(anchor.lang.as_deref(), Some("md"));
561        assert_eq!(resolve(dir.path(), &anchor), AnchorState::Current);
562        std::fs::write(dir.path().join("src/notes.md"), "retry three times  \r\n").unwrap();
563        assert_eq!(
564            resolve(dir.path(), &anchor),
565            AnchorState::Current,
566            "normalised"
567        );
568        std::fs::write(dir.path().join("src/notes.md"), "retry twice\n").unwrap();
569        assert_eq!(resolve(dir.path(), &anchor), AnchorState::Changed);
570        std::fs::remove_file(dir.path().join("src/notes.md")).unwrap();
571        assert_eq!(resolve(dir.path(), &anchor), AnchorState::Missing);
572    }
573
574    /// C0 1.9 section 3: a whole-file anchor captured from disk carries the
575    /// contract's reference digest for every vector.
576    #[test]
577    fn file_anchors_reproduce_the_contract_digest_vectors() {
578        let vectors: serde_json::Value = serde_json::from_str(include_str!(
579            "../../../crates/lean-ctx-protocol/tests/fixtures/hive/anchor_digest.vectors.json"
580        ))
581        .unwrap();
582        let cases = vectors["cases"].as_array().unwrap();
583        assert!(cases.len() >= 7);
584        for case in cases {
585            let name = case["name"].as_str().unwrap();
586            let input = hex::decode(case["input_hex"].as_str().unwrap()).unwrap();
587            let dir = project(&[]);
588            std::fs::create_dir_all(dir.path().join("src")).unwrap();
589            std::fs::write(dir.path().join("src/case.txt"), &input).unwrap();
590            let anchor = capture(dir.path(), "src/case.txt", None).unwrap();
591            assert_eq!(anchor.digest, case["digest"].as_str().unwrap(), "{name}");
592            assert_eq!(resolve(dir.path(), &anchor), AnchorState::Current, "{name}");
593        }
594    }
595
596    #[cfg(feature = "tree-sitter")]
597    #[test]
598    fn symbol_anchors_cover_only_their_definition() {
599        let source = "/// Retries a webhook.\nfn retry() -> u8 {\n    3\n}\n\nfn other() {}\n";
600        let dir = project(&[("src/hook.rs", source)]);
601        let anchor = capture(dir.path(), "src/hook.rs", Some("retry")).unwrap();
602        assert_eq!(anchor.digest, digest(b"fn retry() -> u8 {\n    3\n}"));
603        // Edits elsewhere, and to the doc comment, leave it current.
604        std::fs::write(
605            dir.path().join("src/hook.rs"),
606            "/// Retries a webhook, with care.\nfn retry() -> u8 {\n    3\n}\n\nfn other() { let _ = 1; }\n",
607        )
608        .unwrap();
609        assert_eq!(resolve(dir.path(), &anchor), AnchorState::Current);
610        std::fs::write(
611            dir.path().join("src/hook.rs"),
612            "fn retry() -> u8 {\n    5\n}\n",
613        )
614        .unwrap();
615        assert_eq!(resolve(dir.path(), &anchor), AnchorState::Changed);
616        assert!(capture(dir.path(), "src/hook.rs", Some("absent")).is_err());
617    }
618
619    #[test]
620    fn paths_stay_inside_the_project_and_follow_the_contract() {
621        let dir = project(&[("a.rs", "fn a() {}\n")]);
622        assert!(capture(dir.path(), "../a.rs", None).is_err());
623        assert!(capture(dir.path(), "/etc/hosts", None).is_err());
624        assert_eq!(anchor_path(dir.path(), "./a.rs").as_deref(), Some("a.rs"));
625        #[cfg(unix)]
626        {
627            let outside = tempfile::tempdir().unwrap();
628            std::fs::write(outside.path().join("secret"), "x").unwrap();
629            std::os::unix::fs::symlink(outside.path().join("secret"), dir.path().join("link"))
630                .unwrap();
631            assert!(
632                capture(dir.path(), "link", None).is_err(),
633                "no symlink out of the checkout"
634            );
635        }
636        for bad in ["", "/a", "./a", "a/", "a//b", "a/../b", "a\\b"] {
637            assert!(check_path(bad).is_err(), "{bad:?}");
638        }
639        let nfd = "cafe\u{301}.md";
640        assert!(check_path(nfd).is_err(), "NFC only");
641        assert!(check_path(&nfd.nfc().collect::<String>()).is_ok());
642    }
643
644    #[test]
645    fn a_fact_carries_sorted_unique_valid_anchors() {
646        let a = |path: &str, symbol: Option<&str>| CodeAnchor {
647            path: path.into(),
648            symbol: symbol.map(str::to_owned),
649            digest: digest(b"x"),
650            lang: None,
651        };
652        let anchors = canonical(vec![
653            a("b.rs", None),
654            a("a.rs", Some("f")),
655            a("a.rs", None),
656            a("a.rs", None),
657        ]);
658        assert_eq!(
659            anchors,
660            vec![a("a.rs", None), a("a.rs", Some("f")), a("b.rs", None)]
661        );
662        assert!(validate_all(&anchors).is_ok());
663        assert!(validate_all(&[a("b.rs", None), a("a.rs", None)]).is_err());
664        assert!(validate_all(&vec![a("a.rs", None); 2]).is_err());
665        assert!(
666            validate_all(
667                &(0..17)
668                    .map(|i| a(&format!("f{i:02}.rs"), None))
669                    .collect::<Vec<_>>()
670            )
671            .is_err()
672        );
673        let mut bad = a("a.rs", Some(" f"));
674        assert!(bad.validate().is_err());
675        bad.symbol = None;
676        bad.lang = Some("Rust".into());
677        assert!(bad.validate().is_err());
678        assert_eq!(parse_spec("src/a.rs::retry"), ("src/a.rs", Some("retry")));
679        assert_eq!(parse_spec("src/a.rs"), ("src/a.rs", None));
680    }
681
682    #[test]
683    fn markdown_sections_nest_by_level_and_skip_fenced_code() {
684        let doc = "# Release\nintro\n## Steps\n1. tag\n```sh\n# not a heading\n```\n## Steps\nagain\n# Notes & More\nend\n";
685        let sections = markdown_sections(doc);
686        let names: Vec<&str> = sections.iter().map(|(n, _)| n.as_str()).collect();
687        assert_eq!(
688            names,
689            ["release", "release/steps", "release/steps#2", "notes-more"]
690        );
691        let span = |name: &str| {
692            let (_, range) = sections.iter().find(|(n, _)| n == name).unwrap();
693            &doc[range.clone()]
694        };
695        assert_eq!(
696            span("release/steps"),
697            "## Steps\n1. tag\n```sh\n# not a heading\n```\n"
698        );
699        assert_eq!(span("notes-more"), "# Notes & More\nend\n");
700        assert!(span("release").starts_with("# Release\n") && span("release").ends_with("again\n"));
701        assert_eq!(heading_slug("  Release & Steps!  "), "release-steps");
702        assert_eq!(heading_slug("Grüße 2"), "grüße-2");
703    }
704
705    #[test]
706    fn a_markdown_section_anchor_ignores_edits_elsewhere() {
707        let dir = project(&[(
708            "docs/release.md",
709            "# Release\n## Steps\n1. tag\n## Notes\nx\n",
710        )]);
711        let anchor = capture(dir.path(), "docs/release.md", Some("release/steps")).unwrap();
712        std::fs::write(
713            dir.path().join("docs/release.md"),
714            "# Release\n## Steps\n1. tag\n## Notes\ny\n",
715        )
716        .unwrap();
717        assert_eq!(resolve(dir.path(), &anchor), AnchorState::Current);
718        std::fs::write(
719            dir.path().join("docs/release.md"),
720            "# Release\n## Notes\ny\n",
721        )
722        .unwrap();
723        assert_eq!(resolve(dir.path(), &anchor), AnchorState::Missing);
724    }
725}