rubik 0.1.6 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. checksums.yaml +4 -4
  2. data/ATTRIBUTION.md +5 -1
  3. data/CHANGELOG.md +169 -0
  4. data/README.md +137 -255
  5. data/bin/rubik +9 -0
  6. data/lib/rubik/ast/extraction_result.rb +37 -0
  7. data/lib/rubik/ast/extractor.rb +35 -9
  8. data/lib/rubik/ast/graph.rb +27 -1
  9. data/lib/rubik/ast/treesitter/c_walker.rb +136 -28
  10. data/lib/rubik/ast/treesitter_extractor.rb +45 -17
  11. data/lib/rubik/buffer/apply_contract.rb +78 -0
  12. data/lib/rubik/buffer/manager.rb +61 -5
  13. data/lib/rubik/cli/workspace_trust.rb +78 -0
  14. data/lib/rubik/concurrency/event_loop.rb +56 -44
  15. data/lib/rubik/concurrency/scheduler.rb +7 -24
  16. data/lib/rubik/context/git_lister.rb +6 -1
  17. data/lib/rubik/context/scanner.rb +15 -3
  18. data/lib/rubik/kernel/init.rb +15 -0
  19. data/lib/rubik/mcp/transport/stdio.rb +14 -11
  20. data/lib/rubik/orchestrator/auto_apply.rb +1 -1
  21. data/lib/rubik/orchestrator/subagent/activation.rb +29 -4
  22. data/lib/rubik/orchestrator/subagent/builtin_types.rb +117 -0
  23. data/lib/rubik/orchestrator/subagent/dynamic_store.rb +119 -0
  24. data/lib/rubik/orchestrator/subagent/instance.rb +8 -36
  25. data/lib/rubik/orchestrator/subagent/journal.rb +77 -4
  26. data/lib/rubik/orchestrator/subagent/profile_contract.rb +187 -0
  27. data/lib/rubik/orchestrator/subagent/profile_snapshot.rb +72 -0
  28. data/lib/rubik/orchestrator/subagent/reuse.rb +2 -1
  29. data/lib/rubik/orchestrator/subagent/scoped_registry.rb +2 -0
  30. data/lib/rubik/orchestrator/subagent/spawn_transaction.rb +170 -0
  31. data/lib/rubik/orchestrator/subagent/start_gate.rb +98 -0
  32. data/lib/rubik/orchestrator/subagent/supervisor.rb +4 -67
  33. data/lib/rubik/orchestrator/subagent/type_definition.rb +84 -0
  34. data/lib/rubik/orchestrator/subagent/type_registry.rb +139 -159
  35. data/lib/rubik/orchestrator/turn_executor/subagent_channel.rb +4 -2
  36. data/lib/rubik/platform/process.rb +152 -3
  37. data/lib/rubik/plugin/manager.rb +148 -71
  38. data/lib/rubik/plugin/package_inventory.rb +84 -0
  39. data/lib/rubik/plugin/requires_dag.rb +40 -0
  40. data/lib/rubik/plugin/storage.rb +100 -14
  41. data/lib/rubik/prompt/context_builder.rb +54 -20
  42. data/lib/rubik/prompt/doctrine.rb +158 -22
  43. data/lib/rubik/prompt/token_estimator.rb +5 -3
  44. data/lib/rubik/prompt/tool_teachings.rb +19 -12
  45. data/lib/rubik/repl/commands/buffer.rb +28 -18
  46. data/lib/rubik/runtime/repair_probe.rb +98 -0
  47. data/lib/rubik/sandbox/driver/bubblewrap.rb +13 -59
  48. data/lib/rubik/sandbox/driver/docker.rb +14 -60
  49. data/lib/rubik/sandbox/driver/podman.rb +13 -56
  50. data/lib/rubik/sandbox/driver/process.rb +12 -64
  51. data/lib/rubik/security/blocked_guidance.rb +19 -0
  52. data/lib/rubik/security/guard.rb +116 -7
  53. data/lib/rubik/storage/store.rb +52 -11
  54. data/lib/rubik/tools/builtins/define_subagent.rb +69 -0
  55. data/lib/rubik/tools/builtins/lifecycle.rb +129 -136
  56. data/lib/rubik/tools/builtins/storage.rb +8 -5
  57. data/lib/rubik/tools/builtins/subagent.rb +20 -53
  58. data/lib/rubik/tools/builtins/synthesis.rb +6 -1
  59. data/lib/rubik/tools/builtins.rb +1 -0
  60. data/lib/rubik/tools/diagnostic_reporter.rb +2 -1
  61. data/lib/rubik/version.rb +1 -1
  62. metadata +15 -1
data/README.md CHANGED
@@ -1,284 +1,166 @@
1
- # 🎲 Rubik — Autonomous AI Coding Agent & REPL Harness
1
+ # Rubik
2
2
 
3
3
  English | [Türkçe](README.tr.md)
4
4
 
