Implement the P1 slice of marqdo-knowledge#14 with the #12 contract: every query hit now carries the document-structure identity and source evidence it came from, without re-parsing and without a second knowledge body. - Index anchors from the public Analysis document facts next to each unit node, including module_id, unit_kind, mode, level and path; plain-Markdown documents keep null upstream identity instead of fabricating one. - Query hits add an additive `location` object (module_id, unit_id, unit_kind, anchors, path, level, mode, nature, exact span) and an `evidence` object (status current|stale, source_digest, snapshot_digest). `nature` is `unspecified` because the current public inputs do not declare authority; Knowledge never guesses it. - spec/knowledge.md documents §3.1.1 candidate location/evidence and §4.1 document-structure index semantics: entry vs navigation, units/anchors/spans, and the link != import != call separation (links never become execution edges). Schema stays version 1; fields are additive and optional. - tests/query.rs asserts location/evidence on a real compiled project. No new parser, no metadata syntax, no cross-repo dependency, no execution or network behavior change.
930 lines
34 KiB
Rust
930 lines
34 KiB
Rust
//! Read-only query surface: exact lookup, lexical/fuzzy/semantic candidates,
|
||
//! weighted fusion, bounded graph expansion and bounded Markdown slices.
|
||
//!
|
||
//! Query never compiles implicitly, never writes graph facts and never serves a
|
||
//! stale snapshot unless `--snapshot` is explicit. Default output is human
|
||
//! Markdown; `--format json` emits the single machine envelope.
|
||
|
||
pub mod fuzzy;
|
||
pub mod search;
|
||
pub mod semantic;
|
||
pub mod slice;
|
||
|
||
use crate::cli::Output;
|
||
use crate::cli::{OutputFormat, QueryArgs, SliceKind};
|
||
use crate::diagnostic::{code, Diagnostic, DiagnosticSet};
|
||
use crate::document::discovery;
|
||
use crate::error::{KnowledgeError, EXIT_OK};
|
||
use crate::graph::identity;
|
||
use crate::model::{EdgeKind, NodeKind, Span};
|
||
use crate::query::search::{ExactResolution, ExpandOptions, FinalHit};
|
||
use crate::storage::read::{ReadStore, StoredDocumentMeta};
|
||
use crate::storage::BuildMeta;
|
||
use std::collections::HashMap;
|
||
use std::path::Path;
|
||
|
||
const DEFAULT_LIMIT: usize = 10;
|
||
const DEFAULT_DEPTH: usize = 1;
|
||
const SNIPPET_BUDGET: usize = 700;
|
||
|
||
/// 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> {
|
||
let scope = discovery::resolve_scope(&args.root, &[])?;
|
||
let snapshot = discovery::discover(&scope)?;
|
||
let store = ReadStore::open(&scope.database_path())?;
|
||
let meta = store.build_meta()?;
|
||
// Reproduce the stored referenced-asset inputs so freshness compares the
|
||
// same input set that the build recorded.
|
||
let mut snapshot = snapshot;
|
||
populate_assets(&scope, &mut snapshot, &store)?;
|
||
let currentness = store.currentness(&snapshot)?;
|
||
let mut diagnostics = DiagnosticSet::new();
|
||
if !currentness.current {
|
||
if !args.snapshot {
|
||
return Err(KnowledgeError::environment(
|
||
code::DATABASE_STALE,
|
||
"knowledge database does not match the current sources",
|
||
)
|
||
.with_hint("run `marqdo knowledge compile` or pass --snapshot to read the last snapshot explicitly"));
|
||
}
|
||
diagnostics.push(
|
||
Diagnostic::warning(
|
||
code::SNAPSHOT_STALE,
|
||
format!(
|
||
"serving the stored snapshot; {} input(s) changed since it was built",
|
||
currentness.changed_inputs.len()
|
||
),
|
||
)
|
||
.with_hint("results describe the stored snapshot, not the current files"),
|
||
);
|
||
}
|
||
let mut engine = Engine {
|
||
store: &store,
|
||
meta: &meta,
|
||
documents: store
|
||
.documents()?
|
||
.into_iter()
|
||
.map(|document| (document.id, document))
|
||
.collect(),
|
||
sources: HashMap::new(),
|
||
diagnostics,
|
||
snapshot_digest: snapshot.snapshot_digest(),
|
||
current: currentness.current,
|
||
};
|
||
let result = if let Some(slice_kind) = args.slice {
|
||
engine.build_slice_result(args, slice_kind)?
|
||
} else if args.exact {
|
||
engine.exact_result(args)?
|
||
} else {
|
||
engine.hybrid_result(args)?
|
||
};
|
||
let output = match args.format {
|
||
OutputFormat::Json => {
|
||
let envelope = engine.envelope(args, &result)?;
|
||
let mut output =
|
||
Output::ok(serde_json::to_string_pretty(&envelope).unwrap_or_else(|_| "{}".into()));
|
||
output.stderr = crate::compiler::render_diagnostics(&engine.diagnostics);
|
||
output.exit_code = result.exit_code;
|
||
output
|
||
}
|
||
OutputFormat::Markdown => {
|
||
let mut output = Output::ok(result.markdown());
|
||
output.stderr = crate::compiler::render_diagnostics(&engine.diagnostics);
|
||
output.exit_code = result.exit_code;
|
||
output
|
||
}
|
||
};
|
||
Ok(output)
|
||
}
|
||
|
||
fn populate_assets(
|
||
scope: &crate::document::Scope,
|
||
snapshot: &mut crate::document::SourceSnapshot,
|
||
store: &ReadStore,
|
||
) -> Result<(), KnowledgeError> {
|
||
let mut facts = HashMap::new();
|
||
for document in store.documents()? {
|
||
if let Some(cached) = store.load_facts(&document.path)? {
|
||
facts.insert(document.path.clone(), cached.facts);
|
||
}
|
||
}
|
||
let (assets, _missing) = crate::compiler::collect_assets(scope, snapshot, &facts)?;
|
||
snapshot.assets = assets;
|
||
Ok(())
|
||
}
|
||
|
||
/// Query result before rendering.
|
||
struct QueryResult {
|
||
hits: Vec<Hit>,
|
||
slice: Option<SliceOutput>,
|
||
channels: Vec<String>,
|
||
truncated: bool,
|
||
exit_code: i32,
|
||
}
|
||
|
||
impl QueryResult {
|
||
fn empty(channels: Vec<String>) -> Self {
|
||
Self {
|
||
hits: Vec::new(),
|
||
slice: None,
|
||
channels,
|
||
truncated: false,
|
||
exit_code: EXIT_OK,
|
||
}
|
||
}
|
||
|
||
fn markdown(&self) -> String {
|
||
if let Some(slice) = &self.slice {
|
||
return slice.markdown();
|
||
}
|
||
let mut out = String::new();
|
||
out.push_str("# 知识查询结果\n\n");
|
||
if self.hits.is_empty() {
|
||
out.push_str("未找到匹配的知识候选。\n");
|
||
return out;
|
||
}
|
||
out.push_str(&format!(
|
||
"- 命中: {} 个(通道: {})\n- 截断: {}\n\n",
|
||
self.hits.len(),
|
||
self.channels.join(", "),
|
||
if self.truncated { "是" } else { "否" }
|
||
));
|
||
for (index, hit) in self.hits.iter().enumerate() {
|
||
out.push_str(&format!(
|
||
"## {}. {} ({})\n\n",
|
||
index + 1,
|
||
escape_markdown_text(&hit.title),
|
||
hit.kind.as_str()
|
||
));
|
||
if let Some(source) = &hit.source {
|
||
out.push_str(&format!(
|
||
"- 来源: `{}:{}`\n",
|
||
source.path,
|
||
source
|
||
.span
|
||
.map(|span| format!("{}..{}", span.start, span.end))
|
||
.unwrap_or_else(|| "-".into())
|
||
));
|
||
}
|
||
let matches: Vec<String> = hit
|
||
.matches
|
||
.iter()
|
||
.map(|reason| format!("{}/{}", reason.channel, reason.field))
|
||
.collect();
|
||
out.push_str(&format!("- 匹配: {}\n", matches.join(", ")));
|
||
out.push_str(&format!("- 分数: {:.6}\n", hit.score));
|
||
if let Some(callable) = &hit.callable {
|
||
if let Some(function_id) =
|
||
callable.get("function_id").and_then(|value| value.as_str())
|
||
{
|
||
out.push_str(&format!(
|
||
"- 可调用接口: `{}`(仅定位,不执行)\n",
|
||
function_id
|
||
));
|
||
}
|
||
}
|
||
if !hit.snippet.is_empty() {
|
||
out.push_str("\n片段原文:\n\n");
|
||
out.push_str(&fenced(&hit.snippet, "text"));
|
||
out.push('\n');
|
||
}
|
||
}
|
||
out
|
||
}
|
||
}
|
||
|
||
struct Hit {
|
||
id: String,
|
||
kind: NodeKind,
|
||
title: String,
|
||
source: Option<HitSource>,
|
||
snippet: String,
|
||
matches: Vec<search::MatchReason>,
|
||
score: f64,
|
||
callable: Option<serde_json::Value>,
|
||
location: Option<serde_json::Value>,
|
||
evidence: serde_json::Value,
|
||
related: Vec<serde_json::Value>,
|
||
}
|
||
|
||
struct HitSource {
|
||
path: String,
|
||
digest: String,
|
||
span: Option<Span>,
|
||
}
|
||
|
||
struct SliceOutput {
|
||
json: serde_json::Value,
|
||
markdown_text: String,
|
||
}
|
||
|
||
impl SliceOutput {
|
||
fn markdown(&self) -> String {
|
||
self.markdown_text.clone()
|
||
}
|
||
}
|
||
|
||
struct Engine<'a> {
|
||
store: &'a ReadStore,
|
||
meta: &'a BuildMeta,
|
||
documents: HashMap<i64, StoredDocumentMeta>,
|
||
sources: HashMap<i64, Vec<u8>>,
|
||
diagnostics: DiagnosticSet,
|
||
snapshot_digest: String,
|
||
current: bool,
|
||
}
|
||
|
||
impl<'a> Engine<'a> {
|
||
fn effective_limit(args: &QueryArgs) -> usize {
|
||
args.limit.unwrap_or(DEFAULT_LIMIT).clamp(1, 100)
|
||
}
|
||
|
||
fn effective_depth(args: &QueryArgs) -> usize {
|
||
args.depth.unwrap_or(DEFAULT_DEPTH).min(8)
|
||
}
|
||
|
||
fn relations(args: &QueryArgs) -> Vec<EdgeKind> {
|
||
args.relation
|
||
.iter()
|
||
.filter_map(|relation| relation.parse::<EdgeKind>().ok())
|
||
.collect()
|
||
}
|
||
|
||
fn document_meta(&self, doc_id: i64) -> Option<&StoredDocumentMeta> {
|
||
self.documents.get(&doc_id)
|
||
}
|
||
|
||
fn source(&mut self, doc_id: i64) -> Result<Option<&[u8]>, KnowledgeError> {
|
||
if !self.sources.contains_key(&doc_id) {
|
||
let source = self.store.document_source(doc_id)?;
|
||
self.sources.insert(doc_id, source);
|
||
}
|
||
Ok(self.sources.get(&doc_id).map(Vec::as_slice))
|
||
}
|
||
|
||
fn exact_result(&mut self, args: &QueryArgs) -> Result<QueryResult, KnowledgeError> {
|
||
let resolution = search::exact(self.store, &args.query)?;
|
||
let mut result = QueryResult::empty(vec!["exact".into()]);
|
||
match &resolution {
|
||
ExactResolution::Address(node) => {
|
||
if let Some(kind) = parse_kind(args.kind.as_deref()) {
|
||
if node.kind != kind {
|
||
return Ok(result);
|
||
}
|
||
}
|
||
let hit = self.assemble_hit(
|
||
&FinalHit {
|
||
node: node.clone(),
|
||
score: 1.0,
|
||
direct: true,
|
||
matches: vec![search::MatchReason {
|
||
channel: "exact".into(),
|
||
field: "address".into(),
|
||
}],
|
||
best_unit: None,
|
||
related: Vec::new(),
|
||
depth: 0,
|
||
},
|
||
&args.query,
|
||
)?;
|
||
result.hits = vec![hit];
|
||
}
|
||
ExactResolution::Candidates(nodes) => {
|
||
let kind = parse_kind(args.kind.as_deref());
|
||
for node in nodes {
|
||
if kind.is_some_and(|kind| node.kind != kind) {
|
||
continue;
|
||
}
|
||
let hit = self.assemble_hit(
|
||
&FinalHit {
|
||
node: node.clone(),
|
||
score: 1.0,
|
||
direct: true,
|
||
matches: vec![search::MatchReason {
|
||
channel: "exact".into(),
|
||
field: "title".into(),
|
||
}],
|
||
best_unit: None,
|
||
related: Vec::new(),
|
||
depth: 0,
|
||
},
|
||
&args.query,
|
||
)?;
|
||
result.hits.push(hit);
|
||
}
|
||
self.diagnostics.push(
|
||
Diagnostic::warning(
|
||
code::QUERY_AMBIGUOUS,
|
||
"query matches several exact names; candidates are returned without choosing one",
|
||
)
|
||
.with_hint("use a canonical id to select one node"),
|
||
);
|
||
}
|
||
ExactResolution::None => {
|
||
self.diagnostics.push(Diagnostic::warning(
|
||
code::QUERY_NO_RESULTS,
|
||
"no canonical id, alias or unique exact name matches the query",
|
||
));
|
||
}
|
||
}
|
||
if result.hits.is_empty() && matches!(resolution, ExactResolution::None) {
|
||
result.exit_code = EXIT_OK;
|
||
}
|
||
Ok(result)
|
||
}
|
||
|
||
fn hybrid_result(&mut self, args: &QueryArgs) -> Result<QueryResult, KnowledgeError> {
|
||
if self.meta.embedding.is_some() && args.semantic {
|
||
self.check_embedding_config(args)?;
|
||
}
|
||
let channels_requested = vec![
|
||
"exact".to_string(),
|
||
"lexical".to_string(),
|
||
"fuzzy".to_string(),
|
||
"graph".to_string(),
|
||
];
|
||
let mut channels: Vec<search::ChannelResult> = Vec::new();
|
||
let exact_resolution = search::exact(self.store, &args.query)?;
|
||
let exact_channel = search::exact_channel(&exact_resolution);
|
||
if !exact_channel.ranked.is_empty() {
|
||
channels.push(exact_channel);
|
||
}
|
||
channels.push(search::lexical(self.store, &args.query, 200)?);
|
||
let fuzzy = search::fuzzy(self.store, &args.query, 200)?;
|
||
if !fuzzy.ranked.is_empty() {
|
||
channels.push(fuzzy);
|
||
}
|
||
if args.semantic {
|
||
let embedding = self.meta.embedding.clone().ok_or_else(|| {
|
||
KnowledgeError::environment(
|
||
code::EMBEDDING_CONFIG_MISMATCH,
|
||
"database has no semantic index; compile with embedding options first",
|
||
)
|
||
})?;
|
||
let stored_endpoint = embedding
|
||
.get("endpoint")
|
||
.and_then(|value| value.as_str())
|
||
.unwrap_or_default()
|
||
.to_string();
|
||
let stored_model = embedding
|
||
.get("model")
|
||
.and_then(|value| value.as_str())
|
||
.unwrap_or_default()
|
||
.to_string();
|
||
let stored_revision = embedding
|
||
.get("revision")
|
||
.and_then(|value| value.as_str())
|
||
.unwrap_or_default()
|
||
.to_string();
|
||
let dimension = embedding
|
||
.get("dimension")
|
||
.and_then(|value| value.as_u64())
|
||
.unwrap_or(0) as usize;
|
||
let model_digest = embedding
|
||
.get("model_digest")
|
||
.and_then(|value| value.as_str())
|
||
.unwrap_or_default()
|
||
.to_string();
|
||
let url = args.embedding.embedding_url.clone().ok_or_else(|| {
|
||
KnowledgeError::environment(
|
||
code::EMBEDDING_UNAVAILABLE,
|
||
"semantic search requires explicit embedding options",
|
||
)
|
||
})?;
|
||
let model = args.embedding.embedding_model.clone().unwrap_or_default();
|
||
let revision = args
|
||
.embedding
|
||
.embedding_revision
|
||
.clone()
|
||
.unwrap_or_default();
|
||
let config = crate::embedding::EmbeddingConfig::new(
|
||
&url,
|
||
&model,
|
||
&revision,
|
||
args.embedding.allow_remote_embedding,
|
||
)?;
|
||
let client = crate::embedding::EmbeddingClient::new(&config)?;
|
||
if client.endpoint() != stored_endpoint
|
||
|| model != stored_model
|
||
|| revision != stored_revision
|
||
{
|
||
return Err(KnowledgeError::environment(
|
||
code::EMBEDDING_CONFIG_MISMATCH,
|
||
"query embedding configuration does not match the compiled semantic index",
|
||
)
|
||
.with_hint("recompile with the new configuration or pass the original options"));
|
||
}
|
||
let (vectors, returned_dimension) = client.embed(std::slice::from_ref(&args.query))?;
|
||
if returned_dimension != dimension {
|
||
return Err(KnowledgeError::environment(
|
||
code::EMBEDDING_CONFIG_MISMATCH,
|
||
"query embedding dimension does not match the compiled index",
|
||
));
|
||
}
|
||
channels.push(semantic::channel(
|
||
self.store,
|
||
&vectors[0],
|
||
&model_digest,
|
||
dimension,
|
||
200,
|
||
)?);
|
||
}
|
||
let truncated_channels = channels.iter().any(|channel| channel.truncated);
|
||
let fused = search::fuse(&channels);
|
||
let seeds: Vec<(i64, f64)> = fused
|
||
.iter()
|
||
.take(search::GRAPH_SEED_LIMIT)
|
||
.map(|hit| (hit.node_id, hit.score))
|
||
.collect();
|
||
let expansion = search::expand(
|
||
self.store,
|
||
&seeds,
|
||
&ExpandOptions {
|
||
depth: Self::effective_depth(args),
|
||
relations: Self::relations(args),
|
||
reverse: args.reverse,
|
||
},
|
||
)?;
|
||
let kind = parse_kind(args.kind.as_deref());
|
||
let final_hits = search::finalize(
|
||
self.store,
|
||
fused,
|
||
&expansion,
|
||
kind,
|
||
Self::effective_limit(args),
|
||
)?;
|
||
let mut channels_present: Vec<String> = channels
|
||
.iter()
|
||
.filter(|channel| !channel.ranked.is_empty())
|
||
.map(|channel| channel.channel.to_string())
|
||
.collect();
|
||
if !expansion.hits.is_empty() {
|
||
channels_present.push("graph".into());
|
||
}
|
||
if channels_present.is_empty() {
|
||
channels_present = channels_requested;
|
||
}
|
||
let mut result = QueryResult::empty(channels_present);
|
||
result.truncated = truncated_channels || expansion.truncated;
|
||
for final_hit in &final_hits {
|
||
result.hits.push(self.assemble_hit(final_hit, &args.query)?);
|
||
}
|
||
if result.hits.is_empty() {
|
||
self.diagnostics.push(Diagnostic::warning(
|
||
code::QUERY_NO_RESULTS,
|
||
"no reliable knowledge candidate matched the query",
|
||
));
|
||
}
|
||
Ok(result)
|
||
}
|
||
|
||
fn check_embedding_config(&mut self, args: &QueryArgs) -> Result<(), KnowledgeError> {
|
||
let embedding = self
|
||
.meta
|
||
.embedding
|
||
.as_ref()
|
||
.and_then(|value| value.as_object())
|
||
.ok_or_else(|| {
|
||
KnowledgeError::environment(
|
||
code::EMBEDDING_CONFIG_MISMATCH,
|
||
"database has no semantic index metadata",
|
||
)
|
||
})?;
|
||
let stored_url = embedding.get("endpoint").and_then(|value| value.as_str());
|
||
let stored_model = embedding.get("model").and_then(|value| value.as_str());
|
||
let stored_revision = embedding.get("revision").and_then(|value| value.as_str());
|
||
if args.embedding.embedding_url.as_deref() != stored_url
|
||
|| args.embedding.embedding_model.as_deref() != stored_model
|
||
|| args.embedding.embedding_revision.as_deref() != stored_revision
|
||
{
|
||
return Err(KnowledgeError::environment(
|
||
code::EMBEDDING_CONFIG_MISMATCH,
|
||
"query embedding configuration does not match the compiled semantic index",
|
||
)
|
||
.with_hint("recompile with the new configuration or pass the original options"));
|
||
}
|
||
Ok(())
|
||
}
|
||
|
||
fn build_slice_result(
|
||
&mut self,
|
||
args: &QueryArgs,
|
||
kind: SliceKind,
|
||
) -> Result<QueryResult, KnowledgeError> {
|
||
let seed = self.resolve_slice_seed(args)?;
|
||
let mode = match kind {
|
||
SliceKind::Document => slice::SliceMode::Document,
|
||
SliceKind::Execution => slice::SliceMode::Execution,
|
||
SliceKind::Hybrid => slice::SliceMode::Hybrid,
|
||
};
|
||
let policy = slice::SlicePolicy {
|
||
mode,
|
||
depth: args.depth.unwrap_or(DEFAULT_DEPTH).min(8),
|
||
reverse: args.reverse,
|
||
byte_budget: slice::DEFAULT_SLICE_BUDGET,
|
||
};
|
||
let documents = self.documents.clone();
|
||
let planned = slice::plan(self.store, &seed, &documents, &policy)?;
|
||
let built = slice::materialize(planned, &documents, &policy, |doc_id| {
|
||
self.source(doc_id)
|
||
.map(|source| source.map(|slice| slice.to_vec()))
|
||
})?;
|
||
if built.truncated {
|
||
self.diagnostics.push(Diagnostic::warning(
|
||
code::BUDGET,
|
||
format!(
|
||
"slice stopped at the {} byte budget; returned {} bytes",
|
||
built.byte_budget, built.returned_bytes
|
||
),
|
||
));
|
||
}
|
||
let json = slice_json(&built);
|
||
let markdown_text = render_slice_markdown(&built);
|
||
Ok(QueryResult {
|
||
hits: Vec::new(),
|
||
slice: Some(SliceOutput {
|
||
json,
|
||
markdown_text,
|
||
}),
|
||
channels: vec!["exact".into()],
|
||
truncated: built.truncated,
|
||
exit_code: EXIT_OK,
|
||
})
|
||
}
|
||
|
||
fn resolve_slice_seed(
|
||
&mut self,
|
||
args: &QueryArgs,
|
||
) -> Result<crate::storage::read::StoredNode, KnowledgeError> {
|
||
match search::exact(self.store, &args.query)? {
|
||
ExactResolution::Address(node) => Ok(node),
|
||
ExactResolution::Candidates(nodes) => {
|
||
let hints: Vec<String> = nodes
|
||
.iter()
|
||
.take(8)
|
||
.map(|node| format!("{} ({})", node.key, node.title))
|
||
.collect();
|
||
Err(KnowledgeError::input(
|
||
code::SLICE_SEED_AMBIGUOUS,
|
||
"the slice seed is not unique; no node was chosen",
|
||
)
|
||
.with_hint(format!("candidate ids: {}", hints.join(", "))))
|
||
}
|
||
ExactResolution::None => {
|
||
let fuzzy = search::fuzzy(self.store, &args.query, 5)?;
|
||
let hints: Vec<String> = fuzzy
|
||
.ranked
|
||
.iter()
|
||
.filter_map(|ranked| self.store.node_by_id(ranked.node_id).ok().flatten())
|
||
.map(|node| format!("{} ({})", node.key, node.title))
|
||
.collect();
|
||
let mut error = KnowledgeError::input(
|
||
code::SLICE_SEED_MISSING,
|
||
"the slice seed does not resolve to a unique node",
|
||
);
|
||
if !hints.is_empty() {
|
||
error = error.with_hint(format!("candidates: {}", hints.join(", ")));
|
||
}
|
||
Err(error)
|
||
}
|
||
}
|
||
}
|
||
|
||
fn assemble_hit(&mut self, final_hit: &FinalHit, query: &str) -> Result<Hit, KnowledgeError> {
|
||
let node = &final_hit.node;
|
||
let source_meta = node.doc_id.and_then(|id| self.document_meta(id));
|
||
let source_path = source_meta.map(|meta| meta.path.clone());
|
||
let source_digest = source_meta.map(|meta| meta.source_digest.clone());
|
||
let unit_span = match final_hit.best_unit {
|
||
Some(unit_id) => self.store.search_unit(unit_id)?.map(|unit| unit.span),
|
||
None => None,
|
||
};
|
||
let snippet_span = unit_span.or(node.span);
|
||
let snippet = match (node.doc_id, snippet_span) {
|
||
(Some(doc_id), Some(span)) => match self.source(doc_id)? {
|
||
Some(source) => snippet_from(source, span, query),
|
||
None => String::new(),
|
||
},
|
||
_ => String::new(),
|
||
};
|
||
let callable = if node
|
||
.metadata
|
||
.get("callable")
|
||
.and_then(|value| value.as_bool())
|
||
== Some(true)
|
||
{
|
||
Some(serde_json::json!({
|
||
"function_id": node.metadata.get("function_id"),
|
||
"signature": node.metadata.get("signature"),
|
||
"effects": node.metadata.get("effects"),
|
||
"context": node.metadata.get("analysis"),
|
||
}))
|
||
} else {
|
||
None
|
||
};
|
||
let mut related = Vec::new();
|
||
for relation in &final_hit.related {
|
||
if let Some(related_node) = self.store.node_by_id(relation.node_id)? {
|
||
related.push(serde_json::json!({
|
||
"id": related_node.key,
|
||
"kind": related_node.kind.as_str(),
|
||
"title": related_node.title,
|
||
"relation": relation.relation,
|
||
"direction": relation.direction,
|
||
}));
|
||
}
|
||
}
|
||
// Stable candidate location: the document-structure identity a
|
||
// consumer can address without re-parsing (unit id, anchors, path,
|
||
// mode, exact source span). `nature` is `unspecified` because the
|
||
// current public inputs (Markdown structure / OKF) do not declare
|
||
// normative authority; Knowledge never guesses it (issue #14).
|
||
let location = node.metadata.get("path").map(|path| {
|
||
serde_json::json!({
|
||
"module_id": node.metadata.get("module_id"),
|
||
"unit_id": node.metadata.get("unit_id"),
|
||
"unit_kind": node.metadata.get("unit_kind"),
|
||
"anchors": node.metadata.get("anchors").cloned().unwrap_or_else(|| serde_json::json!([])),
|
||
"path": path,
|
||
"level": node.metadata.get("level"),
|
||
"mode": node.metadata.get("mode"),
|
||
"nature": node.metadata.get("nature"),
|
||
"span": node.span.map(|span| serde_json::json!({
|
||
"start": span.start,
|
||
"end": span.end,
|
||
})),
|
||
})
|
||
});
|
||
let evidence = serde_json::json!({
|
||
"status": if self.current { "current" } else { "stale" },
|
||
"source_digest": source_digest,
|
||
"snapshot_digest": self.snapshot_digest,
|
||
});
|
||
Ok(Hit {
|
||
id: node.key.clone(),
|
||
kind: node.kind,
|
||
title: node.title.clone(),
|
||
source: match (source_path, source_digest) {
|
||
(Some(path), Some(digest)) => Some(HitSource {
|
||
path,
|
||
digest,
|
||
span: node.span,
|
||
}),
|
||
_ => None,
|
||
},
|
||
snippet,
|
||
matches: final_hit.matches.clone(),
|
||
score: (final_hit.score * 1_000_000.0).round() / 1_000_000.0,
|
||
callable,
|
||
location,
|
||
evidence,
|
||
related,
|
||
})
|
||
}
|
||
|
||
fn envelope(
|
||
&mut self,
|
||
args: &QueryArgs,
|
||
result: &QueryResult,
|
||
) -> Result<serde_json::Value, KnowledgeError> {
|
||
let hits: Vec<serde_json::Value> = result
|
||
.hits
|
||
.iter()
|
||
.map(|hit| {
|
||
let mut value = serde_json::json!({
|
||
"id": hit.id,
|
||
"kind": hit.kind.as_str(),
|
||
"title": hit.title,
|
||
"matches": hit.matches.iter().map(|reason| serde_json::json!({
|
||
"channel": reason.channel,
|
||
"field": reason.field,
|
||
})).collect::<Vec<_>>(),
|
||
"score": hit.score,
|
||
"related": hit.related,
|
||
});
|
||
let object = value.as_object_mut().expect("object");
|
||
if let Some(source) = &hit.source {
|
||
object.insert(
|
||
"source".into(),
|
||
serde_json::json!({
|
||
"path": source.path,
|
||
"digest": source.digest,
|
||
"span": source.span.map(|span| serde_json::json!({
|
||
"start": span.start,
|
||
"end": span.end,
|
||
})),
|
||
}),
|
||
);
|
||
}
|
||
object.insert(
|
||
"snippet".into(),
|
||
serde_json::Value::String(hit.snippet.clone()),
|
||
);
|
||
if let Some(callable) = &hit.callable {
|
||
object.insert("callable".into(), callable.clone());
|
||
}
|
||
if let Some(location) = &hit.location {
|
||
object.insert("location".into(), location.clone());
|
||
}
|
||
object.insert("evidence".into(), hit.evidence.clone());
|
||
value
|
||
})
|
||
.collect();
|
||
let mut payload = serde_json::json!({
|
||
"exact": args.exact,
|
||
"limit": Self::effective_limit(args),
|
||
"depth": Self::effective_depth(args),
|
||
"snapshot": args.snapshot,
|
||
});
|
||
if let Some(slice) = &result.slice {
|
||
payload
|
||
.as_object_mut()
|
||
.expect("object")
|
||
.insert("slice".into(), slice.json.clone());
|
||
}
|
||
Ok(serde_json::json!({
|
||
"schema": "marqdo.knowledge.result",
|
||
"schema_version": 1,
|
||
"command": "query",
|
||
"success": true,
|
||
"tool_version": crate::compiler::tool_version(),
|
||
"snapshot_digest": self.snapshot_digest,
|
||
"current": self.current,
|
||
"query": args.query,
|
||
"channels": result.channels,
|
||
"truncated": result.truncated,
|
||
"hits": hits,
|
||
"diagnostics": self.diagnostics.as_slice(),
|
||
"payload": payload,
|
||
}))
|
||
}
|
||
}
|
||
|
||
fn parse_kind(value: Option<&str>) -> Option<NodeKind> {
|
||
value.and_then(|value| value.parse::<NodeKind>().ok())
|
||
}
|
||
|
||
fn snippet_from(source: &[u8], span: Span, query: &str) -> String {
|
||
let Some(text) = span.slice(source) else {
|
||
return String::new();
|
||
};
|
||
if text.len() <= SNIPPET_BUDGET {
|
||
return text.to_string();
|
||
}
|
||
// Choose a window around the first occurrence of the raw query when the
|
||
// occurrence is inside this span; otherwise take the leading window. The
|
||
// result is always an exact substring of the original source.
|
||
let offset = text
|
||
.find(query)
|
||
.map(|position| {
|
||
let half = SNIPPET_BUDGET / 2;
|
||
let start = position.saturating_sub(half);
|
||
let mut start = start.min(text.len().saturating_sub(SNIPPET_BUDGET));
|
||
while start > 0 && !text.is_char_boundary(start) {
|
||
start -= 1;
|
||
}
|
||
start
|
||
})
|
||
.unwrap_or(0);
|
||
let mut end = (offset + SNIPPET_BUDGET).min(text.len());
|
||
while end > offset && !text.is_char_boundary(end) {
|
||
end -= 1;
|
||
}
|
||
text[offset..end].to_string()
|
||
}
|
||
|
||
fn fenced(text: &str, language: &str) -> String {
|
||
let mut fence = "```".to_string();
|
||
while text.contains(&fence) {
|
||
fence.push('`');
|
||
}
|
||
format!("{fence}{language}\n{text}\n{fence}")
|
||
}
|
||
|
||
fn escape_markdown_text(text: &str) -> String {
|
||
text.replace('\n', " ").replace('`', "'")
|
||
}
|
||
|
||
fn slice_json(built: &slice::Slice) -> serde_json::Value {
|
||
let pieces: Vec<serde_json::Value> = built
|
||
.pieces
|
||
.iter()
|
||
.map(|piece| {
|
||
let mut value = serde_json::json!({
|
||
"id": piece.node.key,
|
||
"kind": piece.node.kind.as_str(),
|
||
"title": piece.node.title,
|
||
"relation": piece.relation,
|
||
"direction": piece.direction,
|
||
"text": piece.text,
|
||
});
|
||
let object = value.as_object_mut().expect("object");
|
||
if let Some(path) = &piece.doc_path {
|
||
object.insert(
|
||
"source".into(),
|
||
serde_json::json!({
|
||
"path": path,
|
||
"span": piece.span.map(|span| serde_json::json!({
|
||
"start": span.start,
|
||
"end": span.end,
|
||
})),
|
||
}),
|
||
);
|
||
}
|
||
if let Some(gap) = &piece.gap {
|
||
object.insert("gap".into(), serde_json::Value::String(gap.clone()));
|
||
}
|
||
value
|
||
})
|
||
.collect();
|
||
serde_json::json!({
|
||
"kind": built.mode.as_str(),
|
||
"seed": {
|
||
"id": built.seed.key,
|
||
"kind": built.seed.kind.as_str(),
|
||
"title": built.seed.title,
|
||
},
|
||
"complete": built.complete,
|
||
"truncated": built.truncated,
|
||
"byte_budget": built.byte_budget,
|
||
"returned_bytes": built.returned_bytes,
|
||
"pieces": pieces,
|
||
})
|
||
}
|
||
|
||
fn render_slice_markdown(built: &slice::Slice) -> String {
|
||
let mut out = String::new();
|
||
out.push_str(&format!("# 阅读切片 ({})\n\n", built.mode.as_str()));
|
||
out.push_str(&format!(
|
||
"- 种子: `{}` ({})\n- 预算: {}/{} 字节\n- 完整: {}\n- 说明: 阅读切片,保留原文与来源地址,不是可执行程序。\n\n",
|
||
escape_markdown_text(&built.seed.title),
|
||
built.seed.kind.as_str(),
|
||
built.returned_bytes,
|
||
built.byte_budget,
|
||
if built.complete { "是" } else { "否(受预算截断)" }
|
||
));
|
||
for piece in &built.pieces {
|
||
out.push_str(&format!(
|
||
"## {}\n\n",
|
||
escape_markdown_text(&piece.node.title)
|
||
));
|
||
if let (Some(path), Some(span)) = (&piece.doc_path, piece.span) {
|
||
out.push_str(&format!(
|
||
"来源: `{}:{}..{}`\n\n",
|
||
path, span.start, span.end
|
||
));
|
||
}
|
||
out.push_str(&format!("关系: {}/{}\n\n", piece.relation, piece.direction));
|
||
if let Some(gap) = &piece.gap {
|
||
out.push_str(&format!("缺口: {gap}\n\n"));
|
||
} else {
|
||
out.push_str(&piece.text);
|
||
out.push_str("\n\n");
|
||
}
|
||
out.push_str("---\n\n");
|
||
}
|
||
out
|
||
}
|
||
|
||
/// Canonical key helper for tests.
|
||
pub fn canonical_document_key(path: &str) -> String {
|
||
identity::document_key(path).into_string()
|
||
}
|
||
|
||
#[cfg(test)]
|
||
mod tests {
|
||
use super::*;
|
||
|
||
#[test]
|
||
fn snippet_is_an_exact_source_substring() {
|
||
let source = "前言".repeat(200) + "目标片段" + &"尾".repeat(200);
|
||
let bytes = source.as_bytes();
|
||
let span = Span::new(0, bytes.len() as u64);
|
||
let snippet = snippet_from(bytes, span, "目标片段");
|
||
assert!(snippet.contains("目标片段"));
|
||
assert!(source.contains(&snippet));
|
||
assert!(snippet.len() <= SNIPPET_BUDGET + 8);
|
||
}
|
||
|
||
#[test]
|
||
fn fences_grow_when_the_text_contains_backticks() {
|
||
let text = "```rust\ncode\n```";
|
||
let fenced = fenced(text, "text");
|
||
assert!(fenced.starts_with("````text"));
|
||
}
|
||
|
||
#[test]
|
||
fn canonical_key_helper_is_opaque() {
|
||
let key = canonical_document_key("dir/文档.md");
|
||
assert!(!key.contains('#'));
|
||
assert!(!key.contains(' '));
|
||
}
|
||
|
||
#[test]
|
||
fn diagnostics_set_reports_stale_snapshot() {
|
||
let diagnostic = Diagnostic::warning(code::SNAPSHOT_STALE, "stale");
|
||
assert_eq!(diagnostic.code, "knowledge.snapshot_stale");
|
||
}
|
||
}
|