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
This commit is contained in:
marqdo-knowledge committed 2026-11-26 02:26:37 +08:00
1 parent 514d9fbd4c
commit 87b9c132aa
20 files changed
+2882 -106

No files matched your search

+2
View File
@@ -1951,6 +1951,7 @@ fn module_to_facts(
let mut diagnostics = DiagnosticSet::new();
let blocks = markdown::searchable_blocks(&module.document, &units);
let front_matter = markdown::front_matter_fact(&module.document, &mut diagnostics, &path);
let okf = super::okf::analyze(&path, front_matter.as_ref(), &mut diagnostics);
let document_title = document_title(&units, &module.relative_path);
let stdlib_digest = artifact
@@ -1990,6 +1991,7 @@ fn module_to_facts(
resources,
blocks,
front_matter,
okf,
analysis: Some(analysis),
diagnostics: all,
})
+2
View File
@@ -50,6 +50,7 @@ pub fn parse_plain(file: &SourceFile) -> DocumentFacts {
}
let front_matter = front_matter_fact(&ast, &mut diagnostics, &file.rel_path);
let okf = super::okf::analyze(&file.rel_path, front_matter.as_ref(), &mut diagnostics);
let mut units = build_units(&ast, file);
fix_unit_spans(&mut units, source.len() as u64);
let anchors = build_anchors(&units);
@@ -73,6 +74,7 @@ pub fn parse_plain(file: &SourceFile) -> DocumentFacts {
resources: Vec::new(),
blocks,
front_matter,
okf,
analysis: None::<AnalysisFacts>,
diagnostics,
}
+4 -2
View File
@@ -521,6 +521,9 @@ pub struct DocumentFacts {
pub resources: Vec<ResourceFact>,
pub blocks: Vec<BlockFact>,
pub front_matter: Option<FrontMatterFact>,
/// OKF document-layer recognition. Metadata never changes program semantics.
#[serde(default)]
pub okf: okf::OkfInfo,
pub analysis: Option<AnalysisFacts>,
pub diagnostics: DiagnosticSet,
}
@@ -558,11 +561,10 @@ impl DocumentFacts {
}
}
#[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
2
}
#[cfg(test)]
+375 -14
View File
@@ -1,25 +1,386 @@
//! OKF v0.3 document-layer recognition and `check --okf` validation.
//!
//! OKF is an optional Markdown organisation convention, not a project type and
//! not an additional knowledge format. Recognition only reads front-matter
//! metadata and fixed file roles; it never executes an executor/attester and
//! never changes program semantics.
//! not an additional knowledge format. This module only reads front-matter
//! metadata and fixed file roles:
//!
//! Implemented by the OKF milestone. Until then `--okf` reports an explicit
//! unverified diagnostic instead of pretending to validate.
//! * a bundle is a directory of UTF-8 `.md` files;
//! * `index.md` and `log.md` are reserved navigation/history files at every
//! level and are never concepts, whatever front matter they carry;
//! * every other file is a concept and needs a non-empty YAML `type`;
//! * `title`, `description`, `tags` and `resource` are recognised when present;
//! * unknown types, unknown keys and unknown optional fields are preserved and
//! tolerated; no executor or attester is ever run.
//!
//! OKF metadata never changes program semantics. Compile always recognises the
//! metadata; OKF *link* semantics (bundle-root absolute paths) are only applied
//! when the user explicitly requests an OKF check.
use super::FrontMatterFact;
use crate::diagnostic::{code, Diagnostic, DiagnosticSet};
use crate::document::{DocumentFacts, SourceSnapshot};
use serde::{Deserialize, Serialize};
/// Validate the supported OKF surface for an explicitly requested bundle.
pub fn validate_okf(_snapshot: &SourceSnapshot, _facts: &[DocumentFacts]) -> DiagnosticSet {
/// OKF specification version this implementation targets.
pub const OKF_VERSION: &str = "0.3";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum OkfRole {
Native,
Concept,
Index,
Log,
}
impl OkfRole {
pub fn as_str(self) -> &'static str {
match self {
OkfRole::Native => "native",
OkfRole::Concept => "concept",
OkfRole::Index => "index",
OkfRole::Log => "log",
}
}
pub fn is_reserved(self) -> bool {
matches!(self, OkfRole::Index | OkfRole::Log)
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct OkfInfo {
pub role: OkfRole,
/// Concept id = bundle-relative path without `.md` (never fabricated for
/// non-concepts).
pub concept_id: Option<String>,
/// Free-form concept type (unregistered, never validated against a list).
pub concept_type: Option<String>,
pub title: Option<String>,
pub description: Option<String>,
pub tags: Vec<String>,
/// `resource` value as written; only recognised as a path when it has no URL
/// scheme. Root-absolute bundle paths are OKF-only semantics.
pub resource: Option<String>,
/// Full parsed front-matter object, unknown keys preserved.
pub metadata: serde_json::Value,
/// Root `okf_version` when present.
pub declared_version: Option<String>,
}
impl Default for OkfInfo {
fn default() -> Self {
Self {
role: OkfRole::Native,
concept_id: None,
concept_type: None,
title: None,
description: None,
tags: Vec::new(),
resource: None,
metadata: serde_json::Value::Null,
declared_version: None,
}
}
}
impl OkfInfo {
pub fn resource_is_relative_path(&self) -> Option<&str> {
let resource = self.resource.as_deref()?;
if resource.is_empty()
|| resource.contains("://")
|| resource.starts_with("//")
|| resource.split_once(':').is_some_and(|(scheme, _)| {
!scheme.is_empty()
&& scheme
.chars()
.next()
.is_some_and(|c| c.is_ascii_alphabetic())
&& scheme
.chars()
.all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'))
})
{
return None;
}
Some(resource)
}
/// Document role used by storage.
pub fn role(&self) -> OkfRole {
self.role
}
}
/// Recognise OKF metadata for one document.
pub fn analyze(
rel_path: &str,
front_matter: Option<&FrontMatterFact>,
diagnostics: &mut DiagnosticSet,
) -> OkfInfo {
let name = rel_path.rsplit('/').next().unwrap_or(rel_path);
let stem = name.strip_suffix(".md").unwrap_or(name);
let mut info = OkfInfo::default();
let value = front_matter.and_then(|front_matter| front_matter.value.clone());
if let Some(value) = &value {
if let Some(object) = value.as_object() {
if let Some(version) = object.get("okf_version").and_then(|value| value.as_str()) {
info.declared_version = Some(version.to_string());
}
info.concept_type = object
.get("type")
.and_then(|value| value.as_str())
.map(str::trim)
.filter(|value| !value.is_empty())
.map(str::to_string);
info.title = object
.get("title")
.and_then(|value| value.as_str())
.map(str::to_string);
info.description = object
.get("description")
.and_then(|value| value.as_str())
.map(str::to_string);
if let Some(tags) = object.get("tags").and_then(|value| value.as_array()) {
info.tags = tags
.iter()
.filter_map(|tag| tag.as_str())
.map(str::to_string)
.collect();
}
info.resource = object
.get("resource")
.and_then(|value| value.as_str())
.map(str::to_string);
info.metadata = value.clone();
}
}
if stem == "index" {
info.role = OkfRole::Index;
return info;
}
if stem == "log" {
info.role = OkfRole::Log;
return info;
}
if info.concept_type.is_some() {
info.role = OkfRole::Concept;
info.concept_id = Some(strip_markdown_suffix(rel_path));
if info.title.is_none() {
info.title = None;
}
} else if front_matter.is_some() {
// Front matter without a type is not a concept. The front matter layer
// already reported parse problems; do not invent one here.
info.role = OkfRole::Native;
let _ = diagnostics;
}
info
}
fn strip_markdown_suffix(rel_path: &str) -> String {
rel_path.strip_suffix(".md").unwrap_or(rel_path).to_string()
}
/// `check --okf`: validate the supported conformance surface for an explicitly
/// requested bundle. This is not an attestation verifier: unknown types and
/// unknown keys are accepted, broken links are reported as notices, and nothing
/// is executed.
pub fn validate_okf(snapshot: &SourceSnapshot, facts: &[DocumentFacts]) -> DiagnosticSet {
let mut diagnostics = DiagnosticSet::new();
diagnostics.push(
Diagnostic::warning(
code::OKF_UNVERIFIED,
"OKF v0.3 validation is not implemented in this build; no OKF claim is made",
)
.with_hint("see docs/STATUS.md for the current capability matrix"),
);
let by_path: std::collections::HashMap<&str, &DocumentFacts> = facts
.iter()
.map(|fact| (fact.rel_path.as_str(), fact))
.collect();
for file in &snapshot.files {
let Some(fact) = by_path.get(file.rel_path.as_str()) else {
continue;
};
let info = &fact.okf;
match info.role {
OkfRole::Index => {
if let Some(front_matter) = &fact.front_matter {
if let Some(value) = &front_matter.value {
if let Some(object) = value.as_object() {
let unknown: Vec<&String> = object
.keys()
.filter(|key| key.as_str() != "okf_version")
.collect();
if !unknown.is_empty() {
diagnostics.push(
Diagnostic::warning(
code::OKF_UNVERIFIED,
format!(
"reserved index file carries extra front-matter keys ({}) ; they are preserved but not interpreted",
unknown
.iter()
.map(|key| key.as_str())
.collect::<Vec<_>>()
.join(", ")
),
)
.with_path(&file.rel_path)
.with_span(front_matter.span),
);
}
}
}
}
}
OkfRole::Log => {
// Conformance does not require date headings; only report that
// no history semantics were interpreted.
}
OkfRole::Concept => {}
OkfRole::Native => {
// Conformance §11: every non-reserved Markdown file in a bundle
// needs parseable YAML front matter with a non-empty type.
match &fact.front_matter {
None => diagnostics.push(
Diagnostic::error(
code::OKF_INVALID,
format!(
"non-reserved file `{}` has no front matter; OKF concepts require a `type`",
file.rel_path
),
)
.with_path(&file.rel_path)
.with_hint("add YAML front matter with a non-empty `type`, or exclude the file"),
),
Some(front_matter) => {
if let Some(error) = &front_matter.error {
diagnostics.push(
Diagnostic::error(
code::OKF_INVALID,
format!("front matter is not valid OKF metadata: {error}"),
)
.with_path(&file.rel_path)
.with_span(front_matter.span),
);
} else {
diagnostics.push(
Diagnostic::error(
code::OKF_INVALID,
format!(
"non-reserved file `{}` has no non-empty `type`",
file.rel_path
),
)
.with_path(&file.rel_path)
.with_span(front_matter.span),
);
}
}
}
}
}
// Consumers must tolerate broken links; they are notices, not errors.
for reference in &fact.references {
if let Some(analysis) = &reference.analysis {
if matches!(
analysis.state,
crate::model::EdgeState::Missing | crate::model::EdgeState::Ambiguous
) {
diagnostics.push(
Diagnostic::warning(
code::OKF_UNVERIFIED,
format!("bundle link `{}` could not be verified", reference.url),
)
.with_path(&file.rel_path)
.with_span(reference.span),
);
}
}
}
}
diagnostics.sorted();
diagnostics
}
#[cfg(test)]
mod tests {
use super::*;
use crate::document::FrontMatterFact;
use crate::model::Span;
fn front(value: serde_json::Value) -> FrontMatterFact {
FrontMatterFact {
span: Span::new(0, 1),
literal: String::new(),
value: Some(value),
error: None,
}
}
#[test]
fn typed_document_is_a_concept_with_preserved_metadata() {
let mut diagnostics = DiagnosticSet::new();
let info = analyze(
"physics/mechanics.md",
Some(&front(serde_json::json!({
"type": "Theory",
"title": "经典力学",
"tags": ["physics", "mechanics"],
"custom": {"a": 1}
}))),
&mut diagnostics,
);
assert_eq!(info.role, OkfRole::Concept);
assert_eq!(info.concept_id.as_deref(), Some("physics/mechanics"));
assert_eq!(info.concept_type.as_deref(), Some("Theory"));
assert_eq!(info.tags, vec!["physics", "mechanics"]);
assert_eq!(info.metadata["custom"]["a"], 1);
}
#[test]
fn reserved_files_are_never_concepts() {
let mut diagnostics = DiagnosticSet::new();
let value = front(serde_json::json!({"type": "Index"}));
assert_eq!(
analyze("index.md", Some(&value), &mut diagnostics).role,
OkfRole::Index
);
assert_eq!(
analyze("a/b/log.md", Some(&value), &mut diagnostics).role,
OkfRole::Log
);
let info = analyze("a/b/index.md", Some(&value), &mut diagnostics);
assert!(info.concept_id.is_none());
}
#[test]
fn untyped_document_stays_native() {
let mut diagnostics = DiagnosticSet::new();
let info = analyze(
"notes.md",
Some(&front(serde_json::json!({"title": "notes"}))),
&mut diagnostics,
);
assert_eq!(info.role, OkfRole::Native);
assert!(info.concept_id.is_none());
assert!(analyze("plain.md", None, &mut diagnostics).role == OkfRole::Native);
}
#[test]
fn resource_paths_are_separated_from_urls() {
let mut diagnostics = DiagnosticSet::new();
let info = analyze(
"a.md",
Some(&front(serde_json::json!({
"type": "Dataset",
"resource": "../data/table.csv"
}))),
&mut diagnostics,
);
assert_eq!(info.resource_is_relative_path(), Some("../data/table.csv"));
let info = analyze(
"a.md",
Some(&front(serde_json::json!({
"type": "Dataset",
"resource": "https://example.com/x.csv"
}))),
&mut diagnostics,
);
assert_eq!(info.resource_is_relative_path(), None);
}
}