🎲 Rubik — Autonomous AI Coding Agent & REPL Harness
English | Türkçe
A next-generation autonomous pair-programming and REPL harness written in pure Ruby, built on the Spatiotemporal Composability & Self-Evolving Runtime architecture.
👋 What is Rubik?
Rubik is a terminal-native autonomous coding agent and interactive REPL in pure Ruby. A maestro agent orchestrates specialized subagents (research / coder / self) over a 34-tool belt: file edits stage in a virtual in-memory buffer (!diff → !apply, with configurable model authority and auto-apply policies), managed runtime side effects register LIFO inverses to support dynamic reloads and teardowns without process restarts, and failing services can be diagnosed and repaired live. It supports Linux, macOS, and Windows across a bounded CI matrix, connects to OpenAI-compatible endpoints, Anthropic, or local Ollama, and the runtime is embeddable from Ruby with require "rubik".
🚀 Quick Start
From the gem
Requires Ruby 3.4+:
CI tests Linux on Ruby 3.4 (minimum) and 4.0, and macOS and Windows on
Ruby 4.0. Each job installs dependencies, runs the full unit/integration suite,
and builds, installs and smokes the gem (rubik --version and require "rubik").
See CI runs
for results on a specific commit; platform artifacts contain environment details,
installation/smoke logs, test counts and skip reasons. Other Ruby/OS combinations
are not covered by this bounded matrix.
gem install rubikThe installer puts the rubik launcher into RubyGems' bin directory (already on your PATH), so you can start it from any project directory:
rubikor with Bundler:
gem "rubik"Platform notes
| Platform | Install experience |
|---|---|
| 🐧 Linux / 🍎 macOS |
gem install rubik — dependencies ship prebuilt. |
| 🪟 Windows |
tree_sitter_language_pack has no Windows prebuilt and compiles from source: install Rust with the GNU toolchain and export RUST_TARGET=x86_64-pc-windows-gnu before installing. The exact, working recipe is .github/workflows/ci.yml. |
From source
Prerequisites
-
Ruby: 3.4.0 or later (
ruby -v)-
Linux / macOS: Via the system package manager,
rbenv,rvm, orasdf. -
Windows: Scoop (
scoop install ruby) or RubyInstaller with DevKit.
-
Linux / macOS: Via the system package manager,
-
Git: Git 2.30+ (
git -v) -
LLM Provider: Local Ollama (
ollama run qwen2.5-coder:7b) or a DeepSeek, OpenRouter, Anthropic, or OpenAI API key.
Clone the project, install the dependencies, and start the REPL:
git clone https://github.com/ozgurulukir/rubik.git
cd rubik
bundle install🐧 Linux & 🍎 macOS (POSIX)
# Proje dizininden doğrudan çalıştırma
./bin/rubik
# Veya sistemde global kullanmak için ~/.local/bin dizinine bağlayın:
ln -sf $(pwd)/bin/rubik ~/.local/bin/rubik
rubikNote
The gem and a clone can coexist. On POSIX the symlink always runs your clone: bin/rubik resolves lib/ from its own real path, so a git pull is live on the very next launch — even while the rubik gem stays installed. The gem-installed rubik keeps serving the last released version until you run gem update rubik. On Windows, whichever bin folder comes first in PATH wins — where.exe rubik shows the winner.
🪟 Windows (PowerShell / Command Prompt)
Rubik ships with built-in .cmd, .bat, and .ps1 wrappers for Windows:
# PowerShell üzerinden çalıştırma
.\bin\rubik.ps1
# veya Command Prompt / Terminal üzerinden
.\bin\rubik.cmd
# veya Ruby üzerinden doğrudan
ruby bin\rubikTip
The Global rubik Command on Windows:
By adding Rubik's bin folder to your environment variables (User PATH), you can launch it from any terminal simply by typing rubik:
[Environment]::SetEnvironmentVariable("PATH", "$env:PATH;$PWD\bin", "User")Adding a Provider & Model
You can connect any OpenAI-compatible provider in a single line:
# REPL içerisinden sağlayıcı ekleme:
rubik > !provider add deepseek openai_compatible https://api.deepseek.com/v1/chat/completions --key=sk-... --model=deepseek-coder --context=64000
rubik > !model deepseek/deepseek-coderAnthropic talks over its native Messages API (not an OpenAI shim): the anthropic provider is registered out of the box — set ANTHROPIC_API_KEY and pick a model:
rubik > !model anthropic/claude-sonnet-5-5First Session Example
╭── rubik ─────────────────────────────────────────────────╮
│ 🎲 Rubik v0.1.0 │
│ deepseek/deepseek-coder │
│ my_project · main │
│ !help komutlar · ctrl+c kes · !config ayarlar │
╰──────────────────────────────────────────────────────────╯
deepseek/deepseek-coder · ctx 3% · temiz · sandbox kapalı
rubik (my_project) [main] > !status
Project: my_project (main)
Default Model: deepseek/deepseek-coder
Dirty buffer: false
rubik (my_project) [main] > Kullanıcı kayıt formunu doğrulayan bir helper fonksiyonu yaz
✻ Düşünüyor… · 1s (ctrl+c: kes)
⏺ write_file — lib/validator.rb
⎿ 3 lines · 18ms
[Rubik] In-memory buffer updated. Type `!diff` to view, `!apply` to save.
rubik (my_project) [main] [DIRTY: 1 ✎] > !diff
+ def validate_user(params)
+ raise "Invalid email" unless params[:email]&.include?("@")
+ end
rubik (my_project) [main] [DIRTY: 1 ✎] > !test
Applied 1 file(s) before test. All 12 tests passed!
Tip
Safe Execution (Tree-Sitter AST) & Pluggable OS Isolation (Bubblewrap / Container):
Before running any command, Rubik keeps the Security::Guard shield active (Safe Execution), which detects dangerous commands, pipeline poisoning, and directory escapes ahead of time via Tree-Sitter syntax-tree (AST) analysis for Bash and PowerShell plus a database of 172 CLI YAML rules. The command gate fails closed on unrecognized syntax or classifier errors. Hardware-enforced OS isolation is optional and disabled by default (sandbox.enabled: false); enabling it on Linux requires Bubblewrap (bwrap) or OCI containers (docker/podman):
!sandbox on # Enables hardware/container OS isolation on Linux
!config set sandbox.allow_network true -p # Grants outbound network access within the sandbox⚡ Key Features
- 🌐 Cross-Platform Support (Linux, macOS, Windows): Supports Windows 11 / Windows Server environments (PowerShell, Command Prompt, Windows Terminal) alongside POSIX systems (Linux, macOS). Uses pure-Ruby binary resolution, NTFS case-insensitivity handling, RFC 8089 LSP URIs, and native Windows CLI (
.cmd,.bat,.ps1) wrappers. Verified against CI's bounded matrix (Windows gem installation compilestree_sitter_language_packfrom source using the Rust GNU toolchain; see .github/workflows/ci.yml). - 🛡️ In-Memory Virtual Buffer & Staged Writes: When the model writes code, file changes stage in an in-memory virtual buffer before touching disk. You can inspect changes with
!diff, apply them with!apply, or discard unapplied buffer edits with!undo.-
Authority & Review Gates: Staging alone does not enforce manual human review. By default,
buffer.auto_apply: manualstages changes, butbuffer.model_can_apply: trueallows the model to flush its own edits via theapply_buffertool. To guarantee human operator review before any disk modification, setbuffer.model_can_apply: falsealongsidebuffer.auto_apply: manual. Whenbuffer.auto_applyis set toon_test,on_finish, oralways, the runtime automatically flushes dirty buffer edits to disk at trigger boundaries. -
Atomic File Writes vs Multi-File Transactions: Each individual file write is atomic (written to a temporary file and atomically renamed/replaced), but applying changes across multiple files is not an all-or-nothing multi-file transaction. If an error occurs midway (e.g. permission error or containment block), previously written files remain on disk while failed and pending files stay dirty in the buffer with a structured partial report (
applied,failed,pending,conflicts).
-
Authority & Review Gates: Staging alone does not enforce manual human review. By default,
- 🏢 Multi-Workspace & Extra Root Directories: In monorepo or sibling-package layouts (
../shared-kernel,../proto), you can safely attach external root directories (!workspace add) and include them in the buffer and the AST index in read-only or writable (--rw) mode. - ⚡ Live LSP Compiler Diagnostics: When configured language server binaries (
rust-analyzer,gopls,ruff,typescript-language-server,typeprof, etc.) are installed on the hostPATH, Rubik connects over stdio JSON-RPC to feed compiler diagnostics back to the agent after edits. Language servers are external dependencies; if a server binary is missing, unconfigured, or fails the handshake, Rubik falls back to syntax and AST analysis without blocking the session (see LSP.md). - 🌳 Multilingual Tree-Sitter & Prism Hybrid AST Engine: Employs built-in Prism for Ruby and Tree-Sitter grammars for Python, Go, Rust, TypeScript, TSX, JavaScript, C, C++, and Zig to avoid string/comment lexical confusion during symbol parsing. If Tree-Sitter grammars or C extensions are unavailable or encounter parse errors, the engine falls back to legacy regex extractors (which have known structural limits with complex or nested code). The symbol and call graph (
!symbols,!outline,!refs) scans asynchronously in the background and leverages an on-disk cache (.rubik/cache/ast_index.json) to minimize cold-start indexing overhead across restarts; cold and warm timings for a 150-file synthetic Ruby fixture are recorded in _report/runtime-capacity-validation-2026-10-16.md. - 🤖 Dynamic LLM Providers & Multi-Role Routing: Light/heavy task routing with support for all OpenAI-compatible endpoints (DeepSeek, Groq, OpenRouter, Mistral, vLLM), Anthropic Claude, OpenAI, and local Ollama.
- 🧬 Spatiotemporal Composability & Self-Evolving Runtime: The model can synthesize new REPL commands (
synthesize_command) or built-in tools (synthesize_tool) at runtime; managed runtime effects registered through the context are unwound with LIFO inverses ($\Omega$). - 🩹 Self-Healing Runtime (Service Repair Plane): Runtime components never require a process restart.
inspect_runtimeexposes the live fiber/coeffect/service state;repair_runtime_servicediagnoses a failing component (LSP server, test runner, linter, or shell command), probes replacement commands with pre-flight verification in an isolated sub-context, and re-provides the repaired service — session state, caches, and conversations stay intact.provide_serviceregisters new services live. Repair probes are bounded and disposable; failed promotion or persistence restores session state. Successfully saved operator configuration survives lifecycle cleanup. See runtime repair for probe and rollback contracts. - 📋 Structured Goal Ledger (SKILL.state adaptation): the
!goalloop keeps a rev-guarded ΔΣ ledger (objective, tasks, findings, decisions, open questions, environment notes) instead of trusting lossy conversation memory. The maestro patches it with the root-onlyupdate_goal_ledgertool (classified syntax/schema/conflict feedback, bounded retries), the current Σ is pinned through every compaction tier and re-injected each step, every revision is appended to storage (goal-ledgerref), declarativeverifyspecs are re-checked at step boundaries (a failed check flips the task tostale— the world-drift signal), and banked tool results compact into per-row<absorbed_into_ledger>tombstones. Default ON (goal.ledger.*, operator-only; opt-out per key). - 🧹 Context Pruner (Semi-Deterministic Window Cleanup): Long sessions accumulate stale exploration in the maestro's conversation window. A Vakanüvis-style two-plane pruner cleans it: a silent LLM subagent proposes a keep/drop/summarize plan, and the harness validates it deterministically (goal pinning, tool-use pairing, head/tail preservation bands, token budget) and applies it atomically at the next turn boundary — never mid-turn. It auto-fires at 60% of the input ceiling (before the blind drop-oldest trimmer would) or on demand via the
prune_contexttool and!prune. Default ON since 2026-10-10 (subagents.pruner.*, operator-only; opt-outenabled: false); the deterministic compaction stack always remains the safety net. - 🔌 Drop-in Plugin System (User Plugins): Drop-in
.rbfiles or package directories under~/.rubik/plugins(global) or.rubik/plugins(project) load dynamically (!plugin add,!plugin reload). Integrity is gated by SHA-256 digests in.manifest.json(full package tree for directory plugins). Plugins execute arbitrary Ruby in the host process; manifests protect against untracked or modified files, but do not sandbox plugin runtime behavior. Foreign repositories without a manifest require explicit review or operator consent (RUBIK_BOOTSTRAP_OVERLAYS=1/RUBIK_TRUST_OVERLAYS=1). See PLUGINS.md. - 🔌 Model Context Protocol (MCP) & Spatiotemporal Tool Isolation: Dynamically attaches external MCP servers (
filesystem,fetch, databases, GitHub, etc.) over the stdio transport (!mcp connect,!mcp add). Discovered tools join the registry asRubik::Tools::BaseToolproxies; server termination triggers registered LIFO cleanup inverses ($\Omega$) for child processes and proxy tools; these inverses help prevent orphan processes and stale tool calls when cleanup completes successfully. The cleanup path was exercised across 1,000 normal, handshake-failure, and crash/recovery cycles with explicit resource tolerances; see _report/runtime-capacity-validation-2026-10-16.md. - 📺 Tiered Live Agent Monitoring (Step Formatter & Verbosity): With the
quiet,normal,verbose, anddebuglevels, step progress, tool calls, execution times, and intermediate thoughts are watched in real time (!verbosity,!verbose). - 🎨 Hybrid TUI Display Layer: The
⏺/⎿agent flow language, a live spinner cycling through Turkish verbs (✻ Kavuruyor… 4sn), an above-prompt statusline (model · context percentage · dirty buffer), live markdown rendering, a colored diff viewer, one-key quick approvals, and the interactive!agentsfiber board. UnderNO_COLOR/--no-colorand in pipe mode the output degrades to plain text; session logs never contain ANSI codes (live settings via!config set ui.*). - ⚡ Native Tool Acceleration: When available on the system,
grep_searchis delegated to ripgrep and context scanning togit ls-files; AST symbols warm up with lazy body loading. Without rg/git, or withtools.native: offorRUBIK_NATIVE=off, every path falls back to pure Ruby with identical output — the output format never changes. - 🧵 Quiet Concurrency (Fiber Scheduler Event Loop): The pure-stdlib
Rubik::Concurrencylayer provides cooperative single-threaded concurrency WITHOUT altering any existing blocking I/O call sites (Net::HTTP, sleep, Open3 pipes, Mutex/CV/Thread#join): tested at 100 and 1,000 concurrent local network requests, including latency, timeout, cancellation, and sequential comparisons; see _report/runtime-capacity-validation-2026-10-16.md), the MCP boot fan-out, and the subagent provider pool all run through theConcurrency.silently/.mapboundary (not CPU parallelism, due to the GVL). Kill switch:RUBIK_FIBER_SCHEDULER=off. - 📜 Vakanüvis Chronicler (Session Annals): The deterministic harness records REPL root turns and subagent lifecycle events into the
rubik://storageannals; a budget-capped LLM distiller mines memory and a wiki skeleton from those annals. All planes are governed bysubagents.vakanuvis.*; chronicles can be recalled through the Vakanüvis tool (recall/record/forget/digest).
🛡️ Security note — when cloning unfamiliar repositories: The
.rubik/commandsand.rubik/toolsdirectories contain overlay files that can be interpreted at runtime. SHA-256 manifest verification blocks later modifications; files carrying a sentinel header but no manifest are accepted on the first scan only with the explicit consent ofRUBIK_BOOTSTRAP_OVERLAYS=1. If you have cloned a repository you do not know, inspect the.rubik/directory before the first run.
🕹️ REPL Bang Commands
For detailed parameters, flags, and usage scenarios of all 30+ interactive commands:
👉 Check out the COMMANDS.md — Comprehensive REPL Command Guide document.
Command Summary Table
| Command Group | Key Commands | Description |
|---|---|---|
| Models & Providers |
!provider, !providers, !model
|
Provider add/remove (CRUD), model role assignment, and smart routing. |
| Agent & Planning |
!plan, !goal, !steps
|
Step-by-step planning, the autonomous goal loop, and step budget management. |
| Buffer & Snapshots |
!diff, !apply, !autoapply, !undo
|
Inspect the in-memory virtual file buffer, save to disk, and revert. |
| Runtime & Fibers |
!runtime, !fibers, !services
|
Coeffect services, active/pending fibers, and the $\Omega$ inverse depth. |
| Code Intelligence & LSP |
!lsp, !symbols, !outline, !refs
|
Compiler diagnostics and semantic AST graph searches. |
| Tests & Execution |
!test, !lint, !format, !sh, !sandbox
|
Multilingual test runs, Safe Execution, and a pluggable sandbox (bwrap/docker/podman). |
| Session & Settings |
!session, !history, !config, !verbosity, !status
|
Session persistence, resuming with rubik -c, verbosity, and live settings. |
| Workspace & Roots |
!workspace, !roots, !allow
|
Adding/removing multiple root directories (add/remove), external permissions (!allow), and status listing. |
Agent Surface Contract
Every command is typed with an audience at registration time: :human (operator only), :agent, or :both. Agent-visible built-in commands (!diff, !status, !undo, !rollback, !autoapply, !context, !steps, !config, !model, !providers, !runtime, !fibers, !services, !agents, !lint, !format, !history, !prune) are published as <agent_commands> in the system prompt and can be invoked via the exec_repl_command tool; file, code, test, and shell operations are always performed directly through the tools (read_file, write_file, run_tests, run_command). Human-only commands (!provider, !workspace, !allow, !verbosity, …) are reported back to the agent as a steering message; session lifecycle commands (!quit, !exit, !clear, !reset) are hard-blocked for the agent, while !plan/!goal are redirected to the "finish" tool behind reentrancy protection. Two notes: a !model switch takes effect on the next agent run; and !undo/!rollback revert buffer changes not yet applied to disk, while in buffer.auto_apply = on_test/always mode they may trigger the pre-run auto-apply.
⚙️ Configuration
For details on all model, LSP, buffer policy, provider, and sandbox settings:
👉 Check out the CONFIG.md — Rubik Configuration Guide document.
🖥️ Agent Shell Behavior
run_command commands are never left to an implicit interpreter: the Safe Execution infrastructure runs every command with a resolved shell and an explicit argv array. sandbox.shell: auto (the default) chooses per command via a syntax gate — bash-required syntax (<(...), /dev/null, heredocs) and $ substitutions go to bash, the PowerShell fingerprint ($env:, Select-String, Get-* and other cmdlets) goes to pwsh, and plain commands take the fast path to cmd on Windows (bash elsewhere). The choice is labeled in the result ([EXIT 1] (bash)), and the system prompt announces the shell behavior to the model up front via the <environment> line — the model now knows which shell it is writing commands for. Use sandbox.shell: bash|pwsh|cmd|sh to pin a preference (see CONFIG.md §7).
🧪 Test Suite
Full suite: rake (or rake test). Single file: ruby -Itest test/unit/test_repl.rb.
Windows notes:
- Tests run sequentially in a single process; multi-file arguments such as
ruby -Itest a.rb b.rbrun only the first file — always userakefor the full suite. - A space-containing
TESTvalue such asrake test TEST="a b"is interpreted as a single path on Windows; make one invocation per file. - Temp-directory removal (
teardown) can fail withErrno::EACCESon Windows while a handle is still open; theremove_temp_dirhelper intest_helper.rbswallows this with a best-effort retry and never muddies test results.
Environmental test skips:
- PowerShell shell execution tests are skipped when the
pwsh(PowerShell Core) binary is not present on the system. - Alternative AST parser tests are skipped when the
prismgem or its C extension is not present on the system. - In non-interactive / headless CI environments, direct TUI/reline terminal tests automatically run in non-blocking mode or are skipped in a controlled way.
- Capability skips report their reasons; unexpected failures still fail CI. A passing run describes that runner and commit, not a universal platform guarantee.
📦 Versioning Policy & SemVer 2.0 (Pre-1.0 Stability Roadmap)
Rubik adopts the Semantic Versioning 2.0.0 standard. In the current pre-1.0 release (0.1.0), the Spatiotemporal Composability core architecture, the fiber lifecycle, and the agent protocols are being hardened:
- 0.x Releases: A phase of rapid architectural evolution and refinement of experimental capabilities. Improvements to the core APIs are managed alongside the plan documents.
- 1.0.0 Goal: Reaching production stability by freezing the core SPI interfaces, the Revertible Effects LIFO protocol, and the agent surface contract.
- Backward Compatibility: Before every minor release, comprehensive backward-compatibility and SPI breakage analyses (using GitNexus knowledge-graph & PDG analysis) are mandatory.
📚 Documentation
Every guide ships as a bilingual pair — X.md (English, authoritative) alongside X.tr.md (Turkish translation).
Architecture & Internals
| Guide | What it covers |
|---|---|
| 🌌 AGENTS.md | The Spatiotemporal Composability Protocol — theory, invariants, the fiber lifecycle state machine. |
| 🏗️ ARCHITECTURE.md | The 30 core domains and the responsibility matrix. |
| 🧬 SELF_EVOLUTION.md | How the LLM synthesizes tools, repairs services, and evolves its own runtime. |
| 🔌 API.md | Embedding the runtime from Ruby: config, tool registry, provider contract, orchestrator loop, error contracts. |
User & Operator Guides
| Guide | What it covers |
|---|---|
| 🕹️ COMMANDS.md | All 30+ REPL bang commands with parameters and usage scenarios. |
| 🧰 TOOLS.md | Catalog of the 34 built-in agent tools: parameters, risk classes, diagnostics. |
| ⚙️ CONFIG.md | Every configuration knob (models, LSP, buffer policy, sandbox, subagents, pruner…). |
| 🌍 ENV.md | Environment variables — single consolidated reference table. |
| 🖥️ LSP.md | Step-by-step language-server setup and diagnostics walkthrough. |
| 🔌 PLUGINS.md | The drop-in plugin system: layout, manifests, zero-downtime reloads. |
Project & Policy
| Guide | What it covers |
|---|---|
| 🤝 CONTRIBUTING.md | Dev setup, test commands, commit/PR conventions, security reporting. |
| 🧪 TESTING.md | Running the suite, naming conventions, test templates, flaky-test policy. |
| 🔒 SECURITY.md | Command gate, critical-write protection, synthesis gates, sandbox, audit log. |
| 📜 ATTRIBUTION.md | Open-source attributions and third-party notices. |
| 📜 CHANGELOG.md | Thematic release history; the full record lives in git log. |
| 📄 LICENSE | Software license (MIT). |