feat(compiler): end-to-end compile and check orchestration

- resolve scope, discover exact snapshot, project plain Markdown, run real
  Analysis for .mq.md entries, cross-check module source bytes, merge contexts
  and reject uncovered/invalid Marqdo documents
- collect referenced local assets and known-missing paths before linking so a
  missing file is distinguished from an unindexed/excluded one
- incremental plan by content-digest change set: unchanged documents reuse
  digest-guarded facts; any .mq.md/manifest/lock/core-identity change triggers
  the conservative full re-analysis; plain-only edits never invoke Analysis
- no-op compiles preserve the stored snapshot and generation; rebuilds
  increment the generation and atomically replace the artifact
- recheck every source digest immediately before publishing, never mixing
  snapshots, and refuse to publish graphs with blocking diagnostics
- check validates sources, references, Analysis coverage, database structure
  and currentness, writes nothing and exits 1 for definite broken links
- add end-to-end tests for plain-only compile without a core binary, mixed
  real-Analysis compile, incremental/rebuild/no-op, stale database and broken
  links
This commit is contained in:
marqdo-knowledge committed 2026-11-26 01:21:29 +08:00
1 parent cca8fbdab1
commit 66f3e168c4
5 files changed
+1106 -14

No files matched your search

+872 -10
View File
@@ -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<Output, KnowledgeError> {
Err(KnowledgeError::not_implemented("compile"))
pub fn compile(args: &CompileArgs, marqdo_bin: Option<&Path>) -> Result<Output, KnowledgeError> {
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<CompileOutcome, KnowledgeError> {
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<PreviousState> =
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<String, DocumentFacts> = 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<ProjectContext> = 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<DocumentFacts> = 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<Output, KnowledgeError> {
Err(KnowledgeError::not_implemented("check"))
pub fn check(args: &CheckArgs, marqdo_bin: Option<&Path>) -> Result<Output, KnowledgeError> {
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<String, DocumentFacts> = 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<DocumentFacts> = 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<ProjectContext>,
inputs: HashMap<String, String>,
cache: HashMap<String, CachedFacts>,
}
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<Option<PreviousState>, 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<String, CachedFacts>,
contexts: Vec<ProjectContext>,
changed_inputs: Vec<String>,
}
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<String, String> = snapshot
.inputs()
.into_iter()
.map(|input| (input.path, input.digest))
.collect();
let mut changed_inputs = Vec::new();
for (path, digest) in &current_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<String> = 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<String, DocumentFacts>,
) -> Result<(Vec<crate::document::AssetFile>, HashSet<String>), KnowledgeError> {
let documents: HashSet<&str> = snapshot
.files
.iter()
.map(|file| file.rel_path.as_str())
.collect();
let mut candidates: Vec<String> = 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_"));
}
}
}
+1
View File
@@ -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)]
+23 -1
View File
@@ -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
}
+12 -3
View File
@@ -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<u64, KnowledgeError> {
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