---
name: sofuu
description: Comprehensive operational guide and instruction set for AI coding assistants to build, test, debug, and run applications using Sofuu — a general-purpose runtime for AI, built to run anywhere from servers to smart devices.
---

# Sofuu Runtime AI Developer Skill

This skill provides complete operational knowledge for AI assistants (Antigravity, Claude, Cursor, Copilot, Windsurf — nominative, no affiliation implied) working with **Sofuu** (`sofuu`), the general-purpose runtime for AI — built to run anywhere from servers to smart devices.

Sofuu is an early-stage AI runtime including QuickJS, libuv, local vector memory, JS/TS agent loops, MCP, and Kaze. Executables may require OS libraries; models, providers and external servers have their own dependencies. Local brain storage is encrypted by default; plaintext mode and unencrypted brain-card exports exist. Logs and remote providers have separate data handling.

---

## 1. Core Principles & Architectural Invariants

1. **Selected In-Process Workflows**:
   - Sofuu compiles QuickJS, a libuv event loop, encrypted cognitive vector memory (`.qtsq`), and agent loops directly into a single native binary.
   - Local memory can run without a database daemon; external inference providers, remote tools and servers may require additional processes or network access.
2. **Experimental Built-in Inference vs. External Endpoints**:
   - The built-in in-process local inference engine (`sofuu infer`, `sofuu.ai.streamLocal`) is an **[Experimental - Preview]** module using Metal GPU shaders and ARM NEON / AVX2 kernels.
   - **Deployment Guideline**: For heavy local inference workloads, route through a **llama.cpp / llama-server** endpoint (`sofuu.ai.stream({ provider: "llamacpp", ... })`). For remote models, use `sofuu.ai.stream()` / `complete()` with OpenAI, Anthropic, OpenRouter, or DeepSeek API keys.
3. **No Model Weight Downloads**:
   - Test and benchmark harnesses must run exclusively against local GGUFs already on disk. Never pull model weights from Hugging Face or remote CDNs in background jobs. Synthetic fixtures may test parsers and headers only; they are not real inference. Use existing local weights for inference or report the coverage gap. `sofuu.ai.embedLocal` is a deterministic hash embedder.
4. **Prompt Sovereignty**:
   - The project aims to preserve developer system prompts. Verify the actual provider and execution path for the relevant workload.
5. **Fail-Closed Security Architecture**:
   - Policy checks and approval handling vary by execution surface; do not assume a universal security boundary.
   - `sofuu.sandbox.*` provides a separate execution realm. R7 checks apply on supported host-tool paths; plugins run in-process and must be trusted as code.
6. **Adaptive Microtask Queue Scheduling**:
   - QuickJS microtasks (`Promise.then`, `await`, `queueMicrotask`) are pumped via adaptive dynamic batching (`adaptive_microtask_batch`). Under saturated event loops, the batch size scales from 64 (when I/O or timers are waiting) up to 1,024 (when no I/O is pending), providing high throughput with zero I/O starvation.
   - Idle microtask checks use an O(1) short-circuit (`JS_IsJobPending == 0`) with zero heap vector allocations.
7. **12-Factor Configuration Resolution**:
   - Standalone binaries and Kaze agent routines resolve configuration according to the production 12-factor hierarchy: CLI Flags (`--arg`, positionals) > Environment Variables (`AGENT_<PARAM>`, `SOFUU_*`) > Configuration File (`--config <path>`, `./agent.config.json`) > Agent Routine Signatures.
   - Missing required routine parameters emit structured diagnostic guidance detailing resolution steps.
8. **Native Cryptography (`node:crypto`)**:
   - Native cryptographic engine supporting standard SHA-1, MD5, SHA-256, SHA-512, and keyed HMAC algorithms directly within the standalone binary.
9. **Beta Development Status**:
   - Sofuu is in active beta (`v0.3.0-beta`). Certain features and edge integrations are under active iteration. Direct bug reports and issues to `hello@sofuu.xyz` or GitHub.

---

