agent_hub_runtime/core/content_hash.rs
1use anyhow::{Context, Result};
2use sha2::{Digest, Sha256};
3use std::borrow::Cow;
4use std::path::{Path, PathBuf};
5use walkdir::WalkDir;
6
7const IGNORED: &[&str] = &[".git", ".gitignore"];
8
9/// Generated caches and OS metadata that need no delivery or removal warning.
10pub(crate) fn is_regenerable(name: &str) -> bool {
11 matches!(name, "__pycache__" | ".DS_Store" | "Thumbs.db") || name.ends_with(".pyc")
12}
13
14/// True for names excluded from a skill's content scope: the exact-match
15/// [`IGNORED`] entries plus [`is_regenerable`] artifacts. Python caches are
16/// regenerated whenever a skill's Python scripts run, so without excluding
17/// them a copy-mode deployment would read as permanently "changed" against
18/// the library the first time the skill is used.
19fn is_ignored(name: &str) -> bool {
20 IGNORED.contains(&name) || is_regenerable(name)
21}
22
23/// Dependency installs (`npm install`, a Python venv) inside a skill. They stay
24/// in the content hash — a directory that holds them is not interchangeable
25/// with one that doesn't, and repairs that replace a directory on hash
26/// equality must keep seeing the difference. Only the update-check tiebreaker
27/// ([`hash_directory_eol_insensitive`]) looks past them (#502). The cost is
28/// that an edit to a file a skill keeps under a directory with one of these
29/// names goes unnoticed by that tiebreaker — nobody authors skill files there.
30const DEPENDENCY_DIRS: &[&str] = &["node_modules", ".venv", "venv"];
31
32/// One file in a skill's canonical "content scope" — the set of files that
33/// both [`hash_directory`] and the source-diff command operate on. Sharing
34/// this enumeration keeps the update badge and the diff from ever
35/// disagreeing about which files count.
36pub struct ContentEntry {
37 /// Path relative to the scanned directory, in the same lossy form the
38 /// hash consumes (keeps the hashed byte stream stable).
39 pub relative_path: String,
40 pub path: PathBuf,
41 /// `mode & 0o111` on unix when metadata is readable, else `None`.
42 /// Always `None` on non-unix. `None` means "not folded into the hash".
43 pub exec_bits: Option<u32>,
44 /// Modification time in ms since the Unix epoch, captured during the walk
45 /// so callers don't need a second `metadata()` syscall (or a separate
46 /// recursive walk) just to learn when the content last changed.
47 pub modified_ms: Option<i64>,
48}
49
50impl ContentEntry {
51 pub fn is_executable(&self) -> bool {
52 self.exec_bits.is_some_and(|bits| bits != 0)
53 }
54}
55
56#[cfg(unix)]
57fn exec_bits_of(path: &Path) -> Option<u32> {
58 use std::os::unix::fs::PermissionsExt;
59 path.metadata().ok().map(|m| m.permissions().mode() & 0o111)
60}
61
62#[cfg(not(unix))]
63fn exec_bits_of(_path: &Path) -> Option<u32> {
64 None
65}
66
67/// Enumerate the files that make up a skill's content, sorted by path and
68/// filtered by the shared ignore-list. Single source of truth for "what is
69/// skill content"; hashing and diffing both build on it.
70///
71/// Traversal errors are dropped, so an unreadable subdirectory reads as absent.
72/// Callers that must not mistake "could not look" for "not there" want
73/// [`list_content_files_strict`] instead.
74pub fn list_content_files(dir: &Path) -> Vec<ContentEntry> {
75 // The lossy walk cannot fail: every error is skipped below.
76 walk_content_files(dir, false, false).unwrap_or_default()
77}
78
79/// [`list_content_files`] over the same content scope, but a directory that
80/// cannot be traversed is an error rather than an empty one.
81pub fn list_content_files_strict(dir: &Path) -> Result<Vec<ContentEntry>> {
82 walk_content_files(dir, true, false)
83}
84
85fn walk_content_files(dir: &Path, strict: bool, skip_deps: bool) -> Result<Vec<ContentEntry>> {
86 let mut entries = Vec::new();
87 for result in WalkDir::new(dir).into_iter().filter_entry(|e| {
88 let name = e.file_name().to_string_lossy();
89 !is_ignored(&name)
90 && !(skip_deps
91 && e.depth() > 0
92 && e.file_type().is_dir()
93 && DEPENDENCY_DIRS.contains(&name.as_ref()))
94 }) {
95 match result {
96 Ok(entry) if entry.file_type().is_file() => entries.push(entry),
97 Ok(_) => {}
98 Err(err) if strict => {
99 return Err(
100 anyhow::Error::new(err).context(format!("failed to walk {}", dir.display()))
101 );
102 }
103 Err(_) => {}
104 }
105 }
106
107 entries.sort_by(|a, b| a.path().cmp(b.path()));
108
109 let mapped = entries
110 .into_iter()
111 .map(|entry| {
112 let relative_path = entry
113 .path()
114 .strip_prefix(dir)
115 .unwrap_or(entry.path())
116 .to_string_lossy()
117 .into_owned();
118 // Normalize Windows separators to `/` so the hashed byte
119 // stream is identical across platforms — otherwise Windows
120 // feeds `sub\c.md` into the hash and disagrees with every
121 // other OS about the same content. Windows-only because `\`
122 // is a legal filename character on unix.
123 #[cfg(windows)]
124 let relative_path = relative_path.replace('\\', "/");
125 let exec_bits = exec_bits_of(entry.path());
126 // Reuse WalkDir's already-fetched metadata for the mtime: no extra
127 // stat, and no separate recursive walk to answer "last modified?".
128 let modified_ms = entry
129 .metadata()
130 .ok()
131 .and_then(|m| m.modified().ok())
132 .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
133 .map(|d| d.as_millis() as i64);
134 ContentEntry {
135 relative_path,
136 path: entry.into_path(),
137 exec_bits,
138 modified_ms,
139 }
140 })
141 .collect();
142 Ok(mapped)
143}
144
145/// Hash a prepared content-file list. Split out from [`hash_directory`] so a
146/// caller that already walked the tree (via [`list_content_files`]) can hash
147/// and inspect the same entries without walking again (#248).
148pub fn hash_entries(entries: &[ContentEntry]) -> String {
149 let mut hasher = Sha256::new();
150 for entry in entries {
151 hasher.update(entry.relative_path.as_bytes());
152 if let Ok(content) = std::fs::read(&entry.path) {
153 hasher.update(&content);
154 }
155 // Include executable bit so permission-only changes are detected.
156 #[cfg(unix)]
157 if let Some(bits) = entry.exec_bits {
158 hasher.update(bits.to_le_bytes());
159 }
160 }
161 hex::encode(hasher.finalize())
162}
163
164/// Latest content-file modification time (ms since epoch) from a prepared
165/// entry list. Scoped to the same files the hash covers: dirs, `.git`,
166/// `.DS_Store`, and `*.pyc` are excluded, so it reflects real content change.
167pub fn latest_modified_ms(entries: &[ContentEntry]) -> Option<i64> {
168 entries.iter().filter_map(|e| e.modified_ms).max()
169}
170
171pub fn hash_directory(dir: &Path) -> Result<String> {
172 Ok(hash_entries(&list_content_files(dir)))
173}
174
175/// True when `content` is text this may safely fold: valid UTF-8 with no NUL.
176///
177/// Both halves are needed, and both are deliberately stricter than git's
178/// heuristic (a NUL in the first 8000 bytes). Git is deciding how to *display*
179/// a file; this decides whether two files are the same, so every wrong answer
180/// here hides a real change:
181/// - a binary whose first NUL falls past byte 8000 is text to git, and two such
182/// files differing by one `\r` would fold into each other;
183/// - a binary with no NUL at all (`FF 0D 0A` vs `FF 0A`) passes any NUL test,
184/// so "no NUL" cannot establish text on its own.
185///
186/// Requiring valid UTF-8 draws the line at a representation whose `\r\n` really
187/// is a line ending. It also means text in a non-UTF-8 encoding is treated as
188/// binary and its line endings are not folded — that direction is the safe one:
189/// an update is offered that may not be needed, rather than a real one hidden.
190fn is_foldable_text(content: &[u8]) -> bool {
191 !content.contains(&0) && std::str::from_utf8(content).is_ok()
192}
193
194/// Fold CRLF line endings to LF in content [`is_foldable_text`] accepts;
195/// everything else is returned untouched.
196///
197/// The guarantee is bounded, and worth stating exactly: content that fails that
198/// test is never folded, so the `FF 0D 0A` / `FF 0A` class of binary cannot
199/// normalize together. It is *not* a claim that no two meaningfully different
200/// files can — a file that is valid UTF-8 and NUL-free is folded whether or not
201/// its `\r\n` carries meaning (a fixture asserting CRLF handling, say). Drawing
202/// the line anywhere admits some such file; this one is drawn where `\r\n`
203/// almost always is a line ending.
204///
205/// A lone `\r` (old-Mac line ending, or a carriage return inside a progress
206/// bar) is left alone — only `\r\n` is a line ending both platforms mean the
207/// same thing by.
208fn fold_crlf(content: &[u8]) -> Cow<'_, [u8]> {
209 if !is_foldable_text(content) || !content.windows(2).any(|pair| pair == b"\r\n") {
210 return Cow::Borrowed(content);
211 }
212 let mut folded = Vec::with_capacity(content.len());
213 let mut index = 0;
214 while index < content.len() {
215 if content[index] == b'\r' && content.get(index + 1) == Some(&b'\n') {
216 index += 1; // drop the CR, keep the LF the next iteration copies
217 continue;
218 }
219 folded.push(content[index]);
220 index += 1;
221 }
222 Cow::Owned(folded)
223}
224
225/// Hash the same content scope as [`hash_entries`], with CRLF folded to LF in
226/// text files.
227///
228/// This is a **tiebreaker, not a replacement**: [`hash_entries`] stays the
229/// stored, byte-exact identity of a skill, and this is only consulted once two
230/// byte hashes already disagree, to answer the narrower question "do these two
231/// trees differ by anything other than line endings?".
232///
233/// It exists because a skill that reaches one machine through a git checkout
234/// and another through our own byte copy legitimately holds the same content in
235/// two encodings: Git for Windows defaults to `core.autocrlf=true`, so the same
236/// file is CRLF there and LF on macOS. Nothing is wrong in that case and the
237/// user must not be told there is an update.
238///
239/// Unlike [`hash_entries`], an unreadable file is an **error, not an empty
240/// file**. The two differ in what a wrong answer costs: a byte hash that cannot
241/// read a file reports "changed" and the user is offered an update they may not
242/// need, while this function's answer *suppresses* an update, so a file it
243/// could not read must never be quietly treated as matching the other side.
244///
245/// Each field is length-framed, where [`hash_entries`] concatenates a path
246/// directly onto its content. Unframed, a rename that shifts bytes across the
247/// boundary collides: `ab` holding `c\n` and `a` holding `bc\r\n` both feed
248/// `abc\n` into the hasher, so a removed file, an added file and a content
249/// change all read as "no difference". `hash_entries` shares that flaw and is
250/// deliberately left alone — it is the stored identity of every skill, and
251/// reframing it would invalidate every hash on disk.
252pub fn hash_entries_eol_insensitive(entries: &[ContentEntry]) -> Result<String> {
253 let mut hasher = Sha256::new();
254 for entry in entries {
255 let path = entry.relative_path.as_bytes();
256 hasher.update((path.len() as u64).to_le_bytes());
257 hasher.update(path);
258 let content = std::fs::read(&entry.path)
259 .with_context(|| format!("failed to read {}", entry.path.display()))?;
260 let folded = fold_crlf(&content);
261 hasher.update((folded.len() as u64).to_le_bytes());
262 hasher.update(folded.as_ref());
263 // Kept in step with `hash_entries`: a permission-only change is still
264 // a change, and must not hide behind the line-ending comparison.
265 #[cfg(unix)]
266 if let Some(bits) = entry.exec_bits {
267 hasher.update(bits.to_le_bytes());
268 }
269 }
270 Ok(hex::encode(hasher.finalize()))
271}
272
273/// [`hash_entries_eol_insensitive`] over a directory, enumerated strictly.
274///
275/// Two refusals rather than an answer, both because this function's answer can
276/// only ever *suppress* an update:
277/// - a directory that cannot be traversed is an error, not an absent one —
278/// otherwise two trees whose unreadable subtrees hold different files would
279/// match on what remains;
280/// - an empty or missing directory is an error, not "the hash of nothing",
281/// which every empty tree would share.
282///
283/// Dependency installs ([`DEPENDENCY_DIRS`]) are skipped as well: `npm install`
284/// in a local skill's source is not an update to offer (#502).
285pub fn hash_directory_eol_insensitive(dir: &Path) -> Result<String> {
286 let entries = walk_content_files(dir, true, true)?;
287 if entries.is_empty() {
288 anyhow::bail!("no content files under {}", dir.display());
289 }
290 hash_entries_eol_insensitive(&entries)
291}
292
293#[cfg(test)]
294mod tests;