Everything You Ever Wanted to Know About FractalOS

The Definitive Architectural Codex, System Internals, and Operating Manual

Release v1.0.0 Python 3.14.2 / WebAssembly 153 Native Commands P2P WebRTC Mesh Kinetic Autopilot AI

Book I: Systems Philosophy & Origins

1. The Soul of a Living Terminal

In an era dominated by opaque cloud computing and walled gardens, FractalOS represents a return to first principles: an operating system that lives, breathes, and persists entirely on your machine. Originally conceived as OopisOS—a browser-based Unix simulation—FractalOS has evolved into a full-fledged, dual-engine computational habitat.

FractalOS is founded on the concept of Narrative Computing. The shell is not merely a dumb parser that executes isolated binaries; it is a collaborative environment where a local Large Language Model (Samwise) lives directly alongside the operator. You can interact through orthodox Unix pipelines, inspect system telemetry, or hold a natural conversation with an autonomous agent that inspects file trees, runs Python code, and coordinates distributed swarms on your behalf.

The Five Core Tenets of FractalOS
  1. Python is the Source of Truth: The virtual file system, user security model, permissions, and shell execution logic reside exclusively inside the WebAssembly Python kernel. JavaScript mirrors state for presentation, but never decides it.
  2. The Kernel Never Touches the Page: Anything visible, audible, or browser-specific is expressed as a declarative Effect returned by the kernel. The frontend stage manager fulfills these effects.
  3. Zero Build Step, Zero npm Dependencies: Clone the repository, serve resources/ over any standard HTTP server, and run. There are no node_modules, webpack bundlers, or remote CDN fetches.
  4. The AI is a User, Not Root: The autonomous agent executes through the identical executor, permission matrix, and audit logging as a human operator. Destructive steps are governed by an objective Voltage Safety policy.
  5. Verified Means Observed: Claims are invalid until proven by automated headless browser smoke tests or in-OS diagnostic test runners.

2. The Collaborative Partnership & Unique License

FractalOS was developed through an intimate partnership between its human curator (Andrew Edmark) and AI assistants (Gemini & Claude). Unlike conventional software where AI serves merely as an autocomplete utility, FractalOS was architected and documented as a deliberate joint venture.

The project is governed by a permissive MIT-style license featuring a dedicated Authorship and Contribution Acknowledgment. The preamble acknowledges the shared creative direction: the human curator provides architectural vision, constraints, and approval, while the AI generates code, constructs tests, and documents systems.

3. The Three Runtimes

FractalOS does not confine itself to a browser tab. It is engineered to operate across three distinct environments:

3.1 Browser Mode (Zero-Install WebOS)

What It Does

Runs FractalOS in any modern desktop or mobile browser by serving static files over any standard HTTP server (e.g. python3 -m http.server 8000 --directory resources).

How It Works

Pyodide WebAssembly fetches its trimmed runtime and Python packages from local disk (./dep/pyodide/). File system changes are persisted to the browser's transactional IndexedDB store through an asynchronous Storage Hardware Abstraction Layer (IndexedDBStorageHAL).

Why It Works

Complete portability. Users can boot a fully featured Unix workstation with zero setup, zero permissions, and zero tracking, sandboxed entirely within the browser's WebAssembly memory space.

3.2 Portable Desktop Mode (Neutralinojs)

What It Does

Executes FractalOS as a native standalone desktop application on Linux, macOS, and Windows with physical disk persistence.

How It Works

The application runs inside a lightweight Neutralinojs webview shell (under 15 MB). The frontend detects window.Neutralino and automatically swaps the IndexedDB HAL for NeutralinoStorageHAL. System state, user directories, and configuration are persisted directly to the local filesystem in data/.

Why It Works

Frees the user from browser storage quotas and accidental cache clears while avoiding the memory bloat of Electron. The operating system feels like a genuine native workstation.

3.3 Bare-Metal Appliance Mode (Fractal Pi)

What It Does

Boots directly to a full-screen FractalOS terminal on Raspberry Pi or ARM64 single-board hardware, transforming the board into a dedicated physical appliance.

How It Works

Provisioned via extras/build_distro.sh, the appliance boots minimal Linux (e.g., Raspberry Pi OS Lite), auto-logs in a dedicated user, initializes an X11 kiosk display server, and launches the FractalOS interface. A host bridge enables direct control over hardware GPIO pins, button interrupts, and physical sensors.

Why It Works

Bridges the virtual shell with physical computing. Autonomous agents in the shell can sense hardware buttons, drive LEDs, and act as physical ambient computing hubs.


Book II: The Core Architecture & Engine Room

The fundamental breakthrough separating FractalOS 1.0 from OopisOS v5.0 is the complete migration from an in-browser JavaScript interpreter to a true Hybrid WebAssembly/Python Kernel architecture.

+-----------------------------------------------------------------------------------+
|                            JAVASCRIPT FRONTEND ("STAGE MANAGER")                  |
|                                                                                   |
|   +-------------------+  +--------------------+  +----------------------------+   |
|   | Terminal UI & Multiplexer |  | Window Manager (wm)|  | Tone.js Audio Synthesizer  |   |
|   | (split_h / split_v)       |  | (floating / docked)|  | (polyphonic music engine)  |   |
|   +-------------------+  +--------------------+  +----------------------------+   |
|             |                      |                           |                  |
|             v                      v                           v                  |
|   +---------------------------------------------------------------------------+   |
|   |                       effect_handler.js (EFFECT ROUTER)                   |   |
|   |     play_sound | split_pane | launch_app | confirm_ai_command | sudo_exec     |   |
|   +---------------------------------------------------------------------------+   |
|             ^                                                                     |
+-------------|---------------------------------------------------------------------+
              | (Declarative Effects JSON)             | (Context JSON & Stdin)
              |                                        v
