capsa

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 2, 2026 License: Apache-2.0 Imports: 21 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

capsa

CI Release Go Version License

capsa is an encrypted memory and knowledge base for AI agents. It stores OKF (Open Knowledge Format) markdown bundles in PostgreSQL with pgvector, seals the content at rest with AES-256-GCM, and serves it to agents over MCP (Streamable HTTP): semantic search by meaning across Russian and English, whole-file reads, versioned writes, bearer tokens with scopes. Nothing is hosted but the database — the binary carries its schema and talks to any PostgreSQL with pgvector.

Why

Four things, each of which is a choice rather than a feature checkbox:

  • Encrypted at rest. A dump of the database is not a knowledge leak. Concept text, chunks, versions, raw notes and even the agents' search queries are sealed per value with AES-256-GCM, each bound to its row and column. The vectors and the structural columns (paths, types, tags, statuses) stay plaintext so filters still run. See Encryption for exactly what that means and what it does not.
  • Postgres only. No Qdrant, no Redis, no object store. One database to back up, one thing to operate; the vectors sit beside the rows the filters need. Migrations are embedded and applied at start.
  • OKF is the format. A knowledge base is a directory of typed markdown files with YAML frontmatter and links — readable by agents, diffable by people, exportable 1:1 from the database. capsa is a consumer of the format, not a lock-in: capsa export gives you the bundle back.
  • Local or hosted embeddings, and no LLM in the retrieval path. Point CAPSA_EMBEDDINGS_BASE_URL at a local Ollama or TEI and the text never leaves your host; point it at OpenRouter for the best-measured model. A search is a vector comparison and a sort — no model call per query, no tokens, milliseconds. An optional cross-encoder reranker can be switched on as a second stage.

