# Kindex MCP Agent Guide

This guide is for AI coding agents connected to the `kindex` MCP server.
Kindex is the user's durable memory layer: a persistent knowledge graph for
projects, decisions, tasks, constraints, reminders, and session context.

## Core Rule

Use kindex proactively. Do not wait for the user to mention it.

At the start of meaningful work, search or ask kindex for relevant context.
During work, capture durable discoveries as they happen. At the end of work,
summarize the session with a tag update.

## AI Operating Contract

For durable work, use Kindex as the persistent task and knowledge store rather
than relying on session-local task systems or ephemeral scratch state.

- Start with `tag_start` or `tag_resume`, then `search`, `context`, or `ask`
  before editing.
- Use `task_add`, `task_list`, and `task_done` for durable work items. Do not
  assume a host-specific task tool survives the end of the current conversation.
- Search before `add`; prefer `edit` or `supersede` over duplicate nodes.
- Capture decisions, constraints, questions, watches, and notable outputs while
  they are fresh, then link related nodes.
- Treat tracked `.kin` files as shipped project state, not local cache.
- Never commit a machine-local path, local-only report pointer, secret, private
  transcript, or host-specific scratch reference into tracked artifacts.
- If a generated artifact matters to future users or agents, make it
  repo-local, durable, and independently usable after a fresh clone.
- When a repo tracks generated `.kin` snapshots, regenerate them from source
  rather than hand-editing the generated JSON.

If the host also exposes session-local task tools, use those only for
temporary planning. Durable tasks belong in Kindex because they must survive
the current conversation and remain linkable to graph context.

## Session Lifecycle

1. Start: call `tag_start` with a short session name and current focus, or
   `tag_resume` if continuing known work.
2. Orient: call `search`, `context`, or `ask` before significant investigation
   or edits.
3. Policy: when shell access is available, run
   `kin policy check --event agent-start` from the project root. If the repo
   has `.kin/config`, treat it as tracked project context.
4. Work: capture discoveries, decisions, tasks, watches, and connections while
   they are fresh.
5. Segment: when changing topics, call `tag_update` with `action=segment`.
6. End: call `tag_update` with `action=end` and a concise summary.

`tag_update` is a native MCP tool (segment, pause, end, and focus updates all
go through it). Earlier releases required a CLI fallback for tag updates; that
is no longer the case.

## Project `.kin/` Contract

Kindex projects may ship a `.kin/` directory in git. Treat it as part of the
codebase contract, not private scratch space.

- `.kin/config`: project metadata, inheritance, voice, domains, and optional
  `work_policy`.
- `.kin/index.json`: git-tracked graph snapshot generated by `kin index`.
- `.kin/code-map.json`: git-tracked repo-relative code map generated by
  `kin export code-map`.
- `.kin/.gitignore`: ignores only local/private subdirectories such as
  `.kin/local`, `.kin/cache`, `.kin/tmp`, and `.kin/private`.

`.kin/index.json` and `.kin/code-map.json` are generated, id-keyed snapshots:
never hand-resolve a git conflict in them. `kin index` auto-registers a
structured merge driver (`kin merge-kin`) on first run that unions them
losslessly across branches (run `kin setup-merge` to re-install it in a fresh
clone). If you do need a clean copy, regenerate with `kin index` /
`kin export code-map` rather than hand-editing the JSON.

Never put secrets, API keys, private transcripts, or machine-local cache in
tracked `.kin` files. Tracked task/report metadata must not point at a local
filesystem path outside the repo; if the evidence matters, ship a repo-local
subset or a durable shared artifact. Put local state in `~/.kindex` or ignored
`.kin/local`.

For code-map output, use `kin export code-map` when a consumer needs current
repo structure. It emits repo-relative POSIX paths, not raw local provenance.
`kin export` is the broader audience-aware graph export; it is not a substitute
for the code-map projection.

Linear is opt-in per project. Enforce Linear only when the project policy says:

```yaml
work_policy:
  linear:
    enabled: true
    require_issue: true
```

If no `work_policy` is present, continue normally. Absence of policy is not an
error; it means kindex is memory/context only for that repo.

## Tool Use Patterns

### Search Before Work

Use `search` when starting a task, entering an unfamiliar project, revisiting a
topic, or before adding new knowledge. This prevents duplicates and reveals
constraints or previous decisions.

### Capture Knowledge

Use `add` for durable knowledge, not routine transcript logging.

Recommended node types:

- `concept`: facts, architecture, important files, patterns, domain terms
- `decision`: choices and rationale
- `question`: open problems that should resurface
- `constraint`: hard invariants or safety rules
- `directive`: soft preferences and style rules
- `watch`: ongoing risks, flaky tests, unstable APIs, tech debt
- `checkpoint`: pre-flight checks before release or high-risk work

Always search before adding unless the knowledge is obviously new and immediate.

### Link Related Ideas

Use `link` when two nodes relate. Prefer explicit relationship types:

- `relates_to`
- `depends_on`
- `implements`
- `contradicts`
- `blocks`
- `context_of`
- `answers`
- `supersedes`

The graph becomes useful through links. Add them whenever a relationship matters
for future work.

### Edit and Supersede

Use `edit` to correct or extend an existing node instead of adding a near
duplicate. Edits are policy-aware by node type:

- editable (concept, document, artifact, skill, person, project, question):
  full in-place edit — title, content, append, add/remove tags, intent, expires
- additive (decision, constraint, directive, checkpoint, watch): history
  matters — only `append` (dated addendum) and `expires` are allowed
- managed (task, session, coordination): refused — use the dedicated
  task/tag/coord tools

Use `supersede` when an additive node's content must actually change: it
creates a fresh node, links it with a `supersedes` edge, and marks the old
node superseded. Pass `reason` so the provenance survives.

Both accept a node ID or exact title. Both are refused while another agent
holds an advisory lock on the node. `edit` accepts `force=True` to override
(only when you are sure); `supersede` has no force flag — release the lock
first (`lock_release` with `force=True`) before superseding a locked node.
Every edit logs per-field old/new diffs, visible via `changelog`.

Use `expires` (YYYY-MM-DD) on time-bound knowledge — expired nodes stop
surfacing in context and are archived by the daemon.

### Learn From Large Text

Use `learn` after reading long files, logs, design docs, transcripts, or command
outputs. It extracts multiple concepts in one pass.

### Manage Tasks

Use `task_add` for actionable work items. Link tasks to relevant concepts when
possible so they surface contextually.

Use `task_list` when planning or resuming work. Use `task_done` immediately when
a task is completed.

Use `task_claim` before taking shared work from a task list, and `task_release`
when handing it back. Claims expire, so abandoned agent work does not become a
permanent lock.

Use `coord_start`, `coord_post`, `coord_read`, and `coord_end` for short-lived
agent coordination. Coordination messages are operational state; promote only
durable discoveries, decisions, or tasks into the graph with normal capture
tools.

### Collaborate With Other Agents

When several agents share work, use the collab tools on top of basic
coordination:

- `coord_join`: become a member of a conversation. Members get a read cursor
  (unread tracking) and receive the conversation's standing messages in their
  session context. `coord_read` advances your cursor.
- `coord_post` with `to=<agent>`: targeted message — counts as unread only
  for that agent (broadcast when omitted).
- `coord_attach`: attach a graph node as a shared resource so members see who
  holds what when it is locked.
- `coord_inject`: set, clear, or list standing messages that are pushed into
  member agents' context by the session hooks until cleared. Use for
  "don't touch X until Y lands" style coordination.
- `lock_acquire` / `lock_release`: advisory locks on nodes. A lock signals
  "I am working on this" — `edit` refuses foreign locks, and locked attached
  resources surface to collab members. Locks expire by TTL; an expired lock
  never blocks anyone.

Your agent identity resolves automatically (`KIN_AGENT_ID` env, then the
`agent_id` config key, then `user@shorthost`), so these tools work without
explicit agent parameters.

### Add Watches

Use `watch_add` for issues that need future attention: flaky tests, unstable
dependencies, brittle APIs, unresolved performance concerns, or migration
deadlines.

Use `watch_resolve` once the risk is fixed or irrelevant.

### Use Reminders

Use `remind_create` for time-based follow-up. A reminder may include a shell
action, natural-language instructions, or a headless Codex/OpenCode wakeup. Use
`wake=codex` or `wake=opencode` with optional `wake_session`, `wake_cwd`,
`wake_model`, and `wake_agent` fields to start or resume a noninteractive turn
when the reminder fires.

Do not treat reminders as reentrant interrupts for an idle interactive thread.
`remind_create` stores the reminder; it fires only when `kin remind check`,
`kin remind exec`, `kin cron`, or an installed `kin setup-cron` schedule runs.
Codex wakeups launch `codex exec` (or `codex exec resume ...`) from that
daemon/cron context. OpenCode wakeups launch `opencode run` with `--session` or
`--continue` when requested. If the host has no same-thread wake server,
Kindex starts a headless follow-up turn instead of prodding the original TUI.

