OKF4net

A zero-dependency .NET (C#) implementation of the Open Knowledge Format
(OKF) v0.2 —
Google's open, human- and agent-friendly format for representing knowledge as
a directory of markdown files with YAML frontmatter.
> OKF is intentionally minimal: "if you can cat a file, you can read OKF; if
> you can git clone a repo, you can ship it." This project honors that
> spirit — it is implemented entirely on the .NET base class library, with
> no third-party dependencies (it includes its own YAML-subset parser,
> markdown link scanner, directory walker, and CLI argument parsing).
>
> OKF4net is an independent, zero-dependency .NET implementation of the Open
> Knowledge Format, built from the OKF v0.2 specification. It is backed by an
> extensive test suite, including snapshot comparisons of the CLI's output and full-projection
> tests of its machine outputs (see tests/fixtures/). Everything it builds is
> LGPL-3.0-or-later; see NOTICE.
📖 Documentation & project site → jchable.github.io/okf4net —
a guided project overview, getting-started walkthroughs, and developer docs:
getting started ·
guides ·
CLI reference ·
library reference ·
MCP ·
spec mapping.
This README is the technical reference; the site is the friendlier entry point
for newcomers.
Tutorials (in this repository, every step run against the current code):
library users — write, index, load and
validate a bundle through the provider API ·
agent builders — expose a bundle through
OKF4net.Agents and okf-mcp.
> Want to contribute? OKF4net is a young, welcoming project with a clear
> roadmap and issues labelled
> good first issue.
> No prior OKF knowledge required — see Contributing & roadmap.
What OKF is
- A bundle is a directory tree of UTF-8 markdown files (the unit of
distribution).
- A concept is one markdown document: a YAML frontmatter block delimited
by
---, followed by a markdown body.
- A concept id is the file's path within the bundle with
.md removed
(tables/users.md → tables/users).
- Concepts cross-link via ordinary markdown links — absolute
(
/tables/users.md, bundle-relative) or relative (./other.md).
index.md files provide directory listings for progressive disclosure;
log.md files record date-grouped change history. Both are reserved
filenames.
- The only hard requirement for conformance is a non-empty
type field on
every concept; consumers must otherwise be permissive (unknown types, unknown
keys, broken links, and missing optional fields are all tolerated).
See mapping to the spec below for the section-by-section
mapping, or the longer
What OKF is page on the site.
Projects & packages
OKF4net ships as several projects. The core library is the foundation; each
other project layers a specific integration on top and points back to it.
| Project | NuGet package | Responsibility | Deep dive |
|---|
OKF4net | OKF4net | Zero-dependency core library: parse, validate, index, graph OKF bundles. | Library overview |
OKF4net.Cli | OKF4net.Cli (the okf dotnet tool; also Native AOT okf binaries) | The okf command-line tool (validate/audit/verify/info/index/graph/parse/fmt). | As a CLI |
OKF4net.Render | — (Native AOT okf-render binary, no PackageId) | Standalone CLI: generates a browsable HTML site from a bundle. | As a CLI |
OKF4net.Viewer | — (ships inside the okf-render binary, not packed by release.yml) | Static HTML site generation for a bundle; backs okf-render. | As a CLI |
OKF4net.Agents | OKF4net.Agents | Microsoft Agent Framework tools + OkfContextProvider (context & memory). | Microsoft Agent Framework |
OKF4net.Catalog | OKF4net.Catalog | Catalog of OKF bundles (local or any provider): catalog.json + resolver. | Local catalog · README |
OKF4net.Catalog.Hosting | OKF4net.Catalog.Hosting | IServiceCollection integration (AddKnowledge) for the catalog. | README |
OKF4net.Providers.EmbeddedResources | OKF4net.Providers.EmbeddedResources | A bundle shipped inside your assembly: the OkfBundle MSBuild item and a read-only provider; BCL only. | README |
OKF4net.Providers.S3 | OKF4net.Providers.S3 | A bundle in Amazon S3 or an S3-compatible store (read-only, async; depends on AWSSDK.S3). | README |
OKF4net.Mcp | OKF4net.Mcp | Local MCP server exposing an OKF bundle to Claude Desktop / Claude Code. | Use OKF in Claude (MCP) · README |
OKF4net.Attestation | OKF4net.Attestation | Host-plugged §10 attested-computation orchestration (bind → execute → attest). | Attested computation · README |
OKF4net.Attestation.Containers | — (not packed by release.yml; needs a container engine on PATH) | Runs a bundle's sanctioned script/SQL and its attester in real containers (Docker/Podman/nerdctl), never reimplemented in C#. | README |
Library overview
| Type / namespace | Responsibility |
|---|
OKF4net.Yaml.YamlValue / YamlMapping | A YAML-subset value/mapping model for frontmatter |
OKF4net.Yaml.YamlValue.Parse / YamlEmitter | Parser entry point and emitter for the same YAML subset |
OKF4net.OkfDocument | Frontmatter + body; parse / serialize / validate (§4) |
OKF4net.Frontmatter | Typed accessors over an order-preserving mapping (§4.1) |
OKF4net.ConceptId | ConceptId ↔ path conversion and segment validation (§2) |
OKF4net.Actor / Trust / Provenance / Lifecycle | Provenance, trust, and lifecycle value types and parsing (§5, §7) |
OKF4net.LinkScanner | Markdown link extraction, classification, legacy citations (§6.1, §13.1) |
OKF4net.Bundle | Bundle.Load — walk a tree, build the concept graph + backlinks (§3, §6) |
OKF4net.IndexGenerator | Generate index.md directory listings (§8) |
OKF4net.ChangeLog | Parse / build log.md update histories (§9) |
OKF4net.BundleValidator | §11 conformance checking with severity-tagged diagnostics |
The split follows the OKF reference implementation's bundle/ package
(document.py, index.py, paths.py) so behaviour stays spec-compatible:
the document parser, validator, and index generator are verified by an
extensive test suite, including snapshot comparisons of the CLI's output.
Design choices
-
Frontmatter preserves everything. Rather than deserializing into a fixed
type (which would drop producer-defined keys), Frontmatter keeps the full
ordered mapping and layers typed getters (Type, Title, Tags, …) on
top. This satisfies the spec's requirement that consumers preserve unknown
keys when round-tripping.
-
Permissive loading. Bundle.Load never aborts on a bad concept file; it
collects parse failures in ParseProblems and keeps going. Broken
cross-links are retained as graph edges to non-existent concepts.
-
Two levels of validation. OkfDocument.ValidateConformance() enforces
only what §11 requires (a non-empty type). OkfDocument.Validate() is the
stricter producer-side check: type, title and description
(Frontmatter.RequiredKeys). timestamp is a legacy §13.1 field since the
v0.2 bump and is not required.
-
A documented YAML subset. Real OKF frontmatter is scalars, lists, and
shallow maps. The parser handles block/flow collections, quoted/plain
scalars, |/> block scalars, and comments. It rejects, with a
YamlParseException giving the line and naming the feature, the YAML features
that never appear in frontmatter:
- anchors (
&name), aliases (*name) and tags (!name, !!type) at the
start of an unquoted node: a block key or value, a sequence item, a node on
its own line, or a flow item or key;
- directives, meaning a line starting at column 0 with
% (%YAML 1.2);
- document markers, meaning a line starting at column 0 with
--- or ...
followed by the end of the line, a space or a tab (..., --- x, ... # end);
- an indented
--- line (spaces or tabs, then ---, then optional spaces or
tabs) anywhere except inside |/> block-scalar content, reported as a
mistyped frontmatter fence. Through OkfDocument.Parse, that message also
gives the file line;
- text after a closing quote other than a
# comment (k: "a" b).
A quoted scalar ("*a"), an indicator later in a plain scalar (a & b,
50%), a value starting with % (k: %foo), block-scalar content and a plain
scalar's continuation lines stay text. Constructs the subset does not parse
as YAML structure are read as plain strings, so an indicator inside them is not
detected: compact nested sequences (- - *a, k: - *a), flow-collection keys
([*a]: v) and ? complex keys (? *a, {? *a : b}).
The frontmatter fences themselves are --- at column 0, optionally followed
by spaces or tabs (§4). An indented --- is not a fence. On line 1 it means
the file has no frontmatter, which okf validate flags with a warning next to
the missing-type error. Inside the frontmatter it is the parse error above,
except as block-scalar content.
Usage
As a library
A concern-by-concern API walkthrough lives in the
library docs on the site,
and the library users' tutorial builds a
bundle end to end with the asynchronous provider API; below is the short
version.
using OKF4net;
var bundle = Bundle.Load("./my_bundle");
Console.WriteLine($"{bundle.Count} concepts");
// Conformance check (§11).
var report = BundleValidator.Validate(bundle);
if (report.IsConformant)
{
Console.WriteLine($"conformant with OKF v{OkfSpec.Version}");
}
// Traverse the cross-link graph.
var id = ConceptId.Parse("tables/orders");
foreach (var link in bundle.LinksFrom(id))
{
Console.WriteLine($"{id} -> {link.Target} (exists: {link.Exists})");
}
foreach (var backlink in bundle.Backlinks(id))
{
Console.WriteLine($"cited by {backlink}");
}
Parsing and round-tripping a single document:
using OKF4net;
var doc = OkfDocument.Parse("---\ntype: Metric\ntitle: DAU\n---\n\n# Body\n");
Console.WriteLine(doc.Frontmatter.Type); // "Metric"
doc.ValidateConformance(); // throws DocumentValidationException on failure
// Serialize() preserves frontmatter key order and the body.
var text = doc.Serialize();
Reading and appending to a bundle's log.md change history (§9):
using OKF4net;
var log = ChangeLog.Parse(File.ReadAllText("./my_bundle/log.md"));
foreach (var day in log.Days) // newest first, by convention
{
foreach (var entry in day.Entries)
{
Console.WriteLine($"{day.Date} {entry.Kind}: {entry.Text}"); // Kind is null without a **bold** marker
}
}
// Appending goes through the writer, not through File.WriteAllText: it writes
// through the bundle's provider, under the write lock, conditioned on the
// version it read, and throws BundleReadOnlyException over a read-only provider.
// (ChangeLog, LogDay and LogEntry remain the immutable model to parse and render.)
var writer = new BundleConceptWriter("./my_bundle");
Console.WriteLine(writer.AppendLog("Update", "Documented the refunds table."));
Loading through a provider
Bundle.Load(string root) is now an overload over the default
FileSystemBundleProvider (it still throws BundleLoadException for a root
that is not a directory, before delegating). A host can load through any IBundleProvider
(OKF4net.Providers) — a key space of objects, read-only unless the provider
declares Capabilities.CanWrite — with await Bundle.LoadAsync(provider, new BundleLoadOptions { Limits = …, KeyPolicy = … }, ct). The provider contract is
asynchronous at the I/O edges (ValueTask, IAsyncEnumerable, a required
CancellationToken); queries on the loaded image stay synchronous. A provider
whose operations always complete before they return says so with
Capabilities.CompletesSynchronously (the filesystem provider does): only such a
provider serves the synchronous entry points (Bundle.Load(string), the writer's
and the index generator's string overloads, BundleValidator.Validate), which
never wait — a pending read is cancelled and the call throws
InvalidOperationException naming the async overload, and a synchronous write is
refused before any I/O starts. LoadAsync reads the concepts with at most
BundleLimits.MaxConcurrentRequests reads in flight, and reports the failing key
of the smallest rank whatever finished first. Every image reports the memory it
takes as an estimate, Bundle.EstimatedMemoryBytes: a linear model over the size
of the concept objects read and the links they hold, calibrated against retained
bytes. It is an approximation, not a heap measurement. A host can bound it with
BundleLoadOptions.MemoryCeilingBytes (no ceiling by default). A load that would
exceed the ceiling is refused with BundleMemoryCeilingExceededException, inside
the BundleLoadException, carrying the ceiling and the estimate. The refusal
comes before any read when the sizes the listing declares already exceed it,
otherwise as soon as the running estimate crosses it, never after loading
everything. The ceiling bounds one image: during a refresh the previous image is
still held, so the peak can reach twice the ceiling. A BundleHandle whose reload
is refused keeps serving its previous image, flagged stale. Keys are validated as a tree
under the Native policy by default: the loader refuses only what the
provider's storage itself cannot hold or would alias (OKF §11 imposes no naming
constraint), so Orders.md beside orders.md (on any volume that holds
both) or a decomposed café.md load as they always did, and so does con.md
on every OS: Windows 11 creates and opens such reserved device names through
ordinary APIs (git refuses them), so the default loads them with a
KeyNotPortable warning and Strict refuses them. The Windows native set keeps
only what aliases another name (a trailing dot or space, a character Windows
forbids) and the file/directory conflict. Sibling collisions are not a native rule on any OS:
the provider matches stored names exactly, so no key opens another key's
object. A name the portable
profile would refuse is listed in Bundle.PortabilityIssues and reported by
okf validate as a KeyNotPortable warning (the name is not portable: …).
Strict is the opt-in portable profile, for hosts that must produce or
consume bundles that survive any filesystem: no Windows reserved names, no
trailing dot, no case- or Unicode-form-colliding siblings, NFC names only (a
quick check), no file that is also a directory. FileSystemBundleProvider
always matches the stored name exactly, on every OS; a host that wants
colliding siblings refused at load rather than reported adds
additionalConstraints: BundleKeyConstraints.CaseInsensitiveCollisions (or
UnicodeFormCollisions). Default bounds, finite but
out of reach of real bundles: 256 MiB per object, 10 000 000 entries, depth
1 024 (every listed name counted, node_modules included), keys of 1 024
bytes; hosts reading untrusted storage should lower them. The filesystem
walk is recursive and needs roughly 0.6 KB of stack per level, so the default
depth takes about 0.6 MB: a host that runs Bundle.Load over untrusted storage
on a thread of 512 KB or less should lower MaxDepth.
Every rejected .md name is a Bundle.ParseProblems entry
(bundle.DisplayPath(problem) gives the path to print; the obsolete
ParseErrors projects the same list); other rejected names are skipped silently. The
filesystem provider is writable (see "Writing through a provider" below); no
other provider is writable: OKF4net.Providers.EmbeddedResources (see "A bundle
inside your assembly" below, #141) and OKF4net.Providers.S3 (see "A bundle in
S3" below, #142) serve a bundle read-only.
The historical members Bundle.TryResolveResource and
Bundle.ReadResourceText(string) still resolve through the OS filesystem, so
they apply neither the key policy, nor the rejected-key guard, nor the
exact-case and backslash rules; they are obsolete (a warning naming
TryResolveResourceKey and ReadResourceText(BundleKey), removed with #152),
and no reader in this repository uses them any more
(AttestationOrchestrator.Capture, OkfBundleTools and the validator read
through the key-based members). The other path-based members of Bundle
(Root, IndexFiles, LogFiles, ParseErrors) and the BundleRoot of
BundleConceptWriter and OkfBundleTools are obsolete in the same way;
Concept.Path, Diagnostic.Path and AuditFinding.Path are not: each is the
display path of its object, set beside the Key the load gave it (a
Diagnostic about a refused name, or a hand-built finding, has a Path and no
Key).
Writing through a provider
provider.Write(key, bytes, condition) stores one object atomically if its
condition holds — BundleWriteCondition.None, MustNotExist, or
IfMatch(version) with the version a Read returned — and returns the new
version; provider.Delete(key, condition) removes one. A key space has no
directories: a write creates the missing prefixes, and a delete leaves empty
directories behind, which hold no key. A provider whose Capabilities.CanWrite
is false, or the view provider.AsReadOnly() returns, throws
BundleReadOnlyException before attempting anything. A condition that does
not hold throws BundleWriteConflictException and changes nothing.
FileSystemBundleProvider writes the bytes to a temporary
.okf-write-<32 hex>.tmp beside the target, flushes it to stable storage,
then checks the confinement boundary, the path (no symlink or junction, the
exact stored names) and the condition (on the SHA-256 of the stored bytes)
again under a per-object lock, and commits with File.Replace or, for a new
object, File.Move without overwrite. On Unix a replacement's temporary is
owner-only until it takes the target's mode, and a read-only target is
refused as before; only IfMatch reads the target. What a write needs: the
right to create files in, and rename within, the target's directory — more
than the old in-place File.WriteAllText, which needed only the right to write
the target. In a directory the process cannot create files in (mode 0555 on
Unix; on Windows an ACL denying it that right) every write is refused with the
raw access error, which names the .okf-write-*.tmp it could not create
(okf verify, okf index and the writer's methods exit 1 or return
Error: Access to the path '…/.okf-write-….tmp' is denied.), the object
unchanged and no temporary left; on Unix, in a sticky directory shared between
users (like /tmp), a file owned by another user cannot be replaced either. A
delete needs the right to write the object's directory too (an unprivileged
process in a 0555 directory gets the access error, the file kept). There is no in-place fallback — it would reopen the torn writes of #157 — so a
bundle in a directory its writer cannot create files in is not a supported
deployment for writes. What this promises:
- Crash or I/O error mid-write: never a part of either content: the object
holds its whole old content or its whole new content, or (Windows,
ReplaceFile error 1176 or 1177) no object under the key while the new
content is kept in the temporary.
- Power loss: the old content, the new content, or for a new object no
object at all — the directory entry is not flushed (.NET has no API for
it).
- Concurrent readers: never a part of the new content. On Unix the commit
is a
rename. On Windows ReplaceFile can, for a moment, make a reader
find no object under the name or meet a sharing violation; Read retries
both a few times, which narrows that moment without removing it.
- A replacement Windows refuses without effect (
ReplaceFile error 1175,
or a sharing violation) is made again, at most three times in all, then
fails with BundleWriteNotCommittedException, the object unchanged.
- Other processes: a condition is checked atomically with the replacement
within one process only (the lock is an in-process lock); between the last
check and the commit another process can still write the same object, which is
then overwritten although its caller was told it was committed (#178, the
tracked follow-up; there is no cross-process lock yet). Measured in the review
of this change, with two processes each making 150
AppendLog /
AppendToConceptAtomic appends to one bundle: on Linux up to 100 of 297
appends reported committed were lost; on Windows 17 were lost, with
ReplaceFile errors 1176/1177 reported as unknown outcomes, the log
momentarily absent, and .okf-write-*.tmp files left behind by ordinary
contention. The old in-place writer lost more entries in the same Windows
test (127 + 136 reported committed, 83 + 89 present) but never left a
temporary. Do not run two processes writing the same objects of one bundle
where an append must not be lost.
A write whose outcome cannot be established (BundleWriteOutcomeUnknownException,
for instance Windows ReplaceFile error 1176, which can leave no object
under the key) keeps its temporary: it may be the only copy of the new
content. So does a process crash between the temporary's creation and the
commit, so can a failed write whose temporary could not be removed safely, and
on Windows so can ordinary contention between two processes writing one object
(the same ReplaceFile errors, see "Other processes").
okf validate ignores such a file (it is not .md), but it counts
toward the entry bound and an empty-directory check sees it; look for
.okf-write-*.tmp files and remove them by hand once you have checked them.
BundleConceptWriter writes concepts through a provider:
new BundleConceptWriter(provider, options: loadOptions) (the string
constructor builds a FileSystemBundleProvider over the directory). Give it
the BundleLoadOptions the bundle is loaded with: it checks every key under
that policy before writing, and refuses a creation that would make the tree
invalid under it — a concept file on the new key's path, objects under it,
or, under a policy that folds names, a sibling differing only in case or
Unicode form — so it never writes what the next load would discard. A
read-only provider makes every write method throw BundleReadOnlyException.
AppendToConceptAtomic and RecordVerifications write conditioned on the
version they read and retry a conflict, at most three attempts in all, re-reading each
time (so buildBody must be a pure function of the body it receives);
WriteConcept(…, BundleWriteCondition) lets a caller condition a rewrite on
the version it read itself, and is never retried.
AppendLog(kind, text) appends an entry to the root log.md the same way.
The writer's in-process lock is keyed by the directory for a
FileSystemBundleProvider and by the provider's Id for any other provider,
so a decorator around a FileSystemBundleProvider does not share the
directory's lock with a writer built from the root string: two such writers
are then serialised only by the provider's own commit lock and the write
conditions.
IndexGenerator.RegenerateIndexes(provider, options) regenerates every
index.md through a provider: it lists and validates the bundle as a load
does, writes each index.md conditioned on the version it read (or on its
absence), retries a conflict like the writer, and returns a
BundleWriteReport — the index.md keys written, in order, and those it could
not write, with why. A directory is referenced by its parent's index only when
a file lies under it: an empty directory is not, a directory holding only
non-.md files is. IndexGenerator.RegenerateIndexes(path) and okf index
go through a FileSystemBundleProvider and keep their return values and
output, except for the directories the rule above no longer references and the
other cases the CHANGELOG lists. They throw BundleWriteConflictException
(reason NameUnavailable, okf index exits 1) for a directory named
index.md with files under it, and, on a volume that folds case (NTFS, the
default macOS volume), for a file whose name differs from index.md only in
case (Index.md at the root or in a subdirectory): that file is never written
through, where the write that preceded the provider overwrote it. The
"Failures" remarks of RegenerateIndexesWith give the rest of what they throw.
A bundle inside your assembly
OKF4net.Providers.EmbeddedResources embeds a bundle at build time and serves it back at run time, Native AOT and single-file included:
var bundle = await Bundle.LoadAsync(new EmbeddedResourceBundleProvider(typeof(App).Assembly, "kb"));
The bundle is read-only, one manifest resource per file (okf:kb/); links under the directory, and names an assembly cannot hold, fail the build with a named OKFEMB00x error. See the package README.
A bundle in S3
OKF4net.Providers.S3 serves a bundle from Amazon S3 or an S3-compatible store, through a read-only, truly asynchronous IBundleProvider (synchronous entry points refuse it or never wait on it):
using var provider = new S3BundleProvider(credentials, new S3BundleSource { Bucket = "my-knowledge", Prefix = "okf/prod", Region = RegionEndpoint.EUWest3 });
var bundle = await Bundle.LoadAsync(provider);
It builds its own client behind a request guard (one authority, one path prefix), takes your credentials as any AWSCredentials, and versions objects by the SHA-256 of their bytes. Like OKF4net.Agents, OKF4net.Catalog.Hosting and OKF4net.Mcp, it carries a third-party dependency (AWSSDK.S3); the core and the other providers do not. Its tests against a real store are excluded from CI and run locally (dotnet test tests/OKF4net.Tests --filter Category=S3Integration). See the package README.
One image per source: BundleHandle
A BundleHandle (spec §5.2) holds one bundle's image: its provider, the
BundleLoadOptions every load uses, a refresh policy and the current Bundle
(await handle.GetCurrentAsync(ct), loaded on first use). One load runs at a time
and is shared — concurrent callers join the operation in progress (a caller joins
only one that started at a generation covering its own reload obligation), and one
that cancels stops waiting without cancelling the others' load — and the image is
replaced as a whole, so a caller never sees two versions. A reload that fails (the
storage unreachable, a bound exceeded) keeps the previous image served:
handle.IsStale is true and handle.LastLoadError holds the failure (its
inner exception is the raw cause, for the host's log only); only the very
first load throws. handle.Invalidate() obliges the next use to reload
whatever the policy; the obligation is acknowledged only by a successful load
started after it. The refresh policies (BundleRefreshPolicy) are all lazy —
no timer, no thread: Manual (the default: the host calls await handle.RefreshAsync()),
OnAccess (the provider's version token is compared before every use),
Every(interval) (compared at most once per interval, at an access) and
Notify (a provider implementing IBundleChangeNotifier signals a possible
change; the next access compares the token — a signal is a hint, never a
reload by itself, and asking for Notify over a provider that cannot signal is
an ArgumentException).
Sharing is explicit: new OkfBundleTools(handle) and new BundleConceptWriter(handle) work on that image (the writer invalidates it
after each committed write), an OkfContextProvider built over the tool set
uses the tool set's handle, and two consumers built from a root string
(new OkfBundleTools(root)) have two handles and two images. tools.Handle
is the handle a tool set serves from; tools.Location the provider's
displayable location. The image is replaced as a whole but its documents are
not frozen (the Frontmatter of today is mutable): modifying a document of a
shared image is not supported.
A catalog keeps the handles itself (spec §9): each FileKnowledgeCatalog
snapshot carries one per enabled knowledge source
(snapshot.Handles[sourceId]), built under the catalog's
KnowledgeCatalogOptions.LoadOptions and the source's refresh policy
(RefreshPolicy, OnAccess by default, so a source stays almost as fresh as when it
was reloaded at every request at the cost of a token read — a weak token for a
directory: name, length and modification time; RefreshPolicyFor chooses per
source), and the resolvers search through them. A source whose later reload
fails is answered from its last good image and reported as
KnowledgeDiagnosticCode.SourceStale; only a first load that fails is
SourceUnavailable. A reload keeps a source's handle, image included, while
its effective configuration is unchanged, and rebuilds it otherwise (a changed
path, say); a handle that leaves the catalog is disposed, which only ends its
change subscription — a request still holding the old snapshot keeps reading
its image. A catalog.json source may name another storage than a directory
under the catalog root: "provider": "" plus "settings", served by the
IBundleProviderFactory the host registered for that type
(KnowledgeOptions.AddProviderFactory, or KnowledgeCatalogOptions.ProviderFactories);
each factory declares the settings it accepts, and a source carrying any other
setting, an unknown type (on an enabled source), or a path on a non-filesystem type is rejected
with the whole manifest or reload, so no credential ever travels through the
manifest (spec §7). Memory sources stay on the filesystem.
As a CLI
On Windows, install via winget:
winget install Coderise.OKF4net
On Linux or macOS, install a release binary with the install script:
curl -sSL https://raw.githubusercontent.com/jchable/okf4net/main/packaging/install.sh | sh
It detects your OS/architecture, downloads the matching archive from the
latest GitHub Release,
verifies its SHA-256 checksum, and installs to /usr/local/bin (falling back
to ~/.local/bin when that isn't writable — it never calls sudo). Pass
--bin okf-render to install the site generator instead of okf, --version to pin a release, --dir to override the destination, or
--dry-run to see what it would do without touching disk or network beyond
resolving the version. Run it with -h for the full option list; see
packaging/install.sh for the implementation.
If the machine has the .NET SDK, okf is also a
dotnet tool, and that is the
best way to run it in CI. Pin it in the repository's tool manifest, commit
the manifest, and every clone and CI run gets the same version back:
dotnet new tool-manifest # once per repository; creates dotnet-tools.json
dotnet tool install OKF4net.Cli # records the version in the manifest
dotnet tool restore # what CI runs
dotnet okf validate ./knowledge
dotnet tool install -g OKF4net.Cli installs it globally instead, and
dnx OKF4net.Cli validate ./knowledge runs it once without installing
anything (it asks before downloading; --yes answers in advance for a
non-interactive run, but only the .NET 11 SDK and later have it). The tool is portable IL and needs the .NET 10 runtime or a later
one. It is built from the same source as the native binary and gives the same
verdicts. If both are installed, the first okf on PATH wins, while
dotnet okf always runs the manifest's version.
On any OS, you can also build from source — see
Building & testing.
okf validate Check a bundle against OKF v0.2 conformance (§11)
okf audit Report trust, freshness and lifecycle across the bundle
okf verify … Record a review of one or more concepts (--by )
okf info Summarize a bundle (concepts, types, links, version)
okf index (Re)generate every index.md in the bundle
okf graph Print the cross-link graph (--dot for Graphviz DOT)
okf parse Parse one concept document and print its structure
okf fmt Normalize a document by parse + re-serialize (-w writes)
okf help Show this help (same as -h, --help)
okf version Show version (same as -V, --version)
Every verb takes -h/--help for its own usage and option list. Arguments are
validated per verb: an option that verb does not define, or a surplus
positional, is an error rather than silently ignored — so a typo'd flag never
runs the command with different behaviour than you asked for.
okf validate exits non-zero when a bundle is not conformant, so it drops
straight into CI. No bundle of your own yet? The repository ships sample
bundles under bundles/ — ga4 validates with no
warnings, so it is a good first target:
okf validate ./bundles/ga4
okf graph ./bundles/ga4 --dot | dot -Tsvg > graph.svg
okf audit reports trust, freshness and lifecycle across a whole
bundle: counts per trust tier (§5.3) and status (§5.4), plus the worklist of
stale concepts (§5.5). Filter it to ask corpus-level questions —
# Which concepts are past stale_after and were never verified by a human?
okf audit bundles/acme_retail --stale --trust unverified,machine-confirmed
Without filter flags it selects exactly what --stale selects and prints the
summary form; with any filter flag it prints one line per matching concept, so
the output pipes. --json always emits the full document.
A verified stamp attests a moment, not a version (§5.2: content can change
without re-confirmation). --review-outdated selects the concepts whose content
changed after their latest review: generated.at (or the legacy timestamp,
§13.1) strictly later than the latest verified[].at, whoever the actor. It is
a signal for a reviewer and leaves the trust tier alone. A concept without
either date is never selected. Each --json finding carries the two instants
compared (lastVerifiedAt, lastChangedAt) and the verdict (reviewOutdated).
Only the frontmatter is read, so a file edited without updating generated.at is
not detected. To compare with the file's history instead, take lastVerifiedAt
from the JSON and git log -1 --format=%cI -- from git.
# Which reviewed concepts were regenerated since their last review?
okf audit bundles/acme_retail --review-outdated
--as-of pins the date staleness is evaluated against, on both
okf audit and okf validate; it pins to midnight UTC on that date, since §5
makes stale_after an instant. Without it, anything touching stale_after
(§5.5) depends on the day it runs — including okf validate's
concept is stale warning, which is why a CI job that wants a reproducible
report should pin the date rather than let the calendar move under it. The
exit code never depends on it: staleness is a warning, not a conformance
error. Note the counts
always cover the whole bundle while findings covers the selection: audit is
a worklist, not an inventory (use okf info --json for that).
Both commands' --json document carries asOf (the evaluation date) and
evaluatedAt (the exact instant, yyyy-MM-ddTHH:mm:ssZ) right beside it —
asOf is evaluatedAt's date only, both coming from a single clock read per run, so
an archived report can be told apart from an unpinned run down to the second,
not just the day.
okf verify … --by records a review (§5.2): it adds — or,
for a repeat review from the same actor, replaces — a { by, at } entry in
each named concept's verified list. It is the verb that answers what
okf audit asks about trust: audit finds concepts a human has never reviewed
(--trust unverified / unverified,machine-confirmed), verify records that
the review happened, and — for a human: actor — the reviewed concept
clears that trust-filtered selection. A process: or / actor is accepted
symmetrically (§7), but only moves the concept from unverified to
machine-confirmed (§5.3), which --trust unverified,machine-confirmed
still selects. Verification only moves the trust dimension (§5.3) — it never
touches stale_after, so a concept just reviewed can still show up in
okf audit's default worklist, which selects on staleness alone (see
above). … also accepts a single -, reading one concept id per line
from standard input, so the two verbs compose into one line:
okf audit bundles/acme_retail --trust unverified | cut -d' ' -f1 | okf verify bundles/acme_retail --by human:ada -
An empty stream there is "nothing to do", not an error: okf audit exits 0
printing nothing when the worklist is empty, and okf verify - on that
stream writes nothing and exits 0 too, so the loop is idempotent and safe
under set -e on a healthy bundle. Naming no concept at all
(okf verify ) is still an error — that is the mistyped-validate
case, and it stays loud.
Every named concept is checked for existence and §11 conformance before
anything is written, so a batch is rejected as a whole at that stage; a
mid-batch I/O failure can still leave the concepts already written stamped
(okf verify lists the concepts it wrote before it stopped). --dry-run prints what
would be recorded without writing anything; --at
overrides the default of "now" for reproducible scripting — a bare date, a
numeric offset, or fractional seconds are all rejected, not silently rounded.
> What a verified stamp does and doesn't prove. It guarantees the
> stamp is well-formed, dated, and attached to the concepts named — nothing
> more. It does not guarantee the signer's identity, nor that anyone
> actually read the concept: no zero-dependency tool can authenticate --by,
> and okf_write_concept can write the exact same field with no ceremony at
> all — deliberately unguarded, since a full frontmatter rewrite (importing a
> bundle, correcting a concept) has to be able to touch verified too.
> Credibility comes from where the stamp lands: in a diff a human reviewed,
> under branch protection, where the reviewer sees the assertion and can
> reject it. That argument only works if the diff is legible, which is why
> verify is deliberately not like every other write path in this
> library: instead of re-serializing the whole document, it edits the
> verified: block in place in the raw text (FrontmatterBlockEdit) and
> leaves every other byte untouched — CRLF line endings, YAML comments, and
> flow-style/folded scalar spellings elsewhere (tags: [a, b], generated: { > by: …, at: … }, description: >) survive exactly as the bundle had them.
> The one exception is a column-0 comment sitting inside the verified:
> block itself (between the verified: line and the next top-level key): it
> is replaced along with the block it comments on, since there is no way to
> know which of the stamp's lines it was meant to annotate. A reviewer's diff
> for a verify run is therefore just the changed verified: lines, with no
> okf fmt -w step needed first to keep the reformat from swallowing it.
> Never infer
> a stamp from a PR approval — that turns "a human
> approved this diff" into "a human vouches for this knowledge," which are
> different every time a PR touches a file for a reason other than reviewing
> it (which is most of the time). Doing so would mass-promote every concept
> the diff happens to touch and silently empty the very worklist this feature
> exists to populate.
okf is OKF4net.Cli, published two ways from the same project: a
self-contained, Native AOT single-file binary for winget and the install
script, which needs no .NET runtime on the target machine, and the portable
OKF4net.Cli dotnet tool described above. Full command reference with real output samples:
CLI docs on the site.
okf-render — generate a static HTML site
Static HTML site generation lives in a separate binary, okf-render
(OKF4net.Render), not in okf itself — okf is meant to be the small,
dependency-free CI validator that winget and nuget.org distribute, and the site generator pulls
in a vendored copy of marked (MIT) and
three embedded fonts (SIL OFL 1.1) that a CI job running okf validate never
needs. OKF4net.Mcp already
established the pattern this follows: a leaf executable owns the dependencies
its one job needs, instead of pushing them into the shared core.
dotnet publish src/OKF4net.Render -c Release # Native AOT, self-contained okf-render binary
okf-render bundles/ga4 --out /tmp/ga4-site
# then open /tmp/ga4-site/index.html


The acme_retail sample bundle rendered by okf-render: a concept page (top) and the global graph (bottom). Screenshots are regenerated by tools/viewer-security-check/recette/docs-shots.js.
The generated site is self-contained and opens straight off the filesystem —
no server needed. Every page carries one header (the bundle's name, its
concept and link counts, a "Jump to" palette — Ctrl+K or /, matching
titles, ids and tags —, a "Global graph" link and a light/dark toggle) and a
tree explorer of the bundle with type shapes, type filters and trust and
staleness flags. A concept page shows a breadcrumb, its title, chips for
type, status, trust and staleness, and a folding frontmatter box; its side
panel holds the page's contents, the pages that reference it and, when the
concept has neighbours, a "Neighbourhood" local graph (its neighbours at one
or two hops, at most 40 drawn, with an equivalent list of all of them and an
"Open in graph" link; it can be enlarged into a dialog). "Global graph" opens graph.html, a page that draws
the whole bundle's links with a layout computed in the browser, narrowed by
facets (type, trust, freshness, tags), with a list equivalent and keyboard
navigation; both are described in
src/OKF4net.Viewer/README.md and, with screenshots, in the
viewer docs. The right-hand
column can be resized with a splitter (drag it, or use the arrow keys). The Inter,
Inter Tight and Space Mono fonts are embedded.
It is read-only, and has no full-text search: a static site has no server
to run the shared ConceptSearch scorer, and mirroring its weights in
JavaScript would fork it. Interactive browsing with search is planned as a
VS Code extension instead (see
#163), not as a local
server. okf-render has its own winget package,
Coderise.OKF4net.Render, built and attached to each Release the same way
as okf's — but its first submission to winget-pkgs is a manual, one-time
step (see packaging/winget/README.md). It was made for 0.6.0 and
closed, then made again for 0.7.0, and that PR is waiting in the winget-pkgs moderation queue, so
winget install Coderise.OKF4net.Render will not resolve until it is merged.
Until then, on Linux or macOS install it with the same script
as okf above (--bin okf-render), or on any OS grab a prebuilt archive from
a GitHub Release or build it
from source as shown above.
Using OKF4net with Microsoft Agent Framework
src/OKF4net.Agents/ exposes bundle operations as function tools for the
Microsoft Agent Framework:
OkfBundleTools wraps one bundle root and its GetTools() method returns
twelve ready-to-use AITools unconditionally, which AsAIAgent turns into an
agent's tool list, plus a thirteenth — okf_run_computation — only when the
tool set is constructed with an OKF4net.Attestation orchestrator wired in
(see Attested computation).
using Microsoft.Agents.AI;
using Microsoft.Extensions.AI;
using OKF4net.Agents;
IChatClient chatClient = /* your IChatClient, e.g. from an OpenAI/Azure client */;
var tools = new OkfBundleTools("./my_bundle");
// The write tools need the host's approval before they run. `GetTools()` with
// no argument returns them ungated — see the security note below.
AIAgent agent = chatClient.AsAIAgent(tools: tools.GetTools(OkfToolMode.RequireApprovalForWrites));
var response = await agent.RunAsync("Search the bundle for concepts about refunds.");
Console.WriteLine(response.Text);
To see this run before choosing a model,
samples/agents-quickstart/ does it with
no LLM endpoint, API key or network access: it lists the tools, calls two of
them directly, then drives the same AsAIAgent wiring — with the read-only
tool list — through a scripted IChatClient against bundles/ga4
(dotnet run --project samples/agents-quickstart/src/AgentsQuickstart).
samples/acme-retail-agent/ is the
same kind of agent over a real OpenAI-compatible endpoint.
The agent builders' tutorial walks through
a shared BundleHandle, the tool modes, OkfContextProvider, an approved
write and okf-mcp.
samples/agents-handoff/, also with no
model or key, hands knowledge from one agent to another over a copy of
bundles/ga4: a curator with the read-write tools writes a note, and a reader
with the read-only tools finds it in its OkfContextProvider context, because
both tool sets share one BundleHandle (see
Sharing a BundleHandle).
The twelve unconditional tools, plus the thirteenth conditional on an attestation
orchestrator being wired (read → browse → graph → search → audit → write →
verify → append → regenerate → validate → changes-since → get-computation → run-computation):
| Tool | Description |
|---|
okf_read_concept | Read one concept from the OKF bundle: its frontmatter (a yaml block that okf_write_concept accepts as is), body, outgoing links and backlinks. |
okf_browse | Browse the bundle via its index files (progressive disclosure). Without a path, lists the bundle root. |
okf_graph | Inspect the cross-link graph. With a concept id: its outgoing links, backlinks and broken links. Without: bundle-wide stats. |
okf_search | Full-text search across concept titles, descriptions, tags and bodies. Returns the best-matching concept id first, then spreads the remaining results across top-level id families, so the list is not in descending score order. |
okf_audit | Audit the bundle's trust, freshness and lifecycle signals (§5.3–§5.5): counts by trust tier and status, plus the concepts needing attention. Read-only. |
okf_write_concept | Create or update a concept document. The frontmatter must contain non-empty type, title and description (producer-grade validation is enforced before writing). |
okf_verify | Record a review (§5.2): adds or replaces the caller's {by, at} entry in each concept's verified list — a dated declaration, not a proof; never infer one from a PR approval. |
okf_append_log | Append an entry to the bundle root log.md under today's date (ISO). Note: log.md is re-rendered through the strict §9 model, so non-conforming prose or comments in a hand-authored log.md are not preserved; a leading frontmatter block is kept as it was. |
okf_regenerate_indexes | Regenerate every index.md in the bundle (progressive-disclosure listings). Run after adding or changing concepts. |
okf_validate_bundle | Validate the bundle against OKF v0.2 conformance (§11). Returns the diagnostics report. |
okf_changes_since | Summarize bundle changes since a given ISO date, aggregated from every log.md in the bundle. |
okf_get_computation | Read a §10 attested-computation concept's contract and sanctioned computation source. Always available; read-only, needs no attestation runtime. |
okf_run_computation | Run a §10 attested computation end to end (bind → execute → attest → stale-gate) through a host-wired AttestationOrchestrator. Only present in GetTools() when one was passed to the constructor. |
Security note: bundle content (concept bodies, frontmatter, log entries)
is untrusted — it comes from files on disk that may have been written by
another agent or a human contributor — and is never injected into the
conversation with a system role; it only ever reaches the model as tool
output.
That matters most for the four write-capable tools (okf_write_concept,
okf_verify, okf_append_log, okf_regenerate_indexes), because an injection carried in a
concept body is only dangerous if it can reach a persistent write.
GetTools() returns them ungated, and nothing asks on your behalf: the
Agent Framework's approval mechanism is not active by default, so a plain
AIFunction is invoked directly. Choose how they are exposed:
// The model must not write at all:
var tools = okf.GetTools(OkfToolMode.ReadOnly);
// Or: every tool, but a write needs the host's approval first.
var tools = okf.GetTools(OkfToolMode.RequireApprovalForWrites);
RequireApprovalForWrites wraps exactly the write tools in
ApprovalRequiredAIFunction; read tools stay ungated, since prompting for
everything trains a user to click through and is how the one approval that
mattered gets waved past. OkfBundleTools.WriteToolNames is the single source
of truth for which tools count, so a write tool added later cannot slip past a
host's own filtering either. The parameterless GetTools() keeps its
historical ungated meaning so existing hosts are not changed under them.
The core OKF4net library stays dependency-free (BCL only); only
OKF4net.Agents references Microsoft.Agents.AI, and OKF4net.Providers.S3 references
AWSSDK.S3 (see Hard rules for the per-project dependency policy).
Automatic context & memory (OkfContextProvider)
OkfContextProvider is an AIContextProvider that, layered onto the same
OkfBundleTools instance as the tools above, automatically injects relevant
bundle context into each invocation and — when explicitly enabled — captures
the exchange back into the bundle as long-term memory, no extra tool calls
required from the model. Register it via ChatClientAgentOptions.AIContextProviders
(the tools + providers convenience overload doesn't exist; this is the one
API surface that wires both):
using Microsoft.Agents.AI;
using Microsoft.Extensions.AI;
using OKF4net.Agents;
var tools = new OkfBundleTools("./my_bundle");
// MemoryCapture defaults to MemoryCaptureMode.Disabled; opt in explicitly
// (see the memory trust model caveat below) to get the capture behavior
// shown here.
var provider = new OkfContextProvider(tools, new OkfContextProviderOptions { MemoryCapture = MemoryCaptureMode.Enabled });
AIAgent agent = chatClient.AsAIAgent(new ChatClientAgentOptions
{
ChatOptions = new ChatOptions { Tools = tools.GetTools(OkfToolMode.RequireApprovalForWrites) },
AIContextProviders = [provider],
});
var response = await agent.RunAsync("What do we know about orders?");
OkfContextProviderOptions:
| Option | Default | Meaning |
|---|
TokenBudget | 2000 | Approximate token budget (chars/4 estimate) for context injected per invocation. |
MemoryCapture | MemoryCaptureMode.Disabled | Opt-in: MemoryCaptureMode.Enabled captures exchanges as long-term memory concepts in the bundle after each invocation; Disabled writes nothing. |
MemoryDirectory | "memory" | Bundle subdirectory holding memory concepts, as a single ConceptId segment (no /). |
MaxConceptsInjected | 5 | Maximum number of scored concepts injected into a single invocation's context. |
OnInternalError | null | Host-side sink for exceptions context assembly swallows (a failed bundle load, a failed knowledge/memory read). The model only ever sees a category. |
Security note: as with the tools above, bundle content is untrusted.
ProvideAIContextAsync injects the bundle root index plus the top scored
concepts (progressive disclosure, budget-bounded) as reference data in a
message — it is never written into AIContext.Instructions, so a
prompt-injection payload smuggled into a concept body cannot reach the
instructions channel.
Information flows the other way too. When context assembly fails, the model is
told a category (bundle unavailable: I/O error), never the exception's own
message — a .NET filesystem exception carries the absolute path, and an
exception from a host-plugged runtime can carry a connection string or a query.
The same applies to okf_run_computation: the outcome rendered to the model
names the failing stage and the exception type, while the exception itself
stays on AttestationOutcome.Error for the host. Wire OnInternalError to get
the detail into your own logs.
Memory design (v1, deterministic): StoreAIContextAsync captures each
exchange with no LLM call — the last user message and the agent's final
response are appended to one memory concept per UTC day
(/), plus a matching log.md entry. Captured
text is blockquote-neutralized (each line prefixed with >) so injected markdown
structure (---, headings, a fake # Citations section) can't be mistaken
for genuine document structure. Writes go through the same
OkfBundleTools.WriteConcept/AppendLog calls — and therefore the same
producer-grade validation, write lock and reparse-point guards — any other
caller would use, and the provider never throws toward the invocation
pipeline. The write lock and the reparse-point guards have precise scopes —
see the concurrency and reparse-point caveats below before relying on either
as a stronger guarantee than documented.
A few known v1 caveats:
- Budget is approximate:
TokenBudget uses a crude chars/4 estimate, and
the per-block `` framing overhead (tags, id, joining newlines,
a trailing truncation marker) is charged against it, so the injected
message tracks the budget closely — but it's still a soft budget, not a
hard cap: the estimate itself is approximate, so the result can land a
little under or over.
- **The
elements keep their structure, but they are not a security boundary:** inside an element (and in its id) every `&` is written `&` and every `<` `<`, and the content sits in a code fence longer than any fence run it holds, so a concept body containing a literal, or an index.md that leaves a fence open, can no longer
close its element or reach into the next one (#122); still, the whole
injected message is untrusted user-role reference data, and nothing in it
is ever treated as instructions in the first place (see the security note
above).
- Memory is bundle-global, unscoped, and opt-in: captured memory carries
no session/user/tenant key, so a scored recall in
ProvideAIContextAsync
can surface one session's captured exchange in a completely different
session sharing the same bundle. That's why MemoryCapture defaults to
MemoryCaptureMode.Disabled — set it to MemoryCaptureMode.Enabled
only for a bundle that's intended to be a shared, non-sensitive memory
across those sessions.
- Concurrent same-day capture is safe only within one process, and only up
to a residual filesystem-race caveat: same-day capture is a
read-modify-write on one concept file, done through
OkfBundleTools.AppendToConceptAtomic under a write lock that's shared —
not just by one instance — via a process-wide registry, by every
OkfBundleTools instance whose bundle root resolves, at the moment it
takes the lock, to the same directory (a junction or symlink to the bundle
shares its lock; if resolution fails, the lexical path is the key; a
topology change during an operation is not followed). Operations using an
identical namespace-normalized lexical root also remain serialized when
its resolved key changes, with one exception: a thread that already holds
a write lock never waits for that lexical gate. A nested acquisition that
finds the gate busy (which ordinary contention on that root causes, with
no topology change) takes the resolved monitor without the gate and holds
no gate for its whole operation; if the root's resolution changes while
it runs, another writer on the same lexical root can overlap it.
Releasing the gate before the monitor, and retrying it once (without
blocking) after resolving, narrow this but do not close it.
Different aliases can still diverge if the
topology changes during an active operation: no filesystem handle pins
their targets. Nested calls over different resolved bundles need a
consistent caller lock order over the registry's case-folded keys. A
link on the path retargeted during an operation, even one every alias
follows, splits the bundle in two for that purpose: aliases of it nested
in opposite order can then deadlock between their resolved monitors.
Within these limits, two (or more) truly concurrent
StoreAIContextAsync calls, even across separate OkfBundleTools/
OkfContextProvider instances sharing a session pool, never lose a
same-day section as long as they're all in the same process. This
guarantee does not extend across separate processes (e.g. two CLI
invocations, or two independently-hosted server processes sharing a
network bundle path) — nothing coordinates them, so a same-day count
divergence between log.md and the memory concept is possible there.
Separately, the reparse-point guard that write tools use to reject a
symlink/junction inside the bundle is a check-then-write: it rejects a
reparse point present when it runs (both an early check and a second,
best-effort re-check immediately before the actual write), but a
concurrent local actor able to substitute a path component with a
symlink/junction in the narrow remaining window is not something a C#
lock — in-process or not — can fully close (there's no portable
no-follow atomic write in .NET). That actor would already need write
access inside the bundle tree to plant the substitution in the first
place, so this residual gap defends the bundle's own content from causing
an accidental escape more than it defends against a hostile, already
co-resident writer.
Attested computation (OKF4net.Attestation)
src/OKF4net.Attestation/ orchestrates §10 Attested
Computations:
a concept can declare a runtime/parameters/computation/executor/attester
contract (Frontmatter.ComputationContract) and a sanctioned computation —
an inline fenced # Computation block or a computation: file resolved via
§6.2 path-safe resolution (OkfDocument.Computation()). The host plugs in
IParameterBinder, IComputationExecutor and IAttester per runtime name
through an IAttestationRuntimeRegistry; AttestationOrchestrator.RunAsync
drives one run end to end — resolve → bind → execute → receipt-shape check →
attest → gate on the verdict and stale_after — always returning an
AttestationOutcome (errors-as-data, never throwing for an expected
failure). §10.6: a verdict is never written back to the bundle — attestation
is per-run, not stored provenance.
using OKF4net;
using OKF4net.Attestation;
IAttestationRuntimeRegistry runtimes = new AttestationRuntimeRegistry(
new Dictionary { ["bigquery"] = myBigQueryRuntime });
var orchestrator = new AttestationOrchestrator(runtimes);
AttestationOutcome outcome = await orchestrator.RunAsync(
bundle, conceptId, new Dictionary { ["region"] = "eu" });
if (outcome.Displayable)
{
Console.WriteLine(outcome.Receipt);
}
else
{
Console.WriteLine(string.Join("; ", outcome.Reasons));
}
An orchestrator runs whatever sanctioned code the bundle references. A host
that does not trust everyone who can write to the bundle's source passes
AttestationOrchestratorOptions.AllowedCodeDigests. That is an allowlist of
SHA-256 digests of the exact computation and attester texts
(AttestationCodeDigest.Of). Anything else is refused before any runtime
stage, and the refused digests are reported to the host on
outcome.UnapprovedCode, never in the reasons a model sees (#154).
OKF4net.Agents' okf_get_computation tool (read-only, always available)
surfaces a computation's contract and source without running anything; pass
an AttestationOrchestrator to new OkfBundleTools(bundleRoot, orchestrator) to also expose okf_run_computation — see the tool
table above. OKF4net.Attestation
references only OKF4net — zero third-party runtime dependencies. See
OKF4net.Attestation's README for the
full contract/value-type reference.
Local catalog (OKF4net.Catalog)
src/OKF4net.Catalog/ and src/OKF4net.Catalog.Hosting/ add a catalog of
OKF bundles (directories under the catalog root unless the host registers a
provider factory): a hot-reloadable catalog.json manifest naming one or more
bundles as sources, and a resolver that searches every enabled source.
catalog.json is an OKF4net manifest, not an OKF concept — it configures
the catalog from the outside and is not part of the OKF spec.
using OKF4net.Catalog;
using OKF4net.Catalog.Hosting;
services.AddKnowledge(o => o.AddCatalogFile("./config/catalog.json"));
// Elsewhere, resolve and search:
IKnowledgeResolver resolver = provider.GetRequiredService();
KnowledgeContext result = await resolver.SearchAsync(new KnowledgeQuery("refund policy"));
V1 limits, stated exactly:
- Bundles under the catalog root by default; another storage only through a
provider factory the host registers (
provider in catalog.json, see "One
image per source" above). No provider but the filesystem ships with this
repository (#141 embedded resources, #142 S3 are the tracked ones), and
memory sources are always on the filesystem.
- One shared catalog.
- No semantic/fuzzy deduplication across sources (two manifest entries
resolving to the same directory are collapsed only under the two merged
strategies; similar content in genuinely different bundles is not).
- No external connectors.
- No tenant-aware authorization of any kind.
Scoped memory (shipped): a read-only knowledge vs writable memory
source role split, and host-scoped, layered memory tiers (session / user /
tenant) so captured memory can be enabled on a multi-user deployment without
cross-scope leakage — see
the scoped-memory design
for the full reasoning and
OKF4net.Catalog's README
for the deployment example.
Cross-source ranking (shipped): three selectable resolver strategies —
GroupedBySource (the default, unchanged behaviour), Merged (one ranking
by descending score across every source), and PriorityWeighted (source
priority first, score within a tier) — chosen per host or per query, with
optional fairness interleaving for budget-truncated consumers. See
the resolver-strategies design
and OKF4net.Catalog's README.
Source visibility (shipped): restrict which sources a caller may see,
per host default or per query — a host-precomputed PermittedSourceIds set
(the recommended default) or a SourceVisibilityPolicy function evaluated
per source, either overridable per query. See
the source-visibility design
and OKF4net.Catalog's README.
See OKF4net.Catalog and
OKF4net.Catalog.Hosting for full
package documentation.
Use OKF in Claude (MCP)
OKF4net.Mcp is a local MCP server that plugs an OKF bundle straight into
Claude Desktop / Claude Code, so you can read, search, and persist knowledge in
your bundle from a chat — the way an Obsidian MCP server exposes a vault.
dotnet tool install -g OKF4net.Mcp
Then point Claude Desktop at a bundle in claude_desktop_config.json:
{ "mcpServers": { "okf": { "command": "okf-mcp", "args": ["/path/to/bundle"] } } }
okf-mcp serves the bundle read-only by default; set OKF_MCP_WRITABLE=1
to register the four write tools as well. See
src/OKF4net.Mcp/README.md for the full tool list, or the
MCP setup guide on the site.
samples/second-brain/ is a read-write
example: a starter personal-notes bundle served writable in Claude Desktop
(the claude_desktop_config.json for Windows and macOS, from the installed
tool or from this repository), example prompts, and a smoke test that drives
okf-mcp over stdio without Claude Desktop. It also says what a write does
not do: okf_write_concept leaves index.md and log.md alone, and they
change only when okf_regenerate_indexes and okf_append_log are called.
Mapping to the spec
This table is also published as the
spec-mapping page on the site.
| Spec section | Implemented by |
|---|
| §2 Terminology / concept id | OKF4net.ConceptId |
| §3 Bundle structure | OKF4net.Bundle, Bundle.ReservedFilenames |
| §4 Concept documents | OKF4net.OkfDocument, OKF4net.Frontmatter |
| §4.2 Body headings | OkfDocument.Computation() (fenced # Computation heading) |
| §5 Provenance, trust, and lifecycle | Frontmatter.Sources/Generated/Verified/TrustTier/Status/StaleAfter, Actor/Trust/Provenance/Lifecycle |
| §5.2 Generation and verification stamps | Frontmatter.Generated/Verified, BundleConceptWriter.RecordVerifications — the governed writer behind okf verify and okf_verify |
| §5.3–§5.5 trust, lifecycle, staleness | ConceptAudit, AuditQuery, AuditReport — the corpus-level query behind okf audit and okf_audit |
| §6 Cross-linking and paths | OKF4net.LinkScanner, Bundle.LinksFrom / Bundle.Backlinks |
| §6.2 Path-valued fields | OkfDocument.FrontmatterResources(), Bundle.TryResolveResourceKey / Bundle.ReadResourceText(BundleKey) |
| §7 Actor convention | OKF4net.Actor.Parse — human:/process:// |
| §8 Index files | OKF4net.IndexGenerator |
| §9 Log files | OKF4net.ChangeLog |
| §10 Attested Computation | Frontmatter.ComputationContract, OkfDocument.Computation(), OKF4net.Attestation (AttestationOrchestrator) |
| §11 Conformance | OKF4net.BundleValidator |
| §12 Versioning | Bundle.OkfVersion, OKF4net.OkfSpec.Version |
| §13 Changes from v0.1 (legacy fallbacks) | Frontmatter.LastChangedAt (falls back to legacy timestamp), OkfDocument.Sources() (falls back to a legacy # Citations list) |
OKF4net version ↔ OKF spec version
| OKF4net | OKF spec | Highlights |
|---|
| 0.1.0 | v0.1 | Core library + okf CLI (validate/info/index/graph/parse/fmt), Native AOT |
| 0.1.1 | v0.1 | winget distribution; project website and developer docs |
| 0.2.0 | v0.1 | OKF4net.Agents (Agent Framework tools + context provider), OKF4net.Catalog(.Hosting), OKF4net.Mcp server, scoped long-term memory (V2) |
| 0.3.0 | v0.2 | Provenance/trust/lifecycle frontmatter model, v0.1 legacy-field fallbacks, v0.2 validator diagnostics |
| 0.3.1-preview.1 | v0.2 | Per-caller source visibility, §10 Attested Computation (new OKF4net.Attestation package, okf_get_computation/okf_run_computation), §6.2 path-valued frontmatter resolution |
| 0.4.0 | v0.2 | okf-mcp bundle auto-discovery, OkfBundleTools.WriteToolNames, ComputationExtractor fence-safety fix, path-containment comparison hardening |
| 0.5.0 | v0.2 | --json diagnostics on validate/info, §11 conformance now enforced for malformed reserved files, YAML multi-line scalar support, producer-facing in-memory concept API |
| 0.6.0 | v0.2 | okf audit / okf verify (§5.2–§5.5), okf-render split out of okf, okf-mcp read-only by default, §6.2 paths resolved from the bundle root, container-based §10 host (unpublished), hardened model-facing output and link guards |
| 0.7.0 | v0.2 | Interactive okf-render sites (explorer, palette, local and global link graphs), okf as the OKF4net.Cli dotnet tool, one YAML nesting rule, okf verify output hardened against forged lines, bounded YamlValue equality and emitter |
| 0.8.0 | v0.2 | Bundle providers (asynchronous IBundleProvider, shared BundleHandle), new OKF4net.Providers.EmbeddedResources and OKF4net.Providers.S3 packages, a provider failure no longer read as a problem of the file, agent tools that show round-tripping frontmatter and return plain text over okf-mcp, generated.by naming the library version |
Contributing & roadmap
Contributions are welcome and the barrier to entry is deliberately low — the
library is pure BCL C# with no third-party runtime dependencies, so there is
no framework to learn before you can help.
Building & testing
dotnet build OKF4net.sln # core library + okf CLI + okf-render + test project
dotnet test OKF4net.sln # unit + integration tests (incl. golden CLI comparisons)
dotnet publish src/OKF4net.Cli -c Release # Native AOT, self-contained okf binary
dotnet pack src/OKF4net.Cli -c Release # the portable okf dotnet tool (OKF4net.Cli)
dotnet publish src/OKF4net.Render -c Release # Native AOT, self-contained okf-render binary
Just want the okf binary on Windows, not a source build? winget install Coderise.OKF4net (see As a CLI).
License
OKF4net is licensed under the GNU Lesser General Public License v3.0 or
later (LGPL-3.0-or-later) — see LICENSE for the full LGPLv3
text and LICENSE.GPL-3.0 for the GPLv3 text it
incorporates by reference.
That applies to everything this project builds: every OKF4net library and
binary is original work, LGPL-3.0-or-later in its entirety. The okf binary
and the packages published to NuGet — OKF4net, OKF4net.Agents,
OKF4net.Catalog, OKF4net.Catalog.Hosting, OKF4net.Attestation,
OKF4net.Providers.EmbeddedResources, OKF4net.Providers.S3,
OKF4net.Cli, OKF4net.Mcp — carry that one licence and include no third-party source
code.
The exceptions anywhere in the build are both in OKF4net.Viewer (not itself
published to NuGet): it vendors a copy of
marked (MIT) for client-side markdown
rendering, and the Inter, Inter Tight and Space Mono fonts (SIL Open Font
License 1.1). Their licence texts are written beside them under
assets/fonts/ (the fonts') and assets/licenses/ (marked's) and travel with
the okf-render archives; all of it is embedded in that library and shipped
inside the okf-render binary it backs; okf itself never references them. See NOTICE
for the full accounting, including those vendored copies and the two kinds of
Apache-2.0 material also in this repository — the vendored
OKF specification and the upstream sample bundles
under bundles/, both Copyright Google LLC and
documentation/sample data rather than code, covered by
LICENSE.Apache-2.0 and not packaged for
distribution.
This is an independent implementation and is not affiliated with or endorsed by
Google.