## 2. CLI Command Reference

Execute commands using `sofuu <subcommand>`:

| Command | Usage & Purpose |
|---|---|
| `sofuu` / `sofuu repl` | Boots interactive AI chat or JavaScript evaluation REPL. |
| `sofuu run <file.js\|ts>` | Executes JS or TS directly without a separate build step. Supports `sofuu run -` (stdin) and `-e <code>`. |
| `sofuu eval "<code>"` | Evaluates JavaScript inline (e.g. `sofuu eval 'console.log(sofuu.version)'`). Supports `eval <<EOF` via stdin. Add `-q` to silence return output. |
| `sofuu script run <agent.kaze>` | Executes a declarative Kaze agent routine with capability policy (`--policy`) and 12-factor configuration. |
| `sofuu script check <agent.kaze>` | Performs static verification and type checking on a Kaze routine without execution. |
| `sofuu script compile <agent.kaze>` | Compiles a Kaze routine into portable Kaze bytecode (`.kazebc`). |
| `sofuu compile <src> -o <bin>` | Compiles JavaScript, TypeScript, or Kaze (`.kaze`) directly into a standalone single-file native executable. |
| `sofuu chat` | Interactive coding agent in terminal with tool execution, persistent memory, and `@agent` routing. |
| `sofuu dev [dir]` | Starts AI-native full-stack dev server (`--port`, `--host`, `--model`). |
| `sofuu bundle <entry> -o <out>` | Bundles code and dependencies into a single distributable script. |
| `sofuu install` / `sofuu add <pkg>` | Resolves and installs npm packages without deep `node_modules` indirection. |
| `sofuu agent list` | Lists all agent definitions discovered in `~/.sofuu/agents/*.js`. |
| `sofuu agent run <name> "task"` | Executes an agent headless against a task. Use `--json` for pipeline output. |
| `sofuu logs` | Lists recent agent runs with run ID, timestamps, step counts, and status (`DONE`, `ERROR`, `CANCELLED`). |
| `sofuu logs show <id>` | Renders human-readable step-by-step trace transcript for a specific run. |
| `sofuu logs --last-error` | Renders a diagnostic post-mortem card for the newest crash. |
| `sofuu logs --follow` | Streams live events and tool calls from an active background agent worker. |
| `sofuu resume <id>` | Attempts to resume from a usable checkpoint; redacted or truncated checkpoints may be refused. |
| `sofuu plugin init <name>` | Scaffolds a 5-shield plugin (`--category=tool\|service\|workflow\|hook`). |
| `sofuu plugin validate <f>` | Strictly validates `plugin.json` manifest schema and declared permissions. |
| `sofuu plugin test <tool>` | Invokes an in-process plugin tool and reports its result. |
| `sofuu plugin run <tool>` | Executes a plugin tool with runtime 5-shield security enforcement. |
| `sofuu session list\|show\|repair` | Manages segmented `.store` project sessions and repairs damaged manifests. |
| `sofuu outputs list\|search\|context` | Queries, searches, and builds historical task context from archived outputs. |
| `sofuu policy check\|why` | Validates security policy or explains why an operation was allowed/denied. |
| `sofuu capabilities` | Emits the complete runtime capability manifest in JSON format. |
| `sofuu mcp list\|test\|add\|remove` | Discovers, tests, and configures Model Context Protocol servers. |
| `sofuu serve --brain <path>` | Serves local encrypted cognitive memory over an OpenAI-compatible HTTP API. |
| `sofuu infer <model> "<prompt>"` | On-device local GGUF inference *(experimental engine)*. |
| `sofuu doctor` | Verifies QTSQ linking, brain round-trip write/recall, and context window limits. |
| `sofuu version` | Prints version (e.g. `sofuu 0.3.0-beta revision b9c36976d`). |

---

## 3. Kaze: Domain-Specific Scripting

