Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@ edition = "2024"
license = "BSL-1.0"

[workspace.dependencies]
# The Plugin SDK at contract 0.9, pinned to a commit. A Host loads this
# The Plugin SDK at contract 0.10, pinned to a commit. A Host loads this
# Plugin only when its Harness speaks the same contract version.
runvil-plugin-sdk = { version = "0.9.0", git = "https://github.com/cppalliance/runvil-plugin-api", rev = "4c10a7d4d26c11e6a3055c6f6c4b5657f1bf2faa" }
runvil-plugin-sdk = { version = "0.10.0", git = "https://github.com/cppalliance/runvil-plugin-api", rev = "626bd548706a1ab05b4eea5d218a5ad3723642ed" }
# The shell: a bash interpreter that runs in process, with every command
# built in. Its default features are off, which leaves out its own tool
# layer and the time zone database, and no feature that reaches the
Expand Down
131 changes: 131 additions & 0 deletions plan/2026-12-02-3-native-preludes.plan.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
---
name: Native Preludes and RvLua
overview: Add native preludes (RV_PACK_OPEN and the handle-based RvLua C API) and optional Lua source preludes to the C Plugin contract (v0.10.0) and runvil-plugin-sdk, implement the Engine's mlua-backed RvLua host and native Prelude support in runvil-harness, and roll out contract 0.10.0 across the downstream plugin, workshop, and runvil repositories with lean, bloat-free commits, rust-rulebook compliance on every touched file, PRs, CodeRabbit triage, and ordered upstream merges.
todos:
- id: wave1-plugin-api
content: "Wave 1 (runvil-plugin-api v0.10.0 -> SHA P): 3 testable commits (plan copy, bump runvil-plugin-sys to 0.10.0 + runvil_plugin.h + c-layout, add lean LuaPrelude/Pack::open/PackInfo::lua_prelude + fake Host in runvil-plugin-sdk); apply rust-rulebook to all touched files, push to origin, open PR, address worthwhile CodeRabbit feedback, and merge to upstream"
status: pending
- id: wave2a-three-plugins
content: "Wave 2a (runvil-plugin-std, bashkit, web in parallel -> SHAs S, B, W): 2 testable commits per repo (plan copy, pin runvil-plugin-sdk 0.10.0 at SHA P); apply rust-rulebook, push to origin, open PRs, triage CodeRabbit, and merge to upstream"
status: pending
- id: wave2b-harness
content: "Wave 2b (runvil-harness -> SHA H, parallel with Wave 2a): 4 testable commits (plan copy, lean mlua host + Prelude open in runvil-lua/runvil-types/runvil-plugin, pin contract 0.10.0 at SHA P + RV_PACK_OPEN/RvLua in harness-plugin-loader/harness-runner, update harness-test-plugin + decisions/ + public-api.txt); apply rust-rulebook to all touched files, push to origin, open PR, triage CodeRabbit, and merge to upstream"
status: pending
- id: wave3-workshop-and-runvil
content: "Wave 3 (runvil-workshop -> SHA K, then runvil): 2 testable commits in runvil-workshop pinning H/P/S/B/W, PR + CodeRabbit + merge to upstream (SHA K); then 2 testable commits in runvil pinning Workshop SHA K, PR + CodeRabbit + merge to upstream"
status: pending
isProject: false
---

# Native Preludes and Handle-Based `RvLua` in the Plugin Contract and Engine

## Core Discipline: Lean Code, `rust-rulebook.md`, Testable Commits, and Ordered PRs

1. **Tight, lean code with zero bloat**:
- Do not invent redundant wrapper structs, traits, or helper functions when an existing type or direct function suffices.
- Reuse existing code directly instead of duplicating logic:
- In `runvil-lua`: reuse `order::WalkPlace` / `order::compare_places` for deterministic table walks, `proxy::view_data` for \(O(1)\) Engine view unsealing, `json::json_of_text` and `json::to_json` for `from_json` / `to_json`, and `prelude.rs`'s existing `env` creation, `defined_globals`, collision checks, and `read_only_proxy` sealing.
- In `harness-plugin-loader`: reuse `session::{Field, Shape, RESERVED, field, shape, size_field, rv_str}` and `Plugin`'s `Arc<Plugin>` ownership.
- In `runvil-plugin-sdk`: keep the safe Lua wrapper in one focused `src/lua.rs` module (`Lua<'a>`, `Value<'a>`, `Table<'a>`, `UserDataType<T>`) without mirroring unnecessary `mlua` traits.
- Keep `Prelude` in `crates/runvil-internal/types/src/packs.rs` (or `runvil-lua`) as a single struct rather than introducing parallel prelude types; attach the optional native opener closure directly on `Prelude` with crate-internal constructors so `public-api.txt` gains zero unnecessary surface items.

