diff --git a/src/diagnostic.rs b/src/diagnostic.rs index 42787ec..1a2f4d8 100644 --- a/src/diagnostic.rs +++ b/src/diagnostic.rs @@ -60,6 +60,7 @@ pub mod code { 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 QUERY_AMBIGUOUS: &str = "knowledge.query_ambiguous"; 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"; diff --git a/src/query.rs b/src/query.rs deleted file mode 100644 index 7dd9731..0000000 --- a/src/query.rs +++ /dev/null @@ -1,16 +0,0 @@ -//! 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 { - Err(KnowledgeError::not_implemented("query")) -} diff --git a/src/query/fuzzy.rs b/src/query/fuzzy.rs new file mode 100644 index 0000000..58dfd74 --- /dev/null +++ b/src/query/fuzzy.rs @@ -0,0 +1,129 @@ +//! Fuzzy candidate scoring. +//! +//! The inverted gram index decides which candidates are *recalled*; this module +//! scores only those bounded candidates with normalised edit distance. It never +//! scans the whole corpus and never changes node identity or binding. + +use crate::storage::read::StoredNode; +use crate::text; + +/// One scored fuzzy candidate. +#[derive(Debug, Clone)] +pub struct ScoredCandidate { + pub node: StoredNode, + pub score: f64, + /// Best matching candidate text (for the match reason). + pub matched_text: String, + pub overlap: i64, + pub query_grams: usize, +} + +/// Score a recalled node against the query. +pub fn score_candidate( + node: &StoredNode, + query: &str, + overlap: i64, + query_grams: usize, +) -> Option { + let normalized_query = text::normalize(query); + if normalized_query.is_empty() { + return None; + } + let mut best_similarity = text::best_window_similarity(&normalized_query, &node.title); + let mut matched_text = node.title.clone(); + if let Some(local) = node + .metadata + .get("local_name") + .and_then(|value| value.as_str()) + { + let similarity = text::similarity(&normalized_query, local); + if similarity > best_similarity { + best_similarity = similarity; + matched_text = local.to_string(); + } + } + if let Some(symbol) = &node.symbol_norm { + let similarity = text::similarity(&normalized_query, symbol); + if similarity > best_similarity { + best_similarity = similarity; + matched_text = symbol.clone(); + } + } + if let Some(path) = node.metadata.get("path").and_then(|path| path.as_array()) { + let joined = path + .iter() + .filter_map(|segment| segment.as_str()) + .collect::>() + .join(" "); + let similarity = text::similarity(&normalized_query, &joined); + if similarity > best_similarity { + best_similarity = similarity; + matched_text = joined; + } + } + let overlap_ratio = if query_grams == 0 { + 0.0 + } else { + (overlap as f64 / query_grams as f64).min(1.0) + }; + // Recall signal (shared grams) plus precision signal (bounded edit + // distance). Both are ranking signals, never identity. A body-only shared + // gram must still be recallable (typo-in-body case), so overlap dominates. + // Shared grams alone are not enough when the title is unrelated; a strong + // near-spelling always qualifies, and a high shared-gram ratio qualifies + // even for a body-only typo where the title differs. + if best_similarity < 0.2 && overlap_ratio < 0.6 { + return None; + } + let score = 0.7 * overlap_ratio + 0.3 * best_similarity; + if score < 0.15 { + return None; + } + Some(ScoredCandidate { + node: node.clone(), + score, + matched_text, + overlap, + query_grams, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::model::NodeKind; + + fn node(title: &str, local: Option<&str>) -> StoredNode { + StoredNode { + id: 1, + key: "k".into(), + kind: NodeKind::Function, + doc_id: Some(1), + parent_id: None, + span: None, + title: title.into(), + title_norm: text::normalize(title), + symbol_norm: local.map(text::normalize), + content_digest: "sha256:x".into(), + semantic_digest: None, + searchable: true, + metadata: local + .map(|local| serde_json::json!({"local_name": local})) + .unwrap_or(serde_json::Value::Null), + } + } + + #[test] + fn typo_candidate_still_scores() { + let candidate = node("归一化检查", Some("normalize_check")); + let scored = score_candidate(&candidate, "归一化检差", 3, 7).unwrap(); + assert!(scored.score > 0.2); + assert!(scored.matched_text.contains("归一化")); + } + + #[test] + fn unrelated_candidate_is_dropped() { + let candidate = node("完全不同的主题", None); + assert!(score_candidate(&candidate, "quantum", 1, 4).is_none()); + } +} diff --git a/src/query/mod.rs b/src/query/mod.rs new file mode 100644 index 0000000..e342dd1 --- /dev/null +++ b/src/query/mod.rs @@ -0,0 +1,818 @@ +//! 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 { + let scope = discovery::resolve_scope(&args.root, &[])?; + let snapshot = discovery::discover(&scope)?; + let store = ReadStore::open(&scope.database_path())?; + let meta = store.build_meta()?; + 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) +} + +/// Query result before rendering. +struct QueryResult { + hits: Vec, + slice: Option, + channels: Vec, + truncated: bool, + exit_code: i32, +} + +impl QueryResult { + fn empty(channels: Vec) -> 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 = 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, + snippet: String, + matches: Vec, + score: f64, + callable: Option, + related: Vec, +} + +struct HitSource { + path: String, + digest: String, + span: Option, +} + +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, + sources: HashMap>, + 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 { + args.relation + .iter() + .filter_map(|relation| relation.parse::().ok()) + .collect() + } + + fn document_meta(&self, doc_id: i64) -> Option<&StoredDocumentMeta> { + self.documents.get(&doc_id) + } + + fn source(&mut self, doc_id: i64) -> Result, 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 { + 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 { + 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 = 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 model_digest = embedding + .get("model_digest") + .and_then(|value| value.as_str()) + .unwrap_or_default(); + channels.push(semantic::channel( + self.store, + &args.query, + model_digest, + 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 = 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 { + 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 { + match search::exact(self.store, &args.query)? { + ExactResolution::Address(node) => Ok(node), + ExactResolution::Candidates(nodes) => { + let hints: Vec = 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 = 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 { + 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, + })); + } + } + 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, + related, + }) + } + + fn envelope( + &mut self, + args: &QueryArgs, + result: &QueryResult, + ) -> Result { + let hits: Vec = 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::>(), + "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()); + } + 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 { + value.and_then(|value| value.parse::().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 = 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"); + } +} diff --git a/src/query/search.rs b/src/query/search.rs new file mode 100644 index 0000000..3f68e84 --- /dev/null +++ b/src/query/search.rs @@ -0,0 +1,701 @@ +//! Candidate channels and weighted Reciprocal Rank Fusion. +//! +//! Channels produce ranked node candidates; identities are never fuzzy. Fusion +//! works on global node ranks (not raw channel scores) so different scales never +//! mix. Graph expansion runs after fusion with hard budgets and explicit +//! truncation reporting. + +use super::fuzzy; +use crate::error::KnowledgeError; +use crate::model::{EdgeKind, EdgeState, NodeKey, NodeKind}; +use crate::storage::read::{ReadStore, StoredNode}; +use crate::text; +use std::collections::{HashMap, HashSet}; + +/// RRF constant from the development specification. +pub const RRF_K: f64 = 60.0; +/// Weight of the exact title/name channel in fusion. +pub const EXACT_WEIGHT: f64 = 1.5; +pub const LEXICAL_WEIGHT: f64 = 1.0; +pub const FUZZY_WEIGHT: f64 = 1.0; +pub const SEMANTIC_WEIGHT: f64 = 1.0; +/// Default graph expansion bounds. +pub const GRAPH_SEED_LIMIT: usize = 20; +pub const GRAPH_EDGES_PER_SEED: usize = 20; +pub const GRAPH_NODE_LIMIT: usize = 200; +pub const GRAPH_DECAY: f64 = 0.35; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct MatchReason { + pub channel: String, + pub field: String, +} + +#[derive(Debug, Clone)] +pub struct RankedNode { + pub node_id: i64, + pub rank: usize, + pub unit_id: Option, + pub field: String, + pub matched_text: String, +} + +#[derive(Debug, Clone)] +pub struct ChannelResult { + pub channel: &'static str, + pub ranked: Vec, + pub truncated: bool, +} + +#[derive(Debug, Clone)] +pub struct FusedHit { + pub node_id: i64, + pub score: f64, + pub matches: Vec, + pub best_unit: Option, +} + +#[derive(Debug, Clone)] +#[allow(clippy::large_enum_variant)] // one node is the common address hit +pub enum ExactResolution { + Address(StoredNode), + Candidates(Vec), + None, +} + +/// Canonical address / exact-name lookup. Never fuzzy. +pub fn exact(store: &ReadStore, query: &str) -> Result { + if let Some(key) = NodeKey::from_encoded(query) { + if let Some(node) = store.node_by_key(key.as_str())? { + return Ok(ExactResolution::Address(node)); + } + } + if let Some(node) = store.node_by_key(query)? { + return Ok(ExactResolution::Address(node)); + } + let aliases = store.aliases_for(query)?; + if aliases.len() == 1 { + return Ok(ExactResolution::Address(aliases[0].1.clone())); + } + if aliases.len() > 1 { + let mut nodes: Vec = aliases.into_iter().map(|(_, node)| node).collect(); + nodes.sort_by(|a, b| a.key.cmp(&b.key)); + return Ok(ExactResolution::Candidates(nodes)); + } + let normalized = text::normalize(query); + if normalized.is_empty() { + return Ok(ExactResolution::None); + } + let nodes = store.nodes_by_exact_name(&normalized)?; + match nodes.len() { + 0 => Ok(ExactResolution::None), + 1 => Ok(ExactResolution::Address( + nodes.into_iter().next().expect("one"), + )), + _ => Ok(ExactResolution::Candidates(nodes)), + } +} + +/// Lexical channel over FTS5 BM25. +pub fn lexical( + store: &ReadStore, + query: &str, + limit: usize, +) -> Result { + let Some(fts_query) = text::fts_query(query) else { + return Ok(ChannelResult { + channel: "lexical", + ranked: Vec::new(), + truncated: false, + }); + }; + let query_tokens = text::tokens(query); + let hits = store.fts_search(&fts_query, limit)?; + let truncated = hits.len() >= limit; + let mut grouped: HashMap = HashMap::new(); + let mut unit_order: Vec = Vec::new(); + for (position, hit) in hits.iter().enumerate() { + let unit = match store.search_unit(hit.unit_id)? { + Some(unit) => unit, + None => continue, + }; + let field = detect_field(&unit, &query_tokens); + let entry = RankedNode { + node_id: hit.node_id, + rank: position + 1, + unit_id: Some(hit.unit_id), + field, + matched_text: String::new(), + }; + unit_order.push(hit.unit_id); + grouped + .entry(hit.node_id) + .and_modify(|existing| { + if entry.rank < existing.rank { + *existing = entry.clone(); + } + }) + .or_insert(entry); + } + let _ = unit_order; + let mut nodes: Vec = grouped.into_values().collect(); + nodes.sort_by(|a, b| a.rank.cmp(&b.rank).then(a.node_id.cmp(&b.node_id))); + for (index, node) in nodes.iter_mut().enumerate() { + node.rank = index + 1; + } + Ok(ChannelResult { + channel: "lexical", + ranked: nodes, + truncated, + }) +} + +fn detect_field(unit: &crate::storage::read::SearchUnitRow, tokens: &[String]) -> String { + for (name, value) in unit.fields_for_matching() { + let padded = format!(" {} ", value); + if tokens + .iter() + .any(|token| padded.contains(&format!(" {token} "))) + { + return name.to_string(); + } + } + "body".to_string() +} + +/// Fuzzy channel: gram recall then bounded edit-distance scoring. +pub fn fuzzy( + store: &ReadStore, + query: &str, + limit: usize, +) -> Result { + let grams = text::grams(query); + let candidates = if grams.is_empty() { + Vec::new() + } else { + store.gram_candidates(&grams, limit)? + }; + // Short/typo fallbacks: single-character CJK probes and a bounded prefix + // scan. They only recall candidates; edit distance still scores them. + let mut fallback_nodes: Vec<(i64, Option, i64)> = Vec::new(); + let mut truncated = candidates.len() >= limit; + if candidates.is_empty() { + let single_chars = text::single_char_terms(query); + if single_chars.len() == 1 && text::tokens(query).len() == 1 { + // One-character CJK query: bounded exact-character candidates, + // ordered deterministically. This is a limitation, not a full scan. + let mut seen = std::collections::BTreeSet::new(); + for node_id_hit in store.single_char_candidates(&single_chars, limit)? { + if seen.insert(node_id_hit.node_id) { + fallback_nodes.push((node_id_hit.node_id, None, 0)); + } + } + truncated = true; + let mut ranked = Vec::new(); + for (index, (node_id, unit_id, _)) in fallback_nodes.into_iter().enumerate() { + ranked.push(RankedNode { + node_id, + rank: index + 1, + unit_id, + field: "title".into(), + matched_text: String::new(), + }); + } + return Ok(ChannelResult { + channel: "fuzzy", + ranked, + truncated, + }); + } + let mut seen = std::collections::BTreeSet::new(); + for ch in single_chars { + for hit in store.single_char_candidates(&[ch], 64)? { + if seen.insert(hit.node_id) { + fallback_nodes.push((hit.node_id, None, 0)); + } + } + } + let normalized = text::normalize(query); + let prefix: String = normalized.chars().take(2).collect(); + if !prefix.is_empty() { + for hit in store.prefix_candidates(&prefix, 128)? { + if seen.insert(hit.node_id) { + fallback_nodes.push((hit.node_id, None, 0)); + } + } + } + truncated = true; + } + let mut seen_nodes: HashMap)> = HashMap::new(); + for candidate in &candidates { + let entry = seen_nodes + .entry(candidate.node_id) + .or_insert((candidate.overlap, Some(candidate.unit_id))); + if candidate.overlap > entry.0 { + *entry = (candidate.overlap, Some(candidate.unit_id)); + } + } + for (node_id, unit_id, overlap) in fallback_nodes { + seen_nodes.entry(node_id).or_insert((overlap, unit_id)); + } + let mut scored: Vec<(RankedNode, f64)> = Vec::new(); + for (node_id, (overlap, unit_id)) in seen_nodes { + let Some(node) = store.node_by_id(node_id)? else { + continue; + }; + if !node.searchable { + continue; + } + if let Some(candidate) = fuzzy::score_candidate(&node, query, overlap, grams.len()) { + let field = match unit_id { + Some(unit_id) => match store.search_unit(unit_id)? { + Some(unit) => detect_field(&unit, &text::tokens(query)), + None => "title".into(), + }, + None => "title".into(), + }; + scored.push(( + RankedNode { + node_id, + rank: 0, + unit_id, + field, + matched_text: candidate.matched_text, + }, + candidate.score, + )); + } + } + scored.sort_by(|a, b| { + b.1.partial_cmp(&a.1) + .unwrap_or(std::cmp::Ordering::Equal) + .then(a.0.node_id.cmp(&b.0.node_id)) + }); + let mut ranked: Vec = Vec::with_capacity(scored.len()); + for (index, (mut node, _score)) in scored.into_iter().enumerate() { + node.rank = index + 1; + ranked.push(node); + } + Ok(ChannelResult { + channel: "fuzzy", + ranked, + truncated, + }) +} + +/// Weighted RRF over channels. Direct hits keep their fused score; the best +/// search unit per node is kept for snippet selection. +pub fn fuse(channels: &[ChannelResult]) -> Vec { + let mut fused: HashMap = HashMap::new(); + for channel in channels { + let weight = channel_weight(channel.channel); + for ranked in &channel.ranked { + let contribution = weight / (RRF_K + ranked.rank as f64); + let entry = fused.entry(ranked.node_id).or_insert_with(|| FusedHit { + node_id: ranked.node_id, + score: 0.0, + matches: Vec::new(), + best_unit: None, + }); + entry.score += contribution; + if entry.best_unit.is_none() { + entry.best_unit = ranked.unit_id; + } + let reason = MatchReason { + channel: channel.channel.to_string(), + field: ranked.field.clone(), + }; + if !entry.matches.contains(&reason) { + entry.matches.push(reason); + } + } + } + let mut hits: Vec = fused.into_values().collect(); + hits.sort_by(|a, b| { + b.score + .partial_cmp(&a.score) + .unwrap_or(std::cmp::Ordering::Equal) + .then(a.node_id.cmp(&b.node_id)) + }); + hits +} + +fn channel_weight(channel: &str) -> f64 { + match channel { + "exact" => EXACT_WEIGHT, + "lexical" => LEXICAL_WEIGHT, + "fuzzy" => FUZZY_WEIGHT, + "semantic" => SEMANTIC_WEIGHT, + _ => 1.0, + } +} + +#[derive(Debug, Clone)] +pub struct GraphRelated { + pub relation: String, + pub direction: String, + pub node_id: i64, + pub title: String, +} + +#[derive(Debug, Clone)] +pub struct GraphHit { + pub node_id: i64, + pub score: f64, + pub depth: usize, + pub related: Vec, +} + +#[derive(Debug, Clone)] +pub struct Expansion { + pub hits: Vec, + pub truncated: bool, +} + +#[derive(Debug, Clone)] +pub struct ExpandOptions { + pub depth: usize, + pub relations: Vec, + pub reverse: bool, +} + +impl Default for ExpandOptions { + fn default() -> Self { + Self { + depth: 1, + relations: Vec::new(), + reverse: false, + } + } +} + +/// Bounded graph expansion from high-ranked seeds. +pub fn expand( + store: &ReadStore, + seeds: &[(i64, f64)], + options: &ExpandOptions, +) -> Result { + if options.depth == 0 { + return Ok(Expansion { + hits: Vec::new(), + truncated: false, + }); + } + let relations: Vec = if options.relations.is_empty() { + vec![ + EdgeKind::References, + EdgeKind::Contains, + EdgeKind::Calls, + EdgeKind::Imports, + ] + } else { + options.relations.clone() + }; + let direct: HashSet = seeds.iter().map(|(id, _)| *id).collect(); + let mut best: HashMap = HashMap::new(); + let mut truncated = false; + let mut edges_visited = 0usize; + let mut visited_total = 0usize; + for (seed_index, (seed, seed_score)) in seeds.iter().take(GRAPH_SEED_LIMIT).enumerate() { + let mut frontier: Vec<(i64, usize, f64)> = vec![(*seed, 0, *seed_score)]; + let mut seed_edges = 0usize; + while let Some((current, depth, contribution)) = frontier.pop() { + if depth >= options.depth { + continue; + } + let next_contribution = contribution * GRAPH_DECAY; + for kind in &relations { + let neighbours = neighbours(store, current, *kind, options.reverse)?; + for (neighbour, direction) in neighbours { + edges_visited += 1; + seed_edges += 1; + if seed_edges > GRAPH_EDGES_PER_SEED + || edges_visited > GRAPH_EDGES_PER_SEED * 10 + { + truncated = true; + break; + } + if direct.contains(&neighbour) { + continue; + } + let title = store + .node_by_id(neighbour)? + .map(|node| node.title) + .unwrap_or_default(); + let related = GraphRelated { + relation: kind.as_str().to_string(), + direction: direction.clone(), + node_id: neighbour, + title: title.clone(), + }; + let entry = best.entry(neighbour).or_insert_with(|| { + visited_total += 1; + GraphHit { + node_id: neighbour, + score: 0.0, + depth: depth + 1, + related: Vec::new(), + } + }); + if next_contribution > entry.score { + entry.score = next_contribution; + entry.depth = depth + 1; + entry.related = vec![related]; + } + if visited_total >= GRAPH_NODE_LIMIT { + truncated = true; + break; + } + if depth + 1 < options.depth { + frontier.push((neighbour, depth + 1, next_contribution)); + } + } + if seed_edges > GRAPH_EDGES_PER_SEED { + break; + } + } + let _ = seed_index; + } + } + let mut hits: Vec = best.into_values().collect(); + hits.sort_by(|a, b| { + b.score + .partial_cmp(&a.score) + .unwrap_or(std::cmp::Ordering::Equal) + .then(a.node_id.cmp(&b.node_id)) + }); + Ok(Expansion { hits, truncated }) +} + +fn neighbours( + store: &ReadStore, + node_id: i64, + kind: EdgeKind, + reverse: bool, +) -> Result, KnowledgeError> { + let mut out = Vec::new(); + let outgoing = !reverse || kind == EdgeKind::Contains; + let incoming = reverse || matches!(kind, EdgeKind::Contains | EdgeKind::References); + if outgoing { + for edge in store.edges_from(&[node_id], &[kind])? { + if edge.state.is_bound() { + if let Some(target) = edge.target_id { + out.push((target, format!("{}_out", kind.as_str()))); + } + } + } + } + if incoming { + for edge in store.edges_to(&[node_id], &[kind])? { + if edge.state.is_bound() { + out.push((edge.source_id, format!("{}_in", kind.as_str()))); + } + } + } + let mut seen = HashSet::new(); + out.retain(|(id, _)| seen.insert(*id)); + out.sort(); + Ok(out) +} + +/// Filter and order final hits: direct hits first, then graph neighbours, then +/// apply `--kind` and `--limit`. +pub fn finalize( + store: &ReadStore, + fused: Vec, + expansion: &Expansion, + kind: Option, + limit: usize, +) -> Result, KnowledgeError> { + let mut final_hits: Vec = Vec::new(); + let direct_ids: HashSet = fused.iter().map(|hit| hit.node_id).collect(); + for hit in &fused { + let Some(node) = store.node_by_id(hit.node_id)? else { + continue; + }; + if let Some(kind) = kind { + if node.kind != kind { + continue; + } + } + if !node.searchable { + continue; + } + final_hits.push(FinalHit { + node, + score: hit.score, + direct: true, + matches: hit.matches.clone(), + best_unit: hit.best_unit, + related: Vec::new(), + depth: 0, + }); + } + for hit in &expansion.hits { + if direct_ids.contains(&hit.node_id) { + continue; + } + let Some(node) = store.node_by_id(hit.node_id)? else { + continue; + }; + if let Some(kind) = kind { + if node.kind != kind { + continue; + } + } + if matches!( + node.kind, + NodeKind::External | NodeKind::Statement | NodeKind::Document + ) { + continue; + } + final_hits.push(FinalHit { + node, + score: hit.score, + direct: false, + matches: vec![MatchReason { + channel: "graph".into(), + field: "relation".into(), + }], + best_unit: None, + related: hit.related.clone(), + depth: hit.depth, + }); + } + final_hits.sort_by(|a, b| { + b.direct + .cmp(&a.direct) + .then( + b.score + .partial_cmp(&a.score) + .unwrap_or(std::cmp::Ordering::Equal), + ) + .then(a.node.key.cmp(&b.node.key)) + }); + final_hits.truncate(limit); + Ok(final_hits) +} + +#[derive(Debug, Clone)] +pub struct FinalHit { + pub node: StoredNode, + pub score: f64, + pub direct: bool, + pub matches: Vec, + pub best_unit: Option, + pub related: Vec, + pub depth: usize, +} + +/// Build the exact channel from an exact resolution. +pub fn exact_channel(resolution: &ExactResolution) -> ChannelResult { + let ranked = match resolution { + ExactResolution::Address(node) => vec![RankedNode { + node_id: node.id, + rank: 1, + unit_id: None, + field: "address".into(), + matched_text: node.title.clone(), + }], + ExactResolution::Candidates(nodes) => nodes + .iter() + .enumerate() + .map(|(index, node)| RankedNode { + node_id: node.id, + rank: index + 1, + unit_id: None, + field: "title".into(), + matched_text: node.title.clone(), + }) + .collect(), + ExactResolution::None => Vec::new(), + }; + ChannelResult { + channel: "exact", + ranked, + truncated: false, + } +} + +/// State name for a stored edge (used by slices). +pub fn state_is_bound(state: EdgeState) -> bool { + state != EdgeState::Missing + && state != EdgeState::Invalid + && state != EdgeState::OutOfScope + && state != EdgeState::Dynamic + && state != EdgeState::Unresolved +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn rrf_prefers_agreement_across_channels() { + let lexical = ChannelResult { + channel: "lexical", + ranked: vec![ + RankedNode { + node_id: 1, + rank: 1, + unit_id: None, + field: "title".into(), + matched_text: String::new(), + }, + RankedNode { + node_id: 2, + rank: 2, + unit_id: None, + field: "body".into(), + matched_text: String::new(), + }, + ], + truncated: false, + }; + let fuzzy = ChannelResult { + channel: "fuzzy", + ranked: vec![RankedNode { + node_id: 2, + rank: 1, + unit_id: None, + field: "title".into(), + matched_text: String::new(), + }], + truncated: false, + }; + let fused = fuse(&[lexical, fuzzy]); + // Node 2 appears in both channels and should win. + assert_eq!(fused[0].node_id, 2); + assert!(fused[0].score > fused[1].score); + assert_eq!(fused[0].matches.len(), 2); + } + + #[test] + fn exact_addresses_rank_first() { + let node = crate::storage::read::StoredNode { + id: 7, + key: "k".into(), + kind: NodeKind::Section, + doc_id: Some(1), + parent_id: None, + span: None, + title: "t".into(), + title_norm: "t".into(), + symbol_norm: None, + content_digest: "sha256:x".into(), + semantic_digest: None, + searchable: true, + metadata: serde_json::Value::Null, + }; + let channel = exact_channel(&ExactResolution::Address(node)); + assert_eq!(channel.ranked[0].node_id, 7); + assert_eq!(channel.ranked[0].field, "address"); + } + + #[test] + fn expansion_direction_flags_are_consistent() { + assert!(state_is_bound(EdgeState::Resolved)); + assert!(state_is_bound(EdgeState::External)); + assert!(!state_is_bound(EdgeState::Unresolved)); + } +} diff --git a/src/query/semantic.rs b/src/query/semantic.rs new file mode 100644 index 0000000..ab28d83 --- /dev/null +++ b/src/query/semantic.rs @@ -0,0 +1,79 @@ +//! Semantic channel: OpenAI-compatible embeddings. +//! +//! Semantic search is an explicit opt-in. The default query path never performs +//! network I/O, never reads embeddings and never downloads a model. A query +//! embedding is requested only with `--semantic`, and only against the endpoint +//! and model recorded in the build metadata. +//! +//! The transport itself is implemented by the embedding client module; this +//! module fuses stored vectors with the lexical/fuzzy channels. + +use crate::error::KnowledgeError; +use crate::query::search::{ChannelResult, RankedNode}; +use crate::storage::read::ReadStore; + +/// Maximum number of stored vectors scanned by the exact cosine scan. +pub const MAX_VECTOR_SCAN: usize = 50_000; + +/// Run the semantic channel. The caller must have checked that semantic +/// configuration matches the build metadata first. +pub fn channel( + _store: &ReadStore, + _query: &str, + _model_digest: &str, + _limit: usize, +) -> Result { + Err(KnowledgeError::environment( + crate::diagnostic::code::EMBEDDING_UNAVAILABLE, + "semantic search is not available in this build", + ) + .with_hint("run `marqdo knowledge compile` with embedding options and a compatible endpoint")) +} + +/// Candidate ordering helper used by the vector scan. +pub fn ranked_from_scores(scores: Vec<(i64, Option, f64)>, limit: usize) -> ChannelResult { + let mut nodes: Vec<(RankedNode, f64)> = scores + .into_iter() + .map(|(node_id, unit_id, score)| { + ( + RankedNode { + node_id, + rank: 0, + unit_id, + field: "semantic".into(), + matched_text: String::new(), + }, + score, + ) + }) + .collect(); + nodes.sort_by(|a, b| { + b.1.partial_cmp(&a.1) + .unwrap_or(std::cmp::Ordering::Equal) + .then(a.0.node_id.cmp(&b.0.node_id)) + }); + nodes.truncate(limit); + let truncated = nodes.len() >= limit; + let mut ranked = Vec::with_capacity(nodes.len()); + for (index, (mut node, _)) in nodes.into_iter().enumerate() { + node.rank = index + 1; + ranked.push(node); + } + ChannelResult { + channel: "semantic", + ranked, + truncated, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn cosine_channel_ordering_is_deterministic() { + let channel = ranked_from_scores(vec![(2, Some(20), 0.9), (1, Some(10), 0.8)], 10); + assert_eq!(channel.ranked[0].node_id, 2); + assert_eq!(channel.ranked[1].node_id, 1); + } +} diff --git a/src/query/slice.rs b/src/query/slice.rs new file mode 100644 index 0000000..ef8bca5 --- /dev/null +++ b/src/query/slice.rs @@ -0,0 +1,360 @@ +//! Bounded knowledge slices: document, execution and hybrid. +//! +//! A slice returns exact original source pieces with their paths and spans. It +//! is reading material, never a runnable program and never a rewritten summary. +//! Planning (graph traversal) is separate from materialisation (source slices) +//! so traversal never needs to load unrelated document sources. + +use crate::error::KnowledgeError; +use crate::model::{EdgeKind, NodeKind, Span}; +use crate::storage::read::{ReadStore, StoredDocumentMeta, StoredNode}; +use std::collections::{HashMap, HashSet}; + +/// Default slice byte budget (development specification §9). +pub const DEFAULT_SLICE_BUDGET: usize = 32 * 1024; +/// Hard upper bound regardless of user input. +pub const MAX_SLICE_BUDGET: usize = 1024 * 1024; +const MAX_SLICE_NODES: usize = 500; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SliceMode { + Document, + Execution, + Hybrid, +} + +impl SliceMode { + pub fn as_str(self) -> &'static str { + match self { + SliceMode::Document => "document", + SliceMode::Execution => "execution", + SliceMode::Hybrid => "hybrid", + } + } + + fn relations(self) -> Vec { + match self { + SliceMode::Document => vec![EdgeKind::Contains, EdgeKind::References], + SliceMode::Execution => vec![EdgeKind::Calls, EdgeKind::Imports], + SliceMode::Hybrid => vec![ + EdgeKind::Contains, + EdgeKind::References, + EdgeKind::Calls, + EdgeKind::Imports, + ], + } + } + + fn includes_module_context(self) -> bool { + matches!(self, SliceMode::Execution | SliceMode::Hybrid) + } +} + +#[derive(Debug, Clone)] +pub struct SlicePolicy { + pub mode: SliceMode, + pub depth: usize, + pub reverse: bool, + pub byte_budget: usize, +} + +impl Default for SlicePolicy { + fn default() -> Self { + Self { + mode: SliceMode::Document, + depth: 1, + reverse: false, + byte_budget: DEFAULT_SLICE_BUDGET, + } + } +} + +#[derive(Debug, Clone)] +pub struct PlannedPiece { + pub node: StoredNode, + pub relation: String, + pub direction: String, + /// Module context pieces contribute structure/imports, not duplicated text. + pub include_text: bool, +} + +#[derive(Debug, Clone)] +pub struct SlicePlan { + pub seed: StoredNode, + pub pieces: Vec, + pub truncated: bool, + pub mode: SliceMode, +} + +#[derive(Debug, Clone)] +pub struct SlicePiece { + pub node: StoredNode, + pub doc_path: Option, + pub span: Option, + pub text: String, + pub relation: String, + pub direction: String, + pub gap: Option, +} + +#[derive(Debug, Clone)] +pub struct Slice { + pub mode: SliceMode, + pub seed: StoredNode, + pub pieces: Vec, + pub complete: bool, + pub truncated: bool, + pub returned_bytes: usize, + pub byte_budget: usize, +} + +/// Traverse the graph around the seed. Uses only node/edge rows. +pub fn plan( + store: &ReadStore, + seed: &StoredNode, + documents: &HashMap, + policy: &SlicePolicy, +) -> Result { + let relations = policy.mode.relations(); + let mut pieces: Vec = Vec::new(); + let mut visited: HashSet = HashSet::new(); + visited.insert(seed.id); + pieces.push(PlannedPiece { + node: seed.clone(), + relation: "seed".into(), + direction: "self".into(), + include_text: true, + }); + let mut truncated = false; + + // Execution/hybrid slices include the owning module document for its imports + // and context, but never duplicate its full text. + let mut frontier: Vec<(i64, usize)> = Vec::new(); + if policy.mode.includes_module_context() { + if let Some(doc_id) = seed.doc_id { + if let Some(meta) = documents.get(&doc_id) { + let key = crate::graph::identity::document_key(&meta.path); + if let Some(document) = store.node_by_key(key.as_str())? { + if visited.insert(document.id) { + pieces.push(PlannedPiece { + node: document.clone(), + relation: "module".into(), + direction: "owner".into(), + include_text: false, + }); + frontier.push((document.id, 1)); + } + } + } + } + } + frontier.push((seed.id, 0)); + + while let Some((current, depth)) = frontier.pop() { + if depth >= policy.depth { + continue; + } + let mut neighbours = Vec::new(); + for kind in &relations { + neighbours.extend(neighbours_of(store, current, *kind, policy.reverse)?); + } + neighbours.sort(); + neighbours.dedup_by(|a, b| a.0 == b.0); + for (neighbour, relation, direction) in neighbours { + if pieces.len() >= MAX_SLICE_NODES { + truncated = true; + break; + } + if !visited.insert(neighbour) { + continue; + } + let Some(node) = store.node_by_id(neighbour)? else { + continue; + }; + if matches!(node.kind, NodeKind::Statement) { + continue; + } + pieces.push(PlannedPiece { + node, + relation, + direction, + include_text: true, + }); + if depth + 1 < policy.depth { + frontier.push((neighbour, depth + 1)); + } + } + } + // Deterministic order: seed, module context, then relation/direction/key. + let mut rest: Vec = pieces.split_off(1); + let module: Vec = rest + .iter() + .filter(|piece| piece.relation == "module") + .cloned() + .collect(); + rest.retain(|piece| piece.relation != "module"); + rest.sort_by(|a, b| { + a.relation + .cmp(&b.relation) + .then(a.direction.cmp(&b.direction)) + .then(a.node.key.cmp(&b.node.key)) + }); + let mut ordered = vec![pieces.remove(0)]; + ordered.extend(module); + ordered.extend(rest); + Ok(SlicePlan { + seed: seed.clone(), + pieces: ordered, + truncated, + mode: policy.mode, + }) +} + +/// Materialise exact source text with a deterministic byte budget. +pub fn materialize( + plan: SlicePlan, + documents: &HashMap, + policy: &SlicePolicy, + mut load_source: F, +) -> Result +where + F: FnMut(i64) -> Result>, KnowledgeError>, +{ + let budget = policy.byte_budget.clamp(1, MAX_SLICE_BUDGET); + let mut used = 0usize; + let mut truncated = plan.truncated; + let mut pieces = Vec::new(); + for planned in plan.pieces { + let doc_path = planned + .node + .doc_id + .and_then(|doc_id| documents.get(&doc_id).map(|meta| meta.path.clone())); + let mut text = String::new(); + if planned.include_text { + if let (Some(doc_id), Some(span)) = (planned.node.doc_id, planned.node.span) { + if let Some(source) = load_source(doc_id)? { + if let Some(slice) = span.slice(&source) { + text = slice.to_string(); + } + } + } + } + // Truncate the seed (or an oversized piece) on a UTF-8 boundary. + if !text.is_empty() && used + text.len() > budget { + let remaining = budget.saturating_sub(used); + text = truncate_utf8(&text, remaining); + truncated = true; + if text.is_empty() { + continue; + } + } + used += text.len(); + let gap = if text.is_empty() { + Some(match planned.node.kind { + NodeKind::External => { + "external target: no local source is available (static closure gap)".to_string() + } + NodeKind::Document => "module context: imports only".to_string(), + _ => "node has no source text".to_string(), + }) + } else { + None + }; + let node_span = planned.node.span; + pieces.push(SlicePiece { + node: planned.node, + doc_path, + span: node_span, + text, + relation: planned.relation, + direction: planned.direction, + gap, + }); + if used >= budget { + truncated = true; + break; + } + } + let returned_bytes = pieces.iter().map(|piece| piece.text.len()).sum(); + Ok(Slice { + mode: plan.mode, + seed: plan.seed, + pieces, + complete: !truncated, + truncated, + returned_bytes, + byte_budget: budget, + }) +} + +fn neighbours_of( + store: &ReadStore, + node_id: i64, + kind: EdgeKind, + reverse: bool, +) -> Result, KnowledgeError> { + let mut out = Vec::new(); + // Contains follows children only in slices: parent sections would duplicate + // the entire descendant text. References are bidirectional; calls/imports + // follow their direction unless --reverse is explicit. + let outgoing = !reverse || kind == EdgeKind::References; + let incoming = matches!(kind, EdgeKind::References) || (reverse && kind != EdgeKind::Contains); + if outgoing { + for edge in store.edges_from(&[node_id], &[kind])? { + if edge.state.is_bound() { + if let Some(target) = edge.target_id { + out.push((target, kind.as_str().to_string(), "out".to_string())); + } + } + } + } + if incoming { + for edge in store.edges_to(&[node_id], &[kind])? { + if edge.state.is_bound() { + out.push((edge.source_id, kind.as_str().to_string(), "in".to_string())); + } + } + } + let mut seen = HashSet::new(); + out.retain(|(id, _, _)| seen.insert(*id)); + Ok(out) +} + +fn truncate_utf8(text: &str, budget: usize) -> String { + if text.len() <= budget { + return text.to_string(); + } + let mut end = budget.min(text.len()); + while end > 0 && !text.is_char_boundary(end) { + end -= 1; + } + text[..end].to_string() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn utf8_truncation_never_splits_a_character() { + let text = "量子力学"; + assert_eq!(truncate_utf8(text, 4), "量"); + assert_eq!(truncate_utf8(text, 3), "量"); + assert_eq!(truncate_utf8(text, 100), text); + } + + #[test] + fn slice_modes_map_to_the_four_relation_kinds() { + assert_eq!( + SliceMode::Document.relations(), + vec![EdgeKind::Contains, EdgeKind::References] + ); + assert_eq!( + SliceMode::Execution.relations(), + vec![EdgeKind::Calls, EdgeKind::Imports] + ); + assert_eq!(SliceMode::Hybrid.relations().len(), 4); + assert!(SliceMode::Execution.includes_module_context()); + assert!(!SliceMode::Document.includes_module_context()); + } +} diff --git a/src/storage/read.rs b/src/storage/read.rs index bd3e9b8..3ac4265 100644 --- a/src/storage/read.rs +++ b/src/storage/read.rs @@ -640,6 +640,38 @@ impl ReadStore { Ok(out) } + /// Bounded prefix recall for short/typo queries without shared grams. + pub fn prefix_candidates( + &self, + normalized_prefix: &str, + limit: usize, + ) -> Result, KnowledgeError> { + if normalized_prefix.is_empty() { + return Ok(Vec::new()); + } + let like = format!("{}%", escape_like(normalized_prefix)); + let mut statement = self + .conn + .prepare( + "SELECT id FROM nodes + WHERE searchable = 1 AND (title_norm LIKE ?1 ESCAPE '\\' OR symbol_norm LIKE ?1 ESCAPE '\\') + ORDER BY id LIMIT ?2", + ) + .map_err(db)?; + let rows = statement + .query_map(rusqlite::params![like, limit as i64], |row| { + row.get::<_, i64>(0) + }) + .map_err(db)?; + let mut out = Vec::new(); + for row in rows { + out.push(NodeIdHit { + node_id: row.map_err(db)?, + }); + } + Ok(out) + } + pub fn embeddings( &self, model_digest: &str, diff --git a/src/text.rs b/src/text.rs index 5cf62f0..6e03de5 100644 --- a/src/text.rs +++ b/src/text.rs @@ -235,6 +235,35 @@ pub fn similarity(left: &str, right: &str) -> f64 { } } +/// Best similarity between the query and any character window of `text` whose +/// length is close to the query length. Bounded to short strings; used only for +/// fuzzy ranking. This tolerates a title suffix ("归一化动机" vs "归依化") without +/// scanning the corpus. +pub fn best_window_similarity(query: &str, text: &str) -> f64 { + let normalized_query = normalize(query); + let normalized_text = normalize(text); + let query_chars: Vec = normalized_query.chars().collect(); + let text_chars: Vec = normalized_text.chars().collect(); + if query_chars.is_empty() || text_chars.is_empty() { + return 0.0; + } + if text_chars.len() <= query_chars.len() { + return similarity(&normalized_query, &normalized_text); + } + let width = query_chars.len(); + let mut best = 0.0f64; + let max_start = text_chars.len().saturating_sub(width).min(32); + for start in 0..=max_start { + let end = (start + width).min(text_chars.len()); + let window: String = text_chars[start..end].iter().collect(); + best = best.max(similarity(&normalized_query, &window)); + if best >= 0.999 { + break; + } + } + best +} + /// Escape one token for an FTS5 query: the token is emitted as a quoted string /// literal, so no FTS operator can be injected. Empty tokens are dropped. pub fn fts_quote(token: &str) -> Option { diff --git a/tests/query.rs b/tests/query.rs new file mode 100644 index 0000000..228ffdc --- /dev/null +++ b/tests/query.rs @@ -0,0 +1,265 @@ +//! 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 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"); +}