Asoba Asoba Open Source

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

NEHANDA TURN LIFECYCLE — runUserTurn(db, rt, userText, io) In-Process Deterministic Turn Execution · Jev-Mem Control Plane · 11-Phase Governance 1. Hook: UserPromptSubmit Pre-submission interception · Can block or reshape prompt 2. Append to transcript_entries Immutable SQLite audit record · User payload serialized 3. Jev-Mem Hot Path (Laya System-1) Ingest observation → Laya state extraction → Evidence retrieval → Pinned context 4. Build Phase Prompt + Tool Mask Inject [GROUNDED FACTS] · Filter tools by active SDLC phase 5. Stream Inference Completion Stream tokens · Live reasoning spinner · Native tools or [TOOL_CALL] rescue Tool Invocations Emitted Execute tool → Record provenance → Loop Plain Text Completed Evaluate SDLC human gate or return turn TOOL LOOP lib/orchestrate.mjs · runUserTurn() · executeToolUses()

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:

4. Phase Tool Masking & Grounded Facts

The engine constructs the API system prompt dynamically:

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:

  1. PreToolUse hook fires.
  2. The permission gate evaluates policies (allow, deny, or ask).
  3. If blocked by security rules, the interactive BlockConfirmMenu prompts the operator ([A] Session Approve, [S] Run in OS Sandbox, [C] Cancel).
  4. The tool executes, and elapsed runtime is measured.
  5. In SDLC testing phases, test runner outputs are parsed and classified for execution provenance (test_executions table).
  6. Tool outputs are appended to transcript_entries and 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:


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