Dev.to Security πŸ” Cybersecurity πŸ‘ 2 πŸ“– 13 min read

MomongaCode: An Open-Source Terminal Coding Agent Built Around Z3, TLA+, and an OS Sandbox

Most terminal coding agents treat safety as a prompt suggestion: tell the model not to touch ~/.ssh, hope a regex rule catches dangerous flags, and trust the model when it says the tests passed. MomongaCode (momonga, MI

MomongaCode: An Open-Source Terminal Coding Agent Built Around Z3, TLA+, and an OS Sandbox

MomongaCode demo

Most terminal coding agents treat safety as a prompt suggestion: tell the model not to touch ~/.ssh, hope a regex rule catches dangerous flags, and trust the model when it says the tests passed.

MomongaCode (momonga, MIT License) takes a different approach. It is an open-source coding agent for the terminal built around verifiable boundariesβ€”enforced by the operating system, proven with formal methods, and inspectable live inside your session.

In this article, we'll walk through how MomongaCode works under the hood, with architecture and protocol diagrams covering:

  1. Its daemonized process & capability-isolated trust architecture
  2. Built-in Z3 SMT policy proofs & 44 TLA+ specifications (284M+ TLC states)
  3. The OS sandbox (Seatbelt, bubblewrap, Windows MXC) & SNI-verifying egress proxy
  4. Tool-call permissions, VIGIL / SkillGuard, and offline ONNX guard models
  5. Taint-tracked, HMAC-sealed memory & PoEM execution ledgers
  6. Verifiable completion gates (where the runtime, not the model, proves tests pass)
  7. Three-tier prompt caching, token-efficiency engineering, and daily TUI ergonomics

Try It in 30 Seconds (No API Key Required)

You can install MomongaCode with one command. Both installers fetch SHA256SUMS and SHA256SUMS.sig from GitHub Releases and verify the binary against an embedded Ed25519 public key via ssh-keygen before installing:

macOS and Linux:

curl -fsSL https://momongacode.com/install.sh | bash

Windows (PowerShell):

irm https://momongacode.com/install.ps1 | iex

Even without configuring an API key or local model server, you can launch momonga in any folder and test two core verification features immediately inside the terminal UI:

momonga

Inside the running session, run:

/policy verify --file .claude/settings.json
/policy verify --file opencode.jsonc --format opencode-json
/sandbox check

/policy verify --file runs Z3 in-process to verify MomongaCode, Claude Code (settings.json), or OpenCode (opencode.json / opencode.jsonc) permission files offline. /sandbox check executes live OS sandbox and egress-proxy probes in a disposable temporary workspace without touching ~/.momonga or your real credentials.

1. Process & Trust Architecture

The momonga binary is a thin client (interactive terminal UI, -p headless runner for scripts/CI, or momonga acp editor server). Execution, policy enforcement, persistence, and model traffic live in background daemon processes managed by a supervisor.

flowchart TB
    subgraph Clients["Thin Clients"]
        TUI["momonga (Interactive TUI)"]
        Headless["momonga -p (Scripts and CI)"]
        ACP["momonga acp (Editor Integration)"]
    end

    subgraph Daemon["Background Daemon Processes"]
        Sup["Supervisor (Zero-Interruption Handover)"]
        RT["Runtime (Sessions, Policy, Tools, Sandbox)"]
        GW["Gateway (Model Adapters, Retries, Caching)"]
        Store["State Store (~/.momonga/state)"]
    end

    subgraph Child["Spawned Child Processes"]
        Cmd["Tool Commands, MCP Stdio, Hooks, Terminal Pane"]
    end

    TUI -->|"128-bit person-capability"| RT
    Headless -->|"128-bit person-capability"| RT
    ACP -->|"128-bit person-capability"| RT

    Sup -->|"Manages generations without cutting work"| RT
    Sup -->|"256-bit MOMONGA_CREDENTIAL_CAPABILITY"| GW
    RT <-->|"Model I/O"| GW
    RT <-->|"HMAC Ledgers and Sealed Memories"| Store

    RT -->|"Spawns inside OS sandbox"| Cmd
    Cmd -.->|"Blocked from ~/.momonga and person-capability"| Store

Two capability boundaries stand out here:

  • 128-bit person-capability: User-authorized daemon endpoints (approvals, rules, trust, memories, /terminal connections) require a 128-bit random capability stored in an owner-only file under ~/.momonga and verified in constant time. Spawned child processes never inherit it and are sandboxed away from MomongaCode's home directory, so process lineage checks are not relied on.
  • 256-bit MOMONGA_CREDENTIAL_CAPABILITY: On every gateway launch, the supervisor generates a fresh 256-bit capability so only the active gateway can fetch model API keys declared in settings, and every returned secret is automatically registered for output redaction.
  • Zero-interruption daemon handover: When MomongaCode updates, a new daemon starts alongside the retiring one. Existing runs and open /terminal panes keep running and hand over at a quiet point without aborting active work.

2. Built-In Z3 SMT Verification & 44 TLA+ Specifications

MomongaCode compiles Z3 to WebAssembly directly inside the binary and backs its core protocols with 44 TLA+ specifications checked with TLC in the test suite (579 configurationsβ€”196 check rows and 383 evidence rowsβ€”covering 284,320,150 distinct states).

flowchart LR
    subgraph Inputs["Policy & Contract Inputs"]
        P1[".momonga / .claude settings.json"]
        P2["opencode.json / opencode.jsonc"]
        P3["SKILL.md policy frontmatter & tracePolicies"]
    end

    Z3["In-Process Z3 WASM Solver (/policy verify)"]

    subgraph Proved["8 Checked Properties"]
        C1["deny-precedence"]
        C2["secret-reach"]
        C3["rule-consistency & bash-admission"]
        C4["superseded-forms & mandate-holds"]
        C5["vigil-contracts & skill-guard-reach"]
    end

    Replay["Counterexample Replay vs. TypeScript decide()"]
    Outside["Explicit 'Outside the proof:' List"]

    Inputs --> Z3
    Z3 --> Proved
    Z3 -->|"On refutation"| Replay
    Z3 -->|"Unmodelled tools or patterns"| Outside

What /policy verify checks

When you run /policy verify inside the TUI (or /policy verify --file <path> for external configs), Z3 proves eight properties across modelled paths, commands, MCP tools, and skill contracts:

Property What it proves
deny-precedence No allow rule overrides a deny rule on any modelled path, command, or MCP tool.
secret-reach No allow rule opens ~/.ssh, ~/.aws, ~/.gnupg, ~/.azure, ~/.kube, ~/.config/gcloud, ~/.config/gh, ~/.docker/config.json, ~/.netrc, ~/.npmrc, ~/.pypirc, ~/.git-credentials, MomongaCode's home folder, the OS key store, or --secret paths.
rule-consistency Every rule can take effect rather than being shadowed or redundant.
bash-admission Modelled Bash allow and deny rules agree without unintended overlap.
superseded-forms With --mandate, flags Bash allow rules superseded by dedicated Git/forge tools.
mandate-holds With --mandate, ensures operations requiring a human remain gated.
vigil-contracts Checks that SKILL.md policy: frontmatter and tracePolicies parse cleanly, narrow monotonically over deny rules, and have feasible require_before prerequisites.
skill-guard-reach Proves that under security.skillGuard, tainted runs cannot reach secret reads, protected writes, outside-folder writes, or unconfined network egress sinks.

Two crucial honesty guarantees:

  1. Counterexample replay: Every counterexample Z3 finds is immediately replayed against the real TypeScript decide function, catching any drift between the solver model and the runtime code.
  2. No silent drops: Any unsupported tool or unmodelled pattern (such as WebFetch(domain:...)) is printed explicitly under Outside the proof:.

Real defects caught by formal verification

This isn't decorative mathβ€”it caught real bugs during development:

  • Refresh token reuse on persist failure (PlanCredential): A persist fault in the two-generation TLA+ model showed TLC violating SingleUse in 43,443 statesβ€”one generation rotated a refresh token in memory, failed to write to disk, released the lock, and a second generation re-read and re-sent the spent token.
  • Mandate secret-reach refutation (shipped-dataset-mandates): Z3 refuted all six shipped eval dataset mandates because bare Read, Glob, and Grep allow rules inadvertently opened ~/.ssh, keychains, and MomongaCode's home folder, forcing them to be tightened to workspace-scoped rules (Read(./**)).
  • Terminal reply drain across exit paths (TerminalModes): TLA+ modelling across start, replies, suspend, external editor, handover, and exit transitions ensured terminal replies drain cleanly on every exit path.

3. OS-Enforced Sandbox & SNI-Verifying Egress Proxy

Permission rules alone aren't enoughβ€”especially because Bash(...) allow rules (just like in Claude Code) match command text literally and cannot inspect what flags like git -c core.pager=... or find . -exec ... do. That's why MomongaCode pairs permissions with OS-level enforcement:

  • macOS: Seatbelt (sandbox-exec)
  • Linux: bubblewrap (bwrap)
  • Windows: Windows sandbox MXC (@microsoft/mxc-sdk 1.1.0) for the PowerShell tool (Bash runs unsandboxed on Windows and prompts before every command)

When a command needs network access to a named host (declared as e.g. {"hosts": ["registry.example.org"]}), MomongaCode spawns a per-command HTTP/HTTPS egress proxy that enforces both host allowlists and TLS SNI / HTTP Host verification.

sequenceDiagram
    participant Tool as "Sandboxed Tool (Seatbelt / bwrap)"
    participant Kernel as "OS Kernel Boundary"
    participant Proxy as "Per-Command Egress Proxy"
    participant Net as "Remote Host"

    Tool->>Kernel: "Write inside workspace"
    Kernel-->>Tool: "Allowed"

    Tool->>Kernel: "Read ~/.ssh or ~/.momonga"
    Kernel-->>Tool: "EACCES / Denied"

    Tool->>Kernel: "Direct outbound TCP or Unix socket"
    Kernel-->>Tool: "Blocked (0 connections)"

    Tool->>Proxy: "CONNECT granted.example:443 (SNI: granted.example)"
    Proxy->>Proxy: "Verify Host & TLS SNI match granted host"
    Proxy->>Net: "Forward encrypted stream"

    Tool->>Proxy: "CONNECT granted.example:443 (SNI: evil.example)"
    Proxy-->>Tool: "Close tunnel immediately (0 bytes forwarded)"

Inside the TUI, /sandbox check tests these exact boundaries live on your machine:

  1. Write outside workspace β€” confirms kernel denial and host non-existence.
  2. Read denied secret path β€” reads a sentinel protected by the same readDenied rules as ~/.ssh and ~/.momonga, confirming zero output.
  3. Direct outbound network (deny) β€” attempts a TCP connection to an ephemeral loopback listener, confirming 0 connections arrive.
  4. Egress proxy & SNI enforcement β€” verifies direct loopback bypass fails, an ungranted host CONNECT gets HTTP 403, and a CONNECT tunnel carrying a mismatched TLS SNI (evil.example) is closed with 0 bytes forwarded upstream.
  5. Unix domain socket access β€” attempts to connect to an ephemeral Unix socket when unixSocketAllow: [], confirming 0 connections arrive.

(On Windows with MXC, /sandbox check runs probes 1–3 for PowerShell and marks egress proxy and Unix socket probes as [N/A ] because MXC refuses named-host proxy policies fail-closed and does not restrict Unix sockets. If no OS sandbox is available, probes are [SKIPPED] and the command exits non-zero rather than faking a pass.)

4. Permission Modes, VIGIL Contracts & Local Guard Models

Every tool call passes through a deterministic decision pipeline before execution. You can switch modes in the session with /mode (manual, acceptEdits, plan, auto, bypassPermissions) or jump straight into read-only exploration with /plan.

flowchart TD
    Call["Proposed Tool Call"] --> Hard{"Secret path or explicit deny rule?"}
    Hard -->|"Yes"| Block["Blocked in every mode (including bypassPermissions)"]
    Hard -->|"No"| Vigil["VIGIL & SkillGuard Check (/skills inspect)"]
    Vigil -->|"Violates trace policy or taint sink"| Block
    Vigil -->|"Allowed"| Explicit{"Matches ask or allow rule?"}
    Explicit -->|"ask"| Prompt["Human Approval UI + PermissionRequest Hooks"]
    Explicit -->|"allow (and sandbox active)"| Run["Execute in OS Sandbox"]
    Explicit -->|"No rule match"| Mode{"Active /mode"}

    Mode -->|"manual"| Prompt
    Mode -->|"acceptEdits"| EditCheck{"Workspace edit?"}
    EditCheck -->|"Yes"| Run
    EditCheck -->|"No"| Prompt
    Mode -->|"plan"| PlanCheck{"Read-only?"}
    PlanCheck -->|"Yes"| Run
    PlanCheck -->|"No"| BlockPlan["Blocked or Ask"]
    Mode -->|"bypassPermissions"| Run
    Mode -->|"auto"| Classifier["Classifier Model (/auto-mode)"]

    Classifier -->|"High-confidence safe"| Run
    Classifier -->|"Unsafe, refusal, timeout, or >1024 tok"| Prompt

Runtime confinement & built-in guard models

  • VIGIL & SkillGuard (/skills inspect): Active by default (security.vigil: true, security.skillGuard: "fractional"). Skills can declare policy: frontmatter (tools, deny, paths, network, and trace rules like forbid_flow, never_after, require_before) that can only narrow permissions monotonically.
  • Built-in offline CPU classifiers (local-guard): In auto mode, instead of letting the main coding model judge its own calls, /auto-mode lets you choose a dedicated classifierβ€”including two built-in offline ONNX models (momonga-guard-small and momonga-guard-base) that download on demand with SHA-256 verification and run on CPU in an isolated local-guard-worker child process (1,024-token limit, fail-closed to human approval on errors or timeouts).
  • Choice-only judging models (system-one): You can also point autoMode.classifier or memory.autoReviewModel at a choice-only judging model via the system-one adapter (such as TypeSafe Jev on OpenRouter) that outputs fixed-choice decisions without generating prose.

5. Provenance-Sealed Memory & PoEM Execution Ledgers

In MomongaCode, long-term memory is structured (fact, episode, procedure) and grounded in verifiable evidenceβ€”not blind text appended to a prompt.

flowchart TD
    Run["Agent Run"] --> Taint{"Ingested untrusted external input? (MCP, network, outside read, tainted note)"}

    Taint -->|"No (Untainted)"| CandClean["Candidate Memory (authority: trusted_run)"]
    Taint -->|"Yes (Tainted)"| CandTainted["Candidate Memory (authority: tainted)"]

    CandClean --> AutoRev{"/memory auto on?"}
    AutoRev -->|"Yes (e.g. momonga-memory-guard)"| Judge{"Judged safe with high confidence?"}
    Judge -->|"Yes"| Active["Active Memory (HMAC-SHA256 Sealed)"]
    Judge -->|"No / Uncertain"| HumanRev["Human Queue (/memory review)"]
    AutoRev -->|"No"| HumanRev

    CandTainted -->|"Excluded from autoReview"| HumanRev
    CandTainted -->|"Corroborated by untainted run"| Active

    HumanRev -->|"Accept (/memory review)"| ActivePerson["Active Memory (authority: person)"]
    HumanRev -->|"Reject"| Rejected["Rejected"]

    Active --> Fresh{"Bound file SHA-256 & commit unchanged?"}
    ActivePerson --> Fresh
    Fresh -->|"Yes"| Verified["Recalled as verified"]
    Fresh -->|"No"| Stale["Flagged stale; archived after forgetAfterDays (default 90)"]
  • Evidence & freshness: Memories bind to file paths (with SHA-256 hashes), commits, and execution-ledger checks. When a bound file changes, MomongaCode automatically marks the memory stale inline in the UI and recall context.
  • Taint provenance: Runs that read MCP responses, network commands, outside-workspace paths, or existing tainted notes produce authority: tainted candidates. They are excluded from /memory auto and can only activate through explicit human review (/memory review) or independent untainted corroboration (corroboratedByRunId).
  • HMAC-SHA256 chains (/memory verify & /trace verify): Memory authority transitions and per-run PoEM (Provenance-of-Execution) ledgers are HMAC-SHA256 chained using subkeys derived via HKDF-SHA256 from your OS credential store (unsealed if no credential store exists). Tampered memories are excluded from recall, and tampered or key_missing ledgers fail closed at completion gates.

6. Verifiable Completion Gates

In many coding agents, if the model claims "all tests pass," the session endsβ€”even if the model skipped the suite or misread a failure. MomongaCode separates what the model ran from proof of completion.

flowchart TD
    Stop["Model Finishes Turn"] --> VerifyLedger["Verify PoEM Execution Ledger"]
    VerifyLedger -->|"Tampered or key_missing"| FailClosed["Fail Closed"]
    VerifyLedger -->|"Valid"| Conditions["Runtime Executes Owed Completion Conditions in Sandbox"]
    Conditions --> Pass{"All conditions exited 0?"}
    Pass -->|"Yes"| Done["COMPLETED (Eligible to propose memories)"]
    Pass -->|"No"| Changed{"Workspace changed since last failed round?"}
    Changed -->|"Yes"| Loop["Send failures back to model to fix"]
    Loop --> Stop
    Changed -->|"No"| Stopped["STOPPED (reason: conditions_unmet)"]

Completion conditions come from --until/--require flags, custom agent frontmatter, verification.commands, or project test commands you accept in /init or /config. A command the model ran during its own turn never counts as proof. Only after every owed condition passes on the final workspace state does the run reach COMPLETED (inspectable anytime with /report).

7. Prompt Caching, Token Efficiency & Live Inspection

Long coding sessions burn tokens quickly when prefixes shift or tool schemas bloat. MomongaCode turns six token-efficiency optimizations on by default and lets you audit them live with /inspect (Ctrl+X i) and /cost --breakdown.

flowchart LR
    T1["Tier 1: Immutable Core Prefix (Prompt Cache Anchor)"] --> T2["Tier 2: Capability-Adapted Tool Rules & LoadTools Catalog"]
    T2 --> T3["Tier 3: Adaptive Memory Budget, Compacted History & Fenced Data"]

    subgraph Engines["On-by-Default Runtime Engines"]
        E1["Tool Deferral (after 20 unused runs)"]
        E2["Concise Descriptions & Output Formatters (log, json, grep, identicalOutput)"]
        E3["Loop Guidance & Observed Context Capacity"]
        E4["fenceUntrusted (random per-session boundary)"]
    end

    Engines --> T2
    Engines --> T3
    T3 --> Inspect["Live Diagnostics: /inspect (Ctrl+X i) & /cost --breakdown"]
  • Three-tier cache-first assembly: Immutable instructions stay at the front so provider prompt caches hit reliably across turns and folders, followed by active tool guidelines (omitting inactive or denied tools completely) and session/environment details last.
  • No model-name branches: Behavior adapts strictly from measured or declared capabilities (parallelToolCalls, effort, contextWindow) rather than hardcoded if (model === ...) checks.
  • Adaptive memory & searchable compaction: Every 20 runs, MomongaCode scales the memory context budget (1/16 to 1/2 of budget) based on whether recalled memories were actually used. Once context passes 70% (context.compactAt), older turns compact with summary checks while remaining searchable via HistorySearch and HistoryRead.
  • Prompt injection fencing: Tool outputs, attached files, and ! shell outputs pass through fenceUntrusted with random per-session boundaries, isolating untrusted text under an explicit four-tier instruction hierarchy.

Built for Everyday Terminal Work

Beyond verification and security, MomongaCode is packed with practical workflows inside the interactive TUI:

  • Use any model (/login, /model): Connect local servers (Ollama, Apple fm), subscription accounts (ChatGPT, Grok, Claude Code, or Google Antigravity via agy), or API keys (OpenAI, Anthropic, Gemini) with automatic fallback (models.fallback) and idempotency-key support (idempotencyKeyHeader) against double-billing on retries.
  • A real terminal inside your session (/terminal): Splits the lower half of the fullscreen TUI into your $SHELL (ctrl+x t to switch focus). Commands there stay isolated from ~/.momonga and keychains, the model sees nothing from it, and the pane stays alive across /exit and daemon updates until /terminal close.
  • Extensions & IDE integration (/hooks, /mcp, /lsp):
    • 13 hook events (including PermissionRequest, async, and asyncRewake) installable via ~/.momonga/hooks/<name>.json.
    • MCP servers over stdio or HTTP/OAuth with headersHelper credential rotation, tool deferral, and automatic secret redaction.
    • Built-in LSP tool & post-edit diagnostics (/lsp) so Edit and Write surface new compiler errors immediately.
    • Agent Client Protocol (momonga acp) for editors.
  • Multi-session & delegated workflows (/sessions, /delegate, /style, /polish): Discover and message peer sessions (/sessions, /rename), run bounded tasks under named mandates (/delegate), tune response verbosity (/style), or run codebase-verified two-pass document revisions (/polish).

Get Started

If you're using Claude Code or OpenCode configs today, try installing momonga and running /policy verify --file on your existing settingsβ€”it takes 30 seconds and requires zero API keys.

πŸ“° Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.