2. **Apply `tools-public/rulebooks/rust-rulebook.md` to every touched `.rs` file**:
- Three-block `use` grouping (`std`/`core`/`alloc`, external crates, `crate`/`super`/`self`); import types by name and free functions through their module (`use std::fmt;` then `fmt::Display`).
- `pub(crate)` default visibility; `unreachable_pub` clean; no test-only `#[cfg(test)] use` in parent modules feeding child test globs.
- Guard clauses with `let Some(...) = ... else { return ... };`; no `.unwrap()` in library code; `#[expect(..., reason = "...")]` instead of `#[allow(...)]`.
- Every `unsafe fn` has `# Safety`, every `unsafe` block is preceded immediately by `// SAFETY:`, and edition 2024 inner `unsafe` blocks are explicit inside `unsafe fn`s.
- Every `pub` item has third-person indicative `///` docs (`# Errors`, `# Panics`, `# Safety` where applicable), and module headers start with `//!`. Note: `runvil-harness` enforces `no_doctests` (`crates/build-xtask/src/no_doctests.rs`), so doc code fences in `runvil-harness` use ` ```text `.
- In `runvil-plugin-api`, keep Rust 1.85 compatibility (no `let` chains, which require 1.88).

3. **Git, Testable Commits, PRs, CodeRabbit, and Upstream Merge Order**:
- Stay on `master` in every repository (no topical branches; `origin` is `vinniefalco/*`, `upstream` is `cppalliance/*`). Sync `master` with `upstream/master` before starting each repo.
- Commit 1 in every touched repository adds `plan/2026-12-02-3-native-preludes.plan.md` so every commit message ends with `Plan: /plan/2026-12-02-3-native-preludes.plan.md`.
- Every commit must compile and pass `cargo fmt --all --check`, `cargo clippy --all-targets --all-features -- -D warnings`, and the repo's test / `xtask` suite before committing.
- At the end of each wave: push `master` to `origin`, open a PR to `cppalliance/<repo>:master` with `gh pr create`, monitor CI and CodeRabbit review comments, address worthwhile CodeRabbit feedback in clean testable commits (and reply/resolve noise), merge the PR to `upstream` once green, and `git fetch upstream` + `git merge --ff-only upstream/master` to record the exact merged `upstream` SHA for the next wave.

```mermaid
flowchart TD
W1["Wave 1: plugin-api 0.10"] -->|"SHA P"| W2Std["Wave 2a: plugin-std"]
W1 -->|"SHA P"| W2Bash["Wave 2a: plugin-bashkit"]
W1 -->|"SHA P"| W2Web["Wave 2a: plugin-web"]
W1 -->|"SHA P"| W2Harness["Wave 2b: runvil-harness"]
W2Std -->|"SHA S"| W3Workshop["Wave 3a: runvil-workshop"]
W2Bash -->|"SHA B"| W3Workshop
W2Web -->|"SHA W"| W3Workshop
W2Harness -->|"SHA H"| W3Workshop
W3Workshop -->|"SHA K"| W3Runvil["Wave 3b: runvil"]
```

---

## Technical Design

### 1. C Contract (`runvil-plugin-sys` v0.10.0)
- **Status codes & verb**:
- Fill the reserved status slots `1..3`: `RV_ERR_LUA = 1`, `RV_ERR_FATAL = 2`, `RV_ERR_TYPE = 3`.
- Fill the reserved verb slot `8`: `RV_PACK_OPEN = 8`, sent once per section VM for each declared Pack on `call->pack_run` with `RvPackOpenArgs`.
- A Pack with no native prelude answers `RV_PACK_OPEN` with `RV_ERR_UNSUPPORTED` (matching `RV_PACK_RENDER`), which the loader treats as a no-op.
- **`RvPackInfo` & `RvPackOpenArgs`**:
- Append `pub lua_prelude: RvStr` to `RvPackInfo` (empty `{NULL, 0}` when unset, capped at `RV_MAX_TOOL_TEXT = 65_536` bytes of UTF-8; size grows from 40 to 56 bytes on 64-bit).
- `RvPackOpenArgs { size: u32, reserved: u32, ctx: *mut c_void, pack_id: RvStr, env: RvValue, lua: *const RvLua, refuse: unsafe extern "C" fn(ctx: *mut c_void, reason: RvStr) -> RvStatus }`.
- **Flat 16-byte `RvValue` (zero `union` / zero `unsafe` in `runvil-plugin-sys`)**:
- `#[repr(C)] pub struct RvValue { pub kind: RvKind, pub reserved: u32, pub payload: u64 }`.
- `RvKind`: `RV_NIL = 0`, `RV_BOOLEAN = 1` (`0` or `1`), `RV_INTEGER = 2` (`payload as i64`), `RV_NUMBER = 3` (`f64::from_bits(payload)`), `RV_NULL = 4` (`json.null`), `RV_LIGHTUSERDATA = 5` (`payload as usize as *mut c_void`), `RV_STRING = 6`, `RV_TABLE = 7`, `RV_FUNCTION = 8`, `RV_USERDATA = 9`, `RV_OPAQUE = 10`.
- **Call-scoped tokens, callbacks, and `RvLua`**:
- `RvCx { pub bits: u64 }`, `RvMark { pub bits: u64 }`, `RvIter { pub bits: u64 }`.
- `RvFunction = unsafe extern "C" fn(cx: RvCx, lua: *const RvLua, data: *mut c_void, args: *const RvValue, nargs: usize) -> RvStatus`.
- `RvDrop = unsafe extern "C" fn(data: *mut c_void)`.
- `RvFunctionInfo`, `RvMethod`, `RvUserdataType` (with `user_values` up to `RV_MAX_USER_VALUES = 4`, `methods`, `index`, `newindex`, `tostring`, `eq`, `lt`, `le`, `len`, `call`, `drop`), and `RvLua` (`size`, `reserved`, and the 30 functions from `2026-10-18-mlua-c-wrapper.md`, using `RvStr` for UTF-8 names/messages/JSON and `RvBytes` for arbitrary Lua string bytes).

### 2. Engine & Loader Architecture (`runvil-harness`)
- **Why no new crates or public facade types are needed**:
- `runvil-lua` implements the safe `mlua` operations in `crates/runvil-internal/lua/src/prelude/native.rs` (table-backed handle arena with generational slots, error states, table/view ops, deterministic iteration, functions, userdata with protected metatables, and JSON conversion) and exposes a lean `LuaHost` API to `runvil-plugin`.
- `Prelude` in `runvil-types` (or moved to `runvil-lua` and re-exported by `runvil-types`, `runvil-engine::packs::Prelude`, and `runvil-plugin`) keeps its exact existing public API (`Prelude::new`, `Prelude::pack`, `Prelude::source`) while gaining crate-internal support for an optional native opener callback and optional Lua source.
- In `crates/runvil-internal/lua/src/prelude.rs` (`install_preludes`), for each declared Pack: build `env` once, run the native opener first (if present), run the Lua source chunk second in the same `env` (if present), and run `defined_globals`, collision checks, and top-level table sealing (`read_only_proxy` for `Value::Table`, unchanged `Value::UserData` / `Value::Function`).
- In `harness-plugin-loader`: `EntryPack` implements `Pack::open` by opening an `RV_PACK_OPEN` session and calling the `PluginEntry` with `RvPackOpenArgs` pointing to the static `RvLua` vtable in `crates/harness-internal/plugin-loader/src/lua.rs`. Every userdata and function wrapper holds an `Arc<Plugin>` field declared **after** its native data drop guard so `(type.drop)(data)` / `(info.drop)(data)` runs during `SectionVm::teardown` (`lua_close`) before the last `Arc<Plugin>` can drop and close the library.

---

## Wave 1: `runvil-plugin-api` v0.10.0 (3 Testable Commits -> Merged Upstream SHA `P`)

- **Commit 1**: Add `plan/2026-12-02-3-native-preludes.plan.md`.
- **Commit 2 (`runvil-plugin-sys` v0.10.0 + `runvil_plugin.h` + `c-layout`)**:
- Update `crates/runvil-plugin-sys/src/lib.rs` (`RV_API_MINOR = 10`, status codes `1..3`, verb `RV_PACK_OPEN = 8`, `RvPackInfo.lua_prelude`, `RvValue`, `RvCx`, `RvMark`, `RvIter`, `RvFunction`, `RvDrop`, `RvFunctionInfo`, `RvMethod`, `RvUserdataType`, `RvLua`, `RvPackOpenArgs`) and bump `Cargo.toml` versions to `0.10.0`.
- Regenerate `crates/runvil-plugin-sys/include/runvil_plugin.h` with `cargo xtask header` and update `tests/c-layout/src/lib.rs`, `layout.c`, and `layout.cpp`.
- **Commit 3 (`runvil-plugin-sdk` v0.10.0 + `testing`)**:
- Add `PackInfo::lua_prelude` and `Pack::open` in `crates/runvil-plugin-sdk/src/pack.rs` and wire `RV_PACK_OPEN` in `crates/runvil-plugin-sdk/src/entry/pack.rs` and `entry/plugin.rs`.
- Add `crates/runvil-plugin-sdk/src/lua.rs` with lean, safe lifetime-bound wrappers over `RvCx` and `*const RvLua`, panic containment on all callbacks/drops, and fake Host support in `src/testing/`.
- Apply `rust-rulebook.md` to every touched file, verify MSRV `1.85`, `c-layout`, `clippy`, `nextest`/`test`, and `doc`, push to `origin`, open PR, address worthwhile CodeRabbit comments, and merge to `upstream` -> SHA `P`.

---

## Wave 2: Three Plugin Repos + `runvil-harness` (Parallel PRs once `P` Merges)

### Wave 2a: `runvil-plugin-std`, `runvil-plugin-bashkit`, `runvil-plugin-web` (2 Commits Each -> SHAs `S`, `B`, `W`)
- **Commit 1**: Add `plan/2026-12-02-3-native-preludes.plan.md`.
- **Commit 2**: Pin `runvil-plugin-sdk = "0.10.0"` at SHA `P`, verify `build-checks`, `fmt`, `clippy`, `test`, and `doc`, push to `origin`, open PRs, triage CodeRabbit, and merge to `upstream` -> SHAs `S`, `B`, `W`.

### Wave 2b: `runvil-harness` (4 Testable Commits -> Merged Upstream SHA `H`)
- **Commit 1**: Add `plan/2026-12-02-3-native-preludes.plan.md`.
- **Commit 2 (Engine `mlua` host + hybrid `Prelude` in `runvil-lua`, `runvil-types`, `runvil-plugin`, `harness-runner`)**:
- Implement `crates/runvil-internal/lua/src/prelude/native.rs` and wire native + Lua source execution in `crates/runvil-internal/lua/src/prelude.rs`.
- Add `Pack::open` in `crates/runvil-plugin/src/pack.rs` and wire `RunPacks::snapshot` in `crates/harness-internal/runner/src/packs.rs` so declared usable Packs contribute native `open`, `info.prelude`, or both.
- Add thorough unit tests in `runvil-lua` covering arena handles, `mark`/`release_to`, error catching vs. sticky fatal errors, guarded `var`/`args`/`sys` table access, deterministic iteration, functions, userdata with `drop` on VM teardown, light userdata, and `from_json`/`to_json`.
- **Commit 3 (Pin contract `0.10.0` at `P` and wire `RV_PACK_OPEN` + `RvLua` in `harness-plugin-loader`)**:
- Pin `runvil-plugin-sys = "0.10.0"` at SHA `P` in `Cargo.toml`.
- Read `info.lua_prelude` in `crates/harness-internal/plugin-loader/src/plugin.rs` (`insert_pack`) and wire `crates/harness-internal/plugin-loader/src/lua.rs` + `pack.rs` (`RV_PACK_OPEN`, `RvLua` vtable, `Arc<Plugin>`-pinned function/userdata drop guards, and loader unit tests).
- **Commit 4 (`harness-test-plugin` 0.10 + end-to-end tests + `decisions/`)**:
- Update `crates/harness-internal/test-plugin/src/lib.rs` to contract `0.10` with a native prelude (installing table functions and a callable userdata whose `drop` increments an atomic counter on VM teardown) plus a `lua_prelude`, and add end-to-end tests in `crates/harness-internal/test-plugin/tests/it/`.
- Update `decisions/tools-and-packs.md` and `decisions/prompt-language.md`.
- Apply `rust-rulebook.md` across all touched files, run full verification (`nextest`, `clippy`, `fmt`, `doc`, `xtask tidy`, `xtask api --check`, `docs-claims.mjs`), push to `origin`, open PR, triage CodeRabbit, and merge to `upstream` -> SHA `H`.

---

## Wave 3: `runvil-workshop` and `runvil`

- **Wave 3a (`runvil-workshop` -> SHA `K`)**:
- Commit 1: Add `plan/2026-12-02-3-native-preludes.plan.md`.
- Commit 2: Pin `runvil-harness` (`H`), `runvil-plugin-sdk` `0.10.0` (`P`), `std-plugin` (`S`), `bashkit-plugin` (`B`), and `web-plugin` (`W`) in `Cargo.toml`. Verify all checks, push to `origin`, open PR, triage CodeRabbit, and merge to `upstream` -> SHA `K`.
- **Wave 3b (`runvil`)**:
- Commit 1: Add `plan/2026-12-02-3-native-preludes.plan.md`.
- Commit 2: Pin Workshop SHA `K` in `Cargo.toml`, verify `xtask`, push to `origin`, open PR, triage CodeRabbit, and merge to `upstream`.
Loading