fix(knowledge): warm-load IR for preflight/find/reuse queries
Stop full recompile on every knowledge preflight by writing ekc/graph/ir.json and loading it unless --refresh or missing projections, cutting chat预检 wall time. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
b8265a92aa
commit
16f26d7d60
8 files changed
+237
-68
No files matched your search
+38
-34
@@ -114,7 +114,23 @@ pub fn ekc_graph_dir(out_dir: &Path) -> std::path::PathBuf {
|
||||
out_dir.join("ekc").join("graph")
|
||||
}
|
||||
|
||||
/// Path of the full IR snapshot used by warm query paths (preflight/find/reuse).
|
||||
pub fn ir_snapshot_path(out_dir: &Path) -> std::path::PathBuf {
|
||||
ekc_graph_dir(out_dir).join("ir.json")
|
||||
}
|
||||
|
||||
/// Load a previously compiled KnowledgeGraph without re-extracting sources.
|
||||
/// Prefers `ekc/graph/ir.json`. Does **not** walk the source tree.
|
||||
pub fn load_graph(out_dir: &Path) -> Result<KnowledgeGraph> {
|
||||
let ir_path = ir_snapshot_path(out_dir);
|
||||
if ir_path.exists() {
|
||||
let raw = fs::read_to_string(&ir_path)
|
||||
.with_context(|| format!("read {}", ir_path.display()))?;
|
||||
let graph: KnowledgeGraph = serde_json::from_str(&raw)
|
||||
.with_context(|| format!("parse {}", ir_path.display()))?;
|
||||
return Ok(graph);
|
||||
}
|
||||
|
||||
let graph_path = ekc_graph_dir(out_dir).join("graph.json");
|
||||
let edges_path = ekc_graph_dir(out_dir).join("edges.json");
|
||||
if !graph_path.exists() {
|
||||
@@ -123,47 +139,19 @@ pub fn load_graph(out_dir: &Path) -> Result<KnowledgeGraph> {
|
||||
graph_path.display()
|
||||
);
|
||||
}
|
||||
// Prefer re-extract for freshness when source path known; for query commands
|
||||
// we rebuild from JSON snapshot fields + re-scan if catalog sibling exists.
|
||||
// Snapshot load: reconstruct minimal IR from written pages + edges.json.
|
||||
|
||||
// Legacy projections without ir.json: edges-only fallback (no source walk).
|
||||
let edges_raw = fs::read_to_string(&edges_path).unwrap_or_else(|_| "{\"edges\":[]}".into());
|
||||
let edges_v: serde_json::Value = serde_json::from_str(&edges_raw)?;
|
||||
let graph_raw = fs::read_to_string(&graph_path)?;
|
||||
let graph_v: serde_json::Value = serde_json::from_str(&graph_raw)?;
|
||||
|
||||
// Re-compile from recorded root if present in graph.json
|
||||
if let Some(root) = graph_v
|
||||
.pointer("/repository/root")
|
||||
.and_then(|v| v.as_str())
|
||||
{
|
||||
let root_path = Path::new(root);
|
||||
if root_path.exists() {
|
||||
return extract_graph(&ExtractOptions {
|
||||
path: root_path.to_path_buf(),
|
||||
out_dir: out_dir.to_path_buf(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback: empty-ish graph with edges only
|
||||
let mut edges = Vec::new();
|
||||
if let Some(arr) = edges_v.get("edges").and_then(|e| e.as_array()) {
|
||||
for e in arr {
|
||||
let kind = match e.get("kind").and_then(|k| k.as_str()).unwrap_or("") {
|
||||
"implements" => crate::knowledge::ir::EdgeKind::Implements,
|
||||
"uses" => crate::knowledge::ir::EdgeKind::Uses,
|
||||
"depends_on" => crate::knowledge::ir::EdgeKind::DependsOn,
|
||||
"tested_by" => crate::knowledge::ir::EdgeKind::TestedBy,
|
||||
"documented_by" => crate::knowledge::ir::EdgeKind::DocumentedBy,
|
||||
"constrained_by" => crate::knowledge::ir::EdgeKind::ConstrainedBy,
|
||||
"decided_by" => crate::knowledge::ir::EdgeKind::DecidedBy,
|
||||
"supersedes" => crate::knowledge::ir::EdgeKind::Supersedes,
|
||||
"conflicts_with" => crate::knowledge::ir::EdgeKind::ConflictsWith,
|
||||
"deprecated_by" => crate::knowledge::ir::EdgeKind::DeprecatedBy,
|
||||
"derived_from" => crate::knowledge::ir::EdgeKind::DerivedFrom,
|
||||
"failed_by" => crate::knowledge::ir::EdgeKind::FailedBy,
|
||||
_ => crate::knowledge::ir::EdgeKind::RelatedTo,
|
||||
};
|
||||
let kind = crate::knowledge::ir::EdgeKind::parse(
|
||||
e.get("kind").and_then(|k| k.as_str()).unwrap_or(""),
|
||||
);
|
||||
edges.push(crate::knowledge::ir::Edge {
|
||||
from: e.get("from").and_then(|v| v.as_str()).unwrap_or("").into(),
|
||||
to: e.get("to").and_then(|v| v.as_str()).unwrap_or("").into(),
|
||||
@@ -204,14 +192,27 @@ pub fn load_graph(out_dir: &Path) -> Result<KnowledgeGraph> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Force a full knowledge compile (write path / `--refresh`).
|
||||
pub fn ensure_compiled(path: &Path, out_dir: &Path) -> Result<KnowledgeGraph> {
|
||||
// Always refresh from source when path is given.
|
||||
compile(KnowledgeOptions {
|
||||
path: path.to_path_buf(),
|
||||
out_dir: out_dir.to_path_buf(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Query path loader: compile if missing (or `refresh`), else hot-load `ir.json`.
|
||||
pub fn graph_for_query(path: &Path, out_dir: &Path, refresh: bool) -> Result<KnowledgeGraph> {
|
||||
if refresh {
|
||||
return ensure_compiled(path, out_dir);
|
||||
}
|
||||
let has_ir = ir_snapshot_path(out_dir).exists();
|
||||
let has_graph = ekc_graph_dir(out_dir).join("graph.json").exists();
|
||||
if has_ir || has_graph {
|
||||
return load_graph(out_dir);
|
||||
}
|
||||
ensure_compiled(path, out_dir)
|
||||
}
|
||||
|
||||
fn write_projections(out_dir: &Path, graph: &KnowledgeGraph) -> Result<()> {
|
||||
let dirs = [
|
||||
"catalog/modules",
|
||||
@@ -299,6 +300,9 @@ fn write_projections(out_dir: &Path, graph: &KnowledgeGraph) -> Result<()> {
|
||||
fs::write(ekc.join("graph.json"), graph_json)?;
|
||||
let edges_json = serde_json::to_string_pretty(&graph.to_edges_json())?;
|
||||
fs::write(ekc.join("edges.json"), edges_json)?;
|
||||
// Full IR snapshot for warm query paths (preflight/find/reuse) — no re-extract.
|
||||
let ir_json = serde_json::to_string(&graph)?;
|
||||
fs::write(ekc.join("ir.json"), ir_json)?;
|
||||
|
||||
// Search index
|
||||
let index = json!({
|
||||
|
||||
+67
-9
@@ -1,5 +1,6 @@
|
||||
//! Engineering Knowledge IR (L0–L4) — projections of `.mq.md`, not a second source of truth.
|
||||
|
||||
use serde::{Deserialize, Deserializer, Serialize, Serializer};
|
||||
use serde_json::{json, Value};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
@@ -13,6 +14,19 @@ pub enum Lifecycle {
|
||||
Superseded,
|
||||
}
|
||||
|
||||
impl Serialize for Lifecycle {
|
||||
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
|
||||
serializer.serialize_str(self.as_str())
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for Lifecycle {
|
||||
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
|
||||
let s = String::deserialize(deserializer)?;
|
||||
Ok(Self::parse(&s))
|
||||
}
|
||||
}
|
||||
|
||||
impl Lifecycle {
|
||||
pub fn as_str(&self) -> &'static str {
|
||||
match self {
|
||||
@@ -35,7 +49,7 @@ impl Lifecycle {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
||||
pub struct Evidence {
|
||||
pub sources: Vec<String>,
|
||||
pub tests: Vec<String>,
|
||||
@@ -55,7 +69,7 @@ impl Evidence {
|
||||
}
|
||||
|
||||
/// Graded confidence with explanation (not a bare float).
|
||||
#[derive(Debug, Clone)]
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct Confidence {
|
||||
pub level: String, // high | medium | low
|
||||
pub implementation: String,
|
||||
@@ -87,7 +101,7 @@ impl Confidence {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct RepositoryInfo {
|
||||
pub title: String,
|
||||
pub root: String,
|
||||
@@ -98,7 +112,7 @@ pub struct RepositoryInfo {
|
||||
pub knowledge_count: usize,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct ModuleInfo {
|
||||
pub id: String,
|
||||
pub resource: String,
|
||||
@@ -111,7 +125,7 @@ pub struct ModuleInfo {
|
||||
pub status: Lifecycle,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct SymbolInfo {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
@@ -135,7 +149,7 @@ pub struct SymbolInfo {
|
||||
pub confidence: Confidence,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct CapabilityInfo {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
@@ -215,7 +229,20 @@ impl KnowledgeKind {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
impl Serialize for KnowledgeKind {
|
||||
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
|
||||
serializer.serialize_str(self.as_str())
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for KnowledgeKind {
|
||||
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
|
||||
let s = String::deserialize(deserializer)?;
|
||||
Ok(Self::parse(&s))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct KnowledgeItem {
|
||||
pub id: String,
|
||||
pub kind: KnowledgeKind,
|
||||
@@ -269,9 +296,40 @@ impl EdgeKind {
|
||||
Self::RelatedTo => "related_to",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse(s: &str) -> Self {
|
||||
match s.trim() {
|
||||
"implements" => Self::Implements,
|
||||
"uses" => Self::Uses,
|
||||
"depends_on" => Self::DependsOn,
|
||||
"tested_by" => Self::TestedBy,
|
||||
"documented_by" => Self::DocumentedBy,
|
||||
"constrained_by" => Self::ConstrainedBy,
|
||||
"decided_by" => Self::DecidedBy,
|
||||
"supersedes" => Self::Supersedes,
|
||||
"conflicts_with" => Self::ConflictsWith,
|
||||
"deprecated_by" => Self::DeprecatedBy,
|
||||
"derived_from" => Self::DerivedFrom,
|
||||
"failed_by" => Self::FailedBy,
|
||||
_ => Self::RelatedTo,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
impl Serialize for EdgeKind {
|
||||
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
|
||||
serializer.serialize_str(self.as_str())
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for EdgeKind {
|
||||
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
|
||||
let s = String::deserialize(deserializer)?;
|
||||
Ok(Self::parse(&s))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct Edge {
|
||||
pub from: String,
|
||||
pub to: String,
|
||||
@@ -336,7 +394,7 @@ pub struct ReuseResult {
|
||||
pub recommended: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct KnowledgeGraph {
|
||||
pub repository: RepositoryInfo,
|
||||
pub modules: Vec<ModuleInfo>,
|
||||
|
||||
@@ -20,7 +20,10 @@ pub mod preflight;
|
||||
pub mod reuse;
|
||||
pub mod util;
|
||||
|
||||
pub use compile::{compile, ekc_graph_dir, ensure_compiled, load_graph, KnowledgeOptions};
|
||||
pub use compile::{
|
||||
compile, ekc_graph_dir, ensure_compiled, graph_for_query, ir_snapshot_path, load_graph,
|
||||
KnowledgeOptions,
|
||||
};
|
||||
pub use duplicate::{find_duplicates, format_duplicates_text};
|
||||
pub use find::{find, find_json, format_find_text};
|
||||
pub use impact::{format_impact_text, impact, impact_json};
|
||||
@@ -32,7 +35,9 @@ pub use lifecycle::{
|
||||
};
|
||||
pub use metrics::{load_metrics, record_decision, save_metrics, ReuseMetrics};
|
||||
pub use policy::compile_policy;
|
||||
pub use preflight::{format_preflight_yaml, preflight, preflight_json, PreflightResult};
|
||||
pub use preflight::{
|
||||
format_preflight_yaml, preflight, preflight_from_reuse, preflight_json, PreflightResult,
|
||||
};
|
||||
pub use reuse::{format_reuse_text, resolve, reuse_json, ReuseBudget};
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
@@ -33,6 +33,16 @@ pub fn preflight(
|
||||
out_dir: Option<&Path>,
|
||||
) -> Result<PreflightResult> {
|
||||
let reuse = resolve(graph, task, budget);
|
||||
preflight_from_reuse(graph, task, &reuse, out_dir)
|
||||
}
|
||||
|
||||
/// Build a Context Pack from an already-resolved reuse result (avoids a second `resolve`).
|
||||
pub fn preflight_from_reuse(
|
||||
graph: &KnowledgeGraph,
|
||||
task: &str,
|
||||
reuse: &crate::knowledge::ir::ReuseResult,
|
||||
out_dir: Option<&Path>,
|
||||
) -> Result<PreflightResult> {
|
||||
let intent = reuse
|
||||
.capability
|
||||
.clone()
|
||||
@@ -46,7 +56,7 @@ pub fn preflight(
|
||||
.map(|c| c.title.clone())
|
||||
.collect();
|
||||
|
||||
let pack = render_context_pack(task, &intent, &reuse, graph);
|
||||
let pack = render_context_pack(task, &intent, reuse, graph);
|
||||
let mut context_path = None;
|
||||
if let Some(out) = out_dir {
|
||||
let contexts = out.join("agent/contexts");
|
||||
|
||||
Reference in new issue
Block a user