Kaze is for bounded agent and device routines, not general-purpose programming. The parser, checker, VM, capability declarations, and compilation exist. The embedded host can return synthetic AI, tool, memory and alert results; the real model-and-authorized-tool journey remains an open milestone. Do not present these outcomes as real integrations or deploy the examples for real-world actions.

```kaze
action add(a, b):
    return a + b
```

Use `sofuu script check agent.kaze` to check syntax without executing capabilities. Supported routines can be packaged with `sofuu compile agent.kaze -o my-agent`; OS libraries and workflow-specific models or services may still be needed.

## 4. JavaScript & TypeScript Runtime APIs

Every script executed by `sofuu run`, `sofuu eval`, or an agent has access to the global `sofuu` object.

### 4.1 Quickstart
```javascript
// quickstart.js - memory · native tools · agents · zero daemons
const brain = sofuu.memory.open("./brain.qtsq", 768);
brain.remember(sofuu.ai.embedLocal("runtime"), "AI runtime. Under 10 MB.");

// Local vector recall using the same embedding space
const [hit] = brain.recall(sofuu.ai.embedLocal("speed"), 1);

// Sandboxed native tool executed in-process with policy gates
const sys = sofuu.tools.execute("system_info", {});

// Autonomous agent - define once with memory & tools (0 models needed to test)
const agent = sofuu.agent.define({
  name: "assistant",
  system: "Cite sources.",
  tools: ["coding", "memory", "web"],
});

console.log(hit.text, "•", sys.platform || process.platform, "• agent:", agent.name);
// -> AI runtime. Under 10 MB. · darwin · agent: assistant
```

### 4.2 `sofuu.ai` — Inference, Embeddings & Vectors
```typescript
// 1. Cloud Streaming (OpenAI, Anthropic, OpenRouter, DeepSeek)
const stream = sofuu.ai.stream("Explain SIMD acceleration in one sentence", {
  provider: "openai",
  model: "gpt-4o",
});
for await (const chunk of stream) {
  process.stdout.write(chunk.text);
}

// 2. Offline Deterministic Embedding (Zero-byte model file, sub-microsecond)
const vector768 = sofuu.ai.embedLocal("native AI runtime"); // Float32Array(768)

// 3. Hardware SIMD Vector Math (ARM NEON / x86 AVX2)
const sim = sofuu.ai.similarity(vectorA, vectorB); // Cosine similarity [-1, 1]
const dot = sofuu.ai.dot(vectorA, vectorB);
const dist = sofuu.ai.l2(vectorA, vectorB);

// 4. In-Process Local Inference (Experimental Preview)
const localStream = sofuu.ai.streamLocal("./model.gguf", "Hello world");
```

### 4.3 `sofuu.memory` (CMA v2) & `sofuu.kv` — Encrypted On-Device Storage
```typescript
// Open or initialize encrypted .qtsq vector memory
const brain = sofuu.memory.open("./brain.qtsq", 768);

// Remember a fact with an embedding
brain.remember(
  sofuu.ai.embedLocal("runtime"),
  "Sofuu boots in under 25ms with zero background daemons."
);

// Vector recall using SIMD cosine search; latency varies
const [hit] = brain.recall(sofuu.ai.embedLocal("speed"), 1);
console.log("Recalled:", hit.text, "Score:", hit.score);

// Consolidate weak memories and run decay pass
brain.consolidate();

// Encrypted key-value storage
const kv = sofuu.kv.open("./state.qtsq");
kv.set("last_run", JSON.stringify({ ok: true, timestamp: Date.now() }));
const state = JSON.parse(kv.get("last_run"));
```

### 4.4 `sofuu.agent` & Domain Toolpacks
```typescript
// Define an autonomous agent with prompt sovereignty and modular toolpacks
sofuu.agent.define({
  name: "reviewer",
  system: "You are a code reviewer. Report bugs and security risks clearly.",
  tools: ["coding", "memory", "system"],
  memory: "agent",
  budget: { maxSteps: 10, maxWallMs: 60_000, taskGate: false },
});

// Run the agent headless
const result = await sofuu.agent.run("reviewer", "Audit src/js/runtime.js for memory leaks");
console.log(result.answer);
```

