Files
marqdo-knowledge/tests/query.rs
cflmy 98ed8e5c49
ci/woodpecker/pr/ci Pipeline was successful
feat: expose document role in query hits
Continue marqdo-knowledge#14 P2 with one additive, path-convention-derived
field on every query hit: role = entry (index.mq.md), index/log (OKF reserved
files), document (other .mq.md), concept (other .md), or unknown without a
source path.

This is navigation information for agents, not execution or authority: no new
metadata syntax, no extra source read, no second index. spec/knowledge.md
records the field and the path mapping; tests/query.rs compiles a real project
with all four roles; STATUS records implementation and test.

No release; schema_version stays 1 (additive optional-aware field).
2026-11-30 17:01:54 +08:00

328 lines
11 KiB
Rust

//! End-to-end query tests over a compiled plain-Markdown project.
use marqdo_knowledge::cli::{
CheckArgs, CompileArgs, EmbeddingArgs, OutputFormat, QueryArgs, SliceKind,
};
use marqdo_knowledge::compiler;
use marqdo_knowledge::query;
use std::path::{Path, PathBuf};
fn project(files: &[(&str, &str)]) -> PathBuf {
let temp = tempfile::tempdir().unwrap();
let root = temp.path().to_path_buf();
for (path, content) in files {
let absolute = root.join(path);
if let Some(parent) = absolute.parent() {
std::fs::create_dir_all(parent).unwrap();
}
std::fs::write(absolute, content).unwrap();
}
std::mem::forget(temp);
root
}
fn compile(root: &Path) {
let args = CompileArgs {
root: root.to_path_buf(),
exclude: Vec::new(),
rebuild: false,
json: true,
embedding: EmbeddingArgs::default(),
};
compiler::compile(&args, None).unwrap();
}
fn query_args(root: &Path, query: &str) -> QueryArgs {
QueryArgs {
query: query.to_string(),
root: root.to_path_buf(),
exact: false,
kind: None,
limit: None,
depth: None,
relation: Vec::new(),
reverse: false,
slice: None,
format: OutputFormat::Json,
snapshot: false,
semantic: false,
embedding: EmbeddingArgs::default(),
}
}
fn run(_root: &Path, args: QueryArgs) -> serde_json::Value {
let output = query::run_query(&args, None).unwrap();
assert_eq!(output.exit_code, 0, "{}", output.stderr);
serde_json::from_str(&output.stdout).expect("query envelope is valid JSON")
}
fn sample_project() -> PathBuf {
let root = project(&[
(
"physics/mechanics.md",
"# 经典力学\n\n## 牛顿第二定律\n\n合外力等于质量与加速度的乘积。\n\n计算入口:[计算力](../compute.md#计算力)。\n\n## 归一化动机\n\n消除向量模长影响,归一化是常见操作。\n\n相关计算:[计算力](../compute.md#计算力)。\n",
),
(
"compute.md",
"# 计算\n\n## 计算力\n\n依据[牛顿第二定律](physics/mechanics.md#牛顿第二定律)。\n\n`return m * a`\n\n| 符号 | 含义 |\n| --- | --- |\n| m | 质量 |\n",
),
]);
compile(&root);
root
}
#[test]
fn lexical_channel_finds_two_character_chinese() {
let root = sample_project();
let value = run(&root, query_args(&root, "牛顿"));
let hits = value["hits"].as_array().unwrap();
assert!(!hits.is_empty());
assert_eq!(hits[0]["title"], "牛顿第二定律");
assert_eq!(value["schema"], "marqdo.knowledge.result");
assert_eq!(value["command"], "query");
assert_eq!(value["current"], true);
assert!(value["channels"]
.as_array()
.unwrap()
.iter()
.any(|channel| channel == "lexical"));
// Snippets are exact source substrings.
let source = std::fs::read_to_string(root.join("physics/mechanics.md")).unwrap();
assert!(source.contains(hits[0]["snippet"].as_str().unwrap()));
}
#[test]
fn hits_return_a_stable_location_and_evidence_status() {
// Candidate location contract (issue #14/#12): a hit must carry the exact
// document-structure identity and source evidence, without re-parsing.
let root = sample_project();
let value = run(&root, query_args(&root, "牛顿"));
let hit = value["hits"]
.as_array()
.unwrap()
.iter()
.find(|hit| hit["location"]["path"].is_array())
.expect("a unit hit with a location");
let location = &hit["location"];
assert!(!location["path"].as_array().unwrap().is_empty());
assert!(location["unit_kind"].is_string());
assert!(location["mode"].is_string());
assert_eq!(location["nature"], "unspecified");
assert!(location["span"]["start"].as_u64().is_some());
assert!(hit["source"]["path"].is_string());
let evidence = &hit["evidence"];
assert_eq!(evidence["status"], "current");
assert!(evidence["source_digest"]
.as_str()
.unwrap()
.starts_with("sha256:"));
assert!(evidence["snapshot_digest"]
.as_str()
.unwrap()
.starts_with("sha256:"));
assert_eq!(value["schema"], "marqdo.knowledge.result");
assert_eq!(value["schema_version"], 1);
}
#[test]
fn fuzzy_channel_recalls_a_typo_query() {
let root = sample_project();
let value = run(&root, query_args(&root, "归依化"));
let hits = value["hits"].as_array().unwrap();
assert!(!hits.is_empty());
let titles: Vec<&str> = hits
.iter()
.filter_map(|hit| hit["title"].as_str())
.collect();
assert!(titles.iter().any(|title| title.contains("归一化")));
assert!(value["channels"]
.as_array()
.unwrap()
.iter()
.any(|channel| channel == "fuzzy"));
}
#[test]
fn exact_mode_returns_address_or_ambiguous_candidates() {
let root = sample_project();
let mut args = query_args(&root, "牛顿第二定律");
args.exact = true;
let value = run(&root, args);
assert_eq!(value["hits"].as_array().unwrap().len(), 1);
assert_eq!(value["hits"][0]["matches"][0]["field"], "address");
let canonical = value["hits"][0]["id"].as_str().unwrap().to_string();
let mut args = query_args(&root, &canonical);
args.exact = true;
let value = run(&root, args);
assert_eq!(value["hits"][0]["id"], canonical);
// Two nodes share the display title "经典力学" (document + H1 unit).
let mut args = query_args(&root, "经典力学");
args.exact = true;
let value = run(&root, args);
assert_eq!(value["hits"].as_array().unwrap().len(), 2);
assert!(value["diagnostics"]
.as_array()
.unwrap()
.iter()
.any(|diagnostic| diagnostic["code"] == "knowledge.query_ambiguous"));
}
#[test]
fn kind_filter_applies_after_expansion() {
let root = sample_project();
let mut args = query_args(&root, "计算力");
args.kind = Some("function".to_string());
let value = run(&root, args);
// No function exists in a plain-Markdown project.
assert!(value["hits"].as_array().unwrap().is_empty());
assert!(value["diagnostics"]
.as_array()
.unwrap()
.iter()
.any(|diagnostic| diagnostic["code"] == "knowledge.query_no_results"));
}
#[test]
fn graph_expansion_finds_linked_neighbours() {
let root = sample_project();
let mut args = query_args(&root, "归一化动机");
args.depth = Some(1);
let value = run(&root, args);
let hits = value["hits"].as_array().unwrap();
assert!(
hits.iter().any(|hit| {
hit["title"] == "计算力"
&& hit["matches"]
.as_array()
.unwrap()
.iter()
.any(|reason| reason["channel"] == "graph")
}),
"graph expansion must reach the linked section: {hits:?}"
);
}
#[test]
fn slices_keep_exact_source_and_respect_the_budget() {
let root = sample_project();
let mut args = query_args(&root, "牛顿第二定律");
args.slice = Some(SliceKind::Document);
let value = run(&root, args);
let slice = &value["payload"]["slice"];
assert_eq!(slice["kind"], "document");
assert_eq!(slice["complete"], true);
let pieces = slice["pieces"].as_array().unwrap();
assert!(!pieces.is_empty());
let seed_text = pieces[0]["text"].as_str().unwrap();
let source = std::fs::read_to_string(root.join("physics/mechanics.md")).unwrap();
assert!(source.contains(seed_text));
assert!(slice["returned_bytes"].as_u64().unwrap() <= 32768);
let mut args = query_args(&root, "牛顿第二定律");
args.slice = Some(SliceKind::Execution);
let value = run(&root, args);
assert_eq!(value["payload"]["slice"]["kind"], "execution");
}
#[test]
fn stale_database_is_refused_unless_snapshot_is_explicit() {
let root = sample_project();
std::fs::write(root.join("compute.md"), "# 计算\n\n新的内容。\n").unwrap();
let error = query::run_query(&query_args(&root, "牛顿"), None).unwrap_err();
assert_eq!(error.code, "knowledge.database_stale");
assert_eq!(error.exit_code, 2);
let mut args = query_args(&root, "牛顿");
args.snapshot = true;
let value = run(&root, args);
assert_eq!(value["current"], false);
assert!(value["diagnostics"]
.as_array()
.unwrap()
.iter()
.any(|diagnostic| diagnostic["code"] == "knowledge.snapshot_stale"));
}
#[test]
fn missing_database_does_not_compile_implicitly() {
let root = project(&[("doc.md", "# t\n")]);
let error = query::run_query(&query_args(&root, "t"), None).unwrap_err();
assert_eq!(error.code, "knowledge.database_missing");
assert!(!root.join(".marqdo/knowledge.sqlite").exists());
}
#[test]
fn no_result_query_returns_no_fabricated_hits() {
let root = sample_project();
let value = run(&root, query_args(&root, "完全无关的查询词xyzzy"));
assert!(value["hits"].as_array().unwrap().is_empty());
assert!(value["diagnostics"]
.as_array()
.unwrap()
.iter()
.any(|diagnostic| diagnostic["code"] == "knowledge.query_no_results"));
}
#[test]
fn semantic_without_index_is_an_explicit_error() {
let root = sample_project();
let mut args = query_args(&root, "牛顿");
args.semantic = true;
args.embedding = EmbeddingArgs {
embedding_url: Some("http://127.0.0.1:1/v1".into()),
embedding_model: Some("test".into()),
embedding_revision: Some("r1".into()),
allow_remote_embedding: false,
};
let error = query::run_query(&args, None).unwrap_err();
assert!(matches!(
error.code,
"knowledge.embedding_config_mismatch" | "knowledge.embedding_unavailable"
));
}
#[test]
fn check_sees_the_database_as_current_after_compile() {
let root = sample_project();
let args = CheckArgs {
root: root.clone(),
okf: false,
json: true,
};
let output = compiler::check(&args, None).unwrap();
assert_eq!(output.exit_code, 0, "{}", output.stderr);
let value: serde_json::Value = serde_json::from_str(&output.stdout).unwrap();
assert_eq!(value["payload"]["database"], "current");
}
#[test]
fn hits_expose_entry_navigation_and_concept_roles() {
let root = project(&[
("index.md", "# 知识入口\n\n导航到 [机制](mechanics.md)。\n"),
("mechanics.md", "# 机制\n\n## 说明\n\n机制正文。\n"),
("log.md", "# 变更日志\n\n## 记录\n\n历史。\n"),
(
"compute.mq.md",
"# @knowledge 计算\n\n## 说明\n\n可执行文稿。\n",
),
]);
compile(&root);
for (query, expected) in [
("知识入口", "index"),
("机制", "concept"),
("变更日志", "log"),
("计算", "document"),
] {
let value = run(&root, query_args(&root, query));
let hit = value["hits"]
.as_array()
.unwrap()
.iter()
.find(|hit| hit["role"] == expected)
.unwrap_or_else(|| panic!("missing role {expected} for query {query}: {value}"));
assert!(hit["role"].is_string());
}
}