# 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 ```json { "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 ```text 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 `/.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 * `--exact` and `--semantic` conflict. `--slice` requires a unique exact seed; a fuzzy query returns candidates and requires a canonical id instead. * `--limit` 1..=100 (default 10); `--depth` 0..=8 (default 1). * `--kind` filters final hits only, after candidate/graph expansion. * `--relation` accepts `contains`, `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 ```json { "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", "role": "concept", "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). ```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. * `role` is the document role derived from existing public path conventions: `entry` for `index.mq.md`, `index`/`log` for the OKF reserved files at any level, `document` for other `.mq.md` files, `concept` for other `.md` files and `unknown` when no source path exists. It is information for agents (entry and navigation versus ordinary documents), not an execution or authority claim. * `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 { "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. | | path convention | hit `role` | `entry` (`index.mq.md`), `index`/`log` (OKF reserved), `document` (other `.mq.md`), `concept` (other `.md`); no new metadata syntax. | 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: ```sh "$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 (`inputs` table: 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 them `out_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.