Features

  • MCP server at /mcp — Streamable HTTP, stateless, bearer-token protected. Seven tools: search, get, list, remember, put, deprecate, whoami.
  • Admin REST API at /api/admin/* — bundles, concepts, episodes, tokens, stats, query log, audit log. Health at /healthz and /readyz.
  • Semantic search — exact cosine scan over halfvec(1024) chunk embeddings; filters on bundle, type, tags and status; a key-term boost so identifiers stay findable; at most two chunks per concept in the top five; a full-text fallback when the embedding provider is down; an advisory low_confidence flag; an optional reranker stage.
  • OKF v0.3 in and out — import a bundle directory, export it back verbatim. Concepts are versioned (a changed file is a new version, unchanged is a no-op), chunked by headings (700–1400 bytes), linked into a graph used for navigation.
  • Tokens with scopes — read, write, admin, optionally restricted to a list of bundles. Shown once, hashed at rest.
  • Content sealing at rest — capsa keygen, capsa encrypt --yes, capsa decrypt --yes; the server refuses a wrong key or sealed content without a key at startup.
  • Audit and query logs — every write is audited; every search is logged with mode, latency and top score.
  • Operations in the binary — doctor (check the database, --fix creates pgvector), ready (container healthcheck), index (embed pending chunks), stats.

Quick start

Get the binary one of three ways:

# from GitHub Releases — capsa_<version>_<os>_<arch>.tar.gz (.zip on Windows),
# linux/darwin/windows amd64+arm64, with checksums.txt
# https://github.com/svetlovtech/capsa/releases/latest

# from source (Go 1.27)
go install github.com/svetlovtech/capsa/cmd/capsa@latest

# with Docker: PostgreSQL (pgvector) + capsa on http://127.0.0.1:8116
git clone https://github.com/svetlovtech/capsa.git && cd capsa
docker compose up -d

You need a PostgreSQL with pgvector 0.7.0 or newer for the content — halfvec arrived in 0.7.0. pgvector/pgvector:pg16 is the easy way; capsa doctor tells you what is missing and how to fix it. With compose, the CLI runs inside the container: docker compose exec capsa /capsa <command>; settings go in a .env next to the compose file.

Bare capsa prints help. The server is capsa serve.

The five-minute path
# 1. a content key. Put it in a password manager BEFORE anything is sealed with it:
#    a lost key is a lost database.
capsa keygen
# {"CAPSA_CONTENT_KEY": "…", "note": "…"}

# 2. give it to capsa. A chmod 600 file (CAPSA_CONTENT_KEY_FILE) is preferred over the variable.
export CAPSA_CONTENT_KEY='…'            # the value from step 1

# 3. point it at a database and check it — --fix creates the pgvector extension when the role may
export CAPSA_DATABASE_URL='postgres://capsa:capsa@127.0.0.1:5432/capsa?sslmode=disable'
capsa doctor --fix

# 4. an embeddings endpoint. With a key set, full-text search is off, so search needs one.
#    Local (no key, text stays on your host) — Ollama:
export CAPSA_EMBEDDINGS_BASE_URL=http://127.0.0.1:11434/v1 CAPSA_EMBEDDINGS_MODEL=bge-m3 CAPSA_EMBEDDINGS_QUERY_INSTRUCTION=
#    Or hosted (OpenRouter, default model):
# export CAPSA_EMBEDDINGS_BASE_URL=https://openrouter.ai/api/v1 CAPSA_EMBEDDINGS_API_KEY=sk-or-…

# 5. run the server (migrations first, then /mcp, /api/admin, /healthz, /readyz)
capsa serve &

# 6. a token for an agent — the plaintext is shown once
capsa token create --name agent --scopes read,write

# 7. put some knowledge in and make sure it was embedded
capsa import --dir testdata/smoke --slug smoke     # a tiny OKF bundle to try; --wrap also takes plain markdown
capsa stats                                       # pending_chunks should be 0

Every setting can also live in a .env file in the working directory (copy .env.example); the file wins over the environment.

Setting up with an AI agent

Hand the setup to the agent that will use the memory: skills/capsa-setup/SKILL.md is a step-by-step skill (preflight, three install paths, configure, verify, tokens, MCP client, import, hand-over, troubleshooting). It covers the fully native path — PostgreSQL with pgvector installed on the host, the superuser creating the extension because pgvector is not "trusted", Ollama as a native app, systemd/launchd units to keep the server running — as well as Docker Compose and the plain binary.

Connect an MCP client

Claude Code:

claude mcp add --transport http capsa http://127.0.0.1:8116/mcp --header "Authorization: Bearer mem_…"

Claude Desktop, Cursor, Windsurf, Cline — a JSON server entry under mcpServers:

{
  "mcpServers": {
    "capsa": {
      "type": "http",
      "url": "http://127.0.0.1:8116/mcp",
      "headers": { "Authorization": "Bearer mem_…" }
    }
  }
}

Streamable HTTP clients call the type http or streamable-http; some omit it and take url alone. OpenCode uses its own shape, type: "remote", under mcp:

{
  "mcp": {
    "capsa": {
      "type": "remote",
      "url": "http://127.0.0.1:8116/mcp",
      "headers": { "Authorization": "Bearer mem_…" }
    }
  }
}

The URL and the header are the same everywhere. Then, in the agent's words: search the memory before you guess. The tools answer JSON.

MCP tools

Every answer is JSON text. Paths are OKF concept ids: the bundle-relative file path without .md (e.g. services/chat).

Tool Scope Parameters What it does
memory_search read query (required) — what to look for, in any language
bundle — one knowledge base; omit to search every bundle the token may read
type — only concepts of this OKF type (e.g. Host, Service, Playbook)
tags — array; concepts carrying at least one of them
limit — integer 1–50, default 8
include_deprecated — boolean, default false
Semantic search over concepts. Returns the best-matching chunks with their concept path, score, status, trust tier and staleness, plus mode (vector, fts or vector+rerank), low_confidence and, when something fell back, fallback_reason. low_confidence=true means the answer may have nothing behind it: read the chunks or rephrase.
memory_get read bundle, path (required) One concept: its whole markdown file (frontmatter + body), status, trust tier, staleness, version, and the concepts linked to and from it.
memory_list read bundle (required)
prefix — only paths under it (e.g. services/)
include_deprecated — default false
Lists concepts: path, type, title, status. To see what a bundle holds before searching.
memory_remember write bundle, text (required) Appends a raw note to the bundle's episode log: what happened, what you tried, what the user prefers (≤ 64 KiB). The log is append-only and memory_search does not search it; nothing consolidates it into concepts yet. Good for session events and context. For knowledge that must be found later, use memory_put.
memory_put write bundle, path, content (required) Writes a concept as a whole OKF file: YAML frontmatter with at least a non-empty type, then markdown. A new path creates it; the same path with changed content stores a new version; unchanged content is a no-op. This is the tool for knowledge the agent must find later.
memory_deprecate write bundle, path (required)
superseded_by — the concept id that replaces it
Retires a concept: status: deprecated in its frontmatter. Deprecated concepts are kept for links and history and drop out of search results.
memory_whoami any valid token — The token's name, scopes and the bundles it may touch.

Scopes: read covers the first three tools, write the next three, admin the REST API below. A token without the scope gets an error result naming the scope it lacks.

CLI reference

Cobra: flags take two dashes, with one-letter shorthands where listed. Every command reads the CAPSA_* settings (environment or .env). Output is indented JSON on stdout; diagnostics go to stderr. Exit codes: 0 success, 1 failure, 2 usage error. Every command that opens the database applies the migrations first, so import works before the server has ever started.

Command Flags What it does
capsa — Prints help.
capsa serve — Runs the server: migrations, then /mcp, /api/admin, /healthz, /readyz, and the indexing worker (every CAPSA_INDEX_INTERVAL_SECONDS) until SIGINT or SIGTERM.
capsa ready — Probes /readyz of a running server and exits with its answer; prints ok. The container healthcheck. Probes loopback only (READINESS_ADDR overrides the address).
capsa doctor --fix (default false) Examines the database the way the server will use it: URL, connection, PostgreSQL version (13+), pgvector present / new enough (0.7.0+) / created in this database, the role's privilege to create tables, and the schema. --fix creates the pgvector extension when the server has it and the role may; nothing else is changed. Exit 1 when the server cannot start against this database.
capsa token create --name/-n (shown in logs)
--scopes/-s (default read; comma-separated read,write,admin)
--bundles/-b (comma-separated slugs; empty = all)
Creates a token. The secret is shown once.
capsa token revoke --name/-n Revokes the token with that name.
capsa import --dir/-d (required: the OKF markdown tree)
--slug/-s (required: the bundle slug, [a-z0-9_-] up to 100 chars)
--prune/-p (default false: remove concepts the directory no longer holds)
--index/-i (default true: embed the chunks left pending after the import)
--wrap/-w (default false: also import plain markdown files — no OKF type — as concepts with synthesized frontmatter)
Stores a bundle directory. Unchanged concepts (same content hash) are left alone, so a re-import is cheap. Reports concepts, created, updated, unchanged, removed, edges, pending_chunks.
capsa export --slug/-s (required)
--dir/-d (required: output directory)
Writes a bundle back as an OKF directory, each concept exactly as stored, plus a generated index.md.
capsa index — Embeds every pending chunk (what a write or an import left while the embeddings endpoint was down).
capsa stats — Bundles with indexing state, query-log aggregates per tool, token count.
capsa keygen — Prints a fresh content key. Needs no configuration.
capsa encrypt --dry-run, --yes/-y Seals every stored content value in place — the rows written before the key existed. Needs CAPSA_CONTENT_KEY; re-runnable. Run --dry-run first.
capsa decrypt --yes/-y (required: confirms the rewrite)
--dry-run
Opens every sealed value — the rollback, or the step before a key change. Without --yes it reports what it would change and exits 1.
capsa version, capsa --version — Print the version.

Configuration

Settings come from the environment with the CAPSA_ prefix and, when it exists, from a .env file in the working directory — the file wins (ENV_FILE names another file). Copy .env.example to start.

Variable Default Meaning
CAPSA_DATABASE_URL — (required) postgres://user:password@host:5432/capsa?sslmode=…. The database capsa owns; it needs pgvector. The binary creates and migrates the schema itself.
CAPSA_HTTP_ADDR 127.0.0.1:8116 Where the server listens: MCP at /mcp, admin API at /api/admin, health at /healthz and /readyz. Loopback by default — expose it deliberately, behind TLS.
CAPSA_LOG_LEVEL info debug, info, warn or error.
CAPSA_LOG_FORMAT text text for a terminal, json for a log pipeline.
CAPSA_EMBEDDINGS_BASE_URL (empty) An OpenAI-compatible /embeddings base — any provider, see Embeddings. Empty turns vector search off: the server searches full-text only.
CAPSA_EMBEDDINGS_API_KEY (empty) Bearer key for a hosted provider. Empty for a local endpoint.
CAPSA_EMBEDDINGS_MODEL qwen/qwen3-embedding-8b The OpenRouter default is the winner of the retrieval benchmark. Recorded in the bundle's settings; switching the model means re-indexing. Required when an API key is set.
CAPSA_EMBEDDINGS_DIM 1024 Must be 1024 — the stored halfvec(1024) width. Other sizes are refused with a clear message ("needs a migration first").
CAPSA_EMBEDDINGS_QUERY_INSTRUCTION Instruct: Given a web search query, retrieve relevant passages that answer the query\nQuery: Put before every query text (what Qwen3-Embedding expects). Set it to an empty value for bge-m3, which takes no instruction; e5 wants query:.
CAPSA_EMBEDDINGS_DOC_PREFIX (empty) Put before every document text (e5 wants passage:).
CAPSA_EMBEDDINGS_INPUT_TYPE true Sends `input_type: query
CAPSA_INDEX_INTERVAL_SECONDS 120 How often the worker embeds chunks left pending (a write while the embeddings endpoint was down).
CAPSA_RERANK_BASE_URL (empty) Optional reranker endpoint (any provider with an HTTP /rerank route). Empty = no reranking. See Reranking.
CAPSA_RERANK_API_KEY (empty) Key for a hosted reranker; empty for a local one.
CAPSA_RERANK_MODEL (empty) The reranker's model name, as the provider spells it.
CAPSA_RERANK_API inferred from the host Request shape: generic, voyage or cohere. Inferred: OpenRouter, Jina, vLLM, TEI → generic; api.voyageai.com → voyage; api.cohere.com → cohere.
CAPSA_RERANK_CANDIDATES 20 How many top vector candidates are sent to the reranker.
CAPSA_RERANK_MIN_SCORE 0 (off) Drop reranked candidates below this relevance; 0 keeps everything the provider scored.
CAPSA_CONTENT_KEY (empty) The content key: 32 bytes in base64, from capsa keygen. Empty stores plaintext. Set it before storing anything that must be sealed.
CAPSA_CONTENT_KEY_FILE (empty) A file (chmod 600) holding the key. Preferred over the variable, and wins when both are set. Must be readable by its owner alone and non-empty.

Two more variables, not in .env.example because they are not server settings: ENV_FILE (another env file than .env) and READINESS_ADDR (what capsa ready probes). The tests read DB_PORT, DB_USER, DB_PASSWORD, DB_HOST, DB_NAME, DB_SSLMODE — see Development.

Validation at load: the URL must be postgres://; the base URLs must be http(s)://; the dimension must be 1024; the log level and format must be one of the listed values; the key must decode to 32 bytes that are not one repeated byte; the key file must be private and non-empty. A wrong value is an error at start, not a silent fallback.

Embeddings

Any OpenAI-compatible /embeddings endpoint works. The stored vectors are 1024-wide, so the model must produce 1024 dimensions (MRL models take dimensions: 1024); other sizes are refused at startup with a clear message. Vectors of different models are not comparable — switching the model means re-indexing (capsa import again, or a new bundle).

Provider CAPSA_EMBEDDINGS_BASE_URL CAPSA_EMBEDDINGS_MODEL Key Notes
OpenRouter https://openrouter.ai/api/v1 qwen/qwen3-embedding-8b (default) yes (CAPSA_EMBEDDINGS_API_KEY) The best-measured model (strict R@5 93 %, MRR 0.804). 1024 dims through MRL; keeps the default query instruction.
Ollama, native app or Docker http://127.0.0.1:11434/v1 bge-m3 or qwen3-embedding:0.6b no Both 1024 dims. bge-m3 takes no query instruction: set CAPSA_EMBEDDINGS_QUERY_INSTRUCTION= (empty). The Qwen3 model keeps the default. Check the size with ollama show <model> | grep embedding.
Text Embeddings Inference (TEI) http://127.0.0.1:8080/v1 whatever TEI serves no Local; no external dependency.
OpenAI https://api.openai.com/v1 text-embedding-3-small or text-embedding-3-large yes Both take dimensions: 1024 — CAPSA_EMBEDDINGS_DIM is already 1024.

A local endpoint keeps every chunk text and query on your host; a hosted one sees them. See Security.

Reranking (optional)

With CAPSA_RERANK_BASE_URL set, memory_search sends its top CAPSA_RERANK_CANDIDATES (default 20) vector candidates to the rerank provider — a cross-encoder that scores each chunk against the query — and returns them in the provider's order; the result reports "mode": "vector+rerank". CAPSA_RERANK_MIN_SCORE (default 0, off) drops candidates the provider scored below it. A failing reranker never fails the search: it falls back to the vector order and says so in the result's fallback reason.

The request shape is inferred from the host (CAPSA_RERANK_API overrides it): OpenRouter, Jina, vLLM and TEI speak generic; Voyage voyage; Cohere cohere. Off by default — vectors alone measured well (above), and a reranker is one more network call per query. Ollama has no rerank endpoint, so a local reranker is TEI or vLLM. The reranker sees the query and the candidate texts in plaintext, like the embeddings provider.

Encryption

The model. With a key set, every content value is sealed on its way into the database and opened on its way out — AES-256-GCM, a random nonce per value, stored as enc1:<key-id>:<base64> in the existing text columns. The associated data binds each value to its row and column, so a ciphertext copied to another row does not open. The key id (8 hex characters of the key's fingerprint) is recorded in every value, which is what makes a rotation possible and a wrong key legible.

Sealed Plaintext, by design
concept title, description, frontmatter, body, content · version content · chunk heading, text · episode content · query-log query path, type, tags, status, stale_after, trust_tier, superseded_by, bundle slug/title/description, content_hash, vectors (embedding), tokens (hash + prefix), audit log, query-log metadata
  • The embedding provider sees plaintext; the database does not. A vector cannot be computed over ciphertext. A local endpoint keeps that text on your host; a hosted one does not. The same goes for the reranker, when on.
  • With a key, full-text search is off. The tsv column stores the words of every chunk, which is content; sealed chunks have no tsv. Search comes from the vector index only — which makes the embeddings endpoint a hard dependency when content is sealed (a provider outage returns an empty fts result, not an error).
  • Startup refuses a wrong key, or sealed content without a key. It opens one sealed value of every table before serving. Plaintext rows with a key are a warning with the count, not an error.

Order of operations: key first, then store.

capsa keygen                                            # 1. make the key; keep it in a password manager NOW
export CAPSA_CONTENT_KEY_FILE=/etc/capsa/content.key    # 2. a chmod 600 file, preferred over the variable
capsa doctor --fix && capsa serve                       # 3. only now import what must be sealed

Rows written before the key existed stay plaintext until capsa encrypt --yes rewrites them (the server logs how many are left at every start). A key is never generated implicitly at first start: one that was generated and then lost takes the database with it.

Legacy rows. capsa encrypt --yes (it only counts without --yes, and proves first that the key opens what is already sealed) seals every plaintext content value in place, in one transaction with FOR UPDATE on every table, so a concurrent write waits and then sees the rewritten row instead of being overwritten. --dry-run first counts. Run it when agents are idle: a connection that holds content rows for 30 s fails the run with a message, not a half-rewrite.

Rollback. capsa decrypt --yes is the inverse: plaintext back into every row. It refuses to run without --yes. The same two commands are a key rotation: decrypt --yes with the old key, encrypt with the new one.

Backup advice. Back up the key with the same care as the database, separately from it. A pg_dump of a sealed database is still sealed; a dump made while rows were plaintext is not. capsa export writes plaintext markdown (files 0600) — treat the output directory as you treat the key file. And again: a lost key is a lost database.

Security

See SECURITY.md for the threat model (what sealing protects against — a database or host compromise — and what it does not: the process that holds the key, the embeddings and rerank providers, anyone with a valid token, metadata), the exact list of sealed and plaintext columns, how tokens are stored (scopes, bundle restriction, shown once, SHA-256 at rest), and how to report a vulnerability (GitHub Private Vulnerability Reporting; do not open public issues).

In short: loopback by default, no default tokens, no TLS built in — put a reverse proxy in front if you expose it.

Retrieval quality

75 blind questions over a real OKF bundle (899 files): 70 answerable with a gold file each, 5 unanswerable. The questions were written by a separate agent that knew nothing of the retrieval methods; the question set is not published because it references private documents. The metric is file-level recall (a hit is a gold file in the top-k) and the bytes an agent reads up to the first hit. Strict gold set, from docs/eval/models_strict.md:

method R@1 R@3 R@5 R@10 MRR@10 all-gold@10 avg KB to answer
grep-literal 6% 29% 37% 61% 0.224 53% 420.7
fts-chunk (Postgres full-text) 36% 56% 69% 81% 0.495 76% 7.0
vector (local bge-m3) 60% 86% 91% 96% 0.727 90% 3.3
vector (qwen3-embedding-8b, the default) 70% 89% 93% 97% 0.804 96% 2.2

Lenient gold set (any file containing the answer), from docs/eval/models_strict_lenient.md: grep-literal R@5 50%, MRR 0.375; fts-chunk 77%, 0.552; local bge-m3 94%, 0.761; qwen3-embedding-8b 96%, 0.827. A multimodal candidate that also embeds images, docs/eval/models_pplx_v2.md: pplx-v2-ctx 67% / 87% / 90% / 97%, MRR 0.784.

What it means:

  • Dense vectors find what grep cannot: on paraphrased questions, R@5 is 87 % for qwen3-8b against 33 % for grep and 27 % for full-text; on cross-lingual (xling) questions 90 % against 20 %. On exact identifiers they lose nothing (93 % against 47 %).
  • An agent reads about 2–3 KB to an answer instead of 400 KB.
  • No model abstains on cosine: the top-1 similarity of an unanswerable question overlaps that of an answerable one (qwen3-8b: 0.679 vs 0.676). That is why low_confidence is advisory and the tool tells the agent to read the chunks.
  • Full-text is a fallback (69 % R@5), not a default; a hybrid of the two scored lower than vectors alone (89 % R@5, MRR 0.68). An LLM reranker added +2 p.p. R@5 for 5–30 s per query, which is why the reranker stage is opt-in and off by default. The numbers behind every rejected option are in docs/design.md.

The full model comparison (ten models, cost and time per full indexation, paired wins/ties/losses) is in docs/eval/; embedding the whole corpus costs about $0.01.

Architecture in ten lines

cmd/capsa/          the CLI (cobra): serve, ready, doctor, token, import, export, index, stats, keygen, encrypt, decrypt
config.go server.go package capsa: CAPSA_* settings + .env, the routes, the startup content check, the indexing worker
okf/                public OKF v0.3 parser: bundle scan, concept parsing, links, trust tier, heading chunker
internal/api/       admin REST handlers under /api/admin
internal/bearer/    the one auth gate: Authorization: Bearer → token → scope (MCP and admin both)
internal/database/  pool, embedded migrations (advisory lock, schema_migrations), doctor
internal/embed/     Provider interface, OpenAI-compatible client, deterministic fake for tests
internal/rerank/    optional cross-encoder stage: generic / voyage / cohere request shapes
internal/mcp/       Streamable HTTP MCP server + tool schemas
internal/service/   domain: import/export, put/deprecate, search + fallback + re-scoring, tokens, indexing, logs
internal/store/     pgx repository — the only package that opens sealed values; vector and full-text search
migrations/         embedded SQL, NNNNNN_name.up.sql / .down.sql pairs

Dependencies: pgx v5, golang-migrate v4, mark3labs/mcp-go, cobra, testify, go.yaml.in/yaml/v3. Stdlib net/http, no framework.

Admin API

All routes are under /api/admin and need a bearer token with the admin scope (Authorization: Bearer mem_…). Errors are JSON {"detail": "…"}: 401 no header, 403 invalid/revoked token or missing scope, 404 unknown bundle or row, 400 invalid concept/path/scope/query, 409 slug taken, 422 malformed body, 413 body over 4 MiB, 503 token store unavailable.

Method and path Body / query Response
GET /api/admin/bundles — Bundles with concept and pending-chunk counts.
POST /api/admin/bundles {"slug", "title", "description"} 201; creates an empty bundle.
DELETE /api/admin/bundles/{slug} — {"deleted": "slug"} — the bundle and everything in it.
GET /api/admin/bundles/{slug}/concepts ?prefix=services/, ?include_deprecated=true {"concepts": [...]} — path, type, title, description, status, version.
GET /api/admin/bundles/{slug}/concepts/{path...} — One concept: whole file, neighbours, version, staleness.
GET /api/admin/bundles/{slug}/episodes ?limit=50 (20–200) {"episodes": [...]} — the raw notes, newest first.
GET /api/admin/tokens — {"tokens": [...]} — name, prefix, scopes, bundles, last use, revoked at. Never the hash.
POST /api/admin/tokens {"name", "scopes": ["read"], "bundles": ["a","b"]} 201 with the plaintext — shown once.
DELETE /api/admin/tokens/{id} — {"revoked": "id"}.
GET /api/admin/stats — Bundles, per-tool query aggregates (calls, vector calls, average latency and results, last use), token count.
GET /api/admin/queries ?limit=100 (max 1000) {"queries": [...]} — the newest searches.
GET /api/admin/audit ?limit=100 (max 1000) {"audit": [...]} — the newest writes.

The first token cannot come from the API — a fresh database has none — so mint it with the CLI: capsa token create --name admin --scopes admin. A token's bundle restriction applies on the admin API to the concepts and episodes of a bundle, not to the bundle listing, stats or the logs.

Development

go build ./...
go vet ./...
golangci-lint run ./...          # .golangci.yml; new code must be clean (new-from-rev: origin/main)

# the tests need a PostgreSQL with pgvector; without DB_PORT they skip
docker run -d -p 5432:5432 -e POSTGRES_PASSWORD=postgres pgvector/pgvector:pg16
DB_PORT=5432 DB_USER=postgres DB_PASSWORD=postgres go test -race ./...

Every database test gets a fresh scratch database and drops it. testdata/smoke/ is a tiny OKF bundle for the end-to-end smoke test. CONTRIBUTING.md has the conventions (testify, table-driven, -race, Conventional Commits); AGENTS.md is the same for coding agents; docs/design.md is the design and the decisions.

Roadmap

Planned, not done — built when the query log shows agents use the memory:

  • Section-level memory_edit with a version check — edit one section of a concept; refuse a stale version.
  • Files and assets — blobs, upload, text extraction.
  • Tasks with a lease-based claim — two agents race, exactly one wins.
  • Editable skills — a bundle of skills an agent reads and improves.
  • stdio transport — a local MCP server that talks to the service.
  • Admin UI over the admin API.
  • Consolidation of the episode log into concepts.

License

Apache-2.0

Documentation

Overview

Package capsa wires the server together: its configuration, the HTTP routes (the MCP endpoint, the admin API, health) and the indexing worker.

capsa is an encrypted memory and knowledge base for AI agents: OKF v0.3 bundles in PostgreSQL + pgvector, semantic search over MCP, bearer tokens with scopes, and an audit and query log. Nothing is hosted but the database: the binary carries its schema and talks to any PostgreSQL with the pgvector extension.

Settings come from the environment with the CAPSA_ prefix, or from an env file that wins over it. A local embeddings endpoint needs no API key.

Index

Constants

This section is empty.

Variables

View Source
var Version = "dev"

Version is the release the binary was built from (set with -ldflags "-X main.version=..." at release time).

Functions

This section is empty.

Types

type Config

type Config struct {
	// DatabaseURL is the PostgreSQL connection string of the capsa database
	// (CAPSA_DATABASE_URL). The database needs the pgvector extension.
	DatabaseURL string
	// HTTPAddr is where the server listens (CAPSA_HTTP_ADDR). Loopback by
	// default: expose it deliberately, behind TLS.
	HTTPAddr string
	// LogLevel is debug, info, warn or error; LogFormat is text or json.
	LogLevel  string
	LogFormat string
	// EmbeddingsBaseURL is an OpenAI-compatible /embeddings base: a hosted
	// provider or a local one (TEI, Ollama's OpenAI-compatible endpoint).
	// Empty disables vector search: the server searches full-text only.
	// EmbeddingsAPIKey is empty for a local endpoint.
	EmbeddingsBaseURL          string
	EmbeddingsAPIKey           string
	EmbeddingsModel            string
	EmbeddingsDim              int
	EmbeddingsQueryInstruction string
	EmbeddingsDocPrefix        string
	// EmbeddingsInputType sends input_type query/document (Perplexity needs it).
	EmbeddingsInputType bool
	// IndexInterval is how often the worker embeds chunks left pending.
	IndexInterval time.Duration
	// RerankBaseURL is the base of a rerank endpoint: OpenRouter
	// (https://openrouter.ai/api/v1, model qwen/qwen3-reranker or
	// voyage/rerank-3-lite), Voyage, Cohere, Jina, or a local vLLM / Text
	// Embeddings Inference. Empty: no reranker, the search order stands.
	// RerankModel is the provider's model name; RerankAPI selects the
	// request shape (generic, voyage, cohere) and is inferred from the host
	// when empty.
	RerankBaseURL string
	RerankAPIKey  string
	RerankModel   string
	RerankAPI     string
	// RerankCandidates is how many of the best hits the reranker sees.
	RerankCandidates int
	// RerankMinScore drops reranked hits below this relevance (0: keep all).
	RerankMinScore float32
	// ContentKey seals the stored content: 32 bytes in base64, from
	// CAPSA_CONTENT_KEY or from the file named by CAPSA_CONTENT_KEY_FILE
	// (which wins). Empty stores plaintext. With a key the full-text search
	// is off: the embedding provider still sees plaintext, the database
	// does not.
	ContentKey string
}

Config is every setting of the server.

func LoadConfig

func LoadConfig(envFile string) (Config, error)

LoadConfig reads the settings from the environment and, when it exists, from the env file (which wins).

func (*Config) NewContentBox

func (c *Config) NewContentBox() (*store.Box, error)

NewContentBox builds the content-sealing box from the configured key; nil (and no error) when no key is set.

func (*Config) NewLogger

func (c *Config) NewLogger() *slog.Logger

NewLogger builds the process logger from the configured level and format.

func (*Config) NewProvider

func (c *Config) NewProvider() (embed.Provider, error)

NewProvider builds the embeddings provider: nil (no vector search) when no base URL is configured. A zero dimension means the stored vector size.

func (*Config) NewRepo

func (c *Config) NewRepo(db *pgxpool.Pool) (*store.Repo, error)

NewRepo returns the repository with content sealing configured.

func (*Config) NewReranker

func (c *Config) NewReranker() (rerank.Provider, error)

NewReranker builds the reranker of the configuration; nil (and no error) when no endpoint is set.

func (*Config) Validate

func (c *Config) Validate() error

Validate refuses a configuration the server cannot run with.

type Server

type Server struct {
	// contains filtered or unexported fields
}

Server is one capsa process over one database: the MCP endpoint (/mcp), the admin API (/api/admin), the health routes and the indexing worker.

func NewServer

func NewServer(cfg *Config, provider embed.Provider) *Server

NewServer builds a server. provider nil means the configured embeddings provider; a provider is how the tests inject a fake one.

func (*Server) Handler

func (s *Server) Handler() http.Handler

Handler returns the HTTP handler of every route.

func (*Server) RunWorker

func (s *Server) RunWorker(ctx context.Context) error

RunWorker embeds the chunks that a write or an import left pending while the provider was down, every IndexInterval, until ctx is done.

func (*Server) Service

func (s *Server) Service() *service.Service

Service returns the wired service (the CLI subcommands work through it).

func (*Server) Start

func (s *Server) Start(ctx context.Context, pool *pgxpool.Pool, logger *slog.Logger) error

Start wires the server over the pool: the embeddings provider, the repository with its content check, the service and the routes.

Directories

Path Synopsis
cmd
capsa command
Command capsa is an encrypted memory and knowledge base for AI agents: OKF v0.3 bundles in PostgreSQL + pgvector, semantic search over MCP (/mcp), an admin API (/api/admin), bearer tokens with scopes, audit and query logs.
Command capsa is an encrypted memory and knowledge base for AI agents: OKF v0.3 bundles in PostgreSQL + pgvector, semantic search over MCP (/mcp), an admin API (/api/admin), bearer tokens with scopes, audit and query logs.
internal
adminui
Package adminui serves the self-hosted admin console: one page with its script, stylesheet and icon, embedded in the binary.
Package adminui serves the self-hosted admin console: one page with its script, stylesheet and icon, embedded in the binary.
api
Package api holds the admin HTTP handlers under /api/admin: the bundles, concepts, tokens, statistics, the query log and the audit log.
Package api holds the admin HTTP handlers under /api/admin: the bundles, concepts, tokens, statistics, the query log and the audit log.
bearer
Package bearer authenticates HTTP requests with the service's bearer tokens.
Package bearer authenticates HTTP requests with the service's bearer tokens.
database
Package database opens the PostgreSQL pool and applies the embedded migrations.
Package database opens the PostgreSQL pool and applies the embedded migrations.
embed
Package embed defines the embedding providers the memory service uses to turn text into vectors: a search query on one side, the chunks of a concept on the other.
Package embed defines the embedding providers the memory service uses to turn text into vectors: a search query on one side, the chunks of a concept on the other.
httpx
Package httpx holds the HTTP helpers the handlers share: the JSON and error writers and the query parsers.
Package httpx holds the HTTP helpers the handlers share: the JSON and error writers and the query parsers.
mcp
Package mcp is the capsa MCP server mounted at /mcp: a Streamable HTTP endpoint, bearer-token protected, through which agents search, read and write the knowledge bases.
Package mcp is the capsa MCP server mounted at /mcp: a Streamable HTTP endpoint, bearer-token protected, through which agents search, read and write the knowledge bases.
rerank
Package rerank scores search candidates with a cross-encoder: the second stage of retrieval, after the vector search has picked the candidates and before anything is truncated to the requested limit.
Package rerank scores search candidates with a cross-encoder: the second stage of retrieval, after the vector search has picked the candidates and before anything is truncated to the requested limit.
service
Package service is the memory service's domain logic: OKF bundles in and out, concepts with their chunks and edges, search with its full-text fallback, agent tokens, and the audit trail behind every write.
Package service is the memory service's domain logic: OKF bundles in and out, concepts with their chunks and edges, search with its full-text fallback, agent tokens, and the audit trail behind every write.
store
Package store is the memory service's PostgreSQL repository: OKF bundles and concepts with their chunks and edges, search (vector and full-text), agent tokens, and the audit and query logs.
Package store is the memory service's PostgreSQL repository: OKF bundles and concepts with their chunks and edges, search (vector and full-text), agent tokens, and the audit and query logs.
testdb
Package testdb gives the tests a scratch database with the pgvector extension and the migrations applied — the way the binary applies them at start.
Package testdb gives the tests a scratch database with the pgvector extension and the migrations applied — the way the binary applies them at start.
Package migrations embeds the SQL migrations, so the binary carries its own schema wherever it runs: a release, a wheel, a container.
Package migrations embeds the SQL migrations, so the binary carries its own schema wherever it runs: a release, a wheel, a container.
Package okf is a consumer of Open Knowledge Format (OKF) v0.3 bundles.
Package okf is a consumer of Open Knowledge Format (OKF) v0.3 bundles.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL