diff --git a/src/document/analysis.rs b/src/document/analysis.rs new file mode 100644 index 0000000..805bcac --- /dev/null +++ b/src/document/analysis.rs @@ -0,0 +1,4 @@ +//! Adapter for the core CLI's current public Analysis contract +//! (`marqdo.analysis`, revision 3, produced by `check ENTRY --emit PATH`). +//! +//! Implemented in the document milestone. diff --git a/src/document/discovery.rs b/src/document/discovery.rs new file mode 100644 index 0000000..5c7770f --- /dev/null +++ b/src/document/discovery.rs @@ -0,0 +1,804 @@ +//! 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); + match read_document(scope, &abs, single, &mut diagnostics)? { + Some(file) => { + total_bytes += file.len(); + files.push(file); + } + None => {} + } + } 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()); + } +} diff --git a/src/document/markdown.rs b/src/document/markdown.rs new file mode 100644 index 0000000..796cfdd --- /dev/null +++ b/src/document/markdown.rs @@ -0,0 +1,4 @@ +//! Plain CommonMark/GFM projection for `.md` documents. +//! +//! Implemented in the document milestone. Plain Markdown never gains +//! executable Marqdo semantics from `@exec` text. diff --git a/src/document/mod.rs b/src/document/mod.rs new file mode 100644 index 0000000..fc21dff --- /dev/null +++ b/src/document/mod.rs @@ -0,0 +1,331 @@ +//! Document layer: deterministic discovery, plain Markdown projection, the +//! core Analysis v3 adapter and OKF recognition. +//! +//! The layer never writes the database and never renders output. Every fact it +//! returns carries the exact UTF-8 byte span it came from and the digest of the +//! source snapshot it belongs to. + +pub mod analysis; +pub mod discovery; +pub mod markdown; +pub mod okf; + +use crate::diagnostic::DiagnosticSet; +use crate::model::{DocumentFormat, Span}; +use std::path::PathBuf; + +/// Hard input budgets. They are part of the safety contract: hard overruns +/// abort publication instead of producing a partial database. +pub const PER_FILE_LIMIT: u64 = 16 * 1024 * 1024; +pub const TOTAL_SOURCE_LIMIT: u64 = 512 * 1024 * 1024; +pub const DOCUMENT_LIMIT: usize = 100_000; +pub const MAX_AST_DEPTH: usize = 256; +pub const MAX_SQLITE_BYTES: u64 = 4 * 1024 * 1024 * 1024; +pub const MAX_MANIFEST_BYTES: u64 = 1024 * 1024; + +/// Configurable limits (tests use smaller values; production uses the default). +#[derive(Debug, Clone, Copy)] +pub struct Limits { + pub per_file: u64, + pub total_source: u64, + pub documents: usize, + pub manifest: u64, +} + +impl Default for Limits { + fn default() -> Self { + Self { + per_file: PER_FILE_LIMIT, + total_source: TOTAL_SOURCE_LIMIT, + documents: DOCUMENT_LIMIT, + manifest: MAX_MANIFEST_BYTES, + } + } +} + +/// The explicitly selected compilation scope. +#[derive(Debug, Clone)] +pub struct Scope { + /// Canonical absolute root directory. + pub root: PathBuf, + /// When the user named a single Markdown file, its root-relative path. + pub single_file: Option, + /// Validated, root-relative exclusion globs in the order given. + pub excludes: Vec, + /// Compiled exclusion patterns (parallel to `excludes`). + pub patterns: Vec, + pub limits: Limits, +} + +impl Scope { + pub fn dir_for_database(&self) -> PathBuf { + self.root.join(".marqdo") + } + + pub fn database_path(&self) -> PathBuf { + self.dir_for_database().join("knowledge.sqlite") + } + + /// Deterministic description stored in build metadata. Uses no absolute + /// machine paths. + pub fn describe(&self) -> serde_json::Value { + serde_json::json!({ + "single_file": self.single_file, + "excludes": self.excludes, + }) + } +} + +/// One discovered Markdown document with its exact bytes. +#[derive(Debug, Clone)] +pub struct SourceFile { + /// Root-relative path with `/` separators. + pub rel_path: String, + /// Absolute path used only for local I/O (never emitted). + pub abs_path: PathBuf, + pub format: DocumentFormat, + /// Exact decoded UTF-8 source; `text.as_bytes()` equals the file bytes. + pub text: String, + /// `sha256:` + lowercase hex of the raw bytes. + pub digest: String, +} + +impl SourceFile { + pub fn bytes(&self) -> &[u8] { + self.text.as_bytes() + } + + pub fn len(&self) -> u64 { + self.bytes().len() as u64 + } + + pub fn is_empty(&self) -> bool { + self.bytes().is_empty() + } + + /// Exact source slice for a span, or `None` when invalid. + pub fn slice(&self, span: Span) -> Option<&str> { + span.slice(self.bytes()) + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum InputKind { + Document, + Manifest, + Lock, + Asset, +} + +impl InputKind { + pub fn as_str(self) -> &'static str { + match self { + InputKind::Document => "document", + InputKind::Manifest => "manifest", + InputKind::Lock => "lock", + InputKind::Asset => "asset", + } + } +} + +/// One file that participated in the snapshot. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct InputRecord { + pub path: String, + pub kind: InputKind, + pub digest: String, + pub size: u64, +} + +/// A referenced non-Markdown asset. Only path, size and (within budget) digest +/// are recorded; content is never indexed as text. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct AssetFile { + pub rel_path: String, + pub size: u64, + pub digest: Option, +} + +/// The immutable source snapshot used for one compile. +#[derive(Debug)] +pub struct SourceSnapshot { + pub scope: Scope, + /// Accepted documents, sorted byte-wise by `rel_path`. + pub files: Vec, + pub assets: Vec, + pub manifest: Option, + pub lock: Option, + pub diagnostics: DiagnosticSet, + pub total_bytes: u64, +} + +impl SourceSnapshot { + /// All inputs in deterministic order (documents, manifest, lock, assets). + pub fn inputs(&self) -> Vec { + let mut inputs: Vec = self + .files + .iter() + .map(|file| InputRecord { + path: file.rel_path.clone(), + kind: InputKind::Document, + digest: file.digest.clone(), + size: file.len(), + }) + .collect(); + if let Some(manifest) = &self.manifest { + inputs.push(manifest.clone()); + } + if let Some(lock) = &self.lock { + inputs.push(lock.clone()); + } + inputs.extend(self.assets.iter().map(|asset| { + InputRecord { + path: asset.rel_path.clone(), + kind: InputKind::Asset, + digest: asset + .digest + .clone() + .unwrap_or_else(|| format!("size:{}", asset.size)), + size: asset.size, + } + })); + inputs.sort_by(|a, b| { + a.path + .cmp(&b.path) + .then(a.kind.as_str().cmp(b.kind.as_str())) + }); + inputs + } + + /// Re-read every recorded input and compare digests. Used immediately + /// before publishing so a concurrently edited source never produces a + /// mixed snapshot. + pub fn verify_unchanged(&self) -> DiagnosticSet { + let mut diagnostics = DiagnosticSet::new(); + for file in &self.files { + match std::fs::read(&file.abs_path) { + Ok(bytes) => { + let digest = crate::model::sha256_prefixed(&bytes); + if digest != file.digest || bytes != file.bytes() { + diagnostics.push( + crate::diagnostic::Diagnostic::error( + crate::diagnostic::code::SOURCE_CHANGED, + "source changed while compiling; the snapshot was not published", + ) + .with_path(&file.rel_path), + ); + } + } + Err(error) => diagnostics.push( + crate::diagnostic::Diagnostic::error( + crate::diagnostic::code::SOURCE_CHANGED, + format!("source cannot be re-read before publishing: {error}"), + ) + .with_path(&file.rel_path), + ), + } + } + for (record, abs) in self.non_document_inputs() { + match std::fs::read(&abs) { + Ok(bytes) => { + let digest = crate::model::sha256_prefixed(&bytes); + if digest != record.digest { + diagnostics.push( + crate::diagnostic::Diagnostic::error( + crate::diagnostic::code::SOURCE_CHANGED, + "input changed while compiling; the snapshot was not published", + ) + .with_path(&record.path), + ); + } + } + Err(_) => { + // Removal is a change too. + diagnostics.push( + crate::diagnostic::Diagnostic::error( + crate::diagnostic::code::SOURCE_CHANGED, + "input disappeared while compiling; the snapshot was not published", + ) + .with_path(&record.path), + ); + } + } + } + diagnostics + } + + fn non_document_inputs(&self) -> Vec<(InputRecord, PathBuf)> { + let mut out = Vec::new(); + if let Some(manifest) = &self.manifest { + out.push((manifest.clone(), self.scope.root.join(&manifest.path))); + } + if let Some(lock) = &self.lock { + out.push((lock.clone(), self.scope.root.join(&lock.path))); + } + for asset in &self.assets { + if let Some(digest) = &asset.digest { + out.push(( + InputRecord { + path: asset.rel_path.clone(), + kind: InputKind::Asset, + digest: digest.clone(), + size: asset.size, + }, + self.scope.root.join(&asset.rel_path), + )); + } else { + let abs = self.scope.root.join(&asset.rel_path); + match std::fs::metadata(&abs) { + Ok(metadata) if metadata.len() == asset.size => {} + _ => out.push(( + InputRecord { + path: asset.rel_path.clone(), + kind: InputKind::Asset, + digest: format!("size:{}", asset.size), + size: asset.size, + }, + abs, + )), + } + } + } + out + } + + /// Deterministic snapshot manifest digest over all recorded inputs and the + /// scope description. Independent of absolute paths and wall-clock time. + pub fn snapshot_digest(&self) -> String { + let mut buffer = String::new(); + let described = self.scope.describe().to_string(); + buffer.push_str("scope\n"); + buffer.push_str(&described); + buffer.push('\n'); + for input in self.inputs() { + buffer.push_str(input.kind.as_str()); + buffer.push('\t'); + buffer.push_str(&input.path); + buffer.push('\t'); + buffer.push_str(&input.digest); + buffer.push('\n'); + } + crate::model::sha256_prefixed(buffer.as_bytes()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn scope_database_path_is_fixed_below_root() { + let root = PathBuf::from("/tmp/example"); + let scope = Scope { + root: root.clone(), + single_file: None, + excludes: Vec::new(), + patterns: Vec::new(), + limits: Limits::default(), + }; + assert_eq!(scope.database_path(), root.join(".marqdo/knowledge.sqlite")); + } +} diff --git a/src/document/okf.rs b/src/document/okf.rs new file mode 100644 index 0000000..7e074e5 --- /dev/null +++ b/src/document/okf.rs @@ -0,0 +1,3 @@ +//! OKF v0.3 document-layer recognition and `check --okf` validation. +//! +//! Implemented in the OKF milestone. diff --git a/src/lib.rs b/src/lib.rs index d16e472..fb56971 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -8,6 +8,7 @@ pub mod cli; pub mod compiler; pub mod diagnostic; +pub mod document; pub mod error; pub mod model; pub mod query;