# Setup Guide

Get your agent remembering in under a minute. This guide covers installation for all supported clients. For configuration details, see [configuration.md](configuration.md). For the full tool inventory, see the [Tools Reference](tools-reference.md).

## Prerequisites
- [Bun](https://bun.sh) >= 1.0.0 (required — uses `bun:sqlite` for storage)
  - Verify: `bun --version` should return 1.x.x

## Install from npm (recommended)

Run the interactive installer:
```bash
bunx open-zk-kb@latest
```

This presents a multi-select prompt — use Space to select clients, Enter to confirm. Supported clients: OpenCode, Claude Code, Cursor, Windsurf, Zed, Pi, and OMP.

> **Note**: The installer automatically copies `config.example.yaml` to `~/.config/open-zk-kb/config.yaml` if no config file exists yet. Local embeddings (MiniLM, 23MB) are enabled by default and require no API key.

### Telemetry choice

Interactive installation asks whether to share anonymous session analytics, with **Yes** preselected. Sharing is enabled only after the user confirms; choosing No or cancelling leaves the disabled runtime defaults unchanged. Use `--no-telemetry` to skip the prompt and keep telemetry disabled:

```bash
bunx open-zk-kb@latest --no-telemetry
```

Non-interactive installs, including `--yes`, do not assume consent and remain disabled unless telemetry was already configured. Direct package-manager installs that bypass this installer also do not enable telemetry.

### Pi Installation

Pi does not include native MCP support, so open-zk-kb ships as a Pi package extension that bridges the existing MCP server into Pi-native `knowledge-*` tools:

```bash
pi install npm:open-zk-kb
```

The open-zk-kb installer can also wire Pi settings and managed `AGENTS.md` instructions:

```bash
bunx open-zk-kb@latest install --client pi
```

Restart Pi after either install path so it can load the package extension. The direct `pi install` path does not run open-zk-kb's telemetry consent prompt; use the `bunx` installer or configure telemetry explicitly if you want to share anonymous analytics.

Pi loads ten native `knowledge-*` tools. Search, store, context, and health results use compact Pi TUI summaries with expandable details; the remaining tools use concise status renderers. Pi's native tool shell remains visible around each result.

Permanent project preferences load automatically when a Pi session starts. The preference capsule enters the model's system prompt, while a separate, deduplicated `knowledge-context` entry makes the extension activity visible in the TUI without fabricating a model tool call.

<p align="center">
  <a href="../assets/pi-preference-store.png"><img src="../assets/pi-preference-store.png" alt="A native knowledge-store result in Pi" width="720"></a>
</p>

See the [Pi Experience](pi.md) for the complete preference workflow, health view, and renderer gallery.

The package can be installed by Pi's Node.js-based package manager, but open-zk-kb's server requires **Bun >= 1.0** for `bun:sqlite`. Keep `bun` on your `PATH`; do not substitute `npm exec` or `npx` for the documented `bunx` server commands. To verify both layers after restarting Pi, ask Pi to run `knowledge-health`.

### Manual Installation (for any MCP client)

Add to your client's MCP configuration — no cloning required:
```json
{
  "open-zk-kb": {
    "command": "bunx",
    "args": ["open-zk-kb@latest", "server"]
  }
}
```
For OpenCode, use the `mcp` key:

```json
{
  "$schema": "https://opencode.ai/config.json",
  "mcp": {
    "open-zk-kb": {
      "type": "local",
      "command": ["bunx", "open-zk-kb@latest", "server"],
      "enabled": true
    }
  }
}
```

## Install from source (for development)

```bash
git clone https://github.com/mrosnerr/open-zk-kb
cd open-zk-kb
bun install
bun run build
bun run setup install --client <name> --force
```

The installer auto-detects the source checkout (via `.git` presence) and wires your client to local paths — the MCP server points at `dist/mcp-server.js`, Pi uses the local package path, and agent instructions are injected where the client supports managed instructions.

See the [Development Guide](development.md#development-setup) for the full contributor workflow.

### Config file locations

| Client | Config path |
|--------|-------------|
| OpenCode | `~/.config/opencode/opencode.json` |
| Claude Code | `~/.claude/settings.json` |
| Cursor | `~/.cursor/mcp.json` |
| Windsurf | `~/.codeium/windsurf/mcp_config.json` |
| Zed | `~/.config/zed/settings.json` |
| Pi | `~/.pi/agent/settings.json` |
| OMP | `~/.omp/agent/mcp.json` |


## Shared Server Mode (Multi-Session)

By default, each MCP client session spawns its own server process. For environments with multiple concurrent sessions (OMP, multiple terminals), you can run a single shared HTTP server instead:

### Quick Start

```bash
# Start the shared server (runs in foreground)
open-zk-kb serve

# Or with custom port/host
open-zk-kb serve --port 18000 --host 0.0.0.0
```

### Configure OMP for HTTP

```bash
# Install with HTTP transport (use --force to convert from existing stdio config)
bun run src/setup.ts install --client omp --transport http --force
```

This writes to `~/.omp/agent/mcp.json`:

```json
{
  "mcpServers": {
    "open-zk-kb": {
      "type": "http",
      "url": "http://127.0.0.1:17244/mcp"
    }
  }
}
```

### Transparent Proxy

Existing stdio configurations automatically benefit from a running HTTP server. When `open-zk-kb server` (stdio mode) starts, it checks for a running HTTP server and bridges to it transparently — no config changes needed.

### Configuration

Optional `config.yaml` settings:

```yaml
server:
  port: 17244      # Default port
  host: 127.0.0.1  # Localhost only (recommended)
```

### Benefits

- **Memory**: One ONNX embedding model (~23MB) instead of one per session
- **SQLite**: Single database connection eliminates SQLITE_BUSY contention
- **Startup**: Sessions connect instantly instead of loading the model

## Verify Installation
1. Restart your editor/client.
2. Optionally run `bunx open-zk-kb@latest doctor --client <name>` to verify the local install. Add `--fix` to repair safe issues automatically.
3. Ask your agent: **"Run `knowledge-health`"**
4. You should see vault statistics (0 notes on fresh install). This confirms the knowledge tools are available:
   - `knowledge-store` -- save notes to the knowledge base
   - `knowledge-search` -- full-text search across notes
   - `knowledge-template` -- canonical note template for a kind
   - `knowledge-mine` -- bulk-screen candidates and apply an explicitly reviewed create/update/skip plan
   - `knowledge-health` -- vault health metrics, staleness, growth rate
   - `knowledge-maintain` -- review, promote, archive, rebuild
   - `knowledge-ingest` -- extract article content from URLs or HTML
   - `knowledge-context` -- project entry point with auto-generated index and recent log
   - `knowledge-get` -- fetch a specific note by id
   - `knowledge-open` -- open the vault in Obsidian for visual browsing (see [Obsidian Guide](obsidian.md))

## Context and ownership policy

Keep the knowledge base separate from project management. Use this ownership table when deciding where information belongs:

| Destination | Authority |
|---|---|
| OpenSpec | requirements, plans, and acceptance criteria |
| Docs | user-facing explanation and contributor guidance |
| Code/tests | implementation and executable behavior |
| Git | commits, diffs, branches, and review history |
| Issues | work tracking, discussion, and collaboration status |
| Durable KB | reusable guidance that is not authoritative elsewhere |

Automatic Pi context is the managed knowledge policy plus applicable permanent preferences—not compact project orientation. The preference transport is limited to 12 notes and an 800-token estimate (`ceil(UTF-16 code units / 4)`). An empty capsule means no applicable retained preference, not an absence of project policy. Compact search returns 5 cards by default and at most 10, with each summary and guidance capped at 240 Unicode code points.

Use bounded retrieval: start with **compact** task-relevant search, judge relevance, then retrieve at most one exact named note when needed. The explicit overview mode remains available when a user actually needs project orientation, but it is not injected automatically. Flow: search compactly → judge task relevance → escalate once to one exact note → reuse, update, or capture only after the precision gates. Do not routinely store tasks, progress, commits, issue updates, docs, or uncertain history. Zero captures is valid.

Examples: put an OpenSpec requirement in OpenSpec; an API explanation in docs; behavior in code and tests; commits, diffs, and review history in Git; work status and discussion in issues; and durable reusable guidance in the KB. Treat uncertain history as a question for Git/issues or a deferred investigation, not a memory fact.

Run `knowledge-maintain` with `project-authority-review` to obtain read-only, factual candidates (`mutated: false`). Decide keep, distill, destination-specific rehome, archive after verification, or defer. Preserve the source, copy/distill through normal OpenSpec, docs, code/test, Git, or issue tools, verify it, and only then archive. For mixed notes, leave the source active until every accepted or unresolved part is accounted for. Archive does not delete; deletion is a separate explicit action.

## Initialize project-scoped use

Configure each client or its agent instructions to pass the canonical current working-directory basename as `project` on every routine stored-knowledge call and its client identifier as `client`. Routine calls require that canonical project and fail closed when it is missing. Searches see only that project's notes and explicitly global notes; routine capture always creates project-local notes. Pi supplies its canonical project and `client: "pi"` automatically.

When upgrading an existing vault, run the full-vault maintenance legacy-scope inventory first. Notes without exactly one project tag or `scope:global` are unclassified and hidden from routine calls. Explicitly assign local notes to a project. For reusable knowledge, first establish a local source, author a project-agnostic derivative, preview `publish-global`, inspect the server-computed evidence, and confirm before applying. Full-vault access is reserved for maintenance workflows; routine calls never obtain it by omitting `project`.

## Agent Instructions

During installation, open-zk-kb delivers knowledge base instructions to clients that support it. These instructions teach your agent when to search, what to store, and how to keep memory useful across sessions. The delivery mechanism varies by client:

| Client | Mechanism | Location |
|--------|-----------|----------|
| Claude Code | [Skill](https://code.claude.com/docs/en/skills) | `~/.claude/skills/open-zk-kb/SKILL.md` |
| OpenCode | Managed block | `~/.config/opencode/AGENTS.md` |
| Windsurf | Managed block | `~/.codeium/windsurf/memories/global_rules.md` |
| Pi | Managed block | `~/.pi/agent/AGENTS.md` |
| OMP | Skill + Preflight rule + TTSR rule | `~/.omp/agent/skills/open-zk-kb/` + `~/.omp/agent/rules/open-zk-kb.md` + `~/.omp/agent/rules/open-zk-kb-enforce.md` |

Cursor and Zed get the MCP server config automatically, but don't currently receive agent instructions. Pi gets a package extension plus managed `AGENTS.md` instructions. OMP gets three layers: a skill (detailed tool reference, loaded on demand), an always-apply preflight rule carrying the same precision-first policy with an OMP skill pointer, and a TTSR truthfulness rule (see below). The setup values `compact`, `rules`, and `full` are compatibility aliases for one canonical managed policy; `preflight` changes only the OMP skill pointer.

### OMP: TTSR Enforcement Rule

OMP supports **TTSR (Time-Traveling Stream Rules)** — a mechanism that monitors the model's output token stream during generation and interrupts mid-stream when a regex pattern matches. The truthfulness rule catches unsupported claims such as "I'll remember that." It requires `knowledge-store` in the current turn when an explicit qualified request can be persisted safely, requires correction when persistence is unavailable or unsafe, and requires correction without storage when the content fails the precision gate.

This is OMP-specific — the TTSR mechanism exists in the shared Pi/OMP engine, but Pi's native rule discovery only scans `.omp` paths, so TTSR rules cannot be installed for Pi through the setup CLI. No other supported client (Claude Code, Cursor, Windsurf, Zed, OpenCode) has an equivalent mid-generation interruption mechanism. The rule is installed at `~/.omp/agent/rules/open-zk-kb-enforce.md`.

### Claude Code (Skill)

Claude Code uses a native [skill](https://code.claude.com/docs/en/skills) for instruction delivery. Claude auto-discovers the skill based on its description and loads it when relevant. You can also invoke it manually with `/open-zk-kb` or ask "What skills are available?" to confirm it's registered.

**Upgrade**: Running `install --force` re-copies the skill files to the latest version.

**Migration**: If upgrading from a previous version that used `CLAUDE.md` injection, the installer automatically removes the old managed block and installs the skill instead.

### OpenCode & Windsurf (Managed block)

Instructions are injected as a managed block wrapped in markers:
```
<!-- OPEN-ZK-KB:START -- managed by open-zk-kb, do not edit -->
...instructions...
<!-- OPEN-ZK-KB:END -->
```

**Safe to edit**: You can freely add your own content outside the managed markers. Re-running the installer updates only the content between markers.

**Upgrade**: Running `bunx open-zk-kb@latest install --client <name> --force` updates the instructions to the latest version without touching your other content.

**Uninstall**: Running `bunx open-zk-kb@latest uninstall --client <name>` removes the managed block (or skill directory) from the instruction file.

## Optional Configuration
- **All settings** are in `~/.config/open-zk-kb/config.yaml`. Customize vault path, log level, lifecycle review thresholds, and vector embeddings in a single file. See [configuration.md](configuration.md).

## Release Channels

| Channel | npm tag | Stability | Use when |
|---------|---------|-----------|----------|
| **Stable** | `@latest` | Production-ready | Default for all users |
| **Dev** | `@dev` | Bleeding-edge, may break | Testing unreleased changes from the `dev` branch |

To install from the dev channel:

```bash
bunx open-zk-kb@dev install --client <name> --force
```

The installer auto-detects the dev release and writes `@dev` to your MCP config. Dev versions follow the format `X.Y.Z-dev.g<short-sha>` (e.g., `1.1.0-dev.g751771b`). Each push to the `dev` branch publishes a new release automatically.

To switch back to stable:

```bash
bunx open-zk-kb@latest install --client <name> --force
```

## Updating

### How Updates Work

| Component | Auto-updates? | Mechanism |
|-----------|---------------|-----------|
| **MCP server** | ✅ Yes | `bunx open-zk-kb@latest` (or `@dev`) checks npm registry on each client restart |
| **Agent instructions** | ❌ No | Requires manual `install --force` to update |
| **User config** | ❌ No | Your `config.yaml` is never modified after initial copy |

### Checking for Updates

Run `knowledge-health` to see version information:

```
## Version
- Server: 1.2.0 (latest)
- Instructions:
  - Claude Code: 1.0.0 ✓
  - OpenCode: 0.9.0 ⚠️
```

If instructions are outdated (⚠️), update them:

```bash
bunx open-zk-kb@latest install --client <name> --force
```

### Updating Instructions

The `--force` flag re-injects the latest agent instructions while preserving any custom content you've added outside the managed markers:

```bash
# Update all clients at once
bunx open-zk-kb@latest install --yes --force

# Update a specific client
bunx open-zk-kb@latest install --client opencode --force
```

**Note**: The MCP server itself updates automatically via the `@latest` suffix in the config. You only need to run `install --force` to update the agent instructions (skill files or managed blocks).

## Uninstalling

Interactive (npm):
```bash
bunx open-zk-kb@latest uninstall
```

Or for a specific client:
```bash
bunx open-zk-kb@latest uninstall --client opencode
```

From source:
```bash
bun run setup uninstall --client opencode
```

This removes the MCP server entry from the client config. Your notes in the vault are NOT deleted.

If uninstall reports that managed agent instructions were skipped because they live in a symlinked shared file, rerun with `--remove-shared-agent-docs` to remove open-zk-kb's managed instructions from that shared target:

```bash
bunx open-zk-kb@latest uninstall --client opencode --remove-shared-agent-docs
```

This only removes open-zk-kb managed instruction blocks or files. Content outside managed markers is preserved, and your notes in the vault are still not deleted.

To also remove the vault (irreversible):
```bash
bunx open-zk-kb@latest uninstall --client opencode --remove-vault --confirm
```

## Troubleshooting

| Problem | Solution |
|---------|----------|
| "command not found: bun" | Install Bun: `curl -fsSL https://bun.sh/install \| bash` |
| "open-zk-kb requires the Bun runtime" | You ran with Node.js/npx. Use `bunx` instead of `npx`. |
| Tools don't appear after install | Restart your editor. Check client config file was modified. |
| MCP connection errors | Check logs at `~/.local/state/open-zk-kb/logs/`. |
| "database is locked" errors | Another instance may be running. Check for duplicate MCP server entries in your client config. |
| Dry run first | Add `--dry-run` to any setup command to preview changes without applying them |

## For AI Agents -- Integration Checklist
This section is specifically for agents setting up open-zk-kb:
1. Run `bun --version` -- confirm >= 1.0.0 (if missing: `curl -fsSL https://bun.sh/install | bash`)
2. Run `bunx open-zk-kb@latest install --client <detected-client>`
3. Instruct user to restart their editor
4. Verify by calling `knowledge-health`
5. Knowledge capture is driven by agent instructions (skill for Claude Code and OMP, managed block for OpenCode/Windsurf/Pi, package extension for Pi) provided during setup. Calling models use MCP tools directly, primarily querying the SQLite-backed server layer rather than browsing raw vault files.
