Chakshu Architecture Specification¶
This document details the architectural design, component interactions, data pipelines, and security mechanisms of Chakshu.
High-Level System Architecture¶
Chakshu is designed as a local-first, zero-proxy, single-binary monitoring and observability system for AI coding agents.
flowchart TD
subgraph AgentEnvironment["Agent Environment (Local Host)"]
Codex["OpenAI Codex (~/.codex)"]
Claude["Claude Code (~/.claude)"]
Gemini["Gemini CLI / Antigravity (~/.gemini)"]
Cursor["Cursor IDE (~/.cursor)"]
end
subgraph ChakshuDaemon["Chakshu Daemon (Background Process)"]
Watcher["Watcher & Guardrails (internal/watcher)"]
Adapters["Agent Adapters (internal/adapter)"]
AuditEngine["Audit & Chaining Engine (internal/audit)"]
PolicyEngine["Policy Engine (internal/policy)"]
IncidentMgr["Incident Manager (internal/incident)"]
Store["SQLite + FTS5 Engine (modernc.org/sqlite, ~/.chakshu/chakshu.db)"]
end
subgraph UserInterfaces["User Interfaces"]
CLI["Terminal CLI (cmd/chakshu)"]
WebUI["Embedded Web UI (internal/ui - Next.js)"]
MCPMem["MCP Memory Server (internal/mcpserver)"]
Export["JSON / CSV Exporter (internal/exporter)"]
end
Codex -->|Append JSONL| Watcher
Claude -->|Append JSONL| Watcher
Gemini -->|Append JSONL| Watcher
Cursor -->|Append JSONL| Watcher
Watcher --> Adapters
Adapters -->|ToolCall records| Store
Adapters -->|ToolCall records| AuditEngine
AuditEngine -->|SecurityEvent records| Store
AuditEngine --> PolicyEngine
PolicyEngine -->|Violations| IncidentMgr
IncidentMgr --> Store
Store --> CLI
Store --> WebUI
Store --> MCPMem
Store --> Export
Core Components¶
1. Watcher & Guardrails (internal/watcher)¶
- Continuously polls known agent transcript directories for file changes.
- Tracks exact byte offsets per file in the SQLite
offsetstable. - Evaluates incoming tool calls against
internal/policyand chains violations intosecurity_events. - Runs a sliding-window retry-loop and token-burn guardrail (
guardrails.go) to warn on runaway loops and token spikes. - Tolerates log rotations, file truncation, and daemon restarts with zero event duplication.
2. Adapters (internal/adapter)¶
- Codex Adapter: Parses Codex session rollout logs, extracts bash execution, skill invocations, and user prompt turns.
- Claude Code Adapter: Extracts assistant tool use blocks, tool results, API token usage metadata (
input_tokens,output_tokens), and chat conversations. - Gemini CLI / Antigravity Adapter: Parses multi-agent JSONL transcripts, steps, subagent delegations, and model execution metrics.
- Cursor IDE Adapter (
cursor.go): Parses Cursor agent/composer JSONL transcripts under~/.cursor/{projects,chats,sessions}including subagent transcripts.
3. Store (internal/store)¶
- Implemented with pure Go SQLite (
modernc.org/sqlite), eliminating CGO dependencies and enabling seamless cross-compilation. - Stores normalized
ToolCall,tool_calls_fts(FTS5full-text search),ApprovalEvent,SecurityEvent,Incident,MCPServerRecord,SkillRecord,PluginRecord,session_memories,memory_edges,file_snapshots,skill_versions,evaluation_*tables, andoffsets. - Automatically executes migrations on startup to ensure backwards and forwards schema compatibility.
4. Security & Audit Engine (internal/audit)¶
- Analyzes every tool call in real time against high-risk operational patterns:
- Destructive filesystem operations (
rm -rf, disk wipes, force git operations). - Piped remote shell execution (
curl | bash,wget | sh). - Sensitive credential leaks (
.envfile exposure, private keys, API secrets). - Path traversal and unauthorized filesystem escape.
- Chaining Engine (
chainer.go): Identifies multi-step attack vectors (e.g., reading a credential file followed immediately by an outbound network call).
5. Policy Engine & Incident Management (internal/policy, internal/incident)¶
- Evaluates actions against defined security policies.
- Automatically flags incidents and computes risk severity levels (INFO, LOW, MEDIUM, HIGH, CRITICAL).
- Provides agent process discovery (
ps) extracting PID, command line, real-time RSS RAM (MB), VSZ, and %MEM, along with process lifecycle controls (kill,terminate,pause,resume) that strictly validate process identity before executing OS signals.
6. Embedded Web UI (internal/ui & web/)¶
- Modern Next.js 16 (React 19 + TypeScript) dashboard statically compiled and embedded into the Go binary using
embed.FS. - Communicates with local REST endpoints (
/api/calls,/api/search,/api/stats,/api/sessions,/api/session,/api/sessions/{sessionId}/approvals,/api/approvals,/api/approvals/{approvalId},/api/analytics/approvals*,/api/audit,/api/security/events,/api/mcp,/api/skills,/api/plugins,/api/plugins/detail,/api/processes,/api/kill,/api/memory,/api/memory/decisions*,/api/snapshots,/api/rollback,/api/skill-intel/*,/api/benchmarks/*,/api/evaluation/*,/api/meta,/api/refresh). - Client-side hash routing (
#/sessions/:id/:subtab,#/calls,#/memory,#/skills/:tab,#/approvals,#/audit,#/plugins) ensuring robust page refreshes on static servers, plusCmd+K/Ctrl+KGlobal Search (GlobalSearchModal). - Features deep-dive session subtabs: Execution Trace, Performance & Tokens, Touched Files & Safety (with one-click snapshot rollback), Security & Secrets, Context & Memory Analytics, and Human Approvals.
- Automatic polling suspension when browser tab is inactive (Pause-on-Blur).
7. Plugin Engine & Discovery Catalog (internal/plugin)¶
- Passively discovers installed plugins and extensions across Antigravity, Claude Code, Gemini CLI, Cursor, and workspace environments.
- Parses plugin manifests (
plugin.json,gemini-extension.json,.claude-plugin/plugin.json, and declaredplugins.json). - Automatically catalogs bundled components:
- Skills:
skills/*/SKILL.md - Rules:
rules/*.md - MCP Servers:
mcp_config.json - Lifecycle Hooks:
hooks.json - Executes static supply-chain security analysis (detecting hazardous shell commands, unredacted API secrets, prompt injections) and computes deterministic cryptographic SHA-256 fingerprints.
8. Agent Memory Subsystem (internal/memory)¶
- Implements comprehensive 3-tier memory observability:
- Working Context Window Memory: Tracks turn-by-turn context expansion against model context window limits (Claude 200k, Gemini 1M–2M, GPT-4o 128k), calculating saturation percentage (<50% optimal, 50–75% elevated, >75% critical context fatigue), moving-average turns to exhaustion, and context window compaction/truncation events.
- Memory Bloat Hotspot Detection: Identifies anomalous tool invocations that injected massive token outputs into working memory (>8k tokens or >3x average).
- Context Composition Breakdown: Analyzes the distribution between Tool Outputs, Persistent Rules, User Prompts, and Model Outputs.
- Persistent Knowledge Memory Bank: Passively discovers workspace and user-level instruction artifacts (
AGENTS.md,CLAUDE.md,.cursorrules,.cursor/rules/*.mdc,.gemini/rules/*.md,copilot-instructions.md), categorizing rules and computing exact token weights. - Token Tax Calculator: Evaluates continuous prompt overhead and dollar cost ($/100 turns) incurred by injecting static rules into prompts.
- Memory Security & Conflict Auditor: Audits persistent memory files for prompt injection directives, command execution risks, credential leaks, and cross-memory configuration conflicts.
9. Human Approval & Intervention Tracking Engine (internal/approval)¶
- Passively observes human-in-the-loop permission prompts, decisions, and post-decision outcomes from agent transcripts without intercepting or blocking execution.
- Extensible Agent Extractors (
extractor.go,codex.go,claudecode.go,gemini.go): Separate parsers for Codex, Claude Code, and Gemini CLI / Antigravity registered throughApprovalExtractor. - Correlation Engine (
correlator.go): Correlates request, decision, execution, and session-abort signals using exactRequestIDandToolCallIDmatching; handles simultaneous requests, repeated requests, out-of-order ingestion, missing decisions, and incremental watcher appends while preventing duplicate ingestion and ambiguous guessing. - Independent Risk Classification (
risk.go): Evaluates inherent risk (INFO–CRITICAL) across Terminal/Shell, Filesystem, Git, MCP/Tools, Network, Infrastructure/Database, and Agent Permissions completely independently of the human decision. - Pre-Persistence Redaction (
redact.go): Redacts API keys, tokens, credentials, URL passwords, and sensitive JSON fields before writing to SQLite (approval_events) or serving APIs. - Cross-Session Analytics (
analytics.go): Computes approval/rejection rates, average & P95 latency, agent intelligence, tool & MCP hotspots, repeated requests, and security intelligence (high-risk approvals, escalations, and unusual patterns).
10. Skill Intelligence & Benchmarking Engine (internal/evaluation, internal/skill)¶
- Content-Addressed Skill Versioning: Tracks revisions (
skill_versions) via composite SHA-256 fingerprints acrossSKILL.mdand companion files, preserving parent revision links and change summaries. - Benchmark Studio (
benchmark/): Manages repeatable suites and multi-rule scenarios, built-in templates, and dependency-free JSON/YAML import-export. - Windowed Execution Attribution (
attribution.go): Scopes captured session events to skill-specific turn windows with explicit confidence scores and baseline pairing without re-executing commands. - Deterministic & Human Evaluation (
rules/,human/,scorer.go): Executeschakshu-eval-v1.0normalized scoring (NOT_APPLICABLEexclusion,UNOBSERVABLEtelemetry separation, evidence deduplication, required-rule gating, and independentSecurityVerdictreporting). - Paired Comparisons, Insights & Optional Judge (
comparison.go,insights.go,judge/): Compares revisions or baselines with compatibility and trial-count guards (INSUFFICIENT_TRIALSwhen< 3trials), emits evidence-linked recommendations, and optionally invokes a consent-gated local agent CLI (agy,claude,codex,gemini) or HTTP LLM judge (net/http). Supports headless CI regression gating viachakshu eval --ci. See Skill Intelligence Docs.
11. Pre-Execution File Snapshots & Rollback (internal/snapshot)¶
- Captures content-addressed pre-edit file backups via
chakshu snapshot-hook(readingPreToolUseJSON on stdin) and stores metadata infile_snapshots. - Supports listing and restoring captured snapshots via
chakshu rollback [--list] [<call-id>]or one-click rollback in the SessionFilesWeb UI (/api/snapshots,/api/rollback).
12. Local MCP Memory Server (internal/mcpserver)¶
- Zero-dependency stdio JSON-RPC 2.0 server (
chakshu mcp-memory) exposing Chakshu's SQLite store to Claude Code, Cursor, Codex, and Gemini. - Exposes four tools:
search_decisions,get_file_context,search_sessions, andrecord_constraint.
Data Flow Sequence¶
sequenceDiagram
autonumber
participant Agent as AI Coding Agent
participant File as Agent Transcript (.jsonl)
participant Watcher as Chakshu Watcher
participant Adapter as Agent Adapter
participant Audit as Security Audit Engine
participant Store as SQLite Store
participant UI as Chakshu Web / CLI
Agent->>File: Write tool call / completion
Watcher->>File: Poll & read new bytes from saved offset
Watcher->>Adapter: Parse transcript line
Adapter-->>Watcher: Return normalized ToolCall
Watcher->>Audit: Audit ToolCall for security anomalies
Audit-->>Watcher: Return SecurityEvent / Incident findings
Watcher->>Store: Commit ToolCalls, SecurityEvents & new offset (Tx)
UI->>Store: Query calls, stats, or security events
Store-->>UI: Return formatted results
Security Boundaries & Guarantees¶
- Zero External Telemetry: All database transactions and logs are confined to
~/.chakshu/. - Read-Only Observation: The watcher opens agent transcript files in read-only mode (
os.O_RDONLY). - Safe Redaction: Secrets detected in tool inputs or outputs are redacted with semantic tokens (e.g.
[SECRET:AUTH_TOKEN]) before display. - Process Validation: Agent killswitch mechanisms inspect process executable names and command lines to prevent terminating non-agent processes.