- 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
592 lines
19 KiB
Rust
592 lines
19 KiB
Rust
//! Document layer: deterministic discovery, plain Markdown projection, the
|
|
//! core Analysis v3 adapter and OKF recognition.
|
|
//!
|
|
//! The layer never writes the database and never renders output. Every fact it
|
|
//! returns carries the exact UTF-8 byte span it came from and the digest of the
|
|
//! source snapshot it belongs to.
|
|
|
|
pub mod analysis;
|
|
pub mod ast;
|
|
pub mod core_cli;
|
|
pub mod discovery;
|
|
pub mod markdown;
|
|
pub mod okf;
|
|
|
|
use crate::diagnostic::DiagnosticSet;
|
|
pub use crate::model::DocumentFormat;
|
|
use crate::model::Span;
|
|
use serde::{Deserialize, Serialize};
|
|
use std::path::PathBuf;
|
|
|
|
/// Hard input budgets. They are part of the safety contract: hard overruns
|
|
/// abort publication instead of producing a partial database.
|
|
pub const PER_FILE_LIMIT: u64 = 16 * 1024 * 1024;
|
|
pub const TOTAL_SOURCE_LIMIT: u64 = 512 * 1024 * 1024;
|
|
pub const DOCUMENT_LIMIT: usize = 100_000;
|
|
pub const MAX_AST_DEPTH: usize = 256;
|
|
pub const MAX_SQLITE_BYTES: u64 = 4 * 1024 * 1024 * 1024;
|
|
pub const MAX_MANIFEST_BYTES: u64 = 1024 * 1024;
|
|
|
|
/// Configurable limits (tests use smaller values; production uses the default).
|
|
#[derive(Debug, Clone, Copy)]
|
|
pub struct Limits {
|
|
pub per_file: u64,
|
|
pub total_source: u64,
|
|
pub documents: usize,
|
|
pub manifest: u64,
|
|
}
|
|
|
|
impl Default for Limits {
|
|
fn default() -> Self {
|
|
Self {
|
|
per_file: PER_FILE_LIMIT,
|
|
total_source: TOTAL_SOURCE_LIMIT,
|
|
documents: DOCUMENT_LIMIT,
|
|
manifest: MAX_MANIFEST_BYTES,
|
|
}
|
|
}
|
|
}
|
|
|
|
/// The explicitly selected compilation scope.
|
|
#[derive(Debug, Clone)]
|
|
pub struct Scope {
|
|
/// Canonical absolute root directory.
|
|
pub root: PathBuf,
|
|
/// When the user named a single Markdown file, its root-relative path.
|
|
pub single_file: Option<String>,
|
|
/// Validated, root-relative exclusion globs in the order given.
|
|
pub excludes: Vec<String>,
|
|
/// Compiled exclusion patterns (parallel to `excludes`).
|
|
pub patterns: Vec<glob::Pattern>,
|
|
pub limits: Limits,
|
|
}
|
|
|
|
impl Scope {
|
|
pub fn dir_for_database(&self) -> PathBuf {
|
|
self.root.join(".marqdo")
|
|
}
|
|
|
|
pub fn database_path(&self) -> PathBuf {
|
|
self.dir_for_database().join("knowledge.sqlite")
|
|
}
|
|
|
|
/// Deterministic description stored in build metadata. Uses no absolute
|
|
/// machine paths.
|
|
pub fn describe(&self) -> serde_json::Value {
|
|
serde_json::json!({
|
|
"single_file": self.single_file,
|
|
"excludes": self.excludes,
|
|
})
|
|
}
|
|
}
|
|
|
|
/// One discovered Markdown document with its exact bytes.
|
|
#[derive(Debug, Clone)]
|
|
pub struct SourceFile {
|
|
/// Root-relative path with `/` separators.
|
|
pub rel_path: String,
|
|
/// Absolute path used only for local I/O (never emitted).
|
|
pub abs_path: PathBuf,
|
|
pub format: DocumentFormat,
|
|
/// Exact decoded UTF-8 source; `text.as_bytes()` equals the file bytes.
|
|
pub text: String,
|
|
/// `sha256:` + lowercase hex of the raw bytes.
|
|
pub digest: String,
|
|
}
|
|
|
|
impl SourceFile {
|
|
pub fn bytes(&self) -> &[u8] {
|
|
self.text.as_bytes()
|
|
}
|
|
|
|
pub fn len(&self) -> u64 {
|
|
self.bytes().len() as u64
|
|
}
|
|
|
|
pub fn is_empty(&self) -> bool {
|
|
self.bytes().is_empty()
|
|
}
|
|
|
|
/// Exact source slice for a span, or `None` when invalid.
|
|
pub fn slice(&self, span: Span) -> Option<&str> {
|
|
span.slice(self.bytes())
|
|
}
|
|
}
|
|
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
pub enum InputKind {
|
|
Document,
|
|
Manifest,
|
|
Lock,
|
|
Asset,
|
|
}
|
|
|
|
impl InputKind {
|
|
pub fn as_str(self) -> &'static str {
|
|
match self {
|
|
InputKind::Document => "document",
|
|
InputKind::Manifest => "manifest",
|
|
InputKind::Lock => "lock",
|
|
InputKind::Asset => "asset",
|
|
}
|
|
}
|
|
}
|
|
|
|
/// One file that participated in the snapshot.
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
pub struct InputRecord {
|
|
pub path: String,
|
|
pub kind: InputKind,
|
|
pub digest: String,
|
|
pub size: u64,
|
|
}
|
|
|
|
/// A referenced non-Markdown asset. Only path, size and (within budget) digest
|
|
/// are recorded; content is never indexed as text.
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
pub struct AssetFile {
|
|
pub rel_path: String,
|
|
pub size: u64,
|
|
pub digest: Option<String>,
|
|
}
|
|
|
|
/// The immutable source snapshot used for one compile.
|
|
#[derive(Debug)]
|
|
pub struct SourceSnapshot {
|
|
pub scope: Scope,
|
|
/// Accepted documents, sorted byte-wise by `rel_path`.
|
|
pub files: Vec<SourceFile>,
|
|
pub assets: Vec<AssetFile>,
|
|
pub manifest: Option<InputRecord>,
|
|
pub lock: Option<InputRecord>,
|
|
pub diagnostics: DiagnosticSet,
|
|
pub total_bytes: u64,
|
|
}
|
|
|
|
impl SourceSnapshot {
|
|
/// All inputs in deterministic order (documents, manifest, lock, assets).
|
|
pub fn inputs(&self) -> Vec<InputRecord> {
|
|
let mut inputs: Vec<InputRecord> = self
|
|
.files
|
|
.iter()
|
|
.map(|file| InputRecord {
|
|
path: file.rel_path.clone(),
|
|
kind: InputKind::Document,
|
|
digest: file.digest.clone(),
|
|
size: file.len(),
|
|
})
|
|
.collect();
|
|
if let Some(manifest) = &self.manifest {
|
|
inputs.push(manifest.clone());
|
|
}
|
|
if let Some(lock) = &self.lock {
|
|
inputs.push(lock.clone());
|
|
}
|
|
inputs.extend(self.assets.iter().map(|asset| {
|
|
InputRecord {
|
|
path: asset.rel_path.clone(),
|
|
kind: InputKind::Asset,
|
|
digest: asset
|
|
.digest
|
|
.clone()
|
|
.unwrap_or_else(|| format!("size:{}", asset.size)),
|
|
size: asset.size,
|
|
}
|
|
}));
|
|
inputs.sort_by(|a, b| {
|
|
a.path
|
|
.cmp(&b.path)
|
|
.then(a.kind.as_str().cmp(b.kind.as_str()))
|
|
});
|
|
inputs
|
|
}
|
|
|
|
/// Re-read every recorded input and compare digests. Used immediately
|
|
/// before publishing so a concurrently edited source never produces a
|
|
/// mixed snapshot.
|
|
pub fn verify_unchanged(&self) -> DiagnosticSet {
|
|
let mut diagnostics = DiagnosticSet::new();
|
|
for file in &self.files {
|
|
match std::fs::read(&file.abs_path) {
|
|
Ok(bytes) => {
|
|
let digest = crate::model::sha256_prefixed(&bytes);
|
|
if digest != file.digest || bytes != file.bytes() {
|
|
diagnostics.push(
|
|
crate::diagnostic::Diagnostic::error(
|
|
crate::diagnostic::code::SOURCE_CHANGED,
|
|
"source changed while compiling; the snapshot was not published",
|
|
)
|
|
.with_path(&file.rel_path),
|
|
);
|
|
}
|
|
}
|
|
Err(error) => diagnostics.push(
|
|
crate::diagnostic::Diagnostic::error(
|
|
crate::diagnostic::code::SOURCE_CHANGED,
|
|
format!("source cannot be re-read before publishing: {error}"),
|
|
)
|
|
.with_path(&file.rel_path),
|
|
),
|
|
}
|
|
}
|
|
for (record, abs) in self.non_document_inputs() {
|
|
match std::fs::read(&abs) {
|
|
Ok(bytes) => {
|
|
let digest = crate::model::sha256_prefixed(&bytes);
|
|
if digest != record.digest {
|
|
diagnostics.push(
|
|
crate::diagnostic::Diagnostic::error(
|
|
crate::diagnostic::code::SOURCE_CHANGED,
|
|
"input changed while compiling; the snapshot was not published",
|
|
)
|
|
.with_path(&record.path),
|
|
);
|
|
}
|
|
}
|
|
Err(_) => {
|
|
// Removal is a change too.
|
|
diagnostics.push(
|
|
crate::diagnostic::Diagnostic::error(
|
|
crate::diagnostic::code::SOURCE_CHANGED,
|
|
"input disappeared while compiling; the snapshot was not published",
|
|
)
|
|
.with_path(&record.path),
|
|
);
|
|
}
|
|
}
|
|
}
|
|
diagnostics
|
|
}
|
|
|
|
fn non_document_inputs(&self) -> Vec<(InputRecord, PathBuf)> {
|
|
let mut out = Vec::new();
|
|
if let Some(manifest) = &self.manifest {
|
|
out.push((manifest.clone(), self.scope.root.join(&manifest.path)));
|
|
}
|
|
if let Some(lock) = &self.lock {
|
|
out.push((lock.clone(), self.scope.root.join(&lock.path)));
|
|
}
|
|
for asset in &self.assets {
|
|
if let Some(digest) = &asset.digest {
|
|
out.push((
|
|
InputRecord {
|
|
path: asset.rel_path.clone(),
|
|
kind: InputKind::Asset,
|
|
digest: digest.clone(),
|
|
size: asset.size,
|
|
},
|
|
self.scope.root.join(&asset.rel_path),
|
|
));
|
|
} else {
|
|
let abs = self.scope.root.join(&asset.rel_path);
|
|
match std::fs::metadata(&abs) {
|
|
Ok(metadata) if metadata.len() == asset.size => {}
|
|
_ => out.push((
|
|
InputRecord {
|
|
path: asset.rel_path.clone(),
|
|
kind: InputKind::Asset,
|
|
digest: format!("size:{}", asset.size),
|
|
size: asset.size,
|
|
},
|
|
abs,
|
|
)),
|
|
}
|
|
}
|
|
}
|
|
out
|
|
}
|
|
|
|
/// Deterministic snapshot manifest digest over all recorded inputs and the
|
|
/// scope description. Independent of absolute paths and wall-clock time.
|
|
pub fn snapshot_digest(&self) -> String {
|
|
let mut buffer = String::new();
|
|
let described = self.scope.describe().to_string();
|
|
buffer.push_str("scope\n");
|
|
buffer.push_str(&described);
|
|
buffer.push('\n');
|
|
for input in self.inputs() {
|
|
buffer.push_str(input.kind.as_str());
|
|
buffer.push('\t');
|
|
buffer.push_str(&input.path);
|
|
buffer.push('\t');
|
|
buffer.push_str(&input.digest);
|
|
buffer.push('\n');
|
|
}
|
|
crate::model::sha256_prefixed(buffer.as_bytes())
|
|
}
|
|
}
|
|
|
|
/// Unit kinds as projected into graph nodes. The document root maps to the
|
|
/// document node; an Exec H2 and its function are one node.
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
|
#[serde(rename_all = "snake_case")]
|
|
pub enum UnitKind {
|
|
Root,
|
|
Namespace,
|
|
Knowledge,
|
|
Function,
|
|
Section,
|
|
}
|
|
|
|
impl UnitKind {
|
|
pub fn as_str(self) -> &'static str {
|
|
match self {
|
|
UnitKind::Root => "root",
|
|
UnitKind::Namespace => "namespace",
|
|
UnitKind::Knowledge => "knowledge",
|
|
UnitKind::Function => "function",
|
|
UnitKind::Section => "section",
|
|
}
|
|
}
|
|
}
|
|
|
|
/// One heading scope. `path` is authoritative; ids are never split.
|
|
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
|
pub struct UnitFact {
|
|
/// Canonical structured heading path; `[]` for the root.
|
|
pub path: Vec<String>,
|
|
pub kind: UnitKind,
|
|
pub name: String,
|
|
pub level: u8,
|
|
/// Complete section range (root: whole source).
|
|
pub span: Span,
|
|
pub heading_span: Option<Span>,
|
|
/// Index into the same unit vector.
|
|
pub parent: Option<usize>,
|
|
/// Canonical upstream FunctionId for an Exec section.
|
|
pub function_id: Option<String>,
|
|
/// Upstream canonical UnitId when the fact came from Analysis.
|
|
pub unit_id: Option<String>,
|
|
/// Effective mode: `knowledge` or `exec`.
|
|
pub mode: String,
|
|
/// Deterministic occurrence index for duplicate canonical paths (0 for
|
|
/// the first occurrence). Together with `path` it makes the node key
|
|
/// unique without changing the authoritative path.
|
|
pub occurrence: u32,
|
|
}
|
|
|
|
/// Navigation anchor (unique by construction).
|
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
|
pub struct AnchorFact {
|
|
pub anchor: String,
|
|
pub unit: usize,
|
|
}
|
|
|
|
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
|
pub struct FunctionFact {
|
|
pub function_id: String,
|
|
pub unit: usize,
|
|
pub local_name: String,
|
|
pub namespace: Option<String>,
|
|
pub span: Span,
|
|
pub heading_span: Span,
|
|
pub signature: serde_json::Value,
|
|
pub effects: Vec<String>,
|
|
pub body: serde_json::Value,
|
|
}
|
|
|
|
/// Upstream resolution record for a Marqdo Markdown link. Knowledge must not
|
|
/// re-bind a resolved target and must not turn `not_loaded` into `missing`.
|
|
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
|
pub struct AnalysisReferenceFact {
|
|
pub state: crate::model::EdgeState,
|
|
pub target_kind: Option<String>,
|
|
pub target_module: Option<String>,
|
|
pub target_unit: Option<String>,
|
|
pub candidate_package_instance_id: Option<String>,
|
|
pub candidate_path: Option<String>,
|
|
pub fragment: Option<String>,
|
|
pub candidates: Vec<String>,
|
|
}
|
|
|
|
/// One Markdown link/image occurrence.
|
|
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
|
pub struct ReferenceFact {
|
|
/// Raw URL exactly as written (never percent-decoded).
|
|
pub url: String,
|
|
pub span: Span,
|
|
/// Innermost unit containing the occurrence.
|
|
pub unit: usize,
|
|
pub is_image: bool,
|
|
pub title: Option<String>,
|
|
/// Present only for `.mq.md` facts that came from Analysis.
|
|
pub analysis: Option<AnalysisReferenceFact>,
|
|
}
|
|
|
|
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
|
pub struct ImportFact {
|
|
pub alias: String,
|
|
pub target: String,
|
|
pub span: Span,
|
|
pub unit: usize,
|
|
/// Canonical resolved module id, or `None` for a diagnostic import.
|
|
pub resolved: Option<String>,
|
|
}
|
|
|
|
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
|
pub struct CallFact {
|
|
/// Canonical owning FunctionId.
|
|
pub function_id: String,
|
|
pub span: Span,
|
|
pub callee: serde_json::Value,
|
|
/// `function`, `builtin`, `plugin` or `unresolved`.
|
|
pub state: String,
|
|
pub target: Option<String>,
|
|
pub target_kind: Option<String>,
|
|
pub target_owner: Option<serde_json::Value>,
|
|
pub reason: Option<String>,
|
|
}
|
|
|
|
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
|
pub struct ResourceFact {
|
|
pub id: String,
|
|
pub kind: String,
|
|
pub span: Span,
|
|
pub content_digest: String,
|
|
pub language: Option<String>,
|
|
pub display: Option<bool>,
|
|
/// Innermost unit containing the resource.
|
|
pub unit: usize,
|
|
}
|
|
|
|
/// One extractable content block used to build search units.
|
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
|
#[serde(rename_all = "snake_case")]
|
|
pub enum BlockKind {
|
|
Paragraph,
|
|
List,
|
|
Quote,
|
|
Table,
|
|
Formula,
|
|
Code,
|
|
Html,
|
|
Other,
|
|
}
|
|
|
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
|
pub struct BlockFact {
|
|
pub kind: BlockKind,
|
|
pub span: Span,
|
|
/// Innermost unit owning the block.
|
|
pub unit: usize,
|
|
pub text: String,
|
|
pub formula: String,
|
|
pub table: String,
|
|
pub links: String,
|
|
pub code: String,
|
|
}
|
|
|
|
/// Bounded front-matter facts. YAML is parsed only to a JSON value with strict
|
|
/// size/depth/alias limits; the raw literal is always preserved.
|
|
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
|
pub struct FrontMatterFact {
|
|
pub span: Span,
|
|
pub literal: String,
|
|
pub value: Option<serde_json::Value>,
|
|
pub error: Option<String>,
|
|
}
|
|
|
|
/// Analysis context identity of one `.mq.md` module.
|
|
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
|
pub struct AnalysisFacts {
|
|
pub module_id: String,
|
|
pub package_instance_id: String,
|
|
pub context_id: String,
|
|
pub entry_module_id: String,
|
|
pub root_id: String,
|
|
pub identity_kind: String,
|
|
pub manifest_digest: String,
|
|
pub lock_digest: String,
|
|
pub stdlib_digest: Option<String>,
|
|
pub producer_version: String,
|
|
/// SHA-256 of the exact emitted Analysis bytes.
|
|
pub analysis_digest: String,
|
|
pub extensions: serde_json::Value,
|
|
}
|
|
|
|
/// Everything one document contributes to the graph, before linking.
|
|
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
|
pub struct DocumentFacts {
|
|
pub rel_path: String,
|
|
pub format: DocumentFormat,
|
|
pub source_digest: String,
|
|
pub document_title: String,
|
|
pub ast: crate::document::ast::AstNode,
|
|
pub units: Vec<UnitFact>,
|
|
pub anchors: Vec<AnchorFact>,
|
|
pub functions: Vec<FunctionFact>,
|
|
pub imports: Vec<ImportFact>,
|
|
pub references: Vec<ReferenceFact>,
|
|
pub calls: Vec<CallFact>,
|
|
pub resources: Vec<ResourceFact>,
|
|
pub blocks: Vec<BlockFact>,
|
|
pub front_matter: Option<FrontMatterFact>,
|
|
/// OKF document-layer recognition. Metadata never changes program semantics.
|
|
#[serde(default)]
|
|
pub okf: okf::OkfInfo,
|
|
pub analysis: Option<AnalysisFacts>,
|
|
pub diagnostics: DiagnosticSet,
|
|
}
|
|
|
|
impl DocumentFacts {
|
|
/// Innermost unit whose complete span contains `span`. The root unit is the
|
|
/// fallback and always spans the whole source.
|
|
pub fn innermost_unit(&self, span: Span) -> usize {
|
|
let mut best = 0usize;
|
|
let mut best_level = 0u8;
|
|
for (index, unit) in self.units.iter().enumerate() {
|
|
if index == 0 {
|
|
continue;
|
|
}
|
|
if unit.span.contains(span) && unit.level >= best_level {
|
|
best = index;
|
|
best_level = unit.level;
|
|
}
|
|
}
|
|
best
|
|
}
|
|
|
|
/// Node path for a unit: the document root is the empty path.
|
|
pub fn unit_path(&self, unit: usize) -> Vec<String> {
|
|
self.units
|
|
.get(unit)
|
|
.map(|unit| unit.path.clone())
|
|
.unwrap_or_default()
|
|
}
|
|
|
|
pub fn function_by_id(&self, function_id: &str) -> Option<&FunctionFact> {
|
|
self.functions
|
|
.iter()
|
|
.find(|function| function.function_id == function_id)
|
|
}
|
|
}
|
|
|
|
pub(crate) fn facts_cache_version() -> u32 {
|
|
// Bump when the serialised DocumentFacts shape or extraction semantics
|
|
// change. The cache is derived data; a mismatch forces re-extraction.
|
|
2
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn facts_cache_version_is_positive() {
|
|
assert!(facts_cache_version() >= 1);
|
|
}
|
|
|
|
#[test]
|
|
fn scope_database_path_is_fixed_below_root() {
|
|
let root = PathBuf::from("/tmp/example");
|
|
let scope = Scope {
|
|
root: root.clone(),
|
|
single_file: None,
|
|
excludes: Vec::new(),
|
|
patterns: Vec::new(),
|
|
limits: Limits::default(),
|
|
};
|
|
assert_eq!(scope.database_path(), root.join(".marqdo/knowledge.sqlite"));
|
|
}
|
|
}
|