feat(document): normalized AST and plain Markdown projection

- add the closed normalized AST shape shared by the plain projection and
  upstream Analysis, with required-attribute, UTF-8 span and depth validation
- parse plain .md with pinned comrak 1.0.0 fixed options (GFM tables,
  footnotes, task lists, strikethrough, autolink, dollar math, front matter)
- convert parser line/column positions to exact half-open byte spans and keep
  BOM/CRLF/CJK byte identity
- build heading units (complete section spans, parents, occurrence-indexed
  duplicate paths), fixed-rule anchors, raw link facts and searchable blocks
- parse front matter as bounded YAML to JSON with alias/depth/size rejection
  while preserving the raw literal; plain @exec text stays inert
- add shared DocumentFacts vocabulary with serde caching shape
This commit is contained in:
marqdo-knowledge committed 2026-11-26 00:11:30 +08:00
1 parent f2f3b38eca
commit 682717a610
5 files changed
+1648 -4

No files matched your search

+255
View File
@@ -6,12 +6,14 @@
//! source snapshot it belongs to.
pub mod analysis;
pub mod ast;
pub mod discovery;
pub mod markdown;
pub mod okf;
use crate::diagnostic::DiagnosticSet;
use crate::model::{DocumentFormat, Span};
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
/// Hard input budgets. They are part of the safety contract: hard overruns
@@ -312,10 +314,263 @@ impl SourceSnapshot {
}
}
/// 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>,
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 unit.span.contains(span) && (index == 0 || unit.level >= best_level) {
if index == 0 || 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)
}
}
#[allow(dead_code)] // consumed by the incremental compiler milestone
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.
1
}
#[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");