> ## 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.

# Doctor Pattern

> Formal diagnostic sessions for memory system health and structural analysis

The doctor pattern provides structured diagnostic sessions for evaluating memory system health. It checks instruction file compliance, seed belief integrity, platform hook installation, and performs deep structural analysis of the memory graph.

## Overview

<CardGroup cols={3}>
  <Card title="Boot Compliance" icon="clipboard-check">
    Verify instruction files, load sequences, and hook configuration
  </Card>

  <Card title="Structural Analysis" icon="microscope">
    Detect orphaned references, contradictions, and stale records
  </Card>

  <Card title="Formal Sessions" icon="file-medical">
    Privacy-aware diagnostic sessions with consent and access levels
  </Card>
</CardGroup>

## Why Diagnostics Matter

Memory systems degrade over time. References break, beliefs accumulate contradictions, relationships go stale, and goals lose relevance. The doctor pattern provides a principled approach to memory health:

* **Early detection**: Find problems before they affect SI behavior
* **Privacy-safe**: Structural checks use IDs and scores only, never memory content
* **Audit trail**: Diagnostic sessions and reports are persisted for review
* **Trust-gated**: Operator-initiated sessions require sufficient trust

***

## Diagnostic Session Dataclass

| Field           | Type       | Description                                                                              |
| --------------- | ---------- | ---------------------------------------------------------------------------------------- |
| `id`            | `str`      | Unique identifier                                                                        |
| `stack_id`      | `str`      | Owning stack                                                                             |
| `session_type`  | `str`      | Who initiated: `self_requested`, `routine`, `anomaly_triggered`, or `operator_initiated` |
| `access_level`  | `str`      | What the session can see: `structural`, `content`, or `full`                             |
| `status`        | `str`      | Session status: `active`, `completed`, or `cancelled`                                    |
| `consent_given` | `bool`     | Whether consent was obtained                                                             |
| `started_at`    | `datetime` | When the session started                                                                 |
| `completed_at`  | `datetime` | When the session completed                                                               |

### Session Types

| Type                 | Description                                    |
| -------------------- | ---------------------------------------------- |
| `self_requested`     | SI initiated the session                       |
| `routine`            | Scheduled or periodic check                    |
| `anomaly_triggered`  | Triggered by detected anomaly                  |
| `operator_initiated` | Human operator requested (requires trust gate) |

### Access Levels

| Level        | Description                                 |
| ------------ | ------------------------------------------- |
| `structural` | IDs and scores only (default, privacy-safe) |
| `content`    | Can read statement text                     |
| `full`       | Complete access to all memory data          |

<Warning>
  Operator-initiated sessions are gated by trust. The `stack-owner` entity must have trust at or above the `diagnostic` threshold (0.85) for the session to proceed.
</Warning>

***

## Diagnostic Report Dataclass

| Field        | Type         | Description                                                                         |
| ------------ | ------------ | ----------------------------------------------------------------------------------- |
| `id`         | `str`        | Unique identifier                                                                   |
| `stack_id`   | `str`        | Owning stack                                                                        |
| `session_id` | `str`        | References the `DiagnosticSession` that produced this report                        |
| `findings`   | `List[Dict]` | List of findings, each with `severity`, `category`, `description`, `recommendation` |
| `summary`    | `str`        | Human-readable summary of findings                                                  |
| `created_at` | `datetime`   | When the report was generated                                                       |

### Finding Structure

Each finding in the report contains:

```json theme={null}
{
  "severity": "warning",
  "category": "low_confidence_belief",
  "description": "Belief #6bc41d9d (confidence 0.25) -- low confidence, never verified",
  "recommendation": "Review and verify or archive low-confidence beliefs"
}
```

Severity levels: `error`, `warning`, `info`.

***

## CLI Commands

### Basic Doctor Check

The default `doctor` command checks instruction file compliance:

```bash theme={null}
kernle -s my-project doctor
```

```
╔══════════════════════════════════════════════════╗
║         Kernle Doctor - System Health            ║
╚══════════════════════════════════════════════════╝
  Stack: my-project
  Seed Beliefs Version: 3
  Instruction File: CLAUDE.md

Status: Good - required checks pass, some recommendations missing
   Required: 3/3
   Recommended: 2/3

──────────────────────────────────────────────────
INSTRUCTION FILE CHECKS
──────────────────────────────────────────────────
  [required]     Instruction file found: CLAUDE.md
  [required]     Load instruction found
  [required]     Health check instruction found
  [recommended]  Per-message health check instruction found
  [recommended]  Checkpoint instruction found
  [recommended]  Dedicated memory section found
```

### Full Doctor Check

Include seed beliefs and platform hook verification:

```bash theme={null}
kernle -s my-project doctor --full
```

This adds two additional sections:

```
──────────────────────────────────────────────────
SEED BELIEFS
──────────────────────────────────────────────────
  [recommended]  Full seed beliefs present (12/12) v3

──────────────────────────────────────────────────
PLATFORM HOOKS
──────────────────────────────────────────────────
  [recommended]  Claude Code hook configured (global)
```

### Auto-Fix

Attempt to fix instruction file issues automatically:

```bash theme={null}
kernle -s my-project doctor --fix
```

### Structural Health Check

