# marqdo-knowledge public contract Status: current contract for `0.1.0-beta.1` (first beta; 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.1", "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", "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.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. ## 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.