knk
A C++20 embedded bitemporal assertion store with an append-only log as the source of truth
A C++20 embedded bitemporal assertion store with an append-only log as the source of truth — the persistent core for conversational, temporal, and provenance-aware knowledge systems. The primitive isn't a row, a document, or a graph edge. It's an Assertion: a versioned, temporally-scoped claim about the world — carrying valid_from/valid_to (when it's true in the world), observed_at (when the kernel learned it), confidence, status, and supersedes_id/retracts_id links back to whatever it corrected or withdrew. The assertion log is append-only: nothing is ever overwritten in place.
Summary extracted from the README.
knk — Knowledge Kernel
A C++20 embedded bitemporal assertion store with an append-only log as the source of truth — the persistent core for conversational, temporal, and provenance-aware knowledge systems.
What it is
The primitive isn't a row, a document, or a graph edge. It's an Assertion: a versioned,
temporally-scoped claim about the world —
subject --predicate--> object
carrying valid_from/valid_to (when it's true in the world), observed_at (when the kernel
learned it), confidence, status, and supersedes_id/retracts_id links back to whatever it
corrected or withdrew. The assertion log is append-only: nothing is ever overwritten in place.
Corrections and removals are new records that supersede or retract earlier ones, so the kernel
never loses the history of how its knowledge changed.
Key capabilities
- Bitemporal queries —
current,valid_at,known_at,valid_at_known_at, and full valid-time/observed-time/commit-history timelines per subject/predicate. - Durable, recoverable storage — a segmented, checksummed, fsync'd append-only log with crash-tolerant recovery, persistent indexes, and explicit snapshots for fast restart.
- Batch commits —
commit_batchappends many assertions under a single durability boundary (one fsync per log for the whole batch, not per assertion), each entry keeping its own valid time, returning the new ids in input order;commit_batch_by_nameis the same from names and literals instead of ids, andrecord_provenance_batchattaches provenance to a whole batch under one boundary too. - Batch reads —
entity_name_batch,entity_value_batch,predicate_name_batch, andprovenance_for_batchresolve many ids in one call, answering in input order with anullslot wherever the single resolver would answernull. - Shaped queries —
querytakes a reified, typed query IR (not SQL): subject/predicate/object, a valid-time point, an observed-time window, open-endedness, an explicit status set, deterministic ordering and paging, in any combination. Every single-purpose read above is expressible as one, and results are bounded and report whether they were truncated. - Filters and projection — queries carry a filter tree (ordered comparisons, comparisons against
an object's interned value, and
and/or/not), and can resolve catalog names for the returned page in the same call, so rendering results needs no second round trip. - Aggregation —
aggregateanswerscount/count_distinct/sum/min/max/avgover the same selection surface, grouped by subject, predicate, object, status, or a fixed-width time bucket, streaming rows into groups rather than materializing them. - Read-only opens —
mcp_server <root> --read-only(orOpenMode::ReadOnly) queries a live storage root alongside the writing process, taking no lock and writing nothing, so an external analytics client can read without stopping the writer. - Columnar projection — a memory-mapped, column-per-field projection of the log, maintained in lockstep with every commit and rebuilt from the log whenever it cannot be verified: derived state that the scan-oriented query paths are built on.
- Vectorized scans — queries without an applicable index filter column-at-a-time and materialize only the page they return, which is both faster and provably identical to the row path: every randomized test query is answered through an index, the columnar scan, and the row scan, and all must agree.
- Cost-based planning — every usable source is costed on exact row counts and the cheapest is taken,
so an index is used when it is selective and skipped when it is not;
explain_queryreturns the plan, its alternatives, and why each was rejected, without running the query. - Columnar result handoff —
query_spillwrites a large result to disk as plain fixed-width columns plus a dictionary of the ids it mentions, and returns a descriptor; a reader is about twenty lines (tools/read_spill.py), and a read-only kernel can produce one without writing to the store. - As-of reconstruction —
as_of_commit/as_of_observedanswer a query against the store as it stood at an earlier point: rows committed or observed later are invisible, and every row's status is what it was then, so "what did we believe at close" stops changing every time a fact is corrected. - Cursor paging and budgets —
next_cursorresumes a walk strictly after the last row returned, so paging cannot repeat or skip rows while another process commits, and stays as cheap at page 100 as at page 1;max_rows_examinedandmax_groupsbound a query's work and fail with a structured error naming the budget rather than with a slow answer. - Discovery —
describe_predicatesanddescribe_corpustell a caller which predicates a store actually uses and what shape it is, so an agent can build a query instead of guessing names. - Entity/predicate catalog — idempotent name and typed-literal interning
(
intern_entity/intern_value/intern_predicate), plus a payload store for large content (documents) addressed by id. - Provenance & audit —
record_provenance/provenance_for("which source produced this claim?"),explain(walk a supersession/retraction chain to its root), andfind_conflicts(overlapping active assertions for the same subject/predicate). - Hypotheses & bounded graph traversal — a labeled
Hypothesisstatus for machine-suggested facts, plus small, capped-hopneighbors/co_occurring_predicatesfeature extraction for an external prediction/causal-inference tool. - Entity merge & archival — one-way deduplication redirects (
merge_entities) and segment archival/compaction (archive_segments_before) — pruning, never deletion. - A closed command layer + local MCP server — every public operation is reified as a
KernelCommand/KernelResultpair, and a stdio Model Context Protocol server (mcp_server) exposes each one as a tool, so an external agent process can call into the kernel without linking against the C++ API.
See AGENTS.md for the full design spec, architectural invariants, and roadmap this
project follows.
Quick start
cmake -S . -B build # configure
cmake --build build # build the kernel lib, kernel_demo, mcp_server, and all tests
ctest --test-dir build --output-on-failure # run the test suite
Each test binary is also a plain executable you can run directly, e.g. ./build/knowledge_kernel_tests.
A minimal example
#include "kernel/knowledge_kernel.hpp"
using namespace knk;
KnowledgeKernel kernel(StorageConfig{"/path/to/storage"});
// Commit a fact from names/literals -- interning is idempotent, so this is safe to call again.
kernel.commit_by_name("Alice", "works_at", Value::of_text("Acme"),
/*valid_from=*/1704067200, /*valid_to=*/OPEN_ENDED,
/*observed_at=*/1719792000, /*confidence=*/0.95);
// Ask what we currently know about Alice, by name.
for (const Assertion &fact : kernel.current_by_name("Alice")) {
// fact.subject / fact.predicate / fact.object are EntityId/PredicateId/EntityId
}
examples/knowledge_kernel_demo.cpp is a guided, runnable tour of the full API (./build/kernel_demo);
examples/agent_workflow_demo.cpp chains several features together the way a real caller would.
Architecture
Layering is strict and one-directional:
KnowledgeKernel query semantics + public commit/query API
IndexManager in-memory and persistent indexes, keyed by AssertionId only
StorageEngine coordinates durable storage (owns AssertionLog)
AssertionLog append/read raw assertion records; no semantics
AssertionLog/StorageEngine never know about bitemporal semantics or "current" state;
IndexManager returns ids only, never full assertions — the kernel resolves them. The log is
always the source of truth: every other in-memory structure is rebuildable by replaying it.
MCP server
./build/mcp_server <storage-root>
A subprocess speaking newline-delimited JSON-RPC 2.0 over its own stdin/stdout — one MCP tool per
KnowledgeKernel operation. See docs/mcp_server.md for the full tool list,
an example JSON-RPC session, and how to point a real MCP client at it.
Project status
Phases 1–8 of the roadmap in AGENTS.md are complete: in-memory
temporal model, storage engine, persistent indexes, segmented/checksummed storage internals,
entity/predicate catalog + payload store, provenance + the command layer, hypotheses + bounded
graph traversal, and entity merge + archival.
The query-engine arc, Phases 10–19, is also complete: the query IR, filters and name resolution,
aggregation, read-only opens, the columnar store, vectorized execution, cost-based planning and
explain_query, columnar result handoff, cursors/budgets/discovery, and as-of reconstruction.
Phase 9 (general performance work — SIMD, lock-free readers, etc.) remains explicitly gated behind a
demonstrated bottleneck from real usage; a benchmark harness and baselines exist (see
docs/benchmarks.md), and the optimization work that has happened was
benchmark-driven and confined to the query engine's own phases.
Further reading
AGENTS.md— the authoritative spec: architecture, assertion semantics, storage rules, roadmap, testing requirements, and style.docs/query_semantics.md- what each query method returns and excludes.docs/storage_format.md— on-disk format and durability model.docs/mcp_server.md— MCP tool reference and protocol usage.docs/benchmarks.md— benchmark methodology and baseline numbers.CONTRIBUTING.md— how to propose a change.