Skip to main content

lean_ctx_protocol/hive/
anchor.rs

1// SPDX-License-Identifier: Apache-2.0
2
3//! Code anchors (C0 1.9): where in the code a fact, or a piece of task
4//! evidence, applies.
5//!
6//! An anchor names a repo-relative `path`, optionally a `symbol` in it, and
7//! the `digest` of what it covered when it was written. The engine resolves
8//! anchors against its local code graph; Hive only stores them.
9//!
10//! The digest (section 3) is [`anchor_digest`] of the covered bytes: the
11//! exact bytes of the symbol's syntax node (without the comments before it),
12//! or of the whole file without a symbol, normalized by
13//! [`normalize_anchor_content`]. `vectors.json` → `anchor_digest` holds the
14//! reference cases every implementation reproduces.
15//!
16//! In sealed vaults anchors travel only inside sealed content: a path or a
17//! symbol name is information too.
18
19use serde::{Deserialize, Serialize};
20use sha2::{Digest, Sha256};
21
22use crate::ValidationError;
23
24/// The covered content as it is hashed: a leading UTF-8 byte-order mark
25/// dropped, every `\r\n` and lone `\r` turned into `\n`, and trailing spaces
26/// and tabs removed from every line. Nothing else changes: indentation,
27/// blank lines and the final newline (or its absence) stay.
28pub fn normalize_anchor_content(content: &[u8]) -> Vec<u8> {
29    let content = content.strip_prefix(b"\xEF\xBB\xBF").unwrap_or(content);
30    let mut lf = Vec::with_capacity(content.len());
31    let mut bytes = content.iter().copied().peekable();
32    while let Some(byte) = bytes.next() {
33        if byte == b'\r' {
34            if bytes.peek() == Some(&b'\n') {
35                bytes.next();
36            }
37            lf.push(b'\n');
38        } else {
39            lf.push(byte);
40        }
41    }
42    let mut out = Vec::with_capacity(lf.len());
43    for (i, line) in lf.split(|b| *b == b'\n').enumerate() {
44        if i > 0 {
45            out.push(b'\n');
46        }
47        let end = line
48            .iter()
49            .rposition(|b| *b != b' ' && *b != b'\t')
50            .map_or(0, |last| last + 1);
51        out.extend_from_slice(&line[..end]);
52    }
53    out
54}
55
56/// `sha256:` + lowercase hex of the normalized content.
57pub fn anchor_digest(content: &[u8]) -> String {
58    let digest = Sha256::digest(normalize_anchor_content(content));
59    let mut out = String::with_capacity(71);
60    out.push_str("sha256:");
61    for byte in digest {
62        out.push_str(&format!("{byte:02x}"));
63    }
64    out
65}
66
67pub const MAX_ANCHOR_PATH_BYTES: usize = 512;
68pub const MAX_ANCHOR_SYMBOL_CHARS: usize = 256;
69pub const MAX_ANCHORS: usize = 16;
70
71/// One code anchor.
72#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
73#[serde(deny_unknown_fields)]
74pub struct CodeAnchorV1 {
75    /// Repo-relative, `/`-separated, NFC; no `.` or `..` segment, no leading
76    /// or trailing `/`.
77    pub path: String,
78    /// Language-neutral qualified name from the code graph
79    /// (`hive::policy::verify_bundle`, `AuthService.verify`); the whole file
80    /// when absent.
81    #[serde(default, skip_serializing_if = "Option::is_none")]
82    pub symbol: Option<String>,
83    /// `sha256:` + 64 lowercase hex over the normalized symbol span (or the
84    /// whole file without a symbol).
85    pub digest: String,
86    /// Tree-sitter language id, a hint only.
87    #[serde(default, skip_serializing_if = "Option::is_none")]
88    pub lang: Option<String>,
89}
90
91/// Characters that could make two paths look alike: every one a text field
92/// refuses ([`super::invisible`]) and, in a path, the joiners as well.
93fn invisible(c: char) -> bool {
94    super::invisible(c) || matches!(c, '\u{200C}' | '\u{200D}')
95}
96
97/// A repo-relative, `/`-separated path without `.` or `..` segments (the
98/// rule for anchors and, 1.9 section 8, the code graph). 1.9 R3: no `:`
99/// (drive letters, alternate data streams) and no invisible format
100/// characters.
101pub fn validate_anchor_path(path: &str) -> Result<(), ValidationError> {
102    if path.is_empty()
103        || path.len() > MAX_ANCHOR_PATH_BYTES
104        || path.starts_with('/')
105        || path.ends_with('/')
106        || path.contains('\\')
107        || path.contains(':')
108        || path.chars().any(|c| c.is_control() || invisible(c))
109        || path
110            .split('/')
111            .any(|part| part.is_empty() || part == "." || part == "..")
112    {
113        return Err(ValidationError::new(
114            "anchor path must be a normalized repo-relative path",
115        ));
116    }
117    Ok(())
118}
119
120impl CodeAnchorV1 {
121    pub fn validate(&self) -> Result<(), ValidationError> {
122        validate_anchor_path(&self.path)?;
123        if let Some(symbol) = &self.symbol
124            && (symbol.is_empty()
125                || symbol.chars().count() > MAX_ANCHOR_SYMBOL_CHARS
126                || symbol.trim() != symbol
127                || symbol.chars().any(char::is_control))
128        {
129            return Err(ValidationError::new(
130                "anchor symbol must be 1-256 characters without surrounding spaces",
131            ));
132        }
133        let hex = self
134            .digest
135            .strip_prefix("sha256:")
136            .ok_or_else(|| ValidationError::new("anchor digest must start with sha256:"))?;
137        super::validate_hex64(hex, "anchor digest")?;
138        if let Some(lang) = &self.lang
139            && (lang.is_empty()
140                || lang.len() > 32
141                || !lang
142                    .bytes()
143                    .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_'))
144        {
145            return Err(ValidationError::new(
146                "anchor lang must be 1-32 characters of [a-z0-9_]",
147            ));
148        }
149        Ok(())
150    }
151}
152
153/// A list of anchors: at most [`MAX_ANCHORS`], sorted by `(path, symbol)`
154/// (no symbol first), without repeats.
155pub fn validate_anchors(anchors: &[CodeAnchorV1]) -> Result<(), ValidationError> {
156    if anchors.len() > MAX_ANCHORS {
157        return Err(ValidationError::new(format!(
158            "at most {MAX_ANCHORS} anchors"
159        )));
160    }
161    for (i, anchor) in anchors.iter().enumerate() {
162        anchor.validate()?;
163        if i > 0 {
164            let prev = &anchors[i - 1];
165            if (prev.path.as_str(), prev.symbol.as_deref())
166                >= (anchor.path.as_str(), anchor.symbol.as_deref())
167            {
168                return Err(ValidationError::new(
169                    "anchors must be sorted by path and symbol without repeats",
170                ));
171            }
172        }
173    }
174    Ok(())
175}
176
177#[cfg(test)]
178mod tests {
179    use super::*;
180
181    fn anchor(path: &str, symbol: Option<&str>) -> CodeAnchorV1 {
182        CodeAnchorV1 {
183            path: path.into(),
184            symbol: symbol.map(Into::into),
185            digest: format!("sha256:{}", "a".repeat(64)),
186            lang: None,
187        }
188    }
189
190    #[test]
191    fn paths_are_normalized_and_repo_relative() {
192        assert!(
193            anchor("src/retry.rs", Some("retry::budget"))
194                .validate()
195                .is_ok()
196        );
197        for bad in [
198            "/etc/x",
199            "src/",
200            "a//b",
201            "./a",
202            "a/../b",
203            "a\\b",
204            "",
205            "C:/x",
206            "a.txt:stream",
207            "a\u{202E}b",
208        ] {
209            assert!(anchor(bad, None).validate().is_err(), "{bad}");
210        }
211    }
212
213    #[test]
214    fn anchor_lists_are_sorted_without_repeats() {
215        let a = anchor("a.rs", None);
216        let a_sym = anchor("a.rs", Some("f"));
217        let b = anchor("b.rs", None);
218        assert!(validate_anchors(&[a.clone(), a_sym.clone(), b.clone()]).is_ok());
219        assert!(validate_anchors(&[a_sym.clone(), a.clone()]).is_err());
220        assert!(validate_anchors(&[b.clone(), b]).is_err());
221    }
222}