diff --git a/src/compiler.rs b/src/compiler.rs index 96c4e67..69e0cff 100644 --- a/src/compiler.rs +++ b/src/compiler.rs @@ -1,20 +1,882 @@ //! Compile orchestration: the single write-transaction boundary. //! -//! This module is filled in by the compiler milestone; the type signatures are -//! the stable boundary used by `cli.rs`. It owns discovery, Analysis retrieval, -//! graph linking, staging and atomic publishing. +//! ```text +//! resolve scope -> discover exact snapshot -> plain projection + Analysis v3 +//! -> collect referenced assets -> unify graph -> verify sources unchanged +//! -> publish atomically +//! ``` +//! +//! Incremental rules: file changes are detected by content digest; unchanged +//! `.md`/`.mq.md` documents reuse their digest-guarded normalised facts. Any +//! `.mq.md` change, manifest/lock change or core CLI identity change forces a +//! conservative re-analysis of every entry (the specification permits exactly +//! this conservative bound). Plain-only changes never invoke the core CLI. -use crate::cli::Output; -use crate::cli::{CheckArgs, CompileArgs}; -use crate::error::KnowledgeError; +use crate::cli::{CheckArgs, CompileArgs, Output}; +use crate::diagnostic::{code, Diagnostic, DiagnosticSet}; +use crate::document::analysis::{self, AnalysisBatch, ProjectContext}; +use crate::document::core_cli::CoreCli; +use crate::document::discovery; +use crate::document::markdown; +use crate::document::{DocumentFacts, DocumentFormat, SourceSnapshot}; +use crate::error::{KnowledgeError, EXIT_INPUT, EXIT_OK}; +use crate::graph; +use crate::model::{sha256_prefixed, EdgeState}; +use crate::storage::read::{CachedFacts, ReadStore}; +use crate::storage::{self, BuildMeta, PublishRequest}; +use std::collections::{HashMap, HashSet}; use std::path::Path; +pub const TOOL_VERSION: &str = env!("CARGO_PKG_VERSION"); +/// Diagnostic codes that make `check` fail for a definite broken reference. +const DEFINITE_BROKEN_REFERENCE: [&str; 4] = [ + code::REFERENCE_MISSING, + code::REFERENCE_AMBIGUOUS, + code::REFERENCE_OUT_OF_SCOPE, + code::REFERENCE_INVALID, +]; + /// Compile or incrementally update one knowledge root. -pub fn compile(_args: &CompileArgs, _marqdo_bin: Option<&Path>) -> Result { - Err(KnowledgeError::not_implemented("compile")) +pub fn compile(args: &CompileArgs, marqdo_bin: Option<&Path>) -> Result { + let outcome = compile_inner(args, marqdo_bin)?; + let diagnostics_text = render_diagnostics(&outcome.diagnostics); + let payload = serde_json::json!({ + "mode": outcome.mode, + "documents": outcome.stats.documents, + "nodes": outcome.stats.nodes, + "edges": outcome.stats.edges, + "search_units": outcome.stats.search_units, + "grams": outcome.stats.grams, + "rebuild_generation": outcome.stats.rebuild_generation, + "errors": outcome.diagnostics.error_count(), + "warnings": outcome.diagnostics.warning_count(), + }); + let envelope = result_envelope( + "compile", + true, + &outcome.snapshot_digest, + true, + payload, + &outcome.diagnostics, + ); + let mut output = + Output::ok(serde_json::to_string_pretty(&envelope).unwrap_or_else(|_| "{}".into())); + output.stderr = diagnostics_text; + // A compile that only produced warnings is still a success; blocking errors + // are returned as `KnowledgeError` before reaching this point. + output.exit_code = EXIT_OK; + Ok(output) +} + +struct CompileOutcome { + mode: String, + snapshot_digest: String, + stats: storage::PublishStats, + diagnostics: DiagnosticSet, +} + +fn compile_inner( + args: &CompileArgs, + marqdo_bin: Option<&Path>, +) -> Result { + let scope = discovery::resolve_scope(&args.root, &args.exclude)?; + let mut snapshot = discovery::discover(&scope)?; + let database_path = scope.database_path(); + + // Existing state (if any) drives incremental reuse and rebuild generation. + let previous: Option = + load_previous_state(&database_path, &scope, args.rebuild)?; + + let mq_entries = analysis::entry_candidates(&snapshot.files); + let core = if mq_entries.is_empty() { + None + } else { + Some(CoreCli::locate(marqdo_bin).map_err(|error| { + error.with_hint("install the tool through `marqdo tool install` or pass --marqdo-bin") + })?) + }; + check_launch_context(core.as_ref(), mq_entries.is_empty())?; + if args.embedding.embedding_url.is_some() { + return Err(KnowledgeError::environment( + code::EMBEDDING_UNAVAILABLE, + "semantic indexing is not available in this build", + ) + .with_hint("compile without embedding options for the offline index")); + } + + let previous_ref = previous.as_ref(); + let reuse = plan_reuse(previous_ref, &snapshot, core.as_ref()); + let mut diagnostics = snapshot.diagnostics.clone(); + + // Plain Markdown facts: reparse changed documents, reuse unchanged ones. + let mut facts_by_path: HashMap = HashMap::new(); + for file in &snapshot.files { + if file.format != DocumentFormat::PlainMarkdown { + continue; + } + match &reuse { + ReusePlan::Incremental { cache } => { + if let Some(cached) = cache.docs.get(&file.rel_path) { + if cached.facts.source_digest == file.digest + && cached.facts.format == DocumentFormat::PlainMarkdown + { + facts_by_path.insert(file.rel_path.clone(), cached.facts.clone()); + continue; + } + } + facts_by_path.insert(file.rel_path.clone(), markdown::parse_plain(file)); + } + ReusePlan::Full => { + facts_by_path.insert(file.rel_path.clone(), markdown::parse_plain(file)); + } + } + } + + // Marqdo facts: reuse cached facts unless the conservative re-analysis + // trigger fired. + let mut contexts: Vec = Vec::new(); + let mut producer_version = previous_ref + .map(|previous| previous.meta.producer_version.clone()) + .unwrap_or_default(); + if !mq_entries.is_empty() { + let reanalyze = matches!(reuse, ReusePlan::Full) || reuse.requires_analysis(); + if reanalyze { + let batch = analysis::analyze_core( + &scope.root, + &mq_entries, + core.as_ref().expect("core present"), + ); + diagnostics.merge(batch.diagnostics.clone()); + producer_version = batch.producer_version.clone(); + if batch.diagnostics.has_errors() { + return Err(fatal_from_diagnostics(&diagnostics)); + } + let discovered: HashMap<&str, &crate::document::SourceFile> = snapshot + .files + .iter() + .map(|file| (file.rel_path.as_str(), file)) + .collect(); + for module in &batch.modules { + let Some(file) = discovered.get(module.facts.rel_path.as_str()) else { + // Modules outside the selected root are represented as + // external targets; they never get document nodes. + continue; + }; + if module.source != file.text { + return Err(KnowledgeError::input( + code::ANALYSIS_CONTEXT_CONFLICT, + format!( + "core Analysis source for `{}` differs from the discovered file", + module.facts.rel_path + ), + )); + } + facts_by_path.insert(module.facts.rel_path.clone(), module.facts.clone()); + } + contexts = batch.contexts.clone(); + } else if let ReusePlan::Incremental { cache } = &reuse { + for file in &snapshot.files { + if file.format != DocumentFormat::Marqdo { + continue; + } + let Some(cached) = cache.docs.get(&file.rel_path) else { + return Err(KnowledgeError::input( + code::MARQDO_INVALID, + format!( + "document `{}` has no analysable compiled facts; rerun a full compile", + file.rel_path + ), + )); + }; + if cached.facts.source_digest != file.digest { + return Err(KnowledgeError::input( + code::SOURCE_CHANGED, + format!( + "document `{}` changed during incremental reuse", + file.rel_path + ), + )); + } + facts_by_path.insert(file.rel_path.clone(), cached.facts.clone()); + } + contexts = cache.contexts.clone(); + } + } + + // Every discovered `.mq.md` must be covered by Analysis facts. + for file in &snapshot.files { + if file.format == DocumentFormat::Marqdo && !facts_by_path.contains_key(&file.rel_path) { + diagnostics.push( + Diagnostic::error( + code::MARQDO_INVALID, + "Marqdo document is not covered by any valid Analysis; it cannot be indexed", + ) + .with_path(&file.rel_path), + ); + } + } + if diagnostics.has_errors() { + return Err(fatal_from_diagnostics(&diagnostics)); + } + if let Some(core) = &core { + if producer_version.is_empty() { + producer_version = core.identity.version.clone(); + } + } + + // Referenced local assets and known-missing paths (exact state, never + // invented). Assets are recorded, never text-indexed. + let (assets, missing_paths) = collect_assets(&scope, &snapshot, &facts_by_path)?; + snapshot.assets = assets; + + let mut facts: Vec = snapshot + .files + .iter() + .filter_map(|file| facts_by_path.remove(&file.rel_path)) + .collect(); + facts.sort_by(|a, b| a.rel_path.cmp(&b.rel_path)); + let sources: HashMap<&str, &str> = snapshot + .files + .iter() + .map(|file| (file.rel_path.as_str(), file.text.as_str())) + .collect(); + let graph = graph::build(facts, &sources, &snapshot.assets, &missing_paths); + diagnostics.merge(graph.diagnostics.clone()); + if graph.diagnostics.has_errors() { + return Err(fatal_from_diagnostics(&diagnostics)); + } + + // Source recheck immediately before publishing: never mix snapshots. + let changed = snapshot.verify_unchanged(); + if changed.has_errors() { + diagnostics.merge(changed); + return Err(fatal_from_diagnostics(&diagnostics)); + } + + let snapshot_digest = snapshot.snapshot_digest(); + let logical_digest = graph.logical_digest(); + let no_op = !args.rebuild + && previous_ref.is_some_and(|previous| { + previous.meta.snapshot_digest == snapshot_digest + && previous.meta.logical_digest == logical_digest + && previous.meta.complete + }); + if no_op { + let previous = previous_ref.expect("checked"); + let (documents, nodes, edges) = previous.meta.counts(); + let stats = storage::PublishStats { + mode: "incremental".into(), + documents, + nodes, + edges, + search_units: previous.meta.search_units, + grams: 0, + rebuild_generation: previous.meta.rebuild_generation, + }; + return Ok(CompileOutcome { + mode: "incremental".into(), + snapshot_digest, + stats, + diagnostics, + }); + } + + let generation = if args.rebuild { + previous_ref.map_or(1, |previous| previous.meta.rebuild_generation + 1) + } else { + previous_ref.map_or(1, |previous| previous.meta.rebuild_generation + 1) + }; + let mut meta = BuildMeta::new(TOOL_VERSION, snapshot_digest.clone(), logical_digest); + meta.scope = scope.describe(); + meta.options = serde_json::json!({ + "excludes": scope.excludes, + "single_file": scope.single_file, + "rebuild": args.rebuild, + }); + meta.producer_version = producer_version; + meta.core_identity = core + .as_ref() + .map(|core| core.identity.describe()) + .unwrap_or_else(|| "native-only".into()); + meta.facts_cache_version = crate::document::facts_cache_version(); + meta.rebuild_generation = generation; + meta.embedding = None; + if contexts.is_empty() { + if let Some(previous) = previous_ref { + contexts = previous.contexts.clone(); + } + } + // Merge any contexts produced by re-analysis with previously stored ones so + // an incremental compile never drops a context that still owns cached facts. + if let Some(previous) = previous_ref { + for context in &previous.contexts { + if !contexts + .iter() + .any(|existing| existing.context_id == context.context_id) + { + contexts.push(context.clone()); + } + } + } + let stats = storage::publish(PublishRequest { + database_path, + rebuild: args.rebuild, + meta, + graph: &graph, + snapshot: &snapshot, + contexts: &contexts, + })?; + Ok(CompileOutcome { + mode: stats.mode.clone(), + snapshot_digest, + stats, + diagnostics, + }) } /// Statically check sources and an existing database without writing. -pub fn check(_args: &CheckArgs, _marqdo_bin: Option<&Path>) -> Result { - Err(KnowledgeError::not_implemented("check")) +pub fn check(args: &CheckArgs, marqdo_bin: Option<&Path>) -> Result { + let scope = discovery::resolve_scope(&args.root, &[])?; + let snapshot = discovery::discover(&scope)?; + let mut diagnostics = snapshot.diagnostics.clone(); + + let mq_entries = analysis::entry_candidates(&snapshot.files); + let core = if mq_entries.is_empty() { + None + } else { + Some(CoreCli::locate(marqdo_bin)?) + }; + check_launch_context(core.as_ref(), mq_entries.is_empty())?; + + let mut facts_by_path: HashMap = HashMap::new(); + for file in &snapshot.files { + if file.format == DocumentFormat::PlainMarkdown { + facts_by_path.insert(file.rel_path.clone(), markdown::parse_plain(file)); + } + } + let mut producer_version = String::new(); + if let Some(core) = &core { + let batch: AnalysisBatch = analysis::analyze_core(&scope.root, &mq_entries, core); + diagnostics.merge(batch.diagnostics.clone()); + producer_version = batch.producer_version; + for module in &batch.modules { + let Some(file) = snapshot + .files + .iter() + .find(|file| file.rel_path == module.facts.rel_path) + else { + continue; + }; + if module.source != file.text { + diagnostics.push( + Diagnostic::error( + code::ANALYSIS_CONTEXT_CONFLICT, + "core Analysis source differs from the discovered file", + ) + .with_path(&file.rel_path), + ); + continue; + } + facts_by_path.insert(module.facts.rel_path.clone(), module.facts.clone()); + } + } + for file in &snapshot.files { + if file.format == DocumentFormat::Marqdo && !facts_by_path.contains_key(&file.rel_path) { + diagnostics.push( + Diagnostic::error( + code::MARQDO_INVALID, + "Marqdo document is not covered by any valid Analysis", + ) + .with_path(&file.rel_path), + ); + } + } + let _ = producer_version; + let (assets, missing_paths) = collect_assets(&scope, &snapshot, &facts_by_path)?; + let mut snapshot = snapshot; + snapshot.assets = assets; + let mut facts: Vec = snapshot + .files + .iter() + .filter_map(|file| facts_by_path.remove(&file.rel_path)) + .collect(); + facts.sort_by(|a, b| a.rel_path.cmp(&b.rel_path)); + let sources: HashMap<&str, &str> = snapshot + .files + .iter() + .map(|file| (file.rel_path.as_str(), file.text.as_str())) + .collect(); + let graph = graph::build(facts, &sources, &snapshot.assets, &missing_paths); + diagnostics.merge(graph.diagnostics.clone()); + + // OKF structural validation is a separate, explicit mode. + if args.okf { + let okf_diagnostics = crate::document::okf::validate_okf(&snapshot, &graph.facts); + diagnostics.merge(okf_diagnostics); + } + + // Existing database structure and currentness (never modified). + let database_path = scope.database_path(); + let mut database_state = "absent"; + let mut database_digest = serde_json::Value::Null; + if database_path.exists() { + match ReadStore::open(&database_path) { + Ok(store) => { + let meta = store.build_meta()?; + database_digest = serde_json::Value::String(meta.snapshot_digest.clone()); + let currentness = store.currentness(&snapshot)?; + if currentness.current { + database_state = "current"; + } else { + database_state = "stale"; + diagnostics.push( + Diagnostic::warning( + code::DATABASE_STALE, + format!( + "stored database does not match the current sources ({} changed input(s))", + currentness.changed_inputs.len() + ), + ) + .with_hint("run `marqdo knowledge compile` to refresh the projection"), + ); + } + store.integrity_check(false)?; + } + Err(error) + if error.code == code::DATABASE_MISSING + || error.code == code::DATABASE_NOT_OURS + || error.code == code::DATABASE_OLD_SCHEMA + || error.code == code::DATABASE_CORRUPT => + { + return Err(error); + } + Err(error) => return Err(error), + } + } + + diagnostics.sorted(); + let definite_broken = diagnostics + .iter() + .any(|diagnostic| DEFINITE_BROKEN_REFERENCE.contains(&diagnostic.code.as_str())); + let failed = diagnostics.has_errors() || definite_broken || database_state == "stale"; + let payload = serde_json::json!({ + "documents": snapshot.files.len(), + "errors": diagnostics.error_count(), + "warnings": diagnostics.warning_count(), + "database": database_state, + "snapshot_digest": snapshot.snapshot_digest(), + "database_snapshot_digest": database_digest, + }); + let envelope = result_envelope( + "check", + !failed, + &snapshot.snapshot_digest(), + database_state == "current" || database_state == "absent", + payload, + &diagnostics, + ); + let mut output = + Output::ok(serde_json::to_string_pretty(&envelope).unwrap_or_else(|_| "{}".into())); + output.stderr = render_diagnostics(&diagnostics); + output.exit_code = if failed { EXIT_INPUT } else { EXIT_OK }; + Ok(output) +} + +fn check_launch_context( + core: Option<&CoreCli>, + no_marqdo_documents: bool, +) -> Result<(), KnowledgeError> { + if core.is_some() || no_marqdo_documents { + return Ok(()); + } + if std::env::var_os("MARQDO_API_REVISION").is_none() { + return Err(KnowledgeError::environment( + code::NOT_LAUNCHED_BY_MARQDO, + "this tool is not running through the marqdo CLI dispatcher", + ) + .with_hint( + "launch through `marqdo knowledge ...` or pass --marqdo-bin PATH for development", + )); + } + Ok(()) +} + +// --------------------------------------------------------------------------- +// Previous state and incremental planning +// --------------------------------------------------------------------------- + +struct PreviousState { + meta: PreviousMeta, + contexts: Vec, + inputs: HashMap, + cache: HashMap, +} + +struct PreviousMeta { + snapshot_digest: String, + logical_digest: String, + core_identity: String, + producer_version: String, + facts_cache_version: u32, + rebuild_generation: u64, + complete: bool, + documents: u64, + nodes: u64, + edges: u64, + search_units: u64, +} + +impl PreviousMeta { + fn counts(&self) -> (u64, u64, u64) { + (self.documents, self.nodes, self.edges) + } +} + +fn load_previous_state( + database_path: &Path, + scope: &crate::document::Scope, + rebuild: bool, +) -> Result, KnowledgeError> { + if !database_path.exists() { + return Ok(None); + } + if rebuild { + // A rebuild replaces the artifact; only identity and generation are + // read. An old schema is itself a reason to rebuild. + match ReadStore::open(database_path) { + Ok(store) => { + let meta = store.build_meta()?; + let (documents, nodes, edges) = store.counts()?; + return Ok(Some(PreviousState { + meta: PreviousMeta { + snapshot_digest: meta.snapshot_digest, + logical_digest: meta.logical_digest, + core_identity: meta.core_identity, + producer_version: meta.producer_version, + facts_cache_version: meta.facts_cache_version, + rebuild_generation: meta.rebuild_generation, + complete: meta.complete, + documents, + nodes, + edges, + search_units: store.search_unit_count()?, + }, + contexts: store.contexts()?, + inputs: store + .inputs()? + .into_iter() + .map(|input| (input.path, input.digest)) + .collect(), + cache: HashMap::new(), + })); + } + Err(error) if error.code == code::DATABASE_OLD_SCHEMA => { + return Ok(Some(PreviousState { + meta: PreviousMeta { + snapshot_digest: String::new(), + logical_digest: String::new(), + core_identity: String::new(), + producer_version: String::new(), + facts_cache_version: 0, + rebuild_generation: 0, + complete: false, + documents: 0, + nodes: 0, + edges: 0, + search_units: 0, + }, + contexts: Vec::new(), + inputs: HashMap::new(), + cache: HashMap::new(), + })); + } + Err(error) => return Err(error), + } + } + let _ = scope; + let store = ReadStore::open(database_path)?; + let meta = store.build_meta()?; + let (documents, nodes, edges) = store.counts()?; + let search_units = store.search_unit_count()?; + let mut cache = HashMap::new(); + if meta.facts_cache_version == crate::document::facts_cache_version() { + for document in store.documents()? { + if document.facts_cache_version == Some(crate::document::facts_cache_version()) { + if let Some(cached) = store.load_facts(&document.path)? { + cache.insert(document.path.clone(), cached); + } + } + } + } + Ok(Some(PreviousState { + meta: PreviousMeta { + snapshot_digest: meta.snapshot_digest, + logical_digest: meta.logical_digest, + core_identity: meta.core_identity, + producer_version: meta.producer_version, + facts_cache_version: meta.facts_cache_version, + rebuild_generation: meta.rebuild_generation, + complete: meta.complete, + documents, + nodes, + edges, + search_units, + }, + contexts: store.contexts()?, + inputs: store + .inputs()? + .into_iter() + .map(|input| (input.path, input.digest)) + .collect(), + cache, + })) +} + +enum ReusePlan { + Full, + Incremental { cache: PreviousCache }, +} + +struct PreviousCache { + docs: HashMap, + contexts: Vec, + changed_inputs: Vec, +} + +impl ReusePlan { + /// True when the conservative bound requires re-running Analysis. + fn requires_analysis(&self) -> bool { + match self { + ReusePlan::Full => true, + ReusePlan::Incremental { cache } => cache.changed_inputs.iter().any(|path| { + path.ends_with(".mq.md") || path == "marqdo.yaml" || path == "marqdo.lock" + }), + } + } +} + +fn plan_reuse( + previous: Option<&PreviousState>, + snapshot: &SourceSnapshot, + core: Option<&CoreCli>, +) -> ReusePlan { + let Some(previous) = previous else { + return ReusePlan::Full; + }; + let cache_version_ok = + previous.meta.facts_cache_version == crate::document::facts_cache_version(); + let core_identity = core + .map(|core| core.identity.describe()) + .unwrap_or_else(|| "native-only".into()); + let core_changed = previous.meta.core_identity != core_identity; + if !cache_version_ok || core_changed || !previous.meta.complete { + return ReusePlan::Full; + } + let current_inputs: HashMap = snapshot + .inputs() + .into_iter() + .map(|input| (input.path, input.digest)) + .collect(); + let mut changed_inputs = Vec::new(); + for (path, digest) in ¤t_inputs { + match previous.inputs.get(path) { + Some(stored) if stored == digest => {} + _ => changed_inputs.push(path.clone()), + } + } + for path in previous.inputs.keys() { + if !current_inputs.contains_key(path) { + changed_inputs.push(path.clone()); + } + } + changed_inputs.sort(); + changed_inputs.dedup(); + ReusePlan::Incremental { + cache: PreviousCache { + docs: previous.cache.clone(), + contexts: previous.contexts.clone(), + changed_inputs, + }, + } +} + +fn fatal_from_diagnostics(diagnostics: &DiagnosticSet) -> KnowledgeError { + let mut hints: Vec = diagnostics + .iter() + .filter(|diagnostic| diagnostic.is_error()) + .take(8) + .map(|diagnostic| diagnostic.to_string()) + .collect(); + if hints.is_empty() { + hints = diagnostics + .iter() + .take(8) + .map(|diagnostic| diagnostic.to_string()) + .collect(); + } + let mut error = KnowledgeError::input( + code::COMPILATION_FAILED, + format!( + "compilation failed with {} error(s); nothing was published", + diagnostics.error_count() + ), + ); + error.hints = hints; + error +} + +// --------------------------------------------------------------------------- +// Referenced assets and known-missing paths +// --------------------------------------------------------------------------- + +fn collect_assets( + scope: &crate::document::Scope, + snapshot: &SourceSnapshot, + facts_by_path: &HashMap, +) -> Result<(Vec, HashSet), KnowledgeError> { + let documents: HashSet<&str> = snapshot + .files + .iter() + .map(|file| file.rel_path.as_str()) + .collect(); + let mut candidates: Vec = Vec::new(); + for facts in facts_by_path.values() { + for reference in &facts.references { + if let Some(analysis) = &reference.analysis { + let package_matches = analysis + .candidate_package_instance_id + .as_deref() + .is_none_or(|candidate| { + facts + .analysis + .as_ref() + .is_some_and(|own| own.package_instance_id == candidate) + }); + if !package_matches { + continue; + } + let is_file_target = analysis.target_kind.as_deref() == Some("file") + || (analysis.state == EdgeState::NotLoaded && analysis.target_kind.is_none()); + if !is_file_target { + continue; + } + if let Some(path) = &analysis.candidate_path { + candidates.push(path.clone()); + } + } else if let Ok(graph::resolve::ParsedLink::Local { path, .. }) = + graph::resolve::parse_link(&reference.url) + { + if path.is_empty() { + continue; + } + if let Ok(rel) = discovery::resolve_link_path(&facts.rel_path, &path) { + candidates.push(rel); + } + } + } + } + candidates.sort(); + candidates.dedup(); + let mut assets = Vec::new(); + let mut missing = HashSet::new(); + let mut seen = HashSet::new(); + for candidate in candidates { + if documents.contains(candidate.as_str()) { + continue; + } + if crate::document::discovery::validate_relative_path(&candidate).is_err() { + continue; + } + let read = discovery::read_asset(scope, &candidate)?; + let is_markdown = DocumentFormat::from_path(&candidate).is_some(); + match read { + Some(asset) => { + if !is_markdown && seen.insert(asset.rel_path.clone()) { + assets.push(asset); + } + // Existing but unindexed Markdown is `not_loaded`, not an asset. + } + None => { + missing.insert(candidate); + } + } + } + Ok((assets, missing)) +} + +// --------------------------------------------------------------------------- +// Rendering helpers +// --------------------------------------------------------------------------- + +fn result_envelope( + command: &str, + success: bool, + snapshot_digest: &str, + current: bool, + payload: serde_json::Value, + diagnostics: &DiagnosticSet, +) -> serde_json::Value { + serde_json::json!({ + "schema": "marqdo.knowledge.result", + "schema_version": 1, + "command": command, + "success": success, + "tool_version": TOOL_VERSION, + "snapshot_digest": snapshot_digest, + "current": current, + "channels": [], + "truncated": false, + "hits": [], + "diagnostics": diagnostics.as_slice(), + "payload": payload, + }) +} + +pub fn render_diagnostics(diagnostics: &DiagnosticSet) -> String { + let mut out = String::new(); + for diagnostic in diagnostics.iter() { + out.push_str(&diagnostic.to_string()); + out.push('\n'); + } + out +} + +/// Re-export for integration tests and downstream consumers. +pub use crate::document::markdown::parse_plain as parse_plain_document; + +/// Tool version used in build metadata and machine envelopes. +pub fn tool_version() -> &'static str { + TOOL_VERSION +} + +/// Snapshot digest helper for tests. +pub fn snapshot_identity(snapshot: &SourceSnapshot) -> String { + sha256_prefixed(snapshot.snapshot_digest().as_bytes()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn fatal_error_carries_bounded_hints() { + let mut diagnostics = DiagnosticSet::new(); + for index in 0..20 { + diagnostics.push( + Diagnostic::error(code::REFERENCE_MISSING, format!("missing {index}")) + .with_path(format!("doc{index}.md")), + ); + } + let error = fatal_from_diagnostics(&diagnostics); + assert_eq!(error.exit_code, EXIT_INPUT); + assert!(error.hints.len() <= 8); + assert!(error.message.contains("20 error(s)")); + } + + #[test] + fn definite_broken_codes_are_recognised() { + for broken in DEFINITE_BROKEN_REFERENCE { + assert!(broken.starts_with("knowledge.reference_")); + } + } } diff --git a/src/diagnostic.rs b/src/diagnostic.rs index 4e60889..42787ec 100644 --- a/src/diagnostic.rs +++ b/src/diagnostic.rs @@ -76,6 +76,7 @@ pub mod code { pub const USAGE: &str = "knowledge.usage"; pub const NOT_IMPLEMENTED: &str = "knowledge.not_implemented"; pub const INTERNAL: &str = "knowledge.internal"; + pub const COMPILATION_FAILED: &str = "knowledge.compilation_failed"; } #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] diff --git a/src/document/okf.rs b/src/document/okf.rs index 7e074e5..6e344e1 100644 --- a/src/document/okf.rs +++ b/src/document/okf.rs @@ -1,3 +1,25 @@ //! OKF v0.3 document-layer recognition and `check --okf` validation. //! -//! Implemented in the OKF milestone. +//! OKF is an optional Markdown organisation convention, not a project type and +//! not an additional knowledge format. Recognition only reads front-matter +//! metadata and fixed file roles; it never executes an executor/attester and +//! never changes program semantics. +//! +//! Implemented by the OKF milestone. Until then `--okf` reports an explicit +//! unverified diagnostic instead of pretending to validate. + +use crate::diagnostic::{code, Diagnostic, DiagnosticSet}; +use crate::document::{DocumentFacts, SourceSnapshot}; + +/// Validate the supported OKF surface for an explicitly requested bundle. +pub fn validate_okf(_snapshot: &SourceSnapshot, _facts: &[DocumentFacts]) -> DiagnosticSet { + let mut diagnostics = DiagnosticSet::new(); + diagnostics.push( + Diagnostic::warning( + code::OKF_UNVERIFIED, + "OKF v0.3 validation is not implemented in this build; no OKF claim is made", + ) + .with_hint("see docs/STATUS.md for the current capability matrix"), + ); + diagnostics +} diff --git a/src/storage/read.rs b/src/storage/read.rs index 5d3a41d..bd3e9b8 100644 --- a/src/storage/read.rs +++ b/src/storage/read.rs @@ -355,16 +355,17 @@ impl ReadStore { let mut statement = self .conn .prepare( - "SELECT a.context_id, n.id, n.canonical_key, n.kind, n.doc_id, n.parent_id, + "SELECT n.id, n.canonical_key, n.kind, n.doc_id, n.parent_id, n.span_start, n.span_end, n.title, n.title_norm, n.symbol_norm, - n.content_digest, n.semantic_digest, n.searchable, n.metadata_json + n.content_digest, n.semantic_digest, n.searchable, n.metadata_json, + a.context_id FROM aliases a JOIN nodes n ON n.id = a.node_id WHERE a.alias = ?1 ORDER BY a.context_id", ) .map_err(db)?; let rows = statement .query_map([alias], |row| { - Ok((row.get::<_, String>(0)?, map_node(row)?)) + Ok((row.get::<_, String>(14)?, map_node(row)?)) }) .map_err(db)?; let mut out = Vec::new(); @@ -735,6 +736,14 @@ impl ReadStore { } } + pub fn search_unit_count(&self) -> Result { + let count: i64 = self + .conn + .query_row("SELECT count(*) FROM search_units", [], |row| row.get(0)) + .map_err(db)?; + Ok(count as u64) + } + pub fn counts(&self) -> Result<(u64, u64, u64), KnowledgeError> { let documents: i64 = self .conn diff --git a/tests/compile.rs b/tests/compile.rs new file mode 100644 index 0000000..361ed1b --- /dev/null +++ b/tests/compile.rs @@ -0,0 +1,198 @@ +//! End-to-end compile/check tests over the CLI-facing API. + +use marqdo_knowledge::cli::{CheckArgs, CompileArgs, EmbeddingArgs}; +use marqdo_knowledge::compiler; +use marqdo_knowledge::storage::read::ReadStore; +use std::path::{Path, PathBuf}; + +fn project(files: &[(&str, &str)]) -> PathBuf { + let temp = tempfile::tempdir().unwrap(); + let root = temp.path().to_path_buf(); + for (path, content) in files { + let absolute = root.join(path); + if let Some(parent) = absolute.parent() { + std::fs::create_dir_all(parent).unwrap(); + } + std::fs::write(absolute, content).unwrap(); + } + std::mem::forget(temp); + root +} + +fn compile_args(root: &Path) -> CompileArgs { + CompileArgs { + root: root.to_path_buf(), + exclude: Vec::new(), + rebuild: false, + json: true, + embedding: EmbeddingArgs::default(), + } +} + +fn check_args(root: &Path) -> CheckArgs { + CheckArgs { + root: root.to_path_buf(), + okf: false, + json: true, + } +} + +fn envelope(output: &marqdo_knowledge::cli::Output) -> serde_json::Value { + serde_json::from_str(&output.stdout).expect("machine envelope is valid JSON") +} + +fn core_bin() -> Option { + let path = PathBuf::from(std::env::var_os("MARQDO_TEST_BIN")?); + path.is_file().then_some(path) +} + +#[test] +fn plain_markdown_compiles_without_a_core_cli() { + let root = project(&[ + ( + "notes.md", + "# 笔记\n\n概率归一化是常见操作。\n\n参见[笔记](#笔记)。\n", + ), + ("dir/other.md", "# 其他\n\n内容。\n"), + ]); + let output = compiler::compile(&compile_args(&root), None).unwrap(); + assert_eq!(output.exit_code, 0); + let value = envelope(&output); + assert_eq!(value["schema"], "marqdo.knowledge.result"); + assert_eq!(value["command"], "compile"); + assert_eq!(value["success"], true); + assert_eq!(value["payload"]["documents"], 2); + assert_eq!(value["payload"]["mode"], "rebuild"); + assert!(value["snapshot_digest"] + .as_str() + .unwrap() + .starts_with("sha256:")); + assert!(root.join(".marqdo/knowledge.sqlite").is_file()); + let store = ReadStore::open(&root.join(".marqdo/knowledge.sqlite")).unwrap(); + store.integrity_check(true).unwrap(); + assert_eq!(store.build_meta().unwrap().core_identity, "native-only"); +} + +#[test] +fn incremental_compile_reuses_unchanged_documents_and_increments_generation() { + let root = project(&[("doc.md", "# 标题\n\n第一版内容。\n")]); + let first = compiler::compile(&compile_args(&root), None).unwrap(); + let first = envelope(&first); + assert_eq!(first["payload"]["mode"], "rebuild"); + let first_digest = first["snapshot_digest"].as_str().unwrap().to_string(); + assert_eq!(first["payload"]["rebuild_generation"], 1); + + let second = compiler::compile(&compile_args(&root), None).unwrap(); + let second = envelope(&second); + assert_eq!(second["payload"]["mode"], "incremental"); + assert_eq!(second["snapshot_digest"], first_digest); + // A no-op compile keeps the generation counter stable. + assert_eq!(second["payload"]["rebuild_generation"], 1); + + std::fs::write(root.join("doc.md"), "# 标题\n\n第二版内容。\n").unwrap(); + let third = compiler::compile(&compile_args(&root), None).unwrap(); + let third = envelope(&third); + assert_ne!(third["snapshot_digest"], first_digest); + assert_eq!(third["payload"]["rebuild_generation"], 2); + let store = ReadStore::open(&root.join(".marqdo/knowledge.sqlite")).unwrap(); + let query = marqdo_knowledge::text::fts_query("二版").unwrap(); + assert!(!store.fts_search(&query, 5).unwrap().is_empty()); + let old = marqdo_knowledge::text::fts_query("一版").unwrap(); + assert!(store.fts_search(&old, 5).unwrap().is_empty()); +} + +#[test] +fn rebuild_replaces_the_artifact_explicitly() { + let root = project(&[("doc.md", "# 标题\n\n内容。\n")]); + compiler::compile(&compile_args(&root), None).unwrap(); + let mut args = compile_args(&root); + args.rebuild = true; + let value = envelope(&compiler::compile(&args, None).unwrap()); + assert_eq!(value["payload"]["mode"], "rebuild"); + assert_eq!(value["payload"]["rebuild_generation"], 2); +} + +#[test] +fn check_reports_absent_then_current_database() { + let root = project(&[("doc.md", "# 标题\n\n内容。\n")]); + let absent = envelope(&compiler::check(&check_args(&root), None).unwrap()); + assert_eq!(absent["payload"]["database"], "absent"); + assert_eq!(absent["success"], true); + + compiler::compile(&compile_args(&root), None).unwrap(); + let current = compiler::check(&check_args(&root), None).unwrap(); + let value = envelope(¤t); + assert_eq!(value["payload"]["database"], "current"); + assert_eq!(current.exit_code, 0); + + std::fs::write(root.join("doc.md"), "# 标题\n\n改变。\n").unwrap(); + let stale = compiler::check(&check_args(&root), None).unwrap(); + let value = envelope(&stale); + assert_eq!(value["payload"]["database"], "stale"); + assert_eq!(stale.exit_code, 1); +} + +#[test] +fn check_fails_on_a_definite_broken_link() { + let root = project(&[("doc.md", "# 标题\n\n[x](missing.md)\n")]); + let output = compiler::check(&check_args(&root), None).unwrap(); + assert_eq!(output.exit_code, 1); + let value = envelope(&output); + assert_eq!(value["success"], false); + let diagnostics = value["diagnostics"].as_array().unwrap(); + assert!(diagnostics + .iter() + .any(|diagnostic| diagnostic["code"] == "knowledge.reference_missing")); +} + +#[test] +fn mixed_project_uses_real_analysis_when_available() { + let Some(core) = core_bin() else { + eprintln!("skip: MARQDO_TEST_BIN is not set"); + return; + }; + let root = project(&[ + ( + "marqdo.yaml", + "project:\n name: demo\n version: 0.1.0\n marqdo: \">=3.0.0-beta.1,<4.0.0\"\ndependencies: {}\n", + ), + ( + "physics/mechanics.mq.md", + "---\ntype: Theory\ntitle: 经典力学\n---\n\n# 经典力学\n\n## @knowledge 牛顿第二定律\n\n合外力等于质量与加速度的乘积。\n\n计算入口:[计算力](#计算力)。\n\n## @exec 计算力\n\n`params(m, a)`\n\n依据[牛顿第二定律](#牛顿第二定律)。\n\n`return m * a`\n", + ), + ( + "notes.md", + "# 笔记\n\n概率归一化。\n\n参见[经典力学](physics/mechanics.mq.md#经典力学)。\n", + ), + ]); + let output = compiler::compile(&compile_args(&root), Some(&core)).unwrap(); + assert_eq!(output.exit_code, 0, "{}", output.stderr); + let value = envelope(&output); + assert_eq!(value["payload"]["documents"], 2); + let store = ReadStore::open(&root.join(".marqdo/knowledge.sqlite")).unwrap(); + let meta = store.build_meta().unwrap(); + assert!(meta.producer_version.starts_with('3')); + assert!(meta.core_identity.starts_with("marqdo@")); + assert_eq!(store.contexts().unwrap().len(), 1); + // The Exec function is a real callable node with an upstream FunctionId. + let exact = store + .nodes_by_exact_name(&marqdo_knowledge::text::normalize("计算力")) + .unwrap(); + let function = exact + .iter() + .find(|node| node.kind == marqdo_knowledge::model::NodeKind::Function) + .expect("function node"); + let metadata = &function.metadata; + assert_eq!(metadata["callable"], true); + assert!(metadata["function_id"] + .as_str() + .unwrap() + .contains("::经典力学.计算力")); + // Plain Markdown link into the Marqdo module resolves to the anchored unit. + let hints = store + .aliases_for(metadata["function_id"].as_str().unwrap()) + .unwrap(); + assert!(!hints.is_empty()); + let check = compiler::check(&check_args(&root), Some(&core)).unwrap(); + assert_eq!(check.exit_code, 0, "{}", check.stderr); +}