Engine & Turn Loop
The engine is the computational core of Nehanda CLI. It executes completely in-process within a single Node.js runtime (v22+) — eliminating daemon architectures, container dependencies, or external proxies. Every interaction flows through runUserTurn, the central orchestrator in lib/orchestrate.mjs.
Turn Lifecycle
Detailed Step Walkthrough
1. Pre-Submission Hook (UserPromptSubmit)
Fires before any token processing occurs. An external security plugin or local policy hook can inspect userText and cancel execution early by returning { ok: false, message: "..." }.
2. Transcript Serialization
The prompt is durably written to transcript_entries in the local SQLite database. Even if the process terminates or network connectivity drops mid-inference, the exact prompt sequence is preserved.
3. Jev-Mem Hot Path & Laya System-1 Control Plane
Nehanda uses a two-tier neural architecture:
- System-1 (Laya): Primed into memory on startup (
method: 'load'), Laya is a 322M non-autoregressive classifier. It ingests the latest transcript observations, updates memory graph relation edges (semantic, temporal, causal, entity), and sets the canonical state inlaya_jev_state. - Adaptive Evidence Retrieval: Queries full-text search (
memories_fts) and recency graphs to extract only pertinent memory anchors. - Pinned Invariants: Domain invariants (such as ODSE register maps, physical asset specs, and simulation bounds) are fetched from
pinned_contextand prepended verbatim to every System-2 prompt. - Prefill Reduction: Cuts System-2 context size by 70–85% compared to raw transcript histories.
4. Phase Tool Masking & Grounded Facts
The engine constructs the API system prompt dynamically:
- Injects a
[GROUNDED FACTS]block containing the verified date, operating system, current working directory, and shell. - Strictly filters tool schemas based on the active SDLC phase. A model in the
explorephase only receivesRead,Glob, andGrepschemas.
5. Streaming Inference & Reasoning Counters
Streams server-sent events (SSE) from the inference backend. If the model emits reasoning content (e.g. delta.reasoning_content), the TUI spinner updates live with incremental token counts (⠋ Thinking (N tokens)...).
6. Tool Execution Pipeline
When tool use blocks are detected:
PreToolUsehook fires.- The permission gate evaluates policies (
allow,deny, orask). - If blocked by security rules, the interactive
BlockConfirmMenuprompts the operator ([A]Session Approve,[S]Run in OS Sandbox,[C]Cancel). - The tool executes, and elapsed runtime is measured.
- In SDLC testing phases, test runner outputs are parsed and classified for execution provenance (
test_executionstable). - Tool outputs are appended to
transcript_entriesand streamed back into the conversation turn loop.
Governed 11-Phase SDLC Loop
When SDLC governance is active, the engine executes a phase advancement loop across the 11 states:
while (['explore', 'diagnose', 'create_issue', 'create_tests', 'planning', 'implement', 'verify', 'safety', 'confirm_fix'].includes(phase)) {
const text = await runPhase(db, rt, io, hookRt, ...tools, phase)
if (text === null) return // model error / aborted
let advanced = false
if (phase === 'explore') advanced = await exploreGate(db, rt, io)
else if (phase === 'diagnose') advanced = await diagnoseGate(db, rt, io)
else if (phase === 'create_issue') advanced = await issueGate(db, rt, io)
else if (phase === 'create_tests') advanced = await redTestGate(db, rt, io)
else if (phase === 'planning') advanced = await planGate(db, rt, io)
else if (phase === 'implement') advanced = await implementGate(db, rt, io)
else if (phase === 'verify') advanced = await greenVerifyGate(db, rt, io)
else if (phase === 'safety') advanced = await safetyGate(db, rt, io)
else if (phase === 'confirm_fix') advanced = await confirmFixGate(db, rt, io)
if (!advanced) break
phase = getPhase(db, rt.conversationId)
}
Bounded Exploration Safeguards
To prevent recursive agent loops and token waste during explore:
- 20-Request Budget Ceiling: A hard limit of 20 productive tool requests is enforced during exploration. The 21st request is blocked, forcing a mandatory transition to
diagnose. - Stagnation Detection: Repeated file reads without new evidence extraction or zero-hit queries trigger an early exit.
.ona/mapFallback: Ifdocs/MAP.mdis absent, the engine computes a lightweight.ona/mapcache to guide exploration.
Tool Availability Matrix by Phase
| Phase | Read, Glob, Grep | Write, Edit | Bash | Web Tools | Rationale |
|---|---|---|---|---|---|
idle |
Allowed | Ask / Gated | Refused if mutating | Allowed | Open inquiry |
explore |
Allowed | Blocked | Blocked | Allowed | Strict discovery |
diagnose |
Allowed | Blocked | Blocked | Allowed | Evidence synthesis |
create_issue |
Allowed | .issues/ only |
Blocked | Allowed | Register task artifact |
create_tests |
Allowed | tests/** only |
Allowed (Test runner) | Allowed | TDD RED regression |
planning |
Blocked | Blocked | Blocked | Blocked | Plan Triad text only |
implement |
Allowed | Allowed | Allowed | Allowed | Approved code changes |
verify |
Allowed | Blocked | Allowed (Test runner) | Allowed | TDD GREEN verification |
safety |
Allowed | Blocked | Allowed (Checkers) | Allowed | Static checkers + coverage |
confirm_fix |
Allowed | Blocked | Blocked | Allowed | Human review |
done |
Allowed | Blocked | Allowed (Git commit) | Allowed | Final commit & reset |