Architecture
Nehanda CLI is a layered, single-process engine with six distinct architectural layers. Every component runs in-process within Node.js (v22+) — eliminating external daemon processes, relay proxies, or container runtimes.

Layer Overview
Layer 1: REPL / Ink TUI
The user interface layer is built with Ink (React in the terminal).
- Command Parser: Interprets interactive slash commands (
/model,/key,/config,/mcp,/help,/clear,/exit). - Interactive Safety & BlockConfirmMenu: When an execution checker detects risky operations (opening local network sockets, writing outside project root, inspecting hardware buses), execution is paused. The user is prompted with an interactive menu:
[A]Approve for Session: Caches approval in-memory (cacheSessionApproval) so the command is not prompted again.[S]Run in OS Sandbox: Executes the action within an ephemeral, credential-filtered copy confined via OS primitives (macOS Seatbelt or Linux Bubblewrap).[C]Cancel: Safely aborts execution.
- Process Legibility & Bounded Output:
- Displays live spinner verbs (
Analyzing,Thinking,Reading,Running) and real-time reasoning token counters (⠋ Thinking (42 tokens)...). - Summarizes tool invocations (
⚙ Read(package.json),⚙ Bash(git status)). - Automatically formats JSON array payloads from telemetry and tool results into box-drawing tables via
cli-table3, capped at 10 rows with overflow notice.
- Displays live spinner verbs (
Layer 2: Engine Core
The central orchestration engine runs entirely inside the host Node.js process:
- Turn Loop (
runUserTurn): Executes the standard deterministic cycle: ingest user prompt $\rightarrow$ append to transcript $\rightarrow$ invoke Jev-Mem hot path $\rightarrow$ resolve model $\rightarrow$ stream model completion $\rightarrow$ execute tools $\rightarrow$ record state. - 11-Phase SDLC State Machine: Governs transitions through an 11-phase sequence: \(\text{idle} \rightarrow \text{explore} \rightarrow \text{diagnose} \rightarrow \text{create\_issue} \rightarrow \text{create\_tests} \rightarrow \text{planning} \rightarrow \text{implement} \rightarrow \text{verify} \rightarrow \text{safety} \rightarrow \text{confirm\_fix} \rightarrow \text{done}\) Model prose cannot advance phases; every gate requires verifiable execution evidence.
- Bounded Exploration: Scans
docs/MAP.mdand repository documentation first, enforces a strict 20-request ceiling, terminates upon detected stagnation, and falls back to a.ona/mapcache if MAP documentation is absent. - Laya System-1 Hot Path: Pre-primes the 322M-parameter Laya neural decision model upon launch (
method: 'load'), classifies intent, and extracts evidence graph nodes to cut System-2 context prefill by 70–85%. [TOOL_CALL]Rescue Engine: Delimiter-based tool calling bypasses vLLM stop-token stripping for strict, non-hallucinated tool execution on OpenAI-compatible proxies.
Layer 3: Tool Layer
- Built-in Tools (21): Core file system (
Read,Write,Edit), terminal execution (Bash), discovery (Glob,Grep), notebooks, worktrees, and web lookup. - Phase-Aware Tool Masks: Restricts tool access strictly by phase (e.g.,
exploreis read-only;planninghas no tools;create_testsallows mutations only intests/**;implementallows production edits). - Mandatory Safety Checkers (3):
lib/scripts/js-safety-checker.cjslib/scripts/shell-safety-checker.shlib/scripts/python-safety-checker.py
- Branch Coverage Gate: Integrates
branch-coverage-collector.mjsto require $\ge 70\%$ branch coverage across modified production code before authorizing completion. - MCP Client: Connects to Model Context Protocol servers over stdio JSON-RPC, namespacing tools under
mcp__<server>__<tool>.
Layer 4: ODSE Middleware
Intercepts MCP results from energy assets and standardizes them to the ODS-E specification:
- Dual-Pass Brand Detection: First inspects the MCP server identifier (e.g.
energy-huawei$\rightarrow$ Huawei), then falls back to JSON schema field fingerprinting across 20+ solar inverter, battery, and SCADA schemas. - Normalization Engine: Executes
lib/scripts/odse-transform.pyto produce uniform telemetry arrays formatted as terminal tables or NDJSON.
Layer 5: Provider Layer
Unified interface across frontier cloud providers and local open-source inference:
- Goose-Style
/modelWizard: Discovers available models dynamically from provider catalogs (GET /modelsor Ollama/api/tags). - Credential Isolation: Strict separation of provider credentials prevents API keys or custom hosts from bleeding between sessions. Secrets are masked in the UI and redacted in transcript records.
- Ollama Capability Probe: Automatically inspects Ollama model capabilities, supports native tool calling or rescue delimiters, and toggles
think: falsewhere supported.
Layer 6: Persistence Layer (Schema v4)
Single-file, zero-daemon SQLite storage at ~/.config/nehanda/ona-session.db:
- WAL Mode & FTS5: High-concurrency Write-Ahead Logging and full-text search across all memories.
- Runtime Evidence Tables (Schema v4):
test_executions: Durable records of command identity, input hashes, timing, and failure/pass classification.red_evidence: Provenance records of genuine test runner RED failures.safety_evidence: Reports from mandatory JavaScript, Shell, and Python safety checkers.
- Pinned Context (
pinned_context): Protects mission-critical invariants (ODSE schemas, asset limits, simulation bounds) from being summarized away during context compaction. - Jev-Mem Multi-Relational Plane: Tracks semantic, temporal, causal, and entity edges across observations.
Cross-Cutting Concerns
| Concern | Description | Reference |
|---|---|---|
| OS-Primitives Sandbox | Disposable project snapshot (256 MiB / 10k entries); Seatbelt on macOS; Bubblewrap on Linux; network egress allowlist proxy | Permissions & Sandbox |
| Epistemic Filter | Redacts implementation blocks from assistant messages during test generation and verification | SDLC Workflow |
| Database Migrations | Automatic zero-downtime migration through schema versions v1 $\rightarrow$ v2 $\rightarrow$ v3 $\rightarrow$ v4 | Database |
| Hook Plane | Event-driven triggers (PreToolUse, PostToolUse, UserPromptSubmit, PhaseTransition) |
Hooks |