## What Not To Capture

Do not capture trivial file reads, routine git status output, obvious
boilerplate, private secrets, duplicate knowledge, or every step of a
transcript. Capture what should help a future agent or future user.

## Recommended Startup Behavior

1. `tag_start` or `tag_resume`
2. `kin policy check --event agent-start` when shell access is available
3. `search` the current project/topic
4. `task_list` for nearby or global open tasks
5. `remind_check` if reminders are enabled
6. Continue with the user's task

## Recommended Shutdown Behavior

1. Add any final decisions, tasks, watches, or questions
2. Link newly captured nodes where obvious
3. `tag_update` with `action=end` and a concise summary

## Client Setup

Install kindex with the `mcp` extra using whichever installer you prefer
(`pip install 'kindex[mcp]'`, `uv tool install 'kindex[mcp]'`, or
`git clone … && make install`). Then wire each agent:

### Claude Code

```bash
claude mcp add --scope user --transport stdio kindex -- kin-mcp
kin init
kin setup-claude-md --install
kin setup-hooks
```

Claude Code supports lifecycle hooks, so `kin setup-hooks` can prime context,
capture pre-compaction context, and run stop guards.

### Codex

```bash
kin setup-codex-mcp
kin setup-codex-hooks
kin setup-agents-md --install --global
kin ingest codex-sessions   # optional: backfill saved sessions
```

Or hand-edit `~/.codex/config.toml`:

```toml
[mcp_servers.kindex]
command = "kin-mcp"
```

### Gemini CLI

```bash
kin setup-gemini-mcp
kin setup-gemini-md --install
```

Or hand-edit `~/.gemini/settings.json`:

```json
{ "mcpServers": { "kindex": { "command": "kin-mcp", "args": [] } } }
```

### Google Antigravity

```bash
kin setup-antigravity-mcp
kin setup-antigravity-hooks
kin setup-antigravity-md --install
```

Antigravity uses standalone MCP config files, so Kindex writes both
`~/.gemini/config/mcp_config.json` and
`~/.gemini/antigravity-cli/mcp_config.json`. Hooks live in
`~/.gemini/config/hooks.json`: Kindex installs PreInvocation context priming and
prompt checks, PreToolUse advisory attention plus config-write permission
gating, and Stop-time reinforcement enqueue.

### OpenCode

```bash
kin setup-opencode-mcp
kin setup-agents-md --install --global   # OpenCode reads AGENTS.md
```

Or hand-edit `~/.config/opencode/opencode.json`:

```json
{
  "$schema": "https://opencode.ai/config.json",
  "mcp": {
    "kindex": { "type": "local", "command": ["kin-mcp"], "enabled": true }
  }
}
```

### Cursor

```bash
kin setup-cursor-mcp
kin setup-cursor-rules --install
```

The rules file lands at `~/.cursor/rules/kindex.mdc` with `alwaysApply: true`.
Or hand-edit `~/.cursor/mcp.json`:

```json
{ "mcpServers": { "kindex": { "type": "stdio", "command": "kin-mcp" } } }
```

## Agent-Specific Tuning

Root config is the global/project default. Client and instance overrides live
under `agents.clients` and `agents.instances`:

```bash
kin config set attention.tick_interval 3
kin agent-config set attention.tick_interval 2 --client claude
kin agent-config set hooks.prime_tokens 1200 --client claude --scope instance --instance session-a
```

Agents may propose these changes, but writes should go through the host's normal
tool/command permission gate. Antigravity hooks force an explicit user prompt
before `kin config set` or `kin agent-config set` runs.

## Human Setup Checklist

1. Install kindex (`pip install 'kindex[mcp]'` / `uv tool install 'kindex[mcp]'` / source).
2. Run `kin init` to initialize the knowledge graph.
3. Install the MCP server for your agent (see Client Setup above).
4. Install the agent instruction file (`CLAUDE.md`, `AGENTS.md`, `GEMINI.md`, or Cursor `.mdc`).
5. Run `kin setup-cron` for periodic maintenance.
6. Backfill saved sessions with `kin ingest codex-sessions` or `kin ingest sessions`.

For a human-facing walkthrough with reminders, docs site URLs, and release
metadata checks, see [human-guide.md](human-guide.md).
