# pdgit12/knitbrain architecture

> Architecture diagram of the GitHub repository pdgit12/knitbrain, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-07-08). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/pdgit12/knitbrain
- Repository: https://github.com/pdgit12/knitbrain

## Overview

1. **What this repo is**
   knitbrain is a local-first Node/TypeScript runtime for agent loops. It combines three concerns in one package: a state layer, an optimization layer, and an enforcement layer. The top-level CLI can run as an MCP server, a headless loop runner, a proxy wrapper, a dashboard, or an installer for host integrations.

2. **Primary entry points**
   `src/index.ts`, `src/server.ts`, `src/setup.ts`, `src/loop.ts`, `src/fan.ts`, `src/wrap.ts`, `src/dashboard.ts`, and `src/hub/*` are the main operational surfaces. They map to distinct modes: stdio MCP server, installation/bootstrap, goal loop execution, parallel fan-out, request-wrapping proxy mode, local observability, and optional team sync.

3. **Core engine boundary**
   `src/engine/*` is the application brain. It owns project onboarding, goal/workflow state, memory, knowledge graphs, retrieval, calibration, skills/agents/teams composition, quota and usage accounting, receipts, feedback, self-checks, and closed-loop iteration. This is where “done,” “fail,” and “learned” are decided, not in the host agent.

4. **Loop orchestration**
   The loop subsystem is centered around `src/engine/closed-loop.ts`, `workflow.ts`, `receipt.ts`, `feedback.ts`, `quota.ts`, `meter.ts`, and `usage.ts`. The data flow is: goal/constraints in, tool actions and verify results out, then failure history and saved state fed back into the next cycle. This is the main “can’t lie / can’t run away / can’t go broke” control boundary.

5. **State, memory, and knowledge**
   `src/engine/memory.ts`, `knowledge.ts`, `wiki.ts`, `retrieval.ts`, and `brain.ts` implement the persistent local memory model. They support session handoff, compounding knowledge, code/function retrieval, and project-specific onboarding artifacts. The repo’s architecture assumes state is local and durable under `~/.knitbrain`, not remote.

6. **Optimization pipeline**
   `src/optimizer/*`, `src/tokenizer.ts`, `src/compress-file.ts`, and `src/ccr/store.ts` implement output compression and recall. The key architectural idea is lossless, content-addressed recall: large outputs can be replaced by compact skeletons plus a retrieval handle, while the original bytes are stored locally for exact restoration. JSON/tool contracts are treated specially so machine-readable responses remain parseable.

7. **Two delivery paths for optimization**
   The repo has two materially different traffic paths. For API-key workflows, `src/proxy/*` sits between agent and provider and can rewrite requests/responses on the wire. For subscription/OAuth-hosted workflows, optimization happens through MCP tools and hooks instead, because the wire is not interceptable. The same optimization logic is reused, but the interception boundary changes.

8. **MCP tool server**
   `src/mcp/host.ts`, `instructions.ts`, and `tools.ts` define the MCP-facing surface. This is how editors/agents call into knitbrain for read, retrieval, memory, workflow, and meta operations. The MCP server is the common integration layer across Claude Code, Codex, Cursor, Gemini, Copilot, and other clients.

9. **Hook enforcement layer**
   `src/hooks/*` is the enforcement boundary. It detects the host platform, then uses PreToolUse, PostToolUse, SessionStart, and Stop-style hooks to deny forbidden actions, redirect oversized reads, inject goal context, and block premature stopping. This layer is what turns policy into physical enforcement at the agent-tool boundary.

10. **Host/platform adaptation**
   `src/platforms.ts`, `src/global-config.ts`, `src/profile.ts`, `src/paths.ts`, and `src/lib.ts` provide host detection, config resolution, filesystem locations, and shared utility behavior. The architecture is intentionally multi-host: the same core engine is adapted to each editor/CLI’s hook schema instead of forking the business logic.

11. **Optional team hub**
   `src/hub/server.ts` and `src/hub/client.ts` implement an optional local/team coordination channel. This is separate from the core local brain: it shares findings over a hub endpoint without changing the main persistence model or loop semantics.

