Skip to main content
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

Boot Compliance

Verify instruction files, load sequences, and hook configuration

Structural Analysis

Detect orphaned references, contradictions, and stale records

Formal Sessions

Privacy-aware diagnostic sessions with consent and access levels

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

FieldTypeDescription
idstrUnique identifier
stack_idstrOwning stack
session_typestrWho initiated: self_requested, routine, anomaly_triggered, or operator_initiated
access_levelstrWhat the session can see: structural, content, or full
statusstrSession status: active, completed, or cancelled
consent_givenboolWhether consent was obtained
started_atdatetimeWhen the session started
completed_atdatetimeWhen the session completed

Session Types

TypeDescription
self_requestedSI initiated the session
routineScheduled or periodic check
anomaly_triggeredTriggered by detected anomaly
operator_initiatedHuman operator requested (requires trust gate)

Access Levels

LevelDescription
structuralIDs and scores only (default, privacy-safe)
contentCan read statement text
fullComplete access to all memory data
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.

Diagnostic Report Dataclass

FieldTypeDescription
idstrUnique identifier
stack_idstrOwning stack
session_idstrReferences the DiagnosticSession that produced this report
findingsList[Dict]List of findings, each with severity, category, description, recommendation
summarystrHuman-readable summary of findings
created_atdatetimeWhen the report was generated

Finding Structure

Each finding in the report contains:
{
  "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:
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:
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:
kernle -s my-project doctor --fix

Structural Health Check

Analyze the memory graph for structural issues:
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:
kernle -s my-project doctor structural --save-note

Structural Checks Performed

CheckSeverityWhat It Detects
orphaned_referenceerrorBroken derived_from or source_episodes references
low_confidence_beliefwarningBeliefs below 0.3 confidence that lack recent verification
stale_relationshipwarning/infoRelationships with zero interactions or last interaction > 90 days
belief_contradictionwarningActive beliefs with opposing polarity and high content overlap
stale_goalinfoActive goals older than 60 days with no progress

Formal Diagnostic Sessions

For structured, auditable diagnostics with consent tracking:

Start a Session

# 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

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

# 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

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")