How pdgit12/knitbrain works
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: index.ts CLI · closed-loop.ts Closed loop · brain.ts Brain · memory.ts Memory
Components 23
Entry points
CLI and operational modes exposed by the package
- CLI · Top-level command dispatch for the package
src/index.ts - MCP server · Runs the stdio-facing server mode
src/server.ts - Installer · Bootstrap and host integration setup
src/setup.ts - Goal loop · Headless loop execution mode
src/loop.ts - Fan-out · Parallel execution and branching mode
src/fan.ts - Proxy wrapper · Request-wrapping mode around a provider client
src/wrap.ts - Dashboard · Local observability and inspection surface
src/dashboard.ts
Integration layer
MCP tools, hooks, proxying, and host adaptation
- MCP tools · MCP-facing tool surface for agents and editors
src/mcp/host.ts - Hooks · Host hook orchestration and enforcement boundary
src/hooks/index.ts - Wire proxy · Intercepts and rewrites API-key workflow traffic
src/proxy/server.ts - Host adapt · Detects host platforms and adapts config behavior
src/platforms.ts
Core engine
Local goal loop, memory, accounting, and project state
- Closed loop · Decides iteration, failure, and completion
src/engine/closed-loop.ts - Brain · Coordinates onboarding, state, skills, and workflows
src/engine/brain.ts - Memory · Persistent local session and project memory
src/engine/memory.ts - Retrieval · Fetches stored knowledge and prior context
src/engine/retrieval.ts - Receipts · Records tool actions and loop evidence
src/engine/receipt.ts - Quota · Tracks usage limits and budget enforcement
src/engine/quota.ts - Self-check · Validates invariants and output quality
src/engine/self-check.ts
Optimization
Compression and content-addressed recall
- Optimizer · Routes text, code, JSON, and structured compression
src/optimizer/router.ts - Recall store · Stores exact bytes behind compressed handles
src/ccr/store.ts
Connections 23
- 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