12. **Offline analysis and quality gates**
   `src/learn.ts`, `src/evals.ts`, and `src/engine/self-check.ts` are the learning and validation sidecars. They mine past sessions, measure answer preservation, and run invariants that protect against stale, drifting, or unsafe behavior. The repository’s CI and test suite are part of the architecture because they gate the guarantees the runtime claims.

13. **Persistence and local-only boundary**
   The repo is designed to keep sensitive state local. The dashboard, proxy, and hub bind to `127.0.0.1`, and the persistent working data lives under `~/.knitbrain`. External network interaction is only through the model/provider endpoint when using the proxy path; otherwise, the system is local orchestration plus local storage.

14. **How to read the architecture diagram**
   A good diagram should show four main boxes: host agents/editors, knitbrain’s MCP/hook/proxy front doors, the engine/state store, and the local dashboard/hub. The most important arrows are: goal/context into the loop, tool output into optimization, optimized/recall-backed state into memory, and verify results back into loop control. The core design principle is that enforcement and accounting happen at the boundary, while state and optimization remain inside the local runtime.

Main entry points: [`src/index.ts`](https://github.com/pdgit12/knitbrain/blob/main/src/index.ts) (CLI), [`src/engine/closed-loop.ts`](https://github.com/pdgit12/knitbrain/blob/main/src/engine/closed-loop.ts) (Closed loop), [`src/engine/brain.ts`](https://github.com/pdgit12/knitbrain/blob/main/src/engine/brain.ts) (Brain), [`src/engine/memory.ts`](https://github.com/pdgit12/knitbrain/blob/main/src/engine/memory.ts) (Memory)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_entry["Entry points"]
  node_src_index_ts["CLI<br/>entrypoint<br/>[index.ts]"]
  node_src_server_ts["MCP server<br/>mcp entry<br/>[server.ts]"]
  node_src_setup_ts["Installer<br/>bootstrap<br/>[setup.ts]"]
  node_src_loop_ts["Goal loop<br/>runner<br/>[loop.ts]"]
  node_src_fan_ts["Fan-out<br/>runner<br/>[fan.ts]"]
  node_src_wrap_ts["Proxy wrapper<br/>proxy entry<br/>[wrap.ts]"]
  node_src_dashboard_ts["Dashboard<br/>ui entry<br/>[dashboard.ts]"]
end

subgraph group_integration["Integration layer"]
  node_src_mcp_host_ts["MCP tools<br/>tool server<br/>[host.ts]"]
  node_src_hooks_index_ts["Hooks<br/>policy layer<br/>[index.ts]"]
  node_src_proxy_server_ts["Wire proxy<br/>traffic proxy<br/>[server.ts]"]
  node_src_platforms_ts["Host adapt<br/>platform layer<br/>[platforms.ts]"]
end

subgraph group_engine["Core engine"]
  node_src_engine_closed_loop_ts["Closed loop<br/>control core<br/>[closed-loop.ts]"]
  node_src_engine_brain_ts["Brain<br/>orchestrator<br/>[brain.ts]"]
  node_src_engine_memory_ts[("Memory<br/>state store<br/>[memory.ts]")]
  node_src_engine_retrieval_ts["Retrieval<br/>recall<br/>[retrieval.ts]"]
  node_src_engine_receipt_ts["Receipts<br/>accounting<br/>[receipt.ts]"]
  node_src_engine_quota_ts["Quota<br/>accounting<br/>[quota.ts]"]
  node_src_engine_self_check_ts["Self-check<br/>safety gate<br/>[self-check.ts]"]
end

subgraph group_opt["Optimization"]
  node_src_optimizer_router_ts["Optimizer<br/>compression router<br/>[router.ts]"]
  node_src_ccr_store_ts[("Recall store<br/>content-addressed store<br/>[store.ts]")]
end

subgraph group_sync["Sync and analysis"]
  node_src_hub_server_ts["Hub<br/>sync server<br/>[server.ts]"]
  node_src_learn_ts["Learn<br/>analysis<br/>[learn.ts]"]
  node_src_evals_ts["Evals<br/>quality analysis<br/>[evals.ts]"]
end

node_src_index_ts -->|"starts"| node_src_server_ts
node_src_index_ts -->|"installs"| node_src_setup_ts
node_src_index_ts -->|"runs"| node_src_loop_ts
node_src_index_ts -->|"fans out"| node_src_fan_ts
node_src_index_ts -->|"wraps"| node_src_wrap_ts
node_src_index_ts -->|"opens"| node_src_dashboard_ts
node_src_server_ts -->|"serves"| node_src_mcp_host_ts
node_src_setup_ts -->|"adapts"| node_src_platforms_ts
node_src_hooks_index_ts -->|"detects"| node_src_platforms_ts
node_src_mcp_host_ts -->|"calls"| node_src_engine_brain_ts
node_src_hooks_index_ts -->|"enforces"| node_src_engine_closed_loop_ts
node_src_proxy_server_ts -->|"optimizes"| node_src_optimizer_router_ts
node_src_proxy_server_ts -->|"stores"| node_src_ccr_store_ts
node_src_engine_brain_ts -->|"persists"| node_src_engine_memory_ts
node_src_engine_brain_ts -->|"recalls"| node_src_engine_retrieval_ts
node_src_engine_closed_loop_ts -->|"records"| node_src_engine_receipt_ts
node_src_engine_closed_loop_ts -->|"limits"| node_src_engine_quota_ts
node_src_engine_closed_loop_ts -->|"verifies"| node_src_engine_self_check_ts
node_src_engine_retrieval_ts -->|"loads"| node_src_ccr_store_ts
node_src_optimizer_router_ts -->|"handles"| node_src_ccr_store_ts
node_src_hub_server_ts -->|"shares"| node_src_engine_memory_ts
node_src_learn_ts -->|"mines"| node_src_engine_memory_ts
node_src_evals_ts -->|"gates"| node_src_engine_self_check_ts

click node_src_index_ts "https://github.com/pdgit12/knitbrain/blob/main/src/index.ts"
click node_src_server_ts "https://github.com/pdgit12/knitbrain/blob/main/src/server.ts"
click node_src_setup_ts "https://github.com/pdgit12/knitbrain/blob/main/src/setup.ts"
click node_src_loop_ts "https://github.com/pdgit12/knitbrain/blob/main/src/loop.ts"
click node_src_fan_ts "https://github.com/pdgit12/knitbrain/blob/main/src/fan.ts"
click node_src_wrap_ts "https://github.com/pdgit12/knitbrain/blob/main/src/wrap.ts"
click node_src_dashboard_ts "https://github.com/pdgit12/knitbrain/blob/main/src/dashboard.ts"
click node_src_mcp_host_ts "https://github.com/pdgit12/knitbrain/blob/main/src/mcp/host.ts"
click node_src_hooks_index_ts "https://github.com/pdgit12/knitbrain/blob/main/src/hooks/index.ts"
click node_src_proxy_server_ts "https://github.com/pdgit12/knitbrain/blob/main/src/proxy/server.ts"
click node_src_platforms_ts "https://github.com/pdgit12/knitbrain/blob/main/src/platforms.ts"
click node_src_engine_closed_loop_ts "https://github.com/pdgit12/knitbrain/blob/main/src/engine/closed-loop.ts"
click node_src_engine_brain_ts "https://github.com/pdgit12/knitbrain/blob/main/src/engine/brain.ts"
click node_src_engine_memory_ts "https://github.com/pdgit12/knitbrain/blob/main/src/engine/memory.ts"
click node_src_engine_retrieval_ts "https://github.com/pdgit12/knitbrain/blob/main/src/engine/retrieval.ts"
click node_src_engine_receipt_ts "https://github.com/pdgit12/knitbrain/blob/main/src/engine/receipt.ts"
click node_src_engine_quota_ts "https://github.com/pdgit12/knitbrain/blob/main/src/engine/quota.ts"
click node_src_engine_self_check_ts "https://github.com/pdgit12/knitbrain/blob/main/src/engine/self-check.ts"
click node_src_optimizer_router_ts "https://github.com/pdgit12/knitbrain/blob/main/src/optimizer/router.ts"
click node_src_ccr_store_ts "https://github.com/pdgit12/knitbrain/blob/main/src/ccr/store.ts"
click node_src_hub_server_ts "https://github.com/pdgit12/knitbrain/blob/main/src/hub/server.ts"
click node_src_learn_ts "https://github.com/pdgit12/knitbrain/blob/main/src/learn.ts"
click node_src_evals_ts "https://github.com/pdgit12/knitbrain/blob/main/src/evals.ts"

classDef toneNeutral fill:#f8fafc,stroke:#334155,stroke-width:1.5px,color:#0f172a
classDef toneBlue fill:#dbeafe,stroke:#2563eb,stroke-width:1.5px,color:#172554
classDef toneAmber fill:#fef3c7,stroke:#d97706,stroke-width:1.5px,color:#78350f
classDef toneMint fill:#dcfce7,stroke:#16a34a,stroke-width:1.5px,color:#14532d
classDef toneRose fill:#ffe4e6,stroke:#e11d48,stroke-width:1.5px,color:#881337
classDef toneIndigo fill:#e0e7ff,stroke:#4f46e5,stroke-width:1.5px,color:#312e81
classDef toneTeal fill:#ccfbf1,stroke:#0f766e,stroke-width:1.5px,color:#134e4a
class node_src_index_ts,node_src_server_ts,node_src_setup_ts,node_src_loop_ts,node_src_fan_ts,node_src_wrap_ts,node_src_dashboard_ts toneBlue
class node_src_mcp_host_ts,node_src_hooks_index_ts,node_src_proxy_server_ts,node_src_platforms_ts toneAmber
class node_src_engine_closed_loop_ts,node_src_engine_brain_ts,node_src_engine_memory_ts,node_src_engine_retrieval_ts,node_src_engine_receipt_ts,node_src_engine_quota_ts,node_src_engine_self_check_ts toneMint
class node_src_optimizer_router_ts,node_src_ccr_store_ts toneRose
class node_src_hub_server_ts,node_src_learn_ts,node_src_evals_ts toneIndigo
```

## Components

### Entry points

CLI and operational modes exposed by the package

- [CLI](https://github.com/pdgit12/knitbrain/blob/main/src/index.ts): entrypoint · Top-level command dispatch for the package · `src/index.ts`
- [MCP server](https://github.com/pdgit12/knitbrain/blob/main/src/server.ts): mcp entry · Runs the stdio-facing server mode · `src/server.ts`
- [Installer](https://github.com/pdgit12/knitbrain/blob/main/src/setup.ts): bootstrap · Bootstrap and host integration setup · `src/setup.ts`
- [Goal loop](https://github.com/pdgit12/knitbrain/blob/main/src/loop.ts): runner · Headless loop execution mode · `src/loop.ts`
- [Fan-out](https://github.com/pdgit12/knitbrain/blob/main/src/fan.ts): runner · Parallel execution and branching mode · `src/fan.ts`
- [Proxy wrapper](https://github.com/pdgit12/knitbrain/blob/main/src/wrap.ts): proxy entry · Request-wrapping mode around a provider client · `src/wrap.ts`
- [Dashboard](https://github.com/pdgit12/knitbrain/blob/main/src/dashboard.ts): ui entry · Local observability and inspection surface · `src/dashboard.ts`

### Integration layer

MCP tools, hooks, proxying, and host adaptation

- [MCP tools](https://github.com/pdgit12/knitbrain/blob/main/src/mcp/host.ts): tool server · MCP-facing tool surface for agents and editors · `src/mcp/host.ts`
- [Hooks](https://github.com/pdgit12/knitbrain/blob/main/src/hooks/index.ts): policy layer · Host hook orchestration and enforcement boundary · `src/hooks/index.ts`
- [Wire proxy](https://github.com/pdgit12/knitbrain/blob/main/src/proxy/server.ts): traffic proxy · Intercepts and rewrites API-key workflow traffic · `src/proxy/server.ts`
- [Host adapt](https://github.com/pdgit12/knitbrain/blob/main/src/platforms.ts): platform layer · Detects host platforms and adapts config behavior · `src/platforms.ts`

### Core engine

Local goal loop, memory, accounting, and project state

- [Closed loop](https://github.com/pdgit12/knitbrain/blob/main/src/engine/closed-loop.ts): control core · Decides iteration, failure, and completion · `src/engine/closed-loop.ts`
- [Brain](https://github.com/pdgit12/knitbrain/blob/main/src/engine/brain.ts): orchestrator · Coordinates onboarding, state, skills, and workflows · `src/engine/brain.ts`
- [Memory](https://github.com/pdgit12/knitbrain/blob/main/src/engine/memory.ts): state store · Persistent local session and project memory · `src/engine/memory.ts`
- [Retrieval](https://github.com/pdgit12/knitbrain/blob/main/src/engine/retrieval.ts): recall · Fetches stored knowledge and prior context · `src/engine/retrieval.ts`
- [Receipts](https://github.com/pdgit12/knitbrain/blob/main/src/engine/receipt.ts): accounting · Records tool actions and loop evidence · `src/engine/receipt.ts`
- [Quota](https://github.com/pdgit12/knitbrain/blob/main/src/engine/quota.ts): accounting · Tracks usage limits and budget enforcement · `src/engine/quota.ts`
- [Self-check](https://github.com/pdgit12/knitbrain/blob/main/src/engine/self-check.ts): safety gate · Validates invariants and output quality · `src/engine/self-check.ts`

### Optimization

Compression and content-addressed recall

- [Optimizer](https://github.com/pdgit12/knitbrain/blob/main/src/optimizer/router.ts): compression router · Routes text, code, JSON, and structured compression · `src/optimizer/router.ts`
- [Recall store](https://github.com/pdgit12/knitbrain/blob/main/src/ccr/store.ts): content-addressed store · Stores exact bytes behind compressed handles · `src/ccr/store.ts`

### Sync and analysis

Optional hub plus offline learning and checks

- [Hub](https://github.com/pdgit12/knitbrain/blob/main/src/hub/server.ts): sync server · Optional local/team coordination endpoint · `src/hub/server.ts`
- [Learn](https://github.com/pdgit12/knitbrain/blob/main/src/learn.ts): analysis · Mines past sessions for reusable knowledge · `src/learn.ts`
- [Evals](https://github.com/pdgit12/knitbrain/blob/main/src/evals.ts): quality analysis · Measures preservation and behavior quality · `src/evals.ts`

## Connections

- CLI → MCP server: starts · CLI can launch the MCP server mode
- CLI → Installer: installs · CLI exposes bootstrap and host setup
- CLI → Goal loop: runs · CLI can run the headless goal loop
- CLI → Fan-out: fans out · CLI can launch parallel execution mode
- CLI → Proxy wrapper: wraps · CLI can run as a proxy wrapper
- CLI → Dashboard: opens · CLI can start local observability UI
- MCP server → MCP tools: serves · Server mode exposes MCP tools
- Installer → Host adapt: adapts · Bootstrap resolves host-specific behavior
- Hooks → Host adapt: detects · Hooks depend on host/platform detection
- MCP tools → Brain: calls · Tool requests delegate into the engine
- Hooks → Closed loop: enforces · Hooks inject and protect loop control
- Wire proxy → Optimizer: optimizes · Proxy path rewrites traffic through optimization
- Wire proxy → Recall store: stores · Large outputs are preserved for exact recall
- Brain → Memory: persists · Brain reads and updates durable memory
- Brain → Retrieval: recalls · Brain retrieves prior knowledge and context
- Closed loop → Receipts: records · Loop execution emits receipts and evidence
- Closed loop → Quota: limits · Loop is constrained by budget accounting
- Closed loop → Self-check: verifies · Loop validates outputs before advancing
- Retrieval → Recall store: loads · Recall can rehydrate compressed artifacts
- Optimizer → Recall store: handles · Compression emits handles backed by stored bytes
- Hub → Memory: shares · Hub sync shares findings without replacing local state
- Learn → Memory: mines · Offline learning uses session history as input
- Evals → Self-check: gates · Evaluation feeds quality and safety checks
