kage://docs · v2.2

Kage docs.

Kage gives coding agents verified memory: every packet is checked against your code when it's written, when it's recalled, and when your diff changes what it cites. The session loop runs itself — auto-capture with a signal gate, a "previously…" digest on every start, memory injected the moment the agent reads a cited file, receipts for what it saves you — and personal memory follows you across machines over your own git remote. This guide takes you from one install command to the full reference.

npx -y @kage-core/kage-graph-mcp install

Quickstart

Requires Node.js 18 or newer. The package installs two binaries: kage and kage-graph-mcp.

# one command from inside your repo — init + index + auto-wires detected agents
npx -y @kage-core/kage-graph-mcp install
# restart the agent once
kage setup verify-agent --agent claude-code --project .
kage recall "how do I run tests" --project .

Prefer explicit steps? npm install -g @kage-core/kage-graph-mcp, then kage init --project . and kage setup <agent> --project . --write per agent below.

Repo-local by default.

Kage doesn't need a hosted database or API key. Memory packets live in .agent_memory/ next to your code as plain JSON.

Choose your agent

Run kage setup <agent> --project . --write once per repo, then restart the agent so the MCP server reloads.

Codex

kage setup codex --project . --write
kage setup verify-agent --agent codex --project .

Claude Code

kage setup claude-code --project . --write
kage setup verify-agent --agent claude-code --project .

Installs MCP plus SessionStart, UserPromptSubmit, PreToolUse(Read), PostToolUse, PostToolUseFailure, PreCompact, Stop, and SessionEnd hooks — prompt-time recall, read-time memory injection, observation, auto-distillation, handoff refresh, and memory reconciliation.

Cursor

kage setup cursor --project . --write

Other MCP clients

kage setup list
kage setup generic-mcp --project .

Other supported targets: Windsurf, Gemini CLI, OpenCode, Cline, Goose, Roo Code, Kilo Code, Claude Desktop, Aider, generic MCP.

CLI-only path

Kage works without an MCP-capable agent. Use the CLI directly to capture and recall memory:

kage init --project .
kage learn --project . --learning "Run npm test --prefix mcp after parser changes."
kage recall "parser tests" --project .

REST path

HTTP-only agents can use the daemon instead of MCP. /kage/context returns combined recall, graph facts, validation, risk, and dependency context; /kage/profile gives a compact project orientation; /kage/capabilities audits memory-system readiness; /kage/context-slots manages pinned repo guidance; /kage/replay shows privacy-preserving observed-session timelines; /kage/capture, /kage/learn, and /kage/feedback write or review the same repo-local packets used by CLI and MCP.

kage daemon start --project .
curl -X POST http://127.0.0.1:3111/kage/context \
  -H 'content-type: application/json' \
  -d '{"query":"how does auth work?","limit":5}'

Verifying setup

kage setup verify-agent confirms the harness is live by checking config, repo policy, indexes, recall, MCP reachability, and Claude Code ambient hooks when applicable. kage setup doctor --json and the MCP kage_setup_doctor tool expose the same hook summary for install audits.

kage setup verify-agent --agent codex --project . --json
kage doctor --project .

First-day workflow

Use your coding agent normally — with the hooks installed, the loop below runs itself. Every command here is the manual equivalent of something Kage already does ambiently.

Sessions start warm

The SessionStart hook injects the memory policy plus a "previously…" digest and recent-memory timeline. When the agent reads a file, verified packets citing it are injected right then.

kage resume --project .      # what the hook injects
kage recall "how does auth work?" --project .

Learnings become packets — even forgotten ones

Agents capture explicitly with kage_learn; sessions that saved nothing are auto-distilled into pending drafts at session end (signal-gated, reviewed by you).

kage learn --project . --type gotcha \
  --learning "Do not merge these retry paths; one uses idempotency keys."
kage inbox --project .       # review auto-distilled drafts

Your diff gets checked

The Stop hook refreshes memory and runs reconciliation; kage pr check leads with any team memories your change invalidated.

kage pr check --project .
kage gains --project .       # the receipt: tokens, $, stale blocked

When something breaks

One command backs up, fixes, and rebuilds — broken packets, missing indexes, lost hooks. Every CLI error ends with a copy-pasteable Try:.

kage repair --project .

