//! Deterministic source discovery and snapshot construction. //! //! Rules implemented here (development specification §6 and §13): //! * explicit root, never an implicit parent/HOME/cache/network scan; //! * only `.md`/`.mq.md`, sorted by byte-wise root-relative path; //! * skip `.git`, `.marqdo`, `target`, `node_modules`, hidden entries and //! symlinks (reported, never followed); //! * exact UTF-8 bytes and SHA-256 digests, per-file/total/document budgets; //! * root-relative path validation for every discovered and referenced path; //! * `marqdo.yaml` / `marqdo.lock` captured as inputs when present. use super::{AssetFile, InputKind, InputRecord, Limits, Scope, SourceFile, SourceSnapshot}; use crate::diagnostic::{code, Diagnostic, DiagnosticSet}; use crate::error::KnowledgeError; use crate::model::{sha256_prefixed, DocumentFormat}; use std::path::{Component, Path, PathBuf}; /// Directories that are never knowledge content. const SKIPPED_DIRS: [&str; 4] = [".git", ".marqdo", "target", "node_modules"]; /// Files larger than this are never read for asset digests. const ASSET_DIGEST_BUDGET: u64 = 8 * 1024 * 1024; /// Resolve and validate the user-selected root and exclusions. pub fn resolve_scope(input: &Path, excludes: &[String]) -> Result { if excludes.len() > 256 { return Err(KnowledgeError::usage( "at most 256 --exclude patterns are accepted", )); } let mut patterns = Vec::with_capacity(excludes.len()); for pattern in excludes { let trimmed = pattern.trim(); if trimmed.is_empty() { return Err(KnowledgeError::usage("--exclude must not be empty")); } if trimmed.starts_with('/') || trimmed.starts_with('\\') || trimmed.contains('\\') { return Err(KnowledgeError::usage(format!( "--exclude `{pattern}` must be a root-relative glob with `/` separators" ))); } if trimmed.split('/').any(|segment| segment == "..") { return Err(KnowledgeError::usage(format!( "--exclude `{pattern}` must not contain `..` segments" ))); } let parsed = glob::Pattern::new(trimmed).map_err(|error| { KnowledgeError::usage(format!( "--exclude `{pattern}` is not a valid glob: {error}" )) })?; patterns.push(parsed); } let metadata = std::fs::symlink_metadata(input).map_err(|error| { KnowledgeError::environment( code::INVALID_ROOT, format!("knowledge root cannot be read: {error}"), ) })?; if metadata.file_type().is_symlink() { return Err(KnowledgeError::environment( code::SCOPE_ESCAPE, "knowledge root must not be a symbolic link", )); } let canonical = std::fs::canonicalize(input).map_err(|error| { KnowledgeError::environment( code::INVALID_ROOT, format!("knowledge root cannot be resolved: {error}"), ) })?; let mut single_file = None; let root = if metadata.is_file() { if DocumentFormat::from_path(&file_name_string(&canonical)?).is_none() { return Err(KnowledgeError::usage( "a single-file root must be a .md or .mq.md document", )); } let name = file_name_string(&canonical)?; single_file = Some(name); canonical .parent() .map(Path::to_path_buf) .ok_or_else(|| KnowledgeError::usage("cannot determine the parent directory"))? } else if metadata.is_dir() { canonical } else { return Err(KnowledgeError::environment( code::INVALID_ROOT, "knowledge root must be a directory or a Markdown file", )); }; Ok(Scope { root, single_file, excludes: excludes.to_vec(), patterns, limits: Limits::default(), }) } fn file_name_string(path: &Path) -> Result { path.file_name() .and_then(|name| name.to_str()) .map(str::to_string) .ok_or_else(|| KnowledgeError::usage("knowledge path is not valid UTF-8")) } /// Walk the scope and read the exact source snapshot. pub fn discover(scope: &Scope) -> Result { let mut diagnostics = DiagnosticSet::new(); let mut files = Vec::new(); let mut total_bytes = 0u64; if let Some(single) = &scope.single_file { validate_relative_path(single).map_err(|message| { KnowledgeError::environment(code::SCOPE_ESCAPE, format!("invalid root file: {message}")) })?; let abs = scope.root.join(single); if let Some(file) = read_document(scope, &abs, single, &mut diagnostics)? { total_bytes += file.len(); files.push(file); } } else { walk( scope, &scope.root, "", &mut files, &mut diagnostics, &mut total_bytes, )?; } if files.len() > scope.limits.documents { diagnostics.push(Diagnostic::error( code::BUDGET_EXCEEDED, format!( "document count {} exceeds the {} document budget", files.len(), scope.limits.documents ), )); } files.sort_by(|a, b| a.rel_path.cmp(&b.rel_path)); if files .windows(2) .any(|pair| pair[0].rel_path == pair[1].rel_path) { return Err(KnowledgeError::environment( code::INTERNAL, "discovery produced duplicate root-relative paths", )); } let manifest = read_optional_input(scope, "marqdo.yaml", InputKind::Manifest, &mut diagnostics)?; let lock = read_optional_input(scope, "marqdo.lock", InputKind::Lock, &mut diagnostics)?; Ok(SourceSnapshot { scope: scope.clone(), files, assets: Vec::new(), manifest, lock, diagnostics, total_bytes, }) } fn walk( scope: &Scope, dir: &Path, rel_dir: &str, files: &mut Vec, diagnostics: &mut DiagnosticSet, total_bytes: &mut u64, ) -> Result<(), KnowledgeError> { let entries = match std::fs::read_dir(dir) { Ok(entries) => entries, Err(error) => { diagnostics.push(Diagnostic::warning( code::IO, format!("directory cannot be read and was skipped: {error}"), )); return Ok(()); } }; let mut entries: Vec<_> = entries .filter_map(|entry| match entry { Ok(entry) => Some(entry), Err(error) => { diagnostics.push(Diagnostic::warning( code::IO, format!("directory entry cannot be read and was skipped: {error}"), )); None } }) .collect(); entries.sort_by_key(|entry| entry.file_name()); for entry in entries { let name = entry.file_name(); let Some(name) = name.to_str() else { diagnostics.push(Diagnostic::warning( code::IO, "non-UTF-8 file name was skipped", )); continue; }; let rel_path = if rel_dir.is_empty() { name.to_string() } else { format!("{rel_dir}/{name}") }; let metadata = match std::fs::symlink_metadata(entry.path()) { Ok(metadata) => metadata, Err(error) => { diagnostics.push( Diagnostic::warning(code::IO, format!("entry cannot be inspected: {error}")) .with_path(&rel_path), ); continue; } }; if metadata.file_type().is_symlink() { diagnostics.push( Diagnostic::warning( code::SYMLINK_SKIPPED, "symbolic links are not followed and were skipped", ) .with_path(&rel_path), ); continue; } if name.starts_with('.') { continue; } if metadata.is_dir() { if SKIPPED_DIRS.contains(&name) { continue; } if is_excluded(scope, &rel_path, true) { continue; } validate_relative_path(&rel_path) .map_err(|message| KnowledgeError::environment(code::SCOPE_ESCAPE, message))?; walk( scope, &entry.path(), &rel_path, files, diagnostics, total_bytes, )?; continue; } if !metadata.is_file() { continue; } if DocumentFormat::from_path(name).is_none() { // Non-Markdown files are only read when a document references them. continue; } if is_excluded(scope, &rel_path, false) { diagnostics.push( Diagnostic::warning(code::EXCLUDED_PATH, "excluded by --exclude") .with_path(&rel_path), ); continue; } validate_relative_path(&rel_path) .map_err(|message| KnowledgeError::environment(code::SCOPE_ESCAPE, message))?; if let Some(file) = read_document(scope, &entry.path(), &rel_path, diagnostics)? { *total_bytes += file.len(); if *total_bytes > scope.limits.total_source { diagnostics.push(Diagnostic::error( code::BUDGET_EXCEEDED, format!( "total source bytes exceed the {} byte budget", scope.limits.total_source ), )); return Ok(()); } files.push(file); } } Ok(()) } fn is_excluded(scope: &Scope, rel_path: &str, is_dir: bool) -> bool { scope.patterns.iter().any(|pattern| { if pattern.matches(rel_path) { return true; } if is_dir { // `vendor/**` should prune `vendor` itself as well. let with_marker = format!("{rel_path}/x"); return pattern.matches(&with_marker); } false }) } fn read_document( scope: &Scope, abs_path: &Path, rel_path: &str, diagnostics: &mut DiagnosticSet, ) -> Result, KnowledgeError> { let metadata = std::fs::symlink_metadata(abs_path).map_err(|error| { KnowledgeError::environment( code::IO, format!("document cannot be inspected ({rel_path}): {error}"), ) })?; if metadata.file_type().is_symlink() { diagnostics.push( Diagnostic::warning( code::SYMLINK_SKIPPED, "symbolic links are not followed and were skipped", ) .with_path(rel_path), ); return Ok(None); } if !metadata.is_file() { return Ok(None); } if metadata.len() > scope.limits.per_file { diagnostics.push( Diagnostic::error( code::BUDGET_EXCEEDED, format!( "document is {} bytes, above the {} byte per-file budget", metadata.len(), scope.limits.per_file ), ) .with_path(rel_path), ); return Ok(None); } let bytes = std::fs::read(abs_path).map_err(|error| { KnowledgeError::environment( code::IO, format!("document cannot be read ({rel_path}): {error}"), ) })?; if bytes.len() as u64 > scope.limits.per_file { diagnostics.push( Diagnostic::error( code::BUDGET_EXCEEDED, "document grew above the per-file budget while reading", ) .with_path(rel_path), ); return Ok(None); } // Re-check identity after reading to avoid publishing a mixed snapshot. if let Ok(after) = std::fs::metadata(abs_path) { if after.len() != bytes.len() as u64 { diagnostics.push( Diagnostic::error( code::SOURCE_CHANGED, "document changed while being read; snapshot aborted", ) .with_path(rel_path), ); return Ok(None); } } let text = match String::from_utf8(bytes) { Ok(text) => text, Err(_) => { diagnostics.push( Diagnostic::error( code::INVALID_UTF8, "document is not valid UTF-8; it was not indexed", ) .with_path(rel_path), ); return Ok(None); } }; let format = DocumentFormat::from_path(rel_path).ok_or_else(|| { KnowledgeError::internal(format!("document `{rel_path}` has no supported format")) })?; Ok(Some(SourceFile { rel_path: rel_path.to_string(), abs_path: abs_path.to_path_buf(), format, digest: sha256_prefixed(text.as_bytes()), text, })) } fn read_optional_input( scope: &Scope, rel_path: &str, kind: InputKind, diagnostics: &mut DiagnosticSet, ) -> Result, KnowledgeError> { let abs = scope.root.join(rel_path); let metadata = match std::fs::symlink_metadata(&abs) { Ok(metadata) => metadata, Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None), Err(error) => { return Err(KnowledgeError::environment( code::IO, format!("{rel_path} cannot be inspected: {error}"), )); } }; if metadata.file_type().is_symlink() { diagnostics.push( Diagnostic::warning( code::SYMLINK_SKIPPED, "symbolic links are not followed and were skipped", ) .with_path(rel_path), ); return Ok(None); } if !metadata.is_file() { diagnostics.push( Diagnostic::warning(code::IO, "input is not a regular file and was skipped") .with_path(rel_path), ); return Ok(None); } if metadata.len() > scope.limits.manifest { diagnostics.push( Diagnostic::error( code::BUDGET_EXCEEDED, format!( "input is above the {} byte manifest budget", scope.limits.manifest ), ) .with_path(rel_path), ); return Ok(None); } let bytes = std::fs::read(&abs).map_err(|error| { KnowledgeError::environment(code::IO, format!("{rel_path} cannot be read: {error}")) })?; Ok(Some(InputRecord { path: rel_path.to_string(), kind, digest: sha256_prefixed(&bytes), size: bytes.len() as u64, })) } /// Read a referenced local asset within the root. Returns `None` when the path /// does not name a regular file inside the root; symlinks and escapes are /// rejected, never followed. pub fn read_asset(scope: &Scope, rel_path: &str) -> Result, KnowledgeError> { if validate_relative_path(rel_path).is_err() { return Ok(None); } let abs = scope.root.join(rel_path); let metadata = match std::fs::symlink_metadata(&abs) { Ok(metadata) => metadata, Err(_) => return Ok(None), }; if metadata.file_type().is_symlink() || !metadata.is_file() { return Ok(None); } let size = metadata.len(); let digest = if size <= ASSET_DIGEST_BUDGET { match std::fs::read(&abs) { Ok(bytes) => Some(sha256_prefixed(&bytes)), Err(_) => return Ok(None), } } else { None }; Ok(Some(AssetFile { rel_path: rel_path.to_string(), size, digest, })) } /// Validate a root-relative path using only syntactic rules: no absolute path, /// drive/UNC prefix, backslash, empty/`.`/`..` segment, NUL or trailing slash. pub fn validate_relative_path(rel_path: &str) -> Result<(), String> { if rel_path.is_empty() { return Err("path is empty".to_string()); } if rel_path.len() > 4096 { return Err("path exceeds 4096 bytes".to_string()); } if rel_path.contains('\0') { return Err("path contains a NUL byte".to_string()); } if rel_path.contains('\\') { return Err(format!("path `{rel_path}` contains a backslash")); } if rel_path.starts_with('/') { return Err(format!("path `{rel_path}` is absolute")); } if rel_path.len() >= 2 && rel_path.as_bytes()[1] == b':' { return Err(format!("path `{rel_path}` uses a drive prefix")); } if rel_path.ends_with('/') { return Err(format!("path `{rel_path}` ends with a separator")); } for segment in rel_path.split('/') { if segment.is_empty() { return Err(format!("path `{rel_path}` contains an empty segment")); } if segment == "." || segment == ".." { return Err(format!("path `{rel_path}` contains a `{segment}` segment")); } } // Reject control characters (including NUL already checked). if rel_path.chars().any(|c| c.is_control()) { return Err(format!("path `{rel_path}` contains control characters")); } Ok(()) } /// Resolve a link target relative to the directory of `from_doc`, then validate /// and normalise it into a root-relative path. Returns `Err` when the target /// escapes the root or is syntactically unsafe. pub fn resolve_link_path(from_doc: &str, raw_target: &str) -> Result { if raw_target.is_empty() { return Err("target is empty".to_string()); } if raw_target.contains('\0') { return Err("target contains a NUL byte".to_string()); } if raw_target.contains('\\') { return Err("target contains a backslash".to_string()); } let is_absolute = raw_target.starts_with('/') || (raw_target.len() >= 2 && raw_target.as_bytes()[1] == b':'); if is_absolute { return Err("target is an absolute path".to_string()); } let mut stack: Vec<&str> = if from_doc.is_empty() { Vec::new() } else { let mut segments: Vec<&str> = from_doc.split('/').collect(); segments.pop(); segments }; for segment in raw_target.split('/') { match segment { "" => return Err("target contains an empty segment".to_string()), "." => continue, ".." => { if stack.pop().is_none() { return Err("target escapes the knowledge root".to_string()); } } other => { if other.chars().any(|c| c.is_control()) { return Err("target contains control characters".to_string()); } stack.push(other); } } } let joined = stack.join("/"); validate_relative_path(&joined).map_err(|message| format!("invalid target: {message}"))?; Ok(joined) } /// Convert an absolute path to a normalised relative `Path` for messages and /// internal comparisons. Only used after the path was validated. pub fn relative_components(rel_path: &str) -> Vec { rel_path .split('/') .filter(|segment| !segment.is_empty()) .map(str::to_string) .collect() } /// Join without allowing any unsafe component. Returns `None` for invalid /// input; callers must have validated already. pub fn safe_join(root: &Path, rel_path: &str) -> Option { if validate_relative_path(rel_path).is_err() { return None; } let mut path = root.to_path_buf(); for component in Path::new(rel_path).components() { match component { Component::Normal(part) => path.push(part), _ => return None, } } Some(path) } #[cfg(test)] mod tests { use super::*; use std::io::Write; fn write_file(root: &Path, rel: &str, content: &str) { let path = root.join(rel); if let Some(parent) = path.parent() { std::fs::create_dir_all(parent).unwrap(); } let mut file = std::fs::File::create(path).unwrap(); file.write_all(content.as_bytes()).unwrap(); } fn scope_for(root: &Path, excludes: &[String]) -> Scope { resolve_scope(root, excludes).unwrap() } #[test] fn discovery_is_sorted_and_skips_generated_and_hidden_entries() { let temp = tempfile::tempdir().unwrap(); let root = temp.path(); write_file(root, "b.md", "# B\n"); write_file(root, "a/z.md", "# Z\n"); write_file(root, "a/a.mq.md", "# A\n"); write_file(root, ".hidden.md", "# hidden\n"); write_file(root, ".git/x.md", "# git\n"); write_file(root, "target/y.md", "# target\n"); write_file(root, "node_modules/n.md", "# nm\n"); write_file(root, "notes.txt", "not markdown\n"); let snapshot = discover(&scope_for(root, &[])).unwrap(); let paths: Vec<_> = snapshot.files.iter().map(|f| f.rel_path.as_str()).collect(); assert_eq!(paths, vec!["a/a.mq.md", "a/z.md", "b.md"]); assert_eq!(snapshot.files[1].format, DocumentFormat::PlainMarkdown); assert_eq!(snapshot.files[0].format, DocumentFormat::Marqdo); } #[test] fn excludes_remove_files_and_prune_directories() { let temp = tempfile::tempdir().unwrap(); let root = temp.path(); write_file(root, "keep.md", "# keep\n"); write_file(root, "vendor/x.md", "# x\n"); write_file(root, "draft/a.md", "# a\n"); let snapshot = discover(&scope_for( root, &["vendor/**".to_string(), "draft/*.md".to_string()], )) .unwrap(); let paths: Vec<_> = snapshot.files.iter().map(|f| f.rel_path.as_str()).collect(); assert_eq!(paths, vec!["keep.md"]); assert!(snapshot .diagnostics .iter() .any(|d| d.code == code::EXCLUDED_PATH)); } #[test] fn exact_bytes_and_digests_are_preserved() { let temp = tempfile::tempdir().unwrap(); let root = temp.path(); let content = "\u{feff}# 标题\r\n\r\nbody 😀\r\n"; write_file(root, "doc.md", content); let snapshot = discover(&scope_for(root, &[])).unwrap(); let file = &snapshot.files[0]; assert_eq!(file.text, content); assert_eq!(file.digest, sha256_prefixed(content.as_bytes())); assert_eq!(snapshot.snapshot_digest().len(), 71); } #[test] fn invalid_utf8_is_a_blocking_diagnostic() { let temp = tempfile::tempdir().unwrap(); let root = temp.path(); std::fs::write(root.join("bad.md"), [0xff, 0xfe, 0x00]).unwrap(); let snapshot = discover(&scope_for(root, &[])).unwrap(); assert!(snapshot.files.is_empty()); assert!(snapshot .diagnostics .iter() .any(|d| d.code == code::INVALID_UTF8 && d.is_error())); } #[test] fn single_file_scope_indexes_only_that_file() { let temp = tempfile::tempdir().unwrap(); let root = temp.path(); write_file(root, "one.md", "# one\n"); write_file(root, "two.md", "# two\n"); let scope = resolve_scope(&root.join("one.md"), &[]).unwrap(); assert_eq!(scope.single_file.as_deref(), Some("one.md")); let snapshot = discover(&scope).unwrap(); let paths: Vec<_> = snapshot.files.iter().map(|f| f.rel_path.as_str()).collect(); assert_eq!(paths, vec!["one.md"]); } #[test] fn symlinks_are_skipped_not_followed() { let temp = tempfile::tempdir().unwrap(); let root = temp.path(); write_file(root, "real.md", "# real\n"); #[cfg(unix)] std::os::unix::fs::symlink(root.join("real.md"), root.join("link.md")).unwrap(); let snapshot = discover(&scope_for(root, &[])).unwrap(); let paths: Vec<_> = snapshot.files.iter().map(|f| f.rel_path.as_str()).collect(); assert_eq!(paths, vec!["real.md"]); assert!(snapshot .diagnostics .iter() .any(|d| d.code == code::SYMLINK_SKIPPED)); } #[test] fn path_validation_rejects_traversal_and_absolute_paths() { assert!(validate_relative_path("a/b.md").is_ok()); for bad in [ "", "/etc/passwd", "../x.md", "a/../x.md", "a//b.md", "a\\b.md", "C:/x.md", "a/b.md/", "a/\0/b.md", ] { assert!(validate_relative_path(bad).is_err(), "{bad}"); } assert_eq!( resolve_link_path("dir/doc.md", "../other.md").unwrap(), "other.md" ); assert_eq!( resolve_link_path("dir/doc.md", "./sub/x.md").unwrap(), "dir/sub/x.md" ); assert!(resolve_link_path("doc.md", "../escape.md").is_err()); assert!(resolve_link_path("doc.md", "/abs.md").is_err()); } #[test] fn budgets_are_enforced() { let temp = tempfile::tempdir().unwrap(); let root = temp.path(); write_file(root, "big.md", &"x".repeat(64)); let mut scope = scope_for(root, &[]); scope.limits.per_file = 32; let snapshot = discover(&scope).unwrap(); assert!(snapshot.files.is_empty()); assert!(snapshot .diagnostics .iter() .any(|d| d.code == code::BUDGET_EXCEEDED && d.is_error())); } #[test] fn manifest_and_lock_are_recorded_as_inputs() { let temp = tempfile::tempdir().unwrap(); let root = temp.path(); write_file(root, "doc.md", "# d\n"); write_file( root, "marqdo.yaml", "project: {name: demo, version: 0.1.0}\n", ); write_file(root, "marqdo.lock", "lock-version: 4\n"); let snapshot = discover(&scope_for(root, &[])).unwrap(); let inputs = snapshot.inputs(); assert!(inputs .iter() .any(|i| i.kind == InputKind::Manifest && i.path == "marqdo.yaml")); assert!(inputs .iter() .any(|i| i.kind == InputKind::Lock && i.path == "marqdo.lock")); } #[test] fn source_change_detection_reports_differences() { let temp = tempfile::tempdir().unwrap(); let root = temp.path(); write_file(root, "doc.md", "# d\n"); let snapshot = discover(&scope_for(root, &[])).unwrap(); assert!(snapshot.verify_unchanged().is_empty()); std::fs::write(root.join("doc.md"), "# changed\n").unwrap(); let diagnostics = snapshot.verify_unchanged(); assert!(diagnostics.iter().any(|d| d.code == code::SOURCE_CHANGED)); } #[test] fn root_must_exist_and_be_a_file_or_directory() { let temp = tempfile::tempdir().unwrap(); assert!(resolve_scope(&temp.path().join("missing"), &[]).is_err()); let file = temp.path().join("x.txt"); std::fs::write(&file, "x").unwrap(); assert!(resolve_scope(&file, &[]).is_err()); } }