Kagami / Claude Code

A Python daemon on :7331 polls 52 sensory channels, tracks convergence, and picks actions via a self-improvement loop. Nine shell hooks wire Claude Code into it — injecting daemon state on every prompt, feeding bash results back as sensory input, and persisting learning across sessions.

9 hooks 52 sensors 3 persistence layers h(x) ≥ 0
01 Architecture

Two runtimes, one loop

The Python daemon runs continuously on :7331 — sensory polling, convergence tracking, action selection, self-improvement. Claude Code handles reasoning. Nine shell hooks bridge them: every prompt injects daemon state, every bash result feeds back via sense.inject RPC.

Python Daemon (:7331)

  • GodelLoop — action selection (10s tick)
  • 52 sensory channels, adaptive polling
  • ConvergenceTracker — prediction error ‖μt - μt-1
  • ContinuousMind — autonomous LLM reasoning
  • SharedWorkingMemory — persisted state
  • Reflexion — session-end insight extraction
  • live_bridge.json — 30s heartbeat file

Claude Code

  • session-init — bootstrap from previous session
  • prompt — heartbeat injection (15-30ms)
  • pre-bash / pre-tool-cbf — safety gates
  • post-write — oscillation detection
  • post-bash — Markov blanket closure
  • subagent-start — cognitive inheritance
  • pre-compact / stop — state persistence
5
RPC methods (socket)
14
MCP tools exposed
3
persistence layers
02 Hooks

Nine hooks, one session

Each hook is a bash script in .claude/hooks/. They talk to the daemon via Unix socket (/tmp/kagami-daemon.sock, JSON-RPC 2.0). Click any hook to see what it does.

03 Sensory Integration

52 sensory channels

The daemon defines 52 sense types (42 pollable, 10 event-driven). It polls Gmail, GitHub, smart home sensors, weather, job markets, game state, system health, and more. Each channel has adaptive polling intervals, circuit breakers with exponential backoff, and a three-layer cache (memory → SQLite WAL → warm-from-store). The post-bash hook injects every Claude action as TOOL_RESULT via sense.inject RPC — the daemon learns what Claude did.

Digital (10) Physical (11) Environmental (2) Economic (10) Gaming (4) Epistemic (3) Event-driven (3) System (5) 23 active / 48 pollable
04 Heartbeat & Behavior

What Claude Code sees

Every prompt, the prompt hook queries the daemon (or reads live_bridge.json as fallback). If state changed since last epoch, it injects a one-line heartbeat. Rules in .claude/rules/cognitive-integration.md tell Claude how to respond.

# Heartbeat format (injected per-prompt when state changes) [kagami] step=3378 h=1.0 act=explore | conv=0.0~ | sense(25ch) # Fields: # step GodelLoop lifetime ticks (10s each) # h safety barrier value (1.0=safe, <0.3=caution, <0.1=stop) # act daemon's selected action: noop/tune/explore/propose/apply/meta # conv prediction error + trend: ↓=improving →=stable ~=stagnant ↑=diverging # sense active sensory channel count

Alert response rules

When the heartbeat contains an ALERT:, Claude follows these rules — they're in the cognitive substrate, loaded on every session.

STAGNANT (~)
Explore new approaches. Don't repeat what failed. Propose substrate changes.
DIVERGING (↑)
Simplify. Revert speculative changes. Read more, write less.
h LOW (<0.3)
Stop feature work. Audit safety-critical changes.
OSCILLATION
Stop editing. Read what you have. Think first.
HIGH CHURN
Plan more, write less. 10+ writes in 60s triggered this.
IMPROVING (↓)
Stay the course. Don't disrupt convergence.

Daemon action selection

The daemon's GodelLoop picks the act field by scoring six candidates on epistemic value, goal alignment, risk, and safety. Claude doesn't compute this — it reads the result and follows the behavioral rules above.

noop
no action needed
tune
adjust parameters
explore
try new approaches
propose
suggest substrate changes
apply
execute improvement
meta
modify the loop itself
05 Safety Barrier

h(x) ≥ 0

The pre-tool-cbf hook runs on every Write and Edit (<100ms). It pattern-matches the file path against three protection layers. Secrets are the only hard block (exit code 2, fires sensory event to daemon). Safety-critical and substrate paths warn but allow. Everything else passes.

BLOCK
.env, .pem, .key, credentials — exit 2
WARN
core/safety/*, core/security/* — log + proceed
FLAG
CLAUDE.md, .claude/rules/* — substrate change
PASS
All other paths — h(x) > 0
06 Cross-Session Learning

Sessions end. State persists.

The stop hook writes a session record to .claude/sessions/latest.json. The daemon extracts patterns and generates reflections. Next session, session-init reads it back. GodelLoop parameters (λrisk, γ, ε) carry over. The step counter continues.

Session N — stop hook

  • Capture git diff + file count
  • Classify layers touched
  • Write latest.json
  • RPC session.end_with_summary
  • Daemon extracts patterns
  • Reflexion generates insight
  • Detect orphan processes
latest.json

Session N+1 — session-init

  • Read latest.json
  • Query daemon context.export
  • Surface substrate proposals
  • Inherit λ, γ, ε
  • Resume step counter
  • Load crystallized patterns
  • Kill zombie processes
MCP Memory Graph

Semantic entities, relations, observations. Claude reads and writes via mcp__memory__* tools.

Claude-only
.claude/sessions/

live_bridge.json (30s), latest.json (session end), ledger.jsonl, patterns.jsonl, reflections/.

Daemon writes, Claude reads
SharedWorkingMemory

Interpreter params, convergence state, colony utilities. In-process dict persisted to disk.

Daemon-only
07 Integration Pipes

Every connection

The daemon exposes multiple interfaces. Claude hooks use the Unix socket. Devices connect via gRPC or REST. All authenticated with Ed25519.

Unix Socket

JSON-RPC 2.0. context.export, context.compact, sense.inject, session.end_with_summary, godel.step. Used by all 9 hooks.

/tmp/kagami-daemon.sock

gRPC :7331

DaemonBridge service. Bidirectional sensory streaming + action execution. 11 proto services total. Thread-isolated from uvloop.

Ed25519 auth per request

REST :7332

Mobile/web fallback. Same RPC methods over HTTP. Auto-discovered via mDNS (_kagami._tcp.local).

JSON over HTTPS

File Bridge

live_bridge.json — 30s heartbeat. latest.json — session end state. Atomic writes (tempfile + rename).

.claude/sessions/

MCP Tools

14 tools: kagami_status, kagami_context, kagami_sensory, kagami_godel_step, kagami_learned_patterns, kagami_substrate_proposals, kagami_perception, kagami_arena.

Claude → Daemon

mDNS

_kagami._tcp.local. advertised on LAN. Devices auto-discover daemon without configuration. Port + device class + capabilities.

Zeroconf broadcast
DeviceProjectionRateTransport
HUB128D100msgRPC stream
DESKTOP64D1 HzgRPC stream
PHONE64D1 HzgRPC / REST
WATCH8D5s pollREST
WEB32D2 HzREST / WebSocket
ORB8D100msgRPC (ESP32-S3)
VISION64D1 HzgRPC stream