- add a transport client for one current backend protocol with loopback http, TLS-only remote endpoints, explicit remote consent, disabled redirects, bounded timeout/batch/payload/response/dimension and no credential in URLs - validate responses strictly (count, index order, dimension, finite values, non-zero norm, mixed-model rejection) and abort publication when any vector is missing so a mixed index is never stored - embed search units in the same transaction that writes the projection, with content-digest/model-digest guarded reuse for incremental compiles; the build metadata records endpoint/model/revision/dimension/distance/chunking - add the semantic query channel behind explicit --semantic using an exact cosine scan with a bounded vector budget; default queries stay completely offline even when vectors exist - add a local mock-server integration test proving protocol handling, cross-vocabulary recall, offline default behaviour, remote consent rules and all-or-nothing failure; real-model quality remains NOT RUN and is not claimed
1035 lines
38 KiB
Rust
1035 lines
38 KiB
Rust
//! Compile orchestration: the single write-transaction boundary.
|
|
//!
|
|
//! ```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::{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> {
|
|
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,
|
|
"embeddings": outcome.stats.embeddings,
|
|
"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())?;
|
|
|
|
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, false);
|
|
diagnostics.merge(graph.diagnostics.clone());
|
|
if graph.diagnostics.has_errors() {
|
|
return Err(fatal_from_diagnostics(&diagnostics));
|
|
}
|
|
|
|
// Semantic index preparation (explicit opt-in only). All vectors must be
|
|
// ready and complete before the transaction starts; any failure aborts the
|
|
// whole compile and publishes nothing.
|
|
let mut embedding_meta: Option<serde_json::Value> = None;
|
|
let mut embedding_vectors: Option<crate::embedding::EmbeddingVectors> = None;
|
|
if let Some(url) = &args.embedding.embedding_url {
|
|
let model = args
|
|
.embedding
|
|
.embedding_model
|
|
.clone()
|
|
.ok_or_else(|| KnowledgeError::usage("--embedding-model is required"))?;
|
|
let revision = args
|
|
.embedding
|
|
.embedding_revision
|
|
.clone()
|
|
.ok_or_else(|| KnowledgeError::usage("--embedding-revision is required"))?;
|
|
let config = crate::embedding::EmbeddingConfig::new(
|
|
url,
|
|
&model,
|
|
&revision,
|
|
args.embedding.allow_remote_embedding,
|
|
)?;
|
|
let client = crate::embedding::EmbeddingClient::new(&config)?;
|
|
let sources = storage::index::embedding_sources(&graph)?;
|
|
if sources.is_empty() {
|
|
return Err(KnowledgeError::environment(
|
|
code::EMBEDDING_UNAVAILABLE,
|
|
"there are no search units to embed in this root",
|
|
));
|
|
}
|
|
let mut reused: HashMap<String, Vec<f32>> = HashMap::new();
|
|
let mut dimension = 0usize;
|
|
let mut stored_digest: Option<String> = None;
|
|
if let Some(previous) = previous_ref {
|
|
if let Some(stored) = &previous.meta.embedding {
|
|
let stored_endpoint = stored.get("endpoint").and_then(|value| value.as_str());
|
|
let stored_model = stored.get("model").and_then(|value| value.as_str());
|
|
let stored_revision = stored.get("revision").and_then(|value| value.as_str());
|
|
if stored_endpoint == Some(client.endpoint())
|
|
&& stored_model == Some(model.as_str())
|
|
&& stored_revision == Some(revision.as_str())
|
|
{
|
|
dimension = stored
|
|
.get("dimension")
|
|
.and_then(|value| value.as_u64())
|
|
.unwrap_or(0) as usize;
|
|
stored_digest = stored
|
|
.get("model_digest")
|
|
.and_then(|value| value.as_str())
|
|
.map(str::to_string);
|
|
}
|
|
}
|
|
}
|
|
if dimension > 0 {
|
|
let digest = config.model_digest(dimension)?;
|
|
if stored_digest.as_deref() == Some(digest.as_str()) {
|
|
reused = previous_ref
|
|
.map(|previous| previous.embedding_vectors.clone())
|
|
.unwrap_or_default();
|
|
}
|
|
}
|
|
let mut vectors: HashMap<(String, u64, String), Vec<f32>> = HashMap::new();
|
|
let mut missing: Vec<&crate::embedding::EmbeddingSource> = Vec::new();
|
|
for source in &sources {
|
|
match reused.get(&source.content_digest) {
|
|
Some(vector) => {
|
|
vectors.insert(
|
|
(
|
|
source.node_key.clone(),
|
|
source.span_start,
|
|
source.content_digest.clone(),
|
|
),
|
|
vector.clone(),
|
|
);
|
|
}
|
|
None => missing.push(source),
|
|
}
|
|
}
|
|
if !missing.is_empty() {
|
|
let texts: Vec<String> = missing.iter().map(|source| source.text.clone()).collect();
|
|
let (new_vectors, new_dimension) = client.embed(&texts)?;
|
|
if dimension == 0 {
|
|
dimension = new_dimension;
|
|
} else if dimension != new_dimension {
|
|
return Err(KnowledgeError::environment(
|
|
code::EMBEDDING_CONFIG_MISMATCH,
|
|
"embedding model returned a different dimension than the existing index",
|
|
));
|
|
}
|
|
for (source, vector) in missing.iter().zip(new_vectors) {
|
|
vectors.insert(
|
|
(
|
|
source.node_key.clone(),
|
|
source.span_start,
|
|
source.content_digest.clone(),
|
|
),
|
|
vector,
|
|
);
|
|
}
|
|
}
|
|
if dimension == 0 {
|
|
return Err(KnowledgeError::environment(
|
|
code::EMBEDDING_INVALID_RESPONSE,
|
|
"embedding endpoint returned no dimension",
|
|
));
|
|
}
|
|
let model_digest = config.model_digest(dimension)?;
|
|
embedding_meta = Some(serde_json::json!(crate::embedding::EmbeddingMeta {
|
|
endpoint: config.endpoint()?,
|
|
model,
|
|
revision,
|
|
dimension,
|
|
distance: crate::embedding::DISTANCE.to_string(),
|
|
model_digest: model_digest.clone(),
|
|
chunking: crate::embedding::CHUNKING.to_string(),
|
|
max_input_chars: crate::embedding::MAX_INPUT_CHARS,
|
|
}));
|
|
embedding_vectors = Some(crate::embedding::EmbeddingVectors {
|
|
model_digest,
|
|
dimension,
|
|
vectors,
|
|
});
|
|
}
|
|
|
|
// 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,
|
|
embeddings: previous
|
|
.meta
|
|
.embedding
|
|
.as_ref()
|
|
.map_or(0, |_| previous.meta.search_units),
|
|
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 = embedding_meta;
|
|
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,
|
|
embeddings: embedding_vectors.as_ref(),
|
|
})?;
|
|
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> {
|
|
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, args.okf);
|
|
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();
|
|
// A plain check fails on a definite broken link. In explicit OKF mode the
|
|
// OKF conformance rules tolerate broken links (they are reported as
|
|
// notices), so only structural/metadata errors fail the bundle check.
|
|
let definite_broken = !args.okf
|
|
&& 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>,
|
|
embedding_vectors: HashMap<String, Vec<f32>>,
|
|
}
|
|
|
|
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,
|
|
embedding: Option<serde_json::Value>,
|
|
}
|
|
|
|
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()?,
|
|
embedding: meta.embedding.clone(),
|
|
},
|
|
contexts: store.contexts()?,
|
|
inputs: store
|
|
.inputs()?
|
|
.into_iter()
|
|
.map(|input| (input.path, input.digest))
|
|
.collect(),
|
|
cache: HashMap::new(),
|
|
embedding_vectors: 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,
|
|
embedding: None,
|
|
},
|
|
contexts: Vec::new(),
|
|
inputs: HashMap::new(),
|
|
cache: HashMap::new(),
|
|
embedding_vectors: 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 embedding_vectors = match meta
|
|
.embedding
|
|
.as_ref()
|
|
.and_then(|embedding| embedding.get("model_digest"))
|
|
.and_then(|digest| digest.as_str())
|
|
{
|
|
Some(model_digest) => store.all_embeddings_by_digest(model_digest)?,
|
|
None => HashMap::new(),
|
|
};
|
|
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,
|
|
embedding: meta.embedding.clone(),
|
|
},
|
|
contexts: store.contexts()?,
|
|
inputs: store
|
|
.inputs()?
|
|
.into_iter()
|
|
.map(|input| (input.path, input.digest))
|
|
.collect(),
|
|
cache,
|
|
embedding_vectors,
|
|
}))
|
|
}
|
|
|
|
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 ¤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<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
|
|
// ---------------------------------------------------------------------------
|
|
|
|
pub(crate) 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() {
|
|
// OKF `resource` is an explicit path field and participates in the
|
|
// snapshot as a referenced asset.
|
|
if let Some(resource) = facts.okf.resource_is_relative_path() {
|
|
if let Ok(rel) = discovery::resolve_link_path(&facts.rel_path, resource) {
|
|
candidates.push(rel);
|
|
}
|
|
}
|
|
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_"));
|
|
}
|
|
}
|
|
}
|