Files
marqdo-knowledge/src/model.rs
T
marqdo-knowledge 59d5afe10b feat(analysis): consume the current public Analysis v3 contract
- add the process boundary for the core CLI: explicit MARQDO_BIN/--marqdo-bin
  only (never PATH), argv-only invocation of check ENTRY --emit, bounded
  timeout, private temp artifact, exit checks and absolute-path sanitisation
- deserialize every Analysis record with closed serde shapes and validate
  semantic invariants that JSON Schema cannot express: identities, source
  digests, UTF-8 spans, unit tree/order/mode ancestry, anchors, functions and
  signatures, references states, calls, resources, diagnostics and budgets
- validate statement/expression trees structurally with depth and span checks
- convert accepted modules into DocumentFacts, preserving honest upstream
  reference states and one node per Exec unit/function
- merge modules across entry contexts only when identity and source agree,
  otherwise report knowledge.analysis_context_conflict
- add the real rc.4 Analysis positive fixture (with provenance and regeneration
  script), tamper negative tests and optional real-binary integration tests
2026-11-26 00:29:19 +08:00

472 lines
14 KiB
Rust

//! Shared typed domain values.
//!
//! This module owns the small, dependency-free vocabulary that every other
//! module exchanges: source spans, canonical node identities, node/edge kinds
//! and diagnostics. It must not depend on the filesystem, SQLite, the core
//! Marqdo CLI or any network transport.
//!
//! Identity rule: a [`NodeKey`] is the UTF-8 percent-encoded canonical JSON
//! array of its structured parts. Parts are never concatenated with `#`, `::`
//! or `/`; encoding a tuple is unambiguous and stable across runs. The encoded
//! form is an opaque public id and the unique internal key.
use serde::{Deserialize, Serialize};
use std::fmt;
use std::str::FromStr;
/// Half-open byte range into a document's exact UTF-8 source.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Span {
pub start: u64,
pub end: u64,
}
impl Span {
pub fn new(start: u64, end: u64) -> Self {
Self { start, end }
}
pub fn len(self) -> u64 {
self.end.saturating_sub(self.start)
}
pub fn is_empty(self) -> bool {
self.start == self.end
}
pub fn contains(self, other: Span) -> bool {
self.start <= other.start && other.end <= self.end
}
/// Return the exact source slice when the span is valid and lies on UTF-8
/// boundaries. Never panics on hostile offsets.
pub fn slice(self, source: &[u8]) -> Option<&str> {
if self.start > self.end || self.end > source.len() as u64 {
return None;
}
let start = usize::try_from(self.start).ok()?;
let end = usize::try_from(self.end).ok()?;
std::str::from_utf8(&source[start..end]).ok()
}
pub fn on_utf8_boundaries(self, source: &[u8]) -> bool {
self.slice(source).is_some()
}
}
impl fmt::Display for Span {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}..{}", self.start, self.end)
}
}
/// Canonical, opaque node identity.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct NodeKey(String);
impl NodeKey {
/// Build a key from structured parts. The canonical serialisation is a
/// JSON array of strings, then RFC 3986 percent encoding of every byte
/// outside the unreserved set.
pub fn from_parts(parts: &[&str]) -> Self {
let json = serde_json::to_string(parts).expect("string array serialises");
Self(percent_encode(json.as_bytes()))
}
/// Parse a previously emitted key. The encoded bytes must decode to a JSON
/// string array and re-encode byte-identically (canonical form).
pub fn from_encoded(encoded: &str) -> Option<Self> {
let bytes = percent_decode(encoded.as_bytes())?;
let json = std::str::from_utf8(&bytes).ok()?;
let parts: Vec<String> = serde_json::from_str(json).ok()?;
let reencoded = serde_json::to_string(&parts).ok()?;
if percent_encode(reencoded.as_bytes()) == encoded {
Some(Self(encoded.to_string()))
} else {
None
}
}
pub fn as_str(&self) -> &str {
&self.0
}
pub fn into_string(self) -> String {
self.0
}
}
impl fmt::Display for NodeKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
fn is_unreserved(b: u8) -> bool {
b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~')
}
/// RFC 3986 percent encoding over bytes (upper-case hex).
pub fn percent_encode(bytes: &[u8]) -> String {
let mut out = String::with_capacity(bytes.len());
for &b in bytes {
if is_unreserved(b) {
out.push(char::from(b));
} else {
out.push('%');
out.push(char::from(hex_upper(b >> 4)));
out.push(char::from(hex_upper(b & 0x0f)));
}
}
out
}
/// Decode percent escapes exactly once. Returns `None` for malformed escapes
/// or embedded NUL bytes.
pub fn percent_decode(bytes: &[u8]) -> Option<Vec<u8>> {
let mut out = Vec::with_capacity(bytes.len());
let mut i = 0;
while i < bytes.len() {
if bytes[i] == b'%' {
if i + 2 >= bytes.len() {
return None;
}
let hi = hex_val(bytes[i + 1])?;
let lo = hex_val(bytes[i + 2])?;
let decoded = (hi << 4) | lo;
if decoded == 0 {
return None;
}
out.push(decoded);
i += 3;
} else {
out.push(bytes[i]);
i += 1;
}
}
Some(out)
}
fn hex_upper(n: u8) -> u8 {
match n {
0..=9 => b'0' + n,
_ => b'A' + (n - 10),
}
}
fn hex_val(b: u8) -> Option<u8> {
match b {
b'0'..=b'9' => Some(b - b'0'),
b'a'..=b'f' => Some(b - b'a' + 10),
b'A'..=b'F' => Some(b - b'A' + 10),
_ => None,
}
}
/// Lowercase hex SHA-256 digest, always prefixed for public output.
pub fn sha256_prefixed(bytes: &[u8]) -> String {
use sha2::{Digest, Sha256};
let mut hasher = Sha256::new();
hasher.update(bytes);
format!("sha256:{}", hex::encode(hasher.finalize()))
}
/// Bare lowercase hex SHA-256 digest for compact on-disk columns.
pub fn sha256_hex(bytes: &[u8]) -> String {
use sha2::{Digest, Sha256};
let mut hasher = Sha256::new();
hasher.update(bytes);
hex::encode(hasher.finalize())
}
pub fn is_sha256_prefixed(value: &str) -> bool {
value.len() == 71
&& value.starts_with("sha256:")
&& value[7..]
.bytes()
.all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase())
}
pub fn is_sha256_hex(value: &str) -> bool {
value.len() == 64
&& value
.bytes()
.all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase())
}
/// Node kinds of the single knowledge graph.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum NodeKind {
Document,
Namespace,
Section,
Function,
Statement,
Resource,
External,
}
impl NodeKind {
pub const ALL: [NodeKind; 7] = [
NodeKind::Document,
NodeKind::Namespace,
NodeKind::Section,
NodeKind::Function,
NodeKind::Statement,
NodeKind::Resource,
NodeKind::External,
];
pub fn as_str(self) -> &'static str {
match self {
NodeKind::Document => "document",
NodeKind::Namespace => "namespace",
NodeKind::Section => "section",
NodeKind::Function => "function",
NodeKind::Statement => "statement",
NodeKind::Resource => "resource",
NodeKind::External => "external",
}
}
}
impl FromStr for NodeKind {
type Err = String;
fn from_str(value: &str) -> Result<Self, Self::Err> {
match value {
"document" => Ok(NodeKind::Document),
"namespace" => Ok(NodeKind::Namespace),
"section" => Ok(NodeKind::Section),
"function" => Ok(NodeKind::Function),
"statement" => Ok(NodeKind::Statement),
"resource" => Ok(NodeKind::Resource),
"external" => Ok(NodeKind::External),
other => Err(format!(
"unsupported node kind `{other}` (expected one of: document, namespace, section, function, statement, resource, external)"
)),
}
}
}
impl fmt::Display for NodeKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
/// Edge kinds of the single knowledge graph.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum EdgeKind {
Contains,
References,
Imports,
Calls,
}
impl EdgeKind {
pub const ALL: [EdgeKind; 4] = [
EdgeKind::Contains,
EdgeKind::References,
EdgeKind::Imports,
EdgeKind::Calls,
];
pub fn as_str(self) -> &'static str {
match self {
EdgeKind::Contains => "contains",
EdgeKind::References => "references",
EdgeKind::Imports => "imports",
EdgeKind::Calls => "calls",
}
}
}
impl FromStr for EdgeKind {
type Err = String;
fn from_str(value: &str) -> Result<Self, Self::Err> {
match value {
"contains" => Ok(EdgeKind::Contains),
"references" => Ok(EdgeKind::References),
"imports" => Ok(EdgeKind::Imports),
"calls" => Ok(EdgeKind::Calls),
other => Err(format!(
"unsupported relation `{other}` (expected one of: contains, references, imports, calls)"
)),
}
}
}
impl fmt::Display for EdgeKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum EdgeOrigin {
Document,
Analysis,
}
impl EdgeOrigin {
pub fn as_str(self) -> &'static str {
match self {
EdgeOrigin::Document => "document",
EdgeOrigin::Analysis => "analysis",
}
}
}
/// Resolution state of a `references`, `imports` or `calls` edge. The graph
/// never invents a target: unresolved edges keep their raw target and state.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum EdgeState {
Resolved,
NotLoaded,
Missing,
Ambiguous,
External,
OutOfScope,
Invalid,
Dynamic,
Unresolved,
}
impl EdgeState {
pub fn as_str(self) -> &'static str {
match self {
EdgeState::Resolved => "resolved",
EdgeState::NotLoaded => "not_loaded",
EdgeState::Missing => "missing",
EdgeState::Ambiguous => "ambiguous",
EdgeState::External => "external",
EdgeState::OutOfScope => "out_of_scope",
EdgeState::Invalid => "invalid",
EdgeState::Dynamic => "dynamic",
EdgeState::Unresolved => "unresolved",
}
}
/// Whether the edge participates in a valid dependency closure.
pub fn is_bound(self) -> bool {
matches!(self, EdgeState::Resolved)
}
}
impl fmt::Display for EdgeState {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
/// Parse a resolution state emitted by the core Analysis artefact.
pub fn edge_state_from_analysis(value: &str) -> Option<EdgeState> {
match value {
"resolved" => Some(EdgeState::Resolved),
"not_loaded" => Some(EdgeState::NotLoaded),
"missing" => Some(EdgeState::Missing),
"ambiguous" => Some(EdgeState::Ambiguous),
"external" => Some(EdgeState::External),
"outside_scope" => Some(EdgeState::OutOfScope),
"invalid" => Some(EdgeState::Invalid),
"dynamic" => Some(EdgeState::Dynamic),
"unbound" | "unresolved" => Some(EdgeState::Unresolved),
_ => None,
}
}
/// Source format of a discovered document.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum DocumentFormat {
PlainMarkdown,
Marqdo,
}
impl DocumentFormat {
pub fn as_str(self) -> &'static str {
match self {
DocumentFormat::PlainMarkdown => "plain_markdown",
DocumentFormat::Marqdo => "marqdo",
}
}
pub fn from_path(path: &str) -> Option<Self> {
if path.ends_with(".mq.md") {
Some(DocumentFormat::Marqdo)
} else if path.ends_with(".md") {
Some(DocumentFormat::PlainMarkdown)
} else {
None
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn node_keys_are_canonical_and_unambiguous() {
let a = NodeKey::from_parts(&["unit", "a/b.md", "x/y"]);
let b = NodeKey::from_parts(&["unit", "a/b.md", "x/y"]);
assert_eq!(a, b);
// A part that itself contains the separators must not collide.
let c = NodeKey::from_parts(&["unit", "a/b.md#x/y"]);
let d = NodeKey::from_parts(&["unit", "a/b.md", "x/y"]);
assert_ne!(c, d);
// Round trip.
assert_eq!(NodeKey::from_encoded(a.as_str()).as_ref(), Some(&a));
}
#[test]
fn node_key_percent_encoding_escapes_reserved_bytes() {
let key = NodeKey::from_parts(&["document", "中文 #1.md"]);
assert!(!key.as_str().contains('#'));
assert!(!key.as_str().contains(' '));
assert!(key.as_str().contains("%23"));
}
#[test]
fn malformed_percent_escapes_are_rejected() {
assert!(percent_decode(b"%ZZ").is_none());
assert!(percent_decode(b"%0").is_none());
assert!(percent_decode(b"a%00b").is_none());
assert!(NodeKey::from_encoded("%ZZ").is_none());
}
#[test]
fn span_rejects_out_of_range_and_non_boundary() {
let source = "a中b".as_bytes();
assert_eq!(Span::new(0, 1).slice(source), Some("a"));
assert_eq!(Span::new(1, 4).slice(source), Some("中"));
assert_eq!(Span::new(0, 2).slice(source), None); // splits a CJK char
assert_eq!(Span::new(0, 9).slice(source), None);
assert_eq!(Span::new(5, 4).slice(source), None);
}
#[test]
fn node_kind_parsing_is_strict() {
assert_eq!("function".parse::<NodeKind>().unwrap(), NodeKind::Function);
assert!("knowledge".parse::<NodeKind>().is_err());
assert_eq!("calls".parse::<EdgeKind>().unwrap(), EdgeKind::Calls);
assert!("supports".parse::<EdgeKind>().is_err());
}
#[test]
fn digests_are_lowercase_prefixed() {
let digest = sha256_prefixed(b"abc");
assert!(is_sha256_prefixed(&digest));
assert!(is_sha256_hex(&sha256_hex(b"abc")));
assert!(!is_sha256_prefixed("sha256:ABC"));
}
}