5
- > A next-generation autonomous pair-programming and REPL harness written in pure Ruby, built on the **Spatiotemporal Composability & Self-Evolving Runtime** architecture.
5
+ [![Build](https://github.com/ozgurulukir/rubik/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/ozgurulukir/rubik/actions/workflows/ci.yml)
6
+ [![Gem version](https://img.shields.io/gem/v/rubik.svg)](https://rubygems.org/gems/rubik)
7
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
8
+ [![Ruby 3.4+](https://img.shields.io/badge/ruby-3.4%2B-red.svg)](https://www.ruby-lang.org/)
9
+ [![Coverage reports](https://img.shields.io/badge/coverage-CI%20artifacts-blue.svg)](https://github.com/ozgurulukir/rubik/actions/workflows/ci.yml)
10
+ [![Test Suite](https://img.shields.io/badge/tests-see%20CI-blue.svg)](https://github.com/ozgurulukir/rubik/actions/workflows/ci.yml)
6
11
 
7
- [![Gem Version](https://img.shields.io/gem/v/rubik.svg)](https://rubygems.org/gems/rubik)
8
- [![Gem Downloads](https://img.shields.io/gem/dt/rubik.svg)](https://rubygems.org/gems/rubik)
9
- [![Ruby Version](https://img.shields.io/badge/ruby-3.4%2B-red.svg)](https://www.ruby-lang.org)
10
- [![Platform](https://img.shields.io/badge/platform-Linux%20%7C%20macOS%20%7C%20Windows-blue.svg)]()
11
- [![Protocol](https://img.shields.io/badge/protocol-AGENTS.md-blue.svg)](AGENTS.md)
12
- [![Commands Guide](https://img.shields.io/badge/docs-COMMANDS.md-yellow.svg)](COMMANDS.md)
13
- [![Config Guide](https://img.shields.io/badge/docs-CONFIG.md-green.svg)](CONFIG.md)
14
- [![Test Suite](https://img.shields.io/badge/tests-3403%20runs%20%7C%20100%25%20passed-brightgreen.svg)]()
12
+ ## About
15
13
 
16
- ---
14
+ Rubik is a Ruby terminal coding agent and interactive REPL. It connects an LLM to
15
+ workspace tools for reading and changing code, while staging file edits in a
16
+ reviewable in-memory buffer. Developers can use it as a CLI or embed its runtime
17
+ from Ruby with `require "rubik"`.
17
18
 
18
- ## 👋 What is Rubik?
19
+ Rubik is for developers who want an agent in their terminal and control over how
20
+ its changes reach disk. It supports OpenAI-compatible providers, Anthropic, and
21
+ local Ollama. Its security checks and optional OS sandbox are described in
22
+ [Security](SECURITY.md).
19
23
 
20
- 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 while you keep the wheel: file edits stage in a reviewable in-memory buffer (`!diff` → `!apply`), every runtime side effect is registered with a LIFO inverse (zero-restart reloads and teardown), and failing services are diagnosed and repaired live. It runs cross-platform (Linux, macOS, Windows), talks to any OpenAI-compatible endpoint, Anthropic, or local Ollama, and the whole runtime is embeddable from Ruby with `require "rubik"`.
24
+ ## Quickstart
21
25
 
22
- ---
26
+ **Prerequisites:** Ruby 3.4 or later and an OpenRouter API key for this example.
27
+ The gem is the shortest install path:
23
28
 
24
- ## 🚀 Quick Start
25
-
26
- ### From the gem
27
-
28
- Requires **Ruby 3.4+**:
29
-
30
- ```bash
29
+ ```sh
31
30
  gem install rubik
32
31
  ```
33
32
 
34
- The installer puts the `rubik` launcher into RubyGems' bin directory (already on your `PATH`), so you can start it from any project directory:
33
+ Set the key in your shell, then start Rubik. Replace the example value with your
34
+ key:
35
35
 
36
- ```bash
36
+ ```sh
37
+ export OPENROUTER_API_KEY="your-key"
37
38
  rubik
38
39
  ```
39
40
 
40
- or with Bundler:
41
-
42
- ```ruby
43
- gem "rubik"
44
- ```
45
-
46
- #### Platform notes
47
-
48
- | Platform | Install experience |
49
- | :--- | :--- |
50
- | 🐧 Linux / 🍎 macOS | `gem install rubik` — dependencies ship prebuilt. |
51
- | 🪟 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`](.github/workflows/ci.yml). |
52
-
53
- ### From source
54
-
55
- **Prerequisites**
56
-
57
- - **Ruby:** 3.4.0 or later (`ruby -v`)
58
- - **Linux / macOS:** Via the system package manager, `rbenv`, `rvm`, or `asdf`.
59
- - **Windows:** [Scoop](https://scoop.sh) (`scoop install ruby`) or [RubyInstaller with DevKit](https://rubyinstaller.org).
60
- - **Git:** Git 2.30+ (`git -v`)
61
- - **LLM Provider:** Local [Ollama](https://ollama.ai) (`ollama run qwen2.5-coder:7b`) or a DeepSeek, OpenRouter, Anthropic, or OpenAI API key.
62
-
63
- Clone the project, install the dependencies, and start the REPL:
64
-
65
- ```bash
66
- git clone https://github.com/ozgurulukir/rubik.git
67
- cd rubik
68
- bundle install
69
- ```
70
-
71
- #### 🐧 Linux & 🍎 macOS (POSIX)
72
-
73
- ```bash
74
- # Proje dizininden doğrudan çalıştırma
75
- ./bin/rubik
76
-
77
- # Veya sistemde global kullanmak için ~/.local/bin dizinine bağlayın:
78
- ln -sf $(pwd)/bin/rubik ~/.local/bin/rubik
79
- rubik
80
- ```
81
-
82
- > [!NOTE]
83
- > **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.
84
-
85
- #### 🪟 Windows (PowerShell / Command Prompt)
86
-
87
- Rubik ships with built-in `.cmd`, `.bat`, and `.ps1` wrappers for Windows:
41
+ In PowerShell:
88
42
 
89
43
  ```powershell
90
- # PowerShell üzerinden çalıştırma
91
- .\bin\rubik.ps1
92
-
93
- # veya Command Prompt / Terminal üzerinden
94
- .\bin\rubik.cmd
95
-
96
- # veya Ruby üzerinden doğrudan
97
- ruby bin\rubik
44
+ $env:OPENROUTER_API_KEY = "your-key"
45
+ rubik
98
46
  ```
99
47
 
100
- > [!TIP]
101
- > **The Global `rubik` Command on Windows:**
102
- > By adding Rubik's `bin` folder to your environment variables (User PATH), you can launch it from any terminal simply by typing `rubik`:
103
- > ```powershell
104
- > [Environment]::SetEnvironmentVariable("PATH", "$env:PATH;$PWD\bin", "User")
105
- > ```
106
-
107
- ### Adding a Provider & Model
48
+ At the REPL prompt, register the provider and choose a model:
108
49
 
109
- You can connect any OpenAI-compatible provider in a single line:
50
+ <!-- markdownlint-disable MD013 -->
110
51
 
111
- ```bash
112
- # REPL içerisinden sağlayıcı ekleme:
113
- rubik > !provider add deepseek openai_compatible https://api.deepseek.com/v1/chat/completions --key=sk-... --model=deepseek-coder --context=64000
114
- rubik > !model deepseek/deepseek-coder
52
+ ```text
53
+ !provider add openrouter openai_compatible https://openrouter.ai/api/v1/chat/completions --key-env=OPENROUTER_API_KEY --model=anthropic/claude-sonnet-5.5 --context=200000 -g
54
+ !model openrouter/anthropic/claude-sonnet-5.5
115
55
  ```
116
56
 
117
- Anthropic 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:
118
-
119
- ```bash
120
- rubik > !model anthropic/claude-sonnet-5-5
121
- ```
57
+ <!-- markdownlint-enable MD013 -->
122
58
 
123
- ### First Session Example
59
+ Then enter a prompt at the REPL:
124
60
 
125
61
  ```text
126
- ╭── rubik ─────────────────────────────────────────────────╮
127
- │ 🎲 Rubik v0.1.0 │
128
- │ deepseek/deepseek-coder │
129
- │ my_project · main │
130
- │ !help komutlar · ctrl+c kes · !config ayarlar │
131
- ╰──────────────────────────────────────────────────────────╯
132
- deepseek/deepseek-coder · ctx 3% · temiz · sandbox kapalı
133
- rubik (my_project) [main] > !status
134
- Project: my_project (main)
135
- Default Model: deepseek/deepseek-coder
136
- Dirty buffer: false
137
-
138
- rubik (my_project) [main] > Kullanıcı kayıt formunu doğrulayan bir helper fonksiyonu yaz
139
- ✻ Düşünüyor… · 1s (ctrl+c: kes)
140
- ⏺ write_file — lib/validator.rb
141
- ⎿ 3 lines · 18ms
142
-
143
- [Rubik] In-memory buffer updated. Type `!diff` to view, `!apply` to save.
144
-
145
- rubik (my_project) [main] [DIRTY: 1 ✎] > !diff
146
- + def validate_user(params)
147
- + raise "Invalid email" unless params[:email]&.include?("@")
148
- + end
149
-
150
- rubik (my_project) [main] [DIRTY: 1 ✎] > !test
151
- Applied 1 file(s) before test. All 12 tests passed!
62
+ Summarize the files in this project.
152
63
  ```
153
64
 
154
- > [!TIP]
155
- > **Safe Execution (Tree-Sitter AST) & Hardware-Enforced OS Isolation (Bubblewrap / Container):**
156
- > Before running any command, Rubik always 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. For hardware-enforced OS isolation on Linux, use Bubblewrap (`bwrap`) or OCI (`docker`/`podman`):
157
- > ```bash
158
- > !sandbox on # Linux'ta Bubblewrap ile donanımsal OS izolasyonunu açar
159
- > !config set sandbox.allow_network true -p # Ağ erişimi gerektiren komutlar için izin verir
160
- > ```
161
-
162
- ---
163
-
164
- ## ⚡ Key Features
165
-
166
- - 🌐 **Full Cross-Platform Support (Linux, macOS, Windows):** Runs with zero friction on Windows 11 / Windows Server environments (PowerShell, Command Prompt, Windows Terminal) in addition to POSIX systems. Ships with a pure-Ruby binary resolution solution, NTFS case-insensitivity handling, the RFC 8089 LSP URI standard, and native Windows CLI (`.cmd`, `.bat`, `.ps1`) wrappers.
167
- - 🛡️ **Zero-Risk In-Memory Buffer:** When the model writes code, your files are not written to disk immediately; they are staged in an in-memory virtual buffer. You can inspect them with `!diff`, approve them with `!apply`, or revert them within seconds with `!undo`.
168
- - 🏢 **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.
169
- - ⚡ **Live LSP Compiler Diagnostics:** While the model writes code, language servers such as `rust-analyzer`, `typescript-language-server`, `ruff`, `typeprof`, and `gopls` stand guard. As soon as a syntax or type error occurs, the model is alerted before any tests have even run.
170
- - 🌳 **Multilingual Tree-Sitter & Prism Hybrid AST Engine:** Ships with the built-in **Prism** parser for Ruby and a full **Tree-Sitter** AST engine for Python, Go, Rust, TypeScript, TSX, JavaScript, C, C++, and Zig. It is 100% immune to curly-brace traps inside comments/strings and to modern language patterns; when a library is unavailable it silently falls back to the legacy regex extractors (fail-safe graceful fallback). The symbol and call graph (`!symbols`, `!outline`, `!refs`) is scanned asynchronously in the background; thanks to the persistent on-disk cache (`.rubik/cache/ast_index.json`) it is ready instantly across restarts.
171
- - 🤖 **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.
172
- - 🧬 **Spatiotemporal Composability & Self-Evolving Runtime:** The model can synthesize new REPL commands (`synthesize_command`) or built-in tools (`synthesize_tool`) at runtime; every side effect is tracked safely by the LIFO inverse-operation accumulator ($\Omega$).
173
- - 🩹 **Self-Healing Runtime (Service Repair Plane):** Runtime components never require a process restart. `inspect_runtime` exposes the live fiber/coeffect/service state; `repair_runtime_service` diagnoses 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_service` registers new services live; every step is LIFO-revertible per the protocol above.
174
- - 📋 **Structured Goal Ledger (SKILL.state adaptation):** the `!goal` loop 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-only `update_goal_ledger` tool (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-ledger` ref), declarative `verify` specs are re-checked at step boundaries (a failed check flips the task to `stale` — 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).
175
- - 🧹 **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_context` tool and `!prune`. Default ON since 2026-10-10 (`subagents.pruner.*`, operator-only; opt-out `enabled: false`); the deterministic compaction stack always remains the safety net.
176
- - 🔌 **Drop-in Plugin System (User Plugins):** `.rb` plugin files (drop-in) or directories under `~/.rubik/plugins` (global) or `.rubik/plugins` (project) are loaded automatically. Plugins are managed dynamically and with zero downtime from the REPL (`!plugin add`, `!plugin reload`); integrity is enforced through SHA-256 `.manifest.json` security verification.
177
- - 🔌 **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 as `Rubik::Tools::BaseTool` proxies; when a server stops or crashes, the `AGENTS.md` LIFO inverse-operation accumulator ($\Omega$) and atomic rollback guarantee zero leftover processes and zero leaks.
178
- - 📺 **Tiered Live Agent Monitoring (Step Formatter & Verbosity):** With the `quiet`, `normal`, `verbose`, and `debug` levels, step progress, tool calls, execution times, and intermediate thoughts are watched in real time (`!verbosity`, `!verbose`).
179
- - 🎨 **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 `!agents` fiber board. Under `NO_COLOR`/`--no-color` and in pipe mode the output degrades to plain text; session logs never contain ANSI codes (live settings via `!config set ui.*`).
180
- - ⚡ **Native Tool Acceleration:** When available on the system, `grep_search` is delegated to ripgrep and context scanning to `git ls-files`; AST symbols warm up with lazy body loading. Without rg/git, or with `tools.native: off` or `RUBIK_NATIVE=off`, every path falls back to pure Ruby with identical output — the output format never changes.
181
- - 🧵 **Quiet Concurrency (Fiber Scheduler Event Loop):** The pure-stdlib `Rubik::Concurrency` layer provides cooperative single-threaded concurrency WITHOUT altering any existing blocking I/O call sites (Net::HTTP, sleep, Open3 pipes, Mutex/CV/Thread#join): thousands of concurrent network requests, the MCP boot fan-out, and the subagent provider pool all run through the `Concurrency.silently`/`.map` boundary (not CPU parallelism, due to the GVL). Kill switch: `RUBIK_FIBER_SCHEDULER=off`.
182
- - 📜 **Vakanüvis Chronicler (Session Annals):** The deterministic harness records REPL root turns and subagent lifecycle events into the `rubik://storage` annals; a budget-capped LLM distiller mines memory and a wiki skeleton from those annals. All planes are governed by `subagents.vakanuvis.*`; chronicles can be recalled through the Vakanüvis tool (`recall`/`record`/`forget`/`digest`).
183
-
184
- > 🛡️ **Security note — when cloning unfamiliar repositories:** The `.rubik/commands` and `.rubik/tools` directories 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 of `RUBIK_BOOTSTRAP_OVERLAYS=1`. If you have cloned a repository you do not know, inspect the `.rubik/` directory before the first run.
185
-
186
- ---
187
-
188
- ## 🕹️ REPL Bang Commands
189
-
190
- For detailed parameters, flags, and usage scenarios of all 30+ interactive commands:
191
- 👉 Check out the **[COMMANDS.md — Comprehensive REPL Command Guide](COMMANDS.md)** document.
192
-
193
- ### Command Summary Table
194
-
195
- | Command Group | Key Commands | Description |
196
- | :--- | :--- | :--- |
197
- | **Models & Providers** | `!provider`, `!providers`, `!model` | Provider add/remove (CRUD), model role assignment, and smart routing. |
198
- | **Agent & Planning** | `!plan`, `!goal`, `!steps` | Step-by-step planning, the autonomous goal loop, and step budget management. |
199
- | **Buffer & Snapshots** | `!diff`, `!apply`, `!autoapply`, `!undo` | Inspect the in-memory virtual file buffer, save to disk, and revert. |
200
- | **Runtime & Fibers** | `!runtime`, `!fibers`, `!services` | Coeffect services, active/pending fibers, and the $\Omega$ inverse depth. |
201
- | **Code Intelligence & LSP** | `!lsp`, `!symbols`, `!outline`, `!refs` | Compiler diagnostics and semantic AST graph searches. |
202
- | **Tests & Execution** | `!test`, `!lint`, `!format`, `!sh`, `!sandbox` | Multilingual test runs, Safe Execution, and a pluggable sandbox (bwrap/docker/podman). |
203
- | **Session & Settings** | `!session`, `!history`, `!config`, `!verbosity`, `!status` | Session persistence, resuming with `rubik -c`, verbosity, and live settings. |
204
- | **Workspace & Roots** | `!workspace`, `!roots`, `!allow` | Adding/removing multiple root directories (`add`/`remove`), external permissions (`!allow`), and status listing. |
205
-
206
- ### Agent Surface Contract
207
-
208
- 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.
209
-
210
- ---
211
-
212
- ## ⚙️ Configuration
213
-
214
- For details on all model, LSP, buffer policy, provider, and sandbox settings:
215
- 👉 Check out the **[CONFIG.md — Rubik Configuration Guide](CONFIG.md)** document.
216
-
217
- ---
218
-
219
- ## 🖥️ Agent Shell Behavior
220
-
221
- `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](CONFIG.md) §7).
222
-
223
- ---
224
-
225
- ## 🧪 Test Suite
226
-
227
- Full suite: `rake` (or `rake test`). Single file: `ruby -Itest test/unit/test_repl.rb`.
228
-
229
- Windows notes:
230
- - Tests run sequentially in a single process; multi-file arguments such as `ruby -Itest a.rb b.rb` run only the **first** file — always use `rake` for the full suite.
231
- - A space-containing `TEST` value such as `rake test TEST="a b"` is interpreted as a single path on Windows; make one invocation per file.
232
- - Temp-directory removal (`teardown`) can fail with `Errno::EACCES` on Windows while a handle is still open; the `remove_temp_dir` helper in `test_helper.rb` swallows this with a best-effort retry and never muddies test results.
233
-
234
- Environmental test skips:
235
- - PowerShell shell execution tests are skipped when the `pwsh` (PowerShell Core) binary is not present on the system.
236
- - Alternative AST parser tests are skipped when the `prism` gem or its C extension is not present on the system.
237
- - In non-interactive / headless CI environments, direct TUI/reline terminal tests automatically run in non-blocking mode or are skipped in a controlled way.
238
- - These skips keep the test suite portable and guarantee a 100% green run on every platform.
239
-
240
- ---
241
-
242
- ## 📦 Versioning Policy & SemVer 2.0 (Pre-1.0 Stability Roadmap)
243
-
244
- Rubik adopts the [Semantic Versioning 2.0.0](https://semver.org/) 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:
245
- - **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.
246
- - **1.0.0 Goal:** Reaching production stability by freezing the core SPI interfaces, the Revertible Effects LIFO protocol, and the agent surface contract.
247
- - **Backward Compatibility:** Before every minor release, comprehensive backward-compatibility and SPI breakage analyses (using GitNexus knowledge-graph & PDG analysis) are mandatory.
248
-
249
- ---
250
-
251
- ## 📚 Documentation
252
-
253
- Every guide ships as a bilingual pair — `X.md` (English, authoritative) alongside `X.tr.md` (Turkish translation).
254
-
255
- ### Architecture & Internals
256
-
257
- | Guide | What it covers |
258
- | :--- | :--- |
259
- | 🌌 [AGENTS.md](AGENTS.md) | The Spatiotemporal Composability Protocol — theory, invariants, the fiber lifecycle state machine. |
260
- | 🏗️ [ARCHITECTURE.md](ARCHITECTURE.md) | The 30 core domains and the responsibility matrix. |
261
- | 🧬 [SELF_EVOLUTION.md](SELF_EVOLUTION.md) | How the LLM synthesizes tools, repairs services, and evolves its own runtime. |
262
- | 🔌 [API.md](API.md) | Embedding the runtime from Ruby: config, tool registry, provider contract, orchestrator loop, error contracts. |
263
-
264
- ### User & Operator Guides
265
-
266
- | Guide | What it covers |
267
- | :--- | :--- |
268
- | 🕹️ [COMMANDS.md](COMMANDS.md) | All 30+ REPL bang commands with parameters and usage scenarios. |
269
- | 🧰 [TOOLS.md](TOOLS.md) | Catalog of the 34 built-in agent tools: parameters, risk classes, diagnostics. |
270
- | ⚙️ [CONFIG.md](CONFIG.md) | Every configuration knob (models, LSP, buffer policy, sandbox, subagents, pruner…). |
271
- | 🌍 [ENV.md](ENV.md) | Environment variables — single consolidated reference table. |
272
- | 🖥️ [LSP.md](LSP.md) | Step-by-step language-server setup and diagnostics walkthrough. |
273
- | 🔌 [PLUGINS.md](PLUGINS.md) | The drop-in plugin system: layout, manifests, zero-downtime reloads. |
274
-
275
- ### Project & Policy
276
-
277
- | Guide | What it covers |
278
- | :--- | :--- |
279
- | 🤝 [CONTRIBUTING.md](CONTRIBUTING.md) | Dev setup, test commands, commit/PR conventions, security reporting. |
280
- | 🧪 [TESTING.md](TESTING.md) | Running the suite, naming conventions, test templates, flaky-test policy. |
281
- | 🔒 [SECURITY.md](SECURITY.md) | Command gate, critical-write protection, synthesis gates, sandbox, audit log. |
282
- | 📜 [ATTRIBUTION.md](ATTRIBUTION.md) | Open-source attributions and third-party notices. |
283
- | 📜 [CHANGELOG.md](CHANGELOG.md) | Thematic release history; the full record lives in `git log`. |
284
- | 📄 [LICENSE](LICENSE) | Software license (MIT). |
65
+ Use `!diff` to review staged file changes and `!apply` to write them to disk. See the
66
+ [first-session tutorial](docs/tutorials/first-session.md) for platform-specific
67
+ credential setup and a longer walkthrough. Windows gem installation may compile
68
+ a dependency from source; see the [installation guide](docs/how-to/installation.md).
69
+
70
+ > **Safety note:** Model-generated code and commands can be incorrect or unsafe. Review
71
+ > changes with `!diff` and run tests before relying on them. For strict human approval
72
+ > of **buffered file changes only**, set `buffer.auto_apply: manual` and
73
+ > `buffer.model_can_apply: false`. These settings do not gate shell commands or
74
+ > background processes: the command safety gate checks them, but allowed commands run
75
+ > without a separate per-command approval prompt. The OS sandbox is disabled by default;
76
+ > run untrusted code in an isolated environment. See [Security](SECURITY.md).
77
+
78
+ ## Features
79
+
80
+ 1. **Core · Cross-platform CLI.** Run the terminal agent and REPL on Linux,
81
+ macOS, or Windows. The CI matrix covers Ubuntu with Ruby 3.4 and 4.0, and
82
+ macOS and Windows with Ruby 4.0. In the Windows CI environment, gem
83
+ installation compiles a native dependency with the Rust GNU toolchain. See
84
+ the [installation guide](docs/how-to/installation.md).
85
+ 2. **Core · Staged file edits.** Model writes go to an in-memory virtual buffer;
86
+ inspect them with `!diff`, apply them with `!apply`, or discard unapplied
87
+ edits with `!undo`.
88
+ 3. **Core · Review control and write semantics.** To require operator approval
89
+ for buffered file changes, set `buffer.model_can_apply: false` together with
90
+ `buffer.auto_apply: manual`. This does not add approval prompts for shell
91
+ commands or background processes; see [security practices](SECURITY.md). Each
92
+ file is written atomically, but a multi-file apply is not a transaction: a
93
+ partial failure leaves the remaining changes dirty and reports applied,
94
+ failed, and pending files. See [buffer configuration](docs/how-to/configuration.md).
95
+ 4. **Core · Multiple workspace roots.** Add sibling or external directories as
96
+ read-only roots by default, or allow writes with `--rw`; additional roots can
97
+ join code search and the AST index. See the [`!workspace` commands](docs/reference/commands.md).
98
+ 5. **Core · Guarded command execution.** Commands pass through Rubik's safety
99
+ checks. Bubblewrap, Docker, or Podman isolation is optional and disabled by
100
+ default. See [security practices](SECURITY.md).
101
+ 6. **Models · Provider and role routing.** Connect OpenAI-compatible endpoints,
102
+ Anthropic, OpenAI, or local Ollama, then assign models to default, fast, and
103
+ advanced roles or use task-based routing. See [provider configuration](docs/how-to/configuration.md).
104
+ 7. **Code intelligence · Hybrid AST.** Prism parses Ruby; Tree-Sitter grammars
105
+ cover Python, Go, Rust, TypeScript, TSX, JavaScript, C, C++, and Zig. Symbol
106
+ and call-graph indexing can warm in the background and persists to a local
107
+ cache. If Tree-Sitter is unavailable, Rubik can use regex extractors, which
108
+ have structural limits. Parsing errors have structured statuses, and a
109
+ failed re-index preserves previously indexed symbols. See [architecture](docs/explanation/architecture.md).
110
+ 8. **Code intelligence · Live LSP diagnostics.** Configured language servers
111
+ can start on demand and return compiler or linter diagnostics after edits.
112
+ Missing or failing servers do not block a session; Rubik falls back to its
113
+ built-in syntax and AST analysis. See [language-server setup](docs/how-to/language-servers.md).
114
+ 9. **Code intelligence · Native fast paths.** When available, ripgrep and Git
115
+ accelerate search and context scanning; Rubik falls back to pure Ruby when
116
+ those binaries are missing or native paths are disabled. Control them through
117
+ `tools.native` or `RUBIK_NATIVE`. See [configuration](docs/how-to/configuration.md).
118
+ 10. **Extensions · Runtime synthesis.** The model can create REPL commands and
119
+ tools during a session. Managed runtime effects register cleanup actions
120
+ and unwind them in LIFO order. See [self-evolution](docs/explanation/self-evolution.md).
121
+ 11. **Extensions · Plugins.** Load or reload drop-in Ruby plugins from user or
122
+ project directories. SHA-256 manifests detect modified files, but plugins
123
+ execute arbitrary Ruby in the host process and are not sandboxed. See the
124
+ [plugin guide](docs/how-to/plugins.md).
125
+ 12. **Extensions · MCP servers.** Connect external stdio servers and expose
126
+ discovered tools through Rubik's registry. Lifecycle cleanup removes proxy
127
+ tools and attempts to stop child processes when the server is disconnected.
128
+ See [MCP commands](docs/reference/commands.md).
129
+ 13. **Recovery · Live service repair.** Inspect runtime state, verify a
130
+ replacement command in a disposable context, then promote it without
131
+ restarting the process. Failed promotion or persistence unwinds session
132
+ changes; if a previous service cannot be restored, the repair result reports
133
+ incomplete rollback. Successful operator configuration saves remain in
134
+ place. See [runtime repair](docs/explanation/runtime-repair.md).
135
+ 14. **Long sessions · Structured goal ledger.** The `!goal` loop keeps a
136
+ revision-guarded record of objectives, tasks, findings, and decisions;
137
+ current state survives compaction, and configured verification checks run
138
+ at step boundaries. See [goal commands](docs/reference/commands.md).
139
+ 15. **Long sessions · Context pruning.** A pruner can propose what to keep,
140
+ drop, or summarize; the harness validates the plan and applies it at a turn
141
+ boundary. The operator can also invoke it with `!prune`. See [pruner settings](docs/how-to/configuration.md).
142
+ 16. **Long sessions · Vakanüvis annals.** When configured, the chronicler
143
+ records session turns and subagent events; its distiller can build memory
144
+ notes and a wiki skeleton. See [runtime architecture](docs/explanation/architecture.md).
145
+ 17. **Interaction · Live monitoring and TUI.** Choose quiet, normal, verbose,
146
+ or debug output. The interface combines a statusline, spinner, Markdown
147
+ renderer, colored diff view, and interactive `!agents` board. `NO_COLOR` and
148
+ pipe mode fall back to plain text, and session logs omit ANSI codes. See
149
+ [UI configuration](docs/how-to/configuration.md).
150
+ 18. **Runtime · Cooperative I/O concurrency.** A pure-Ruby Fiber Scheduler can
151
+ overlap supported blocking I/O on one thread; it does not parallelize CPU
152
+ work; disable it with `RUBIK_FIBER_SCHEDULER=off`. The capacity harness
153
+ exercises lifecycle checks at 1,000 epochs, 100 and 1,000 concurrent loopback
154
+ requests, and AST-cache behavior. See [architecture](docs/explanation/architecture.md)
155
+ and [testing](docs/development/testing.md).
156
+
157
+ ## Documentation
158
+
159
+ Browse the [documentation index](docs/index.md) for tutorials, how-to guides,
160
+ references, architecture explanations, and development guidance. The
161
+ [changelog](CHANGELOG.md) records releases.
162
+
163
+ ## Contributing and policies
164
+
165
+ [Contributing](CONTRIBUTING.md) · [Code of Conduct](CODE_OF_CONDUCT.md) ·
166
+ [Security policy](SECURITY.md) · [License](LICENSE)
data/bin/rubik CHANGED
@@ -3,6 +3,7 @@
3
3
 
4
4
  $LOAD_PATH.unshift File.expand_path("../lib", __dir__)
5
5
  require "rubik"
6
+ require "rubik/cli/workspace_trust"
6
7
  require "optparse"
7
8
 
8
9
  # Global SIGINT safety net. The REPL installs its own "INT" handler while
@@ -60,6 +61,14 @@ OptionParser.new do |opts|
60
61
  end
61
62
  end.parse!
62
63
 
64
+ workspace_trusted = options[:script] ||
65
+ Rubik::CLI::WorkspaceTrust.authorize!(
66
+ workspace: Dir.pwd,
67
+ input: $stdin,
68
+ output: $stdout
69
+ )
70
+ Kernel.exit(0) unless workspace_trusted
71
+
63
72
  shell = Rubik::REPL::Shell.new
64
73
 
65
74
  if options[:continue]
@@ -0,0 +1,37 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Rubik
4
+ module AST
5
+ # Structured outcome of one file extraction (issue #147): `symbols` is
6
+ # always the best available list (possibly empty), while `status` says HOW
7
+ # much it can be trusted — so "no symbols here" and "extraction failed"
8
+ # are never confused:
9
+ # :ok — authoritative result (clean parse, or the primary
10
+ # extractor for this file/environment)
11
+ # :partial — the language parser reported syntax errors; extracted
12
+ # symbols are usable but may be incomplete
13
+ # :failed — no trustworthy result (parser crashed, parse errors
14
+ # with nothing extracted, fallback failed too);
15
+ # `symbols` may carry best-effort output
16
+ # :unavailable — no language extractor claims this extension; the
17
+ # legacy graceful fallback produced whatever it could
18
+ # `source` names who produced the symbols (:ruby, :tree_sitter,
19
+ # :fallback, :none) and `detail` carries the failure reason when there is
20
+ # one.
21
+ ExtractionResult = Struct.new(:symbols, :status, :source, :detail, keyword_init: true) do
22
+ def ok?
23
+ status == :ok
24
+ end
25
+
26
+ def failed?
27
+ status == :failed
28
+ end
29
+
30
+ # A result a caller may rely on for symbol lookup (possibly incomplete
31
+ # but produced by the language parser itself).
32
+ def trustworthy?
33
+ [:ok, :partial].include?(status)
34
+ end
35
+ end
36
+ end
37
+ end
@@ -1,5 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require_relative "extraction_result"
3
4
  require_relative "ruby_extractor"
4
5
  require_relative "go_extractor"
5
6
  require_relative "rust_extractor"
@@ -31,24 +32,49 @@ module Rubik
31
32
  EXTENSIONS = FALLBACK_EXTRACTORS
32
33
 
33
34
  def self.extract(file_path, content = nil)
35
+ extract_result(file_path, content).symbols
36
+ end
37
+
38
+ # Structured outcome (issue #147): symbols plus status/source/detail, so
39
+ # a failed extraction is distinguishable from a legitimately empty file
40
+ # and from a degraded regex fallback. Status vocabulary lives in
41
+ # AST::ExtractionResult.
42
+ def self.extract_result(file_path, content = nil)
34
43
  ext = File.extname(file_path).downcase
35
44
 
36
45
  # 1. Ruby files: always use Prism-powered RubyExtractor first
37
- return RubyExtractor.extract(file_path, content) if ext == ".rb"
46
+ if ext == ".rb"
47
+ return ExtractionResult.new(symbols: RubyExtractor.extract(file_path, content),
48
+ status: :ok, source: :ruby)
49
+ end
38
50
 
39
- # 2. Polyglot files: use Tree-Sitter AST extractor if available
51
+ # 2. Polyglot files: use the Tree-Sitter AST extractor if available
40
52
  if TreeSitterExtractor.available? && TreeSitterExtractor.supports?(ext)
41
- symbols = TreeSitterExtractor.extract(file_path, content)
42
- return symbols unless symbols.nil?
53
+ ts = TreeSitterExtractor.extract_result(file_path, content)
54
+ if ts.trustworthy?
55
+ return ExtractionResult.new(symbols: ts.symbols, status: ts.status,
56
+ source: :tree_sitter, detail: ts.detail)
57
+ end
58
+
59
+ # The language parser failed (crash / unparsable): the regex
60
+ # fallback is best-effort only, and the status says so.
61
+ return fallback_result(file_path, content, ext, status: :failed, detail: ts.detail) if ts.failed?
43
62
  end
44
63
 
45
- # 3. Graceful Fallback: use legacy regex extractor
46
- extractor_class = FALLBACK_EXTRACTORS[ext] || RubyExtractor
47
- extractor_class.extract(file_path, content)
64
+ # 3. Graceful fallback: the legacy regex extractor — the primary path
65
+ # in environments without the tree-sitter pack or for extensions no
66
+ # language extractor claims (:unavailable, legacy Ruby parse).
67
+ fallback_result(file_path, content, ext)
48
68
  rescue StandardError, ScriptError => e
49
69
  warn "[WARN] Extraction failed for #{file_path}: #{e.class}: #{e.message}" if ENV["RUBIK_DEBUG"]
50
- # Graceful fallback to empty symbols on syntax/parsing anomalies
51
- []
70
+ ExtractionResult.new(symbols: [], status: :failed, source: :none, detail: "#{e.class}: #{e.message}")
71
+ end
72
+
73
+ def self.fallback_result(file_path, content, ext, status: nil, detail: nil)
74
+ extractor = FALLBACK_EXTRACTORS[ext]
75
+ status ||= extractor ? :ok : :unavailable
76
+ symbols = (extractor || RubyExtractor).extract(file_path, content)
77
+ ExtractionResult.new(symbols: symbols, status: status, source: :fallback, detail: detail)
52
78
  end
53
79
 
54
80
  def self.supported_extensions