chore: bootstrap marqdo-knowledge crate, CLI surface and architecture docs

- pin Rust 2021 / MSRV 1.89 and exact dependency versions
- add typed model vocabulary (UTF-8 spans, canonical JSON-array node keys,
  node/edge/state enums, digest helpers) with unit tests
- add deterministic diagnostics and unified error/exit semantics (0/1/2)
- add the three-command clap surface with strict argument validation
- record the single-derived-artifact decision, architecture overview and
  current public contract; STATUS lists real evidence only
This commit is contained in:
marqdo-knowledge committed 2026-11-25 22:24:51 +08:00
1 parent fbca63b972
commit 430f950631
19 files changed
+2945

No files matched your search

+49
View File
@@ -0,0 +1,49 @@
# Status
Last updated: 2026-11-25. Evidence-based; this file lists what the code does,
not what the design intends. Anything not listed as verified is **NOT RUN** and
must not be claimed as passing.
The development baseline is `marqdo-knowledge-development.md` (kept outside
this repository). Upstream Analysis baseline for integration is
`cflmy/marqdo-cli` `3.0.0-rc.4` (`4bbefc92449ee480c8a2c89b0308feb4cda8d0e7`),
contract `marqdo.analysis` revision 3. The original static audit in the
development specification refers to `e6066e6`; the current public boundary has
since been implemented upstream as ADR-0069, so this tool targets the current
revision-3 shape and rejects everything else.
## Capability matrix
| Area | State | Evidence |
|---|---|---|
| Repository scaffold, CLI surface, exit codes | implemented | unit tests in `src/cli.rs` |
| Discovery, snapshot, budgets | in progress | - |
| Plain Markdown projection | in progress | - |
| Analysis v3 adapter + semantic validation | in progress | - |
| Unified graph and reference resolution | in progress | - |
| SQLite schema, transactions, atomic publish | in progress | - |
| Compile command | in progress | - |
| Lexical / fuzzy / graph query, RRF | in progress | - |
| Slices | in progress | - |
| Incremental update | in progress | - |
| OKF v0.3 recognition and check | in progress | - |
| Semantic channel (OpenAI-compatible embeddings) | in progress | - |
| Packaging (`tool.json`, release script) | in progress | - |
| Performance / retrieval benchmarks | NOT RUN | no frozen dataset yet |
| Real-model semantic benchmark | NOT RUN | requires a pinned model revision not available in this environment |
| Cold install against a real `marqdo` binary | NOT RUN | - |
## Known limitations
* Linux x86_64 is the only release-candidate platform.
* The exact quality/performance gates of the development specification §16 are
not yet measured; no threshold is claimed.
## Reproduce
```sh
scripts/cargo.sh fmt --all -- --check
scripts/cargo.sh clippy --all-targets -- -D warnings
scripts/cargo.sh test
scripts/cargo.sh build --release
```
+37
View File
@@ -0,0 +1,37 @@
# ADR-0001: One derived SQLite artifact, one current contract
- Status: accepted (implementation baseline)
- Date: 2026-11-25
- Context: `marqdo-knowledge-development.md` §1, §7, §12, §17
## Decision
1. `marqdo-knowledge` persists exactly one knowledge artifact per root:
`.marqdo/knowledge.sqlite`. It is derived, rebuildable and private to the
tool. No `knowledge.yaml`, node manifest, JSONL graph, vector file or
separate knowledge IR is created or read.
2. The only machine input for Marqdo program semantics is the core CLI's current
public Analysis (`marqdo.analysis`, revision 3) produced by
`check ENTRY --emit PATH`. There is no second Analysis shape, version probe,
legacy reader or fallback parser.
3. The public CLI contract is exactly three business subcommands: `compile`,
`check`, `query`. No `init/search/graph/impact/export/serve` aliases.
4. Query never writes graph facts; `compile` is the only write path; `check`
never writes.
5. Schema changes are explicit and destructive: the tool rejects an old schema
revision and asks for `compile --rebuild`. There is no automatic migration.
6. Freshness is content-based: query compares the recorded input digests with
the current root and refuses to serve a stale snapshot unless the user
explicitly passes `--snapshot`.
## Consequences
* Deleting the database loses nothing; a rebuild is the only recovery needed.
* Incremental compilation must prove semantic equivalence to a full compile.
The implementation keeps a digest-guarded cache of normalised document facts
inside the database so that unchanged Analysis contexts are not re-invoked;
the cache is derived data and is verified on every use.
* Schema revision, Analysis revision and product version are independent
numbers. They are not bumped for cosmetic alignment.
* There is one producer and one validator for each boundary; retiring a shape
means deleting it, not keeping a compatibility branch.
+209
View File
@@ -0,0 +1,209 @@
# marqdo-knowledge architecture
Status: current design (implementation in progress; see `docs/STATUS.md`).
## 1. Scope
`marqdo-knowledge` is a separate CLI tool dispatched by `marqdo` as command
`knowledge`. It compiles an existing directory of Markdown and Marqdo documents
into one derived, rebuildable SQLite projection and answers exact, lexical,
fuzzy, graph and optionally semantic queries over it.
Non-goals are fixed by the development specification: no execution, no runtime,
no plugins, no foreign kernels, no proof/attestation, no knowledge server, no
second Markdown parser for executable semantics, no generated knowledge files.
The knowledge truth is always the original Markdown sources plus the resources
they explicitly reference. `.marqdo/knowledge.sqlite` is a derived artifact: it
may be deleted at any moment and fully rebuilt.
## 2. Data flow
```text
ROOT + options
-> discovery deterministic source snapshot (exact bytes, digests)
-> documents plain .md projection | Marqdo Analysis v3 adapter
-> graph one Node/Edge graph (contains/references/imports/calls)
-> storage one SQLite transaction + derived search indexes
-> query exact | lexical FTS5 | fuzzy grams | graph | semantic
-> render human Markdown or the machine JSON envelope
```
`compile` is the only writer. `check` never writes. `query` opens the database
read-only, verifies freshness and never recompiles implicitly.
## 3. Layers and dependency direction
```text
main -> cli -> compiler / query
compiler -> document -> (plain Markdown parser | core Analysis JSON)
compiler -> graph -> model
compiler -> storage <- query
query -> fuzzy / slice / semantic -> model + read-only storage
storage -> rusqlite + model
model and diagnostic depend on neither I/O nor SQLite
```
Rules:
* `model` owns the shared typed vocabulary (span, canonical key, node/edge/state
kinds, digest helpers). One definition only; no parallel JSON dictionaries.
* `document` never writes SQLite and never renders output.
* `graph` never reads the filesystem, SQLite or the network.
* `storage` never parses Markdown and never runs the core CLI.
* `query` never mutates stored graph facts; it has a read-only storage handle.
* `compiler` is the single write-transaction orchestration point.
* `cli` owns argv and rendering only; the compiler/query layers return
structured reports, they never print.
* The semantic client receives only explicitly selected snippets and the query;
it has no workspace access.
## 4. Source snapshot and discovery
* The root is canonicalised once. Directories are walked without following
symbolic links; `.git`, `.marqdo`, hidden entries, `target` and
`node_modules` are skipped.
* Only `.md` and `.mq.md` are knowledge documents. A root may also be a single
Markdown file (scope = that file; the root for the database is its parent).
* Files are read as exact bytes, validated as UTF-8, limited by per-file and
total budgets, and sorted by byte-wise relative path.
* Every input (document, manifest, lock, referenced local asset) is recorded in
`inputs` with its digest, so freshness and incremental invalidation compare
content, never mtime.
* Paths are validated segment by segment: no absolute path, drive/UNC prefix,
backslash, empty/`.`/`..` segment, NUL, or escape from the root. Link
fragments are percent-decoded exactly once.
## 5. Document projections
### 5.1 Plain `.md`
Parsed with the pinned CommonMark/GFM parser (`comrak = 1.0.0`, fixed
options: tables, footnotes, strikethrough, task lists, dollar math, front
matter). Line/column positions are converted to exact half-open UTF-8 byte
offsets. The projection produces headings, byte spans, link/image URLs,
front-matter metadata and extractable block text. `@exec` text in a plain
`.md` file is never executable.
### 5.2 `.mq.md`
Never re-parsed for program semantics. The tool invokes the core CLI once per
entry candidate:
```text
$MARQDO_BIN check <entry> --emit <private-temp-path>
```
and consumes the current `marqdo.analysis` revision 3 artefact as a closed
contract. It verifies the schema identity, project/module identities, every
`source_digest`, every span (range, UTF-8 boundary, module ownership), the unit
parent tree, anchors, functions, references states, calls and resources. A
module may be covered by several entries; it is merged only when identity and
source digest agree, otherwise compilation is blocked with
`knowledge.analysis_context_conflict`. The exact Analysis bytes are never
published as a knowledge artifact.
### 5.3 OKF v0.3
An optional document-layer convention, not a new format and not a project type.
Front-matter `type` turns a document/heading into an OKF concept identity;
`index.md`/`log.md` stay Native documents with navigation/history roles;
unknown keys are preserved as data and never change program semantics. `check
--okf` validates the supported OKF structure and link rules; it is not a
general attestation verifier.
## 6. Graph
One `Node` type with `NodeKind` (document, namespace, section, function,
statement, resource, external). One `Edge` type with `EdgeKind` (contains,
references, imports, calls), `EdgeOrigin` (document, analysis) and an explicit
resolution state (resolved, not_loaded, missing, ambiguous, external,
out_of_scope, invalid, dynamic, unresolved).
* A Marqdo unit and its function are the same node: the unit path is the node
key and the upstream FunctionId is an alias. Document roots map to the
document node; no second document node is created.
* `contains` is a single-parent tree. `references`/`imports`/`calls` may have
unresolved targets; the raw target and source span are always retained.
* Each occurrence of a repeated link is its own edge (identity includes the
source span), so a document with ten links to the same target keeps ten
locations.
* External URIs become `external` nodes and are never fetched. Missing,
ambiguous, out-of-scope, dynamic and unverified targets are reported as
states, never silently bound.
* At most these four relation kinds are stored. Similarity scores are search
signals, not edges.
## 7. Identity
* Logical identity: root-relative document path plus the upstream structured
unit path (or `FunctionId` alias). Canonical keys are UTF-8 percent-encoded
canonical JSON arrays, never raw `#`/`::`/`/` concatenation.
* Source position: `source_digest` plus half-open UTF-8 byte range. Human
line/column are presentation only.
* Snapshot identity: canonical input list, raw byte digests, relevant Analysis
context digests, lock/stdlib digests and compiler/index configuration. It
excludes absolute paths, wall-clock time and SQLite page layout.
## 8. Storage
A single SQLite file, `.marqdo/knowledge.sqlite`, with tables `build`,
`documents`, `nodes`, `aliases`, `edges`, `contexts`, `inputs`, `diagnostics`,
`search_units`, `search_fts` (FTS5), `grams` and optional `embeddings`.
`PRAGMA foreign_keys=ON` is set per connection; spans are checked; an unresolved
edge has a `NULL` target. All SQL uses parameter binding.
`compile` stages changes in a transaction (full rebuild stages a private
database and renames it into place) and only publishes after source recheck and
integrity checks. A failed compile never overwrites the last successful
artifact. Schema revision changes are rejected with an explicit rebuild
instruction; there is no automatic migration and no legacy reader.
Derived facts needed for a conservative incremental update (normalised document
facts + the Analysis context identity) are cached in the database and reused
only when the exact source digest and context signature still match. They are
an optimisation of derived data, not a second source of truth; deleting the
database loses nothing.
## 9. Query pipeline
1. Exact canonical address lookup (never fuzzy, never guesses).
2. Lexical channel: FTS5 with CJK bigram pre-segmentation and weighted fields.
3. Fuzzy channel: normalised 2/3-gram inverted index plus bounded edit
distance over candidate titles/symbols.
4. Optional semantic channel: OpenAI-compatible `POST /embeddings`, explicit
opt-in, vectors stored as float32 BLOBs and invalidated on config change.
5. Weighted Reciprocal Rank Fusion per search unit, then per node.
6. Bounded graph expansion from high-ranked seeds (depth, relations, reverse,
node/edge budgets, decay) with `truncated` reported honestly.
7. Slices: document (contains + references), execution (calls + imports),
hybrid; deterministic byte budget, original source text only.
Fuzzy/semantic recall may be approximate. Identity and binding never are.
## 10. Determinism and limits
* Same inputs and configuration produce the same logical digest and ordering
regardless of checkout path, clock or SQLite page layout.
* Finite budgets: 16 MiB per file, 512 MiB total source, 100,000 documents,
AST depth 256, 2,000,000 nodes and edges, 120 s per Analysis invocation,
query input 4 KiB, 200 candidates per channel, 200 graph nodes, 32 KiB
default slice. Every truncation is reported.
* Default execution is offline; only an explicitly enabled embedding endpoint
performs network I/O. No command executes knowledge.
## 11. Module map
| Path | Responsibility |
|---|---|
| `src/main.rs` | process entry and exit code only |
| `src/lib.rs` | minimal public surface; `run()` |
| `src/cli.rs` | argv, validation, human/JSON rendering |
| `src/compiler.rs` | discovery -> facts -> graph -> publish orchestration, incremental invalidation |
| `src/document/` | discovery, plain Markdown projection, Analysis adapter, OKF |
| `src/graph/` | identity, node/edge building, reference/call resolution |
| `src/storage/` | SQLite schema, transactions, read/write APIs, indexes |
| `src/query/` | search, fuzzy, semantic, fusion, graph expansion, slices |
| `src/model.rs` | shared typed domain values |
| `src/diagnostic.rs` | diagnostic codes and deterministic collections |
| `src/error.rs` | unified error and exit semantics |