feat: return candidate location and evidence status per hit

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.
This commit is contained in:
cflmy committed 2026-11-30 11:59:42 +08:00
1 parent 3cc477de60
commit 3bd93363a1
5 files changed
+168

No files matched your search

+1
View File
@@ -50,6 +50,7 @@ must not be claimed as passing.
| Compile command incl. digest-based incremental facts reuse and conservative re-analysis bound | implemented | `tests/compile.rs` |
| Check command (sources, references, database structure/currentness) | implemented | `tests/compile.rs`, `tests/query.rs` |
| Exact / lexical / fuzzy / graph query, weighted RRF, bounded expansion | implemented | `src/query/*` tests, `tests/query.rs` |
| Candidate location + evidence status (module/unit/anchor/span/digest, current/stale, `nature: unspecified`) | implemented | `tests/query.rs`, `spec/knowledge.md` §3.1.1/§4.1 |
| Document / execution / hybrid slices with 32 KiB budget | implemented | `tests/query.rs`, `src/query/slice.rs` |
| OKF v0.3 metadata recognition, reserved roles, concept aliases, `check --okf` conformance | implemented | `tests/okf.rs` |
| Explicit OpenAI-compatible semantic channel with all-or-nothing indexing | implemented | `tests/embedding.rs` (local mock protocol server) |
+69
View File
@@ -110,6 +110,52 @@ current Analysis passed static checking; it is interface information, not
execution permission. Every `snippet` is an exact source slice; external nodes
carry no fabricated path, span or snippet.
### 3.1.1 Candidate location and evidence (additive)
Every hit may carry two optional objects. They are additive within
`schema_version: 1`: consumers must ignore unknown fields and must not treat
their absence as an error (older databases predate them).
```json
"location": {
"module_id": "root:demo@0.1.0::index.mq.md",
"unit_id": "root:demo@0.1.0::index.mq.md#力学/计算力",
"unit_kind": "function",
"anchors": ["计算力"],
"path": ["力学", "计算力"],
"level": 2,
"mode": "exec",
"nature": "unspecified",
"span": {"start": 100, "end": 180}
},
"evidence": {
"status": "current",
"source_digest": "sha256:...",
"snapshot_digest": "sha256:..."
}
```
* `location` is the document-structure identity from the public Analysis
projection (`units[].id/path/level/mode`, `anchors[]`) or from this tool's own
plain-Markdown heading projection. `unit_id`/`module_id` stay `null` when the
document has no Analysis module identity; they are never fabricated.
`anchors` are navigation names, not identities or execution rights.
* `nature` is the authority/nature marker from `marqdo#55` §5. It is
`"unspecified"` unless an existing public input (document structure or OKF
metadata) declares a nature. Knowledge never guesses normative, explanatory,
experimental or historical status and never adds metadata syntax.
* `evidence.status` is `current` only when the database input manifest still
matches the source snapshot. A `--snapshot` query or a stale database reports
`stale`; the result envelope's `current` flag is authoritative for the whole
result.
* `source`/`source.span` remain the exact snippet location; `location` is the
structured candidate address. Neither is a second knowledge body: the
authoritative text is always the source file, read through the CLI's public
capability.
* `related[].relation` keeps the public vocabulary (`contains`, `references`,
`imports`, `calls`). A Markdown link is a `references` relation and is never
rewritten into an import or execution dependency.
### 3.2 Error
```json
@@ -147,6 +193,29 @@ link semantics; `check --okf` additionally applies OKF bundle-root absolute
link semantics and reports conformance/notice diagnostics. OKF never executes an
executor or attester and never upgrades trust.
## 4.1 Document-structure index semantics
The index reuses the current document structure; it does not define a second
one. The mapping from public facts to indexed objects is:
| Public fact | Indexed as | Notes |
|---|---|---|
| `project.entry_module_id`, `project.root_id` | document metadata `analysis` | Entry is a project fact. `index.mq.md` is an ordinary document; the index never scans directories or treats navigation content as an entry. |
| `units[]` heading tree | `namespace`/`section`/`function` nodes | Metadata `path`, `level`, `mode`, `unit_kind`, `unit_id`, `anchors`; root is the document node. |
| `anchors[]` | node metadata `anchors` | Navigation names, unique by construction; the CLI numbers slug collisions. They are not identities. |
| `source_digest`, `span` | documents/node spans | Every snippet is an exact UTF-8 byte slice of the recorded source; Analysis inputs are digest-checked before indexing. |
| `references[]` | `references` edges (origin `document`) | States are preserved verbatim (`resolved`/`not_loaded`/`missing`/`ambiguous`/`external`/`outside_scope`/`invalid`). A link is knowledge navigation, never an import or execution edge. |
| `imports[]` | `imports` edges (origin `analysis`) | Only explicit imports create module dependencies. |
| `calls[]` | `calls` edges (origin `analysis`) | Static call graph; unresolved/dynamic calls stay explicitly unresolved. |
| `resources[]` | resource nodes | Inert formula/code payloads; no execution. |
| structure / OKF metadata | `nature` in the candidate location | `unspecified` when the inputs do not declare a nature. |
Consequences: an entry/navigation document and a knowledge unit are distinct
concepts; a resolved link does not make its target executable; and a candidate
never claims a normative nature that the public inputs did not state. Exact
reading of the located span remains the CLI's public capability; this tool does
not keep an authoritative copy of the body.
## 5. Analysis input
Marqdo program semantics come only from the core CLI:
+31
View File
@@ -200,6 +200,21 @@ pub fn build(
},
);
// Navigation anchors are a separate namespace from unit identity
// (spec/document-structure.md §2, marqdo#55 §7): index them next to the
// unit so query candidates can return a stable location without
// re-parsing the source.
let mut anchors_by_unit: BTreeMap<usize, Vec<String>> = BTreeMap::new();
for anchor in &document.anchors {
anchors_by_unit
.entry(anchor.unit)
.or_default()
.push(anchor.anchor.clone());
}
let module_id = document
.analysis
.as_ref()
.map(|analysis| analysis.module_id.clone());
let mut unit_nodes: Vec<NodeKey> = Vec::with_capacity(document.units.len());
for (index, unit) in document.units.iter().enumerate() {
if index == 0 {
@@ -212,12 +227,24 @@ pub fn build(
.iter()
.find(|function| function.unit == index);
let span = Some(unit.span);
let anchors = anchors_by_unit.get(&index).cloned().unwrap_or_default();
let unit_kind = match unit.kind {
crate::document::UnitKind::Root => "root",
crate::document::UnitKind::Namespace => "namespace",
crate::document::UnitKind::Function => "function",
crate::document::UnitKind::Knowledge => "knowledge",
crate::document::UnitKind::Section => "section",
};
let metadata = match function {
Some(function) => serde_json::json!({
"mode": unit.mode,
"level": unit.level,
"path": unit.path,
"unit_id": unit.unit_id,
"unit_kind": unit_kind,
"anchors": anchors,
"module_id": module_id,
"nature": "unspecified",
"function_id": function.function_id,
"local_name": function.local_name,
"namespace": function.namespace,
@@ -236,6 +263,10 @@ pub fn build(
"level": unit.level,
"path": unit.path,
"unit_id": unit.unit_id,
"unit_kind": unit_kind,
"anchors": anchors,
"module_id": module_id,
"nature": "unspecified",
}),
};
let semantic_digest = function.map(|function| {
+34
View File
@@ -203,6 +203,8 @@ struct Hit {
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>,
}
@@ -633,6 +635,32 @@ impl<'a> Engine<'a> {
}));
}
}
// 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,
@@ -649,6 +677,8 @@ impl<'a> Engine<'a> {
matches: final_hit.matches.clone(),
score: (final_hit.score * 1_000_000.0).round() / 1_000_000.0,
callable,
location,
evidence,
related,
})
}
@@ -694,6 +724,10 @@ impl<'a> Engine<'a> {
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();
+33
View File
@@ -91,6 +91,39 @@ fn lexical_channel_finds_two_character_chinese() {
assert!(source.contains(hits[0]["snippet"].as_str().unwrap()));
}
#[test]
fn hits_return_a_stable_location_and_evidence_status() {
// Candidate location contract (issue #14/#12): a hit must carry the exact
// document-structure identity and source evidence, without re-parsing.
let root = sample_project();
let value = run(&root, query_args(&root, "牛顿"));
let hit = value["hits"]
.as_array()
.unwrap()
.iter()
.find(|hit| hit["location"]["path"].is_array())
.expect("a unit hit with a location");
let location = &hit["location"];
assert!(!location["path"].as_array().unwrap().is_empty());
assert!(location["unit_kind"].is_string());
assert!(location["mode"].is_string());
assert_eq!(location["nature"], "unspecified");
assert!(location["span"]["start"].as_u64().is_some());
assert!(hit["source"]["path"].is_string());
let evidence = &hit["evidence"];
assert_eq!(evidence["status"], "current");
assert!(evidence["source_digest"]
.as_str()
.unwrap()
.starts_with("sha256:"));
assert!(evidence["snapshot_digest"]
.as_str()
.unwrap()
.starts_with("sha256:"));
assert_eq!(value["schema"], "marqdo.knowledge.result");
assert_eq!(value["schema_version"], 1);
}
#[test]
fn fuzzy_channel_recalls_a_typo_query() {
let root = sample_project();