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.
13 KiB
marqdo-knowledge public contract
Status: current contract for the 0.1.0-beta line (no stable-version claim). The normative
development specification is marqdo-knowledge-development.md; this file
records the exact contract this repository implements. Where the two differ,
the development specification wins and this file must be corrected in place —
there is never a second active contract.
1. Tool identity
{
"schema": "marqdo.cli-tool",
"schema_version": 1,
"name": "marqdo-knowledge",
"version": "0.1.0-beta.3",
"command": "knowledge",
"entrypoint": "bin/marqdo-knowledge",
"requires": {"api_revision": 1, "analysis": 3}
}
tool.json describes the release package; it is not a knowledge-base
configuration file. Launch through marqdo knowledge .... Direct invocation is
supported for development and tests with an explicit --marqdo-bin PATH
(or MARQDO_BIN). The tool never scans PATH for a guessed core binary.
2. Commands
marqdo knowledge compile [ROOT] [--exclude GLOB ...] [--rebuild] [--json]
[--embedding-url URL --embedding-model MODEL --embedding-revision REV
[--allow-remote-embedding]]
marqdo knowledge check [ROOT] [--okf] [--json]
marqdo knowledge query QUERY [--root ROOT] [--exact] [--kind KIND] [--limit N]
[--depth N] [--relation KIND ...] [--reverse]
[--slice document|execution|hybrid] [--format markdown|json] [--snapshot]
[--semantic] [embedding options]
| Command | Semantics |
|---|---|
compile |
Initialise or incrementally update .marqdo/knowledge.sqlite. Publishes only on success. --rebuild requests an explicit full replacement. |
check |
Static check without executing or writing the knowledge base. Validates Analysis input, diagnostics and, when a database exists, its structure and freshness. --okf additionally validates the supported OKF rules. |
query |
Read-only, offline by default. --exact restricts to exact identity/unique-name resolution; --snapshot explicitly permits a stale snapshot; --semantic requires the embedding channel. |
Database location is always <ROOT>/.marqdo/knowledge.sqlite. Parent directories
are never searched for a database. query never compiles implicitly.
2.1 Exit codes
| Code | Meaning |
|---|---|
| 0 | success (including zero search hits) |
| 1 | invalid knowledge, definite broken link, failed check |
| 2 | usage, protocol mismatch, missing/old database, I/O, hard resource budget |
2.2 Argument rules
--exactand--semanticconflict.--slicerequires a unique exact seed; a fuzzy query returns candidates and requires a canonical id instead.--limit1..=100 (default 10);--depth0..=8 (default 1).--kindfilters final hits only, after candidate/graph expansion.--relationacceptscontains,references,imports,calls.- Unsupported kind/relation/format values are usage errors.
- Embedding options are all-or-nothing and are never read from the source tree.
The API key comes from the environment variable
MARQDO_KNOWLEDGE_EMBEDDING_API_KEY; it is never stored in the database, logs or output.
3. Machine output
All machine output uses one envelope schema per boundary; there is no JSONL stream and no per-query bespoke format.
3.1 Success
{
"schema": "marqdo.knowledge.result",
"schema_version": 1,
"command": "query",
"success": true,
"snapshot_digest": "sha256:...",
"current": true,
"query": "归一话",
"channels": ["lexical", "fuzzy", "graph"],
"truncated": false,
"hits": [
{
"id": "opaque-canonical-id",
"kind": "function",
"title": "归一化检查",
"source": {"path": "state.mq.md", "digest": "sha256:...", "span": {"start": 100, "end": 180}},
"snippet": "原文片段(非生成文本)",
"matches": [{"channel": "fuzzy", "field": "title"}],
"score": 0.031,
"callable": {"function_id": "upstream canonical id", "signature": {}},
"related": []
}
],
"diagnostics": [],
"payload": {}
}
compile and check use the same envelope with command set accordingly and a
command-specific payload. callable is present only for functions whose
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).
"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:..."
}
locationis 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_idstaynullwhen the document has no Analysis module identity; they are never fabricated.anchorsare navigation names, not identities or execution rights.natureis the authority/nature marker frommarqdo#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.statusiscurrentonly when the database input manifest still matches the source snapshot. A--snapshotquery or a stale database reportsstale; the result envelope'scurrentflag is authoritative for the whole result.source/source.spanremain the exact snippet location;locationis 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[].relationkeeps the public vocabulary (contains,references,imports,calls). A Markdown link is areferencesrelation and is never rewritten into an import or execution dependency.
3.2 Error
{
"schema": "marqdo.knowledge.error",
"schema_version": 1,
"command": "query",
"success": false,
"error": {"code": "knowledge.database_missing", "message": "...", "hints": [], "exit_code": 2}
}
Machine mode never emits partial JSON on stdout. Diagnostics are also reported
on stderr as human lines with stable knowledge.* codes.
3.3 Semantic mode
--semantic is the only network path. It requires compile-time and query-time
options to match exactly (sanitised endpoint, model, revision, dimension); the
API key is read from MARQDO_KNOWLEDGE_EMBEDDING_API_KEY and is never stored or
printed. Remote endpoints must be HTTPS and require
--allow-remote-embedding; loopback HTTP is allowed for a local compatible
service. A failed or incomplete embedding run publishes nothing and leaves the
previous artifact intact. Semantic results are explicitly marked in channels;
their quality depends on the user-supplied model and is not a correctness score.
4. OKF (document layer)
OKF v0.3 is recognised from front matter only: index.md/log.md are reserved
roles at every level, other documents with a non-empty type are concepts
(concept id = bundle-relative path without .md, mapped to the document node),
unknown keys/types are preserved and tolerated, and resource is the only
metadata field treated as a path. Compile has no --okf flag and keeps Native
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:
"$MARQDO_BIN" check ENTRY --emit ARTIFACT
The artifact must identify itself as marqdo.analysis revision 3, producer
marqdo with markdown profile marqdo.md.v1, and must pass closed-schema and
semantic validation (module/unit/anchor/function/reference/call invariants,
source digests, UTF-8 spans, tree shape). Any other revision, missing field,
unknown required kind, digest mismatch or invariant violation is rejected with
knowledge.analysis_invalid/knowledge.analysis_unsupported; there is no
fallback parsing. Plain .md files are parsed by this tool with the pinned
CommonMark/GFM/footnote options and never gain executable semantics.
5. Databases and freshness
Incremental compiles reuse digest-guarded normalised facts for unchanged
documents and never re-run Analysis when only plain Markdown changed. Any
.mq.md/manifest/lock/core-identity change re-runs Analysis conservatively. The
projection rows are then rewritten and committed in one transaction, so
incremental semantics equal a full compile; the write-volume benchmark is not
yet measured.
The database stores one build row with:
- application id and schema revision;
- compiler/tool/profile identity and index configuration;
- scope and options;
snapshot_digest(logical identity of the exact source snapshot);- input manifest (
inputstable: path, digest, size).
On open, the tool verifies the application id, schema revision, required
tables/columns and PRAGMA quick_check. A schema mismatch or foreign database is
rejected with a rebuild instruction; nothing is migrated or overwritten. A
query whose recorded inputs no longer match the root exits 2 with
knowledge.database_stale unless --snapshot is supplied, in which case the
result states current: false and the snapshot digest.
5.1 Known limitations
- OKF bundle-root absolute links are only resolved by
check --okf; compiled Native knowledge reports themout_of_scope. - Single-character CJK queries use a bounded title/symbol/body probe and may be truncated; they are not exhaustive.
- No schema migration: a schema revision change requires
compile --rebuild. - Semantic retrieval quality requires a real model; only protocol, validation, storage and fusion are covered by this repository's tests.
6. Vocabulary
Resolution states: resolved, not_loaded, missing, ambiguous, external,
out_of_scope, invalid, dynamic, unresolved. Node kinds: document,
namespace, section, function, statement, resource, external.
Relation kinds: contains, references, imports, calls; origins are
document or analysis.
7. Security defaults
- No execution: no
run/call, plugin loading, provider, foreign kernel, attester, HTTP document fetch, shell or script execution. - Offline by default. Only an explicitly configured embedding endpoint performs
network I/O; non-loopback endpoints require TLS and
--allow-remote-embedding. - Filesystem scope is the compiled root. Symlinks are not followed; path traversal, absolute paths, drive/UNC paths and NUL bytes are rejected. Referenced binary assets are recorded (path/size/digest within budget) and never indexed as text.
- Logs and diagnostics never contain source text, credentials or machine absolute paths.