Analyze the memory graph for structural issues:

```bash theme={null}
kernle -s my-project doctor structural
```

```
=======================================================
  Kernle Doctor - Structural Health Check
=======================================================
  Stack: my-project

  Findings: 1 errors, 3 warnings, 2 info

-------------------------------------------------------
ERRORS
-------------------------------------------------------
  [error]   Belief #6bc41d9d has broken derived_from ref -> episode:missing123

-------------------------------------------------------
WARNINGS
-------------------------------------------------------
  [warning] Belief #a1b2c3d4 (confidence 0.25) -- low confidence, never verified
  [warning] Relationship #e5f6a7b8 (old-collaborator) -- zero interactions
  [warning] Potential contradiction: Belief #1a2b3c4d vs #5e6f7a8b (overlap: 45%)

-------------------------------------------------------
INFO
-------------------------------------------------------
  [info]    Relationship #c9d0e1f2 (former-team) -- last interaction 120d ago
  [info]    Goal #f3a4b5c6 is active but 75d old -- consider reviewing status
```

Save findings as a diagnostic note:

```bash theme={null}
kernle -s my-project doctor structural --save-note
```

### Structural Checks Performed

| Check                   | Severity     | What It Detects                                                    |
| ----------------------- | ------------ | ------------------------------------------------------------------ |
| `orphaned_reference`    | error        | Broken `derived_from` or `source_episodes` references              |
| `low_confidence_belief` | warning      | Beliefs below 0.3 confidence that lack recent verification         |
| `stale_relationship`    | warning/info | Relationships with zero interactions or last interaction > 90 days |
| `belief_contradiction`  | warning      | Active beliefs with opposing polarity and high content overlap     |
| `stale_goal`            | info         | Active goals older than 60 days with no progress                   |

***

## Formal Diagnostic Sessions

For structured, auditable diagnostics with consent tracking:

### Start a Session

```bash theme={null}
# Self-requested session (default)
kernle -s my-project doctor session start

# Routine check
kernle -s my-project doctor session start --type routine

# Operator-initiated (trust-gated)
kernle -s my-project doctor session start --type operator_initiated
```

```
=======================================================
  Kernle Doctor - Diagnostic Session
=======================================================
  Stack: my-project
  Session: a1b2c3d4e5f6...
  Type: self_requested
  Access: structural

  Found 3 finding(s): 1 error(s), 2 warning(s)

-------------------------------------------------------
ERRORS
-------------------------------------------------------
  [error]   Belief #6bc41d9d has broken derived_from ref -> episode:missing123
           -> Remove or update broken references

-------------------------------------------------------
WARNINGS
-------------------------------------------------------
  [warning] Belief #a1b2c3d4 (confidence 0.25) -- low confidence, never verified
           -> Review and verify or archive low-confidence beliefs

  Report saved: f7a8b9c0d1e2...
```

### List Sessions

```bash theme={null}
kernle -s my-project doctor session list
```

```
=======================================================
  Kernle Doctor - Diagnostic Sessions
=======================================================
  Stack: my-project

  [done]   a1b2c3d4e5f6...  self_requested        2026-02-01 10:30
  [done]   b2c3d4e5f6a7...  routine               2026-01-15 09:00
```

### View a Report

```bash theme={null}
# View the latest report
kernle -s my-project doctor report latest

# View a specific report by session ID
kernle -s my-project doctor report a1b2c3d4e5f6
```

***

## Python API

```python theme={null}
from kernle import Kernle
from kernle.storage.base import DiagnosticSession, DiagnosticReport
import uuid
from datetime import datetime, timezone

k = Kernle(stack_id="my-stack")

# Run the basic doctor check (instruction file compliance)
# This is primarily a CLI command; programmatic usage works through storage

# Create a diagnostic session
session = DiagnosticSession(
    id=str(uuid.uuid4()),
    stack_id=k.stack_id,
    session_type="self_requested",
    access_level="structural",
    status="active",
    consent_given=True,
    started_at=datetime.now(timezone.utc),
)
k._storage.save_diagnostic_session(session)

# Run structural checks (internal API)
from kernle.cli.commands.doctor import run_structural_checks
findings = run_structural_checks(k)

# Create a report from findings
report = DiagnosticReport(
    id=str(uuid.uuid4()),
    stack_id=k.stack_id,
    session_id=session.id,
    findings=[f.to_dict() for f in findings],
    summary=f"Found {len(findings)} issue(s)",
    created_at=datetime.now(timezone.utc),
)
k._storage.save_diagnostic_report(report)

# Complete the session
k._storage.complete_diagnostic_session(session.id)

# List past sessions
sessions = k._storage.get_diagnostic_sessions(limit=10)
for s in sessions:
    print(f"  [{s.status}] {s.session_type} - {s.started_at}")

# Get reports for a session
reports = k._storage.get_diagnostic_reports(session_id=session.id)
for r in reports:
    print(f"  {r.summary}")
    for f in (r.findings or []):
        print(f"    [{f['severity']}] {f['description']}")

# Trust gating for operator-initiated diagnostics
result = k.gate_memory_input(
    source_entity="stack-owner",
    action="diagnostic"
)
if result["allowed"]:
    print("Operator diagnostic permitted")
```
