feat(discovery): deterministic source snapshot with explicit boundaries

- resolve explicit dir/file roots, reject symlink roots and unsafe --exclude
  globs; keep the database at <root>/.marqdo/knowledge.sqlite
- walk without following symlinks, skip .git/.marqdo/target/node_modules and
  hidden entries, sort by byte-wise root-relative path
- read exact UTF-8 bytes with per-file/total/document budgets and digest
  based source-change detection before publishing
- record marqdo.yaml/marqdo.lock and referenced local assets as inputs;
  asset digests are bounded and never full-text indexed
- add validate_relative_path/resolve_link_path/safe_join primitives with
  traversal, drive/UNC, NUL and escape tests
This commit is contained in:
marqdo-knowledge committed 2026-11-25 22:29:42 +08:00
1 parent 430f950631
commit f2f3b38eca
6 files changed
+1147

No files matched your search

+331
View File
@@ -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<String>,
/// Validated, root-relative exclusion globs in the order given.
pub excludes: Vec<String>,
/// Compiled exclusion patterns (parallel to `excludes`).
pub patterns: Vec<glob::Pattern>,
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<String>,
}
/// 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<SourceFile>,
pub assets: Vec<AssetFile>,
pub manifest: Option<InputRecord>,
pub lock: Option<InputRecord>,
pub diagnostics: DiagnosticSet,
pub total_bytes: u64,
}
impl SourceSnapshot {
/// All inputs in deterministic order (documents, manifest, lock, assets).
pub fn inputs(&self) -> Vec<InputRecord> {
let mut inputs: Vec<InputRecord> = 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"));
}
}