需要 Go 1.26 工具链编译,README 标注为零依赖但未说明更低版本是否可用;bootstrap 会向目标项目写入 AGENTS.md 与 knowledge/ 目录,需确认不会覆盖已有配置;pull 与 hub 相关命令依赖外部 Registry 或 Hub 服务,离线环境不可用。
okf-agent-memory
okf-memoryMIT活跃维护给 AI 编码代理用的 Git 原生持久记忆库,纯 Go 实现,内置 MCP 服务和 BM25 内存检索,无需外部数据库,能把上下文 token 消耗降低约 80%。
Git-native persistent memory for AI coding agents. Implements Google OKF v0.2 with sub-300µs in-memory BM25 search, embedded MCP server, and progressive disclosure. Slashes token bloat by 80% with zero external databases or dependencies. Built in pure Go.
make build
./bin/okf bootstrap /path/to/project --name "My Project"README 未说明显存或 GPU 要求;工具为纯 Go 编译的单二进制,README 标称内存占用低于 15MB,未提及 CPU 运行限制。
给 AI 编码代理用的 Git 原生持久记忆,用 OKF v0.2 规范加内存 BM25 检索,避免提示词膨胀
给 AI 编码代理用的 Git 原生持久记忆库,纯 Go 实现,内置 MCP 服务和 BM25 内存检索,无需外部数据库,能把上下文 token 消耗降低约 80%。
核心能力
- 用 DMAA 双记忆架构分离常驻行为准则与按需检索的领域知识
- 以内存 BM25 检索概念,README 标称低于 300µs
- 用渐进式披露按 index.md 层级只加载需要的概念
- 知识以纯文本存入 Git,可用 git diff 审计且无需外部数据库
- 内置 MCP 服务端,并提供 validate、search、show 等 CLI 子命令
容易踩的坑
- v0.8.0最新正式版2026-11-05 · 2026-11-05 22:47 UTC
Release v0.8.0: Bundle Scope Isolation, Concurrent Write Protection & Multi-Writer Sync Hardening
Release
v0.8.0introduces declarative Bundle Scope Isolation viascopesin the rootknowledge/index.mdfrontmatter, adds Two-Stage Concurrent Local Write Protection (WithBundleLockandErrConcurrentModification), hardens multi-writer Hub Sync conflict forks (#60, PR #66), wires automatic SSoT tool symlinks intookf bootstrap, and removes the legacybundlealias for--scopeacross the CLI and MCP server. Because removing the--scope bundlealias is a breaking CLI/MCP schema change, this is a minor release (v0.8.0).
1. Breaking Changes & Migration
- Removed the legacy
bundlealias for--scope(okf searchand MCPokf_search).--scopenow accepts only the canonical scope names:all,project,vendor,user, andsystem.- Passing
--scope bundle(or"scope": "bundle"in MCPokf_search) now returns an invalid-scope error. - Migration: Replace
--scope bundlewith--scope project. The--bundle <dir>flag and the MCP"bundle"directory parameter remain unchanged.
2. Features
-
Declarative Bundle Scope Isolation (
scopesin rootknowledge/index.md).- Projects (such as client repositories, open-source projects, or isolated domains) can now restrict which memory layers are active by declaring an explicit
scopeslist in the rootknowledge/index.mdfrontmatter (both flow lists and block lists are supported):--- okf_version: "0.2" scopes: [project, vendor] --- - Default Behavior: When
scopesis omitted, all four canonical scopes (project,vendor,user,system) remain active. - Implicit Filtering: Disabled scopes (e.g.
userandsystemin the example above) are automatically skipped during--scope allsearches (SearchLayered) and bare-IDokf show/okf_showfallback (ResolveScopedConcept). - Strict Enforcement: Explicit queries targeting a disabled scope (e.g.
okf search --scope user,okf show user:secret, orokf://user/secret) are rejected with an error:scope "user" is disabled by bundle configuration in index.md (allowed: project, vendor). - Fail-Closed Validation: Declaring an empty
scopeskey (scopes: []orscopes:) or any non-canonical value (such asall,bundle, or a typo) immediately fails bundle loading andokf validate.
- Projects (such as client repositories, open-source projects, or isolated domains) can now restrict which memory layers are active by declaring an explicit
-
Two-Stage Concurrent Local Write Protection (
WithBundleLock& Optimistic Concurrency Check).- Stage 1 – Cross-Process Bundle Write Lock (
.okf-write.lock):InitBundle,SaveConcept,UpdateConcept,RelateConcepts,UpdateParentIndex, andAppendLogEntrynow serialize local Read-Modify-Write transactions across concurrent processes and goroutines (e.g. parallel subagents or multiple IDE MCP servers sharingknowledge/or~/.okf/) using an atomicO_CREATE|O_EXCLbundle lockfile with bounded backoff and automatic stale-lock recovery. - Stage 2a – Transactional RMW Serialization (
UpdateConcept&RelateConcepts): CLIokf update, MCPokf_update, CLIokf relate, and MCPokf_relatenow acquire the bundle write lock before loading and mutating the target concept, preventing concurrent field updates or link insertions on the same concept from overwriting each other. - Stage 2b – Optimistic Concurrency Check (
ErrConcurrentModification):LoadBundlerecords the on-disk SHA-256 content digest of each concept; if a caller mutates a pre-loadedConceptstruct and callsSaveConceptafter an external write modified that file on disk,SaveConceptdetects the digest mismatch inside the lock and rejects the stale overwrite withErrConcurrentModification.
- Stage 1 – Cross-Process Bundle Write Lock (
-
Automatic SSoT Tool Symlinks in
okf bootstrap.okf bootstrapnow automatically creates the canonical SSoT tool symlinks (CLAUDE.md,.cursorrules,.windsurfrules, and `.github/copilot-instruc
- Removed the legacy
- v0.7.22026-10-28 · 2026-10-28 17:06 UTC
查看更新说明
Release v0.7.2: Remote Path Boundary Hardening & Symlinked CWD Confinement
Release
v0.7.2is a security and stability patch release hardening remote path containment acrossokf hub pull,okf hub sync,okf pull,okf restore, andokf vendor remove, introducing staging-directory atomic rollbacks for registry installations, and resolving a false-positive traversal error when mutating relative bundles from a symlinked working directory.
1. Security Hardening & Bug Fixes
Remote Input Write Containment in Hub Sync & Registry Installs (#64)
- Problem:
okf hub pull,okf hub sync,okf pull, andokf restorederived filesystem destination paths from remote data (hub tree manifests, registry bundle IDs,okf.lockentries, and archive headers) without uniformly rejecting parent traversal (..), absolute paths, hidden dotfiles (e.g..git/hooks/*,.okf-vault.json), or symlinks resolving outside the bundle or workspace. Furthermore,okf pull --forceandokf restore --forceunpacked directly into the target path and executedos.RemoveAllon validation failure, allowing an escaping bundle ID or symlink to delete directories outside the workspace or wipe a preexisting installation. - Resolution:
- Hub Sync Tree & State Confinement (
pkg/sync): AddedvalidateTreePath/validateTreePathsto reject empty, absolute, volume-qualified, non-canonical (.,..,//), hidden (.git,.okf-vault.json,.okf), NUL-byte, and backslash paths before any blob is fetched. AddedhubTargetsandcontainedPathto pre-verify every write and delete destination viafilepath.EvalSymlinksandfilepath.Rel(all-or-nothing commit application). Confined.okf/sync-state.jsonreads and writes to the resolved bundle root and ignored poisoned delete bases in stored state. - Registry Bundle ID & Archive Confinement (
pkg/registry): AddedValidateBundleIDandResolveVendorDirto enforce canonical relative slash-separated IDs (preserving legitimate scoped and nested IDs such as@peter/django-5-rulesandacme/tools/linter) and verify that.okf/vendorresolves within the workspace and each bundle resolves strictly inside.okf/vendor. HardenedDownloadAndExtractto pre-verify all archive entries lexically and through symlinks prior to extraction. - Staged Installations & Safe Rollback (
internal/cli,pkg/registry): AddedStaging(NewStaging,Commit,Discard).okf pullandokf restorenow extract and validate bundles inside a fresh.okf/.vendor-staging-*directory before atomically committing them into.okf/vendor. Failed installs discard only the staging directory created by that invocation, preserving any previous--forceinstallation and never following symlinks during rollback orokf vendor remove.
- Hub Sync Tree & State Confinement (
- Credit: Reported via responsible disclosure with reproduction fixtures and implemented by Nick Hodulik (@nhod) in PR #64.
Symlinked Working Directory Bundle Root Resolution (#62, #63)
- Problem:
ensureWithinRootinpkg/okf(andcontainedPathinpkg/sync) calledfilepath.EvalSymlinksbeforefilepath.Abs. Whenokfwas invoked with a relative bundle root (e.g.knowledge) from a symlinked working directory (such as macOS/tmp$\rightarrow$/private/tmp),EvalSymlinksreturned a relative path while target paths resolved to their canonical target under/private/tmp, causing legitimate writes to be refused as path traversal escapes. - Resolution: Normalized the bundle root to an absolute path via
filepath.Absbefore callingfilepath.EvalSymlinks, ensuring both root and target resolve through the same working-directory symlinks. - Credit: Reported in #62 and implemented in PR #63 by Nick Hodulik (@nhod).
2. Knowledge & Architecture
- Updated architecture/security-boundaries documenting re
- Problem:
- v0.7.12026-10-27 · 2026-10-27 09:23 UTC
查看更新说明
Release v0.7.1: Multi-Scope Show Resolution & Metadata Hardening
Release
v0.7.1is a patch release resolving search/show scope disagreement through nearest-first bare ID fallback across scopes, ensuring safe round-trip preservation of custom metadata withinsourceslist items, fixing double-joined relative bundle root resolution inokf mcp, and cleaning up embedded struct selector linter warnings.
1. Bug Fixes & Improvements
Nearest-First Scope Fallback for Bare Concept IDs in
show&okf_show(#47, #61)- Problem:
okf show <id>and the MCP toolokf_showpreviously resolved bare IDs exclusively within the local project bundle (knowledge/). Concepts residing in user (~/.okf) or system (/etc/okf) memory surfaced in search results but could not be opened withokf show <id>. - Resolution: Implemented deterministic nearest-first fallback for bare concept identifiers:
project$\rightarrow$user$\rightarrow$system.- Vendor bundles are strictly excluded from bare-ID fallback to prevent cross-bundle ID collisions; vendor concepts continue to require explicit
@<bundle-id>/<concept-id>references. - Explicit scoped references (
okf://project/...,user:...,system:...,@...) remain exact and never fall back. - Human-readable CLI text output, CLI JSON output (
--json), and MCP responses now explicitly report the resolvedscope. Raw Markdown output (--raw) remains identical to disk contents.
- Vendor bundles are strictly excluded from bare-ID fallback to prevent cross-bundle ID collisions; vendor concepts continue to require explicit
- Credit: Reported by @DevMasterDru in #47; implemented by @gezerui888 in PR #61.
Safe Round-Trip Preservation of Custom
sourcesMetadata Keys (#57)- Problem: OKF v0.2 mandates that consumers must tolerate unknown metadata keys and preserve them across updates. While top-level unknown keys survived
okf update, non-standard keys within individualsourceslist items (e.g.checksum,accessed) were dropped by the parser and discarded during serialization. - Resolution: Extended
SourcewithExtra map[string]string(json:"extra,omitempty").ParseConceptcaptures unknown item keys andSerializeConceptdeterministically serializes them in canonical key order across mutations. - Credit: Reported with reproduction tests by @iSkyleya1 in #57.
Relative Nested Bundle Path Resolution in
okf mcp(#58)- Problem: When starting
okf mcp docs/knowledgewithOKF_MCP_ROOTunset, the server derivedrootDirfrom the bundle's parent (docs), but keptbundleDiras relative.resolveBundleDirjoined the relative bundle path to the root, resolving todocs/docs/knowledgeand causing all subsequent tool calls to fail. - Resolution:
RunMCPServerIOnow resolvesbundleDirto an absolute path viafilepath.Absbefore deriving the serverrootDirwhenOKF_MCP_ROOTis unset, preventing multi-segment relative path duplication while preserving strict server boundary confinement. - Credit: Reported and diagnosed with reproduction tests by @iSkyleya1 in #58.
Test Suite Cleanliness & Staticcheck QF1008
- Improvement: Removed redundant embedded field selectors on
ScopedConceptResult(res.Concept.Title$\rightarrow$res.Title), satisfyingstaticcheckrule QF1008 across all test suites.
2. Knowledge & Architecture
- Updated architecture/security-boundaries documenting multi-segment relative path normalization in MCP server root confinement.
- Updated architecture/metadata-roundtrip documenting
sourcesitem unknown key retention. - Updated architecture/registry-and-vendor-layering codifying bare ID scope fallback rules in
showandokf_show. - Synchronized knowledge/log.md with all
- Problem:
- v0.7.02026-10-20 · 2026-10-20 20:17 UTC
查看更新说明
Release v0.7.0: Bundle Quality Scorecards & Pre-Pull Quality Gating
Release
v0.7.0introduces OpenSSF-inspired Bundle Quality Scorecards (Phase 21), deterministic pre-pull quality gating (--min-score) with atomic filesystem rollback, machine-readable Scorecard telemetry inokf validate --json, and duplicate-safe ISO date log mutations.
1. Key Highlights & Features
Open Knowledge Quality Scorecards (
pkg/okf/scorecard.go)- Objective Quality Evaluation: Implements deterministic, reproducible quality evaluation (scores 0–100 and letter grades A through F) for decentralized OKF agent memory bundles without external network calls or tracking.
- Three Weighted Quality Pillars:
- Epistemic Maintenance (35% Weight): Evaluates freshness horizons and active concept lifecycles via
stale_after: YYYY-MM-DD. Concepts are penalized proportionally if allowed to expire without review. - Human Stewardship (35% Weight): Verifies human maintainer accountability (
verified.by: human/<handle>) to protect autonomous AI coding agents from recursive synthetic hallucinations. - Conformance Integrity (30% Weight): Strict DAG validation under OKF v0.2 §5 & §7. Broken markdown links are penalized -50% each; unindexed or orphaned concepts are penalized -30% each.
- Epistemic Maintenance (35% Weight): Evaluates freshness horizons and active concept lifecycles via
- CLI Inspection:
Emits formatted scorecard telemetry with grade, score breakdown, and human-readable signals.okf validate . --scorecard
Pre-Pull Quality Gating with Atomic Rollback (
okf pull,okf restore)- Policy Enforcement at Pull Time: Added
--min-score <N>tookf pullandokf restore:okf pull github.com/okf-memory/jwt --min-score 80 okf restore --min-score 85 - Atomic Safety: The bundle archive is unpacked into an isolated temporary directory and strictly validated against the required quality threshold before copying into
.okf/vendor/or updatingokf.lock. If validation or score checks fail, the transaction rolls back cleanly without leaving orphaned files.
Machine-Readable Scorecard JSON Telemetry
- Enhanced
okf validate --scorecard --jsonto include structuredscorecardpayloads:{ "scorecard": { "score": 100, "grade": "A", "maintenance": 100, "stewardship": 100, "integrity": 100, "signals": [ "all 4 concept(s) active and current (4 durable invariants)", "100% human stewardship (4/4 verified or authored by humans)", "strict conformance passed: 0 broken links, 0 orphans, valid DAG" ], "summary": "Quality Scorecard: Grade A (Score: 100/100) — M:100% S:100% I:100%" } }
Mutation Bookkeeping Hygiene
- Same-Day Log Entry Deduplication: Sanitized
pkg/okf/mutate.goso mutations on the same calendar day append under existing## YYYY-MM-DDheadings rather than creating duplicate date sections inlog.md.
2. Knowledge & Architecture
- Updated knowledge/roadmap/milestones.md marking Phase 21 as completed.
- Synchronized knowledge/log.md with all architectural changes and scorecard engine invariants.
3. Pre-Built Binaries
Pre-compiled standalone binaries for macOS, Linux, and Windows are available in GitHub Release assets:
- macOS (
darwin/arm64,darwin/amd64) - Linux (
linux/amd64,linux/arm64) - Windows (
windows/amd64,windows/arm64)
Install via Homebrew:
brew update brew upgrade okfFull Changelog
See commits between
v0.6.2...v0.7.0on GitHub. - v0.6.22026-10-19 · 2026-10-19 20:44 UTC
查看更新说明
Release v0.6.2: Semantic Index Merging in Hub Sync & Composite Vendor IDF
Release
v0.6.2is a patch release resolving multi-deviceindex.mdbookkeeping collisions during hub synchronization, fixing per-bundle IDF distortion across vendor packages in layered BM25 search, supporting numberedRelated Conceptsheadings during relationship mutations, and retiring standalone starter-pack distribution archives in favor of native CLI scaffolding.
1. Bug Fixes & Improvements
Semantic 3-Way Merge for
index.mdBookkeeping in Hub Sync (#52, #55)- Problem:
okf createandokf updateautomatically rewrite the parent folder'sindex.md. When two devices or agent harnesses concurrently created different concepts inside the same folder, they modified no common concept file, yet both updated that folder'sindex.md. Because the reconcile engine previously only auto-mergedlog.md, the shared index became a same-file collision: the remote index won, the local index was forked toindex.conflict-local.md, and the canonical index silently dropped the locally created concept. - Resolution: Added
MergeIndexContent(base, local, remote)inpkg/sync/index_merge.goand unified bookkeeping conflict resolution undermergeBookkeepinginpkg/sync/engine.go. Each* [Title](file.md) - Descriptionlisting line is merged as an independent record keyed by its link target using the persisted base tree from.okf/sync-state.json. Disjoint additions and removals from both sides apply cleanly, edits take precedence over concurrent deletions, and same-listing edits favor the remote version. Non-listing prose and frontmatter are merged as a whole, falling back to.conflict-local.mdonly when both sides modified the prose differently. - Credit: Reported and implemented by @cdcore09 in #52 and PR #55.
Composite BM25 IDF Across Vendor Packages in Layered Search (#54)
- Problem:
SearchLayered(pkg/okf/scope.go) previously executedSearchAdvancedon each vendor bundle individually before merging all vendor hits at priority 70. Because BM25 document frequency (df) and corpus size (N) were computed per bundle in isolation, a vendor package dedicated to a specific topic (where the topic term appears in nearly every concept, $df \approx N$) suffered severe IDF suppression compared to an unrelated vendor package mentioning that term once in passing ($df = 1$). - Resolution: Non-shadowed vendor concepts across all installed
.okf/vendor/bundles are now aggregated into a single composite vendor corpus prior to executingSearchAdvanced.Nanddfare computed uniformly across the entire vendor layer while preserving bundle-relative concept IDs for tokenization and preventing unintended cross-vendor ID shadowing. - Credit: Reported with root-cause analysis and reproduction script by @Khouloud-Kessentini in #54.
Numbered
Related ConceptsHeading Support in Mutations- Improvement: Enhanced Markdown section parsing in
pkg/okf/mutate.go(isRelatedHeading,AddRelationship,hasRelationship) to recognize arbitrary heading depths (H1–H6), strip leading section numbers (e.g.## 4. Related Concepts), terminate section bounds accurately on sibling or parent headings, and match both-and*list bullets.
Packaging & Agent Codex Updates
- Starter-Pack Archive Retirement: Retired standalone
okf-starter-pack.zipand.tar.gzrelease archives (Makefile,.github/workflows/release.yml) in favor of single-command scaffolding viaokf bootstrap. - AAG Commit Message Guidelines: Codified Conventional Commits constraints (
<= 50char imperative header) inAGENTS.mdusing Agent Action Grammar (AAG v0.1).
2. Knowledge & Architecture
- Created architecture/semantic-bookkeeping-merge documenting the 3-way per-lis
- Problem:
用户点评
登录用户的真实使用记录,可按版本和硬件筛选还没有人点评。第一个说出真实体验的人最有价值。
OKF Agent Memory
A Domain-Neutral, Git-Native Persistent Project Memory for AI Agents based on the Open Knowledge Format (OKF) v0.2.
🌟 Overview
Conversations with AI agents reset when context windows close. Valuable architectural decisions, domain discoveries, and operational facts are lost unless stored persistently.
Traditional approaches suffer from two fatal failure modes:
- The Prompt Monolith: Stuffing all domain knowledge and rules into
AGENTS.mdorCLAUDE.mdcreates massive context bloat and causes attention drift (agents ignore critical instructions). - The RAG Blindspot: Dumping behavioral rules into vector databases fails because agents never semantically search for operational constraints (e.g. formatting or security rules) during general tasks.
OKF Agent Memory resolves this dilemma with the Dual-Memory Agent Architecture (DMAA):
flowchart TD
subgraph PUSH["1. Normative Working Memory (Push Layer)"]
direction TB
C1["Canonical AGENTS.md (capped at 400 tokens)"]
C2["Domain Codex (Invariants, Ethics, Tone)"]
C3["OKF Memory Bridge (Deterministic Triggers)"]
C4["Agent Action Grammar (AAG) Micro-Syntax"]
end
subgraph PULL["2. Semantic Domain Memory (Pull Layer)"]
direction TB
O1["OKF v0.2 Knowledge Bundle (knowledge/)"]
O2["0 Tokens baseline in system prompt"]
O3["Selective Retrieval via okf_search / okf_show"]
O4["Persistent Graph of Decisions, Facts & Runbooks"]
end
INPUT["User Request"] --> PUSH
PUSH -->|Enforces Domain Codex & Triggers| AGENT["AI Agent (LLM)"]
AGENT -->|Selective Retrieval| PULL
PULL -->|Context & Facts| AGENT
AGENT --> OUTPUT["Deterministic Response"]
The Universal Composition Model
In DMAA, every agent configuration is structured by a universal composition:
$$\text{AGENTS.md} = \underbrace{\text{Domain Codex (AAG)}}{\text{Project Invariants, Tone, Guardrails}} + \underbrace{\text{OKF Memory Bridge}}{\text{Standardized Triggers: Search-Before-Write}}$$
- Layer 1: Normative Working Memory (Push Layer): A permanent, ultra-compact behavioral codex (capped at 400 tokens) expressed in Agent Action Grammar (AAG). Loaded at session start, enforcing zero-tolerance invariants.
- Layer 2: Semantic Domain Memory (Pull Layer): An OKF v0.2 knowledge bundle (
knowledge/) that consumes 0 tokens at baseline and is queried on-demand in microseconds.
flowchart TD
L1["1. OKF v0.2 Specification<br/>(Normative Markdown & YAML Format)"]
L2["2. Agent Memory Convention & DMAA<br/>(Dual-Memory Model, Search-Before-Write, Trust)"]
L3["3. Agent Skill & AAG Codex<br/>(Agent Action Grammar, Workflows, Triggers)"]
L4["4. Tooling Layer: Go Library & CLI<br/>(Deterministic Parsing, Validation, BM25, MCP)"]
L5["5. Project Knowledge Corpus<br/>(knowledge/ OKF Bundle)"]
L1 --> L2
L2 --> L3
L3 --> L4
L4 --> L5
⚡ Key Highlights
- Dual-Memory Cognitive Architecture (DMAA): Separates normative push working memory (
AGENTS.mdcodex) from semantic pull domain memory (knowledge/bundle), completely eliminating prompt bloat. - Agent Action Grammar (AAG): Ultra-compact, deterministic ASCII micro-syntax saving ~78–85% tokens compared to natural language prompt instructions.
- Blazing Fast Performance (<300µs Search, ~4ms Graph Validation): In-memory BM25 retrieval and bundle validation execute in microseconds without VM spin-up or network roundtrips.
- 100% Git-Native & Zero Vendor Lock-in: Everything is version-controlled plain text. Inspect, audit, and review your agent's memory using standard
git diffandgit log. No external database required. - Zero API Costs for Memory Retrieval: Local lexical BM25 indexing eliminates recurring vector embedding API costs and network roundtrips.
- Built on Google OKF v0.2: Uses the open standard format for agent knowledge with full support for provenance (
sources), trust tiers (generatedvs.verified), and lifecycle metadata (status,stale_after). - Solves Context Bloat & Memory Rot: Employs Progressive Disclosure (hierarchical
index.mdfiles and link graphs) so agents only load the exact concepts they need. - Search-Before-Write Principle: Mandates querying existing memory before authoring, preventing concept duplication and hallucinated divergence.
- Governance & Code-to-Knowledge Binding: Bind architecture decisions directly to source files via
code_refsand query active constraints/holds via--for-pathbefore modifying code. - Truly Domain-Neutral: Designed for Software Engineering, Coaching, Scientific Research, Literature Reviews, and Operations.
📊 Performance Benchmarks
Built in Go with zero external dependencies, okf is engineered for high-frequency agent tool calling loops:
| Benchmark Metric | Python / Vector DB Runtimes (Mem0, Letta) | Deno / Node.js Tooling | OKF Agent Memory (Go) |
|---|---|---|---|
| Concept Search Latency | 150ms – 800ms (Embedding API + Vector DB) | 40ms – 120ms | < 300 µs (Microseconds, In-Memory BM25) |
| Full Corpus Parse & Graph Validation | 200ms – 1.5s | 80ms – 250ms | ~4.0 ms (50+ concepts, bidirectional graph) |
| Process Cold-Start Overhead | 250ms – 600ms (Python VM boot) | 80ms – 180ms (V8 / Deno boot) | < 4 ms (Compiled Single Binary) |
| Retrieval Cost per 1,000 Queries | ~$0.10 – $0.50 (Embedding tokens) | $0.00 | $0.00 (Zero API cost, fully local) |
| Memory Footprint (RSS) | ~120 MB – 350 MB | ~60 MB – 140 MB | < 15 MB |
[!TIP] Reproduce Locally with your own LLM: We provide an automated benchmark runner in pure Go to verify Time-To-First-Token (TTFT) speedups and -80% token reduction on your local hardware (LM Studio / Ollama with Gemma, Qwen, Llama). Run
make benchmarkor explore the Progressive Disclosure Benchmark Suite.
🚀 Quickstart
1. Build the Tooling
Clone the repository and compile the standalone okf executable:
make build
This generates the standalone binary at bin/okf.
2. Basic CLI Commands
# Validate bundle conformance, graph connectivity, and description drift
./bin/okf validate knowledge --strict --drift
# Evaluate bundle quality scorecard (3 pillars: maintenance, stewardship, integrity)
./bin/okf validate knowledge --scorecard
# Gate bundle quality in CI or pre-commit pipelines (fails if score < 80)
./bin/okf validate knowledge --min-score 80
# Search concepts via in-memory BM25 scoring
./bin/okf search "architecture layers" knowledge
# Discover constraints and active holds governing a specific source file before editing
./bin/okf search --for-path pkg/okf/types.go knowledge
# Inspect a concept and its relationships (with --json support)
./bin/okf show architecture/layers knowledge --json
# Create a new concept with automated log.md and index.md bookkeeping
./bin/okf create decisions/auth-flow knowledge \
--type Decision \
--title "OAuth2 Authorization Flow" \
--desc "Standardized on PKCE for client authentication."
# Update an existing concept
./bin/okf update decisions/auth-flow knowledge \
--desc "Updated OAuth2 PKCE token refresh interval."
# Bootstrap full agent memory stack into any target project
./bin/okf bootstrap /path/to/project --name "My Project"
# Initialize only a bare OKF bundle in any directory
./bin/okf init my-project/knowledge
# Zero-Knowledge Sync: initialize vault and print Emergency Kit
./bin/okf hub init-vault knowledge
# Zero-Knowledge Sync: push or sync changes with the Hub (optional: --token or OKF_HUB_TOKEN)
./bin/okf hub push knowledge --password "pass" --secret-key "XXXX-..." --auth-token "my-token"
./bin/okf hub sync knowledge --password "pass" --secret-key "XXXX-..."
# Pull external knowledge bundles from OKF Registry (registry.okf-memory.dev) or Git
./bin/okf pull nextjs-15
./bin/okf pull nextjs-15 --min-score 80 # Gate bundle quality before installation
./bin/okf pull peter/django-5-rules
./bin/okf pull github.com/acme/[email protected]
# Restore all locked vendor bundles in fresh environments
./bin/okf restore
./bin/okf restore --min-score 80 # Gate all restored bundles
# Inspect and manage installed vendor bundles
./bin/okf vendor list
./bin/okf vendor remove nextjs-15
3. Multi-Scope Memory Layering & Scoped Resolution
OKF Agent Memory organises knowledge across four deterministic memory scopes. Higher layers strictly shadow identical concept IDs in lower layers during search, ensuring local project decisions always take precedence over external upstream packages or machine baselines:
flowchart TD
subgraph Scopes ["OKF 4-Tier Memory Hierarchy"]
P["<b>Project</b> (Priority 100)<br/>Prefix: <i>none</i> (e.g. decisions/auth)<br/>Location: ./knowledge/"]
V["<b>Vendor</b> (Priority 70)<br/>Prefix: @bundle/... (e.g. @nextjs-15/routing)<br/>Location: .okf/vendor/"]
U["<b>User</b> (Priority 50)<br/>Prefix: user:... (e.g. user:guidelines/style)<br/>Location: ~/.okf/"]
S["<b>System</b> (Priority 10)<br/>Prefix: system:... (e.g. system:corp/policy)<br/>Location: /etc/okf/"]
end
P -->|shadows| V
V -->|shadows| U
U -->|shadows| S
Scope Specification Matrix
| Scope | Link / Reference Syntax | Canonical URN | Storage Location | Priority | Precedence & Rules |
|---|---|---|---|---|---|
project | decisions/auth.md | (bundle relative) | ./knowledge/ | 100 | Local Project Memory. Authoritative SSoT for current repository; strictly shadows identical IDs from vendor, user, and system layers. |
vendor | @nextjs-15/routing.md@peter/django-rules/auth.md | okf://@nextjs-15/routingokf://@peter/django-rules/auth | .okf/vendor/<bundle>/ | 70 | External Packages. Pinned dependencies pulled from OKF Registry (registry.okf-memory.dev) or Git. Shadows user and system. |
user | user:guidelines/style.md | okf://user/guidelines/style | ~/.okf/ | 50 | Personal Agent Memory. Developer preferences and cross-project notes. Shadows system. |
system | system:corp/policies.md | okf://system/corp/policies | /etc/okf/ | 10 | Enterprise / Machine Memory. Infrastructure baselines and compliance policies. |
Filtering by Scope in Search & Show
# Default (--scope all): Search across all layers with automatic shadowing & priority ranking
./bin/okf search "authentication"
# Search strictly within vendor packages
./bin/okf search "routing" --scope vendor
# Search strictly within local project memory
./bin/okf search "architecture" --scope project
# Search user or system layers
./bin/okf search "style" --scope user
./bin/okf search "compliance" --scope system
# Inspect concepts across scopes
./bin/okf show decisions/auth # Local project concept
./bin/okf show @nextjs-15/decisions/routing # Vendor package concept
./bin/okf show user:guidelines/style # Personal user concept
./bin/okf show system:corp/policies # System compliance concept
Bundle Scope Isolation (scopes in knowledge/index.md)
By default, all four scopes (project, vendor, user, system) are active. To isolate a project (e.g. preventing agents in a client or open-source repository from accessing personal ~/.okf/ notes), declare an explicit scopes list in the root knowledge/index.md frontmatter:
---
okf_version: "0.2"
scopes: [project, vendor]
---
- Only the listed scopes are searched under
--scope allor bare-IDokf showfallback. - Explicit queries targeting a disabled scope (e.g.
okf search --scope userorokf show user:secret) are rejected with an error. - Empty (
scopes: []) or non-canonical scope names fail bundle loading and validation immediately (fail-closed).
4. Bundle Quality Scorecards (OpenSSF-Style)
Evaluate knowledge bundles across three weighted pillars to eliminate "reproducibly wrong" context without maintenance chores:
- Epistemic Maintenance (35%): Invariant version-bound facts without
stale_afterremain 100% valid by default; penalties apply only to lapsed review deadlines or deprecated status. - Human Stewardship (35%): Strictly distinguishes verified human sign-offs (
verified.by: human/*oruser/*) from unreviewed synthetic bot dumps. Non-human verifications earn 0 stewardship points. - Graph Integrity (30%): Strict OKF v0.2 graph health (0 broken links, 0 orphans, valid DAG).
# Human-readable scorecard breakdown with Grade (A-F)
./bin/okf validate knowledge --scorecard
# Machine-readable JSON output
./bin/okf validate knowledge --scorecard --json
# Quality gating in CI (fails with exit code 1 if score < 80)
./bin/okf validate knowledge --min-score 80
# Pre-pull quality gating (aborts installation & rolls back if score < 80)
./bin/okf pull nextjs-15 --min-score 80
5. Bootstrapping Agent Memory in Any Project
Scaffold the complete OKF Agent Memory architecture into any new or existing repository with a single command:
# Bootstrap full memory stack into target project
./bin/okf bootstrap /path/to/my-project --name "My Service"
This automatically sets up:
knowledge/— OKF v0.2 compliant persistent memory bundle (index.md,log.md).agents/skills/okf-memory/— Embedded agent skill definition and capability guidesAGENTS.md— Project-tailored operating instructions for AI coding agentsMakefile— Convenience tasks for validation (make validate) and search (make search q="...")
6. Running as an MCP Server
okf ships with a native Model Context Protocol (MCP) server over stdio to seamlessly connect with Claude Code, Cursor, Codex, and other agent platforms:
./bin/okf mcp knowledge
Example MCP Configuration (claude_desktop_config.json or Cursor):
{
"mcpServers": {
"okf-memory": {
"command": "/path/to/okf-agent-memory/bin/okf",
"args": ["mcp", "/path/to/project/knowledge"]
}
}
}
📂 Repository Structure
okf-agent-memory/
├── .agents/ # Active agent skills and agent configuration
│ └── skills/okf-memory/ # Authoritative OKF memory skill for AI agents (Single Source of Truth)
├── benchmarks/ # Progressive disclosure benchmark suite & hardware test data
│ ├── data/ # Monolith docs vs OKF bundle test fixtures
│ └── results/ # Reproducible benchmark logs across 8+ local & cloud LLMs
├── cmd/
│ ├── okf/ # Standalone CLI and embedded MCP server (`stdio`)
│ └── okf-benchmark/ # Automated benchmark runner for LLM TTFT & token measurements
├── docs/ # Guides, specifications, architecture & release playbook
│ ├── README.md # Central documentation index & navigation
│ ├── guides/ # User guides, CLI/MCP reference & AI instruction best practices
│ ├── spec/ # OKF convention v0.1, compatibility analysis & architecture RFCs
│ ├── security/ # Data governance, secret prevention & adversarial security audits
│ ├── project/ # Project roadmap, release playbook & multi-agent testing
│ └── releases/ # Versioned release notes & changelog archive (v0.1.0 - v0.8.0)
├── examples/ # Domain-neutral reference DMAA projects (AGENTS.md + OKF v0.2 knowledge/)
│ ├── books/ # Literature & editorial analysis repository
│ ├── coaching/ # Executive coaching & client session repository
│ └── software/ # Microservices architecture & ADR engineering repository
├── knowledge/ # Project's own OKF v0.2 persistent memory bundle
│ ├── index.md # Root progressive disclosure index (okf_version: "0.2")
│ ├── log.md # Dated change log (ISO 8601 YYYY-MM-DD)
│ ├── project/ # Overview & value propositions
│ ├── architecture/ # 5-tier architecture, governance model & decisions
│ ├── convention/ # Principles & lifecycle workflows
│ └── roadmap/ # Milestones
├── packaging/ # Distribution packaging
│ └── homebrew/ # Official Homebrew formula & tap instructions
├── pkg/
│ ├── lock/ # Zero-dependency okf.lock parser & serializer
│ ├── okf/ # Core library (parser, validator, BM25, MCP, bootstrap)
│ │ └── assets/ # Embedded bootstrap templates & skills mirrored via `make sync-assets`
│ ├── registry/ # Decentralized OKF Registry client & archive unpacker
│ ├── sync/ # Blind sync engine, 3-way reconcile & hub client/server
│ └── vault/ # AES-256-GCM envelope crypto, Argon2id KDF & CAS blind storage
├── AGENTS.md # Operating instructions for AI coding agents
├── CONTRIBUTING.md # Contribution guidelines & development workflow
├── CONTRIBUTORS.md # Community contributors & acknowledgements
├── CODE_OF_CONDUCT.md # Contributor Covenant v2.1 code of conduct
├── Makefile # Build, test, lint, validation & release targets
├── LICENSE # MIT License
├── README.md # Main repository documentation
└── SECURITY.md # Security policy & reporting guidelines
🧪 Testing & Verification
Run the full test suite and validate the repository's self-documenting knowledge bundle:
make check
📖 Further Documentation
- Documentation Index — Central directory of all project documentation.
- Getting Started Guide — Comprehensive onboarding guide for agents and humans.
- CLI & MCP Reference — Complete command-line and protocol tools reference.
- Dual-Memory Agent Architecture RFC — Cognitive 2-layer agent memory model (Push codex + Pull knowledge).
- Agent Action Grammar RFC — Deterministic, token-efficient AAG micro-syntax specification for
AGENTS.md. - Agent Instruction Best Practices — Guide to deterministic instruction design and token optimization.
- OKF Agent Memory Convention v0.1 — Behavioral rules and lifecycle specification.
- Contributing Guide — Development setup, quality gates, and pull request standards.
- Security & Privacy Guidelines — Data governance, secret prevention, and PII protection rules.
- Multi-Agent Testing & Evaluation — Test scenarios, compatibility matrix, and benchmarks.
- Project Roadmap & Milestones — Phased development plan.
- Release Playbook — Versioning, CI/CD pipeline, and distribution procedures.
- Release Notes & History — Versioned changelogs and historical release notes archive.
- OKF v0.2 Compatibility Matrix — Specification validation analysis.
- Why OKF Agent Memory? — Detailed value proposition & differentiators.
- Alternatives & Ecosystem Comparison — Comparison with Mem0, Letta, and ad-hoc markdown files.
👥 Contributors
Thank you to all the wonderful contributors who have helped build and refine OKF Agent Memory!
Contributions of all kinds are warmly welcomed! See CONTRIBUTING.md and CONTRIBUTORS.md for details.
💖 Support & Sponsoring
If you find OKF Agent Memory valuable for your autonomous agent workflows, consider sponsoring the project on GitHub to help support continuous development, security hardening, and spec compliance!
📄 License
MIT License. See LICENSE for details.