Optional automation

A marker-delimited git post-commit hook refreshes memory after commits (kage hook install); kage staleguard works as a pre-commit stale-catch. Both preserve existing hook content and respect KAGE_SKIP_HOOK=1.

kage hook install --project .
kage staleguard --project .

Core concepts

Kage stores reusable learnings as packets, not raw chat transcripts. A good packet is short, source-backed, path-grounded, and useful to a future agent.

  • runbook: how to run, test, build, debug.
  • bug_fix: cause, fix, evidence, verification.
  • decision: what was decided and why.
  • rationale: why a tradeoff exists.
  • convention: a repo rule agents should follow.
  • workflow: repeated steps for a task.
  • gotcha: a failure mode to avoid.
  • code_explanation: why non-obvious code exists.
  • negative_result: what was tried and did not work.
  • constraint: a limitation that changes choices.
repo-local reviewable JSON path-grounded source-backed not transcripts

Memory graph vs code graph

Two graph surfaces: a memory graph generated from approved packets, and a source-derived code graph generated from your code. The viewer overlays them so humans can see what was recalled, why it matters, and what signals are attached.

The packet journey & the scores

Every memory packet moves through a fixed lifecycle, and every number Kage shows you is derived from where packets sit in it. Here is the whole journey, and exactly what each score means.

1. The journey of a packet

  1. Capture — an agent records a learning with kage_learn (or kage propose --from-diff): a title, body, type, and the source paths it is about.
  2. Citation check — Kage rejects a strict capture whose cited paths don't exist. Memory can't be grounded to files that aren't there — this is the anti-hallucination gate. Paths your repo declares non-knowledge in .kageignore are dropped here, never stored as grounding.
  3. Grounding — the surviving paths are fingerprinted (content hashes). This is the link between a memory and the code it describes.
  4. Approve — repo-local captures are written as git-tracked JSON in .agent_memory/packets/. Org/public promotion is separate and human-gated.
  5. Recall — when an agent asks, Kage ranks packets and returns them — but excludes any that have gone stale, so agents never act on memory that no longer matches the code.
  6. Refreshkage refresh re-checks every packet's grounding, flags stale ones, prunes dead or ignored paths, and rebuilds the graphs.
  7. Supersede / retire — when a learning is replaced or no longer true, it is superseded or deprecated and stops being recalled.

When a packet is "stale"

  • A cited path is missing — a grounded file was deleted or renamed.
  • A linked path changed — a cited file's hash no longer matches the fingerprint taken when it was verified.
  • Freshness expired — it passed its time-to-live (365 days by default) without re-verification.
  • It was reported — a human or agent flagged it, or it was deprecated/superseded.

Paths listed in .kageignore (e.g. a presentation/visualization layer) never count as grounding and never trigger staleness — they aren't knowledge-bearing.

Health — the colored states

The viewer's Memory list and health donut classify every packet:

  • Hot — recalled 3+ times in the last 30 days. High-value repo lore.
  • Healthy — approved, grounded, non-stale, and recalled at least once.
  • Cold — approved and durable, but not recalled yet (or still pending review).
  • Stale — a staleness condition above is true; verify, update, or supersede before trusting it.
  • Disputed — stale and also reported or voted down.
  • Ungrounded — approved but with no concrete code-path grounding; add files/symbols so agents know when to recall it.
  • Generated — branch/change handoff context, useful now but not durable lore.

Memory Trust — the 0–100 score

Trust is not a vanity metric. It is produced by a reproducible local benchmark (kage benchmark --trust) that runs three gates, and the score is their average:

  • Hallucinated citations rejected (target 100%) — in a throwaway sandbox repo, Kage attempts to store memory citing files that don't exist; this measures how many it refuses.
  • Stale memory excluded from recall (target 100%) — memory is grounded to real files, the files are deleted, and this measures how much Kage withholds from recall afterward.
  • Live memory grounded to code (target 80%+) — of your real repo's approved memory, how much is grounded (cited files exist) and not stale.

A fourth figure, wrong advice prevented, combines the rejection and exclusion gates. Gates 1–2 run in an isolated sandbox so the number can't be gamed; gate 3 measures your actual repo, so it moves as memory drifts from or re-aligns with the code.

