lean_ctx_protocol/hive/
anchor.rs1use serde::{Deserialize, Serialize};
20use sha2::{Digest, Sha256};
21
22use crate::ValidationError;
23
24pub 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
56pub 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#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
73#[serde(deny_unknown_fields)]
74pub struct CodeAnchorV1 {
75 pub path: String,
78 #[serde(default, skip_serializing_if = "Option::is_none")]
82 pub symbol: Option<String>,
83 pub digest: String,
86 #[serde(default, skip_serializing_if = "Option::is_none")]
88 pub lang: Option<String>,
89}
90
91fn invisible(c: char) -> bool {
94 super::invisible(c) || matches!(c, '\u{200C}' | '\u{200D}')
95}
96
97pub 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
153pub 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}