#### Available Toolpacks (`sofuu.tools.PACKS`):
- `coding`: `read_file`, `write_file`, `edit_file`, `apply_patch`, `grep`, `glob`, `list_dir`, `bash`, `code_eval`, `todo_write`.
- `web`: `web_search`, `web_open` (reader-friendly text scraper).
- `memory`: `memory_search`, `memory_remember`.
- `system`: `system_info` (OS, CPU, GPU engine, memory, capabilities).

### 4.5 `sofuu.sandbox` — Hermetic Realm Execution
```typescript
// Hermetic execution realm: zero host access unless explicitly bridged
const r = await sofuu.sandbox.run("const x: number = 6 * 7; x", {
  preset: "strict",
  fuel: 5_000_000,
  timeoutMs: 2_000,
  maxMemoryMB: 64,
});
console.log(r.success, r.result); // true, 42
```

### 4.6 `sofuu.mcp` — Model Context Protocol
```typescript
// Connect to external MCP server over stdio
const mcp = await sofuu.mcp.connect("npx -y @modelcontextprotocol/server-filesystem /tmp");
const content = await mcp.call("tools/call", {
  name: "read_file",
  arguments: { path: "/tmp/data.txt" },
}, { timeoutMs: 30_000 });
mcp.disconnect();

// Expose local Sofuu tools as an in-process MCP server host
sofuu.mcp.serve();
```

---

## 5. Architectural Subsystems & Division Registry

The project enforces strict modularity documented in `sofuu-map.md`:

| Division | Name | Focus | Invariants |
|---|---|---|---|
| **D01** | Core Substrate & Event Loop | QuickJS, libuv, C-API, memory allocator | Release binary $\le 5.5\text{ MiB}$; fast-path zero-allocation microtask queue drain. |
| **D02** | Cognitive Vector Memory | In-process QTSQ engine, SIMD recall | Zero external DB servers; deterministic 768-dim offline embeddings. |
| **D03** | Autonomous AI Agents | Turn-block context retention, sub-agents | Bytecode snapshots strictly synchronized (`make bc-check`). |
| **D04** | Tool Belt & Protocol Gates | Sandboxed tools, SSRF firewall, native MCP | Policy and SSRF checks apply on supported paths; enforcement varies by surface. |
| **D05** | Kaze Language & Compiler | Declarative `.kaze`, linear arena VM | 100% domain-agnostic compiler; zero hardcoded parameter names. |
| **D06** | Hardware Inference Engine | GGUF/SafeTensors, Metal shaders, NEON | Designated as [Experimental - Preview]; zero model weight downloads. |
| **D07** | Robotics, Drones & Edge | MAVLink 2.0, GPIO pulse timers | Heartbeat loss triggers immediate fail-closed motor stop. |
| **D08** | CLI, Interactive TUI & REPL | Terminal chat, doctor, flags | Standardized "runtime for AI" brand voice; zero decorative emojis. |
| **D09** | Mobile & Native Embeddings | Android APK/AAR, Swift Package Manager | Clean C-ABI (`sofuu-capi`); dual-architecture support. |
| **D10** | Desktop App Presentation | Tauri GUI presentation shell | Isolated from default workspace members; system GTK linkage. |
| **D11** | Public Surface & Distribution | Landing page, npm package, docs | Transparent active beta status; report bugs to `hello@sofuu.xyz`. |

---

## 6. Pre-Commit Verification Gatekeepers

Before committing changes in any division:
1. `make bc-check`: Asserts 11 shipped QuickJS bytecode snapshots match their JavaScript sources.
2. `make size-check`: Asserts the release binary remains within the $5,767,168\text{ byte}$ ($5.5\text{ MiB}$) budget.
3. `cargo test --manifest-path kaze/Cargo.toml`: Asserts all 174 Kaze language and capability gate tests pass.
4. `scripts/contract/run_contract_tests.sh`: Asserts strict contract test execution.