The other dashboard numbers

  • Memory packets — approved durable packets in this repo.
  • Saved per recall — estimated tokens an agent avoids by recalling a grounded packet instead of re-reading source.
  • Evidence coverage — share of memory-graph edges backed by concrete evidence.
  • Average quality — mean packet quality score across the repo.
  • Files / symbols / routes / tests — what Kage's source-derived code graph has mapped: the surface memory is grounded against.

What to commit

Kage writes to .agent_memory/. Some files are durable repo memory; others are rebuildable artifacts.

Commit these

  • .agent_memory/packets/*.json — durable repo memory.
  • AGENTS.md — agent harness policy.

Optional to commit

  • .agent_memory/graph/, code_graph/, structural/ — rebuildable with kage refresh.
  • .agent_memory/reports/*.json — helpful for CI viewer artifacts.

If you don't want to commit generated artifacts, add .agent_memory/graph, .agent_memory/code_graph, .agent_memory/structural, and .agent_memory/reports to .gitignore. .agent_memory/packets/ should stay tracked.

Good memory examples

Worth saving

  • Cause + verified fix for a recurring bug.
  • A command teammates re-discover (test, build, lint, deploy).
  • A decision and its rationale (why this design over that one).
  • A path-specific gotcha that would surprise the next agent.
  • An explanation of non-obvious code.

Do not save

  • Raw chat transcripts or step-by-step session logs.
  • Anything the code or git history already shows clearly.
  • Secrets, tokens, private URLs, customer data, PII.
  • Personal notes irrelevant to future agents.

CLI by job

Use --json where automation needs structured output. Below: commands grouped by what you need to do.

Setup and verification

kage install One-shot setup

Init + index + auto-detects installed agents (Claude Code, Codex, Cursor, Windsurf, Gemini CLI, OpenCode, Goose, Aider) and wires them. The fastest path from zero to live memory.

npx -y @kage-core/kage-graph-mcp install

kage scan Truth Report

Zero-setup, ~60-second report on any repo: duplicate implementations, ghost exports, bus-factor-1 hot files, knowledge voids, and doc lies — every finding cites file:line evidence.

kage scan --project . [--json]

kage gains Savings receipt

What the memory harness actually did: tokens and dollars saved (measured, per-packet replay value), stale memories blocked, stale knowledge caught at change-time.

kage gains --project .

kage resume Session continuity

The "previously…" digest: last session's work, distilled learnings, drafts awaiting review, unresolved reconciliation, and a compact timeline of recent memory. Injected automatically at session start.

kage resume --project . [--json]

kage repair One-command recovery

Backs up and fixes broken packet JSON (including committed merge-conflict markers), rebuilds missing indexes, cleans stale locks, and re-wires agents that lost their hooks. Prints a receipt of every step.

kage repair --project . [--json]

kage file-context Memory for one file

Up to three currently-verified packets citing a given file, as a compact context block. Powers the PreToolUse(Read) hook that injects memory the moment the agent opens a file.

kage file-context --project . --path src/auth.ts

kage audit-claude-mem Audit a claude-mem store

Read-only truth report over an existing claude-mem database: every observation classified as VERIFIED, DRIFTED, GONE, or UNCITED against your current repo. Their memory, our verification.

kage audit-claude-mem --project . [--store ~/.claude-mem/claude-mem.db]

kage merge-packet Git merge driver

Auto-resolves packet JSON conflicts (newest-wins, recovers committed conflict markers). kage init/install write the .gitattributes entry; enable per clone with one config line.

git config merge.kage-packet.driver "npx -y @kage-core/kage-graph-mcp merge-packet %A %O %B"

kage init Initialize a repo

Creates memory structure, installs policy, builds the first index. Use when you want memory only, without agent wiring.

kage init --project .

kage setup Configure agents

Lists targets, writes agent config, verifies live integration. Claude Code setup also installs ambient hooks for prompt recall, observation, compaction distillation, and stop-time handoff refresh.

kage setup list
kage setup codex --project . --write
kage setup verify-agent --agent codex --project . --json

kage doctor Diagnose a repo

Validates config, indexes, and policy state.

kage doctor --project .

Recall and capture

kage recall Retrieve relevant memory

Returns an agent-ready context block. Use --explain to see why packets matched.

kage recall "query" --project . --json --explain

kage profile Orient an agent quickly

Summarizes repo totals, languages, top code+memory concepts, key files, run commands, memory focus, and next actions without loading every packet or graph node.

kage profile --project . --json

kage capabilities Audit memory-system readiness

Scores repo memory, collaboration/session proof, benchmark proof, and dashboard/viewer readiness with evidence, gaps, and next actions.

kage capabilities --project . --json

kage slots Pin tiny repo guidance

Creates reviewable repo-local context slots that Kage includes before task-specific recall. Use this for stable constraints, commands, or warnings that are too important to rediscover but too small for a full memory search.

kage slots set --project . --label project_context \
  --content "Always run checkout retry tests after touching retry modules." \
  --paths src/retry.ts --tags checkout,tests
kage slots --project . --json

kage embeddings Optional dense local recall

Builds a rebuildable local embedding artifact for semantic recall after installing @xenova/transformers in the same Node environment as Kage. Normal recall remains dependency-free.

npm install -g @xenova/transformers
kage embeddings build --project .
kage recall "query" --project . --embeddings --explain

kage learn Capture a learning

Writes a concise repo-local memory packet for a reusable fact.

kage learn --project . --type decision --title "Parser tests need fixtures" \
  --learning "Run parser fixture tests after grammar edits." \
  --paths mcp/kernel.ts,mcp/kernel.test.ts

kage capture Create a structured packet

Writes a packet with explicit title, summary, body, type, tags, paths, and stack metadata.

kage capture --project . --title "Auth retry gotcha" --body "..." --type gotcha --tags auth,retry

kage feedback Mark memory helpful, wrong, stale

Records usefulness signals on recalled packets.

kage feedback --project . --packet <id> --kind stale

kage sessions Review observed sessions

Shows privacy-scanned local observations, durable distillation candidates, and next actions without raw transcript replay.

kage sessions --project . --json
kage replay --project . --json
kage distill --project . --session <id>

kage memory-access See reused memory

Reports hot, cold, and recently recalled packets from local ignored access telemetry, then recommends what to verify, ground, or clean up. Recall does not mutate shareable packet files.

kage memory-access --project . --json

kage memory-audit Review memory mutations

Shows explicit memory changes: capture, feedback, approve, reject, supersede, deprecate, and delete, with packet ids, branch/head, actor, and details.

kage memory-audit --project . --limit 50 --json

kage handoff Prepare the next teammate or agent

Combines inbox, lifecycle, audit, timeline, and lineage into one action queue: what is blocking handoff, what changed recently, and which retired memories need replacement links.

kage handoff --project . --json

kage lifecycle Review memory health

Classifies packets as healthy, hot, cold, stale, disputed, ungrounded, pending, or generated, then gives teammates concrete review actions.

kage lifecycle --project . --json

kage timeline Review memory history

Shows recently added, updated, pending, and retired packets so teammates know what repo knowledge changed before handoff.

kage timeline --project . --days 14 --json

kage lineage Replace old memory safely

Shows superseded packets, their current replacements, and orphaned retired memory that needs a replacement link.

kage supersede --project . --packet <old-id> --replacement <new-id> --reason "newer verified context"
kage lineage --project . --json

Maintain generated state

kage refresh Rebuild generated state

Updates indexes, structural artifacts, graphs, metrics, and stale-memory checks. Newly captured and diff-derived packets store linked-file fingerprints, so Kage can flag memory when the source code it explains has changed. --full bypasses cache.

kage refresh --project .
kage refresh --project . --full --json

kage reconcile Agent memory repair gate

Reports linked-memory packets that the current agent must update, supersede, or mark stale after changing related source files. Claude Code Stop hooks and kage pr check use this as an enforcement gate, so users do not have to manually babysit memory updates.

kage reconcile --project . --json
kage reconcile --project . --session <session-id>

kage hook Auto-refresh after commits

Marker-delimited git post-commit hook. Preserves existing hook content; respects KAGE_SKIP_HOOK=1.

kage hook install --project .
kage hook status --project . --json
kage hook uninstall --project .

kage gc Inspect or clean generated artifacts

Reports or prunes regenerable files when needed.

kage gc --project . --dry-run

Inspect graphs

kage graph Query memory graph

Evidence-backed entities and relationships from approved packets.

kage graph "checkout retry" --project . --json

kage code-graph Query source graph

Files, symbols, imports, confidence-scored calls, routes, tests. Recognizes FastAPI, Flask, Django, Rails, Laravel, Spring, Go, Rust, ASP.NET routes. SCIP/LSP/LSIF/tree-sitter override generic facts when present.

kage code-graph "recall ranking" --project . --json

kage dependency-path Connect two files

Shortest source graph path between two files.

kage dependency-path --project . --from src/app.ts --to src/auth.ts --json

kage graph-insights Architecture signals

Parser coverage, edge mix, central files, cycles, communities, entry flows.

kage graph-insights --project . --json

Risk, ownership, review

kage risk Pre-edit risk check

Dependents, impact surface, churn, ownership silos, co-change warnings, missing test signals.

kage risk --project . --targets src/auth.ts --json

kage reviewers Suggest local reviewers

Ranks reviewers from git authorship and co-change ownership. Local-only.

kage reviewers --project . --changed-files src/auth.ts --json

kage contributors Profile local ownership

Commits, recent activity, touched files/modules, ownership silos, hotspot ownership.

kage contributors --project . --json

kage decisions Why-memory coverage

Decision/runbook/gotcha coverage, weak/stale memories, important paths without why-memory.

kage decisions --project . --json

kage module-health Module scorecards

Rolls up graph, test, cleanup, churn, ownership signals.

kage module-health --project . --json

kage cleanup-candidates Cleanup review input

Conservative unreferenced-file, unused-export, and internal-symbol candidates with confidence and reasons. Never mutates code.

kage cleanup-candidates --project . --json

PR and handoff

kage propose --from-diff Branch change memory

Creates a branch summary and repo-local change-memory packet from git diff.

kage propose --project . --from-diff

kage pr Summarize and check

Verifies validation, stale packets, graph freshness, memory changes, and unresolved agent memory reconciliation before merge.

kage pr summarize --project .
kage pr check --project . --json

Workspace

kage workspace Recall across sibling repos

Scans a local parent dir for git repos, reports memory coverage, package deps, route/topic contracts, and git co-change links.

kage workspace --project .. --json
kage workspace recall "auth header contract" --project .. --json

Adoption and quality

kage metrics

Code graph coverage, memory graph evidence, useful memory ratio, readiness.

kage metrics --project . --json

kage audit / kage quality / kage validate

Audit health, structured context coverage, code graph quality, and trust signals.

kage audit --project . --json
kage quality --project . --json
kage validate --project .

kage benchmark

Compares baseline discovery cost vs Kage context and can run packaged coding-memory retrieval and scale benchmarks.

kage benchmark --project . --compare --task "fix flaky checkout retry" --json
kage benchmark --memory-quality --json
kage benchmark --scale --sizes 240,1000,5000 --json

kage inbox / kage review-artifact

Pending, stale, duplicate packets, validation issues, recommended actions.

kage inbox --project . --json

Personal memory & sync

kage learn --personal / kage sync

Personal packets live in ~/.kage/memory and follow you, not the repo. Sync over your own private git remote — no account. Recall labels them [personal] and re-verifies citations in every clone; they never enter pr-check or staleguard.

kage learn --personal --learning "Always run the full suite before releasing"
kage sync setup --remote git@github.com:you/kage-memory.git   # once per machine
kage sync            # pushed/pulled/resolved receipt; conflicts keep both versions
kage sync --status   # ahead/behind/dirty, no network mutation

Viewer

kage viewer

Starts the local viewer with repo graph, code graph, metrics, review queue, pending memory, and reports preloaded.

kage viewer --project . --port 3113

MCP tools

Agents should prefer MCP tools when available. Start with kage_context — it combines validation, recall, code graph search, knowledge graph search, target-aware risk signals, and memory reconciliation.

kage_context Main task entry point

Call before repo-specific implementation, debugging, architecture, or code questions. When a query or target list includes file paths, Kage also adds risk, dependency-path context, and any linked memory the agent must repair before final handoff.

kage_recall, kage_graph, kage_code_graph

Lower-level recall and graph tools when the combined context tool is not enough.

kage_memory_reconcile

Agent-owned repair list for memory linked to source files changed in the current task. Use it to decide which packet to update, supersede, or mark stale before final handoff.

kage_risk

Pre-edit risk assessment with graph dependents, churn, ownership, co-change warnings, impact surface, test-gap signals.

kage_dependency_path

Shortest code graph path between two files.

kage_cleanup_candidates

Conservative review input. Never mutates files.

kage_profile

Compact project orientation for agents: repo shape, top concepts, key files, commands, memory focus, and next actions.

kage_capabilities

Evidence-backed readiness report across memory, collaboration, benchmark proof, and dashboard/viewer proof.

kage_context_slots, kage_context_slot_set, kage_context_slot_delete

List, upsert, or delete pinned repo context slots that are included before task-specific recall.

kage_session_replay

Review observed agent session timelines, touched paths, commands, durable candidates, and distill actions without raw transcript text.

kage_reviewers, kage_contributors

Local git-derived reviewer suggestions and contributor profiles.

kage_decisions, kage_module_health, kage_graph_insights

Why-memory coverage, module scorecards, architecture signals.

kage_workspace, kage_workspace_recall

Summarize sibling repos and recall across a local multi-repo workspace.

kage_learn, kage_capture, kage_feedback, kage_supersede

Capture new repo knowledge, mark recalled memory helpful/wrong/stale, or link old memory to a current replacement.

kage_refresh, kage_pr_summarize, kage_pr_check

Keep generated artifacts current and create merge-ready branch memory.

kage_metrics, kage_audit, kage_inbox, kage_quality, kage_benchmark, kage_memory_handoff, kage_memory_audit

Inspect readiness, quality, duplicates, stale packets, benchmark estimates, profile, handoff, lifecycle, memory timeline, lineage, and mutation audit reports.

kage_setup_agent, kage_verify_agent, kage_install_policy

Install or verify agent harness configuration.

kage_search, kage_fetch, kage_list_domains

Optional community knowledge graph search. Returned public context is advisory.

kage_workflow

A no-op tool whose description teaches agents the loop — context first, learn reusables, refresh after changes, pr-check before finishing — so any MCP client learns the workflow just by listing tools.

The server exposes more specialized tools (lifecycle, lineage, timelines, structural index, benchmarks); run kage help --all or list tools from your agent for the full set.

Viewer

Two ways to use it: a hosted demo at viewer/, and the local viewer for your real repo.

kage viewer --project .

When to open the viewer

  • Before editing a shared file — check Risks for dependents and co-change partners.
  • To find repo lore — search the Memory page by file, feature, bug, or command.
  • To inspect why an agent recalled something — follow memory-to-code links from the Graph.
  • Before merging — clear the Review queue, including distillable session learnings that should become memory.
  • Before quoting benchmark numbers — check Quality/Benchmark for proof commands, thresholds, and next actions.
  • To diagnose generation quality — open the Artifacts diagnostics link.

The local viewer is preferred for real repos because it loads active artifacts and reports automatically.

Privacy and trust

Kage is collaborative because repo memory travels with the repository and can be reviewed like code. Sharing outside the repo is explicit and human-gated.

Repo-local (default)

Packets, graphs, reports, and metrics stay under .agent_memory/. No external service is contacted for normal recall.

Org / global / public

Promotion needs explicit review commands. Repo-local memory wins when context conflicts. Treat public/community content as advisory.

Capture safety

Capture scans for obvious secrets and PII before writing. Do not store credentials, customer data, or private URLs in packets.

Reviewable changes

Memory packets are JSON. Branch changes can be summarized with kage propose --from-diff and checked with kage pr check.

Troubleshooting

Agent does not call Kage

Verify setup and restart the agent.

kage setup verify-agent --agent codex --project .
kage doctor --project .

Recall returns stale or wrong memory

Mark the packet, refresh, and review the inbox.

kage feedback --project . --packet <packet-id> --kind stale
kage inbox --project . --json

Viewer has no graph

Launch from the repo or open the hosted viewer with graph/code/metrics URL params.

kage viewer --project .

Refresh is slow

Check cache hits, indexable files, ignored files, and parser coverage before forcing a full rebuild.

kage metrics --project . --json
kage audit --project . --json

Node version error

Kage requires Node 18 or newer. Check with node --version and upgrade if needed.