- 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
9.8 KiB
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
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
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:
modelowns the shared typed vocabulary (span, canonical key, node/edge/state kinds, digest helpers). One definition only; no parallel JSON dictionaries.documentnever writes SQLite and never renders output.graphnever reads the filesystem, SQLite or the network.storagenever parses Markdown and never runs the core CLI.querynever mutates stored graph facts; it has a read-only storage handle.compileris the single write-transaction orchestration point.cliowns 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,targetandnode_modulesare skipped. - Only
.mdand.mq.mdare 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
inputswith 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:
$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.
containsis a single-parent tree.references/imports/callsmay 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
externalnodes 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
FunctionIdalias). Canonical keys are UTF-8 percent-encoded canonical JSON arrays, never raw#/:://concatenation. - Source position:
source_digestplus 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
- Exact canonical address lookup (never fuzzy, never guesses).
- Lexical channel: FTS5 with CJK bigram pre-segmentation and weighted fields.
- Fuzzy channel: normalised 2/3-gram inverted index plus bounded edit distance over candidate titles/symbols.
- Optional semantic channel: OpenAI-compatible
POST /embeddings, explicit opt-in, vectors stored as float32 BLOBs and invalidated on config change. - Weighted Reciprocal Rank Fusion per search unit, then per node.
- Bounded graph expansion from high-ranked seeds (depth, relations, reverse,
node/edge budgets, decay) with
truncatedreported honestly. - 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 |