> ## Documentation Index
> Fetch the complete documentation index at: https://docs.kernle.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Claude Code

> Automatic memory lifecycle for Claude Code sessions

# Claude Code Integration

Kernle integrates with Claude Code via hooks — memory loads automatically, checkpoints save before compaction and at session end, and native memory file writes are intercepted and captured into Kernle.

## How It Works

```
CLAUDE CODE SESSION STARTS
       ↓
1. SessionStart hook fires
2. `kernle hook session-start` loads memory
3. Memory injected as session context automatically
4. SI has full memory: values, beliefs, goals, checkpoint, episodes
       ↓
   SI WORKS (captures memories via CLI as they happen)
       ↓
   CONTEXT COMPACTION
       ↓
5. PreCompact hook saves checkpoint automatically
6. SessionStart re-fires — memory reloaded into fresh context
       ↓
   SI CONTINUES WORKING
       ↓
SESSION ENDS
       ↓
7. SessionEnd hook saves final checkpoint automatically
```

### Write Interception

When the SI tries to write to `memory/` or `MEMORY.md` (Claude Code's native memory), the PreToolUse hook:

1. Captures the content as a Kernle raw entry
2. Blocks the write
3. Returns a message directing the SI to use Kernle commands instead

This ensures all memory flows through Kernle's structured system.

## Installation (Recommended)

The recommended approach uses `kernle setup` which writes hooks directly into `.claude/settings.json` — no plugin directory or repo access needed.

<Steps>
  <Step title="Install Kernle">
    ```bash theme={null}
    pip install kernle
    # or
    pipx install kernle
    ```
  </Step>

  <Step title="Initialize a Stack">
    ```bash theme={null}
    kernle -s my-project init
    ```
  </Step>

  <Step title="Setup Claude Code Hooks">
    ```bash theme={null}
    # Project-level (writes to .claude/settings.json)
    kernle setup claude-code

    # Or global (writes to ~/.claude/settings.json)
    kernle setup claude-code --global
    ```
  </Step>

  <Step title="Verify">
    ```bash theme={null}
    kernle doctor --full
    ```

    Then start a new Claude Code session:

    ```bash theme={null}
    claude
    ```

    Ask: *"What are my current values and goals from Kernle?"*

    The SI should respond with your memory without needing to run any commands.
  </Step>
</Steps>

## Installation (Plugin Mode)

Alternatively, use the plugin directory (requires access to the Kernle source repo):

```bash theme={null}
claude --plugin-dir ./integrations/claude-code
```

Both approaches call the same `kernle hook <event>` commands.

## Configuration

All configuration is via environment variables — no config files needed:

| Variable              | Default       | Description                     |
| --------------------- | ------------- | ------------------------------- |
| `KERNLE_STACK_ID`     | auto-detected | Kernle stack ID                 |
| `KERNLE_TOKEN_BUDGET` | `8000`        | Token budget for memory loading |

### Stack ID Resolution

The hooks resolve the stack ID in order:

1. `--stack` flag baked into hook commands by `kernle setup`
2. `KERNLE_STACK_ID` environment variable
3. Project directory name from working directory
4. Kernle auto-resolve

For multi-project setups, set `KERNLE_STACK_ID` in your shell profile:

```bash theme={null}
export KERNLE_STACK_ID=my-project
```

## Hooks

### SessionStart — Memory Loading

Fires on startup, resume, clear, and compact. Loads memory and injects it as `additionalContext` in the session.

### PreToolUse — Write Interception

Matches `Write`, `Edit`, and `NotebookEdit` tool calls. When the target path matches a memory file (`memory/`, `MEMORY.md`), the hook:

* Captures the content as a Kernle raw entry (for preservation)
* Blocks the write with a deny decision
* Returns a message explaining that memory is handled by Kernle

### PreCompact — Pre-Compaction Checkpoint

Fires before context compaction. Reads the transcript to extract the last user message (task) and assistant message (context), then saves a checkpoint prefixed with `[pre-compact]`.

### SessionEnd — Final Checkpoint

Fires when the session terminates. Reads the transcript and saves both a checkpoint and a raw entry marking session completion.

### Graceful Degradation

All hooks exit 0 on any error. If Kernle is not installed, the stack doesn't exist, or any command fails, the session continues normally with no error messages.

## What Gets Loaded

The SessionStart hook loads memory containing:

* **Checkpoint** — current task, context, next steps (resume point)
* **Values** — core principles
* **Beliefs** — held truths with confidence levels
* **Goals** — active goals with priority
* **Drives** — motivations with intensity
* **Lessons** — extracted from recent episodes
* **Relationships** — key entities with sentiment

Memory loading is budget-aware (default 8000 tokens). Items are loaded by priority: checkpoint > values > beliefs > goals > drives > episodes > notes > relationships.

## During Work

The SI captures memories via CLI as they happen. Each command writes immediately to local storage:

```bash theme={null}
# Quick capture
kernle -s my-project raw "API rate limit is per-user, not per-key"

# Record a significant experience
kernle -s my-project episode "Debugged API timeout" "success" \
  --lesson "Check network latency before assuming code issues"

# Document a decision
kernle -s my-project note "Using Redis for session cache" \
  --type decision \
  --reason "Need sub-millisecond reads"
```

## Relationship to Native Features

Claude Code has its own memory mechanisms. Here's how they interact with Kernle:

| Feature                               | What It Does                      | Kernle Relationship                                        |
| ------------------------------------- | --------------------------------- | ---------------------------------------------------------- |
| `CLAUDE.md`                           | Static project instructions       | **Coexists** — different purpose (instructions vs memory)  |
| Auto-memory (`~/.claude/.../memory/`) | Simple text notes across sessions | **Replaced** — hook intercepts writes and routes to Kernle |
| Conversation context                  | In-session history                | **Coexists** — Kernle adds cross-session persistence       |

<Note>
  `CLAUDE.md` is not replaced by Kernle. It serves as the project instruction file — where you put setup commands, coding guidelines, and workflow rules. Kernle handles dynamic memory (what the SI has experienced, learned, and believes).
</Note>

## MCP Server (Alternative)

Kernle also provides an MCP server that works with Claude Code. This is an alternative to the hook approach — use one or the other for memory loading, not both.

The hook approach is recommended because:

* Memory loads automatically (no manual tool call needed)
* Auto-checkpointing before compaction and at session end
* Native write interception routes all memory through Kernle
* No MCP configuration required

If you need MCP tools during the session (e.g., `memory_search`, `memory_anxiety`), you can use both: hooks for automatic lifecycle management, and MCP for in-session memory operations. See the [MCP Integration](/integration/mcp) guide.

## Diagnostics

Verify the integration works:

```bash theme={null}
# Full health check (includes hook validation)
kernle doctor --full

# Verify Kernle is available
which kernle
kernle -s my-project status

# Test loading manually
kernle -s my-project load

# Test hooks manually
echo '{"cwd": "."}' | kernle hook session-start
```

## Troubleshooting

### Memory not appearing at session start

1. Run the doctor check:
   ```bash theme={null}
   kernle doctor --full
   ```

2. Verify hooks are in settings.json:
   ```bash theme={null}
   cat .claude/settings.json
   # Should show SessionStart, PreToolUse, PreCompact, SessionEnd hooks
   ```

3. Test the load command manually:
   ```bash theme={null}
   kernle -s my-project load
   ```

4. Check if stack is initialized:
   ```bash theme={null}
   kernle -s my-project status
   ```

### Kernle command not found

Ensure Kernle is installed and in PATH:

```bash theme={null}
which kernle
# If missing:
pip install kernle
```

### Writes to MEMORY.md being blocked

This is expected behavior. The hook intercepts writes to memory files and routes them through Kernle. Use Kernle CLI commands instead:

```bash theme={null}
kernle -s my-project raw "your thought here"
kernle -s my-project note "your observation" --type insight
```
