Files
marqdo-knowledge/tests/okf.rs
T
marqdo-knowledge 87b9c132aa feat(embedding): explicit OpenAI-compatible semantic channel
- 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
2026-11-26 02:26:37 +08:00

243 lines
8.1 KiB
Rust

//! OKF v0.3 recognition, metadata preservation and `check --okf` conformance.
use marqdo_knowledge::cli::{CheckArgs, CompileArgs, EmbeddingArgs, OutputFormat, QueryArgs};
use marqdo_knowledge::compiler;
use marqdo_knowledge::document::discovery::{discover, resolve_scope};
use marqdo_knowledge::document::markdown::parse_plain;
use marqdo_knowledge::graph;
use marqdo_knowledge::model::EdgeState;
use marqdo_knowledge::query;
use marqdo_knowledge::storage::read::ReadStore;
use std::collections::{HashMap, HashSet};
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(),
};
let output = compiler::compile(&args, None).unwrap();
assert_eq!(output.exit_code, 0, "{}", output.stderr);
}
fn check_okf(root: &Path) -> (i32, serde_json::Value) {
let args = CheckArgs {
root: root.to_path_buf(),
okf: true,
json: true,
};
let output = compiler::check(&args, None).unwrap();
(
output.exit_code,
serde_json::from_str(&output.stdout).unwrap(),
)
}
fn bundle() -> PathBuf {
project(&[
("index.md", "# Knowledge\n\n- [经典力学](physics/mechanics.md)\n"),
("log.md", "# Change log\n\n## 2026-11-25\n\n- initial concept\n"),
(
"physics/mechanics.md",
"---\ntype: Theory\ntitle: 经典力学\ntags: [physics, mechanics]\ndescription: 力学总览\ncustom_key: preserved\n---\n\n# 经典力学\n\n## 牛顿第二定律\n\n合外力等于质量与加速度的乘积。\n",
),
(
"datasets/table.md",
"---\ntype: Dataset\ntitle: 数据表\nresource: ../data/values.csv\n---\n\n# 数据表\n\n数据说明。\n",
),
("data/values.csv", "a,b\n1,2\n"),
])
}
#[test]
fn concept_metadata_and_roles_are_recognised() {
let root = bundle();
compile(&root);
let store = ReadStore::open(&root.join(".marqdo/knowledge.sqlite")).unwrap();
let mut roles: Vec<(String, String)> = store
.documents()
.unwrap()
.into_iter()
.map(|document| (document.path, document.role))
.collect();
roles.sort();
assert_eq!(
roles,
vec![
("datasets/table.md".to_string(), "concept".to_string()),
("index.md".to_string(), "index".to_string()),
("log.md".to_string(), "log".to_string()),
("physics/mechanics.md".to_string(), "concept".to_string()),
]
);
// Concept identity maps to the document node through an exact alias.
let aliases = store.aliases_for("physics/mechanics").unwrap();
assert_eq!(aliases.len(), 1);
let node = &aliases[0].1;
assert_eq!(node.kind, marqdo_knowledge::model::NodeKind::Document);
assert_eq!(node.metadata["okf"]["concept_type"], "Theory");
assert_eq!(node.metadata["okf"]["tags"][0], "physics");
assert_eq!(node.metadata["okf"]["metadata"]["custom_key"], "preserved");
// Reserved files never get concept ids.
assert!(store.aliases_for("index").unwrap().is_empty());
assert!(store.aliases_for("log").unwrap().is_empty());
}
#[test]
fn exact_query_resolves_a_concept_id() {
let root = bundle();
compile(&root);
let args = QueryArgs {
query: "physics/mechanics".into(),
root: root.clone(),
exact: true,
kind: None,
limit: None,
depth: None,
relation: Vec::new(),
reverse: false,
slice: None,
format: OutputFormat::Json,
snapshot: false,
semantic: false,
embedding: EmbeddingArgs::default(),
};
let output = query::run_query(&args, None).unwrap();
assert_eq!(output.exit_code, 0);
let value: serde_json::Value = serde_json::from_str(&output.stdout).unwrap();
assert_eq!(value["hits"][0]["title"], "经典力学");
assert_eq!(value["hits"][0]["kind"], "document");
}
#[test]
fn okf_resource_is_a_reference_edge_to_the_asset() {
let root = bundle();
compile(&root);
let store = ReadStore::open(&root.join(".marqdo/knowledge.sqlite")).unwrap();
let document = store
.node_by_key(graph::identity::document_key("datasets/table.md").as_str())
.unwrap()
.unwrap();
let edges = store
.edges_from(
&[document.id],
&[marqdo_knowledge::model::EdgeKind::References],
)
.unwrap();
let resource_edge = edges
.iter()
.find(|edge| edge.raw_target == "../data/values.csv")
.expect("resource reference edge");
assert_eq!(resource_edge.state, EdgeState::Resolved);
let target = store
.node_by_id(resource_edge.target_id.unwrap())
.unwrap()
.unwrap();
assert_eq!(target.kind, marqdo_knowledge::model::NodeKind::Resource);
assert_eq!(target.metadata["path"], "data/values.csv");
}
#[test]
fn valid_bundle_passes_okf_check() {
let root = bundle();
let (exit, value) = check_okf(&root);
assert_eq!(exit, 0, "{value:?}");
assert_eq!(value["payload"]["errors"], 0);
}
#[test]
fn non_reserved_file_without_type_fails_okf_check_only() {
let root = project(&[
("index.md", "# Knowledge\n"),
("concept.md", "---\ntype: Note\ntitle: ok\n---\n\n# ok\n"),
("loose.md", "# no front matter\n"),
]);
// Native compile still works: ordinary documents remain knowledge.
compile(&root);
let (exit, value) = check_okf(&root);
assert_eq!(exit, 1);
assert!(value["diagnostics"]
.as_array()
.unwrap()
.iter()
.any(|diagnostic| diagnostic["code"] == "knowledge.okf_invalid"));
}
#[test]
fn broken_links_are_tolerated_in_okf_mode_but_not_in_plain_check() {
let root = project(&[
("index.md", "# Knowledge\n"),
(
"concept.md",
"---\ntype: Note\n---\n\n# note\n\n[missing](missing-target.md)\n",
),
]);
let (exit, _) = check_okf(&root);
assert_eq!(exit, 0, "OKF conformance tolerates broken links");
let plain = compiler::check(
&CheckArgs {
root: root.clone(),
okf: false,
json: true,
},
None,
)
.unwrap();
assert_eq!(
plain.exit_code, 1,
"plain check fails on a definite broken link"
);
}
#[test]
fn root_absolute_okf_links_resolve_inside_the_bundle() {
let root = project(&[
("index.md", "# Knowledge\n"),
("a.md", "---\ntype: Note\n---\n\n# a\n\n[b](/b.md#b)\n"),
("b.md", "---\ntype: Note\n---\n\n# b\n\ncontent\n"),
]);
let scope = resolve_scope(&root, &[]).unwrap();
let snapshot = discover(&scope).unwrap();
let facts: Vec<_> = snapshot.files.iter().map(parse_plain).collect();
let mut sources: HashMap<&str, &str> = HashMap::new();
for file in &snapshot.files {
sources.insert(file.rel_path.as_str(), file.text.as_str());
}
let missing: HashSet<String> = HashSet::new();
let native = graph::build(facts.clone(), &sources, &snapshot.assets, &missing, false);
let native_edge = native
.edges
.iter()
.find(|edge| edge.raw_target == "/b.md#b")
.unwrap();
assert_eq!(native_edge.state, EdgeState::OutOfScope);
let okf = graph::build(facts, &sources, &snapshot.assets, &missing, true);
let okf_edge = okf
.edges
.iter()
.find(|edge| edge.raw_target == "/b.md#b")
.unwrap();
assert_eq!(okf_edge.state, EdgeState::Resolved);
assert!(okf_edge.target.is_some());
assert!(okf.diagnostics.iter().all(|diagnostic| !diagnostic
.message
.contains("escapes the allowed knowledge root")));
}