chore: bootstrap marqdo-knowledge crate, CLI surface and architecture docs
- pin Rust 2021 / MSRV 1.89 and exact dependency versions - add typed model vocabulary (UTF-8 spans, canonical JSON-array node keys, node/edge/state enums, digest helpers) with unit tests - add deterministic diagnostics and unified error/exit semantics (0/1/2) - add the three-command clap surface with strict argument validation - record the single-derived-artifact decision, architecture overview and current public contract; STATUS lists real evidence only
This commit is contained in:
1 parent
fbca63b972
commit
430f950631
19 files changed
+2945
No files matched your search
+475
@@ -0,0 +1,475 @@
|
||||
//! Command-line surface, argument validation and result rendering.
|
||||
//!
|
||||
//! Only three business subcommands exist: `compile`, `check` and `query`.
|
||||
//! Argument parsing owns usage errors; rendering owns stdout/stderr so that the
|
||||
//! compiler and query layers never print.
|
||||
|
||||
use crate::error::{KnowledgeError, EXIT_INPUT, EXIT_OK, EXIT_USAGE};
|
||||
use crate::model::NodeKind;
|
||||
use clap::{Args, Parser, Subcommand, ValueEnum};
|
||||
use std::fmt::Write as _;
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// Process-wide flags and the selected subcommand.
|
||||
#[derive(Debug, Parser)]
|
||||
#[command(
|
||||
name = "marqdo-knowledge",
|
||||
version,
|
||||
about = "Compile Markdown and Marqdo documents into a deterministic, queryable knowledge projection.",
|
||||
long_about = None,
|
||||
disable_help_subcommand = true,
|
||||
propagate_version = true
|
||||
)]
|
||||
pub struct Cli {
|
||||
/// Core Marqdo binary used for static Analysis (`check --emit`).
|
||||
///
|
||||
/// Normally supplied by `marqdo` through `MARQDO_BIN`. The explicit flag is
|
||||
/// a development/test override; this tool never scans `PATH` for a guessed
|
||||
/// core binary.
|
||||
#[arg(long, global = true, value_name = "PATH", env = "MARQDO_BIN")]
|
||||
pub marqdo_bin: Option<PathBuf>,
|
||||
|
||||
#[command(subcommand)]
|
||||
pub command: Command,
|
||||
}
|
||||
|
||||
#[derive(Debug, Subcommand)]
|
||||
pub enum Command {
|
||||
/// Compile a knowledge root into `.marqdo/knowledge.sqlite`.
|
||||
Compile(CompileArgs),
|
||||
/// Statically check sources (and an existing database) without writing.
|
||||
Check(CheckArgs),
|
||||
/// Query the compiled knowledge projection.
|
||||
Query(QueryArgs),
|
||||
}
|
||||
|
||||
/// Embedding backend options shared by compile and query.
|
||||
///
|
||||
/// Semantic indexing is opt-in. No option here enables network access
|
||||
/// implicitly and no credential is accepted on the command line.
|
||||
#[derive(Debug, Clone, Args, Default)]
|
||||
pub struct EmbeddingArgs {
|
||||
/// OpenAI-compatible embeddings endpoint, for example
|
||||
/// `http://127.0.0.1:8080/v1`.
|
||||
#[arg(long, value_name = "URL")]
|
||||
pub embedding_url: Option<String>,
|
||||
|
||||
/// Embedding model identifier used for the index and query vectors.
|
||||
#[arg(long, value_name = "MODEL")]
|
||||
pub embedding_model: Option<String>,
|
||||
|
||||
/// User-declared immutable model revision.
|
||||
#[arg(long, value_name = "REVISION")]
|
||||
pub embedding_revision: Option<String>,
|
||||
|
||||
/// Explicitly permit a non-loopback (remote) embeddings endpoint. Remote
|
||||
/// endpoints must use TLS.
|
||||
#[arg(long)]
|
||||
pub allow_remote_embedding: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Args)]
|
||||
pub struct CompileArgs {
|
||||
/// Knowledge root directory (default: current directory). A single
|
||||
/// Markdown file is accepted as a one-document scope.
|
||||
#[arg(value_name = "ROOT", default_value = ".")]
|
||||
pub root: PathBuf,
|
||||
|
||||
/// Additional root-relative glob to exclude. Repeatable.
|
||||
#[arg(long, value_name = "GLOB")]
|
||||
pub exclude: Vec<String>,
|
||||
|
||||
/// Explicit full rebuild. Required after a schema change; never implicit.
|
||||
#[arg(long)]
|
||||
pub rebuild: bool,
|
||||
|
||||
/// Emit the machine result envelope on stdout.
|
||||
#[arg(long)]
|
||||
pub json: bool,
|
||||
|
||||
#[command(flatten)]
|
||||
pub embedding: EmbeddingArgs,
|
||||
}
|
||||
|
||||
#[derive(Debug, Args)]
|
||||
pub struct CheckArgs {
|
||||
/// Knowledge root directory (default: current directory).
|
||||
#[arg(value_name = "ROOT", default_value = ".")]
|
||||
pub root: PathBuf,
|
||||
|
||||
/// Also validate OKF bundle structure and metadata rules.
|
||||
#[arg(long)]
|
||||
pub okf: bool,
|
||||
|
||||
/// Emit the machine result envelope on stdout.
|
||||
#[arg(long)]
|
||||
pub json: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Args)]
|
||||
pub struct QueryArgs {
|
||||
/// Query text, or a canonical node id when `--exact`/`--slice` is used.
|
||||
#[arg(value_name = "QUERY")]
|
||||
pub query: String,
|
||||
|
||||
/// Knowledge root whose `.marqdo/knowledge.sqlite` is read (default: current
|
||||
/// directory).
|
||||
#[arg(long, value_name = "ROOT", default_value = ".")]
|
||||
pub root: PathBuf,
|
||||
|
||||
/// Exact identity/unique-name resolution only; never fuzzy.
|
||||
#[arg(long, conflicts_with = "semantic")]
|
||||
pub exact: bool,
|
||||
|
||||
/// Restrict returned hits to this node kind after candidate expansion.
|
||||
#[arg(long, value_name = "KIND")]
|
||||
pub kind: Option<String>,
|
||||
|
||||
/// Maximum number of hits (1..=100).
|
||||
#[arg(long, value_name = "N")]
|
||||
pub limit: Option<usize>,
|
||||
|
||||
/// Graph expansion depth for ranking (0 disables expansion; default 1).
|
||||
#[arg(long, value_name = "N")]
|
||||
pub depth: Option<usize>,
|
||||
|
||||
/// Restrict graph expansion to a relation kind. Repeatable.
|
||||
#[arg(long, value_name = "KIND")]
|
||||
pub relation: Vec<String>,
|
||||
|
||||
/// Traverse selected relations in reverse direction.
|
||||
#[arg(long)]
|
||||
pub reverse: bool,
|
||||
|
||||
/// Return a bounded reading/dependency slice from a unique seed.
|
||||
#[arg(long, value_name = "KIND")]
|
||||
pub slice: Option<SliceKind>,
|
||||
|
||||
/// Output format on stdout.
|
||||
#[arg(long, value_name = "FORMAT", default_value = "markdown")]
|
||||
pub format: OutputFormat,
|
||||
|
||||
/// Explicitly allow reading a stale snapshot instead of refusing it.
|
||||
#[arg(long)]
|
||||
pub snapshot: bool,
|
||||
|
||||
/// Require the embedding channel (implies a network request to the
|
||||
/// configured endpoint).
|
||||
#[arg(long)]
|
||||
pub semantic: bool,
|
||||
|
||||
#[command(flatten)]
|
||||
pub embedding: EmbeddingArgs,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
|
||||
pub enum SliceKind {
|
||||
Document,
|
||||
Execution,
|
||||
Hybrid,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
|
||||
pub enum OutputFormat {
|
||||
Markdown,
|
||||
Json,
|
||||
}
|
||||
|
||||
/// Rendered outcome of a subcommand.
|
||||
#[derive(Debug)]
|
||||
pub struct Output {
|
||||
pub stdout: String,
|
||||
pub stderr: String,
|
||||
pub exit_code: i32,
|
||||
}
|
||||
|
||||
impl Output {
|
||||
pub fn ok(stdout: String) -> Self {
|
||||
Self {
|
||||
stdout,
|
||||
stderr: String::new(),
|
||||
exit_code: EXIT_OK,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_diagnostics(mut self, diagnostics: &str) -> Self {
|
||||
self.stderr = diagnostics.to_string();
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse argv, execute and render. Returns the process exit code.
|
||||
pub fn run() -> i32 {
|
||||
let cli = match Cli::try_parse() {
|
||||
Ok(cli) => cli,
|
||||
Err(error) => {
|
||||
// clap owns usage/help/version rendering and uses exit code 2.
|
||||
error.print().ok();
|
||||
return error.exit_code();
|
||||
}
|
||||
};
|
||||
let machine = cli.command.machine_output();
|
||||
match execute(&cli) {
|
||||
Ok(output) => {
|
||||
print!("{}", output.stdout);
|
||||
eprint!("{}", output.stderr);
|
||||
output.exit_code
|
||||
}
|
||||
Err(error) => {
|
||||
if machine {
|
||||
print_json_error(&cli.command, &error);
|
||||
}
|
||||
eprintln!("marqdo-knowledge: {error}");
|
||||
error.exit_code
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Command {
|
||||
pub fn machine_output(&self) -> bool {
|
||||
match self {
|
||||
Command::Compile(args) => args.json,
|
||||
Command::Check(args) => args.json,
|
||||
Command::Query(args) => args.format == OutputFormat::Json,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn print_json_error(command: &Command, error: &KnowledgeError) {
|
||||
let name = match command {
|
||||
Command::Compile(_) => "compile",
|
||||
Command::Check(_) => "check",
|
||||
Command::Query(_) => "query",
|
||||
};
|
||||
let envelope = serde_json::json!({
|
||||
"schema": "marqdo.knowledge.error",
|
||||
"schema_version": 1,
|
||||
"command": name,
|
||||
"success": false,
|
||||
"error": {
|
||||
"code": error.code,
|
||||
"message": error.message,
|
||||
"hints": error.hints,
|
||||
"exit_code": error.exit_code,
|
||||
}
|
||||
});
|
||||
match serde_json::to_string_pretty(&envelope) {
|
||||
Ok(text) => println!("{text}"),
|
||||
Err(_) => println!(
|
||||
"{{\"schema\":\"marqdo.knowledge.error\",\"schema_version\":1,\"success\":false}}"
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// Validate the arguments that clap cannot express, then dispatch.
|
||||
fn execute(cli: &Cli) -> Result<Output, KnowledgeError> {
|
||||
match &cli.command {
|
||||
Command::Compile(args) => {
|
||||
validate_embedding(&args.embedding, false)?;
|
||||
let mut out = crate::compiler::compile(args, cli.marqdo_bin.as_deref())?;
|
||||
if !args.json {
|
||||
out.stdout = render_compile_human(&out.stdout)?;
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
Command::Check(args) => {
|
||||
let mut out = crate::compiler::check(args, cli.marqdo_bin.as_deref())?;
|
||||
if !args.json {
|
||||
out.stdout = render_check_human(&out.stdout)?;
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
Command::Query(args) => {
|
||||
validate_query(args)?;
|
||||
validate_embedding(&args.embedding, args.semantic)?;
|
||||
crate::query::run_query(args, cli.marqdo_bin.as_deref())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_query(args: &QueryArgs) -> Result<(), KnowledgeError> {
|
||||
if args.limit == Some(0) || args.limit.is_some_and(|n| n > 100) {
|
||||
return Err(KnowledgeError::usage(
|
||||
"--limit must be between 1 and 100 (default 10)",
|
||||
));
|
||||
}
|
||||
if let Some(depth) = args.depth {
|
||||
if depth > 8 {
|
||||
return Err(KnowledgeError::usage(
|
||||
"--depth must be between 0 and 8 (default 1)",
|
||||
));
|
||||
}
|
||||
}
|
||||
if let Some(kind) = &args.kind {
|
||||
kind.parse::<NodeKind>()
|
||||
.map_err(|message| KnowledgeError::usage(format!("--kind: {message}")))?;
|
||||
}
|
||||
for relation in &args.relation {
|
||||
relation
|
||||
.parse::<crate::model::EdgeKind>()
|
||||
.map_err(|message| KnowledgeError::usage(format!("--relation: {message}")))?;
|
||||
}
|
||||
if args.query.trim().is_empty() {
|
||||
return Err(KnowledgeError::usage("QUERY must not be empty"));
|
||||
}
|
||||
if args.query.len() > 4096 {
|
||||
return Err(KnowledgeError::usage(
|
||||
"QUERY exceeds the 4 KiB input budget",
|
||||
));
|
||||
}
|
||||
if args.slice.is_some() && args.semantic {
|
||||
return Err(KnowledgeError::usage(
|
||||
"--slice and --semantic cannot be combined: a slice needs a unique seed",
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_embedding(
|
||||
embedding: &EmbeddingArgs,
|
||||
semantic_required: bool,
|
||||
) -> Result<(), KnowledgeError> {
|
||||
let configured = embedding.embedding_url.is_some()
|
||||
|| embedding.embedding_model.is_some()
|
||||
|| embedding.embedding_revision.is_some();
|
||||
if semantic_required && !configured {
|
||||
return Err(KnowledgeError::environment(
|
||||
crate::diagnostic::code::EMBEDDING_UNAVAILABLE,
|
||||
"semantic search requires --embedding-url, --embedding-model and --embedding-revision",
|
||||
));
|
||||
}
|
||||
if configured {
|
||||
if embedding.embedding_url.is_none()
|
||||
|| embedding.embedding_model.is_none()
|
||||
|| embedding.embedding_revision.is_none()
|
||||
{
|
||||
return Err(KnowledgeError::usage(
|
||||
"--embedding-url, --embedding-model and --embedding-revision must be given together",
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Human rendering is intentionally thin: the command layer already produced
|
||||
/// structured facts and this function only formats them.
|
||||
fn render_compile_human(json_text: &str) -> Result<String, KnowledgeError> {
|
||||
let value: serde_json::Value = serde_json::from_str(json_text)
|
||||
.map_err(|_| KnowledgeError::internal("compile report is not valid JSON"))?;
|
||||
let payload = value.get("payload").cloned().unwrap_or_default();
|
||||
let mut text = String::new();
|
||||
let docs = payload
|
||||
.get("documents")
|
||||
.and_then(|v| v.as_u64())
|
||||
.unwrap_or(0);
|
||||
let nodes = payload.get("nodes").and_then(|v| v.as_u64()).unwrap_or(0);
|
||||
let edges = payload.get("edges").and_then(|v| v.as_u64()).unwrap_or(0);
|
||||
let mode = payload
|
||||
.get("mode")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("compiled");
|
||||
writeln!(
|
||||
text,
|
||||
"compiled {docs} document(s), {nodes} node(s), {edges} edge(s) ({mode})"
|
||||
)
|
||||
.map_err(|_| KnowledgeError::internal("formatting failed"))?;
|
||||
if let Some(digest) = value.get("snapshot_digest").and_then(|v| v.as_str()) {
|
||||
writeln!(text, "snapshot: {digest}")
|
||||
.map_err(|_| KnowledgeError::internal("formatting failed"))?;
|
||||
}
|
||||
let errors = payload.get("errors").and_then(|v| v.as_u64()).unwrap_or(0);
|
||||
let warnings = payload
|
||||
.get("warnings")
|
||||
.and_then(|v| v.as_u64())
|
||||
.unwrap_or(0);
|
||||
if errors + warnings > 0 {
|
||||
writeln!(
|
||||
text,
|
||||
"diagnostics: {errors} error(s), {warnings} warning(s)"
|
||||
)
|
||||
.map_err(|_| KnowledgeError::internal("formatting failed"))?;
|
||||
}
|
||||
Ok(text)
|
||||
}
|
||||
|
||||
fn render_check_human(json_text: &str) -> Result<String, KnowledgeError> {
|
||||
let value: serde_json::Value = serde_json::from_str(json_text)
|
||||
.map_err(|_| KnowledgeError::internal("check report is not valid JSON"))?;
|
||||
let payload = value.get("payload").cloned().unwrap_or_default();
|
||||
let documents = payload
|
||||
.get("documents")
|
||||
.and_then(|v| v.as_u64())
|
||||
.unwrap_or(0);
|
||||
let errors = payload.get("errors").and_then(|v| v.as_u64()).unwrap_or(0);
|
||||
let warnings = payload
|
||||
.get("warnings")
|
||||
.and_then(|v| v.as_u64())
|
||||
.unwrap_or(0);
|
||||
let database = payload
|
||||
.get("database")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("absent");
|
||||
let mut text = String::new();
|
||||
writeln!(
|
||||
text,
|
||||
"checked {documents} document(s): {errors} error(s), {warnings} warning(s)"
|
||||
)
|
||||
.map_err(|_| KnowledgeError::internal("formatting failed"))?;
|
||||
writeln!(text, "database: {database}")
|
||||
.map_err(|_| KnowledgeError::internal("formatting failed"))?;
|
||||
Ok(text)
|
||||
}
|
||||
|
||||
/// Exit code helper for commands that produce knowledge diagnostics.
|
||||
pub fn exit_code_for(errors: usize, warnings: usize) -> i32 {
|
||||
if errors > 0 {
|
||||
EXIT_INPUT
|
||||
} else if warnings > 0 {
|
||||
EXIT_OK
|
||||
} else {
|
||||
EXIT_OK
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse and validate a `--kind` value at the command boundary.
|
||||
pub fn parse_kind(value: &str) -> Result<NodeKind, String> {
|
||||
value.parse::<NodeKind>()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use clap::CommandFactory;
|
||||
|
||||
#[test]
|
||||
fn cli_definition_is_valid() {
|
||||
Cli::command().debug_assert();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn three_business_subcommands_only() {
|
||||
let command = Cli::command();
|
||||
let names: Vec<_> = command.get_subcommands().map(|c| c.get_name()).collect();
|
||||
assert_eq!(names, vec!["compile", "check", "query"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn query_rejects_exact_with_semantic() {
|
||||
use clap::Parser as _;
|
||||
let err = Cli::try_parse_from(["marqdo-knowledge", "query", "x", "--exact", "--semantic"])
|
||||
.unwrap_err();
|
||||
assert_eq!(err.exit_code(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn limit_and_kind_are_validated() {
|
||||
use clap::Parser as _;
|
||||
let cli =
|
||||
Cli::try_parse_from(["marqdo-knowledge", "query", "量子", "--limit", "101"]).unwrap();
|
||||
assert!(validate_query(match &cli.command {
|
||||
Command::Query(args) => args,
|
||||
_ => unreachable!(),
|
||||
})
|
||||
.is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
//! 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.
|
||||
|
||||
use crate::cli::Output;
|
||||
use crate::cli::{CheckArgs, CompileArgs};
|
||||
use crate::error::KnowledgeError;
|
||||
use std::path::Path;
|
||||
|
||||
/// Compile or incrementally update one knowledge root.
|
||||
pub fn compile(_args: &CompileArgs, _marqdo_bin: Option<&Path>) -> Result<Output, KnowledgeError> {
|
||||
Err(KnowledgeError::not_implemented("compile"))
|
||||
}
|
||||
|
||||
/// 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"))
|
||||
}
|
||||
@@ -0,0 +1,283 @@
|
||||
//! Diagnostics: stable codes, deterministic ordering, human rendering.
|
||||
//!
|
||||
//! A diagnostic always names a stable `knowledge.*` code, a severity, an
|
||||
//! optional root-relative path and an optional exact byte span. Diagnostics do
|
||||
//! not print source text and never contain machine absolute paths.
|
||||
|
||||
use crate::model::Span;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::fmt;
|
||||
|
||||
/// Stable diagnostic codes. Adding a code is an interface change.
|
||||
pub mod code {
|
||||
// Input and scope.
|
||||
pub const INVALID_ROOT: &str = "knowledge.invalid_root";
|
||||
pub const SCOPE_ESCAPE: &str = "knowledge.scope_escape";
|
||||
pub const SYMLINK_SKIPPED: &str = "knowledge.symlink_skipped";
|
||||
pub const EXCLUDED_PATH: &str = "knowledge.excluded_path";
|
||||
pub const BUDGET_EXCEEDED: &str = "knowledge.budget_exceeded";
|
||||
pub const INVALID_UTF8: &str = "knowledge.invalid_utf8";
|
||||
pub const IO: &str = "knowledge.io";
|
||||
pub const SOURCE_CHANGED: &str = "knowledge.source_changed";
|
||||
|
||||
// Core CLI integration.
|
||||
pub const NOT_LAUNCHED_BY_MARQDO: &str = "knowledge.not_launched_by_marqdo";
|
||||
pub const CORE_CLI_MISSING: &str = "knowledge.core_cli_missing";
|
||||
pub const CORE_CLI_FAILED: &str = "knowledge.core_cli_failed";
|
||||
pub const CORE_CLI_TIMEOUT: &str = "knowledge.core_cli_timeout";
|
||||
pub const ANALYSIS_MISSING: &str = "knowledge.analysis_missing";
|
||||
pub const ANALYSIS_INVALID: &str = "knowledge.analysis_invalid";
|
||||
pub const ANALYSIS_UNSUPPORTED: &str = "knowledge.analysis_unsupported";
|
||||
pub const ANALYSIS_CONTEXT_CONFLICT: &str = "knowledge.analysis_context_conflict";
|
||||
|
||||
// Documents.
|
||||
pub const MARKDOWN_INVALID: &str = "knowledge.markdown_invalid";
|
||||
pub const MARQDO_INVALID: &str = "knowledge.marqdo_invalid";
|
||||
pub const OKF_INVALID: &str = "knowledge.okf_invalid";
|
||||
pub const OKF_UNVERIFIED: &str = "knowledge.okf_unverified";
|
||||
pub const UNKNOWN_FRONT_MATTER: &str = "knowledge.unknown_front_matter";
|
||||
|
||||
// Graph and references.
|
||||
pub const REFERENCE_MISSING: &str = "knowledge.reference_missing";
|
||||
pub const REFERENCE_AMBIGUOUS: &str = "knowledge.reference_ambiguous";
|
||||
pub const REFERENCE_OUT_OF_SCOPE: &str = "knowledge.reference_out_of_scope";
|
||||
pub const REFERENCE_INVALID: &str = "knowledge.reference_invalid";
|
||||
pub const REFERENCE_EXTERNAL: &str = "knowledge.reference_external";
|
||||
pub const REFERENCE_NOT_LOADED: &str = "knowledge.reference_not_loaded";
|
||||
pub const IDENTITY_AMBIGUOUS: &str = "knowledge.identity_ambiguous";
|
||||
pub const INTERFACE_CONFLICT: &str = "knowledge.interface_conflict";
|
||||
|
||||
// Storage and freshness.
|
||||
pub const DATABASE_MISSING: &str = "knowledge.database_missing";
|
||||
pub const DATABASE_OLD_SCHEMA: &str = "knowledge.database_old_schema";
|
||||
pub const DATABASE_NOT_OURS: &str = "knowledge.database_not_ours";
|
||||
pub const DATABASE_CORRUPT: &str = "knowledge.database_corrupt";
|
||||
pub const DATABASE_STALE: &str = "knowledge.database_stale";
|
||||
pub const SNAPSHOT_STALE: &str = "knowledge.snapshot_stale";
|
||||
pub const REBUILD_REQUIRED: &str = "knowledge.rebuild_required";
|
||||
|
||||
// Query.
|
||||
pub const QUERY_INVALID: &str = "knowledge.query_invalid";
|
||||
pub const QUERY_NO_RESULTS: &str = "knowledge.query_no_results";
|
||||
pub const QUERY_UNSUPPORTED: &str = "knowledge.query_unsupported";
|
||||
pub const SLICE_SEED_AMBIGUOUS: &str = "knowledge.slice_seed_ambiguous";
|
||||
pub const SLICE_SEED_MISSING: &str = "knowledge.slice_seed_missing";
|
||||
pub const BUDGET: &str = "knowledge.budget";
|
||||
|
||||
// Embeddings.
|
||||
pub const EMBEDDING_DISABLED: &str = "knowledge.embedding_disabled";
|
||||
pub const EMBEDDING_CONFIG_MISMATCH: &str = "knowledge.embedding_config_mismatch";
|
||||
pub const EMBEDDING_REMOTE_NOT_ALLOWED: &str = "knowledge.embedding_remote_not_allowed";
|
||||
pub const EMBEDDING_TRANSPORT: &str = "knowledge.embedding_transport";
|
||||
pub const EMBEDDING_INVALID_RESPONSE: &str = "knowledge.embedding_invalid_response";
|
||||
pub const EMBEDDING_UNAVAILABLE: &str = "knowledge.embedding_unavailable";
|
||||
|
||||
// Usage.
|
||||
pub const USAGE: &str = "knowledge.usage";
|
||||
pub const NOT_IMPLEMENTED: &str = "knowledge.not_implemented";
|
||||
pub const INTERNAL: &str = "knowledge.internal";
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Severity {
|
||||
Error,
|
||||
Warning,
|
||||
}
|
||||
|
||||
impl Severity {
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Severity::Error => "error",
|
||||
Severity::Warning => "warning",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One deterministic diagnostic.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Diagnostic {
|
||||
pub code: String,
|
||||
pub severity: Severity,
|
||||
pub path: Option<String>,
|
||||
pub span: Option<Span>,
|
||||
pub message: String,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub hints: Vec<String>,
|
||||
}
|
||||
|
||||
impl Diagnostic {
|
||||
pub fn error(code: &str, message: impl Into<String>) -> Self {
|
||||
Self {
|
||||
code: code.to_string(),
|
||||
severity: Severity::Error,
|
||||
path: None,
|
||||
span: None,
|
||||
message: message.into(),
|
||||
hints: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn warning(code: &str, message: impl Into<String>) -> Self {
|
||||
Self {
|
||||
code: code.to_string(),
|
||||
severity: Severity::Warning,
|
||||
path: None,
|
||||
span: None,
|
||||
message: message.into(),
|
||||
hints: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_path(mut self, path: impl Into<String>) -> Self {
|
||||
self.path = Some(path.into());
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_span(mut self, span: Span) -> Self {
|
||||
self.span = Some(span);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_hint(mut self, hint: impl Into<String>) -> Self {
|
||||
self.hints.push(hint.into());
|
||||
self
|
||||
}
|
||||
|
||||
pub fn is_error(&self) -> bool {
|
||||
self.severity == Severity::Error
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for Diagnostic {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "{} [{}]", self.severity.as_str(), self.code)?;
|
||||
if let Some(path) = &self.path {
|
||||
write!(f, " {path}")?;
|
||||
if let Some(span) = self.span {
|
||||
write!(f, ":{span}")?;
|
||||
}
|
||||
}
|
||||
write!(f, ": {}", self.message)?;
|
||||
for hint in &self.hints {
|
||||
write!(f, "\n hint: {hint}")?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// A deterministic diagnostic collection.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct DiagnosticSet {
|
||||
items: Vec<Diagnostic>,
|
||||
}
|
||||
|
||||
impl DiagnosticSet {
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
pub fn push(&mut self, diagnostic: Diagnostic) {
|
||||
self.items.push(diagnostic);
|
||||
}
|
||||
|
||||
pub fn extend(&mut self, other: impl IntoIterator<Item = Diagnostic>) {
|
||||
self.items.extend(other);
|
||||
}
|
||||
|
||||
pub fn merge(&mut self, mut other: DiagnosticSet) {
|
||||
self.items.append(&mut other.items);
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.items.is_empty()
|
||||
}
|
||||
|
||||
pub fn len(&self) -> usize {
|
||||
self.items.len()
|
||||
}
|
||||
|
||||
pub fn has_errors(&self) -> bool {
|
||||
self.items.iter().any(Diagnostic::is_error)
|
||||
}
|
||||
|
||||
pub fn error_count(&self) -> usize {
|
||||
self.items.iter().filter(|d| d.is_error()).count()
|
||||
}
|
||||
|
||||
pub fn warning_count(&self) -> usize {
|
||||
self.items.iter().filter(|d| !d.is_error()).count()
|
||||
}
|
||||
|
||||
pub fn iter(&self) -> impl Iterator<Item = &Diagnostic> {
|
||||
self.items.iter()
|
||||
}
|
||||
|
||||
pub fn into_vec(self) -> Vec<Diagnostic> {
|
||||
self.items
|
||||
}
|
||||
|
||||
pub fn as_slice(&self) -> &[Diagnostic] {
|
||||
&self.items
|
||||
}
|
||||
|
||||
/// Sort by path, span start, code, then message for stable output and
|
||||
/// stable logical digests.
|
||||
pub fn sorted(&mut self) {
|
||||
self.items.sort_by(|a, b| {
|
||||
a.path
|
||||
.cmp(&b.path)
|
||||
.then(a.span.map(|s| s.start).cmp(&b.span.map(|s| s.start)))
|
||||
.then(a.span.map(|s| s.end).cmp(&b.span.map(|s| s.end)))
|
||||
.then(a.code.cmp(&b.code))
|
||||
.then(a.message.cmp(&b.message))
|
||||
});
|
||||
self.items.dedup();
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoIterator for DiagnosticSet {
|
||||
type Item = Diagnostic;
|
||||
type IntoIter = std::vec::IntoIter<Diagnostic>;
|
||||
|
||||
fn into_iter(self) -> Self::IntoIter {
|
||||
self.items.into_iter()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn diagnostics_sort_deterministically() {
|
||||
let mut set = DiagnosticSet::new();
|
||||
set.push(
|
||||
Diagnostic::error(code::IO, "b")
|
||||
.with_path("a.md")
|
||||
.with_span(Span::new(5, 8)),
|
||||
);
|
||||
set.push(
|
||||
Diagnostic::error(code::IO, "a")
|
||||
.with_path("a.md")
|
||||
.with_span(Span::new(1, 2)),
|
||||
);
|
||||
set.push(Diagnostic::warning(code::OKF_UNVERIFIED, "w").with_path("b.md"));
|
||||
set.sorted();
|
||||
let paths: Vec<_> = set.iter().map(|d| d.path.as_deref().unwrap()).collect();
|
||||
assert_eq!(paths, vec!["a.md", "a.md", "b.md"]);
|
||||
assert_eq!(set.error_count(), 2);
|
||||
assert_eq!(set.warning_count(), 1);
|
||||
assert!(set.has_errors());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn diagnostic_display_has_no_source_text() {
|
||||
let d = Diagnostic::error(code::REFERENCE_MISSING, "missing target")
|
||||
.with_path("a.md")
|
||||
.with_span(Span::new(1, 3));
|
||||
let text = d.to_string();
|
||||
assert!(text.contains("knowledge.reference_missing"));
|
||||
assert!(text.contains("a.md:1..3"));
|
||||
}
|
||||
}
|
||||
+103
@@ -0,0 +1,103 @@
|
||||
//! Unified error type and process exit semantics.
|
||||
//!
|
||||
//! Exit codes are part of the public contract:
|
||||
//! * `0` success (an empty search result is still success);
|
||||
//! * `1` input knowledge/validation failure (invalid source, definite broken
|
||||
//! link, negative check result);
|
||||
//! * `2` usage, protocol, database absence/old schema, I/O and hard resource
|
||||
//! budget failures.
|
||||
//!
|
||||
//! Errors never carry source text, secrets or machine absolute paths in their
|
||||
//! public message.
|
||||
|
||||
use crate::diagnostic::code;
|
||||
use std::fmt;
|
||||
|
||||
pub const EXIT_OK: i32 = 0;
|
||||
pub const EXIT_INPUT: i32 = 1;
|
||||
pub const EXIT_USAGE: i32 = 2;
|
||||
|
||||
/// A fatal knowledge error with a stable code and an exit class.
|
||||
#[derive(Debug)]
|
||||
pub struct KnowledgeError {
|
||||
pub code: &'static str,
|
||||
pub message: String,
|
||||
pub hints: Vec<String>,
|
||||
/// `1` for invalid knowledge/input, `2` for usage/protocol/environment.
|
||||
pub exit_code: i32,
|
||||
}
|
||||
|
||||
impl KnowledgeError {
|
||||
pub fn usage(message: impl Into<String>) -> Self {
|
||||
Self {
|
||||
code: code::USAGE,
|
||||
message: message.into(),
|
||||
hints: Vec::new(),
|
||||
exit_code: EXIT_USAGE,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn input(code: &'static str, message: impl Into<String>) -> Self {
|
||||
Self {
|
||||
code,
|
||||
message: message.into(),
|
||||
hints: Vec::new(),
|
||||
exit_code: EXIT_INPUT,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn environment(code: &'static str, message: impl Into<String>) -> Self {
|
||||
Self {
|
||||
code,
|
||||
message: message.into(),
|
||||
hints: Vec::new(),
|
||||
exit_code: EXIT_USAGE,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn internal(message: impl Into<String>) -> Self {
|
||||
Self {
|
||||
code: code::INTERNAL,
|
||||
message: message.into(),
|
||||
hints: Vec::new(),
|
||||
exit_code: EXIT_USAGE,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn not_implemented(what: &str) -> Self {
|
||||
Self {
|
||||
code: code::NOT_IMPLEMENTED,
|
||||
message: format!("{what} is not implemented in this build"),
|
||||
hints: vec!["see docs/STATUS.md for the current capability matrix".to_string()],
|
||||
exit_code: EXIT_USAGE,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_hint(mut self, hint: impl Into<String>) -> Self {
|
||||
self.hints.push(hint.into());
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_exit_code(mut self, exit_code: i32) -> Self {
|
||||
self.exit_code = exit_code;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for KnowledgeError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "{}: {}", self.code, self.message)?;
|
||||
for hint in &self.hints {
|
||||
write!(f, "\n hint: {hint}")?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for KnowledgeError {}
|
||||
|
||||
impl From<std::io::Error> for KnowledgeError {
|
||||
fn from(error: std::io::Error) -> Self {
|
||||
KnowledgeError::environment(code::IO, error.to_string())
|
||||
}
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
//! `marqdo-knowledge` public library surface.
|
||||
//!
|
||||
//! The binary is a thin wrapper: [`run`] parses argv, dispatches the internal
|
||||
//! layers and returns the process exit code. Library consumers (tests,
|
||||
//! independent protocol consumers) use this crate's public modules; no module
|
||||
//! exposes a second query or Analysis contract.
|
||||
|
||||
pub mod cli;
|
||||
pub mod compiler;
|
||||
pub mod diagnostic;
|
||||
pub mod error;
|
||||
pub mod model;
|
||||
pub mod query;
|
||||
|
||||
/// Run the command line. Returns the process exit code (0/1/2).
|
||||
pub fn run() -> i32 {
|
||||
cli::run()
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
//! Binary entry point: only process setup and the exit code live here.
|
||||
|
||||
fn main() {
|
||||
std::process::exit(marqdo_knowledge::run());
|
||||
}
|
||||
+471
@@ -0,0 +1,471 @@
|
||||
//! 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<'a>(self, source: &'a [u8]) -> Option<&'a 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"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
//! Read-only query surface: exact lookup, lexical/fuzzy candidates, fusion,
|
||||
//! bounded graph expansion and Markdown slices.
|
||||
//!
|
||||
//! Filled in by the query milestones. Query never mutates graph facts or the
|
||||
//! knowledge sources.
|
||||
|
||||
use crate::cli::Output;
|
||||
use crate::cli::QueryArgs;
|
||||
use crate::error::KnowledgeError;
|
||||
use std::path::Path;
|
||||
|
||||
/// Execute one query against `.marqdo/knowledge.sqlite` under the requested
|
||||
/// root. Does not compile implicitly.
|
||||
pub fn run_query(_args: &QueryArgs, _marqdo_bin: Option<&Path>) -> Result<Output, KnowledgeError> {
|
||||
Err(KnowledgeError::not_implemented("query"))
|
||||
}
|
||||
Reference in new issue
Block a user