diff --git a/decisions/README.md b/decisions/README.md index 2d8b69a..fbea5dd 100644 --- a/decisions/README.md +++ b/decisions/README.md @@ -1,35 +1,30 @@ # Runvil design decisions -This folder has fifteen pages, one for each part of Runvil's design. A page says what the part is, what it does, and why it is built that way. Every page describes the code as it is at the commits listed below. The pages are for developers who are new to the code, and the developer who will own a part reads its page first. - -- Code: `runvil` at commit `fa9936f64`, `runvil-gateway` at `9369a7d`, `runvil-docs` at `cfd69a4`, `runvil-cloud-providers` at `1817cc4`, `runvil-plugin-api` at `63a2403`, and `runvil-plugin-bashkit` at `6a2e36d` -- Repositories: the Engine and the Harness moved to the `runvil-harness` repository after that commit of `runvil`. The text on repositories, crates, dependency rules, and CI describes `runvil` at `48a4dbc08` and `runvil-harness` at `5bca6f9` (see Limits) -- Plugins: Workshop then moved to the `runvil-workshop` repository. The text on Plugins, Packs, and file access by tools describes `runvil-harness` at `ee199e3a`, `runvil-workshop` at `956e7800`, `runvil-plugin-api` at `52a4905`, `runvil-plugin-std` at `a806bf6`, and `runvil-plugin-bashkit` at `f348f7a` (see Limits) -- Size: 564 entries in about 107,000 words +This folder has one page for each part of Runvil's design. A page says what the part is, what it does, and why it is built that way. Every page describes the code as it is. The pages are for developers who are new to the code, and the developer who will own a part reads its page first. ## The pages -| Page | What it covers | Entries | Gaps | Questions | -|---|---|---|---|---| -| [The prompt language](prompt-language.md) | The prompt file, sections, Lua blocks, the Lua globals, arguments, substitution, `jump`, `call`, and `execute` | 51 | 1 | 9 | -| [Model calls and conversations](models-and-conversations.md) | The `models` API, the model loop, roles, replies, messages, compaction | 45 | 5 | 10 | -| [Tasks and fanout](tasks-and-fanout.md) | Concurrent work in a run, the scheduler's order, determinism, inboxes | 26 | 1 | 4 | -| [Files and the VFS](files-and-the-vfs.md) | The `store` API, the virtual file system, policies, conflicts | 30 | 5 | 7 | -| [The Engine](engine.md) | Parsing, the run state machine, effects, limits, the one error type, the public surface | 44 | 2 | 3 | -| [The Harness and the Host API](harness-and-host.md) | The `runvil` crate, `Host`, `RunSetup`, performing effects, the recorder, the run inbox, stop and cancel | 40 | 5 | 14 | -| [Tools and Packs](tools-and-packs.md) | Tools, Packs, Plugins, the C contract, the shipped Packs | 65 | 8 | 18 | -| [The Gateway](gateway.md) | The Gateway's API, configuration, local models, providers, profiles, boot | 52 | 15 | 10 | -| [Speech](speech.md) | Speech to text, text to speech, voice in Workshop | 39 | 7 | 6 | -| [Workshop: how the app is built](workshop-app.md) | The desktop shell, the server, the protocol, state, the workspace document | 48 | 11 | 9 | -| [Workshop: what the user sees](workshop-ui.md) | Windows, menus, the agent window, the chat box, the look | 32 | 8 | 7 | -| [Crates, build, and CI](crates-build-and-ci.md) | The two workspaces, crate families, dependency rules, structural checks, the toolchain, CI, releases | 49 | 2 | 9 | -| [Testing and debugging](testing-and-debugging.md) | Test support, scripted models, rules for test code, logs and traces | 21 | 3 | 5 | -| [Guides and docs](guides-and-docs.md) | The language guide, the docs site, crate docs | 15 | 4 | 3 | -| [Prompts that ship](shipped-prompts.md) | The sample prompts and the built-in chat prompt | 7 | 2 | 4 | +| Page | What it covers | +|---|---| +| [The prompt language](prompt-language.md) | The prompt file, sections, Lua blocks, the Lua globals, arguments, substitution, `jump`, `call`, and `execute` | +| [Model calls and conversations](models-and-conversations.md) | The `models` API, the model loop, roles, replies, messages, compaction | +| [Tasks and fanout](tasks-and-fanout.md) | Concurrent work in a run, the scheduler's order, determinism, inboxes | +| [Files and the VFS](files-and-the-vfs.md) | The `store` API, the virtual file system, policies, conflicts | +| [The Engine](engine.md) | Parsing, the run state machine, effects, limits, the one error type, the public surface | +| [The Harness and the Host API](harness-and-host.md) | The `runvil` crate, `Host`, `RunSetup`, performing effects, the recorder, the run inbox, stop and cancel | +| [Tools and Packs](tools-and-packs.md) | Tools, Packs, Plugins, the C contract, the shipped Packs | +| [The Gateway](gateway.md) | The Gateway's API, configuration, local models, providers, profiles, boot | +| [Speech](speech.md) | Speech to text, text to speech, voice in Workshop | +| [Workshop: how the app is built](workshop-app.md) | The desktop shell, the server, the protocol, state, the workspace document | +| [Workshop: what the user sees](workshop-ui.md) | Windows, menus, the agent window, the chat box, the look | +| [Crates, build, and CI](crates-build-and-ci.md) | The workspaces, crate families, dependency rules, structural checks, the toolchain, CI, releases | +| [Testing and debugging](testing-and-debugging.md) | Test support, scripted models, rules for test code, logs and traces | +| [Guides and docs](guides-and-docs.md) | The language guide, the docs site, crate docs | +| [Prompts that ship](shipped-prompts.md) | The sample prompts and the built-in chat prompt | ## Where to start -- **Everyone.** [The prompt language](prompt-language.md), then [The Engine](engine.md) and [The Harness and the Host API](harness-and-host.md). These three define the terms that the other pages use. +- **Everyone.** [The prompt language](prompt-language.md), then [The Engine](engine.md) and [The Harness and the Host API](harness-and-host.md). These pages define the terms that the other pages use. - **Packs and Plugins.** [Tools and Packs](tools-and-packs.md) and [Files and the VFS](files-and-the-vfs.md). - **Agent behavior.** [Model calls and conversations](models-and-conversations.md) and [Tasks and fanout](tasks-and-fanout.md). - **Workshop.** [Workshop: how the app is built](workshop-app.md), then [Workshop: what the user sees](workshop-ui.md), and [Speech](speech.md) for voice. @@ -40,7 +35,7 @@ This folder has fifteen pages, one for each part of Runvil's design. A page says Every page has the same parts in the same order. -1. A summary of the design in three paragraphs. +1. A summary of the design. 2. A walk-through that follows one concrete thing through the code, such as a tool call, a chat request, or a user's message. 3. Numbered sections of entries. An entry's heading states one part of the design, and its body says what the code does and why. 4. Planned work: what is still to be built. @@ -50,36 +45,26 @@ Every page has the same parts in the same order. ## The gaps that matter most -The pages list 79 gaps and ask 118 questions. These ten gaps matter most. - 1. **MCP server text marked trusted.** An adhoc tool that wraps `mcp/get_dynamic_tools` returns the servers' text to the model outside the untrusted envelope and marked trusted, because two trust rules overlap. The evidence is a reading of the code and two tests, and a test with the real `mcp` Pack would confirm it. ([Tools and Packs](tools-and-packs.md)) -2. **A Gateway guide that differs from the code.** Most of the Gateway page's fifteen gaps are places where the guide says one thing and the code does another. The Speech page lists seven more in the guide's speech chapter, which describes loudness detection where the code runs Silero. ([The Gateway](gateway.md), [Speech](speech.md)) -3. **A docs site that leaves out the Gateway guide.** `runvil-docs` has the guide's 11 chapters, and the site build lists only the other two books. ([Guides and docs](guides-and-docs.md)) -4. **A restart feature that is half built.** `POST /admin/restart` answers 409 on every Gateway that a shipped launcher starts. The route, the supervised flag, and exit code 75 exist, and the supervisor process is still to be built. ([The Gateway](gateway.md)) +2. **A Gateway guide that differs from the code.** Most of the Gateway page's gaps are places where the guide says one thing and the code does another. The Speech page lists more in the guide's speech chapter, which describes loudness detection where the code runs Silero. ([The Gateway](gateway.md), [Speech](speech.md)) +3. **A docs site that leaves out the Gateway guide.** `runvil-docs` has the guide's chapters, and the site build lists only the other books. ([Guides and docs](guides-and-docs.md)) +4. **A restart feature that is half built.** The route `POST /admin/restart`, the supervised flag, exit code 75, and the supervisor exist. The supervisor never restores the `.prev` copies that Apply writes, and the config UI lacks a Restart to Apply button, so nothing calls the route. ([The Gateway](gateway.md)) 5. **Server state that the Workshop UI ignores.** The server computes `chat_ready`, and the UI ignores it, so the chat box can offer send and the microphone while the server reports chat as unavailable. The UI also lacks a sender for the `switch_profile` frame. ([Workshop: what the user sees](workshop-ui.md), [Workshop: how the app is built](workshop-app.md)) -6. **Three paths that close unsaved editors.** Open Workspace, Close Window, and Exit skip the save dialog that the other close paths show. The evidence is a reading of the code. ([Workshop: what the user sees](workshop-ui.md)) -7. **A toolchain pin that two workflows override.** The repository pins Rust 1.99, and `nightly.yml` and `workshop-installer-smoke.yml` set `RUSTUP_TOOLCHAIN: stable`. ([Crates, build, and CI](crates-build-and-ci.md)) -8. **Logs and debug data that Workshop drops.** Workshop lacks a `tracing` subscriber, so its process discards the Harness's log lines. `RunSetup` lacks a switch for the Engine's events that record each model request and response body. ([Testing and debugging](testing-and-debugging.md)) -9. **A demo that names one developer's machine.** `language_guide.rs` in Workshop's server mounts the language guide from a folder on one developer's machine, behind a switch that is off. The built-in chat prompt describes a system message that its own Lua has commented out. ([Workshop: how the app is built](workshop-app.md), [Prompts that ship](shipped-prompts.md)) -10. **Two APIs that install Packs.** `std` and `bash` reach a Host through the C contract, and `web` and `mcp` reach it through a Rust `install` function, with abilities that the contract lacks: a configuration, Host services, an unavailable Pack with a reason, the call's origin, the `describes_tools` flag, a wait on outside work, and error causes. The design is one Plugin API, and `insert_plugin`, the function for a Plugin that is compiled into the Host, has tests as its only callers. ([Tools and Packs](tools-and-packs.md), [The Harness and the Host API](harness-and-host.md)) +6. **Paths that close unsaved editors.** Open Workspace, Close Window, and Exit skip the save dialog that the other close paths show. The evidence is a reading of the code. ([Workshop: what the user sees](workshop-ui.md)) +7. **Logs and debug data that Workshop drops.** Workshop lacks a `tracing` subscriber, so its process discards the Harness's log lines. `RunSetup` lacks a switch for the Engine's events that record each model request and response body. ([Testing and debugging](testing-and-debugging.md)) +8. **A demo that names one developer's machine.** `language_guide.rs` in Workshop's server mounts the language guide from a folder on one developer's machine, behind a switch that is off. The built-in chat prompt describes a system message that its own Lua has commented out. ([Workshop: how the app is built](workshop-app.md), [Prompts that ship](shipped-prompts.md)) +9. **Two APIs that install Packs.** `std`, `bash`, and `web` reach a Host through the C contract, and `mcp` reaches it through a Rust `install` function, with abilities that the contract lacks: a configuration, an unavailable Pack with a reason, the call's origin, the `describes_tools` flag, the Host's runtime handle, and error causes. The design is one Plugin API, and `with_plugin`, the builder method for a Plugin that is compiled into the Host, has tests as its only callers. ([Tools and Packs](tools-and-packs.md), [The Harness and the Host API](harness-and-host.md)) ## How the pages were checked -- **Sources.** Each fact on a page was read in a frozen copy of the code at the commits above. -- **Review.** A separate reviewer session for each page opened about 2,150 claims at their sources in the code and the guides, and corrected about 190 of them. -- **Second check.** A further session for each page compared about 700 stated reasons with their sources and corrected 21. It confirmed about 195 facts in the code and fixed 5. +- **Sources.** Each fact on a page was read in a frozen copy of the code. +- **Review.** A separate reviewer session for each page opened each claim at its source in the code and the guides, and corrected the claims that were wrong. +- **Second check.** A further session for each page compared each stated reason with its source and corrected the ones that were wrong. It also confirmed facts in the code. - **The checker.** A script checks each page: every quote is word for word in the code, a guide, or the owner's own words, and the page follows the prose rules of the set. ## Limits - **Behavior is read from the code.** The sessions read the code and its tests, and left the build and the tests unrun. -- **Error rate.** The reviewers corrected about 9% of the claims they checked. For a sentence outside those checks, the evidence is one session's reading of the code. -- **Currency.** The pages describe the commits listed at the top. The update bullets below name the text that was brought to later code, and the last bullet names the text that still describes older code. -- **Update of 2026-11-11.** The text on Plugins, crates, and dependency rules was brought to `runvil` at `b0693699d`, `runvil-plugin-api` at `03a9fa3`, and `runvil-plugin-std` at `782ad23`, where `std` is a library Plugin that Workshop loads from a Plugin directory and the `shared-*` crate family is gone. The update is on five pages: [Tools and Packs](tools-and-packs.md), [Workshop: how the app is built](workshop-app.md), [Crates, build, and CI](crates-build-and-ci.md), [The Harness and the Host API](harness-and-host.md), and [Files and the VFS](files-and-the-vfs.md). -- **Update of 2026-11-12.** The text on repositories was brought to `runvil` at `48a4dbc08` and `runvil-harness` at `5bca6f9`, where the Engine, Harness, and Plugin crates are in the `runvil-harness` repository and `runvil` pins four of them by commit. The history of `runvil-harness` was written a second time that day, to include the plan and vibe records of the Engine and the Harness, and commit `48a4dbc08` of `runvil` moved the pin to `5bca6f9` in that history. [Crates, build, and CI](crates-build-and-ci.md) has most of it: the two workspaces, their crates, the dependency rules, the place of each structural check, and the CI jobs, with one new entry on the pin. [Workshop: how the app is built](workshop-app.md), [Guides and docs](guides-and-docs.md), and [Prompts that ship](shipped-prompts.md) have the sentences that the move changed. Eight pages have a new Paths bullet, because the code they describe is in `runvil-harness`: [The prompt language](prompt-language.md), [Model calls and conversations](models-and-conversations.md), [Tasks and fanout](tasks-and-fanout.md), [Files and the VFS](files-and-the-vfs.md), [The Engine](engine.md), [The Harness and the Host API](harness-and-host.md), [Tools and Packs](tools-and-packs.md), and [Testing and debugging](testing-and-debugging.md). Each page lists its updated parts in its last section. -- **Update of 2026-11-13.** The text on Plugins, Packs, and file access by tools was brought to `runvil-harness` at `18361d02`, `runvil-workshop` at `f386801b`, `runvil-plugin-api` at `03a9fa3`, `runvil-plugin-std` at `ee04d10`, and `runvil-plugin-bashkit` at `9c8e980`. Workshop is in the `runvil-workshop` repository, which pins `runvil-harness` at `7147e709`, `runvil-plugin-std` at `782ad23`, and `runvil-plugin-bashkit` at `0864f1f`. The update is on [Tools and Packs](tools-and-packs.md) and on six more pages: [Files and the VFS](files-and-the-vfs.md), [The Harness and the Host API](harness-and-host.md), [Crates, build, and CI](crates-build-and-ci.md), [Workshop: how the app is built](workshop-app.md), [Testing and debugging](testing-and-debugging.md), and [Prompts that ship](shipped-prompts.md). The pages state three things. `web` and `mcp` enter a Host through a Rust `install` API, and one Plugin API through the C contract is planned work. The Plugin surface is unfinished and grows a piece at a time. The C contract reads files, and its functions that write and delete a file are still to be built. [Tools and Packs](tools-and-packs.md) gained one entry, on the `bash` Pack, one gap, on the two APIs, and two questions. Its list of places where the language guide differs from the code went from seven to one, after the same session corrected six of them in the working tree of `runvil-docs` over commit `c03ec91`. That session read the code and left the build and the tests unrun. Each page lists its updated parts in its last section. -- **Update of 2026-11-19.** The text on Plugins, Packs, and file access by tools was brought to `runvil-harness` at `ee199e3a`, `runvil-workshop` at `956e7800`, `runvil-plugin-api` at `52a4905`, `runvil-plugin-std` at `a806bf6`, and `runvil-plugin-bashkit` at `f348f7a`. Workshop pins `runvil-harness` at `4afed45f`, whose code is the code of `ee199e3a`, and the other three at the commits named here. Between the two updates a tool lost its file access: it asks its caller for each file operation, the Engine issues the operation as a `Vfs` effect, and the Harness performs it and records it. The C contract went from version 0.4 to 0.5 and gained six functions that change files, so the `std` tools Write, StrReplace, and Delete do their work and the shell of `bash` changes files. The conflict check applies in a store only, and a call of a tool that changes files runs alone, after the calls that the model listed before it. The update is on eight pages. [Files and the VFS](files-and-the-vfs.md) gained four entries, lost one gap and gained four, and lost two questions and gained one. [Tools and Packs](tools-and-packs.md) gained two entries and three gaps, and lost one question and gained three. [The Engine](engine.md) gained one entry, lost the eight questions that the owner answered, and gained two. [The Harness and the Host API](harness-and-host.md) gained two questions, and [Tasks and fanout](tasks-and-fanout.md) lost one, which the owner answered. [Testing and debugging](testing-and-debugging.md), [Workshop: how the app is built](workshop-app.md), and [Prompts that ship](shipped-prompts.md) have the counts they had. The owner's words on the new decisions are quoted from the decision pages of `runvil-harness` at `ee199e3a`. Two counts that were wrong before this change were corrected with it: the surface check allows three serde crates, in [Crates, build, and CI](crates-build-and-ci.md), and the Engine has seven internal crates, in [Testing and debugging](testing-and-debugging.md). The two entries of [Crates, build, and CI](crates-build-and-ci.md) on the pin and on Plugin crates were read against these commits and stand as the update of 2026-11-13 left them, and the gap on the language guide in [Tools and Packs](tools-and-packs.md) stays at the commits of that update. Those sessions read the code and left the build and the tests unrun. Each page lists its updated parts in its last section. -- **Update of 2026-11-24.** The text on streaming a reply was brought to `runvil-harness` at `5d9c7bf8` and `runvil-workshop` at `1b33d9f8`, where `InferenceBroker::chat` takes an `on_piece` callback and a Host sets `RunSetup::streaming`. Workshop pins `runvil-harness` at `5d9c7bf8`. The update is on three pages: [The Harness and the Host API](harness-and-host.md), [Model calls and conversations](models-and-conversations.md), and [Workshop: how the app is built](workshop-app.md). The pages state that the Harness hands a Host's callback each piece of a section's own model round, that the callback returns at once and never calls into the Harness, and that Workshop's launch code sets the callback and publishes each piece into the conversation. The three pages have the entry counts they had, and each page lists its updated parts in its last section. The verification list of each repository passes at those commits. -- **Still to update.** Four groups of text describe older code. The entries on installers, releases, and lints in [Crates, build, and CI](crates-build-and-ci.md) describe the code at the commits listed at the top, and gap 7 above names two workflows that `runvil` has since replaced with `installers.yml`. The text on sections, `jump` targets, and the `prompt` reads in [The prompt language](prompt-language.md) also describes that code, and so does the entry on `find_visible` in [The Engine](engine.md), which names four functions that `runvil-harness` at `ee199e3a` lacks. Gap 2 of [The Engine](engine.md) counts six parse error kinds in the language guide and six codes of `Prompt::parse`, and that page's summary repeats the six kinds, where `runvil-docs` at `1d28c66` and `runvil-harness` at `ee199e3a` each have five. Workshop moved to the `runvil-workshop` repository after the update of 2026-11-12, and the text outside the updates of 2026-11-13 and 2026-11-19 describes Workshop's crates as part of `runvil`: the workspaces, crate counts, families, pins, and checks in [Crates, build, and CI](crates-build-and-ci.md), and the Paths bullets and repository names of the pages that the update of 2026-11-13 left alone. +- **Evidence.** The reviewers corrected some of the claims they checked. For a sentence outside those checks, the evidence is one session's reading of the code. *2026-11-10 16:53 - Claude Fable 5.2* diff --git a/decisions/crates-build-and-ci.md b/decisions/crates-build-and-ci.md index 9b91434..6e6a9e6 100644 --- a/decisions/crates-build-and-ci.md +++ b/decisions/crates-build-and-ci.md @@ -1,57 +1,53 @@ # Crates, build, and CI: design decisions and their reasons -- Scope: crate names and families, which crate may depend on which, the two facades and the check of their public surface, structural checks, lint rules and rulebooks, the toolchain, CI, releases, and installers -- Code: `runvil` at commit `fa9936f64`, `runvil-gateway` at `9369a7d`, and `runvil-plugin-api` at `63a2403` -- Update: the two workspaces, the crate counts, the families, the dependency rules, the git dependencies, the place of each structural check, `default-members`, and the jobs of `ci.yml` describe `runvil` at commit `48a4dbc08` and `runvil-harness` at `5bca6f9` (section 13) -- Update: the reason for the pin on the two Rust Plugins and the dependency rule for Plugin crates, in section 2, describe `runvil-harness` at commit `18361d02`, `runvil-plugin-std` at `ee04d10`, and `runvil-plugin-bashkit` at `9c8e980` (section 13) -- Update: the count of serde crates in the entry on `cargo xtask api`, in section 4, describes `runvil-harness` at commit `ee199e3a` (section 13) -- Paths: code paths start at the root of the `runvil` repository, and a path in another repository starts with that repository's name +- Scope: crate names and families, which crate may depend on which, the facades and the check of their public surface, structural checks, lint rules and rulebooks, the toolchain, CI, releases, and installers +- Paths: code paths start at the root of the `runvil-workshop` repository, and a path in another repository starts with that repository's name ## Summary -The Rust crates are in two workspaces, each in a repository of its own. The `runvil-harness` workspace has 17 crates: the Engine, the Harness, two Rust Plugins, and a `build-xtask` crate. The `runvil` workspace has 20 crates, the 16 of Workshop and four build crates, and its root `Cargo.toml` pins four crates of `runvil-harness` by commit. A crate's name prefix sets its family. Two crates of re-exports are the facades: `runvil-engine` for the Engine, and `runvil` for the Harness, the one crate a Host depends on. Each workspace has a crate `build-xtask` with its structural checks: tests that read manifests and source files and fail on a dependency that the family rules refuse, on a facade that defines an item, and on banned attributes. Every crate inherits the lint table of its workspace. Each repository's `ci.yml` runs its jobs behind one required job, and two workflows build the Workshop installers. Sections 1 to 9 describe these parts. +The Rust crates of the Engine, the Harness, and Workshop are in workspaces, each in a repository of its own. The `runvil-harness` workspace has the crates of the Engine and the Harness, the Rust Plugin crate, and a `build-xtask` crate. The `runvil-workshop` workspace has the Workshop crates and the build crates, and its root `Cargo.toml` pins crates of `runvil-harness` by commit. Another repository, `runvil`, has a workspace of build crates that build the installers and the docs site. A crate's name prefix sets its family. The facades are crates of re-exports: `runvil-engine` for the Engine, and `runvil` for the Harness, the one crate a Host depends on. Each workspace has a crate `build-xtask` with its structural checks: tests that read manifests and source files and fail on a dependency that the family rules refuse, on a facade that defines an item, and on banned attributes. Every crate inherits the lint table of its workspace. Each repository's `ci.yml` runs its jobs behind one required job, and `installers.yml` in `runvil` builds, tests, and publishes the installers. Sections 1 to 9 describe these parts. -A check of this page against the code found two gaps and left nine questions about reasons for the owner. Section 11 lists the gaps, and section 12 lists the questions. The larger gap is in the toolchain: `rust-toolchain.toml` pins Rust 1.99, and `nightly.yml` and `workshop-installer-smoke.yml` compile with the newest stable release. +Section 11 lists the gaps between this page and the code, and section 12 lists the questions about reasons for the owner. A gap is in the Gateway's containers: a crate at the root of `crates/` in `runvil-gateway` can depend on one of the private crates and pass every structural check. Section 10 lists the planned work. Its largest item is platform code signing for the installers. ## From a new crate to a release build -A developer who adds a Workshop crate runs `cargo xtask new-crate` with a name that starts with `workshop-`. The scaffolder in `build-xtask` writes three files under `crates/workshop/`: a `Cargo.toml` with `[lints] workspace = true`, a `src/lib.rs` with an `## Invariants` section, and `tests/it/main.rs`. The developer adds the crate's path to `members` in the root `Cargo.toml`, and adds the package to one of the five tier tables in `crates/build-xtask/src/tidy.rs` (section 2). +A developer who adds a Workshop crate runs `cargo xtask new-crate` with a name that starts with `workshop-`. The scaffolder in `build-xtask` writes these files under `crates/workshop/`: a `Cargo.toml` with `[lints] workspace = true`, a `src/lib.rs` with an `## Invariants` section, and `tests/it/main.rs`. The developer adds the crate's path to `members` in the root `Cargo.toml`, and adds the package to one of the tier tables in `crates/build-xtask/src/tidy.rs` (section 2). `cargo test -p build-xtask` then runs every structural check, each in a test of its own. `family` classifies the package by its prefix, and `product_boundary_violations` tests each of its dependencies on a workspace crate against the desktop boundary and the container rule. `harness_pin_violations` tests each dependency that names `runvil-harness`. Before a push, `.githooks/pre-push` runs a scan of rulebook wording, clippy with `CARGO_BUILD_WARNINGS=deny`, and `cargo deny`. -On the pull request, `.github/workflows/ci.yml` runs nine jobs. `test` runs `cargo nextest` over the workspace, which includes the `build-xtask` checks. `check-workshop` lints and tests the desktop crates on Windows, and `dylint` runs the custom lints. `ci-green` succeeds when all nine succeeded. A change to an Engine or Harness crate is a pull request in `runvil-harness`. The `ci.yml` of that repository has ten jobs: among them, `api-surface` runs `cargo xtask api --check` on the pinned nightly, and `msrv` builds Engine crates with Rust 1.95. +On the pull request, `.github/workflows/ci.yml` runs its jobs. `test` runs `cargo nextest` over the workspace, which includes the `build-xtask` checks. `check-workshop` lints and tests the desktop crates on Windows, and `dylint` runs the custom lints. `ci-green` succeeds when every job it lists succeeded. A change to an Engine or Harness crate is a pull request in `runvil-harness`. The `ci.yml` of that repository has its own jobs: among them, `api-surface` runs `cargo xtask api --check` on the pinned nightly, and `msrv` builds Engine crates with Rust 1.95. -The merge to `master` starts `nightly.yml`, which builds Workshop on five runners and replaces the `nightly` prerelease. A tag that starts with `workshop-v` starts `release-workshop.yml`. Its `prepare` job compares the tag with the workspace version. `build` stages the Gateway binary that `gateway-pin/pin.json` names and builds seven installers with `tauri-action`. `test` installs and runs each installer, and `publish` creates the GitHub Release and updates the rolling release `workshop-latest`. +The installers are built in `runvil`, from a checkout of `runvil-workshop`. A tag such as `v0.3.0` in `runvil` starts `runvil/.github/workflows/installers.yml`. Its `prepare` job compares the tag with the workspace version and checks out `runvil-workshop` at the commit that the root `Cargo.toml` of `runvil` pins. `build` stages the Gateway release that `gateway-pin/pin.json` of that checkout names and runs `cargo installer --sign` on a runner for each target, one installer for each. `test` installs each installer on a fresh machine of its kind, once for each component selection. `manifest` writes and verifies `latest.json` and `SHA256SUMS`, and `publish-release` creates the GitHub Release and updates the rolling release `workshop-latest`. In `runvil-workshop`, `.github/workflows/bundle.yml` runs `cargo workshop bundle` on the same targets for a pull request that touches the bundle and for a manual run, and the installers are made from that bundle. ## 1. Crate names and families ### A crate's name prefix sets its family -In each workspace, `family` in `crates/build-xtask/src/product.rs` maps a package name to a family. In `runvil-harness`, the prefix `runvil-` means Engine, the exact name `runvil` and the prefix `harness-` mean Harness, and the prefixes `plugin-` and `build-` name the other two. In `runvil`, the prefix `workshop-` and the desktop app's package `workshop` mean Workshop, and the prefix `build-` means Build. Any other name is `Unaffiliated`. +In each workspace, `family` in `crates/build-xtask/src/product.rs` maps a package name to a family. In `runvil-harness`, the prefix `runvil-` means Engine, the exact name `runvil` and the prefix `harness-` mean Harness, and the prefixes `plugin-` and `build-` name the other families. In `runvil-workshop`, the prefix `workshop-` and the desktop app's package `workshop` mean Workshop, and the prefix `build-` means Build. In `runvil`, the prefix `build-` means Build, because every crate there is build tooling. Any other name is `Unaffiliated`. -The owner's goal: "You can immediately tell which crate belongs to which deliverable." A rename and the edit of `family` belong in one change. A crate whose new name `family` fails to recognize is `Unaffiliated`, and the checks then skip its family's rules and still pass. +The owner's goal: "You can immediately tell which crate belongs to which deliverable." A rename and the edit of `family` belong in one change. A crate whose name `family` fails to recognize is `Unaffiliated`, and the checks then skip its family's rules and still pass. ### `runvil` is the one crate a Host depends on -A Host writes against `runvil`, the Harness facade, which re-exports the Harness, the Engine items a Host reads, and the Plugin contract. [The Harness and the Host API](harness-and-host.md) lists what `runvil` re-exports. Workshop, a Host in a different repository, names the crate as a git dependency (section 2). +A Host writes against `runvil`, the Harness facade, which re-exports the Harness, the Engine items a Host reads, and the Plugin contract. [The Harness and the Host API](harness-and-host.md) lists what `runvil` re-exports. Workshop, a Host in the `runvil-workshop` repository, names the crate as a git dependency (section 2). ### Each family's private crates are in a container directory -A container is a directory under `crates/` that lacks a `Cargo.toml` of its own. In `runvil-harness`, `crates/runvil-internal/` contains the seven private Engine crates, and `crates/harness-internal/` three Harness crates. In `runvil`, `crates/workshop/` contains the 16 Workshop crates. A container crate's directory drops the family prefix, so `runvil-harness/crates/runvil-internal/lua` is the package `runvil-lua`. Each root `Cargo.toml` excludes its containers and lists each container crate in `members`. +A container is a directory under `crates/` that lacks a `Cargo.toml` of its own. In `runvil-harness`, `crates/runvil-internal/` contains the private Engine crates, and `crates/harness-internal/` the private Harness crates. In `runvil-workshop`, `crates/workshop/` contains the Workshop crates, the desktop app among them. A container crate's directory drops the family prefix, so `runvil-harness/crates/runvil-internal/lua` is the package `runvil-lua`. The root `Cargo.toml` of `runvil-harness` and of `runvil-workshop` excludes its containers and lists each container crate in `members`. The containers exist so that a maintainer or a coding agent who browses `crates/` can tell from the tree which crates are public API and which are internal machinery. ### Both workspaces prefer many small crates to a few large ones -The Engine is seven private crates behind its facade: `runvil-types`, `runvil-vfs`, `runvil-markdown`, `runvil-prompt`, `runvil-model-client`, `runvil-lua`, and `runvil-runtime`. The root `AGENTS.md` of each repository tells authors to "prefer more, smaller crates to fewer, larger ones". +The Engine's private crates sit behind its facade: `runvil-types`, `runvil-vfs`, `runvil-markdown`, `runvil-prompt`, `runvil-model-client`, `runvil-lua`, and `runvil-runtime`. The root `AGENTS.md` of each repository tells authors to "prefer more, smaller crates to fewer, larger ones". A larger crate has more interactions between its own parts. A smaller crate is more focused, and the crate is the natural unit of context for a coding session. The boundaries between the Engine's private crates also let Cargo enforce their layering and compile them in parallel. ### The Gateway is a separate product in its own repository -The Gateway's crates are in the `runvil-gateway` repository. The other two repositories contain the clients. In `runvil-harness`, `harness-gateway-client` sends model requests over HTTP. In `runvil`, `workshop-gateway` is Workshop's HTTP client, and `workshop-gateway-discovery` finds a running Gateway. `runvil` also contains the tooling that ships a Gateway binary with Workshop, which sections 7 and 9 describe. [The Gateway](gateway.md) covers the Gateway's API, configuration, and model serving. +The Gateway's crates are in the `runvil-gateway` repository. `runvil-harness` and `runvil-workshop` contain the clients. In `runvil-harness`, `harness-gateway-client` sends model requests over HTTP. In `runvil-workshop`, `workshop-gateway` is Workshop's HTTP client, and `workshop-gateway-discovery` finds a running Gateway. `runvil-workshop` also contains the tooling that stages a Gateway binary for Workshop's builds, and `runvil` builds the installers that hold that binary, which sections 7 and 9 describe. [The Gateway](gateway.md) covers the Gateway's API, configuration, and model serving. ### Every crate sets `publish = false`, and formats and APIs change freely @@ -68,51 +64,51 @@ In each workspace, `product_boundary_violations` reads each crate's `Cargo.toml` 1. An Engine crate on a Harness crate. 2. A Harness crate on a `build-*` or unaffiliated crate. 3. A Plugin crate on a workspace crate other than `runvil-plugin`. -4. An Engine or Harness crate on a Plugin crate, with one exception that a later entry names. +4. An Engine or Harness crate on a Plugin crate. -In `runvil` it reports a dependency that crosses the desktop boundary and a dependency from outside into the `crates/workshop/` container, which later entries describe. A dependency on a crate of a different repository is outside both matrices, and `runvil` has a second check for the crates it takes from `runvil-harness`. +In `runvil-workshop` it reports a dependency that crosses the desktop boundary and a dependency from outside into the `crates/workshop/` container, which later entries describe. The matrix of `runvil` holds only the container rule. A dependency on a crate of a different repository is outside every matrix, and `runvil-workshop` has a second check for the crates it takes from `runvil-harness`. Each check is a test of its `build-xtask`, so cargo itself enforces the structure of each workspace. ### A crate outside a family depends on that family's public crates -The Engine family has two public crates, `runvil-engine` and `runvil-plugin`. The Harness family has two, `runvil` and `harness-gateway-client`. The matrix of `runvil-harness` reports a crate outside a family that names any other crate of that family. +The Engine family's public crates are `runvil-engine` and `runvil-plugin`. The Harness family's are `runvil` and `harness-gateway-client`. The matrix of `runvil-harness` reports a crate outside a family that names any other crate of that family. -A second rule covers the containers. In `runvil-harness`, two outside crates may depend into `crates/runvil-internal/`, `runvil-engine` and `runvil-plugin`, and one may depend into `crates/harness-internal/`, `runvil`. In `runvil`, one kind of outside crate may depend into `crates/workshop/`, a `build-*` crate, and the four build crates leave that permission unused. +A second rule covers the containers. In `runvil-harness`, `runvil-engine` and `runvil-plugin` may depend into `crates/runvil-internal/` from outside it, and `runvil` may depend into `crates/harness-internal/`. In `runvil-workshop`, a `build-*` crate may depend into `crates/workshop/`, and the build crates leave that permission unused. -For the Engine family, the goal of the rule is zero leakage of its private crates. `harness-gateway-client` is the second public Harness crate so that a Host can depend on it directly. +For the Engine family, the goal of the rule is zero leakage of its private crates. `harness-gateway-client` is a public Harness crate so that a Host can depend on it directly. -### `runvil` takes four crates from `runvil-harness`, all at one commit +### `runvil-workshop` takes crates from `runvil-harness`, all at one commit -The root `Cargo.toml` of `runvil` names `runvil`, `harness-gateway-client`, `plugin-web`, and `plugin-mcp` in `[workspace.dependencies]` as git dependencies on `runvil-harness`, each with the same `rev`. `harness_pin_violations` in `crates/build-xtask/src/harness_pin.rs` reads that table and the manifest of every workspace member. It reports an entry from that repository that names a fifth crate, an entry that lacks a `rev`, a second `rev` among the entries, and a member that names the repository in a manifest of its own. A member takes each of the four with `workspace = true`. +The root `Cargo.toml` of `runvil-workshop` names `runvil`, `harness-gateway-client`, and `plugin-mcp` in `[workspace.dependencies]` as git dependencies on `runvil-harness`, each with the same `rev`. `harness_pin_violations` in `crates/build-xtask/src/harness_pin.rs` reads that table and the manifest of every workspace member. It reports an entry from that repository that names any other crate, an entry that lacks a `rev`, a second `rev` among the entries, and a member that names the repository in a manifest of its own. A member takes each of them with `workspace = true`. -The matrix of `runvil` reads only the crates of its workspace, so the pin has a check of its own. The four are the two public Harness crates and the two Rust Plugins that Workshop links in, so Workshop reaches the Engine only through `runvil`, the facade. The two Plugin crates are in the pin because `web` and `mcp` enter the Host through the Rust `install` API, whose types the Harness shares with them. The `std` Plugin and the bashkit Plugin follow the C contract and have pins of their own. The move of `web` and `mcp` onto the contract is planned work ([Tools and Packs](tools-and-packs.md)). One `rev` is the rule because two commits of `runvil-harness` in one build are two copies of every type that the four crates share. To take new Engine or Harness work, a developer changes the `rev` of the four entries in one commit. +The matrix of `runvil-workshop` reads only the crates of its workspace, so the pin has a check of its own. The pinned crates are the public Harness crates and the Rust Plugin that Workshop links in, so Workshop reaches the Engine only through `runvil`, the facade. The Plugin crate is in the pin because `mcp` enters the Host through the Rust `install` API, whose types the Harness shares with it. The `std` Plugin, the bashkit Plugin, and the web Plugin follow the C contract and have pins of their own. The move of `mcp` onto the contract is planned work ([Tools and Packs](tools-and-packs.md)). One `rev` is the rule because two commits of `runvil-harness` in one build are two copies of every type that the pinned crates share. To take new Engine or Harness work, a developer changes the `rev` of every entry in one commit. ### Outside its family, a Harness crate names `runvil-engine` and `runvil-plugin` -The matrix of `runvil-harness` reports a Harness crate that depends on a `build-*` crate or an unaffiliated crate. The check exempts one dependency: `harness-gateway-client` depends on `plugin-web`, whose `SearchProvider` trait it implements. +The matrix of `runvil-harness` reports a Harness crate that depends on a `build-*` crate or an unaffiliated crate. Outside its family, a Harness crate may name only `runvil-engine` and `runvil-plugin`. -The rule exists so that the Harness can be built, published, or moved out of the workspace by itself, and so that its documentation tree needs only what the docs site contains. The rule held when the Engine and the Harness moved to `runvil-harness`, and that workspace's matrix keeps it. +The rule exists so that the Harness can be built, published, or moved out of the workspace by itself, and so that its documentation tree needs only what the docs site contains. The matrix of `runvil-harness` enforces it. -### Workshop crates form four tiers below one desktop boundary +### Workshop crates form tiers below one desktop boundary -`crates/build-xtask/src/tidy.rs` lists each Workshop server crate in one of five tables over four tiers: vocabulary and library Plugins, services, features, and server. [Workshop: how the app is built](workshop-app.md) describes them. A crate depends on crates of lower tiers, and a new `workshop-*` crate joins a tier table before `workshop-server` may depend on it. The two library Plugin crates, `workshop-plugin-std` and `workshop-plugin-bashkit`, depend only on crates outside the Workshop family, and `workshop-server` alone may depend on them. The desktop app, package `workshop`, depends on one Workshop crate, `workshop-server-api`, which depends only on `workshop-server`. +`crates/build-xtask/src/tidy.rs` lists each Workshop server crate in one of its tier tables: vocabulary and library Plugins, services, features, and server. [Workshop: how the app is built](workshop-app.md) describes them. A crate depends on crates of lower tiers, and a new `workshop-*` crate joins a tier table before `workshop-server` may depend on it. The library Plugin crates, `workshop-plugin-std`, `workshop-plugin-bashkit`, and `workshop-plugin-web`, depend only on crates outside the Workshop family, and `workshop-server` alone may depend on them. The desktop app, package `workshop`, depends on one Workshop crate, `workshop-server-api`, which depends only on `workshop-server`. The pin on `runvil-harness`, which an earlier entry of this section describes, keeps the Engine's own crates out of every Workshop manifest, so Workshop imports Engine types from `runvil`. -### A Rust Plugin crate depends on `runvil-plugin`, and one Harness crate names a Plugin crate +### A Rust Plugin crate depends on `runvil-plugin`, and no Engine or Harness crate names a Plugin crate -In `runvil-harness`, a `plugin-*` crate may depend on `runvil-plugin` and on libraries from outside the workspace. The matrix also reports an Engine or Harness crate that depends on a Plugin crate, dev-dependencies included, with `harness-gateway-client` as the exception. +In `runvil-harness`, a `plugin-*` crate may depend on `runvil-plugin` and on libraries from outside the workspace. The matrix also reports an Engine or Harness crate that depends on a Plugin crate, dev-dependencies included. -These checks place every `plugin-*` crate below the Harness: `runvil-plugin`, which defines the Rust Plugin API, is the only Engine or Harness crate that a `plugin-*` crate may depend on. The rule covers the two Rust Plugins, `plugin-web` and `plugin-mcp`. A Plugin that follows the C contract depends on `runvil-plugin-sdk` or `runvil-plugin-sys` from `runvil-plugin-api` and on zero crates of `runvil-harness`, as the `std` Plugin and the bashkit Plugin do. One API for both kinds of Plugin is planned work. [Tools and Packs](tools-and-packs.md) covers `runvil-plugin` and the C contract crate `runvil-plugin-sys`. +These checks place every `plugin-*` crate below the Harness: `runvil-plugin`, which defines the Rust Plugin API, is the only Engine or Harness crate that a `plugin-*` crate may depend on. The rule covers the Rust Plugin, `plugin-mcp`. A Plugin that follows the C contract depends on `runvil-plugin-sdk` or `runvil-plugin-sys` from `runvil-plugin-api` and on zero crates of `runvil-harness`, as the `std` Plugin, the bashkit Plugin, and the web Plugin do. One API for both kinds of Plugin is planned work. [Tools and Packs](tools-and-packs.md) covers `runvil-plugin` and the C contract crate `runvil-plugin-sys`. -Each workspace pins its git dependencies by commit. `runvil-harness` has one, `runvil-plugin-sys` from `runvil-plugin-api`. `runvil` has seven: the four crates of `runvil-harness`, `runvil-plugin-sdk` from `runvil-plugin-api`, the `std` Plugin from `runvil-plugin-std`, and the bashkit Plugin from `runvil-plugin-bashkit`. `runvil-plugin-sys` sets `links`, and Cargo then refuses two commits of the contract in one build, so `runvil` pins `runvil-plugin-sdk` at the commit of `runvil-plugin-api` that `runvil-harness` pins. +Each workspace pins its git dependencies by commit. `runvil-harness` has `runvil-plugin-sys` from `runvil-plugin-api`. `runvil-workshop` has the crates it takes from `runvil-harness`, `runvil-plugin-sdk` from `runvil-plugin-api`, the `std` Plugin from `runvil-plugin-std`, the bashkit Plugin from `runvil-plugin-bashkit`, and the web Plugin from `runvil-plugin-web`. `runvil-plugin-sys` sets `links`, and Cargo then refuses two commits of the contract in one build, so `runvil-workshop` pins `runvil-plugin-sdk` at the commit of `runvil-plugin-api` that `runvil-harness` pins. ## 3. Bans on dependencies and features -### An Engine crate that depends on one of six crates fails the check +### An Engine crate that depends on a banned crate fails the check -The six are `tokio`, `tokio-util`, `async-trait`, `reqwest`, `getrandom`, and `fastrand`. `runvil-harness/crates/build-xtask/src/engine_deps.rs` applies the ban to `runvil-engine`, `runvil-plugin`, and every crate under `crates/runvil-internal/`. It scans every dependency table of each manifest, dev-dependencies included. It then runs `cargo tree` for each Engine crate with all features and all targets, and reports a banned crate anywhere in the resolved graph. +The banned crates are `tokio`, `tokio-util`, `async-trait`, `reqwest`, `getrandom`, and `fastrand`. `runvil-harness/crates/build-xtask/src/engine_deps.rs` applies the ban to `runvil-engine`, `runvil-plugin`, and every crate under `crates/runvil-internal/`. It scans every dependency table of each manifest, dev-dependencies included. It then runs `cargo tree` for each Engine crate with all features and all targets, and reports a banned crate anywhere in the resolved graph. The owner's rule: "tokio is not allowed anywhere in the engine". The check makes tokio and operating system entropy impossible in every Engine crate, tests included. [The Engine](engine.md) explains why the Engine leaves all I/O to its caller. @@ -124,7 +120,7 @@ The facade and its container exclude tokio so that a Host can await a run on any ### A crate enables `test-support` only from `[dev-dependencies]` -Four Engine crates declare one Cargo feature, `test-support`, and compile their test drivers and fixtures under it. Both facades omit a `[features]` table. `runvil-harness/crates/build-xtask/src/test_support_leak.rs` scans the `[dependencies]`, `[build-dependencies]`, and `[features]` tables of every crate and the root `[workspace.dependencies]` table. It reports an entry that enables `test-support` on an Engine or Harness crate, because that entry "would pull the test drivers into a shipping binary". +Some Engine crates declare a Cargo feature, `test-support`, and compile their test drivers and fixtures under it. Both facades omit a `[features]` table. `runvil-harness/crates/build-xtask/src/test_support_leak.rs` scans the `[dependencies]`, `[build-dependencies]`, and `[features]` tables of every crate and the root `[workspace.dependencies]` table. It reports an entry that enables `test-support` on an Engine or Harness crate, because that entry "would pull the test drivers into a shipping binary". The Engine and the Harness allow a Cargo feature only for testing, and only inside the workspace. The root `AGENTS.md` states the general rule: a Cargo feature "gates a real constraint such as a toolchain requirement or heavy native build, not product shape". @@ -136,21 +132,21 @@ A feature set shared by the whole workspace would compile the test-only feature ### Workshop links one rustls crypto backend -Both workspaces pin `reqwest` at 0.13, whose `rustls` feature selects the `aws-lc-rs` backend. The `supply-chain` CI job of `runvil` runs `cargo tree` on the `workshop` package and fails when `ring` appears in its normal dependency graph. The same job of `runvil-harness` runs the command on its whole workspace, so a Host that links those crates gets the one backend too. +Both workspaces pin `reqwest` at 0.13, whose `rustls` feature selects the `aws-lc-rs` backend. The `supply-chain` CI job of `runvil-workshop` runs `cargo tree` on the `workshop` package and fails when `ring` appears in its normal dependency graph. The same job of `runvil-harness` runs the command on its whole workspace, so a Host that links those crates gets the one backend too. Two crypto libraries in one binary would mean two sets of security advisories to follow, and rustls is unable to choose a `CryptoProvider` by itself when both are present. The version pin enforces the rule through feature resolution, because `reqwest` 0.13 lacks a `ring` option. -## 4. The two facades and the check of their surface +## 4. The facades and the check of their surface ### A facade's source contains `pub use` lines and documented `pub mod` blocks Both facades are in `runvil-harness`. The files under `crates/runvil-engine/src` and `crates/runvil/src` of that repository contain re-exports and comments. Each line of code is a single-item re-export of the form `pub use internal_crate::path::Item;`, or belongs to a `pub mod` block with a doc comment that groups such re-exports. `runvil-harness/crates/build-xtask/src/facade_shape.rs` parses both crates and reports a glob, a grouped list, an item definition, or a path that starts outside the facade's `[dependencies]`. -A re-export of a whole module or crate would expose every item that the module gets later, and a second path to an item would make the API ambiguous. [The Engine](engine.md) and [The Harness and the Host API](harness-and-host.md) describe the two surfaces. +A re-export of a whole module or crate would expose every item that the module gets later, and a second path to an item would make the API ambiguous. [The Engine](engine.md) and [The Harness and the Host API](harness-and-host.md) describe the surfaces. ### `cargo xtask api` proves each surface closed and compares it with a listing -The command belongs to the `build-xtask` of `runvil-harness`. It builds rustdoc JSON for `runvil-engine` and for `runvil`. Its closure check reports a surface item whose signature, fields, bounds, impls, or doc links name something outside the facade's re-exports, the standard library, and three serde crates. Its listing check compares one line per item with the `public-api.txt` in the facade's directory. `--check` fails on a violation or a difference, and `--bless` rewrites the listing. +The command belongs to the `build-xtask` of `runvil-harness`. It builds rustdoc JSON for `runvil-engine` and for `runvil`. Its closure check reports a surface item whose signature, fields, bounds, impls, or doc links name something outside the facade's re-exports, the standard library, and the serde crates it allows. Its listing check compares one line per item with the `public-api.txt` in the facade's directory. `--check` fails on a violation or a difference, and `--bless` rewrites the listing. A developer who adds a `pub use` therefore changes `public-api.txt`, so the change to the surface gets a review. The workspace uses its own command because the `cargo-public-api` tool leaves out the items inside cross-crate re-exports. @@ -162,7 +158,7 @@ The pin exists because only a nightly toolchain emits rustdoc JSON, and the form ### `doc(hidden)` fails the check in both facades and both containers -`runvil-harness/crates/build-xtask/src/doc_hidden.rs` reads every attribute in every `.rs` file under the two facades, `crates/runvil-internal/`, and `crates/harness-internal/`. It reports `doc(hidden)` on an item, a field, a variant, a method, or a re-export, and inside a macro body. +`runvil-harness/crates/build-xtask/src/doc_hidden.rs` reads every attribute in every `.rs` file under the facades, `crates/runvil-internal/`, and `crates/harness-internal/`. It reports `doc(hidden)` on an item, a field, a variant, a method, or a re-export, and inside a macro body. The dependency rules and the surface check make internal items unavailable to outside code, so `doc(hidden)` would only hide them from a family's own docs, which hurts contributors. @@ -170,33 +166,33 @@ The dependency rules and the surface check make internal items unavailable to ou ### `cargo test -p build-xtask` runs every structural check -Each workspace's `build-xtask` has its own checks, and each check has a test that asserts an empty list of violations for its workspace. `cargo xtask tidy` runs them through `all_violations` in `crates/build-xtask/src/tidy.rs` and prints the violations. `runvil-harness` has eleven checks, and `runvil` has nine. Seven are in both: the matrix, the `## Invariants` marker, lint inheritance, the unsafe allowlist, the doctest ban, the size limits on types, and the spelling `fmt::Debug` for the `Debug` trait in every `.rs` file, a rule that clippy lacks a lint for. `runvil-harness` adds the Engine guards, the Harness ban on `tokio`, the shape of the facades, and the `doc(hidden)` ban. `runvil` adds the Workshop tiers and the pin on `runvil-harness`. The entries of sections 2 to 5 describe the other checks. +Each workspace's `build-xtask` has its own checks, and each check has a test that asserts an empty list of violations for its workspace. `cargo xtask tidy` runs them through `all_violations` in `crates/build-xtask/src/tidy.rs` and prints the violations. These checks are in both `runvil-harness` and `runvil-workshop`: the matrix, the `## Invariants` marker, lint inheritance, the unsafe allowlist, the doctest ban, the size limits on types, and the spelling `fmt::Debug` for the `Debug` trait in every `.rs` file, a rule that clippy lacks a lint for. `runvil` has the same checks except the marker. `runvil-harness` adds the Engine guards, the Harness ban on `tokio`, the shape of the facades, and the `doc(hidden)` ban. `runvil-workshop` adds the Workshop tiers and the pin on `runvil-harness`. The entries of sections 2 to 5 describe the other checks. `AGENTS.md` states what a check may test: "Gate on yes/no properties, never on a score threshold that ordinary work edits." ### Every crate inherits one lint table from the root `Cargo.toml` -The two root `Cargo.toml` files have the same lint table. Every crate declares `[lints] workspace = true`, and `lint_inheritance_violations` reports a crate that omits it. The table denies `unsafe_code`, clippy's `all` and `pedantic` groups, `unwrap_used`, `expect_used`, `todo`, and `exit`. It also denies `allow_attributes`, so an author writes a suppression as `#[expect(lint, reason = "...")]`. +The root `Cargo.toml` files of `runvil-harness`, `runvil-workshop`, and `runvil` have the same lint table. Every crate declares `[lints] workspace = true`, and `lint_inheritance_violations` reports a crate that omits it. The table denies `unsafe_code`, clippy's `all` and `pedantic` groups, `unwrap_used`, `expect_used`, `todo`, and `exit`. It also denies `allow_attributes`, so an author writes a suppression as `#[expect(lint, reason = "...")]`. -The level of `unsafe_code` is `deny` because a `forbid` blocks a module-level exception, and a crate with unsafe code would then need a copy of the table. The owner's rule: "I do not want copies of workspace lint. I want the strictest possible settings that still lets us vibe." The allowlist of the next entry limits the exception to four crates. +The level of `unsafe_code` is `deny` because a `forbid` blocks a module-level exception, and a crate with unsafe code would then need a copy of the table. The owner's rule: "I do not want copies of workspace lint. I want the strictest possible settings that still lets us vibe." The allowlist of the next entry limits the exception to the crates it lists. -### Four crates may contain unsafe code +### Only the allowlisted crates may contain unsafe code -In each workspace, `OWNED` in `crates/build-xtask/src/unsafe_allowlist.rs` lists two crates: `crates/workshop/desktop` and `crates/workshop/gateway-discovery` in `runvil`, and `crates/harness-internal/plugin-loader` and `crates/harness-internal/test-plugin` in `runvil-harness`. Each relaxes the lint with `#[expect(unsafe_code, reason = ...)]` on the module that needs it. The check reports an `expect` or `allow` of `unsafe_code` in any other crate, and clippy requires a `SAFETY` comment before each unsafe block. +In `runvil-workshop` and `runvil-harness`, `OWNED` in `crates/build-xtask/src/unsafe_allowlist.rs` lists the crates that may: `crates/workshop/desktop` and `crates/workshop/gateway-discovery` in `runvil-workshop`, and `crates/harness-internal/plugin-loader` and `crates/harness-internal/test-plugin` in `runvil-harness`. Each relaxes the lint with `#[expect(unsafe_code, reason = ...)]` on the module that needs it. The check reports an `expect` or `allow` of `unsafe_code` in any other crate, and clippy requires a `SAFETY` comment before each unsafe block. Any crate can relax a `deny`, so the allowlist check makes the lint as strict as a `forbid` in every other crate. All Plugin loading is in `harness-plugin-loader`, so its unsafe code is in one crate that a reviewer can audit. The loader is outside the facade because a facade contains only re-exports. ### Clippy refuses process-global installers outside a binary entry point -The root `clippy.toml` lists seven `disallowed-methods`: `std::panic::set_hook`, two `log` installers, three `tracing` installers, and `rustls::crypto::CryptoProvider::install_default`. The lint table denies `disallowed_methods` and `exit`. A binary's entry point calls one under `#[expect]` with a reason. +The root `clippy.toml` lists the `disallowed-methods`: `std::panic::set_hook`, the `log` installers, the `tracing` installers, and `rustls::crypto::CryptoProvider::install_default`. The lint table denies `disallowed_methods` and `exit`. A binary's entry point calls one under `#[expect]` with a reason. A library returns a failure to its caller, and only a binary entry point exits the process or installs process-global state. The rule is a clippy setting because the project prefers a structural check to a line of `AGENTS.md`. -### Three `clippy.toml` files ban sleeps, clock reads, and timed waits in Engine code +### The Engine `clippy.toml` files ban sleeps, clock reads, and timed waits in Engine code -In `runvil-harness`, `crates/runvil-internal/clippy.toml`, `crates/runvil-engine/clippy.toml`, and `crates/runvil-plugin/clippy.toml` repeat the root entries and add eight bans: `std::thread::sleep`, `SystemTime::now`, `Instant::now`, `RandomState::new`, and four timed waits. The bans apply to tests, benches, and examples. `crates/build-xtask/src/engine_clippy.rs` of that repository fails when an Engine crate resolves to another file, when a file lacks an entry, or when Engine source suppresses `clippy::disallowed_methods`. +In `runvil-harness`, `crates/runvil-internal/clippy.toml`, `crates/runvil-engine/clippy.toml`, and `crates/runvil-plugin/clippy.toml` repeat the root entries and add these bans: `std::thread::sleep`, `SystemTime::now`, `Instant::now`, `RandomState::new`, and the timed waits. The bans apply to tests, benches, and examples. `crates/build-xtask/src/engine_clippy.rs` of that repository fails when an Engine crate resolves to another file, when a file lacks an entry, or when Engine source suppresses `clippy::disallowed_methods`. -The files are three copies because clippy reads only the nearest `clippy.toml` above a crate's manifest and ignores the root file. [Testing and debugging](testing-and-debugging.md) covers the tests that these bans constrain. +The files are copies because clippy reads only the nearest `clippy.toml` above a crate's manifest and ignores the root file. [Testing and debugging](testing-and-debugging.md) covers the tests that these bans constrain. ### A doc comment with a compiled code block fails the check @@ -206,7 +202,7 @@ Doctest steps would add about 67 seconds to every local run of the checks, so th ### Size limits apply to functions and types, and a file may have any length -Clippy fails a function with more than 100 lines or 7 arguments. In each workspace, `crates/build-xtask/src/type_size.rs` fails a type with more than 25 inherent methods in its crate, and a struct with more than 12 named fields. `ALLOWED` has nine entries in `runvil-harness` and two in `runvil` for types over a limit, each with a recorded ceiling and a reason, and `AGENTS.md` calls a new entry "a plan decision with a reason, never a way to make a change pass". +Clippy fails a function with more than 100 lines or 7 arguments. In each workspace, `crates/build-xtask/src/type_size.rs` fails a type with more than 25 inherent methods in its crate, and a struct with more than 12 named fields. `ALLOWED` lists the types over a limit in each workspace, each with a recorded ceiling and a reason, and `AGENTS.md` calls a new entry "a plan decision with a reason, never a way to make a change pass". `AGENTS.md` states the rule for files: "A file holds one concept and has no length limit." The limits apply to functions and types because a caller depends on what a type does, whatever file contains it. A limit on the length of a file fails to measure structure, and it causes splits whose only purpose is to fit the limit. @@ -218,13 +214,13 @@ The other crates use a flat layout: a subdirectory exists for three or more file ### Every `workshop-*`, `harness-*`, and `plugin-*` crate has an `## Invariants` section in its crate docs -`marker_violations` reports such a crate when its `src/lib.rs` or `src/main.rs` lacks the line `//! ## Invariants`. The check of `runvil` binds the `workshop-*` crates, and the check of `runvil-harness` binds the `harness-*` and `plugin-*` crates. The section states the crate's tier, its allowed dependencies, and its structural rules. The check confirms the marker, and authors update the text below it by hand. +`marker_violations` reports such a crate when its `src/lib.rs` or `src/main.rs` lacks the line `//! ## Invariants`. The check of `runvil-workshop` binds the `workshop-*` crates, and the check of `runvil-harness` binds the `harness-*` and `plugin-*` crates. The section states the crate's tier, its allowed dependencies, and its structural rules. The check confirms the marker, and authors update the text below it by hand. ## 6. Rulebooks ### An `AGENTS.md` file states the rules that checks leave unenforced -The root `AGENTS.md` of `runvil` has six sections, from Definitions to SPA and CSS Rules, and the root `AGENTS.md` of `runvil-harness` has the first five. A crate's own `AGENTS.md` is a title and a few bullets, and most crates lack one. A line belongs in a rule file when it states policy that the code leaves unstated, when the checks and tests leave it unenforced, and when a breach is costly. +The root `AGENTS.md` of `runvil-workshop` has sections from Definitions to SPA and CSS Rules, the root `AGENTS.md` of `runvil-harness` has sections from Definitions to Structural Rules, and the root `AGENTS.md` of `runvil` has Workshop's sections from Definitions to Structural Rules. A crate's own `AGENTS.md` is a title and a few bullets, and most crates lack one. A line belongs in a rule file when it states policy that the code leaves unstated, when the checks and tests leave it unenforced, and when a breach is costly. Rule files are short because the code changes faster than they do, and a stale file steers a coding session toward a design that the code has abandoned. A corrected line becomes stale again at the next refactor, while a test fails when the code changes. @@ -232,11 +228,11 @@ Rule files are short because the code changes faster than they do, and a stale f When a line in an `AGENTS.md` or a `.cursor/rules` file conflicts with the planned design of a change, the design wins, and the commit that creates the conflict deletes the line. The owner's rule: "If any AGENTS.md rule would conflict, then remove the rule. Prefer shrinking AGENTS.md over modifying the planned design." -### Seven terms have one meaning each, and a Node test scans the rulebooks +### Each defined term has one meaning, and a Node test scans the rulebooks -Each root `AGENTS.md` defines the same seven terms, from Engine to Dynamic Set. Each repository has a copy of the Node test: `crates/workshop/ui/test/docs-claims.mjs` in `runvil`, and `tools/docs-claims.mjs` in `runvil-harness`. The test reads every `AGENTS.md`, every `.cursor/rules` file, and every crate doc that has an `## Invariants` section. It fails on a lowercase `host`, `engine`, `harness`, or `plugin` used as a prose word. A second test, which only the copy in `runvil-harness` has, makes Engine crates say "the caller" for the code that steps a run. +Each root `AGENTS.md` defines the same terms, from Engine to Dynamic Set. Each repository has a copy of the Node test: `crates/workshop/ui/test/docs-claims.mjs` in `runvil-workshop`, and `tools/docs-claims.mjs` in `runvil-harness` and in `runvil`. The test reads every `AGENTS.md`, every `.cursor/rules` file, and every crate doc that has an `## Invariants` section. It fails on a lowercase `host`, `engine`, `harness`, or `plugin` used as a prose word. A second test, which only the copy in `runvil-harness` has, makes Engine crates say "the caller" for the code that steps a run. -Code names follow the same terms. The scan runs in the `ui` CI job of `runvil`, in the `wording` CI job of `runvil-harness`, and in each repository's `.githooks/pre-push`. The hook runs it because the cargo commands that check Rust work skip the scan, and a change would otherwise include text that the rule forbids. +Code names follow the same terms. The scan runs in the `ui` CI job of `runvil-workshop`, in the `wording` CI job of `runvil-harness` and of `runvil`, and in each repository's `.githooks/pre-push`. The hook runs it because the cargo commands that check Rust work skip the scan, and a change would otherwise include text that the rule forbids. ### A feature reuses an existing facility before it adds a new one @@ -250,29 +246,29 @@ A convention that this repository wrote down overrides the general Rust rulebook ### `rust-toolchain.toml` pins Rust 1.99 for local builds and CI -Each repository has the file. It names channel `1.99`, and rustup installs that release for anyone who builds in the repository. The jobs of each `ci.yml` use it too, with two exceptions. `api-surface` and `msrv` in `runvil-harness` set a toolchain of their own, and each `dylint` job builds the lint library on the nightly that the library's own `rust-toolchain.toml` names. +Each repository has the file. It names channel `1.99`, and rustup installs that release for anyone who builds in the repository. The jobs of each `ci.yml` use it too, with these exceptions. `api-surface` and `msrv` in `runvil-harness` set a toolchain of their own, and each `dylint` job builds the lint library on the nightly that the library's own `rust-toolchain.toml` names. -The owner's rule: "I want a rule: local builds and CI use the same environment. I never want CI to fail when local succeeds." The file names an exact release, because a build on the `stable` channel fails on a machine whose stable release is out of date. Section 11 lists two workflows that override the pin. +The owner's rule: "I want a rule: local builds and CI use the same environment. I never want CI to fail when local succeeds." The file names an exact release, because a build on the `stable` channel fails on a machine whose stable release is out of date. ### The Engine crates declare Rust 1.95 as their floor -`[workspace.package]` in the root manifest of `runvil-harness` sets `rust-version` to 1.95, and the Engine facade and the seven internal crates inherit it. The `msrv` CI job of that repository reads the value from the manifest and builds the facade and six of the internal crates by name with that toolchain. The seventh, `runvil-markdown`, is a dependency of two of the six. The manifest's comment explains the value: "`runvil-lua` calls the atomics' `try_update`, stable since 1.95". The root manifest of `runvil` omits `rust-version`. +`[workspace.package]` in the root manifest of `runvil-harness` sets `rust-version` to 1.95, and the Engine facade and the internal crates inherit it. The `msrv` CI job of that repository reads the value from the manifest and builds the facade and the internal crates by name with that toolchain, except `runvil-markdown`, which Cargo builds as a dependency of the listed crates. The manifest's comment explains the value: "`runvil-lua` calls the atomics' `try_update`, stable since 1.95". The root manifests of `runvil-workshop` and `runvil` omit `rust-version`. -### A plain `cargo build` in `runvil` builds every crate except the three desktop crates +### A plain `cargo build` in `runvil-workshop` builds every crate except the desktop crates -`default-members` in the root manifest of `runvil` lists 17 of the 20 crates. It omits the desktop app `workshop`, `workshop-server`, and `workshop-server-api`, which are the crates that need Node.js or the Tauri system packages, so a fresh clone on macOS or Linux builds the 17 with only Rust. A developer builds the desktop app by name, with `cargo build -p workshop`. The root manifest of `runvil-harness` omits the setting, and a plain `cargo build` there builds all 17 crates of that workspace. +`default-members` in the root manifest of `runvil-workshop` lists every crate except the desktop crates. It omits the desktop app `workshop`, `workshop-server`, and `workshop-server-api`, which are the crates that need Node.js or the Tauri system packages, so a fresh clone on macOS or Linux builds the rest with only Rust. A developer builds the desktop app by name, with `cargo build -p workshop`. The root manifest of `runvil-harness` omits the setting, and a plain `cargo build` there builds every crate of that workspace. -The setting exists because a build of every crate of `runvil` fails on a macOS or Linux machine that has only Rust. +The setting exists because a build of every crate of `runvil-workshop` fails on a macOS or Linux machine that has only Rust. ### A build writes the UI bundle to `OUT_DIR` The `build.rs` of `workshop-server` calls `build_sibling` in the `build-ui` crate, which runs esbuild on `crates/workshop/ui` and writes the bundle to `$OUT_DIR/ui-dist/`. `rust-embed` reads that folder from disk in a debug build and embeds it in a release build. A build needs Node.js 22 and one `npm ci` in `crates/workshop`, the root of an npm workspace with the members `ui`, `look`, and `platform`. -Every build step writes outside the folders that git tracks. The helper refuses `npx`, because `npx` can download a different version and produce different output. Four CI jobs of `runvil` end with a `Clean tree` step, which fails when `git status` reports a change. +Every build step writes outside the folders that git tracks. The helper refuses `npx`, because `npx` can download a different version and produce different output. CI jobs of `runvil-workshop` end with a `Clean tree` step, which fails when `git status` reports a change. ### `cargo workshop` builds the desktop app with a staged Gateway binary -`cargo workshop` is an alias for the `build-workshop` crate. It stages a Gateway binary under `crates/workshop/desktop/binaries/` and builds the `workshop` package. It takes the binary from `--gateway-binary`, then from `RUNVIL_GATEWAY_SIDECAR`, then from a file already staged. With all three absent, the command stops and names `node tools/fetch-gateway-sidecar.mjs`, which downloads the release in `gateway-pin/pin.json` and verifies its checksum. +`cargo workshop` is an alias for the `build-workshop` crate. It places a Gateway binary where Workshop finds it, which is the sidecar slot under `crates/workshop/desktop/binaries/` for a Windows target and the target directory beside Workshop elsewhere, and it builds the `workshop` package. It takes the binary from `--gateway-binary`, then from `RUNVIL_GATEWAY_SIDECAR`, then from a file already staged. With all three absent, the command stops and names `node tools/fetch-gateway-sidecar.mjs`, which downloads the release in `gateway-pin/pin.json` and verifies its checksum. `cargo workshop bundle` builds one platform's Tauri bundle with the same Gateway sources, and `cargo installer` in `runvil` makes the installer from that bundle. The root `AGENTS.md` states the rule for run time: "Runtime and serve paths never compile native dependencies or invoke build tools". [The Gateway](gateway.md) covers how the Gateway obtains its `llama-server` program. @@ -280,17 +276,17 @@ The root `AGENTS.md` states the rule for run time: "Runtime and serve paths neve ### Each `ci.yml` runs its jobs behind one required job -Each repository's workflow runs on a push to `master` or `main` and on every pull request. In `runvil` its nine jobs are `fmt`, `clippy`, `test`, `docs`, `check-workshop`, `check-workshop-linux`, `ui`, `supply-chain`, and `dylint`. In `runvil-harness` its ten jobs are `fmt`, `clippy`, `test`, `test-windows`, `docs`, `wording`, `supply-chain`, `api-surface`, `dylint`, and `msrv`. `ci-green` lists the jobs of its workflow in `needs:` and fails when any result differs from success. The workflow's comment warns that the list is static, so "every newly added job must be added to it". Branch protection then requires one status, `ci-green`. +Each repository's workflow runs on a push to `master` or `main` and on every pull request. In `runvil-workshop` its jobs are `fmt`, `clippy`, `test`, `docs`, `check-workshop`, `check-workshop-linux`, `ui`, `supply-chain`, and `dylint`. In `runvil-harness` its jobs are `fmt`, `clippy`, `test`, `test-windows`, `docs`, `wording`, `supply-chain`, `api-surface`, `dylint`, and `msrv`. In `runvil` its jobs are `fmt`, `clippy`, `test`, `docs`, `wording`, `supply-chain`, and `dylint`. `ci-green` lists the jobs of its workflow in `needs:` and fails when any result differs from success. The workflow's comment warns that the list is static, so "every newly added job must be added to it". Branch protection then requires one status, `ci-green`. -### The three desktop crates have their own Windows job +### The desktop crates have their own Windows job -In `runvil`, the workspace-wide clippy, test, and docs commands exclude `workshop`, `workshop-server`, and `workshop-server-api`. The `check-workshop` job lints and tests them on `windows-latest`. `check-workshop-linux` compiles the desktop app on Ubuntu 22.04 with the Tauri system packages. Both jobs stage a stub Gateway binary with `node tools/fetch-gateway-sidecar.mjs --stub`. +In `runvil-workshop`, the workspace-wide clippy, test, and docs commands exclude `workshop`, `workshop-server`, and `workshop-server-api`. The `check-workshop` job lints and tests them on `windows-latest`. `check-workshop-linux` compiles the desktop app on Ubuntu 22.04 with the Tauri system packages. Both jobs stage a stub Gateway binary with `node tools/fetch-gateway-sidecar.mjs --stub`. Their job runs on Windows because the desktop crates need GUI packages that the Ubuntu runner lacks, and Workshop ships on Windows. The Linux job compiles the app so that CI catches the failures of a Linux build, which the Windows job misses. -### CI denies rustdoc warnings and documents two crates with private items +### CI denies rustdoc warnings and documents the private items of some crates -Each repository's `docs` job sets `RUSTDOCFLAGS` to `-D warnings` and runs `cargo doc` for its workspace. The job of `runvil-harness` also runs it for each facade with default features, and for `runvil-runtime` with `--document-private-items`. The Windows job of `runvil` does the same for `workshop-server`. A doc link whose target has moved or has a new name then fails CI. +Each repository's `docs` job sets `RUSTDOCFLAGS` to `-D warnings` and runs `cargo doc` for its workspace. The job of `runvil-harness` also runs it for each facade with default features, and for `runvil-runtime` with `--document-private-items`. The `check-workshop` job of `runvil-workshop` does the same for `workshop-server`. A doc link to an item that does not exist then fails CI. The steps for private items are in CI because a line in `AGENTS.md` would rely on each author to remember it. [Guides and docs](guides-and-docs.md) covers the build of the docs site. @@ -302,54 +298,46 @@ The setting is limited to those two so that a new Rust lint leaves every local b ## 9. Releases and installers -### A `workshop-v` tag builds seven installers for five targets +### A `v` tag in `runvil` builds an installer for each target -`release-workshop.yml` starts on a tag such as `workshop-v0.3.0`. Its `build` job runs `tauri-action` on five runners, one for each target: Windows x64, macOS ARM and Intel, and Linux x64 and ARM64. The Tauri bundler produces an NSIS installer, two DMGs, two debs, and two AppImages. Each runner first stages the Gateway binary that `gateway-pin/pin.json` names and checks its version. +`runvil/.github/workflows/installers.yml` starts on a tag such as `v0.3.0`. Its `build` job runs `cargo installer --sign` on a runner for each target: Windows x64, macOS ARM and Intel, and Linux x64 and ARM64. `cargo installer` runs `cargo workshop bundle` in the `runvil-workshop` checkout and makes the installer from the bundle. The Windows installer is the NSIS setup from that bundle, with the Gateway inside. The macOS installers are DMGs and the Linux installers are `.run` files, built with the Qt Installer Framework, and each installs Workshop and the Gateway as separate components. Each runner first stages the Gateway release that `gateway-pin/pin.json` of the checkout names, and the build refuses a Gateway of another version. -Each product has its own tag prefix, because cargo-dist and `tauri-action` each create the release for a tag and would conflict on one tag. The Gateway's releases use cargo-dist and `gateway-v` tags, which `dist-workspace.toml` in the `runvil-gateway` repository sets. +Each product has its own tag prefix, so a tag starts the release of one product. The Gateway's releases use cargo-dist and `gateway-v` tags, which `dist-workspace.toml` in the `runvil-gateway` repository sets. ### A release publishes after every installer passes an install test -The `test` job downloads each installer to a fresh runner of the same kind, installs it, runs `runvil-workshop --version`, starts the app, and requests its page and `app.js`. It fails when the version differs from the workspace version or when `app.js` exceeds 3,000,000 bytes. The `publish` job needs `test`, so a failed test stops the release. +The `test` job downloads each installer to a fresh runner of the same kind and runs one cell for each component selection: all, Workshop only, and Gateway only on every platform, and Gateway with Speech to Text on Windows. A cell installs the selection and checks that exactly the selected components are present. It runs `--version` on each installed program and fails when Workshop prints another version than the workspace version or the Gateway another than the pinned one. It checks that Workshop loads its library Plugins, starts the app, and requests its page and `app.js`, which must stay under 3,000,000 bytes, and it requests the Gateway's `/config/` page. The `publish-release` job needs `test` and `manifest`, so a failed cell stops the release. -A manual run of the workflow builds unsigned installers, runs the same tests, and stops before `publish`. The mode exists so that a developer can test how an unsigned installer installs, independently of a release. +A manual run of the workflow builds every platform, runs every cell, and stops before `publish-release`, and the installers stay as workflow artifacts for 7 days. A pull request that touches the installer paths runs the `all` and `workshop` cells for each platform. Every mode builds with `--sign`: outside a release the key is one that the `prepare` job generates and nothing trusts, so the `manifest` job checks the same signatures that a release has. ### The rolling `workshop-latest` release has the updater manifest and version-free installer names -After it publishes a versioned release, the `publish` job uploads two things to the release named `workshop-latest`. The first is `latest.json`, the manifest that the Tauri updater in an installed Workshop reads. The second is a copy of each installer under a fixed name, such as `Runvil-setup.exe` and `Runvil-arm64.dmg`. The workflow signs the updater bundles with a minisign key from GitHub secrets. +After it publishes a versioned release, the `publish-release` job uploads these files to the release named `workshop-latest`. One is `latest.json`, the manifest that the Tauri updater in an installed Workshop reads, which `cargo installer manifest` writes after it verifies each updater signature. Another is a copy of each installer under a fixed name, such as `Runvil-setup.exe` and `Runvil-arm64.dmg`. A release build signs the updater files with a minisign key from GitHub secrets. The fixed names make each direct download URL stable across versions. The names are on the release that has `latest.json`, because a tag of their own would be a second rolling release to look after. [Workshop: how the app is built](workshop-app.md) covers the updater. -### `nightly.yml` replaces one prerelease named `nightly` - -The workflow runs on a push to `master` and on a manual start. Its `check` job compares `HEAD` with the commit of the `nightly` tag and skips the build when they match. The `workshop` job builds on the same five runners as a release, and the nightly skips the install tests. The `publish` job deletes the previous `nightly` release and tag, and creates a new prerelease with the installers and a `SHA256SUMS` file. - -One rolling release stops the nightly builds from competing with real releases for storage and attention. The workflow runs on each push so that a fork can test it, and section 10 lists a daily schedule as planned work. - ### The Windows installer offers Workshop, the Gateway, and speech to text as components -`crates/workshop/desktop/installer.nsi` is a custom NSIS template with a components page and three sections: `Runvil Workshop`, `Runvil Gateway`, and `Speech to Text (Transcription)`. The installer includes the Gateway binary as a Tauri `externalBin`. The speech section has an empty body: the installer records the choice in the registry value `InstallSTT`, which the Gateway reads when it generates its first config. An update run restores the saved choices, stops a running Gateway, and restarts it. +`crates/workshop/desktop/installer.nsi` is a custom NSIS template with a components page and these sections: `Runvil Workshop`, `Runvil Gateway`, and `Speech to Text`, whose label also states the size of the download. The installer includes the Gateway binary as a Tauri `externalBin`. The speech section has an empty body: the installer records the choice in the registry value `InstallSTT`, which the Gateway reads when it generates its first config. An update run restores the saved choices, stops a running Gateway, and restarts it. -The components allow two partial installs: the Gateway only, which is the headless server install, and Workshop only, which is a client that attaches to a Gateway over the local network. The custom template repeats the updater's command-line switches, because the updater otherwise fails silently. +The components allow partial installs: the Gateway only, which is the headless server install, and Workshop only, which is a client that attaches to a Gateway over the local network. The custom template repeats the updater's command-line switches, because the updater otherwise fails silently. ## 10. Planned work Each of these items is still to be built. -- **Platform code signing.** A Windows certificate and a macOS Developer ID that sign the installers. The release workflow marks with a comment where each belongs, and it signs only the updater bundles, with the minisign key. Unsigned installers block a launch in managed environments. -- **The nightly's schedule.** A daily schedule for `nightly.yml`, with a guard on the repository name. The workflow runs on every push to `master` and on a manual start. -- **One check command.** A `cargo xtask check` that runs every command of the Verification list in `AGENTS.md`, and Cursor hooks that run it. A developer runs each command of that list, and `.githooks/pre-push` runs three checks before a push. -- **Surface listings for two more crates.** A `public-api.txt` for `runvil-plugin` and one for `workshop-server-api`. `cargo xtask api` checks the two facades. +- **Platform code signing.** A Windows certificate and a macOS Developer ID that sign the installers. The installers workflow signs only the updater files, with the minisign key. Unsigned installers block a launch in managed environments. +- **One check command.** A `cargo xtask check` that runs every command of the Verification list in `AGENTS.md`, and Cursor hooks that run it. A developer runs each command of that list, and `.githooks/pre-push` runs a scan of rulebook wording, clippy, and `cargo deny` before a push. +- **Surface listings for more crates.** A `public-api.txt` for `runvil-plugin` and one for `workshop-server-api`. `cargo xtask api` checks the facades. - **Private-item docs for more crates.** The private-item docs step of section 8 for `runvil-lua` and the Harness crates. CI documents the private items of `runvil-runtime` and `workshop-server`. -- **More determinism bans for Engine crates.** Clippy's `iter_over_hash_type` lint, and bans for `Instant::elapsed`, `RandomState::default`, and `HashMap::new`. The three Engine `clippy.toml` files have the eight determinism bans that section 5 describes. +- **More determinism bans for Engine crates.** Clippy's `iter_over_hash_type` lint, and bans for `Instant::elapsed`, `RandomState::default`, and `HashMap::new`. The Engine `clippy.toml` files have the determinism bans that section 5 describes. - **A scaffold for other families.** `cargo xtask new-crate` for a crate outside the Workshop family. The command accepts a `workshop-*` name and refuses any other. ## 11. Known gaps Each item names two parts of the code or its configuration that disagree. -1. The toolchain of two workflows. `rust-toolchain.toml` pins channel `1.99`. `nightly.yml` and `workshop-installer-smoke.yml` set `RUSTUP_TOOLCHAIN: stable`, so those two workflows compile with the newest stable release, while CI and a tagged release compile with 1.99. -2. The Gateway's containers. The root `Cargo.toml` of `runvil-gateway` describes `crates/gateway/` and `crates/gateway/stt/` as containers of "the gateway's private crates". `all_violations` in `crates/build-xtask/src/tidy.rs` of that repository runs lint inheritance, a check that each `build.rs` calls the file-size limit, the unsafe allowlist, the walled admin tier, the doctest ban, and the `Debug` spelling. A crate at the root of `crates/` can depend on one of the private crates and pass every check. +1. The Gateway's containers. The root `Cargo.toml` of `runvil-gateway` describes `crates/gateway/` and `crates/gateway/stt/` as containers of "the gateway's private crates". `all_violations` in `crates/build-xtask/src/tidy.rs` of that repository runs lint inheritance, a check that each `build.rs` calls the file-size limit, the unsafe allowlist, the walled admin tier, the doctest ban, and the `Debug` spelling. A crate at the root of `crates/` can depend on one of the private crates and pass every check. ## 12. Questions for the owner @@ -369,23 +357,15 @@ Each question asks for the reason behind a part of the design. **Toolchain and CI** -7. Why do `nightly.yml` and `workshop-installer-smoke.yml` set `RUSTUP_TOOLCHAIN: stable` while `rust-toolchain.toml` pins Rust 1.99? -8. Why is `CARGO_BUILD_WARNINGS=deny` limited to CI and the pre-push hook? With the toolchain pinned, a new lint appears only when the pin changes, so `.cargo/config.toml` could set it for every build. +7. Why is `CARGO_BUILD_WARNINGS=deny` limited to CI and the pre-push hook? With the toolchain pinned, a new lint appears only when the pin changes, so `.cargo/config.toml` could set it for every build. **Releases** -9. Why does `release-workshop.yml` require the workspace version 0.3.0? `AGENTS.md` tells authors to "never bump a format, schema, or crate version number". +8. Why does `installers.yml` require a release tag to name the workspace version 0.3.0? `AGENTS.md` tells authors to "never bump a format, schema, or crate version number". ## 13. Method and limits -- **Code.** The page describes `runvil` at commit `fa9936f64`, `runvil-gateway` at `9369a7d`, and `runvil-plugin-api` at `63a2403`. -- **Checks.** The facts on this page were read in the code at those commits. A second session checked the gaps, the values, and the walk-through against the code. +- **Checks.** The facts on this page were read in the code. A second session checked the gaps, the values, and the walk-through against the code. - **Limits.** The sessions read the code and its tests, and left the build and the tests unrun. -- **Update.** On 2026-11-12 the text on workspaces, crates, dependency rules, structural checks, and CI jobs was brought to `runvil` at commit `48a4dbc08` and `runvil-harness` at `5bca6f9`. Commit `adca9db10` of `runvil` removed the Engine, Harness, and Plugin crates, which are in `runvil-harness` with their history, and pinned four of them by commit. Commit `df857f4b1` added the check `harness_pin`. Earlier commits added the Engine crate `runvil-markdown` and the Workshop crate `workshop-plugin-bashkit`. The update covers the first paragraph of the summary, the second and third paragraphs of the walk-through, sections 1 and 2, the paths and the `supply-chain` sentence of section 3, the paths of section 4, seven entries of section 5, two entries of section 6, the first three entries of section 7 and the count of jobs with a `Clean tree` step, and three entries of section 8. Section 2 has one new entry, on the pin. The history of `runvil-harness` was written a second time on 2026-11-12, to include the plan and vibe records of the Engine and the Harness, and commit `48a4dbc08` of `runvil` moved the pin to `5bca6f9` in that history. -- **Earlier update.** On 2026-11-11 the crate counts, the families, the family matrix, the Workshop tier tables, and the git dependencies were brought to `runvil` at commit `b0693699d`, after `std` became a library Plugin and the `shared-*` family left the matrix. The update of 2026-11-12 replaces that text. -- **Still at `fa9936f64`.** The text on installers, releases, and the workflows that build them still describes `runvil` at `fa9936f64`: the sentences of the summary and of section 7 that name those workflows, the last paragraph of the walk-through, section 9, the first two items of section 10, gap 1, and questions 7 and 9. `runvil` at `48a4dbc08` has one workflow for installers, `installers.yml`. Each sentence outside the update of 2026-11-12 also describes `fa9936f64`. -- **Update.** On 2026-11-13 two entries of section 2, on the pin and on the dependency rule for Plugin crates, were brought to `runvil-harness` at commit `18361d02`, `runvil-plugin-std` at `ee04d10`, and `runvil-plugin-bashkit` at `9c8e980`. The update states that the rule covers the two Rust Plugins, that a Plugin on the C contract depends on zero crates of `runvil-harness`, and that one Plugin API is planned work. That session read the code and left the build and the tests unrun. -- **Update.** On 2026-11-19 the count of serde crates in the entry on `cargo xtask api`, in section 4, was brought to `runvil-harness` at commit `ee199e3a`. The surface check allows three serde crates, `serde`, `serde_core`, and `serde_json`, where the page named four: commit `0d938885` of that repository took `serde_yaml_ng` off the list. That session read the code and left the build and the tests unrun. -- **Still to update.** Commit `25d19f3f6` of `runvil` removed Workshop and its build tooling, which are in the repository `runvil-workshop`. The text of the page on workspaces, crate counts, families, the pin, the git dependencies, and the place of Workshop's checks still describes Workshop inside `runvil`. *2026-11-10 16:47 - Claude Fable 5.2* diff --git a/decisions/engine.md b/decisions/engine.md index 956b528..c15f3f1 100644 --- a/decisions/engine.md +++ b/decisions/engine.md @@ -1,17 +1,13 @@ # The Engine: design decisions and their reasons - Scope: the Engine as a library: parsing a prompt, the run state machine, effects and their answers, run limits, the one error type, the public surface, and the internal crates -- Code: `runvil` at commit `fa9936f64`, and `runvil-docs` at commit `cfd69a4` -- Update: the Paths bullet names the repositories as of `runvil` at commit `48a4dbc08` and `runvil-harness` at `5bca6f9`, after the Engine and the Harness moved (section 12) -- Update: the entry on how a run ends in section 3, the entry on section entries in section 5, and the questions of section 11 state the rules of the second change that follows `8de43c2f` in `runvil-harness`: every heading starts a section, and the code before the first heading is the preamble (section 12) -- Update: the text on file operations as effects, on the file requests of a tool call, on closed enums, and on effect records describes `runvil-harness` at commit `ee199e3a`, and so do the owner's reasons in six entries, the questions of section 11, and the counts of sections 1 to 8 (section 12) -- Paths: code paths start at the `crates/` folder of `runvil-harness`, the repository of the Engine and the Harness, and a path that begins with `workshop/` starts at the `crates/` folder of `runvil` +- Paths: code paths start at the `crates/` folder of `runvil-harness`, the repository of the Engine and the Harness ## Summary -The Engine is a Rust library that parses a prompt file and runs it as a state machine. `Prompt::parse` compiles each Lua block and returns a `Prompt`, which also holds every prompt that it lists for `execute`, and `Run::new` builds a `Run` from it. Each `Run::step` runs the prompt's Lua until the run waits for answers and returns the effects the run needs: model rounds, Pack renders, Pack tool calls, file operations, and timers. The caller performs each effect and passes its answer to `Run::resume`. A tool whose call is open asks the caller for each file operation it needs, and the caller reports the request with `Run::request_file`, so the run issues that operation as an effect too. A run ends with its final text or with one `Error`. Seven private crates contain the code, and `runvil-engine` re-exports the 105 names a caller uses. Sections 1 to 8 describe these parts. +The Engine is a Rust library that parses a prompt file and runs it as a state machine. `Prompt::parse` compiles each Lua block and returns a `Prompt`, which also holds every prompt that it lists for `execute`, and `Run::new` builds a `Run` from it. Each `Run::step` runs the prompt's Lua until the run waits for answers and returns the effects the run needs: model rounds, Pack renders, Pack tool calls, file operations, and timers. The caller performs each effect and passes its answer to `Run::resume`. A tool whose call is open asks the caller for each file operation it needs, and the caller reports the request with `Run::request_file`, so the run issues that operation as an effect too. A run ends with its final text or with one `Error`. Private crates contain the code, and `runvil-engine` re-exports each name a caller uses. Sections 1 to 8 describe these parts. -A check of this page against the code found two gaps and left three questions about reasons for the owner. Section 10 lists the gaps, and section 11 lists the questions. The largest gap is in chapter 16 of the language guide, which teaches six parse error kinds and calls the set open, while the code has one closed `ErrorCode` enum. +Section 10 lists the gaps between this page and the code, and section 11 lists the questions about reasons for the owner. The largest gap is in chapter 16 of the language guide, which teaches parse error kinds and calls the set open, while the code has one closed `ErrorCode` enum. Section 9 lists the planned work. Its largest item is replay: Harness code that runs a recorded run a second time and compares the records of the two runs. @@ -37,21 +33,21 @@ An effect is a Rust value that describes one piece of outside work, such as a mo The Engine returns this work as values so that it is independent of any runtime and is a deterministic function of its inputs. -### The Engine returns five kinds of work as effects and performs the rest itself +### The Engine returns each kind of outside work as an effect and performs the rest itself -`Effect` has five variants: `Chat` for one model round, `Render` for a Pack's rendering of offered tools, `ToolCall` for one call of a Pack's tool, `Vfs` for one file operation, and `Timer` for one sleep. A file operation is a `store` call of the prompt's Lua, or a file request of an open tool call. [Tools and Packs](tools-and-packs.md) covers `Render` and `ToolCall`. +`Effect` has a variant for each kind of work: `Chat` for one model round, `Render` for a Pack's rendering of offered tools, `ToolCall` for one call of a Pack's tool, `Vfs` for one file operation, and `Timer` for one sleep. A file operation is a `store` call of the prompt's Lua, or a file request of an open tool call. [Tools and Packs](tools-and-packs.md) covers `Render` and `ToolCall`. -The Engine performs three kinds of work itself and reports each as an event: an adhoc tool call, a `GetDynamicTools` call, and a refused discovery call. +The Engine performs other work itself and reports each piece as an event: an adhoc tool call, a `GetDynamicTools` call, and a refused discovery call. ### The caller supplies the start time and a 256-bit seed -`RunParams::new` takes a `RunSeed` and a `Timestamp`, and nine `with_` setters add a run's other inputs. Lua reads the timestamp as `sys.when`, every timeout is a `Timer` effect, and clippy rejects a clock read in an Engine crate. The same prompt, arguments, params, and answers produce the same effects, events, and result ([Tasks and fanout](tasks-and-fanout.md)). +`RunParams::new` takes a `RunSeed` and a `Timestamp`, and the `with_` setters add a run's other inputs. Lua reads the timestamp as `sys.when`, every timeout is a `Timer` effect, and clippy rejects a clock read in an Engine crate. The same prompt, arguments, params, and answers produce the same effects, events, and result ([Tasks and fanout](tasks-and-fanout.md)). The seed is 32 bytes, and the Engine derives from it, with SHA-256, the nonce of the envelope that it wraps around untrusted text ([Tools and Packs](tools-and-packs.md)). A 64-bit seed would cap the nonce's unpredictability at 64 bits. ### Plugin code and wire code are outside the Engine -The Engine receives each tool as a `ToolInfo`, each Pack prelude as Lua source, and each model reply as a `Completion`. `runvil-plugin`, the crate with the `Pack` trait, depends on two Engine crates, and the Engine crates are independent of it. The Engine sees only a Pack's descriptors, preludes, and ids. A Pack whose tool calls the Harness performs is a catalog Pack in Engine code. The name leaves the Harness out, because Engine crates name the Harness only to assign it a responsibility. +The Engine receives each tool as a `ToolInfo`, each Pack prelude as Lua source, and each model reply as a `Completion`. `runvil-plugin`, the crate with the `Pack` trait, depends on Engine crates, and the Engine crates are independent of it. The Engine sees only a Pack's descriptors, preludes, and ids. A Pack whose tool calls the Harness performs is a catalog Pack in Engine code. The name leaves the Harness out, because Engine crates name the Harness only to assign it a responsibility. The Harness's gateway client parses SSE streams and OpenAI bodies, because the Engine is neutral about the transport. @@ -59,7 +55,7 @@ The Harness's gateway client parses SSE streams and OpenAI bodies, because the E ### `Prompt::parse` takes a `PromptFinder` and a name, and the name identifies the prompt -`PromptFinder` is a trait with one method, `find(name)`, which returns a prompt's source text. `Prompt::parse(finder, name)` calls it and parses the text, and a closure of the form `Fn(&str) -> Result` is a finder. `Prompt::file` and every failure name the prompt by the caller's name for it, such as `research.md`. +`PromptFinder` is a trait with the method `find(name)`, which returns a prompt's source text. `Prompt::parse(finder, name)` calls it and parses the text, and a closure of the form `Fn(&str) -> Result` is a finder. `Prompt::file` and every failure name the prompt by the caller's name for it, such as `research.md`. Prompts refer to each other by these names. A prompt's `prompts:` list names the prompts that its Lua may run with `execute`, and the parse keeps each prompt it has reached under its name, so the name is also the key that tells the parse it has a prompt already. @@ -77,15 +73,17 @@ The parser compiles each `lua` fence into a `LuaProgram`, which contains the sou ### A parsed prompt has one shared body string, and the Engine reads it in place -The parser stores the prompt's body, the text after the front matter, as one `Arc`. A `BodyText` is a handle to that string plus a byte range, and each section's raw Markdown, prose blocks, and list items are `BodyText` values. A run reads sections through `Visible`, a borrowed view of the sections that a running section may name. +The parser stores the prompt's body, the text after the front matter, as one `Arc`. A `BodyText` is a handle to that string plus a byte range, and each section's raw Markdown and prose blocks are `BodyText` values. A chain names a section with a `SectionPos`, a path of indices that a lookup resolves against the shared `Prompt`, so a chain borrows nothing from the tree. -### One function, `find_visible`, looks up every heading in a visible set +### One module resolves every section path, and a hidden section looks the same as a missing one -A running section may name its siblings and its direct children by heading, and that list is its visible set ([The prompt language](prompt-language.md)). `find_visible` searches the set for `jump`, `call`, a task spawn, and a `prompt.section` or `prompt.list` read. `read_visible` turns a miss into `nil`, and `resolve_visible` turns it into an error. A heading outside the set and a heading absent from the file get the same answer, because telling them apart would need the whole document, and a miss would then reveal what the visible-set rule hides. `require` searches a wider set with a second function, `find_reachable`. +A running section may name its siblings and its direct children, and that list is its visible set ([The prompt language](prompt-language.md)). Lua names a section by a path: `name` for a direct child, `../name` for a sibling, and `/a/b` from the top of the prompt. The module `section_path` in `runvil-internal/runtime/src/` holds the lookup, with one entry for each rule about which forms a function takes. `resolve_neighbor` serves `jump`, `call`, a task spawn, and a fanout worker, and takes the relative forms. `find` serves `prompt.section` and `prompt.section_or`, and takes every form. `resolve_from_top` serves `require`, and takes only a path from the top. The functions `resolve_jump_target`, `read_section`, and `resolve_library` in `runvil-internal/runtime/src/execute/walk_target.rs` call them. + +A well-formed path that names no section is a miss. A miss raises the not-found error for `jump`, `call`, a task spawn, `require`, and `prompt.section`, and `prompt.section_or` returns `nil`. A relative path to a section outside the visible set and a relative path to a section absent from the file get the same answer, because the lookup searches only the children or the siblings of its starting section, and the error names where it looked and lists no section. Telling the two cases apart would need the whole document, and a miss would then reveal what the visible-set rule hides. ## 3. The run state machine -### A caller steps a run with five functions +### A caller steps a run with the functions of `Run` `Run::new(prompt, args, params)` builds a run, and `args` is the text of the run's arguments, one JSON object. The run holds `prompt` and every prompt it links, so a caller passes the prompt that `Prompt::parse` returned. `Run::step` advances it until it needs an answer and returns a `Step`. `Run::resume(id, answer)` delivers the answer to one effect. `Run::deliver(text)` queues a message for the main chain's inbox ([The Harness and the Host API](harness-and-host.md)). `Run::request_file(call, op)` reports one file request of an open tool call, and the next `Run::step` returns the operation as a `Vfs` effect. `Run` is `Send` and owns its prompt through an `Arc`. @@ -105,7 +103,7 @@ The request goes through the Engine so that the run's record holds every file op ### `Run::new` always succeeds, and the first `step` checks that the run can start -The first `Run::step` calls `check_start`, which makes three checks in order. The prompt and every prompt it links declare `runvil: 0`. The arguments are one JSON object that matches the prompt's `args:` declaration ([The prompt language](prompt-language.md)): `Run::new` reads the text and keeps a mismatch for this check, which returns it with the code `args_invalid` and no location. The params meet what each of those prompts requires: each Pack under a `uses:` is `Usable` in the roster that the caller passed to `RunParams::with_packs`, and the model in each role that a prompt declares meets that prompt's requirements for the role. A requirements failure has the code `requirements_unmet`, and its message names every gap. +The first `Run::step` calls `check_start`, which makes its checks in order. The prompt and every prompt it links declare `runvil: 0`. The arguments are one JSON object that matches the prompt's `args:` declaration ([The prompt language](prompt-language.md)): `Run::new` reads the text and keeps a mismatch for this check, which returns it with the code `args_invalid` and no location. The params meet what each of those prompts requires: each Pack under a `uses:` is `Usable` in the roster that the caller passed to `RunParams::with_packs`, and the model in each role that a prompt declares meets that prompt's requirements for the role. A requirements failure has the code `requirements_unmet`, and its message names every gap. `Run::new` returns a `Run` and never an error, so every failure of a run, a failed start check included, reaches the caller in one place: the `result` of `Step::Done`. The caller handles a failed run there already, and a failure out of `Run::new` would need a second path that records and reports the same thing. `Run::step` and `Run::resume` return no error either. The owner's reason: "having one place for the error is better than two". @@ -113,13 +111,13 @@ The checks cover the linked prompts because a run may execute any of them. The o ### A step returns its effects and its events as values -`Step::Pending` has four fields: `effects`, `events`, `withdrawn`, and `waiting_for_input`. Each element of `effects` is an `IssuedEffect` with an `id`, a `provenance`, and the `effect`. `events` lists what the run reported since the previous step. Because a step returns effects and events as values, the Engine is pure, the Harness receives one ordered stream, and a test asserts on a vector. The caller receives events one step at a time, and a step runs at the speed of its Lua. +`Step::Pending` has the fields `effects`, `events`, `withdrawn`, and `waiting_for_input`. Each element of `effects` is an `IssuedEffect` with an `id`, a `provenance`, and the `effect`. `events` lists what the run reported since the previous step. Because a step returns effects and events as values, the Engine is pure, the Harness receives one ordered stream, and a test asserts on a vector. The caller receives events one step at a time, and a step runs at the speed of its Lua. An `EffectId` may differ between runs. The `provenance`, a task and a position within it, is the same in every run with the same inputs and answers. ### `Step`, `Effect`, `EffectAnswer`, `VfsAsker`, `VfsOp`, and `VfsOutcome` are closed enums -The six enums omit the `#[non_exhaustive]` attribute. A `match` that names every variant of one of them needs no wildcard arm, and a new variant fails the build at each such `match`. The Harness matches `Step`, `Effect`, and `EffectAnswer` values. With `#[non_exhaustive]` it would need wildcard arms, and it would still compile after the Engine gains a variant. +These enums omit the `#[non_exhaustive]` attribute. A `match` that names every variant of one of them needs no wildcard arm, and a new variant fails the build at each such `match`. The Harness matches `Step`, `Effect`, and `EffectAnswer` values. With `#[non_exhaustive]` it would need wildcard arms, and it would still compile after the Engine gains a variant. `VfsAsker`, `VfsOp`, and `VfsOutcome` are closed for the same reason. The asker of a `Vfs` effect settles the answer that the effect takes, so a caller has a rule for each asker. Each place with a rule for every operation or every outcome, such as the code that performs a file operation, records it, or makes its receipt, names every variant, so a new variant fails the build there. With `#[non_exhaustive]`, each such place would need a wildcard arm, and the record of a run would hold nothing for an operation or an outcome that is new to the record code. The owner's words on the attribute: "I would expect that if they are extended, then all call sites should break, no?" The owner's rule: "also VfsAsker, and VfsOp I think should fail to build if a new thing is added and call sites are not updated." And on `VfsOutcome`: "Yeah close VfsOutcome too." @@ -127,9 +125,9 @@ The six enums omit the `#[non_exhaustive]` attribute. A `match` that names every ### Every effect gets exactly one answer, and `Dropped` is an answer -`EffectAnswer` has seven variants: one for each of the five effect kinds, a second one for the `Vfs` kind, and `Dropped`. A `Vfs` effect takes `Vfs` when the prompt's Lua asked for it and `VfsReceipt` when a tool call did. A caller that abandons an effect answers it `Dropped`, and the chain that waited resumes with the canceled error. The chain of a tool call waits on the call and on none of its file effects, so `Dropped` for one of those resumes nothing, and the tool call still needs its own answer. `Run::step` returns `Step::Done` once the caller has answered every issued effect, so a file operation still in progress finishes inside the run's file scope. +`EffectAnswer` has a variant for each effect kind, a second one for the `Vfs` kind, and `Dropped`. A `Vfs` effect takes `Vfs` when the prompt's Lua asked for it and `VfsReceipt` when a tool call did. A caller that abandons an effect answers it `Dropped`, and the chain that waited resumes with the canceled error. The chain of a tool call waits on the call and on none of its file effects, so `Dropped` for one of those resumes nothing, and the tool call still needs its own answer. `Run::step` returns `Step::Done` once the caller has answered every issued effect, so a file operation still in progress finishes inside the run's file scope. -Four mistakes in an answer end the run with an `internal` error: an answer of the wrong kind, a `Vfs` answer of the other form, an answer for an unknown id, and a second answer for one effect. The Engine discards an answer for an effect whose chain stopped waiting. +These mistakes in an answer end the run with an `internal` error: an answer of the wrong kind, a `Vfs` answer of the other form, an answer for an unknown id, and a second answer for one effect. The Engine discards an answer for an effect whose chain stopped waiting. ### A step lists the effects it withdraws @@ -145,7 +143,7 @@ The two polls follow one rule: the Engine honors a cancel while a block runs and ### A run ends with its final text or with one `Error` -`Step::Done` has three fields: `result`, `events`, and `unread`. `result` is a `Result`: `Ok` is the run's final text, a canceled run ends with the error whose code is `canceled`, and any other error is a failure. `unread` lists the messages still in the main chain's inbox. +`Step::Done` has the fields `result`, `events`, and `unread`. `result` is a `Result`: `Ok` is the run's final text, a canceled run ends with the error whose code is `canceled`, and any other error is a failure. `unread` lists the messages still in the main chain's inbox. A prompt declines its task by returning its reason from Lua, so the run completes and `result` is `Ok` with that text. A prompt that fails a check of its own, such as an `assert` on the range of an argument, raises a Lua error, and the run ends with the code `lua_runtime`, whichever section raised it ([The prompt language](prompt-language.md)). The code `requirements_unmet` belongs to the start checks alone. The code `args_invalid` belongs to the start check of the run's arguments and to an `execute` whose arguments the executed prompt's declaration refuses. @@ -161,19 +159,19 @@ A main chain that waits on its inbox is a different case: `step` returns `Pendin ### `Effect::Chat` contains the whole request -A `Chat` effect has five fields: the model `binding`, the `messages` in wire order, the `tools` schemas, the `round`, and `after`. The messages are the full request, so the caller can perform the round from the effect. The request settings are in the binding only: a second copy in the effect could differ from the binding, and the effect's record would then describe a request that differs from the one sent. +A `Chat` effect has these fields: the model `binding`, the `messages` in wire order, the `tools` schemas, the `round`, and `after`. The messages are the full request, so the caller can perform the round from the effect. The request settings are in the binding only: a second copy in the effect could differ from the binding, and the effect's record would then describe a request that differs from the one sent. `after` names the earlier round whose request this one extends, with the number of leading messages the two share, and the effect's record omits those messages. ### The Engine numbers the model rounds of a run from 0 -One counter numbers every model round of a run in issue order, and loop rounds and nested `models.infer` rounds share it. Each `Effect::Chat` has a `Round` with that `RoundId` and an origin, `Chat` or `Infer`. The Engine writes the same id in the round's thinking, reply, and tool-call events, so a caller that streams partial output matches it to the finished events. A `Round` has only these two values, because a caller needs only a round's id and whether the round is user-facing. +One counter numbers every model round of a run in issue order, and loop rounds and nested `models.infer` rounds share it. Each `Effect::Chat` has a `Round` with that `RoundId` and an origin, `Chat` or `Infer`. The Engine writes the same id in the round's thinking, reply, and tool-call events, so a caller that streams partial output matches it to the finished events. A `Round` holds only the id and the origin, because a caller needs only a round's id and whether the round is user-facing. ### `Effect::Vfs` is one file operation, and it says who asked -The Engine issues a `Vfs` effect for each of the eight `store.*` calls, and for each file request of an open tool call that the caller reports with `Run::request_file`. The effect has three fields: `asker`, `access`, and `op`, a `VfsOp` with the operation's arguments. `VfsOp` is one list of 15 operations in `runvil-vfs`: a `store` call uses one of the first eight, and a tool may ask for any of them. `asker` is a `VfsAsker`: `Lua` for a `store` call, with the id of the store that the call works on, and `Tool` for a tool's request, with the effect id of the tool call. The asker settles the files. A `store` call works on its chain's store, and `access` is the calling chain's view of that store. A tool's request works on the file system that the caller gave the run, and `access` is the call's own file access (section 3). A caller performs the operation with `Access::perform`, or with `perform_vfs_op(&access, &op)`, a synchronous function that calls it ([Files and the VFS](files-and-the-vfs.md)). +The Engine issues a `Vfs` effect for each `store.*` call, and for each file request of an open tool call that the caller reports with `Run::request_file`. The effect holds `asker`, `access`, and `op`, a `VfsOp` with the operation's arguments. `VfsOp` is one list of the file operations in `runvil-vfs`: a `store` call uses one of the operations that a `store.*` function names, and a tool may ask for any of them. `asker` is a `VfsAsker`: `Lua` for a `store` call, with the id of the store that the call works on, and `Tool` for a tool's request, with the effect id of the tool call. The asker settles the files. A `store` call works on its chain's store, and `access` is the calling chain's view of that store. A tool's request works on the file system that the caller gave the run, and `access` is the call's own file access (section 3). A caller performs the operation with `Access::perform`, or with `perform_vfs_op(&access, &op)`, a synchronous function that calls it ([Files and the VFS](files-and-the-vfs.md)). -A caller answers a `store` call with `EffectAnswer::Vfs`, the whole `VfsOutcome`, and the `store` call resumes with it. It answers a tool's request with `EffectAnswer::VfsReceipt`, once it has handed the whole outcome to the tool. `VfsReceipt` has five variants: `Stat` with a stat, `Bool` with a bool, `Count` with a number of entries or paths, `Bytes` with a number of bytes, and `Done`. `VfsReceipt::of` makes one from an outcome. The Engine gets the receipt alone, so it holds no copy of the bytes of a read. The answer to a tool's request resumes no chain, and a failure in it goes to the tool and leaves the run as it is, because the chain waits on the tool call and the tool decides what a failed operation means. The Engine reports no event for a tool's file operation: the effect record and the answer record are the view. A `store` call keeps its events. +A caller answers a `store` call with `EffectAnswer::Vfs`, the whole `VfsOutcome`, and the `store` call resumes with it. It answers a tool's request with `EffectAnswer::VfsReceipt`, once it has handed the whole outcome to the tool. `VfsReceipt` has the variants `Stat` with a stat, `Bool` with a bool, `Count` with a number of entries or paths, `Bytes` with a number of bytes, and `Done`. `VfsReceipt::of` makes one from an outcome. The Engine gets the receipt alone, so it holds no copy of the bytes of a read. The answer to a tool's request resumes no chain, and a failure in it goes to the tool and leaves the run as it is, because the chain waits on the tool call and the tool decides what a failed operation means. The Engine reports no event for a tool's file operation: the effect record and the answer record are the view. A `store` call keeps its events. A run has more than one store when a prompt executes another, so the effect of a `store` call names its store. The id is a `ChainId`: `0`, the id of the root chain, for the store that a run starts with, and the id of an executed prompt's chain, such as `0.0`, for a store that an `execute` made. The view alone would be enough to perform the operation, and the id is there for the record. @@ -202,7 +200,7 @@ The frame constructor creates the VM and applies the run's memory and log limits 1. It injects `args`, `sys`, and `var`. 2. It installs the Engine globals, such as `log` and `json`. 3. It installs `jump` and the `prompt` reads. -4. It installs the coroutine shims, `models.loop`, `call`, `execute`, and the eight `store` functions among them. +4. It installs the coroutine shims, `models.loop`, `call`, `execute`, and the `store` functions among them. 5. It runs the prelude of each Pack that the section's prompt declares. 6. It installs `require`. @@ -224,7 +222,7 @@ The workspace builds `mlua` 0.12 with the features `lua55`, `vendored`, `seriali ### `Request` is one closed enum, and every `Answer` variant is a success -Every call that suspends a block is one variant of `Request` in the Lua crate, with typed fields that the parse checks. The enum has 21 variants. A leaf request, such as `Infer` or `Store`, becomes an effect. A structural request, such as `Call`, `Execute`, or `Spawn`, changes which chains the scheduler runs. The enum is closed because it is the audit surface: one file lists everything a script can cause. +Every call that suspends a block is one variant of `Request` in the Lua crate, with typed fields that the parse checks. A leaf request, such as `Infer` or `Store`, becomes an effect. A structural request, such as `Call`, `Execute`, or `Spawn`, changes which chains the scheduler runs. The enum is closed because it is the audit surface: one file lists everything a script can cause. One request can become several effects. `ToolCalls` holds the unanswered tool calls of one model round, and `dispatch_tool_calls` in `runvil-internal/runtime/src/execute/scheduler/tool_call.rs` issues a `ToolCall` effect for each call of a Pack's tool, in the model's order, up to the first call that runs alone: a call of an adhoc tool or a discovery tool, or a call of a tool whose `ToolInfo` sets `changes_files`. The scheduler answers the request once each issued call has its answer. The loop then sends the call that stopped the batch alone, as a `ToolCall` request, and the calls after it as a new `ToolCalls` request. A call of a tool that changes files is therefore issued after every call listed before it has its answer, and the calls listed after it are issued once it has its own ([Tools and Packs](tools-and-packs.md)). @@ -238,15 +236,15 @@ The trampoline is Lua because a Rust function can yield only with mlua's `async` The loop's rules are in Rust because the loop works on the message list, and the list is a Rust object. A model's reply reaches the step function as a value that the trampoline passes along unread, and the step appends the records itself, so the Engine can keep data in the list that Lua never reads. The owner's reason: "we need to be able to manipulate the messages object. The messages object is in Rust". The owner expects to need this for requests to OpenAI endpoints and to Anthropic endpoints, which is planned work, and says of what the Engine then does with the list: "Lua can't see it." The Rust state machine also meets the owner's request that "the rules are unit-testable without a VM". The other calls with rules of their own, `tasks.fanout`, the `tasks` waits, and `require`, are Lua, and they work on values that Lua holds: task handles, results, and section code. -### The `Scheduler` owns five state objects, and a one-chain request runs in a `ChainOps` view +### The `Scheduler` owns its state objects, and a one-chain request runs in a `ChainOps` view -A `Run` owns one `Scheduler`, and the scheduler owns five objects, each with its own state and rules. `ChainArena` stores the chains, `EffectTable` lists the effects that await an answer, `TaskArena` stores the tasks, `Inboxes` stores unread messages, and `Admission` queues the chains that wait for a concurrency slot. The scheduler itself owns the ready queue and the run's phase, and it performs every action that writes to two of the five. +A `Run` owns one `Scheduler`, and the scheduler owns these objects, each with its own state and rules. `ChainArena` stores the chains, `EffectTable` lists the effects that await an answer, `TaskArena` stores the tasks, `Inboxes` stores unread messages, and `Admission` queues the chains that wait for a concurrency slot. The scheduler itself owns the ready queue and the run's phase, and it performs every action that writes to more than one of them. A request that changes one chain and the effect table, such as a model round, runs in `ChainOps`, a view that borrows that chain and the table. `Scheduler::with_chain` is the one entry to the view. Functions in the `execute` module take the chain's `ChainState` as their first parameter, `ctx`. ### A chain holds the state of the prompt it runs -`ChainState` has three layers. `SharedState` is the same for every chain of a run: the limits, the cancel flag, the event buffer, the handle to the run's files, and a table of the run's prompts by name. `PromptState` is the same for every chain that runs one prompt: the prompt, its tool set, its model set, and the preludes of the Packs that it declares. The fields of `ChainState` itself are the ones that a fork replaces: the chain's arguments, its reporting handles, its prompt, and its store. `ChainState::root` in `runvil-internal/runtime/src/execute/context.rs` builds one `PromptState` for the run's own prompt and one for each prompt it links. +`ChainState` is built in layers. `SharedState` is the same for every chain of a run: the limits, the cancel flag, the event buffer, the handle to the run's files, and a table of the run's prompts by name. `PromptState` is the same for every chain that runs one prompt: the prompt, its tool set, its model set, and the preludes of the Packs that it declares. The fields of `ChainState` itself are the ones that a fork replaces: the chain's arguments, its reporting handles, its prompt, and its store. `ChainState::root` in `runvil-internal/runtime/src/execute/context.rs` builds one `PromptState` for the run's own prompt and one for each prompt it links. The scheduler reads a chain's prompt from the chain. A section lookup, `sys.section_count`, the round cap of `models.loop`, and the file name in an error therefore each come from the prompt that the chain runs. A `call` chain and a task keep the prompt and the store of the chain that started them. @@ -254,7 +252,7 @@ Each prompt has a tool set and a model set of its own because both depend on its ### `execute` starts a `call` chain in another of the run's prompts -`Request::Execute` has a name and optional arguments. `prepare_execute` in `runvil-internal/runtime/src/execute/scheduler/dispatch.rs` makes three checks in order: the depth cap, the name against the `prompts:` list of the prompt that the caller runs, and the arguments against the `args:` declaration of the named prompt. A failed check raises its error at the `execute`, and no chain starts. The function then forks the caller's state with `ChainState::with_prompt`, which gives the new chain the `PromptState` of the named prompt, the checked arguments, and a new store. It starts a chain of the kind `ChainKind::Call` whose parent is the caller. The chain starts at the first top-level section of the named prompt, with an empty `var`, on the `default` model of that prompt's model set, under the caller's file access and the caller's concurrency limit. +`Request::Execute` has a name and optional arguments. `prepare_execute` in `runvil-internal/runtime/src/execute/scheduler/dispatch.rs` makes these checks in order: the depth cap, the name against the `prompts:` list of the prompt that the caller runs, and the arguments against the `args:` declaration of the named prompt. A failed check raises its error at the `execute`, and no chain starts. The function then forks the caller's state with `ChainState::with_prompt`, which gives the new chain the `PromptState` of the named prompt, the checked arguments, and a new store. It starts a chain of the kind `ChainKind::Call` whose parent is the caller. The chain starts at the first top-level section of the named prompt, with an empty `var`, on the `default` model of that prompt's model set, under the caller's file access and the caller's concurrency limit. The new chain is a `call` chain in all but the prompt it runs, so the scheduler has one code path for both. The caller is parked as on a `call`, and the chain's end answers it with the final text or with no text. The finish, the abort of a subtree, a cancel, the depth count, and the admission of tasks work as they do for a `call`, and the run reports no event of its own for an `execute`. The owner's reason: "it's not a separate run. The run is somewhat integrated into the whole." @@ -266,7 +264,7 @@ A `SectionPos` names a section by the path to its list of siblings and an index ## 6. Run limits -### `RunLimits` is a struct with six public fields +### `RunLimits` is a struct with public fields A caller changes a limit by assigning a field of `RunLimits::default()` and passing the struct to `RunParams::with_limits`. The fields and their defaults: @@ -287,15 +285,15 @@ The default values of the limits are arbitrary, and so is the interval of the ca Each Lua VM has a hook that fires every 10,000 instructions and reads the run's cancel flag, and a set flag aborts the block. An endless loop in a prompt therefore runs until the caller cancels the run. The owner's reason: "If the user codes an infinite loop that's their problem". -The Engine sets two quotas, both on `log`: a count of events and a count of bytes. A call past either one raises an error with the code `lua_quota`. +The Engine sets quotas on `log`: a count of events and a count of bytes. A call past either one raises an error with the code `lua_quota`. ## 7. The one error type ### Every Engine and Harness failure is one `Error` record with an `ErrorCode` -`Error` is a struct in `runvil-types` with five public fields: `code`, `message`, `prose`, `at`, and `facts`. `ErrorCode` is an enum of 67 codes, each with a number and a tag such as `lua_runtime` (201). The hundreds digit names the family: 1xx parse, 2xx Lua, 3xx tasks, 4xx model, 5xx tools, 6xx store, 7xx run, and 8xx caller. The enum's docs add: "A number is never reused." The root `AGENTS.md` makes `Error` the one error type of the Engine and Harness crates, with `VfsError` as the main exception. +`Error` is a struct in `runvil-types` with the public fields `code`, `message`, `prose`, `at`, and `facts`. `ErrorCode` is an enum of codes, each with a number and a tag such as `lua_runtime` (201). The hundreds digit names the family: 1xx parse, 2xx Lua, 3xx tasks, 4xx model, 5xx tools, 6xx store, 7xx run, and 8xx caller. The enum's docs add: "A number is never reused." The root `AGENTS.md` makes `Error` the one error type of the Engine and Harness crates, with `VfsError` as the main exception. -The crates share one `Error` because they once had dozens of error types, and every one that a facade exported was another public item. One record made the code easier to read and to change, and it keeps the public surface small. The owner's reason: "There was a proliferation of error types and unifying them into one made the code much easier to understand and easier to work on". On the surface: "one is better than 52 in this case". The 52 is the owner's own count and is unconfirmed: a search of the older code finds fewer. The owner limits the rule to this API: "for unified public harness and engine API, it's better to just have one error", and of the rule elsewhere, "that might not be generally true". +The crates share one `Error` because every error type that a facade exports is another public item. One record makes the code easier to read and to change, and it keeps the public surface small. The owner's reason: "There was a proliferation of error types and unifying them into one made the code much easier to understand and easier to work on". On the surface: "one is better than 52 in this case". The number in that quote is the owner's own count and is unconfirmed. The owner limits the rule to this API: "for unified public harness and engine API, it's better to just have one error", and of the rule elsewhere, "that might not be generally true". The owner has made no decision about how the codes are grouped. `call_depth_exceeded` is 204, in the Lua family. The grouping and the numbers may change while Runvil has no users. The owner's reason: "there's no users that are comparing error codes yet, so it's easy to change". A code that moves to another family takes a new number, so a move keeps the rule that a number is never reused. @@ -321,7 +319,7 @@ The Lua crate builds a failure with `make_lua_runtime_error` when the prompt aut ### `runvil-engine` contains re-exports, and each item has one path -The crate's one source file has 105 `pub use` lines, at the root and in nine `pub mod` blocks, and private crates define every item. The code calls such a crate a facade. Each line re-exports one item by name from the crate that defines it. A structural check rejects a glob, a list, and an item definition, and `cargo xtask api` rejects a re-exported module ([Crates, build, and CI](crates-build-and-ci.md)). The `runvil` crate, which a Host depends on, is a second facade ([The Harness and the Host API](harness-and-host.md)). +The crate's source has a `pub use` line for each item, at the root and in `pub mod` blocks, and private crates define every item. The code calls such a crate a facade. Each line re-exports one item by name from the crate that defines it. A structural check rejects a glob, a list, and an item definition, and `cargo xtask api` rejects a re-exported module ([Crates, build, and CI](crates-build-and-ci.md)). The `runvil` crate, which a Host depends on, is another facade ([The Harness and the Host API](harness-and-host.md)). A caller finds every item in this one crate. The owner's reason: "I dont want types scattered around different crates. I have discovered it becomes hard to browse the cargo doc that way." Each line names a single item because a re-exported module or crate would expose everything that the module later gains, and a second path to an item would make the API ambiguous. @@ -331,9 +329,9 @@ The facade re-exports an item when production code of a crate outside the Engine So the Engine builds every `ToolSchema`: a public constructor would widen the facade only for tests. -### A signature on the surface names facade items, the standard library, and three serde crates +### A signature on the surface names facade items, the standard library, and the serde crates -`cargo xtask api` reads rustdoc's JSON for the facade and fails when a signature, field, or impl on the surface names anything else. The three crates are `serde`, `serde_core`, and `serde_json`. The limit applies to the surface only: the internal crates may use many external crates, and the surface is restricted to a few basic ones. +`cargo xtask api` reads rustdoc's JSON for the facade and fails when a signature, field, or impl on the surface names anything else. The serde crates are `serde`, `serde_core`, and `serde_json`. The limit applies to the surface only: the internal crates may use many external crates, and the surface is restricted to a few basic ones. ### An operation reserved for Engine crates is a free function in a `detail` module @@ -341,13 +339,13 @@ Some operations on a public type are reserved for Engine crates, such as buildin The operations are free functions because a free function in a module outside the facade is invisible on the type's docs page. A hidden trait implemented on a public type can render there as an impl that links into an internal crate. -### The Engine is seven private crates, each with one job +### The Engine is split into private crates, each with one job The crates are in `runvil-internal/`, and code outside that folder imports them through `runvil-engine` and `runvil-plugin` ([Crates, build, and CI](crates-build-and-ci.md)). - `runvil-types` defines ids, events, metrics, `Error`, the cancel flag, and the untrusted envelope. - `runvil-vfs` is the virtual file system, and it defines the file operations as values, `VfsOp` and `VfsOutcome`. -- `runvil-markdown` reads Markdown text into blocks, writes blocks back as text, and holds the two grammars that name a section and a block. +- `runvil-markdown` reads Markdown text into blocks, writes blocks back as text, and holds the grammars that name a section and a block. - `runvil-model-client` defines messages, tool schemas, completions, and model bindings. - `runvil-lua` runs the Lua sandbox and defines the Engine globals and the request protocol. - `runvil-prompt` parses a prompt and compiles its Lua, and uses `runvil-lua` for `LuaProgram`. @@ -362,15 +360,15 @@ Each of these items is still to be built. - **An `execute` that returns at once.** A Lua `execute_async` call that starts another prompt as a task and returns its handle. `execute` runs a listed prompt as a blocking child chain, and its caller waits for the result. - **Replay.** Harness code that runs a recorded run a second time and compares the records of the two runs. The Engine attaches a `Provenance` to each effect and event, and `Effect::record` and `EffectAnswer::record` return the JSON that a run log stores. A file request of a tool is an input of the run, as an answer is, so a replay reports each recorded request again with `Run::request_file`. - **The round id on `ModelTurnFailed`.** A round id in the `ModelTurnFailed` event, so that a Host can drop exactly the failed round's streamed pieces. The Engine writes the round id in a round's thinking, reply, and tool-call events. -- **Bounds on JSON conversion.** A size budget at every site that converts a Lua table. `json.encode` and `var` writes have a size budget. Six other sites in the Lua crate convert a table of any size, and one encode runs as a single Rust callback between cancel polls. +- **Bounds on JSON conversion.** A size budget at every site that converts a Lua table. `json.encode` and `var` writes have a size budget. Other sites in the Lua crate convert a table of any size, and one encode runs as a single Rust callback between cancel polls. - **`#[non_exhaustive]` on the error types.** The attribute on `ErrorCode`, and on `Error` and `ErrorFact` if the owner extends it to them, so that a new code leaves a Host's build intact. The three types are closed, and `kind_of` in `runvil-lua` names every code with no catch-all arm, so it would need one or a move into `runvil-types`. ## 10. Known gaps Each item names a place where the language guide differs from the code. -1. Run limits. Chapter 16 has a section titled "The five run limits" and says that a prompt's own value "replaces the run's round cap". `RunLimits` in `runvil-internal/runtime/src/execute/params.rs` has six fields, and `PromptState::max_tool_iterations` caps the prompt's value at `tool_iterations_ceiling`. -2. Parse error kinds. Chapter 16 teaches six kinds, such as `Frontmatter` and `Structure`, and says "The set of parse error kinds is open". The code has one closed enum, `ErrorCode` in `runvil-internal/types/src/error.rs`, and `Prompt::parse` returns one of six codes, such as `frontmatter_invalid` or `lua_compile`. +1. Run limits. Chapter 16 has a section titled with a count of the run limits, and the count differs from the fields of `RunLimits` in `runvil-internal/runtime/src/execute/params.rs`. The chapter also says that a prompt's own value "replaces the run's round cap", while `PromptState::max_tool_iterations` caps the prompt's value at `tool_iterations_ceiling`. +2. Parse error kinds. Chapter 16 teaches parse error kinds, such as `Frontmatter` and `Structure`, and says "The set of parse error kinds is open". The code has one closed enum, `ErrorCode` in `runvil-internal/types/src/error.rs`, and `Prompt::parse` returns one of its parse codes, such as `frontmatter_invalid` or `lua_compile`. ## 11. Questions for the owner @@ -383,15 +381,11 @@ Each question asks for the reason behind a part of the design. **The surface** -3. Why is `RosterEntry` a closed enum? It is an enum of the facade without `#[non_exhaustive]`, and the entry on closed enums in section 3 names six others. +3. Why is `RosterEntry` a closed enum? It is an enum of the facade without `#[non_exhaustive]`, and the entry on closed enums in section 3 names others. ## 12. Method and limits -- **Code.** The page describes `runvil` at commit `fa9936f64` and `runvil-docs` at commit `cfd69a4`. -- **Checks.** The facts on this page were read in the code at those commits. A second session checked the gaps, the values, and the walk-through against the code. +- **Checks.** The facts on this page were read in the code. A second session checked the gaps, the values, and the walk-through against the code. - **Limits.** The sessions read the code and its tests, and left the build and the tests unrun. -- **Move.** On 2026-11-12 the Paths bullet was brought to `runvil` at commit `48a4dbc08` and `runvil-harness` at `5bca6f9`. Commit `adca9db10` of `runvil` removed the Engine, Harness, and Plugin crates, which are in `runvil-harness` with their history and at the same paths under `crates/`. The text of the page still describes the code at the commits above, when those crates were in `runvil`. -- **Every heading is a section.** On 2026-11-13 the entry on how a run ends in section 3, the entry on section entries in section 5, and the questions of section 11 were brought to the second change that follows `8de43c2f` in `runvil-harness`, whose plan is `plan/2026-11-13-2-every-heading-is-a-section.plan.md` there. Before it, a prompt had exactly one H1 as its title, and the Lua blocks under it ran once in a chain of their own, the H1 pass, before the main walk. A Lua error in that pass ended the run with the code `requirements_unmet`. Section 11 had a first question on why those blocks ran once, and the questions after it each moved up one number. That session ran the build and its tests. -- **Update.** On 2026-11-19 the text on file operations was brought to `runvil-harness` at commit `ee199e3a`. Between the commits, the `ToolCall` effect lost its file access: a tool asks its caller for each file operation, the caller reports the request with `Run::request_file`, and the Engine issues the operation as a `Vfs` effect that names the call. The update covers the first paragraph of the summary and the count of questions in the second, the walk-through, the second entry of section 1, three entries of section 3 and a new entry there on the open tool call, the entries on `Effect::Vfs` and on records in section 4, the entry on `Request` in section 5, the item on replay in section 9, and section 11. The Engine's decision page in `runvil-harness` at that commit has the owner's answers to eight of the nine questions that section 11 had, and each answer is in its entry: the entries on `Run::new` and on how a run ends in section 3, on a call that waits and on `models.loop` in section 5, on `RunLimits` in section 6, and on the one `Error` in section 7. The entry on how a run ends also names the second place of the code `args_invalid`, an `execute`. Section 11 keeps the question on the cancel flag and has two new ones. Section 9 lost the item on the store as a tool, as the planned work of that page did, and it has a new item on the error types. The counts and the lists of fields in sections 1 to 8 were counted again at that commit, and three counts of section 8 changed: the facade has 105 `pub use` lines where it had 103, the Engine has seven private crates where the page named six, with `runvil-markdown` as the seventh, and the surface check allows three serde crates where the page named four. That session read the code and left the build and the tests unrun. The rest of the page still describes the commits above, except the text on `execute` and on linked prompts, which describes `runvil-harness` after the change whose plan is `plan/2026-11-14-4-execute-child-prompts.plan.md` there. In that rest, the entry on `find_visible` in section 2 names four functions that the code at `ee199e3a` lacks. *2026-11-10 16:37 - Claude Fable 5.2* diff --git a/decisions/files-and-the-vfs.md b/decisions/files-and-the-vfs.md index 86448aa..3b4d137 100644 --- a/decisions/files-and-the-vfs.md +++ b/decisions/files-and-the-vfs.md @@ -1,23 +1,19 @@ # Files and the VFS: design decisions and their reasons - Scope: the `store` Lua API, the virtual file system (VFS), real and virtual roots, what a run may read and write, file identities and conflicts, and persistence -- Code: `runvil` at commit `fa9936f64`, and `runvil-docs` at commit `cfd69a4` -- Update: the Paths bullet names the repositories as of `runvil` at `48a4dbc08` and `runvil-harness` at `5bca6f9`, after the Engine and the Harness moved (section 11) -- Update: the first entry of section 1 states the rule of the second change that follows `8de43c2f` in `runvil-harness`: every heading starts a section, and the code before the first heading is the preamble (section 11) -- Update: the text on the list of file operations, on a tool's file requests, on conflicts and claims, on policies and the operation sink, on the `Vfs` effect and its record, and on Workshop's demo mounts, with the planned work, the known gaps, and the questions, describes `runvil-harness` at commit `ee199e3a`, `runvil-workshop` at `956e7800`, `runvil-plugin-api` at `52a4905`, `runvil-plugin-std` at `a806bf6`, and `runvil-plugin-bashkit` at `f348f7a` (section 11) - Paths: code paths start at the `crates/` folder of `runvil-harness`, the repository of the Engine and the Harness, and a path that begins with `workshop/` starts at the `crates/` folder of `runvil-workshop` ## Summary A run's files are in a virtual file system, the VFS, which the crate `runvil-vfs` implements. The Host builds one `VfsRef` handle for each run: a table of mounts, each a backend in memory or over a real directory, which holds the files the run's tools work in. The store is a separate value, a `Store`, that the Engine makes for each run, and each `execute` gives the prompt that it runs a store of its own. Lua reads and writes a store through the `store` table. The main walk, each task, and each tool call has an `Access`, an object that performs file operations for one identity: it checks the path and the policy of its handle, and then calls the backend. A `store` call runs on a view of the store, an `Access` with the calling chain's identity that reaches the store alone and asks no Host policy. A view also checks what the other identities have read and written in its store, which an `Access` to the Host's files leaves unchecked. A tool holds no `Access`: it asks for each file operation, the Engine issues the operation as a `Vfs` effect, as it does for a `store` call, and the Harness performs it on the `Access` of the tool call and records it. Sections 1 to 7 describe this design. -A check of this page against the code found five gaps (section 9) and seven questions about reasons (section 10). The largest gap is a lost edit: a tool that edits a file as a read followed by a write can lose a change that another task makes between the two, because the Host's files have no conflict check. +Section 9 lists the gaps between this page and the code, and section 10 lists the questions about reasons for the owner. The largest gap is a lost edit: a tool that edits a file as a read followed by a write can lose a change that another task makes between the two, because the Host's files have no conflict check. Section 8 lists the planned work: a real directory in Workshop, a database mount, replay, and a glob across mounts. ## From `store.write` to the backend and back -A Lua block calls `store.write('notes.md', text)`. The function is a shim that yields a table, which the Engine parses into a `Request::Store` with a `VfsOp::Write`. The Engine derives a store view from the run's `Store` under the `Access` of the calling chain, such as the main walk or a task. The view is a second `Access` with the chain's identity and scope, and it reaches the run's store alone. The Engine issues `Effect::Vfs` with its three fields: `asker` is a `VfsAsker::Lua` that holds the id of the store, `access` is the view, and `op` is the operation. `Run::step` returns the effect, and the chain waits. +A Lua block calls `store.write('notes.md', text)`. The function is a shim that yields a table, which the Engine parses into a `Request::Store` with a `VfsOp::Write`. The Engine derives a store view from the run's `Store` under the `Access` of the calling chain, such as the main walk or a task. The view is a second `Access` with the chain's identity and scope, and it reaches the run's store alone. The Engine issues `Effect::Vfs` with its fields: `asker` is a `VfsAsker::Lua` that holds the id of the store, `access` is the view, and `op` is the operation. `Run::step` returns the effect, and the chain waits. The Harness records the effect and calls `perform_vfs_op`, which runs the operation on the view with `Access::perform`. A `VfsOp::Write` runs as `Access::write`. @@ -39,11 +35,11 @@ The store holds files because a prompt is often a pipeline: a stage runs inferen The inspection that the owner means happens during the run, at a breakpoint or at any stage. With the evidence in file A and the inference over it in file B, "if we get a breakpoint now we can see A and B", where a B written as a series of edits to A would leave only the event log to show the earlier text. The owner's reason: "Having it in the store means there's a blob there." A debugger that rebuilds each store from the run's records is planned work (section 8), and the record is the only view of a store from outside the run (section 7). -### The `store` table has eight functions, and a prompt composes the rest +### The `store` table offers a subset of the VFS operations, and a prompt composes the rest The functions are `write`, `append`, `read`, `read_numbered`, `str_replace`, `delete`, `glob`, and `exists`. `store.str_replace` replaces an anchor text that must occur exactly once, because an edit by anchor is the pattern that works for models. `store.delete` succeeds on an absent path. -The table stops at eight because a prompt can write the other VFS operations from them. It leaves out `stat` because timestamps are nondeterministic, and the store's memory backend tracks none. +The table stops there because a prompt can write the other VFS operations from them. It leaves out `stat` because timestamps are nondeterministic, and the store's memory backend tracks none. ### `store.read` takes 1-based inclusive line bounds, and `store.read_numbered` numbers the lines @@ -61,7 +57,7 @@ The backslash, colon, suffix, and device-name rules refuse spellings that some b ### The file system types are Runvil's own, and a run's tool files and its store are separate values built from them -`runvil-vfs` defines the file system types. A backend implements two traits: `Vfs` for the storage and `VfsAccess` for one identity's session with it. `VfsRef` is a cloneable handle to a set of mounted backends, and an `Access` performs operations through it for one identity. A Host builds a `VfsRef` from these types for the files that a run's tools work in (section 3). A `Store` is a value of its own, built from the same types: an empty set of files in memory under a claims table of its own, outside every `VfsRef`. +`runvil-vfs` defines the file system types. A backend implements the traits `Vfs` for the storage and `VfsAccess` for one identity's session with it. `VfsRef` is a cloneable handle to a set of mounted backends, and an `Access` performs operations through it for one identity. A Host builds a `VfsRef` from these types for the files that a run's tools work in (section 3). A `Store` is a value of its own, built from the same types: an empty set of files in memory under a claims table of its own, outside every `VfsRef`. A store is built from the file system types because it keeps their claims rules (section 5). The owner's reason: "We need the claim system that the VFS has." @@ -71,11 +67,11 @@ The `vfs` module of each facade crate, `runvil` and `runvil-engine`, exports the For each `store` call the Engine derives a store view with `Store::view`, from the calling chain's `Store` and the calling chain's `Access`. `Store::view` is the only way into a store. The view is a second `Access` with the chain's identity and scope, and its operations reach that store alone. It checks each path against the store's path rules (section 1) and gives error paths back in the form the caller wrote. `dispatch_vfs` in `runvil-internal/runtime/src/execute/scheduler/dispatch.rs` is the one place in the Engine that makes a store view. -The store follows one rule: it offers a subset of the operations of the VFS. A store is a value and not a mount of a handle, because one scope has to hold many stores. A child prompt that `execute` runs gets a store of its own, and it runs in its caller's scope under its caller's identity (section 3). The owner's rule: "prompts passed to execute or execute_async should get their own store which is completely isolated from the caller's store. they cannot see each others' paths or claims." +The store follows a rule: it offers a subset of the operations of the VFS. A store is a value and not a mount of a handle, because one scope has to hold many stores. A child prompt that `execute` runs gets a store of its own, and it runs in its caller's scope under its caller's identity (section 3). The owner's rule: "prompts passed to execute or execute_async should get their own store which is completely isolated from the caller's store. they cannot see each others' paths or claims." ### One list of operations serves the `store` functions and a tool's file requests -`runvil-vfs` defines the file operations as values, in `runvil-internal/vfs/src/vfs_op.rs`. A `VfsOp` is one operation with its arguments, `Access::perform` runs it on an `Access`, and a `VfsOutcome` is what it returns. The list has 15 operations. The `store` functions use eight of them, `Write`, `Append`, `Read`, `ReadNumbered`, `StrReplace`, `Delete`, `Glob`, and `Exists`, and each `store` call is one of them. A tool asks for nine through the file functions of the C contract: `Stat`, `List`, `ReadRange`, `Mkdir`, `Remove`, `Rename`, and `Copy`, beside `Write` and `Append` ([Tools and Packs](tools-and-packs.md)). A Rust Pack's tool may ask for any operation of the list. `Write` and `Append` hold bytes, because a tool writes bytes, and a `store` call passes the bytes of its text. `Delete` succeeds on an absent path, and `Remove` fails on one with `VfsError::NotFound`. They are two operations, so a run's record shows which one ran. `VfsOutcome` has seven variants: `Unit`, `Text`, `Paths`, `Bool`, `Stat`, `Entries`, and `Bytes`. `VfsOp` and `VfsOutcome` are closed enums, so an operation or an outcome that the list gains fails the build at each place that must handle it ([The Engine](engine.md)). +`runvil-vfs` defines the file operations as values, in `runvil-internal/vfs/src/vfs_op.rs`. A `VfsOp` is one operation with its arguments, `Access::perform` runs it on an `Access`, and a `VfsOutcome` is what it returns. The `store` functions use `Write`, `Append`, `Read`, `ReadNumbered`, `StrReplace`, `Delete`, `Glob`, and `Exists`, and each `store` call is one of them. A tool asks for its operations through the file functions of the C contract: `Stat`, `List`, `ReadRange`, `Mkdir`, `Remove`, `Rename`, and `Copy`, beside `Write` and `Append` ([Tools and Packs](tools-and-packs.md)). A Rust Pack's tool may ask for any operation of the list. `Write` and `Append` hold bytes, because a tool writes bytes, and a `store` call passes the bytes of its text. `Delete` succeeds on an absent path, and `Remove` fails on one with `VfsError::NotFound`. They are two operations, so a run's record shows which one ran. `VfsOutcome` has the variants `Unit`, `Text`, `Paths`, `Bool`, `Stat`, `Entries`, and `Bytes`. `VfsOp` and `VfsOutcome` are closed enums, so an operation or an outcome that the list gains fails the build at each place that must handle it ([The Engine](engine.md)). The owner's reason for one list: "in principle, the store is just a virtual directory in the file system that is unique to a prompt." A `store` call and a tool's file request are two views of the same operations, and the Engine and the Harness handle the whole list, so either side gains an operation by adding one function. Each of the two reaches the list as a `Vfs` effect, which says who asked (section 7). @@ -83,7 +79,7 @@ The owner's reason for one list: "in principle, the store is just a virtual dire A virtual path is rooted and uses forward slashes on every operating system. An `Access` canonicalizes each path when it receives it, so the policy, the claims table, and the backend see one spelling. A path without a leading `/` is relative to `/`. -With one canonical form, only `RealBackend` translates a path to the operating system's form. Case is significant. A claims table has one exception: below a rooted real mount on Windows and macOS it compares paths in lowercase, because a false conflict fails safe. A store is memory, and a handle that a Host builds checks no claims (section 5), so the exception is out of the reach of every run. +With one canonical form, only `RealBackend` translates a path to the operating system's form. Case is significant. A claims table has an exception: below a rooted real mount on Windows and macOS it compares paths in lowercase, because a false conflict fails safe. A store is memory, and a handle that a Host builds checks no claims (section 5), so the exception is out of the reach of every run. ### `VfsRefBuilder::build` fixes a handle's mount table, and the longest matching prefix wins @@ -101,7 +97,7 @@ The traits are synchronous because the backends are synchronous by nature: memor ### The Host builds the file system that a run's tools work in -A Host sets `RunSetup.vfs` to one `VfsRef` for each run: the file system that the run's tool calls work in ([The Harness and the Host API](harness-and-host.md)). The Harness passes the handle to the Engine with `RunParams::with_vfs`, and the Engine makes an `Access` to it for each tool call (section 5). `RunSetup::new` sets `VfsRef::default()`, one empty in-memory mount at `/`. A Host can fill the handle before a run and read it after the run, through its own clone of the `VfsRef`, and concurrent runs can share one handle. When the handle refuses the run its access, or refuses the fork for a task or a tool call, the failure has the handle's own error code and the message `file access failed: {cause}`. +A Host sets `RunSetup.vfs` to one `VfsRef` for each run: the file system that the run's tool calls work in ([The Harness and the Host API](harness-and-host.md)). The Harness passes the handle to the Engine with `RunParams::with_vfs`, and the Engine makes an `Access` to it for each tool call (section 5). `RunSetup::new` sets `VfsRef::default()`, an empty in-memory mount at `/`. A Host can fill the handle before a run and read it after the run, through its own clone of the `VfsRef`, and concurrent runs can share one handle. When the handle refuses the run its access, or refuses the fork for a task or a tool call, the failure has the handle's own error code and the message `file access failed: {cause}`. The Host builds the handle because the mounts are the Host's choice: memory, a real directory, or a backend of its own. The handle holds tool files alone, and the Engine and the Harness put nothing into it. @@ -127,7 +123,7 @@ The rule is the owner's (section 2). An executed prompt therefore has the one wa `RealBackend::rooted(dir)` maps the virtual root to one real directory and refuses a path that resolves outside it with `OutsideRoot`. `RealBackend::identity()` maps each virtual path to the same real path. `remove`, `exists`, `stat`, `mkdir`, and `rename` act on a link itself, and the content operations follow a link whose target is inside the root. `with_writability` makes a backend read-only. A failed write leaves the file unchanged, because the backend writes a temporary sibling file and renames it. The policy of the handle is asked about the path that an operation names, a link's own path included, and never about the link's target (section 4). -The five operations act on the link itself because a `remove` that followed the link would delete the link's target. `RealBackend` is part of `runvil-vfs` itself: `std::fs` belongs to the standard library, so the backend fits the crate's zero-dependency rule ([Crates, build, and CI](crates-build-and-ci.md)). +These operations act on the link itself because a `remove` that followed the link would delete the link's target. `RealBackend` is part of `runvil-vfs` itself: `std::fs` belongs to the standard library, so the backend fits the crate's zero-dependency rule ([Crates, build, and CI](crates-build-and-ci.md)). ### A mount is for storage that answers quickly, and a remote system is a tool's job @@ -173,13 +169,13 @@ An operation on the files of the run's handle makes no claim and checks none, wh The owner's reason: "maybe the determinism error should only apply to store operations? and we should otherwise try to behave like regular harnesses, so that two subagents which conflict on file access can just work it out". On the prompt's own `tools.call`, the owner's words: "I think I am ok with Lua's own tools.call on Host files being unchecked. We can always put it back in later." The store is the prompt's own memory, and every party in it is the prompt's Lua, so the check stays there. The Host's files are the outside world: with a real folder mounted, another program can change a file, and a claims table knows the run's own identities alone. -The record of a run stays whole without the check, because each operation that a tool asks for is a recorded effect that the Harness performs in order (the last entry of this section). The changes that one model reply asks for apply one at a time, in the order the reply lists them, because a call of a tool whose `ToolInfo` sets `changes_files` runs alone ([Tools and Packs](tools-and-packs.md)). One gap is known: a tool that edits a file as a read followed by a write can lose an edit that another task makes between the two (section 9). +The record of a run stays whole without the check, because each operation that a tool asks for is a recorded effect that the Harness performs in order (the last entry of this section). The changes that one model reply asks for apply one at a time, in the order the reply lists them, because a call of a tool whose `ToolInfo` sets `changes_files` runs alone ([Tools and Packs](tools-and-packs.md)). A gap is known: a tool that edits a file as a read followed by a write can lose an edit that another task makes between the two (section 9). -The claims code stays in `runvil-vfs` with its tests, and only that crate can make a handle check claims: `VfsRefBuilder::checking_claims` is private to the crate, and `Store::new` calls it. The check on the Host's files can therefore return. +The claims code stays in `runvil-vfs` with its tests, and only that crate can make a handle check claims: `VfsRefBuilder::checking_claims` is private to the crate, and `Store::new` calls it. ### Happens-before order decides whether two accesses to a store conflict -Each identity has a vector clock. Fork and join are methods of a public type, `ScopeHandle` in `runvil-internal/vfs/src/handle/scope_handle.rs`, which `VfsRef::acquire_scope` returns. The type has four methods: `spawn`, `join`, `end_access`, and `end`. `ScopeHandle::spawn` forks a child identity, and the fork orders everything the parent did before it ahead of the child's first operation. `ScopeHandle::join` merges a child's clock into its owner's, and the owner may then read what the child wrote to the store. The Engine forks at each task spawn and joins at each delivery of a task's result ([Tasks and fanout](tasks-and-fanout.md)). +Each identity has a vector clock. Fork and join are methods of a public type, `ScopeHandle` in `runvil-internal/vfs/src/handle/scope_handle.rs`, which `VfsRef::acquire_scope` returns. The type has the methods `spawn`, `join`, `end_access`, and `end`. `ScopeHandle::spawn` forks a child identity, and the fork orders everything the parent did before it ahead of the child's first operation. `ScopeHandle::join` merges a child's clock into its owner's, and the owner may then read what the child wrote to the store. The Engine forks at each task spawn and joins at each delivery of a task's result ([Tasks and fanout](tasks-and-fanout.md)). The ordering test is the one that the FastTrack race detector uses, and with it a verdict depends only on the structure of the program. A claim that lasted for the life of its identity would make the verdict depend on which model call returns first. @@ -203,7 +199,7 @@ A tool call's operations make no claim, so none of them conflicts with another a ### A tool's file request is a `Vfs` effect, which the Harness performs and records -A tool asks for a file operation and waits for the outcome. A Rust Pack's tool asks through `ToolContext::files`, a `ToolFiles` whose method `request` takes a `VfsOp` and resolves with a `VfsOutcome` or a `VfsError`. A library Pack's tool asks through one of the nine file functions of the C contract, and the loader passes the request on through the same `ToolFiles` ([Tools and Packs](tools-and-packs.md)). The Harness reports the request to the Engine with `Run::request_file`, the Engine issues a `Vfs` effect under the call's identity, the Harness performs and records it, and the tool goes on with the answer ([The Engine](engine.md)). The tool receives the whole outcome, and the Engine receives a receipt of it, which resumes no chain, because the chain still waits for the tool call. A request is a tool's one way to the run's files, so the record holds every file operation of a tool. The file tools of `std` and the shell of `bash` read and change a run's files this way. The owner's rule: "every VFS operation that's performed by a tool has to turn into an effect in the engine." +A tool asks for a file operation and waits for the outcome. A Rust Pack's tool asks through `ToolContext::files`, a `ToolFiles` whose method `request` takes a `VfsOp` and resolves with a `VfsOutcome` or a `VfsError`. A library Pack's tool asks through one of the file functions of the C contract, and the loader passes the request on through the same `ToolFiles` ([Tools and Packs](tools-and-packs.md)). The Harness reports the request to the Engine with `Run::request_file`, the Engine issues a `Vfs` effect under the call's identity, the Harness performs and records it, and the tool goes on with the answer ([The Engine](engine.md)). The tool receives the whole outcome, and the Engine receives a receipt of it, which resumes no chain, because the chain still waits for the tool call. A request is a tool's one way to the run's files, so the record holds every file operation of a tool. The file tools of `std` and the shell of `bash` read and change a run's files this way. The owner's rule: "every VFS operation that's performed by a tool has to turn into an effect in the engine." The Harness performs a tool's request as it performs a `store` call: inline, with one blocking call of `Access::perform`, in the order in which the Engine issues the effects (section 7). It runs a tool's operation inside a guard, so a panic in the Host's policy or backend reaches the tool as a `VfsError::Backend`. A call that has returned or was aborted has no one to take an outcome, so the Harness drops its later requests and answers its outstanding `Vfs` effect as `Dropped`, with the operation left unperformed ([The Harness and the Host API](harness-and-host.md)). @@ -213,7 +209,7 @@ The reason is the record. The owner's questions about a tool that performs its f ### `VfsError` is the one error type, and each variant has a stable tag -A VFS operation that fails returns a `VfsError`, an enum of 20 variants whose details are public fields. `VfsError::tag()` returns one fixed string for each variant, such as `not_found`. Each kind of refusal has its own variant, such as `ReadOnly` and `OutsideRoot`. +A VFS operation that fails returns a `VfsError`, an enum whose variants have public fields. `VfsError::tag()` returns one fixed string for each variant, such as `not_found`. Each kind of refusal has its own variant, such as `ReadOnly` and `OutsideRoot`. ### A failed `store` call raises a Lua error value of kind `store` @@ -225,7 +221,7 @@ An error has three readers: Rust code matches the variant, Lua code branches on ### Each `store` call is one `Vfs` effect, which the Harness performs inline -A `store` function yields its operation, and the Engine issues one `Effect::Vfs` for it ([The Engine](engine.md)). The Harness performs the effect at once with `perform_vfs_op`, before it waits for any other effect. The Engine reports one of sixteen events for each call, such as `VfsWriteSucceeded`, which names the section and omits the path and the store. The run's record holds every store operation: each `Vfs` effect record with the id of its store and its operation, and each answer record with its outcome, in order. The record is the only view of a store outside its run, and the records of one store are enough to rebuild it. The test `a_runs_vfs_records_rebuild_its_store` in `harness-internal/runner/tests/it/effect_loop-vfs.rs` applies each `Vfs` record of a run that has an `Ok` answer to an empty memory handle, and the file it rebuilds reads as the text that the run returned. +A `store` function yields its operation, and the Engine issues one `Effect::Vfs` for it ([The Engine](engine.md)). The Harness performs the effect at once with `perform_vfs_op`, before it waits for any other effect. The Engine reports an event for each call, such as `VfsWriteSucceeded`, which names the section and omits the path and the store. The run's record holds every store operation: each `Vfs` effect record with the id of its store and its operation, and each answer record with its outcome, in order. The record is the only view of a store outside its run, and the records of one store are enough to rebuild it. The test `a_runs_vfs_records_rebuild_its_store` in `harness-internal/runner/tests/it/effect_loop-vfs.rs` applies each `Vfs` record of a run that has an `Ok` answer to an empty memory handle, and the file it rebuilds reads as the text that the run returned. The Harness performs the call inline because file operations are synchronous by design: the storage underneath is synchronous, so a `Vfs` effect has no future for the effect loop to wait on, and the run waits for the operation. The owner's reason: "all file I/O synchronizes the, the harness, and that's in line with our design." `answer_vfs` in `harness-internal/runner/src/effect_loop.rs` performs the operation through the effect's view, and the view drops when the function returns, so the Harness holds no way to the store between effects. The loop answers every `Vfs` effect of a step this way and then steps the run once. VFS operations run one at a time, in the order the Engine issues them, whether a `store` call or a tool's request asked for each. @@ -235,9 +231,9 @@ The `store` functions stay in the Engine. Serving them from a tool would only re ### A `Vfs` effect and its record name a store by a chain id, and a tool call by its effect id -`Effect::Vfs` has three fields: `asker`, `access`, and `op`. The asker of a `store` call is a `VfsAsker::Lua`, which names the store by a `ChainId`, and the effect's record holds that id beside the operation, as in `{"Vfs":{"store":"0","op":{...}}}`. The id `0`, the root chain's, names the store that the run starts with. A store that an `execute` made has the id of the executed prompt's chain, such as `0.0`, and every operation on that store has this id, whichever chain of the executed prompt made the call. `ChainStore` in `runvil-internal/runtime/src/execute/context.rs` keeps a store together with the id of the chain it was made for. +`Effect::Vfs` has the fields `asker`, `access`, and `op`. The asker of a `store` call is a `VfsAsker::Lua`, which names the store by a `ChainId`, and the effect's record holds that id beside the operation, as in `{"Vfs":{"store":"0","op":{...}}}`. The id `0`, the root chain's, names the store that the run starts with. A store that an `execute` made has the id of the executed prompt's chain, such as `0.0`, and every operation on that store has this id, whichever chain of the executed prompt made the call. `ChainStore` in `runvil-internal/runtime/src/execute/context.rs` keeps a store together with the id of the chain it was made for. -The record names the store because an executed prompt reports under its caller's task, and two stores can each have a file at one path. Without the id, a reader of the log could not tell the caller's `a.md` from the child's, and neither store could be rebuilt. With it, the records of each store rebuild that store. The test `the_vfs_records_of_each_store_id_rebuild_that_store` in `runvil-internal/runtime/src/execute/tests/execute/store.rs` applies the records of a run of three prompts to one empty store for each id, and each rebuilt store has the files that its prompt wrote. The id is a chain id because a chain id is the same in every run with the same inputs and answers ([Tasks and fanout](tasks-and-fanout.md)), which a replay needs. +The record names the store because an executed prompt reports under its caller's task, and two stores can each have a file at one path. Without the id, a reader of the log could not tell the caller's `a.md` from the child's, and neither store could be rebuilt. With it, the records of each store rebuild that store. The test `the_vfs_records_of_each_store_id_rebuild_that_store` in `runvil-internal/runtime/src/execute/tests/execute/store.rs` applies the records of a run of nested prompts to one empty store for each id, and each rebuilt store has the files that its prompt wrote. The id is a chain id because a chain id is the same in every run with the same inputs and answers ([Tasks and fanout](tasks-and-fanout.md)), which a replay needs. The asker of a tool's request is a `VfsAsker::Tool`, which names the tool call by the id of its `ToolCall` effect, and the record holds that id beside the operation, as in `{"Vfs":{"call":7,"op":{...}}}`. Its files are the files of the run's handle, which the record leaves unnamed because a run has one handle. The effect record holds the operation with the bytes of a write, as text under `contents` when they are UTF-8 and as hex under `contents_hex` otherwise. The answer record holds a receipt in place of content, a `VfsReceipt`, such as `{"VfsReceipt":{"Ok":{"Bytes":12}}}` for a read of 12 bytes ([The Engine](engine.md)). The tool's own result is the answer of its `ToolCall` effect. The Engine reports no event for a tool's file operation, so the two records are the view of it. @@ -251,7 +247,7 @@ A run has one way in, its arguments, and one way out, its result. The owner's re Each of these items is still to be built. -- **A real directory in Workshop.** Workshop would mount a real directory into each run's file system, and the choice of the directory is a product decision. Workshop builds `VfsRef::default()` for each run, so the files that a run's tools write and change are in memory and end with the run. Its code has two real mounts in `workshop/server/src/agents/language_guide.rs`, each read-only and each behind a constant that is `false`: `ENABLED` mounts a demo of the language guide, and `C_DRIVE` mounts the `C:` drive at `/c`, so that the shell and the file tools can be tried on real files. A tool's change under such a mount fails with `VfsError::ReadOnly`. +- **A real directory in Workshop.** Workshop would mount a real directory into each run's file system, and the choice of the directory is a product decision. Workshop builds `VfsRef::default()` for each run, so the files that a run's tools write and change are in memory and end with the run. Its code has real mounts in `workshop/server/src/agents/language_guide.rs`, each read-only and each behind a constant that is `false`: `ENABLED` mounts a demo of the language guide, and `C_DRIVE` mounts the `C:` drive at `/c`, so that the shell and the file tools can be tried on real files. A tool's change under such a mount fails with `VfsError::ReadOnly`. - **A database mount.** A mount would show an agent's run database as files. Its backend would be synchronous like every other, so a backend over a database client with an async interface would drive that client on a thread of its own. The backends that ship are `MemoryBackend` and `RealBackend`. - **Replay.** Replay would read a run's records back into a run. A debugger would rebuild each store of a run from the same records, at any step. The Harness records each `Vfs` effect and its answer, for a `store` call and for a tool's file request. - **Glob across mounts.** A glob would also search the backends mounted below the mount that matches its pattern. A glob runs inside that one mount and skips a backend mounted below it. @@ -268,8 +264,8 @@ Each item names a doc comment in `runvil-vfs` that differs from the code, or a f 2. A lost edit. A tool that edits a file as a read followed by a write can lose a change that another task makes between the two, because an operation on the Host's files checks no claim (section 5). StrReplace of the `std` Pack edits this way, with a stat, a read, and a write, each a request of its own. The list of operations has `StrReplace`, which replaces a text in one operation, and a Rust Pack's tool can ask for it. The C contract has no function for it, which leaves the tools of `std` and `bash` with the read and the write, and whether to add one is the owner's decision. The gap is tracked as [runvil-plugin-std issue 4](https://github.com/cppalliance/runvil-plugin-std/issues/4). Delete of `std` has the same shape with its stat and its removal: it removes a directory with no entries that another task puts at the path between the two ([runvil-plugin-std issue 3](https://github.com/cppalliance/runvil-plugin-std/issues/3)). 3. The removal of a directory that a mount sits under. With a mount at `/project/assets` and no `/project` in the backend that serves `/`, the directory `/project` exists, stats as a directory, and lists `assets`. A removal of it goes to the serving backend, which has no such path: a `Delete` succeeds, a `Remove` fails with `NotFound`, and the directory is still there. A store has one mount, so the fault shows only on a handle that a Host builds with one mount below another. The evidence is a reading of `RoutingAccess` in `runvil-internal/vfs/src/router.rs`, and the tests of that file leave the case out. -4. A write below a file. The two backends that ship answer differently for a write to a path directly below a file. `MemoryBackend` fails with `NotADirectory` for the parent. `RealBackend` asks the standard library's `create_dir_all` to make the parent, and the plan of the change, `plan/2026-11-16-1-tool-file-effects.plan.md` in `runvil-harness`, records from a reading of that function that the write fails with `AlreadyExists` for the written path. That session and this one left the case unrun. -5. A read far past the end of a file. The doc of `Access::read_range` promises an empty answer for an offset at or past the end of a file. `RealBackend` seeks to the offset before it reads, and the loader caps the offset of a tool's read at `i64::MAX`. The same plan records, from a reading of the code and of the kernel's rule, that ext4 refuses a seek past its largest file size, so such a read would fail there with an I/O error. That session and this one left the case unrun. +4. A write below a file. The backends that ship answer differently for a write to a path directly below a file. `MemoryBackend` fails with `NotADirectory` for the parent. `RealBackend` asks the standard library's `create_dir_all` to make the parent, in `create_parent` in `runvil-internal/vfs/src/real/files.rs`, and a reading of that function says the write fails with `AlreadyExists` for the written path. No test checks which error it is: `a_failed_write_leaves_the_destination_unchanged_and_no_temp_file_behind` only checks that such a write fails. +5. A read far past the end of a file. The doc of `Access::read_range` promises an empty answer for an offset at or past the end of a file. `RealBackend` seeks to the offset before it reads, and the loader caps the offset of a tool's read at `i64::MAX`. A reading of the code and of the kernel's rule says that ext4 refuses a seek past its largest file size, so such a read would fail there with an I/O error. No test of `RealBackend` reads at an offset that large. ## 10. Questions for the owner @@ -278,7 +274,7 @@ Each question asks for the reason behind a part of the design. **The store API** 1. Why does `store.delete` succeed on an absent path? -2. Why do store calls report sixteen event kinds, one pair for each operation? +2. Why do store calls report one pair of event kinds for each operation? **Conflicts** @@ -293,13 +289,7 @@ Each question asks for the reason behind a part of the design. ## 11. Method and limits -- **Code.** The page describes the commits of the `Code:` bullet. -- **Checks.** The facts on this page were read in the code at those commits. A second session checked the gaps, the values, and the walk-through against the code. +- **Checks.** The facts on this page were read in the code. A second session checked the gaps, the values, and the walk-through against the code. - **Limits.** The sessions read the code and its tests, and left the build and the tests unrun. -- **Update.** On 2026-11-11 the sentence on the `std` Pack's answer to a conflict, in the entry on conflicts inside a tool call, was brought to `runvil` at commit `b0693699d` and `runvil-plugin-std` at `782ad23`, where `std` is a library Plugin. The rest of the page still describes the commits of the `Code:` bullet. -- **Move.** On 2026-11-12 the Paths bullet was brought to `runvil` at commit `48a4dbc08` and `runvil-harness` at `5bca6f9`. Commit `adca9db10` of `runvil` removed the Engine, Harness, and Plugin crates, which are in `runvil-harness` with their history and at the same paths under `crates/`. The text of the page still describes the code at the commits above, when those crates were in `runvil`. -- **Every heading is a section.** On 2026-11-13 the first entry of section 1 was brought to the second change that follows `8de43c2f` in `runvil-harness`, whose plan is `plan/2026-11-13-2-every-heading-is-a-section.plan.md` there. Before it, the Lua blocks under a prompt's one H1 ran once outside every section, as the H1 pass, in a VM of their own that had the `store` table too. That session ran the build and its tests. -- **Update.** On 2026-11-13 the text on file access by tools was brought to `runvil-harness` at commit `18361d02`, `runvil-workshop` at `f386801b`, `runvil-plugin-api` at `03a9fa3`, `runvil-plugin-std` at `ee04d10`, and `runvil-plugin-bashkit` at `9c8e980`. Between the commits, Workshop moved to the `runvil-workshop` repository, and the bashkit Plugin with its `bash` Pack began to ship. The update covers the first entry of section 1, the policy entry of section 4, the entry on a tool call's identity in section 5, three items of section 8, and the Paths bullet. That session read the code and left the build and the tests unrun. The rest of the page still describes the commits above. -- **Update.** On 2026-11-19 the text on file operations by tools was brought to `runvil-harness` at commit `ee199e3a`, `runvil-workshop` at `956e7800`, `runvil-plugin-api` at `52a4905`, `runvil-plugin-std` at `a806bf6`, and `runvil-plugin-bashkit` at `f348f7a`. The code of `runvil-harness` at `ee199e3a` is the code at `4afed45f`, which `runvil-workshop` pins. Between the commits of the update above and these, a tool lost its file access: it asks for each file operation, the Engine issues the operation as a `Vfs` effect, and the Harness performs and records it. The C contract went from version 0.4 to 0.5 and gained six functions that change files, and the claims check moved to the store alone. The update covers the summary, the walk-through, the first entry of section 1, four entries of section 2, four entries of section 3, the three entries of section 4, the seven entries of section 5, the first two entries of section 7, sections 8 to 10, and the Update bullets at the top of the page. Four of those entries are new: on the one list of operations, on slow storage and remote systems, on the claims check, and on a tool's file request. Three items left section 8: the store as a tool and an async VFS, which the owner decided against, and file changes for a Plugin's tools, which are built. The gap on the comment of the `Vfs` trait left section 9, because the comment gives the reason of section 2 at these commits, and four known faults joined that section. Two questions left section 10, because the entries of sections 1 and 5 hold their answers, and one question joined it. The update replaces the text that the updates of 2026-11-11 and 2026-11-13 brought, except the Paths bullet. The owner's words that it adds are quoted from the decision pages of `runvil-harness` at `ee199e3a`. That session read the code and left the build and the tests unrun. It also read the entries that it left as they were against the same commits and found nothing to change in them. *2026-11-10 16:40 - Claude Fable 5.2* diff --git a/decisions/gateway.md b/decisions/gateway.md index 64b1ee0..4cf72c7 100644 --- a/decisions/gateway.md +++ b/decisions/gateway.md @@ -1,16 +1,15 @@ # The Gateway: design decisions and their reasons - Scope: the Gateway server in the `runvil-gateway` repository: its HTTP API and auth, its configuration file and config UI, local models, cloud providers and the published model sheet, profiles, routing and tool-call dialects, web search, boot, restart, logging, and progress -- Code: `runvil-gateway` at commit `9369a7d`, `runvil-cloud-providers` at `1817cc4`, `runvil-docs` at `cfd69a4`, and `runvil` at `fa9936f64` - Paths: code paths start at the `crates/gateway/` folder of the `runvil-gateway` repository ## Summary The Gateway is a server process, `runvil-gateway`, that accepts OpenAI-shaped requests and forwards each one to a model. One file, `gateway.toml`, lists remote backends as `[[endpoint]]` and `[[model]]` entries and local models as `[[local_model]]` entries. For a remote model the Gateway sends an HTTP request to a provider with the provider's key. A local model is a `llama-server` child process that the Gateway starts at boot from the selected profile. An admin API and a browser UI at `/config/` edit the file through staged copies, called shadow files, and an Apply step. Sections 1 to 9 describe these parts. -A check of this page against the code found fifteen gaps and left ten questions about reasons for the owner. Section 11 lists the gaps, and section 12 lists the questions. The largest gap is the restart feature: the route, the flag, and the exit code exist, and the supervisor that acts on them is still to be built. +Section 11 lists the gaps between this page and the code, and section 12 lists the questions about reasons for the owner. The largest gap is the restart feature: the route, the flag, the exit code, and the supervisor exist, and the config rollback and the Restart to Apply button are still to be built. -Section 10 lists the planned work. Its largest item is the supervisor process that restarts the Gateway after a change that needs a restart. +Section 10 lists the planned work. Its largest item is Restart to Apply, a button in the config UI that restarts the Gateway after a change that needs a restart. ## From a chat request to a model's reply @@ -30,7 +29,7 @@ The Gateway reads each provider's API key from its config, maps a requested mode ### The API follows OpenAI's shapes, and each side defines its own structs -The chat, embeddings, and model list routes use OpenAI's request and response shapes. The Gateway's README states the aim: "a program written against that standard works against the gateway". `ChatRequest` names three fields, `model`, `messages`, and `stream`, and the Gateway forwards every other field and every message unchanged. Clients send only these shapes: an Anthropic-shaped request is outside the API, because the Gateway's purpose is exactly one way of doing things. Where the Gateway needs something that a standard lacks, the README states the rule: the route follows the standard shape, the addition is the smallest opt-in extension, and a client still works when the extension is absent. +The chat, embeddings, and model list routes use OpenAI's request and response shapes. The Gateway's README states the aim: "a program written against that standard works against the gateway". `ChatRequest` names the fields `model`, `messages`, and `stream`, and the Gateway forwards every other field and every message unchanged. Clients send only these shapes: an Anthropic-shaped request is outside the API, because the Gateway's purpose is exactly one way of doing things. Where the Gateway needs something that a standard lacks, the README states the rule: the route follows the standard shape, the addition is the smallest opt-in extension, and a client still works when the extension is absent. The Gateway and its clients share JSON, and each side defines its own Rust types: JSON is the contract. A shared client crate would be code, and shared code is the coupling that the JSON contract avoids. The Harness's client is on [Model calls and conversations](models-and-conversations.md) and [The Harness and the Host API](harness-and-host.md). @@ -62,7 +61,7 @@ The stream owns the request's `Permit` until it ends. The streaming HTTP client The route returns an OpenAI-shaped list with one entry for each model in the live routing table, plus the loaded speech-to-text models ([Speech](speech.md)). Each routed entry adds `kind`, `description`, `context`, `thinking`, and the capability keys from the config, such as `max_output`, `images`, `effort_levels`, and `provider`. The list exists so that the Harness fetches authoritative model metadata from the Gateway. -The capability keys describe a model to clients, and the Gateway forwards each request as the client wrote it. Seven of the nine keys, `default_temperature` included, are facts that a client needs to construct a valid request, so a client applies them. The Harness ignores all seven. A local model that is still starting is absent from the list, and `GET /admin/status` reports it under `loading_models`. The list is limited to models that can answer so that the route remains OpenAI-compatible. +The capability keys describe a model to clients, and the Gateway forwards each request as the client wrote it. The keys that are facts a client needs to construct a valid request, `default_temperature` included, are for a client to apply. The Harness ignores all of them. A local model that is still starting is absent from the list, and `GET /admin/status` reports it under `loading_models`. The list is limited to models that can answer so that the route remains OpenAI-compatible. ### `POST /v1/tools/web_search` returns search results and leaves page fetches to the caller @@ -74,13 +73,13 @@ The call is in the Gateway because the Gateway has the Brave key. The route retu ### Auth accepts a bearer key, a handoff cookie, or loopback trust -`check_auth` passes a request when one of three rules matches, tried in this order: the bearer token equals `[server] api_key`, the cookie from the browser handoff verifies, or loopback trust applies. A handler takes an `AuthedCaller` argument, and axum runs the check before the handler's body and before any body parsing. +`check_auth` passes a request when one of these rules matches, tried in this order: the bearer token equals `[server] api_key`, the cookie from the browser handoff verifies, or loopback trust applies. A handler takes an `AuthedCaller` argument, and axum runs the check before the handler's body and before any body parsing. The handoff is `GET /auth?key=`. The Gateway's tray icon opens that URL, the Gateway sets an HttpOnly cookie, and it redirects to `/config/`, so the browser's history records a URL without the key. The Gateway answers a wrong bearer with 401, even from the same machine: loopback trust applies to the absence of credentials, and a caller that presents wrong ones intended to authenticate. The check fails closed: on any uncertainty it refuses the request. ### The Gateway admits a keyless caller on the same machine by default -With `trust_loopback = true` under `[server]`, the default, the Gateway admits a request that meets three conditions: the peer address is loopback, the request omits the `Authorization` header, and its `Sec-Fetch-Site` header is absent, `same-origin`, or `none`. The setting covers every route, the admin routes included. +With `trust_loopback = true` under `[server]`, the default, the Gateway admits a request that meets all of these conditions: the peer address is loopback, the request omits the `Authorization` header, and its `Sec-Fetch-Site` header is absent, `same-origin`, or `none`. The setting covers every route, the admin routes included. The owner's rule: "RUNVIL_GATEWAY_API_KEY should not be required when the incoming connection is on the loopback adaptor". The cost is that on a shared machine another operating-system account can use the Gateway. The header test exists because any web page can send a request to a local port. A browser adds `Sec-Fetch-Site` to every request from a page, so the Gateway answers 401 to a page on another origin. @@ -90,13 +89,13 @@ When the listener's address is loopback, `build_router` wraps every route in `re ### The walled admin tier refuses callers from other machines -The admin routes have two tiers, and the tier is the directory. `admin/open/` has the routes that any admitted caller may use: profiles, status, progress, and queue cancellation. `admin/walled/` has the routes that read secrets in plaintext, write files, or start processes: config, env, apply, revert, restart, and `POST /shutdown`. `build_router` applies `require_loopback` once to the walled tier, so a caller from another machine gets 403 before auth runs, even with the key. +The admin routes have an open tier and a walled tier, and the tier is the directory. `admin/open/` has the routes that any admitted caller may use: profiles, status, progress, and queue cancellation. `admin/walled/` has the routes that read secrets in plaintext, write files, or start processes: config, env, apply, revert, restart, and `POST /shutdown`. `build_router` applies `require_loopback` once to the walled tier, so a caller from another machine gets 403 before auth runs, even with the key. The check is in a crate that every build compiles, because the UI crate is optional and the wall must exist in every build. A structural check fails when a file outside the tier names a `crate::admin::walled::` path. ### Each route area mounts its own routes and declares them in a registry -A route area is a module such as `relay`, `speech`, `models`, or `health`. Each one defines `routes()`, which mounts its handlers, and `ROUTES`, a list of `RouteInfo` values with a path, the methods, and a `Tier` of `Open` or `Walled`. `build_router` merges the areas, so a new endpoint changes one area module. An area behind a Cargo feature is absent from a build that turns the feature off. The four features, `local`, `web-search`, `config-ui`, and `stt`, are on by default. +A route area is a module such as `relay`, `speech`, `models`, or `health`. Each one defines `routes()`, which mounts its handlers, and `ROUTES`, a list of `RouteInfo` values with a path, the methods, and a `Tier` of `Open` or `Walled`. `build_router` merges the areas, so a new endpoint changes one area module. An area behind a Cargo feature is absent from a build that turns the feature off. The features `local`, `web-search`, `config-ui`, and `stt` are on by default. The tests take their list of routes from the registry, because a route list written by hand in a test can miss a route. The Gateway's private crates are the folders under `crates/gateway/`, and [Crates, build, and CI](crates-build-and-ci.md) covers the structural checks on them. @@ -114,7 +113,7 @@ The file exists so that the secrets are independent of what the process inherits ### The Gateway writes a default config on its first run -The Gateway takes its config from `--config` or `RUNVIL_GATEWAY_CONFIG`, then looks beside the executable, then in the working directory, then in `~/.runvil`. When all of these are empty, `generate_default` writes a file into `~/.runvil` with `bind = "127.0.0.1:0"`, a random `api_key`, `trust_loopback = true`, the recommended pair of speech-to-text models, and a profile named `default`. It also writes the state file that selects that profile. +The Gateway takes its config from `--config` or `RUNVIL_GATEWAY_CONFIG`, then looks beside the executable, then in the working directory, then in `~/.runvil`. When all of these are empty, `generate_default` writes a file into `~/.runvil` with `bind = "127.0.0.1:0"`, a random `api_key`, `trust_loopback = true`, the recommended speech-to-text models, and a profile named `default`. It also writes the state file that selects that profile. The Gateway generates the file itself, so its first start works the same whether a person or Workshop launches it. The Gateway generates the key once and reads the same key on every later start. @@ -158,7 +157,7 @@ The route returns the running config as JSON, and `ser_redacted` writes the mark ### The config UI is plain TypeScript on the Gateway's own port -The Gateway serves the UI at `/config/` on its one listener, to loopback callers. The crate `gateway-config-ui` contains the UI, which is TypeScript against the browser's DOM, bundled with esbuild. It has seven pages: Settings, Discover, Local, Remote, Cloud, Profiles, and Secrets. With `?mode=panel` it runs in an iframe inside Workshop and sends each API call to Workshop with `postMessage`, so the key remains outside the iframe ([Workshop: how the app is built](workshop-app.md)). +The Gateway serves the UI at `/config/` on its one listener, to loopback callers. The crate `gateway-config-ui` contains the UI, which is TypeScript against the browser's DOM, bundled with esbuild. It has these pages: Settings, Discover, Local, Remote, Cloud, Profiles, and Secrets. With `?mode=panel` it runs in an iframe inside Workshop and sends each API call to Workshop with `postMessage`, so the key remains outside the iframe ([Workshop: how the app is built](workshop-app.md)). The UI is framework-free and uses the same tools as Workshop's UI. Each element copies an existing product. The owner's rule: "do not innovate UI elements. always look to unsloth first to find an element to use verbatim." @@ -172,7 +171,7 @@ The owner's rule: "profile should only apply to local models ... all remote mode ### A state file beside the config stores the selected profile -`gateway.state.toml` has one key, `active_profile`. At startup the Gateway takes the profile from `--profile`, then from `RUNVIL_PROFILE`, then from the state file. When all three are empty, the Gateway boots, routes every remote model, and logs `no profile selected; serving remote models only`. +`gateway.state.toml` holds `active_profile`, the selected profile. At startup the Gateway takes the profile from `--profile`, then from `RUNVIL_PROFILE`, then from the state file. When all three are empty, the Gateway boots, routes every remote model, and logs `no profile selected; serving remote models only`. When the state file names an undefined profile, the Gateway logs a warning and boots with only the remote models. An operator who deletes the last profile in the config UI and applies the change therefore still has a Gateway that starts. An undefined name in the flag or the variable stops the boot, because the Gateway would otherwise ignore a wrong explicit instruction from the operator in silence. @@ -190,7 +189,7 @@ The route leaves the restart to its caller, although the Gateway could restart i ### A request for a local model that is still starting gets a 503 -`resolve_routed_model` answers a request for a missing name in one of three ways. While the boot load is starting the model's child process, the answer is 503 with the code `model_loading` and `Retry-After: 5`. While a command is active and the config declares the model, for example during its download, the answer is 503 with the code `model_provisioning`. Otherwise the answer is 404. Requests for remote models continue the whole time. +`resolve_routed_model` answers a request for a missing name in one of these ways. While the boot load is starting the model's child process, the answer is 503 with the code `model_loading` and `Retry-After: 5`. While a command is active and the config declares the model, for example during its download, the answer is 503 with the code `model_provisioning`. Otherwise the answer is 404. Requests for remote models continue the whole time. ## 6. Queues, tool-call dialects, and outbound TLS @@ -214,7 +213,7 @@ The Gateway does this work so that every client uses one OpenAI-shaped interface ### The Gateway detects a local model's dialect, and a tie or a miss fails the model -When a local chat model starts, `resolve_local_dialect` reads the child's `/props` and `/v1/models` replies and scores two dialects, `openai` and `gemma3_tool_code`, in plain Rust. A metadata file that the Gateway wrote beside the model file supplies the chat template when `/props` lacks one. The function selects the dialect with the highest score. It returns `DialectResolveError::Tie` for two equal top scores and `NoMatch` for an empty score list. Either one fails the model's start, because the alternative is a silent fallback to `openai`. +When a local chat model starts, `resolve_local_dialect` reads the child's `/props` and `/v1/models` replies and scores each dialect, `openai` and `gemma3_tool_code`, in plain Rust. A metadata file that the Gateway wrote beside the model file supplies the chat template when `/props` lacks one. The function selects the dialect with the highest score. It returns `DialectResolveError::Tie` for two equal top scores and `NoMatch` for an empty score list. Either one fails the model's start, because the alternative is a silent fallback to `openai`. A remote `[[model]]` takes a `tool_dialect` key that defaults to `openai`. A `[[local_model]]` lacks the key, and an operator leaves a local model's dialect to the detection. @@ -238,7 +237,7 @@ The `parallel` key exists because, with one slot, the requests of a concurrent f ### The Gateway downloads model files into its cache and resumes a broken transfer -A model's `source` is a URL or a file path. The Gateway downloads a URL into `/models`, where `cache_dir` defaults to `~/.runvil`, and checks the `sha256` pin when the entry has one. After one hash that matches the pin, a marker file records the digest, the file's size, and its modification time, and a later start skips the hash while all three match. The cache lists a file when its `.meta.json` sidecar exists, and both download paths write the sidecar before they publish the file. Three routes manage the same cache for other programs: `POST /v1/cache`, `GET /v1/cache`, and `DELETE /v1/cache/{sha256}`. Through them another program can tell the Gateway which pinned Hugging Face file it needs. +A model's `source` is a URL or a file path. The Gateway downloads a URL into `/models`, where `cache_dir` defaults to `~/.runvil`, and checks the `sha256` pin when the entry has one. After one hash that matches the pin, a marker file records the digest, the file's size, and its modification time, and a later start skips the hash while all three match. The cache lists a file when its `.meta.json` sidecar exists, and both download paths write the sidecar before they publish the file. These routes manage the same cache for other programs: `POST /v1/cache`, `GET /v1/cache`, and `DELETE /v1/cache/{sha256}`. Through them another program can tell the Gateway which pinned Hugging Face file it needs. A failed download leaves its partial file, and the next attempt asks the server for the remaining bytes, because a restart from the first byte is fatal for a multi-gigabyte download on a connection that resets. A transfer that receives zero bytes for 30 seconds fails, so that Cancel and Quit take effect. The marker is a weaker check than the hash, and the design accepts that: anyone who can write the cache can fake a size and a modification time, and the cache folder has the operator's trust. @@ -256,9 +255,9 @@ The server is a download so that the CUDA toolkit, CMake, and a GPU are all unne ### The Gateway picks a chat template in a fixed order and refuses a model that lacks one -For a local chat model, `resolve_chat_template_file` picks the template in this order: a path in `chat_template_file`, a bundled family written as `builtin:`, a known replacement for a broken template, and last the template inside the model file. The Gateway bundles templates for the twelve families of the `Family` enum. When all four are empty, the start fails with `MissingChatTemplate`, and the message names the fix. +For a local chat model, `resolve_chat_template_file` picks the template in this order: a path in `chat_template_file`, a bundled family written as `builtin:`, a known replacement for a broken template, and last the template inside the model file. The Gateway bundles templates for the families of the `Family` enum. When all of these are empty, the start fails with `MissingChatTemplate`, and the message names the fix. -The three sources ahead of the model file exist to correct bugs in GGUF files after they ship. A missing template fails the start, because the alternative is a silent fallback. +The sources ahead of the model file exist to correct bugs in GGUF files after they ship. A missing template fails the start, because the alternative is a silent fallback. ## 8. Cloud providers and the model sheet @@ -270,7 +269,7 @@ The sheet exists because metadata for the models of closed-weight providers, wri ### Each provider has one Rust file with a public descriptor and private details -Each of the 23 providers has a file such as `anthropic.rs` that exports a `Provider` value: a name, a display name, a `Tier`, the name of its key variable, and its base URLs. The auth header, pagination, field names, and model grouping are private to the file. +Each provider has a file such as `anthropic.rs` that exports a `Provider` value: a name, a display name, a `Tier`, the name of its key variable, and its base URLs. The auth header, pagination, field names, and model grouping are private to the file. A tier is `prime`, `subprime`, `niche`, or `aggregator`. It is an opinion about a provider that the project curates. The sheet records that a model has a setting and copies the provider's own values for it unchanged. A `Provider` describes a vendor in code, and an `[[endpoint]]` is a backend that an operator configured. @@ -308,7 +307,7 @@ The order exists so that the Gateway is live the moment it starts. The bound por ### One queue runs slow work one command at a time -`CommandQueue` has one worker that takes commands in the order they were queued. Two commands run in production: `LoadProfile`, the boot load, and `ApplyConfig`. Each has a `CancellationToken` that the worker checks at download chunks and between phases. `POST /admin/queue/cancel` cancels the active command, and `GET /admin/status` reports the active and waiting commands. Quit and `POST /shutdown` cancel the active command first, and the shutdown waits at most 5 seconds for the worker. +`CommandQueue` has one worker that takes commands in the order they were queued. These commands run in production: `LoadProfile`, the boot load, and `ApplyConfig`. Each has a `CancellationToken` that the worker checks at download chunks and between phases. `POST /admin/queue/cancel` cancels the active command, and `GET /admin/status` reports the active and waiting commands. Quit and `POST /shutdown` cancel the active command first, and the shutdown waits at most 5 seconds for the worker. The rule is that every piece of work that takes time is a command in this queue, and that any command can be cancelled. With one command at a time, each download has the bandwidth to itself. @@ -320,15 +319,17 @@ After the bind, the winner writes `gateway.json` into the run directory with its ### `runvil-gateway` starts the server by default and shows a tray icon on a desktop -The binary has one subcommand, `diagnostics`, and every other launch starts the server. `--no-tray` runs headless for servers and CI, `--browser` opens the Settings page after the bind, and `--login` marks a start from the login entry and overrides `--browser`. A second launch opens the running Gateway's Settings page. +The binary has the subcommand `diagnostics`, and every other launch starts the server. `--no-tray` runs headless for servers and CI, `--browser` opens the Settings page after the bind, and `--login` marks a start from the login entry and overrides `--browser`. A second launch opens the running Gateway's Settings page. `diagnostics` prints a JSON report of the state directory, the config path, the log files, and the discovery file, so that a person who is new to the config can still find the files of a failed run. On a desktop the Gateway shows a tray icon with a status line, Workshop, Settings, Launch at Login, and Quit. The Gateway is a background process, so on an installed system the tray icon is the part of it that a person sees. -### The Gateway asks for a restart with exit code 75, and the supervisor that acts on it is still to be built +### The Gateway asks for a restart with exit code 75, and its supervisor starts the next Gateway `POST /admin/restart` cancels the active command and stops the Gateway with the exit code `RESTART_REQUESTED`, 75. The route answers 409 with the code `restart_unavailable` unless the process started with the hidden flag `--supervised`. A supervised Gateway also watches its stdin and stops when the pipe closes. The first Apply after a start copies each real file to `.prev` before it replaces it, and the next successful start deletes the copies. -These parts are the Gateway's half of the restart design. The other half is a supervisor process that starts the Gateway with `--supervised`, starts a new one after exit code 75, and restores the `.prev` files when the new one fails to boot. The supervisor is still to be built (section 11). The Gateway reports the request through its exit code and leaves the launch of its successor to the supervisor, because a Gateway that started its own successor would race it for the lease and the port. +An ordinary launch, one without `--supervised` or `--print-url`, runs the supervisor in `app/src/supervisor.rs`. The supervisor holds a launch lock for its whole life and runs the serving Gateway as a child with `--supervised`, copying the child's output to its own. A second launch that finds the lock held opens the running Gateway's Settings page. When the child exits with code 75, the supervisor starts a new child with `--preferred-port` set to the port the old child published, so a config that binds port 0 keeps its port across a restart. A restart gets at most five launches, with a wait of 250 ms before the second that doubles for each launch after it. A child that fails its first boot, or that exits with any other code, ends the supervisor with that code. The supervisor never restores the `.prev` files, and the config UI has no Restart to Apply button (section 11). + +The Gateway reports the request through its exit code and leaves the launch of its successor to the supervisor, because a Gateway that started its own successor would race it for the lease and the port. ### The log has fixed limits, a fixed location, and a redaction pass @@ -346,15 +347,15 @@ The terminal shows only log lines: the terminal is for logs, and the UI is for p Each of these items is still to be built. -- **The supervisor and Restart to Apply.** A parent process for the Gateway and a Restart to Apply button in the config UI. The process starts the Gateway with `--supervised`, starts a new one after exit code 75, and restores the `.prev` config files when the new one fails to boot. `POST /admin/restart` answers 409 unless the Gateway started with `--supervised`, and the UI shows a banner that asks the operator for a restart. +- **Restart to Apply and config rollback.** A Restart to Apply button in the config UI, and a supervisor that restores the `.prev` config files when a restarted Gateway fails to boot. The supervisor already starts a new Gateway after exit code 75. The UI shows a banner that asks the operator for a restart, and nothing in the UI calls `POST /admin/restart`. - **An operating-system service.** A headless service with a thin tray client for each user. The Gateway is a process that a person, Workshop, or the login entry starts, and the Linux release archive has a sample systemd unit. - **A choice among endpoints.** A pick among a model's `endpoints` by load, with fallback chains and priority weights. The first priority is a lane for speech requests in a dominion's queue. The Gateway uses the first endpoint in a model's list, and a queue admits waiting callers round-robin. -- **A second protocol.** A translator for providers that lack an OpenAI-compatible API. `Protocol` has one variant, `Openai`, and the Cloud page disables Add for seven of the 23 providers. +- **A second protocol.** A translator for providers that lack an OpenAI-compatible API. `Protocol` has only the variant `Openai`, and the Cloud page disables Add for each provider whose slice lacks `openai_base_url`. - **The thinking switch for remote providers.** A per-model setting that translates `chat_template_kwargs.enable_thinking` for a provider that ignores the field. The Gateway forwards the field as the client wrote it. - **Normalized metrics.** One format of timing record for every backend. The Harness parses the llama.cpp and vLLM timing fields itself. - **Timeouts.** A configurable limit for plain requests and an idle deadline for streams. A plain request has a fixed limit of 120 seconds, and a stream has only the 10 second connect timeout. - **Image generation.** An OpenAI-shaped image route with a local `sd-server` child process. The Gateway's inference routes cover chat, embeddings, rerank, and speech. -- **Sheet upkeep.** An age limit for `stale` slices, versioned asset names at the publisher, and workflow secrets for eight providers. The binary copies a `stale` slice forward for as long as the provider's fetch fails, the workflow overwrites one asset at one URL, and a provider whose key the workflow lacks counts as a failed fetch. +- **Sheet upkeep.** An age limit for `stale` slices, versioned asset names at the publisher, and workflow secrets for the providers that lack one. The binary copies a `stale` slice forward for as long as the provider's fetch fails, the workflow overwrites one asset at one URL, and a provider whose key the workflow lacks counts as a failed fetch. - **Routing reload for an env change.** A reload of the routing table when only the env file changes, so that a new key works before the restart. An Apply that changes the env file reports `restart_required`, and the new value applies at the next start. ## 11. Known gaps @@ -363,7 +364,7 @@ Each item names a feature that is half built, a config key that the code leaves **Restart** -1. The restart feature is half built. The Gateway's half is in the code: `POST /admin/restart` in `app/src/admin/walled/restart.rs`, the hidden options `--supervised` and `--preferred-port` in `app/src/cli.rs`, `RESTART_REQUESTED` and `stdin_watchdog` in `app/src/shutdown.rs`, and the `.prev` copies in `app/src/commands/apply.rs`. The supervisor's half is still to be built: the app lacks a supervisor module, the Gateway's own tests are the one caller in `runvil-gateway` or `runvil` that passes `--supervised`, and the UI lacks the Restart to Apply button. Workshop's `GatewaySupervisor` thread launches a missing Gateway with an empty argument list ([Workshop: how the app is built](workshop-app.md)). `POST /admin/restart` therefore answers 409 on every Gateway that a shipped launcher starts. Apply writes the `.prev` copies, and the next start deletes them unused. +1. The restart feature is half built. The route and the supervisor are in the code: `POST /admin/restart` in `app/src/admin/walled/restart.rs`, the hidden options `--supervised` and `--preferred-port` in `app/src/cli.rs`, `RESTART_REQUESTED` and `stdin_watchdog` in `app/src/shutdown.rs`, and the supervisor in `app/src/supervisor.rs`, which an ordinary launch runs. These parts are still to be built. The supervisor never restores the `.prev` copies that Apply writes in `app/src/commands/apply.rs`, although the doc comments on `rollback_path` and `write_rollback_files` say it does, so a restarted Gateway that fails to boot gets no rollback, and the next successful start deletes the copies unused. The UI lacks the Restart to Apply button, and neither the config UI nor Workshop calls `POST /admin/restart`. Workshop's `GatewaySupervisor` thread launches a missing Gateway with an empty argument list, which is an ordinary launch, so the Gateway it starts runs under the supervisor and the route answers 202 ([Workshop: how the app is built](workshop-app.md)). 2. The doc comment on `supervised` in `app/src/admin/open/status.rs` says the config UI offers Restart to Apply. `main.ts` shows the banner `Restart the gateway to apply these changes.`, and the button is still to be built. **The config crate** @@ -377,9 +378,9 @@ Each item names a feature that is half built, a config key that the code leaves 6. A model that is still downloading. Chapters 1 and 7 say the Gateway answers 503 with `model_loading`, and chapter 7 adds `Retry-After: 5`. `resolve_routed_model` answers `model_provisioning` during a download, and `retry_after_seconds` in `app/src/error.rs` sets the header only for `ModelLoading`. 7. The config version. Chapter 2 calls the config "a single version-2 `gateway.toml` file" above an example with `config-version = 0`. `Config::validate` requires 0. 8. The `[workshop]` table. Chapters 2, 9, 10, and 11 describe it as a section that loads. `RawConfig` refuses unknown keys and lacks a `workshop` field, and `renderWorkshop` in `settings-page.ts` edits `stt`. -9. The diagnostic for `include`. Chapter 2 says an `include` chain fails with its own diagnostic and lists a "removed layout feature" kind. `ConfigErrorKind` in `config/src/api_error.rs` has six kinds, and that kind is absent. -10. Capability keys. Chapter 3 shows a `[model.capabilities]` table with seven keys. `Capabilities` is flattened into the model entry, the test `parses_model_capabilities` writes the keys directly in `[[model]]`, and the struct has two more keys, `voices` and `provider`. -11. UI pages. Chapter 10 names six views. `router.ts` defines seven `PageId` values, and the seventh is `cloud`. +9. The diagnostic for `include`. Chapter 2 says an `include` chain fails with its own diagnostic and lists a "removed layout feature" kind. `ConfigErrorKind` in `config/src/api_error.rs` lacks that kind. +10. Capability keys. Chapter 3 shows a `[model.capabilities]` table. `Capabilities` is flattened into the model entry, the test `parses_model_capabilities` writes the keys directly in `[[model]]`, and the struct has keys that the chapter's table lacks, `voices` and `provider`. +11. UI pages. Chapter 10 names the views but not the Cloud page, which `router.ts` defines as the `PageId` value `cloud`. 12. Progress. Chapter 11 says `GET /admin/progress` replays live operations and that status reports a progress fraction. `progress_sse_response` sends one `Progress` snapshot per change, and `ActiveCommandReply` has `name` and `started_at`. 13. Inline Apply. Chapter 9 says an Apply that touches only boot-owned sections runs inline. `capture_apply` returns `ApplyPlan::Inline` when `gateway.toml.next` is absent, so every config shadow queues a command. 14. Log files. Chapter 1 says five previous runs remain on disk. `RETAINED_SEGMENTS` in `logging/src/config.rs` is five segments of at most 16 MiB each, and a run that writes more than 16 MiB fills several of them. @@ -413,8 +414,7 @@ Each question asks for the reason behind a part of the design. ## 13. Method and limits -- **Code.** The page describes `runvil-gateway` at commit `9369a7d`, `runvil-cloud-providers` at `1817cc4`, `runvil-docs` at `cfd69a4`, and `runvil` at `fa9936f64`. -- **Checks.** The facts on this page were read in the code at those commits. A second session checked the gaps, the values, and the walk-through against the code. +- **Checks.** The facts on this page were read in the code. A second session checked the gaps, the values, and the walk-through against the code. - **Limits.** The sessions read the code and its tests, and left the build and the tests unrun. *2026-11-10 16:44 - Claude Fable 5.2* diff --git a/decisions/guides-and-docs.md b/decisions/guides-and-docs.md index 0440ba3..e35e012 100644 --- a/decisions/guides-and-docs.md +++ b/decisions/guides-and-docs.md @@ -1,23 +1,21 @@ # Guides and docs: design decisions and their reasons - Scope: the language guide, the Gateway guide, the docs site and its build, crate docs, the wording rules, and where each kind of document is stored -- Code: `runvil` at commit `fa9936f64`, `runvil-docs` at `cfd69a4`, and `runvil-gateway` at `9369a7d` -- Update: the text on the source of the API references, the two copies of the wording test, and the paths of Engine and Harness files describe `runvil` at commit `48a4dbc08` and `runvil-harness` at `5bca6f9`, after the Engine and the Harness moved (section 8) - Paths: code paths start at the root of `runvil`, and a path in another repository starts with that repository's name ## Summary -The guides are Markdown chapters in the `runvil-docs` repository, and people edit them by hand. Code in the `runvil` repository builds the docs site. The `build-user-guide` program copies each guide's chapters into a source tree for mdBook, the tool that turns Markdown chapters into a website. The build code calls a guide a book. `cargo xtask site` runs mdBook and rustdoc, writes the landing page, and checks the links. The `site.yml` workflow publishes the result. Inside `runvil`, doc comments and short READMEs are the documentation. Sections 1 to 4 describe these parts. +The guides are Markdown chapters in the `runvil-docs` repository, and people edit them by hand. Code in the `runvil` repository builds the docs site. The `build-user-guide` program copies each guide's chapters into a source tree for mdBook, the tool that turns Markdown chapters into a website. The build code calls a guide a book. `cargo xtask site` runs mdBook and rustdoc, writes the landing page, and checks the links. The `site.yml` workflow publishes the result. In the code repositories, doc comments and short READMEs are the documentation. Sections 1 to 4 describe these parts. -A check of this page against the code found four gaps and left three questions for the owner. Section 6 lists the gaps, and section 7 lists the questions. The largest gap is the Gateway guide: `runvil-docs` has its 11 chapters, and the site build skips them. +Section 6 lists the gaps between this page and the code, and section 7 lists the questions about reasons for the owner. The largest gap is the Gateway guide: `runvil-docs` has its chapters, and the site build skips them. -The largest planned item in section 5 is the Workshop guide, which is one chapter titled "Coming Soon". +The largest planned item in section 5 is the Workshop guide, which is a placeholder chapter titled "Coming Soon". ## From a chapter file to a published page A chapter is one Markdown file, such as `runvil-docs/src/language/12-tools.md`. The number at the start of its name sets its place in the book, and its first H1 heading is its title. -The `site.yml` workflow starts on each push to `main` or `master` of `runvil` and at 07:17 UTC each day. Its `build` job checks out `runvil` and `cppalliance/runvil-docs`, sets `RUNVIL_DOCS` to the docs folder, and runs `cargo xtask site`. +The `site.yml` workflow starts on each push to `main` or `master` of `runvil` and at 07:17 UTC each day. Its `build` job checks out `runvil`, `cppalliance/runvil-docs`, and `cppalliance/runvil-harness`, sets `RUNVIL_DOCS` and `RUNVIL_HARNESS` to the folders of the last two, and runs `cargo xtask site`. The site command runs `build-user-guide` in its `stage` mode as a child process. For each book in the list `BOOKS`, `stage` copies `guide/books//book.toml`, `guide/chrome/back-link.js`, and the book's chapters into `target/site-books//`, and writes `SUMMARY.md` and `index.md` from the chapter titles. @@ -25,15 +23,15 @@ The site command then runs mdBook on each staged book, builds the rustdoc sites ## 1. Where each kind of document is stored -### Inside `runvil`, doc comments and short READMEs are the documentation +### In the code repositories, doc comments and short READMEs are the documentation -Rustdoc builds the API reference from the doc comments on declarations. Ten crates also have a `README.md`, one paragraph that states the crate's responsibility, and the root `README.md` is the project's front page. +Rustdoc builds the API reference from the doc comments on declarations. Many crates also have a `README.md`, usually a short paragraph that states the crate's responsibility, and the root `README.md` of each repository is the project's front page. The documentation has this form because long-form docs inside the repository drift from the code after every session of a coding agent. The agents then treat the stale text as truth. ### The guide chapters are files in `runvil-docs`, and `runvil` builds the site -`runvil-docs` contains the chapters under `src//`. `runvil` contains each book's `book.toml` under `guide/books/`, two files under `guide/chrome/` that add an "All docs" link to every page, and the code and workflow that build the site. The build reads the chapters from the folder that `RUNVIL_DOCS` names and fails when the variable is unset. +`runvil-docs` contains the chapters under `src//`. `runvil` contains each book's `book.toml` under `guide/books/`, the files under `guide/chrome/` that add an "All docs" link to every page, and the code and workflow that build the site. The build reads the chapters from the folder that `RUNVIL_DOCS` names and fails when the variable is unset. Guide prose drifts from the code, and the separate repository puts that prose outside what a coding agent reads while the agent edits the code. @@ -45,11 +43,11 @@ The crate doc comment in `lib.rs` or `main.rs` has a section named `## Invariant ### Each audience has one guide -`runvil-docs` has three sets of chapters: `src/gateway/` for a Gateway operator, `src/language/` for a prompt author, and `src/workshop/` for a Workshop user. A Rust developer reads the API references, because rustdoc covers the Rust API. The owner's rule: "There should not be a user guide per crate. There should be a user guide per product." +`runvil-docs` has a set of chapters for each audience: `src/gateway/` for a Gateway operator, `src/language/` for a prompt author, and `src/workshop/` for a Workshop user. A Rust developer reads the API references, because rustdoc covers the Rust API. The owner's rule: "There should not be a user guide per crate. There should be a user guide per product." -The Workshop set is one placeholder chapter. Workshop changes fast before its beta, and prose about such a product is out of date sooner than anyone can update it. +The Workshop set is a placeholder chapter. Workshop changes fast before its beta, and prose about such a product is out of date sooner than anyone can update it. -### The language guide has sixteen teaching chapters and a quick reference +### The language guide has teaching chapters and a quick reference The files are `01-what-a-prompt-is.md` through `17-quick-reference.md`. Each teaching chapter owns one group of topics, and a feature that fits two chapters belongs to the chapter where an author would look for it first. The quick reference lists every name an author can write, and its `Taught in` column links to the section that teaches the name. @@ -57,7 +55,7 @@ The files are `01-what-a-prompt-is.md` through `17-quick-reference.md`. Each tea The reader is an author of Runvil `.md` prompt files, and the guide omits the Rust API, the internals of the Harness and the Gateway, and every planned form. A chapter teaches an item only when the code or a test shows that an author can use it. The prose is in the present tense and leaves out history, migration, deprecation, and roadmap. -A prompt example is a complete prompt. `runvil-docs/CONTRIBUTING.md` adds three house rules: a single dash, four backticks on every fence, and one line for each paragraph. +A prompt example is a complete prompt. `runvil-docs/CONTRIBUTING.md` adds these house rules: a single dash, four backticks on every fence, and one line for each paragraph. ### People edit the chapters by hand, and the site workflow publishes them as committed @@ -71,7 +69,7 @@ When a coding session finds a doc comment, a code comment, or a guide passage th ### `build-user-guide` stages one mdBook tree for each book in `BOOKS` -`BOOKS` is the one list of books, and it names two: `workshop` and `language`. For each one, `stage` copies the chapters from the `runvil-docs` checkout, sorts them by file name, and reads each title from the file's first H1, which every chapter needs. It writes `SUMMARY.md` and `index.md` into the staged tree, so authors leave both files out of `runvil-docs`. It also writes each book as one file, `runvil--guide.md`. Section 6 covers the Gateway set, which `BOOKS` leaves out. +`BOOKS` is the one list of books, and it names `workshop` and `language`. For each one, `stage` copies the chapters from the `runvil-docs` checkout, sorts them by file name, and reads each title from the file's first H1, which every chapter needs. It writes `SUMMARY.md` and `index.md` into the staged tree, so authors leave both files out of `runvil-docs`. It also writes each book as one file, `runvil--guide.md`. Section 6 covers the Gateway set, which `BOOKS` leaves out. ### `cargo xtask site` builds the whole site under `target/` and fails on a broken link @@ -79,9 +77,9 @@ The command writes the site to `target/site/`, and the flag `--books-only` skips Each link ends in a file name, as in `language/index.html`, because a browser that opens the built site from disk, under `file://`, shows a directory listing for a link to a folder. After the build, `check_links` reads every `.html` page outside the rustdoc folders, except each `404.html`, and fails on each link that names a folder or a missing file. -### The site has five API references and two books, each in its own folder +### The site has API references and books, each in its own folder -`RUSTDOC_SITES` lists five crates: `runvil-engine`, `runvil`, `harness-gateway-client`, `plugin-web`, and `plugin-mcp`. The five are crates of `runvil-harness`, and the site command documents each at the commit that the root `Cargo.toml` of `runvil` pins ([Crates, build, and CI](crates-build-and-ci.md)). A change to their doc comments therefore reaches the site when `runvil` moves that pin. Rustdoc documents each with its default features, so that each published reference shows its crate as the crate's dependents see it. Each API reference and each book has its own folder under `target/site/`, with its own navigation and search. +`RUSTDOC_SITES` lists these crates: `runvil-engine`, `runvil`, `harness-gateway-client`, and `plugin-mcp`. They are crates of `runvil-harness`, and the site command documents each in the checkout that `RUNVIL_HARNESS` names, which the `site.yml` workflow takes from the default branch of `runvil-harness` ([Crates, build, and CI](crates-build-and-ci.md)). A change to their doc comments therefore reaches the site on the next full build. Rustdoc documents each with its default features, so that each published reference shows its crate as the crate's dependents see it. Each API reference and each book has its own folder under `target/site/`, with its own navigation and search. The folders are separate so that each product has documentation of its own. Together they are one site, because GitHub Pages publishes one site for each repository. @@ -95,27 +93,27 @@ The command generates the page from those two lists because a hand-written page `site.yml` deploys the full site on a push to `main` or `master`, on a manual run, and once a night. On a pull request that changes the site's build code, it builds the books with `--books-only` and skips the upload. Only the `deploy` job has the Pages permissions. -The nightly run exists for the chapters: they are in `runvil-docs`, and the workflow starts only on events in `runvil`. A chapter edit therefore appears on the site within a day. A rebuild on every push to `runvil-docs` would need a cross-repository token. +The nightly run exists for the chapters and the documented crates: the chapters are in `runvil-docs`, the crates are in `runvil-harness`, and the workflow starts only on events in `runvil`. A chapter edit or a change to a doc comment therefore appears on the site within a day. A rebuild on every push to `runvil-docs` or `runvil-harness` would need a cross-repository token. ## 4. Crate docs and wording ### A doc comment contains prose, and examples are tests or example programs -The structural check in `no_doctests.rs`, which the `build-xtask` crate of each workspace has, fails any doc comment with a code block that rustdoc would compile, and any doc attribute that reads its text from a file with `include_str!`. Runnable examples are ordinary tests and two programs in `runvil-harness`, `greeter.rs` in `runvil-engine` and `run-prompt.rs` in `runvil`. +The structural check in `no_doctests.rs`, which the `build-xtask` crate of each workspace has, fails any doc comment with a code block that rustdoc would compile, and any doc attribute that reads its text from a file with `include_str!`. Runnable examples are ordinary tests and these programs in `runvil-harness`: `greeter.rs` in `runvil-engine` and `run-prompt.rs` in `runvil`. The project's checks leave out doctest steps, which would add about 67 seconds to every local run. The test runs would therefore skip a doctest that an agent writes, and the structural check exists to fail it. -### `AGENTS.md` defines seven terms, and a Node test checks the rulebooks for four of them +### `AGENTS.md` defines the terms, and a Node test checks the rulebooks for Host, Engine, Harness, and Plugin -The root `AGENTS.md` of each repository defines Engine, Harness, Host, Pack, Plugin, Static Set, and Dynamic Set. Each repository has a copy of the test, `crates/workshop/ui/test/docs-claims.mjs` in `runvil` and `runvil-harness/tools/docs-claims.mjs`. The test reads every rulebook of its repository: each `AGENTS.md`, each `.cursor/rules` file, and each crate doc with an `## Invariants` section. It fails on a lowercase "host", "engine", "harness", or "plugin" outside a short list of allowed phrases. The copy in `runvil-harness` also fails on text in an Engine crate that names the Host. +The root `AGENTS.md` of each repository defines Engine, Harness, Host, Pack, Plugin, Static Set, and Dynamic Set. Each repository has a copy of the test: `tools/docs-claims.mjs` in `runvil`, `runvil-harness/tools/docs-claims.mjs`, and `runvil-workshop/crates/workshop/ui/test/docs-claims.mjs`. The test reads every rulebook of its repository: each `AGENTS.md`, each `.cursor/rules` file, and each crate doc with an `## Invariants` section. It fails on a lowercase "host", "engine", "harness", or "plugin" outside a short list of allowed phrases. The copy in `runvil-harness` also fails on text in an Engine crate that names the Host. -The test exists so that every rulebook uses the four terms one way, and only the root `AGENTS.md` defines them. The pre-push hook of each repository runs the test. +The test exists so that every rulebook uses those terms one way, and only the root `AGENTS.md` defines them. The pre-push hook of each repository runs the test. ## 5. Planned work Each of these items is still to be built. -- **The Workshop guide.** A guide for a person who uses Workshop. The `workshop` book has one placeholder chapter, titled "Coming Soon". +- **The Workshop guide.** A guide for a person who uses Workshop. The `workshop` book has a placeholder chapter, titled "Coming Soon". - **A check of guide examples.** A scheduled job in `runvil-docs` that parses every prompt example with the Engine's parser. The site workflow publishes each chapter as committed, with its examples unparsed. - **A check of names in prose.** A check that fails when a comment or a README names an item that the code lacks. READMEs name code items: `runvil-harness/crates/harness-internal/runner/README.md` names `Host` and `send`. @@ -123,8 +121,8 @@ Each of these items is still to be built. Each item names a place where a guide, a README, a contributing file, or a doc comment differs from the code, or a file in `runvil-docs` that the site build skips. The pages of the other subjects, such as [The prompt language](prompt-language.md), list further differences in what a guide teaches. -1. The site omits the Gateway guide. `runvil-docs/src/gateway/` has 11 chapters. `BOOKS` in `crates/build-user-guide/src/main.rs` lists the other two books, so `stage` skips the Gateway chapters. The root `README.md` of `runvil` says the guide is in the Gateway's repository, and `runvil-gateway/README.md` says it is in "the main Runvil documentation". `runvil-gateway` lacks both the chapters and a site workflow. -2. `runvil-docs/CONTRIBUTING.md` says each of three sets "builds as its own book", and `BOOKS` lists two. It omits that `cargo xtask site` belongs to `runvil` and needs `RUNVIL_DOCS`. +1. The site omits the Gateway guide. `runvil-docs/src/gateway/` has the Gateway chapters. `BOOKS` in `crates/build-user-guide/src/main.rs` lists the other books, so `stage` skips the Gateway chapters. The root `README.md` of `runvil` says the guide is in the Gateway's repository, and `runvil-gateway/README.md` says it is in "the main Runvil documentation". `runvil-gateway` lacks both the chapters and a site workflow. +2. `runvil-docs/CONTRIBUTING.md` says each set "builds as its own book", and `BOOKS` lists only `workshop` and `language`. It omits that `cargo xtask site` belongs to `runvil` and needs `RUNVIL_DOCS`. 3. The crate docs of `build-user-guide` say "The generator owns the chapters". People edit the chapters by hand, and `build-user-guide` copies them unchanged. 4. The site build skips `runvil-docs/src/introduction.md`. The file says Workshop records runs in "an append-only, hash-chained event store", and the crates lack a hash chain. @@ -143,9 +141,7 @@ Each question asks for the reason behind a part of the design. ## 8. Method and limits -- **Code.** The page describes `runvil` at commit `fa9936f64`, `runvil-docs` at commit `cfd69a4`, and `runvil-gateway` at commit `9369a7d`. -- **Checks.** The facts on this page were read in the code at those commits. A second session checked the gaps, the values, and the walk-through against the code. +- **Checks.** The facts on this page were read in the code. A second session checked the gaps, the values, and the walk-through against the code. - **Limits.** The sessions read the code and its tests, and left the build and the tests unrun. -- **Update.** On 2026-11-12 the text that the move of the Engine and the Harness changed was brought to `runvil` at commit `48a4dbc08` and `runvil-harness` at `5bca6f9`. Commit `adca9db10` of `runvil` removed the Engine, Harness, and Plugin crates, which are in `runvil-harness` with their history, and the code that builds the site stays in `runvil`. The update covers the entry on the five API references, the two entries of section 4, and the path in the third planned item. The rest of the page still describes the commits above. *2026-11-10 16:37 - Claude Fable 5.2* diff --git a/decisions/harness-and-host.md b/decisions/harness-and-host.md index e3d6ab0..613c23b 100644 --- a/decisions/harness-and-host.md +++ b/decisions/harness-and-host.md @@ -1,34 +1,29 @@ # The Harness and the Host API: design decisions and their reasons -- Scope: the `runvil` crate, `Host`, `RunSetup`, one Harness per run, the effect loop, inference brokers, Host services, the recorder and run events, the run inbox from the Host's side, stop and cancel -- Code: `runvil` at commit `fa9936f64`, and `runvil-docs` at commit `cfd69a4` -- Update: the walk-through's sentence on filling the `PackRegistry` describes `runvil` at commit `b0693699d`, and the Paths bullet names the repositories as of `runvil` at `48a4dbc08` and `runvil-harness` at `5bca6f9`, after the Engine and the Harness moved (section 10) -- Update: the text on how a Host installs Plugins, on `runvil::plugin`, on `ready`, on `HostServices`, and two planned items describe `runvil-harness` at commit `18361d02`, `runvil-workshop` at `f386801b`, and `runvil-plugin-api` at `03a9fa3` (section 10) -- Update: the text on file operations as effects, on the files of a tool call, on the turn that the effect loop gives its executor, on the record of a tool's file operation, on a stop and a cancel of a tool call that asks for files, the sentence on `ToolFiles` and the count of re-exports in section 1, two planned items, and two questions describe `runvil-harness` at commit `ee199e3a` and `runvil-plugin-api` at `52a4905` (section 10) -- Update: the two entries on the inference broker and on streaming in section 4 describe `runvil-harness` at commit `5d9c7bf8` (section 10) -- Paths: code paths start at the `crates/` folder of `runvil-harness`, the repository of the Engine and the Harness, and a path that begins with `workshop/` starts at the `crates/` folder of `runvil-workshop` +- Scope: the `runvil` crate, `Host`, `RunSetup`, one Harness per run, the effect loop, inference brokers, the timer, what a Host hands its Plugins, the recorder and run events, the run inbox from the Host's side, stop and cancel +- Paths: code paths start at the `crates/` folder of `runvil-harness`, the repository of the Engine and the Harness ## Summary -A Host is an application that runs prompts, and it depends on one crate, `runvil`. At startup it builds one `Host` struct: its installed Packs, a prompt finder, and a timer. For each run it fills a `RunSetup` with a recorder, an inference broker, a file system, and the run's settings, and creates one `Harness`. `Harness::run` is one future. It steps the Engine, performs each effect, writes every event, effect, and answer to the recorder, and returns a `RunReport`. A `RunControl` sends messages to the run, stops the work in flight, or cancels the run. Sections 1 to 6 describe these parts. +A Host is an application that runs prompts, and it depends on one crate, `runvil`. At startup it builds one `Host` through `Host::builder`, from a prompt finder and the Plugins that supply its Packs. For each run it fills a `RunSetup` with a recorder, an inference broker, a timer, a file system, and the run's settings, and creates one `Harness`. `Harness::run` is one future. It steps the Engine, performs each effect, writes every event, effect, and answer to the recorder, and returns a `RunReport`. A `RunControl` sends messages to the run, stops the work in flight, or cancels the run. Sections 1 to 6 describe these parts. -A check of this page against the code found five gaps and left fourteen questions about reasons for the owner. Section 8 lists the gaps, and section 9 lists the questions. The largest gap is in the language guide: the table in chapter 16 says that the Harness changes the response cap and the receive timeout, and `GatewayBroker::new` always uses the defaults. +Section 8 lists the gaps between this page and the code, and section 9 lists the questions about reasons for the owner. The largest gap is in the language guide: the table in chapter 16 says that the Harness changes the response cap and the receive timeout, and `GatewayBroker::new` always uses the defaults. Section 7 lists the planned work. Its largest item is replay: the recorder receives the seed, the start time, every answer, every message, and every file request of a tool call, and the code that passes them to a second run is still to be built. ## From a Host's setup to a recorded result -At startup a Host creates a `PackRegistry` and fills it. `insert_plugin_dir` loads each library Plugin of a directory, `insert_plugin` loads a Plugin that is compiled into the Host, and both kinds follow the C contract. Two Plugins, `plugin-web` and `plugin-mcp`, enter through a second API: each is a Rust function named `install`, which the Host calls with the registry, a configuration value, and the Host's services. The move of the two onto the C contract is planned work (section 7). The Host then passes the registry to `Packs::new`. It builds one `Host` with three fields: `packs`, a `PromptFinder` in `prompts`, and a `Timer` in `timer`. The `run-prompt` example in the `runvil` crate runs one prompt this way, with only the built-in Packs. +At startup a Host calls `Host::builder` with a prompt finder and names its Plugins on the builder. `with_plugin_dir` names each library Plugin of a directory, `with_plugin_file` names the library Plugin in one file, and `with_plugin` names a Plugin that is compiled into the Host by its entry point, and each follows the C contract. One Plugin, `plugin-mcp`, enters through a second API: it is a Rust function named `install`, which the Host names with `with_rust_plugin` as a function that is lent the registry and passes the Host's list of MCP servers and the handle of its tokio runtime. The move of `plugin-mcp` onto the C contract is planned work (section 7). `build()` runs the steps in the order written, adds the built-in Packs, and returns the `Host` inside an `Arc`, with a `PluginReport` for each step. The `run-prompt` example in the `runvil` crate runs one prompt this way, with only the built-in Packs. -For each run the Host calls `Host::parse` with the prompt's name. `Host::parse` finds the source, parses it and every prompt that it lists for `execute`, and checks the `uses:` list of each against the installed Packs. The Host then calls `RunSetup::new` with a recorder and a broker, sets the fields this run needs, and calls `Harness::new`. It takes a `RunControl` from `Harness::control` and awaits `Harness::run`. +For each run the Host calls `Host::parse` with the prompt's name. `Host::parse` finds the source, parses it and every prompt that it lists for `execute`, and checks the `uses:` list of each against the installed Packs. The Host then calls `RunSetup::new` with a recorder, a broker, and a timer, sets the fields this run needs, and calls `Harness::new`. It takes a `RunControl` from `Harness::control` and awaits `Harness::run`. -`Harness::run` first calls the recorder's `begin_run` with a `RunMeta`: a seed drawn from the operating system and the start time from the Host's timer. It asks the broker for its model list and picks the run's model. It creates the run's Pack instances and builds an Engine `Run` with the arguments in `RunSetup.args`. +`Harness::run` first calls the recorder's `begin_run` with a `RunMeta`: a seed drawn from the operating system and the start time from the run's timer. It asks the broker for its model list and picks the run's model. It creates the run's Pack instances and builds an Engine `Run` with the arguments in `RunSetup.args`. The effect loop then calls `Run::step`. It appends the step's events to the recorder, then appends each effect and starts it. A `Chat` effect calls `InferenceBroker::chat`, a `ToolCall` or `Render` effect calls the run's Packs, a `Timer` effect calls `Timer::sleep`, and a `Vfs` effect, which is one file operation, runs at once on the same thread. When an answer is ready, the loop appends it and calls `Run::resume`. The same wait also ends on a cancel, a stop, a sent message, or a file request of a tool call in flight. The loop reports such a request with `Run::request_file`, the next step returns it as a `Vfs` effect that names the call, and the loop performs the operation on the file system of `RunSetup.vfs` and hands the outcome to the call. -When `Run::step` returns `Step::Done`, the loop calls the recorder's `end_run` with the result. `Harness::run` returns a `RunReport` with three fields: the run's id in `run_id`, the same result in `result`, and the messages that the run left unread in `unread`. +When `Run::step` returns `Step::Done`, the loop calls the recorder's `end_run` with the result. `Harness::run` returns a `RunReport` that holds the run's id in `run_id`, the same result in `result`, and the messages that the run left unread in `unread`. -## 1. The three layers and the `runvil` crate +## 1. The layers and the `runvil` crate ### The Engine emits effects, the Harness performs them, and the Host decides policy @@ -42,17 +37,17 @@ A prompt file names a model by a role, such as `strong`, and a set of tools by a ### A Host depends on one crate, `runvil` -`runvil` re-exports three groups of items: the Harness, the Engine items a Host reads and builds, and the Rust Plugin API. `Harness`, `Host`, `RunSetup`, `RunReport`, and `RunControl` are at the crate root, and the rest of the Harness is in `runvil::harness`, which includes the loader of the C contract: `insert_plugin`, `insert_plugin_dir`, `Plugin`, `PluginReport`, and `PluginSource`. The same module has three stock prompt finders: `FindTextPrompt`, `FindFilePrompt`, and `PromptSet` (section 2). `runvil::plugin` has the Rust Plugin API of the crate `runvil-plugin`, such as `PackRegistry`, `Pack`, and `HostServices`. `ToolFiles` is in that module too: a tool call asks for each file operation through it, as a `VfsOp` of `runvil::vfs` that resolves with a `VfsOutcome` (section 3). The types of the C contract are in `runvil-plugin-sys`, outside `runvil`. The crate has 124 re-exports, each at one path. `cargo xtask api` checks that every type from this repository that a `runvil` signature names is among them. +`runvil` re-exports the Harness, the Engine items a Host reads and builds, and the Rust Plugin API. `Harness`, `Host`, `HostBuilder`, `RunSetup`, `RunReport`, and `RunControl` are at the crate root, and the rest of the Harness is in `runvil::harness`, which includes the report types of the loader of the C contract (`Plugin`, `PluginReport`, and `PluginSource`), the `HostResources` that a Host offers its Plugins, and `insert_plugin_dir`, which fills a `PackRegistry` apart from a `Host`. The same module has the stock prompt finders `FindTextPrompt`, `FindFilePrompt`, and `PromptSet` (section 2), and a stock broker, `OfflineBroker`. `runvil::plugin` has the Rust Plugin API of the crate `runvil-plugin`, such as `PackRegistry`, `Pack`, and `PackFactory`. `ToolFiles` is in that module too: a tool call asks for each file operation through it, as a `VfsOp` of `runvil::vfs` that resolves with a `VfsOutcome` (section 3). The types of the C contract are in `runvil-plugin-sys`, outside `runvil`. The crate re-exports each item at one path. `cargo xtask api` checks that every type from this repository that a `runvil` signature names is among them. The owner's goal: "I want the outside world to only see one runvil crate, not runvil-*." ### `runvil` leaves out the Engine's stepping API -`runvil` omits 17 Engine names, the items that step a run and perform its effects, among them `Run`, `Step`, `RunParams`, `Effect`, `EffectAnswer`, and the `cancel` module. Code that steps a run itself imports them from `runvil-engine`, as the Harness does, and a Host cancels through `RunControl`. `runvil` re-exports every other Engine name, including names that the existing Hosts leave unused. +`runvil` omits the Engine names that step a run and perform its effects, among them `Run`, `Step`, `RunParams`, `Effect`, `EffectAnswer`, and the `cancel` module. Code that steps a run itself imports them from `runvil-engine`, as the Harness does, and a Host cancels through `RunControl`. `runvil` re-exports every other Engine name, including names that the existing Hosts leave unused. -### `harness-gateway-client` is the Harness family's second public crate +### `harness-gateway-client` is a public crate of the Harness family, beside `runvil` -`harness-gateway-client` contains what a Host needs to call the Gateway: `GatewayBroker`, which implements `InferenceBroker`; `GatewayChat`, the HTTP client it uses; `fetch_model_catalog`; and `GatewaySearch`, the search provider for the `web` Pack. It is the one Harness crate besides `runvil` that an outside crate may depend on. +`harness-gateway-client` contains what a Host needs to call the Gateway: `GatewayBroker`, which implements `InferenceBroker`; `GatewayChat`, the HTTP client it uses; `fetch_model_catalog`; and `provide_gateway_resources`, which offers the Gateway to the Plugins of the C contract. It also has `TokioTimer`, the stock timer of a Host that runs on tokio. An outside crate may depend on `runvil` and on this crate. The client is a crate of its own for two reasons. Inference is a Host service and `runvil` excludes tokio, so `runvil` leaves HTTP to the Host. Every Host still needs a standard Gateway client. [The Gateway](gateway.md) covers the routes it calls. @@ -60,13 +55,13 @@ The client is a crate of its own for two reasons. Inference is a Host service an `harness-runner`, the crate with the effect loop, uses `futures-util` for its async work, and a structural check fails when `runvil` or a crate under `crates/harness-internal` lists `tokio` under `[dependencies]`. A Host therefore awaits `Harness::run` on whichever executor it has. -A Host's own parts may still need a runtime: the docs of `GatewayBroker` state that its futures need tokio. +A Host's own parts may still need a runtime: the docs of `GatewayBroker` and of `TokioTimer` state that their futures need tokio. ## 2. `Host`, `RunSetup`, and one Harness per run ### A Host builds one `Host` at startup and one `RunSetup` for each run -`Host` is a struct with three public fields: `packs`, `prompts`, and `timer`. A Host builds one and shares it behind an `Arc`. `RunSetup` is a struct with nine public fields that the Host fills for each run. The two structs sort every input by lifetime: `Host` contains what every run of one Host shares, and `RunSetup` contains what one run gets on top of the Host. +`Host::builder(prompts)` takes the Host's prompt finder and returns a builder. A `with_` method of the builder names one Plugin, or sets the resources that the Host offers its Plugins, and `build()` installs the Plugins in the order written and returns the `Host` inside an `Arc`, which every run shares. The fields of `Host` are private, so `build()` is the one way to get a `Host`. `RunSetup` is a struct of public fields that the Host fills for each run. The two structs sort every input by lifetime: `Host` contains what every run of one Host shares, and `RunSetup` contains what one run gets on top of the Host, which includes the services that the run waits on: the recorder, the broker, and the timer. ### `Harness::new` takes the `Host`, a parsed `Prompt`, and the `RunSetup`, and `run` consumes the Harness @@ -74,30 +69,29 @@ A Host's own parts may still need a runtime: the docs of `GatewayBroker` state t ### `Host::parse` parses the prompt before a run exists, and a parse failure returns to the caller unrecorded -`Host::parse(name)` calls `Prompt::parse` with the Host's `PromptFinder`, which parses the named prompt and every prompt that the `prompts:` lists reach from it ([The Engine](engine.md)). It then checks the `uses:` list of each of those prompts against the installed Packs. It returns the parse error unchanged, or a `RequirementsUnmet` error that names each declared Pack that the Host lacks or that a Plugin inserted as unavailable. The line of a Pack that only a linked prompt declares starts with that prompt's name, as in `- review.md: web is unavailable: runvil/web is not installed`. Only a Rust `install` inserts a Pack as unavailable. The loader drops every Pack of a contract Plugin whose load fails, so `Host::parse` reports each of them with the text `is not installed`, and the reason is in the `PluginReport` that `insert_plugin_dir` returned. The recorder's first call for a run is `begin_run`, inside `Harness::run`. +`Host::parse(name)` calls `Prompt::parse` with the Host's `PromptFinder`, which parses the named prompt and every prompt that the `prompts:` lists reach from it ([The Engine](engine.md)). It then checks the `uses:` list of each of those prompts against the installed Packs. It returns the parse error unchanged, or a `RequirementsUnmet` error that names each declared Pack that the Host lacks or that a Plugin inserted as unavailable. The line of a Pack that only a linked prompt declares starts with that prompt's name, as in `- review.md: web is unavailable: runvil/web is not installed`. Only a Rust `install` inserts a Pack as unavailable. The loader drops every Pack of a contract Plugin whose load fails, so `Host::parse` reports each of them with the text `is not installed`, and the reason is in the Host's `plugin_reports()`. The recorder's first call for a run is `begin_run`, inside `Harness::run`. ### A prompt that lists other prompts needs a finder that serves each listed name The Harness calls the Host's finder only inside `Host::parse`. One parse finds the named prompt and then each prompt that the `prompts:` lists reach, so the finder has to serve every one of those names. A listed name that the finder lacks fails the parse, and the failure is placed on the `prompts:` line of the prompt that lists the name. -`runvil::harness` has three stock finders. `FindTextPrompt` serves one prompt from text, and `FindFilePrompt` serves one from a file. Each fails a find for any other name with the code `not_found` and the message `no prompt named {name}`, so the two fit a prompt that lists no prompt, or only itself. `PromptSet` serves the prompts that a Host inserts as text, as files, and as directories, each file of a directory under its file name, such as `greet.md`. A Host whose prompts execute each other therefore gives its `Host` a `PromptSet`, or a finder of its own that serves each name. +`runvil::harness` has stock finders. `FindTextPrompt` serves one prompt from text, and `FindFilePrompt` serves one from a file. Each fails a find for any other name with the code `not_found` and the message `no prompt named {name}`, so the two fit a prompt that lists no prompt, or only itself. `PromptSet` serves the prompts that a Host inserts as text, as files, and as directories, each file of a directory under its file name, such as `greet.md`. A Host whose prompts execute each other therefore gives its `Host` a `PromptSet`, or a finder of its own that serves each name. A run that has started holds its parsed prompt and every prompt that one links, and an `execute` runs one of those. `PromptSet::rescan` lists the set's directories again, which changes what later parses find and changes no run in progress. The test `a_run_executes_the_prompt_its_parse_linked_though_the_set_has_lost_that_prompts_file` in `harness-internal/runner/tests/it/harness-execute.rs` removes a listed prompt's file after the parse and rescans: the run still executes the prompt, and the next `Host::parse` fails with `no prompt named greet.md`. Every find happens in `Host::parse` because a stock finder reads a file with a blocking `std::fs` call, and a parse runs before the run's future exists. The rule holds for a prompt that executes others because the parse has read them all. -### `RunSetup::new` takes the recorder and the broker, and every other field has a default +### `RunSetup::new` takes the recorder, the broker, and the timer, and every other field has a default -`RunSetup::new(recorder, broker)` sets the two required fields. The other seven start at defaults: an empty in-memory file system in `vfs`, empty values in `selected_model` and `workspace_roots`, the empty object `{}` in `args`, `RunLimits::default()` in `limits`, 10 in `max_tool_calls_in_flight`, and `false` in `has_user`. Workshop leaves `limits` and `max_tool_calls_in_flight` at their defaults, among them 24 loop rounds and 8 concurrent tasks. +`RunSetup::new(recorder, broker, timer)` sets the required fields. The other fields start at defaults: an empty in-memory file system in `vfs`, no selection in `selected_model`, the empty object `{}` in `args`, `RunLimits::default()` in `limits`, 10 in `max_tool_calls_in_flight`, `false` in `has_user`, and no callback in `streaming`. Workshop leaves `limits` and `max_tool_calls_in_flight` at their defaults, among them 24 loop rounds and 8 concurrent tasks. The default of `args` is `{}`, which is what a caller with nothing to pass sends. A Host that leaves the field alone therefore starts a valid run of every prompt that requires no argument. -The broker is a required argument because every run needs inference. A Host that leaves it out fails to compile. With an optional broker, the Harness would refuse each run of such a Host as it prepares the run. +The broker is a required argument because every run needs inference. A Host that leaves it out fails to compile. With an optional broker, the Harness would refuse each run of such a Host as it prepares the run. A Host that runs prompts without a model passes `OfflineBroker`, so the code that builds the setup says so. The timer is a required argument for a reason of the same kind: a timer that a Host could leave out would be missed only at a timed wait inside a run. ### The Harness reads each `RunSetup` field once, and the run's tool calls work in the one file system that the setup holds -The Harness reads each field once per run. This matters most for `vfs`, the file system that the run's tool calls work in: the Harness performs every file request of the run's tool calls on that one file system. The run's store is no part of it. The Engine makes each run an empty store of its own, which no setup fills and no report returns. The `Policy` of that file system, such as a `ModePolicy` in its Ask, Plan, or Agent mode, sees the file operations of tool calls. So does the operation sink that `VfsRefBuilder::on_op` installs. Neither sees a store operation. A prompt reads `selected_model` and the first of `workspace_roots` through `ui()`. - +The Harness reads each field once per run. This matters most for `vfs`, the file system that the run's tool calls work in: the Harness performs every file request of the run's tool calls on that one file system. The run's store is no part of it. The Engine makes each run an empty store of its own, which no setup fills and no report returns. The `Policy` of that file system, such as a `ModePolicy` in its Ask, Plan, or Agent mode, sees the file operations of tool calls. So does the operation sink that `VfsRefBuilder::on_op` installs. Neither sees a store operation. The Host chooses where the files of a run's tool calls are stored, because the Engine only executes the prompt, and each file request of a tool call works on the file system that the Engine's caller supplies. No Host policy applies to the store, because a store is no part of that file system: a policy decides what a run's tools may do to the Host's files, and the store is the run's own memory. [Files and the VFS](files-and-the-vfs.md) covers the file system. ### The Harness passes `args` to the Engine as the Host set it, and the run's result is the report's `result` @@ -108,9 +102,9 @@ The Harness leaves the check to the Engine so that one piece of code decides wha A run has one way in, its arguments, and one way out, its result. The owner's rule: "If a prompt wants to return a file, it should return it as the string of its return value." -### `Harness::run` returns a `RunReport` for every run, and its one error is `RecorderFailed` +### `Harness::run` returns a `RunReport` for every run, and its error is `RecorderFailed` -`RunReport` has three fields: `run_id`, `result`, and `unread`. `result` is the final text or the `Error` that ended the run, and a cancel is the error whose code is `canceled`. The record begins before the model lookup, so a failed lookup and an early cancel each produce a report. `Harness::run` returns `Err` in one case, a recorder that refused a write, with the code `RecorderFailed`. +`RunReport` holds `run_id`, `result`, and `unread`. `result` is the final text or the `Error` that ended the run, and a cancel is the error whose code is `canceled`. The record begins before the model lookup, so a failed lookup and an early cancel each produce a report. `Harness::run` returns `Err` when a recorder refuses a write, with the code `RecorderFailed`. The Harness delivers a failed prompt as a result that says why the prompt failed, the same way it delivers a text that the prompt produced through inference. @@ -138,9 +132,9 @@ A `Vfs` effect is one file operation, a `VfsOp`. Its `asker` says who asked for The prompt's Lua asks with a `store` call, and the operation works on a store of the run. A run has the store that it starts with, and one more for each `execute` ([Files and the VFS](files-and-the-vfs.md)). The asker is `VfsAsker::Lua`, which names the store by the id of its chain, and the access is a view of that store under the calling chain's identity. The loop performs the operation with `perform_vfs_op` on that view and answers with `EffectAnswer::Vfs`, the whole outcome. The Harness reaches a run's store only to perform the one operation of a `Vfs` effect, through that effect's view. It puts nothing in the store before a run and reads nothing from it after. -A tool call asks through the files of its `ToolContext` ([Tools and Packs](tools-and-packs.md)). `ToolContext::files` returns a `ToolFiles`, a trait of the crate `runvil-plugin` whose one method, `request`, takes a `VfsOp` and returns a future of its outcome. The loop gives each tool call a `CallDesk` as its files, and a request joins the desk at the first poll of its future. The loop reads the requests of the calls in flight beside their answers and reports each one to the run with `Run::request_file`. The run issues the request at its next step as a `Vfs` effect whose asker is `VfsAsker::Tool` with the id of the call, and the loop performs it on the file system of `RunSetup.vfs`, under the call's own identity and the Host's policy. The loop then resumes the run with `EffectAnswer::VfsReceipt`, a receipt of the outcome, and hands the whole outcome to the call, which stays in flight throughout. A call that has landed or was dropped gets no further operation: the loop drops a request it still makes, and answers `Dropped`, unperformed, a `Vfs` effect that the run issued for it. A panic of the Host's policy or storage inside an operation reaches the tool as a failed operation, a `VfsError::Backend` with the message `the file operation panicked`, and the run goes on. +A tool call asks through the files of its `ToolContext` ([Tools and Packs](tools-and-packs.md)). `ToolContext::files` returns a `ToolFiles`, a trait of the crate `runvil-plugin` whose method `request` takes a `VfsOp` and returns a future of its outcome. The loop gives each tool call a `CallDesk` as its files, and a request joins the desk at the first poll of its future. The loop reads the requests of the calls in flight beside their answers and reports each one to the run with `Run::request_file`. The run issues the request at its next step as a `Vfs` effect whose asker is `VfsAsker::Tool` with the id of the call, and the loop performs it on the file system of `RunSetup.vfs`, under the call's own identity and the Host's policy. The loop then resumes the run with `EffectAnswer::VfsReceipt`, a receipt of the outcome, and hands the whole outcome to the call, which stays in flight throughout. A call that has landed or was dropped gets no further operation: the loop drops a request it still makes, and answers `Dropped`, unperformed, a `Vfs` effect that the run issued for it. A panic of the Host's policy or storage inside an operation reaches the tool as a failed operation, a `VfsError::Backend` with the message `the file operation panicked`, and the run goes on. -A tool of a library Plugin asks through the same files. The loader, the crate `harness-plugin-loader`, follows version 0.5 of the C contract, in which the `RvToolCallArgs` of a step has nine file functions: `file_stat`, `file_list`, and `file_read` read, and `file_write`, `file_append`, `file_mkdir`, `file_remove`, `file_rename`, and `file_copy` change files. A file function takes the one request of its step and fills nothing, and a step that made a request returns `RV_PENDING`. The loader asks the `ToolFiles` of the call for the operation, and the call's next step receives the answer as an `RvFileAnswer`. The loader reaches the run's files in no other way, so the Harness performs and records every file operation of a library tool, and the Host's policy applies to each one. +A tool of a library Plugin asks through the same files. The loader, the crate `harness-plugin-loader`, follows the C contract, in which the `RvToolCallArgs` of a step has file functions: `file_stat`, `file_list`, and `file_read` read, and `file_write`, `file_append`, `file_mkdir`, `file_remove`, `file_rename`, and `file_copy` change files. A file function takes the one request of its step and fills nothing, and a step that made a request returns `RV_PENDING`. The loader asks the `ToolFiles` of the call for the operation, and the call's next step receives the answer as an `RvFileAnswer`. The loader reaches the run's files in no other way, so the Harness performs and records every file operation of a library tool, and the Host's policy applies to each one. While the recorder answers at once, the loop goes from one file request to the next without a return to the executor that polls the run. So once in every 32 file requests of the run's tool calls, the value of `REQUESTS_PER_TURN` in `tool_files.rs`, the run's future wakes itself and returns pending once, and the loop reports the request after that return. Which task the executor polls next is the executor's choice, so the return is one more chance for the Host's other tasks, one that stops or cancels the run among them, and no promise. An executor that takes its tasks in turn runs them then, so a tool call that keeps asking for files gives up the thread at each such return. A file operation is one blocking call, so the loop returns between operations and never in the middle of one, however long a backend takes. Only the file requests of tool calls count: a Lua loop of `store` calls, and a Lua loop of calls to a tool whose future is ready at its first poll, run on without such a return while the recorder answers at once. @@ -162,7 +156,7 @@ A `Step::Pending` with an empty effect list, while every earlier effect is answe When the main chain, the run's root task, waits on its inbox of sent messages, `Step::Pending` sets `waiting_for_input`, and the loop waits for a `RunControl::send` or a cancel. The same applies to a run whose `has_user` is `false`, since a Host may still call `RunControl::send` from code. -## 4. Inference, the clock, and Host services +## 4. Inference, the clock, and what a Host hands its Plugins ### The Host supplies model inference as an `InferenceBroker` @@ -170,9 +164,9 @@ When the main chain, the run's root task, waits on its inbox of sent messages, ` The Host supplies inference so that the Host's broker owns the Gateway's URL, its key, and its model catalog, and `RunSetup` needs only the broker. [Model calls and conversations](models-and-conversations.md) covers the request a round sends. -### The Harness picks the run's model once, and that model fills all five roles +### The Harness picks the run's model once, and that model fills every role -Before it prepares the run, the Harness awaits `models()` until the broker answers or the Host cancels the run, so a broker may wait until it has a model. The Harness picks the model that `RunSetup.selected_model` names, or the first listed model when the field is `None`. A selection absent from the list ends the run with `RequirementsUnmet` and the reason `model_absent`. The Harness passes the Engine a role map with one entry, `default`, so the picked model fills all five roles. +Before it prepares the run, the Harness awaits `models()` until the broker answers or the Host cancels the run, so a broker may wait until it has a model. The Harness picks the model that `RunSetup.selected_model` names, or the first listed model when the field is `None`. A selection absent from the list ends the run with `RequirementsUnmet` and the reason `model_absent`. The Harness passes the Engine a role map with one entry, `default`, so the picked model fills every role. The map has one entry because `RunSetup` has one `selected_model`, and section 7 lists a model for each role as planned work. Workshop's broker uses the wait: it answers once its catalog has a chat-capable model. @@ -186,23 +180,25 @@ The callback returns at once and never calls into the Harness. It runs inside th ### The Host's `Timer` performs each sleep and stamps each run's start -`Timer` is a trait with two methods. `sleep(duration)` returns the future that the loop polls for a `Timer` effect. `now()` returns the time that the Harness records as the run's start and passes to the Engine, and its default reads the system clock. +`Timer` is a trait. `sleep(duration)` returns the future that the loop polls for a `Timer` effect. `now()` returns the time that the Harness records as the run's start and passes to the Engine, and its default reads the system clock. + +The timer is a required argument of `RunSetup::new`, so a Host that leaves it out fails to compile. A timer that a Host could leave out would be missed only at a timed wait inside a run. It is part of the setup because a run is what uses it: the Harness reads the run's start from it and performs the run's sleeps through it, and a parse never waits. Two runs of one Host may each have a clock of their own. `harness-gateway-client` has a stock timer, `TokioTimer`, whose `sleep` is one `tokio::time::sleep` and whose `now` is the default, so a Host on tokio passes it to `RunSetup::new`. A Host on another runtime implements `Timer` over that runtime's sleep. -The timer is a required field of `Host`. As an entry of `HostServices` it could be missing, and a missing timer would show only at a timed wait inside a run. +### The Host fills one `HostResources`, and each tool call of a contract Plugin is lent them as text -### The Host fills one `HostServices` map, and the `install` of each Rust Plugin reads it +`HostResources` holds what a Host offers the Plugins it loads through the C contract: JSON values under names of two segments, a vendor and a name, such as `runvil/web-search`. A Host makes one with `HostResources::new`, offers each resource with `provide(name, read)`, and passes the whole to the builder with `with_resources`. `read` is a function that returns the resource's value, or nothing when the Host has none to offer right now. `provide` refuses a name that is not a vendor and a name, and a name that is offered already, with an `InvalidValue` error that names it. A Host that loads nothing through the contract, or offers nothing, leaves `with_resources` out, and the builder then offers an empty one. -`HostServices` is a map from a two-segment id, such as `runvil/tokio-runtime`, to a typed object. The Host fills one map at startup and passes it to the `install` function of each Rust Plugin, and a Pack factory stores what its instances need. The C contract lacks Host services: a contract Plugin receives the contract's version and the functions of its load call, so the bashkit Plugin owns a tokio runtime of its own. Services for contract Plugins are planned work (section 7). The recorder, the broker, and the timer are required values outside the map. +The Harness calls each `read` when a tool call of a contract Plugin starts, on the task that polls the run, so `read` returns at once. The call is lent the JSON text of one object that holds each value under its name, and every step of the call is lent that same text. A `read` that returns nothing leaves its resource out of that call, and a `read` that panics ends that one call as any panic in a call does. A clone of a `HostResources` shares the functions, and its `Debug` lists the names and leaves the values out, because a value can hold a key. -A `ServiceKey` binds each id to the type of its object, so a Host provides only an object of that type under the key. [Tools and Packs](tools-and-packs.md) covers a Pack's side. +A resource is read when a call starts so that a Host whose value changes has nothing more to do: the next call reads the new value, and no task of the Host hands changes on. `provide` takes a function alone, because a value that stays the same is a function that returns it. A resource is a JSON value because that is what crosses the contract: a Plugin in any language reads the text, where a Rust object would stay on the Host's side. [Tools and Packs](tools-and-packs.md) covers a Plugin's side. ## 5. The recorder and run events ### The Host supplies the `RunRecorder` and receives a run's events through it -`RunRecorder` is a trait with three methods: `begin_run(meta)` returns a `RunId`, `append(run, record)` adds one record, and `end_run(run, result)` closes the run. The Host chooses the storage: `MemoryRecorder` stores runs in memory, and Workshop's recorder writes a Turso database. Calls for different runs may overlap, so each recorder locks its own state. +`RunRecorder` is a trait with these methods: `begin_run(meta)` returns a `RunId`, `append(run, record)` adds the record of one effect or one answer, `append_event(run, record, event)` adds the record of one event with the event itself, and `end_run(run, result)` closes the run. The Host chooses the storage: `MemoryRecorder` stores runs in memory, and Workshop's recorder writes a Turso database. Calls for different runs may overlap, so each recorder locks its own state. -A Host sees a run's events through its recorder: `append` is the only call in which the Harness passes an event to the Host. +A Host sees a run's events through its recorder: `append_event` is the one call in which the Harness passes an event to the Host. Its default stores the record through `append`, so a recorder that only stores a run implements `append` and leaves `append_event` as it is. ### The Harness writes every event, effect, and answer in loop order @@ -224,7 +220,7 @@ A second event kind for `models.infer` replies would duplicate the reply payload ### `RunMeta` has the seed, a reserved flags field, and the start time -`begin_run` receives a `RunMeta` with three fields: `seed`, `flags`, and `started_at`. `flags` is reserved for replay, and the Harness writes 0. The field exists so that an Engine change that alters an exit rule or a protocol detail sets a flag, which a replay of the run reads. The recorder issues the `RunId`, and every later record names the run by that id. +`begin_run` receives a `RunMeta` with `seed`, `flags`, and `started_at`. `flags` is reserved for replay, and the Harness writes 0. The field exists so that an Engine change that alters an exit rule or a protocol detail sets a flag, which a replay of the run reads. The recorder issues the `RunId`, and every later record names the run by that id. The recorder receives every record under its run's id, so an event omits a name for its run. Workshop's recorder stores its own label for a run in an `agent` column. @@ -236,11 +232,11 @@ The rule exists for replay, which is still to be built: a replay compares the re ### Record formats change in place, and every reader changes with them -A commit that changes an event, a record, or `RunMeta` also changes every reader, and it leaves stored data as it is. `AGENTS.md` states the principle for the whole repository: "There are no users and no recorded runs, logs, or stored data to preserve, so backward compatibility does not matter". +A change to an event, a record, or `RunMeta` also changes every reader, and it leaves stored data as it is. `AGENTS.md` states the principle for the whole repository: "There are no users and no recorded runs, logs, or stored data to preserve, so backward compatibility does not matter". ## 6. The run inbox, stop, and cancel -### `RunControl` has three calls: `send`, `stop_round`, and `cancel` +### `RunControl` has the calls `send`, `stop_round`, and `cancel` `RunControl` is a handle that the Host clones and calls from any thread. `send(text)` queues a message for the run's main chain. `stop_round()` drops the work in flight, and the run continues. `cancel()` ends the run. @@ -252,7 +248,7 @@ A stop is a call of its own because a cancel ends the run. After a cancel, Works `send` applies only to the main chain: a sub-agent is a task in the same run, and only a run has a `RunControl`. [Tasks and fanout](tasks-and-fanout.md) covers what the main chain does with a message. -### Two events tell the Host whether the main chain waits for input +### The inbox events tell the Host whether the main chain waits for input The Engine emits `inbox_message` when a message enters an inbox and `inbox_waiting` when a chain starts to wait on an empty inbox. Both name the chain in their `provenance`, and the main chain is task `0`. A Host reads them as its recorder receives them: after `inbox_waiting` on task `0` the run waits for the person, and after the next `inbox_message` it continues. Workshop converts them to its `awaiting_input` and `user_message` agent events. @@ -285,12 +281,12 @@ A message leaves tool calls running. To cut a long tool call short, the Host sto Each of these items is still to be built. - **Replay and resume.** A driver that builds a run from a recorded seed and start time, passes the recorded answers to `Run::resume`, the messages to `Run::deliver`, and the file requests of tool calls to `Run::request_file`, each in its recorded order and at its recorded step, and reports where the second run diverges. The recorder receives the seed, the start time, every answer, every message, and every file request of a tool call, which is the record of its `Vfs` effect. -- **A model for each role.** `RunSetup` has one `selected_model`, which fills all five roles. +- **A model for each role.** `RunSetup` has one `selected_model`, which fills every role. - **Small records for large answers.** An answer record stores the whole tool output, or the whole text that a `store` call read, so the record contains a copy of everything a script reads. The answer record of a tool's file operation holds a receipt, and the effect record of a tool's write holds the bytes. When those bytes are among the tool's arguments, the record holds them twice: in the `ToolCall` effect record and in the `Vfs` effect record. - **Request limits for a Host.** `GatewayBroker::new` always uses a receive timeout of 120 seconds and a reply cap of 16 MiB. - **A step hook.** Pack code that rewrites an effect or its answer between `Run::step` and the performers. The loop starts each effect as `Run::step` returned it and resumes the run with each answer as its performer returned it. -- **More Host services.** Secrets, a schedule, a model client for Packs, the parent environment of a sub-run, and a way for a contract Plugin to read a service. The two Rust Plugins read two services: `plugin-web` and `plugin-mcp` read `runvil/tokio-runtime`, the Host's runtime handle, and `plugin-web` reads `runvil/search-provider`, the search provider for the `web` Pack. A contract Plugin reads none. -- **One Plugin API.** `web` and `mcp` as Plugins that follow the C contract, which a Host inserts with `insert_plugin`, and with them contract functions for configuration, Host services, an unavailable Pack with its reason, the origin of a call, and a wait on outside work. The two Plugins are Rust functions named `install`, and `insert_plugin` has tests as its only callers ([Tools and Packs](tools-and-packs.md)). +- **More for a Host to hand its Packs.** Secrets, a schedule, a model client for Packs, and the parent environment of a sub-run. A library Plugin is lent the Host's resources, and the one resource that a shipped Pack reads is the Gateway's web search. +- **One Plugin API.** `mcp` as a Plugin that follows the C contract, which a Host names with `with_plugin`, and with it contract functions for configuration, an unavailable Pack with its reason, and the origin of a call, and something in place of the runtime handle that the Host passes to `install`. The Plugin is a Rust function named `install`, compiled into the Host, which takes its list of servers and the Host's runtime handle as arguments ([Tools and Packs](tools-and-packs.md)). - **Approvals.** An approval as an effect of its own, with the dialog in the Host. The effect kinds are `Chat`, `Render`, `ToolCall`, `Vfs`, and `Timer`. When the `Policy` of `RunSetup.vfs` returns `Ask` for a file operation of a tool call, the file system refuses it with `VfsError::ApprovalRequired`. The `Policy` never sees a store operation (section 2). - **Requirement gaps before a run.** A call that returns every gap as data before a run exists. `Host::parse` reports missing Packs, and every other gap ends a run with a `RequirementsUnmet` error. @@ -301,13 +297,12 @@ Each item names a place where a guide or a doc comment differs from the code, or **The language guide** 1. Request limits. The table in chapter 16 says the Harness changes the response cap and the receive timeout. `GatewayChat::with_request_limits` sets them, and `GatewayBroker::new` always uses the defaults. -2. Start time. Chapter 4 says the start is stamped "from the system wall clock". The Harness calls `now()` on the Host's `Timer`, whose default reads the system clock. +2. Start time. Chapter 4 says the start is stamped "from the system wall clock". The Harness calls `now()` on the run's `Timer`, whose default reads the system clock. **Doc comments and code that only tests call** 3. The doc comment on `RunMeta.seed` says that the run's id derives from the seed. The recorder issues each `RunId`. -4. The doc comment on `HostServices::provide` names the reason of an invalid id as `make_invalid_id_error`. The code writes `invalid_id`. -5. `CancelHandle::child()` has tests as its only callers. Section 6 describes it. +4. `CancelHandle::child()` has tests as its only callers. Section 6 describes it. ## 9. Questions for the owner @@ -332,7 +327,7 @@ Each question asks for the reason behind a part of the design. **The inbox and cancel** -9. Why does a Host learn whether the run waits for input from two events, through its recorder? +9. Why does a Host learn whether the run waits for input from events, through its recorder? 10. Why does `send` return `false` after the run has ended, where it could return an error? 11. What will call `CancelHandle::child()`? 12. Why does every run get a record, including one that ends before its first step? @@ -344,13 +339,7 @@ Each question asks for the reason behind a part of the design. ## 10. Method and limits -- **Code.** The page describes `runvil` at commit `fa9936f64` and `runvil-docs` at commit `cfd69a4`. -- **Checks.** The facts on this page were read in the code at those commits. A second session checked the gaps, the values, and the walk-through against the code. +- **Checks.** The facts on this page were read in the code. A second session checked the gaps, the values, and the walk-through against the code. - **Limits.** The sessions read the code and its tests, and left the build and the tests unrun. -- **Update.** On 2026-11-11 the walk-through's sentence on filling the `PackRegistry` was brought to `runvil` at commit `b0693699d`, where a Host also loads library Plugins with `insert_plugin_dir`. The rest of the page still describes the commits above. -- **Move.** On 2026-11-12 the Paths bullet was brought to `runvil` at commit `48a4dbc08` and `runvil-harness` at `5bca6f9`. Commit `adca9db10` of `runvil` removed the Engine, Harness, and Plugin crates, which are in `runvil-harness` with their history and at the same paths under `crates/`. Workshop, the Host in `runvil`, takes the `runvil` crate from that repository as a git dependency at a pinned commit ([Crates, build, and CI](crates-build-and-ci.md)). The text of the page still describes the code at the commits above, when those crates were in `runvil`. -- **Update.** On 2026-11-13 the text on Plugins and Host services was brought to `runvil-harness` at commit `18361d02`, `runvil-workshop` at `f386801b`, and `runvil-plugin-api` at `03a9fa3`. Workshop moved to the `runvil-workshop` repository after the commits of the Move note. The update covers the first paragraph of the walk-through, the entry on the one crate in section 1, the entries on `Host::parse` and on `ready` in section 2, the entry on `HostServices` in section 4, two items of section 7, and the Paths bullet. It states that `web` and `mcp` enter a Host through the Rust `install` API and that one Plugin API is planned work. That session read the code and left the build and the tests unrun. The rest of the page still describes the commits above. -- **Update.** On 2026-11-19 the text on the file operations of tool calls was brought to `runvil-harness` at commit `ee199e3a` and `runvil-plugin-api` at `52a4905`, where the C contract is at version 0.5. At those commits a tool call holds no file access: its tool asks for each file operation, the Engine issues the operation as a `Vfs` effect, and the Harness performs it and records it. The update covers two sentences of the summary, the fourth paragraph of the walk-through, the entries on the three layers and on the one crate in section 1, the entry on the `RunSetup` fields in section 2, the entries on the one future and on the `Vfs` effect in section 3, the entry on loop order in section 5, the entries on a stop and on a cancel in section 6, the items on replay and on small records in section 7, questions 13 and 14 of section 9, and the third Update bullet at the top of the page. It states that the loop returns to its executor once in every 32 file requests of tool calls, that the record of a tool's file operation holds the operation and a receipt of its outcome, and that a replay has to repeat the file requests of tool calls beside the answers and the messages. The crate `runvil` has 124 re-exports where it had 121, and `ToolFiles`, `VfsOp`, and `VfsOutcome` are the difference. The count of 17 Engine names that `runvil` omits was taken again and is the same: `VfsOp` and `VfsOutcome` left that group, and `VfsAsker` and `VfsReceipt` joined it. That session read the code and left the build and the tests unrun. The update leaves the rest of the page as it was. -- **Update.** On 2026-11-24 the two entries of section 4 on the inference broker and on streaming were brought to `runvil-harness` at commit `5d9c7bf8`, the head of pull request 76, where Workshop's pull request 38 at `runvil-workshop` commit `1b33d9f8` sets the callback. The update covers those two entries and the fourth Update bullet at the top of the page. It states that `chat` takes an optional `on_piece` callback and that `supports_streaming` is a required method, that a Host sets `RunSetup::streaming` and the Harness hands it each piece of a section's own model round with its round, that the callback returns at once and never calls into the Harness, and that a callback that panics ends its round as `Dropped`. At those commits the whole verification list of each repository passes. The rest of the page still describes the commits above. *2026-11-10 16:41 - Claude Fable 5.2* diff --git a/decisions/models-and-conversations.md b/decisions/models-and-conversations.md index cda2d01..232d82f 100644 --- a/decisions/models-and-conversations.md +++ b/decisions/models-and-conversations.md @@ -1,19 +1,15 @@ # Model calls and conversations: design decisions and their reasons - Scope: how a prompt calls a model and what a conversation is: the `models` API, model roles, the model loop, replies, limits on a round, messages, compaction, and the client that sends a model request -- Code: `runvil` at commit `fa9936f64`, `runvil-docs` at `cfd69a4`, and `runvil-gateway` at `9369a7d` -- Update: the Paths bullet names the repositories as of `runvil` at commit `48a4dbc08` and `runvil-harness` at `5bca6f9`, after the Engine and the Harness moved (section 11) -- Update: the two entries on a chain's current model in section 2, the entry on a section entry's conversation in section 5, and gap 1 of section 9 state the rules of the second change that follows `8de43c2f` in `runvil-harness`: every heading starts a section, and the code before the first heading is the preamble (section 11) -- Update: the entry on the Gateway client's stream and on live text in section 7 describes `runvil-harness` at commit `5d9c7bf8` (section 11) -- Paths: code paths start at the `crates/` folder of `runvil-harness`, the repository of the Engine and the Harness, and a path that begins with `workshop/` starts at the `crates/` folder of `runvil` +- Paths: code paths start at the `crates/` folder of `runvil-harness`, the repository of the Engine and the Harness, and a path that begins with `workshop/` starts at the `crates/` folder of `runvil-workshop`, the repository of Workshop ## Summary -A prompt names one of five model roles, and the Host decides which model fills each role. Lua starts every model request: `models.infer` sends one prompt, and `models.loop` runs rounds of model replies and tool calls over `messages`, the one conversation of a section entry. A compactor, a Lua function, shortens the conversation when it exceeds the model's context window. The Engine asks for each round as an effect, and the Host's broker sends it. The standard broker uses the Gateway client. Sections 1 to 7 describe this design. +A prompt names one of the model roles, and the Host decides which model fills each role. Lua starts every model request: `models.infer` sends one prompt, and `models.loop` runs rounds of model replies and tool calls over `messages`, the one conversation of a section entry. A compactor, a Lua function, shortens the conversation when it exceeds the model's context window. The Engine asks for each round as an effect, and the Host's broker sends it. The standard broker uses the Gateway client. Sections 1 to 7 describe this design. -A check of this page against the code found five gaps and left ten questions about reasons for the owner. Section 9 lists the gaps, and section 10 lists the questions. The largest gap is in the built-in chat prompt: its text says that a model change in Workshop takes effect on the next run, and Workshop's broker sends the next round to the new model. +Section 9 lists the gaps between this page and the code, and section 10 lists the questions about reasons for the owner. The largest gap is in the built-in chat prompt: its text says that a model change in Workshop takes effect on the next run, and Workshop's broker sends the next round to the new model. -Section 8 lists the planned work. Its largest item is a model for each role: the Engine accepts a map with five models, and the Harness passes one. +Section 8 lists the planned work. Its largest item is a model for each role: the Engine accepts a map with a model for each role, and the Harness passes one. ## From a `models.loop` call to the reply in `messages` @@ -27,21 +23,21 @@ The Harness answers the effect with the completion, and `accept_chat` answers th ## 1. Model roles and the models that fill them -### Every prompt has five fixed model roles, and the Host maps each role to a model +### Every prompt has fixed model roles, and the Host maps each role to a model -The roles are `default`, `strong`, `small`, `fast`, and `creative`, the five variants of the enum `ModelRole`. A prompt names a role, and the Host decides which model fills it, so one prompt file runs on any Host's models. +The roles are `default`, `strong`, `small`, `fast`, and `creative`, the variants of the enum `ModelRole`. A prompt names a role, and the Host decides which model fills it, so one prompt file runs on any Host's models. The names are fixed because a label that a prompt declared for itself would be an empty formality: the Host would bind every such label to the same model. ### The `models:` key is optional and states requirements -Under `models:` in the front matter, a prompt maps a role name to two optional requirements: `min_context`, a token count, and `thinking`, true or false. A prompt that omits the key runs on the Host's `default` model. The parser refuses a role outside the five, a third field, a repeated role, and `min_context: 0`. +Under `models:` in the front matter, a prompt maps a role name to optional requirements: `min_context`, a token count, and `thinking`, true or false. A prompt that omits the key runs on the Host's `default` model. The parser refuses an unknown role, an unknown field, a repeated role, and `min_context: 0`. The key is optional so that a typical prompt leaves it out, and a prompt with a requirement can still state it. `thinking` is a requirement on a role's model. The owner's reason: thinking "is a property of a model not a model role". ### The Engine's caller passes one map from role to model, and `default` fills each role that the map omits -The caller passes a `BTreeMap` to `RunParams::with_models`. When `Run::new` builds the run, before any Lua runs, `fill_model_set` builds a `ModelBinding`, one model with its request settings, for each of the five roles and uses the `default` entry for a role that the map omits. An empty map tells the Engine that the Host lacks a model. Every role is then empty, and `models.infer` and `models.loop` raise an error of kind `model_required`. +The caller passes a `BTreeMap` to `RunParams::with_models`. When `Run::new` builds the run, before any Lua runs, `fill_model_set` builds a `ModelBinding`, one model with its request settings, for each role and uses the `default` entry for a role that the map omits. An empty map tells the Engine that the Host lacks a model. Every role is then empty, and `models.infer` and `models.loop` raise an error of kind `model_required`. ### The run's first step checks each declared requirement against the model that fills the role @@ -51,7 +47,7 @@ A `Switchable` model passes `thinking: false` because it can honor the requireme ### The Harness passes one model for a run, as the `default` entry -`current_model` asks the Host's broker for its model list ([The Harness and the Host API](harness-and-host.md)) and takes the model that `RunSetup.selected_model` names, or the first one listed. The Harness passes that model as the map's one entry, so one model fills all five roles. A model id has a namespace and a name, as in `gateway/fast`, and a request names the model by the name part. +`current_model` asks the Host's broker for its model list ([The Harness and the Host API](harness-and-host.md)) and takes the model that `RunSetup.selected_model` names, or the first one listed. The Harness passes that model as the map's one entry, so one model fills every role. A model id has a namespace and a name, as in `gateway/fast`, and a request names the model by the name part. The Harness passes only `default` because `RunSetup` has one `selected_model`. Section 8 lists a model for each role as planned work. @@ -69,13 +65,13 @@ A `call` child, a `tasks.spawn` task, and each fanout arm copy the parent chain' The Engine copies at dispatch because a spawned task can wait in a queue before it starts, and a copy taken at the task's start would include a later switch in the parent. [Tasks and fanout](tasks-and-fanout.md) describes the model-first form of `tasks.fanout`. -### `models.use` takes a role name or a handle, and two sampling options +### `models.use` takes a role name or a handle, and sampling options `models.use('strong', { temperature = 0, max_tokens = 4096 })` selects the role and sets both options on the selection. `temperature` is a number from 0.0 to 2.0, `max_tokens` is a positive integer, and any other key raises an error. A handle saved from `models.current()` restores an earlier selection with its options. The options are arguments of `models.use` because a prompt needs to set `max_tokens` section by section. The value is also arguably outside the prompt's contract, which the front matter states. A second call with a role name replaces the options, because a merge across calls would make a section's settings depend on its call history. The client sends a temperature as declared, and a provider's refusal of the value fails that round. -### A model handle is a value with nine fields, and a `models` function takes it as its first argument +### A model handle is a value with named fields, and a `models` function takes it as its first argument `models.use`, `models.get`, and `models.current` return a handle, a userdata over a frozen `ModelBinding`. Lua reads `name`, `label`, `model_id`, `description`, `context`, `provider`, `thinking`, `temperature`, and `max_tokens`. `provider` is the provider id that the Host's catalog names, or nil. A prompt writes a call on a handle as `models.infer(model, prompt)` or `models.loop(model, compactor?)`. @@ -83,7 +79,7 @@ A handle has only its fields, so the `models` functions are the one way to run a ### `models.get` returns a role's handle and leaves the current model as it is -`models.get('fast')` returns the handle of the `fast` role. A role name is a string that Lua passes as an argument. When the Engine's caller passes a state snapshot to `RunParams::with_ui`, as the Harness does for every run, `models.get` also takes a raw Gateway model id, and that handle has a fixed context window of 8192 tokens. +`models.get('fast')` returns the handle of the `fast` role. A role name is a string that Lua passes as an argument. A name that is not a role raises an error that lists the roles. A prompt names a model by its role, and the Host chooses the model that fills each role ([The Harness and the Host API](harness-and-host.md)). ## 3. `models.infer` and `models.loop` @@ -183,13 +179,13 @@ The owner's reason: "Because of prefix cache invalidation, changes to the prefix ### The list checks a record when Lua adds it, and the projection checks the whole list before each request -`parse_record` checks one record's role, content, and tool fields at the builder call, and drops any field outside the five that a record has. Before each request, `project_messages` checks the rules that span records: every tool call id is unique, and one result for each call follows an assistant record's tool calls directly. It then builds the wire messages and joins consecutive user records into one message. +`parse_record` checks one record's role, content, and tool fields at the builder call, and drops any field that a record does not define. Before each request, `project_messages` checks the rules that span records: every tool call id is unique, and one result for each call follows an assistant record's tool calls directly. It then builds the wire messages and joins consecutive user records into one message. The first check runs at the builder call so that a malformed record fails there, before `models.loop` runs. The projection enforces the pairing because OpenAI-shaped models reject unanswered tool calls. ### A record can have `meta`, which Lua reads and the projection omits -`meta` is any JSON value of at most 8192 bytes as compact JSON. Lua sets it as the last argument of a builder or as a field of an appended record, and reads it from a view. The projection sends four fields to the model: `role`, `content`, `tool_call_id`, and `tool_calls`. The records that the loop appends have plain text content and omit `meta`. +`meta` is any JSON value of at most 8192 bytes as compact JSON. Lua sets it as the last argument of a builder or as a field of an appended record, and reads it from a view. The projection sends `role`, `content`, `tool_call_id`, and `tool_calls` to the model. The records that the loop appends have plain text content and omit `meta`. The field exists because a compactor needs hints that survive in the list, and a view lacks a stable identity. @@ -267,7 +263,7 @@ The client is a crate of its own for two reasons. Inference is a Host service an ### One function normalizes every reply, and reasoning text is separate from the answer -`normalize` in the client's `wire/parse.rs` reads the assembled reply and returns three things: text or tool calls, the finish reason, and reasoning text. It reads reasoning from the first non-empty field among `reasoning_content`, `reasoning`, and `thinking`. +`normalize` in the client's `wire/parse.rs` reads the assembled reply and returns text or tool calls, the finish reason, and reasoning text. It reads reasoning from the first non-empty field among `reasoning_content`, `reasoning`, and `thinking`. The module concentrates the wire quirks so that the rest of Runvil works the same across models. A new special case belongs in this module. Its growth is acceptable, and scattered special cases are the risk. @@ -277,7 +273,7 @@ The module concentrates the wire quirks so that the rest of Runvil works the sam The checks that are independent of the wire format are in the Engine so that they run for every broker. The client fails a cut-off batch so that only calls with complete JSON arguments run. -### The receive timeout restarts with each chunk, and the client owns both request limits +### The receive timeout restarts with each chunk, and the client owns the request limits `GatewayChat` waits at most 120 seconds for the response headers and then for each next chunk, and it accepts at most 16 MiB for one reply. A stream that continues to send data completes, and a silent stream fails with the code `Timeout`. `GatewayChat::with_request_limits` sets both values, and `GatewayBroker::new` uses the defaults. @@ -287,7 +283,7 @@ The timeout restarts with each chunk because a cap of 120 seconds on the whole r A failed round is an `Error` with a model code such as `Overloaded`, `Timeout`, or `ContextOverflow` ([The Engine](engine.md)). Its `prose` field, the text that a model reads, is the code's fixed phrase, with ` (status N)` appended for an HTTP status. The client appends the provider's escaped text to the error's message, and Lua receives the prose. In Lua a caught failure has the kind `model_failure`, and a round on a chain that lacks a model has `model_required`. -Lua has these two kinds because a single kind, `internal`, would cover three unrelated conditions, and a model that reads a caught 503 would see `internal`. +Lua has these two kinds because a single kind, `internal`, would cover unrelated conditions, and a model that reads a caught 503 would see `internal`. ### The client redacts its key and builds a keyless client for a loopback Gateway @@ -299,10 +295,10 @@ The client has the Gateway's key, and the Gateway has the model provider's key. Each of these items is still to be built. -- **A model for each role.** A model that the Host selects for each of the five roles. `RunSetup` has one `selected_model`, and the Harness passes that model as `default`, so it fills all five roles. +- **A model for each role.** A model that the Host selects for each role. `RunSetup` has one `selected_model`, and the Harness passes that model as `default`, so it fills every role. - **A model swap that the Engine knows about.** A swap that also changes the Engine's binding for the role. After a swap by the broker, the Engine's precheck, `sys.model`, and the request's thinking switch and token cap describe the first model. - **A scoped model switch.** A Lua form that switches the model for one block of work and restores it afterward. `models.use` switches the model for the rest of the chain, and a prompt restores the earlier model with a handle saved from `models.current()`. -- **A role for compaction.** A role beside the five that names the model for compaction. A compactor calls `models.infer` on the chain's current model or on a handle, and the item waits for evidence of what compaction needs. +- **A role for compaction.** A role beside the others that names the model for compaction. A compactor calls `models.infer` on the chain's current model or on a handle, and the item waits for evidence of what compaction needs. - **The thinking switch for remote providers.** A per-model Gateway setting that translates the switch for a remote provider. The Gateway forwards `chat_template_kwargs.enable_thinking` to a remote provider as written, and a provider that ignores the field uses its own default ([The Gateway](gateway.md)). - **Tool schemas and images in the precheck.** A token count for tool schemas and image parts. The estimate omits both, and the item waits until retries overflow at the provider or image summaries fail the shrink rule. - **Tool ids in records.** A record whose tool call names the tool by its id, such as `web/fetch`, as Lua does. The record has the wire name, such as `web_fetch`. @@ -316,12 +312,12 @@ Each item names a text that differs from the code: the shipped chat prompt, a gu 1. Model changes in Workshop. The paragraph before the first heading of `workshop/agents/agents/chat.md` says of the model that "a selection change takes effect on the next run". `WorkshopBroker::routed` in `workshop/server/src/agents/broker.rs` sends each round to the dropdown's current pick, and the Workshop test `gate_a_model_picked_between_turns_serves_the_next_round` pins that. 2. The ceiling on rounds. Guide chapter 16 says "A prompt's own `max_tool_iterations` value replaces the run's round cap". `max_tool_iterations` in `runvil-internal/runtime/src/execute/context.rs` also applies `RunLimits::tool_iterations_ceiling`, which the guide omits. -3. Who sets the request limits. A table in chapter 16 names the Harness as the part that changes the response cap and the receive timeout. `GatewayChat::with_request_limits` is the one setter, `GatewayBroker::new` uses the defaults, and `RunSetup` lacks both values. +3. Who sets the request limits. A table in chapter 16 names the Harness as the part that changes the response cap and the receive timeout. `GatewayChat::with_request_limits` is the setter, `GatewayBroker::new` uses the defaults, and `RunSetup` lacks both values. **An error text and doc comments** 4. The text of the missing-model error. The prose of `ErrorCode::ModelRequired` in `runvil-internal/types/src/error.rs` tells the author to select a model or "bind a default model". The `models` API lacks a call that binds a default model: the `default` model is an entry of the map that the Engine's caller passes. Guide chapter 10 repeats the text. -5. Who owns the model selection. The module docs of `runvil-internal/model-client/src/model.rs` say "a section that never calls it runs on the `default` role", where "it" is `models.use`. The module docs of `runvil-internal/lua/src/models.rs` and a field doc in `runvil-internal/runtime/src/execute/section_vm.rs` also call the selection the section's, wording that at least twelve other comments in `runvil-lua` and `runvil-runtime` share. The chain owns the selection, and such a section runs on the chain's current model. +5. Who owns the model selection. The module docs of `runvil-internal/model-client/src/model.rs` say "a section that never calls it runs on the `default` role", where "it" is `models.use`. The module docs of `runvil-internal/lua/src/models.rs` and a field doc in `runvil-internal/runtime/src/execute/section_vm.rs` also call the selection the section's, wording that other comments in `runvil-lua` and `runvil-runtime` share. The chain owns the selection, and such a section runs on the chain's current model. ## 10. Questions for the owner @@ -329,30 +325,25 @@ Each question asks for the reason behind a part of the design. **Roles and models** -1. Why five roles, and why these names? +1. Why this set of roles, and why these names? 2. Why is a requirement on a role checked against the `default` model when the Host's map omits that role? The check can surprise a Host author. -3. Why does `models.get` take a raw Gateway model id when the Engine's caller passes a state snapshot, and refuse it otherwise? -4. Why does the client send the thinking switch as `chat_template_kwargs.enable_thinking`? +3. Why does the client send the thinking switch as `chat_template_kwargs.enable_thinking`? **The loop and the conversation** -5. Why does `models.infer` send an empty tool list? -6. Why is the default cap 24 rounds? The Tools and Packs page asks the same question. -7. Why does the count of answered tool calls, which permits an empty final reply, restart with each `models.loop` call? -8. Why may a list start with several system records? +4. Why does `models.infer` send an empty tool list? +5. Why is the default cap 24 rounds? The Tools and Packs page asks the same question. +6. Why does the count of answered tool calls, which permits an empty final reply, restart with each `models.loop` call? +7. Why may a list start with several system records? **The client** -9. Why does the client send tools in the OpenAI function-calling format? -10. Why does the client cut a backend's error body at 2000 characters, and why does `GatewayChat::keyless` accept an endpoint on any host? +8. Why does the client send tools in the OpenAI function-calling format? +9. Why does the client cut a backend's error body at 2000 characters, and why does `GatewayChat::keyless` accept an endpoint on any host? ## 11. Method and limits -- **Code.** The page describes `runvil` at commit `fa9936f64`, `runvil-docs` at `cfd69a4`, and `runvil-gateway` at `9369a7d`. -- **Checks.** The facts on this page were read in the code at those commits. A second session checked the gaps, the values, and the walk-through against the code. +- **Checks.** The facts on this page were read in the code. A second session checked the gaps, the values, and the walk-through against the code. - **Limits.** The sessions read the code and its tests, and left the build and the tests unrun. -- **Move.** On 2026-11-12 the Paths bullet was brought to `runvil` at commit `48a4dbc08` and `runvil-harness` at `5bca6f9`. Commit `adca9db10` of `runvil` removed the Engine, Harness, and Plugin crates, which are in `runvil-harness` with their history and at the same paths under `crates/`. The Workshop crates stay in `runvil`. The text of the page still describes the code at the commits above, when all of these crates were in `runvil`. -- **Every heading is a section.** On 2026-11-13 the two entries on a chain's current model in section 2 and the entry on a section entry's conversation in section 5 were brought to the second change that follows `8de43c2f` in `runvil-harness`, whose plan is `plan/2026-11-13-2-every-heading-is-a-section.plan.md` there. Before it, the Lua blocks under a prompt's one H1 ran once in a chain of their own, the H1 pass. The pass started on the `default` role, and the main walk started on the model that the pass ended on. Gap 1 of section 9 named the H1 prose of Workshop's `chat.md`. It names the paragraph before the file's first heading, because Workshop pins that change at `7147e709` and the file has no title line. That session ran the build and its tests. -- **Streaming.** On 2026-11-24 the entry of section 7 on the Gateway client's stream and on live text was brought to `runvil-harness` at commit `5d9c7bf8`, the head of pull request 76. The update covers that entry and the third Update bullet at the top of the page. It states that the standard broker hands each piece to the callback the Harness gives the round, and that a Host that sets `RunSetup::streaming` receives each piece of a section's own round. The Harness's whole verification list passes at that commit. The rest of the page still describes the commits above. *2026-11-10 16:39 - Claude Fable 5.2* diff --git a/decisions/prompt-language.md b/decisions/prompt-language.md index 0de4f66..a4f9aa7 100644 --- a/decisions/prompt-language.md +++ b/decisions/prompt-language.md @@ -1,23 +1,19 @@ # The prompt language: design decisions and their reasons - Scope: the prompt file as its author writes it: front matter, sections, Lua blocks and prose, the order sections run in, `jump`, `call`, `execute`, and `require`, arguments, substitution, the Lua globals, and the limits and errors an author meets -- Code: `runvil` at commit `fa9936f64`, and `runvil-docs` at commit `cfd69a4` -- Update: the Paths bullet names the repositories as of `runvil` at commit `48a4dbc08` and `runvil-harness` at `5bca6f9`, after the Engine and the Harness moved (section 11) -- Update: the entries on `return` in sections 3 and 4, and the entry on `call` in section 3, state the rules of the two changes that follow `5bca6f9` in `runvil-harness`: a `return` always ends its chain, and `call` returns nil for a chain that ends with no text (section 11) -- Update: the summary, the walk-through, and entries in sections 1, 2, 3, and 6, among them the entries on the prompt file, on headings, and on the preamble, state the rules of the two changes that follow `8de43c2f` in `runvil-harness`: every heading starts a section, and the code before the first heading is the preamble (section 11) -- Paths: code paths start at the `crates/` folder of `runvil-harness`, the repository of the Engine and the Harness, and a path that begins with `workshop/` starts at the `crates/` folder of `runvil` +- Paths: code paths start at the `crates/` folder of `runvil-harness`, the repository of the Engine and the Harness ## Summary A prompt is one Markdown file. Its front matter names the prompt and declares its arguments and requirements, and each heading in its body starts a section, which is a list of prose blocks and Lua blocks. Lua before the first heading is the preamble, which is the first section. The Engine runs the top-level sections in file order, each in a fresh Lua VM. A Lua block moves the run to another section with `jump` or `call`, runs another prompt file with `execute`, loads shared code with `require`, and sends prose to a model with a call such as `models.infer`. The Engine passes the table `var` from each section to the next. Sections 1 to 7 describe these parts. -A check of this page against the code found one gap and left nine questions about reasons for the owner. Section 9 describes the gap, and section 10 lists the questions. The gap is in the language guide: eight chapters name a failed parse by a parse error kind, and `Prompt::parse` returns one `Error` type whose `code` names the failure. +Section 9 lists the gaps between this page and the code, and section 10 lists the questions about reasons for the owner. A gap is in the language guide: its chapters name a failed parse by a parse error kind, and `Prompt::parse` returns one `Error` type whose `code` names the failure. Section 8 lists the planned work. Its largest item is Lua module files and Markdown includes: `require` loads only sections of the running prompt. ## From a prompt file to its final text -The shipped prompt `greet.md`, in the repository's `prompts/` folder, has four front matter keys, a paragraph that describes the prompt, and one section named `Main`. Its `args:` key declares one required string named `name`. `Main` has a Lua block, one line of prose with the placeholder `{{ var.greeting }}`, and a second Lua block. `Prompt::parse` checks the keys, builds the section tree, and compiles both Lua blocks. +The shipped prompt `greet.md`, in the repository's `prompts/` folder, has front matter, a paragraph that describes the prompt, and a section named `Main`. Its `args:` key declares a required string named `name`. `Main` has a Lua block, a line of prose with the placeholder `{{ var.greeting }}`, and a second Lua block. `Prompt::parse` checks the keys, builds the section tree, and compiles each Lua block. A caller starts a run with one JSON object as its arguments, for example `{"name":"Ada"}`. The run's first step reads `runvil: 0` and accepts the prompt, and then it checks the arguments against the declaration. The paragraph above the `Main` heading has no Lua block, so it is commentary, and the first code that runs is in `Main`. The Engine's scheduler enters `Main` and builds a fresh Lua VM, where `args.name` is `Ada` and `var` is an empty table. @@ -37,11 +33,11 @@ The owner's rule: "we don't require any headings at all". An author who wants a Every prompt is a Markdown file, and the same Engine code runs a fixed pipeline, a model that calls tools in a loop, and a chat with a user. The Lua in each section decides which of these the section does. The choice belongs to the section because one prompt can combine all three. -### Front matter accepts eight keys and refuses any other +### Front matter accepts a fixed set of keys and refuses any other -The keys are `name`, `description`, `runvil`, `max_tool_iterations`, `uses`, `args`, `models`, and `prompts`. The parser requires the first two. The struct `Frontmatter` has the serde attribute `deny_unknown_fields`, so a misspelled key fails the parse with the code `frontmatter_invalid`. +The keys are `name`, `description`, `runvil`, `max_tool_iterations`, `uses`, `args`, `models`, and `prompts`. The parser requires `name` and `description`. The struct `Frontmatter` has the serde attribute `deny_unknown_fields`, so a misspelled key fails the parse with the code `frontmatter_invalid`. -Section 5 covers `args:`, and the next entry covers `prompts:`. Other pages cover three keys: `uses:` ([Tools and Packs](tools-and-packs.md)), and `models:` and `max_tool_iterations` ([Model calls and conversations](models-and-conversations.md)). +Section 5 covers `args:`, and the next entry covers `prompts:`. Other pages cover `uses:` ([Tools and Packs](tools-and-packs.md)), and `models:` and `max_tool_iterations` ([Model calls and conversations](models-and-conversations.md)). ### `prompts:` lists the prompts that a prompt may run with `execute` @@ -67,11 +63,13 @@ Only headings mark sections, so XML tags remain free for the author and the mode The top level follows the file so that a plain series of H2 sections runs in file order by fall-through (section 3). The owner's reason: "Wouldn't it be better to just let the author start with the H2? And now it's implicit, it's just a series of H2." If every prompt had an H1 as its root section, the H2 sections would be its children, and each would run only when the H1's Lua named it. The owner's reason: "every H1 that wants to chain has to have a jump, and that looks ugly". -### Lua names a section by its heading, with the `#` markers +### Lua names a section by a path, and a path says where the section sits -A heading reference is the markers, a space, and the name, as in `'## Research'`. The Engine matches the exact level and the exact name. A bare name raises an error that begins `section heading must include ### markers`. Sibling sections have distinct names, and the parser refuses a duplicate. +A section path is a Lua string of section names, and it takes these forms. `name` names a direct child of the section the code is written in. `../name` names a sibling, another section under the same parent, and from the preamble the top-level sections are siblings. `/a/b` starts at the top-level sections and names one section for each level, so it names the same section wherever it is written. Each name matches a section's name exactly and case-sensitively, whatever its heading level. `call`, `jump`, `tasks.spawn`, and `tasks.fanout` take the relative forms, the `prompt` reads take every form, and `require` takes only a path from the top, as in `require '/helpers'`. A malformed path fails with a Lua error that quotes the path. Sibling sections have distinct names, and the parser refuses a duplicate. -The name is the heading's text as the Markdown parser decodes it, so Lua addresses a heading written `## Q&A` as `'## Q&A'`. `collect_headings` in `runvil-internal/prompt/src/sections.rs` builds a section's name from the Markdown parser's text events, and the parser emits a decoded entity as text. With names in raw source form, an author would have to write `jump('## Q&A')`. +The name is the heading's text as the Markdown parser decodes it, so Lua addresses a heading written `## Q&A` as `Q&A`. `collect_headings` in `runvil-internal/prompt/src/sections.rs` builds a section's name from the Markdown parser's text events, and the parser emits a decoded entity as text. With names in raw source form, an author would have to write `jump('Q&A')`. + +A path says where a section sits, so the relative paths between a section and its neighbors stay the same when they all move to another depth. A path from the top gives a shared section one address at every depth. ### A section is an ordered list of Lua blocks and prose blocks @@ -95,17 +93,17 @@ Each Lua block has its own `prose`. The Engine substitutes the `{{ }}` placehold The Engine sends prose to a model when a Lua block passes it to a call such as `models.infer(prose)` ([Model calls and conversations](models-and-conversations.md)). -### A section whose lines are all list markers is a list section +### A list in a section is one block, and `prompt.section(path, 'list')` reads it -When a section has only prose and every nonblank line starts with a marker (`-`, `*`, `1.`, or `1)`), the parser stores each line's text as an item of the section. A marker with an empty text fails the parse with the code `list_empty_item`. Lua reads the items with `prompt.list`. `tasks.fanout` can run a worker section once for each item, and each such run is a fanout arm ([Tasks and fanout](tasks-and-fanout.md)). +A list is one block of its section. `prompt.section(path, 'list')` parses the section's own Markdown by the rules of `markdown.parse` and returns the section's one list as a table whose `items` field is an array of strings, each an item's text with its marker removed. A section with two lists needs an index, as in `prompt.section(path, 'list', 2)`. `tasks.fanout` can run a worker section once for each item, and each such run is a fanout arm ([Tasks and fanout](tasks-and-fanout.md)). -The parser builds the items when it loads the prompt, so an empty item fails the parse, where it would otherwise fail a run. A plain line among the markers is different: `bullet_items` in `runvil-internal/prompt/src/list.rs` treats the whole section as prose, so that ordinary prose with one incidental bullet in it remains prose. When the prompt runs, `prompt.list` raises for such a section with an error that ends `has no pre-parsed items`. +The parser keeps no items and refuses no list: a section made only of a list is an ordinary section. A list is read with the selector form of `prompt.section` because a list, a fence, and every other block are read with one syntax, the one that `markdown.section` takes. -### `prompt.section` and `prompt.list` read another section, and a miss returns nil +### `prompt.section` and `prompt.section_or` read another section, and `prompt.section` raises for a miss -`prompt.section(heading)` returns a section's own raw Markdown, from the line after its heading to the next heading of any level. `prompt.list(heading)` returns the items of a list section as an array of strings. Both return nil for a heading outside the caller's visible set (section 3), and both raise for a malformed heading. +`prompt.section(path)` returns a section's own raw Markdown, from the line after its heading to the next heading of any level. With a second argument, a selector, the read returns one block of that Markdown as a table: the only block that the selector matches, or the match that a number in a third argument picks. `prompt.section_or` takes the same arguments and returns nil where `prompt.section` raises for a section or a block that is not there. Both raise for a malformed path, selector, or index. The reads take a path from the top beside the relative forms, so they may name any section (section 3). -A miss returns nil because a read is optional by nature: a prompt can use headings as an index and test each lookup for nil. +`prompt.section` raises for a miss so that a read that names nothing fails at its own line, with an error that says what is missing, and not later as an index of nil. `prompt.section_or` is the other form for a prompt that treats a read as optional by nature: a prompt can use section names as an index and test each lookup for nil. ## 3. The order sections run in @@ -153,7 +151,7 @@ The output of a prompt is its return value: a prompt that built a file returns t ### `jump` ends the block and continues the walk at another section -`jump(heading)` records its target and ends the current block. The Engine then closes the section, looks the heading up, and enters the target in a fresh VM that starts with the jumper's `var`. A section may jump to an earlier sibling, so two sections can form a loop. +`jump(path)` records its target and ends the current block. The Engine then closes the section, looks the target up, and enters it in a fresh VM that starts with the jumper's `var`. A section may jump to an earlier sibling, so two sections can form a loop. A section of a called chain may jump as well, so what a section can do is independent of how the run entered it. The prompt's author is responsible for coherent control flow, as in any programming language, and that includes infinite loops and wrong targets. @@ -165,7 +163,7 @@ The rules are identical at every level: the Engine's section semantics are indep ### `call` runs a contained chain and returns its final text, or nil for a chain with none -`call(heading, args)` starts a new chain at the target and suspends the calling block. The chain follows the rules of the walk: it falls through the target's following siblings, and its sections may jump. It ends when a block executes a `return` or the last section at its level ends. `call` returns the chain's final text as a string, and it returns nil for a chain that ends with no text. +`call(path, args)` starts a new chain at the target and suspends the calling block. The chain follows the rules of the walk: it falls through the target's following siblings, and its sections may jump. It ends when a block executes a `return` or the last section at its level ends. `call` returns the chain's final text as a string, and it returns nil for a chain that ends with no text. A `call` works like a call of a different prompt whose sections happen to be in the same file. The caller inherits only the chain's answer, because the tokens that the chain spent would otherwise bloat the caller. @@ -187,7 +185,7 @@ The executed prompt is a part of the caller's run and not a run of its own. It h ### Only the arguments go into an executed prompt, and only its text comes back -`call`, `jump`, `require`, the `prompt` reads, and the task calls look a heading up in the prompt that they are written in. One section name in two prompts therefore names two sections, and a prompt has no way to name a section of another prompt. The owner's goal: "I just want it to be as if the other prompt sections were in the main document, but without having their section names conflict". The owner's rule: "prompts can't name sections from other prompts. You can just only execute." +`call`, `jump`, `require`, the `prompt` reads, and the task calls look a section up in the prompt that they are written in. One section name in two prompts therefore names two sections, and a prompt has no way to name a section of another prompt. The owner's goal: "I just want it to be as if the other prompt sections were in the main document, but without having their section names conflict". The owner's rule: "prompts can't name sections from other prompts. You can just only execute." The child starts with an empty `var`, on the `default` model of its own model set, and with a new, empty store ([Files and the VFS](files-and-the-vfs.md)). A `call` differs on the first two: its chain starts with a copy of the caller's `var` and on the caller's current model. The child's `args` are the arguments of the `execute`. After the `execute` returns, the caller's `var`, `args`, and current model are the same as before it. The owner's rule: "The executed prompt gets a new var, nothing comes across except args/argv". @@ -201,15 +199,15 @@ The second argument of `execute` is optional: a table of named fields or a strin ### A section names its siblings and its direct children -Every function that takes a heading, except `require`, looks it up in the calling section's visible set: the other sections with the same parent, plus the section's direct children. The parent, a sibling's child, and the section itself are outside the set. A `jump` or a `call` to a heading outside the set fails with an error that lists the set ([The Engine](engine.md)). +`jump`, `call`, `tasks.spawn`, and `tasks.fanout` look a section up in the visible set of the section that their path starts at: the other sections with the same parent, which `../name` names, plus that section's direct children, which `name` names. The parent, a sibling's child, and the section itself are outside the set, and no relative form reaches them. A `jump` or a `call` to a section outside the set fails with the not-found error ([The Engine](engine.md)). The `prompt` reads and `require` are not held to the set, because they leave the walk where it is, so a path from the top lets them name any section. -With only the children in the set, two sibling sections would be unable to share one worker, and with only the top-level sections in it, a child section would be unaddressable. The error lists only the visible set, so the error text hides the rest of the document's structure. +With only the children in the set, two sibling sections would be unable to share one worker, and with only the top-level sections in it, a child section would be unaddressable. The error names the path and the section where the lookup looked and lists no other section, so the error text hides the rest of the document's structure. ## 4. Sharing code with `require` ### `require` loads a section as a library into the calling section's VM -`require '## helpers'` runs the Lua blocks of the named section inside the caller's VM. The library reads the caller's globals, `var`, and `args`, and the globals it defines remain for the caller. Runvil's `require` loads only sections of the running prompt, and the Engine leaves Lua's `package` library unloaded. +`require '/helpers'` runs the Lua blocks of the named section inside the caller's VM. The library reads the caller's globals, `var`, and `args`, and the globals it defines remain for the caller. Runvil's `require` loads only sections of the running prompt, and the Engine leaves Lua's `package` library unloaded. Shared code exists for reuse, so a library runs only where a section asks for it. With Lua's own `require`, a prompt could load Lua files from disk, and library code would be unable to make a call that waits. @@ -219,11 +217,11 @@ A library's blocks run in order. After a block that ends with no `return`, the n `require` returns a value of any type because a library returns its module as a table. A `return` ends the load the way a block's `return` ends a chain, and the result `true` for a library with no value matches standard Lua. The cycle error exists because standard Lua 5.5 lacks cycle detection and recurses until the stack overflows. -### `require` can also name the siblings of each ancestor section +### `require` takes only a path from the top, so it names any section -From a section, `require` finds the section's direct children, its siblings, and the siblings of each of its ancestors up to the top level. `call`, `jump`, the prompt reads, and the task calls use the smaller visible set. A `require` that runs while a library loads resolves from the library's own position, so a library can load helper sections nested under it. +`require` takes a path from the top of the prompt, such as `/helpers`, and nothing else: a relative path given to `require` fails with an error that says `require` takes a path from the top. The path names any section, and it names the same section wherever the `require` is written. `call`, `jump`, and the task calls take only the relative forms, which reach a neighbor of the section they start from, and the `prompt` reads take both kinds. A relative path in a library's own code starts at the library, whichever section requires it, so a library can keep its own templates and workers. -The wider set exists for worker sections, which are often nested. With the smaller set, an author would have to copy each library under every parent section. Control flow needs a smaller set than reuse does. +Loading a library leaves the walk where it is, so it needs no visible set, while control flow needs a small one. A path from the top gives a library one spelling on every line of the prompt: with relative forms, the same top-level library would need a different spelling at each depth, and a `require` that moves to another section would break. ### A library is an ordinary section, and each section requires the libraries it uses @@ -235,7 +233,7 @@ A library that a parent section loaded exists only in the parent's VM, so a call `require` is a Lua function, so a library's blocks run inside the calling block's coroutine ([The Engine](engine.md)) and may call a model, the store, and tools while they load. Library code is ordinary section code that runs in another place. A `jump` during a load raises an error that begins `jump is unavailable while a library loads`, because a transfer of control in the middle of a load lacks a coherent meaning. -The parser leaves `require` calls unchecked, so a bad heading raises an error when the call runs. A check at parse time would need each block's syntax tree, which the Lua compiler leaves unexposed, and a search of the text would misfire on strings and comments. +The parser leaves `require` calls unchecked, so a `require` of a missing section raises an error when the call runs. A check at parse time would need each block's syntax tree, which the Lua compiler leaves unexposed, and a search of the text would misfire on strings and comments. ## 5. Arguments and substitution @@ -247,7 +245,7 @@ The arguments are an object so that a Host can publish any prompt as a tool: the ### `args:` declares the object in a subset of JSON Schema, and the default is one optional string named `text` -The value of `args:` is a schema with eight keywords: `type`, `properties`, `required`, `additionalProperties`, `items`, `enum`, `description`, and `default`. A `type` is `string`, `boolean`, `integer`, `number`, `array`, or `object`, and the root is an object whose `properties` name the arguments. The parser refuses any other keyword, a node that lacks a `type`, an array that lacks `items`, and a default that differs from its own node. Each refusal has the code `frontmatter_invalid` and names the YAML path of the node, such as `args.properties.query`. An object is closed: a field outside its `properties` ends the run, unless the object says `additionalProperties: true`. Before the check, the Engine gives each missing field its `default`, at every depth. A `null` for a field outside the `required` list counts as the field left out. A prompt that omits the key takes one optional string named `text`, so a Host with plain text sends `{"text":"hello"}`. +The value of `args:` is a schema with these keywords: `type`, `properties`, `required`, `additionalProperties`, `items`, `enum`, `description`, and `default`. A `type` is `string`, `boolean`, `integer`, `number`, `array`, or `object`, and the root is an object whose `properties` name the arguments. The parser refuses any other keyword, a node that lacks a `type`, an array that lacks `items`, and a default that differs from its own node. Each refusal has the code `frontmatter_invalid` and names the YAML path of the node, such as `args.properties.query`. An object is closed: a field outside its `properties` ends the run, unless the object says `additionalProperties: true`. Before the check, the Engine gives each missing field its `default`, at every depth. A `null` for a field outside the `required` list counts as the field left out. A prompt that omits the key takes one optional string named `text`, so a Host with plain text sends `{"text":"hello"}`. The declaration is JSON Schema because that is the form in which a tool publishes its arguments, and `ArgsSchema::as_json` returns the declaration in that form. It is a subset so that an unknown keyword fails the parse: a misspelled keyword is an error when the prompt loads, where a reader of full JSON Schema would ignore it. An object is closed so that the Engine refuses a misspelled optional field, which an open object would accept and the prompt would never read. The Engine fills a default because a caller that reads the schema expects the prompt to use it. A `null` counts as a field left out because models send `null` for a field they omit, and the checker of the `std` Pack reads a `null` the same way ([Tools and Packs](tools-and-packs.md)). @@ -271,21 +269,21 @@ A missing key, a null value, or a path that ends at a function raises an error a ### A section VM runs Lua 5.5 with the `string`, `table`, `math`, and `utf8` libraries -The Engine removes fourteen base globals, among them `load`, `dofile`, `rawget`, `rawset`, `collectgarbage`, and `print`. The names `io`, `os`, `package`, `debug`, and `coroutine` read nil. +The Engine removes base globals, among them `load`, `dofile`, `rawget`, `rawset`, `collectgarbage`, and `print`. The names `io`, `os`, `package`, `debug`, and `coroutine` read nil. The libraries include `utf8` because it is pure, and an author needs it to cut a string at a character boundary. -### The Engine installs 21 globals and reserves 63 names +### The Engine installs its globals and reserves names -Six Engine globals are the data of the run: `args`, `item`, `messages`, `prose`, `sys`, and `var`. Eight are tables of operations: `compactors`, `json`, `markdown`, `models`, `prompt`, `store`, `tasks`, and `tools`. Seven are functions: `call`, `execute`, `jump`, `log`, `require`, `ui`, and `untrusted`. Two exist only in some VMs: `ui` when the caller supplied a snapshot, and `item` in the first section of a task whose spawn supplied one. The list `RESERVED_NAMES` adds the 19 Lua globals that the sandbox leaves in place and the 23 keywords of Lua 5.5. A Pack prelude, the Lua that the Engine runs for a Pack in each section VM, fails to install when it defines a reserved name. +Some Engine globals are the data of the run: `args`, `item`, `messages`, `prose`, `sys`, and `var`. Some are tables of operations: `compactors`, `json`, `markdown`, `models`, `prompt`, `store`, `tasks`, and `tools`. Some are functions: `call`, `execute`, `jump`, `log`, `require`, and `untrusted`. Of these, `item` exists only in some VMs: in the first section of a task whose spawn supplied one. The list `RESERVED_NAMES` adds the Lua globals that the sandbox leaves in place and the keywords of Lua 5.5. A Pack prelude, the Lua that the Engine runs for a Pack in each section VM, fails to install when it defines a reserved name. Other pages cover `models`, `messages`, and `compactors` ([Model calls and conversations](models-and-conversations.md)), `tools` and `untrusted` ([Tools and Packs](tools-and-packs.md)), `tasks` and `item` ([Tasks and fanout](tasks-and-fanout.md)), and `store` ([Files and the VFS](files-and-the-vfs.md)). -`markdown` has five functions over Markdown text from outside the prompt's own sections. `markdown.parse` reads text into a list of blocks, which are plain tables. `markdown.section` returns the one section that a path names, or one block of it, and raises when it is absent, and `markdown.section_or` returns nil for that miss. `markdown.select` collects every block that a selector matches, and `markdown.render` writes the blocks back as one text. +`markdown` has functions over Markdown text from outside the prompt's own sections. `markdown.parse` reads text into a list of blocks, which are plain tables. `markdown.section` returns the one section that a path names, or one block of it, and raises when it is absent, and `markdown.section_or` returns nil for that miss. `markdown.select` collects every block that a selector matches, and `markdown.render` writes the blocks back as one text. ### A handle is a plain value, and its operations are functions of a namespace table -A model handle, a tool object, and a task handle are values with fields. Each operation on one is a function of a namespace table that takes the handle as an argument, as in `models.infer(handle, text)` and `tools.call(tool, arguments)`. The message list is the one exception: its builders are colon methods, as in `messages:user(text)`. +A model handle, a tool object, and a task handle are values with fields. Each operation on one is a function of a namespace table that takes the handle as an argument, as in `models.infer(handle, text)` and `tools.call(tool, arguments)`. The message list is an exception: its builders are colon methods, as in `messages:user(text)`. The owner's reason: "Simpler implementation. Simpler mental model for authors. This is best for AI because only one way to do things." [Model calls and conversations](models-and-conversations.md) covers model handles. @@ -307,10 +305,6 @@ The table refuses writes because `sys` is runtime metadata: the Engine writes it The limits loosen only after examples from real prompt debugging establish a need for multiline or structured values. -### `ui()` returns the Host's snapshot from the start of the run - -`ui()` returns a new table on each call with the data the caller supplied when the run started. The Harness fills two fields, `selected_model` and `workspace_root`. - ### `pairs` and `next` visit keys in a fixed order The Engine replaces both functions. Each visits the array part of a table in index order, then the other keys sorted: booleans, then numbers, then strings. Two runs therefore walk a table the same way. Both read through a view, so a walk of a `var` table or of a table inside `args` visits the entries of the data in that order, and the value it yields for a nested table is a view too. A `__pairs` metamethod still applies, on a table and on a userdata. @@ -325,7 +319,7 @@ The Engine puts one metatable on the globals table. It answers reads of `args`, ### `json` is a global table with `json.null` for null and `json.array` for lists -`json` has six members: `encode`, `encode_lines`, `decode`, `decode_lines`, `null`, and `array`. `json.decode` returns fresh writable tables and returns `json.null` for each JSON null. `json.null` is truthy, and code tests for it with `v == json.null`. An unmarked empty table encodes as `{}`, and `json.array()` returns an empty table that encodes as `[]`. The two `_lines` functions read and write JSON Lines. +`json` has the members `encode`, `encode_lines`, `decode`, `decode_lines`, `null`, and `array`. `json.decode` returns fresh writable tables and returns `json.null` for each JSON null. `json.null` is truthy, and code tests for it with `v == json.null`. An unmarked empty table encodes as `{}`, and `json.array()` returns an empty table that encodes as `[]`. The two `_lines` functions read and write JSON Lines. The table is always present because `require` loads only sections of the running prompt. Null is a sentinel value so that a key whose value is null remains in its table. A sequence encodes as an array, so only the empty array needs the `json.array()` marker. @@ -339,7 +333,7 @@ The Engine walks the value itself, because the conversion of mlua, the Lua bindi ### Lua catches every Engine failure as a table with `kind`, `code`, and `message` -`pcall` returns a failure as a table whose `tostring` is its message. `kind` is one of sixteen strings that an author branches on, such as `lua`, `store`, `tool`, `model_failure`, and `canceled`. `code` is the tag of the exact failure, such as `lua_quota`, and an uncaught error ends the run with it ([The Engine](engine.md)). `message` starts with the prompt's file and line when the failure has a location. +`pcall` returns a failure as a table whose `tostring` is its message. `kind` is one of the strings that an author branches on, such as `lua`, `store`, `tool`, `model_failure`, and `canceled`. `code` is the tag of the exact failure, such as `lua_quota`, and an uncaught error ends the run with it ([The Engine](engine.md)). `message` starts with the prompt's file and line when the failure has a location. The table prints as its message, so code that prints a caught failure shows the text, and code that branches reads `kind`. @@ -349,9 +343,9 @@ When the Host cancels a run, the Engine's `pcall` and `xpcall` raise a caught fa A stop drops the model round or the tool call in flight and leaves the cancel flag clear. The waiting Lua call raises an error of kind `canceled`, and a `pcall` around it catches the error. The built-in chat prompt wraps `models.loop` in `pcall`, so a stop ends one reply and the chat continues ([The Harness and the Host API](harness-and-host.md)). -### A call that waits raises an error inside a comparator of `table.sort` +### A call that waits raises an error inside a callback of a C function -A call that waits, such as `tools.call`, yields the block's coroutine, and the module comment of `runvil-internal/lua/src/coro.rs` says "Yield cannot cross the C boundary". Lua's `table.sort` is a C function, so a waiting call inside its comparator raises Lua's own error, `attempt to yield across a C-call boundary`. +A call that waits, such as `tools.call`, yields the block's coroutine, and the module comment of `runvil-internal/lua/src/coro.rs` says "Yield cannot cross the C boundary". Lua's `string.gsub` is a C function, so a waiting call inside its replacement function raises Lua's own error, `attempt to yield across a C-call boundary`. `table.sort` is the Engine's own Lua function in `runvil-internal/lua/src/__impl_stdlib.lua`, so a waiting call inside its comparison function works. ### `call`, `execute`, tasks, and fanout arms nest at most 8 levels @@ -376,7 +370,7 @@ Each of these items is still to be built. - **An `execute` that returns at once.** A Lua function, planned as `execute_async`, that starts a listed prompt as a task and returns the task's handle. `execute` suspends its caller until the executed prompt ends. - **Lua module files and Markdown includes.** A `require` of a Lua file by its path, as in `require("./path.lua")`, and an `include` for partial Markdown. `require` loads only sections of the running prompt. -- **Front matter in Lua.** A sealed table with the prompt's own `name`, `args`, and `models` declarations. The `prompt` table has two functions, `section` and `list`, and both read sections. +- **Front matter in Lua.** A sealed table with the prompt's own `name`, `args`, and `models` declarations. The `prompt` table has the functions `section` and `section_or`, and both read sections. - **A live clock.** A way for Lua to read the current time during a run. `sys.when` is the run's start time. - **More of `json`.** Encoding of message records, pretty printing, and a decode that builds its values inside the VM's memory limit. `json.encode` raises for a message record, as for every userdata other than `json.null`, and `json.decode` accepts 8,388,608 bytes of input. - **An acyclic section order.** A rule that `jump` names only a child or a later sibling. Whether the rule is possible, and whether it would limit authors too much, are open questions. A section may jump to an earlier sibling, so two sections can form a loop. @@ -385,7 +379,7 @@ Each of these items is still to be built. The item names a place where the language guide differs from the code. -1. Parse error kinds. Eight chapters of the guide name a failed parse by a parse error kind, such as `Fence` or `Structure`, and chapter 16 also lists the code for each kind. `Prompt::parse` returns the one `Error` type ([The Engine](engine.md)), whose `code` is `frontmatter_invalid`, `structure_invalid`, `fence_invalid`, `list_empty_item`, `lua_compile`, or `internal`. +1. Parse error kinds. Eight chapters of the guide name a failed parse by a parse error kind, such as `Fence` or `Structure`, and chapter 16 also lists the code for each kind. `Prompt::parse` returns the one `Error` type ([The Engine](engine.md)), whose `code` is `frontmatter_invalid`, `structure_invalid`, `fence_invalid`, `lua_compile`, or `internal`. ## 10. Questions for the owner @@ -393,30 +387,24 @@ Each question asks for the reason behind a part of the design. **Sections and the walk** -1. Why does Lua name a section with its `#` markers? -2. Why does the walk skip child sections? -3. Why does a called chain, a task, or a fanout arm work on a copy of `var`, and why does the Engine discard its writes? -4. Why does a main walk that ends with no text return the text `done`, while a called chain returns nil and a task returns the empty string? -5. Why may a section alternate any number of Lua blocks and prose blocks? -6. Why is the number of `jump` calls unlimited, while nesting and the rounds of `models.loop` each have a cap? +1. Why does the walk skip child sections? +2. Why does a called chain, a task, or a fanout arm work on a copy of `var`, and why does the Engine discard its writes? +3. Why does a main walk that ends with no text return the text `done`, while a called chain returns nil and a task returns the empty string? +4. Why may a section alternate any number of Lua blocks and prose blocks? +5. Why is the number of `jump` calls unlimited, while nesting and the rounds of `models.loop` each have a cap? **Parsing** -7. Why is a heading inside a block quote or a list item prose? -8. Why is the `runvil:` key optional to the parser and required by the run's first step? +6. Why is a heading inside a block quote or a list item prose? +7. Why is the `runvil:` key optional to the parser and required by the run's first step? **The Lua environment** -9. Why does a read of an unknown `sys` field raise, while a missing key of `var` or of `args` reads nil? +8. Why does a read of an unknown `sys` field raise, while a missing key of `var` or of `args` reads nil? ## 11. Method and limits -- **Code.** The page describes `runvil` at commit `fa9936f64` and `runvil-docs` at commit `cfd69a4`. -- **Checks.** The facts on this page were read in the code at those commits. A second session checked the gaps, the values, and the walk-through against the code. +- **Checks.** The facts on this page were read in the code. A second session checked the gaps, the values, and the walk-through against the code. - **Limits.** The sessions read the code and its tests, and left the build and the tests unrun. -- **Move.** On 2026-11-12 the Paths bullet was brought to `runvil` at commit `48a4dbc08` and `runvil-harness` at `5bca6f9`. Commit `adca9db10` of `runvil` removed the Engine, Harness, and Plugin crates, which are in `runvil-harness` with their history and at the same paths under `crates/`. The `prompts/` folder of the walk-through moved with them. The text of the page still describes the code at the commits above, when those crates were in `runvil`. -- **Return rule.** On 2026-11-13 the entries on `return` in sections 3 and 4 were brought to the change that follows `5bca6f9` in `runvil-harness`, whose plan is `plan/2026-11-13-1-return-ends-the-chain.plan.md` there. Before it, a block that returned nil or no value let the next block run, and `require` took the first block value other than nil. That session ran the build and its tests. The rest of the page still describes the code at the commits above. -- **`call` with no text.** On 2026-11-13 the entry on `call` in section 3 and question 4 of section 10 were brought to the second change that follows `5bca6f9` in `runvil-harness`: `call` returns nil for a chain that ends with no text, where it returned the empty string. That session ran the build and its tests too. -- **Every heading is a section.** On 2026-11-13 the text on headings, the preamble, and `argv` was brought to the two changes that follow `8de43c2f` in `runvil-harness`, whose plan is `plan/2026-11-13-2-every-heading-is-a-section.plan.md` there. The update covers the summary, the walk-through, the entry on the prompt file in section 1, the entry on headings in section 2, the entries on the preamble, the walk, chains, `return`, and a jump to a child in section 3, the entries on `args` and `argv` in section 5, the entries on `sys` and the `_G` guard in section 6, and the questions of section 10. Before them, a prompt had exactly one H1, whose text was its title, and the Lua blocks under it ran once as the H1 pass, which handed its `var`, its `argv`, its model, its concurrency limit, and its tasks to the walk over the H2 sections. A Lua error in the pass ended the run with the code `requirements_unmet`, and the pass could assign `argv`, which every later section read frozen. Section 10 had a question on a prompt with an H1 and no sections, and the questions after it each moved up one number. That session ran the build and its tests. *2026-11-10 16:47 - Claude Fable 5.2* diff --git a/decisions/shipped-prompts.md b/decisions/shipped-prompts.md index e323aa9..a018476 100644 --- a/decisions/shipped-prompts.md +++ b/decisions/shipped-prompts.md @@ -1,17 +1,13 @@ # Prompts that ship: design decisions and their reasons - Scope: the sample prompts in `prompts` and Workshop's built-in chat prompt -- Code: `runvil` at commit `fa9936f64`, and `runvil-docs` at commit `cfd69a4` -- Update: the place of the sample prompts and the Paths bullet describe `runvil` at commit `48a4dbc08` and `runvil-harness` at `5bca6f9`, after the Engine and the Harness moved (section 7) -- Update: the sentence on where the chat prompt makes its offers, in section 2, names the preamble, and gap 1 of section 5 names the paragraph before the chat prompt's first heading, as of the second change that follows `8de43c2f` in `runvil-harness`: every heading starts a section, and the code before the first heading is the preamble (section 7) -- Update: the text on the Packs of the chat prompt, in the walk-through and in section 2, and the Paths bullet describe `runvil-workshop` at commit `956e7800`, which pins `runvil-harness` at `4afed45f` (section 7) - Paths: code paths start at the root of the `runvil-workshop` repository, except the `prompts` folder and the Engine and Harness crates, which are in the `runvil-harness` repository at the same paths ## Summary -Runvil ships six prompts. Five are sample files in the `prompts` folder of `runvil-harness`, the repository of the Engine and the Harness: four small examples and `research-person.md`, which researches a person on the web. The sixth is `chat.md`, the built-in chat agent, which Workshop compiles into its binary and launches when an agent panel opens. Its one section is a loop: it reads the operator's next message, runs model rounds and tool calls until the model answers, and summarizes older turns when a turn overflows the model's context window. Section 1 describes the samples, and sections 2 and 3 describe the chat prompt. +Runvil ships sample prompts and a built-in chat prompt. The samples are files in the `prompts` folder of `runvil-harness`, the repository of the Engine and the Harness: small examples and `research-person.md`, which researches a person on the web. The built-in chat prompt is `chat.md`, the chat agent, which Workshop compiles into its binary and launches when an agent panel opens. Its `## Conversation` section is a loop: it reads the operator's next message, runs model rounds and tool calls until the model answers, and summarizes older turns when a turn overflows the model's context window. Section 1 describes the samples, and sections 2 and 3 describe the chat prompt. -A check of this page against the code found two gaps and left four questions about reasons for the owner. Section 5 lists the gaps, and section 6 lists the questions. In the larger gap, the prose of `chat.md` describes a system message about a mounted language guide, while the Lua line that adds that message is a comment and the mount is switched off. +Section 5 lists the gaps between this page and the code, and section 6 lists the questions about reasons for the owner. In the largest gap, the prose of `chat.md` describes a system message about a mounted language guide, while the Lua line that adds that message is a comment and the mount is switched off. Section 4 lists the planned work. Its largest item is a Pack ([Tools and Packs](tools-and-packs.md)) that turns a folder of prompts into tools. @@ -19,13 +15,13 @@ Section 4 lists the planned work. Its largest item is a Pack ([Tools and Packs]( The built-in chat prompt is the file `crates/workshop/agents/agents/chat.md`. The `workshop-agents` crate compiles the file's text into Workshop as the constant `BUILTIN_CHAT_SOURCE`, and `discover_agents` lists the `.md` files of the agents folder plus the name `chat`. -When an agent panel opens, the UI launches `chat`. The server opens a `Conversation` and builds a `RunSetup` with `has_user` set to true. `Conversation::run` calls `Host::parse`, which reads the text through `load_agent` and checks the four Packs under `uses:`. `Conversation::run` then creates a `Harness` and calls its `run` method ([The Harness and the Host API](harness-and-host.md)). +When an agent panel opens, the UI launches `chat`. The server opens a `Conversation` and builds a `RunSetup` with `has_user` set to true. `Conversation::run` calls `Host::parse`, which reads the text through `load_agent` and checks the Packs under `uses:`. `Conversation::run` then creates a `Harness` and calls its `run` method ([The Harness and the Host API](harness-and-host.md)). -The run enters the prompt's one section, `## Conversation`. Its Lua block offers tools, defines the function `compact`, and waits in `tasks.receive()`. When the operator sends a message, `Conversation::send_input` calls `RunControl::send`, and `tasks.receive()` returns the text. The block appends the text with `messages:user`, and `models.loop` runs model rounds and tool calls until the model answers in text. The block then waits again. `Conversation::close` cancels the run. +The run enters the prompt's `## Conversation` section. Its Lua block offers tools, defines the function `compact`, and waits in `tasks.receive()`. When the operator sends a message, `Conversation::send_input` calls `RunControl::send`, and `tasks.receive()` returns the text. The block appends the text with `messages:user`, and `models.loop` runs model rounds and tool calls until the model answers in text. The block then waits again. `Conversation::close` cancels the run. ## 1. The sample prompts -### Five sample prompts ship under `prompts`, and a test parses each one +### The sample prompts ship under `prompts`, and a test parses each one The samples are `hello.md`, `echo.md`, `greet.md`, `analyst-example.md`, and `research-person.md`, and the language guide's first chapter says what each one shows. @@ -45,9 +41,9 @@ The round limit is in the front matter because the budget belongs with the promp The chat gate tests in `workshop-server` launch the embedded text, and the Engine test file `models_loop-author-shapes.rs` contains a copy of the prompt's `compact` function (section 3). A change to one copy requires the same change to the other, and the two copies are in two repositories: the prompt in `runvil-workshop`, and the test in `runvil-harness`. [Workshop: how the app is built](workshop-app.md) covers discovery and launch. -### The chat prompt offers `std`, `bash`, `web`, and the extras in its one section +### The chat prompt offers `std`, `bash`, `web`, and the extras in its `## Conversation` section -The front matter declares `user`, `std`, `bash`, and `web`. The Lua block in `## Conversation` offers `std`, then `bash`, then `web`, then `tools.packs.extras()`, the run's Packs that the prompt leaves undeclared. In Workshop those are `mcp` and `subagents`. The tool list of `subagents` is empty, so the fourth offer adds the two tools of the `mcp` Pack to the chat model's tool list. The offers of `std` and `bash` include four tools that change the files of the run: `Write`, `StrReplace`, and `Delete` of `std`, and `Shell` of `bash`. In Workshop those files are in memory and end with the run. `std` and `bash` come from the two library Plugins in Workshop's Plugin directory, and `Host::parse` refuses the chat prompt when the directory lacks either one ([Workshop: how the app is built](workshop-app.md)). +The front matter declares `user`, `std`, `bash`, and `web`. The Lua block in `## Conversation` offers `std`, then `bash`, then `web`, then `tools.packs.extras()`, the run's Packs that the prompt leaves undeclared. In Workshop those are `mcp` and `subagents`. The tool list of `subagents` is empty, so the fourth offer adds the tools of the `mcp` Pack to the chat model's tool list. The offers of `std` and `bash` include the tools that change the files of the run: `Write`, `StrReplace`, and `Delete` of `std`, and `Shell` of `bash`. In Workshop those files are in memory and end with the run. `std`, `bash`, and `web` come from the library Plugins in Workshop's Plugin directory, and `Host::parse` refuses the chat prompt when the directory lacks any of them ([Workshop: how the app is built](workshop-app.md)). The model loop runs in that section, so the block makes the offers there: an offer in the preamble, the Lua before a prompt's first heading, would leave the loop's tool list unchanged. The fourth offer exists so that the tools of a new Pack among the extras appear in the chat model's tool list without a change to the prompt. @@ -82,7 +78,7 @@ Each of these items is still to be built. ## 5. Known gaps -The prose of `chat.md` differs from the code in two places. +The prose of `chat.md` differs from the code in these places. 1. The system message. The paragraph before the prompt's first heading, commentary that the run ignores, says the agent's "one system message says where the Runvil prompting language documentation is mounted". The line that adds the message is a Lua comment, and `ENABLED` in `language_guide.rs`, the switch that mounts the guide in each run, is `false`. The mount's `SOURCE` is a folder on one developer's machine. 2. The model switch. The same paragraph says "a selection change takes effect on the next run". `WorkshopBroker::routed` in `broker.rs` sends each round to the model that the menu names, and the gate test `gate_a_model_picked_between_turns_serves_the_next_round` checks it. @@ -93,7 +89,7 @@ Each question asks for the reason behind a part of the design. **The sample prompts** -1. Why does Runvil ship `research-person.md`, and what are the four small samples for? +1. Why does Runvil ship `research-person.md`, and what are the small samples for? **The chat prompt** @@ -103,12 +99,7 @@ Each question asks for the reason behind a part of the design. ## 7. Method and limits -- **Code.** The page describes `runvil` at commit `fa9936f64` and `runvil-docs` at commit `cfd69a4`. -- **Checks.** The facts on this page were read in the code at those commits. A second session checked the gaps, the values, and the walk-through against the code. +- **Checks.** The facts on this page were read in the code. A second session checked the gaps, the values, and the walk-through against the code. - **Limits.** The sessions read the code and its tests, and left the build and the tests unrun. -- **Update.** On 2026-11-12 the Paths bullet and the text on where the sample prompts are were brought to `runvil` at commit `48a4dbc08` and `runvil-harness` at `5bca6f9`. Commit `adca9db10` of `runvil` removed the `prompts` folder and the Engine, Harness, and Plugin crates, which are in `runvil-harness` with their history and at the same paths. The update covers one sentence each in the summary, the entry on the five samples, the entry on the embedded chat prompt, and the first planned item. The rest of the page still describes the commits above. At `runvil` commit `5bc561c14`, the chat prompt also requires and offers the `bash` Pack, and the text on the chat prompt's Packs is still to be brought to that commit. -- **Preamble.** On 2026-11-13 the sentence on where the chat prompt makes its offers, in the entry on the chat prompt's Packs, was brought to the second change that follows `8de43c2f` in `runvil-harness`, whose plan is `plan/2026-11-13-2-every-heading-is-a-section.plan.md` there. Before it, a prompt had exactly one H1 as its title, and the Lua blocks under it ran once before the first section. The five sample prompts have no title line at that change, and the text on them names no title, so it is unchanged. Gap 1 of section 5 named the paragraph under the title of `chat.md`. It names the paragraph before the file's first heading, because Workshop pins that change at `7147e709` and the file has no title line. That session ran the build and its tests. -- **Update.** On 2026-11-13 the text on the chat prompt's Packs was brought to `runvil-workshop` at commit `f386801b` and `runvil-harness` at `18361d02`. The chat prompt is in the `runvil-workshop` repository, and it declares and offers the `bash` Pack beside `std` and `web`. The update covers one sentence of the walk-through, the entry on the chat prompt's Packs and one sentence of the entry on the embedded prompt in section 2, and the Paths bullet. It settles the last sentence of the Update note of 2026-11-12. That session read the code and left the build and the tests unrun. The rest of the page still describes the commits above. -- **Update.** On 2026-11-19 the text on the chat prompt's Packs was brought to `runvil-workshop` at commit `956e7800`, which pins `runvil-harness` at `4afed45f`, `runvil-plugin-std` at `a806bf6`, and `runvil-plugin-bashkit` at `f348f7a`. The chat prompt is the same file as at `f386801b`. At the pinned commits the `std` tools Write, StrReplace, and Delete work, and the shell of `bash` changes files. The update adds two sentences to the entry on the chat prompt's Packs: the offers of `std` and `bash` include four tools that change the files of the run, and in Workshop those files are in memory. The other sentences of that text were checked against the same commits and are unchanged. The update covers that entry and the third Update bullet at the top of the page. That session read the code and left the build and the tests unrun. The rest of the page still describes the commits above. *2026-11-10 16:41 - Claude Fable 5.2* diff --git a/decisions/speech.md b/decisions/speech.md index d21fe2e..1d2c912 100644 --- a/decisions/speech.md +++ b/decisions/speech.md @@ -1,14 +1,13 @@ # Speech: design decisions and their reasons - Scope: speech to text and speech synthesis in the Gateway, and dictation in Workshop -- Code: `runvil-gateway` at commit `9369a7d`, `runvil` at commit `fa9936f64`, and `runvil-docs` at commit `cfd69a4` -- Paths: Gateway code paths start at `crates/gateway/` in `runvil-gateway`, and Workshop code paths at `crates/workshop/` in `runvil` +- Paths: Gateway code paths start at `crates/gateway/` in `runvil-gateway`, and Workshop code paths at `crates/workshop/` in `runvil-workshop` ## Summary -The Gateway turns speech into text with whisper.cpp. A realtime client streams audio over the WebSocket `/v1/realtime` and receives text while the person speaks, and a batch client uploads a file to `POST /v1/audio/transcriptions`. Two Whisper models share each recording: a fast one decodes every half second and shows its words, and an accurate one decodes each finished segment and replaces them. A third model, Silero, decides which audio is speech. `POST /v1/audio/speech` forwards a synthesis request to a remote provider and relays the audio. Workshop's voice feature is dictation: its server relays microphone audio to the Gateway, and the text appears in the chat box. Sections 1 to 8 describe these parts. +The Gateway turns speech into text with whisper.cpp. A realtime client streams audio over the WebSocket `/v1/realtime` and receives text while the person speaks, and a batch client uploads a file to `POST /v1/audio/transcriptions`. In a realtime session, Whisper models share each recording: a fast one decodes every half second and shows its words, and an accurate one decodes each finished segment and replaces them. Another model, Silero, decides which audio is speech. `POST /v1/audio/speech` forwards a synthesis request to a remote provider and relays the audio. Workshop's voice feature is dictation: its server relays microphone audio to the Gateway, and the text appears in the chat box. Sections 1 to 8 describe these parts. -A check of this page against the code found seven gaps and left six questions about reasons for the owner. Section 10 lists the gaps, and section 11 lists the questions. All seven gaps are in guide chapter 05, and the largest is speech detection: the chapter describes a loudness threshold, and the code classifies every frame with Silero. +Section 10 lists the gaps between this page and the code, and section 11 lists the questions about reasons for the owner. Every gap is in guide chapter 05, and the largest is speech detection: the chapter describes a loudness threshold, and the code classifies every frame with Silero. Section 9 lists the planned work. Its largest item is a local engine for speech synthesis: a remote provider produces all audio, and the Gateway refuses a local model of the speech kind. @@ -30,7 +29,7 @@ The Gateway loads the speech models, decodes audio, and answers both transcripti The Gateway loads the models because it budgets VRAM (section 2). A model that Workshop loaded itself would allocate VRAM that the Gateway is unaware of. -### Four crates under `stt/` depend on each other in one direction +### The crates under `stt/` depend on each other in one direction `gateway-stt`, in the folder `api/`, has the routes, the sessions, and the state of each recording. `gateway-stt-engine` defines the decoder and detector traits and runs the worker threads. `gateway-stt-backend-whisper` implements the traits with Whisper and Silero. `gateway-whisper-ffi` loads the whisper.cpp library and contains the subsystem's unsafe code. `api` depends on `engine` and `backend-whisper`, and `backend-whisper` depends on `engine` and `whisper-ffi`. @@ -64,21 +63,21 @@ The owner's goal: "Low latency is important but it is more important to get the The Gateway binds its listener first. Its queued boot command then calls `SpeechService::load_initial` once, which downloads the models and starts the workers. Each decoder runs one warm-up decode at load and discards the result. Until the load finishes, `/v1/realtime` answers 503. When it fails, speech is unavailable until a restart, and the Gateway continues to answer its other routes. A later profile switch saves the new speech selection, and the next start loads it. -A switch leaves the running engine in place. Its replacement at run time would add five mechanisms to the transcription path: publication of the new engine, quiescence of the running one, rollback, reconstruction, and cancellation. +A switch leaves the running engine in place. Its replacement at run time would add these mechanisms to the transcription path: publication of the new engine, quiescence of the running one, rollback, reconstruction, and cancellation. ### Every speech load downloads and opens the pinned Silero model `SILERO_VAD_MODEL` in the config crate names the Silero model's URL, digest, size, and license. The speech load downloads the file, checks the digest, and opens one detector as a test. The model is a constant in code, outside `[[stt_model]]`, because `SttRole` has only the roles `interim` and `final`. -The speech load fails when any of the three steps fails, because a fallback to loudness detection would be worse in two ways. In a test on noise clips, dictation with loudness detection invented 84 lines of text, and dictation with Silero invented zero. A fallback would also degrade speech silently, and silent degradation can hide a bug. +The speech load fails when any of these steps fails, because a fallback to loudness detection would be worse in two ways. In a test on noise clips, dictation with loudness detection invented 84 lines of text, and dictation with Silero invented zero. A fallback would also degrade speech silently, and silent degradation can hide a bug. ## 3. The realtime route ### Live transcription uses a strict subset of OpenAI's Realtime protocol -The route is the WebSocket `/v1/realtime?intent=transcription`. A client sends four JSON events: `session.update`, `input_audio_buffer.append`, `input_audio_buffer.commit`, and `input_audio_buffer.clear`. Audio is Base64 text of mono 16-bit PCM at 24 kHz, and the Gateway converts it once to 16 kHz. The converter, `Resampler24To16`, is a low-pass polyphase filter, and the audio runs 1 ms behind its timeline. The Gateway answers an unknown field or an option outside the subset, such as a language or turn detection, with an `error` event whose code names the fault. +The route is the WebSocket `/v1/realtime?intent=transcription`. A client sends these JSON events: `session.update`, `input_audio_buffer.append`, `input_audio_buffer.commit`, and `input_audio_buffer.clear`. Audio is Base64 text of mono 16-bit PCM at 24 kHz, and the Gateway converts it once to 16 kHz. The converter, `Resampler24To16`, is a low-pass polyphase filter, and the audio runs 1 ms behind its timeline. The Gateway answers an unknown field or an option outside the subset, such as a language or turn detection, with an `error` event whose code names the fault. -The subset exists for standard clients of OpenAI's protocol. One optional extension, the hypothesis snapshot, exists for Runvil's live transcript in three parts (section 5). +The subset exists for standard clients of OpenAI's protocol. An optional extension, the hypothesis snapshot, exists for Runvil's live transcript, which has finalized, agreed, and tentative parts (section 5). ### A commit ends the turn, and the Gateway finalizes the item in the background @@ -90,7 +89,7 @@ The buffer copies the prompt so that a prompt change leaves the open buffer and A client that puts `item.input_audio_transcription.hypothesis` in the `include` list of `session.update` receives `conversation.item.input_audio_transcription.hypothesis` events. Each one replaces the last: it has a `revision` number, the whole `transcript`, and its `finalized`, `agreed`, and `tentative` parts. A client with an empty list receives standard `conversation.item.input_audio_transcription.delta` events, built from the finalized text plus the agreed text less its last two words. -The extension's two names are part of version one of the public wire format, and canonical fixtures pin them. The two-word margin exists because agreed text only grows, so append-only deltas are safe except near its end, where a rewrite by the final pass can still change words. +The extension's names are part of version one of the public wire format, and canonical fixtures pin them. The two-word margin exists because agreed text only grows, so append-only deltas are safe except near its end, where a rewrite by the final pass can still change words. ### Realtime clients name `realtime-transcribe`, and batch clients name a configured model @@ -178,7 +177,7 @@ The prompt has the form of a glossary because, in measurements, that form outper ### `[stt] whisper_backend` selects the CPU or the CUDA build of whisper.cpp -The setting has three values: `auto`, the default, `cpu`, and `cuda`. The Gateway reads it once, at speech load, on Windows x86-64 and Linux x86-64, the two platforms with both builds. Under every setting the Gateway checks the CPU before it downloads a build, and an x86-64 CPU that lacks one of the builds' six instruction-set extensions fails the speech load with `LocalError::UnsupportedCpu`. +The setting has the values `auto`, the default, `cpu`, and `cuda`. The Gateway reads it once, at speech load, on Windows x86-64 and Linux x86-64, the two platforms with both builds. Under every setting the Gateway checks the CPU before it downloads a build, and an x86-64 CPU that lacks an instruction-set extension that a build needs fails the speech load with `LocalError::UnsupportedCpu`. The CUDA build exists for speed: on Linux, a final pass takes 2.14 s with the CPU build and 0.13 s with the same sources built for CUDA. The CPU build exists because a Windows machine that lacks an NVIDIA driver fails to load the CUDA build. @@ -227,7 +226,7 @@ OpenAI's API lacks a voice list. The route exists because off-the-shelf clients ### The Gateway relays the provider's audio bytes unread, and a failed stream fails the client's read -The Gateway sends the provider's audio to the client in chunks. A spawned task owns the provider's body and the queue permit, and four constants bound it: 60 minutes in total, 1 GiB, 30 seconds of provider silence, and 60 seconds of a client that stops reading. When the stream exceeds a bound or the provider fails after the 200 status, the task ends the body with an error, so the client's read fails. +The Gateway sends the provider's audio to the client in chunks. A spawned task owns the provider's body and the queue permit, and these constants bound it: 60 minutes in total, 1 GiB, 30 seconds of provider silence, and 60 seconds of a client that stops reading. When the stream exceeds a bound or the provider fails after the 200 status, the task ends the body with an error, so the client's read fails. The task ends the body with an error because a normal end would look like a complete response. The Gateway is unable to validate audio chunk by chunk, and a JSON error is impossible after the 200 status and the first audio bytes. The limit on provider silence exists so that a dead provider releases the queue permit. @@ -249,7 +248,7 @@ The capture service decides because there is one microphone, and the capture ser `setupStt` connects dictation to one text input and returns an `SttHandle`. `press()` starts a take when idle and stops it when recording, and `state` is `idle`, `recording`, or `blocked`. The agent view copies the state to the chat box and forwards the box's `mic-press` event to `press()`. The button is pressable in every state, and the handle writes the reason for a refused press on the status bar. -The chat box draws the button because the button is part of the chat box, whose contract is events out and props in. [Workshop: what the user sees](workshop-ui.md) covers the button's three roles. +The chat box draws the button because the button is part of the chat box, whose contract is events out and props in. [Workshop: what the user sees](workshop-ui.md) covers the button's roles. ### Dictation inserts at the cursor like typing, and the chat box is read-only during a take @@ -279,13 +278,13 @@ The registry patches only the changed words because a rewrite of the whole take Each of these items is still to be built. -- **A local synthesis engine.** An engine that runs an Orpheus model on the machine. Two candidates await a trial: the prebuilt speech server CrispASR as a child process, and the existing llama-server child with a SNAC audio decoder inside the Gateway. The trial transcribes the audio or compares it with a reference recording, because a wrong decode fails silently, as silent audio. Output encoders, a priority lane for speech in the dominion queue, and sampling defaults wait for the engine. A remote provider produces all audio, and the Gateway refuses a `[[local_model]]` of the speech kind (section 7). +- **A local synthesis engine.** An engine that runs an Orpheus model on the machine. Candidates await a trial: the prebuilt speech server CrispASR as a child process, and the existing llama-server child with a SNAC audio decoder inside the Gateway. The trial transcribes the audio or compares it with a reference recording, because a wrong decode fails silently, as silent audio. Output encoders, a priority lane for speech in the dominion queue, and sampling defaults wait for the engine. A remote provider produces all audio, and the Gateway refuses a `[[local_model]]` of the speech kind (section 7). - **Streaming from Together.** A decoder for the server-sent events in which Together streams speech under its `raw` format. The Gateway's closed format set refuses `raw`. - **Playback in Workshop.** A player for synthesized speech: an `AudioWorklet` that reads a streamed `pcm` response and buffers 400 to 600 ms before it plays. Workshop has yet to call the synthesis route. - **Interim windows that start at the last agreed word.** An interim window starts at the open segment (section 4). `DecodeOutput` has the word end times, and `next_window_snapshot` ignores them. - **A Windows CUDA archive with OpenMP off.** An archive that ends the crash of the Gateway at a graceful stop under an explicit `cuda`. It waits for the next whisper.cpp tag, and the workflow builds only the Windows CPU archive with OpenMP off. - **Decoder experiments.** A streaming interim model, AlignAtt, a rewind guard, look-ahead punctuation at segment joins, and stutter suppression. Both passes decode with whisper.cpp under the profiles of section 5. -- **A fix for two panics.** `process_closed` panics at two calls when the audio of a queued range has left the buffer. +- **A fix for panics.** `process_closed` panics at the calls that read or compact a queued range when its audio has left the buffer. - **Gateway-ended sessions in Workshop.** A change of Workshop's reaction to a session that the Gateway ends. Workshop rolls back the take that is recording, and for a dropped socket it writes the finalized and agreed text (section 8). - **Tests on real Silero.** A run of the native replay test and the long-speech test with the Silero model. Both tests detect speech by loudness. [Testing and debugging](testing-and-debugging.md) covers the replay test. @@ -319,8 +318,7 @@ Each question asks for the reason behind a part of the design. ## 12. Method and limits -- **Code.** The page describes `runvil-gateway` at commit `9369a7d`, `runvil` at commit `fa9936f64`, and `runvil-docs` at commit `cfd69a4`. -- **Checks.** The facts on this page were read in the code at those commits. A second session checked the gaps, the values, and the walk-through against the code. +- **Checks.** The facts on this page were read in the code. A second session checked the gaps, the values, and the walk-through against the code. - **Limits.** The sessions read the code and its tests, and left the build and the tests unrun. *2026-11-10 16:39 - Claude Fable 5.2* diff --git a/decisions/tasks-and-fanout.md b/decisions/tasks-and-fanout.md index 37019e0..73b030c 100644 --- a/decisions/tasks-and-fanout.md +++ b/decisions/tasks-and-fanout.md @@ -1,23 +1,19 @@ # Tasks and fanout: design decisions and their reasons - Scope: concurrent work inside a run: tasks, fanout, the scheduler's order, limits, determinism, and a task's inbox -- Code: `runvil` at commit `fa9936f64`, and `runvil-docs` at commit `cfd69a4` -- Update: the Paths bullet names the repositories as of `runvil` at commit `48a4dbc08` and `runvil-harness` at `5bca6f9`, after the Engine and the Harness moved (section 10) -- Update: the entries on task ownership in section 2, on ids in section 5, and on inboxes in section 6 state the rules of the second change that follows `8de43c2f` in `runvil-harness`: every heading starts a section, and the code before the first heading is the preamble (section 10) -- Update: the text on the inputs of a replay, on conflicts in a store and on the Host's files, on the calls of one model reply that change files, and on the value 8 of three limits describes `runvil-harness` at commit `ee199e3a` (section 10) -- Paths: code paths start at the `crates/` folder of `runvil-harness`, the repository of the Engine and the Harness, and a path that begins with `workshop/` starts at the `crates/` folder of `runvil` +- Paths: code paths start at the `crates/` folder of `runvil-harness`, the repository of the Engine and the Harness ## Summary A chain is one walk through a prompt's sections. A run has a chain for the main walk, one for each `call`, one for each `execute`, and one for each task, and a task is a chain that runs beside the chain that spawned it. The Engine's scheduler runs the chains in turns on one thread. `tasks.spawn` starts a task, `tasks.join_any` waits for one, and `tasks.fanout` is a Lua function that spawns one task for each member of a table. Sections 1 to 6 describe this design. -A check of this page against the code found one gap and left four questions about reasons for the owner. Section 8 describes the gap, and section 9 lists the questions. The gap is a doc comment in `ids.rs`, which calls the depth of a run unbounded, while the code caps it at 8. +Section 8 lists the gaps between this page and the code, and section 9 lists the questions about reasons for the owner. A gap is a doc comment in `ids.rs`, which calls the depth of a run unbounded, while the code caps it at 8. Section 7 lists the planned work. Its largest item is replay: the Harness driver that runs a recorded run again from its seed, start time, answers, messages, and file requests is still to be built. ## From a `tasks.fanout` call to its results -A section's Lua calls `tasks.fanout('### Worker', items)`, a Lua function in `__impl_fanout.lua` that the code's comments call the `fanout` shim. The shim calls `collection_members` to list the members of `items`, copies the caller's `var`, and yields one `spawn` request for each member. +A section's Lua calls `tasks.fanout('Worker', items)`, a Lua function in `__impl_fanout.lua` that the code's comments call the `fanout` shim. The shim calls `collection_members` to list the members of `items`, copies the caller's `var`, and yields one `spawn` request for each member. For each request, the scheduler's `dispatch_spawn` checks the depth cap, forks a file identity from the caller's (section 5), and assigns the next child id, such as `0.0`. It adds a `TaskEntry` to the `TaskArena`, queues the new chain in `Admission`, and resumes the shim. @@ -43,7 +39,7 @@ They are methods of `Scheduler` because the owners depend on each other through ### `tasks.spawn` starts a chain over a section and returns a handle at once -`tasks.spawn(target, opts)` queues a new chain that starts at the target section, and returns before that chain runs. `opts.args` gives the chain its own arguments, a table of named fields or a string, by the rule of the second argument of `call` ([The prompt language](prompt-language.md)), and a chain that gets none reads its spawner's `args`. `opts` takes the keys `args`, `item`, and `index`, and any other key raises an error that names it, so a misspelled option fails at the call. The handle is a plain table, `{ task = id }`, and every `tasks` function that names a task takes the handle or the id string. The `tasks` table has thirteen functions: `spawn`, `join_any`, `join`, `ready`, `status`, `pending`, `note`, `cancel`, `concurrency`, `receive`, `send`, `reply`, and `fanout`. +`tasks.spawn(target, opts)` queues a new chain that starts at the target section, and returns before that chain runs. `opts.args` gives the chain its own arguments, a table of named fields or a string, by the rule of the second argument of `call` ([The prompt language](prompt-language.md)), and a chain that gets none reads its spawner's `args`. `opts` takes the keys `args`, `item`, and `index`, and any other key raises an error that names it, so a misspelled option fails at the call. The handle is a plain table, `{ task = id }`, and every `tasks` function that names a task takes the handle or the id string. The `tasks` table has these functions: `spawn`, `join_any`, `join`, `ready`, `status`, `pending`, `note`, `cancel`, `concurrency`, `receive`, `send`, `reply`, and `fanout`. ### The chain that spawns a task owns it @@ -77,9 +73,9 @@ When a run ends as a whole, by a cancel or a fatal answer, `Scheduler::end` firs ### The collection is a Lua table, and the shim lists its members in a fixed order -`collection_members` lists the array part in index order and then the keyed part sorted by key. It reads a view through to its data, so a list from `args` or from `var` is a collection like any table. A keyed member becomes a pair table that the arm reads as `item.key` and `item.value`. Any other value in place of the table raises an error that points to `prompt.list(heading)`. +`collection_members` lists the array part in index order and then the keyed part sorted by key. It reads a view through to its data, so a list from `args` or from `var` is a collection like any table. A keyed member becomes a pair table that the arm reads as `item.key` and `item.value`. Any other value in place of the table raises an error that points to `prompt.section(path, "list").items`. -A heading in place of the table is one of the refused values. `prompt.list(heading)` returns the items of a list section, so a heading as the argument would be a second way to do one thing, and a bare string is ambiguous against a section name. The sort of the keyed part makes every process spawn the arms in the same order. +A section path in place of the table is one of the refused values. `prompt.section(path, "list").items` returns the items of a list, so a path as the argument would be a second way to do one thing, and a bare string is ambiguous against a section name. The sort of the keyed part makes every process spawn the arms in the same order. ### Each arm is a task that runs the worker section with `item` and `sys.index` @@ -93,9 +89,9 @@ The shim yields a `spawn` request for every member before its first `join_any`. Under the join rule of section 5, an arm spawned after a join would be ordered after the arm that the join returned and could read that arm's store files, so its result would depend on timing. With every arm spawned before the first join, the arms are unordered among themselves. -### Results return in collection order as objects with four fields +### Results return in collection order as objects with named fields -`tasks.fanout` returns an array with one result at each member's position. `text` is the arm's final text, `ok` says whether the arm completed, `item` is the member, and `exhausted` says whether the arm ran out of model rounds. Each result is a read-only view: `pairs` walks its four fields as it walks a plain table, and an assignment to a result raises an error that reads "tasks.fanout results are read-only". +`tasks.fanout` returns an array with one result at each member's position. `text` is the arm's final text, `ok` says whether the arm completed, `item` is the member, and `exhausted` says whether the arm ran out of model rounds. Each result is a read-only view: `pairs` walks its fields as it walks a plain table, and an assignment to a result raises an error that reads "tasks.fanout results are read-only". The caller combines the results itself. `item` lets the caller match each result with its member when the member is a rich value, such as a record. @@ -149,7 +145,7 @@ The cap is 8 because that is more depth than the owner expects a prompt to need ### The same seed, start time, and answers produce the same run -For each run the Harness generates a random seed, reads the clock, and passes both to the Engine in `RunParams`. With the same two values, and the same answers, messages, and file requests delivered in the same order at the same steps, and with no cancel, the Engine emits the same effects, events, and ids. The order of answers is an input. So is the order of the file requests that the Harness reports for open tool calls with `Run::request_file`, each of which the Engine issues as an effect at its next step ([The Engine](engine.md)). So is each message that a Host sends the run, with its place among the answers and the steps ([The Harness and the Host API](harness-and-host.md)). Among waiting tool calls, the Harness starts the one with the lowest effect id ([Tools and Packs](tools-and-packs.md)), and `Run` lacks a call that reports a start. That choice therefore affects the Engine only through the order of answers and of file requests, so a replay (section 7) that repeats the answers, the messages, and the file requests in their order and at their steps is independent of the Harness's start order. Three results depend on the order of answers: which task `tasks.join_any` returns, whether a timed wait runs out, and how far a canceled task got. The guide adds a fourth: where a `tasks.send` message applies in a task's work. +For each run the Harness generates a random seed, reads the clock, and passes both to the Engine in `RunParams`. With the same two values, and the same answers, messages, and file requests delivered in the same order at the same steps, and with no cancel, the Engine emits the same effects, events, and ids. The order of answers is an input. So is the order of the file requests that the Harness reports for open tool calls with `Run::request_file`, each of which the Engine issues as an effect at its next step ([The Engine](engine.md)). So is each message that a Host sends the run, with its place among the answers and the steps ([The Harness and the Host API](harness-and-host.md)). Among waiting tool calls, the Harness starts the one with the lowest effect id ([Tools and Packs](tools-and-packs.md)), and `Run` lacks a call that reports a start. That choice therefore affects the Engine only through the order of answers and of file requests, so a replay (section 7) that repeats the answers, the messages, and the file requests in their order and at their steps is independent of the Harness's start order. These results depend on the order of answers: which task `tasks.join_any` returns, whether a timed wait runs out, and how far a canceled task got. The guide adds another: where a `tasks.send` message applies in a task's work. Because of this rule, replay is a job for the Harness: the Engine is deterministic, so the Harness can match a recorded run exactly. The rule covers Lua's table walks too. The Engine's `pairs` and `next` walk a table in sorted order, where the order of stock Lua's walk depends on a hash seed. @@ -213,7 +209,7 @@ Each question asks for the reason behind a part of the design. **Fanout** 1. Why does the first failing arm cancel the others? -2. Why does a result have these four fields, and why is `exhausted` separate from `ok`? +2. Why does a result have these fields, and why is `exhausted` separate from `ok`? **Tasks** @@ -222,11 +218,7 @@ Each question asks for the reason behind a part of the design. ## 10. Method and limits -- **Code.** The page describes `runvil` at commit `fa9936f64` and `runvil-docs` at commit `cfd69a4`. -- **Checks.** The facts on this page were read in the code at those commits. A second session checked the gaps, the values, and the walk-through against the code. +- **Checks.** The facts on this page were read in the code. A second session checked the gaps, the values, and the walk-through against the code. - **Limits.** The sessions read the code and its tests, and left the build and the tests unrun. -- **Move.** On 2026-11-12 the Paths bullet was brought to `runvil` at commit `48a4dbc08` and `runvil-harness` at `5bca6f9`. Commit `adca9db10` of `runvil` removed the Engine, Harness, and Plugin crates, which are in `runvil-harness` with their history and at the same paths under `crates/`. The text of the page still describes the code at the commits above, when those crates were in `runvil`. -- **Every heading is a section.** On 2026-11-13 the entries on task ownership in section 2, on ids in section 5, and on inboxes in section 6 were brought to the second change that follows `8de43c2f` in `runvil-harness`, whose plan is `plan/2026-11-13-2-every-heading-is-a-section.plan.md` there. Before it, the Lua blocks under a prompt's one H1 ran once in a chain of their own, the H1 pass, which handed its tasks to the main walk and shared the main chain's inbox with it. The pass had entry `0.0`, so the first section of the main walk read `0.1`. That session ran the build and its tests. -- **Update.** On 2026-11-19 the text on determinism and on file access was brought to `runvil-harness` at commit `ee199e3a`. At that commit a tool asks its caller for each file operation, the Harness reports the request to the run with `Run::request_file`, and the conflict check applies in a store only. The update covers two sentences of the summary, the entry on spawning every arm in section 3, the entries on the limit of 8, on admission, and on the depth cap in section 4, the entries on the same run and on fork and join in section 5, the entry on idle tasks in section 6, the item on replay in section 7, and the third Update bullet at the top of the page. It states that a Host's messages and the file requests of tool calls are inputs of a replay beside the answers, that the same inputs give the same run when no cancel is raised, that a store checks conflicts and the Host's files have no such check, and that the calls of one model reply that change files run one at a time, in the order the model listed them. It adds the owner's reasons for the value 8 of `max_concurrency`, of `max_idle_tasks`, and of the depth cap, as the decision pages of `runvil-harness` give them, and it removes question 5 of section 9, which those reasons answer. That session read the code and left the build and the tests unrun. The update leaves the rest of the page as it was. *2026-11-10 16:38 - Claude Fable 5.2* diff --git a/decisions/testing-and-debugging.md b/decisions/testing-and-debugging.md index 74a90e3..ceb7704 100644 --- a/decisions/testing-and-debugging.md +++ b/decisions/testing-and-debugging.md @@ -1,28 +1,25 @@ # Testing and debugging: design decisions and their reasons - Scope: test harnesses and test support, fixtures, scripted models, the facade suites, the rules for test code, logs and traces, and dev tools -- Code: `runvil` at commit `fa9936f64`, `runvil-gateway` at `9369a7d`, and `runvil-docs` at `cfd69a4` -- Update: the Paths bullet names the repositories as of `runvil` at commit `48a4dbc08` and `runvil-harness` at `5bca6f9`, after the Engine and the Harness moved (section 10) -- Update: the entry on Plugin tests in section 4 describes `runvil-harness` at commit `ee199e3a`, `runvil-plugin-api` at `52a4905`, `runvil-plugin-std` at `a806bf6`, and `runvil-plugin-bashkit` at `f348f7a`, and the count of the Engine's internal crates in the summary and in section 1 describes `runvil-harness` at that commit (section 10) - Paths: code paths start at the `crates/` folder of `runvil-harness`, the repository of the Engine and the Harness, a path that begins with `workshop/` starts at the `crates/` folder of `runvil-workshop`, and a `tools/` path starts at the root of its repository ## Summary -A step of a run returns effects: requests for outside work, such as a model reply, that the caller performs ([The Engine](engine.md)). A test steps a run on its own thread and answers every effect itself, so the clock, the seed, and the model's replies are values the test supplies. Each of the Engine's seven internal crates has a `test_support` module. The one in `runvil-runtime` defines `Scenario`, a struct with one test's setup, and `ScriptedChat`, a scripted model that answers from a list of replies. The facades `runvil-engine` and `runvil`, two crates of re-exports, each have a suite written against public paths. For debugging, the Harness writes every effect, answer, and event of a run to the Host's recorder. Sections 1 to 6 describe these parts. +A step of a run returns effects: requests for outside work, such as a model reply, that the caller performs ([The Engine](engine.md)). A test steps a run on its own thread and answers every effect itself, so the clock, the seed, and the model's replies are values the test supplies. Each of the Engine's internal crates has a `test_support` module. The one in `runvil-runtime` defines `Scenario`, a struct with one test's setup, and `ScriptedChat`, a scripted model that answers from a list of replies. The facades `runvil-engine` and `runvil`, crates of re-exports, each have a suite written against public paths. For debugging, the Harness writes every effect, answer, and event of a run to the Host's recorder. Sections 1 to 6 describe these parts. -A check of this page against the code found three gaps and left five questions about reasons for the owner. Section 8 lists the gaps, and section 9 lists the questions. The largest gap is in the language guide: chapter 16 documents a Host debug mode that adds `Request` and `Response` events to a run, and the Harness leaves those events off in every run. +Section 8 lists the gaps between this page and the code, and section 9 lists the questions about reasons for the owner. The largest gap is in the language guide: chapter 16 documents a Host debug mode that adds `Request` and `Response` events to a run, and the Harness leaves those events off in every run. Section 7 lists the planned work. Its largest item is a replay driver, which steps a recorded run through the Engine again and compares the results. ## From a prompt to an assertion -The test `models_loop_repeats_model_tool_rounds_and_appends_each_exchange`, in `runvil-internal/runtime/src/execute/tests/models_loop.rs`, starts with two inputs. `one_section` writes a prompt with one section. The section's Lua offers `tools/echo`, adds a user message, calls `models.loop()`, and asserts on `messages`. `ScriptedChat::new` takes three replies: two calls to `echo`, built with `calls`, and one built with `text`. +The test `models_loop_repeats_model_tool_rounds_and_appends_each_exchange`, in `runvil-internal/runtime/src/execute/tests/models_loop.rs`, starts with a prompt and a list of scripted replies. `one_section` writes a prompt with one section. The section's Lua offers `tools/echo`, adds a user message, calls `models.loop()`, and asserts on `messages`. `ScriptedChat::new` takes the replies: calls to `echo`, built with `calls`, and a last reply built with `text`. `loop_scenario(source)` creates a `Scenario`. `offer("echo", echo_tool())` adds an `FnTool`, a tool whose call is a closure, to the run's tool catalog, and `chat(&gateway)` sets the scripted model. `run()` parses the source with `Prompt::parse`, builds `RunParams` from `TEST_SEED` and `TEST_STARTED_AT`, creates a `Run`, and steps it on the test's thread. The scenario answers each effect before the next step. It answers the `Render` effect with the offered tools unchanged, and the first `Chat` effect with the first reply, through `ScriptedChat::complete_now`, which also records the round's messages and tools. That reply calls `echo`, so the Engine issues a `ToolCall` effect, and the scenario calls the closure, which returns `echoed: one`. The second round repeats the pattern. The third reply is the text `both done`, which ends the loop, and the Lua returns `ok`. -The last step returns `Step::Done`, and `run()` returns a `Trace`. The test asserts that `trace.text()` is `ok`, reads the three recorded rounds from `gateway.requests()`, and asserts that the third round's messages contain both tool results. +The last step returns `Step::Done`, and `run()` returns a `Trace`. The test asserts that `trace.text()` is `ok`, reads the recorded rounds from `gateway.requests()`, and asserts that the third round's messages contain each tool result. ## 1. The Engine's test support @@ -46,11 +43,11 @@ A scripted model in the test process is enough, because the Engine leaves I/O to ### Each internal Engine crate has its own test support, under the same names -Each of the seven crates under `runvil-internal` has a `test_support` module. The names repeat: a source builder (`prompt` and `one_section`, in `runvil-prompt`), prepared answers (`text`, `calls`, `fail`, and `FnTool`), and a driver that returns a record. `runvil-lua` builds a section VM with `TestVm`, `runvil-vfs` has the backend `TestFs`, and `runvil-runtime` defines `Observer` and `DebugCapture`, callback traits for run reports and raw model bodies. +Each crate under `runvil-internal` has a `test_support` module. The names repeat: a source builder (`prompt` and `one_section`, in `runvil-prompt`), prepared answers (`text`, `calls`, `fail`, and `FnTool`), and a driver that returns a record. `runvil-lua` builds a section VM with `TestVm`, `runvil-vfs` has the backend `TestFs`, and `runvil-runtime` defines `Observer` and `DebugCapture`, callback traits for run reports and raw model bodies. The names follow the Engine facade's suite, so that tests read alike across the workspace. Each crate has its own module because one shared test crate would need a dependency of its own on each crate and would cross the `test-support` boundary, which the next entry describes. -### The `test-support` feature of `runvil-runtime` compiles the driver for one bench +### The `test-support` feature of `runvil-runtime` compiles the driver for a bench `runvil-runtime` declares the empty feature `test-support`, which compiles `drive` and `ScriptedChat` for `benches/models_loop.rs`. The feature exists because `#[cfg(test)]` code is invisible to a bench, and this bench needs the serial driver and `ScriptedChat`. `runvil-lua`, `runvil-prompt`, and `runvil-plugin` declare a feature of the same name for the tests of sibling crates. A structural check fails when a production dependency enables the feature (see [Crates, build, and CI](crates-build-and-ci.md)). @@ -82,7 +79,7 @@ A Harness test supplies the model through an `InferenceBroker` that the test cod ### Every clock value, seed, and answer in an Engine-crate test is a value the test supplies -Three `clippy.toml` files ban sleeps, clock reads, timed waits, and `RandomState::new` in `runvil-engine`, `runvil-plugin`, and the crates under `runvil-internal`, tests included (see [Crates, build, and CI](crates-build-and-ci.md)). The test runner, nextest, ends a hung test after three 60-second periods. +The `clippy.toml` files ban sleeps, clock reads, timed waits, and `RandomState::new` in `runvil-engine`, `runvil-plugin`, and the crates under `runvil-internal`, tests included (see [Crates, build, and CI](crates-build-and-ci.md)). The test runner, nextest, ends a hung test after three 60-second periods. The owner's rule: "my instinct tells me that no runvil test should ever sleep or be non-deterministic". The rule covers the Engine crates only, because some Gateway tests are timing-based by nature. The Engine's own determinism rules are on [The Engine](engine.md) and [Tasks and fanout](tasks-and-fanout.md). @@ -92,31 +89,31 @@ The owner's rule: "my instinct tells me that no runvil test should ever sleep or `TempRoot::new(label)` creates `/runvil-tests//