+-------------|---------------------------------------------------------------------+
|             |               PYTHON KERNEL IN WEBASSEMBLY (PYODIDE 314)            |
|             |                                                                     |
|   +---------------------------------------------------------------------------+   |
|   |           bridge.js  <====== (syscall / execute_command) ======>  kernel.py    |   |
|   +---------------------------------------------------------------------------+   |
|             |                                                                     |
|             v                                                                     |
|   +---------------------------------------------------------------------------+   |
|   |                         MODULE_DISPATCHER (kernel.py)                     |   |
|   +---------------------------------------------------------------------------+   |
|      |               |               |                |               |           |
|      v               v               v                v               v           |
|  executor.py   filesystem.py     users.py          sudo.py       ai_manager.py    |
|  (Pipes/Jobs)  (POSIX / Inodes)  (PBKDF2 crypto)   (Sudoers)     (Voltage Safety) |
|      |               |               |                |               |           |
|      +---------------+---------------+----------------+---------------+           |
|                                      |                                            |
|                                      v                                            |
|                   153 Native Python Commands (commands/*.py)                      |
|                                      |                                            |
|                                      v                                            |
|                   Storage HAL (Save Callback to IndexedDB / Host)                 |
+-----------------------------------------------------------------------------------+

4. The Pyodide WebAssembly Kernel & Syscall Bridge

Files: resources/bridge.js, resources/core/kernel.py, resources/core/manifest.json

What It Does

Loads CPython 3.14 compiled to WebAssembly inside the browser, mounts the virtual kernel filesystem, dynamically injects all core Python modules and commands, and exposes a standardized two-way asynchronous communications channel: FractalOS_Kernel.syscall() and FractalOS_Kernel.execute_command().

How It Works
  1. Manifest Fetch: On page boot, bridge.js fetches core/manifest.json (generated by tools/gen_manifest.py), discovering all modules in core/, core/apps/, and core/commands/.
  2. Runtime Initialization: Pyodide loads from vendored assets in ./dep/pyodide/. It installs pre-vendored WebAssembly wheels including cryptography and any community packages listed in /etc/pkg_manifest.json.
  3. VFS Ingestion: bridge.js calls pyodide.FS.mkdir() to create /core, /core/commands, and /core/apps. It reads Python source files via HTTP fetch() and writes them into Pyodide's memory filesystem.
  4. Module Dispatch: kernel.py defines MODULE_DISPATCHER, mapping system modules (executor, filesystem, users, groups, sudo, ai, story, audit, swarm).
  5. Type Sanitization: Raw JavaScript values crossing into Python can be pyodide.ffi.jsnull, which is falsy but not identical to Python None. The bridge normalizes inputs through _from_js() at the single crossing point before execution.
Why It Works

Centralizes all business logic and security authority into genuine Python. Individual shell commands cannot corrupt browser DOM state or leak memory. Python's rich standard library (regular expressions, math, AST parsers, datetime, cryptography) becomes instantly available inside the virtual shell without custom JS reimplementations.

5. The Effect Contract

Files: resources/scripts/effect_handler.js, resources/core/executor.py

What It Does

Defines the formal protocol for the Python kernel to request operations outside its WebAssembly sandbox. Commands never touch the DOM or browser APIs directly; they return declarative JSON "Effect" objects that the JavaScript stage manager fulfills.

How It Works
  1. When a command executes, it returns either text output ({"success": true, "output": "..."}) or one or more effects ({"effect": "name", ...} or {"effects": [...]}).
  2. boot.js captures the execution result and passes each effect to handleEffect(result, options) in effect_handler.js.
  3. A centralized switch statement dispatches the effect to the responsible frontend manager:
    • play_sound: Dispatches note arrays and durations to SoundManager (Tone.js).
    • split_pane / multiplexer_action: Invokes MultiplexerManager to create horizontal/vertical shell viewports.
    • window_action / wm: Invokes WindowManager to float, tile, dock, minimize, or close GUI panels.
    • confirm_ai_command: Opens a modal dialog asking the operator to authorize high-voltage agent commands.
    • mesh_*: Dispatches peer-to-peer data channel operations to NetworkManager.
    • clipboard_action: Reads or writes to the host system clipboard.
    • clear_screen: Clears the terminal DOM buffer.
Why It Works

Preserves strict separation of concerns (Decision D-002). Because commands only generate data structures, the entire operating system can be verified headlessly via Node.js scripts or unit tested in standard Python without needing a browser window.

6. The POSIX Virtual File System

Files: resources/core/filesystem.py

What It Does

Provides a fully compliant, hierarchical, Unix-like virtual file system supporting files, directories, symbolic links, file owners, group memberships, and octal permission modes (e.g. 0o755, 0o644).

How It Works
  1. Data Model: The VFS is structured as an in-memory recursive tree of node dictionaries. Each directory contains a children mapping. Each file contains a content string, size, timestamps (mtime, ctime), owner, group, and octal mode.
  2. Symlink Resolution: get_node_by_path() traverses path components step by step. When it encounters a node of type symlink, it resolves the target path up to a recursion depth limit of 10 to safely prevent circular link loops.
  3. Permission Checking: has_permission(node, user, permission_type) compares the user's UID and supplementary GIDs against the octal bits (read 4, write 2, execute 1) across owner, group, and other classes. The root superuser bypasses standard checks.
  4. Persistence Loop: Whenever a mutating operation occurs (write, create, delete, chmod, chown), fs_manager calls the registered save_function callback, serializing the tree back across the bridge to StorageHAL.save().
Why It Works

In-memory tree traversal yields microsecond response times for complex pipelines, while background synchronization preserves durability across page reloads. Centralizing permission enforcement inside filesystem.py guarantees that commands cannot bypass security boundaries.

7. Identity, Authentication, PBKDF2 & Sudo

Files: resources/core/users.py, resources/core/groups.py, resources/core/sudo.py

What It Does

Maintains multi-user credentials, group hierarchies, cryptographic password hashing via PBKDF2-HMAC-SHA256, and privilege escalation governed by /etc/sudoers.

How It Works
  1. Cryptographic Hashing: Passwords are never stored in plaintext. users.py utilizes Pyodide's compiled cryptography wheel to generate 100,000-iteration PBKDF2-HMAC-SHA256 hashes paired with 16-byte cryptographically secure random salts.
  2. Sudo Policy Engine: SudoManager parses /etc/sudoers dynamically. It supports user rules, group permissions (e.g. %wheel ALL=(ALL) ALL), specific command whitelists, and NOPASSWD directives.
  3. Timestamp Tickets: Upon successful password validation, a temporary timestamp ticket is recorded. Subsequent sudo executions within the timestamp_timeout window (default 5 minutes) bypass password prompts.
  4. Privilege Scoping: sudo_exec returns an effect. The executor elevates the effective user context strictly for the duration of the target command and reverts immediately to the original user upon completion.
Why It Works

Adheres strictly to the principle of least privilege. Real cryptographic key derivation protects user credentials, and the isolated elevation lifecycle prevents privilege leaks across chained shell commands.

8. The Shell Execution Pipeline

Files: resources/core/executor.py

What It Does

The central nervous system of the command line. Deconstructs raw shell text into pipelines, handles environment variable substitution, brace expansion, input/output redirection, background jobs, and chains commands across |, &&, ||, and ; operators.

How It Works
  1. Lexical Analysis & Parsing: Tokenizes input honoring single and double quotes, escaped characters, subshell substitutions ($(...)), and wildcards (*, ?).
  2. Pipeline Assembly: Groups command segments into pipelines. Standard output of an upstream command is fed into the stdin buffer of downstream commands.
  3. Redirection Management: Intercepts >, >>, and < operators, redirecting stdout and stdin streams to and from virtual file nodes.
  4. Module Loading & Execution: Resolves the command name to a module in commands/<name>.py. It verifies user permissions, injects execution context (cwd, user, environment, flags), and invokes the command's asynchronous run() function.
  5. Background Job Tracking: Commands ending with & are registered into an active job table with a unique Process ID (PID) and run asynchronously.
Why It Works

Provides genuine POSIX shell semantics entirely inside Python. Developers can construct complex automation pipelines (e.g. cat logs.txt | grep ERROR | wc -l > count.txt) identically to a native Linux environment.

9. Sessions, Environment & Audit Logging

Files: resources/core/session.py, resources/core/audit.py

What It Does

Manages user session stacks (supporting nested su and logout), scoped environment variables, command history with search, command aliases, and an immutable security audit trail recorded in /var/log/audit.log.

How It Works
  1. Session Stack: session_manager maintains an array of active user states. Logging in with su <user> pushes a new session frame; logout pops the top frame and restores the previous user's cwd and environment.
  2. Environment Scoping: env_manager supports stacked variable scopes. Running shell scripts (run script.sh) pushes a temporary scope that is discarded upon script completion, preventing environment pollution.
  3. Audit Trail: audit_manager automatically records security-critical events (login successes/failures, sudo invocations, user creations, permission modifications) into /var/log/audit.log with ISO timestamps and user IDs.
Why It Works

Provides institutional-grade operational security and reproducible shell states, ensuring that scripts run safely and system administrators can trace every privileged action.

10. The Dual-Tier Storage HAL

Files: resources/scripts/storage.js, resources/scripts/storage_hal.js

What It Does

Decouples system persistence from specific browser or desktop APIs. Employs a dual-tier strategy: fast key-value storage for UI preferences, and an asynchronous Hardware Abstraction Layer (HAL) for the virtual filesystem tree.

How It Works
  1. StorageManager: Wraps browser localStorage for lightweight configuration (theme choices, window layout, command aliases, active terminal history).
  2. StorageHAL Interface: Defines an abstract contract requiring init(), load(), save(), and clear().
  3. IndexedDBStorageHAL: In Browser Mode, stores the full serialized VFS in an IndexedDB object store with transactional integrity, capable of holding hundreds of megabytes of virtual files.
  4. NeutralinoStorageHAL: In Portable Desktop Mode, swaps database storage for direct host file writes inside the application's local data/ folder.
Why It Works

Decoupling persistence through the HAL contract allows FractalOS to swap storage backends (browser databases, local host disk, or remote cloud buckets) without altering a single line of virtual filesystem or kernel code.

11. Tone.js Audio Engine

Files: resources/scripts/sound_manager.js, resources/dep/Tone.js

What It Does

Acts as the auditory nervous system of FractalOS, providing polyphonic music synthesis, system notification tones, and musical scripting capabilities for commands like play, beep, and games.

How It Works
  1. AudioContext Management: Web browsers prohibit audio playback until an explicit user interaction occurs. SoundManager monitors initial mouse and keyboard events to cleanly initialize the Tone.js context.
  2. Polyphonic Synthesis: Manages a shared Tone.PolySynth instance capable of playing individual frequencies (e.g. C4) or complex polyphonic chords (e.g. ["A3", "C4", "E4"]).
  3. Non-blocking Scheduling: Commands issuing audio effects specify note values and musical durations (e.g. 4n for quarter notes). The sound manager schedules synthesis asynchronously while allowing the shell to remain responsive.
Why It Works

Encapsulates complex Web Audio API DSP routing and timing loops within a dedicated, reliable manager, allowing shell scripts and applications to generate expressive sound effects with single-line commands.


Book III: The Living Shell & Kinetic AI

12. Philosophy: The AI as an Operator, Not Root

What It Does

Establishes the behavioral and security boundary for artificial intelligence within FractalOS. Unlike chatbots with unrestricted API backdoors or arbitrary shell execution, the AI operates as an unprivileged system user subject to the exact same permissions, quotas, and audit logging as a human operator.

How It Works

All commands planned by the language model pass through the central command_executor.execute() entry point. If the agent attempts to read /vault/secret.txt owned by root with mode 0o600, the virtual filesystem raises an authentic permission error. The agent cannot grant itself permissions or bypass path validation.

Why It Works

Treating the AI as an unprivileged user guarantees system integrity. The operator retains absolute sovereignty: destructive actions require interactive consent, and all autonomous steps are traceable in /var/log/audit.log.

13. The Samwise Engine

Files: resources/core/ai_manager.py, resources/core/commands/samwise.py, /etc/ai.conf

What It Does

samwise is the primary interface to the system's kinetic AI capabilities. It supports multi-provider connectivity (local Ollama or cloud-based Google Gemini), intent classification, multi-step plan generation, interactive chat mode (samwise -c), and automated shell execution.

How It Works
  1. Configuration Resolution: ai_manager.py loads settings from /etc/ai.conf (default provider, model, local endpoints like http://localhost:11434, and request timeouts). Cloud API keys are retrieved from secure browser storage.
  2. Context Assembly: _get_terminal_context() gathers a live snapshot of the operating environment: effective username, current working directory (cwd), file listings, recent command history, and any active error state.
  3. Intent Routing: Evaluates incoming prompts to determine whether the inquiry is a general conversational question or a filesystem/system task requiring tool execution.
  4. Plan Generation: In tool mode, the planner LLM generates a structured sequence of whitelisted shell commands. The synthesizer LLM subsequently consumes the command execution output to craft a comprehensive final response.
Why It Works

Provider abstraction allows users to run completely offline models via Ollama for maximum privacy or cloud models via Gemini for raw reasoning power without altering shell workflows.

14. Autopilot & The BoneAmanita Driver

Files: resources/core/bone_driver.py

What It Does

Powers the autonomous kinetic mode of the AI (samwise --autopilot or samwise -a). The BoneAmanita driver acts as the subconscious persona of the operating system, enforcing physical and operational laws upon the language model.

How It Works
  1. The Four Laws of Physics: The driver injects strict operational constraints into the system prompt:
    • Gravity: The agent lives in /home/<user> and must operate using absolute paths.
    • Language: Scripts are either Shell (.sh, requiring chmod 755 before run) or Python (.py, executed directly via python using standard library only).
    • Ritual: Modifying executable scripts requires explicit permissions.
    • Memory: Long-term agent memory resides in ~/.samwise/memory/ and vectorizes into subconscious.json during samwise --sleep.
  2. Execution Loop: In autopilot mode, the agent receives a task, generates a clean numbered list of actions, evaluates the plan's voltage, and executes the sequence step-by-step.
Why It Works

A strictly constrained system prompt eliminates conversational fluff. The model outputs only parseable commands, dramatically improving reliability and execution speed.

15. The Voltage Safety Framework

Files: resources/core/bone_driver.py (Decision D-016)

What It Does

Quantifies the operational risk of any proposed AI plan through an objective mathematical score ("Voltage"). Plans with high or dangerous voltages trigger automatic circuit breakers, preventing unintended file loss or disruptive hardware actions.

How It Works

Voltage is computed purely from command operations, never from speculative argument text or model commentary:

Operation / Command Voltage Score Risk Rationale
cd 0.0 V Navigation only; zero filesystem mutation.
Read commands (ls, cat, grep, tree, pwd, head, whoami) 0.1 V Read-only inspection; non-destructive.
Script / Execution (python, run, chmod) 2.0 V Active computation and permission setting.
Filesystem Mutation (mkdir, touch, cp, mv, edit, forge) 5.0 V File creation, overwriting, or structural modification.
Destructive / Rewind (rm, rmdir, clearfs, story rewind) 20.0 V Irreversible file deletion or branch reversion.
Physical Hardware (gpio write, gpio monitor) 5.0 V + Action Hardware actuation plus nested command voltage.
Swarm Delegation (mesh-agent, swarm) 1.0 V / 5.0 V 1.0 V for read queries; 5.0 V with --autopilot.

The total voltage determines the system's safety response:

  • < 1.0 V: 🟢 LOW VOLTAGE (Safe) — Executes silently.
  • 1.0 – 9.9 V: 🟡 MEDIUM VOLTAGE (Caution) — Executes with notification.
  • 10.0 – 19.9 V: 🟠 HIGH VOLTAGE (Risk) — Requires automatic home directory snapshot.
  • ≥ 20.0 V: 🔴 CRITICAL VOLTAGE (Danger) — Safety brake engages! Execution halts unless overridden with explicit operator confirmation or the --force flag.
Why It Works

Objective scoring prevents catastrophic failures (e.g. hallucinated rm -rf /). The model cannot bypass the circuit breaker by rephrasing its output; the operation itself dictates the score.

16. Reliability: Inner Validation Loop, Scar Tissue & Forge

Files: resources/core/ai_manager.py, resources/core/commands/forge.py

What It Does

A triumvirate of reliability systems that turn a fallible language model into a dependable system engineer: automated error correction, memory of recent failures, and safe atomic file creation.

How It Works
  1. Inner Validation Retry Loop (Decision D-022): When validate_plan() detects an invalid command, syntax flaw, or illegal wildcard (e.g. rm -r *), _request_valid_plan intercepts the error before execution. It silently reprompts the model with the exact reason and the allowed command manifest, granting up to 3 self-correction attempts.
  2. Scar Tissue Context Injection (P2-18): Runtime errors (e.g., trying to cd into a nonexistent directory) are stored in _AI_LAST_ERROR. This context is injected into the next prompt as a temporary warning so the model avoids repeating the mistake.
  3. Atomic File Scaffolding (forge): Shell quoting is notoriously fragile when writing multi-line code via echo "..." > file. The forge command allows the agent to scaffold files atomically with clean newline escapes (\n), supporting --literal modes to protect nested Python code.
  4. Dry-Run Planning (samwise --dry-run): Predicts the execution path, computes voltage, tests validation, and displays the plan without running any code.
Why It Works

LLMs frequently make minor syntax or quotation slips on their first attempt. Silent retries and scar tissue give the agent self-healing resilience without interrupting the human operator.

17. Story: Native VFS Snapshot Versioning

Files: resources/core/story_manager.py, resources/core/commands/story.py

What It Does

A lightweight, content-addressed version control system embedded directly into the virtual filesystem. Enables time travel, atomic snapshots, and instantaneous rollback of directory trees.

How It Works
  1. Repository Structure: story begin creates a hidden .story/ directory containing snapshots/ (content-addressed blobs named by SHA-1 hash) and log.json.
  2. Snapshot Creation: story save "message" traverses tracked files, writes new blobs, and records a commit object containing author, timestamp, commit message, and full file tree mapping.
  3. Autopilot Safety Checkpoints: Before executing any mutating autopilot plan, FractalOS automatically saves a snapshot ("Home checkpoint saved").
  4. Time Travel: story rewind <id> restores all files to the exact state captured in that snapshot.
Why It Works

Provides a fail-safe parachute for autonomous AI development. If an agent writes faulty code or corrupts a file, the operator or agent can rewind to the prior checkpoint with a single command.


Book IV: The Distributed P2P Mesh & Swarms

18. Mesh Topology: WebRTC, BroadcastChannel & Signaling

Files: resources/scripts/network_manager.js, signaling_server.cjs

What It Does

Connects independent FractalOS instances running across different browser tabs or separate physical computers into a decentralized peer-to-peer network without storing user data on a central server.

How It Works
  1. Dual-Tier Discovery:
    • Local Mesh: Utilizes browser BroadcastChannel for zero-configuration instant discovery between tabs and windows on the same machine.
    • Remote Mesh: Connects to a lightweight WebSocket signaling server (ws://localhost:8080) solely to exchange SDP offers, answers, and ICE candidates.
  2. Direct Data Channels: Once signaling completes, peers establish an encrypted peer-to-peer RTCDataChannel. All terminal data, files, and chat messages flow directly between client machines.
  3. Node Identity: Each booting node assigns itself a deterministic ephemeral address: oos-<timestamp>-<random>.
Why It Works

Zero reliance on cloud databases. Communication is low-latency, bandwidth-efficient, and inherently private.

19. Node Presence & Telemetry

Files: resources/core/commands/peers.py, resources/core/commands/netstat.py

What It Does

Provides real-time visibility into discovered peers on the mesh network, connection health, round-trip latency, and shared capabilities.

How It Works

peers queries NetworkManager via the effect bridge, rendering an interactive table of active nodes. netstat --mesh outputs connection states (connected, connecting, disconnected) and transport channels (WebRTC vs BroadcastChannel).

Why It Works

Operators have immediate diagnostic feedback when establishing inter-machine terminal clusters or diagnosing network latency.

20. Remote Shell Attachment & Node Collaboration

Files: resources/core/commands/attach.py, wall.py, talk.py

What It Does

Enables an operator on Node A to attach their terminal directly to the active shell session on Node B, broadcast messages across the network, or hold private conversations.

How It Works
  1. Session Mirroring: Running attach <node-id> intercepts local terminal input in boot.js and transmits commands across the WebRTC data channel. The remote host executes the command in its kernel and streams back output and ANSI codes in real time.
  2. Detachment: Typing detach or exit cleanly releases the remote channel, returning the operator to their local shell.
  3. Network Broadcast: wall <message> broadcasts a high-priority system alert to all connected nodes on the mesh.
  4. Direct Messaging: talk <node-id> <msg> sends point-to-point text messages between terminals.
Why It Works

Delivers collaborative pair-programming and remote administration directly inside the browser terminal without SSH keys or external relay proxies.

21. Zero-Cloud P2P File Transfer

Files: resources/core/commands/mesh_cp.py, scp.py

What It Does

Enables secure, peer-to-peer file transfer between nodes across the mesh network without intermediary cloud storage or servers.

How It Works
  1. Push Transfer: mesh-cp local_file.txt oos-node-2:/home/Guest/dest.txt reads the file node from the local VFS, chunks the content into binary or base64 envelopes, and streams it over the active RTCDataChannel.
  2. Pull Transfer: Specifying a remote source (mesh-cp oos-node-2:/var/log/audit.log ./audit.log) sends a file retrieval request to the peer node. The peer's kernel verifies read permissions and streams the file payload back.
Why It Works

Makes distributed workflows frictionless. Developers can transfer code, configs, or data sets between devices instantly over local networks.

22. Swarm Task Delegation & Inter-Node Voltage Policies

Files: resources/core/swarm_manager.py, resources/core/commands/swarm.py, mesh_agent.py, /etc/swarm.conf

What It Does

Allows a local Samwise agent to delegate sub-tasks, queries, or hardware automation instructions to peer agents across the mesh network, synthesizing the multi-node outcomes into a unified answer under strict security policies.

How It Works
  1. Task Dispatch: mesh-agent <peer-id> "inspect sensor pin 17" --autopilot packages the task prompt and sends it to the target node's swarm channel.
  2. Policy Interlocks: The remote node's SwarmManager inspects /etc/swarm.conf:
    {
      "max_remote_voltage": 10.0,
      "allow_remote_autopilot": true,
      "allow_remote_gpio": false,
      "allow_remote_force": false,
      "audit_remote_tasks": true
    }
    If the incoming task exceeds max_remote_voltage (default 10.0 V) or requests unauthorized GPIO actuation without allow_remote_gpio: true, the request is immediately rejected.
  3. Provenance Auditing: Every dispatched and received swarm task is logged to /var/log/audit.log with the origin node ID and timestamp.
Why It Works

Prevents rogue nodes or compromised agents from driving arbitrary hardware or wiping files on peer machines. Swarm computing operates within safe, verifiable boundaries.


Book V: Terminal Multiplexing, Window Management & Hardware

23. Terminal Multiplexing & Split Panes

Files: resources/scripts/multiplexer_manager.js, resources/core/commands/split_h.py, split_v.py, panes.py

What It Does

Transforms the single terminal view into a tiled multiplexer supporting arbitrary horizontal and vertical splits, independent working directories, isolated scrollback buffers, and zoom mode.

How It Works
  1. Pane State: MultiplexerManager tracks an array of pane records. Each pane maintains its own working directory (cwd), output DOM container, prompt line, and index.
  2. Splitting: split-h (horizontal split) and split-v (vertical split) subdivide the active container using responsive Flexbox rules, instantly creating a new child terminal.
  3. Navigation: Operators switch active panes using focus <id>, the panes selector, or keyboard shortcuts (Ctrl+B followed by arrow keys). When a pane activates, FileSystemManager instantly synchronizes its working directory to the kernel.
  4. Zoom: split -z toggles zoom mode, temporarily expanding the active pane to 100% viewport dimensions without destroying neighboring splits.
Why It Works

Provides the multitasking power of tmux or screen within a browser environment, allowing operators to monitor logs in one pane while editing code or running tests in another.

24. The TUI Window Manager

Files: resources/scripts/window_manager.js, resources/core/commands/wm.py, window.py

What It Does

Evolves full-screen overlay applications (Editor, Paint, Adventure, Process Viewer) into a desktop-grade windowing system supporting floating, tiled, docked, minimized, and restored states.

How It Works
  1. Window Records: WindowManager manages application viewports in a central registry. Windows feature titlebars, minimize/maximize buttons, and close controls.
  2. Interactive Manipulation: Windows can be dragged across the screen or resized from their edges using mouse events, maintaining z-index focus layering.
  3. Dock Bar: Minimized windows collapse cleanly into the bottom dock bar (#window-dock) and can be restored with a click.
  4. Command Control: Operators can manipulate windows programmatically via the wm command (wm list, wm tile, wm float <id>, wm dock <id>).
Why It Works

Prevents graphical applications from hijacking the entire terminal. Users can keep documentation open in a floating window beside their active coding terminal.

25. Host Bridges: System Clipboard & Drag-and-Drop

Files: resources/scripts/clipboard_manager.js, resources/scripts/status_bar_manager.js, clip.py, pbcopy.py, pbpaste.py

What It Does

Bridges the virtual OS with the host operating system, providing seamless system clipboard synchronization, drag-and-drop file ingestion, and a persistent top status bar.

How It Works
  1. Clipboard Sync: pbcopy and clip --copy capture standard input and copy it directly to the host machine's clipboard via navigator.clipboard.writeText(). pbpaste retrieves host text into the virtual shell.
  2. Drag-and-Drop File Import: Dragging files from the host desktop into the browser terminal triggers an automatic drop handler in terminal_ui.js, reading file contents and writing them directly into the current working directory in the VFS.
  3. Persistent Status Bar: StatusBarManager renders a persistent top panel displaying active background PIDs, mesh peer counts, audio mute status, and agent telemetry.
Why It Works

Eliminates the friction of sandboxed browser environments, allowing seamless text and file flow between your host workstation and FractalOS.

26. Physical IoT & GPIO Sensor Automation

Files: resources/core/commands/gpio.py, resources/scripts/host_api.js

What It Does

Enables direct interaction with physical hardware pins, sensors, buttons, and actuators when running on Raspberry Pi or ARM64 boards in Bare-Metal Appliance Mode.

How It Works
  1. Hardware Control:
    • gpio mode <pin> <in|out>: Configures GPIO pin direction.
    • gpio write <pin> <0|1>: Sets pin output voltage high or low.
    • gpio read <pin>: Queries current logic state (returns 0 or 1).
  2. Sensor Monitor Daemon: gpio monitor <pin> --trigger <change|rising|falling> --action "<cmd>" launches a background interrupt monitor that executes arbitrary shell commands when physical sensors change state.
  3. Mesh Broadcast: Adding --mesh broadcasts the hardware event across the peer-to-peer network, allowing a button press on one board to trigger actions on another.
  4. Browser Simulation Fallback: When running in standard browser mode without physical hardware, gpio simulate <pin> <val> allows developers to test IoT pipelines virtually.
Why It Works

Unlocks physical computing directly from the terminal shell. Ambient AI agents can inspect environmental conditions and actuate real-world devices.


Book VI: Package Ecosystem & Sandboxing

27. Package Architecture (.fpkg)

Files: resources/core/commands/pkg.py, /etc/pkg_manifest.json, /var/pkg/repo/

What It Does

The native package manager for FractalOS (pkg). Provides end-to-end tooling to scaffold, validate, build, install, audit, and distribute modular software packages.

How It Works
  1. Package Anatomy: Packages are distributed as .fpkg archives containing a JSON manifest, documentation (help, man), dependency lists, and the executable Python command module.
  2. Scaffolding & Validation:
    • pkg init <name>: Generates a standardized package template.
    • pkg validate <name>: Verifies required functions (run, man, help, define_flags) and metadata structure.
    • pkg pack <name>: Compiles the source into a distributable .fpkg bundle.
  3. Installation & Manifest: pkg install <package> extracts the command into /etc/packages/commands/<name>.py and records version, dependencies, and SHA256 checksums in /etc/pkg_manifest.json.
Why It Works

Allows the operating system to grow organically through third-party contributions without touching the immutable kernel codebase.

28. Cryptographic Audits & Permission Sandboxing

Files: resources/core/commands/pkg.py, resources/core/executor.py (Decision D-044)

What It Does

Protects the operating system from malicious or corrupted third-party software through mandatory SHA256 integrity verification, permission scoping, and static AST security audits.

How It Works
  1. Runtime Integrity Verification (pkg verify): Before loading a user package into memory, executor.py computes the SHA256 hash of the on-disk file and compares it against the record in /etc/pkg_manifest.json. If the file has been altered or corrupted, execution is blocked with a SecurityError.
  2. Permission Scopes: Packages declare required privileges (root, hardware, fs:system). Elevated packages require explicit operator approval at installation time via --trust (-t) or --force.
  3. Static Code Audit (pkg audit): Uses Python's standard ast module to inspect package source code without executing it, detecting dangerous patterns such as:
    • Dynamic code execution (eval, exec, __import__).
    • Host process execution attempts (os.system, subprocess).
    • Access to sensitive system paths (/etc/sudoers, /var/log/audit.log).
    Assigns a formal threat score: SAFE, LOW RISK, MODERATE RISK, or HIGH RISK.
Why It Works

Browser-based operating systems face unique supply-chain risks. Static analysis and cryptographic hash pinning guarantee that community packages remain trustworthy.

29. Registry, Community Classics & Wheel Loading

Files: resources/core/standard_packages.py, resources/bridge.js

What It Does

Provides an out-of-the-box standard library of classic Unix utilities, dynamic WebAssembly wheel loading without rebooting, and peer-to-peer package broadcasting.

How It Works
  1. Standard Library Classics: Pre-packaged community favorites including fortune, cowsay, cal, and banner can be installed instantly with pkg install cowsay. They fully support ANSI styling and piped composition (e.g. fortune | cowsay).
  2. Dynamic Wheel Loading: When a package requires external Python libraries, pkg_manifest.json lists required WebAssembly wheels. Pyodide loads these dynamically at startup via loadPackage().
  3. Mesh Package Publishing: pkg publish <pkg> --mesh broadcasts new package definitions across connected nodes, allowing peers to discover and install community packages directly over WebRTC.
Why It Works

Creates a decentralized software distribution network that thrives completely independent of centralized cloud package registries.


Book VII: The Command Codex

30. Anatomy of a FractalOS Command

What It Does

Every command in FractalOS is a modular Python file residing in resources/core/commands/<name>.py. It adheres to a strict, standardized interface audited automatically by tests/structure.js.

How It Works

A compliant command module implements:

def run(args: list, flags: dict, user_context: dict, stdin: str = None, **kwargs) -> dict:
    """Core execution routine (can be synchronous or async coroutine)."""
    # 1. Validation & logic
    # 2. Returns output string: {"success": True, "output": "..."}
    #    OR declarative effect: {"effect": "play_sound", "notes": [...]}

def man(args=None, flags=None, user_context=None, **kwargs) -> str:
    """Returns standard formatted manual page text (NAME, SYNOPSIS, DESCRIPTION, OPTIONS)."""

def help(args=None, flags=None, user_context=None, **kwargs) -> str:
    """Returns concise usage and synopsis text."""

def define_flags() -> dict:
    """(Optional) Declares flag parsing rules, aliases, and value requirements."""
Why It Works

Consistent function signatures allow the shell executor to dynamically load modules via Python's standard importlib, inject execution context seamlessly, and route return values without custom wrappers.

📖 Complete 151-Command Reference Manual

All 151 commands are documented in exhaustive detail in our companion manual, featuring full What It Does, How It Works, and Why It Works breakdowns:

Open The Complete 151-Command Codex →

31. Master Categorized Command Matrix

Quick directory of all 151 native commands organized across 18 functional categories. Click any command to view its full reference in the Codex:

Category Commands
File & Directory Management (17) ls, cd, mkdir, rmdir, touch, cp, mv, rename, rm, find, tree, du, df, ln, mount, clearfs, binder
Text Processing & Pipeline Filters (20) cat, head, tail, grep, sed, awk, cut, tr, sort, uniq, wc, nl, shuf, csplit, xargs, diff, patch, comm, more, less
Living Shell & Kinetic AI (7) samwise, forge, planner, storyboard, remix, chidi, character
Distributed Mesh & Networking (11) peers, attach, detach, wall, talk, mesh_cp, mesh_agent, swarm, scp, nc, netstat
Terminal Multiplexing & Window Control (9) split_h, split_v, split, panes, close_pane, focus, wm, window, status
System Identity, Security & Access (16) login, logout, su, sudo, visudo, whoami, who, useradd, removeuser, passwd, usermod, groupadd, groupdel, groups, listusers, committee
File Permissions & Metadata (3) chmod, chown, chgrp
Shell Execution & Environment (13) run, check_fail, echo, printf, true, delay, agenda, alias, unalias, history, set, unset, clear
Process Management & Job Control (8) ps, top, kill, bg, fg, jobs, uptime, date
Data Integrity, Cryptography & Compression (7) base64, cksum, ocrypt, xor, zip, unzip, fsck
Math & Calculation (2) bc, expr
Versioning & System State (6) story, sync, backup, restore, reset, reboot
System Communication & Ambiance (10) bulletin, post_message, read_messages, notify, clip, pbcopy, pbpaste, theme, cinematic, ritual
Audio & Screen Capture (3) play, beep, printscreen
Host I/O & File Transfer (2) upload, export
Applications, Runtimes & Hardware (8) edit, paint, adventure, basic, log, python, pkg, gpio
TUI Games & Entertainment (6) c4, ttt, netgame, roll, score, cast
System Discovery & Navigation (3) help, man, pwd

Book VIII: Graphical Application Suites

Beyond the terminal prompt, FractalOS provides a complete suite of graphical and text-mode applications. These are not third-party web apps embedded in iframes; they are deeply integrated system programs that extend the standard application base, interact with the kernel via system calls, and can be arranged into floating or docked viewports via the TUI Window Manager.

32. Application Lifecycle Architecture

Files: resources/scripts/apps/app.js, apps.css, ui_components.js, window_manager.js

What It Does

Establishes the common contract and lifecycle for all graphical applications in FractalOS, guaranteeing consistent window geometry, focus handling, keyboard event routing, and teardown cleanup.

How It Works
  1. The App Base Class: Every application extends the abstract App class in app.js. Subclasses must implement enter(container, options), exit(), and handleKeyDown(event).
  2. Standard Chrome Factory: UIComponents.createAppWindow() constructs standard window chrome (header, title, minimize/maximize controls, main content viewport, and footer status bar) styled via apps.css.
  3. Window Manager Coordination: The Window Manager (WindowManager) tracks active instances, handling mouse dragging, edge resizing, dock bar minimization, and z-index elevation.
  4. Graceful Exit: When an app exits, exit() unbinds all DOM event listeners, disposes of interval timers, releases Web Audio or canvas buffers, and restores terminal keyboard focus.
Why It Works

Strict encapsulation prevents visual or memory leaks. Developers building new tools inherit standard window management and keyboard handling automatically.

33. FractalOS Editor (edit)

Files: resources/scripts/apps/editor/editor_manager.js, editor_ui.js, editor.css

What It Does

A full-screen, context-aware code and document editor supporting syntax highlighting, real-time Markdown rendering, live sandboxed HTML iframe preview, and undo/redo history.

How It Works
  1. Mode Detection: Inspects file extensions (.md, .html, .js, .py, .sh) to enable specialized toolbars and preview viewports.
  2. Markdown & HTML Preview: Markdown is parsed via marked.min.js and sanitized with DOMPurify. HTML files are rendered into an isolated, sandboxed <iframe> with live reloading.
  3. State Stack: Tracks changes in debounced undoStack and redoStack arrays, tracking dirty buffer states and prompting before closing unsaved documents.
  4. VFS Synchronization: Saving writes the buffer directly through FileSystemManager.createOrUpdateFile(), committing changes to persistent storage.
Why It Works

Separates editing state (manager) from DOM presentation (view). The live HTML sandbox allows in-OS web development with zero external dependencies.

34. FractalOS Paint (paint)

Files: resources/scripts/apps/paint/paint_manager.js, paint_ui.js, paint.css

What It Does

A retro character-based graphic studio for drawing ANSI art and terminal UI mockups on an 80×24 character grid, complete with geometric shapes, flood fill, and custom color palettes.

How It Works
  1. Grid Data Model: Maintains an 80×24 two-dimensional array of cell objects, each storing a character, foreground color, and background color.
  2. Drawing Algorithms: Implements Bresenham's line algorithm for lines and rectangles, and a queue-based breadth-first search (BFS) for flood-filling contiguous regions.
  3. Dual-Canvas Preview: A transparent overlay canvas previews active brush movements and geometry without altering underlying canvas data until mouse release.
  4. File Format: Serializes artwork into .oopic JSON files or exports plain ANSI text strings for terminal viewing.
Why It Works

Provides native visual design capabilities inside an operating system that lives in the browser, perfect for designing terminal splash screens and game assets.

35. Adventure Engine & World Creator (adventure)

Files: resources/scripts/apps/adventure/adventure_manager.js, adventure_create.js, adventure_ui.js

What It Does

A dual-mode interactive fiction studio. In play mode, it runs text adventure games like the built-in "The Architect's Apprentice". With --create, it launches a dedicated authoring shell for building custom interactive worlds.

How It Works
  1. Natural Language Parser: Understands multi-word verb-noun constructions (e.g. "unlock the brass gate with the silver key"), pronouns ("take it"), and contextual disambiguation.
  2. World State Machine: Tracks player inventory, location rooms, locked exits, item properties, and dynamic scoring rules.
  3. Creation Shell (--create): A dedicated sub-shell allowing authors to create rooms, link cardinal directions (link "Crypt" north "Hall"), populate items, and save the universe into a portable JSON manifest.
Why It Works

Decouples storytelling data from engine execution. Anyone can craft and share rich interactive fiction without writing JavaScript or Python code.

36. Fractal BASIC IDE & System Interop (basic)

Files: resources/scripts/apps/basic/basic_manager.js, basic_interp.js, basic_ui.js, basic.css

What It Does

A complete, line-numbered BASIC programming environment featuring classic commands (PRINT, INPUT, GOTO, GOSUB, FOR/NEXT) and bridge functions (SYS_) to interact with the underlying OS and network.

How It Works
  1. Line Buffer & Execution: Stores program lines ordered by integer line numbers. An interpreter loop advances the program counter, evaluating expressions and loop stacks.
  2. System Call Bridge (SYS_): Special functions connect BASIC programs to the operating system:
    • SYS_CMD("ls -la"): Executes a shell command and captures output.
    • SYS_READ("file.txt") & SYS_WRITE("file.txt", data$): Direct VFS file I/O.
    • SYS_NET_SEND(peer$, msg$): Transmits messages over the WebRTC mesh network!
  3. Vintage Aesthetic: Rendered with a classic Commodore/C64-style deep blue screen and cyan monospace typography.
Why It Works

Elevates vintage programming into a legitimate scripting language for FractalOS automation, making computational learning accessible and nostalgic.

37. Captain's Log (log)

Files: resources/scripts/apps/log/log_manager.js, log_ui.js, log.css

What It Does

A personal journaling and note-taking environment. Supports instant command-line note appending or an interactive two-pane browsing and editing interface.

How It Works
  1. File Organization: Entries are stored as individual Markdown files in ~/.journal/ named by ISO timestamps (YYYY-MM-DDTHH-MM-SS.md).
  2. CLI Quick Add: log "Fixed kernel memory leak" creates and timestamps the entry without opening the GUI.
  3. Interactive Viewer: Running bare log opens a two-pane viewer: reverse-chronological list on the left, full Markdown editor on the right with search filtering.
Why It Works

Plain text files in standard directories preserve user data sovereignty. Your notes are standard files readable by cat, grep, or exportable at any time.

38. Chidi AI Document Analyst (chidi)

Files: resources/scripts/apps/chidi/chidi_manager.js, chidi_ui.js, chidi.css

What It Does

An AI research assistant specialized in deep document synthesis. Creates a "walled garden" around a collection of text files, allowing the user to query, summarize, and cross-reference them without hallucinations.

How It Works
  1. Input Ingestion: Ingests target files from directory paths or piped lists (e.g. find . -name "*.md" | chidi).
  2. Context Assembly: Concatenates the contents of all selected documents into an explicit, bounded context block.
  3. Strict Prompt Guidance: The AI is constrained by system prompts to answer exclusively using facts from the provided text, citing file sources for every claim.
Why It Works

Eliminates knowledge drift. Perfect for analyzing codebases, reading legal contracts, or studying technical documentation inside the virtual OS.

39. Samwise Chat (samwise -c)

Files: resources/scripts/apps/samwise_chat/samwise_chat_manager.js, samwise_chat_ui.js, samwise_chat.css

What It Does

A dedicated floating chat application providing an ongoing, conversational copilot experience with Samwise. Features message history, model selection, and clickable "Run Command" buttons in AI responses.

How It Works
  1. Conversational Loop: Communicates with the kernel's ai_manager via JSON payloads transmitted over standard input, preventing shell escaping exploits.
  2. Interactive Code Blocks: When Samwise proposes shell commands, the UI automatically appends an inline [Run] button that dispatches the command directly to the terminal when clicked.
  3. Live Provider Switching: Allows switching between local Ollama models and cloud Gemini endpoints on the fly.
Why It Works

Bridges natural language conversation with active terminal execution, allowing operators to chat fluidly while selectively executing recommended actions.

40. Process Viewer (top)

Files: resources/scripts/apps/top/top_manager.js, top_ui.js, top.css

What It Does

A real-time process monitoring dashboard displaying active foreground and background jobs, Process IDs (PIDs), execution statuses, and running command lines.

How It Works
  1. Polling Loop: Runs a 1,000 ms timer interval querying CommandExecutor.getActiveJobs().
  2. Efficient Rendering: Uses a DocumentFragment to batch DOM updates, preventing browser reflow lag. Table headers use position: sticky for scrolling long job lists.
  3. Dual-Mode Execution: In interactive terminal mode, it launches the graphical dashboard. When run in non-interactive background scripts (top &), it runs headlessly for system simulation.
Why It Works

Delivers standard Unix job observability, ensuring operators can monitor long-running background tasks and terminate runaway jobs cleanly.

41. Onboarding & First-Boot Wizard (onboarding)

Files: resources/scripts/apps/onboarding/onboarding_manager.js, onboarding_ui.js, onboarding.css

What It Does

The initial setup experience presented to a user when booting FractalOS for the first time on a fresh storage volume.

How It Works
  1. Account Creation: Collects operator username, user password, and the root administrator password.
  2. Cryptographic Provisioning: Calls users.first_time_setup() in the kernel, deriving PBKDF2 hashes and establishing home directories and sudoers records.
  3. Mesh Node Configuration: Offers an option to automatically start the background WebSocket signaling server or mesh discovery upon boot.
Why It Works

Ensures every instance boots with properly configured permissions and salted credentials before any untrusted scripts can execute.

42. Multiplayer & Mesh Games (c4, netgame, ttt)

Files: resources/core/commands/c4.py, netgame.py, ttt.py, resources/scripts/apps/netgame/

What It Does

Interactive, turn-based multiplayer games playable directly across the WebRTC peer-to-peer mesh network, including Connect 4 (c4) and Tic-Tac-Toe (ttt).

How It Works
  1. P2P Handshake: A player hosts a game session; peer nodes discover the game via netgame lobby broadcasts over RTCDataChannel.
  2. State Synchronization: Turn moves (e.g. dropping a chip in column 4) are transmitted as serialized JSON game packets between peer nodes.
  3. TUI Board Drawing: Renders game boards with ANSI color codes and clean terminal borders.
Why It Works

Demonstrates the versatility of the distributed mesh architecture: high-speed, zero-cloud peer-to-peer communication powering real-time interactive entertainment.


Book IX: The Proving Ground (Quality Assurance & Test Engineering)

A complex operating system is only as dependable as its verification suite. FractalOS incorporates a multi-tiered testing harness covering structural integrity, headless browser boots, in-OS shell execution, and autonomous LLM agent grading.

The Proving Ground Philosophy: "Verified Means Observed"

Code that reads correctly is not considered done until it has been observed executing in the live environment. No feature is merged without passing structural validation, the headless smoke test, and the in-OS diagnostic suite.

44. Structure & Manifest Checks (tests/structure.js)

What It Does

A lightning-fast, zero-browser Node.js test that guarantees disk files, manifests, and registration load lists never drift.

How It Works
  1. Verifies that every Python file under resources/core/ is cataloged in core/manifest.json.
  2. Audits that every command in commands/*.py exports both a run() and man() function.
  3. Checks that every JavaScript script and stylesheet is registered in resources/scripts/asset_manifest.js in proper load order.
Why It Works

Catches the silent "ghost limb" bug (Decision D-010): in a WebAssembly OS without npm bundlers, forgetting to register a Python or JS file means it never loads into Pyodide. This test catches the omission in under one second.

45. Headless Browser Smoke Testing (tests/smoke.js)

What It Does

An automated headless Chromium test (driven by Playwright) that launches the operating system against a live HTTP server, verifies kernel boot, exercises cryptographic password verification, and runs foundational shell commands.

How It Works
  1. Boots http://127.0.0.1:8000/index.html in a clean, isolated browser profile.
  2. Waits for FractalOS_Kernel.isReady to resolve.
  3. Validates Pyodide versions and executes PBKDF2 key derivation.
  4. Runs first-time setup, testing correct and incorrect password verification via system calls.
  5. Runs 50+ assertions on shell commands (echo, date, whoami, ls, mkdir permissions denials, and error recovery).
Why It Works

Proves that the entire hybrid stack (Pyodide WebAssembly, DOM stage manager, syscall bridge, and storage HAL) functions cohesively in a real browser engine.

46. The 1,400-Line In-OS Diagnostic Gauntlet (extras/diag.sh & tests/diag.js)

What It Does

A massive, comprehensive shell test script written in FractalOS's own shell syntax that runs inside the virtual operating system as root, systematically testing over 40 distinct phases of OS functionality.

How It Works
  1. Injected into the virtual filesystem via tests/diag.js.
  2. Uses the assertion utility check_fail to verify both expected successes and expected security failures (e.g. ensuring regular users cannot read root vault files).
  3. Tests file manipulation, symlink traversal, octal permissions, pipes, text utilities (grep, sed, awk, csplit), job signals, archives, and environment scopes.
  4. Cleans up all temporary users, groups, and files, ending with a celebratory completion banner.
Why It Works

Validates the operating system against itself. If shell parsing, pipes, or permission checks deviate from POSIX behavior, diag.sh catches the regression immediately.

47. Universe Generator (extras/inflate.sh)

What It Does

A deterministic demo-world generator that rapidly populates an empty filesystem with complex directory hierarchies, sample documents, adventure worlds, and intentional edge cases.

How It Works

Executes shell commands creating user directories, project archives, journal logs, sample code, and deliberate filesystem anomalies (dangling symlinks and orphaned nodes) to challenge diagnostics like fsck.

Why It Works

Ensures developers and automated test harnesses can spin up an identical, reproducible baseline environment across testing sessions.

48. Autonomous Agent Test Harness & Graders

Files: tests/agent.js, tests/fake_ollama.py, tests/agent_grading.js, tests/agent_unit.py

What It Does

A headless test suite that evaluates the samwise agent and BoneAmanita driver through real-world multi-step tasks, grading outcomes directly on filesystem facts.

How It Works
  1. Headless Task Execution: Runs Samwise through tasks (e.g., navigating directories, generating Python scripts, computing Fibonacci numbers, and safely handling deletions).
  2. Stand-In & Real Models: Can be run with fake_ollama.py for instant offline plumbing tests, or connected to real local models (gemma4:12b, llama3.1:8b).
  3. Objective Grading: tests/agent_grading.js inspects VFS node creation, file contents, and exit statuses rather than relying on LLM self-evaluation.
  4. Transcript Logging: Complete multi-turn transcripts are written to tests/out/agent-transcript.md for human inspection.
Why It Works

Guarantees agent reliability. We do not guess whether prompt adjustments work; we prove that models pass all safety brakes and accomplish their goals across deterministic grading checks.

49. In-OS Python Test Suite (tests/test_executor.py)

What It Does

A dedicated test script designed to execute inside FractalOS via the in-OS python command, verifying that real Python code can import and drive the kernel.

How It Works

Copied into the virtual filesystem and executed with python test_executor.py. It imports kernel, tests VFS calls, executes inline scripts, and verifies standard stream bindings.

Why It Works

Proves that Python within the OS is genuine CPython 3.14 with complete kernel integration, not a mock syntax highlighter.


Book X: Runtime Dependencies & Technical Foundations

10.1 Vendored Dependencies

FractalOS strictly avoids npm package installation and remote runtime CDNs. All required third-party libraries are audited, trimmed, and vendored directly into resources/dep/:

Library Version Path Purpose
Pyodide 314.0.7 (Python 3.14.2) resources/dep/pyodide/ WebAssembly CPython runtime powering the system kernel and real Python execution.
Cryptography 43.0.1 (Wasm Wheel) resources/dep/pyodide/cryptography* Provides PBKDF2-HMAC-SHA256 password hashing and secure token generation.
Tone.js r14.7.77 resources/dep/Tone.js Web Audio framework providing polyphonic synthesis, tone playback, and timing.
marked.js v4.3.0 resources/dep/marked.min.js Fast, standard-compliant Markdown parser for Editor, Chidi, and terminal logs.
DOMPurify v3.0.5 resources/dep/purify.min.js Sanitizes rendered HTML, mitigating Cross-Site Scripting (XSS) vectors.
JSZip v3.10.1 resources/dep/jszip.min.js Handles reading and extracting compressed archives and MusicXML files.
Neutralinojs v6.2.0 resources/neutralino.js Lightweight native webview bridge enabling Portable Desktop mode.

Appendix: Critical System Paths & Configurations

The virtual file system reserves standardized paths for system state and configuration:

Path Owner / Mode Purpose
/etc/ai.conf root:root 0o644 Defines default AI provider (ollama vs gemini), model names, endpoints, and timeouts.
/etc/sudoers root:root 0o440 Specifies privilege escalation rules for users and groups; edited safely via visudo.
/etc/passwd root:root 0o644 Stores registered usernames, user IDs, and primary group affiliations.
/etc/pkg_manifest.json root:root 0o644 Catalog of installed third-party packages, permission scopes, and cryptographic SHA256 hashes.
/var/log/audit.log root:root 0o600 Immutable chronological audit log capturing authentication, sudo, and administrative operations.
/var/log/bulletin.md root:root 0o666 System-wide public bulletin board accessible via the bulletin utility.
.story/ User-owned 0o700 Internal snapshot repository storing atomic file versions and rollback trees.